@narumitw/pi-plan-mode 0.55.3 → 0.57.0

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.
@@ -1,6 +1,11 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
+ import {
4
+ createImplementationOptions,
5
+ type ImplementationOptionAction,
6
+ } from "./implementation-options.js";
3
7
  import { type PlanExportDestinationProvider, planExportInputScreen } from "./plan-export-screen.js";
8
+ import type { ImplementationPreferences } from "./settings.js";
4
9
 
5
10
  interface SavedPlanMenuOptions {
6
11
  statusText: string;
@@ -9,8 +14,15 @@ interface SavedPlanMenuOptions {
9
14
  signal: AbortSignal;
10
15
  isCurrent(): boolean;
11
16
  show(): void;
12
- implementHere(): void | Promise<void>;
13
- implementFresh(signal: AbortSignal): void | Promise<void>;
17
+ implementationPreferences?: ImplementationPreferences;
18
+ implementHere(
19
+ preferences?: ImplementationPreferences,
20
+ signal?: AbortSignal,
21
+ ): void | Promise<void>;
22
+ implementFresh(
23
+ signal: AbortSignal,
24
+ preferences?: ImplementationPreferences,
25
+ ): void | Promise<void>;
14
26
  exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
15
27
  settings(signal: AbortSignal): Promise<boolean>;
16
28
  clear(): void;
@@ -22,11 +34,20 @@ export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPla
22
34
  `${options.statusText} Use /plan show, /plan implement, /plan export, or /plan exit.`,
23
35
  );
24
36
  }
25
- type Screen = "saved" | "export";
26
- type Action = "show" | "implement-here" | "implement-fresh" | "export" | "settings" | "clear";
37
+ const implementation = createImplementationOptions(ctx, options.implementationPreferences);
38
+ type Screen = "saved" | "export" | "implementation-options" | "implementation-model";
39
+ type Action =
40
+ | ImplementationOptionAction
41
+ | "show"
42
+ | "implement-here"
43
+ | "implement-fresh"
44
+ | "export"
45
+ | "settings"
46
+ | "clear";
27
47
  const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
28
48
  start: "saved",
29
49
  screens: {
50
+ ...implementation.screens,
30
51
  saved: () => ({
31
52
  kind: "actions",
32
53
  title: "Saved plan",
@@ -35,6 +56,7 @@ export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPla
35
56
  "Implement here keeps this planning conversation.",
36
57
  "Start fresh transfers only the approved plan to a new session.",
37
58
  options.implementationOutcome(),
59
+ implementation.summary(),
38
60
  ],
39
61
  items: [
40
62
  { id: "show", label: "Show saved plan", action: "show" },
@@ -51,6 +73,11 @@ export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPla
51
73
  action: "implement-fresh",
52
74
  busyLabel: "Starting fresh implementation session…",
53
75
  },
76
+ {
77
+ id: "implementation-options",
78
+ label: "Implementation options…",
79
+ to: "implementation-options",
80
+ },
54
81
  { id: "export", label: "Export plan…", to: "export" },
55
82
  { id: "settings", label: "Settings", action: "settings" },
56
83
  { id: "clear", label: "Clear saved plan", action: "clear" },
@@ -60,16 +87,17 @@ export async function showSavedPlanMenu(ctx: ExtensionContext, options: SavedPla
60
87
  export: () => planExportInputScreen(options.getExportDestination),
61
88
  },
62
89
  actions: {
90
+ ...implementation.actions,
63
91
  show: async () => {
64
92
  options.show();
65
93
  return { kind: "close" };
66
94
  },
67
- "implement-here": async () => {
68
- await options.implementHere();
95
+ "implement-here": async ({ signal }) => {
96
+ await options.implementHere(implementation.get(), signal);
69
97
  return { kind: "close" };
70
98
  },
71
99
  "implement-fresh": async ({ signal }) => {
72
- await options.implementFresh(signal);
100
+ await options.implementFresh(signal, implementation.get());
73
101
  return { kind: "close" };
74
102
  },
75
103
  export: async ({ value, signal }) =>
@@ -1,6 +1,11 @@
1
1
  import type { ExtensionContext, ToolInfo } from "@earendil-works/pi-coding-agent";
2
2
  import { defineMenu, type RunMenuResult, runMenu } from "@narumitw/pi-tui-kit";
3
3
  import { PLAN_MODE_COMPLETE_TOOL_NAME } from "./completion-tool.js";
4
+ import {
5
+ createImplementationModelPicker,
6
+ type ImplementationOptionAction,
7
+ implementationSettingItems,
8
+ } from "./implementation-options.js";
4
9
  import { retentionLabel } from "./implementation-retention.js";
5
10
  import { planExportDestination } from "./plan-export.js";
6
11
  import { PLAN_MODE_QUESTION_TOOL_NAME } from "./question-tool.js";
@@ -44,8 +49,9 @@ export interface PlanModeSettingsMenuOptions {
44
49
  onSaved(settings: PlanModeSettings): void;
45
50
  }
46
51
 
47
- type Screen = "settings" | "tools" | "export" | "shortcut";
52
+ type Screen = "settings" | "tools" | "export" | "shortcut" | "implementation-model";
48
53
  type Action =
54
+ | ImplementationOptionAction
49
55
  | "set-thinking"
50
56
  | "open-tools"
51
57
  | "toggle-tool"
@@ -92,6 +98,7 @@ export async function showPlanModeSettings(
92
98
  };
93
99
  };
94
100
 
101
+ let implementationPicker: ReturnType<typeof createImplementationModelPicker> | undefined;
95
102
  const menu = defineMenu<SettingsMenuState, Screen, Action, ExtensionContext>({
96
103
  start: "settings",
97
104
  screens: {
@@ -144,8 +151,13 @@ export async function showPlanModeSettings(
144
151
  currentValue: configuredPlanModeToggleShortcut(state.settings) ?? "none",
145
152
  action: "open-shortcut",
146
153
  },
154
+ ...implementationSettingItems(state.settings),
147
155
  ],
148
156
  },
157
+ "implementation-model": ({ state }) => {
158
+ implementationPicker ??= createImplementationModelPicker(ctx);
159
+ return implementationPicker.screen(state.settings);
160
+ },
149
161
  tools: ({ state }) => ({
150
162
  kind: "multiSelect",
151
163
  title: "Default Plan policy allowlist",
@@ -203,6 +215,28 @@ export async function showPlanModeSettings(
203
215
  }),
204
216
  },
205
217
  actions: {
218
+ "open-implementation-model": async () => ({ kind: "to", screen: "implementation-model" }),
219
+ "set-implementation-model": async ({ ctx: actionCtx, itemId, signal }) => {
220
+ const model = implementationPicker?.selection(itemId);
221
+ if (model === undefined) return { kind: "rejected" };
222
+ const result = await savePatch(
223
+ actionCtx,
224
+ { implementationModel: model },
225
+ signal,
226
+ "Implementation model saved. Applies when implementation starts.",
227
+ );
228
+ return result.kind === "stay" ? { kind: "back" } : result;
229
+ },
230
+ "set-implementation-thinking": async ({ ctx: actionCtx, value, signal }) => {
231
+ const level = PLAN_MODE_THINKING_LEVELS.find((level) => level === value);
232
+ if (!level) return { kind: "rejected" };
233
+ return savePatch(
234
+ actionCtx,
235
+ { implementationThinkingLevel: level },
236
+ signal,
237
+ "Implementation thinking saved. Applies when implementation starts.",
238
+ );
239
+ },
206
240
  "set-thinking": async ({ ctx: actionCtx, value, signal }) => {
207
241
  if (
208
242
  !PLAN_MODE_THINKING_LEVELS.includes(value as (typeof PLAN_MODE_THINKING_LEVELS)[number])
package/src/settings.ts CHANGED
@@ -4,13 +4,7 @@ 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
- SAFE_GH_SUBCOMMAND_PATHS,
9
- SAFE_GIT_SUBCOMMANDS,
10
- type SafeGhSubcommandPath,
11
- type SafeGitSubcommand,
12
- type SafeSubcommands,
13
- } from "./tool-policy.js";
7
+ import type { SafeSubcommands } from "./tool-policy.js";
14
8
 
15
9
  export const PLAN_MODE_SETTINGS_FILE = "pi-plan-mode.json";
16
10
  const LEGACY_PLAN_MODE_SETTINGS_FILE = "plan-mode.json";
@@ -90,7 +84,11 @@ const MAX_PLAN_EXPORT_PATH_LENGTH = 4096;
90
84
  export type PlanModeThinkingLevel = (typeof PLAN_MODE_THINKING_LEVELS)[number];
91
85
  export type ImplementationPlanRetention = (typeof IMPLEMENTATION_PLAN_RETENTIONS)[number];
92
86
  export type PlanModeFixedThinkingLevel = Exclude<PlanModeThinkingLevel, "inherit">;
93
- export interface PlanModeSettings {
87
+ export interface ImplementationPreferences {
88
+ implementationModel?: { provider: string; id: string };
89
+ implementationThinkingLevel?: PlanModeThinkingLevel;
90
+ }
91
+ export interface PlanModeSettings extends ImplementationPreferences {
94
92
  thinkingLevel: PlanModeThinkingLevel;
95
93
  defaultPlanTools?: string[];
96
94
  implementationPlanRetention?: ImplementationPlanRetention;
@@ -99,6 +97,8 @@ export interface PlanModeSettings {
99
97
  toggleShortcut?: KeyId;
100
98
  }
101
99
  export interface PlanModeSettingsPatch {
100
+ implementationModel?: ImplementationPreferences["implementationModel"] | null;
101
+ implementationThinkingLevel?: PlanModeThinkingLevel;
102
102
  thinkingLevel?: PlanModeThinkingLevel;
103
103
  defaultPlanTools?: readonly string[] | null;
104
104
  implementationPlanRetention?: ImplementationPlanRetention;
@@ -143,6 +143,21 @@ export function normalizePlanModeSettings(value: unknown): PlanModeSettings | un
143
143
  const settings: PlanModeSettings = {
144
144
  thinkingLevel: thinkingLevel as PlanModeThinkingLevel,
145
145
  };
146
+ if (Object.hasOwn(value, "implementationModel")) {
147
+ const model = Reflect.get(value, "implementationModel");
148
+ if (
149
+ !isSettingsDocument(model) ||
150
+ !validModelIdentity(model.provider) ||
151
+ !validModelIdentity(model.id)
152
+ )
153
+ return undefined;
154
+ settings.implementationModel = { provider: model.provider, id: model.id };
155
+ }
156
+ if (Object.hasOwn(value, "implementationThinkingLevel")) {
157
+ const level = Reflect.get(value, "implementationThinkingLevel");
158
+ if (!PLAN_MODE_THINKING_LEVELS.includes(level as PlanModeThinkingLevel)) return undefined;
159
+ settings.implementationThinkingLevel = level as PlanModeThinkingLevel;
160
+ }
146
161
  if (Object.hasOwn(value, "defaultPlanTools")) {
147
162
  const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
148
163
  if (!defaultPlanTools) return undefined;
@@ -180,6 +195,10 @@ export function normalizePlanModeSettings(value: unknown): PlanModeSettings | un
180
195
  return settings;
181
196
  }
182
197
 
198
+ function validModelIdentity(value: unknown): value is string {
199
+ return typeof value === "string" && value.trim().length > 0 && value.length <= 4096;
200
+ }
201
+
183
202
  function normalizeToolNames(value: unknown) {
184
203
  if (
185
204
  !Array.isArray(value) ||
@@ -230,30 +249,26 @@ export function normalizeKeyId(value: unknown): KeyId | undefined {
230
249
 
231
250
  function normalizeSafeSubcommands(value: unknown): SafeSubcommands | undefined {
232
251
  if (!isSettingsDocument(value)) return undefined;
233
- if (Object.keys(value).some((key) => key !== "git" && key !== "gh")) return undefined;
234
-
235
- const safeSubcommands: SafeSubcommands = {};
236
- if (Object.hasOwn(value, "git")) {
237
- const git = normalizeKnownValues(Reflect.get(value, "git"), SAFE_GIT_SUBCOMMANDS);
238
- if (!git) return undefined;
239
- safeSubcommands.git = git as SafeGitSubcommand[];
240
- }
241
- if (Object.hasOwn(value, "gh")) {
242
- const gh = normalizeKnownValues(Reflect.get(value, "gh"), SAFE_GH_SUBCOMMAND_PATHS);
243
- if (!gh) return undefined;
244
- safeSubcommands.gh = gh as SafeGhSubcommandPath[];
245
- }
246
- return safeSubcommands;
247
- }
248
-
249
- function normalizeKnownValues(value: unknown, supported: readonly string[]) {
250
- if (
251
- !Array.isArray(value) ||
252
- !value.every((item): item is string => typeof item === "string" && supported.includes(item))
253
- ) {
254
- return undefined;
252
+ const entries: Array<[string, string[]]> = [];
253
+ for (const [command, subcommands] of Object.entries(value)) {
254
+ const normalizedCommand = command.trim();
255
+ if (
256
+ !normalizedCommand ||
257
+ !Array.isArray(subcommands) ||
258
+ !subcommands.every(
259
+ (item): item is string => typeof item === "string" && item.trim().length > 0,
260
+ )
261
+ ) {
262
+ return undefined;
263
+ }
264
+ const normalizedSubcommands = Array.from(
265
+ new Set(subcommands.map((subcommand) => subcommand.trim())),
266
+ );
267
+ const existing = entries.find(([existingCommand]) => existingCommand === normalizedCommand);
268
+ if (existing) existing[1] = Array.from(new Set([...existing[1], ...normalizedSubcommands]));
269
+ else entries.push([normalizedCommand, normalizedSubcommands]);
255
270
  }
256
- return Array.from(new Set(value));
271
+ return Object.fromEntries(entries);
257
272
  }
258
273
 
259
274
  export async function readPlanModeSettings(
@@ -299,6 +314,15 @@ export function updatePlanModeSettings(
299
314
  const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
300
315
  const updated: SettingsDocument = { ...current };
301
316
  if (patch.thinkingLevel !== undefined) updated.thinkingLevel = patch.thinkingLevel;
317
+ if (patch.implementationModel === null) delete updated.implementationModel;
318
+ else if (patch.implementationModel !== undefined) {
319
+ const previous = isSettingsDocument(updated.implementationModel)
320
+ ? updated.implementationModel
321
+ : {};
322
+ updated.implementationModel = { ...previous, ...patch.implementationModel };
323
+ }
324
+ if (patch.implementationThinkingLevel !== undefined)
325
+ updated.implementationThinkingLevel = patch.implementationThinkingLevel;
302
326
  if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
303
327
  else if (patch.defaultPlanTools !== undefined) {
304
328
  updated.defaultPlanTools = [...patch.defaultPlanTools];
@@ -30,8 +30,7 @@ export type ConfigurableSafeGitSubcommand = (typeof CONFIGURABLE_SAFE_GIT_SUBCOM
30
30
  export type SafeGitSubcommand = (typeof SAFE_GIT_SUBCOMMANDS)[number];
31
31
  export type SafeGhSubcommandPath = (typeof SAFE_GH_SUBCOMMAND_PATHS)[number];
32
32
  export interface SafeSubcommands {
33
- git?: SafeGitSubcommand[];
34
- gh?: SafeGhSubcommandPath[];
33
+ [command: string]: string[] | undefined;
35
34
  }
36
35
 
37
36
  export const SAFE_BUILTIN_PLAN_TOOLS = new Set([
@@ -148,18 +147,25 @@ export function findBlockedCommandSegment(
148
147
  command: string,
149
148
  safeSubcommands: SafeSubcommands = {},
150
149
  workingDirectory?: string,
150
+ platform: NodeJS.Platform = process.platform,
151
151
  ): string | undefined {
152
+ if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return undefined;
152
153
  const segments = splitShellSegments(command);
153
154
  if (!segments || segments.length === 0) return command.trim() || "(empty command)";
154
- return segments.find((segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory));
155
+ return segments.find(
156
+ (segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory, platform),
157
+ );
155
158
  }
156
159
 
157
160
  export function isSafeCommand(
158
161
  command: string,
159
162
  safeSubcommands: SafeSubcommands = {},
160
163
  workingDirectory?: string,
164
+ platform: NodeJS.Platform = process.platform,
161
165
  ) {
162
- return findBlockedCommandSegment(command, safeSubcommands, workingDirectory) === undefined;
166
+ return (
167
+ findBlockedCommandSegment(command, safeSubcommands, workingDirectory, platform) === undefined
168
+ );
163
169
  }
164
170
 
165
171
  export function findBlockedPowerShellCommandSegment(
@@ -167,6 +173,7 @@ export function findBlockedPowerShellCommandSegment(
167
173
  safeSubcommands: SafeSubcommands = {},
168
174
  workingDirectory?: string,
169
175
  ): string | undefined {
176
+ if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return undefined;
170
177
  const segments = splitPowerShellSegments(command);
171
178
  if (!segments || segments.length === 0) return command.trim() || "(empty command)";
172
179
  return segments.find(
@@ -184,6 +191,20 @@ export function isSafePowerShellCommand(
184
191
  );
185
192
  }
186
193
 
194
+ function matchesConfiguredSafeSubcommand(command: string, safeSubcommands: SafeSubcommands) {
195
+ const candidate = command.trimStart();
196
+ return Object.entries(safeSubcommands).some(([configuredCommand, subcommands]) =>
197
+ subcommands?.some((subcommand) => {
198
+ const prefix = `${configuredCommand.trim()} ${subcommand.trim()}`;
199
+ if (!configuredCommand.trim() || !subcommand.trim() || !candidate.startsWith(prefix)) {
200
+ return false;
201
+ }
202
+ const boundary = candidate[prefix.length];
203
+ return boundary === undefined || /[\s;&|<>()]/.test(boundary);
204
+ }),
205
+ );
206
+ }
207
+
187
208
  function splitPowerShellSegments(command: string): string[] | undefined {
188
209
  const trimmed = command.trim();
189
210
  if (!trimmed || /[\n\r`\u2018-\u201e]/.test(trimmed)) return undefined;
@@ -242,6 +263,8 @@ function isSafePowerShellSegment(
242
263
  if (!command) return false;
243
264
  const args = tokens.slice(1);
244
265
  if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
266
+ if (command === "get-process") return isSafeGetProcessArguments(args);
267
+ if (command === "get-service") return isSafeGetServiceArguments(args);
245
268
  if (command !== "git" && command !== "gh") return false;
246
269
  return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
247
270
  }
@@ -344,7 +367,8 @@ function splitShellSegments(command: string): string[] | undefined {
344
367
  function isSafeSegment(
345
368
  segment: string,
346
369
  safeSubcommands: SafeSubcommands,
347
- workingDirectory?: string,
370
+ workingDirectory: string | undefined,
371
+ platform: NodeJS.Platform,
348
372
  ) {
349
373
  if (hasShellExpansion(segment) || /(^|\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {
350
374
  return false;
@@ -355,6 +379,8 @@ function isSafeSegment(
355
379
  if (!command || MUTATING_COMMANDS.has(command)) return false;
356
380
  const args = tokens.slice(1);
357
381
  if (!hasSafeArguments(command, args)) return false;
382
+ if (command === "hostname") return args.length === 0;
383
+ if (command === "tasklist") return platform === "win32" && isSafeTasklistArguments(args);
358
384
  if (READ_ONLY_COMMANDS.has(command)) return true;
359
385
  return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
360
386
  }
@@ -584,6 +610,72 @@ function isSafeStructuredCommand(
584
610
  return false;
585
611
  }
586
612
 
613
+ function isSafeTasklistArguments(args: string[]) {
614
+ for (let index = 0; index < args.length; index += 1) {
615
+ const argument = args[index]?.toLowerCase();
616
+ if (["/v", "/nh", "/svc"].includes(argument ?? "")) continue;
617
+ if (argument === "/fo") {
618
+ const format = args[index + 1]?.toLowerCase();
619
+ if (!format || !["table", "list", "csv"].includes(format)) return false;
620
+ index += 1;
621
+ continue;
622
+ }
623
+ if (argument === "/fi") {
624
+ const filter = args[index + 1];
625
+ if (!filter || filter.startsWith("/")) return false;
626
+ index += 1;
627
+ continue;
628
+ }
629
+ if (argument === "/m") {
630
+ const module = args[index + 1];
631
+ if (module && !module.startsWith("/")) index += 1;
632
+ continue;
633
+ }
634
+ return false;
635
+ }
636
+ return true;
637
+ }
638
+
639
+ function isSafeGetProcessArguments(args: string[]) {
640
+ return hasSafePowerShellQueryArguments(
641
+ args,
642
+ new Set(["-module", "-fileversioninfo", "-includeusername"]),
643
+ new Set(["-name", "-id"]),
644
+ );
645
+ }
646
+
647
+ function isSafeGetServiceArguments(args: string[]) {
648
+ return hasSafePowerShellQueryArguments(
649
+ args,
650
+ new Set(["-dependentservices", "-requiredservices"]),
651
+ new Set(["-name", "-displayname", "-include", "-exclude"]),
652
+ );
653
+ }
654
+
655
+ function hasSafePowerShellQueryArguments(
656
+ args: string[],
657
+ switches: ReadonlySet<string>,
658
+ valueOptions: ReadonlySet<string>,
659
+ ) {
660
+ let positionalValues = 0;
661
+ for (let index = 0; index < args.length; index += 1) {
662
+ const argument = args[index];
663
+ const normalized = argument?.toLowerCase();
664
+ if (!argument || !normalized) return false;
665
+ if (!argument.startsWith("-")) {
666
+ positionalValues += 1;
667
+ if (positionalValues > 1) return false;
668
+ continue;
669
+ }
670
+ if (switches.has(normalized)) continue;
671
+ if (!valueOptions.has(normalized)) return false;
672
+ const value = args[index + 1];
673
+ if (!value || value.startsWith("-")) return false;
674
+ index += 1;
675
+ }
676
+ return true;
677
+ }
678
+
587
679
  function isSafeGitCommand(
588
680
  args: string[],
589
681
  safeSubcommands: SafeSubcommands,