mentra 0.28.0

An agent runtime for tool-using LLM applications
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use std::{
    fs,
    path::{Path, PathBuf},
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use async_trait::async_trait;
use serde_json::json;

use crate::{
    AgentConfig, BuiltinProvider, ContentBlock, FileToolProfile, Message, RuntimePolicy,
    runtime::{
        Runtime, RuntimeError, SessionOptions, SessionResumeOptions, VolatileRuntimeStore,
        control::{
            BeforeDecision, ExecutionHookParticipant, HookDecision, PreExecutionContext,
            PreExecutionHook,
        },
    },
    session::{Session, SessionEvent, TaskLifecycleStatus},
};

use super::support::{
    ScriptedProvider, StaticTool, model_info, shell_pwd_command, text_stream, tool_use_stream,
};

struct TestDirectory(PathBuf);

impl TestDirectory {
    fn new(label: &str) -> Self {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time after Unix epoch")
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "mentra-session-policy-{label}-{}-{unique}",
            std::process::id()
        ));
        fs::create_dir_all(&path).expect("create test directory");
        Self(path)
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for TestDirectory {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

fn result_for(history: &[Message], call_id: &str) -> (String, bool) {
    history
        .iter()
        .flat_map(|message| message.content.iter())
        .find_map(|block| match block {
            ContentBlock::ToolResult {
                tool_use_id,
                content,
                is_error,
            } if tool_use_id == call_id => Some((content.to_display_string(), *is_error)),
            _ => None,
        })
        .unwrap_or_else(|| panic!("missing tool result for {call_id}"))
}

fn workspace_config(path: &Path) -> AgentConfig {
    AgentConfig {
        workspace: crate::agent::WorkspaceConfig {
            base_dir: path.to_path_buf(),
            ..Default::default()
        },
        ..Default::default()
    }
}

async fn append_turn(session: &mut Session, prompt: &str) {
    session
        .append_turn(vec![ContentBlock::text(prompt)])
        .await
        .expect("scripted turn succeeds");
}

const ORIGINAL_SAFE_WRITE: &str = r#"{"path":"notes.md","content":"safe"}"#;
const REWRITTEN_PROTECTED_WRITE: &str = r#"{"path":".git/config","content":"denied"}"#;

#[derive(Clone, Copy)]
enum PolicyRewrite {
    None,
    Legacy,
    Mixed,
}

struct LegacyPolicyRewrite;

#[async_trait]
impl PreExecutionHook for LegacyPolicyRewrite {
    async fn pre_tool_execution(
        &self,
        _context: &PreExecutionContext,
    ) -> Result<HookDecision, RuntimeError> {
        Ok(HookDecision::Modify {
            input_json: REWRITTEN_PROTECTED_WRITE.to_string(),
            reason: Some("redirected to protected config".to_string()),
        })
    }
}

struct MixedPolicyRewrite;

#[async_trait]
impl ExecutionHookParticipant for MixedPolicyRewrite {
    fn name(&self) -> &str {
        "workspace-policy"
    }

    async fn before(&self, _context: &PreExecutionContext) -> Result<BeforeDecision, RuntimeError> {
        Ok(BeforeDecision::Modify {
            input_json: REWRITTEN_PROTECTED_WRITE.to_string(),
            attribution: Some("redirected to protected config".to_string()),
        })
    }
}

async fn protected_write_denial(rewrite: PolicyRewrite) -> (String, String) {
    let directory = TestDirectory::new("rewritten-protected-write");
    let protected_root = directory.path().join(".git");
    fs::create_dir_all(&protected_root).expect("create protected root");
    let protected_target = fs::canonicalize(&protected_root)
        .expect("canonical protected root")
        .join("config");
    let model = model_info("model", BuiltinProvider::Anthropic);
    let model_input = match rewrite {
        PolicyRewrite::None => REWRITTEN_PROTECTED_WRITE,
        PolicyRewrite::Legacy | PolicyRewrite::Mixed => ORIGINAL_SAFE_WRITE,
    };
    let provider = ScriptedProvider::new(
        BuiltinProvider::Anthropic,
        vec![model.clone()],
        vec![
            tool_use_stream(&model.id, "protected-write", "write", model_input),
            text_stream(&model.id, "done"),
        ],
    );
    let mut builder = Runtime::builder()
        .with_store(VolatileRuntimeStore::new())
        .with_provider_instance(provider)
        .with_file_tools(FileToolProfile::Split)
        .with_policy(
            RuntimePolicy::workspace_bounded(directory.path())
                .with_denied_write_root(&protected_root),
        );
    builder = match rewrite {
        PolicyRewrite::None => builder,
        PolicyRewrite::Legacy => builder.with_pre_hook(LegacyPolicyRewrite),
        PolicyRewrite::Mixed => builder.with_execution_hook(MixedPolicyRewrite),
    };
    let runtime = builder.build().expect("build runtime");
    let mut agent = runtime
        .spawn_with_config("agent", model, workspace_config(directory.path()))
        .expect("spawn agent");

    agent
        .send(vec![ContentBlock::text("write the file")])
        .await
        .expect("run completes");

    let (result, is_error) = result_for(agent.history(), "protected-write");
    assert!(is_error, "the protected write must fail: {result}");
    assert!(
        !directory.path().join(".git/config").exists(),
        "the denied write must not reach the filesystem"
    );
    let policy_denial = format!(
        "Path '{}' is inside a runtime policy denied write root",
        protected_target.display()
    );
    (result, policy_denial)
}

#[tokio::test]
async fn rewritten_runtime_policy_denials_name_legacy_and_mixed_hooks() {
    let (legacy, legacy_policy_denial) = protected_write_denial(PolicyRewrite::Legacy).await;
    assert_eq!(
        legacy,
        format!(
            "pre-execution hook rewrote this call; the rewritten call then failed: \
             {legacy_policy_denial}"
        )
    );

    let (mixed, mixed_policy_denial) = protected_write_denial(PolicyRewrite::Mixed).await;
    assert_eq!(
        mixed,
        format!(
            "mixed execution hooks (execution hook 'workspace-policy': redirected to protected \
             config) rewrote this call; the rewritten call then failed: {mixed_policy_denial}"
        )
    );
}

#[tokio::test]
async fn an_unmodified_runtime_policy_denial_keeps_its_exact_content() {
    let (result, policy_denial) = protected_write_denial(PolicyRewrite::None).await;
    assert_eq!(result, policy_denial);
}

#[tokio::test]
async fn contradictory_session_policies_are_isolated_and_none_inherits_the_runtime() {
    let model = model_info("model", BuiltinProvider::Anthropic);
    let command = json!({ "command": shell_pwd_command() }).to_string();
    let provider = ScriptedProvider::new(
        BuiltinProvider::Anthropic,
        vec![model.clone()],
        vec![
            tool_use_stream(&model.id, "allowed-shell", "shell", &command),
            text_stream(&model.id, "allowed done"),
            tool_use_stream(&model.id, "denied-shell", "shell", &command),
            text_stream(&model.id, "denied done"),
            tool_use_stream(&model.id, "inherited-shell", "shell", &command),
            text_stream(&model.id, "inherited done"),
        ],
    );
    let runtime = Runtime::builder()
        .with_store(VolatileRuntimeStore::new())
        .with_provider_instance(provider)
        .with_policy(RuntimePolicy::default())
        .build()
        .expect("build runtime");

    let mut allowed = runtime
        .create_session_with_options(
            "allowed",
            model.clone(),
            SessionOptions {
                policy: Some(RuntimePolicy::permissive()),
                ..Default::default()
            },
        )
        .expect("create allowed session");
    let mut denied = runtime
        .create_session_with_options(
            "denied",
            model.clone(),
            SessionOptions {
                policy: Some(RuntimePolicy::default()),
                ..Default::default()
            },
        )
        .expect("create denied session");
    let mut inherited = runtime
        .create_session("inherited", model)
        .expect("create inherited session");

    append_turn(&mut allowed, "run the shell").await;
    append_turn(&mut denied, "run the shell").await;
    append_turn(&mut inherited, "run the shell").await;

    let (_, allowed_error) = result_for(allowed.history(), "allowed-shell");
    let (denied_result, denied_error) = result_for(denied.history(), "denied-shell");
    let (inherited_result, inherited_error) = result_for(inherited.history(), "inherited-shell");
    assert!(
        !allowed_error,
        "the permissive session executes its command"
    );
    assert!(denied_error, "the scoped default policy denies its command");
    assert!(
        denied_result.contains("disabled by the runtime policy"),
        "{denied_result}"
    );
    assert!(
        inherited_error && inherited_result.contains("disabled by the runtime policy"),
        "None must inherit the runtime policy: {inherited_result}"
    );
}

async fn assert_protected_write_is_denied(
    profile: FileToolProfile,
    tool_name: &str,
    call_id: &str,
    input: serde_json::Value,
    relative_target: &Path,
) {
    let directory = TestDirectory::new(tool_name);
    let protected_root = directory.path().join(".git").join("hooks");
    fs::create_dir_all(&protected_root).expect("create protected root");
    let model = model_info("model", BuiltinProvider::Anthropic);
    let provider = ScriptedProvider::new(
        BuiltinProvider::Anthropic,
        vec![model.clone()],
        vec![
            tool_use_stream(&model.id, call_id, tool_name, &input.to_string()),
            text_stream(&model.id, "done"),
        ],
    );
    let runtime = Runtime::builder()
        .with_store(VolatileRuntimeStore::new())
        .with_provider_instance(provider)
        .with_file_tools(profile)
        .with_policy(RuntimePolicy::permissive())
        .build()
        .expect("build runtime");
    let policy =
        RuntimePolicy::workspace_bounded(directory.path()).with_denied_write_root(protected_root);
    let mut session = runtime
        .create_session_with_options(
            "protected",
            model,
            SessionOptions {
                config: workspace_config(directory.path()),
                policy: Some(policy),
                ..Default::default()
            },
        )
        .expect("create protected session");

    append_turn(&mut session, "write the protected file").await;

    let (result, is_error) = result_for(session.history(), call_id);
    assert!(is_error, "the protected write must fail: {result}");
    assert!(result.contains("denied write root"), "{result}");
    assert!(
        !directory.path().join(relative_target).exists(),
        "the denied write must not reach the filesystem"
    );
}

#[tokio::test]
async fn batched_and_split_file_writes_use_the_session_policy() {
    assert_protected_write_is_denied(
        FileToolProfile::Batched,
        "files",
        "batched-write",
        json!({
            "operations": [{
                "op": "create",
                "path": ".git/hooks/pre-commit",
                "content": "echo denied"
            }]
        }),
        Path::new(".git/hooks/pre-commit"),
    )
    .await;

    assert_protected_write_is_denied(
        FileToolProfile::Split,
        "write",
        "split-write",
        json!({
            "path": ".git/hooks/pre-push",
            "content": "echo denied"
        }),
        Path::new(".git/hooks/pre-push"),
    )
    .await;
}

#[tokio::test]
async fn tool_result_caps_use_the_session_policy() {
    const FULL_OUTPUT: &str = "abcdefghijklmnopqrstuvwxyz0123456789";

    let model = model_info("model", BuiltinProvider::Anthropic);
    let provider = ScriptedProvider::new(
        BuiltinProvider::Anthropic,
        vec![model.clone()],
        vec![
            tool_use_stream(&model.id, "capped-output", "long_output", r#"{}"#),
            text_stream(&model.id, "done"),
        ],
    );
    let runtime = Runtime::empty_builder()
        .with_store(VolatileRuntimeStore::new())
        .with_provider_instance(provider)
        .with_tool(StaticTool::success("long_output", FULL_OUTPUT))
        .with_policy(
            RuntimePolicy::permissive()
                .with_max_tool_result_bytes(usize::MAX)
                .with_max_tool_result_lines(usize::MAX),
        )
        .build()
        .expect("build runtime");
    let policy = RuntimePolicy::permissive()
        .with_max_tool_result_bytes(16)
        .with_max_tool_result_lines(usize::MAX)
        .spill_full_tool_output(false);
    let mut session = runtime
        .create_session_with_options(
            "capped",
            model,
            SessionOptions {
                policy: Some(policy),
                ..Default::default()
            },
        )
        .expect("create capped session");

    append_turn(&mut session, "return the long output").await;

    let (result, is_error) = result_for(session.history(), "capped-output");
    assert!(!is_error, "the tool itself succeeds: {result}");
    assert!(result.contains("[truncated:"), "{result}");
    assert!(
        !result.contains(FULL_OUTPUT),
        "the full body must be capped"
    );
}

#[tokio::test]
async fn disposable_subagents_inherit_the_session_policy() {
    let model = model_info("model", BuiltinProvider::Anthropic);
    let command = json!({ "command": shell_pwd_command() }).to_string();
    let provider = ScriptedProvider::new(
        BuiltinProvider::Anthropic,
        vec![model.clone()],
        vec![
            tool_use_stream(&model.id, "child-shell", "shell", &command),
            text_stream(&model.id, "child done"),
        ],
    );
    let provider_log = provider.clone();
    let runtime = Runtime::builder()
        .with_store(VolatileRuntimeStore::new())
        .with_provider_instance(provider)
        .with_policy(RuntimePolicy::permissive())
        .build()
        .expect("build runtime");
    let mut session = runtime
        .create_session_with_options(
            "parent",
            model,
            SessionOptions {
                policy: Some(RuntimePolicy::default()),
                ..Default::default()
            },
        )
        .expect("create parent session");
    let mut events = session.subscribe();
    let subagent = session
        .spawn_subagent("child", "try the shell")
        .await
        .expect("spawn child");

    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            match events.recv().await.expect("subagent event") {
                SessionEvent::TaskUpdated {
                    task_id,
                    status: TaskLifecycleStatus::Finished,
                    ..
                } if task_id == subagent.agent_id => break,
                _ => continue,
            }
        }
    })
    .await
    .expect("subagent finishes");

    let requests = provider_log.recorded_requests().await;
    assert_eq!(requests.len(), 2);
    let (result, is_error) = result_for(&requests[1].messages, "child-shell");
    assert!(is_error, "the child must inherit the denial: {result}");
    assert!(
        result.contains("disabled by the runtime policy"),
        "{result}"
    );
}

#[tokio::test]
async fn resume_uses_the_supplied_current_policy_and_never_persists_it() {
    let model = model_info("model", BuiltinProvider::Anthropic);
    let command = json!({ "command": shell_pwd_command() }).to_string();
    let provider = ScriptedProvider::new(
        BuiltinProvider::Anthropic,
        vec![model.clone()],
        vec![
            tool_use_stream(&model.id, "resumed-allowed", "shell", &command),
            text_stream(&model.id, "allowed done"),
            tool_use_stream(&model.id, "resumed-inherited", "shell", &command),
            text_stream(&model.id, "inherited done"),
        ],
    );
    let runtime = Runtime::builder()
        .with_store(VolatileRuntimeStore::new())
        .with_provider_instance(provider)
        .with_policy(RuntimePolicy::default())
        .build()
        .expect("build runtime");
    let original = runtime
        .create_session_with_options(
            "persisted",
            model,
            SessionOptions {
                policy: Some(RuntimePolicy::permissive()),
                ..Default::default()
            },
        )
        .expect("create persisted session");
    let agent_id = original.agent_id().to_string();
    drop(original);

    let mut explicitly_permissive = runtime
        .resume_session_with_options(
            &agent_id,
            SessionResumeOptions {
                policy: Some(RuntimePolicy::permissive()),
                ..Default::default()
            },
        )
        .expect("resume with current policy");
    append_turn(&mut explicitly_permissive, "run after explicit resume").await;
    let (_, allowed_error) = result_for(explicitly_permissive.history(), "resumed-allowed");
    assert!(!allowed_error, "the supplied current policy must apply");
    drop(explicitly_permissive);

    let mut inherited = runtime
        .resume_session(&agent_id)
        .expect("resume with runtime policy");
    append_turn(&mut inherited, "run after inherited resume").await;
    let (result, is_error) = result_for(inherited.history(), "resumed-inherited");
    assert!(is_error, "the old scoped policy must not be persisted");
    assert!(
        result.contains("disabled by the runtime policy"),
        "{result}"
    );
}