@narumitw/pi-plan-mode 0.58.0 → 0.58.2

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