@narumitw/pi-plan-mode 0.57.1 → 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,16 +14,20 @@ 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
23
  createImplementationRetentionCoordinator,
21
24
  exportStoredPlan,
25
+ findAvailableImplementationModel,
22
26
  findBlockedCommandSegment,
23
27
  findBlockedPowerShellCommandSegment,
24
28
  implementationRetentionPreview,
25
29
  invalidPlanMessage,
30
+ isPendingImplementationModelIdentifier,
26
31
  latestAssistantStopReason,
27
32
  latestAssistantText,
28
33
  messageTextContent,
@@ -37,15 +42,17 @@ import {
37
42
  readCommand,
38
43
  readPlanModeSettings,
39
44
  renderPlanModeCompletion,
45
+ snapshotAvailableImplementationModels,
40
46
  snapshotPlanModeSelectedNames,
41
47
  toolPolicyLabel,
42
48
  updatePlanModeSettings
43
- } from "./chunks/chunk-57OBPS7P.js";
49
+ } from "./chunks/chunk-QHHHBTDO.js";
44
50
 
45
51
  // src/plan-mode.ts
46
52
  import { randomUUID as randomUUID2 } from "node:crypto";
47
53
  import { watch } from "node:fs";
48
54
  import { basename, dirname } from "node:path";
55
+ import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
49
56
 
50
57
  // src/command.ts
51
58
  var PLAN_COMMAND_COMPLETIONS = [
@@ -54,6 +61,7 @@ var PLAN_COMMAND_COMPLETIONS = [
54
61
  { value: "finalize", label: "finalize", description: "Request a completed plan" },
55
62
  { value: "implement", label: "implement", description: "Implement the completed or saved plan" },
56
63
  { value: "save", label: "save", description: "Save the completed plan for later" },
64
+ { value: "settings", label: "settings", description: "Open Plan mode settings" },
57
65
  { value: "export", label: "export", description: "Export the stored plan to a Markdown file" },
58
66
  { value: "exit", label: "exit", description: "Leave Plan mode or clear a saved/active plan" },
59
67
  { value: "off", label: "off", description: "Leave Plan mode or clear a saved/active plan" },
@@ -117,8 +125,45 @@ function createFinalizationRequestCoordinator() {
117
125
  };
118
126
  }
119
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
+
120
164
  // src/fresh-implementation.ts
121
165
  import { randomUUID } from "node:crypto";
166
+ import { stripVTControlCharacters } from "node:util";
122
167
 
123
168
  // src/prompt.ts
124
169
  var PLAN_CONTEXT_MARKER = "[CODEX-LIKE PLAN MODE ACTIVE]";
@@ -256,6 +301,134 @@ function unwrapMessage(message) {
256
301
  return entry?.message ?? message ?? {};
257
302
  }
258
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
+
259
432
  // src/fresh-implementation.ts
260
433
  function formatImplementationHandoff(plan) {
261
434
  return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:
@@ -297,6 +470,7 @@ async function startFreshImplementationFromState(ctx, options) {
297
470
  source,
298
471
  retention: options.retention,
299
472
  stateEntryType: options.stateEntryType,
473
+ runtime: options.runtime,
300
474
  isCurrent
301
475
  });
302
476
  }
@@ -306,20 +480,23 @@ async function startFreshImplementationSession(ctx, request) {
306
480
  }
307
481
  await ctx.waitForIdle();
308
482
  if (!request.isCurrent()) return { kind: "stale" };
309
- if (!await preflightModel(ctx, request.isCurrent)) return { kind: "rejected" };
483
+ if (!await preflightModel(ctx, request)) return { kind: "rejected" };
310
484
  if (!request.isCurrent()) return { kind: "stale" };
311
485
  const usesConversationHistory = request.retention === "clear-on-start";
312
- 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 ? {
313
495
  enabled: false,
314
496
  awaitingAction: false,
315
- activeImplementation: {
316
- id: randomUUID(),
317
- plan: request.plan,
318
- source: request.source,
319
- startedAt: Date.now(),
320
- retention: request.retention
321
- }
322
- };
497
+ ...activeImplementation ? { activeImplementation } : {},
498
+ ...pendingImplementationRuntime ? { pendingImplementationRuntime } : {}
499
+ } : void 0;
323
500
  const handoff = usesConversationHistory ? formatTransferredPlanPrompt(request.plan, true) : formatImplementationHandoff(request.plan);
324
501
  const parentSession = ctx.sessionManager.getSessionFile();
325
502
  let setupError;
@@ -350,18 +527,33 @@ async function startFreshImplementationSession(ctx, request) {
350
527
  recoverSetupFailure(replacementCtx, handoff, setupError);
351
528
  return;
352
529
  }
353
- try {
354
- await replacementCtx.sendUserMessage(handoff);
355
- } catch (error) {
356
- kickoffError = safeErrorDetail(error);
530
+ const reportKickoffFailure = (detail) => {
531
+ kickoffError = detail;
357
532
  const recoveredInEditor = usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
358
533
  safeNotify(
359
534
  replacementCtx,
360
- 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.`,
361
536
  "error"
362
537
  );
538
+ };
539
+ try {
540
+ await replacementCtx.sendUserMessage(handoff);
541
+ } catch (error) {
542
+ reportKickoffFailure(safeErrorDetail(error));
363
543
  return;
364
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
+ }
365
557
  safeNotify(
366
558
  replacementCtx,
367
559
  "Fresh implementation session started. Only the approved plan was transferred.",
@@ -383,28 +575,87 @@ async function startFreshImplementationSession(ctx, request) {
383
575
  }
384
576
  return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
385
577
  }
386
- async function preflightModel(ctx, isCurrent) {
387
- 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
+ }
388
615
  if (!model) {
389
- 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");
390
617
  return false;
391
618
  }
392
619
  let auth;
393
620
  try {
394
621
  auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
395
622
  } catch (error) {
396
- if (isCurrent()) {
397
- ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
398
- }
623
+ notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
399
624
  return false;
400
625
  }
401
- if (!isCurrent()) return false;
626
+ if (!request.isCurrent()) return false;
402
627
  if (!auth.ok) {
403
- 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
+ );
404
634
  return false;
405
635
  }
406
636
  return true;
407
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
+ }
408
659
  function recoverSetupFailure(ctx, handoff, setupError) {
409
660
  const recoveredInEditor = safeSetEditorText(ctx, handoff);
410
661
  safeNotify(
@@ -432,9 +683,9 @@ function isCommandContext(ctx) {
432
683
  }
433
684
  function safeErrorDetail(error) {
434
685
  const detail = error instanceof Error ? error.message : String(error);
435
- const normalized = [...detail].map((character) => {
686
+ const normalized = [...stripVTControlCharacters(detail)].map((character) => {
436
687
  const codePoint = character.codePointAt(0) ?? 0;
437
- 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;
438
689
  }).join("").replace(/\s+/gu, " ").trim() || "unknown error";
439
690
  const characters = [...normalized];
440
691
  return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
@@ -442,7 +693,40 @@ function safeErrorDetail(error) {
442
693
 
443
694
  // src/plan-action-controller.ts
444
695
  function createPlanActionController(options) {
445
- const freshAction = (ctx, lifecycle, signal) => options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);
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
+ };
446
730
  return {
447
731
  async showSaved(ctx) {
448
732
  const lifecycle = options.captureLifecycle();
@@ -457,7 +741,7 @@ function createPlanActionController(options) {
457
741
  isCurrent: lifecycle.isCurrent,
458
742
  show: () => options.show(ctx),
459
743
  implementHere: () => options.implementHere(ctx),
460
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
744
+ implementFresh: (signal) => freshAction(ctx, lifecycle, signal, effectiveDefaults(ctx), "immediate"),
461
745
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
462
746
  settings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),
463
747
  clear: () => options.clearSaved(ctx)
@@ -474,6 +758,8 @@ function createPlanActionController(options) {
474
758
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
475
759
  await ui.showPlanModeMenu(ctx, {
476
760
  statusText: options.statusText(),
761
+ planThinkingLevel: options.getThinkingLevel(),
762
+ implementationDefaults: configuredDefaults(),
477
763
  hasReadyPlan: options.getState().latestPlan !== void 0,
478
764
  implementationOutcome: options.implementationOutcome,
479
765
  getExportDestination: () => options.getExportDestination(ctx),
@@ -481,7 +767,7 @@ function createPlanActionController(options) {
481
767
  show: () => options.show(ctx),
482
768
  finalize: () => options.finalize(ctx),
483
769
  implementHere: () => options.implementHere(ctx),
484
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
770
+ implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, "immediate"),
485
771
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
486
772
  save: () => options.save(ctx),
487
773
  stay: () => options.stay(ctx),
@@ -495,10 +781,12 @@ function createPlanActionController(options) {
495
781
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
496
782
  await ui.showReadyPlanMenu(ctx, {
497
783
  ...lifecycle,
784
+ planThinkingLevel: options.getThinkingLevel(),
785
+ implementationDefaults: configuredDefaults(),
498
786
  implementationOutcome: options.implementationOutcome,
499
787
  getExportDestination: () => options.getExportDestination(ctx),
500
788
  implementHere: () => options.implementHere(ctx),
501
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
789
+ implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, "after-settled"),
502
790
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
503
791
  save: () => options.save(ctx),
504
792
  stay: () => void 0,
@@ -697,106 +985,6 @@ async function preflightSavedPlanImplementation(ctx, isCurrent) {
697
985
  return true;
698
986
  }
699
987
 
700
- // src/state.ts
701
- function restorePlanModeState(entries, stateEntryType) {
702
- const branch = entries;
703
- let stateEntryIndex = -1;
704
- for (let index = branch.length - 1; index >= 0; index -= 1) {
705
- const candidate = branch[index];
706
- if (candidate?.type === "custom" && candidate.customType === stateEntryType) {
707
- stateEntryIndex = index;
708
- break;
709
- }
710
- }
711
- const entry = branch[stateEntryIndex];
712
- if (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };
713
- const enabled = entry.data.enabled === true;
714
- const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : void 0;
715
- const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : void 0;
716
- const recoveredPlan = enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : void 0;
717
- const latestPlan = persistedPlan ?? recoveredPlan;
718
- const activeImplementation = enabled ? void 0 : normalizeActiveImplementation(entry.data.activeImplementation);
719
- const savedPlan = enabled || activeImplementation ? void 0 : normalizeSavedPlan(entry.data.savedPlan);
720
- return {
721
- enabled,
722
- latestPlan,
723
- latestPlanSource: enabled ? (persistedPlan ? persistedSource : void 0) ?? (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : void 0) : void 0,
724
- awaitingAction: enabled && latestPlan !== void 0,
725
- savedPlan,
726
- activeImplementation,
727
- selectedToolNames: stringArray(entry.data.selectedToolNames),
728
- selectedToolKeys: stringArray(entry.data.selectedToolKeys),
729
- workflowToolPolicy: enabled ? normalizeWorkflowToolPolicy(entry.data.workflowToolPolicy) : void 0,
730
- previousThinkingLevel: enabled ? fixedThinkingLevel(entry.data.previousThinkingLevel) : void 0,
731
- appliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : void 0,
732
- manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : void 0
733
- };
734
- }
735
- function normalizeWorkflowToolPolicy(value) {
736
- if (value === void 0) return void 0;
737
- const denied = {
738
- kind: "automatic",
739
- allowedNames: [],
740
- resolved: true
741
- };
742
- if (!isRecord(value)) return denied;
743
- const kind = value.kind === "automatic" || value.kind === "explicit" ? value.kind : void 0;
744
- const allowedNames = stringArray(value.allowedNames);
745
- if (!kind || !allowedNames || typeof value.resolved !== "boolean") return denied;
746
- if (kind === "automatic") {
747
- return { kind, allowedNames, resolved: value.resolved };
748
- }
749
- const desiredNames = stringArray(value.desiredNames);
750
- if (!desiredNames) return denied;
751
- return { kind, desiredNames, allowedNames, resolved: value.resolved };
752
- }
753
- function normalizeSavedPlan(value) {
754
- if (!isRecord(value)) return void 0;
755
- const source = planCompletionSource(value.source);
756
- const normalized = normalizePlanModeCompletion({ plan: value.plan });
757
- if (!source || !normalized.ok) return void 0;
758
- return { plan: normalized.plan, source };
759
- }
760
- function normalizeActiveImplementation(value) {
761
- if (!isRecord(value)) return void 0;
762
- const id = typeof value.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id) ? value.id : void 0;
763
- const source = planCompletionSource(value.source);
764
- const normalized = normalizePlanModeCompletion({ plan: value.plan });
765
- const startedAt = typeof value.startedAt === "number" && Number.isSafeInteger(value.startedAt) && value.startedAt >= 0 ? value.startedAt : void 0;
766
- if (!id || !source || !normalized.ok || startedAt === void 0) return void 0;
767
- const retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(
768
- value.retention
769
- ) ? value.retention : "keep";
770
- return { id, plan: normalized.plan, source, startedAt, retention };
771
- }
772
- function normalizePersistedPlan(value) {
773
- const normalized = normalizePlanModeCompletion({ plan: value });
774
- return normalized.ok ? normalized.plan : void 0;
775
- }
776
- function latestCompletionPlan(entries) {
777
- for (let index = entries.length - 1; index >= 0; index -= 1) {
778
- const message = entries[index]?.message;
779
- if (message?.role !== "toolResult" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {
780
- continue;
781
- }
782
- const plan = planFromCompletionDetails(message.details);
783
- if (plan) return plan;
784
- }
785
- return void 0;
786
- }
787
- function planCompletionSource(value) {
788
- return value === PLAN_MODE_COMPLETE_TOOL_NAME || value === "legacy_proposed_plan" ? value : void 0;
789
- }
790
- function fixedThinkingLevel(value) {
791
- return typeof value === "string" && value !== "inherit" && PLAN_MODE_THINKING_LEVELS.includes(value) ? value : void 0;
792
- }
793
- function stringArray(value) {
794
- return Array.isArray(value) && value.every((item) => typeof item === "string") ? Array.from(new Set(value)) : void 0;
795
- }
796
- function isRecord(value) {
797
- return typeof value === "object" && value !== null && !Array.isArray(value);
798
- }
799
-
800
988
  // src/workflow-mutex.ts
801
989
  var WORKFLOW_MUTEX_CHANNEL = "workflow:mutex:v1";
802
990
  var AGENT_WORKFLOW_GROUP = "agent-workflow";
@@ -863,6 +1051,7 @@ var WorkflowMutex = class {
863
1051
  // src/plan-mode.ts
864
1052
  var STATE_ENTRY_TYPE = "plan-mode-state";
865
1053
  var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
1054
+ var RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE = "plan-mode-recovered-input";
866
1055
  var BLOCKED_MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "update_plan"]);
867
1056
  var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
868
1057
  function planMode(pi, dependencies = {}) {
@@ -874,7 +1063,7 @@ function planMode(pi, dependencies = {}) {
874
1063
  const loadInteractiveUi = () => {
875
1064
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
876
1065
  if (!interactiveUiPromise) {
877
- interactiveUiPromise = import("./chunks/interactive-ui-N2ZKBVNE.js").catch((error) => {
1066
+ interactiveUiPromise = import("./chunks/interactive-ui-UNJGC2RQ.js").catch((error) => {
878
1067
  interactiveUiPromise = void 0;
879
1068
  throw error;
880
1069
  });
@@ -893,10 +1082,15 @@ function planMode(pi, dependencies = {}) {
893
1082
  let modeContractsRelevant = false;
894
1083
  let readyPresentationIntent;
895
1084
  let latestCommandContext;
1085
+ let stagedFreshImplementation;
1086
+ const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();
896
1087
  let nextReadyPresentationNonce = 0;
897
1088
  let menuGeneration = 0;
898
1089
  let workflowGeneration = 0;
899
1090
  let refreshStateBeforeFirstAgentStart = false;
1091
+ let activeImplementationRuntimeApplication;
1092
+ let pendingRuntimeAdmissionSession;
1093
+ let queuedRuntimeAdmissionInputs = [];
900
1094
  let menuController = new AbortController();
901
1095
  let settingsWatch;
902
1096
  let settingsReloadTimer;
@@ -915,6 +1109,10 @@ function planMode(pi, dependencies = {}) {
915
1109
  getState: () => state,
916
1110
  captureLifecycle: captureMenuLifecycle,
917
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,
918
1116
  implementationOutcome,
919
1117
  getExportDestination: (ctx) => planExports.getDestination(ctx),
920
1118
  show: (ctx) => showStoredPlan(pi, ctx, state),
@@ -1026,6 +1224,14 @@ function planMode(pi, dependencies = {}) {
1026
1224
  savePlanForLater(ctx);
1027
1225
  return;
1028
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
+ }
1029
1235
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
1030
1236
  if (exportMatch) {
1031
1237
  const lifecycle = captureMenuLifecycle();
@@ -1155,6 +1361,7 @@ function planMode(pi, dependencies = {}) {
1155
1361
  }
1156
1362
  };
1157
1363
  pi.on("session_start", async (event, ctx) => {
1364
+ cancelDeferredFreshImplementation();
1158
1365
  const generation = ++menuGeneration;
1159
1366
  finalizationRequest.reset();
1160
1367
  currentSession = ctx.sessionManager;
@@ -1162,6 +1369,8 @@ function planMode(pi, dependencies = {}) {
1162
1369
  workflowOwner = void 0;
1163
1370
  workflowMutex.bindSession(ctx.sessionManager);
1164
1371
  refreshStateBeforeFirstAgentStart = event.reason === "new";
1372
+ pendingRuntimeAdmissionSession = void 0;
1373
+ queuedRuntimeAdmissionInputs = [];
1165
1374
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
1166
1375
  menuController = new AbortController();
1167
1376
  readyPresentationIntent = void 0;
@@ -1180,8 +1389,18 @@ function planMode(pi, dependencies = {}) {
1180
1389
  if (!installRestoredState(restoredState, ctx)) return;
1181
1390
  implementationRetention.restore(state.activeImplementation);
1182
1391
  updateUi(ctx);
1392
+ if (event.reason !== "new") await applyPendingImplementationRuntime(ctx);
1183
1393
  });
1184
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
+ }
1185
1404
  const target = ctx.sessionManager.getEntry(event.preparation.targetId);
1186
1405
  if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
1187
1406
  return;
@@ -1194,13 +1413,16 @@ function planMode(pi, dependencies = {}) {
1194
1413
  }
1195
1414
  return { cancel: true };
1196
1415
  });
1197
- pi.on("session_tree", (_event, ctx) => {
1416
+ pi.on("session_tree", async (_event, ctx) => {
1417
+ cancelDeferredFreshImplementation();
1198
1418
  advanceWorkflowGeneration();
1199
1419
  menuGeneration += 1;
1200
1420
  menuController.abort(new DOMException("Plan-mode tree branch changed", "AbortError"));
1201
1421
  menuController = new AbortController();
1202
1422
  readyPresentationIntent = void 0;
1203
1423
  latestCommandContext = void 0;
1424
+ pendingRuntimeAdmissionSession = void 0;
1425
+ queuedRuntimeAdmissionInputs = [];
1204
1426
  implementationRetention.reset();
1205
1427
  const branch = ctx.sessionManager.getBranch();
1206
1428
  const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
@@ -1209,6 +1431,7 @@ function planMode(pi, dependencies = {}) {
1209
1431
  implementationRetention.restore(state.activeImplementation);
1210
1432
  startPlanModeSettingsWatch(menuGeneration);
1211
1433
  updateUi(ctx);
1434
+ await applyPendingImplementationRuntime(ctx);
1212
1435
  });
1213
1436
  pi.on("thinking_level_select", (event) => {
1214
1437
  if (!state.enabled || !state.appliedThinkingLevel) return;
@@ -1223,16 +1446,37 @@ function planMode(pi, dependencies = {}) {
1223
1446
  }
1224
1447
  });
1225
1448
  pi.on("session_shutdown", async (_event, ctx) => {
1449
+ cancelDeferredFreshImplementation();
1226
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
+ }
1227
1464
  finalizationRequest.reset();
1228
1465
  menuGeneration += 1;
1229
1466
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
1230
1467
  readyPresentationIntent = void 0;
1231
1468
  latestCommandContext = void 0;
1232
1469
  refreshStateBeforeFirstAgentStart = false;
1470
+ pendingRuntimeAdmissionSession = void 0;
1471
+ queuedRuntimeAdmissionInputs = [];
1233
1472
  workflowAllowedToolNames = void 0;
1234
1473
  pendingWorkflowToolPolicy = void 0;
1235
1474
  implementationRetention.reset();
1475
+ if (runtimeApplication) await runtimeApplication.completion;
1476
+ if (currentSession !== void 0 && currentSession !== shutdownSession) {
1477
+ workflowMutex.unbindSession(shutdownSession);
1478
+ return;
1479
+ }
1236
1480
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
1237
1481
  if (currentSession !== void 0 && currentSession !== shutdownSession) {
1238
1482
  workflowMutex.unbindSession(shutdownSession);
@@ -1342,19 +1586,41 @@ Blocked command: ${blocked}`
1342
1586
  const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
1343
1587
  return { messages };
1344
1588
  });
1345
- pi.on("before_agent_start", (_event, ctx) => {
1346
- if (refreshStateBeforeFirstAgentStart) {
1347
- refreshStateBeforeFirstAgentStart = false;
1348
- implementationRetention.reset();
1349
- const branch = ctx.sessionManager.getBranch();
1350
- const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
1351
- restoreModeContractTracking(branch, restoredState);
1352
- if (!installRestoredState(restoredState, ctx)) return;
1353
- implementationRetention.restore(state.activeImplementation);
1354
- 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
+ });
1355
1617
  }
1618
+ });
1619
+ pi.on("before_agent_start", (_event, ctx) => {
1620
+ refreshStateForFirstPrompt(ctx);
1356
1621
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1357
1622
  if (state.latestPlan || state.awaitingAction) {
1623
+ cancelDeferredFreshImplementation();
1358
1624
  readyPresentationIntent = void 0;
1359
1625
  state = {
1360
1626
  ...state,
@@ -1404,6 +1670,7 @@ Blocked command: ${blocked}`
1404
1670
  if (!intent || !readyPresentationIsCurrent(intent)) return;
1405
1671
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
1406
1672
  readyPresentationIntent = void 0;
1673
+ stagedFreshImplementation = void 0;
1407
1674
  try {
1408
1675
  if (intent.source === "legacy_proposed_plan") {
1409
1676
  pi.sendMessage(
@@ -1420,7 +1687,11 @@ ${intent.plan}`,
1420
1687
  if (ctx.hasUI && completedPlanIsCurrent(intent)) {
1421
1688
  await planActions.showReady(latestCommandContext ?? ctx);
1422
1689
  }
1690
+ const request = stagedFreshImplementation;
1691
+ stagedFreshImplementation = void 0;
1692
+ if (request) armDeferredFreshImplementation(request);
1423
1693
  } catch (error) {
1694
+ stagedFreshImplementation = void 0;
1424
1695
  if (!isStaleExtensionContextError(error)) throw error;
1425
1696
  }
1426
1697
  });
@@ -1451,6 +1722,7 @@ ${intent.plan}`,
1451
1722
  awaitingAction: false,
1452
1723
  savedPlan: void 0,
1453
1724
  activeImplementation: void 0,
1725
+ pendingImplementationRuntime: void 0,
1454
1726
  selectedToolNames: candidate.selectedToolNames,
1455
1727
  selectedToolKeys: candidate.selectedToolKeys
1456
1728
  };
@@ -1493,6 +1765,7 @@ ${intent.plan}`,
1493
1765
  awaitingAction: false,
1494
1766
  savedPlan: void 0,
1495
1767
  activeImplementation: void 0,
1768
+ pendingImplementationRuntime: void 0,
1496
1769
  workflowToolPolicy: void 0,
1497
1770
  manualThinkingLevel: void 0
1498
1771
  };
@@ -1507,7 +1780,7 @@ ${intent.plan}`,
1507
1780
  }
1508
1781
  function restoreModeContractTracking(branch, restoredState) {
1509
1782
  publishedContractMode = latestModeContract(branch)?.mode;
1510
- 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;
1511
1784
  }
1512
1785
  function publishModeContract(mode, ctx) {
1513
1786
  if (publishedContractMode === mode) return true;
@@ -1612,6 +1885,7 @@ ${intent.plan}`,
1612
1885
  awaitingAction: false,
1613
1886
  savedPlan: { plan, source },
1614
1887
  activeImplementation: void 0,
1888
+ pendingImplementationRuntime: void 0,
1615
1889
  workflowToolPolicy: void 0,
1616
1890
  manualThinkingLevel: void 0
1617
1891
  };
@@ -1622,13 +1896,75 @@ ${intent.plan}`,
1622
1896
  releaseWorkflowOwner();
1623
1897
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
1624
1898
  }
1625
- async function startFreshImplementation(ctx, menuIsCurrent) {
1626
- await startFreshImplementationFromState(ctx, {
1627
- getState: () => state,
1628
- menuIsCurrent,
1629
- retention: configuredImplementationPlanRetention(settings),
1630
- stateEntryType: STATE_ENTRY_TYPE
1631
- });
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
+ });
1909
+ return;
1910
+ }
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 = {
1917
+ ctx,
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
1945
+ });
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 {
1955
+ }
1956
+ }
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;
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();
1632
1968
  }
1633
1969
  async function startImplementation(ctx) {
1634
1970
  const savedPlan = state.enabled ? void 0 : state.savedPlan;
@@ -1664,6 +2000,7 @@ ${intent.plan}`,
1664
2000
  latestPlanSource: void 0,
1665
2001
  awaitingAction: false,
1666
2002
  savedPlan: void 0,
2003
+ pendingImplementationRuntime: void 0,
1667
2004
  activeImplementation: usesConversationHistory ? void 0 : {
1668
2005
  id: randomUUID2(),
1669
2006
  plan,
@@ -1852,6 +2189,7 @@ ${intent.plan}`,
1852
2189
  return false;
1853
2190
  }
1854
2191
  function advanceWorkflowGeneration() {
2192
+ cancelDeferredFreshImplementation();
1855
2193
  workflowGeneration += 1;
1856
2194
  pendingWorkflowToolPolicy = void 0;
1857
2195
  finalizationRequest.reset();
@@ -2005,6 +2343,174 @@ ${intent.plan}`,
2005
2343
  return [];
2006
2344
  }
2007
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
+ }
2008
2514
  function applyPlanThinkingLevel() {
2009
2515
  if (state.manualThinkingLevel) {
2010
2516
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
@@ -2198,10 +2704,19 @@ ${intent.plan}`,
2198
2704
  const safe = safeTerminalText(value) || "(unnamed tool)";
2199
2705
  return safe.length > 120 ? `${safe.slice(0, 119)}\u2026` : safe;
2200
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
+ }
2201
2716
  function safeTerminalText(value) {
2202
- return [...value].map((character) => {
2717
+ return [...stripVTControlCharacters2(value)].map((character) => {
2203
2718
  const codePoint = character.codePointAt(0) ?? 0;
2204
- 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;
2205
2720
  }).join("").trim();
2206
2721
  }
2207
2722
  }