@narumitw/pi-plan-mode 0.52.0 → 0.54.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,8 +1,10 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
2
+ import { stripTerminalSequences, truncateToWidth } from "@earendil-works/pi-tui";
2
3
  import type { PlanModeState } from "./state.js";
3
4
 
4
5
  const STATUS_KEY = "plan-mode";
5
6
  const PLAN_WIDGET_KEY = "plan-mode-plan";
7
+ const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
6
8
 
7
9
  export function updatePlanModeUi(
8
10
  ctx: ExtensionContext,
@@ -10,30 +12,44 @@ export function updatePlanModeUi(
10
12
  toolSummary: () => string,
11
13
  ) {
12
14
  ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
15
+ let lines: string[] | undefined;
13
16
  if (state.enabled && state.latestPlan) {
14
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [
15
- "Proposed plan ready",
16
- "Use /plan to implement, save, revise, or exit Plan mode.",
17
- ]);
17
+ lines = ["Proposed plan ready", "Use /plan to implement, save, revise, or exit Plan mode."];
18
18
  } else if (state.enabled) {
19
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [
19
+ lines = [
20
20
  "Plan mode: planning",
21
21
  toolSummary(),
22
22
  "Finish with plan_mode_complete when decision-ready.",
23
- ]);
23
+ ];
24
24
  } else if (state.savedPlan) {
25
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [
26
- "Plan saved for later",
27
- "Use /plan to show, implement, or clear it.",
28
- ]);
25
+ lines = ["Plan saved for later", "Use /plan to show, implement, or clear it."];
29
26
  } else if (state.activeImplementation) {
30
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [
31
- "Implementation plan active",
32
- "Use /plan to show, replace, or clear it.",
33
- ]);
34
- } else {
35
- ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
27
+ lines = ["Implementation plan active", "Use /plan to show, replace, or clear it."];
28
+ }
29
+
30
+ publishPlanModeWidget(ctx, lines);
31
+ }
32
+
33
+ export function renderPlanModeWidget(
34
+ lines: readonly string[],
35
+ theme: Theme,
36
+ width: number,
37
+ ): string[] {
38
+ const renderWidth = Math.max(0, width);
39
+ return [
40
+ theme.fg("borderMuted", "─".repeat(renderWidth)),
41
+ ...lines.map((line) => truncateToWidth(sanitizePlanModeWidgetLine(line), renderWidth, "")),
42
+ ];
43
+ }
44
+
45
+ export function sanitizePlanModeWidgetLine(value: string): string {
46
+ let text = "";
47
+ for (const character of stripTerminalSequences(value).replace(BIDI_CONTROLS, "")) {
48
+ const codePoint = character.codePointAt(0) ?? 0;
49
+ const isControl = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
50
+ text += isControl ? " " : character;
36
51
  }
52
+ return text;
37
53
  }
38
54
 
39
55
  export function clearPlanModeUi(ctx: ExtensionContext) {
@@ -97,6 +113,23 @@ export function planModeStatusText(state: PlanModeState, toolSummary: () => stri
97
113
  return "Plan mode is off.";
98
114
  }
99
115
 
116
+ function publishPlanModeWidget(ctx: ExtensionContext, lines: readonly string[] | undefined) {
117
+ if (!lines) {
118
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, undefined);
119
+ return;
120
+ }
121
+ if (ctx.mode !== "tui") {
122
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, [...lines]);
123
+ return;
124
+ }
125
+
126
+ const snapshot = [...lines];
127
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => ({
128
+ render: (width) => renderPlanModeWidget(snapshot, theme, width),
129
+ invalidate: () => {},
130
+ }));
131
+ }
132
+
100
133
  function formatStatus(state: PlanModeState) {
101
134
  if (state.enabled) {
102
135
  if (state.awaitingAction || state.latestPlan) return "plan ready";
package/src/prompt.ts CHANGED
@@ -11,7 +11,7 @@ You are in Plan Mode, a Codex-like collaboration mode for producing a decision-c
11
11
  - Stay in Plan Mode until a developer or extension explicitly exits it.
12
12
  - Treat requests to implement as requests to plan the implementation; do not edit files or carry out the plan.
13
13
  - Do not use update_plan/TODO tooling in Plan Mode; Plan Mode is conversational planning, not execution progress tracking.
14
- - Plan Mode manages built-in tool safety only. Non-built-in tools are disabled by default and may be enabled by the user at their own risk.
14
+ - Plan Mode keeps the session's model-visible tool schemas unchanged and enforces a runtime policy allowlist. Non-built-in tools are denied by default and may be allowed only when already active in Pi and explicitly selected by the user at their own risk.
15
15
  - Do not perform mutating actions: no edit/write tools, no patching, no formatting that rewrites files, no dependency installation, no commits, no migrations.
16
16
 
17
17
  ## Phase 1 — Ground in the environment
@@ -30,6 +30,8 @@ You are in Plan Mode, a Codex-like collaboration mode for producing a decision-c
30
30
 
31
31
  - Once intent is stable, keep asking until the spec is decision-complete: approach, interfaces, data flow, edge cases/failure modes, testing and acceptance criteria, and any migration or compatibility constraints.
32
32
  - Use plan_mode_question for important preferences, tradeoffs, or assumption locks that cannot be discovered by non-mutating exploration. Ask 1-3 concise questions with 2-4 meaningful options. Do not include filler options.
33
+ - Treat plan_mode_question and plan_mode_complete as callable when they are listed in the current request's active tools. Do not infer that they are unavailable from earlier modes or conversation history.
34
+ - If a Plan tool call returns an actual error, respond to that error. Do not replace an available structured tool call with prose claiming that the tool is unavailable.
33
35
  - If plan_mode_question returns cancelled or ui_unavailable, do not jump straight to a final plan when the missing answer is high impact. Ask one concise plain-text question or proceed only with a clearly stated low-risk assumption.
34
36
 
35
37
  ## Ending each turn
@@ -10,10 +10,6 @@ export function withRequiredPlanModeTools(toolNames: string[]) {
10
10
  ]);
11
11
  }
12
12
 
13
- export function withoutPlanModeQuestionTool(toolNames: string[]) {
14
- return toolNames.filter((toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME);
15
- }
16
-
17
13
  export function withoutRequiredPlanModeTools(toolNames: string[]) {
18
14
  return toolNames.filter(
19
15
  (toolName) =>
@@ -8,9 +8,11 @@ import {
8
8
  configuredImplementationPlanRetention,
9
9
  configuredPlanExportPath,
10
10
  configuredPlanModeToggleShortcut,
11
+ configuredPlanModeToolVisibility,
11
12
  IMPLEMENTATION_PLAN_RETENTIONS,
12
13
  normalizeKeyId,
13
14
  PLAN_MODE_THINKING_LEVELS,
15
+ PLAN_MODE_TOOL_VISIBILITIES,
14
16
  type PlanModeSettings,
15
17
  type PlanModeSettingsLoadResult,
16
18
  type PlanModeSettingsPatch,
@@ -31,6 +33,7 @@ interface SettingsMenuState {
31
33
 
32
34
  export interface PlanModeSettingsMenuOptions {
33
35
  tools: readonly ToolInfo[];
36
+ activeToolNames?: readonly string[];
34
37
  signal: AbortSignal;
35
38
  isCurrent(): boolean;
36
39
  settingsPath?: string;
@@ -46,6 +49,7 @@ export interface PlanModeSettingsMenuOptions {
46
49
  type Screen = "settings" | "tools" | "export" | "shortcut";
47
50
  type Action =
48
51
  | "set-thinking"
52
+ | "set-tool-visibility"
49
53
  | "open-tools"
50
54
  | "toggle-tool"
51
55
  | "reset-tools"
@@ -62,6 +66,9 @@ export async function showPlanModeSettings(
62
66
  const settingsPath = options.settingsPath ?? planModeSettingsPath();
63
67
  const readSettings = options.readSettings ?? readPlanModeSettings;
64
68
  const updateSettings = options.updateSettings ?? updatePlanModeSettings;
69
+ const activeToolNames = new Set(
70
+ options.activeToolNames ?? options.tools.map((tool) => tool.name),
71
+ );
65
72
  const tools = options.tools.filter(
66
73
  (tool) =>
67
74
  tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME,
@@ -105,16 +112,17 @@ export async function showPlanModeSettings(
105
112
  },
106
113
  {
107
114
  id: "defaultPlanTools",
108
- label: "Plan tools",
115
+ label: "Plan policy tools",
109
116
  description:
110
- "Choose persistent defaults; a launch-time selection still overrides them for that session.",
117
+ "Choose which already-active tools Plan mode may execute by default.",
111
118
  currentValue: defaultToolsValue(state.settings.defaultPlanTools),
112
119
  action: "open-tools",
113
120
  },
114
121
  {
115
122
  id: "implementationPlanRetention",
116
- label: "After Implement",
117
- description: "Choose how long the accepted plan keeps guiding implementation.",
123
+ label: "Plan reinjection",
124
+ description:
125
+ "Choose how long Plan mode restores the exact plan when ordinary context no longer contains it.",
118
126
  currentValue: retentionLabel(
119
127
  configuredImplementationPlanRetention(state.settings),
120
128
  ),
@@ -135,18 +143,29 @@ export async function showPlanModeSettings(
135
143
  currentValue: configuredPlanModeToggleShortcut(state.settings) ?? "none",
136
144
  action: "open-shortcut",
137
145
  },
146
+ {
147
+ id: "toolVisibility",
148
+ label: "Plan tools",
149
+ description:
150
+ "Keep Plan helper tools visible, or reveal them after the first plan.",
151
+ currentValue: toolVisibilityLabel(
152
+ configuredPlanModeToolVisibility(state.settings),
153
+ ),
154
+ values: PLAN_MODE_TOOL_VISIBILITIES.map(toolVisibilityLabel),
155
+ action: "set-tool-visibility",
156
+ },
138
157
  ],
139
158
  },
140
159
  tools: ({ state }) => ({
141
160
  kind: "multiSelect",
142
- title: "Default Plan-mode tools",
161
+ title: "Default Plan policy allowlist",
143
162
  lines: [
144
- "Changes apply when a later Plan workflow starts; required Plan tools stay enabled.",
145
- "Non-built-in tools run at user risk.",
163
+ "Changes apply when a later Plan workflow starts; model-visible tools stay unchanged.",
164
+ "Only tools already active in Pi can be allowed; non-built-ins run at user risk.",
146
165
  ],
147
166
  enableSearch: true,
148
167
  viewportSize: 10,
149
- items: defaultToolItems(tools, state.settings.defaultPlanTools),
168
+ items: defaultToolItems(tools, state.settings.defaultPlanTools, activeToolNames),
150
169
  action: "toggle-tool",
151
170
  actions: [
152
171
  {
@@ -201,6 +220,16 @@ export async function showPlanModeSettings(
201
220
  `Plan mode thinking level: ${value}. Applies to the next Plan workflow.`,
202
221
  );
203
222
  },
223
+ "set-tool-visibility": async ({ ctx: actionCtx, value, signal }) => {
224
+ const toolVisibility = toolVisibilityFromLabel(value);
225
+ if (!toolVisibility) return { kind: "rejected" };
226
+ return savePatch(
227
+ actionCtx,
228
+ { toolVisibility },
229
+ signal,
230
+ `Plan tools: ${toolVisibilityLabel(toolVisibility)}.`,
231
+ );
232
+ },
204
233
  "open-tools": async () => ({ kind: "to", screen: "tools" }),
205
234
  "set-retention": async ({ ctx: actionCtx, value, signal }) => {
206
235
  const implementationPlanRetention = retentionFromLabel(value);
@@ -209,7 +238,7 @@ export async function showPlanModeSettings(
209
238
  actionCtx,
210
239
  { implementationPlanRetention },
211
240
  signal,
212
- `After Implement: ${retentionLabel(implementationPlanRetention)}. Applies to the next Implement action.`,
241
+ `Plan reinjection: ${retentionLabel(implementationPlanRetention)}. Applies to the next Implement action.`,
213
242
  );
214
243
  },
215
244
  "open-export": async () => ({ kind: "to", screen: "export" }),
@@ -248,7 +277,9 @@ export async function showPlanModeSettings(
248
277
  },
249
278
  "toggle-tool": async ({ ctx: actionCtx, state, itemId, selected, signal }) => {
250
279
  const tool = tools.find((candidate) => candidate.name === itemId);
251
- if (!tool || !canSelectToolInPlanMode(tool)) return { kind: "rejected" };
280
+ if (!tool || !activeToolNames.has(tool.name) || !canSelectToolInPlanMode(tool)) {
281
+ return { kind: "rejected" };
282
+ }
252
283
  const names = explicitToolNames(tools, state.settings.defaultPlanTools);
253
284
  const next = selected
254
285
  ? Array.from(new Set([...names, tool.name]))
@@ -257,7 +288,7 @@ export async function showPlanModeSettings(
257
288
  actionCtx,
258
289
  { defaultPlanTools: next },
259
290
  signal,
260
- `Default Plan-mode tools: ${next.length === 0 ? "required tools only" : `${next.length} selected`}.`,
291
+ `Default Plan policy: ${next.length === 0 ? "no optional tools" : `${next.length} allowed`}.`,
261
292
  );
262
293
  },
263
294
  "reset-tools": async ({ ctx: actionCtx, state, signal }) => {
@@ -310,7 +341,7 @@ export async function showPlanModeSettings(
310
341
  function settingsLines(settingsPath: string, notice: string | undefined) {
311
342
  return [
312
343
  `User settings · ${safeTerminalText(settingsPath)}`,
313
- "Plan defaults apply to the next workflow; handoff and export choices apply to their next action.",
344
+ "Plan defaults apply to the next workflow; reinjection and export choices apply to their next action.",
314
345
  ...(notice ? [safeTerminalText(notice)] : []),
315
346
  ];
316
347
  }
@@ -332,18 +363,33 @@ function retentionFromLabel(value: string | undefined) {
332
363
  return IMPLEMENTATION_PLAN_RETENTIONS.find((retention) => retentionLabel(retention) === value);
333
364
  }
334
365
 
366
+ function toolVisibilityLabel(value: PlanModeSettings["toolVisibility"] | "after-first-plan") {
367
+ return value === "always" ? "Always" : "After first plan";
368
+ }
369
+
370
+ function toolVisibilityFromLabel(value: string | undefined) {
371
+ return PLAN_MODE_TOOL_VISIBILITIES.find(
372
+ (visibility) => toolVisibilityLabel(visibility) === value,
373
+ );
374
+ }
375
+
335
376
  function defaultToolsValue(configured: string[] | undefined) {
336
377
  if (configured === undefined) return "Automatic safe built-ins";
337
- if (configured.length === 0) return "Required tools only";
378
+ if (configured.length === 0) return "No optional tools";
338
379
  return `${configured.length} selected`;
339
380
  }
340
381
 
341
- function defaultToolItems(tools: readonly ToolInfo[], configured: string[] | undefined) {
382
+ function defaultToolItems(
383
+ tools: readonly ToolInfo[],
384
+ configured: string[] | undefined,
385
+ activeToolNames: ReadonlySet<string>,
386
+ ) {
342
387
  const selected = new Set(explicitToolNames(tools, configured));
343
388
  const availableNames = new Set(tools.map((tool) => tool.name));
344
389
  const items = tools.map((tool) => {
345
- const selectable = canSelectToolInPlanMode(tool);
346
- const policy = toolPolicyLabel(tool);
390
+ const active = activeToolNames.has(tool.name);
391
+ const selectable = active && canSelectToolInPlanMode(tool);
392
+ const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
347
393
  const description = tool.description ?? "No description available";
348
394
  return {
349
395
  id: tool.name,
@@ -352,7 +398,11 @@ function defaultToolItems(tools: readonly ToolInfo[], configured: string[] | und
352
398
  searchText: `${policy} ${description}`,
353
399
  selected: selected.has(tool.name),
354
400
  disabled: !selectable,
355
- disabledReason: selectable ? undefined : "Blocked by Plan-mode policy",
401
+ disabledReason: !active
402
+ ? "Not active in Pi; Plan mode will not activate it"
403
+ : selectable
404
+ ? undefined
405
+ : "Blocked by Plan-mode policy",
356
406
  };
357
407
  });
358
408
  for (const name of configured ?? []) {
package/src/settings.ts CHANGED
@@ -26,10 +26,12 @@ export const PLAN_MODE_THINKING_LEVELS = [
26
26
  "max",
27
27
  ] as const;
28
28
  export const IMPLEMENTATION_PLAN_RETENTIONS = [
29
- "keep",
30
29
  "clear-on-start",
31
30
  "clear-after-first-run",
31
+ "keep",
32
32
  ] as const;
33
+ export const PLAN_MODE_TOOL_VISIBILITIES = ["always", "after-first-plan"] as const;
34
+ export const DEFAULT_PLAN_MODE_TOOL_VISIBILITY = "after-first-plan";
33
35
  export const DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
34
36
  const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
35
37
  const BASE_KEYS = new Set([
@@ -89,9 +91,11 @@ const MAX_PLAN_EXPORT_PATH_LENGTH = 4096;
89
91
 
90
92
  export type PlanModeThinkingLevel = (typeof PLAN_MODE_THINKING_LEVELS)[number];
91
93
  export type ImplementationPlanRetention = (typeof IMPLEMENTATION_PLAN_RETENTIONS)[number];
94
+ export type PlanModeToolVisibility = (typeof PLAN_MODE_TOOL_VISIBILITIES)[number];
92
95
  export type PlanModeFixedThinkingLevel = Exclude<PlanModeThinkingLevel, "inherit">;
93
96
  export interface PlanModeSettings {
94
97
  thinkingLevel: PlanModeThinkingLevel;
98
+ toolVisibility?: PlanModeToolVisibility;
95
99
  defaultPlanTools?: string[];
96
100
  implementationPlanRetention?: ImplementationPlanRetention;
97
101
  defaultPlanExportPath?: string;
@@ -100,6 +104,7 @@ export interface PlanModeSettings {
100
104
  }
101
105
  export interface PlanModeSettingsPatch {
102
106
  thinkingLevel?: PlanModeThinkingLevel;
107
+ toolVisibility?: PlanModeToolVisibility;
103
108
  defaultPlanTools?: readonly string[] | null;
104
109
  implementationPlanRetention?: ImplementationPlanRetention;
105
110
  defaultPlanExportPath?: string | null;
@@ -143,6 +148,13 @@ export function normalizePlanModeSettings(value: unknown): PlanModeSettings | un
143
148
  const settings: PlanModeSettings = {
144
149
  thinkingLevel: thinkingLevel as PlanModeThinkingLevel,
145
150
  };
151
+ if (Object.hasOwn(value, "toolVisibility")) {
152
+ const toolVisibility = Reflect.get(value, "toolVisibility");
153
+ if (!PLAN_MODE_TOOL_VISIBILITIES.includes(toolVisibility as PlanModeToolVisibility)) {
154
+ return undefined;
155
+ }
156
+ settings.toolVisibility = toolVisibility as PlanModeToolVisibility;
157
+ }
146
158
  if (Object.hasOwn(value, "defaultPlanTools")) {
147
159
  const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
148
160
  if (!defaultPlanTools) return undefined;
@@ -299,6 +311,7 @@ export function updatePlanModeSettings(
299
311
  const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
300
312
  const updated: SettingsDocument = { ...current };
301
313
  if (patch.thinkingLevel !== undefined) updated.thinkingLevel = patch.thinkingLevel;
314
+ if (patch.toolVisibility !== undefined) updated.toolVisibility = patch.toolVisibility;
302
315
  if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
303
316
  else if (patch.defaultPlanTools !== undefined) {
304
317
  updated.defaultPlanTools = [...patch.defaultPlanTools];
@@ -482,10 +495,16 @@ export function configuredThinkingLevel(
482
495
  return settings.thinkingLevel === "inherit" ? undefined : settings.thinkingLevel;
483
496
  }
484
497
 
498
+ export function configuredPlanModeToolVisibility(
499
+ settings: PlanModeSettings,
500
+ ): PlanModeToolVisibility {
501
+ return settings.toolVisibility ?? DEFAULT_PLAN_MODE_TOOL_VISIBILITY;
502
+ }
503
+
485
504
  export function configuredImplementationPlanRetention(
486
505
  settings: PlanModeSettings,
487
506
  ): ImplementationPlanRetention {
488
- return settings.implementationPlanRetention ?? "keep";
507
+ return settings.implementationPlanRetention ?? "clear-on-start";
489
508
  }
490
509
 
491
510
  export function configuredPlanExportPath(settings: PlanModeSettings) {
@@ -33,7 +33,14 @@ export interface SafeSubcommands {
33
33
  gh?: SafeGhSubcommandPath[];
34
34
  }
35
35
 
36
- export const SAFE_BUILTIN_PLAN_TOOLS = new Set(["read", "bash", "grep", "find", "ls"]);
36
+ export const SAFE_BUILTIN_PLAN_TOOLS = new Set([
37
+ "read",
38
+ "bash",
39
+ "powershell",
40
+ "grep",
41
+ "find",
42
+ "ls",
43
+ ]);
37
44
  export type PlanModeToolPolicy = "read-only" | "limited" | "user-opt-in" | "blocked";
38
45
 
39
46
  const BLOCKED_BUILTIN_TOOLS = new Set(["edit", "write"]);
@@ -65,6 +72,21 @@ const MUTATING_COMMANDS = new Set([
65
72
  "code",
66
73
  "subl",
67
74
  ]);
75
+ const READ_ONLY_POWERSHELL_COMMANDS = new Set([
76
+ "format-list",
77
+ "format-table",
78
+ "get-childitem",
79
+ "get-content",
80
+ "get-item",
81
+ "get-location",
82
+ "measure-object",
83
+ "out-string",
84
+ "resolve-path",
85
+ "select-string",
86
+ "sort-object",
87
+ "test-path",
88
+ "write-output",
89
+ ]);
68
90
  const READ_ONLY_COMMANDS = new Set([
69
91
  "cat",
70
92
  "head",
@@ -108,7 +130,7 @@ export function isBuiltinTool(tool: ToolInfo) {
108
130
  export function classifyPlanModeTool(tool: ToolInfo): PlanModeToolPolicy {
109
131
  if (!isBuiltinTool(tool)) return "user-opt-in";
110
132
  if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return "blocked";
111
- if (tool.name === "bash") return "limited";
133
+ if (tool.name === "bash" || tool.name === "powershell") return "limited";
112
134
  return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? "read-only" : "blocked";
113
135
  }
114
136
 
@@ -134,6 +156,119 @@ export function isSafeCommand(command: string, safeSubcommands: SafeSubcommands
134
156
  return findBlockedCommandSegment(command, safeSubcommands) === undefined;
135
157
  }
136
158
 
159
+ export function findBlockedPowerShellCommandSegment(
160
+ command: string,
161
+ safeSubcommands: SafeSubcommands = {},
162
+ ): string | undefined {
163
+ const segments = splitPowerShellSegments(command);
164
+ if (!segments || segments.length === 0) return command.trim() || "(empty command)";
165
+ return segments.find((segment) => !isSafePowerShellSegment(segment, safeSubcommands));
166
+ }
167
+
168
+ export function isSafePowerShellCommand(command: string, safeSubcommands: SafeSubcommands = {}) {
169
+ return findBlockedPowerShellCommandSegment(command, safeSubcommands) === undefined;
170
+ }
171
+
172
+ function splitPowerShellSegments(command: string): string[] | undefined {
173
+ const trimmed = command.trim();
174
+ if (!trimmed || /[\n\r`\u2018-\u201e]/.test(trimmed)) return undefined;
175
+
176
+ const segments: string[] = [];
177
+ let quote: "'" | '"' | undefined;
178
+ let start = 0;
179
+ for (let index = 0; index < trimmed.length; index += 1) {
180
+ const character = trimmed[index];
181
+ if (quote === "'") {
182
+ if (character !== "'") continue;
183
+ if (trimmed[index + 1] === "'") {
184
+ index += 1;
185
+ continue;
186
+ }
187
+ quote = undefined;
188
+ continue;
189
+ }
190
+ if (quote === '"') {
191
+ if (character === "$" || character === "`") return undefined;
192
+ if (character === '"') quote = undefined;
193
+ continue;
194
+ }
195
+ if (character === "'" || character === '"') {
196
+ quote = character;
197
+ continue;
198
+ }
199
+ if (["$", "@", "#", "!", "?", "{", "}", "(", ")", "[", "]", ">", "<"].includes(character)) {
200
+ return undefined;
201
+ }
202
+ const next = trimmed[index + 1];
203
+ if (character === "&" || (character === "|" && next === "|")) return undefined;
204
+ const separatorLength = character === ";" || character === "|" ? 1 : 0;
205
+ if (separatorLength === 0) continue;
206
+ const segment = trimmed.slice(start, index).trim();
207
+ if (!segment) return undefined;
208
+ segments.push(segment);
209
+ index += separatorLength - 1;
210
+ start = index + 1;
211
+ }
212
+ if (quote) return undefined;
213
+ const finalSegment = trimmed.slice(start).trim();
214
+ if (!finalSegment) return undefined;
215
+ segments.push(finalSegment);
216
+ return segments;
217
+ }
218
+
219
+ function isSafePowerShellSegment(segment: string, safeSubcommands: SafeSubcommands) {
220
+ const tokens = powerShellWords(segment);
221
+ if (!tokens || tokens.length === 0 || tokens.includes("--%")) return false;
222
+ const command = tokens[0]?.toLowerCase();
223
+ if (!command) return false;
224
+ const args = tokens.slice(1);
225
+ if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
226
+ if (command !== "git" && command !== "gh") return false;
227
+ return isSafeStructuredCommand(command, args, safeSubcommands);
228
+ }
229
+
230
+ function powerShellWords(segment: string): string[] | undefined {
231
+ const words: string[] = [];
232
+ let word = "";
233
+ let hasWord = false;
234
+ let quote: "'" | '"' | undefined;
235
+ for (let index = 0; index < segment.length; index += 1) {
236
+ const character = segment[index];
237
+ if (quote === "'") {
238
+ if (character !== "'") {
239
+ word += character;
240
+ continue;
241
+ }
242
+ if (segment[index + 1] === "'") {
243
+ word += "'";
244
+ index += 1;
245
+ continue;
246
+ }
247
+ quote = undefined;
248
+ continue;
249
+ }
250
+ if (quote === '"') {
251
+ if (character === '"') quote = undefined;
252
+ else word += character;
253
+ continue;
254
+ }
255
+ if (character === "'" || character === '"') {
256
+ quote = character;
257
+ hasWord = true;
258
+ } else if (/\s/.test(character)) {
259
+ if (hasWord) words.push(word);
260
+ word = "";
261
+ hasWord = false;
262
+ } else {
263
+ word += character;
264
+ hasWord = true;
265
+ }
266
+ }
267
+ if (quote) return undefined;
268
+ if (hasWord) words.push(word);
269
+ return words;
270
+ }
271
+
137
272
  function splitShellSegments(command: string): string[] | undefined {
138
273
  const trimmed = command.trim();
139
274
  if (!trimmed || /[\n\r`]/.test(trimmed)) return undefined;
@@ -1,7 +1,4 @@
1
1
  import type { ToolInfo } from "@earendil-works/pi-coding-agent";
2
- import { PLAN_MODE_COMPLETE_TOOL_NAME } from "./completion-tool.js";
3
- import { PLAN_MODE_QUESTION_TOOL_NAME } from "./question-tool.js";
4
- import { withRequiredPlanModeTools } from "./required-tools.js";
5
2
  import {
6
3
  canSelectToolInPlanMode,
7
4
  classifyPlanModeTool,
@@ -76,23 +73,3 @@ export function snapshotPlanModeSelectedNames(
76
73
  : filterAvailableSelectedToolNames(selectedToolNames, tools),
77
74
  );
78
75
  }
79
-
80
- export function snapshotPlanModeToolNames(
81
- tools: ToolInfo[],
82
- selectedNames: ReadonlySet<string>,
83
- selection: PlanModeToolSelectionSnapshot,
84
- ) {
85
- if (
86
- tools.length === 0 &&
87
- selection.selectedToolNames === undefined &&
88
- selection.selectedToolKeys === undefined &&
89
- selection.defaultPlanTools === undefined
90
- ) {
91
- return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
92
- }
93
- return withRequiredPlanModeTools(
94
- tools
95
- .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
96
- .map((tool) => tool.name),
97
- );
98
- }