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