@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/CHANGELOG.md +228 -0
- package/README.md +40 -13
- package/dist/chunks/{chunk-MJV6WNHK.ts → chunk-UJ6TV2YV.ts} +102 -86
- package/dist/chunks/chunk-UJ6TV2YV.ts.map +7 -0
- package/dist/chunks/{interactive-ui-F7FMN7FT.ts → interactive-ui-EMUWYNHT.ts} +15 -2
- package/dist/chunks/interactive-ui-EMUWYNHT.ts.map +7 -0
- package/dist/index.ts +616 -32
- package/dist/index.ts.map +4 -4
- package/docs/command-workflows.md +30 -0
- package/package.json +5 -4
- package/src/finalization-request.ts +3 -0
- package/src/interaction-contract.ts +73 -0
- package/src/interaction-coordinator.ts +379 -0
- package/src/plan-action-controller.ts +11 -2
- package/src/plan-action-menus.ts +18 -0
- package/src/plan-mode.ts +115 -24
- package/src/presentation.ts +42 -9
- package/src/question-renderer.ts +174 -0
- package/src/question-tool.ts +32 -4
- package/src/state.ts +40 -0
- package/dist/chunks/chunk-MJV6WNHK.ts.map +0 -7
- package/dist/chunks/interactive-ui-F7FMN7FT.ts.map +0 -7
package/dist/index.ts
CHANGED
|
@@ -48,7 +48,7 @@ import {
|
|
|
48
48
|
snapshotAvailableImplementationModels,
|
|
49
49
|
snapshotPlanModeSelectedNames,
|
|
50
50
|
updatePlanModeSettings
|
|
51
|
-
} from "./chunks/chunk-
|
|
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
|
|
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,13 +1197,25 @@ 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) {
|
|
821
1201
|
ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
|
|
1202
|
+
const discussion = state.interactionMode === "discussion";
|
|
1203
|
+
const interactionHint = formatInteractionHint(state, ctx.mode === "tui" ? interactionShortcut : void 0);
|
|
822
1204
|
let lines;
|
|
823
1205
|
if (state.enabled && state.latestPlan) {
|
|
824
|
-
lines = [
|
|
1206
|
+
lines = [
|
|
1207
|
+
"Proposed plan ready",
|
|
1208
|
+
...discussion ? ["Plan mode: free discussion"] : [],
|
|
1209
|
+
"Use /plan to implement, save, revise, or exit Plan mode.",
|
|
1210
|
+
interactionHint
|
|
1211
|
+
];
|
|
825
1212
|
} else if (state.enabled) {
|
|
826
|
-
lines = [
|
|
1213
|
+
lines = [
|
|
1214
|
+
discussion ? "Plan mode: free discussion" : "Plan mode: planning",
|
|
1215
|
+
toolSummary(),
|
|
1216
|
+
discussion ? "Plain-text questions are allowed; questionnaires are paused." : "Finish with plan_mode_complete when decision-ready.",
|
|
1217
|
+
interactionHint
|
|
1218
|
+
];
|
|
827
1219
|
} else if (state.savedPlan) {
|
|
828
1220
|
lines = ["Plan saved for later", "Use /plan to show, implement, or clear it."];
|
|
829
1221
|
} else if (state.activeImplementation) {
|
|
@@ -832,7 +1224,13 @@ function updatePlanModeUi(ctx, state, toolSummary) {
|
|
|
832
1224
|
publishPlanModeWidget(ctx, lines);
|
|
833
1225
|
}
|
|
834
1226
|
function createPlanModeWidget(lines, theme) {
|
|
835
|
-
return new EditorStatusWidget({
|
|
1227
|
+
return new EditorStatusWidget({
|
|
1228
|
+
theme,
|
|
1229
|
+
renderBody: () => lines.map((line, index) => {
|
|
1230
|
+
const text = sanitizePlanModeWidgetLine(line);
|
|
1231
|
+
return index === 0 ? text : theme.fg("muted", text);
|
|
1232
|
+
})
|
|
1233
|
+
});
|
|
836
1234
|
}
|
|
837
1235
|
function sanitizePlanModeWidgetLine(value) {
|
|
838
1236
|
let text = "";
|
|
@@ -881,10 +1279,9 @@ ${plan}`,
|
|
|
881
1279
|
}
|
|
882
1280
|
function planModeStatusText(state, toolSummary) {
|
|
883
1281
|
if (state.enabled) {
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
}
|
|
887
|
-
return `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;
|
|
1282
|
+
const ready = state.latestPlan ? " A proposed plan is ready." : "";
|
|
1283
|
+
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.";
|
|
1284
|
+
return `Plan mode is active.${ready} ${interaction} File edits remain blocked. ${toolSummary()}`;
|
|
888
1285
|
}
|
|
889
1286
|
if (state.savedPlan) return "A plan is saved for later.";
|
|
890
1287
|
if (state.activeImplementation) return "An implementation plan is active.";
|
|
@@ -902,16 +1299,136 @@ function publishPlanModeWidget(ctx, lines) {
|
|
|
902
1299
|
const snapshot = [...lines];
|
|
903
1300
|
ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => createPlanModeWidget(snapshot, theme));
|
|
904
1301
|
}
|
|
1302
|
+
function formatInteractionHint(state, interactionShortcut) {
|
|
1303
|
+
const action = state.interactionMode === "discussion" ? "enable questionnaires" : "switch to free discussion";
|
|
1304
|
+
return interactionShortcut ? `${interactionShortcut}: ${action}.` : `Use /plan to ${action}.`;
|
|
1305
|
+
}
|
|
905
1306
|
function formatStatus(state) {
|
|
906
1307
|
if (state.enabled) {
|
|
907
1308
|
if (state.awaitingAction || state.latestPlan) return "plan ready";
|
|
908
|
-
return "plan active";
|
|
1309
|
+
return state.interactionMode === "discussion" ? "plan discussion" : "plan active";
|
|
909
1310
|
}
|
|
910
1311
|
if (state.savedPlan) return "plan saved";
|
|
911
1312
|
if (state.activeImplementation) return "plan implementing";
|
|
912
1313
|
return void 0;
|
|
913
1314
|
}
|
|
914
1315
|
|
|
1316
|
+
// src/question-renderer.ts
|
|
1317
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
1318
|
+
import { hardWrapTerminalDocument, sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
|
|
1319
|
+
import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
|
|
1320
|
+
var graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
|
|
1321
|
+
function renderPlanModeQuestionCall(args, theme) {
|
|
1322
|
+
const questions = isRecord3(args) && Array.isArray(args.questions) ? args.questions : [];
|
|
1323
|
+
return boundedComponent((width) => {
|
|
1324
|
+
const title = questions.length > 1 ? "Plan questions" : "Plan question";
|
|
1325
|
+
const headers = questions.map((question) => isRecord3(question) ? displayLine(question.header) : "").filter(Boolean);
|
|
1326
|
+
const text = theme.fg("toolTitle", theme.bold(title)) + theme.fg("muted", headers.length ? ` ${headers.join(" \xB7 ")}` : "");
|
|
1327
|
+
return [truncateToWidth(text, width, "\u2026")];
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
function renderPlanModeQuestionResult(result, { expanded, isPartial }, theme, context = {}) {
|
|
1331
|
+
const text = result.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
|
|
1332
|
+
const payload = questionPayload(result.details, text);
|
|
1333
|
+
return boundedComponent((width) => {
|
|
1334
|
+
const muted = (value) => theme.fg("muted", value);
|
|
1335
|
+
const hint = () => context.keyText?.("app.tools.expand") && context.keyHint ? [truncateToWidth(muted(context.keyHint("app.tools.expand", "to expand")), width, "\u2026")] : [];
|
|
1336
|
+
if (isPartial) return [truncateToWidth(muted("Waiting for answers\u2026"), width, "\u2026")];
|
|
1337
|
+
if (context.isError || payload?.cancelled === true) {
|
|
1338
|
+
const reason = payload?.reason;
|
|
1339
|
+
const failed = context.isError || reason === "invalid_input";
|
|
1340
|
+
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";
|
|
1341
|
+
const message = typeof payload?.message === "string" ? payload.message : text;
|
|
1342
|
+
const lines2 = documentLines(status, width, (value) => theme.fg(failed ? "error" : "warning", value));
|
|
1343
|
+
if (expanded) {
|
|
1344
|
+
lines2.push(...documentLines(message, width, muted, " "));
|
|
1345
|
+
} else if (message) {
|
|
1346
|
+
lines2.push(...hint());
|
|
1347
|
+
}
|
|
1348
|
+
return lines2;
|
|
1349
|
+
}
|
|
1350
|
+
const answers = payload?.answers;
|
|
1351
|
+
if (payload?.cancelled === false && Array.isArray(answers) && answers.length > 0 && answers.every(isAnswer)) {
|
|
1352
|
+
const lines2 = [];
|
|
1353
|
+
for (const answer of answers) {
|
|
1354
|
+
if (!expanded) {
|
|
1355
|
+
const badge = answer.wasCustom ? muted(" (custom)") : "";
|
|
1356
|
+
const note = answer.note ? muted(" \xB7 note") : "";
|
|
1357
|
+
lines2.push(
|
|
1358
|
+
truncateToWidth(
|
|
1359
|
+
theme.fg("success", "\u2713 ") + muted(`${displayLine(answer.header)}: `) + theme.fg("accent", displayLine(answer.answer)) + badge + note,
|
|
1360
|
+
width,
|
|
1361
|
+
"\u2026"
|
|
1362
|
+
)
|
|
1363
|
+
);
|
|
1364
|
+
continue;
|
|
1365
|
+
}
|
|
1366
|
+
if (lines2.length) lines2.push("");
|
|
1367
|
+
lines2.push(...documentLines(answer.header, width, (value) => theme.fg("accent", theme.bold(value))));
|
|
1368
|
+
lines2.push(...documentLines(answer.question, width, muted, " "));
|
|
1369
|
+
if (answer.wasCustom) lines2.push(...documentLines("Custom answer", width, muted, " "));
|
|
1370
|
+
lines2.push(
|
|
1371
|
+
...documentLines(
|
|
1372
|
+
answer.answer,
|
|
1373
|
+
width,
|
|
1374
|
+
(value) => theme.fg("text", value),
|
|
1375
|
+
" \u2713 ",
|
|
1376
|
+
(value) => theme.fg("success", value)
|
|
1377
|
+
)
|
|
1378
|
+
);
|
|
1379
|
+
if (answer.note) {
|
|
1380
|
+
lines2.push(...documentLines("Note", width, muted, " "));
|
|
1381
|
+
lines2.push(...documentLines(answer.note, width, muted, " "));
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
if (!expanded) lines2.push(...hint());
|
|
1385
|
+
return lines2;
|
|
1386
|
+
}
|
|
1387
|
+
const lines = documentLines(text || "No answer returned.", width, (value) => theme.fg("toolOutput", value));
|
|
1388
|
+
return expanded || lines.length <= 4 ? lines : [...lines.slice(0, 4), ...hint()];
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
function questionPayload(details, text) {
|
|
1392
|
+
let payload;
|
|
1393
|
+
try {
|
|
1394
|
+
payload = JSON.parse(text);
|
|
1395
|
+
} catch {
|
|
1396
|
+
}
|
|
1397
|
+
const parsed = isRecord3(payload) ? payload : void 0;
|
|
1398
|
+
return isRecord3(details) && typeof details.cancelled === "boolean" ? { ...parsed, ...details } : parsed;
|
|
1399
|
+
}
|
|
1400
|
+
function isAnswer(value) {
|
|
1401
|
+
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");
|
|
1402
|
+
}
|
|
1403
|
+
function isRecord3(value) {
|
|
1404
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1405
|
+
}
|
|
1406
|
+
function displayLine(value) {
|
|
1407
|
+
return typeof value === "string" ? sanitizeTerminalText(value) : "";
|
|
1408
|
+
}
|
|
1409
|
+
function documentLines(value, width, style, prefix = "", prefixStyle = style) {
|
|
1410
|
+
const text = sanitizeTerminalDocument(value);
|
|
1411
|
+
let contentWidth = 1;
|
|
1412
|
+
for (const { segment } of graphemeSegmenter.segment(text)) {
|
|
1413
|
+
contentWidth = Math.min(width, Math.max(contentWidth, visibleWidth(segment)));
|
|
1414
|
+
}
|
|
1415
|
+
const visiblePrefix = truncateToWidth(prefix, width - contentWidth, "");
|
|
1416
|
+
const prefixWidth = visibleWidth(visiblePrefix);
|
|
1417
|
+
return hardWrapTerminalDocument(text, width - prefixWidth).map((line, index) => {
|
|
1418
|
+
const decoration = index === 0 ? visiblePrefix : " ".repeat(prefixWidth);
|
|
1419
|
+
const safePrefix = visibleWidth(decoration + line) <= width ? decoration : "";
|
|
1420
|
+
return prefixStyle(safePrefix) + style(line);
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
function boundedComponent(render) {
|
|
1424
|
+
return {
|
|
1425
|
+
render: (width) => Number.isFinite(width) && width >= 1 ? render(Math.floor(width)) : [],
|
|
1426
|
+
// Theme styles are evaluated on every render, so there is no cache to clear.
|
|
1427
|
+
invalidate() {
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
|
|
915
1432
|
// src/required-tools.ts
|
|
916
1433
|
var REQUIRED_PLAN_MODE_TOOL_NAMES = [PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
|
|
917
1434
|
function planModeHelperToolsAvailable(toolNames) {
|
|
@@ -1037,7 +1554,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
1037
1554
|
const loadInteractiveUi = () => {
|
|
1038
1555
|
if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
|
|
1039
1556
|
if (!interactiveUiPromise) {
|
|
1040
|
-
interactiveUiPromise = import("./chunks/interactive-ui-
|
|
1557
|
+
interactiveUiPromise = import("./chunks/interactive-ui-EMUWYNHT.ts").catch((error) => {
|
|
1041
1558
|
interactiveUiPromise = void 0;
|
|
1042
1559
|
throw error;
|
|
1043
1560
|
});
|
|
@@ -1054,6 +1571,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
1054
1571
|
let publishedContractMode;
|
|
1055
1572
|
let modeContractsRelevant = false;
|
|
1056
1573
|
let readyPresentationIntent;
|
|
1574
|
+
let readyMenuController = new AbortController();
|
|
1057
1575
|
let latestCommandContext;
|
|
1058
1576
|
let stagedFreshImplementation;
|
|
1059
1577
|
const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();
|
|
@@ -1070,6 +1588,26 @@ function planMode(pi, dependencies = {}) {
|
|
|
1070
1588
|
const implementationRetention = createImplementationRetentionCoordinator();
|
|
1071
1589
|
const finalizationRequest = createFinalizationRequestCoordinator();
|
|
1072
1590
|
const persistState = () => pi.appendEntry(STATE_ENTRY_TYPE, state);
|
|
1591
|
+
const interaction = createInteractionCoordinator(pi, {
|
|
1592
|
+
getState: () => state,
|
|
1593
|
+
setState: (next) => {
|
|
1594
|
+
state = next;
|
|
1595
|
+
},
|
|
1596
|
+
persistState,
|
|
1597
|
+
captureCurrent: (ctx) => {
|
|
1598
|
+
const session = ctx.sessionManager;
|
|
1599
|
+
const generation = workflowGeneration;
|
|
1600
|
+
const sessionGeneration = menuGeneration;
|
|
1601
|
+
const owner = workflowOwner;
|
|
1602
|
+
return () => currentSession === session && generation === workflowGeneration && sessionGeneration === menuGeneration && !menuController.signal.aborted && workflowMutex.isOwner(owner);
|
|
1603
|
+
},
|
|
1604
|
+
clearReadyIntent: () => {
|
|
1605
|
+
invalidateReadyMenu();
|
|
1606
|
+
readyPresentationIntent = readyPresentationIntent?.source === "legacy_proposed_plan" ? { ...readyPresentationIntent, showMenu: false } : void 0;
|
|
1607
|
+
},
|
|
1608
|
+
resetFinalization: () => finalizationRequest.reset(),
|
|
1609
|
+
updateUi
|
|
1610
|
+
});
|
|
1073
1611
|
const planExports = createPlanExportController({
|
|
1074
1612
|
getState: () => state,
|
|
1075
1613
|
getSettings: () => settings,
|
|
@@ -1096,6 +1634,9 @@ function planMode(pi, dependencies = {}) {
|
|
|
1096
1634
|
settings: showSettings,
|
|
1097
1635
|
save: savePlanForLater,
|
|
1098
1636
|
stay: updateUi,
|
|
1637
|
+
toggleInteraction: (ctx) => {
|
|
1638
|
+
interaction.toggle(ctx);
|
|
1639
|
+
},
|
|
1099
1640
|
exitReady: (ctx) => {
|
|
1100
1641
|
if (exitPlanMode(ctx)) {
|
|
1101
1642
|
ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
|
|
@@ -1110,7 +1651,9 @@ function planMode(pi, dependencies = {}) {
|
|
|
1110
1651
|
label: "Plan question",
|
|
1111
1652
|
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
1653
|
parameters: PLAN_MODE_QUESTION_PARAMS,
|
|
1113
|
-
|
|
1654
|
+
renderCall: renderPlanModeQuestionCall,
|
|
1655
|
+
renderResult: renderPlanModeQuestionResult,
|
|
1656
|
+
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
1114
1657
|
if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) {
|
|
1115
1658
|
return planModeQuestionCancelled(
|
|
1116
1659
|
[],
|
|
@@ -1123,6 +1666,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
1123
1666
|
return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
|
|
1124
1667
|
}
|
|
1125
1668
|
finalizationRequest.satisfy();
|
|
1669
|
+
if (interaction.questionsPaused()) return interaction.answer(toolCallId, parsed.questions, ctx, signal);
|
|
1126
1670
|
if (!ctx.hasUI) {
|
|
1127
1671
|
return planModeQuestionCancelled(
|
|
1128
1672
|
parsed.questions,
|
|
@@ -1130,13 +1674,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
1130
1674
|
"Unable to ask Plan-mode questions because interactive UI is not available."
|
|
1131
1675
|
);
|
|
1132
1676
|
}
|
|
1133
|
-
|
|
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
|
-
});
|
|
1677
|
+
return interaction.answer(toolCallId, parsed.questions, ctx, signal);
|
|
1140
1678
|
}
|
|
1141
1679
|
});
|
|
1142
1680
|
pi.registerTool({
|
|
@@ -1321,6 +1859,8 @@ function planMode(pi, dependencies = {}) {
|
|
|
1321
1859
|
}
|
|
1322
1860
|
};
|
|
1323
1861
|
pi.on("session_start", async (event, ctx) => {
|
|
1862
|
+
interaction.disposeSession();
|
|
1863
|
+
invalidateReadyMenu();
|
|
1324
1864
|
cancelDeferredFreshImplementation();
|
|
1325
1865
|
const generation = ++menuGeneration;
|
|
1326
1866
|
finalizationRequest.reset();
|
|
@@ -1346,6 +1886,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
1346
1886
|
await applyPlanModeSettings(generation, ctx, true);
|
|
1347
1887
|
if (generation !== menuGeneration || menuController.signal.aborted) return;
|
|
1348
1888
|
initializePlanModeShortcut();
|
|
1889
|
+
interaction.startSession(ctx, startupToggleShortcut);
|
|
1349
1890
|
startPlanModeSettingsWatch(generation);
|
|
1350
1891
|
if (!installRestoredState(restoredState, ctx)) return;
|
|
1351
1892
|
implementationRetention.restore(state.activeImplementation);
|
|
@@ -1363,7 +1904,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
1363
1904
|
return { cancel: true };
|
|
1364
1905
|
}
|
|
1365
1906
|
const target = ctx.sessionManager.getEntry(event.preparation.targetId);
|
|
1366
|
-
if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
|
|
1907
|
+
if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE && target.customType !== INTERACTION_CONTRACT_MESSAGE_TYPE) {
|
|
1367
1908
|
return;
|
|
1368
1909
|
}
|
|
1369
1910
|
if (ctx.hasUI) {
|
|
@@ -1407,6 +1948,12 @@ function planMode(pi, dependencies = {}) {
|
|
|
1407
1948
|
}
|
|
1408
1949
|
});
|
|
1409
1950
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1951
|
+
if (currentSession !== void 0 && currentSession !== ctx.sessionManager) {
|
|
1952
|
+
workflowMutex.unbindSession(ctx.sessionManager);
|
|
1953
|
+
return;
|
|
1954
|
+
}
|
|
1955
|
+
interaction.disposeSession();
|
|
1956
|
+
invalidateReadyMenu();
|
|
1410
1957
|
cancelDeferredFreshImplementation();
|
|
1411
1958
|
const shutdownSession = ctx.sessionManager;
|
|
1412
1959
|
const runtimeApplication = activeImplementationRuntimeApplication?.sessionManager === shutdownSession && activeImplementationRuntimeApplication.drainOnShutdown ? activeImplementationRuntimeApplication : void 0;
|
|
@@ -1534,8 +2081,17 @@ Blocked command: ${blocked}`
|
|
|
1534
2081
|
}
|
|
1535
2082
|
}
|
|
1536
2083
|
});
|
|
2084
|
+
pi.on("tool_execution_end", (event, ctx) => {
|
|
2085
|
+
interaction.toolExecutionEnd(event.toolCallId, ctx);
|
|
2086
|
+
});
|
|
2087
|
+
pi.on("ui_prompt_start", (_event, ctx) => {
|
|
2088
|
+
interaction.promptChanged(true, ctx);
|
|
2089
|
+
});
|
|
2090
|
+
pi.on("ui_prompt_end", (_event, ctx) => {
|
|
2091
|
+
interaction.promptChanged(false, ctx);
|
|
2092
|
+
});
|
|
1537
2093
|
pi.on("message_start", (event) => {
|
|
1538
|
-
if (state.enabled && event.message.role === "user" && messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT) {
|
|
2094
|
+
if (state.enabled && interaction.mode() === "questions" && event.message.role === "user" && messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT) {
|
|
1539
2095
|
finalizationRequest.request(workflowGeneration);
|
|
1540
2096
|
}
|
|
1541
2097
|
});
|
|
@@ -1546,7 +2102,7 @@ Blocked command: ${blocked}`
|
|
|
1546
2102
|
clearActiveImplementation(result.clearActiveImplementationId, ctx);
|
|
1547
2103
|
}
|
|
1548
2104
|
const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
|
|
1549
|
-
return { messages };
|
|
2105
|
+
return { messages: interaction.transformContext(messages, ctx) };
|
|
1550
2106
|
});
|
|
1551
2107
|
pi.on("input", async (event, ctx) => {
|
|
1552
2108
|
refreshStateForFirstPrompt(ctx);
|
|
@@ -1583,6 +2139,7 @@ Blocked command: ${blocked}`
|
|
|
1583
2139
|
refreshStateForFirstPrompt(ctx);
|
|
1584
2140
|
if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
|
|
1585
2141
|
if (state.latestPlan || state.awaitingAction) {
|
|
2142
|
+
invalidateReadyMenu();
|
|
1586
2143
|
cancelDeferredFreshImplementation();
|
|
1587
2144
|
readyPresentationIntent = void 0;
|
|
1588
2145
|
state = {
|
|
@@ -1600,7 +2157,9 @@ Blocked command: ${blocked}`
|
|
|
1600
2157
|
const text = latestAssistantText(event.messages);
|
|
1601
2158
|
const parsedPlan = parseProposedPlan(text);
|
|
1602
2159
|
if (parsedPlan.kind !== "valid") {
|
|
1603
|
-
|
|
2160
|
+
if (interaction.mode() === "questions") {
|
|
2161
|
+
finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
|
|
2162
|
+
}
|
|
1604
2163
|
if (parsedPlan.kind !== "absent") {
|
|
1605
2164
|
ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
|
|
1606
2165
|
}
|
|
@@ -1613,7 +2172,7 @@ Blocked command: ${blocked}`
|
|
|
1613
2172
|
pi.on("agent_settled", async (_event, ctx) => {
|
|
1614
2173
|
const settledImplementationId = implementationRetention.implementationSettled(state.activeImplementation);
|
|
1615
2174
|
if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
|
|
1616
|
-
if (finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
|
|
2175
|
+
if (interaction.mode() === "questions" && finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
|
|
1617
2176
|
if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
|
|
1618
2177
|
const action = finalizationRequest.settle(workflowGeneration);
|
|
1619
2178
|
if (action === "retry") {
|
|
@@ -1645,8 +2204,12 @@ ${intent.plan}`,
|
|
|
1645
2204
|
{ triggerTurn: false }
|
|
1646
2205
|
);
|
|
1647
2206
|
}
|
|
1648
|
-
if (ctx.hasUI && completedPlanIsCurrent(intent)) {
|
|
1649
|
-
|
|
2207
|
+
if (intent.showMenu && ctx.hasUI && completedPlanIsCurrent(intent)) {
|
|
2208
|
+
const controller = readyMenuController;
|
|
2209
|
+
await planActions.showReady(latestCommandContext ?? ctx, {
|
|
2210
|
+
signal: controller.signal,
|
|
2211
|
+
isCurrent: () => completedPlanIsCurrent(intent) && interaction.mode() === "questions"
|
|
2212
|
+
});
|
|
1650
2213
|
}
|
|
1651
2214
|
const request = stagedFreshImplementation;
|
|
1652
2215
|
stagedFreshImplementation = void 0;
|
|
@@ -1680,6 +2243,7 @@ ${intent.plan}`,
|
|
|
1680
2243
|
state = {
|
|
1681
2244
|
...state,
|
|
1682
2245
|
enabled: true,
|
|
2246
|
+
interactionMode: "questions",
|
|
1683
2247
|
awaitingAction: false,
|
|
1684
2248
|
savedPlan: void 0,
|
|
1685
2249
|
activeImplementation: void 0,
|
|
@@ -1690,6 +2254,7 @@ ${intent.plan}`,
|
|
|
1690
2254
|
beginWorkflowToolPolicy();
|
|
1691
2255
|
applyPlanThinkingLevel();
|
|
1692
2256
|
persistState();
|
|
2257
|
+
interaction.publish("questions");
|
|
1693
2258
|
updateUi(ctx);
|
|
1694
2259
|
return true;
|
|
1695
2260
|
} catch (error) {
|
|
@@ -1721,6 +2286,7 @@ ${intent.plan}`,
|
|
|
1721
2286
|
state = {
|
|
1722
2287
|
...state,
|
|
1723
2288
|
enabled: false,
|
|
2289
|
+
interactionMode: void 0,
|
|
1724
2290
|
latestPlan: void 0,
|
|
1725
2291
|
latestPlanSource: void 0,
|
|
1726
2292
|
awaitingAction: false,
|
|
@@ -1782,20 +2348,27 @@ ${intent.plan}`,
|
|
|
1782
2348
|
if (state.enabled && state.awaitingAction && state.latestPlan === normalized.plan && state.latestPlanSource === source) {
|
|
1783
2349
|
return;
|
|
1784
2350
|
}
|
|
2351
|
+
invalidateReadyMenu();
|
|
1785
2352
|
state = {
|
|
1786
2353
|
...state,
|
|
1787
2354
|
latestPlan: normalized.plan,
|
|
1788
2355
|
latestPlanSource: source,
|
|
1789
2356
|
awaitingAction: true
|
|
1790
2357
|
};
|
|
1791
|
-
|
|
2358
|
+
const showMenu = interaction.mode() === "questions";
|
|
2359
|
+
readyPresentationIntent = showMenu || source === "legacy_proposed_plan" ? {
|
|
1792
2360
|
nonce: ++nextReadyPresentationNonce,
|
|
1793
2361
|
plan: normalized.plan,
|
|
1794
|
-
source
|
|
1795
|
-
|
|
2362
|
+
source,
|
|
2363
|
+
showMenu
|
|
2364
|
+
} : void 0;
|
|
1796
2365
|
persistState();
|
|
1797
2366
|
updateUi(ctx);
|
|
1798
2367
|
}
|
|
2368
|
+
function invalidateReadyMenu() {
|
|
2369
|
+
readyMenuController.abort(new DOMException("Plan presentation superseded", "AbortError"));
|
|
2370
|
+
readyMenuController = new AbortController();
|
|
2371
|
+
}
|
|
1799
2372
|
function completedPlanIsCurrent(intent) {
|
|
1800
2373
|
return state.enabled && workflowMutex.isOwner(workflowOwner) && state.awaitingAction && state.latestPlan === intent.plan && state.latestPlanSource === intent.source;
|
|
1801
2374
|
}
|
|
@@ -1821,6 +2394,11 @@ ${intent.plan}`,
|
|
|
1821
2394
|
ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
|
|
1822
2395
|
return;
|
|
1823
2396
|
}
|
|
2397
|
+
if (interaction.mode() === "discussion") {
|
|
2398
|
+
finalizationRequest.reset();
|
|
2399
|
+
sendPlanModeUserMessage(DISCUSSION_FINALIZE_PLAN_PROMPT, ctx);
|
|
2400
|
+
return;
|
|
2401
|
+
}
|
|
1824
2402
|
finalizationRequest.request(workflowGeneration);
|
|
1825
2403
|
if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
|
|
1826
2404
|
}
|
|
@@ -1841,6 +2419,7 @@ ${intent.plan}`,
|
|
|
1841
2419
|
state = {
|
|
1842
2420
|
...state,
|
|
1843
2421
|
enabled: false,
|
|
2422
|
+
interactionMode: void 0,
|
|
1844
2423
|
latestPlan: void 0,
|
|
1845
2424
|
latestPlanSource: void 0,
|
|
1846
2425
|
awaitingAction: false,
|
|
@@ -1957,6 +2536,7 @@ ${intent.plan}`,
|
|
|
1957
2536
|
state = {
|
|
1958
2537
|
...state,
|
|
1959
2538
|
enabled: false,
|
|
2539
|
+
interactionMode: void 0,
|
|
1960
2540
|
latestPlan: void 0,
|
|
1961
2541
|
latestPlanSource: void 0,
|
|
1962
2542
|
awaitingAction: false,
|
|
@@ -1986,6 +2566,7 @@ ${intent.plan}`,
|
|
|
1986
2566
|
if (wasEnabled) {
|
|
1987
2567
|
restoreWorkflowToolPolicy(state.workflowToolPolicy);
|
|
1988
2568
|
publishModeContract("plan", ctx);
|
|
2569
|
+
interaction.publish(interaction.mode());
|
|
1989
2570
|
applyPlanThinkingLevel();
|
|
1990
2571
|
}
|
|
1991
2572
|
persistState();
|
|
@@ -2133,6 +2714,8 @@ ${intent.plan}`,
|
|
|
2133
2714
|
return false;
|
|
2134
2715
|
}
|
|
2135
2716
|
function advanceWorkflowGeneration() {
|
|
2717
|
+
interaction.reset();
|
|
2718
|
+
invalidateReadyMenu();
|
|
2136
2719
|
cancelDeferredFreshImplementation();
|
|
2137
2720
|
workflowGeneration += 1;
|
|
2138
2721
|
pendingWorkflowToolPolicy = void 0;
|
|
@@ -2562,6 +3145,7 @@ ${intent.plan}`,
|
|
|
2562
3145
|
}
|
|
2563
3146
|
function rollbackNewActivation(previousState, ctx, previousOwner) {
|
|
2564
3147
|
const activatedOwner = workflowOwner;
|
|
3148
|
+
interaction.reset();
|
|
2565
3149
|
readyPresentationIntent = void 0;
|
|
2566
3150
|
try {
|
|
2567
3151
|
if (state.enabled) {
|
|
@@ -2622,7 +3206,7 @@ ${intent.plan}`,
|
|
|
2622
3206
|
return false;
|
|
2623
3207
|
}
|
|
2624
3208
|
function updateUi(ctx) {
|
|
2625
|
-
updatePlanModeUi(ctx, state, formatToolSummary);
|
|
3209
|
+
updatePlanModeUi(ctx, state, formatToolSummary, interaction.shortcutLabel(ctx));
|
|
2626
3210
|
}
|
|
2627
3211
|
function clearUi(ctx) {
|
|
2628
3212
|
clearPlanModeUi(ctx);
|