symbi-runtime 1.4.0

Agent Runtime System for the Symbi 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
//! Codex CLI adapter for the CLI executor
//!
//! Implements `AiCliAdapter` for OpenAI's Codex CLI tool,
//! using `exec --full-auto --json <prompt>` for non-interactive operation.

use std::collections::HashMap;
use std::path::PathBuf;

use async_trait::async_trait;
use serde::{Deserialize, Serialize};

use crate::cli_executor::adapter::{AiCliAdapter, CodeGenRequest, CodeGenResult};
use crate::cli_executor::executor::StdinStrategy;
use crate::sandbox::ExecutionResult;

/// Approval mode for Codex CLI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum CodexApprovalMode {
    /// Automatically apply all changes without confirmation.
    FullAuto,
    /// Suggest changes but don't apply automatically.
    Suggest,
}

impl Default for CodexApprovalMode {
    fn default() -> Self {
        Self::FullAuto
    }
}

/// Adapter for OpenAI's Codex CLI tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodexAdapter {
    /// Path or name of the Codex executable.
    pub executable_path: String,
    /// Model to use (e.g. "o4-mini", "o3").
    pub model: Option<String>,
    /// Approval mode (FullAuto or Suggest).
    pub approval_mode: CodexApprovalMode,
    /// Additional CLI arguments passed through to Codex.
    pub extra_args: Vec<String>,
}

impl Default for CodexAdapter {
    fn default() -> Self {
        Self {
            executable_path: "codex".to_string(),
            model: None,
            approval_mode: CodexApprovalMode::FullAuto,
            extra_args: Vec::new(),
        }
    }
}

#[async_trait]
impl AiCliAdapter for CodexAdapter {
    fn name(&self) -> &str {
        "codex"
    }

    fn executable(&self) -> &str {
        &self.executable_path
    }

    fn build_args(&self, request: &CodeGenRequest) -> Vec<String> {
        let mut args = vec!["exec".to_string()];

        match self.approval_mode {
            CodexApprovalMode::FullAuto => args.push("--full-auto".to_string()),
            CodexApprovalMode::Suggest => args.push("--suggest".to_string()),
        }

        args.push("--json".to_string());

        // Request-level model takes precedence over adapter default
        let model = request.model.as_ref().or(self.model.as_ref());
        if let Some(m) = model {
            args.push("--model".to_string());
            args.push(m.clone());
        }

        // Append extra args
        args.extend(self.extra_args.iter().cloned());

        // The prompt is the final positional argument
        args.push(request.prompt.clone());

        args
    }

    fn non_interactive_env(&self) -> HashMap<String, String> {
        // Codex `exec` subcommand is non-interactive;
        // base executor already sets CI=true etc.
        HashMap::new()
    }

    fn stdin_strategy(&self) -> StdinStrategy {
        // `exec` subcommand is non-interactive
        StdinStrategy::CloseImmediately
    }

    fn parse_output(&self, _request: &CodeGenRequest, result: ExecutionResult) -> CodeGenResult {
        // Codex --json emits newline-delimited JSON events.
        // Collect all events into a JSON array; look for file write events.
        let mut events: Vec<serde_json::Value> = Vec::new();
        let mut files_modified: Vec<PathBuf> = Vec::new();

        for line in result.stdout.lines() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            if let Ok(event) = serde_json::from_str::<serde_json::Value>(line) {
                // Look for file write events to populate files_modified
                if let Some(path) = extract_file_path(&event) {
                    if !files_modified.contains(&path) {
                        files_modified.push(path);
                    }
                }
                events.push(event);
            }
        }

        let parsed_output = if events.is_empty() {
            None
        } else {
            Some(serde_json::Value::Array(events))
        };

        let success = result.success;

        CodeGenResult {
            success,
            execution: result,
            parsed_output,
            files_modified,
            adapter_name: self.name().to_string(),
        }
    }

    async fn health_check(&self) -> Result<(), anyhow::Error> {
        let output = tokio::process::Command::new(&self.executable_path)
            .arg("--version")
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .await
            .map_err(|e| anyhow::anyhow!("Codex not found at '{}': {}", self.executable_path, e))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!(
                "Codex health check failed (exit {}): {}",
                output.status.code().unwrap_or(-1),
                stderr
            );
        }

        Ok(())
    }
}

/// Extract a file path from a Codex JSON event.
///
/// Codex events may contain file paths in several forms:
/// - `{"type": "file_write", "path": "..."}`
/// - `{"type": "patch", "path": "..."}`
/// - `{"path": "...", "action": "write"}`
fn extract_file_path(event: &serde_json::Value) -> Option<PathBuf> {
    let path_str = event.get("path").and_then(|v| v.as_str())?;

    let event_type = event.get("type").and_then(|v| v.as_str()).unwrap_or("");
    let action = event.get("action").and_then(|v| v.as_str()).unwrap_or("");

    if matches!(event_type, "file_write" | "patch" | "write")
        || matches!(action, "write" | "patch" | "create")
    {
        Some(PathBuf::from(path_str))
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_request() -> CodeGenRequest {
        CodeGenRequest {
            prompt: "Fix the bug in main.rs".to_string(),
            working_dir: PathBuf::from("/tmp/project"),
            target_files: vec![PathBuf::from("src/main.rs")],
            system_context: None,
            model: None,
            options: HashMap::new(),
        }
    }

    #[test]
    fn test_build_args_basic() {
        let adapter = CodexAdapter::default();
        let request = sample_request();
        let args = adapter.build_args(&request);

        assert_eq!(args[0], "exec");
        assert_eq!(args[1], "--full-auto");
        assert_eq!(args[2], "--json");
        assert_eq!(*args.last().unwrap(), "Fix the bug in main.rs");
    }

    #[test]
    fn test_build_args_suggest_mode() {
        let adapter = CodexAdapter {
            approval_mode: CodexApprovalMode::Suggest,
            ..Default::default()
        };
        let request = sample_request();
        let args = adapter.build_args(&request);

        assert_eq!(args[0], "exec");
        assert_eq!(args[1], "--suggest");
        assert!(!args.contains(&"--full-auto".to_string()));
    }

    #[test]
    fn test_build_args_model_override_from_request() {
        let adapter = CodexAdapter {
            model: Some("default-model".to_string()),
            ..Default::default()
        };
        let mut request = sample_request();
        request.model = Some("request-model".to_string());
        let args = adapter.build_args(&request);

        let idx = args.iter().position(|a| a == "--model").unwrap();
        assert_eq!(args[idx + 1], "request-model");
    }

    #[test]
    fn test_build_args_model_from_adapter() {
        let adapter = CodexAdapter {
            model: Some("adapter-model".to_string()),
            ..Default::default()
        };
        let request = sample_request();
        let args = adapter.build_args(&request);

        let idx = args.iter().position(|a| a == "--model").unwrap();
        assert_eq!(args[idx + 1], "adapter-model");
    }

    #[test]
    fn test_build_args_with_extra_args() {
        let adapter = CodexAdapter {
            extra_args: vec!["--verbose".to_string()],
            ..Default::default()
        };
        let request = sample_request();
        let args = adapter.build_args(&request);

        assert!(args.contains(&"--verbose".to_string()));
    }

    #[test]
    fn test_parse_output_valid_ndjson() {
        let adapter = CodexAdapter::default();
        let request = sample_request();

        let stdout = [
            r#"{"type":"file_write","path":"src/main.rs","content":"fn main() {}"}"#,
            r#"{"type":"message","text":"Done!"}"#,
            r#"{"type":"patch","path":"src/lib.rs","diff":"..."}"#,
        ]
        .join("\n");

        let result = ExecutionResult {
            exit_code: 0,
            stdout,
            stderr: String::new(),
            execution_time_ms: 3000,
            success: true,
            stdout_truncated: false,
            stderr_truncated: false,
        };

        let codegen = adapter.parse_output(&request, result);

        assert!(codegen.success);
        assert!(codegen.parsed_output.is_some());
        let events = codegen.parsed_output.unwrap();
        assert_eq!(events.as_array().unwrap().len(), 3);
        assert_eq!(codegen.files_modified.len(), 2);
        assert_eq!(codegen.files_modified[0], PathBuf::from("src/main.rs"));
        assert_eq!(codegen.files_modified[1], PathBuf::from("src/lib.rs"));
        assert_eq!(codegen.adapter_name, "codex");
    }

    #[test]
    fn test_parse_output_non_json() {
        let adapter = CodexAdapter::default();
        let request = sample_request();

        let result = ExecutionResult {
            exit_code: 0,
            stdout: "Not valid JSON output from codex\nJust plain text".to_string(),
            stderr: String::new(),
            execution_time_ms: 500,
            success: true,
            stdout_truncated: false,
            stderr_truncated: false,
        };

        let codegen = adapter.parse_output(&request, result);

        // Should degrade gracefully
        assert!(codegen.success);
        assert!(codegen.parsed_output.is_none());
        assert!(codegen.files_modified.is_empty());
    }

    #[test]
    fn test_parse_output_empty() {
        let adapter = CodexAdapter::default();
        let request = sample_request();

        let result = ExecutionResult {
            exit_code: 0,
            stdout: String::new(),
            stderr: String::new(),
            execution_time_ms: 100,
            success: true,
            stdout_truncated: false,
            stderr_truncated: false,
        };

        let codegen = adapter.parse_output(&request, result);

        assert!(codegen.success);
        assert!(codegen.parsed_output.is_none());
        assert!(codegen.files_modified.is_empty());
    }

    #[test]
    fn test_parse_output_failure() {
        let adapter = CodexAdapter::default();
        let request = sample_request();

        let result = ExecutionResult {
            exit_code: 1,
            stdout: String::new(),
            stderr: "Error: something went wrong".to_string(),
            execution_time_ms: 200,
            success: false,
            stdout_truncated: false,
            stderr_truncated: false,
        };

        let codegen = adapter.parse_output(&request, result);
        assert!(!codegen.success);
    }

    #[test]
    fn test_parse_output_deduplicates_files() {
        let adapter = CodexAdapter::default();
        let request = sample_request();

        let stdout = [
            r#"{"type":"file_write","path":"src/main.rs","content":"v1"}"#,
            r#"{"type":"file_write","path":"src/main.rs","content":"v2"}"#,
        ]
        .join("\n");

        let result = ExecutionResult {
            exit_code: 0,
            stdout,
            stderr: String::new(),
            execution_time_ms: 1000,
            success: true,
            stdout_truncated: false,
            stderr_truncated: false,
        };

        let codegen = adapter.parse_output(&request, result);
        assert_eq!(codegen.files_modified.len(), 1);
    }

    #[test]
    fn test_stdin_strategy_is_close_immediately() {
        let adapter = CodexAdapter::default();
        assert!(matches!(
            adapter.stdin_strategy(),
            StdinStrategy::CloseImmediately
        ));
    }

    #[test]
    fn test_non_interactive_env() {
        let adapter = CodexAdapter::default();
        let env = adapter.non_interactive_env();
        // Codex doesn't need extra env vars beyond base executor defaults
        assert!(env.is_empty());
    }

    #[tokio::test]
    #[ignore] // Requires Codex to be installed
    async fn test_health_check() {
        let adapter = CodexAdapter::default();
        let result = adapter.health_check().await;
        let _ = result;
    }
}