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