@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.
@@ -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,
@@ -723,10 +1046,12 @@ var PLAN_MODE_THINKING_LEVELS = [
723
1046
  "max"
724
1047
  ];
725
1048
  var IMPLEMENTATION_PLAN_RETENTIONS = [
726
- "keep",
727
1049
  "clear-on-start",
728
- "clear-after-first-run"
1050
+ "clear-after-first-run",
1051
+ "keep"
729
1052
  ];
1053
+ var PLAN_MODE_TOOL_VISIBILITIES = ["always", "after-first-plan"];
1054
+ var DEFAULT_PLAN_MODE_TOOL_VISIBILITY = "after-first-plan";
730
1055
  var DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
731
1056
  var MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]);
732
1057
  var BASE_KEYS = /* @__PURE__ */ new Set([
@@ -799,6 +1124,13 @@ function normalizePlanModeSettings(value) {
799
1124
  const settings = {
800
1125
  thinkingLevel
801
1126
  };
1127
+ if (Object.hasOwn(value, "toolVisibility")) {
1128
+ const toolVisibility = Reflect.get(value, "toolVisibility");
1129
+ if (!PLAN_MODE_TOOL_VISIBILITIES.includes(toolVisibility)) {
1130
+ return void 0;
1131
+ }
1132
+ settings.toolVisibility = toolVisibility;
1133
+ }
802
1134
  if (Object.hasOwn(value, "defaultPlanTools")) {
803
1135
  const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
804
1136
  if (!defaultPlanTools) return void 0;
@@ -916,6 +1248,7 @@ function updatePlanModeSettings(patch, options = {}) {
916
1248
  const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
917
1249
  const updated = { ...current };
918
1250
  if (patch.thinkingLevel !== void 0) updated.thinkingLevel = patch.thinkingLevel;
1251
+ if (patch.toolVisibility !== void 0) updated.toolVisibility = patch.toolVisibility;
919
1252
  if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
920
1253
  else if (patch.defaultPlanTools !== void 0) {
921
1254
  updated.defaultPlanTools = [...patch.defaultPlanTools];
@@ -1074,8 +1407,11 @@ function safeReadError(error) {
1074
1407
  function configuredThinkingLevel(settings) {
1075
1408
  return settings.thinkingLevel === "inherit" ? void 0 : settings.thinkingLevel;
1076
1409
  }
1410
+ function configuredPlanModeToolVisibility(settings) {
1411
+ return settings.toolVisibility ?? DEFAULT_PLAN_MODE_TOOL_VISIBILITY;
1412
+ }
1077
1413
  function configuredImplementationPlanRetention(settings) {
1078
- return settings.implementationPlanRetention ?? "keep";
1414
+ return settings.implementationPlanRetention ?? "clear-on-start";
1079
1415
  }
1080
1416
  function configuredPlanExportPath(settings) {
1081
1417
  return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
@@ -1175,254 +1511,6 @@ function isNodeError2(error) {
1175
1511
  return error instanceof Error && "code" in error;
1176
1512
  }
1177
1513
 
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
1514
  // src/tool-selection.ts
1427
1515
  function toolNameFromLegacyKey(key, tools) {
1428
1516
  const directName = tools.find((tool) => tool.name === key)?.name;
@@ -1467,14 +1555,6 @@ function snapshotPlanModeSelectedNames(tools, selection) {
1467
1555
  selectedToolNames === void 0 ? defaultPlanModeToolNames(tools, selection.defaultPlanTools) : filterAvailableSelectedToolNames(selectedToolNames, tools)
1468
1556
  );
1469
1557
  }
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
1558
 
1479
1559
  export {
1480
1560
  PLAN_MODE_COMPLETE_TOOL_NAME,
@@ -1483,9 +1563,17 @@ export {
1483
1563
  planFromCompletionDetails,
1484
1564
  planModeCompleted,
1485
1565
  renderPlanModeCompletion,
1566
+ PLAN_HISTORY_IMPLEMENTATION_PROMPT,
1486
1567
  parseProposedPlan,
1487
1568
  invalidPlanMessage,
1488
1569
  latestAssistantText,
1570
+ latestAssistantStopReason,
1571
+ messageTextContent,
1572
+ PLAN_MODE_QUESTION_TOOL_NAME,
1573
+ PLAN_MODE_QUESTION_PARAMS,
1574
+ normalizePlanModeQuestionParams,
1575
+ answerPlanModeQuestions,
1576
+ planModeQuestionCancelled,
1489
1577
  retentionLabel,
1490
1578
  implementationRetentionPreview,
1491
1579
  createImplementationRetentionCoordinator,
@@ -1495,29 +1583,24 @@ export {
1495
1583
  findBlockedCommandSegment,
1496
1584
  PLAN_MODE_THINKING_LEVELS,
1497
1585
  IMPLEMENTATION_PLAN_RETENTIONS,
1586
+ PLAN_MODE_TOOL_VISIBILITIES,
1498
1587
  planModeSettingsPath,
1499
1588
  normalizeKeyId,
1500
1589
  readPlanModeSettings,
1501
1590
  updatePlanModeSettings,
1502
1591
  awaitPlanModeSettingsWrites,
1503
1592
  configuredThinkingLevel,
1593
+ configuredPlanModeToolVisibility,
1504
1594
  configuredImplementationPlanRetention,
1505
1595
  configuredPlanExportPath,
1506
1596
  configuredPlanModeToggleShortcut,
1507
1597
  exportStoredPlan,
1508
1598
  planExportDestination,
1509
- PLAN_MODE_QUESTION_TOOL_NAME,
1510
- PLAN_MODE_QUESTION_PARAMS,
1511
- normalizePlanModeQuestionParams,
1512
- answerPlanModeQuestions,
1513
- planModeQuestionCancelled,
1514
1599
  compareTools,
1515
1600
  toolPolicyLabel,
1601
+ unique,
1516
1602
  filterAvailableSelectedToolNames,
1517
1603
  defaultPlanModeToolNames,
1518
- snapshotPlanModeSelectedNames,
1519
- snapshotPlanModeToolNames,
1520
- withRequiredPlanModeTools,
1521
- withoutRequiredPlanModeTools
1604
+ snapshotPlanModeSelectedNames
1522
1605
  };
1523
- //# sourceMappingURL=chunk-H3RGWRY7.ts.map
1606
+ //# sourceMappingURL=chunk-D2V3VWND.ts.map