@narumitw/pi-plan-mode 0.57.0 → 0.58.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/src/plan-mode.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { watch } from "node:fs";
3
3
  import { basename, dirname } from "node:path";
4
+ import { stripVTControlCharacters } from "node:util";
4
5
  import type {
5
6
  ExtensionAPI,
6
7
  ExtensionCommandContext,
7
8
  ExtensionContext,
9
+ InputEvent,
10
+ InputSource,
8
11
  } from "@earendil-works/pi-coding-agent";
9
12
  import { completePlanArguments } from "./command.js";
10
13
  import {
@@ -21,21 +24,13 @@ import {
21
24
  type FinalizationRunOutcome,
22
25
  RETRY_FINALIZE_PLAN_PROMPT,
23
26
  } from "./finalization-request.js";
27
+ import { createDeferredFreshHandoffCoordinator } from "./fresh-handoff-coordinator.js";
24
28
  import {
25
29
  formatHistoryImplementationPrompt,
26
30
  formatImplementationHandoff,
27
31
  formatTransferredPlanPrompt,
28
32
  startFreshImplementationFromState,
29
33
  } 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";
39
34
  import {
40
35
  createImplementationRetentionCoordinator,
41
36
  implementationRetentionPreview,
@@ -55,7 +50,10 @@ import {
55
50
  type PlanModeContract,
56
51
  reconcileModeContract,
57
52
  } from "./mode-contract.js";
58
- import { createPlanActionController } from "./plan-action-controller.js";
53
+ import {
54
+ createPlanActionController,
55
+ type FreshImplementationTiming,
56
+ } from "./plan-action-controller.js";
59
57
  import { createPlanExportController } from "./plan-export-controller.js";
60
58
  import {
61
59
  clearPlanModeUi,
@@ -83,7 +81,7 @@ import {
83
81
  configuredImplementationPlanRetention,
84
82
  configuredPlanModeToggleShortcut,
85
83
  configuredThinkingLevel,
86
- type ImplementationPreferences,
84
+ type ImplementationPlanRetention,
87
85
  type PlanModeSettings,
88
86
  type PlanModeSettingsPatch,
89
87
  planModeSettingsPath,
@@ -92,6 +90,7 @@ import {
92
90
  updatePlanModeSettings,
93
91
  } from "./settings.js";
94
92
  import {
93
+ type ImplementationRuntimeSelection,
95
94
  type PlanCompletionSource,
96
95
  type PlanModeState,
97
96
  type PlanModeWorkflowToolPolicy,
@@ -109,6 +108,7 @@ import { WorkflowMutex, type WorkflowMutexOwner } from "./workflow-mutex.js";
109
108
 
110
109
  const STATE_ENTRY_TYPE = "plan-mode-state";
111
110
  const PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
111
+ const RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE = "plan-mode-recovered-input";
112
112
  const BLOCKED_MUTATING_TOOLS = new Set(["edit", "write", "update_plan"]);
113
113
  const DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
114
114
  interface ReadyPresentationIntent {
@@ -116,10 +116,37 @@ interface ReadyPresentationIntent {
116
116
  plan: string;
117
117
  source: PlanCompletionSource;
118
118
  }
119
+ interface DeferredFreshImplementation {
120
+ ctx: ExtensionContext;
121
+ sourceSession: object;
122
+ menuGeneration: number;
123
+ workflowGeneration: number;
124
+ workflowOwner: WorkflowMutexOwner | undefined;
125
+ enabled: boolean;
126
+ plan: string;
127
+ source: PlanCompletionSource;
128
+ savedPlan: PlanModeState["savedPlan"];
129
+ retention: ImplementationPlanRetention;
130
+ runtime: ImplementationRuntimeSelection | undefined;
131
+ menuIsCurrent(): boolean;
132
+ }
119
133
  interface PendingWorkflowToolPolicy {
120
134
  generation: number;
121
135
  mode: "resolve" | "revalidate";
122
136
  }
137
+ type ImplementationRuntimeApplicationResult = "ready" | "blocked" | "stale";
138
+ interface ActiveImplementationRuntimeApplication {
139
+ sessionManager: ExtensionContext["sessionManager"];
140
+ completion: Promise<ImplementationRuntimeApplicationResult>;
141
+ drainOnShutdown: boolean;
142
+ holdForAdmission: boolean;
143
+ }
144
+ interface QueuedRuntimeAdmissionInput {
145
+ sessionManager: ExtensionContext["sessionManager"];
146
+ text: string;
147
+ images?: NonNullable<InputEvent["images"]>;
148
+ source: InputSource;
149
+ }
123
150
  type InteractiveUi = typeof import("./interactive-ui.js");
124
151
 
125
152
  interface PlanModeDependencies {
@@ -135,7 +162,6 @@ interface PlanModeDependencies {
135
162
  // Keep session state, persistence, tool, thinking, and mutex commits in this one closure so an
136
163
  // activation path cannot bypass the same atomic transition by crossing module-owned state.
137
164
  export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDependencies = {}) {
138
- const selectionSnapshot = observeImplementationModelSelections(pi);
139
165
  const workflowMutex = new WorkflowMutex(pi);
140
166
  let workflowOwner: WorkflowMutexOwner | undefined;
141
167
  let currentSession: object | undefined;
@@ -162,12 +188,15 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
162
188
  let modeContractsRelevant = false;
163
189
  let readyPresentationIntent: ReadyPresentationIntent | undefined;
164
190
  let latestCommandContext: ExtensionCommandContext | undefined;
191
+ let stagedFreshImplementation: DeferredFreshImplementation | undefined;
192
+ const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();
165
193
  let nextReadyPresentationNonce = 0;
166
194
  let menuGeneration = 0;
167
- let implementationInFlight = false;
168
- let applyingImplementationPreferences = false;
169
195
  let workflowGeneration = 0;
170
196
  let refreshStateBeforeFirstAgentStart = false;
197
+ let activeImplementationRuntimeApplication: ActiveImplementationRuntimeApplication | undefined;
198
+ let pendingRuntimeAdmissionSession: object | undefined;
199
+ let queuedRuntimeAdmissionInputs: QueuedRuntimeAdmissionInput[] = [];
171
200
  let menuController = new AbortController();
172
201
  let settingsWatch: ReturnType<typeof watch> | undefined;
173
202
  let settingsReloadTimer: ReturnType<typeof setTimeout> | undefined;
@@ -186,14 +215,14 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
186
215
  getState: () => state,
187
216
  captureLifecycle: captureMenuLifecycle,
188
217
  statusText: planStatusText,
218
+ // ExtensionContext.thinkingLevel was added after the supported Pi 0.80.6 floor.
219
+ // ExtensionAPI has exposed the same runtime value throughout that compatibility range.
220
+ getThinkingLevel: () => pi.getThinkingLevel(),
221
+ getSettings: () => settings,
189
222
  implementationOutcome,
190
223
  getExportDestination: (ctx) => planExports.getDestination(ctx),
191
224
  show: (ctx) => showStoredPlan(pi, ctx, state),
192
225
  finalize: requestFinalPlan,
193
- getImplementationPreferences: () => ({
194
- implementationModel: settings.implementationModel,
195
- implementationThinkingLevel: settings.implementationThinkingLevel,
196
- }),
197
226
  implementHere: startImplementation,
198
227
  implementFresh: startFreshImplementation,
199
228
  exportPlan: exportPlan,
@@ -313,6 +342,14 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
313
342
  savePlanForLater(ctx);
314
343
  return;
315
344
  }
345
+ if (command === "settings") {
346
+ if (!ctx.hasUI) {
347
+ throw new Error("/plan settings requires TUI or RPC mode and is unavailable here.");
348
+ }
349
+ const lifecycle = captureMenuLifecycle();
350
+ await showSettings(ctx, lifecycle.signal, lifecycle.isCurrent);
351
+ return;
352
+ }
316
353
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
317
354
  if (exportMatch) {
318
355
  const lifecycle = captureMenuLifecycle();
@@ -459,6 +496,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
459
496
  };
460
497
 
461
498
  pi.on("session_start", async (event, ctx) => {
499
+ cancelDeferredFreshImplementation();
462
500
  const generation = ++menuGeneration;
463
501
  finalizationRequest.reset();
464
502
  currentSession = ctx.sessionManager;
@@ -466,6 +504,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
466
504
  workflowOwner = undefined;
467
505
  workflowMutex.bindSession(ctx.sessionManager);
468
506
  refreshStateBeforeFirstAgentStart = event.reason === "new";
507
+ pendingRuntimeAdmissionSession = undefined;
508
+ queuedRuntimeAdmissionInputs = [];
469
509
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
470
510
  menuController = new AbortController();
471
511
  readyPresentationIntent = undefined;
@@ -484,16 +524,22 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
484
524
  if (!installRestoredState(restoredState, ctx)) return;
485
525
  implementationRetention.restore(state.activeImplementation);
486
526
  updateUi(ctx);
487
- if (event.reason === "new")
488
- await applyFreshImplementationPreferences(
489
- pi,
490
- ctx,
491
- () => generation === menuGeneration && !menuController.signal.aborted,
492
- selectionSnapshot,
493
- );
527
+ // A new session receives its setup entries after session_start, so its input gate refreshes
528
+ // them. Resumed and forked sessions already have the intent and must apply it here because
529
+ // extension-triggered custom-message turns bypass both input and before_agent_start.
530
+ if (event.reason !== "new") await applyPendingImplementationRuntime(ctx);
494
531
  });
495
532
 
496
533
  pi.on("session_before_tree", (event, ctx) => {
534
+ if (runtimeAdmissionIsPending(ctx.sessionManager)) {
535
+ if (ctx.hasUI) {
536
+ ctx.ui.notify(
537
+ "Wait for fresh implementation startup to admit the pending prompts before changing branches.",
538
+ "warning",
539
+ );
540
+ }
541
+ return { cancel: true };
542
+ }
497
543
  const target = ctx.sessionManager.getEntry(event.preparation.targetId);
498
544
  if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
499
545
  return;
@@ -507,13 +553,16 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
507
553
  return { cancel: true };
508
554
  });
509
555
 
510
- pi.on("session_tree", (_event, ctx) => {
556
+ pi.on("session_tree", async (_event, ctx) => {
557
+ cancelDeferredFreshImplementation();
511
558
  advanceWorkflowGeneration();
512
559
  menuGeneration += 1;
513
560
  menuController.abort(new DOMException("Plan-mode tree branch changed", "AbortError"));
514
561
  menuController = new AbortController();
515
562
  readyPresentationIntent = undefined;
516
563
  latestCommandContext = undefined;
564
+ pendingRuntimeAdmissionSession = undefined;
565
+ queuedRuntimeAdmissionInputs = [];
517
566
  implementationRetention.reset();
518
567
  const branch = ctx.sessionManager.getBranch();
519
568
  const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
@@ -522,10 +571,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
522
571
  implementationRetention.restore(state.activeImplementation);
523
572
  startPlanModeSettingsWatch(menuGeneration);
524
573
  updateUi(ctx);
574
+ await applyPendingImplementationRuntime(ctx);
525
575
  });
526
576
 
527
577
  pi.on("thinking_level_select", (event) => {
528
- if (applyingImplementationPreferences || !state.enabled || !state.appliedThinkingLevel) return;
578
+ if (!state.enabled || !state.appliedThinkingLevel) return;
529
579
  if (event.level !== state.appliedThinkingLevel) {
530
580
  state = {
531
581
  ...state,
@@ -538,16 +588,41 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
538
588
  });
539
589
 
540
590
  pi.on("session_shutdown", async (_event, ctx) => {
591
+ cancelDeferredFreshImplementation();
541
592
  const shutdownSession = ctx.sessionManager;
593
+ const runtimeApplication =
594
+ activeImplementationRuntimeApplication?.sessionManager === shutdownSession &&
595
+ activeImplementationRuntimeApplication.drainOnShutdown
596
+ ? activeImplementationRuntimeApplication
597
+ : undefined;
598
+ const queuedInputs = takeQueuedRuntimeAdmissionInputs(shutdownSession);
599
+ for (const queued of queuedInputs) {
600
+ pi.sendMessage(
601
+ {
602
+ customType: RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE,
603
+ content: runtimeAdmissionInputContent(queued),
604
+ display: true,
605
+ details: { source: queued.source },
606
+ },
607
+ { triggerTurn: false },
608
+ );
609
+ }
542
610
  finalizationRequest.reset();
543
611
  menuGeneration += 1;
544
612
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
545
613
  readyPresentationIntent = undefined;
546
614
  latestCommandContext = undefined;
547
615
  refreshStateBeforeFirstAgentStart = false;
616
+ pendingRuntimeAdmissionSession = undefined;
617
+ queuedRuntimeAdmissionInputs = [];
548
618
  workflowAllowedToolNames = undefined;
549
619
  pendingWorkflowToolPolicy = undefined;
550
620
  implementationRetention.reset();
621
+ if (runtimeApplication) await runtimeApplication.completion;
622
+ if (currentSession !== undefined && currentSession !== shutdownSession) {
623
+ workflowMutex.unbindSession(shutdownSession);
624
+ return;
625
+ }
551
626
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
552
627
  if (currentSession !== undefined && currentSession !== shutdownSession) {
553
628
  workflowMutex.unbindSession(shutdownSession);
@@ -678,19 +753,47 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
678
753
  return { messages: messages as typeof event.messages };
679
754
  });
680
755
 
681
- pi.on("before_agent_start", (_event, ctx) => {
682
- if (refreshStateBeforeFirstAgentStart) {
683
- refreshStateBeforeFirstAgentStart = false;
684
- implementationRetention.reset();
685
- const branch = ctx.sessionManager.getBranch();
686
- const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
687
- restoreModeContractTracking(branch, restoredState);
688
- if (!installRestoredState(restoredState, ctx)) return;
689
- implementationRetention.restore(state.activeImplementation);
690
- updateUi(ctx);
756
+ pi.on("input", async (event, ctx) => {
757
+ refreshStateForFirstPrompt(ctx);
758
+ const waitsForRuntimeAdmission =
759
+ activeImplementationRuntimeApplication?.sessionManager === ctx.sessionManager ||
760
+ pendingRuntimeAdmissionSession === ctx.sessionManager;
761
+ const queuedInput = waitsForRuntimeAdmission
762
+ ? {
763
+ sessionManager: ctx.sessionManager,
764
+ text: event.text,
765
+ ...(event.images ? { images: [...event.images] } : {}),
766
+ source: event.source,
767
+ }
768
+ : undefined;
769
+ if (queuedInput) queuedRuntimeAdmissionInputs.push(queuedInput);
770
+ const result = await applyPendingImplementationRuntime(ctx, true);
771
+ if (result !== "ready") {
772
+ if (result === "stale" && queuedInput) removeQueuedRuntimeAdmissionInput(queuedInput);
773
+ return { action: "handled" };
774
+ }
775
+ if (queuedInput) return { action: "handled" };
776
+ });
777
+
778
+ pi.on("agent_start", (_event, ctx) => {
779
+ if (currentSession !== ctx.sessionManager) return;
780
+ if (pendingRuntimeAdmissionSession === ctx.sessionManager) {
781
+ pendingRuntimeAdmissionSession = undefined;
782
+ }
783
+ const queuedInputs = takeQueuedRuntimeAdmissionInputs(ctx.sessionManager);
784
+ for (const queued of queuedInputs) {
785
+ pi.sendUserMessage(runtimeAdmissionInputContent(queued), {
786
+ deliverAs: "followUp",
787
+ expandPromptTemplates: queued.source !== "extension",
788
+ });
691
789
  }
790
+ });
791
+
792
+ pi.on("before_agent_start", (_event, ctx) => {
793
+ refreshStateForFirstPrompt(ctx);
692
794
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
693
795
  if (state.latestPlan || state.awaitingAction) {
796
+ cancelDeferredFreshImplementation();
694
797
  readyPresentationIntent = undefined;
695
798
  state = {
696
799
  ...state,
@@ -750,6 +853,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
750
853
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
751
854
 
752
855
  readyPresentationIntent = undefined;
856
+ stagedFreshImplementation = undefined;
753
857
  try {
754
858
  if (intent.source === "legacy_proposed_plan") {
755
859
  pi.sendMessage(
@@ -764,7 +868,11 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
764
868
  if (ctx.hasUI && completedPlanIsCurrent(intent)) {
765
869
  await planActions.showReady(latestCommandContext ?? ctx);
766
870
  }
871
+ const request = stagedFreshImplementation;
872
+ stagedFreshImplementation = undefined;
873
+ if (request) armDeferredFreshImplementation(request);
767
874
  } catch (error: unknown) {
875
+ stagedFreshImplementation = undefined;
768
876
  if (!isStaleExtensionContextError(error)) throw error;
769
877
  }
770
878
  });
@@ -800,6 +908,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
800
908
  awaitingAction: false,
801
909
  savedPlan: undefined,
802
910
  activeImplementation: undefined,
911
+ pendingImplementationRuntime: undefined,
803
912
  selectedToolNames: candidate.selectedToolNames,
804
913
  selectedToolKeys: candidate.selectedToolKeys,
805
914
  };
@@ -844,6 +953,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
844
953
  awaitingAction: false,
845
954
  savedPlan: undefined,
846
955
  activeImplementation: undefined,
956
+ pendingImplementationRuntime: undefined,
847
957
  workflowToolPolicy: undefined,
848
958
  manualThinkingLevel: undefined,
849
959
  };
@@ -863,7 +973,8 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
863
973
  hasModeContractArtifact(branch) ||
864
974
  restoredState.enabled ||
865
975
  restoredState.savedPlan !== undefined ||
866
- restoredState.activeImplementation !== undefined;
976
+ restoredState.activeImplementation !== undefined ||
977
+ restoredState.pendingImplementationRuntime !== undefined;
867
978
  }
868
979
 
869
980
  function publishModeContract(mode: PlanModeContract, ctx: ExtensionContext) {
@@ -995,6 +1106,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
995
1106
  awaitingAction: false,
996
1107
  savedPlan: { plan, source },
997
1108
  activeImplementation: undefined,
1109
+ pendingImplementationRuntime: undefined,
998
1110
  workflowToolPolicy: undefined,
999
1111
  manualThinkingLevel: undefined,
1000
1112
  };
@@ -1009,88 +1121,98 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1009
1121
  async function startFreshImplementation(
1010
1122
  ctx: ExtensionContext,
1011
1123
  menuIsCurrent: () => boolean,
1012
- preferences: ImplementationPreferences = settings,
1013
- ) {
1014
- await startFreshImplementationFromState(ctx, {
1015
- preferences,
1016
- getState: () => state,
1017
- menuIsCurrent,
1018
- retention: configuredImplementationPlanRetention(settings),
1019
- stateEntryType: STATE_ENTRY_TYPE,
1020
- });
1021
- }
1022
-
1023
- async function startImplementation(
1024
- ctx: ExtensionContext,
1025
- preferences: ImplementationPreferences = settings,
1026
- menuIsCurrent: () => boolean = () => true,
1124
+ runtime: ImplementationRuntimeSelection | undefined,
1125
+ timing: FreshImplementationTiming,
1027
1126
  ) {
1028
- if (implementationInFlight || !menuIsCurrent()) return;
1029
- if (!hasImplementationPreferences(preferences)) {
1030
- await startImplementationCore(ctx);
1127
+ const retention = configuredImplementationPlanRetention(settings);
1128
+ if (timing === "immediate") {
1129
+ await startFreshImplementationFromState(ctx, {
1130
+ getState: () => state,
1131
+ menuIsCurrent,
1132
+ retention,
1133
+ stateEntryType: STATE_ENTRY_TYPE,
1134
+ runtime,
1135
+ });
1031
1136
  return;
1032
1137
  }
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,
1138
+
1139
+ const initialState = state;
1140
+ const savedPlan = initialState.enabled ? undefined : initialState.savedPlan;
1141
+ const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();
1142
+ const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;
1143
+ if (!plan || !source || !menuIsCurrent()) return;
1144
+ stagedFreshImplementation = {
1051
1145
  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");
1146
+ sourceSession: ctx.sessionManager,
1147
+ menuGeneration,
1148
+ workflowGeneration,
1149
+ workflowOwner,
1150
+ enabled: initialState.enabled,
1151
+ plan,
1152
+ source,
1153
+ savedPlan,
1154
+ retention,
1155
+ runtime: runtime
1156
+ ? {
1157
+ ...(runtime.model ? { model: { ...runtime.model } } : {}),
1158
+ ...(runtime.thinkingLevel ? { thinkingLevel: runtime.thinkingLevel } : {}),
1159
+ }
1160
+ : undefined,
1161
+ menuIsCurrent,
1162
+ };
1163
+ }
1164
+
1165
+ function armDeferredFreshImplementation(request: DeferredFreshImplementation) {
1166
+ deferredFreshHandoff.schedule(
1167
+ async (taskIsCurrent) => {
1168
+ const isCurrent = () => taskIsCurrent() && deferredFreshImplementationIsCurrent(request);
1169
+ if (!isCurrent()) return;
1170
+ await startFreshImplementationFromState(request.ctx, {
1171
+ getState: () => state,
1172
+ menuIsCurrent: isCurrent,
1173
+ retention: request.retention,
1174
+ stateEntryType: STATE_ENTRY_TYPE,
1175
+ runtime: request.runtime,
1080
1176
  });
1081
- if (sessionCurrent() && state === expectedState) {
1082
- state = previousState;
1083
- captureManualThinkingLevel();
1084
- persistState();
1085
- updateUi(ctx);
1177
+ },
1178
+ (error) => {
1179
+ if (!deferredFreshImplementationIsCurrent(request)) return;
1180
+ try {
1181
+ request.ctx.ui.notify(
1182
+ `Unable to start the deferred fresh implementation: ${terminalErrorDetail(error)}`,
1183
+ "error",
1184
+ );
1185
+ } catch {
1186
+ // The source context can become stale while a detached failure is reported.
1086
1187
  }
1087
- }
1088
- applyingImplementationPreferences = false;
1089
- implementationInFlight = false;
1188
+ },
1189
+ );
1190
+ }
1191
+
1192
+ function deferredFreshImplementationIsCurrent(request: DeferredFreshImplementation) {
1193
+ if (
1194
+ currentSession !== request.sourceSession ||
1195
+ menuGeneration !== request.menuGeneration ||
1196
+ workflowGeneration !== request.workflowGeneration ||
1197
+ workflowOwner !== request.workflowOwner ||
1198
+ !request.menuIsCurrent() ||
1199
+ state.enabled !== request.enabled
1200
+ ) {
1201
+ return false;
1090
1202
  }
1203
+ return request.enabled
1204
+ ? workflowMutex.isOwner(request.workflowOwner) &&
1205
+ state.latestPlan === request.plan &&
1206
+ state.latestPlanSource === request.source
1207
+ : state.savedPlan === request.savedPlan;
1091
1208
  }
1092
1209
 
1093
- async function startImplementationCore(ctx: ExtensionContext, preferencesApplied = false) {
1210
+ function cancelDeferredFreshImplementation() {
1211
+ stagedFreshImplementation = undefined;
1212
+ deferredFreshHandoff.cancel();
1213
+ }
1214
+
1215
+ async function startImplementation(ctx: ExtensionContext) {
1094
1216
  const savedPlan = state.enabled ? undefined : state.savedPlan;
1095
1217
  const initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
1096
1218
  if (!initialPlan) {
@@ -1098,7 +1220,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1098
1220
  return;
1099
1221
  }
1100
1222
  if (!allowModeTransition(ctx, "start plan implementation")) return;
1101
- if (savedPlan && !preferencesApplied) {
1223
+ if (savedPlan) {
1102
1224
  const sessionGeneration = menuGeneration;
1103
1225
  const planWorkflowGeneration = workflowGeneration;
1104
1226
  const isCurrent = () =>
@@ -1131,6 +1253,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1131
1253
  latestPlanSource: undefined,
1132
1254
  awaitingAction: false,
1133
1255
  savedPlan: undefined,
1256
+ pendingImplementationRuntime: undefined,
1134
1257
  activeImplementation: usesConversationHistory
1135
1258
  ? undefined
1136
1259
  : {
@@ -1143,7 +1266,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1143
1266
  workflowToolPolicy: undefined,
1144
1267
  manualThinkingLevel: undefined,
1145
1268
  };
1146
- if (wasEnabled && !preferencesApplied) {
1269
+ if (wasEnabled) {
1147
1270
  restoreThinkingLevel();
1148
1271
  state = { ...state, manualThinkingLevel: undefined };
1149
1272
  }
@@ -1162,14 +1285,13 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1162
1285
  if (wasEnabled) {
1163
1286
  restoreWorkflowToolPolicy(state.workflowToolPolicy);
1164
1287
  publishModeContract("plan", ctx);
1165
- if (!preferencesApplied) applyPlanThinkingLevel();
1288
+ applyPlanThinkingLevel();
1166
1289
  }
1167
1290
  persistState();
1168
1291
  updateUi(ctx);
1169
1292
  return;
1170
1293
  }
1171
1294
  if (wasEnabled) releaseWorkflowOwner();
1172
- return true;
1173
1295
  }
1174
1296
 
1175
1297
  function clearActiveImplementation(id: string, ctx: ExtensionContext) {
@@ -1376,6 +1498,7 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1376
1498
  }
1377
1499
 
1378
1500
  function advanceWorkflowGeneration() {
1501
+ cancelDeferredFreshImplementation();
1379
1502
  workflowGeneration += 1;
1380
1503
  pendingWorkflowToolPolicy = undefined;
1381
1504
  finalizationRequest.reset();
@@ -1582,6 +1705,200 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1582
1705
  }
1583
1706
  }
1584
1707
 
1708
+ function runtimeAdmissionIsPending(sessionManager: ExtensionContext["sessionManager"]) {
1709
+ return (
1710
+ activeImplementationRuntimeApplication?.sessionManager === sessionManager ||
1711
+ pendingRuntimeAdmissionSession === sessionManager ||
1712
+ queuedRuntimeAdmissionInputs.some((queued) => queued.sessionManager === sessionManager)
1713
+ );
1714
+ }
1715
+
1716
+ function takeQueuedRuntimeAdmissionInputs(sessionManager: ExtensionContext["sessionManager"]) {
1717
+ const matching: QueuedRuntimeAdmissionInput[] = [];
1718
+ const remaining: QueuedRuntimeAdmissionInput[] = [];
1719
+ for (const queued of queuedRuntimeAdmissionInputs) {
1720
+ if (queued.sessionManager === sessionManager) matching.push(queued);
1721
+ else remaining.push(queued);
1722
+ }
1723
+ queuedRuntimeAdmissionInputs = remaining;
1724
+ return matching;
1725
+ }
1726
+
1727
+ function removeQueuedRuntimeAdmissionInput(queuedInput: QueuedRuntimeAdmissionInput) {
1728
+ const index = queuedRuntimeAdmissionInputs.indexOf(queuedInput);
1729
+ if (index >= 0) queuedRuntimeAdmissionInputs.splice(index, 1);
1730
+ }
1731
+
1732
+ function runtimeAdmissionInputContent(queued: QueuedRuntimeAdmissionInput) {
1733
+ return queued.images?.length
1734
+ ? [{ type: "text" as const, text: queued.text }, ...queued.images]
1735
+ : queued.text;
1736
+ }
1737
+
1738
+ function refreshStateForFirstPrompt(ctx: ExtensionContext) {
1739
+ if (!refreshStateBeforeFirstAgentStart) return;
1740
+ refreshStateBeforeFirstAgentStart = false;
1741
+ implementationRetention.reset();
1742
+ const branch = ctx.sessionManager.getBranch();
1743
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1744
+ restoreModeContractTracking(branch, restoredState);
1745
+ if (!installRestoredState(restoredState, ctx)) return;
1746
+ implementationRetention.restore(state.activeImplementation);
1747
+ updateUi(ctx);
1748
+ }
1749
+
1750
+ async function applyPendingImplementationRuntime(
1751
+ ctx: ExtensionContext,
1752
+ holdForAdmission = false,
1753
+ ): Promise<ImplementationRuntimeApplicationResult> {
1754
+ const session = ctx.sessionManager;
1755
+ const activeApplication = activeImplementationRuntimeApplication;
1756
+ if (activeApplication?.sessionManager === session) {
1757
+ if (holdForAdmission) activeApplication.holdForAdmission = true;
1758
+ return activeApplication.completion;
1759
+ }
1760
+
1761
+ const intent = state.enabled ? undefined : state.pendingImplementationRuntime;
1762
+ if (!intent) return "ready";
1763
+ const generation = menuGeneration;
1764
+ const isCurrent = () =>
1765
+ currentSession === session && generation === menuGeneration && !menuController.signal.aborted;
1766
+ const notifyCurrent = (message: string) => {
1767
+ if (!isCurrent()) return;
1768
+ try {
1769
+ ctx.ui.notify(message, "warning");
1770
+ } catch {
1771
+ // The session can become stale while an asynchronous runtime application settles.
1772
+ }
1773
+ };
1774
+ let application!: ActiveImplementationRuntimeApplication;
1775
+ const completion = Promise.resolve()
1776
+ .then(async (): Promise<ImplementationRuntimeApplicationResult> => {
1777
+ if (!isCurrent()) return "stale";
1778
+ const pendingState = state;
1779
+ const previousThinkingLevel = pi.getThinkingLevel();
1780
+
1781
+ const applyThinking = () => {
1782
+ if (!intent.thinkingLevel) return;
1783
+ try {
1784
+ pi.setThinkingLevel(intent.thinkingLevel);
1785
+ const effectiveLevel = pi.getThinkingLevel();
1786
+ if (effectiveLevel !== intent.thinkingLevel) {
1787
+ notifyCurrent(
1788
+ `Implementation thinking ${intent.thinkingLevel} is unsupported by the destination model; Pi is using ${effectiveLevel}.`,
1789
+ );
1790
+ }
1791
+ } catch (error: unknown) {
1792
+ notifyCurrent(
1793
+ `Implementation thinking ${intent.thinkingLevel} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default will continue.`,
1794
+ );
1795
+ }
1796
+ };
1797
+
1798
+ if (intent.model) {
1799
+ let model: ReturnType<ExtensionContext["modelRegistry"]["find"]>;
1800
+ let resolutionFailed = false;
1801
+ try {
1802
+ model = ctx.modelRegistry.find(intent.model.provider, intent.model.modelId);
1803
+ } catch (error: unknown) {
1804
+ notifyCurrent(
1805
+ `Implementation model ${terminalModelReference(intent.model)} could not be resolved: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,
1806
+ );
1807
+ resolutionFailed = true;
1808
+ model = undefined;
1809
+ }
1810
+ if (!model && !resolutionFailed) {
1811
+ notifyCurrent(
1812
+ `Implementation model ${terminalModelReference(intent.model)} is no longer available. The destination default model will continue.`,
1813
+ );
1814
+ }
1815
+ if (model) {
1816
+ let authenticated = false;
1817
+ try {
1818
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
1819
+ if (!isCurrent()) return "stale";
1820
+ if (auth.ok) authenticated = true;
1821
+ else {
1822
+ notifyCurrent(
1823
+ `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(auth.error)}. The destination default model will continue.`,
1824
+ );
1825
+ }
1826
+ } catch (error: unknown) {
1827
+ notifyCurrent(
1828
+ `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,
1829
+ );
1830
+ }
1831
+ if (!isCurrent()) return "stale";
1832
+ if (authenticated) {
1833
+ let applied = false;
1834
+ let applicationFailed = false;
1835
+ application.drainOnShutdown = true;
1836
+ try {
1837
+ try {
1838
+ applied = await pi.setModel(model);
1839
+ } catch (error: unknown) {
1840
+ applicationFailed = true;
1841
+ notifyCurrent(
1842
+ `Implementation model ${terminalModelReference(intent.model)} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`,
1843
+ );
1844
+ }
1845
+ } finally {
1846
+ application.drainOnShutdown = false;
1847
+ }
1848
+ if (!isCurrent()) return "stale";
1849
+ if (!applied && !applicationFailed) {
1850
+ notifyCurrent(
1851
+ `Implementation model ${terminalModelReference(intent.model)} could not be applied after authentication changed. The destination default model will continue.`,
1852
+ );
1853
+ }
1854
+ }
1855
+ }
1856
+ }
1857
+ if (!isCurrent()) return "stale";
1858
+ applyThinking();
1859
+ if (!isCurrent()) return "stale";
1860
+
1861
+ state = { ...state, pendingImplementationRuntime: undefined };
1862
+ try {
1863
+ persistState();
1864
+ } catch (error: unknown) {
1865
+ state = pendingState;
1866
+ try {
1867
+ if (pi.getThinkingLevel() !== previousThinkingLevel) {
1868
+ pi.setThinkingLevel(previousThinkingLevel);
1869
+ }
1870
+ } catch {
1871
+ // Keep the durable intent pending even if a runtime rollback is unavailable.
1872
+ }
1873
+ try {
1874
+ persistState();
1875
+ } catch {
1876
+ // SessionManager mutates its in-memory branch before a disk append can fail.
1877
+ // A best-effort rollback entry keeps that branch aligned with durable pending state.
1878
+ }
1879
+ notifyCurrent(
1880
+ `Unable to apply fresh implementation settings because their one-shot state could not be consumed: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The implementation request was not sent; retry after session persistence is available.`,
1881
+ );
1882
+ return "blocked";
1883
+ }
1884
+ if (application.holdForAdmission) pendingRuntimeAdmissionSession = session;
1885
+ return "ready";
1886
+ })
1887
+ .finally(() => {
1888
+ if (activeImplementationRuntimeApplication === application) {
1889
+ activeImplementationRuntimeApplication = undefined;
1890
+ }
1891
+ });
1892
+ application = {
1893
+ sessionManager: session,
1894
+ completion,
1895
+ drainOnShutdown: false,
1896
+ holdForAdmission,
1897
+ };
1898
+ activeImplementationRuntimeApplication = application;
1899
+ return completion;
1900
+ }
1901
+
1585
1902
  function applyPlanThinkingLevel() {
1586
1903
  if (state.manualThinkingLevel) {
1587
1904
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
@@ -1805,11 +2122,27 @@ export default function planMode(pi: ExtensionAPI, dependencies: PlanModeDepende
1805
2122
  return safe.length > 120 ? `${safe.slice(0, 119)}…` : safe;
1806
2123
  }
1807
2124
 
2125
+ function terminalModelReference(model: { provider: string; modelId: string }) {
2126
+ const safe = safeTerminalText(`${model.provider}/${model.modelId}`) || "(unnamed model)";
2127
+ return safe.length > 160 ? `${safe.slice(0, 159)}…` : safe;
2128
+ }
2129
+
2130
+ function terminalErrorDetail(error: unknown) {
2131
+ const safe = safeTerminalText(error instanceof Error ? error.message : String(error));
2132
+ if (!safe) return "unknown error";
2133
+ return safe.length > 500 ? `${safe.slice(0, 499)}…` : safe;
2134
+ }
2135
+
1808
2136
  function safeTerminalText(value: string) {
1809
- return [...value]
2137
+ return [...stripVTControlCharacters(value)]
1810
2138
  .map((character) => {
1811
2139
  const codePoint = character.codePointAt(0) ?? 0;
1812
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? " " : character;
2140
+ return codePoint <= 0x1f ||
2141
+ (codePoint >= 0x7f && codePoint <= 0x9f) ||
2142
+ (codePoint >= 0x202a && codePoint <= 0x202e) ||
2143
+ (codePoint >= 0x2066 && codePoint <= 0x2069)
2144
+ ? " "
2145
+ : character;
1813
2146
  })
1814
2147
  .join("")
1815
2148
  .trim();