@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
package/src/settings.ts CHANGED
@@ -4,484 +4,505 @@ import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
6
  import type { KeyId } from "@earendil-works/pi-tui";
7
+ import { type ImplementationModelOverride, isPendingImplementationModelIdentifier } from "./implementation-models.js";
7
8
  import type { SafeSubcommands } from "./tool-policy.js";
8
9
 
9
10
  export const PLAN_MODE_SETTINGS_FILE = "pi-plan-mode.json";
10
11
  const LEGACY_PLAN_MODE_SETTINGS_FILE = "plan-mode.json";
11
12
  const MAX_SETTINGS_BYTES = 64 * 1024;
12
13
  export const PLAN_MODE_THINKING_LEVELS = [
13
- "inherit",
14
- "off",
15
- "minimal",
16
- "low",
17
- "medium",
18
- "high",
19
- "xhigh",
20
- "max",
21
- ] as const;
22
- export const IMPLEMENTATION_PLAN_RETENTIONS = [
23
- "clear-on-start",
24
- "clear-after-first-run",
25
- "keep",
14
+ "inherit",
15
+ "off",
16
+ "minimal",
17
+ "low",
18
+ "medium",
19
+ "high",
20
+ "xhigh",
21
+ "max",
26
22
  ] as const;
23
+ export const IMPLEMENTATION_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
24
+ export const IMPLEMENTATION_PLAN_RETENTIONS = ["clear-on-start", "clear-after-first-run", "keep"] as const;
27
25
  export const DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
28
26
  const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
29
27
  const BASE_KEYS = new Set([
30
- ..."abcdefghijklmnopqrstuvwxyz0123456789",
31
- "`",
32
- "-",
33
- "=",
34
- "[",
35
- "]",
36
- "\\",
37
- ";",
38
- "'",
39
- ",",
40
- ".",
41
- "/",
42
- "!",
43
- "@",
44
- "#",
45
- "$",
46
- "%",
47
- "^",
48
- "&",
49
- "*",
50
- "(",
51
- ")",
52
- "_",
53
- "+",
54
- "|",
55
- "~",
56
- "{",
57
- "}",
58
- ":",
59
- "<",
60
- ">",
61
- "?",
62
- "escape",
63
- "esc",
64
- "enter",
65
- "return",
66
- "tab",
67
- "space",
68
- "backspace",
69
- "delete",
70
- "insert",
71
- "clear",
72
- "home",
73
- "end",
74
- "pageup",
75
- "pagedown",
76
- "up",
77
- "down",
78
- "left",
79
- "right",
80
- ...Array.from({ length: 12 }, (_unused, index) => `f${index + 1}`),
28
+ ..."abcdefghijklmnopqrstuvwxyz0123456789",
29
+ "`",
30
+ "-",
31
+ "=",
32
+ "[",
33
+ "]",
34
+ "\\",
35
+ ";",
36
+ "'",
37
+ ",",
38
+ ".",
39
+ "/",
40
+ "!",
41
+ "@",
42
+ "#",
43
+ "$",
44
+ "%",
45
+ "^",
46
+ "&",
47
+ "*",
48
+ "(",
49
+ ")",
50
+ "_",
51
+ "+",
52
+ "|",
53
+ "~",
54
+ "{",
55
+ "}",
56
+ ":",
57
+ "<",
58
+ ">",
59
+ "?",
60
+ "escape",
61
+ "esc",
62
+ "enter",
63
+ "return",
64
+ "tab",
65
+ "space",
66
+ "backspace",
67
+ "delete",
68
+ "insert",
69
+ "clear",
70
+ "home",
71
+ "end",
72
+ "pageup",
73
+ "pagedown",
74
+ "up",
75
+ "down",
76
+ "left",
77
+ "right",
78
+ ...Array.from({ length: 12 }, (_unused, index) => `f${index + 1}`),
81
79
  ]);
82
80
  const MAX_PLAN_EXPORT_PATH_LENGTH = 4096;
83
81
 
84
82
  export type PlanModeThinkingLevel = (typeof PLAN_MODE_THINKING_LEVELS)[number];
85
83
  export type ImplementationPlanRetention = (typeof IMPLEMENTATION_PLAN_RETENTIONS)[number];
86
- export type PlanModeFixedThinkingLevel = Exclude<PlanModeThinkingLevel, "inherit">;
84
+ export type PlanModeFixedThinkingLevel = (typeof IMPLEMENTATION_THINKING_LEVELS)[number];
87
85
  export interface PlanModeSettings {
88
- thinkingLevel: PlanModeThinkingLevel;
89
- defaultPlanTools?: string[];
90
- implementationPlanRetention?: ImplementationPlanRetention;
91
- defaultPlanExportPath?: string;
92
- safeSubcommands?: SafeSubcommands;
93
- toggleShortcut?: KeyId;
86
+ thinkingLevel: PlanModeThinkingLevel;
87
+ defaultPlanTools?: string[];
88
+ implementationPlanRetention?: ImplementationPlanRetention;
89
+ defaultImplementationModel?: ImplementationModelOverride;
90
+ defaultImplementationThinkingLevel?: PlanModeFixedThinkingLevel;
91
+ defaultPlanExportPath?: string;
92
+ safeSubcommands?: SafeSubcommands;
93
+ toggleShortcut?: KeyId;
94
94
  }
95
95
  export interface PlanModeSettingsPatch {
96
- thinkingLevel?: PlanModeThinkingLevel;
97
- defaultPlanTools?: readonly string[] | null;
98
- implementationPlanRetention?: ImplementationPlanRetention;
99
- defaultPlanExportPath?: string | null;
100
- toggleShortcut?: KeyId | null;
96
+ thinkingLevel?: PlanModeThinkingLevel;
97
+ defaultPlanTools?: readonly string[] | null;
98
+ implementationPlanRetention?: ImplementationPlanRetention;
99
+ defaultImplementationModel?: ImplementationModelOverride | null;
100
+ defaultImplementationThinkingLevel?: PlanModeFixedThinkingLevel | null;
101
+ defaultPlanExportPath?: string | null;
102
+ toggleShortcut?: KeyId | null;
101
103
  }
102
104
  export interface UpdatePlanModeSettingsOptions {
103
- settingsPath?: string;
104
- legacySettingsPath?: string;
105
- signal?: AbortSignal;
106
- beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
105
+ settingsPath?: string;
106
+ legacySettingsPath?: string;
107
+ signal?: AbortSignal;
108
+ beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
107
109
  }
108
110
  export type PlanModeSettingsLoadResult =
109
- | { kind: "missing"; notice?: string }
110
- | { kind: "invalid"; reason: string; notice?: string }
111
- | { kind: "loaded"; settings: PlanModeSettings; notice?: string };
111
+ | { kind: "missing"; notice?: string }
112
+ | { kind: "invalid"; reason: string; notice?: string }
113
+ | { kind: "loaded"; settings: PlanModeSettings; notice?: string };
112
114
 
113
115
  type SettingsDocument = Record<string, unknown>;
114
116
  type SettingsSnapshot = {
115
- result: PlanModeSettingsLoadResult;
116
- document?: SettingsDocument;
117
+ result: PlanModeSettingsLoadResult;
118
+ document?: SettingsDocument;
117
119
  };
118
120
 
119
121
  const mutationQueues = new Map<string, Promise<void>>();
120
122
 
121
123
  export function planModeSettingsPath() {
122
- return join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);
124
+ return join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);
123
125
  }
124
126
 
125
127
  function legacyPlanModeSettingsPath() {
126
- return join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);
128
+ return join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);
127
129
  }
128
130
 
129
131
  export function normalizePlanModeSettings(value: unknown): PlanModeSettings | undefined {
130
- if (!isSettingsDocument(value)) return undefined;
131
- const thinkingLevel = Object.hasOwn(value, "thinkingLevel")
132
- ? Reflect.get(value, "thinkingLevel")
133
- : "inherit";
134
- if (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel as PlanModeThinkingLevel)) {
135
- return undefined;
136
- }
137
- const settings: PlanModeSettings = {
138
- thinkingLevel: thinkingLevel as PlanModeThinkingLevel,
139
- };
140
- if (Object.hasOwn(value, "defaultPlanTools")) {
141
- const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
142
- if (!defaultPlanTools) return undefined;
143
- settings.defaultPlanTools = defaultPlanTools;
144
- }
145
- if (Object.hasOwn(value, "implementationPlanRetention")) {
146
- const implementationPlanRetention = Reflect.get(value, "implementationPlanRetention");
147
- if (
148
- !IMPLEMENTATION_PLAN_RETENTIONS.includes(
149
- implementationPlanRetention as ImplementationPlanRetention,
150
- )
151
- ) {
152
- return undefined;
153
- }
154
- settings.implementationPlanRetention =
155
- implementationPlanRetention as ImplementationPlanRetention;
156
- }
157
- if (Object.hasOwn(value, "defaultPlanExportPath")) {
158
- const defaultPlanExportPath = normalizePlanExportPath(
159
- Reflect.get(value, "defaultPlanExportPath"),
160
- );
161
- if (!defaultPlanExportPath) return undefined;
162
- settings.defaultPlanExportPath = defaultPlanExportPath;
163
- }
164
- if (Object.hasOwn(value, "toggleShortcut")) {
165
- const toggleShortcut = normalizeKeyId(Reflect.get(value, "toggleShortcut"));
166
- if (!toggleShortcut) return undefined;
167
- settings.toggleShortcut = toggleShortcut;
168
- }
169
- if (Object.hasOwn(value, "safeSubcommands")) {
170
- const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, "safeSubcommands"));
171
- if (!safeSubcommands) return undefined;
172
- settings.safeSubcommands = safeSubcommands;
173
- }
174
- return settings;
132
+ if (!isSettingsDocument(value)) return undefined;
133
+ const thinkingLevel = Object.hasOwn(value, "thinkingLevel") ? Reflect.get(value, "thinkingLevel") : "inherit";
134
+ if (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel as PlanModeThinkingLevel)) {
135
+ return undefined;
136
+ }
137
+ const settings: PlanModeSettings = {
138
+ thinkingLevel: thinkingLevel as PlanModeThinkingLevel,
139
+ };
140
+ if (Object.hasOwn(value, "defaultPlanTools")) {
141
+ const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
142
+ if (!defaultPlanTools) return undefined;
143
+ settings.defaultPlanTools = defaultPlanTools;
144
+ }
145
+ if (Object.hasOwn(value, "implementationPlanRetention")) {
146
+ const implementationPlanRetention = Reflect.get(value, "implementationPlanRetention");
147
+ if (!IMPLEMENTATION_PLAN_RETENTIONS.includes(implementationPlanRetention as ImplementationPlanRetention)) {
148
+ return undefined;
149
+ }
150
+ settings.implementationPlanRetention = implementationPlanRetention as ImplementationPlanRetention;
151
+ }
152
+ if (Object.hasOwn(value, "defaultImplementationModel")) {
153
+ const defaultImplementationModel = normalizeImplementationModel(Reflect.get(value, "defaultImplementationModel"));
154
+ if (!defaultImplementationModel) return undefined;
155
+ settings.defaultImplementationModel = defaultImplementationModel;
156
+ }
157
+ if (Object.hasOwn(value, "defaultImplementationThinkingLevel")) {
158
+ const defaultImplementationThinkingLevel = Reflect.get(value, "defaultImplementationThinkingLevel");
159
+ if (!IMPLEMENTATION_THINKING_LEVELS.includes(defaultImplementationThinkingLevel as PlanModeFixedThinkingLevel)) {
160
+ return undefined;
161
+ }
162
+ settings.defaultImplementationThinkingLevel = defaultImplementationThinkingLevel as PlanModeFixedThinkingLevel;
163
+ }
164
+ if (Object.hasOwn(value, "defaultPlanExportPath")) {
165
+ const defaultPlanExportPath = normalizePlanExportPath(Reflect.get(value, "defaultPlanExportPath"));
166
+ if (!defaultPlanExportPath) return undefined;
167
+ settings.defaultPlanExportPath = defaultPlanExportPath;
168
+ }
169
+ if (Object.hasOwn(value, "toggleShortcut")) {
170
+ const toggleShortcut = normalizeKeyId(Reflect.get(value, "toggleShortcut"));
171
+ if (!toggleShortcut) return undefined;
172
+ settings.toggleShortcut = toggleShortcut;
173
+ }
174
+ if (Object.hasOwn(value, "safeSubcommands")) {
175
+ const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, "safeSubcommands"));
176
+ if (!safeSubcommands) return undefined;
177
+ settings.safeSubcommands = safeSubcommands;
178
+ }
179
+ return settings;
180
+ }
181
+
182
+ function normalizeImplementationModel(value: unknown): ImplementationModelOverride | undefined {
183
+ if (!isSettingsDocument(value) || Object.keys(value).some((key) => key !== "provider" && key !== "modelId")) {
184
+ return undefined;
185
+ }
186
+ const provider = typeof value.provider === "string" ? value.provider.trim() : value.provider;
187
+ const modelId = typeof value.modelId === "string" ? value.modelId.trim() : value.modelId;
188
+ if (!isPendingImplementationModelIdentifier(provider) || !isPendingImplementationModelIdentifier(modelId)) {
189
+ return undefined;
190
+ }
191
+ return { provider, modelId };
175
192
  }
176
193
 
177
194
  function normalizeToolNames(value: unknown) {
178
- if (
179
- !Array.isArray(value) ||
180
- !value.every((item): item is string => typeof item === "string" && item.trim().length > 0)
181
- ) {
182
- return undefined;
183
- }
184
- return Array.from(new Set(value));
195
+ if (
196
+ !Array.isArray(value) ||
197
+ !value.every((item): item is string => typeof item === "string" && item.trim().length > 0)
198
+ ) {
199
+ return undefined;
200
+ }
201
+ return Array.from(new Set(value));
185
202
  }
186
203
 
187
204
  function normalizePlanExportPath(value: unknown) {
188
- if (typeof value !== "string") return undefined;
189
- const normalized = value.trim();
190
- if (
191
- !normalized ||
192
- normalized.length > MAX_PLAN_EXPORT_PATH_LENGTH ||
193
- !/[^@\s]/u.test(normalized) ||
194
- [...normalized].some((character) => {
195
- const codePoint = character.codePointAt(0) ?? 0;
196
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
197
- })
198
- ) {
199
- return undefined;
200
- }
201
- return normalized;
205
+ if (typeof value !== "string") return undefined;
206
+ const normalized = value.trim();
207
+ if (
208
+ !normalized ||
209
+ normalized.length > MAX_PLAN_EXPORT_PATH_LENGTH ||
210
+ !/[^@\s]/u.test(normalized) ||
211
+ [...normalized].some((character) => {
212
+ const codePoint = character.codePointAt(0) ?? 0;
213
+ return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
214
+ })
215
+ ) {
216
+ return undefined;
217
+ }
218
+ return normalized;
202
219
  }
203
220
 
204
221
  export function normalizeKeyId(value: unknown): KeyId | undefined {
205
- if (typeof value !== "string") return undefined;
206
- const normalized = value.trim().toLowerCase();
207
- const base = [...BASE_KEYS]
208
- .sort((left, right) => right.length - left.length)
209
- .find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));
210
- if (!base) return undefined;
211
- const prefix = normalized.slice(0, normalized.length - base.length);
212
- if (!prefix) return base as KeyId;
213
- if (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith("+")) return undefined;
214
- const modifiers = prefix.slice(0, -1).split("+");
215
- if (
216
- modifiers.length === 0 ||
217
- modifiers.some((modifier) => !MODIFIERS.has(modifier)) ||
218
- new Set(modifiers).size !== modifiers.length
219
- ) {
220
- return undefined;
221
- }
222
- return normalized as KeyId;
222
+ if (typeof value !== "string") return undefined;
223
+ const normalized = value.trim().toLowerCase();
224
+ const base = [...BASE_KEYS]
225
+ .sort((left, right) => right.length - left.length)
226
+ .find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));
227
+ if (!base) return undefined;
228
+ const prefix = normalized.slice(0, normalized.length - base.length);
229
+ if (!prefix) return base as KeyId;
230
+ if (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith("+")) return undefined;
231
+ const modifiers = prefix.slice(0, -1).split("+");
232
+ if (
233
+ modifiers.length === 0 ||
234
+ modifiers.some((modifier) => !MODIFIERS.has(modifier)) ||
235
+ new Set(modifiers).size !== modifiers.length
236
+ ) {
237
+ return undefined;
238
+ }
239
+ return normalized as KeyId;
223
240
  }
224
241
 
225
242
  function normalizeSafeSubcommands(value: unknown): SafeSubcommands | undefined {
226
- if (!isSettingsDocument(value)) return undefined;
227
- const entries: Array<[string, string[]]> = [];
228
- for (const [command, subcommands] of Object.entries(value)) {
229
- const normalizedCommand = command.trim();
230
- if (
231
- !normalizedCommand ||
232
- !Array.isArray(subcommands) ||
233
- !subcommands.every(
234
- (item): item is string => typeof item === "string" && item.trim().length > 0,
235
- )
236
- ) {
237
- return undefined;
238
- }
239
- const normalizedSubcommands = Array.from(
240
- new Set(subcommands.map((subcommand) => subcommand.trim())),
241
- );
242
- const existing = entries.find(([existingCommand]) => existingCommand === normalizedCommand);
243
- if (existing) existing[1] = Array.from(new Set([...existing[1], ...normalizedSubcommands]));
244
- else entries.push([normalizedCommand, normalizedSubcommands]);
245
- }
246
- return Object.fromEntries(entries);
243
+ if (!isSettingsDocument(value)) return undefined;
244
+ const entries: [string, string[]][] = [];
245
+ for (const [command, subcommands] of Object.entries(value)) {
246
+ const normalizedCommand = command.trim();
247
+ if (
248
+ !normalizedCommand ||
249
+ !Array.isArray(subcommands) ||
250
+ !subcommands.every((item): item is string => typeof item === "string" && item.trim().length > 0)
251
+ ) {
252
+ return undefined;
253
+ }
254
+ const normalizedSubcommands = Array.from(new Set(subcommands.map((subcommand) => subcommand.trim())));
255
+ const existing = entries.find(([existingCommand]) => existingCommand === normalizedCommand);
256
+ if (existing) existing[1] = Array.from(new Set([...existing[1], ...normalizedSubcommands]));
257
+ else entries.push([normalizedCommand, normalizedSubcommands]);
258
+ }
259
+ return Object.fromEntries(entries);
247
260
  }
248
261
 
249
- export async function readPlanModeSettings(
250
- settingsPath?: string,
251
- ): Promise<PlanModeSettingsLoadResult> {
252
- if (settingsPath) {
253
- await awaitPlanModeSettingsWrites(settingsPath);
254
- return (await readSettingsSnapshot(settingsPath)).result;
255
- }
256
- const canonicalPath = planModeSettingsPath();
257
- await awaitPlanModeSettingsWrites(canonicalPath);
258
- const canonical = await readSettingsSnapshot(canonicalPath);
259
- const legacyPath = legacyPlanModeSettingsPath();
260
- if (canonical.result.kind !== "missing") {
261
- return (await pathExists(legacyPath))
262
- ? {
263
- ...canonical.result,
264
- notice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`,
265
- }
266
- : canonical.result;
267
- }
268
-
269
- const legacy = await readSettingsSnapshot(legacyPath);
270
- const raced = await readSettingsSnapshot(canonicalPath);
271
- if (raced.result.kind !== "missing") return raced.result;
272
- return legacy.result.kind === "loaded"
273
- ? {
274
- ...legacy.result,
275
- notice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`,
276
- }
277
- : legacy.result;
262
+ export async function readPlanModeSettings(settingsPath?: string): Promise<PlanModeSettingsLoadResult> {
263
+ if (settingsPath) {
264
+ await awaitPlanModeSettingsWrites(settingsPath);
265
+ return (await readSettingsSnapshot(settingsPath)).result;
266
+ }
267
+ const canonicalPath = planModeSettingsPath();
268
+ await awaitPlanModeSettingsWrites(canonicalPath);
269
+ const canonical = await readSettingsSnapshot(canonicalPath);
270
+ const legacyPath = legacyPlanModeSettingsPath();
271
+ if (canonical.result.kind !== "missing") {
272
+ return (await pathExists(legacyPath))
273
+ ? {
274
+ ...canonical.result,
275
+ notice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`,
276
+ }
277
+ : canonical.result;
278
+ }
279
+
280
+ const legacy = await readSettingsSnapshot(legacyPath);
281
+ const raced = await readSettingsSnapshot(canonicalPath);
282
+ if (raced.result.kind !== "missing") return raced.result;
283
+ return legacy.result.kind === "loaded"
284
+ ? {
285
+ ...legacy.result,
286
+ notice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`,
287
+ }
288
+ : legacy.result;
278
289
  }
279
290
 
280
291
  export function updatePlanModeSettings(
281
- patch: PlanModeSettingsPatch,
282
- options: UpdatePlanModeSettingsOptions = {},
292
+ patch: PlanModeSettingsPatch,
293
+ options: UpdatePlanModeSettingsOptions = {},
283
294
  ): Promise<PlanModeSettings> {
284
- const settingsPath = options.settingsPath ?? planModeSettingsPath();
285
- const legacySettingsPath =
286
- options.legacySettingsPath ?? (options.settingsPath ? undefined : legacyPlanModeSettingsPath());
287
- return enqueueMutation(settingsPath, async () => {
288
- options.signal?.throwIfAborted();
289
- const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
290
- const updated: SettingsDocument = { ...current };
291
- if (patch.thinkingLevel !== undefined) updated.thinkingLevel = patch.thinkingLevel;
292
- if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
293
- else if (patch.defaultPlanTools !== undefined) {
294
- updated.defaultPlanTools = [...patch.defaultPlanTools];
295
- }
296
- if (patch.implementationPlanRetention !== undefined) {
297
- updated.implementationPlanRetention = patch.implementationPlanRetention;
298
- }
299
- if (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;
300
- else if (patch.defaultPlanExportPath !== undefined) {
301
- updated.defaultPlanExportPath = patch.defaultPlanExportPath;
302
- }
303
- if (patch.toggleShortcut === null) delete updated.toggleShortcut;
304
- else if (patch.toggleShortcut !== undefined) {
305
- updated.toggleShortcut = patch.toggleShortcut;
306
- }
307
- const settings = normalizePlanModeSettings(updated);
308
- if (!settings) throw invalidSettingsError(settingsPath, "invalid settings shape");
309
- await publishSettings(settingsPath, updated, options.signal, options.beforeRename);
310
- return settings;
311
- });
295
+ const settingsPath = options.settingsPath ?? planModeSettingsPath();
296
+ const legacySettingsPath =
297
+ options.legacySettingsPath ?? (options.settingsPath ? undefined : legacyPlanModeSettingsPath());
298
+ return enqueueMutation(settingsPath, async () => {
299
+ options.signal?.throwIfAborted();
300
+ const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
301
+ const updated: SettingsDocument = { ...current };
302
+ if (patch.thinkingLevel !== undefined) updated.thinkingLevel = patch.thinkingLevel;
303
+ if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
304
+ else if (patch.defaultPlanTools !== undefined) {
305
+ updated.defaultPlanTools = [...patch.defaultPlanTools];
306
+ }
307
+ if (patch.implementationPlanRetention !== undefined) {
308
+ updated.implementationPlanRetention = patch.implementationPlanRetention;
309
+ }
310
+ if (patch.defaultImplementationModel === null) delete updated.defaultImplementationModel;
311
+ else if (patch.defaultImplementationModel !== undefined) {
312
+ const model = normalizeImplementationModel(patch.defaultImplementationModel);
313
+ if (!model) throw invalidSettingsError(settingsPath, "invalid implementation model");
314
+ updated.defaultImplementationModel = model;
315
+ }
316
+ if (patch.defaultImplementationThinkingLevel === null) {
317
+ delete updated.defaultImplementationThinkingLevel;
318
+ } else if (patch.defaultImplementationThinkingLevel !== undefined) {
319
+ updated.defaultImplementationThinkingLevel = patch.defaultImplementationThinkingLevel;
320
+ }
321
+ if (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;
322
+ else if (patch.defaultPlanExportPath !== undefined) {
323
+ updated.defaultPlanExportPath = patch.defaultPlanExportPath;
324
+ }
325
+ if (patch.toggleShortcut === null) delete updated.toggleShortcut;
326
+ else if (patch.toggleShortcut !== undefined) {
327
+ updated.toggleShortcut = patch.toggleShortcut;
328
+ }
329
+ const settings = normalizePlanModeSettings(updated);
330
+ if (!settings) throw invalidSettingsError(settingsPath, "invalid settings shape");
331
+ await publishSettings(settingsPath, updated, options.signal, options.beforeRename);
332
+ return settings;
333
+ });
312
334
  }
313
335
 
314
- export async function awaitPlanModeSettingsWrites(
315
- settingsPath = planModeSettingsPath(),
316
- ): Promise<void> {
317
- await mutationQueues.get(settingsPath);
336
+ export async function awaitPlanModeSettingsWrites(settingsPath = planModeSettingsPath()): Promise<void> {
337
+ await mutationQueues.get(settingsPath);
318
338
  }
319
339
 
320
340
  function enqueueMutation<T>(settingsPath: string, mutation: () => Promise<T>): Promise<T> {
321
- const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();
322
- const result = previous.then(mutation, mutation);
323
- const settled = result.then(
324
- () => undefined,
325
- () => undefined,
326
- );
327
- mutationQueues.set(settingsPath, settled);
328
- void settled.finally(() => {
329
- if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);
330
- });
331
- return result;
341
+ const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();
342
+ const result = previous.then(mutation, mutation);
343
+ const settled = result.then(
344
+ () => undefined,
345
+ () => undefined,
346
+ );
347
+ mutationQueues.set(settingsPath, settled);
348
+ void settled.finally(() => {
349
+ if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);
350
+ });
351
+ return result;
332
352
  }
333
353
 
334
354
  async function readSettingsDocumentForUpdate(
335
- settingsPath: string,
336
- legacySettingsPath: string | undefined,
355
+ settingsPath: string,
356
+ legacySettingsPath: string | undefined,
337
357
  ): Promise<SettingsDocument> {
338
- const canonical = await readSettingsSnapshot(settingsPath);
339
- if (canonical.result.kind === "loaded") return canonical.document ?? {};
340
- if (canonical.result.kind === "invalid") {
341
- throw invalidSettingsError(settingsPath, canonical.result.reason);
342
- }
343
- if (!legacySettingsPath) return {};
344
-
345
- const legacy = await readSettingsSnapshot(legacySettingsPath);
346
- const raced = await readSettingsSnapshot(settingsPath);
347
- if (raced.result.kind === "loaded") return raced.document ?? {};
348
- if (raced.result.kind === "invalid") {
349
- throw invalidSettingsError(settingsPath, raced.result.reason);
350
- }
351
- if (legacy.result.kind === "invalid") {
352
- throw invalidSettingsError(legacySettingsPath, legacy.result.reason);
353
- }
354
- return legacy.document ?? {};
358
+ const canonical = await readSettingsSnapshot(settingsPath);
359
+ if (canonical.result.kind === "loaded") return canonical.document ?? {};
360
+ if (canonical.result.kind === "invalid") {
361
+ throw invalidSettingsError(settingsPath, canonical.result.reason);
362
+ }
363
+ if (!legacySettingsPath) return {};
364
+
365
+ const legacy = await readSettingsSnapshot(legacySettingsPath);
366
+ const raced = await readSettingsSnapshot(settingsPath);
367
+ if (raced.result.kind === "loaded") return raced.document ?? {};
368
+ if (raced.result.kind === "invalid") {
369
+ throw invalidSettingsError(settingsPath, raced.result.reason);
370
+ }
371
+ if (legacy.result.kind === "invalid") {
372
+ throw invalidSettingsError(legacySettingsPath, legacy.result.reason);
373
+ }
374
+ return legacy.document ?? {};
355
375
  }
356
376
 
357
377
  async function readSettingsSnapshot(settingsPath: string): Promise<SettingsSnapshot> {
358
- let contents: string;
359
- try {
360
- contents = await readSettingsContents(settingsPath);
361
- } catch (error: unknown) {
362
- if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
363
- return { result: { kind: "invalid", reason: safeReadError(error) } };
364
- }
365
- let parsed: unknown;
366
- try {
367
- parsed = JSON.parse(contents) as unknown;
368
- } catch {
369
- return { result: { kind: "invalid", reason: "invalid JSON" } };
370
- }
371
- const settings = normalizePlanModeSettings(parsed);
372
- if (!settings || !isSettingsDocument(parsed)) {
373
- return { result: { kind: "invalid", reason: "invalid settings shape" } };
374
- }
375
- return { document: parsed, result: { kind: "loaded", settings } };
378
+ let contents: string;
379
+ try {
380
+ contents = await readSettingsContents(settingsPath);
381
+ } catch (error: unknown) {
382
+ if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
383
+ return { result: { kind: "invalid", reason: safeReadError(error) } };
384
+ }
385
+ let parsed: unknown;
386
+ try {
387
+ parsed = JSON.parse(contents) as unknown;
388
+ } catch {
389
+ return { result: { kind: "invalid", reason: "invalid JSON" } };
390
+ }
391
+ const settings = normalizePlanModeSettings(parsed);
392
+ if (!settings || !isSettingsDocument(parsed)) {
393
+ return { result: { kind: "invalid", reason: "invalid settings shape" } };
394
+ }
395
+ return { document: parsed, result: { kind: "loaded", settings } };
376
396
  }
377
397
 
378
398
  async function readSettingsContents(settingsPath: string): Promise<string> {
379
- const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);
380
- const handle = await open(settingsPath, flags);
381
- try {
382
- const stats = await handle.stat();
383
- if (!stats.isFile()) throw new Error("settings path is not a regular file");
384
- if (stats.size > MAX_SETTINGS_BYTES) {
385
- throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
386
- }
387
- const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
388
- let offset = 0;
389
- while (offset < buffer.byteLength) {
390
- const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);
391
- if (bytesRead === 0) break;
392
- offset += bytesRead;
393
- }
394
- if (offset > MAX_SETTINGS_BYTES) {
395
- throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
396
- }
397
- try {
398
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
399
- buffer.subarray(0, offset),
400
- );
401
- } catch {
402
- throw new Error("settings file is not valid UTF-8");
403
- }
404
- } finally {
405
- await handle.close();
406
- }
399
+ const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);
400
+ const handle = await open(settingsPath, flags);
401
+ try {
402
+ const stats = await handle.stat();
403
+ if (!stats.isFile()) throw new Error("settings path is not a regular file");
404
+ if (stats.size > MAX_SETTINGS_BYTES) {
405
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
406
+ }
407
+ const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
408
+ let offset = 0;
409
+ while (offset < buffer.byteLength) {
410
+ const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);
411
+ if (bytesRead === 0) break;
412
+ offset += bytesRead;
413
+ }
414
+ if (offset > MAX_SETTINGS_BYTES) {
415
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
416
+ }
417
+ try {
418
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));
419
+ } catch {
420
+ throw new Error("settings file is not valid UTF-8");
421
+ }
422
+ } finally {
423
+ await handle.close();
424
+ }
407
425
  }
408
426
 
409
427
  async function publishSettings(
410
- settingsPath: string,
411
- document: SettingsDocument,
412
- signal?: AbortSignal,
413
- beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>,
428
+ settingsPath: string,
429
+ document: SettingsDocument,
430
+ signal?: AbortSignal,
431
+ beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>,
414
432
  ): Promise<void> {
415
- signal?.throwIfAborted();
416
- const contents = `${JSON.stringify(document, null, 2)}\n`;
417
- if (Buffer.byteLength(contents, "utf8") > MAX_SETTINGS_BYTES) {
418
- throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);
419
- }
420
- const directory = dirname(settingsPath);
421
- await mkdir(directory, { recursive: true });
422
- signal?.throwIfAborted();
423
- const temporaryPath = join(
424
- directory,
425
- `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`,
426
- );
427
- try {
428
- await writeFile(temporaryPath, contents, {
429
- encoding: "utf8",
430
- flag: "wx",
431
- mode: 0o600,
432
- signal,
433
- });
434
- await beforeRename?.(temporaryPath, settingsPath);
435
- signal?.throwIfAborted();
436
- await rename(temporaryPath, settingsPath);
437
- } finally {
438
- await rm(temporaryPath, { force: true }).catch(() => undefined);
439
- }
433
+ signal?.throwIfAborted();
434
+ const contents = `${JSON.stringify(document, null, 2)}\n`;
435
+ if (Buffer.byteLength(contents, "utf8") > MAX_SETTINGS_BYTES) {
436
+ throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);
437
+ }
438
+ const directory = dirname(settingsPath);
439
+ await mkdir(directory, { recursive: true });
440
+ signal?.throwIfAborted();
441
+ const temporaryPath = join(directory, `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`);
442
+ try {
443
+ await writeFile(temporaryPath, contents, {
444
+ encoding: "utf8",
445
+ flag: "wx",
446
+ mode: 0o600,
447
+ signal,
448
+ });
449
+ await beforeRename?.(temporaryPath, settingsPath);
450
+ signal?.throwIfAborted();
451
+ await rename(temporaryPath, settingsPath);
452
+ } finally {
453
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
454
+ }
440
455
  }
441
456
 
442
457
  function isSettingsDocument(value: unknown): value is SettingsDocument {
443
- return typeof value === "object" && value !== null && !Array.isArray(value);
458
+ return typeof value === "object" && value !== null && !Array.isArray(value);
444
459
  }
445
460
 
446
461
  async function pathExists(path: string) {
447
- try {
448
- const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
449
- await handle.close();
450
- return true;
451
- } catch (error: unknown) {
452
- return !(isNodeError(error) && error.code === "ENOENT");
453
- }
462
+ try {
463
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
464
+ await handle.close();
465
+ return true;
466
+ } catch (error: unknown) {
467
+ return !(isNodeError(error) && error.code === "ENOENT");
468
+ }
454
469
  }
455
470
 
456
471
  function invalidSettingsError(settingsPath: string, reason: string) {
457
- return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);
472
+ return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);
458
473
  }
459
474
 
460
475
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
461
- return error instanceof Error && "code" in error;
476
+ return error instanceof Error && "code" in error;
462
477
  }
463
478
 
464
479
  function safeReadError(error: unknown) {
465
- if (isNodeError(error) && error.code === "ELOOP") return "settings path is not a regular file";
466
- return error instanceof Error ? error.message : String(error);
480
+ if (isNodeError(error) && error.code === "ELOOP") return "settings path is not a regular file";
481
+ return error instanceof Error ? error.message : String(error);
467
482
  }
468
483
 
469
- export function configuredThinkingLevel(
470
- settings: PlanModeSettings,
471
- ): PlanModeFixedThinkingLevel | undefined {
472
- return settings.thinkingLevel === "inherit" ? undefined : settings.thinkingLevel;
484
+ export function configuredThinkingLevel(settings: PlanModeSettings): PlanModeFixedThinkingLevel | undefined {
485
+ return settings.thinkingLevel === "inherit" ? undefined : settings.thinkingLevel;
486
+ }
487
+
488
+ export function configuredImplementationPlanRetention(settings: PlanModeSettings): ImplementationPlanRetention {
489
+ return settings.implementationPlanRetention ?? "clear-on-start";
473
490
  }
474
491
 
475
- export function configuredImplementationPlanRetention(
476
- settings: PlanModeSettings,
477
- ): ImplementationPlanRetention {
478
- return settings.implementationPlanRetention ?? "clear-on-start";
492
+ export function configuredImplementationModel(settings: PlanModeSettings): ImplementationModelOverride | undefined {
493
+ return settings.defaultImplementationModel;
494
+ }
495
+
496
+ export function configuredImplementationThinkingLevel(
497
+ settings: PlanModeSettings,
498
+ ): PlanModeFixedThinkingLevel | undefined {
499
+ return settings.defaultImplementationThinkingLevel;
479
500
  }
480
501
 
481
502
  export function configuredPlanExportPath(settings: PlanModeSettings) {
482
- return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
503
+ return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
483
504
  }
484
505
 
485
506
  export function configuredPlanModeToggleShortcut(settings: PlanModeSettings): KeyId | undefined {
486
- return settings.toggleShortcut;
507
+ return settings.toggleShortcut;
487
508
  }