ailoy 0.3.3

Agents that drive a language model through tool-augmented turns, in a virtx console.
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
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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! A language model backed by the Gemini CLI in headless mode.
//!
//! Each call starts one `gemini` process, with no extensions (`-e none`), in
//! a project directory of its own: an empty temporary directory under a
//! directory private to the user ([`PROJECT_DIR`] under the user's cache
//! directory, see [`project_dir`]), holding only `.gemini/settings.json`.
//! These project settings take precedence over the user's (see
//! [`GeminiCliModel::settings`]): they keep the CLI's own tools and context
//! files out, declare the tools through a discovery command that prints the
//! file named by `AILOY_GEMINI_TOOLS`, add a `BeforeTool` hook that stops the
//! agent before any tool runs, with hooks on whatever the user's settings say,
//! disable the user's own hooks, and carry the call's model config. (They
//! are not system settings: gemini-cli 0.60.0 and later skip a system settings
//! file unless it and every directory above it belong to root.)
//!
//! The call's other files go in a second temporary directory:
//! - `system.md`, which replaces the CLI's system prompt (`GEMINI_SYSTEM_MD`);
//! - `tools.json`, the function declarations (`AILOY_GEMINI_TOOLS`);
//! - `session.jsonl`, the earlier turns as a session record (`--session-file`),
//!   with tool calls and results as function calls and responses.
//!
//! The latest user message goes to stdin, and the reply is read as one JSON
//! event per line from stdout (`--output-format stream-json`). The model
//! calls the tools as declared functions: each call is reported as a
//! `tool_use` event, the hook then stops the run, and the final `result`
//! event closes the reply with the calls and the usage of the reply's request.

use std::{path::Path, process::Stdio};

use anyhow::Context as _;
use futures::{
    StreamExt as _,
    future::BoxFuture,
    stream::{self, BoxStream},
};
use tokio::{
    io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _, BufReader},
    process::Command,
};

use super::gemini_api::inline_image;
use crate::{
    message::{
        Delta as _, FinishReason, Message, MessageDeltaOutput, MessageOutput, Part, PartDelta,
        PartDeltaFunction, Role, TokenUsage,
    },
    model::{InferLangModel, LangModelOptions, ThinkingEffort},
    tool::ToolDesc,
};

/// The directory the calls' project directories go in, under ailoy's directory in the user's cache.
const PROJECT_DIR: &str = "gemini";

/// The name of the hook that stops the agent, unique so the user's hooks can
/// be disabled by name without it.
const STOP_HOOK: &str = "ailoy-stop-before-tool";

/// The CLI's own tools, kept from the model. Names unknown to the installed
/// version are ignored. (`tools.core`, the CLI's allowlist, cannot be used
/// instead: it denies discovered tools too.)
const BUILTIN_TOOLS: &[&str] = &[
    "activate_skill",
    "ask_user",
    "complete_task",
    "enter_plan_mode",
    "exit_plan_mode",
    "get_internal_docs",
    "glob",
    "google_web_search",
    "grep_search",
    "invoke_agent",
    "list_background_processes",
    "list_directory",
    "list_mcp_resources",
    "read_background_output",
    "read_file",
    "read_many_files",
    "read_mcp_resource",
    "replace",
    "run_shell_command",
    "save_memory",
    "take_snapshot",
    "tracker_add_dependency",
    "tracker_create_task",
    "tracker_get_task",
    "tracker_list_tasks",
    "tracker_update_task",
    "tracker_visualize",
    "update_topic",
    "web_fetch",
    "write_file",
    "write_todos",
];

/// The prefix the CLI gives the names of discovered tools.
const TOOL_PREFIX: &str = "discovered_tool_";

/// The prompt when the conversation ends with tool results: the CLI needs one,
/// and the results themselves are in the session.
const CONTINUE_PROMPT: &str = "Continue from the tool results above.";
/// The prompt when the latest user message has images: the CLI takes only text
/// through stdin, so the message itself is in the session.
const IMAGE_PROMPT: &str = "Reply to the message above.";

/// Runs Gemini through the `gemini` CLI instead of calling the API directly.
///
/// The CLI's login (Google account or API key) is used as is. System messages
/// replace the CLI's own system prompt; without any, the prompt is empty.
/// Tools are declared to the model, so it calls them as it would any tool.
///
/// Limits of going through the CLI:
/// - System and assistant messages are text only. Thinking is not reported.
/// - A tool's description gets the CLI's note on discovered tools appended.
/// - After tool results, the turn goes on from a short user prompt
///   (`"Continue from the tool results above."`), since the CLI needs one;
///   before it, the CLI puts a model turn noting that the previous response
///   was interrupted. A latest user message with images likewise goes into
///   the session, followed by `"Reply to the message above."`.
/// - The CLI drops earlier user messages that start with `/` or `?` from the
///   session, and takes a latest message that starts with `/` as a command.
/// - The user's settings still apply where ailoy's do not override them, and
///   system (admin) settings override ailoy's.
/// - Each call leaves a session record under `~/.gemini/tmp`.
/// - The discovery command and the hook run through `sh`, so not on Windows.
#[derive(Clone, Debug)]
pub struct GeminiCliModel {
    program: String,
    model: Option<String>,
}

impl Default for GeminiCliModel {
    fn default() -> Self {
        Self::new()
    }
}

impl GeminiCliModel {
    pub fn new() -> Self {
        Self {
            program: "gemini".to_owned(),
            model: None,
        }
    }

    /// Model name for `--model` (e.g. `"gemini-2.5-flash"`); unset keeps the CLI default.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = Some(model.into());
        self
    }

    /// Name or path of the `gemini` executable.
    pub fn with_program(mut self, program: impl Into<String>) -> Self {
        self.program = program.into();
        self
    }

    /// Writes the files for one call into `project` (its project directory)
    /// and `workdir`, and builds the command, without starting it.
    fn command(
        &self,
        plan: &Plan,
        options: &LangModelOptions,
        project: &Path,
        workdir: &Path,
    ) -> anyhow::Result<Command> {
        let settings_dir = project.join(".gemini");
        std::fs::create_dir(&settings_dir)?;
        let settings = self.settings(options)?;
        std::fs::write(
            settings_dir.join("settings.json"),
            serde_json::to_string(&settings)?,
        )?;
        let system_md = workdir.join("system.md");
        std::fs::write(&system_md, &plan.system)?;
        let tools_json = workdir.join("tools.json");
        std::fs::write(&tools_json, serde_json::to_string(&plan.tools)?)?;

        let mut command = Command::new(&self.program);
        command.args([
            "--output-format",
            "stream-json",
            // Without it, tools that need approval are kept from the model in
            // headless mode; the hook stops them before they run anyway.
            "--approval-mode",
            "yolo",
            // Names no configured server, so none is started.
            "--allowed-mcp-server-names",
            "ailoy-none",
            // No extension is loaded, nor its hooks, tools or context.
            "--extensions",
            "none",
        ]);
        if let Some(model) = &self.model {
            command.args(["--model", model.as_str()]);
        }
        if !plan.session.is_empty() {
            let session = workdir.join("session.jsonl");
            std::fs::write(&session, &plan.session)?;
            command.arg("--session-file").arg(session);
        }
        command
            // Always set, even empty: otherwise the CLI's own coding-agent prompt is used.
            .env("GEMINI_SYSTEM_MD", &system_md)
            .env("AILOY_GEMINI_TOOLS", &tools_json)
            // Without trust, neither the project settings nor any hook is
            // loaded. The project directory is the user's own.
            .env("GEMINI_CLI_TRUST_WORKSPACE", "true")
            .current_dir(project)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            // Dropping a stream mid-reply ends the process with it.
            .kill_on_drop(true);
        Ok(command)
    }
}

impl GeminiCliModel {
    /// The project settings for one call. Merged after the user's, they
    /// override them, except that lists of hooks and excluded tools add up.
    fn settings(&self, options: &LangModelOptions) -> anyhow::Result<serde_json::Value> {
        let mut settings = serde_json::json!({
            "tools": {
                "exclude": BUILTIN_TOOLS,
                // Quoted so the CLI passes the variable to `sh` unexpanded.
                "discoveryCommand": "sh -c 'cat \"$AILOY_GEMINI_TOOLS\"'",
                // Never run: the hook stops the agent first.
                "callCommand": "false",
            },
            "context": {
                // No such file exists, so no GEMINI.md is added to the system prompt.
                "fileName": "AILOY_NO_CONTEXT.md",
                // Keeps the directory listing out of the context the CLI adds.
                "includeDirectoryTree": false,
            },
            "model": {
                // The CLI's default, kept should the user's settings turn the check on: it asks
                // another model after the reply, and `parse_usage` takes the last model's counts.
                "skipNextSpeakerCheck": true,
            },
            "hooksConfig": {
                // On even if the user's settings turn hooks off, or the hook would not run.
                "enabled": true,
                // The user's hooks could change the requests or let a tool run.
                "disabled": user_hook_names()?,
            },
            "hooks": {
                "BeforeTool": [{
                    "matcher": ".*",
                    "hooks": [{
                        "type": "command",
                        "name": STOP_HOOK,
                        "command": "echo '{\"continue\":false,\"stopReason\":\"the call goes back to the caller\"}'",
                    }],
                }],
            },
        });
        if let Some(config) = self.generate_config(options) {
            // Applies to the main chat only, whichever model it runs on.
            settings["modelConfigs"] = serde_json::json!({
                "customOverrides": [{
                    "match": {"isChatModel": true},
                    "modelConfig": {"generateContentConfig": config},
                }],
            });
        }
        Ok(settings)
    }

    /// The `generateContentConfig` fields `options` set, or `None` when they set none.
    fn generate_config(&self, options: &LangModelOptions) -> Option<serde_json::Value> {
        let mut config = serde_json::Map::new();
        if let Some(effort) = options.thinking_effort {
            // Gemini 2.x takes a token budget, later models a level.
            let legacy = self
                .model
                .as_deref()
                .is_some_and(|m| m.starts_with("gemini-2"));
            let thinking = match (legacy, effort) {
                (true, ThinkingEffort::Low) => serde_json::json!({"thinkingBudget": 2048}),
                (true, ThinkingEffort::Medium) => serde_json::json!({"thinkingBudget": 8192}),
                (true, ThinkingEffort::High) => serde_json::json!({"thinkingBudget": 24576}),
                (false, ThinkingEffort::Low) => serde_json::json!({"thinkingLevel": "LOW"}),
                (false, ThinkingEffort::Medium) => serde_json::json!({"thinkingLevel": "MEDIUM"}),
                (false, ThinkingEffort::High) => serde_json::json!({"thinkingLevel": "HIGH"}),
            };
            config.insert("thinkingConfig".to_owned(), thinking);
        }
        if let Some(schema) = &options.output_schema {
            config.insert("responseMimeType".to_owned(), "application/json".into());
            config.insert("responseJsonSchema".to_owned(), schema.clone().into());
        }
        (!config.is_empty()).then(|| config.into())
    }
}

/// A new project directory for one call, empty, in a directory private to the
/// user (see [`private_dir`](super::codex_cli::private_dir)). Removed when dropped.
///
/// Each call has its own, since the call's model config goes in its settings.
/// The CLI trusts it (`GEMINI_CLI_TRUST_WORKSPACE`), so loads its
/// `.gemini/settings.json`, and looks for a `.env` file from it upwards
/// (`.gemini/.env` or `.env` in each directory up to the root). Under the
/// user's cache directory, the directories above it are the user's own up to
/// the home directory, and the system's beyond, where other users cannot write.
fn project_dir() -> anyhow::Result<tempfile::TempDir> {
    let parent = super::codex_cli::private_dir(PROJECT_DIR)?;
    Ok(tempfile::Builder::new()
        .prefix("call-")
        .tempdir_in(parent)?)
}

/// The names of the hooks in the user's settings, to disable them by: the
/// CLI adds up the hooks of every settings file, so the user's cannot be
/// overridden otherwise.
///
/// The CLI names a hook by its `name`, or by its command.
fn user_hook_names() -> anyhow::Result<Vec<String>> {
    let home = match std::env::var_os("GEMINI_CLI_HOME") {
        Some(home) if !home.is_empty() => std::path::PathBuf::from(home),
        _ => dirs::home_dir().context("no home directory for this user")?,
    };
    let path = home.join(".gemini").join("settings.json");
    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e).with_context(|| format!("failed to read {}", path.display())),
    };
    let settings: serde_json::Value = serde_json::from_str(&strip_comments(&text))
        .with_context(|| format!("failed to parse {}", path.display()))?;
    let mut names = Vec::new();
    let events = settings["hooks"].as_object().into_iter().flatten();
    for (_, definitions) in events {
        let hooks = definitions
            .as_array()
            .into_iter()
            .flatten()
            .flat_map(|d| d["hooks"].as_array().into_iter().flatten());
        for hook in hooks {
            if let Some(name) = hook["name"].as_str().or(hook["command"].as_str())
                && name != STOP_HOOK
            {
                names.push(name.to_owned());
            }
        }
    }
    Ok(names)
}

/// JSON with `//` and `/* */` comments, as the CLI takes its settings, with
/// the comments taken out.
fn strip_comments(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    let mut in_string = false;
    while let Some(c) = chars.next() {
        if in_string {
            out.push(c);
            match c {
                '\\' => out.extend(chars.next()),
                '"' => in_string = false,
                _ => {}
            }
            continue;
        }
        match (c, chars.peek()) {
            ('"', _) => {
                in_string = true;
                out.push(c);
            }
            ('/', Some('/')) => {
                // Up to the end of the line, which is kept.
                while chars.next_if(|&c| c != '\n').is_some() {}
            }
            ('/', Some('*')) => {
                chars.next();
                let mut last = '\0';
                for c in chars.by_ref() {
                    if last == '*' && c == '/' {
                        break;
                    }
                    last = c;
                }
                out.push(' ');
            }
            _ => out.push(c),
        }
    }
    out
}

impl InferLangModel for GeminiCliModel {
    fn infer(
        &self,
        messages: &[Message],
        tools: &[ToolDesc],
        options: &LangModelOptions,
    ) -> BoxFuture<'static, anyhow::Result<MessageOutput>> {
        let mut deltas = self.infer_stream(messages, tools, options);
        Box::pin(async move {
            let mut acc = MessageDeltaOutput::new();
            while let Some(delta) = deltas.next().await {
                acc = acc.accumulate(delta?)?;
            }
            acc.finish()
        })
    }

    fn infer_stream(
        &self,
        messages: &[Message],
        tools: &[ToolDesc],
        options: &LangModelOptions,
    ) -> BoxStream<'static, anyhow::Result<MessageDeltaOutput>> {
        let plan = match Plan::new(messages, tools) {
            Ok(plan) => plan,
            Err(e) => return Box::pin(stream::once(async move { Err(e) })),
        };
        let this = self.clone();
        let options = options.clone();

        Box::pin(async_stream::try_stream! {
            let project = project_dir()?;
            let workdir = tempfile::tempdir()?;
            let mut child = this
                .command(&plan, &options, project.path(), workdir.path())?
                .spawn()
                .context("failed to start the gemini CLI")?;
            let mut stdin = child.stdin.take().expect("stdin is piped");
            stdin.write_all(plan.prompt.as_bytes()).await?;
            // Closing stdin ends the prompt.
            drop(stdin);
            let stdout = child.stdout.take().expect("stdout is piped");
            let mut stderr = child.stderr.take().expect("stderr is piped");
            // Drained alongside stdout so a full stderr pipe cannot stall the process.
            let stderr = tokio::spawn(async move {
                let mut buf = String::new();
                let _ = stderr.read_to_string(&mut buf).await;
                buf
            });

            let mut lines = BufReader::new(stdout).lines();
            let mut reader = Reader::default();
            let mut finished = false;
            while let Some(line) = lines.next_line().await? {
                // The CLI may print plain log lines too.
                if !line.trim_start().starts_with('{') {
                    continue;
                }
                let event: serde_json::Value = serde_json::from_str(&line)
                    .with_context(|| format!("unexpected output from gemini: {line}"))?;
                if let Some(out) = reader.on_event(event)? {
                    finished = out.finish_reason.is_some();
                    yield out;
                    if finished {
                        break;
                    }
                }
            }

            if finished {
                // The run has ended; a no-op unless it lingers.
                let _ = child.start_kill();
                let _ = child.wait().await;
            } else {
                let status = child.wait().await?;
                let stderr = stderr.await.unwrap_or_default();
                Err(anyhow::anyhow!("gemini exited with {status} before finishing: {stderr}"))?;
            }
            drop(workdir);
            drop(project);
        })
    }
}

/// What one call hands to the CLI, built from the conversation.
#[derive(Debug)]
struct Plan {
    /// System messages, joined.
    system: String,
    /// Function declarations for the discovery command to print.
    tools: Vec<serde_json::Value>,
    /// The earlier turns as a session record, or empty when there are none.
    session: String,
    /// The prompt for stdin.
    prompt: String,
}

impl Plan {
    fn new(messages: &[Message], tools: &[ToolDesc]) -> anyhow::Result<Self> {
        let (system, conversation): (Vec<&Message>, Vec<&Message>) =
            messages.iter().partition(|m| m.role == Role::System);
        let system = system
            .into_iter()
            .map(text_of)
            .collect::<anyhow::Result<Vec<_>>>()?
            .join("\n\n");
        let tools = tools
            .iter()
            .map(|tool| {
                serde_json::json!({
                    "name": tool.name,
                    "description": tool.description.clone().unwrap_or_default(),
                    "parametersJsonSchema": tool.parameters,
                })
            })
            .collect();

        let Some((latest, earlier)) = conversation.split_last() else {
            anyhow::bail!("no message to send");
        };
        let (earlier, prompt) = match latest.role {
            // Only text goes through stdin, so a message with images goes into the session.
            Role::User if latest.contents.iter().any(Part::is_image) => {
                (&conversation[..], IMAGE_PROMPT.to_owned())
            }
            Role::User => (earlier, user_text(latest)?),
            // The results go into the session, and the turn goes on from a short prompt.
            Role::Tool => (&conversation[..], CONTINUE_PROMPT.to_owned()),
            _ => anyhow::bail!("the last message must be a user message or tool results"),
        };
        if prompt.trim().is_empty() {
            anyhow::bail!("the user message is empty");
        }

        Ok(Self {
            system,
            tools,
            session: session_record(earlier)?,
            prompt,
        })
    }
}

/// The conversation as a session record: a metadata line, then one line per
/// message. Tool results are attached to the calls they answer.
fn session_record(conversation: &[&Message]) -> anyhow::Result<String> {
    if conversation.is_empty() {
        return Ok(String::new());
    }
    let mut records: Vec<serde_json::Value> = Vec::new();
    for message in conversation {
        match message.role {
            Role::User => records.push(serde_json::json!({
                "id": format!("m{}", records.len()),
                "type": "user",
                "content": user_parts(message)?,
            })),
            Role::Assistant => {
                let text = texts_of(message)?;
                let mut calls = Vec::new();
                for part in message.tool_calls.iter().flatten() {
                    let Part::Function { id, function } = part else {
                        anyhow::bail!("a tool call must be a function part");
                    };
                    calls.push(serde_json::json!({
                        "id": id,
                        "name": format!("{TOOL_PREFIX}{}", function.name),
                        "args": function.arguments,
                    }));
                }
                // Without text the content is empty but present, as the CLI requires.
                let content = if text.is_empty() {
                    serde_json::json!([])
                } else {
                    serde_json::json!(text)
                };
                records.push(serde_json::json!({
                    "id": format!("m{}", records.len()),
                    "type": "gemini",
                    "content": content,
                    "toolCalls": calls,
                }));
            }
            Role::Tool => {
                let call_id = message
                    .id
                    .as_deref()
                    .context("a tool result must carry its call id")?;
                let mut output = Vec::new();
                let mut images = Vec::new();
                for part in &message.contents {
                    match part {
                        Part::Image { image } => images.push(inline_image(image)?.into()),
                        _ => output.push(part_text(part)?),
                    }
                }
                let call = records
                    .iter_mut()
                    .rev()
                    .filter(|r| r["type"] == "gemini")
                    .flat_map(|r| r["toolCalls"].as_array_mut().into_iter().flatten())
                    .find(|c| c["id"] == call_id)
                    .with_context(|| format!("no call {call_id} for its result"))?;
                let output = output.join("\n");
                call["result"] = if images.is_empty() {
                    output.into()
                } else {
                    // As parts, the response is the CLI's own for a text result, and the
                    // images go beside it.
                    let mut parts = vec![serde_json::json!({"functionResponse": {
                        "id": call_id,
                        "name": call["name"],
                        "response": {"output": output},
                    }})];
                    parts.extend(images);
                    serde_json::Value::Array(parts)
                };
            }
            ref role => anyhow::bail!("GeminiCliModel does not support {role} messages here"),
        }
    }

    let mut lines =
        vec![serde_json::json!({"sessionId": "ailoy", "projectHash": "ailoy"}).to_string()];
    lines.extend(records.iter().map(|r| r.to_string()));
    Ok(lines.join("\n") + "\n")
}

/// Turns the CLI's events into deltas.
#[derive(Default)]
struct Reader {
    started: bool,
    /// Calls to the tools in the reply so far.
    calls: Vec<PartDelta>,
}

impl Reader {
    /// Handles one event. A delta with a finish reason ends the reply.
    fn on_event(&mut self, event: serde_json::Value) -> anyhow::Result<Option<MessageDeltaOutput>> {
        let mut out = MessageDeltaOutput::new();
        match event["type"].as_str() {
            // The prompt is echoed back as a `user` message first.
            Some("message") if event["role"] == "assistant" => {
                let text = event["content"].as_str().unwrap_or_default().to_owned();
                if text.is_empty() {
                    return Ok(None);
                }
                out.delta = out.delta.with_contents([PartDelta::Text { text }]);
            }
            Some("tool_use") => {
                let name = event["tool_name"].as_str().unwrap_or_default();
                let Some(name) = name.strip_prefix(TOOL_PREFIX) else {
                    anyhow::bail!("gemini used a tool of its own ({name}): {event}");
                };
                self.calls.push(PartDelta::Function {
                    id: event["tool_id"].as_str().map(str::to_owned),
                    function: PartDeltaFunction::WithParsedArgs {
                        name: name.to_owned(),
                        arguments: event["parameters"].clone().into(),
                    },
                });
                return Ok(None);
            }
            // The run is over: the reply ends with the calls, if any, and the usage.
            Some("result") => {
                if event["status"] != "success" {
                    let message = event["error"]["message"].as_str().unwrap_or_default();
                    anyhow::bail!("gemini failed: {message}");
                }
                if self.calls.is_empty() {
                    out.finish_reason = Some(FinishReason::Stop {});
                } else {
                    out.delta = out.delta.with_tool_calls(std::mem::take(&mut self.calls));
                    out.finish_reason = Some(FinishReason::ToolCall {});
                }
                out.usage = parse_usage(&event["stats"]);
            }
            // `tool_result` is the hook stopping a call; `error` events are
            // warnings, or precede a failed `result`.
            _ => return Ok(None),
        }
        if !self.started {
            out.delta.role = Some(Role::Assistant);
            self.started = true;
        }
        Ok(Some(out))
    }
}

/// The text of a message that cannot carry tool calls.
fn text_of(message: &Message) -> anyhow::Result<String> {
    if message.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty()) {
        anyhow::bail!("only assistant messages can carry tool calls");
    }
    texts_of(message)
}

/// A user message as Gemini parts: text and values as `text`, images as
/// `inlineData`. Without images, the message is one text part, as the CLI
/// sends a prompt from stdin, so a latest message is sent the same way in the
/// next call's session and the prompts share a prefix.
fn user_parts(message: &Message) -> anyhow::Result<Vec<serde_json::Value>> {
    if !message.contents.iter().any(Part::is_image) {
        return Ok(vec![serde_json::json!({"text": user_text(message)?})]);
    }
    if message.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty()) {
        anyhow::bail!("only assistant messages can carry tool calls");
    }
    message
        .contents
        .iter()
        .map(|part| {
            Ok(match part {
                Part::Image { image } => inline_image(image)?.into(),
                _ => serde_json::json!({"text": part_text(part)?}),
            })
        })
        .collect()
}

/// A user message without images as text: its text and value parts joined.
fn user_text(message: &Message) -> anyhow::Result<String> {
    if message.tool_calls.as_ref().is_some_and(|tc| !tc.is_empty()) {
        anyhow::bail!("only assistant messages can carry tool calls");
    }
    let texts = message
        .contents
        .iter()
        .map(part_text)
        .collect::<anyhow::Result<Vec<_>>>()?;
    Ok(texts.join("\n"))
}

/// A text or value part as text, strings without their quotes.
fn part_text(part: &Part) -> anyhow::Result<String> {
    Ok(match part {
        Part::Text { text } => text.clone(),
        Part::Value { value } => match value.as_str() {
            Some(s) => s.to_owned(),
            None => serde_json::to_string(value)?,
        },
        _ => anyhow::bail!("GeminiCliModel takes only text, values and images in message contents"),
    })
}

/// The text parts of a message joined; any other part is an error.
fn texts_of(message: &Message) -> anyhow::Result<String> {
    let texts = message
        .contents
        .iter()
        .map(|part| {
            part.as_text()
                .ok_or_else(|| anyhow::anyhow!("GeminiCliModel supports only text parts"))
        })
        .collect::<anyhow::Result<Vec<_>>>()?;
    Ok(texts.join("\n"))
}

/// The usage of the request the reply came from, out of the run's `stats`.
///
/// The run's own counts add up every request it made, the router's too under the CLI's
/// default model (`auto`). `stats.models` counts each model apart, in the order each first
/// returned or failed a response, and with no request after the reply (see
/// [`GeminiCliModel::settings`]) the reply's model is the last one with tokens. A model that
/// also served an earlier request of the run has that request in its counts. Without a model
/// with tokens, the run's counts are used.
///
/// Thinking is billed as output: `output_tokens` leaves it out and `total_tokens` has it, so
/// the output is the total less the input, unless the total is missing or smaller than the
/// input and output it should hold.
fn parse_usage(stats: &serde_json::Value) -> Option<TokenUsage> {
    let has_tokens = |counts: &&serde_json::Value| {
        ["input_tokens", "output_tokens", "total_tokens"]
            .iter()
            .any(|key| counts[*key].as_u64().unwrap_or(0) > 0)
    };
    let counts = stats["models"]
        .as_object()
        .and_then(|models| models.values().rev().find(has_tokens))
        .unwrap_or(stats);
    let input_tokens = counts["input_tokens"].as_u64()?;
    let reported_output = counts["output_tokens"].as_u64()?;
    let output_tokens = match counts["total_tokens"].as_u64() {
        Some(total) if total >= input_tokens + reported_output => total - input_tokens,
        _ => reported_output,
    };
    Some(TokenUsage {
        input_tokens,
        output_tokens,
        cache_creation_input_tokens: None,
        cache_read_input_tokens: counts["cached"].as_u64(),
    })
}

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

    fn weather_call() -> [Message; 3] {
        [
            Message::new(Role::User).with_contents([Part::text("weather?")]),
            Message::new(Role::Assistant).with_tool_calls([Part::function(
                "c1",
                "get_weather",
                serde_json::json!({"city": "Seoul"}),
            )]),
            Message::new(Role::Tool)
                .with_id("c1")
                .with_contents([Part::text("sunny")]),
        ]
    }

    #[test]
    fn results_attach_to_their_calls_in_the_session() {
        let plan = Plan::new(&weather_call(), &[]).unwrap();
        assert_eq!(plan.prompt, CONTINUE_PROMPT);
        let lines: Vec<serde_json::Value> = plan
            .session
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert_eq!(
            lines,
            [
                serde_json::json!({"sessionId": "ailoy", "projectHash": "ailoy"}),
                serde_json::json!({"id": "m0", "type": "user", "content": [{"text": "weather?"}]}),
                serde_json::json!({"id": "m1", "type": "gemini", "content": [], "toolCalls": [
                    {"id": "c1", "name": "discovered_tool_get_weather", "args": {"city": "Seoul"}, "result": "sunny"},
                ]}),
            ]
        );
    }

    #[test]
    fn lone_user_message_needs_no_session() {
        let messages = [
            Message::new(Role::System).with_contents([Part::text("Be brief.")]),
            Message::new(Role::User).with_contents([Part::text("hi")]),
        ];
        let plan = Plan::new(&messages, &[]).unwrap();
        assert_eq!(
            (
                plan.system.as_str(),
                plan.prompt.as_str(),
                plan.session.as_str()
            ),
            ("Be brief.", "hi", "")
        );
    }

    /// Runs `events` through a reader; returns the deltas until the first finish.
    fn read(events: &[serde_json::Value]) -> anyhow::Result<Vec<MessageDeltaOutput>> {
        let mut reader = Reader::default();
        let mut outs = Vec::new();
        for event in events {
            if let Some(out) = reader.on_event(event.clone())? {
                let finished = out.finish_reason.is_some();
                outs.push(out);
                if finished {
                    break;
                }
            }
        }
        Ok(outs)
    }

    #[test]
    fn calls_end_the_reply_with_usage() {
        let tool_use = |id: &str, city: &str| serde_json::json!({"type": "tool_use", "tool_name": "discovered_tool_get_weather", "tool_id": id, "parameters": {"city": city}});
        let outs = read(&[
            serde_json::json!({"type": "init", "session_id": "s", "model": "gemini"}),
            serde_json::json!({"type": "message", "role": "user", "content": "weather?"}),
            serde_json::json!({"type": "message", "role": "assistant", "content": "Let me check.", "delta": true}),
            tool_use("t1", "Seoul"),
            tool_use("t2", "Tokyo"),
            serde_json::json!({"type": "tool_result", "tool_id": "t1", "status": "error", "output": ""}),
            serde_json::json!({"type": "result", "status": "success", "stats": {"total_tokens": 15, "input_tokens": 10, "output_tokens": 5, "cached": 4, "input": 6, "duration_ms": 1, "tool_calls": 1}}),
        ])
        .unwrap();
        assert_eq!(outs[0].delta.role, Some(Role::Assistant));
        let last = outs.last().unwrap();
        assert!(matches!(
            last.finish_reason,
            Some(FinishReason::ToolCall {})
        ));
        let names: Vec<_> = last
            .delta
            .tool_calls
            .iter()
            .map(|c| match c {
                PartDelta::Function {
                    id,
                    function: PartDeltaFunction::WithParsedArgs { name, .. },
                } => (id.clone().unwrap(), name.clone()),
                other => panic!("not a parsed call: {other:?}"),
            })
            .collect();
        assert_eq!(
            names,
            [
                ("t1".to_owned(), "get_weather".to_owned()),
                ("t2".to_owned(), "get_weather".to_owned())
            ]
        );
        let usage = last.usage.as_ref().unwrap();
        assert_eq!(
            (
                usage.input_tokens,
                usage.output_tokens,
                usage.cache_read_input_tokens
            ),
            (10, 5, Some(4))
        );
    }

    /// The `(input, output, cached)` usage `stats` gives a reply.
    fn usage_of(stats: serde_json::Value) -> (u64, u64, Option<u64>) {
        let outs = read(&[
            serde_json::json!({"type": "message", "role": "assistant", "content": "Hi.", "delta": true}),
            serde_json::json!({"type": "result", "status": "success", "stats": stats}),
        ])
        .unwrap();
        let usage = outs.last().unwrap().usage.clone().unwrap();
        (
            usage.input_tokens,
            usage.output_tokens,
            usage.cache_read_input_tokens,
        )
    }

    /// The `routed` and `named` rows are the `stats` of a call to `get_weather`, measured on
    /// 2026-11-03 with gemini-cli 0.66.0, under the CLI's default model and with
    /// `--model gemini-2.5-flash`.
    #[test]
    fn the_usage_is_the_replys_own_request() {
        let counts = |input: u64, output: u64, total: u64| serde_json::json!({"total_tokens": total, "input_tokens": input, "output_tokens": output, "cached": 0, "input": input});
        let run = |models: serde_json::Value| serde_json::json!({"total_tokens": 1943, "input_tokens": 1250, "output_tokens": 53, "cached": 0, "input": 1250, "duration_ms": 1, "tool_calls": 1, "models": models});
        for (row, stats, usage) in [
            (
                "routed",
                run(
                    serde_json::json!({"gemini-3.5-flash-lite": counts(757, 33, 1343), "gemini-3.8-flash": counts(493, 20, 600)}),
                ),
                (493, 600 - 493, Some(0)),
            ),
            (
                "named",
                run(serde_json::json!({"gemini-2.5-flash": counts(504, 18, 573)})),
                (504, 573 - 504, Some(0)),
            ),
            // The CLI's order, not the names', says which model answered.
            (
                "order",
                run(
                    serde_json::json!({"zz-router": counts(757, 33, 1343), "aa-answer": counts(493, 20, 600)}),
                ),
                (493, 107, Some(0)),
            ),
            // A model that only failed after the reply has no tokens to read.
            (
                "failed last",
                run(serde_json::json!({"a": counts(493, 20, 600), "b": counts(0, 0, 0)})),
                (493, 107, Some(0)),
            ),
            (
                "no total",
                run(
                    serde_json::json!({"a": {"input_tokens": 100, "output_tokens": 5, "cached": 0}}),
                ),
                (100, 5, Some(0)),
            ),
            (
                "total short",
                run(serde_json::json!({"a": counts(100, 5, 0)})),
                (100, 5, Some(0)),
            ),
            (
                "no models",
                run(serde_json::json!({})),
                (1250, 1943 - 1250, Some(0)),
            ),
        ] {
            assert_eq!(usage_of(stats), usage, "{row}");
        }
    }

    #[test]
    fn settings_skip_the_next_speaker_check() {
        let settings = GeminiCliModel::new()
            .settings(&LangModelOptions::default())
            .unwrap();
        assert_eq!(settings["model"]["skipNextSpeakerCheck"], true);
    }

    #[test]
    fn plain_reply_stops_and_failure_errors() {
        let outs = read(&[
            serde_json::json!({"type": "message", "role": "assistant", "content": "Hi.", "delta": true}),
            serde_json::json!({"type": "result", "status": "success", "stats": {"input_tokens": 3, "output_tokens": 1, "cached": 0}}),
        ])
        .unwrap();
        assert!(matches!(
            outs.last().unwrap().finish_reason,
            Some(FinishReason::Stop {})
        ));

        let err = read(&[serde_json::json!({"type": "result", "status": "error", "error": {"type": "Error", "message": "quota"}, "stats": {}})])
            .unwrap_err();
        assert!(err.to_string().contains("quota"), "{err}");

        let err = read(&[serde_json::json!({"type": "tool_use", "tool_name": "run_shell_command", "tool_id": "x", "parameters": {}})])
            .unwrap_err();
        assert!(err.to_string().contains("run_shell_command"), "{err}");
    }

    #[test]
    fn images_go_into_the_session() {
        let image = || Part::image_embedded("image/png", vec![1, 2, 3].into()).unwrap();
        let inline = serde_json::json!({"inlineData": {"mimeType": "image/png", "data": "AQID"}});
        let messages = [
            Message::new(Role::User).with_contents([Part::text("read a.png")]),
            Message::new(Role::Assistant).with_tool_calls([Part::function(
                "c1",
                "imgread",
                serde_json::json!({"path": "a.png"}),
            )]),
            Message::new(Role::Tool)
                .with_id("c1")
                .with_contents([image()]),
            Message::new(Role::User).with_contents([Part::text("and this?"), image()]),
        ];
        let plan = Plan::new(&messages, &[]).unwrap();
        assert_eq!(plan.prompt, IMAGE_PROMPT);
        let lines: Vec<serde_json::Value> = plan
            .session
            .lines()
            .map(|l| serde_json::from_str(l).unwrap())
            .collect();
        assert_eq!(
            lines[2]["toolCalls"][0]["result"],
            serde_json::json!([
                {"functionResponse": {"id": "c1", "name": "discovered_tool_imgread", "response": {"output": ""}}},
                inline,
            ])
        );
        assert_eq!(
            lines[3]["content"],
            serde_json::json!([{"text": "and this?"}, inline])
        );
    }
}