@narumitw/pi-plan-mode 0.59.6 → 0.60.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.ts CHANGED
@@ -48,7 +48,7 @@ import {
48
48
  snapshotAvailableImplementationModels,
49
49
  snapshotPlanModeSelectedNames,
50
50
  updatePlanModeSettings
51
- } from "./chunks/chunk-W7D6N2MI.ts";
51
+ } from "./chunks/chunk-UJ6TV2YV.ts";
52
52
 
53
53
  // src/plan-mode.ts
54
54
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -88,6 +88,7 @@ function isStaleExtensionContextError(error) {
88
88
 
89
89
  // src/finalization-request.ts
90
90
  var FINALIZE_PLAN_PROMPT = "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.";
91
+ var DISCUSSION_FINALIZE_PLAN_PROMPT = "Finalize the current implementation plan if it is decision-ready. If a material decision remains, discuss it or ask one concise plain-text question instead. Questionnaires remain paused until the user enables them. Otherwise call plan_mode_complete alone with the complete plan.";
91
92
  var RETRY_FINALIZE_PLAN_PROMPT = "Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.";
92
93
  function createFinalizationRequestCoordinator() {
93
94
  let pending;
@@ -321,6 +322,8 @@ function restorePlanModeState(entries, stateEntryType) {
321
322
  const entry = branch[stateEntryIndex];
322
323
  if (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };
323
324
  const enabled = entry.data.enabled === true;
325
+ const interactionMode = entry.data.interactionMode === "discussion" ? "discussion" : "questions";
326
+ const interactionRestorations = Array.isArray(entry.data.interactionRestorations) ? entry.data.interactionRestorations.map(normalizeInteractionRestoration).filter((value) => value !== void 0) : [];
324
327
  const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : void 0;
325
328
  const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : void 0;
326
329
  const recoveredPlan = enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : void 0;
@@ -330,6 +333,8 @@ function restorePlanModeState(entries, stateEntryType) {
330
333
  const pendingImplementationRuntime = enabled ? void 0 : normalizePendingImplementationRuntime(entry.data.pendingImplementationRuntime);
331
334
  return {
332
335
  enabled,
336
+ ...enabled && entry.data.interactionMode !== void 0 ? { interactionMode } : {},
337
+ ...interactionRestorations.length ? { interactionRestorations } : {},
333
338
  latestPlan,
334
339
  latestPlanSource: enabled ? (persistedPlan ? persistedSource : void 0) ?? (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : void 0) : void 0,
335
340
  awaitingAction: enabled && latestPlan !== void 0,
@@ -344,6 +349,15 @@ function restorePlanModeState(entries, stateEntryType) {
344
349
  manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : void 0
345
350
  };
346
351
  }
352
+ function normalizeInteractionRestoration(value) {
353
+ if (!isRecord(value) || value.version !== 1 || value.mode !== "questions" && value.mode !== "discussion" || !isRecord(value.boundary))
354
+ return void 0;
355
+ const mode = value.mode;
356
+ const { length, hash } = value.boundary;
357
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || typeof hash !== "string" || !/^[a-f0-9]{64}$/u.test(hash))
358
+ return void 0;
359
+ return { version: 1, mode, boundary: { length, hash } };
360
+ }
347
361
  function normalizeWorkflowToolPolicy(value) {
348
362
  if (value === void 0) return void 0;
349
363
  const denied = {
@@ -685,6 +699,366 @@ function safeErrorDetail(error) {
685
699
  return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
686
700
  }
687
701
 
702
+ // src/interaction-contract.ts
703
+ var INTERACTION_CONTRACT_MESSAGE_TYPE = "plan-mode-interaction";
704
+ var INTERACTION_CONTRACT_VERSION = 1;
705
+ var CONTRACTS = {
706
+ questions: `[PI PLAN MODE INTERACTION CONTRACT v1: QUESTIONS]
707
+ Plan Mode remains active with all read-only restrictions unchanged. Do not edit files, perform mutating actions, or implement the plan.
708
+ The user has enabled questionnaires. Restore the original Plan-mode rule: every turn that advances or finalizes the plan must end with plan_mode_question when a material decision remains, or plan_mode_complete alone as the final action when the plan is decision-complete. If interactive UI is unavailable, ask one concise plain-text question instead.
709
+ Re-evaluate the current discussion after the next user message. Do not replay stale questions or reopen an earlier questionnaire. Enabling questionnaires does not itself start a model turn or open a questionnaire.
710
+ Only the user can change this interaction mode.`,
711
+ discussion: `[PI PLAN MODE INTERACTION CONTRACT v1: DISCUSSION]
712
+ Plan Mode remains active with all read-only restrictions unchanged. Do not edit files, perform mutating actions, or implement the plan.
713
+ This contract overrides the original Plan-mode rule that each advancing or finalizing turn must end with plan_mode_question or plan_mode_complete. You may analyze, answer, ask natural plain-text questions, and end with ordinary text without calling either tool.
714
+ Do not call plan_mode_question or open questionnaires. Do not resume questionnaires automatically; only the user can enable them again. Discard unsubmitted questionnaire answers and do not replay stale questions.
715
+ When the plan is decision-complete, you may call plan_mode_complete alone as the final action to display and save the complete plan. Completion does not automatically open an action menu in discussion mode; the user can open /plan. Continue revisions through the existing complete-replacement plan flow, and use plain-text questions when decisions remain.`
716
+ };
717
+ function createInteractionContractMessage(mode, timestamp = Date.now()) {
718
+ return {
719
+ role: "custom",
720
+ customType: INTERACTION_CONTRACT_MESSAGE_TYPE,
721
+ content: CONTRACTS[mode],
722
+ display: false,
723
+ details: { version: INTERACTION_CONTRACT_VERSION, mode },
724
+ timestamp
725
+ };
726
+ }
727
+ function interactionContractFromMessage(message) {
728
+ const candidate = customMessage(message);
729
+ if (candidate?.customType !== INTERACTION_CONTRACT_MESSAGE_TYPE || candidate.display !== false) return void 0;
730
+ const details = candidate.details;
731
+ if (!isRecord2(details) || details.version !== INTERACTION_CONTRACT_VERSION) return void 0;
732
+ const mode = details.mode;
733
+ if (mode !== "questions" && mode !== "discussion") return void 0;
734
+ return candidate.content === CONTRACTS[mode] ? mode : void 0;
735
+ }
736
+ function latestInteractionContract(messages) {
737
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
738
+ const message = messages[index];
739
+ const mode = interactionContractFromMessage(message);
740
+ if (mode) return { index, mode };
741
+ if (modeContractFromMessage(customMessage(message))) return void 0;
742
+ }
743
+ return void 0;
744
+ }
745
+ function customMessage(value) {
746
+ if (!isRecord2(value)) return void 0;
747
+ if (value.type === "custom_message") return value;
748
+ if (value.type === "message") {
749
+ return isRecord2(value.message) && value.message.role === "custom" ? value.message : void 0;
750
+ }
751
+ return value.type === void 0 && value.role === "custom" ? value : void 0;
752
+ }
753
+ function isRecord2(value) {
754
+ return typeof value === "object" && value !== null && !Array.isArray(value);
755
+ }
756
+
757
+ // src/interaction-coordinator.ts
758
+ import { createHash as createHash2 } from "node:crypto";
759
+ import { getKeybindings, isKeyRelease, isKeyRepeat, matchesKey } from "@earendil-works/pi-tui";
760
+ var F2_INPUTS = ["\x1BOQ", "\x1B[12~", "\x1B[[B", "\x1B[1;1Q", "\x1B[12;1~", "\x1B[-22;1u"];
761
+ var PASTE_START = "\x1B[200~";
762
+ var PASTE_END = "\x1B[201~";
763
+ function interactionShortcutAvailable(bindings, otherShortcut) {
764
+ const reserved = [
765
+ ...Object.values(bindings).flatMap((value) => Array.isArray(value) ? value : [value]),
766
+ otherShortcut
767
+ ];
768
+ return !reserved.some(
769
+ (key) => typeof key === "string" && F2_INPUTS.some((input) => matchesKey(input, "f2") && matchesKey(input, key))
770
+ );
771
+ }
772
+ function createInteractionInputGuard() {
773
+ let pasting = false;
774
+ let suffix = "";
775
+ return (data) => {
776
+ const text = suffix + data;
777
+ const wasPasting = pasting;
778
+ let markerSeen = false;
779
+ for (let index = 0; index < text.length; index += 1) {
780
+ if (text.startsWith(PASTE_START, index)) {
781
+ pasting = true;
782
+ markerSeen = true;
783
+ index += PASTE_START.length - 1;
784
+ } else if (text.startsWith(PASTE_END, index)) {
785
+ pasting = false;
786
+ markerSeen = true;
787
+ index += PASTE_END.length - 1;
788
+ }
789
+ }
790
+ suffix = "";
791
+ for (let length = 1; length < PASTE_START.length && length <= text.length; length += 1) {
792
+ const candidate = text.slice(-length);
793
+ if (PASTE_START.startsWith(candidate) || PASTE_END.startsWith(candidate)) suffix = candidate;
794
+ }
795
+ return !wasPasting && !pasting && !markerSeen && !suffix && !isKeyRelease(data) && !isKeyRepeat(data);
796
+ };
797
+ }
798
+ function createInteractionCoordinator(pi, dependencies) {
799
+ const questions = /* @__PURE__ */ new Set();
800
+ const pendingAborts = /* @__PURE__ */ new Map();
801
+ let shortcutInitialized = false;
802
+ let shortcutRegistered = false;
803
+ let removeSessionInput = () => {
804
+ };
805
+ let mainShortcutAllowed = true;
806
+ let promptOpen = false;
807
+ let failed = false;
808
+ function mode() {
809
+ return dependencies.getState().interactionMode === "discussion" ? "discussion" : "questions";
810
+ }
811
+ function publish(nextMode) {
812
+ const { role: _role, timestamp: _timestamp, ...message } = createInteractionContractMessage(nextMode);
813
+ pi.sendMessage(message, { triggerTurn: false });
814
+ }
815
+ function report(ctx, text) {
816
+ if (ctx.hasUI) ctx.ui.notify(text, "error");
817
+ }
818
+ function cancelQuestions() {
819
+ for (const question of questions) {
820
+ question.unsubscribe();
821
+ question.controller.abort(new DOMException("Plan question owner changed", "AbortError"));
822
+ }
823
+ questions.clear();
824
+ }
825
+ function reset() {
826
+ cancelQuestions();
827
+ pendingAborts.clear();
828
+ failed = false;
829
+ mainShortcutAllowed = true;
830
+ promptOpen = false;
831
+ }
832
+ function failClosed(ctx) {
833
+ failed = true;
834
+ dependencies.resetFinalization();
835
+ dependencies.clearReadyIntent();
836
+ cancelQuestions();
837
+ ctx.abort();
838
+ report(
839
+ ctx,
840
+ "Plan interaction state could not be recovered. Questionnaires are blocked; run /reload before continuing."
841
+ );
842
+ }
843
+ function toggle(ctx) {
844
+ const isCurrent = dependencies.captureCurrent(ctx);
845
+ if (!isCurrent() || !dependencies.getState().enabled) return false;
846
+ if (failed) {
847
+ report(ctx, "Questionnaires are blocked after a failed interaction transition. Run /reload before continuing.");
848
+ return false;
849
+ }
850
+ const currentQuestions = [...questions].filter((question) => question.isCurrent());
851
+ if (!ctx.isIdle() && (ctx.mode !== "tui" || currentQuestions.length === 0)) {
852
+ if (ctx.hasUI)
853
+ ctx.ui.notify("Wait for the agent run to settle before changing Plan interaction mode.", "warning");
854
+ return false;
855
+ }
856
+ const previousState = dependencies.getState();
857
+ const previousMode = mode();
858
+ const nextMode = previousMode === "questions" ? "discussion" : "questions";
859
+ try {
860
+ dependencies.setState({ ...previousState, interactionMode: nextMode });
861
+ dependencies.persistState();
862
+ publish(nextMode);
863
+ } catch {
864
+ dependencies.setState(previousState);
865
+ try {
866
+ dependencies.persistState();
867
+ publish(previousMode);
868
+ } catch {
869
+ failClosed(ctx);
870
+ return false;
871
+ }
872
+ report(ctx, "Unable to change Plan interaction mode. The previous mode and questionnaire are unchanged.");
873
+ return false;
874
+ }
875
+ if (!isCurrent()) return false;
876
+ dependencies.resetFinalization();
877
+ dependencies.clearReadyIntent();
878
+ if (nextMode === "discussion") {
879
+ for (const question of currentQuestions) {
880
+ question.discussionRequested = true;
881
+ pendingAborts.set(question.toolCallId, question);
882
+ question.unsubscribe();
883
+ question.controller.abort(new DOMException("Free discussion requested", "AbortError"));
884
+ }
885
+ }
886
+ dependencies.updateUi(ctx);
887
+ return true;
888
+ }
889
+ return {
890
+ mode,
891
+ publish,
892
+ toggle,
893
+ reset,
894
+ questionsPaused: () => failed || mode() === "discussion",
895
+ shortcutLabel: (ctx) => ctx.mode === "tui" && shortcutRegistered && (!promptOpen || [...questions].some((question) => question.isCurrent())) ? "F2" : void 0,
896
+ promptChanged(open, ctx) {
897
+ if (!dependencies.captureCurrent(ctx)()) return;
898
+ promptOpen = open;
899
+ dependencies.updateUi(ctx);
900
+ },
901
+ startSession(ctx, otherShortcut) {
902
+ removeSessionInput();
903
+ removeSessionInput = () => {
904
+ };
905
+ if (!shortcutInitialized) {
906
+ shortcutInitialized = true;
907
+ if (ctx.mode === "tui") {
908
+ try {
909
+ shortcutRegistered = interactionShortcutAvailable(getKeybindings().getResolvedBindings(), otherShortcut);
910
+ } catch {
911
+ shortcutRegistered = false;
912
+ }
913
+ if (shortcutRegistered) {
914
+ pi.registerShortcut("f2", {
915
+ description: "Toggle Plan questionnaires and free discussion",
916
+ handler: (shortcutCtx) => {
917
+ if (mainShortcutAllowed && !promptOpen) toggle(shortcutCtx);
918
+ }
919
+ });
920
+ }
921
+ }
922
+ }
923
+ if (ctx.mode === "tui" && shortcutRegistered) {
924
+ const permitsInput = createInteractionInputGuard();
925
+ removeSessionInput = ctx.ui.onTerminalInput((data) => {
926
+ mainShortcutAllowed = permitsInput(data);
927
+ const ownsInput = dependencies.getState().enabled && (!promptOpen || [...questions].some((question) => question.isCurrent()));
928
+ if (ownsInput && matchesKey(data, "f2") && (isKeyRelease(data) || isKeyRepeat(data)))
929
+ return { consume: true };
930
+ return void 0;
931
+ });
932
+ }
933
+ },
934
+ disposeSession() {
935
+ removeSessionInput();
936
+ removeSessionInput = () => {
937
+ };
938
+ reset();
939
+ },
940
+ async answer(toolCallId, values, ctx, signal) {
941
+ if (failed || mode() === "discussion") {
942
+ return planModeQuestionCancelled(
943
+ values,
944
+ "questions_paused",
945
+ "Questionnaires are paused. Continue in plain text; only the user can enable questionnaires."
946
+ );
947
+ }
948
+ const isCurrent = dependencies.captureCurrent(ctx);
949
+ const controller = new AbortController();
950
+ const signals = [controller.signal, signal, ctx.signal].filter(
951
+ (value) => value !== void 0
952
+ );
953
+ const question = {
954
+ toolCallId,
955
+ sessionManager: ctx.sessionManager,
956
+ isCurrent,
957
+ controller,
958
+ discussionRequested: false,
959
+ unsubscribe: () => {
960
+ }
961
+ };
962
+ questions.add(question);
963
+ try {
964
+ if (ctx.mode === "tui" && shortcutRegistered) {
965
+ const permitsInput = createInteractionInputGuard();
966
+ const listener = (data) => {
967
+ if (!permitsInput(data) || !matchesKey(data, "f2") || !isCurrent()) return void 0;
968
+ toggle(ctx);
969
+ return { consume: true };
970
+ };
971
+ question.unsubscribe = ctx.ui.onTerminalInput(listener);
972
+ }
973
+ return await answerPlanModeQuestions(values, ctx, {
974
+ isCurrent,
975
+ isEnabled: () => dependencies.getState().enabled,
976
+ signal: AbortSignal.any(signals),
977
+ discussionRequested: () => question.discussionRequested
978
+ });
979
+ } finally {
980
+ question.unsubscribe();
981
+ controller.abort(new DOMException("Plan question completed", "AbortError"));
982
+ questions.delete(question);
983
+ }
984
+ },
985
+ toolExecutionEnd(toolCallId, ctx) {
986
+ const question = pendingAborts.get(toolCallId);
987
+ if (!question) return;
988
+ pendingAborts.delete(toolCallId);
989
+ if (question.sessionManager !== ctx.sessionManager || !question.isCurrent()) return;
990
+ pendingAborts.clear();
991
+ ctx.abort();
992
+ },
993
+ transformContext(messages, ctx) {
994
+ const anchored = restoreInteractionHistory(messages, dependencies.getState().interactionRestorations ?? []);
995
+ if (!dependencies.getState().enabled) return anchored;
996
+ const expected = mode();
997
+ if (latestInteractionContract(anchored)?.mode === expected) return anchored;
998
+ const boundary = { length: anchored.length, hash: contextHash(anchored) };
999
+ const canonical = createInteractionContractMessage(expected, 0);
1000
+ const message = { ...canonical, details: { ...canonical.details, contextBoundary: boundary } };
1001
+ const previousState = dependencies.getState();
1002
+ try {
1003
+ dependencies.setState({
1004
+ ...previousState,
1005
+ interactionRestorations: [
1006
+ ...previousState.interactionRestorations ?? [],
1007
+ { version: 1, mode: expected, boundary }
1008
+ ]
1009
+ });
1010
+ dependencies.persistState();
1011
+ const { role: _role, timestamp: _timestamp, ...persisted } = message;
1012
+ pi.sendMessage(persisted, { triggerTurn: false });
1013
+ } catch {
1014
+ dependencies.setState(previousState);
1015
+ failClosed(ctx);
1016
+ }
1017
+ return [...anchored, message];
1018
+ }
1019
+ };
1020
+ }
1021
+ function contextHash(messages) {
1022
+ return createHash2("sha256").update(JSON.stringify(messages)).digest("hex");
1023
+ }
1024
+ function boundaryMatches(messages, boundary) {
1025
+ return boundary.length <= messages.length && contextHash(messages.slice(0, boundary.length)) === boundary.hash;
1026
+ }
1027
+ function insertAtBoundary(messages, message, index) {
1028
+ return [...messages.slice(0, index), message, ...messages.slice(index)];
1029
+ }
1030
+ function restorationFromMessage(value) {
1031
+ const mode = interactionContractFromMessage(value);
1032
+ if (!mode) return void 0;
1033
+ const message = value;
1034
+ const boundary = message.details?.contextBoundary;
1035
+ if (!boundary || !Number.isSafeInteger(boundary.length) || boundary.length < 0 || typeof boundary.hash !== "string" || !/^[a-f0-9]{64}$/u.test(boundary.hash))
1036
+ return void 0;
1037
+ return { version: 1, mode, boundary };
1038
+ }
1039
+ function restorationKey(value) {
1040
+ return `${value.mode}:${value.boundary.length}:${value.boundary.hash}`;
1041
+ }
1042
+ function restoreInteractionHistory(messages, history) {
1043
+ const restorations = new Map(history.map((value) => [restorationKey(value), value]));
1044
+ for (const message of messages) {
1045
+ const restored = restorationFromMessage(message);
1046
+ if (restored) restorations.set(restorationKey(restored), restored);
1047
+ }
1048
+ let result = messages;
1049
+ for (const [key, restored] of restorations) {
1050
+ const remaining = result.filter((message2) => {
1051
+ const candidate = restorationFromMessage(message2);
1052
+ return !candidate || restorationKey(candidate) !== key;
1053
+ });
1054
+ if (!boundaryMatches(remaining, restored.boundary)) continue;
1055
+ const canonical = createInteractionContractMessage(restored.mode, 0);
1056
+ const message = { ...canonical, details: { ...canonical.details, contextBoundary: restored.boundary } };
1057
+ result = insertAtBoundary(remaining, message, restored.boundary.length);
1058
+ }
1059
+ return result;
1060
+ }
1061
+
688
1062
  // src/plan-action-controller.ts
689
1063
  function createPlanActionController(options) {
690
1064
  const configuredDefaults = () => {
@@ -752,6 +1126,8 @@ function createPlanActionController(options) {
752
1126
  planThinkingLevel: options.getThinkingLevel(),
753
1127
  implementationDefaults: configuredDefaults(),
754
1128
  hasReadyPlan: options.getState().latestPlan !== void 0,
1129
+ interactionMode: options.getState().interactionMode,
1130
+ ...options.toggleInteraction ? { toggleInteraction: () => options.toggleInteraction?.(ctx) } : {},
755
1131
  implementationOutcome: options.implementationOutcome,
756
1132
  getExportDestination: () => options.getExportDestination(ctx),
757
1133
  ...lifecycle,
@@ -765,8 +1141,12 @@ function createPlanActionController(options) {
765
1141
  exit: () => options.exitReady(ctx)
766
1142
  });
767
1143
  },
768
- async showReady(ctx) {
769
- const lifecycle = options.captureLifecycle();
1144
+ async showReady(ctx, presentation) {
1145
+ const workflow = options.captureLifecycle();
1146
+ const lifecycle = presentation ? {
1147
+ signal: AbortSignal.any([workflow.signal, presentation.signal]),
1148
+ isCurrent: () => workflow.isCurrent() && presentation.isCurrent() && !presentation.signal.aborted
1149
+ } : workflow;
770
1150
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
771
1151
  const ui = await options.loadInteractiveUi();
772
1152
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
@@ -817,22 +1197,60 @@ import { EditorStatusWidget } from "@narumitw/pi-tui-kit/editor-status-widget";
817
1197
  var STATUS_KEY = "plan-mode";
818
1198
  var PLAN_WIDGET_KEY = "plan-mode-plan";
819
1199
  var BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
820
- function updatePlanModeUi(ctx, state, toolSummary) {
1200
+ function updatePlanModeUi(ctx, state, toolSummary, interactionShortcut, widgetState) {
821
1201
  ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
822
- let lines;
1202
+ const discussion = state.interactionMode === "discussion";
1203
+ const interactionHint = formatInteractionHint(state, ctx.mode === "tui" ? interactionShortcut : void 0);
1204
+ let presentation;
823
1205
  if (state.enabled && state.latestPlan) {
824
- lines = ["Proposed plan ready", "Use /plan to implement, save, revise, or exit Plan mode."];
1206
+ const actions = "Use /plan to implement, save, revise, or exit Plan mode.";
1207
+ presentation = {
1208
+ summary: discussion ? "Ready \xB7 Free discussion" : "Ready",
1209
+ body: ["File edits remain blocked.", actions, interactionHint],
1210
+ fallback: [
1211
+ "Proposed plan ready",
1212
+ ...discussion ? ["Plan mode: free discussion"] : [],
1213
+ actions,
1214
+ interactionHint
1215
+ ]
1216
+ };
825
1217
  } else if (state.enabled) {
826
- lines = ["Plan mode: planning", toolSummary(), "Finish with plan_mode_complete when decision-ready."];
1218
+ const tools = toolSummary();
1219
+ const discussionHint = "Plain-text questions are allowed; questionnaires are paused.";
1220
+ presentation = {
1221
+ summary: discussion ? "Free discussion" : "Planning",
1222
+ body: ["File edits remain blocked.", tools, ...discussion ? [discussionHint] : [], interactionHint],
1223
+ fallback: [
1224
+ discussion ? "Plan mode: free discussion" : "Plan mode: planning",
1225
+ tools,
1226
+ discussion ? discussionHint : "Finish with plan_mode_complete when decision-ready.",
1227
+ interactionHint
1228
+ ]
1229
+ };
827
1230
  } else if (state.savedPlan) {
828
- lines = ["Plan saved for later", "Use /plan to show, implement, or clear it."];
1231
+ const actions = "Use /plan to show, implement, or clear it.";
1232
+ presentation = { summary: "Saved", body: [actions], fallback: ["Plan saved for later", actions] };
829
1233
  } else if (state.activeImplementation) {
830
- lines = ["Implementation plan active", "Use /plan to show, replace, or clear it."];
1234
+ const actions = "Use /plan to show, replace, or clear it.";
1235
+ presentation = {
1236
+ summary: "Implementation active",
1237
+ body: [actions],
1238
+ fallback: ["Implementation plan active", actions]
1239
+ };
831
1240
  }
832
- publishPlanModeWidget(ctx, lines);
1241
+ publishPlanModeWidget(ctx, presentation, widgetState);
833
1242
  }
834
- function createPlanModeWidget(lines, theme) {
835
- return new EditorStatusWidget({ theme, renderBody: () => lines.map(sanitizePlanModeWidgetLine) });
1243
+ function createPlanModeWidget(lines, theme, state, summary) {
1244
+ return new EditorStatusWidget({
1245
+ theme,
1246
+ name: "Plan mode",
1247
+ summary,
1248
+ state,
1249
+ renderBody: () => lines.map((line, index) => {
1250
+ const text = sanitizePlanModeWidgetLine(line);
1251
+ return index === 0 ? text : theme.fg("muted", text);
1252
+ })
1253
+ });
836
1254
  }
837
1255
  function sanitizePlanModeWidgetLine(value) {
838
1256
  let text = "";
@@ -881,37 +1299,159 @@ ${plan}`,
881
1299
  }
882
1300
  function planModeStatusText(state, toolSummary) {
883
1301
  if (state.enabled) {
884
- if (state.latestPlan) {
885
- return `Plan mode is active and a proposed plan is ready. ${toolSummary()}`;
886
- }
887
- return `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;
1302
+ const ready = state.latestPlan ? " A proposed plan is ready." : "";
1303
+ const interaction = state.interactionMode === "discussion" ? "Free discussion is active; questionnaires are paused and plain-text questions are allowed." : "Explore, ask, and finish with plan_mode_complete when decision-ready.";
1304
+ return `Plan mode is active.${ready} ${interaction} File edits remain blocked. ${toolSummary()}`;
888
1305
  }
889
1306
  if (state.savedPlan) return "A plan is saved for later.";
890
1307
  if (state.activeImplementation) return "An implementation plan is active.";
891
1308
  return "Plan mode is off.";
892
1309
  }
893
- function publishPlanModeWidget(ctx, lines) {
894
- if (!lines) {
1310
+ function publishPlanModeWidget(ctx, presentation, widgetState) {
1311
+ if (!presentation) {
895
1312
  ctx.ui.setWidget(PLAN_WIDGET_KEY, void 0);
896
1313
  return;
897
1314
  }
898
1315
  if (ctx.mode !== "tui") {
899
- ctx.ui.setWidget(PLAN_WIDGET_KEY, [...lines]);
1316
+ ctx.ui.setWidget(PLAN_WIDGET_KEY, [...presentation.fallback]);
900
1317
  return;
901
1318
  }
902
- const snapshot = [...lines];
903
- ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => createPlanModeWidget(snapshot, theme));
1319
+ const snapshot = [...presentation.body];
1320
+ ctx.ui.setWidget(
1321
+ PLAN_WIDGET_KEY,
1322
+ (_tui, theme) => createPlanModeWidget(snapshot, theme, widgetState, presentation.summary)
1323
+ );
1324
+ }
1325
+ function formatInteractionHint(state, interactionShortcut) {
1326
+ const action = state.interactionMode === "discussion" ? "enable questionnaires" : "switch to free discussion";
1327
+ return interactionShortcut ? `${interactionShortcut}: ${action}.` : `Use /plan to ${action}.`;
904
1328
  }
905
1329
  function formatStatus(state) {
906
1330
  if (state.enabled) {
907
1331
  if (state.awaitingAction || state.latestPlan) return "plan ready";
908
- return "plan active";
1332
+ return state.interactionMode === "discussion" ? "plan discussion" : "plan active";
909
1333
  }
910
1334
  if (state.savedPlan) return "plan saved";
911
1335
  if (state.activeImplementation) return "plan implementing";
912
1336
  return void 0;
913
1337
  }
914
1338
 
1339
+ // src/question-renderer.ts
1340
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
1341
+ import { hardWrapTerminalDocument, sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
1342
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
1343
+ var graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1344
+ function renderPlanModeQuestionCall(args, theme) {
1345
+ const questions = isRecord3(args) && Array.isArray(args.questions) ? args.questions : [];
1346
+ return boundedComponent((width) => {
1347
+ const title = questions.length > 1 ? "Plan questions" : "Plan question";
1348
+ const headers = questions.map((question) => isRecord3(question) ? displayLine(question.header) : "").filter(Boolean);
1349
+ const text = theme.fg("toolTitle", theme.bold(title)) + theme.fg("muted", headers.length ? ` ${headers.join(" \xB7 ")}` : "");
1350
+ return [truncateToWidth(text, width, "\u2026")];
1351
+ });
1352
+ }
1353
+ function renderPlanModeQuestionResult(result, { expanded, isPartial }, theme, context = {}) {
1354
+ const text = result.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
1355
+ const payload = questionPayload(result.details, text);
1356
+ return boundedComponent((width) => {
1357
+ const muted = (value) => theme.fg("muted", value);
1358
+ const hint = () => context.keyText?.("app.tools.expand") && context.keyHint ? [truncateToWidth(muted(context.keyHint("app.tools.expand", "to expand")), width, "\u2026")] : [];
1359
+ if (isPartial) return [truncateToWidth(muted("Waiting for answers\u2026"), width, "\u2026")];
1360
+ if (context.isError || payload?.cancelled === true) {
1361
+ const reason = payload?.reason;
1362
+ const failed = context.isError || reason === "invalid_input";
1363
+ const status = context.isError ? "Question failed" : reason === "ui_unavailable" ? "Interactive UI unavailable" : reason === "plan_mode_inactive" ? "Plan mode inactive" : reason === "invalid_input" ? "Invalid question" : "Question cancelled";
1364
+ const message = typeof payload?.message === "string" ? payload.message : text;
1365
+ const lines2 = documentLines(status, width, (value) => theme.fg(failed ? "error" : "warning", value));
1366
+ if (expanded) {
1367
+ lines2.push(...documentLines(message, width, muted, " "));
1368
+ } else if (message) {
1369
+ lines2.push(...hint());
1370
+ }
1371
+ return lines2;
1372
+ }
1373
+ const answers = payload?.answers;
1374
+ if (payload?.cancelled === false && Array.isArray(answers) && answers.length > 0 && answers.every(isAnswer)) {
1375
+ const lines2 = [];
1376
+ for (const answer of answers) {
1377
+ if (!expanded) {
1378
+ const badge = answer.wasCustom ? muted(" (custom)") : "";
1379
+ const note = answer.note ? muted(" \xB7 note") : "";
1380
+ lines2.push(
1381
+ truncateToWidth(
1382
+ theme.fg("success", "\u2713 ") + muted(`${displayLine(answer.header)}: `) + theme.fg("accent", displayLine(answer.answer)) + badge + note,
1383
+ width,
1384
+ "\u2026"
1385
+ )
1386
+ );
1387
+ continue;
1388
+ }
1389
+ if (lines2.length) lines2.push("");
1390
+ lines2.push(...documentLines(answer.header, width, (value) => theme.fg("accent", theme.bold(value))));
1391
+ lines2.push(...documentLines(answer.question, width, muted, " "));
1392
+ if (answer.wasCustom) lines2.push(...documentLines("Custom answer", width, muted, " "));
1393
+ lines2.push(
1394
+ ...documentLines(
1395
+ answer.answer,
1396
+ width,
1397
+ (value) => theme.fg("text", value),
1398
+ " \u2713 ",
1399
+ (value) => theme.fg("success", value)
1400
+ )
1401
+ );
1402
+ if (answer.note) {
1403
+ lines2.push(...documentLines("Note", width, muted, " "));
1404
+ lines2.push(...documentLines(answer.note, width, muted, " "));
1405
+ }
1406
+ }
1407
+ if (!expanded) lines2.push(...hint());
1408
+ return lines2;
1409
+ }
1410
+ const lines = documentLines(text || "No answer returned.", width, (value) => theme.fg("toolOutput", value));
1411
+ return expanded || lines.length <= 4 ? lines : [...lines.slice(0, 4), ...hint()];
1412
+ });
1413
+ }
1414
+ function questionPayload(details, text) {
1415
+ let payload;
1416
+ try {
1417
+ payload = JSON.parse(text);
1418
+ } catch {
1419
+ }
1420
+ const parsed = isRecord3(payload) ? payload : void 0;
1421
+ return isRecord3(details) && typeof details.cancelled === "boolean" ? { ...parsed, ...details } : parsed;
1422
+ }
1423
+ function isAnswer(value) {
1424
+ return isRecord3(value) && typeof value.header === "string" && typeof value.question === "string" && typeof value.answer === "string" && typeof value.wasCustom === "boolean" && (value.note === void 0 || typeof value.note === "string");
1425
+ }
1426
+ function isRecord3(value) {
1427
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1428
+ }
1429
+ function displayLine(value) {
1430
+ return typeof value === "string" ? sanitizeTerminalText(value) : "";
1431
+ }
1432
+ function documentLines(value, width, style, prefix = "", prefixStyle = style) {
1433
+ const text = sanitizeTerminalDocument(value);
1434
+ let contentWidth = 1;
1435
+ for (const { segment } of graphemeSegmenter.segment(text)) {
1436
+ contentWidth = Math.min(width, Math.max(contentWidth, visibleWidth(segment)));
1437
+ }
1438
+ const visiblePrefix = truncateToWidth(prefix, width - contentWidth, "");
1439
+ const prefixWidth = visibleWidth(visiblePrefix);
1440
+ return hardWrapTerminalDocument(text, width - prefixWidth).map((line, index) => {
1441
+ const decoration = index === 0 ? visiblePrefix : " ".repeat(prefixWidth);
1442
+ const safePrefix = visibleWidth(decoration + line) <= width ? decoration : "";
1443
+ return prefixStyle(safePrefix) + style(line);
1444
+ });
1445
+ }
1446
+ function boundedComponent(render) {
1447
+ return {
1448
+ render: (width) => Number.isFinite(width) && width >= 1 ? render(Math.floor(width)) : [],
1449
+ // Theme styles are evaluated on every render, so there is no cache to clear.
1450
+ invalidate() {
1451
+ }
1452
+ };
1453
+ }
1454
+
915
1455
  // src/required-tools.ts
916
1456
  var REQUIRED_PLAN_MODE_TOOL_NAMES = [PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
917
1457
  function planModeHelperToolsAvailable(toolNames) {
@@ -1033,11 +1573,12 @@ function planMode(pi, dependencies = {}) {
1033
1573
  let workflowOwner;
1034
1574
  let currentSession;
1035
1575
  let currentSessionContext;
1576
+ let widgetState = { collapsed: false };
1036
1577
  let interactiveUiPromise;
1037
1578
  const loadInteractiveUi = () => {
1038
1579
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
1039
1580
  if (!interactiveUiPromise) {
1040
- interactiveUiPromise = import("./chunks/interactive-ui-RG7CBW6F.ts").catch((error) => {
1581
+ interactiveUiPromise = import("./chunks/interactive-ui-EMUWYNHT.ts").catch((error) => {
1041
1582
  interactiveUiPromise = void 0;
1042
1583
  throw error;
1043
1584
  });
@@ -1054,6 +1595,7 @@ function planMode(pi, dependencies = {}) {
1054
1595
  let publishedContractMode;
1055
1596
  let modeContractsRelevant = false;
1056
1597
  let readyPresentationIntent;
1598
+ let readyMenuController = new AbortController();
1057
1599
  let latestCommandContext;
1058
1600
  let stagedFreshImplementation;
1059
1601
  const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();
@@ -1070,6 +1612,26 @@ function planMode(pi, dependencies = {}) {
1070
1612
  const implementationRetention = createImplementationRetentionCoordinator();
1071
1613
  const finalizationRequest = createFinalizationRequestCoordinator();
1072
1614
  const persistState = () => pi.appendEntry(STATE_ENTRY_TYPE, state);
1615
+ const interaction = createInteractionCoordinator(pi, {
1616
+ getState: () => state,
1617
+ setState: (next) => {
1618
+ state = next;
1619
+ },
1620
+ persistState,
1621
+ captureCurrent: (ctx) => {
1622
+ const session = ctx.sessionManager;
1623
+ const generation = workflowGeneration;
1624
+ const sessionGeneration = menuGeneration;
1625
+ const owner = workflowOwner;
1626
+ return () => currentSession === session && generation === workflowGeneration && sessionGeneration === menuGeneration && !menuController.signal.aborted && workflowMutex.isOwner(owner);
1627
+ },
1628
+ clearReadyIntent: () => {
1629
+ invalidateReadyMenu();
1630
+ readyPresentationIntent = readyPresentationIntent?.source === "legacy_proposed_plan" ? { ...readyPresentationIntent, showMenu: false } : void 0;
1631
+ },
1632
+ resetFinalization: () => finalizationRequest.reset(),
1633
+ updateUi
1634
+ });
1073
1635
  const planExports = createPlanExportController({
1074
1636
  getState: () => state,
1075
1637
  getSettings: () => settings,
@@ -1096,6 +1658,9 @@ function planMode(pi, dependencies = {}) {
1096
1658
  settings: showSettings,
1097
1659
  save: savePlanForLater,
1098
1660
  stay: updateUi,
1661
+ toggleInteraction: (ctx) => {
1662
+ interaction.toggle(ctx);
1663
+ },
1099
1664
  exitReady: (ctx) => {
1100
1665
  if (exitPlanMode(ctx)) {
1101
1666
  ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
@@ -1110,7 +1675,9 @@ function planMode(pi, dependencies = {}) {
1110
1675
  label: "Plan question",
1111
1676
  description: "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.",
1112
1677
  parameters: PLAN_MODE_QUESTION_PARAMS,
1113
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1678
+ renderCall: renderPlanModeQuestionCall,
1679
+ renderResult: renderPlanModeQuestionResult,
1680
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
1114
1681
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
1115
1682
  return planModeQuestionCancelled(
1116
1683
  [],
@@ -1123,6 +1690,7 @@ function planMode(pi, dependencies = {}) {
1123
1690
  return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
1124
1691
  }
1125
1692
  finalizationRequest.satisfy();
1693
+ if (interaction.questionsPaused()) return interaction.answer(toolCallId, parsed.questions, ctx, signal);
1126
1694
  if (!ctx.hasUI) {
1127
1695
  return planModeQuestionCancelled(
1128
1696
  parsed.questions,
@@ -1130,13 +1698,7 @@ function planMode(pi, dependencies = {}) {
1130
1698
  "Unable to ask Plan-mode questions because interactive UI is not available."
1131
1699
  );
1132
1700
  }
1133
- const sessionGeneration = menuGeneration;
1134
- const questionWorkflowGeneration = workflowGeneration;
1135
- const questionOwner = workflowOwner;
1136
- return answerPlanModeQuestions(parsed.questions, ctx, {
1137
- isCurrent: () => sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration && workflowMutex.isOwner(questionOwner),
1138
- isEnabled: () => state.enabled
1139
- });
1701
+ return interaction.answer(toolCallId, parsed.questions, ctx, signal);
1140
1702
  }
1141
1703
  });
1142
1704
  pi.registerTool({
@@ -1236,6 +1798,10 @@ function planMode(pi, dependencies = {}) {
1236
1798
  "The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>."
1237
1799
  );
1238
1800
  }
1801
+ if (ctx.mode === "tui" && widgetState.collapsed) {
1802
+ widgetState.collapsed = false;
1803
+ updateUi(ctx);
1804
+ }
1239
1805
  if (!state.enabled) {
1240
1806
  if (state.activeImplementation && ctx.hasUI) {
1241
1807
  await showActivePlanMenu(ctx);
@@ -1321,9 +1887,12 @@ function planMode(pi, dependencies = {}) {
1321
1887
  }
1322
1888
  };
1323
1889
  pi.on("session_start", async (event, ctx) => {
1890
+ interaction.disposeSession();
1891
+ invalidateReadyMenu();
1324
1892
  cancelDeferredFreshImplementation();
1325
1893
  const generation = ++menuGeneration;
1326
1894
  finalizationRequest.reset();
1895
+ widgetState = { collapsed: false };
1327
1896
  currentSession = ctx.sessionManager;
1328
1897
  currentSessionContext = ctx;
1329
1898
  workflowOwner = void 0;
@@ -1346,6 +1915,7 @@ function planMode(pi, dependencies = {}) {
1346
1915
  await applyPlanModeSettings(generation, ctx, true);
1347
1916
  if (generation !== menuGeneration || menuController.signal.aborted) return;
1348
1917
  initializePlanModeShortcut();
1918
+ interaction.startSession(ctx, startupToggleShortcut);
1349
1919
  startPlanModeSettingsWatch(generation);
1350
1920
  if (!installRestoredState(restoredState, ctx)) return;
1351
1921
  implementationRetention.restore(state.activeImplementation);
@@ -1363,7 +1933,7 @@ function planMode(pi, dependencies = {}) {
1363
1933
  return { cancel: true };
1364
1934
  }
1365
1935
  const target = ctx.sessionManager.getEntry(event.preparation.targetId);
1366
- if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
1936
+ if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE && target.customType !== INTERACTION_CONTRACT_MESSAGE_TYPE) {
1367
1937
  return;
1368
1938
  }
1369
1939
  if (ctx.hasUI) {
@@ -1407,6 +1977,12 @@ function planMode(pi, dependencies = {}) {
1407
1977
  }
1408
1978
  });
1409
1979
  pi.on("session_shutdown", async (_event, ctx) => {
1980
+ if (currentSession !== void 0 && currentSession !== ctx.sessionManager) {
1981
+ workflowMutex.unbindSession(ctx.sessionManager);
1982
+ return;
1983
+ }
1984
+ interaction.disposeSession();
1985
+ invalidateReadyMenu();
1410
1986
  cancelDeferredFreshImplementation();
1411
1987
  const shutdownSession = ctx.sessionManager;
1412
1988
  const runtimeApplication = activeImplementationRuntimeApplication?.sessionManager === shutdownSession && activeImplementationRuntimeApplication.drainOnShutdown ? activeImplementationRuntimeApplication : void 0;
@@ -1453,6 +2029,7 @@ function planMode(pi, dependencies = {}) {
1453
2029
  if (currentSession === ctx.sessionManager) {
1454
2030
  currentSession = void 0;
1455
2031
  currentSessionContext = void 0;
2032
+ widgetState = { collapsed: false };
1456
2033
  }
1457
2034
  });
1458
2035
  pi.on("tool_call", async (event, ctx) => {
@@ -1534,8 +2111,17 @@ Blocked command: ${blocked}`
1534
2111
  }
1535
2112
  }
1536
2113
  });
2114
+ pi.on("tool_execution_end", (event, ctx) => {
2115
+ interaction.toolExecutionEnd(event.toolCallId, ctx);
2116
+ });
2117
+ pi.on("ui_prompt_start", (_event, ctx) => {
2118
+ interaction.promptChanged(true, ctx);
2119
+ });
2120
+ pi.on("ui_prompt_end", (_event, ctx) => {
2121
+ interaction.promptChanged(false, ctx);
2122
+ });
1537
2123
  pi.on("message_start", (event) => {
1538
- if (state.enabled && event.message.role === "user" && messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT) {
2124
+ if (state.enabled && interaction.mode() === "questions" && event.message.role === "user" && messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT) {
1539
2125
  finalizationRequest.request(workflowGeneration);
1540
2126
  }
1541
2127
  });
@@ -1546,7 +2132,7 @@ Blocked command: ${blocked}`
1546
2132
  clearActiveImplementation(result.clearActiveImplementationId, ctx);
1547
2133
  }
1548
2134
  const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
1549
- return { messages };
2135
+ return { messages: interaction.transformContext(messages, ctx) };
1550
2136
  });
1551
2137
  pi.on("input", async (event, ctx) => {
1552
2138
  refreshStateForFirstPrompt(ctx);
@@ -1583,6 +2169,7 @@ Blocked command: ${blocked}`
1583
2169
  refreshStateForFirstPrompt(ctx);
1584
2170
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1585
2171
  if (state.latestPlan || state.awaitingAction) {
2172
+ invalidateReadyMenu();
1586
2173
  cancelDeferredFreshImplementation();
1587
2174
  readyPresentationIntent = void 0;
1588
2175
  state = {
@@ -1600,7 +2187,9 @@ Blocked command: ${blocked}`
1600
2187
  const text = latestAssistantText(event.messages);
1601
2188
  const parsedPlan = parseProposedPlan(text);
1602
2189
  if (parsedPlan.kind !== "valid") {
1603
- finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
2190
+ if (interaction.mode() === "questions") {
2191
+ finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
2192
+ }
1604
2193
  if (parsedPlan.kind !== "absent") {
1605
2194
  ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
1606
2195
  }
@@ -1613,7 +2202,7 @@ Blocked command: ${blocked}`
1613
2202
  pi.on("agent_settled", async (_event, ctx) => {
1614
2203
  const settledImplementationId = implementationRetention.implementationSettled(state.activeImplementation);
1615
2204
  if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
1616
- if (finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
2205
+ if (interaction.mode() === "questions" && finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
1617
2206
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
1618
2207
  const action = finalizationRequest.settle(workflowGeneration);
1619
2208
  if (action === "retry") {
@@ -1645,8 +2234,12 @@ ${intent.plan}`,
1645
2234
  { triggerTurn: false }
1646
2235
  );
1647
2236
  }
1648
- if (ctx.hasUI && completedPlanIsCurrent(intent)) {
1649
- await planActions.showReady(latestCommandContext ?? ctx);
2237
+ if (intent.showMenu && ctx.hasUI && completedPlanIsCurrent(intent)) {
2238
+ const controller = readyMenuController;
2239
+ await planActions.showReady(latestCommandContext ?? ctx, {
2240
+ signal: controller.signal,
2241
+ isCurrent: () => completedPlanIsCurrent(intent) && interaction.mode() === "questions"
2242
+ });
1650
2243
  }
1651
2244
  const request = stagedFreshImplementation;
1652
2245
  stagedFreshImplementation = void 0;
@@ -1680,6 +2273,7 @@ ${intent.plan}`,
1680
2273
  state = {
1681
2274
  ...state,
1682
2275
  enabled: true,
2276
+ interactionMode: "questions",
1683
2277
  awaitingAction: false,
1684
2278
  savedPlan: void 0,
1685
2279
  activeImplementation: void 0,
@@ -1690,6 +2284,7 @@ ${intent.plan}`,
1690
2284
  beginWorkflowToolPolicy();
1691
2285
  applyPlanThinkingLevel();
1692
2286
  persistState();
2287
+ interaction.publish("questions");
1693
2288
  updateUi(ctx);
1694
2289
  return true;
1695
2290
  } catch (error) {
@@ -1721,6 +2316,7 @@ ${intent.plan}`,
1721
2316
  state = {
1722
2317
  ...state,
1723
2318
  enabled: false,
2319
+ interactionMode: void 0,
1724
2320
  latestPlan: void 0,
1725
2321
  latestPlanSource: void 0,
1726
2322
  awaitingAction: false,
@@ -1782,20 +2378,27 @@ ${intent.plan}`,
1782
2378
  if (state.enabled && state.awaitingAction && state.latestPlan === normalized.plan && state.latestPlanSource === source) {
1783
2379
  return;
1784
2380
  }
2381
+ invalidateReadyMenu();
1785
2382
  state = {
1786
2383
  ...state,
1787
2384
  latestPlan: normalized.plan,
1788
2385
  latestPlanSource: source,
1789
2386
  awaitingAction: true
1790
2387
  };
1791
- readyPresentationIntent = {
2388
+ const showMenu = interaction.mode() === "questions";
2389
+ readyPresentationIntent = showMenu || source === "legacy_proposed_plan" ? {
1792
2390
  nonce: ++nextReadyPresentationNonce,
1793
2391
  plan: normalized.plan,
1794
- source
1795
- };
2392
+ source,
2393
+ showMenu
2394
+ } : void 0;
1796
2395
  persistState();
1797
2396
  updateUi(ctx);
1798
2397
  }
2398
+ function invalidateReadyMenu() {
2399
+ readyMenuController.abort(new DOMException("Plan presentation superseded", "AbortError"));
2400
+ readyMenuController = new AbortController();
2401
+ }
1799
2402
  function completedPlanIsCurrent(intent) {
1800
2403
  return state.enabled && workflowMutex.isOwner(workflowOwner) && state.awaitingAction && state.latestPlan === intent.plan && state.latestPlanSource === intent.source;
1801
2404
  }
@@ -1821,6 +2424,11 @@ ${intent.plan}`,
1821
2424
  ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
1822
2425
  return;
1823
2426
  }
2427
+ if (interaction.mode() === "discussion") {
2428
+ finalizationRequest.reset();
2429
+ sendPlanModeUserMessage(DISCUSSION_FINALIZE_PLAN_PROMPT, ctx);
2430
+ return;
2431
+ }
1824
2432
  finalizationRequest.request(workflowGeneration);
1825
2433
  if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
1826
2434
  }
@@ -1841,6 +2449,7 @@ ${intent.plan}`,
1841
2449
  state = {
1842
2450
  ...state,
1843
2451
  enabled: false,
2452
+ interactionMode: void 0,
1844
2453
  latestPlan: void 0,
1845
2454
  latestPlanSource: void 0,
1846
2455
  awaitingAction: false,
@@ -1957,6 +2566,7 @@ ${intent.plan}`,
1957
2566
  state = {
1958
2567
  ...state,
1959
2568
  enabled: false,
2569
+ interactionMode: void 0,
1960
2570
  latestPlan: void 0,
1961
2571
  latestPlanSource: void 0,
1962
2572
  awaitingAction: false,
@@ -1986,6 +2596,7 @@ ${intent.plan}`,
1986
2596
  if (wasEnabled) {
1987
2597
  restoreWorkflowToolPolicy(state.workflowToolPolicy);
1988
2598
  publishModeContract("plan", ctx);
2599
+ interaction.publish(interaction.mode());
1989
2600
  applyPlanThinkingLevel();
1990
2601
  }
1991
2602
  persistState();
@@ -2133,6 +2744,8 @@ ${intent.plan}`,
2133
2744
  return false;
2134
2745
  }
2135
2746
  function advanceWorkflowGeneration() {
2747
+ interaction.reset();
2748
+ invalidateReadyMenu();
2136
2749
  cancelDeferredFreshImplementation();
2137
2750
  workflowGeneration += 1;
2138
2751
  pendingWorkflowToolPolicy = void 0;
@@ -2562,6 +3175,7 @@ ${intent.plan}`,
2562
3175
  }
2563
3176
  function rollbackNewActivation(previousState, ctx, previousOwner) {
2564
3177
  const activatedOwner = workflowOwner;
3178
+ interaction.reset();
2565
3179
  readyPresentationIntent = void 0;
2566
3180
  try {
2567
3181
  if (state.enabled) {
@@ -2585,6 +3199,7 @@ ${intent.plan}`,
2585
3199
  }
2586
3200
  function bindWorkflowSessionIfNeeded(ctx) {
2587
3201
  if (currentSession === ctx.sessionManager) return;
3202
+ widgetState = { collapsed: false };
2588
3203
  currentSession = ctx.sessionManager;
2589
3204
  workflowOwner = void 0;
2590
3205
  workflowMutex.bindSession(ctx.sessionManager);
@@ -2622,7 +3237,7 @@ ${intent.plan}`,
2622
3237
  return false;
2623
3238
  }
2624
3239
  function updateUi(ctx) {
2625
- updatePlanModeUi(ctx, state, formatToolSummary);
3240
+ updatePlanModeUi(ctx, state, formatToolSummary, interaction.shortcutLabel(ctx), widgetState);
2626
3241
  }
2627
3242
  function clearUi(ctx) {
2628
3243
  clearPlanModeUi(ctx);