base/permission.rs
1//! 权限模式与权限规则。一次调用的判定结果是
2//! `interface::permission::PermissionOutcome`。
3
4use crate::interface::config_source::Tier;
5use serde::{Deserialize, Serialize};
6
7/// Permission mode for tool execution.
8#[derive(
9 Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default, schemars::JsonSchema,
10)]
11#[serde(rename_all = "camelCase")]
12pub enum PermissionMode {
13 /// Prompt user for each tool call that isn't explicitly allowed.
14 #[default]
15 Default,
16 /// Allow file writes inside the project (the working directory and
17 /// `files.extra_dirs`) and read-only calls without asking;
18 /// ask about the rest, as `default` does. Writes into the project's
19 /// `.git`, its project directory (`.agix` unless renamed; then `.agix`
20 /// too), `.claude` and `.agents/skills` still ask.
21 AcceptEdits,
22 /// Ask nothing and skip the rules of the user's tiers. Credentials
23 /// (`.ssh`, `.aws`, `.gnupg`, the state directory's settings and tokens)
24 /// are still refused, the deployment's managed `deny` / `ask` rules still
25 /// apply, input that is not valid is still refused, and `Bash` still runs
26 /// in the OS sandbox.
27 BypassPermissions,
28 /// Plan mode — only allow read-only tools.
29 Plan,
30 /// Don't ask — deny any tool not explicitly allowed (no prompt).
31 DontAsk,
32 /// Bubble mode — forward permission requests up to a parent agent.
33 /// **Program-only**: set by team/coordinator runtime; cannot be set by user.
34 #[schemars(skip)]
35 Bubble,
36}
37
38impl PermissionMode {
39 /// Whether the user can set this mode via settings.json / CLI.
40 /// `Bubble` is program-only — set by the team coordinator runtime and
41 /// rejected from user config.
42 pub fn is_user_settable(self) -> bool {
43 !matches!(self, Self::Bubble)
44 }
45
46 /// How permissive this mode is, on a total order — higher grants more
47 /// without asking.
48 ///
49 /// Exists so a host can *clamp* a mode it did not choose: the daemon's
50 /// `session.create` RPC accepts `options.settings.permissions.mode`, and
51 /// without an ordering there was no way to express "a client may tighten
52 /// this, but may not loosen it past what `settings.json` configured".
53 /// Anyone who could reach the socket could simply ask for
54 /// `bypassPermissions` and get it, whatever the daemon was configured
55 /// with — see `assembly::session_pool::effective_permission_mode`.
56 ///
57 /// The ranking:
58 /// - `DontAsk` refuses anything not explicitly allowed — nothing is more
59 /// restrictive.
60 /// - `Plan` refuses every non-read-only tool.
61 /// - `Default` asks about anything not explicitly allowed.
62 /// - `Bubble` is `Default` with the question routed to a parent agent
63 /// rather than a human; the same set of calls still needs approval.
64 /// - `AcceptEdits` additionally waves through `Write`/`Edit`.
65 /// - `BypassPermissions` asks nothing at all.
66 pub fn permissiveness(self) -> u8 {
67 match self {
68 Self::DontAsk => 0,
69 Self::Plan => 1,
70 Self::Default => 2,
71 Self::Bubble => 3,
72 Self::AcceptEdits => 4,
73 Self::BypassPermissions => 5,
74 }
75 }
76
77 /// The stricter (less permissive) of two modes. Ties keep `self`.
78 pub fn min_permissive(self, other: Self) -> Self {
79 if other.permissiveness() < self.permissiveness() {
80 other
81 } else {
82 self
83 }
84 }
85
86 /// The mode a delegate (sub-agent, team member) runs in when the session
87 /// that spawned it is in `self`: its own, wider or narrower — except that a
88 /// planning parent holds it to plan, a parent that asks nobody holds it to
89 /// `dontAsk`, and a parent that bypasses takes it along, unless it may only
90 /// tighten (`Delegate::mode_under`).
91 pub fn for_delegate(self, delegate: Self) -> Self {
92 match self {
93 Self::Plan | Self::DontAsk => delegate.min_permissive(self),
94 Self::BypassPermissions => self,
95 _ => delegate,
96 }
97 }
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
101pub struct PermissionRule {
102 pub source: RuleSource,
103 pub behavior: RuleBehavior,
104 pub tool_name: String,
105 /// 例:Bash 用 "git push:*";Read 用 "/etc/**"
106 #[serde(skip_serializing_if = "Option::is_none", default)]
107 pub rule_content: Option<String>,
108}
109
110#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, schemars::JsonSchema)]
111#[serde(rename_all = "camelCase")]
112pub enum RuleSource {
113 /// `~/.agix/scenes/<scope>/settings.json`
114 UserSettings,
115 /// `settings.json` in the project directory (`.agix` by default)
116 ProjectSettings,
117 /// `settings.local.json` in the project directory
118 LocalSettings,
119 /// 设置的 `cli` 层:`agixd --set permissions.allow=…` 或 `EmbedConfig::settings`
120 CliArg,
121 /// 这个会话自己的:建会话时 `options.settings` 里的规则串,与会话里答应的「本会话都允许」
122 Session,
123 /// 部署方的 managed settings(`settings::managed`)
124 PolicySettings,
125 /// 由命令展开时临时注入
126 Command,
127 /// 由已安装插件贡献。卸载插件时用 `Policy::remove_rules_by_source`
128 /// 整批撤销。
129 Plugin,
130 /// 宿主自带的 `PermissionPolicy`:它的回答作为一层规则参与裁决。
131 Host,
132}
133
134impl RuleSource {
135 /// 同一行为有多条规则命中时,用它挑出报告哪一条:数值越大越先选中。
136 /// 不参与 allow / ask / deny 之间的裁决——那只看行为,deny 永远优先。
137 pub fn priority(self) -> u8 {
138 match self {
139 Self::PolicySettings => 70,
140 Self::Host => 65,
141 Self::CliArg => 60,
142 Self::Session => 50,
143 Self::Command => 45,
144 Self::LocalSettings => 40,
145 Self::ProjectSettings => 30,
146 Self::UserSettings => 20,
147 Self::Plugin => 5,
148 }
149 }
150}
151
152#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, schemars::JsonSchema)]
153#[serde(rename_all = "camelCase")]
154pub enum RuleBehavior {
155 Allow,
156 Deny,
157 Ask,
158}
159
160/// One rule string of a settings file's `permissions` block, with the list it
161/// was written in: `allow`, `ask` and `deny` give the action, `allow_exact`
162/// an allow whose content matches only the same text.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct PermissionRuleEntry {
165 /// As written: `Bash`, `Bash(git push:*)`, `mcp__srv__tool`.
166 pub tool: String,
167 pub action: RuleBehavior,
168 pub matching: crate::interface::permission::GrantMatch,
169}
170
171/// A permission rule as loaded: the rule, the tier whose file it came from,
172/// and whether that file was the tier's `settings.local.json`.
173#[derive(Debug, Clone)]
174#[non_exhaustive]
175pub struct LoadedRule {
176 pub rule: PermissionRuleEntry,
177 pub tier: Tier,
178 pub machine_local: bool,
179}
180
181impl LoadedRule {
182 pub fn new(rule: PermissionRuleEntry, tier: Tier, machine_local: bool) -> Self {
183 Self {
184 rule,
185 tier,
186 machine_local,
187 }
188 }
189}
190
191#[derive(Debug, Clone, Default, PartialEq)]
192pub struct ManagedSettings {
193 /// The file (or other source) the layer came from.
194 pub origin: String,
195 /// Why the layer cannot be honoured. While set, every tool call is refused.
196 pub error: Option<String>,
197 pub rules: Vec<PermissionRuleEntry>,
198 pub disable_bypass: bool,
199 /// Every other setting the layer sets, shaped as a settings file holds
200 /// it: put over every other layer.
201 pub values: serde_json::Map<String, serde_json::Value>,
202}
203
204impl ManagedSettings {
205 /// Whether a `bypassPermissions` session under this layer can still be
206 /// asked about a call: the layer takes bypass away, or holds an `ask` or
207 /// `deny` rule. A `deny` counts because a command it cannot read through
208 /// (`$CMD x`) is asked about rather than refused.
209 pub fn asks_under_bypass(&self) -> bool {
210 self.error.is_none()
211 && (self.disable_bypass || self.rules.iter().any(|r| r.action != RuleBehavior::Allow))
212 }
213}
214
215/// What the permission engine reads of the loaded settings: every tier's
216/// rules, the managed layer, and where a project-scoped grant is written. The
217/// sandbox it reads off the call's `ToolContext::config`.
218#[derive(Debug, Clone, Default)]
219pub struct PermissionSettings {
220 pub rules: Vec<LoadedRule>,
221 pub managed: Option<ManagedSettings>,
222 /// `None` for a session with no project: a grant lasts the session only.
223 pub project_rules: Option<std::sync::Arc<dyn crate::interface::permission::RuleFile>>,
224 /// Whose worktrees a path rule also matches in, as the main checkout
225 /// holds them ([`crate::paths::Layout::main_checkout_copies`]).
226 pub layout: crate::paths::Layout,
227}
228
229/// Whether the project tier of a `LoadedSettings` is in effect as written.
230#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
231pub enum ProjectTrust {
232 /// No project tier of its own: no project at all, or one whose `.agix`
233 /// is the global or scene directory.
234 #[default]
235 NoProject,
236 Trusted,
237 Untrusted,
238}
239
240impl ProjectTrust {
241 pub fn as_str(self) -> &'static str {
242 match self {
243 Self::NoProject => "none",
244 Self::Trusted => "trusted",
245 Self::Untrusted => "untrusted",
246 }
247 }
248
249 pub fn is_untrusted(self) -> bool {
250 self == Self::Untrusted
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
259 fn rule_priority_ordering() {
260 assert!(RuleSource::CliArg.priority() > RuleSource::LocalSettings.priority());
261 assert!(RuleSource::LocalSettings.priority() > RuleSource::ProjectSettings.priority());
262 assert!(RuleSource::ProjectSettings.priority() > RuleSource::UserSettings.priority());
263 assert!(RuleSource::PolicySettings.priority() > RuleSource::CliArg.priority());
264 }
265
266 #[test]
267 fn permission_mode_serializes_camelcase() {
268 let s = serde_json::to_value(PermissionMode::BypassPermissions).unwrap();
269 assert_eq!(s, serde_json::Value::String("bypassPermissions".into()));
270 let back: PermissionMode = serde_json::from_value(s).unwrap();
271 assert_eq!(back, PermissionMode::BypassPermissions);
272 }
273
274 #[test]
275 fn only_the_claude_code_spellings_are_modes() {
276 for spelling in ["auto", "yolo", "bypass_permissions"] {
277 assert!(serde_json::from_value::<PermissionMode>(spelling.into()).is_err());
278 }
279 }
280
281 #[test]
282 fn rule_roundtrip() {
283 let r = PermissionRule {
284 source: RuleSource::ProjectSettings,
285 behavior: RuleBehavior::Deny,
286 tool_name: "Bash".into(),
287 rule_content: Some("rm -rf *".into()),
288 };
289 let s = serde_json::to_string(&r).unwrap();
290 let back: PermissionRule = serde_json::from_str(&s).unwrap();
291 assert_eq!(r, back);
292 }
293}