@narumitw/pi-plan-mode 0.52.0 → 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
@@ -658,17 +927,19 @@ var WorkflowMutex = class {
658
927
  // src/plan-mode.ts
659
928
  var STATE_ENTRY_TYPE = "plan-mode-state";
660
929
  var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
661
- var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
930
+ var BLOCKED_MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "update_plan"]);
662
931
  var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
663
932
  function planMode(pi, dependencies = {}) {
664
933
  const workflowMutex = new WorkflowMutex(pi);
934
+ const helperVisibility = new PlanModeHelperVisibilityPolicy(pi);
665
935
  let workflowOwner;
666
936
  let currentSession;
937
+ let currentSessionContext;
667
938
  let interactiveUiPromise;
668
939
  const loadInteractiveUi = () => {
669
940
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
670
941
  if (!interactiveUiPromise) {
671
- interactiveUiPromise = import("./chunks/interactive-ui-GFNX5OF4.js").catch((error) => {
942
+ interactiveUiPromise = import("./chunks/interactive-ui-VESWS25D.js").catch((error) => {
672
943
  interactiveUiPromise = void 0;
673
944
  throw error;
674
945
  });
@@ -681,7 +952,10 @@ function planMode(pi, dependencies = {}) {
681
952
  let toggleShortcut;
682
953
  const clearPlanModeShortcutHandler = () => {
683
954
  };
684
- let previousTools;
955
+ let activeToolBaseline = [];
956
+ let workflowAllowedToolNames;
957
+ let publishedContractMode;
958
+ let modeContractsRelevant = false;
685
959
  let readyPresentationIntent;
686
960
  let latestCommandContext;
687
961
  let nextReadyPresentationNonce = 0;
@@ -692,11 +966,14 @@ function planMode(pi, dependencies = {}) {
692
966
  let settingsWatch;
693
967
  let settingsReloadTimer;
694
968
  const implementationRetention = createImplementationRetentionCoordinator();
969
+ const finalizationRequest = createFinalizationRequestCoordinator();
695
970
  const persistState = () => pi.appendEntry(STATE_ENTRY_TYPE, state);
696
971
  const planExports = createPlanExportController({
697
972
  getState: () => state,
698
973
  getSettings: () => settings,
699
- finishReady: (ctx) => exitPlanMode(ctx)
974
+ finishReady: (ctx) => {
975
+ exitPlanMode(ctx);
976
+ }
700
977
  });
701
978
  const planActions = createPlanActionController({
702
979
  loadInteractiveUi,
@@ -709,24 +986,19 @@ function planMode(pi, dependencies = {}) {
709
986
  finalize: requestFinalPlan,
710
987
  implementHere: startImplementation,
711
988
  implementFresh: startFreshImplementation,
712
- exportPlan: (ctx, path, signal, isCurrent) => planExports.export(path, ctx, signal, isCurrent),
989
+ exportPlan,
713
990
  settings: showSettings,
714
991
  save: savePlanForLater,
715
992
  stay: updateUi,
716
993
  exitReady: (ctx) => {
717
- exitPlanMode(ctx);
718
- 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
+ }
719
997
  },
720
998
  clearSaved: (ctx) => {
721
- exitPlanMode(ctx);
722
- ctx.ui.notify("Saved plan cleared.", "info");
999
+ if (exitPlanMode(ctx)) ctx.ui.notify("Saved plan cleared.", "info");
723
1000
  }
724
1001
  });
725
- pi.registerFlag("plan", {
726
- description: "Start in Codex-like Plan mode",
727
- type: "boolean",
728
- default: false
729
- });
730
1002
  pi.registerTool({
731
1003
  name: PLAN_MODE_QUESTION_TOOL_NAME,
732
1004
  label: "Plan question",
@@ -748,6 +1020,7 @@ function planMode(pi, dependencies = {}) {
748
1020
  if (!parsed.ok) {
749
1021
  return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
750
1022
  }
1023
+ finalizationRequest.satisfy();
751
1024
  if (!ctx.hasUI) {
752
1025
  return planModeQuestionCancelled(
753
1026
  parsed.questions,
@@ -829,12 +1102,12 @@ function planMode(pi, dependencies = {}) {
829
1102
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
830
1103
  if (exportMatch) {
831
1104
  const lifecycle = captureMenuLifecycle();
832
- await planExports.export(exportMatch[1], ctx, lifecycle.signal, lifecycle.isCurrent);
1105
+ await exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);
833
1106
  return;
834
1107
  }
835
1108
  if (command === "exit" || command === "off") {
836
- ctx.ui.notify(planModeDisableNotification(), "info");
837
- exitPlanMode(ctx);
1109
+ const notification = planModeDisableNotification();
1110
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
838
1111
  return;
839
1112
  }
840
1113
  if (command === "tools") {
@@ -900,16 +1173,17 @@ function planMode(pi, dependencies = {}) {
900
1173
  const readPlanModeRuntimeSettings = async () => {
901
1174
  return dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);
902
1175
  };
903
- const applyPlanModeSettings = async (generation, ctx, showWarnings) => {
1176
+ const applyPlanModeSettings = async (generation, ctx, showWarnings, applyWatchedVisibility = false) => {
904
1177
  const loadedSettings = await readPlanModeRuntimeSettings();
905
1178
  if (generation !== menuGeneration || menuController.signal.aborted) {
906
1179
  return void 0;
907
1180
  }
908
- if (loadedSettings.kind === "loaded") {
909
- settings = loadedSettings.settings;
910
- } else {
911
- 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);
912
1185
  }
1186
+ settings = nextSettings;
913
1187
  applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
914
1188
  if (!ctx || !showWarnings) return loadedSettings;
915
1189
  if (loadedSettings.kind === "invalid") {
@@ -935,7 +1209,7 @@ function planMode(pi, dependencies = {}) {
935
1209
  }
936
1210
  settingsReloadTimer = setTimeout(() => {
937
1211
  settingsReloadTimer = void 0;
938
- void applyPlanModeSettings(generation, void 0, false);
1212
+ void applyPlanModeSettings(generation, currentSessionContext, false, true);
939
1213
  }, 75);
940
1214
  };
941
1215
  const startPlanModeSettingsWatch = (generation) => {
@@ -960,35 +1234,64 @@ function planMode(pi, dependencies = {}) {
960
1234
  };
961
1235
  pi.on("session_start", async (event, ctx) => {
962
1236
  const generation = ++menuGeneration;
1237
+ const previousToolVisibility = configuredPlanModeToolVisibility(settings);
1238
+ finalizationRequest.reset();
963
1239
  currentSession = ctx.sessionManager;
1240
+ currentSessionContext = ctx;
964
1241
  workflowOwner = void 0;
965
1242
  workflowMutex.bindSession(ctx.sessionManager);
1243
+ captureToolBaseline();
966
1244
  refreshStateBeforeFirstAgentStart = event.reason === "new";
967
1245
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
968
1246
  menuController = new AbortController();
969
1247
  readyPresentationIntent = void 0;
970
1248
  latestCommandContext = void 0;
971
- previousTools = void 0;
1249
+ workflowAllowedToolNames = void 0;
972
1250
  implementationRetention.reset();
973
1251
  settings = { thinkingLevel: "inherit" };
974
- const restoredState = readRestoredState(ctx);
1252
+ const branch = ctx.sessionManager.getBranch();
1253
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1254
+ restoreModeContractTracking(branch, restoredState);
975
1255
  state = { enabled: false, awaitingAction: false };
976
1256
  await applyPlanModeSettings(generation, ctx, true);
977
1257
  if (generation !== menuGeneration || menuController.signal.aborted) return;
978
1258
  startPlanModeSettingsWatch(generation);
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;
1259
+ if (restoredState.enabled) {
1260
+ if (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;
1261
+ } else {
1262
+ reconcileInactiveHelperVisibility(previousToolVisibility, ctx);
1263
+ if (!installRestoredState(restoredState, ctx)) return;
1264
+ }
990
1265
  implementationRetention.restore(state.activeImplementation);
991
- if (persistFlagActivation && state.enabled) persistState();
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);
992
1295
  updateUi(ctx);
993
1296
  });
994
1297
  pi.on("thinking_level_select", (event) => {
@@ -1005,6 +1308,7 @@ function planMode(pi, dependencies = {}) {
1005
1308
  });
1006
1309
  pi.on("session_shutdown", async (_event, ctx) => {
1007
1310
  const shutdownSession = ctx.sessionManager;
1311
+ finalizationRequest.reset();
1008
1312
  menuGeneration += 1;
1009
1313
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
1010
1314
  readyPresentationIntent = void 0;
@@ -1018,35 +1322,50 @@ function planMode(pi, dependencies = {}) {
1018
1322
  }
1019
1323
  captureManualThinkingLevel();
1020
1324
  persistState();
1021
- if (state.enabled) {
1022
- restoreTools();
1023
- restoreThinkingLevel();
1024
- }
1325
+ if (state.enabled) restoreThinkingLevel();
1025
1326
  stopPlanModeSettingsWatch();
1026
1327
  clearUi(ctx);
1027
1328
  releaseWorkflowOwner();
1028
1329
  workflowMutex.unbindSession(ctx.sessionManager);
1029
- if (currentSession === ctx.sessionManager) currentSession = void 0;
1330
+ if (currentSession === ctx.sessionManager) {
1331
+ currentSession = void 0;
1332
+ currentSessionContext = void 0;
1333
+ }
1030
1334
  });
1031
1335
  pi.on("tool_call", async (event) => {
1032
- if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1033
- 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;
1034
1339
  return {
1035
1340
  block: true,
1036
- 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.`
1037
1342
  };
1038
1343
  }
1039
- const calledTool = toolByName(event.toolName);
1040
- 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)) {
1041
1351
  return {
1042
1352
  block: true,
1043
- reason: `Plan mode blocks built-in tool '${event.toolName}' because its policy class is blocked.`
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}'.`
1044
1354
  };
1045
1355
  }
1046
- if (!calledTool && BLOCKED_BUILTIN_TOOLS.has(event.toolName)) {
1356
+ if (requiredHelper) return;
1357
+ const allowedToolNames = new Set(planModePolicyToolNames());
1358
+ if (!allowedToolNames.has(event.toolName)) {
1047
1359
  return {
1048
1360
  block: true,
1049
- reason: `Plan mode blocks built-in tool '${event.toolName}' because its metadata is unavailable.`
1361
+ reason: `Plan mode blocks tool '${event.toolName}' because it is unavailable or not selected by the Plan policy.`
1362
+ };
1363
+ }
1364
+ const calledTool = toolByName(event.toolName);
1365
+ if (!calledTool || classifyPlanModeTool(calledTool) === "blocked") {
1366
+ return {
1367
+ block: true,
1368
+ reason: `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`
1050
1369
  };
1051
1370
  }
1052
1371
  if (event.toolName !== "bash") return;
@@ -1059,18 +1378,27 @@ Blocked command: ${blocked}`
1059
1378
  };
1060
1379
  }
1061
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
+ });
1062
1386
  pi.on("context", async (event, ctx) => {
1063
1387
  const result = implementationRetention.transformContext(event.messages, state);
1064
1388
  if (result.clearActiveImplementationId) {
1065
1389
  clearActiveImplementation(result.clearActiveImplementationId, ctx);
1066
1390
  }
1067
- return { messages: result.messages };
1391
+ const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
1392
+ return { messages };
1068
1393
  });
1069
- pi.on("before_agent_start", (event, ctx) => {
1394
+ pi.on("before_agent_start", (_event, ctx) => {
1070
1395
  if (refreshStateBeforeFirstAgentStart) {
1071
1396
  refreshStateBeforeFirstAgentStart = false;
1072
1397
  implementationRetention.reset();
1073
- if (!installRestoredState(readRestoredState(ctx), ctx)) return;
1398
+ const branch = ctx.sessionManager.getBranch();
1399
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1400
+ restoreModeContractTracking(branch, restoredState);
1401
+ if (!installRestoredState(restoredState, ctx)) return;
1074
1402
  implementationRetention.restore(state.activeImplementation);
1075
1403
  updateUi(ctx);
1076
1404
  }
@@ -1086,18 +1414,13 @@ Blocked command: ${blocked}`
1086
1414
  persistState();
1087
1415
  updateUi(ctx);
1088
1416
  }
1089
- applyPlanModeTools();
1090
- return {
1091
- systemPrompt: `${event.systemPrompt}
1092
-
1093
- ${buildPlanModePrompt()}`
1094
- };
1095
1417
  });
1096
1418
  pi.on("agent_end", async (event, ctx) => {
1097
1419
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1098
1420
  const text = latestAssistantText(event.messages);
1099
1421
  const parsedPlan = parseProposedPlan(text);
1100
1422
  if (parsedPlan.kind !== "valid") {
1423
+ finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
1101
1424
  if (parsedPlan.kind !== "absent") {
1102
1425
  ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
1103
1426
  }
@@ -1107,11 +1430,25 @@ ${buildPlanModePrompt()}`
1107
1430
  }
1108
1431
  acceptCompletedPlan(parsedPlan.plan, "legacy_proposed_plan", ctx);
1109
1432
  });
1110
- onAgentSettled(pi, async (_event, ctx) => {
1433
+ pi.on("agent_settled", async (_event, ctx) => {
1111
1434
  const settledImplementationId = implementationRetention.implementationSettled(
1112
1435
  state.activeImplementation
1113
1436
  );
1114
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
+ }
1115
1452
  const intent = readyPresentationIntent;
1116
1453
  if (!intent || !readyPresentationIsCurrent(intent)) return;
1117
1454
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
@@ -1137,16 +1474,29 @@ ${intent.plan}`,
1137
1474
  }
1138
1475
  });
1139
1476
  function enterPlanMode(ctx, candidate = state) {
1477
+ if (!state.enabled && !allowModeTransition(ctx, "start Plan mode")) return false;
1140
1478
  bindWorkflowSessionIfNeeded(ctx);
1141
1479
  if (state.enabled) return workflowMutex.isOwner(workflowOwner);
1142
1480
  const owner = workflowMutex.acquire();
1143
1481
  if (!owner) return reportWorkflowBusy(ctx);
1144
1482
  workflowOwner = owner;
1145
1483
  const previousState = state;
1146
- const previousToolSnapshot = previousTools;
1147
- workflowGeneration += 1;
1484
+ const previousHelperVisibility = helperVisibility.snapshot();
1148
1485
  try {
1149
- previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
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;
1150
1500
  state = {
1151
1501
  ...state,
1152
1502
  enabled: true,
@@ -1156,20 +1506,20 @@ ${intent.plan}`,
1156
1506
  selectedToolNames: candidate.selectedToolNames,
1157
1507
  selectedToolKeys: candidate.selectedToolKeys
1158
1508
  };
1159
- activatePlanModeTools();
1509
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
1160
1510
  applyPlanThinkingLevel();
1161
1511
  persistState();
1162
1512
  updateUi(ctx);
1163
1513
  return true;
1164
1514
  } catch (error) {
1165
- rollbackNewActivation(previousState, previousToolSnapshot, ctx);
1515
+ rollbackNewActivation(previousState, ctx, void 0, previousHelperVisibility);
1166
1516
  throw error;
1167
1517
  }
1168
1518
  }
1169
1519
  function enterPlanModeWithPrompt(prompt, ctx) {
1170
1520
  const previousState = state;
1171
1521
  const previousOwner = workflowOwner;
1172
- const previousToolSnapshot = previousTools;
1522
+ const previousHelperVisibility = helperVisibility.snapshot();
1173
1523
  const wasEnabled = state.enabled;
1174
1524
  if (!enterPlanMode(ctx)) return;
1175
1525
  if (!wasEnabled) {
@@ -1177,12 +1527,17 @@ ${intent.plan}`,
1177
1527
  }
1178
1528
  if (sendPlanModeUserMessage(prompt, ctx)) return;
1179
1529
  if (wasEnabled) return;
1180
- rollbackNewActivation(previousState, previousToolSnapshot, ctx, previousOwner);
1530
+ rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);
1181
1531
  }
1182
1532
  function exitPlanMode(ctx) {
1183
- workflowGeneration += 1;
1533
+ if (!allowModeTransition(ctx, "leave or clear Plan mode")) return false;
1184
1534
  const wasEnabled = state.enabled;
1535
+ if ((wasEnabled || modeContractsRelevant) && !publishModeContract("normal", ctx)) {
1536
+ return false;
1537
+ }
1538
+ advanceWorkflowGeneration();
1185
1539
  readyPresentationIntent = void 0;
1540
+ workflowAllowedToolNames = void 0;
1186
1541
  state = {
1187
1542
  ...state,
1188
1543
  enabled: false,
@@ -1194,13 +1549,33 @@ ${intent.plan}`,
1194
1549
  manualThinkingLevel: void 0
1195
1550
  };
1196
1551
  if (wasEnabled) {
1197
- restoreTools();
1198
1552
  restoreThinkingLevel();
1199
1553
  state = { ...state, manualThinkingLevel: void 0 };
1200
1554
  }
1201
1555
  persistState();
1202
1556
  updateUi(ctx);
1203
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
+ }
1204
1579
  }
1205
1580
  function sendPlanModeUserMessage(message, ctx) {
1206
1581
  try {
@@ -1208,7 +1583,7 @@ ${intent.plan}`,
1208
1583
  else pi.sendUserMessage(message, { deliverAs: "followUp" });
1209
1584
  return true;
1210
1585
  } catch (error) {
1211
- const detail = error instanceof Error ? error.message : String(error);
1586
+ const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
1212
1587
  ctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, "error");
1213
1588
  return false;
1214
1589
  }
@@ -1221,6 +1596,7 @@ ${intent.plan}`,
1221
1596
  updateUi(ctx);
1222
1597
  return;
1223
1598
  }
1599
+ finalizationRequest.satisfy();
1224
1600
  if (state.enabled && state.awaitingAction && state.latestPlan === normalized.plan && state.latestPlanSource === source) {
1225
1601
  return;
1226
1602
  }
@@ -1246,8 +1622,8 @@ ${intent.plan}`,
1246
1622
  }
1247
1623
  function togglePlanMode(ctx) {
1248
1624
  if (state.enabled) {
1249
- ctx.ui.notify(planModeDisableNotification(), "info");
1250
- exitPlanMode(ctx);
1625
+ const notification = planModeDisableNotification();
1626
+ if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
1251
1627
  return;
1252
1628
  }
1253
1629
  if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0)) return;
@@ -1263,10 +1639,8 @@ ${intent.plan}`,
1263
1639
  ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
1264
1640
  return;
1265
1641
  }
1266
- sendPlanModeUserMessage(
1267
- "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.",
1268
- ctx
1269
- );
1642
+ finalizationRequest.request(workflowGeneration);
1643
+ if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
1270
1644
  }
1271
1645
  function savePlanForLater(ctx) {
1272
1646
  const plan = state.enabled ? state.latestPlan?.trim() : void 0;
@@ -1277,8 +1651,11 @@ ${intent.plan}`,
1277
1651
  return;
1278
1652
  }
1279
1653
  const source = state.latestPlanSource ?? "legacy_proposed_plan";
1280
- workflowGeneration += 1;
1654
+ if (!allowModeTransition(ctx, "save the plan and leave Plan mode")) return;
1655
+ if (!publishModeContract("normal", ctx)) return;
1656
+ advanceWorkflowGeneration();
1281
1657
  readyPresentationIntent = void 0;
1658
+ workflowAllowedToolNames = void 0;
1282
1659
  state = {
1283
1660
  ...state,
1284
1661
  enabled: false,
@@ -1289,7 +1666,6 @@ ${intent.plan}`,
1289
1666
  activeImplementation: void 0,
1290
1667
  manualThinkingLevel: void 0
1291
1668
  };
1292
- restoreTools();
1293
1669
  restoreThinkingLevel();
1294
1670
  state = { ...state, manualThinkingLevel: void 0 };
1295
1671
  persistState();
@@ -1307,24 +1683,31 @@ ${intent.plan}`,
1307
1683
  }
1308
1684
  async function startImplementation(ctx) {
1309
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;
1310
1692
  if (savedPlan) {
1311
1693
  const sessionGeneration = menuGeneration;
1312
1694
  const planWorkflowGeneration = workflowGeneration;
1313
1695
  const isCurrent = () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !menuController.signal.aborted && !state.enabled && state.savedPlan === savedPlan;
1314
1696
  if (!await preflightSavedPlanImplementation(ctx, isCurrent)) return;
1697
+ if (!allowModeTransition(ctx, "start plan implementation")) return;
1315
1698
  }
1316
1699
  const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
1317
1700
  const source = (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? "legacy_proposed_plan";
1318
- if (!plan) {
1319
- ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
1320
- return;
1321
- }
1322
- workflowGeneration += 1;
1701
+ if (!plan) return;
1323
1702
  const previousState = state;
1324
1703
  const previousIntent = readyPresentationIntent;
1325
- const previousToolSnapshot = previousTools;
1326
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";
1327
1709
  readyPresentationIntent = void 0;
1710
+ workflowAllowedToolNames = void 0;
1328
1711
  state = {
1329
1712
  ...state,
1330
1713
  enabled: false,
@@ -1332,29 +1715,29 @@ ${intent.plan}`,
1332
1715
  latestPlanSource: void 0,
1333
1716
  awaitingAction: false,
1334
1717
  savedPlan: void 0,
1335
- activeImplementation: {
1718
+ activeImplementation: usesConversationHistory ? void 0 : {
1336
1719
  id: randomUUID2(),
1337
1720
  plan,
1338
1721
  source,
1339
1722
  startedAt: Date.now(),
1340
- retention: configuredImplementationPlanRetention(settings)
1723
+ retention
1341
1724
  },
1342
1725
  manualThinkingLevel: void 0
1343
1726
  };
1344
1727
  if (wasEnabled) {
1345
- restoreTools();
1346
1728
  restoreThinkingLevel();
1347
1729
  state = { ...state, manualThinkingLevel: void 0 };
1348
1730
  }
1349
1731
  persistState();
1350
1732
  updateUi(ctx);
1351
- const sent = sendPlanModeUserMessage(formatImplementationHandoff(plan), ctx);
1733
+ const handoff = usesConversationHistory ? wasEnabled ? formatHistoryImplementationPrompt() : formatTransferredPlanPrompt(plan, false) : formatImplementationHandoff(plan);
1734
+ const sent = sendPlanModeUserMessage(handoff, ctx);
1352
1735
  if (!sent) {
1353
1736
  state = previousState;
1354
1737
  readyPresentationIntent = previousIntent;
1355
1738
  if (wasEnabled) {
1356
- previousTools = previousToolSnapshot;
1357
- applyPlanModeTools();
1739
+ publishModeContract("plan", ctx);
1740
+ workflowAllowedToolNames = computePlanModePolicyToolNames();
1358
1741
  applyPlanThinkingLevel();
1359
1742
  }
1360
1743
  persistState();
@@ -1365,12 +1748,21 @@ ${intent.plan}`,
1365
1748
  }
1366
1749
  function clearActiveImplementation(id, ctx) {
1367
1750
  if (state.activeImplementation?.id !== id) return false;
1368
- workflowGeneration += 1;
1751
+ advanceWorkflowGeneration();
1369
1752
  state = { ...state, activeImplementation: void 0 };
1370
1753
  persistState();
1371
1754
  updateUi(ctx);
1372
1755
  return true;
1373
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
+ }
1374
1766
  async function showLaunchMenu(ctx, initialScreen = "main") {
1375
1767
  const lifecycle = captureMenuLifecycle();
1376
1768
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
@@ -1378,20 +1770,26 @@ ${intent.plan}`,
1378
1770
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
1379
1771
  const tools = selectableTools();
1380
1772
  await ui.showPlanLaunchMenu(ctx, {
1381
- 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.",
1382
1774
  initialScreen,
1383
1775
  getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
1384
- 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
+ },
1385
1782
  tools: tools.map((tool) => {
1386
1783
  const selectable = canSelectToolInPlanMode(tool);
1387
- const policy = toolPolicyLabel(tool);
1784
+ const active = toolIsActive(tool.name);
1785
+ const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
1388
1786
  const description = tool.description ?? "No description available";
1389
1787
  return {
1390
1788
  name: tool.name,
1391
1789
  description: `${policy} \xB7 ${description}`,
1392
1790
  searchText: [policy, description].join(" "),
1393
- disabled: !selectable,
1394
- 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"
1395
1793
  };
1396
1794
  }),
1397
1795
  ...lifecycle,
@@ -1406,7 +1804,7 @@ ${intent.plan}`,
1406
1804
  },
1407
1805
  startWithTools: (names, signal) => {
1408
1806
  if (signal.aborted || !lifecycle.isCurrent()) return;
1409
- const selectedToolNames = filterAvailableSelectedToolNames(names, tools);
1807
+ const selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());
1410
1808
  if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: void 0 })) {
1411
1809
  ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
1412
1810
  }
@@ -1440,8 +1838,7 @@ ${intent.plan}`,
1440
1838
  }
1441
1839
  },
1442
1840
  clear: () => {
1443
- exitPlanMode(ctx);
1444
- ctx.ui.notify("Active implementation plan cleared.", "info");
1841
+ if (exitPlanMode(ctx)) ctx.ui.notify("Active implementation plan cleared.", "info");
1445
1842
  }
1446
1843
  });
1447
1844
  }
@@ -1451,9 +1848,11 @@ ${intent.plan}`,
1451
1848
  if (!isCurrent() || signal.aborted) return false;
1452
1849
  const result = await ui.showPlanModeSettings(ctx, {
1453
1850
  tools: selectableTools(),
1851
+ activeToolNames: activeToolBaseline,
1454
1852
  signal,
1455
1853
  isCurrent,
1456
1854
  settingsPath: dependencies.settingsPath,
1855
+ updateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),
1457
1856
  onSaved: (saved) => {
1458
1857
  if (!isCurrent()) return;
1459
1858
  settings = saved;
@@ -1463,6 +1862,71 @@ ${intent.plan}`,
1463
1862
  });
1464
1863
  return result.kind === "closed" && "reason" in result && result.reason === "close";
1465
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
+ }
1466
1930
  function captureMenuLifecycle() {
1467
1931
  const sessionGeneration = menuGeneration;
1468
1932
  const planWorkflowGeneration = workflowGeneration;
@@ -1473,22 +1937,83 @@ ${intent.plan}`,
1473
1937
  isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted && (!state.enabled || workflowMutex.isOwner(owner))
1474
1938
  };
1475
1939
  }
1476
- function activatePlanModeTools() {
1477
- previousTools ??= withoutRequiredPlanModeTools(safeGetActiveTools());
1478
- applyPlanModeTools();
1940
+ function captureToolBaseline() {
1941
+ activeToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());
1479
1942
  }
1480
- function applyPlanModeTools() {
1481
- 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
+ }
1482
1981
  }
1483
- function planModeToolNames() {
1484
- const tools = selectableTools();
1485
- if (tools.length === 0 && state.selectedToolNames === void 0 && state.selectedToolKeys === void 0 && settings.defaultPlanTools === void 0) {
1486
- 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;
1487
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);
2008
+ }
2009
+ }
2010
+ function planModePolicyToolNames() {
2011
+ return workflowAllowedToolNames ?? computePlanModePolicyToolNames();
2012
+ }
2013
+ function computePlanModePolicyToolNames() {
2014
+ const tools = activePlanPolicyTools();
1488
2015
  const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
1489
- return withRequiredPlanModeTools(
1490
- tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name)
1491
- );
2016
+ return tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name);
1492
2017
  }
1493
2018
  function toolSelectionSnapshot() {
1494
2019
  return {
@@ -1502,6 +2027,13 @@ ${intent.plan}`,
1502
2027
  (tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME
1503
2028
  ).sort(compareTools);
1504
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
+ }
1505
2037
  function safeGetAllTools() {
1506
2038
  try {
1507
2039
  return pi.getAllTools();
@@ -1509,15 +2041,10 @@ ${intent.plan}`,
1509
2041
  return [];
1510
2042
  }
1511
2043
  }
1512
- function restoreTools() {
1513
- const restoredTools = previousTools ?? DEFAULT_TOOLS;
1514
- pi.setActiveTools(withoutRequiredPlanModeTools(restoredTools));
1515
- previousTools = void 0;
1516
- }
1517
2044
  function applyPlanThinkingLevel() {
1518
2045
  if (state.manualThinkingLevel) {
1519
2046
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
1520
- setPlanThinkingLevel(pi, state.manualThinkingLevel);
2047
+ pi.setThinkingLevel(state.manualThinkingLevel);
1521
2048
  }
1522
2049
  return;
1523
2050
  }
@@ -1532,7 +2059,7 @@ ${intent.plan}`,
1532
2059
  }
1533
2060
  const current = pi.getThinkingLevel();
1534
2061
  if (!state.appliedThinkingLevel) state.previousThinkingLevel = current;
1535
- if (current !== configured) setPlanThinkingLevel(pi, configured);
2062
+ if (current !== configured) pi.setThinkingLevel(configured);
1536
2063
  state.appliedThinkingLevel = pi.getThinkingLevel();
1537
2064
  }
1538
2065
  function captureManualThinkingLevel() {
@@ -1550,17 +2077,10 @@ ${intent.plan}`,
1550
2077
  captureManualThinkingLevel();
1551
2078
  const { appliedThinkingLevel, previousThinkingLevel } = state;
1552
2079
  if (appliedThinkingLevel && previousThinkingLevel && pi.getThinkingLevel() === appliedThinkingLevel) {
1553
- setPlanThinkingLevel(pi, previousThinkingLevel);
2080
+ pi.setThinkingLevel(previousThinkingLevel);
1554
2081
  }
1555
2082
  state = { ...state, appliedThinkingLevel: void 0, previousThinkingLevel: void 0 };
1556
2083
  }
1557
- function deactivatePlanModeQuestionTool() {
1558
- const activeTools = safeGetActiveTools();
1559
- const filteredTools = withoutRequiredPlanModeTools(activeTools);
1560
- if (filteredTools.length !== activeTools.length) {
1561
- pi.setActiveTools(filteredTools);
1562
- }
1563
- }
1564
2084
  function safeGetActiveTools() {
1565
2085
  try {
1566
2086
  return pi.getActiveTools();
@@ -1568,52 +2088,60 @@ ${intent.plan}`,
1568
2088
  return DEFAULT_TOOLS;
1569
2089
  }
1570
2090
  }
1571
- function readRestoredState(ctx) {
1572
- return restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
1573
- }
1574
- function installRestoredState(candidate, ctx) {
2091
+ function installRestoredState(candidate, ctx, previousToolVisibility) {
1575
2092
  const previousState = state;
1576
- const previousToolSnapshot = previousTools;
2093
+ const previousWorkflowAllowedToolNames = workflowAllowedToolNames;
1577
2094
  const previousOwner = workflowOwner;
2095
+ const previousHelperVisibility = helperVisibility.snapshot();
1578
2096
  const wasEnabled = state.enabled;
1579
2097
  if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
1580
2098
  const owner = workflowMutex.acquire();
1581
2099
  if (!owner) {
1582
2100
  state = { enabled: false, awaitingAction: false };
1583
- previousTools = void 0;
2101
+ workflowAllowedToolNames = void 0;
1584
2102
  reportRestoredWorkflowBusy(ctx);
1585
2103
  return false;
1586
2104
  }
1587
2105
  workflowOwner = owner;
1588
2106
  }
1589
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
+ }
1590
2129
  if (wasEnabled && !candidate.enabled) {
1591
2130
  readyPresentationIntent = void 0;
1592
- restoreTools();
1593
2131
  restoreThinkingLevel();
1594
2132
  }
1595
2133
  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
- }
2134
+ workflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : void 0;
2135
+ if (state.enabled) applyPlanThinkingLevel();
2136
+ else if (wasEnabled) releaseWorkflowOwner();
1604
2137
  return true;
1605
2138
  } catch (error) {
1606
2139
  try {
1607
- if (!wasEnabled && state.enabled) {
1608
- try {
1609
- restoreTools();
1610
- } finally {
1611
- restoreThinkingLevel();
1612
- }
1613
- }
2140
+ if (!wasEnabled && state.enabled) restoreThinkingLevel();
1614
2141
  } finally {
1615
2142
  state = previousState;
1616
- previousTools = previousToolSnapshot;
2143
+ workflowAllowedToolNames = previousWorkflowAllowedToolNames;
2144
+ helperVisibility.restore(previousHelperVisibility);
1617
2145
  if (workflowOwner !== previousOwner) {
1618
2146
  workflowMutex.release(workflowOwner);
1619
2147
  workflowOwner = previousOwner;
@@ -1622,21 +2150,19 @@ ${intent.plan}`,
1622
2150
  throw error;
1623
2151
  }
1624
2152
  }
1625
- function rollbackNewActivation(previousState, previousToolSnapshot, ctx, previousOwner) {
2153
+ function rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility) {
1626
2154
  const activatedOwner = workflowOwner;
1627
2155
  readyPresentationIntent = void 0;
1628
2156
  try {
1629
2157
  if (state.enabled) {
1630
- try {
1631
- restoreTools();
1632
- } finally {
1633
- restoreThinkingLevel();
1634
- }
2158
+ publishModeContract("normal", ctx);
2159
+ restoreThinkingLevel();
1635
2160
  }
1636
2161
  } finally {
1637
2162
  state = previousState;
1638
- previousTools = previousToolSnapshot;
2163
+ workflowAllowedToolNames = void 0;
1639
2164
  try {
2165
+ if (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);
1640
2166
  persistState();
1641
2167
  updateUi(ctx);
1642
2168
  } finally {
@@ -1671,6 +2197,20 @@ ${intent.plan}`,
1671
2197
  "warning"
1672
2198
  );
1673
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;
2213
+ }
1674
2214
  function updateUi(ctx) {
1675
2215
  updatePlanModeUi(ctx, state, formatToolSummary);
1676
2216
  }
@@ -1684,12 +2224,18 @@ ${intent.plan}`,
1684
2224
  return implementationRetentionPreview(configuredImplementationPlanRetention(settings));
1685
2225
  }
1686
2226
  function formatToolSummary() {
1687
- const names = planModeToolNames();
1688
- 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.`;
1689
2229
  }
1690
2230
  function toolByName(toolName) {
1691
2231
  return safeGetAllTools().find((candidate) => candidate.name === toolName);
1692
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
+ }
1693
2239
  }
1694
2240
  export {
1695
2241
  planMode as default