@narumitw/pi-plan-mode 0.49.3 → 0.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1490 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+
4
+ // src/completion-tool.ts
5
+ import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
6
+ import { Markdown } from "@earendil-works/pi-tui";
7
+ var PLAN_MODE_COMPLETE_TOOL_NAME = "plan_mode_complete";
8
+ var PLAN_MODE_COMPLETE_VERSION = 1;
9
+ var PLAN_MODE_MAX_CHARS = 5e4;
10
+ var PLAN_MODE_COMPLETE_PARAMS = {
11
+ type: "object",
12
+ additionalProperties: false,
13
+ required: ["plan"],
14
+ properties: {
15
+ plan: {
16
+ type: "string",
17
+ minLength: 1,
18
+ maxLength: PLAN_MODE_MAX_CHARS,
19
+ description: "The complete decision-ready implementation plan in Markdown."
20
+ }
21
+ }
22
+ };
23
+ function normalizePlanModeCompletion(input) {
24
+ if (!isRecord(input) || typeof input.plan !== "string") {
25
+ return { ok: false, error: "plan must be a string" };
26
+ }
27
+ const plan = input.plan.trim();
28
+ if (!plan) return { ok: false, error: "plan must not be empty" };
29
+ if (plan.length > PLAN_MODE_MAX_CHARS) {
30
+ return {
31
+ ok: false,
32
+ error: `plan must not exceed ${PLAN_MODE_MAX_CHARS} characters`
33
+ };
34
+ }
35
+ return { ok: true, plan };
36
+ }
37
+ function planFromCompletionDetails(value) {
38
+ if (!isRecord(value)) return void 0;
39
+ if (value.version !== PLAN_MODE_COMPLETE_VERSION || value.source !== PLAN_MODE_COMPLETE_TOOL_NAME) {
40
+ return void 0;
41
+ }
42
+ const normalized = normalizePlanModeCompletion({ plan: value.plan });
43
+ return normalized.ok ? normalized.plan : void 0;
44
+ }
45
+ function planModeCompleted(plan) {
46
+ return {
47
+ content: [{ type: "text", text: `**Proposed Plan**
48
+
49
+ ${plan}` }],
50
+ details: {
51
+ version: PLAN_MODE_COMPLETE_VERSION,
52
+ source: PLAN_MODE_COMPLETE_TOOL_NAME,
53
+ plan
54
+ },
55
+ terminate: true
56
+ };
57
+ }
58
+ function planModeCompletionMarkdown(result) {
59
+ const content = result.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
60
+ if (content) return content;
61
+ const plan = planFromCompletionDetails(result.details);
62
+ return plan ? `**Proposed Plan**
63
+
64
+ ${plan}` : "";
65
+ }
66
+ function renderPlanModeCompletion(result) {
67
+ return new Markdown(planModeCompletionMarkdown(result), 0, 0, getMarkdownTheme());
68
+ }
69
+ function isRecord(value) {
70
+ return typeof value === "object" && value !== null && !Array.isArray(value);
71
+ }
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 PROPOSED_PLAN_PATTERN = /^<proposed_plan>[\t ]*\r?\n([\s\S]*?)\r?\n<\/proposed_plan>[\t ]*$/gm;
79
+ var PROPOSED_PLAN_BLOCK_PATTERN = /^<proposed_plan>[\t ]*\r?\n[\s\S]*?\r?\n<\/proposed_plan>[\t ]*$/gm;
80
+ function parseProposedPlan(text) {
81
+ const openingCount = text.match(/<proposed_plan>/gi)?.length ?? 0;
82
+ const closingCount = text.match(/<\/proposed_plan>/gi)?.length ?? 0;
83
+ if (openingCount === 0 && closingCount === 0) return { kind: "absent" };
84
+ if (openingCount > 1 || closingCount > 1) return { kind: "multiple" };
85
+ if (openingCount === 1 && closingCount === 0) return { kind: "unclosed" };
86
+ if (openingCount !== 1 || closingCount !== 1) return { kind: "malformed" };
87
+ const matches = Array.from(text.matchAll(PROPOSED_PLAN_PATTERN));
88
+ if (matches.length !== 1) return { kind: "malformed" };
89
+ const plan = matches[0]?.[1]?.trim() ?? "";
90
+ return plan ? { kind: "valid", plan } : { kind: "empty" };
91
+ }
92
+ function invalidPlanMessage(kind) {
93
+ const detail = {
94
+ empty: "the block is empty",
95
+ multiple: "more than one plan block was produced",
96
+ malformed: "the tags must be on their own lines",
97
+ unclosed: "the closing tag is missing"
98
+ }[kind];
99
+ return `Proposed plan is not ready: ${detail}. Continue Plan mode and produce one complete non-empty <proposed_plan> block.`;
100
+ }
101
+ function latestAssistantText(messages) {
102
+ if (!Array.isArray(messages)) return "";
103
+ for (const entry of [...messages].reverse()) {
104
+ const message = entry?.message ?? entry;
105
+ if (message?.role !== "assistant") continue;
106
+ const text = messageText(message);
107
+ if (text) return text;
108
+ }
109
+ return "";
110
+ }
111
+ function messageContainsLegacyPlanModeContextArtifact(message) {
112
+ return unwrapSessionMessage(message).customType === PLAN_CONTEXT_MESSAGE_TYPE;
113
+ }
114
+ function messageContainsPlanModeImplementationContextArtifact(message) {
115
+ return unwrapSessionMessage(message).customType === PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE;
116
+ }
117
+ function injectActiveImplementationContext(messages, activeImplementation) {
118
+ let foundCurrentHandoff = false;
119
+ const messagesWithoutStaleContext = messages.filter((message) => {
120
+ if (messageContainsPlanModeImplementationContextArtifact(message)) return false;
121
+ if (!messageContainsPlanModeImplementationHandoff(message)) return true;
122
+ if (!foundCurrentHandoff && messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)) {
123
+ foundCurrentHandoff = true;
124
+ return true;
125
+ }
126
+ return false;
127
+ });
128
+ if (foundCurrentHandoff) return messagesWithoutStaleContext;
129
+ let insertionIndex = 0;
130
+ while (isSummaryMessage(messagesWithoutStaleContext[insertionIndex])) insertionIndex += 1;
131
+ const contextMessage = {
132
+ role: "custom",
133
+ customType: PLAN_IMPLEMENTATION_CONTEXT_MESSAGE_TYPE,
134
+ content: `[ACTIVE IMPLEMENTATION PLAN]
135
+
136
+ 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:
137
+
138
+ ${activeImplementation.plan}`,
139
+ display: false,
140
+ timestamp: activeImplementation.startedAt
141
+ };
142
+ return [
143
+ ...messagesWithoutStaleContext.slice(0, insertionIndex),
144
+ contextMessage,
145
+ ...messagesWithoutStaleContext.slice(insertionIndex)
146
+ ];
147
+ }
148
+ function messageContainsInactivePlanModeArtifact(message) {
149
+ const candidate = unwrapSessionMessage(message);
150
+ return candidate.customType === PROPOSED_PLAN_MESSAGE_TYPE || candidate.role === "toolResult" && candidate.toolName === PLAN_MODE_COMPLETE_TOOL_NAME;
151
+ }
152
+ function messageContainsPlanModeImplementationHandoff(message) {
153
+ const candidate = unwrapSessionMessage(message);
154
+ return candidate.role === "user" && contentText(candidate.content).trimStart().startsWith(PLAN_IMPLEMENTATION_HANDOFF_PREFIX);
155
+ }
156
+ function messageContainsExactPlanModeImplementationHandoff(message, plan) {
157
+ const candidate = unwrapSessionMessage(message);
158
+ if (candidate.role !== "user") return false;
159
+ return contentText(candidate.content).trim() === `${PLAN_IMPLEMENTATION_HANDOFF_PREFIX}
160
+
161
+ ${plan}`.trim();
162
+ }
163
+ function isSummaryMessage(message) {
164
+ const role = unwrapSessionMessage(message)?.role;
165
+ return role === "compactionSummary" || role === "branchSummary";
166
+ }
167
+ function stripProposedPlanBlocksFromMessage(message) {
168
+ return replaceAssistantContent(message, stripProposedPlanBlocksFromContent);
169
+ }
170
+ function stripPlanModeCompletionCallsFromMessage(message) {
171
+ return replaceAssistantContent(message, (content) => {
172
+ if (!Array.isArray(content)) return content;
173
+ const nextContent = content.filter((block) => {
174
+ const candidate = block;
175
+ return !(candidate.type === "toolCall" && candidate.name === PLAN_MODE_COMPLETE_TOOL_NAME);
176
+ });
177
+ return nextContent.length === content.length ? content : nextContent;
178
+ });
179
+ }
180
+ function isEmptyAssistantMessage(message) {
181
+ const candidate = unwrapSessionMessage(message);
182
+ return candidate.role === "assistant" && Array.isArray(candidate.content) && candidate.content.length === 0;
183
+ }
184
+ function replaceAssistantContent(message, transform) {
185
+ const candidate = unwrapSessionMessage(message);
186
+ if (candidate.role !== "assistant") return message;
187
+ const content = transform(candidate.content);
188
+ if (content === candidate.content) return message;
189
+ if (isSessionMessageEntry(message)) {
190
+ return { ...message, message: { ...candidate, content } };
191
+ }
192
+ return { ...candidate, content };
193
+ }
194
+ function unwrapSessionMessage(message) {
195
+ const entry = message;
196
+ return entry?.message ?? message ?? {};
197
+ }
198
+ function isSessionMessageEntry(message) {
199
+ return typeof message === "object" && message !== null && "message" in message;
200
+ }
201
+ function stripProposedPlanBlocksFromContent(content) {
202
+ if (typeof content === "string") return stripProposedPlanBlocks(content);
203
+ if (!Array.isArray(content)) return content;
204
+ let changed = false;
205
+ const nextContent = content.map((block) => {
206
+ const textBlock = block;
207
+ if (textBlock.type !== "text" || typeof textBlock.text !== "string") return block;
208
+ const text = stripProposedPlanBlocks(textBlock.text);
209
+ if (text === textBlock.text) return block;
210
+ changed = true;
211
+ return { ...textBlock, text };
212
+ });
213
+ return changed ? nextContent : content;
214
+ }
215
+ function stripProposedPlanBlocks(text) {
216
+ return text.replace(PROPOSED_PLAN_BLOCK_PATTERN, "");
217
+ }
218
+ function messageText(message) {
219
+ return contentText(message.content);
220
+ }
221
+ function contentText(content) {
222
+ if (typeof content === "string") return content;
223
+ if (!Array.isArray(content)) return "";
224
+ return content.map((block) => {
225
+ const textBlock = block;
226
+ return textBlock.type === "text" && typeof textBlock.text === "string" ? textBlock.text : "";
227
+ }).filter(Boolean).join("\n");
228
+ }
229
+
230
+ // src/implementation-retention.ts
231
+ function retentionLabel(retention) {
232
+ return {
233
+ keep: "Keep plan active",
234
+ "clear-on-start": "Use plan for handoff only",
235
+ "clear-after-first-run": "Clear after first implementation run"
236
+ }[retention];
237
+ }
238
+ function implementationRetentionPreview(retention) {
239
+ return {
240
+ keep: "After Implement: Keep plan active until /plan exit.",
241
+ "clear-on-start": "After Implement: Use the plan for the implementation handoff only, then clear it.",
242
+ "clear-after-first-run": "After Implement: Clear after the first implementation run settles."
243
+ }[retention];
244
+ }
245
+ function createImplementationRetentionCoordinator() {
246
+ let implementationWithDeliveredContext;
247
+ let restoredImplementationAwaitingContext;
248
+ return {
249
+ restore(activeImplementation) {
250
+ restoredImplementationAwaitingContext = activeImplementation && activeImplementation.retention !== "keep" ? activeImplementation.id : void 0;
251
+ },
252
+ transformContext(messages, state) {
253
+ const messagesWithoutPlanContext = messages.filter(
254
+ (message) => !messageContainsLegacyPlanModeContextArtifact(message) && !messageContainsPlanModeImplementationContextArtifact(message)
255
+ );
256
+ if (state.enabled) {
257
+ return {
258
+ messages: messagesWithoutPlanContext.filter(
259
+ (message) => !messageContainsPlanModeImplementationHandoff(message)
260
+ )
261
+ };
262
+ }
263
+ const activeImplementation = state.activeImplementation;
264
+ const inactiveMessages = activeImplementation ? messagesWithoutPlanContext : messagesWithoutPlanContext.filter(
265
+ (message) => !messageContainsPlanModeImplementationHandoff(message)
266
+ );
267
+ const filteredMessages = inactiveMessages.filter((message) => !messageContainsInactivePlanModeArtifact(message)).map(stripProposedPlanBlocksFromMessage).map(stripPlanModeCompletionCallsFromMessage).filter((message) => !isEmptyAssistantMessage(message));
268
+ if (!activeImplementation) return { messages: filteredMessages };
269
+ const contextualMessages = injectActiveImplementationContext(
270
+ filteredMessages,
271
+ activeImplementation
272
+ );
273
+ const deliveredCurrentHandoff = restoredImplementationAwaitingContext === activeImplementation.id || filteredMessages.some(
274
+ (message) => messageContainsExactPlanModeImplementationHandoff(message, activeImplementation.plan)
275
+ );
276
+ if (!deliveredCurrentHandoff) return { messages: contextualMessages };
277
+ restoredImplementationAwaitingContext = void 0;
278
+ if (activeImplementation.retention === "clear-after-first-run") {
279
+ implementationWithDeliveredContext = activeImplementation.id;
280
+ }
281
+ return {
282
+ messages: contextualMessages,
283
+ clearActiveImplementationId: activeImplementation.retention === "clear-on-start" ? activeImplementation.id : void 0
284
+ };
285
+ },
286
+ implementationSettled(activeImplementation) {
287
+ if (activeImplementation?.retention !== "clear-after-first-run" || implementationWithDeliveredContext !== activeImplementation.id) {
288
+ return void 0;
289
+ }
290
+ implementationWithDeliveredContext = void 0;
291
+ return activeImplementation.id;
292
+ },
293
+ reset() {
294
+ implementationWithDeliveredContext = void 0;
295
+ restoredImplementationAwaitingContext = void 0;
296
+ }
297
+ };
298
+ }
299
+
300
+ // src/tool-policy.ts
301
+ var BUILTIN_SAFE_GIT_SUBCOMMANDS = [
302
+ "status",
303
+ "log",
304
+ "diff",
305
+ "show",
306
+ "branch",
307
+ "remote",
308
+ "ls-files",
309
+ "grep"
310
+ ];
311
+ var CONFIGURABLE_SAFE_GIT_SUBCOMMANDS = [
312
+ "rev-parse",
313
+ "blame",
314
+ "describe",
315
+ "merge-base",
316
+ "ls-tree",
317
+ "cat-file"
318
+ ];
319
+ var SAFE_GIT_SUBCOMMANDS = [
320
+ ...BUILTIN_SAFE_GIT_SUBCOMMANDS,
321
+ ...CONFIGURABLE_SAFE_GIT_SUBCOMMANDS
322
+ ];
323
+ var SAFE_GH_SUBCOMMAND_PATHS = ["pr view", "pr list", "issue view", "issue list"];
324
+ var SAFE_BUILTIN_PLAN_TOOLS = /* @__PURE__ */ new Set(["read", "bash", "grep", "find", "ls"]);
325
+ var BLOCKED_BUILTIN_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
326
+ var MUTATING_COMMANDS = /* @__PURE__ */ new Set([
327
+ "rm",
328
+ "rmdir",
329
+ "mv",
330
+ "cp",
331
+ "mkdir",
332
+ "touch",
333
+ "chmod",
334
+ "chown",
335
+ "chgrp",
336
+ "ln",
337
+ "tee",
338
+ "truncate",
339
+ "dd",
340
+ "sudo",
341
+ "su",
342
+ "kill",
343
+ "pkill",
344
+ "killall",
345
+ "reboot",
346
+ "shutdown",
347
+ "vim",
348
+ "vi",
349
+ "nano",
350
+ "emacs",
351
+ "code",
352
+ "subl"
353
+ ]);
354
+ var READ_ONLY_COMMANDS = /* @__PURE__ */ new Set([
355
+ "cat",
356
+ "head",
357
+ "tail",
358
+ "grep",
359
+ "find",
360
+ "ls",
361
+ "pwd",
362
+ "echo",
363
+ "printf",
364
+ "wc",
365
+ "sort",
366
+ "uniq",
367
+ "diff",
368
+ "file",
369
+ "stat",
370
+ "du",
371
+ "df",
372
+ "tree",
373
+ "which",
374
+ "whereis",
375
+ "type",
376
+ "printenv",
377
+ "uname",
378
+ "whoami",
379
+ "id",
380
+ "date",
381
+ "uptime",
382
+ "ps",
383
+ "jq",
384
+ "rg",
385
+ "fd",
386
+ "bat",
387
+ "eza"
388
+ ]);
389
+ function isBuiltinTool(tool) {
390
+ return tool.sourceInfo.source === "builtin";
391
+ }
392
+ function classifyPlanModeTool(tool) {
393
+ if (!isBuiltinTool(tool)) return "user-opt-in";
394
+ if (BLOCKED_BUILTIN_TOOLS.has(tool.name)) return "blocked";
395
+ if (tool.name === "bash") return "limited";
396
+ return SAFE_BUILTIN_PLAN_TOOLS.has(tool.name) ? "read-only" : "blocked";
397
+ }
398
+ function canSelectToolInPlanMode(tool) {
399
+ return classifyPlanModeTool(tool) !== "blocked";
400
+ }
401
+ function readCommand(input) {
402
+ const command = input;
403
+ return typeof command?.command === "string" ? command.command : "";
404
+ }
405
+ function findBlockedCommandSegment(command, safeSubcommands = {}) {
406
+ const segments = splitShellSegments(command);
407
+ if (!segments || segments.length === 0) return command.trim() || "(empty command)";
408
+ return segments.find((segment) => !isSafeSegment(segment, safeSubcommands));
409
+ }
410
+ function splitShellSegments(command) {
411
+ const trimmed = command.trim();
412
+ if (!trimmed || /[\n\r`]/.test(trimmed)) return void 0;
413
+ const segments = [];
414
+ let quote;
415
+ let escaped = false;
416
+ let start = 0;
417
+ for (let index = 0; index < trimmed.length; index += 1) {
418
+ const character = trimmed[index];
419
+ if (escaped) {
420
+ escaped = false;
421
+ continue;
422
+ }
423
+ if (character === "\\" && quote !== "'") {
424
+ escaped = true;
425
+ continue;
426
+ }
427
+ if (quote) {
428
+ if (character === quote) quote = void 0;
429
+ continue;
430
+ }
431
+ if (character === "'" || character === '"') {
432
+ quote = character;
433
+ continue;
434
+ }
435
+ if (character === ">" || character === "<" || character === "(" || character === ")") {
436
+ return void 0;
437
+ }
438
+ const next = trimmed[index + 1];
439
+ if (character === "&" && next !== "&") return void 0;
440
+ const separatorLength = character === ";" || character === "|" ? next === character ? 2 : 1 : character === "&" && next === "&" ? 2 : 0;
441
+ if (separatorLength === 0) continue;
442
+ const segment = trimmed.slice(start, index).trim();
443
+ if (!segment) return void 0;
444
+ segments.push(segment);
445
+ index += separatorLength - 1;
446
+ start = index + 1;
447
+ }
448
+ if (quote || escaped) return void 0;
449
+ const finalSegment = trimmed.slice(start).trim();
450
+ if (!finalSegment) return void 0;
451
+ segments.push(finalSegment);
452
+ return segments;
453
+ }
454
+ function isSafeSegment(segment, safeSubcommands) {
455
+ if (hasShellExpansion(segment) || /(^|\s)[A-Za-z_][A-Za-z0-9_]*=/.test(segment)) {
456
+ return false;
457
+ }
458
+ const tokens = shellWords(segment);
459
+ if (!tokens || tokens.length === 0) return false;
460
+ const command = tokens[0]?.toLowerCase();
461
+ if (!command || MUTATING_COMMANDS.has(command)) return false;
462
+ const args = tokens.slice(1);
463
+ if (!hasSafeArguments(command, args)) return false;
464
+ if (READ_ONLY_COMMANDS.has(command)) return true;
465
+ return isSafeStructuredCommand(command, args, safeSubcommands);
466
+ }
467
+ function hasShellExpansion(segment) {
468
+ let quote;
469
+ let escaped = false;
470
+ for (const character of segment) {
471
+ if (escaped) {
472
+ escaped = false;
473
+ continue;
474
+ }
475
+ if (character === "\\" && quote !== "'") {
476
+ escaped = true;
477
+ continue;
478
+ }
479
+ if (quote) {
480
+ if (character === quote) quote = void 0;
481
+ else if (character === "$" && quote === '"') return true;
482
+ continue;
483
+ }
484
+ if (character === "'" || character === '"') {
485
+ quote = character;
486
+ continue;
487
+ }
488
+ if (["$", "*", "?", "[", "{"].includes(character)) return true;
489
+ }
490
+ return false;
491
+ }
492
+ function shellWords(segment) {
493
+ const words = [];
494
+ let word = "";
495
+ let quote;
496
+ let escaped = false;
497
+ for (const character of segment) {
498
+ if (escaped) {
499
+ word += character;
500
+ escaped = false;
501
+ continue;
502
+ }
503
+ if (character === "\\" && quote !== "'") {
504
+ escaped = true;
505
+ continue;
506
+ }
507
+ if (quote) {
508
+ if (character === quote) quote = void 0;
509
+ else word += character;
510
+ continue;
511
+ }
512
+ if (character === "'" || character === '"') quote = character;
513
+ else if (/\s/.test(character)) {
514
+ if (word) words.push(word);
515
+ word = "";
516
+ } else word += character;
517
+ }
518
+ if (quote || escaped) return void 0;
519
+ if (word) words.push(word);
520
+ return words;
521
+ }
522
+ function hasSafeArguments(command, args) {
523
+ const forbidden = /* @__PURE__ */ new Set(["-i", "--in-place", "--fix", "--write", "-delete", "--delete"]);
524
+ if (args.some((argument) => forbidden.has(argument))) return false;
525
+ if (command === "sed" && args.some(
526
+ (argument) => argument.startsWith("--in-place=") || /^-[^-]+/.test(argument) && argument.slice(1).includes("i")
527
+ )) {
528
+ return false;
529
+ }
530
+ if (command === "find" && args.some(
531
+ (argument) => ["-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"].includes(
532
+ argument
533
+ )
534
+ )) {
535
+ return false;
536
+ }
537
+ if (command === "date" && args.some((argument) => argument === "-s" || argument.startsWith("--set"))) {
538
+ return false;
539
+ }
540
+ if ((command === "sort" || command === "tree") && args.some(
541
+ (argument) => argument === "-o" || argument.startsWith("-o") && !argument.startsWith("--") || argument.startsWith("--output")
542
+ )) {
543
+ return false;
544
+ }
545
+ if (command === "sort" && args.some(
546
+ (argument) => argument === "-T" || argument.startsWith("-T") && argument.length > 2 || argument.startsWith("--temporary-directory") || argument.startsWith("--compress-program")
547
+ )) {
548
+ return false;
549
+ }
550
+ if (command === "diff" && args.some((argument) => argument === "--output" || argument.startsWith("--output="))) {
551
+ return false;
552
+ }
553
+ if (command === "uniq" && args.filter((argument) => !argument.startsWith("-")).length > 1) {
554
+ return false;
555
+ }
556
+ if (command === "fd" && args.some(
557
+ (argument) => ["-x", "-X", "--exec", "--exec-batch"].some(
558
+ (flag) => argument === flag || argument.startsWith(`${flag}=`)
559
+ )
560
+ )) {
561
+ return false;
562
+ }
563
+ if (command === "rg" && args.some((argument) => argument === "--pre" || argument.startsWith("--pre="))) {
564
+ return false;
565
+ }
566
+ if (command === "bat" && args.some((argument) => argument === "--pager" || argument.startsWith("--pager="))) {
567
+ return false;
568
+ }
569
+ return true;
570
+ }
571
+ var allowReadOnlyArguments = () => true;
572
+ var BUILTIN_GIT_VALIDATORS = {
573
+ status: allowReadOnlyArguments,
574
+ log: allowReadOnlyArguments,
575
+ diff: allowReadOnlyArguments,
576
+ show: allowReadOnlyArguments,
577
+ branch: isSafeGitBranchArguments,
578
+ remote: isSafeGitRemoteArguments,
579
+ "ls-files": allowReadOnlyArguments,
580
+ grep: isSafeGitGrepArguments
581
+ };
582
+ var CONFIGURABLE_GIT_VALIDATORS = {
583
+ "rev-parse": allowReadOnlyArguments,
584
+ blame: allowReadOnlyArguments,
585
+ describe: allowReadOnlyArguments,
586
+ "merge-base": allowReadOnlyArguments,
587
+ "ls-tree": allowReadOnlyArguments,
588
+ "cat-file": isSafeGitCatFileArguments
589
+ };
590
+ var GH_VALIDATORS = {
591
+ "pr view": isSafeGhReadArguments,
592
+ "pr list": isSafeGhReadArguments,
593
+ "issue view": isSafeGhReadArguments,
594
+ "issue list": isSafeGhReadArguments
595
+ };
596
+ function isSafeStructuredCommand(command, args, safeSubcommands) {
597
+ if (command === "git") return isSafeGitCommand(args, safeSubcommands);
598
+ if (command === "gh") return isSafeGhCommand(args, safeSubcommands);
599
+ const subcommandIndex = args.findIndex((argument) => !argument.startsWith("-"));
600
+ const subcommand = args[subcommandIndex]?.toLowerCase();
601
+ const subcommandArgs = subcommandIndex >= 0 ? args.slice(subcommandIndex + 1) : [];
602
+ if (command === "sed") {
603
+ const script = args.find((argument) => !argument.startsWith("-"));
604
+ return Boolean(script) && (args.includes("-n") || args.some((argument) => /^-[^-]*n[^-]*$/.test(argument))) && /^\d+(,\d+)?p$/.test(script ?? "");
605
+ }
606
+ if (["node", "python", "python3", "tsc", "biome", "ruff", "ty"].includes(command)) {
607
+ if (args.includes("--version")) return true;
608
+ return command === "tsc" && args.includes("--noEmit") && !args.some(
609
+ (argument) => argument === "--incremental" || argument.startsWith("--incremental=") || argument === "--tsBuildInfoFile" || argument.startsWith("--tsBuildInfoFile=") || argument === "--generateTrace" || argument.startsWith("--generateTrace=")
610
+ );
611
+ }
612
+ if (command === "npm") {
613
+ if (subcommand === "audit" && subcommandArgs.includes("fix")) return false;
614
+ if (["list", "ls", "view", "info", "search", "outdated", "audit", "test"].includes(
615
+ subcommand ?? ""
616
+ )) {
617
+ return true;
618
+ }
619
+ return subcommand === "run" && ["test", "check", "typecheck", "lint"].includes(args[1] ?? "");
620
+ }
621
+ if (["cargo", "go", "pytest", "vitest", "jest"].includes(command)) {
622
+ return ["test", "check"].includes(subcommand ?? "") || ["pytest", "vitest", "jest"].includes(command);
623
+ }
624
+ return false;
625
+ }
626
+ function isSafeGitCommand(args, safeSubcommands) {
627
+ let subcommandIndex = 0;
628
+ while (args[subcommandIndex] === "--no-pager") subcommandIndex += 1;
629
+ const subcommand = args[subcommandIndex]?.toLowerCase();
630
+ if (!subcommand || subcommand.startsWith("-")) return false;
631
+ const subcommandArgs = args.slice(subcommandIndex + 1);
632
+ const builtinValidator = BUILTIN_GIT_VALIDATORS[subcommand];
633
+ const configuredValidator = CONFIGURABLE_GIT_VALIDATORS[subcommand];
634
+ const configured = safeSubcommands.git?.includes(subcommand) === true;
635
+ const validator = builtinValidator ?? (configured ? configuredValidator : void 0);
636
+ return validator !== void 0 && hasSafeGitArguments(subcommand, subcommandArgs) && validator(subcommandArgs);
637
+ }
638
+ function hasSafeGitArguments(subcommand, args) {
639
+ return !args.some(
640
+ (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"))
641
+ );
642
+ }
643
+ function isSafeGitCatFileArguments(args) {
644
+ return !args.some(
645
+ (argument) => matchesLongOptionPrefix(argument, "--filters", "--fi") || matchesLongOptionPrefix(argument, "--textconv", "--t")
646
+ );
647
+ }
648
+ function isSafeGitGrepArguments(args) {
649
+ return !args.some(
650
+ (argument) => matchesLongOptionPrefix(argument, "--textconv", "--textc") || matchesLongOptionPrefix(argument, "--open-files-in-pager", "--op") || matchesLongOptionPrefix(argument, "--ext-grep", "--ext")
651
+ );
652
+ }
653
+ function matchesLongOptionPrefix(argument, option, shortest) {
654
+ const optionName = argument.split("=", 1)[0] ?? "";
655
+ return optionName.length >= shortest.length && option.startsWith(optionName);
656
+ }
657
+ function isSafeGitBranchArguments(args) {
658
+ if (args.some((argument) => !argument.startsWith("-"))) return false;
659
+ return !args.some(
660
+ (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")
661
+ );
662
+ }
663
+ function isSafeGitRemoteArguments(args) {
664
+ const actionIndex = args.findIndex((argument) => !argument.startsWith("-"));
665
+ if (actionIndex < 0) return true;
666
+ const action = args[actionIndex];
667
+ if (action === "get-url") return true;
668
+ if (action !== "show") return false;
669
+ const showArgs = args.slice(actionIndex + 1);
670
+ if (showArgs.includes("--")) return false;
671
+ const remotes = showArgs.filter((argument) => !argument.startsWith("-"));
672
+ return remotes.length === 0 || remotes.length === 1 && showArgs.includes("-n");
673
+ }
674
+ function isSafeGhCommand(args, safeSubcommands) {
675
+ const group = args[0]?.toLowerCase();
676
+ const action = args[1]?.toLowerCase();
677
+ if (!group || !action || group.startsWith("-") || action.startsWith("-")) return false;
678
+ const path = `${group} ${action}`;
679
+ if (!safeSubcommands.gh?.includes(path)) return false;
680
+ const validator = GH_VALIDATORS[path];
681
+ return validator?.(args.slice(2)) ?? false;
682
+ }
683
+ function isSafeGhReadArguments(args) {
684
+ return !args.some(isUnsafeGhReadArgument) && hasGhJsonOutput(args);
685
+ }
686
+ function isUnsafeGhReadArgument(argument) {
687
+ 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=");
688
+ }
689
+ function hasGhJsonOutput(args) {
690
+ let hasJson = false;
691
+ for (let index = 0; index < args.length; index += 1) {
692
+ const argument = args[index];
693
+ if (argument === "--json") {
694
+ const value = args[index + 1];
695
+ if (!value || value.startsWith("-")) return false;
696
+ hasJson = true;
697
+ index += 1;
698
+ } else if (argument.startsWith("--json=")) {
699
+ if (argument === "--json=") return false;
700
+ hasJson = true;
701
+ }
702
+ }
703
+ return hasJson;
704
+ }
705
+
706
+ // src/settings.ts
707
+ import { randomUUID } from "node:crypto";
708
+ import { constants } from "node:fs";
709
+ import { mkdir, open, rename, rm, writeFile } from "node:fs/promises";
710
+ import { basename, dirname, join } from "node:path";
711
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
712
+ var PLAN_MODE_SETTINGS_FILE = "pi-plan-mode.json";
713
+ var LEGACY_PLAN_MODE_SETTINGS_FILE = "plan-mode.json";
714
+ var MAX_SETTINGS_BYTES = 64 * 1024;
715
+ var PLAN_MODE_THINKING_LEVELS = [
716
+ "inherit",
717
+ "off",
718
+ "minimal",
719
+ "low",
720
+ "medium",
721
+ "high",
722
+ "xhigh",
723
+ "max"
724
+ ];
725
+ var IMPLEMENTATION_PLAN_RETENTIONS = [
726
+ "keep",
727
+ "clear-on-start",
728
+ "clear-after-first-run"
729
+ ];
730
+ var DEFAULT_PLAN_EXPORT_PATH = "PLAN.md";
731
+ var MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]);
732
+ var BASE_KEYS = /* @__PURE__ */ new Set([
733
+ ..."abcdefghijklmnopqrstuvwxyz0123456789",
734
+ "`",
735
+ "-",
736
+ "=",
737
+ "[",
738
+ "]",
739
+ "\\",
740
+ ";",
741
+ "'",
742
+ ",",
743
+ ".",
744
+ "/",
745
+ "!",
746
+ "@",
747
+ "#",
748
+ "$",
749
+ "%",
750
+ "^",
751
+ "&",
752
+ "*",
753
+ "(",
754
+ ")",
755
+ "_",
756
+ "+",
757
+ "|",
758
+ "~",
759
+ "{",
760
+ "}",
761
+ ":",
762
+ "<",
763
+ ">",
764
+ "?",
765
+ "escape",
766
+ "esc",
767
+ "enter",
768
+ "return",
769
+ "tab",
770
+ "space",
771
+ "backspace",
772
+ "delete",
773
+ "insert",
774
+ "clear",
775
+ "home",
776
+ "end",
777
+ "pageup",
778
+ "pagedown",
779
+ "up",
780
+ "down",
781
+ "left",
782
+ "right",
783
+ ...Array.from({ length: 12 }, (_unused, index) => `f${index + 1}`)
784
+ ]);
785
+ var MAX_PLAN_EXPORT_PATH_LENGTH = 4096;
786
+ var mutationQueues = /* @__PURE__ */ new Map();
787
+ function planModeSettingsPath() {
788
+ return join(getAgentDir(), PLAN_MODE_SETTINGS_FILE);
789
+ }
790
+ function legacyPlanModeSettingsPath() {
791
+ return join(getAgentDir(), LEGACY_PLAN_MODE_SETTINGS_FILE);
792
+ }
793
+ function normalizePlanModeSettings(value) {
794
+ if (!isSettingsDocument(value)) return void 0;
795
+ const thinkingLevel = Object.hasOwn(value, "thinkingLevel") ? Reflect.get(value, "thinkingLevel") : "inherit";
796
+ if (!PLAN_MODE_THINKING_LEVELS.includes(thinkingLevel)) {
797
+ return void 0;
798
+ }
799
+ const settings = {
800
+ thinkingLevel
801
+ };
802
+ if (Object.hasOwn(value, "defaultPlanTools")) {
803
+ const defaultPlanTools = normalizeToolNames(Reflect.get(value, "defaultPlanTools"));
804
+ if (!defaultPlanTools) return void 0;
805
+ settings.defaultPlanTools = defaultPlanTools;
806
+ }
807
+ if (Object.hasOwn(value, "implementationPlanRetention")) {
808
+ const implementationPlanRetention = Reflect.get(value, "implementationPlanRetention");
809
+ if (!IMPLEMENTATION_PLAN_RETENTIONS.includes(
810
+ implementationPlanRetention
811
+ )) {
812
+ return void 0;
813
+ }
814
+ settings.implementationPlanRetention = implementationPlanRetention;
815
+ }
816
+ if (Object.hasOwn(value, "defaultPlanExportPath")) {
817
+ const defaultPlanExportPath = normalizePlanExportPath(
818
+ Reflect.get(value, "defaultPlanExportPath")
819
+ );
820
+ if (!defaultPlanExportPath) return void 0;
821
+ settings.defaultPlanExportPath = defaultPlanExportPath;
822
+ }
823
+ if (Object.hasOwn(value, "toggleShortcut")) {
824
+ const toggleShortcut = normalizeKeyId(Reflect.get(value, "toggleShortcut"));
825
+ if (!toggleShortcut) return void 0;
826
+ settings.toggleShortcut = toggleShortcut;
827
+ }
828
+ if (Object.hasOwn(value, "safeSubcommands")) {
829
+ const safeSubcommands = normalizeSafeSubcommands(Reflect.get(value, "safeSubcommands"));
830
+ if (!safeSubcommands) return void 0;
831
+ settings.safeSubcommands = safeSubcommands;
832
+ }
833
+ return settings;
834
+ }
835
+ function normalizeToolNames(value) {
836
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && item.trim().length > 0)) {
837
+ return void 0;
838
+ }
839
+ return Array.from(new Set(value));
840
+ }
841
+ function normalizePlanExportPath(value) {
842
+ if (typeof value !== "string") return void 0;
843
+ const normalized = value.trim();
844
+ if (!normalized || normalized.length > MAX_PLAN_EXPORT_PATH_LENGTH || !/[^@\s]/u.test(normalized) || [...normalized].some((character) => {
845
+ const codePoint = character.codePointAt(0) ?? 0;
846
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
847
+ })) {
848
+ return void 0;
849
+ }
850
+ return normalized;
851
+ }
852
+ function normalizeKeyId(value) {
853
+ if (typeof value !== "string") return void 0;
854
+ const normalized = value.trim().toLowerCase();
855
+ const base = [...BASE_KEYS].sort((left, right) => right.length - left.length).find((candidate) => normalized === candidate || normalized.endsWith(`+${candidate}`));
856
+ if (!base) return void 0;
857
+ const prefix = normalized.slice(0, normalized.length - base.length);
858
+ if (!prefix) return base;
859
+ if (/^f(?:[1-9]|1[0-2])$/.test(base) || !prefix.endsWith("+")) return void 0;
860
+ const modifiers = prefix.slice(0, -1).split("+");
861
+ if (modifiers.length === 0 || modifiers.some((modifier) => !MODIFIERS.has(modifier)) || new Set(modifiers).size !== modifiers.length) {
862
+ return void 0;
863
+ }
864
+ return normalized;
865
+ }
866
+ function normalizeSafeSubcommands(value) {
867
+ if (!isSettingsDocument(value)) return void 0;
868
+ if (Object.keys(value).some((key) => key !== "git" && key !== "gh")) return void 0;
869
+ const safeSubcommands = {};
870
+ if (Object.hasOwn(value, "git")) {
871
+ const git = normalizeKnownValues(Reflect.get(value, "git"), SAFE_GIT_SUBCOMMANDS);
872
+ if (!git) return void 0;
873
+ safeSubcommands.git = git;
874
+ }
875
+ if (Object.hasOwn(value, "gh")) {
876
+ const gh = normalizeKnownValues(Reflect.get(value, "gh"), SAFE_GH_SUBCOMMAND_PATHS);
877
+ if (!gh) return void 0;
878
+ safeSubcommands.gh = gh;
879
+ }
880
+ return safeSubcommands;
881
+ }
882
+ function normalizeKnownValues(value, supported) {
883
+ if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && supported.includes(item))) {
884
+ return void 0;
885
+ }
886
+ return Array.from(new Set(value));
887
+ }
888
+ async function readPlanModeSettings(settingsPath) {
889
+ if (settingsPath) {
890
+ await awaitPlanModeSettingsWrites(settingsPath);
891
+ return (await readSettingsSnapshot(settingsPath)).result;
892
+ }
893
+ const canonicalPath = planModeSettingsPath();
894
+ await awaitPlanModeSettingsWrites(canonicalPath);
895
+ const canonical = await readSettingsSnapshot(canonicalPath);
896
+ const legacyPath = legacyPlanModeSettingsPath();
897
+ if (canonical.result.kind !== "missing") {
898
+ return await pathExists(legacyPath) ? {
899
+ ...canonical.result,
900
+ notice: `${LEGACY_PLAN_MODE_SETTINGS_FILE} ignored because ${PLAN_MODE_SETTINGS_FILE} takes precedence.`
901
+ } : canonical.result;
902
+ }
903
+ const legacy = await readSettingsSnapshot(legacyPath);
904
+ const raced = await readSettingsSnapshot(canonicalPath);
905
+ if (raced.result.kind !== "missing") return raced.result;
906
+ return legacy.result.kind === "loaded" ? {
907
+ ...legacy.result,
908
+ notice: `Using legacy ${LEGACY_PLAN_MODE_SETTINGS_FILE}; rename it to ${PLAN_MODE_SETTINGS_FILE}. The legacy file was not modified.`
909
+ } : legacy.result;
910
+ }
911
+ function updatePlanModeSettings(patch, options = {}) {
912
+ const settingsPath = options.settingsPath ?? planModeSettingsPath();
913
+ const legacySettingsPath = options.legacySettingsPath ?? (options.settingsPath ? void 0 : legacyPlanModeSettingsPath());
914
+ return enqueueMutation(settingsPath, async () => {
915
+ options.signal?.throwIfAborted();
916
+ const current = await readSettingsDocumentForUpdate(settingsPath, legacySettingsPath);
917
+ const updated = { ...current };
918
+ if (patch.thinkingLevel !== void 0) updated.thinkingLevel = patch.thinkingLevel;
919
+ if (patch.defaultPlanTools === null) delete updated.defaultPlanTools;
920
+ else if (patch.defaultPlanTools !== void 0) {
921
+ updated.defaultPlanTools = [...patch.defaultPlanTools];
922
+ }
923
+ if (patch.implementationPlanRetention !== void 0) {
924
+ updated.implementationPlanRetention = patch.implementationPlanRetention;
925
+ }
926
+ if (patch.defaultPlanExportPath === null) delete updated.defaultPlanExportPath;
927
+ else if (patch.defaultPlanExportPath !== void 0) {
928
+ updated.defaultPlanExportPath = patch.defaultPlanExportPath;
929
+ }
930
+ if (patch.toggleShortcut === null) delete updated.toggleShortcut;
931
+ else if (patch.toggleShortcut !== void 0) {
932
+ updated.toggleShortcut = patch.toggleShortcut;
933
+ }
934
+ const settings = normalizePlanModeSettings(updated);
935
+ if (!settings) throw invalidSettingsError(settingsPath, "invalid settings shape");
936
+ await publishSettings(settingsPath, updated, options.signal, options.beforeRename);
937
+ return settings;
938
+ });
939
+ }
940
+ async function awaitPlanModeSettingsWrites(settingsPath = planModeSettingsPath()) {
941
+ await mutationQueues.get(settingsPath);
942
+ }
943
+ function enqueueMutation(settingsPath, mutation) {
944
+ const previous = mutationQueues.get(settingsPath) ?? Promise.resolve();
945
+ const result = previous.then(mutation, mutation);
946
+ const settled = result.then(
947
+ () => void 0,
948
+ () => void 0
949
+ );
950
+ mutationQueues.set(settingsPath, settled);
951
+ void settled.finally(() => {
952
+ if (mutationQueues.get(settingsPath) === settled) mutationQueues.delete(settingsPath);
953
+ });
954
+ return result;
955
+ }
956
+ async function readSettingsDocumentForUpdate(settingsPath, legacySettingsPath) {
957
+ const canonical = await readSettingsSnapshot(settingsPath);
958
+ if (canonical.result.kind === "loaded") return canonical.document ?? {};
959
+ if (canonical.result.kind === "invalid") {
960
+ throw invalidSettingsError(settingsPath, canonical.result.reason);
961
+ }
962
+ if (!legacySettingsPath) return {};
963
+ const legacy = await readSettingsSnapshot(legacySettingsPath);
964
+ const raced = await readSettingsSnapshot(settingsPath);
965
+ if (raced.result.kind === "loaded") return raced.document ?? {};
966
+ if (raced.result.kind === "invalid") {
967
+ throw invalidSettingsError(settingsPath, raced.result.reason);
968
+ }
969
+ if (legacy.result.kind === "invalid") {
970
+ throw invalidSettingsError(legacySettingsPath, legacy.result.reason);
971
+ }
972
+ return legacy.document ?? {};
973
+ }
974
+ async function readSettingsSnapshot(settingsPath) {
975
+ let contents;
976
+ try {
977
+ contents = await readSettingsContents(settingsPath);
978
+ } catch (error) {
979
+ if (isNodeError(error) && error.code === "ENOENT") return { result: { kind: "missing" } };
980
+ return { result: { kind: "invalid", reason: safeReadError(error) } };
981
+ }
982
+ let parsed;
983
+ try {
984
+ parsed = JSON.parse(contents);
985
+ } catch {
986
+ return { result: { kind: "invalid", reason: "invalid JSON" } };
987
+ }
988
+ const settings = normalizePlanModeSettings(parsed);
989
+ if (!settings || !isSettingsDocument(parsed)) {
990
+ return { result: { kind: "invalid", reason: "invalid settings shape" } };
991
+ }
992
+ return { document: parsed, result: { kind: "loaded", settings } };
993
+ }
994
+ async function readSettingsContents(settingsPath) {
995
+ const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);
996
+ const handle = await open(settingsPath, flags);
997
+ try {
998
+ const stats = await handle.stat();
999
+ if (!stats.isFile()) throw new Error("settings path is not a regular file");
1000
+ if (stats.size > MAX_SETTINGS_BYTES) {
1001
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
1002
+ }
1003
+ const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
1004
+ let offset = 0;
1005
+ while (offset < buffer.byteLength) {
1006
+ const { bytesRead } = await handle.read(buffer, offset, buffer.byteLength - offset, offset);
1007
+ if (bytesRead === 0) break;
1008
+ offset += bytesRead;
1009
+ }
1010
+ if (offset > MAX_SETTINGS_BYTES) {
1011
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
1012
+ }
1013
+ try {
1014
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
1015
+ buffer.subarray(0, offset)
1016
+ );
1017
+ } catch {
1018
+ throw new Error("settings file is not valid UTF-8");
1019
+ }
1020
+ } finally {
1021
+ await handle.close();
1022
+ }
1023
+ }
1024
+ async function publishSettings(settingsPath, document, signal, beforeRename) {
1025
+ signal?.throwIfAborted();
1026
+ const contents = `${JSON.stringify(document, null, 2)}
1027
+ `;
1028
+ if (Buffer.byteLength(contents, "utf8") > MAX_SETTINGS_BYTES) {
1029
+ throw new Error(`settings document exceeds ${MAX_SETTINGS_BYTES} bytes`);
1030
+ }
1031
+ const directory = dirname(settingsPath);
1032
+ await mkdir(directory, { recursive: true });
1033
+ signal?.throwIfAborted();
1034
+ const temporaryPath = join(
1035
+ directory,
1036
+ `.${basename(settingsPath)}.${process.pid}.${randomUUID()}.tmp`
1037
+ );
1038
+ try {
1039
+ await writeFile(temporaryPath, contents, {
1040
+ encoding: "utf8",
1041
+ flag: "wx",
1042
+ mode: 384,
1043
+ signal
1044
+ });
1045
+ await beforeRename?.(temporaryPath, settingsPath);
1046
+ signal?.throwIfAborted();
1047
+ await rename(temporaryPath, settingsPath);
1048
+ } finally {
1049
+ await rm(temporaryPath, { force: true }).catch(() => void 0);
1050
+ }
1051
+ }
1052
+ function isSettingsDocument(value) {
1053
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1054
+ }
1055
+ async function pathExists(path) {
1056
+ try {
1057
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
1058
+ await handle.close();
1059
+ return true;
1060
+ } catch (error) {
1061
+ return !(isNodeError(error) && error.code === "ENOENT");
1062
+ }
1063
+ }
1064
+ function invalidSettingsError(settingsPath, reason) {
1065
+ return new Error(`pi-plan-mode settings at ${settingsPath} are invalid: ${reason}`);
1066
+ }
1067
+ function isNodeError(error) {
1068
+ return error instanceof Error && "code" in error;
1069
+ }
1070
+ function safeReadError(error) {
1071
+ if (isNodeError(error) && error.code === "ELOOP") return "settings path is not a regular file";
1072
+ return error instanceof Error ? error.message : String(error);
1073
+ }
1074
+ function configuredThinkingLevel(settings) {
1075
+ return settings.thinkingLevel === "inherit" ? void 0 : settings.thinkingLevel;
1076
+ }
1077
+ function configuredImplementationPlanRetention(settings) {
1078
+ return settings.implementationPlanRetention ?? "keep";
1079
+ }
1080
+ function configuredPlanExportPath(settings) {
1081
+ return settings.defaultPlanExportPath ?? DEFAULT_PLAN_EXPORT_PATH;
1082
+ }
1083
+ function configuredPlanModeToggleShortcut(settings) {
1084
+ return settings.toggleShortcut;
1085
+ }
1086
+
1087
+ // src/plan-export.ts
1088
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
1089
+ import { dirname as dirname2, resolve } from "node:path";
1090
+ import { stripVTControlCharacters } from "node:util";
1091
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
1092
+ async function exportStoredPlan(state, requestedPath, ctx, lifecycle, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1093
+ const plan = (state.enabled ? state.latestPlan : void 0)?.trim() ?? state.savedPlan?.plan.trim() ?? state.activeImplementation?.plan.trim();
1094
+ if (!plan) {
1095
+ const error = new Error(
1096
+ "No completed plan is available to export. Use /plan finalize when planning is complete."
1097
+ );
1098
+ if (!ctx.hasUI) throw error;
1099
+ ctx.ui.notify(error.message, "warning");
1100
+ return false;
1101
+ }
1102
+ const isCurrent = () => !lifecycle || lifecycle.isCurrent() && (!lifecycle.getState || lifecycle.getState() === state);
1103
+ let result;
1104
+ try {
1105
+ result = await exportPlanToFile(
1106
+ plan,
1107
+ requestedPath,
1108
+ ctx.cwd,
1109
+ lifecycle?.signal,
1110
+ isCurrent,
1111
+ defaultPath
1112
+ );
1113
+ } catch (error) {
1114
+ if (lifecycle?.signal.aborted || !isCurrent()) return false;
1115
+ if (!ctx.hasUI) throw error;
1116
+ const detail2 = error instanceof Error ? error.message : String(error);
1117
+ ctx.ui.notify(safeNotification(`Unable to export plan: ${detail2}`), "error");
1118
+ return false;
1119
+ }
1120
+ if (!isCurrent()) return false;
1121
+ const finishedReady = state.enabled && Boolean(state.latestPlan?.trim()) && lifecycle?.finishReady !== void 0;
1122
+ if (finishedReady) lifecycle.finishReady?.();
1123
+ const detail = finishedReady ? " Plan mode disabled." : "";
1124
+ ctx.ui.notify(safeNotification(`Plan exported to ${result.path}.${detail}`), "info");
1125
+ return true;
1126
+ }
1127
+ async function exportPlanToFile(plan, requestedPath, cwd, signal, isCurrent = () => true, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1128
+ const path = resolvePlanExportPath(requestedPath, cwd, defaultPath);
1129
+ await withFileMutationQueue(path, async () => {
1130
+ throwIfCancelled(signal, isCurrent);
1131
+ await mkdir2(dirname2(path), { recursive: true });
1132
+ throwIfCancelled(signal, isCurrent);
1133
+ try {
1134
+ await writeFile2(path, `${plan}
1135
+ `, { encoding: "utf8", flag: "wx" });
1136
+ } catch (error) {
1137
+ if (isNodeError2(error) && error.code === "EEXIST") {
1138
+ throw new Error(
1139
+ `Plan export target already exists: ${path}. Choose another path or remove it first.`
1140
+ );
1141
+ }
1142
+ throw error;
1143
+ }
1144
+ });
1145
+ return { path };
1146
+ }
1147
+ function planExportDestination(defaultPath, cwd) {
1148
+ return {
1149
+ configuredPath: safeNotification(defaultPath),
1150
+ resolvedPath: safeNotification(resolvePlanExportPath(void 0, cwd, defaultPath))
1151
+ };
1152
+ }
1153
+ function resolvePlanExportPath(requestedPath, cwd, defaultPath = DEFAULT_PLAN_EXPORT_PATH) {
1154
+ const rawPath = requestedPath?.trim() || defaultPath;
1155
+ const normalizedPath = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
1156
+ if (!normalizedPath.trim()) throw new Error("Plan export path must not be empty.");
1157
+ if (normalizedPath.includes("\0")) {
1158
+ throw new Error("Plan export path must not contain NUL bytes.");
1159
+ }
1160
+ return resolve(cwd, normalizedPath);
1161
+ }
1162
+ function safeNotification(value) {
1163
+ let sanitized = "";
1164
+ for (const character of stripVTControlCharacters(value)) {
1165
+ const codePoint = character.codePointAt(0);
1166
+ sanitized += codePoint !== void 0 && codePoint > 31 && !(codePoint >= 127 && codePoint <= 159) ? character : " ";
1167
+ }
1168
+ return sanitized;
1169
+ }
1170
+ function throwIfCancelled(signal, isCurrent) {
1171
+ if (!signal?.aborted && isCurrent()) return;
1172
+ throw signal?.reason instanceof Error ? signal.reason : new DOMException("Plan export cancelled", "AbortError");
1173
+ }
1174
+ function isNodeError2(error) {
1175
+ return error instanceof Error && "code" in error;
1176
+ }
1177
+
1178
+ // src/question-tool.ts
1179
+ var PLAN_MODE_QUESTION_TOOL_NAME = "plan_mode_question";
1180
+ var PLAN_MODE_QUESTION_PARAMS = {
1181
+ type: "object",
1182
+ additionalProperties: false,
1183
+ required: ["questions"],
1184
+ properties: {
1185
+ questions: {
1186
+ type: "array",
1187
+ minItems: 1,
1188
+ maxItems: 3,
1189
+ description: "Questions to show the user. Prefer 1 and do not exceed 3.",
1190
+ items: {
1191
+ type: "object",
1192
+ additionalProperties: false,
1193
+ required: ["id", "header", "question", "options"],
1194
+ properties: {
1195
+ id: {
1196
+ type: "string",
1197
+ description: "Stable identifier for mapping answers (snake_case)."
1198
+ },
1199
+ header: {
1200
+ type: "string",
1201
+ description: "Short header label shown in the UI (12 or fewer chars)."
1202
+ },
1203
+ question: { type: "string", description: "Single-sentence prompt shown to the user." },
1204
+ options: {
1205
+ type: "array",
1206
+ minItems: 2,
1207
+ maxItems: 4,
1208
+ description: "Provide 2-4 mutually exclusive choices. Put the recommended option first when there is a clear default.",
1209
+ items: {
1210
+ type: "object",
1211
+ additionalProperties: false,
1212
+ required: ["label", "description"],
1213
+ properties: {
1214
+ label: { type: "string", description: "User-facing label (1-5 words)." },
1215
+ description: {
1216
+ type: "string",
1217
+ description: "One short sentence explaining impact/tradeoff if selected."
1218
+ }
1219
+ }
1220
+ }
1221
+ }
1222
+ }
1223
+ }
1224
+ }
1225
+ }
1226
+ };
1227
+ function normalizePlanModeQuestionParams(input) {
1228
+ if (!isRecord2(input) || !Array.isArray(input.questions)) {
1229
+ return { ok: false, error: "questions must be an array" };
1230
+ }
1231
+ if (input.questions.length < 1 || input.questions.length > 3) {
1232
+ return { ok: false, error: "questions must contain 1-3 items" };
1233
+ }
1234
+ const questions = [];
1235
+ for (const [questionIndex, rawQuestion] of input.questions.entries()) {
1236
+ if (!isRecord2(rawQuestion)) {
1237
+ return { ok: false, error: `question ${questionIndex + 1} must be an object` };
1238
+ }
1239
+ const id = stringField(rawQuestion.id);
1240
+ const header = stringField(rawQuestion.header);
1241
+ const question = stringField(rawQuestion.question);
1242
+ if (!id || !header || !question) {
1243
+ return {
1244
+ ok: false,
1245
+ error: `question ${questionIndex + 1} requires non-empty id, header, and question`
1246
+ };
1247
+ }
1248
+ if (!Array.isArray(rawQuestion.options)) {
1249
+ return { ok: false, error: `question ${questionIndex + 1} options must be an array` };
1250
+ }
1251
+ if (rawQuestion.options.length < 2 || rawQuestion.options.length > 4) {
1252
+ return { ok: false, error: `question ${questionIndex + 1} options must contain 2-4 items` };
1253
+ }
1254
+ const options = [];
1255
+ for (const [optionIndex, rawOption] of rawQuestion.options.entries()) {
1256
+ if (!isRecord2(rawOption)) {
1257
+ return {
1258
+ ok: false,
1259
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} must be an object`
1260
+ };
1261
+ }
1262
+ const label = stringField(rawOption.label);
1263
+ if (!label) {
1264
+ return {
1265
+ ok: false,
1266
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a label`
1267
+ };
1268
+ }
1269
+ const description = stringField(rawOption.description);
1270
+ if (!description) {
1271
+ return {
1272
+ ok: false,
1273
+ error: `question ${questionIndex + 1} option ${optionIndex + 1} requires a description`
1274
+ };
1275
+ }
1276
+ options.push({ label, description });
1277
+ }
1278
+ questions.push({ id, header, question, options });
1279
+ }
1280
+ return { ok: true, questions };
1281
+ }
1282
+ async function answerPlanModeQuestions(questions, ctx, lifecycle) {
1283
+ const answers = await askPlanModeQuestions(
1284
+ questions,
1285
+ ctx,
1286
+ () => lifecycle.isCurrent() && lifecycle.isEnabled()
1287
+ );
1288
+ if (!lifecycle.isCurrent()) {
1289
+ return planModeQuestionCancelled(
1290
+ questions,
1291
+ "cancelled",
1292
+ "Plan-mode question cancelled because the session changed."
1293
+ );
1294
+ }
1295
+ if (!lifecycle.isEnabled()) {
1296
+ return planModeQuestionCancelled(
1297
+ questions,
1298
+ "plan_mode_inactive",
1299
+ "Plan-mode question cancelled because Plan mode is no longer active."
1300
+ );
1301
+ }
1302
+ if (!answers) {
1303
+ return planModeQuestionCancelled(
1304
+ questions,
1305
+ "cancelled",
1306
+ "User cancelled the Plan-mode question prompt."
1307
+ );
1308
+ }
1309
+ return planModeQuestionAnswered(questions, answers);
1310
+ }
1311
+ async function askPlanModeQuestions(questions, ctx, shouldContinue = () => true) {
1312
+ const answers = [];
1313
+ for (const question of questions) {
1314
+ const choices = question.options.map(formatPlanModeQuestionChoice);
1315
+ const otherChoice = `${question.options.length + 1}. Other (free-form)`;
1316
+ const choice = await ctx.ui.select(`${question.header}: ${question.question}`, [
1317
+ ...choices,
1318
+ otherChoice
1319
+ ]);
1320
+ if (!shouldContinue() || !choice) return void 0;
1321
+ if (choice === otherChoice) {
1322
+ const customAnswer = (await ctx.ui.editor(question.question, ""))?.trim();
1323
+ if (!shouldContinue() || !customAnswer) return void 0;
1324
+ answers.push({
1325
+ id: question.id,
1326
+ header: question.header,
1327
+ question: question.question,
1328
+ answer: customAnswer,
1329
+ wasCustom: true
1330
+ });
1331
+ continue;
1332
+ }
1333
+ const optionIndex = choices.indexOf(choice);
1334
+ const option = question.options[optionIndex];
1335
+ if (!option) return void 0;
1336
+ answers.push({
1337
+ id: question.id,
1338
+ header: question.header,
1339
+ question: question.question,
1340
+ answer: option.label,
1341
+ wasCustom: false,
1342
+ optionIndex: optionIndex + 1
1343
+ });
1344
+ }
1345
+ return answers;
1346
+ }
1347
+ function formatPlanModeQuestionChoice(option, index) {
1348
+ return `${index + 1}. ${option.label}${option.description ? ` \u2014 ${option.description}` : ""}`;
1349
+ }
1350
+ function planModeQuestionAnswered(questions, answers) {
1351
+ return {
1352
+ content: [
1353
+ { type: "text", text: formatPlanModeQuestionPayload({ cancelled: false, answers }) }
1354
+ ],
1355
+ details: { cancelled: false, questions, answers }
1356
+ };
1357
+ }
1358
+ function planModeQuestionCancelled(questions, reason, message) {
1359
+ return {
1360
+ content: [
1361
+ {
1362
+ type: "text",
1363
+ text: formatPlanModeQuestionPayload({ cancelled: true, reason, message })
1364
+ }
1365
+ ],
1366
+ details: { cancelled: true, reason, questions }
1367
+ };
1368
+ }
1369
+ function formatPlanModeQuestionPayload(payload) {
1370
+ return JSON.stringify(payload, null, 2);
1371
+ }
1372
+ function isRecord2(value) {
1373
+ return typeof value === "object" && value !== null;
1374
+ }
1375
+ function stringField(value) {
1376
+ return typeof value === "string" ? value.trim() : void 0;
1377
+ }
1378
+
1379
+ // src/required-tools.ts
1380
+ function withRequiredPlanModeTools(toolNames) {
1381
+ return unique([
1382
+ ...withoutRequiredPlanModeTools(toolNames),
1383
+ PLAN_MODE_QUESTION_TOOL_NAME,
1384
+ PLAN_MODE_COMPLETE_TOOL_NAME
1385
+ ]);
1386
+ }
1387
+ function withoutRequiredPlanModeTools(toolNames) {
1388
+ return toolNames.filter(
1389
+ (toolName) => toolName !== PLAN_MODE_QUESTION_TOOL_NAME && toolName !== PLAN_MODE_COMPLETE_TOOL_NAME
1390
+ );
1391
+ }
1392
+
1393
+ // src/tool-selection.ts
1394
+ function toolNameFromLegacyKey(key, tools) {
1395
+ const directName = tools.find((tool) => tool.name === key)?.name;
1396
+ if (directName) return directName;
1397
+ const [name] = key.split("");
1398
+ return tools.find((tool) => tool.name === name) ? name : void 0;
1399
+ }
1400
+ function compareTools(left, right) {
1401
+ const leftBuiltin = isBuiltinTool(left);
1402
+ const rightBuiltin = isBuiltinTool(right);
1403
+ if (leftBuiltin !== rightBuiltin) return leftBuiltin ? -1 : 1;
1404
+ return left.name.localeCompare(right.name);
1405
+ }
1406
+ function toolPolicyLabel(tool) {
1407
+ const policy = classifyPlanModeTool(tool);
1408
+ if (policy === "read-only") return "built-in read-only";
1409
+ if (policy === "limited") return "built-in limited";
1410
+ if (policy === "blocked") return "built-in blocked";
1411
+ return `user opt-in: ${toolSourceLabel(tool)}`;
1412
+ }
1413
+ function toolSourceLabel(tool) {
1414
+ const sourceInfo = tool.sourceInfo;
1415
+ const source = `${sourceInfo.scope}/${sourceInfo.source}`;
1416
+ return sourceInfo.path ? `${source} ${sourceInfo.path}` : source;
1417
+ }
1418
+ function unique(values) {
1419
+ return Array.from(new Set(values));
1420
+ }
1421
+ function filterAvailableSelectedToolNames(names, tools) {
1422
+ const availableNames = new Set(tools.filter(canSelectToolInPlanMode).map((tool) => tool.name));
1423
+ return unique(names.filter((name) => availableNames.has(name)));
1424
+ }
1425
+ function defaultPlanModeToolNames(tools, configuredNames) {
1426
+ if (configuredNames !== void 0) {
1427
+ return filterAvailableSelectedToolNames(configuredNames, tools);
1428
+ }
1429
+ return tools.filter((tool) => isBuiltinTool(tool) && SAFE_BUILTIN_PLAN_TOOLS.has(tool.name)).map((tool) => tool.name);
1430
+ }
1431
+ function snapshotPlanModeSelectedNames(tools, selection) {
1432
+ const selectedToolNames = selection.selectedToolNames ?? selection.selectedToolKeys?.map((key) => toolNameFromLegacyKey(key, tools)).filter((name) => name !== void 0);
1433
+ return new Set(
1434
+ selectedToolNames === void 0 ? defaultPlanModeToolNames(tools, selection.defaultPlanTools) : filterAvailableSelectedToolNames(selectedToolNames, tools)
1435
+ );
1436
+ }
1437
+ function snapshotPlanModeToolNames(tools, selectedNames, selection) {
1438
+ if (tools.length === 0 && selection.selectedToolNames === void 0 && selection.selectedToolKeys === void 0 && selection.defaultPlanTools === void 0) {
1439
+ return ["read", "bash", PLAN_MODE_QUESTION_TOOL_NAME, PLAN_MODE_COMPLETE_TOOL_NAME];
1440
+ }
1441
+ return withRequiredPlanModeTools(
1442
+ tools.filter((tool) => selectedNames.has(tool.name) && canSelectToolInPlanMode(tool)).map((tool) => tool.name)
1443
+ );
1444
+ }
1445
+
1446
+ export {
1447
+ PLAN_MODE_COMPLETE_TOOL_NAME,
1448
+ PLAN_MODE_COMPLETE_PARAMS,
1449
+ normalizePlanModeCompletion,
1450
+ planFromCompletionDetails,
1451
+ planModeCompleted,
1452
+ renderPlanModeCompletion,
1453
+ parseProposedPlan,
1454
+ invalidPlanMessage,
1455
+ latestAssistantText,
1456
+ retentionLabel,
1457
+ implementationRetentionPreview,
1458
+ createImplementationRetentionCoordinator,
1459
+ classifyPlanModeTool,
1460
+ canSelectToolInPlanMode,
1461
+ readCommand,
1462
+ findBlockedCommandSegment,
1463
+ PLAN_MODE_THINKING_LEVELS,
1464
+ IMPLEMENTATION_PLAN_RETENTIONS,
1465
+ planModeSettingsPath,
1466
+ normalizeKeyId,
1467
+ readPlanModeSettings,
1468
+ updatePlanModeSettings,
1469
+ awaitPlanModeSettingsWrites,
1470
+ configuredThinkingLevel,
1471
+ configuredImplementationPlanRetention,
1472
+ configuredPlanExportPath,
1473
+ configuredPlanModeToggleShortcut,
1474
+ exportStoredPlan,
1475
+ planExportDestination,
1476
+ PLAN_MODE_QUESTION_TOOL_NAME,
1477
+ PLAN_MODE_QUESTION_PARAMS,
1478
+ normalizePlanModeQuestionParams,
1479
+ answerPlanModeQuestions,
1480
+ planModeQuestionCancelled,
1481
+ compareTools,
1482
+ toolPolicyLabel,
1483
+ filterAvailableSelectedToolNames,
1484
+ defaultPlanModeToolNames,
1485
+ snapshotPlanModeSelectedNames,
1486
+ snapshotPlanModeToolNames,
1487
+ withRequiredPlanModeTools,
1488
+ withoutRequiredPlanModeTools
1489
+ };
1490
+ //# sourceMappingURL=chunk-6SDTCIHD.ts.map