agent-air-runtime 0.7.0

Core runtime for agent-air - LLM orchestration, tools, and permissions (no TUI dependencies)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
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
//! Grant structure combining target and permission level.
//!
//! A Grant is the fundamental unit of the permission system, representing
//! the tuple `(Target, Level)` - what resource is being accessed and how.

use super::{GrantTarget, PermissionLevel};
use serde::{Deserialize, Serialize};
use std::time::Instant;

/// A permission grant combining a target and permission level.
///
/// Grants are the core building blocks of the permission system. Each grant
/// specifies:
/// - What can be accessed (the target)
/// - What level of access is permitted (the level)
/// - When the grant expires (optional)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grant {
    /// What this grant applies to (path, domain, or command).
    pub target: GrantTarget,
    /// The permission level granted.
    pub level: PermissionLevel,
    /// Optional expiration time. If `None`, grant lasts for the session.
    #[serde(skip)]
    pub expires: Option<Instant>,
}

impl Grant {
    /// Creates a new grant with the given target and level.
    ///
    /// The grant has no expiration (session-scoped).
    pub fn new(target: GrantTarget, level: PermissionLevel) -> Self {
        Self {
            target,
            level,
            expires: None,
        }
    }

    /// Creates a new grant with an expiration time.
    pub fn with_expiration(target: GrantTarget, level: PermissionLevel, expires: Instant) -> Self {
        Self {
            target,
            level,
            expires: Some(expires),
        }
    }

    /// Creates a read grant for a path.
    pub fn read_path(path: impl Into<std::path::PathBuf>, recursive: bool) -> Self {
        Self::new(GrantTarget::path(path, recursive), PermissionLevel::Read)
    }

    /// Creates a write grant for a path.
    pub fn write_path(path: impl Into<std::path::PathBuf>, recursive: bool) -> Self {
        Self::new(GrantTarget::path(path, recursive), PermissionLevel::Write)
    }

    /// Creates an execute grant for a path.
    pub fn execute_path(path: impl Into<std::path::PathBuf>, recursive: bool) -> Self {
        Self::new(GrantTarget::path(path, recursive), PermissionLevel::Execute)
    }

    /// Creates an admin grant for a path.
    pub fn admin_path(path: impl Into<std::path::PathBuf>, recursive: bool) -> Self {
        Self::new(GrantTarget::path(path, recursive), PermissionLevel::Admin)
    }

    /// Creates a grant for a network domain.
    pub fn domain(pattern: impl Into<String>, level: PermissionLevel) -> Self {
        Self::new(GrantTarget::domain(pattern), level)
    }

    /// Creates a grant for a shell command pattern.
    pub fn command(pattern: impl Into<String>, level: PermissionLevel) -> Self {
        Self::new(GrantTarget::command(pattern), level)
    }

    /// Creates a grant for a tool invocation.
    pub fn tool(tool_name: impl Into<String>, level: PermissionLevel) -> Self {
        Self::new(GrantTarget::tool(tool_name), level)
    }

    /// Checks if this grant satisfies a permission request.
    ///
    /// A grant satisfies a request if:
    /// 1. The grant's target covers the request's target
    /// 2. The grant's level satisfies the request's required level
    /// 3. The grant has not expired
    ///
    /// # Arguments
    /// * `request` - The permission request to check against
    ///
    /// # Returns
    /// `true` if this grant satisfies the request
    pub fn satisfies(&self, request: &PermissionRequest) -> bool {
        // Check expiration
        if let Some(expires) = self.expires
            && Instant::now() >= expires
        {
            return false;
        }

        // Check target coverage
        if !self.target.covers(&request.target) {
            return false;
        }

        // Check level hierarchy
        self.level.satisfies(request.required_level)
    }

    /// Checks if this grant has expired.
    pub fn is_expired(&self) -> bool {
        self.expires.is_some_and(|e| Instant::now() >= e)
    }

    /// Returns a display-friendly description of this grant.
    pub fn description(&self) -> String {
        format!("[{}] {}", self.level, self.target)
    }
}

impl std::fmt::Display for Grant {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description())
    }
}

/// A request for permission to perform an operation.
///
/// Permission requests are generated by tools when they need access to
/// resources. The request specifies:
/// - What target is being accessed
/// - What level of access is needed
/// - A human-readable description of the operation
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PermissionRequest {
    /// Unique identifier for this request.
    pub id: String,
    /// The target being accessed.
    pub target: GrantTarget,
    /// The required permission level.
    pub required_level: PermissionLevel,
    /// Human-readable description of the operation.
    pub description: String,
    /// Optional reason explaining why this access is needed.
    pub reason: Option<String>,
    /// The tool that generated this request.
    pub tool_name: Option<String>,
}

impl PermissionRequest {
    /// Creates a new permission request.
    pub fn new(
        id: impl Into<String>,
        target: GrantTarget,
        required_level: PermissionLevel,
        description: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            target,
            required_level,
            description: description.into(),
            reason: None,
            tool_name: None,
        }
    }

    /// Sets the reason for this request.
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Sets the tool name for this request.
    pub fn with_tool(mut self, tool_name: impl Into<String>) -> Self {
        self.tool_name = Some(tool_name.into());
        self
    }

    /// Creates a file read request.
    pub fn file_read(id: impl Into<String>, path: impl Into<std::path::PathBuf>) -> Self {
        let path = path.into();
        let description = format!("Read file: {}", path.display());
        Self::new(
            id,
            GrantTarget::path(path, false),
            PermissionLevel::Read,
            description,
        )
    }

    /// Creates a file write request.
    pub fn file_write(id: impl Into<String>, path: impl Into<std::path::PathBuf>) -> Self {
        let path = path.into();
        let description = format!("Write file: {}", path.display());
        Self::new(
            id,
            GrantTarget::path(path, false),
            PermissionLevel::Write,
            description,
        )
    }

    /// Creates a directory read request.
    pub fn directory_read(
        id: impl Into<String>,
        path: impl Into<std::path::PathBuf>,
        recursive: bool,
    ) -> Self {
        let path = path.into();
        let description = if recursive {
            format!("Read directory (recursive): {}", path.display())
        } else {
            format!("Read directory: {}", path.display())
        };
        Self::new(
            id,
            GrantTarget::path(path, recursive),
            PermissionLevel::Read,
            description,
        )
    }

    /// Creates a command execution request.
    pub fn command_execute(id: impl Into<String>, command: impl Into<String>) -> Self {
        let command = command.into();
        let description = format!("Execute command: {}", command);
        Self::new(
            id,
            GrantTarget::command(command),
            PermissionLevel::Execute,
            description,
        )
    }

    /// Creates a tool invocation request.
    pub fn tool_use(
        id: impl Into<String>,
        tool_name: impl Into<String>,
        level: PermissionLevel,
    ) -> Self {
        let tool_name = tool_name.into();
        let description = format!("Use tool: {}", tool_name);
        Self::new(id, GrantTarget::tool(&tool_name), level, description).with_tool(tool_name)
    }

    /// Creates a network request.
    pub fn network_access(
        id: impl Into<String>,
        domain: impl Into<String>,
        level: PermissionLevel,
    ) -> Self {
        let domain = domain.into();
        let description = format!("Access domain: {}", domain);
        Self::new(id, GrantTarget::domain(domain), level, description)
    }
}

impl std::fmt::Display for PermissionRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] {}", self.required_level, self.description)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod grant_tests {
        use super::*;

        #[test]
        fn test_grant_satisfies_same_level() {
            let grant = Grant::read_path("/project/src", true);
            let request = PermissionRequest::file_read("1", "/project/src/main.rs");
            assert!(grant.satisfies(&request));
        }

        #[test]
        fn test_grant_satisfies_higher_level() {
            let grant = Grant::write_path("/project/src", true);
            let request = PermissionRequest::file_read("1", "/project/src/main.rs");
            assert!(grant.satisfies(&request));
        }

        #[test]
        fn test_grant_fails_lower_level() {
            let grant = Grant::read_path("/project/src", true);
            let request = PermissionRequest::file_write("1", "/project/src/main.rs");
            assert!(!grant.satisfies(&request));
        }

        #[test]
        fn test_grant_fails_wrong_path() {
            let grant = Grant::write_path("/project/src", true);
            let request = PermissionRequest::file_write("1", "/other/file.rs");
            assert!(!grant.satisfies(&request));
        }

        #[test]
        fn test_grant_fails_non_recursive() {
            let grant = Grant::read_path("/project/src", false);
            let request = PermissionRequest::file_read("1", "/project/src/utils/mod.rs");
            assert!(!grant.satisfies(&request));
        }

        #[test]
        fn test_admin_grant_satisfies_all_levels() {
            let grant = Grant::admin_path("/project", true);

            let read_request = PermissionRequest::file_read("1", "/project/src/main.rs");
            let write_request = PermissionRequest::file_write("2", "/project/src/main.rs");

            assert!(grant.satisfies(&read_request));
            assert!(grant.satisfies(&write_request));
        }

        #[test]
        fn test_domain_grant() {
            let grant = Grant::domain("*.github.com", PermissionLevel::Read);
            let request =
                PermissionRequest::network_access("1", "api.github.com", PermissionLevel::Read);
            assert!(grant.satisfies(&request));
        }

        #[test]
        fn test_command_grant() {
            let grant = Grant::command("git *", PermissionLevel::Execute);
            let request = PermissionRequest::command_execute("1", "git status");
            assert!(grant.satisfies(&request));
        }

        #[test]
        fn test_tool_grant() {
            let grant = Grant::tool("switch_aws_account", PermissionLevel::Execute);
            let request =
                PermissionRequest::tool_use("1", "switch_aws_account", PermissionLevel::Execute);
            assert!(grant.satisfies(&request));
        }

        #[test]
        fn test_tool_grant_different_tool_fails() {
            let grant = Grant::tool("switch_aws_account", PermissionLevel::Execute);
            let request =
                PermissionRequest::tool_use("1", "delete_resource", PermissionLevel::Execute);
            assert!(!grant.satisfies(&request));
        }

        #[test]
        fn test_expired_grant() {
            use std::time::Duration;
            let expired = Instant::now() - Duration::from_secs(1);
            let grant = Grant::with_expiration(
                GrantTarget::path("/project", true),
                PermissionLevel::Read,
                expired,
            );

            let request = PermissionRequest::file_read("1", "/project/file.rs");
            assert!(!grant.satisfies(&request));
        }

        #[test]
        fn test_grant_description() {
            let grant = Grant::write_path("/project/src", true);
            let desc = grant.description();
            assert!(desc.contains("Write"));
            assert!(desc.contains("/project/src"));
        }
    }

    mod request_tests {
        use super::*;

        #[test]
        fn test_file_read_request() {
            let request = PermissionRequest::file_read("test-id", "/path/to/file.rs");
            assert_eq!(request.id, "test-id");
            assert_eq!(request.required_level, PermissionLevel::Read);
            assert!(request.description.contains("Read file"));
        }

        #[test]
        fn test_file_write_request() {
            let request = PermissionRequest::file_write("test-id", "/path/to/file.rs");
            assert_eq!(request.required_level, PermissionLevel::Write);
            assert!(request.description.contains("Write file"));
        }

        #[test]
        fn test_request_with_reason() {
            let request = PermissionRequest::file_read("1", "/file.rs")
                .with_reason("Need to analyze the code");
            assert_eq!(request.reason, Some("Need to analyze the code".to_string()));
        }

        #[test]
        fn test_request_with_tool() {
            let request = PermissionRequest::file_read("1", "/file.rs").with_tool("read_file");
            assert_eq!(request.tool_name, Some("read_file".to_string()));
        }

        #[test]
        fn test_tool_use_request() {
            let request = PermissionRequest::tool_use(
                "test-id",
                "switch_aws_account",
                PermissionLevel::Execute,
            );
            assert_eq!(request.id, "test-id");
            assert_eq!(request.required_level, PermissionLevel::Execute);
            assert!(request.description.contains("Use tool"));
            assert!(request.description.contains("switch_aws_account"));
            assert_eq!(request.tool_name, Some("switch_aws_account".to_string()));
        }
    }

    mod serialization_tests {
        use super::*;

        #[test]
        fn test_grant_serialization() {
            let grant = Grant::write_path("/project/src", true);
            let json = serde_json::to_string(&grant).unwrap();

            let deserialized: Grant = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized.target, grant.target);
            assert_eq!(deserialized.level, grant.level);
        }

        #[test]
        fn test_request_serialization() {
            let request =
                PermissionRequest::file_read("test-id", "/path/to/file.rs").with_reason("testing");
            let json = serde_json::to_string(&request).unwrap();

            let deserialized: PermissionRequest = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized.id, request.id);
            assert_eq!(deserialized.reason, request.reason);
        }
    }
}