@narumitw/pi-plan-mode 0.52.0 → 0.54.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.
@@ -1,5 +1,5 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
- // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
2
+ // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
 
4
4
  // src/completion-tool.ts
5
5
  import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
@@ -75,6 +75,7 @@ var PLAN_CONTEXT_MESSAGE_TYPE = "plan-mode-context";
75
75
  var PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE = "plan-mode-implementation-context";
76
76
  var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
77
77
  var PLAN_IMPLEMENTATION_HANDOFF_PREFIX = "Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:";
78
+ var PLAN_HISTORY_IMPLEMENTATION_PROMPT = "Implement the plan.";
78
79
  var PROPOSED_PLAN_PATTERN = /^<proposed_plan>[\t ]*\r?\n([\s\S]*?)\r?\n<\/proposed_plan>[\t ]*$/gm;
79
80
  var PROPOSED_PLAN_BLOCK_PATTERN = /^<proposed_plan>[\t ]*\r?\n[\s\S]*?\r?\n<\/proposed_plan>[\t ]*$/gm;
80
81
  function parseProposedPlan(text) {
@@ -108,6 +109,19 @@ function latestAssistantText(messages) {
108
109
  }
109
110
  return "";
110
111
  }
112
+ function latestAssistantStopReason(messages) {
113
+ if (!Array.isArray(messages)) return void 0;
114
+ for (const entry of [...messages].reverse()) {
115
+ const message = entry?.message ?? entry;
116
+ if (message?.role === "assistant") return message.stopReason;
117
+ }
118
+ return void 0;
119
+ }
120
+ function messageTextContent(message) {
121
+ return messageText(
122
+ message?.message ?? message
123
+ );
124
+ }
111
125
  function messageContainsLegacyPlanModeContextArtifact(message) {
112
126
  return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;
113
127
  }
@@ -115,9 +129,18 @@ function messageContainsPlanModeImplementationContextArtifact(message) {
115
129
  return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;
116
130
  }
117
131
  function injectActiveImplementationContext(messages, activeImplementation) {
132
+ let foundCurrentContext = false;
118
133
  let foundCurrentHandoff = false;
134
+ const expectedContext = activeImplementationContextContent(activeImplementation);
119
135
  const messagesWithoutStaleContext = messages.filter((message) => {
120
- if (messageContainsPlanModeImplementationContextArtifact(message)) return false;
136
+ if (messageContainsPlanModeImplementationContextArtifact(message)) {
137
+ const candidate = unwrapSessionMessage(message);
138
+ if (!foundCurrentContext && candidate.content === expectedContext) {
139
+ foundCurrentContext = true;
140
+ return true;
141
+ }
142
+ return false;
143
+ }
121
144
  if (!messageContainsPlanModeImplementationHandoff(message)) return true;
122
145
  if (!foundCurrentHandoff && messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)) {
123
146
  foundCurrentHandoff = true;
@@ -125,17 +148,13 @@ function injectActiveImplementationContext(messages, activeImplementation) {
125
148
  }
126
149
  return false;
127
150
  });
128
- if (foundCurrentHandoff) return messagesWithoutStaleContext;
151
+ if (foundCurrentHandoff || foundCurrentContext) return messagesWithoutStaleContext;
129
152
  let insertionIndex = 0;
130
153
  while (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;
131
154
  const contextMessage = {
132
155
  role: "custom",
133
156
  customType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,
134
- content: `[ACTIVE IMPLEMENTATION PLAN]
135
-
136
- The user approved the exact implementation plan below. Continue following it until the user explicitly clears or supersedes it. The exact plan is the remainder of this message:
137
-
138
- ${activeImplementation.plan}`,
157
+ content: expectedContext,
139
158
  display: false,
140
159
  timestamp: activeImplementation.startedAt
141
160
  };
@@ -145,10 +164,68 @@ ${activeImplementation.plan}`,
145
164
  ...messagesWithoutStaleContext.slice(insertionIndex)
146
165
  ];
147
166
  }
167
+ function activeImplementationContextContent(activeImplementation) {
168
+ return `[ACTIVE IMPLEMENTATION PLAN]
169
+
170
+ The user approved the exact implementation plan below. Continue following it until the user explicitly clears or supersedes it. The exact plan is the remainder of this message:
171
+
172
+ ${activeImplementation.plan}`;
173
+ }
148
174
  function messageContainsInactivePlanModeArtifact(message) {
149
175
  const candidate = unwrapSessionMessage(message);
150
176
  return candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE || candidate.role === "toolResult" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
151
177
  }
178
+ function findHistoryImplementationArtifact(messages) {
179
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
180
+ const candidate = unwrapSessionMessage(messages[index]);
181
+ if (candidate.role !== "user" || contentText(candidate.content).trim() !== PLAN_HISTORY_IMPLEMENTATION_PROMPT) {
182
+ continue;
183
+ }
184
+ const artifact = findHistoryImplementationArtifactBeforeKickoff(messages, index);
185
+ if (artifact) return artifact;
186
+ }
187
+ return void 0;
188
+ }
189
+ function findHistoryImplementationArtifactBeforeKickoff(messages, kickoffIndex) {
190
+ for (let index = kickoffIndex - 1; index >= 0; index -= 1) {
191
+ const candidate = unwrapSessionMessage(messages[index]);
192
+ if (candidate.role === "user" || isSummaryMessage(messages[index])) return void 0;
193
+ if (candidate.role === "toolResult" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME) {
194
+ const toolCallId = candidate.toolCallId;
195
+ const toolCallMessageIndex = toolCallId ? findPlanModeCompletionCallMessageIndex(messages, index, toolCallId) : void 0;
196
+ if (toolCallId && toolCallMessageIndex !== void 0) {
197
+ return {
198
+ messageIndex: index,
199
+ kind: "completion",
200
+ toolCallId,
201
+ toolCallMessageIndex
202
+ };
203
+ }
204
+ continue;
205
+ }
206
+ if (candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE) {
207
+ return { messageIndex: index, kind: "presentation" };
208
+ }
209
+ if (candidate.role === "assistant" && contentText(candidate.content).match(PROPOSED_PLAN_BLOCK_PATTERN)) {
210
+ return { messageIndex: index, kind: "legacy" };
211
+ }
212
+ }
213
+ return void 0;
214
+ }
215
+ function findPlanModeCompletionCallMessageIndex(messages, endIndex, toolCallId) {
216
+ for (let index = endIndex - 1; index >= 0; index -= 1) {
217
+ const candidate = unwrapSessionMessage(messages[index]);
218
+ if (candidate.role === "user" || isSummaryMessage(messages[index])) return void 0;
219
+ if (!Array.isArray(candidate.content)) continue;
220
+ if (candidate.content.some((block) => {
221
+ const toolCall = block;
222
+ return toolCall.type === "toolCall" && toolCall.id === toolCallId && toolCall.name === PLAN_MODE_COMPLETE_TOOL_NAME;
223
+ })) {
224
+ return index;
225
+ }
226
+ }
227
+ return void 0;
228
+ }
152
229
  function messageContainsPlanModeImplementationHandoff(message) {
153
230
  const candidate = unwrapSessionMessage(message);
154
231
  return candidate.role === "user" && contentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX);
@@ -167,12 +244,12 @@ function isSummaryMessage(message) {
167
244
  function stripProposedPlanBlocksFromMessage(message) {
168
245
  return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);
169
246
  }
170
- function stripPlanModeCompletionCallsFromMessage(message) {
247
+ function stripPlanModeCompletionCallsFromMessage(message, preservedToolCallId) {
171
248
  return replaceAssistantContent(message, (content) => {
172
249
  if (!Array.isArray(content)) return content;
173
250
  const nextContent = content.filter((block) => {
174
251
  const candidate = block;
175
- return !(candidate.type === "toolCall" && candidate.name === PLAN_MODE_COMPLETE_TOOL_NAME);
252
+ return !(candidate.type === "toolCall" && candidate.name === PLAN_MODE_COMPLETE_TOOL_NAME && (!preservedToolCallId || candidate.id !== preservedToolCallId));
176
253
  });
177
254
  return nextContent.length === content.length ? content : nextContent;
178
255
  });
@@ -227,19 +304,253 @@ function contentText(content) {
227
304
  }).filter(Boolean).join("\n");
228
305
  }
229
306
 
307
+ // src/question-tool.ts
308
+ var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
309
+ var MAX_PLAN_MODE_RESPONSE_LENGTH = 4e3;
310
+ var PLAN_MODE_QUESTION_PARAMS = {
311
+ type: "object",
312
+ additionalProperties: false,
313
+ required: ["questions"],
314
+ properties: {
315
+ questions: {
316
+ type: "array",
317
+ minItems: 1,
318
+ maxItems: 3,
319
+ description: "Questions to show the user. Prefer 1 and do not exceed 3.",
320
+ items: {
321
+ type: "object",
322
+ additionalProperties: false,
323
+ required: ["id", "header", "question", "options"],
324
+ properties: {
325
+ id: {
326
+ type: "string",
327
+ description: "Stable identifier for mapping answers (snake_case)."
328
+ },
329
+ header: {
330
+ type: "string",
331
+ description: "Short header label shown in the UI (12 or fewer chars)."
332
+ },
333
+ question: { type: "string", description: "Single-sentence prompt shown to the user." },
334
+ options: {
335
+ type: "array",
336
+ minItems: 2,
337
+ maxItems: 4,
338
+ description: "Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.",
339
+ items: {
340
+ type: "object",
341
+ additionalProperties: false,
342
+ required: ["label", "description"],
343
+ properties: {
344
+ label: { type: "string", description: "User-facing label (1-5 words)." },
345
+ description: {
346
+ type: "string",
347
+ description: "One short sentence explaining impact/tradeoff if selected."
348
+ }
349
+ }
350
+ }
351
+ }
352
+ }
353
+ }
354
+ }
355
+ }
356
+ };
357
+ function normalizePlanModeQuestionParams(input) {
358
+ if (!isRecord2(input) || !Array.isArray(input.questions)) {
359
+ return { ok: false, error: "questions must be an array" };
360
+ }
361
+ if (input.questions.length < 1 || input.questions.length > 3) {
362
+ return { ok: false, error: "questions must contain 1-3 items" };
363
+ }
364
+ const questions = [];
365
+ for (const [questionIndex, rawQuestion] of input.questions.entries()) {
366
+ if (!isRecord2(rawQuestion)) {
367
+ return { ok: false, error: `question ${questionIndex + 1} must be an object` };
368
+ }
369
+ const id = stringField(rawQuestion.id);
370
+ const header = stringField(rawQuestion.header);
371
+ const question = stringField(rawQuestion.question);
372
+ if (!id || !header || !question) {
373
+ return {
374
+ ok: false,
375
+ error: `question ${questionIndex + 1} requires non-empty id, header, and question`
376
+ };
377
+ }
378
+ if (!Array.isArray(rawQuestion.options)) {
379
+ return { ok: false, error: `question ${questionIndex + 1} options must be an array` };
380
+ }
381
+ if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {
382
+ return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };
383
+ }
384
+ const options = [];
385
+ for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {
386
+ if (!isRecord2(rawOption)) {
387
+ return {
388
+ ok: false,
389
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`
390
+ };
391
+ }
392
+ const label = stringField(rawOption.label);
393
+ if (!label) {
394
+ return {
395
+ ok: false,
396
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`
397
+ };
398
+ }
399
+ const description = stringField(rawOption.description);
400
+ if (!description) {
401
+ return {
402
+ ok: false,
403
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`
404
+ };
405
+ }
406
+ options.push({ label, description });
407
+ }
408
+ questions.push({ id, header, question, options });
409
+ }
410
+ return { ok: true, questions };
411
+ }
412
+ async function answerPlanModeQuestions(questions, ctx, lifecycle) {
413
+ const answers = await askPlanModeQuestions(
414
+ questions,
415
+ ctx,
416
+ () => lifecycle.isCurrent() && lifecycle.isEnabled()
417
+ );
418
+ if (!lifecycle.isCurrent()) {
419
+ return planModeQuestionCancelled(
420
+ questions,
421
+ "cancelled",
422
+ "Plan-mode question cancelled because the session changed."
423
+ );
424
+ }
425
+ if (!lifecycle.isEnabled()) {
426
+ return planModeQuestionCancelled(
427
+ questions,
428
+ "plan_mode_inactive",
429
+ "Plan-mode question cancelled because Plan mode is no longer active."
430
+ );
431
+ }
432
+ if (!answers) {
433
+ return planModeQuestionCancelled(
434
+ questions,
435
+ "cancelled",
436
+ "User cancelled the Plan-mode question prompt."
437
+ );
438
+ }
439
+ return planModeQuestionAnswered(questions, answers);
440
+ }
441
+ async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
442
+ const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
443
+ if (!shouldContinue()) return void 0;
444
+ const runnerQuestions = questions.map((question, index) => ({
445
+ id: String(index),
446
+ header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),
447
+ prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),
448
+ options: question.options.map((option, optionIndex) => ({
449
+ ...option,
450
+ label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText)
451
+ }))
452
+ }));
453
+ const result = await runQuestionnaire(ctx, {
454
+ questions: runnerQuestions,
455
+ allowNotes: true,
456
+ maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
457
+ signal: ctx.signal,
458
+ isCurrent: shouldContinue
459
+ });
460
+ if (!shouldContinue()) return void 0;
461
+ return mapQuestionnaireResult(questions, result);
462
+ }
463
+ function mapQuestionnaireResult(questions, result) {
464
+ if (result.kind !== "submitted") return void 0;
465
+ if (result.answers.length !== questions.length) {
466
+ throw new Error("Questionnaire returned an incomplete answer set");
467
+ }
468
+ const answers = /* @__PURE__ */ new Map();
469
+ for (const answer of result.answers) {
470
+ const index = Number(answer.questionId);
471
+ if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {
472
+ throw new Error("Questionnaire returned an answer for an unknown question");
473
+ }
474
+ if (answers.has(index)) throw new Error("Questionnaire returned duplicate answers");
475
+ if (answer.wasCustom) {
476
+ if (answer.optionIndex !== void 0) {
477
+ throw new Error("Questionnaire returned a custom answer with an option index");
478
+ }
479
+ if (!answer.answer.trim()) return void 0;
480
+ } else if (answer.optionIndex === void 0 || !questions[index]?.options[answer.optionIndex - 1]) {
481
+ throw new Error("Questionnaire returned an invalid selected option");
482
+ }
483
+ answers.set(index, answer);
484
+ }
485
+ return questions.map((question, index) => {
486
+ const answer = answers.get(index);
487
+ if (!answer) throw new Error("Questionnaire returned an incomplete answer set");
488
+ const answerText = answer.wasCustom ? answer.answer : question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer;
489
+ return answerFor(question, answerText, {
490
+ wasCustom: answer.wasCustom,
491
+ optionIndex: answer.optionIndex,
492
+ note: answer.note
493
+ });
494
+ });
495
+ }
496
+ function displayText(value, fallback, sanitize) {
497
+ const sanitized = sanitize(value);
498
+ return sanitized.trim() ? sanitized : fallback;
499
+ }
500
+ function answerFor(question, answer, options) {
501
+ const result = {
502
+ id: question.id,
503
+ header: question.header,
504
+ question: question.question,
505
+ answer,
506
+ wasCustom: options.wasCustom
507
+ };
508
+ if (options.optionIndex !== void 0) result.optionIndex = options.optionIndex;
509
+ if (options.note !== void 0) result.note = options.note;
510
+ return result;
511
+ }
512
+ function planModeQuestionAnswered(questions, answers) {
513
+ return {
514
+ content: [
515
+ { type: "text", text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }
516
+ ],
517
+ details: { cancelled: false, questions, answers }
518
+ };
519
+ }
520
+ function planModeQuestionCancelled(questions, reason, message) {
521
+ return {
522
+ content: [
523
+ {
524
+ type: "text",
525
+ text: formatPlanModeQuestionPayload({ cancelled: true, reason, message })
526
+ }
527
+ ],
528
+ details: { cancelled: true, reason, questions }
529
+ };
530
+ }
531
+ function formatPlanModeQuestionPayload(payload) {
532
+ return JSON.stringify(payload, null, 2);
533
+ }
534
+ function isRecord2(value) {
535
+ return typeof value === "object" && value !== null;
536
+ }
537
+ function stringField(value) {
538
+ return typeof value === "string" ? value.trim() : void 0;
539
+ }
540
+
230
541
  // src/implementation-retention.ts
231
542
  function retentionLabel(retention) {
232
543
  return {
233
- keep: "Keep plan active",
234
- "clear-on-start": "Use plan for handoff only",
235
- "clear-after-first-run": "Clear after first implementation run"
544
+ "clear-on-start": "Off \u2014 conversation history only",
545
+ "clear-after-first-run": "Through first implementation run",
546
+ keep: "Until manually cleared"
236
547
  }[retention];
237
548
  }
238
549
  function implementationRetentionPreview(retention) {
239
550
  return {
240
- keep: "After Implement: Keep plan active until /plan exit.",
241
- "clear-on-start": "After Implement: Use the plan for the implementation handoff only, then clear it.",
242
- "clear-after-first-run": "After Implement: Clear after the first implementation run settles."
551
+ "clear-on-start": "Plan reinjection: Off; use conversation history only.",
552
+ "clear-after-first-run": "Plan reinjection: Through the first implementation run.",
553
+ keep: "Plan reinjection: Until /plan exit."
243
554
  }[retention];
244
555
  }
245
556
  function createImplementationRetentionCoordinator() {
@@ -250,21 +561,33 @@ function createImplementationRetentionCoordinator() {
250
561
  restoredImplementationAwaitingContext = activeImplementation && activeImplementation.retention !== "keep" ? activeImplementation.id : void 0;
251
562
  },
252
563
  transformContext(messages, state) {
253
- const messagesWithoutPlanContext = messages.filter(
254
- (message) => !messageContainsLegacyPlanModeContextArtifact(message) && !messageContainsPlanModeImplementationContextArtifact(message)
564
+ const messagesWithoutLegacyContext = messages.filter(
565
+ (message) => !messageContainsLegacyPlanModeContextArtifact(message)
255
566
  );
256
567
  if (state.enabled) {
257
568
  return {
258
- messages: messagesWithoutPlanContext.filter(
259
- (message) => !messageContainsPlanModeImplementationHandoff(message)
569
+ messages: messagesWithoutLegacyContext.filter(
570
+ (message) => !messageContainsPlanModeImplementationContextArtifact(message) && !messageContainsPlanModeImplementationHandoff(message)
260
571
  )
261
572
  };
262
573
  }
263
574
  const activeImplementation = state.activeImplementation;
264
- const inactiveMessages = activeImplementation ? messagesWithoutPlanContext : messagesWithoutPlanContext.filter(
265
- (message) => !messageContainsPlanModeImplementationHandoff(message)
575
+ const inactiveMessages = activeImplementation ? messagesWithoutLegacyContext : messagesWithoutLegacyContext.filter(
576
+ (message) => !messageContainsPlanModeImplementationContextArtifact(message) && !messageContainsPlanModeImplementationHandoff(message)
266
577
  );
267
- const filteredMessages = inactiveMessages.filter((message) => !messageContainsInactivePlanModeArtifact(message)).map(stripProposedPlanBlocksFromMessage).map(stripPlanModeCompletionCallsFromMessage).filter((message) => !isEmptyAssistantMessage(message));
578
+ const historyArtifact = activeImplementation ? void 0 : findHistoryImplementationArtifact(inactiveMessages);
579
+ const historyArtifactMessage = historyArtifact ? inactiveMessages[historyArtifact.messageIndex] : void 0;
580
+ const historyToolCallMessage = historyArtifact?.toolCallMessageIndex !== void 0 ? inactiveMessages[historyArtifact.toolCallMessageIndex] : void 0;
581
+ const filteredMessages = inactiveMessages.filter(
582
+ (message) => message === historyArtifactMessage || !messageContainsInactivePlanModeArtifact(message)
583
+ ).map(
584
+ (message) => message === historyArtifactMessage && historyArtifact?.kind === "legacy" ? message : stripProposedPlanBlocksFromMessage(message)
585
+ ).map(
586
+ (message) => stripPlanModeCompletionCallsFromMessage(
587
+ message,
588
+ message === historyToolCallMessage ? historyArtifact?.toolCallId : void 0
589
+ )
590
+ ).filter((message) => !isEmptyAssistantMessage(message));
268
591
  if (!activeImplementation) return { messages: filteredMessages };
269
592
  const contextualMessages = injectActiveImplementationContext(
270
593
  filteredMessages,
@@ -321,7 +644,14 @@ var SAFE_GIT_SUBCOMMANDS = [
321
644
  ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS
322
645
  ];
323
646
  var SAFE_GH_SUBCOMMAND_PATHS = ["pr view", "pr list", "issue view", "issue list"];
324
- var SAFE_BUILTIN_PLAN_TOOLS = /* @__PURE__ */ new Set(["read", "bash", "grep", "find", "ls"]);
647
+ var SAFE_BUILTIN_PLAN_TOOLS = /* @__PURE__ */ new Set([
648
+ "read",
649
+ "bash",
650
+ "powershell",
651
+ "grep",
652
+ "find",
653
+ "ls"
654
+ ]);
325
655
  var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
326
656
  var MUTATING_COMMANDS = /* @__PURE__ */ new Set([
327
657
  "rm",
@@ -351,6 +681,21 @@ var MUTATING_COMMANDS = /* @__PURE__ */ new Set([
351
681
  "code",
352
682
  "subl"
353
683
  ]);
684
+ var READ_ONLY_POWERSHELL_COMMANDS = /* @__PURE__ */ new Set([
685
+ "format-list",
686
+ "format-table",
687
+ "get-childitem",
688
+ "get-content",
689
+ "get-item",
690
+ "get-location",
691
+ "measure-object",
692
+ "out-string",
693
+ "resolve-path",
694
+ "select-string",
695
+ "sort-object",
696
+ "test-path",
697
+ "write-output"
698
+ ]);
354
699
  var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
355
700
  "cat",
356
701
  "head",
@@ -392,7 +737,7 @@ function isBuiltinTool(tool) {
392
737
  function classifyPlanModeTool(tool) {
393
738
  if (!isBuiltinTool(tool)) return "user-opt-in";
394
739
  if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return "blocked";
395
- if (tool.name === "bash") return "limited";
740
+ if (tool.name === "bash" || tool.name === "powershell") return "limited";
396
741
  return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? "read-only" : "blocked";
397
742
  }
398
743
  function canSelectToolInPlanMode(tool) {
@@ -407,6 +752,107 @@ function findBlockedCommandSegment(command, safeSubcommands = {}) {
407
752
  if (!segments || segments.length === 0) return command.trim() || "(empty command)";
408
753
  return segments.find((segment) => !isSafeSegment(segment, safeSubcommands));
409
754
  }
755
+ function findBlockedPowerShellCommandSegment(command, safeSubcommands = {}) {
756
+ const segments = splitPowerShellSegments(command);
757
+ if (!segments || segments.length === 0) return command.trim() || "(empty command)";
758
+ return segments.find((segment) => !isSafePowerShellSegment(segment, safeSubcommands));
759
+ }
760
+ function splitPowerShellSegments(command) {
761
+ const trimmed = command.trim();
762
+ if (!trimmed || /[\n\r`\u2018-\u201e]/.test(trimmed)) return void 0;
763
+ const segments = [];
764
+ let quote;
765
+ let start = 0;
766
+ for (let index = 0; index < trimmed.length; index += 1) {
767
+ const character = trimmed[index];
768
+ if (quote === "'") {
769
+ if (character !== "'") continue;
770
+ if (trimmed[index + 1] === "'") {
771
+ index += 1;
772
+ continue;
773
+ }
774
+ quote = void 0;
775
+ continue;
776
+ }
777
+ if (quote === '"') {
778
+ if (character === "$" || character === "`") return void 0;
779
+ if (character === '"') quote = void 0;
780
+ continue;
781
+ }
782
+ if (character === "'" || character === '"') {
783
+ quote = character;
784
+ continue;
785
+ }
786
+ if (["$", "@", "#", "!", "?", "{", "}", "(", ")", "[", "]", ">", "<"].includes(character)) {
787
+ return void 0;
788
+ }
789
+ const next = trimmed[index + 1];
790
+ if (character === "&" || character === "|" && next === "|") return void 0;
791
+ const separatorLength = character === ";" || character === "|" ? 1 : 0;
792
+ if (separatorLength === 0) continue;
793
+ const segment = trimmed.slice(start, index).trim();
794
+ if (!segment) return void 0;
795
+ segments.push(segment);
796
+ index += separatorLength - 1;
797
+ start = index + 1;
798
+ }
799
+ if (quote) return void 0;
800
+ const finalSegment = trimmed.slice(start).trim();
801
+ if (!finalSegment) return void 0;
802
+ segments.push(finalSegment);
803
+ return segments;
804
+ }
805
+ function isSafePowerShellSegment(segment, safeSubcommands) {
806
+ const tokens = powerShellWords(segment);
807
+ if (!tokens || tokens.length === 0 || tokens.includes("--%")) return false;
808
+ const command = tokens[0]?.toLowerCase();
809
+ if (!command) return false;
810
+ const args = tokens.slice(1);
811
+ if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
812
+ if (command !== "git" && command !== "gh") return false;
813
+ return isSafeStructuredCommand(command, args, safeSubcommands);
814
+ }
815
+ function powerShellWords(segment) {
816
+ const words = [];
817
+ let word = "";
818
+ let hasWord = false;
819
+ let quote;
820
+ for (let index = 0; index < segment.length; index += 1) {
821
+ const character = segment[index];
822
+ if (quote === "'") {
823
+ if (character !== "'") {
824
+ word += character;
825
+ continue;
826
+ }
827
+ if (segment[index + 1] === "'") {
828
+ word += "'";
829
+ index += 1;
830
+ continue;
831
+ }
832
+ quote = void 0;
833
+ continue;
834
+ }
835
+ if (quote === '"') {
836
+ if (character === '"') quote = void 0;
837
+ else word += character;
838
+ continue;
839
+ }
840
+ if (character === "'" || character === '"') {
841
+ quote = character;
842
+ hasWord = true;
843
+ } else if (/\s/.test(character)) {
844
+ if (hasWord) words.push(word);
845
+ word = "";
846
+ hasWord = false;
847
+ } else {
848
+ word += character;
849
+ hasWord = true;
850
+ }
851
+ }
852
+ if (quote) return void 0;
853
+ if (hasWord) words.push(word);
854
+ return words;
855
+ }
410
856
  function splitShellSegments(command) {
411
857
  const trimmed = command.trim();
412
858
  if (!trimmed || /[\n\r`]/.test(trimmed)) return void 0;
@@ -723,10 +1169,12 @@ var PLAN_MODE_THINKING_LEVELS = [
723
1169
  "max"
724
1170
  ];
725
1171
  var IMPLEMENTATION_PLAN_RETENTIONS = [
726
- "keep",
727
1172
  "clear-on-start",
728
- "clear-after-first-run"
1173
+ "clear-after-first-run",
1174
+ "keep"
729
1175
  ];
1176
+ var PLAN_MODE_TOOL_VISIBILITIES = ["always", "after-first-plan"];
1177
+ var DEFAULT_PLAN_MODE_TOOL_VISIBILITY = "after-first-plan";
730
1178
  var DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
731
1179
  var MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]);
732
1180
  var BASE_KEYS = /* @__PURE__ */ new Set([
@@ -799,6 +1247,13 @@ function normalizePlanModeSettings(value) {
799
1247
  const settings = {
800
1248
  thinkingLevel
801
1249
  };
1250
+ if (Object.hasOwn(value, "toolVisibility")) {
1251
+ const toolVisibility = Reflect.get(value, "toolVisibility");
1252
+ if (!PLAN_MODE_TOOL_VISIBILITIES.includes(toolVisibility)) {
1253
+ return void 0;
1254
+ }
1255
+ settings.toolVisibility = toolVisibility;
1256
+ }
802
1257
  if (Object.hasOwn(value, "defaultPlanTools")) {
803
1258
  const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
804
1259
  if (!defaultPlanTools) return void 0;
@@ -916,6 +1371,7 @@ function updatePlanModeSettings(patch, options = {}) {
916
1371
  const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
917
1372
  const updated = { ...current };
918
1373
  if (patch.thinkingLevel !== void 0) updated.thinkingLevel = patch.thinkingLevel;
1374
+ if (patch.toolVisibility !== void 0) updated.toolVisibility = patch.toolVisibility;
919
1375
  if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
920
1376
  else if (patch.defaultPlanTools !== void 0) {
921
1377
  updated.defaultPlanTools = [...patch.defaultPlanTools];
@@ -1074,8 +1530,11 @@ function safeReadError(error) {
1074
1530
  function configuredThinkingLevel(settings) {
1075
1531
  return settings.thinkingLevel === "inherit" ? void 0 : settings.thinkingLevel;
1076
1532
  }
1533
+ function configuredPlanModeToolVisibility(settings) {
1534
+ return settings.toolVisibility ?? DEFAULT_PLAN_MODE_TOOL_VISIBILITY;
1535
+ }
1077
1536
  function configuredImplementationPlanRetention(settings) {
1078
- return settings.implementationPlanRetention ?? "keep";
1537
+ return settings.implementationPlanRetention ?? "clear-on-start";
1079
1538
  }
1080
1539
  function configuredPlanExportPath(settings) {
1081
1540
  return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
@@ -1175,254 +1634,6 @@ function isNodeError2(error) {
1175
1634
  return error instanceof Error && "code" in error;
1176
1635
  }
1177
1636
 
1178
- // src/question-tool.ts
1179
- var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
1180
- var MAX_PLAN_MODE_RESPONSE_LENGTH = 4e3;
1181
- var PLAN_MODE_QUESTION_PARAMS = {
1182
- type: "object",
1183
- additionalProperties: false,
1184
- required: ["questions"],
1185
- properties: {
1186
- questions: {
1187
- type: "array",
1188
- minItems: 1,
1189
- maxItems: 3,
1190
- description: "Questions to show the user. Prefer 1 and do not exceed 3.",
1191
- items: {
1192
- type: "object",
1193
- additionalProperties: false,
1194
- required: ["id", "header", "question", "options"],
1195
- properties: {
1196
- id: {
1197
- type: "string",
1198
- description: "Stable identifier for mapping answers (snake_case)."
1199
- },
1200
- header: {
1201
- type: "string",
1202
- description: "Short header label shown in the UI (12 or fewer chars)."
1203
- },
1204
- question: { type: "string", description: "Single-sentence prompt shown to the user." },
1205
- options: {
1206
- type: "array",
1207
- minItems: 2,
1208
- maxItems: 4,
1209
- description: "Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.",
1210
- items: {
1211
- type: "object",
1212
- additionalProperties: false,
1213
- required: ["label", "description"],
1214
- properties: {
1215
- label: { type: "string", description: "User-facing label (1-5 words)." },
1216
- description: {
1217
- type: "string",
1218
- description: "One short sentence explaining impact/tradeoff if selected."
1219
- }
1220
- }
1221
- }
1222
- }
1223
- }
1224
- }
1225
- }
1226
- }
1227
- };
1228
- function normalizePlanModeQuestionParams(input) {
1229
- if (!isRecord2(input) || !Array.isArray(input.questions)) {
1230
- return { ok: false, error: "questions must be an array" };
1231
- }
1232
- if (input.questions.length < 1 || input.questions.length > 3) {
1233
- return { ok: false, error: "questions must contain 1-3 items" };
1234
- }
1235
- const questions = [];
1236
- for (const [questionIndex, rawQuestion] of input.questions.entries()) {
1237
- if (!isRecord2(rawQuestion)) {
1238
- return { ok: false, error: `question ${questionIndex + 1} must be an object` };
1239
- }
1240
- const id = stringField(rawQuestion.id);
1241
- const header = stringField(rawQuestion.header);
1242
- const question = stringField(rawQuestion.question);
1243
- if (!id || !header || !question) {
1244
- return {
1245
- ok: false,
1246
- error: `question ${questionIndex + 1} requires non-empty id, header, and question`
1247
- };
1248
- }
1249
- if (!Array.isArray(rawQuestion.options)) {
1250
- return { ok: false, error: `question ${questionIndex + 1} options must be an array` };
1251
- }
1252
- if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {
1253
- return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };
1254
- }
1255
- const options = [];
1256
- for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {
1257
- if (!isRecord2(rawOption)) {
1258
- return {
1259
- ok: false,
1260
- error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`
1261
- };
1262
- }
1263
- const label = stringField(rawOption.label);
1264
- if (!label) {
1265
- return {
1266
- ok: false,
1267
- error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`
1268
- };
1269
- }
1270
- const description = stringField(rawOption.description);
1271
- if (!description) {
1272
- return {
1273
- ok: false,
1274
- error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`
1275
- };
1276
- }
1277
- options.push({ label, description });
1278
- }
1279
- questions.push({ id, header, question, options });
1280
- }
1281
- return { ok: true, questions };
1282
- }
1283
- async function answerPlanModeQuestions(questions, ctx, lifecycle) {
1284
- const answers = await askPlanModeQuestions(
1285
- questions,
1286
- ctx,
1287
- () => lifecycle.isCurrent() && lifecycle.isEnabled()
1288
- );
1289
- if (!lifecycle.isCurrent()) {
1290
- return planModeQuestionCancelled(
1291
- questions,
1292
- "cancelled",
1293
- "Plan-mode question cancelled because the session changed."
1294
- );
1295
- }
1296
- if (!lifecycle.isEnabled()) {
1297
- return planModeQuestionCancelled(
1298
- questions,
1299
- "plan_mode_inactive",
1300
- "Plan-mode question cancelled because Plan mode is no longer active."
1301
- );
1302
- }
1303
- if (!answers) {
1304
- return planModeQuestionCancelled(
1305
- questions,
1306
- "cancelled",
1307
- "User cancelled the Plan-mode question prompt."
1308
- );
1309
- }
1310
- return planModeQuestionAnswered(questions, answers);
1311
- }
1312
- async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
1313
- const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
1314
- if (!shouldContinue()) return void 0;
1315
- const runnerQuestions = questions.map((question, index) => ({
1316
- id: String(index),
1317
- header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),
1318
- prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),
1319
- options: question.options.map((option, optionIndex) => ({
1320
- ...option,
1321
- label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText)
1322
- }))
1323
- }));
1324
- const result = await runQuestionnaire(ctx, {
1325
- questions: runnerQuestions,
1326
- allowNotes: true,
1327
- maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
1328
- signal: ctx.signal,
1329
- isCurrent: shouldContinue
1330
- });
1331
- if (!shouldContinue()) return void 0;
1332
- return mapQuestionnaireResult(questions, result);
1333
- }
1334
- function mapQuestionnaireResult(questions, result) {
1335
- if (result.kind !== "submitted") return void 0;
1336
- if (result.answers.length !== questions.length) {
1337
- throw new Error("Questionnaire returned an incomplete answer set");
1338
- }
1339
- const answers = /* @__PURE__ */ new Map();
1340
- for (const answer of result.answers) {
1341
- const index = Number(answer.questionId);
1342
- if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {
1343
- throw new Error("Questionnaire returned an answer for an unknown question");
1344
- }
1345
- if (answers.has(index)) throw new Error("Questionnaire returned duplicate answers");
1346
- if (answer.wasCustom) {
1347
- if (answer.optionIndex !== void 0) {
1348
- throw new Error("Questionnaire returned a custom answer with an option index");
1349
- }
1350
- if (!answer.answer.trim()) return void 0;
1351
- } else if (answer.optionIndex === void 0 || !questions[index]?.options[answer.optionIndex - 1]) {
1352
- throw new Error("Questionnaire returned an invalid selected option");
1353
- }
1354
- answers.set(index, answer);
1355
- }
1356
- return questions.map((question, index) => {
1357
- const answer = answers.get(index);
1358
- if (!answer) throw new Error("Questionnaire returned an incomplete answer set");
1359
- const answerText = answer.wasCustom ? answer.answer : question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer;
1360
- return answerFor(question, answerText, {
1361
- wasCustom: answer.wasCustom,
1362
- optionIndex: answer.optionIndex,
1363
- note: answer.note
1364
- });
1365
- });
1366
- }
1367
- function displayText(value, fallback, sanitize) {
1368
- const sanitized = sanitize(value);
1369
- return sanitized.trim() ? sanitized : fallback;
1370
- }
1371
- function answerFor(question, answer, options) {
1372
- const result = {
1373
- id: question.id,
1374
- header: question.header,
1375
- question: question.question,
1376
- answer,
1377
- wasCustom: options.wasCustom
1378
- };
1379
- if (options.optionIndex !== void 0) result.optionIndex = options.optionIndex;
1380
- if (options.note !== void 0) result.note = options.note;
1381
- return result;
1382
- }
1383
- function planModeQuestionAnswered(questions, answers) {
1384
- return {
1385
- content: [
1386
- { type: "text", text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }
1387
- ],
1388
- details: { cancelled: false, questions, answers }
1389
- };
1390
- }
1391
- function planModeQuestionCancelled(questions, reason, message) {
1392
- return {
1393
- content: [
1394
- {
1395
- type: "text",
1396
- text: formatPlanModeQuestionPayload({ cancelled: true, reason, message })
1397
- }
1398
- ],
1399
- details: { cancelled: true, reason, questions }
1400
- };
1401
- }
1402
- function formatPlanModeQuestionPayload(payload) {
1403
- return JSON.stringify(payload, null, 2);
1404
- }
1405
- function isRecord2(value) {
1406
- return typeof value === "object" && value !== null;
1407
- }
1408
- function stringField(value) {
1409
- return typeof value === "string" ? value.trim() : void 0;
1410
- }
1411
-
1412
- // src/required-tools.ts
1413
- function withRequiredPlanModeTools(toolNames) {
1414
- return unique([
1415
- ...withoutRequiredPlanModeTools(toolNames),
1416
- PLAN_MODE_QUESTION_TOOL_NAME,
1417
- PLAN_MODE_COMPLETE_TOOL_NAME
1418
- ]);
1419
- }
1420
- function withoutRequiredPlanModeTools(toolNames) {
1421
- return toolNames.filter(
1422
- (toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME
1423
- );
1424
- }
1425
-
1426
1637
  // src/tool-selection.ts
1427
1638
  function toolNameFromLegacyKey(key, tools) {
1428
1639
  const directName = tools.find((tool) => tool.name === key)?.name;
@@ -1467,14 +1678,6 @@ function snapshotPlanModeSelectedNames(tools, selection) {
1467
1678
  selectedToolNames === void 0 ? defaultPlanModeToolNames(tools, selection.defaultPlanTools) : filterAvailableSelectedToolNames(selectedToolNames, tools)
1468
1679
  );
1469
1680
  }
1470
- function snapshotPlanModeToolNames(tools, selectedNames, selection) {
1471
- if (tools.length === 0 && selection.selectedToolNames === void 0 && selection.selectedToolKeys === void 0 && selection.defaultPlanTools === void 0) {
1472
- return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
1473
- }
1474
- return withRequiredPlanModeTools(
1475
- tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name)
1476
- );
1477
- }
1478
1681
 
1479
1682
  export {
1480
1683
  PLAN_MODE_COMPLETE_TOOL_NAME,
@@ -1483,9 +1686,17 @@ export {
1483
1686
  planFromCompletionDetails,
1484
1687
  planModeCompleted,
1485
1688
  renderPlanModeCompletion,
1689
+ PLAN_HISTORY_IMPLEMENTATION_PROMPT,
1486
1690
  parseProposedPlan,
1487
1691
  invalidPlanMessage,
1488
1692
  latestAssistantText,
1693
+ latestAssistantStopReason,
1694
+ messageTextContent,
1695
+ PLAN_MODE_QUESTION_TOOL_NAME,
1696
+ PLAN_MODE_QUESTION_PARAMS,
1697
+ normalizePlanModeQuestionParams,
1698
+ answerPlanModeQuestions,
1699
+ planModeQuestionCancelled,
1489
1700
  retentionLabel,
1490
1701
  implementationRetentionPreview,
1491
1702
  createImplementationRetentionCoordinator,
@@ -1493,31 +1704,27 @@ export {
1493
1704
  canSelectToolInPlanMode,
1494
1705
  readCommand,
1495
1706
  findBlockedCommandSegment,
1707
+ findBlockedPowerShellCommandSegment,
1496
1708
  PLAN_MODE_THINKING_LEVELS,
1497
1709
  IMPLEMENTATION_PLAN_RETENTIONS,
1710
+ PLAN_MODE_TOOL_VISIBILITIES,
1498
1711
  planModeSettingsPath,
1499
1712
  normalizeKeyId,
1500
1713
  readPlanModeSettings,
1501
1714
  updatePlanModeSettings,
1502
1715
  awaitPlanModeSettingsWrites,
1503
1716
  configuredThinkingLevel,
1717
+ configuredPlanModeToolVisibility,
1504
1718
  configuredImplementationPlanRetention,
1505
1719
  configuredPlanExportPath,
1506
1720
  configuredPlanModeToggleShortcut,
1507
1721
  exportStoredPlan,
1508
1722
  planExportDestination,
1509
- PLAN_MODE_QUESTION_TOOL_NAME,
1510
- PLAN_MODE_QUESTION_PARAMS,
1511
- normalizePlanModeQuestionParams,
1512
- answerPlanModeQuestions,
1513
- planModeQuestionCancelled,
1514
1723
  compareTools,
1515
1724
  toolPolicyLabel,
1725
+ unique,
1516
1726
  filterAvailableSelectedToolNames,
1517
1727
  defaultPlanModeToolNames,
1518
- snapshotPlanModeSelectedNames,
1519
- snapshotPlanModeToolNames,
1520
- withRequiredPlanModeTools,
1521
- withoutRequiredPlanModeTools
1728
+ snapshotPlanModeSelectedNames
1522
1729
  };
1523
- //# sourceMappingURL=chunk-H3RGWRY7.ts.map
1730
+ //# sourceMappingURL=chunk-U5CQ7RQX.js.map