@narumitw/pi-plan-mode 0.58.0 → 0.58.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.
Files changed (39) hide show
  1. package/dist/chunks/{chunk-QHHHBTDO.js → chunk-HF7ZEYIC.js} +29 -111
  2. package/dist/chunks/chunk-HF7ZEYIC.js.map +7 -0
  3. package/dist/chunks/{interactive-ui-UNJGC2RQ.js → interactive-ui-UK7IGPOE.js} +13 -41
  4. package/dist/chunks/interactive-ui-UK7IGPOE.js.map +7 -0
  5. package/dist/index.ts +25 -82
  6. package/dist/index.ts.map +2 -2
  7. package/package.json +50 -51
  8. package/src/active-implementation-menu.ts +57 -60
  9. package/src/command.ts +22 -22
  10. package/src/completion-tool.ts +53 -56
  11. package/src/extension-runtime.ts +5 -5
  12. package/src/finalization-request.ts +40 -44
  13. package/src/fresh-handoff-coordinator.ts +38 -41
  14. package/src/fresh-implementation.ts +293 -310
  15. package/src/implementation-models.ts +25 -30
  16. package/src/implementation-retention.ts +109 -123
  17. package/src/message-transform.ts +218 -252
  18. package/src/mode-contract.ts +46 -49
  19. package/src/plan-action-controller.ts +134 -155
  20. package/src/plan-action-menus.ts +390 -408
  21. package/src/plan-export-controller.ts +23 -28
  22. package/src/plan-export-screen.ts +13 -13
  23. package/src/plan-export.ts +85 -102
  24. package/src/plan-launch-menu.ts +119 -119
  25. package/src/plan-mode.ts +2017 -2098
  26. package/src/presentation.ts +84 -108
  27. package/src/prompt.ts +1 -1
  28. package/src/question-tool.ts +239 -267
  29. package/src/required-tools.ts +15 -19
  30. package/src/saved-plan-menu.ts +82 -84
  31. package/src/saved-plan-preflight.ts +29 -33
  32. package/src/settings-menu.ts +470 -513
  33. package/src/settings.ts +393 -452
  34. package/src/state.ts +167 -198
  35. package/src/tool-policy.ts +634 -699
  36. package/src/tool-selection.ts +39 -44
  37. package/src/workflow-mutex.ts +66 -66
  38. package/dist/chunks/chunk-QHHHBTDO.js.map +0 -7
  39. package/dist/chunks/interactive-ui-UNJGC2RQ.js.map +0 -7
@@ -1,585 +1,542 @@
1
1
  import type { ExtensionContext, ToolInfo } from "@earendil-works/pi-coding-agent";
2
- import {
3
- defineMenu,
4
- type RunMenuResult,
5
- runMenu,
6
- sanitizeTerminalText,
7
- } from "@narumitw/pi-tui-kit";
2
+ import { defineMenu, type RunMenuResult, runMenu, sanitizeTerminalText } from "@narumitw/pi-tui-kit";
8
3
  import { PLAN_MODE_COMPLETE_TOOL_NAME } from "./completion-tool.js";
9
4
  import {
10
- type AvailableImplementationModel,
11
- findAvailableImplementationModel,
12
- type ImplementationModelOverride,
13
- snapshotAvailableImplementationModels,
5
+ type AvailableImplementationModel,
6
+ findAvailableImplementationModel,
7
+ type ImplementationModelOverride,
8
+ snapshotAvailableImplementationModels,
14
9
  } from "./implementation-models.js";
15
10
  import { retentionLabel } from "./implementation-retention.js";
16
11
  import { planExportDestination } from "./plan-export.js";
17
12
  import { PLAN_MODE_QUESTION_TOOL_NAME } from "./question-tool.js";
18
13
  import {
19
- configuredImplementationModel,
20
- configuredImplementationPlanRetention,
21
- configuredImplementationThinkingLevel,
22
- configuredPlanExportPath,
23
- configuredPlanModeToggleShortcut,
24
- IMPLEMENTATION_PLAN_RETENTIONS,
25
- IMPLEMENTATION_THINKING_LEVELS,
26
- normalizeKeyId,
27
- PLAN_MODE_THINKING_LEVELS,
28
- type PlanModeSettings,
29
- type PlanModeSettingsLoadResult,
30
- type PlanModeSettingsPatch,
31
- planModeSettingsPath,
32
- readPlanModeSettings,
33
- type UpdatePlanModeSettingsOptions,
34
- updatePlanModeSettings,
14
+ configuredImplementationModel,
15
+ configuredImplementationPlanRetention,
16
+ configuredImplementationThinkingLevel,
17
+ configuredPlanExportPath,
18
+ configuredPlanModeToggleShortcut,
19
+ IMPLEMENTATION_PLAN_RETENTIONS,
20
+ IMPLEMENTATION_THINKING_LEVELS,
21
+ normalizeKeyId,
22
+ PLAN_MODE_THINKING_LEVELS,
23
+ type PlanModeSettings,
24
+ type PlanModeSettingsLoadResult,
25
+ type PlanModeSettingsPatch,
26
+ planModeSettingsPath,
27
+ readPlanModeSettings,
28
+ type UpdatePlanModeSettingsOptions,
29
+ updatePlanModeSettings,
35
30
  } from "./settings.js";
36
31
  import { canSelectToolInPlanMode } from "./tool-policy.js";
37
32
  import { defaultPlanModeToolNames, toolPolicyLabel } from "./tool-selection.js";
38
33
 
39
34
  interface SettingsMenuState {
40
- kind: "valid" | "invalid";
41
- settings: PlanModeSettings;
42
- notice?: string;
43
- reason?: string;
35
+ kind: "valid" | "invalid";
36
+ settings: PlanModeSettings;
37
+ notice?: string;
38
+ reason?: string;
44
39
  }
45
40
 
46
41
  export interface PlanModeSettingsMenuOptions {
47
- tools: readonly ToolInfo[];
48
- activeToolNames?: readonly string[];
49
- signal: AbortSignal;
50
- isCurrent(): boolean;
51
- settingsPath?: string;
52
- legacySettingsPath?: string;
53
- readSettings?: (settingsPath?: string) => Promise<PlanModeSettingsLoadResult>;
54
- updateSettings?: (
55
- patch: PlanModeSettingsPatch,
56
- options?: UpdatePlanModeSettingsOptions,
57
- ) => Promise<PlanModeSettings>;
58
- onSaved(settings: PlanModeSettings): void;
42
+ tools: readonly ToolInfo[];
43
+ activeToolNames?: readonly string[];
44
+ signal: AbortSignal;
45
+ isCurrent(): boolean;
46
+ settingsPath?: string;
47
+ legacySettingsPath?: string;
48
+ readSettings?: (settingsPath?: string) => Promise<PlanModeSettingsLoadResult>;
49
+ updateSettings?: (patch: PlanModeSettingsPatch, options?: UpdatePlanModeSettingsOptions) => Promise<PlanModeSettings>;
50
+ onSaved(settings: PlanModeSettings): void;
59
51
  }
60
52
 
61
53
  type Screen = "settings" | "tools" | "implementation-model" | "export" | "shortcut";
62
54
  type Action =
63
- | "set-thinking"
64
- | "open-tools"
65
- | "toggle-tool"
66
- | "reset-tools"
67
- | "set-retention"
68
- | "open-implementation-model"
69
- | "set-implementation-model"
70
- | "set-implementation-thinking"
71
- | "open-export"
72
- | "set-export"
73
- | "open-shortcut"
74
- | "set-shortcut";
55
+ | "set-thinking"
56
+ | "open-tools"
57
+ | "toggle-tool"
58
+ | "reset-tools"
59
+ | "set-retention"
60
+ | "open-implementation-model"
61
+ | "set-implementation-model"
62
+ | "set-implementation-thinking"
63
+ | "open-export"
64
+ | "set-export"
65
+ | "open-shortcut"
66
+ | "set-shortcut";
75
67
 
76
68
  export async function showPlanModeSettings(
77
- ctx: ExtensionContext,
78
- options: PlanModeSettingsMenuOptions,
69
+ ctx: ExtensionContext,
70
+ options: PlanModeSettingsMenuOptions,
79
71
  ): Promise<RunMenuResult> {
80
- const settingsPath = options.settingsPath ?? planModeSettingsPath();
81
- const readSettings = options.readSettings ?? readPlanModeSettings;
82
- const updateSettings = options.updateSettings ?? updatePlanModeSettings;
83
- const activeToolNames = new Set(
84
- options.activeToolNames ?? options.tools.map((tool) => tool.name),
85
- );
86
- const tools = options.tools.filter(
87
- (tool) =>
88
- tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME,
89
- );
90
- const toolItemIds = new Map(
91
- tools.map((tool, index) => [tool.name, `plan-settings-tool:${index}`]),
92
- );
93
- const toolsByItemId = new Map(tools.map((tool) => [toolItemIds.get(tool.name) as string, tool]));
94
- const implementationModels = snapshotAvailableImplementationModels(ctx);
95
- const modelItemIds = new Map(
96
- implementationModels.map((model, index) => [model, `plan-settings-model:${index}`]),
97
- );
98
- const modelsByItemId = new Map(
99
- implementationModels.map((model) => [modelItemIds.get(model) as string, model]),
100
- );
72
+ const settingsPath = options.settingsPath ?? planModeSettingsPath();
73
+ const readSettings = options.readSettings ?? readPlanModeSettings;
74
+ const updateSettings = options.updateSettings ?? updatePlanModeSettings;
75
+ const activeToolNames = new Set(options.activeToolNames ?? options.tools.map((tool) => tool.name));
76
+ const tools = options.tools.filter(
77
+ (tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME,
78
+ );
79
+ const toolItemIds = new Map(tools.map((tool, index) => [tool.name, `plan-settings-tool:${index}`]));
80
+ const toolsByItemId = new Map(tools.map((tool) => [toolItemIds.get(tool.name) as string, tool]));
81
+ const implementationModels = snapshotAvailableImplementationModels(ctx);
82
+ const modelItemIds = new Map(implementationModels.map((model, index) => [model, `plan-settings-model:${index}`]));
83
+ const modelsByItemId = new Map(implementationModels.map((model) => [modelItemIds.get(model) as string, model]));
101
84
 
102
- const loadState = async (): Promise<SettingsMenuState> => {
103
- const loaded = await readSettings(options.settingsPath);
104
- if (loaded.kind === "invalid") {
105
- return {
106
- kind: "invalid",
107
- settings: { thinkingLevel: "inherit" },
108
- notice: loaded.notice,
109
- reason: loaded.reason,
110
- };
111
- }
112
- return {
113
- kind: "valid",
114
- settings: loaded.kind === "loaded" ? loaded.settings : { thinkingLevel: "inherit" },
115
- notice: loaded.notice,
116
- };
117
- };
85
+ const loadState = async (): Promise<SettingsMenuState> => {
86
+ const loaded = await readSettings(options.settingsPath);
87
+ if (loaded.kind === "invalid") {
88
+ return {
89
+ kind: "invalid",
90
+ settings: { thinkingLevel: "inherit" },
91
+ notice: loaded.notice,
92
+ reason: loaded.reason,
93
+ };
94
+ }
95
+ return {
96
+ kind: "valid",
97
+ settings: loaded.kind === "loaded" ? loaded.settings : { thinkingLevel: "inherit" },
98
+ notice: loaded.notice,
99
+ };
100
+ };
118
101
 
119
- const menu = defineMenu<SettingsMenuState, Screen, Action, ExtensionContext>({
120
- start: "settings",
121
- screens: {
122
- settings: ({ state }) =>
123
- state.kind === "invalid"
124
- ? invalidScreen(settingsPath, state)
125
- : {
126
- kind: "settings",
127
- title: "Plan Mode Settings",
128
- lines: settingsLines(settingsPath, state.notice),
129
- items: [
130
- {
131
- id: "thinkingLevel",
132
- label: "Plan thinking",
133
- description: "Set the thinking level when the next Plan workflow starts.",
134
- currentValue: state.settings.thinkingLevel,
135
- values: PLAN_MODE_THINKING_LEVELS,
136
- action: "set-thinking",
137
- },
138
- {
139
- id: "defaultPlanTools",
140
- label: "Plan policy tools",
141
- description:
142
- "Choose active tools or retain names to resolve before the first request.",
143
- currentValue: defaultToolsValue(state.settings.defaultPlanTools),
144
- action: "open-tools",
145
- },
146
- {
147
- id: "implementationPlanRetention",
148
- label: "Plan reinjection",
149
- description:
150
- "Choose how long Plan mode restores the exact plan when ordinary context no longer contains it.",
151
- currentValue: retentionLabel(
152
- configuredImplementationPlanRetention(state.settings),
153
- ),
154
- values: IMPLEMENTATION_PLAN_RETENTIONS.map(retentionLabel),
155
- action: "set-retention",
156
- },
157
- {
158
- id: "defaultImplementationModel",
159
- label: "Fresh model",
160
- description: "Choose the default model for a fresh implementation session.",
161
- currentValue: implementationModelValue(state.settings, implementationModels),
162
- action: "open-implementation-model",
163
- },
164
- {
165
- id: "defaultImplementationThinkingLevel",
166
- label: "Fresh thinking",
167
- description:
168
- "Choose the default thinking level for a fresh implementation session.",
169
- currentValue:
170
- configuredImplementationThinkingLevel(state.settings) ?? "same as plan",
171
- values: ["same as plan", ...IMPLEMENTATION_THINKING_LEVELS],
172
- action: "set-implementation-thinking",
173
- },
174
- {
175
- id: "defaultPlanExportPath",
176
- label: "Export destination",
177
- description: "Set the destination used when an export omits its path.",
178
- currentValue: safeTerminalText(configuredPlanExportPath(state.settings)),
179
- action: "open-export",
180
- },
181
- {
182
- id: "toggleShortcut",
183
- label: "Plan mode shortcut",
184
- description: "Set the global shortcut used to toggle Plan mode.",
185
- currentValue: configuredPlanModeToggleShortcut(state.settings) ?? "none",
186
- action: "open-shortcut",
187
- },
188
- ],
189
- },
190
- tools: ({ state }) => ({
191
- kind: "multiSelect",
192
- title: "Default Plan policy allowlist",
193
- lines: [
194
- "Changes apply when a later Plan workflow starts; model-visible tools stay unchanged.",
195
- "Retained inactive names resolve before that workflow's first request.",
196
- "Plan mode never activates tools, and non-built-ins run at user risk.",
197
- ],
198
- enableSearch: true,
199
- viewportSize: 10,
200
- items: defaultToolItems(
201
- tools,
202
- state.settings.defaultPlanTools,
203
- activeToolNames,
204
- toolItemIds,
205
- ),
206
- action: "toggle-tool",
207
- actions: [
208
- {
209
- id: "reset-tools",
210
- label: "Use automatic safe built-ins",
211
- action: "reset-tools",
212
- },
213
- ],
214
- hint: "back",
215
- }),
216
- "implementation-model": ({ state }) => ({
217
- kind: "choice",
218
- title: "Fresh implementation model",
219
- lines: ["Same as plan is the default and fallback when a configured model is unavailable."],
220
- items: implementationModelItems(implementationModels, modelItemIds),
221
- action: "set-implementation-model",
222
- initialItemId: implementationModelItemId(
223
- configuredImplementationModel(state.settings),
224
- implementationModels,
225
- modelItemIds,
226
- ),
227
- enableSearch: true,
228
- viewportSize: 10,
229
- hint: "back",
230
- }),
231
- export: ({ state }) => {
232
- const configured = configuredPlanExportPath(state.settings);
233
- const destination = planExportDestination(configured, ctx.cwd);
234
- return {
235
- kind: "input",
236
- title: "Export destination",
237
- lines: [
238
- `Configured: ${destination.configuredPath}`,
239
- `Resolves here to: ${destination.resolvedPath}`,
240
- "Submit an empty value to reset to PLAN.md. Changes affect the next export.",
241
- ],
242
- placeholder: configured,
243
- action: "set-export",
244
- hint: "back",
245
- };
246
- },
247
- shortcut: ({ state }) => ({
248
- kind: "input",
249
- title: "Plan mode shortcut",
250
- lines: [
251
- `Configured: ${configuredPlanModeToggleShortcut(state.settings) ?? "none"}`,
252
- "Use Pi key identifiers.",
253
- "Submit an empty value to clear the shortcut.",
254
- "When unset, Plan mode has no global shortcut.",
255
- ],
256
- placeholder: configuredPlanModeToggleShortcut(state.settings) ?? "",
257
- action: "set-shortcut",
258
- hint: "back",
259
- }),
260
- },
261
- actions: {
262
- "set-thinking": async ({ ctx: actionCtx, value, signal }) => {
263
- if (
264
- !PLAN_MODE_THINKING_LEVELS.includes(value as (typeof PLAN_MODE_THINKING_LEVELS)[number])
265
- ) {
266
- return { kind: "rejected" };
267
- }
268
- return savePatch(
269
- actionCtx,
270
- { thinkingLevel: value as PlanModeSettings["thinkingLevel"] },
271
- signal,
272
- `Plan mode thinking level: ${value}. Applies to the next Plan workflow.`,
273
- );
274
- },
275
- "open-tools": async () => ({ kind: "to", screen: "tools" }),
276
- "set-retention": async ({ ctx: actionCtx, value, signal }) => {
277
- const implementationPlanRetention = retentionFromLabel(value);
278
- if (!implementationPlanRetention) return { kind: "rejected" };
279
- return savePatch(
280
- actionCtx,
281
- { implementationPlanRetention },
282
- signal,
283
- `Plan reinjection: ${retentionLabel(implementationPlanRetention)}. Applies to the next Implement action.`,
284
- );
285
- },
286
- "open-implementation-model": async () => ({
287
- kind: "to",
288
- screen: "implementation-model",
289
- }),
290
- "set-implementation-model": async ({ ctx: actionCtx, itemId, signal }) => {
291
- const model = itemId ? modelsByItemId.get(itemId) : undefined;
292
- if (itemId !== "same-as-plan" && !model) return { kind: "rejected" };
293
- const defaultImplementationModel = model
294
- ? { provider: model.provider, modelId: model.id }
295
- : null;
296
- const result = await savePatch(
297
- actionCtx,
298
- { defaultImplementationModel },
299
- signal,
300
- model
301
- ? `Fresh implementation model: ${safeModelReference({ provider: model.provider, modelId: model.id })}.`
302
- : "Fresh implementation model: same as plan.",
303
- );
304
- return result.kind === "stay" ? { kind: "to", screen: "settings" } : result;
305
- },
306
- "set-implementation-thinking": async ({ ctx: actionCtx, value, signal }) => {
307
- if (value === "same as plan") {
308
- return savePatch(
309
- actionCtx,
310
- { defaultImplementationThinkingLevel: null },
311
- signal,
312
- "Fresh implementation thinking: same as plan.",
313
- );
314
- }
315
- if (
316
- !IMPLEMENTATION_THINKING_LEVELS.includes(
317
- value as (typeof IMPLEMENTATION_THINKING_LEVELS)[number],
318
- )
319
- ) {
320
- return { kind: "rejected" };
321
- }
322
- return savePatch(
323
- actionCtx,
324
- {
325
- defaultImplementationThinkingLevel:
326
- value as PlanModeSettings["defaultImplementationThinkingLevel"],
327
- },
328
- signal,
329
- `Fresh implementation thinking: ${value}.`,
330
- );
331
- },
332
- "open-export": async () => ({ kind: "to", screen: "export" }),
333
- "set-export": async ({ ctx: actionCtx, value, signal }) => {
334
- const defaultPlanExportPath = value?.trim() || null;
335
- const result = await savePatch(
336
- actionCtx,
337
- { defaultPlanExportPath },
338
- signal,
339
- defaultPlanExportPath
340
- ? `Default Plan export destination: ${safeTerminalText(defaultPlanExportPath)}.`
341
- : "Default Plan export destination reset to PLAN.md.",
342
- );
343
- return result.kind === "stay" ? { kind: "to", screen: "settings" } : result;
344
- },
345
- "open-shortcut": async () => ({ kind: "to", screen: "shortcut" }),
346
- "set-shortcut": async ({ ctx: actionCtx, value, signal }) => {
347
- const raw = value?.trim() || null;
348
- if (raw && !normalizeKeyId(raw)) {
349
- actionCtx.ui.notify(
350
- `Invalid key identifier: ${safeTerminalText(raw)}. Use Pi key identifiers like ctrl+alt+p.`,
351
- "warning",
352
- );
353
- return { kind: "stay" as const };
354
- }
355
- const toggleShortcut = raw as PlanModeSettingsPatch["toggleShortcut"];
356
- const result = await savePatch(
357
- actionCtx,
358
- { toggleShortcut },
359
- signal,
360
- toggleShortcut
361
- ? `Plan mode shortcut: ${safeTerminalText(toggleShortcut)}.`
362
- : "Plan mode shortcut cleared (no global shortcut).",
363
- );
364
- return result.kind === "stay" ? { kind: "to", screen: "settings" } : result;
365
- },
366
- "toggle-tool": async ({ ctx: actionCtx, state, itemId, selected, signal }) => {
367
- const tool = itemId ? toolsByItemId.get(itemId) : undefined;
368
- if (!tool || !activeToolNames.has(tool.name) || !canSelectToolInPlanMode(tool)) {
369
- return { kind: "rejected" };
370
- }
371
- const names = explicitToolNames(tools, state.settings.defaultPlanTools);
372
- const next = selected
373
- ? Array.from(new Set([...names, tool.name]))
374
- : names.filter((name) => name !== tool.name);
375
- return savePatch(
376
- actionCtx,
377
- { defaultPlanTools: next },
378
- signal,
379
- `Default Plan policy: ${next.length === 0 ? "no optional tools" : `${next.length} allowed`}.`,
380
- );
381
- },
382
- "reset-tools": async ({ ctx: actionCtx, state, signal }) => {
383
- if (state.settings.defaultPlanTools === undefined) return { kind: "stay" };
384
- return savePatch(
385
- actionCtx,
386
- { defaultPlanTools: null },
387
- signal,
388
- "Default Plan-mode tools: automatic safe built-ins.",
389
- );
390
- },
391
- },
392
- });
102
+ const menu = defineMenu<SettingsMenuState, Screen, Action, ExtensionContext>({
103
+ start: "settings",
104
+ screens: {
105
+ settings: ({ state }) =>
106
+ state.kind === "invalid"
107
+ ? invalidScreen(settingsPath, state)
108
+ : {
109
+ kind: "settings",
110
+ title: "Plan Mode Settings",
111
+ lines: settingsLines(settingsPath, state.notice),
112
+ items: [
113
+ {
114
+ id: "thinkingLevel",
115
+ label: "Plan thinking",
116
+ description: "Set the thinking level when the next Plan workflow starts.",
117
+ currentValue: state.settings.thinkingLevel,
118
+ values: PLAN_MODE_THINKING_LEVELS,
119
+ action: "set-thinking",
120
+ },
121
+ {
122
+ id: "defaultPlanTools",
123
+ label: "Plan policy tools",
124
+ description: "Choose active tools or retain names to resolve before the first request.",
125
+ currentValue: defaultToolsValue(state.settings.defaultPlanTools),
126
+ action: "open-tools",
127
+ },
128
+ {
129
+ id: "implementationPlanRetention",
130
+ label: "Plan reinjection",
131
+ description:
132
+ "Choose how long Plan mode restores the exact plan when ordinary context no longer contains it.",
133
+ currentValue: retentionLabel(configuredImplementationPlanRetention(state.settings)),
134
+ values: IMPLEMENTATION_PLAN_RETENTIONS.map(retentionLabel),
135
+ action: "set-retention",
136
+ },
137
+ {
138
+ id: "defaultImplementationModel",
139
+ label: "Fresh model",
140
+ description: "Choose the default model for a fresh implementation session.",
141
+ currentValue: implementationModelValue(state.settings, implementationModels),
142
+ action: "open-implementation-model",
143
+ },
144
+ {
145
+ id: "defaultImplementationThinkingLevel",
146
+ label: "Fresh thinking",
147
+ description: "Choose the default thinking level for a fresh implementation session.",
148
+ currentValue: configuredImplementationThinkingLevel(state.settings) ?? "same as plan",
149
+ values: ["same as plan", ...IMPLEMENTATION_THINKING_LEVELS],
150
+ action: "set-implementation-thinking",
151
+ },
152
+ {
153
+ id: "defaultPlanExportPath",
154
+ label: "Export destination",
155
+ description: "Set the destination used when an export omits its path.",
156
+ currentValue: safeTerminalText(configuredPlanExportPath(state.settings)),
157
+ action: "open-export",
158
+ },
159
+ {
160
+ id: "toggleShortcut",
161
+ label: "Plan mode shortcut",
162
+ description: "Set the global shortcut used to toggle Plan mode.",
163
+ currentValue: configuredPlanModeToggleShortcut(state.settings) ?? "none",
164
+ action: "open-shortcut",
165
+ },
166
+ ],
167
+ },
168
+ tools: ({ state }) => ({
169
+ kind: "multiSelect",
170
+ title: "Default Plan policy allowlist",
171
+ lines: [
172
+ "Changes apply when a later Plan workflow starts; model-visible tools stay unchanged.",
173
+ "Retained inactive names resolve before that workflow's first request.",
174
+ "Plan mode never activates tools, and non-built-ins run at user risk.",
175
+ ],
176
+ enableSearch: true,
177
+ viewportSize: 10,
178
+ items: defaultToolItems(tools, state.settings.defaultPlanTools, activeToolNames, toolItemIds),
179
+ action: "toggle-tool",
180
+ actions: [
181
+ {
182
+ id: "reset-tools",
183
+ label: "Use automatic safe built-ins",
184
+ action: "reset-tools",
185
+ },
186
+ ],
187
+ hint: "back",
188
+ }),
189
+ "implementation-model": ({ state }) => ({
190
+ kind: "choice",
191
+ title: "Fresh implementation model",
192
+ lines: ["Same as plan is the default and fallback when a configured model is unavailable."],
193
+ items: implementationModelItems(implementationModels, modelItemIds),
194
+ action: "set-implementation-model",
195
+ initialItemId: implementationModelItemId(
196
+ configuredImplementationModel(state.settings),
197
+ implementationModels,
198
+ modelItemIds,
199
+ ),
200
+ enableSearch: true,
201
+ viewportSize: 10,
202
+ hint: "back",
203
+ }),
204
+ export: ({ state }) => {
205
+ const configured = configuredPlanExportPath(state.settings);
206
+ const destination = planExportDestination(configured, ctx.cwd);
207
+ return {
208
+ kind: "input",
209
+ title: "Export destination",
210
+ lines: [
211
+ `Configured: ${destination.configuredPath}`,
212
+ `Resolves here to: ${destination.resolvedPath}`,
213
+ "Submit an empty value to reset to PLAN.md. Changes affect the next export.",
214
+ ],
215
+ placeholder: configured,
216
+ action: "set-export",
217
+ hint: "back",
218
+ };
219
+ },
220
+ shortcut: ({ state }) => ({
221
+ kind: "input",
222
+ title: "Plan mode shortcut",
223
+ lines: [
224
+ `Configured: ${configuredPlanModeToggleShortcut(state.settings) ?? "none"}`,
225
+ "Use Pi key identifiers.",
226
+ "Submit an empty value to clear the shortcut.",
227
+ "When unset, Plan mode has no global shortcut.",
228
+ ],
229
+ placeholder: configuredPlanModeToggleShortcut(state.settings) ?? "",
230
+ action: "set-shortcut",
231
+ hint: "back",
232
+ }),
233
+ },
234
+ actions: {
235
+ "set-thinking": async ({ ctx: actionCtx, value, signal }) => {
236
+ if (!PLAN_MODE_THINKING_LEVELS.includes(value as (typeof PLAN_MODE_THINKING_LEVELS)[number])) {
237
+ return { kind: "rejected" };
238
+ }
239
+ return savePatch(
240
+ actionCtx,
241
+ { thinkingLevel: value as PlanModeSettings["thinkingLevel"] },
242
+ signal,
243
+ `Plan mode thinking level: ${value}. Applies to the next Plan workflow.`,
244
+ );
245
+ },
246
+ "open-tools": async () => ({ kind: "to", screen: "tools" }),
247
+ "set-retention": async ({ ctx: actionCtx, value, signal }) => {
248
+ const implementationPlanRetention = retentionFromLabel(value);
249
+ if (!implementationPlanRetention) return { kind: "rejected" };
250
+ return savePatch(
251
+ actionCtx,
252
+ { implementationPlanRetention },
253
+ signal,
254
+ `Plan reinjection: ${retentionLabel(implementationPlanRetention)}. Applies to the next Implement action.`,
255
+ );
256
+ },
257
+ "open-implementation-model": async () => ({
258
+ kind: "to",
259
+ screen: "implementation-model",
260
+ }),
261
+ "set-implementation-model": async ({ ctx: actionCtx, itemId, signal }) => {
262
+ const model = itemId ? modelsByItemId.get(itemId) : undefined;
263
+ if (itemId !== "same-as-plan" && !model) return { kind: "rejected" };
264
+ const defaultImplementationModel = model ? { provider: model.provider, modelId: model.id } : null;
265
+ const result = await savePatch(
266
+ actionCtx,
267
+ { defaultImplementationModel },
268
+ signal,
269
+ model
270
+ ? `Fresh implementation model: ${safeModelReference({ provider: model.provider, modelId: model.id })}.`
271
+ : "Fresh implementation model: same as plan.",
272
+ );
273
+ return result.kind === "stay" ? { kind: "to", screen: "settings" } : result;
274
+ },
275
+ "set-implementation-thinking": async ({ ctx: actionCtx, value, signal }) => {
276
+ if (value === "same as plan") {
277
+ return savePatch(
278
+ actionCtx,
279
+ { defaultImplementationThinkingLevel: null },
280
+ signal,
281
+ "Fresh implementation thinking: same as plan.",
282
+ );
283
+ }
284
+ if (!IMPLEMENTATION_THINKING_LEVELS.includes(value as (typeof IMPLEMENTATION_THINKING_LEVELS)[number])) {
285
+ return { kind: "rejected" };
286
+ }
287
+ return savePatch(
288
+ actionCtx,
289
+ {
290
+ defaultImplementationThinkingLevel: value as PlanModeSettings["defaultImplementationThinkingLevel"],
291
+ },
292
+ signal,
293
+ `Fresh implementation thinking: ${value}.`,
294
+ );
295
+ },
296
+ "open-export": async () => ({ kind: "to", screen: "export" }),
297
+ "set-export": async ({ ctx: actionCtx, value, signal }) => {
298
+ const defaultPlanExportPath = value?.trim() || null;
299
+ const result = await savePatch(
300
+ actionCtx,
301
+ { defaultPlanExportPath },
302
+ signal,
303
+ defaultPlanExportPath
304
+ ? `Default Plan export destination: ${safeTerminalText(defaultPlanExportPath)}.`
305
+ : "Default Plan export destination reset to PLAN.md.",
306
+ );
307
+ return result.kind === "stay" ? { kind: "to", screen: "settings" } : result;
308
+ },
309
+ "open-shortcut": async () => ({ kind: "to", screen: "shortcut" }),
310
+ "set-shortcut": async ({ ctx: actionCtx, value, signal }) => {
311
+ const raw = value?.trim() || null;
312
+ if (raw && !normalizeKeyId(raw)) {
313
+ actionCtx.ui.notify(
314
+ `Invalid key identifier: ${safeTerminalText(raw)}. Use Pi key identifiers like ctrl+alt+p.`,
315
+ "warning",
316
+ );
317
+ return { kind: "stay" as const };
318
+ }
319
+ const toggleShortcut = raw as PlanModeSettingsPatch["toggleShortcut"];
320
+ const result = await savePatch(
321
+ actionCtx,
322
+ { toggleShortcut },
323
+ signal,
324
+ toggleShortcut
325
+ ? `Plan mode shortcut: ${safeTerminalText(toggleShortcut)}.`
326
+ : "Plan mode shortcut cleared (no global shortcut).",
327
+ );
328
+ return result.kind === "stay" ? { kind: "to", screen: "settings" } : result;
329
+ },
330
+ "toggle-tool": async ({ ctx: actionCtx, state, itemId, selected, signal }) => {
331
+ const tool = itemId ? toolsByItemId.get(itemId) : undefined;
332
+ if (!tool || !activeToolNames.has(tool.name) || !canSelectToolInPlanMode(tool)) {
333
+ return { kind: "rejected" };
334
+ }
335
+ const names = explicitToolNames(tools, state.settings.defaultPlanTools);
336
+ const next = selected ? Array.from(new Set([...names, tool.name])) : names.filter((name) => name !== tool.name);
337
+ return savePatch(
338
+ actionCtx,
339
+ { defaultPlanTools: next },
340
+ signal,
341
+ `Default Plan policy: ${next.length === 0 ? "no optional tools" : `${next.length} allowed`}.`,
342
+ );
343
+ },
344
+ "reset-tools": async ({ ctx: actionCtx, state, signal }) => {
345
+ if (state.settings.defaultPlanTools === undefined) return { kind: "stay" };
346
+ return savePatch(
347
+ actionCtx,
348
+ { defaultPlanTools: null },
349
+ signal,
350
+ "Default Plan-mode tools: automatic safe built-ins.",
351
+ );
352
+ },
353
+ },
354
+ });
393
355
 
394
- return runMenu(ctx, menu, {
395
- getState: loadState,
396
- signal: options.signal,
397
- isCurrent: options.isCurrent,
398
- });
356
+ return runMenu(ctx, menu, {
357
+ getState: loadState,
358
+ signal: options.signal,
359
+ isCurrent: options.isCurrent,
360
+ });
399
361
 
400
- async function savePatch(
401
- actionCtx: ExtensionContext,
402
- patch: PlanModeSettingsPatch,
403
- signal: AbortSignal,
404
- successMessage: string,
405
- ) {
406
- if (signal.aborted || !options.isCurrent()) return { kind: "rejected" as const };
407
- try {
408
- const saved = await updateSettings(patch, {
409
- settingsPath: options.settingsPath,
410
- legacySettingsPath: options.legacySettingsPath,
411
- signal,
412
- });
413
- if (options.isCurrent()) options.onSaved(saved);
414
- if (signal.aborted || !options.isCurrent()) return { kind: "rejected" as const };
415
- actionCtx.ui.notify(successMessage, "info");
416
- return { kind: "stay" as const };
417
- } catch (error) {
418
- if (!signal.aborted && options.isCurrent()) {
419
- actionCtx.ui.notify(
420
- `Could not save Plan mode settings; the previous value remains: ${safeTerminalText(formatError(error))}`,
421
- "error",
422
- );
423
- }
424
- return { kind: "rejected" as const };
425
- }
426
- }
362
+ async function savePatch(
363
+ actionCtx: ExtensionContext,
364
+ patch: PlanModeSettingsPatch,
365
+ signal: AbortSignal,
366
+ successMessage: string,
367
+ ) {
368
+ if (signal.aborted || !options.isCurrent()) return { kind: "rejected" as const };
369
+ try {
370
+ const saved = await updateSettings(patch, {
371
+ settingsPath: options.settingsPath,
372
+ legacySettingsPath: options.legacySettingsPath,
373
+ signal,
374
+ });
375
+ if (options.isCurrent()) options.onSaved(saved);
376
+ if (signal.aborted || !options.isCurrent()) return { kind: "rejected" as const };
377
+ actionCtx.ui.notify(successMessage, "info");
378
+ return { kind: "stay" as const };
379
+ } catch (error) {
380
+ if (!signal.aborted && options.isCurrent()) {
381
+ actionCtx.ui.notify(
382
+ `Could not save Plan mode settings; the previous value remains: ${safeTerminalText(formatError(error))}`,
383
+ "error",
384
+ );
385
+ }
386
+ return { kind: "rejected" as const };
387
+ }
388
+ }
427
389
  }
428
390
 
429
391
  function settingsLines(settingsPath: string, notice: string | undefined) {
430
- return [
431
- `User settings · ${safeTerminalText(settingsPath)}`,
432
- "Plan defaults apply to the next workflow; reinjection and export choices apply to their next action.",
433
- ...(notice ? [safeTerminalText(notice)] : []),
434
- ];
392
+ return [
393
+ `User settings · ${safeTerminalText(settingsPath)}`,
394
+ "Plan defaults apply to the next workflow; reinjection and export choices apply to their next action.",
395
+ ...(notice ? [safeTerminalText(notice)] : []),
396
+ ];
435
397
  }
436
398
 
437
399
  function invalidScreen(settingsPath: string, state: SettingsMenuState) {
438
- return {
439
- kind: "detail" as const,
440
- title: "Plan Mode Settings · Read only",
441
- lines: [
442
- `Invalid settings file. Fix ${safeTerminalText(settingsPath)} before saving.`,
443
- safeTerminalText(state.reason ?? "The settings file is invalid."),
444
- ...(state.notice ? [safeTerminalText(state.notice)] : []),
445
- ],
446
- hint: "back" as const,
447
- };
400
+ return {
401
+ kind: "detail" as const,
402
+ title: "Plan Mode Settings · Read only",
403
+ lines: [
404
+ `Invalid settings file. Fix ${safeTerminalText(settingsPath)} before saving.`,
405
+ safeTerminalText(state.reason ?? "The settings file is invalid."),
406
+ ...(state.notice ? [safeTerminalText(state.notice)] : []),
407
+ ],
408
+ hint: "back" as const,
409
+ };
448
410
  }
449
411
 
450
412
  function retentionFromLabel(value: string | undefined) {
451
- return IMPLEMENTATION_PLAN_RETENTIONS.find((retention) => retentionLabel(retention) === value);
413
+ return IMPLEMENTATION_PLAN_RETENTIONS.find((retention) => retentionLabel(retention) === value);
452
414
  }
453
415
 
454
- function implementationModelValue(
455
- settings: PlanModeSettings,
456
- models: readonly AvailableImplementationModel[],
457
- ) {
458
- const configured = configuredImplementationModel(settings);
459
- if (!configured) return "same as plan";
460
- return findAvailableImplementationModel(models, configured)
461
- ? safeModelReference(configured)
462
- : `same as plan · ${safeModelReference(configured)} unavailable`;
416
+ function implementationModelValue(settings: PlanModeSettings, models: readonly AvailableImplementationModel[]) {
417
+ const configured = configuredImplementationModel(settings);
418
+ if (!configured) return "same as plan";
419
+ return findAvailableImplementationModel(models, configured)
420
+ ? safeModelReference(configured)
421
+ : `same as plan · ${safeModelReference(configured)} unavailable`;
463
422
  }
464
423
 
465
424
  function implementationModelItems(
466
- models: readonly AvailableImplementationModel[],
467
- itemIds: ReadonlyMap<AvailableImplementationModel, string>,
425
+ models: readonly AvailableImplementationModel[],
426
+ itemIds: ReadonlyMap<AvailableImplementationModel, string>,
468
427
  ) {
469
- return [
470
- {
471
- id: "same-as-plan",
472
- label: "Same as plan",
473
- description: "Use the planning session model.",
474
- },
475
- ...models.map((model) => {
476
- const reference = safeModelReference({ provider: model.provider, modelId: model.id });
477
- const name = safeModelMetadata(model.name, "");
478
- return {
479
- id: itemIds.get(model) as string,
480
- label: reference,
481
- ...(name ? { details: [`Model Name: ${name}`] } : {}),
482
- searchText: [reference, name].filter(Boolean).join(" "),
483
- };
484
- }),
485
- ];
428
+ return [
429
+ {
430
+ id: "same-as-plan",
431
+ label: "Same as plan",
432
+ description: "Use the planning session model.",
433
+ },
434
+ ...models.map((model) => {
435
+ const reference = safeModelReference({ provider: model.provider, modelId: model.id });
436
+ const name = safeModelMetadata(model.name, "");
437
+ return {
438
+ id: itemIds.get(model) as string,
439
+ label: reference,
440
+ ...(name ? { details: [`Model Name: ${name}`] } : {}),
441
+ searchText: [reference, name].filter(Boolean).join(" "),
442
+ };
443
+ }),
444
+ ];
486
445
  }
487
446
 
488
447
  function implementationModelItemId(
489
- configured: ImplementationModelOverride | undefined,
490
- models: readonly AvailableImplementationModel[],
491
- itemIds: ReadonlyMap<AvailableImplementationModel, string>,
448
+ configured: ImplementationModelOverride | undefined,
449
+ models: readonly AvailableImplementationModel[],
450
+ itemIds: ReadonlyMap<AvailableImplementationModel, string>,
492
451
  ) {
493
- const model = findAvailableImplementationModel(models, configured);
494
- return model ? itemIds.get(model) : "same-as-plan";
452
+ const model = findAvailableImplementationModel(models, configured);
453
+ return model ? itemIds.get(model) : "same-as-plan";
495
454
  }
496
455
 
497
456
  function safeModelReference(model: ImplementationModelOverride) {
498
- return `${safeModelMetadata(model.modelId, "unknown model")} [${safeModelMetadata(model.provider, "unknown provider")}]`;
457
+ return `${safeModelMetadata(model.modelId, "unknown model")} [${safeModelMetadata(model.provider, "unknown provider")}]`;
499
458
  }
500
459
 
501
460
  function safeModelMetadata(value: unknown, fallback: string) {
502
- if (typeof value !== "string") return fallback;
503
- const safe = sanitizeTerminalText(value).trim() || fallback;
504
- return [...safe].slice(0, 512).join("");
461
+ if (typeof value !== "string") return fallback;
462
+ const safe = sanitizeTerminalText(value).trim() || fallback;
463
+ return [...safe].slice(0, 512).join("");
505
464
  }
506
465
 
507
466
  function defaultToolsValue(configured: string[] | undefined) {
508
- if (configured === undefined) return "Automatic safe built-ins";
509
- if (configured.length === 0) return "No optional tools";
510
- return `${configured.length} selected`;
467
+ if (configured === undefined) return "Automatic safe built-ins";
468
+ if (configured.length === 0) return "No optional tools";
469
+ return `${configured.length} selected`;
511
470
  }
512
471
 
513
472
  function defaultToolItems(
514
- tools: readonly ToolInfo[],
515
- configured: string[] | undefined,
516
- activeToolNames: ReadonlySet<string>,
517
- toolItemIds: ReadonlyMap<string, string>,
473
+ tools: readonly ToolInfo[],
474
+ configured: string[] | undefined,
475
+ activeToolNames: ReadonlySet<string>,
476
+ toolItemIds: ReadonlyMap<string, string>,
518
477
  ) {
519
- const selected = new Set(explicitToolNames(tools, configured));
520
- const availableNames = new Set(tools.map((tool) => tool.name));
521
- const items = tools.map((tool) => {
522
- const active = activeToolNames.has(tool.name);
523
- const selectable = active && canSelectToolInPlanMode(tool);
524
- const policy = active
525
- ? toolPolicyLabel(tool)
526
- : selected.has(tool.name)
527
- ? "not active yet; retained for first-request resolution"
528
- : "not active in this Pi session";
529
- const description = tool.description ?? "No description available";
530
- return {
531
- id: toolItemIds.get(tool.name) as string,
532
- label: tool.name,
533
- description: `${policy} · ${description}`,
534
- searchText: `${policy} ${description}`,
535
- selected: selected.has(tool.name),
536
- disabled: !selectable,
537
- disabledReason: !active
538
- ? selected.has(tool.name)
539
- ? "Not active yet; retained and resolved before the first request"
540
- : "Not active in Pi; Plan mode will not activate it"
541
- : selectable
542
- ? undefined
543
- : "Blocked by Plan-mode policy",
544
- };
545
- });
546
- for (const [index, name] of (configured ?? []).entries()) {
547
- if (availableNames.has(name)) continue;
548
- const label = terminalToolName(name);
549
- items.push({
550
- id: `plan-settings-pending:${index}`,
551
- label,
552
- description: "pending registration · Retained and resolved before the first request",
553
- searchText: `${label} pending registration retained settings first request`,
554
- selected: true,
555
- disabled: true,
556
- disabledReason: "Not registered yet; reset defaults to remove retained names",
557
- });
558
- }
559
- return items;
478
+ const selected = new Set(explicitToolNames(tools, configured));
479
+ const availableNames = new Set(tools.map((tool) => tool.name));
480
+ const items = tools.map((tool) => {
481
+ const active = activeToolNames.has(tool.name);
482
+ const selectable = active && canSelectToolInPlanMode(tool);
483
+ const policy = active
484
+ ? toolPolicyLabel(tool)
485
+ : selected.has(tool.name)
486
+ ? "not active yet; retained for first-request resolution"
487
+ : "not active in this Pi session";
488
+ const description = tool.description ?? "No description available";
489
+ return {
490
+ id: toolItemIds.get(tool.name) as string,
491
+ label: tool.name,
492
+ description: `${policy} · ${description}`,
493
+ searchText: `${policy} ${description}`,
494
+ selected: selected.has(tool.name),
495
+ disabled: !selectable,
496
+ disabledReason: !active
497
+ ? selected.has(tool.name)
498
+ ? "Not active yet; retained and resolved before the first request"
499
+ : "Not active in Pi; Plan mode will not activate it"
500
+ : selectable
501
+ ? undefined
502
+ : "Blocked by Plan-mode policy",
503
+ };
504
+ });
505
+ for (const [index, name] of (configured ?? []).entries()) {
506
+ if (availableNames.has(name)) continue;
507
+ const label = terminalToolName(name);
508
+ items.push({
509
+ id: `plan-settings-pending:${index}`,
510
+ label,
511
+ description: "pending registration · Retained and resolved before the first request",
512
+ searchText: `${label} pending registration retained settings first request`,
513
+ selected: true,
514
+ disabled: true,
515
+ disabledReason: "Not registered yet; reset defaults to remove retained names",
516
+ });
517
+ }
518
+ return items;
560
519
  }
561
520
 
562
521
  function explicitToolNames(tools: readonly ToolInfo[], configured: string[] | undefined) {
563
- return configured === undefined
564
- ? defaultPlanModeToolNames([...tools], undefined)
565
- : [...configured];
522
+ return configured === undefined ? defaultPlanModeToolNames([...tools], undefined) : [...configured];
566
523
  }
567
524
 
568
525
  function terminalToolName(value: string) {
569
- const safe = safeTerminalText(value) || "(unnamed tool)";
570
- return safe.length > 120 ? `${safe.slice(0, 119)}…` : safe;
526
+ const safe = safeTerminalText(value) || "(unnamed tool)";
527
+ return safe.length > 120 ? `${safe.slice(0, 119)}…` : safe;
571
528
  }
572
529
 
573
530
  function safeTerminalText(value: string) {
574
- return [...value]
575
- .map((character) => {
576
- const codePoint = character.codePointAt(0) ?? 0;
577
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
578
- })
579
- .join("")
580
- .trim();
531
+ return [...value]
532
+ .map((character) => {
533
+ const codePoint = character.codePointAt(0) ?? 0;
534
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
535
+ })
536
+ .join("")
537
+ .trim();
581
538
  }
582
539
 
583
540
  function formatError(error: unknown) {
584
- return error instanceof Error ? error.message : String(error);
541
+ return error instanceof Error ? error.message : String(error);
585
542
  }