@narumitw/pi-plan-mode 0.59.6 → 0.60.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # @narumitw/pi-plan-mode
2
2
 
3
+ ## 0.60.1
4
+
5
+ ### Patch Changes
6
+
7
+ - cf7b63d: Put editor widget names and short current count/state summaries in their divider lines. Remove duplicate body titles while retaining safety text, detail rows, privacy modes, and standalone RPC/tool output. In fullscreen Pi, click anywhere in a widget to collapse it to one named line, then click that line to restore the latest content. Preserve independent, session-local disclosure through updates without taking editor focus, changing domain data, or stopping background work. Existing owner controls provide keyboard restoration; regular-mode mouse input remains terminal-owned.
8
+
9
+ The Kit minor release supplies the named widget state and publisher disclosure APIs. Changesets raises all adopting consumers' Kit dependency floors in the same Version PR. Publish and verify the exact Kit artifact before its consumers.
10
+ - Updated dependencies [cf7b63d]
11
+ - @narumitw/pi-tui-kit@0.70.0
12
+
13
+ ## 0.60.0
14
+
15
+ ### Minor Changes
16
+
17
+ - 522796b: Add free discussion within Plan mode. Switch with F2 when no native Pi binding uses it, or use the active `/plan` menu. Switching discards unfinished questionnaire answers without changing the main prompt draft. Discussion keeps read-only restrictions and stores completed plans without opening an automatic action menu. Restore the interaction mode with the workflow; new workflows start with questionnaires enabled.
18
+
19
+ ### Patch Changes
20
+
21
+ - 227aedc: Preserve wide graphemes in expanded question details and prevent leading combining marks from making decorative prefixes exceed the viewport. Apply the same bounds to questions, answers, notes, cancellations, and errors.
22
+ - b6da988: Show compact, themed question-and-answer summaries in the transcript, with full questions and notes available when tool output is expanded.
23
+ - Updated dependencies [4f79c28]
24
+ - @narumitw/pi-tui-kit@0.69.1
25
+
3
26
  ## 0.59.6
4
27
 
5
28
  ### Patch Changes
package/README.md CHANGED
@@ -8,7 +8,8 @@ Use a Codex-like `/plan` mode to explore a codebase, resolve important questions
8
8
 
9
9
  - Starts and manages Plan mode through `/plan`, `/plan start`, or `/plan <prompt>`.
10
10
  - Blocks mutations, inactive helpers, and unsafe shell forms while keeping helper schemas stable.
11
- - Uses structured questions for important ambiguity and explicit completion for a decision-ready plan.
11
+ - Switches between structured questionnaires and free discussion without leaving read-only planning.
12
+ - Uses explicit completion for a decision-ready plan.
12
13
  - Reviews the complete plan before implementation, export, save, further planning, or discard.
13
14
  - Implements in the planning session or a fresh linked session with the approved plan.
14
15
  - Configures persistent or one-shot destination model and thinking choices for fresh implementation.
@@ -46,7 +47,7 @@ Install only from sources you trust because Pi extensions run with Pi's permissi
46
47
  Run `/plan` to open the state-aware menu, then start Plan mode and ask the agent to inspect and design the change.
47
48
  Run `/plan <prompt>` when the first planning request is already known.
48
49
 
49
- ## 🗺️ How it works
50
+ ## 🧭 How it works
50
51
 
51
52
  Plan mode keeps exploration and implementation on opposite sides of an explicit review boundary:
52
53
 
@@ -55,7 +56,7 @@ flowchart LR
55
56
  start["Start: /plan or /plan with a prompt"]
56
57
  start --> explore["Explore safely: inspect and clarify"]
57
58
  explore --> complete["Complete the plan with plan_mode_complete"]
58
- complete --> review["Review the ready plan"]
59
+ complete --> review["Review the ready plan: use /plan in discussion"]
59
60
  review -->|Revise| explore
60
61
  review -->|Implement here| current["Current session: planning context retained"]
61
62
  review -->|Start fresh| fresh["Fresh session: approved plan transferred"]
@@ -77,7 +78,12 @@ sequenceDiagram
77
78
  Plan->>User: Ask material questions when needed
78
79
  User-->>Plan: Answer or refine the request
79
80
  Plan->>Pi: Submit the complete plan
80
- Pi-->>User: Show the ready-plan review
81
+ alt Questionnaires enabled
82
+ Pi-->>User: Show the ready-plan action menu
83
+ else Free discussion
84
+ Pi-->>User: Display and store the ready plan without a menu
85
+ User->>Pi: Open /plan when ready
86
+ end
81
87
  alt Implement here
82
88
  Pi->>Work: Restore Normal mode in the current session
83
89
  else Start fresh and implement
@@ -89,7 +95,7 @@ sequenceDiagram
89
95
 
90
96
  | Command | Purpose |
91
97
  | --- | --- |
92
- | `/plan` | Start or manage planning, review a plan, or choose same-session or fresh-session implementation. |
98
+ | `/plan` | Start or manage planning, switch questionnaire/discussion mode, review a plan, or choose same-session or fresh-session implementation. |
93
99
  | `/plan start` | Enter Plan mode without sending a model message. |
94
100
  | `/plan <prompt>` | Start planning with a prompt, or send a follow-up while already active. |
95
101
  | `/plan tools` | Choose a session-specific tool policy, then start; cancellation changes nothing. |
@@ -114,7 +120,7 @@ See [command workflows](./docs/command-workflows.md) for tool selection, busy-st
114
120
  ## 🔒 Security and privacy
115
121
 
116
122
  While Plan mode is active, the policy blocks built-in editing tools and instructs the agent not to edit files or implement the change.
117
- It should explore first and ask structured questions when a preference or tradeoff materially changes the plan.
123
+ It should explore first and ask structured questions when a preference or tradeoff materially changes the plan, or ask in plain text during free discussion.
118
124
  Configure persistent defaults or a one-workflow tool override before activation; active and ready workflows lock those controls.
119
125
 
120
126
  Plan mode registers `plan_mode_question` and `plan_mode_complete` during extension load and never changes their active status itself.
@@ -161,6 +167,20 @@ Trusted commands can still mutate data or execute code with Pi's permissions; se
161
167
 
162
168
  ## 🧭 Planning and implementation
163
169
 
170
+ Each new Plan workflow starts with questionnaires enabled.
171
+ In TUI, F2 switches between questionnaires and free discussion only when the main editor is idle or the current workflow's questionnaire is open; it does not toggle Plan mode itself.
172
+ If an effective native Pi keybinding uses F2, this shortcut is not registered or shown; use the active `/plan` menu instead.
173
+ Other running work does not accept the toggle.
174
+ Switching from a questionnaire discards all unfinished answers and notes, leaves the main prompt draft unchanged, and stops the questionnaire run without sending a message.
175
+ Enabling questionnaires again does not call the model or reopen old questions.
176
+
177
+ Free discussion keeps the same read-only restrictions and allows plain-text questions without questionnaire dialogs.
178
+ Completed plans are still displayed, stored, and marked `plan ready`, but no automatic action menu opens; use `/plan` manually to implement, save, export, revise, exit, or enable questionnaires.
179
+ The editor widget shows the interaction mode and the available F2 or `/plan` entry point, including when a plan is ready.
180
+ In fullscreen TUI mode, click the **Plan mode** divider or any body row, including its blank right side, to collapse or expand it. Collapse changes only the display, not the workflow or read-only restrictions. The choice survives status updates and branch navigation, but resets on session replacement or reload. Open `/plan` without arguments to expand it from the keyboard.
181
+ The interaction mode restores with the active workflow on reload or resume; a new workflow starts with questionnaires enabled.
182
+ See [interaction switching](./docs/command-workflows.md#questionnaires-and-free-discussion) for RPC behavior and recovery.
183
+
164
184
  `plan_mode_question` follows Codex's `request_user_input` pattern: the agent can ask 1-3 concise questions, each with meaningful options and a free-form Other path.
165
185
  In TUI mode, a single question shows its header as plain muted text, submits as soon as its preset or custom answer is confirmed, and does not show tabs, Review, or question-navigation controls.
166
186
  Add an optional note with `n` before confirming a single preset answer.
@@ -170,6 +190,7 @@ Use up and down to choose an option, Enter to record it and advance, or `n` to r
170
190
  Press `n` again on an answered item to edit or clear its note.
171
191
  Revisit a question to replace its answer; changing the chosen option clears its prior note.
172
192
  Review lists every answer and note, blocks incomplete submission, and requires returning to a question to edit its answer or note.
193
+ The transcript shows a compact summary of each answer instead of raw tool JSON. Expand the tool output to read the full questions, answers, and notes.
173
194
  Custom answers and notes retain their raw submitted text in the tool result, while terminal rendering is sanitized.
174
195
  In TUI mode, a custom editor registered through Pi's `ctx.ui.setEditorComponent()` also handles answer and note editing in a separate instance, without changing the main prompt draft.
175
196
  While that editor is active, it controls Escape and submission keys; Ctrl+C still cancels the question.
@@ -197,7 +218,8 @@ Termination is best effort: if a model puts it in a parallel tool batch, Pi term
197
218
  The prompt therefore requires the completion call to be standalone and last.
198
219
  The extension deliberately does not infer completion from phrases such as “I will present the plan,” and ordinary research or clarification turns never trigger automatic retries.
199
220
  `/plan finalize` and its exact canonical finalization prompt are explicit recovery requests.
200
- If one of those requests ends normally without a valid structured question or completed plan, Plan mode waits for `agent_settled` and retries once with stronger tool guidance.
221
+ With questionnaires enabled, if one of those requests ends normally without a valid structured question or completed plan, Plan mode waits for `agent_settled` and retries once with stronger tool guidance.
222
+ In free discussion, `/plan finalize` can finish the plan or ask a remaining material question in plain text; it does not start this structured-tool retry.
201
223
  A valid question, accepted completion, user cancellation, explicit exit, workflow supersession, reload, session replacement, or shutdown cancels the retry.
202
224
  A second prose-only failure leaves Plan mode active, warns in interactive modes, and requires another explicit `/plan finalize` request.
203
225
 
@@ -277,14 +299,16 @@ The extension deliberately does not infer completion from assistant prose or age
277
299
  Under **Off — conversation history only**, implementation messages remain ordinary conversation history and there is no active plan for `/plan exit` to remove.
278
300
  Choosing Stay before implementation keeps the plan ready.
279
301
  Revision feedback starts another Plan-mode turn and clears the previous implementable plan until an updated completion arrives.
280
- For clarification-only follow-ups, the agent answers and resubmits the complete unchanged plan so it remains implementable.
302
+ With questionnaires enabled, for clarification-only follow-ups, the agent answers and resubmits the complete unchanged plan so it remains implementable.
303
+ Free discussion can continue in plain text and uses the same revision flow when the user sends a follow-up.
281
304
  Before saving or implementation, exit/off discards the ready plan and removes its completion result from later non-Plan model context.
282
305
 
283
306
  While Plan mode is enabled, the extension also publishes a compact status for Pi statuslines.
284
307
  With `@narumitw/pi-statusline`, this appears in the extension status area:
285
308
 
286
- - `plan active`: Plan mode is enabled and still gathering context or drafting a plan.
287
- - `plan ready`: A completed plan is stored until you implement it, export it, save it, continue planning, or exit Plan mode.
309
+ - `plan active`: Plan mode is enabled with questionnaires available and is gathering context or drafting a plan.
310
+ - `plan discussion`: Free discussion is active with questionnaires paused; file edits remain blocked.
311
+ - `plan ready`: A completed plan is stored until you implement it, export it, save it, continue planning, or exit Plan mode; the widget still shows free discussion when active.
288
312
  - `plan saved`: One completed plan is stored outside model context in the current session until you implement or clear it.
289
313
  - `plan implementing`: The exact accepted plan is guaranteed under **Through first implementation run** or **Until manually cleared**.
290
314
 
@@ -301,6 +325,7 @@ During a guaranteed-plan implementation, it removes both the original implementa
301
325
  Plan and Normal requests share one append-only conversation.
302
326
  The extension appends one hidden, model-visible, versioned Plan contract before the first Plan prompt and one Normal contract before the first post-Plan Normal or implementation prompt.
303
327
  Ordinary linear turns do not rewrite or duplicate these contracts.
328
+ A separate versioned interaction contract is appended when a workflow starts or the user switches between questionnaires and discussion; existing Plan contracts and conversation history are not rewritten.
304
329
  The Plan contract explains native-tool opt-in and per-call nested enforcement; this wording changes future Plan transitions without rewriting existing transition messages.
305
330
  **Implement here** retains the Plan dialogue, structured questions, tool calls, completion evidence, and `Implement the plan.` kickoff in order.
306
331
  **Start fresh and implement** is the isolation path and transfers only the approved plan plus the Normal contract to a linked session.
@@ -375,8 +400,9 @@ The optional file is read at session start and watched for changes; only an expl
375
400
  ```
376
401
 
377
402
  By default, Plan mode inherits thinking, allows active safe built-ins, uses the planning model and thinking level for fresh implementation, exports to `PLAN.md`, and relies on ordinary conversation history after implementation starts.
378
- The shortcut is disabled unless configured; enabling, changing, or removing it takes effect after `/reload` or restarting Pi.
379
- Until then, the current shortcut binding stays unchanged.
403
+ The existing Plan-mode toggle shortcut (`toggleShortcut`) is disabled unless configured; enabling, changing, or removing it takes effect after `/reload` or restarting Pi.
404
+ Until then, that shortcut binding stays unchanged.
405
+ This setting is unrelated to the conditional F2 questionnaire/discussion toggle and does not configure it.
380
406
  Settings saves apply to later workflows; an active implementation keeps its captured reinjection policy.
381
407
  The export destination affects the next export immediately.
382
408
  Inactive built-in `grep`, `find`, and `ls` must be [enabled in Pi settings](./docs/settings.md#enable-inactive-built-in-search-tools-in-pi); Plan policy only grants execution permission.
@@ -397,7 +423,8 @@ This extension maps Codex's `ModeKind::Plan` behavior onto Pi's extension API:
397
423
 
398
424
  - Plan mode is conversational collaboration, not TODO or progress tracking.
399
425
  - `/plan <prompt>` enters Plan mode before submitting the prompt.
400
- - The agent uses `plan_mode_question` for material preferences and completes with a standalone `plan_mode_complete` call instead of prose detection.
426
+ - With questionnaires enabled, the agent uses `plan_mode_question` for material preferences; free discussion permits plain-text questions.
427
+ - The agent completes with a standalone `plan_mode_complete` call instead of prose detection.
401
428
  - `update_plan` is blocked until the explicit implementation boundary restores Normal mode.
402
429
  - The default `clear-on-start` policy uses conversation history; `clear-after-first-run` and `keep` add exact-plan guarantees.
403
430
  - Append-only Plan and Normal contracts keep helper schemas stable, but Pi's tool policy is risk reduction rather than Codex sandbox enforcement.
@@ -803,86 +803,6 @@ function createImplementationRetentionCoordinator() {
803
803
  };
804
804
  }
805
805
 
806
- // src/plan-export.ts
807
- import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
808
- import { dirname as dirname2, resolve } from "node:path";
809
- import { stripVTControlCharacters } from "node:util";
810
- import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
811
- async function exportStoredPlan(state, requestedPath, ctx, lifecycle, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
812
- const plan = (state.enabled ? state.latestPlan : void 0)?.trim() ?? state.savedPlan?.plan.trim() ?? state.activeImplementation?.plan.trim();
813
- if (!plan) {
814
- const error = new Error("No completed plan is available to export. Use /plan finalize when planning is complete.");
815
- if (!ctx.hasUI) throw error;
816
- ctx.ui.notify(error.message, "warning");
817
- return false;
818
- }
819
- const isCurrent = () => !lifecycle || lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state);
820
- let result;
821
- try {
822
- result = await exportPlanToFile(plan, requestedPath, ctx.cwd, lifecycle?.signal, isCurrent, defaultPath);
823
- } catch (error) {
824
- if (lifecycle?.signal.aborted || !isCurrent()) return false;
825
- if (!ctx.hasUI) throw error;
826
- const detail2 = error instanceof Error ? error.message : String(error);
827
- ctx.ui.notify(safeNotification(`Unable to export plan: ${detail2}`), "error");
828
- return false;
829
- }
830
- if (!isCurrent()) return false;
831
- const finishedReady = state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== void 0;
832
- if (finishedReady) lifecycle.finishReady?.();
833
- const detail = finishedReady ? " Plan mode disabled." : "";
834
- ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), "info");
835
- return true;
836
- }
837
- async function exportPlanToFile(plan, requestedPath, cwd, signal, isCurrent = () => true, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
838
- const path = resolvePlanExportPath(requestedPath, cwd, defaultPath);
839
- await withFileMutationQueue(path, async () => {
840
- throwIfCancelled(signal, isCurrent);
841
- await mkdir2(dirname2(path), { recursive: true });
842
- throwIfCancelled(signal, isCurrent);
843
- try {
844
- await writeFile2(path, `${plan}
845
- `, { encoding: "utf8", flag: "wx" });
846
- } catch (error) {
847
- if (isNodeError2(error) && error.code === "EEXIST") {
848
- throw new Error(`Plan export target already exists: ${path}. Choose another path or remove it first.`);
849
- }
850
- throw error;
851
- }
852
- });
853
- return { path };
854
- }
855
- function planExportDestination(defaultPath, cwd) {
856
- return {
857
- configuredPath: safeNotification(defaultPath),
858
- resolvedPath: safeNotification(resolvePlanExportPath(void 0, cwd, defaultPath))
859
- };
860
- }
861
- function resolvePlanExportPath(requestedPath, cwd, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
862
- const rawPath = requestedPath?.trim() || defaultPath;
863
- const normalizedPath = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
864
- if (!normalizedPath.trim()) throw new Error("Plan export path must not be empty.");
865
- if (normalizedPath.includes("\0")) {
866
- throw new Error("Plan export path must not contain NUL bytes.");
867
- }
868
- return resolve(cwd, normalizedPath);
869
- }
870
- function safeNotification(value) {
871
- let sanitized = "";
872
- for (const character of stripVTControlCharacters(value)) {
873
- const codePoint = character.codePointAt(0);
874
- sanitized += codePoint !== void 0 && codePoint > 31 && !(codePoint >= 127 && codePoint <= 159) ? character : " ";
875
- }
876
- return sanitized;
877
- }
878
- function throwIfCancelled(signal, isCurrent) {
879
- if (!signal?.aborted && isCurrent()) return;
880
- throw signal?.reason instanceof Error ? signal.reason : new DOMException("Plan export cancelled", "AbortError");
881
- }
882
- function isNodeError2(error) {
883
- return error instanceof Error && "code" in error;
884
- }
885
-
886
806
  // src/question-tool.ts
887
807
  var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
888
808
  var MAX_PLAN_MODE_RESPONSE_LENGTH = 4e3;
@@ -989,7 +909,12 @@ function normalizePlanModeQuestionParams(input) {
989
909
  return { ok: true, questions };
990
910
  }
991
911
  async function answerPlanModeQuestions(questions, ctx, lifecycle) {
992
- const answers = await askPlanModeQuestions(questions, ctx, () => lifecycle.isCurrent() && lifecycle.isEnabled());
912
+ const answers = await askPlanModeQuestions(
913
+ questions,
914
+ ctx,
915
+ () => lifecycle.isCurrent() && lifecycle.isEnabled(),
916
+ lifecycle.signal
917
+ );
993
918
  if (!lifecycle.isCurrent()) {
994
919
  return planModeQuestionCancelled(
995
920
  questions,
@@ -1004,12 +929,22 @@ async function answerPlanModeQuestions(questions, ctx, lifecycle) {
1004
929
  "Plan-mode question cancelled because Plan mode is no longer active."
1005
930
  );
1006
931
  }
932
+ if (lifecycle.discussionRequested?.()) {
933
+ return {
934
+ ...planModeQuestionCancelled(
935
+ questions,
936
+ "discussion_requested",
937
+ "The user switched to free discussion without submitting answers. Wait for the user to speak; do not reopen the questionnaire."
938
+ ),
939
+ terminate: true
940
+ };
941
+ }
1007
942
  if (!answers) {
1008
943
  return planModeQuestionCancelled(questions, "cancelled", "User cancelled the Plan-mode question prompt.");
1009
944
  }
1010
945
  return planModeQuestionAnswered(questions, answers);
1011
946
  }
1012
- async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
947
+ async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true, signal = ctx.signal) {
1013
948
  const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
1014
949
  if (!shouldContinue()) return void 0;
1015
950
  const runnerQuestions = questions.map((question, index) => ({
@@ -1026,7 +961,7 @@ async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true)
1026
961
  questions: runnerQuestions,
1027
962
  allowNotes: true,
1028
963
  maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
1029
- signal: ctx.signal,
964
+ signal,
1030
965
  isCurrent: shouldContinue
1031
966
  });
1032
967
  if (!shouldContinue()) return void 0;
@@ -1108,6 +1043,86 @@ function stringField(value) {
1108
1043
  return typeof value === "string" ? value.trim() : void 0;
1109
1044
  }
1110
1045
 
1046
+ // src/plan-export.ts
1047
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
1048
+ import { dirname as dirname2, resolve } from "node:path";
1049
+ import { stripVTControlCharacters } from "node:util";
1050
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
1051
+ async function exportStoredPlan(state, requestedPath, ctx, lifecycle, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1052
+ const plan = (state.enabled ? state.latestPlan : void 0)?.trim() ?? state.savedPlan?.plan.trim() ?? state.activeImplementation?.plan.trim();
1053
+ if (!plan) {
1054
+ const error = new Error("No completed plan is available to export. Use /plan finalize when planning is complete.");
1055
+ if (!ctx.hasUI) throw error;
1056
+ ctx.ui.notify(error.message, "warning");
1057
+ return false;
1058
+ }
1059
+ const isCurrent = () => !lifecycle || lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state);
1060
+ let result;
1061
+ try {
1062
+ result = await exportPlanToFile(plan, requestedPath, ctx.cwd, lifecycle?.signal, isCurrent, defaultPath);
1063
+ } catch (error) {
1064
+ if (lifecycle?.signal.aborted || !isCurrent()) return false;
1065
+ if (!ctx.hasUI) throw error;
1066
+ const detail2 = error instanceof Error ? error.message : String(error);
1067
+ ctx.ui.notify(safeNotification(`Unable to export plan: ${detail2}`), "error");
1068
+ return false;
1069
+ }
1070
+ if (!isCurrent()) return false;
1071
+ const finishedReady = state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== void 0;
1072
+ if (finishedReady) lifecycle.finishReady?.();
1073
+ const detail = finishedReady ? " Plan mode disabled." : "";
1074
+ ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), "info");
1075
+ return true;
1076
+ }
1077
+ async function exportPlanToFile(plan, requestedPath, cwd, signal, isCurrent = () => true, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1078
+ const path = resolvePlanExportPath(requestedPath, cwd, defaultPath);
1079
+ await withFileMutationQueue(path, async () => {
1080
+ throwIfCancelled(signal, isCurrent);
1081
+ await mkdir2(dirname2(path), { recursive: true });
1082
+ throwIfCancelled(signal, isCurrent);
1083
+ try {
1084
+ await writeFile2(path, `${plan}
1085
+ `, { encoding: "utf8", flag: "wx" });
1086
+ } catch (error) {
1087
+ if (isNodeError2(error) && error.code === "EEXIST") {
1088
+ throw new Error(`Plan export target already exists: ${path}. Choose another path or remove it first.`);
1089
+ }
1090
+ throw error;
1091
+ }
1092
+ });
1093
+ return { path };
1094
+ }
1095
+ function planExportDestination(defaultPath, cwd) {
1096
+ return {
1097
+ configuredPath: safeNotification(defaultPath),
1098
+ resolvedPath: safeNotification(resolvePlanExportPath(void 0, cwd, defaultPath))
1099
+ };
1100
+ }
1101
+ function resolvePlanExportPath(requestedPath, cwd, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1102
+ const rawPath = requestedPath?.trim() || defaultPath;
1103
+ const normalizedPath = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
1104
+ if (!normalizedPath.trim()) throw new Error("Plan export path must not be empty.");
1105
+ if (normalizedPath.includes("\0")) {
1106
+ throw new Error("Plan export path must not contain NUL bytes.");
1107
+ }
1108
+ return resolve(cwd, normalizedPath);
1109
+ }
1110
+ function safeNotification(value) {
1111
+ let sanitized = "";
1112
+ for (const character of stripVTControlCharacters(value)) {
1113
+ const codePoint = character.codePointAt(0);
1114
+ sanitized += codePoint !== void 0 && codePoint > 31 && !(codePoint >= 127 && codePoint <= 159) ? character : " ";
1115
+ }
1116
+ return sanitized;
1117
+ }
1118
+ function throwIfCancelled(signal, isCurrent) {
1119
+ if (!signal?.aborted && isCurrent()) return;
1120
+ throw signal?.reason instanceof Error ? signal.reason : new DOMException("Plan export cancelled", "AbortError");
1121
+ }
1122
+ function isNodeError2(error) {
1123
+ return error instanceof Error && "code" in error;
1124
+ }
1125
+
1111
1126
  // src/tool-availability.ts
1112
1127
  function planModeToolAvailability(tool, activeNames, route = "selection") {
1113
1128
  switch (tool.exposure) {
@@ -1858,13 +1873,13 @@ export {
1858
1873
  retentionLabel,
1859
1874
  implementationRetentionPreview,
1860
1875
  createImplementationRetentionCoordinator,
1861
- exportStoredPlan,
1862
- planExportDestination,
1863
1876
  PLAN_MODE_QUESTION_TOOL_NAME,
1864
1877
  PLAN_MODE_QUESTION_PARAMS,
1865
1878
  normalizePlanModeQuestionParams,
1866
1879
  answerPlanModeQuestions,
1867
1880
  planModeQuestionCancelled,
1881
+ exportStoredPlan,
1882
+ planExportDestination,
1868
1883
  planModeToolAvailability,
1869
1884
  classifyPlanModeTool,
1870
1885
  canSelectToolInPlanMode,
@@ -1877,4 +1892,4 @@ export {
1877
1892
  defaultPlanModeToolNames,
1878
1893
  snapshotPlanModeSelectedNames
1879
1894
  };
1880
- //# sourceMappingURL=chunk-W7D6N2MI.ts.map
1895
+ //# sourceMappingURL=chunk-UJ6TV2YV.ts.map