aither-agent 0.28.0

AI agent framework with planning, memory, and tool execution for aither
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
//! Command hooks driven by a real hook script that runs `ast-grep`, through
//! a real terminal tool.

use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use aither_core::llm::{Tool, ToolContext, ToolResult};
use aither_sandbox::permission::{PermissionError, PermissionHandler, TerminalMode};
use aither_sandbox::{
    DynTerminalTool, DynToolHandler, ScriptLanguage, SubagentGrant, TerminalTool,
    ToolRegistryBuilder,
};
use executor_core::tokio::TokioGlobal;

use super::tests::{logged, script};
use super::*;

/// Longest any wait in these tests lasts.
const BOUND: Duration = Duration::from_secs(60);

/// Reads the command from the hook input, logs the input to the file named
/// by the first argument, and asks `ast-grep` whether the command contains
/// `rm -rf`, wherever the shell syntax nests it: a match blocks, a clean
/// run allows, and any other exit status makes the hook itself fail.
const AST_GREP_HOOK: &str = r#"#!/bin/sh
input=$(cat)
printf '%s\n' "$input" >> "$1"
command=$(printf '%s' "$input" | jq -r .command)
printf '%s' "$command" | ast-grep run --lang bash --pattern 'rm -rf $$$ARGS' --stdin >/dev/null
case $? in
  0) printf '{"decision":"block","reason":"rm -rf is not allowed here"}' ;;
  1) printf '{"decision":"allow"}' ;;
  *) exit 3 ;;
esac
"#;

/// A permission handler that grants the sandbox and nothing beyond it, and
/// records every request it is asked.
#[derive(Clone, Default)]
struct SandboxOnly {
    asked: Arc<Mutex<Vec<(TerminalMode, String)>>>,
}

impl PermissionHandler for SandboxOnly {
    fn check(
        &self,
        mode: TerminalMode,
        script: &str,
        _language: ScriptLanguage,
    ) -> impl Future<Output = Result<bool, PermissionError>> + Send {
        self.asked.lock().unwrap().push((mode, script.to_string()));
        std::future::ready(Ok(mode == TerminalMode::Sandboxed))
    }
}

fn config(name: &str, program: &[&str], deadline_ms: u64) -> CommandHookConfig {
    CommandHookConfig {
        name: name.into(),
        command: HookCommand {
            command: program.iter().map(ToString::to_string).collect(),
            deadline_ms,
        },
    }
}

/// The ast-grep hook, logging its inputs to `log`.
fn ast_grep_hook(dir: &Path, log: &Path) -> CommandHookConfig {
    let hook = script(dir, "ast-grep-hook.sh", AST_GREP_HOOK);
    config(
        "ast-grep",
        &["sh", &hook.to_string_lossy(), &log.to_string_lossy()],
        20_000,
    )
}

/// The managed tools every terminal here is prepared with.
struct Tools {
    distribution: aither_sandbox::ToolDistribution,
    cache: crate::test_support::ToolCache,
    _source: tempfile::TempDir,
}

impl Tools {
    /// The baseline fixture the crate's other terminal tests use, which only
    /// makes sandboxed execution available.
    async fn stub() -> Self {
        let source = tempfile::tempdir().unwrap();
        let binary = crate::test_support::compile_baseline_fixture(source.path()).await;
        Self {
            distribution: crate::test_support::fixture_distribution(&binary, "1.0.0").await,
            cache: crate::test_support::ToolCache::temporary(),
            _source: source,
        }
    }

    /// The real `ripgrep`, `ast-grep` and `jq` of the repository's pinned
    /// distribution, downloaded and verified into the cache.
    async fn real() -> Self {
        let source = tempfile::tempdir().unwrap();
        let binary = crate::test_support::compile_baseline_fixture(source.path()).await;
        Self {
            distribution: crate::test_support::real_distribution(&binary).await,
            cache: crate::test_support::ToolCache::shared(),
            _source: source,
        }
    }
}

/// The terminal of the main agent, gated by command hooks that run with the
/// terminal's own prepared tools on their `PATH`, and those hooks.
async fn terminal(
    tools: &Tools,
    dir: &Path,
    permission: SandboxOnly,
    command_hooks: Vec<CommandHookConfig>,
) -> (
    TerminalTool<SandboxOnly, TokioGlobal, aither_sandbox::Configured>,
    ExternalHooks,
) {
    let terminal = TerminalTool::new_exact(dir, permission, TokioGlobal)
        .await
        .expect("the terminal initializes")
        .initialize_tools(&tools.distribution, tools.cache.path())
        .await
        .expect("the managed tools are prepared");
    let host_tools = terminal
        .shell_sessions()
        .host_tools(&tools.distribution, tools.cache.path())
        .await
        .expect("the host tools are prepared");
    let hooks = ExternalHooks::new(
        &LiveHooks::start(
            HooksConfig {
                command: command_hooks,
                ..HooksConfig::default()
            },
            &host_tools,
            executor_core::AnyExecutor::new(TokioGlobal),
        )
        .await
        .expect("the hooks start"),
    );
    let mut builder = ToolRegistryBuilder::new();
    builder.gate_commands(hooks.command_gate());
    let registry = Arc::new(builder.build(terminal.output_store().clone()));
    (terminal.with_registry(registry), hooks)
}

fn args(script: &str, mode: &str) -> serde_json::Value {
    serde_json::json!({
        "description": "run a test command",
        "script": script,
        "mode": mode,
        "raw": true,
        "timeout": 60,
    })
}

/// What the model reads for a foreground `terminal` call, or the refusal
/// that replaced it.
async fn run<P>(
    terminal: &TerminalTool<P, TokioGlobal, aither_sandbox::Configured>,
    script: &str,
    mode: &str,
) -> Result<String, String>
where
    P: PermissionHandler + 'static,
{
    let arguments = serde_json::from_value(args(script, mode)).unwrap();
    tokio::time::timeout(BOUND, terminal.call(arguments, ToolContext::new()))
        .await
        .expect("the call finishes within its bound")
        .map(|result| result.render_for_model())
        .map_err(|error| error.to_string())
}

/// The `terminal` handler of a subagent's terminal.
fn terminal_handler(terminal: DynTerminalTool) -> DynToolHandler {
    terminal
        .into_entries()
        .into_iter()
        .find(|entry| entry.definition.name() == "terminal")
        .expect("the subagent has a terminal")
        .handler
}

/// Calls a subagent's `terminal` handler.
async fn run_dyn(handler: &DynToolHandler, script: &str) -> String {
    let result: ToolResult = tokio::time::timeout(
        BOUND,
        handler(&args(script, "default").to_string(), ToolContext::new()),
    )
    .await
    .expect("the call finishes within its bound");
    result.render_for_model()
}

#[tokio::test(flavor = "multi_thread")]
async fn an_ast_grep_hook_blocks_nested_matches_and_allows_a_non_match() {
    let dir = tempfile::tempdir().unwrap();
    let log = dir.path().join("log");
    let work = tempfile::tempdir().unwrap();
    let tools = Tools::real().await;
    let (terminal, _) = terminal(
        &tools,
        work.path(),
        SandboxOnly::default(),
        vec![ast_grep_hook(dir.path(), &log)],
    )
    .await;

    for nested in [
        "echo go | rm -rf /nowhere/pipeline",
        "(cd /nowhere && rm -rf subshell)",
        "echo $(rm -rf /nowhere/substitution)",
        "rm -rf /nowhere/plain",
    ] {
        let refusal = run(&terminal, nested, "default")
            .await
            .expect_err(&format!("`{nested}` is blocked"));
        assert!(
            refusal.contains("ast-grep") && refusal.contains("rm -rf is not allowed here"),
            "{refusal}"
        );
    }

    let output = run(
        &terminal,
        "echo rm -rf is only text; echo ran-ok",
        "default",
    )
    .await
    .expect("a non-match runs");
    assert!(output.contains("ran-ok"), "{output}");

    // The hook saw each full command, once, as the main agent.
    let inputs = logged(&log);
    assert_eq!(inputs.len(), 5);
    assert_eq!(
        inputs[0],
        serde_json::json!({
            "event": "before_command", "role": "main",
            "command": "echo go | rm -rf /nowhere/pipeline"
        })
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_background_command_is_gated_too() {
    let dir = tempfile::tempdir().unwrap();
    let log = dir.path().join("log");
    let work = tempfile::tempdir().unwrap();
    let tools = Tools::real().await;
    let (terminal, _) = terminal(
        &tools,
        work.path(),
        SandboxOnly::default(),
        vec![ast_grep_hook(dir.path(), &log)],
    )
    .await;

    let mut background = args("echo $(rm -rf /nowhere)", "default");
    background["timeout"] = 30.into();
    let arguments = serde_json::from_value(background).unwrap();
    let refusal = tokio::time::timeout(BOUND, terminal.run_background(arguments))
        .await
        .expect("the call finishes within its bound")
        .expect_err("the background command is blocked");
    assert!(
        refusal.to_string().contains("rm -rf is not allowed here"),
        "{refusal}"
    );
    assert_eq!(logged(&log).len(), 1);
}

#[tokio::test(flavor = "multi_thread")]
async fn allowing_a_command_grants_no_permission_beyond_the_sandbox() {
    let dir = tempfile::tempdir().unwrap();
    let log = dir.path().join("log");
    let work = tempfile::tempdir().unwrap();
    let tools = Tools::real().await;
    let permission = SandboxOnly::default();
    let (terminal, _) = terminal(
        &tools,
        work.path(),
        permission.clone(),
        vec![ast_grep_hook(dir.path(), &log)],
    )
    .await;

    // The hook allows this command, yet it still needs the permission an
    // unsandboxed command needs, which is refused.
    let refusal = run(&terminal, "echo escape-attempt", "unsafe")
        .await
        .expect_err("the hook's allow does not stand in for permission");
    assert!(!refusal.contains("ast-grep"), "{refusal}");
    assert_eq!(logged(&log).len(), 1, "the hook allowed it");
    assert_eq!(
        *permission.asked.lock().unwrap(),
        [(TerminalMode::Unsafe, "echo escape-attempt".to_string())],
        "the permission path still decided"
    );

    // An answer that tries to carry a grant is not an answer at all.
    let grant = script(
        dir.path(),
        "grant.sh",
        "#!/bin/sh\ncat >/dev/null\nprintf '{\"decision\":\"allow\",\"grant\":\"unsafe\"}'\n",
    );
    let permission = SandboxOnly::default();
    let (terminal, _) = self::terminal(
        &tools,
        work.path(),
        permission.clone(),
        vec![config(
            "granting",
            &["sh", &grant.to_string_lossy()],
            20_000,
        )],
    )
    .await;
    let refusal = run(&terminal, "echo escape-attempt", "unsafe")
        .await
        .expect_err("a grant is refused");
    assert!(refusal.contains("did not answer"), "{refusal}");
    assert!(permission.asked.lock().unwrap().is_empty());
}

#[tokio::test(flavor = "multi_thread")]
async fn a_command_hook_that_fails_blocks_the_command_naming_the_failure() {
    let dir = tempfile::tempdir().unwrap();
    let work = tempfile::tempdir().unwrap();
    let tools = Tools::stub().await;
    let silent = script(dir.path(), "silent.sh", "#!/bin/sh\ncat >/dev/null\n");
    let nonsense = script(
        dir.path(),
        "nonsense.sh",
        "#!/bin/sh\ncat >/dev/null\nprintf 'allow'\n",
    );
    let crash = script(
        dir.path(),
        "crash.sh",
        "#!/bin/sh\ncat >/dev/null\necho broken >&2\nexit 7\n",
    );
    let slow = script(
        dir.path(),
        "slow.sh",
        "#!/bin/sh\ncat >/dev/null\nsleep 30\n",
    );
    let cases = [
        (
            config("missing", &["/nonexistent/hook"], 20_000),
            "cannot be started",
        ),
        (
            config("silent", &["sh", &silent.to_string_lossy()], 20_000),
            "printed no answer",
        ),
        (
            config("nonsense", &["sh", &nonsense.to_string_lossy()], 20_000),
            "not a valid answer",
        ),
        (
            config("crash", &["sh", &crash.to_string_lossy()], 20_000),
            "broken",
        ),
        (
            config("slow", &["sh", &slow.to_string_lossy()], 300),
            "deadline",
        ),
    ];
    for (hook, failure) in cases {
        let name = hook.name.clone();
        let (terminal, _) = terminal(&tools, work.path(), SandboxOnly::default(), vec![hook]).await;
        let refusal = run(&terminal, "echo should-not-run", "default")
            .await
            .expect_err(&format!("the failing hook `{name}` blocks"));
        assert!(
            refusal.contains(&name)
                && refusal.contains("did not answer")
                && refusal.contains(failure),
            "{name}: {refusal}"
        );
        assert!(!refusal.contains("should-not-run\n"), "{refusal}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_subagent_terminal_is_gated_and_its_hooks_see_the_subagent_role() {
    let dir = tempfile::tempdir().unwrap();
    let log = dir.path().join("log");
    let work = tempfile::tempdir().unwrap();
    let tools = Tools::real().await;
    let (terminal, hooks) = terminal(
        &tools,
        work.path(),
        SandboxOnly::default(),
        vec![ast_grep_hook(dir.path(), &log)],
    )
    .await;

    let child_hooks = hooks.for_subagent();
    let subagent = terminal
        .binding()
        .launcher()
        .create(
            SubagentGrant::new(),
            Some(child_hooks.command_observer()),
            Some(child_hooks.command_gate()),
            None,
        )
        .await
        .expect("the subagent terminal launches");
    let subagent = terminal_handler(subagent);

    let refusal = run_dyn(&subagent, "(rm -rf /nowhere)").await;
    assert!(refusal.contains("rm -rf is not allowed here"), "{refusal}");
    let ran = run_dyn(&subagent, "echo child-ok").await;
    assert!(ran.contains("child-ok"), "{ran}");

    let roles: Vec<_> = logged(&log)
        .iter()
        .map(|input| input["role"].as_str().unwrap().to_string())
        .collect();
    assert_eq!(roles, ["subagent", "subagent"]);
}

#[tokio::test(flavor = "multi_thread")]
async fn a_hook_finds_the_terminals_prepared_tools_ahead_of_the_host_path() {
    let dir = tempfile::tempdir().unwrap();
    let work = tempfile::tempdir().unwrap();
    let tools = Tools::stub().await;
    let which = script(
        dir.path(),
        "which.sh",
        r#"#!/bin/sh
cat >/dev/null
for tool in apply_patch rg ast-grep jq; do
  printf '%s=%s\n' "$tool" "$(command -v "$tool")"
done > "$1"
printf '{"decision":"allow"}'
"#,
    );
    let found = dir.path().join("found");
    let (terminal, _) = terminal(
        &tools,
        work.path(),
        SandboxOnly::default(),
        vec![config(
            "which",
            &["sh", &which.to_string_lossy(), &found.to_string_lossy()],
            20_000,
        )],
    )
    .await;
    let prepared = terminal.shell_sessions().local_tools().unwrap().bin_dir();

    run(&terminal, "echo ok", "default")
        .await
        .expect("the hook allows");

    let found = std::fs::read_to_string(&found).unwrap();
    for tool in ["apply_patch", "rg", "ast-grep", "jq"] {
        let expected = format!("{tool}={}", prepared.join(tool).display());
        assert!(found.lines().any(|line| line == expected), "{found}");
    }
}