gemini-cli-sdk 0.1.0

Rust SDK wrapping Google's Gemini CLI as a subprocess via JSON-RPC 2.0
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
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
//! Client configuration.
//!
//! The primary entry point for configuring a Gemini CLI session is
//! [`ClientConfig`], built via the [`TypedBuilder`]-derived builder pattern.
//!
//! # Example
//!
//! ```rust,no_run
//! use gemini_cli_sdk::config::{ClientConfig, PermissionMode};
//!
//! let config = ClientConfig::builder()
//!     .prompt("Summarise the repo")
//!     .model("gemini-2.5-pro")
//!     .permission_mode(PermissionMode::AcceptEdits)
//!     .build();
//!
//! let args = config.to_cli_args();
//! assert!(args.contains(&"--approval-mode".to_string()));
//! ```

use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;

use crate::hooks::HookMatcher;
use crate::mcp::McpServers;
use crate::permissions::CanUseToolCallback;

// Re-export `MessageCallback` so callers can import it from this module,
// mirroring the claude-cli-sdk API surface.
pub use crate::callback::MessageCallback;

// ── ClientConfig ────────────────────────────────────────────────────────────

/// Full configuration for a Gemini CLI session.
///
/// Built with the [`TypedBuilder`] pattern. Only `prompt` is required; all
/// other fields have sensible defaults. Gemini-specific fields (`auth_method`,
/// `sandbox`, `extra_args`) extend the common set.
///
/// # Example
///
/// ```rust,no_run
/// use gemini_cli_sdk::config::{ClientConfig, AuthMethod};
///
/// let config = ClientConfig::builder()
///     .prompt("Hello, Gemini!")
///     .model("gemini-2.5-flash")
///     .auth_method(AuthMethod::ApiKey)
///     .verbose(true)
///     .build();
/// ```
#[derive(TypedBuilder)]
pub struct ClientConfig {
    // ── Required ────────────────────────────────────────────────────────────

    /// The prompt text sent to the CLI.
    #[builder(setter(into))]
    pub prompt: String,

    // ── CLI process ─────────────────────────────────────────────────────────

    /// Override the path to the `gemini` CLI binary.
    /// When `None`, the binary is located via `PATH` using [`which`].
    #[builder(default, setter(strip_option))]
    pub cli_path: Option<PathBuf>,

    /// Working directory for the CLI subprocess.
    /// Defaults to the current process's working directory when `None`.
    #[builder(default, setter(strip_option))]
    pub cwd: Option<PathBuf>,

    // ── Model ───────────────────────────────────────────────────────────────

    /// Gemini model identifier (e.g., `"gemini-2.5-pro"`).
    #[builder(default, setter(strip_option, into))]
    pub model: Option<String>,

    // ── Session behaviour ────────────────────────────────────────────────────

    /// Custom system prompt injected into the session.
    #[builder(default, setter(strip_option))]
    pub system_prompt: Option<SystemPrompt>,

    /// Maximum number of agentic turns before the session is terminated.
    #[builder(default, setter(strip_option))]
    pub max_turns: Option<u32>,

    // ── Tools ───────────────────────────────────────────────────────────────

    /// Tool names the CLI is explicitly permitted to use.
    /// An empty list means all tools are allowed (subject to `disallowed_tools`).
    #[builder(default)]
    pub allowed_tools: Vec<String>,

    /// Tool names that are always denied, overriding `allowed_tools`.
    #[builder(default)]
    pub disallowed_tools: Vec<String>,

    // ── Permissions ──────────────────────────────────────────────────────────

    /// Global permission mode passed to the CLI via approval-mode flags.
    #[builder(default)]
    pub permission_mode: PermissionMode,

    /// Fine-grained per-tool permission callback, evaluated before each tool
    /// execution. Takes precedence over `permission_mode` for individual calls.
    #[builder(default, setter(strip_option))]
    pub can_use_tool: Option<CanUseToolCallback>,

    // ── Session resume ───────────────────────────────────────────────────────

    /// Session ID to resume. When set, the CLI is invoked with `--resume`.
    #[builder(default, setter(strip_option, into))]
    pub resume: Option<String>,

    // ── Hooks ────────────────────────────────────────────────────────────────

    /// Event hooks that fire at defined points in the session lifecycle.
    #[builder(default)]
    pub hooks: Vec<HookMatcher>,

    // ── MCP ─────────────────────────────────────────────────────────────────

    /// MCP server configurations forwarded to the CLI at session creation.
    #[builder(default)]
    pub mcp_servers: McpServers,

    // ── Callbacks ────────────────────────────────────────────────────────────

    /// Optional callback invoked for each message before it is yielded to the
    /// stream. Suitable for logging, persistence, or UI updates.
    #[builder(default, setter(strip_option))]
    pub message_callback: Option<MessageCallback>,

    // ── Process environment ──────────────────────────────────────────────────

    /// Additional environment variables injected into the CLI subprocess.
    #[builder(default)]
    pub env: HashMap<String, String>,

    /// Enable verbose CLI output (passes the `--debug` flag, or equivalent).
    #[builder(default)]
    pub verbose: bool,

    // ── Gemini-specific ──────────────────────────────────────────────────────

    /// Authentication method for the Gemini CLI.
    ///
    /// Auth is configured via environment variables rather than CLI flags:
    /// - [`LoginWithGoogle`] — expects the user to have run `gemini auth login`.
    /// - [`ApiKey`] — reads `GEMINI_API_KEY` from the environment.
    /// - [`VertexAi`] — reads `GOOGLE_CLOUD_PROJECT` + ADC credentials.
    ///
    /// This field does **not** generate CLI arguments in `to_cli_args()`.
    ///
    /// [`LoginWithGoogle`]: AuthMethod::LoginWithGoogle
    /// [`ApiKey`]: AuthMethod::ApiKey
    /// [`VertexAi`]: AuthMethod::VertexAi
    #[builder(default, setter(strip_option))]
    pub auth_method: Option<AuthMethod>,

    /// Run the session inside a sandbox.
    #[builder(default)]
    pub sandbox: bool,

    /// Arbitrary extra CLI flags. The map key becomes `--{key}`, the optional
    /// value is appended as a separate argument when `Some`.
    #[builder(default)]
    pub extra_args: BTreeMap<String, Option<String>>,

    // ── Timeouts ─────────────────────────────────────────────────────────────

    /// Timeout for the initial JSON-RPC connection handshake.
    #[builder(default_code = "Some(Duration::from_secs(30))")]
    pub connect_timeout: Option<Duration>,

    /// Grace period allowed for the CLI process to exit cleanly on shutdown.
    #[builder(default_code = "Some(Duration::from_secs(10))")]
    pub close_timeout: Option<Duration>,

    /// Per-read timeout on the stdio transport. `None` means no timeout.
    ///
    /// **Note:** This field is accepted for forward-compatibility but is not yet
    /// enforced by the transport layer. It is reserved for a future release.
    #[builder(default)]
    pub read_timeout: Option<Duration>,

    /// Default timeout budget given to each hook execution.
    #[builder(default_code = "Duration::from_secs(30)")]
    pub default_hook_timeout: Duration,

    /// Timeout for the background CLI version check. `None` skips the check.
    ///
    /// **Note:** This field is accepted for forward-compatibility but is not yet
    /// enforced by the transport layer. It is reserved for a future release.
    #[builder(default_code = "Some(Duration::from_secs(5))")]
    pub version_check_timeout: Option<Duration>,

    // ── Diagnostics ──────────────────────────────────────────────────────────

    /// Optional callback that receives every line written to the CLI's stderr.
    /// Useful for surfacing CLI-level warnings and errors to callers.
    #[builder(default, setter(strip_option))]
    pub stderr_callback: Option<Arc<dyn Fn(String) + Send + Sync>>,
}

impl ClientConfig {
    /// Translate this configuration into CLI arguments for the Gemini binary.
    ///
    /// The ACP mode flag (`--experimental-acp`) is always prepended. Remaining
    /// flags are derived from the fields that have non-default values.
    ///
    /// # Example
    ///
    /// ```rust
    /// use gemini_cli_sdk::config::{ClientConfig, PermissionMode};
    ///
    /// let config = ClientConfig::builder()
    ///     .prompt("test")
    ///     .permission_mode(PermissionMode::BypassPermissions)
    ///     .build();
    ///
    /// let args = config.to_cli_args();
    /// assert!(args.contains(&"--yolo".to_string()));
    /// ```
    pub fn to_cli_args(&self) -> Vec<String> {
        let mut args = vec!["--experimental-acp".to_string()];

        if let Some(model) = &self.model {
            args.push("--model".to_string());
            args.push(model.clone());
        }

        if self.sandbox {
            args.push("--sandbox".to_string());
        }

        match self.permission_mode {
            PermissionMode::Default => {}
            PermissionMode::AcceptEdits => {
                args.push("--approval-mode".to_string());
                args.push("auto_edit".to_string());
            }
            PermissionMode::Plan => {
                args.push("--approval-mode".to_string());
                args.push("plan".to_string());
            }
            PermissionMode::BypassPermissions => {
                args.push("--yolo".to_string());
            }
        }

        if self.verbose {
            args.push("--debug".to_string());
        }

        if let Some(turns) = self.max_turns {
            args.push("--max-turns".to_string());
            args.push(turns.to_string());
        }

        if let Some(sp) = &self.system_prompt {
            match sp {
                SystemPrompt::Text(text) => {
                    args.push("--system-prompt".to_string());
                    args.push(text.clone());
                }
                SystemPrompt::File(path) => {
                    args.push("--system-prompt-file".to_string());
                    args.push(path.to_string_lossy().to_string());
                }
            }
        }

        if !self.allowed_tools.is_empty() {
            args.push("--allowed-tools".to_string());
            args.push(self.allowed_tools.join(","));
        }

        if !self.disallowed_tools.is_empty() {
            args.push("--disallowed-tools".to_string());
            args.push(self.disallowed_tools.join(","));
        }

        for (key, value) in &self.extra_args {
            args.push(format!("--{key}"));
            if let Some(v) = value {
                args.push(v.clone());
            }
        }

        args
    }
}

// ── AuthMethod ───────────────────────────────────────────────────────────────

/// Authentication method passed to the Gemini CLI.
///
/// Determines how the CLI authenticates with Google's APIs. The default
/// (when `None` is set on [`ClientConfig`]) defers to the CLI's own
/// credential resolution order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthMethod {
    /// Interactive OAuth 2.0 flow — opens a browser window on first run.
    LoginWithGoogle,
    /// API key passed via the `GEMINI_API_KEY` environment variable.
    ApiKey,
    /// Vertex AI service account credentials.
    VertexAi,
}

// ── PermissionMode ───────────────────────────────────────────────────────────

/// Global permission mode controlling how the CLI handles tool approval.
///
/// Corresponds to the `--approval-mode` CLI flag, with [`BypassPermissions`]
/// mapping to `--yolo` for compatibility with the Gemini CLI's flag naming.
///
/// [`BypassPermissions`]: PermissionMode::BypassPermissions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PermissionMode {
    /// Default interactive approval — prompts for confirmation before tools run.
    #[default]
    Default,
    /// Automatically approve edit operations without prompting.
    AcceptEdits,
    /// Plan-only mode — the CLI describes actions but does not execute them.
    Plan,
    /// Skip all approval prompts. Use with caution in automated environments.
    BypassPermissions,
}

// ── SystemPrompt ─────────────────────────────────────────────────────────────

/// System prompt configuration.
///
/// The system prompt is injected into the session before the user's first
/// message. It can be provided as inline text or as a path to a file on disk
/// (which the CLI reads at startup).
#[derive(Debug, Clone)]
pub enum SystemPrompt {
    /// Inline system prompt text.
    Text(String),
    /// Path to a file containing the system prompt.
    File(PathBuf),
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::{AuthMethod, ClientConfig, PermissionMode};

    // ── Builder construction ─────────────────────────────────────────────────

    #[test]
    fn test_config_builder_minimal() {
        // Only the required `prompt` field is set — all other fields take
        // their defaults. This verifies the builder compiles and produces a
        // valid struct without panicking.
        let config = ClientConfig::builder().prompt("test").build();
        assert_eq!(config.prompt, "test");
        assert!(config.cli_path.is_none());
        assert!(config.model.is_none());
        assert!(config.cwd.is_none());
        assert!(config.allowed_tools.is_empty());
        assert!(config.disallowed_tools.is_empty());
        assert!(config.hooks.is_empty());
        assert!(config.mcp_servers.is_empty());
        assert!(!config.sandbox);
        assert!(!config.verbose);
    }

    #[test]
    fn test_config_builder_with_model() {
        let config = ClientConfig::builder()
            .prompt("hello")
            .model("gemini-2.5-pro")
            .build();

        assert_eq!(config.model.as_deref(), Some("gemini-2.5-pro"));
    }

    // ── to_cli_args ──────────────────────────────────────────────────────────

    #[test]
    fn test_to_cli_args_default() {
        // Default config produces only the mandatory ACP flag.
        let config = ClientConfig::builder().prompt("test").build();
        let args = config.to_cli_args();
        assert_eq!(args, vec!["--experimental-acp"]);
    }

    #[test]
    fn test_to_cli_args_with_model() {
        let config = ClientConfig::builder()
            .prompt("test")
            .model("gemini-2.5-flash")
            .build();
        let args = config.to_cli_args();
        assert!(
            args.contains(&"--model".to_string()),
            "expected --model flag"
        );
        assert!(
            args.contains(&"gemini-2.5-flash".to_string()),
            "expected model value"
        );
        // Flags must be adjacent: --model <value>
        let model_pos = args.iter().position(|a| a == "--model").unwrap();
        assert_eq!(args[model_pos + 1], "gemini-2.5-flash");
    }

    #[test]
    fn test_to_cli_args_accept_edits() {
        let config = ClientConfig::builder()
            .prompt("test")
            .permission_mode(PermissionMode::AcceptEdits)
            .build();
        let args = config.to_cli_args();
        assert!(
            args.contains(&"--approval-mode".to_string()),
            "expected --approval-mode"
        );
        assert!(
            args.contains(&"auto_edit".to_string()),
            "expected auto_edit value"
        );
        let pos = args.iter().position(|a| a == "--approval-mode").unwrap();
        assert_eq!(args[pos + 1], "auto_edit");
    }

    #[test]
    fn test_to_cli_args_plan_mode() {
        let config = ClientConfig::builder()
            .prompt("test")
            .permission_mode(PermissionMode::Plan)
            .build();
        let args = config.to_cli_args();
        let pos = args.iter().position(|a| a == "--approval-mode").unwrap();
        assert_eq!(args[pos + 1], "plan");
    }

    #[test]
    fn test_to_cli_args_bypass() {
        let config = ClientConfig::builder()
            .prompt("test")
            .permission_mode(PermissionMode::BypassPermissions)
            .build();
        let args = config.to_cli_args();
        assert!(
            args.contains(&"--yolo".to_string()),
            "BypassPermissions must map to --yolo"
        );
        // --yolo and --approval-mode are mutually exclusive paths — ensure no
        // approval-mode flag leaks through alongside --yolo.
        assert!(
            !args.contains(&"--approval-mode".to_string()),
            "--approval-mode must not appear alongside --yolo"
        );
    }

    #[test]
    fn test_to_cli_args_sandbox() {
        let config = ClientConfig::builder()
            .prompt("test")
            .sandbox(true)
            .build();
        let args = config.to_cli_args();
        assert!(
            args.contains(&"--sandbox".to_string()),
            "sandbox=true must emit --sandbox"
        );
    }

    #[test]
    fn test_to_cli_args_sandbox_false_omitted() {
        // sandbox defaults to false; the flag must not appear.
        let config = ClientConfig::builder().prompt("test").build();
        let args = config.to_cli_args();
        assert!(
            !args.contains(&"--sandbox".to_string()),
            "--sandbox must not appear when sandbox=false"
        );
    }

    #[test]
    fn test_to_cli_args_extra() {
        let mut extra = BTreeMap::new();
        extra.insert("temperature".to_string(), Some("0.7".to_string()));
        extra.insert("top-p".to_string(), None);

        let config = ClientConfig::builder()
            .prompt("test")
            .extra_args(extra)
            .build();
        let args = config.to_cli_args();

        assert!(
            args.contains(&"--temperature".to_string()),
            "extra key must become --<key>"
        );
        assert!(
            args.contains(&"0.7".to_string()),
            "extra value must appear as a separate arg"
        );
        assert!(
            args.contains(&"--top-p".to_string()),
            "flag-only extra arg must appear without a value"
        );
    }

    #[test]
    fn test_to_cli_args_extra_btreemap_ordering() {
        // BTreeMap is sorted alphabetically; verify the output order is stable.
        let mut extra = BTreeMap::new();
        extra.insert("zzz".to_string(), Some("last".to_string()));
        extra.insert("aaa".to_string(), Some("first".to_string()));

        let config = ClientConfig::builder()
            .prompt("test")
            .extra_args(extra)
            .build();
        let args = config.to_cli_args();

        // --experimental-acp comes first; then aaa, then zzz (alpha order).
        let aaa_pos = args.iter().position(|a| a == "--aaa").unwrap();
        let zzz_pos = args.iter().position(|a| a == "--zzz").unwrap();
        assert!(aaa_pos < zzz_pos, "--aaa must precede --zzz (BTreeMap order)");
    }

    // ── PermissionMode ───────────────────────────────────────────────────────

    #[test]
    fn test_permission_mode_default() {
        assert_eq!(
            PermissionMode::default(),
            PermissionMode::Default,
            "Default must be the zero-value for PermissionMode"
        );
    }

    #[test]
    fn test_permission_mode_debug() {
        // Ensure all variants have a Debug impl (derived).
        let _ = format!("{:?}", PermissionMode::Default);
        let _ = format!("{:?}", PermissionMode::AcceptEdits);
        let _ = format!("{:?}", PermissionMode::Plan);
        let _ = format!("{:?}", PermissionMode::BypassPermissions);
    }

    // ── AuthMethod ───────────────────────────────────────────────────────────

    #[test]
    fn test_auth_method_serde_roundtrip() {
        for variant in [
            AuthMethod::LoginWithGoogle,
            AuthMethod::ApiKey,
            AuthMethod::VertexAi,
        ] {
            let json = serde_json::to_string(&variant).expect("serialize");
            let recovered: AuthMethod = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(variant, recovered, "serde roundtrip failed for {json}");
        }
    }

    #[test]
    fn test_auth_method_partial_eq() {
        assert_eq!(AuthMethod::ApiKey, AuthMethod::ApiKey);
        assert_ne!(AuthMethod::ApiKey, AuthMethod::VertexAi);
    }

    // ── Timeouts ─────────────────────────────────────────────────────────────

    #[test]
    fn test_default_timeouts() {
        let config = ClientConfig::builder().prompt("test").build();
        assert_eq!(
            config.connect_timeout,
            Some(std::time::Duration::from_secs(30)),
            "connect_timeout default must be 30 s"
        );
        assert_eq!(
            config.close_timeout,
            Some(std::time::Duration::from_secs(10)),
            "close_timeout default must be 10 s"
        );
        assert_eq!(
            config.default_hook_timeout,
            std::time::Duration::from_secs(30),
            "hook timeout default must be 30 s"
        );
        assert_eq!(
            config.version_check_timeout,
            Some(std::time::Duration::from_secs(5)),
            "version_check_timeout default must be 5 s"
        );
        assert!(
            config.read_timeout.is_none(),
            "read_timeout must default to None"
        );
    }

    // ── Verbose flag ─────────────────────────────────────────────────────────

    #[test]
    fn test_to_cli_args_verbose() {
        let config = ClientConfig::builder()
            .prompt("test")
            .verbose(true)
            .build();
        let args = config.to_cli_args();
        assert!(
            args.contains(&"--debug".to_string()),
            "verbose=true must emit --debug"
        );
    }

    #[test]
    fn test_to_cli_args_verbose_false_omitted() {
        let config = ClientConfig::builder().prompt("test").build();
        let args = config.to_cli_args();
        assert!(
            !args.contains(&"--debug".to_string()),
            "--debug must not appear when verbose=false"
        );
    }

    #[test]
    fn test_to_cli_args_max_turns() {
        let config = ClientConfig::builder()
            .prompt("test")
            .max_turns(5_u32)
            .build();
        let args = config.to_cli_args();
        let pos = args.iter().position(|a| a == "--max-turns").expect("--max-turns missing");
        assert_eq!(args[pos + 1], "5");
    }

    #[test]
    fn test_to_cli_args_system_prompt_text() {
        let config = ClientConfig::builder()
            .prompt("test")
            .system_prompt(crate::config::SystemPrompt::Text("You are helpful.".to_string()))
            .build();
        let args = config.to_cli_args();
        let pos = args.iter().position(|a| a == "--system-prompt").expect("--system-prompt missing");
        assert_eq!(args[pos + 1], "You are helpful.");
    }

    #[test]
    fn test_to_cli_args_system_prompt_file() {
        let config = ClientConfig::builder()
            .prompt("test")
            .system_prompt(crate::config::SystemPrompt::File(
                std::path::PathBuf::from("/etc/prompt.txt"),
            ))
            .build();
        let args = config.to_cli_args();
        let pos = args.iter().position(|a| a == "--system-prompt-file").expect("--system-prompt-file missing");
        assert_eq!(args[pos + 1], "/etc/prompt.txt");
    }

    #[test]
    fn test_to_cli_args_allowed_tools() {
        let config = ClientConfig::builder()
            .prompt("test")
            .allowed_tools(vec!["read_file".to_string(), "write_file".to_string()])
            .build();
        let args = config.to_cli_args();
        let pos = args.iter().position(|a| a == "--allowed-tools").expect("--allowed-tools missing");
        assert_eq!(args[pos + 1], "read_file,write_file");
    }

    #[test]
    fn test_to_cli_args_disallowed_tools() {
        let config = ClientConfig::builder()
            .prompt("test")
            .disallowed_tools(vec!["shell".to_string()])
            .build();
        let args = config.to_cli_args();
        let pos = args.iter().position(|a| a == "--disallowed-tools").expect("--disallowed-tools missing");
        assert_eq!(args[pos + 1], "shell");
    }

    #[test]
    fn test_to_cli_args_empty_tool_lists_omitted() {
        // Default (empty) lists must NOT emit any flags.
        let config = ClientConfig::builder().prompt("test").build();
        let args = config.to_cli_args();
        assert!(!args.contains(&"--allowed-tools".to_string()));
        assert!(!args.contains(&"--disallowed-tools".to_string()));
    }

    // ── experimental-acp always present ─────────────────────────────────────

    #[test]
    fn test_to_cli_args_always_has_acp_flag() {
        // Regardless of other settings, the ACP flag is always the first arg.
        let config = ClientConfig::builder()
            .prompt("p")
            .model("gemini-2.5-pro")
            .sandbox(true)
            .permission_mode(PermissionMode::BypassPermissions)
            .build();
        let args = config.to_cli_args();
        assert_eq!(
            args[0], "--experimental-acp",
            "--experimental-acp must always be the first argument"
        );
    }
}