Skip to main content

rinne_workers/adapters/
codex.rs

1//! Codex CLI adapter (`CONTEXT.md` §16, `plan.md` Phase 3).
2//!
3//! Drives `codex exec --json`, which honors the user's ChatGPT login or API key.
4//! `--json` emits a JSONL event stream (when supported); we parse terminal
5//! agent messages into the result and map progress events for the Stage UI.
6//! Falls back to plain stdout when the CLI does not speak JSONL.
7
8use std::path::Path;
9use std::time::Duration;
10
11use rinne_core::worker::{
12    AuthMode, Capability, LatencyProfile, McpServerSpec, QuotaModel, Transport, Usage,
13    WorkerDescriptor, WorkerEvent, WorkerFamily,
14};
15use rinne_core::Result;
16
17use super::common::{approvals_are_auto, HarnessAdapter, ParsedHarness, Provision};
18use super::mcp_util;
19use crate::transport::subprocess::SubprocessOutput;
20
21pub fn worker() -> HarnessAdapter {
22    HarnessAdapter {
23        descriptor: descriptor(),
24        program: "codex".to_string(),
25        build_args,
26        plan_args: Some(plan_args),
27        // Interactive Codex TUI (not `codex exec --json`).
28        interactive_args: Some(interactive_args),
29        parse,
30        line_mapper,
31        prompt_via_stdin: false,
32        default_timeout: Duration::from_secs(600),
33        provisioner: Some(provision),
34    }
35}
36
37fn descriptor() -> WorkerDescriptor {
38    WorkerDescriptor {
39        name: "codex".to_string(),
40        family: WorkerFamily::Harness,
41        capabilities: vec![
42            Capability::CodeEdit,
43            Capability::RepoAware,
44            Capability::Reasoning,
45            Capability::ToolRun,
46            Capability::Writing,
47            Capability::CodeReview,
48        ],
49        auth_mode: AuthMode::Subscription,
50        quota: QuotaModel {
51            capacity: 150_000.0,
52            refill_per_minute: 15_000.0,
53        },
54        latency: LatencyProfile::Medium,
55        transport: Transport::SubprocessJson,
56        // Discover fills live ladder; cheap→strong defaults for ChatGPT/Codex.
57        // Keep this list to models a ChatGPT-account login can actually run —
58        // Codex rejects o-series with HTTP 400 there, which fails the node
59        // rather than degrading, so an unusable rung is worse than a short ladder.
60        models: vec!["gpt-5-mini".into(), "gpt-5".into(), "o4-mini".into()],
61    }
62}
63
64/// Work invocation: JSONL stream + non-interactive approval when the CLI allows.
65fn build_args(prompt: &str, model: Option<&str>) -> Vec<String> {
66    let mut args = vec![
67        "exec".into(),
68        // Structured event stream for Stage + parser (ignored by older CLIs →
69        // they still run; we fall back to raw parse).
70        "--json".into(),
71        // Auto-approve tool use for headless/PTY orchestration (harness power
72        // without blocking on interactive prompts).
73        "--full-auto".into(),
74    ];
75    if let Some(m) = model {
76        args.push("--model".into());
77        args.push(m.into());
78    }
79    args.push(prompt.into());
80    args
81}
82
83/// Lean planner path: plain exec without JSON flags (more robust for short plans).
84fn plan_args(prompt: &str, model: Option<&str>) -> Vec<String> {
85    let mut args = vec!["exec".into(), "--full-auto".into()];
86    if let Some(m) = model {
87        args.push("--model".into());
88        args.push(m.into());
89    }
90    args.push(prompt.into());
91    args
92}
93
94/// Full interactive Codex UI (no `exec` / `--json`).
95fn interactive_args(prompt: &str, model: Option<&str>) -> Vec<String> {
96    let mut args = Vec::new();
97    if let Some(m) = model {
98        args.push("--model".into());
99        args.push(m.into());
100    }
101    // Nobody is watching a Stage session, so an approval prompt burns the
102    // node's whole timeout. `--ask-for-approval never` alone is only half of
103    // `--full-auto`: the sandbox still defaults to read-only in a workspace the
104    // user has not trusted, and with approvals off the model cannot escalate —
105    // every edit is rejected and the node burns its budget failing silently.
106    if approvals_are_auto() {
107        args.push("--ask-for-approval".into());
108        args.push("never".into());
109        args.push("--sandbox".into());
110        args.push("workspace-write".into());
111    }
112    args.push(prompt.into());
113    args
114}
115
116/// Parse Codex JSONL (when present) or fall back to the last non-empty text block.
117fn parse(out: &SubprocessOutput) -> ParsedHarness {
118    let mut result = String::new();
119    let mut session_id = None;
120    let mut usage = Usage::default();
121    let mut saw_json = false;
122    let mut is_error = false;
123
124    for line in out.stdout.lines() {
125        let line = line.trim();
126        if line.is_empty() || !line.starts_with('{') {
127            continue;
128        }
129        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
130            continue;
131        };
132        saw_json = true;
133
134        // Event type field varies: `type`, `msg.type`, `item.type`.
135        let ty = v
136            .get("type")
137            .or_else(|| v.pointer("/msg/type"))
138            .or_else(|| v.pointer("/item/type"))
139            .and_then(|t| t.as_str())
140            .unwrap_or("");
141
142        match ty {
143            "agent_message" | "message" | "assistant_message" | "agent_message_delta" => {
144                if let Some(text) = pick_text(&v) {
145                    if ty.ends_with("_delta") {
146                        result.push_str(&text);
147                    } else if text.len() >= result.len() {
148                        result = text;
149                    }
150                }
151            }
152            "item.completed" | "turn.completed" | "task_complete" | "completed" => {
153                if let Some(text) = pick_text(&v) {
154                    if !text.is_empty() {
155                        result = text;
156                    }
157                }
158                if let Some(u) = v.get("usage").or_else(|| v.pointer("/msg/usage")) {
159                    fill_usage(&mut usage, u);
160                }
161            }
162            "error" | "turn.failed" | "task_failed" => {
163                is_error = true;
164                if let Some(text) = pick_text(&v) {
165                    result = text;
166                }
167            }
168            "session_created" | "thread.started" => {
169                session_id = v
170                    .get("session_id")
171                    .or_else(|| v.get("thread_id"))
172                    .or_else(|| v.pointer("/msg/session_id"))
173                    .and_then(|s| s.as_str())
174                    .map(String::from)
175                    .or(session_id);
176            }
177            _ => {
178                // Generic: last substantial text field wins.
179                if let Some(text) = pick_text(&v) {
180                    if text.len() > result.len() {
181                        result = text;
182                    }
183                }
184                if let Some(u) = v.get("usage") {
185                    fill_usage(&mut usage, u);
186                }
187            }
188        }
189    }
190
191    if !result.trim().is_empty() {
192        return ParsedHarness {
193            result: result.trim().to_string(),
194            session_id,
195            usage,
196            is_error,
197        };
198    }
199
200    if saw_json {
201        // JSONL present but no text — still return raw for debugging.
202        return ParsedHarness::raw(&out.stdout);
203    }
204
205    // Plain text path: take the last non-empty paragraph as the answer.
206    let plain = last_paragraph(&out.stdout);
207    if plain.is_empty() {
208        ParsedHarness::raw(&out.stdout)
209    } else {
210        ParsedHarness {
211            result: plain,
212            session_id: None,
213            usage: Usage::default(),
214            is_error: !matches!(out.status, rinne_core::worker::ExecStatus::Success),
215        }
216    }
217}
218
219fn pick_text(v: &serde_json::Value) -> Option<String> {
220    const KEYS: &[&str] = &[
221        "text",
222        "message",
223        "content",
224        "result",
225        "output",
226        "agent_message",
227        "final_message",
228    ];
229    for k in KEYS {
230        if let Some(s) = v.get(*k).and_then(|x| x.as_str()) {
231            let t = s.trim();
232            if !t.is_empty() {
233                return Some(t.to_string());
234            }
235        }
236        if let Some(s) = v.pointer(&format!("/msg/{k}")).and_then(|x| x.as_str()) {
237            let t = s.trim();
238            if !t.is_empty() {
239                return Some(t.to_string());
240            }
241        }
242        if let Some(s) = v.pointer(&format!("/item/{k}")).and_then(|x| x.as_str()) {
243            let t = s.trim();
244            if !t.is_empty() {
245                return Some(t.to_string());
246            }
247        }
248    }
249    // content array (OpenAI-style)
250    if let Some(arr) = v
251        .get("content")
252        .or_else(|| v.pointer("/msg/content"))
253        .and_then(|c| c.as_array())
254    {
255        let mut acc = String::new();
256        for block in arr {
257            if let Some(t) = block.get("text").and_then(|t| t.as_str()) {
258                acc.push_str(t);
259            }
260        }
261        if !acc.trim().is_empty() {
262            return Some(acc);
263        }
264    }
265    None
266}
267
268fn fill_usage(usage: &mut Usage, u: &serde_json::Value) {
269    if let Some(n) = u
270        .get("input_tokens")
271        .or_else(|| u.get("prompt_tokens"))
272        .and_then(|x| x.as_u64())
273    {
274        usage.prompt_tokens = n;
275    }
276    if let Some(n) = u
277        .get("output_tokens")
278        .or_else(|| u.get("completion_tokens"))
279        .and_then(|x| x.as_u64())
280    {
281        usage.completion_tokens = n;
282    }
283}
284
285fn last_paragraph(stdout: &str) -> String {
286    let mut blocks: Vec<&str> = stdout
287        .split("\n\n")
288        .map(str::trim)
289        .filter(|b| !b.is_empty())
290        .collect();
291    // Prefer the last block that doesn't look like a log line.
292    while let Some(b) = blocks.last() {
293        if b.starts_with("INFO") || b.starts_with("DEBUG") || b.starts_with("WARN") {
294            blocks.pop();
295            continue;
296        }
297        break;
298    }
299    blocks.last().copied().unwrap_or("").to_string()
300}
301
302/// Map Codex JSONL or plain progress lines into Stage-friendly events.
303fn line_mapper(line: &str) -> Vec<WorkerEvent> {
304    let t = line.trim();
305    if t.is_empty() {
306        return Vec::new();
307    }
308
309    if t.starts_with('{') {
310        if let Ok(v) = serde_json::from_str::<serde_json::Value>(t) {
311            return map_json_event(&v);
312        }
313    }
314
315    // Plain-text heuristics for older non-JSON codex builds.
316    let lower = t.to_ascii_lowercase();
317    if lower.contains("reading ") || lower.starts_with("read ") {
318        return vec![WorkerEvent::Reading(t.to_string())];
319    }
320    if lower.contains("writing ")
321        || lower.contains("edited ")
322        || lower.contains("applying patch")
323        || lower.contains("applied edit")
324    {
325        return vec![WorkerEvent::Editing(t.to_string())];
326    }
327    if lower.contains("running ") || lower.starts_with("$ ") || lower.contains("command:") {
328        return vec![WorkerEvent::ToolUse(t.to_string())];
329    }
330    vec![WorkerEvent::Message(t.to_string())]
331}
332
333fn map_json_event(v: &serde_json::Value) -> Vec<WorkerEvent> {
334    let ty = v
335        .get("type")
336        .or_else(|| v.pointer("/msg/type"))
337        .or_else(|| v.pointer("/item/type"))
338        .and_then(|t| t.as_str())
339        .unwrap_or("");
340
341    match ty {
342        "agent_message" | "message" | "assistant_message" => pick_text(v)
343            .map(|t| vec![WorkerEvent::Message(t)])
344            .unwrap_or_default(),
345        "agent_message_delta" | "message_delta" => pick_text(v)
346            .map(|t| vec![WorkerEvent::Token(t)])
347            .unwrap_or_default(),
348        "reasoning" | "thought" | "thinking" => pick_text(v)
349            .map(|t| vec![WorkerEvent::Thinking(t)])
350            .unwrap_or_default(),
351        "command_execution" | "exec_command" | "shell" | "command" => {
352            let cmd = v
353                .get("command")
354                .or_else(|| v.pointer("/item/command"))
355                .or_else(|| v.pointer("/msg/command"))
356                .and_then(|c| c.as_str())
357                .unwrap_or("command");
358            vec![WorkerEvent::ToolUse(truncate(cmd, 100))]
359        }
360        "file_change" | "patch" | "apply_patch" | "file_edit" => {
361            let path = v
362                .get("path")
363                .or_else(|| v.get("file"))
364                .or_else(|| v.pointer("/item/path"))
365                .and_then(|p| p.as_str())
366                .unwrap_or("file");
367            vec![WorkerEvent::Editing(format!("editing {path}"))]
368        }
369        "file_read" | "read" => {
370            let path = v
371                .get("path")
372                .or_else(|| v.get("file"))
373                .and_then(|p| p.as_str())
374                .unwrap_or("file");
375            vec![WorkerEvent::Reading(path.to_string())]
376        }
377        "tool" | "tool_call" | "mcp_tool_call" => {
378            let name = v
379                .get("name")
380                .or_else(|| v.get("tool"))
381                .and_then(|n| n.as_str())
382                .unwrap_or("tool");
383            vec![WorkerEvent::ToolUse(name.to_string())]
384        }
385        "error" | "turn.failed" => pick_text(v)
386            .map(|t| vec![WorkerEvent::Message(format!("error: {t}"))])
387            .unwrap_or_default(),
388        // session / completed / noise
389        _ => Vec::new(),
390    }
391}
392
393fn truncate(s: &str, max: usize) -> String {
394    if s.chars().count() <= max {
395        s.to_string()
396    } else {
397        s.chars().take(max).collect::<String>() + "…"
398    }
399}
400
401fn provision(servers: &[McpServerSpec], scratch: &Path) -> Result<Provision> {
402    mcp_util::provision_codex_style(servers, scratch)
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use rinne_core::worker::ExecStatus;
409
410    #[test]
411    fn default_ladder_only_holds_models_a_chatgpt_account_can_run() {
412        // Codex signed in with a ChatGPT account rejects o-series models with
413        // "The 'o3' model is not supported when using Codex with a ChatGPT
414        // account" (HTTP 400), so routing to that rung fails the whole node.
415        let models = descriptor().models;
416        assert!(
417            !models.iter().any(|m| m == "o3"),
418            "o3 is not runnable on a ChatGPT account: {models:?}"
419        );
420        assert!(models.iter().any(|m| m == "gpt-5"), "{models:?}");
421    }
422
423    fn out(stdout: &str) -> SubprocessOutput {
424        SubprocessOutput {
425            stdout: stdout.into(),
426            stderr: String::new(),
427            exit_code: Some(0),
428            status: ExecStatus::Success,
429            wall_ms: 10,
430        }
431    }
432
433    #[test]
434    fn parses_jsonl_agent_message() {
435        let stdout = r#"
436{"type":"session_created","session_id":"s1"}
437{"type":"agent_message","text":"Done: fixed the bug."}
438{"type":"turn.completed","usage":{"input_tokens":10,"output_tokens":5}}
439"#;
440        let p = parse(&out(stdout));
441        assert!(p.result.contains("fixed the bug"));
442        assert_eq!(p.session_id.as_deref(), Some("s1"));
443        assert_eq!(p.usage.prompt_tokens, 10);
444        assert_eq!(p.usage.completion_tokens, 5);
445    }
446
447    #[test]
448    fn plain_text_fallback() {
449        let p = parse(&out("INFO start\n\nAll tests passed.\n"));
450        assert!(p.result.contains("All tests passed"));
451    }
452
453    #[test]
454    fn line_mapper_maps_tool_events() {
455        let evs = line_mapper(r#"{"type":"file_change","path":"src/main.rs"}"#);
456        assert!(matches!(evs.first(), Some(WorkerEvent::Editing(_))));
457        let evs = line_mapper("Applying patch to foo.rs");
458        assert!(matches!(evs.first(), Some(WorkerEvent::Editing(_))));
459    }
460}