horus 0.6.9

A small, modular Rust framework for building coding agents
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Sandboxed execution and its approval boundary.

use std::collections::BTreeSet;
use std::sync::Arc;

use serde::Deserialize;
use serde::Serialize;

use crate::BoxFuture;
use crate::Error;
use crate::Result;
use crate::backend::model::ToolCall;
use crate::middleware::manifest::MiddlewareManifest;
use crate::middleware::manifest::MiddlewareSettingChoice;
use crate::middleware::manifest::MiddlewareSettingChoices;
use crate::middleware::manifest::MiddlewareSettingManifest;
use crate::protocol::EventMsg;
use crate::protocol::FrontendBlock;
use crate::protocol::FrontendContribution;
use crate::protocol::FrontendEvent;
use crate::protocol::ReviewDecision;

mod approval;
mod background;
pub mod local;
mod process_group;

pub(crate) const MAX_FILE_BYTES: usize = 1024 * 1024;
const MAX_BINARY_FILE_BYTES: usize = 25 * 1024 * 1024;

mod text {
    include!(concat!(
        env!("OUT_DIR"),
        "/src_backend_sandbox_sandbox_text.rs"
    ));
}

const APPROVAL_POLICIES: &[MiddlewareSettingChoice] = &[
    MiddlewareSettingChoice {
        value: "ask",
        label: text::APPROVAL_POLICY_ASK_LABEL,
        description: text::APPROVAL_POLICY_ASK_DESCRIPTION,
    },
    MiddlewareSettingChoice {
        value: "allow",
        label: text::APPROVAL_POLICY_ALLOW_LABEL,
        description: text::APPROVAL_POLICY_ALLOW_DESCRIPTION,
    },
    MiddlewareSettingChoice {
        value: "allow_network",
        label: text::APPROVAL_POLICY_ALLOW_NETWORK_LABEL,
        description: text::APPROVAL_POLICY_ALLOW_NETWORK_DESCRIPTION,
    },
    MiddlewareSettingChoice {
        value: "auto_approve",
        label: text::APPROVAL_POLICY_AUTO_APPROVE_LABEL,
        description: text::APPROVAL_POLICY_AUTO_APPROVE_DESCRIPTION,
    },
];
const REVIEWER_STRICTNESS: &[MiddlewareSettingChoice] = &[
    MiddlewareSettingChoice {
        value: "relaxed",
        label: text::REVIEWER_STRICTNESS_RELAXED_LABEL,
        description: text::REVIEWER_STRICTNESS_RELAXED_DESCRIPTION,
    },
    MiddlewareSettingChoice {
        value: "standard",
        label: text::REVIEWER_STRICTNESS_STANDARD_LABEL,
        description: text::REVIEWER_STRICTNESS_STANDARD_DESCRIPTION,
    },
    MiddlewareSettingChoice {
        value: "strict",
        label: text::REVIEWER_STRICTNESS_STRICT_LABEL,
        description: text::REVIEWER_STRICTNESS_STRICT_DESCRIPTION,
    },
];
const SETTINGS: &[MiddlewareSettingManifest] = &[
    MiddlewareSettingManifest::Select {
        id: "approval_policy",
        label: text::SETTING_APPROVAL_POLICY_LABEL,
        description: text::SETTING_APPROVAL_POLICY_DESCRIPTION,
        choices: MiddlewareSettingChoices::Static(APPROVAL_POLICIES),
        unset_label: None,
        default: Some(text::DEFAULTS_APPROVAL_POLICY),
        max_bytes: 32,
    },
    MiddlewareSettingManifest::Select {
        id: "reviewer_model_route",
        label: text::SETTING_REVIEWER_MODEL_ROUTE_LABEL,
        description: text::SETTING_REVIEWER_MODEL_ROUTE_DESCRIPTION,
        choices: MiddlewareSettingChoices::ModelRoutes,
        unset_label: Some(text::SETTING_REVIEWER_MODEL_ROUTE_UNSET_LABEL),
        default: None,
        max_bytes: 4 * 1024,
    },
    MiddlewareSettingManifest::Select {
        id: "reviewer_strictness",
        label: text::SETTING_REVIEWER_STRICTNESS_LABEL,
        description: text::SETTING_REVIEWER_STRICTNESS_DESCRIPTION,
        choices: MiddlewareSettingChoices::Static(REVIEWER_STRICTNESS),
        unset_label: None,
        default: Some(text::DEFAULTS_REVIEWER_STRICTNESS),
        max_bytes: 16,
    },
];

/// Configuration and presentation metadata for sandbox approval policy.
pub const MANIFEST: MiddlewareManifest = MiddlewareManifest {
    id: "sandbox",
    label: text::MANIFEST_LABEL,
    description: text::MANIFEST_DESCRIPTION,
    required: true,
    default_enabled: true,
    settings: SETTINGS,
};

pub use approval::ApprovalPolicy;
pub use approval::ApprovalReviewerConfig;
pub use approval::ApprovalStrictness;
#[cfg(target_os = "macos")]
#[doc(hidden)]
pub use process_group::MACOS_COMMAND_WRAPPER;
#[doc(hidden)]
pub use process_group::ProcessGroupGuard;

use approval::Approval;
pub(crate) use background::BackgroundCommandPoll;
#[cfg(test)]
pub(crate) use background::BackgroundCommandStatus;
use background::BackgroundCommands;

/// Deny-by-default macOS Seatbelt prelude shared by first-party sandbox backends.
///
/// Backends must append their own filesystem allow rules before using it.
#[cfg(target_os = "macos")]
#[doc(hidden)]
pub const MACOS_SEATBELT_BASE_POLICY: &str = include_str!("seatbelt_base_policy.sbpl");

/// Whether a sandbox backend permits network access for one command.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetworkAccess {
    #[default]
    Denied,
    Allowed,
}

/// Bounded output from a sandboxed command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandOutput {
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
}

/// One byte stream emitted by a sandboxed command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandStream {
    Stdout,
    Stderr,
}

/// Whether command execution has a foreground deadline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandMode {
    Foreground,
    Background,
}

/// Optional observer for bounded command output consumers.
#[derive(Clone, Default)]
pub struct CommandOutputSink {
    callback: Option<Arc<CommandOutputCallback>>,
}

type CommandOutputCallback = dyn Fn(CommandStream, &[u8]) + Send + Sync;

impl CommandOutputSink {
    pub(crate) fn new(callback: impl Fn(CommandStream, &[u8]) + Send + Sync + 'static) -> Self {
        Self {
            callback: Some(Arc::new(callback)),
        }
    }

    /// Publishes one output chunk while the backend continues draining the stream.
    pub fn write(&self, stream: CommandStream, bytes: &[u8]) {
        if let Some(callback) = &self.callback {
            callback(stream, bytes);
        }
    }
}

/// Implements one sandbox execution environment.
pub trait SandboxBackend: Send + Sync {
    /// Reads a UTF-8 file.
    fn read<'a>(&'a self, path: &'a str) -> BoxFuture<'a, Result<String>>;

    /// Reads one binary file through a single bounded open handle.
    fn read_bytes<'a>(&'a self, path: &'a str, max_bytes: usize) -> BoxFuture<'a, Result<Vec<u8>>>;

    /// Writes a UTF-8 file.
    fn write<'a>(&'a self, path: &'a str, content: &'a str) -> BoxFuture<'a, Result<()>>;

    /// Runs a shell command and forwards drained output under the requested isolation.
    fn execute<'a>(
        &'a self,
        command: &'a str,
        network_access: NetworkAccess,
        mode: CommandMode,
        output: CommandOutputSink,
    ) -> BoxFuture<'a, Result<CommandOutput>>;
}

/// Approval-owning boundary around one execution backend.
pub struct Sandbox {
    backend: Arc<dyn SandboxBackend>,
    approval: Approval,
    background: BackgroundCommands,
}

impl Sandbox {
    /// Creates a sandbox with its initial approval policy.
    #[must_use]
    pub fn new(backend: Arc<dyn SandboxBackend>, policy: ApprovalPolicy) -> Self {
        Self {
            backend,
            approval: Approval::new(policy),
            background: BackgroundCommands::default(),
        }
    }

    /// Configures the isolated model reviewer used by automatic approval.
    #[must_use]
    pub fn approval_reviewer(mut self, reviewer: ApprovalReviewerConfig) -> Self {
        self.approval = self.approval.with_reviewer(reviewer);
        self
    }

    /// Reads a UTF-8 file.
    pub fn read<'a>(&'a self, path: &'a str) -> BoxFuture<'a, Result<String>> {
        self.backend.read(path)
    }

    /// Reads one bounded binary file.
    pub fn read_bytes<'a>(
        &'a self,
        path: &'a str,
        max_bytes: usize,
    ) -> BoxFuture<'a, Result<Vec<u8>>> {
        if max_bytes == 0 || max_bytes > MAX_BINARY_FILE_BYTES {
            return Box::pin(async {
                Err(Error::Sandbox(format!(
                    "binary file read size must be 1–{MAX_BINARY_FILE_BYTES} bytes"
                )))
            });
        }
        self.backend.read_bytes(path, max_bytes)
    }

    /// Writes a UTF-8 file when this call has mutation authority.
    pub fn write<'a>(
        &'a self,
        path: &'a str,
        content: &'a str,
        permissions: &'a ToolPermissions,
    ) -> BoxFuture<'a, Result<()>> {
        if !permissions.mutation {
            return Box::pin(async {
                Err(Error::Sandbox(
                    "tool call is not authorized to mutate the workspace".into(),
                ))
            });
        }
        if content.len() > MAX_FILE_BYTES {
            return Box::pin(async { Err(Error::Sandbox("file exceeds write limit".into())) });
        }
        self.backend.write(path, content)
    }

    /// Runs a command when this call has mutation authority.
    pub fn execute<'a>(
        &'a self,
        command: &'a str,
        permissions: &'a ToolPermissions,
    ) -> BoxFuture<'a, Result<CommandOutput>> {
        if !permissions.mutation {
            return Box::pin(async {
                Err(Error::Sandbox(
                    "tool call is not authorized to execute commands".into(),
                ))
            });
        }
        self.backend.execute(
            command,
            permissions.network_access,
            CommandMode::Foreground,
            CommandOutputSink::default(),
        )
    }

    pub(crate) fn start_background(
        &self,
        command: String,
        permissions: &ToolPermissions,
    ) -> Result<String> {
        if !permissions.mutation {
            return Err(Error::Sandbox(
                "tool call is not authorized to execute commands".into(),
            ));
        }
        self.background.start(
            &permissions.session_id,
            Arc::clone(&self.backend),
            command,
            permissions.network_access,
        )
    }

    pub(crate) async fn poll_background(
        &self,
        id: &str,
        permissions: &ToolPermissions,
    ) -> Result<BackgroundCommandPoll> {
        self.background.poll(&permissions.session_id, id).await
    }

    pub(crate) async fn stop_background(
        &self,
        id: &str,
        permissions: &ToolPermissions,
    ) -> Result<BackgroundCommandPoll> {
        self.background.stop(&permissions.session_id, id).await
    }

    pub(crate) fn frontend(&self) -> FrontendContribution {
        self.approval.frontend()
    }

    pub(crate) fn render(&self, event: &EventMsg) -> Option<FrontendBlock> {
        self.approval.render(event)
    }

    pub(crate) fn initialize(&self, session_id: &str) -> Result<Vec<FrontendEvent>> {
        self.approval.initialize(session_id)
    }

    pub(crate) fn authorize(
        &self,
        session_id: &str,
        calls: &[ToolCall],
        mutation_call_ids: &[String],
    ) -> Result<SandboxAuthorization> {
        self.approval
            .authorize(session_id, calls, mutation_call_ids)
    }

    pub(crate) fn resolve_approval(
        &self,
        session_id: &str,
        calls: &[ToolCall],
        approval_call_ids: &[String],
        decision: &ReviewDecision,
        permissions: SandboxPermissions,
    ) -> Result<SandboxPermissions> {
        self.approval
            .resolve(session_id, calls, approval_call_ids, decision, permissions)
    }

    pub(crate) async fn shutdown(&self, session_id: &str) -> Result<()> {
        let approval = self.approval.shutdown(session_id);
        let background = self.background.shutdown(session_id).await;
        approval.and(background)
    }
}

/// Batch authority issued by the sandbox approval policy.
#[derive(Debug)]
pub(crate) struct SandboxPermissions {
    session_id: String,
    network_access: NetworkAccess,
    mutation_call_ids: BTreeSet<String>,
}

impl SandboxPermissions {
    fn new(
        session_id: impl Into<String>,
        network_access: NetworkAccess,
        mutation_call_ids: impl IntoIterator<Item = String>,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            network_access,
            mutation_call_ids: mutation_call_ids.into_iter().collect(),
        }
    }

    pub(crate) fn restore(
        session_id: impl Into<String>,
        network_access: NetworkAccess,
        mutation_call_ids: impl IntoIterator<Item = String>,
    ) -> Self {
        Self::new(session_id, network_access, mutation_call_ids)
    }

    pub(crate) fn network_access(&self) -> NetworkAccess {
        self.network_access
    }

    pub(crate) fn mutation_call_ids(&self) -> Vec<String> {
        self.mutation_call_ids.iter().cloned().collect()
    }

    pub(crate) fn for_call(&self, call_id: &str) -> ToolPermissions {
        ToolPermissions {
            session_id: self.session_id.clone(),
            network_access: self.network_access,
            mutation: self.mutation_call_ids.contains(call_id),
        }
    }

    fn allow_mutations(&mut self, call_ids: impl IntoIterator<Item = String>) {
        self.mutation_call_ids.extend(call_ids);
    }
}

/// Opaque authority attached to exactly one tool call.
pub struct ToolPermissions {
    session_id: String,
    network_access: NetworkAccess,
    mutation: bool,
}

impl ToolPermissions {
    pub(crate) fn allows_mutation(&self) -> bool {
        self.mutation
    }
}

pub(crate) enum SandboxAuthorization {
    Execute(SandboxPermissions),
    Review(SandboxReview),
    Approval {
        request: SandboxApprovalRequest,
        permissions: SandboxPermissions,
    },
}

pub(crate) struct SandboxReview {
    pub(crate) request: SandboxApprovalRequest,
    pub(crate) reviewer: ApprovalReviewerConfig,
    pub(crate) permissions: SandboxPermissions,
}

pub(crate) struct SandboxApprovalRequest {
    pub(crate) id: String,
    pub(crate) reason: String,
    pub(crate) call_ids: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::sandbox::local::LocalSandbox;

    #[tokio::test]
    async fn mutation_fails_closed_without_per_call_authority() {
        let workspace = tempfile::tempdir().expect("workspace");
        let sandbox = Sandbox::new(
            Arc::new(LocalSandbox::new(workspace.path()).expect("backend")),
            ApprovalPolicy::Ask,
        );
        let permissions = SandboxPermissions::new("session", NetworkAccess::Allowed, Vec::new());

        assert!(
            sandbox
                .write("blocked.txt", "blocked", &permissions.for_call("call"))
                .await
                .is_err()
        );
        assert!(!workspace.path().join("blocked.txt").exists());
    }
}