@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/dist/index.ts CHANGED
@@ -16,11 +16,9 @@ import {
16
16
  configuredImplementationPlanRetention,
17
17
  configuredPlanExportPath,
18
18
  configuredPlanModeToggleShortcut,
19
- configuredPlanModeToolVisibility,
20
19
  configuredThinkingLevel,
21
20
  createImplementationRetentionCoordinator,
22
21
  exportStoredPlan,
23
- filterAvailableSelectedToolNames,
24
22
  findBlockedCommandSegment,
25
23
  findBlockedPowerShellCommandSegment,
26
24
  implementationRetentionPreview,
@@ -41,9 +39,8 @@ import {
41
39
  renderPlanModeCompletion,
42
40
  snapshotPlanModeSelectedNames,
43
41
  toolPolicyLabel,
44
- unique,
45
42
  updatePlanModeSettings
46
- } from "./chunks/chunk-U5CQ7RQX.js";
43
+ } from "./chunks/chunk-AS76FCC5.js";
47
44
 
48
45
  // src/plan-mode.ts
49
46
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -443,114 +440,6 @@ function safeErrorDetail(error) {
443
440
  return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
444
441
  }
445
442
 
446
- // src/helper-tool-visibility.ts
447
- var PLAN_MODE_HELPER_TOOL_NAMES = [
448
- PLAN_MODE_QUESTION_TOOL_NAME,
449
- PLAN_MODE_COMPLETE_TOOL_NAME
450
- ];
451
- var PlanModeHelperVisibilityPolicy = class {
452
- constructor(pi) {
453
- this.pi = pi;
454
- }
455
- pi;
456
- unlocked = false;
457
- hiddenByPolicy = /* @__PURE__ */ new Set();
458
- isUnlocked() {
459
- return this.unlocked;
460
- }
461
- hasHiddenTools() {
462
- return this.hiddenByPolicy.size > 0;
463
- }
464
- toolsAvailable() {
465
- const active = new Set(this.pi.getActiveTools());
466
- return PLAN_MODE_HELPER_TOOL_NAMES.every((name) => active.has(name));
467
- }
468
- prepareSessionStart(visibility, previous) {
469
- if (visibility === "after-first-plan" && previous === "always") this.lock();
470
- if (visibility === "always") this.reveal();
471
- }
472
- reconcileInactiveState(visibility) {
473
- if (visibility === "after-first-plan" && !this.unlocked) this.hideIfLocked();
474
- }
475
- deferVisibilityChange(visibility) {
476
- if (visibility === "after-first-plan") this.lock();
477
- }
478
- prepareActivation(ctx) {
479
- if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
480
- throw new Error("wait until Pi is idle before revealing the Plan tools");
481
- }
482
- this.reveal();
483
- }
484
- applyVisibilityChange(previous, next, ctx) {
485
- if (previous === next) return;
486
- if (next === "always") {
487
- if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
488
- throw new Error("Wait for Pi to become idle before revealing Plan tools.");
489
- }
490
- this.reveal();
491
- return;
492
- }
493
- if (ctx.isIdle?.() !== true) {
494
- throw new Error("Wait for Pi to become idle before hiding Plan tools.");
495
- }
496
- this.lock();
497
- this.hideIfLocked();
498
- }
499
- hideIfLocked() {
500
- if (this.unlocked) return;
501
- const active = this.pi.getActiveTools();
502
- const hidden = active.filter((name) => this.isHelperTool(name));
503
- if (hidden.length === 0) return;
504
- this.pi.setActiveTools(active.filter((name) => !this.isHelperTool(name)));
505
- for (const name of hidden) this.hiddenByPolicy.add(name);
506
- }
507
- snapshot() {
508
- return {
509
- activeTools: this.pi.getActiveTools(),
510
- helperToolsUnlocked: this.unlocked,
511
- helperToolsHiddenByPolicy: [...this.hiddenByPolicy]
512
- };
513
- }
514
- restore(snapshot) {
515
- this.pi.setActiveTools(snapshot.activeTools);
516
- this.unlocked = snapshot.helperToolsUnlocked;
517
- this.hiddenByPolicy.clear();
518
- for (const name of snapshot.helperToolsHiddenByPolicy) this.hiddenByPolicy.add(name);
519
- }
520
- reveal() {
521
- const snapshot = this.snapshot();
522
- try {
523
- const active = this.pi.getActiveTools();
524
- const canonical = [
525
- ...active.filter((name) => !this.isHelperTool(name)),
526
- ...PLAN_MODE_HELPER_TOOL_NAMES
527
- ];
528
- if (canonical.length !== active.length || canonical.some((name, index) => name !== active[index])) {
529
- this.pi.setActiveTools(canonical);
530
- }
531
- if (!this.toolsAvailable()) {
532
- throw new Error(
533
- "plan_mode_question and plan_mode_complete are unavailable; leave the restrictive tool mode before starting Plan mode"
534
- );
535
- }
536
- this.unlockAndForgetHidden();
537
- } catch (error) {
538
- this.restore(snapshot);
539
- throw error;
540
- }
541
- }
542
- lock() {
543
- this.unlocked = false;
544
- }
545
- unlockAndForgetHidden() {
546
- this.unlocked = true;
547
- this.hiddenByPolicy.clear();
548
- }
549
- isHelperTool(name) {
550
- return PLAN_MODE_HELPER_TOOL_NAMES.includes(name);
551
- }
552
- };
553
-
554
443
  // src/plan-action-controller.ts
555
444
  function createPlanActionController(options) {
556
445
  const freshAction = (ctx, lifecycle, signal) => options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);
@@ -759,16 +648,18 @@ function formatStatus(state) {
759
648
  }
760
649
 
761
650
  // src/required-tools.ts
762
- function withRequiredPlanModeTools(toolNames) {
763
- return unique([
764
- ...withoutRequiredPlanModeTools(toolNames),
765
- PLAN_MODE_QUESTION_TOOL_NAME,
766
- PLAN_MODE_COMPLETE_TOOL_NAME
767
- ]);
651
+ var REQUIRED_PLAN_MODE_TOOL_NAMES = [
652
+ PLAN_MODE_QUESTION_TOOL_NAME,
653
+ PLAN_MODE_COMPLETE_TOOL_NAME
654
+ ];
655
+ function planModeHelperToolsAvailable(toolNames) {
656
+ const active = new Set(toolNames);
657
+ return REQUIRED_PLAN_MODE_TOOL_NAMES.every((name) => active.has(name));
768
658
  }
769
- function withoutRequiredPlanModeTools(toolNames) {
770
- return toolNames.filter(
771
- (toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME
659
+ function assertPlanModeHelperToolsAvailable(toolNames) {
660
+ if (planModeHelperToolsAvailable(toolNames)) return;
661
+ throw new Error(
662
+ "plan_mode_question and plan_mode_complete are unavailable; include them in the active tool allowlist or leave the restrictive tool mode before starting Plan mode"
772
663
  );
773
664
  }
774
665
 
@@ -835,11 +726,30 @@ function restorePlanModeState(entries, stateEntryType) {
835
726
  activeImplementation,
836
727
  selectedToolNames: stringArray(entry.data.selectedToolNames),
837
728
  selectedToolKeys: stringArray(entry.data.selectedToolKeys),
729
+ workflowToolPolicy: enabled ? normalizeWorkflowToolPolicy(entry.data.workflowToolPolicy) : void 0,
838
730
  previousThinkingLevel: enabled ? fixedThinkingLevel(entry.data.previousThinkingLevel) : void 0,
839
731
  appliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : void 0,
840
732
  manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : void 0
841
733
  };
842
734
  }
735
+ function normalizeWorkflowToolPolicy(value) {
736
+ if (value === void 0) return void 0;
737
+ const denied = {
738
+ kind: "automatic",
739
+ allowedNames: [],
740
+ resolved: true
741
+ };
742
+ if (!isRecord(value)) return denied;
743
+ const kind = value.kind === "automatic" || value.kind === "explicit" ? value.kind : void 0;
744
+ const allowedNames = stringArray(value.allowedNames);
745
+ if (!kind || !allowedNames || typeof value.resolved !== "boolean") return denied;
746
+ if (kind === "automatic") {
747
+ return { kind, allowedNames, resolved: value.resolved };
748
+ }
749
+ const desiredNames = stringArray(value.desiredNames);
750
+ if (!desiredNames) return denied;
751
+ return { kind, desiredNames, allowedNames, resolved: value.resolved };
752
+ }
843
753
  function normalizeSavedPlan(value) {
844
754
  if (!isRecord(value)) return void 0;
845
755
  const source = planCompletionSource(value.source);
@@ -957,7 +867,6 @@ var BLOCKED_MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "update_p
957
867
  var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
958
868
  function planMode(pi, dependencies = {}) {
959
869
  const workflowMutex = new WorkflowMutex(pi);
960
- const helperVisibility = new PlanModeHelperVisibilityPolicy(pi);
961
870
  let workflowOwner;
962
871
  let currentSession;
963
872
  let currentSessionContext;
@@ -965,7 +874,7 @@ function planMode(pi, dependencies = {}) {
965
874
  const loadInteractiveUi = () => {
966
875
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
967
876
  if (!interactiveUiPromise) {
968
- interactiveUiPromise = import("./chunks/interactive-ui-W3VYAJIQ.js").catch((error) => {
877
+ interactiveUiPromise = import("./chunks/interactive-ui-UCL5UIJN.js").catch((error) => {
969
878
  interactiveUiPromise = void 0;
970
879
  throw error;
971
880
  });
@@ -978,8 +887,8 @@ function planMode(pi, dependencies = {}) {
978
887
  let toggleShortcut;
979
888
  const clearPlanModeShortcutHandler = () => {
980
889
  };
981
- let activeToolBaseline = [];
982
890
  let workflowAllowedToolNames;
891
+ let pendingWorkflowToolPolicy;
983
892
  let publishedContractMode;
984
893
  let modeContractsRelevant = false;
985
894
  let readyPresentationIntent;
@@ -1028,11 +937,7 @@ function planMode(pi, dependencies = {}) {
1028
937
  pi.registerTool({
1029
938
  name: PLAN_MODE_QUESTION_TOOL_NAME,
1030
939
  label: "Plan question",
1031
- description: "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.",
1032
- promptSnippet: "Ask user decision questions while Plan mode is active",
1033
- promptGuidelines: [
1034
- "In Plan mode, use plan_mode_question for important preferences, tradeoffs, or assumptions that cannot be discovered from read-only exploration."
1035
- ],
940
+ description: "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.",
1036
941
  parameters: PLAN_MODE_QUESTION_PARAMS,
1037
942
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1038
943
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
@@ -1066,11 +971,7 @@ function planMode(pi, dependencies = {}) {
1066
971
  pi.registerTool({
1067
972
  name: PLAN_MODE_COMPLETE_TOOL_NAME,
1068
973
  label: "Complete plan",
1069
- description: "Submit the complete decision-ready implementation plan for user review. Only available while Plan mode is active, and must be the final standalone action.",
1070
- promptSnippet: "Submit the final Plan-mode implementation plan",
1071
- promptGuidelines: [
1072
- "Call plan_mode_complete alone as the final action only after the implementation plan is decision-complete."
1073
- ],
974
+ description: "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.",
1074
975
  parameters: PLAN_MODE_COMPLETE_PARAMS,
1075
976
  renderResult: renderPlanModeCompletion,
1076
977
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
@@ -1199,17 +1100,12 @@ function planMode(pi, dependencies = {}) {
1199
1100
  const readPlanModeRuntimeSettings = async () => {
1200
1101
  return dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);
1201
1102
  };
1202
- const applyPlanModeSettings = async (generation, ctx, showWarnings, applyWatchedVisibility = false) => {
1103
+ const applyPlanModeSettings = async (generation, ctx, showWarnings) => {
1203
1104
  const loadedSettings = await readPlanModeRuntimeSettings();
1204
1105
  if (generation !== menuGeneration || menuController.signal.aborted) {
1205
1106
  return void 0;
1206
1107
  }
1207
- const previousSettings = settings;
1208
- const nextSettings = loadedSettings.kind === "loaded" ? loadedSettings.settings : { thinkingLevel: "inherit" };
1209
- if (applyWatchedVisibility && ctx) {
1210
- applyWatchedHelperVisibility(previousSettings, nextSettings, ctx);
1211
- }
1212
- settings = nextSettings;
1108
+ settings = loadedSettings.kind === "loaded" ? loadedSettings.settings : { thinkingLevel: "inherit" };
1213
1109
  applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
1214
1110
  if (!ctx || !showWarnings) return loadedSettings;
1215
1111
  if (loadedSettings.kind === "invalid") {
@@ -1235,7 +1131,7 @@ function planMode(pi, dependencies = {}) {
1235
1131
  }
1236
1132
  settingsReloadTimer = setTimeout(() => {
1237
1133
  settingsReloadTimer = void 0;
1238
- void applyPlanModeSettings(generation, currentSessionContext, false, true);
1134
+ void applyPlanModeSettings(generation, currentSessionContext, false);
1239
1135
  }, 75);
1240
1136
  };
1241
1137
  const startPlanModeSettingsWatch = (generation) => {
@@ -1260,19 +1156,18 @@ function planMode(pi, dependencies = {}) {
1260
1156
  };
1261
1157
  pi.on("session_start", async (event, ctx) => {
1262
1158
  const generation = ++menuGeneration;
1263
- const previousToolVisibility = configuredPlanModeToolVisibility(settings);
1264
1159
  finalizationRequest.reset();
1265
1160
  currentSession = ctx.sessionManager;
1266
1161
  currentSessionContext = ctx;
1267
1162
  workflowOwner = void 0;
1268
1163
  workflowMutex.bindSession(ctx.sessionManager);
1269
- captureToolBaseline();
1270
1164
  refreshStateBeforeFirstAgentStart = event.reason === "new";
1271
1165
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
1272
1166
  menuController = new AbortController();
1273
1167
  readyPresentationIntent = void 0;
1274
1168
  latestCommandContext = void 0;
1275
1169
  workflowAllowedToolNames = void 0;
1170
+ pendingWorkflowToolPolicy = void 0;
1276
1171
  implementationRetention.reset();
1277
1172
  settings = { thinkingLevel: "inherit" };
1278
1173
  const branch = ctx.sessionManager.getBranch();
@@ -1282,12 +1177,7 @@ function planMode(pi, dependencies = {}) {
1282
1177
  await applyPlanModeSettings(generation, ctx, true);
1283
1178
  if (generation !== menuGeneration || menuController.signal.aborted) return;
1284
1179
  startPlanModeSettingsWatch(generation);
1285
- if (restoredState.enabled) {
1286
- if (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;
1287
- } else {
1288
- reconcileInactiveHelperVisibility(previousToolVisibility, ctx);
1289
- if (!installRestoredState(restoredState, ctx)) return;
1290
- }
1180
+ if (!installRestoredState(restoredState, ctx)) return;
1291
1181
  implementationRetention.restore(state.activeImplementation);
1292
1182
  updateUi(ctx);
1293
1183
  });
@@ -1340,6 +1230,8 @@ function planMode(pi, dependencies = {}) {
1340
1230
  readyPresentationIntent = void 0;
1341
1231
  latestCommandContext = void 0;
1342
1232
  refreshStateBeforeFirstAgentStart = false;
1233
+ workflowAllowedToolNames = void 0;
1234
+ pendingWorkflowToolPolicy = void 0;
1343
1235
  implementationRetention.reset();
1344
1236
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
1345
1237
  if (currentSession !== void 0 && currentSession !== shutdownSession) {
@@ -1424,6 +1316,7 @@ Blocked command: ${blocked}`
1424
1316
  }
1425
1317
  });
1426
1318
  pi.on("context", async (event, ctx) => {
1319
+ resolvePendingWorkflowToolPolicy(ctx);
1427
1320
  const result = implementationRetention.transformContext(event.messages, state);
1428
1321
  if (result.clearActiveImplementationId) {
1429
1322
  clearActiveImplementation(result.clearActiveImplementationId, ctx);
@@ -1521,16 +1414,13 @@ ${intent.plan}`,
1521
1414
  if (!owner) return reportWorkflowBusy(ctx);
1522
1415
  workflowOwner = owner;
1523
1416
  const previousState = state;
1524
- const previousHelperVisibility = helperVisibility.snapshot();
1525
1417
  try {
1526
- helperVisibility.prepareActivation(ctx);
1418
+ assertPlanModeHelperToolsAvailable(safeGetActiveTools());
1527
1419
  if (!publishModeContract("plan", ctx)) {
1528
- helperVisibility.restore(previousHelperVisibility);
1529
1420
  releaseWorkflowOwner();
1530
1421
  return false;
1531
1422
  }
1532
1423
  } catch (error) {
1533
- helperVisibility.restore(previousHelperVisibility);
1534
1424
  releaseWorkflowOwner();
1535
1425
  return reportHelperActivationFailure(ctx, error);
1536
1426
  }
@@ -1546,20 +1436,19 @@ ${intent.plan}`,
1546
1436
  selectedToolNames: candidate.selectedToolNames,
1547
1437
  selectedToolKeys: candidate.selectedToolKeys
1548
1438
  };
1549
- workflowAllowedToolNames = computePlanModePolicyToolNames();
1439
+ beginWorkflowToolPolicy();
1550
1440
  applyPlanThinkingLevel();
1551
1441
  persistState();
1552
1442
  updateUi(ctx);
1553
1443
  return true;
1554
1444
  } catch (error) {
1555
- rollbackNewActivation(previousState, ctx, void 0, previousHelperVisibility);
1445
+ rollbackNewActivation(previousState, ctx);
1556
1446
  throw error;
1557
1447
  }
1558
1448
  }
1559
1449
  function enterPlanModeWithPrompt(prompt, ctx) {
1560
1450
  const previousState = state;
1561
1451
  const previousOwner = workflowOwner;
1562
- const previousHelperVisibility = helperVisibility.snapshot();
1563
1452
  const wasEnabled = state.enabled;
1564
1453
  if (!enterPlanMode(ctx)) return;
1565
1454
  if (!wasEnabled) {
@@ -1567,7 +1456,7 @@ ${intent.plan}`,
1567
1456
  }
1568
1457
  if (sendPlanModeUserMessage(prompt, ctx)) return;
1569
1458
  if (wasEnabled) return;
1570
- rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);
1459
+ rollbackNewActivation(previousState, ctx, previousOwner);
1571
1460
  }
1572
1461
  function exitPlanMode(ctx) {
1573
1462
  if (!allowModeTransition(ctx, "leave or clear Plan mode")) return false;
@@ -1586,6 +1475,7 @@ ${intent.plan}`,
1586
1475
  awaitingAction: false,
1587
1476
  savedPlan: void 0,
1588
1477
  activeImplementation: void 0,
1478
+ workflowToolPolicy: void 0,
1589
1479
  manualThinkingLevel: void 0
1590
1480
  };
1591
1481
  if (wasEnabled) {
@@ -1704,6 +1594,7 @@ ${intent.plan}`,
1704
1594
  awaitingAction: false,
1705
1595
  savedPlan: { plan, source },
1706
1596
  activeImplementation: void 0,
1597
+ workflowToolPolicy: void 0,
1707
1598
  manualThinkingLevel: void 0
1708
1599
  };
1709
1600
  restoreThinkingLevel();
@@ -1762,6 +1653,7 @@ ${intent.plan}`,
1762
1653
  startedAt: Date.now(),
1763
1654
  retention
1764
1655
  },
1656
+ workflowToolPolicy: void 0,
1765
1657
  manualThinkingLevel: void 0
1766
1658
  };
1767
1659
  if (wasEnabled) {
@@ -1776,8 +1668,8 @@ ${intent.plan}`,
1776
1668
  state = previousState;
1777
1669
  readyPresentationIntent = previousIntent;
1778
1670
  if (wasEnabled) {
1671
+ restoreWorkflowToolPolicy(state.workflowToolPolicy);
1779
1672
  publishModeContract("plan", ctx);
1780
- workflowAllowedToolNames = computePlanModePolicyToolNames();
1781
1673
  applyPlanThinkingLevel();
1782
1674
  }
1783
1675
  persistState();
@@ -1809,29 +1701,57 @@ ${intent.plan}`,
1809
1701
  const ui = await loadInteractiveUi();
1810
1702
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
1811
1703
  const tools = selectableTools();
1704
+ const activeToolNames = new Set(safeGetActiveTools());
1705
+ const initialSelectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
1706
+ const retainsInactiveSelection = state.selectedToolNames !== void 0 || state.selectedToolKeys !== void 0 || settings.defaultPlanTools !== void 0;
1707
+ const retainedInactiveNames = retainsInactiveSelection ? initialSelectedNames : /* @__PURE__ */ new Set();
1708
+ const registeredNames = new Set(tools.map((tool) => tool.name));
1709
+ const pendingNames = Array.from(retainedInactiveNames).filter(
1710
+ (name) => !registeredNames.has(name)
1711
+ );
1812
1712
  await ui.showPlanLaunchMenu(ctx, {
1813
- statusText: helperVisibility.toolsAvailable() ? "Status: Off \u2014 Plan helper tools are visible for this runtime." : "Status: Off \u2014 Plan helper tools load on the first Plan start.",
1713
+ statusText: planModeHelperToolsAvailable(safeGetActiveTools()) ? "Status: Off \u2014 visible Plan helpers stay inactive until /plan starts." : "Status: Off \u2014 required Plan helpers are unavailable under the active tool policy.",
1814
1714
  initialScreen,
1815
1715
  getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
1816
1716
  toolSummary: (selectedNames) => {
1817
1717
  const allowed = tools.filter(
1818
- (tool) => toolIsActive(tool.name) && selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)
1718
+ (tool) => activeToolNames.has(tool.name) && selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)
1819
1719
  ).map((tool) => tool.name);
1820
- return `Plan policy will allow: ${allowed.length > 0 ? allowed.join(", ") : "none"}.`;
1720
+ const pending = pendingNames.filter((name) => selectedNames.has(name)).map(terminalToolName);
1721
+ const visiblePending = pending.slice(0, 3);
1722
+ const pendingSuffix = pending.length > visiblePending.length ? `, +${pending.length - visiblePending.length} more` : "";
1723
+ return [
1724
+ `Plan policy will allow: ${allowed.length > 0 ? allowed.join(", ") : "none"}.`,
1725
+ ...pending.length > 0 ? [`Pending registration: ${visiblePending.join(", ")}${pendingSuffix}.`] : []
1726
+ ].join(" ");
1821
1727
  },
1822
- tools: tools.map((tool) => {
1823
- const selectable = canSelectToolInPlanMode(tool);
1824
- const active = toolIsActive(tool.name);
1825
- const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
1826
- const description = tool.description ?? "No description available";
1827
- return {
1828
- name: tool.name,
1829
- description: `${policy} \xB7 ${description}`,
1830
- searchText: [policy, description].join(" "),
1831
- disabled: !selectable || !active,
1832
- disabledReason: !active ? "Not active in Pi; Plan mode will not activate it" : selectable ? void 0 : "Blocked by Plan-mode policy"
1833
- };
1834
- }),
1728
+ tools: [
1729
+ ...tools.map((tool) => {
1730
+ const selectable = canSelectToolInPlanMode(tool);
1731
+ const active = activeToolNames.has(tool.name);
1732
+ const retained = retainedInactiveNames.has(tool.name);
1733
+ const policy = active ? toolPolicyLabel(tool) : retained ? "not active yet; retained for first-request resolution" : "not active in this Pi session";
1734
+ const description = tool.description ?? "No description available";
1735
+ return {
1736
+ name: tool.name,
1737
+ description: `${policy} \xB7 ${description}`,
1738
+ searchText: [policy, description].join(" "),
1739
+ disabled: !selectable || !active,
1740
+ disabledReason: !active ? retained ? "Not active yet; retained and resolved before the first request" : "Not active in Pi; Plan mode will not activate it" : selectable ? void 0 : "Blocked by Plan-mode policy"
1741
+ };
1742
+ }),
1743
+ ...pendingNames.map((name) => {
1744
+ const label = terminalToolName(name);
1745
+ return {
1746
+ name,
1747
+ label,
1748
+ description: "pending registration \xB7 Retained and resolved before the first Plan request",
1749
+ searchText: `${label} pending registration retained first Plan request`,
1750
+ disabled: true,
1751
+ disabledReason: "Not registered yet; Plan mode will not activate it and will resolve it before the first request"
1752
+ };
1753
+ })
1754
+ ],
1835
1755
  ...lifecycle,
1836
1756
  start: (signal) => {
1837
1757
  if (signal.aborted || !lifecycle.isCurrent()) return;
@@ -1844,7 +1764,11 @@ ${intent.plan}`,
1844
1764
  },
1845
1765
  startWithTools: (names, signal) => {
1846
1766
  if (signal.aborted || !lifecycle.isCurrent()) return;
1847
- const selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());
1767
+ const selectedToolNames = Array.from(
1768
+ new Set(
1769
+ names.filter((name) => activeToolNames.has(name) || retainedInactiveNames.has(name))
1770
+ )
1771
+ );
1848
1772
  if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: void 0 })) {
1849
1773
  ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1850
1774
  }
@@ -1888,11 +1812,11 @@ ${intent.plan}`,
1888
1812
  if (!isCurrent() || signal.aborted) return false;
1889
1813
  const result = await ui.showPlanModeSettings(ctx, {
1890
1814
  tools: selectableTools(),
1891
- activeToolNames: activeToolBaseline,
1815
+ activeToolNames: safeGetActiveTools(),
1892
1816
  signal,
1893
1817
  isCurrent,
1894
1818
  settingsPath: dependencies.settingsPath,
1895
- updateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),
1819
+ updateSettings: dependencies.updateSettings ?? updatePlanModeSettings,
1896
1820
  onSaved: (saved) => {
1897
1821
  if (!isCurrent()) return;
1898
1822
  settings = saved;
@@ -1902,54 +1826,6 @@ ${intent.plan}`,
1902
1826
  });
1903
1827
  return result.kind === "closed" && "reason" in result && result.reason === "close";
1904
1828
  }
1905
- async function updateSettingsWithRuntime(patch, options, ctx, isCurrent) {
1906
- const previousVisibility = configuredPlanModeToolVisibility(settings);
1907
- const nextVisibility = patch.toolVisibility ?? previousVisibility;
1908
- const persistSettings = dependencies.updateSettings ?? updatePlanModeSettings;
1909
- if (nextVisibility === previousVisibility) {
1910
- return persistSettings(patch, options);
1911
- }
1912
- if (!ctx.isIdle()) {
1913
- throw new Error("Wait for Pi to become idle before changing Plan tool visibility.");
1914
- }
1915
- bindWorkflowSessionIfNeeded(ctx);
1916
- const applicationSession = ctx.sessionManager;
1917
- const applicationGeneration = menuGeneration;
1918
- const applicationIsCurrent = () => currentSession === applicationSession && menuGeneration === applicationGeneration && isCurrent();
1919
- const retainedOwner = workflowMutex.isOwner(workflowOwner);
1920
- const temporaryOwner = retainedOwner ? workflowOwner : workflowMutex.acquire();
1921
- if (!temporaryOwner) {
1922
- throw new Error(
1923
- "Another workflow is active in this session. Plan tool visibility was not changed."
1924
- );
1925
- }
1926
- const visibilitySnapshot = helperVisibility.snapshot();
1927
- try {
1928
- helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
1929
- const saved = await persistSettings(patch, options);
1930
- if (!applicationIsCurrent()) {
1931
- throw new DOMException("Plan settings session replaced", "AbortError");
1932
- }
1933
- settings = saved;
1934
- applyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));
1935
- return saved;
1936
- } catch (error) {
1937
- if (applicationIsCurrent()) {
1938
- try {
1939
- helperVisibility.restore(visibilitySnapshot);
1940
- } catch (rollbackError) {
1941
- throw new AggregateError(
1942
- [error, rollbackError],
1943
- "Plan tool visibility settings failed and runtime rollback was incomplete."
1944
- );
1945
- }
1946
- }
1947
- throw error;
1948
- } finally {
1949
- if (!retainedOwner) workflowMutex.release(temporaryOwner);
1950
- if (!isCurrent()) latestCommandContext = void 0;
1951
- }
1952
- }
1953
1829
  function allowModeTransition(ctx, action) {
1954
1830
  if (ctx.isIdle()) return true;
1955
1831
  const message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;
@@ -1959,6 +1835,7 @@ ${intent.plan}`,
1959
1835
  }
1960
1836
  function advanceWorkflowGeneration() {
1961
1837
  workflowGeneration += 1;
1838
+ pendingWorkflowToolPolicy = void 0;
1962
1839
  finalizationRequest.reset();
1963
1840
  }
1964
1841
  function finalizationRunOutcome(messages) {
@@ -1977,83 +1854,108 @@ ${intent.plan}`,
1977
1854
  isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted && (!state.enabled || workflowMutex.isOwner(owner))
1978
1855
  };
1979
1856
  }
1980
- function captureToolBaseline() {
1981
- activeToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());
1982
- }
1983
- function applyWatchedHelperVisibility(previousSettings, nextSettings, ctx) {
1984
- const previousVisibility = configuredPlanModeToolVisibility(previousSettings);
1985
- const nextVisibility = configuredPlanModeToolVisibility(nextSettings);
1986
- if (previousVisibility === nextVisibility) return;
1987
- if (state.enabled) {
1988
- helperVisibility.deferVisibilityChange(nextVisibility);
1989
- return;
1990
- }
1991
- try {
1992
- if (!ctx.isIdle()) {
1993
- helperVisibility.deferVisibilityChange(nextVisibility);
1994
- return;
1995
- }
1996
- } catch {
1997
- helperVisibility.deferVisibilityChange(nextVisibility);
1857
+ function planModePolicyToolNames() {
1858
+ if (state.enabled) return workflowAllowedToolNames ?? [];
1859
+ return computePlanModePolicyToolNames();
1860
+ }
1861
+ function beginWorkflowToolPolicy() {
1862
+ const kind = toolPolicySelectionIsExplicit() ? "explicit" : "automatic";
1863
+ const desiredNames = desiredPlanModeToolNames();
1864
+ const allowedNames = resolvePlanModePolicyToolNames(desiredNames);
1865
+ const policy = {
1866
+ kind,
1867
+ ...kind === "explicit" ? { desiredNames } : {},
1868
+ allowedNames,
1869
+ resolved: false
1870
+ };
1871
+ state = { ...state, workflowToolPolicy: policy };
1872
+ pendingWorkflowToolPolicy = { generation: workflowGeneration, mode: "resolve" };
1873
+ workflowAllowedToolNames = allowedNames;
1874
+ }
1875
+ function resolvePendingWorkflowToolPolicy(ctx) {
1876
+ const pending = pendingWorkflowToolPolicy;
1877
+ if (!pending) return;
1878
+ if (pending.generation !== workflowGeneration || !state.enabled || !workflowMutex.isOwner(workflowOwner)) {
1879
+ pendingWorkflowToolPolicy = void 0;
1998
1880
  return;
1999
1881
  }
2000
- const owner = workflowMutex.acquire();
2001
- if (!owner) {
2002
- helperVisibility.deferVisibilityChange(nextVisibility);
1882
+ const policy = state.workflowToolPolicy;
1883
+ const expectedResolved = pending.mode === "revalidate";
1884
+ if (!policy || policy.resolved !== expectedResolved) {
1885
+ pendingWorkflowToolPolicy = void 0;
2003
1886
  return;
2004
1887
  }
2005
- const snapshot = helperVisibility.snapshot();
2006
- try {
2007
- helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
2008
- } catch (error) {
2009
- helperVisibility.restore(snapshot);
2010
- helperVisibility.deferVisibilityChange(nextVisibility);
2011
- if (ctx.hasUI) {
2012
- const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
2013
- ctx.ui.notify(
2014
- `Could not apply reloaded Plan tool visibility; the current tool envelope remains unchanged until a later safe boundary: ${detail}`,
2015
- "warning"
2016
- );
2017
- }
2018
- } finally {
2019
- workflowMutex.release(owner);
2020
- }
1888
+ const allowedNames = pending.mode === "resolve" ? resolveWorkflowToolPolicy(policy) : revalidateFrozenWorkflowToolPolicy(policy);
1889
+ const policyChanged = !policy.resolved || !arrayEquals(policy.allowedNames, allowedNames);
1890
+ workflowAllowedToolNames = allowedNames;
1891
+ state = {
1892
+ ...state,
1893
+ workflowToolPolicy: { ...policy, allowedNames, resolved: true }
1894
+ };
1895
+ pendingWorkflowToolPolicy = void 0;
1896
+ if (policyChanged) persistState();
1897
+ updateUi(ctx);
2021
1898
  }
2022
- function reconcileInactiveHelperVisibility(previousVisibility, ctx) {
2023
- const owner = workflowMutex.acquire();
2024
- if (!owner) {
2025
- if (ctx.hasUI) {
2026
- ctx.ui.notify(
2027
- "Plan tool visibility was deferred because another workflow is active in this session.",
2028
- "warning"
2029
- );
2030
- }
2031
- return false;
2032
- }
2033
- const snapshot = helperVisibility.snapshot();
2034
- try {
2035
- const visibility = configuredPlanModeToolVisibility(settings);
2036
- helperVisibility.prepareSessionStart(visibility, previousVisibility);
2037
- helperVisibility.reconcileInactiveState(visibility);
2038
- return true;
2039
- } catch (error) {
2040
- helperVisibility.restore(snapshot);
2041
- if (ctx.hasUI) {
2042
- const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
2043
- ctx.ui.notify(`Could not apply Plan tool visibility: ${detail}`, "error");
2044
- }
2045
- return false;
2046
- } finally {
2047
- workflowMutex.release(owner);
1899
+ function toolPolicySelectionIsExplicit() {
1900
+ return state.selectedToolNames !== void 0 || state.selectedToolKeys !== void 0 || settings.defaultPlanTools !== void 0;
1901
+ }
1902
+ function desiredPlanModeToolNames() {
1903
+ const tools = activePlanPolicyTools();
1904
+ return Array.from(snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()));
1905
+ }
1906
+ function automaticPlanModeToolNames() {
1907
+ return Array.from(snapshotPlanModeSelectedNames(activePlanPolicyTools(), {}));
1908
+ }
1909
+ function resolveWorkflowToolPolicy(policy) {
1910
+ return resolvePlanModePolicyToolNames(
1911
+ policy.kind === "automatic" ? automaticPlanModeToolNames() : policy.desiredNames ?? []
1912
+ );
1913
+ }
1914
+ function revalidateFrozenWorkflowToolPolicy(policy) {
1915
+ const currentlyAllowed = new Set(
1916
+ policy.kind === "automatic" ? resolvePlanModePolicyToolNames(automaticPlanModeToolNames()) : resolvePlanModePolicyToolNames(policy.allowedNames)
1917
+ );
1918
+ return policy.allowedNames.filter((name) => currentlyAllowed.has(name));
1919
+ }
1920
+ function restoreWorkflowToolPolicy(policy) {
1921
+ let nextPolicy;
1922
+ if (!policy) {
1923
+ const kind = toolPolicySelectionIsExplicit() ? "explicit" : "automatic";
1924
+ const desiredNames = desiredPlanModeToolNames();
1925
+ nextPolicy = {
1926
+ kind,
1927
+ ...kind === "explicit" ? { desiredNames } : {},
1928
+ allowedNames: resolvePlanModePolicyToolNames(desiredNames),
1929
+ resolved: true
1930
+ };
1931
+ } else if (policy.resolved) {
1932
+ nextPolicy = policy;
1933
+ } else {
1934
+ nextPolicy = {
1935
+ ...policy,
1936
+ allowedNames: resolveWorkflowToolPolicy(policy)
1937
+ };
2048
1938
  }
1939
+ state = { ...state, workflowToolPolicy: nextPolicy };
1940
+ workflowAllowedToolNames = nextPolicy.resolved ? revalidateFrozenWorkflowToolPolicy(nextPolicy) : nextPolicy.allowedNames;
1941
+ pendingWorkflowToolPolicy = {
1942
+ generation: workflowGeneration,
1943
+ mode: nextPolicy.resolved ? "revalidate" : "resolve"
1944
+ };
1945
+ return !workflowToolPoliciesEqual(policy, nextPolicy);
2049
1946
  }
2050
- function planModePolicyToolNames() {
2051
- return workflowAllowedToolNames ?? computePlanModePolicyToolNames();
1947
+ function workflowToolPoliciesEqual(left, right) {
1948
+ return left?.kind === right.kind && left.resolved === right.resolved && arrayEquals(left.allowedNames, right.allowedNames) && arrayEquals(left.desiredNames ?? [], right.desiredNames ?? []);
1949
+ }
1950
+ function arrayEquals(left, right) {
1951
+ return left.length === right.length && left.every((value, index) => value === right[index]);
2052
1952
  }
2053
1953
  function computePlanModePolicyToolNames() {
2054
- const tools = activePlanPolicyTools();
2055
- const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
2056
- return tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name);
1954
+ return resolvePlanModePolicyToolNames(desiredPlanModeToolNames());
1955
+ }
1956
+ function resolvePlanModePolicyToolNames(desiredNames) {
1957
+ const selectedNames = new Set(desiredNames);
1958
+ return activePlanPolicyTools().filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name);
2057
1959
  }
2058
1960
  function toolSelectionSnapshot() {
2059
1961
  return {
@@ -2068,12 +1970,9 @@ ${intent.plan}`,
2068
1970
  ).sort(compareTools);
2069
1971
  }
2070
1972
  function activePlanPolicyTools() {
2071
- const activeNames = new Set(activeToolBaseline);
1973
+ const activeNames = new Set(safeGetActiveTools());
2072
1974
  return selectableTools().filter((tool) => activeNames.has(tool.name));
2073
1975
  }
2074
- function toolIsActive(toolName) {
2075
- return activeToolBaseline.includes(toolName);
2076
- }
2077
1976
  function safeGetAllTools() {
2078
1977
  try {
2079
1978
  return pi.getAllTools();
@@ -2128,17 +2027,18 @@ ${intent.plan}`,
2128
2027
  return DEFAULT_TOOLS;
2129
2028
  }
2130
2029
  }
2131
- function installRestoredState(candidate, ctx, previousToolVisibility) {
2030
+ function installRestoredState(candidate, ctx) {
2132
2031
  const previousState = state;
2133
2032
  const previousWorkflowAllowedToolNames = workflowAllowedToolNames;
2033
+ const previousPendingWorkflowToolPolicy = pendingWorkflowToolPolicy;
2134
2034
  const previousOwner = workflowOwner;
2135
- const previousHelperVisibility = helperVisibility.snapshot();
2136
2035
  const wasEnabled = state.enabled;
2137
2036
  if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
2138
2037
  const owner = workflowMutex.acquire();
2139
2038
  if (!owner) {
2140
2039
  state = { enabled: false, awaitingAction: false };
2141
2040
  workflowAllowedToolNames = void 0;
2041
+ pendingWorkflowToolPolicy = void 0;
2142
2042
  reportRestoredWorkflowBusy(ctx);
2143
2043
  return false;
2144
2044
  }
@@ -2146,24 +2046,18 @@ ${intent.plan}`,
2146
2046
  }
2147
2047
  try {
2148
2048
  if (candidate.enabled) {
2149
- const visibility = configuredPlanModeToolVisibility(settings);
2150
- if (previousToolVisibility === void 0) {
2151
- helperVisibility.prepareActivation(ctx);
2152
- } else {
2153
- try {
2154
- helperVisibility.prepareSessionStart(visibility, previousToolVisibility);
2155
- helperVisibility.prepareActivation(ctx);
2156
- } catch {
2157
- helperVisibility.restore(previousHelperVisibility);
2158
- state = { enabled: false, awaitingAction: false };
2159
- workflowAllowedToolNames = void 0;
2160
- if (workflowOwner !== previousOwner) {
2161
- workflowMutex.release(workflowOwner);
2162
- workflowOwner = previousOwner;
2163
- }
2164
- reportRestoredHelpersUnavailable(ctx);
2165
- return false;
2049
+ try {
2050
+ assertPlanModeHelperToolsAvailable(safeGetActiveTools());
2051
+ } catch {
2052
+ state = { enabled: false, awaitingAction: false };
2053
+ workflowAllowedToolNames = void 0;
2054
+ pendingWorkflowToolPolicy = void 0;
2055
+ if (workflowOwner !== previousOwner) {
2056
+ workflowMutex.release(workflowOwner);
2057
+ workflowOwner = previousOwner;
2166
2058
  }
2059
+ reportRestoredHelpersUnavailable(ctx);
2060
+ return false;
2167
2061
  }
2168
2062
  }
2169
2063
  if (wasEnabled && !candidate.enabled) {
@@ -2171,7 +2065,12 @@ ${intent.plan}`,
2171
2065
  restoreThinkingLevel();
2172
2066
  }
2173
2067
  state = candidate;
2174
- workflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : void 0;
2068
+ const policyChanged = state.enabled ? restoreWorkflowToolPolicy(state.workflowToolPolicy) : false;
2069
+ if (!state.enabled) {
2070
+ workflowAllowedToolNames = void 0;
2071
+ pendingWorkflowToolPolicy = void 0;
2072
+ }
2073
+ if (policyChanged) persistState();
2175
2074
  if (state.enabled) applyPlanThinkingLevel();
2176
2075
  else if (wasEnabled) releaseWorkflowOwner();
2177
2076
  return true;
@@ -2181,7 +2080,7 @@ ${intent.plan}`,
2181
2080
  } finally {
2182
2081
  state = previousState;
2183
2082
  workflowAllowedToolNames = previousWorkflowAllowedToolNames;
2184
- helperVisibility.restore(previousHelperVisibility);
2083
+ pendingWorkflowToolPolicy = previousPendingWorkflowToolPolicy;
2185
2084
  if (workflowOwner !== previousOwner) {
2186
2085
  workflowMutex.release(workflowOwner);
2187
2086
  workflowOwner = previousOwner;
@@ -2190,7 +2089,7 @@ ${intent.plan}`,
2190
2089
  throw error;
2191
2090
  }
2192
2091
  }
2193
- function rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility) {
2092
+ function rollbackNewActivation(previousState, ctx, previousOwner) {
2194
2093
  const activatedOwner = workflowOwner;
2195
2094
  readyPresentationIntent = void 0;
2196
2095
  try {
@@ -2201,8 +2100,8 @@ ${intent.plan}`,
2201
2100
  } finally {
2202
2101
  state = previousState;
2203
2102
  workflowAllowedToolNames = void 0;
2103
+ pendingWorkflowToolPolicy = void 0;
2204
2104
  try {
2205
- if (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);
2206
2105
  persistState();
2207
2106
  updateUi(ctx);
2208
2107
  } finally {
@@ -2270,6 +2169,10 @@ ${intent.plan}`,
2270
2169
  function toolByName(toolName) {
2271
2170
  return safeGetAllTools().find((candidate) => candidate.name === toolName);
2272
2171
  }
2172
+ function terminalToolName(value) {
2173
+ const safe = safeTerminalText(value) || "(unnamed tool)";
2174
+ return safe.length > 120 ? `${safe.slice(0, 119)}\u2026` : safe;
2175
+ }
2273
2176
  function safeTerminalText(value) {
2274
2177
  return [...value].map((character) => {
2275
2178
  const codePoint = character.codePointAt(0) ?? 0;