llmman 0.1.689

Run any agent on any model, models stored as OCI images
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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
//! `llmman run` — interactive chat or one-shot prompt.
//!
//! Interactive mode uses a raw-mode readline ported directly from ollama's
//! readline package (readline/readline.go, readline/term.go). Paste
//! detection mirrors ollama exactly:
//!
//!   // ollama (Go)
//!   if i.Terminal.reader.Buffered() > 0 { draining = true }
//!
//!   // llmman (Rust)
//!   if !reader.buffer().is_empty() { draining = true; }
//!
//! While draining a paste, '\n' submits the line like Enter; otherwise
//! it's Ctrl-J multiline, same as ollama.
//!
//! Streamed responses are ported from ollama's `cmd/cmd.go`
//! (`generate`/`chat`, `displayResponse`, `thinkingOutputOpeningText`/
//! `...ClosingText`): word-wrapped at the terminal width, "Thinking..."
//! in dim grey/bold ANSI, sent over an async reqwest client racing
//! `tokio::signal::ctrl_c()` so Ctrl-C cancels only the in-flight turn
//! (mirrors ollama's `context.WithCancel` + `signal.Notify`) instead of
//! killing the process. In the interactive REPL, raw mode is released
//! for the duration of each response and re-entered before the next
//! prompt — mirrors `readline.Instance.Readline()`'s own enter/`defer`
//! restore — which is why Ctrl-C while typing is read as byte 3 (ISIG
//! off) but Ctrl-C during a response is a real SIGINT (ISIG back on).
//!
//! Image attachments are ported from ollama's `cmd/interactive.go`: when
//! `/api/show` reports `vision`, image/audio paths in the prompt are
//! read, base64-encoded onto the message's `images`, and removed from
//! the text.

use std::io::{self, IsTerminal, Read, Seek, Write};
use std::path::Path;
use std::sync::OnceLock;

use anyhow::Context;
use base64::Engine as _;
use clap::Args;
use futures::TryStreamExt;
use indicatif::ProgressBar;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tokio::io::AsyncBufReadExt;

use crate::daemon;

mod decide;

// ---------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------

#[derive(Args, Debug, Clone)]
pub struct RunArgs {
    #[arg(value_name = "MODEL")]
    pub model: String,
    /// Chat with MODEL at this hosted provider (openai, anthropic,
    /// openrouter, …) instead of locally. The request still goes through
    /// `llmman serve`, which forwards it upstream; MODEL is the
    /// provider's own model id. See `llmman providers`.
    #[arg(long, short = 'p', value_name = "PROVIDER")]
    pub provider: Option<String>,
    /// Send requests too large for the local MODEL to this provider
    /// instead (openai, anthropic, openrouter, ...). Needs
    /// --overflow-model; not combinable with --provider.
    #[arg(long, value_name = "PROVIDER")]
    pub overflow_provider: Option<String>,
    /// The --overflow-provider model that serves requests too large for
    /// the local MODEL. Everything that fits stays on this machine.
    #[arg(long, value_name = "MODEL")]
    pub overflow_model: Option<String>,
    /// Forwarded as Ollama's own top-level `think` field on every request
    /// this sends (see cmd::serve::types's think_to_chat_template_kwargs) —
    /// `--think false` disables a reasoning model's thinking block
    /// entirely, `--think true` forces it on. Omitted (leaving the
    /// model's own template default in effect) if not passed at all.
    #[arg(long)]
    pub think: Option<bool>,
    /// Model variant, as opencode's `run --variant`: `none`, `thinking`
    /// or a level (see `llmman show`). Sent as `think`.
    #[arg(long, value_name = "VARIANT", conflicts_with = "think", value_parser = variant_parser())]
    pub variant: Option<String>,
    /// Forwarded as `options.num_predict` (Ollama's own name for
    /// llama-server's `max_tokens` — see opt_u32 in cmd::serve::ollama) on every
    /// request this sends: a hard ceiling on how many tokens a single
    /// reply may generate, regardless of *why* it might otherwise run
    /// away (a real, no-stopping-condition-hit degenerate loop, observed
    /// directly with qwen3.5:0.8b even with `--think false` and a
    /// repeat_penalty already in effect — see this repo's own git history
    /// — is not reliably preventable any other way). Omitted (no ceiling
    /// at all, matching Ollama's own num_predict default of -1) if not
    /// passed.
    #[arg(long)]
    pub num_predict: Option<u32>,
    /// Mirrors ollama's own `run --nowordwrap` — opts out of the
    /// terminal-width word wrap in `wrap_write` below.
    #[arg(long)]
    pub nowordwrap: bool,
    /// Image generation models only (see `crate::imagegen`): output
    /// width in pixels. Hidden, like ollama's own image flags.
    #[arg(long, hide = true, default_value_t = 0)]
    pub width: u32,
    /// Image generation models only: output height in pixels.
    #[arg(long, hide = true, default_value_t = 0)]
    pub height: u32,
    /// Image generation models only: denoising steps (0 = model default).
    #[arg(long, hide = true, default_value_t = 0)]
    pub steps: u32,
    /// Image generation models only: random seed.
    #[arg(long, hide = true)]
    pub seed: Option<u32>,
    /// Image generation models only: guidance scale (>1 enables --negative).
    #[arg(long, hide = true, default_value_t = 0.0)]
    pub cfg_scale: f32,
    /// Image generation models only: negative prompt.
    #[arg(long, hide = true, default_value = "")]
    pub negative: String,
    /// Media generation models only: generate a video (mp4) instead of
    /// an image.
    #[arg(long, hide = true, conflicts_with = "audio")]
    pub video: bool,
    /// Media generation models only: generate audio (wav) instead of an
    /// image.
    #[arg(long, hide = true)]
    pub audio: bool,
    /// Media generation models only: length of a --video / --audio clip.
    #[arg(long, hide = true, default_value_t = 0.0)]
    pub seconds: f32,
    /// Media generation models only: conditioning image (PNG/JPEG) for
    /// image-to-video, or an action run's first frame.
    #[arg(long, hide = true, value_name = "PATH")]
    pub image: Option<std::path::PathBuf>,
    /// Media generation models only: the conditioning video of a
    /// video-to-video or action run.
    #[arg(long, hide = true, value_name = "PATH")]
    pub input_video: Option<std::path::PathBuf>,
    /// Video-to-video: latent frames kept from --input-video (default 0,1).
    #[arg(long, hide = true, value_name = "IDX,IDX", default_value = "")]
    pub condition_frames: String,
    /// Video-to-video: take the conditioning frames from the end of the clip.
    #[arg(long, hide = true)]
    pub condition_keep_last: bool,
    /// Cosmos3 action run: forward_dynamics, inverse_dynamics or policy.
    #[arg(long, hide = true, value_name = "MODE")]
    pub action_mode: Option<String>,
    /// Cosmos3 action run: embodiment domain (bridge_orig_lerobot, av, ...).
    #[arg(long, hide = true, default_value = "")]
    pub action_domain: String,
    /// Cosmos3 action run: JSON file with the [T][D] actions (forward dynamics).
    #[arg(long, hide = true, value_name = "PATH")]
    pub actions: Option<std::path::PathBuf>,
    /// Cosmos3 action run: action transitions in the chunk.
    #[arg(long, hide = true, default_value_t = 0)]
    pub action_chunk: u32,
    /// Cosmos3 action run: conditioning canvas tier (256, 480, 704, 720).
    #[arg(long, hide = true, default_value_t = 480)]
    pub action_tier: u32,
    /// Cosmos3 action run: camera viewpoint (ego_view, third_person_view, ...).
    #[arg(long, hide = true, default_value = "ego_view")]
    pub action_view: String,
    /// Media generation models only: frames per second of the clip.
    #[arg(long, hide = true, default_value_t = 0.0)]
    pub fps: f32,
    /// Cosmos3: scheduler flow shift (the reference action runs use 10).
    #[arg(long, hide = true)]
    pub flow_shift: Option<f32>,
    /// How long the model stays loaded after the last request, as a
    /// duration (`5m`) or seconds: `0` unloads it at once, a negative value
    /// keeps it loaded. Defaults to the daemon's `LLMMAN_KEEP_ALIVE`.
    #[arg(long, value_name = "DURATION", allow_hyphen_values = true)]
    pub keepalive: Option<String>,
    /// Decision models only: `--ask`, with `--choice` and `--level`.
    #[command(flatten)]
    pub ask: decide::Asked,
    /// Decision models only: `json` prints the whole response.
    #[arg(long, value_name = "FORMAT", value_parser = ["json"])]
    pub format: Option<String>,
    /// Decision models only: show what the answers cost.
    #[arg(long)]
    pub verbose: bool,
    #[arg(
        value_name = "PROMPT",
        trailing_var_arg = true,
        allow_hyphen_values = true
    )]
    pub prompt: Vec<String>,
}

/// Every word `--variant` takes, here and on `launch`.
pub(crate) fn variants() -> impl Iterator<Item = &'static str> {
    let levels = crate::chat_template::EFFORT_LEVELS.iter().copied();
    ["none", "thinking"].into_iter().chain(levels)
}

/// Every `--variant`, here and on `launch`.
pub(crate) fn variant_parser() -> clap::builder::PossibleValuesParser {
    clap::builder::PossibleValuesParser::new(variants())
}

/// Ollama's `think`: a switch or a reasoning level.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
#[serde(untagged)]
enum Think<'a> {
    Switch(bool),
    Level(&'a str),
}

impl<'a> Think<'a> {
    /// `--variant`, else `--think`; clap rejects both.
    fn from_args(args: &'a RunArgs) -> Option<Self> {
        match args.variant.as_deref() {
            Some("none") => Some(Think::Switch(false)),
            Some("thinking") => Some(Think::Switch(true)),
            Some(level) => Some(Think::Level(level)),
            None => args.think.map(Think::Switch),
        }
    }
}

/// Per-request knobs threaded through unchanged from `RunArgs`.
#[derive(Debug, Clone, Copy)]
struct ChatOptions<'a> {
    think: Option<Think<'a>>,
    num_predict: Option<u32>,
    /// Inverse of `RunArgs::nowordwrap`, matching ollama's
    /// `runOptions.WordWrap` (defaults `true`).
    word_wrap: bool,
    /// Provider key to send with every request under `--provider` (see
    /// `provider_model`), `None` for a local model. Applied as a default
    /// header, not a body field — see `chat_client`.
    api_key: Option<&'a str>,
    /// Ollama's `runOptions.MultiModal`, from `/api/show`'s capabilities:
    /// only then is a prompt scanned for image paths.
    multimodal: bool,
    /// `--keepalive`.
    keep_alive: Option<&'a str>,
}

impl Default for ChatOptions<'_> {
    fn default() -> Self {
        Self {
            think: None,
            num_predict: None,
            word_wrap: true,
            api_key: None,
            multimodal: false,
            keep_alive: None,
        }
    }
}

pub fn run(args: &RunArgs) -> anyhow::Result<()> {
    let provider = crate::providers::provider_flag(args.provider.as_deref())?;
    let overflow = crate::hybrid::overflow_flags(
        args.overflow_provider.as_deref(),
        args.overflow_model.as_deref(),
        provider,
    )?;
    let prompt = args.prompt.join(" ");
    check_keepalive(args.keepalive.as_deref())?;

    // resolve_ollama_api, not resolve: `llmman run` is an /api/chat client
    // (see chat_submit/run_interactive_tty below), so a bare name must
    // resolve the same way it would if requested directly over the Ollama
    // API — otherwise a name resolved here, then handed to every /api/chat
    // request this sends, is no longer "bare" by the time ensure_model
    // resolves it server-side (it already has a "/" and a "."), so the
    // docker.io/ai/ default never fires and this silently falls back to
    // hf.co/<name> instead.
    //
    // Not applied under `--provider`: that MODEL names a model on someone
    // else's servers, so no shortname aliasing, tag defaulting, store
    // lookup or pull applies — the same call ensure_model makes
    // server-side. Resolved before the daemon starts, so a malformed
    // local reference still fails without one.
    let route = match provider {
        Some(provider) => Route::Provider(provider),
        None => Route::Local(crate::shortnames::resolve_ollama_api(&args.model)?),
    };

    // Starts `llmman serve` detached, left running indefinitely, if one
    // isn't already reachable — the same shared helper pull/push/launch
    // use (see daemon::ensure_server's doc comment for why stdio is
    // redirected there: without it, this command would hang forever
    // waiting for the (never-exiting) daemon's inherited stdout/stderr
    // pipes to close). No preload model is passed: the resulting daemon
    // is a plain `llmman serve` with no model argument, so it's shared
    // cleanly across every future `run`/`pull`/`push`/`launch` in this
    // session rather than looking like it's dedicated to whatever model
    // happened to start it first.
    //
    // A provider-routed model has nothing to preload or pull, but needs
    // the daemon sooner still: it owns the catalog `provider_model`
    // validates against, and it forwards the chat upstream.
    crate::daemon::ensure_server("")?;

    // Mirrors ollama's RunHandler: interactive needs *both* ends of the
    // terminal, not just stdin — otherwise a redirected stdout still gets
    // raw-moded and starts emitting ANSI escapes into it.
    let interactive = prompt.is_empty() && io::stdin().is_terminal() && io::stdout().is_terminal();

    let (model, api_key, multimodal) = match route {
        Route::Provider(provider) => {
            decide::reject_questions(args)?;
            let (model, key) = provider_model(provider, &args.model)?;
            // /api/show has no capabilities for a provider-routed model.
            (model, key, false)
        }
        Route::Local(model) => {
            // Fail fast on a bad/unresolvable reference — mirrors ollama's
            // RunHandler, which resolves (Show, falling back to Pull) the
            // model before ever showing its interactive prompt. Without
            // this, an error like an invalid `hf.co/...` reference wouldn't
            // surface until the first message was submitted to /api/chat,
            // well after the `> ` prompt had already been shown and read
            // from. The same Show also answers ollama's `opts.MultiModal`.
            let info = crate::daemon::ensure_model_pulled(&model)?;
            // A decision model answers questions instead of chatting.
            if info.decision() {
                return decide::run(&model, args, info.multimodal(), interactive);
            }
            decide::reject_questions(args)?;
            // An image generation model has no chat at all: every prompt
            // is a picture (ollama's `CapabilityImage` branch of
            // RunHandler, before it dropped image generation).
            if info.image() {
                let opts = crate::imagegen::ImageOptions {
                    media: if args.video {
                        crate::imagegen::Media::Video
                    } else if args.audio {
                        crate::imagegen::Media::Audio
                    } else {
                        crate::imagegen::Media::Image
                    },
                    width: args.width,
                    height: args.height,
                    steps: args.steps,
                    seed: args.seed,
                    cfg_scale: args.cfg_scale,
                    negative: args.negative.clone(),
                    seconds: args.seconds,
                    fps: args.fps,
                    flow_shift: args.flow_shift,
                    image: args.image.clone(),
                    input_video: args.input_video.clone(),
                    condition_frames: args.condition_frames.clone(),
                    condition_keep_last: args.condition_keep_last,
                    action: args
                        .action_mode
                        .as_ref()
                        .map(|mode| crate::imagegen::ActionOptions {
                            mode: mode.clone(),
                            domain: args.action_domain.clone(),
                            actions: args.actions.clone(),
                            chunk: args.action_chunk,
                            tier: args.action_tier,
                            view: args.action_view.clone(),
                        }),
                };
                return crate::imagegen::run(&model, &prompt, interactive, opts);
            }
            let multimodal = info.multimodal();
            match overflow {
                // The hosted half is validated and keyed as a bare
                // --provider model is, then paired with the local model.
                Some((provider, hosted)) => {
                    let (remote, key) = provider_model(provider, hosted)?;
                    (
                        crate::hybrid::pair_with_local(&model, &remote)?,
                        key,
                        multimodal,
                    )
                }
                None => (model, None, multimodal),
            }
        }
    };

    let opts = ChatOptions {
        think: Think::from_args(args),
        num_predict: args.num_predict,
        word_wrap: !args.nowordwrap,
        api_key: api_key.as_deref(),
        multimodal,
        keep_alive: args.keepalive.as_deref(),
    };

    if interactive {
        run_interactive_tty(&mut Chat::new(&model, opts)?)
    } else {
        let p = if prompt.is_empty() {
            let mut s = String::new();
            io::stdin().read_line(&mut s)?;
            s.trim().to_string()
        } else {
            prompt
        };
        if !p.is_empty() {
            // One-shot "conversation" over /api/chat, same helper as
            // interactive mode. A fresh tokio runtime, not
            // reqwest::blocking, so Ctrl-C can race the response via
            // `tokio::select!` in `chat_submit` — see that fn's doc comment.
            let rt = tokio::runtime::Runtime::new().context("start tokio runtime")?;
            let client = chat_client(opts.api_key)?;
            chat_submit(&rt, &client, &model, &mut Vec::new(), p, opts)?;
        }
        Ok(())
    }
}

/// Fails on a `--keepalive` the daemon could not read; it would quietly
/// take its default.
fn check_keepalive(keepalive: Option<&str>) -> anyhow::Result<()> {
    if let Some(keepalive) = keepalive {
        anyhow::ensure!(
            crate::cmd::serve::parse_keep_alive_str(keepalive).is_some(),
            "invalid --keepalive {keepalive:?}: want a duration such as 5m, or seconds"
        );
    }
    Ok(())
}

/// Where this chat goes: a local reference, already resolved (see `run`),
/// or a provider id `provider_model` still has to validate.
enum Route<'a> {
    Local(String),
    Provider(&'a str),
}

/// Validates `--provider`/MODEL against the daemon's catalog, returning
/// the reference the daemon routes on (see
/// [`crate::providers::REMOTE_PREFIX`]) and the key to send with each
/// request, if this shell has one.
///
/// Mirrors `cmd::launch`'s `resolve_provider_model` minus the
/// integrations: the key travels per request in an `Authorization` header
/// (see `client_api_key` in cmd::serve), never to disk.
fn provider_model(provider: &str, model: &str) -> anyhow::Result<(String, Option<String>)> {
    // Same rule as `launch --provider` (see check_provider_supported in
    // cmd::launch): a key sent to a daemon elsewhere on the network over
    // plain http would cross it in cleartext. A wildcard bind is fine —
    // that hop is still loopback — and so is an `https://` LLMMAN_HOST.
    anyhow::ensure!(
        crate::daemon::connects_securely(),
        "--provider needs a local llmman serve, or one over TLS: LLMMAN_HOST points at {}, \
         and the provider key would cross the network in cleartext.\n\
         Export the key where that daemon runs, and run llmman there.",
        crate::daemon::server()
    );

    let model = model.trim();
    let entry = daemon::provider(provider, Some(model).filter(|m| !m.is_empty()))?;
    anyhow::ensure!(
        !model.is_empty(),
        "--provider {provider} also needs a model\n\n{}",
        crate::providers::example_models(&entry.name, &entry.model_ids())
    );

    entry.warn_unlisted(model);

    // Naming where the missing key goes beats a 401 mid-conversation —
    // unless the daemon has one of its own, or the provider takes none.
    let key = entry.client_key();
    anyhow::ensure!(
        key.is_some() || entry.daemon_key_usable() || entry.key_optional,
        "no API key for {} — {}",
        entry.name,
        entry.key_hint()
    );
    Ok((crate::providers::format_remote_ref(provider, model), key))
}

// ---------------------------------------------------------------------------
// Wire types
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Msg {
    role: String,
    content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    thinking: Option<String>,
    /// Ollama's `api.Message.Images`: standard base64, one per image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    images: Option<Vec<String>>,
}

impl Msg {
    fn text(role: &str, content: String) -> Self {
        Self {
            role: role.into(),
            content,
            thinking: None,
            images: None,
        }
    }
}

/// Async, not `reqwest::blocking`, so a chat turn's response can be raced
/// against `tokio::signal::ctrl_c()` in `chat_submit` — no `.timeout()`
/// needed either, unlike the blocking client's own 30s default.
///
/// A `--provider` key rides along as a default header for `client_api_key`
/// in cmd::serve to read: `Authorization: Bearer`, or `x-api-key` when
/// the daemon's own key already occupies the bearer, so both arrive.
fn chat_client(api_key: Option<&str>) -> anyhow::Result<Client> {
    let mut headers = crate::auth::client_headers()?;
    if let Some(key) = api_key {
        if headers.contains_key(reqwest::header::AUTHORIZATION) {
            let mut value = reqwest::header::HeaderValue::from_str(key)
                .context("provider API key is not a valid HTTP header value")?;
            value.set_sensitive(true);
            headers.insert("x-api-key", value);
        } else {
            headers.insert(reqwest::header::AUTHORIZATION, crate::auth::bearer(key)?);
        }
    }
    // No redirects: reqwest drops `Authorization` across origins but not
    // `x-api-key`, and the daemon never redirects anyway.
    crate::daemon::async_client_builder()?
        .default_headers(headers)
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .context("build http client")
}

#[derive(Serialize)]
struct ChatReq<'a> {
    model: &'a str,
    messages: &'a [Msg],
    stream: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    keep_alive: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    think: Option<Think<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    options: Option<ChatReqOptions>,
}

#[derive(Serialize)]
struct ChatReqOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    num_predict: Option<u32>,
}

#[derive(Deserialize)]
struct ChatChunk {
    #[serde(default)]
    message: Option<Msg>,
    #[serde(default)]
    done: bool,
}

// ---------------------------------------------------------------------------
// Image attachments — ported from ollama's cmd/interactive.go
// ---------------------------------------------------------------------------

/// Ollama's `normalizeFilePath`: undoes shell escaping from a drag-and-drop
/// (`My\ Photo.jpg` → `My Photo.jpg`). Same table and order as its
/// `strings.NewReplacer`.
fn normalize_file_path(fp: &str) -> String {
    const PAIRS: &[(&str, &str)] = &[
        ("\\ ", " "),
        ("\\(", "("),
        ("\\)", ")"),
        ("\\[", "["),
        ("\\]", "]"),
        ("\\{", "{"),
        ("\\}", "}"),
        ("\\$", "$"),
        ("\\&", "&"),
        ("\\;", ";"),
        ("\\'", "'"),
        ("\\\\", "\\"),
        ("\\*", "*"),
        ("\\?", "?"),
        ("\\~", "~"),
    ];
    let mut out = String::with_capacity(fp.len());
    let mut rest = fp;
    'outer: while !rest.is_empty() {
        for (from, to) in PAIRS {
            if let Some(tail) = rest.strip_prefix(from) {
                out.push_str(to);
                rest = tail;
                continue 'outer;
            }
        }
        let ch = rest.chars().next().expect("non-empty");
        out.push(ch);
        rest = &rest[ch.len_utf8()..];
    }
    out
}

/// Ollama's `extractFileNames`, regex verbatim. Over-matches on purpose;
/// `extract_file_data` drops anything that isn't a real file.
fn extract_file_names(input: &str) -> Vec<&str> {
    static RE: OnceLock<regex::Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        regex::Regex::new(r"(?:[a-zA-Z]:)?(?:\./|/|\\)[\S\\ ]+?\.(?i:jpg|jpeg|png|webp|wav)\b")
            .expect("valid regex")
    });
    re.find_iter(input).map(|m| m.as_str()).collect()
}

/// Ollama's `extractFileData`: base64-encodes every existing image/audio
/// file named in `input` and strips the paths (and surrounding single
/// quotes) from the text. A missing path is left in place; an existing
/// file of an unsupported type is an error.
fn extract_file_data(input: &str) -> anyhow::Result<(String, Vec<String>)> {
    let (text, files) = extract_files(input)?;
    let engine = base64::engine::general_purpose::STANDARD;
    Ok((text, files.iter().map(|f| engine.encode(&f.data)).collect()))
}

/// A file [`extract_files`] read: its sniffed MIME type and bytes.
struct MediaFile {
    content_type: &'static str,
    data: Vec<u8>,
}

/// [`extract_file_data`] before the encoding: a decision model also wants
/// the type, for a data URL.
fn extract_files(input: &str) -> anyhow::Result<(String, Vec<MediaFile>)> {
    let mut out = input.to_string();
    let mut files = Vec::new();

    for fp in extract_file_names(input) {
        let nfp = normalize_file_path(fp);
        let data = match get_image_data(&nfp) {
            Ok(data) => data,
            Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
            Err(e) => {
                eprintln!("Couldn't process file: {:?}", e.to_string());
                return Err(e.into());
            }
        };
        let ext = Path::new(&nfp)
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_lowercase())
            .unwrap_or_default();
        match ext.as_str() {
            "wav" => eprintln!("Added audio '{nfp}'"),
            _ => eprintln!("Added image '{nfp}'"),
        }
        out = out.replace(&format!("'{nfp}'"), "");
        out = out.replace(&format!("'{fp}'"), "");
        out = out.replace(fp, "");
        files.push(MediaFile {
            content_type: detect_content_type(&data),
            data,
        });
    }
    Ok((out.trim().to_string(), files))
}

/// Ollama's `getImageData`: sniff the first 512 bytes, cap at 100MB, then
/// read exactly the stat'd size (its `io.ReadFull` into a sized buffer).
fn get_image_data(file_path: &str) -> io::Result<Vec<u8>> {
    let mut file = std::fs::File::open(file_path)?;

    let mut buf = [0u8; 512];
    if file.read(&mut buf)? == 0 {
        // Go's Read on an empty file is io.EOF: an error, not a skip.
        return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF"));
    }

    let content_type = detect_content_type(&buf);
    const ALLOWED: &[&str] = &[
        "image/jpeg",
        "image/jpg",
        "image/png",
        "image/webp",
        "audio/wave",
    ];
    if !ALLOWED.contains(&content_type) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!("invalid file type: {content_type}"),
        ));
    }

    let size = file.metadata()?.len();
    const MAX_SIZE: u64 = 100 * 1024 * 1024;
    if size > MAX_SIZE {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "file size exceeds maximum limit (100MB)",
        ));
    }

    let mut data = Vec::with_capacity(size as usize);
    file.seek(io::SeekFrom::Start(0))?;
    file.take(size).read_to_end(&mut data)?;
    if data.len() as u64 != size {
        return Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "unexpected EOF",
        ));
    }
    Ok(data)
}

/// The cases of Go's `http.DetectContentType` that `get_image_data` can
/// accept; everything else is the sniffer's `application/octet-stream`.
fn detect_content_type(data: &[u8]) -> &'static str {
    fn masked(data: &[u8], mask: &[u8], pat: &[u8]) -> bool {
        data.len() >= pat.len()
            && data
                .iter()
                .zip(mask)
                .zip(pat)
                .all(|((d, m), p)| d & m == *p)
    }
    if data.starts_with(b"\xFF\xD8\xFF") {
        "image/jpeg"
    } else if data.starts_with(b"\x89PNG\x0D\x0A\x1A\x0A") {
        "image/png"
    } else if masked(
        data,
        b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF",
        b"RIFF\x00\x00\x00\x00WEBPVP",
    ) {
        "image/webp"
    } else if masked(
        data,
        b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF",
        b"RIFF\x00\x00\x00\x00WAVE",
    ) {
        "audio/wave"
    } else {
        "application/octet-stream"
    }
}

// ---------------------------------------------------------------------------
// Terminal rendering — ported from ollama's cmd.go (displayResponse,
// thinkingOutputOpeningText/ClosingText): the "Thinking..." block is the
// one place `ollama run` colors anything.
// ---------------------------------------------------------------------------

/// ollama's readline.ColorGrey/ColorBold/ColorDefault (readline/types.go).
const COLOR_GREY: &str = "\x1b[38;5;245m";
const COLOR_BOLD: &str = "\x1b[1m";
const COLOR_DEFAULT: &str = "\x1b[0m";

/// Mirrors ollama's `thinkingOutputOpeningText`. Ends re-applying grey
/// (not a full reset) so the streamed thinking text after it can rely on
/// that still-active SGR state instead of coloring itself.
fn thinking_opening_text(plain: bool) -> String {
    let text = "Thinking...\n";
    if plain {
        text.to_string()
    } else {
        format!("{COLOR_GREY}{COLOR_BOLD}{text}{COLOR_DEFAULT}{COLOR_GREY}")
    }
}

/// Mirrors ollama's `thinkingOutputClosingText` — a full reset this time.
fn thinking_closing_text(plain: bool) -> String {
    let text = "...done thinking.\n\n";
    if plain {
        text.to_string()
    } else {
        format!("{COLOR_GREY}{COLOR_BOLD}{text}{COLOR_DEFAULT}")
    }
}

/// Mirrors ollama's `displayResponseState`.
#[derive(Default)]
struct WrapState {
    line_length: usize,
    word_buffer: String,
}

/// Terminal width, falling back to 80 like ollama's `displayResponse`
/// does when `term.GetSize` fails (e.g. not a real terminal).
fn term_width() -> usize {
    crate::fmt::terminal_cols(1).map_or(80, usize::from)
}

/// Pure computation half of `wrap_write`, split out so it's testable
/// without a real terminal. Direct port of ollama's `displayResponse`:
/// track the current word, and once a line would overflow, backtrack to
/// its start, clear to end of line, and continue on the next one. Every
/// char counts as one column (no `runewidth`-style CJK width handling).
fn wrap_chunk(content: &str, wrap: bool, width: usize, state: &mut WrapState) -> String {
    let mut out = String::new();
    if wrap && width >= 10 {
        for ch in content.chars() {
            if state.line_length + 1 > width - 5 {
                if state.word_buffer.chars().count() > width - 10 {
                    out.push_str(&state.word_buffer);
                    out.push(ch);
                    state.word_buffer.clear();
                    state.line_length = 0;
                    continue;
                }
                let a = state.word_buffer.chars().count();
                if a > 0 {
                    out.push_str(&format!("\x1b[{a}D"));
                }
                out.push_str("\x1b[K\n");
                out.push_str(&state.word_buffer);
                out.push(ch);
                state.line_length = state.word_buffer.chars().count() + 1;
            } else {
                out.push(ch);
                state.line_length += 1;
                match ch {
                    ' ' | '\t' => state.word_buffer.clear(),
                    '\n' | '\r' => {
                        state.line_length = 0;
                        state.word_buffer.clear();
                    }
                    _ => state.word_buffer.push(ch),
                }
            }
        }
    } else {
        out.push_str(&state.word_buffer);
        out.push_str(content);
        state.word_buffer.clear();
    }
    out
}

/// Streams `content` to stdout, word-wrapped via `wrap_chunk` above.
fn wrap_write(content: &str, wrap: bool, state: &mut WrapState) {
    let out = wrap_chunk(content, wrap, term_width(), state);
    print!("{out}");
    io::stdout().flush().ok();
}

/// Mirrors ollama's `progress.NewSpinner("")` (`chat`/`generate` in
/// cmd.go): a braille spinner shown until the first streamed response
/// object arrives, same glyphs and 100ms tick. Unlike ollama, only shown
/// when stderr is a real terminal, so a piped stderr doesn't get raw
/// escape sequences dumped into it.
fn start_spinner() -> Option<ProgressBar> {
    if !io::stderr().is_terminal() {
        return None;
    }
    Some(crate::fmt::braille_spinner("{spinner} "))
}

/// RAII wrapper around `start_spinner`'s result — mirrors ollama's own
/// `defer p.StopAndClear()`: whichever of `chat_submit_async`'s
/// early-return paths fires, this clears any still-running spinner
/// exactly once.
struct SpinnerGuard(Option<ProgressBar>);

impl SpinnerGuard {
    /// Called on Ctrl-C or once the first response object is decoded —
    /// a no-op after the first call, like ollama's own `Spinner.Stop`.
    fn stop(&mut self) {
        if let Some(sp) = self.0.take() {
            sp.finish_and_clear();
        }
    }
}

impl Drop for SpinnerGuard {
    fn drop(&mut self) {
        self.stop();
    }
}

// ---------------------------------------------------------------------------
// Interactive — TTY path
// ---------------------------------------------------------------------------

/// What the interactive loop does with what is typed: a chat turn, or for a
/// decision model (see [`decide`]) a text or questions about it. The loop
/// owns reading, paste handling, `"""` blocks and `/` commands.
trait Turns {
    /// Whether an image path is a file to attach, not an unknown `/` command.
    #[cfg_attr(not(unix), allow(dead_code))]
    fn multimodal(&self) -> bool;
    /// One submitted message, with the terminal out of raw mode so Ctrl-C
    /// reaches the request.
    fn submit(&mut self, content: String) -> anyhow::Result<()>;
    /// `/clear`.
    fn clear(&mut self);
}

/// A conversation with a chat model over `/api/chat`.
struct Chat<'a> {
    // One runtime for every turn; see `chat_submit`.
    rt: tokio::runtime::Runtime,
    client: Client,
    model: &'a str,
    messages: Vec<Msg>,
    opts: ChatOptions<'a>,
}

impl<'a> Chat<'a> {
    fn new(model: &'a str, opts: ChatOptions<'a>) -> anyhow::Result<Self> {
        Ok(Self {
            rt: tokio::runtime::Runtime::new().context("start tokio runtime")?,
            client: chat_client(opts.api_key)?,
            model,
            messages: Vec::new(),
            opts,
        })
    }
}

impl Turns for Chat<'_> {
    fn multimodal(&self) -> bool {
        self.opts.multimodal
    }

    fn submit(&mut self, content: String) -> anyhow::Result<()> {
        chat_submit(
            &self.rt,
            &self.client,
            self.model,
            &mut self.messages,
            content,
            self.opts,
        )
    }

    fn clear(&mut self) {
        self.messages.clear();
        eprintln!("Conversation cleared.");
    }
}

fn run_interactive_tty(turns: &mut dyn Turns) -> anyhow::Result<()> {
    #[cfg(unix)]
    {
        run_interactive_unix(turns)
    }
    #[cfg(not(unix))]
    {
        // Windows fallback: basic cooked-mode loop
        run_interactive_cooked(turns)
    }
}

// ---------------------------------------------------------------------------
// Interactive — Unix raw-mode readline (ported from ollama readline package)
// ---------------------------------------------------------------------------

#[cfg(unix)]
fn run_interactive_unix(turns: &mut dyn Turns) -> anyhow::Result<()> {
    use unix_readline::Readline;

    let mut rl = Readline::new()?;
    let mut multiline: Option<String> = None; // Some while inside """
                                              // Accumulates lines while rl.pasting, mirrors ollama's `sb`.
    let mut paste_sb = String::new();

    loop {
        // ". " is ollama's AltPrompt: shown both inside a """ block
        // and while a bracketed paste is still accumulating.
        let prompt = if multiline.is_some() || !paste_sb.is_empty() {
            ". "
        } else {
            "> "
        };

        let line = match rl.readline(prompt) {
            Ok(Some(l)) => l,
            Ok(None) => break,
            Err(unix_readline::ReadlineError::Interrupted) => {
                multiline = None;
                paste_sb.clear();
                continue;
            }
        };

        // ── Bracketed paste accumulation ────────────────────────────────────
        // Mirrors `case scanner.Pasting: fmt.Fprintln(&sb, line); continue`
        // rl.pasting is true while between \x1b[200~ and \x1b[201~.
        // While pasting, ACCUMULATE into paste_sb WITHOUT submitting.
        // When pasting ends, the final line falls through to normal handling
        // with paste_sb prepended — same as ollama's `default: sb.WriteString`.
        if rl.pasting {
            paste_sb.push_str(&line);
            paste_sb.push('\n');
            continue;
        }

        // Not pasting: prepend any accumulated paste content to this line.
        // (ollama: `default: sb.WriteString(line)` then submit if sb.Len()>0)
        let line = if !paste_sb.is_empty() {
            let mut full = std::mem::take(&mut paste_sb);
            full.push_str(&line);
            full
        } else {
            line
        };

        // ── """ multiline mode ───────────────────────────────────────────────
        if let Some(ref mut buf) = multiline {
            if let Some(content) = line.strip_suffix("\"\"\"") {
                buf.push_str(content);
                let full = std::mem::take(buf).trim_end_matches('\n').to_string();
                multiline = None;
                if !full.trim().is_empty() {
                    submit_turn(&mut rl, turns, full)?;
                }
            } else {
                buf.push_str(&line);
                buf.push('\n');
            }
            continue;
        }

        // ── Slash commands ───────────────────────────────────────────────────
        match line.trim() {
            "" => continue,
            "/bye" | "/exit" => break,
            "/clear" => {
                turns.clear();
                continue;
            }
            s if s.starts_with('/') => {
                // Ollama: a line starting with an image path is a prompt,
                // not an unknown command, when the model is multimodal.
                let first_word = s.split_whitespace().next().unwrap_or(s);
                let is_file = turns.multimodal()
                    && extract_file_names(s)
                        .iter()
                        .any(|f| f.starts_with(first_word));
                if !is_file {
                    eprintln!("Unknown command '{first_word}'.");
                    eprintln!("Commands: /bye  /clear  \"\"\" (multiline)");
                    continue;
                }
            }
            _ => {}
        }

        // ── Triple-quote multiline opener ────────────────────────────────────
        if line.trim_start().starts_with("\"\"\"") {
            let inner = line.trim_start().trim_start_matches("\"\"\"");
            if let Some(closed) = inner.strip_suffix("\"\"\"") {
                let content = closed.to_string();
                if !content.trim().is_empty() {
                    submit_turn(&mut rl, turns, content)?;
                }
            } else {
                multiline = Some(inner.to_string() + "\n");
            }
            continue;
        }

        if !line.trim().is_empty() {
            submit_turn(&mut rl, turns, line)?;
        }
    }

    Ok(())
}

/// Wraps `chat_submit` with the raw-mode toggle that lets Ctrl-C actually
/// interrupt a streaming response — mirrors ollama's
/// `readline.Instance.Readline()`, which holds raw mode only around
/// reading one line. Without this, raw mode (ISIG off) would stay active
/// through the response too, so Ctrl-C would just sit as an unread byte 3
/// until the next `rl.readline()` call instead of interrupting now.
#[cfg(unix)]
fn submit_turn(
    rl: &mut unix_readline::Readline,
    turns: &mut dyn Turns,
    content: String,
) -> anyhow::Result<()> {
    rl.leave_raw();
    let result = turns.submit(content);
    rl.enter_raw();
    result
}

/// Sends one chat turn and streams the response, racing it against
/// Ctrl-C — mirrors ollama's per-turn `context.WithCancel` +
/// `signal.Notify(SIGINT)`: Ctrl-C stops just this turn's response
/// without killing the process. An interrupted turn's partial reply is
/// *not* added to `messages`, matching cmd.go's `chat` returning `nil`
/// on `context.Canceled`.
///
/// Async, not `reqwest::blocking`, so the stream can be raced against
/// `tokio::signal::ctrl_c()` via `tokio::select!` below.
fn chat_submit(
    rt: &tokio::runtime::Runtime,
    client: &Client,
    model: &str,
    messages: &mut Vec<Msg>,
    content: String,
    opts: ChatOptions<'_>,
) -> anyhow::Result<()> {
    rt.block_on(chat_submit_async(client, model, messages, content, opts))
}

async fn chat_submit_async(
    client: &Client,
    model: &str,
    messages: &mut Vec<Msg>,
    content: String,
    opts: ChatOptions<'_>,
) -> anyhow::Result<()> {
    // Ollama: `if opts.MultiModal { ... extractFileData(opts.Prompt) }`.
    // A non-vision model gets the path as plain text, as there.
    let mut user = Msg::text("user", content);
    if opts.multimodal {
        let (text, images) = extract_file_data(&user.content)?;
        user.content = text;
        if !images.is_empty() {
            user.images = Some(images);
        }
    }
    messages.push(user);

    // Mirrors ollama's `progress.NewSpinner("")`: ticks on stderr until
    // the first token/thinking chunk arrives, so `llmman run` doesn't sit
    // silently while a cold model loads server-side.
    let mut spinner = SpinnerGuard(start_spinner());

    // One listener for this whole turn, mirroring ollama's own
    // `signal.Notify(sigChan, syscall.SIGINT)` called once per turn (not
    // per streamed chunk). Recreating `tokio::signal::ctrl_c()` on every
    // loop iteration would subscribe a fresh listener each time, and a
    // SIGINT delivered in the gap between the old one dropping and the
    // new one subscribing could be missed — pinning it once and reusing
    // it via `&mut` closes that gap.
    let ctrl_c = tokio::signal::ctrl_c();
    tokio::pin!(ctrl_c);

    let send = client
        .post(format!("{}/api/chat", daemon::server()))
        .json(&ChatReq {
            model,
            messages,
            stream: true,
            keep_alive: opts.keep_alive,
            think: opts.think,
            options: opts.num_predict.map(|n| ChatReqOptions {
                num_predict: Some(n),
            }),
        })
        .send();

    let resp = tokio::select! {
        r = send => r.context("connect to llmman serve")?,
        // Nothing printed yet, so just stop — `spinner`'s Drop clears it.
        _ = &mut ctrl_c => return Ok(()),
    };

    if !resp.status().is_success() {
        spinner.stop();
        let body = resp.text().await.unwrap_or_default();
        // The daemon's own message, not the JSON envelope around it: a
        // provider's 401 naming the key it rejected is the whole of what
        // is needed here.
        anyhow::bail!("{}", daemon::api_error(&body).unwrap_or(body));
    }

    // Stream NDJSON lines as they arrive, async so each read can be
    // `tokio::select!`ed against Ctrl-C below.
    let byte_stream = resp.bytes_stream().map_err(io::Error::other);
    let mut lines =
        tokio::io::BufReader::new(tokio_util::io::StreamReader::new(byte_stream)).lines();

    // Mirrors ollama's `plainText`: no ANSI codes when stdout is redirected.
    let plain_text = !io::stdout().is_terminal();
    let mut full = String::new();
    let mut thinking_content = String::new();
    let mut thinking_open = false;
    let mut thinking_closed = false;
    let mut wrap = WrapState::default();
    let mut interrupted = false;

    loop {
        let line = tokio::select! {
            l = lines.next_line() => l.context("read response stream")?,
            // Same pinned listener as above, see its comment for why.
            _ = &mut ctrl_c => { interrupted = true; break; }
        };
        let Some(line) = line else { break };
        if line.is_empty() {
            continue;
        }
        let Ok(chunk) = serde_json::from_str::<ChatChunk>(&line) else {
            continue;
        };
        // Cleared on the first decoded response object, like ollama's
        // own `fn` callback.
        spinner.stop();
        if let Some(ref msg) = chunk.message {
            if let Some(ref t) = msg.thinking {
                if !t.is_empty() {
                    if !thinking_open {
                        print!("{}", thinking_opening_text(plain_text));
                        thinking_open = true;
                        thinking_closed = false;
                    }
                    thinking_content.push_str(t);
                    wrap_write(t, opts.word_wrap, &mut wrap);
                }
            }
            if thinking_open && !thinking_closed && !msg.content.is_empty() {
                if !thinking_content.ends_with('\n') {
                    println!();
                }
                print!("{}", thinking_closing_text(plain_text));
                thinking_open = false;
                thinking_closed = true;
                wrap = WrapState::default();
            }
            if !msg.content.is_empty() {
                wrap_write(&msg.content, opts.word_wrap, &mut wrap);
                full.push_str(&msg.content);
            }
        }
        if chunk.done {
            break;
        }
    }

    if interrupted {
        return Ok(());
    }

    println!("\n");
    messages.push(Msg::text("assistant", full));
    Ok(())
}

// ---------------------------------------------------------------------------
// Unix raw-mode readline — direct port of ollama readline/readline.go
// ---------------------------------------------------------------------------

#[cfg(unix)]
mod unix_readline {
    use std::io::{BufReader, Read, Stdin, Write};
    use std::os::unix::io::AsRawFd;

    // Character codes — identical to ollama readline/types.go
    const CHAR_INTERRUPT: u8 = 3; // Ctrl-C
    const CHAR_EOF: u8 = 4; // Ctrl-D
    const CHAR_CTRL_J: u8 = 10; // \n  line feed / pasted newline
    const CHAR_ENTER: u8 = 13; // \r  keyboard Enter
    const CHAR_ESC: u8 = 27;
    const CHAR_ESCAPE_EX: u8 = 91; // '[' — second byte of ESC[
    const CHAR_BACKSPACE: u8 = 127;

    pub enum ReadlineError {
        Interrupted,
    }

    // CharBracketedPaste = 50 ('2') — third byte of ESC[ sequence;
    // reading 3 more bytes gives "00~" (paste start) or "01~" (paste end).
    // Mirrors ollama readline/types.go: CharBracketedPaste/Start/End.
    const CHAR_BRACKETED_PASTE: u8 = 50; // '2'
    const PASTE_START: &[u8; 3] = b"00~";
    const PASTE_END: &[u8; 3] = b"01~";

    pub struct Readline {
        reader: BufReader<Stdin>,
        orig: libc::termios,
        fd: std::os::unix::io::RawFd,
        pub pasting: bool, // true while inside \x1b[200~...\x1b[201~
    }

    impl Readline {
        /// Enable raw mode + bracketed paste (mirrors ollama SetRawMode + StartBracketedPaste).
        pub fn new() -> anyhow::Result<Self> {
            let stdin = std::io::stdin();
            let fd = stdin.as_raw_fd();

            let orig = unsafe {
                let mut t: libc::termios = std::mem::zeroed();
                if libc::tcgetattr(fd, &mut t) < 0 {
                    anyhow::bail!("tcgetattr failed");
                }
                t
            };

            let rl = Self {
                reader: BufReader::new(stdin),
                orig,
                fd,
                pasting: false,
            };
            if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &rl.raw_termios()) } < 0 {
                anyhow::bail!("tcsetattr failed");
            }

            // Enable bracketed paste for the whole session (toggled off
            // once, in Drop) — mirrors ollama's own start/end pair
            // wrapping the entire REPL loop, not each `Readline()` call.
            print!("\x1b[?2004h");
            std::io::stdout().flush().ok();

            Ok(rl)
        }

        /// Raw-mode termios derived from `orig`, mirrors `SetRawMode`.
        fn raw_termios(&self) -> libc::termios {
            let mut raw = self.orig;
            raw.c_iflag &= !(libc::IGNBRK
                | libc::BRKINT
                | libc::PARMRK
                | libc::ISTRIP
                | libc::INLCR
                | libc::IGNCR
                | libc::ICRNL
                | libc::IXON);
            raw.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
            raw.c_cflag &= !(libc::CSIZE | libc::PARENB);
            raw.c_cflag |= libc::CS8;
            raw.c_cc[libc::VMIN] = 1;
            raw.c_cc[libc::VTIME] = 0;
            raw
        }

        /// (Re-)enters raw mode — used by `new()` and by `run::submit_turn`
        /// to undo `leave_raw` before the next `readline()` call.
        pub fn enter_raw(&self) {
            unsafe {
                libc::tcsetattr(self.fd, libc::TCSANOW, &self.raw_termios());
            }
        }

        /// Restores cooked (ISIG-enabled) mode for the duration of a
        /// streamed response, so a real SIGINT reaches `chat_submit`'s
        /// `ctrl_c()` instead of raw mode swallowing it as a plain byte 3.
        pub fn leave_raw(&self) {
            unsafe {
                libc::tcsetattr(self.fd, libc::TCSANOW, &self.orig);
            }
        }

        /// Read one logical line from the terminal.
        ///
        /// Paste detection mirrors ollama readline/readline.go exactly:
        ///   - After each read, check reader.buffer() (≡ reader.Buffered() in Go)
        ///   - If non-empty → draining (we are consuming a paste)
        ///   - CharCtrlJ (\n) while draining → submit (same as Enter)
        ///   - CharCtrlJ while NOT draining → Ctrl-J multiline continuation
        ///   - CharEnter (\r) → always submit
        pub fn readline(&mut self, prompt: &str) -> Result<Option<String>, ReadlineError> {
            print!("{prompt}");
            std::io::stdout().flush().ok();

            let mut buf: Vec<u8> = Vec::new();
            let mut pasted_lines: Vec<String> = Vec::new();
            let mut draining = false;
            let mut stop_draining = false;
            let mut esc = false;
            let mut esc_ex = false;

            loop {
                // Apply deferred state from previous iteration (ollama lines 130-134)
                if stop_draining {
                    draining = false;
                    stop_draining = false;
                }

                // Read exactly one byte
                let mut b = [0u8; 1];
                match self.reader.read_exact(&mut b) {
                    Ok(_) => {}
                    Err(_) => return Ok(None),
                }
                let r = b[0];

                // Paste detection: mirrors `if i.Terminal.reader.Buffered() > 0`
                if !self.reader.buffer().is_empty() {
                    draining = true;
                } else if draining {
                    stop_draining = true;
                }

                // ESC sequence handling — mirrors ollama readline.go escex block.
                // Key addition: CharBracketedPaste ('2') reads 3 more bytes to
                // detect "00~" (paste start) or "01~" (paste end).
                if esc_ex {
                    esc_ex = false;
                    match r {
                        CHAR_BRACKETED_PASTE => {
                            // Read 3 more bytes: "00~" or "01~"
                            let mut code = [0u8; 3];
                            if self.reader.read_exact(&mut code).is_ok() {
                                if &code == PASTE_START {
                                    self.pasting = true;
                                } else if &code == PASTE_END {
                                    self.pasting = false;
                                }
                                // Update draining after reading extra bytes
                                if !self.reader.buffer().is_empty() {
                                    draining = true;
                                }
                            }
                        }
                        // Consume the '~' for delete/other 2-byte sequences
                        51 | 53 | 54 => {
                            let mut tilde = [0u8; 1];
                            let _ = self.reader.read_exact(&mut tilde);
                        }
                        _ => {} // arrow keys etc. — just skip
                    }
                    continue;
                } else if esc {
                    esc = false;
                    if r == CHAR_ESCAPE_EX {
                        esc_ex = true;
                    }
                    continue;
                }

                match r {
                    CHAR_INTERRUPT => {
                        pasted_lines.clear();
                        buf.clear();
                        println!();
                        return Err(ReadlineError::Interrupted);
                    }
                    CHAR_EOF => {
                        // Mirrors ollama's `case CharDelete`: only checks
                        // the current line's own buffer, so Ctrl-D on a
                        // fresh empty continuation line exits the whole
                        // REPL even mid-multiline-entry.
                        if buf.is_empty() {
                            println!();
                            return Ok(None);
                        }
                    }
                    CHAR_ESC => {
                        esc = true;
                    }
                    CHAR_BACKSPACE => {
                        if !buf.is_empty() {
                            // Remove last complete UTF-8 codepoint
                            loop {
                                match buf.pop() {
                                    None => break,
                                    Some(b) if (b & 0xC0) != 0x80 => break, // lead byte
                                    Some(_) => {} // continuation byte, keep going
                                }
                            }
                            print!("\x08 \x08");
                            std::io::stdout().flush().ok();
                        } else if !pasted_lines.is_empty() {
                            let prev = pasted_lines.pop().unwrap();
                            print!("\r\x1b[K\x1b[A\r\x1b[K{prompt}{prev}");
                            std::io::stdout().flush().ok();
                            buf = prev.into_bytes();
                        }
                    }
                    CHAR_CTRL_J => {
                        // \n: pasted newline (draining) or Ctrl-J multiline (not draining)
                        // Mirrors ollama case CharCtrlJ
                        if !draining {
                            // Not draining → multiline continuation (Ctrl-J typed)
                            pasted_lines.push(String::from_utf8_lossy(&buf).to_string());
                            buf.clear();
                            println!();
                            print!(". ");
                            std::io::stdout().flush().ok();
                        } else {
                            // Draining → submit (pasted \n acts like Enter)
                            return Ok(Some(Self::assemble(&mut buf, &mut pasted_lines)));
                        }
                    }
                    CHAR_ENTER => {
                        // \r: keyboard Enter → always submit
                        return Ok(Some(Self::assemble(&mut buf, &mut pasted_lines)));
                    }
                    c => {
                        // Printable ASCII, tab, or UTF-8 bytes
                        if c >= 32 || c == 9 || c >= 0x80 {
                            buf.push(c);
                            let _ = std::io::stdout().write_all(&[c]);
                            std::io::stdout().flush().ok();
                        }
                    }
                }
            }
        }

        fn assemble(buf: &mut Vec<u8>, pasted_lines: &mut Vec<String>) -> String {
            let last = String::from_utf8_lossy(buf).to_string();
            buf.clear();
            println!();
            if pasted_lines.is_empty() {
                last
            } else {
                let prefix = pasted_lines.join("\n");
                pasted_lines.clear();
                format!("{prefix}\n{last}")
            }
        }
    }

    impl Drop for Readline {
        fn drop(&mut self) {
            // Disable bracketed paste, restore terminal — mirrors ollama's defer
            print!("\x1b[?2004l");
            std::io::stdout().flush().ok();
            unsafe {
                libc::tcsetattr(self.fd, libc::TCSANOW, &self.orig);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Windows / non-TTY fallback (cooked mode)
// ---------------------------------------------------------------------------

#[allow(dead_code)]
fn run_interactive_cooked(turns: &mut dyn Turns) -> anyhow::Result<()> {
    use std::io::BufRead;
    let stdin = std::io::stdin();
    let mut reader = std::io::BufReader::new(stdin.lock());

    loop {
        print!("> ");
        io::stdout().flush().ok();
        let mut line = String::new();
        if reader.read_line(&mut line)? == 0 {
            break;
        }
        let line = line
            .trim_end_matches('\n')
            .trim_end_matches('\r')
            .to_string();
        match line.trim() {
            "" => continue,
            "/bye" | "/exit" => break,
            "/clear" => {
                turns.clear();
                continue;
            }
            _ => {}
        }
        if !line.trim().is_empty() {
            turns.submit(line)?;
        }
    }
    Ok(())
}

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

    #[test]
    fn chat_options_default_matches_ollamas_own_wordwrap_true_default() {
        let opts = ChatOptions::default();
        assert_eq!(opts.think, None);
        assert_eq!(opts.num_predict, None);
        assert!(opts.word_wrap);
        assert!(!opts.multimodal);
    }

    fn parse(argv: &[&str]) -> Result<RunArgs, clap::Error> {
        #[derive(clap::Parser)]
        struct Cli {
            #[command(flatten)]
            args: RunArgs,
        }
        let argv = ["run", "m"].iter().chain(argv);
        <Cli as clap::Parser>::try_parse_from(argv).map(|c| c.args)
    }

    fn think_json(argv: &[&str]) -> serde_json::Value {
        serde_json::to_value(Think::from_args(&parse(argv).unwrap())).unwrap()
    }

    #[test]
    fn variant_is_sent_as_ollamas_think() {
        assert_eq!(think_json(&[]), serde_json::Value::Null);
        assert_eq!(think_json(&["--variant", "none"]), false);
        assert_eq!(think_json(&["--variant", "thinking"]), true);
        assert_eq!(think_json(&["--variant", "xhigh"]), "xhigh");
        assert_eq!(think_json(&["--think", "false"]), false);
    }

    /// For clap the prompt takes everything from its first word on, flags
    /// included; a decision model re-parses it (see `decide::reparse`).
    #[test]
    fn ask_flags_come_before_the_prompt() {
        let args = parse(&[
            "--ask",
            "Is it spam?",
            "--format",
            "json",
            "Win",
            "a",
            "cruise",
        ])
        .unwrap();
        assert!(!args.ask.is_empty());
        assert_eq!(args.format.as_deref(), Some("json"));
        assert_eq!(args.prompt, ["Win", "a", "cruise"]);

        let args = parse(&["Win a cruise", "--ask", "Is it spam?"]).unwrap();
        assert!(args.ask.is_empty());
        assert_eq!(args.prompt, ["Win a cruise", "--ask", "Is it spam?"]);

        assert!(parse(&["--format", "xml"]).is_err());
    }

    /// `--keepalive` rides on the chat request, and takes negative values.
    #[test]
    fn keepalive_rides_on_the_chat_request() {
        let body = |keep_alive| {
            serde_json::to_value(ChatReq {
                model: "m",
                messages: &[],
                stream: true,
                keep_alive,
                think: None,
                options: None,
            })
            .unwrap()
        };
        assert_eq!(body(Some("5m"))["keep_alive"], "5m");
        assert!(body(None).get("keep_alive").is_none());
        for value in ["1h30m", "-1", "-5m"] {
            let args = parse(&["--keepalive", value]).unwrap();
            assert_eq!(args.keepalive.as_deref(), Some(value));
        }
    }

    #[test]
    fn variant_rejects_unknown_names_and_think() {
        assert!(parse(&["--variant", "turbo"]).is_err());
        assert!(parse(&["--variant", "high", "--think", "true"]).is_err());
    }

    // -- image attachments: ports of ollama's cmd/interactive_test.go ------

    /// Ollama's `TestExtractFilenames`, unix-style half.
    #[test]
    fn extract_file_names_unix_style_paths() {
        let input = " some preamble \n \
./relative\\ path/one.png inbetween1 ./not a valid two.jpg inbetween2 ./1.svg\n\
/unescaped space /three.jpeg inbetween3 /valid\\ path/dir/four.png \"./quoted with spaces/five.JPG\n\
/unescaped space /six.webp inbetween6 /valid\\ path/dir/seven.WEBP";
        let res = extract_file_names(input);
        assert_eq!(res.len(), 7, "{res:?}");
        assert!(res[0].contains("one.png"));
        assert!(res[1].contains("two.jpg"));
        assert!(res[2].contains("three.jpeg"));
        assert!(res[3].contains("four.png"));
        assert!(res[4].contains("five.JPG"));
        assert!(res[5].contains("six.webp"));
        assert!(res[6].contains("seven.WEBP"));
        assert!(!res[4].contains('"'));
        assert!(!res.contains(&"inbetween1"));
        assert!(!res.contains(&"./1.svg"));
    }

    /// Ollama's `TestExtractFilenames`, windows-style half.
    #[test]
    fn extract_file_names_windows_style_paths() {
        let input = " some preamble\n \
c:/users/jdoe/one.png inbetween1 c:/program files/someplace/two.jpg inbetween2 \n \
/absolute/nospace/three.jpeg inbetween3 /absolute/with space/four.png inbetween4\n\
./relative\\ path/five.JPG inbetween5 \"./relative with/spaces/six.png inbetween6\n\
d:\\path with\\spaces\\seven.JPEG inbetween7 c:\\users\\jdoe\\eight.png inbetween8 \n \
d:\\program files\\someplace\\nine.png inbetween9 \"E:\\program files\\someplace\\ten.PNG\n\
c:/users/jdoe/eleven.webp inbetween11 c:/program files/someplace/twelve.WebP inbetween12\n\
d:\\path with\\spaces\\thirteen.WEBP some ending\n";
        let res = extract_file_names(input);
        assert_eq!(res.len(), 13, "{res:?}");
        assert!(!res.contains(&"inbetween2"));
        assert!(res[0].contains("one.png") && res[0].contains("c:"));
        assert!(res[1].contains("two.jpg") && res[1].contains("c:"));
        assert!(res[2].contains("three.jpeg"));
        assert!(res[3].contains("four.png"));
        assert!(res[4].contains("five.JPG"));
        assert!(res[5].contains("six.png"));
        assert!(res[6].contains("seven.JPEG") && res[6].contains("d:"));
        assert!(res[7].contains("eight.png") && res[7].contains("c:"));
        assert!(res[8].contains("nine.png") && res[8].contains("d:"));
        assert!(res[9].contains("ten.PNG") && res[9].contains("E:"));
        assert!(res[10].contains("eleven.webp") && res[10].contains("c:"));
        assert!(res[11].contains("twelve.WebP") && res[11].contains("c:"));
        assert!(res[12].contains("thirteen.WEBP") && res[12].contains("d:"));
    }

    #[test]
    fn normalize_file_path_undoes_shell_escapes() {
        assert_eq!(
            normalize_file_path("/My\\ Photos/a\\(1\\)\\[x\\]\\{y\\}\\$\\&\\;\\'\\*\\?\\~.png"),
            "/My Photos/a(1)[x]{y}$&;'*?~.png"
        );
        assert_eq!(normalize_file_path("a\\\\b"), "a\\b");
        assert_eq!(normalize_file_path("/plain/path.jpg"), "/plain/path.jpg");
    }

    #[test]
    fn detect_content_type_matches_gos_sniffer_for_the_allowed_types() {
        assert_eq!(
            detect_content_type(b"\xFF\xD8\xFF\xE0\x00\x10JFIF"),
            "image/jpeg"
        );
        assert_eq!(
            detect_content_type(b"\x89PNG\x0D\x0A\x1A\x0A\x00\x00\x00\x0DIHDR"),
            "image/png"
        );
        assert_eq!(
            detect_content_type(b"RIFF\x24\x00\x00\x00WEBPVP8 "),
            "image/webp"
        );
        assert_eq!(
            detect_content_type(b"RIFF\x58\x02\x00\x00WAVEfmt "),
            "audio/wave"
        );
        assert_eq!(detect_content_type(b"GIF89a"), "application/octet-stream");
        assert_eq!(detect_content_type(b"hello"), "application/octet-stream");
        assert_eq!(detect_content_type(b"RIFF"), "application/octet-stream");
    }

    fn temp_file(name: &str, data: &[u8]) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "llmman-run-img-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let fp = dir.join(name);
        std::fs::write(&fp, data).unwrap();
        fp
    }

    fn jpeg_bytes() -> Vec<u8> {
        let mut data = vec![0u8; 600];
        data[..22].copy_from_slice(&[
            0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, b'J', b'F', b'I', b'F', 0x00, 0x01, 0x01, 0x01,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xd9,
        ]);
        data
    }

    /// Ollama's `TestExtractFileDataRemovesQuotedFilepath`.
    #[test]
    fn extract_file_data_removes_quoted_filepath() {
        let fp = temp_file("img.jpg", &jpeg_bytes());
        let input = format!("before '{}' after", fp.display());
        let (cleaned, imgs) = extract_file_data(&input).unwrap();
        assert_eq!(imgs.len(), 1);
        assert_eq!(cleaned, "before  after");
    }

    /// Ollama's `TestExtractFileDataWAV`.
    #[test]
    fn extract_file_data_wav() {
        let mut data = vec![0u8; 600];
        data[..44].copy_from_slice(&[
            b'R', b'I', b'F', b'F', //
            0x58, 0x02, 0x00, 0x00, // file size - 8
            b'W', b'A', b'V', b'E', //
            b'f', b'm', b't', b' ', //
            0x10, 0x00, 0x00, 0x00, // fmt chunk size
            0x01, 0x00, // PCM
            0x01, 0x00, // mono
            0x80, 0x3e, 0x00, 0x00, // 16000 Hz
            0x00, 0x7d, 0x00, 0x00, // byte rate
            0x02, 0x00, // block align
            0x10, 0x00, // 16-bit
            b'd', b'a', b't', b'a', //
            0x34, 0x02, 0x00, 0x00, // data size
        ]);
        let fp = temp_file("sample.wav", &data);
        let input = format!("before {} after", fp.display());
        let (cleaned, imgs) = extract_file_data(&input).unwrap();
        assert_eq!(imgs.len(), 1);
        assert_eq!(cleaned, "before  after");
    }

    #[test]
    fn extract_file_data_encodes_the_file_as_standard_base64() {
        let bytes = jpeg_bytes();
        let fp = temp_file("img.jpg", &bytes);
        let (_, imgs) = extract_file_data(&format!("look: {}", fp.display())).unwrap();
        assert_eq!(
            imgs,
            vec![base64::engine::general_purpose::STANDARD.encode(&bytes)]
        );
    }

    #[test]
    fn extract_file_data_leaves_a_nonexistent_path_in_the_prompt() {
        let input = "what is in /definitely/not/here.png then";
        let (cleaned, imgs) = extract_file_data(input).unwrap();
        assert!(imgs.is_empty());
        assert_eq!(cleaned, input);
    }

    #[test]
    fn extract_file_data_rejects_an_existing_file_of_the_wrong_type() {
        let fp = temp_file("fake.png", b"this is not a png at all, just text");
        let err = extract_file_data(&format!("see {}", fp.display())).unwrap_err();
        assert!(err.to_string().contains("invalid file type"), "{err:#}");
    }

    #[test]
    fn msg_images_is_omitted_from_json_when_none() {
        let json = serde_json::to_string(&Msg::text("user", "hi".into())).unwrap();
        assert_eq!(json, r#"{"role":"user","content":"hi"}"#);
        let mut with = Msg::text("user", "hi".into());
        with.images = Some(vec!["QUJD".into()]);
        let json = serde_json::to_string(&with).unwrap();
        assert_eq!(json, r#"{"role":"user","content":"hi","images":["QUJD"]}"#);
    }

    #[test]
    fn thinking_opening_text_plain_has_no_ansi_codes() {
        assert_eq!(thinking_opening_text(true), "Thinking...\n");
    }

    #[test]
    fn thinking_opening_text_colored_wraps_in_grey_bold_then_grey_again() {
        let text = thinking_opening_text(false);
        assert!(text.starts_with(&format!("{COLOR_GREY}{COLOR_BOLD}")));
        assert!(text.contains("Thinking...\n"));
        // Re-applies grey rather than a full reset.
        assert!(text.ends_with(&format!("{COLOR_DEFAULT}{COLOR_GREY}")));
    }

    #[test]
    fn thinking_closing_text_plain_has_no_ansi_codes() {
        assert_eq!(thinking_closing_text(true), "...done thinking.\n\n");
    }

    #[test]
    fn thinking_closing_text_colored_ends_in_a_full_reset() {
        let text = thinking_closing_text(false);
        assert!(text.starts_with(&format!("{COLOR_GREY}{COLOR_BOLD}")));
        assert!(text.contains("...done thinking.\n\n"));
        assert!(text.ends_with(COLOR_DEFAULT));
        assert!(!text.ends_with(&format!("{COLOR_DEFAULT}{COLOR_GREY}")));
    }

    #[test]
    fn wrap_chunk_disabled_passes_content_through_unchanged() {
        let mut state = WrapState::default();
        let out = wrap_chunk(
            "hello there, this line is not wrapped at all",
            false,
            20,
            &mut state,
        );
        assert_eq!(out, "hello there, this line is not wrapped at all");
    }

    #[test]
    fn wrap_chunk_too_narrow_terminal_passes_content_through_unchanged() {
        // Mirrors ollama's `wordWrap && termWidth >= 10` guard.
        let mut state = WrapState::default();
        let out = wrap_chunk("hello there", true, 9, &mut state);
        assert_eq!(out, "hello there");
    }

    #[test]
    fn wrap_chunk_breaks_before_a_word_that_would_overflow_the_line() {
        let mut state = WrapState::default();
        // width=20: overflow threshold is line_length+1 > width-5 (>15).
        let out = wrap_chunk("one two three four five", true, 20, &mut state);
        // "four" gets backtracked onto a new line instead of splitting.
        assert!(out.contains("\x1b[K\n"));
        let after_break = out.split("\x1b[K\n").nth(1).unwrap();
        assert!(after_break.starts_with("four"));
    }

    #[test]
    fn wrap_chunk_state_persists_across_calls_like_a_single_stream() {
        // Several small calls (one per streamed token) must wrap the
        // same as one big call, carried via WrapState between them.
        let mut state_streamed = WrapState::default();
        let mut streamed = String::new();
        for word in ["one ", "two ", "three ", "four ", "five"] {
            streamed.push_str(&wrap_chunk(word, true, 20, &mut state_streamed));
        }

        let mut state_whole = WrapState::default();
        let whole = wrap_chunk("one two three four five", true, 20, &mut state_whole);

        assert_eq!(streamed, whole);
    }

    #[test]
    fn wrap_chunk_an_unbroken_word_longer_than_the_line_flushes_without_backtracking() {
        // A word too long to ever fit its own line skips the backtrack
        // and just flushes the buffered prefix again — faithfully
        // mirroring ollama's own `fmt.Printf("%s%c", wordBuffer, ch)`
        // here, the buffered prefix really does appear twice in the
        // output for this rare edge case.
        let mut state = WrapState::default();
        let out = wrap_chunk("supercalifragilisticexpialidocious", true, 20, &mut state);
        assert_eq!(
            out,
            "supercalifragilsupercalifragilisticexpialidocisticexpialidocious"
        );
    }
}