zag-agent 0.15.0

Core library for zag — a unified interface for AI coding agents
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
//! Integration tests exercising the full AgentBuilder → AgentFactory → MockAgent pipeline.
//!
//! These tests only use public API methods. Tests that need to verify internal
//! state downcast to MockAgent via `as_any_ref()`.

use crate::builder::AgentBuilder;
use crate::factory::AgentFactory;
use crate::output::Usage;
use crate::providers::mock::{MockAgent, MockResponse, events};

// ---------------------------------------------------------------------------
// Factory integration (public API only)
// ---------------------------------------------------------------------------

#[test]
fn test_factory_create_mock() {
    let agent = AgentFactory::create("mock", None, None, None, false, vec![]).unwrap();
    assert_eq!(agent.name(), "mock");
    // Model depends on config (may be "mock-medium" if config has model = "medium")
    let model = agent.get_model();
    assert!(
        model.starts_with("mock-"),
        "Expected mock model, got: {model}"
    );
}

#[test]
fn test_factory_create_mock_with_model() {
    let agent = AgentFactory::create(
        "mock",
        None,
        Some("mock-large".to_string()),
        None,
        false,
        vec![],
    )
    .unwrap();
    assert_eq!(agent.get_model(), "mock-large");
}

#[test]
fn test_factory_create_mock_with_size_alias() {
    let agent =
        AgentFactory::create("mock", None, Some("small".to_string()), None, false, vec![]).unwrap();
    assert_eq!(agent.get_model(), "mock-small");
}

#[test]
fn test_factory_create_mock_medium_size() {
    let agent = AgentFactory::create(
        "mock",
        None,
        Some("medium".to_string()),
        None,
        false,
        vec![],
    )
    .unwrap();
    assert_eq!(agent.get_model(), "mock-medium");
}

#[test]
fn test_factory_create_mock_large_size() {
    let agent =
        AgentFactory::create("mock", None, Some("large".to_string()), None, false, vec![]).unwrap();
    assert_eq!(agent.get_model(), "mock-large");
}

#[test]
fn test_factory_create_mock_with_system_prompt() {
    let agent = AgentFactory::create(
        "mock",
        Some("Be helpful".to_string()),
        None,
        None,
        false,
        vec![],
    )
    .unwrap();
    assert_eq!(agent.system_prompt(), "Be helpful");
}

#[test]
fn test_factory_create_mock_with_invalid_model() {
    let result = AgentFactory::create(
        "mock",
        None,
        Some("invalid-model".to_string()),
        None,
        false,
        vec![],
    );
    let err = result.err().expect("Expected an error");
    assert!(err.to_string().contains("Invalid model"));
}

#[test]
fn test_factory_create_mock_with_auto_approve() {
    let agent = AgentFactory::create("mock", None, None, None, true, vec![]).unwrap();
    let mock = agent.as_any_ref().downcast_ref::<MockAgent>().unwrap();
    assert!(mock.skip_permissions());
}

#[test]
fn test_factory_create_mock_with_add_dirs() {
    let agent = AgentFactory::create(
        "mock",
        None,
        None,
        None,
        false,
        vec!["/a".to_string(), "/b".to_string()],
    )
    .unwrap();
    let mock = agent.as_any_ref().downcast_ref::<MockAgent>().unwrap();
    assert_eq!(mock.add_dirs(), &["/a", "/b"]);
}

// ---------------------------------------------------------------------------
// Builder → exec integration
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_builder_exec_with_mock() {
    let output = AgentBuilder::new()
        .provider("mock")
        .exec("say hello")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
    assert!(!output.is_error);
}

#[tokio::test]
async fn test_builder_exec_mock_with_model() {
    let output = AgentBuilder::new()
        .provider("mock")
        .model("mock-large")
        .exec("test prompt")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_with_size_alias() {
    let output = AgentBuilder::new()
        .provider("mock")
        .model("small")
        .exec("test prompt")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_with_system_prompt() {
    let output = AgentBuilder::new()
        .provider("mock")
        .system_prompt("You are a test assistant")
        .exec("test")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_with_max_turns() {
    let output = AgentBuilder::new()
        .provider("mock")
        .max_turns(5)
        .exec("test")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_json_mode() {
    // JSON mode for non-claude agents should augment the system prompt
    let output = AgentBuilder::new()
        .provider("mock")
        .json()
        .exec("list 3 colors")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_json_schema_valid() {
    // The default mock response is "" which won't parse as valid JSON,
    // so schema validation should fail
    let schema = serde_json::json!({
        "type": "object",
        "properties": {
            "colors": { "type": "array" }
        },
        "required": ["colors"]
    });

    let result = AgentBuilder::new()
        .provider("mock")
        .json_schema(schema)
        .exec("list colors")
        .await;

    // Default mock response is "" which fails JSON schema validation
    assert!(result.is_err());
}

#[tokio::test]
async fn test_builder_exec_mock_auto_approve() {
    let output = AgentBuilder::new()
        .provider("mock")
        .auto_approve(true)
        .exec("test")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_output_format() {
    let output = AgentBuilder::new()
        .provider("mock")
        .output_format("json")
        .exec("test")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_verbose() {
    let output = AgentBuilder::new()
        .provider("mock")
        .verbose(true)
        .exec("test")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

#[tokio::test]
async fn test_builder_exec_mock_quiet() {
    let output = AgentBuilder::new()
        .provider("mock")
        .quiet(true)
        .exec("test")
        .await
        .unwrap();

    assert_eq!(output.agent, "mock");
}

// ---------------------------------------------------------------------------
// AgentOutput structure tests
// ---------------------------------------------------------------------------

#[test]
fn test_mock_output_from_text() {
    let output = MockResponse::text("hello world").into_output();
    assert_eq!(output.agent, "mock");
    assert_eq!(output.final_result(), Some("hello world"));
    assert!(output.is_success());
    assert!(output.errors().is_empty());
}

#[test]
fn test_mock_output_error() {
    let output = MockResponse::error("something broke").into_output();
    assert!(output.is_error);
    assert_eq!(output.errors().len(), 1);
}

#[test]
fn test_mock_output_with_events() {
    let output = MockResponse::with_events(vec![
        events::init("mock-default"),
        events::assistant_message("I'll help"),
        events::tool_execution("Bash", "echo hi", "hi"),
        events::assistant_message("Done"),
        events::result_success("completed"),
    ])
    .into_output();

    assert_eq!(output.events.len(), 5);
    assert_eq!(output.final_result(), Some("completed"));
    assert_eq!(output.tool_executions().len(), 1);
}

#[test]
fn test_mock_output_with_usage() {
    let usage = Usage {
        input_tokens: 500,
        output_tokens: 200,
        cache_read_tokens: Some(100),
        cache_creation_tokens: Some(50),
        web_search_requests: None,
        web_fetch_requests: None,
    };
    let output = MockResponse::with_usage("result", usage).into_output();
    let u = output.usage.unwrap();
    assert_eq!(u.input_tokens, 500);
    assert_eq!(u.output_tokens, 200);
    assert_eq!(u.cache_read_tokens, Some(100));
}

#[test]
fn test_mock_output_with_cost() {
    let output = MockResponse::text("result").cost(0.05).into_output();
    assert_eq!(output.total_cost_usd, Some(0.05));
}

// ---------------------------------------------------------------------------
// Log entry extraction
// ---------------------------------------------------------------------------

#[test]
fn test_mock_output_log_entries() {
    let output = MockResponse::with_events(vec![
        events::init("mock-default"),
        events::assistant_message("hello"),
        events::tool_execution("Bash", "ls", "file.txt"),
        events::result_success("done"),
    ])
    .into_output();

    let entries = output.to_log_entries(crate::output::LogLevel::Debug);
    assert!(!entries.is_empty());
}

// ---------------------------------------------------------------------------
// Session log / live event streaming (fix for missing live stderr tail)
// ---------------------------------------------------------------------------

/// A scoped override for `ZAG_USER_LOG_DIR` so each test gets a clean logs
/// directory and doesn't race with other tests or the developer's real
/// `~/.zag`. Restores the previous value on drop.
struct ScopedLogsDir {
    _tmp: tempfile::TempDir,
    previous: Option<String>,
}

impl ScopedLogsDir {
    fn new() -> Self {
        let tmp = tempfile::tempdir().expect("tempdir");
        let previous = std::env::var("ZAG_USER_LOG_DIR").ok();
        // SAFETY: single-threaded test; we restore on drop.
        // The env var is the documented override used by zag serve.
        unsafe {
            std::env::set_var("ZAG_USER_LOG_DIR", tmp.path());
        }
        Self {
            _tmp: tmp,
            previous,
        }
    }
}

impl Drop for ScopedLogsDir {
    fn drop(&mut self) {
        unsafe {
            match &self.previous {
                Some(v) => std::env::set_var("ZAG_USER_LOG_DIR", v),
                None => std::env::remove_var("ZAG_USER_LOG_DIR"),
            }
        }
    }
}

#[tokio::test]
async fn test_exec_without_session_log_leaves_log_path_none() {
    let _guard = ScopedLogsDir::new();
    let output = AgentBuilder::new()
        .provider("mock")
        .exec("hi")
        .await
        .unwrap();
    assert!(
        output.log_path.is_none(),
        "session log should stay opt-in for library callers"
    );
}

#[tokio::test]
async fn test_exec_with_enable_session_log_populates_log_path() {
    let _guard = ScopedLogsDir::new();
    let output = AgentBuilder::new()
        .provider("mock")
        .enable_session_log(true)
        .exec("hi")
        .await
        .unwrap();
    let log_path = output.log_path.expect("log_path must be populated");
    let p = std::path::Path::new(&log_path);
    assert!(p.exists(), "expected JSONL log at {log_path}");
    assert_eq!(p.extension().and_then(|e| e.to_str()), Some("jsonl"));
}

#[tokio::test]
async fn test_on_log_event_receives_lifecycle_events() {
    let _guard = ScopedLogsDir::new();
    let counter = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let counter_clone = counter.clone();

    let output = AgentBuilder::new()
        .provider("mock")
        .on_log_event(move |_ev| {
            counter_clone.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        })
        .exec("hi")
        .await
        .unwrap();

    // Should have seen at least SessionStarted + SessionEnded.
    assert!(
        counter.load(std::sync::atomic::Ordering::SeqCst) >= 2,
        "expected at least 2 log events, got {}",
        counter.load(std::sync::atomic::Ordering::SeqCst)
    );
    assert!(output.log_path.is_some());
}

#[tokio::test]
async fn test_on_log_event_implicitly_enables_session_log() {
    let _guard = ScopedLogsDir::new();
    let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
    let seen_clone = seen.clone();

    AgentBuilder::new()
        .provider("mock")
        // Deliberately do not call .enable_session_log(true) — the
        // callback must flip it on implicitly.
        .on_log_event(move |ev| {
            let kind = crate::listen::event_type_name(&ev.kind).to_string();
            seen_clone.lock().unwrap().push(kind);
        })
        .exec("hi")
        .await
        .unwrap();

    let events = seen.lock().unwrap();
    assert!(
        events.iter().any(|k| k == "session_started"),
        "expected session_started event, got: {events:?}"
    );
}

#[tokio::test]
async fn test_stream_events_to_stderr_implicitly_enables_session_log() {
    let _guard = ScopedLogsDir::new();
    let output = AgentBuilder::new()
        .provider("mock")
        .stream_events_to_stderr(crate::listen::ListenFormat::Text)
        .exec("hi")
        .await
        .unwrap();
    assert!(output.log_path.is_some(), "stream setter must enable log");
}