@narumitw/pi-plan-mode 0.52.0 → 0.54.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/README.md +143 -72
- package/dist/chunks/{chunk-H3RGWRY7.ts → chunk-U5CQ7RQX.js} +501 -294
- package/dist/chunks/chunk-U5CQ7RQX.js.map +7 -0
- package/dist/chunks/{interactive-ui-GFNX5OF4.ts → interactive-ui-W3VYAJIQ.js} +60 -24
- package/dist/chunks/interactive-ui-W3VYAJIQ.js.map +7 -0
- package/dist/index.ts +856 -270
- package/dist/index.ts.map +3 -3
- package/package.json +5 -5
- package/src/extension-runtime.ts +0 -17
- package/src/finalization-request.ts +57 -0
- package/src/fresh-implementation.ts +73 -27
- package/src/helper-tool-visibility.ts +142 -0
- package/src/implementation-retention.ts +43 -19
- package/src/message-transform.ts +130 -6
- package/src/mode-contract.ts +93 -0
- package/src/plan-launch-menu.ts +4 -4
- package/src/plan-mode.ts +586 -190
- package/src/presentation.ts +50 -17
- package/src/prompt.ts +3 -1
- package/src/required-tools.ts +0 -4
- package/src/settings-menu.ts +67 -17
- package/src/settings.ts +21 -2
- package/src/tool-policy.ts +137 -2
- package/src/tool-selection.ts +0 -23
- package/dist/chunks/chunk-H3RGWRY7.ts.map +0 -7
- package/dist/chunks/interactive-ui-GFNX5OF4.ts.map +0 -7
package/dist/index.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
-
// @ts-nocheck -- generated
|
|
2
|
+
// @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
|
|
3
3
|
import {
|
|
4
4
|
IMPLEMENTATION_PLAN_RETENTIONS,
|
|
5
|
+
PLAN_HISTORY_IMPLEMENTATION_PROMPT,
|
|
5
6
|
PLAN_MODE_COMPLETE_PARAMS,
|
|
6
7
|
PLAN_MODE_COMPLETE_TOOL_NAME,
|
|
7
8
|
PLAN_MODE_QUESTION_PARAMS,
|
|
@@ -15,14 +16,18 @@ import {
|
|
|
15
16
|
configuredImplementationPlanRetention,
|
|
16
17
|
configuredPlanExportPath,
|
|
17
18
|
configuredPlanModeToggleShortcut,
|
|
19
|
+
configuredPlanModeToolVisibility,
|
|
18
20
|
configuredThinkingLevel,
|
|
19
21
|
createImplementationRetentionCoordinator,
|
|
20
22
|
exportStoredPlan,
|
|
21
23
|
filterAvailableSelectedToolNames,
|
|
22
24
|
findBlockedCommandSegment,
|
|
25
|
+
findBlockedPowerShellCommandSegment,
|
|
23
26
|
implementationRetentionPreview,
|
|
24
27
|
invalidPlanMessage,
|
|
28
|
+
latestAssistantStopReason,
|
|
25
29
|
latestAssistantText,
|
|
30
|
+
messageTextContent,
|
|
26
31
|
normalizePlanModeCompletion,
|
|
27
32
|
normalizePlanModeQuestionParams,
|
|
28
33
|
parseProposedPlan,
|
|
@@ -35,11 +40,10 @@ import {
|
|
|
35
40
|
readPlanModeSettings,
|
|
36
41
|
renderPlanModeCompletion,
|
|
37
42
|
snapshotPlanModeSelectedNames,
|
|
38
|
-
snapshotPlanModeToolNames,
|
|
39
43
|
toolPolicyLabel,
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
} from "./chunks/chunk-
|
|
44
|
+
unique,
|
|
45
|
+
updatePlanModeSettings
|
|
46
|
+
} from "./chunks/chunk-U5CQ7RQX.js";
|
|
43
47
|
|
|
44
48
|
// src/plan-mode.ts
|
|
45
49
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
@@ -71,21 +75,203 @@ function completePlanArguments(argumentPrefix) {
|
|
|
71
75
|
}
|
|
72
76
|
|
|
73
77
|
// 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
78
|
function isStaleExtensionContextError(error) {
|
|
81
79
|
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
80
|
}
|
|
83
81
|
|
|
82
|
+
// src/finalization-request.ts
|
|
83
|
+
var FINALIZE_PLAN_PROMPT = "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.";
|
|
84
|
+
var RETRY_FINALIZE_PLAN_PROMPT = "Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.";
|
|
85
|
+
function createFinalizationRequestCoordinator() {
|
|
86
|
+
let pending;
|
|
87
|
+
return {
|
|
88
|
+
request(workflowGeneration) {
|
|
89
|
+
pending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };
|
|
90
|
+
},
|
|
91
|
+
satisfy() {
|
|
92
|
+
pending = void 0;
|
|
93
|
+
},
|
|
94
|
+
observeRunEnd(workflowGeneration, outcome) {
|
|
95
|
+
if (!pending || pending.workflowGeneration !== workflowGeneration) return;
|
|
96
|
+
if (outcome !== "normal") {
|
|
97
|
+
pending = void 0;
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
pending.awaitingSettlement = true;
|
|
101
|
+
},
|
|
102
|
+
settle(workflowGeneration) {
|
|
103
|
+
if (!pending || pending.workflowGeneration !== workflowGeneration || !pending.awaitingSettlement) {
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
if (pending.retryCount === 0) {
|
|
107
|
+
pending.retryCount = 1;
|
|
108
|
+
pending.awaitingSettlement = false;
|
|
109
|
+
return "retry";
|
|
110
|
+
}
|
|
111
|
+
pending = void 0;
|
|
112
|
+
return "failed";
|
|
113
|
+
},
|
|
114
|
+
reset() {
|
|
115
|
+
pending = void 0;
|
|
116
|
+
},
|
|
117
|
+
hasPendingRequest() {
|
|
118
|
+
return pending !== void 0;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
84
123
|
// src/fresh-implementation.ts
|
|
85
124
|
import { randomUUID } from "node:crypto";
|
|
125
|
+
|
|
126
|
+
// src/prompt.ts
|
|
127
|
+
var PLAN_CONTEXT_MARKER = "[CODEX-LIKE PLAN MODE ACTIVE]";
|
|
128
|
+
function buildPlanModePrompt() {
|
|
129
|
+
return `${PLAN_CONTEXT_MARKER}
|
|
130
|
+
# Plan Mode (Conversational)
|
|
131
|
+
|
|
132
|
+
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.
|
|
133
|
+
|
|
134
|
+
## Mode rules
|
|
135
|
+
|
|
136
|
+
- Stay in Plan Mode until a developer or extension explicitly exits it.
|
|
137
|
+
- Treat requests to implement as requests to plan the implementation; do not edit files or carry out the plan.
|
|
138
|
+
- Do not use update_plan/TODO tooling in Plan Mode; Plan Mode is conversational planning, not execution progress tracking.
|
|
139
|
+
- Plan Mode keeps the session's model-visible tool schemas unchanged and enforces a runtime policy allowlist. Non-built-in tools are denied by default and may be allowed only when already active in Pi and explicitly selected by the user at their own risk.
|
|
140
|
+
- Do not perform mutating actions: no edit/write tools, no patching, no formatting that rewrites files, no dependency installation, no commits, no migrations.
|
|
141
|
+
|
|
142
|
+
## Phase 1 \u2014 Ground in the environment
|
|
143
|
+
|
|
144
|
+
- Explore first and ask second. Use non-mutating exploration to read files, search, inspect configuration, run read-only checks, and resolve discoverable facts.
|
|
145
|
+
- Before asking the user any question, perform at least one targeted non-mutating exploration pass unless no local environment or repository is available.
|
|
146
|
+
- 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.
|
|
147
|
+
|
|
148
|
+
## Phase 2 \u2014 Intent chat
|
|
149
|
+
|
|
150
|
+
- Keep asking until you can clearly state the goal, success criteria, in/out of scope, constraints, current state, and key preferences/tradeoffs.
|
|
151
|
+
- Bias toward questions over guessing: if a high-impact ambiguity remains, do not produce a proposed plan yet.
|
|
152
|
+
- 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.
|
|
153
|
+
|
|
154
|
+
## Phase 3 \u2014 Implementation chat
|
|
155
|
+
|
|
156
|
+
- 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.
|
|
157
|
+
- 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.
|
|
158
|
+
- Treat plan_mode_question and plan_mode_complete as callable when they are listed in the current request's active tools. Do not infer that they are unavailable from earlier modes or conversation history.
|
|
159
|
+
- If a Plan tool call returns an actual error, respond to that error. Do not replace an available structured tool call with prose claiming that the tool is unavailable.
|
|
160
|
+
- 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.
|
|
161
|
+
|
|
162
|
+
## Ending each turn
|
|
163
|
+
|
|
164
|
+
Every Plan-mode turn that advances or finalizes the plan must end in exactly one of these ways:
|
|
165
|
+
|
|
166
|
+
- If a material decision remains, use plan_mode_question. If interactive UI is unavailable, ask one concise plain-text question instead.
|
|
167
|
+
- 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.
|
|
168
|
+
|
|
169
|
+
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.
|
|
170
|
+
|
|
171
|
+
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.
|
|
172
|
+
|
|
173
|
+
## Completion rule
|
|
174
|
+
|
|
175
|
+
Only call plan_mode_complete when the plan leaves no implementation decisions unresolved. Pass the complete plan as Markdown with:
|
|
176
|
+
|
|
177
|
+
- A clear title
|
|
178
|
+
- A brief summary
|
|
179
|
+
- Important changes to behavior, public APIs, interfaces, or types
|
|
180
|
+
- Test cases and verification scenarios
|
|
181
|
+
- Explicit assumptions and defaults chosen where needed
|
|
182
|
+
|
|
183
|
+
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.
|
|
184
|
+
|
|
185
|
+
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.`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// src/mode-contract.ts
|
|
189
|
+
var MODE_CONTRACT_MESSAGE_TYPE = "plan-mode-transition";
|
|
190
|
+
var MODE_CONTRACT_VERSION = 1;
|
|
191
|
+
var PLAN_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: PLAN]`;
|
|
192
|
+
var NORMAL_CONTRACT_MARKER = `[PI PLAN MODE CONTRACT v${MODE_CONTRACT_VERSION}: NORMAL]`;
|
|
193
|
+
var NORMAL_CONTRACT = `${NORMAL_CONTRACT_MARKER}
|
|
194
|
+
Plan Mode is no longer active.
|
|
195
|
+
Follow the user's current Normal-mode request and ordinary system instructions.
|
|
196
|
+
Earlier Plan-mode restrictions no longer apply, but retain the planning conversation as context.
|
|
197
|
+
The visible tool schemas are session capabilities; use only tools appropriate for the current request.`;
|
|
198
|
+
function modeContractContent(mode) {
|
|
199
|
+
return mode === "plan" ? `${PLAN_CONTRACT_MARKER}
|
|
200
|
+
${buildPlanModePrompt()}` : NORMAL_CONTRACT;
|
|
201
|
+
}
|
|
202
|
+
function createModeContractMessage(mode, timestamp = Date.now()) {
|
|
203
|
+
return {
|
|
204
|
+
role: "custom",
|
|
205
|
+
customType: MODE_CONTRACT_MESSAGE_TYPE,
|
|
206
|
+
content: modeContractContent(mode),
|
|
207
|
+
display: false,
|
|
208
|
+
details: { version: MODE_CONTRACT_VERSION, mode },
|
|
209
|
+
timestamp
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function modeContractFromMessage(message) {
|
|
213
|
+
const candidate = unwrapMessage(message);
|
|
214
|
+
if (candidate.customType !== MODE_CONTRACT_MESSAGE_TYPE) return void 0;
|
|
215
|
+
if (candidate.content === modeContractContent("plan")) return "plan";
|
|
216
|
+
if (candidate.content === modeContractContent("normal")) return "normal";
|
|
217
|
+
return void 0;
|
|
218
|
+
}
|
|
219
|
+
function hasModeContractArtifact(messages) {
|
|
220
|
+
return messages.some(
|
|
221
|
+
(message) => unwrapMessage(message).customType === MODE_CONTRACT_MESSAGE_TYPE
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
function latestModeContract(messages) {
|
|
225
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
226
|
+
const mode = modeContractFromMessage(messages[index]);
|
|
227
|
+
if (mode) return { index, mode };
|
|
228
|
+
}
|
|
229
|
+
return void 0;
|
|
230
|
+
}
|
|
231
|
+
function reconcileModeContract(messages, expected) {
|
|
232
|
+
const latest = latestModeContract(messages);
|
|
233
|
+
if (latest?.mode === expected) return messages;
|
|
234
|
+
const latestContractIndex = findLatestContractArtifactIndex(messages);
|
|
235
|
+
const insertionIndex = latestContractIndex >= 0 ? latestContractIndex + 1 : leadingSummaryBoundary(messages);
|
|
236
|
+
return [
|
|
237
|
+
...messages.slice(0, insertionIndex),
|
|
238
|
+
createModeContractMessage(expected, 0),
|
|
239
|
+
...messages.slice(insertionIndex)
|
|
240
|
+
];
|
|
241
|
+
}
|
|
242
|
+
function findLatestContractArtifactIndex(messages) {
|
|
243
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
244
|
+
if (unwrapMessage(messages[index]).customType === MODE_CONTRACT_MESSAGE_TYPE) return index;
|
|
245
|
+
}
|
|
246
|
+
return -1;
|
|
247
|
+
}
|
|
248
|
+
function leadingSummaryBoundary(messages) {
|
|
249
|
+
let index = 0;
|
|
250
|
+
while (index < messages.length) {
|
|
251
|
+
const role = unwrapMessage(messages[index]).role;
|
|
252
|
+
if (role !== "compactionSummary" && role !== "branchSummary") break;
|
|
253
|
+
index += 1;
|
|
254
|
+
}
|
|
255
|
+
return index;
|
|
256
|
+
}
|
|
257
|
+
function unwrapMessage(message) {
|
|
258
|
+
const entry = message;
|
|
259
|
+
return entry?.message ?? message ?? {};
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// src/fresh-implementation.ts
|
|
86
263
|
function formatImplementationHandoff(plan) {
|
|
87
264
|
return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:
|
|
88
265
|
|
|
266
|
+
${plan}`;
|
|
267
|
+
}
|
|
268
|
+
function formatHistoryImplementationPrompt() {
|
|
269
|
+
return PLAN_HISTORY_IMPLEMENTATION_PROMPT;
|
|
270
|
+
}
|
|
271
|
+
function formatTransferredPlanPrompt(plan, fresh) {
|
|
272
|
+
const destination = fresh ? " in a fresh context" : "";
|
|
273
|
+
return `A previous agent produced the plan below to accomplish the user's task. Implement the plan${destination}. Treat the plan as the source of user intent, re-read files as needed, and carry the work through implementation and verification.
|
|
274
|
+
|
|
89
275
|
${plan}`;
|
|
90
276
|
}
|
|
91
277
|
async function startFreshImplementationFromState(ctx, options) {
|
|
@@ -125,30 +311,39 @@ async function startFreshImplementationSession(ctx, request) {
|
|
|
125
311
|
if (!request.isCurrent()) return { kind: "stale" };
|
|
126
312
|
if (!await preflightModel(ctx, request.isCurrent)) return { kind: "rejected" };
|
|
127
313
|
if (!request.isCurrent()) return { kind: "stale" };
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
plan: request.plan,
|
|
131
|
-
source: request.source,
|
|
132
|
-
startedAt: Date.now(),
|
|
133
|
-
retention: request.retention
|
|
134
|
-
};
|
|
135
|
-
const destinationState = {
|
|
314
|
+
const usesConversationHistory = request.retention === "clear-on-start";
|
|
315
|
+
const destinationState = usesConversationHistory ? void 0 : {
|
|
136
316
|
enabled: false,
|
|
137
317
|
awaitingAction: false,
|
|
138
|
-
activeImplementation
|
|
318
|
+
activeImplementation: {
|
|
319
|
+
id: randomUUID(),
|
|
320
|
+
plan: request.plan,
|
|
321
|
+
source: request.source,
|
|
322
|
+
startedAt: Date.now(),
|
|
323
|
+
retention: request.retention
|
|
324
|
+
}
|
|
139
325
|
};
|
|
140
|
-
const handoff = formatImplementationHandoff(request.plan);
|
|
326
|
+
const handoff = usesConversationHistory ? formatTransferredPlanPrompt(request.plan, true) : formatImplementationHandoff(request.plan);
|
|
141
327
|
const parentSession = ctx.sessionManager.getSessionFile();
|
|
142
328
|
let setupError;
|
|
143
329
|
let kickoffError;
|
|
144
|
-
if (ctx.mode === "rpc") ctx
|
|
330
|
+
if (ctx.mode === "rpc") safeNotify(ctx, "Starting fresh implementation session\u2026", "info");
|
|
145
331
|
let result;
|
|
146
332
|
try {
|
|
147
333
|
result = await ctx.newSession({
|
|
148
334
|
...parentSession ? { parentSession } : {},
|
|
149
335
|
setup: async (sessionManager) => {
|
|
150
336
|
try {
|
|
151
|
-
|
|
337
|
+
const contract = createModeContractMessage("normal");
|
|
338
|
+
sessionManager.appendCustomMessageEntry(
|
|
339
|
+
contract.customType,
|
|
340
|
+
contract.content,
|
|
341
|
+
contract.display,
|
|
342
|
+
contract.details
|
|
343
|
+
);
|
|
344
|
+
if (destinationState) {
|
|
345
|
+
sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
|
|
346
|
+
}
|
|
152
347
|
} catch (error) {
|
|
153
348
|
setupError = safeErrorDetail(error);
|
|
154
349
|
}
|
|
@@ -160,17 +355,21 @@ async function startFreshImplementationSession(ctx, request) {
|
|
|
160
355
|
}
|
|
161
356
|
try {
|
|
162
357
|
await replacementCtx.sendUserMessage(handoff);
|
|
163
|
-
replacementCtx.ui.notify(
|
|
164
|
-
"Fresh implementation session started. Only the approved plan was transferred.",
|
|
165
|
-
"info"
|
|
166
|
-
);
|
|
167
358
|
} catch (error) {
|
|
168
359
|
kickoffError = safeErrorDetail(error);
|
|
169
|
-
replacementCtx
|
|
170
|
-
|
|
360
|
+
const recoveredInEditor = usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
|
|
361
|
+
safeNotify(
|
|
362
|
+
replacementCtx,
|
|
363
|
+
usesConversationHistory ? recoveredInEditor ? `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request is in the editor; submit it or resume the parent planning session.` : `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request could not be restored to the editor; resume the parent planning session.` : `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
364
|
"error"
|
|
172
365
|
);
|
|
366
|
+
return;
|
|
173
367
|
}
|
|
368
|
+
safeNotify(
|
|
369
|
+
replacementCtx,
|
|
370
|
+
"Fresh implementation session started. Only the approved plan was transferred.",
|
|
371
|
+
"info"
|
|
372
|
+
);
|
|
174
373
|
}
|
|
175
374
|
});
|
|
176
375
|
} catch (error) {
|
|
@@ -182,7 +381,7 @@ async function startFreshImplementationSession(ctx, request) {
|
|
|
182
381
|
return { kind: "rejected" };
|
|
183
382
|
}
|
|
184
383
|
if (result.cancelled) {
|
|
185
|
-
ctx
|
|
384
|
+
safeNotify(ctx, "Fresh implementation cancelled. The plan remains available.", "info");
|
|
186
385
|
return { kind: "cancelled" };
|
|
187
386
|
}
|
|
188
387
|
return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
|
|
@@ -210,12 +409,21 @@ async function preflightModel(ctx, isCurrent) {
|
|
|
210
409
|
return true;
|
|
211
410
|
}
|
|
212
411
|
function recoverSetupFailure(ctx, handoff, setupError) {
|
|
213
|
-
ctx
|
|
214
|
-
|
|
215
|
-
|
|
412
|
+
const recoveredInEditor = safeSetEditorText(ctx, handoff);
|
|
413
|
+
safeNotify(
|
|
414
|
+
ctx,
|
|
415
|
+
recoveredInEditor ? `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.` : `Fresh session created, but the active plan could not be saved: ${setupError}. The implementation request could not be restored to the editor; resume the parent planning session.`,
|
|
216
416
|
"error"
|
|
217
417
|
);
|
|
218
418
|
}
|
|
419
|
+
function safeSetEditorText(ctx, text) {
|
|
420
|
+
try {
|
|
421
|
+
ctx.ui.setEditorText(text);
|
|
422
|
+
return true;
|
|
423
|
+
} catch {
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
219
427
|
function safeNotify(ctx, message, level) {
|
|
220
428
|
try {
|
|
221
429
|
ctx.ui.notify(message, level);
|
|
@@ -235,6 +443,114 @@ function safeErrorDetail(error) {
|
|
|
235
443
|
return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
|
|
236
444
|
}
|
|
237
445
|
|
|
446
|
+
// src/helper-tool-visibility.ts
|
|
447
|
+
var PLAN_MODE_HELPER_TOOL_NAMES = [
|
|
448
|
+
PLAN_MODE_QUESTION_TOOL_NAME,
|
|
449
|
+
PLAN_MODE_COMPLETE_TOOL_NAME
|
|
450
|
+
];
|
|
451
|
+
var PlanModeHelperVisibilityPolicy = class {
|
|
452
|
+
constructor(pi) {
|
|
453
|
+
this.pi = pi;
|
|
454
|
+
}
|
|
455
|
+
pi;
|
|
456
|
+
unlocked = false;
|
|
457
|
+
hiddenByPolicy = /* @__PURE__ */ new Set();
|
|
458
|
+
isUnlocked() {
|
|
459
|
+
return this.unlocked;
|
|
460
|
+
}
|
|
461
|
+
hasHiddenTools() {
|
|
462
|
+
return this.hiddenByPolicy.size > 0;
|
|
463
|
+
}
|
|
464
|
+
toolsAvailable() {
|
|
465
|
+
const active = new Set(this.pi.getActiveTools());
|
|
466
|
+
return PLAN_MODE_HELPER_TOOL_NAMES.every((name) => active.has(name));
|
|
467
|
+
}
|
|
468
|
+
prepareSessionStart(visibility, previous) {
|
|
469
|
+
if (visibility === "after-first-plan" && previous === "always") this.lock();
|
|
470
|
+
if (visibility === "always") this.reveal();
|
|
471
|
+
}
|
|
472
|
+
reconcileInactiveState(visibility) {
|
|
473
|
+
if (visibility === "after-first-plan" && !this.unlocked) this.hideIfLocked();
|
|
474
|
+
}
|
|
475
|
+
deferVisibilityChange(visibility) {
|
|
476
|
+
if (visibility === "after-first-plan") this.lock();
|
|
477
|
+
}
|
|
478
|
+
prepareActivation(ctx) {
|
|
479
|
+
if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
|
|
480
|
+
throw new Error("wait until Pi is idle before revealing the Plan tools");
|
|
481
|
+
}
|
|
482
|
+
this.reveal();
|
|
483
|
+
}
|
|
484
|
+
applyVisibilityChange(previous, next, ctx) {
|
|
485
|
+
if (previous === next) return;
|
|
486
|
+
if (next === "always") {
|
|
487
|
+
if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
|
|
488
|
+
throw new Error("Wait for Pi to become idle before revealing Plan tools.");
|
|
489
|
+
}
|
|
490
|
+
this.reveal();
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
if (ctx.isIdle?.() !== true) {
|
|
494
|
+
throw new Error("Wait for Pi to become idle before hiding Plan tools.");
|
|
495
|
+
}
|
|
496
|
+
this.lock();
|
|
497
|
+
this.hideIfLocked();
|
|
498
|
+
}
|
|
499
|
+
hideIfLocked() {
|
|
500
|
+
if (this.unlocked) return;
|
|
501
|
+
const active = this.pi.getActiveTools();
|
|
502
|
+
const hidden = active.filter((name) => this.isHelperTool(name));
|
|
503
|
+
if (hidden.length === 0) return;
|
|
504
|
+
this.pi.setActiveTools(active.filter((name) => !this.isHelperTool(name)));
|
|
505
|
+
for (const name of hidden) this.hiddenByPolicy.add(name);
|
|
506
|
+
}
|
|
507
|
+
snapshot() {
|
|
508
|
+
return {
|
|
509
|
+
activeTools: this.pi.getActiveTools(),
|
|
510
|
+
helperToolsUnlocked: this.unlocked,
|
|
511
|
+
helperToolsHiddenByPolicy: [...this.hiddenByPolicy]
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
restore(snapshot) {
|
|
515
|
+
this.pi.setActiveTools(snapshot.activeTools);
|
|
516
|
+
this.unlocked = snapshot.helperToolsUnlocked;
|
|
517
|
+
this.hiddenByPolicy.clear();
|
|
518
|
+
for (const name of snapshot.helperToolsHiddenByPolicy) this.hiddenByPolicy.add(name);
|
|
519
|
+
}
|
|
520
|
+
reveal() {
|
|
521
|
+
const snapshot = this.snapshot();
|
|
522
|
+
try {
|
|
523
|
+
const active = this.pi.getActiveTools();
|
|
524
|
+
const canonical = [
|
|
525
|
+
...active.filter((name) => !this.isHelperTool(name)),
|
|
526
|
+
...PLAN_MODE_HELPER_TOOL_NAMES
|
|
527
|
+
];
|
|
528
|
+
if (canonical.length !== active.length || canonical.some((name, index) => name !== active[index])) {
|
|
529
|
+
this.pi.setActiveTools(canonical);
|
|
530
|
+
}
|
|
531
|
+
if (!this.toolsAvailable()) {
|
|
532
|
+
throw new Error(
|
|
533
|
+
"plan_mode_question and plan_mode_complete are unavailable; leave the restrictive tool mode before starting Plan mode"
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
this.unlockAndForgetHidden();
|
|
537
|
+
} catch (error) {
|
|
538
|
+
this.restore(snapshot);
|
|
539
|
+
throw error;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
lock() {
|
|
543
|
+
this.unlocked = false;
|
|
544
|
+
}
|
|
545
|
+
unlockAndForgetHidden() {
|
|
546
|
+
this.unlocked = true;
|
|
547
|
+
this.hiddenByPolicy.clear();
|
|
548
|
+
}
|
|
549
|
+
isHelperTool(name) {
|
|
550
|
+
return PLAN_MODE_HELPER_TOOL_NAMES.includes(name);
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
|
|
238
554
|
// src/plan-action-controller.ts
|
|
239
555
|
function createPlanActionController(options) {
|
|
240
556
|
const freshAction = (ctx, lifecycle, signal) => options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);
|
|
@@ -328,34 +644,43 @@ function createPlanExportController(options) {
|
|
|
328
644
|
}
|
|
329
645
|
|
|
330
646
|
// src/presentation.ts
|
|
647
|
+
import { stripTerminalSequences, truncateToWidth } from "@earendil-works/pi-tui";
|
|
331
648
|
var STATUS_KEY = "plan-mode";
|
|
332
649
|
var PLAN_WIDGET_KEY = "plan-mode-plan";
|
|
650
|
+
var BIDI_CONTROLS = /[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu;
|
|
333
651
|
function updatePlanModeUi(ctx, state, toolSummary) {
|
|
334
652
|
ctx.ui.setStatus(STATUS_KEY, formatStatus(state));
|
|
653
|
+
let lines;
|
|
335
654
|
if (state.enabled && state.latestPlan) {
|
|
336
|
-
|
|
337
|
-
"Proposed plan ready",
|
|
338
|
-
"Use /plan to implement, save, revise, or exit Plan mode."
|
|
339
|
-
]);
|
|
655
|
+
lines = ["Proposed plan ready", "Use /plan to implement, save, revise, or exit Plan mode."];
|
|
340
656
|
} else if (state.enabled) {
|
|
341
|
-
|
|
657
|
+
lines = [
|
|
342
658
|
"Plan mode: planning",
|
|
343
659
|
toolSummary(),
|
|
344
660
|
"Finish with plan_mode_complete when decision-ready."
|
|
345
|
-
]
|
|
661
|
+
];
|
|
346
662
|
} else if (state.savedPlan) {
|
|
347
|
-
|
|
348
|
-
"Plan saved for later",
|
|
349
|
-
"Use /plan to show, implement, or clear it."
|
|
350
|
-
]);
|
|
663
|
+
lines = ["Plan saved for later", "Use /plan to show, implement, or clear it."];
|
|
351
664
|
} else if (state.activeImplementation) {
|
|
352
|
-
|
|
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);
|
|
665
|
+
lines = ["Implementation plan active", "Use /plan to show, replace, or clear it."];
|
|
358
666
|
}
|
|
667
|
+
publishPlanModeWidget(ctx, lines);
|
|
668
|
+
}
|
|
669
|
+
function renderPlanModeWidget(lines, theme, width) {
|
|
670
|
+
const renderWidth = Math.max(0, width);
|
|
671
|
+
return [
|
|
672
|
+
theme.fg("borderMuted", "\u2500".repeat(renderWidth)),
|
|
673
|
+
...lines.map((line) => truncateToWidth(sanitizePlanModeWidgetLine(line), renderWidth, ""))
|
|
674
|
+
];
|
|
675
|
+
}
|
|
676
|
+
function sanitizePlanModeWidgetLine(value) {
|
|
677
|
+
let text = "";
|
|
678
|
+
for (const character of stripTerminalSequences(value).replace(BIDI_CONTROLS, "")) {
|
|
679
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
680
|
+
const isControl = codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
|
|
681
|
+
text += isControl ? " " : character;
|
|
682
|
+
}
|
|
683
|
+
return text;
|
|
359
684
|
}
|
|
360
685
|
function clearPlanModeUi(ctx) {
|
|
361
686
|
ctx.ui.setStatus(STATUS_KEY, void 0);
|
|
@@ -407,6 +732,22 @@ function planModeStatusText(state, toolSummary) {
|
|
|
407
732
|
if (state.activeImplementation) return "An implementation plan is active.";
|
|
408
733
|
return "Plan mode is off.";
|
|
409
734
|
}
|
|
735
|
+
function publishPlanModeWidget(ctx, lines) {
|
|
736
|
+
if (!lines) {
|
|
737
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, void 0);
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
if (ctx.mode !== "tui") {
|
|
741
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, [...lines]);
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
const snapshot = [...lines];
|
|
745
|
+
ctx.ui.setWidget(PLAN_WIDGET_KEY, (_tui, theme) => ({
|
|
746
|
+
render: (width) => renderPlanModeWidget(snapshot, theme, width),
|
|
747
|
+
invalidate: () => {
|
|
748
|
+
}
|
|
749
|
+
}));
|
|
750
|
+
}
|
|
410
751
|
function formatStatus(state) {
|
|
411
752
|
if (state.enabled) {
|
|
412
753
|
if (state.awaitingAction || state.latestPlan) return "plan ready";
|
|
@@ -417,64 +758,18 @@ function formatStatus(state) {
|
|
|
417
758
|
return void 0;
|
|
418
759
|
}
|
|
419
760
|
|
|
420
|
-
// src/
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
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.`;
|
|
761
|
+
// src/required-tools.ts
|
|
762
|
+
function withRequiredPlanModeTools(toolNames) {
|
|
763
|
+
return unique([
|
|
764
|
+
...withoutRequiredPlanModeTools(toolNames),
|
|
765
|
+
PLAN_MODE_QUESTION_TOOL_NAME,
|
|
766
|
+
PLAN_MODE_COMPLETE_TOOL_NAME
|
|
767
|
+
]);
|
|
768
|
+
}
|
|
769
|
+
function withoutRequiredPlanModeTools(toolNames) {
|
|
770
|
+
return toolNames.filter(
|
|
771
|
+
(toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME
|
|
772
|
+
);
|
|
478
773
|
}
|
|
479
774
|
|
|
480
775
|
// src/saved-plan-preflight.ts
|
|
@@ -658,17 +953,19 @@ var WorkflowMutex = class {
|
|
|
658
953
|
// src/plan-mode.ts
|
|
659
954
|
var STATE_ENTRY_TYPE = "plan-mode-state";
|
|
660
955
|
var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
|
|
661
|
-
var
|
|
956
|
+
var BLOCKED_MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "update_plan"]);
|
|
662
957
|
var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
|
|
663
958
|
function planMode(pi, dependencies = {}) {
|
|
664
959
|
const workflowMutex = new WorkflowMutex(pi);
|
|
960
|
+
const helperVisibility = new PlanModeHelperVisibilityPolicy(pi);
|
|
665
961
|
let workflowOwner;
|
|
666
962
|
let currentSession;
|
|
963
|
+
let currentSessionContext;
|
|
667
964
|
let interactiveUiPromise;
|
|
668
965
|
const loadInteractiveUi = () => {
|
|
669
966
|
if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
|
|
670
967
|
if (!interactiveUiPromise) {
|
|
671
|
-
interactiveUiPromise = import("./chunks/interactive-ui-
|
|
968
|
+
interactiveUiPromise = import("./chunks/interactive-ui-W3VYAJIQ.js").catch((error) => {
|
|
672
969
|
interactiveUiPromise = void 0;
|
|
673
970
|
throw error;
|
|
674
971
|
});
|
|
@@ -681,7 +978,10 @@ function planMode(pi, dependencies = {}) {
|
|
|
681
978
|
let toggleShortcut;
|
|
682
979
|
const clearPlanModeShortcutHandler = () => {
|
|
683
980
|
};
|
|
684
|
-
let
|
|
981
|
+
let activeToolBaseline = [];
|
|
982
|
+
let workflowAllowedToolNames;
|
|
983
|
+
let publishedContractMode;
|
|
984
|
+
let modeContractsRelevant = false;
|
|
685
985
|
let readyPresentationIntent;
|
|
686
986
|
let latestCommandContext;
|
|
687
987
|
let nextReadyPresentationNonce = 0;
|
|
@@ -692,11 +992,14 @@ function planMode(pi, dependencies = {}) {
|
|
|
692
992
|
let settingsWatch;
|
|
693
993
|
let settingsReloadTimer;
|
|
694
994
|
const implementationRetention = createImplementationRetentionCoordinator();
|
|
995
|
+
const finalizationRequest = createFinalizationRequestCoordinator();
|
|
695
996
|
const persistState = () => pi.appendEntry(STATE_ENTRY_TYPE, state);
|
|
696
997
|
const planExports = createPlanExportController({
|
|
697
998
|
getState: () => state,
|
|
698
999
|
getSettings: () => settings,
|
|
699
|
-
finishReady: (ctx) =>
|
|
1000
|
+
finishReady: (ctx) => {
|
|
1001
|
+
exitPlanMode(ctx);
|
|
1002
|
+
}
|
|
700
1003
|
});
|
|
701
1004
|
const planActions = createPlanActionController({
|
|
702
1005
|
loadInteractiveUi,
|
|
@@ -709,24 +1012,19 @@ function planMode(pi, dependencies = {}) {
|
|
|
709
1012
|
finalize: requestFinalPlan,
|
|
710
1013
|
implementHere: startImplementation,
|
|
711
1014
|
implementFresh: startFreshImplementation,
|
|
712
|
-
exportPlan
|
|
1015
|
+
exportPlan,
|
|
713
1016
|
settings: showSettings,
|
|
714
1017
|
save: savePlanForLater,
|
|
715
1018
|
stay: updateUi,
|
|
716
1019
|
exitReady: (ctx) => {
|
|
717
|
-
exitPlanMode(ctx)
|
|
718
|
-
|
|
1020
|
+
if (exitPlanMode(ctx)) {
|
|
1021
|
+
ctx.ui.notify("Plan mode disabled. Proposed plan discarded.", "info");
|
|
1022
|
+
}
|
|
719
1023
|
},
|
|
720
1024
|
clearSaved: (ctx) => {
|
|
721
|
-
exitPlanMode(ctx);
|
|
722
|
-
ctx.ui.notify("Saved plan cleared.", "info");
|
|
1025
|
+
if (exitPlanMode(ctx)) ctx.ui.notify("Saved plan cleared.", "info");
|
|
723
1026
|
}
|
|
724
1027
|
});
|
|
725
|
-
pi.registerFlag("plan", {
|
|
726
|
-
description: "Start in Codex-like Plan mode",
|
|
727
|
-
type: "boolean",
|
|
728
|
-
default: false
|
|
729
|
-
});
|
|
730
1028
|
pi.registerTool({
|
|
731
1029
|
name: PLAN_MODE_QUESTION_TOOL_NAME,
|
|
732
1030
|
label: "Plan question",
|
|
@@ -748,6 +1046,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
748
1046
|
if (!parsed.ok) {
|
|
749
1047
|
return planModeQuestionCancelled([], "invalid_input", `Error: ${parsed.error}`);
|
|
750
1048
|
}
|
|
1049
|
+
finalizationRequest.satisfy();
|
|
751
1050
|
if (!ctx.hasUI) {
|
|
752
1051
|
return planModeQuestionCancelled(
|
|
753
1052
|
parsed.questions,
|
|
@@ -829,12 +1128,12 @@ function planMode(pi, dependencies = {}) {
|
|
|
829
1128
|
const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
|
|
830
1129
|
if (exportMatch) {
|
|
831
1130
|
const lifecycle = captureMenuLifecycle();
|
|
832
|
-
await
|
|
1131
|
+
await exportPlan(ctx, exportMatch[1], lifecycle.signal, lifecycle.isCurrent);
|
|
833
1132
|
return;
|
|
834
1133
|
}
|
|
835
1134
|
if (command === "exit" || command === "off") {
|
|
836
|
-
|
|
837
|
-
exitPlanMode(ctx);
|
|
1135
|
+
const notification = planModeDisableNotification();
|
|
1136
|
+
if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
|
|
838
1137
|
return;
|
|
839
1138
|
}
|
|
840
1139
|
if (command === "tools") {
|
|
@@ -900,16 +1199,17 @@ function planMode(pi, dependencies = {}) {
|
|
|
900
1199
|
const readPlanModeRuntimeSettings = async () => {
|
|
901
1200
|
return dependencies.readSettings?.() ?? readPlanModeSettings(explicitPlanModeSettingsPath);
|
|
902
1201
|
};
|
|
903
|
-
const applyPlanModeSettings = async (generation, ctx, showWarnings) => {
|
|
1202
|
+
const applyPlanModeSettings = async (generation, ctx, showWarnings, applyWatchedVisibility = false) => {
|
|
904
1203
|
const loadedSettings = await readPlanModeRuntimeSettings();
|
|
905
1204
|
if (generation !== menuGeneration || menuController.signal.aborted) {
|
|
906
1205
|
return void 0;
|
|
907
1206
|
}
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
1207
|
+
const previousSettings = settings;
|
|
1208
|
+
const nextSettings = loadedSettings.kind === "loaded" ? loadedSettings.settings : { thinkingLevel: "inherit" };
|
|
1209
|
+
if (applyWatchedVisibility && ctx) {
|
|
1210
|
+
applyWatchedHelperVisibility(previousSettings, nextSettings, ctx);
|
|
912
1211
|
}
|
|
1212
|
+
settings = nextSettings;
|
|
913
1213
|
applyPlanModeShortcut(configuredPlanModeToggleShortcut(settings));
|
|
914
1214
|
if (!ctx || !showWarnings) return loadedSettings;
|
|
915
1215
|
if (loadedSettings.kind === "invalid") {
|
|
@@ -935,7 +1235,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
935
1235
|
}
|
|
936
1236
|
settingsReloadTimer = setTimeout(() => {
|
|
937
1237
|
settingsReloadTimer = void 0;
|
|
938
|
-
void applyPlanModeSettings(generation,
|
|
1238
|
+
void applyPlanModeSettings(generation, currentSessionContext, false, true);
|
|
939
1239
|
}, 75);
|
|
940
1240
|
};
|
|
941
1241
|
const startPlanModeSettingsWatch = (generation) => {
|
|
@@ -960,35 +1260,64 @@ function planMode(pi, dependencies = {}) {
|
|
|
960
1260
|
};
|
|
961
1261
|
pi.on("session_start", async (event, ctx) => {
|
|
962
1262
|
const generation = ++menuGeneration;
|
|
1263
|
+
const previousToolVisibility = configuredPlanModeToolVisibility(settings);
|
|
1264
|
+
finalizationRequest.reset();
|
|
963
1265
|
currentSession = ctx.sessionManager;
|
|
1266
|
+
currentSessionContext = ctx;
|
|
964
1267
|
workflowOwner = void 0;
|
|
965
1268
|
workflowMutex.bindSession(ctx.sessionManager);
|
|
1269
|
+
captureToolBaseline();
|
|
966
1270
|
refreshStateBeforeFirstAgentStart = event.reason === "new";
|
|
967
1271
|
menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
|
|
968
1272
|
menuController = new AbortController();
|
|
969
1273
|
readyPresentationIntent = void 0;
|
|
970
1274
|
latestCommandContext = void 0;
|
|
971
|
-
|
|
1275
|
+
workflowAllowedToolNames = void 0;
|
|
972
1276
|
implementationRetention.reset();
|
|
973
1277
|
settings = { thinkingLevel: "inherit" };
|
|
974
|
-
const
|
|
1278
|
+
const branch = ctx.sessionManager.getBranch();
|
|
1279
|
+
const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
|
|
1280
|
+
restoreModeContractTracking(branch, restoredState);
|
|
975
1281
|
state = { enabled: false, awaitingAction: false };
|
|
976
1282
|
await applyPlanModeSettings(generation, ctx, true);
|
|
977
1283
|
if (generation !== menuGeneration || menuController.signal.aborted) return;
|
|
978
1284
|
startPlanModeSettingsWatch(generation);
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1285
|
+
if (restoredState.enabled) {
|
|
1286
|
+
if (!installRestoredState(restoredState, ctx, previousToolVisibility)) return;
|
|
1287
|
+
} else {
|
|
1288
|
+
reconcileInactiveHelperVisibility(previousToolVisibility, ctx);
|
|
1289
|
+
if (!installRestoredState(restoredState, ctx)) return;
|
|
1290
|
+
}
|
|
1291
|
+
implementationRetention.restore(state.activeImplementation);
|
|
1292
|
+
updateUi(ctx);
|
|
1293
|
+
});
|
|
1294
|
+
pi.on("session_before_tree", (event, ctx) => {
|
|
1295
|
+
const target = ctx.sessionManager.getEntry(event.preparation.targetId);
|
|
1296
|
+
if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
if (ctx.hasUI) {
|
|
1300
|
+
ctx.ui.notify(
|
|
1301
|
+
"Plan mode transition markers are internal. Select the adjacent conversation entry instead.",
|
|
1302
|
+
"warning"
|
|
1303
|
+
);
|
|
1304
|
+
}
|
|
1305
|
+
return { cancel: true };
|
|
1306
|
+
});
|
|
1307
|
+
pi.on("session_tree", (_event, ctx) => {
|
|
1308
|
+
advanceWorkflowGeneration();
|
|
1309
|
+
menuGeneration += 1;
|
|
1310
|
+
menuController.abort(new DOMException("Plan-mode tree branch changed", "AbortError"));
|
|
1311
|
+
menuController = new AbortController();
|
|
1312
|
+
readyPresentationIntent = void 0;
|
|
1313
|
+
latestCommandContext = void 0;
|
|
1314
|
+
implementationRetention.reset();
|
|
1315
|
+
const branch = ctx.sessionManager.getBranch();
|
|
1316
|
+
const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
|
|
1317
|
+
restoreModeContractTracking(branch, restoredState);
|
|
1318
|
+
if (!installRestoredState(restoredState, ctx)) return;
|
|
990
1319
|
implementationRetention.restore(state.activeImplementation);
|
|
991
|
-
|
|
1320
|
+
startPlanModeSettingsWatch(menuGeneration);
|
|
992
1321
|
updateUi(ctx);
|
|
993
1322
|
});
|
|
994
1323
|
pi.on("thinking_level_select", (event) => {
|
|
@@ -1005,6 +1334,7 @@ function planMode(pi, dependencies = {}) {
|
|
|
1005
1334
|
});
|
|
1006
1335
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1007
1336
|
const shutdownSession = ctx.sessionManager;
|
|
1337
|
+
finalizationRequest.reset();
|
|
1008
1338
|
menuGeneration += 1;
|
|
1009
1339
|
menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
|
|
1010
1340
|
readyPresentationIntent = void 0;
|
|
@@ -1018,59 +1348,97 @@ function planMode(pi, dependencies = {}) {
|
|
|
1018
1348
|
}
|
|
1019
1349
|
captureManualThinkingLevel();
|
|
1020
1350
|
persistState();
|
|
1021
|
-
if (state.enabled)
|
|
1022
|
-
restoreTools();
|
|
1023
|
-
restoreThinkingLevel();
|
|
1024
|
-
}
|
|
1351
|
+
if (state.enabled) restoreThinkingLevel();
|
|
1025
1352
|
stopPlanModeSettingsWatch();
|
|
1026
1353
|
clearUi(ctx);
|
|
1027
1354
|
releaseWorkflowOwner();
|
|
1028
1355
|
workflowMutex.unbindSession(ctx.sessionManager);
|
|
1029
|
-
if (currentSession === ctx.sessionManager)
|
|
1356
|
+
if (currentSession === ctx.sessionManager) {
|
|
1357
|
+
currentSession = void 0;
|
|
1358
|
+
currentSessionContext = void 0;
|
|
1359
|
+
}
|
|
1030
1360
|
});
|
|
1031
1361
|
pi.on("tool_call", async (event) => {
|
|
1032
|
-
|
|
1033
|
-
if (
|
|
1362
|
+
const requiredHelper = event.toolName === PLAN_MODE_QUESTION_TOOL_NAME || event.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
|
|
1363
|
+
if (!state.enabled) {
|
|
1364
|
+
if (!requiredHelper) return;
|
|
1034
1365
|
return {
|
|
1035
1366
|
block: true,
|
|
1036
|
-
reason:
|
|
1367
|
+
reason: `${event.toolName} is only available while Plan mode is active.`
|
|
1037
1368
|
};
|
|
1038
1369
|
}
|
|
1039
|
-
|
|
1040
|
-
if (calledTool && classifyPlanModeTool(calledTool) === "blocked") {
|
|
1370
|
+
if (!workflowMutex.isOwner(workflowOwner)) {
|
|
1041
1371
|
return {
|
|
1042
1372
|
block: true,
|
|
1043
|
-
reason: `Plan mode blocks
|
|
1373
|
+
reason: `Plan mode blocks tool '${event.toolName}' because workflow ownership is unavailable.`
|
|
1044
1374
|
};
|
|
1045
1375
|
}
|
|
1046
|
-
if (
|
|
1376
|
+
if (BLOCKED_MUTATING_TOOLS.has(event.toolName)) {
|
|
1047
1377
|
return {
|
|
1048
1378
|
block: true,
|
|
1049
|
-
reason: `Plan mode blocks
|
|
1379
|
+
reason: event.toolName === "update_plan" ? "Plan mode blocks update_plan because it tracks execution progress rather than conversational planning." : `Plan mode blocks mutating tool '${event.toolName}'.`
|
|
1050
1380
|
};
|
|
1051
1381
|
}
|
|
1052
|
-
if (
|
|
1053
|
-
const
|
|
1054
|
-
if (
|
|
1382
|
+
if (requiredHelper) return;
|
|
1383
|
+
const allowedToolNames = new Set(planModePolicyToolNames());
|
|
1384
|
+
if (!allowedToolNames.has(event.toolName)) {
|
|
1055
1385
|
return {
|
|
1056
1386
|
block: true,
|
|
1057
|
-
reason: `Plan mode blocks
|
|
1058
|
-
Blocked command: ${blocked}`
|
|
1387
|
+
reason: `Plan mode blocks tool '${event.toolName}' because it is unavailable or not selected by the Plan policy.`
|
|
1059
1388
|
};
|
|
1060
1389
|
}
|
|
1390
|
+
const calledTool = toolByName(event.toolName);
|
|
1391
|
+
if (!calledTool || classifyPlanModeTool(calledTool) === "blocked") {
|
|
1392
|
+
return {
|
|
1393
|
+
block: true,
|
|
1394
|
+
reason: `Plan mode blocks tool '${event.toolName}' because its safe policy metadata is unavailable.`
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
if (event.toolName === "bash") {
|
|
1398
|
+
const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands);
|
|
1399
|
+
if (blocked !== void 0) {
|
|
1400
|
+
return {
|
|
1401
|
+
block: true,
|
|
1402
|
+
reason: `Plan mode blocks bash commands outside its reviewed inspection policy or containing explicitly unsafe arguments.
|
|
1403
|
+
Blocked command: ${blocked}`
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
if (event.toolName === "powershell") {
|
|
1408
|
+
const blocked = findBlockedPowerShellCommandSegment(
|
|
1409
|
+
readCommand(event.input),
|
|
1410
|
+
settings.safeSubcommands
|
|
1411
|
+
);
|
|
1412
|
+
if (blocked !== void 0) {
|
|
1413
|
+
return {
|
|
1414
|
+
block: true,
|
|
1415
|
+
reason: `Plan mode blocks PowerShell commands outside its reviewed inspection policy or containing explicitly unsafe syntax.
|
|
1416
|
+
Blocked command: ${blocked}`
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
});
|
|
1421
|
+
pi.on("message_start", (event) => {
|
|
1422
|
+
if (state.enabled && event.message.role === "user" && messageTextContent(event.message).trim() === FINALIZE_PLAN_PROMPT) {
|
|
1423
|
+
finalizationRequest.request(workflowGeneration);
|
|
1424
|
+
}
|
|
1061
1425
|
});
|
|
1062
1426
|
pi.on("context", async (event, ctx) => {
|
|
1063
1427
|
const result = implementationRetention.transformContext(event.messages, state);
|
|
1064
1428
|
if (result.clearActiveImplementationId) {
|
|
1065
1429
|
clearActiveImplementation(result.clearActiveImplementationId, ctx);
|
|
1066
1430
|
}
|
|
1067
|
-
|
|
1431
|
+
const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
|
|
1432
|
+
return { messages };
|
|
1068
1433
|
});
|
|
1069
|
-
pi.on("before_agent_start", (
|
|
1434
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
1070
1435
|
if (refreshStateBeforeFirstAgentStart) {
|
|
1071
1436
|
refreshStateBeforeFirstAgentStart = false;
|
|
1072
1437
|
implementationRetention.reset();
|
|
1073
|
-
|
|
1438
|
+
const branch = ctx.sessionManager.getBranch();
|
|
1439
|
+
const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
|
|
1440
|
+
restoreModeContractTracking(branch, restoredState);
|
|
1441
|
+
if (!installRestoredState(restoredState, ctx)) return;
|
|
1074
1442
|
implementationRetention.restore(state.activeImplementation);
|
|
1075
1443
|
updateUi(ctx);
|
|
1076
1444
|
}
|
|
@@ -1086,18 +1454,13 @@ Blocked command: ${blocked}`
|
|
|
1086
1454
|
persistState();
|
|
1087
1455
|
updateUi(ctx);
|
|
1088
1456
|
}
|
|
1089
|
-
applyPlanModeTools();
|
|
1090
|
-
return {
|
|
1091
|
-
systemPrompt: `${event.systemPrompt}
|
|
1092
|
-
|
|
1093
|
-
${buildPlanModePrompt()}`
|
|
1094
|
-
};
|
|
1095
1457
|
});
|
|
1096
1458
|
pi.on("agent_end", async (event, ctx) => {
|
|
1097
1459
|
if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
|
|
1098
1460
|
const text = latestAssistantText(event.messages);
|
|
1099
1461
|
const parsedPlan = parseProposedPlan(text);
|
|
1100
1462
|
if (parsedPlan.kind !== "valid") {
|
|
1463
|
+
finalizationRequest.observeRunEnd(workflowGeneration, finalizationRunOutcome(event.messages));
|
|
1101
1464
|
if (parsedPlan.kind !== "absent") {
|
|
1102
1465
|
ctx.ui.notify(invalidPlanMessage(parsedPlan.kind), "warning");
|
|
1103
1466
|
}
|
|
@@ -1107,11 +1470,25 @@ ${buildPlanModePrompt()}`
|
|
|
1107
1470
|
}
|
|
1108
1471
|
acceptCompletedPlan(parsedPlan.plan, "legacy_proposed_plan", ctx);
|
|
1109
1472
|
});
|
|
1110
|
-
|
|
1473
|
+
pi.on("agent_settled", async (_event, ctx) => {
|
|
1111
1474
|
const settledImplementationId = implementationRetention.implementationSettled(
|
|
1112
1475
|
state.activeImplementation
|
|
1113
1476
|
);
|
|
1114
1477
|
if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
|
|
1478
|
+
if (finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
|
|
1479
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
|
|
1480
|
+
const action = finalizationRequest.settle(workflowGeneration);
|
|
1481
|
+
if (action === "retry") {
|
|
1482
|
+
if (sendPlanModeUserMessage(RETRY_FINALIZE_PLAN_PROMPT, ctx)) return;
|
|
1483
|
+
finalizationRequest.reset();
|
|
1484
|
+
}
|
|
1485
|
+
if (action === "failed") {
|
|
1486
|
+
ctx.ui.notify(
|
|
1487
|
+
"Plan finalization ended twice without a structured question or completed plan. Plan mode remains active; revise the plan or run /plan finalize again.",
|
|
1488
|
+
"warning"
|
|
1489
|
+
);
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1115
1492
|
const intent = readyPresentationIntent;
|
|
1116
1493
|
if (!intent || !readyPresentationIsCurrent(intent)) return;
|
|
1117
1494
|
if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
|
|
@@ -1137,16 +1514,29 @@ ${intent.plan}`,
|
|
|
1137
1514
|
}
|
|
1138
1515
|
});
|
|
1139
1516
|
function enterPlanMode(ctx, candidate = state) {
|
|
1517
|
+
if (!state.enabled && !allowModeTransition(ctx, "start Plan mode")) return false;
|
|
1140
1518
|
bindWorkflowSessionIfNeeded(ctx);
|
|
1141
1519
|
if (state.enabled) return workflowMutex.isOwner(workflowOwner);
|
|
1142
1520
|
const owner = workflowMutex.acquire();
|
|
1143
1521
|
if (!owner) return reportWorkflowBusy(ctx);
|
|
1144
1522
|
workflowOwner = owner;
|
|
1145
1523
|
const previousState = state;
|
|
1146
|
-
const
|
|
1147
|
-
workflowGeneration += 1;
|
|
1524
|
+
const previousHelperVisibility = helperVisibility.snapshot();
|
|
1148
1525
|
try {
|
|
1149
|
-
|
|
1526
|
+
helperVisibility.prepareActivation(ctx);
|
|
1527
|
+
if (!publishModeContract("plan", ctx)) {
|
|
1528
|
+
helperVisibility.restore(previousHelperVisibility);
|
|
1529
|
+
releaseWorkflowOwner();
|
|
1530
|
+
return false;
|
|
1531
|
+
}
|
|
1532
|
+
} catch (error) {
|
|
1533
|
+
helperVisibility.restore(previousHelperVisibility);
|
|
1534
|
+
releaseWorkflowOwner();
|
|
1535
|
+
return reportHelperActivationFailure(ctx, error);
|
|
1536
|
+
}
|
|
1537
|
+
advanceWorkflowGeneration();
|
|
1538
|
+
try {
|
|
1539
|
+
modeContractsRelevant = true;
|
|
1150
1540
|
state = {
|
|
1151
1541
|
...state,
|
|
1152
1542
|
enabled: true,
|
|
@@ -1156,20 +1546,20 @@ ${intent.plan}`,
|
|
|
1156
1546
|
selectedToolNames: candidate.selectedToolNames,
|
|
1157
1547
|
selectedToolKeys: candidate.selectedToolKeys
|
|
1158
1548
|
};
|
|
1159
|
-
|
|
1549
|
+
workflowAllowedToolNames = computePlanModePolicyToolNames();
|
|
1160
1550
|
applyPlanThinkingLevel();
|
|
1161
1551
|
persistState();
|
|
1162
1552
|
updateUi(ctx);
|
|
1163
1553
|
return true;
|
|
1164
1554
|
} catch (error) {
|
|
1165
|
-
rollbackNewActivation(previousState,
|
|
1555
|
+
rollbackNewActivation(previousState, ctx, void 0, previousHelperVisibility);
|
|
1166
1556
|
throw error;
|
|
1167
1557
|
}
|
|
1168
1558
|
}
|
|
1169
1559
|
function enterPlanModeWithPrompt(prompt, ctx) {
|
|
1170
1560
|
const previousState = state;
|
|
1171
1561
|
const previousOwner = workflowOwner;
|
|
1172
|
-
const
|
|
1562
|
+
const previousHelperVisibility = helperVisibility.snapshot();
|
|
1173
1563
|
const wasEnabled = state.enabled;
|
|
1174
1564
|
if (!enterPlanMode(ctx)) return;
|
|
1175
1565
|
if (!wasEnabled) {
|
|
@@ -1177,12 +1567,17 @@ ${intent.plan}`,
|
|
|
1177
1567
|
}
|
|
1178
1568
|
if (sendPlanModeUserMessage(prompt, ctx)) return;
|
|
1179
1569
|
if (wasEnabled) return;
|
|
1180
|
-
rollbackNewActivation(previousState,
|
|
1570
|
+
rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility);
|
|
1181
1571
|
}
|
|
1182
1572
|
function exitPlanMode(ctx) {
|
|
1183
|
-
|
|
1573
|
+
if (!allowModeTransition(ctx, "leave or clear Plan mode")) return false;
|
|
1184
1574
|
const wasEnabled = state.enabled;
|
|
1575
|
+
if ((wasEnabled || modeContractsRelevant) && !publishModeContract("normal", ctx)) {
|
|
1576
|
+
return false;
|
|
1577
|
+
}
|
|
1578
|
+
advanceWorkflowGeneration();
|
|
1185
1579
|
readyPresentationIntent = void 0;
|
|
1580
|
+
workflowAllowedToolNames = void 0;
|
|
1186
1581
|
state = {
|
|
1187
1582
|
...state,
|
|
1188
1583
|
enabled: false,
|
|
@@ -1194,13 +1589,33 @@ ${intent.plan}`,
|
|
|
1194
1589
|
manualThinkingLevel: void 0
|
|
1195
1590
|
};
|
|
1196
1591
|
if (wasEnabled) {
|
|
1197
|
-
restoreTools();
|
|
1198
1592
|
restoreThinkingLevel();
|
|
1199
1593
|
state = { ...state, manualThinkingLevel: void 0 };
|
|
1200
1594
|
}
|
|
1201
1595
|
persistState();
|
|
1202
1596
|
updateUi(ctx);
|
|
1203
1597
|
if (wasEnabled) releaseWorkflowOwner();
|
|
1598
|
+
return true;
|
|
1599
|
+
}
|
|
1600
|
+
function restoreModeContractTracking(branch, restoredState) {
|
|
1601
|
+
publishedContractMode = latestModeContract(branch)?.mode;
|
|
1602
|
+
modeContractsRelevant = hasModeContractArtifact(branch) || restoredState.enabled || restoredState.savedPlan !== void 0 || restoredState.activeImplementation !== void 0;
|
|
1603
|
+
}
|
|
1604
|
+
function publishModeContract(mode, ctx) {
|
|
1605
|
+
if (publishedContractMode === mode) return true;
|
|
1606
|
+
const { role: _role, timestamp: _timestamp, ...message } = createModeContractMessage(mode);
|
|
1607
|
+
try {
|
|
1608
|
+
pi.sendMessage(message, { triggerTurn: false });
|
|
1609
|
+
publishedContractMode = mode;
|
|
1610
|
+
modeContractsRelevant = true;
|
|
1611
|
+
return true;
|
|
1612
|
+
} catch (error) {
|
|
1613
|
+
const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
|
|
1614
|
+
const notification = `Unable to publish the ${mode === "plan" ? "Plan" : "Normal"} mode contract: ${detail}`;
|
|
1615
|
+
if (!ctx.hasUI) throw new Error(notification, { cause: error });
|
|
1616
|
+
ctx.ui.notify(notification, "error");
|
|
1617
|
+
return false;
|
|
1618
|
+
}
|
|
1204
1619
|
}
|
|
1205
1620
|
function sendPlanModeUserMessage(message, ctx) {
|
|
1206
1621
|
try {
|
|
@@ -1208,7 +1623,7 @@ ${intent.plan}`,
|
|
|
1208
1623
|
else pi.sendUserMessage(message, { deliverAs: "followUp" });
|
|
1209
1624
|
return true;
|
|
1210
1625
|
} catch (error) {
|
|
1211
|
-
const detail = error instanceof Error ? error.message : String(error);
|
|
1626
|
+
const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
|
|
1212
1627
|
ctx.ui.notify(`Unable to send Plan-mode message: ${detail}`, "error");
|
|
1213
1628
|
return false;
|
|
1214
1629
|
}
|
|
@@ -1221,6 +1636,7 @@ ${intent.plan}`,
|
|
|
1221
1636
|
updateUi(ctx);
|
|
1222
1637
|
return;
|
|
1223
1638
|
}
|
|
1639
|
+
finalizationRequest.satisfy();
|
|
1224
1640
|
if (state.enabled && state.awaitingAction && state.latestPlan === normalized.plan && state.latestPlanSource === source) {
|
|
1225
1641
|
return;
|
|
1226
1642
|
}
|
|
@@ -1246,8 +1662,8 @@ ${intent.plan}`,
|
|
|
1246
1662
|
}
|
|
1247
1663
|
function togglePlanMode(ctx) {
|
|
1248
1664
|
if (state.enabled) {
|
|
1249
|
-
|
|
1250
|
-
exitPlanMode(ctx);
|
|
1665
|
+
const notification = planModeDisableNotification();
|
|
1666
|
+
if (exitPlanMode(ctx)) ctx.ui.notify(notification, "info");
|
|
1251
1667
|
return;
|
|
1252
1668
|
}
|
|
1253
1669
|
if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0)) return;
|
|
@@ -1263,10 +1679,8 @@ ${intent.plan}`,
|
|
|
1263
1679
|
ctx.ui.notify("Plan mode is not active. Use /plan first.", "warning");
|
|
1264
1680
|
return;
|
|
1265
1681
|
}
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
ctx
|
|
1269
|
-
);
|
|
1682
|
+
finalizationRequest.request(workflowGeneration);
|
|
1683
|
+
if (!sendPlanModeUserMessage(FINALIZE_PLAN_PROMPT, ctx)) finalizationRequest.reset();
|
|
1270
1684
|
}
|
|
1271
1685
|
function savePlanForLater(ctx) {
|
|
1272
1686
|
const plan = state.enabled ? state.latestPlan?.trim() : void 0;
|
|
@@ -1277,8 +1691,11 @@ ${intent.plan}`,
|
|
|
1277
1691
|
return;
|
|
1278
1692
|
}
|
|
1279
1693
|
const source = state.latestPlanSource ?? "legacy_proposed_plan";
|
|
1280
|
-
|
|
1694
|
+
if (!allowModeTransition(ctx, "save the plan and leave Plan mode")) return;
|
|
1695
|
+
if (!publishModeContract("normal", ctx)) return;
|
|
1696
|
+
advanceWorkflowGeneration();
|
|
1281
1697
|
readyPresentationIntent = void 0;
|
|
1698
|
+
workflowAllowedToolNames = void 0;
|
|
1282
1699
|
state = {
|
|
1283
1700
|
...state,
|
|
1284
1701
|
enabled: false,
|
|
@@ -1289,7 +1706,6 @@ ${intent.plan}`,
|
|
|
1289
1706
|
activeImplementation: void 0,
|
|
1290
1707
|
manualThinkingLevel: void 0
|
|
1291
1708
|
};
|
|
1292
|
-
restoreTools();
|
|
1293
1709
|
restoreThinkingLevel();
|
|
1294
1710
|
state = { ...state, manualThinkingLevel: void 0 };
|
|
1295
1711
|
persistState();
|
|
@@ -1307,24 +1723,31 @@ ${intent.plan}`,
|
|
|
1307
1723
|
}
|
|
1308
1724
|
async function startImplementation(ctx) {
|
|
1309
1725
|
const savedPlan = state.enabled ? void 0 : state.savedPlan;
|
|
1726
|
+
const initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
|
|
1727
|
+
if (!initialPlan) {
|
|
1728
|
+
ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
|
|
1729
|
+
return;
|
|
1730
|
+
}
|
|
1731
|
+
if (!allowModeTransition(ctx, "start plan implementation")) return;
|
|
1310
1732
|
if (savedPlan) {
|
|
1311
1733
|
const sessionGeneration = menuGeneration;
|
|
1312
1734
|
const planWorkflowGeneration = workflowGeneration;
|
|
1313
1735
|
const isCurrent = () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !menuController.signal.aborted && !state.enabled && state.savedPlan === savedPlan;
|
|
1314
1736
|
if (!await preflightSavedPlanImplementation(ctx, isCurrent)) return;
|
|
1737
|
+
if (!allowModeTransition(ctx, "start plan implementation")) return;
|
|
1315
1738
|
}
|
|
1316
1739
|
const plan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
|
|
1317
1740
|
const source = (state.enabled ? state.latestPlanSource : savedPlan?.source) ?? "legacy_proposed_plan";
|
|
1318
|
-
if (!plan)
|
|
1319
|
-
ctx.ui.notify("Plan mode disabled. No proposed plan is available to implement.", "warning");
|
|
1320
|
-
return;
|
|
1321
|
-
}
|
|
1322
|
-
workflowGeneration += 1;
|
|
1741
|
+
if (!plan) return;
|
|
1323
1742
|
const previousState = state;
|
|
1324
1743
|
const previousIntent = readyPresentationIntent;
|
|
1325
|
-
const previousToolSnapshot = previousTools;
|
|
1326
1744
|
const wasEnabled = state.enabled;
|
|
1745
|
+
if (!publishModeContract("normal", ctx)) return;
|
|
1746
|
+
advanceWorkflowGeneration();
|
|
1747
|
+
const retention = configuredImplementationPlanRetention(settings);
|
|
1748
|
+
const usesConversationHistory = retention === "clear-on-start";
|
|
1327
1749
|
readyPresentationIntent = void 0;
|
|
1750
|
+
workflowAllowedToolNames = void 0;
|
|
1328
1751
|
state = {
|
|
1329
1752
|
...state,
|
|
1330
1753
|
enabled: false,
|
|
@@ -1332,29 +1755,29 @@ ${intent.plan}`,
|
|
|
1332
1755
|
latestPlanSource: void 0,
|
|
1333
1756
|
awaitingAction: false,
|
|
1334
1757
|
savedPlan: void 0,
|
|
1335
|
-
activeImplementation: {
|
|
1758
|
+
activeImplementation: usesConversationHistory ? void 0 : {
|
|
1336
1759
|
id: randomUUID2(),
|
|
1337
1760
|
plan,
|
|
1338
1761
|
source,
|
|
1339
1762
|
startedAt: Date.now(),
|
|
1340
|
-
retention
|
|
1763
|
+
retention
|
|
1341
1764
|
},
|
|
1342
1765
|
manualThinkingLevel: void 0
|
|
1343
1766
|
};
|
|
1344
1767
|
if (wasEnabled) {
|
|
1345
|
-
restoreTools();
|
|
1346
1768
|
restoreThinkingLevel();
|
|
1347
1769
|
state = { ...state, manualThinkingLevel: void 0 };
|
|
1348
1770
|
}
|
|
1349
1771
|
persistState();
|
|
1350
1772
|
updateUi(ctx);
|
|
1351
|
-
const
|
|
1773
|
+
const handoff = usesConversationHistory ? wasEnabled ? formatHistoryImplementationPrompt() : formatTransferredPlanPrompt(plan, false) : formatImplementationHandoff(plan);
|
|
1774
|
+
const sent = sendPlanModeUserMessage(handoff, ctx);
|
|
1352
1775
|
if (!sent) {
|
|
1353
1776
|
state = previousState;
|
|
1354
1777
|
readyPresentationIntent = previousIntent;
|
|
1355
1778
|
if (wasEnabled) {
|
|
1356
|
-
|
|
1357
|
-
|
|
1779
|
+
publishModeContract("plan", ctx);
|
|
1780
|
+
workflowAllowedToolNames = computePlanModePolicyToolNames();
|
|
1358
1781
|
applyPlanThinkingLevel();
|
|
1359
1782
|
}
|
|
1360
1783
|
persistState();
|
|
@@ -1365,12 +1788,21 @@ ${intent.plan}`,
|
|
|
1365
1788
|
}
|
|
1366
1789
|
function clearActiveImplementation(id, ctx) {
|
|
1367
1790
|
if (state.activeImplementation?.id !== id) return false;
|
|
1368
|
-
|
|
1791
|
+
advanceWorkflowGeneration();
|
|
1369
1792
|
state = { ...state, activeImplementation: void 0 };
|
|
1370
1793
|
persistState();
|
|
1371
1794
|
updateUi(ctx);
|
|
1372
1795
|
return true;
|
|
1373
1796
|
}
|
|
1797
|
+
async function exportPlan(ctx, path, signal, isCurrent) {
|
|
1798
|
+
const exitsReadyPlan = state.enabled && Boolean(state.latestPlan?.trim());
|
|
1799
|
+
if (exitsReadyPlan && !allowModeTransition(ctx, "export the ready plan and leave Plan mode")) {
|
|
1800
|
+
return false;
|
|
1801
|
+
}
|
|
1802
|
+
return planExports.export(path, ctx, signal, () => {
|
|
1803
|
+
return isCurrent() && (!exitsReadyPlan || ctx.isIdle());
|
|
1804
|
+
});
|
|
1805
|
+
}
|
|
1374
1806
|
async function showLaunchMenu(ctx, initialScreen = "main") {
|
|
1375
1807
|
const lifecycle = captureMenuLifecycle();
|
|
1376
1808
|
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
@@ -1378,20 +1810,26 @@ ${intent.plan}`,
|
|
|
1378
1810
|
if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
|
|
1379
1811
|
const tools = selectableTools();
|
|
1380
1812
|
await ui.showPlanLaunchMenu(ctx, {
|
|
1381
|
-
statusText: "Status: Off \u2014
|
|
1813
|
+
statusText: helperVisibility.toolsAvailable() ? "Status: Off \u2014 Plan helper tools are visible for this runtime." : "Status: Off \u2014 Plan helper tools load on the first Plan start.",
|
|
1382
1814
|
initialScreen,
|
|
1383
1815
|
getSelectedNames: () => snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot()),
|
|
1384
|
-
toolSummary: (selectedNames) =>
|
|
1816
|
+
toolSummary: (selectedNames) => {
|
|
1817
|
+
const allowed = tools.filter(
|
|
1818
|
+
(tool) => toolIsActive(tool.name) && selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)
|
|
1819
|
+
).map((tool) => tool.name);
|
|
1820
|
+
return `Plan policy will allow: ${allowed.length > 0 ? allowed.join(", ") : "none"}.`;
|
|
1821
|
+
},
|
|
1385
1822
|
tools: tools.map((tool) => {
|
|
1386
1823
|
const selectable = canSelectToolInPlanMode(tool);
|
|
1387
|
-
const
|
|
1824
|
+
const active = toolIsActive(tool.name);
|
|
1825
|
+
const policy = active ? toolPolicyLabel(tool) : "not active in this Pi session";
|
|
1388
1826
|
const description = tool.description ?? "No description available";
|
|
1389
1827
|
return {
|
|
1390
1828
|
name: tool.name,
|
|
1391
1829
|
description: `${policy} \xB7 ${description}`,
|
|
1392
1830
|
searchText: [policy, description].join(" "),
|
|
1393
|
-
disabled: !selectable,
|
|
1394
|
-
disabledReason: selectable ? void 0 : "Blocked by Plan-mode policy"
|
|
1831
|
+
disabled: !selectable || !active,
|
|
1832
|
+
disabledReason: !active ? "Not active in Pi; Plan mode will not activate it" : selectable ? void 0 : "Blocked by Plan-mode policy"
|
|
1395
1833
|
};
|
|
1396
1834
|
}),
|
|
1397
1835
|
...lifecycle,
|
|
@@ -1406,7 +1844,7 @@ ${intent.plan}`,
|
|
|
1406
1844
|
},
|
|
1407
1845
|
startWithTools: (names, signal) => {
|
|
1408
1846
|
if (signal.aborted || !lifecycle.isCurrent()) return;
|
|
1409
|
-
const selectedToolNames = filterAvailableSelectedToolNames(names,
|
|
1847
|
+
const selectedToolNames = filterAvailableSelectedToolNames(names, activePlanPolicyTools());
|
|
1410
1848
|
if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: void 0 })) {
|
|
1411
1849
|
ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
|
|
1412
1850
|
}
|
|
@@ -1440,8 +1878,7 @@ ${intent.plan}`,
|
|
|
1440
1878
|
}
|
|
1441
1879
|
},
|
|
1442
1880
|
clear: () => {
|
|
1443
|
-
exitPlanMode(ctx);
|
|
1444
|
-
ctx.ui.notify("Active implementation plan cleared.", "info");
|
|
1881
|
+
if (exitPlanMode(ctx)) ctx.ui.notify("Active implementation plan cleared.", "info");
|
|
1445
1882
|
}
|
|
1446
1883
|
});
|
|
1447
1884
|
}
|
|
@@ -1451,9 +1888,11 @@ ${intent.plan}`,
|
|
|
1451
1888
|
if (!isCurrent() || signal.aborted) return false;
|
|
1452
1889
|
const result = await ui.showPlanModeSettings(ctx, {
|
|
1453
1890
|
tools: selectableTools(),
|
|
1891
|
+
activeToolNames: activeToolBaseline,
|
|
1454
1892
|
signal,
|
|
1455
1893
|
isCurrent,
|
|
1456
1894
|
settingsPath: dependencies.settingsPath,
|
|
1895
|
+
updateSettings: (patch, options) => updateSettingsWithRuntime(patch, options, ctx, isCurrent),
|
|
1457
1896
|
onSaved: (saved) => {
|
|
1458
1897
|
if (!isCurrent()) return;
|
|
1459
1898
|
settings = saved;
|
|
@@ -1463,6 +1902,71 @@ ${intent.plan}`,
|
|
|
1463
1902
|
});
|
|
1464
1903
|
return result.kind === "closed" && "reason" in result && result.reason === "close";
|
|
1465
1904
|
}
|
|
1905
|
+
async function updateSettingsWithRuntime(patch, options, ctx, isCurrent) {
|
|
1906
|
+
const previousVisibility = configuredPlanModeToolVisibility(settings);
|
|
1907
|
+
const nextVisibility = patch.toolVisibility ?? previousVisibility;
|
|
1908
|
+
const persistSettings = dependencies.updateSettings ?? updatePlanModeSettings;
|
|
1909
|
+
if (nextVisibility === previousVisibility) {
|
|
1910
|
+
return persistSettings(patch, options);
|
|
1911
|
+
}
|
|
1912
|
+
if (!ctx.isIdle()) {
|
|
1913
|
+
throw new Error("Wait for Pi to become idle before changing Plan tool visibility.");
|
|
1914
|
+
}
|
|
1915
|
+
bindWorkflowSessionIfNeeded(ctx);
|
|
1916
|
+
const applicationSession = ctx.sessionManager;
|
|
1917
|
+
const applicationGeneration = menuGeneration;
|
|
1918
|
+
const applicationIsCurrent = () => currentSession === applicationSession && menuGeneration === applicationGeneration && isCurrent();
|
|
1919
|
+
const retainedOwner = workflowMutex.isOwner(workflowOwner);
|
|
1920
|
+
const temporaryOwner = retainedOwner ? workflowOwner : workflowMutex.acquire();
|
|
1921
|
+
if (!temporaryOwner) {
|
|
1922
|
+
throw new Error(
|
|
1923
|
+
"Another workflow is active in this session. Plan tool visibility was not changed."
|
|
1924
|
+
);
|
|
1925
|
+
}
|
|
1926
|
+
const visibilitySnapshot = helperVisibility.snapshot();
|
|
1927
|
+
try {
|
|
1928
|
+
helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
|
|
1929
|
+
const saved = await persistSettings(patch, options);
|
|
1930
|
+
if (!applicationIsCurrent()) {
|
|
1931
|
+
throw new DOMException("Plan settings session replaced", "AbortError");
|
|
1932
|
+
}
|
|
1933
|
+
settings = saved;
|
|
1934
|
+
applyPlanModeShortcut(configuredPlanModeToggleShortcut(saved));
|
|
1935
|
+
return saved;
|
|
1936
|
+
} catch (error) {
|
|
1937
|
+
if (applicationIsCurrent()) {
|
|
1938
|
+
try {
|
|
1939
|
+
helperVisibility.restore(visibilitySnapshot);
|
|
1940
|
+
} catch (rollbackError) {
|
|
1941
|
+
throw new AggregateError(
|
|
1942
|
+
[error, rollbackError],
|
|
1943
|
+
"Plan tool visibility settings failed and runtime rollback was incomplete."
|
|
1944
|
+
);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
throw error;
|
|
1948
|
+
} finally {
|
|
1949
|
+
if (!retainedOwner) workflowMutex.release(temporaryOwner);
|
|
1950
|
+
if (!isCurrent()) latestCommandContext = void 0;
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
function allowModeTransition(ctx, action) {
|
|
1954
|
+
if (ctx.isIdle()) return true;
|
|
1955
|
+
const message = `Cannot ${action} while an agent run is active. Wait for the run to settle, then retry.`;
|
|
1956
|
+
if (!ctx.hasUI) throw new Error(message);
|
|
1957
|
+
ctx.ui.notify(message, "warning");
|
|
1958
|
+
return false;
|
|
1959
|
+
}
|
|
1960
|
+
function advanceWorkflowGeneration() {
|
|
1961
|
+
workflowGeneration += 1;
|
|
1962
|
+
finalizationRequest.reset();
|
|
1963
|
+
}
|
|
1964
|
+
function finalizationRunOutcome(messages) {
|
|
1965
|
+
const stopReason = latestAssistantStopReason(messages);
|
|
1966
|
+
if (stopReason === void 0 || stopReason === "stop") return "normal";
|
|
1967
|
+
if (stopReason === "aborted") return "cancelled";
|
|
1968
|
+
return "error";
|
|
1969
|
+
}
|
|
1466
1970
|
function captureMenuLifecycle() {
|
|
1467
1971
|
const sessionGeneration = menuGeneration;
|
|
1468
1972
|
const planWorkflowGeneration = workflowGeneration;
|
|
@@ -1473,22 +1977,83 @@ ${intent.plan}`,
|
|
|
1473
1977
|
isCurrent: () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !controller.signal.aborted && (!state.enabled || workflowMutex.isOwner(owner))
|
|
1474
1978
|
};
|
|
1475
1979
|
}
|
|
1476
|
-
function
|
|
1477
|
-
|
|
1478
|
-
applyPlanModeTools();
|
|
1980
|
+
function captureToolBaseline() {
|
|
1981
|
+
activeToolBaseline = withRequiredPlanModeTools(safeGetActiveTools());
|
|
1479
1982
|
}
|
|
1480
|
-
function
|
|
1481
|
-
|
|
1983
|
+
function applyWatchedHelperVisibility(previousSettings, nextSettings, ctx) {
|
|
1984
|
+
const previousVisibility = configuredPlanModeToolVisibility(previousSettings);
|
|
1985
|
+
const nextVisibility = configuredPlanModeToolVisibility(nextSettings);
|
|
1986
|
+
if (previousVisibility === nextVisibility) return;
|
|
1987
|
+
if (state.enabled) {
|
|
1988
|
+
helperVisibility.deferVisibilityChange(nextVisibility);
|
|
1989
|
+
return;
|
|
1990
|
+
}
|
|
1991
|
+
try {
|
|
1992
|
+
if (!ctx.isIdle()) {
|
|
1993
|
+
helperVisibility.deferVisibilityChange(nextVisibility);
|
|
1994
|
+
return;
|
|
1995
|
+
}
|
|
1996
|
+
} catch {
|
|
1997
|
+
helperVisibility.deferVisibilityChange(nextVisibility);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
const owner = workflowMutex.acquire();
|
|
2001
|
+
if (!owner) {
|
|
2002
|
+
helperVisibility.deferVisibilityChange(nextVisibility);
|
|
2003
|
+
return;
|
|
2004
|
+
}
|
|
2005
|
+
const snapshot = helperVisibility.snapshot();
|
|
2006
|
+
try {
|
|
2007
|
+
helperVisibility.applyVisibilityChange(previousVisibility, nextVisibility, ctx);
|
|
2008
|
+
} catch (error) {
|
|
2009
|
+
helperVisibility.restore(snapshot);
|
|
2010
|
+
helperVisibility.deferVisibilityChange(nextVisibility);
|
|
2011
|
+
if (ctx.hasUI) {
|
|
2012
|
+
const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
|
|
2013
|
+
ctx.ui.notify(
|
|
2014
|
+
`Could not apply reloaded Plan tool visibility; the current tool envelope remains unchanged until a later safe boundary: ${detail}`,
|
|
2015
|
+
"warning"
|
|
2016
|
+
);
|
|
2017
|
+
}
|
|
2018
|
+
} finally {
|
|
2019
|
+
workflowMutex.release(owner);
|
|
2020
|
+
}
|
|
1482
2021
|
}
|
|
1483
|
-
function
|
|
1484
|
-
const
|
|
1485
|
-
if (
|
|
1486
|
-
|
|
2022
|
+
function reconcileInactiveHelperVisibility(previousVisibility, ctx) {
|
|
2023
|
+
const owner = workflowMutex.acquire();
|
|
2024
|
+
if (!owner) {
|
|
2025
|
+
if (ctx.hasUI) {
|
|
2026
|
+
ctx.ui.notify(
|
|
2027
|
+
"Plan tool visibility was deferred because another workflow is active in this session.",
|
|
2028
|
+
"warning"
|
|
2029
|
+
);
|
|
2030
|
+
}
|
|
2031
|
+
return false;
|
|
1487
2032
|
}
|
|
2033
|
+
const snapshot = helperVisibility.snapshot();
|
|
2034
|
+
try {
|
|
2035
|
+
const visibility = configuredPlanModeToolVisibility(settings);
|
|
2036
|
+
helperVisibility.prepareSessionStart(visibility, previousVisibility);
|
|
2037
|
+
helperVisibility.reconcileInactiveState(visibility);
|
|
2038
|
+
return true;
|
|
2039
|
+
} catch (error) {
|
|
2040
|
+
helperVisibility.restore(snapshot);
|
|
2041
|
+
if (ctx.hasUI) {
|
|
2042
|
+
const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
|
|
2043
|
+
ctx.ui.notify(`Could not apply Plan tool visibility: ${detail}`, "error");
|
|
2044
|
+
}
|
|
2045
|
+
return false;
|
|
2046
|
+
} finally {
|
|
2047
|
+
workflowMutex.release(owner);
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
function planModePolicyToolNames() {
|
|
2051
|
+
return workflowAllowedToolNames ?? computePlanModePolicyToolNames();
|
|
2052
|
+
}
|
|
2053
|
+
function computePlanModePolicyToolNames() {
|
|
2054
|
+
const tools = activePlanPolicyTools();
|
|
1488
2055
|
const selectedNames = snapshotPlanModeSelectedNames(tools, toolSelectionSnapshot());
|
|
1489
|
-
return
|
|
1490
|
-
tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name)
|
|
1491
|
-
);
|
|
2056
|
+
return tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name);
|
|
1492
2057
|
}
|
|
1493
2058
|
function toolSelectionSnapshot() {
|
|
1494
2059
|
return {
|
|
@@ -1502,6 +2067,13 @@ ${intent.plan}`,
|
|
|
1502
2067
|
(tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME
|
|
1503
2068
|
).sort(compareTools);
|
|
1504
2069
|
}
|
|
2070
|
+
function activePlanPolicyTools() {
|
|
2071
|
+
const activeNames = new Set(activeToolBaseline);
|
|
2072
|
+
return selectableTools().filter((tool) => activeNames.has(tool.name));
|
|
2073
|
+
}
|
|
2074
|
+
function toolIsActive(toolName) {
|
|
2075
|
+
return activeToolBaseline.includes(toolName);
|
|
2076
|
+
}
|
|
1505
2077
|
function safeGetAllTools() {
|
|
1506
2078
|
try {
|
|
1507
2079
|
return pi.getAllTools();
|
|
@@ -1509,15 +2081,10 @@ ${intent.plan}`,
|
|
|
1509
2081
|
return [];
|
|
1510
2082
|
}
|
|
1511
2083
|
}
|
|
1512
|
-
function restoreTools() {
|
|
1513
|
-
const restoredTools = previousTools ?? DEFAULT_TOOLS;
|
|
1514
|
-
pi.setActiveTools(withoutRequiredPlanModeTools(restoredTools));
|
|
1515
|
-
previousTools = void 0;
|
|
1516
|
-
}
|
|
1517
2084
|
function applyPlanThinkingLevel() {
|
|
1518
2085
|
if (state.manualThinkingLevel) {
|
|
1519
2086
|
if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
|
|
1520
|
-
|
|
2087
|
+
pi.setThinkingLevel(state.manualThinkingLevel);
|
|
1521
2088
|
}
|
|
1522
2089
|
return;
|
|
1523
2090
|
}
|
|
@@ -1532,7 +2099,7 @@ ${intent.plan}`,
|
|
|
1532
2099
|
}
|
|
1533
2100
|
const current = pi.getThinkingLevel();
|
|
1534
2101
|
if (!state.appliedThinkingLevel) state.previousThinkingLevel = current;
|
|
1535
|
-
if (current !== configured)
|
|
2102
|
+
if (current !== configured) pi.setThinkingLevel(configured);
|
|
1536
2103
|
state.appliedThinkingLevel = pi.getThinkingLevel();
|
|
1537
2104
|
}
|
|
1538
2105
|
function captureManualThinkingLevel() {
|
|
@@ -1550,17 +2117,10 @@ ${intent.plan}`,
|
|
|
1550
2117
|
captureManualThinkingLevel();
|
|
1551
2118
|
const { appliedThinkingLevel, previousThinkingLevel } = state;
|
|
1552
2119
|
if (appliedThinkingLevel && previousThinkingLevel && pi.getThinkingLevel() === appliedThinkingLevel) {
|
|
1553
|
-
|
|
2120
|
+
pi.setThinkingLevel(previousThinkingLevel);
|
|
1554
2121
|
}
|
|
1555
2122
|
state = { ...state, appliedThinkingLevel: void 0, previousThinkingLevel: void 0 };
|
|
1556
2123
|
}
|
|
1557
|
-
function deactivatePlanModeQuestionTool() {
|
|
1558
|
-
const activeTools = safeGetActiveTools();
|
|
1559
|
-
const filteredTools = withoutRequiredPlanModeTools(activeTools);
|
|
1560
|
-
if (filteredTools.length !== activeTools.length) {
|
|
1561
|
-
pi.setActiveTools(filteredTools);
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
2124
|
function safeGetActiveTools() {
|
|
1565
2125
|
try {
|
|
1566
2126
|
return pi.getActiveTools();
|
|
@@ -1568,52 +2128,60 @@ ${intent.plan}`,
|
|
|
1568
2128
|
return DEFAULT_TOOLS;
|
|
1569
2129
|
}
|
|
1570
2130
|
}
|
|
1571
|
-
function
|
|
1572
|
-
return restorePlanModeState(ctx.sessionManager.getBranch(), STATE_ENTRY_TYPE);
|
|
1573
|
-
}
|
|
1574
|
-
function installRestoredState(candidate, ctx) {
|
|
2131
|
+
function installRestoredState(candidate, ctx, previousToolVisibility) {
|
|
1575
2132
|
const previousState = state;
|
|
1576
|
-
const
|
|
2133
|
+
const previousWorkflowAllowedToolNames = workflowAllowedToolNames;
|
|
1577
2134
|
const previousOwner = workflowOwner;
|
|
2135
|
+
const previousHelperVisibility = helperVisibility.snapshot();
|
|
1578
2136
|
const wasEnabled = state.enabled;
|
|
1579
2137
|
if (candidate.enabled && !workflowMutex.isOwner(workflowOwner)) {
|
|
1580
2138
|
const owner = workflowMutex.acquire();
|
|
1581
2139
|
if (!owner) {
|
|
1582
2140
|
state = { enabled: false, awaitingAction: false };
|
|
1583
|
-
|
|
2141
|
+
workflowAllowedToolNames = void 0;
|
|
1584
2142
|
reportRestoredWorkflowBusy(ctx);
|
|
1585
2143
|
return false;
|
|
1586
2144
|
}
|
|
1587
2145
|
workflowOwner = owner;
|
|
1588
2146
|
}
|
|
1589
2147
|
try {
|
|
2148
|
+
if (candidate.enabled) {
|
|
2149
|
+
const visibility = configuredPlanModeToolVisibility(settings);
|
|
2150
|
+
if (previousToolVisibility === void 0) {
|
|
2151
|
+
helperVisibility.prepareActivation(ctx);
|
|
2152
|
+
} else {
|
|
2153
|
+
try {
|
|
2154
|
+
helperVisibility.prepareSessionStart(visibility, previousToolVisibility);
|
|
2155
|
+
helperVisibility.prepareActivation(ctx);
|
|
2156
|
+
} catch {
|
|
2157
|
+
helperVisibility.restore(previousHelperVisibility);
|
|
2158
|
+
state = { enabled: false, awaitingAction: false };
|
|
2159
|
+
workflowAllowedToolNames = void 0;
|
|
2160
|
+
if (workflowOwner !== previousOwner) {
|
|
2161
|
+
workflowMutex.release(workflowOwner);
|
|
2162
|
+
workflowOwner = previousOwner;
|
|
2163
|
+
}
|
|
2164
|
+
reportRestoredHelpersUnavailable(ctx);
|
|
2165
|
+
return false;
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
1590
2169
|
if (wasEnabled && !candidate.enabled) {
|
|
1591
2170
|
readyPresentationIntent = void 0;
|
|
1592
|
-
restoreTools();
|
|
1593
2171
|
restoreThinkingLevel();
|
|
1594
2172
|
}
|
|
1595
2173
|
state = candidate;
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
applyPlanThinkingLevel();
|
|
1600
|
-
} else {
|
|
1601
|
-
deactivatePlanModeQuestionTool();
|
|
1602
|
-
if (wasEnabled) releaseWorkflowOwner();
|
|
1603
|
-
}
|
|
2174
|
+
workflowAllowedToolNames = state.enabled ? computePlanModePolicyToolNames() : void 0;
|
|
2175
|
+
if (state.enabled) applyPlanThinkingLevel();
|
|
2176
|
+
else if (wasEnabled) releaseWorkflowOwner();
|
|
1604
2177
|
return true;
|
|
1605
2178
|
} catch (error) {
|
|
1606
2179
|
try {
|
|
1607
|
-
if (!wasEnabled && state.enabled)
|
|
1608
|
-
try {
|
|
1609
|
-
restoreTools();
|
|
1610
|
-
} finally {
|
|
1611
|
-
restoreThinkingLevel();
|
|
1612
|
-
}
|
|
1613
|
-
}
|
|
2180
|
+
if (!wasEnabled && state.enabled) restoreThinkingLevel();
|
|
1614
2181
|
} finally {
|
|
1615
2182
|
state = previousState;
|
|
1616
|
-
|
|
2183
|
+
workflowAllowedToolNames = previousWorkflowAllowedToolNames;
|
|
2184
|
+
helperVisibility.restore(previousHelperVisibility);
|
|
1617
2185
|
if (workflowOwner !== previousOwner) {
|
|
1618
2186
|
workflowMutex.release(workflowOwner);
|
|
1619
2187
|
workflowOwner = previousOwner;
|
|
@@ -1622,21 +2190,19 @@ ${intent.plan}`,
|
|
|
1622
2190
|
throw error;
|
|
1623
2191
|
}
|
|
1624
2192
|
}
|
|
1625
|
-
function rollbackNewActivation(previousState,
|
|
2193
|
+
function rollbackNewActivation(previousState, ctx, previousOwner, previousHelperVisibility) {
|
|
1626
2194
|
const activatedOwner = workflowOwner;
|
|
1627
2195
|
readyPresentationIntent = void 0;
|
|
1628
2196
|
try {
|
|
1629
2197
|
if (state.enabled) {
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
} finally {
|
|
1633
|
-
restoreThinkingLevel();
|
|
1634
|
-
}
|
|
2198
|
+
publishModeContract("normal", ctx);
|
|
2199
|
+
restoreThinkingLevel();
|
|
1635
2200
|
}
|
|
1636
2201
|
} finally {
|
|
1637
2202
|
state = previousState;
|
|
1638
|
-
|
|
2203
|
+
workflowAllowedToolNames = void 0;
|
|
1639
2204
|
try {
|
|
2205
|
+
if (previousHelperVisibility) helperVisibility.restore(previousHelperVisibility);
|
|
1640
2206
|
persistState();
|
|
1641
2207
|
updateUi(ctx);
|
|
1642
2208
|
} finally {
|
|
@@ -1671,6 +2237,20 @@ ${intent.plan}`,
|
|
|
1671
2237
|
"warning"
|
|
1672
2238
|
);
|
|
1673
2239
|
}
|
|
2240
|
+
function reportRestoredHelpersUnavailable(ctx) {
|
|
2241
|
+
if (!ctx.hasUI) return;
|
|
2242
|
+
ctx.ui.notify(
|
|
2243
|
+
"Plan mode was not restored because its helper tools are unavailable under the active tool policy.",
|
|
2244
|
+
"warning"
|
|
2245
|
+
);
|
|
2246
|
+
}
|
|
2247
|
+
function reportHelperActivationFailure(ctx, error) {
|
|
2248
|
+
const detail = safeTerminalText(error instanceof Error ? error.message : String(error));
|
|
2249
|
+
const message = `Cannot start Plan mode: ${detail}.`;
|
|
2250
|
+
if (!ctx.hasUI) throw new Error(message, { cause: error });
|
|
2251
|
+
ctx.ui.notify(message, "error");
|
|
2252
|
+
return false;
|
|
2253
|
+
}
|
|
1674
2254
|
function updateUi(ctx) {
|
|
1675
2255
|
updatePlanModeUi(ctx, state, formatToolSummary);
|
|
1676
2256
|
}
|
|
@@ -1684,12 +2264,18 @@ ${intent.plan}`,
|
|
|
1684
2264
|
return implementationRetentionPreview(configuredImplementationPlanRetention(settings));
|
|
1685
2265
|
}
|
|
1686
2266
|
function formatToolSummary() {
|
|
1687
|
-
const names =
|
|
1688
|
-
return `
|
|
2267
|
+
const names = planModePolicyToolNames();
|
|
2268
|
+
return `Plan policy allows: ${names.length > 0 ? names.join(", ") : "none"}. Model-visible tools stay unchanged.`;
|
|
1689
2269
|
}
|
|
1690
2270
|
function toolByName(toolName) {
|
|
1691
2271
|
return safeGetAllTools().find((candidate) => candidate.name === toolName);
|
|
1692
2272
|
}
|
|
2273
|
+
function safeTerminalText(value) {
|
|
2274
|
+
return [...value].map((character) => {
|
|
2275
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
2276
|
+
return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
|
|
2277
|
+
}).join("").trim();
|
|
2278
|
+
}
|
|
1693
2279
|
}
|
|
1694
2280
|
export {
|
|
1695
2281
|
planMode as default
|