@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/dist/index.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  IMPLEMENTATION_PLAN_RETENTIONS,
5
+ MAX_PENDING_IMPLEMENTATION_MODEL_IDENTIFIER_LENGTH,
5
6
  PLAN_HISTORY_IMPLEMENTATION_PROMPT,
6
7
  PLAN_MODE_COMPLETE_PARAMS,
7
8
  PLAN_MODE_COMPLETE_TOOL_NAME,
@@ -13,46 +14,45 @@ import {
13
14
  canSelectToolInPlanMode,
14
15
  classifyPlanModeTool,
15
16
  compareTools,
17
+ configuredImplementationModel,
16
18
  configuredImplementationPlanRetention,
19
+ configuredImplementationThinkingLevel,
17
20
  configuredPlanExportPath,
18
21
  configuredPlanModeToggleShortcut,
19
22
  configuredThinkingLevel,
20
- createImplementationPreferenceChange,
21
23
  createImplementationRetentionCoordinator,
22
24
  exportStoredPlan,
25
+ findAvailableImplementationModel,
23
26
  findBlockedCommandSegment,
24
27
  findBlockedPowerShellCommandSegment,
25
- hasImplementationPreferences,
26
28
  implementationRetentionPreview,
27
29
  invalidPlanMessage,
30
+ isPendingImplementationModelIdentifier,
28
31
  latestAssistantStopReason,
29
32
  latestAssistantText,
30
33
  messageTextContent,
31
34
  normalizePlanModeCompletion,
32
35
  normalizePlanModeQuestionParams,
33
- normalizePlanModeSettings,
34
- observeImplementationModelSelections,
35
36
  parseProposedPlan,
36
37
  planExportDestination,
37
38
  planFromCompletionDetails,
38
39
  planModeCompleted,
39
40
  planModeQuestionCancelled,
40
41
  planModeSettingsPath,
41
- preferenceError,
42
- preflightImplementationPreferences,
43
42
  readCommand,
44
43
  readPlanModeSettings,
45
44
  renderPlanModeCompletion,
46
- sameModel,
45
+ snapshotAvailableImplementationModels,
47
46
  snapshotPlanModeSelectedNames,
48
47
  toolPolicyLabel,
49
48
  updatePlanModeSettings
50
- } from "./chunks/chunk-YUFPCQVG.js";
49
+ } from "./chunks/chunk-QHHHBTDO.js";
51
50
 
52
51
  // src/plan-mode.ts
53
52
  import { randomUUID as randomUUID2 } from "node:crypto";
54
53
  import { watch } from "node:fs";
55
54
  import { basename, dirname } from "node:path";
55
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
56
56
 
57
57
  // src/command.ts
58
58
  var PLAN_COMMAND_COMPLETIONS = [
@@ -61,6 +61,7 @@ var PLAN_COMMAND_COMPLETIONS = [
61
61
  { value: "finalize", label: "finalize", description: "Request a completed plan" },
62
62
  { value: "implement", label: "implement", description: "Implement the completed or saved plan" },
63
63
  { value: "save", label: "save", description: "Save the completed plan for later" },
64
+ { value: "settings", label: "settings", description: "Open Plan mode settings" },
64
65
  { value: "export", label: "export", description: "Export the stored plan to a Markdown file" },
65
66
  { value: "exit", label: "exit", description: "Leave Plan mode or clear a saved/active plan" },
66
67
  { value: "off", label: "off", description: "Leave Plan mode or clear a saved/active plan" },
@@ -124,67 +125,45 @@ function createFinalizationRequestCoordinator() {
124
125
  };
125
126
  }
126
127
 
128
+ // src/fresh-handoff-coordinator.ts
129
+ var defaultDependencies = {
130
+ schedule: (callback) => setTimeout(callback, 0),
131
+ cancel: (handle) => clearTimeout(handle)
132
+ };
133
+ function createDeferredFreshHandoffCoordinator(dependencies = defaultDependencies) {
134
+ let generation = 0;
135
+ let pending;
136
+ const cancel = () => {
137
+ generation += 1;
138
+ if (!pending) return;
139
+ dependencies.cancel(pending.handle);
140
+ pending = void 0;
141
+ };
142
+ return {
143
+ schedule(run, onError) {
144
+ cancel();
145
+ const taskGeneration = generation;
146
+ const handle = dependencies.schedule(() => {
147
+ if (pending?.generation !== taskGeneration || generation !== taskGeneration) return;
148
+ pending = void 0;
149
+ const isCurrent = () => generation === taskGeneration;
150
+ void Promise.resolve().then(() => run(isCurrent)).catch((error) => {
151
+ if (!isCurrent()) return;
152
+ try {
153
+ onError(error);
154
+ } catch {
155
+ }
156
+ });
157
+ });
158
+ pending = { generation: taskGeneration, handle };
159
+ },
160
+ cancel
161
+ };
162
+ }
163
+
127
164
  // src/fresh-implementation.ts
128
165
  import { randomUUID } from "node:crypto";
129
-
130
- // src/fresh-implementation-preferences.ts
131
- var FRESH_PREFERENCES_ENTRY = "plan-mode:fresh-preferences:v1";
132
- async function applyFreshImplementationPreferences(pi, ctx, isCurrent, selectionSnapshot) {
133
- if (!isCurrent() || !ctx.isIdle()) return;
134
- const entry = latestPreferenceEntry(ctx);
135
- if (entry?.type !== "custom" || !entry.data || typeof entry.data !== "object") return;
136
- const request = entry.data;
137
- if (request.status !== "pending" || typeof request.id !== "string") return;
138
- const preferences = normalizePlanModeSettings(request.preferences);
139
- pi.appendEntry(FRESH_PREFERENCES_ENTRY, { id: request.id, status: "failed" });
140
- if (!preferences || !hasImplementationPreferences(preferences)) return;
141
- const change = createImplementationPreferenceChange(
142
- pi,
143
- ctx,
144
- isCurrent,
145
- void 0,
146
- selectionSnapshot
147
- );
148
- try {
149
- const originalModel = ctx.model;
150
- const originalThinking = pi.getThinkingLevel();
151
- const current = () => isCurrent() && ctx.isIdle();
152
- const model = await preflightImplementationPreferences(
153
- ctx,
154
- preferences,
155
- () => current() && sameModel(ctx.model, originalModel) && pi.getThinkingLevel() === originalThinking
156
- );
157
- if (!model || !current()) return;
158
- if (!await change.apply(model, preferences, current) || !current()) {
159
- await change.rollback();
160
- return;
161
- }
162
- pi.appendEntry(FRESH_PREFERENCES_ENTRY, {
163
- id: request.id,
164
- status: "applied",
165
- model: { provider: ctx.model?.provider, id: ctx.model?.id },
166
- thinking: pi.getThinkingLevel()
167
- });
168
- } catch (error) {
169
- if (!isCurrent()) return;
170
- await change.rollback().catch(() => void 0);
171
- if (!isCurrent()) return;
172
- pi.appendEntry(FRESH_PREFERENCES_ENTRY, {
173
- id: request.id,
174
- status: "failed",
175
- error: preferenceError(error)
176
- });
177
- }
178
- }
179
- function latestPreferenceEntry(ctx) {
180
- return ctx.sessionManager.getBranch().slice().reverse().find((entry) => entry.type === "custom" && entry.customType === FRESH_PREFERENCES_ENTRY);
181
- }
182
- function freshPreferencesApplied(ctx, id) {
183
- const entry = latestPreferenceEntry(ctx);
184
- if (entry?.type !== "custom" || !entry.data || typeof entry.data !== "object") return false;
185
- const result = entry.data;
186
- return result.id === id && result.status === "applied" && sameModel(ctx.model, result.model) && ctx.thinkingLevel === result.thinking;
187
- }
166
+ import { stripVTControlCharacters } from "node:util";
188
167
 
189
168
  // src/prompt.ts
190
169
  var PLAN_CONTEXT_MARKER = "[CODEX-LIKE PLAN MODE ACTIVE]";
@@ -322,6 +301,134 @@ function unwrapMessage(message) {
322
301
  return entry?.message ?? message ?? {};
323
302
  }
324
303
 
304
+ // src/state.ts
305
+ function restorePlanModeState(entries, stateEntryType) {
306
+ const branch = entries;
307
+ let stateEntryIndex = -1;
308
+ for (let index = branch.length - 1; index >= 0; index -= 1) {
309
+ const candidate = branch[index];
310
+ if (candidate?.type === "custom" && candidate.customType === stateEntryType) {
311
+ stateEntryIndex = index;
312
+ break;
313
+ }
314
+ }
315
+ const entry = branch[stateEntryIndex];
316
+ if (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };
317
+ const enabled = entry.data.enabled === true;
318
+ const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : void 0;
319
+ const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : void 0;
320
+ const recoveredPlan = enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : void 0;
321
+ const latestPlan = persistedPlan ?? recoveredPlan;
322
+ const activeImplementation = enabled ? void 0 : normalizeActiveImplementation(entry.data.activeImplementation);
323
+ const savedPlan = enabled || activeImplementation ? void 0 : normalizeSavedPlan(entry.data.savedPlan);
324
+ const pendingImplementationRuntime = enabled ? void 0 : normalizePendingImplementationRuntime(entry.data.pendingImplementationRuntime);
325
+ return {
326
+ enabled,
327
+ latestPlan,
328
+ latestPlanSource: enabled ? (persistedPlan ? persistedSource : void 0) ?? (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : void 0) : void 0,
329
+ awaitingAction: enabled && latestPlan !== void 0,
330
+ savedPlan,
331
+ activeImplementation,
332
+ pendingImplementationRuntime,
333
+ selectedToolNames: stringArray(entry.data.selectedToolNames),
334
+ selectedToolKeys: stringArray(entry.data.selectedToolKeys),
335
+ workflowToolPolicy: enabled ? normalizeWorkflowToolPolicy(entry.data.workflowToolPolicy) : void 0,
336
+ previousThinkingLevel: enabled ? fixedThinkingLevel(entry.data.previousThinkingLevel) : void 0,
337
+ appliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : void 0,
338
+ manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : void 0
339
+ };
340
+ }
341
+ function normalizeWorkflowToolPolicy(value) {
342
+ if (value === void 0) return void 0;
343
+ const denied = {
344
+ kind: "automatic",
345
+ allowedNames: [],
346
+ resolved: true
347
+ };
348
+ if (!isRecord(value)) return denied;
349
+ const kind = value.kind === "automatic" || value.kind === "explicit" ? value.kind : void 0;
350
+ const allowedNames = stringArray(value.allowedNames);
351
+ if (!kind || !allowedNames || typeof value.resolved !== "boolean") return denied;
352
+ if (kind === "automatic") {
353
+ return { kind, allowedNames, resolved: value.resolved };
354
+ }
355
+ const desiredNames = stringArray(value.desiredNames);
356
+ if (!desiredNames) return denied;
357
+ return { kind, desiredNames, allowedNames, resolved: value.resolved };
358
+ }
359
+ function normalizeSavedPlan(value) {
360
+ if (!isRecord(value)) return void 0;
361
+ const source = planCompletionSource(value.source);
362
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
363
+ if (!source || !normalized.ok) return void 0;
364
+ return { plan: normalized.plan, source };
365
+ }
366
+ function normalizePendingImplementationRuntime(value) {
367
+ if (!isRecord(value) || value.version !== 1) return void 0;
368
+ if (Object.keys(value).some(
369
+ (key) => key !== "version" && key !== "model" && key !== "thinkingLevel"
370
+ )) {
371
+ return void 0;
372
+ }
373
+ let model;
374
+ if (value.model !== void 0) {
375
+ if (!isRecord(value.model) || Object.keys(value.model).some((key) => key !== "provider" && key !== "modelId")) {
376
+ return void 0;
377
+ }
378
+ if (!isPendingImplementationModelIdentifier(value.model.provider) || !isPendingImplementationModelIdentifier(value.model.modelId)) {
379
+ return void 0;
380
+ }
381
+ model = { provider: value.model.provider, modelId: value.model.modelId };
382
+ }
383
+ const thinkingLevel = value.thinkingLevel === void 0 ? void 0 : fixedThinkingLevel(value.thinkingLevel);
384
+ if (value.thinkingLevel !== void 0 && !thinkingLevel) return void 0;
385
+ if (!model && !thinkingLevel) return void 0;
386
+ return {
387
+ version: 1,
388
+ ...model ? { model } : {},
389
+ ...thinkingLevel ? { thinkingLevel } : {}
390
+ };
391
+ }
392
+ function normalizeActiveImplementation(value) {
393
+ if (!isRecord(value)) return void 0;
394
+ const id = typeof value.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id) ? value.id : void 0;
395
+ const source = planCompletionSource(value.source);
396
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
397
+ const startedAt = typeof value.startedAt === "number" && Number.isSafeInteger(value.startedAt) && value.startedAt >= 0 ? value.startedAt : void 0;
398
+ if (!id || !source || !normalized.ok || startedAt === void 0) return void 0;
399
+ const retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(
400
+ value.retention
401
+ ) ? value.retention : "keep";
402
+ return { id, plan: normalized.plan, source, startedAt, retention };
403
+ }
404
+ function normalizePersistedPlan(value) {
405
+ const normalized = normalizePlanModeCompletion({ plan: value });
406
+ return normalized.ok ? normalized.plan : void 0;
407
+ }
408
+ function latestCompletionPlan(entries) {
409
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
410
+ const message = entries[index]?.message;
411
+ if (message?.role !== "toolResult" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {
412
+ continue;
413
+ }
414
+ const plan = planFromCompletionDetails(message.details);
415
+ if (plan) return plan;
416
+ }
417
+ return void 0;
418
+ }
419
+ function planCompletionSource(value) {
420
+ return value === PLAN_MODE_COMPLETE_TOOL_NAME || value === "legacy_proposed_plan" ? value : void 0;
421
+ }
422
+ function fixedThinkingLevel(value) {
423
+ return typeof value === "string" && value !== "inherit" && PLAN_MODE_THINKING_LEVELS.includes(value) ? value : void 0;
424
+ }
425
+ function stringArray(value) {
426
+ return Array.isArray(value) && value.every((item) => typeof item === "string") ? Array.from(new Set(value)) : void 0;
427
+ }
428
+ function isRecord(value) {
429
+ return typeof value === "object" && value !== null && !Array.isArray(value);
430
+ }
431
+
325
432
  // src/fresh-implementation.ts
326
433
  function formatImplementationHandoff(plan) {
327
434
  return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:
@@ -361,9 +468,9 @@ async function startFreshImplementationFromState(ctx, options) {
361
468
  return startFreshImplementationSession(ctx, {
362
469
  plan,
363
470
  source,
364
- preferences: options.preferences,
365
471
  retention: options.retention,
366
472
  stateEntryType: options.stateEntryType,
473
+ runtime: options.runtime,
367
474
  isCurrent
368
475
  });
369
476
  }
@@ -373,34 +480,23 @@ async function startFreshImplementationSession(ctx, request) {
373
480
  }
374
481
  await ctx.waitForIdle();
375
482
  if (!request.isCurrent()) return { kind: "stale" };
376
- const preferences = request.preferences ?? {};
377
- const originalModel = ctx.model;
378
- const originalThinking = ctx.thinkingLevel;
379
- const preflightCurrent = () => request.isCurrent() && sameModel(ctx.model, originalModel) && ctx.thinkingLevel === originalThinking;
380
- const preferencesId = hasImplementationPreferences(preferences) ? randomUUID() : void 0;
381
- if (preferencesId) {
382
- try {
383
- if (!await preflightImplementationPreferences(ctx, preferences, preflightCurrent))
384
- return { kind: "stale" };
385
- } catch (error) {
386
- if (preflightCurrent())
387
- safeNotify(ctx, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
388
- return { kind: "rejected" };
389
- }
390
- } else if (!await preflightModel(ctx, preflightCurrent)) return { kind: "rejected" };
391
- if (!preflightCurrent() || !ctx.isIdle()) return { kind: "stale" };
483
+ if (!await preflightModel(ctx, request)) return { kind: "rejected" };
484
+ if (!request.isCurrent()) return { kind: "stale" };
392
485
  const usesConversationHistory = request.retention === "clear-on-start";
393
- const destinationState = usesConversationHistory ? void 0 : {
486
+ const pendingImplementationRuntime = pendingRuntimeIntent(request.runtime);
487
+ const activeImplementation = usesConversationHistory ? void 0 : {
488
+ id: randomUUID(),
489
+ plan: request.plan,
490
+ source: request.source,
491
+ startedAt: Date.now(),
492
+ retention: request.retention
493
+ };
494
+ const destinationState = activeImplementation || pendingImplementationRuntime ? {
394
495
  enabled: false,
395
496
  awaitingAction: false,
396
- activeImplementation: {
397
- id: randomUUID(),
398
- plan: request.plan,
399
- source: request.source,
400
- startedAt: Date.now(),
401
- retention: request.retention
402
- }
403
- };
497
+ ...activeImplementation ? { activeImplementation } : {},
498
+ ...pendingImplementationRuntime ? { pendingImplementationRuntime } : {}
499
+ } : void 0;
404
500
  const handoff = usesConversationHistory ? formatTransferredPlanPrompt(request.plan, true) : formatImplementationHandoff(request.plan);
405
501
  const parentSession = ctx.sessionManager.getSessionFile();
406
502
  let setupError;
@@ -412,12 +508,6 @@ async function startFreshImplementationSession(ctx, request) {
412
508
  ...parentSession ? { parentSession } : {},
413
509
  setup: async (sessionManager) => {
414
510
  try {
415
- if (preferencesId)
416
- sessionManager.appendCustomEntry(FRESH_PREFERENCES_ENTRY, {
417
- id: preferencesId,
418
- status: "pending",
419
- preferences
420
- });
421
511
  const contract = createModeContractMessage("normal");
422
512
  sessionManager.appendCustomMessageEntry(
423
513
  contract.customType,
@@ -433,25 +523,37 @@ async function startFreshImplementationSession(ctx, request) {
433
523
  }
434
524
  },
435
525
  withSession: async (replacementCtx) => {
436
- if (!setupError && preferencesId && !freshPreferencesApplied(replacementCtx, preferencesId)) {
437
- setupError = "Implementation model/thinking could not be applied or changed before kickoff";
438
- }
439
526
  if (setupError) {
440
527
  recoverSetupFailure(replacementCtx, handoff, setupError);
441
528
  return;
442
529
  }
443
- try {
444
- await replacementCtx.sendUserMessage(handoff);
445
- } catch (error) {
446
- kickoffError = safeErrorDetail(error);
530
+ const reportKickoffFailure = (detail) => {
531
+ kickoffError = detail;
447
532
  const recoveredInEditor = usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
448
533
  safeNotify(
449
534
  replacementCtx,
450
- usesConversationHistory ? recoveredInEditor ? `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request is in the editor; submit it or resume the parent planning session.` : `Fresh session created, but implementation did not start: ${kickoffError}. The implementation request could not be restored to the editor; resume the parent planning session.` : `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.`,
535
+ usesConversationHistory ? recoveredInEditor ? `Fresh session created, but implementation did not start: ${detail}. The implementation request is in the editor; submit it or resume the parent planning session.` : `Fresh session created, but implementation did not start: ${detail}. The implementation request could not be restored to the editor; resume the parent planning session.` : `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.`,
451
536
  "error"
452
537
  );
538
+ };
539
+ try {
540
+ await replacementCtx.sendUserMessage(handoff);
541
+ } catch (error) {
542
+ reportKickoffFailure(safeErrorDetail(error));
453
543
  return;
454
544
  }
545
+ if (pendingImplementationRuntime) {
546
+ const runtimeStatus = destinationRuntimeConsumptionStatus(
547
+ replacementCtx,
548
+ request.stateEntryType
549
+ );
550
+ if (runtimeStatus !== "consumed") {
551
+ reportKickoffFailure(
552
+ runtimeStatus === "pending" ? "fresh implementation settings could not be consumed" : "fresh implementation settings could not be verified as consumed"
553
+ );
554
+ return;
555
+ }
556
+ }
455
557
  safeNotify(
456
558
  replacementCtx,
457
559
  "Fresh implementation session started. Only the approved plan was transferred.",
@@ -473,28 +575,87 @@ async function startFreshImplementationSession(ctx, request) {
473
575
  }
474
576
  return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
475
577
  }
476
- async function preflightModel(ctx, isCurrent) {
477
- const model = ctx.model;
578
+ async function preflightModel(ctx, request) {
579
+ const requestedModel = request.runtime?.model;
580
+ let model = ctx.model;
581
+ if (requestedModel) {
582
+ if (!isPendingImplementationModelIdentifier(requestedModel.provider) || !isPendingImplementationModelIdentifier(requestedModel.modelId)) {
583
+ notifyCurrent(
584
+ ctx,
585
+ request,
586
+ `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.`,
587
+ "warning"
588
+ );
589
+ return false;
590
+ }
591
+ const isCurrentModel = ctx.model?.provider === requestedModel.provider && ctx.model.id === requestedModel.modelId;
592
+ if (!isCurrentModel) {
593
+ try {
594
+ model = ctx.modelRegistry.find(requestedModel.provider, requestedModel.modelId);
595
+ } catch (error) {
596
+ notifyCurrent(
597
+ ctx,
598
+ request,
599
+ `Unable to implement the plan: ${safeErrorDetail(error)}`,
600
+ "error"
601
+ );
602
+ return false;
603
+ }
604
+ }
605
+ if (!model) {
606
+ notifyCurrent(
607
+ ctx,
608
+ request,
609
+ `Unable to implement the plan: implementation model ${safeModelReference(requestedModel)} is no longer available. Choose another model and retry.`,
610
+ "warning"
611
+ );
612
+ return false;
613
+ }
614
+ }
478
615
  if (!model) {
479
- ctx.ui.notify("Unable to implement the plan: no model is selected.", "warning");
616
+ notifyCurrent(ctx, request, "Unable to implement the plan: no model is selected.", "warning");
480
617
  return false;
481
618
  }
482
619
  let auth;
483
620
  try {
484
621
  auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
485
622
  } catch (error) {
486
- if (isCurrent()) {
487
- ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
488
- }
623
+ notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
489
624
  return false;
490
625
  }
491
- if (!isCurrent()) return false;
626
+ if (!request.isCurrent()) return false;
492
627
  if (!auth.ok) {
493
- ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(auth.error)}`, "warning");
628
+ notifyCurrent(
629
+ ctx,
630
+ request,
631
+ requestedModel ? `Unable to implement the plan with ${safeModelReference(model)}: ${safeErrorDetail(auth.error)}. Choose another model or configure authentication, then retry.` : `Unable to implement the plan: ${safeErrorDetail(auth.error)}`,
632
+ "warning"
633
+ );
494
634
  return false;
495
635
  }
496
636
  return true;
497
637
  }
638
+ function notifyCurrent(ctx, request, message, level) {
639
+ if (request.isCurrent()) safeNotify(ctx, message, level);
640
+ }
641
+ function pendingRuntimeIntent(selection) {
642
+ if (!selection?.model && !selection?.thinkingLevel) return void 0;
643
+ return {
644
+ version: 1,
645
+ ...selection.model ? { model: { provider: selection.model.provider, modelId: selection.model.modelId } } : {},
646
+ ...selection.thinkingLevel ? { thinkingLevel: selection.thinkingLevel } : {}
647
+ };
648
+ }
649
+ function safeModelReference(model) {
650
+ return safeErrorDetail(`${model.provider}/${model.modelId ?? model.id ?? "unknown"}`);
651
+ }
652
+ function destinationRuntimeConsumptionStatus(ctx, stateEntryType) {
653
+ try {
654
+ return restorePlanModeState(ctx.sessionManager.getBranch(), stateEntryType).pendingImplementationRuntime ? "pending" : "consumed";
655
+ } catch {
656
+ return "unavailable";
657
+ }
658
+ }
498
659
  function recoverSetupFailure(ctx, handoff, setupError) {
499
660
  const recoveredInEditor = safeSetEditorText(ctx, handoff);
500
661
  safeNotify(
@@ -522,9 +683,9 @@ function isCommandContext(ctx) {
522
683
  }
523
684
  function safeErrorDetail(error) {
524
685
  const detail = error instanceof Error ? error.message : String(error);
525
- const normalized = [...detail].map((character) => {
686
+ const normalized = [...stripVTControlCharacters(detail)].map((character) => {
526
687
  const codePoint = character.codePointAt(0) ?? 0;
527
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
688
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 ? " " : character;
528
689
  }).join("").replace(/\s+/gu, " ").trim() || "unknown error";
529
690
  const characters = [...normalized];
530
691
  return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
@@ -532,15 +693,40 @@ function safeErrorDetail(error) {
532
693
 
533
694
  // src/plan-action-controller.ts
534
695
  function createPlanActionController(options) {
535
- const implementationActions = (ctx, lifecycle) => ({
536
- implementationPreferences: options.getImplementationPreferences?.(),
537
- implementHere: (preferences, signal) => options.implementHere(
538
- ctx,
539
- preferences,
540
- () => lifecycle.isCurrent() && !lifecycle.signal.aborted && !signal?.aborted
541
- ),
542
- implementFresh: (signal, preferences) => options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted, preferences)
543
- });
696
+ const configuredDefaults = () => {
697
+ const settings = options.getSettings();
698
+ const model = configuredImplementationModel(settings);
699
+ const thinkingLevel = configuredImplementationThinkingLevel(settings);
700
+ return {
701
+ ...model ? { model: { ...model } } : {},
702
+ ...thinkingLevel ? { thinkingLevel } : {}
703
+ };
704
+ };
705
+ const effectiveDefaults = (ctx) => {
706
+ const configured = configuredDefaults();
707
+ const availableModel = findAvailableImplementationModel(
708
+ snapshotAvailableImplementationModels(ctx),
709
+ configured.model
710
+ );
711
+ if (configured.model && !availableModel) {
712
+ ctx.ui.notify(
713
+ "The configured fresh implementation model is unavailable; using the planning model.",
714
+ "warning"
715
+ );
716
+ }
717
+ const planModel = ctx.model ? { provider: ctx.model.provider, modelId: ctx.model.id } : void 0;
718
+ const model = availableModel ? { provider: availableModel.provider, modelId: availableModel.id } : planModel;
719
+ const thinkingLevel = configured.thinkingLevel ?? options.getThinkingLevel();
720
+ return {
721
+ ...model ? { model } : {},
722
+ ...thinkingLevel ? { thinkingLevel } : {}
723
+ };
724
+ };
725
+ const freshAction = (ctx, lifecycle, signal, runtime, timing) => {
726
+ if (signal.aborted) return;
727
+ const isCurrent = timing === "after-settled" ? lifecycle.isCurrent : () => lifecycle.isCurrent() && !signal.aborted;
728
+ return options.implementFresh(ctx, isCurrent, runtime, timing);
729
+ };
544
730
  return {
545
731
  async showSaved(ctx) {
546
732
  const lifecycle = options.captureLifecycle();
@@ -554,7 +740,8 @@ function createPlanActionController(options) {
554
740
  signal: lifecycle.signal,
555
741
  isCurrent: lifecycle.isCurrent,
556
742
  show: () => options.show(ctx),
557
- ...implementationActions(ctx, lifecycle),
743
+ implementHere: () => options.implementHere(ctx),
744
+ implementFresh: (signal) => freshAction(ctx, lifecycle, signal, effectiveDefaults(ctx), "immediate"),
558
745
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
559
746
  settings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),
560
747
  clear: () => options.clearSaved(ctx)
@@ -571,13 +758,16 @@ function createPlanActionController(options) {
571
758
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
572
759
  await ui.showPlanModeMenu(ctx, {
573
760
  statusText: options.statusText(),
761
+ planThinkingLevel: options.getThinkingLevel(),
762
+ implementationDefaults: configuredDefaults(),
574
763
  hasReadyPlan: options.getState().latestPlan !== void 0,
575
764
  implementationOutcome: options.implementationOutcome,
576
765
  getExportDestination: () => options.getExportDestination(ctx),
577
766
  ...lifecycle,
578
767
  show: () => options.show(ctx),
579
768
  finalize: () => options.finalize(ctx),
580
- ...implementationActions(ctx, lifecycle),
769
+ implementHere: () => options.implementHere(ctx),
770
+ implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, "immediate"),
581
771
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
582
772
  save: () => options.save(ctx),
583
773
  stay: () => options.stay(ctx),
@@ -591,9 +781,12 @@ function createPlanActionController(options) {
591
781
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
592
782
  await ui.showReadyPlanMenu(ctx, {
593
783
  ...lifecycle,
784
+ planThinkingLevel: options.getThinkingLevel(),
785
+ implementationDefaults: configuredDefaults(),
594
786
  implementationOutcome: options.implementationOutcome,
595
787
  getExportDestination: () => options.getExportDestination(ctx),
596
- ...implementationActions(ctx, lifecycle),
788
+ implementHere: () => options.implementHere(ctx),
789
+ implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, "after-settled"),
597
790
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
598
791
  save: () => options.save(ctx),
599
792
  stay: () => void 0,
@@ -792,106 +985,6 @@ async function preflightSavedPlanImplementation(ctx, isCurrent) {
792
985
  return true;
793
986
  }
794
987
 
795
- // src/state.ts
796
- function restorePlanModeState(entries, stateEntryType) {
797
- const branch = entries;
798
- let stateEntryIndex = -1;
799
- for (let index = branch.length - 1; index >= 0; index -= 1) {
800
- const candidate = branch[index];
801
- if (candidate?.type === "custom" && candidate.customType === stateEntryType) {
802
- stateEntryIndex = index;
803
- break;
804
- }
805
- }
806
- const entry = branch[stateEntryIndex];
807
- if (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };
808
- const enabled = entry.data.enabled === true;
809
- const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : void 0;
810
- const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : void 0;
811
- const recoveredPlan = enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : void 0;
812
- const latestPlan = persistedPlan ?? recoveredPlan;
813
- const activeImplementation = enabled ? void 0 : normalizeActiveImplementation(entry.data.activeImplementation);
814
- const savedPlan = enabled || activeImplementation ? void 0 : normalizeSavedPlan(entry.data.savedPlan);
815
- return {
816
- enabled,
817
- latestPlan,
818
- latestPlanSource: enabled ? (persistedPlan ? persistedSource : void 0) ?? (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : void 0) : void 0,
819
- awaitingAction: enabled && latestPlan !== void 0,
820
- savedPlan,
821
- activeImplementation,
822
- selectedToolNames: stringArray(entry.data.selectedToolNames),
823
- selectedToolKeys: stringArray(entry.data.selectedToolKeys),
824
- workflowToolPolicy: enabled ? normalizeWorkflowToolPolicy(entry.data.workflowToolPolicy) : void 0,
825
- previousThinkingLevel: enabled ? fixedThinkingLevel(entry.data.previousThinkingLevel) : void 0,
826
- appliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : void 0,
827
- manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : void 0
828
- };
829
- }
830
- function normalizeWorkflowToolPolicy(value) {
831
- if (value === void 0) return void 0;
832
- const denied = {
833
- kind: "automatic",
834
- allowedNames: [],
835
- resolved: true
836
- };
837
- if (!isRecord(value)) return denied;
838
- const kind = value.kind === "automatic" || value.kind === "explicit" ? value.kind : void 0;
839
- const allowedNames = stringArray(value.allowedNames);
840
- if (!kind || !allowedNames || typeof value.resolved !== "boolean") return denied;
841
- if (kind === "automatic") {
842
- return { kind, allowedNames, resolved: value.resolved };
843
- }
844
- const desiredNames = stringArray(value.desiredNames);
845
- if (!desiredNames) return denied;
846
- return { kind, desiredNames, allowedNames, resolved: value.resolved };
847
- }
848
- function normalizeSavedPlan(value) {
849
- if (!isRecord(value)) return void 0;
850
- const source = planCompletionSource(value.source);
851
- const normalized = normalizePlanModeCompletion({ plan: value.plan });
852
- if (!source || !normalized.ok) return void 0;
853
- return { plan: normalized.plan, source };
854
- }
855
- function normalizeActiveImplementation(value) {
856
- if (!isRecord(value)) return void 0;
857
- const id = typeof value.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id) ? value.id : void 0;
858
- const source = planCompletionSource(value.source);
859
- const normalized = normalizePlanModeCompletion({ plan: value.plan });
860
- const startedAt = typeof value.startedAt === "number" && Number.isSafeInteger(value.startedAt) && value.startedAt >= 0 ? value.startedAt : void 0;
861
- if (!id || !source || !normalized.ok || startedAt === void 0) return void 0;
862
- const retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(
863
- value.retention
864
- ) ? value.retention : "keep";
865
- return { id, plan: normalized.plan, source, startedAt, retention };
866
- }
867
- function normalizePersistedPlan(value) {
868
- const normalized = normalizePlanModeCompletion({ plan: value });
869
- return normalized.ok ? normalized.plan : void 0;
870
- }
871
- function latestCompletionPlan(entries) {
872
- for (let index = entries.length - 1; index >= 0; index -= 1) {
873
- const message = entries[index]?.message;
874
- if (message?.role !== "toolResult" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {
875
- continue;
876
- }
877
- const plan = planFromCompletionDetails(message.details);
878
- if (plan) return plan;
879
- }
880
- return void 0;
881
- }
882
- function planCompletionSource(value) {
883
- return value === PLAN_MODE_COMPLETE_TOOL_NAME || value === "legacy_proposed_plan" ? value : void 0;
884
- }
885
- function fixedThinkingLevel(value) {
886
- return typeof value === "string" && value !== "inherit" && PLAN_MODE_THINKING_LEVELS.includes(value) ? value : void 0;
887
- }
888
- function stringArray(value) {
889
- return Array.isArray(value) && value.every((item) => typeof item === "string") ? Array.from(new Set(value)) : void 0;
890
- }
891
- function isRecord(value) {
892
- return typeof value === "object" && value !== null && !Array.isArray(value);
893
- }
894
-
895
988
  // src/workflow-mutex.ts
896
989
  var WORKFLOW_MUTEX_CHANNEL = "workflow:mutex:v1";
897
990
  var AGENT_WORKFLOW_GROUP = "agent-workflow";
@@ -958,10 +1051,10 @@ var WorkflowMutex = class {
958
1051
  // src/plan-mode.ts
959
1052
  var STATE_ENTRY_TYPE = "plan-mode-state";
960
1053
  var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
1054
+ var RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE = "plan-mode-recovered-input";
961
1055
  var BLOCKED_MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "update_plan"]);
962
1056
  var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
963
1057
  function planMode(pi, dependencies = {}) {
964
- const selectionSnapshot = observeImplementationModelSelections(pi);
965
1058
  const workflowMutex = new WorkflowMutex(pi);
966
1059
  let workflowOwner;
967
1060
  let currentSession;
@@ -970,7 +1063,7 @@ function planMode(pi, dependencies = {}) {
970
1063
  const loadInteractiveUi = () => {
971
1064
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
972
1065
  if (!interactiveUiPromise) {
973
- interactiveUiPromise = import("./chunks/interactive-ui-M3GEZN4M.js").catch((error) => {
1066
+ interactiveUiPromise = import("./chunks/interactive-ui-UNJGC2RQ.js").catch((error) => {
974
1067
  interactiveUiPromise = void 0;
975
1068
  throw error;
976
1069
  });
@@ -989,12 +1082,15 @@ function planMode(pi, dependencies = {}) {
989
1082
  let modeContractsRelevant = false;
990
1083
  let readyPresentationIntent;
991
1084
  let latestCommandContext;
1085
+ let stagedFreshImplementation;
1086
+ const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();
992
1087
  let nextReadyPresentationNonce = 0;
993
1088
  let menuGeneration = 0;
994
- let implementationInFlight = false;
995
- let applyingImplementationPreferences = false;
996
1089
  let workflowGeneration = 0;
997
1090
  let refreshStateBeforeFirstAgentStart = false;
1091
+ let activeImplementationRuntimeApplication;
1092
+ let pendingRuntimeAdmissionSession;
1093
+ let queuedRuntimeAdmissionInputs = [];
998
1094
  let menuController = new AbortController();
999
1095
  let settingsWatch;
1000
1096
  let settingsReloadTimer;
@@ -1013,14 +1109,14 @@ function planMode(pi, dependencies = {}) {
1013
1109
  getState: () => state,
1014
1110
  captureLifecycle: captureMenuLifecycle,
1015
1111
  statusText: planStatusText,
1112
+ // ExtensionContext.thinkingLevel was added after the supported Pi 0.80.6 floor.
1113
+ // ExtensionAPI has exposed the same runtime value throughout that compatibility range.
1114
+ getThinkingLevel: () => pi.getThinkingLevel(),
1115
+ getSettings: () => settings,
1016
1116
  implementationOutcome,
1017
1117
  getExportDestination: (ctx) => planExports.getDestination(ctx),
1018
1118
  show: (ctx) => showStoredPlan(pi, ctx, state),
1019
1119
  finalize: requestFinalPlan,
1020
- getImplementationPreferences: () => ({
1021
- implementationModel: settings.implementationModel,
1022
- implementationThinkingLevel: settings.implementationThinkingLevel
1023
- }),
1024
1120
  implementHere: startImplementation,
1025
1121
  implementFresh: startFreshImplementation,
1026
1122
  exportPlan,
@@ -1128,6 +1224,14 @@ function planMode(pi, dependencies = {}) {
1128
1224
  savePlanForLater(ctx);
1129
1225
  return;
1130
1226
  }
1227
+ if (command === "settings") {
1228
+ if (!ctx.hasUI) {
1229
+ throw new Error("/plan settings requires TUI or RPC mode and is unavailable here.");
1230
+ }
1231
+ const lifecycle = captureMenuLifecycle();
1232
+ await showSettings(ctx, lifecycle.signal, lifecycle.isCurrent);
1233
+ return;
1234
+ }
1131
1235
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
1132
1236
  if (exportMatch) {
1133
1237
  const lifecycle = captureMenuLifecycle();
@@ -1257,6 +1361,7 @@ function planMode(pi, dependencies = {}) {
1257
1361
  }
1258
1362
  };
1259
1363
  pi.on("session_start", async (event, ctx) => {
1364
+ cancelDeferredFreshImplementation();
1260
1365
  const generation = ++menuGeneration;
1261
1366
  finalizationRequest.reset();
1262
1367
  currentSession = ctx.sessionManager;
@@ -1264,6 +1369,8 @@ function planMode(pi, dependencies = {}) {
1264
1369
  workflowOwner = void 0;
1265
1370
  workflowMutex.bindSession(ctx.sessionManager);
1266
1371
  refreshStateBeforeFirstAgentStart = event.reason === "new";
1372
+ pendingRuntimeAdmissionSession = void 0;
1373
+ queuedRuntimeAdmissionInputs = [];
1267
1374
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
1268
1375
  menuController = new AbortController();
1269
1376
  readyPresentationIntent = void 0;
@@ -1282,15 +1389,18 @@ function planMode(pi, dependencies = {}) {
1282
1389
  if (!installRestoredState(restoredState, ctx)) return;
1283
1390
  implementationRetention.restore(state.activeImplementation);
1284
1391
  updateUi(ctx);
1285
- if (event.reason === "new")
1286
- await applyFreshImplementationPreferences(
1287
- pi,
1288
- ctx,
1289
- () => generation === menuGeneration && !menuController.signal.aborted,
1290
- selectionSnapshot
1291
- );
1392
+ if (event.reason !== "new") await applyPendingImplementationRuntime(ctx);
1292
1393
  });
1293
1394
  pi.on("session_before_tree", (event, ctx) => {
1395
+ if (runtimeAdmissionIsPending(ctx.sessionManager)) {
1396
+ if (ctx.hasUI) {
1397
+ ctx.ui.notify(
1398
+ "Wait for fresh implementation startup to admit the pending prompts before changing branches.",
1399
+ "warning"
1400
+ );
1401
+ }
1402
+ return { cancel: true };
1403
+ }
1294
1404
  const target = ctx.sessionManager.getEntry(event.preparation.targetId);
1295
1405
  if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
1296
1406
  return;
@@ -1303,13 +1413,16 @@ function planMode(pi, dependencies = {}) {
1303
1413
  }
1304
1414
  return { cancel: true };
1305
1415
  });
1306
- pi.on("session_tree", (_event, ctx) => {
1416
+ pi.on("session_tree", async (_event, ctx) => {
1417
+ cancelDeferredFreshImplementation();
1307
1418
  advanceWorkflowGeneration();
1308
1419
  menuGeneration += 1;
1309
1420
  menuController.abort(new DOMException("Plan-mode tree branch changed", "AbortError"));
1310
1421
  menuController = new AbortController();
1311
1422
  readyPresentationIntent = void 0;
1312
1423
  latestCommandContext = void 0;
1424
+ pendingRuntimeAdmissionSession = void 0;
1425
+ queuedRuntimeAdmissionInputs = [];
1313
1426
  implementationRetention.reset();
1314
1427
  const branch = ctx.sessionManager.getBranch();
1315
1428
  const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
@@ -1318,9 +1431,10 @@ function planMode(pi, dependencies = {}) {
1318
1431
  implementationRetention.restore(state.activeImplementation);
1319
1432
  startPlanModeSettingsWatch(menuGeneration);
1320
1433
  updateUi(ctx);
1434
+ await applyPendingImplementationRuntime(ctx);
1321
1435
  });
1322
1436
  pi.on("thinking_level_select", (event) => {
1323
- if (applyingImplementationPreferences || !state.enabled || !state.appliedThinkingLevel) return;
1437
+ if (!state.enabled || !state.appliedThinkingLevel) return;
1324
1438
  if (event.level !== state.appliedThinkingLevel) {
1325
1439
  state = {
1326
1440
  ...state,
@@ -1332,16 +1446,37 @@ function planMode(pi, dependencies = {}) {
1332
1446
  }
1333
1447
  });
1334
1448
  pi.on("session_shutdown", async (_event, ctx) => {
1449
+ cancelDeferredFreshImplementation();
1335
1450
  const shutdownSession = ctx.sessionManager;
1451
+ const runtimeApplication = activeImplementationRuntimeApplication?.sessionManager === shutdownSession && activeImplementationRuntimeApplication.drainOnShutdown ? activeImplementationRuntimeApplication : void 0;
1452
+ const queuedInputs = takeQueuedRuntimeAdmissionInputs(shutdownSession);
1453
+ for (const queued of queuedInputs) {
1454
+ pi.sendMessage(
1455
+ {
1456
+ customType: RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE,
1457
+ content: runtimeAdmissionInputContent(queued),
1458
+ display: true,
1459
+ details: { source: queued.source }
1460
+ },
1461
+ { triggerTurn: false }
1462
+ );
1463
+ }
1336
1464
  finalizationRequest.reset();
1337
1465
  menuGeneration += 1;
1338
1466
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
1339
1467
  readyPresentationIntent = void 0;
1340
1468
  latestCommandContext = void 0;
1341
1469
  refreshStateBeforeFirstAgentStart = false;
1470
+ pendingRuntimeAdmissionSession = void 0;
1471
+ queuedRuntimeAdmissionInputs = [];
1342
1472
  workflowAllowedToolNames = void 0;
1343
1473
  pendingWorkflowToolPolicy = void 0;
1344
1474
  implementationRetention.reset();
1475
+ if (runtimeApplication) await runtimeApplication.completion;
1476
+ if (currentSession !== void 0 && currentSession !== shutdownSession) {
1477
+ workflowMutex.unbindSession(shutdownSession);
1478
+ return;
1479
+ }
1345
1480
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
1346
1481
  if (currentSession !== void 0 && currentSession !== shutdownSession) {
1347
1482
  workflowMutex.unbindSession(shutdownSession);
@@ -1451,19 +1586,41 @@ Blocked command: ${blocked}`
1451
1586
  const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
1452
1587
  return { messages };
1453
1588
  });
1454
- pi.on("before_agent_start", (_event, ctx) => {
1455
- if (refreshStateBeforeFirstAgentStart) {
1456
- refreshStateBeforeFirstAgentStart = false;
1457
- implementationRetention.reset();
1458
- const branch = ctx.sessionManager.getBranch();
1459
- const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1460
- restoreModeContractTracking(branch, restoredState);
1461
- if (!installRestoredState(restoredState, ctx)) return;
1462
- implementationRetention.restore(state.activeImplementation);
1463
- updateUi(ctx);
1589
+ pi.on("input", async (event, ctx) => {
1590
+ refreshStateForFirstPrompt(ctx);
1591
+ const waitsForRuntimeAdmission = activeImplementationRuntimeApplication?.sessionManager === ctx.sessionManager || pendingRuntimeAdmissionSession === ctx.sessionManager;
1592
+ const queuedInput = waitsForRuntimeAdmission ? {
1593
+ sessionManager: ctx.sessionManager,
1594
+ text: event.text,
1595
+ ...event.images ? { images: [...event.images] } : {},
1596
+ source: event.source
1597
+ } : void 0;
1598
+ if (queuedInput) queuedRuntimeAdmissionInputs.push(queuedInput);
1599
+ const result = await applyPendingImplementationRuntime(ctx, true);
1600
+ if (result !== "ready") {
1601
+ if (result === "stale" && queuedInput) removeQueuedRuntimeAdmissionInput(queuedInput);
1602
+ return { action: "handled" };
1603
+ }
1604
+ if (queuedInput) return { action: "handled" };
1605
+ });
1606
+ pi.on("agent_start", (_event, ctx) => {
1607
+ if (currentSession !== ctx.sessionManager) return;
1608
+ if (pendingRuntimeAdmissionSession === ctx.sessionManager) {
1609
+ pendingRuntimeAdmissionSession = void 0;
1610
+ }
1611
+ const queuedInputs = takeQueuedRuntimeAdmissionInputs(ctx.sessionManager);
1612
+ for (const queued of queuedInputs) {
1613
+ pi.sendUserMessage(runtimeAdmissionInputContent(queued), {
1614
+ deliverAs: "followUp",
1615
+ expandPromptTemplates: queued.source !== "extension"
1616
+ });
1464
1617
  }
1618
+ });
1619
+ pi.on("before_agent_start", (_event, ctx) => {
1620
+ refreshStateForFirstPrompt(ctx);
1465
1621
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1466
1622
  if (state.latestPlan || state.awaitingAction) {
1623
+ cancelDeferredFreshImplementation();
1467
1624
  readyPresentationIntent = void 0;
1468
1625
  state = {
1469
1626
  ...state,
@@ -1513,6 +1670,7 @@ Blocked command: ${blocked}`
1513
1670
  if (!intent || !readyPresentationIsCurrent(intent)) return;
1514
1671
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
1515
1672
  readyPresentationIntent = void 0;
1673
+ stagedFreshImplementation = void 0;
1516
1674
  try {
1517
1675
  if (intent.source === "legacy_proposed_plan") {
1518
1676
  pi.sendMessage(
@@ -1529,7 +1687,11 @@ ${intent.plan}`,
1529
1687
  if (ctx.hasUI && completedPlanIsCurrent(intent)) {
1530
1688
  await planActions.showReady(latestCommandContext ?? ctx);
1531
1689
  }
1690
+ const request = stagedFreshImplementation;
1691
+ stagedFreshImplementation = void 0;
1692
+ if (request) armDeferredFreshImplementation(request);
1532
1693
  } catch (error) {
1694
+ stagedFreshImplementation = void 0;
1533
1695
  if (!isStaleExtensionContextError(error)) throw error;
1534
1696
  }
1535
1697
  });
@@ -1560,6 +1722,7 @@ ${intent.plan}`,
1560
1722
  awaitingAction: false,
1561
1723
  savedPlan: void 0,
1562
1724
  activeImplementation: void 0,
1725
+ pendingImplementationRuntime: void 0,
1563
1726
  selectedToolNames: candidate.selectedToolNames,
1564
1727
  selectedToolKeys: candidate.selectedToolKeys
1565
1728
  };
@@ -1602,6 +1765,7 @@ ${intent.plan}`,
1602
1765
  awaitingAction: false,
1603
1766
  savedPlan: void 0,
1604
1767
  activeImplementation: void 0,
1768
+ pendingImplementationRuntime: void 0,
1605
1769
  workflowToolPolicy: void 0,
1606
1770
  manualThinkingLevel: void 0
1607
1771
  };
@@ -1616,7 +1780,7 @@ ${intent.plan}`,
1616
1780
  }
1617
1781
  function restoreModeContractTracking(branch, restoredState) {
1618
1782
  publishedContractMode = latestModeContract(branch)?.mode;
1619
- modeContractsRelevant = hasModeContractArtifact(branch) || restoredState.enabled || restoredState.savedPlan !== void 0 || restoredState.activeImplementation !== void 0;
1783
+ modeContractsRelevant = hasModeContractArtifact(branch) || restoredState.enabled || restoredState.savedPlan !== void 0 || restoredState.activeImplementation !== void 0 || restoredState.pendingImplementationRuntime !== void 0;
1620
1784
  }
1621
1785
  function publishModeContract(mode, ctx) {
1622
1786
  if (publishedContractMode === mode) return true;
@@ -1721,6 +1885,7 @@ ${intent.plan}`,
1721
1885
  awaitingAction: false,
1722
1886
  savedPlan: { plan, source },
1723
1887
  activeImplementation: void 0,
1888
+ pendingImplementationRuntime: void 0,
1724
1889
  workflowToolPolicy: void 0,
1725
1890
  manualThinkingLevel: void 0
1726
1891
  };
@@ -1731,73 +1896,77 @@ ${intent.plan}`,
1731
1896
  releaseWorkflowOwner();
1732
1897
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
1733
1898
  }
1734
- async function startFreshImplementation(ctx, menuIsCurrent, preferences = settings) {
1735
- await startFreshImplementationFromState(ctx, {
1736
- preferences,
1737
- getState: () => state,
1738
- menuIsCurrent,
1739
- retention: configuredImplementationPlanRetention(settings),
1740
- stateEntryType: STATE_ENTRY_TYPE
1741
- });
1742
- }
1743
- async function startImplementation(ctx, preferences = settings, menuIsCurrent = () => true) {
1744
- if (implementationInFlight || !menuIsCurrent()) return;
1745
- if (!hasImplementationPreferences(preferences)) {
1746
- await startImplementationCore(ctx);
1899
+ async function startFreshImplementation(ctx, menuIsCurrent, runtime, timing) {
1900
+ const retention = configuredImplementationPlanRetention(settings);
1901
+ if (timing === "immediate") {
1902
+ await startFreshImplementationFromState(ctx, {
1903
+ getState: () => state,
1904
+ menuIsCurrent,
1905
+ retention,
1906
+ stateEntryType: STATE_ENTRY_TYPE,
1907
+ runtime
1908
+ });
1747
1909
  return;
1748
1910
  }
1749
- if (!allowModeTransition(ctx, "start plan implementation")) return;
1750
- if (ctx.mode === "print" || ctx.mode === "json")
1751
- throw new Error("Implementation model options require TUI or RPC mode.");
1752
- const previousState = state;
1753
- if (!(state.enabled ? state.latestPlan : state.savedPlan?.plan)) return;
1754
- const generation = menuGeneration;
1755
- const workflow = workflowGeneration;
1756
- const original = { model: ctx.model, thinking: pi.getThinkingLevel() };
1757
- const sessionCurrent = () => generation === menuGeneration && !menuController.signal.aborted;
1758
- let expectedState = state;
1759
- const current = () => sessionCurrent() && workflow === workflowGeneration && state === expectedState && menuIsCurrent() && ctx.isIdle();
1760
- const change = createImplementationPreferenceChange(
1761
- pi,
1911
+ const initialState = state;
1912
+ const savedPlan = initialState.enabled ? void 0 : initialState.savedPlan;
1913
+ const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();
1914
+ const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;
1915
+ if (!plan || !source || !menuIsCurrent()) return;
1916
+ stagedFreshImplementation = {
1762
1917
  ctx,
1763
- sessionCurrent,
1764
- original,
1765
- selectionSnapshot
1766
- );
1767
- implementationInFlight = true;
1768
- let started = false;
1769
- try {
1770
- const model = await preflightImplementationPreferences(
1771
- ctx,
1772
- preferences,
1773
- () => current() && sameModel(ctx.model, original.model) && pi.getThinkingLevel() === original.thinking
1774
- );
1775
- if (!model || !current()) return;
1776
- applyingImplementationPreferences = true;
1777
- if (state.enabled) restoreThinkingLevel();
1778
- expectedState = state;
1779
- if (!await change.apply(model, preferences, current) || !current()) return;
1780
- started = await startImplementationCore(ctx, true) === true;
1781
- } catch (error) {
1782
- if (sessionCurrent())
1783
- ctx.ui.notify(`Unable to start implementation: ${preferenceError(error)}`, "error");
1784
- } finally {
1785
- if (!started && sessionCurrent()) {
1786
- await change.rollback().catch((error) => {
1787
- if (sessionCurrent()) ctx.ui.notify(preferenceError(error), "error");
1918
+ sourceSession: ctx.sessionManager,
1919
+ menuGeneration,
1920
+ workflowGeneration,
1921
+ workflowOwner,
1922
+ enabled: initialState.enabled,
1923
+ plan,
1924
+ source,
1925
+ savedPlan,
1926
+ retention,
1927
+ runtime: runtime ? {
1928
+ ...runtime.model ? { model: { ...runtime.model } } : {},
1929
+ ...runtime.thinkingLevel ? { thinkingLevel: runtime.thinkingLevel } : {}
1930
+ } : void 0,
1931
+ menuIsCurrent
1932
+ };
1933
+ }
1934
+ function armDeferredFreshImplementation(request) {
1935
+ deferredFreshHandoff.schedule(
1936
+ async (taskIsCurrent) => {
1937
+ const isCurrent = () => taskIsCurrent() && deferredFreshImplementationIsCurrent(request);
1938
+ if (!isCurrent()) return;
1939
+ await startFreshImplementationFromState(request.ctx, {
1940
+ getState: () => state,
1941
+ menuIsCurrent: isCurrent,
1942
+ retention: request.retention,
1943
+ stateEntryType: STATE_ENTRY_TYPE,
1944
+ runtime: request.runtime
1788
1945
  });
1789
- if (sessionCurrent() && state === expectedState) {
1790
- state = previousState;
1791
- captureManualThinkingLevel();
1792
- persistState();
1793
- updateUi(ctx);
1946
+ },
1947
+ (error) => {
1948
+ if (!deferredFreshImplementationIsCurrent(request)) return;
1949
+ try {
1950
+ request.ctx.ui.notify(
1951
+ `Unable to start the deferred fresh implementation: ${terminalErrorDetail(error)}`,
1952
+ "error"
1953
+ );
1954
+ } catch {
1794
1955
  }
1795
1956
  }
1796
- applyingImplementationPreferences = false;
1797
- implementationInFlight = false;
1957
+ );
1958
+ }
1959
+ function deferredFreshImplementationIsCurrent(request) {
1960
+ if (currentSession !== request.sourceSession || menuGeneration !== request.menuGeneration || workflowGeneration !== request.workflowGeneration || workflowOwner !== request.workflowOwner || !request.menuIsCurrent() || state.enabled !== request.enabled) {
1961
+ return false;
1798
1962
  }
1963
+ return request.enabled ? workflowMutex.isOwner(request.workflowOwner) && state.latestPlan === request.plan && state.latestPlanSource === request.source : state.savedPlan === request.savedPlan;
1964
+ }
1965
+ function cancelDeferredFreshImplementation() {
1966
+ stagedFreshImplementation = void 0;
1967
+ deferredFreshHandoff.cancel();
1799
1968
  }
1800
- async function startImplementationCore(ctx, preferencesApplied = false) {
1969
+ async function startImplementation(ctx) {
1801
1970
  const savedPlan = state.enabled ? void 0 : state.savedPlan;
1802
1971
  const initialPlan = (state.enabled ? state.latestPlan : savedPlan?.plan)?.trim();
1803
1972
  if (!initialPlan) {
@@ -1805,7 +1974,7 @@ ${intent.plan}`,
1805
1974
  return;
1806
1975
  }
1807
1976
  if (!allowModeTransition(ctx, "start plan implementation")) return;
1808
- if (savedPlan && !preferencesApplied) {
1977
+ if (savedPlan) {
1809
1978
  const sessionGeneration = menuGeneration;
1810
1979
  const planWorkflowGeneration = workflowGeneration;
1811
1980
  const isCurrent = () => sessionGeneration === menuGeneration && planWorkflowGeneration === workflowGeneration && !menuController.signal.aborted && !state.enabled && state.savedPlan === savedPlan;
@@ -1831,6 +2000,7 @@ ${intent.plan}`,
1831
2000
  latestPlanSource: void 0,
1832
2001
  awaitingAction: false,
1833
2002
  savedPlan: void 0,
2003
+ pendingImplementationRuntime: void 0,
1834
2004
  activeImplementation: usesConversationHistory ? void 0 : {
1835
2005
  id: randomUUID2(),
1836
2006
  plan,
@@ -1841,7 +2011,7 @@ ${intent.plan}`,
1841
2011
  workflowToolPolicy: void 0,
1842
2012
  manualThinkingLevel: void 0
1843
2013
  };
1844
- if (wasEnabled && !preferencesApplied) {
2014
+ if (wasEnabled) {
1845
2015
  restoreThinkingLevel();
1846
2016
  state = { ...state, manualThinkingLevel: void 0 };
1847
2017
  }
@@ -1855,14 +2025,13 @@ ${intent.plan}`,
1855
2025
  if (wasEnabled) {
1856
2026
  restoreWorkflowToolPolicy(state.workflowToolPolicy);
1857
2027
  publishModeContract("plan", ctx);
1858
- if (!preferencesApplied) applyPlanThinkingLevel();
2028
+ applyPlanThinkingLevel();
1859
2029
  }
1860
2030
  persistState();
1861
2031
  updateUi(ctx);
1862
2032
  return;
1863
2033
  }
1864
2034
  if (wasEnabled) releaseWorkflowOwner();
1865
- return true;
1866
2035
  }
1867
2036
  function clearActiveImplementation(id, ctx) {
1868
2037
  if (state.activeImplementation?.id !== id) return false;
@@ -2020,6 +2189,7 @@ ${intent.plan}`,
2020
2189
  return false;
2021
2190
  }
2022
2191
  function advanceWorkflowGeneration() {
2192
+ cancelDeferredFreshImplementation();
2023
2193
  workflowGeneration += 1;
2024
2194
  pendingWorkflowToolPolicy = void 0;
2025
2195
  finalizationRequest.reset();
@@ -2173,6 +2343,174 @@ ${intent.plan}`,
2173
2343
  return [];
2174
2344
  }
2175
2345
  }
2346
+ function runtimeAdmissionIsPending(sessionManager) {
2347
+ return activeImplementationRuntimeApplication?.sessionManager === sessionManager || pendingRuntimeAdmissionSession === sessionManager || queuedRuntimeAdmissionInputs.some((queued) => queued.sessionManager === sessionManager);
2348
+ }
2349
+ function takeQueuedRuntimeAdmissionInputs(sessionManager) {
2350
+ const matching = [];
2351
+ const remaining = [];
2352
+ for (const queued of queuedRuntimeAdmissionInputs) {
2353
+ if (queued.sessionManager === sessionManager) matching.push(queued);
2354
+ else remaining.push(queued);
2355
+ }
2356
+ queuedRuntimeAdmissionInputs = remaining;
2357
+ return matching;
2358
+ }
2359
+ function removeQueuedRuntimeAdmissionInput(queuedInput) {
2360
+ const index = queuedRuntimeAdmissionInputs.indexOf(queuedInput);
2361
+ if (index >= 0) queuedRuntimeAdmissionInputs.splice(index, 1);
2362
+ }
2363
+ function runtimeAdmissionInputContent(queued) {
2364
+ return queued.images?.length ? [{ type: "text", text: queued.text }, ...queued.images] : queued.text;
2365
+ }
2366
+ function refreshStateForFirstPrompt(ctx) {
2367
+ if (!refreshStateBeforeFirstAgentStart) return;
2368
+ refreshStateBeforeFirstAgentStart = false;
2369
+ implementationRetention.reset();
2370
+ const branch = ctx.sessionManager.getBranch();
2371
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
2372
+ restoreModeContractTracking(branch, restoredState);
2373
+ if (!installRestoredState(restoredState, ctx)) return;
2374
+ implementationRetention.restore(state.activeImplementation);
2375
+ updateUi(ctx);
2376
+ }
2377
+ async function applyPendingImplementationRuntime(ctx, holdForAdmission = false) {
2378
+ const session = ctx.sessionManager;
2379
+ const activeApplication = activeImplementationRuntimeApplication;
2380
+ if (activeApplication?.sessionManager === session) {
2381
+ if (holdForAdmission) activeApplication.holdForAdmission = true;
2382
+ return activeApplication.completion;
2383
+ }
2384
+ const intent = state.enabled ? void 0 : state.pendingImplementationRuntime;
2385
+ if (!intent) return "ready";
2386
+ const generation = menuGeneration;
2387
+ const isCurrent = () => currentSession === session && generation === menuGeneration && !menuController.signal.aborted;
2388
+ const notifyCurrent2 = (message) => {
2389
+ if (!isCurrent()) return;
2390
+ try {
2391
+ ctx.ui.notify(message, "warning");
2392
+ } catch {
2393
+ }
2394
+ };
2395
+ let application;
2396
+ const completion = Promise.resolve().then(async () => {
2397
+ if (!isCurrent()) return "stale";
2398
+ const pendingState = state;
2399
+ const previousThinkingLevel = pi.getThinkingLevel();
2400
+ const applyThinking = () => {
2401
+ if (!intent.thinkingLevel) return;
2402
+ try {
2403
+ pi.setThinkingLevel(intent.thinkingLevel);
2404
+ const effectiveLevel = pi.getThinkingLevel();
2405
+ if (effectiveLevel !== intent.thinkingLevel) {
2406
+ notifyCurrent2(
2407
+ `Implementation thinking ${intent.thinkingLevel} is unsupported by the destination model; Pi is using ${effectiveLevel}.`
2408
+ );
2409
+ }
2410
+ } catch (error) {
2411
+ notifyCurrent2(
2412
+ `Implementation thinking ${intent.thinkingLevel} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default will continue.`
2413
+ );
2414
+ }
2415
+ };
2416
+ if (intent.model) {
2417
+ let model;
2418
+ let resolutionFailed = false;
2419
+ try {
2420
+ model = ctx.modelRegistry.find(intent.model.provider, intent.model.modelId);
2421
+ } catch (error) {
2422
+ notifyCurrent2(
2423
+ `Implementation model ${terminalModelReference(intent.model)} could not be resolved: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`
2424
+ );
2425
+ resolutionFailed = true;
2426
+ model = void 0;
2427
+ }
2428
+ if (!model && !resolutionFailed) {
2429
+ notifyCurrent2(
2430
+ `Implementation model ${terminalModelReference(intent.model)} is no longer available. The destination default model will continue.`
2431
+ );
2432
+ }
2433
+ if (model) {
2434
+ let authenticated = false;
2435
+ try {
2436
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
2437
+ if (!isCurrent()) return "stale";
2438
+ if (auth.ok) authenticated = true;
2439
+ else {
2440
+ notifyCurrent2(
2441
+ `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(auth.error)}. The destination default model will continue.`
2442
+ );
2443
+ }
2444
+ } catch (error) {
2445
+ notifyCurrent2(
2446
+ `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`
2447
+ );
2448
+ }
2449
+ if (!isCurrent()) return "stale";
2450
+ if (authenticated) {
2451
+ let applied = false;
2452
+ let applicationFailed = false;
2453
+ application.drainOnShutdown = true;
2454
+ try {
2455
+ try {
2456
+ applied = await pi.setModel(model);
2457
+ } catch (error) {
2458
+ applicationFailed = true;
2459
+ notifyCurrent2(
2460
+ `Implementation model ${terminalModelReference(intent.model)} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`
2461
+ );
2462
+ }
2463
+ } finally {
2464
+ application.drainOnShutdown = false;
2465
+ }
2466
+ if (!isCurrent()) return "stale";
2467
+ if (!applied && !applicationFailed) {
2468
+ notifyCurrent2(
2469
+ `Implementation model ${terminalModelReference(intent.model)} could not be applied after authentication changed. The destination default model will continue.`
2470
+ );
2471
+ }
2472
+ }
2473
+ }
2474
+ }
2475
+ if (!isCurrent()) return "stale";
2476
+ applyThinking();
2477
+ if (!isCurrent()) return "stale";
2478
+ state = { ...state, pendingImplementationRuntime: void 0 };
2479
+ try {
2480
+ persistState();
2481
+ } catch (error) {
2482
+ state = pendingState;
2483
+ try {
2484
+ if (pi.getThinkingLevel() !== previousThinkingLevel) {
2485
+ pi.setThinkingLevel(previousThinkingLevel);
2486
+ }
2487
+ } catch {
2488
+ }
2489
+ try {
2490
+ persistState();
2491
+ } catch {
2492
+ }
2493
+ notifyCurrent2(
2494
+ `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.`
2495
+ );
2496
+ return "blocked";
2497
+ }
2498
+ if (application.holdForAdmission) pendingRuntimeAdmissionSession = session;
2499
+ return "ready";
2500
+ }).finally(() => {
2501
+ if (activeImplementationRuntimeApplication === application) {
2502
+ activeImplementationRuntimeApplication = void 0;
2503
+ }
2504
+ });
2505
+ application = {
2506
+ sessionManager: session,
2507
+ completion,
2508
+ drainOnShutdown: false,
2509
+ holdForAdmission
2510
+ };
2511
+ activeImplementationRuntimeApplication = application;
2512
+ return completion;
2513
+ }
2176
2514
  function applyPlanThinkingLevel() {
2177
2515
  if (state.manualThinkingLevel) {
2178
2516
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
@@ -2366,10 +2704,19 @@ ${intent.plan}`,
2366
2704
  const safe = safeTerminalText(value) || "(unnamed tool)";
2367
2705
  return safe.length > 120 ? `${safe.slice(0, 119)}\u2026` : safe;
2368
2706
  }
2707
+ function terminalModelReference(model) {
2708
+ const safe = safeTerminalText(`${model.provider}/${model.modelId}`) || "(unnamed model)";
2709
+ return safe.length > 160 ? `${safe.slice(0, 159)}\u2026` : safe;
2710
+ }
2711
+ function terminalErrorDetail(error) {
2712
+ const safe = safeTerminalText(error instanceof Error ? error.message : String(error));
2713
+ if (!safe) return "unknown error";
2714
+ return safe.length > 500 ? `${safe.slice(0, 499)}\u2026` : safe;
2715
+ }
2369
2716
  function safeTerminalText(value) {
2370
- return [...value].map((character) => {
2717
+ return [...stripVTControlCharacters2(value)].map((character) => {
2371
2718
  const codePoint = character.codePointAt(0) ?? 0;
2372
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
2719
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 ? " " : character;
2373
2720
  }).join("").trim();
2374
2721
  }
2375
2722
  }