agent-code 0.19.0

An AI-powered coding agent for the terminal, written in pure Rust
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Structured JSONL output for non-interactive / CI mode.
//!
//! `--output-format json` writes one JSON object per line to stdout.
//! Human-readable status messages go to stderr so downstream
//! consumers can pipe stdout directly into `jq` or a processing
//! script.
//!
//! ```text
//! agent -p "fix tests" --output-format json \
//!   | jq 'select(.type == "tool_call")'
//! ```

use std::io::Write;
use std::sync::Mutex;

use agent_code_lib::llm::message::Usage;
use agent_code_lib::query::StreamSink;
use serde::Serialize;

/// Output format for one-shot mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
    #[default]
    Text,
    Json,
}

impl std::str::FromStr for OutputFormat {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "text" => Ok(Self::Text),
            "json" => Ok(Self::Json),
            other => Err(format!(
                "unknown output format: {other} (expected text or json)"
            )),
        }
    }
}

impl std::fmt::Display for OutputFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Text => write!(f, "text"),
            Self::Json => write!(f, "json"),
        }
    }
}

/// Exit codes for non-interactive mode (ROADMAP 7.7).
#[repr(u8)]
pub enum ExitCode {
    Success = 0,
    ConfigError = 1,
    InputError = 2,
    ToolFailure = 3,
    LlmError = 4,
    CostLimit = 5,
    TurnLimit = 6,
    PermissionDenied = 7,
}

/// Envelope event written as a single JSONL line to stdout.
#[derive(Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
enum Event<'a> {
    SessionStart {
        session_id: &'a str,
        model: &'a str,
        timestamp: &'a str,
        /// Session working directory. Absolute path. Lets consumers
        /// tag runs against a project root without polling state.
        cwd: &'a str,
        /// Host OS identifier (`linux`, `macos`, `windows`).
        os: &'a str,
        /// Host CPU architecture (`x86_64`, `aarch64`, ...).
        arch: &'a str,
        /// Version of the agent binary — matches the `version` field in
        /// `crates/cli/Cargo.toml`. Use for correlating runs with
        /// release notes when triaging issues.
        agent_version: &'a str,
    },
    /// A new agent turn has just begun. Fires BEFORE any text or tool
    /// activity for this turn, so consumers can render a "turn N"
    /// progress indicator without waiting for TurnComplete.
    TurnStart {
        turn: usize,
    },
    TextDelta {
        content: &'a str,
        turn: usize,
    },
    Thinking {
        content: &'a str,
        turn: usize,
    },
    ToolCall {
        tool: &'a str,
        input: &'a serde_json::Value,
        turn: usize,
    },
    ToolResult {
        tool: &'a str,
        output: &'a str,
        is_error: bool,
        turn: usize,
    },
    /// A tool call was blocked by the permission system (policy-driven
    /// denial or an explicit user `Deny` at the prompt). Consumers of
    /// the JSONL stream previously had to grep the `tool_result.output`
    /// field for the string "Permission denied: " to tell policy
    /// violations apart from genuine tool errors — this event makes
    /// them a first-class signal.
    PermissionDenied {
        tool: &'a str,
        reason: &'a str,
        turn: usize,
    },
    TurnComplete {
        turn: usize,
        input_tokens: u64,
        output_tokens: u64,
        cost_usd: f64,
    },
    Error {
        message: &'a str,
        turn: usize,
    },
    /// Non-fatal warning surfaced by the engine (budget approaching a
    /// limit, rate-limit backoff, schema fallback, etc.). JSONL consumers
    /// need these on stdout so they can tag runs without re-parsing
    /// stderr.
    Warning {
        message: &'a str,
        turn: usize,
    },
    /// Autocompaction just freed context. The human stderr line still
    /// fires — this event lets consumers surface cost/context shifts
    /// in dashboards and audit logs.
    Compact {
        freed_tokens: u64,
        turn: usize,
    },
    SessionEnd {
        turns: usize,
        total_cost_usd: f64,
        exit_code: u8,
    },
}

/// Internal mutable state shared across sink callbacks.
struct SinkState {
    turn: usize,
    last_usage: Usage,
}

/// A [`StreamSink`] that writes JSONL events to stdout.
///
/// Status/warning messages go to stderr so the JSONL stream on
/// stdout remains machine-parseable.
pub struct JsonStreamSink {
    model: String,
    inner: Mutex<SinkState>,
}

impl JsonStreamSink {
    pub fn new(model: &str) -> Self {
        Self {
            model: model.to_string(),
            inner: Mutex::new(SinkState {
                turn: 0,
                last_usage: Usage::default(),
            }),
        }
    }

    /// Emit the `session_start` envelope before the first turn.
    pub fn emit_session_start(&self, session_id: &str) {
        let ts = chrono::Utc::now().to_rfc3339();
        let cwd = std::env::current_dir()
            .map(|p| p.display().to_string())
            .unwrap_or_default();
        emit(&Event::SessionStart {
            session_id,
            model: &self.model,
            timestamp: &ts,
            cwd: &cwd,
            os: std::env::consts::OS,
            arch: std::env::consts::ARCH,
            agent_version: env!("CARGO_PKG_VERSION"),
        });
    }

    /// Emit the `session_end` envelope after the run completes.
    pub fn emit_session_end(&self, total_cost_usd: f64, exit_code: u8) {
        let state = self.inner.lock().unwrap();
        emit(&Event::SessionEnd {
            turns: state.turn,
            total_cost_usd,
            exit_code,
        });
    }
}

impl StreamSink for JsonStreamSink {
    fn on_turn_start(&self, turn: usize) {
        self.inner.lock().unwrap().turn = turn;
        // Emit after updating state so downstream consumers see a
        // turn_start line carrying the new turn number. TurnComplete
        // already fires at the end; this is the matching bookend.
        emit(&Event::TurnStart { turn });
    }

    fn on_text(&self, text: &str) {
        let turn = self.inner.lock().unwrap().turn;
        emit(&Event::TextDelta {
            content: text,
            turn,
        });
    }

    fn on_thinking(&self, text: &str) {
        let turn = self.inner.lock().unwrap().turn;
        emit(&Event::Thinking {
            content: text,
            turn,
        });
    }

    fn on_tool_start(&self, tool_name: &str, input: &serde_json::Value) {
        let state = self.inner.lock().unwrap();
        emit(&Event::ToolCall {
            tool: tool_name,
            input,
            turn: state.turn,
        });
    }

    fn on_tool_result(&self, tool_name: &str, result: &agent_code_lib::tools::ToolResult) {
        let state = self.inner.lock().unwrap();
        // Policy-driven denials are still reported as a ToolResult so
        // downstream consumers that only know about the old envelope
        // keep working. We ALSO emit a dedicated PermissionDenied event
        // so consumers that want to tell policy apart from tool bugs
        // can subscribe to it directly.
        if let Some(reason) = permission_denied_reason(&result.content, result.is_error) {
            emit(&Event::PermissionDenied {
                tool: tool_name,
                reason,
                turn: state.turn,
            });
        }
        emit(&Event::ToolResult {
            tool: tool_name,
            output: &result.content,
            is_error: result.is_error,
            turn: state.turn,
        });
    }

    fn on_usage(&self, usage: &Usage) {
        let mut state = self.inner.lock().unwrap();
        state.last_usage = usage.clone();
    }

    fn on_turn_complete(&self, turn: usize) {
        let mut state = self.inner.lock().unwrap();
        state.turn = turn;
        let cost = crate::estimate_model_cost(&state.last_usage, &self.model);
        emit(&Event::TurnComplete {
            turn,
            input_tokens: state.last_usage.input_tokens,
            output_tokens: state.last_usage.output_tokens,
            cost_usd: cost,
        });
    }

    fn on_error(&self, error: &str) {
        let turn = self.inner.lock().unwrap().turn;
        emit(&Event::Error {
            message: error,
            turn,
        });
    }

    fn on_warning(&self, msg: &str) {
        // Stderr stays for humans tailing the run; stdout JSONL is for
        // automation consumers that would otherwise lose budget /
        // rate-limit signals entirely.
        let turn = self.inner.lock().unwrap().turn;
        emit(&Event::Warning { message: msg, turn });
        let _ = writeln!(std::io::stderr(), "{msg}");
    }

    fn on_compact(&self, freed_tokens: u64) {
        let turn = self.inner.lock().unwrap().turn;
        emit(&Event::Compact { freed_tokens, turn });
        let _ = writeln!(std::io::stderr(), "compacted: freed ~{freed_tokens} tokens");
    }
}

/// Write a single JSONL event to stdout (locked, flushed).
fn emit(event: &Event<'_>) {
    if let Ok(line) = serde_json::to_string(event) {
        let stdout = std::io::stdout();
        let mut lock = stdout.lock();
        let _ = writeln!(lock, "{line}");
        let _ = lock.flush();
    }
}

/// If this tool result looks like a permission-system denial, return
/// the human-readable reason so the sink can emit a structured event
/// in addition to the normal ToolResult envelope.
///
/// Matches the two shapes emitted by `crates/lib/src/tools/executor.rs`:
/// - Policy Deny: `"Permission denied: {reason}"`
/// - User Deny at prompt: `"Permission denied by user"`
///
/// The contract between the executor and this sink is: if the executor
/// ever changes its prefix, this function MUST be updated — the tests
/// below pin both detected shapes.
fn permission_denied_reason(content: &str, is_error: bool) -> Option<&str> {
    if !is_error {
        return None;
    }
    if let Some(reason) = content.strip_prefix("Permission denied: ") {
        // Guard against the empty-reason case so we don't emit a
        // stray event with `reason=""` — meaningless to consumers.
        if reason.trim().is_empty() {
            return None;
        }
        return Some(reason);
    }
    // User-initiated deny at the interactive prompt. No colon-delimited
    // reason, so synthesize one from the message body itself.
    if content == "Permission denied by user" {
        return Some("user denied at prompt");
    }
    None
}

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

    #[test]
    fn output_format_parse() {
        assert_eq!("json".parse::<OutputFormat>().unwrap(), OutputFormat::Json);
        assert_eq!("text".parse::<OutputFormat>().unwrap(), OutputFormat::Text);
        assert_eq!("JSON".parse::<OutputFormat>().unwrap(), OutputFormat::Json);
        assert!("xml".parse::<OutputFormat>().is_err());
    }

    #[test]
    fn event_serialization_text_delta() {
        let event = Event::TextDelta {
            content: "hello",
            turn: 1,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"text_delta""#));
        assert!(json.contains(r#""content":"hello""#));
        assert!(json.contains(r#""turn":1"#));
    }

    #[test]
    fn event_serialization_session_start() {
        let event = Event::SessionStart {
            session_id: "abc-123",
            model: "test-model",
            timestamp: "2026-04-15T00:00:00Z",
            cwd: "/tmp/proj",
            os: "linux",
            arch: "x86_64",
            agent_version: "9.9.9",
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"session_start""#));
        assert!(json.contains(r#""session_id":"abc-123""#));
        assert!(json.contains(r#""cwd":"/tmp/proj""#));
        assert!(json.contains(r#""os":"linux""#));
        assert!(json.contains(r#""arch":"x86_64""#));
        assert!(json.contains(r#""agent_version":"9.9.9""#));
    }

    /// Envelope snapshot guard: `session_start` carries exactly these 7
    /// keys (type + 6 payload). If a future refactor adds or removes a
    /// field, strict-shape JSONL consumers silently break — this test
    /// forces the migration conversation.
    #[test]
    fn session_start_envelope_shape_is_seven_keys() {
        let event = Event::SessionStart {
            session_id: "x",
            model: "m",
            timestamp: "t",
            cwd: "/w",
            os: "linux",
            arch: "x86_64",
            agent_version: "0.0.0",
        };
        let val = serde_json::to_value(event).unwrap();
        let obj = val.as_object().unwrap();
        let mut keys: Vec<_> = obj.keys().map(|k| k.as_str()).collect();
        keys.sort();
        assert_eq!(
            keys,
            vec![
                "agent_version",
                "arch",
                "cwd",
                "model",
                "os",
                "session_id",
                "timestamp",
                "type",
            ]
        );
    }

    #[test]
    fn event_serialization_tool_call() {
        let input = serde_json::json!({"file_path": "test.rs", "content": "fn main() {}"});
        let event = Event::ToolCall {
            tool: "FileWrite",
            input: &input,
            turn: 2,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"tool_call""#));
        assert!(json.contains(r#""tool":"FileWrite""#));
        assert!(json.contains(r#""file_path":"test.rs""#));
    }

    #[test]
    fn event_serialization_session_end() {
        let event = Event::SessionEnd {
            turns: 3,
            total_cost_usd: 0.042,
            exit_code: 0,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"session_end""#));
        assert!(json.contains(r#""exit_code":0"#));
    }

    #[test]
    fn event_serialization_turn_complete() {
        let event = Event::TurnComplete {
            turn: 1,
            input_tokens: 1234,
            output_tokens: 567,
            cost_usd: 0.003,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"turn_complete""#));
        assert!(json.contains(r#""input_tokens":1234"#));
    }

    #[test]
    fn event_serialization_error() {
        let event = Event::Error {
            message: "rate limited",
            turn: 1,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"error""#));
        assert!(json.contains(r#""message":"rate limited""#));
    }

    #[test]
    fn all_events_are_single_line_json() {
        let events: Vec<serde_json::Value> = vec![
            serde_json::to_value(Event::SessionStart {
                session_id: "x",
                model: "m",
                timestamp: "t",
                cwd: "/w",
                os: "linux",
                arch: "x86_64",
                agent_version: "0.0.0",
            })
            .unwrap(),
            serde_json::to_value(Event::TurnStart { turn: 1 }).unwrap(),
            serde_json::to_value(Event::TextDelta {
                content: "multi\nline\ncontent",
                turn: 1,
            })
            .unwrap(),
            serde_json::to_value(Event::SessionEnd {
                turns: 1,
                total_cost_usd: 0.0,
                exit_code: 0,
            })
            .unwrap(),
            serde_json::to_value(Event::Warning {
                message: "budget exceeded\nsecond line",
                turn: 2,
            })
            .unwrap(),
            serde_json::to_value(Event::Compact {
                freed_tokens: 1500,
                turn: 3,
            })
            .unwrap(),
            serde_json::to_value(Event::PermissionDenied {
                tool: "Bash",
                reason: "multi\nline\nreason",
                turn: 4,
            })
            .unwrap(),
        ];
        for val in events {
            let line = serde_json::to_string(&val).unwrap();
            assert!(!line.contains('\n'), "event must be single-line: {line}",);
        }
    }

    #[test]
    fn permission_denied_reason_detects_standard_prefix() {
        // Pin the prefix emitted by tools/executor.rs. If the executor
        // ever renames it, this assertion fires and points at the
        // sync point.
        let got = permission_denied_reason("Permission denied: path outside cwd", true);
        assert_eq!(got, Some("path outside cwd"));
    }

    #[test]
    fn permission_denied_reason_ignores_non_errors() {
        // A successful tool result can never be a denial, even if its
        // body coincidentally contains the prefix string (e.g. a log
        // line read from disk).
        let got = permission_denied_reason("Permission denied: oh no", false);
        assert!(got.is_none());
    }

    #[test]
    fn permission_denied_reason_ignores_generic_tool_errors() {
        // Regular tool errors (file not found, timeout, syntax error)
        // must NOT be tagged as permission denials.
        assert!(permission_denied_reason("File not found: foo.rs", true).is_none());
        assert!(permission_denied_reason("timed out after 30s", true).is_none());
    }

    #[test]
    fn permission_denied_reason_rejects_empty_reason() {
        // Executor shouldn't produce these, but defense-in-depth: an
        // empty reason emits a useless event. Better to skip.
        assert!(permission_denied_reason("Permission denied: ", true).is_none());
        assert!(permission_denied_reason("Permission denied:   ", true).is_none());
    }

    #[test]
    fn permission_denied_reason_detects_user_deny_at_prompt() {
        // Pin the exact string produced by the user-Deny branch in
        // tools/executor.rs. Since there's no colon-delimited reason,
        // the detector synthesizes a stable one for consumers.
        let got = permission_denied_reason("Permission denied by user", true);
        assert_eq!(got, Some("user denied at prompt"));
    }

    #[test]
    fn event_serialization_permission_denied_uses_snake_case_type() {
        let event = Event::PermissionDenied {
            tool: "Bash",
            reason: "network access not in allowlist",
            turn: 3,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"permission_denied""#));
        assert!(json.contains(r#""tool":"Bash""#));
        assert!(json.contains(r#""reason":"network access not in allowlist""#));
        assert!(json.contains(r#""turn":3"#));
    }

    #[test]
    fn event_serialization_turn_start_uses_snake_case_type() {
        let event = Event::TurnStart { turn: 5 };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"turn_start""#));
        assert!(json.contains(r#""turn":5"#));
    }

    #[test]
    fn turn_start_event_does_not_include_model_or_session_fields() {
        // TurnStart is intentionally small — just the turn number. If
        // a field accidentally slips in (e.g. model), JSONL consumers
        // that snapshot the envelope shape will start silently failing.
        let event = Event::TurnStart { turn: 1 };
        let val = serde_json::to_value(event).unwrap();
        let obj = val.as_object().unwrap();
        assert_eq!(obj.len(), 2, "expected only `type` and `turn`, got {obj:?}");
        assert!(obj.contains_key("type"));
        assert!(obj.contains_key("turn"));
    }

    #[test]
    fn event_serialization_warning_uses_snake_case_type() {
        let event = Event::Warning {
            message: "budget approaching",
            turn: 4,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"warning""#));
        assert!(json.contains(r#""message":"budget approaching""#));
        assert!(json.contains(r#""turn":4"#));
    }

    #[test]
    fn event_serialization_compact_uses_snake_case_type() {
        let event = Event::Compact {
            freed_tokens: 2048,
            turn: 7,
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains(r#""type":"compact""#));
        assert!(json.contains(r#""freed_tokens":2048"#));
        assert!(json.contains(r#""turn":7"#));
    }

    #[test]
    fn warning_event_preserves_turn_from_sink_state() {
        // Warnings need the current turn stamped in the envelope so
        // consumers can correlate them with the surrounding TurnComplete.
        // This is a structural check — the sink reads `inner.turn` under
        // the same lock that on_turn_start writes to.
        let sink = JsonStreamSink::new("test-model");
        sink.on_turn_start(9);
        // We can't easily capture the stdout line from here without a
        // test scaffold; assert the internal state is what on_warning
        // will read instead.
        let captured_turn = sink.inner.lock().unwrap().turn;
        assert_eq!(captured_turn, 9);
    }
}