@narumitw/pi-plan-mode 0.57.1 → 0.58.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +68 -4
  2. package/dist/chunks/{chunk-57OBPS7P.js → chunk-HF7ZEYIC.js} +169 -164
  3. package/dist/chunks/chunk-HF7ZEYIC.js.map +7 -0
  4. package/dist/chunks/{interactive-ui-N2ZKBVNE.js → interactive-ui-UK7IGPOE.js} +312 -32
  5. package/dist/chunks/interactive-ui-UK7IGPOE.js.map +7 -0
  6. package/dist/index.ts +670 -212
  7. package/dist/index.ts.map +4 -4
  8. package/docs/settings.md +26 -2
  9. package/package.json +50 -51
  10. package/src/active-implementation-menu.ts +57 -60
  11. package/src/command.ts +22 -21
  12. package/src/completion-tool.ts +53 -56
  13. package/src/extension-runtime.ts +5 -5
  14. package/src/finalization-request.ts +40 -44
  15. package/src/fresh-handoff-coordinator.ts +52 -0
  16. package/src/fresh-implementation.ts +312 -205
  17. package/src/implementation-models.ts +43 -0
  18. package/src/implementation-retention.ts +109 -123
  19. package/src/message-transform.ts +218 -252
  20. package/src/mode-contract.ts +46 -49
  21. package/src/plan-action-controller.ts +139 -89
  22. package/src/plan-action-menus.ts +414 -177
  23. package/src/plan-export-controller.ts +23 -28
  24. package/src/plan-export-screen.ts +13 -13
  25. package/src/plan-export.ts +85 -102
  26. package/src/plan-launch-menu.ts +119 -119
  27. package/src/plan-mode.ts +2027 -1675
  28. package/src/presentation.ts +84 -108
  29. package/src/prompt.ts +1 -1
  30. package/src/question-tool.ts +239 -267
  31. package/src/required-tools.ts +15 -19
  32. package/src/saved-plan-menu.ts +82 -84
  33. package/src/saved-plan-preflight.ts +29 -33
  34. package/src/settings-menu.ts +489 -377
  35. package/src/settings.ts +403 -382
  36. package/src/state.ts +177 -146
  37. package/src/tool-policy.ts +634 -699
  38. package/src/tool-selection.ts +39 -44
  39. package/src/workflow-mutex.ts +66 -66
  40. package/dist/chunks/chunk-57OBPS7P.js.map +0 -7
  41. package/dist/chunks/interactive-ui-N2ZKBVNE.js.map +0 -7
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-HF7ZEYIC.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]";
@@ -214,9 +259,7 @@ function modeContractFromMessage(message) {
214
259
  return void 0;
215
260
  }
216
261
  function hasModeContractArtifact(messages) {
217
- return messages.some(
218
- (message) => unwrapMessage(message).customType === MODE_CONTRACT_MESSAGE_TYPE
219
- );
262
+ return messages.some((message) => unwrapMessage(message).customType === MODE_CONTRACT_MESSAGE_TYPE);
220
263
  }
221
264
  function latestModeContract(messages) {
222
265
  for (let index = messages.length - 1; index >= 0; index -= 1) {
@@ -243,7 +286,7 @@ function findLatestContractArtifactIndex(messages) {
243
286
  return -1;
244
287
  }
245
288
  function leadingSummaryBoundary(messages) {
246
- let index = 0;
289
+ let index = unwrapMessage(messages[0]).role === "system" ? 1 : 0;
247
290
  while (index < messages.length) {
248
291
  const role = unwrapMessage(messages[index]).role;
249
292
  if (role !== "compactionSummary" && role !== "branchSummary") break;
@@ -256,6 +299,130 @@ function unwrapMessage(message) {
256
299
  return entry?.message ?? message ?? {};
257
300
  }
258
301
 
302
+ // src/state.ts
303
+ function restorePlanModeState(entries, stateEntryType) {
304
+ const branch = entries;
305
+ let stateEntryIndex = -1;
306
+ for (let index = branch.length - 1; index >= 0; index -= 1) {
307
+ const candidate = branch[index];
308
+ if (candidate?.type === "custom" && candidate.customType === stateEntryType) {
309
+ stateEntryIndex = index;
310
+ break;
311
+ }
312
+ }
313
+ const entry = branch[stateEntryIndex];
314
+ if (!isRecord(entry?.data)) return { enabled: false, awaitingAction: false };
315
+ const enabled = entry.data.enabled === true;
316
+ const persistedSource = enabled ? planCompletionSource(entry.data.latestPlanSource) : void 0;
317
+ const persistedPlan = enabled ? normalizePersistedPlan(entry.data.latestPlan) : void 0;
318
+ const recoveredPlan = enabled && !persistedPlan ? latestCompletionPlan(branch.slice(stateEntryIndex + 1)) : void 0;
319
+ const latestPlan = persistedPlan ?? recoveredPlan;
320
+ const activeImplementation = enabled ? void 0 : normalizeActiveImplementation(entry.data.activeImplementation);
321
+ const savedPlan = enabled || activeImplementation ? void 0 : normalizeSavedPlan(entry.data.savedPlan);
322
+ const pendingImplementationRuntime = enabled ? void 0 : normalizePendingImplementationRuntime(entry.data.pendingImplementationRuntime);
323
+ return {
324
+ enabled,
325
+ latestPlan,
326
+ latestPlanSource: enabled ? (persistedPlan ? persistedSource : void 0) ?? (recoveredPlan ? PLAN_MODE_COMPLETE_TOOL_NAME : void 0) : void 0,
327
+ awaitingAction: enabled && latestPlan !== void 0,
328
+ savedPlan,
329
+ activeImplementation,
330
+ pendingImplementationRuntime,
331
+ selectedToolNames: stringArray(entry.data.selectedToolNames),
332
+ selectedToolKeys: stringArray(entry.data.selectedToolKeys),
333
+ workflowToolPolicy: enabled ? normalizeWorkflowToolPolicy(entry.data.workflowToolPolicy) : void 0,
334
+ previousThinkingLevel: enabled ? fixedThinkingLevel(entry.data.previousThinkingLevel) : void 0,
335
+ appliedThinkingLevel: enabled ? fixedThinkingLevel(entry.data.appliedThinkingLevel) : void 0,
336
+ manualThinkingLevel: enabled ? fixedThinkingLevel(entry.data.manualThinkingLevel) : void 0
337
+ };
338
+ }
339
+ function normalizeWorkflowToolPolicy(value) {
340
+ if (value === void 0) return void 0;
341
+ const denied = {
342
+ kind: "automatic",
343
+ allowedNames: [],
344
+ resolved: true
345
+ };
346
+ if (!isRecord(value)) return denied;
347
+ const kind = value.kind === "automatic" || value.kind === "explicit" ? value.kind : void 0;
348
+ const allowedNames = stringArray(value.allowedNames);
349
+ if (!kind || !allowedNames || typeof value.resolved !== "boolean") return denied;
350
+ if (kind === "automatic") {
351
+ return { kind, allowedNames, resolved: value.resolved };
352
+ }
353
+ const desiredNames = stringArray(value.desiredNames);
354
+ if (!desiredNames) return denied;
355
+ return { kind, desiredNames, allowedNames, resolved: value.resolved };
356
+ }
357
+ function normalizeSavedPlan(value) {
358
+ if (!isRecord(value)) return void 0;
359
+ const source = planCompletionSource(value.source);
360
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
361
+ if (!source || !normalized.ok) return void 0;
362
+ return { plan: normalized.plan, source };
363
+ }
364
+ function normalizePendingImplementationRuntime(value) {
365
+ if (!isRecord(value) || value.version !== 1) return void 0;
366
+ if (Object.keys(value).some((key) => key !== "version" && key !== "model" && key !== "thinkingLevel")) {
367
+ return void 0;
368
+ }
369
+ let model;
370
+ if (value.model !== void 0) {
371
+ if (!isRecord(value.model) || Object.keys(value.model).some((key) => key !== "provider" && key !== "modelId")) {
372
+ return void 0;
373
+ }
374
+ if (!isPendingImplementationModelIdentifier(value.model.provider) || !isPendingImplementationModelIdentifier(value.model.modelId)) {
375
+ return void 0;
376
+ }
377
+ model = { provider: value.model.provider, modelId: value.model.modelId };
378
+ }
379
+ const thinkingLevel = value.thinkingLevel === void 0 ? void 0 : fixedThinkingLevel(value.thinkingLevel);
380
+ if (value.thinkingLevel !== void 0 && !thinkingLevel) return void 0;
381
+ if (!model && !thinkingLevel) return void 0;
382
+ return {
383
+ version: 1,
384
+ ...model ? { model } : {},
385
+ ...thinkingLevel ? { thinkingLevel } : {}
386
+ };
387
+ }
388
+ function normalizeActiveImplementation(value) {
389
+ if (!isRecord(value)) return void 0;
390
+ const id = typeof value.id === "string" && /^[A-Za-z0-9._:-]{1,128}$/u.test(value.id) ? value.id : void 0;
391
+ const source = planCompletionSource(value.source);
392
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
393
+ const startedAt = typeof value.startedAt === "number" && Number.isSafeInteger(value.startedAt) && value.startedAt >= 0 ? value.startedAt : void 0;
394
+ if (!id || !source || !normalized.ok || startedAt === void 0) return void 0;
395
+ const retention = IMPLEMENTATION_PLAN_RETENTIONS.includes(value.retention) ? value.retention : "keep";
396
+ return { id, plan: normalized.plan, source, startedAt, retention };
397
+ }
398
+ function normalizePersistedPlan(value) {
399
+ const normalized = normalizePlanModeCompletion({ plan: value });
400
+ return normalized.ok ? normalized.plan : void 0;
401
+ }
402
+ function latestCompletionPlan(entries) {
403
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
404
+ const message = entries[index]?.message;
405
+ if (message?.role !== "toolResult" || message.toolName !== PLAN_MODE_COMPLETE_TOOL_NAME) {
406
+ continue;
407
+ }
408
+ const plan = planFromCompletionDetails(message.details);
409
+ if (plan) return plan;
410
+ }
411
+ return void 0;
412
+ }
413
+ function planCompletionSource(value) {
414
+ return value === PLAN_MODE_COMPLETE_TOOL_NAME || value === "legacy_proposed_plan" ? value : void 0;
415
+ }
416
+ function fixedThinkingLevel(value) {
417
+ return typeof value === "string" && value !== "inherit" && PLAN_MODE_THINKING_LEVELS.includes(value) ? value : void 0;
418
+ }
419
+ function stringArray(value) {
420
+ return Array.isArray(value) && value.every((item) => typeof item === "string") ? Array.from(new Set(value)) : void 0;
421
+ }
422
+ function isRecord(value) {
423
+ return typeof value === "object" && value !== null && !Array.isArray(value);
424
+ }
425
+
259
426
  // src/fresh-implementation.ts
260
427
  function formatImplementationHandoff(plan) {
261
428
  return `Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:
@@ -297,6 +464,7 @@ async function startFreshImplementationFromState(ctx, options) {
297
464
  source,
298
465
  retention: options.retention,
299
466
  stateEntryType: options.stateEntryType,
467
+ runtime: options.runtime,
300
468
  isCurrent
301
469
  });
302
470
  }
@@ -306,20 +474,23 @@ async function startFreshImplementationSession(ctx, request) {
306
474
  }
307
475
  await ctx.waitForIdle();
308
476
  if (!request.isCurrent()) return { kind: "stale" };
309
- if (!await preflightModel(ctx, request.isCurrent)) return { kind: "rejected" };
477
+ if (!await preflightModel(ctx, request)) return { kind: "rejected" };
310
478
  if (!request.isCurrent()) return { kind: "stale" };
311
479
  const usesConversationHistory = request.retention === "clear-on-start";
312
- const destinationState = usesConversationHistory ? void 0 : {
480
+ const pendingImplementationRuntime = pendingRuntimeIntent(request.runtime);
481
+ const activeImplementation = usesConversationHistory ? void 0 : {
482
+ id: randomUUID(),
483
+ plan: request.plan,
484
+ source: request.source,
485
+ startedAt: Date.now(),
486
+ retention: request.retention
487
+ };
488
+ const destinationState = activeImplementation || pendingImplementationRuntime ? {
313
489
  enabled: false,
314
490
  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
- };
491
+ ...activeImplementation ? { activeImplementation } : {},
492
+ ...pendingImplementationRuntime ? { pendingImplementationRuntime } : {}
493
+ } : void 0;
323
494
  const handoff = usesConversationHistory ? formatTransferredPlanPrompt(request.plan, true) : formatImplementationHandoff(request.plan);
324
495
  const parentSession = ctx.sessionManager.getSessionFile();
325
496
  let setupError;
@@ -350,18 +521,30 @@ async function startFreshImplementationSession(ctx, request) {
350
521
  recoverSetupFailure(replacementCtx, handoff, setupError);
351
522
  return;
352
523
  }
353
- try {
354
- await replacementCtx.sendUserMessage(handoff);
355
- } catch (error) {
356
- kickoffError = safeErrorDetail(error);
524
+ const reportKickoffFailure = (detail) => {
525
+ kickoffError = detail;
357
526
  const recoveredInEditor = usesConversationHistory && safeSetEditorText(replacementCtx, handoff);
358
527
  safeNotify(
359
528
  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.`,
529
+ 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
530
  "error"
362
531
  );
532
+ };
533
+ try {
534
+ await replacementCtx.sendUserMessage(handoff);
535
+ } catch (error) {
536
+ reportKickoffFailure(safeErrorDetail(error));
363
537
  return;
364
538
  }
539
+ if (pendingImplementationRuntime) {
540
+ const runtimeStatus = destinationRuntimeConsumptionStatus(replacementCtx, request.stateEntryType);
541
+ if (runtimeStatus !== "consumed") {
542
+ reportKickoffFailure(
543
+ runtimeStatus === "pending" ? "fresh implementation settings could not be consumed" : "fresh implementation settings could not be verified as consumed"
544
+ );
545
+ return;
546
+ }
547
+ }
365
548
  safeNotify(
366
549
  replacementCtx,
367
550
  "Fresh implementation session started. Only the approved plan was transferred.",
@@ -383,28 +566,82 @@ async function startFreshImplementationSession(ctx, request) {
383
566
  }
384
567
  return setupError || kickoffError ? { kind: "partial" } : { kind: "started" };
385
568
  }
386
- async function preflightModel(ctx, isCurrent) {
387
- const model = ctx.model;
569
+ async function preflightModel(ctx, request) {
570
+ const requestedModel = request.runtime?.model;
571
+ let model = ctx.model;
572
+ if (requestedModel) {
573
+ if (!isPendingImplementationModelIdentifier(requestedModel.provider) || !isPendingImplementationModelIdentifier(requestedModel.modelId)) {
574
+ notifyCurrent(
575
+ ctx,
576
+ request,
577
+ `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.`,
578
+ "warning"
579
+ );
580
+ return false;
581
+ }
582
+ const isCurrentModel = ctx.model?.provider === requestedModel.provider && ctx.model.id === requestedModel.modelId;
583
+ if (!isCurrentModel) {
584
+ try {
585
+ model = ctx.modelRegistry.find(requestedModel.provider, requestedModel.modelId);
586
+ } catch (error) {
587
+ notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
588
+ return false;
589
+ }
590
+ }
591
+ if (!model) {
592
+ notifyCurrent(
593
+ ctx,
594
+ request,
595
+ `Unable to implement the plan: implementation model ${safeModelReference(requestedModel)} is no longer available. Choose another model and retry.`,
596
+ "warning"
597
+ );
598
+ return false;
599
+ }
600
+ }
388
601
  if (!model) {
389
- ctx.ui.notify("Unable to implement the plan: no model is selected.", "warning");
602
+ notifyCurrent(ctx, request, "Unable to implement the plan: no model is selected.", "warning");
390
603
  return false;
391
604
  }
392
605
  let auth;
393
606
  try {
394
607
  auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
395
608
  } catch (error) {
396
- if (isCurrent()) {
397
- ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
398
- }
609
+ notifyCurrent(ctx, request, `Unable to implement the plan: ${safeErrorDetail(error)}`, "error");
399
610
  return false;
400
611
  }
401
- if (!isCurrent()) return false;
612
+ if (!request.isCurrent()) return false;
402
613
  if (!auth.ok) {
403
- ctx.ui.notify(`Unable to implement the plan: ${safeErrorDetail(auth.error)}`, "warning");
614
+ notifyCurrent(
615
+ ctx,
616
+ request,
617
+ 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)}`,
618
+ "warning"
619
+ );
404
620
  return false;
405
621
  }
406
622
  return true;
407
623
  }
624
+ function notifyCurrent(ctx, request, message, level) {
625
+ if (request.isCurrent()) safeNotify(ctx, message, level);
626
+ }
627
+ function pendingRuntimeIntent(selection) {
628
+ if (!selection?.model && !selection?.thinkingLevel) return void 0;
629
+ return {
630
+ version: 1,
631
+ ...selection.model ? { model: { provider: selection.model.provider, modelId: selection.model.modelId } } : {},
632
+ ...selection.thinkingLevel ? { thinkingLevel: selection.thinkingLevel } : {}
633
+ };
634
+ }
635
+ function safeModelReference(model) {
636
+ return safeErrorDetail(`${model.provider}/${model.modelId ?? model.id ?? "unknown"}`);
637
+ }
638
+ function destinationRuntimeConsumptionStatus(ctx, stateEntryType) {
639
+ try {
640
+ return restorePlanModeState(ctx.sessionManager.getBranch(), stateEntryType).pendingImplementationRuntime ? "pending" : "consumed";
641
+ } catch {
642
+ return "unavailable";
643
+ }
644
+ }
408
645
  function recoverSetupFailure(ctx, handoff, setupError) {
409
646
  const recoveredInEditor = safeSetEditorText(ctx, handoff);
410
647
  safeNotify(
@@ -432,9 +669,9 @@ function isCommandContext(ctx) {
432
669
  }
433
670
  function safeErrorDetail(error) {
434
671
  const detail = error instanceof Error ? error.message : String(error);
435
- const normalized = [...detail].map((character) => {
672
+ const normalized = [...stripVTControlCharacters(detail)].map((character) => {
436
673
  const codePoint = character.codePointAt(0) ?? 0;
437
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
674
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 ? " " : character;
438
675
  }).join("").replace(/\s+/gu, " ").trim() || "unknown error";
439
676
  const characters = [...normalized];
440
677
  return characters.length > 500 ? `${characters.slice(0, 499).join("")}\u2026` : normalized;
@@ -442,7 +679,37 @@ function safeErrorDetail(error) {
442
679
 
443
680
  // src/plan-action-controller.ts
444
681
  function createPlanActionController(options) {
445
- const freshAction = (ctx, lifecycle, signal) => options.implementFresh(ctx, () => lifecycle.isCurrent() && !signal.aborted);
682
+ const configuredDefaults = () => {
683
+ const settings = options.getSettings();
684
+ const model = configuredImplementationModel(settings);
685
+ const thinkingLevel = configuredImplementationThinkingLevel(settings);
686
+ return {
687
+ ...model ? { model: { ...model } } : {},
688
+ ...thinkingLevel ? { thinkingLevel } : {}
689
+ };
690
+ };
691
+ const effectiveDefaults = (ctx) => {
692
+ const configured = configuredDefaults();
693
+ const availableModel = findAvailableImplementationModel(
694
+ snapshotAvailableImplementationModels(ctx),
695
+ configured.model
696
+ );
697
+ if (configured.model && !availableModel) {
698
+ ctx.ui.notify("The configured fresh implementation model is unavailable; using the planning model.", "warning");
699
+ }
700
+ const planModel = ctx.model ? { provider: ctx.model.provider, modelId: ctx.model.id } : void 0;
701
+ const model = availableModel ? { provider: availableModel.provider, modelId: availableModel.id } : planModel;
702
+ const thinkingLevel = configured.thinkingLevel ?? options.getThinkingLevel();
703
+ return {
704
+ ...model ? { model } : {},
705
+ ...thinkingLevel ? { thinkingLevel } : {}
706
+ };
707
+ };
708
+ const freshAction = (ctx, lifecycle, signal, runtime, timing) => {
709
+ if (signal.aborted) return;
710
+ const isCurrent = timing === "after-settled" ? lifecycle.isCurrent : () => lifecycle.isCurrent() && !signal.aborted;
711
+ return options.implementFresh(ctx, isCurrent, runtime, timing);
712
+ };
446
713
  return {
447
714
  async showSaved(ctx) {
448
715
  const lifecycle = options.captureLifecycle();
@@ -457,7 +724,7 @@ function createPlanActionController(options) {
457
724
  isCurrent: lifecycle.isCurrent,
458
725
  show: () => options.show(ctx),
459
726
  implementHere: () => options.implementHere(ctx),
460
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
727
+ implementFresh: (signal) => freshAction(ctx, lifecycle, signal, effectiveDefaults(ctx), "immediate"),
461
728
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
462
729
  settings: (signal) => options.settings(ctx, signal, lifecycle.isCurrent),
463
730
  clear: () => options.clearSaved(ctx)
@@ -474,6 +741,8 @@ function createPlanActionController(options) {
474
741
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
475
742
  await ui.showPlanModeMenu(ctx, {
476
743
  statusText: options.statusText(),
744
+ planThinkingLevel: options.getThinkingLevel(),
745
+ implementationDefaults: configuredDefaults(),
477
746
  hasReadyPlan: options.getState().latestPlan !== void 0,
478
747
  implementationOutcome: options.implementationOutcome,
479
748
  getExportDestination: () => options.getExportDestination(ctx),
@@ -481,7 +750,7 @@ function createPlanActionController(options) {
481
750
  show: () => options.show(ctx),
482
751
  finalize: () => options.finalize(ctx),
483
752
  implementHere: () => options.implementHere(ctx),
484
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
753
+ implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, "immediate"),
485
754
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
486
755
  save: () => options.save(ctx),
487
756
  stay: () => options.stay(ctx),
@@ -495,10 +764,12 @@ function createPlanActionController(options) {
495
764
  if (!lifecycle.isCurrent() || lifecycle.signal.aborted) return;
496
765
  await ui.showReadyPlanMenu(ctx, {
497
766
  ...lifecycle,
767
+ planThinkingLevel: options.getThinkingLevel(),
768
+ implementationDefaults: configuredDefaults(),
498
769
  implementationOutcome: options.implementationOutcome,
499
770
  getExportDestination: () => options.getExportDestination(ctx),
500
771
  implementHere: () => options.implementHere(ctx),
501
- implementFresh: (signal) => freshAction(ctx, lifecycle, signal),
772
+ implementFresh: (runtime, signal) => freshAction(ctx, lifecycle, signal, runtime, "after-settled"),
502
773
  exportPlan: (path, signal) => options.exportPlan(ctx, path, signal, lifecycle.isCurrent),
503
774
  save: () => options.save(ctx),
504
775
  stay: () => void 0,
@@ -543,11 +814,7 @@ function updatePlanModeUi(ctx, state, toolSummary) {
543
814
  if (state.enabled && state.latestPlan) {
544
815
  lines = ["Proposed plan ready", "Use /plan to implement, save, revise, or exit Plan mode."];
545
816
  } else if (state.enabled) {
546
- lines = [
547
- "Plan mode: planning",
548
- toolSummary(),
549
- "Finish with plan_mode_complete when decision-ready."
550
- ];
817
+ lines = ["Plan mode: planning", toolSummary(), "Finish with plan_mode_complete when decision-ready."];
551
818
  } else if (state.savedPlan) {
552
819
  lines = ["Plan saved for later", "Use /plan to show, implement, or clear it."];
553
820
  } else if (state.activeImplementation) {
@@ -584,10 +851,7 @@ function showStoredPlan(pi, ctx, state) {
584
851
  const activePlan = state.activeImplementation?.plan.trim();
585
852
  const plan = readyPlan ?? savedPlan ?? activePlan;
586
853
  if (!plan) {
587
- ctx.ui.notify(
588
- "No completed plan is available. Use /plan finalize when planning is complete.",
589
- "info"
590
- );
854
+ ctx.ui.notify("No completed plan is available. Use /plan finalize when planning is complete.", "info");
591
855
  return;
592
856
  }
593
857
  const title = readyPlan ? "Proposed Plan" : savedPlan ? "Saved Plan" : "Active Implementation Plan";
@@ -648,10 +912,7 @@ function formatStatus(state) {
648
912
  }
649
913
 
650
914
  // src/required-tools.ts
651
- var REQUIRED_PLAN_MODE_TOOL_NAMES = [
652
- PLAN_MODE_QUESTION_TOOL_NAME,
653
- PLAN_MODE_COMPLETE_TOOL_NAME
654
- ];
915
+ var REQUIRED_PLAN_MODE_TOOL_NAMES = [PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
655
916
  function planModeHelperToolsAvailable(toolNames) {
656
917
  const active = new Set(toolNames);
657
918
  return REQUIRED_PLAN_MODE_TOOL_NAMES.every((name) => active.has(name));
@@ -697,106 +958,6 @@ async function preflightSavedPlanImplementation(ctx, isCurrent) {
697
958
  return true;
698
959
  }
699
960
 
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
961
  // src/workflow-mutex.ts
801
962
  var WORKFLOW_MUTEX_CHANNEL = "workflow:mutex:v1";
802
963
  var AGENT_WORKFLOW_GROUP = "agent-workflow";
@@ -863,6 +1024,7 @@ var WorkflowMutex = class {
863
1024
  // src/plan-mode.ts
864
1025
  var STATE_ENTRY_TYPE = "plan-mode-state";
865
1026
  var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
1027
+ var RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE = "plan-mode-recovered-input";
866
1028
  var BLOCKED_MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "update_plan"]);
867
1029
  var DEFAULT_TOOLS = ["read", "bash", "edit", "write"];
868
1030
  function planMode(pi, dependencies = {}) {
@@ -874,7 +1036,7 @@ function planMode(pi, dependencies = {}) {
874
1036
  const loadInteractiveUi = () => {
875
1037
  if (dependencies.loadInteractiveUi) return dependencies.loadInteractiveUi();
876
1038
  if (!interactiveUiPromise) {
877
- interactiveUiPromise = import("./chunks/interactive-ui-N2ZKBVNE.js").catch((error) => {
1039
+ interactiveUiPromise = import("./chunks/interactive-ui-UK7IGPOE.js").catch((error) => {
878
1040
  interactiveUiPromise = void 0;
879
1041
  throw error;
880
1042
  });
@@ -893,10 +1055,15 @@ function planMode(pi, dependencies = {}) {
893
1055
  let modeContractsRelevant = false;
894
1056
  let readyPresentationIntent;
895
1057
  let latestCommandContext;
1058
+ let stagedFreshImplementation;
1059
+ const deferredFreshHandoff = createDeferredFreshHandoffCoordinator();
896
1060
  let nextReadyPresentationNonce = 0;
897
1061
  let menuGeneration = 0;
898
1062
  let workflowGeneration = 0;
899
1063
  let refreshStateBeforeFirstAgentStart = false;
1064
+ let activeImplementationRuntimeApplication;
1065
+ let pendingRuntimeAdmissionSession;
1066
+ let queuedRuntimeAdmissionInputs = [];
900
1067
  let menuController = new AbortController();
901
1068
  let settingsWatch;
902
1069
  let settingsReloadTimer;
@@ -915,6 +1082,10 @@ function planMode(pi, dependencies = {}) {
915
1082
  getState: () => state,
916
1083
  captureLifecycle: captureMenuLifecycle,
917
1084
  statusText: planStatusText,
1085
+ // ExtensionContext.thinkingLevel was added after the supported Pi 0.80.6 floor.
1086
+ // ExtensionAPI has exposed the same runtime value throughout that compatibility range.
1087
+ getThinkingLevel: () => pi.getThinkingLevel(),
1088
+ getSettings: () => settings,
918
1089
  implementationOutcome,
919
1090
  getExportDestination: (ctx) => planExports.getDestination(ctx),
920
1091
  show: (ctx) => showStoredPlan(pi, ctx, state),
@@ -992,17 +1163,13 @@ function planMode(pi, dependencies = {}) {
992
1163
  const prompt = args.trim();
993
1164
  const command = prompt.toLowerCase();
994
1165
  if (command === "start") {
995
- if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled))
996
- return;
1166
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled)) return;
997
1167
  if (state.enabled) {
998
1168
  ctx.ui.notify("Plan mode is already active.", "info");
999
1169
  return;
1000
1170
  }
1001
1171
  if (enterPlanMode(ctx)) {
1002
- ctx.ui.notify(
1003
- "Plan mode enabled. I will explore and plan, but not modify files.",
1004
- "info"
1005
- );
1172
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1006
1173
  }
1007
1174
  return;
1008
1175
  }
@@ -1026,6 +1193,14 @@ function planMode(pi, dependencies = {}) {
1026
1193
  savePlanForLater(ctx);
1027
1194
  return;
1028
1195
  }
1196
+ if (command === "settings") {
1197
+ if (!ctx.hasUI) {
1198
+ throw new Error("/plan settings requires TUI or RPC mode and is unavailable here.");
1199
+ }
1200
+ const lifecycle = captureMenuLifecycle();
1201
+ await showSettings(ctx, lifecycle.signal, lifecycle.isCurrent);
1202
+ return;
1203
+ }
1029
1204
  const exportMatch = /^export(?:\s+([\s\S]+))?$/iu.exec(prompt);
1030
1205
  if (exportMatch) {
1031
1206
  const lifecycle = captureMenuLifecycle();
@@ -1038,8 +1213,7 @@ function planMode(pi, dependencies = {}) {
1038
1213
  return;
1039
1214
  }
1040
1215
  if (command === "tools") {
1041
- if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled))
1042
- return;
1216
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled)) return;
1043
1217
  if (state.enabled) {
1044
1218
  const message = "Plan-mode tools are locked while Planning is active. Exit Plan mode and choose tools before starting again.";
1045
1219
  if (!ctx.hasUI) throw new Error(message);
@@ -1053,8 +1227,7 @@ function planMode(pi, dependencies = {}) {
1053
1227
  return;
1054
1228
  }
1055
1229
  if (prompt) {
1056
- if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled))
1057
- return;
1230
+ if (savedPlanBlocksNewWorkflow(ctx, state.savedPlan !== void 0 && !state.enabled)) return;
1058
1231
  enterPlanModeWithPrompt(prompt, ctx);
1059
1232
  return;
1060
1233
  }
@@ -1155,6 +1328,7 @@ function planMode(pi, dependencies = {}) {
1155
1328
  }
1156
1329
  };
1157
1330
  pi.on("session_start", async (event, ctx) => {
1331
+ cancelDeferredFreshImplementation();
1158
1332
  const generation = ++menuGeneration;
1159
1333
  finalizationRequest.reset();
1160
1334
  currentSession = ctx.sessionManager;
@@ -1162,6 +1336,8 @@ function planMode(pi, dependencies = {}) {
1162
1336
  workflowOwner = void 0;
1163
1337
  workflowMutex.bindSession(ctx.sessionManager);
1164
1338
  refreshStateBeforeFirstAgentStart = event.reason === "new";
1339
+ pendingRuntimeAdmissionSession = void 0;
1340
+ queuedRuntimeAdmissionInputs = [];
1165
1341
  menuController.abort(new DOMException("Plan-mode session replaced", "AbortError"));
1166
1342
  menuController = new AbortController();
1167
1343
  readyPresentationIntent = void 0;
@@ -1180,8 +1356,18 @@ function planMode(pi, dependencies = {}) {
1180
1356
  if (!installRestoredState(restoredState, ctx)) return;
1181
1357
  implementationRetention.restore(state.activeImplementation);
1182
1358
  updateUi(ctx);
1359
+ if (event.reason !== "new") await applyPendingImplementationRuntime(ctx);
1183
1360
  });
1184
1361
  pi.on("session_before_tree", (event, ctx) => {
1362
+ if (runtimeAdmissionIsPending(ctx.sessionManager)) {
1363
+ if (ctx.hasUI) {
1364
+ ctx.ui.notify(
1365
+ "Wait for fresh implementation startup to admit the pending prompts before changing branches.",
1366
+ "warning"
1367
+ );
1368
+ }
1369
+ return { cancel: true };
1370
+ }
1185
1371
  const target = ctx.sessionManager.getEntry(event.preparation.targetId);
1186
1372
  if (target?.type !== "custom_message" || target.customType !== MODE_CONTRACT_MESSAGE_TYPE) {
1187
1373
  return;
@@ -1194,13 +1380,16 @@ function planMode(pi, dependencies = {}) {
1194
1380
  }
1195
1381
  return { cancel: true };
1196
1382
  });
1197
- pi.on("session_tree", (_event, ctx) => {
1383
+ pi.on("session_tree", async (_event, ctx) => {
1384
+ cancelDeferredFreshImplementation();
1198
1385
  advanceWorkflowGeneration();
1199
1386
  menuGeneration += 1;
1200
1387
  menuController.abort(new DOMException("Plan-mode tree branch changed", "AbortError"));
1201
1388
  menuController = new AbortController();
1202
1389
  readyPresentationIntent = void 0;
1203
1390
  latestCommandContext = void 0;
1391
+ pendingRuntimeAdmissionSession = void 0;
1392
+ queuedRuntimeAdmissionInputs = [];
1204
1393
  implementationRetention.reset();
1205
1394
  const branch = ctx.sessionManager.getBranch();
1206
1395
  const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
@@ -1209,6 +1398,7 @@ function planMode(pi, dependencies = {}) {
1209
1398
  implementationRetention.restore(state.activeImplementation);
1210
1399
  startPlanModeSettingsWatch(menuGeneration);
1211
1400
  updateUi(ctx);
1401
+ await applyPendingImplementationRuntime(ctx);
1212
1402
  });
1213
1403
  pi.on("thinking_level_select", (event) => {
1214
1404
  if (!state.enabled || !state.appliedThinkingLevel) return;
@@ -1223,16 +1413,37 @@ function planMode(pi, dependencies = {}) {
1223
1413
  }
1224
1414
  });
1225
1415
  pi.on("session_shutdown", async (_event, ctx) => {
1416
+ cancelDeferredFreshImplementation();
1226
1417
  const shutdownSession = ctx.sessionManager;
1418
+ const runtimeApplication = activeImplementationRuntimeApplication?.sessionManager === shutdownSession && activeImplementationRuntimeApplication.drainOnShutdown ? activeImplementationRuntimeApplication : void 0;
1419
+ const queuedInputs = takeQueuedRuntimeAdmissionInputs(shutdownSession);
1420
+ for (const queued of queuedInputs) {
1421
+ pi.sendMessage(
1422
+ {
1423
+ customType: RECOVERED_RUNTIME_ADMISSION_INPUT_MESSAGE_TYPE,
1424
+ content: runtimeAdmissionInputContent(queued),
1425
+ display: true,
1426
+ details: { source: queued.source }
1427
+ },
1428
+ { triggerTurn: false }
1429
+ );
1430
+ }
1227
1431
  finalizationRequest.reset();
1228
1432
  menuGeneration += 1;
1229
1433
  menuController.abort(new DOMException("Plan-mode session shut down", "AbortError"));
1230
1434
  readyPresentationIntent = void 0;
1231
1435
  latestCommandContext = void 0;
1232
1436
  refreshStateBeforeFirstAgentStart = false;
1437
+ pendingRuntimeAdmissionSession = void 0;
1438
+ queuedRuntimeAdmissionInputs = [];
1233
1439
  workflowAllowedToolNames = void 0;
1234
1440
  pendingWorkflowToolPolicy = void 0;
1235
1441
  implementationRetention.reset();
1442
+ if (runtimeApplication) await runtimeApplication.completion;
1443
+ if (currentSession !== void 0 && currentSession !== shutdownSession) {
1444
+ workflowMutex.unbindSession(shutdownSession);
1445
+ return;
1446
+ }
1236
1447
  await awaitPlanModeSettingsWrites(dependencies.settingsPath);
1237
1448
  if (currentSession !== void 0 && currentSession !== shutdownSession) {
1238
1449
  workflowMutex.unbindSession(shutdownSession);
@@ -1300,11 +1511,7 @@ function planMode(pi, dependencies = {}) {
1300
1511
  };
1301
1512
  }
1302
1513
  if (event.toolName === "bash") {
1303
- const blocked = findBlockedCommandSegment(
1304
- readCommand(event.input),
1305
- settings.safeSubcommands,
1306
- ctx.cwd
1307
- );
1514
+ const blocked = findBlockedCommandSegment(readCommand(event.input), settings.safeSubcommands, ctx.cwd);
1308
1515
  if (blocked !== void 0) {
1309
1516
  return {
1310
1517
  block: true,
@@ -1314,11 +1521,7 @@ Blocked command: ${blocked}`
1314
1521
  }
1315
1522
  }
1316
1523
  if (event.toolName === "powershell") {
1317
- const blocked = findBlockedPowerShellCommandSegment(
1318
- readCommand(event.input),
1319
- settings.safeSubcommands,
1320
- ctx.cwd
1321
- );
1524
+ const blocked = findBlockedPowerShellCommandSegment(readCommand(event.input), settings.safeSubcommands, ctx.cwd);
1322
1525
  if (blocked !== void 0) {
1323
1526
  return {
1324
1527
  block: true,
@@ -1342,19 +1545,41 @@ Blocked command: ${blocked}`
1342
1545
  const messages = state.enabled || modeContractsRelevant ? reconcileModeContract(result.messages, state.enabled ? "plan" : "normal") : result.messages;
1343
1546
  return { messages };
1344
1547
  });
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);
1548
+ pi.on("input", async (event, ctx) => {
1549
+ refreshStateForFirstPrompt(ctx);
1550
+ const waitsForRuntimeAdmission = activeImplementationRuntimeApplication?.sessionManager === ctx.sessionManager || pendingRuntimeAdmissionSession === ctx.sessionManager;
1551
+ const queuedInput = waitsForRuntimeAdmission ? {
1552
+ sessionManager: ctx.sessionManager,
1553
+ text: event.text,
1554
+ ...event.images ? { images: [...event.images] } : {},
1555
+ source: event.source
1556
+ } : void 0;
1557
+ if (queuedInput) queuedRuntimeAdmissionInputs.push(queuedInput);
1558
+ const result = await applyPendingImplementationRuntime(ctx, true);
1559
+ if (result !== "ready") {
1560
+ if (result === "stale" && queuedInput) removeQueuedRuntimeAdmissionInput(queuedInput);
1561
+ return { action: "handled" };
1562
+ }
1563
+ if (queuedInput) return { action: "handled" };
1564
+ });
1565
+ pi.on("agent_start", (_event, ctx) => {
1566
+ if (currentSession !== ctx.sessionManager) return;
1567
+ if (pendingRuntimeAdmissionSession === ctx.sessionManager) {
1568
+ pendingRuntimeAdmissionSession = void 0;
1569
+ }
1570
+ const queuedInputs = takeQueuedRuntimeAdmissionInputs(ctx.sessionManager);
1571
+ for (const queued of queuedInputs) {
1572
+ pi.sendUserMessage(runtimeAdmissionInputContent(queued), {
1573
+ deliverAs: "followUp",
1574
+ expandPromptTemplates: queued.source !== "extension"
1575
+ });
1355
1576
  }
1577
+ });
1578
+ pi.on("before_agent_start", (_event, ctx) => {
1579
+ refreshStateForFirstPrompt(ctx);
1356
1580
  if (!state.enabled || !workflowMutex.isOwner(workflowOwner)) return;
1357
1581
  if (state.latestPlan || state.awaitingAction) {
1582
+ cancelDeferredFreshImplementation();
1358
1583
  readyPresentationIntent = void 0;
1359
1584
  state = {
1360
1585
  ...state,
@@ -1382,9 +1607,7 @@ Blocked command: ${blocked}`
1382
1607
  acceptCompletedPlan(parsedPlan.plan, "legacy_proposed_plan", ctx);
1383
1608
  });
1384
1609
  pi.on("agent_settled", async (_event, ctx) => {
1385
- const settledImplementationId = implementationRetention.implementationSettled(
1386
- state.activeImplementation
1387
- );
1610
+ const settledImplementationId = implementationRetention.implementationSettled(state.activeImplementation);
1388
1611
  if (settledImplementationId) clearActiveImplementation(settledImplementationId, ctx);
1389
1612
  if (finalizationRequest.hasPendingRequest() && state.enabled && workflowMutex.isOwner(workflowOwner)) {
1390
1613
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
@@ -1404,6 +1627,7 @@ Blocked command: ${blocked}`
1404
1627
  if (!intent || !readyPresentationIsCurrent(intent)) return;
1405
1628
  if (!ctx.isIdle() || ctx.hasPendingMessages()) return;
1406
1629
  readyPresentationIntent = void 0;
1630
+ stagedFreshImplementation = void 0;
1407
1631
  try {
1408
1632
  if (intent.source === "legacy_proposed_plan") {
1409
1633
  pi.sendMessage(
@@ -1420,7 +1644,11 @@ ${intent.plan}`,
1420
1644
  if (ctx.hasUI && completedPlanIsCurrent(intent)) {
1421
1645
  await planActions.showReady(latestCommandContext ?? ctx);
1422
1646
  }
1647
+ const request = stagedFreshImplementation;
1648
+ stagedFreshImplementation = void 0;
1649
+ if (request) armDeferredFreshImplementation(request);
1423
1650
  } catch (error) {
1651
+ stagedFreshImplementation = void 0;
1424
1652
  if (!isStaleExtensionContextError(error)) throw error;
1425
1653
  }
1426
1654
  });
@@ -1451,6 +1679,7 @@ ${intent.plan}`,
1451
1679
  awaitingAction: false,
1452
1680
  savedPlan: void 0,
1453
1681
  activeImplementation: void 0,
1682
+ pendingImplementationRuntime: void 0,
1454
1683
  selectedToolNames: candidate.selectedToolNames,
1455
1684
  selectedToolKeys: candidate.selectedToolKeys
1456
1685
  };
@@ -1493,6 +1722,7 @@ ${intent.plan}`,
1493
1722
  awaitingAction: false,
1494
1723
  savedPlan: void 0,
1495
1724
  activeImplementation: void 0,
1725
+ pendingImplementationRuntime: void 0,
1496
1726
  workflowToolPolicy: void 0,
1497
1727
  manualThinkingLevel: void 0
1498
1728
  };
@@ -1507,7 +1737,7 @@ ${intent.plan}`,
1507
1737
  }
1508
1738
  function restoreModeContractTracking(branch, restoredState) {
1509
1739
  publishedContractMode = latestModeContract(branch)?.mode;
1510
- modeContractsRelevant = hasModeContractArtifact(branch) || restoredState.enabled || restoredState.savedPlan !== void 0 || restoredState.activeImplementation !== void 0;
1740
+ modeContractsRelevant = hasModeContractArtifact(branch) || restoredState.enabled || restoredState.savedPlan !== void 0 || restoredState.activeImplementation !== void 0 || restoredState.pendingImplementationRuntime !== void 0;
1511
1741
  }
1512
1742
  function publishModeContract(mode, ctx) {
1513
1743
  if (publishedContractMode === mode) return true;
@@ -1612,6 +1842,7 @@ ${intent.plan}`,
1612
1842
  awaitingAction: false,
1613
1843
  savedPlan: { plan, source },
1614
1844
  activeImplementation: void 0,
1845
+ pendingImplementationRuntime: void 0,
1615
1846
  workflowToolPolicy: void 0,
1616
1847
  manualThinkingLevel: void 0
1617
1848
  };
@@ -1622,13 +1853,75 @@ ${intent.plan}`,
1622
1853
  releaseWorkflowOwner();
1623
1854
  ctx.ui.notify("Plan saved for later. Plan mode disabled.", "info");
1624
1855
  }
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
- });
1856
+ async function startFreshImplementation(ctx, menuIsCurrent, runtime, timing) {
1857
+ const retention = configuredImplementationPlanRetention(settings);
1858
+ if (timing === "immediate") {
1859
+ await startFreshImplementationFromState(ctx, {
1860
+ getState: () => state,
1861
+ menuIsCurrent,
1862
+ retention,
1863
+ stateEntryType: STATE_ENTRY_TYPE,
1864
+ runtime
1865
+ });
1866
+ return;
1867
+ }
1868
+ const initialState = state;
1869
+ const savedPlan = initialState.enabled ? void 0 : initialState.savedPlan;
1870
+ const plan = (initialState.enabled ? initialState.latestPlan : savedPlan?.plan)?.trim();
1871
+ const source = initialState.enabled ? initialState.latestPlanSource : savedPlan?.source;
1872
+ if (!plan || !source || !menuIsCurrent()) return;
1873
+ stagedFreshImplementation = {
1874
+ ctx,
1875
+ sourceSession: ctx.sessionManager,
1876
+ menuGeneration,
1877
+ workflowGeneration,
1878
+ workflowOwner,
1879
+ enabled: initialState.enabled,
1880
+ plan,
1881
+ source,
1882
+ savedPlan,
1883
+ retention,
1884
+ runtime: runtime ? {
1885
+ ...runtime.model ? { model: { ...runtime.model } } : {},
1886
+ ...runtime.thinkingLevel ? { thinkingLevel: runtime.thinkingLevel } : {}
1887
+ } : void 0,
1888
+ menuIsCurrent
1889
+ };
1890
+ }
1891
+ function armDeferredFreshImplementation(request) {
1892
+ deferredFreshHandoff.schedule(
1893
+ async (taskIsCurrent) => {
1894
+ const isCurrent = () => taskIsCurrent() && deferredFreshImplementationIsCurrent(request);
1895
+ if (!isCurrent()) return;
1896
+ await startFreshImplementationFromState(request.ctx, {
1897
+ getState: () => state,
1898
+ menuIsCurrent: isCurrent,
1899
+ retention: request.retention,
1900
+ stateEntryType: STATE_ENTRY_TYPE,
1901
+ runtime: request.runtime
1902
+ });
1903
+ },
1904
+ (error) => {
1905
+ if (!deferredFreshImplementationIsCurrent(request)) return;
1906
+ try {
1907
+ request.ctx.ui.notify(
1908
+ `Unable to start the deferred fresh implementation: ${terminalErrorDetail(error)}`,
1909
+ "error"
1910
+ );
1911
+ } catch {
1912
+ }
1913
+ }
1914
+ );
1915
+ }
1916
+ function deferredFreshImplementationIsCurrent(request) {
1917
+ if (currentSession !== request.sourceSession || menuGeneration !== request.menuGeneration || workflowGeneration !== request.workflowGeneration || workflowOwner !== request.workflowOwner || !request.menuIsCurrent() || state.enabled !== request.enabled) {
1918
+ return false;
1919
+ }
1920
+ return request.enabled ? workflowMutex.isOwner(request.workflowOwner) && state.latestPlan === request.plan && state.latestPlanSource === request.source : state.savedPlan === request.savedPlan;
1921
+ }
1922
+ function cancelDeferredFreshImplementation() {
1923
+ stagedFreshImplementation = void 0;
1924
+ deferredFreshHandoff.cancel();
1632
1925
  }
1633
1926
  async function startImplementation(ctx) {
1634
1927
  const savedPlan = state.enabled ? void 0 : state.savedPlan;
@@ -1664,6 +1957,7 @@ ${intent.plan}`,
1664
1957
  latestPlanSource: void 0,
1665
1958
  awaitingAction: false,
1666
1959
  savedPlan: void 0,
1960
+ pendingImplementationRuntime: void 0,
1667
1961
  activeImplementation: usesConversationHistory ? void 0 : {
1668
1962
  id: randomUUID2(),
1669
1963
  plan,
@@ -1724,9 +2018,7 @@ ${intent.plan}`,
1724
2018
  const retainsInactiveSelection = state.selectedToolNames !== void 0 || state.selectedToolKeys !== void 0 || settings.defaultPlanTools !== void 0;
1725
2019
  const retainedInactiveNames = retainsInactiveSelection ? initialSelectedNames : /* @__PURE__ */ new Set();
1726
2020
  const registeredNames = new Set(tools.map((tool) => tool.name));
1727
- const pendingNames = Array.from(retainedInactiveNames).filter(
1728
- (name) => !registeredNames.has(name)
1729
- );
2021
+ const pendingNames = Array.from(retainedInactiveNames).filter((name) => !registeredNames.has(name));
1730
2022
  await ui.showPlanLaunchMenu(ctx, {
1731
2023
  statusText: planModeHelperToolsAvailable(safeGetActiveTools()) ? "Status: Off \u2014 visible Plan helpers stay inactive until /plan starts." : "Status: Off \u2014 required Plan helpers are unavailable under the active tool policy.",
1732
2024
  initialScreen,
@@ -1774,18 +2066,13 @@ ${intent.plan}`,
1774
2066
  start: (signal) => {
1775
2067
  if (signal.aborted || !lifecycle.isCurrent()) return;
1776
2068
  if (enterPlanMode(ctx)) {
1777
- ctx.ui.notify(
1778
- "Plan mode enabled. I will explore and plan, but not modify files.",
1779
- "info"
1780
- );
2069
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1781
2070
  }
1782
2071
  },
1783
2072
  startWithTools: (names, signal) => {
1784
2073
  if (signal.aborted || !lifecycle.isCurrent()) return;
1785
2074
  const selectedToolNames = Array.from(
1786
- new Set(
1787
- names.filter((name) => activeToolNames.has(name) || retainedInactiveNames.has(name))
1788
- )
2075
+ new Set(names.filter((name) => activeToolNames.has(name) || retainedInactiveNames.has(name)))
1789
2076
  );
1790
2077
  if (enterPlanMode(ctx, { selectedToolNames, selectedToolKeys: void 0 })) {
1791
2078
  ctx.ui.notify("Plan mode enabled with the selected tools.", "info");
@@ -1813,10 +2100,7 @@ ${intent.plan}`,
1813
2100
  settings: (signal) => showSettings(ctx, signal, lifecycle.isCurrent),
1814
2101
  startNew: () => {
1815
2102
  if (enterPlanMode(ctx)) {
1816
- ctx.ui.notify(
1817
- "Plan mode enabled. I will explore and plan, but not modify files.",
1818
- "info"
1819
- );
2103
+ ctx.ui.notify("Plan mode enabled. I will explore and plan, but not modify files.", "info");
1820
2104
  }
1821
2105
  },
1822
2106
  clear: () => {
@@ -1852,6 +2136,7 @@ ${intent.plan}`,
1852
2136
  return false;
1853
2137
  }
1854
2138
  function advanceWorkflowGeneration() {
2139
+ cancelDeferredFreshImplementation();
1855
2140
  workflowGeneration += 1;
1856
2141
  pendingWorkflowToolPolicy = void 0;
1857
2142
  finalizationRequest.reset();
@@ -1879,9 +2164,7 @@ ${intent.plan}`,
1879
2164
  function workflowDesiredToolNames() {
1880
2165
  const policy = state.workflowToolPolicy;
1881
2166
  if (!state.enabled || !policy) return /* @__PURE__ */ new Set();
1882
- return new Set(
1883
- policy.kind === "automatic" ? automaticPlanModeToolNames() : policy.desiredNames ?? []
1884
- );
2167
+ return new Set(policy.kind === "automatic" ? automaticPlanModeToolNames() : policy.desiredNames ?? []);
1885
2168
  }
1886
2169
  function beginWorkflowToolPolicy() {
1887
2170
  const kind = toolPolicySelectionIsExplicit() ? "explicit" : "automatic";
@@ -1990,9 +2273,7 @@ ${intent.plan}`,
1990
2273
  };
1991
2274
  }
1992
2275
  function selectableTools() {
1993
- return safeGetAllTools().filter(
1994
- (tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME
1995
- ).sort(compareTools);
2276
+ return safeGetAllTools().filter((tool) => tool.name !== PLAN_MODE_QUESTION_TOOL_NAME && tool.name !== PLAN_MODE_COMPLETE_TOOL_NAME).sort(compareTools);
1996
2277
  }
1997
2278
  function activePlanPolicyTools() {
1998
2279
  const activeNames = new Set(safeGetActiveTools());
@@ -2005,6 +2286,174 @@ ${intent.plan}`,
2005
2286
  return [];
2006
2287
  }
2007
2288
  }
2289
+ function runtimeAdmissionIsPending(sessionManager) {
2290
+ return activeImplementationRuntimeApplication?.sessionManager === sessionManager || pendingRuntimeAdmissionSession === sessionManager || queuedRuntimeAdmissionInputs.some((queued) => queued.sessionManager === sessionManager);
2291
+ }
2292
+ function takeQueuedRuntimeAdmissionInputs(sessionManager) {
2293
+ const matching = [];
2294
+ const remaining = [];
2295
+ for (const queued of queuedRuntimeAdmissionInputs) {
2296
+ if (queued.sessionManager === sessionManager) matching.push(queued);
2297
+ else remaining.push(queued);
2298
+ }
2299
+ queuedRuntimeAdmissionInputs = remaining;
2300
+ return matching;
2301
+ }
2302
+ function removeQueuedRuntimeAdmissionInput(queuedInput) {
2303
+ const index = queuedRuntimeAdmissionInputs.indexOf(queuedInput);
2304
+ if (index >= 0) queuedRuntimeAdmissionInputs.splice(index, 1);
2305
+ }
2306
+ function runtimeAdmissionInputContent(queued) {
2307
+ return queued.images?.length ? [{ type: "text", text: queued.text }, ...queued.images] : queued.text;
2308
+ }
2309
+ function refreshStateForFirstPrompt(ctx) {
2310
+ if (!refreshStateBeforeFirstAgentStart) return;
2311
+ refreshStateBeforeFirstAgentStart = false;
2312
+ implementationRetention.reset();
2313
+ const branch = ctx.sessionManager.getBranch();
2314
+ const restoredState = restorePlanModeState(branch, STATE_ENTRY_TYPE);
2315
+ restoreModeContractTracking(branch, restoredState);
2316
+ if (!installRestoredState(restoredState, ctx)) return;
2317
+ implementationRetention.restore(state.activeImplementation);
2318
+ updateUi(ctx);
2319
+ }
2320
+ async function applyPendingImplementationRuntime(ctx, holdForAdmission = false) {
2321
+ const session = ctx.sessionManager;
2322
+ const activeApplication = activeImplementationRuntimeApplication;
2323
+ if (activeApplication?.sessionManager === session) {
2324
+ if (holdForAdmission) activeApplication.holdForAdmission = true;
2325
+ return activeApplication.completion;
2326
+ }
2327
+ const intent = state.enabled ? void 0 : state.pendingImplementationRuntime;
2328
+ if (!intent) return "ready";
2329
+ const generation = menuGeneration;
2330
+ const isCurrent = () => currentSession === session && generation === menuGeneration && !menuController.signal.aborted;
2331
+ const notifyCurrent2 = (message) => {
2332
+ if (!isCurrent()) return;
2333
+ try {
2334
+ ctx.ui.notify(message, "warning");
2335
+ } catch {
2336
+ }
2337
+ };
2338
+ let application;
2339
+ const completion = Promise.resolve().then(async () => {
2340
+ if (!isCurrent()) return "stale";
2341
+ const pendingState = state;
2342
+ const previousThinkingLevel = pi.getThinkingLevel();
2343
+ const applyThinking = () => {
2344
+ if (!intent.thinkingLevel) return;
2345
+ try {
2346
+ pi.setThinkingLevel(intent.thinkingLevel);
2347
+ const effectiveLevel = pi.getThinkingLevel();
2348
+ if (effectiveLevel !== intent.thinkingLevel) {
2349
+ notifyCurrent2(
2350
+ `Implementation thinking ${intent.thinkingLevel} is unsupported by the destination model; Pi is using ${effectiveLevel}.`
2351
+ );
2352
+ }
2353
+ } catch (error) {
2354
+ notifyCurrent2(
2355
+ `Implementation thinking ${intent.thinkingLevel} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default will continue.`
2356
+ );
2357
+ }
2358
+ };
2359
+ if (intent.model) {
2360
+ let model;
2361
+ let resolutionFailed = false;
2362
+ try {
2363
+ model = ctx.modelRegistry.find(intent.model.provider, intent.model.modelId);
2364
+ } catch (error) {
2365
+ notifyCurrent2(
2366
+ `Implementation model ${terminalModelReference(intent.model)} could not be resolved: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`
2367
+ );
2368
+ resolutionFailed = true;
2369
+ model = void 0;
2370
+ }
2371
+ if (!model && !resolutionFailed) {
2372
+ notifyCurrent2(
2373
+ `Implementation model ${terminalModelReference(intent.model)} is no longer available. The destination default model will continue.`
2374
+ );
2375
+ }
2376
+ if (model) {
2377
+ let authenticated = false;
2378
+ try {
2379
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
2380
+ if (!isCurrent()) return "stale";
2381
+ if (auth.ok) authenticated = true;
2382
+ else {
2383
+ notifyCurrent2(
2384
+ `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(auth.error)}. The destination default model will continue.`
2385
+ );
2386
+ }
2387
+ } catch (error) {
2388
+ notifyCurrent2(
2389
+ `Implementation model ${terminalModelReference(intent.model)} could not be authenticated: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`
2390
+ );
2391
+ }
2392
+ if (!isCurrent()) return "stale";
2393
+ if (authenticated) {
2394
+ let applied = false;
2395
+ let applicationFailed = false;
2396
+ application.drainOnShutdown = true;
2397
+ try {
2398
+ try {
2399
+ applied = await pi.setModel(model);
2400
+ } catch (error) {
2401
+ applicationFailed = true;
2402
+ notifyCurrent2(
2403
+ `Implementation model ${terminalModelReference(intent.model)} could not be applied: ${safeTerminalText(error instanceof Error ? error.message : String(error))}. The destination default model will continue.`
2404
+ );
2405
+ }
2406
+ } finally {
2407
+ application.drainOnShutdown = false;
2408
+ }
2409
+ if (!isCurrent()) return "stale";
2410
+ if (!applied && !applicationFailed) {
2411
+ notifyCurrent2(
2412
+ `Implementation model ${terminalModelReference(intent.model)} could not be applied after authentication changed. The destination default model will continue.`
2413
+ );
2414
+ }
2415
+ }
2416
+ }
2417
+ }
2418
+ if (!isCurrent()) return "stale";
2419
+ applyThinking();
2420
+ if (!isCurrent()) return "stale";
2421
+ state = { ...state, pendingImplementationRuntime: void 0 };
2422
+ try {
2423
+ persistState();
2424
+ } catch (error) {
2425
+ state = pendingState;
2426
+ try {
2427
+ if (pi.getThinkingLevel() !== previousThinkingLevel) {
2428
+ pi.setThinkingLevel(previousThinkingLevel);
2429
+ }
2430
+ } catch {
2431
+ }
2432
+ try {
2433
+ persistState();
2434
+ } catch {
2435
+ }
2436
+ notifyCurrent2(
2437
+ `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.`
2438
+ );
2439
+ return "blocked";
2440
+ }
2441
+ if (application.holdForAdmission) pendingRuntimeAdmissionSession = session;
2442
+ return "ready";
2443
+ }).finally(() => {
2444
+ if (activeImplementationRuntimeApplication === application) {
2445
+ activeImplementationRuntimeApplication = void 0;
2446
+ }
2447
+ });
2448
+ application = {
2449
+ sessionManager: session,
2450
+ completion,
2451
+ drainOnShutdown: false,
2452
+ holdForAdmission
2453
+ };
2454
+ activeImplementationRuntimeApplication = application;
2455
+ return completion;
2456
+ }
2008
2457
  function applyPlanThinkingLevel() {
2009
2458
  if (state.manualThinkingLevel) {
2010
2459
  if (pi.getThinkingLevel() !== state.manualThinkingLevel) {
@@ -2198,10 +2647,19 @@ ${intent.plan}`,
2198
2647
  const safe = safeTerminalText(value) || "(unnamed tool)";
2199
2648
  return safe.length > 120 ? `${safe.slice(0, 119)}\u2026` : safe;
2200
2649
  }
2650
+ function terminalModelReference(model) {
2651
+ const safe = safeTerminalText(`${model.provider}/${model.modelId}`) || "(unnamed model)";
2652
+ return safe.length > 160 ? `${safe.slice(0, 159)}\u2026` : safe;
2653
+ }
2654
+ function terminalErrorDetail(error) {
2655
+ const safe = safeTerminalText(error instanceof Error ? error.message : String(error));
2656
+ if (!safe) return "unknown error";
2657
+ return safe.length > 500 ? `${safe.slice(0, 499)}\u2026` : safe;
2658
+ }
2201
2659
  function safeTerminalText(value) {
2202
- return [...value].map((character) => {
2660
+ return [...stripVTControlCharacters2(value)].map((character) => {
2203
2661
  const codePoint = character.codePointAt(0) ?? 0;
2204
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? " " : character;
2662
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 ? " " : character;
2205
2663
  }).join("").trim();
2206
2664
  }
2207
2665
  }