summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 786b070216cf2f7c21b9d5248768cb26347db363 (plain) (blame)
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
/*
 * This file is part of agent686
 * Copyright (C) 2026 Salmonik <salmon@2137697.xyz>
 * SPDX-License-Identifier: GPL-3.0-or-later
 * https://git.2137697.xyz/agent686
 */

use serde_json::json;
use std::io::{BufRead, IsTerminal, Write};
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

use serde_json::Value;

use agent686::config::Config;
use agent686::line::Editor;
use agent686::session::{self, Session};
use agent686::ui::Approver;
use agent686::{agent, doctor, signal};

const HELP: &str = "\
agent686 — a small coding agent

USAGE:
  agent686 [OPTIONS] [--] [PROMPT...]

With a prompt it runs one turn and exits. Without one it reads prompts from
stdin. In a terminal: up/down for history, ctrl-a/e/u/w/k to edit, ctrl-d to
exit, ctrl-c to abandon the line.

COMMANDS (at the prompt):
  /paste   read a block of lines until a lone `.`
  /exit    quit
  /help    this text

OPTIONS:
  -m, --model <ID>      model id (default: deepseek-v4.1-flash)
      --base-url <URL>  provider base URL
      --session <ID>    resume a session, creating it if the id is new
                    (alias: --resume)
  -c, --continue        resume the most recent session
      --list            list sessions and exit
      --show [ID]       print a transcript (most recent if no ID) and exit
      --doctor          check key, directories, provider and model, then exit
      --yolo            approve every tool call without asking
      --provider <TYPE>  opencode (requires the session header, default) or
                         openai-compatible (any OpenAI-style endpoint; pair with
                         --base-url, e.g. Ollama http://localhost:11434/v1)
      --lenient         tolerate providers that omit [DONE]/usage
      --system-ca       verify TLS with the system trust store
  -V, --version         print the version and exit
  -h, --help            this text

EXIT CODES:
  0 success · 1 error · 2 usage · 3 a tool call was denied · 130 aborted

ENVIRONMENT:
  OPENCODE_API_KEY     credential (falls back to ~/.config/agent686/key)
  AGENT686_MODEL       default model id
  AGENT686_BASE_URL    default provider base URL
  AGENT686_DATA        where sessions live (default ~/.local/share/agent686)
  AGENT686_ALLOW_HOME  permit --yolo in $HOME or /
  NO_COLOR             disable colour
";

struct Args {
    prompt: Option<String>,
    model: Option<String>,
    base_url: Option<String>,
    session: Option<String>,
    continue_last: bool,
    list: bool,
    show: Option<Option<String>>,
    doctor: bool,
    yolo: bool,
    json: bool,
    provider: Option<String>,
    lenient: bool,
    system_ca: bool,
}

fn main() {
    let args = match parse_args() {
        Ok(args) => args,
        Err(message) => {
            eprintln!("agent686: {message}");
            std::process::exit(2);
        }
    };
    run(args);
}

fn parse_args() -> Result<Args, String> {
    let mut args = Args {
        prompt: None,
        model: None,
        base_url: None,
        session: None,
        continue_last: false,
        list: false,
        show: None,
        doctor: false,
        yolo: false,
        json: false,
        provider: None,
        lenient: false,
        system_ca: false,
    };
    let mut words: Vec<String> = Vec::new();
    let mut iter = std::env::args().skip(1).peekable();
    let mut literal = false;

    while let Some(arg) = iter.next() {
        if literal {
            words.push(arg);
            continue;
        }
        // `--flag=value` form, so a value that begins with `-` is expressible.
        if arg.starts_with('-') {
            if let Some((flag, value)) = arg.split_once('=') {
                match flag {
                    "-m" | "--model" => {
                        args.model = Some(value.to_string());
                        continue;
                    }
                    "--base-url" => {
                        args.base_url = Some(value.to_string());
                        continue;
                    }
                    "--session" | "--resume" => {
                        args.session = Some(value.to_string());
                        continue;
                    }
                    "--show" => {
                        args.show = Some(Some(value.to_string()));
                        continue;
                    }
                    "--provider" => {
                        args.provider = Some(value.to_string());
                        continue;
                    }
                    _ => return Err(format!("unknown flag {flag}\n\n{HELP}")),
                }
            }
        }
        match arg.as_str() {
            "--" => literal = true,
            "-m" | "--model" => args.model = Some(take_value(&mut iter, "--model")?),
            "--base-url" => args.base_url = Some(take_value(&mut iter, "--base-url")?),
            "--session" | "--resume" => args.session = Some(take_value(&mut iter, "--session")?),
            "-c" | "--continue" => args.continue_last = true,
            "--list" => args.list = true,
            "--show" => {
                // Optional value: an id, or nothing for the most recent session.
                let id = match iter.peek() {
                    Some(next) if !next.starts_with('-') => iter.next(),
                    _ => None,
                };
                args.show = Some(id);
            }
            "--doctor" => args.doctor = true,
            "--yolo" => args.yolo = true,
            "--json" => args.json = true,
            "--provider" => args.provider = Some(take_value(&mut iter, "--provider")?),
            "--lenient" => args.lenient = true,
            "--system-ca" => args.system_ca = true,
            "-V" | "--version" => {
                println!("agent686 {}", env!("CARGO_PKG_VERSION"));
                std::process::exit(0);
            }
            "-h" | "--help" => {
                print!("{HELP}");
                std::process::exit(0);
            }
            flag if flag.starts_with('-') && flag.len() > 1 => {
                return Err(format!("unknown flag {flag}\n\n{HELP}"))
            }
            word => words.push(word.to_string()),
        }
    }

    if !words.is_empty() {
        args.prompt = Some(words.join(" "));
    }
    if args.continue_last && args.session.is_some() {
        return Err("--continue and --session cannot be combined".into());
    }
    if args.list && args.doctor {
        return Err("--list and --doctor cannot be combined".into());
    }
    if args.show.is_some() && (args.list || args.doctor) {
        return Err("--show cannot be combined with --list or --doctor".into());
    }
    if let Some(id) = &args.session {
        validate_session_id(id)?;
    }
    Ok(args)
}

fn take_value(iter: &mut impl Iterator<Item = String>, flag: &str) -> Result<String, String> {
    match iter.next() {
        Some(value) if !value.trim().is_empty() && !(value.starts_with('-') && value.len() > 1) => {
            Ok(value)
        }
        _ => Err(format!(
            "{flag} needs a value (use {flag}=… for a value starting with -)"
        )),
    }
}

fn validate_session_id(id: &str) -> Result<(), String> {
    let valid = !id.is_empty()
        && id.len() <= 64
        && id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
    if valid {
        Ok(())
    } else {
        Err(format!(
            "invalid session id `{id}`: use 1-64 characters of A-Z a-z 0-9 . _ -"
        ))
    }
}

fn run(args: Args) {
    signal::install();

    if let Some(id) = args.show {
        show_session(id, args.json);
        return;
    }

    if args.list {
        print_sessions(args.json);
        return;
    }

    let cli = agent686::config::Cli {
        model: args.model.clone(),
        base_url: args.base_url.clone(),
        provider: args.provider.clone(),
        yolo: args.yolo,
        lenient: args.lenient,
        system_ca: args.system_ca,
    };

    if args.doctor {
        let mut config = Config::resolve_lenient(&cli);
        // `/models` needs the session header too, even though this is not a turn.
        config.session = session::new_id();
        std::process::exit(doctor::run(&config, args.json));
    }

    let mut cfg = match Config::resolve(&cli) {
        Ok(cfg) => cfg,
        Err(message) => {
            eprintln!("agent686: {message}");
            std::process::exit(1);
        }
    };

    let resuming = args.session.is_some() || args.continue_last;
    let (mut session, mut history) = match open_session(&cfg, args.session, args.continue_last) {
        Ok(pair) => pair,
        Err(message) => {
            eprintln!("agent686: {message}");
            std::process::exit(1);
        }
    };
    cfg.session = session.id.clone();

    warn_if_moved(&session);
    if resuming {
        print_last_reply(&session);
    }
    if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") {
        eprintln!(
            "agent686: this session was written by {}; the prompt and tool schemas may \
             differ, so the provider's cache will be repopulated",
            session.version
        );
    }
    if !session.model.is_empty() && session.model != cfg.model {
        let _ = session.record_model(&cfg.model);
    }
    refuse_yolo(&cfg);

    let mut approver = Approver::new(cfg.yolo);
    let watched = agent::agents_md();
    let mut warned = false;

    if let Some(prompt) = args.prompt {
        match agent::run_turn(
            &cfg,
            &mut session,
            &mut history,
            &prompt,
            &signal::CANCEL,
            &mut approver,
        ) {
            Ok(report) => {
                if report.aborted {
                    std::process::exit(130);
                }
                if report.denied > 0 {
                    std::process::exit(3);
                }
            }
            Err(error) => {
                eprintln!("agent686: {error}");
                std::process::exit(1);
            }
        }
        return;
    }

    let mut editor = Editor::new();
    let interactive = editor.is_interactive();
    let mut checkpoint: Option<String> = None;
    if !interactive && !cfg.yolo {
        eprintln!(
            "agent686: stdin is not a terminal, so write/edit/bash will be denied; \
             pass --yolo to allow them"
        );
    }
    if interactive {
        eprintln!(
            "agent686 · {} · session {}{}",
            cfg.model,
            cfg.session,
            if cfg.yolo { " · yolo" } else { "" }
        );
        eprintln!("type a prompt · up/down history · ctrl-d exit · /help");
    }

    let stdin = std::io::stdin();
    let mut line = String::new();
    loop {
        let mut text = match editor.read("> ") {
            Ok(Some(text)) => text,
            Ok(None) => break,
            Err(error) => {
                eprintln!("agent686: input: {error}");
                break;
            }
        };
        if text.trim().is_empty() {
            continue;
        }

        if text == "/models" {
            list_models(&cfg);
            continue;
        }
        if let Some(model) = text.strip_prefix("/model ") {
            switch_model(&mut cfg, &mut session, model.trim());
            continue;
        }
        if text == "/forget" || text.starts_with("/forget ") {
            forget_sessions(&text, &session);
            continue;
        }
        if text == "/undo" {
            undo(checkpoint.as_deref());
            continue;
        }
        if text == "/compact" {
            compact(&cfg, &mut session, &mut history);
            continue;
        }

        match text.as_str() {
            "/exit" | "/quit" => break,
            "/help" => {
                print!("{HELP}");
                continue;
            }
            "/paste" => {
                let mut buffer = String::new();
                loop {
                    if interactive {
                        print!("… ");
                        let _ = std::io::stdout().flush();
                    }
                    line.clear();
                    if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 {
                        break;
                    }
                    let piece = line.trim_end_matches(['\n', '\r']);
                    if piece == "." {
                        break;
                    }
                    buffer.push_str(piece);
                    buffer.push('\n');
                }
                text = buffer.trim_end().to_string();
                if text.is_empty() {
                    continue;
                }
            }
            _ => {}
        }

        warn_if_changed(&watched, &mut warned);
        checkpoint = git_checkpoint();
        if let Err(error) = agent::run_turn(
            &cfg,
            &mut session,
            &mut history,
            &text,
            &signal::CANCEL,
            &mut approver,
        ) {
            eprintln!("agent686: {error}");
        }
    }
}

fn open_session(
    cfg: &Config,
    resume: Option<String>,
    continue_last: bool,
) -> Result<(Session, Vec<Value>), String> {
    let id = match resume {
        Some(id) => Some(id),
        None if continue_last => Some(
            session::latest()?
                .ok_or_else(|| "no sessions to continue; run without --continue".to_string())?,
        ),
        None => None,
    };

    match id {
        Some(id) if !session::exists(&id) => {
            let system = agent::system_prompt();
            let session = Session::create_as(id, &cfg.model, &system)?;
            eprintln!(
                "agent686: new session {} ({})",
                session.id,
                session.path().display()
            );
            Ok((session, agent::new_history(system)))
        }
        Some(id) => {
            let (session, system, messages) = Session::open(&id)?;
            if !session.model.is_empty() && session.model != cfg.model {
                eprintln!(
                    "agent686: session used {}; continuing with {} (this invalidates the \
                     provider's prompt cache for the whole history)",
                    session.model, cfg.model
                );
            }
            // The system message frozen at session start is reused verbatim, so
            // the request prefix stays byte-identical across restarts.
            let system = if system.is_null() {
                agent::system_prompt()
            } else {
                system
            };
            let mut history = agent::new_history(system);
            let count = messages.len();
            history.extend(messages);
            eprintln!("agent686: resumed {} ({count} messages)", session.id);
            Ok((session, history))
        }
        None => {
            let system = agent::system_prompt();
            let session = Session::create(&cfg.model, &system)?;
            eprintln!(
                "agent686: new session {} ({})",
                session.id,
                session.path().display()
            );
            Ok((session, agent::new_history(system)))
        }
    }
}

/// The system prompt is frozen with the directory the session started in. If the
/// user resumes from somewhere else, tools and prompt disagree.
/// Git is the documented undo, so before a turn we snapshot the tree with a
/// commit when it is dirty. `/undo` resets back to this.
fn git_checkpoint() -> Option<String> {
    let Ok(cwd) = std::env::current_dir() else {
        return None;
    };
    agent686::git::checkpoint(&cwd)
}

fn undo(checkpoint: Option<&str>) {
    let Some(sha) = checkpoint else {
        eprintln!("agent686: /undo needs a git repository");
        return;
    };
    let Ok(cwd) = std::env::current_dir() else {
        return;
    };
    agent686::git::undo(&cwd, sha);
    eprintln!("agent686: restored to {sha}");
}

/// `/compact`: summarise the conversation and start again from the summary, in
/// the same session id. The only sanctioned rewrite of the transcript (ADR 0003).
fn compact(cfg: &Config, session: &mut Session, history: &mut Vec<Value>) {
    let system = history
        .first()
        .cloned()
        .unwrap_or_else(|| agent::system_prompt());
    let mut messages = history.clone();
    messages.push(json!({
        "role": "user",
        "content": "Summarize the conversation so far into one concise paragraph that \
                    preserves the goal, decisions made, files changed, and the current \
                    state. Omit pleasantries."
    }));
    let summary = match agent686::provider::summarize(cfg, &messages) {
        Ok(summary) if !summary.trim().is_empty() => summary,
        Ok(_) => {
            eprintln!("agent686: /compact produced an empty summary; aborting");
            return;
        }
        Err(error) => {
            eprintln!("agent686: /compact failed: {error}");
            return;
        }
    };

    let user = json!({
        "role": "user",
        "content": format!("[earlier conversation, summarized]\n{summary}"),
    });
    let new_history = vec![system.clone(), user];
    if let Err(error) = session.rewrite(&system, &new_history[1..]) {
        eprintln!("agent686: /compact could not rewrite the session: {error}");
        return;
    }
    *history = new_history;
    eprintln!(
        "agent686: compacted into a {}-character summary",
        summary.len()
    );
}

fn list_models(cfg: &Config) {
    match agent686::provider::models(cfg) {
        Ok(models) => {
            for model in models {
                if model == cfg.model {
                    println!("* {model}");
                } else {
                    println!("  {model}");
                }
            }
        }
        Err(error) => eprintln!("agent686: {error}"),
    }
}

fn switch_model(cfg: &mut Config, session: &mut Session, model: &str) {
    if model.is_empty() {
        eprintln!("agent686: /model needs a model id");
        return;
    }
    if model == cfg.model {
        eprintln!("agent686: already using {model}");
        return;
    }
    cfg.model = model.to_string();
    // The prompt and tool schemas are unchanged, but the model differs, so the
    // provider's prefix cache restarts.
    match session.record_model(model) {
        Ok(()) => eprintln!("agent686: switched to {model}"),
        Err(error) => eprintln!("agent686: {error}"),
    }
}

fn forget_sessions(text: &str, current: &Session) {
    let dir = session::sessions_dir();
    let target = text.trim_start_matches("/forget").trim();
    if target == "--all" {
        let removed = remove_all_except(&dir, &current.id);
        eprintln!("agent686: removed {removed} session(s)");
        return;
    }
    if target.is_empty() {
        eprintln!("agent686: /forget <id> or /forget --all");
        return;
    }
    if target == current.id {
        eprintln!("agent686: that is the current session; /forget it from elsewhere");
        return;
    }
    let path = dir.join(format!("{target}.jsonl"));
    match std::fs::remove_file(&path) {
        Ok(()) => eprintln!("agent686: removed {target}"),
        Err(error) => eprintln!("agent686: {target}: {error}"),
    }
}

fn remove_all_except(dir: &std::path::Path, keep: &str) -> usize {
    let mut removed = 0;
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        if path.file_stem().and_then(|s| s.to_str()) == Some(keep) {
            continue;
        }
        if std::fs::remove_file(&path).is_ok() {
            removed += 1;
        }
    }
    removed
}

fn warn_if_moved(session: &Session) {
    if session.cwd.is_empty() {
        return;
    }
    if let Ok(now) = std::env::current_dir() {
        let now = now.display().to_string();
        if now != session.cwd {
            eprintln!(
                "agent686: this session started in {}, but you are in {now}; tools use the \
                 current directory, and the prompt still describes the old one",
                session.cwd
            );
        }
    }
}

fn warn_if_changed(watched: &Option<(PathBuf, SystemTime)>, warned: &mut bool) {
    let (path, seen) = match watched {
        Some(watched) => watched,
        None => return,
    };
    if *warned {
        return;
    }
    if let Ok(modified) = std::fs::metadata(path).and_then(|m| m.modified()) {
        if modified != *seen {
            eprintln!(
                "agent686: {} changed; start a new session to pick it up",
                path.display()
            );
            *warned = true;
        }
    }
}

fn print_sessions(json: bool) {
    let sessions = match session::list() {
        Ok(sessions) => sessions,
        Err(error) => {
            eprintln!("agent686: {error}");
            return;
        }
    };
    if json {
        let rows: Vec<Value> = sessions
            .iter()
            .map(|info| {
                json!({
                    "id": info.id,
                    "model": info.model,
                    "messages": info.messages,
                    "modified_ms": info.modified.duration_since(UNIX_EPOCH)
                        .map(|d| d.as_millis() as u64).unwrap_or(0),
                    "path": info.path.display().to_string(),
                })
            })
            .collect();
        println!(
            "{}",
            serde_json::to_string(&rows).unwrap_or_else(|_| "[]".into())
        );
        return;
    }
    if sessions.is_empty() {
        println!("no sessions");
        return;
    }
    println!(
        "{:<34} {:<22} {:>5}  {:>4}",
        "SESSION", "MODEL", "MSGS", "AGE"
    );
    for info in sessions {
        println!(
            "{:<34} {:<22} {:>5}  {:>4}",
            info.id,
            info.model,
            info.messages,
            ago(info.modified)
        );
    }
}

fn ago(modified: SystemTime) -> String {
    let seconds = SystemTime::now()
        .duration_since(modified)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    match seconds {
        0..=59 => format!("{seconds}s"),
        60..=3599 => format!("{}m", seconds / 60),
        3600..=86_399 => format!("{}h", seconds / 3600),
        _ => format!("{}d", seconds / 86_400),
    }
}

/// `--yolo` with no approval and no undo is how a transcript ends up deleting a
/// checkout. Git is the documented undo, so `--yolo` needs a repository unless
/// allowed. `$HOME` and `/` are refused outright.
fn refuse_yolo(cfg: &Config) {
    if !cfg.yolo {
        return;
    }
    let Ok(cwd) = std::env::current_dir() else {
        return;
    };

    let home = std::env::var_os("HOME").map(PathBuf::from);
    let at_home = home.as_deref() == Some(cwd.as_path());
    let at_root = cwd.parent().is_none();
    if (at_home || at_root) && !cfg.allow_home {
        eprintln!(
            "agent686: refusing --yolo in {} — the model can overwrite anything here. \
             Run inside a project, or set allow_home in the config.",
            cwd.display()
        );
        std::process::exit(2);
    }

    if !in_git_repo(&cwd) && !cfg.allow_nogit {
        eprintln!(
            "agent686: refusing --yolo outside a git repository ({} has no .git), so \
             there is no undo. Run git init, or set allow_nogit in the config.",
            cwd.display()
        );
        std::process::exit(2);
    }
}

fn in_git_repo(dir: &Path) -> bool {
    agent686::git::in_repo(dir)
}

fn style(code: &str, text: &str, color: bool) -> String {
    if color {
        format!("\x1b[{code}m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

fn first_lines(text: &str, max: usize) -> String {
    let mut lines: Vec<String> = text
        .lines()
        .take(max)
        .map(|line| crate::truncate_line(line, 160))
        .collect();
    let total = text.lines().count();
    if total > max {
        lines.push(format!("… {} more line(s)", total - max));
    }
    lines.join("\n    ")
}

fn truncate_line(line: &str, max: usize) -> String {
    agent686::provider::truncate(line, max)
}

/// Renders a transcript: what was said, what was asked, what came back. Reads
/// the file without locking so it works while a session is open elsewhere.
fn show_session(id: Option<String>, json: bool) {
    let id = match id.or_else(|| session::latest().ok().flatten()) {
        Some(id) => id,
        None => {
            println!("no sessions");
            return;
        }
    };
    let path = session::sessions_dir().join(format!("{id}.jsonl"));
    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(error) => {
            eprintln!("agent686: {}: {error}", path.display());
            std::process::exit(1);
        }
    };

    let color = std::io::stdout().is_terminal()
        && std::env::var_os("NO_COLOR").is_none()
        && std::env::var("TERM").map(|t| t != "dumb").unwrap_or(true);

    let mut model = String::from("?");
    let mut cwd = String::new();
    let mut count = 0usize;
    let mut rendered = Vec::new();
    let mut messages_json: Vec<Value> = Vec::new();

    for line in text.lines() {
        let value: Value = match serde_json::from_str(line) {
            Ok(value) => value,
            Err(_) => continue,
        };
        match value.get("t").and_then(|t| t.as_str()) {
            Some("header") => {
                model = value
                    .get("model")
                    .and_then(|m| m.as_str())
                    .unwrap_or("?")
                    .to_string();
                cwd = value
                    .get("cwd")
                    .and_then(|c| c.as_str())
                    .unwrap_or("")
                    .to_string();
            }
            Some("model") => {
                if let Some(name) = value.get("model").and_then(|m| m.as_str()) {
                    rendered.push(style("2", &format!("— model switched to {name}"), color));
                }
            }
            Some("msg") => {
                count += 1;
                let mut message = value.clone();
                if let Some(object) = message.as_object_mut() {
                    object.remove("t");
                }
                messages_json.push(message.clone());
                rendered.push(render_message(&value, color));
            }
            _ => {}
        }
    }

    if json {
        let doc = json!({
            "id": id,
            "model": model,
            "cwd": cwd,
            "messages": messages_json,
        });
        println!("{}", serde_json::to_string(&doc).unwrap_or_default());
        return;
    }

    println!(
        "{}",
        style(
            "1",
            &format!("session {id} · {model} · {count} messages"),
            color
        )
    );
    if !cwd.is_empty() {
        println!("{}", style("2", &format!("started in {cwd}"), color));
    }
    println!("{}", style("2", &path.display().to_string(), color));
    println!();
    for block in rendered {
        println!("{block}");
    }
}

fn render_message(message: &Value, color: bool) -> String {
    match message.get("role").and_then(|r| r.as_str()).unwrap_or("?") {
        "user" => format!(
            "{}\n{}\n",
            style("1;33", "user", color),
            message
                .get("content")
                .and_then(|c| c.as_str())
                .unwrap_or("")
        ),
        "assistant" => {
            let mut out = String::new();
            if let Some(reasoning) = message.get("_reasoning").and_then(|r| r.as_str()) {
                out.push_str(&style("2", reasoning, color));
                out.push('\n');
            }
            if let Some(content) = message.get("content").and_then(|c| c.as_str()) {
                out.push_str(content);
                out.push('\n');
            }
            if let Some(calls) = message.get("tool_calls").and_then(|c| c.as_array()) {
                for call in calls {
                    let name = call
                        .get("function")
                        .and_then(|f| f.get("name"))
                        .and_then(|n| n.as_str())
                        .unwrap_or("?");
                    let args = call
                        .get("function")
                        .and_then(|f| f.get("arguments"))
                        .and_then(|a| a.as_str())
                        .unwrap_or("");
                    out.push_str(&style("1;36", &format!("  ● {name}"), color));
                    out.push('\n');
                    out.push_str(&style(
                        "2",
                        &format!("    {}", truncate_line(args, 200)),
                        color,
                    ));
                    out.push('\n');
                }
            }
            out
        }
        "tool" => format!(
            "{}\n",
            style(
                "2",
                &format!(
                    "  └ {}",
                    first_lines(
                        message
                            .get("content")
                            .and_then(|c| c.as_str())
                            .unwrap_or(""),
                        4
                    )
                ),
                color
            )
        ),
        other => format!("[{other}]\n"),
    }
}

/// On resume, show where the conversation left off: the last answer, or the last
/// reasoning when the model never produced content. Only on a terminal, so piped
/// runs stay clean.
fn print_last_reply(session: &Session) {
    if !std::io::stdout().is_terminal() {
        return;
    }
    let Some(reply) = session.last_reply.as_ref() else {
        return;
    };
    let text = if reply.content.trim().is_empty() {
        reply.reasoning.trim()
    } else {
        reply.content.trim()
    };
    if text.is_empty() {
        return;
    }

    let lines: Vec<&str> = text.lines().collect();
    let limit = 20;
    println!();
    println!("{}", style("2", "── where you left off ──", true));
    for line in lines.iter().take(limit) {
        println!("{line}");
    }
    if lines.len() > limit {
        println!(
            "{}",
            style(
                "2",
                &format!(
                    "… {} more line(s); `agent686 --show` for the transcript",
                    lines.len() - limit
                ),
                true
            )
        );
    }
    println!();
}