@narumitw/pi-plan-mode 0.56.0 → 0.57.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.
@@ -0,0 +1,145 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { ImplementationPreferences } from "./settings.js";
3
+
4
+ type Model = NonNullable<ExtensionContext["model"]>;
5
+ type Thinking = ReturnType<ExtensionAPI["getThinkingLevel"]>;
6
+ export interface ImplementationSnapshot {
7
+ model: Model | undefined;
8
+ thinking: Thinking;
9
+ }
10
+
11
+ export function observeImplementationModelSelections(pi: ExtensionAPI) {
12
+ let latest: ImplementationSnapshot | undefined;
13
+ pi.on("model_select", (_event, ctx) => {
14
+ latest = { model: ctx.model, thinking: pi.getThinkingLevel() };
15
+ });
16
+ return () => latest;
17
+ }
18
+
19
+ export function hasImplementationPreferences(preferences: ImplementationPreferences) {
20
+ return (
21
+ preferences.implementationModel !== undefined ||
22
+ (preferences.implementationThinkingLevel !== undefined &&
23
+ preferences.implementationThinkingLevel !== "inherit")
24
+ );
25
+ }
26
+
27
+ export function sameModel(
28
+ left: { provider: string; id: string } | undefined,
29
+ right: { provider: string; id: string } | undefined,
30
+ ) {
31
+ return left?.provider === right?.provider && left?.id === right?.id;
32
+ }
33
+
34
+ export function safeImplementationText(value: string) {
35
+ return [...value]
36
+ .map((character) => {
37
+ const code = character.codePointAt(0) ?? 0;
38
+ return code <= 0x1f || (code >= 0x7f && code <= 0x9f) ? " " : character;
39
+ })
40
+ .join("")
41
+ .trim();
42
+ }
43
+
44
+ export function preferenceError(error: unknown) {
45
+ return safeImplementationText(error instanceof Error ? error.message : String(error)).slice(
46
+ 0,
47
+ 500,
48
+ );
49
+ }
50
+
51
+ export async function preflightImplementationPreferences(
52
+ ctx: ExtensionContext,
53
+ preferences: ImplementationPreferences,
54
+ isCurrent: () => boolean,
55
+ ): Promise<Model | undefined> {
56
+ if (!isCurrent()) return undefined;
57
+ const identity = preferences.implementationModel;
58
+ const model = identity ? ctx.modelRegistry.find(identity.provider, identity.id) : ctx.model;
59
+ if (!model)
60
+ throw new Error(
61
+ "Implementation model is unavailable. Select a registered model or use current.",
62
+ );
63
+ // Pi's auth facade has no AbortSignal. Pi owns this operation; drain it and
64
+ // revalidate rather than claiming that cancellation stops provider auth work.
65
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
66
+ if (!isCurrent()) return undefined;
67
+ // Composed registries may materialize a new definition on every lookup.
68
+ const currentModel = identity ? ctx.modelRegistry.find(identity.provider, identity.id) : model;
69
+ if (!currentModel) {
70
+ throw new Error(
71
+ "Implementation model catalogue changed during preflight. Reopen the menu and retry.",
72
+ );
73
+ }
74
+ if (!auth.ok) throw new Error(auth.error);
75
+ return currentModel;
76
+ }
77
+
78
+ /** A one-shot handoff transaction, never an implementation-run restoration hook. */
79
+ export function createImplementationPreferenceChange(
80
+ pi: ExtensionAPI,
81
+ ctx: ExtensionContext,
82
+ isSessionCurrent: () => boolean,
83
+ original: ImplementationSnapshot = { model: ctx.model, thinking: pi.getThinkingLevel() },
84
+ selectionSnapshot?: () => ImplementationSnapshot | undefined,
85
+ ) {
86
+ let applied: ImplementationSnapshot | undefined;
87
+ const snapshot = (): ImplementationSnapshot => ({
88
+ model: ctx.model,
89
+ thinking: pi.getThinkingLevel(),
90
+ });
91
+ const matches = (value: ImplementationSnapshot) =>
92
+ sameModel(ctx.model, value.model) && pi.getThinkingLevel() === value.thinking;
93
+ return {
94
+ async apply(model: Model, preferences: ImplementationPreferences, isCurrent: () => boolean) {
95
+ if (!isCurrent()) return false;
96
+ // Includes any Plan-thinking restoration performed immediately before apply.
97
+ applied = snapshot();
98
+ if (preferences.implementationModel && !sameModel(ctx.model, model)) {
99
+ const beforeSelection = selectionSnapshot?.();
100
+ if (!(await pi.setModel(model)))
101
+ throw new Error("Implementation model authentication is unavailable.");
102
+ if (!isSessionCurrent()) return false;
103
+ if (!sameModel(ctx.model, model)) return false;
104
+ const selected = selectionSnapshot?.();
105
+ applied = selected && selected !== beforeSelection ? selected : snapshot();
106
+ if (!matches(applied)) {
107
+ if (ctx.hasUI)
108
+ ctx.ui.notify(
109
+ "Model or thinking changed during implementation preparation. The plan remains available; retry when ready.",
110
+ "warning",
111
+ );
112
+ return false;
113
+ }
114
+ if (!isCurrent()) return false;
115
+ }
116
+ const level = preferences.implementationThinkingLevel;
117
+ if (level && level !== "inherit") {
118
+ pi.setThinkingLevel(level);
119
+ applied = snapshot();
120
+ if (applied.thinking !== level && ctx.hasUI)
121
+ ctx.ui.notify(
122
+ `Implementation thinking: ${applied.thinking} (requested ${level}; adjusted by Pi for this model).`,
123
+ "info",
124
+ );
125
+ }
126
+ return isCurrent();
127
+ },
128
+ async rollback() {
129
+ if (!applied || !isSessionCurrent() || !ctx.isIdle() || !matches(applied)) return;
130
+ if (!sameModel(ctx.model, original.model)) {
131
+ const beforeSelection = selectionSnapshot?.();
132
+ if (!original.model || !(await pi.setModel(original.model))) {
133
+ throw new Error(
134
+ "Could not restore the previous model. The plan remains available; select a model before retrying.",
135
+ );
136
+ }
137
+ if (!isSessionCurrent() || !ctx.isIdle() || !sameModel(ctx.model, original.model)) return;
138
+ const selected = selectionSnapshot?.();
139
+ if (selected && selected !== beforeSelection && !matches(selected)) return;
140
+ }
141
+ pi.setThinkingLevel(original.thinking);
142
+ applied = undefined;
143
+ },
144
+ };
145
+ }
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { PlanExportDestination } from "./plan-export.js";
3
+ import type { ImplementationPreferences } from "./settings.js";
3
4
  import type { PlanModeState } from "./state.js";
4
5
 
5
6
  type InteractiveUi = typeof import("./interactive-ui.js");
@@ -18,8 +19,17 @@ interface PlanActionControllerOptions {
18
19
  getExportDestination(ctx: ExtensionContext): PlanExportDestination;
19
20
  show(ctx: ExtensionContext): void;
20
21
  finalize(ctx: ExtensionContext): void;
21
- implementHere(ctx: ExtensionContext): void | Promise<void>;
22
- implementFresh(ctx: ExtensionContext, isCurrent: () => boolean): void | Promise<void>;
22
+ getImplementationPreferences?(): ImplementationPreferences;
23
+ implementHere(
24
+ ctx: ExtensionContext,
25
+ preferences?: ImplementationPreferences,
26
+ isCurrent?: () => boolean,
27
+ ): void | Promise<void>;
28
+ implementFresh(
29
+ ctx: ExtensionContext,
30
+ isCurrent: () => boolean,
31
+ preferences?: ImplementationPreferences,
32
+ ): void | Promise<void>;
23
33
  exportPlan(
24
34
  ctx: ExtensionContext,
25
35
  path: string,
@@ -34,8 +44,17 @@ interface PlanActionControllerOptions {
34
44
  }
35
45
 
36
46
  export function createPlanActionController(options: PlanActionControllerOptions) {
37
- const freshAction = (ctx: ExtensionContext, lifecycle: MenuLifecycle, signal: AbortSignal) =>
38
- options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);
47
+ const implementationActions = (ctx: ExtensionContext, lifecycle: MenuLifecycle) => ({
48
+ implementationPreferences: options.getImplementationPreferences?.(),
49
+ implementHere: (preferences?: ImplementationPreferences, signal?: AbortSignal) =>
50
+ options.implementHere(
51
+ ctx,
52
+ preferences,
53
+ () => lifecycle.isCurrent() && !lifecycle.signal.aborted && !signal?.aborted,
54
+ ),
55
+ implementFresh: (signal: AbortSignal, preferences?: ImplementationPreferences) =>
56
+ options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted, preferences),
57
+ });
39
58
 
40
59
  return {
41
60
  async showSaved(ctx: ExtensionContext) {
@@ -50,8 +69,7 @@ export function createPlanActionController(options: PlanActionControllerOptions)
50
69
  signal: lifecycle.signal,
51
70
  isCurrent: lifecycle.isCurrent,
52
71
  show: () => options.show(ctx),
53
- implementHere: () => options.implementHere(ctx),
54
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
72
+ ...implementationActions(ctx, lifecycle),
55
73
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
56
74
  settings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),
57
75
  clear: () => options.clearSaved(ctx),
@@ -74,8 +92,7 @@ export function createPlanActionController(options: PlanActionControllerOptions)
74
92
  ...lifecycle,
75
93
  show: () => options.show(ctx),
76
94
  finalize: () => options.finalize(ctx),
77
- implementHere: () => options.implementHere(ctx),
78
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
95
+ ...implementationActions(ctx, lifecycle),
79
96
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
80
97
  save: () => options.save(ctx),
81
98
  stay: () => options.stay(ctx),
@@ -91,8 +108,7 @@ export function createPlanActionController(options: PlanActionControllerOptions)
91
108
  ...lifecycle,
92
109
  implementationOutcome: options.implementationOutcome,
93
110
  getExportDestination: () => options.getExportDestination(ctx),
94
- implementHere: () => options.implementHere(ctx),
95
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
111
+ ...implementationActions(ctx, lifecycle),
96
112
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
97
113
  save: () => options.save(ctx),
98
114
  stay: () => undefined,
@@ -1,35 +1,57 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
+ import {
4
+ createImplementationOptions,
5
+ type ImplementationOptionAction,
6
+ } from "./implementation-options.js";
3
7
  import { type PlanExportDestinationProvider, planExportInputScreen } from "./plan-export-screen.js";
8
+ import type { ImplementationPreferences } from "./settings.js";
4
9
 
5
- interface MenuLifecycle {
10
+ interface ReadyPlanMenuOptions {
6
11
  signal: AbortSignal;
7
12
  isCurrent(): boolean;
8
- }
9
-
10
- const IMPLEMENTATION_CONTEXT_LINES = [
11
- "Implement here keeps this planning conversation.",
12
- "Start fresh transfers only the approved plan to a new session.",
13
- ] as const;
14
-
15
- interface PlanMenuOptions extends MenuLifecycle {
16
- statusText: string;
17
- hasReadyPlan: boolean;
13
+ implementationPreferences?: ImplementationPreferences;
18
14
  implementationOutcome(): string;
19
15
  getExportDestination: PlanExportDestinationProvider;
20
- show(): void;
21
- finalize(): void;
22
- implementHere(): void | Promise<void>;
23
- implementFresh(signal: AbortSignal): void | Promise<void>;
16
+ implementHere(
17
+ preferences?: ImplementationPreferences,
18
+ signal?: AbortSignal,
19
+ ): void | Promise<void>;
20
+ implementFresh(
21
+ signal: AbortSignal,
22
+ preferences?: ImplementationPreferences,
23
+ ): void | Promise<void>;
24
24
  exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
25
25
  save(): void;
26
26
  stay(): void;
27
27
  exit(): void;
28
28
  }
29
29
 
30
- export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuOptions) {
31
- type Screen = "main" | "export";
30
+ interface PlanMenuOptions extends ReadyPlanMenuOptions {
31
+ statusText: string;
32
+ hasReadyPlan: boolean;
33
+ show(): void;
34
+ finalize(): void;
35
+ }
36
+
37
+ export function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuOptions) {
38
+ return showActions(ctx, options, options);
39
+ }
40
+
41
+ export function showReadyPlanMenu(ctx: ExtensionContext, options: ReadyPlanMenuOptions) {
42
+ return showActions(ctx, options);
43
+ }
44
+
45
+ async function showActions(
46
+ ctx: ExtensionContext,
47
+ options: ReadyPlanMenuOptions,
48
+ current?: PlanMenuOptions,
49
+ ) {
50
+ const implementation = createImplementationOptions(ctx, options.implementationPreferences);
51
+ const ready = current?.hasReadyPlan ?? true;
52
+ type Screen = "main" | "export" | "implementation-options" | "implementation-model";
32
53
  type Action =
54
+ | ImplementationOptionAction
33
55
  | "show"
34
56
  | "finalize"
35
57
  | "implement-here"
@@ -41,23 +63,32 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
41
63
  const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
42
64
  start: "main",
43
65
  screens: {
66
+ ...implementation.screens,
44
67
  main: () => ({
45
68
  kind: "actions",
46
- title: "Plan mode",
69
+ title: current ? "Plan mode" : "Proposed plan ready. What next?",
47
70
  lines: [
48
- options.statusText,
49
- ...(options.hasReadyPlan
50
- ? [...IMPLEMENTATION_CONTEXT_LINES, options.implementationOutcome()]
71
+ ...(current ? [current.statusText] : []),
72
+ ...(ready
73
+ ? [
74
+ "Implement here keeps this planning conversation.",
75
+ "Start fresh transfers only the approved plan to a new session.",
76
+ options.implementationOutcome(),
77
+ implementation.summary(),
78
+ ]
51
79
  : []),
52
80
  ],
53
- items: options.hasReadyPlan
81
+ items: ready
54
82
  ? [
55
- { id: "show", label: "Show latest proposed plan", action: "show" },
83
+ ...(current
84
+ ? [{ id: "show", label: "Show latest proposed plan", action: "show" as const }]
85
+ : []),
56
86
  {
57
87
  id: "implement-here",
58
88
  label: "Implement here",
59
89
  description: "Continue in this session with the planning conversation.",
60
90
  action: "implement-here",
91
+ busyLabel: "Preparing implementation…",
61
92
  },
62
93
  {
63
94
  id: "implement-fresh",
@@ -66,6 +97,11 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
66
97
  action: "implement-fresh",
67
98
  busyLabel: "Starting fresh implementation session…",
68
99
  },
100
+ {
101
+ id: "implementation-options",
102
+ label: "Implementation options…",
103
+ to: "implementation-options",
104
+ },
69
105
  { id: "export", label: "Export plan…", to: "export" },
70
106
  { id: "save", label: "Save for later", action: "save" },
71
107
  { id: "stay", label: "Stay in Plan mode", action: "stay" },
@@ -81,96 +117,21 @@ export async function showPlanModeMenu(ctx: ExtensionContext, options: PlanMenuO
81
117
  export: () => planExportInputScreen(options.getExportDestination),
82
118
  },
83
119
  actions: {
120
+ ...implementation.actions,
84
121
  show: async () => {
85
- options.show();
122
+ current?.show();
86
123
  return { kind: "close" };
87
124
  },
88
125
  finalize: async () => {
89
- options.finalize();
90
- return { kind: "close" };
91
- },
92
- "implement-here": async () => {
93
- await options.implementHere();
94
- return { kind: "close" };
95
- },
96
- "implement-fresh": async ({ signal }) => {
97
- await options.implementFresh(signal);
98
- return { kind: "close" };
99
- },
100
- export: async ({ value, signal }) =>
101
- (await options.exportPlan(value ?? "", signal)) ? { kind: "close" } : { kind: "rejected" },
102
- save: async () => {
103
- options.save();
104
- return { kind: "close" };
105
- },
106
- stay: async () => {
107
- options.stay();
108
- return { kind: "close" };
109
- },
110
- exit: async () => {
111
- options.exit();
126
+ current?.finalize();
112
127
  return { kind: "close" };
113
128
  },
114
- },
115
- });
116
- await runMenu(ctx, menu, {
117
- getState: () => undefined,
118
- signal: options.signal,
119
- isCurrent: options.isCurrent,
120
- });
121
- }
122
-
123
- interface ReadyPlanMenuOptions extends MenuLifecycle {
124
- implementationOutcome(): string;
125
- getExportDestination: PlanExportDestinationProvider;
126
- implementHere(): void | Promise<void>;
127
- implementFresh(signal: AbortSignal): void | Promise<void>;
128
- exportPlan(path: string, signal: AbortSignal): Promise<boolean>;
129
- save(): void;
130
- stay(): void;
131
- exit(): void;
132
- }
133
-
134
- export async function showReadyPlanMenu(ctx: ExtensionContext, options: ReadyPlanMenuOptions) {
135
- type Screen = "ready" | "export";
136
- type Action = "implement-here" | "implement-fresh" | "export" | "save" | "stay" | "exit";
137
- const menu = defineMenu<undefined, Screen, Action, ExtensionContext>({
138
- start: "ready",
139
- screens: {
140
- ready: () => ({
141
- kind: "actions",
142
- title: "Proposed plan ready. What next?",
143
- lines: [...IMPLEMENTATION_CONTEXT_LINES, options.implementationOutcome()],
144
- items: [
145
- {
146
- id: "implement-here",
147
- label: "Implement here",
148
- description: "Continue in this session with the planning conversation.",
149
- action: "implement-here",
150
- },
151
- {
152
- id: "implement-fresh",
153
- label: "Start fresh and implement",
154
- description: "Open a new linked session; transfer only the approved plan.",
155
- action: "implement-fresh",
156
- busyLabel: "Starting fresh implementation session…",
157
- },
158
- { id: "export", label: "Export plan…", to: "export" },
159
- { id: "save", label: "Save for later", action: "save" },
160
- { id: "stay", label: "Stay in Plan mode", action: "stay" },
161
- { id: "exit", label: "Discard plan and exit", action: "exit" },
162
- ],
163
- hint: "close",
164
- }),
165
- export: () => planExportInputScreen(options.getExportDestination),
166
- },
167
- actions: {
168
- "implement-here": async () => {
169
- await options.implementHere();
129
+ "implement-here": async ({ signal }) => {
130
+ await options.implementHere(implementation.get(), signal);
170
131
  return { kind: "close" };
171
132
  },
172
133
  "implement-fresh": async ({ signal }) => {
173
- await options.implementFresh(signal);
134
+ await options.implementFresh(signal, implementation.get());
174
135
  return { kind: "close" };
175
136
  },
176
137
  export: async ({ value, signal }) =>
package/src/plan-mode.ts CHANGED
@@ -27,6 +27,15 @@ import {
27
27
  formatTransferredPlanPrompt,
28
28
  startFreshImplementationFromState,
29
29
  } from "./fresh-implementation.js";
30
+ import { applyFreshImplementationPreferences } from "./fresh-implementation-preferences.js";
31
+ import {
32
+ createImplementationPreferenceChange,
33
+ hasImplementationPreferences,
34
+ observeImplementationModelSelections,
35
+ preferenceError,
36
+ preflightImplementationPreferences,
37
+ sameModel,
38
+ } from "./implementation-preferences.js";
30
39
  import {
31
40
  createImplementationRetentionCoordinator,
32
41
  implementationRetentionPreview,
@@ -74,6 +83,7 @@ import {
74
83
  configuredImplementationPlanRetention,
75
84
  configuredPlanModeToggleShortcut,
76
85
  configuredThinkingLevel,
86
+ type ImplementationPreferences,
77
87
  type PlanModeSettings,
78
88
  type PlanModeSettingsPatch,
79
89
  planModeSettingsPath,
@@ -125,6 +135,7 @@ interface PlanModeDependencies {
125
135
  // Keep session state, persistence, tool, thinking, and mutex commits in this one closure so an
126
136
  // activation path cannot bypass the same atomic transition by crossing module-owned state.
127
137
  export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {
138
+ const selectionSnapshot = observeImplementationModelSelections(pi);
128
139
  const workflowMutex = new WorkflowMutex(pi);
129
140
  let workflowOwner: WorkflowMutexOwner | undefined;
130
141
  let currentSession: object | undefined;
@@ -153,6 +164,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
153
164
  let latestCommandContext: ExtensionCommandContext | undefined;
154
165
  let nextReadyPresentationNonce = 0;
155
166
  let menuGeneration = 0;
167
+ let implementationInFlight = false;
168
+ let applyingImplementationPreferences = false;
156
169
  let workflowGeneration = 0;
157
170
  let refreshStateBeforeFirstAgentStart = false;
158
171
  let menuController = new AbortController();
@@ -177,6 +190,10 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
177
190
  getExportDestination: (ctx) => planExports.getDestination(ctx),
178
191
  show: (ctx) => showStoredPlan(pi, ctx, state),
179
192
  finalize: requestFinalPlan,
193
+ getImplementationPreferences: () => ({
194
+ implementationModel: settings.implementationModel,
195
+ implementationThinkingLevel: settings.implementationThinkingLevel,
196
+ }),
180
197
  implementHere: startImplementation,
181
198
  implementFresh: startFreshImplementation,
182
199
  exportPlan: exportPlan,
@@ -467,6 +484,13 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
467
484
  if (!installRestoredState(restoredState, ctx)) return;
468
485
  implementationRetention.restore(state.activeImplementation);
469
486
  updateUi(ctx);
487
+ if (event.reason === "new")
488
+ await applyFreshImplementationPreferences(
489
+ pi,
490
+ ctx,
491
+ () => generation === menuGeneration && !menuController.signal.aborted,
492
+ selectionSnapshot,
493
+ );
470
494
  });
471
495
 
472
496
  pi.on("session_before_tree", (event, ctx) => {
@@ -501,7 +525,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
501
525
  });
502
526
 
503
527
  pi.on("thinking_level_select", (event) => {
504
- if (!state.enabled || !state.appliedThinkingLevel) return;
528
+ if (applyingImplementationPreferences || !state.enabled || !state.appliedThinkingLevel) return;
505
529
  if (event.level !== state.appliedThinkingLevel) {
506
530
  state = {
507
531
  ...state,
@@ -982,8 +1006,13 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
982
1006
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
983
1007
  }
984
1008
 
985
- async function startFreshImplementation(ctx: ExtensionContext, menuIsCurrent: () => boolean) {
1009
+ async function startFreshImplementation(
1010
+ ctx: ExtensionContext,
1011
+ menuIsCurrent: () => boolean,
1012
+ preferences: ImplementationPreferences = settings,
1013
+ ) {
986
1014
  await startFreshImplementationFromState(ctx, {
1015
+ preferences,
987
1016
  getState: () => state,
988
1017
  menuIsCurrent,
989
1018
  retention: configuredImplementationPlanRetention(settings),
@@ -991,7 +1020,77 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
991
1020
  });
992
1021
  }
993
1022
 
994
- async function startImplementation(ctx: ExtensionContext) {
1023
+ async function startImplementation(
1024
+ ctx: ExtensionContext,
1025
+ preferences: ImplementationPreferences = settings,
1026
+ menuIsCurrent: () => boolean = () => true,
1027
+ ) {
1028
+ if (implementationInFlight || !menuIsCurrent()) return;
1029
+ if (!hasImplementationPreferences(preferences)) {
1030
+ await startImplementationCore(ctx);
1031
+ return;
1032
+ }
1033
+ if (!allowModeTransition(ctx, "start plan implementation")) return;
1034
+ if (ctx.mode === "print" || ctx.mode === "json")
1035
+ throw new Error("Implementation model options require TUI or RPC mode.");
1036
+ const previousState = state;
1037
+ if (!(state.enabled ? state.latestPlan : state.savedPlan?.plan)) return;
1038
+ const generation = menuGeneration;
1039
+ const workflow = workflowGeneration;
1040
+ const original = { model: ctx.model, thinking: pi.getThinkingLevel() };
1041
+ const sessionCurrent = () => generation === menuGeneration && !menuController.signal.aborted;
1042
+ let expectedState = state;
1043
+ const current = () =>
1044
+ sessionCurrent() &&
1045
+ workflow === workflowGeneration &&
1046
+ state === expectedState &&
1047
+ menuIsCurrent() &&
1048
+ ctx.isIdle();
1049
+ const change = createImplementationPreferenceChange(
1050
+ pi,
1051
+ ctx,
1052
+ sessionCurrent,
1053
+ original,
1054
+ selectionSnapshot,
1055
+ );
1056
+ implementationInFlight = true;
1057
+ let started = false;
1058
+ try {
1059
+ const model = await preflightImplementationPreferences(
1060
+ ctx,
1061
+ preferences,
1062
+ () =>
1063
+ current() &&
1064
+ sameModel(ctx.model, original.model) &&
1065
+ pi.getThinkingLevel() === original.thinking,
1066
+ );
1067
+ if (!model || !current()) return;
1068
+ applyingImplementationPreferences = true;
1069
+ if (state.enabled) restoreThinkingLevel();
1070
+ expectedState = state;
1071
+ if (!(await change.apply(model, preferences, current)) || !current()) return;
1072
+ started = (await startImplementationCore(ctx, true)) === true;
1073
+ } catch (error) {
1074
+ if (sessionCurrent())
1075
+ ctx.ui.notify(`Unable to start implementation: ${preferenceError(error)}`, "error");
1076
+ } finally {
1077
+ if (!started && sessionCurrent()) {
1078
+ await change.rollback().catch((error) => {
1079
+ if (sessionCurrent()) ctx.ui.notify(preferenceError(error), "error");
1080
+ });
1081
+ if (sessionCurrent() && state === expectedState) {
1082
+ state = previousState;
1083
+ captureManualThinkingLevel();
1084
+ persistState();
1085
+ updateUi(ctx);
1086
+ }
1087
+ }
1088
+ applyingImplementationPreferences = false;
1089
+ implementationInFlight = false;
1090
+ }
1091
+ }
1092
+
1093
+ async function startImplementationCore(ctx: ExtensionContext, preferencesApplied = false) {
995
1094
  const savedPlan = state.enabled ? undefined : state.savedPlan;
996
1095
  const initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
997
1096
  if (!initialPlan) {
@@ -999,7 +1098,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
999
1098
  return;
1000
1099
  }
1001
1100
  if (!allowModeTransition(ctx, "start plan implementation")) return;
1002
- if (savedPlan) {
1101
+ if (savedPlan && !preferencesApplied) {
1003
1102
  const sessionGeneration = menuGeneration;
1004
1103
  const planWorkflowGeneration = workflowGeneration;
1005
1104
  const isCurrent = () =>
@@ -1044,7 +1143,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1044
1143
  workflowToolPolicy: undefined,
1045
1144
  manualThinkingLevel: undefined,
1046
1145
  };
1047
- if (wasEnabled) {
1146
+ if (wasEnabled && !preferencesApplied) {
1048
1147
  restoreThinkingLevel();
1049
1148
  state = { ...state, manualThinkingLevel: undefined };
1050
1149
  }
@@ -1063,13 +1162,14 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1063
1162
  if (wasEnabled) {
1064
1163
  restoreWorkflowToolPolicy(state.workflowToolPolicy);
1065
1164
  publishModeContract("plan", ctx);
1066
- applyPlanThinkingLevel();
1165
+ if (!preferencesApplied) applyPlanThinkingLevel();
1067
1166
  }
1068
1167
  persistState();
1069
1168
  updateUi(ctx);
1070
1169
  return;
1071
1170
  }
1072
1171
  if (wasEnabled) releaseWorkflowOwner();
1172
+ return true;
1073
1173
  }
1074
1174
 
1075
1175
  function clearActiveImplementation(id: string, ctx: ExtensionContext) {