vtcode-core 0.99.1

Core library for VT Code - a Rust-based terminal coding agent
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
//! Tool Orchestrator (from Codex)
//!
//! Central place for approvals + sandbox selection + retry semantics. Drives a
//! simple sequence for any ToolRuntime: approval → select sandbox → attempt →
//! retry without sandbox on denial (no re-approval thanks to caching).

use crate::tools::handlers::sandboxing::{
    ApprovalCtx, AskForApproval, ExecApprovalRequirement, ReviewDecision, SandboxAttempt,
    SandboxManager, SandboxOverride, SandboxType, ToolCtx, ToolError, ToolRuntime,
    canonical_sandbox_policy, default_exec_approval_requirement,
};
use crate::tools::handlers::tool_handler::TurnContext;

/// Tool orchestrator for coordinating execution (from Codex)
///
/// The orchestrator handles:
/// 1. Approval flow with caching
/// 2. Sandbox creation and selection
/// 3. Retry logic for sandbox escalation
pub struct ToolOrchestrator {
    sandbox: SandboxManager,
}

impl Default for ToolOrchestrator {
    fn default() -> Self {
        Self::new()
    }
}

impl ToolOrchestrator {
    pub fn new() -> Self {
        Self {
            sandbox: SandboxManager::new(),
        }
    }

    /// Run a tool with the orchestrator managing sandbox and retries (from Codex)
    ///
    /// Flow:
    /// 1. Check exec approval requirement
    /// 2. Request approval if needed
    /// 3. Select initial sandbox
    /// 4. First attempt
    /// 5. On sandbox denial, retry without sandbox (with approval if needed)
    pub async fn run<Req, Out, T>(
        &mut self,
        tool: &mut T,
        req: &Req,
        tool_ctx: &ToolCtx,
        turn_ctx: &TurnContext,
        approval_policy: AskForApproval,
    ) -> Result<Out, ToolError>
    where
        Req: Send + Sync,
        Out: Send + Sync,
        T: ToolRuntime<Req, Out>,
    {
        // 1) Determine approval requirement
        let mut already_approved = false;

        let requirement = tool.exec_approval_requirement(req).unwrap_or_else(|| {
            default_exec_approval_requirement(approval_policy, turn_ctx.sandbox_policy.get())
        });

        match &requirement {
            ExecApprovalRequirement::Skip { .. } => {
                // No approval needed, continue
                tracing::debug!("Skipping approval for tool: {}", tool_ctx.tool_name);
            }
            ExecApprovalRequirement::Forbidden { reason } => {
                return Err(ToolError::Rejected(reason.clone()));
            }
            ExecApprovalRequirement::NeedsApproval { reason, .. } => {
                // Request approval
                let approval_ctx = ApprovalCtx {
                    session: tool_ctx.session.as_ref(),
                    turn: tool_ctx.turn.as_ref(),
                    call_id: &tool_ctx.call_id,
                    retry_reason: reason.clone(),
                };

                let decision = tool.start_approval_async(req, approval_ctx).await;

                match decision {
                    ReviewDecision::Denied | ReviewDecision::Abort => {
                        return Err(ToolError::Rejected("rejected by user".to_string()));
                    }
                    ReviewDecision::Approved
                    | ReviewDecision::ApprovedExecpolicyAmendment { .. }
                    | ReviewDecision::ApprovedForSession => {
                        already_approved = true;
                    }
                }
            }
        }

        // 2) Select initial sandbox
        let canonical_policy = canonical_sandbox_policy(turn_ctx);
        let initial_sandbox = match tool.sandbox_mode_for_first_attempt(req) {
            SandboxOverride::BypassSandboxFirstAttempt => SandboxType::None,
            SandboxOverride::NoOverride => self
                .sandbox
                .select_initial_for_canonical(&canonical_policy, tool.sandbox_preference()),
        };

        // 3) First attempt
        let initial_attempt = SandboxAttempt {
            sandbox: initial_sandbox,
            policy: turn_ctx.sandbox_policy.get(),
            sandbox_cwd: &turn_ctx.cwd,
            codex_linux_sandbox_exe: turn_ctx.codex_linux_sandbox_exe.as_ref(),
        };

        match tool.run(req, &initial_attempt, tool_ctx).await {
            Ok(out) => Ok(out),
            Err(ToolError::SandboxDenied(output)) => {
                // 4) Handle sandbox denial
                if !tool.escalate_on_failure() {
                    return Err(ToolError::SandboxDenied(output));
                }

                // Under `Never` or `OnRequest`, do not retry without sandbox
                if !tool.wants_no_sandbox_approval(approval_policy) {
                    return Err(ToolError::SandboxDenied(build_denial_reason_from_output(
                        Some(&output),
                    )));
                }

                // Ask for approval before retrying without sandbox
                if !tool.should_bypass_approval(approval_policy, already_approved) {
                    let reason_msg = build_denial_reason_from_output(Some(&output));
                    let approval_ctx = ApprovalCtx {
                        session: tool_ctx.session.as_ref(),
                        turn: tool_ctx.turn.as_ref(),
                        call_id: &tool_ctx.call_id,
                        retry_reason: Some(reason_msg),
                    };

                    let decision = tool.start_approval_async(req, approval_ctx).await;

                    match decision {
                        ReviewDecision::Denied | ReviewDecision::Abort => {
                            return Err(ToolError::Rejected("rejected by user".to_string()));
                        }
                        ReviewDecision::Approved
                        | ReviewDecision::ApprovedExecpolicyAmendment { .. }
                        | ReviewDecision::ApprovedForSession => {}
                    }
                }

                // 5) Second attempt without sandbox
                let escalated_attempt = SandboxAttempt {
                    sandbox: SandboxType::None,
                    policy: turn_ctx.sandbox_policy.get(),
                    sandbox_cwd: &turn_ctx.cwd,
                    codex_linux_sandbox_exe: None,
                };

                tool.run(req, &escalated_attempt, tool_ctx).await
            }
            Err(other) => Err(other),
        }
    }
}

/// Build a denial reason message from output (from Codex)
fn build_denial_reason_from_output(output: Option<&str>) -> String {
    match output {
        Some(o) if !o.is_empty() => format!("Sandbox denied with output: {}", truncate_output(o)),
        _ => "Sandbox denied execution".to_string(),
    }
}

/// Truncate output for display
fn truncate_output(output: &str) -> &str {
    const MAX_LEN: usize = 500;
    if output.len() > MAX_LEN {
        &output[..MAX_LEN]
    } else {
        output
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::path::PathBuf;
    use std::sync::Arc;

    use crate::tools::handlers::sandboxing::{
        Approvable, BoxFuture, NetworkAccess, SandboxMode, SandboxPolicy, Sandboxable,
        SandboxablePreference,
    };
    use crate::tools::handlers::tool_handler::{
        ApprovalPolicy, Constrained, ShellEnvironmentPolicy, ToolEvent, ToolSession,
    };

    struct TestSession {
        cwd: PathBuf,
    }

    impl TestSession {
        fn new(cwd: PathBuf) -> Self {
            Self { cwd }
        }
    }

    #[async_trait]
    impl ToolSession for TestSession {
        fn cwd(&self) -> &PathBuf {
            &self.cwd
        }

        fn workspace_root(&self) -> &PathBuf {
            &self.cwd
        }

        async fn record_warning(&self, _message: String) {}

        fn user_shell(&self) -> &str {
            "/bin/zsh"
        }

        async fn send_event(&self, _event: ToolEvent) {}
    }

    struct TestRuntime {
        calls: usize,
        escalate: bool,
    }

    impl TestRuntime {
        fn new(escalate: bool) -> Self {
            Self { calls: 0, escalate }
        }
    }

    impl Sandboxable for TestRuntime {
        fn sandbox_preference(&self) -> SandboxablePreference {
            SandboxablePreference::Auto
        }

        fn escalate_on_failure(&self) -> bool {
            self.escalate
        }
    }

    impl Approvable<()> for TestRuntime {
        type ApprovalKey = String;

        fn approval_key(&self, _req: &()) -> Self::ApprovalKey {
            "test-runtime".to_string()
        }

        fn start_approval_async<'a>(
            &'a mut self,
            _req: &'a (),
            _ctx: ApprovalCtx<'a>,
        ) -> BoxFuture<'a, ReviewDecision> {
            Box::pin(async { ReviewDecision::Approved })
        }
    }

    #[async_trait]
    impl ToolRuntime<(), &'static str> for TestRuntime {
        async fn run(
            &mut self,
            _req: &(),
            attempt: &SandboxAttempt<'_>,
            _ctx: &ToolCtx,
        ) -> Result<&'static str, ToolError> {
            self.calls += 1;
            if attempt.sandbox == SandboxType::None {
                Ok("ok")
            } else {
                Err(ToolError::SandboxDenied("denied".to_string()))
            }
        }
    }

    struct FirstAttemptProbeRuntime {
        first_sandbox: Option<SandboxType>,
        preference: SandboxablePreference,
    }

    impl FirstAttemptProbeRuntime {
        fn new(preference: SandboxablePreference) -> Self {
            Self {
                first_sandbox: None,
                preference,
            }
        }
    }

    impl Sandboxable for FirstAttemptProbeRuntime {
        fn sandbox_preference(&self) -> SandboxablePreference {
            self.preference
        }
    }

    impl Approvable<()> for FirstAttemptProbeRuntime {
        type ApprovalKey = String;

        fn approval_key(&self, _req: &()) -> Self::ApprovalKey {
            "probe-runtime".to_string()
        }

        fn start_approval_async<'a>(
            &'a mut self,
            _req: &'a (),
            _ctx: ApprovalCtx<'a>,
        ) -> BoxFuture<'a, ReviewDecision> {
            Box::pin(async { ReviewDecision::Approved })
        }
    }

    #[async_trait]
    impl ToolRuntime<(), &'static str> for FirstAttemptProbeRuntime {
        async fn run(
            &mut self,
            _req: &(),
            attempt: &SandboxAttempt<'_>,
            _ctx: &ToolCtx,
        ) -> Result<&'static str, ToolError> {
            if self.first_sandbox.is_none() {
                self.first_sandbox = Some(attempt.sandbox);
            }
            Ok("ok")
        }
    }

    fn test_turn_context(cwd: PathBuf, sandbox_policy: SandboxPolicy) -> TurnContext {
        TurnContext {
            cwd,
            turn_id: "turn-1".to_string(),
            sub_id: None,
            shell_environment_policy: ShellEnvironmentPolicy::Inherit,
            approval_policy: Constrained::allow_any(ApprovalPolicy::Never),
            codex_linux_sandbox_exe: None,
            sandbox_policy: Constrained::allow_any(sandbox_policy),
        }
    }

    fn test_tool_ctx(turn: Arc<TurnContext>, session: Arc<TestSession>) -> ToolCtx {
        ToolCtx {
            session,
            turn,
            call_id: "call-1".to_string(),
            tool_name: "test".to_string(),
        }
    }

    #[test]
    fn test_build_denial_reason_empty() {
        assert_eq!(
            build_denial_reason_from_output(None),
            "Sandbox denied execution"
        );
        assert_eq!(
            build_denial_reason_from_output(Some("")),
            "Sandbox denied execution"
        );
    }

    #[test]
    fn test_build_denial_reason_with_output() {
        let reason = build_denial_reason_from_output(Some("permission denied"));
        assert!(reason.contains("permission denied"));
    }

    #[test]
    fn test_truncate_output() {
        let short = "hello";
        assert_eq!(truncate_output(short), short);

        let long = "a".repeat(1000);
        assert_eq!(truncate_output(&long).len(), 500);
    }

    #[tokio::test]
    async fn orchestrator_escalates_when_runtime_allows_it() {
        let cwd = PathBuf::from(".");
        let session = Arc::new(TestSession::new(cwd.clone()));
        let turn = Arc::new(test_turn_context(cwd, SandboxPolicy::default()));
        let tool_ctx = test_tool_ctx(turn.clone(), session);
        let mut runtime = TestRuntime::new(true);
        let mut orchestrator = ToolOrchestrator::new();

        let out = orchestrator
            .run(
                &mut runtime,
                &(),
                &tool_ctx,
                turn.as_ref(),
                AskForApproval::OnFailure,
            )
            .await
            .expect("expected escalated retry to succeed");

        assert_eq!(out, "ok");
        assert_eq!(runtime.calls, 2);
    }

    #[tokio::test]
    async fn orchestrator_stops_on_sandbox_denial_when_runtime_disables_retry() {
        let cwd = PathBuf::from(".");
        let session = Arc::new(TestSession::new(cwd.clone()));
        let turn = Arc::new(test_turn_context(cwd, SandboxPolicy::default()));
        let tool_ctx = test_tool_ctx(turn.clone(), session);
        let mut runtime = TestRuntime::new(false);
        let mut orchestrator = ToolOrchestrator::new();

        let err = orchestrator
            .run(
                &mut runtime,
                &(),
                &tool_ctx,
                turn.as_ref(),
                AskForApproval::OnFailure,
            )
            .await
            .expect_err("expected sandbox denial without retry");

        assert!(matches!(err, ToolError::SandboxDenied(_)));
        assert_eq!(runtime.calls, 1);
    }

    #[tokio::test]
    async fn canonical_full_access_turn_starts_without_sandbox() {
        let cwd = PathBuf::from(".");
        let session = Arc::new(TestSession::new(cwd.clone()));
        let turn = Arc::new(test_turn_context(
            cwd,
            SandboxPolicy {
                mode: SandboxMode::DangerFullAccess,
                network_access: NetworkAccess::Full,
            },
        ));
        let tool_ctx = test_tool_ctx(turn.clone(), session);
        let mut runtime = FirstAttemptProbeRuntime::new(SandboxablePreference::Auto);
        let mut orchestrator = ToolOrchestrator::new();

        orchestrator
            .run(
                &mut runtime,
                &(),
                &tool_ctx,
                turn.as_ref(),
                AskForApproval::Never,
            )
            .await
            .expect("expected run to succeed");

        assert_eq!(runtime.first_sandbox, Some(SandboxType::None));
    }
}