@narumitw/pi-plan-mode 0.55.3 → 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,1578 +70,1779 @@ 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" };
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() };
78
+ });
79
+ return () => latest;
92
80
  }
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.`;
81
+ function hasImplementationPreferences(preferences) {
82
+ return preferences.implementationModel !== void 0 || preferences.implementationThinkingLevel !== void 0 && preferences.implementationThinkingLevel !== "inherit";
101
83
  }
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 "";
84
+ function sameModel(left, right) {
85
+ return left?.provider === right?.provider && left?.id === right?.id;
111
86
  }
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;
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();
119
92
  }
120
- function messageTextContent(message) {
121
- return messageText(
122
- message?.message ?? message
93
+ function preferenceError(error) {
94
+ return safeImplementationText(error instanceof Error ? error.message : String(error)).slice(
95
+ 0,
96
+ 500
123
97
  );
124
98
  }
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;
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
+ );
114
+ }
115
+ if (!auth.ok) throw new Error(auth.error);
116
+ return currentModel;
130
117
  }
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;
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()
123
+ });
124
+ const matches = (value) => sameModel(ctx.model, value.model) && pi.getThinkingLevel() === value.thinking;
125
+ return {
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;
141
146
  }
142
- return false;
143
- }
144
- if (!messageContainsPlanModeImplementationHandoff(message)) return true;
145
- if (!foundCurrentHandoff && messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)) {
146
- foundCurrentHandoff = true;
147
- return true;
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
+ );
156
+ }
157
+ return isCurrent();
158
+ },
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;
171
+ }
172
+ pi.setThinkingLevel(original.thinking);
173
+ applied = void 0;
148
174
  }
149
- return false;
150
- });
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
175
  };
161
- return [
162
- ...messagesWithoutStaleContext.slice(0, insertionIndex),
163
- contextMessage,
164
- ...messagesWithoutStaleContext.slice(insertionIndex)
165
- ];
166
176
  }
167
- function activeImplementationContextContent(activeImplementation) {
168
- return `[ACTIVE IMPLEMENTATION PLAN]
169
177
 
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}`;
178
+ // src/settings.ts
179
+ import { randomUUID } from "node:crypto";
180
+ import { constants } from "node:fs";
181
+ import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
182
+ import { basename, dirname, join } from "node:path";
183
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
184
+ var PLAN_MODE_SETTINGS_FILE = "pi-plan-mode.json";
185
+ var LEGACY_PLAN_MODE_SETTINGS_FILE = "plan-mode.json";
186
+ var MAX_SETTINGS_BYTES = 64 * 1024;
187
+ var PLAN_MODE_THINKING_LEVELS = [
188
+ "inherit",
189
+ "off",
190
+ "minimal",
191
+ "low",
192
+ "medium",
193
+ "high",
194
+ "xhigh",
195
+ "max"
196
+ ];
197
+ var IMPLEMENTATION_PLAN_RETENTIONS = [
198
+ "clear-on-start",
199
+ "clear-after-first-run",
200
+ "keep"
201
+ ];
202
+ var DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
203
+ var MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]);
204
+ var BASE_KEYS = /* @__PURE__ */ new Set([
205
+ ..."abcdefghijklmnopqrstuvwxyz0123456789",
206
+ "`",
207
+ "-",
208
+ "=",
209
+ "[",
210
+ "]",
211
+ "\\",
212
+ ";",
213
+ "'",
214
+ ",",
215
+ ".",
216
+ "/",
217
+ "!",
218
+ "@",
219
+ "#",
220
+ "$",
221
+ "%",
222
+ "^",
223
+ "&",
224
+ "*",
225
+ "(",
226
+ ")",
227
+ "_",
228
+ "+",
229
+ "|",
230
+ "~",
231
+ "{",
232
+ "}",
233
+ ":",
234
+ "<",
235
+ ">",
236
+ "?",
237
+ "escape",
238
+ "esc",
239
+ "enter",
240
+ "return",
241
+ "tab",
242
+ "space",
243
+ "backspace",
244
+ "delete",
245
+ "insert",
246
+ "clear",
247
+ "home",
248
+ "end",
249
+ "pageup",
250
+ "pagedown",
251
+ "up",
252
+ "down",
253
+ "left",
254
+ "right",
255
+ ...Array.from({ length: 12 }, (_unused, index) => `f${index + 1}`)
256
+ ]);
257
+ var MAX_PLAN_EXPORT_PATH_LENGTH = 4096;
258
+ var mutationQueues = /* @__PURE__ */ new Map();
259
+ function planModeSettingsPath() {
260
+ return join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);
173
261
  }
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;
262
+ function legacyPlanModeSettingsPath() {
263
+ return join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);
177
264
  }
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;
265
+ function normalizePlanModeSettings(value) {
266
+ if (!isSettingsDocument(value)) return void 0;
267
+ const thinkingLevel = Object.hasOwn(value, "thinkingLevel") ? Reflect.get(value, "thinkingLevel") : "inherit";
268
+ if (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel)) {
269
+ return void 0;
186
270
  }
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
- }
271
+ const settings = {
272
+ thinkingLevel
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 };
212
279
  }
213
- return void 0;
214
- }
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;
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
+ }
285
+ if (Object.hasOwn(value, "defaultPlanTools")) {
286
+ const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
287
+ if (!defaultPlanTools) return void 0;
288
+ settings.defaultPlanTools = defaultPlanTools;
289
+ }
290
+ if (Object.hasOwn(value, "implementationPlanRetention")) {
291
+ const implementationPlanRetention = Reflect.get(value, "implementationPlanRetention");
292
+ if (!IMPLEMENTATION_PLAN_RETENTIONS.includes(
293
+ implementationPlanRetention
294
+ )) {
295
+ return void 0;
225
296
  }
297
+ settings.implementationPlanRetention = implementationPlanRetention;
226
298
  }
227
- return void 0;
228
- }
229
- function messageContainsPlanModeImplementationHandoff(message) {
230
- const candidate = unwrapSessionMessage(message);
231
- return candidate.role === "user" && contentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX);
299
+ if (Object.hasOwn(value, "defaultPlanExportPath")) {
300
+ const defaultPlanExportPath = normalizePlanExportPath(
301
+ Reflect.get(value, "defaultPlanExportPath")
302
+ );
303
+ if (!defaultPlanExportPath) return void 0;
304
+ settings.defaultPlanExportPath = defaultPlanExportPath;
305
+ }
306
+ if (Object.hasOwn(value, "toggleShortcut")) {
307
+ const toggleShortcut = normalizeKeyId(Reflect.get(value, "toggleShortcut"));
308
+ if (!toggleShortcut) return void 0;
309
+ settings.toggleShortcut = toggleShortcut;
310
+ }
311
+ if (Object.hasOwn(value, "safeSubcommands")) {
312
+ const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, "safeSubcommands"));
313
+ if (!safeSubcommands) return void 0;
314
+ settings.safeSubcommands = safeSubcommands;
315
+ }
316
+ return settings;
232
317
  }
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();
318
+ function validModelIdentity(value) {
319
+ return typeof value === "string" && value.trim().length > 0 && value.length <= 4096;
239
320
  }
240
- function isSummaryMessage(message) {
241
- const role = unwrapSessionMessage(message)?.role;
242
- return role === "compactionSummary" || role === "branchSummary";
321
+ function normalizeToolNames(value) {
322
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim().length > 0)) {
323
+ return void 0;
324
+ }
325
+ return Array.from(new Set(value));
243
326
  }
244
- function stripProposedPlanBlocksFromMessage(message) {
245
- return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);
327
+ function normalizePlanExportPath(value) {
328
+ if (typeof value !== "string") return void 0;
329
+ const normalized = value.trim();
330
+ if (!normalized || normalized.length > MAX_PLAN_EXPORT_PATH_LENGTH || !/[^@\s]/u.test(normalized) || [...normalized].some((character) => {
331
+ const codePoint = character.codePointAt(0) ?? 0;
332
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
333
+ })) {
334
+ return void 0;
335
+ }
336
+ return normalized;
246
337
  }
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
- });
338
+ function normalizeKeyId(value) {
339
+ if (typeof value !== "string") return void 0;
340
+ const normalized = value.trim().toLowerCase();
341
+ const base = [...BASE_KEYS].sort((left, right) => right.length - left.length).find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));
342
+ if (!base) return void 0;
343
+ const prefix = normalized.slice(0, normalized.length - base.length);
344
+ if (!prefix) return base;
345
+ if (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith("+")) return void 0;
346
+ const modifiers = prefix.slice(0, -1).split("+");
347
+ if (modifiers.length === 0 || modifiers.some((modifier) => !MODIFIERS.has(modifier)) || new Set(modifiers).size !== modifiers.length) {
348
+ return void 0;
349
+ }
350
+ return normalized;
256
351
  }
257
- function isEmptyAssistantMessage(message) {
258
- const candidate = unwrapSessionMessage(message);
259
- return candidate.role === "assistant" && Array.isArray(candidate.content) && candidate.content.length === 0;
352
+ function normalizeSafeSubcommands(value) {
353
+ if (!isSettingsDocument(value)) return void 0;
354
+ const entries = [];
355
+ for (const [command, subcommands] of Object.entries(value)) {
356
+ const normalizedCommand = command.trim();
357
+ if (!normalizedCommand || !Array.isArray(subcommands) || !subcommands.every(
358
+ (item) => typeof item === "string" && item.trim().length > 0
359
+ )) {
360
+ return void 0;
361
+ }
362
+ const normalizedSubcommands = Array.from(
363
+ new Set(subcommands.map((subcommand) => subcommand.trim()))
364
+ );
365
+ const existing = entries.find(([existingCommand]) => existingCommand === normalizedCommand);
366
+ if (existing) existing[1] = Array.from(/* @__PURE__ */ new Set([...existing[1], ...normalizedSubcommands]));
367
+ else entries.push([normalizedCommand, normalizedSubcommands]);
368
+ }
369
+ return Object.fromEntries(entries);
260
370
  }
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 } };
371
+ async function readPlanModeSettings(settingsPath) {
372
+ if (settingsPath) {
373
+ await awaitPlanModeSettingsWrites(settingsPath);
374
+ return (await readSettingsSnapshot(settingsPath)).result;
268
375
  }
269
- return { ...candidate, content };
376
+ const canonicalPath = planModeSettingsPath();
377
+ await awaitPlanModeSettingsWrites(canonicalPath);
378
+ const canonical = await readSettingsSnapshot(canonicalPath);
379
+ const legacyPath = legacyPlanModeSettingsPath();
380
+ if (canonical.result.kind !== "missing") {
381
+ return await pathExists(legacyPath) ? {
382
+ ...canonical.result,
383
+ notice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`
384
+ } : canonical.result;
385
+ }
386
+ const legacy = await readSettingsSnapshot(legacyPath);
387
+ const raced = await readSettingsSnapshot(canonicalPath);
388
+ if (raced.result.kind !== "missing") return raced.result;
389
+ return legacy.result.kind === "loaded" ? {
390
+ ...legacy.result,
391
+ notice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`
392
+ } : legacy.result;
270
393
  }
271
- function unwrapSessionMessage(message) {
272
- const entry = message;
273
- return entry?.message ?? message ?? {};
394
+ function updatePlanModeSettings(patch, options = {}) {
395
+ const settingsPath = options.settingsPath ?? planModeSettingsPath();
396
+ const legacySettingsPath = options.legacySettingsPath ?? (options.settingsPath ? void 0 : legacyPlanModeSettingsPath());
397
+ return enqueueMutation(settingsPath, async () => {
398
+ options.signal?.throwIfAborted();
399
+ const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
400
+ const updated = { ...current };
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;
409
+ if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
410
+ else if (patch.defaultPlanTools !== void 0) {
411
+ updated.defaultPlanTools = [...patch.defaultPlanTools];
412
+ }
413
+ if (patch.implementationPlanRetention !== void 0) {
414
+ updated.implementationPlanRetention = patch.implementationPlanRetention;
415
+ }
416
+ if (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;
417
+ else if (patch.defaultPlanExportPath !== void 0) {
418
+ updated.defaultPlanExportPath = patch.defaultPlanExportPath;
419
+ }
420
+ if (patch.toggleShortcut === null) delete updated.toggleShortcut;
421
+ else if (patch.toggleShortcut !== void 0) {
422
+ updated.toggleShortcut = patch.toggleShortcut;
423
+ }
424
+ const settings = normalizePlanModeSettings(updated);
425
+ if (!settings) throw invalidSettingsError(settingsPath, "invalid settings shape");
426
+ await publishSettings(settingsPath, updated, options.signal, options.beforeRename);
427
+ return settings;
428
+ });
274
429
  }
275
- function isSessionMessageEntry(message) {
276
- return typeof message === "object" && message !== null && "message" in message;
430
+ async function awaitPlanModeSettingsWrites(settingsPath = planModeSettingsPath()) {
431
+ await mutationQueues.get(settingsPath);
277
432
  }
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 };
433
+ function enqueueMutation(settingsPath, mutation) {
434
+ const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();
435
+ const result = previous.then(mutation, mutation);
436
+ const settled = result.then(
437
+ () => void 0,
438
+ () => void 0
439
+ );
440
+ mutationQueues.set(settingsPath, settled);
441
+ void settled.finally(() => {
442
+ if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);
289
443
  });
290
- return changed ? nextContent : content;
291
- }
292
- function stripProposedPlanBlocks(text) {
293
- return text.replace(PROPOSED_PLAN_BLOCK_PATTERN, "");
444
+ return result;
294
445
  }
295
- function messageText(message) {
296
- return contentText(message.content);
446
+ async function readSettingsDocumentForUpdate(settingsPath, legacySettingsPath) {
447
+ const canonical = await readSettingsSnapshot(settingsPath);
448
+ if (canonical.result.kind === "loaded") return canonical.document ?? {};
449
+ if (canonical.result.kind === "invalid") {
450
+ throw invalidSettingsError(settingsPath, canonical.result.reason);
451
+ }
452
+ if (!legacySettingsPath) return {};
453
+ const legacy = await readSettingsSnapshot(legacySettingsPath);
454
+ const raced = await readSettingsSnapshot(settingsPath);
455
+ if (raced.result.kind === "loaded") return raced.document ?? {};
456
+ if (raced.result.kind === "invalid") {
457
+ throw invalidSettingsError(settingsPath, raced.result.reason);
458
+ }
459
+ if (legacy.result.kind === "invalid") {
460
+ throw invalidSettingsError(legacySettingsPath, legacy.result.reason);
461
+ }
462
+ return legacy.document ?? {};
297
463
  }
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");
464
+ async function readSettingsSnapshot(settingsPath) {
465
+ let contents;
466
+ try {
467
+ contents = await readSettingsContents(settingsPath);
468
+ } catch (error) {
469
+ if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
470
+ return { result: { kind: "invalid", reason: safeReadError(error) } };
471
+ }
472
+ let parsed;
473
+ try {
474
+ parsed = JSON.parse(contents);
475
+ } catch {
476
+ return { result: { kind: "invalid", reason: "invalid JSON" } };
477
+ }
478
+ const settings = normalizePlanModeSettings(parsed);
479
+ if (!settings || !isSettingsDocument(parsed)) {
480
+ return { result: { kind: "invalid", reason: "invalid settings shape" } };
481
+ }
482
+ return { document: parsed, result: { kind: "loaded", settings } };
305
483
  }
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];
484
+ async function readSettingsContents(settingsPath) {
485
+ const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);
486
+ const handle = await open(settingsPath, flags);
487
+ try {
488
+ const stats = await handle.stat();
489
+ if (!stats.isFile()) throw new Error("settings path is not a regular file");
490
+ if (stats.size > MAX_SETTINGS_BYTES) {
491
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
492
+ }
493
+ const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
494
+ let offset = 0;
495
+ while (offset < buffer.byteLength) {
496
+ const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);
497
+ if (bytesRead === 0) break;
498
+ offset += bytesRead;
499
+ }
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
+ }
314
513
  }
315
- function implementationRetentionPreview(retention) {
316
- 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
- };
339
- }
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;
369
- }
370
- return {
371
- messages: contextualMessages,
372
- clearActiveImplementationId: activeImplementation.retention === "clear-on-start" ? activeImplementation.id : void 0
373
- };
374
- },
375
- implementationSettled(activeImplementation) {
376
- if (activeImplementation?.retention !== "clear-after-first-run" || implementationWithDeliveredContext !== activeImplementation.id) {
377
- return void 0;
378
- }
379
- implementationWithDeliveredContext = void 0;
380
- return activeImplementation.id;
381
- },
382
- reset() {
383
- implementationWithDeliveredContext = void 0;
384
- restoredImplementationAwaitingContext = void 0;
385
- }
386
- };
387
- }
388
-
389
- // src/tool-policy.ts
390
- import { isAbsolute, normalize } from "node:path";
391
- var BUILTIN_SAFE_GIT_SUBCOMMANDS = [
392
- "status",
393
- "log",
394
- "diff",
395
- "show",
396
- "branch",
397
- "remote",
398
- "ls-files",
399
- "grep"
400
- ];
401
- var CONFIGURABLE_SAFE_GIT_SUBCOMMANDS = [
402
- "rev-parse",
403
- "blame",
404
- "describe",
405
- "merge-base",
406
- "ls-tree",
407
- "cat-file"
408
- ];
409
- var SAFE_GIT_SUBCOMMANDS = [
410
- ...BUILTIN_SAFE_GIT_SUBCOMMANDS,
411
- ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS
412
- ];
413
- var SAFE_GH_SUBCOMMAND_PATHS = ["pr view", "pr list", "issue view", "issue list"];
414
- var SAFE_BUILTIN_PLAN_TOOLS = /* @__PURE__ */ new Set([
415
- "read",
416
- "bash",
417
- "powershell",
418
- "grep",
419
- "find",
420
- "ls"
421
- ]);
422
- var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
423
- var MUTATING_COMMANDS = /* @__PURE__ */ new Set([
424
- "rm",
425
- "rmdir",
426
- "mv",
427
- "cp",
428
- "mkdir",
429
- "touch",
430
- "chmod",
431
- "chown",
432
- "chgrp",
433
- "ln",
434
- "tee",
435
- "truncate",
436
- "dd",
437
- "sudo",
438
- "su",
439
- "kill",
440
- "pkill",
441
- "killall",
442
- "reboot",
443
- "shutdown",
444
- "vim",
445
- "vi",
446
- "nano",
447
- "emacs",
448
- "code",
449
- "subl"
450
- ]);
451
- var READ_ONLY_POWERSHELL_COMMANDS = /* @__PURE__ */ new Set([
452
- "format-list",
453
- "format-table",
454
- "get-childitem",
455
- "get-content",
456
- "get-item",
457
- "get-location",
458
- "measure-object",
459
- "out-string",
460
- "resolve-path",
461
- "select-string",
462
- "sort-object",
463
- "test-path",
464
- "write-output"
465
- ]);
466
- var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
467
- "cat",
468
- "head",
469
- "tail",
470
- "grep",
471
- "find",
472
- "ls",
473
- "pwd",
474
- "echo",
475
- "printf",
476
- "wc",
477
- "sort",
478
- "uniq",
479
- "diff",
480
- "file",
481
- "stat",
482
- "du",
483
- "df",
484
- "tree",
485
- "which",
486
- "whereis",
487
- "type",
488
- "printenv",
489
- "uname",
490
- "whoami",
491
- "id",
492
- "date",
493
- "uptime",
494
- "ps",
495
- "jq",
496
- "rg",
497
- "fd",
498
- "bat",
499
- "eza"
500
- ]);
501
- function isBuiltinTool(tool) {
502
- return tool.sourceInfo.source === "builtin";
503
- }
504
- function classifyPlanModeTool(tool) {
505
- if (!isBuiltinTool(tool)) return "user-opt-in";
506
- if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return "blocked";
507
- if (tool.name === "bash" || tool.name === "powershell") return "limited";
508
- return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? "read-only" : "blocked";
509
- }
510
- function canSelectToolInPlanMode(tool) {
511
- return classifyPlanModeTool(tool) !== "blocked";
512
- }
513
- function readCommand(input) {
514
- const command = input;
515
- return typeof command?.command === "string" ? command.command : "";
516
- }
517
- function findBlockedCommandSegment(command, safeSubcommands = {}, workingDirectory) {
518
- const segments = splitShellSegments(command);
519
- if (!segments || segments.length === 0) return command.trim() || "(empty command)";
520
- return segments.find((segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory));
521
- }
522
- function findBlockedPowerShellCommandSegment(command, safeSubcommands = {}, workingDirectory) {
523
- const segments = splitPowerShellSegments(command);
524
- if (!segments || segments.length === 0) return command.trim() || "(empty command)";
525
- return segments.find(
526
- (segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory)
527
- );
528
- }
529
- function splitPowerShellSegments(command) {
530
- const trimmed = command.trim();
531
- if (!trimmed || /[\n\r`\u2018-\u201e]/.test(trimmed)) return void 0;
532
- const segments = [];
533
- let quote;
534
- let start = 0;
535
- for (let index = 0; index < trimmed.length; index += 1) {
536
- const character = trimmed[index];
537
- if (quote === "'") {
538
- if (character !== "'") continue;
539
- if (trimmed[index + 1] === "'") {
540
- index += 1;
541
- continue;
542
- }
543
- quote = void 0;
544
- continue;
545
- }
546
- if (quote === '"') {
547
- if (character === "$" || character === "`") return void 0;
548
- if (character === '"') quote = void 0;
549
- continue;
550
- }
551
- if (character === "'" || character === '"') {
552
- quote = character;
553
- continue;
554
- }
555
- if (["$", "@", "#", "!", "?", "{", "}", "(", ")", "[", "]", ">", "<"].includes(character)) {
556
- return void 0;
557
- }
558
- const next = trimmed[index + 1];
559
- if (character === "&" || character === "|" && next === "|") return void 0;
560
- const separatorLength = character === ";" || character === "|" ? 1 : 0;
561
- if (separatorLength === 0) continue;
562
- const segment = trimmed.slice(start, index).trim();
563
- if (!segment) return void 0;
564
- segments.push(segment);
565
- index += separatorLength - 1;
566
- start = index + 1;
567
- }
568
- if (quote) return void 0;
569
- const finalSegment = trimmed.slice(start).trim();
570
- if (!finalSegment) return void 0;
571
- segments.push(finalSegment);
572
- return segments;
573
- }
574
- function isSafePowerShellSegment(segment, safeSubcommands, workingDirectory) {
575
- const tokens = powerShellWords(segment);
576
- if (!tokens || tokens.length === 0 || tokens.includes("--%")) return false;
577
- const command = tokens[0]?.toLowerCase();
578
- if (!command) return false;
579
- const args = tokens.slice(1);
580
- if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
581
- if (command !== "git" && command !== "gh") return false;
582
- return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
583
- }
584
- function powerShellWords(segment) {
585
- const words = [];
586
- let word = "";
587
- let hasWord = false;
588
- let quote;
589
- for (let index = 0; index < segment.length; index += 1) {
590
- const character = segment[index];
591
- if (quote === "'") {
592
- if (character !== "'") {
593
- word += character;
594
- continue;
595
- }
596
- if (segment[index + 1] === "'") {
597
- word += "'";
598
- index += 1;
599
- continue;
600
- }
601
- quote = void 0;
602
- continue;
603
- }
604
- if (quote === '"') {
605
- if (character === '"') quote = void 0;
606
- else word += character;
607
- continue;
608
- }
609
- if (character === "'" || character === '"') {
610
- quote = character;
611
- hasWord = true;
612
- } else if (/\s/.test(character)) {
613
- if (hasWord) words.push(word);
614
- word = "";
615
- hasWord = false;
616
- } else {
617
- word += character;
618
- hasWord = true;
619
- }
620
- }
621
- if (quote) return void 0;
622
- if (hasWord) words.push(word);
623
- return words;
624
- }
625
- function splitShellSegments(command) {
626
- const trimmed = command.trim();
627
- if (!trimmed || /[\n\r`]/.test(trimmed)) return void 0;
628
- const segments = [];
629
- let quote;
630
- let escaped = false;
631
- let start = 0;
632
- for (let index = 0; index < trimmed.length; index += 1) {
633
- const character = trimmed[index];
634
- if (escaped) {
635
- escaped = false;
636
- continue;
637
- }
638
- if (character === "\\" && quote !== "'") {
639
- escaped = true;
640
- continue;
641
- }
642
- if (quote) {
643
- if (character === quote) quote = void 0;
644
- continue;
645
- }
646
- if (character === "'" || character === '"') {
647
- quote = character;
648
- continue;
649
- }
650
- if (character === ">" || character === "<" || character === "(" || character === ")") {
651
- return void 0;
652
- }
653
- const next = trimmed[index + 1];
654
- if (character === "&" && next !== "&") return void 0;
655
- const separatorLength = character === ";" || character === "|" ? next === character ? 2 : 1 : character === "&" && next === "&" ? 2 : 0;
656
- if (separatorLength === 0) continue;
657
- const segment = trimmed.slice(start, index).trim();
658
- if (!segment) return void 0;
659
- segments.push(segment);
660
- index += separatorLength - 1;
661
- start = index + 1;
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`);
662
520
  }
663
- if (quote || escaped) return void 0;
664
- const finalSegment = trimmed.slice(start).trim();
665
- if (!finalSegment) return void 0;
666
- segments.push(finalSegment);
667
- return segments;
668
- }
669
- function isSafeSegment(segment, safeSubcommands, workingDirectory) {
670
- if (hasShellExpansion(segment) || /(^|\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {
671
- return false;
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);
672
540
  }
673
- const tokens = shellWords(segment);
674
- if (!tokens || tokens.length === 0) return false;
675
- const command = tokens[0]?.toLowerCase();
676
- if (!command || MUTATING_COMMANDS.has(command)) return false;
677
- const args = tokens.slice(1);
678
- if (!hasSafeArguments(command, args)) return false;
679
- if (READ_ONLY_COMMANDS.has(command)) return true;
680
- return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
681
541
  }
682
- function hasShellExpansion(segment) {
683
- let quote;
684
- let escaped = false;
685
- for (const character of segment) {
686
- if (escaped) {
687
- escaped = false;
688
- continue;
689
- }
690
- if (character === "\\" && quote !== "'") {
691
- escaped = true;
692
- continue;
693
- }
694
- if (quote) {
695
- if (character === quote) quote = void 0;
696
- else if (character === "$" && quote === '"') return true;
697
- continue;
698
- }
699
- if (character === "'" || character === '"') {
700
- quote = character;
701
- continue;
702
- }
703
- if (["$", "*", "?", "[", "{"].includes(character)) return true;
704
- }
705
- return false;
542
+ function isSettingsDocument(value) {
543
+ return typeof value === "object" && value !== null && !Array.isArray(value);
706
544
  }
707
- function shellWords(segment) {
708
- const words = [];
709
- let word = "";
710
- let quote;
711
- let escaped = false;
712
- for (const character of segment) {
713
- if (escaped) {
714
- word += character;
715
- escaped = false;
716
- continue;
717
- }
718
- if (character === "\\" && quote !== "'") {
719
- escaped = true;
720
- continue;
721
- }
722
- if (quote) {
723
- if (character === quote) quote = void 0;
724
- else word += character;
725
- continue;
726
- }
727
- if (character === "'" || character === '"') quote = character;
728
- else if (/\s/.test(character)) {
729
- if (word) words.push(word);
730
- word = "";
731
- } else word += character;
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");
732
552
  }
733
- if (quote || escaped) return void 0;
734
- if (word) words.push(word);
735
- return words;
736
553
  }
737
- function hasSafeArguments(command, args) {
738
- const forbidden = /* @__PURE__ */ new Set(["-i", "--in-place", "--fix", "--write", "-delete", "--delete"]);
739
- if (args.some((argument) => forbidden.has(argument))) return false;
740
- if (command === "sed" && args.some(
741
- (argument) => argument.startsWith("--in-place=") || /^-[^-]+/.test(argument) && argument.slice(1).includes("i")
742
- )) {
743
- return false;
744
- }
745
- if (command === "find" && args.some(
746
- (argument) => ["-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"].includes(
747
- argument
748
- )
749
- )) {
750
- return false;
751
- }
752
- if (command === "date" && args.some((argument) => argument === "-s" || argument.startsWith("--set"))) {
753
- return false;
754
- }
755
- if ((command === "sort" || command === "tree") && args.some(
756
- (argument) => argument === "-o" || argument.startsWith("-o") && !argument.startsWith("--") || argument.startsWith("--output")
757
- )) {
758
- return false;
759
- }
760
- if (command === "sort" && args.some(
761
- (argument) => argument === "-T" || argument.startsWith("-T") && argument.length > 2 || argument.startsWith("--temporary-directory") || argument.startsWith("--compress-program")
762
- )) {
763
- return false;
764
- }
765
- if (command === "diff" && args.some((argument) => argument === "--output" || argument.startsWith("--output="))) {
766
- return false;
767
- }
768
- if (command === "uniq" && args.filter((argument) => !argument.startsWith("-")).length > 1) {
769
- return false;
770
- }
771
- if (command === "fd" && args.some(
772
- (argument) => ["-x", "-X", "--exec", "--exec-batch"].some(
773
- (flag) => argument === flag || argument.startsWith(`${flag}=`)
774
- )
775
- )) {
776
- return false;
777
- }
778
- if (command === "rg" && args.some((argument) => argument === "--pre" || argument.startsWith("--pre="))) {
779
- return false;
780
- }
781
- if (command === "bat" && args.some((argument) => argument === "--pager" || argument.startsWith("--pager="))) {
782
- return false;
783
- }
784
- return true;
554
+ function invalidSettingsError(settingsPath, reason) {
555
+ return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);
785
556
  }
786
- var allowReadOnlyArguments = () => true;
787
- var BUILTIN_GIT_VALIDATORS = {
788
- status: allowReadOnlyArguments,
789
- log: allowReadOnlyArguments,
790
- diff: allowReadOnlyArguments,
791
- show: allowReadOnlyArguments,
792
- branch: isSafeGitBranchArguments,
793
- remote: isSafeGitRemoteArguments,
794
- "ls-files": allowReadOnlyArguments,
795
- grep: isSafeGitGrepArguments
796
- };
797
- var CONFIGURABLE_GIT_VALIDATORS = {
798
- "rev-parse": allowReadOnlyArguments,
799
- blame: allowReadOnlyArguments,
800
- describe: allowReadOnlyArguments,
801
- "merge-base": allowReadOnlyArguments,
802
- "ls-tree": allowReadOnlyArguments,
803
- "cat-file": isSafeGitCatFileArguments
804
- };
805
- var GH_VALIDATORS = {
806
- "pr view": isSafeGhReadArguments,
807
- "pr list": isSafeGhReadArguments,
808
- "issue view": isSafeGhReadArguments,
809
- "issue list": isSafeGhReadArguments
810
- };
811
- function isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory) {
812
- if (command === "git") return isSafeGitCommand(args, safeSubcommands, workingDirectory);
813
- if (command === "gh") return isSafeGhCommand(args, safeSubcommands);
814
- const subcommandIndex = args.findIndex((argument) => !argument.startsWith("-"));
815
- const subcommand = args[subcommandIndex]?.toLowerCase();
816
- const subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];
817
- if (command === "sed") {
818
- const script = args.find((argument) => !argument.startsWith("-"));
819
- return Boolean(script) && (args.includes("-n") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) && /^\d+(,\d+)?p$/.test(script ?? "");
820
- }
821
- if (["node", "python", "python3", "tsc", "biome", "ruff", "ty"].includes(command)) {
822
- if (args.includes("--version")) return true;
823
- return command === "tsc" && args.includes("--noEmit") && !args.some(
824
- (argument) => argument === "--incremental" || argument.startsWith("--incremental=") || argument === "--tsBuildInfoFile" || argument.startsWith("--tsBuildInfoFile=") || argument === "--generateTrace" || argument.startsWith("--generateTrace=")
825
- );
826
- }
827
- if (command === "npm") {
828
- if (subcommand === "audit" && subcommandArgs.includes("fix")) return false;
829
- if (["list", "ls", "view", "info", "search", "outdated", "audit", "test"].includes(
830
- subcommand ?? ""
831
- )) {
832
- return true;
833
- }
834
- return subcommand === "run" && ["test", "check", "typecheck", "lint"].includes(args[1] ?? "");
835
- }
836
- if (["cargo", "go", "pytest", "vitest", "jest"].includes(command)) {
837
- return ["test", "check"].includes(subcommand ?? "") || ["pytest", "vitest", "jest"].includes(command);
838
- }
839
- return false;
557
+ function isNodeError(error) {
558
+ return error instanceof Error && "code" in error;
840
559
  }
841
- function isSafeGitCommand(args, safeSubcommands, workingDirectory) {
842
- const subcommandIndex = parseGitGlobalOptions(args, workingDirectory);
843
- if (subcommandIndex === void 0) return false;
844
- const subcommand = args[subcommandIndex]?.toLowerCase();
845
- if (!subcommand || subcommand.startsWith("-")) return false;
846
- const subcommandArgs = args.slice(subcommandIndex + 1);
847
- const builtinValidator = BUILTIN_GIT_VALIDATORS[subcommand];
848
- const configuredValidator = CONFIGURABLE_GIT_VALIDATORS[subcommand];
849
- const configured = safeSubcommands.git?.includes(subcommand) === true;
850
- const validator = builtinValidator ?? (configured ? configuredValidator : void 0);
851
- return validator !== void 0 && hasSafeGitArguments(subcommand, subcommandArgs) && validator(subcommandArgs);
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);
852
563
  }
853
- function parseGitGlobalOptions(args, workingDirectory) {
854
- let index = 0;
855
- while (index < args.length) {
856
- const argument = args[index];
857
- if (argument === "--no-pager") {
858
- index += 1;
859
- continue;
860
- }
861
- if (argument !== "-C") break;
862
- const directory = args[index + 1];
863
- if (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return void 0;
864
- index += 2;
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;
865
613
  }
866
- return index;
867
- }
868
- function isCurrentWorkingDirectory(directory, workingDirectory) {
869
- if (!workingDirectory || directory.split(/[\\/]+/u).includes("..")) return false;
870
- if (normalize(directory) === ".") return true;
871
- return isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);
614
+ return "";
872
615
  }
873
- function hasSafeGitArguments(subcommand, args) {
874
- return !args.some(
875
- (argument) => argument === "--help" || argument === "--show-signature" || argument.startsWith("--show-signature=") || argument.includes("%G") || argument === "--output" || argument.startsWith("--output=") || argument === "--ext-diff" || argument.startsWith("--ext-diff=") || argument === "--textconv" || argument.startsWith("--textconv=") || argument === "--paginate" || argument === "--open-files-in-pager" || argument.startsWith("--open-files-in-pager=") || subcommand === "grep" && (argument === "-O" || argument.startsWith("-O"))
876
- );
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;
877
623
  }
878
- function isSafeGitCatFileArguments(args) {
879
- return !args.some(
880
- (argument) => matchesLongOptionPrefix(argument, "--filters", "--fi") || matchesLongOptionPrefix(argument, "--textconv", "--t")
624
+ function messageTextContent(message) {
625
+ return messageText(
626
+ message?.message ?? message
881
627
  );
882
628
  }
883
- function isSafeGitGrepArguments(args) {
884
- return !args.some(
885
- (argument) => matchesLongOptionPrefix(argument, "--textconv", "--textc") || matchesLongOptionPrefix(argument, "--open-files-in-pager", "--op") || matchesLongOptionPrefix(argument, "--ext-grep", "--ext")
886
- );
629
+ function messageContainsLegacyPlanModeContextArtifact(message) {
630
+ return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;
887
631
  }
888
- function matchesLongOptionPrefix(argument, option, shortest) {
889
- const optionName = argument.split("=", 1)[0] ?? "";
890
- return optionName.length >= shortest.length && option.startsWith(optionName);
632
+ function messageContainsPlanModeImplementationContextArtifact(message) {
633
+ return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;
891
634
  }
892
- function isSafeGitBranchArguments(args) {
893
- if (args.some((argument) => !argument.startsWith("-"))) return false;
894
- return !args.some(
895
- (argument) => /^-[^-]*[dDmMcCu]/.test(argument) || matchesLongOptionPrefix(argument, "--delete", "--del") || matchesLongOptionPrefix(argument, "--move", "--mov") || matchesLongOptionPrefix(argument, "--copy", "--cop") || matchesLongOptionPrefix(argument, "--edit-description", "--e") || matchesLongOptionPrefix(argument, "--unset-upstream", "--u") || matchesLongOptionPrefix(argument, "--set-upstream-to", "--set-u") || matchesLongOptionPrefix(argument, "--create-reflog", "--creat")
896
- );
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
+ ];
897
670
  }
898
- function isSafeGitRemoteArguments(args) {
899
- const actionIndex = args.findIndex((argument) => !argument.startsWith("-"));
900
- if (actionIndex < 0) return true;
901
- const action = args[actionIndex];
902
- if (action === "get-url") return true;
903
- if (action !== "show") return false;
904
- const showArgs = args.slice(actionIndex + 1);
905
- if (showArgs.includes("--")) return false;
906
- const remotes = showArgs.filter((argument) => !argument.startsWith("-"));
907
- return remotes.length === 0 || remotes.length === 1 && showArgs.includes("-n");
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}`;
908
677
  }
909
- function isSafeGhCommand(args, safeSubcommands) {
910
- const group = args[0]?.toLowerCase();
911
- const action = args[1]?.toLowerCase();
912
- if (!group || !action || group.startsWith("-") || action.startsWith("-")) return false;
913
- const path = `${group} ${action}`;
914
- if (!safeSubcommands.gh?.includes(path)) return false;
915
- const validator = GH_VALIDATORS[path];
916
- return validator?.(args.slice(2)) ?? false;
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;
917
681
  }
918
- function isSafeGhReadArguments(args) {
919
- return !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);
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;
920
692
  }
921
- function isUnsafeGhReadArgument(argument) {
922
- return argument.startsWith("-w") || argument === "--web" || argument.startsWith("--web=") || argument === "--browser" || argument.startsWith("--browser=") || argument === "--paginate" || argument === "--pager" || argument.startsWith("--pager=") || argument === "--output" || argument.startsWith("--output=");
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" };
712
+ }
713
+ if (candidate.role === "assistant" && contentText(candidate.content).match(PROPOSED_PLAN_BLOCK_PATTERN)) {
714
+ return { messageIndex: index, kind: "legacy" };
715
+ }
716
+ }
717
+ return void 0;
923
718
  }
924
- function hasGhJsonOutput(args) {
925
- let hasJson = false;
926
- for (let index = 0; index < args.length; index += 1) {
927
- const argument = args[index];
928
- if (argument === "--json") {
929
- const value = args[index + 1];
930
- if (!value || value.startsWith("-")) return false;
931
- hasJson = true;
932
- index += 1;
933
- } else if (argument.startsWith("--json=")) {
934
- if (argument === "--json=") return false;
935
- hasJson = true;
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;
936
729
  }
937
730
  }
938
- return hasJson;
731
+ return void 0;
939
732
  }
940
-
941
- // src/settings.ts
942
- import { randomUUID } from "node:crypto";
943
- import { constants } from "node:fs";
944
- import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
945
- import { basename, dirname, join } from "node:path";
946
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
947
- var PLAN_MODE_SETTINGS_FILE = "pi-plan-mode.json";
948
- var LEGACY_PLAN_MODE_SETTINGS_FILE = "plan-mode.json";
949
- var MAX_SETTINGS_BYTES = 64 * 1024;
950
- var PLAN_MODE_THINKING_LEVELS = [
951
- "inherit",
952
- "off",
953
- "minimal",
954
- "low",
955
- "medium",
956
- "high",
957
- "xhigh",
958
- "max"
959
- ];
960
- var IMPLEMENTATION_PLAN_RETENTIONS = [
961
- "clear-on-start",
962
- "clear-after-first-run",
963
- "keep"
964
- ];
965
- var DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
966
- var MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]);
967
- var BASE_KEYS = /* @__PURE__ */ new Set([
968
- ..."abcdefghijklmnopqrstuvwxyz0123456789",
969
- "`",
970
- "-",
971
- "=",
972
- "[",
973
- "]",
974
- "\\",
975
- ";",
976
- "'",
977
- ",",
978
- ".",
979
- "/",
980
- "!",
981
- "@",
982
- "#",
983
- "$",
984
- "%",
985
- "^",
986
- "&",
987
- "*",
988
- "(",
989
- ")",
990
- "_",
991
- "+",
992
- "|",
993
- "~",
994
- "{",
995
- "}",
996
- ":",
997
- "<",
998
- ">",
999
- "?",
1000
- "escape",
1001
- "esc",
1002
- "enter",
1003
- "return",
1004
- "tab",
1005
- "space",
1006
- "backspace",
1007
- "delete",
1008
- "insert",
1009
- "clear",
1010
- "home",
1011
- "end",
1012
- "pageup",
1013
- "pagedown",
1014
- "up",
1015
- "down",
1016
- "left",
1017
- "right",
1018
- ...Array.from({ length: 12 }, (_unused, index) => `f${index + 1}`)
1019
- ]);
1020
- var MAX_PLAN_EXPORT_PATH_LENGTH = 4096;
1021
- var mutationQueues = /* @__PURE__ */ new Map();
1022
- function planModeSettingsPath() {
1023
- return join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);
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();
1024
743
  }
1025
- function legacyPlanModeSettingsPath() {
1026
- return join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);
744
+ function isSummaryMessage(message) {
745
+ const role = unwrapSessionMessage(message)?.role;
746
+ return role === "compactionSummary" || role === "branchSummary";
1027
747
  }
1028
- function normalizePlanModeSettings(value) {
1029
- if (!isSettingsDocument(value)) return void 0;
1030
- const thinkingLevel = Object.hasOwn(value, "thinkingLevel") ? Reflect.get(value, "thinkingLevel") : "inherit";
1031
- if (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel)) {
1032
- return void 0;
1033
- }
1034
- const settings = {
1035
- thinkingLevel
1036
- };
1037
- if (Object.hasOwn(value, "defaultPlanTools")) {
1038
- const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
1039
- if (!defaultPlanTools) return void 0;
1040
- settings.defaultPlanTools = defaultPlanTools;
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));
757
+ });
758
+ return nextContent.length === content.length ? content : nextContent;
759
+ });
760
+ }
761
+ function isEmptyAssistantMessage(message) {
762
+ const candidate = unwrapSessionMessage(message);
763
+ return candidate.role === "assistant" && Array.isArray(candidate.content) && candidate.content.length === 0;
764
+ }
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 } };
1041
772
  }
1042
- if (Object.hasOwn(value, "implementationPlanRetention")) {
1043
- const implementationPlanRetention = Reflect.get(value, "implementationPlanRetention");
1044
- if (!IMPLEMENTATION_PLAN_RETENTIONS.includes(
1045
- implementationPlanRetention
1046
- )) {
1047
- return void 0;
773
+ return { ...candidate, content };
774
+ }
775
+ function unwrapSessionMessage(message) {
776
+ const entry = message;
777
+ return entry?.message ?? message ?? {};
778
+ }
779
+ function isSessionMessageEntry(message) {
780
+ return typeof message === "object" && message !== null && "message" in message;
781
+ }
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;
795
+ }
796
+ function stripProposedPlanBlocks(text) {
797
+ return text.replace(PROPOSED_PLAN_BLOCK_PATTERN, "");
798
+ }
799
+ function messageText(message) {
800
+ return contentText(message.content);
801
+ }
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");
809
+ }
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;
1048
889
  }
1049
- settings.implementationPlanRetention = implementationPlanRetention;
1050
- }
1051
- if (Object.hasOwn(value, "defaultPlanExportPath")) {
1052
- const defaultPlanExportPath = normalizePlanExportPath(
1053
- Reflect.get(value, "defaultPlanExportPath")
890
+ };
891
+ }
892
+
893
+ // src/plan-export.ts
894
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
895
+ import { dirname as dirname2, resolve } from "node:path";
896
+ import { stripVTControlCharacters } from "node:util";
897
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
898
+ async function exportStoredPlan(state, requestedPath, ctx, lifecycle, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
899
+ const plan = (state.enabled ? state.latestPlan : void 0)?.trim() ?? state.savedPlan?.plan.trim() ?? state.activeImplementation?.plan.trim();
900
+ if (!plan) {
901
+ const error = new Error(
902
+ "No completed plan is available to export. Use /plan finalize when planning is complete."
1054
903
  );
1055
- if (!defaultPlanExportPath) return void 0;
1056
- settings.defaultPlanExportPath = defaultPlanExportPath;
1057
- }
1058
- if (Object.hasOwn(value, "toggleShortcut")) {
1059
- const toggleShortcut = normalizeKeyId(Reflect.get(value, "toggleShortcut"));
1060
- if (!toggleShortcut) return void 0;
1061
- settings.toggleShortcut = toggleShortcut;
904
+ if (!ctx.hasUI) throw error;
905
+ ctx.ui.notify(error.message, "warning");
906
+ return false;
1062
907
  }
1063
- if (Object.hasOwn(value, "safeSubcommands")) {
1064
- const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, "safeSubcommands"));
1065
- if (!safeSubcommands) return void 0;
1066
- settings.safeSubcommands = safeSubcommands;
908
+ const isCurrent = () => !lifecycle || lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state);
909
+ let result;
910
+ try {
911
+ result = await exportPlanToFile(
912
+ plan,
913
+ requestedPath,
914
+ ctx.cwd,
915
+ lifecycle?.signal,
916
+ isCurrent,
917
+ defaultPath
918
+ );
919
+ } catch (error) {
920
+ if (lifecycle?.signal.aborted || !isCurrent()) return false;
921
+ if (!ctx.hasUI) throw error;
922
+ const detail2 = error instanceof Error ? error.message : String(error);
923
+ ctx.ui.notify(safeNotification(`Unable to export plan: ${detail2}`), "error");
924
+ return false;
1067
925
  }
1068
- return settings;
926
+ if (!isCurrent()) return false;
927
+ const finishedReady = state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== void 0;
928
+ if (finishedReady) lifecycle.finishReady?.();
929
+ const detail = finishedReady ? " Plan mode disabled." : "";
930
+ ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), "info");
931
+ return true;
1069
932
  }
1070
- function normalizeToolNames(value) {
1071
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim().length > 0)) {
1072
- return void 0;
933
+ async function exportPlanToFile(plan, requestedPath, cwd, signal, isCurrent = () => true, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
934
+ const path = resolvePlanExportPath(requestedPath, cwd, defaultPath);
935
+ await withFileMutationQueue(path, async () => {
936
+ throwIfCancelled(signal, isCurrent);
937
+ await mkdir2(dirname2(path), { recursive: true });
938
+ throwIfCancelled(signal, isCurrent);
939
+ try {
940
+ await writeFile2(path, `${plan}
941
+ `, { encoding: "utf8", flag: "wx" });
942
+ } catch (error) {
943
+ if (isNodeError2(error) && error.code === "EEXIST") {
944
+ throw new Error(
945
+ `Plan export target already exists: ${path}. Choose another path or remove it first.`
946
+ );
947
+ }
948
+ throw error;
949
+ }
950
+ });
951
+ return { path };
952
+ }
953
+ function planExportDestination(defaultPath, cwd) {
954
+ return {
955
+ configuredPath: safeNotification(defaultPath),
956
+ resolvedPath: safeNotification(resolvePlanExportPath(void 0, cwd, defaultPath))
957
+ };
958
+ }
959
+ function resolvePlanExportPath(requestedPath, cwd, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
960
+ const rawPath = requestedPath?.trim() || defaultPath;
961
+ const normalizedPath = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
962
+ if (!normalizedPath.trim()) throw new Error("Plan export path must not be empty.");
963
+ if (normalizedPath.includes("\0")) {
964
+ throw new Error("Plan export path must not contain NUL bytes.");
1073
965
  }
1074
- return Array.from(new Set(value));
966
+ return resolve(cwd, normalizedPath);
1075
967
  }
1076
- function normalizePlanExportPath(value) {
1077
- if (typeof value !== "string") return void 0;
1078
- const normalized = value.trim();
1079
- if (!normalized || normalized.length > MAX_PLAN_EXPORT_PATH_LENGTH || !/[^@\s]/u.test(normalized) || [...normalized].some((character) => {
1080
- const codePoint = character.codePointAt(0) ?? 0;
1081
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
1082
- })) {
1083
- return void 0;
968
+ function safeNotification(value) {
969
+ let sanitized = "";
970
+ for (const character of stripVTControlCharacters(value)) {
971
+ const codePoint = character.codePointAt(0);
972
+ sanitized += codePoint !== void 0 && codePoint > 31 && !(codePoint >= 127 && codePoint <= 159) ? character : " ";
1084
973
  }
1085
- return normalized;
974
+ return sanitized;
1086
975
  }
1087
- function normalizeKeyId(value) {
1088
- if (typeof value !== "string") return void 0;
1089
- const normalized = value.trim().toLowerCase();
1090
- const base = [...BASE_KEYS].sort((left, right) => right.length - left.length).find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));
1091
- if (!base) return void 0;
1092
- const prefix = normalized.slice(0, normalized.length - base.length);
1093
- if (!prefix) return base;
1094
- if (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith("+")) return void 0;
1095
- const modifiers = prefix.slice(0, -1).split("+");
1096
- if (modifiers.length === 0 || modifiers.some((modifier) => !MODIFIERS.has(modifier)) || new Set(modifiers).size !== modifiers.length) {
1097
- return void 0;
1098
- }
1099
- return normalized;
976
+ function throwIfCancelled(signal, isCurrent) {
977
+ if (!signal?.aborted && isCurrent()) return;
978
+ throw signal?.reason instanceof Error ? signal.reason : new DOMException("Plan export cancelled", "AbortError");
1100
979
  }
1101
- function normalizeSafeSubcommands(value) {
1102
- if (!isSettingsDocument(value)) return void 0;
1103
- if (Object.keys(value).some((key) => key !== "git" && key !== "gh")) return void 0;
1104
- const safeSubcommands = {};
1105
- if (Object.hasOwn(value, "git")) {
1106
- const git = normalizeKnownValues(Reflect.get(value, "git"), SAFE_GIT_SUBCOMMANDS);
1107
- if (!git) return void 0;
1108
- safeSubcommands.git = git;
1109
- }
1110
- if (Object.hasOwn(value, "gh")) {
1111
- const gh = normalizeKnownValues(Reflect.get(value, "gh"), SAFE_GH_SUBCOMMAND_PATHS);
1112
- if (!gh) return void 0;
1113
- safeSubcommands.gh = gh;
1114
- }
1115
- return safeSubcommands;
1116
- }
1117
- function normalizeKnownValues(value, supported) {
1118
- if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && supported.includes(item))) {
1119
- return void 0;
1120
- }
1121
- return Array.from(new Set(value));
980
+ function isNodeError2(error) {
981
+ return error instanceof Error && "code" in error;
1122
982
  }
1123
- async function readPlanModeSettings(settingsPath) {
1124
- if (settingsPath) {
1125
- await awaitPlanModeSettingsWrites(settingsPath);
1126
- return (await readSettingsSnapshot(settingsPath)).result;
983
+
984
+ // src/question-tool.ts
985
+ var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
986
+ var MAX_PLAN_MODE_RESPONSE_LENGTH = 4e3;
987
+ var PLAN_MODE_QUESTION_PARAMS = {
988
+ type: "object",
989
+ additionalProperties: false,
990
+ required: ["questions"],
991
+ properties: {
992
+ questions: {
993
+ type: "array",
994
+ minItems: 1,
995
+ maxItems: 3,
996
+ description: "Questions to show the user. Prefer 1 and do not exceed 3.",
997
+ items: {
998
+ type: "object",
999
+ additionalProperties: false,
1000
+ required: ["id", "header", "question", "options"],
1001
+ properties: {
1002
+ id: {
1003
+ type: "string",
1004
+ description: "Stable identifier for mapping answers (snake_case)."
1005
+ },
1006
+ header: {
1007
+ type: "string",
1008
+ description: "Short header label shown in the UI (12 or fewer chars)."
1009
+ },
1010
+ question: { type: "string", description: "Single-sentence prompt shown to the user." },
1011
+ options: {
1012
+ type: "array",
1013
+ minItems: 2,
1014
+ maxItems: 4,
1015
+ description: "Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.",
1016
+ items: {
1017
+ type: "object",
1018
+ additionalProperties: false,
1019
+ required: ["label", "description"],
1020
+ properties: {
1021
+ label: { type: "string", description: "User-facing label (1-5 words)." },
1022
+ description: {
1023
+ type: "string",
1024
+ description: "One short sentence explaining impact/tradeoff if selected."
1025
+ }
1026
+ }
1027
+ }
1028
+ }
1029
+ }
1030
+ }
1031
+ }
1127
1032
  }
1128
- const canonicalPath = planModeSettingsPath();
1129
- await awaitPlanModeSettingsWrites(canonicalPath);
1130
- const canonical = await readSettingsSnapshot(canonicalPath);
1131
- const legacyPath = legacyPlanModeSettingsPath();
1132
- if (canonical.result.kind !== "missing") {
1133
- return await pathExists(legacyPath) ? {
1134
- ...canonical.result,
1135
- notice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`
1136
- } : canonical.result;
1033
+ };
1034
+ function normalizePlanModeQuestionParams(input) {
1035
+ if (!isRecord2(input) || !Array.isArray(input.questions)) {
1036
+ return { ok: false, error: "questions must be an array" };
1137
1037
  }
1138
- const legacy = await readSettingsSnapshot(legacyPath);
1139
- const raced = await readSettingsSnapshot(canonicalPath);
1140
- if (raced.result.kind !== "missing") return raced.result;
1141
- return legacy.result.kind === "loaded" ? {
1142
- ...legacy.result,
1143
- notice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`
1144
- } : legacy.result;
1145
- }
1146
- function updatePlanModeSettings(patch, options = {}) {
1147
- const settingsPath = options.settingsPath ?? planModeSettingsPath();
1148
- const legacySettingsPath = options.legacySettingsPath ?? (options.settingsPath ? void 0 : legacyPlanModeSettingsPath());
1149
- return enqueueMutation(settingsPath, async () => {
1150
- options.signal?.throwIfAborted();
1151
- const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
1152
- const updated = { ...current };
1153
- if (patch.thinkingLevel !== void 0) updated.thinkingLevel = patch.thinkingLevel;
1154
- if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
1155
- else if (patch.defaultPlanTools !== void 0) {
1156
- updated.defaultPlanTools = [...patch.defaultPlanTools];
1038
+ if (input.questions.length < 1 || input.questions.length > 3) {
1039
+ return { ok: false, error: "questions must contain 1-3 items" };
1040
+ }
1041
+ const questions = [];
1042
+ for (const [questionIndex, rawQuestion] of input.questions.entries()) {
1043
+ if (!isRecord2(rawQuestion)) {
1044
+ return { ok: false, error: `question ${questionIndex + 1} must be an object` };
1157
1045
  }
1158
- if (patch.implementationPlanRetention !== void 0) {
1159
- updated.implementationPlanRetention = patch.implementationPlanRetention;
1046
+ const id = stringField(rawQuestion.id);
1047
+ const header = stringField(rawQuestion.header);
1048
+ const question = stringField(rawQuestion.question);
1049
+ if (!id || !header || !question) {
1050
+ return {
1051
+ ok: false,
1052
+ error: `question ${questionIndex + 1} requires non-empty id, header, and question`
1053
+ };
1160
1054
  }
1161
- if (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;
1162
- else if (patch.defaultPlanExportPath !== void 0) {
1163
- updated.defaultPlanExportPath = patch.defaultPlanExportPath;
1055
+ if (!Array.isArray(rawQuestion.options)) {
1056
+ return { ok: false, error: `question ${questionIndex + 1} options must be an array` };
1164
1057
  }
1165
- if (patch.toggleShortcut === null) delete updated.toggleShortcut;
1166
- else if (patch.toggleShortcut !== void 0) {
1167
- updated.toggleShortcut = patch.toggleShortcut;
1058
+ if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {
1059
+ return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };
1168
1060
  }
1169
- const settings = normalizePlanModeSettings(updated);
1170
- if (!settings) throw invalidSettingsError(settingsPath, "invalid settings shape");
1171
- await publishSettings(settingsPath, updated, options.signal, options.beforeRename);
1172
- return settings;
1173
- });
1174
- }
1175
- async function awaitPlanModeSettingsWrites(settingsPath = planModeSettingsPath()) {
1176
- await mutationQueues.get(settingsPath);
1061
+ const options = [];
1062
+ for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {
1063
+ if (!isRecord2(rawOption)) {
1064
+ return {
1065
+ ok: false,
1066
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`
1067
+ };
1068
+ }
1069
+ const label = stringField(rawOption.label);
1070
+ if (!label) {
1071
+ return {
1072
+ ok: false,
1073
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`
1074
+ };
1075
+ }
1076
+ const description = stringField(rawOption.description);
1077
+ if (!description) {
1078
+ return {
1079
+ ok: false,
1080
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`
1081
+ };
1082
+ }
1083
+ options.push({ label, description });
1084
+ }
1085
+ questions.push({ id, header, question, options });
1086
+ }
1087
+ return { ok: true, questions };
1177
1088
  }
1178
- function enqueueMutation(settingsPath, mutation) {
1179
- const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();
1180
- const result = previous.then(mutation, mutation);
1181
- const settled = result.then(
1182
- () => void 0,
1183
- () => void 0
1089
+ async function answerPlanModeQuestions(questions, ctx, lifecycle) {
1090
+ const answers = await askPlanModeQuestions(
1091
+ questions,
1092
+ ctx,
1093
+ () => lifecycle.isCurrent() && lifecycle.isEnabled()
1184
1094
  );
1185
- mutationQueues.set(settingsPath, settled);
1186
- void settled.finally(() => {
1187
- if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);
1188
- });
1189
- return result;
1190
- }
1191
- async function readSettingsDocumentForUpdate(settingsPath, legacySettingsPath) {
1192
- const canonical = await readSettingsSnapshot(settingsPath);
1193
- if (canonical.result.kind === "loaded") return canonical.document ?? {};
1194
- if (canonical.result.kind === "invalid") {
1195
- throw invalidSettingsError(settingsPath, canonical.result.reason);
1095
+ if (!lifecycle.isCurrent()) {
1096
+ return planModeQuestionCancelled(
1097
+ questions,
1098
+ "cancelled",
1099
+ "Plan-mode question cancelled because the session changed."
1100
+ );
1196
1101
  }
1197
- if (!legacySettingsPath) return {};
1198
- const legacy = await readSettingsSnapshot(legacySettingsPath);
1199
- const raced = await readSettingsSnapshot(settingsPath);
1200
- if (raced.result.kind === "loaded") return raced.document ?? {};
1201
- if (raced.result.kind === "invalid") {
1202
- throw invalidSettingsError(settingsPath, raced.result.reason);
1102
+ if (!lifecycle.isEnabled()) {
1103
+ return planModeQuestionCancelled(
1104
+ questions,
1105
+ "plan_mode_inactive",
1106
+ "Plan-mode question cancelled because Plan mode is no longer active."
1107
+ );
1203
1108
  }
1204
- if (legacy.result.kind === "invalid") {
1205
- throw invalidSettingsError(legacySettingsPath, legacy.result.reason);
1109
+ if (!answers) {
1110
+ return planModeQuestionCancelled(
1111
+ questions,
1112
+ "cancelled",
1113
+ "User cancelled the Plan-mode question prompt."
1114
+ );
1206
1115
  }
1207
- return legacy.document ?? {};
1116
+ return planModeQuestionAnswered(questions, answers);
1117
+ }
1118
+ async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
1119
+ const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
1120
+ if (!shouldContinue()) return void 0;
1121
+ const runnerQuestions = questions.map((question, index) => ({
1122
+ id: String(index),
1123
+ header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),
1124
+ prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),
1125
+ options: question.options.map((option, optionIndex) => ({
1126
+ ...option,
1127
+ label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText)
1128
+ }))
1129
+ }));
1130
+ const result = await runQuestionnaire(ctx, {
1131
+ questions: runnerQuestions,
1132
+ allowNotes: true,
1133
+ maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
1134
+ signal: ctx.signal,
1135
+ isCurrent: shouldContinue
1136
+ });
1137
+ if (!shouldContinue()) return void 0;
1138
+ return mapQuestionnaireResult(questions, result);
1208
1139
  }
1209
- async function readSettingsSnapshot(settingsPath) {
1210
- let contents;
1211
- try {
1212
- contents = await readSettingsContents(settingsPath);
1213
- } catch (error) {
1214
- if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
1215
- return { result: { kind: "invalid", reason: safeReadError(error) } };
1216
- }
1217
- let parsed;
1218
- try {
1219
- parsed = JSON.parse(contents);
1220
- } catch {
1221
- return { result: { kind: "invalid", reason: "invalid JSON" } };
1222
- }
1223
- const settings = normalizePlanModeSettings(parsed);
1224
- if (!settings || !isSettingsDocument(parsed)) {
1225
- return { result: { kind: "invalid", reason: "invalid settings shape" } };
1140
+ function mapQuestionnaireResult(questions, result) {
1141
+ if (result.kind !== "submitted") return void 0;
1142
+ if (result.answers.length !== questions.length) {
1143
+ throw new Error("Questionnaire returned an incomplete answer set");
1226
1144
  }
1227
- return { document: parsed, result: { kind: "loaded", settings } };
1228
- }
1229
- async function readSettingsContents(settingsPath) {
1230
- const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);
1231
- const handle = await open(settingsPath, flags);
1232
- try {
1233
- const stats = await handle.stat();
1234
- if (!stats.isFile()) throw new Error("settings path is not a regular file");
1235
- if (stats.size > MAX_SETTINGS_BYTES) {
1236
- throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
1237
- }
1238
- const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
1239
- let offset = 0;
1240
- while (offset < buffer.byteLength) {
1241
- const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);
1242
- if (bytesRead === 0) break;
1243
- offset += bytesRead;
1244
- }
1245
- if (offset > MAX_SETTINGS_BYTES) {
1246
- throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
1145
+ const answers = /* @__PURE__ */ new Map();
1146
+ for (const answer of result.answers) {
1147
+ const index = Number(answer.questionId);
1148
+ if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {
1149
+ throw new Error("Questionnaire returned an answer for an unknown question");
1247
1150
  }
1248
- try {
1249
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
1250
- buffer.subarray(0, offset)
1251
- );
1252
- } catch {
1253
- throw new Error("settings file is not valid UTF-8");
1151
+ if (answers.has(index)) throw new Error("Questionnaire returned duplicate answers");
1152
+ if (answer.wasCustom) {
1153
+ if (answer.optionIndex !== void 0) {
1154
+ throw new Error("Questionnaire returned a custom answer with an option index");
1155
+ }
1156
+ if (!answer.answer.trim()) return void 0;
1157
+ } else if (answer.optionIndex === void 0 || !questions[index]?.options[answer.optionIndex - 1]) {
1158
+ throw new Error("Questionnaire returned an invalid selected option");
1254
1159
  }
1255
- } finally {
1256
- await handle.close();
1257
- }
1258
- }
1259
- async function publishSettings(settingsPath, document, signal, beforeRename) {
1260
- signal?.throwIfAborted();
1261
- const contents = `${JSON.stringify(document, null, 2)}
1262
- `;
1263
- if (Buffer.byteLength(contents, "utf8") > MAX_SETTINGS_BYTES) {
1264
- throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);
1160
+ answers.set(index, answer);
1265
1161
  }
1266
- const directory = dirname(settingsPath);
1267
- await mkdir(directory, { recursive: true });
1268
- signal?.throwIfAborted();
1269
- const temporaryPath = join(
1270
- directory,
1271
- `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`
1272
- );
1273
- try {
1274
- await writeFile(temporaryPath, contents, {
1275
- encoding: "utf8",
1276
- flag: "wx",
1277
- mode: 384,
1278
- signal
1162
+ return questions.map((question, index) => {
1163
+ const answer = answers.get(index);
1164
+ if (!answer) throw new Error("Questionnaire returned an incomplete answer set");
1165
+ const answerText = answer.wasCustom ? answer.answer : question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer;
1166
+ return answerFor(question, answerText, {
1167
+ wasCustom: answer.wasCustom,
1168
+ optionIndex: answer.optionIndex,
1169
+ note: answer.note
1279
1170
  });
1280
- await beforeRename?.(temporaryPath, settingsPath);
1281
- signal?.throwIfAborted();
1282
- await rename(temporaryPath, settingsPath);
1283
- } finally {
1284
- await rm(temporaryPath, { force: true }).catch(() => void 0);
1285
- }
1171
+ });
1286
1172
  }
1287
- function isSettingsDocument(value) {
1288
- return typeof value === "object" && value !== null && !Array.isArray(value);
1173
+ function displayText(value, fallback, sanitize) {
1174
+ const sanitized = sanitize(value);
1175
+ return sanitized.trim() ? sanitized : fallback;
1289
1176
  }
1290
- async function pathExists(path) {
1291
- try {
1292
- const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
1293
- await handle.close();
1294
- return true;
1295
- } catch (error) {
1296
- return !(isNodeError(error) && error.code === "ENOENT");
1297
- }
1177
+ function answerFor(question, answer, options) {
1178
+ const result = {
1179
+ id: question.id,
1180
+ header: question.header,
1181
+ question: question.question,
1182
+ answer,
1183
+ wasCustom: options.wasCustom
1184
+ };
1185
+ if (options.optionIndex !== void 0) result.optionIndex = options.optionIndex;
1186
+ if (options.note !== void 0) result.note = options.note;
1187
+ return result;
1298
1188
  }
1299
- function invalidSettingsError(settingsPath, reason) {
1300
- return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);
1189
+ function planModeQuestionAnswered(questions, answers) {
1190
+ return {
1191
+ content: [
1192
+ { type: "text", text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }
1193
+ ],
1194
+ details: { cancelled: false, questions, answers }
1195
+ };
1301
1196
  }
1302
- function isNodeError(error) {
1303
- return error instanceof Error && "code" in error;
1197
+ function planModeQuestionCancelled(questions, reason, message) {
1198
+ return {
1199
+ content: [
1200
+ {
1201
+ type: "text",
1202
+ text: formatPlanModeQuestionPayload({ cancelled: true, reason, message })
1203
+ }
1204
+ ],
1205
+ details: { cancelled: true, reason, questions }
1206
+ };
1207
+ }
1208
+ function formatPlanModeQuestionPayload(payload) {
1209
+ return JSON.stringify(payload, null, 2);
1210
+ }
1211
+ function isRecord2(value) {
1212
+ return typeof value === "object" && value !== null;
1213
+ }
1214
+ function stringField(value) {
1215
+ return typeof value === "string" ? value.trim() : void 0;
1216
+ }
1217
+
1218
+ // src/tool-policy.ts
1219
+ import { isAbsolute, normalize } from "node:path";
1220
+ var BUILTIN_SAFE_GIT_SUBCOMMANDS = [
1221
+ "status",
1222
+ "log",
1223
+ "diff",
1224
+ "show",
1225
+ "branch",
1226
+ "remote",
1227
+ "ls-files",
1228
+ "grep"
1229
+ ];
1230
+ var CONFIGURABLE_SAFE_GIT_SUBCOMMANDS = [
1231
+ "rev-parse",
1232
+ "blame",
1233
+ "describe",
1234
+ "merge-base",
1235
+ "ls-tree",
1236
+ "cat-file"
1237
+ ];
1238
+ var SAFE_GIT_SUBCOMMANDS = [
1239
+ ...BUILTIN_SAFE_GIT_SUBCOMMANDS,
1240
+ ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS
1241
+ ];
1242
+ var SAFE_BUILTIN_PLAN_TOOLS = /* @__PURE__ */ new Set([
1243
+ "read",
1244
+ "bash",
1245
+ "powershell",
1246
+ "grep",
1247
+ "find",
1248
+ "ls"
1249
+ ]);
1250
+ var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
1251
+ var MUTATING_COMMANDS = /* @__PURE__ */ new Set([
1252
+ "rm",
1253
+ "rmdir",
1254
+ "mv",
1255
+ "cp",
1256
+ "mkdir",
1257
+ "touch",
1258
+ "chmod",
1259
+ "chown",
1260
+ "chgrp",
1261
+ "ln",
1262
+ "tee",
1263
+ "truncate",
1264
+ "dd",
1265
+ "sudo",
1266
+ "su",
1267
+ "kill",
1268
+ "pkill",
1269
+ "killall",
1270
+ "reboot",
1271
+ "shutdown",
1272
+ "vim",
1273
+ "vi",
1274
+ "nano",
1275
+ "emacs",
1276
+ "code",
1277
+ "subl"
1278
+ ]);
1279
+ var READ_ONLY_POWERSHELL_COMMANDS = /* @__PURE__ */ new Set([
1280
+ "format-list",
1281
+ "format-table",
1282
+ "get-childitem",
1283
+ "get-content",
1284
+ "get-item",
1285
+ "get-location",
1286
+ "measure-object",
1287
+ "out-string",
1288
+ "resolve-path",
1289
+ "select-string",
1290
+ "sort-object",
1291
+ "test-path",
1292
+ "write-output"
1293
+ ]);
1294
+ var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
1295
+ "cat",
1296
+ "head",
1297
+ "tail",
1298
+ "grep",
1299
+ "find",
1300
+ "ls",
1301
+ "pwd",
1302
+ "echo",
1303
+ "printf",
1304
+ "wc",
1305
+ "sort",
1306
+ "uniq",
1307
+ "diff",
1308
+ "file",
1309
+ "stat",
1310
+ "du",
1311
+ "df",
1312
+ "tree",
1313
+ "which",
1314
+ "whereis",
1315
+ "type",
1316
+ "printenv",
1317
+ "uname",
1318
+ "whoami",
1319
+ "id",
1320
+ "date",
1321
+ "uptime",
1322
+ "ps",
1323
+ "jq",
1324
+ "rg",
1325
+ "fd",
1326
+ "bat",
1327
+ "eza"
1328
+ ]);
1329
+ function isBuiltinTool(tool) {
1330
+ return tool.sourceInfo.source === "builtin";
1304
1331
  }
1305
- function safeReadError(error) {
1306
- if (isNodeError(error) && error.code === "ELOOP") return "settings path is not a regular file";
1307
- return error instanceof Error ? error.message : String(error);
1332
+ function classifyPlanModeTool(tool) {
1333
+ if (!isBuiltinTool(tool)) return "user-opt-in";
1334
+ if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return "blocked";
1335
+ if (tool.name === "bash" || tool.name === "powershell") return "limited";
1336
+ return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? "read-only" : "blocked";
1308
1337
  }
1309
- function configuredThinkingLevel(settings) {
1310
- return settings.thinkingLevel === "inherit" ? void 0 : settings.thinkingLevel;
1338
+ function canSelectToolInPlanMode(tool) {
1339
+ return classifyPlanModeTool(tool) !== "blocked";
1311
1340
  }
1312
- function configuredImplementationPlanRetention(settings) {
1313
- return settings.implementationPlanRetention ?? "clear-on-start";
1341
+ function readCommand(input) {
1342
+ const command = input;
1343
+ return typeof command?.command === "string" ? command.command : "";
1314
1344
  }
1315
- function configuredPlanExportPath(settings) {
1316
- return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
1345
+ function findBlockedCommandSegment(command, safeSubcommands = {}, workingDirectory, platform = process.platform) {
1346
+ if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return void 0;
1347
+ const segments = splitShellSegments(command);
1348
+ if (!segments || segments.length === 0) return command.trim() || "(empty command)";
1349
+ return segments.find(
1350
+ (segment) => !isSafeSegment(segment, safeSubcommands, workingDirectory, platform)
1351
+ );
1317
1352
  }
1318
- function configuredPlanModeToggleShortcut(settings) {
1319
- return settings.toggleShortcut;
1353
+ function findBlockedPowerShellCommandSegment(command, safeSubcommands = {}, workingDirectory) {
1354
+ if (matchesConfiguredSafeSubcommand(command, safeSubcommands)) return void 0;
1355
+ const segments = splitPowerShellSegments(command);
1356
+ if (!segments || segments.length === 0) return command.trim() || "(empty command)";
1357
+ return segments.find(
1358
+ (segment) => !isSafePowerShellSegment(segment, safeSubcommands, workingDirectory)
1359
+ );
1320
1360
  }
1321
-
1322
- // src/plan-export.ts
1323
- import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
1324
- import { dirname as dirname2, resolve } from "node:path";
1325
- import { stripVTControlCharacters } from "node:util";
1326
- import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
1327
- async function exportStoredPlan(state, requestedPath, ctx, lifecycle, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1328
- const plan = (state.enabled ? state.latestPlan : void 0)?.trim() ?? state.savedPlan?.plan.trim() ?? state.activeImplementation?.plan.trim();
1329
- if (!plan) {
1330
- const error = new Error(
1331
- "No completed plan is available to export. Use /plan finalize when planning is complete."
1332
- );
1333
- if (!ctx.hasUI) throw error;
1334
- ctx.ui.notify(error.message, "warning");
1335
- return false;
1336
- }
1337
- const isCurrent = () => !lifecycle || lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state);
1338
- let result;
1339
- try {
1340
- result = await exportPlanToFile(
1341
- plan,
1342
- requestedPath,
1343
- ctx.cwd,
1344
- lifecycle?.signal,
1345
- isCurrent,
1346
- defaultPath
1347
- );
1348
- } catch (error) {
1349
- if (lifecycle?.signal.aborted || !isCurrent()) return false;
1350
- if (!ctx.hasUI) throw error;
1351
- const detail2 = error instanceof Error ? error.message : String(error);
1352
- ctx.ui.notify(safeNotification(`Unable to export plan: ${detail2}`), "error");
1353
- return false;
1354
- }
1355
- if (!isCurrent()) return false;
1356
- const finishedReady = state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== void 0;
1357
- if (finishedReady) lifecycle.finishReady?.();
1358
- const detail = finishedReady ? " Plan mode disabled." : "";
1359
- ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), "info");
1360
- return true;
1361
+ function matchesConfiguredSafeSubcommand(command, safeSubcommands) {
1362
+ const candidate = command.trimStart();
1363
+ return Object.entries(safeSubcommands).some(
1364
+ ([configuredCommand, subcommands]) => subcommands?.some((subcommand) => {
1365
+ const prefix = `${configuredCommand.trim()} ${subcommand.trim()}`;
1366
+ if (!configuredCommand.trim() || !subcommand.trim() || !candidate.startsWith(prefix)) {
1367
+ return false;
1368
+ }
1369
+ const boundary = candidate[prefix.length];
1370
+ return boundary === void 0 || /[\s;&|<>()]/.test(boundary);
1371
+ })
1372
+ );
1361
1373
  }
1362
- async function exportPlanToFile(plan, requestedPath, cwd, signal, isCurrent = () => true, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1363
- const path = resolvePlanExportPath(requestedPath, cwd, defaultPath);
1364
- await withFileMutationQueue(path, async () => {
1365
- throwIfCancelled(signal, isCurrent);
1366
- await mkdir2(dirname2(path), { recursive: true });
1367
- throwIfCancelled(signal, isCurrent);
1368
- try {
1369
- await writeFile2(path, `${plan}
1370
- `, { encoding: "utf8", flag: "wx" });
1371
- } catch (error) {
1372
- if (isNodeError2(error) && error.code === "EEXIST") {
1373
- throw new Error(
1374
- `Plan export target already exists: ${path}. Choose another path or remove it first.`
1375
- );
1374
+ function splitPowerShellSegments(command) {
1375
+ const trimmed = command.trim();
1376
+ if (!trimmed || /[\n\r`\u2018-\u201e]/.test(trimmed)) return void 0;
1377
+ const segments = [];
1378
+ let quote;
1379
+ let start = 0;
1380
+ for (let index = 0; index < trimmed.length; index += 1) {
1381
+ const character = trimmed[index];
1382
+ if (quote === "'") {
1383
+ if (character !== "'") continue;
1384
+ if (trimmed[index + 1] === "'") {
1385
+ index += 1;
1386
+ continue;
1376
1387
  }
1377
- throw error;
1388
+ quote = void 0;
1389
+ continue;
1378
1390
  }
1379
- });
1380
- return { path };
1381
- }
1382
- function planExportDestination(defaultPath, cwd) {
1383
- return {
1384
- configuredPath: safeNotification(defaultPath),
1385
- resolvedPath: safeNotification(resolvePlanExportPath(void 0, cwd, defaultPath))
1386
- };
1387
- }
1388
- function resolvePlanExportPath(requestedPath, cwd, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1389
- const rawPath = requestedPath?.trim() || defaultPath;
1390
- const normalizedPath = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
1391
- if (!normalizedPath.trim()) throw new Error("Plan export path must not be empty.");
1392
- if (normalizedPath.includes("\0")) {
1393
- throw new Error("Plan export path must not contain NUL bytes.");
1394
- }
1395
- return resolve(cwd, normalizedPath);
1396
- }
1397
- function safeNotification(value) {
1398
- let sanitized = "";
1399
- for (const character of stripVTControlCharacters(value)) {
1400
- const codePoint = character.codePointAt(0);
1401
- sanitized += codePoint !== void 0 && codePoint > 31 && !(codePoint >= 127 && codePoint <= 159) ? character : " ";
1391
+ if (quote === '"') {
1392
+ if (character === "$" || character === "`") return void 0;
1393
+ if (character === '"') quote = void 0;
1394
+ continue;
1395
+ }
1396
+ if (character === "'" || character === '"') {
1397
+ quote = character;
1398
+ continue;
1399
+ }
1400
+ if (["$", "@", "#", "!", "?", "{", "}", "(", ")", "[", "]", ">", "<"].includes(character)) {
1401
+ return void 0;
1402
+ }
1403
+ const next = trimmed[index + 1];
1404
+ if (character === "&" || character === "|" && next === "|") return void 0;
1405
+ const separatorLength = character === ";" || character === "|" ? 1 : 0;
1406
+ if (separatorLength === 0) continue;
1407
+ const segment = trimmed.slice(start, index).trim();
1408
+ if (!segment) return void 0;
1409
+ segments.push(segment);
1410
+ index += separatorLength - 1;
1411
+ start = index + 1;
1402
1412
  }
1403
- return sanitized;
1404
- }
1405
- function throwIfCancelled(signal, isCurrent) {
1406
- if (!signal?.aborted && isCurrent()) return;
1407
- throw signal?.reason instanceof Error ? signal.reason : new DOMException("Plan export cancelled", "AbortError");
1413
+ if (quote) return void 0;
1414
+ const finalSegment = trimmed.slice(start).trim();
1415
+ if (!finalSegment) return void 0;
1416
+ segments.push(finalSegment);
1417
+ return segments;
1408
1418
  }
1409
- function isNodeError2(error) {
1410
- return error instanceof Error && "code" in error;
1419
+ function isSafePowerShellSegment(segment, safeSubcommands, workingDirectory) {
1420
+ const tokens = powerShellWords(segment);
1421
+ if (!tokens || tokens.length === 0 || tokens.includes("--%")) return false;
1422
+ const command = tokens[0]?.toLowerCase();
1423
+ if (!command) return false;
1424
+ const args = tokens.slice(1);
1425
+ if (READ_ONLY_POWERSHELL_COMMANDS.has(command)) return true;
1426
+ if (command === "get-process") return isSafeGetProcessArguments(args);
1427
+ if (command === "get-service") return isSafeGetServiceArguments(args);
1428
+ if (command !== "git" && command !== "gh") return false;
1429
+ return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
1411
1430
  }
1412
-
1413
- // src/question-tool.ts
1414
- var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
1415
- var MAX_PLAN_MODE_RESPONSE_LENGTH = 4e3;
1416
- var PLAN_MODE_QUESTION_PARAMS = {
1417
- type: "object",
1418
- additionalProperties: false,
1419
- required: ["questions"],
1420
- properties: {
1421
- questions: {
1422
- type: "array",
1423
- minItems: 1,
1424
- maxItems: 3,
1425
- description: "Questions to show the user. Prefer 1 and do not exceed 3.",
1426
- items: {
1427
- type: "object",
1428
- additionalProperties: false,
1429
- required: ["id", "header", "question", "options"],
1430
- properties: {
1431
- id: {
1432
- type: "string",
1433
- description: "Stable identifier for mapping answers (snake_case)."
1434
- },
1435
- header: {
1436
- type: "string",
1437
- description: "Short header label shown in the UI (12 or fewer chars)."
1438
- },
1439
- question: { type: "string", description: "Single-sentence prompt shown to the user." },
1440
- options: {
1441
- type: "array",
1442
- minItems: 2,
1443
- maxItems: 4,
1444
- description: "Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.",
1445
- items: {
1446
- type: "object",
1447
- additionalProperties: false,
1448
- required: ["label", "description"],
1449
- properties: {
1450
- label: { type: "string", description: "User-facing label (1-5 words)." },
1451
- description: {
1452
- type: "string",
1453
- description: "One short sentence explaining impact/tradeoff if selected."
1454
- }
1455
- }
1456
- }
1457
- }
1458
- }
1431
+ function powerShellWords(segment) {
1432
+ const words = [];
1433
+ let word = "";
1434
+ let hasWord = false;
1435
+ let quote;
1436
+ for (let index = 0; index < segment.length; index += 1) {
1437
+ const character = segment[index];
1438
+ if (quote === "'") {
1439
+ if (character !== "'") {
1440
+ word += character;
1441
+ continue;
1442
+ }
1443
+ if (segment[index + 1] === "'") {
1444
+ word += "'";
1445
+ index += 1;
1446
+ continue;
1459
1447
  }
1448
+ quote = void 0;
1449
+ continue;
1450
+ }
1451
+ if (quote === '"') {
1452
+ if (character === '"') quote = void 0;
1453
+ else word += character;
1454
+ continue;
1455
+ }
1456
+ if (character === "'" || character === '"') {
1457
+ quote = character;
1458
+ hasWord = true;
1459
+ } else if (/\s/.test(character)) {
1460
+ if (hasWord) words.push(word);
1461
+ word = "";
1462
+ hasWord = false;
1463
+ } else {
1464
+ word += character;
1465
+ hasWord = true;
1460
1466
  }
1461
1467
  }
1462
- };
1463
- function normalizePlanModeQuestionParams(input) {
1464
- if (!isRecord2(input) || !Array.isArray(input.questions)) {
1465
- return { ok: false, error: "questions must be an array" };
1468
+ if (quote) return void 0;
1469
+ if (hasWord) words.push(word);
1470
+ return words;
1471
+ }
1472
+ function splitShellSegments(command) {
1473
+ const trimmed = command.trim();
1474
+ if (!trimmed || /[\n\r`]/.test(trimmed)) return void 0;
1475
+ const segments = [];
1476
+ let quote;
1477
+ let escaped = false;
1478
+ let start = 0;
1479
+ for (let index = 0; index < trimmed.length; index += 1) {
1480
+ const character = trimmed[index];
1481
+ if (escaped) {
1482
+ escaped = false;
1483
+ continue;
1484
+ }
1485
+ if (character === "\\" && quote !== "'") {
1486
+ escaped = true;
1487
+ continue;
1488
+ }
1489
+ if (quote) {
1490
+ if (character === quote) quote = void 0;
1491
+ continue;
1492
+ }
1493
+ if (character === "'" || character === '"') {
1494
+ quote = character;
1495
+ continue;
1496
+ }
1497
+ if (character === ">" || character === "<" || character === "(" || character === ")") {
1498
+ return void 0;
1499
+ }
1500
+ const next = trimmed[index + 1];
1501
+ if (character === "&" && next !== "&") return void 0;
1502
+ const separatorLength = character === ";" || character === "|" ? next === character ? 2 : 1 : character === "&" && next === "&" ? 2 : 0;
1503
+ if (separatorLength === 0) continue;
1504
+ const segment = trimmed.slice(start, index).trim();
1505
+ if (!segment) return void 0;
1506
+ segments.push(segment);
1507
+ index += separatorLength - 1;
1508
+ start = index + 1;
1466
1509
  }
1467
- if (input.questions.length < 1 || input.questions.length > 3) {
1468
- return { ok: false, error: "questions must contain 1-3 items" };
1510
+ if (quote || escaped) return void 0;
1511
+ const finalSegment = trimmed.slice(start).trim();
1512
+ if (!finalSegment) return void 0;
1513
+ segments.push(finalSegment);
1514
+ return segments;
1515
+ }
1516
+ function isSafeSegment(segment, safeSubcommands, workingDirectory, platform) {
1517
+ if (hasShellExpansion(segment) || /(^|\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {
1518
+ return false;
1469
1519
  }
1470
- const questions = [];
1471
- for (const [questionIndex, rawQuestion] of input.questions.entries()) {
1472
- if (!isRecord2(rawQuestion)) {
1473
- return { ok: false, error: `question ${questionIndex + 1} must be an object` };
1520
+ const tokens = shellWords(segment);
1521
+ if (!tokens || tokens.length === 0) return false;
1522
+ const command = tokens[0]?.toLowerCase();
1523
+ if (!command || MUTATING_COMMANDS.has(command)) return false;
1524
+ const args = tokens.slice(1);
1525
+ if (!hasSafeArguments(command, args)) return false;
1526
+ if (command === "hostname") return args.length === 0;
1527
+ if (command === "tasklist") return platform === "win32" && isSafeTasklistArguments(args);
1528
+ if (READ_ONLY_COMMANDS.has(command)) return true;
1529
+ return isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory);
1530
+ }
1531
+ function hasShellExpansion(segment) {
1532
+ let quote;
1533
+ let escaped = false;
1534
+ for (const character of segment) {
1535
+ if (escaped) {
1536
+ escaped = false;
1537
+ continue;
1474
1538
  }
1475
- const id = stringField(rawQuestion.id);
1476
- const header = stringField(rawQuestion.header);
1477
- const question = stringField(rawQuestion.question);
1478
- if (!id || !header || !question) {
1479
- return {
1480
- ok: false,
1481
- error: `question ${questionIndex + 1} requires non-empty id, header, and question`
1482
- };
1539
+ if (character === "\\" && quote !== "'") {
1540
+ escaped = true;
1541
+ continue;
1483
1542
  }
1484
- if (!Array.isArray(rawQuestion.options)) {
1485
- return { ok: false, error: `question ${questionIndex + 1} options must be an array` };
1543
+ if (quote) {
1544
+ if (character === quote) quote = void 0;
1545
+ else if (character === "$" && quote === '"') return true;
1546
+ continue;
1486
1547
  }
1487
- if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {
1488
- return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };
1548
+ if (character === "'" || character === '"') {
1549
+ quote = character;
1550
+ continue;
1489
1551
  }
1490
- const options = [];
1491
- for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {
1492
- if (!isRecord2(rawOption)) {
1493
- return {
1494
- ok: false,
1495
- error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`
1496
- };
1497
- }
1498
- const label = stringField(rawOption.label);
1499
- if (!label) {
1500
- return {
1501
- ok: false,
1502
- error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`
1503
- };
1504
- }
1505
- const description = stringField(rawOption.description);
1506
- if (!description) {
1507
- return {
1508
- ok: false,
1509
- error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`
1510
- };
1511
- }
1512
- options.push({ label, description });
1552
+ if (["$", "*", "?", "[", "{"].includes(character)) return true;
1553
+ }
1554
+ return false;
1555
+ }
1556
+ function shellWords(segment) {
1557
+ const words = [];
1558
+ let word = "";
1559
+ let quote;
1560
+ let escaped = false;
1561
+ for (const character of segment) {
1562
+ if (escaped) {
1563
+ word += character;
1564
+ escaped = false;
1565
+ continue;
1513
1566
  }
1514
- questions.push({ id, header, question, options });
1567
+ if (character === "\\" && quote !== "'") {
1568
+ escaped = true;
1569
+ continue;
1570
+ }
1571
+ if (quote) {
1572
+ if (character === quote) quote = void 0;
1573
+ else word += character;
1574
+ continue;
1575
+ }
1576
+ if (character === "'" || character === '"') quote = character;
1577
+ else if (/\s/.test(character)) {
1578
+ if (word) words.push(word);
1579
+ word = "";
1580
+ } else word += character;
1515
1581
  }
1516
- return { ok: true, questions };
1582
+ if (quote || escaped) return void 0;
1583
+ if (word) words.push(word);
1584
+ return words;
1517
1585
  }
1518
- async function answerPlanModeQuestions(questions, ctx, lifecycle) {
1519
- const answers = await askPlanModeQuestions(
1520
- questions,
1521
- ctx,
1522
- () => lifecycle.isCurrent() && lifecycle.isEnabled()
1523
- );
1524
- if (!lifecycle.isCurrent()) {
1525
- return planModeQuestionCancelled(
1526
- questions,
1527
- "cancelled",
1528
- "Plan-mode question cancelled because the session changed."
1529
- );
1586
+ function hasSafeArguments(command, args) {
1587
+ const forbidden = /* @__PURE__ */ new Set(["-i", "--in-place", "--fix", "--write", "-delete", "--delete"]);
1588
+ if (args.some((argument) => forbidden.has(argument))) return false;
1589
+ if (command === "sed" && args.some(
1590
+ (argument) => argument.startsWith("--in-place=") || /^-[^-]+/.test(argument) && argument.slice(1).includes("i")
1591
+ )) {
1592
+ return false;
1593
+ }
1594
+ if (command === "find" && args.some(
1595
+ (argument) => ["-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"].includes(
1596
+ argument
1597
+ )
1598
+ )) {
1599
+ return false;
1600
+ }
1601
+ if (command === "date" && args.some((argument) => argument === "-s" || argument.startsWith("--set"))) {
1602
+ return false;
1603
+ }
1604
+ if ((command === "sort" || command === "tree") && args.some(
1605
+ (argument) => argument === "-o" || argument.startsWith("-o") && !argument.startsWith("--") || argument.startsWith("--output")
1606
+ )) {
1607
+ return false;
1608
+ }
1609
+ if (command === "sort" && args.some(
1610
+ (argument) => argument === "-T" || argument.startsWith("-T") && argument.length > 2 || argument.startsWith("--temporary-directory") || argument.startsWith("--compress-program")
1611
+ )) {
1612
+ return false;
1613
+ }
1614
+ if (command === "diff" && args.some((argument) => argument === "--output" || argument.startsWith("--output="))) {
1615
+ return false;
1616
+ }
1617
+ if (command === "uniq" && args.filter((argument) => !argument.startsWith("-")).length > 1) {
1618
+ return false;
1619
+ }
1620
+ if (command === "fd" && args.some(
1621
+ (argument) => ["-x", "-X", "--exec", "--exec-batch"].some(
1622
+ (flag) => argument === flag || argument.startsWith(`${flag}=`)
1623
+ )
1624
+ )) {
1625
+ return false;
1626
+ }
1627
+ if (command === "rg" && args.some((argument) => argument === "--pre" || argument.startsWith("--pre="))) {
1628
+ return false;
1629
+ }
1630
+ if (command === "bat" && args.some((argument) => argument === "--pager" || argument.startsWith("--pager="))) {
1631
+ return false;
1632
+ }
1633
+ return true;
1634
+ }
1635
+ var allowReadOnlyArguments = () => true;
1636
+ var BUILTIN_GIT_VALIDATORS = {
1637
+ status: allowReadOnlyArguments,
1638
+ log: allowReadOnlyArguments,
1639
+ diff: allowReadOnlyArguments,
1640
+ show: allowReadOnlyArguments,
1641
+ branch: isSafeGitBranchArguments,
1642
+ remote: isSafeGitRemoteArguments,
1643
+ "ls-files": allowReadOnlyArguments,
1644
+ grep: isSafeGitGrepArguments
1645
+ };
1646
+ var CONFIGURABLE_GIT_VALIDATORS = {
1647
+ "rev-parse": allowReadOnlyArguments,
1648
+ blame: allowReadOnlyArguments,
1649
+ describe: allowReadOnlyArguments,
1650
+ "merge-base": allowReadOnlyArguments,
1651
+ "ls-tree": allowReadOnlyArguments,
1652
+ "cat-file": isSafeGitCatFileArguments
1653
+ };
1654
+ var GH_VALIDATORS = {
1655
+ "pr view": isSafeGhReadArguments,
1656
+ "pr list": isSafeGhReadArguments,
1657
+ "issue view": isSafeGhReadArguments,
1658
+ "issue list": isSafeGhReadArguments
1659
+ };
1660
+ function isSafeStructuredCommand(command, args, safeSubcommands, workingDirectory) {
1661
+ if (command === "git") return isSafeGitCommand(args, safeSubcommands, workingDirectory);
1662
+ if (command === "gh") return isSafeGhCommand(args, safeSubcommands);
1663
+ const subcommandIndex = args.findIndex((argument) => !argument.startsWith("-"));
1664
+ const subcommand = args[subcommandIndex]?.toLowerCase();
1665
+ const subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];
1666
+ if (command === "sed") {
1667
+ const script = args.find((argument) => !argument.startsWith("-"));
1668
+ return Boolean(script) && (args.includes("-n") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) && /^\d+(,\d+)?p$/.test(script ?? "");
1530
1669
  }
1531
- if (!lifecycle.isEnabled()) {
1532
- return planModeQuestionCancelled(
1533
- questions,
1534
- "plan_mode_inactive",
1535
- "Plan-mode question cancelled because Plan mode is no longer active."
1670
+ if (["node", "python", "python3", "tsc", "biome", "ruff", "ty"].includes(command)) {
1671
+ if (args.includes("--version")) return true;
1672
+ return command === "tsc" && args.includes("--noEmit") && !args.some(
1673
+ (argument) => argument === "--incremental" || argument.startsWith("--incremental=") || argument === "--tsBuildInfoFile" || argument.startsWith("--tsBuildInfoFile=") || argument === "--generateTrace" || argument.startsWith("--generateTrace=")
1536
1674
  );
1537
1675
  }
1538
- if (!answers) {
1539
- return planModeQuestionCancelled(
1540
- questions,
1541
- "cancelled",
1542
- "User cancelled the Plan-mode question prompt."
1543
- );
1676
+ if (command === "npm") {
1677
+ if (subcommand === "audit" && subcommandArgs.includes("fix")) return false;
1678
+ if (["list", "ls", "view", "info", "search", "outdated", "audit", "test"].includes(
1679
+ subcommand ?? ""
1680
+ )) {
1681
+ return true;
1682
+ }
1683
+ return subcommand === "run" && ["test", "check", "typecheck", "lint"].includes(args[1] ?? "");
1544
1684
  }
1545
- return planModeQuestionAnswered(questions, answers);
1546
- }
1547
- async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
1548
- const { runQuestionnaire, sanitizeTerminalText } = await import("@narumitw/pi-tui-kit");
1549
- if (!shouldContinue()) return void 0;
1550
- const runnerQuestions = questions.map((question, index) => ({
1551
- id: String(index),
1552
- header: displayText(question.header, `Question ${index + 1}`, sanitizeTerminalText),
1553
- prompt: displayText(question.question, `Question ${index + 1}`, sanitizeTerminalText),
1554
- options: question.options.map((option, optionIndex) => ({
1555
- ...option,
1556
- label: displayText(option.label, `Option ${optionIndex + 1}`, sanitizeTerminalText)
1557
- }))
1558
- }));
1559
- const result = await runQuestionnaire(ctx, {
1560
- questions: runnerQuestions,
1561
- allowNotes: true,
1562
- maxTextLength: MAX_PLAN_MODE_RESPONSE_LENGTH,
1563
- signal: ctx.signal,
1564
- isCurrent: shouldContinue
1565
- });
1566
- if (!shouldContinue()) return void 0;
1567
- return mapQuestionnaireResult(questions, result);
1685
+ if (["cargo", "go", "pytest", "vitest", "jest"].includes(command)) {
1686
+ return ["test", "check"].includes(subcommand ?? "") || ["pytest", "vitest", "jest"].includes(command);
1687
+ }
1688
+ return false;
1568
1689
  }
1569
- function mapQuestionnaireResult(questions, result) {
1570
- if (result.kind !== "submitted") return void 0;
1571
- if (result.answers.length !== questions.length) {
1572
- throw new Error("Questionnaire returned an incomplete answer set");
1690
+ function isSafeTasklistArguments(args) {
1691
+ for (let index = 0; index < args.length; index += 1) {
1692
+ const argument = args[index]?.toLowerCase();
1693
+ if (["/v", "/nh", "/svc"].includes(argument ?? "")) continue;
1694
+ if (argument === "/fo") {
1695
+ const format = args[index + 1]?.toLowerCase();
1696
+ if (!format || !["table", "list", "csv"].includes(format)) return false;
1697
+ index += 1;
1698
+ continue;
1699
+ }
1700
+ if (argument === "/fi") {
1701
+ const filter = args[index + 1];
1702
+ if (!filter || filter.startsWith("/")) return false;
1703
+ index += 1;
1704
+ continue;
1705
+ }
1706
+ if (argument === "/m") {
1707
+ const module = args[index + 1];
1708
+ if (module && !module.startsWith("/")) index += 1;
1709
+ continue;
1710
+ }
1711
+ return false;
1573
1712
  }
1574
- const answers = /* @__PURE__ */ new Map();
1575
- for (const answer of result.answers) {
1576
- const index = Number(answer.questionId);
1577
- if (!Number.isSafeInteger(index) || String(index) !== answer.questionId || !questions[index]) {
1578
- throw new Error("Questionnaire returned an answer for an unknown question");
1713
+ return true;
1714
+ }
1715
+ function isSafeGetProcessArguments(args) {
1716
+ return hasSafePowerShellQueryArguments(
1717
+ args,
1718
+ /* @__PURE__ */ new Set(["-module", "-fileversioninfo", "-includeusername"]),
1719
+ /* @__PURE__ */ new Set(["-name", "-id"])
1720
+ );
1721
+ }
1722
+ function isSafeGetServiceArguments(args) {
1723
+ return hasSafePowerShellQueryArguments(
1724
+ args,
1725
+ /* @__PURE__ */ new Set(["-dependentservices", "-requiredservices"]),
1726
+ /* @__PURE__ */ new Set(["-name", "-displayname", "-include", "-exclude"])
1727
+ );
1728
+ }
1729
+ function hasSafePowerShellQueryArguments(args, switches, valueOptions) {
1730
+ let positionalValues = 0;
1731
+ for (let index = 0; index < args.length; index += 1) {
1732
+ const argument = args[index];
1733
+ const normalized = argument?.toLowerCase();
1734
+ if (!argument || !normalized) return false;
1735
+ if (!argument.startsWith("-")) {
1736
+ positionalValues += 1;
1737
+ if (positionalValues > 1) return false;
1738
+ continue;
1579
1739
  }
1580
- if (answers.has(index)) throw new Error("Questionnaire returned duplicate answers");
1581
- if (answer.wasCustom) {
1582
- if (answer.optionIndex !== void 0) {
1583
- throw new Error("Questionnaire returned a custom answer with an option index");
1584
- }
1585
- if (!answer.answer.trim()) return void 0;
1586
- } else if (answer.optionIndex === void 0 || !questions[index]?.options[answer.optionIndex - 1]) {
1587
- throw new Error("Questionnaire returned an invalid selected option");
1740
+ if (switches.has(normalized)) continue;
1741
+ if (!valueOptions.has(normalized)) return false;
1742
+ const value = args[index + 1];
1743
+ if (!value || value.startsWith("-")) return false;
1744
+ index += 1;
1745
+ }
1746
+ return true;
1747
+ }
1748
+ function isSafeGitCommand(args, safeSubcommands, workingDirectory) {
1749
+ const subcommandIndex = parseGitGlobalOptions(args, workingDirectory);
1750
+ if (subcommandIndex === void 0) return false;
1751
+ const subcommand = args[subcommandIndex]?.toLowerCase();
1752
+ if (!subcommand || subcommand.startsWith("-")) return false;
1753
+ const subcommandArgs = args.slice(subcommandIndex + 1);
1754
+ const builtinValidator = BUILTIN_GIT_VALIDATORS[subcommand];
1755
+ const configuredValidator = CONFIGURABLE_GIT_VALIDATORS[subcommand];
1756
+ const configured = safeSubcommands.git?.includes(subcommand) === true;
1757
+ const validator = builtinValidator ?? (configured ? configuredValidator : void 0);
1758
+ return validator !== void 0 && hasSafeGitArguments(subcommand, subcommandArgs) && validator(subcommandArgs);
1759
+ }
1760
+ function parseGitGlobalOptions(args, workingDirectory) {
1761
+ let index = 0;
1762
+ while (index < args.length) {
1763
+ const argument = args[index];
1764
+ if (argument === "--no-pager") {
1765
+ index += 1;
1766
+ continue;
1588
1767
  }
1589
- answers.set(index, answer);
1768
+ if (argument !== "-C") break;
1769
+ const directory = args[index + 1];
1770
+ if (!directory || !isCurrentWorkingDirectory(directory, workingDirectory)) return void 0;
1771
+ index += 2;
1590
1772
  }
1591
- return questions.map((question, index) => {
1592
- const answer = answers.get(index);
1593
- if (!answer) throw new Error("Questionnaire returned an incomplete answer set");
1594
- const answerText = answer.wasCustom ? answer.answer : question.options[(answer.optionIndex ?? 0) - 1]?.label ?? answer.answer;
1595
- return answerFor(question, answerText, {
1596
- wasCustom: answer.wasCustom,
1597
- optionIndex: answer.optionIndex,
1598
- note: answer.note
1599
- });
1600
- });
1773
+ return index;
1601
1774
  }
1602
- function displayText(value, fallback, sanitize) {
1603
- const sanitized = sanitize(value);
1604
- return sanitized.trim() ? sanitized : fallback;
1775
+ function isCurrentWorkingDirectory(directory, workingDirectory) {
1776
+ if (!workingDirectory || directory.split(/[\\/]+/u).includes("..")) return false;
1777
+ if (normalize(directory) === ".") return true;
1778
+ return isAbsolute(directory) && normalize(directory) === normalize(workingDirectory);
1605
1779
  }
1606
- function answerFor(question, answer, options) {
1607
- const result = {
1608
- id: question.id,
1609
- header: question.header,
1610
- question: question.question,
1611
- answer,
1612
- wasCustom: options.wasCustom
1613
- };
1614
- if (options.optionIndex !== void 0) result.optionIndex = options.optionIndex;
1615
- if (options.note !== void 0) result.note = options.note;
1616
- return result;
1780
+ function hasSafeGitArguments(subcommand, args) {
1781
+ return !args.some(
1782
+ (argument) => argument === "--help" || argument === "--show-signature" || argument.startsWith("--show-signature=") || argument.includes("%G") || argument === "--output" || argument.startsWith("--output=") || argument === "--ext-diff" || argument.startsWith("--ext-diff=") || argument === "--textconv" || argument.startsWith("--textconv=") || argument === "--paginate" || argument === "--open-files-in-pager" || argument.startsWith("--open-files-in-pager=") || subcommand === "grep" && (argument === "-O" || argument.startsWith("-O"))
1783
+ );
1617
1784
  }
1618
- function planModeQuestionAnswered(questions, answers) {
1619
- return {
1620
- content: [
1621
- { type: "text", text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }
1622
- ],
1623
- details: { cancelled: false, questions, answers }
1624
- };
1785
+ function isSafeGitCatFileArguments(args) {
1786
+ return !args.some(
1787
+ (argument) => matchesLongOptionPrefix(argument, "--filters", "--fi") || matchesLongOptionPrefix(argument, "--textconv", "--t")
1788
+ );
1625
1789
  }
1626
- function planModeQuestionCancelled(questions, reason, message) {
1627
- return {
1628
- content: [
1629
- {
1630
- type: "text",
1631
- text: formatPlanModeQuestionPayload({ cancelled: true, reason, message })
1632
- }
1633
- ],
1634
- details: { cancelled: true, reason, questions }
1635
- };
1790
+ function isSafeGitGrepArguments(args) {
1791
+ return !args.some(
1792
+ (argument) => matchesLongOptionPrefix(argument, "--textconv", "--textc") || matchesLongOptionPrefix(argument, "--open-files-in-pager", "--op") || matchesLongOptionPrefix(argument, "--ext-grep", "--ext")
1793
+ );
1636
1794
  }
1637
- function formatPlanModeQuestionPayload(payload) {
1638
- return JSON.stringify(payload, null, 2);
1795
+ function matchesLongOptionPrefix(argument, option, shortest) {
1796
+ const optionName = argument.split("=", 1)[0] ?? "";
1797
+ return optionName.length >= shortest.length && option.startsWith(optionName);
1639
1798
  }
1640
- function isRecord2(value) {
1641
- return typeof value === "object" && value !== null;
1799
+ function isSafeGitBranchArguments(args) {
1800
+ if (args.some((argument) => !argument.startsWith("-"))) return false;
1801
+ return !args.some(
1802
+ (argument) => /^-[^-]*[dDmMcCu]/.test(argument) || matchesLongOptionPrefix(argument, "--delete", "--del") || matchesLongOptionPrefix(argument, "--move", "--mov") || matchesLongOptionPrefix(argument, "--copy", "--cop") || matchesLongOptionPrefix(argument, "--edit-description", "--e") || matchesLongOptionPrefix(argument, "--unset-upstream", "--u") || matchesLongOptionPrefix(argument, "--set-upstream-to", "--set-u") || matchesLongOptionPrefix(argument, "--create-reflog", "--creat")
1803
+ );
1642
1804
  }
1643
- function stringField(value) {
1644
- return typeof value === "string" ? value.trim() : void 0;
1805
+ function isSafeGitRemoteArguments(args) {
1806
+ const actionIndex = args.findIndex((argument) => !argument.startsWith("-"));
1807
+ if (actionIndex < 0) return true;
1808
+ const action = args[actionIndex];
1809
+ if (action === "get-url") return true;
1810
+ if (action !== "show") return false;
1811
+ const showArgs = args.slice(actionIndex + 1);
1812
+ if (showArgs.includes("--")) return false;
1813
+ const remotes = showArgs.filter((argument) => !argument.startsWith("-"));
1814
+ return remotes.length === 0 || remotes.length === 1 && showArgs.includes("-n");
1815
+ }
1816
+ function isSafeGhCommand(args, safeSubcommands) {
1817
+ const group = args[0]?.toLowerCase();
1818
+ const action = args[1]?.toLowerCase();
1819
+ if (!group || !action || group.startsWith("-") || action.startsWith("-")) return false;
1820
+ const path = `${group} ${action}`;
1821
+ if (!safeSubcommands.gh?.includes(path)) return false;
1822
+ const validator = GH_VALIDATORS[path];
1823
+ return validator?.(args.slice(2)) ?? false;
1824
+ }
1825
+ function isSafeGhReadArguments(args) {
1826
+ return !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);
1827
+ }
1828
+ function isUnsafeGhReadArgument(argument) {
1829
+ return argument.startsWith("-w") || argument === "--web" || argument.startsWith("--web=") || argument === "--browser" || argument.startsWith("--browser=") || argument === "--paginate" || argument === "--pager" || argument.startsWith("--pager=") || argument === "--output" || argument.startsWith("--output=");
1830
+ }
1831
+ function hasGhJsonOutput(args) {
1832
+ let hasJson = false;
1833
+ for (let index = 0; index < args.length; index += 1) {
1834
+ const argument = args[index];
1835
+ if (argument === "--json") {
1836
+ const value = args[index + 1];
1837
+ if (!value || value.startsWith("-")) return false;
1838
+ hasJson = true;
1839
+ index += 1;
1840
+ } else if (argument.startsWith("--json=")) {
1841
+ if (argument === "--json=") return false;
1842
+ hasJson = true;
1843
+ }
1844
+ }
1845
+ return hasJson;
1645
1846
  }
1646
1847
 
1647
1848
  // src/tool-selection.ts
@@ -1690,23 +1891,17 @@ export {
1690
1891
  planFromCompletionDetails,
1691
1892
  planModeCompleted,
1692
1893
  renderPlanModeCompletion,
1693
- PLAN_HISTORY_IMPLEMENTATION_PROMPT,
1694
- parseProposedPlan,
1695
- invalidPlanMessage,
1696
- latestAssistantText,
1697
- latestAssistantStopReason,
1698
- messageTextContent,
1699
- retentionLabel,
1700
- implementationRetentionPreview,
1701
- createImplementationRetentionCoordinator,
1702
- classifyPlanModeTool,
1703
- canSelectToolInPlanMode,
1704
- readCommand,
1705
- findBlockedCommandSegment,
1706
- findBlockedPowerShellCommandSegment,
1894
+ observeImplementationModelSelections,
1895
+ hasImplementationPreferences,
1896
+ sameModel,
1897
+ safeImplementationText,
1898
+ preferenceError,
1899
+ preflightImplementationPreferences,
1900
+ createImplementationPreferenceChange,
1707
1901
  PLAN_MODE_THINKING_LEVELS,
1708
1902
  IMPLEMENTATION_PLAN_RETENTIONS,
1709
1903
  planModeSettingsPath,
1904
+ normalizePlanModeSettings,
1710
1905
  normalizeKeyId,
1711
1906
  readPlanModeSettings,
1712
1907
  updatePlanModeSettings,
@@ -1715,6 +1910,15 @@ export {
1715
1910
  configuredImplementationPlanRetention,
1716
1911
  configuredPlanExportPath,
1717
1912
  configuredPlanModeToggleShortcut,
1913
+ PLAN_HISTORY_IMPLEMENTATION_PROMPT,
1914
+ parseProposedPlan,
1915
+ invalidPlanMessage,
1916
+ latestAssistantText,
1917
+ latestAssistantStopReason,
1918
+ messageTextContent,
1919
+ retentionLabel,
1920
+ implementationRetentionPreview,
1921
+ createImplementationRetentionCoordinator,
1718
1922
  exportStoredPlan,
1719
1923
  planExportDestination,
1720
1924
  PLAN_MODE_QUESTION_TOOL_NAME,
@@ -1722,9 +1926,14 @@ export {
1722
1926
  normalizePlanModeQuestionParams,
1723
1927
  answerPlanModeQuestions,
1724
1928
  planModeQuestionCancelled,
1929
+ classifyPlanModeTool,
1930
+ canSelectToolInPlanMode,
1931
+ readCommand,
1932
+ findBlockedCommandSegment,
1933
+ findBlockedPowerShellCommandSegment,
1725
1934
  compareTools,
1726
1935
  toolPolicyLabel,
1727
1936
  defaultPlanModeToolNames,
1728
1937
  snapshotPlanModeSelectedNames
1729
1938
  };
1730
- //# sourceMappingURL=chunk-TZVK4O2Q.js.map
1939
+ //# sourceMappingURL=chunk-YUFPCQVG.js.map