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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! High-level builder API for driving agents programmatically.
//!
//! Instead of shelling out to the `agent` CLI binary, Rust programs can
//! use `AgentBuilder` to configure and execute agent sessions directly.
//!
//! # Examples
//!
//! ```no_run
//! use zag_agent::builder::AgentBuilder;
//!
//! # async fn example() -> anyhow::Result<()> {
//! // Non-interactive exec — returns structured output
//! let output = AgentBuilder::new()
//! .provider("claude")
//! .model("sonnet")
//! .auto_approve(true)
//! .exec("write a hello world program")
//! .await?;
//!
//! println!("{}", output.result.unwrap_or_default());
//!
//! // Interactive session
//! AgentBuilder::new()
//! .provider("claude")
//! .run(Some("initial prompt"))
//! .await?;
//! # Ok(())
//! # }
//! ```
use crate::agent::Agent;
use crate::attachment::{self, Attachment};
use crate::config::Config;
use crate::factory::AgentFactory;
use crate::json_validation;
use crate::output::AgentOutput;
use crate::progress::{ProgressHandler, SilentProgress};
use crate::providers::claude::Claude;
use crate::providers::ollama::Ollama;
use crate::sandbox::SandboxConfig;
use crate::streaming::StreamingSession;
use crate::worktree;
use anyhow::{Result, bail};
use log::{debug, warn};
use std::time::Duration;
/// Format a Duration as a human-readable string (e.g., "5m", "1h30m").
fn format_duration(d: Duration) -> String {
let total_secs = d.as_secs();
let h = total_secs / 3600;
let m = (total_secs % 3600) / 60;
let s = total_secs % 60;
let mut parts = Vec::new();
if h > 0 {
parts.push(format!("{h}h"));
}
if m > 0 {
parts.push(format!("{m}m"));
}
if s > 0 || parts.is_empty() {
parts.push(format!("{s}s"));
}
parts.join("")
}
/// Builder for configuring and running agent sessions.
///
/// Use the builder pattern to set options, then call a terminal method
/// (`exec`, `run`, `resume`, `continue_last`) to execute.
pub struct AgentBuilder {
provider: Option<String>,
/// Set to true when the caller explicitly pinned a provider via
/// `.provider()`. When false (default), the fallback tier list is
/// allowed to downgrade to the next provider on binary/probe failure.
provider_explicit: bool,
model: Option<String>,
system_prompt: Option<String>,
root: Option<String>,
auto_approve: bool,
add_dirs: Vec<String>,
files: Vec<String>,
env_vars: Vec<(String, String)>,
worktree: Option<Option<String>>,
sandbox: Option<Option<String>>,
size: Option<String>,
json_mode: bool,
json_schema: Option<serde_json::Value>,
session_id: Option<String>,
output_format: Option<String>,
input_format: Option<String>,
replay_user_messages: bool,
include_partial_messages: bool,
verbose: bool,
quiet: bool,
show_usage: bool,
max_turns: Option<u32>,
timeout: Option<std::time::Duration>,
mcp_config: Option<String>,
progress: Box<dyn ProgressHandler>,
}
impl Default for AgentBuilder {
fn default() -> Self {
Self::new()
}
}
impl AgentBuilder {
/// Create a new builder with default settings.
pub fn new() -> Self {
Self {
provider: None,
provider_explicit: false,
model: None,
system_prompt: None,
root: None,
auto_approve: false,
add_dirs: Vec::new(),
files: Vec::new(),
env_vars: Vec::new(),
worktree: None,
sandbox: None,
size: None,
json_mode: false,
json_schema: None,
session_id: None,
output_format: None,
input_format: None,
replay_user_messages: false,
include_partial_messages: false,
verbose: false,
quiet: false,
show_usage: false,
max_turns: None,
timeout: None,
mcp_config: None,
progress: Box::new(SilentProgress),
}
}
/// Set the provider (e.g., "claude", "codex", "gemini", "copilot", "ollama").
///
/// Calling this method pins the provider — it will NOT be downgraded to
/// another provider in the tier list if its binary is missing or the
/// startup probe fails. Omit this call (or set `provider` via the config
/// file) to allow automatic downgrading.
pub fn provider(mut self, provider: &str) -> Self {
self.provider = Some(provider.to_string());
self.provider_explicit = true;
self
}
/// Set the model (e.g., "sonnet", "opus", "small", "large").
pub fn model(mut self, model: &str) -> Self {
self.model = Some(model.to_string());
self
}
/// Set a system prompt to configure agent behavior.
pub fn system_prompt(mut self, prompt: &str) -> Self {
self.system_prompt = Some(prompt.to_string());
self
}
/// Set the root directory for the agent to operate in.
pub fn root(mut self, root: &str) -> Self {
self.root = Some(root.to_string());
self
}
/// Enable auto-approve mode (skip permission prompts).
pub fn auto_approve(mut self, approve: bool) -> Self {
self.auto_approve = approve;
self
}
/// Add an additional directory for the agent to include.
pub fn add_dir(mut self, dir: &str) -> Self {
self.add_dirs.push(dir.to_string());
self
}
/// Attach a file to the prompt (text files ≤50 KB inlined, others referenced).
pub fn file(mut self, path: &str) -> Self {
self.files.push(path.to_string());
self
}
/// Add an environment variable for the agent subprocess.
pub fn env(mut self, key: &str, value: &str) -> Self {
self.env_vars.push((key.to_string(), value.to_string()));
self
}
/// Enable worktree mode with an optional name.
pub fn worktree(mut self, name: Option<&str>) -> Self {
self.worktree = Some(name.map(String::from));
self
}
/// Enable sandbox mode with an optional name.
pub fn sandbox(mut self, name: Option<&str>) -> Self {
self.sandbox = Some(name.map(String::from));
self
}
/// Set the Ollama parameter size (e.g., "2b", "9b", "35b").
pub fn size(mut self, size: &str) -> Self {
self.size = Some(size.to_string());
self
}
/// Request JSON output from the agent.
pub fn json(mut self) -> Self {
self.json_mode = true;
self
}
/// Set a JSON schema for structured output validation.
/// Implies `json()`.
pub fn json_schema(mut self, schema: serde_json::Value) -> Self {
self.json_schema = Some(schema);
self.json_mode = true;
self
}
/// Set a specific session ID (UUID).
pub fn session_id(mut self, id: &str) -> Self {
self.session_id = Some(id.to_string());
self
}
/// Set the output format (e.g., "text", "json", "json-pretty", "stream-json").
pub fn output_format(mut self, format: &str) -> Self {
self.output_format = Some(format.to_string());
self
}
/// Set the input format (Claude only, e.g., "text", "stream-json").
///
/// No-op for Codex, Gemini, Copilot, and Ollama. See `docs/providers.md`
/// for the full per-provider support matrix.
pub fn input_format(mut self, format: &str) -> Self {
self.input_format = Some(format.to_string());
self
}
/// Re-emit user messages from stdin on stdout (Claude only).
///
/// Only works with `--input-format stream-json` and `--output-format stream-json`.
/// [`exec_streaming`](Self::exec_streaming) auto-enables this flag, so most
/// callers never need to set it manually. No-op for non-Claude providers.
pub fn replay_user_messages(mut self, replay: bool) -> Self {
self.replay_user_messages = replay;
self
}
/// Include partial message chunks in streaming output (Claude only).
///
/// Only works with `--output-format stream-json`. Defaults to `false`.
///
/// When `false` (the default), streaming surfaces one `assistant_message`
/// event per complete assistant turn. When `true`, the agent instead emits
/// a stream of token-level partial `assistant_message` chunks as the model
/// generates them — use this for responsive, token-by-token UIs over
/// [`exec_streaming`](Self::exec_streaming). No-op for non-Claude providers.
pub fn include_partial_messages(mut self, include: bool) -> Self {
self.include_partial_messages = include;
self
}
/// Enable verbose output.
pub fn verbose(mut self, v: bool) -> Self {
self.verbose = v;
self
}
/// Enable quiet mode (suppress all non-essential output).
pub fn quiet(mut self, q: bool) -> Self {
self.quiet = q;
self
}
/// Show token usage statistics.
pub fn show_usage(mut self, show: bool) -> Self {
self.show_usage = show;
self
}
/// Set the maximum number of agentic turns.
pub fn max_turns(mut self, turns: u32) -> Self {
self.max_turns = Some(turns);
self
}
/// Set a timeout for exec. If the agent doesn't complete within this
/// duration, it will be killed and an error returned.
pub fn timeout(mut self, duration: std::time::Duration) -> Self {
self.timeout = Some(duration);
self
}
/// Set MCP server config for this invocation (Claude only).
///
/// Accepts either a JSON string (`{"mcpServers": {...}}`) or a path to a JSON file.
/// No-op for Codex, Gemini, Copilot, and Ollama — those providers manage
/// MCP configuration through their own CLIs or do not support it. See
/// `docs/providers.md` for the full per-provider support matrix.
pub fn mcp_config(mut self, config: &str) -> Self {
self.mcp_config = Some(config.to_string());
self
}
/// Set a custom progress handler for status reporting.
pub fn on_progress(mut self, handler: Box<dyn ProgressHandler>) -> Self {
self.progress = handler;
self
}
/// Resolve file attachments and prepend them to a prompt.
fn prepend_files(&self, prompt: &str) -> Result<String> {
if self.files.is_empty() {
return Ok(prompt.to_string());
}
let attachments: Vec<Attachment> = self
.files
.iter()
.map(|f| Attachment::from_path(std::path::Path::new(f)))
.collect::<Result<Vec<_>>>()?;
let prefix = attachment::format_attachments_prefix(&attachments);
Ok(format!("{}{}", prefix, prompt))
}
/// Resolve the effective provider name.
fn resolve_provider(&self) -> Result<String> {
if let Some(ref p) = self.provider {
let p = p.to_lowercase();
if !Config::VALID_PROVIDERS.contains(&p.as_str()) {
bail!(
"Invalid provider '{}'. Available: {}",
p,
Config::VALID_PROVIDERS.join(", ")
);
}
return Ok(p);
}
let config = Config::load(self.root.as_deref()).unwrap_or_default();
if let Some(p) = config.provider() {
return Ok(p.to_string());
}
Ok("claude".to_string())
}
/// Create and configure the agent.
///
/// Returns the constructed agent along with the provider name that
/// actually succeeded. When `provider_explicit` is false, the factory
/// may downgrade to another provider in the tier list, so the returned
/// provider can differ from the one passed in.
async fn create_agent(&self, provider: &str) -> Result<(Box<dyn Agent + Send + Sync>, String)> {
// Apply system_prompt config fallback
let base_system_prompt = self.system_prompt.clone().or_else(|| {
Config::load(self.root.as_deref())
.unwrap_or_default()
.system_prompt()
.map(String::from)
});
// Augment system prompt with JSON instructions for non-Claude agents
let system_prompt = if self.json_mode && provider != "claude" {
let mut prompt = base_system_prompt.unwrap_or_default();
if let Some(ref schema) = self.json_schema {
let schema_str = serde_json::to_string_pretty(schema).unwrap_or_default();
prompt.push_str(&format!(
"\n\nYou MUST respond with valid JSON only. No markdown fences, no explanations. \
Your response must conform to this JSON schema:\n{}",
schema_str
));
} else {
prompt.push_str(
"\n\nYou MUST respond with valid JSON only. No markdown fences, no explanations.",
);
}
Some(prompt)
} else {
base_system_prompt
};
self.progress
.on_spinner_start(&format!("Initializing {} agent", provider));
let progress = &*self.progress;
let mut on_downgrade = |from: &str, to: &str, reason: &str| {
progress.on_warning(&format!(
"Downgrading provider: {} → {} ({})",
from, to, reason
));
};
let (mut agent, effective_provider) = AgentFactory::create_with_fallback(
provider,
self.provider_explicit,
system_prompt,
self.model.clone(),
self.root.clone(),
self.auto_approve,
self.add_dirs.clone(),
&mut on_downgrade,
)
.await?;
let provider = effective_provider.as_str();
// Apply max_turns: explicit > config > none
let effective_max_turns = self.max_turns.or_else(|| {
Config::load(self.root.as_deref())
.unwrap_or_default()
.max_turns()
});
if let Some(turns) = effective_max_turns {
agent.set_max_turns(turns);
}
// Set output format
let mut output_format = self.output_format.clone();
if self.json_mode && output_format.is_none() {
output_format = Some("json".to_string());
if provider != "claude" {
agent.set_capture_output(true);
}
}
agent.set_output_format(output_format);
// Configure Claude-specific options
if provider == "claude"
&& let Some(claude_agent) = agent.as_any_mut().downcast_mut::<Claude>()
{
claude_agent.set_verbose(self.verbose);
if let Some(ref session_id) = self.session_id {
claude_agent.set_session_id(session_id.clone());
}
if let Some(ref input_fmt) = self.input_format {
claude_agent.set_input_format(Some(input_fmt.clone()));
}
if self.replay_user_messages {
claude_agent.set_replay_user_messages(true);
}
if self.include_partial_messages {
claude_agent.set_include_partial_messages(true);
}
if self.json_mode
&& let Some(ref schema) = self.json_schema
{
let schema_str = serde_json::to_string(schema).unwrap_or_default();
claude_agent.set_json_schema(Some(schema_str));
}
if self.mcp_config.is_some() {
claude_agent.set_mcp_config(self.mcp_config.clone());
}
}
// Configure Ollama-specific options
if provider == "ollama"
&& let Some(ollama_agent) = agent.as_any_mut().downcast_mut::<Ollama>()
{
let config = Config::load(self.root.as_deref()).unwrap_or_default();
if let Some(ref size) = self.size {
let resolved = config.ollama_size_for(size);
ollama_agent.set_size(resolved.to_string());
}
}
// Configure sandbox
if let Some(ref sandbox_opt) = self.sandbox {
let sandbox_name = sandbox_opt
.as_deref()
.map(String::from)
.unwrap_or_else(crate::sandbox::generate_name);
let template = crate::sandbox::template_for_provider(provider);
let workspace = self.root.clone().unwrap_or_else(|| ".".to_string());
agent.set_sandbox(SandboxConfig {
name: sandbox_name,
template: template.to_string(),
workspace,
});
}
if !self.env_vars.is_empty() {
agent.set_env_vars(self.env_vars.clone());
}
self.progress.on_spinner_finish();
self.progress.on_success(&format!(
"{} initialized with model {}",
provider,
agent.get_model()
));
Ok((agent, effective_provider))
}
/// Run the agent non-interactively and return structured output.
///
/// This is the primary entry point for programmatic use.
pub async fn exec(self, prompt: &str) -> Result<AgentOutput> {
let provider = self.resolve_provider()?;
debug!("exec: provider={}", provider);
// Set up worktree if requested
let effective_root = if let Some(ref wt_opt) = self.worktree {
let wt_name = wt_opt
.as_deref()
.map(String::from)
.unwrap_or_else(worktree::generate_name);
let repo_root = worktree::git_repo_root(self.root.as_deref())?;
let wt_path = worktree::create_worktree(&repo_root, &wt_name)?;
self.progress
.on_success(&format!("Worktree created at {}", wt_path.display()));
Some(wt_path.to_string_lossy().to_string())
} else {
self.root.clone()
};
let mut builder = self;
if effective_root.is_some() {
builder.root = effective_root;
}
let (agent, provider) = builder.create_agent(&provider).await?;
// Prepend file attachments
let prompt_with_files = builder.prepend_files(prompt)?;
// Handle JSON mode with prompt wrapping for non-Claude agents
let effective_prompt = if builder.json_mode && provider != "claude" {
format!(
"IMPORTANT: You MUST respond with valid JSON only. No markdown, no explanation.\n\n{}",
prompt_with_files
)
} else {
prompt_with_files
};
let result = if let Some(timeout_dur) = builder.timeout {
match tokio::time::timeout(timeout_dur, agent.run(Some(&effective_prompt))).await {
Ok(r) => r?,
Err(_) => {
agent.cleanup().await.ok();
bail!("Agent timed out after {}", format_duration(timeout_dur));
}
}
} else {
agent.run(Some(&effective_prompt)).await?
};
// Clean up
agent.cleanup().await?;
if let Some(output) = result {
// Validate JSON output if schema is provided
if let Some(ref schema) = builder.json_schema {
if !builder.json_mode {
warn!(
"json_schema is set but json_mode is false — \
schema will not be sent to the agent, only used for output validation"
);
}
if let Some(ref result_text) = output.result {
debug!(
"exec: validating result ({} bytes): {:.300}",
result_text.len(),
result_text
);
if let Err(errors) = json_validation::validate_json_schema(result_text, schema)
{
let preview = if result_text.len() > 500 {
&result_text[..500]
} else {
result_text.as_str()
};
bail!(
"JSON schema validation failed: {}\nRaw agent output ({} bytes):\n{}",
errors.join("; "),
result_text.len(),
preview
);
}
}
}
Ok(output)
} else {
// Agent returned no structured output — create a minimal one
Ok(AgentOutput::from_text(&provider, ""))
}
}
/// Run the agent with streaming input and output (Claude only).
///
/// Returns a [`StreamingSession`] that allows sending NDJSON messages to
/// the agent's stdin and reading events from stdout. Automatically
/// configures `--input-format stream-json`, `--output-format stream-json`,
/// and `--replay-user-messages`.
///
/// # Default emission granularity
///
/// By default `assistant_message` events are emitted **once per complete
/// assistant turn** — you get one event when the model finishes speaking,
/// not a stream of token chunks. For responsive, token-level UIs call
/// [`include_partial_messages(true)`](Self::include_partial_messages)
/// on the builder before `exec_streaming`; the session will then emit
/// partial `assistant_message` chunks as the model generates them.
///
/// The default is kept `false` so existing callers that render whole-turn
/// bubbles are not broken. See `docs/providers.md` for the full
/// per-provider flag support matrix.
///
/// # Event lifecycle
///
/// The session emits a unified
/// [`Event::Result`](crate::output::Event::Result) at the **end of every
/// agent turn** — not only at final session end. Use that event as the
/// authoritative turn-boundary signal. After a `Result`, the session
/// remains open and accepts another
/// [`send_user_message`](StreamingSession::send_user_message) for the next
/// turn. Call
/// [`close_input`](StreamingSession::close_input) followed by
/// [`wait`](StreamingSession::wait) to terminate the session cleanly.
///
/// Do not depend on replayed `user_message` events to detect turn
/// boundaries; those only appear while `--replay-user-messages` is set.
///
/// # Examples
///
/// ```no_run
/// use zag_agent::builder::AgentBuilder;
/// use zag_agent::output::Event;
///
/// # async fn example() -> anyhow::Result<()> {
/// let mut session = AgentBuilder::new()
/// .provider("claude")
/// .exec_streaming("initial prompt")
/// .await?;
///
/// // Drain the first turn until Result.
/// while let Some(event) = session.next_event().await? {
/// println!("{:?}", event);
/// if matches!(event, Event::Result { .. }) {
/// break;
/// }
/// }
///
/// // Follow-up turn.
/// session.send_user_message("do something else").await?;
/// while let Some(event) = session.next_event().await? {
/// if matches!(event, Event::Result { .. }) {
/// break;
/// }
/// }
///
/// session.close_input();
/// session.wait().await?;
/// # Ok(())
/// # }
/// ```
pub async fn exec_streaming(self, prompt: &str) -> Result<StreamingSession> {
let provider = self.resolve_provider()?;
debug!("exec_streaming: provider={}", provider);
if provider != "claude" {
bail!("Streaming input is only supported by the Claude provider");
}
// Prepend file attachments
let prompt_with_files = self.prepend_files(prompt)?;
// Streaming only works on Claude — do not allow the fallback loop
// to downgrade to a provider that can't stream.
let mut builder = self;
builder.provider_explicit = true;
let (agent, _provider) = builder.create_agent(&provider).await?;
// Downcast to Claude to call execute_streaming
let claude_agent = agent
.as_any_ref()
.downcast_ref::<Claude>()
.ok_or_else(|| anyhow::anyhow!("Failed to downcast agent to Claude"))?;
claude_agent.execute_streaming(Some(&prompt_with_files))
}
/// Start an interactive agent session.
///
/// This takes over stdin/stdout for the duration of the session.
pub async fn run(self, prompt: Option<&str>) -> Result<()> {
let provider = self.resolve_provider()?;
debug!("run: provider={}", provider);
// Prepend file attachments
let prompt_with_files = match prompt {
Some(p) => Some(self.prepend_files(p)?),
None if !self.files.is_empty() => {
let attachments: Vec<Attachment> = self
.files
.iter()
.map(|f| Attachment::from_path(std::path::Path::new(f)))
.collect::<Result<Vec<_>>>()?;
Some(attachment::format_attachments_prefix(&attachments))
}
None => None,
};
let (agent, _provider) = self.create_agent(&provider).await?;
agent.run_interactive(prompt_with_files.as_deref()).await?;
agent.cleanup().await?;
Ok(())
}
/// Resume a previous session by ID.
pub async fn resume(self, session_id: &str) -> Result<()> {
let provider = self.resolve_provider()?;
debug!("resume: provider={}, session={}", provider, session_id);
// Resuming must stick with the recorded provider — no downgrade.
let mut builder = self;
builder.provider_explicit = true;
let (agent, _provider) = builder.create_agent(&provider).await?;
agent.run_resume(Some(session_id), false).await?;
agent.cleanup().await?;
Ok(())
}
/// Resume the most recent session.
pub async fn continue_last(self) -> Result<()> {
let provider = self.resolve_provider()?;
debug!("continue_last: provider={}", provider);
// Resuming must stick with the recorded provider — no downgrade.
let mut builder = self;
builder.provider_explicit = true;
let (agent, _provider) = builder.create_agent(&provider).await?;
agent.run_resume(None, true).await?;
agent.cleanup().await?;
Ok(())
}
}
#[cfg(test)]
#[path = "builder_tests.rs"]
mod tests;