@narumitw/pi-plan-mode 0.51.1 → 0.53.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.
package/dist/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  IMPLEMENTATION_PLAN_RETENTIONS,
5
+ PLAN_HISTORY_IMPLEMENTATION_PROMPT,
5
6
  PLAN_MODE_COMPLETE_PARAMS,
6
7
  PLAN_MODE_COMPLETE_TOOL_NAME,
7
8
  PLAN_MODE_QUESTION_PARAMS,
@@ -15,6 +16,7 @@ import {
15
16
  configuredImplementationPlanRetention,
16
17
  configuredPlanExportPath,
17
18
  configuredPlanModeToggleShortcut,
19
+ configuredPlanModeToolVisibility,
18
20
  configuredThinkingLevel,
19
21
  createImplementationRetentionCoordinator,
20
22
  exportStoredPlan,
@@ -22,7 +24,9 @@ import {
22
24
  findBlockedCommandSegment,
23
25
  implementationRetentionPreview,
24
26
  invalidPlanMessage,
27
+ latestAssistantStopReason,
25
28
  latestAssistantText,
29
+ messageTextContent,
26
30
  normalizePlanModeCompletion,
27
31
  normalizePlanModeQuestionParams,
28
32
  parseProposedPlan,
@@ -35,11 +39,10 @@ import {
35
39
  readPlanModeSettings,
36
40
  renderPlanModeCompletion,
37
41
  snapshotPlanModeSelectedNames,
38
- snapshotPlanModeToolNames,
39
42
  toolPolicyLabel,
40
- withRequiredPlanModeTools,
41
- withoutRequiredPlanModeTools
42
- } from "./chunks/chunk-H3RGWRY7.js";
43
+ unique,
44
+ updatePlanModeSettings
45
+ } from "./chunks/chunk-D2V3VWND.js";
43
46
 
44
47
  // src/plan-mode.ts
45
48
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -71,21 +74,203 @@ function completePlanArguments(argumentPrefix) {
71
74
  }
72
75
 
73
76
  // src/extension-runtime.ts
74
- function onAgentSettled(pi, handler) {
75
- pi.on("agent_settled", handler);
76
- }
77
- function setPlanThinkingLevel(pi, level) {
78
- pi.setThinkingLevel(level);
79
- }
80
77
  function isStaleExtensionContextError(error) {
81
78
  return error instanceof Error && (error.message.includes("This extension ctx is stale after session replacement or reload") || error.message.includes("Extension context is no longer active"));
82
79
  }
83
80
 
81
+ // src/finalization-request.ts
82
+ var FINALIZE_PLAN_PROMPT = "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.";
83
+ var RETRY_FINALIZE_PLAN_PROMPT = "Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.";
84
+ function createFinalizationRequestCoordinator() {
85
+ let pending;
86
+ return {
87
+ request(workflowGeneration) {
88
+ pending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };
89
+ },
90
+ satisfy() {
91
+ pending = void 0;
92
+ },
93
+ observeRunEnd(workflowGeneration, outcome) {
94
+ if (!pending || pending.workflowGeneration !== workflowGeneration) return;
95
+ if (outcome !== "normal") {
96
+ pending = void 0;
97
+ return;
98
+ }
99
+ pending.awaitingSettlement = true;
100
+ },
101
+ settle(workflowGeneration) {
102
+ if (!pending || pending.workflowGeneration !== workflowGeneration || !pending.awaitingSettlement) {
103
+ return void 0;
104
+ }
105
+ if (pending.retryCount === 0) {
106
+ pending.retryCount = 1;
107
+ pending.awaitingSettlement = false;
108
+ return "retry";
109
+ }
110
+ pending = void 0;
111
+ return "failed";
112
+ },
113
+ reset() {
114
+ pending = void 0;
115
+ },
116
+ hasPendingRequest() {
117
+ return pending !== void 0;
118
+ }
119
+ };
120
+ }
121
+
84
122
  // src/fresh-implementation.ts
85
123
  import { randomUUID } from "node:crypto";
124
+
125
+ // src/prompt.ts
126
+ var PLAN_CONTEXT_MARKER = "[CODEX-LIKE PLAN MODE ACTIVE]";
127
+ function buildPlanModePrompt() {
128
+ return `${PLAN_CONTEXT_MARKER}
129
+ # Plan Mode (Conversational)
130
+
131
+ You are in Plan Mode, a Codex-like collaboration mode for producing a decision-complete implementation plan. Chat your way to the plan before finalizing it. A final plan must leave no implementation decisions unresolved.
132
+
133
+ ## Mode rules
134
+
135
+ - Stay in Plan Mode until a developer or extension explicitly exits it.
136
+ - Treat requests to implement as requests to plan the implementation; do not edit files or carry out the plan.
137
+ - Do not use update_plan/TODO tooling in Plan Mode; Plan Mode is conversational planning, not execution progress tracking.
138
+ - Plan Mode keeps the session's model-visible tool schemas unchanged and enforces a runtime policy allowlist. Non-built-in tools are denied by default and may be allowed only when already active in Pi and explicitly selected by the user at their own risk.
139
+ - Do not perform mutating actions: no edit/write tools, no patching, no formatting that rewrites files, no dependency installation, no commits, no migrations.
140
+
141
+ ## Phase 1 \u2014 Ground in the environment
142
+
143
+ - Explore first and ask second. Use non-mutating exploration to read files, search, inspect configuration, run read-only checks, and resolve discoverable facts.
144
+ - Before asking the user any question, perform at least one targeted non-mutating exploration pass unless no local environment or repository is available.
145
+ - Do not ask questions that can be answered from repository or system truth. Ask only when multiple plausible choices remain, a needed identifier/context is missing, or the ambiguity is product intent.
146
+
147
+ ## Phase 2 \u2014 Intent chat
148
+
149
+ - Keep asking until you can clearly state the goal, success criteria, in/out of scope, constraints, current state, and key preferences/tradeoffs.
150
+ - Bias toward questions over guessing: if a high-impact ambiguity remains, do not produce a proposed plan yet.
151
+ - For an unanswered preference or tradeoff, use the recommended option only when it is low risk and record that default as an explicit assumption in the final plan.
152
+
153
+ ## Phase 3 \u2014 Implementation chat
154
+
155
+ - Once intent is stable, keep asking until the spec is decision-complete: approach, interfaces, data flow, edge cases/failure modes, testing and acceptance criteria, and any migration or compatibility constraints.
156
+ - Use plan_mode_question for important preferences, tradeoffs, or assumption locks that cannot be discovered by non-mutating exploration. Ask 1-3 concise questions with 2-4 meaningful options. Do not include filler options.
157
+ - Treat plan_mode_question and plan_mode_complete as callable when they are listed in the current request's active tools. Do not infer that they are unavailable from earlier modes or conversation history.
158
+ - If a Plan tool call returns an actual error, respond to that error. Do not replace an available structured tool call with prose claiming that the tool is unavailable.
159
+ - If plan_mode_question returns cancelled or ui_unavailable, do not jump straight to a final plan when the missing answer is high impact. Ask one concise plain-text question or proceed only with a clearly stated low-risk assumption.
160
+
161
+ ## Ending each turn
162
+
163
+ Every Plan-mode turn that advances or finalizes the plan must end in exactly one of these ways:
164
+
165
+ - If a material decision remains, use plan_mode_question. If interactive UI is unavailable, ask one concise plain-text question instead.
166
+ - If the implementation plan is decision-complete, call plan_mode_complete alone as your final action. Do not call other tools in the same batch and do not emit a normal assistant response after it.
167
+
168
+ If a follow-up asks only for clarification and does not change or challenge the plan, answer it directly, then call plan_mode_complete alone as the final action with the complete unchanged plan so it remains available for implementation.
169
+
170
+ Never end with prose that merely announces you are about to present, write, or finalize the plan. Submit the actual plan with plan_mode_complete in that turn.
171
+
172
+ ## Completion rule
173
+
174
+ Only call plan_mode_complete when the plan leaves no implementation decisions unresolved. Pass the complete plan as Markdown with:
175
+
176
+ - A clear title
177
+ - A brief summary
178
+ - Important changes to behavior, public APIs, interfaces, or types
179
+ - Test cases and verification scenarios
180
+ - Explicit assumptions and defaults chosen where needed
181
+
182
+ Keep the plan concise, human and agent digestible, and free of open decisions. Prefer grouped behavior-level changes over file-by-file or symbol-by-symbol inventories. Do not ask "should I proceed?"; plan_mode_complete opens the Plan-mode ready flow.
183
+
184
+ If the user requests revisions after a completed plan, the next plan_mode_complete call must contain a complete replacement, not a delta. If there is not enough information for a complete replacement, continue planning with plan_mode_question instead of calling plan_mode_complete.`;
185
+ }
186
+
187
+ // src/mode-contract.ts
188
+ var MODE_CONTRACT_MESSAGE_TYPE = "plan-mode-transition";
189
+ var MODE_CONTRACT_VERSION = 1;
190
+ var PLAN_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: PLAN]`;
191
+ var NORMAL_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: NORMAL]`;
192
+ var NORMAL_CONTRACT = `${NORMAL_CONTRACT_MARKER}
193
+ Plan Mode is no longer active.
194
+ Follow the user's current Normal-mode request and ordinary system instructions.
195
+ Earlier Plan-mode restrictions no longer apply, but retain the planning conversation as context.
196
+ The visible tool schemas are session capabilities; use only tools appropriate for the current request.`;
197
+ function modeContractContent(mode) {
198
+ return mode === "plan" ? `${PLAN_CONTRACT_MARKER}
199
+ ${buildPlanModePrompt()}` : NORMAL_CONTRACT;
200
+ }
201
+ function createModeContractMessage(mode, timestamp = Date.now()) {
202
+ return {
203
+ role: "custom",
204
+ customType: MODE_CONTRACT_MESSAGE_TYPE,
205
+ content: modeContractContent(mode),
206
+ display: false,
207
+ details: { version: MODE_CONTRACT_VERSION, mode },
208
+ timestamp
209
+ };
210
+ }
211
+ function modeContractFromMessage(message) {
212
+ const candidate = unwrapMessage(message);
213
+ if (candidate.customType !== MODE_CONTRACT_MESSAGE_TYPE) return void 0;
214
+ if (candidate.content === modeContractContent("plan")) return "plan";
215
+ if (candidate.content === modeContractContent("normal")) return "normal";
216
+ return void 0;
217
+ }
218
+ function hasModeContractArtifact(messages) {
219
+ return messages.some(
220
+ (message) => unwrapMessage(message).customType === MODE_CONTRACT_MESSAGE_TYPE
221
+ );
222
+ }
223
+ function latestModeContract(messages) {
224
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
225
+ const mode = modeContractFromMessage(messages[index]);
226
+ if (mode) return { index, mode };
227
+ }
228
+ return void 0;
229
+ }
230
+ function reconcileModeContract(messages, expected) {
231
+ const latest = latestModeContract(messages);
232
+ if (latest?.mode === expected) return messages;
233
+ const latestContractIndex = findLatestContractArtifactIndex(messages);
234
+ const insertionIndex = latestContractIndex >= 0 ? latestContractIndex + 1 : leadingSummaryBoundary(messages);
235
+ return [
236
+ ...messages.slice(0, insertionIndex),
237
+ createModeContractMessage(expected, 0),
238
+ ...messages.slice(insertionIndex)
239
+ ];
240
+ }
241
+ function findLatestContractArtifactIndex(messages) {
242
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
243
+ if (unwrapMessage(messages[index]).customType === MODE_CONTRACT_MESSAGE_TYPE) return index;
244
+ }
245
+ return -1;
246
+ }
247
+ function leadingSummaryBoundary(messages) {
248
+ let index = 0;
249
+ while (index < messages.length) {
250
+ const role = unwrapMessage(messages[index]).role;
251
+ if (role !== "compactionSummary" && role !== "branchSummary") break;
252
+ index += 1;
253
+ }
254
+ return index;
255
+ }
256
+ function unwrapMessage(message) {
257
+ const entry = message;
258
+ return entry?.message ?? message ?? {};
259
+ }
260
+
261
+ // src/fresh-implementation.ts
86
262
  function formatImplementationHandoff(plan) {
87
263
  return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:
88
264
 
265
+ ${plan}`;
266
+ }
267
+ function formatHistoryImplementationPrompt() {
268
+ return PLAN_HISTORY_IMPLEMENTATION_PROMPT;
269
+ }
270
+ function formatTransferredPlanPrompt(plan, fresh) {
271
+ const destination = fresh ? " in a fresh context" : "";
272
+ return `A previous agent produced the plan below to accomplish the user's task. Implement the plan${destination}. Treat the plan as the source of user intent, re-read files as needed, and carry the work through implementation and verification.
273
+
89
274
  ${plan}`;
90
275
  }
91
276
  async function startFreshImplementationFromState(ctx, options) {
@@ -125,30 +310,39 @@ async function startFreshImplementationSession(ctx, request) {
125
310
  if (!request.isCurrent()) return { kind: "stale" };
126
311
  if (!await preflightModel(ctx, request.isCurrent)) return { kind: "rejected" };
127
312
  if (!request.isCurrent()) return { kind: "stale" };
128
- const activeImplementation = {
129
- id: randomUUID(),
130
- plan: request.plan,
131
- source: request.source,
132
- startedAt: Date.now(),
133
- retention: request.retention
134
- };
135
- const destinationState = {
313
+ const usesConversationHistory = request.retention === "clear-on-start";
314
+ const destinationState = usesConversationHistory ? void 0 : {
136
315
  enabled: false,
137
316
  awaitingAction: false,
138
- activeImplementation
317
+ activeImplementation: {
318
+ id: randomUUID(),
319
+ plan: request.plan,
320
+ source: request.source,
321
+ startedAt: Date.now(),
322
+ retention: request.retention
323
+ }
139
324
  };
140
- const handoff = formatImplementationHandoff(request.plan);
325
+ const handoff = usesConversationHistory ? formatTransferredPlanPrompt(request.plan, true) : formatImplementationHandoff(request.plan);
141
326
  const parentSession = ctx.sessionManager.getSessionFile();
142
327
  let setupError;
143
328
  let kickoffError;
144
- if (ctx.mode === "rpc") ctx.ui.notify("Starting fresh implementation session\u2026", "info");
329
+ if (ctx.mode === "rpc") safeNotify(ctx, "Starting fresh implementation session\u2026", "info");
145
330
  let result;
146
331
  try {
147
332
  result = await ctx.newSession({
148
333
  ...parentSession ? { parentSession } : {},
149
334
  setup: async (sessionManager) => {
150
335
  try {
151
- sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
336
+ const contract = createModeContractMessage("normal");
337
+ sessionManager.appendCustomMessageEntry(
338
+ contract.customType,
339
+ contract.content,
340
+ contract.display,
341
+ contract.details
342
+ );
343
+ if (destinationState) {
344
+ sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
345
+ }
152
346
  } catch (error) {
153
347
  setupError = safeErrorDetail(error);
154
348
  }
@@ -160,17 +354,21 @@ async function startFreshImplementationSession(ctx, request) {
160
354
  }
161
355
  try {
162
356
  await replacementCtx.sendUserMessage(handoff);
163
- replacementCtx.ui.notify(
164
- "Fresh implementation session started. Only the approved plan was transferred.",
165
- "info"
166
- );
167
357
  } catch (error) {
168
358
  kickoffError = safeErrorDetail(error);
169
- replacementCtx.ui.notify(
170
- `Fresh session created, but implementation did not start: ${kickoffError}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,
359
+ const recoveredInEditor = usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
360
+ safeNotify(
361
+ replacementCtx,
362
+ usesConversationHistory ? recoveredInEditor ? `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request is in the editor; submit it or resume the parent planning session.` : `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request could not be restored to the editor; resume the parent planning session.` : `Fresh session created, but implementation did not start: ${kickoffError}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,
171
363
  "error"
172
364
  );
365
+ return;
173
366
  }
367
+ safeNotify(
368
+ replacementCtx,
369
+ "Fresh implementation session started. Only the approved plan was transferred.",
370
+ "info"
371
+ );
174
372
  }
175
373
  });
176
374
  } catch (error) {
@@ -182,7 +380,7 @@ async function startFreshImplementationSession(ctx, request) {
182
380
  return { kind: "rejected" };
183
381
  }
184
382
  if (result.cancelled) {
185
- ctx.ui.notify("Fresh implementation cancelled. The plan remains available.", "info");
383
+ safeNotify(ctx, "Fresh implementation cancelled. The plan remains available.", "info");
186
384
  return { kind: "cancelled" };
187
385
  }
188
386
  return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
@@ -210,12 +408,21 @@ async function preflightModel(ctx, isCurrent) {
210
408
  return true;
211
409
  }
212
410
  function recoverSetupFailure(ctx, handoff, setupError) {
213
- ctx.ui.setEditorText(handoff);
214
- ctx.ui.notify(
215
- `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request is in the editor; submit it to continue or resume the parent planning session.`,
411
+ const recoveredInEditor = safeSetEditorText(ctx, handoff);
412
+ safeNotify(
413
+ ctx,
414
+ recoveredInEditor ? `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request is in the editor; submit it to continue or resume the parent planning session.` : `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request could not be restored to the editor; resume the parent planning session.`,
216
415
  "error"
217
416
  );
218
417
  }
418
+ function safeSetEditorText(ctx, text) {
419
+ try {
420
+ ctx.ui.setEditorText(text);
421
+ return true;
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
219
426
  function safeNotify(ctx, message, level) {
220
427
  try {
221
428
  ctx.ui.notify(message, level);
@@ -235,6 +442,114 @@ function safeErrorDetail(error) {
235
442
  return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
236
443
  }
237
444
 
445
+ // src/helper-tool-visibility.ts
446
+ var PLAN_MODE_HELPER_TOOL_NAMES = [
447
+ PLAN_MODE_QUESTION_TOOL_NAME,
448
+ PLAN_MODE_COMPLETE_TOOL_NAME
449
+ ];
450
+ var PlanModeHelperVisibilityPolicy = class {
451
+ constructor(pi) {
452
+ this.pi = pi;
453
+ }
454
+ pi;
455
+ unlocked = false;
456
+ hiddenByPolicy = /* @__PURE__ */ new Set();
457
+ isUnlocked() {
458
+ return this.unlocked;
459
+ }
460
+ hasHiddenTools() {
461
+ return this.hiddenByPolicy.size > 0;
462
+ }
463
+ toolsAvailable() {
464
+ const active = new Set(this.pi.getActiveTools());
465
+ return PLAN_MODE_HELPER_TOOL_NAMES.every((name) => active.has(name));
466
+ }
467
+ prepareSessionStart(visibility, previous) {
468
+ if (visibility === "after-first-plan" && previous === "always") this.lock();
469
+ if (visibility === "always") this.reveal();
470
+ }
471
+ reconcileInactiveState(visibility) {
472
+ if (visibility === "after-first-plan" && !this.unlocked) this.hideIfLocked();
473
+ }
474
+ deferVisibilityChange(visibility) {
475
+ if (visibility === "after-first-plan") this.lock();
476
+ }
477
+ prepareActivation(ctx) {
478
+ if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
479
+ throw new Error("wait until Pi is idle before revealing the Plan tools");
480
+ }
481
+ this.reveal();
482
+ }
483
+ applyVisibilityChange(previous, next, ctx) {
484
+ if (previous === next) return;
485
+ if (next === "always") {
486
+ if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
487
+ throw new Error("Wait for Pi to become idle before revealing Plan tools.");
488
+ }
489
+ this.reveal();
490
+ return;
491
+ }
492
+ if (ctx.isIdle?.() !== true) {
493
+ throw new Error("Wait for Pi to become idle before hiding Plan tools.");
494
+ }
495
+ this.lock();
496
+ this.hideIfLocked();
497
+ }
498
+ hideIfLocked() {
499
+ if (this.unlocked) return;
500
+ const active = this.pi.getActiveTools();
501
+ const hidden = active.filter((name) => this.isHelperTool(name));
502
+ if (hidden.length === 0) return;
503
+ this.pi.setActiveTools(active.filter((name) => !this.isHelperTool(name)));
504
+ for (const name of hidden) this.hiddenByPolicy.add(name);
505
+ }
506
+ snapshot() {
507
+ return {
508
+ activeTools: this.pi.getActiveTools(),
509
+ helperToolsUnlocked: this.unlocked,
510
+ helperToolsHiddenByPolicy: [...this.hiddenByPolicy]
511
+ };
512
+ }
513
+ restore(snapshot) {
514
+ this.pi.setActiveTools(snapshot.activeTools);
515
+ this.unlocked = snapshot.helperToolsUnlocked;
516
+ this.hiddenByPolicy.clear();
517
+ for (const name of snapshot.helperToolsHiddenByPolicy) this.hiddenByPolicy.add(name);
518
+ }
519
+ reveal() {
520
+ const snapshot = this.snapshot();
521
+ try {
522
+ const active = this.pi.getActiveTools();
523
+ const canonical = [
524
+ ...active.filter((name) => !this.isHelperTool(name)),
525
+ ...PLAN_MODE_HELPER_TOOL_NAMES
526
+ ];
527
+ if (canonical.length !== active.length || canonical.some((name, index) => name !== active[index])) {
528
+ this.pi.setActiveTools(canonical);
529
+ }
530
+ if (!this.toolsAvailable()) {
531
+ throw new Error(
532
+ "plan_mode_question and plan_mode_complete are unavailable; leave the restrictive tool mode before starting Plan mode"
533
+ );
534
+ }
535
+ this.unlockAndForgetHidden();
536
+ } catch (error) {
537
+ this.restore(snapshot);
538
+ throw error;
539
+ }
540
+ }
541
+ lock() {
542
+ this.unlocked = false;
543
+ }
544
+ unlockAndForgetHidden() {
545
+ this.unlocked = true;
546
+ this.hiddenByPolicy.clear();
547
+ }
548
+ isHelperTool(name) {
549
+ return PLAN_MODE_HELPER_TOOL_NAMES.includes(name);
550
+ }
551
+ };
552
+
238
553
  // src/plan-action-controller.ts
239
554
  function createPlanActionController(options) {
240
555
  const freshAction = (ctx, lifecycle, signal) => options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);
@@ -417,64 +732,18 @@ function formatStatus(state) {
417
732
  return void 0;
418
733
  }
419
734
 
420
- // src/prompt.ts
421
- var PLAN_CONTEXT_MARKER = "[CODEX-LIKE PLAN MODE ACTIVE]";
422
- function buildPlanModePrompt() {
423
- return `${PLAN_CONTEXT_MARKER}
424
- # Plan Mode (Conversational)
425
-
426
- You are in Plan Mode, a Codex-like collaboration mode for producing a decision-complete implementation plan. Chat your way to the plan before finalizing it. A final plan must leave no implementation decisions unresolved.
427
-
428
- ## Mode rules
429
-
430
- - Stay in Plan Mode until a developer or extension explicitly exits it.
431
- - Treat requests to implement as requests to plan the implementation; do not edit files or carry out the plan.
432
- - Do not use update_plan/TODO tooling in Plan Mode; Plan Mode is conversational planning, not execution progress tracking.
433
- - Plan Mode manages built-in tool safety only. Non-built-in tools are disabled by default and may be enabled by the user at their own risk.
434
- - Do not perform mutating actions: no edit/write tools, no patching, no formatting that rewrites files, no dependency installation, no commits, no migrations.
435
-
436
- ## Phase 1 \u2014 Ground in the environment
437
-
438
- - Explore first and ask second. Use non-mutating exploration to read files, search, inspect configuration, run read-only checks, and resolve discoverable facts.
439
- - Before asking the user any question, perform at least one targeted non-mutating exploration pass unless no local environment or repository is available.
440
- - Do not ask questions that can be answered from repository or system truth. Ask only when multiple plausible choices remain, a needed identifier/context is missing, or the ambiguity is product intent.
441
-
442
- ## Phase 2 \u2014 Intent chat
443
-
444
- - Keep asking until you can clearly state the goal, success criteria, in/out of scope, constraints, current state, and key preferences/tradeoffs.
445
- - Bias toward questions over guessing: if a high-impact ambiguity remains, do not produce a proposed plan yet.
446
- - For an unanswered preference or tradeoff, use the recommended option only when it is low risk and record that default as an explicit assumption in the final plan.
447
-
448
- ## Phase 3 \u2014 Implementation chat
449
-
450
- - Once intent is stable, keep asking until the spec is decision-complete: approach, interfaces, data flow, edge cases/failure modes, testing and acceptance criteria, and any migration or compatibility constraints.
451
- - Use plan_mode_question for important preferences, tradeoffs, or assumption locks that cannot be discovered by non-mutating exploration. Ask 1-3 concise questions with 2-4 meaningful options. Do not include filler options.
452
- - If plan_mode_question returns cancelled or ui_unavailable, do not jump straight to a final plan when the missing answer is high impact. Ask one concise plain-text question or proceed only with a clearly stated low-risk assumption.
453
-
454
- ## Ending each turn
455
-
456
- Every Plan-mode turn that advances or finalizes the plan must end in exactly one of these ways:
457
-
458
- - If a material decision remains, use plan_mode_question. If interactive UI is unavailable, ask one concise plain-text question instead.
459
- - If the implementation plan is decision-complete, call plan_mode_complete alone as your final action. Do not call other tools in the same batch and do not emit a normal assistant response after it.
460
-
461
- If a follow-up asks only for clarification and does not change or challenge the plan, answer it directly, then call plan_mode_complete alone as the final action with the complete unchanged plan so it remains available for implementation.
462
-
463
- Never end with prose that merely announces you are about to present, write, or finalize the plan. Submit the actual plan with plan_mode_complete in that turn.
464
-
465
- ## Completion rule
466
-
467
- Only call plan_mode_complete when the plan leaves no implementation decisions unresolved. Pass the complete plan as Markdown with:
468
-
469
- - A clear title
470
- - A brief summary
471
- - Important changes to behavior, public APIs, interfaces, or types
472
- - Test cases and verification scenarios
473
- - Explicit assumptions and defaults chosen where needed
474
-
475
- Keep the plan concise, human and agent digestible, and free of open decisions. Prefer grouped behavior-level changes over file-by-file or symbol-by-symbol inventories. Do not ask "should I proceed?"; plan_mode_complete opens the Plan-mode ready flow.
476
-
477
- If the user requests revisions after a completed plan, the next plan_mode_complete call must contain a complete replacement, not a delta. If there is not enough information for a complete replacement, continue planning with plan_mode_question instead of calling plan_mode_complete.`;
735
+ // src/required-tools.ts
736
+ function withRequiredPlanModeTools(toolNames) {
737
+ return unique([
738
+ ...withoutRequiredPlanModeTools(toolNames),
739
+ PLAN_MODE_QUESTION_TOOL_NAME,
740
+ PLAN_MODE_COMPLETE_TOOL_NAME
741
+ ]);
742
+ }
743
+ function withoutRequiredPlanModeTools(toolNames) {
744
+ return toolNames.filter(
745
+ (toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME
746
+ );
478
747
  }
479
748
 
480
749
  // src/saved-plan-preflight.ts
@@ -592,17 +861,85 @@ function isRecord(value) {
592
861
  return typeof value === "object" && value !== null && !Array.isArray(value);
593
862
  }
594
863
 
864
+ // src/workflow-mutex.ts
865
+ var WORKFLOW_MUTEX_CHANNEL = "workflow:mutex:v1";
866
+ var AGENT_WORKFLOW_GROUP = "agent-workflow";
867
+ var WorkflowMutex = class {
868
+ constructor(pi) {
869
+ this.pi = pi;
870
+ pi.events.on(WORKFLOW_MUTEX_CHANNEL, (payload) => {
871
+ this.answer(payload);
872
+ });
873
+ }
874
+ pi;
875
+ session;
876
+ heldGroups = /* @__PURE__ */ new Map();
877
+ generation = 0;
878
+ bindSession(session) {
879
+ this.generation += 1;
880
+ this.heldGroups.clear();
881
+ this.session = session;
882
+ }
883
+ unbindSession(session) {
884
+ if (this.session !== session) return;
885
+ this.generation += 1;
886
+ this.heldGroups.clear();
887
+ this.session = void 0;
888
+ }
889
+ acquire(group = AGENT_WORKFLOW_GROUP) {
890
+ const session = this.session;
891
+ const generation = this.generation;
892
+ if (!session || this.heldGroups.has(group)) return void 0;
893
+ const attempt = { session, group, busy: false };
894
+ try {
895
+ this.pi.events.emit(WORKFLOW_MUTEX_CHANNEL, attempt);
896
+ } catch {
897
+ return void 0;
898
+ }
899
+ if (this.session !== session || this.generation !== generation || attempt.session !== session || attempt.group !== group || attempt.busy !== false || this.heldGroups.has(group)) {
900
+ return void 0;
901
+ }
902
+ const owner = Symbol(group);
903
+ this.heldGroups.set(group, owner);
904
+ return owner;
905
+ }
906
+ isOwner(owner, group = AGENT_WORKFLOW_GROUP) {
907
+ return owner !== void 0 && this.heldGroups.get(group) === owner;
908
+ }
909
+ release(owner, group = AGENT_WORKFLOW_GROUP) {
910
+ if (!this.isOwner(owner, group)) return;
911
+ this.heldGroups.delete(group);
912
+ }
913
+ answer(payload) {
914
+ try {
915
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return;
916
+ const attempt = payload;
917
+ if (attempt.session !== this.session) return;
918
+ if (attempt.group !== AGENT_WORKFLOW_GROUP) return;
919
+ if (typeof attempt.busy !== "boolean") return;
920
+ if (!this.heldGroups.has(attempt.group)) return;
921
+ attempt.busy = true;
922
+ } catch {
923
+ }
924
+ }
925
+ };
926
+
595
927
  // src/plan-mode.ts
596
928
  var STATE_ENTRY_TYPE = "plan-mode-state";
597
929
  var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
598
- var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
930
+ var BLOCKED_MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "update_plan"]);
599
931
  var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
600
932
  function planMode(pi, dependencies = {}) {
933
+ const workflowMutex = new WorkflowMutex(pi);
934
+ const helperVisibility = new PlanModeHelperVisibilityPolicy(pi);
935
+ let workflowOwner;
936
+ let currentSession;
937
+ let currentSessionContext;
601
938
  let interactiveUiPromise;
602
939
  const loadInteractiveUi = () => {
603
940
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
604
941
  if (!interactiveUiPromise) {
605
- interactiveUiPromise = import("./chunks/interactive-ui-GFNX5OF4.js").catch((error) => {
942
+ interactiveUiPromise = import("./chunks/interactive-ui-VESWS25D.js").catch((error) => {
606
943
  interactiveUiPromise = void 0;
607
944
  throw error;
608
945
  });
@@ -615,7 +952,10 @@ function planMode(pi, dependencies = {}) {
615
952
  let toggleShortcut;
616
953
  const clearPlanModeShortcutHandler = () => {
617
954
  };
618
- let previousTools;
955
+ let activeToolBaseline = [];
956
+ let workflowAllowedToolNames;
957
+ let publishedContractMode;
958
+ let modeContractsRelevant = false;
619
959
  let readyPresentationIntent;
620
960
  let latestCommandContext;
621
961
  let nextReadyPresentationNonce = 0;
@@ -626,11 +966,14 @@ function planMode(pi, dependencies = {}) {
626
966
  let settingsWatch;
627
967
  let settingsReloadTimer;
628
968
  const implementationRetention = createImplementationRetentionCoordinator();
969
+ const finalizationRequest = createFinalizationRequestCoordinator();
629
970
  const persistState = () => pi.appendEntry(STATE_ENTRY_TYPE, state);
630
971
  const planExports = createPlanExportController({
631
972
  getState: () => state,
632
973
  getSettings: () => settings,
633
- finishReady: (ctx) => exitPlanMode(ctx)
974
+ finishReady: (ctx) => {
975
+ exitPlanMode(ctx);
976
+ }
634
977
  });
635
978
  const planActions = createPlanActionController({
636
979
  loadInteractiveUi,
@@ -643,24 +986,19 @@ function planMode(pi, dependencies = {}) {
643
986
  finalize: requestFinalPlan,
644
987
  implementHere: startImplementation,
645
988
  implementFresh: startFreshImplementation,
646
- exportPlan: (ctx, path, signal, isCurrent) => planExports.export(path, ctx, signal, isCurrent),
989
+ exportPlan,
647
990
  settings: showSettings,
648
991
  save: savePlanForLater,
649
992
  stay: updateUi,
650
993
  exitReady: (ctx) => {
651
- exitPlanMode(ctx);
652
- ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
994
+ if (exitPlanMode(ctx)) {
995
+ ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
996
+ }
653
997
  },
654
998
  clearSaved: (ctx) => {
655
- exitPlanMode(ctx);
656
- ctx.ui.notify("Saved plan cleared.", "info");
999
+ if (exitPlanMode(ctx)) ctx.ui.notify("Saved plan cleared.", "info");
657
1000
  }
658
1001
  });
659
- pi.registerFlag("plan", {
660
- description: "Start in Codex-like Plan mode",
661
- type: "boolean",
662
- default: false
663
- });
664
1002
  pi.registerTool({
665
1003
  name: PLAN_MODE_QUESTION_TOOL_NAME,
666
1004
  label: "Plan question",
@@ -671,7 +1009,7 @@ function planMode(pi, dependencies = {}) {
671
1009
  ],
672
1010
  parameters: PLAN_MODE_QUESTION_PARAMS,
673
1011
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
674
- if (!state.enabled) {
1012
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
675
1013
  return planModeQuestionCancelled(
676
1014
  [],
677
1015
  "plan_mode_inactive",
@@ -682,6 +1020,7 @@ function planMode(pi, dependencies = {}) {
682
1020
  if (!parsed.ok) {
683
1021
  return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
684
1022
  }
1023
+ finalizationRequest.satisfy();
685
1024
  if (!ctx.hasUI) {
686
1025
  return planModeQuestionCancelled(
687
1026
  parsed.questions,
@@ -691,8 +1030,9 @@ function planMode(pi, dependencies = {}) {
691
1030
  }
692
1031
  const sessionGeneration = menuGeneration;
693
1032
  const questionWorkflowGeneration = workflowGeneration;
1033
+ const questionOwner = workflowOwner;
694
1034
  return answerPlanModeQuestions(parsed.questions, ctx, {
695
- isCurrent: () => sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration,
1035
+ isCurrent: () => sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration && workflowMutex.isOwner(questionOwner),
696
1036
  isEnabled: () => state.enabled
697
1037
  });
698
1038
  }
@@ -708,7 +1048,7 @@ function planMode(pi, dependencies = {}) {
708
1048
  parameters: PLAN_MODE_COMPLETE_PARAMS,
709
1049
  renderResult: renderPlanModeCompletion,
710
1050
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
711
- if (!state.enabled) {
1051
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
712
1052
  throw new Error("plan_mode_complete is only available while Plan mode is active");
713
1053
  }
714
1054
  const parsed = normalizePlanModeCompletion(params);
@@ -731,8 +1071,12 @@ function planMode(pi, dependencies = {}) {
731
1071
  ctx.ui.notify("Plan mode is already active.", "info");
732
1072
  return;
733
1073
  }
734
- enterPlanMode(ctx);
735
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1074
+ if (enterPlanMode(ctx)) {
1075
+ ctx.ui.notify(
1076
+ "Plan mode enabled. I will explore and plan, but not modify files.",
1077
+ "info"
1078
+ );
1079
+ }
736
1080
  return;
737
1081
  }
738
1082
  if (command === "show") {
@@ -758,12 +1102,12 @@ function planMode(pi, dependencies = {}) {
758
1102
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
759
1103
  if (exportMatch) {
760
1104
  const lifecycle = captureMenuLifecycle();
761
- await planExports.export(exportMatch[1], ctx, lifecycle.signal, lifecycle.isCurrent);
1105
+ await exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);
762
1106
  return;
763
1107
  }
764
1108
  if (command === "exit" || command === "off") {
765
- ctx.ui.notify(planModeDisableNotification(), "info");
766
- exitPlanMode(ctx);
1109
+ const notification = planModeDisableNotification();
1110
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
767
1111
  return;
768
1112
  }
769
1113
  if (command === "tools") {
@@ -829,16 +1173,17 @@ function planMode(pi, dependencies = {}) {
829
1173
  const readPlanModeRuntimeSettings = async () => {
830
1174
  return dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);
831
1175
  };
832
- const applyPlanModeSettings = async (generation, ctx, showWarnings) => {
1176
+ const applyPlanModeSettings = async (generation, ctx, showWarnings, applyWatchedVisibility = false) => {
833
1177
  const loadedSettings = await readPlanModeRuntimeSettings();
834
1178
  if (generation !== menuGeneration || menuController.signal.aborted) {
835
1179
  return void 0;
836
1180
  }
837
- if (loadedSettings.kind === "loaded") {
838
- settings = loadedSettings.settings;
839
- } else {
840
- settings = { thinkingLevel: "inherit" };
1181
+ const previousSettings = settings;
1182
+ const nextSettings = loadedSettings.kind === "loaded" ? loadedSettings.settings : { thinkingLevel: "inherit" };
1183
+ if (applyWatchedVisibility && ctx) {
1184
+ applyWatchedHelperVisibility(previousSettings, nextSettings, ctx);
841
1185
  }
1186
+ settings = nextSettings;
842
1187
  applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
843
1188
  if (!ctx || !showWarnings) return loadedSettings;
844
1189
  if (loadedSettings.kind === "invalid") {
@@ -864,7 +1209,7 @@ function planMode(pi, dependencies = {}) {
864
1209
  }
865
1210
  settingsReloadTimer = setTimeout(() => {
866
1211
  settingsReloadTimer = void 0;
867
- void applyPlanModeSettings(generation, void 0, false);
1212
+ void applyPlanModeSettings(generation, currentSessionContext, false, true);
868
1213
  }, 75);
869
1214
  };
870
1215
  const startPlanModeSettingsWatch = (generation) => {
@@ -889,35 +1234,64 @@ function planMode(pi, dependencies = {}) {
889
1234
  };
890
1235
  pi.on("session_start", async (event, ctx) => {
891
1236
  const generation = ++menuGeneration;
1237
+ const previousToolVisibility = configuredPlanModeToolVisibility(settings);
1238
+ finalizationRequest.reset();
1239
+ currentSession = ctx.sessionManager;
1240
+ currentSessionContext = ctx;
1241
+ workflowOwner = void 0;
1242
+ workflowMutex.bindSession(ctx.sessionManager);
1243
+ captureToolBaseline();
892
1244
  refreshStateBeforeFirstAgentStart = event.reason === "new";
893
1245
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
894
1246
  menuController = new AbortController();
895
1247
  readyPresentationIntent = void 0;
896
1248
  latestCommandContext = void 0;
1249
+ workflowAllowedToolNames = void 0;
897
1250
  implementationRetention.reset();
898
1251
  settings = { thinkingLevel: "inherit" };
899
- restoreState(ctx);
900
- implementationRetention.restore(state.activeImplementation);
1252
+ const branch = ctx.sessionManager.getBranch();
1253
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1254
+ restoreModeContractTracking(branch, restoredState);
1255
+ state = { enabled: false, awaitingAction: false };
901
1256
  await applyPlanModeSettings(generation, ctx, true);
902
1257
  if (generation !== menuGeneration || menuController.signal.aborted) return;
903
1258
  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 };
1259
+ if (restoredState.enabled) {
1260
+ if (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;
1261
+ } else {
1262
+ reconcileInactiveHelperVisibility(previousToolVisibility, ctx);
1263
+ if (!installRestoredState(restoredState, ctx)) return;
915
1264
  }
916
- if (state.enabled) {
917
- activatePlanModeTools();
918
- applyPlanThinkingLevel();
919
- } else deactivatePlanModeQuestionTool();
920
- if (persistFlagActivation) persistState();
1265
+ implementationRetention.restore(state.activeImplementation);
1266
+ updateUi(ctx);
1267
+ });
1268
+ pi.on("session_before_tree", (event, ctx) => {
1269
+ const target = ctx.sessionManager.getEntry(event.preparation.targetId);
1270
+ if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
1271
+ return;
1272
+ }
1273
+ if (ctx.hasUI) {
1274
+ ctx.ui.notify(
1275
+ "Plan mode transition markers are internal. Select the adjacent conversation entry instead.",
1276
+ "warning"
1277
+ );
1278
+ }
1279
+ return { cancel: true };
1280
+ });
1281
+ pi.on("session_tree", (_event, ctx) => {
1282
+ advanceWorkflowGeneration();
1283
+ menuGeneration += 1;
1284
+ menuController.abort(new DOMException("Plan-mode tree branch changed", "AbortError"));
1285
+ menuController = new AbortController();
1286
+ readyPresentationIntent = void 0;
1287
+ latestCommandContext = void 0;
1288
+ implementationRetention.reset();
1289
+ const branch = ctx.sessionManager.getBranch();
1290
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1291
+ restoreModeContractTracking(branch, restoredState);
1292
+ if (!installRestoredState(restoredState, ctx)) return;
1293
+ implementationRetention.restore(state.activeImplementation);
1294
+ startPlanModeSettingsWatch(menuGeneration);
921
1295
  updateUi(ctx);
922
1296
  });
923
1297
  pi.on("thinking_level_select", (event) => {
@@ -933,6 +1307,8 @@ function planMode(pi, dependencies = {}) {
933
1307
  }
934
1308
  });
935
1309
  pi.on("session_shutdown", async (_event, ctx) => {
1310
+ const shutdownSession = ctx.sessionManager;
1311
+ finalizationRequest.reset();
936
1312
  menuGeneration += 1;
937
1313
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
938
1314
  readyPresentationIntent = void 0;
@@ -940,34 +1316,56 @@ function planMode(pi, dependencies = {}) {
940
1316
  refreshStateBeforeFirstAgentStart = false;
941
1317
  implementationRetention.reset();
942
1318
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
1319
+ if (currentSession !== void 0 && currentSession !== shutdownSession) {
1320
+ workflowMutex.unbindSession(shutdownSession);
1321
+ return;
1322
+ }
943
1323
  captureManualThinkingLevel();
944
1324
  persistState();
945
- if (state.enabled) {
946
- restoreTools();
947
- restoreThinkingLevel();
948
- }
1325
+ if (state.enabled) restoreThinkingLevel();
949
1326
  stopPlanModeSettingsWatch();
950
1327
  clearUi(ctx);
1328
+ releaseWorkflowOwner();
1329
+ workflowMutex.unbindSession(ctx.sessionManager);
1330
+ if (currentSession === ctx.sessionManager) {
1331
+ currentSession = void 0;
1332
+ currentSessionContext = void 0;
1333
+ }
951
1334
  });
952
1335
  pi.on("tool_call", async (event) => {
953
- if (!state.enabled) return;
954
- if (event.toolName === "update_plan") {
1336
+ const requiredHelper = event.toolName === PLAN_MODE_QUESTION_TOOL_NAME || event.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
1337
+ if (!state.enabled) {
1338
+ if (!requiredHelper) return;
955
1339
  return {
956
1340
  block: true,
957
- reason: "Plan mode blocks update_plan because it tracks execution progress rather than conversational planning."
1341
+ reason: `${event.toolName} is only available while Plan mode is active.`
958
1342
  };
959
1343
  }
960
- const calledTool = toolByName(event.toolName);
961
- if (calledTool && classifyPlanModeTool(calledTool) === "blocked") {
1344
+ if (!workflowMutex.isOwner(workflowOwner)) {
1345
+ return {
1346
+ block: true,
1347
+ reason: `Plan mode blocks tool '${event.toolName}' because workflow ownership is unavailable.`
1348
+ };
1349
+ }
1350
+ if (BLOCKED_MUTATING_TOOLS.has(event.toolName)) {
1351
+ return {
1352
+ block: true,
1353
+ reason: event.toolName === "update_plan" ? "Plan mode blocks update_plan because it tracks execution progress rather than conversational planning." : `Plan mode blocks mutating tool '${event.toolName}'.`
1354
+ };
1355
+ }
1356
+ if (requiredHelper) return;
1357
+ const allowedToolNames = new Set(planModePolicyToolNames());
1358
+ if (!allowedToolNames.has(event.toolName)) {
962
1359
  return {
963
1360
  block: true,
964
- reason: `Plan mode blocks built-in tool '${event.toolName}' because its policy class is blocked.`
1361
+ reason: `Plan mode blocks tool '${event.toolName}' because it is unavailable or not selected by the Plan policy.`
965
1362
  };
966
1363
  }
967
- if (!calledTool && BLOCKED_BUILTIN_TOOLS.has(event.toolName)) {
1364
+ const calledTool = toolByName(event.toolName);
1365
+ if (!calledTool || classifyPlanModeTool(calledTool) === "blocked") {
968
1366
  return {
969
1367
  block: true,
970
- reason: `Plan mode blocks built-in tool '${event.toolName}' because its metadata is unavailable.`
1368
+ reason: `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`
971
1369
  };
972
1370
  }
973
1371
  if (event.toolName !== "bash") return;
@@ -980,26 +1378,31 @@ Blocked command: ${blocked}`
980
1378
  };
981
1379
  }
982
1380
  });
1381
+ pi.on("message_start", (event) => {
1382
+ if (state.enabled && event.message.role === "user" && messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT) {
1383
+ finalizationRequest.request(workflowGeneration);
1384
+ }
1385
+ });
983
1386
  pi.on("context", async (event, ctx) => {
984
1387
  const result = implementationRetention.transformContext(event.messages, state);
985
1388
  if (result.clearActiveImplementationId) {
986
1389
  clearActiveImplementation(result.clearActiveImplementationId, ctx);
987
1390
  }
988
- return { messages: result.messages };
1391
+ const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
1392
+ return { messages };
989
1393
  });
990
- pi.on("before_agent_start", (event, ctx) => {
1394
+ pi.on("before_agent_start", (_event, ctx) => {
991
1395
  if (refreshStateBeforeFirstAgentStart) {
992
1396
  refreshStateBeforeFirstAgentStart = false;
993
- restoreState(ctx);
994
1397
  implementationRetention.reset();
1398
+ const branch = ctx.sessionManager.getBranch();
1399
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1400
+ restoreModeContractTracking(branch, restoredState);
1401
+ if (!installRestoredState(restoredState, ctx)) return;
995
1402
  implementationRetention.restore(state.activeImplementation);
996
- if (state.enabled) {
997
- activatePlanModeTools();
998
- applyPlanThinkingLevel();
999
- } else deactivatePlanModeQuestionTool();
1000
1403
  updateUi(ctx);
1001
1404
  }
1002
- if (!state.enabled) return;
1405
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1003
1406
  if (state.latestPlan || state.awaitingAction) {
1004
1407
  readyPresentationIntent = void 0;
1005
1408
  state = {
@@ -1011,18 +1414,13 @@ Blocked command: ${blocked}`
1011
1414
  persistState();
1012
1415
  updateUi(ctx);
1013
1416
  }
1014
- applyPlanModeTools();
1015
- return {
1016
- systemPrompt: `${event.systemPrompt}
1017
-
1018
- ${buildPlanModePrompt()}`
1019
- };
1020
1417
  });
1021
1418
  pi.on("agent_end", async (event, ctx) => {
1022
- if (!state.enabled) return;
1419
+ if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1023
1420
  const text = latestAssistantText(event.messages);
1024
1421
  const parsedPlan = parseProposedPlan(text);
1025
1422
  if (parsedPlan.kind !== "valid") {
1423
+ finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
1026
1424
  if (parsedPlan.kind !== "absent") {
1027
1425
  ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
1028
1426
  }
@@ -1032,11 +1430,25 @@ ${buildPlanModePrompt()}`
1032
1430
  }
1033
1431
  acceptCompletedPlan(parsedPlan.plan, "legacy_proposed_plan", ctx);
1034
1432
  });
1035
- onAgentSettled(pi, async (_event, ctx) => {
1433
+ pi.on("agent_settled", async (_event, ctx) => {
1036
1434
  const settledImplementationId = implementationRetention.implementationSettled(
1037
1435
  state.activeImplementation
1038
1436
  );
1039
1437
  if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
1438
+ if (finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
1439
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
1440
+ const action = finalizationRequest.settle(workflowGeneration);
1441
+ if (action === "retry") {
1442
+ if (sendPlanModeUserMessage(RETRY_FINALIZE_PLAN_PROMPT, ctx)) return;
1443
+ finalizationRequest.reset();
1444
+ }
1445
+ if (action === "failed") {
1446
+ ctx.ui.notify(
1447
+ "Plan finalization ended twice without a structured question or completed plan. Plan mode remains active; revise the plan or run /plan finalize again.",
1448
+ "warning"
1449
+ );
1450
+ }
1451
+ }
1040
1452
  const intent = readyPresentationIntent;
1041
1453
  if (!intent || !readyPresentationIsCurrent(intent)) return;
1042
1454
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
@@ -1061,41 +1473,71 @@ ${intent.plan}`,
1061
1473
  if (!isStaleExtensionContextError(error)) throw error;
1062
1474
  }
1063
1475
  });
1064
- function enterPlanMode(ctx) {
1065
- 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);
1476
+ function enterPlanMode(ctx, candidate = state) {
1477
+ if (!state.enabled && !allowModeTransition(ctx, "start Plan mode")) return false;
1478
+ bindWorkflowSessionIfNeeded(ctx);
1479
+ if (state.enabled) return workflowMutex.isOwner(workflowOwner);
1480
+ const owner = workflowMutex.acquire();
1481
+ if (!owner) return reportWorkflowBusy(ctx);
1482
+ workflowOwner = owner;
1483
+ const previousState = state;
1484
+ const previousHelperVisibility = helperVisibility.snapshot();
1485
+ try {
1486
+ helperVisibility.prepareActivation(ctx);
1487
+ if (!publishModeContract("plan", ctx)) {
1488
+ helperVisibility.restore(previousHelperVisibility);
1489
+ releaseWorkflowOwner();
1490
+ return false;
1491
+ }
1492
+ } catch (error) {
1493
+ helperVisibility.restore(previousHelperVisibility);
1494
+ releaseWorkflowOwner();
1495
+ return reportHelperActivationFailure(ctx, error);
1496
+ }
1497
+ advanceWorkflowGeneration();
1498
+ try {
1499
+ modeContractsRelevant = true;
1500
+ state = {
1501
+ ...state,
1502
+ enabled: true,
1503
+ awaitingAction: false,
1504
+ savedPlan: void 0,
1505
+ activeImplementation: void 0,
1506
+ selectedToolNames: candidate.selectedToolNames,
1507
+ selectedToolKeys: candidate.selectedToolKeys
1508
+ };
1509
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
1510
+ applyPlanThinkingLevel();
1511
+ persistState();
1512
+ updateUi(ctx);
1513
+ return true;
1514
+ } catch (error) {
1515
+ rollbackNewActivation(previousState, ctx, void 0, previousHelperVisibility);
1516
+ throw error;
1517
+ }
1078
1518
  }
1079
1519
  function enterPlanModeWithPrompt(prompt, ctx) {
1080
1520
  const previousState = state;
1521
+ const previousOwner = workflowOwner;
1522
+ const previousHelperVisibility = helperVisibility.snapshot();
1081
1523
  const wasEnabled = state.enabled;
1082
- enterPlanMode(ctx);
1524
+ if (!enterPlanMode(ctx)) return;
1083
1525
  if (!wasEnabled) {
1084
1526
  ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1085
1527
  }
1086
1528
  if (sendPlanModeUserMessage(prompt, ctx)) return;
1087
- if (!previousState.enabled) {
1088
- restoreTools();
1089
- restoreThinkingLevel();
1090
- }
1091
- state = previousState;
1092
- persistState();
1093
- updateUi(ctx);
1529
+ if (wasEnabled) return;
1530
+ rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);
1094
1531
  }
1095
1532
  function exitPlanMode(ctx) {
1096
- workflowGeneration += 1;
1533
+ if (!allowModeTransition(ctx, "leave or clear Plan mode")) return false;
1097
1534
  const wasEnabled = state.enabled;
1535
+ if ((wasEnabled || modeContractsRelevant) && !publishModeContract("normal", ctx)) {
1536
+ return false;
1537
+ }
1538
+ advanceWorkflowGeneration();
1098
1539
  readyPresentationIntent = void 0;
1540
+ workflowAllowedToolNames = void 0;
1099
1541
  state = {
1100
1542
  ...state,
1101
1543
  enabled: false,
@@ -1107,12 +1549,33 @@ ${intent.plan}`,
1107
1549
  manualThinkingLevel: void 0
1108
1550
  };
1109
1551
  if (wasEnabled) {
1110
- restoreTools();
1111
1552
  restoreThinkingLevel();
1112
1553
  state = { ...state, manualThinkingLevel: void 0 };
1113
1554
  }
1114
1555
  persistState();
1115
1556
  updateUi(ctx);
1557
+ if (wasEnabled) releaseWorkflowOwner();
1558
+ return true;
1559
+ }
1560
+ function restoreModeContractTracking(branch, restoredState) {
1561
+ publishedContractMode = latestModeContract(branch)?.mode;
1562
+ modeContractsRelevant = hasModeContractArtifact(branch) || restoredState.enabled || restoredState.savedPlan !== void 0 || restoredState.activeImplementation !== void 0;
1563
+ }
1564
+ function publishModeContract(mode, ctx) {
1565
+ if (publishedContractMode === mode) return true;
1566
+ const { role: _role, timestamp: _timestamp, ...message } = createModeContractMessage(mode);
1567
+ try {
1568
+ pi.sendMessage(message, { triggerTurn: false });
1569
+ publishedContractMode = mode;
1570
+ modeContractsRelevant = true;
1571
+ return true;
1572
+ } catch (error) {
1573
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1574
+ const notification = `Unable to publish the ${mode === "plan" ? "Plan" : "Normal"} mode contract: ${detail}`;
1575
+ if (!ctx.hasUI) throw new Error(notification, { cause: error });
1576
+ ctx.ui.notify(notification, "error");
1577
+ return false;
1578
+ }
1116
1579
  }
1117
1580
  function sendPlanModeUserMessage(message, ctx) {
1118
1581
  try {
@@ -1120,7 +1583,7 @@ ${intent.plan}`,
1120
1583
  else pi.sendUserMessage(message, { deliverAs: "followUp" });
1121
1584
  return true;
1122
1585
  } catch (error) {
1123
- const detail = error instanceof Error ? error.message : String(error);
1586
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1124
1587
  ctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, "error");
1125
1588
  return false;
1126
1589
  }
@@ -1133,6 +1596,7 @@ ${intent.plan}`,
1133
1596
  updateUi(ctx);
1134
1597
  return;
1135
1598
  }
1599
+ finalizationRequest.satisfy();
1136
1600
  if (state.enabled && state.awaitingAction && state.latestPlan === normalized.plan && state.latestPlanSource === source) {
1137
1601
  return;
1138
1602
  }
@@ -1151,20 +1615,21 @@ ${intent.plan}`,
1151
1615
  updateUi(ctx);
1152
1616
  }
1153
1617
  function completedPlanIsCurrent(intent) {
1154
- return state.enabled && state.awaitingAction && state.latestPlan === intent.plan && state.latestPlanSource === intent.source;
1618
+ return state.enabled && workflowMutex.isOwner(workflowOwner) && state.awaitingAction && state.latestPlan === intent.plan && state.latestPlanSource === intent.source;
1155
1619
  }
1156
1620
  function readyPresentationIsCurrent(intent) {
1157
1621
  return completedPlanIsCurrent(intent) && readyPresentationIntent?.nonce === intent.nonce;
1158
1622
  }
1159
1623
  function togglePlanMode(ctx) {
1160
1624
  if (state.enabled) {
1161
- ctx.ui.notify(planModeDisableNotification(), "info");
1162
- exitPlanMode(ctx);
1625
+ const notification = planModeDisableNotification();
1626
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
1163
1627
  return;
1164
1628
  }
1165
1629
  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");
1630
+ if (enterPlanMode(ctx)) {
1631
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1632
+ }
1168
1633
  }
1169
1634
  function planModeDisableNotification() {
1170
1635
  return state.activeImplementation ? "Active implementation plan cleared." : state.savedPlan ? "Saved plan cleared." : state.latestPlan ? "Plan mode disabled. Proposed plan discarded." : "Plan mode disabled.";
@@ -1174,10 +1639,8 @@ ${intent.plan}`,
1174
1639
  ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
1175
1640
  return;
1176
1641
  }
1177
- sendPlanModeUserMessage(
1178
- "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.",
1179
- ctx
1180
- );
1642
+ finalizationRequest.request(workflowGeneration);
1643
+ if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
1181
1644
  }
1182
1645
  function savePlanForLater(ctx) {
1183
1646
  const plan = state.enabled ? state.latestPlan?.trim() : void 0;
@@ -1188,8 +1651,11 @@ ${intent.plan}`,
1188
1651
  return;
1189
1652
  }
1190
1653
  const source = state.latestPlanSource ?? "legacy_proposed_plan";
1191
- workflowGeneration += 1;
1654
+ if (!allowModeTransition(ctx, "save the plan and leave Plan mode")) return;
1655
+ if (!publishModeContract("normal", ctx)) return;
1656
+ advanceWorkflowGeneration();
1192
1657
  readyPresentationIntent = void 0;
1658
+ workflowAllowedToolNames = void 0;
1193
1659
  state = {
1194
1660
  ...state,
1195
1661
  enabled: false,
@@ -1200,11 +1666,11 @@ ${intent.plan}`,
1200
1666
  activeImplementation: void 0,
1201
1667
  manualThinkingLevel: void 0
1202
1668
  };
1203
- restoreTools();
1204
1669
  restoreThinkingLevel();
1205
1670
  state = { ...state, manualThinkingLevel: void 0 };
1206
1671
  persistState();
1207
1672
  updateUi(ctx);
1673
+ releaseWorkflowOwner();
1208
1674
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
1209
1675
  }
1210
1676
  async function startFreshImplementation(ctx, menuIsCurrent) {
@@ -1217,22 +1683,31 @@ ${intent.plan}`,
1217
1683
  }
1218
1684
  async function startImplementation(ctx) {
1219
1685
  const savedPlan = state.enabled ? void 0 : state.savedPlan;
1686
+ const initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
1687
+ if (!initialPlan) {
1688
+ ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
1689
+ return;
1690
+ }
1691
+ if (!allowModeTransition(ctx, "start plan implementation")) return;
1220
1692
  if (savedPlan) {
1221
1693
  const sessionGeneration = menuGeneration;
1222
1694
  const planWorkflowGeneration = workflowGeneration;
1223
1695
  const isCurrent = () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !menuController.signal.aborted && !state.enabled && state.savedPlan === savedPlan;
1224
1696
  if (!await preflightSavedPlanImplementation(ctx, isCurrent)) return;
1697
+ if (!allowModeTransition(ctx, "start plan implementation")) return;
1225
1698
  }
1226
1699
  const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
1227
1700
  const source = (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? "legacy_proposed_plan";
1228
- if (!plan) {
1229
- ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
1230
- return;
1231
- }
1232
- workflowGeneration += 1;
1701
+ if (!plan) return;
1233
1702
  const previousState = state;
1703
+ const previousIntent = readyPresentationIntent;
1234
1704
  const wasEnabled = state.enabled;
1705
+ if (!publishModeContract("normal", ctx)) return;
1706
+ advanceWorkflowGeneration();
1707
+ const retention = configuredImplementationPlanRetention(settings);
1708
+ const usesConversationHistory = retention === "clear-on-start";
1235
1709
  readyPresentationIntent = void 0;
1710
+ workflowAllowedToolNames = void 0;
1236
1711
  state = {
1237
1712
  ...state,
1238
1713
  enabled: false,
@@ -1240,43 +1715,54 @@ ${intent.plan}`,
1240
1715
  latestPlanSource: void 0,
1241
1716
  awaitingAction: false,
1242
1717
  savedPlan: void 0,
1243
- activeImplementation: {
1718
+ activeImplementation: usesConversationHistory ? void 0 : {
1244
1719
  id: randomUUID2(),
1245
1720
  plan,
1246
1721
  source,
1247
1722
  startedAt: Date.now(),
1248
- retention: configuredImplementationPlanRetention(settings)
1723
+ retention
1249
1724
  },
1250
1725
  manualThinkingLevel: void 0
1251
1726
  };
1252
1727
  if (wasEnabled) {
1253
- restoreTools();
1254
1728
  restoreThinkingLevel();
1255
1729
  state = { ...state, manualThinkingLevel: void 0 };
1256
1730
  }
1257
1731
  persistState();
1258
1732
  updateUi(ctx);
1259
- const sent = sendPlanModeUserMessage(formatImplementationHandoff(plan), ctx);
1733
+ const handoff = usesConversationHistory ? wasEnabled ? formatHistoryImplementationPrompt() : formatTransferredPlanPrompt(plan, false) : formatImplementationHandoff(plan);
1734
+ const sent = sendPlanModeUserMessage(handoff, ctx);
1260
1735
  if (!sent) {
1261
- if (savedPlan) {
1262
- state = previousState;
1263
- } else {
1264
- enterPlanMode(ctx);
1265
- state = previousState;
1736
+ state = previousState;
1737
+ readyPresentationIntent = previousIntent;
1738
+ if (wasEnabled) {
1739
+ publishModeContract("plan", ctx);
1740
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
1266
1741
  applyPlanThinkingLevel();
1267
1742
  }
1268
1743
  persistState();
1269
1744
  updateUi(ctx);
1745
+ return;
1270
1746
  }
1747
+ if (wasEnabled) releaseWorkflowOwner();
1271
1748
  }
1272
1749
  function clearActiveImplementation(id, ctx) {
1273
1750
  if (state.activeImplementation?.id !== id) return false;
1274
- workflowGeneration += 1;
1751
+ advanceWorkflowGeneration();
1275
1752
  state = { ...state, activeImplementation: void 0 };
1276
1753
  persistState();
1277
1754
  updateUi(ctx);
1278
1755
  return true;
1279
1756
  }
1757
+ async function exportPlan(ctx, path, signal, isCurrent) {
1758
+ const exitsReadyPlan = state.enabled && Boolean(state.latestPlan?.trim());
1759
+ if (exitsReadyPlan && !allowModeTransition(ctx, "export the ready plan and leave Plan mode")) {
1760
+ return false;
1761
+ }
1762
+ return planExports.export(path, ctx, signal, () => {
1763
+ return isCurrent() && (!exitsReadyPlan || ctx.isIdle());
1764
+ });
1765
+ }
1280
1766
  async function showLaunchMenu(ctx, initialScreen = "main") {
1281
1767
  const lifecycle = captureMenuLifecycle();
1282
1768
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
@@ -1284,37 +1770,44 @@ ${intent.plan}`,
1284
1770
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
1285
1771
  const tools = selectableTools();
1286
1772
  await ui.showPlanLaunchMenu(ctx, {
1287
- statusText: "Status: Off \u2014 normal tools are active.",
1773
+ 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.",
1288
1774
  initialScreen,
1289
1775
  getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
1290
- toolSummary: (selectedNames) => `When started: ${snapshotPlanModeToolNames(tools, selectedNames, toolSelectionSnapshot()).join(", ")}`,
1776
+ toolSummary: (selectedNames) => {
1777
+ const allowed = tools.filter(
1778
+ (tool) => toolIsActive(tool.name) && selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)
1779
+ ).map((tool) => tool.name);
1780
+ return `Plan policy will allow: ${allowed.length > 0 ? allowed.join(", ") : "none"}.`;
1781
+ },
1291
1782
  tools: tools.map((tool) => {
1292
1783
  const selectable = canSelectToolInPlanMode(tool);
1293
- const policy = toolPolicyLabel(tool);
1784
+ const active = toolIsActive(tool.name);
1785
+ const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
1294
1786
  const description = tool.description ?? "No description available";
1295
1787
  return {
1296
1788
  name: tool.name,
1297
1789
  description: `${policy} \xB7 ${description}`,
1298
1790
  searchText: [policy, description].join(" "),
1299
- disabled: !selectable,
1300
- disabledReason: selectable ? void 0 : "Blocked by Plan-mode policy"
1791
+ disabled: !selectable || !active,
1792
+ disabledReason: !active ? "Not active in Pi; Plan mode will not activate it" : selectable ? void 0 : "Blocked by Plan-mode policy"
1301
1793
  };
1302
1794
  }),
1303
1795
  ...lifecycle,
1304
1796
  start: (signal) => {
1305
1797
  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");
1798
+ if (enterPlanMode(ctx)) {
1799
+ ctx.ui.notify(
1800
+ "Plan mode enabled. I will explore and plan, but not modify files.",
1801
+ "info"
1802
+ );
1803
+ }
1308
1804
  },
1309
1805
  startWithTools: (names, signal) => {
1310
1806
  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");
1807
+ const selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());
1808
+ if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: void 0 })) {
1809
+ ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1810
+ }
1318
1811
  },
1319
1812
  settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent)
1320
1813
  });
@@ -1337,12 +1830,15 @@ ${intent.plan}`,
1337
1830
  exportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),
1338
1831
  settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
1339
1832
  startNew: () => {
1340
- enterPlanMode(ctx);
1341
- ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1833
+ if (enterPlanMode(ctx)) {
1834
+ ctx.ui.notify(
1835
+ "Plan mode enabled. I will explore and plan, but not modify files.",
1836
+ "info"
1837
+ );
1838
+ }
1342
1839
  },
1343
1840
  clear: () => {
1344
- exitPlanMode(ctx);
1345
- ctx.ui.notify("Active implementation plan cleared.", "info");
1841
+ if (exitPlanMode(ctx)) ctx.ui.notify("Active implementation plan cleared.", "info");
1346
1842
  }
1347
1843
  });
1348
1844
  }
@@ -1352,9 +1848,11 @@ ${intent.plan}`,
1352
1848
  if (!isCurrent() || signal.aborted) return false;
1353
1849
  const result = await ui.showPlanModeSettings(ctx, {
1354
1850
  tools: selectableTools(),
1851
+ activeToolNames: activeToolBaseline,
1355
1852
  signal,
1356
1853
  isCurrent,
1357
1854
  settingsPath: dependencies.settingsPath,
1855
+ updateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),
1358
1856
  onSaved: (saved) => {
1359
1857
  if (!isCurrent()) return;
1360
1858
  settings = saved;
@@ -1364,31 +1862,158 @@ ${intent.plan}`,
1364
1862
  });
1365
1863
  return result.kind === "closed" && "reason" in result && result.reason === "close";
1366
1864
  }
1865
+ async function updateSettingsWithRuntime(patch, options, ctx, isCurrent) {
1866
+ const previousVisibility = configuredPlanModeToolVisibility(settings);
1867
+ const nextVisibility = patch.toolVisibility ?? previousVisibility;
1868
+ const persistSettings = dependencies.updateSettings ?? updatePlanModeSettings;
1869
+ if (nextVisibility === previousVisibility) {
1870
+ return persistSettings(patch, options);
1871
+ }
1872
+ if (!ctx.isIdle()) {
1873
+ throw new Error("Wait for Pi to become idle before changing Plan tool visibility.");
1874
+ }
1875
+ bindWorkflowSessionIfNeeded(ctx);
1876
+ const applicationSession = ctx.sessionManager;
1877
+ const applicationGeneration = menuGeneration;
1878
+ const applicationIsCurrent = () => currentSession === applicationSession && menuGeneration === applicationGeneration && isCurrent();
1879
+ const retainedOwner = workflowMutex.isOwner(workflowOwner);
1880
+ const temporaryOwner = retainedOwner ? workflowOwner : workflowMutex.acquire();
1881
+ if (!temporaryOwner) {
1882
+ throw new Error(
1883
+ "Another workflow is active in this session. Plan tool visibility was not changed."
1884
+ );
1885
+ }
1886
+ const visibilitySnapshot = helperVisibility.snapshot();
1887
+ try {
1888
+ helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
1889
+ const saved = await persistSettings(patch, options);
1890
+ if (!applicationIsCurrent()) {
1891
+ throw new DOMException("Plan settings session replaced", "AbortError");
1892
+ }
1893
+ settings = saved;
1894
+ applyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));
1895
+ return saved;
1896
+ } catch (error) {
1897
+ if (applicationIsCurrent()) {
1898
+ try {
1899
+ helperVisibility.restore(visibilitySnapshot);
1900
+ } catch (rollbackError) {
1901
+ throw new AggregateError(
1902
+ [error, rollbackError],
1903
+ "Plan tool visibility settings failed and runtime rollback was incomplete."
1904
+ );
1905
+ }
1906
+ }
1907
+ throw error;
1908
+ } finally {
1909
+ if (!retainedOwner) workflowMutex.release(temporaryOwner);
1910
+ if (!isCurrent()) latestCommandContext = void 0;
1911
+ }
1912
+ }
1913
+ function allowModeTransition(ctx, action) {
1914
+ if (ctx.isIdle()) return true;
1915
+ const message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;
1916
+ if (!ctx.hasUI) throw new Error(message);
1917
+ ctx.ui.notify(message, "warning");
1918
+ return false;
1919
+ }
1920
+ function advanceWorkflowGeneration() {
1921
+ workflowGeneration += 1;
1922
+ finalizationRequest.reset();
1923
+ }
1924
+ function finalizationRunOutcome(messages) {
1925
+ const stopReason = latestAssistantStopReason(messages);
1926
+ if (stopReason === void 0 || stopReason === "stop") return "normal";
1927
+ if (stopReason === "aborted") return "cancelled";
1928
+ return "error";
1929
+ }
1367
1930
  function captureMenuLifecycle() {
1368
1931
  const sessionGeneration = menuGeneration;
1369
1932
  const planWorkflowGeneration = workflowGeneration;
1933
+ const owner = workflowOwner;
1370
1934
  const controller = menuController;
1371
1935
  return {
1372
1936
  signal: controller.signal,
1373
- isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted
1937
+ isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted && (!state.enabled || workflowMutex.isOwner(owner))
1374
1938
  };
1375
1939
  }
1376
- function activatePlanModeTools() {
1377
- previousTools ??= withoutRequiredPlanModeTools(safeGetActiveTools());
1378
- applyPlanModeTools();
1940
+ function captureToolBaseline() {
1941
+ activeToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());
1379
1942
  }
1380
- function applyPlanModeTools() {
1381
- pi.setActiveTools(planModeToolNames());
1943
+ function applyWatchedHelperVisibility(previousSettings, nextSettings, ctx) {
1944
+ const previousVisibility = configuredPlanModeToolVisibility(previousSettings);
1945
+ const nextVisibility = configuredPlanModeToolVisibility(nextSettings);
1946
+ if (previousVisibility === nextVisibility) return;
1947
+ if (state.enabled) {
1948
+ helperVisibility.deferVisibilityChange(nextVisibility);
1949
+ return;
1950
+ }
1951
+ try {
1952
+ if (!ctx.isIdle()) {
1953
+ helperVisibility.deferVisibilityChange(nextVisibility);
1954
+ return;
1955
+ }
1956
+ } catch {
1957
+ helperVisibility.deferVisibilityChange(nextVisibility);
1958
+ return;
1959
+ }
1960
+ const owner = workflowMutex.acquire();
1961
+ if (!owner) {
1962
+ helperVisibility.deferVisibilityChange(nextVisibility);
1963
+ return;
1964
+ }
1965
+ const snapshot = helperVisibility.snapshot();
1966
+ try {
1967
+ helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
1968
+ } catch (error) {
1969
+ helperVisibility.restore(snapshot);
1970
+ helperVisibility.deferVisibilityChange(nextVisibility);
1971
+ if (ctx.hasUI) {
1972
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1973
+ ctx.ui.notify(
1974
+ `Could not apply reloaded Plan tool visibility; the current tool envelope remains unchanged until a later safe boundary: ${detail}`,
1975
+ "warning"
1976
+ );
1977
+ }
1978
+ } finally {
1979
+ workflowMutex.release(owner);
1980
+ }
1382
1981
  }
1383
- function planModeToolNames() {
1384
- const tools = selectableTools();
1385
- if (tools.length === 0 && state.selectedToolNames === void 0 && state.selectedToolKeys === void 0 && settings.defaultPlanTools === void 0) {
1386
- return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
1982
+ function reconcileInactiveHelperVisibility(previousVisibility, ctx) {
1983
+ const owner = workflowMutex.acquire();
1984
+ if (!owner) {
1985
+ if (ctx.hasUI) {
1986
+ ctx.ui.notify(
1987
+ "Plan tool visibility was deferred because another workflow is active in this session.",
1988
+ "warning"
1989
+ );
1990
+ }
1991
+ return false;
1992
+ }
1993
+ const snapshot = helperVisibility.snapshot();
1994
+ try {
1995
+ const visibility = configuredPlanModeToolVisibility(settings);
1996
+ helperVisibility.prepareSessionStart(visibility, previousVisibility);
1997
+ helperVisibility.reconcileInactiveState(visibility);
1998
+ return true;
1999
+ } catch (error) {
2000
+ helperVisibility.restore(snapshot);
2001
+ if (ctx.hasUI) {
2002
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
2003
+ ctx.ui.notify(`Could not apply Plan tool visibility: ${detail}`, "error");
2004
+ }
2005
+ return false;
2006
+ } finally {
2007
+ workflowMutex.release(owner);
1387
2008
  }
2009
+ }
2010
+ function planModePolicyToolNames() {
2011
+ return workflowAllowedToolNames ?? computePlanModePolicyToolNames();
2012
+ }
2013
+ function computePlanModePolicyToolNames() {
2014
+ const tools = activePlanPolicyTools();
1388
2015
  const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
1389
- return withRequiredPlanModeTools(
1390
- tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name)
1391
- );
2016
+ return tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name);
1392
2017
  }
1393
2018
  function toolSelectionSnapshot() {
1394
2019
  return {
@@ -1402,6 +2027,13 @@ ${intent.plan}`,
1402
2027
  (tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME
1403
2028
  ).sort(compareTools);
1404
2029
  }
2030
+ function activePlanPolicyTools() {
2031
+ const activeNames = new Set(activeToolBaseline);
2032
+ return selectableTools().filter((tool) => activeNames.has(tool.name));
2033
+ }
2034
+ function toolIsActive(toolName) {
2035
+ return activeToolBaseline.includes(toolName);
2036
+ }
1405
2037
  function safeGetAllTools() {
1406
2038
  try {
1407
2039
  return pi.getAllTools();
@@ -1409,15 +2041,10 @@ ${intent.plan}`,
1409
2041
  return [];
1410
2042
  }
1411
2043
  }
1412
- function restoreTools() {
1413
- const restoredTools = previousTools ?? DEFAULT_TOOLS;
1414
- pi.setActiveTools(withoutRequiredPlanModeTools(restoredTools));
1415
- previousTools = void 0;
1416
- }
1417
2044
  function applyPlanThinkingLevel() {
1418
2045
  if (state.manualThinkingLevel) {
1419
2046
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
1420
- setPlanThinkingLevel(pi, state.manualThinkingLevel);
2047
+ pi.setThinkingLevel(state.manualThinkingLevel);
1421
2048
  }
1422
2049
  return;
1423
2050
  }
@@ -1432,7 +2059,7 @@ ${intent.plan}`,
1432
2059
  }
1433
2060
  const current = pi.getThinkingLevel();
1434
2061
  if (!state.appliedThinkingLevel) state.previousThinkingLevel = current;
1435
- if (current !== configured) setPlanThinkingLevel(pi, configured);
2062
+ if (current !== configured) pi.setThinkingLevel(configured);
1436
2063
  state.appliedThinkingLevel = pi.getThinkingLevel();
1437
2064
  }
1438
2065
  function captureManualThinkingLevel() {
@@ -1450,17 +2077,10 @@ ${intent.plan}`,
1450
2077
  captureManualThinkingLevel();
1451
2078
  const { appliedThinkingLevel, previousThinkingLevel } = state;
1452
2079
  if (appliedThinkingLevel && previousThinkingLevel && pi.getThinkingLevel() === appliedThinkingLevel) {
1453
- setPlanThinkingLevel(pi, previousThinkingLevel);
2080
+ pi.setThinkingLevel(previousThinkingLevel);
1454
2081
  }
1455
2082
  state = { ...state, appliedThinkingLevel: void 0, previousThinkingLevel: void 0 };
1456
2083
  }
1457
- function deactivatePlanModeQuestionTool() {
1458
- const activeTools = safeGetActiveTools();
1459
- const filteredTools = withoutRequiredPlanModeTools(activeTools);
1460
- if (filteredTools.length !== activeTools.length) {
1461
- pi.setActiveTools(filteredTools);
1462
- }
1463
- }
1464
2084
  function safeGetActiveTools() {
1465
2085
  try {
1466
2086
  return pi.getActiveTools();
@@ -1468,8 +2088,128 @@ ${intent.plan}`,
1468
2088
  return DEFAULT_TOOLS;
1469
2089
  }
1470
2090
  }
1471
- function restoreState(ctx) {
1472
- state = restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
2091
+ function installRestoredState(candidate, ctx, previousToolVisibility) {
2092
+ const previousState = state;
2093
+ const previousWorkflowAllowedToolNames = workflowAllowedToolNames;
2094
+ const previousOwner = workflowOwner;
2095
+ const previousHelperVisibility = helperVisibility.snapshot();
2096
+ const wasEnabled = state.enabled;
2097
+ if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
2098
+ const owner = workflowMutex.acquire();
2099
+ if (!owner) {
2100
+ state = { enabled: false, awaitingAction: false };
2101
+ workflowAllowedToolNames = void 0;
2102
+ reportRestoredWorkflowBusy(ctx);
2103
+ return false;
2104
+ }
2105
+ workflowOwner = owner;
2106
+ }
2107
+ try {
2108
+ if (candidate.enabled) {
2109
+ const visibility = configuredPlanModeToolVisibility(settings);
2110
+ if (previousToolVisibility === void 0) {
2111
+ helperVisibility.prepareActivation(ctx);
2112
+ } else {
2113
+ try {
2114
+ helperVisibility.prepareSessionStart(visibility, previousToolVisibility);
2115
+ helperVisibility.prepareActivation(ctx);
2116
+ } catch {
2117
+ helperVisibility.restore(previousHelperVisibility);
2118
+ state = { enabled: false, awaitingAction: false };
2119
+ workflowAllowedToolNames = void 0;
2120
+ if (workflowOwner !== previousOwner) {
2121
+ workflowMutex.release(workflowOwner);
2122
+ workflowOwner = previousOwner;
2123
+ }
2124
+ reportRestoredHelpersUnavailable(ctx);
2125
+ return false;
2126
+ }
2127
+ }
2128
+ }
2129
+ if (wasEnabled && !candidate.enabled) {
2130
+ readyPresentationIntent = void 0;
2131
+ restoreThinkingLevel();
2132
+ }
2133
+ state = candidate;
2134
+ workflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : void 0;
2135
+ if (state.enabled) applyPlanThinkingLevel();
2136
+ else if (wasEnabled) releaseWorkflowOwner();
2137
+ return true;
2138
+ } catch (error) {
2139
+ try {
2140
+ if (!wasEnabled && state.enabled) restoreThinkingLevel();
2141
+ } finally {
2142
+ state = previousState;
2143
+ workflowAllowedToolNames = previousWorkflowAllowedToolNames;
2144
+ helperVisibility.restore(previousHelperVisibility);
2145
+ if (workflowOwner !== previousOwner) {
2146
+ workflowMutex.release(workflowOwner);
2147
+ workflowOwner = previousOwner;
2148
+ }
2149
+ }
2150
+ throw error;
2151
+ }
2152
+ }
2153
+ function rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility) {
2154
+ const activatedOwner = workflowOwner;
2155
+ readyPresentationIntent = void 0;
2156
+ try {
2157
+ if (state.enabled) {
2158
+ publishModeContract("normal", ctx);
2159
+ restoreThinkingLevel();
2160
+ }
2161
+ } finally {
2162
+ state = previousState;
2163
+ workflowAllowedToolNames = void 0;
2164
+ try {
2165
+ if (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);
2166
+ persistState();
2167
+ updateUi(ctx);
2168
+ } finally {
2169
+ if (activatedOwner !== previousOwner) {
2170
+ workflowMutex.release(activatedOwner);
2171
+ workflowOwner = previousOwner;
2172
+ }
2173
+ }
2174
+ }
2175
+ }
2176
+ function bindWorkflowSessionIfNeeded(ctx) {
2177
+ if (currentSession === ctx.sessionManager) return;
2178
+ currentSession = ctx.sessionManager;
2179
+ workflowOwner = void 0;
2180
+ workflowMutex.bindSession(ctx.sessionManager);
2181
+ }
2182
+ function releaseWorkflowOwner() {
2183
+ const owner = workflowOwner;
2184
+ workflowMutex.release(owner);
2185
+ if (!workflowMutex.isOwner(owner)) workflowOwner = void 0;
2186
+ }
2187
+ function reportWorkflowBusy(ctx) {
2188
+ const message = "Another workflow is active in this session. End it before starting Plan mode.";
2189
+ if (!ctx.hasUI) throw new Error(message);
2190
+ ctx.ui.notify(message, "warning");
2191
+ return false;
2192
+ }
2193
+ function reportRestoredWorkflowBusy(ctx) {
2194
+ if (!ctx.hasUI) return;
2195
+ ctx.ui.notify(
2196
+ "Plan mode was not restored because another workflow is active in this session. Reload or start Plan mode after it ends.",
2197
+ "warning"
2198
+ );
2199
+ }
2200
+ function reportRestoredHelpersUnavailable(ctx) {
2201
+ if (!ctx.hasUI) return;
2202
+ ctx.ui.notify(
2203
+ "Plan mode was not restored because its helper tools are unavailable under the active tool policy.",
2204
+ "warning"
2205
+ );
2206
+ }
2207
+ function reportHelperActivationFailure(ctx, error) {
2208
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
2209
+ const message = `Cannot start Plan mode: ${detail}.`;
2210
+ if (!ctx.hasUI) throw new Error(message, { cause: error });
2211
+ ctx.ui.notify(message, "error");
2212
+ return false;
1473
2213
  }
1474
2214
  function updateUi(ctx) {
1475
2215
  updatePlanModeUi(ctx, state, formatToolSummary);
@@ -1484,12 +2224,18 @@ ${intent.plan}`,
1484
2224
  return implementationRetentionPreview(configuredImplementationPlanRetention(settings));
1485
2225
  }
1486
2226
  function formatToolSummary() {
1487
- const names = planModeToolNames();
1488
- return `Tools: ${names.length > 0 ? names.join(", ") : "none"}`;
2227
+ const names = planModePolicyToolNames();
2228
+ return `Plan policy allows: ${names.length > 0 ? names.join(", ") : "none"}. Model-visible tools stay unchanged.`;
1489
2229
  }
1490
2230
  function toolByName(toolName) {
1491
2231
  return safeGetAllTools().find((candidate) => candidate.name === toolName);
1492
2232
  }
2233
+ function safeTerminalText(value) {
2234
+ return [...value].map((character) => {
2235
+ const codePoint = character.codePointAt(0) ?? 0;
2236
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
2237
+ }).join("").trim();
2238
+ }
1493
2239
  }
1494
2240
  export {
1495
2241
  planMode as default