collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
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
//! Structured output parsers for CLI coding agent stdout streams.
//!
//! Each CLI agent can emit structured (JSON/NDJSON) output alongside plain text.
//! These parsers convert JSON lines into [`ParsedCliLine`] so that `run_cli_fast_path`
//! can emit clean [`AgentEvent`]s instead of raw JSON noise.

use serde_json::Value;

/// The format a CLI agent emits on stdout.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CliOutputFormat {
    /// Raw text — forward lines as-is.
    Raw,
    /// Claude Code `--output-format stream-json` — NDJSON envelope per turn.
    ClaudeStreamJson,
    /// Codex CLI `--json` — NDJSON event stream.
    CodexNdjson,
    /// Gemini CLI `--output-format json` — JSON response envelope.
    GeminiJson,
}

impl CliOutputFormat {
    /// Detect output format from CLI args list.
    pub fn detect(args: &[String]) -> Self {
        let args_str: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        if args_str
            .windows(2)
            .any(|w| w == ["--output-format", "stream-json"])
            || args_str.windows(2).any(|w| w == ["-f", "stream-json"])
        {
            return Self::ClaudeStreamJson;
        }
        if args_str.contains(&"--json") {
            return Self::CodexNdjson;
        }
        if args_str
            .windows(2)
            .any(|w| w == ["--output-format", "json"])
        {
            return Self::GeminiJson;
        }
        Self::Raw
    }
}

/// Result of parsing a single stdout line from a CLI agent.
#[derive(Debug)]
pub enum ParsedCliLine {
    /// Emit this text as a streaming token.
    Text(String),
    /// A tool call was observed — show its name for visibility.
    ToolCall { name: String },
    /// The definitive final answer (from claude's "result" envelope).
    /// When present, this replaces `full_response` as the context message.
    FinalResult(String),
    /// Line carries no displayable content — skip silently.
    Skip,
}

/// Parse a single stdout line according to the given format.
pub fn parse_cli_line(line: &str, format: CliOutputFormat) -> ParsedCliLine {
    match format {
        CliOutputFormat::Raw => ParsedCliLine::Text(line.to_string()),
        CliOutputFormat::ClaudeStreamJson => parse_claude_stream_json(line),
        CliOutputFormat::CodexNdjson => parse_codex_ndjson(line),
        CliOutputFormat::GeminiJson => parse_gemini_json(line),
    }
}

// ── Claude stream-json ────────────────────────────────────────────────────────
//
// Each line is a complete JSON object. Relevant shapes:
//
//   {"type":"system","subtype":"init",...}           → skip
//   {"type":"assistant","message":{"content":[...]}} → extract text/tool_use
//   {"type":"user","message":{"content":[...]}}      → skip (tool results)
//   {"type":"result","subtype":"success","result":"...","total_cost_usd":0.003}
//                                                    → FinalResult
//   {"type":"result","subtype":"error","error":"..."}→ Text(error)

fn parse_claude_stream_json(line: &str) -> ParsedCliLine {
    let Ok(val) = serde_json::from_str::<Value>(line) else {
        // Not JSON — treat as plain text (e.g. pre-init startup lines).
        return if line.trim().is_empty() {
            ParsedCliLine::Skip
        } else {
            ParsedCliLine::Text(line.to_string())
        };
    };

    let msg_type = val.get("type").and_then(|v| v.as_str()).unwrap_or("");

    match msg_type {
        "system" => ParsedCliLine::Skip,
        "user" => ParsedCliLine::Skip, // tool results — collet tracks these itself

        "assistant" => {
            let Some(message) = val.get("message") else {
                return ParsedCliLine::Skip;
            };
            let Some(content) = message.get("content").and_then(|c| c.as_array()) else {
                return ParsedCliLine::Skip;
            };

            // Collect text blocks; report first tool_use by name.
            let mut text_parts: Vec<String> = Vec::new();
            let mut tool_name: Option<String> = None;

            for block in content {
                match block.get("type").and_then(|t| t.as_str()) {
                    Some("text") => {
                        if let Some(t) = block.get("text").and_then(|v| v.as_str())
                            && !t.is_empty()
                        {
                            text_parts.push(t.to_string());
                        }
                    }
                    Some("tool_use") => {
                        if tool_name.is_none() {
                            tool_name = block
                                .get("name")
                                .and_then(|v| v.as_str())
                                .map(|s| s.to_string());
                        }
                    }
                    _ => {}
                }
            }

            if let Some(name) = tool_name {
                // Prefer showing tool call; text (if any) usually comes separately.
                return ParsedCliLine::ToolCall { name };
            }
            if !text_parts.is_empty() {
                return ParsedCliLine::Text(text_parts.join(""));
            }
            ParsedCliLine::Skip
        }

        "result" => {
            let subtype = val.get("subtype").and_then(|v| v.as_str()).unwrap_or("");
            if subtype == "success" {
                if let Some(result) = val.get("result").and_then(|v| v.as_str()) {
                    return ParsedCliLine::FinalResult(result.to_string());
                }
            } else {
                // error subtype
                let err = val
                    .get("error")
                    .and_then(|v| v.as_str())
                    .unwrap_or("Unknown CLI error");
                return ParsedCliLine::Text(format!("{err}"));
            }
            ParsedCliLine::Skip
        }

        _ => ParsedCliLine::Skip,
    }
}

// ── Codex NDJSON ──────────────────────────────────────────────────────────────
//
// Codex emits an event stream. Common shapes (from codex --json):
//   {"type":"message","role":"assistant","content":"..."}
//   {"type":"reasoning","content":"..."}
//   {"type":"tool_call","name":"...","arguments":{...}}
//   {"type":"tool_result","content":"..."}
//   {"type":"error","message":"..."}

fn parse_codex_ndjson(line: &str) -> ParsedCliLine {
    let Ok(val) = serde_json::from_str::<Value>(line) else {
        return if line.trim().is_empty() {
            ParsedCliLine::Skip
        } else {
            ParsedCliLine::Text(line.to_string())
        };
    };

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

    match event_type {
        "message" => {
            if val.get("role").and_then(|v| v.as_str()) == Some("assistant")
                && let Some(content) = val.get("content").and_then(|v| v.as_str())
                && !content.is_empty()
            {
                return ParsedCliLine::Text(content.to_string());
            }
            ParsedCliLine::Skip
        }
        "reasoning" => ParsedCliLine::Skip, // internal reasoning, skip
        "tool_call" => {
            let name = val
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown_tool")
                .to_string();
            ParsedCliLine::ToolCall { name }
        }
        "tool_result" | "system" => ParsedCliLine::Skip,
        "error" => {
            let msg = val
                .get("message")
                .and_then(|v| v.as_str())
                .unwrap_or("Unknown error");
            ParsedCliLine::Text(format!("{msg}"))
        }
        _ => ParsedCliLine::Skip,
    }
}

// ── Gemini JSON ───────────────────────────────────────────────────────────────
//
// Gemini CLI with `--output-format json` outputs a JSON object per response.
// Common shapes:
//   {"text": "..."}
//   {"parts": [{"text": "..."}]}
//   {"candidates": [{"content": {"parts": [{"text": "..."}]}}]}

fn parse_gemini_json(line: &str) -> ParsedCliLine {
    if line.trim().is_empty() {
        return ParsedCliLine::Skip;
    }
    let Ok(val) = serde_json::from_str::<Value>(line) else {
        // Not JSON — plain text output before/after JSON
        return ParsedCliLine::Text(line.to_string());
    };

    // Shape: {"text": "..."}
    if let Some(text) = val.get("text").and_then(|v| v.as_str())
        && !text.is_empty()
    {
        return ParsedCliLine::Text(text.to_string());
    }

    // Shape: {"parts": [{"text": "..."}]}
    if let Some(parts) = val.get("parts").and_then(|v| v.as_array()) {
        let text: String = parts
            .iter()
            .filter_map(|p| p.get("text").and_then(|t| t.as_str()))
            .collect::<Vec<_>>()
            .join("");
        if !text.is_empty() {
            return ParsedCliLine::Text(text);
        }
    }

    // Shape: {"candidates": [{"content": {"parts": [{"text": "..."}]}}]}
    if let Some(candidates) = val.get("candidates").and_then(|v| v.as_array()) {
        for candidate in candidates {
            if let Some(parts) = candidate
                .get("content")
                .and_then(|c| c.get("parts"))
                .and_then(|p| p.as_array())
            {
                let text: String = parts
                    .iter()
                    .filter_map(|p| p.get("text").and_then(|t| t.as_str()))
                    .collect::<Vec<_>>()
                    .join("");
                if !text.is_empty() {
                    return ParsedCliLine::Text(text);
                }
            }
        }
    }

    ParsedCliLine::Skip
}

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

    #[test]
    fn detect_claude_stream_json() {
        let args: Vec<String> = vec!["-p".into(), "--output-format".into(), "stream-json".into()];
        assert_eq!(
            CliOutputFormat::detect(&args),
            CliOutputFormat::ClaudeStreamJson
        );
    }

    #[test]
    fn detect_codex_ndjson() {
        let args: Vec<String> = vec!["exec".into(), "--json".into()];
        assert_eq!(CliOutputFormat::detect(&args), CliOutputFormat::CodexNdjson);
    }

    #[test]
    fn detect_raw() {
        let args: Vec<String> = vec!["-p".into()];
        assert_eq!(CliOutputFormat::detect(&args), CliOutputFormat::Raw);
    }

    #[test]
    fn parse_claude_text_block() {
        let line = r#"{"type":"assistant","message":{"id":"msg_01","type":"message","role":"assistant","model":"claude-sonnet-4-6","content":[{"type":"text","text":"Hello!"}],"stop_reason":"end_turn","usage":{"input_tokens":10,"output_tokens":5}}}"#;
        match parse_cli_line(line, CliOutputFormat::ClaudeStreamJson) {
            ParsedCliLine::Text(t) => assert_eq!(t, "Hello!"),
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn parse_claude_tool_use() {
        let line = r#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_01","name":"Read","input":{"file_path":"/foo"}}]}}"#;
        match parse_cli_line(line, CliOutputFormat::ClaudeStreamJson) {
            ParsedCliLine::ToolCall { name } => assert_eq!(name, "Read"),
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn parse_claude_result() {
        let line =
            r#"{"type":"result","subtype":"success","result":"Done!","total_cost_usd":0.001}"#;
        match parse_cli_line(line, CliOutputFormat::ClaudeStreamJson) {
            ParsedCliLine::FinalResult(r) => assert_eq!(r, "Done!"),
            other => panic!("expected FinalResult, got {other:?}"),
        }
    }

    #[test]
    fn parse_claude_system_skipped() {
        let line = r#"{"type":"system","subtype":"init","model":"claude-sonnet-4-6"}"#;
        assert!(matches!(
            parse_cli_line(line, CliOutputFormat::ClaudeStreamJson),
            ParsedCliLine::Skip
        ));
    }

    #[test]
    fn parse_raw_passthrough() {
        let line = "plain text output";
        match parse_cli_line(line, CliOutputFormat::Raw) {
            ParsedCliLine::Text(t) => assert_eq!(t, "plain text output"),
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn parse_claude_error_result() {
        let line = r#"{"type":"result","subtype":"error","error":"rate limit exceeded"}"#;
        match parse_cli_line(line, CliOutputFormat::ClaudeStreamJson) {
            ParsedCliLine::Text(t) => assert!(t.contains("rate limit exceeded")),
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn parse_codex_tool_call() {
        let line = r#"{"type":"tool_call","name":"bash","arguments":{"cmd":"ls"}}"#;
        match parse_cli_line(line, CliOutputFormat::CodexNdjson) {
            ParsedCliLine::ToolCall { name } => assert_eq!(name, "bash"),
            other => panic!("expected ToolCall, got {other:?}"),
        }
    }

    #[test]
    fn parse_codex_assistant_message() {
        let line = r#"{"type":"message","role":"assistant","content":"Here is the result."}"#;
        match parse_cli_line(line, CliOutputFormat::CodexNdjson) {
            ParsedCliLine::Text(t) => assert_eq!(t, "Here is the result."),
            other => panic!("expected Text, got {other:?}"),
        }
    }

    #[test]
    fn test_detect_gemini_json() {
        let args = vec!["--output-format".to_string(), "json".to_string()];
        assert_eq!(CliOutputFormat::detect(&args), CliOutputFormat::GeminiJson);
    }

    #[test]
    fn test_parse_gemini_json_text() {
        let line = r#"{"text": "Hello from Gemini"}"#;
        assert!(matches!(
            parse_gemini_json(line),
            ParsedCliLine::Text(t) if t == "Hello from Gemini"
        ));
    }

    #[test]
    fn test_parse_gemini_json_parts() {
        let line = r#"{"parts": [{"text": "part1"}, {"text": "part2"}]}"#;
        assert!(matches!(
            parse_gemini_json(line),
            ParsedCliLine::Text(t) if t == "part1part2"
        ));
    }

    #[test]
    fn test_parse_gemini_json_candidates() {
        let line = r#"{"candidates": [{"content": {"parts": [{"text": "from candidates"}]}}]}"#;
        assert!(matches!(
            parse_gemini_json(line),
            ParsedCliLine::Text(t) if t == "from candidates"
        ));
    }

    #[test]
    fn test_parse_gemini_json_unknown_shape_skipped() {
        let line = r#"{"unknownField": "value"}"#;
        assert!(matches!(parse_gemini_json(line), ParsedCliLine::Skip));
    }

    #[test]
    fn test_detect_gemini_json_does_not_steal_stream_json() {
        // --output-format stream-json must still resolve to ClaudeStreamJson
        let args = vec!["--output-format".to_string(), "stream-json".to_string()];
        assert_eq!(
            CliOutputFormat::detect(&args),
            CliOutputFormat::ClaudeStreamJson
        );
    }
}