@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-plan-mode",
3
- "version": "0.52.0",
3
+ "version": "0.54.0",
4
4
  "description": "Pi extension that adds a Codex-like read-only /plan collaboration mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,9 +38,9 @@
38
38
  "@earendil-works/pi-tui": "*"
39
39
  },
40
40
  "devDependencies": {
41
- "@biomejs/biome": "2.5.9",
42
- "@earendil-works/pi-coding-agent": "0.84.2",
43
- "@earendil-works/pi-tui": "0.84.2",
41
+ "@biomejs/biome": "2.5.10",
42
+ "@earendil-works/pi-coding-agent": "0.84.3",
43
+ "@earendil-works/pi-tui": "0.84.3",
44
44
  "esbuild": "0.28.2",
45
45
  "typescript": "7.0.2"
46
46
  },
@@ -50,6 +50,6 @@
50
50
  "directory": "packages/pi-plan-mode"
51
51
  },
52
52
  "dependencies": {
53
- "@narumitw/pi-tui-kit": "^0.57.1"
53
+ "@narumitw/pi-tui-kit": "^0.58.0"
54
54
  }
55
55
  }
@@ -1,20 +1,3 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { PlanModeFixedThinkingLevel } from "./settings.js";
3
-
4
- type AgentSettledHandler = (event: unknown, ctx: ExtensionContext) => unknown;
5
-
6
- export function onAgentSettled(pi: ExtensionAPI, handler: AgentSettledHandler) {
7
- (
8
- pi as unknown as {
9
- on(event: "agent_settled", callback: AgentSettledHandler): void;
10
- }
11
- ).on("agent_settled", handler);
12
- }
13
-
14
- export function setPlanThinkingLevel(pi: ExtensionAPI, level: PlanModeFixedThinkingLevel) {
15
- (pi.setThinkingLevel as unknown as (level: PlanModeFixedThinkingLevel) => void)(level);
16
- }
17
-
18
1
  export function isStaleExtensionContextError(error: unknown) {
19
2
  return (
20
3
  error instanceof Error &&
@@ -0,0 +1,57 @@
1
+ export const FINALIZE_PLAN_PROMPT =
2
+ "Finalize the current implementation plan now. If any material decision remains, use plan_mode_question instead. Otherwise call plan_mode_complete alone as your final action with the complete decision-ready plan.";
3
+
4
+ export const RETRY_FINALIZE_PLAN_PROMPT =
5
+ "Your previous finalization response did not call plan_mode_question or plan_mode_complete. Both tools are available in the current Plan-mode request. If a material decision remains, call plan_mode_question now. Otherwise call plan_mode_complete alone with the complete decision-ready plan. Do not respond with prose about tool availability.";
6
+
7
+ export type FinalizationRunOutcome = "normal" | "cancelled" | "error";
8
+ export type FinalizationSettlementAction = "retry" | "failed" | undefined;
9
+
10
+ interface PendingFinalizationRequest {
11
+ workflowGeneration: number;
12
+ retryCount: number;
13
+ awaitingSettlement: boolean;
14
+ }
15
+
16
+ export function createFinalizationRequestCoordinator() {
17
+ let pending: PendingFinalizationRequest | undefined;
18
+
19
+ return {
20
+ request(workflowGeneration: number) {
21
+ pending = { workflowGeneration, retryCount: 0, awaitingSettlement: false };
22
+ },
23
+ satisfy() {
24
+ pending = undefined;
25
+ },
26
+ observeRunEnd(workflowGeneration: number, outcome: FinalizationRunOutcome) {
27
+ if (!pending || pending.workflowGeneration !== workflowGeneration) return;
28
+ if (outcome !== "normal") {
29
+ pending = undefined;
30
+ return;
31
+ }
32
+ pending.awaitingSettlement = true;
33
+ },
34
+ settle(workflowGeneration: number): FinalizationSettlementAction {
35
+ if (
36
+ !pending ||
37
+ pending.workflowGeneration !== workflowGeneration ||
38
+ !pending.awaitingSettlement
39
+ ) {
40
+ return undefined;
41
+ }
42
+ if (pending.retryCount === 0) {
43
+ pending.retryCount = 1;
44
+ pending.awaitingSettlement = false;
45
+ return "retry";
46
+ }
47
+ pending = undefined;
48
+ return "failed";
49
+ },
50
+ reset() {
51
+ pending = undefined;
52
+ },
53
+ hasPendingRequest() {
54
+ return pending !== undefined;
55
+ },
56
+ };
57
+ }
@@ -1,5 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { PLAN_HISTORY_IMPLEMENTATION_PROMPT } from "./message-transform.js";
4
+ import { createModeContractMessage } from "./mode-contract.js";
3
5
  import type { ImplementationPlanRetention } from "./settings.js";
4
6
  import type { PlanCompletionSource, PlanModeState } from "./state.js";
5
7
 
@@ -32,6 +34,15 @@ export function formatImplementationHandoff(plan: string) {
32
34
  return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\n\n${plan}`;
33
35
  }
34
36
 
37
+ export function formatHistoryImplementationPrompt() {
38
+ return PLAN_HISTORY_IMPLEMENTATION_PROMPT;
39
+ }
40
+
41
+ export function formatTransferredPlanPrompt(plan: string, fresh: boolean) {
42
+ const destination = fresh ? " in a fresh context" : "";
43
+ 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.\n\n${plan}`;
44
+ }
45
+
35
46
  export async function startFreshImplementationFromState(
36
47
  ctx: ExtensionContext,
37
48
  options: FreshImplementationFromStateOptions,
@@ -84,24 +95,28 @@ export async function startFreshImplementationSession(
84
95
  if (!(await preflightModel(ctx, request.isCurrent))) return { kind: "rejected" };
85
96
  if (!request.isCurrent()) return { kind: "stale" };
86
97
 
87
- const activeImplementation = {
88
- id: randomUUID(),
89
- plan: request.plan,
90
- source: request.source,
91
- startedAt: Date.now(),
92
- retention: request.retention,
93
- };
94
- const destinationState: PlanModeState = {
95
- enabled: false,
96
- awaitingAction: false,
97
- activeImplementation,
98
- };
99
- const handoff = formatImplementationHandoff(request.plan);
98
+ const usesConversationHistory = request.retention === "clear-on-start";
99
+ const destinationState: PlanModeState | undefined = usesConversationHistory
100
+ ? undefined
101
+ : {
102
+ enabled: false,
103
+ awaitingAction: false,
104
+ activeImplementation: {
105
+ id: randomUUID(),
106
+ plan: request.plan,
107
+ source: request.source,
108
+ startedAt: Date.now(),
109
+ retention: request.retention,
110
+ },
111
+ };
112
+ const handoff = usesConversationHistory
113
+ ? formatTransferredPlanPrompt(request.plan, true)
114
+ : formatImplementationHandoff(request.plan);
100
115
  const parentSession = ctx.sessionManager.getSessionFile();
101
116
  let setupError: string | undefined;
102
117
  let kickoffError: string | undefined;
103
118
 
104
- if (ctx.mode === "rpc") ctx.ui.notify("Starting fresh implementation session…", "info");
119
+ if (ctx.mode === "rpc") safeNotify(ctx, "Starting fresh implementation session…", "info");
105
120
 
106
121
  let result: Awaited<ReturnType<ExtensionCommandContext["newSession"]>>;
107
122
  try {
@@ -109,7 +124,16 @@ export async function startFreshImplementationSession(
109
124
  ...(parentSession ? { parentSession } : {}),
110
125
  setup: async (sessionManager) => {
111
126
  try {
112
- sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
127
+ const contract = createModeContractMessage("normal");
128
+ sessionManager.appendCustomMessageEntry(
129
+ contract.customType,
130
+ contract.content,
131
+ contract.display,
132
+ contract.details,
133
+ );
134
+ if (destinationState) {
135
+ sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
136
+ }
113
137
  } catch (error: unknown) {
114
138
  setupError = safeErrorDetail(error);
115
139
  }
@@ -121,17 +145,26 @@ export async function startFreshImplementationSession(
121
145
  }
122
146
  try {
123
147
  await replacementCtx.sendUserMessage(handoff);
124
- replacementCtx.ui.notify(
125
- "Fresh implementation session started. Only the approved plan was transferred.",
126
- "info",
127
- );
128
148
  } catch (error: unknown) {
129
149
  kickoffError = safeErrorDetail(error);
130
- replacementCtx.ui.notify(
131
- `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.`,
150
+ const recoveredInEditor =
151
+ usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
152
+ safeNotify(
153
+ replacementCtx,
154
+ usesConversationHistory
155
+ ? recoveredInEditor
156
+ ? `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request is in the editor; submit it or resume the parent planning session.`
157
+ : `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request could not be restored to the editor; resume the parent planning session.`
158
+ : `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.`,
132
159
  "error",
133
160
  );
161
+ return;
134
162
  }
163
+ safeNotify(
164
+ replacementCtx,
165
+ "Fresh implementation session started. Only the approved plan was transferred.",
166
+ "info",
167
+ );
135
168
  },
136
169
  });
137
170
  } catch (error: unknown) {
@@ -144,7 +177,7 @@ export async function startFreshImplementationSession(
144
177
  }
145
178
 
146
179
  if (result.cancelled) {
147
- ctx.ui.notify("Fresh implementation cancelled. The plan remains available.", "info");
180
+ safeNotify(ctx, "Fresh implementation cancelled. The plan remains available.", "info");
148
181
  return { kind: "cancelled" };
149
182
  }
150
183
  return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
@@ -174,22 +207,35 @@ async function preflightModel(ctx: ExtensionCommandContext, isCurrent: () => boo
174
207
  }
175
208
 
176
209
  function recoverSetupFailure(ctx: ReplacementContext, handoff: string, setupError: string) {
177
- ctx.ui.setEditorText(handoff);
178
- ctx.ui.notify(
179
- `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.`,
210
+ const recoveredInEditor = safeSetEditorText(ctx, handoff);
211
+ safeNotify(
212
+ ctx,
213
+ recoveredInEditor
214
+ ? `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.`
215
+ : `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.`,
180
216
  "error",
181
217
  );
182
218
  }
183
219
 
220
+ function safeSetEditorText(ctx: Pick<ExtensionContext, "ui">, text: string) {
221
+ try {
222
+ ctx.ui.setEditorText(text);
223
+ return true;
224
+ } catch {
225
+ // A replacement context can become stale while Pi reports a partial handoff.
226
+ return false;
227
+ }
228
+ }
229
+
184
230
  function safeNotify(
185
- ctx: ExtensionCommandContext,
231
+ ctx: Pick<ExtensionContext, "ui">,
186
232
  message: string,
187
233
  level: "info" | "warning" | "error",
188
234
  ) {
189
235
  try {
190
236
  ctx.ui.notify(message, level);
191
237
  } catch {
192
- // The source context can become stale if Pi fails after replacement teardown.
238
+ // A source or replacement context can become stale during session replacement.
193
239
  }
194
240
  }
195
241
 
@@ -0,0 +1,142 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { PLAN_MODE_COMPLETE_TOOL_NAME } from "./completion-tool.js";
3
+ import { PLAN_MODE_QUESTION_TOOL_NAME } from "./question-tool.js";
4
+ import type { PlanModeToolVisibility } from "./settings.js";
5
+
6
+ export const PLAN_MODE_HELPER_TOOL_NAMES = [
7
+ PLAN_MODE_QUESTION_TOOL_NAME,
8
+ PLAN_MODE_COMPLETE_TOOL_NAME,
9
+ ] as const;
10
+
11
+ export interface PlanModeHelperVisibilitySnapshot {
12
+ activeTools: string[];
13
+ helperToolsUnlocked: boolean;
14
+ helperToolsHiddenByPolicy: string[];
15
+ }
16
+
17
+ interface ToolVisibilityContext {
18
+ isIdle?: () => boolean;
19
+ }
20
+
21
+ export class PlanModeHelperVisibilityPolicy {
22
+ private unlocked = false;
23
+ private readonly hiddenByPolicy = new Set<string>();
24
+
25
+ constructor(private readonly pi: Pick<ExtensionAPI, "getActiveTools" | "setActiveTools">) {}
26
+
27
+ isUnlocked() {
28
+ return this.unlocked;
29
+ }
30
+
31
+ hasHiddenTools() {
32
+ return this.hiddenByPolicy.size > 0;
33
+ }
34
+
35
+ toolsAvailable() {
36
+ const active = new Set(this.pi.getActiveTools());
37
+ return PLAN_MODE_HELPER_TOOL_NAMES.every((name) => active.has(name));
38
+ }
39
+
40
+ prepareSessionStart(visibility: PlanModeToolVisibility, previous: PlanModeToolVisibility) {
41
+ if (visibility === "after-first-plan" && previous === "always") this.lock();
42
+ if (visibility === "always") this.reveal();
43
+ }
44
+
45
+ reconcileInactiveState(visibility: PlanModeToolVisibility) {
46
+ if (visibility === "after-first-plan" && !this.unlocked) this.hideIfLocked();
47
+ }
48
+
49
+ deferVisibilityChange(visibility: PlanModeToolVisibility) {
50
+ if (visibility === "after-first-plan") this.lock();
51
+ }
52
+
53
+ prepareActivation(ctx: ToolVisibilityContext) {
54
+ if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
55
+ throw new Error("wait until Pi is idle before revealing the Plan tools");
56
+ }
57
+ this.reveal();
58
+ }
59
+
60
+ applyVisibilityChange(
61
+ previous: PlanModeToolVisibility,
62
+ next: PlanModeToolVisibility,
63
+ ctx: ToolVisibilityContext,
64
+ ) {
65
+ if (previous === next) return;
66
+ if (next === "always") {
67
+ if (!this.toolsAvailable() && ctx.isIdle?.() !== true) {
68
+ throw new Error("Wait for Pi to become idle before revealing Plan tools.");
69
+ }
70
+ this.reveal();
71
+ return;
72
+ }
73
+ if (ctx.isIdle?.() !== true) {
74
+ throw new Error("Wait for Pi to become idle before hiding Plan tools.");
75
+ }
76
+ this.lock();
77
+ this.hideIfLocked();
78
+ }
79
+
80
+ hideIfLocked() {
81
+ if (this.unlocked) return;
82
+ const active = this.pi.getActiveTools();
83
+ const hidden = active.filter((name) => this.isHelperTool(name));
84
+ if (hidden.length === 0) return;
85
+ this.pi.setActiveTools(active.filter((name) => !this.isHelperTool(name)));
86
+ for (const name of hidden) this.hiddenByPolicy.add(name);
87
+ }
88
+
89
+ snapshot(): PlanModeHelperVisibilitySnapshot {
90
+ return {
91
+ activeTools: this.pi.getActiveTools(),
92
+ helperToolsUnlocked: this.unlocked,
93
+ helperToolsHiddenByPolicy: [...this.hiddenByPolicy],
94
+ };
95
+ }
96
+
97
+ restore(snapshot: PlanModeHelperVisibilitySnapshot) {
98
+ this.pi.setActiveTools(snapshot.activeTools);
99
+ this.unlocked = snapshot.helperToolsUnlocked;
100
+ this.hiddenByPolicy.clear();
101
+ for (const name of snapshot.helperToolsHiddenByPolicy) this.hiddenByPolicy.add(name);
102
+ }
103
+
104
+ private reveal() {
105
+ const snapshot = this.snapshot();
106
+ try {
107
+ const active = this.pi.getActiveTools();
108
+ const canonical = [
109
+ ...active.filter((name) => !this.isHelperTool(name)),
110
+ ...PLAN_MODE_HELPER_TOOL_NAMES,
111
+ ];
112
+ if (
113
+ canonical.length !== active.length ||
114
+ canonical.some((name, index) => name !== active[index])
115
+ ) {
116
+ this.pi.setActiveTools(canonical);
117
+ }
118
+ if (!this.toolsAvailable()) {
119
+ throw new Error(
120
+ "plan_mode_question and plan_mode_complete are unavailable; leave the restrictive tool mode before starting Plan mode",
121
+ );
122
+ }
123
+ this.unlockAndForgetHidden();
124
+ } catch (error) {
125
+ this.restore(snapshot);
126
+ throw error;
127
+ }
128
+ }
129
+
130
+ private lock() {
131
+ this.unlocked = false;
132
+ }
133
+
134
+ private unlockAndForgetHidden() {
135
+ this.unlocked = true;
136
+ this.hiddenByPolicy.clear();
137
+ }
138
+
139
+ private isHelperTool(name: string) {
140
+ return (PLAN_MODE_HELPER_TOOL_NAMES as readonly string[]).includes(name);
141
+ }
142
+ }
@@ -1,4 +1,5 @@
1
1
  import {
2
+ findHistoryImplementationArtifact,
2
3
  injectActiveImplementationContext,
3
4
  isEmptyAssistantMessage,
4
5
  messageContainsExactPlanModeImplementationHandoff,
@@ -14,18 +15,17 @@ import type { ActiveImplementationPlan, PlanModeState } from "./state.js";
14
15
 
15
16
  export function retentionLabel(retention: ImplementationPlanRetention) {
16
17
  return {
17
- keep: "Keep plan active",
18
- "clear-on-start": "Use plan for handoff only",
19
- "clear-after-first-run": "Clear after first implementation run",
18
+ "clear-on-start": "Off — conversation history only",
19
+ "clear-after-first-run": "Through first implementation run",
20
+ keep: "Until manually cleared",
20
21
  }[retention];
21
22
  }
22
23
 
23
24
  export function implementationRetentionPreview(retention: ImplementationPlanRetention) {
24
25
  return {
25
- keep: "After Implement: Keep plan active until /plan exit.",
26
- "clear-on-start":
27
- "After Implement: Use the plan for the implementation handoff only, then clear it.",
28
- "clear-after-first-run": "After Implement: Clear after the first implementation run settles.",
26
+ "clear-on-start": "Plan reinjection: Off; use conversation history only.",
27
+ "clear-after-first-run": "Plan reinjection: Through the first implementation run.",
28
+ keep: "Plan reinjection: Until /plan exit.",
29
29
  }[retention];
30
30
  }
31
31
 
@@ -55,29 +55,53 @@ export function createImplementationRetentionCoordinator(): ImplementationRetent
55
55
  : undefined;
56
56
  },
57
57
  transformContext(messages, state) {
58
- const messagesWithoutPlanContext = messages.filter(
59
- (message) =>
60
- !messageContainsLegacyPlanModeContextArtifact(message) &&
61
- !messageContainsPlanModeImplementationContextArtifact(message),
58
+ const messagesWithoutLegacyContext = messages.filter(
59
+ (message) => !messageContainsLegacyPlanModeContextArtifact(message),
62
60
  );
63
61
  if (state.enabled) {
64
62
  return {
65
- messages: messagesWithoutPlanContext.filter(
66
- (message) => !messageContainsPlanModeImplementationHandoff(message),
63
+ messages: messagesWithoutLegacyContext.filter(
64
+ (message) =>
65
+ !messageContainsPlanModeImplementationContextArtifact(message) &&
66
+ !messageContainsPlanModeImplementationHandoff(message),
67
67
  ),
68
68
  };
69
69
  }
70
70
 
71
71
  const activeImplementation = state.activeImplementation;
72
72
  const inactiveMessages = activeImplementation
73
- ? messagesWithoutPlanContext
74
- : messagesWithoutPlanContext.filter(
75
- (message) => !messageContainsPlanModeImplementationHandoff(message),
73
+ ? messagesWithoutLegacyContext
74
+ : messagesWithoutLegacyContext.filter(
75
+ (message) =>
76
+ !messageContainsPlanModeImplementationContextArtifact(message) &&
77
+ !messageContainsPlanModeImplementationHandoff(message),
76
78
  );
79
+ const historyArtifact = activeImplementation
80
+ ? undefined
81
+ : findHistoryImplementationArtifact(inactiveMessages);
82
+ const historyArtifactMessage = historyArtifact
83
+ ? inactiveMessages[historyArtifact.messageIndex]
84
+ : undefined;
85
+ const historyToolCallMessage =
86
+ historyArtifact?.toolCallMessageIndex !== undefined
87
+ ? inactiveMessages[historyArtifact.toolCallMessageIndex]
88
+ : undefined;
77
89
  const filteredMessages = inactiveMessages
78
- .filter((message) => !messageContainsInactivePlanModeArtifact(message))
79
- .map(stripProposedPlanBlocksFromMessage)
80
- .map(stripPlanModeCompletionCallsFromMessage)
90
+ .filter(
91
+ (message) =>
92
+ message === historyArtifactMessage || !messageContainsInactivePlanModeArtifact(message),
93
+ )
94
+ .map((message) =>
95
+ message === historyArtifactMessage && historyArtifact?.kind === "legacy"
96
+ ? message
97
+ : stripProposedPlanBlocksFromMessage(message),
98
+ )
99
+ .map((message) =>
100
+ stripPlanModeCompletionCallsFromMessage(
101
+ message,
102
+ message === historyToolCallMessage ? historyArtifact?.toolCallId : undefined,
103
+ ),
104
+ )
81
105
  .filter((message) => !isEmptyAssistantMessage(message));
82
106
  if (!activeImplementation) return { messages: filteredMessages };
83
107