@narumitw/pi-plan-mode 0.54.0 → 0.55.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.
package/src/plan-mode.ts CHANGED
@@ -27,10 +27,6 @@ import {
27
27
  formatTransferredPlanPrompt,
28
28
  startFreshImplementationFromState,
29
29
  } from "./fresh-implementation.js";
30
- import {
31
- PlanModeHelperVisibilityPolicy,
32
- type PlanModeHelperVisibilitySnapshot,
33
- } from "./helper-tool-visibility.js";
34
30
  import {
35
31
  createImplementationRetentionCoordinator,
36
32
  implementationRetentionPreview,
@@ -65,7 +61,10 @@ import {
65
61
  PLAN_MODE_QUESTION_TOOL_NAME,
66
62
  planModeQuestionCancelled,
67
63
  } from "./question-tool.js";
68
- import { withRequiredPlanModeTools } from "./required-tools.js";
64
+ import {
65
+ assertPlanModeHelperToolsAvailable,
66
+ planModeHelperToolsAvailable,
67
+ } from "./required-tools.js";
69
68
  import {
70
69
  preflightSavedPlanImplementation,
71
70
  savedPlanBlocksNewWorkflow,
@@ -74,17 +73,20 @@ import {
74
73
  awaitPlanModeSettingsWrites,
75
74
  configuredImplementationPlanRetention,
76
75
  configuredPlanModeToggleShortcut,
77
- configuredPlanModeToolVisibility,
78
76
  configuredThinkingLevel,
79
77
  type PlanModeSettings,
80
78
  type PlanModeSettingsPatch,
81
- type PlanModeToolVisibility,
82
79
  planModeSettingsPath,
83
80
  readPlanModeSettings,
84
81
  type UpdatePlanModeSettingsOptions,
85
82
  updatePlanModeSettings,
86
83
  } from "./settings.js";
87
- import { type PlanCompletionSource, type PlanModeState, restorePlanModeState } from "./state.js";
84
+ import {
85
+ type PlanCompletionSource,
86
+ type PlanModeState,
87
+ type PlanModeWorkflowToolPolicy,
88
+ restorePlanModeState,
89
+ } from "./state.js";
88
90
  import {
89
91
  canSelectToolInPlanMode,
90
92
  classifyPlanModeTool,
@@ -92,12 +94,7 @@ import {
92
94
  findBlockedPowerShellCommandSegment,
93
95
  readCommand,
94
96
  } from "./tool-policy.js";
95
- import {
96
- compareTools,
97
- filterAvailableSelectedToolNames,
98
- snapshotPlanModeSelectedNames,
99
- toolPolicyLabel,
100
- } from "./tool-selection.js";
97
+ import { compareTools, snapshotPlanModeSelectedNames, toolPolicyLabel } from "./tool-selection.js";
101
98
  import { WorkflowMutex, type WorkflowMutexOwner } from "./workflow-mutex.js";
102
99
 
103
100
  const STATE_ENTRY_TYPE = "plan-mode-state";
@@ -109,6 +106,10 @@ interface ReadyPresentationIntent {
109
106
  plan: string;
110
107
  source: PlanCompletionSource;
111
108
  }
109
+ interface PendingWorkflowToolPolicy {
110
+ generation: number;
111
+ mode: "resolve" | "revalidate";
112
+ }
112
113
  type InteractiveUi = typeof import("./interactive-ui.js");
113
114
 
114
115
  interface PlanModeDependencies {
@@ -125,7 +126,6 @@ interface PlanModeDependencies {
125
126
  // activation path cannot bypass the same atomic transition by crossing module-owned state.
126
127
  export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {
127
128
  const workflowMutex = new WorkflowMutex(pi);
128
- const helperVisibility = new PlanModeHelperVisibilityPolicy(pi);
129
129
  let workflowOwner: WorkflowMutexOwner | undefined;
130
130
  let currentSession: object | undefined;
131
131
  let currentSessionContext: ExtensionContext | undefined;
@@ -145,8 +145,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
145
145
  let settings: PlanModeSettings = { thinkingLevel: "inherit" };
146
146
  let toggleShortcut: ReturnType<typeof configuredPlanModeToggleShortcut>;
147
147
  const clearPlanModeShortcutHandler = () => {};
148
- let activeToolBaseline: string[] = [];
149
148
  let workflowAllowedToolNames: string[] | undefined;
149
+ let pendingWorkflowToolPolicy: PendingWorkflowToolPolicy | undefined;
150
150
  let publishedContractMode: PlanModeContract | undefined;
151
151
  let modeContractsRelevant = false;
152
152
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
@@ -197,11 +197,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
197
197
  name: PLAN_MODE_QUESTION_TOOL_NAME,
198
198
  label: "Plan question",
199
199
  description:
200
- "Ask the user one to three Plan-mode clarification questions with meaningful options, then wait for the answer. Only available while Plan mode is active.",
201
- promptSnippet: "Ask user decision questions while Plan mode is active",
202
- promptGuidelines: [
203
- "In Plan mode, use plan_mode_question for important preferences, tradeoffs, or assumptions that cannot be discovered from read-only exploration.",
204
- ],
200
+ "Ask one to three structured questions only when the latest effective Plan contract explicitly says /plan mode is active. Tool visibility alone does not activate Plan mode. Never call for ordinary planning requests, the writing-plans skill, roadmaps, checklists, or plan-file work.",
205
201
  parameters: PLAN_MODE_QUESTION_PARAMS,
206
202
  async execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {
207
203
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
@@ -243,11 +239,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
243
239
  name: PLAN_MODE_COMPLETE_TOOL_NAME,
244
240
  label: "Complete plan",
245
241
  description:
246
- "Submit the complete decision-ready implementation plan for user review. Only available while Plan mode is active, and must be the final standalone action.",
247
- promptSnippet: "Submit the final Plan-mode implementation plan",
248
- promptGuidelines: [
249
- "Call plan_mode_complete alone as the final action only after the implementation plan is decision-complete.",
250
- ],
242
+ "Submit a decision-ready plan only when the latest effective Plan contract explicitly says /plan mode is active, and call it alone as the final action. Tool visibility alone does not activate Plan mode. Never call for ordinary planning requests, the writing-plans skill, roadmaps, checklists, or plan-file work.",
251
243
  parameters: PLAN_MODE_COMPLETE_PARAMS,
252
244
  renderResult: renderPlanModeCompletion,
253
245
  async execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {
@@ -388,21 +380,15 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
388
380
  generation: number,
389
381
  ctx: ExtensionContext | undefined,
390
382
  showWarnings: boolean,
391
- applyWatchedVisibility = false,
392
383
  ) => {
393
384
  const loadedSettings = await readPlanModeRuntimeSettings();
394
385
  if (generation !== menuGeneration || menuController.signal.aborted) {
395
386
  return undefined;
396
387
  }
397
- const previousSettings = settings;
398
- const nextSettings =
388
+ settings =
399
389
  loadedSettings.kind === "loaded"
400
390
  ? loadedSettings.settings
401
391
  : ({ thinkingLevel: "inherit" } satisfies PlanModeSettings);
402
- if (applyWatchedVisibility && ctx) {
403
- applyWatchedHelperVisibility(previousSettings, nextSettings, ctx);
404
- }
405
- settings = nextSettings;
406
392
  applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
407
393
  if (!ctx || !showWarnings) return loadedSettings;
408
394
  if (loadedSettings.kind === "invalid") {
@@ -430,7 +416,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
430
416
  }
431
417
  settingsReloadTimer = setTimeout(() => {
432
418
  settingsReloadTimer = undefined;
433
- void applyPlanModeSettings(generation, currentSessionContext, false, true);
419
+ void applyPlanModeSettings(generation, currentSessionContext, false);
434
420
  }, 75);
435
421
  };
436
422
 
@@ -457,19 +443,18 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
457
443
 
458
444
  pi.on("session_start", async (event, ctx) => {
459
445
  const generation = ++menuGeneration;
460
- const previousToolVisibility = configuredPlanModeToolVisibility(settings);
461
446
  finalizationRequest.reset();
462
447
  currentSession = ctx.sessionManager;
463
448
  currentSessionContext = ctx;
464
449
  workflowOwner = undefined;
465
450
  workflowMutex.bindSession(ctx.sessionManager);
466
- captureToolBaseline();
467
451
  refreshStateBeforeFirstAgentStart = event.reason === "new";
468
452
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
469
453
  menuController = new AbortController();
470
454
  readyPresentationIntent = undefined;
471
455
  latestCommandContext = undefined;
472
456
  workflowAllowedToolNames = undefined;
457
+ pendingWorkflowToolPolicy = undefined;
473
458
  implementationRetention.reset();
474
459
  settings = { thinkingLevel: "inherit" };
475
460
  const branch = ctx.sessionManager.getBranch();
@@ -479,12 +464,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
479
464
  await applyPlanModeSettings(generation, ctx, true);
480
465
  if (generation !== menuGeneration || menuController.signal.aborted) return;
481
466
  startPlanModeSettingsWatch(generation);
482
- if (restoredState.enabled) {
483
- if (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;
484
- } else {
485
- reconcileInactiveHelperVisibility(previousToolVisibility, ctx);
486
- if (!installRestoredState(restoredState, ctx)) return;
487
- }
467
+ if (!installRestoredState(restoredState, ctx)) return;
488
468
  implementationRetention.restore(state.activeImplementation);
489
469
  updateUi(ctx);
490
470
  });
@@ -541,6 +521,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
541
521
  readyPresentationIntent = undefined;
542
522
  latestCommandContext = undefined;
543
523
  refreshStateBeforeFirstAgentStart = false;
524
+ workflowAllowedToolNames = undefined;
525
+ pendingWorkflowToolPolicy = undefined;
544
526
  implementationRetention.reset();
545
527
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
546
528
  if (currentSession !== undefined && currentSession !== shutdownSession) {
@@ -636,6 +618,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
636
618
  });
637
619
 
638
620
  pi.on("context", async (event, ctx) => {
621
+ resolvePendingWorkflowToolPolicy(ctx);
639
622
  const result = implementationRetention.transformContext(event.messages, state);
640
623
  if (result.clearActiveImplementationId) {
641
624
  clearActiveImplementation(result.clearActiveImplementationId, ctx);
@@ -750,16 +733,13 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
750
733
  workflowOwner = owner;
751
734
 
752
735
  const previousState = state;
753
- const previousHelperVisibility = helperVisibility.snapshot();
754
736
  try {
755
- helperVisibility.prepareActivation(ctx);
737
+ assertPlanModeHelperToolsAvailable(safeGetActiveTools());
756
738
  if (!publishModeContract("plan", ctx)) {
757
- helperVisibility.restore(previousHelperVisibility);
758
739
  releaseWorkflowOwner();
759
740
  return false;
760
741
  }
761
742
  } catch (error: unknown) {
762
- helperVisibility.restore(previousHelperVisibility);
763
743
  releaseWorkflowOwner();
764
744
  return reportHelperActivationFailure(ctx, error);
765
745
  }
@@ -775,13 +755,13 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
775
755
  selectedToolNames: candidate.selectedToolNames,
776
756
  selectedToolKeys: candidate.selectedToolKeys,
777
757
  };
778
- workflowAllowedToolNames = computePlanModePolicyToolNames();
758
+ beginWorkflowToolPolicy();
779
759
  applyPlanThinkingLevel();
780
760
  persistState();
781
761
  updateUi(ctx);
782
762
  return true;
783
763
  } catch (error: unknown) {
784
- rollbackNewActivation(previousState, ctx, undefined, previousHelperVisibility);
764
+ rollbackNewActivation(previousState, ctx);
785
765
  throw error;
786
766
  }
787
767
  }
@@ -789,7 +769,6 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
789
769
  function enterPlanModeWithPrompt(prompt: string, ctx: ExtensionContext) {
790
770
  const previousState = state;
791
771
  const previousOwner = workflowOwner;
792
- const previousHelperVisibility = helperVisibility.snapshot();
793
772
  const wasEnabled = state.enabled;
794
773
  if (!enterPlanMode(ctx)) return;
795
774
  if (!wasEnabled) {
@@ -797,7 +776,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
797
776
  }
798
777
  if (sendPlanModeUserMessage(prompt, ctx)) return;
799
778
  if (wasEnabled) return;
800
- rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);
779
+ rollbackNewActivation(previousState, ctx, previousOwner);
801
780
  }
802
781
 
803
782
  function exitPlanMode(ctx: ExtensionContext) {
@@ -817,6 +796,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
817
796
  awaitingAction: false,
818
797
  savedPlan: undefined,
819
798
  activeImplementation: undefined,
799
+ workflowToolPolicy: undefined,
820
800
  manualThinkingLevel: undefined,
821
801
  };
822
802
  if (wasEnabled) {
@@ -967,6 +947,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
967
947
  awaitingAction: false,
968
948
  savedPlan: { plan, source },
969
949
  activeImplementation: undefined,
950
+ workflowToolPolicy: undefined,
970
951
  manualThinkingLevel: undefined,
971
952
  };
972
953
  restoreThinkingLevel();
@@ -1036,6 +1017,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1036
1017
  startedAt: Date.now(),
1037
1018
  retention,
1038
1019
  },
1020
+ workflowToolPolicy: undefined,
1039
1021
  manualThinkingLevel: undefined,
1040
1022
  };
1041
1023
  if (wasEnabled) {
@@ -1055,8 +1037,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1055
1037
  state = previousState;
1056
1038
  readyPresentationIntent = previousIntent;
1057
1039
  if (wasEnabled) {
1040
+ restoreWorkflowToolPolicy(state.workflowToolPolicy);
1058
1041
  publishModeContract("plan", ctx);
1059
- workflowAllowedToolNames = computePlanModePolicyToolNames();
1060
1042
  applyPlanThinkingLevel();
1061
1043
  }
1062
1044
  persistState();
@@ -1096,40 +1078,88 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1096
1078
  const ui = await loadInteractiveUi();
1097
1079
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
1098
1080
  const tools = selectableTools();
1081
+ const activeToolNames = new Set(safeGetActiveTools());
1082
+ const initialSelectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
1083
+ const retainsInactiveSelection =
1084
+ state.selectedToolNames !== undefined ||
1085
+ state.selectedToolKeys !== undefined ||
1086
+ settings.defaultPlanTools !== undefined;
1087
+ const retainedInactiveNames = retainsInactiveSelection
1088
+ ? initialSelectedNames
1089
+ : new Set<string>();
1090
+ const registeredNames = new Set(tools.map((tool) => tool.name));
1091
+ const pendingNames = Array.from(retainedInactiveNames).filter(
1092
+ (name) => !registeredNames.has(name),
1093
+ );
1099
1094
  await ui.showPlanLaunchMenu(ctx, {
1100
- statusText: helperVisibility.toolsAvailable()
1101
- ? "Status: Off — Plan helper tools are visible for this runtime."
1102
- : "Status: Off — Plan helper tools load on the first Plan start.",
1095
+ statusText: planModeHelperToolsAvailable(safeGetActiveTools())
1096
+ ? "Status: Off — visible Plan helpers stay inactive until /plan starts."
1097
+ : "Status: Off — required Plan helpers are unavailable under the active tool policy.",
1103
1098
  initialScreen,
1104
1099
  getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
1105
1100
  toolSummary: (selectedNames) => {
1106
1101
  const allowed = tools
1107
1102
  .filter(
1108
1103
  (tool) =>
1109
- toolIsActive(tool.name) &&
1104
+ activeToolNames.has(tool.name) &&
1110
1105
  selectedNames.has(tool.name) &&
1111
1106
  canSelectToolInPlanMode(tool),
1112
1107
  )
1113
1108
  .map((tool) => tool.name);
1114
- return `Plan policy will allow: ${allowed.length > 0 ? allowed.join(", ") : "none"}.`;
1109
+ const pending = pendingNames
1110
+ .filter((name) => selectedNames.has(name))
1111
+ .map(terminalToolName);
1112
+ const visiblePending = pending.slice(0, 3);
1113
+ const pendingSuffix =
1114
+ pending.length > visiblePending.length
1115
+ ? `, +${pending.length - visiblePending.length} more`
1116
+ : "";
1117
+ return [
1118
+ `Plan policy will allow: ${allowed.length > 0 ? allowed.join(", ") : "none"}.`,
1119
+ ...(pending.length > 0
1120
+ ? [`Pending registration: ${visiblePending.join(", ")}${pendingSuffix}.`]
1121
+ : []),
1122
+ ].join(" ");
1115
1123
  },
1116
- tools: tools.map((tool) => {
1117
- const selectable = canSelectToolInPlanMode(tool);
1118
- const active = toolIsActive(tool.name);
1119
- const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
1120
- const description = tool.description ?? "No description available";
1121
- return {
1122
- name: tool.name,
1123
- description: `${policy} · ${description}`,
1124
- searchText: [policy, description].join(" "),
1125
- disabled: !selectable || !active,
1126
- disabledReason: !active
1127
- ? "Not active in Pi; Plan mode will not activate it"
1128
- : selectable
1129
- ? undefined
1130
- : "Blocked by Plan-mode policy",
1131
- };
1132
- }),
1124
+ tools: [
1125
+ ...tools.map((tool) => {
1126
+ const selectable = canSelectToolInPlanMode(tool);
1127
+ const active = activeToolNames.has(tool.name);
1128
+ const retained = retainedInactiveNames.has(tool.name);
1129
+ const policy = active
1130
+ ? toolPolicyLabel(tool)
1131
+ : retained
1132
+ ? "not active yet; retained for first-request resolution"
1133
+ : "not active in this Pi session";
1134
+ const description = tool.description ?? "No description available";
1135
+ return {
1136
+ name: tool.name,
1137
+ description: `${policy} · ${description}`,
1138
+ searchText: [policy, description].join(" "),
1139
+ disabled: !selectable || !active,
1140
+ disabledReason: !active
1141
+ ? retained
1142
+ ? "Not active yet; retained and resolved before the first request"
1143
+ : "Not active in Pi; Plan mode will not activate it"
1144
+ : selectable
1145
+ ? undefined
1146
+ : "Blocked by Plan-mode policy",
1147
+ };
1148
+ }),
1149
+ ...pendingNames.map((name) => {
1150
+ const label = terminalToolName(name);
1151
+ return {
1152
+ name,
1153
+ label,
1154
+ description:
1155
+ "pending registration · Retained and resolved before the first Plan request",
1156
+ searchText: `${label} pending registration retained first Plan request`,
1157
+ disabled: true,
1158
+ disabledReason:
1159
+ "Not registered yet; Plan mode will not activate it and will resolve it before the first request",
1160
+ };
1161
+ }),
1162
+ ],
1133
1163
  ...lifecycle,
1134
1164
  start: (signal) => {
1135
1165
  if (signal.aborted || !lifecycle.isCurrent()) return;
@@ -1142,7 +1172,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1142
1172
  },
1143
1173
  startWithTools: (names, signal) => {
1144
1174
  if (signal.aborted || !lifecycle.isCurrent()) return;
1145
- const selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());
1175
+ const selectedToolNames = Array.from(
1176
+ new Set(
1177
+ names.filter((name) => activeToolNames.has(name) || retainedInactiveNames.has(name)),
1178
+ ),
1179
+ );
1146
1180
  if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: undefined })) {
1147
1181
  ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1148
1182
  }
@@ -1192,11 +1226,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1192
1226
  if (!isCurrent() || signal.aborted) return false;
1193
1227
  const result = await ui.showPlanModeSettings(ctx, {
1194
1228
  tools: selectableTools(),
1195
- activeToolNames: activeToolBaseline,
1229
+ activeToolNames: safeGetActiveTools(),
1196
1230
  signal,
1197
1231
  isCurrent,
1198
1232
  settingsPath: dependencies.settingsPath,
1199
- updateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),
1233
+ updateSettings: dependencies.updateSettings ?? updatePlanModeSettings,
1200
1234
  onSaved: (saved) => {
1201
1235
  if (!isCurrent()) return;
1202
1236
  settings = saved;
@@ -1209,63 +1243,6 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1209
1243
  return result.kind === "closed" && "reason" in result && result.reason === "close";
1210
1244
  }
1211
1245
 
1212
- async function updateSettingsWithRuntime(
1213
- patch: PlanModeSettingsPatch,
1214
- options: UpdatePlanModeSettingsOptions | undefined,
1215
- ctx: ExtensionContext,
1216
- isCurrent: () => boolean,
1217
- ) {
1218
- const previousVisibility = configuredPlanModeToolVisibility(settings);
1219
- const nextVisibility = patch.toolVisibility ?? previousVisibility;
1220
- const persistSettings = dependencies.updateSettings ?? updatePlanModeSettings;
1221
- if (nextVisibility === previousVisibility) {
1222
- return persistSettings(patch, options);
1223
- }
1224
- if (!ctx.isIdle()) {
1225
- throw new Error("Wait for Pi to become idle before changing Plan tool visibility.");
1226
- }
1227
- bindWorkflowSessionIfNeeded(ctx);
1228
- const applicationSession = ctx.sessionManager;
1229
- const applicationGeneration = menuGeneration;
1230
- const applicationIsCurrent = () =>
1231
- currentSession === applicationSession &&
1232
- menuGeneration === applicationGeneration &&
1233
- isCurrent();
1234
- const retainedOwner = workflowMutex.isOwner(workflowOwner);
1235
- const temporaryOwner = retainedOwner ? workflowOwner : workflowMutex.acquire();
1236
- if (!temporaryOwner) {
1237
- throw new Error(
1238
- "Another workflow is active in this session. Plan tool visibility was not changed.",
1239
- );
1240
- }
1241
- const visibilitySnapshot = helperVisibility.snapshot();
1242
- try {
1243
- helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
1244
- const saved = await persistSettings(patch, options);
1245
- if (!applicationIsCurrent()) {
1246
- throw new DOMException("Plan settings session replaced", "AbortError");
1247
- }
1248
- settings = saved;
1249
- applyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));
1250
- return saved;
1251
- } catch (error) {
1252
- if (applicationIsCurrent()) {
1253
- try {
1254
- helperVisibility.restore(visibilitySnapshot);
1255
- } catch (rollbackError) {
1256
- throw new AggregateError(
1257
- [error, rollbackError],
1258
- "Plan tool visibility settings failed and runtime rollback was incomplete.",
1259
- );
1260
- }
1261
- }
1262
- throw error;
1263
- } finally {
1264
- if (!retainedOwner) workflowMutex.release(temporaryOwner);
1265
- if (!isCurrent()) latestCommandContext = undefined;
1266
- }
1267
- }
1268
-
1269
1246
  function allowModeTransition(ctx: ExtensionContext, action: string) {
1270
1247
  if (ctx.isIdle()) return true;
1271
1248
  const message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;
@@ -1276,6 +1253,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1276
1253
 
1277
1254
  function advanceWorkflowGeneration() {
1278
1255
  workflowGeneration += 1;
1256
+ pendingWorkflowToolPolicy = undefined;
1279
1257
  finalizationRequest.reset();
1280
1258
  }
1281
1259
 
@@ -1301,94 +1279,143 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1301
1279
  };
1302
1280
  }
1303
1281
 
1304
- function captureToolBaseline() {
1305
- activeToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());
1282
+ function planModePolicyToolNames() {
1283
+ if (state.enabled) return workflowAllowedToolNames ?? [];
1284
+ return computePlanModePolicyToolNames();
1306
1285
  }
1307
1286
 
1308
- function applyWatchedHelperVisibility(
1309
- previousSettings: PlanModeSettings,
1310
- nextSettings: PlanModeSettings,
1311
- ctx: ExtensionContext,
1312
- ) {
1313
- const previousVisibility = configuredPlanModeToolVisibility(previousSettings);
1314
- const nextVisibility = configuredPlanModeToolVisibility(nextSettings);
1315
- if (previousVisibility === nextVisibility) return;
1316
- if (state.enabled) {
1317
- helperVisibility.deferVisibilityChange(nextVisibility);
1318
- return;
1319
- }
1320
- try {
1321
- if (!ctx.isIdle()) {
1322
- helperVisibility.deferVisibilityChange(nextVisibility);
1323
- return;
1324
- }
1325
- } catch {
1326
- helperVisibility.deferVisibilityChange(nextVisibility);
1287
+ function beginWorkflowToolPolicy() {
1288
+ const kind = toolPolicySelectionIsExplicit() ? "explicit" : "automatic";
1289
+ const desiredNames = desiredPlanModeToolNames();
1290
+ const allowedNames = resolvePlanModePolicyToolNames(desiredNames);
1291
+ const policy: PlanModeWorkflowToolPolicy = {
1292
+ kind,
1293
+ ...(kind === "explicit" ? { desiredNames } : {}),
1294
+ allowedNames,
1295
+ resolved: false,
1296
+ };
1297
+ state = { ...state, workflowToolPolicy: policy };
1298
+ pendingWorkflowToolPolicy = { generation: workflowGeneration, mode: "resolve" };
1299
+ workflowAllowedToolNames = allowedNames;
1300
+ }
1301
+
1302
+ function resolvePendingWorkflowToolPolicy(ctx: ExtensionContext) {
1303
+ const pending = pendingWorkflowToolPolicy;
1304
+ if (!pending) return;
1305
+ if (
1306
+ pending.generation !== workflowGeneration ||
1307
+ !state.enabled ||
1308
+ !workflowMutex.isOwner(workflowOwner)
1309
+ ) {
1310
+ pendingWorkflowToolPolicy = undefined;
1327
1311
  return;
1328
1312
  }
1329
- const owner = workflowMutex.acquire();
1330
- if (!owner) {
1331
- helperVisibility.deferVisibilityChange(nextVisibility);
1313
+ const policy = state.workflowToolPolicy;
1314
+ const expectedResolved = pending.mode === "revalidate";
1315
+ if (!policy || policy.resolved !== expectedResolved) {
1316
+ pendingWorkflowToolPolicy = undefined;
1332
1317
  return;
1333
1318
  }
1334
- const snapshot = helperVisibility.snapshot();
1335
- try {
1336
- helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
1337
- } catch (error: unknown) {
1338
- helperVisibility.restore(snapshot);
1339
- helperVisibility.deferVisibilityChange(nextVisibility);
1340
- if (ctx.hasUI) {
1341
- const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1342
- ctx.ui.notify(
1343
- `Could not apply reloaded Plan tool visibility; the current tool envelope remains unchanged until a later safe boundary: ${detail}`,
1344
- "warning",
1345
- );
1346
- }
1347
- } finally {
1348
- workflowMutex.release(owner);
1319
+ const allowedNames =
1320
+ pending.mode === "resolve"
1321
+ ? resolveWorkflowToolPolicy(policy)
1322
+ : revalidateFrozenWorkflowToolPolicy(policy);
1323
+ const policyChanged = !policy.resolved || !arrayEquals(policy.allowedNames, allowedNames);
1324
+ workflowAllowedToolNames = allowedNames;
1325
+ state = {
1326
+ ...state,
1327
+ workflowToolPolicy: { ...policy, allowedNames, resolved: true },
1328
+ };
1329
+ pendingWorkflowToolPolicy = undefined;
1330
+ if (policyChanged) persistState();
1331
+ updateUi(ctx);
1332
+ }
1333
+
1334
+ function toolPolicySelectionIsExplicit() {
1335
+ return (
1336
+ state.selectedToolNames !== undefined ||
1337
+ state.selectedToolKeys !== undefined ||
1338
+ settings.defaultPlanTools !== undefined
1339
+ );
1340
+ }
1341
+
1342
+ function desiredPlanModeToolNames() {
1343
+ const tools = activePlanPolicyTools();
1344
+ return Array.from(snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()));
1345
+ }
1346
+
1347
+ function automaticPlanModeToolNames() {
1348
+ return Array.from(snapshotPlanModeSelectedNames(activePlanPolicyTools(), {}));
1349
+ }
1350
+
1351
+ function resolveWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy) {
1352
+ return resolvePlanModePolicyToolNames(
1353
+ policy.kind === "automatic" ? automaticPlanModeToolNames() : (policy.desiredNames ?? []),
1354
+ );
1355
+ }
1356
+
1357
+ function revalidateFrozenWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy) {
1358
+ const currentlyAllowed = new Set(
1359
+ policy.kind === "automatic"
1360
+ ? resolvePlanModePolicyToolNames(automaticPlanModeToolNames())
1361
+ : resolvePlanModePolicyToolNames(policy.allowedNames),
1362
+ );
1363
+ return policy.allowedNames.filter((name) => currentlyAllowed.has(name));
1364
+ }
1365
+
1366
+ function restoreWorkflowToolPolicy(policy: PlanModeWorkflowToolPolicy | undefined) {
1367
+ let nextPolicy: PlanModeWorkflowToolPolicy;
1368
+ if (!policy) {
1369
+ const kind = toolPolicySelectionIsExplicit() ? "explicit" : "automatic";
1370
+ const desiredNames = desiredPlanModeToolNames();
1371
+ nextPolicy = {
1372
+ kind,
1373
+ ...(kind === "explicit" ? { desiredNames } : {}),
1374
+ allowedNames: resolvePlanModePolicyToolNames(desiredNames),
1375
+ resolved: true,
1376
+ };
1377
+ } else if (policy.resolved) {
1378
+ nextPolicy = policy;
1379
+ } else {
1380
+ nextPolicy = {
1381
+ ...policy,
1382
+ allowedNames: resolveWorkflowToolPolicy(policy),
1383
+ };
1349
1384
  }
1385
+ state = { ...state, workflowToolPolicy: nextPolicy };
1386
+ workflowAllowedToolNames = nextPolicy.resolved
1387
+ ? revalidateFrozenWorkflowToolPolicy(nextPolicy)
1388
+ : nextPolicy.allowedNames;
1389
+ pendingWorkflowToolPolicy = {
1390
+ generation: workflowGeneration,
1391
+ mode: nextPolicy.resolved ? "revalidate" : "resolve",
1392
+ };
1393
+ return !workflowToolPoliciesEqual(policy, nextPolicy);
1350
1394
  }
1351
1395
 
1352
- function reconcileInactiveHelperVisibility(
1353
- previousVisibility: PlanModeToolVisibility,
1354
- ctx: ExtensionContext,
1396
+ function workflowToolPoliciesEqual(
1397
+ left: PlanModeWorkflowToolPolicy | undefined,
1398
+ right: PlanModeWorkflowToolPolicy,
1355
1399
  ) {
1356
- const owner = workflowMutex.acquire();
1357
- if (!owner) {
1358
- if (ctx.hasUI) {
1359
- ctx.ui.notify(
1360
- "Plan tool visibility was deferred because another workflow is active in this session.",
1361
- "warning",
1362
- );
1363
- }
1364
- return false;
1365
- }
1366
- const snapshot = helperVisibility.snapshot();
1367
- try {
1368
- const visibility = configuredPlanModeToolVisibility(settings);
1369
- helperVisibility.prepareSessionStart(visibility, previousVisibility);
1370
- helperVisibility.reconcileInactiveState(visibility);
1371
- return true;
1372
- } catch (error: unknown) {
1373
- helperVisibility.restore(snapshot);
1374
- if (ctx.hasUI) {
1375
- const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1376
- ctx.ui.notify(`Could not apply Plan tool visibility: ${detail}`, "error");
1377
- }
1378
- return false;
1379
- } finally {
1380
- workflowMutex.release(owner);
1381
- }
1400
+ return (
1401
+ left?.kind === right.kind &&
1402
+ left.resolved === right.resolved &&
1403
+ arrayEquals(left.allowedNames, right.allowedNames) &&
1404
+ arrayEquals(left.desiredNames ?? [], right.desiredNames ?? [])
1405
+ );
1382
1406
  }
1383
1407
 
1384
- function planModePolicyToolNames() {
1385
- return workflowAllowedToolNames ?? computePlanModePolicyToolNames();
1408
+ function arrayEquals(left: readonly string[], right: readonly string[]) {
1409
+ return left.length === right.length && left.every((value, index) => value === right[index]);
1386
1410
  }
1387
1411
 
1388
1412
  function computePlanModePolicyToolNames() {
1389
- const tools = activePlanPolicyTools();
1390
- const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
1391
- return tools
1413
+ return resolvePlanModePolicyToolNames(desiredPlanModeToolNames());
1414
+ }
1415
+
1416
+ function resolvePlanModePolicyToolNames(desiredNames: readonly string[]) {
1417
+ const selectedNames = new Set(desiredNames);
1418
+ return activePlanPolicyTools()
1392
1419
  .filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool))
1393
1420
  .map((tool) => tool.name);
1394
1421
  }
@@ -1411,14 +1438,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1411
1438
  }
1412
1439
 
1413
1440
  function activePlanPolicyTools() {
1414
- const activeNames = new Set(activeToolBaseline);
1441
+ const activeNames = new Set(safeGetActiveTools());
1415
1442
  return selectableTools().filter((tool) => activeNames.has(tool.name));
1416
1443
  }
1417
1444
 
1418
- function toolIsActive(toolName: string) {
1419
- return activeToolBaseline.includes(toolName);
1420
- }
1421
-
1422
1445
  function safeGetAllTools() {
1423
1446
  try {
1424
1447
  return pi.getAllTools();
@@ -1482,21 +1505,18 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1482
1505
  }
1483
1506
  }
1484
1507
 
1485
- function installRestoredState(
1486
- candidate: PlanModeState,
1487
- ctx: ExtensionContext,
1488
- previousToolVisibility?: PlanModeToolVisibility,
1489
- ) {
1508
+ function installRestoredState(candidate: PlanModeState, ctx: ExtensionContext) {
1490
1509
  const previousState = state;
1491
1510
  const previousWorkflowAllowedToolNames = workflowAllowedToolNames;
1511
+ const previousPendingWorkflowToolPolicy = pendingWorkflowToolPolicy;
1492
1512
  const previousOwner = workflowOwner;
1493
- const previousHelperVisibility = helperVisibility.snapshot();
1494
1513
  const wasEnabled = state.enabled;
1495
1514
  if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
1496
1515
  const owner = workflowMutex.acquire();
1497
1516
  if (!owner) {
1498
1517
  state = { enabled: false, awaitingAction: false };
1499
1518
  workflowAllowedToolNames = undefined;
1519
+ pendingWorkflowToolPolicy = undefined;
1500
1520
  reportRestoredWorkflowBusy(ctx);
1501
1521
  return false;
1502
1522
  }
@@ -1505,24 +1525,18 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1505
1525
 
1506
1526
  try {
1507
1527
  if (candidate.enabled) {
1508
- const visibility = configuredPlanModeToolVisibility(settings);
1509
- if (previousToolVisibility === undefined) {
1510
- helperVisibility.prepareActivation(ctx);
1511
- } else {
1512
- try {
1513
- helperVisibility.prepareSessionStart(visibility, previousToolVisibility);
1514
- helperVisibility.prepareActivation(ctx);
1515
- } catch {
1516
- helperVisibility.restore(previousHelperVisibility);
1517
- state = { enabled: false, awaitingAction: false };
1518
- workflowAllowedToolNames = undefined;
1519
- if (workflowOwner !== previousOwner) {
1520
- workflowMutex.release(workflowOwner);
1521
- workflowOwner = previousOwner;
1522
- }
1523
- reportRestoredHelpersUnavailable(ctx);
1524
- return false;
1528
+ try {
1529
+ assertPlanModeHelperToolsAvailable(safeGetActiveTools());
1530
+ } catch {
1531
+ state = { enabled: false, awaitingAction: false };
1532
+ workflowAllowedToolNames = undefined;
1533
+ pendingWorkflowToolPolicy = undefined;
1534
+ if (workflowOwner !== previousOwner) {
1535
+ workflowMutex.release(workflowOwner);
1536
+ workflowOwner = previousOwner;
1525
1537
  }
1538
+ reportRestoredHelpersUnavailable(ctx);
1539
+ return false;
1526
1540
  }
1527
1541
  }
1528
1542
  if (wasEnabled && !candidate.enabled) {
@@ -1530,7 +1544,14 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1530
1544
  restoreThinkingLevel();
1531
1545
  }
1532
1546
  state = candidate;
1533
- workflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : undefined;
1547
+ const policyChanged = state.enabled
1548
+ ? restoreWorkflowToolPolicy(state.workflowToolPolicy)
1549
+ : false;
1550
+ if (!state.enabled) {
1551
+ workflowAllowedToolNames = undefined;
1552
+ pendingWorkflowToolPolicy = undefined;
1553
+ }
1554
+ if (policyChanged) persistState();
1534
1555
  if (state.enabled) applyPlanThinkingLevel();
1535
1556
  else if (wasEnabled) releaseWorkflowOwner();
1536
1557
  return true;
@@ -1540,7 +1561,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1540
1561
  } finally {
1541
1562
  state = previousState;
1542
1563
  workflowAllowedToolNames = previousWorkflowAllowedToolNames;
1543
- helperVisibility.restore(previousHelperVisibility);
1564
+ pendingWorkflowToolPolicy = previousPendingWorkflowToolPolicy;
1544
1565
  if (workflowOwner !== previousOwner) {
1545
1566
  workflowMutex.release(workflowOwner);
1546
1567
  workflowOwner = previousOwner;
@@ -1554,7 +1575,6 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1554
1575
  previousState: PlanModeState,
1555
1576
  ctx: ExtensionContext,
1556
1577
  previousOwner?: WorkflowMutexOwner,
1557
- previousHelperVisibility?: PlanModeHelperVisibilitySnapshot,
1558
1578
  ) {
1559
1579
  const activatedOwner = workflowOwner;
1560
1580
  readyPresentationIntent = undefined;
@@ -1566,8 +1586,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1566
1586
  } finally {
1567
1587
  state = previousState;
1568
1588
  workflowAllowedToolNames = undefined;
1589
+ pendingWorkflowToolPolicy = undefined;
1569
1590
  try {
1570
- if (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);
1571
1591
  persistState();
1572
1592
  updateUi(ctx);
1573
1593
  } finally {
@@ -1648,6 +1668,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1648
1668
  return safeGetAllTools().find((candidate) => candidate.name === toolName);
1649
1669
  }
1650
1670
 
1671
+ function terminalToolName(value: string) {
1672
+ const safe = safeTerminalText(value) || "(unnamed tool)";
1673
+ return safe.length > 120 ? `${safe.slice(0, 119)}…` : safe;
1674
+ }
1675
+
1651
1676
  function safeTerminalText(value: string) {
1652
1677
  return [...value]
1653
1678
  .map((character) => {