lha 1.0.2

Long-Horizon Agent command-line package that installs the lha binary.
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
use crate::product::protocol::models::ShellCommandToolCallParams;
use crate::product::protocol::models::ShellToolCallParams;
use async_trait::async_trait;
use std::sync::Arc;

use crate::product::agent::codex::TurnContext;
use crate::product::agent::exec::ExecParams;
use crate::product::agent::exec_env::create_env;
use crate::product::agent::exec_policy::ExecApprovalRequest;
use crate::product::agent::function_tool::FunctionCallError;
use crate::product::agent::is_safe_command::is_known_safe_command;
use crate::product::agent::protocol::ExecCommandSource;
use crate::product::agent::shell::Shell;
use crate::product::agent::tools::context::ToolInvocation;
use crate::product::agent::tools::context::ToolOutput;
use crate::product::agent::tools::context::ToolPayload;
use crate::product::agent::tools::events::ToolEmitter;
use crate::product::agent::tools::events::ToolEventCtx;
use crate::product::agent::tools::handlers::apply_patch::intercept_apply_patch;
use crate::product::agent::tools::handlers::parse_arguments;
use crate::product::agent::tools::orchestrator::ToolOrchestrator;
use crate::product::agent::tools::registry::ToolHandler;
use crate::product::agent::tools::registry::ToolKind;
use crate::product::agent::tools::runtimes::shell::ShellRequest;
use crate::product::agent::tools::runtimes::shell::ShellRuntime;
use crate::product::agent::tools::sandboxing::ToolCtx;

pub struct ShellHandler;

pub struct ShellCommandHandler;

struct RunExecLikeArgs {
    tool_name: String,
    exec_params: ExecParams,
    prefix_rule: Option<Vec<String>>,
    session: Arc<crate::product::agent::codex::Session>,
    turn: Arc<TurnContext>,
    tracker: crate::product::agent::tools::context::SharedTurnDiffTracker,
    call_id: String,
    freeform: bool,
}

impl ShellHandler {
    fn to_exec_params(params: &ShellToolCallParams, turn_context: &TurnContext) -> ExecParams {
        ExecParams {
            command: params.command.clone(),
            cwd: turn_context.resolve_path(params.workdir.clone()),
            expiration: params.timeout_ms.into(),
            env: create_env(&turn_context.shell_environment_policy),
            sandbox_permissions: params.sandbox_permissions.unwrap_or_default(),
            windows_sandbox_level: turn_context.windows_sandbox_level,
            justification: params.justification.clone(),
            arg0: None,
        }
    }
}

impl ShellCommandHandler {
    fn base_command(shell: &Shell, command: &str, login: Option<bool>) -> Vec<String> {
        let use_login_shell = login.unwrap_or(true);
        shell.derive_exec_args(command, use_login_shell)
    }

    fn to_exec_params(
        params: &ShellCommandToolCallParams,
        session: &crate::product::agent::codex::Session,
        turn_context: &TurnContext,
    ) -> ExecParams {
        let shell = session.user_shell();
        let command = Self::base_command(shell.as_ref(), &params.command, params.login);

        ExecParams {
            command,
            cwd: turn_context.resolve_path(params.workdir.clone()),
            expiration: params.timeout_ms.into(),
            env: create_env(&turn_context.shell_environment_policy),
            sandbox_permissions: params.sandbox_permissions.unwrap_or_default(),
            windows_sandbox_level: turn_context.windows_sandbox_level,
            justification: params.justification.clone(),
            arg0: None,
        }
    }
}

#[async_trait]
impl ToolHandler for ShellHandler {
    fn kind(&self) -> ToolKind {
        ToolKind::Function
    }

    fn matches_kind(&self, payload: &ToolPayload) -> bool {
        matches!(
            payload,
            ToolPayload::Function { .. } | ToolPayload::LocalShell { .. }
        )
    }

    async fn is_mutating(&self, invocation: &ToolInvocation) -> bool {
        match &invocation.payload {
            ToolPayload::Function { arguments } => {
                serde_json::from_str::<ShellToolCallParams>(arguments)
                    .map(|params| !is_known_safe_command(&params.command))
                    .unwrap_or(true)
            }
            ToolPayload::LocalShell { params } => !is_known_safe_command(&params.command),
            _ => true, // unknown payloads => assume mutating
        }
    }

    async fn handle(&self, invocation: ToolInvocation) -> Result<ToolOutput, FunctionCallError> {
        let ToolInvocation {
            session,
            turn,
            tracker,
            call_id,
            tool_name,
            payload,
        } = invocation;

        match payload {
            ToolPayload::Function { arguments } => {
                let params: ShellToolCallParams = parse_arguments(&arguments)?;
                validate_argv_command(&params.command)?;
                let prefix_rule = params.prefix_rule.clone();
                let exec_params = Self::to_exec_params(&params, turn.as_ref());
                Self::run_exec_like(RunExecLikeArgs {
                    tool_name: tool_name.clone(),
                    exec_params,
                    prefix_rule,
                    session,
                    turn,
                    tracker,
                    call_id,
                    freeform: false,
                })
                .await
            }
            ToolPayload::LocalShell { params } => {
                validate_argv_command(&params.command)?;
                let exec_params = Self::to_exec_params(&params, turn.as_ref());
                Self::run_exec_like(RunExecLikeArgs {
                    tool_name: tool_name.clone(),
                    exec_params,
                    prefix_rule: None,
                    session,
                    turn,
                    tracker,
                    call_id,
                    freeform: false,
                })
                .await
            }
            _ => Err(FunctionCallError::RespondToModel(format!(
                "unsupported payload for shell handler: {tool_name}"
            ))),
        }
    }
}

#[async_trait]
impl ToolHandler for ShellCommandHandler {
    fn kind(&self) -> ToolKind {
        ToolKind::Function
    }

    fn matches_kind(&self, payload: &ToolPayload) -> bool {
        matches!(payload, ToolPayload::Function { .. })
    }

    async fn is_mutating(&self, invocation: &ToolInvocation) -> bool {
        let ToolPayload::Function { arguments } = &invocation.payload else {
            return true;
        };

        serde_json::from_str::<ShellCommandToolCallParams>(arguments)
            .map(|params| {
                let shell = invocation.session.user_shell();
                let command = Self::base_command(shell.as_ref(), &params.command, params.login);
                !is_known_safe_command(&command)
            })
            .unwrap_or(true)
    }

    async fn handle(&self, invocation: ToolInvocation) -> Result<ToolOutput, FunctionCallError> {
        let ToolInvocation {
            session,
            turn,
            tracker,
            call_id,
            tool_name,
            payload,
        } = invocation;

        let ToolPayload::Function { arguments } = payload else {
            return Err(FunctionCallError::RespondToModel(format!(
                "unsupported payload for shell_command handler: {tool_name}"
            )));
        };

        let params: ShellCommandToolCallParams = parse_arguments(&arguments)?;
        validate_shell_command(&params.command)?;
        let prefix_rule = params.prefix_rule.clone();
        let exec_params = Self::to_exec_params(&params, session.as_ref(), turn.as_ref());
        ShellHandler::run_exec_like(RunExecLikeArgs {
            tool_name,
            exec_params,
            prefix_rule,
            session,
            turn,
            tracker,
            call_id,
            freeform: true,
        })
        .await
    }
}

fn validate_shell_command(command: &str) -> Result<(), FunctionCallError> {
    if command.trim().is_empty() {
        Err(FunctionCallError::RespondToModel(
            "command must be non-empty".to_string(),
        ))
    } else {
        Ok(())
    }
}

fn validate_argv_command(command: &[String]) -> Result<(), FunctionCallError> {
    if command.first().is_none_or(String::is_empty) {
        Err(FunctionCallError::RespondToModel(
            "command must be non-empty".to_string(),
        ))
    } else {
        Ok(())
    }
}

impl ShellHandler {
    async fn run_exec_like(args: RunExecLikeArgs) -> Result<ToolOutput, FunctionCallError> {
        let RunExecLikeArgs {
            tool_name,
            exec_params,
            prefix_rule,
            session,
            turn,
            tracker,
            call_id,
            freeform,
        } = args;

        let features = session.features();
        let request_rule_enabled =
            features.enabled(crate::product::agent::features::Feature::RequestRule);
        let prefix_rule = if request_rule_enabled {
            prefix_rule
        } else {
            None
        };

        let mut exec_params = exec_params;
        let dependency_env = session.dependency_env().await;
        if !dependency_env.is_empty() {
            exec_params.env.extend(dependency_env);
        }

        // Approval policy guard for explicit escalation in non-OnRequest modes.
        if exec_params
            .sandbox_permissions
            .requires_escalated_permissions()
            && !matches!(
                turn.approval_policy,
                crate::product::protocol::protocol::AskForApproval::OnRequest
            )
        {
            let approval_policy = turn.approval_policy;
            return Err(FunctionCallError::RespondToModel(format!(
                "approval policy is {approval_policy:?}; reject command — you should not ask for escalated permissions if the approval policy is {approval_policy:?}"
            )));
        }

        // Intercept apply_patch if present.
        if let Some(output) = intercept_apply_patch(
            &exec_params.command,
            &exec_params.cwd,
            exec_params.expiration.timeout_ms(),
            session.as_ref(),
            turn.as_ref(),
            Some(&tracker),
            &call_id,
            tool_name.as_str(),
        )
        .await?
        {
            return Ok(output);
        }

        let source = ExecCommandSource::Agent;
        let emitter = ToolEmitter::shell(
            exec_params.command.clone(),
            exec_params.cwd.clone(),
            source,
            freeform,
        );
        let event_ctx = ToolEventCtx::new(session.as_ref(), turn.as_ref(), &call_id, None);
        emitter.begin(event_ctx).await;

        let exec_approval_requirement = session
            .services
            .exec_policy
            .create_exec_approval_requirement_for_command(ExecApprovalRequest {
                features: &features,
                command: &exec_params.command,
                approval_policy: turn.approval_policy,
                sandbox_policy: &turn.sandbox_policy,
                sandbox_permissions: exec_params.sandbox_permissions,
                prefix_rule,
            })
            .await;

        let req = ShellRequest {
            command: exec_params.command.clone(),
            cwd: exec_params.cwd.clone(),
            timeout_ms: exec_params.expiration.timeout_ms(),
            env: exec_params.env.clone(),
            sandbox_permissions: exec_params.sandbox_permissions,
            justification: exec_params.justification.clone(),
            exec_approval_requirement,
        };
        let mut orchestrator = ToolOrchestrator::new();
        let mut runtime = ShellRuntime::new();
        let tool_ctx = ToolCtx {
            session: session.as_ref(),
            turn: turn.as_ref(),
            call_id: call_id.clone(),
            tool_name,
        };
        let out = orchestrator
            .run(&mut runtime, &req, &tool_ctx, &turn, turn.approval_policy)
            .await;
        let event_ctx = ToolEventCtx::new(session.as_ref(), turn.as_ref(), &call_id, None);
        let content = emitter.finish(event_ctx, out).await?;
        Ok(ToolOutput::Function {
            content,
            content_items: None,
            success: Some(true),
        })
    }
}

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

    use crate::product::protocol::models::ShellCommandToolCallParams;
    use crate::product::protocol::models::ShellToolCallParams;
    use pretty_assertions::assert_eq;

    use super::validate_argv_command;
    use super::validate_shell_command;
    use crate::product::agent::codex::make_session_and_context;
    use crate::product::agent::exec_env::create_env;
    use crate::product::agent::function_tool::FunctionCallError;
    use crate::product::agent::is_safe_command::is_known_safe_command;
    use crate::product::agent::powershell::try_find_powershell_executable_blocking;
    use crate::product::agent::powershell::try_find_pwsh_executable_blocking;
    use crate::product::agent::sandboxing::SandboxPermissions;
    use crate::product::agent::shell::Shell;
    use crate::product::agent::shell::ShellType;
    use crate::product::agent::shell_snapshot::ShellSnapshot;
    use crate::product::agent::tools::handlers::ShellCommandHandler;
    use tokio::sync::watch;

    fn shell_command_params(command: &str) -> ShellCommandToolCallParams {
        ShellCommandToolCallParams {
            command: command.to_string(),
            workdir: None,
            login: None,
            timeout_ms: None,
            sandbox_permissions: None,
            prefix_rule: None,
            justification: None,
        }
    }

    fn shell_params(command: Vec<String>) -> ShellToolCallParams {
        ShellToolCallParams {
            command,
            workdir: None,
            timeout_ms: None,
            sandbox_permissions: None,
            prefix_rule: None,
            justification: None,
        }
    }

    fn non_empty_command_error() -> FunctionCallError {
        FunctionCallError::RespondToModel("command must be non-empty".to_string())
    }

    #[test]
    fn validate_shell_command_rejects_empty_command() {
        let params = shell_command_params("");

        assert_eq!(
            validate_shell_command(&params.command),
            Err(non_empty_command_error())
        );
    }

    #[test]
    fn validate_shell_command_rejects_whitespace_command() {
        let params = shell_command_params("   \n\t");

        assert_eq!(
            validate_shell_command(&params.command),
            Err(non_empty_command_error())
        );
    }

    #[test]
    fn validate_argv_command_rejects_empty_command() {
        let params = shell_params(Vec::new());

        assert_eq!(
            validate_argv_command(&params.command),
            Err(non_empty_command_error())
        );
    }

    #[test]
    fn validate_argv_command_rejects_empty_program_name() {
        let params = shell_params(vec!["".to_string()]);

        assert_eq!(
            validate_argv_command(&params.command),
            Err(non_empty_command_error())
        );

        let params = shell_params(vec!["".to_string(), "arg".to_string()]);

        assert_eq!(
            validate_argv_command(&params.command),
            Err(non_empty_command_error())
        );
    }

    #[test]
    fn validate_argv_command_accepts_empty_arguments() {
        let params = shell_params(vec!["printf".to_string(), "%s".to_string(), "".to_string()]);

        assert_eq!(validate_argv_command(&params.command), Ok(()));

        let params = shell_params(vec!["test".to_string(), "-z".to_string(), "".to_string()]);

        assert_eq!(validate_argv_command(&params.command), Ok(()));
    }

    #[test]
    fn validate_commands_accept_non_empty_commands() {
        let shell_command = shell_command_params("echo hello");
        let argv_command = shell_params(vec!["echo".to_string(), "hello".to_string()]);

        assert_eq!(validate_shell_command(&shell_command.command), Ok(()));
        assert_eq!(validate_argv_command(&argv_command.command), Ok(()));
    }

    /// The logic for is_known_safe_command() has heuristics for known shells,
    /// so we must ensure the commands generated by [ShellCommandHandler] can be
    /// recognized as safe if the `command` is safe.
    #[test]
    fn commands_generated_by_shell_command_handler_can_be_matched_by_is_known_safe_command() {
        let bash_shell = Shell {
            shell_type: ShellType::Bash,
            shell_path: PathBuf::from("/bin/bash"),
            shell_snapshot: crate::product::agent::shell::empty_shell_snapshot_receiver(),
        };
        assert_safe(&bash_shell, "ls -la");

        let zsh_shell = Shell {
            shell_type: ShellType::Zsh,
            shell_path: PathBuf::from("/bin/zsh"),
            shell_snapshot: crate::product::agent::shell::empty_shell_snapshot_receiver(),
        };
        assert_safe(&zsh_shell, "ls -la");

        if let Some(path) = try_find_powershell_executable_blocking() {
            let powershell = Shell {
                shell_type: ShellType::PowerShell,
                shell_path: path.to_path_buf(),
                shell_snapshot: crate::product::agent::shell::empty_shell_snapshot_receiver(),
            };
            assert_safe(&powershell, "ls -Name");
        }

        if let Some(path) = try_find_pwsh_executable_blocking() {
            let pwsh = Shell {
                shell_type: ShellType::PowerShell,
                shell_path: path.to_path_buf(),
                shell_snapshot: crate::product::agent::shell::empty_shell_snapshot_receiver(),
            };
            assert_safe(&pwsh, "ls -Name");
        }
    }

    fn assert_safe(shell: &Shell, command: &str) {
        assert!(is_known_safe_command(
            &shell.derive_exec_args(command, /* use_login_shell */ true)
        ));
        assert!(is_known_safe_command(
            &shell.derive_exec_args(command, /* use_login_shell */ false)
        ));
    }

    #[tokio::test]
    async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_context() {
        let (session, turn_context) = make_session_and_context().await;

        let command = "echo hello".to_string();
        let workdir = Some("subdir".to_string());
        let login = None;
        let timeout_ms = Some(1234);
        let sandbox_permissions = SandboxPermissions::RequireEscalated;
        let justification = Some("because tests".to_string());

        let expected_command = session.user_shell().derive_exec_args(&command, true);
        let expected_cwd = turn_context.resolve_path(workdir.clone());
        let expected_env = create_env(&turn_context.shell_environment_policy);

        let params = ShellCommandToolCallParams {
            command,
            workdir,
            login,
            timeout_ms,
            sandbox_permissions: Some(sandbox_permissions),
            prefix_rule: None,
            justification: justification.clone(),
        };

        let exec_params = ShellCommandHandler::to_exec_params(&params, &session, &turn_context);

        // ExecParams cannot derive Eq due to the CancellationToken field, so we manually compare the fields.
        assert_eq!(exec_params.command, expected_command);
        assert_eq!(exec_params.cwd, expected_cwd);
        assert_eq!(exec_params.env, expected_env);
        assert_eq!(exec_params.expiration.timeout_ms(), timeout_ms);
        assert_eq!(exec_params.sandbox_permissions, sandbox_permissions);
        assert_eq!(exec_params.justification, justification);
        assert_eq!(exec_params.arg0, None);
    }

    #[test]
    fn shell_command_handler_respects_explicit_login_flag() {
        let (_tx, shell_snapshot) = watch::channel(Some(Arc::new(ShellSnapshot {
            path: PathBuf::from("/tmp/snapshot.sh"),
        })));
        let shell = Shell {
            shell_type: ShellType::Bash,
            shell_path: PathBuf::from("/bin/bash"),
            shell_snapshot,
        };

        let login_command =
            ShellCommandHandler::base_command(&shell, "echo login shell", Some(true));
        assert_eq!(
            login_command,
            shell.derive_exec_args("echo login shell", true)
        );

        let non_login_command =
            ShellCommandHandler::base_command(&shell, "echo non login shell", Some(false));
        assert_eq!(
            non_login_command,
            shell.derive_exec_args("echo non login shell", false)
        );
    }
}