@narumitw/pi-plan-mode 0.49.3 → 0.50.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/README.md +27 -6
- package/dist/chunks/chunk-6SDTCIHD.ts +1490 -0
- package/dist/chunks/chunk-6SDTCIHD.ts.map +7 -0
- package/dist/chunks/interactive-ui-JBSBPK6S.ts +715 -0
- package/dist/chunks/interactive-ui-JBSBPK6S.ts.map +7 -0
- package/dist/index.ts +1497 -0
- package/dist/index.ts.map +7 -0
- package/package.json +15 -8
- package/src/plan-mode.ts +129 -15
- package/src/settings-menu.ts +47 -2
- package/src/settings.ts +91 -0
package/dist/index.ts
ADDED
|
@@ -0,0 +1,1497 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
import {
|
|
4
|
+
IMPLEMENTATION_PLAN_RETENTIONS,
|
|
5
|
+
PLAN_MODE_COMPLETE_PARAMS,
|
|
6
|
+
PLAN_MODE_COMPLETE_TOOL_NAME,
|
|
7
|
+
PLAN_MODE_QUESTION_PARAMS,
|
|
8
|
+
PLAN_MODE_QUESTION_TOOL_NAME,
|
|
9
|
+
PLAN_MODE_THINKING_LEVELS,
|
|
10
|
+
answerPlanModeQuestions,
|
|
11
|
+
awaitPlanModeSettingsWrites,
|
|
12
|
+
canSelectToolInPlanMode,
|
|
13
|
+
classifyPlanModeTool,
|
|
14
|
+
compareTools,
|
|
15
|
+
configuredImplementationPlanRetention,
|
|
16
|
+
configuredPlanExportPath,
|
|
17
|
+
configuredPlanModeToggleShortcut,
|
|
18
|
+
configuredThinkingLevel,
|
|
19
|
+
createImplementationRetentionCoordinator,
|
|
20
|
+
exportStoredPlan,
|
|
21
|
+
filterAvailableSelectedToolNames,
|
|
22
|
+
findBlockedCommandSegment,
|
|
23
|
+
implementationRetentionPreview,
|
|
24
|
+
invalidPlanMessage,
|
|
25
|
+
latestAssistantText,
|
|
26
|
+
normalizePlanModeCompletion,
|
|
27
|
+
normalizePlanModeQuestionParams,
|
|
28
|
+
parseProposedPlan,
|
|
29
|
+
planExportDestination,
|
|
30
|
+
planFromCompletionDetails,
|
|
31
|
+
planModeCompleted,
|
|
32
|
+
planModeQuestionCancelled,
|
|
33
|
+
planModeSettingsPath,
|
|
34
|
+
readCommand,
|
|
35
|
+
readPlanModeSettings,
|
|
36
|
+
renderPlanModeCompletion,
|
|
37
|
+
snapshotPlanModeSelectedNames,
|
|
38
|
+
snapshotPlanModeToolNames,
|
|
39
|
+
toolPolicyLabel,
|
|
40
|
+
withRequiredPlanModeTools,
|
|
41
|
+
withoutRequiredPlanModeTools
|
|
42
|
+
} from "./chunks/chunk-6SDTCIHD.js";
|
|
43
|
+
|
|
44
|
+
// src/plan-mode.ts
|
|
45
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
46
|
+
import { watch } from "node:fs";
|
|
47
|
+
import { basename, dirname } from "node:path";
|
|
48
|
+
|
|
49
|
+
// src/command.ts
|
|
50
|
+
var PLAN_COMMAND_COMPLETIONS = [
|
|
51
|
+
{ value: "start", label: "start", description: "Start Plan mode without sending a prompt" },
|
|
52
|
+
{ value: "show", label: "show", description: "Show the ready, saved, or active plan" },
|
|
53
|
+
{ value: "finalize", label: "finalize", description: "Request a completed plan" },
|
|
54
|
+
{ value: "implement", label: "implement", description: "Implement the completed or saved plan" },
|
|
55
|
+
{ value: "save", label: "save", description: "Save the completed plan for later" },
|
|
56
|
+
{ value: "export", label: "export", description: "Export the stored plan to a Markdown file" },
|
|
57
|
+
{ value: "exit", label: "exit", description: "Leave Plan mode or clear a saved/active plan" },
|
|
58
|
+
{ value: "off", label: "off", description: "Leave Plan mode or clear a saved/active plan" },
|
|
59
|
+
{
|
|
60
|
+
value: "tools",
|
|
61
|
+
label: "tools",
|
|
62
|
+
description: "Choose tools before starting this Plan workflow"
|
|
63
|
+
}
|
|
64
|
+
];
|
|
65
|
+
function completePlanArguments(argumentPrefix) {
|
|
66
|
+
const prefix = argumentPrefix.trimStart().toLowerCase();
|
|
67
|
+
if (prefix === "") return [...PLAN_COMMAND_COMPLETIONS];
|
|
68
|
+
if (/\s/.test(prefix)) return null;
|
|
69
|
+
const matches = PLAN_COMMAND_COMPLETIONS.filter((item) => item.value.startsWith(prefix));
|
|
70
|
+
return matches.length > 0 ? [...matches] : null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/extension-runtime.ts
|
|
74
|
+
function onAgentSettled(pi, handler) {
|
|
75
|
+
pi.on("agent_settled", handler);
|
|
76
|
+
}
|
|
77
|
+
function setPlanThinkingLevel(pi, level) {
|
|
78
|
+
pi.setThinkingLevel(level);
|
|
79
|
+
}
|
|
80
|
+
function isStaleExtensionContextError(error) {
|
|
81
|
+
return error instanceof Error && (error.message.includes("This extension ctx is stale after session replacement or reload") || error.message.includes("Extension context is no longer active"));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/fresh-implementation.ts
|
|
85
|
+
import { randomUUID } from "node:crypto";
|
|
86
|
+
function formatImplementationHandoff(plan) {
|
|
87
|
+
return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:
|
|
88
|
+
|
|
89
|
+
${plan}`;
|
|
90
|
+
}
|
|
91
|
+
async function startFreshImplementationFromState(ctx, options) {
|
|
92
|
+
if (!isCommandContext(ctx)) {
|
|
93
|
+
ctx.ui.notify(
|
|
94
|
+
"Fresh implementation requires the interactive /plan command. Reopen /plan and try again.",
|
|
95
|
+
"warning"
|
|
96
|
+
);
|
|
97
|
+
return { kind: "rejected" };
|
|
98
|
+
}
|
|
99
|
+
const initialState = options.getState();
|
|
100
|
+
const savedPlan = initialState.enabled ? void 0 : initialState.savedPlan;
|
|
101
|
+
const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();
|
|
102
|
+
const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;
|
|
103
|
+
if (!plan || !source) {
|
|
104
|
+
ctx.ui.notify("No completed plan is available to implement.", "warning");
|
|
105
|
+
return { kind: "rejected" };
|
|
106
|
+
}
|
|
107
|
+
const wasEnabled = initialState.enabled;
|
|
108
|
+
const isCurrent = () => {
|
|
109
|
+
const current = options.getState();
|
|
110
|
+
return options.menuIsCurrent() && current.enabled === wasEnabled && (wasEnabled ? current.latestPlan === plan && current.latestPlanSource === source : current.savedPlan === savedPlan);
|
|
111
|
+
};
|
|
112
|
+
return startFreshImplementationSession(ctx, {
|
|
113
|
+
plan,
|
|
114
|
+
source,
|
|
115
|
+
retention: options.retention,
|
|
116
|
+
stateEntryType: options.stateEntryType,
|
|
117
|
+
isCurrent
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
async function startFreshImplementationSession(ctx, request) {
|
|
121
|
+
if (ctx.mode === "print" || ctx.mode === "json") {
|
|
122
|
+
throw new Error("Fresh plan implementation is unavailable in print/JSON mode. Use TUI or RPC.");
|
|
123
|
+
}
|
|
124
|
+
await ctx.waitForIdle();
|
|
125
|
+
if (!request.isCurrent()) return { kind: "stale" };
|
|
126
|
+
if (!await preflightModel(ctx, request.isCurrent)) return { kind: "rejected" };
|
|
127
|
+
if (!request.isCurrent()) return { kind: "stale" };
|
|
128
|
+
const activeImplementation = {
|
|
129
|
+
id: randomUUID(),
|
|
130
|
+
plan: request.plan,
|
|
131
|
+
source: request.source,
|
|
132
|
+
startedAt: Date.now(),
|
|
133
|
+
retention: request.retention
|
|
134
|
+
};
|
|
135
|
+
const destinationState = {
|
|
136
|
+
enabled: false,
|
|
137
|
+
awaitingAction: false,
|
|
138
|
+
activeImplementation
|
|
139
|
+
};
|
|
140
|
+
const handoff = formatImplementationHandoff(request.plan);
|
|
141
|
+
const parentSession = ctx.sessionManager.getSessionFile();
|
|
142
|
+
let setupError;
|
|
143
|
+
let kickoffError;
|
|
144
|
+
if (ctx.mode === "rpc") ctx.ui.notify("Starting fresh implementation session\u2026", "info");
|
|
145
|
+
let result;
|
|
146
|
+
try {
|
|
147
|
+
result = await ctx.newSession({
|
|
148
|
+
...parentSession ? { parentSession } : {},
|
|
149
|
+
setup: async (sessionManager) => {
|
|
150
|
+
try {
|
|
151
|
+
sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
setupError = safeErrorDetail(error);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
withSession: async (replacementCtx) => {
|
|
157
|
+
if (setupError) {
|
|
158
|
+
recoverSetupFailure(replacementCtx, handoff, setupError);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
await replacementCtx.sendUserMessage(handoff);
|
|
163
|
+
replacementCtx.ui.notify(
|
|
164
|
+
"Fresh implementation session started. Only the approved plan was transferred.",
|
|
165
|
+
"info"
|
|
166
|
+
);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
kickoffError = safeErrorDetail(error);
|
|
169
|
+
replacementCtx.ui.notify(
|
|
170
|
+
`Fresh session created, but implementation did not start: ${kickoffError}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,
|
|
171
|
+
"error"
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
} catch (error) {
|
|
177
|
+
safeNotify(
|
|
178
|
+
ctx,
|
|
179
|
+
`Unable to start a fresh implementation session: ${safeErrorDetail(error)}. The source plan remains available; retry or resume the planning session.`,
|
|
180
|
+
"error"
|
|
181
|
+
);
|
|
182
|
+
return { kind: "rejected" };
|
|
183
|
+
}
|
|
184
|
+
if (result.cancelled) {
|
|
185
|
+
ctx.ui.notify("Fresh implementation cancelled. The plan remains available.", "info");
|
|
186
|
+
return { kind: "cancelled" };
|
|
187
|
+
}
|
|
188
|
+
return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
|
|
189
|
+
}
|
|
190
|
+
async function preflightModel(ctx, isCurrent) {
|
|
191
|
+
const model = ctx.model;
|
|
192
|
+
if (!model) {
|
|
193
|
+
ctx.ui.notify("Unable to implement the plan: no model is selected.", "warning");
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
let auth;
|
|
197
|
+
try {
|
|
198
|
+
auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
if (isCurrent()) {
|
|
201
|
+
ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
|
|
202
|
+
}
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
if (!isCurrent()) return false;
|
|
206
|
+
if (!auth.ok) {
|
|
207
|
+
ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(auth.error)}`, "warning");
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
function recoverSetupFailure(ctx, handoff, setupError) {
|
|
213
|
+
ctx.ui.setEditorText(handoff);
|
|
214
|
+
ctx.ui.notify(
|
|
215
|
+
`Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request is in the editor; submit it to continue or resume the parent planning session.`,
|
|
216
|
+
"error"
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
function safeNotify(ctx, message, level) {
|
|
220
|
+
try {
|
|
221
|
+
ctx.ui.notify(message, level);
|
|
222
|
+
} catch {
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function isCommandContext(ctx) {
|
|
226
|
+
return typeof ctx.newSession === "function";
|
|
227
|
+
}
|
|
228
|
+
function safeErrorDetail(error) {
|
|
229
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
230
|
+
const normalized = [...detail].map((character) => {
|
|
231
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
232
|
+
return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
|
|
233
|
+
}).join("").replace(/\s+/gu, " ").trim() || "unknown error";
|
|
234
|
+
const characters = [...normalized];
|
|
235
|
+
return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// src/plan-action-controller.ts
|
|
239
|
+
function createPlanActionController(options) {
|
|
240
|
+
const freshAction = (ctx, lifecycle, signal) => options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);
|
|
241
|
+
return {
|
|
242
|
+
async showSaved(ctx) {
|
|
243
|
+
const lifecycle = options.captureLifecycle();
|
|
244
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
245
|
+
const ui = await options.loadInteractiveUi();
|
|
246
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
247
|
+
await ui.showSavedPlanMenu(ctx, {
|
|
248
|
+
statusText: options.statusText(),
|
|
249
|
+
implementationOutcome: options.implementationOutcome,
|
|
250
|
+
getExportDestination: () => options.getExportDestination(ctx),
|
|
251
|
+
signal: lifecycle.signal,
|
|
252
|
+
isCurrent: lifecycle.isCurrent,
|
|
253
|
+
show: () => options.show(ctx),
|
|
254
|
+
implementHere: () => options.implementHere(ctx),
|
|
255
|
+
implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
|
|
256
|
+
exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
|
|
257
|
+
settings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),
|
|
258
|
+
clear: () => options.clearSaved(ctx)
|
|
259
|
+
});
|
|
260
|
+
},
|
|
261
|
+
async showCurrent(ctx) {
|
|
262
|
+
if (!ctx.hasUI) {
|
|
263
|
+
ctx.ui.notify(options.statusText(), "info");
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const lifecycle = options.captureLifecycle();
|
|
267
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
268
|
+
const ui = await options.loadInteractiveUi();
|
|
269
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
270
|
+
await ui.showPlanModeMenu(ctx, {
|
|
271
|
+
statusText: options.statusText(),
|
|
272
|
+
hasReadyPlan: options.getState().latestPlan !== void 0,
|
|
273
|
+
implementationOutcome: options.implementationOutcome,
|
|
274
|
+
getExportDestination: () => options.getExportDestination(ctx),
|
|
275
|
+
...lifecycle,
|
|
276
|
+
show: () => options.show(ctx),
|
|
277
|
+
finalize: () => options.finalize(ctx),
|
|
278
|
+
implementHere: () => options.implementHere(ctx),
|
|
279
|
+
implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
|
|
280
|
+
exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
|
|
281
|
+
save: () => options.save(ctx),
|
|
282
|
+
stay: () => options.stay(ctx),
|
|
283
|
+
exit: () => options.exitReady(ctx)
|
|
284
|
+
});
|
|
285
|
+
},
|
|
286
|
+
async showReady(ctx) {
|
|
287
|
+
const lifecycle = options.captureLifecycle();
|
|
288
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
289
|
+
const ui = await options.loadInteractiveUi();
|
|
290
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
291
|
+
await ui.showReadyPlanMenu(ctx, {
|
|
292
|
+
...lifecycle,
|
|
293
|
+
implementationOutcome: options.implementationOutcome,
|
|
294
|
+
getExportDestination: () => options.getExportDestination(ctx),
|
|
295
|
+
implementHere: () => options.implementHere(ctx),
|
|
296
|
+
implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
|
|
297
|
+
exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
|
|
298
|
+
save: () => options.save(ctx),
|
|
299
|
+
stay: () => void 0,
|
|
300
|
+
exit: () => options.exitReady(ctx)
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// src/plan-export-controller.ts
|
|
307
|
+
function createPlanExportController(options) {
|
|
308
|
+
return {
|
|
309
|
+
export(path, ctx, signal, isCurrent) {
|
|
310
|
+
const state = options.getState();
|
|
311
|
+
return exportStoredPlan(
|
|
312
|
+
state,
|
|
313
|
+
path,
|
|
314
|
+
ctx,
|
|
315
|
+
{
|
|
316
|
+
signal,
|
|
317
|
+
isCurrent,
|
|
318
|
+
getState: options.getState,
|
|
319
|
+
finishReady: () => options.finishReady(ctx)
|
|
320
|
+
},
|
|
321
|
+
configuredPlanExportPath(options.getSettings())
|
|
322
|
+
);
|
|
323
|
+
},
|
|
324
|
+
getDestination(ctx) {
|
|
325
|
+
return planExportDestination(configuredPlanExportPath(options.getSettings()), ctx.cwd);
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// src/presentation.ts
|
|
331
|
+
var STATUS_KEY = "plan-mode";
|
|
332
|
+
var PLAN_WIDGET_KEY = "plan-mode-plan";
|
|
333
|
+
function updatePlanModeUi(ctx, state, toolSummary) {
|
|
334
|
+
ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
|
|
335
|
+
if (state.enabled && state.latestPlan) {
|
|
336
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, [
|
|
337
|
+
"Proposed plan ready",
|
|
338
|
+
"Use /plan to implement, save, revise, or exit Plan mode."
|
|
339
|
+
]);
|
|
340
|
+
} else if (state.enabled) {
|
|
341
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, [
|
|
342
|
+
"Plan mode: planning",
|
|
343
|
+
toolSummary(),
|
|
344
|
+
"Finish with plan_mode_complete when decision-ready."
|
|
345
|
+
]);
|
|
346
|
+
} else if (state.savedPlan) {
|
|
347
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, [
|
|
348
|
+
"Plan saved for later",
|
|
349
|
+
"Use /plan to show, implement, or clear it."
|
|
350
|
+
]);
|
|
351
|
+
} else if (state.activeImplementation) {
|
|
352
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, [
|
|
353
|
+
"Implementation plan active",
|
|
354
|
+
"Use /plan to show, replace, or clear it."
|
|
355
|
+
]);
|
|
356
|
+
} else {
|
|
357
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, void 0);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function clearPlanModeUi(ctx) {
|
|
361
|
+
ctx.ui.setStatus(STATUS_KEY, void 0);
|
|
362
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, void 0);
|
|
363
|
+
}
|
|
364
|
+
function showStoredPlan(pi, ctx, state) {
|
|
365
|
+
const readyPlan = state.enabled ? state.latestPlan?.trim() : void 0;
|
|
366
|
+
const savedPlan = state.savedPlan?.plan.trim();
|
|
367
|
+
if (savedPlan && (ctx.mode === "print" || ctx.mode === "json")) {
|
|
368
|
+
throw new Error("Saved plan display is unavailable in print/JSON mode. Use TUI or RPC.");
|
|
369
|
+
}
|
|
370
|
+
const activePlan = state.activeImplementation?.plan.trim();
|
|
371
|
+
const plan = readyPlan ?? savedPlan ?? activePlan;
|
|
372
|
+
if (!plan) {
|
|
373
|
+
ctx.ui.notify(
|
|
374
|
+
"No completed plan is available. Use /plan finalize when planning is complete.",
|
|
375
|
+
"info"
|
|
376
|
+
);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
const title = readyPlan ? "Proposed Plan" : savedPlan ? "Saved Plan" : "Active Implementation Plan";
|
|
380
|
+
showPlanModePlan(pi, ctx, title, plan);
|
|
381
|
+
}
|
|
382
|
+
function showPlanModePlan(pi, ctx, title, plan) {
|
|
383
|
+
try {
|
|
384
|
+
pi.sendMessage(
|
|
385
|
+
{
|
|
386
|
+
customType: "proposed-plan",
|
|
387
|
+
content: `**${title}**
|
|
388
|
+
|
|
389
|
+
${plan}`,
|
|
390
|
+
display: true
|
|
391
|
+
},
|
|
392
|
+
{ triggerTurn: false }
|
|
393
|
+
);
|
|
394
|
+
} catch (error) {
|
|
395
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
396
|
+
ctx.ui.notify(`Unable to show completed plan: ${detail}`, "error");
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
function planModeStatusText(state, toolSummary) {
|
|
400
|
+
if (state.enabled) {
|
|
401
|
+
if (state.latestPlan) {
|
|
402
|
+
return `Plan mode is active and a proposed plan is ready. ${toolSummary()}`;
|
|
403
|
+
}
|
|
404
|
+
return `Plan mode is active. ${toolSummary()} Explore, ask, and finish with plan_mode_complete when decision-ready.`;
|
|
405
|
+
}
|
|
406
|
+
if (state.savedPlan) return "A plan is saved for later.";
|
|
407
|
+
if (state.activeImplementation) return "An implementation plan is active.";
|
|
408
|
+
return "Plan mode is off.";
|
|
409
|
+
}
|
|
410
|
+
function formatStatus(state) {
|
|
411
|
+
if (state.enabled) {
|
|
412
|
+
if (state.awaitingAction || state.latestPlan) return "plan ready";
|
|
413
|
+
return "plan active";
|
|
414
|
+
}
|
|
415
|
+
if (state.savedPlan) return "plan saved";
|
|
416
|
+
if (state.activeImplementation) return "plan implementing";
|
|
417
|
+
return void 0;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// src/prompt.ts
|
|
421
|
+
var PLAN_CONTEXT_MARKER = "[CODEX-LIKE PLAN MODE ACTIVE]";
|
|
422
|
+
function buildPlanModePrompt() {
|
|
423
|
+
return `${PLAN_CONTEXT_MARKER}
|
|
424
|
+
# Plan Mode (Conversational)
|
|
425
|
+
|
|
426
|
+
You are in Plan Mode, a Codex-like collaboration mode for producing a decision-complete implementation plan. Chat your way to the plan before finalizing it. A final plan must leave no implementation decisions unresolved.
|
|
427
|
+
|
|
428
|
+
## Mode rules
|
|
429
|
+
|
|
430
|
+
- Stay in Plan Mode until a developer or extension explicitly exits it.
|
|
431
|
+
- Treat requests to implement as requests to plan the implementation; do not edit files or carry out the plan.
|
|
432
|
+
- Do not use update_plan/TODO tooling in Plan Mode; Plan Mode is conversational planning, not execution progress tracking.
|
|
433
|
+
- Plan Mode manages built-in tool safety only. Non-built-in tools are disabled by default and may be enabled by the user at their own risk.
|
|
434
|
+
- Do not perform mutating actions: no edit/write tools, no patching, no formatting that rewrites files, no dependency installation, no commits, no migrations.
|
|
435
|
+
|
|
436
|
+
## Phase 1 \u2014 Ground in the environment
|
|
437
|
+
|
|
438
|
+
- Explore first and ask second. Use non-mutating exploration to read files, search, inspect configuration, run read-only checks, and resolve discoverable facts.
|
|
439
|
+
- Before asking the user any question, perform at least one targeted non-mutating exploration pass unless no local environment or repository is available.
|
|
440
|
+
- Do not ask questions that can be answered from repository or system truth. Ask only when multiple plausible choices remain, a needed identifier/context is missing, or the ambiguity is product intent.
|
|
441
|
+
|
|
442
|
+
## Phase 2 \u2014 Intent chat
|
|
443
|
+
|
|
444
|
+
- Keep asking until you can clearly state the goal, success criteria, in/out of scope, constraints, current state, and key preferences/tradeoffs.
|
|
445
|
+
- Bias toward questions over guessing: if a high-impact ambiguity remains, do not produce a proposed plan yet.
|
|
446
|
+
- For an unanswered preference or tradeoff, use the recommended option only when it is low risk and record that default as an explicit assumption in the final plan.
|
|
447
|
+
|
|
448
|
+
## Phase 3 \u2014 Implementation chat
|
|
449
|
+
|
|
450
|
+
- Once intent is stable, keep asking until the spec is decision-complete: approach, interfaces, data flow, edge cases/failure modes, testing and acceptance criteria, and any migration or compatibility constraints.
|
|
451
|
+
- Use plan_mode_question for important preferences, tradeoffs, or assumption locks that cannot be discovered by non-mutating exploration. Ask 1-3 concise questions with 2-4 meaningful options. Do not include filler options.
|
|
452
|
+
- If plan_mode_question returns cancelled or ui_unavailable, do not jump straight to a final plan when the missing answer is high impact. Ask one concise plain-text question or proceed only with a clearly stated low-risk assumption.
|
|
453
|
+
|
|
454
|
+
## Ending each turn
|
|
455
|
+
|
|
456
|
+
Every Plan-mode turn that advances or finalizes the plan must end in exactly one of these ways:
|
|
457
|
+
|
|
458
|
+
- If a material decision remains, use plan_mode_question. If interactive UI is unavailable, ask one concise plain-text question instead.
|
|
459
|
+
- If the implementation plan is decision-complete, call plan_mode_complete alone as your final action. Do not call other tools in the same batch and do not emit a normal assistant response after it.
|
|
460
|
+
|
|
461
|
+
If a follow-up asks only for clarification and does not change or challenge the plan, answer it directly, then call plan_mode_complete alone as the final action with the complete unchanged plan so it remains available for implementation.
|
|
462
|
+
|
|
463
|
+
Never end with prose that merely announces you are about to present, write, or finalize the plan. Submit the actual plan with plan_mode_complete in that turn.
|
|
464
|
+
|
|
465
|
+
## Completion rule
|
|
466
|
+
|
|
467
|
+
Only call plan_mode_complete when the plan leaves no implementation decisions unresolved. Pass the complete plan as Markdown with:
|
|
468
|
+
|
|
469
|
+
- A clear title
|
|
470
|
+
- A brief summary
|
|
471
|
+
- Important changes to behavior, public APIs, interfaces, or types
|
|
472
|
+
- Test cases and verification scenarios
|
|
473
|
+
- Explicit assumptions and defaults chosen where needed
|
|
474
|
+
|
|
475
|
+
Keep the plan concise, human and agent digestible, and free of open decisions. Prefer grouped behavior-level changes over file-by-file or symbol-by-symbol inventories. Do not ask "should I proceed?"; plan_mode_complete opens the Plan-mode ready flow.
|
|
476
|
+
|
|
477
|
+
If the user requests revisions after a completed plan, the next plan_mode_complete call must contain a complete replacement, not a delta. If there is not enough information for a complete replacement, continue planning with plan_mode_question instead of calling plan_mode_complete.`;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// src/saved-plan-preflight.ts
|
|
481
|
+
function savedPlanBlocksNewWorkflow(ctx, hasSavedPlan) {
|
|
482
|
+
if (!hasSavedPlan) return false;
|
|
483
|
+
const message = "A plan is saved for later. Implement or clear it before starting another Plan-mode workflow.";
|
|
484
|
+
if (!ctx.hasUI) throw new Error(message);
|
|
485
|
+
ctx.ui.notify(message, "warning");
|
|
486
|
+
return true;
|
|
487
|
+
}
|
|
488
|
+
async function preflightSavedPlanImplementation(ctx, isCurrent) {
|
|
489
|
+
if (ctx.mode === "print" || ctx.mode === "json") {
|
|
490
|
+
throw new Error("Saved plan implementation is unavailable in print/JSON mode. Use TUI or RPC.");
|
|
491
|
+
}
|
|
492
|
+
const model = ctx.model;
|
|
493
|
+
if (!model) {
|
|
494
|
+
ctx.ui.notify("Unable to implement saved plan: no model is selected.", "warning");
|
|
495
|
+
return false;
|
|
496
|
+
}
|
|
497
|
+
let auth;
|
|
498
|
+
try {
|
|
499
|
+
auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
500
|
+
} catch (error) {
|
|
501
|
+
if (!isCurrent()) return false;
|
|
502
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
503
|
+
ctx.ui.notify(`Unable to implement saved plan: ${detail}`, "error");
|
|
504
|
+
return false;
|
|
505
|
+
}
|
|
506
|
+
if (!isCurrent()) return false;
|
|
507
|
+
if (!auth.ok) {
|
|
508
|
+
ctx.ui.notify(`Unable to implement saved plan: ${auth.error}`, "warning");
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// src/state.ts
|
|
515
|
+
function restorePlanModeState(entries, stateEntryType) {
|
|
516
|
+
const branch = entries;
|
|
517
|
+
let stateEntryIndex = -1;
|
|
518
|
+
for (let index = branch.length - 1; index >= 0; index -= 1) {
|
|
519
|
+
const candidate = branch[index];
|
|
520
|
+
if (candidate?.type === "custom" && candidate.customType === stateEntryType) {
|
|
521
|
+
stateEntryIndex = index;
|
|
522
|
+
break;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
const entry = branch[stateEntryIndex];
|
|
526
|
+
if (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };
|
|
527
|
+
const enabled = entry.data.enabled === true;
|
|
528
|
+
const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : void 0;
|
|
529
|
+
const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : void 0;
|
|
530
|
+
const recoveredPlan = enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : void 0;
|
|
531
|
+
const latestPlan = persistedPlan ?? recoveredPlan;
|
|
532
|
+
const activeImplementation = enabled ? void 0 : normalizeActiveImplementation(entry.data.activeImplementation);
|
|
533
|
+
const savedPlan = enabled || activeImplementation ? void 0 : normalizeSavedPlan(entry.data.savedPlan);
|
|
534
|
+
return {
|
|
535
|
+
enabled,
|
|
536
|
+
latestPlan,
|
|
537
|
+
latestPlanSource: enabled ? (persistedPlan ? persistedSource : void 0) ?? (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : void 0) : void 0,
|
|
538
|
+
awaitingAction: enabled && latestPlan !== void 0,
|
|
539
|
+
savedPlan,
|
|
540
|
+
activeImplementation,
|
|
541
|
+
selectedToolNames: stringArray(entry.data.selectedToolNames),
|
|
542
|
+
selectedToolKeys: stringArray(entry.data.selectedToolKeys),
|
|
543
|
+
previousThinkingLevel: enabled ? fixedThinkingLevel(entry.data.previousThinkingLevel) : void 0,
|
|
544
|
+
appliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : void 0,
|
|
545
|
+
manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : void 0
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
function normalizeSavedPlan(value) {
|
|
549
|
+
if (!isRecord(value)) return void 0;
|
|
550
|
+
const source = planCompletionSource(value.source);
|
|
551
|
+
const normalized = normalizePlanModeCompletion({ plan: value.plan });
|
|
552
|
+
if (!source || !normalized.ok) return void 0;
|
|
553
|
+
return { plan: normalized.plan, source };
|
|
554
|
+
}
|
|
555
|
+
function normalizeActiveImplementation(value) {
|
|
556
|
+
if (!isRecord(value)) return void 0;
|
|
557
|
+
const id = typeof value.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id) ? value.id : void 0;
|
|
558
|
+
const source = planCompletionSource(value.source);
|
|
559
|
+
const normalized = normalizePlanModeCompletion({ plan: value.plan });
|
|
560
|
+
const startedAt = typeof value.startedAt === "number" && Number.isSafeInteger(value.startedAt) && value.startedAt >= 0 ? value.startedAt : void 0;
|
|
561
|
+
if (!id || !source || !normalized.ok || startedAt === void 0) return void 0;
|
|
562
|
+
const retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(
|
|
563
|
+
value.retention
|
|
564
|
+
) ? value.retention : "keep";
|
|
565
|
+
return { id, plan: normalized.plan, source, startedAt, retention };
|
|
566
|
+
}
|
|
567
|
+
function normalizePersistedPlan(value) {
|
|
568
|
+
const normalized = normalizePlanModeCompletion({ plan: value });
|
|
569
|
+
return normalized.ok ? normalized.plan : void 0;
|
|
570
|
+
}
|
|
571
|
+
function latestCompletionPlan(entries) {
|
|
572
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
573
|
+
const message = entries[index]?.message;
|
|
574
|
+
if (message?.role !== "toolResult" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
const plan = planFromCompletionDetails(message.details);
|
|
578
|
+
if (plan) return plan;
|
|
579
|
+
}
|
|
580
|
+
return void 0;
|
|
581
|
+
}
|
|
582
|
+
function planCompletionSource(value) {
|
|
583
|
+
return value === PLAN_MODE_COMPLETE_TOOL_NAME || value === "legacy_proposed_plan" ? value : void 0;
|
|
584
|
+
}
|
|
585
|
+
function fixedThinkingLevel(value) {
|
|
586
|
+
return typeof value === "string" && value !== "inherit" && PLAN_MODE_THINKING_LEVELS.includes(value) ? value : void 0;
|
|
587
|
+
}
|
|
588
|
+
function stringArray(value) {
|
|
589
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string") ? Array.from(new Set(value)) : void 0;
|
|
590
|
+
}
|
|
591
|
+
function isRecord(value) {
|
|
592
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// src/plan-mode.ts
|
|
596
|
+
var STATE_ENTRY_TYPE = "plan-mode-state";
|
|
597
|
+
var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
|
|
598
|
+
var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
|
|
599
|
+
var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
|
|
600
|
+
function planMode(pi, dependencies = {}) {
|
|
601
|
+
let interactiveUiPromise;
|
|
602
|
+
const loadInteractiveUi = () => {
|
|
603
|
+
if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
|
|
604
|
+
if (!interactiveUiPromise) {
|
|
605
|
+
interactiveUiPromise = import("./chunks/interactive-ui-JBSBPK6S.js").catch((error) => {
|
|
606
|
+
interactiveUiPromise = void 0;
|
|
607
|
+
throw error;
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
return interactiveUiPromise;
|
|
611
|
+
};
|
|
612
|
+
const explicitPlanModeSettingsPath = dependencies.settingsPath;
|
|
613
|
+
let state = { enabled: false, awaitingAction: false };
|
|
614
|
+
let settings = { thinkingLevel: "inherit" };
|
|
615
|
+
let toggleShortcut;
|
|
616
|
+
const clearPlanModeShortcutHandler = () => {
|
|
617
|
+
};
|
|
618
|
+
let previousTools;
|
|
619
|
+
let readyPresentationIntent;
|
|
620
|
+
let latestCommandContext;
|
|
621
|
+
let nextReadyPresentationNonce = 0;
|
|
622
|
+
let menuGeneration = 0;
|
|
623
|
+
let workflowGeneration = 0;
|
|
624
|
+
let refreshStateBeforeFirstAgentStart = false;
|
|
625
|
+
let menuController = new AbortController();
|
|
626
|
+
let settingsWatch;
|
|
627
|
+
let settingsReloadTimer;
|
|
628
|
+
const implementationRetention = createImplementationRetentionCoordinator();
|
|
629
|
+
const persistState = () => pi.appendEntry(STATE_ENTRY_TYPE, state);
|
|
630
|
+
const planExports = createPlanExportController({
|
|
631
|
+
getState: () => state,
|
|
632
|
+
getSettings: () => settings,
|
|
633
|
+
finishReady: (ctx) => exitPlanMode(ctx)
|
|
634
|
+
});
|
|
635
|
+
const planActions = createPlanActionController({
|
|
636
|
+
loadInteractiveUi,
|
|
637
|
+
getState: () => state,
|
|
638
|
+
captureLifecycle: captureMenuLifecycle,
|
|
639
|
+
statusText: planStatusText,
|
|
640
|
+
implementationOutcome,
|
|
641
|
+
getExportDestination: (ctx) => planExports.getDestination(ctx),
|
|
642
|
+
show: (ctx) => showStoredPlan(pi, ctx, state),
|
|
643
|
+
finalize: requestFinalPlan,
|
|
644
|
+
implementHere: startImplementation,
|
|
645
|
+
implementFresh: startFreshImplementation,
|
|
646
|
+
exportPlan: (ctx, path, signal, isCurrent) => planExports.export(path, ctx, signal, isCurrent),
|
|
647
|
+
settings: showSettings,
|
|
648
|
+
save: savePlanForLater,
|
|
649
|
+
stay: updateUi,
|
|
650
|
+
exitReady: (ctx) => {
|
|
651
|
+
exitPlanMode(ctx);
|
|
652
|
+
ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
|
|
653
|
+
},
|
|
654
|
+
clearSaved: (ctx) => {
|
|
655
|
+
exitPlanMode(ctx);
|
|
656
|
+
ctx.ui.notify("Saved plan cleared.", "info");
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
pi.registerFlag("plan", {
|
|
660
|
+
description: "Start in Codex-like Plan mode",
|
|
661
|
+
type: "boolean",
|
|
662
|
+
default: false
|
|
663
|
+
});
|
|
664
|
+
pi.registerTool({
|
|
665
|
+
name: PLAN_MODE_QUESTION_TOOL_NAME,
|
|
666
|
+
label: "Plan question",
|
|
667
|
+
description: "Ask the user one to three Plan-mode clarification questions with meaningful options, then wait for the answer. Only available while Plan mode is active.",
|
|
668
|
+
promptSnippet: "Ask user decision questions while Plan mode is active",
|
|
669
|
+
promptGuidelines: [
|
|
670
|
+
"In Plan mode, use plan_mode_question for important preferences, tradeoffs, or assumptions that cannot be discovered from read-only exploration."
|
|
671
|
+
],
|
|
672
|
+
parameters: PLAN_MODE_QUESTION_PARAMS,
|
|
673
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
674
|
+
if (!state.enabled) {
|
|
675
|
+
return planModeQuestionCancelled(
|
|
676
|
+
[],
|
|
677
|
+
"plan_mode_inactive",
|
|
678
|
+
"Error: plan_mode_question is only available while Plan mode is active."
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
const parsed = normalizePlanModeQuestionParams(params);
|
|
682
|
+
if (!parsed.ok) {
|
|
683
|
+
return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
|
|
684
|
+
}
|
|
685
|
+
if (!ctx.hasUI) {
|
|
686
|
+
return planModeQuestionCancelled(
|
|
687
|
+
parsed.questions,
|
|
688
|
+
"ui_unavailable",
|
|
689
|
+
"Unable to ask Plan-mode questions because interactive UI is not available."
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
const sessionGeneration = menuGeneration;
|
|
693
|
+
const questionWorkflowGeneration = workflowGeneration;
|
|
694
|
+
return answerPlanModeQuestions(parsed.questions, ctx, {
|
|
695
|
+
isCurrent: () => sessionGeneration === menuGeneration && questionWorkflowGeneration === workflowGeneration,
|
|
696
|
+
isEnabled: () => state.enabled
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
});
|
|
700
|
+
pi.registerTool({
|
|
701
|
+
name: PLAN_MODE_COMPLETE_TOOL_NAME,
|
|
702
|
+
label: "Complete plan",
|
|
703
|
+
description: "Submit the complete decision-ready implementation plan for user review. Only available while Plan mode is active, and must be the final standalone action.",
|
|
704
|
+
promptSnippet: "Submit the final Plan-mode implementation plan",
|
|
705
|
+
promptGuidelines: [
|
|
706
|
+
"Call plan_mode_complete alone as the final action only after the implementation plan is decision-complete."
|
|
707
|
+
],
|
|
708
|
+
parameters: PLAN_MODE_COMPLETE_PARAMS,
|
|
709
|
+
renderResult: renderPlanModeCompletion,
|
|
710
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
711
|
+
if (!state.enabled) {
|
|
712
|
+
throw new Error("plan_mode_complete is only available while Plan mode is active");
|
|
713
|
+
}
|
|
714
|
+
const parsed = normalizePlanModeCompletion(params);
|
|
715
|
+
if (!parsed.ok) throw new Error(parsed.error);
|
|
716
|
+
acceptCompletedPlan(parsed.plan, PLAN_MODE_COMPLETE_TOOL_NAME, ctx);
|
|
717
|
+
return planModeCompleted(parsed.plan);
|
|
718
|
+
}
|
|
719
|
+
});
|
|
720
|
+
pi.registerCommand("plan", {
|
|
721
|
+
description: "Enter or manage Codex-like Plan mode",
|
|
722
|
+
getArgumentCompletions: completePlanArguments,
|
|
723
|
+
handler: async (args, ctx) => {
|
|
724
|
+
latestCommandContext = ctx;
|
|
725
|
+
const prompt = args.trim();
|
|
726
|
+
const command = prompt.toLowerCase();
|
|
727
|
+
if (command === "start") {
|
|
728
|
+
if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled))
|
|
729
|
+
return;
|
|
730
|
+
if (state.enabled) {
|
|
731
|
+
ctx.ui.notify("Plan mode is already active.", "info");
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
enterPlanMode(ctx);
|
|
735
|
+
ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
if (command === "show") {
|
|
739
|
+
showStoredPlan(pi, ctx, state);
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (command === "finalize") {
|
|
743
|
+
requestFinalPlan(ctx);
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
if (command === "implement") {
|
|
747
|
+
if (!(state.enabled && state.latestPlan?.trim()) && !state.savedPlan?.plan.trim()) {
|
|
748
|
+
ctx.ui.notify("No completed plan is available to implement.", "warning");
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
await startImplementation(ctx);
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (command === "save") {
|
|
755
|
+
savePlanForLater(ctx);
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
|
|
759
|
+
if (exportMatch) {
|
|
760
|
+
const lifecycle = captureMenuLifecycle();
|
|
761
|
+
await planExports.export(exportMatch[1], ctx, lifecycle.signal, lifecycle.isCurrent);
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (command === "exit" || command === "off") {
|
|
765
|
+
ctx.ui.notify(planModeDisableNotification(), "info");
|
|
766
|
+
exitPlanMode(ctx);
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
if (command === "tools") {
|
|
770
|
+
if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled))
|
|
771
|
+
return;
|
|
772
|
+
if (state.enabled) {
|
|
773
|
+
const message = "Plan-mode tools are locked while Planning is active. Exit Plan mode and choose tools before starting again.";
|
|
774
|
+
if (!ctx.hasUI) throw new Error(message);
|
|
775
|
+
ctx.ui.notify(message, "warning");
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
if (!ctx.hasUI) {
|
|
779
|
+
throw new Error("/plan tools requires TUI or RPC mode and is unavailable here.");
|
|
780
|
+
}
|
|
781
|
+
await showLaunchMenu(ctx, "tools");
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
if (prompt) {
|
|
785
|
+
if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled))
|
|
786
|
+
return;
|
|
787
|
+
enterPlanModeWithPrompt(prompt, ctx);
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
if (!ctx.hasUI) {
|
|
791
|
+
throw new Error(
|
|
792
|
+
"The interactive /plan menu is unavailable in print and JSON modes. Use /plan start or /plan <prompt>."
|
|
793
|
+
);
|
|
794
|
+
}
|
|
795
|
+
if (!state.enabled) {
|
|
796
|
+
if (state.activeImplementation && ctx.hasUI) {
|
|
797
|
+
await showActivePlanMenu(ctx);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
if (state.savedPlan) {
|
|
801
|
+
await planActions.showSaved(ctx);
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
await showLaunchMenu(ctx);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
await planActions.showCurrent(ctx);
|
|
808
|
+
}
|
|
809
|
+
});
|
|
810
|
+
const applyPlanModeShortcut = (nextShortcut) => {
|
|
811
|
+
if (toggleShortcut && toggleShortcut !== nextShortcut) {
|
|
812
|
+
pi.registerShortcut(toggleShortcut, {
|
|
813
|
+
handler: clearPlanModeShortcutHandler
|
|
814
|
+
});
|
|
815
|
+
}
|
|
816
|
+
if (!nextShortcut) {
|
|
817
|
+
toggleShortcut = void 0;
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
if (toggleShortcut === nextShortcut) return;
|
|
821
|
+
pi.registerShortcut(nextShortcut, {
|
|
822
|
+
description: "Toggle Plan mode",
|
|
823
|
+
handler: (ctx) => {
|
|
824
|
+
togglePlanMode(ctx);
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
toggleShortcut = nextShortcut;
|
|
828
|
+
};
|
|
829
|
+
const readPlanModeRuntimeSettings = async () => {
|
|
830
|
+
return dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);
|
|
831
|
+
};
|
|
832
|
+
const applyPlanModeSettings = async (generation, ctx, showWarnings) => {
|
|
833
|
+
const loadedSettings = await readPlanModeRuntimeSettings();
|
|
834
|
+
if (generation !== menuGeneration || menuController.signal.aborted) {
|
|
835
|
+
return void 0;
|
|
836
|
+
}
|
|
837
|
+
if (loadedSettings.kind === "loaded") {
|
|
838
|
+
settings = loadedSettings.settings;
|
|
839
|
+
} else {
|
|
840
|
+
settings = { thinkingLevel: "inherit" };
|
|
841
|
+
}
|
|
842
|
+
applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
|
|
843
|
+
if (!ctx || !showWarnings) return loadedSettings;
|
|
844
|
+
if (loadedSettings.kind === "invalid") {
|
|
845
|
+
ctx.ui.notify(`pi-plan-mode settings ignored: ${loadedSettings.reason}`, "warning");
|
|
846
|
+
}
|
|
847
|
+
if (loadedSettings.notice) {
|
|
848
|
+
ctx.ui.notify(loadedSettings.notice, "warning");
|
|
849
|
+
}
|
|
850
|
+
return loadedSettings;
|
|
851
|
+
};
|
|
852
|
+
const stopPlanModeSettingsWatch = () => {
|
|
853
|
+
if (settingsReloadTimer) {
|
|
854
|
+
clearTimeout(settingsReloadTimer);
|
|
855
|
+
settingsReloadTimer = void 0;
|
|
856
|
+
}
|
|
857
|
+
settingsWatch?.close();
|
|
858
|
+
settingsWatch = void 0;
|
|
859
|
+
};
|
|
860
|
+
const schedulePlanModeSettingsReload = (generation) => {
|
|
861
|
+
if (settingsReloadTimer) {
|
|
862
|
+
clearTimeout(settingsReloadTimer);
|
|
863
|
+
settingsReloadTimer = void 0;
|
|
864
|
+
}
|
|
865
|
+
settingsReloadTimer = setTimeout(() => {
|
|
866
|
+
settingsReloadTimer = void 0;
|
|
867
|
+
void applyPlanModeSettings(generation, void 0, false);
|
|
868
|
+
}, 75);
|
|
869
|
+
};
|
|
870
|
+
const startPlanModeSettingsWatch = (generation) => {
|
|
871
|
+
stopPlanModeSettingsWatch();
|
|
872
|
+
if (dependencies.readSettings) return;
|
|
873
|
+
const pathToWatch = explicitPlanModeSettingsPath ?? planModeSettingsPath();
|
|
874
|
+
try {
|
|
875
|
+
const directory = dirname(pathToWatch);
|
|
876
|
+
const fileName = basename(pathToWatch);
|
|
877
|
+
const watcher = watch(directory, { persistent: false }, (event, changedFile) => {
|
|
878
|
+
if (event !== "rename" && event !== "change") return;
|
|
879
|
+
if (!changedFile || changedFile.toString() !== fileName) return;
|
|
880
|
+
schedulePlanModeSettingsReload(generation);
|
|
881
|
+
});
|
|
882
|
+
watcher.on("error", () => {
|
|
883
|
+
stopPlanModeSettingsWatch();
|
|
884
|
+
});
|
|
885
|
+
settingsWatch = watcher;
|
|
886
|
+
} catch {
|
|
887
|
+
stopPlanModeSettingsWatch();
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
pi.on("session_start", async (event, ctx) => {
|
|
891
|
+
const generation = ++menuGeneration;
|
|
892
|
+
refreshStateBeforeFirstAgentStart = event.reason === "new";
|
|
893
|
+
menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
|
|
894
|
+
menuController = new AbortController();
|
|
895
|
+
readyPresentationIntent = void 0;
|
|
896
|
+
latestCommandContext = void 0;
|
|
897
|
+
implementationRetention.reset();
|
|
898
|
+
settings = { thinkingLevel: "inherit" };
|
|
899
|
+
restoreState(ctx);
|
|
900
|
+
implementationRetention.restore(state.activeImplementation);
|
|
901
|
+
await applyPlanModeSettings(generation, ctx, true);
|
|
902
|
+
if (generation !== menuGeneration || menuController.signal.aborted) return;
|
|
903
|
+
startPlanModeSettingsWatch(generation);
|
|
904
|
+
const persistFlagActivation = pi.getFlag("plan") === true && !state.enabled;
|
|
905
|
+
if (persistFlagActivation) {
|
|
906
|
+
state = state.savedPlan ? {
|
|
907
|
+
...state,
|
|
908
|
+
enabled: true,
|
|
909
|
+
latestPlan: state.savedPlan.plan,
|
|
910
|
+
latestPlanSource: state.savedPlan.source,
|
|
911
|
+
awaitingAction: true,
|
|
912
|
+
savedPlan: void 0,
|
|
913
|
+
activeImplementation: void 0
|
|
914
|
+
} : { ...state, enabled: true, activeImplementation: void 0 };
|
|
915
|
+
}
|
|
916
|
+
if (state.enabled) {
|
|
917
|
+
activatePlanModeTools();
|
|
918
|
+
applyPlanThinkingLevel();
|
|
919
|
+
} else deactivatePlanModeQuestionTool();
|
|
920
|
+
if (persistFlagActivation) persistState();
|
|
921
|
+
updateUi(ctx);
|
|
922
|
+
});
|
|
923
|
+
pi.on("thinking_level_select", (event) => {
|
|
924
|
+
if (!state.enabled || !state.appliedThinkingLevel) return;
|
|
925
|
+
if (event.level !== state.appliedThinkingLevel) {
|
|
926
|
+
state = {
|
|
927
|
+
...state,
|
|
928
|
+
manualThinkingLevel: event.level,
|
|
929
|
+
previousThinkingLevel: void 0,
|
|
930
|
+
appliedThinkingLevel: void 0
|
|
931
|
+
};
|
|
932
|
+
persistState();
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
936
|
+
menuGeneration += 1;
|
|
937
|
+
menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
|
|
938
|
+
readyPresentationIntent = void 0;
|
|
939
|
+
latestCommandContext = void 0;
|
|
940
|
+
refreshStateBeforeFirstAgentStart = false;
|
|
941
|
+
implementationRetention.reset();
|
|
942
|
+
await awaitPlanModeSettingsWrites(dependencies.settingsPath);
|
|
943
|
+
captureManualThinkingLevel();
|
|
944
|
+
persistState();
|
|
945
|
+
if (state.enabled) {
|
|
946
|
+
restoreTools();
|
|
947
|
+
restoreThinkingLevel();
|
|
948
|
+
}
|
|
949
|
+
stopPlanModeSettingsWatch();
|
|
950
|
+
clearUi(ctx);
|
|
951
|
+
});
|
|
952
|
+
pi.on("tool_call", async (event) => {
|
|
953
|
+
if (!state.enabled) return;
|
|
954
|
+
if (event.toolName === "update_plan") {
|
|
955
|
+
return {
|
|
956
|
+
block: true,
|
|
957
|
+
reason: "Plan mode blocks update_plan because it tracks execution progress rather than conversational planning."
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
const calledTool = toolByName(event.toolName);
|
|
961
|
+
if (calledTool && classifyPlanModeTool(calledTool) === "blocked") {
|
|
962
|
+
return {
|
|
963
|
+
block: true,
|
|
964
|
+
reason: `Plan mode blocks built-in tool '${event.toolName}' because its policy class is blocked.`
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
if (!calledTool && BLOCKED_BUILTIN_TOOLS.has(event.toolName)) {
|
|
968
|
+
return {
|
|
969
|
+
block: true,
|
|
970
|
+
reason: `Plan mode blocks built-in tool '${event.toolName}' because its metadata is unavailable.`
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
if (event.toolName !== "bash") return;
|
|
974
|
+
const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);
|
|
975
|
+
if (blocked !== void 0) {
|
|
976
|
+
return {
|
|
977
|
+
block: true,
|
|
978
|
+
reason: `Plan mode blocks bash commands outside its reviewed inspection policy or containing explicitly unsafe arguments.
|
|
979
|
+
Blocked command: ${blocked}`
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
});
|
|
983
|
+
pi.on("context", async (event, ctx) => {
|
|
984
|
+
const result = implementationRetention.transformContext(event.messages, state);
|
|
985
|
+
if (result.clearActiveImplementationId) {
|
|
986
|
+
clearActiveImplementation(result.clearActiveImplementationId, ctx);
|
|
987
|
+
}
|
|
988
|
+
return { messages: result.messages };
|
|
989
|
+
});
|
|
990
|
+
pi.on("before_agent_start", (event, ctx) => {
|
|
991
|
+
if (refreshStateBeforeFirstAgentStart) {
|
|
992
|
+
refreshStateBeforeFirstAgentStart = false;
|
|
993
|
+
restoreState(ctx);
|
|
994
|
+
implementationRetention.reset();
|
|
995
|
+
implementationRetention.restore(state.activeImplementation);
|
|
996
|
+
if (state.enabled) {
|
|
997
|
+
activatePlanModeTools();
|
|
998
|
+
applyPlanThinkingLevel();
|
|
999
|
+
} else deactivatePlanModeQuestionTool();
|
|
1000
|
+
updateUi(ctx);
|
|
1001
|
+
}
|
|
1002
|
+
if (!state.enabled) return;
|
|
1003
|
+
if (state.latestPlan || state.awaitingAction) {
|
|
1004
|
+
readyPresentationIntent = void 0;
|
|
1005
|
+
state = {
|
|
1006
|
+
...state,
|
|
1007
|
+
latestPlan: void 0,
|
|
1008
|
+
latestPlanSource: void 0,
|
|
1009
|
+
awaitingAction: false
|
|
1010
|
+
};
|
|
1011
|
+
persistState();
|
|
1012
|
+
updateUi(ctx);
|
|
1013
|
+
}
|
|
1014
|
+
applyPlanModeTools();
|
|
1015
|
+
return {
|
|
1016
|
+
systemPrompt: `${event.systemPrompt}
|
|
1017
|
+
|
|
1018
|
+
${buildPlanModePrompt()}`
|
|
1019
|
+
};
|
|
1020
|
+
});
|
|
1021
|
+
pi.on("agent_end", async (event, ctx) => {
|
|
1022
|
+
if (!state.enabled) return;
|
|
1023
|
+
const text = latestAssistantText(event.messages);
|
|
1024
|
+
const parsedPlan = parseProposedPlan(text);
|
|
1025
|
+
if (parsedPlan.kind !== "valid") {
|
|
1026
|
+
if (parsedPlan.kind !== "absent") {
|
|
1027
|
+
ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
|
|
1028
|
+
}
|
|
1029
|
+
persistState();
|
|
1030
|
+
updateUi(ctx);
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
acceptCompletedPlan(parsedPlan.plan, "legacy_proposed_plan", ctx);
|
|
1034
|
+
});
|
|
1035
|
+
onAgentSettled(pi, async (_event, ctx) => {
|
|
1036
|
+
const settledImplementationId = implementationRetention.implementationSettled(
|
|
1037
|
+
state.activeImplementation
|
|
1038
|
+
);
|
|
1039
|
+
if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
|
|
1040
|
+
const intent = readyPresentationIntent;
|
|
1041
|
+
if (!intent || !readyPresentationIsCurrent(intent)) return;
|
|
1042
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
|
|
1043
|
+
readyPresentationIntent = void 0;
|
|
1044
|
+
try {
|
|
1045
|
+
if (intent.source === "legacy_proposed_plan") {
|
|
1046
|
+
pi.sendMessage(
|
|
1047
|
+
{
|
|
1048
|
+
customType: PROPOSED_PLAN_MESSAGE_TYPE,
|
|
1049
|
+
content: `**Proposed Plan**
|
|
1050
|
+
|
|
1051
|
+
${intent.plan}`,
|
|
1052
|
+
display: true
|
|
1053
|
+
},
|
|
1054
|
+
{ triggerTurn: false }
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
if (ctx.hasUI && completedPlanIsCurrent(intent)) {
|
|
1058
|
+
await planActions.showReady(latestCommandContext ?? ctx);
|
|
1059
|
+
}
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
if (!isStaleExtensionContextError(error)) throw error;
|
|
1062
|
+
}
|
|
1063
|
+
});
|
|
1064
|
+
function enterPlanMode(ctx) {
|
|
1065
|
+
workflowGeneration += 1;
|
|
1066
|
+
if (!state.enabled) previousTools = withoutRequiredPlanModeTools(safeGetActiveTools());
|
|
1067
|
+
state = {
|
|
1068
|
+
...state,
|
|
1069
|
+
enabled: true,
|
|
1070
|
+
awaitingAction: false,
|
|
1071
|
+
savedPlan: void 0,
|
|
1072
|
+
activeImplementation: void 0
|
|
1073
|
+
};
|
|
1074
|
+
activatePlanModeTools();
|
|
1075
|
+
applyPlanThinkingLevel();
|
|
1076
|
+
persistState();
|
|
1077
|
+
updateUi(ctx);
|
|
1078
|
+
}
|
|
1079
|
+
function enterPlanModeWithPrompt(prompt, ctx) {
|
|
1080
|
+
const previousState = state;
|
|
1081
|
+
const wasEnabled = state.enabled;
|
|
1082
|
+
enterPlanMode(ctx);
|
|
1083
|
+
if (!wasEnabled) {
|
|
1084
|
+
ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
|
|
1085
|
+
}
|
|
1086
|
+
if (sendPlanModeUserMessage(prompt, ctx)) return;
|
|
1087
|
+
if (!previousState.enabled) {
|
|
1088
|
+
restoreTools();
|
|
1089
|
+
restoreThinkingLevel();
|
|
1090
|
+
}
|
|
1091
|
+
state = previousState;
|
|
1092
|
+
persistState();
|
|
1093
|
+
updateUi(ctx);
|
|
1094
|
+
}
|
|
1095
|
+
function exitPlanMode(ctx) {
|
|
1096
|
+
workflowGeneration += 1;
|
|
1097
|
+
const wasEnabled = state.enabled;
|
|
1098
|
+
readyPresentationIntent = void 0;
|
|
1099
|
+
state = {
|
|
1100
|
+
...state,
|
|
1101
|
+
enabled: false,
|
|
1102
|
+
latestPlan: void 0,
|
|
1103
|
+
latestPlanSource: void 0,
|
|
1104
|
+
awaitingAction: false,
|
|
1105
|
+
savedPlan: void 0,
|
|
1106
|
+
activeImplementation: void 0,
|
|
1107
|
+
manualThinkingLevel: void 0
|
|
1108
|
+
};
|
|
1109
|
+
if (wasEnabled) {
|
|
1110
|
+
restoreTools();
|
|
1111
|
+
restoreThinkingLevel();
|
|
1112
|
+
state = { ...state, manualThinkingLevel: void 0 };
|
|
1113
|
+
}
|
|
1114
|
+
persistState();
|
|
1115
|
+
updateUi(ctx);
|
|
1116
|
+
}
|
|
1117
|
+
function sendPlanModeUserMessage(message, ctx) {
|
|
1118
|
+
try {
|
|
1119
|
+
if (ctx.isIdle()) pi.sendUserMessage(message);
|
|
1120
|
+
else pi.sendUserMessage(message, { deliverAs: "followUp" });
|
|
1121
|
+
return true;
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1124
|
+
ctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, "error");
|
|
1125
|
+
return false;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
function acceptCompletedPlan(plan, source, ctx) {
|
|
1129
|
+
const normalized = normalizePlanModeCompletion({ plan });
|
|
1130
|
+
if (!normalized.ok) {
|
|
1131
|
+
ctx.ui.notify(`Proposed plan is not ready: ${normalized.error}.`, "warning");
|
|
1132
|
+
persistState();
|
|
1133
|
+
updateUi(ctx);
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
if (state.enabled && state.awaitingAction && state.latestPlan === normalized.plan && state.latestPlanSource === source) {
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
state = {
|
|
1140
|
+
...state,
|
|
1141
|
+
latestPlan: normalized.plan,
|
|
1142
|
+
latestPlanSource: source,
|
|
1143
|
+
awaitingAction: true
|
|
1144
|
+
};
|
|
1145
|
+
readyPresentationIntent = {
|
|
1146
|
+
nonce: ++nextReadyPresentationNonce,
|
|
1147
|
+
plan: normalized.plan,
|
|
1148
|
+
source
|
|
1149
|
+
};
|
|
1150
|
+
persistState();
|
|
1151
|
+
updateUi(ctx);
|
|
1152
|
+
}
|
|
1153
|
+
function completedPlanIsCurrent(intent) {
|
|
1154
|
+
return state.enabled && state.awaitingAction && state.latestPlan === intent.plan && state.latestPlanSource === intent.source;
|
|
1155
|
+
}
|
|
1156
|
+
function readyPresentationIsCurrent(intent) {
|
|
1157
|
+
return completedPlanIsCurrent(intent) && readyPresentationIntent?.nonce === intent.nonce;
|
|
1158
|
+
}
|
|
1159
|
+
function togglePlanMode(ctx) {
|
|
1160
|
+
if (state.enabled) {
|
|
1161
|
+
ctx.ui.notify(planModeDisableNotification(), "info");
|
|
1162
|
+
exitPlanMode(ctx);
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0)) return;
|
|
1166
|
+
enterPlanMode(ctx);
|
|
1167
|
+
ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
|
|
1168
|
+
}
|
|
1169
|
+
function planModeDisableNotification() {
|
|
1170
|
+
return state.activeImplementation ? "Active implementation plan cleared." : state.savedPlan ? "Saved plan cleared." : state.latestPlan ? "Plan mode disabled. Proposed plan discarded." : "Plan mode disabled.";
|
|
1171
|
+
}
|
|
1172
|
+
function requestFinalPlan(ctx) {
|
|
1173
|
+
if (!state.enabled) {
|
|
1174
|
+
ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
|
|
1175
|
+
return;
|
|
1176
|
+
}
|
|
1177
|
+
sendPlanModeUserMessage(
|
|
1178
|
+
"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.",
|
|
1179
|
+
ctx
|
|
1180
|
+
);
|
|
1181
|
+
}
|
|
1182
|
+
function savePlanForLater(ctx) {
|
|
1183
|
+
const plan = state.enabled ? state.latestPlan?.trim() : void 0;
|
|
1184
|
+
if (!plan) {
|
|
1185
|
+
const message = "No completed plan is available to save.";
|
|
1186
|
+
if (!ctx.hasUI) throw new Error(message);
|
|
1187
|
+
ctx.ui.notify(message, "warning");
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
const source = state.latestPlanSource ?? "legacy_proposed_plan";
|
|
1191
|
+
workflowGeneration += 1;
|
|
1192
|
+
readyPresentationIntent = void 0;
|
|
1193
|
+
state = {
|
|
1194
|
+
...state,
|
|
1195
|
+
enabled: false,
|
|
1196
|
+
latestPlan: void 0,
|
|
1197
|
+
latestPlanSource: void 0,
|
|
1198
|
+
awaitingAction: false,
|
|
1199
|
+
savedPlan: { plan, source },
|
|
1200
|
+
activeImplementation: void 0,
|
|
1201
|
+
manualThinkingLevel: void 0
|
|
1202
|
+
};
|
|
1203
|
+
restoreTools();
|
|
1204
|
+
restoreThinkingLevel();
|
|
1205
|
+
state = { ...state, manualThinkingLevel: void 0 };
|
|
1206
|
+
persistState();
|
|
1207
|
+
updateUi(ctx);
|
|
1208
|
+
ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
|
|
1209
|
+
}
|
|
1210
|
+
async function startFreshImplementation(ctx, menuIsCurrent) {
|
|
1211
|
+
await startFreshImplementationFromState(ctx, {
|
|
1212
|
+
getState: () => state,
|
|
1213
|
+
menuIsCurrent,
|
|
1214
|
+
retention: configuredImplementationPlanRetention(settings),
|
|
1215
|
+
stateEntryType: STATE_ENTRY_TYPE
|
|
1216
|
+
});
|
|
1217
|
+
}
|
|
1218
|
+
async function startImplementation(ctx) {
|
|
1219
|
+
const savedPlan = state.enabled ? void 0 : state.savedPlan;
|
|
1220
|
+
if (savedPlan) {
|
|
1221
|
+
const sessionGeneration = menuGeneration;
|
|
1222
|
+
const planWorkflowGeneration = workflowGeneration;
|
|
1223
|
+
const isCurrent = () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !menuController.signal.aborted && !state.enabled && state.savedPlan === savedPlan;
|
|
1224
|
+
if (!await preflightSavedPlanImplementation(ctx, isCurrent)) return;
|
|
1225
|
+
}
|
|
1226
|
+
const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
|
|
1227
|
+
const source = (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? "legacy_proposed_plan";
|
|
1228
|
+
if (!plan) {
|
|
1229
|
+
ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
workflowGeneration += 1;
|
|
1233
|
+
const previousState = state;
|
|
1234
|
+
const wasEnabled = state.enabled;
|
|
1235
|
+
readyPresentationIntent = void 0;
|
|
1236
|
+
state = {
|
|
1237
|
+
...state,
|
|
1238
|
+
enabled: false,
|
|
1239
|
+
latestPlan: void 0,
|
|
1240
|
+
latestPlanSource: void 0,
|
|
1241
|
+
awaitingAction: false,
|
|
1242
|
+
savedPlan: void 0,
|
|
1243
|
+
activeImplementation: {
|
|
1244
|
+
id: randomUUID2(),
|
|
1245
|
+
plan,
|
|
1246
|
+
source,
|
|
1247
|
+
startedAt: Date.now(),
|
|
1248
|
+
retention: configuredImplementationPlanRetention(settings)
|
|
1249
|
+
},
|
|
1250
|
+
manualThinkingLevel: void 0
|
|
1251
|
+
};
|
|
1252
|
+
if (wasEnabled) {
|
|
1253
|
+
restoreTools();
|
|
1254
|
+
restoreThinkingLevel();
|
|
1255
|
+
state = { ...state, manualThinkingLevel: void 0 };
|
|
1256
|
+
}
|
|
1257
|
+
persistState();
|
|
1258
|
+
updateUi(ctx);
|
|
1259
|
+
const sent = sendPlanModeUserMessage(formatImplementationHandoff(plan), ctx);
|
|
1260
|
+
if (!sent) {
|
|
1261
|
+
if (savedPlan) {
|
|
1262
|
+
state = previousState;
|
|
1263
|
+
} else {
|
|
1264
|
+
enterPlanMode(ctx);
|
|
1265
|
+
state = previousState;
|
|
1266
|
+
applyPlanThinkingLevel();
|
|
1267
|
+
}
|
|
1268
|
+
persistState();
|
|
1269
|
+
updateUi(ctx);
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
function clearActiveImplementation(id, ctx) {
|
|
1273
|
+
if (state.activeImplementation?.id !== id) return false;
|
|
1274
|
+
workflowGeneration += 1;
|
|
1275
|
+
state = { ...state, activeImplementation: void 0 };
|
|
1276
|
+
persistState();
|
|
1277
|
+
updateUi(ctx);
|
|
1278
|
+
return true;
|
|
1279
|
+
}
|
|
1280
|
+
async function showLaunchMenu(ctx, initialScreen = "main") {
|
|
1281
|
+
const lifecycle = captureMenuLifecycle();
|
|
1282
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
1283
|
+
const ui = await loadInteractiveUi();
|
|
1284
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
1285
|
+
const tools = selectableTools();
|
|
1286
|
+
await ui.showPlanLaunchMenu(ctx, {
|
|
1287
|
+
statusText: "Status: Off \u2014 normal tools are active.",
|
|
1288
|
+
initialScreen,
|
|
1289
|
+
getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
|
|
1290
|
+
toolSummary: (selectedNames) => `When started: ${snapshotPlanModeToolNames(tools, selectedNames, toolSelectionSnapshot()).join(", ")}`,
|
|
1291
|
+
tools: tools.map((tool) => {
|
|
1292
|
+
const selectable = canSelectToolInPlanMode(tool);
|
|
1293
|
+
const policy = toolPolicyLabel(tool);
|
|
1294
|
+
const description = tool.description ?? "No description available";
|
|
1295
|
+
return {
|
|
1296
|
+
name: tool.name,
|
|
1297
|
+
description: `${policy} \xB7 ${description}`,
|
|
1298
|
+
searchText: [policy, description].join(" "),
|
|
1299
|
+
disabled: !selectable,
|
|
1300
|
+
disabledReason: selectable ? void 0 : "Blocked by Plan-mode policy"
|
|
1301
|
+
};
|
|
1302
|
+
}),
|
|
1303
|
+
...lifecycle,
|
|
1304
|
+
start: (signal) => {
|
|
1305
|
+
if (signal.aborted || !lifecycle.isCurrent()) return;
|
|
1306
|
+
enterPlanMode(ctx);
|
|
1307
|
+
ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
|
|
1308
|
+
},
|
|
1309
|
+
startWithTools: (names, signal) => {
|
|
1310
|
+
if (signal.aborted || !lifecycle.isCurrent()) return;
|
|
1311
|
+
state = {
|
|
1312
|
+
...state,
|
|
1313
|
+
selectedToolNames: filterAvailableSelectedToolNames(names, tools),
|
|
1314
|
+
selectedToolKeys: void 0
|
|
1315
|
+
};
|
|
1316
|
+
enterPlanMode(ctx);
|
|
1317
|
+
ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
|
|
1318
|
+
},
|
|
1319
|
+
settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent)
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
async function showActivePlanMenu(ctx) {
|
|
1323
|
+
if (!ctx.hasUI) {
|
|
1324
|
+
ctx.ui.notify(planStatusText(), "info");
|
|
1325
|
+
return;
|
|
1326
|
+
}
|
|
1327
|
+
const lifecycle = captureMenuLifecycle();
|
|
1328
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
1329
|
+
const ui = await loadInteractiveUi();
|
|
1330
|
+
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
1331
|
+
await ui.showActiveImplementationMenu(ctx, {
|
|
1332
|
+
statusText: planStatusText(),
|
|
1333
|
+
getExportDestination: () => planExports.getDestination(ctx),
|
|
1334
|
+
signal: lifecycle.signal,
|
|
1335
|
+
isCurrent: lifecycle.isCurrent,
|
|
1336
|
+
show: () => showStoredPlan(pi, ctx, state),
|
|
1337
|
+
exportPlan: (path, signal) => planExports.export(path, ctx, signal, lifecycle.isCurrent),
|
|
1338
|
+
settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
|
|
1339
|
+
startNew: () => {
|
|
1340
|
+
enterPlanMode(ctx);
|
|
1341
|
+
ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
|
|
1342
|
+
},
|
|
1343
|
+
clear: () => {
|
|
1344
|
+
exitPlanMode(ctx);
|
|
1345
|
+
ctx.ui.notify("Active implementation plan cleared.", "info");
|
|
1346
|
+
}
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1349
|
+
async function showSettings(ctx, signal, isCurrent) {
|
|
1350
|
+
if (!isCurrent() || signal.aborted) return false;
|
|
1351
|
+
const ui = await loadInteractiveUi();
|
|
1352
|
+
if (!isCurrent() || signal.aborted) return false;
|
|
1353
|
+
const result = await ui.showPlanModeSettings(ctx, {
|
|
1354
|
+
tools: selectableTools(),
|
|
1355
|
+
signal,
|
|
1356
|
+
isCurrent,
|
|
1357
|
+
settingsPath: dependencies.settingsPath,
|
|
1358
|
+
onSaved: (saved) => {
|
|
1359
|
+
if (!isCurrent()) return;
|
|
1360
|
+
settings = saved;
|
|
1361
|
+
applyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));
|
|
1362
|
+
},
|
|
1363
|
+
...dependencies.readSettings ? { readSettings: async () => dependencies.readSettings?.() ?? { kind: "missing" } } : {}
|
|
1364
|
+
});
|
|
1365
|
+
return result.kind === "closed" && "reason" in result && result.reason === "close";
|
|
1366
|
+
}
|
|
1367
|
+
function captureMenuLifecycle() {
|
|
1368
|
+
const sessionGeneration = menuGeneration;
|
|
1369
|
+
const planWorkflowGeneration = workflowGeneration;
|
|
1370
|
+
const controller = menuController;
|
|
1371
|
+
return {
|
|
1372
|
+
signal: controller.signal,
|
|
1373
|
+
isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
function activatePlanModeTools() {
|
|
1377
|
+
previousTools ??= withoutRequiredPlanModeTools(safeGetActiveTools());
|
|
1378
|
+
applyPlanModeTools();
|
|
1379
|
+
}
|
|
1380
|
+
function applyPlanModeTools() {
|
|
1381
|
+
pi.setActiveTools(planModeToolNames());
|
|
1382
|
+
}
|
|
1383
|
+
function planModeToolNames() {
|
|
1384
|
+
const tools = selectableTools();
|
|
1385
|
+
if (tools.length === 0 && state.selectedToolNames === void 0 && state.selectedToolKeys === void 0 && settings.defaultPlanTools === void 0) {
|
|
1386
|
+
return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
|
|
1387
|
+
}
|
|
1388
|
+
const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
|
|
1389
|
+
return withRequiredPlanModeTools(
|
|
1390
|
+
tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name)
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
function toolSelectionSnapshot() {
|
|
1394
|
+
return {
|
|
1395
|
+
selectedToolNames: state.selectedToolNames,
|
|
1396
|
+
selectedToolKeys: state.selectedToolKeys,
|
|
1397
|
+
defaultPlanTools: settings.defaultPlanTools
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
function selectableTools() {
|
|
1401
|
+
return safeGetAllTools().filter(
|
|
1402
|
+
(tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME
|
|
1403
|
+
).sort(compareTools);
|
|
1404
|
+
}
|
|
1405
|
+
function safeGetAllTools() {
|
|
1406
|
+
try {
|
|
1407
|
+
return pi.getAllTools();
|
|
1408
|
+
} catch {
|
|
1409
|
+
return [];
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
function restoreTools() {
|
|
1413
|
+
const restoredTools = previousTools ?? DEFAULT_TOOLS;
|
|
1414
|
+
pi.setActiveTools(withoutRequiredPlanModeTools(restoredTools));
|
|
1415
|
+
previousTools = void 0;
|
|
1416
|
+
}
|
|
1417
|
+
function applyPlanThinkingLevel() {
|
|
1418
|
+
if (state.manualThinkingLevel) {
|
|
1419
|
+
if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
|
|
1420
|
+
setPlanThinkingLevel(pi, state.manualThinkingLevel);
|
|
1421
|
+
}
|
|
1422
|
+
return;
|
|
1423
|
+
}
|
|
1424
|
+
const configured = configuredThinkingLevel(settings);
|
|
1425
|
+
if (!configured) {
|
|
1426
|
+
state = {
|
|
1427
|
+
...state,
|
|
1428
|
+
previousThinkingLevel: void 0,
|
|
1429
|
+
appliedThinkingLevel: void 0
|
|
1430
|
+
};
|
|
1431
|
+
return;
|
|
1432
|
+
}
|
|
1433
|
+
const current = pi.getThinkingLevel();
|
|
1434
|
+
if (!state.appliedThinkingLevel) state.previousThinkingLevel = current;
|
|
1435
|
+
if (current !== configured) setPlanThinkingLevel(pi, configured);
|
|
1436
|
+
state.appliedThinkingLevel = pi.getThinkingLevel();
|
|
1437
|
+
}
|
|
1438
|
+
function captureManualThinkingLevel() {
|
|
1439
|
+
if (!state.appliedThinkingLevel) return;
|
|
1440
|
+
const current = pi.getThinkingLevel();
|
|
1441
|
+
if (current === state.appliedThinkingLevel) return;
|
|
1442
|
+
state = {
|
|
1443
|
+
...state,
|
|
1444
|
+
manualThinkingLevel: current,
|
|
1445
|
+
previousThinkingLevel: void 0,
|
|
1446
|
+
appliedThinkingLevel: void 0
|
|
1447
|
+
};
|
|
1448
|
+
}
|
|
1449
|
+
function restoreThinkingLevel() {
|
|
1450
|
+
captureManualThinkingLevel();
|
|
1451
|
+
const { appliedThinkingLevel, previousThinkingLevel } = state;
|
|
1452
|
+
if (appliedThinkingLevel && previousThinkingLevel && pi.getThinkingLevel() === appliedThinkingLevel) {
|
|
1453
|
+
setPlanThinkingLevel(pi, previousThinkingLevel);
|
|
1454
|
+
}
|
|
1455
|
+
state = { ...state, appliedThinkingLevel: void 0, previousThinkingLevel: void 0 };
|
|
1456
|
+
}
|
|
1457
|
+
function deactivatePlanModeQuestionTool() {
|
|
1458
|
+
const activeTools = safeGetActiveTools();
|
|
1459
|
+
const filteredTools = withoutRequiredPlanModeTools(activeTools);
|
|
1460
|
+
if (filteredTools.length !== activeTools.length) {
|
|
1461
|
+
pi.setActiveTools(filteredTools);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
function safeGetActiveTools() {
|
|
1465
|
+
try {
|
|
1466
|
+
return pi.getActiveTools();
|
|
1467
|
+
} catch {
|
|
1468
|
+
return DEFAULT_TOOLS;
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
function restoreState(ctx) {
|
|
1472
|
+
state = restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
|
|
1473
|
+
}
|
|
1474
|
+
function updateUi(ctx) {
|
|
1475
|
+
updatePlanModeUi(ctx, state, formatToolSummary);
|
|
1476
|
+
}
|
|
1477
|
+
function clearUi(ctx) {
|
|
1478
|
+
clearPlanModeUi(ctx);
|
|
1479
|
+
}
|
|
1480
|
+
function planStatusText() {
|
|
1481
|
+
return planModeStatusText(state, formatToolSummary);
|
|
1482
|
+
}
|
|
1483
|
+
function implementationOutcome() {
|
|
1484
|
+
return implementationRetentionPreview(configuredImplementationPlanRetention(settings));
|
|
1485
|
+
}
|
|
1486
|
+
function formatToolSummary() {
|
|
1487
|
+
const names = planModeToolNames();
|
|
1488
|
+
return `Tools: ${names.length > 0 ? names.join(", ") : "none"}`;
|
|
1489
|
+
}
|
|
1490
|
+
function toolByName(toolName) {
|
|
1491
|
+
return safeGetAllTools().find((candidate) => candidate.name === toolName);
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
export {
|
|
1495
|
+
planMode as default
|
|
1496
|
+
};
|
|
1497
|
+
//# sourceMappingURL=index.ts.map
|