@narumitw/pi-plan-mode 0.51.0 → 0.52.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.
@@ -17,7 +17,7 @@ import {
17
17
  retentionLabel,
18
18
  toolPolicyLabel,
19
19
  updatePlanModeSettings
20
- } from "./chunk-VMD6XCI5.js";
20
+ } from "./chunk-H3RGWRY7.js";
21
21
 
22
22
  // src/active-implementation-menu.ts
23
23
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
@@ -712,4 +712,4 @@ export {
712
712
  showReadyPlanMenu,
713
713
  showSavedPlanMenu
714
714
  };
715
- //# sourceMappingURL=interactive-ui-ROT43QBA.ts.map
715
+ //# sourceMappingURL=interactive-ui-GFNX5OF4.ts.map
package/dist/index.ts CHANGED
@@ -39,7 +39,7 @@ import {
39
39
  toolPolicyLabel,
40
40
  withRequiredPlanModeTools,
41
41
  withoutRequiredPlanModeTools
42
- } from "./chunks/chunk-VMD6XCI5.js";
42
+ } from "./chunks/chunk-H3RGWRY7.js";
43
43
 
44
44
  // src/plan-mode.ts
45
45
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -592,17 +592,83 @@ function isRecord(value) {
592
592
  return typeof value === "object" && value !== null && !Array.isArray(value);
593
593
  }
594
594
 
595
+ // src/workflow-mutex.ts
596
+ var WORKFLOW_MUTEX_CHANNEL = "workflow:mutex:v1";
597
+ var AGENT_WORKFLOW_GROUP = "agent-workflow";
598
+ var WorkflowMutex = class {
599
+ constructor(pi) {
600
+ this.pi = pi;
601
+ pi.events.on(WORKFLOW_MUTEX_CHANNEL, (payload) => {
602
+ this.answer(payload);
603
+ });
604
+ }
605
+ pi;
606
+ session;
607
+ heldGroups = /* @__PURE__ */ new Map();
608
+ generation = 0;
609
+ bindSession(session) {
610
+ this.generation += 1;
611
+ this.heldGroups.clear();
612
+ this.session = session;
613
+ }
614
+ unbindSession(session) {
615
+ if (this.session !== session) return;
616
+ this.generation += 1;
617
+ this.heldGroups.clear();
618
+ this.session = void 0;
619
+ }
620
+ acquire(group = AGENT_WORKFLOW_GROUP) {
621
+ const session = this.session;
622
+ const generation = this.generation;
623
+ if (!session || this.heldGroups.has(group)) return void 0;
624
+ const attempt = { session, group, busy: false };
625
+ try {
626
+ this.pi.events.emit(WORKFLOW_MUTEX_CHANNEL, attempt);
627
+ } catch {
628
+ return void 0;
629
+ }
630
+ if (this.session !== session || this.generation !== generation || attempt.session !== session || attempt.group !== group || attempt.busy !== false || this.heldGroups.has(group)) {
631
+ return void 0;
632
+ }
633
+ const owner = Symbol(group);
634
+ this.heldGroups.set(group, owner);
635
+ return owner;
636
+ }
637
+ isOwner(owner, group = AGENT_WORKFLOW_GROUP) {
638
+ return owner !== void 0 && this.heldGroups.get(group) === owner;
639
+ }
640
+ release(owner, group = AGENT_WORKFLOW_GROUP) {
641
+ if (!this.isOwner(owner, group)) return;
642
+ this.heldGroups.delete(group);
643
+ }
644
+ answer(payload) {
645
+ try {
646
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
647
+ const attempt = payload;
648
+ if (attempt.session !== this.session) return;
649
+ if (attempt.group !== AGENT_WORKFLOW_GROUP) return;
650
+ if (typeof attempt.busy !== "boolean") return;
651
+ if (!this.heldGroups.has(attempt.group)) return;
652
+ attempt.busy = true;
653
+ } catch {
654
+ }
655
+ }
656
+ };
657
+
595
658
  // src/plan-mode.ts
596
659
  var STATE_ENTRY_TYPE = "plan-mode-state";
597
660
  var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
598
661
  var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
599
662
  var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
600
663
  function planMode(pi, dependencies = {}) {
664
+ const workflowMutex = new WorkflowMutex(pi);
665
+ let workflowOwner;
666
+ let currentSession;
601
667
  let interactiveUiPromise;
602
668
  const loadInteractiveUi = () => {
603
669
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
604
670
  if (!interactiveUiPromise) {
605
- interactiveUiPromise = import("./chunks/interactive-ui-ROT43QBA.js").catch((error) => {
671
+ interactiveUiPromise = import("./chunks/interactive-ui-GFNX5OF4.js").catch((error) => {
606
672
  interactiveUiPromise = void 0;
607
673
  throw error;
608
674
  });
@@ -671,7 +737,7 @@ function planMode(pi, dependencies = {}) {
671
737
  ],
672
738
  parameters: PLAN_MODE_QUESTION_PARAMS,
673
739
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
674
- if (!state.enabled) {
740
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
675
741
  return planModeQuestionCancelled(
676
742
  [],
677
743
  "plan_mode_inactive",
@@ -691,8 +757,9 @@ function planMode(pi, dependencies = {}) {
691
757
  }
692
758
  const sessionGeneration = menuGeneration;
693
759
  const questionWorkflowGeneration = workflowGeneration;
760
+ const questionOwner = workflowOwner;
694
761
  return answerPlanModeQuestions(parsed.questions, ctx, {
695
- isCurrent: () => sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration,
762
+ isCurrent: () => sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration && workflowMutex.isOwner(questionOwner),
696
763
  isEnabled: () => state.enabled
697
764
  });
698
765
  }
@@ -708,7 +775,7 @@ function planMode(pi, dependencies = {}) {
708
775
  parameters: PLAN_MODE_COMPLETE_PARAMS,
709
776
  renderResult: renderPlanModeCompletion,
710
777
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
711
- if (!state.enabled) {
778
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
712
779
  throw new Error("plan_mode_complete is only available while Plan mode is active");
713
780
  }
714
781
  const parsed = normalizePlanModeCompletion(params);
@@ -731,8 +798,12 @@ function planMode(pi, dependencies = {}) {
731
798
  ctx.ui.notify("Plan mode is already active.", "info");
732
799
  return;
733
800
  }
734
- enterPlanMode(ctx);
735
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
801
+ if (enterPlanMode(ctx)) {
802
+ ctx.ui.notify(
803
+ "Plan mode enabled. I will explore and plan, but not modify files.",
804
+ "info"
805
+ );
806
+ }
736
807
  return;
737
808
  }
738
809
  if (command === "show") {
@@ -889,35 +960,35 @@ function planMode(pi, dependencies = {}) {
889
960
  };
890
961
  pi.on("session_start", async (event, ctx) => {
891
962
  const generation = ++menuGeneration;
963
+ currentSession = ctx.sessionManager;
964
+ workflowOwner = void 0;
965
+ workflowMutex.bindSession(ctx.sessionManager);
892
966
  refreshStateBeforeFirstAgentStart = event.reason === "new";
893
967
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
894
968
  menuController = new AbortController();
895
969
  readyPresentationIntent = void 0;
896
970
  latestCommandContext = void 0;
971
+ previousTools = void 0;
897
972
  implementationRetention.reset();
898
973
  settings = { thinkingLevel: "inherit" };
899
- restoreState(ctx);
900
- implementationRetention.restore(state.activeImplementation);
974
+ const restoredState = readRestoredState(ctx);
975
+ state = { enabled: false, awaitingAction: false };
901
976
  await applyPlanModeSettings(generation, ctx, true);
902
977
  if (generation !== menuGeneration || menuController.signal.aborted) return;
903
978
  startPlanModeSettingsWatch(generation);
904
- const persistFlagActivation = pi.getFlag("plan") === true && !state.enabled;
905
- if (persistFlagActivation) {
906
- state = state.savedPlan ? {
907
- ...state,
908
- enabled: true,
909
- latestPlan: state.savedPlan.plan,
910
- latestPlanSource: state.savedPlan.source,
911
- awaitingAction: true,
912
- savedPlan: void 0,
913
- activeImplementation: void 0
914
- } : { ...state, enabled: true, activeImplementation: void 0 };
915
- }
916
- if (state.enabled) {
917
- activatePlanModeTools();
918
- applyPlanThinkingLevel();
919
- } else deactivatePlanModeQuestionTool();
920
- if (persistFlagActivation) persistState();
979
+ const persistFlagActivation = pi.getFlag("plan") === true && !restoredState.enabled;
980
+ const candidate = persistFlagActivation ? restoredState.savedPlan ? {
981
+ ...restoredState,
982
+ enabled: true,
983
+ latestPlan: restoredState.savedPlan.plan,
984
+ latestPlanSource: restoredState.savedPlan.source,
985
+ awaitingAction: true,
986
+ savedPlan: void 0,
987
+ activeImplementation: void 0
988
+ } : { ...restoredState, enabled: true, activeImplementation: void 0 } : restoredState;
989
+ if (!installRestoredState(candidate, ctx)) return;
990
+ implementationRetention.restore(state.activeImplementation);
991
+ if (persistFlagActivation && state.enabled) persistState();
921
992
  updateUi(ctx);
922
993
  });
923
994
  pi.on("thinking_level_select", (event) => {
@@ -933,6 +1004,7 @@ function planMode(pi, dependencies = {}) {
933
1004
  }
934
1005
  });
935
1006
  pi.on("session_shutdown", async (_event, ctx) => {
1007
+ const shutdownSession = ctx.sessionManager;
936
1008
  menuGeneration += 1;
937
1009
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
938
1010
  readyPresentationIntent = void 0;
@@ -940,6 +1012,10 @@ function planMode(pi, dependencies = {}) {
940
1012
  refreshStateBeforeFirstAgentStart = false;
941
1013
  implementationRetention.reset();
942
1014
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
1015
+ if (currentSession !== void 0 && currentSession !== shutdownSession) {
1016
+ workflowMutex.unbindSession(shutdownSession);
1017
+ return;
1018
+ }
943
1019
  captureManualThinkingLevel();
944
1020
  persistState();
945
1021
  if (state.enabled) {
@@ -948,9 +1024,12 @@ function planMode(pi, dependencies = {}) {
948
1024
  }
949
1025
  stopPlanModeSettingsWatch();
950
1026
  clearUi(ctx);
1027
+ releaseWorkflowOwner();
1028
+ workflowMutex.unbindSession(ctx.sessionManager);
1029
+ if (currentSession === ctx.sessionManager) currentSession = void 0;
951
1030
  });
952
1031
  pi.on("tool_call", async (event) => {
953
- if (!state.enabled) return;
1032
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
954
1033
  if (event.toolName === "update_plan") {
955
1034
  return {
956
1035
  block: true,
@@ -990,16 +1069,12 @@ Blocked command: ${blocked}`
990
1069
  pi.on("before_agent_start", (event, ctx) => {
991
1070
  if (refreshStateBeforeFirstAgentStart) {
992
1071
  refreshStateBeforeFirstAgentStart = false;
993
- restoreState(ctx);
994
1072
  implementationRetention.reset();
1073
+ if (!installRestoredState(readRestoredState(ctx), ctx)) return;
995
1074
  implementationRetention.restore(state.activeImplementation);
996
- if (state.enabled) {
997
- activatePlanModeTools();
998
- applyPlanThinkingLevel();
999
- } else deactivatePlanModeQuestionTool();
1000
1075
  updateUi(ctx);
1001
1076
  }
1002
- if (!state.enabled) return;
1077
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1003
1078
  if (state.latestPlan || state.awaitingAction) {
1004
1079
  readyPresentationIntent = void 0;
1005
1080
  state = {
@@ -1019,7 +1094,7 @@ ${buildPlanModePrompt()}`
1019
1094
  };
1020
1095
  });
1021
1096
  pi.on("agent_end", async (event, ctx) => {
1022
- if (!state.enabled) return;
1097
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1023
1098
  const text = latestAssistantText(event.messages);
1024
1099
  const parsedPlan = parseProposedPlan(text);
1025
1100
  if (parsedPlan.kind !== "valid") {
@@ -1061,36 +1136,48 @@ ${intent.plan}`,
1061
1136
  if (!isStaleExtensionContextError(error)) throw error;
1062
1137
  }
1063
1138
  });
1064
- function enterPlanMode(ctx) {
1139
+ function enterPlanMode(ctx, candidate = state) {
1140
+ bindWorkflowSessionIfNeeded(ctx);
1141
+ if (state.enabled) return workflowMutex.isOwner(workflowOwner);
1142
+ const owner = workflowMutex.acquire();
1143
+ if (!owner) return reportWorkflowBusy(ctx);
1144
+ workflowOwner = owner;
1145
+ const previousState = state;
1146
+ const previousToolSnapshot = previousTools;
1065
1147
  workflowGeneration += 1;
1066
- if (!state.enabled) previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
1067
- state = {
1068
- ...state,
1069
- enabled: true,
1070
- awaitingAction: false,
1071
- savedPlan: void 0,
1072
- activeImplementation: void 0
1073
- };
1074
- activatePlanModeTools();
1075
- applyPlanThinkingLevel();
1076
- persistState();
1077
- updateUi(ctx);
1148
+ try {
1149
+ previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
1150
+ state = {
1151
+ ...state,
1152
+ enabled: true,
1153
+ awaitingAction: false,
1154
+ savedPlan: void 0,
1155
+ activeImplementation: void 0,
1156
+ selectedToolNames: candidate.selectedToolNames,
1157
+ selectedToolKeys: candidate.selectedToolKeys
1158
+ };
1159
+ activatePlanModeTools();
1160
+ applyPlanThinkingLevel();
1161
+ persistState();
1162
+ updateUi(ctx);
1163
+ return true;
1164
+ } catch (error) {
1165
+ rollbackNewActivation(previousState, previousToolSnapshot, ctx);
1166
+ throw error;
1167
+ }
1078
1168
  }
1079
1169
  function enterPlanModeWithPrompt(prompt, ctx) {
1080
1170
  const previousState = state;
1171
+ const previousOwner = workflowOwner;
1172
+ const previousToolSnapshot = previousTools;
1081
1173
  const wasEnabled = state.enabled;
1082
- enterPlanMode(ctx);
1174
+ if (!enterPlanMode(ctx)) return;
1083
1175
  if (!wasEnabled) {
1084
1176
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1085
1177
  }
1086
1178
  if (sendPlanModeUserMessage(prompt, ctx)) return;
1087
- if (!previousState.enabled) {
1088
- restoreTools();
1089
- restoreThinkingLevel();
1090
- }
1091
- state = previousState;
1092
- persistState();
1093
- updateUi(ctx);
1179
+ if (wasEnabled) return;
1180
+ rollbackNewActivation(previousState, previousToolSnapshot, ctx, previousOwner);
1094
1181
  }
1095
1182
  function exitPlanMode(ctx) {
1096
1183
  workflowGeneration += 1;
@@ -1113,6 +1200,7 @@ ${intent.plan}`,
1113
1200
  }
1114
1201
  persistState();
1115
1202
  updateUi(ctx);
1203
+ if (wasEnabled) releaseWorkflowOwner();
1116
1204
  }
1117
1205
  function sendPlanModeUserMessage(message, ctx) {
1118
1206
  try {
@@ -1151,7 +1239,7 @@ ${intent.plan}`,
1151
1239
  updateUi(ctx);
1152
1240
  }
1153
1241
  function completedPlanIsCurrent(intent) {
1154
- return state.enabled && state.awaitingAction && state.latestPlan === intent.plan && state.latestPlanSource === intent.source;
1242
+ return state.enabled && workflowMutex.isOwner(workflowOwner) && state.awaitingAction && state.latestPlan === intent.plan && state.latestPlanSource === intent.source;
1155
1243
  }
1156
1244
  function readyPresentationIsCurrent(intent) {
1157
1245
  return completedPlanIsCurrent(intent) && readyPresentationIntent?.nonce === intent.nonce;
@@ -1163,8 +1251,9 @@ ${intent.plan}`,
1163
1251
  return;
1164
1252
  }
1165
1253
  if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0)) return;
1166
- enterPlanMode(ctx);
1167
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1254
+ if (enterPlanMode(ctx)) {
1255
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1256
+ }
1168
1257
  }
1169
1258
  function planModeDisableNotification() {
1170
1259
  return state.activeImplementation ? "Active implementation plan cleared." : state.savedPlan ? "Saved plan cleared." : state.latestPlan ? "Plan mode disabled. Proposed plan discarded." : "Plan mode disabled.";
@@ -1205,6 +1294,7 @@ ${intent.plan}`,
1205
1294
  state = { ...state, manualThinkingLevel: void 0 };
1206
1295
  persistState();
1207
1296
  updateUi(ctx);
1297
+ releaseWorkflowOwner();
1208
1298
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
1209
1299
  }
1210
1300
  async function startFreshImplementation(ctx, menuIsCurrent) {
@@ -1231,6 +1321,8 @@ ${intent.plan}`,
1231
1321
  }
1232
1322
  workflowGeneration += 1;
1233
1323
  const previousState = state;
1324
+ const previousIntent = readyPresentationIntent;
1325
+ const previousToolSnapshot = previousTools;
1234
1326
  const wasEnabled = state.enabled;
1235
1327
  readyPresentationIntent = void 0;
1236
1328
  state = {
@@ -1258,16 +1350,18 @@ ${intent.plan}`,
1258
1350
  updateUi(ctx);
1259
1351
  const sent = sendPlanModeUserMessage(formatImplementationHandoff(plan), ctx);
1260
1352
  if (!sent) {
1261
- if (savedPlan) {
1262
- state = previousState;
1263
- } else {
1264
- enterPlanMode(ctx);
1265
- state = previousState;
1353
+ state = previousState;
1354
+ readyPresentationIntent = previousIntent;
1355
+ if (wasEnabled) {
1356
+ previousTools = previousToolSnapshot;
1357
+ applyPlanModeTools();
1266
1358
  applyPlanThinkingLevel();
1267
1359
  }
1268
1360
  persistState();
1269
1361
  updateUi(ctx);
1362
+ return;
1270
1363
  }
1364
+ if (wasEnabled) releaseWorkflowOwner();
1271
1365
  }
1272
1366
  function clearActiveImplementation(id, ctx) {
1273
1367
  if (state.activeImplementation?.id !== id) return false;
@@ -1303,18 +1397,19 @@ ${intent.plan}`,
1303
1397
  ...lifecycle,
1304
1398
  start: (signal) => {
1305
1399
  if (signal.aborted || !lifecycle.isCurrent()) return;
1306
- enterPlanMode(ctx);
1307
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1400
+ if (enterPlanMode(ctx)) {
1401
+ ctx.ui.notify(
1402
+ "Plan mode enabled. I will explore and plan, but not modify files.",
1403
+ "info"
1404
+ );
1405
+ }
1308
1406
  },
1309
1407
  startWithTools: (names, signal) => {
1310
1408
  if (signal.aborted || !lifecycle.isCurrent()) return;
1311
- state = {
1312
- ...state,
1313
- selectedToolNames: filterAvailableSelectedToolNames(names, tools),
1314
- selectedToolKeys: void 0
1315
- };
1316
- enterPlanMode(ctx);
1317
- ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1409
+ const selectedToolNames = filterAvailableSelectedToolNames(names, tools);
1410
+ if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: void 0 })) {
1411
+ ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1412
+ }
1318
1413
  },
1319
1414
  settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent)
1320
1415
  });
@@ -1337,8 +1432,12 @@ ${intent.plan}`,
1337
1432
  exportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),
1338
1433
  settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
1339
1434
  startNew: () => {
1340
- enterPlanMode(ctx);
1341
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1435
+ if (enterPlanMode(ctx)) {
1436
+ ctx.ui.notify(
1437
+ "Plan mode enabled. I will explore and plan, but not modify files.",
1438
+ "info"
1439
+ );
1440
+ }
1342
1441
  },
1343
1442
  clear: () => {
1344
1443
  exitPlanMode(ctx);
@@ -1367,10 +1466,11 @@ ${intent.plan}`,
1367
1466
  function captureMenuLifecycle() {
1368
1467
  const sessionGeneration = menuGeneration;
1369
1468
  const planWorkflowGeneration = workflowGeneration;
1469
+ const owner = workflowOwner;
1370
1470
  const controller = menuController;
1371
1471
  return {
1372
1472
  signal: controller.signal,
1373
- isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted
1473
+ isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted && (!state.enabled || workflowMutex.isOwner(owner))
1374
1474
  };
1375
1475
  }
1376
1476
  function activatePlanModeTools() {
@@ -1468,8 +1568,108 @@ ${intent.plan}`,
1468
1568
  return DEFAULT_TOOLS;
1469
1569
  }
1470
1570
  }
1471
- function restoreState(ctx) {
1472
- state = restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
1571
+ function readRestoredState(ctx) {
1572
+ return restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
1573
+ }
1574
+ function installRestoredState(candidate, ctx) {
1575
+ const previousState = state;
1576
+ const previousToolSnapshot = previousTools;
1577
+ const previousOwner = workflowOwner;
1578
+ const wasEnabled = state.enabled;
1579
+ if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
1580
+ const owner = workflowMutex.acquire();
1581
+ if (!owner) {
1582
+ state = { enabled: false, awaitingAction: false };
1583
+ previousTools = void 0;
1584
+ reportRestoredWorkflowBusy(ctx);
1585
+ return false;
1586
+ }
1587
+ workflowOwner = owner;
1588
+ }
1589
+ try {
1590
+ if (wasEnabled && !candidate.enabled) {
1591
+ readyPresentationIntent = void 0;
1592
+ restoreTools();
1593
+ restoreThinkingLevel();
1594
+ }
1595
+ state = candidate;
1596
+ if (state.enabled) {
1597
+ if (!wasEnabled) previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
1598
+ activatePlanModeTools();
1599
+ applyPlanThinkingLevel();
1600
+ } else {
1601
+ deactivatePlanModeQuestionTool();
1602
+ if (wasEnabled) releaseWorkflowOwner();
1603
+ }
1604
+ return true;
1605
+ } catch (error) {
1606
+ try {
1607
+ if (!wasEnabled && state.enabled) {
1608
+ try {
1609
+ restoreTools();
1610
+ } finally {
1611
+ restoreThinkingLevel();
1612
+ }
1613
+ }
1614
+ } finally {
1615
+ state = previousState;
1616
+ previousTools = previousToolSnapshot;
1617
+ if (workflowOwner !== previousOwner) {
1618
+ workflowMutex.release(workflowOwner);
1619
+ workflowOwner = previousOwner;
1620
+ }
1621
+ }
1622
+ throw error;
1623
+ }
1624
+ }
1625
+ function rollbackNewActivation(previousState, previousToolSnapshot, ctx, previousOwner) {
1626
+ const activatedOwner = workflowOwner;
1627
+ readyPresentationIntent = void 0;
1628
+ try {
1629
+ if (state.enabled) {
1630
+ try {
1631
+ restoreTools();
1632
+ } finally {
1633
+ restoreThinkingLevel();
1634
+ }
1635
+ }
1636
+ } finally {
1637
+ state = previousState;
1638
+ previousTools = previousToolSnapshot;
1639
+ try {
1640
+ persistState();
1641
+ updateUi(ctx);
1642
+ } finally {
1643
+ if (activatedOwner !== previousOwner) {
1644
+ workflowMutex.release(activatedOwner);
1645
+ workflowOwner = previousOwner;
1646
+ }
1647
+ }
1648
+ }
1649
+ }
1650
+ function bindWorkflowSessionIfNeeded(ctx) {
1651
+ if (currentSession === ctx.sessionManager) return;
1652
+ currentSession = ctx.sessionManager;
1653
+ workflowOwner = void 0;
1654
+ workflowMutex.bindSession(ctx.sessionManager);
1655
+ }
1656
+ function releaseWorkflowOwner() {
1657
+ const owner = workflowOwner;
1658
+ workflowMutex.release(owner);
1659
+ if (!workflowMutex.isOwner(owner)) workflowOwner = void 0;
1660
+ }
1661
+ function reportWorkflowBusy(ctx) {
1662
+ const message = "Another workflow is active in this session. End it before starting Plan mode.";
1663
+ if (!ctx.hasUI) throw new Error(message);
1664
+ ctx.ui.notify(message, "warning");
1665
+ return false;
1666
+ }
1667
+ function reportRestoredWorkflowBusy(ctx) {
1668
+ if (!ctx.hasUI) return;
1669
+ ctx.ui.notify(
1670
+ "Plan mode was not restored because another workflow is active in this session. Reload or start Plan mode after it ends.",
1671
+ "warning"
1672
+ );
1473
1673
  }
1474
1674
  function updateUi(ctx) {
1475
1675
  updatePlanModeUi(ctx, state, formatToolSummary);