// @bun
import {
  getAutoModeDenials,
  init_autoModeDenials
} from "./chunk-xwet3awb.js";
import {
  init_SearchBox
} from "./chunk-1xk07zm3.js";
import {
  init_useSearchInput,
  useSearchInput
} from "./chunk-7h2syxb4.js";
import {
  detectUnreachableRules,
  init_shadowedRuleDetection
} from "./chunk-r9c88ksn.js";
import {
  AddWorkspaceDirectory,
  init_AddWorkspaceDirectory
} from "./chunk-xex1vp3j.js";
import"./chunk-yq7btjq7.js";
import"./chunk-586erhd6.js";
import {
  BashTool,
  SandboxManager,
  Select,
  TextInput,
  WebFetchTool,
  applyPermissionUpdate,
  createPermissionRetryMessage,
  deletePermissionRule,
  getAllowRules,
  getAskRules,
  getDenyRules,
  init_AppState,
  init_BashTool,
  init_PermissionUpdate,
  init_TextInput,
  init_WebFetchTool,
  init_messages1 as init_messages,
  init_permissions,
  init_sandbox_adapter,
  init_select,
  init_useTerminalSize,
  permissionRuleSourceDisplayString,
  persistPermissionUpdate,
  useAppState,
  useSetAppState
} from "./chunk-4vz571bb.js";
import"./chunk-14p6wvsq.js";
import"./chunk-8hseq8b1.js";
import"./chunk-ddtxq6k5.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-ptxteaeh.js";
import"./chunk-wd53a7m4.js";
import"./chunk-hms8ge0k.js";
import"./chunk-whpphypt.js";
import"./chunk-pht800m5.js";
import"./chunk-pjkqh1kq.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-qd3r2s2n.js";
import"./chunk-djzd7tef.js";
import"./chunk-gyhnpbkx.js";
import"./chunk-71sdcaq6.js";
import"./chunk-60gf7p5s.js";
import"./chunk-sj3d0nqx.js";
import"./chunk-9pk9rk2w.js";
import"./chunk-javpza6a.js";
import"./chunk-6v7bre98.js";
import"./chunk-24kv69g3.js";
import {
  init_useExitOnCtrlCDWithKeybindings,
  useExitOnCtrlCDWithKeybindings
} from "./chunk-fcqebw9m.js";
import"./chunk-dnfd3c9s.js";
import"./chunk-15ezj4ww.js";
import"./chunk-1h284c6e.js";
import"./chunk-582g9yce.js";
import {
  init_useKeybinding
} from "./chunk-y3ztgztb.js";
import"./chunk-4spgkgr3.js";
import"./chunk-n8kbhswc.js";
import"./chunk-60fkafk2.js";
import"./chunk-fgbkrbk3.js";
import"./chunk-ssw61jfd.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-k8wq4qsj.js";
import"./chunk-g7d3xx1p.js";
import"./chunk-3wrx2943.js";
import"./chunk-7p9kkh0f.js";
import"./chunk-qp8cgz66.js";
import"./chunk-1mg610h2.js";
import"./chunk-93hc149s.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-nnat9jw5.js";
import"./chunk-hqxp6b72.js";
import"./chunk-4jzkqgf1.js";
import"./chunk-33rd41ng.js";
import"./chunk-f257kqw9.js";
import"./chunk-w5hnghah.js";
import"./chunk-36twraxy.js";
import"./chunk-1bkvnj0y.js";
import"./chunk-akdpcc5p.js";
import {
  SOURCES,
  getRelativeSettingsFilePathForSource,
  init_constants,
  init_permissionRuleParser,
  init_settings1 as init_settings,
  init_stringUtils,
  permissionRuleValueFromString,
  permissionRuleValueToString,
  plural
} from "./chunk-7rrkrej7.js";
import"./chunk-6r0bxrh6.js";
import"./chunk-d6500tvx.js";
import"./chunk-jg4bw4hp.js";
import"./chunk-epvbnq43.js";
import"./chunk-tn2sx7j6.js";
import"./chunk-6tzyv21c.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-ch4pgvwq.js";
import"./chunk-99jc4tcw.js";
import"./chunk-fghczfqt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-f86mwfyd.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-nt5dmk8q.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-0gp4q8aq.js";
import"./chunk-hn4w9pkj.js";
import {
  Dialog,
  Newline,
  Pane,
  SearchBox,
  StatusIcon,
  Tab,
  Tabs,
  ThemedBox_default,
  ThemedText,
  init_source,
  init_src,
  require_react,
  source_default,
  useKeybinding,
  useTabHeaderFocus,
  useTabsWidth,
  useTerminalFocus,
  useTerminalSize,
  use_input_default
} from "./chunk-0r6npc3t.js";
import {
  require_jsx_runtime
} from "./chunk-gxyx8b8w.js";
import"./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-t0450ma3.js";
import"./chunk-0cqw3y8h.js";
import"./chunk-k1sw7km0.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-sc9ycxra.js";
import"./chunk-hhta0nge.js";
import"./chunk-8wsj9fff.js";
import"./chunk-m28vg9w4.js";
import"./chunk-f8prtxs3.js";
import"./chunk-41a6f2kv.js";
import"./chunk-c1yc761e.js";
import {
  figures_default,
  init_figures
} from "./chunk-c5g9shkw.js";
import {
  init_slowOperations,
  jsonStringify
} from "./chunk-byd20vdq.js";
import"./chunk-kb3758f7.js";
import {
  getOriginalCwd,
  init_state
} from "./chunk-3j8w0rq8.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import"./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __esm,
  __toESM
} from "./chunk-hhsxm2yr.js";

// src/components/permissions/rules/PermissionRuleDescription.tsx
function PermissionRuleDescription({ ruleValue }) {
  switch (ruleValue.toolName) {
    case BashTool.name: {
      if (ruleValue.ruleContent) {
        if (ruleValue.ruleContent.endsWith(":*")) {
          return /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "Any Bash command starting with ",
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: ruleValue.ruleContent.slice(0, -2)
              })
            ]
          });
        } else {
          return /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
            dimColor: true,
            children: [
              "The Bash command ",
              /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
                bold: true,
                children: ruleValue.ruleContent
              })
            ]
          });
        }
      } else {
        return /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
          dimColor: true,
          children: "Any Bash command"
        });
      }
    }
    default: {
      if (!ruleValue.ruleContent) {
        return /* @__PURE__ */ jsx_runtime.jsxs(ThemedText, {
          dimColor: true,
          children: [
            "Any use of the ",
            /* @__PURE__ */ jsx_runtime.jsx(ThemedText, {
              bold: true,
              children: ruleValue.toolName
            }),
            " tool"
          ]
        });
      } else {
        return null;
      }
    }
  }
}
var jsx_runtime;
var init_PermissionRuleDescription = __esm(() => {
  init_src();
  init_BashTool();
  jsx_runtime = __toESM(require_jsx_runtime(), 1);
});

// src/components/permissions/rules/AddPermissionRules.tsx
function optionForPermissionSaveDestination(saveDestination) {
  switch (saveDestination) {
    case "localSettings":
      return {
        label: "Project settings (local)",
        description: `Saved in ${getRelativeSettingsFilePathForSource("localSettings")}`,
        value: saveDestination
      };
    case "projectSettings":
      return {
        label: "Project settings",
        description: `Checked in at ${getRelativeSettingsFilePathForSource("projectSettings")}`,
        value: saveDestination
      };
    case "userSettings":
      return {
        label: "User settings",
        description: `Saved in at ~/.claude/settings.json`,
        value: saveDestination
      };
  }
}
function AddPermissionRules({
  onAddRules,
  onCancel,
  ruleValues,
  ruleBehavior,
  initialContext,
  setToolPermissionContext
}) {
  const allOptions = SOURCES.map(optionForPermissionSaveDestination);
  const onSelect = import_react.useCallback((selectedValue) => {
    if (selectedValue === "cancel") {
      onCancel();
      return;
    } else if (SOURCES.includes(selectedValue)) {
      const destination = selectedValue;
      const updatedContext = applyPermissionUpdate(initialContext, {
        type: "addRules",
        rules: ruleValues,
        behavior: ruleBehavior,
        destination
      });
      persistPermissionUpdate({
        type: "addRules",
        rules: ruleValues,
        behavior: ruleBehavior,
        destination
      });
      setToolPermissionContext(updatedContext);
      const rules = ruleValues.map((ruleValue) => ({
        ruleValue,
        ruleBehavior,
        source: destination
      }));
      const sandboxAutoAllowEnabled = SandboxManager.isSandboxingEnabled() && SandboxManager.isAutoAllowBashIfSandboxedEnabled();
      const allUnreachable = detectUnreachableRules(updatedContext, {
        sandboxAutoAllowEnabled
      });
      const newUnreachable = allUnreachable.filter((u) => ruleValues.some((rv) => rv.toolName === u.rule.ruleValue.toolName && rv.ruleContent === u.rule.ruleValue.ruleContent));
      onAddRules(rules, newUnreachable.length > 0 ? newUnreachable : undefined);
    }
  }, [onAddRules, onCancel, ruleValues, ruleBehavior, initialContext, setToolPermissionContext]);
  const title = `Add ${ruleBehavior} permission ${plural(ruleValues.length, "rule")}`;
  return /* @__PURE__ */ jsx_runtime2.jsxs(Dialog, {
    title,
    onCancel,
    color: "permission",
    children: [
      /* @__PURE__ */ jsx_runtime2.jsx(ThemedBox_default, {
        flexDirection: "column",
        paddingX: 2,
        children: ruleValues.map((ruleValue) => /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
          flexDirection: "column",
          children: [
            /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
              bold: true,
              children: permissionRuleValueToString(ruleValue)
            }),
            /* @__PURE__ */ jsx_runtime2.jsx(PermissionRuleDescription, {
              ruleValue
            })
          ]
        }, permissionRuleValueToString(ruleValue)))
      }),
      /* @__PURE__ */ jsx_runtime2.jsxs(ThemedBox_default, {
        flexDirection: "column",
        marginY: 1,
        children: [
          /* @__PURE__ */ jsx_runtime2.jsx(ThemedText, {
            children: ruleValues.length === 1 ? "Where should this rule be saved?" : "Where should these rules be saved?"
          }),
          /* @__PURE__ */ jsx_runtime2.jsx(Select, {
            options: allOptions,
            onChange: onSelect
          })
        ]
      })
    ]
  });
}
var import_react, jsx_runtime2;
var init_AddPermissionRules = __esm(() => {
  init_select();
  init_src();
  init_PermissionUpdate();
  init_permissionRuleParser();
  init_shadowedRuleDetection();
  init_sandbox_adapter();
  init_constants();
  init_settings();
  init_stringUtils();
  init_PermissionRuleDescription();
  import_react = __toESM(require_react(), 1);
  jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
});

// src/components/permissions/rules/PermissionRuleInput.tsx
function PermissionRuleInput({ onCancel, onSubmit, ruleBehavior }) {
  const [inputValue, setInputValue] = import_react2.useState("");
  const [cursorOffset, setCursorOffset] = import_react2.useState(0);
  const exitState = useExitOnCtrlCDWithKeybindings();
  useKeybinding("confirm:no", onCancel, { context: "Settings" });
  const { columns } = useTerminalSize();
  const textInputColumns = columns - 6;
  const handleSubmit = (value) => {
    const trimmedValue = value.trim();
    if (trimmedValue.length === 0) {
      return;
    }
    const ruleValue = permissionRuleValueFromString(trimmedValue);
    onSubmit(ruleValue, ruleBehavior);
  };
  return /* @__PURE__ */ jsx_runtime3.jsxs(jsx_runtime3.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime3.jsxs(ThemedBox_default, {
        flexDirection: "column",
        gap: 1,
        borderStyle: "round",
        paddingLeft: 1,
        paddingRight: 1,
        borderColor: "permission",
        children: [
          /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
            bold: true,
            color: "permission",
            children: [
              "Add ",
              ruleBehavior,
              " permission rule"
            ]
          }),
          /* @__PURE__ */ jsx_runtime3.jsxs(ThemedBox_default, {
            flexDirection: "column",
            children: [
              /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
                children: [
                  "Permission rules are a tool name, optionally followed by a specifier in parentheses.",
                  /* @__PURE__ */ jsx_runtime3.jsx(Newline, {}),
                  "e.g., ",
                  /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
                    bold: true,
                    children: permissionRuleValueToString({ toolName: WebFetchTool.name })
                  }),
                  /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
                    bold: false,
                    children: " or "
                  }),
                  /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
                    bold: true,
                    children: permissionRuleValueToString({
                      toolName: BashTool.name,
                      ruleContent: "ls:*"
                    })
                  })
                ]
              }),
              /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
                borderDimColor: true,
                borderStyle: "round",
                marginY: 1,
                paddingLeft: 1,
                children: /* @__PURE__ */ jsx_runtime3.jsx(TextInput, {
                  showCursor: true,
                  value: inputValue,
                  onChange: setInputValue,
                  onSubmit: handleSubmit,
                  placeholder: `Enter permission rule${figures_default.ellipsis}`,
                  columns: textInputColumns,
                  cursorOffset,
                  onChangeCursorOffset: setCursorOffset
                })
              })
            ]
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime3.jsx(ThemedBox_default, {
        marginLeft: 3,
        children: exitState.pending ? /* @__PURE__ */ jsx_runtime3.jsxs(ThemedText, {
          dimColor: true,
          children: [
            "Press ",
            exitState.keyName,
            " again to exit"
          ]
        }) : /* @__PURE__ */ jsx_runtime3.jsx(ThemedText, {
          dimColor: true,
          children: "Enter to submit \xB7 Esc to cancel"
        })
      })
    ]
  });
}
var import_react2, jsx_runtime3;
var init_PermissionRuleInput = __esm(() => {
  init_figures();
  init_TextInput();
  init_useExitOnCtrlCDWithKeybindings();
  init_useTerminalSize();
  init_src();
  init_useKeybinding();
  init_BashTool();
  init_WebFetchTool();
  init_permissionRuleParser();
  import_react2 = __toESM(require_react(), 1);
  jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
});

// src/components/permissions/rules/RecentDenialsTab.tsx
function RecentDenialsTab({ onHeaderFocusChange, onStateChange }) {
  const { headerFocused, focusHeader } = useTabHeaderFocus();
  import_react3.useEffect(() => {
    onHeaderFocusChange?.(headerFocused);
  }, [headerFocused, onHeaderFocusChange]);
  const [denials] = import_react3.useState(() => getAutoModeDenials());
  const [approved, setApproved] = import_react3.useState(() => new Set);
  const [retry, setRetry] = import_react3.useState(() => new Set);
  const [focusedIdx, setFocusedIdx] = import_react3.useState(0);
  import_react3.useEffect(() => {
    onStateChange({ approved, retry, denials });
  }, [approved, retry, denials, onStateChange]);
  const handleSelect = import_react3.useCallback((value) => {
    const idx = Number(value);
    setApproved((prev) => {
      const next = new Set(prev);
      if (next.has(idx))
        next.delete(idx);
      else
        next.add(idx);
      return next;
    });
  }, []);
  const handleFocus = import_react3.useCallback((value) => {
    setFocusedIdx(Number(value));
  }, []);
  use_input_default((input, _key) => {
    if (input === "r") {
      setRetry((prev) => {
        const next = new Set(prev);
        if (next.has(focusedIdx))
          next.delete(focusedIdx);
        else
          next.add(focusedIdx);
        return next;
      });
      setApproved((prev) => {
        if (prev.has(focusedIdx))
          return prev;
        const next = new Set(prev);
        next.add(focusedIdx);
        return next;
      });
    }
  }, { isActive: denials.length > 0 });
  if (denials.length === 0) {
    return /* @__PURE__ */ jsx_runtime4.jsx(ThemedText, {
      dimColor: true,
      children: "No recent denials. Commands denied by the auto mode classifier will appear here."
    });
  }
  const options = denials.map((d, idx) => {
    const isApproved = approved.has(idx);
    const suffix = retry.has(idx) ? " (retry)" : "";
    return {
      label: /* @__PURE__ */ jsx_runtime4.jsxs(ThemedText, {
        children: [
          /* @__PURE__ */ jsx_runtime4.jsx(StatusIcon, {
            status: isApproved ? "success" : "error",
            withSpace: true
          }),
          d.display,
          /* @__PURE__ */ jsx_runtime4.jsx(ThemedText, {
            dimColor: true,
            children: suffix
          })
        ]
      }),
      value: String(idx)
    };
  });
  return /* @__PURE__ */ jsx_runtime4.jsxs(ThemedBox_default, {
    flexDirection: "column",
    children: [
      /* @__PURE__ */ jsx_runtime4.jsx(ThemedText, {
        children: "Commands recently denied by the auto mode classifier."
      }),
      /* @__PURE__ */ jsx_runtime4.jsx(ThemedBox_default, {
        marginTop: 1,
        children: /* @__PURE__ */ jsx_runtime4.jsx(Select, {
          options,
          onChange: handleSelect,
          onFocus: handleFocus,
          visibleOptionCount: Math.min(10, options.length),
          isDisabled: headerFocused,
          onUpFromFirstItem: focusHeader
        })
      })
    ]
  });
}
var import_react3, jsx_runtime4;
var init_RecentDenialsTab = __esm(() => {
  init_src();
  init_autoModeDenials();
  init_select();
  init_src();
  import_react3 = __toESM(require_react(), 1);
  jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
});

// src/components/permissions/rules/RemoveWorkspaceDirectory.tsx
function RemoveWorkspaceDirectory({
  directoryPath,
  onRemove,
  onCancel,
  permissionContext,
  setPermissionContext
}) {
  const handleRemove = import_react4.useCallback(() => {
    const updatedContext = applyPermissionUpdate(permissionContext, {
      type: "removeDirectories",
      directories: [directoryPath],
      destination: "session"
    });
    setPermissionContext(updatedContext);
    onRemove();
  }, [directoryPath, permissionContext, setPermissionContext, onRemove]);
  const handleSelect = import_react4.useCallback((value) => {
    if (value === "yes") {
      handleRemove();
    } else {
      onCancel();
    }
  }, [handleRemove, onCancel]);
  return /* @__PURE__ */ jsx_runtime5.jsxs(Dialog, {
    title: "Remove directory from workspace?",
    onCancel,
    color: "error",
    children: [
      /* @__PURE__ */ jsx_runtime5.jsx(ThemedBox_default, {
        marginX: 2,
        flexDirection: "column",
        children: /* @__PURE__ */ jsx_runtime5.jsx(ThemedText, {
          bold: true,
          children: directoryPath
        })
      }),
      /* @__PURE__ */ jsx_runtime5.jsx(ThemedText, {
        children: "Chris Code will no longer have access to files in this directory."
      }),
      /* @__PURE__ */ jsx_runtime5.jsx(Select, {
        onChange: handleSelect,
        onCancel,
        options: [
          { label: "Yes", value: "yes" },
          { label: "No", value: "no" }
        ]
      })
    ]
  });
}
var import_react4, jsx_runtime5;
var init_RemoveWorkspaceDirectory = __esm(() => {
  init_select();
  init_src();
  init_PermissionUpdate();
  init_src();
  import_react4 = __toESM(require_react(), 1);
  jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
});

// src/components/permissions/rules/WorkspaceTab.tsx
function WorkspaceTab({
  onExit,
  toolPermissionContext,
  onRequestAddDirectory,
  onRequestRemoveDirectory,
  onHeaderFocusChange
}) {
  const { headerFocused, focusHeader } = useTabHeaderFocus();
  import_react5.useEffect(() => {
    onHeaderFocusChange?.(headerFocused);
  }, [headerFocused, onHeaderFocusChange]);
  const additionalDirectories = React.useMemo(() => {
    return Array.from(toolPermissionContext.additionalWorkingDirectories.keys()).map((path) => ({
      path,
      isCurrent: false,
      isDeletable: true
    }));
  }, [toolPermissionContext.additionalWorkingDirectories]);
  const handleDirectorySelect = import_react5.useCallback((selectedValue) => {
    if (selectedValue === "add-directory") {
      onRequestAddDirectory();
      return;
    }
    const directory = additionalDirectories.find((d) => d.path === selectedValue);
    if (directory && directory.isDeletable) {
      onRequestRemoveDirectory(directory.path);
    }
  }, [additionalDirectories, onRequestAddDirectory, onRequestRemoveDirectory]);
  const handleCancel = import_react5.useCallback(() => onExit("Workspace dialog dismissed", { display: "system" }), [onExit]);
  const options = React.useMemo(() => {
    const opts = additionalDirectories.map((dir) => ({
      label: dir.path,
      value: dir.path
    }));
    opts.push({
      label: `Add directory${figures_default.ellipsis}`,
      value: "add-directory"
    });
    return opts;
  }, [additionalDirectories]);
  return /* @__PURE__ */ jsx_runtime6.jsxs(ThemedBox_default, {
    flexDirection: "column",
    marginBottom: 1,
    children: [
      /* @__PURE__ */ jsx_runtime6.jsxs(ThemedBox_default, {
        flexDirection: "row",
        marginTop: 1,
        marginLeft: 2,
        gap: 1,
        children: [
          /* @__PURE__ */ jsx_runtime6.jsx(ThemedText, {
            children: `-  ${getOriginalCwd()}`
          }),
          /* @__PURE__ */ jsx_runtime6.jsx(ThemedText, {
            dimColor: true,
            children: "(Original working directory)"
          })
        ]
      }),
      /* @__PURE__ */ jsx_runtime6.jsx(Select, {
        options,
        onChange: handleDirectorySelect,
        onCancel: handleCancel,
        visibleOptionCount: Math.min(10, options.length),
        onUpFromFirstItem: focusHeader,
        isDisabled: headerFocused
      })
    ]
  });
}
var React, import_react5, jsx_runtime6;
var init_WorkspaceTab = __esm(() => {
  init_figures();
  init_state();
  init_select();
  init_src();
  React = __toESM(require_react(), 1);
  import_react5 = __toESM(require_react(), 1);
  jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
});

// src/components/permissions/rules/PermissionRuleList.tsx
function RuleSourceText({ rule }) {
  return /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
    dimColor: true,
    children: `From ${permissionRuleSourceDisplayString(rule.source)}`
  });
}
function getRuleBehaviorLabel(ruleBehavior) {
  switch (ruleBehavior) {
    case "allow":
      return "allowed";
    case "deny":
      return "denied";
    case "ask":
      return "ask";
  }
}
function RuleDetails({
  rule,
  onDelete,
  onCancel
}) {
  const exitState = useExitOnCtrlCDWithKeybindings();
  useKeybinding("confirm:no", onCancel, { context: "Confirmation" });
  const ruleDescription = /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
    flexDirection: "column",
    marginX: 2,
    children: [
      /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
        bold: true,
        children: permissionRuleValueToString(rule.ruleValue)
      }),
      /* @__PURE__ */ jsx_runtime7.jsx(PermissionRuleDescription, {
        ruleValue: rule.ruleValue
      }),
      /* @__PURE__ */ jsx_runtime7.jsx(RuleSourceText, {
        rule
      })
    ]
  });
  const footer = /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
    marginLeft: 3,
    children: exitState.pending ? /* @__PURE__ */ jsx_runtime7.jsxs(ThemedText, {
      dimColor: true,
      children: [
        "Press ",
        exitState.keyName,
        " again to exit"
      ]
    }) : /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
      dimColor: true,
      children: "Esc to cancel"
    })
  });
  if (rule.source === "policySettings") {
    return /* @__PURE__ */ jsx_runtime7.jsxs(jsx_runtime7.Fragment, {
      children: [
        /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
          flexDirection: "column",
          gap: 1,
          borderStyle: "round",
          paddingLeft: 1,
          paddingRight: 1,
          borderColor: "permission",
          children: [
            /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
              bold: true,
              color: "permission",
              children: "Rule details"
            }),
            ruleDescription,
            /* @__PURE__ */ jsx_runtime7.jsxs(ThemedText, {
              italic: true,
              children: [
                "This rule is configured by managed settings and cannot be modified.",
                `
`,
                "Contact your system administrator for more information."
              ]
            })
          ]
        }),
        footer
      ]
    });
  }
  return /* @__PURE__ */ jsx_runtime7.jsxs(jsx_runtime7.Fragment, {
    children: [
      /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
        flexDirection: "column",
        gap: 1,
        borderStyle: "round",
        paddingLeft: 1,
        paddingRight: 1,
        borderColor: "error",
        children: [
          /* @__PURE__ */ jsx_runtime7.jsxs(ThemedText, {
            bold: true,
            color: "error",
            children: [
              "Delete ",
              getRuleBehaviorLabel(rule.ruleBehavior),
              " tool?"
            ]
          }),
          ruleDescription,
          /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
            children: "Are you sure you want to delete this permission rule?"
          }),
          /* @__PURE__ */ jsx_runtime7.jsx(Select, {
            onChange: (_) => _ === "yes" ? onDelete() : onCancel(),
            onCancel,
            options: [
              { label: "Yes", value: "yes" },
              { label: "No", value: "no" }
            ]
          })
        ]
      }),
      footer
    ]
  });
}
function RulesTabContent(props) {
  const {
    options,
    searchQuery,
    isSearchMode,
    isFocused,
    onSelect,
    onCancel,
    lastFocusedRuleKey,
    cursorOffset,
    onHeaderFocusChange
  } = props;
  const tabWidth = useTabsWidth();
  const { headerFocused, focusHeader, blurHeader } = useTabHeaderFocus();
  import_react6.useEffect(() => {
    if (isSearchMode && headerFocused)
      blurHeader();
  }, [isSearchMode, headerFocused, blurHeader]);
  import_react6.useEffect(() => {
    onHeaderFocusChange?.(headerFocused);
  }, [headerFocused, onHeaderFocusChange]);
  return /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
    flexDirection: "column",
    children: [
      /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
        marginBottom: 1,
        flexDirection: "column",
        children: /* @__PURE__ */ jsx_runtime7.jsx(SearchBox, {
          query: searchQuery,
          isFocused: isSearchMode && !headerFocused,
          isTerminalFocused: isFocused,
          width: tabWidth,
          cursorOffset
        })
      }),
      /* @__PURE__ */ jsx_runtime7.jsx(Select, {
        options,
        onChange: onSelect,
        onCancel,
        visibleOptionCount: Math.min(10, options.length),
        isDisabled: isSearchMode || headerFocused,
        defaultFocusValue: lastFocusedRuleKey,
        onUpFromFirstItem: focusHeader
      })
    ]
  });
}
function PermissionRulesTab({
  tab,
  getRulesOptions,
  handleToolSelect,
  ...rulesProps
}) {
  return /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
    flexDirection: "column",
    flexShrink: tab === "allow" ? 0 : undefined,
    children: [
      /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
        children: {
          allow: "Chris Code won't ask before using allowed tools.",
          ask: "Chris Code will always ask for confirmation before using these tools.",
          deny: "Chris Code will always reject requests to use denied tools."
        }[tab]
      }),
      /* @__PURE__ */ jsx_runtime7.jsx(RulesTabContent, {
        options: getRulesOptions(tab, rulesProps.searchQuery).options,
        onSelect: (v) => handleToolSelect(v, tab),
        ...rulesProps
      })
    ]
  });
}
function PermissionRuleList({ onExit, initialTab, onRetryDenials }) {
  const hasDenials = getAutoModeDenials().length > 0;
  const defaultTab = initialTab ?? (hasDenials ? "recent" : "allow");
  const [changes, setChanges] = import_react6.useState([]);
  const toolPermissionContext = useAppState((s) => s.toolPermissionContext);
  const setAppState = useSetAppState();
  const isTerminalFocused = useTerminalFocus();
  const denialStateRef = import_react6.useRef({ approved: new Set, retry: new Set, denials: [] });
  const handleDenialStateChange = import_react6.useCallback((s) => {
    denialStateRef.current = s;
  }, []);
  const [selectedRule, setSelectedRule] = import_react6.useState();
  const [lastFocusedRuleKey, setLastFocusedRuleKey] = import_react6.useState();
  const [addingRuleToTab, setAddingRuleToTab] = import_react6.useState(null);
  const [validatedRule, setValidatedRule] = import_react6.useState(null);
  const [isAddingWorkspaceDirectory, setIsAddingWorkspaceDirectory] = import_react6.useState(false);
  const [removingDirectory, setRemovingDirectory] = import_react6.useState(null);
  const [isSearchMode, setIsSearchMode] = import_react6.useState(false);
  const [headerFocused, setHeaderFocused] = import_react6.useState(true);
  const handleHeaderFocusChange = import_react6.useCallback((focused) => {
    setHeaderFocused(focused);
  }, []);
  const allowRulesByKey = import_react6.useMemo(() => {
    const map = new Map;
    getAllowRules(toolPermissionContext).forEach((rule) => {
      map.set(jsonStringify(rule), rule);
    });
    return map;
  }, [toolPermissionContext]);
  const denyRulesByKey = import_react6.useMemo(() => {
    const map = new Map;
    getDenyRules(toolPermissionContext).forEach((rule) => {
      map.set(jsonStringify(rule), rule);
    });
    return map;
  }, [toolPermissionContext]);
  const askRulesByKey = import_react6.useMemo(() => {
    const map = new Map;
    getAskRules(toolPermissionContext).forEach((rule) => {
      map.set(jsonStringify(rule), rule);
    });
    return map;
  }, [toolPermissionContext]);
  const getRulesOptions = import_react6.useCallback((tab, query = "") => {
    const rulesByKey = (() => {
      switch (tab) {
        case "allow":
          return allowRulesByKey;
        case "deny":
          return denyRulesByKey;
        case "ask":
          return askRulesByKey;
        case "workspace":
        case "recent":
          return new Map;
      }
    })();
    const options = [];
    if (tab !== "workspace" && tab !== "recent" && !query) {
      options.push({
        label: `Add a new rule${figures_default.ellipsis}`,
        value: "add-new-rule"
      });
    }
    const sortedRuleKeys = Array.from(rulesByKey.keys()).sort((a, b) => {
      const ruleA = rulesByKey.get(a);
      const ruleB = rulesByKey.get(b);
      if (ruleA && ruleB) {
        const ruleAString = permissionRuleValueToString(ruleA.ruleValue).toLowerCase();
        const ruleBString = permissionRuleValueToString(ruleB.ruleValue).toLowerCase();
        return ruleAString.localeCompare(ruleBString);
      }
      return 0;
    });
    const lowerQuery = query.toLowerCase();
    for (const ruleKey of sortedRuleKeys) {
      const rule = rulesByKey.get(ruleKey);
      if (rule) {
        const ruleString = permissionRuleValueToString(rule.ruleValue);
        if (query && !ruleString.toLowerCase().includes(lowerQuery)) {
          continue;
        }
        options.push({
          label: ruleString,
          value: ruleKey
        });
      }
    }
    return { options, rulesByKey };
  }, [allowRulesByKey, denyRulesByKey, askRulesByKey]);
  const exitState = useExitOnCtrlCDWithKeybindings();
  const isSearchModeActive = !selectedRule && !addingRuleToTab && !validatedRule && !isAddingWorkspaceDirectory && !removingDirectory;
  const {
    query: searchQuery,
    setQuery: setSearchQuery,
    cursorOffset: searchCursorOffset
  } = useSearchInput({
    isActive: isSearchModeActive && isSearchMode,
    onExit: () => {
      setIsSearchMode(false);
    }
  });
  const handleKeyDown = import_react6.useCallback((e) => {
    if (!isSearchModeActive)
      return;
    if (isSearchMode)
      return;
    if (e.ctrl || e.meta)
      return;
    if (e.key === "/") {
      e.preventDefault();
      setIsSearchMode(true);
      setSearchQuery("");
    } else if (e.key.length === 1 && e.key !== "j" && e.key !== "k" && e.key !== "m" && e.key !== "i" && e.key !== "r" && e.key !== " ") {
      e.preventDefault();
      setIsSearchMode(true);
      setSearchQuery(e.key);
    }
  }, [isSearchModeActive, isSearchMode, setSearchQuery]);
  const handleToolSelect = import_react6.useCallback((selectedValue, tab) => {
    const { rulesByKey } = getRulesOptions(tab);
    if (selectedValue === "add-new-rule") {
      setAddingRuleToTab(tab);
      return;
    } else {
      setSelectedRule(rulesByKey.get(selectedValue));
      return;
    }
  }, [getRulesOptions]);
  const handleRuleInputCancel = import_react6.useCallback(() => {
    setAddingRuleToTab(null);
  }, []);
  const handleRuleInputSubmit = import_react6.useCallback((ruleValue, ruleBehavior) => {
    setValidatedRule({ ruleValue, ruleBehavior });
    setAddingRuleToTab(null);
  }, []);
  const handleAddRulesSuccess = import_react6.useCallback((rules, unreachable) => {
    setValidatedRule(null);
    for (const rule of rules) {
      setChanges((prev) => [
        ...prev,
        `Added ${rule.ruleBehavior} rule ${source_default.bold(permissionRuleValueToString(rule.ruleValue))}`
      ]);
    }
    if (unreachable && unreachable.length > 0) {
      for (const u of unreachable) {
        const severity = u.shadowType === "deny" ? "blocked" : "shadowed";
        setChanges((prev) => [
          ...prev,
          source_default.yellow(`${figures_default.warning} Warning: ${permissionRuleValueToString(u.rule.ruleValue)} is ${severity}`),
          source_default.dim(`  ${u.reason}`),
          source_default.dim(`  Fix: ${u.fix}`)
        ]);
      }
    }
  }, []);
  const handleAddRuleCancel = import_react6.useCallback(() => {
    setValidatedRule(null);
  }, []);
  const handleRequestAddDirectory = import_react6.useCallback(() => setIsAddingWorkspaceDirectory(true), []);
  const handleRequestRemoveDirectory = import_react6.useCallback((path) => setRemovingDirectory(path), []);
  const handleRulesCancel = import_react6.useCallback(() => {
    const s = denialStateRef.current;
    const denialsFor = (set) => Array.from(set).map((idx) => s.denials[idx]).filter((d) => d !== undefined);
    const retryDenials = denialsFor(s.retry);
    if (retryDenials.length > 0) {
      const commands = retryDenials.map((d) => d.display);
      onRetryDenials?.(commands);
      onExit(undefined, {
        shouldQuery: true,
        metaMessages: [
          `Permission granted for: ${commands.join(", ")}. You may now retry ${commands.length === 1 ? "this command" : "these commands"} if you would like.`
        ]
      });
      return;
    }
    const approvedDenials = denialsFor(s.approved);
    if (approvedDenials.length > 0 || changes.length > 0) {
      const approvedMsg = approvedDenials.length > 0 ? [`Approved ${approvedDenials.map((d) => source_default.bold(d.display)).join(", ")}`] : [];
      onExit([...approvedMsg, ...changes].join(`
`));
    } else {
      onExit("Permissions dialog dismissed", {
        display: "system"
      });
    }
  }, [changes, onExit, onRetryDenials]);
  useKeybinding("confirm:no", handleRulesCancel, {
    context: "Settings",
    isActive: isSearchModeActive && !isSearchMode
  });
  const handleDeleteRule = () => {
    if (!selectedRule)
      return;
    const { options } = getRulesOptions(selectedRule.ruleBehavior);
    const selectedKey = jsonStringify(selectedRule);
    const ruleKeys = options.filter((opt) => opt.value !== "add-new-rule").map((opt) => opt.value);
    const currentIndex = ruleKeys.indexOf(selectedKey);
    let nextFocusKey;
    if (currentIndex !== -1) {
      if (currentIndex < ruleKeys.length - 1) {
        nextFocusKey = ruleKeys[currentIndex + 1];
      } else if (currentIndex > 0) {
        nextFocusKey = ruleKeys[currentIndex - 1];
      }
    }
    setLastFocusedRuleKey(nextFocusKey);
    deletePermissionRule({
      rule: selectedRule,
      initialContext: toolPermissionContext,
      setToolPermissionContext(toolPermissionContext2) {
        setAppState((prev) => ({
          ...prev,
          toolPermissionContext: toolPermissionContext2
        }));
      }
    });
    setChanges((prev) => [
      ...prev,
      `Deleted ${selectedRule.ruleBehavior} rule ${source_default.bold(permissionRuleValueToString(selectedRule.ruleValue))}`
    ]);
    setSelectedRule(undefined);
  };
  if (selectedRule) {
    return /* @__PURE__ */ jsx_runtime7.jsx(RuleDetails, {
      rule: selectedRule,
      onDelete: handleDeleteRule,
      onCancel: () => setSelectedRule(undefined)
    });
  }
  if (addingRuleToTab && addingRuleToTab !== "workspace" && addingRuleToTab !== "recent") {
    return /* @__PURE__ */ jsx_runtime7.jsx(PermissionRuleInput, {
      onCancel: handleRuleInputCancel,
      onSubmit: handleRuleInputSubmit,
      ruleBehavior: addingRuleToTab
    });
  }
  if (validatedRule) {
    return /* @__PURE__ */ jsx_runtime7.jsx(AddPermissionRules, {
      onAddRules: handleAddRulesSuccess,
      onCancel: handleAddRuleCancel,
      ruleValues: [validatedRule.ruleValue],
      ruleBehavior: validatedRule.ruleBehavior,
      initialContext: toolPermissionContext,
      setToolPermissionContext: (toolPermissionContext2) => {
        setAppState((prev) => ({
          ...prev,
          toolPermissionContext: toolPermissionContext2
        }));
      }
    });
  }
  if (isAddingWorkspaceDirectory) {
    return /* @__PURE__ */ jsx_runtime7.jsx(AddWorkspaceDirectory, {
      onAddDirectory: (path, remember) => {
        const destination = remember ? "localSettings" : "session";
        const permissionUpdate = {
          type: "addDirectories",
          directories: [path],
          destination
        };
        const updatedContext = applyPermissionUpdate(toolPermissionContext, permissionUpdate);
        setAppState((prev) => ({
          ...prev,
          toolPermissionContext: updatedContext
        }));
        if (remember) {
          persistPermissionUpdate(permissionUpdate);
        }
        setChanges((prev) => [
          ...prev,
          `Added directory ${source_default.bold(path)} to workspace${remember ? " and saved to local settings" : " for this session"}`
        ]);
        setIsAddingWorkspaceDirectory(false);
      },
      onCancel: () => setIsAddingWorkspaceDirectory(false),
      permissionContext: toolPermissionContext
    });
  }
  if (removingDirectory) {
    return /* @__PURE__ */ jsx_runtime7.jsx(RemoveWorkspaceDirectory, {
      directoryPath: removingDirectory,
      onRemove: () => {
        setChanges((prev) => [...prev, `Removed directory ${source_default.bold(removingDirectory)} from workspace`]);
        setRemovingDirectory(null);
      },
      onCancel: () => setRemovingDirectory(null),
      permissionContext: toolPermissionContext,
      setPermissionContext: (toolPermissionContext2) => {
        setAppState((prev) => ({
          ...prev,
          toolPermissionContext: toolPermissionContext2
        }));
      }
    });
  }
  const sharedRulesProps = {
    searchQuery,
    isSearchMode,
    isFocused: isTerminalFocused,
    onCancel: handleRulesCancel,
    lastFocusedRuleKey,
    cursorOffset: searchCursorOffset,
    getRulesOptions,
    handleToolSelect,
    onHeaderFocusChange: handleHeaderFocusChange
  };
  const isHidden = !!selectedRule || !!addingRuleToTab || !!validatedRule || isAddingWorkspaceDirectory || !!removingDirectory;
  return /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
    flexDirection: "column",
    onKeyDown: handleKeyDown,
    children: /* @__PURE__ */ jsx_runtime7.jsxs(Pane, {
      color: "permission",
      children: [
        /* @__PURE__ */ jsx_runtime7.jsxs(Tabs, {
          title: "Permissions:",
          color: "permission",
          defaultTab,
          hidden: isHidden,
          initialHeaderFocused: !hasDenials,
          navFromContent: !isSearchMode,
          children: [
            /* @__PURE__ */ jsx_runtime7.jsx(Tab, {
              id: "recent",
              title: "Recently denied",
              children: /* @__PURE__ */ jsx_runtime7.jsx(RecentDenialsTab, {
                onHeaderFocusChange: handleHeaderFocusChange,
                onStateChange: handleDenialStateChange
              })
            }),
            /* @__PURE__ */ jsx_runtime7.jsx(Tab, {
              id: "allow",
              title: "Allow",
              children: /* @__PURE__ */ jsx_runtime7.jsx(PermissionRulesTab, {
                tab: "allow",
                ...sharedRulesProps
              })
            }),
            /* @__PURE__ */ jsx_runtime7.jsx(Tab, {
              id: "ask",
              title: "Ask",
              children: /* @__PURE__ */ jsx_runtime7.jsx(PermissionRulesTab, {
                tab: "ask",
                ...sharedRulesProps
              })
            }),
            /* @__PURE__ */ jsx_runtime7.jsx(Tab, {
              id: "deny",
              title: "Deny",
              children: /* @__PURE__ */ jsx_runtime7.jsx(PermissionRulesTab, {
                tab: "deny",
                ...sharedRulesProps
              })
            }),
            /* @__PURE__ */ jsx_runtime7.jsx(Tab, {
              id: "workspace",
              title: "Workspace",
              children: /* @__PURE__ */ jsx_runtime7.jsxs(ThemedBox_default, {
                flexDirection: "column",
                children: [
                  /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
                    children: "Chris Code can read files in the workspace, and make edits when auto-accept edits is on."
                  }),
                  /* @__PURE__ */ jsx_runtime7.jsx(WorkspaceTab, {
                    onExit,
                    toolPermissionContext,
                    onRequestAddDirectory: handleRequestAddDirectory,
                    onRequestRemoveDirectory: handleRequestRemoveDirectory,
                    onHeaderFocusChange: handleHeaderFocusChange
                  })
                ]
              })
            })
          ]
        }),
        /* @__PURE__ */ jsx_runtime7.jsx(ThemedBox_default, {
          marginTop: 1,
          paddingLeft: 1,
          children: /* @__PURE__ */ jsx_runtime7.jsx(ThemedText, {
            dimColor: true,
            children: exitState.pending ? /* @__PURE__ */ jsx_runtime7.jsxs(jsx_runtime7.Fragment, {
              children: [
                "Press ",
                exitState.keyName,
                " again to exit"
              ]
            }) : headerFocused ? /* @__PURE__ */ jsx_runtime7.jsx(jsx_runtime7.Fragment, {
              children: "\u2190/\u2192 tab switch \xB7 \u2193 return \xB7 Esc cancel"
            }) : isSearchMode ? /* @__PURE__ */ jsx_runtime7.jsx(jsx_runtime7.Fragment, {
              children: "Type to filter \xB7 Enter/\u2193 select \xB7 \u2191 tabs \xB7 Esc clear"
            }) : hasDenials && defaultTab === "recent" ? /* @__PURE__ */ jsx_runtime7.jsx(jsx_runtime7.Fragment, {
              children: "Enter approve \xB7 r retry \xB7 \u2191\u2193 navigate \xB7 \u2190/\u2192 switch \xB7 Esc cancel"
            }) : /* @__PURE__ */ jsx_runtime7.jsx(jsx_runtime7.Fragment, {
              children: "\u2191\u2193 navigate \xB7 Enter select \xB7 Type to search \xB7 \u2190/\u2192 switch \xB7 Esc cancel"
            })
          })
        })
      ]
    })
  });
}
var import_react6, jsx_runtime7;
var init_PermissionRuleList = __esm(() => {
  init_source();
  init_figures();
  init_AppState();
  init_PermissionUpdate();
  init_select();
  init_useExitOnCtrlCDWithKeybindings();
  init_useSearchInput();
  init_src();
  init_useKeybinding();
  init_autoModeDenials();
  init_permissionRuleParser();
  init_permissions();
  init_slowOperations();
  init_src();
  init_SearchBox();
  init_AddPermissionRules();
  init_AddWorkspaceDirectory();
  init_PermissionRuleDescription();
  init_PermissionRuleInput();
  init_RecentDenialsTab();
  init_RemoveWorkspaceDirectory();
  init_WorkspaceTab();
  import_react6 = __toESM(require_react(), 1);
  jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
});

// src/commands/permissions/permissions.tsx
var jsx_runtime8, call = async (onDone, context) => {
  return /* @__PURE__ */ jsx_runtime8.jsx(PermissionRuleList, {
    onExit: onDone,
    onRetryDenials: (commands) => {
      context.setMessages((prev) => [...prev, createPermissionRetryMessage(commands)]);
    }
  });
};
var init_permissions2 = __esm(() => {
  init_PermissionRuleList();
  init_messages();
  jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
});
init_permissions2();

export {
  call
};

//# debugId=93D4DCAB5802EB1064756E2164756E21
//# sourceMappingURL=chunk-dx6cx3jz.js.map
