anda_engine 0.16.3

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
//! Public API regressions for coding tool bundles, patches and shell sessions.

#[cfg(unix)]
use anda_core::StateFeatures;
use anda_core::Tool;
use anda_engine::{
    context::BaseCtx,
    engine::EngineBuilder,
    extension::{
        fs::{
            ApplyPatchArgs, ApplyPatchTool, EditFileArgs, EditFileTool, FileVersion, ReadFileArgs,
            ReadFileTool, WriteFileArgs, WriteFileTool,
        },
        shell::{NativeRuntime, ShellSessionScope},
    },
};
use std::{
    path::{Path, PathBuf},
    sync::Arc,
};

#[cfg(unix)]
use anda_engine::extension::shell::{
    CommandArgs, CommandOutput, CommandState, Executor, SessionAction, SessionArgs, SessionLimits,
};
#[cfg(unix)]
use std::time::Duration;

struct Directory(PathBuf);
impl Directory {
    fn new() -> Self {
        let path = std::env::temp_dir().join(format!(
            "anda-workspace-regression-{:032x}",
            rand::random::<u128>()
        ));
        std::fs::create_dir_all(&path).unwrap();
        Self(std::fs::canonicalize(path).unwrap())
    }
    fn path(&self) -> &Path {
        &self.0
    }
}
impl Drop for Directory {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}
fn context() -> BaseCtx {
    let ctx = EngineBuilder::new().mock_ctx().base;
    ctx.set_state(ShellSessionScope::new());
    ctx
}

#[tokio::test]
async fn concurrent_file_edits_preserve_both_changes() {
    let dir = Directory::new();
    let path = dir.path().join("file.txt");
    let a = EditFileTool::new(dir.0.clone());
    let b = EditFileTool::new(dir.0.clone());
    for _ in 0..20 {
        tokio::fs::write(&path, "alpha=old\nbeta=old\n")
            .await
            .unwrap();
        let (a, b) = tokio::join!(
            a.call(
                context(),
                EditFileArgs {
                    path: "file.txt".into(),
                    old_string: "alpha=old".into(),
                    new_string: "alpha=new".into(),
                    ..Default::default()
                },
                vec![]
            ),
            b.call(
                context(),
                EditFileArgs {
                    path: "file.txt".into(),
                    old_string: "beta=old".into(),
                    new_string: "beta=new".into(),
                    ..Default::default()
                },
                vec![]
            )
        );
        a.unwrap();
        b.unwrap();
        assert_eq!(
            tokio::fs::read_to_string(&path).await.unwrap(),
            "alpha=new\nbeta=new\n"
        );
    }
}

#[tokio::test]
async fn oversized_write_leaves_old_file_unchanged() {
    let dir = Directory::new();
    tokio::fs::write(dir.path().join("file.txt"), "original")
        .await
        .unwrap();
    let tool = WriteFileTool::new(dir.0.clone());
    let result = tool
        .call(
            context(),
            WriteFileArgs {
                path: "file.txt".into(),
                content: "x".repeat(10 * 1024 * 1024 + 1),
                ..Default::default()
            },
            vec![],
        )
        .await;
    assert!(result.is_err());
    assert_eq!(
        tokio::fs::read_to_string(dir.path().join("file.txt"))
            .await
            .unwrap(),
        "original"
    );
}

#[tokio::test]
async fn patch_prevalidation_dry_run_versions_and_crlf() {
    let dir = Directory::new();
    tokio::fs::write(dir.path().join("old.txt"), "alpha\r\nbeta\r\n")
        .await
        .unwrap();
    let tool = ApplyPatchTool::new(dir.0.clone());
    let patch = "*** Begin Patch\n*** Update File: old.txt\n*** Move to: nested/new.txt\n@@\n alpha\n-beta\n+gamma\n*** Add File: added.txt\n+created\n*** End Patch";
    let preview = tool
        .call(
            context(),
            ApplyPatchArgs {
                patch: patch.into(),
                dry_run: true,
                ..Default::default()
            },
            vec![],
        )
        .await
        .unwrap()
        .output;
    assert!(!dir.path().join("added.txt").exists());
    assert!(preview.changes.iter().all(|change| !change.applied));
    assert!(preview.diff.contains("+gamma"));
    let stale = tool
        .call(
            context(),
            ApplyPatchArgs {
                patch: patch.into(),
                expected_versions: vec![FileVersion {
                    path: "old.txt".into(),
                    sha256: "stale".into(),
                }],
                ..Default::default()
            },
            vec![],
        )
        .await;
    assert!(stale.unwrap_err().to_string().contains("Stale"));
    let result = tool
        .call(
            context(),
            ApplyPatchArgs {
                patch: patch.into(),
                expected_versions: preview
                    .changes
                    .iter()
                    .map(|change| FileVersion {
                        path: change.path.clone(),
                        sha256: change.original_sha256.clone(),
                    })
                    .collect(),
                ..Default::default()
            },
            vec![],
        )
        .await
        .unwrap();
    assert_eq!(result.is_error, None);
    assert!(result.output.changes.iter().all(|change| change.applied));
    assert!(!dir.path().join("old.txt").exists());
    assert_eq!(
        tokio::fs::read(dir.path().join("nested/new.txt"))
            .await
            .unwrap(),
        b"alpha\r\ngamma\r\n"
    );
}

#[tokio::test]
async fn invalid_patch_does_not_apply_earlier_changes() {
    let dir = Directory::new();
    tokio::fs::write(dir.path().join("ambiguous.txt"), "same\nsame\n")
        .await
        .unwrap();
    let tool = ApplyPatchTool::new(dir.0.clone());
    for patch in [
        "*** Begin Patch\n*** Add File: new.txt\n+first\n*** Update File: ambiguous.txt\n@@\n-same\n+changed\n*** End Patch",
        "*** Begin Patch\n*** Add File: new.txt\n+first\n*** Add File: ../escape.txt\n+outside\n*** End Patch",
        "*** Begin Patch\n*** Add File: ambiguous.txt\n+overwrite\n*** End Patch",
        "*** Begin Patch\n*** Delete File: missing.txt\n*** End Patch",
    ] {
        assert!(
            tool.call(
                context(),
                ApplyPatchArgs {
                    patch: patch.into(),
                    ..Default::default()
                },
                vec![]
            )
            .await
            .is_err()
        );
        assert!(!dir.path().join("new.txt").exists());
        assert_eq!(
            tokio::fs::read_to_string(dir.path().join("ambiguous.txt"))
                .await
                .unwrap(),
            "same\nsame\n"
        );
    }
}

#[cfg(unix)]
#[tokio::test]
async fn patch_rejects_symlinks_and_hardlinks_for_every_mutation() {
    let dir = Directory::new();
    let outside = Directory::new();
    std::fs::write(outside.path().join("victim"), "secret\n").unwrap();
    std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap();
    std::fs::hard_link(outside.path().join("victim"), dir.path().join("hard")).unwrap();
    let tool = ApplyPatchTool::new(dir.0.clone());
    for body in [
        "*** Delete File: link/victim",
        "*** Add File: link/new\n+bad",
        "*** Update File: hard\n@@\n-secret\n+changed",
        "*** Delete File: hard",
    ] {
        assert!(
            tool.call(
                context(),
                ApplyPatchArgs {
                    patch: format!("*** Begin Patch\n{body}\n*** End Patch"),
                    ..Default::default()
                },
                vec![]
            )
            .await
            .is_err()
        );
    }
    assert_eq!(
        std::fs::read_to_string(outside.path().join("victim")).unwrap(),
        "secret\n"
    );
}

#[cfg(unix)]
async fn finish(
    runtime: &NativeRuntime,
    ctx: &BaseCtx,
    mut output: CommandOutput,
) -> CommandOutput {
    let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
    while output.state == CommandState::Running {
        assert!(
            tokio::time::Instant::now() < deadline,
            "process failed to finish"
        );
        output = runtime
            .interact_session(
                ctx.clone(),
                SessionArgs {
                    task_id: Some(output.task_id),
                    yield_time_ms: Some(50),
                    ..Default::default()
                },
            )
            .await
            .unwrap()
            .command
            .unwrap();
    }
    output
}

#[cfg(unix)]
#[tokio::test]
async fn sessions_poll_input_scopes_and_close_stdin() {
    let dir = Directory::new();
    let runtime = NativeRuntime::new(dir.0.clone()).session_limits(SessionLimits {
        allow_stdin: true,
        ..Default::default()
    });
    let ctx = context();
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "read value; printf 'result:%s' \"$value\"".into(),
                stdin: true,
                background: true,
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    assert_eq!(output.state, CommandState::Running);
    let denied = runtime
        .interact_session(
            context(),
            SessionArgs {
                task_id: Some(output.task_id.clone()),
                ..Default::default()
            },
        )
        .await;
    assert!(denied.unwrap_err().to_string().contains("inaccessible"));
    let first = runtime
        .interact_session(
            ctx.clone(),
            SessionArgs {
                task_id: Some(output.task_id.clone()),
                action: SessionAction::Write,
                input: Some("hello\n".into()),
                yield_time_ms: Some(1000),
                ..Default::default()
            },
        )
        .await
        .unwrap()
        .command
        .unwrap();
    let text = first.output.stdout.clone().unwrap_or_default();
    let final_output = finish(&runtime, &ctx, first).await;
    assert_eq!(final_output.exit_code, Some(0));
    assert!(
        format!("{}{}", text, final_output.output.stdout.unwrap_or_default())
            .contains("result:hello")
    );
    let replay = runtime
        .interact_session(
            ctx.clone(),
            SessionArgs {
                task_id: Some(output.task_id),
                ..Default::default()
            },
        )
        .await
        .unwrap()
        .command
        .unwrap();
    assert_eq!(replay.output.stdout.as_deref(), Some(""));
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "cat >/dev/null".into(),
                stdin: true,
                background: true,
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    let closed = runtime
        .interact_session(
            ctx.clone(),
            SessionArgs {
                task_id: Some(output.task_id),
                action: SessionAction::CloseStdin,
                ..Default::default()
            },
        )
        .await
        .unwrap()
        .command
        .unwrap();
    assert_eq!(finish(&runtime, &ctx, closed).await.exit_code, Some(0));
}

#[cfg(unix)]
#[tokio::test]
async fn shell_exit_terminates_remaining_session_descendants() {
    // Cover descendants that close the pipes as well as those that keep them open.
    for redirect in [" >/dev/null 2>&1", ""] {
        let dir = Directory::new();
        let ctx = context();
        let runtime = NativeRuntime::new(dir.0.clone());
        let output = runtime
            .execute_session(
                ctx.clone(),
                CommandArgs {
                    command: format!("(sleep 0.5; printf escaped > escaped){redirect} &"),
                    ..Default::default()
                },
                Default::default(),
            )
            .await
            .unwrap();
        let output = finish(&runtime, &ctx, output).await;
        assert_eq!(output.state, CommandState::Exited);
        assert_eq!(output.exit_code, Some(0));
        assert!(output.log_complete);
        runtime
            .interact_session(
                ctx,
                SessionArgs {
                    task_id: Some(output.task_id),
                    action: SessionAction::Stop,
                    ..Default::default()
                },
            )
            .await
            .unwrap();
        drop(runtime);
        tokio::time::sleep(Duration::from_millis(650)).await;
        assert!(
            !dir.path().join("escaped").exists(),
            "descendant survived: {redirect:?}"
        );
    }
}

#[cfg(unix)]
#[tokio::test]
async fn runtime_deadline_session_cap_and_stop_are_enforced() {
    let dir = Directory::new();
    let runtime = NativeRuntime::new(dir.0.clone()).session_limits(SessionLimits {
        max_sessions: 1,
        max_runtime: Duration::from_millis(150),
        ..Default::default()
    });
    let ctx = context();
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "sleep 10".into(),
                background: true,
                timeout_ms: Some(30_000),
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    assert!(
        runtime
            .execute_session(
                ctx.clone(),
                CommandArgs {
                    command: "sleep 10".into(),
                    ..Default::default()
                },
                Default::default()
            )
            .await
            .unwrap_err()
            .to_string()
            .contains("limit")
    );
    assert_eq!(
        finish(&runtime, &ctx, output).await.state,
        CommandState::TimedOut
    );
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "sleep 10".into(),
                background: true,
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    let stopped = runtime
        .interact_session(
            ctx.clone(),
            SessionArgs {
                task_id: Some(output.task_id),
                action: SessionAction::Stop,
                ..Default::default()
            },
        )
        .await
        .unwrap()
        .command
        .unwrap();
    assert_eq!(
        finish(&runtime, &ctx, stopped).await.state,
        CommandState::Cancelled
    );
}

#[cfg(unix)]
#[tokio::test]
async fn cancellation_retention_and_admission_do_not_leak_processes() {
    let dir = Directory::new();
    let runtime = NativeRuntime::new(dir.0.clone()).session_limits(SessionLimits {
        max_sessions: 1,
        retention: Duration::from_secs(10),
        ..Default::default()
    });
    let ctx = context();
    let running = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "sleep 10".into(),
                background: true,
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    assert!(
        runtime
            .execute_session(
                ctx.clone(),
                CommandArgs {
                    command: "touch forbidden".into(),
                    ..Default::default()
                },
                Default::default()
            )
            .await
            .is_err()
    );
    assert!(!dir.path().join("forbidden").exists());
    let mut other_agent = ctx.clone();
    other_agent.agent = "different-agent".into();
    assert!(
        runtime
            .interact_session(
                other_agent,
                SessionArgs {
                    task_id: Some(running.task_id.clone()),
                    action: SessionAction::Stop,
                    ..Default::default()
                }
            )
            .await
            .is_err()
    );
    ctx.cancellation_token().cancel();
    // A fresh request can query the same host-created scope after cancellation.
    let next = context();
    next.set_state(ctx.get_state::<ShellSessionScope>().unwrap());
    let finished = finish(&runtime, &next, running).await;
    assert_eq!(finished.state, CommandState::Cancelled);
    tokio::time::sleep(Duration::from_millis(20)).await;
    let retained = runtime
        .interact_session(
            next,
            SessionArgs {
                task_id: Some(finished.task_id),
                ..Default::default()
            },
        )
        .await
        .unwrap();
    assert_eq!(retained.command.unwrap().state, CommandState::Cancelled);
}

#[cfg(unix)]
#[tokio::test]
async fn changing_runtime_policy_invalidates_old_sessions() {
    let dir = Directory::new();
    let ctx = context();
    let runtime = NativeRuntime::new(dir.0.clone()).session_limits(SessionLimits {
        allow_stdin: true,
        ..Default::default()
    });
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "cat >/dev/null".into(),
                stdin: true,
                background: true,
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    let runtime = runtime.session_limits(SessionLimits::default());
    let result = runtime
        .interact_session(
            ctx,
            SessionArgs {
                task_id: Some(output.task_id),
                action: SessionAction::Write,
                input: Some("old authority\n".into()),
                ..Default::default()
            },
        )
        .await;
    assert!(result.unwrap_err().to_string().contains("inaccessible"));
}

#[cfg(target_os = "linux")]
#[tokio::test]
#[ignore = "requires bubblewrap and user namespaces; run explicitly for OS isolation validation"]
async fn process_sandbox_preserves_workspace_and_read_grants_under_tmp() {
    use anda_engine::extension::shell::SandboxPolicy;
    let root = PathBuf::from(format!(
        "/tmp/anda-sandbox-regression-{:032x}",
        rand::random::<u128>()
    ));
    std::fs::create_dir(&root).unwrap();
    let root = Directory(root.canonicalize().unwrap());
    let workspace = root.path().join("workspace");
    let readable = root.path().join("readable");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::create_dir(&readable).unwrap();
    std::fs::write(readable.join("input"), "granted").unwrap();
    let policy = SandboxPolicy::workspace(&workspace)
        .unwrap()
        .allow_read(&readable)
        .unwrap();
    let runtime = NativeRuntime::new(workspace.clone())
        .with_sandbox(policy)
        .unwrap();
    let ctx = context();
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "cat \"$INPUT\" > output && printf ':written' >> output".into(),
                ..Default::default()
            },
            [("INPUT".into(), readable.join("input").display().to_string())].into(),
        )
        .await
        .unwrap();
    let output = finish(&runtime, &ctx, output).await;
    assert_eq!(output.exit_code, Some(0), "{output:?}");
    assert_eq!(
        std::fs::read(workspace.join("output")).unwrap(),
        b"granted:written"
    );
}

#[cfg(target_os = "macos")]
#[tokio::test]
#[ignore = "requires a host allowing sandbox-exec; run explicitly for OS isolation validation"]
async fn process_sandbox_denies_outside_reads_writes_and_network() {
    use anda_engine::extension::shell::SandboxPolicy;
    let dir = Directory::new();
    let outside = Directory::new();
    std::fs::write(outside.path().join("secret"), "sensitive").unwrap();
    // curl's system TLS library reads this configuration even for plain HTTP.
    // Both network policies receive the same explicit, read-only host grant.
    let policy = SandboxPolicy::workspace(dir.path())
        .unwrap()
        .allow_read("/private/etc/ssl/openssl.cnf")
        .unwrap();
    let runtime = NativeRuntime::new(dir.0.clone())
        .with_sandbox(policy.clone())
        .unwrap();
    let mut command = std::process::Command::new("/bin/sh");
    command.args(["-c", "printf ok > allowed; test -f allowed || exit 10; if cat \"$OUTSIDE/secret\"; then exit 11; fi; if printf bad > \"$OUTSIDE/new\"; then exit 12; fi; if /usr/bin/curl --noproxy '*' --max-time 1 http://127.0.0.1:$PORT/; then exit 13; fi; printf passed"]);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let server = tokio::spawn(async move {
        if let Ok((mut socket, _)) = listener.accept().await {
            use tokio::io::AsyncWriteExt;
            let _ = socket
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
                .await;
        }
    });
    let result = runtime
        .execute_command(
            context(),
            "shell",
            command,
            [
                ("OUTSIDE".into(), outside.path().display().to_string()),
                ("PORT".into(), port.to_string()),
            ]
            .into(),
            None,
        )
        .await
        .unwrap();
    assert_eq!(result.stdout.as_deref(), Some("passed"), "{result:?}");
    assert!(!outside.path().join("new").exists());
    // Prove that curl itself works under the same filesystem policy, so a
    // loader/configuration failure cannot masquerade as a denied connection.
    let permitted = NativeRuntime::new(dir.0.clone())
        .with_sandbox(policy.network(anda_engine::extension::shell::SandboxNetwork::Allow))
        .unwrap();
    let mut command = std::process::Command::new("/usr/bin/curl");
    command.args([
        "--noproxy",
        "*",
        "--max-time",
        "2",
        &format!("http://127.0.0.1:{port}/"),
    ]);
    let allowed = permitted
        .execute_command(context(), "shell", command, Default::default(), None)
        .await
        .unwrap();
    server.abort();
    assert_eq!(allowed.stdout.as_deref(), Some("ok"), "{allowed:?}");
    let terminal = runtime.session_limits(SessionLimits {
        allow_pty: true,
        ..Default::default()
    });
    let terminal_ctx = context();
    let output = terminal
        .execute_session(
            terminal_ctx.clone(),
            CommandArgs {
                command: "test -t 0 && printf terminal".into(),
                tty: true,
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    let text = output.output.stdout.clone().unwrap_or_default();
    let output = finish(&terminal, &terminal_ctx, output).await;
    assert_eq!(output.exit_code, Some(0), "{output:?}");
    assert!(format!("{text}{}", output.output.stdout.unwrap_or_default()).contains("terminal"));
}

#[cfg(unix)]
#[tokio::test]
async fn output_budget_logs_cwd_and_spawn_failures() {
    let dir = Directory::new();
    std::fs::create_dir(dir.path().join("nested")).unwrap();
    let runtime = NativeRuntime::new(dir.0.clone()).session_limits(SessionLimits {
        max_log_bytes: 128,
        ..Default::default()
    });
    let ctx = context();
    assert!(
        runtime
            .execute_session(
                ctx.clone(),
                CommandArgs {
                    command: "pwd".into(),
                    cwd: Some("..".into()),
                    ..Default::default()
                },
                Default::default()
            )
            .await
            .is_err()
    );
    let output = runtime.execute_session(ctx.clone(), CommandArgs { command: "printf START; i=0; while [ $i -lt 1000 ]; do printf x; i=$((i+1)); done; printf FAILED".into(), cwd: Some("nested".into()), max_output_bytes: Some(128), ..Default::default() }, Default::default()).await.unwrap();
    assert!(
        output.output.stdout.as_ref().unwrap().len()
            + output.output.stderr.as_ref().map_or(0, String::len)
            <= 128
    );
    let final_output = finish(&runtime, &ctx, output).await;
    let log = runtime
        .interact_session(
            ctx.clone(),
            SessionArgs {
                action: SessionAction::ReadLog,
                task_id: Some(final_output.task_id),
                ..Default::default()
            },
        )
        .await
        .unwrap()
        .log
        .unwrap();
    assert!(!log.complete);
    assert!(log.text.contains("START"));
    let missing = dir.path().join("missing");
    let result = runtime
        .execute_command(
            ctx,
            "shell",
            std::process::Command::new(missing),
            Default::default(),
            None,
        )
        .await;
    assert!(result.unwrap_err().to_string().contains("Failed to spawn"));
}

#[cfg(unix)]
#[tokio::test]
async fn pty_is_opt_in_and_reports_terminal_output() {
    let dir = Directory::new();
    let ctx = context();
    let args = CommandArgs {
        command: "test -t 0 && printf terminal".into(),
        tty: true,
        ..Default::default()
    };
    let disabled = NativeRuntime::new(dir.0.clone());
    assert!(
        disabled
            .execute_session(ctx.clone(), args.clone(), Default::default())
            .await
            .is_err()
    );
    let runtime = NativeRuntime::new(dir.0.clone()).session_limits(SessionLimits {
        allow_pty: true,
        ..Default::default()
    });
    let output = runtime
        .execute_session(ctx.clone(), args, Default::default())
        .await
        .unwrap();
    let text = output.output.stdout.clone().unwrap_or_default();
    let output = finish(&runtime, &ctx, output).await;
    assert_eq!(output.exit_code, Some(0));
    assert!(format!("{text}{}", output.output.stdout.unwrap_or_default()).contains("terminal"));
}

#[tokio::test]
async fn patch_deletes_binary_files() {
    let dir = Directory::new();
    std::fs::write(
        dir.path().join("logo.png"),
        [0x89, b'P', b'N', b'G', 0, 0xff],
    )
    .unwrap();
    let tool = ApplyPatchTool::new(dir.0.clone());
    let result = tool
        .call(
            context(),
            ApplyPatchArgs {
                patch: "*** Begin Patch\n*** Delete File: logo.png\n*** End Patch".into(),
                ..Default::default()
            },
            vec![],
        )
        .await
        .unwrap();
    assert!(result.output.changes[0].applied);
    assert!(result.output.diff.contains("Binary file deleted"));
    assert!(!dir.path().join("logo.png").exists());
}

#[cfg(unix)]
#[tokio::test]
async fn foreground_wait_completes_commands_and_hooks_only_see_background_ones() {
    use anda_core::ToolOutput;
    use anda_engine::{
        extension::shell::{ExecArgs, ExecOutput, ShellToolHook},
        hook::{BackgroundHandle, ToolHook},
    };
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Default)]
    struct Events {
        start: AtomicUsize,
        end: AtomicUsize,
    }
    #[async_trait::async_trait]
    impl ToolHook<ExecArgs, ExecOutput> for Events {
        async fn on_background_start(&self, _: &BaseCtx, _: BackgroundHandle, _: &ExecArgs) {
            self.start.fetch_add(1, Ordering::SeqCst);
        }
        async fn on_background_end(&self, _: &BaseCtx, _: String, _: ToolOutput<ExecOutput>) {
            self.end.fetch_add(1, Ordering::SeqCst);
        }
    }

    let dir = Directory::new();
    let runtime = NativeRuntime::new(dir.0.clone());
    let ctx = context();
    let events = Arc::new(Events::default());
    ctx.set_state(ShellToolHook::new(events.clone()));
    // Early output must not end the foreground wait before the process exits.
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "printf a; sleep 0.2; printf b".into(),
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    assert_eq!(output.state, CommandState::Exited);
    assert_eq!(output.output.stdout.as_deref(), Some("ab"));

    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: "sleep 10".into(),
                yield_time_ms: Some(50),
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    assert_eq!(output.state, CommandState::Running);
    let stopped = runtime
        .interact_session(
            ctx.clone(),
            SessionArgs {
                task_id: Some(output.task_id),
                action: SessionAction::Stop,
                ..Default::default()
            },
        )
        .await
        .unwrap()
        .command
        .unwrap();
    finish(&runtime, &ctx, stopped).await;
    let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
    while events.end.load(Ordering::SeqCst) == 0 && tokio::time::Instant::now() < deadline {
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    assert_eq!(events.start.load(Ordering::SeqCst), 1);
    assert_eq!(events.end.load(Ordering::SeqCst), 1);
}

#[cfg(unix)]
#[tokio::test]
async fn read_log_keeps_multibyte_characters_whole() {
    let dir = Directory::new();
    let runtime = NativeRuntime::new(dir.0.clone());
    let ctx = context();
    let text = "汉字".repeat(10);
    let output = runtime
        .execute_session(
            ctx.clone(),
            CommandArgs {
                command: format!("printf '{text}'"),
                ..Default::default()
            },
            Default::default(),
        )
        .await
        .unwrap();
    let output = finish(&runtime, &ctx, output).await;
    let (mut offset, mut log_text) = (0, String::new());
    loop {
        let log = runtime
            .interact_session(
                ctx.clone(),
                SessionArgs {
                    task_id: Some(output.task_id.clone()),
                    action: SessionAction::ReadLog,
                    max_output_bytes: Some(128),
                    offset,
                    ..Default::default()
                },
            )
            .await
            .unwrap()
            .log
            .unwrap();
        log_text.push_str(&log.text);
        offset = log.next_offset;
        if log.eof {
            break;
        }
    }
    assert!(!log_text.contains('\u{fffd}'), "{log_text:?}");
    assert!(log_text.contains(&text));
}

#[tokio::test]
async fn coding_bundle_registers_no_redundant_file_read_tools() {
    use anda_engine::extension::workspace::{coding_tools, readonly_file_tools};
    let dir = Directory::new();
    let tools = coding_tools(Arc::new(NativeRuntime::new(dir.0.clone())), vec![]).unwrap();
    let builder = EngineBuilder::new().register_tools(tools).unwrap();
    let ctx = builder.mock_ctx();
    use anda_core::AgentContext;
    let names = ctx
        .tool_definitions(None)
        .into_iter()
        .map(|definition| definition.name)
        .collect::<Vec<_>>();
    for name in ["shell", "shell_session", "apply_patch"] {
        assert!(names.iter().any(|actual| actual == name));
    }
    for name in ["read_file", "search_file", "write_file", "edit_file"] {
        assert!(!names.iter().any(|actual| actual == name));
    }
    let ctx = EngineBuilder::new()
        .register_tools(readonly_file_tools(dir.0.clone()).unwrap())
        .unwrap()
        .mock_ctx();
    assert!(
        !ctx.tool_definitions(None)
            .iter()
            .any(|definition| definition.name == "shell")
    );
    // Existing filesystem APIs remain independently usable.
    let tool = ReadFileTool::new(dir.0.clone());
    assert!(
        tool.call(
            context(),
            ReadFileArgs {
                path: "missing".into(),
                ..Default::default()
            },
            vec![]
        )
        .await
        .is_err()
    );
}

#[cfg(unix)]
#[tokio::test]
async fn legacy_shell_hook_still_gates_session_commands() {
    use anda_core::{BoxError, ToolOutput};
    use anda_engine::{
        extension::shell::{ExecArgs, ExecOutput, ShellCommandTool, ShellToolHook},
        hook::ToolHook,
    };
    use parking_lot::Mutex;

    #[derive(Default)]
    struct Gate {
        seen: Mutex<Vec<String>>,
    }
    #[async_trait::async_trait]
    impl ToolHook<ExecArgs, ExecOutput> for Gate {
        async fn before_tool_call(
            &self,
            _: &BaseCtx,
            mut args: ExecArgs,
        ) -> Result<ExecArgs, BoxError> {
            if args.command.contains("marker") {
                return Err("denied by the host".into());
            }
            args.command = args.command.replace("original", "rewritten");
            Ok(args)
        }
        async fn after_tool_call(
            &self,
            _: &BaseCtx,
            output: ToolOutput<ExecOutput>,
        ) -> Result<ToolOutput<ExecOutput>, BoxError> {
            self.seen
                .lock()
                .push(output.output.stdout.clone().unwrap_or_default());
            Ok(output)
        }
    }

    let dir = Directory::new();
    let tool = ShellCommandTool::new(Arc::new(NativeRuntime::new(dir.0.clone())), vec![]);
    let gate = Arc::new(Gate::default());
    let ctx = context();
    ctx.set_state(ShellToolHook::new(gate.clone()));

    let denied = tool
        .call(
            ctx.clone(),
            CommandArgs {
                command: "touch marker".into(),
                ..Default::default()
            },
            vec![],
        )
        .await;
    assert!(
        denied
            .unwrap_err()
            .to_string()
            .contains("denied by the host")
    );
    assert!(!dir.path().join("marker").exists());

    let output = tool
        .call(
            ctx,
            CommandArgs {
                command: "printf original".into(),
                ..Default::default()
            },
            vec![],
        )
        .await
        .unwrap();
    assert_eq!(output.output.output.stdout.as_deref(), Some("rewritten"));
    assert_eq!(*gate.seen.lock(), vec!["rewritten".to_string()]);
}

#[cfg(unix)]
#[tokio::test]
async fn workspace_runtimes_share_sessions_with_their_base() {
    let base_dir = Directory::new();
    let granted = Directory::new();
    let runtime = NativeRuntime::new(base_dir.0.clone());
    let ctx = context();
    let output = {
        let derived = runtime.for_workspace(granted.0.clone());
        derived
            .execute_session(
                ctx.clone(),
                CommandArgs {
                    command: "sleep 0.2; printf done".into(),
                    background: true,
                    ..Default::default()
                },
                Default::default(),
            )
            .await
            .unwrap()
    };
    // The derived runtime is gone; its command must live on and stay reachable.
    assert_eq!(output.state, CommandState::Running);
    let task_id = output.task_id.clone();
    let output = finish(&runtime, &ctx, output).await;
    assert_eq!(output.state, CommandState::Exited);
    assert_eq!(
        output.output.workspace.as_deref(),
        Some(granted.path().to_string_lossy().as_ref())
    );
    let log = runtime
        .interact_session(
            ctx,
            SessionArgs {
                task_id: Some(task_id),
                action: SessionAction::ReadLog,
                ..Default::default()
            },
        )
        .await
        .unwrap()
        .log
        .unwrap();
    assert!(log.text.contains("done"), "{}", log.text);
}