@wbline/pi-plan-build 0.0.0-stage → 0.0.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.
package/src/index.ts ADDED
@@ -0,0 +1,241 @@
1
+ /**
2
+ * pi-plan-build v2 入口:Plan/Build 双模式扩展。
3
+ *
4
+ * 设计原则:分层模块 + 集中状态机 + 原生 UI(setStatus/setWidget/custom),
5
+ * 不接管 composer/editor,与其它扩展零冲突。详见 README.md。
6
+ *
7
+ * 唯一命令:/plan-build —— 交互菜单(切换模式/状态/完成/放弃/语言/设置)
8
+ * 快捷键:Alt+M 切换模式
9
+ */
10
+
11
+ import fs from "node:fs";
12
+ import type {
13
+ ExtensionAPI,
14
+ ExtensionContext,
15
+ Theme,
16
+ } from "@earendil-works/pi-coding-agent";
17
+ import { Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
18
+ import { configPath, loadConfig, saveConfig } from "./config.ts";
19
+ import { type State, statusLine } from "./core/state.ts";
20
+ import { PlanEngine } from "./engine.ts";
21
+ import { wireLifecycle } from "./lifecycle.ts";
22
+ import { registerAllTools } from "./tools/index.ts";
23
+
24
+ export default function planBuild(pi: ExtensionAPI): void {
25
+ const loaded = loadConfig();
26
+ const engine = new PlanEngine(pi, loaded.config);
27
+
28
+ // --- 唯一命令:交互菜单 ---
29
+ pi.registerCommand("plan-build", {
30
+ description: "Plan/Build 菜单:切换模式、状态、完成、放弃、语言、设置",
31
+ handler: async (_args, ctx) => {
32
+ await openMenu(engine, ctx);
33
+ },
34
+ });
35
+
36
+ // --- 工具与生命周期 ---
37
+ registerAllTools(pi, engine);
38
+ wireLifecycle(pi, engine);
39
+
40
+ // --- 快捷键:Alt+M 切换模式(全局,不碰编辑器补全)---
41
+ pi.registerShortcut(Key.alt("m"), {
42
+ description: "切换 Plan/Build 模式",
43
+ handler: async (ctx) => {
44
+ const next = engine.state.mode === "plan" ? "build" : "plan";
45
+ const r = engine.tryApply({ t: "mode.set", mode: next }, ctx);
46
+ if ("error" in r) ctx.ui.notify(r.error, "error");
47
+ },
48
+ });
49
+
50
+ // --- 启动模式应用(在首个 session_start 时)---
51
+ pi.on("session_start", (event, ctx) => {
52
+ if (event.reason !== "startup") return;
53
+ const mode =
54
+ engine.state.mode === "plan" ? "plan" : loaded.config.defaultMode;
55
+ if (mode !== engine.state.mode) engine.apply({ t: "mode.set", mode }, ctx);
56
+ else engine.refreshUI(ctx);
57
+ });
58
+
59
+ if (loaded.warning) {
60
+ // factory 里只能注册,不能弹 UI;挂到首个 context 前的 session_start 提示。
61
+ pi.on("session_start", (_event, ctx) => {
62
+ if (loaded.warning) ctx.ui.notify(loaded.warning, "warning");
63
+ });
64
+ }
65
+ }
66
+
67
+ // ============ 菜单 ============
68
+
69
+ type MenuAction = "toggle" | "status" | "done" | "abandon" | "lang" | "config";
70
+
71
+ function buildMenuItems(s: State): { id: MenuAction; label: string }[] {
72
+ const items: { id: MenuAction; label: string }[] = [
73
+ {
74
+ id: "toggle",
75
+ label: `切换模式 → ${s.mode === "plan" ? "Build" : "Plan"}`,
76
+ },
77
+ { id: "status", label: "查看状态" },
78
+ ];
79
+ if (s.plan) {
80
+ items.push({ id: "done", label: "标记计划完成" });
81
+ items.push({ id: "abandon", label: "放弃计划…" });
82
+ }
83
+ items.push({ id: "lang", label: "提示词语言 → 中/EN 切换" });
84
+ items.push({ id: "config", label: "设置文件…" });
85
+ return items;
86
+ }
87
+
88
+ async function openMenu(
89
+ engine: PlanEngine,
90
+ ctx: ExtensionContext,
91
+ ): Promise<void> {
92
+ if (!ctx.hasUI) return; // print/json 模式:无交互面
93
+ if (ctx.mode === "tui") {
94
+ const action = await ctx.ui.custom<MenuAction | undefined>(
95
+ (_tui, theme, _kb, done) => new MenuComponent(theme, engine.state, done),
96
+ );
97
+ await runAction(engine, ctx, action);
98
+ return;
99
+ }
100
+ // RPC:原生 select 单次选择
101
+ const items = buildMenuItems(engine.state);
102
+ const choice = await ctx.ui.select(
103
+ "Plan/Build 菜单",
104
+ items.map((x) => x.label),
105
+ );
106
+ const selected = items.find((x) => x.label === choice);
107
+ if (selected) await runAction(engine, ctx, selected.id);
108
+ }
109
+
110
+ async function runAction(
111
+ engine: PlanEngine,
112
+ ctx: ExtensionContext,
113
+ action: MenuAction | undefined,
114
+ ): Promise<void> {
115
+ if (!action) return;
116
+ const s = engine.state;
117
+ switch (action) {
118
+ case "toggle": {
119
+ const next = s.mode === "plan" ? "build" : "plan";
120
+ const r = engine.tryApply({ t: "mode.set", mode: next }, ctx);
121
+ if ("error" in r) ctx.ui.notify(r.error, "error");
122
+ return;
123
+ }
124
+ case "status":
125
+ showPanel(ctx, statusBody(s));
126
+ return;
127
+ case "done": {
128
+ if (!s.plan) return;
129
+ const r = engine.tryApply({ t: "plan.complete" }, ctx);
130
+ if ("error" in r) ctx.ui.notify(r.error, "error");
131
+ else ctx.ui.notify("计划已标记完成。", "info");
132
+ return;
133
+ }
134
+ case "abandon": {
135
+ if (!s.plan) return;
136
+ const reason =
137
+ (await ctx.ui.input(
138
+ "放弃计划(文件保留)",
139
+ "放弃原因,如:方向变了",
140
+ )) ?? "";
141
+ if (!reason.trim()) return; // 取消/空原因:不动
142
+ const r = engine.tryApply(
143
+ { t: "plan.abandon", reason: reason.trim() },
144
+ ctx,
145
+ );
146
+ if ("error" in r) ctx.ui.notify(r.error, "error");
147
+ return;
148
+ }
149
+ case "lang": {
150
+ const lang = engine.config.lang === "zh" ? "en" : "zh";
151
+ engine.setConfig({ lang });
152
+ saveConfig({ lang });
153
+ ctx.ui.notify(
154
+ `提示词语言:${lang === "en" ? "English" : "中文"}`,
155
+ "info",
156
+ );
157
+ return;
158
+ }
159
+ case "config": {
160
+ const p = configPath();
161
+ const body = fs.existsSync(p) ? fs.readFileSync(p, "utf8") : "{}";
162
+ showPanel(ctx, `${p}\n\n${body}`);
163
+ return;
164
+ }
165
+ }
166
+ }
167
+
168
+ function statusBody(s: State): string {
169
+ const lines = [statusLine(s)];
170
+ if (s.plan) {
171
+ lines.push(`文件:${s.plan.path}${s.plan.saved ? "" : "(未写盘)"}`);
172
+ lines.push(`seq:${s.plan.seq} · 模式:${s.mode}`);
173
+ if (s.execution) {
174
+ lines.push(
175
+ ...s.execution.steps.map((x) => ` ${x.n}. [${x.status}] ${x.text}`),
176
+ );
177
+ }
178
+ } else {
179
+ lines.push("没有当前计划。Plan 模式下让 agent 规划,或直接讨论。");
180
+ }
181
+ return lines.join("\n");
182
+ }
183
+
184
+ /** TUI 菜单组件:↑↓ 选择、Enter 执行、Esc 关闭(执行后自动关闭)。 */
185
+ class MenuComponent {
186
+ private selected = 0;
187
+ constructor(
188
+ private readonly theme: Theme,
189
+ private readonly state: State,
190
+ private readonly done: (action: MenuAction | undefined) => void,
191
+ ) {}
192
+
193
+ handleInput(data: string): void {
194
+ const count = buildMenuItems(this.state).length;
195
+ if (matchesKey(data, "escape")) this.done(undefined);
196
+ else if (matchesKey(data, "up"))
197
+ this.selected = (this.selected - 1 + count) % count;
198
+ else if (matchesKey(data, "down"))
199
+ this.selected = (this.selected + 1) % count;
200
+ else if (matchesKey(data, "return"))
201
+ this.done(buildMenuItems(this.state)[this.selected]?.id);
202
+ }
203
+
204
+ render(width: number): string[] {
205
+ const th = this.theme;
206
+ const items = buildMenuItems(this.state);
207
+ const lines: string[] = ["", ` ${th.fg("accent", "Plan/Build")}`, ""];
208
+ items.forEach((item, i) => {
209
+ const row =
210
+ i === this.selected
211
+ ? `${th.fg("accent", "❯ ")}${th.fg("accent", item.label)}`
212
+ : ` ${item.label}`;
213
+ lines.push(truncateToWidth(` ${row}`, width));
214
+ });
215
+ lines.push("", ` ${th.fg("dim", "↑↓ 选择 · Enter 执行 · Esc 关闭")}`, "");
216
+ return lines;
217
+ }
218
+
219
+ invalidate() {}
220
+ }
221
+
222
+ function showPanel(ctx: ExtensionContext, body: string): void {
223
+ if (ctx.mode === "tui") {
224
+ void ctx.ui.custom<void>((_tui, _theme, _kb, done) => {
225
+ const lines = body.split("\n").map((l) => ` ${l}`);
226
+ return {
227
+ render(width: number) {
228
+ return lines.map((l) =>
229
+ l.length > width ? `${l.slice(0, width - 1)}…` : l,
230
+ );
231
+ },
232
+ handleInput(data: string) {
233
+ if (matchesKey(data, "escape") || matchesKey(data, "return")) done();
234
+ },
235
+ invalidate() {},
236
+ };
237
+ });
238
+ } else {
239
+ ctx.ui.notify(body, "info");
240
+ }
241
+ }
@@ -0,0 +1,88 @@
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
+ FILE_MUTATION_TOOLS,
10
+ normalizePath,
11
+ realpathLike,
12
+ } from "./core/guard.ts";
13
+ import type { PlanEngine } from "./engine.ts";
14
+
15
+ export function wireLifecycle(pi: ExtensionAPI, engine: PlanEngine): void {
16
+ // --- 会话恢复 ---
17
+ pi.on("session_start", (_event, ctx) => {
18
+ engine.attachContext(ctx);
19
+ const entries = ctx.sessionManager.getBranch() as readonly {
20
+ customType?: string;
21
+ data?: unknown;
22
+ }[];
23
+ const { corruptEntry } = engine.restore(entries);
24
+ if (corruptEntry) {
25
+ engine.corrupt = true;
26
+ ctx.ui.notify(
27
+ "检测到损坏的计划状态条目,扩展进入只读保护;请检查会话文件或 /reload。",
28
+ "error",
29
+ );
30
+ }
31
+ engine.refreshUI(ctx);
32
+ });
33
+
34
+ pi.on("session_info_changed", (_event, ctx) => engine.attachContext(ctx));
35
+
36
+ // --- 权限守卫(tool_call 可拦截)---
37
+ pi.on("tool_call", (event, ctx) => {
38
+ if (!FILE_MUTATION_TOOLS.has(event.toolName)) return;
39
+ const s = engine.state;
40
+ if (s.mode === "build" && !engine.config.protectPlanFile) return; // 用户关闭保护
41
+ const planPath = s.plan?.path ? realpathLike(s.plan.path) : null;
42
+ const input = event.input as { path?: unknown };
43
+ const target =
44
+ typeof input.path === "string" && input.path
45
+ ? realpathLike(normalizePath(input.path, ctx.cwd))
46
+ : undefined;
47
+ const decision = decideFileMutation(
48
+ event.toolName,
49
+ s.mode,
50
+ planPath,
51
+ s.plan?.saved ?? false,
52
+ target,
53
+ );
54
+ if (decision.action === "block")
55
+ return { block: true, reason: decision.reason };
56
+ });
57
+
58
+ // --- 上下文注入(prompt cache 友好)---
59
+ pi.on("context", (event) => {
60
+ const block = buildContextBlock(engine.state, engine.P);
61
+ if (!block) return;
62
+ return { messages: injectContext(event.messages, block) };
63
+ });
64
+
65
+ // --- 验证问询:awaiting_validation 结算后问一次 ---
66
+ pi.on("agent_settled", async (_event, ctx) => {
67
+ const outcome = engine.state.plan?.outcome;
68
+ if (outcome?.kind !== "awaiting_validation" || engine.validationAsked)
69
+ return;
70
+ if (!ctx.hasUI || !ctx.isIdle()) return;
71
+ engine.validationAsked = true;
72
+ const passed = await ctx.ui.confirm(
73
+ "必需验证是否通过?",
74
+ outcome.userAction,
75
+ );
76
+ if (passed && engine.state.plan?.outcome?.kind === "awaiting_validation") {
77
+ engine.apply({ t: "plan.complete" }, ctx);
78
+ ctx.ui.notify("验证通过,计划已标记完成。", "info");
79
+ }
80
+ // 未通过/取消:什么都不做,计划保持开放;用户会在对话里说明失败详情。
81
+ });
82
+
83
+ // --- 卸载清理(widget/status 由 reload 重建)---
84
+ pi.on("session_shutdown", (_event, ctx) => {
85
+ ctx.ui.setStatus("plan-build", undefined);
86
+ ctx.ui.setWidget("plan-build-steps", undefined);
87
+ });
88
+ }
@@ -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,90 @@
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
+ if (!plan.saved) engine.apply({ t: "plan.saved" }, ctx);
37
+
38
+ const markdown = fs.readFileSync(plan.path, "utf8");
39
+ const parsed = parseSteps(markdown);
40
+
41
+ // 审阅渲染:把计划全文作为工具结果回显,模型轮结束后用户在对话里看到(无自定义 entry,减少 UI 接管)。
42
+ const review = `# 计划审阅:${plan.title}\n\n${markdown}`;
43
+
44
+ let choice: string | undefined;
45
+ if (ctx.hasUI) {
46
+ choice = await ctx.ui.select(`计划已就绪:${plan.title}`, [
47
+ HERE,
48
+ STEPWISE,
49
+ STAY,
50
+ ]);
51
+ }
52
+ if (!choice || choice === STAY) {
53
+ return ok(
54
+ `${review}\n\n---\n已留在 Plan 模式。等待用户进一步指示;不要开始实现。`,
55
+ );
56
+ }
57
+
58
+ if (choice === STEPWISE) {
59
+ if (parsed.error) {
60
+ return fail(
61
+ `${review}\n\n---\n分步执行需要步骤列表:${parsed.error}`,
62
+ );
63
+ }
64
+ const r = engine.apply({ t: "exec.start", steps: parsed.steps }, ctx);
65
+ engine.apply({ t: "mode.set", mode: "build" }, ctx);
66
+ const n = r.state.execution?.steps.length ?? parsed.steps.length;
67
+ return ok(
68
+ `${review}\n\n---\n用户批准分步实现(共 ${n} 步),已切换到 Build 模式。第 1 步就绪但未开始:向用户简述第 1 步并等待其明确批准(如"继续"),批准后调用 plan_step_control start。`,
69
+ );
70
+ }
71
+
72
+ // 本会话实现
73
+ engine.apply({ t: "mode.set", mode: "build" }, ctx);
74
+ return ok(
75
+ `${review}\n\n---\n用户批准在本会话实现,已切换到 Build 模式。请在批准的范围内实现全部工作,按计划 ## 验证 小节执行必需检查,完成后调用 plan_complete(或 plan_set_outcome 记录未竟事项)。`,
76
+ );
77
+ },
78
+ });
79
+ }
80
+
81
+ function ok(t: string) {
82
+ return { content: [{ type: "text" as const, text: t }], details: undefined };
83
+ }
84
+ function fail(t: string) {
85
+ return {
86
+ content: [{ type: "text" as const, text: t }],
87
+ details: undefined,
88
+ isError: true as const,
89
+ };
90
+ }
@@ -0,0 +1,120 @@
1
+ /** plan_complete + plan_set_outcome:结局记录。 */
2
+
3
+ import { StringEnum } from "@earendil-works/pi-ai";
4
+ import type {
5
+ ExtensionAPI,
6
+ ExtensionToolContext,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import { Type } from "typebox";
9
+ import type { PlanOutcome } from "../core/state.ts";
10
+ import type { PlanEngine } from "../engine.ts";
11
+
12
+ const CompleteParams = Type.Object({
13
+ summary: Type.Optional(
14
+ Type.String({ description: "事实性完成摘要(可选),随历史记录保留" }),
15
+ ),
16
+ });
17
+
18
+ const FinishParams = Type.Object({
19
+ outcome: StringEnum([
20
+ "awaiting_validation",
21
+ "blocked",
22
+ "waiting_for_input",
23
+ "still_working",
24
+ ]),
25
+ userAction: Type.Optional(
26
+ Type.String({
27
+ description: "awaiting_validation 必填:用户要执行的精确验证步骤",
28
+ }),
29
+ ),
30
+ reason: Type.Optional(
31
+ Type.String({
32
+ description: "blocked/waiting_for_input/still_working 必填:原因",
33
+ }),
34
+ ),
35
+ });
36
+
37
+ export function registerPlanOutcome(
38
+ pi: ExtensionAPI,
39
+ engine: PlanEngine,
40
+ ): void {
41
+ pi.registerTool({
42
+ name: "plan_complete",
43
+ label: "Plan Complete",
44
+ description:
45
+ "标记整个计划完成:仅在全部批准工作与必需检查通过后,或用户明确指示整计划完成时调用(分步执行进行中也允许,会如实收尾)。绝不虚构未执行的检查。",
46
+ parameters: CompleteParams,
47
+ async execute(_id, params, _signal, _onUpdate, ctx: ExtensionToolContext) {
48
+ if (!engine.state.plan) return fail("当前没有计划。");
49
+ engine.validationAsked = false;
50
+ const r = engine.apply(
51
+ { t: "plan.complete", summary: params.summary },
52
+ ctx,
53
+ );
54
+ return ok(
55
+ `计划已标记完成。${r.note ?? ""}${params.summary ? `\n摘要:${params.summary}` : ""}`,
56
+ );
57
+ },
58
+ });
59
+
60
+ pi.registerTool({
61
+ name: "plan_set_outcome",
62
+ label: "Plan Set Outcome",
63
+ description:
64
+ "记录未完成结局并保持计划开放:awaiting_validation(必需的用户验证,userAction 必填)、blocked / waiting_for_input / still_working(reason 必填)。绝不因空闲推断成功。",
65
+ parameters: FinishParams,
66
+ async execute(_id, params, _signal, _onUpdate, ctx: ExtensionToolContext) {
67
+ if (!engine.state.plan) return fail("当前没有计划。");
68
+ if (
69
+ params.outcome === "awaiting_validation" &&
70
+ !params.userAction?.trim()
71
+ ) {
72
+ return fail(
73
+ "awaiting_validation 需要 userAction:用户要执行的精确验证步骤(多项检查每项一个简短要点)。",
74
+ );
75
+ }
76
+ if (params.outcome !== "awaiting_validation" && !params.reason?.trim()) {
77
+ return fail(`${params.outcome} 需要 reason。`);
78
+ }
79
+ let outcome: PlanOutcome;
80
+ switch (params.outcome) {
81
+ case "awaiting_validation":
82
+ outcome = {
83
+ kind: "awaiting_validation",
84
+ userAction: (params.userAction ?? "").trim(),
85
+ };
86
+ break;
87
+ case "blocked":
88
+ case "waiting_for_input":
89
+ case "still_working":
90
+ outcome = {
91
+ kind: params.outcome,
92
+ reason: (params.reason ?? "").trim(),
93
+ };
94
+ break;
95
+ default:
96
+ return fail(`未知 outcome:${String(params.outcome)}`);
97
+ }
98
+ const r = engine.apply({ t: "plan.finish", outcome }, ctx);
99
+ engine.validationAsked = false;
100
+ const action =
101
+ outcome.kind === "awaiting_validation"
102
+ ? `\n请在总结后向用户展示必需验证步骤:${outcome.userAction}`
103
+ : "";
104
+ return ok(
105
+ `已记录结局:${outcome.kind}。计划保持开放。${r.note ?? ""}${action}`,
106
+ );
107
+ },
108
+ });
109
+ }
110
+
111
+ function ok(t: string) {
112
+ return { content: [{ type: "text" as const, text: t }], details: undefined };
113
+ }
114
+ function fail(t: string) {
115
+ return {
116
+ content: [{ type: "text" as const, text: t }],
117
+ details: undefined,
118
+ isError: true as const,
119
+ };
120
+ }
@@ -0,0 +1,80 @@
1
+ /** question:结构化提问工具(精简自官方 question.ts 模式)。 */
2
+
3
+ import type {
4
+ ExtensionAPI,
5
+ ExtensionToolContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+
9
+ const QuestionT = Type.Object({
10
+ question: Type.String({ description: "问题" }),
11
+ header: Type.String({ description: "短标题(≤12 字符)" }),
12
+ options: Type.Array(
13
+ Type.Object({
14
+ label: Type.String({ description: "选项显示文本" }),
15
+ description: Type.Optional(Type.String({ description: "选项说明" })),
16
+ }),
17
+ { minItems: 2, maxItems: 4 },
18
+ ),
19
+ });
20
+
21
+ const Params = Type.Object({
22
+ questions: Type.Array(QuestionT, { minItems: 1, maxItems: 4 }),
23
+ });
24
+
25
+ export function registerQuestion(pi: ExtensionAPI): void {
26
+ pi.registerTool({
27
+ name: "plan_question",
28
+ label: "Plan Question",
29
+ description:
30
+ "向用户提出结构化选择题,收集决策/澄清歧义。推荐选项放第一个并在 label 尾部加“(推荐)”。",
31
+ parameters: Params,
32
+ async execute(_id, params, _signal, _onUpdate, ctx: ExtensionToolContext) {
33
+ if (!ctx.hasUI) {
34
+ const rendered = params.questions
35
+ .map(
36
+ (q, i) =>
37
+ `${i + 1}. ${q.question}\n${q.options.map((o) => ` - ${o.label}${o.description ? `:${o.description}` : ""}`).join("\n")}`,
38
+ )
39
+ .join("\n");
40
+ return {
41
+ content: [
42
+ {
43
+ type: "text" as const,
44
+ text: `当前无交互 UI,请把问题作为文本等待用户回复:\n${rendered}`,
45
+ },
46
+ ],
47
+ details: undefined,
48
+ };
49
+ }
50
+ const answers: string[] = [];
51
+ for (const q of params.questions) {
52
+ const choice = await ctx.ui.select(
53
+ q.question,
54
+ q.options.map((o) => o.label),
55
+ );
56
+ if (choice === undefined) {
57
+ return {
58
+ content: [
59
+ {
60
+ type: "text" as const,
61
+ text: "用户取消了提问。请根据上下文继续,不要重复询问。",
62
+ },
63
+ ],
64
+ details: undefined,
65
+ };
66
+ }
67
+ answers.push(`${q.header}: ${choice}`);
68
+ }
69
+ return {
70
+ content: [
71
+ {
72
+ type: "text" as const,
73
+ text: `用户的选择:\n${answers.join("\n")}`,
74
+ },
75
+ ],
76
+ details: undefined,
77
+ };
78
+ },
79
+ });
80
+ }