@narumitw/pi-plan-mode 0.57.1 → 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 (41) hide show
  1. package/README.md +68 -4
  2. package/dist/chunks/{chunk-57OBPS7P.js → chunk-HF7ZEYIC.js} +169 -164
  3. package/dist/chunks/chunk-HF7ZEYIC.js.map +7 -0
  4. package/dist/chunks/{interactive-ui-N2ZKBVNE.js → interactive-ui-UK7IGPOE.js} +312 -32
  5. package/dist/chunks/interactive-ui-UK7IGPOE.js.map +7 -0
  6. package/dist/index.ts +670 -212
  7. package/dist/index.ts.map +4 -4
  8. package/docs/settings.md +26 -2
  9. package/package.json +50 -51
  10. package/src/active-implementation-menu.ts +57 -60
  11. package/src/command.ts +22 -21
  12. package/src/completion-tool.ts +53 -56
  13. package/src/extension-runtime.ts +5 -5
  14. package/src/finalization-request.ts +40 -44
  15. package/src/fresh-handoff-coordinator.ts +52 -0
  16. package/src/fresh-implementation.ts +312 -205
  17. package/src/implementation-models.ts +43 -0
  18. package/src/implementation-retention.ts +109 -123
  19. package/src/message-transform.ts +218 -252
  20. package/src/mode-contract.ts +46 -49
  21. package/src/plan-action-controller.ts +139 -89
  22. package/src/plan-action-menus.ts +414 -177
  23. package/src/plan-export-controller.ts +23 -28
  24. package/src/plan-export-screen.ts +13 -13
  25. package/src/plan-export.ts +85 -102
  26. package/src/plan-launch-menu.ts +119 -119
  27. package/src/plan-mode.ts +2027 -1675
  28. package/src/presentation.ts +84 -108
  29. package/src/prompt.ts +1 -1
  30. package/src/question-tool.ts +239 -267
  31. package/src/required-tools.ts +15 -19
  32. package/src/saved-plan-menu.ts +82 -84
  33. package/src/saved-plan-preflight.ts +29 -33
  34. package/src/settings-menu.ts +489 -377
  35. package/src/settings.ts +403 -382
  36. package/src/state.ts +177 -146
  37. package/src/tool-policy.ts +634 -699
  38. package/src/tool-selection.ts +39 -44
  39. package/src/workflow-mutex.ts +66 -66
  40. package/dist/chunks/chunk-57OBPS7P.js.map +0 -7
  41. package/dist/chunks/interactive-ui-N2ZKBVNE.js.map +0 -7
@@ -0,0 +1,52 @@
1
+ export interface DeferredFreshHandoffDependencies {
2
+ schedule(callback: () => void): unknown;
3
+ cancel(handle: unknown): void;
4
+ }
5
+
6
+ export interface DeferredFreshHandoffCoordinator {
7
+ schedule(run: (isCurrent: () => boolean) => Promise<void>, onError: (error: unknown) => void): void;
8
+ cancel(): void;
9
+ }
10
+
11
+ const defaultDependencies: DeferredFreshHandoffDependencies = {
12
+ schedule: (callback) => setTimeout(callback, 0),
13
+ cancel: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
14
+ };
15
+
16
+ export function createDeferredFreshHandoffCoordinator(
17
+ dependencies: DeferredFreshHandoffDependencies = defaultDependencies,
18
+ ): DeferredFreshHandoffCoordinator {
19
+ let generation = 0;
20
+ let pending: { generation: number; handle: unknown } | undefined;
21
+
22
+ const cancel = () => {
23
+ generation += 1;
24
+ if (!pending) return;
25
+ dependencies.cancel(pending.handle);
26
+ pending = undefined;
27
+ };
28
+
29
+ return {
30
+ schedule(run, onError) {
31
+ cancel();
32
+ const taskGeneration = generation;
33
+ const handle = dependencies.schedule(() => {
34
+ if (pending?.generation !== taskGeneration || generation !== taskGeneration) return;
35
+ pending = undefined;
36
+ const isCurrent = () => generation === taskGeneration;
37
+ void Promise.resolve()
38
+ .then(() => run(isCurrent))
39
+ .catch((error: unknown) => {
40
+ if (!isCurrent()) return;
41
+ try {
42
+ onError(error);
43
+ } catch {
44
+ // Detached error reporting must not create another unhandled rejection.
45
+ }
46
+ });
47
+ });
48
+ pending = { generation: taskGeneration, handle };
49
+ },
50
+ cancel,
51
+ };
52
+ }
@@ -1,259 +1,366 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { stripVTControlCharacters } from "node:util";
2
3
  import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
4
  import { PLAN_HISTORY_IMPLEMENTATION_PROMPT } from "./message-transform.js";
4
5
  import { createModeContractMessage } from "./mode-contract.js";
5
6
  import type { ImplementationPlanRetention } from "./settings.js";
6
- import type { PlanCompletionSource, PlanModeState } from "./state.js";
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,
15
+ } from "./state.js";
7
16
 
8
17
  type NewSessionOptions = Exclude<Parameters<ExtensionCommandContext["newSession"]>[0], undefined>;
9
18
  type ReplacementContext = Parameters<NonNullable<NewSessionOptions["withSession"]>>[0];
10
19
 
11
20
  export interface FreshImplementationRequest {
12
- plan: string;
13
- source: PlanCompletionSource;
14
- retention: ImplementationPlanRetention;
15
- stateEntryType: string;
16
- isCurrent(): boolean;
21
+ plan: string;
22
+ source: PlanCompletionSource;
23
+ retention: ImplementationPlanRetention;
24
+ stateEntryType: string;
25
+ runtime?: ImplementationRuntimeSelection;
26
+ isCurrent(): boolean;
17
27
  }
18
28
 
19
29
  interface FreshImplementationFromStateOptions {
20
- getState(): PlanModeState;
21
- menuIsCurrent(): boolean;
22
- retention: ImplementationPlanRetention;
23
- stateEntryType: string;
30
+ getState(): PlanModeState;
31
+ menuIsCurrent(): boolean;
32
+ retention: ImplementationPlanRetention;
33
+ stateEntryType: string;
34
+ runtime?: ImplementationRuntimeSelection;
24
35
  }
25
36
 
26
37
  export type FreshImplementationResult =
27
- | { kind: "started" }
28
- | { kind: "cancelled" }
29
- | { kind: "partial" }
30
- | { kind: "rejected" }
31
- | { kind: "stale" };
38
+ | { kind: "started" }
39
+ | { kind: "cancelled" }
40
+ | { kind: "partial" }
41
+ | { kind: "rejected" }
42
+ | { kind: "stale" };
32
43
 
33
44
  export function formatImplementationHandoff(plan: string) {
34
- 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}`;
35
46
  }
36
47
 
37
48
  export function formatHistoryImplementationPrompt() {
38
- return PLAN_HISTORY_IMPLEMENTATION_PROMPT;
49
+ return PLAN_HISTORY_IMPLEMENTATION_PROMPT;
39
50
  }
40
51
 
41
52
  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}`;
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}`;
44
55
  }
45
56
 
46
57
  export async function startFreshImplementationFromState(
47
- ctx: ExtensionContext,
48
- options: FreshImplementationFromStateOptions,
58
+ ctx: ExtensionContext,
59
+ options: FreshImplementationFromStateOptions,
49
60
  ) {
50
- if (!isCommandContext(ctx)) {
51
- ctx.ui.notify(
52
- "Fresh implementation requires the interactive /plan command. Reopen /plan and try again.",
53
- "warning",
54
- );
55
- return { kind: "rejected" } as const;
56
- }
57
- const initialState = options.getState();
58
- const savedPlan = initialState.enabled ? undefined : initialState.savedPlan;
59
- const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();
60
- const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;
61
- if (!plan || !source) {
62
- ctx.ui.notify("No completed plan is available to implement.", "warning");
63
- return { kind: "rejected" } as const;
64
- }
65
- const wasEnabled = initialState.enabled;
66
- const isCurrent = () => {
67
- const current = options.getState();
68
- return (
69
- options.menuIsCurrent() &&
70
- current.enabled === wasEnabled &&
71
- (wasEnabled
72
- ? current.latestPlan === plan && current.latestPlanSource === source
73
- : current.savedPlan === savedPlan)
74
- );
75
- };
76
- return startFreshImplementationSession(ctx, {
77
- plan,
78
- source,
79
- retention: options.retention,
80
- stateEntryType: options.stateEntryType,
81
- isCurrent,
82
- });
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
+ });
83
95
  }
84
96
 
85
97
  export async function startFreshImplementationSession(
86
- ctx: ExtensionCommandContext,
87
- request: FreshImplementationRequest,
98
+ ctx: ExtensionCommandContext,
99
+ request: FreshImplementationRequest,
88
100
  ): Promise<FreshImplementationResult> {
89
- if (ctx.mode === "print" || ctx.mode === "json") {
90
- throw new Error("Fresh plan implementation is unavailable in print/JSON mode. Use TUI or RPC.");
91
- }
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
+ }
92
104
 
93
- await ctx.waitForIdle();
94
- if (!request.isCurrent()) return { kind: "stale" };
95
- if (!(await preflightModel(ctx, request.isCurrent))) return { kind: "rejected" };
96
- 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" };
97
109
 
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);
115
- const parentSession = ctx.sessionManager.getSessionFile();
116
- let setupError: string | undefined;
117
- 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;
118
136
 
119
- if (ctx.mode === "rpc") safeNotify(ctx, "Starting fresh implementation session…", "info");
137
+ if (ctx.mode === "rpc") safeNotify(ctx, "Starting fresh implementation session…", "info");
120
138
 
121
- let result: Awaited<ReturnType<ExtensionCommandContext["newSession"]>>;
122
- try {
123
- result = await ctx.newSession({
124
- ...(parentSession ? { parentSession } : {}),
125
- setup: async (sessionManager) => {
126
- try {
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
- }
137
- } catch (error: unknown) {
138
- setupError = safeErrorDetail(error);
139
- }
140
- },
141
- withSession: async (replacementCtx) => {
142
- if (setupError) {
143
- recoverSetupFailure(replacementCtx, handoff, setupError);
144
- return;
145
- }
146
- try {
147
- await replacementCtx.sendUserMessage(handoff);
148
- } catch (error: unknown) {
149
- kickoffError = safeErrorDetail(error);
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.`,
159
- "error",
160
- );
161
- return;
162
- }
163
- safeNotify(
164
- replacementCtx,
165
- "Fresh implementation session started. Only the approved plan was transferred.",
166
- "info",
167
- );
168
- },
169
- });
170
- } catch (error: unknown) {
171
- safeNotify(
172
- ctx,
173
- `Unable to start a fresh implementation session: ${safeErrorDetail(error)}. The source plan remains available; retry or resume the planning session.`,
174
- "error",
175
- );
176
- return { kind: "rejected" };
177
- }
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
+ }
178
209
 
179
- if (result.cancelled) {
180
- safeNotify(ctx, "Fresh implementation cancelled. The plan remains available.", "info");
181
- return { kind: "cancelled" };
182
- }
183
- 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" };
184
215
  }
185
216
 
186
- async function preflightModel(ctx: ExtensionCommandContext, isCurrent: () => boolean) {
187
- const model = ctx.model;
188
- if (!model) {
189
- ctx.ui.notify("Unable to implement the plan: no model is selected.", "warning");
190
- return false;
191
- }
192
- let auth: Awaited<ReturnType<ExtensionCommandContext["modelRegistry"]["getApiKeyAndHeaders"]>>;
193
- try {
194
- auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
195
- } catch (error: unknown) {
196
- if (isCurrent()) {
197
- ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
198
- }
199
- return false;
200
- }
201
- if (!isCurrent()) return false;
202
- if (!auth.ok) {
203
- ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(auth.error)}`, "warning");
204
- return false;
205
- }
206
- return true;
217
+ async function preflightModel(ctx: ExtensionCommandContext, request: FreshImplementationRequest) {
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;
276
+ }
277
+
278
+ function notifyCurrent(
279
+ ctx: Pick<ExtensionContext, "ui">,
280
+ request: FreshImplementationRequest,
281
+ message: string,
282
+ level: "info" | "warning" | "error",
283
+ ) {
284
+ if (request.isCurrent()) safeNotify(ctx, message, level);
285
+ }
286
+
287
+ function pendingRuntimeIntent(
288
+ selection: ImplementationRuntimeSelection | undefined,
289
+ ): PendingImplementationRuntime | undefined {
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
+ };
296
+ }
297
+
298
+ function safeModelReference(model: { provider: string; id?: string; modelId?: string }) {
299
+ return safeErrorDetail(`${model.provider}/${model.modelId ?? model.id ?? "unknown"}`);
300
+ }
301
+
302
+ function destinationRuntimeConsumptionStatus(
303
+ ctx: ReplacementContext,
304
+ stateEntryType: string,
305
+ ): "consumed" | "pending" | "unavailable" {
306
+ try {
307
+ return restorePlanModeState(ctx.sessionManager.getBranch(), stateEntryType).pendingImplementationRuntime
308
+ ? "pending"
309
+ : "consumed";
310
+ } catch {
311
+ return "unavailable";
312
+ }
207
313
  }
208
314
 
209
315
  function recoverSetupFailure(ctx: ReplacementContext, handoff: string, setupError: string) {
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.`,
216
- "error",
217
- );
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
+ );
218
324
  }
219
325
 
220
326
  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
- }
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
+ }
228
334
  }
229
335
 
230
- function safeNotify(
231
- ctx: Pick<ExtensionContext, "ui">,
232
- message: string,
233
- level: "info" | "warning" | "error",
234
- ) {
235
- try {
236
- ctx.ui.notify(message, level);
237
- } catch {
238
- // A source or replacement context can become stale during session replacement.
239
- }
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
+ }
240
342
  }
241
343
 
242
344
  function isCommandContext(ctx: ExtensionContext): ctx is ExtensionCommandContext {
243
- return typeof (ctx as Partial<ExtensionCommandContext>).newSession === "function";
345
+ return typeof (ctx as Partial<ExtensionCommandContext>).newSession === "function";
244
346
  }
245
347
 
246
348
  function safeErrorDetail(error: unknown) {
247
- const detail = error instanceof Error ? error.message : String(error);
248
- const normalized =
249
- [...detail]
250
- .map((character) => {
251
- const codePoint = character.codePointAt(0) ?? 0;
252
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
253
- })
254
- .join("")
255
- .replace(/\s+/gu, " ")
256
- .trim() || "unknown error";
257
- const characters = [...normalized];
258
- 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;
259
366
  }