@narumitw/pi-plan-mode 0.59.5 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/plan-mode.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  import { isStaleExtensionContextError } from "./extension-runtime.js";
21
21
  import {
22
22
  createFinalizationRequestCoordinator,
23
+ DISCUSSION_FINALIZE_PLAN_PROMPT,
23
24
  FINALIZE_PLAN_PROMPT,
24
25
  type FinalizationRunOutcome,
25
26
  RETRY_FINALIZE_PLAN_PROMPT,
@@ -35,6 +36,8 @@ import {
35
36
  createImplementationRetentionCoordinator,
36
37
  implementationRetentionPreview,
37
38
  } from "./implementation-retention.js";
39
+ import { INTERACTION_CONTRACT_MESSAGE_TYPE } from "./interaction-contract.js";
40
+ import { createInteractionCoordinator } from "./interaction-coordinator.js";
38
41
  import {
39
42
  invalidPlanMessage,
40
43
  latestAssistantStopReason,
@@ -58,8 +61,8 @@ import {
58
61
  showStoredPlan,
59
62
  updatePlanModeUi,
60
63
  } from "./presentation.js";
64
+ import { renderPlanModeQuestionCall, renderPlanModeQuestionResult } from "./question-renderer.js";
61
65
  import {
62
- answerPlanModeQuestions,
63
66
  normalizePlanModeQuestionParams,
64
67
  PLAN_MODE_QUESTION_PARAMS,
65
68
  PLAN_MODE_QUESTION_TOOL_NAME,
@@ -112,6 +115,7 @@ interface ReadyPresentationIntent {
112
115
  nonce: number;
113
116
  plan: string;
114
117
  source: PlanCompletionSource;
118
+ showMenu: boolean;
115
119
  }
116
120
  interface DeferredFreshImplementation {
117
121
  ctx: ExtensionContext;
@@ -184,6 +188,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
184
188
  let publishedContractMode: PlanModeContract | undefined;
185
189
  let modeContractsRelevant = false;
186
190
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
191
+ let readyMenuController = new AbortController();
187
192
  let latestCommandContext: ExtensionCommandContext | undefined;
188
193
  let stagedFreshImplementation: DeferredFreshImplementation | undefined;
189
194
  const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();
@@ -200,6 +205,34 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
200
205
  const implementationRetention = createImplementationRetentionCoordinator();
201
206
  const finalizationRequest = createFinalizationRequestCoordinator();
202
207
  const persistState = () => pi.appendEntry<PlanModeState>(STATE_ENTRY_TYPE, state);
208
+ const interaction = createInteractionCoordinator(pi, {
209
+ getState: () => state,
210
+ setState: (next) => {
211
+ state = next;
212
+ },
213
+ persistState,
214
+ captureCurrent: (ctx) => {
215
+ const session = ctx.sessionManager;
216
+ const generation = workflowGeneration;
217
+ const sessionGeneration = menuGeneration;
218
+ const owner = workflowOwner;
219
+ return () =>
220
+ currentSession === session &&
221
+ generation === workflowGeneration &&
222
+ sessionGeneration === menuGeneration &&
223
+ !menuController.signal.aborted &&
224
+ workflowMutex.isOwner(owner);
225
+ },
226
+ clearReadyIntent: () => {
227
+ invalidateReadyMenu();
228
+ readyPresentationIntent =
229
+ readyPresentationIntent?.source === "legacy_proposed_plan"
230
+ ? { ...readyPresentationIntent, showMenu: false }
231
+ : undefined;
232
+ },
233
+ resetFinalization: () => finalizationRequest.reset(),
234
+ updateUi,
235
+ });
203
236
  const planExports = createPlanExportController({
204
237
  getState: () => state,
205
238
  getSettings: () => settings,
@@ -226,6 +259,9 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
226
259
  settings: showSettings,
227
260
  save: savePlanForLater,
228
261
  stay: updateUi,
262
+ toggleInteraction: (ctx) => {
263
+ interaction.toggle(ctx);
264
+ },
229
265
  exitReady: (ctx) => {
230
266
  if (exitPlanMode(ctx)) {
231
267
  ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
@@ -242,7 +278,9 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
242
278
  description:
243
279
  "Ask one to three structured questions only when the latest effective Plan contract explicitly says /plan mode is active. Tool visibility alone does not activate Plan mode. Never call for ordinary planning requests, the writing-plans skill, roadmaps, checklists, or plan-file work.",
244
280
  parameters: PLAN_MODE_QUESTION_PARAMS,
245
- async execute(_toolCallId, params: unknown, _signal, _onUpdate, ctx) {
281
+ renderCall: renderPlanModeQuestionCall,
282
+ renderResult: renderPlanModeQuestionResult,
283
+ async execute(toolCallId, params: unknown, signal, _onUpdate, ctx) {
246
284
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
247
285
  return planModeQuestionCancelled(
248
286
  [],
@@ -257,6 +295,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
257
295
  }
258
296
  finalizationRequest.satisfy();
259
297
 
298
+ if (interaction.questionsPaused()) return interaction.answer(toolCallId, parsed.questions, ctx, signal);
260
299
  if (!ctx.hasUI) {
261
300
  return planModeQuestionCancelled(
262
301
  parsed.questions,
@@ -265,16 +304,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
265
304
  );
266
305
  }
267
306
 
268
- const sessionGeneration = menuGeneration;
269
- const questionWorkflowGeneration = workflowGeneration;
270
- const questionOwner = workflowOwner;
271
- return answerPlanModeQuestions(parsed.questions, ctx, {
272
- isCurrent: () =>
273
- sessionGeneration === menuGeneration &&
274
- questionWorkflowGeneration === workflowGeneration &&
275
- workflowMutex.isOwner(questionOwner),
276
- isEnabled: () => state.enabled,
277
- });
307
+ return interaction.answer(toolCallId, parsed.questions, ctx, signal);
278
308
  },
279
309
  });
280
310
 
@@ -480,6 +510,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
480
510
  };
481
511
 
482
512
  pi.on("session_start", async (event, ctx) => {
513
+ interaction.disposeSession();
514
+ invalidateReadyMenu();
483
515
  cancelDeferredFreshImplementation();
484
516
  const generation = ++menuGeneration;
485
517
  finalizationRequest.reset();
@@ -505,6 +537,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
505
537
  await applyPlanModeSettings(generation, ctx, true);
506
538
  if (generation !== menuGeneration || menuController.signal.aborted) return;
507
539
  initializePlanModeShortcut();
540
+ interaction.startSession(ctx, startupToggleShortcut);
508
541
  startPlanModeSettingsWatch(generation);
509
542
  if (!installRestoredState(restoredState, ctx)) return;
510
543
  implementationRetention.restore(state.activeImplementation);
@@ -526,7 +559,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
526
559
  return { cancel: true };
527
560
  }
528
561
  const target = ctx.sessionManager.getEntry(event.preparation.targetId);
529
- if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
562
+ if (
563
+ target?.type !== "custom_message" ||
564
+ (target.customType !== MODE_CONTRACT_MESSAGE_TYPE && target.customType !== INTERACTION_CONTRACT_MESSAGE_TYPE)
565
+ ) {
530
566
  return;
531
567
  }
532
568
  if (ctx.hasUI) {
@@ -573,6 +609,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
573
609
  });
574
610
 
575
611
  pi.on("session_shutdown", async (_event, ctx) => {
612
+ if (currentSession !== undefined && currentSession !== ctx.sessionManager) {
613
+ workflowMutex.unbindSession(ctx.sessionManager);
614
+ return;
615
+ }
616
+ interaction.disposeSession();
617
+ invalidateReadyMenu();
576
618
  cancelDeferredFreshImplementation();
577
619
  const shutdownSession = ctx.sessionManager;
578
620
  const runtimeApplication =
@@ -722,9 +764,21 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
722
764
  }
723
765
  });
724
766
 
767
+ pi.on("tool_execution_end", (event, ctx) => {
768
+ interaction.toolExecutionEnd(event.toolCallId, ctx);
769
+ });
770
+
771
+ pi.on("ui_prompt_start", (_event, ctx) => {
772
+ interaction.promptChanged(true, ctx);
773
+ });
774
+ pi.on("ui_prompt_end", (_event, ctx) => {
775
+ interaction.promptChanged(false, ctx);
776
+ });
777
+
725
778
  pi.on("message_start", (event) => {
726
779
  if (
727
780
  state.enabled &&
781
+ interaction.mode() === "questions" &&
728
782
  event.message.role === "user" &&
729
783
  messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT
730
784
  ) {
@@ -742,7 +796,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
742
796
  state.enabled || modeContractsRelevant
743
797
  ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal")
744
798
  : result.messages;
745
- return { messages: messages as typeof event.messages };
799
+ return { messages: interaction.transformContext(messages, ctx) as typeof event.messages };
746
800
  });
747
801
 
748
802
  pi.on("input", async (event, ctx) => {
@@ -786,6 +840,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
786
840
  refreshStateForFirstPrompt(ctx);
787
841
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
788
842
  if (state.latestPlan || state.awaitingAction) {
843
+ invalidateReadyMenu();
789
844
  cancelDeferredFreshImplementation();
790
845
  readyPresentationIntent = undefined;
791
846
  state = {
@@ -805,7 +860,9 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
805
860
  const text = latestAssistantText(event.messages);
806
861
  const parsedPlan = parseProposedPlan(text);
807
862
  if (parsedPlan.kind !== "valid") {
808
- finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
863
+ if (interaction.mode() === "questions") {
864
+ finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
865
+ }
809
866
  if (parsedPlan.kind !== "absent") {
810
867
  ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
811
868
  }
@@ -820,7 +877,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
820
877
  const settledImplementationId = implementationRetention.implementationSettled(state.activeImplementation);
821
878
  if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
822
879
 
823
- if (finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
880
+ if (
881
+ interaction.mode() === "questions" &&
882
+ finalizationRequest.hasPendingRequest() &&
883
+ state.enabled &&
884
+ workflowMutex.isOwner(workflowOwner)
885
+ ) {
824
886
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
825
887
  const action = finalizationRequest.settle(workflowGeneration);
826
888
  if (action === "retry") {
@@ -852,8 +914,12 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
852
914
  { triggerTurn: false },
853
915
  );
854
916
  }
855
- if (ctx.hasUI && completedPlanIsCurrent(intent)) {
856
- await planActions.showReady(latestCommandContext ?? ctx);
917
+ if (intent.showMenu && ctx.hasUI && completedPlanIsCurrent(intent)) {
918
+ const controller = readyMenuController;
919
+ await planActions.showReady(latestCommandContext ?? ctx, {
920
+ signal: controller.signal,
921
+ isCurrent: () => completedPlanIsCurrent(intent) && interaction.mode() === "questions",
922
+ });
857
923
  }
858
924
  const request = stagedFreshImplementation;
859
925
  stagedFreshImplementation = undefined;
@@ -892,6 +958,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
892
958
  state = {
893
959
  ...state,
894
960
  enabled: true,
961
+ interactionMode: "questions",
895
962
  awaitingAction: false,
896
963
  savedPlan: undefined,
897
964
  activeImplementation: undefined,
@@ -902,6 +969,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
902
969
  beginWorkflowToolPolicy();
903
970
  applyPlanThinkingLevel();
904
971
  persistState();
972
+ interaction.publish("questions");
905
973
  updateUi(ctx);
906
974
  return true;
907
975
  } catch (error: unknown) {
@@ -935,6 +1003,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
935
1003
  state = {
936
1004
  ...state,
937
1005
  enabled: false,
1006
+ interactionMode: undefined,
938
1007
  latestPlan: undefined,
939
1008
  latestPlanSource: undefined,
940
1009
  awaitingAction: false,
@@ -1010,21 +1079,32 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1010
1079
  ) {
1011
1080
  return;
1012
1081
  }
1082
+ invalidateReadyMenu();
1013
1083
  state = {
1014
1084
  ...state,
1015
1085
  latestPlan: normalized.plan,
1016
1086
  latestPlanSource: source,
1017
1087
  awaitingAction: true,
1018
1088
  };
1019
- readyPresentationIntent = {
1020
- nonce: ++nextReadyPresentationNonce,
1021
- plan: normalized.plan,
1022
- source,
1023
- };
1089
+ const showMenu = interaction.mode() === "questions";
1090
+ readyPresentationIntent =
1091
+ showMenu || source === "legacy_proposed_plan"
1092
+ ? {
1093
+ nonce: ++nextReadyPresentationNonce,
1094
+ plan: normalized.plan,
1095
+ source,
1096
+ showMenu,
1097
+ }
1098
+ : undefined;
1024
1099
  persistState();
1025
1100
  updateUi(ctx);
1026
1101
  }
1027
1102
 
1103
+ function invalidateReadyMenu() {
1104
+ readyMenuController.abort(new DOMException("Plan presentation superseded", "AbortError"));
1105
+ readyMenuController = new AbortController();
1106
+ }
1107
+
1028
1108
  function completedPlanIsCurrent(intent: ReadyPresentationIntent) {
1029
1109
  return (
1030
1110
  state.enabled &&
@@ -1066,6 +1146,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1066
1146
  ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
1067
1147
  return;
1068
1148
  }
1149
+ if (interaction.mode() === "discussion") {
1150
+ finalizationRequest.reset();
1151
+ sendPlanModeUserMessage(DISCUSSION_FINALIZE_PLAN_PROMPT, ctx);
1152
+ return;
1153
+ }
1069
1154
  finalizationRequest.request(workflowGeneration);
1070
1155
  if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
1071
1156
  }
@@ -1088,6 +1173,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1088
1173
  state = {
1089
1174
  ...state,
1090
1175
  enabled: false,
1176
+ interactionMode: undefined,
1091
1177
  latestPlan: undefined,
1092
1178
  latestPlanSource: undefined,
1093
1179
  awaitingAction: false,
@@ -1235,6 +1321,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1235
1321
  state = {
1236
1322
  ...state,
1237
1323
  enabled: false,
1324
+ interactionMode: undefined,
1238
1325
  latestPlan: undefined,
1239
1326
  latestPlanSource: undefined,
1240
1327
  awaitingAction: false,
@@ -1271,6 +1358,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1271
1358
  if (wasEnabled) {
1272
1359
  restoreWorkflowToolPolicy(state.workflowToolPolicy);
1273
1360
  publishModeContract("plan", ctx);
1361
+ interaction.publish(interaction.mode());
1274
1362
  applyPlanThinkingLevel();
1275
1363
  }
1276
1364
  persistState();
@@ -1444,6 +1532,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1444
1532
  }
1445
1533
 
1446
1534
  function advanceWorkflowGeneration() {
1535
+ interaction.reset();
1536
+ invalidateReadyMenu();
1447
1537
  cancelDeferredFreshImplementation();
1448
1538
  workflowGeneration += 1;
1449
1539
  pendingWorkflowToolPolicy = undefined;
@@ -1950,6 +2040,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1950
2040
  previousOwner?: WorkflowMutexOwner,
1951
2041
  ) {
1952
2042
  const activatedOwner = workflowOwner;
2043
+ interaction.reset();
1953
2044
  readyPresentationIntent = undefined;
1954
2045
  try {
1955
2046
  if (state.enabled) {
@@ -2017,7 +2108,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
2017
2108
  }
2018
2109
 
2019
2110
  function updateUi(ctx: ExtensionContext) {
2020
- updatePlanModeUi(ctx, state, formatToolSummary);
2111
+ updatePlanModeUi(ctx, state, formatToolSummary, interaction.shortcutLabel(ctx));
2021
2112
  }
2022
2113
 
2023
2114
  function clearUi(ctx: ExtensionContext) {
@@ -7,13 +7,32 @@ const STATUS_KEY = "plan-mode";
7
7
  const PLAN_WIDGET_KEY = "plan-mode-plan";
8
8
  const BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
9
9
 
10
- export function updatePlanModeUi(ctx: ExtensionContext, state: PlanModeState, toolSummary: () => string) {
10
+ export function updatePlanModeUi(
11
+ ctx: ExtensionContext,
12
+ state: PlanModeState,
13
+ toolSummary: () => string,
14
+ interactionShortcut?: string,
15
+ ) {
11
16
  ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
17
+ const discussion = state.interactionMode === "discussion";
18
+ const interactionHint = formatInteractionHint(state, ctx.mode === "tui" ? interactionShortcut : undefined);
12
19
  let lines: string[] | undefined;
13
20
  if (state.enabled && state.latestPlan) {
14
- lines = ["Proposed plan ready", "Use /plan to implement, save, revise, or exit Plan mode."];
21
+ lines = [
22
+ "Proposed plan ready",
23
+ ...(discussion ? ["Plan mode: free discussion"] : []),
24
+ "Use /plan to implement, save, revise, or exit Plan mode.",
25
+ interactionHint,
26
+ ];
15
27
  } else if (state.enabled) {
16
- lines = ["Plan mode: planning", toolSummary(), "Finish with plan_mode_complete when decision-ready."];
28
+ lines = [
29
+ discussion ? "Plan mode: free discussion" : "Plan mode: planning",
30
+ toolSummary(),
31
+ discussion
32
+ ? "Plain-text questions are allowed; questionnaires are paused."
33
+ : "Finish with plan_mode_complete when decision-ready.",
34
+ interactionHint,
35
+ ];
17
36
  } else if (state.savedPlan) {
18
37
  lines = ["Plan saved for later", "Use /plan to show, implement, or clear it."];
19
38
  } else if (state.activeImplementation) {
@@ -29,7 +48,14 @@ export function renderPlanModeWidget(lines: readonly string[], theme: Theme, wid
29
48
 
30
49
  function createPlanModeWidget(lines: readonly string[], theme: Theme): EditorStatusWidget {
31
50
  // Kit normalizes fractional and invalid widths before clipping sanitized body rows.
32
- return new EditorStatusWidget({ theme, renderBody: () => lines.map(sanitizePlanModeWidgetLine) });
51
+ return new EditorStatusWidget({
52
+ theme,
53
+ renderBody: () =>
54
+ lines.map((line, index) => {
55
+ const text = sanitizePlanModeWidgetLine(line);
56
+ return index === 0 ? text : theme.fg("muted", text);
57
+ }),
58
+ });
33
59
  }
34
60
 
35
61
  export function sanitizePlanModeWidgetLine(value: string): string {
@@ -81,10 +107,12 @@ export function showPlanModePlan(pi: ExtensionAPI, ctx: ExtensionContext, title:
81
107
 
82
108
  export function planModeStatusText(state: PlanModeState, toolSummary: () => string) {
83
109
  if (state.enabled) {
84
- if (state.latestPlan) {
85
- return `Plan mode is active and a proposed plan is ready. ${toolSummary()}`;
86
- }
87
- return `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;
110
+ const ready = state.latestPlan ? " A proposed plan is ready." : "";
111
+ const interaction =
112
+ state.interactionMode === "discussion"
113
+ ? "Free discussion is active; questionnaires are paused and plain-text questions are allowed."
114
+ : "Explore, ask, and finish with plan_mode_complete when decision-ready.";
115
+ return `Plan mode is active.${ready} ${interaction} File edits remain blocked. ${toolSummary()}`;
88
116
  }
89
117
  if (state.savedPlan) return "A plan is saved for later.";
90
118
  if (state.activeImplementation) return "An implementation plan is active.";
@@ -105,10 +133,15 @@ function publishPlanModeWidget(ctx: ExtensionContext, lines: readonly string[] |
105
133
  ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => createPlanModeWidget(snapshot, theme));
106
134
  }
107
135
 
136
+ function formatInteractionHint(state: PlanModeState, interactionShortcut?: string) {
137
+ const action = state.interactionMode === "discussion" ? "enable questionnaires" : "switch to free discussion";
138
+ return interactionShortcut ? `${interactionShortcut}: ${action}.` : `Use /plan to ${action}.`;
139
+ }
140
+
108
141
  function formatStatus(state: PlanModeState) {
109
142
  if (state.enabled) {
110
143
  if (state.awaitingAction || state.latestPlan) return "plan ready";
111
- return "plan active";
144
+ return state.interactionMode === "discussion" ? "plan discussion" : "plan active";
112
145
  }
113
146
  if (state.savedPlan) return "plan saved";
114
147
  if (state.activeImplementation) return "plan implementing";
@@ -0,0 +1,174 @@
1
+ import type { KeybindingHints, Theme, ToolRenderResultOptions } from "@earendil-works/pi-coding-agent";
2
+ import { type Component, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import { hardWrapTerminalDocument, sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
4
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
5
+ import type { PlanModeQuestionAnswer } from "./question-tool.js";
6
+
7
+ type QuestionResult = {
8
+ content: Array<{ type: string; text?: string }>;
9
+ details?: unknown;
10
+ };
11
+
12
+ type RenderContext = Partial<KeybindingHints> & { isError?: boolean };
13
+ type Answer = Pick<PlanModeQuestionAnswer, "header" | "question" | "answer" | "wasCustom" | "note">;
14
+ type Style = (text: string) => string;
15
+
16
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
17
+
18
+ export function renderPlanModeQuestionCall(args: unknown, theme: Theme): Component {
19
+ const questions = isRecord(args) && Array.isArray(args.questions) ? args.questions : [];
20
+ return boundedComponent((width) => {
21
+ const title = questions.length > 1 ? "Plan questions" : "Plan question";
22
+ const headers = questions
23
+ .map((question) => (isRecord(question) ? displayLine(question.header) : ""))
24
+ .filter(Boolean);
25
+ const text =
26
+ theme.fg("toolTitle", theme.bold(title)) + theme.fg("muted", headers.length ? ` ${headers.join(" · ")}` : "");
27
+ return [truncateToWidth(text, width, "…")];
28
+ });
29
+ }
30
+
31
+ export function renderPlanModeQuestionResult(
32
+ result: QuestionResult,
33
+ { expanded, isPartial }: ToolRenderResultOptions,
34
+ theme: Theme,
35
+ context: RenderContext = {},
36
+ ): Component {
37
+ const text = result.content
38
+ .filter((block) => block.type === "text" && typeof block.text === "string")
39
+ .map((block) => block.text)
40
+ .join("\n");
41
+ const payload = questionPayload(result.details, text);
42
+
43
+ return boundedComponent((width) => {
44
+ const muted = (value: string) => theme.fg("muted", value);
45
+ const hint = () =>
46
+ context.keyText?.("app.tools.expand") && context.keyHint
47
+ ? [truncateToWidth(muted(context.keyHint("app.tools.expand", "to expand")), width, "…")]
48
+ : [];
49
+
50
+ if (isPartial) return [truncateToWidth(muted("Waiting for answers…"), width, "…")];
51
+
52
+ if (context.isError || payload?.cancelled === true) {
53
+ const reason = payload?.reason;
54
+ const failed = context.isError || reason === "invalid_input";
55
+ const status = context.isError
56
+ ? "Question failed"
57
+ : reason === "ui_unavailable"
58
+ ? "Interactive UI unavailable"
59
+ : reason === "plan_mode_inactive"
60
+ ? "Plan mode inactive"
61
+ : reason === "invalid_input"
62
+ ? "Invalid question"
63
+ : "Question cancelled";
64
+ const message = typeof payload?.message === "string" ? payload.message : text;
65
+ const lines = documentLines(status, width, (value) => theme.fg(failed ? "error" : "warning", value));
66
+ if (expanded) {
67
+ lines.push(...documentLines(message, width, muted, " "));
68
+ } else if (message) {
69
+ lines.push(...hint());
70
+ }
71
+ return lines;
72
+ }
73
+
74
+ const answers = payload?.answers;
75
+ if (payload?.cancelled === false && Array.isArray(answers) && answers.length > 0 && answers.every(isAnswer)) {
76
+ const lines: string[] = [];
77
+ for (const answer of answers) {
78
+ if (!expanded) {
79
+ const badge = answer.wasCustom ? muted(" (custom)") : "";
80
+ const note = answer.note ? muted(" · note") : "";
81
+ lines.push(
82
+ truncateToWidth(
83
+ theme.fg("success", "✓ ") +
84
+ muted(`${displayLine(answer.header)}: `) +
85
+ theme.fg("accent", displayLine(answer.answer)) +
86
+ badge +
87
+ note,
88
+ width,
89
+ "…",
90
+ ),
91
+ );
92
+ continue;
93
+ }
94
+ if (lines.length) lines.push("");
95
+ lines.push(...documentLines(answer.header, width, (value) => theme.fg("accent", theme.bold(value))));
96
+ lines.push(...documentLines(answer.question, width, muted, " "));
97
+ if (answer.wasCustom) lines.push(...documentLines("Custom answer", width, muted, " "));
98
+ lines.push(
99
+ ...documentLines(
100
+ answer.answer,
101
+ width,
102
+ (value) => theme.fg("text", value),
103
+ " ✓ ",
104
+ (value) => theme.fg("success", value),
105
+ ),
106
+ );
107
+ if (answer.note) {
108
+ lines.push(...documentLines("Note", width, muted, " "));
109
+ lines.push(...documentLines(answer.note, width, muted, " "));
110
+ }
111
+ }
112
+ if (!expanded) lines.push(...hint());
113
+ return lines;
114
+ }
115
+
116
+ const lines = documentLines(text || "No answer returned.", width, (value) => theme.fg("toolOutput", value));
117
+ return expanded || lines.length <= 4 ? lines : [...lines.slice(0, 4), ...hint()];
118
+ });
119
+ }
120
+
121
+ function questionPayload(details: unknown, text: string): Record<string, unknown> | undefined {
122
+ let payload: unknown;
123
+ try {
124
+ payload = JSON.parse(text);
125
+ } catch {
126
+ // Pi-generated errors and third-party tool-result hooks can return plain text.
127
+ }
128
+ const parsed = isRecord(payload) ? payload : undefined;
129
+ return isRecord(details) && typeof details.cancelled === "boolean" ? { ...parsed, ...details } : parsed;
130
+ }
131
+
132
+ function isAnswer(value: unknown): value is Answer {
133
+ return (
134
+ isRecord(value) &&
135
+ typeof value.header === "string" &&
136
+ typeof value.question === "string" &&
137
+ typeof value.answer === "string" &&
138
+ typeof value.wasCustom === "boolean" &&
139
+ (value.note === undefined || typeof value.note === "string")
140
+ );
141
+ }
142
+
143
+ function isRecord(value: unknown): value is Record<string, unknown> {
144
+ return typeof value === "object" && value !== null && !Array.isArray(value);
145
+ }
146
+
147
+ function displayLine(value: unknown): string {
148
+ return typeof value === "string" ? sanitizeTerminalText(value) : "";
149
+ }
150
+
151
+ function documentLines(value: string, width: number, style: Style, prefix = "", prefixStyle = style): string[] {
152
+ const text = sanitizeTerminalDocument(value);
153
+ let contentWidth = 1;
154
+ for (const { segment } of graphemeSegmenter.segment(text)) {
155
+ contentWidth = Math.min(width, Math.max(contentWidth, visibleWidth(segment)));
156
+ }
157
+ // Reduce decoration before it forces a grapheme that fits the viewport into Kit's fallback.
158
+ const visiblePrefix = truncateToWidth(prefix, width - contentWidth, "");
159
+ const prefixWidth = visibleWidth(visiblePrefix);
160
+ return hardWrapTerminalDocument(text, width - prefixWidth).map((line, index) => {
161
+ const decoration = index === 0 ? visiblePrefix : " ".repeat(prefixWidth);
162
+ // Leading marks can change width when they join the decoration's final grapheme.
163
+ const safePrefix = visibleWidth(decoration + line) <= width ? decoration : "";
164
+ return prefixStyle(safePrefix) + style(line);
165
+ });
166
+ }
167
+
168
+ function boundedComponent(render: (width: number) => string[]): Component {
169
+ return {
170
+ render: (width) => (Number.isFinite(width) && width >= 1 ? render(Math.floor(width)) : []),
171
+ // Theme styles are evaluated on every render, so there is no cache to clear.
172
+ invalidate() {},
173
+ };
174
+ }