everruns-platform 0.19.2

Backend control-plane entities and store contracts for the Everruns Platform
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
//! Tool implementations for container sandbox operations.
//!
//! Decision: One sandbox per session (container name derived from session ID).
//! Decision: All tools require context (requires_context = true).
//! Decision: Uses tool_output_sanitizer for exec output (same pipeline as Daytona).

use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use everruns_core::tool_context::ToolContext;
use everruns_core::tool_output_sanitizer::{
    READ_FILE_DEFAULT_LIMIT, build_bytes_read_file_result, clean_exec_output,
    output_verbosity_budget, parse_read_file_window_args, resolve_auto_mode,
};
use everruns_core::tools::{Tool, ToolExecutionResult};
use everruns_provider::tool_types::ToolHints;
use serde_json::{Value, json};
use tracing::{debug, error};

use super::client::{ContainerCreateConfig, DockerClient, HostConfig};
use super::config::ContainerSandboxConfig;
use super::state::{
    SandboxState, container_name, delete_sandbox_state, get_sandbox_state, network_name,
    release_sandbox_lease, sandbox_labels, save_sandbox_state, touch_sandbox_lease,
};

/// Helper: extract a required string parameter.
fn required_str(args: &Value, name: &str) -> Result<String, ToolExecutionResult> {
    args.get(name)
        .and_then(|v| v.as_str())
        .map(String::from)
        .ok_or_else(|| {
            ToolExecutionResult::tool_error(format!("Missing required parameter: {name}"))
        })
}

/// Helper: create a DockerClient from config.
fn docker_client(config: &ContainerSandboxConfig) -> DockerClient {
    DockerClient::new(config.docker_host.as_deref())
}

// ============================================================================
// sandbox_create
// ============================================================================

pub struct SandboxCreateTool;

#[async_trait]
impl Tool for SandboxCreateTool {
    fn name(&self) -> &str {
        "sandbox_create"
    }

    fn description(&self) -> &str {
        "Create and start a container sandbox for code execution. \
         One sandbox per session. Returns the sandbox container name."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "image": {
                    "type": "string",
                    "description": "Container image (default: ubuntu:24.04)"
                }
            },
            "additionalProperties": false
        })
    }

    fn hints(&self) -> ToolHints {
        ToolHints::default()
            .with_open_world(true)
            .with_long_running(true)
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "Tool requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let config = ContainerSandboxConfig::default();
        let image = arguments
            .get("image")
            .and_then(|v| v.as_str())
            .unwrap_or(&config.image)
            .to_string();

        let session_id = context.session_id.to_string();
        let c_name = container_name(&session_id);
        let n_name = network_name(&session_id);
        let labels = sandbox_labels(&session_id);
        let client = docker_client(&config);

        // Create network (track whether we created it vs reused an existing one)
        let (network_id, network_created) = match client
            .create_network(&n_name, labels.clone())
            .await
        {
            Ok(id) => (id, true),
            Err(e) if e.contains("already exists") || e.contains("Conflict") => {
                // Network exists, that's fine — reuse
                debug!(name = %n_name, "Network already exists, reusing");
                (n_name.clone(), false)
            }
            Err(e) => {
                return ToolExecutionResult::tool_error(format!("Failed to create network: {e}"));
            }
        };

        // Create container
        let create_config = ContainerCreateConfig {
            image: image.clone(),
            cmd: vec![
                "tail".to_string(),
                "-f".to_string(),
                "/dev/null".to_string(),
            ],
            working_dir: config.working_dir.clone(),
            labels,
            host_config: HostConfig {
                runtime: config.runtime.clone(),
                network_mode: n_name.clone(),
                memory: config.memory_limit,
                nano_cpus: config.cpu_limit,
                pids_limit: config.pids_limit,
                init: true,
            },
        };

        let container = match client.create_container(&c_name, &create_config).await {
            Ok(c) => c,
            Err(e) => {
                // Only remove network if we just created it
                // TODO: idempotent create (409/name conflict) is a follow-up
                if network_created {
                    let _ = client.remove_network(&network_id).await;
                }
                return ToolExecutionResult::tool_error(format!("Failed to create container: {e}"));
            }
        };

        // Start container
        if let Err(e) = client.start_container(&container.id).await {
            let _ = client.remove_container(&container.id).await;
            if network_created {
                let _ = client.remove_network(&network_id).await;
            }
            return ToolExecutionResult::tool_error(format!("Failed to start container: {e}"));
        }

        let now = chrono::Utc::now().to_rfc3339();
        let state = SandboxState {
            container_id: container.id.clone(),
            network_id: network_id.clone(),
            container_name: c_name.clone(),
            network_name: n_name,
            image: image.clone(),
            working_dir: config.working_dir.clone(),
            started_at: now,
        };

        // Save state and register lease
        if let Err(e) = save_sandbox_state(context, &state).await {
            return e;
        }
        if let Err(e) = touch_sandbox_lease(context, &state).await {
            return e;
        }

        ToolExecutionResult::success(format!(
            "Sandbox created and running.\n\
             Container: {c_name}\n\
             Image: {image}\n\
             Working directory: {}",
            config.working_dir
        ))
    }

    fn requires_context(&self) -> bool {
        true
    }
}

// ============================================================================
// sandbox_exec
// ============================================================================

pub struct SandboxExecTool;

#[async_trait]
impl Tool for SandboxExecTool {
    fn name(&self) -> &str {
        "sandbox_exec"
    }

    fn description(&self) -> &str {
        "Execute a command in the container sandbox. Returns stdout/stderr and exit code."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Shell command to execute"
                },
                "working_dir": {
                    "type": "string",
                    "description": "Working directory (default: /workspace)"
                },
                "output": everruns_core::tool_output_sanitizer::output_verbosity_schema()
            },
            "required": ["command"],
            "additionalProperties": false
        })
    }

    fn hints(&self) -> ToolHints {
        ToolHints::default()
            .with_open_world(true)
            .with_long_running(true)
            .with_persist_output(true)
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error(
            "Tool requires context. This tool must be executed with session context.",
        )
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let command = match required_str(&arguments, "command") {
            Ok(c) => c,
            Err(e) => return e,
        };

        // EVE-489: persistence-first default. `auto` returns a compact
        // summary on success and a `normal`-sized diagnostic window on failure.
        let output_mode = arguments
            .get("output")
            .and_then(|v| v.as_str())
            .unwrap_or("auto");

        let state = match get_sandbox_state(context).await {
            Ok(s) => s,
            Err(e) => return e,
        };

        let working_dir = arguments
            .get("working_dir")
            .and_then(|v| v.as_str())
            .unwrap_or(&state.working_dir);

        let config = ContainerSandboxConfig::default();
        let client = docker_client(&config);

        let result = match client
            .exec(
                &state.container_id,
                &["sh", "-c", &command],
                Some(working_dir),
            )
            .await
        {
            Ok(r) => r,
            Err(e) => return ToolExecutionResult::tool_error(format!("Exec failed: {e}")),
        };

        // Refresh lease on successful exec
        let _ = touch_sandbox_lease(context, &state).await;

        // Sanitize output. EVE-489: resolve `auto` against the exit code so
        // successes get a compact summary and failures still get a diagnostic
        // window. `resolve_auto_mode` only branches on `== 0`, so reduce the
        // (possibly i64) Docker exit code to a sentinel that preserves that
        // distinction without lossy casting.
        let exit_code = result.exit_code;
        let success_sentinel: i32 = if exit_code == 0 { 0 } else { 1 };
        let effective_mode = resolve_auto_mode(output_mode, success_sentinel);
        let clean_output = clean_exec_output(&result.output);
        let output = if let Some(budget) = output_verbosity_budget(effective_mode) {
            everruns_core::tool_output_sanitizer::truncate_exec_stream(
                &clean_output,
                budget,
                success_sentinel,
            )
        } else {
            clean_output.clone()
        };

        if exit_code == 0 {
            ToolExecutionResult::success_with_raw_output(output, clean_output)
        } else {
            ToolExecutionResult::success(format!("Exit code: {exit_code}\n\n{output}"))
        }
    }

    fn requires_context(&self) -> bool {
        true
    }
}

// ============================================================================
// sandbox_read_file
// ============================================================================

pub struct SandboxReadFileTool;

#[async_trait]
impl Tool for SandboxReadFileTool {
    fn name(&self) -> &str {
        "sandbox_read_file"
    }

    fn description(&self) -> &str {
        "Read a file from the container sandbox."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Absolute path to the file inside the container"
                },
                "offset": {
                    "type": "integer",
                    "minimum": 0,
                    "default": 0,
                    "description": "Zero-based line offset to start reading from"
                },
                "limit": {
                    "type": "integer",
                    "minimum": 1,
                    "default": READ_FILE_DEFAULT_LIMIT,
                    "description": "Maximum number of lines to return"
                }
            },
            "required": ["path"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error("Tool requires context.")
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let path = match required_str(&arguments, "path") {
            Ok(p) => p,
            Err(e) => return e,
        };
        let (offset, limit) = match parse_read_file_window_args(&arguments) {
            Ok(window) => window,
            Err(err) => return ToolExecutionResult::tool_error(err),
        };

        let state = match get_sandbox_state(context).await {
            Ok(s) => s,
            Err(e) => return e,
        };

        let config = ContainerSandboxConfig::default();
        let client = docker_client(&config);

        match client.get_archive(&state.container_id, &path).await {
            Ok(bytes) => ToolExecutionResult::success(build_bytes_read_file_result(
                "sandbox_read_file",
                &path,
                &bytes,
                offset,
                limit,
            )),
            Err(e) => ToolExecutionResult::tool_error(format!("Failed to read file: {e}")),
        }
    }

    fn requires_context(&self) -> bool {
        true
    }
}

// ============================================================================
// sandbox_write_file
// ============================================================================

pub struct SandboxWriteFileTool;

#[async_trait]
impl Tool for SandboxWriteFileTool {
    fn name(&self) -> &str {
        "sandbox_write_file"
    }

    fn description(&self) -> &str {
        "Write a file to the container sandbox."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Absolute path for the file inside the container"
                },
                "content": {
                    "type": "string",
                    "description": "File content to write"
                }
            },
            "required": ["path", "content"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error("Tool requires context.")
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let path = match required_str(&arguments, "path") {
            Ok(p) => p,
            Err(e) => return e,
        };
        let content = match required_str(&arguments, "content") {
            Ok(c) => c,
            Err(e) => return e,
        };

        let state = match get_sandbox_state(context).await {
            Ok(s) => s,
            Err(e) => return e,
        };

        let config = ContainerSandboxConfig::default();
        let client = docker_client(&config);

        // Split path into directory and filename
        let (dir, filename) = match path.rsplit_once('/') {
            Some((d, f)) if !d.is_empty() => (d.to_string(), f.to_string()),
            _ => ("/".to_string(), path.trim_start_matches('/').to_string()),
        };

        if filename.is_empty() {
            return ToolExecutionResult::tool_error(
                "Invalid path: filename is empty (trailing slash?)",
            );
        }

        match client
            .put_archive(&state.container_id, &dir, &filename, content.as_bytes())
            .await
        {
            Ok(()) => {
                ToolExecutionResult::success(format!("Written {path} ({} bytes)", content.len()))
            }
            Err(e) => ToolExecutionResult::tool_error(format!("Failed to write file: {e}")),
        }
    }

    fn requires_context(&self) -> bool {
        true
    }
}

// ============================================================================
// sandbox_list
// ============================================================================

pub struct SandboxListTool;

#[async_trait]
impl Tool for SandboxListTool {
    fn name(&self) -> &str {
        "sandbox_list"
    }

    fn description(&self) -> &str {
        "List container sandboxes for this session."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {},
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error("Tool requires context.")
    }

    async fn execute_with_context(
        &self,
        _arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let session_id = context.session_id.to_string();
        let config = ContainerSandboxConfig::default();
        let client = docker_client(&config);

        let filters = [("managed-by", "everruns"), ("session", &session_id)];

        match client.list_containers(&filters).await {
            Ok(containers) => {
                if containers.is_empty() {
                    return ToolExecutionResult::success("No sandboxes found for this session.");
                }
                let summary: Vec<String> = containers
                    .iter()
                    .map(|c| {
                        let name = c
                            .names
                            .first()
                            .map(|n| n.trim_start_matches('/'))
                            .unwrap_or("unknown");
                        format!("- {} ({}): {}", name, c.state, c.status)
                    })
                    .collect();
                ToolExecutionResult::success(summary.join("\n"))
            }
            Err(e) => ToolExecutionResult::tool_error(format!("Failed to list containers: {e}")),
        }
    }

    fn requires_context(&self) -> bool {
        true
    }
}

// ============================================================================
// sandbox_manage
// ============================================================================

pub struct SandboxManageTool;

#[async_trait]
impl Tool for SandboxManageTool {
    fn name(&self) -> &str {
        "sandbox_manage"
    }

    fn description(&self) -> &str {
        "Manage the container sandbox: stop, start, or remove it."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "description": "Action to perform",
                    "enum": ["stop", "start", "remove"]
                }
            },
            "required": ["action"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error("Tool requires context.")
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let action = match required_str(&arguments, "action") {
            Ok(a) => a,
            Err(e) => return e,
        };

        let state = match get_sandbox_state(context).await {
            Ok(s) => s,
            Err(e) => return e,
        };

        let config = ContainerSandboxConfig::default();
        let client = docker_client(&config);

        match action.as_str() {
            "stop" => {
                if let Err(e) = client.stop_container(&state.container_id, 10).await {
                    return ToolExecutionResult::tool_error(format!("Failed to stop: {e}"));
                }
                ToolExecutionResult::success("Sandbox stopped.")
            }
            "start" => {
                if let Err(e) = client.start_container(&state.container_id).await {
                    return ToolExecutionResult::tool_error(format!("Failed to start: {e}"));
                }
                let _ = touch_sandbox_lease(context, &state).await;
                ToolExecutionResult::success("Sandbox started.")
            }
            "remove" => {
                // Stop, remove container, remove network, clean up state
                let _ = client.stop_container(&state.container_id, 5).await;
                if let Err(e) = client.remove_container(&state.container_id).await {
                    error!("Failed to remove container: {e}");
                }
                let _ = client.remove_network(&state.network_id).await;
                let _ = release_sandbox_lease(context, &state.container_id).await;
                let _ = delete_sandbox_state(context, &state.container_name).await;
                ToolExecutionResult::success("Sandbox removed and cleaned up.")
            }
            _ => ToolExecutionResult::tool_error("Invalid action. Use: stop, start, or remove"),
        }
    }

    fn requires_context(&self) -> bool {
        true
    }
}

// ============================================================================
// sandbox_upload
// ============================================================================

pub struct SandboxUploadTool;

#[async_trait]
impl Tool for SandboxUploadTool {
    fn name(&self) -> &str {
        "sandbox_upload"
    }

    fn description(&self) -> &str {
        "Upload a file from session storage to the container sandbox."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "session_path": {
                    "type": "string",
                    "description": "Path of the file in session storage"
                },
                "container_path": {
                    "type": "string",
                    "description": "Absolute destination path inside the container"
                }
            },
            "required": ["session_path", "container_path"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error("Tool requires context.")
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let session_path = match required_str(&arguments, "session_path") {
            Ok(p) => p,
            Err(e) => return e,
        };
        let container_path = match required_str(&arguments, "container_path") {
            Ok(p) => p,
            Err(e) => return e,
        };

        let state = match get_sandbox_state(context).await {
            Ok(s) => s,
            Err(e) => return e,
        };

        let file_store = match context.file_store.as_ref() {
            Some(fs) => fs,
            None => return ToolExecutionResult::tool_error("File store not available"),
        };

        // Read file from session VFS
        let file = match file_store
            .read_file(context.session_id, &session_path)
            .await
        {
            Ok(Some(f)) => f,
            Ok(None) => {
                return ToolExecutionResult::tool_error(format!(
                    "File not found in session storage: {session_path}"
                ));
            }
            Err(e) => {
                return ToolExecutionResult::tool_error(format!(
                    "Failed to read from session storage: {e}"
                ));
            }
        };

        // Decode content (text or base64)
        let content_str = file.content.unwrap_or_default();
        let bytes = if file.encoding == "base64" {
            match BASE64.decode(&content_str) {
                Ok(b) => b,
                Err(e) => {
                    return ToolExecutionResult::tool_error(format!(
                        "Failed to decode base64 content from session file {session_path}: {e}"
                    ));
                }
            }
        } else {
            content_str.as_bytes().to_vec()
        };

        let config = ContainerSandboxConfig::default();
        let client = docker_client(&config);

        let (dir, filename) = match container_path.rsplit_once('/') {
            Some((d, f)) if !d.is_empty() => (d.to_string(), f.to_string()),
            _ => (
                "/".to_string(),
                container_path.trim_start_matches('/').to_string(),
            ),
        };

        if filename.is_empty() {
            return ToolExecutionResult::tool_error(
                "Invalid container_path: filename is empty (trailing slash?)",
            );
        }

        match client
            .put_archive(&state.container_id, &dir, &filename, &bytes)
            .await
        {
            Ok(()) => ToolExecutionResult::success(format!(
                "Uploaded {session_path} → {container_path} ({} bytes)",
                bytes.len()
            )),
            Err(e) => ToolExecutionResult::tool_error(format!("Upload failed: {e}")),
        }
    }

    fn requires_context(&self) -> bool {
        true
    }
}

// ============================================================================
// sandbox_download
// ============================================================================

pub struct SandboxDownloadTool;

#[async_trait]
impl Tool for SandboxDownloadTool {
    fn name(&self) -> &str {
        "sandbox_download"
    }

    fn description(&self) -> &str {
        "Download a file from the container sandbox to session storage."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "container_path": {
                    "type": "string",
                    "description": "Absolute path of the file inside the container"
                },
                "session_path": {
                    "type": "string",
                    "description": "Destination path in session storage"
                }
            },
            "required": ["container_path", "session_path"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        ToolExecutionResult::tool_error("Tool requires context.")
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let container_path = match required_str(&arguments, "container_path") {
            Ok(p) => p,
            Err(e) => return e,
        };
        let session_path = match required_str(&arguments, "session_path") {
            Ok(p) => p,
            Err(e) => return e,
        };

        let state = match get_sandbox_state(context).await {
            Ok(s) => s,
            Err(e) => return e,
        };

        let file_store = match context.file_store.as_ref() {
            Some(fs) => fs,
            None => return ToolExecutionResult::tool_error("File store not available"),
        };

        let config = ContainerSandboxConfig::default();
        let client = docker_client(&config);

        let bytes = match client
            .get_archive(&state.container_id, &container_path)
            .await
        {
            Ok(b) => b,
            Err(e) => {
                return ToolExecutionResult::tool_error(format!("Failed to read file: {e}"));
            }
        };

        // Store as text if valid UTF-8, otherwise base64
        let (content, encoding) = match String::from_utf8(bytes.clone()) {
            Ok(text) => (text, "text"),
            Err(_) => (BASE64.encode(&bytes), "base64"),
        };

        match file_store
            .write_file(context.session_id, &session_path, &content, encoding)
            .await
        {
            Ok(_) => ToolExecutionResult::success(format!(
                "Downloaded {container_path} → {session_path} ({} bytes)",
                bytes.len()
            )),
            Err(e) => {
                ToolExecutionResult::tool_error(format!("Failed to save to session storage: {e}"))
            }
        }
    }

    fn requires_context(&self) -> bool {
        true
    }
}