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