@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
|
@@ -25,10 +25,40 @@ Reopen the selector to refresh newly registered tools.
|
|
|
25
25
|
Active and ready workflows lock tools and settings; exit and start a new workflow to change the allowlist.
|
|
26
26
|
See [Planning and implementation](../README.md#-planning-and-implementation) for the first-request policy boundary, completion, and same-session versus fresh-session handoff.
|
|
27
27
|
|
|
28
|
+
## Questionnaires and free discussion
|
|
29
|
+
|
|
30
|
+
Every new Plan workflow starts with questionnaires enabled.
|
|
31
|
+
In TUI, F2 switches the active workflow between questionnaires and free discussion only while the main editor is idle or that workflow's questionnaire is open.
|
|
32
|
+
It does not leave Plan mode or change its tool policy: file edits and unsafe shell forms remain blocked.
|
|
33
|
+
If any effective native Pi keybinding uses F2, Plan mode does not register or display F2 and does not choose a replacement key.
|
|
34
|
+
Use **Switch to free discussion** or **Enable questionnaires** in the active `/plan` menu instead, including when a completed plan is ready.
|
|
35
|
+
The widget shows F2 only when available, otherwise the `/plan` entry point.
|
|
36
|
+
The existing `toggleShortcut` setting still controls entry to and exit from Plan mode, not this interaction switch.
|
|
37
|
+
|
|
38
|
+
Switching from an open questionnaire closes it, discards every unfinished answer, custom answer, and note, and stops its run's automatic continuation.
|
|
39
|
+
The main prompt draft stays unchanged; no questionnaire content is copied into it and no message is sent.
|
|
40
|
+
Free discussion permits plain-text follow-up questions and ordinary text responses without opening questionnaires.
|
|
41
|
+
The agent cannot enable questionnaires itself.
|
|
42
|
+
Enabling them again changes only the interaction mode: it does not call the model, reopen old questions, or open a previously suppressed ready menu.
|
|
43
|
+
After the next user message, the agent decides whether new questions are needed from the latest discussion.
|
|
44
|
+
|
|
45
|
+
A completed plan in discussion is displayed and stored with `plan ready`, while the widget continues to show free discussion.
|
|
46
|
+
No automatic action menu takes focus; open `/plan` manually to implement, save, export, revise, or exit.
|
|
47
|
+
Further discussion uses the existing plan revision flow.
|
|
48
|
+
`/plan finalize` can complete the plan or ask a material question in plain text without the structured-tool retry used when questionnaires are enabled.
|
|
49
|
+
The interaction mode restores with its active workflow after reload, resume, branch navigation, and compaction; old sessions without this state use questionnaires.
|
|
50
|
+
Leaving, saving, or handing off the plan does not carry discussion mode into the next workflow.
|
|
51
|
+
|
|
52
|
+
RPC uses the same active `/plan` menu while idle; it does not receive the TUI F2 shortcut.
|
|
53
|
+
RPC questionnaire cancellation keeps its existing behavior and does not switch interaction mode.
|
|
54
|
+
Other running work and unrelated dialogs do not accept the toggle.
|
|
55
|
+
Print and JSON modes do not add interactive UI or an interaction-switch route.
|
|
56
|
+
|
|
28
57
|
## Busy transitions and recovery
|
|
29
58
|
|
|
30
59
|
Wait for Pi's run to settle before starting, exiting, saving, exporting a ready plan, implementing, or using another state-changing menu action or configured shortcut.
|
|
31
60
|
Busy transitions leave state unchanged and report a warning in TUI/RPC or an error in print/JSON mode.
|
|
61
|
+
The scoped F2 switch inside the current questionnaire is the only interaction-switch exception described above.
|
|
32
62
|
An ordinary follow-up or `/plan finalize` can still run while Plan mode is active because neither changes its mode contract.
|
|
33
63
|
|
|
34
64
|
`show`, `save`, `export`, and `implement` require an applicable stored plan; `finalize` requires active Plan mode.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-plan-mode",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.60.0",
|
|
4
4
|
"description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"dist",
|
|
18
18
|
"docs",
|
|
19
19
|
"README.md",
|
|
20
|
+
"CHANGELOG.md",
|
|
20
21
|
"LICENSE"
|
|
21
22
|
],
|
|
22
23
|
"pi": {
|
|
@@ -36,8 +37,8 @@
|
|
|
36
37
|
"@earendil-works/pi-tui": "*"
|
|
37
38
|
},
|
|
38
39
|
"devDependencies": {
|
|
39
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
40
|
-
"@earendil-works/pi-tui": "1.
|
|
40
|
+
"@earendil-works/pi-coding-agent": "1.5.0",
|
|
41
|
+
"@earendil-works/pi-tui": "1.5.0",
|
|
41
42
|
"esbuild": "0.28.2",
|
|
42
43
|
"typescript": "7.0.2"
|
|
43
44
|
},
|
|
@@ -47,6 +48,6 @@
|
|
|
47
48
|
"directory": "packages/pi-plan-mode"
|
|
48
49
|
},
|
|
49
50
|
"dependencies": {
|
|
50
|
-
"@narumitw/pi-tui-kit": "^0.
|
|
51
|
+
"@narumitw/pi-tui-kit": "^0.69.1"
|
|
51
52
|
}
|
|
52
53
|
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export const FINALIZE_PLAN_PROMPT =
|
|
2
2
|
"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.";
|
|
3
3
|
|
|
4
|
+
export const DISCUSSION_FINALIZE_PLAN_PROMPT =
|
|
5
|
+
"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.";
|
|
6
|
+
|
|
4
7
|
export const RETRY_FINALIZE_PLAN_PROMPT =
|
|
5
8
|
"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.";
|
|
6
9
|
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { modeContractFromMessage } from "./mode-contract.js";
|
|
2
|
+
|
|
3
|
+
export type PlanInteractionMode = "questions" | "discussion";
|
|
4
|
+
|
|
5
|
+
export const INTERACTION_CONTRACT_MESSAGE_TYPE = "plan-mode-interaction";
|
|
6
|
+
const INTERACTION_CONTRACT_VERSION = 1;
|
|
7
|
+
|
|
8
|
+
const CONTRACTS: Record<PlanInteractionMode, string> = {
|
|
9
|
+
questions: `[PI PLAN MODE INTERACTION CONTRACT v1: QUESTIONS]
|
|
10
|
+
Plan Mode remains active with all read-only restrictions unchanged. Do not edit files, perform mutating actions, or implement the plan.
|
|
11
|
+
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.
|
|
12
|
+
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.
|
|
13
|
+
Only the user can change this interaction mode.`,
|
|
14
|
+
discussion: `[PI PLAN MODE INTERACTION CONTRACT v1: DISCUSSION]
|
|
15
|
+
Plan Mode remains active with all read-only restrictions unchanged. Do not edit files, perform mutating actions, or implement the plan.
|
|
16
|
+
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.
|
|
17
|
+
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.
|
|
18
|
+
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.`,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export function createInteractionContractMessage(mode: PlanInteractionMode, timestamp = Date.now()) {
|
|
22
|
+
return {
|
|
23
|
+
role: "custom" as const,
|
|
24
|
+
customType: INTERACTION_CONTRACT_MESSAGE_TYPE,
|
|
25
|
+
content: CONTRACTS[mode],
|
|
26
|
+
display: false,
|
|
27
|
+
details: { version: INTERACTION_CONTRACT_VERSION, mode },
|
|
28
|
+
timestamp,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function interactionContractFromMessage(message: unknown): PlanInteractionMode | undefined {
|
|
33
|
+
const candidate = customMessage(message);
|
|
34
|
+
if (candidate?.customType !== INTERACTION_CONTRACT_MESSAGE_TYPE || candidate.display !== false) return undefined;
|
|
35
|
+
const details = candidate.details;
|
|
36
|
+
if (!isRecord(details) || details.version !== INTERACTION_CONTRACT_VERSION) return undefined;
|
|
37
|
+
const mode = details.mode;
|
|
38
|
+
if (mode !== "questions" && mode !== "discussion") return undefined;
|
|
39
|
+
return candidate.content === CONTRACTS[mode] ? mode : undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function latestInteractionContract(
|
|
43
|
+
messages: readonly unknown[],
|
|
44
|
+
): { index: number; mode: PlanInteractionMode } | undefined {
|
|
45
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
46
|
+
const message = messages[index];
|
|
47
|
+
const mode = interactionContractFromMessage(message);
|
|
48
|
+
if (mode) return { index, mode };
|
|
49
|
+
// Both transitions start a new boundary. Never inherit another workflow's interaction.
|
|
50
|
+
if (modeContractFromMessage(customMessage(message))) return undefined;
|
|
51
|
+
}
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The caller owns enabled-state checks and durable publication of this fallback.
|
|
56
|
+
export function reconcileInteractionContract(messages: unknown[], expected: PlanInteractionMode): unknown[] {
|
|
57
|
+
if (latestInteractionContract(messages)?.mode === expected) return messages;
|
|
58
|
+
return [...messages, createInteractionContractMessage(expected, 0)];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Match Pi's context-producing custom messages, not state entries or user/tool text.
|
|
62
|
+
function customMessage(value: unknown): Record<string, unknown> | undefined {
|
|
63
|
+
if (!isRecord(value)) return undefined;
|
|
64
|
+
if (value.type === "custom_message") return value;
|
|
65
|
+
if (value.type === "message") {
|
|
66
|
+
return isRecord(value.message) && value.message.role === "custom" ? value.message : undefined;
|
|
67
|
+
}
|
|
68
|
+
return value.type === undefined && value.role === "custom" ? value : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
72
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
73
|
+
}
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext, TerminalInputHandler } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { getKeybindings, isKeyRelease, isKeyRepeat, type KeyId, matchesKey } from "@earendil-works/pi-tui";
|
|
4
|
+
import {
|
|
5
|
+
createInteractionContractMessage,
|
|
6
|
+
interactionContractFromMessage,
|
|
7
|
+
latestInteractionContract,
|
|
8
|
+
type PlanInteractionMode,
|
|
9
|
+
} from "./interaction-contract.js";
|
|
10
|
+
import { answerPlanModeQuestions, type PlanModeQuestion, planModeQuestionCancelled } from "./question-tool.js";
|
|
11
|
+
import type { PlanInteractionRestoration, PlanModeState } from "./state.js";
|
|
12
|
+
|
|
13
|
+
const F2_INPUTS = ["\u001bOQ", "\u001b[12~", "\u001b[[B", "\u001b[1;1Q", "\u001b[12;1~", "\u001b[-22;1u"];
|
|
14
|
+
const PASTE_START = "\u001b[200~";
|
|
15
|
+
const PASTE_END = "\u001b[201~";
|
|
16
|
+
|
|
17
|
+
interface InteractionDependencies {
|
|
18
|
+
getState(): PlanModeState;
|
|
19
|
+
setState(state: PlanModeState): void;
|
|
20
|
+
persistState(): void;
|
|
21
|
+
captureCurrent(ctx: ExtensionContext): () => boolean;
|
|
22
|
+
clearReadyIntent(): void;
|
|
23
|
+
resetFinalization(): void;
|
|
24
|
+
updateUi(ctx: ExtensionContext): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface QuestionInteraction {
|
|
28
|
+
toolCallId: string;
|
|
29
|
+
sessionManager: ExtensionContext["sessionManager"];
|
|
30
|
+
isCurrent(): boolean;
|
|
31
|
+
controller: AbortController;
|
|
32
|
+
discussionRequested: boolean;
|
|
33
|
+
unsubscribe(): void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface ContextBoundary {
|
|
37
|
+
length: number;
|
|
38
|
+
hash: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type Contract = ReturnType<typeof createInteractionContractMessage>;
|
|
42
|
+
|
|
43
|
+
/** Fixed F2 has no modifier aliases; probe every legacy and enhanced matcher branch. */
|
|
44
|
+
export function interactionShortcutAvailable(bindings: Record<string, unknown>, otherShortcut?: string) {
|
|
45
|
+
const reserved = [
|
|
46
|
+
...Object.values(bindings).flatMap((value) => (Array.isArray(value) ? value : [value])),
|
|
47
|
+
otherShortcut,
|
|
48
|
+
];
|
|
49
|
+
return !reserved.some(
|
|
50
|
+
(key) =>
|
|
51
|
+
typeof key === "string" && F2_INPUTS.some((input) => matchesKey(input, "f2") && matchesKey(input, key as KeyId)),
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Track paste markers across raw input fragments without modifying any editor input. */
|
|
56
|
+
export function createInteractionInputGuard() {
|
|
57
|
+
let pasting = false;
|
|
58
|
+
let suffix = "";
|
|
59
|
+
return (data: string) => {
|
|
60
|
+
const text = suffix + data;
|
|
61
|
+
const wasPasting = pasting;
|
|
62
|
+
let markerSeen = false;
|
|
63
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
64
|
+
if (text.startsWith(PASTE_START, index)) {
|
|
65
|
+
pasting = true;
|
|
66
|
+
markerSeen = true;
|
|
67
|
+
index += PASTE_START.length - 1;
|
|
68
|
+
} else if (text.startsWith(PASTE_END, index)) {
|
|
69
|
+
pasting = false;
|
|
70
|
+
markerSeen = true;
|
|
71
|
+
index += PASTE_END.length - 1;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
suffix = "";
|
|
75
|
+
for (let length = 1; length < PASTE_START.length && length <= text.length; length += 1) {
|
|
76
|
+
const candidate = text.slice(-length);
|
|
77
|
+
if (PASTE_START.startsWith(candidate) || PASTE_END.startsWith(candidate)) suffix = candidate;
|
|
78
|
+
}
|
|
79
|
+
return !wasPasting && !pasting && !markerSeen && !suffix && !isKeyRelease(data) && !isKeyRepeat(data);
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Own questionnaire cancellation and interaction transitions, not Plan workflow admission. */
|
|
84
|
+
export function createInteractionCoordinator(pi: ExtensionAPI, dependencies: InteractionDependencies) {
|
|
85
|
+
const questions = new Set<QuestionInteraction>();
|
|
86
|
+
const pendingAborts = new Map<string, QuestionInteraction>();
|
|
87
|
+
let shortcutInitialized = false;
|
|
88
|
+
let shortcutRegistered = false;
|
|
89
|
+
let removeSessionInput = () => {};
|
|
90
|
+
let mainShortcutAllowed = true;
|
|
91
|
+
let promptOpen = false;
|
|
92
|
+
let failed = false;
|
|
93
|
+
|
|
94
|
+
function mode(): PlanInteractionMode {
|
|
95
|
+
return dependencies.getState().interactionMode === "discussion" ? "discussion" : "questions";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function publish(nextMode: PlanInteractionMode) {
|
|
99
|
+
const { role: _role, timestamp: _timestamp, ...message } = createInteractionContractMessage(nextMode);
|
|
100
|
+
pi.sendMessage(message, { triggerTurn: false });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function report(ctx: ExtensionContext, text: string) {
|
|
104
|
+
if (ctx.hasUI) ctx.ui.notify(text, "error");
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function cancelQuestions() {
|
|
108
|
+
for (const question of questions) {
|
|
109
|
+
question.unsubscribe();
|
|
110
|
+
question.controller.abort(new DOMException("Plan question owner changed", "AbortError"));
|
|
111
|
+
}
|
|
112
|
+
questions.clear();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function reset() {
|
|
116
|
+
cancelQuestions();
|
|
117
|
+
pendingAborts.clear();
|
|
118
|
+
failed = false;
|
|
119
|
+
mainShortcutAllowed = true;
|
|
120
|
+
promptOpen = false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function failClosed(ctx: ExtensionContext) {
|
|
124
|
+
failed = true;
|
|
125
|
+
dependencies.resetFinalization();
|
|
126
|
+
dependencies.clearReadyIntent();
|
|
127
|
+
cancelQuestions();
|
|
128
|
+
ctx.abort();
|
|
129
|
+
report(
|
|
130
|
+
ctx,
|
|
131
|
+
"Plan interaction state could not be recovered. Questionnaires are blocked; run /reload before continuing.",
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function toggle(ctx: ExtensionContext): boolean {
|
|
136
|
+
const isCurrent = dependencies.captureCurrent(ctx);
|
|
137
|
+
if (!isCurrent() || !dependencies.getState().enabled) return false;
|
|
138
|
+
if (failed) {
|
|
139
|
+
report(ctx, "Questionnaires are blocked after a failed interaction transition. Run /reload before continuing.");
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
const currentQuestions = [...questions].filter((question) => question.isCurrent());
|
|
143
|
+
if (!ctx.isIdle() && (ctx.mode !== "tui" || currentQuestions.length === 0)) {
|
|
144
|
+
if (ctx.hasUI)
|
|
145
|
+
ctx.ui.notify("Wait for the agent run to settle before changing Plan interaction mode.", "warning");
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
const previousState = dependencies.getState();
|
|
149
|
+
const previousMode = mode();
|
|
150
|
+
const nextMode = previousMode === "questions" ? "discussion" : "questions";
|
|
151
|
+
try {
|
|
152
|
+
dependencies.setState({ ...previousState, interactionMode: nextMode });
|
|
153
|
+
dependencies.persistState();
|
|
154
|
+
publish(nextMode);
|
|
155
|
+
} catch {
|
|
156
|
+
dependencies.setState(previousState);
|
|
157
|
+
try {
|
|
158
|
+
dependencies.persistState();
|
|
159
|
+
publish(previousMode);
|
|
160
|
+
} catch {
|
|
161
|
+
failClosed(ctx);
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
report(ctx, "Unable to change Plan interaction mode. The previous mode and questionnaire are unchanged.");
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
if (!isCurrent()) return false;
|
|
168
|
+
dependencies.resetFinalization();
|
|
169
|
+
dependencies.clearReadyIntent();
|
|
170
|
+
if (nextMode === "discussion") {
|
|
171
|
+
for (const question of currentQuestions) {
|
|
172
|
+
question.discussionRequested = true;
|
|
173
|
+
pendingAborts.set(question.toolCallId, question);
|
|
174
|
+
question.unsubscribe();
|
|
175
|
+
question.controller.abort(new DOMException("Free discussion requested", "AbortError"));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
dependencies.updateUi(ctx);
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
mode,
|
|
184
|
+
publish,
|
|
185
|
+
toggle,
|
|
186
|
+
reset,
|
|
187
|
+
questionsPaused: () => failed || mode() === "discussion",
|
|
188
|
+
shortcutLabel: (ctx: ExtensionContext) =>
|
|
189
|
+
ctx.mode === "tui" &&
|
|
190
|
+
shortcutRegistered &&
|
|
191
|
+
(!promptOpen || [...questions].some((question) => question.isCurrent()))
|
|
192
|
+
? "F2"
|
|
193
|
+
: undefined,
|
|
194
|
+
promptChanged(open: boolean, ctx: ExtensionContext) {
|
|
195
|
+
if (!dependencies.captureCurrent(ctx)()) return;
|
|
196
|
+
promptOpen = open;
|
|
197
|
+
dependencies.updateUi(ctx);
|
|
198
|
+
},
|
|
199
|
+
startSession(ctx: ExtensionContext, otherShortcut?: string) {
|
|
200
|
+
removeSessionInput();
|
|
201
|
+
removeSessionInput = () => {};
|
|
202
|
+
if (!shortcutInitialized) {
|
|
203
|
+
shortcutInitialized = true;
|
|
204
|
+
if (ctx.mode === "tui") {
|
|
205
|
+
try {
|
|
206
|
+
// No custom component owns this startup callback, so use Pi's public host registry.
|
|
207
|
+
shortcutRegistered = interactionShortcutAvailable(getKeybindings().getResolvedBindings(), otherShortcut);
|
|
208
|
+
} catch {
|
|
209
|
+
shortcutRegistered = false;
|
|
210
|
+
}
|
|
211
|
+
if (shortcutRegistered) {
|
|
212
|
+
pi.registerShortcut("f2", {
|
|
213
|
+
description: "Toggle Plan questionnaires and free discussion",
|
|
214
|
+
handler: (shortcutCtx) => {
|
|
215
|
+
if (mainShortcutAllowed && !promptOpen) toggle(shortcutCtx);
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (ctx.mode === "tui" && shortcutRegistered) {
|
|
222
|
+
const permitsInput = createInteractionInputGuard();
|
|
223
|
+
// Pi dispatches registered shortcuts before Editor input. Observe paste state first
|
|
224
|
+
// and consume repeat/release events so holding F2 cannot toggle twice.
|
|
225
|
+
removeSessionInput = ctx.ui.onTerminalInput((data) => {
|
|
226
|
+
mainShortcutAllowed = permitsInput(data);
|
|
227
|
+
const ownsInput =
|
|
228
|
+
dependencies.getState().enabled && (!promptOpen || [...questions].some((question) => question.isCurrent()));
|
|
229
|
+
if (ownsInput && matchesKey(data, "f2") && (isKeyRelease(data) || isKeyRepeat(data)))
|
|
230
|
+
return { consume: true };
|
|
231
|
+
return undefined;
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
disposeSession() {
|
|
236
|
+
removeSessionInput();
|
|
237
|
+
removeSessionInput = () => {};
|
|
238
|
+
reset();
|
|
239
|
+
},
|
|
240
|
+
async answer(toolCallId: string, values: PlanModeQuestion[], ctx: ExtensionContext, signal?: AbortSignal) {
|
|
241
|
+
if (failed || mode() === "discussion") {
|
|
242
|
+
return planModeQuestionCancelled(
|
|
243
|
+
values,
|
|
244
|
+
"questions_paused",
|
|
245
|
+
"Questionnaires are paused. Continue in plain text; only the user can enable questionnaires.",
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
const isCurrent = dependencies.captureCurrent(ctx);
|
|
249
|
+
const controller = new AbortController();
|
|
250
|
+
const signals = [controller.signal, signal, ctx.signal].filter(
|
|
251
|
+
(value): value is AbortSignal => value !== undefined,
|
|
252
|
+
);
|
|
253
|
+
const question: QuestionInteraction = {
|
|
254
|
+
toolCallId,
|
|
255
|
+
sessionManager: ctx.sessionManager,
|
|
256
|
+
isCurrent,
|
|
257
|
+
controller,
|
|
258
|
+
discussionRequested: false,
|
|
259
|
+
unsubscribe: () => {},
|
|
260
|
+
};
|
|
261
|
+
questions.add(question);
|
|
262
|
+
try {
|
|
263
|
+
if (ctx.mode === "tui" && shortcutRegistered) {
|
|
264
|
+
const permitsInput = createInteractionInputGuard();
|
|
265
|
+
const listener: TerminalInputHandler = (data) => {
|
|
266
|
+
if (!permitsInput(data) || !matchesKey(data, "f2") || !isCurrent()) return undefined;
|
|
267
|
+
toggle(ctx);
|
|
268
|
+
return { consume: true };
|
|
269
|
+
};
|
|
270
|
+
question.unsubscribe = ctx.ui.onTerminalInput(listener);
|
|
271
|
+
}
|
|
272
|
+
return await answerPlanModeQuestions(values, ctx, {
|
|
273
|
+
isCurrent,
|
|
274
|
+
isEnabled: () => dependencies.getState().enabled,
|
|
275
|
+
signal: AbortSignal.any(signals),
|
|
276
|
+
discussionRequested: () => question.discussionRequested,
|
|
277
|
+
});
|
|
278
|
+
} finally {
|
|
279
|
+
question.unsubscribe();
|
|
280
|
+
controller.abort(new DOMException("Plan question completed", "AbortError"));
|
|
281
|
+
questions.delete(question);
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
toolExecutionEnd(toolCallId: string, ctx: ExtensionContext) {
|
|
285
|
+
const question = pendingAborts.get(toolCallId);
|
|
286
|
+
if (!question) return;
|
|
287
|
+
pendingAborts.delete(toolCallId);
|
|
288
|
+
if (question.sessionManager !== ctx.sessionManager || !question.isCurrent()) return;
|
|
289
|
+
// terminate alone does not stop mixed parallel batches or nested callers.
|
|
290
|
+
pendingAborts.clear();
|
|
291
|
+
ctx.abort();
|
|
292
|
+
},
|
|
293
|
+
transformContext(messages: unknown[], ctx: ExtensionContext): unknown[] {
|
|
294
|
+
// Previously visible contracts remain part of the prefix after later mode
|
|
295
|
+
// changes and exits, even when their fire-and-forget publication was lost.
|
|
296
|
+
const anchored = restoreInteractionHistory(messages, dependencies.getState().interactionRestorations ?? []);
|
|
297
|
+
if (!dependencies.getState().enabled) return anchored;
|
|
298
|
+
const expected = mode();
|
|
299
|
+
if (latestInteractionContract(anchored)?.mode === expected) return anchored;
|
|
300
|
+
const boundary = { length: anchored.length, hash: contextHash(anchored) };
|
|
301
|
+
const canonical = createInteractionContractMessage(expected, 0);
|
|
302
|
+
const message = { ...canonical, details: { ...canonical.details, contextBoundary: boundary } };
|
|
303
|
+
const previousState = dependencies.getState();
|
|
304
|
+
try {
|
|
305
|
+
// sendMessage is fire-and-forget: Pi reports asynchronous failures separately.
|
|
306
|
+
// The synchronous state entry, not that void call, owns this required contract
|
|
307
|
+
// and its first model-visible boundary, including after reload.
|
|
308
|
+
dependencies.setState({
|
|
309
|
+
...previousState,
|
|
310
|
+
interactionRestorations: [
|
|
311
|
+
...(previousState.interactionRestorations ?? []),
|
|
312
|
+
{ version: 1, mode: expected, boundary },
|
|
313
|
+
],
|
|
314
|
+
});
|
|
315
|
+
dependencies.persistState();
|
|
316
|
+
const { role: _role, timestamp: _timestamp, ...persisted } = message;
|
|
317
|
+
pi.sendMessage(persisted, { triggerTurn: false });
|
|
318
|
+
} catch {
|
|
319
|
+
dependencies.setState(previousState);
|
|
320
|
+
failClosed(ctx);
|
|
321
|
+
}
|
|
322
|
+
return [...anchored, message];
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function contextHash(messages: unknown[]): string {
|
|
328
|
+
return createHash("sha256").update(JSON.stringify(messages)).digest("hex");
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function boundaryMatches(messages: unknown[], boundary: ContextBoundary): boolean {
|
|
332
|
+
return boundary.length <= messages.length && contextHash(messages.slice(0, boundary.length)) === boundary.hash;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function insertAtBoundary(messages: unknown[], message: Contract, index: number) {
|
|
336
|
+
return [...messages.slice(0, index), message, ...messages.slice(index)];
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function restorationFromMessage(value: unknown): PlanInteractionRestoration | undefined {
|
|
340
|
+
const mode = interactionContractFromMessage(value);
|
|
341
|
+
if (!mode) return undefined;
|
|
342
|
+
const message = value as Contract & { details: { contextBoundary?: ContextBoundary } };
|
|
343
|
+
const boundary = message.details?.contextBoundary;
|
|
344
|
+
if (
|
|
345
|
+
!boundary ||
|
|
346
|
+
!Number.isSafeInteger(boundary.length) ||
|
|
347
|
+
boundary.length < 0 ||
|
|
348
|
+
typeof boundary.hash !== "string" ||
|
|
349
|
+
!/^[a-f0-9]{64}$/u.test(boundary.hash)
|
|
350
|
+
)
|
|
351
|
+
return undefined;
|
|
352
|
+
return { version: 1, mode, boundary };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function restorationKey(value: PlanInteractionRestoration): string {
|
|
356
|
+
return `${value.mode}:${value.boundary.length}:${value.boundary.hash}`;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function restoreInteractionHistory(messages: unknown[], history: readonly PlanInteractionRestoration[]): unknown[] {
|
|
360
|
+
const restorations = new Map(history.map((value) => [restorationKey(value), value]));
|
|
361
|
+
for (const message of messages) {
|
|
362
|
+
const restored = restorationFromMessage(message);
|
|
363
|
+
if (restored) restorations.set(restorationKey(restored), restored);
|
|
364
|
+
}
|
|
365
|
+
let result = messages;
|
|
366
|
+
for (const [key, restored] of restorations) {
|
|
367
|
+
const remaining = result.filter((message) => {
|
|
368
|
+
const candidate = restorationFromMessage(message);
|
|
369
|
+
return !candidate || restorationKey(candidate) !== key;
|
|
370
|
+
});
|
|
371
|
+
// Compaction establishes a new prefix epoch. Do not recreate a historical
|
|
372
|
+
// contract whose original retained boundary no longer exists.
|
|
373
|
+
if (!boundaryMatches(remaining, restored.boundary)) continue;
|
|
374
|
+
const canonical = createInteractionContractMessage(restored.mode, 0);
|
|
375
|
+
const message = { ...canonical, details: { ...canonical.details, contextBoundary: restored.boundary } };
|
|
376
|
+
result = insertAtBoundary(remaining, message, restored.boundary.length);
|
|
377
|
+
}
|
|
378
|
+
return result;
|
|
379
|
+
}
|
|
@@ -29,6 +29,7 @@ interface PlanActionControllerOptions {
|
|
|
29
29
|
getExportDestination(ctx: ExtensionContext): PlanExportDestination;
|
|
30
30
|
show(ctx: ExtensionContext): void;
|
|
31
31
|
finalize(ctx: ExtensionContext): void;
|
|
32
|
+
toggleInteraction?(ctx: ExtensionContext): void;
|
|
32
33
|
implementHere(ctx: ExtensionContext): void | Promise<void>;
|
|
33
34
|
implementFresh(
|
|
34
35
|
ctx: ExtensionContext,
|
|
@@ -117,6 +118,8 @@ export function createPlanActionController(options: PlanActionControllerOptions)
|
|
|
117
118
|
planThinkingLevel: options.getThinkingLevel(),
|
|
118
119
|
implementationDefaults: configuredDefaults(),
|
|
119
120
|
hasReadyPlan: options.getState().latestPlan !== undefined,
|
|
121
|
+
interactionMode: options.getState().interactionMode,
|
|
122
|
+
...(options.toggleInteraction ? { toggleInteraction: () => options.toggleInteraction?.(ctx) } : {}),
|
|
120
123
|
implementationOutcome: options.implementationOutcome,
|
|
121
124
|
getExportDestination: () => options.getExportDestination(ctx),
|
|
122
125
|
...lifecycle,
|
|
@@ -130,8 +133,14 @@ export function createPlanActionController(options: PlanActionControllerOptions)
|
|
|
130
133
|
exit: () => options.exitReady(ctx),
|
|
131
134
|
});
|
|
132
135
|
},
|
|
133
|
-
async showReady(ctx: ExtensionContext) {
|
|
134
|
-
const
|
|
136
|
+
async showReady(ctx: ExtensionContext, presentation?: MenuLifecycle) {
|
|
137
|
+
const workflow = options.captureLifecycle();
|
|
138
|
+
const lifecycle: MenuLifecycle = presentation
|
|
139
|
+
? {
|
|
140
|
+
signal: AbortSignal.any([workflow.signal, presentation.signal]),
|
|
141
|
+
isCurrent: () => workflow.isCurrent() && presentation.isCurrent() && !presentation.signal.aborted,
|
|
142
|
+
}
|
|
143
|
+
: workflow;
|
|
135
144
|
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
136
145
|
const ui = await options.loadInteractiveUi();
|
|
137
146
|
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
package/src/plan-action-menus.ts
CHANGED
|
@@ -35,6 +35,8 @@ interface PlanMenuOptions extends MenuLifecycle {
|
|
|
35
35
|
planThinkingLevel: PlanModeFixedThinkingLevel | undefined;
|
|
36
36
|
implementationDefaults?: ImplementationRuntimeSelection;
|
|
37
37
|
hasReadyPlan: boolean;
|
|
38
|
+
interactionMode?: "questions" | "discussion";
|
|
39
|
+
toggleInteraction?(): void;
|
|
38
40
|
implementationOutcome(): string;
|
|
39
41
|
getExportDestination: PlanExportDestinationProvider;
|
|
40
42
|
show(): void;
|
|
@@ -51,6 +53,7 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
|
|
|
51
53
|
type Screen = "main" | "fresh" | "models" | "thinking" | "export";
|
|
52
54
|
type Action =
|
|
53
55
|
| "show"
|
|
56
|
+
| "toggle-interaction"
|
|
54
57
|
| "finalize"
|
|
55
58
|
| "implement-here"
|
|
56
59
|
| "select-model"
|
|
@@ -66,6 +69,15 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
|
|
|
66
69
|
options.implementationDefaults,
|
|
67
70
|
options.implementFresh,
|
|
68
71
|
);
|
|
72
|
+
const interactionItems = options.toggleInteraction
|
|
73
|
+
? [
|
|
74
|
+
{
|
|
75
|
+
id: "toggle-interaction",
|
|
76
|
+
label: options.interactionMode === "discussion" ? "Enable questionnaires" : "Switch to free discussion",
|
|
77
|
+
action: "toggle-interaction" as const,
|
|
78
|
+
},
|
|
79
|
+
]
|
|
80
|
+
: [];
|
|
69
81
|
const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
|
|
70
82
|
start: "main",
|
|
71
83
|
screens: {
|
|
@@ -93,11 +105,13 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
|
|
|
93
105
|
},
|
|
94
106
|
{ id: "export", label: "Export plan…", to: "export" },
|
|
95
107
|
{ id: "save", label: "Save for later", action: "save" },
|
|
108
|
+
...interactionItems,
|
|
96
109
|
{ id: "stay", label: "Stay in Plan mode", action: "stay" },
|
|
97
110
|
{ id: "exit", label: "Discard plan and exit", action: "exit" },
|
|
98
111
|
]
|
|
99
112
|
: [
|
|
100
113
|
{ id: "finalize", label: "Request final plan", action: "finalize" },
|
|
114
|
+
...interactionItems,
|
|
101
115
|
{ id: "stay", label: "Stay in Plan mode", action: "stay" },
|
|
102
116
|
{ id: "exit", label: "Exit Plan mode", action: "exit" },
|
|
103
117
|
],
|
|
@@ -113,6 +127,10 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
|
|
|
113
127
|
options.show();
|
|
114
128
|
return { kind: "close" };
|
|
115
129
|
},
|
|
130
|
+
"toggle-interaction": async () => {
|
|
131
|
+
options.toggleInteraction?.();
|
|
132
|
+
return { kind: "close" };
|
|
133
|
+
},
|
|
116
134
|
finalize: async () => {
|
|
117
135
|
options.finalize();
|
|
118
136
|
return { kind: "close" };
|