@narumitw/pi-plan-mode 0.58.0 → 0.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/chunks/{chunk-QHHHBTDO.js → chunk-HF7ZEYIC.js} +29 -111
  2. package/dist/chunks/chunk-HF7ZEYIC.js.map +7 -0
  3. package/dist/chunks/{interactive-ui-UNJGC2RQ.js → interactive-ui-UK7IGPOE.js} +13 -41
  4. package/dist/chunks/interactive-ui-UK7IGPOE.js.map +7 -0
  5. package/dist/index.ts +25 -82
  6. package/dist/index.ts.map +2 -2
  7. package/package.json +50 -51
  8. package/src/active-implementation-menu.ts +57 -60
  9. package/src/command.ts +22 -22
  10. package/src/completion-tool.ts +53 -56
  11. package/src/extension-runtime.ts +5 -5
  12. package/src/finalization-request.ts +40 -44
  13. package/src/fresh-handoff-coordinator.ts +38 -41
  14. package/src/fresh-implementation.ts +293 -310
  15. package/src/implementation-models.ts +25 -30
  16. package/src/implementation-retention.ts +109 -123
  17. package/src/message-transform.ts +218 -252
  18. package/src/mode-contract.ts +46 -49
  19. package/src/plan-action-controller.ts +134 -155
  20. package/src/plan-action-menus.ts +390 -408
  21. package/src/plan-export-controller.ts +23 -28
  22. package/src/plan-export-screen.ts +13 -13
  23. package/src/plan-export.ts +85 -102
  24. package/src/plan-launch-menu.ts +119 -119
  25. package/src/plan-mode.ts +2017 -2098
  26. package/src/presentation.ts +84 -108
  27. package/src/prompt.ts +1 -1
  28. package/src/question-tool.ts +239 -267
  29. package/src/required-tools.ts +15 -19
  30. package/src/saved-plan-menu.ts +82 -84
  31. package/src/saved-plan-preflight.ts +29 -33
  32. package/src/settings-menu.ts +470 -513
  33. package/src/settings.ts +393 -452
  34. package/src/state.ts +167 -198
  35. package/src/tool-policy.ts +634 -699
  36. package/src/tool-selection.ts +39 -44
  37. package/src/workflow-mutex.ts +66 -66
  38. package/dist/chunks/chunk-QHHHBTDO.js.map +0 -7
  39. package/dist/chunks/interactive-ui-UNJGC2RQ.js.map +0 -7
@@ -5,379 +5,362 @@ import { PLAN_HISTORY_IMPLEMENTATION_PROMPT } from "./message-transform.js";
5
5
  import { createModeContractMessage } from "./mode-contract.js";
6
6
  import type { ImplementationPlanRetention } from "./settings.js";
7
7
  import {
8
- type ImplementationRuntimeSelection,
9
- isPendingImplementationModelIdentifier,
10
- MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH,
11
- type PendingImplementationRuntime,
12
- type PlanCompletionSource,
13
- type PlanModeState,
14
- restorePlanModeState,
8
+ type ImplementationRuntimeSelection,
9
+ isPendingImplementationModelIdentifier,
10
+ MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH,
11
+ type PendingImplementationRuntime,
12
+ type PlanCompletionSource,
13
+ type PlanModeState,
14
+ restorePlanModeState,
15
15
  } from "./state.js";
16
16
 
17
17
  type NewSessionOptions = Exclude<Parameters<ExtensionCommandContext["newSession"]>[0], undefined>;
18
18
  type ReplacementContext = Parameters<NonNullable<NewSessionOptions["withSession"]>>[0];
19
19
 
20
20
  export interface FreshImplementationRequest {
21
- plan: string;
22
- source: PlanCompletionSource;
23
- retention: ImplementationPlanRetention;
24
- stateEntryType: string;
25
- runtime?: ImplementationRuntimeSelection;
26
- isCurrent(): boolean;
21
+ plan: string;
22
+ source: PlanCompletionSource;
23
+ retention: ImplementationPlanRetention;
24
+ stateEntryType: string;
25
+ runtime?: ImplementationRuntimeSelection;
26
+ isCurrent(): boolean;
27
27
  }
28
28
 
29
29
  interface FreshImplementationFromStateOptions {
30
- getState(): PlanModeState;
31
- menuIsCurrent(): boolean;
32
- retention: ImplementationPlanRetention;
33
- stateEntryType: string;
34
- runtime?: ImplementationRuntimeSelection;
30
+ getState(): PlanModeState;
31
+ menuIsCurrent(): boolean;
32
+ retention: ImplementationPlanRetention;
33
+ stateEntryType: string;
34
+ runtime?: ImplementationRuntimeSelection;
35
35
  }
36
36
 
37
37
  export type FreshImplementationResult =
38
- | { kind: "started" }
39
- | { kind: "cancelled" }
40
- | { kind: "partial" }
41
- | { kind: "rejected" }
42
- | { kind: "stale" };
38
+ | { kind: "started" }
39
+ | { kind: "cancelled" }
40
+ | { kind: "partial" }
41
+ | { kind: "rejected" }
42
+ | { kind: "stale" };
43
43
 
44
44
  export function formatImplementationHandoff(plan: string) {
45
- return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\n\n${plan}`;
45
+ return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:\n\n${plan}`;
46
46
  }
47
47
 
48
48
  export function formatHistoryImplementationPrompt() {
49
- return PLAN_HISTORY_IMPLEMENTATION_PROMPT;
49
+ return PLAN_HISTORY_IMPLEMENTATION_PROMPT;
50
50
  }
51
51
 
52
52
  export function formatTransferredPlanPrompt(plan: string, fresh: boolean) {
53
- const destination = fresh ? " in a fresh context" : "";
54
- 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}`;
53
+ const destination = fresh ? " in a fresh context" : "";
54
+ 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}`;
55
55
  }
56
56
 
57
57
  export async function startFreshImplementationFromState(
58
- ctx: ExtensionContext,
59
- options: FreshImplementationFromStateOptions,
58
+ ctx: ExtensionContext,
59
+ options: FreshImplementationFromStateOptions,
60
60
  ) {
61
- if (!isCommandContext(ctx)) {
62
- ctx.ui.notify(
63
- "Fresh implementation requires the interactive /plan command. Reopen /plan and try again.",
64
- "warning",
65
- );
66
- return { kind: "rejected" } as const;
67
- }
68
- const initialState = options.getState();
69
- const savedPlan = initialState.enabled ? undefined : initialState.savedPlan;
70
- const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();
71
- const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;
72
- if (!plan || !source) {
73
- ctx.ui.notify("No completed plan is available to implement.", "warning");
74
- return { kind: "rejected" } as const;
75
- }
76
- const wasEnabled = initialState.enabled;
77
- const isCurrent = () => {
78
- const current = options.getState();
79
- return (
80
- options.menuIsCurrent() &&
81
- current.enabled === wasEnabled &&
82
- (wasEnabled
83
- ? current.latestPlan === plan && current.latestPlanSource === source
84
- : current.savedPlan === savedPlan)
85
- );
86
- };
87
- return startFreshImplementationSession(ctx, {
88
- plan,
89
- source,
90
- retention: options.retention,
91
- stateEntryType: options.stateEntryType,
92
- runtime: options.runtime,
93
- isCurrent,
94
- });
61
+ if (!isCommandContext(ctx)) {
62
+ ctx.ui.notify(
63
+ "Fresh implementation requires the interactive /plan command. Reopen /plan and try again.",
64
+ "warning",
65
+ );
66
+ return { kind: "rejected" } as const;
67
+ }
68
+ const initialState = options.getState();
69
+ const savedPlan = initialState.enabled ? undefined : initialState.savedPlan;
70
+ const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();
71
+ const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;
72
+ if (!plan || !source) {
73
+ ctx.ui.notify("No completed plan is available to implement.", "warning");
74
+ return { kind: "rejected" } as const;
75
+ }
76
+ const wasEnabled = initialState.enabled;
77
+ const isCurrent = () => {
78
+ const current = options.getState();
79
+ return (
80
+ options.menuIsCurrent() &&
81
+ current.enabled === wasEnabled &&
82
+ (wasEnabled
83
+ ? current.latestPlan === plan && current.latestPlanSource === source
84
+ : current.savedPlan === savedPlan)
85
+ );
86
+ };
87
+ return startFreshImplementationSession(ctx, {
88
+ plan,
89
+ source,
90
+ retention: options.retention,
91
+ stateEntryType: options.stateEntryType,
92
+ runtime: options.runtime,
93
+ isCurrent,
94
+ });
95
95
  }
96
96
 
97
97
  export async function startFreshImplementationSession(
98
- ctx: ExtensionCommandContext,
99
- request: FreshImplementationRequest,
98
+ ctx: ExtensionCommandContext,
99
+ request: FreshImplementationRequest,
100
100
  ): Promise<FreshImplementationResult> {
101
- if (ctx.mode === "print" || ctx.mode === "json") {
102
- throw new Error("Fresh plan implementation is unavailable in print/JSON mode. Use TUI or RPC.");
103
- }
101
+ if (ctx.mode === "print" || ctx.mode === "json") {
102
+ throw new Error("Fresh plan implementation is unavailable in print/JSON mode. Use TUI or RPC.");
103
+ }
104
104
 
105
- await ctx.waitForIdle();
106
- if (!request.isCurrent()) return { kind: "stale" };
107
- if (!(await preflightModel(ctx, request))) return { kind: "rejected" };
108
- if (!request.isCurrent()) return { kind: "stale" };
105
+ await ctx.waitForIdle();
106
+ if (!request.isCurrent()) return { kind: "stale" };
107
+ if (!(await preflightModel(ctx, request))) return { kind: "rejected" };
108
+ if (!request.isCurrent()) return { kind: "stale" };
109
109
 
110
- const usesConversationHistory = request.retention === "clear-on-start";
111
- const pendingImplementationRuntime = pendingRuntimeIntent(request.runtime);
112
- const activeImplementation = usesConversationHistory
113
- ? undefined
114
- : {
115
- id: randomUUID(),
116
- plan: request.plan,
117
- source: request.source,
118
- startedAt: Date.now(),
119
- retention: request.retention,
120
- };
121
- const destinationState: PlanModeState | undefined =
122
- activeImplementation || pendingImplementationRuntime
123
- ? {
124
- enabled: false,
125
- awaitingAction: false,
126
- ...(activeImplementation ? { activeImplementation } : {}),
127
- ...(pendingImplementationRuntime ? { pendingImplementationRuntime } : {}),
128
- }
129
- : undefined;
130
- const handoff = usesConversationHistory
131
- ? formatTransferredPlanPrompt(request.plan, true)
132
- : formatImplementationHandoff(request.plan);
133
- const parentSession = ctx.sessionManager.getSessionFile();
134
- let setupError: string | undefined;
135
- let kickoffError: string | undefined;
110
+ const usesConversationHistory = request.retention === "clear-on-start";
111
+ const pendingImplementationRuntime = pendingRuntimeIntent(request.runtime);
112
+ const activeImplementation = usesConversationHistory
113
+ ? undefined
114
+ : {
115
+ id: randomUUID(),
116
+ plan: request.plan,
117
+ source: request.source,
118
+ startedAt: Date.now(),
119
+ retention: request.retention,
120
+ };
121
+ const destinationState: PlanModeState | undefined =
122
+ activeImplementation || pendingImplementationRuntime
123
+ ? {
124
+ enabled: false,
125
+ awaitingAction: false,
126
+ ...(activeImplementation ? { activeImplementation } : {}),
127
+ ...(pendingImplementationRuntime ? { pendingImplementationRuntime } : {}),
128
+ }
129
+ : undefined;
130
+ const handoff = usesConversationHistory
131
+ ? formatTransferredPlanPrompt(request.plan, true)
132
+ : formatImplementationHandoff(request.plan);
133
+ const parentSession = ctx.sessionManager.getSessionFile();
134
+ let setupError: string | undefined;
135
+ let kickoffError: string | undefined;
136
136
 
137
- if (ctx.mode === "rpc") safeNotify(ctx, "Starting fresh implementation session…", "info");
137
+ if (ctx.mode === "rpc") safeNotify(ctx, "Starting fresh implementation session…", "info");
138
138
 
139
- let result: Awaited<ReturnType<ExtensionCommandContext["newSession"]>>;
140
- try {
141
- result = await ctx.newSession({
142
- ...(parentSession ? { parentSession } : {}),
143
- setup: async (sessionManager) => {
144
- try {
145
- const contract = createModeContractMessage("normal");
146
- sessionManager.appendCustomMessageEntry(
147
- contract.customType,
148
- contract.content,
149
- contract.display,
150
- contract.details,
151
- );
152
- if (destinationState) {
153
- sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
154
- }
155
- } catch (error: unknown) {
156
- setupError = safeErrorDetail(error);
157
- }
158
- },
159
- withSession: async (replacementCtx) => {
160
- if (setupError) {
161
- recoverSetupFailure(replacementCtx, handoff, setupError);
162
- return;
163
- }
164
- const reportKickoffFailure = (detail: string) => {
165
- kickoffError = detail;
166
- const recoveredInEditor =
167
- usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
168
- safeNotify(
169
- replacementCtx,
170
- usesConversationHistory
171
- ? recoveredInEditor
172
- ? `Fresh session created, but implementation did not start: ${detail}. The implementation request is in the editor; submit it or resume the parent planning session.`
173
- : `Fresh session created, but implementation did not start: ${detail}. The implementation request could not be restored to the editor; resume the parent planning session.`
174
- : `Fresh session created, but implementation did not start: ${detail}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,
175
- "error",
176
- );
177
- };
178
- try {
179
- await replacementCtx.sendUserMessage(handoff);
180
- } catch (error: unknown) {
181
- reportKickoffFailure(safeErrorDetail(error));
182
- return;
183
- }
184
- if (pendingImplementationRuntime) {
185
- const runtimeStatus = destinationRuntimeConsumptionStatus(
186
- replacementCtx,
187
- request.stateEntryType,
188
- );
189
- if (runtimeStatus !== "consumed") {
190
- reportKickoffFailure(
191
- runtimeStatus === "pending"
192
- ? "fresh implementation settings could not be consumed"
193
- : "fresh implementation settings could not be verified as consumed",
194
- );
195
- return;
196
- }
197
- }
198
- safeNotify(
199
- replacementCtx,
200
- "Fresh implementation session started. Only the approved plan was transferred.",
201
- "info",
202
- );
203
- },
204
- });
205
- } catch (error: unknown) {
206
- safeNotify(
207
- ctx,
208
- `Unable to start a fresh implementation session: ${safeErrorDetail(error)}. The source plan remains available; retry or resume the planning session.`,
209
- "error",
210
- );
211
- return { kind: "rejected" };
212
- }
139
+ let result: Awaited<ReturnType<ExtensionCommandContext["newSession"]>>;
140
+ try {
141
+ result = await ctx.newSession({
142
+ ...(parentSession ? { parentSession } : {}),
143
+ setup: async (sessionManager) => {
144
+ try {
145
+ const contract = createModeContractMessage("normal");
146
+ sessionManager.appendCustomMessageEntry(
147
+ contract.customType,
148
+ contract.content,
149
+ contract.display,
150
+ contract.details,
151
+ );
152
+ if (destinationState) {
153
+ sessionManager.appendCustomEntry(request.stateEntryType, destinationState);
154
+ }
155
+ } catch (error: unknown) {
156
+ setupError = safeErrorDetail(error);
157
+ }
158
+ },
159
+ withSession: async (replacementCtx) => {
160
+ if (setupError) {
161
+ recoverSetupFailure(replacementCtx, handoff, setupError);
162
+ return;
163
+ }
164
+ const reportKickoffFailure = (detail: string) => {
165
+ kickoffError = detail;
166
+ const recoveredInEditor = usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
167
+ safeNotify(
168
+ replacementCtx,
169
+ usesConversationHistory
170
+ ? recoveredInEditor
171
+ ? `Fresh session created, but implementation did not start: ${detail}. The implementation request is in the editor; submit it or resume the parent planning session.`
172
+ : `Fresh session created, but implementation did not start: ${detail}. The implementation request could not be restored to the editor; resume the parent planning session.`
173
+ : `Fresh session created, but implementation did not start: ${detail}. Send a message to continue, use /plan exit to clear the active plan, or resume the parent planning session.`,
174
+ "error",
175
+ );
176
+ };
177
+ try {
178
+ await replacementCtx.sendUserMessage(handoff);
179
+ } catch (error: unknown) {
180
+ reportKickoffFailure(safeErrorDetail(error));
181
+ return;
182
+ }
183
+ if (pendingImplementationRuntime) {
184
+ const runtimeStatus = destinationRuntimeConsumptionStatus(replacementCtx, request.stateEntryType);
185
+ if (runtimeStatus !== "consumed") {
186
+ reportKickoffFailure(
187
+ runtimeStatus === "pending"
188
+ ? "fresh implementation settings could not be consumed"
189
+ : "fresh implementation settings could not be verified as consumed",
190
+ );
191
+ return;
192
+ }
193
+ }
194
+ safeNotify(
195
+ replacementCtx,
196
+ "Fresh implementation session started. Only the approved plan was transferred.",
197
+ "info",
198
+ );
199
+ },
200
+ });
201
+ } catch (error: unknown) {
202
+ safeNotify(
203
+ ctx,
204
+ `Unable to start a fresh implementation session: ${safeErrorDetail(error)}. The source plan remains available; retry or resume the planning session.`,
205
+ "error",
206
+ );
207
+ return { kind: "rejected" };
208
+ }
213
209
 
214
- if (result.cancelled) {
215
- safeNotify(ctx, "Fresh implementation cancelled. The plan remains available.", "info");
216
- return { kind: "cancelled" };
217
- }
218
- return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
210
+ if (result.cancelled) {
211
+ safeNotify(ctx, "Fresh implementation cancelled. The plan remains available.", "info");
212
+ return { kind: "cancelled" };
213
+ }
214
+ return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
219
215
  }
220
216
 
221
217
  async function preflightModel(ctx: ExtensionCommandContext, request: FreshImplementationRequest) {
222
- const requestedModel = request.runtime?.model;
223
- let model = ctx.model;
224
- if (requestedModel) {
225
- if (
226
- !isPendingImplementationModelIdentifier(requestedModel.provider) ||
227
- !isPendingImplementationModelIdentifier(requestedModel.modelId)
228
- ) {
229
- notifyCurrent(
230
- ctx,
231
- request,
232
- `Unable to implement the plan: implementation model provider and ID must each contain 1-${MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH} characters. Choose another model and retry.`,
233
- "warning",
234
- );
235
- return false;
236
- }
237
- const isCurrentModel =
238
- ctx.model?.provider === requestedModel.provider && ctx.model.id === requestedModel.modelId;
239
- if (!isCurrentModel) {
240
- try {
241
- model = ctx.modelRegistry.find(requestedModel.provider, requestedModel.modelId);
242
- } catch (error: unknown) {
243
- notifyCurrent(
244
- ctx,
245
- request,
246
- `Unable to implement the plan: ${safeErrorDetail(error)}`,
247
- "error",
248
- );
249
- return false;
250
- }
251
- }
252
- if (!model) {
253
- notifyCurrent(
254
- ctx,
255
- request,
256
- `Unable to implement the plan: implementation model ${safeModelReference(requestedModel)} is no longer available. Choose another model and retry.`,
257
- "warning",
258
- );
259
- return false;
260
- }
261
- }
262
- if (!model) {
263
- notifyCurrent(ctx, request, "Unable to implement the plan: no model is selected.", "warning");
264
- return false;
265
- }
266
- let auth: Awaited<ReturnType<ExtensionCommandContext["modelRegistry"]["getApiKeyAndHeaders"]>>;
267
- try {
268
- auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
269
- } catch (error: unknown) {
270
- notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
271
- return false;
272
- }
273
- if (!request.isCurrent()) return false;
274
- if (!auth.ok) {
275
- notifyCurrent(
276
- ctx,
277
- request,
278
- requestedModel
279
- ? `Unable to implement the plan with ${safeModelReference(model)}: ${safeErrorDetail(auth.error)}. Choose another model or configure authentication, then retry.`
280
- : `Unable to implement the plan: ${safeErrorDetail(auth.error)}`,
281
- "warning",
282
- );
283
- return false;
284
- }
285
- return true;
218
+ const requestedModel = request.runtime?.model;
219
+ let model = ctx.model;
220
+ if (requestedModel) {
221
+ if (
222
+ !isPendingImplementationModelIdentifier(requestedModel.provider) ||
223
+ !isPendingImplementationModelIdentifier(requestedModel.modelId)
224
+ ) {
225
+ notifyCurrent(
226
+ ctx,
227
+ request,
228
+ `Unable to implement the plan: implementation model provider and ID must each contain 1-${MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH} characters. Choose another model and retry.`,
229
+ "warning",
230
+ );
231
+ return false;
232
+ }
233
+ const isCurrentModel = ctx.model?.provider === requestedModel.provider && ctx.model.id === requestedModel.modelId;
234
+ if (!isCurrentModel) {
235
+ try {
236
+ model = ctx.modelRegistry.find(requestedModel.provider, requestedModel.modelId);
237
+ } catch (error: unknown) {
238
+ notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
239
+ return false;
240
+ }
241
+ }
242
+ if (!model) {
243
+ notifyCurrent(
244
+ ctx,
245
+ request,
246
+ `Unable to implement the plan: implementation model ${safeModelReference(requestedModel)} is no longer available. Choose another model and retry.`,
247
+ "warning",
248
+ );
249
+ return false;
250
+ }
251
+ }
252
+ if (!model) {
253
+ notifyCurrent(ctx, request, "Unable to implement the plan: no model is selected.", "warning");
254
+ return false;
255
+ }
256
+ let auth: Awaited<ReturnType<ExtensionCommandContext["modelRegistry"]["getApiKeyAndHeaders"]>>;
257
+ try {
258
+ auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
259
+ } catch (error: unknown) {
260
+ notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
261
+ return false;
262
+ }
263
+ if (!request.isCurrent()) return false;
264
+ if (!auth.ok) {
265
+ notifyCurrent(
266
+ ctx,
267
+ request,
268
+ requestedModel
269
+ ? `Unable to implement the plan with ${safeModelReference(model)}: ${safeErrorDetail(auth.error)}. Choose another model or configure authentication, then retry.`
270
+ : `Unable to implement the plan: ${safeErrorDetail(auth.error)}`,
271
+ "warning",
272
+ );
273
+ return false;
274
+ }
275
+ return true;
286
276
  }
287
277
 
288
278
  function notifyCurrent(
289
- ctx: Pick<ExtensionContext, "ui">,
290
- request: FreshImplementationRequest,
291
- message: string,
292
- level: "info" | "warning" | "error",
279
+ ctx: Pick<ExtensionContext, "ui">,
280
+ request: FreshImplementationRequest,
281
+ message: string,
282
+ level: "info" | "warning" | "error",
293
283
  ) {
294
- if (request.isCurrent()) safeNotify(ctx, message, level);
284
+ if (request.isCurrent()) safeNotify(ctx, message, level);
295
285
  }
296
286
 
297
287
  function pendingRuntimeIntent(
298
- selection: ImplementationRuntimeSelection | undefined,
288
+ selection: ImplementationRuntimeSelection | undefined,
299
289
  ): PendingImplementationRuntime | undefined {
300
- if (!selection?.model && !selection?.thinkingLevel) return undefined;
301
- return {
302
- version: 1,
303
- ...(selection.model
304
- ? { model: { provider: selection.model.provider, modelId: selection.model.modelId } }
305
- : {}),
306
- ...(selection.thinkingLevel ? { thinkingLevel: selection.thinkingLevel } : {}),
307
- };
290
+ if (!selection?.model && !selection?.thinkingLevel) return undefined;
291
+ return {
292
+ version: 1,
293
+ ...(selection.model ? { model: { provider: selection.model.provider, modelId: selection.model.modelId } } : {}),
294
+ ...(selection.thinkingLevel ? { thinkingLevel: selection.thinkingLevel } : {}),
295
+ };
308
296
  }
309
297
 
310
298
  function safeModelReference(model: { provider: string; id?: string; modelId?: string }) {
311
- return safeErrorDetail(`${model.provider}/${model.modelId ?? model.id ?? "unknown"}`);
299
+ return safeErrorDetail(`${model.provider}/${model.modelId ?? model.id ?? "unknown"}`);
312
300
  }
313
301
 
314
302
  function destinationRuntimeConsumptionStatus(
315
- ctx: ReplacementContext,
316
- stateEntryType: string,
303
+ ctx: ReplacementContext,
304
+ stateEntryType: string,
317
305
  ): "consumed" | "pending" | "unavailable" {
318
- try {
319
- return restorePlanModeState(ctx.sessionManager.getBranch(), stateEntryType)
320
- .pendingImplementationRuntime
321
- ? "pending"
322
- : "consumed";
323
- } catch {
324
- return "unavailable";
325
- }
306
+ try {
307
+ return restorePlanModeState(ctx.sessionManager.getBranch(), stateEntryType).pendingImplementationRuntime
308
+ ? "pending"
309
+ : "consumed";
310
+ } catch {
311
+ return "unavailable";
312
+ }
326
313
  }
327
314
 
328
315
  function recoverSetupFailure(ctx: ReplacementContext, handoff: string, setupError: string) {
329
- const recoveredInEditor = safeSetEditorText(ctx, handoff);
330
- safeNotify(
331
- ctx,
332
- recoveredInEditor
333
- ? `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.`
334
- : `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.`,
335
- "error",
336
- );
316
+ const recoveredInEditor = safeSetEditorText(ctx, handoff);
317
+ safeNotify(
318
+ ctx,
319
+ recoveredInEditor
320
+ ? `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.`
321
+ : `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.`,
322
+ "error",
323
+ );
337
324
  }
338
325
 
339
326
  function safeSetEditorText(ctx: Pick<ExtensionContext, "ui">, text: string) {
340
- try {
341
- ctx.ui.setEditorText(text);
342
- return true;
343
- } catch {
344
- // A replacement context can become stale while Pi reports a partial handoff.
345
- return false;
346
- }
327
+ try {
328
+ ctx.ui.setEditorText(text);
329
+ return true;
330
+ } catch {
331
+ // A replacement context can become stale while Pi reports a partial handoff.
332
+ return false;
333
+ }
347
334
  }
348
335
 
349
- function safeNotify(
350
- ctx: Pick<ExtensionContext, "ui">,
351
- message: string,
352
- level: "info" | "warning" | "error",
353
- ) {
354
- try {
355
- ctx.ui.notify(message, level);
356
- } catch {
357
- // A source or replacement context can become stale during session replacement.
358
- }
336
+ function safeNotify(ctx: Pick<ExtensionContext, "ui">, message: string, level: "info" | "warning" | "error") {
337
+ try {
338
+ ctx.ui.notify(message, level);
339
+ } catch {
340
+ // A source or replacement context can become stale during session replacement.
341
+ }
359
342
  }
360
343
 
361
344
  function isCommandContext(ctx: ExtensionContext): ctx is ExtensionCommandContext {
362
- return typeof (ctx as Partial<ExtensionCommandContext>).newSession === "function";
345
+ return typeof (ctx as Partial<ExtensionCommandContext>).newSession === "function";
363
346
  }
364
347
 
365
348
  function safeErrorDetail(error: unknown) {
366
- const detail = error instanceof Error ? error.message : String(error);
367
- const normalized =
368
- [...stripVTControlCharacters(detail)]
369
- .map((character) => {
370
- const codePoint = character.codePointAt(0) ?? 0;
371
- return codePoint <= 0x1f ||
372
- (codePoint >= 0x7f && codePoint <= 0x9f) ||
373
- (codePoint >= 0x202a && codePoint <= 0x202e) ||
374
- (codePoint >= 0x2066 && codePoint <= 0x2069)
375
- ? " "
376
- : character;
377
- })
378
- .join("")
379
- .replace(/\s+/gu, " ")
380
- .trim() || "unknown error";
381
- const characters = [...normalized];
382
- return characters.length > 500 ? `${characters.slice(0, 499).join("")}…` : normalized;
349
+ const detail = error instanceof Error ? error.message : String(error);
350
+ const normalized =
351
+ [...stripVTControlCharacters(detail)]
352
+ .map((character) => {
353
+ const codePoint = character.codePointAt(0) ?? 0;
354
+ return codePoint <= 0x1f ||
355
+ (codePoint >= 0x7f && codePoint <= 0x9f) ||
356
+ (codePoint >= 0x202a && codePoint <= 0x202e) ||
357
+ (codePoint >= 0x2066 && codePoint <= 0x2069)
358
+ ? " "
359
+ : character;
360
+ })
361
+ .join("")
362
+ .replace(/\s+/gu, " ")
363
+ .trim() || "unknown error";
364
+ const characters = [...normalized];
365
+ return characters.length > 500 ? `${characters.slice(0, 499).join("")}…` : normalized;
383
366
  }