@narumitw/pi-plan-mode 0.56.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,318 +70,107 @@ function isRecord(value) {
70
70
  return typeof value === "object" && value !== null && !Array.isArray(value);
71
71
  }
72
72
 
73
- // src/message-transform.ts
74
- var PLAN_CONTEXT_MESSAGE_TYPE = "plan-mode-context";
75
- var PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE = "plan-mode-implementation-context";
76
- var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
77
- var PLAN_IMPLEMENTATION_HANDOFF_PREFIX = "Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:";
78
- var PLAN_HISTORY_IMPLEMENTATION_PROMPT = "Implement the plan.";
79
- var PROPOSED_PLAN_PATTERN = /^<proposed_plan>[\t ]*\r?\n([\s\S]*?)\r?\n<\/proposed_plan>[\t ]*$/gm;
80
- var PROPOSED_PLAN_BLOCK_PATTERN = /^<proposed_plan>[\t ]*\r?\n[\s\S]*?\r?\n<\/proposed_plan>[\t ]*$/gm;
81
- function parseProposedPlan(text) {
82
- const openingCount = text.match(/<proposed_plan>/gi)?.length ?? 0;
83
- const closingCount = text.match(/<\/proposed_plan>/gi)?.length ?? 0;
84
- if (openingCount === 0 && closingCount === 0) return { kind: "absent" };
85
- if (openingCount > 1 || closingCount > 1) return { kind: "multiple" };
86
- if (openingCount === 1 && closingCount === 0) return { kind: "unclosed" };
87
- if (openingCount !== 1 || closingCount !== 1) return { kind: "malformed" };
88
- const matches = Array.from(text.matchAll(PROPOSED_PLAN_PATTERN));
89
- if (matches.length !== 1) return { kind: "malformed" };
90
- const plan = matches[0]?.[1]?.trim() ?? "";
91
- return plan ? { kind: "valid", plan } : { kind: "empty" };
92
- }
93
- function invalidPlanMessage(kind) {
94
- const detail = {
95
- empty: "the block is empty",
96
- multiple: "more than one plan block was produced",
97
- malformed: "the tags must be on their own lines",
98
- unclosed: "the closing tag is missing"
99
- }[kind];
100
- return `Proposed plan is not ready: ${detail}. Continue Plan mode and produce one complete non-empty <proposed_plan> block.`;
101
- }
102
- function latestAssistantText(messages) {
103
- if (!Array.isArray(messages)) return "";
104
- for (const entry of [...messages].reverse()) {
105
- const message = entry?.message ?? entry;
106
- if (message?.role !== "assistant") continue;
107
- const text = messageText(message);
108
- if (text) return text;
109
- }
110
- return "";
111
- }
112
- function latestAssistantStopReason(messages) {
113
- if (!Array.isArray(messages)) return void 0;
114
- for (const entry of [...messages].reverse()) {
115
- const message = entry?.message ?? entry;
116
- if (message?.role === "assistant") return message.stopReason;
117
- }
118
- return void 0;
119
- }
120
- function messageTextContent(message) {
121
- return messageText(
122
- message?.message ?? message
123
- );
124
- }
125
- function messageContainsLegacyPlanModeContextArtifact(message) {
126
- return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;
127
- }
128
- function messageContainsPlanModeImplementationContextArtifact(message) {
129
- return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;
130
- }
131
- function injectActiveImplementationContext(messages, activeImplementation) {
132
- let foundCurrentContext = false;
133
- let foundCurrentHandoff = false;
134
- const expectedContext = activeImplementationContextContent(activeImplementation);
135
- const messagesWithoutStaleContext = messages.filter((message) => {
136
- if (messageContainsPlanModeImplementationContextArtifact(message)) {
137
- const candidate = unwrapSessionMessage(message);
138
- if (!foundCurrentContext && candidate.content === expectedContext) {
139
- foundCurrentContext = true;
140
- return true;
141
- }
142
- return false;
143
- }
144
- if (!messageContainsPlanModeImplementationHandoff(message)) return true;
145
- if (!foundCurrentHandoff && messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)) {
146
- foundCurrentHandoff = true;
147
- return true;
148
- }
149
- return false;
73
+ // src/implementation-preferences.ts
74
+ function observeImplementationModelSelections(pi) {
75
+ let latest;
76
+ pi.on("model_select", (_event, ctx) => {
77
+ latest = { model: ctx.model, thinking: pi.getThinkingLevel() };
150
78
  });
151
- if (foundCurrentHandoff || foundCurrentContext) return messagesWithoutStaleContext;
152
- let insertionIndex = 0;
153
- while (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;
154
- const contextMessage = {
155
- role: "custom",
156
- customType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,
157
- content: expectedContext,
158
- display: false,
159
- timestamp: activeImplementation.startedAt
160
- };
161
- return [
162
- ...messagesWithoutStaleContext.slice(0, insertionIndex),
163
- contextMessage,
164
- ...messagesWithoutStaleContext.slice(insertionIndex)
165
- ];
166
- }
167
- function activeImplementationContextContent(activeImplementation) {
168
- return `[ACTIVE IMPLEMENTATION PLAN]
169
-
170
- The user approved the exact implementation plan below. Continue following it until the user explicitly clears or supersedes it. The exact plan is the remainder of this message:
171
-
172
- ${activeImplementation.plan}`;
173
- }
174
- function messageContainsInactivePlanModeArtifact(message) {
175
- const candidate = unwrapSessionMessage(message);
176
- return candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE || candidate.role === "toolResult" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
177
- }
178
- function findHistoryImplementationArtifact(messages) {
179
- for (let index = messages.length - 1; index >= 0; index -= 1) {
180
- const candidate = unwrapSessionMessage(messages[index]);
181
- if (candidate.role !== "user" || contentText(candidate.content).trim() !== PLAN_HISTORY_IMPLEMENTATION_PROMPT) {
182
- continue;
183
- }
184
- const artifact = findHistoryImplementationArtifactBeforeKickoff(messages, index);
185
- if (artifact) return artifact;
186
- }
187
- return void 0;
188
- }
189
- function findHistoryImplementationArtifactBeforeKickoff(messages, kickoffIndex) {
190
- for (let index = kickoffIndex - 1; index >= 0; index -= 1) {
191
- const candidate = unwrapSessionMessage(messages[index]);
192
- if (candidate.role === "user" || isSummaryMessage(messages[index])) return void 0;
193
- if (candidate.role === "toolResult" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME) {
194
- const toolCallId = candidate.toolCallId;
195
- const toolCallMessageIndex = toolCallId ? findPlanModeCompletionCallMessageIndex(messages, index, toolCallId) : void 0;
196
- if (toolCallId && toolCallMessageIndex !== void 0) {
197
- return {
198
- messageIndex: index,
199
- kind: "completion",
200
- toolCallId,
201
- toolCallMessageIndex
202
- };
203
- }
204
- continue;
205
- }
206
- if (candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE) {
207
- return { messageIndex: index, kind: "presentation" };
208
- }
209
- if (candidate.role === "assistant" && contentText(candidate.content).match(PROPOSED_PLAN_BLOCK_PATTERN)) {
210
- return { messageIndex: index, kind: "legacy" };
211
- }
212
- }
213
- return void 0;
79
+ return () => latest;
214
80
  }
215
- function findPlanModeCompletionCallMessageIndex(messages, endIndex, toolCallId) {
216
- for (let index = endIndex - 1; index >= 0; index -= 1) {
217
- const candidate = unwrapSessionMessage(messages[index]);
218
- if (candidate.role === "user" || isSummaryMessage(messages[index])) return void 0;
219
- if (!Array.isArray(candidate.content)) continue;
220
- if (candidate.content.some((block) => {
221
- const toolCall = block;
222
- return toolCall.type === "toolCall" && toolCall.id === toolCallId && toolCall.name === PLAN_MODE_COMPLETE_TOOL_NAME;
223
- })) {
224
- return index;
225
- }
226
- }
227
- return void 0;
81
+ function hasImplementationPreferences(preferences) {
82
+ return preferences.implementationModel !== void 0 || preferences.implementationThinkingLevel !== void 0 && preferences.implementationThinkingLevel !== "inherit";
228
83
  }
229
- function messageContainsPlanModeImplementationHandoff(message) {
230
- const candidate = unwrapSessionMessage(message);
231
- return candidate.role === "user" && contentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX);
84
+ function sameModel(left, right) {
85
+ return left?.provider === right?.provider && left?.id === right?.id;
232
86
  }
233
- function messageContainsExactPlanModeImplementationHandoff(message, plan) {
234
- const candidate = unwrapSessionMessage(message);
235
- if (candidate.role !== "user") return false;
236
- return contentText(candidate.content).trim() === `${PLAN_IMPLEMENTATION_HANDOFF_PREFIX}
237
-
238
- ${plan}`.trim();
239
- }
240
- function isSummaryMessage(message) {
241
- const role = unwrapSessionMessage(message)?.role;
242
- return role === "compactionSummary" || role === "branchSummary";
87
+ function safeImplementationText(value) {
88
+ return [...value].map((character) => {
89
+ const code = character.codePointAt(0) ?? 0;
90
+ return code <= 31 || code >= 127 && code <= 159 ? " " : character;
91
+ }).join("").trim();
243
92
  }
244
- function stripProposedPlanBlocksFromMessage(message) {
245
- return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);
246
- }
247
- function stripPlanModeCompletionCallsFromMessage(message, preservedToolCallId) {
248
- return replaceAssistantContent(message, (content) => {
249
- if (!Array.isArray(content)) return content;
250
- const nextContent = content.filter((block) => {
251
- const candidate = block;
252
- return !(candidate.type === "toolCall" && candidate.name === PLAN_MODE_COMPLETE_TOOL_NAME && (!preservedToolCallId || candidate.id !== preservedToolCallId));
253
- });
254
- return nextContent.length === content.length ? content : nextContent;
255
- });
256
- }
257
- function isEmptyAssistantMessage(message) {
258
- const candidate = unwrapSessionMessage(message);
259
- return candidate.role === "assistant" && Array.isArray(candidate.content) && candidate.content.length === 0;
93
+ function preferenceError(error) {
94
+ return safeImplementationText(error instanceof Error ? error.message : String(error)).slice(
95
+ 0,
96
+ 500
97
+ );
260
98
  }
261
- function replaceAssistantContent(message, transform) {
262
- const candidate = unwrapSessionMessage(message);
263
- if (candidate.role !== "assistant") return message;
264
- const content = transform(candidate.content);
265
- if (content === candidate.content) return message;
266
- if (isSessionMessageEntry(message)) {
267
- return { ...message, message: { ...candidate, content } };
99
+ async function preflightImplementationPreferences(ctx, preferences, isCurrent) {
100
+ if (!isCurrent()) return void 0;
101
+ const identity = preferences.implementationModel;
102
+ const model = identity ? ctx.modelRegistry.find(identity.provider, identity.id) : ctx.model;
103
+ if (!model)
104
+ throw new Error(
105
+ "Implementation model is unavailable. Select a registered model or use current."
106
+ );
107
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
108
+ if (!isCurrent()) return void 0;
109
+ const currentModel = identity ? ctx.modelRegistry.find(identity.provider, identity.id) : model;
110
+ if (!currentModel) {
111
+ throw new Error(
112
+ "Implementation model catalogue changed during preflight. Reopen the menu and retry."
113
+ );
268
114
  }
269
- return { ...candidate, content };
270
- }
271
- function unwrapSessionMessage(message) {
272
- const entry = message;
273
- return entry?.message ?? message ?? {};
115
+ if (!auth.ok) throw new Error(auth.error);
116
+ return currentModel;
274
117
  }
275
- function isSessionMessageEntry(message) {
276
- return typeof message === "object" && message !== null && "message" in message;
277
- }
278
- function stripProposedPlanBlocksFromContent(content) {
279
- if (typeof content === "string") return stripProposedPlanBlocks(content);
280
- if (!Array.isArray(content)) return content;
281
- let changed = false;
282
- const nextContent = content.map((block) => {
283
- const textBlock = block;
284
- if (textBlock.type !== "text" || typeof textBlock.text !== "string") return block;
285
- const text = stripProposedPlanBlocks(textBlock.text);
286
- if (text === textBlock.text) return block;
287
- changed = true;
288
- return { ...textBlock, text };
118
+ function createImplementationPreferenceChange(pi, ctx, isSessionCurrent, original = { model: ctx.model, thinking: pi.getThinkingLevel() }, selectionSnapshot) {
119
+ let applied;
120
+ const snapshot = () => ({
121
+ model: ctx.model,
122
+ thinking: pi.getThinkingLevel()
289
123
  });
290
- return changed ? nextContent : content;
291
- }
292
- function stripProposedPlanBlocks(text) {
293
- return text.replace(PROPOSED_PLAN_BLOCK_PATTERN, "");
294
- }
295
- function messageText(message) {
296
- return contentText(message.content);
297
- }
298
- function contentText(content) {
299
- if (typeof content === "string") return content;
300
- if (!Array.isArray(content)) return "";
301
- return content.map((block) => {
302
- const textBlock = block;
303
- return textBlock.type === "text" && typeof textBlock.text === "string" ? textBlock.text : "";
304
- }).filter(Boolean).join("\n");
305
- }
306
-
307
- // src/implementation-retention.ts
308
- function retentionLabel(retention) {
309
- return {
310
- "clear-on-start": "Off \u2014 conversation history only",
311
- "clear-after-first-run": "Through first implementation run",
312
- keep: "Until manually cleared"
313
- }[retention];
314
- }
315
- function implementationRetentionPreview(retention) {
124
+ const matches = (value) => sameModel(ctx.model, value.model) && pi.getThinkingLevel() === value.thinking;
316
125
  return {
317
- "clear-on-start": "Plan reinjection: Off; use conversation history only.",
318
- "clear-after-first-run": "Plan reinjection: Through the first implementation run.",
319
- keep: "Plan reinjection: Until /plan exit."
320
- }[retention];
321
- }
322
- function createImplementationRetentionCoordinator() {
323
- let implementationWithDeliveredContext;
324
- let restoredImplementationAwaitingContext;
325
- return {
326
- restore(activeImplementation) {
327
- restoredImplementationAwaitingContext = activeImplementation && activeImplementation.retention !== "keep" ? activeImplementation.id : void 0;
328
- },
329
- transformContext(messages, state) {
330
- const messagesWithoutLegacyContext = messages.filter(
331
- (message) => !messageContainsLegacyPlanModeContextArtifact(message)
332
- );
333
- if (state.enabled) {
334
- return {
335
- messages: messagesWithoutLegacyContext.filter(
336
- (message) => !messageContainsPlanModeImplementationContextArtifact(message) && !messageContainsPlanModeImplementationHandoff(message)
337
- )
338
- };
126
+ async apply(model, preferences, isCurrent) {
127
+ if (!isCurrent()) return false;
128
+ applied = snapshot();
129
+ if (preferences.implementationModel && !sameModel(ctx.model, model)) {
130
+ const beforeSelection = selectionSnapshot?.();
131
+ if (!await pi.setModel(model))
132
+ throw new Error("Implementation model authentication is unavailable.");
133
+ if (!isSessionCurrent()) return false;
134
+ if (!sameModel(ctx.model, model)) return false;
135
+ const selected = selectionSnapshot?.();
136
+ applied = selected && selected !== beforeSelection ? selected : snapshot();
137
+ if (!matches(applied)) {
138
+ if (ctx.hasUI)
139
+ ctx.ui.notify(
140
+ "Model or thinking changed during implementation preparation. The plan remains available; retry when ready.",
141
+ "warning"
142
+ );
143
+ return false;
144
+ }
145
+ if (!isCurrent()) return false;
339
146
  }
340
- const activeImplementation = state.activeImplementation;
341
- const inactiveMessages = activeImplementation ? messagesWithoutLegacyContext : messagesWithoutLegacyContext.filter(
342
- (message) => !messageContainsPlanModeImplementationContextArtifact(message) && !messageContainsPlanModeImplementationHandoff(message)
343
- );
344
- const historyArtifact = activeImplementation ? void 0 : findHistoryImplementationArtifact(inactiveMessages);
345
- const historyArtifactMessage = historyArtifact ? inactiveMessages[historyArtifact.messageIndex] : void 0;
346
- const historyToolCallMessage = historyArtifact?.toolCallMessageIndex !== void 0 ? inactiveMessages[historyArtifact.toolCallMessageIndex] : void 0;
347
- const filteredMessages = inactiveMessages.filter(
348
- (message) => message === historyArtifactMessage || !messageContainsInactivePlanModeArtifact(message)
349
- ).map(
350
- (message) => message === historyArtifactMessage && historyArtifact?.kind === "legacy" ? message : stripProposedPlanBlocksFromMessage(message)
351
- ).map(
352
- (message) => stripPlanModeCompletionCallsFromMessage(
353
- message,
354
- message === historyToolCallMessage ? historyArtifact?.toolCallId : void 0
355
- )
356
- ).filter((message) => !isEmptyAssistantMessage(message));
357
- if (!activeImplementation) return { messages: filteredMessages };
358
- const contextualMessages = injectActiveImplementationContext(
359
- filteredMessages,
360
- activeImplementation
361
- );
362
- const deliveredCurrentHandoff = restoredImplementationAwaitingContext === activeImplementation.id || filteredMessages.some(
363
- (message) => messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)
364
- );
365
- if (!deliveredCurrentHandoff) return { messages: contextualMessages };
366
- restoredImplementationAwaitingContext = void 0;
367
- if (activeImplementation.retention === "clear-after-first-run") {
368
- implementationWithDeliveredContext = activeImplementation.id;
147
+ const level = preferences.implementationThinkingLevel;
148
+ if (level && level !== "inherit") {
149
+ pi.setThinkingLevel(level);
150
+ applied = snapshot();
151
+ if (applied.thinking !== level && ctx.hasUI)
152
+ ctx.ui.notify(
153
+ `Implementation thinking: ${applied.thinking} (requested ${level}; adjusted by Pi for this model).`,
154
+ "info"
155
+ );
369
156
  }
370
- return {
371
- messages: contextualMessages,
372
- clearActiveImplementationId: activeImplementation.retention === "clear-on-start" ? activeImplementation.id : void 0
373
- };
157
+ return isCurrent();
374
158
  },
375
- implementationSettled(activeImplementation) {
376
- if (activeImplementation?.retention !== "clear-after-first-run" || implementationWithDeliveredContext !== activeImplementation.id) {
377
- return void 0;
159
+ async rollback() {
160
+ if (!applied || !isSessionCurrent() || !ctx.isIdle() || !matches(applied)) return;
161
+ if (!sameModel(ctx.model, original.model)) {
162
+ const beforeSelection = selectionSnapshot?.();
163
+ if (!original.model || !await pi.setModel(original.model)) {
164
+ throw new Error(
165
+ "Could not restore the previous model. The plan remains available; select a model before retrying."
166
+ );
167
+ }
168
+ if (!isSessionCurrent() || !ctx.isIdle() || !sameModel(ctx.model, original.model)) return;
169
+ const selected = selectionSnapshot?.();
170
+ if (selected && selected !== beforeSelection && !matches(selected)) return;
378
171
  }
379
- implementationWithDeliveredContext = void 0;
380
- return activeImplementation.id;
381
- },
382
- reset() {
383
- implementationWithDeliveredContext = void 0;
384
- restoredImplementationAwaitingContext = void 0;
172
+ pi.setThinkingLevel(original.thinking);
173
+ applied = void 0;
385
174
  }
386
175
  };
387
176
  }
@@ -482,6 +271,17 @@ function normalizePlanModeSettings(value) {
482
271
  const settings = {
483
272
  thinkingLevel
484
273
  };
274
+ if (Object.hasOwn(value, "implementationModel")) {
275
+ const model = Reflect.get(value, "implementationModel");
276
+ if (!isSettingsDocument(model) || !validModelIdentity(model.provider) || !validModelIdentity(model.id))
277
+ return void 0;
278
+ settings.implementationModel = { provider: model.provider, id: model.id };
279
+ }
280
+ if (Object.hasOwn(value, "implementationThinkingLevel")) {
281
+ const level = Reflect.get(value, "implementationThinkingLevel");
282
+ if (!PLAN_MODE_THINKING_LEVELS.includes(level)) return void 0;
283
+ settings.implementationThinkingLevel = level;
284
+ }
485
285
  if (Object.hasOwn(value, "defaultPlanTools")) {
486
286
  const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
487
287
  if (!defaultPlanTools) return void 0;
@@ -515,6 +315,9 @@ function normalizePlanModeSettings(value) {
515
315
  }
516
316
  return settings;
517
317
  }
318
+ function validModelIdentity(value) {
319
+ return typeof value === "string" && value.trim().length > 0 && value.length <= 4096;
320
+ }
518
321
  function normalizeToolNames(value) {
519
322
  if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim().length > 0)) {
520
323
  return void 0;
@@ -596,6 +399,13 @@ function updatePlanModeSettings(patch, options = {}) {
596
399
  const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
597
400
  const updated = { ...current };
598
401
  if (patch.thinkingLevel !== void 0) updated.thinkingLevel = patch.thinkingLevel;
402
+ if (patch.implementationModel === null) delete updated.implementationModel;
403
+ else if (patch.implementationModel !== void 0) {
404
+ const previous = isSettingsDocument(updated.implementationModel) ? updated.implementationModel : {};
405
+ updated.implementationModel = { ...previous, ...patch.implementationModel };
406
+ }
407
+ if (patch.implementationThinkingLevel !== void 0)
408
+ updated.implementationThinkingLevel = patch.implementationThinkingLevel;
599
409
  if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
600
410
  else if (patch.defaultPlanTools !== void 0) {
601
411
  updated.defaultPlanTools = [...patch.defaultPlanTools];
@@ -687,81 +497,397 @@ async function readSettingsContents(settingsPath) {
687
497
  if (bytesRead === 0) break;
688
498
  offset += bytesRead;
689
499
  }
690
- if (offset > MAX_SETTINGS_BYTES) {
691
- throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
500
+ if (offset > MAX_SETTINGS_BYTES) {
501
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
502
+ }
503
+ try {
504
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
505
+ buffer.subarray(0, offset)
506
+ );
507
+ } catch {
508
+ throw new Error("settings file is not valid UTF-8");
509
+ }
510
+ } finally {
511
+ await handle.close();
512
+ }
513
+ }
514
+ async function publishSettings(settingsPath, document, signal, beforeRename) {
515
+ signal?.throwIfAborted();
516
+ const contents = `${JSON.stringify(document, null, 2)}
517
+ `;
518
+ if (Buffer.byteLength(contents, "utf8") > MAX_SETTINGS_BYTES) {
519
+ throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);
520
+ }
521
+ const directory = dirname(settingsPath);
522
+ await mkdir(directory, { recursive: true });
523
+ signal?.throwIfAborted();
524
+ const temporaryPath = join(
525
+ directory,
526
+ `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`
527
+ );
528
+ try {
529
+ await writeFile(temporaryPath, contents, {
530
+ encoding: "utf8",
531
+ flag: "wx",
532
+ mode: 384,
533
+ signal
534
+ });
535
+ await beforeRename?.(temporaryPath, settingsPath);
536
+ signal?.throwIfAborted();
537
+ await rename(temporaryPath, settingsPath);
538
+ } finally {
539
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
540
+ }
541
+ }
542
+ function isSettingsDocument(value) {
543
+ return typeof value === "object" && value !== null && !Array.isArray(value);
544
+ }
545
+ async function pathExists(path) {
546
+ try {
547
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
548
+ await handle.close();
549
+ return true;
550
+ } catch (error) {
551
+ return !(isNodeError(error) && error.code === "ENOENT");
552
+ }
553
+ }
554
+ function invalidSettingsError(settingsPath, reason) {
555
+ return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);
556
+ }
557
+ function isNodeError(error) {
558
+ return error instanceof Error && "code" in error;
559
+ }
560
+ function safeReadError(error) {
561
+ if (isNodeError(error) && error.code === "ELOOP") return "settings path is not a regular file";
562
+ return error instanceof Error ? error.message : String(error);
563
+ }
564
+ function configuredThinkingLevel(settings) {
565
+ return settings.thinkingLevel === "inherit" ? void 0 : settings.thinkingLevel;
566
+ }
567
+ function configuredImplementationPlanRetention(settings) {
568
+ return settings.implementationPlanRetention ?? "clear-on-start";
569
+ }
570
+ function configuredPlanExportPath(settings) {
571
+ return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
572
+ }
573
+ function configuredPlanModeToggleShortcut(settings) {
574
+ return settings.toggleShortcut;
575
+ }
576
+
577
+ // src/message-transform.ts
578
+ var PLAN_CONTEXT_MESSAGE_TYPE = "plan-mode-context";
579
+ var PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE = "plan-mode-implementation-context";
580
+ var PROPOSED_PLAN_MESSAGE_TYPE = "proposed-plan";
581
+ var PLAN_IMPLEMENTATION_HANDOFF_PREFIX = "Plan mode is now disabled. Full tool access is restored. Implement this proposed plan now:";
582
+ var PLAN_HISTORY_IMPLEMENTATION_PROMPT = "Implement the plan.";
583
+ var PROPOSED_PLAN_PATTERN = /^<proposed_plan>[\t ]*\r?\n([\s\S]*?)\r?\n<\/proposed_plan>[\t ]*$/gm;
584
+ var PROPOSED_PLAN_BLOCK_PATTERN = /^<proposed_plan>[\t ]*\r?\n[\s\S]*?\r?\n<\/proposed_plan>[\t ]*$/gm;
585
+ function parseProposedPlan(text) {
586
+ const openingCount = text.match(/<proposed_plan>/gi)?.length ?? 0;
587
+ const closingCount = text.match(/<\/proposed_plan>/gi)?.length ?? 0;
588
+ if (openingCount === 0 && closingCount === 0) return { kind: "absent" };
589
+ if (openingCount > 1 || closingCount > 1) return { kind: "multiple" };
590
+ if (openingCount === 1 && closingCount === 0) return { kind: "unclosed" };
591
+ if (openingCount !== 1 || closingCount !== 1) return { kind: "malformed" };
592
+ const matches = Array.from(text.matchAll(PROPOSED_PLAN_PATTERN));
593
+ if (matches.length !== 1) return { kind: "malformed" };
594
+ const plan = matches[0]?.[1]?.trim() ?? "";
595
+ return plan ? { kind: "valid", plan } : { kind: "empty" };
596
+ }
597
+ function invalidPlanMessage(kind) {
598
+ const detail = {
599
+ empty: "the block is empty",
600
+ multiple: "more than one plan block was produced",
601
+ malformed: "the tags must be on their own lines",
602
+ unclosed: "the closing tag is missing"
603
+ }[kind];
604
+ return `Proposed plan is not ready: ${detail}. Continue Plan mode and produce one complete non-empty <proposed_plan> block.`;
605
+ }
606
+ function latestAssistantText(messages) {
607
+ if (!Array.isArray(messages)) return "";
608
+ for (const entry of [...messages].reverse()) {
609
+ const message = entry?.message ?? entry;
610
+ if (message?.role !== "assistant") continue;
611
+ const text = messageText(message);
612
+ if (text) return text;
613
+ }
614
+ return "";
615
+ }
616
+ function latestAssistantStopReason(messages) {
617
+ if (!Array.isArray(messages)) return void 0;
618
+ for (const entry of [...messages].reverse()) {
619
+ const message = entry?.message ?? entry;
620
+ if (message?.role === "assistant") return message.stopReason;
621
+ }
622
+ return void 0;
623
+ }
624
+ function messageTextContent(message) {
625
+ return messageText(
626
+ message?.message ?? message
627
+ );
628
+ }
629
+ function messageContainsLegacyPlanModeContextArtifact(message) {
630
+ return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;
631
+ }
632
+ function messageContainsPlanModeImplementationContextArtifact(message) {
633
+ return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;
634
+ }
635
+ function injectActiveImplementationContext(messages, activeImplementation) {
636
+ let foundCurrentContext = false;
637
+ let foundCurrentHandoff = false;
638
+ const expectedContext = activeImplementationContextContent(activeImplementation);
639
+ const messagesWithoutStaleContext = messages.filter((message) => {
640
+ if (messageContainsPlanModeImplementationContextArtifact(message)) {
641
+ const candidate = unwrapSessionMessage(message);
642
+ if (!foundCurrentContext && candidate.content === expectedContext) {
643
+ foundCurrentContext = true;
644
+ return true;
645
+ }
646
+ return false;
647
+ }
648
+ if (!messageContainsPlanModeImplementationHandoff(message)) return true;
649
+ if (!foundCurrentHandoff && messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)) {
650
+ foundCurrentHandoff = true;
651
+ return true;
652
+ }
653
+ return false;
654
+ });
655
+ if (foundCurrentHandoff || foundCurrentContext) return messagesWithoutStaleContext;
656
+ let insertionIndex = 0;
657
+ while (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;
658
+ const contextMessage = {
659
+ role: "custom",
660
+ customType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,
661
+ content: expectedContext,
662
+ display: false,
663
+ timestamp: activeImplementation.startedAt
664
+ };
665
+ return [
666
+ ...messagesWithoutStaleContext.slice(0, insertionIndex),
667
+ contextMessage,
668
+ ...messagesWithoutStaleContext.slice(insertionIndex)
669
+ ];
670
+ }
671
+ function activeImplementationContextContent(activeImplementation) {
672
+ return `[ACTIVE IMPLEMENTATION PLAN]
673
+
674
+ The user approved the exact implementation plan below. Continue following it until the user explicitly clears or supersedes it. The exact plan is the remainder of this message:
675
+
676
+ ${activeImplementation.plan}`;
677
+ }
678
+ function messageContainsInactivePlanModeArtifact(message) {
679
+ const candidate = unwrapSessionMessage(message);
680
+ return candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE || candidate.role === "toolResult" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
681
+ }
682
+ function findHistoryImplementationArtifact(messages) {
683
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
684
+ const candidate = unwrapSessionMessage(messages[index]);
685
+ if (candidate.role !== "user" || contentText(candidate.content).trim() !== PLAN_HISTORY_IMPLEMENTATION_PROMPT) {
686
+ continue;
687
+ }
688
+ const artifact = findHistoryImplementationArtifactBeforeKickoff(messages, index);
689
+ if (artifact) return artifact;
690
+ }
691
+ return void 0;
692
+ }
693
+ function findHistoryImplementationArtifactBeforeKickoff(messages, kickoffIndex) {
694
+ for (let index = kickoffIndex - 1; index >= 0; index -= 1) {
695
+ const candidate = unwrapSessionMessage(messages[index]);
696
+ if (candidate.role === "user" || isSummaryMessage(messages[index])) return void 0;
697
+ if (candidate.role === "toolResult" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME) {
698
+ const toolCallId = candidate.toolCallId;
699
+ const toolCallMessageIndex = toolCallId ? findPlanModeCompletionCallMessageIndex(messages, index, toolCallId) : void 0;
700
+ if (toolCallId && toolCallMessageIndex !== void 0) {
701
+ return {
702
+ messageIndex: index,
703
+ kind: "completion",
704
+ toolCallId,
705
+ toolCallMessageIndex
706
+ };
707
+ }
708
+ continue;
709
+ }
710
+ if (candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE) {
711
+ return { messageIndex: index, kind: "presentation" };
692
712
  }
693
- try {
694
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
695
- buffer.subarray(0, offset)
696
- );
697
- } catch {
698
- throw new Error("settings file is not valid UTF-8");
713
+ if (candidate.role === "assistant" && contentText(candidate.content).match(PROPOSED_PLAN_BLOCK_PATTERN)) {
714
+ return { messageIndex: index, kind: "legacy" };
699
715
  }
700
- } finally {
701
- await handle.close();
702
716
  }
717
+ return void 0;
703
718
  }
704
- async function publishSettings(settingsPath, document, signal, beforeRename) {
705
- signal?.throwIfAborted();
706
- const contents = `${JSON.stringify(document, null, 2)}
707
- `;
708
- if (Buffer.byteLength(contents, "utf8") > MAX_SETTINGS_BYTES) {
709
- throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);
719
+ function findPlanModeCompletionCallMessageIndex(messages, endIndex, toolCallId) {
720
+ for (let index = endIndex - 1; index >= 0; index -= 1) {
721
+ const candidate = unwrapSessionMessage(messages[index]);
722
+ if (candidate.role === "user" || isSummaryMessage(messages[index])) return void 0;
723
+ if (!Array.isArray(candidate.content)) continue;
724
+ if (candidate.content.some((block) => {
725
+ const toolCall = block;
726
+ return toolCall.type === "toolCall" && toolCall.id === toolCallId && toolCall.name === PLAN_MODE_COMPLETE_TOOL_NAME;
727
+ })) {
728
+ return index;
729
+ }
710
730
  }
711
- const directory = dirname(settingsPath);
712
- await mkdir(directory, { recursive: true });
713
- signal?.throwIfAborted();
714
- const temporaryPath = join(
715
- directory,
716
- `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`
717
- );
718
- try {
719
- await writeFile(temporaryPath, contents, {
720
- encoding: "utf8",
721
- flag: "wx",
722
- mode: 384,
723
- signal
731
+ return void 0;
732
+ }
733
+ function messageContainsPlanModeImplementationHandoff(message) {
734
+ const candidate = unwrapSessionMessage(message);
735
+ return candidate.role === "user" && contentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX);
736
+ }
737
+ function messageContainsExactPlanModeImplementationHandoff(message, plan) {
738
+ const candidate = unwrapSessionMessage(message);
739
+ if (candidate.role !== "user") return false;
740
+ return contentText(candidate.content).trim() === `${PLAN_IMPLEMENTATION_HANDOFF_PREFIX}
741
+
742
+ ${plan}`.trim();
743
+ }
744
+ function isSummaryMessage(message) {
745
+ const role = unwrapSessionMessage(message)?.role;
746
+ return role === "compactionSummary" || role === "branchSummary";
747
+ }
748
+ function stripProposedPlanBlocksFromMessage(message) {
749
+ return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);
750
+ }
751
+ function stripPlanModeCompletionCallsFromMessage(message, preservedToolCallId) {
752
+ return replaceAssistantContent(message, (content) => {
753
+ if (!Array.isArray(content)) return content;
754
+ const nextContent = content.filter((block) => {
755
+ const candidate = block;
756
+ return !(candidate.type === "toolCall" && candidate.name === PLAN_MODE_COMPLETE_TOOL_NAME && (!preservedToolCallId || candidate.id !== preservedToolCallId));
724
757
  });
725
- await beforeRename?.(temporaryPath, settingsPath);
726
- signal?.throwIfAborted();
727
- await rename(temporaryPath, settingsPath);
728
- } finally {
729
- await rm(temporaryPath, { force: true }).catch(() => void 0);
730
- }
758
+ return nextContent.length === content.length ? content : nextContent;
759
+ });
731
760
  }
732
- function isSettingsDocument(value) {
733
- return typeof value === "object" && value !== null && !Array.isArray(value);
761
+ function isEmptyAssistantMessage(message) {
762
+ const candidate = unwrapSessionMessage(message);
763
+ return candidate.role === "assistant" && Array.isArray(candidate.content) && candidate.content.length === 0;
734
764
  }
735
- async function pathExists(path) {
736
- try {
737
- const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
738
- await handle.close();
739
- return true;
740
- } catch (error) {
741
- return !(isNodeError(error) && error.code === "ENOENT");
765
+ function replaceAssistantContent(message, transform) {
766
+ const candidate = unwrapSessionMessage(message);
767
+ if (candidate.role !== "assistant") return message;
768
+ const content = transform(candidate.content);
769
+ if (content === candidate.content) return message;
770
+ if (isSessionMessageEntry(message)) {
771
+ return { ...message, message: { ...candidate, content } };
742
772
  }
773
+ return { ...candidate, content };
743
774
  }
744
- function invalidSettingsError(settingsPath, reason) {
745
- return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);
775
+ function unwrapSessionMessage(message) {
776
+ const entry = message;
777
+ return entry?.message ?? message ?? {};
746
778
  }
747
- function isNodeError(error) {
748
- return error instanceof Error && "code" in error;
779
+ function isSessionMessageEntry(message) {
780
+ return typeof message === "object" && message !== null && "message" in message;
749
781
  }
750
- function safeReadError(error) {
751
- if (isNodeError(error) && error.code === "ELOOP") return "settings path is not a regular file";
752
- return error instanceof Error ? error.message : String(error);
782
+ function stripProposedPlanBlocksFromContent(content) {
783
+ if (typeof content === "string") return stripProposedPlanBlocks(content);
784
+ if (!Array.isArray(content)) return content;
785
+ let changed = false;
786
+ const nextContent = content.map((block) => {
787
+ const textBlock = block;
788
+ if (textBlock.type !== "text" || typeof textBlock.text !== "string") return block;
789
+ const text = stripProposedPlanBlocks(textBlock.text);
790
+ if (text === textBlock.text) return block;
791
+ changed = true;
792
+ return { ...textBlock, text };
793
+ });
794
+ return changed ? nextContent : content;
753
795
  }
754
- function configuredThinkingLevel(settings) {
755
- return settings.thinkingLevel === "inherit" ? void 0 : settings.thinkingLevel;
796
+ function stripProposedPlanBlocks(text) {
797
+ return text.replace(PROPOSED_PLAN_BLOCK_PATTERN, "");
756
798
  }
757
- function configuredImplementationPlanRetention(settings) {
758
- return settings.implementationPlanRetention ?? "clear-on-start";
799
+ function messageText(message) {
800
+ return contentText(message.content);
759
801
  }
760
- function configuredPlanExportPath(settings) {
761
- return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
802
+ function contentText(content) {
803
+ if (typeof content === "string") return content;
804
+ if (!Array.isArray(content)) return "";
805
+ return content.map((block) => {
806
+ const textBlock = block;
807
+ return textBlock.type === "text" && typeof textBlock.text === "string" ? textBlock.text : "";
808
+ }).filter(Boolean).join("\n");
762
809
  }
763
- function configuredPlanModeToggleShortcut(settings) {
764
- return settings.toggleShortcut;
810
+
811
+ // src/implementation-retention.ts
812
+ function retentionLabel(retention) {
813
+ return {
814
+ "clear-on-start": "Off \u2014 conversation history only",
815
+ "clear-after-first-run": "Through first implementation run",
816
+ keep: "Until manually cleared"
817
+ }[retention];
818
+ }
819
+ function implementationRetentionPreview(retention) {
820
+ return {
821
+ "clear-on-start": "Plan reinjection: Off; use conversation history only.",
822
+ "clear-after-first-run": "Plan reinjection: Through the first implementation run.",
823
+ keep: "Plan reinjection: Until /plan exit."
824
+ }[retention];
825
+ }
826
+ function createImplementationRetentionCoordinator() {
827
+ let implementationWithDeliveredContext;
828
+ let restoredImplementationAwaitingContext;
829
+ return {
830
+ restore(activeImplementation) {
831
+ restoredImplementationAwaitingContext = activeImplementation && activeImplementation.retention !== "keep" ? activeImplementation.id : void 0;
832
+ },
833
+ transformContext(messages, state) {
834
+ const messagesWithoutLegacyContext = messages.filter(
835
+ (message) => !messageContainsLegacyPlanModeContextArtifact(message)
836
+ );
837
+ if (state.enabled) {
838
+ return {
839
+ messages: messagesWithoutLegacyContext.filter(
840
+ (message) => !messageContainsPlanModeImplementationContextArtifact(message) && !messageContainsPlanModeImplementationHandoff(message)
841
+ )
842
+ };
843
+ }
844
+ const activeImplementation = state.activeImplementation;
845
+ const inactiveMessages = activeImplementation ? messagesWithoutLegacyContext : messagesWithoutLegacyContext.filter(
846
+ (message) => !messageContainsPlanModeImplementationContextArtifact(message) && !messageContainsPlanModeImplementationHandoff(message)
847
+ );
848
+ const historyArtifact = activeImplementation ? void 0 : findHistoryImplementationArtifact(inactiveMessages);
849
+ const historyArtifactMessage = historyArtifact ? inactiveMessages[historyArtifact.messageIndex] : void 0;
850
+ const historyToolCallMessage = historyArtifact?.toolCallMessageIndex !== void 0 ? inactiveMessages[historyArtifact.toolCallMessageIndex] : void 0;
851
+ const filteredMessages = inactiveMessages.filter(
852
+ (message) => message === historyArtifactMessage || !messageContainsInactivePlanModeArtifact(message)
853
+ ).map(
854
+ (message) => message === historyArtifactMessage && historyArtifact?.kind === "legacy" ? message : stripProposedPlanBlocksFromMessage(message)
855
+ ).map(
856
+ (message) => stripPlanModeCompletionCallsFromMessage(
857
+ message,
858
+ message === historyToolCallMessage ? historyArtifact?.toolCallId : void 0
859
+ )
860
+ ).filter((message) => !isEmptyAssistantMessage(message));
861
+ if (!activeImplementation) return { messages: filteredMessages };
862
+ const contextualMessages = injectActiveImplementationContext(
863
+ filteredMessages,
864
+ activeImplementation
865
+ );
866
+ const deliveredCurrentHandoff = restoredImplementationAwaitingContext === activeImplementation.id || filteredMessages.some(
867
+ (message) => messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)
868
+ );
869
+ if (!deliveredCurrentHandoff) return { messages: contextualMessages };
870
+ restoredImplementationAwaitingContext = void 0;
871
+ if (activeImplementation.retention === "clear-after-first-run") {
872
+ implementationWithDeliveredContext = activeImplementation.id;
873
+ }
874
+ return {
875
+ messages: contextualMessages,
876
+ clearActiveImplementationId: activeImplementation.retention === "clear-on-start" ? activeImplementation.id : void 0
877
+ };
878
+ },
879
+ implementationSettled(activeImplementation) {
880
+ if (activeImplementation?.retention !== "clear-after-first-run" || implementationWithDeliveredContext !== activeImplementation.id) {
881
+ return void 0;
882
+ }
883
+ implementationWithDeliveredContext = void 0;
884
+ return activeImplementation.id;
885
+ },
886
+ reset() {
887
+ implementationWithDeliveredContext = void 0;
888
+ restoredImplementationAwaitingContext = void 0;
889
+ }
890
+ };
765
891
  }
766
892
 
767
893
  // src/plan-export.ts
@@ -1765,18 +1891,17 @@ export {
1765
1891
  planFromCompletionDetails,
1766
1892
  planModeCompleted,
1767
1893
  renderPlanModeCompletion,
1768
- PLAN_HISTORY_IMPLEMENTATION_PROMPT,
1769
- parseProposedPlan,
1770
- invalidPlanMessage,
1771
- latestAssistantText,
1772
- latestAssistantStopReason,
1773
- messageTextContent,
1774
- retentionLabel,
1775
- implementationRetentionPreview,
1776
- createImplementationRetentionCoordinator,
1894
+ observeImplementationModelSelections,
1895
+ hasImplementationPreferences,
1896
+ sameModel,
1897
+ safeImplementationText,
1898
+ preferenceError,
1899
+ preflightImplementationPreferences,
1900
+ createImplementationPreferenceChange,
1777
1901
  PLAN_MODE_THINKING_LEVELS,
1778
1902
  IMPLEMENTATION_PLAN_RETENTIONS,
1779
1903
  planModeSettingsPath,
1904
+ normalizePlanModeSettings,
1780
1905
  normalizeKeyId,
1781
1906
  readPlanModeSettings,
1782
1907
  updatePlanModeSettings,
@@ -1785,6 +1910,15 @@ export {
1785
1910
  configuredImplementationPlanRetention,
1786
1911
  configuredPlanExportPath,
1787
1912
  configuredPlanModeToggleShortcut,
1913
+ PLAN_HISTORY_IMPLEMENTATION_PROMPT,
1914
+ parseProposedPlan,
1915
+ invalidPlanMessage,
1916
+ latestAssistantText,
1917
+ latestAssistantStopReason,
1918
+ messageTextContent,
1919
+ retentionLabel,
1920
+ implementationRetentionPreview,
1921
+ createImplementationRetentionCoordinator,
1788
1922
  exportStoredPlan,
1789
1923
  planExportDestination,
1790
1924
  PLAN_MODE_QUESTION_TOOL_NAME,
@@ -1802,4 +1936,4 @@ export {
1802
1936
  defaultPlanModeToolNames,
1803
1937
  snapshotPlanModeSelectedNames
1804
1938
  };
1805
- //# sourceMappingURL=chunk-57OBPS7P.js.map
1939
+ //# sourceMappingURL=chunk-YUFPCQVG.js.map