byob-tools 0.3.12

Agent tools: filesystem, web fetch, charts, python (L2)
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
//! Artifacts: versioned files the model makes beside the conversation (see
//! [`byob_protocol::artifact`]). `create_artifact`, `update_artifact` and `read_artifact`.
//!
//! What an artifact is and what is done with it per type (content checks, prompt guidance,
//! how it is served) comes from the [`ArtifactTypes`] registry the tools are given; nothing
//! here knows a particular type.
//!
//! Layout, in the chat's workspace:
//!
//! ```text
//! .byob/artifacts/<id>/artifact.json   the index: chat, type, title, file name, versions
//! .byob/artifacts/<id>/v1.html         one file per version, never overwritten
//! ```
//!
//! Charts and images other tools make (`charts/…chart.json`, a PNG from `run_python`) are
//! *adopted*: they get an index whose single version points at the file where it is.
//!
//! Access: [`Access::Read`], like `make_chart`: these tools only ever create new files
//! inside `.byob/artifacts/` (exclusively, never through links) and rewrite their own index.
//! A version a per-turn undo removed simply drops out of the list.

use std::fs::OpenOptions;
use std::io::{ErrorKind, Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use byob_protocol::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion, MediaKind, MediaRef, artifact::valid_id};

use crate::artifact_types::{ArtifactType, ArtifactTypes};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::sandbox;
use crate::{Access, FileChange, Tool, ToolContext, ToolOutput, ToolSpec, parse_args};

/// Workspace folder artifacts live in (inside byob's reserved `.byob`).
pub const ARTIFACT_DIR: &str = ".byob/artifacts";
const META_FILE: &str = "artifact.json";
/// Largest artifact content the model may write (per version).
pub const MAX_CONTENT_BYTES: usize = 1024 * 1024;
/// Largest version file read back (adopted images may be bigger than what tools write).
pub const MAX_FILE_BYTES: u64 = 32 * 1024 * 1024;
/// Find/replace edits in one `update_artifact` call.
pub use crate::edits::MAX_EDITS;
/// Versions one artifact may have.
pub const MAX_VERSIONS: usize = 500;
const MAX_TITLE_CHARS: usize = 80;
const MAX_NOTE_CHARS: usize = 200;
const MAX_META_BYTES: u64 = 512 * 1024;
/// Artifact folders looked at when listing a workspace.
const MAX_LISTED: usize = 2000;
/// Charts/images adopted from one tool call.
const MAX_ADOPTED: usize = 4;
/// Text returned by `read_artifact`.
const MAX_READ_CHARS: usize = 200_000;

/// The index file: an artifact and the chat it belongs to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Meta {
    pub chat: String,
    /// A live file: the person's own file (relative to the workspace) this artifact follows.
    /// Its versions are snapshots of it; removing the artifact never touches the file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub live: Option<String>,
    #[serde(flatten)]
    pub artifact: Artifact,
}

/// Milliseconds since the epoch, strictly increasing within the process (so artifacts made
/// in the same millisecond still list in order).
fn now_ms() -> i64 {
    static LAST: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0);
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));
    let prev = LAST.try_update(Ordering::AcqRel, Ordering::Acquire, |last| Some(now.max(last.saturating_add(1)))).unwrap_or(now);
    now.max(prev.saturating_add(1))
}

/// `.byob/artifacts`, created if needed; refuses links anywhere on the way.
fn root_dir(workspace: &Path) -> Result<(PathBuf, PathBuf), String> {
    let r = sandbox::resolve(workspace, ARTIFACT_DIR)?;
    for dir in [r.root.join(sandbox::RESERVED_DIR), r.abs.clone()] {
        match std::fs::symlink_metadata(&dir) {
            Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return Err(format!("{} is not a plain folder; can't keep artifacts there", dir.display())),
            Ok(_) => {}
            Err(e) if e.kind() == ErrorKind::NotFound => std::fs::create_dir(&dir)
                .or_else(|e| if e.kind() == ErrorKind::AlreadyExists { Ok(()) } else { Err(e) })
                .map_err(|e| format!("can't create {}: {e}", dir.display()))?,
            Err(e) => return Err(format!("can't access {}: {e}", dir.display())),
        }
    }
    Ok((r.root, r.abs))
}

/// The folder of artifact `id` (which must exist and be a plain folder).
fn artifact_dir(workspace: &Path, id: &str) -> Result<(PathBuf, PathBuf), String> {
    if !valid_id(id) {
        return Err(format!("there is no artifact {id:?}"));
    }
    let r = sandbox::resolve(workspace, &format!("{ARTIFACT_DIR}/{id}"))?;
    match std::fs::symlink_metadata(&r.abs) {
        Ok(m) if m.is_dir() && !m.file_type().is_symlink() => Ok((r.root, r.abs)),
        _ => Err(format!("there is no artifact {id:?}")),
    }
}

fn read_capped(path: &Path, max: u64) -> Result<Vec<u8>, String> {
    let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    let meta = std::fs::metadata(path).map_err(|e| format!("{name}: {e}"))?;
    if !meta.is_file() {
        return Err(format!("{name} is not a file"));
    }
    if meta.len() > max {
        return Err(format!("{name} is too big ({} bytes)", meta.len()));
    }
    let mut out = Vec::new();
    std::fs::File::open(path).and_then(|f| f.take(max).read_to_end(&mut out)).map_err(|e| format!("{name}: {e}"))?;
    Ok(out)
}

/// The file behind a version path, if it is still there (inside the workspace).
fn version_file(workspace: &Path, path: &str) -> Option<PathBuf> {
    let r = sandbox::resolve_follow(workspace, path).ok()?;
    std::fs::metadata(&r.abs).ok().filter(std::fs::Metadata::is_file).map(|_| r.abs)
}

/// Read an artifact's index. Versions whose file is gone (e.g. undone) are left out; an
/// artifact with none left is gone.
pub fn load(workspace: &Path, id: &str) -> Result<Meta, String> {
    let (_, dir) = artifact_dir(workspace, id)?;
    let bytes = read_capped(&dir.join(META_FILE), MAX_META_BYTES).map_err(|_| format!("there is no artifact {id:?}"))?;
    let mut meta: Meta = serde_json::from_slice(&bytes).map_err(|e| format!("artifact {id:?} has a broken index: {e}"))?;
    if meta.artifact.id != id {
        return Err(format!("artifact {id:?} has a broken index"));
    }
    meta.artifact.versions.retain(|v| version_file(workspace, &v.path).is_some());
    // Indices written before content types (or with a broken one): what its kind stands for.
    meta.artifact.content_type = meta.artifact.content_type().to_owned();
    if meta.artifact.versions.is_empty() {
        return Err(format!("artifact {id:?} no longer exists"));
    }
    Ok(meta)
}

/// Like [`load`], but only an artifact of `chat`.
pub fn load_in_chat(workspace: &Path, chat: &str, id: &str) -> Result<Meta, String> {
    let meta = load(workspace, id)?;
    if meta.chat != chat {
        return Err(format!("there is no artifact {id:?} in this chat"));
    }
    Ok(meta)
}

/// Write the index (via a temporary file, so a crash never leaves half of one).
fn save(dir: &Path, meta: &Meta) -> Result<(), String> {
    let json = serde_json::to_vec_pretty(meta).map_err(|e| e.to_string())?;
    let tmp = dir.join(format!("{META_FILE}.tmp"));
    let _ = std::fs::remove_file(&tmp);
    let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| format!("can't save the artifact index: {e}"))?;
    f.write_all(&json).map_err(|e| format!("can't save the artifact index: {e}"))?;
    drop(f);
    std::fs::rename(&tmp, dir.join(META_FILE)).map_err(|e| format!("can't save the artifact index: {e}"))
}

/// Every artifact of `chat` in `workspace`, oldest first.
pub fn list(workspace: &Path, chat: &str) -> Vec<Artifact> {
    let Ok(r) = sandbox::resolve(workspace, ARTIFACT_DIR) else { return Vec::new() };
    let Ok(entries) = std::fs::read_dir(&r.abs) else { return Vec::new() };
    let mut out: Vec<Artifact> = entries
        .take(MAX_LISTED)
        .filter_map(Result::ok)
        .filter_map(|e| e.file_name().to_str().map(str::to_owned))
        .filter(|id| valid_id(id))
        .filter_map(|id| load(workspace, &id).ok())
        .filter(|m| m.chat == chat)
        .map(|m| m.artifact)
        .collect();
    out.sort_by_key(|a| (a.versions.first().map_or(0, |v| v.created_at), a.id.clone()));
    out
}

/// Every artifact in `workspace`, with the chat it belongs to (the Library).
pub fn list_all(workspace: &Path) -> Vec<(String, Artifact)> {
    let Ok(r) = sandbox::resolve(workspace, ARTIFACT_DIR) else { return Vec::new() };
    let Ok(entries) = std::fs::read_dir(&r.abs) else { return Vec::new() };
    entries
        .take(MAX_LISTED)
        .filter_map(Result::ok)
        .filter_map(|e| e.file_name().to_str().map(str::to_owned))
        .filter(|id| valid_id(id))
        .filter_map(|id| load(workspace, &id).ok())
        .map(|m| (m.chat, m.artifact))
        .collect()
}

/// Every artifact in `workspace` with its index (chat, live file).
pub fn list_all_meta(workspace: &Path) -> Vec<Meta> {
    let Ok(r) = sandbox::resolve(workspace, ARTIFACT_DIR) else { return Vec::new() };
    let Ok(entries) = std::fs::read_dir(&r.abs) else { return Vec::new() };
    entries
        .take(MAX_LISTED)
        .filter_map(Result::ok)
        .filter_map(|e| e.file_name().to_str().map(str::to_owned))
        .filter(|id| valid_id(id))
        .filter_map(|id| load(workspace, &id).ok())
        .collect()
}

/// Add the person's own file `path` (relative to `workspace`, inside it, not in `.byob`) to
/// the Library as a live file of `chat`: a first snapshot now, a new one whenever it changes
/// ([`refresh_live`]). The file itself is never written or removed by this.
pub fn add_live(types: &ArtifactTypes, workspace: &Path, chat: &str, path: &str) -> Result<Artifact, String> {
    let rel = path.trim().trim_start_matches("./").to_owned();
    if rel.is_empty() || rel.split(['/', '\\']).next() == Some(sandbox::RESERVED_DIR) {
        return Err("that file can't be added".into());
    }
    let r = sandbox::resolve(workspace, &rel)?;
    // by its full path too (`rel` may be absolute)
    if r.abs.strip_prefix(&r.root).ok().and_then(|p| p.components().next()).is_some_and(|c| c.as_os_str() == sandbox::RESERVED_DIR) {
        return Err("that file can't be added".into());
    }
    let info = std::fs::symlink_metadata(&r.abs).map_err(|_| format!("there is no file {rel:?}"))?;
    if !info.is_file() {
        return Err(format!("{rel:?} isn't a file"));
    }
    if let Some(m) = list_all_meta(workspace).into_iter().find(|m| m.chat == chat && m.live.as_deref() == Some(rel.as_str())) {
        return Ok(m.artifact);
    }
    let bytes = read_capped(&r.abs, MAX_FILE_BYTES)?;
    let name = rel.rsplit(['/', '\\']).next().unwrap_or(&rel).to_owned();
    let saved = save_bytes(
        types,
        workspace,
        &SaveBytes { chat, id: None, title: Some(&name), filename: Some(&name), bytes: &bytes, note: "Your file", replace: None, turn: None },
    )?;
    let (_, dir) = artifact_dir(workspace, &saved.artifact.id)?;
    let mut meta = load(workspace, &saved.artifact.id)?;
    meta.live = Some(rel);
    save(&dir, &meta)?;
    Ok(meta.artifact)
}

/// Live files that changed since their latest snapshot (by byob or in another app) get a new
/// snapshot, so no change is ever lost. Returns how many changed.
pub fn refresh_live(types: &ArtifactTypes, workspace: &Path) -> usize {
    let mut changed = 0;
    for meta in list_all_meta(workspace) {
        let Some(rel) = meta.live.as_deref() else { continue };
        let Ok(r) = sandbox::resolve(workspace, rel) else { continue };
        let Ok(now) = read_capped(&r.abs, MAX_FILE_BYTES) else { continue };
        let latest = meta.artifact.latest().and_then(|v| version_file(workspace, &v.path)).and_then(|f| read_capped(&f, MAX_FILE_BYTES).ok());
        if latest.as_deref() == Some(now.as_slice()) || now.is_empty() {
            continue;
        }
        let s =
            SaveBytes { chat: &meta.chat, id: Some(&meta.artifact.id), title: None, filename: None, bytes: &now, note: "Changed", replace: None, turn: None };
        if save_version(types, workspace, &s, true).is_ok() {
            changed += 1;
        }
    }
    changed
}

/// Why live file `id` (following `rel`) takes no versions but the file's own: an edit
/// saved there would be taken back by the file's next snapshot, and never reach the file.
fn live_refusal(id: &str, rel: &str) -> String {
    format!(
        "{id} is the user's own file {rel}, kept as a live file: it follows that file. Change {rel} itself (edit_file or write_file), or make a new artifact"
    )
}

/// Delete artifact `id` of `chat` in `workspace` for good (you chose to delete it).
pub fn remove(workspace: &Path, chat: &str, id: &str) -> Result<(), String> {
    load_in_chat(workspace, chat, id)?;
    let (_, dir) = artifact_dir(workspace, id)?;
    std::fs::remove_dir_all(&dir).map_err(|e| format!("couldn't delete it: {e}"))
}

/// The folder artifact `id` of `chat` keeps its versions in (to show it in the file manager).
pub fn folder_of(workspace: &Path, chat: &str, id: &str) -> Result<PathBuf, String> {
    load_in_chat(workspace, chat, id)?;
    artifact_dir(workspace, id).map(|(_, dir)| dir)
}

/// Delete every artifact of `chat` in `workspace` for good.
/// Returns how many were removed; ones whose index can't be read are left alone.
pub fn remove_chat(workspace: &Path, chat: &str) -> usize {
    let Ok(r) = sandbox::resolve(workspace, ARTIFACT_DIR) else { return 0 };
    let Ok(entries) = std::fs::read_dir(&r.abs) else { return 0 };
    let mut removed = 0;
    for id in entries.filter_map(Result::ok).filter_map(|e| e.file_name().to_str().map(str::to_owned)) {
        let Ok((_, dir)) = artifact_dir(workspace, &id) else { continue };
        let Ok(bytes) = read_capped(&dir.join(META_FILE), MAX_META_BYTES) else { continue };
        let Ok(meta) = serde_json::from_slice::<Meta>(&bytes) else { continue };
        if meta.chat != chat {
            continue;
        }
        match std::fs::remove_dir_all(&dir) {
            Ok(()) => removed += 1,
            Err(e) => log::warn!("couldn't delete artifact {id} of chat {chat}: {e}"),
        }
    }
    removed
}

/// Bytes of version `version` of artifact `id`, which must belong to `chat`.
pub fn read_version(workspace: &Path, chat: &str, id: &str, version: u32, max: u64) -> Result<(Artifact, Vec<u8>), String> {
    let meta = load_in_chat(workspace, chat, id)?;
    let v = meta.artifact.version(version).ok_or_else(|| format!("artifact {id:?} has no version {version}"))?;
    let file = version_file(workspace, &v.path).ok_or_else(|| format!("version {version} of {id:?} is gone"))?;
    let bytes = read_capped(&file, max)?;
    Ok((meta.artifact, bytes))
}

/// `[.../].byob/artifacts/<id>/v<n>.<ext>` → the version it is.
pub fn parse_version_path(path: &str) -> Option<ArtifactRef> {
    let norm = path.replace('\\', "/");
    let rest = norm.rsplit_once(&format!("{ARTIFACT_DIR}/")).map(|(_, r)| r)?;
    let (id, file) = rest.split_once('/')?;
    let n: u32 = file.strip_prefix('v')?.split_once('.')?.0.parse().ok()?;
    (valid_id(id) && n > 0 && !file.contains('/')).then(|| ArtifactRef { id: id.to_owned(), version: n })
}

/// A new artifact id from a title: `loan-calculator-3f2a`.
fn new_id(title: &str) -> String {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let mut slug = String::new();
    for c in title.chars().flat_map(char::to_lowercase) {
        if c.is_ascii_alphanumeric() {
            slug.push(c);
        } else if !slug.ends_with('-') && !slug.is_empty() {
            slug.push('-');
        }
        if slug.len() >= 40 {
            break;
        }
    }
    let slug = slug.trim_matches('-');
    let slug = if slug.is_empty() { "artifact" } else { slug };
    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| u64::from(d.subsec_nanos()));
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let mix = nanos ^ n.wrapping_mul(0x9e37_79b9) ^ u64::from(std::process::id()).rotate_left(16);
    format!("{slug}-{:04x}", mix & 0xffff)
}

/// Create a fresh, empty folder for a new artifact. Returns `(id, folder)`.
fn new_artifact_dir(workspace: &Path, title: &str) -> Result<(String, PathBuf), String> {
    let (_, root) = root_dir(workspace)?;
    for _ in 0..16 {
        let id = new_id(title);
        let dir = root.join(&id);
        match std::fs::create_dir(&dir) {
            Ok(()) => return Ok((id, dir)),
            Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
            Err(e) => return Err(format!("can't create the artifact: {e}")),
        }
    }
    Err("can't find a free artifact id; try again".into())
}

fn rel(root: &Path, path: &Path) -> String {
    path.strip_prefix(root).unwrap_or(path).to_string_lossy().replace('\\', "/")
}

fn clip(s: &str, max: usize) -> String {
    let clean: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
    let clean = clean.trim();
    let mut out: String = clean.chars().take(max).collect();
    if clean.chars().count() > max {
        out.push('…');
    }
    out
}

/// A model-given file name made safe, and the extension its versions are saved with.
fn clean_filename(types: &ArtifactTypes, raw: &str, title: &str) -> Result<(String, String), String> {
    let last = raw.trim().rsplit(['/', '\\']).next().unwrap_or_default();
    let name: String = last.chars().filter(|c| c.is_alphanumeric() || matches!(c, '.' | '-' | '_' | ' ')).take(100).collect();
    let name = name.trim();
    // A stem the filter emptied ("🍅.md") is named after the title, not read as a name
    // without an extension; a space it left before the dot ("ü 🍅.md") goes.
    let name = if name.starts_with('.') && name.len() > 1 { format!("{}{name}", new_id(title)) } else { name.to_owned() };
    let name = match name.rsplit_once('.') {
        Some((stem, ext)) if stem.ends_with(' ') => format!("{}.{ext}", stem.trim_end()),
        _ => name,
    };
    let name = name.trim_start_matches('.').to_owned();
    let lower = name.to_ascii_lowercase();
    let ext = if let Some(ext) = types.compound_extension(&lower) {
        ext
    } else {
        match lower.rsplit_once('.') {
            Some((stem, ext)) if !stem.is_empty() && (1..=10).contains(&ext.len()) && ext.bytes().all(|b| b.is_ascii_alphanumeric()) => ext.to_owned(),
            _ => {
                return Err(format!("filename {raw:?} {}", types.extension_hint()));
            }
        }
    };
    let name = if name.is_empty() { format!("{}.{ext}", new_id(title)) } else { name };
    Ok((name, ext))
}

/// Write a version file exclusively (never through a link, never over another file).
fn write_version(dir: &Path, n: u32, ext: &str, content: &str) -> Result<PathBuf, String> {
    write_version_bytes(dir, n, ext, content.as_bytes())
}

fn write_version_bytes(dir: &Path, n: u32, ext: &str, bytes: &[u8]) -> Result<PathBuf, String> {
    let path = dir.join(format!("v{n}.{ext}"));
    let mut f = OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| format!("can't write version {n}: {e}"))?;
    f.write_all(bytes).map_err(|e| format!("can't write version {n}: {e}"))?;
    Ok(path)
}

/// Check content for type `ty` (size, then the type's own check). Returns the text to save
/// and notes for the model.
fn check_content(ty: &ArtifactType, content: &str) -> Result<(String, String), String> {
    if content.len() > MAX_CONTENT_BYTES {
        return Err(format!("the content is too big ({} bytes; the limit is {MAX_CONTENT_BYTES})", content.len()));
    }
    if content.trim().is_empty() {
        return Err("the content is empty".into());
    }
    ty.hooks.check(content)
}

fn chat_of<'a>(ctx: &ToolContext<'a>) -> Result<&'a str, String> {
    ctx.chat().filter(|c| !c.is_empty()).ok_or_else(|| "artifacts are only available in a chat".to_owned())
}

/// Adopt the charts and images a tool call made as artifacts of `chat` (one version each,
/// pointing at the file where it is). Returns refs for the step.
fn adopt(workspace: &Path, chat: &str, media: &[MediaRef]) -> Vec<ArtifactRef> {
    let mut out = Vec::new();
    for m in media.iter().filter(|m| m.kind != MediaKind::File).take(MAX_ADOPTED) {
        let kind = if m.kind == MediaKind::Chart { ArtifactKind::Chart } else { ArtifactKind::Image };
        let name = m.name().to_owned();
        let content_type = kind.content_type(&name).to_owned();
        let title = name.strip_suffix(".chart.json").or_else(|| name.rsplit_once('.').map(|(s, _)| s)).unwrap_or(&name).to_owned();
        let size = version_file(workspace, &m.path).and_then(|p| std::fs::metadata(p).ok()).map_or(m.size, |md| md.len());
        let result = new_artifact_dir(workspace, &title).and_then(|(id, dir)| {
            let version = ArtifactVersion { n: 1, path: m.path.clone(), created_at: now_ms(), note: String::new(), size, turn: String::new() };
            let artifact = Artifact {
                id: id.clone(),
                kind,
                content_type: content_type.clone(),
                title: clip(&title, MAX_TITLE_CHARS),
                filename: name.clone(),
                versions: vec![version],
                network: false,
            };
            save(&dir, &Meta { chat: chat.to_owned(), live: None, artifact }).map(|()| id)
        });
        match result {
            Ok(id) => out.push(ArtifactRef { id, version: 1 }),
            Err(e) => log::warn!("adopting {} as an artifact: {e}", m.path),
        }
    }
    out
}

/// Let artifact `id` of `chat` use the internet, or not (HTML apps only). Its index file.
pub fn set_network(types: &ArtifactTypes, workspace: &Path, chat: &str, id: &str, on: bool) -> Result<PathBuf, String> {
    let meta = load_in_chat(workspace, chat, id)?;
    if on && !types.of(&meta.artifact).network {
        return Err(format!("only HTML apps can use the internet; {id} isn't one"));
    }
    let (_, dir) = artifact_dir(workspace, id)?;
    // The index as saved (with versions an undo hid), only the switch changed.
    let mut all = serde_json::from_slice::<Meta>(&read_capped(&dir.join(META_FILE), MAX_META_BYTES)?).map_err(|e| e.to_string())?;
    all.artifact.network = on;
    save(&dir, &all)?;
    Ok(dir.join(META_FILE))
}

/// `…/.byob/artifacts/<id>/artifact.json` → `<id>`.
fn meta_path_id(path: &Path) -> Option<String> {
    let s = path.to_string_lossy().replace('\\', "/");
    let rest = s.strip_suffix(&format!("/{META_FILE}"))?;
    let (dir, id) = rest.rsplit_once('/')?;
    (dir.ends_with(ARTIFACT_DIR) && valid_id(id)).then(|| id.to_owned())
}

/// The artifact versions a finished tool call made: versions written by the artifact tools
/// (by path), artifacts whose index changed (their latest version), else the charts and
/// images it made, adopted.
pub fn for_call(workspace: &Path, chat: &str, changes: &[FileChange], media: &[MediaRef]) -> Vec<ArtifactRef> {
    let made: Vec<ArtifactRef> = changes
        .iter()
        .filter_map(|c| match c {
            FileChange::Created(p) => parse_version_path(&p.to_string_lossy()),
            FileChange::Modified(p) => {
                let id = meta_path_id(p)?;
                let latest = load_in_chat(workspace, chat, &id).ok()?.artifact.latest()?.n;
                Some(ArtifactRef { id, version: latest })
            }
            _ => None,
        })
        .collect();
    if !made.is_empty() {
        return made;
    }
    adopt(workspace, chat, media)
}

/// A version to save from bytes someone else made (a plugin backend's tool or view).
#[derive(Debug, Clone, Default)]
pub struct SaveBytes<'a> {
    pub chat: &'a str,
    /// An artifact of `chat`; `None` makes a new one (then `title` and `filename` are needed).
    pub id: Option<&'a str>,
    pub title: Option<&'a str>,
    /// A new file name for an existing artifact renames it (and its type follows the name,
    /// e.g. a `.csv` table that becomes an `.xlsx` workbook).
    pub filename: Option<&'a str>,
    pub bytes: &'a [u8],
    pub note: &'a str,
    /// Overwrite version `n` instead of adding one, if it is still the latest (a draft the
    /// user keeps editing). Ignored otherwise.
    pub replace: Option<u32>,
    /// The request (turn) saving it: when the latest version came from the same one, it is
    /// overwritten (notes joined), so one request makes one version however many saves.
    pub turn: Option<&'a str>,
}

/// What [`save_bytes`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Saved {
    pub artifact: Artifact,
    pub version: u32,
    /// The version's file.
    pub file: PathBuf,
    /// A new artifact.
    pub created: bool,
    /// An existing version was overwritten (`SaveBytes::replace`).
    pub replaced: bool,
}

/// Write `s.bytes` as a new version (or over a draft, see [`SaveBytes::replace`]) of an
/// artifact, or as a new artifact. Same layout and rules as the artifact tools: files only
/// inside `.byob/artifacts`, never through links, version numbers never reused. A live
/// file's versions only follow the person's file ([`refresh_live`]), so nothing else saves one.
pub fn save_bytes(types: &ArtifactTypes, workspace: &Path, s: &SaveBytes<'_>) -> Result<Saved, String> {
    save_version(types, workspace, s, false)
}

fn save_version(types: &ArtifactTypes, workspace: &Path, s: &SaveBytes<'_>, follow: bool) -> Result<Saved, String> {
    if s.chat.is_empty() {
        return Err("artifacts are only available in a chat".into());
    }
    if s.bytes.len() as u64 > MAX_FILE_BYTES {
        return Err(format!("the file is too big ({} bytes; at most {MAX_FILE_BYTES})", s.bytes.len()));
    }
    if s.bytes.is_empty() {
        return Err("the file is empty".into());
    }
    let mut note = clip(s.note, MAX_NOTE_CHARS);
    let turn = s.turn.map(str::trim).unwrap_or_default().to_owned();
    let root = sandbox::root(workspace)?;
    let Some(id) = s.id.map(str::trim).filter(|i| !i.is_empty()) else {
        let title = clip(s.title.unwrap_or_default(), MAX_TITLE_CHARS);
        if title.is_empty() {
            return Err("a new artifact needs a title".into());
        }
        let (filename, ext) = clean_filename(types, s.filename.unwrap_or_default(), &title)?;
        let ty = types.for_filename(&filename);
        let (id, dir) = new_artifact_dir(workspace, &title)?;
        let result = (|| {
            let file = write_version_bytes(&dir, 1, &ext, s.bytes)?;
            let version =
                ArtifactVersion { n: 1, path: rel(&root, &file), created_at: now_ms(), note: note.clone(), size: s.bytes.len() as u64, turn: turn.clone() };
            let artifact = Artifact {
                id: id.clone(),
                kind: ty.kind,
                content_type: ty.content_type.clone(),
                title: title.clone(),
                filename,
                versions: vec![version],
                network: false,
            };
            save(&dir, &Meta { chat: s.chat.to_owned(), live: None, artifact: artifact.clone() })?;
            Ok::<_, String>(Saved { artifact, version: 1, file, created: true, replaced: false })
        })();
        if result.is_err() {
            let _ = std::fs::remove_dir_all(&dir);
        }
        return result;
    };
    let mut meta = load_in_chat(workspace, s.chat, id)?;
    if let Some(rel) = meta.live.as_deref().filter(|_| !follow) {
        return Err(live_refusal(&meta.artifact.id, rel));
    }
    let id = meta.artifact.id.clone();
    let (root, dir) = artifact_dir(workspace, &id)?;
    // Every version, also those whose file is gone (numbers are never reused).
    let all = serde_json::from_slice::<Meta>(&read_capped(&dir.join(META_FILE), MAX_META_BYTES)?).map_err(|e| e.to_string())?;
    if let Some(name) = s.filename.map(str::trim).filter(|n| !n.is_empty() && *n != meta.artifact.filename) {
        let (filename, _) = clean_filename(types, name, &meta.artifact.title)?;
        let ty = types.for_filename(&filename);
        meta.artifact.filename = filename;
        meta.artifact.content_type = ty.content_type.clone();
        meta.artifact.kind = ty.kind;
    }
    if let Some(t) = s.title.map(|t| clip(t, MAX_TITLE_CHARS)).filter(|t| !t.is_empty()) {
        meta.artifact.title = t;
    }
    let lower = meta.artifact.filename.to_ascii_lowercase();
    let ext = types.compound_extension(&lower).unwrap_or_else(|| lower.rsplit_once('.').map_or("bin".to_owned(), |(_, e)| e.to_owned()));
    let latest = meta.artifact.latest().map(|v| v.n);
    let top = all.artifact.versions.iter().map(|v| v.n).max().unwrap_or(0);
    meta.artifact.versions = all.artifact.versions;
    // Saved before in this same request: that version again, with both notes.
    // (Only when it can be written over in place: a file renamed to another type in the turn
    // gets a version of its own, with its own note.)
    let same_turn = (!turn.is_empty())
        .then(|| meta.artifact.versions.iter().find(|v| v.n == top && Some(top) == latest && v.turn == turn && v.path.ends_with(&format!("/v{top}.{ext}"))))
        .flatten();
    if let Some(v) = same_turn {
        note = if note.is_empty() || v.note.ends_with(&note) {
            v.note.clone()
        } else if v.note.is_empty() {
            note
        } else {
            clip(&format!("{}; {note}", v.note), MAX_NOTE_CHARS)
        };
    }
    let replace = s.replace.or_else(|| same_turn.map(|v| v.n));
    if let Some(n) = replace.filter(|n| Some(*n) == latest && *n == top)
        && let Some(v) = meta.artifact.versions.iter_mut().find(|v| v.n == n)
        && v.path.ends_with(&format!("/v{n}.{ext}"))
    {
        let file = dir.join(format!("v{n}.{ext}"));
        let tmp = dir.join(format!("v{n}.{ext}.tmp"));
        let _ = std::fs::remove_file(&tmp);
        let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| format!("can't write version {n}: {e}"))?;
        f.write_all(s.bytes).map_err(|e| format!("can't write version {n}: {e}"))?;
        drop(f);
        std::fs::rename(&tmp, &file).map_err(|e| format!("can't write version {n}: {e}"))?;
        v.size = s.bytes.len() as u64;
        v.created_at = now_ms();
        if !note.is_empty() {
            v.note = note;
        }
        save(&dir, &meta)?;
        return Ok(Saved { artifact: meta.artifact, version: n, file, created: false, replaced: true });
    }
    if meta.artifact.versions.len() >= MAX_VERSIONS {
        return Err(format!("{id} has too many versions; create a new artifact"));
    }
    let n = top.saturating_add(1);
    let file = write_version_bytes(&dir, n, &ext, s.bytes)?;
    meta.artifact.versions.push(ArtifactVersion { n, path: rel(&root, &file), created_at: now_ms(), note, size: s.bytes.len() as u64, turn });
    if let Err(e) = save(&dir, &meta) {
        let _ = std::fs::remove_file(&file);
        return Err(e);
    }
    meta.artifact.versions.retain(|v| version_file(workspace, &v.path).is_some());
    Ok(Saved { artifact: meta.artifact, version: n, file, created: false, replaced: false })
}

/// Lines for the system prompt naming the chat's artifacts, so later turns can update them.
pub fn prompt_list(types: &ArtifactTypes, artifacts: &[Artifact]) -> String {
    if artifacts.is_empty() {
        return String::new();
    }
    let mut out = String::from("Artifacts in this chat (update them by id):");
    for a in artifacts.iter().rev().take(30) {
        let v = a.latest().map_or(1, |v| v.n);
        out.push_str(&format!("\n- {}: \"{}\" ({}, v{v}, {})", a.id, a.title, types.of(a).label, a.filename));
    }
    out
}

// ---------------------------------------------------------------------------------------
// Tools

/// `create_artifact`, for the types in its registry.
#[derive(Clone, Default)]
pub struct CreateArtifact {
    pub types: ArtifactTypes,
}

/// `update_artifact`.
#[derive(Clone, Default)]
pub struct UpdateArtifact {
    pub types: ArtifactTypes,
}

/// `read_artifact`.
#[derive(Clone, Default)]
pub struct ReadArtifact {
    pub types: ArtifactTypes,
}

#[derive(Deserialize)]
struct CreateArgs {
    title: String,
    #[serde(default, alias = "name", alias = "file")]
    filename: String,
    content: String,
    #[serde(default)]
    note: String,
    #[serde(default)]
    network: bool,
}

#[derive(Deserialize)]
struct Edit {
    find: String,
    #[serde(default, alias = "replacement", alias = "replace_with")]
    replace: String,
}

#[derive(Deserialize)]
struct UpdateArgs {
    id: String,
    /// Turn the app's internet access on or off (alone: no new version).
    #[serde(default)]
    network: Option<bool>,
    #[serde(default)]
    content: Option<String>,
    #[serde(default)]
    edits: Option<Vec<Edit>>,
    #[serde(default)]
    note: String,
}

#[derive(Deserialize)]
struct ReadArgs {
    id: String,
    #[serde(default)]
    version: Option<u32>,
}

fn arg_str<'a>(args: &'a Value, key: &str) -> &'a str {
    args.get(key).and_then(Value::as_str).unwrap_or_default()
}

impl Tool for CreateArtifact {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "create_artifact".into(),
            description: self.types.tool_description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "title": {"type": "string", "description": "Short title, e.g. \"Loan calculator\""},
                    "filename": {"type": "string", "description": "File name with extension, e.g. loan-calculator.html, q3-summary.md, prices.csv"},
                    "content": {"type": "string", "description": "The whole file"},
                    "note": {"type": "string", "description": "Optional: what this first version is"},
                    "network": {"type": "boolean", "description": "HTML apps only: let it use the internet (HTTPS: fetch, and scripts, styles, fonts and images by URL). Only when it needs live data or a web API; off, everything must be inline"}
                },
                "required": ["title", "filename", "content"]
            }),
        }
    }

    fn title(&self, args: &Value) -> String {
        format!("Made {}", clip(arg_str(args, "title"), 60))
    }

    fn pending_title(&self, args: &Value) -> String {
        format!("Make {}", clip(arg_str(args, "title"), 60))
    }

    fn access(&self, _args: &Value) -> Access {
        Access::Read
    }

    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
        match create(&self.types, args, ctx) {
            Ok(out) => out,
            Err(e) => ToolOutput::err(e),
        }
    }
}

fn create(types: &ArtifactTypes, args: &Value, ctx: &ToolContext<'_>) -> Result<ToolOutput, String> {
    let chat = chat_of(ctx)?;
    let a: CreateArgs = parse_args(args)?;
    let title = clip(&a.title, MAX_TITLE_CHARS);
    if title.is_empty() {
        return Err("give the artifact a title".into());
    }
    let (filename, ext) = clean_filename(types, &a.filename, &title)?;
    let ty = types.for_filename(&filename);
    if a.network && !ty.network {
        return Err(format!("only HTML apps can use the internet; this is a {}", ty.label));
    }
    let (content, warning) = check_content(&ty, &a.content)?;
    let warning = if a.network { String::new() } else { warning };
    let (id, dir) = new_artifact_dir(ctx.workspace, &title)?;
    let result = (|| {
        let file = write_version(&dir, 1, &ext, &content)?;
        let root = sandbox::root(ctx.workspace)?;
        let version = ArtifactVersion {
            n: 1,
            path: rel(&root, &file),
            created_at: now_ms(),
            note: clip(&a.note, MAX_NOTE_CHARS),
            size: content.len() as u64,
            turn: String::new(),
        };
        let artifact = Artifact {
            id: id.clone(),
            kind: ty.kind,
            content_type: ty.content_type.clone(),
            title: title.clone(),
            filename: filename.clone(),
            versions: vec![version],
            network: a.network,
        };
        save(&dir, &Meta { chat: chat.to_owned(), live: None, artifact })?;
        Ok::<_, String>(file)
    })();
    let file = match result {
        Ok(f) => f,
        Err(e) => {
            let _ = std::fs::remove_dir_all(&dir);
            return Err(e);
        }
    };
    let online = if a.network { " It can use the internet (HTTPS)." } else { "" };
    let text = format!(
        "Created the {} artifact \"{title}\" (id {id}, version 1, {filename}). It shows beside the chat.{online} To change it later, call update_artifact with id {id}.{warning}",
        ty.label
    );
    Ok(ToolOutput { text, failed: false, changes: vec![FileChange::Created(file)], images: Vec::new() })
}

impl Tool for UpdateArtifact {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "update_artifact".into(),
            description: "Save a new version of an artifact. Prefer `edits`: find/replace pairs applied in order, where each `find` is exact text that occurs exactly once \
                in the current version (include enough surrounding text to make it unique). Send `content` (the whole file) only for a rewrite. \
                Use read_artifact first if you don't have the current text."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "id": {"type": "string", "description": "The artifact's id"},
                    "edits": {"type": "array", "items": {"type": "object", "properties": {"find": {"type": "string"}, "replace": {"type": "string"}}, "required": ["find", "replace"]}},
                    "content": {"type": "string", "description": "Or: the whole new file"},
                    "note": {"type": "string", "description": "What changed, in a few words"},
                    "network": {"type": "boolean", "description": "HTML apps only: turn its internet access on or off. Alone (no edits or content) it only switches that, without a new version"}
                },
                "required": ["id"]
            }),
        }
    }

    fn title(&self, args: &Value) -> String {
        format!("Updated {}", clip(arg_str(args, "id"), 60))
    }

    fn pending_title(&self, args: &Value) -> String {
        format!("Update {}", clip(arg_str(args, "id"), 60))
    }

    fn access(&self, _args: &Value) -> Access {
        Access::Read
    }

    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
        match update(&self.types, args, ctx) {
            Ok(out) => out,
            Err(e) => ToolOutput::err(e),
        }
    }
}

/// Apply find/replace edits in order (see [`crate::edits`]): each `find` must occur once in
/// the text as it is at that point, exactly or failing that ignoring whitespace.
pub fn apply_edits(text: &str, edits: &[(String, String)]) -> Result<String, String> {
    let opts =
        crate::edits::Opts { replace_all: false, offer_replace_all: false, max_bytes: MAX_CONTENT_BYTES, what: "the current version", reread: "read_artifact" };
    crate::edits::apply(text, edits, &opts).map(|a| a.text)
}

fn update(types: &ArtifactTypes, args: &Value, ctx: &ToolContext<'_>) -> Result<ToolOutput, String> {
    let chat = chat_of(ctx)?;
    let a: UpdateArgs = parse_args(args)?;
    let mut meta = load_in_chat(ctx.workspace, chat, a.id.trim())?;
    let id = meta.artifact.id.clone();
    if let Some(rel) = meta.live.as_deref() {
        return Err(live_refusal(&id, rel));
    }
    let ty = types.of(&meta.artifact);
    if !ty.text {
        return Err(format!("{id} is not a text file ({}); it can't be edited as text. Make a new one instead", ty.label));
    }
    if meta.artifact.versions.len() >= MAX_VERSIONS {
        return Err(format!("{id} has too many versions; create a new artifact"));
    }
    let latest = meta.artifact.latest().cloned().ok_or_else(|| format!("artifact {id:?} has no versions"))?;
    if a.network == Some(true) && !ty.network {
        return Err(format!("only HTML apps can use the internet; {id} is a {}", ty.label));
    }
    let network = a.network.unwrap_or(meta.artifact.network);
    if a.content.is_none()
        && a.edits.is_none()
        && let Some(on) = a.network
    {
        // Internet access alone: the same version, its index rewritten.
        let meta_file = set_network(types, ctx.workspace, chat, &id, on)?;
        let text = format!("\"{}\" (id {id}) {} use the internet now.", meta.artifact.title, if on { "can" } else { "can't" });
        return Ok(ToolOutput { text, failed: false, changes: vec![FileChange::Modified(meta_file)], images: Vec::new() });
    }
    let new_text = match (a.content, a.edits) {
        (Some(_), Some(_)) => return Err("give either content or edits, not both".into()),
        (None, None) => return Err("give edits (find/replace pairs) or the whole new content (or just network)".into()),
        (Some(content), None) => content,
        (None, Some(edits)) => {
            let file = version_file(ctx.workspace, &latest.path).ok_or_else(|| format!("the latest version of {id} is gone"))?;
            let bytes = read_capped(&file, MAX_FILE_BYTES)?;
            let current = String::from_utf8(bytes).map_err(|_| format!("{id} is not a text file"))?;
            let pairs: Vec<(String, String)> = edits.into_iter().map(|e| (e.find, e.replace)).collect();
            let out = apply_edits(&current, &pairs)?;
            if out == current {
                return Err("the edits change nothing".into());
            }
            out
        }
    };
    let (content, warning) = check_content(&ty, &new_text)?;
    let warning = if network { String::new() } else { warning };
    let (root, dir) = artifact_dir(ctx.workspace, &id)?;
    // Version numbers are never reused, even if a version was undone.
    let ext = latest.path.rsplit_once("/v").and_then(|(_, f)| f.split_once('.')).map(|(_, e)| e.to_owned()).unwrap_or_else(|| {
        let lower = meta.artifact.filename.to_ascii_lowercase();
        types.compound_extension(&lower).unwrap_or_else(|| lower.rsplit_once('.').map_or("txt".to_owned(), |(_, e)| e.to_owned()))
    });
    let all = serde_json::from_slice::<Meta>(&read_capped(&dir.join(META_FILE), MAX_META_BYTES)?).map_err(|e| e.to_string())?;
    let n = all.artifact.versions.iter().map(|v| v.n).max().unwrap_or(0).saturating_add(1);
    let file = write_version(&dir, n, &ext, &content)?;
    let note = clip(&a.note, MAX_NOTE_CHARS);
    meta.artifact.versions = all.artifact.versions;
    meta.artifact.network = network;
    meta.artifact.versions.push(ArtifactVersion {
        n,
        path: rel(&root, &file),
        created_at: now_ms(),
        note: note.clone(),
        size: content.len() as u64,
        turn: String::new(),
    });
    if let Err(e) = save(&dir, &meta) {
        let _ = std::fs::remove_file(&file);
        return Err(e);
    }
    let text =
        format!("Saved version {n} of \"{}\" (id {id}){}.{warning}", meta.artifact.title, if note.is_empty() { String::new() } else { format!(": {note}") });
    Ok(ToolOutput { text, failed: false, changes: vec![FileChange::Created(file)], images: Vec::new() })
}

impl Tool for ReadArtifact {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "read_artifact".into(),
            description:
                "Read the current text of an artifact (or of an older version), e.g. before changing it with update_artifact. Image artifacts are shown to you."
                    .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "id": {"type": "string"},
                    "version": {"type": "integer", "description": "Optional; default the latest"}
                },
                "required": ["id"]
            }),
        }
    }

    fn title(&self, args: &Value) -> String {
        format!("Read {}", clip(arg_str(args, "id"), 60))
    }

    fn pending_title(&self, args: &Value) -> String {
        self.title(args)
    }

    fn access(&self, _args: &Value) -> Access {
        Access::Read
    }

    fn run(&self, args: &Value, ctx: &ToolContext<'_>) -> ToolOutput {
        let result = (|| {
            let chat = chat_of(ctx)?;
            let a: ReadArgs = parse_args(args)?;
            let meta = load_in_chat(ctx.workspace, chat, a.id.trim())?;
            let v = match a.version {
                Some(n) => meta.artifact.version(n).cloned().ok_or_else(|| format!("{} has no version {n}", meta.artifact.id))?,
                None => meta.artifact.latest().cloned().ok_or("no versions")?,
            };
            let ty = self.types.of(&meta.artifact);
            if !ty.text {
                // An image the model can look at; other binaries can't be read.
                let (_, bytes) = read_version(ctx.workspace, chat, &meta.artifact.id, v.n, MAX_FILE_BYTES)?;
                if crate::images::sniff(&bytes).is_none() {
                    return Err(format!("{} is not a text file ({}); it can't be read as text", meta.artifact.id, ty.label));
                }
                let (mime, data) = crate::images::fit(bytes, crate::images::MODEL_IMAGE_SIDE, byob_protocol::media::MAX_IMAGE_BYTES)?;
                let text = format!(
                    "{} \"{}\", version {} of {} ({}): an image",
                    meta.artifact.id,
                    meta.artifact.title,
                    v.n,
                    meta.artifact.versions.len(),
                    meta.artifact.filename
                );
                return Ok(ToolOutput { images: vec![format!("data:{mime};base64,{}", byob_protocol::media::encode(&data))], ..ToolOutput::ok(text) });
            }
            let (_, bytes) = read_version(ctx.workspace, chat, &meta.artifact.id, v.n, MAX_FILE_BYTES)?;
            let text = String::from_utf8_lossy(&bytes);
            let shown: String = text.chars().take(MAX_READ_CHARS).collect();
            let more = if shown.len() < text.len() { "\n… [cut off]" } else { "" };
            Ok(ToolOutput::ok(format!(
                "{} \"{}\", version {} of {} ({}):\n{shown}{more}",
                meta.artifact.id,
                meta.artifact.title,
                v.n,
                meta.artifact.versions.len(),
                meta.artifact.filename
            )))
        })();
        match result {
            Ok(out) => out,
            Err(e) => ToolOutput::err(e),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicBool;

    fn run_in(tool: &dyn Tool, ws: &Path, chat: &str, args: Value) -> ToolOutput {
        let cancel = AtomicBool::new(false);
        tool.run(&args, &ToolContext::new(ws, &cancel).with_chat(chat))
    }

    fn id_of(out: &ToolOutput) -> String {
        let p = match &out.changes[..] {
            [FileChange::Created(p)] => p.to_string_lossy().into_owned(),
            other => panic!("{other:?} / {}", out.text),
        };
        parse_version_path(&p).unwrap().id
    }

    const HTML: &str = "<!doctype html><button style=\"background:red\">Go</button><button>Stop</button>";

    #[test]
    fn create_update_read_and_versions() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        let out = run_in(&CreateArtifact::default(), ws, "c1", json!({"title": "Loan calculator", "filename": "loan.html", "content": HTML}));
        assert!(!out.failed, "{}", out.text);
        let id = id_of(&out);
        assert!(id.starts_with("loan-calculator-"), "{id}");
        assert!(out.text.contains(&id));
        let a = &list(ws, "c1")[0];
        assert_eq!((a.kind, a.filename.as_str(), a.versions.len()), (ArtifactKind::Html, "loan.html", 1));
        assert_eq!(a.versions[0].path, format!(".byob/artifacts/{id}/v1.html"));
        assert!(list(ws, "other").is_empty(), "artifacts are per chat");

        let out = run_in(
            &UpdateArtifact::default(),
            ws,
            "c1",
            json!({"id": id, "edits": [{"find": "background:red", "replace": "background:blue"}], "note": "blue"}),
        );
        assert!(!out.failed, "{}", out.text);
        assert_eq!(parse_version_path(&id_of_path(&out)).unwrap().version, 2);
        let (a, v2) = read_version(ws, "c1", &id, 2, MAX_FILE_BYTES).unwrap();
        assert_eq!(String::from_utf8(v2).unwrap(), HTML.replace("red", "blue"));
        assert_eq!(a.latest().unwrap().note, "blue");
        // v1 is untouched
        assert_eq!(read_version(ws, "c1", &id, 1, MAX_FILE_BYTES).unwrap().1, HTML.as_bytes());

        let read = run_in(&ReadArtifact::default(), ws, "c1", json!({"id": id}));
        assert!(read.text.contains("version 2") && read.text.contains("background:blue"), "{}", read.text);
        let other_chat = run_in(&ReadArtifact::default(), ws, "c2", json!({"id": id}));
        assert!(other_chat.failed);
        assert!(run_in(&UpdateArtifact::default(), ws, "c2", json!({"id": id, "content": "x"})).failed, "can't touch another chat's artifact");
        assert!(read_version(ws, "c2", &id, 1, MAX_FILE_BYTES).is_err());

        // a whole-content rewrite
        let out = run_in(&UpdateArtifact::default(), ws, "c1", json!({"id": id, "content": "<p>new</p>"}));
        assert!(!out.failed, "{}", out.text);
        assert_eq!(load(ws, &id).unwrap().artifact.latest().unwrap().n, 3);
        // an undone version (file removed) drops out; numbers are never reused
        std::fs::remove_file(ws.join(format!(".byob/artifacts/{id}/v3.html"))).unwrap();
        assert_eq!(load(ws, &id).unwrap().artifact.latest().unwrap().n, 2);
        let out = run_in(&UpdateArtifact::default(), ws, "c1", json!({"id": id, "content": "<p>again</p>"}));
        assert!(!out.failed, "{}", out.text);
        assert_eq!(load(ws, &id).unwrap().artifact.versions.iter().map(|v| v.n).collect::<Vec<_>>(), vec![1, 2, 4]);
    }

    /// An HTML app can be given the internet when made, or switched on and off later on its
    /// own (no new version; the step points at the latest one). Other types can't have it, and
    /// an online app isn't warned about loading things from the web.
    #[test]
    fn html_apps_can_be_given_internet_access() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        let page = "<script>fetch('https://api.example.com/rates')</script>";
        let offline = run_in(&CreateArtifact::default(), ws, "c1", json!({"title": "Rates", "filename": "rates.html", "content": page}));
        assert!(offline.text.contains("network: true"), "the warning says how to get it: {}", offline.text);
        let out = run_in(&CreateArtifact::default(), ws, "c1", json!({"title": "Live rates", "filename": "live.html", "content": page, "network": true}));
        assert!(!out.failed && !out.text.contains("Warning") && out.text.contains("internet"), "{}", out.text);
        let id = id_of(&out);
        assert!(load(ws, &id).unwrap().artifact.network);
        // Off again, alone: no new version, and the change points at the index.
        let off = run_in(&UpdateArtifact::default(), ws, "c1", json!({"id": id, "network": false}));
        assert!(!off.failed, "{}", off.text);
        let a = load(ws, &id).unwrap().artifact;
        assert!(!a.network && a.versions.len() == 1, "{a:?}");
        assert_eq!(for_call(ws, "c1", &off.changes, &[]), vec![ArtifactRef { id: id.clone(), version: 1 }]);
        // An edit keeps the switch as it is; giving it with the edit changes it too.
        let on = run_in(&UpdateArtifact::default(), ws, "c1", json!({"id": id, "content": page, "network": true}));
        assert!(!on.failed, "{}", on.text);
        let out = run_in(&UpdateArtifact::default(), ws, "c1", json!({"id": id, "content": "<p>v3</p>"}));
        assert!(!out.failed);
        assert!(load(ws, &id).unwrap().artifact.network);
        // Not for documents, nor another chat's app.
        let doc = run_in(&CreateArtifact::default(), ws, "c1", json!({"title": "Notes", "filename": "notes.md", "content": "# hi", "network": true}));
        assert!(doc.failed && doc.text.contains("only HTML apps"), "{}", doc.text);
        assert!(run_in(&UpdateArtifact::default(), ws, "c2", json!({"id": id, "network": false})).failed);
        assert!(set_network(&ArtifactTypes::builtin(), ws, "c1", &id, false).is_ok());
        assert!(!load(ws, &id).unwrap().artifact.network);
    }

    /// Deleting a chat deletes its artifacts for good (they were left orphaned before).
    #[test]
    fn removing_a_chat_removes_only_its_artifacts() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        for (chat, title) in [("c1", "One"), ("c1", "Two"), ("c2", "Other")] {
            assert!(!run_in(&CreateArtifact::default(), ws, chat, json!({"title": title, "filename": "a.md", "content": "# hi"})).failed);
        }
        assert_eq!(remove_chat(ws, "c1"), 2);
        assert!(list(ws, "c1").is_empty());
        assert_eq!(list(ws, "c2").len(), 1);
        assert_eq!(std::fs::read_dir(ws.join(ARTIFACT_DIR)).unwrap().count(), 1, "nothing left behind on disk");
        assert_eq!(remove_chat(ws, "c1"), 0);
        assert_eq!(remove_chat(&ws.join("missing"), "c2"), 0);
    }

    fn id_of_path(out: &ToolOutput) -> String {
        match &out.changes[..] {
            [FileChange::Created(p)] => p.to_string_lossy().into_owned(),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn edits_must_match_exactly_once() {
        let t = "a b a c";
        assert_eq!(apply_edits(t, &[("b".into(), "B".into()), ("c".into(), "C".into())]).unwrap(), "a B a C");
        let e = apply_edits(t, &[("a".into(), "x".into())]).unwrap_err();
        assert!(e.contains("occurs 2 times") && e.contains("edit 1"), "{e}");
        let e = apply_edits(t, &[("b".into(), "B".into()), ("zz".into(), "x".into())]).unwrap_err();
        assert!(e.contains("edit 2") && e.contains("not in the current version") && e.contains("read_artifact"), "{e}");
        // edits see the text as earlier edits left it
        assert_eq!(apply_edits(t, &[("b".into(), "q".into()), ("q a".into(), "r".into())]).unwrap(), "a r c");
        assert!(apply_edits(t, &[]).is_err());
        assert!(apply_edits(t, &[(String::new(), "x".into())]).is_err());
        let many: Vec<(String, String)> = (0..=MAX_EDITS).map(|i| (format!("{i}"), String::new())).collect();
        assert!(apply_edits(t, &many).unwrap_err().contains("too many"));
        let big = "x".repeat(MAX_CONTENT_BYTES);
        assert!(apply_edits("ab", &[("a".into(), big)]).unwrap_err().contains("too big"));
    }

    #[test]
    fn failed_edits_write_nothing() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        let id = id_of(&run_in(&CreateArtifact::default(), ws, "c", json!({"title": "T", "filename": "t.html", "content": HTML})));
        let out = run_in(&UpdateArtifact::default(), ws, "c", json!({"id": id, "edits": [{"find": "button", "replace": "x"}]}));
        assert!(out.failed && out.text.contains("occurs 4 times"), "{}", out.text);
        assert!(out.changes.is_empty());
        assert_eq!(load(ws, &id).unwrap().artifact.versions.len(), 1);
        let both = run_in(&UpdateArtifact::default(), ws, "c", json!({"id": id, "content": "x", "edits": [{"find": "Go", "replace": "x"}]}));
        assert!(both.failed && both.text.contains("not both"));
        assert!(run_in(&UpdateArtifact::default(), ws, "c", json!({"id": id})).failed);
        assert!(run_in(&UpdateArtifact::default(), ws, "c", json!({"id": "../../etc", "content": "x"})).failed);
        let same = run_in(&UpdateArtifact::default(), ws, "c", json!({"id": id, "edits": [{"find": "Go", "replace": "Go"}]}));
        assert!(same.failed && same.text.contains("change nothing"));
    }

    #[test]
    fn create_validates_names_kinds_and_sizes() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        let c = |args: Value| run_in(&CreateArtifact::default(), ws, "c", args);
        assert!(c(json!({"title": "T", "filename": "noext", "content": "x"})).text.contains("extension"));
        assert!(c(json!({"title": "T", "filename": "p.png", "content": "x"})).text.contains("images"));
        assert!(c(json!({"title": "", "filename": "a.md", "content": "x"})).failed);
        assert!(c(json!({"title": "T", "filename": "a.md", "content": "  "})).failed);
        let big = "x".repeat(MAX_CONTENT_BYTES + 1);
        assert!(c(json!({"title": "T", "filename": "a.md", "content": big})).text.contains("too big"));
        assert!(c(json!({"title": "T", "filename": "a.chart.json", "content": "{nope"})).failed);
        // Emoji in a name: dropped, without losing the extension or leaving a space.
        let emoji = c(json!({"title": "Tomato", "filename": "🍅.md", "content": "x"}));
        assert!(!emoji.failed && emoji.text.contains(".md)") && emoji.text.contains("tomato-"), "{}", emoji.text);
        let mixed = c(json!({"title": "T", "filename": "ü 🍅.md", "content": "x"}));
        assert!(mixed.text.contains("ü.md)"), "{}", mixed.text);
        for a in list(ws, "c") {
            remove(ws, "c", &a.id).unwrap();
        }
        // nothing half-made is left behind
        assert!(list(ws, "c").is_empty());
        let root = ws.join(ARTIFACT_DIR);
        assert_eq!(std::fs::read_dir(&root).map(|r| r.count()).unwrap_or(0), 0);

        let md = c(json!({"title": "Q3 summary", "filename": "../../q3.md", "content": "# Q3\n"}));
        assert!(!md.failed, "{}", md.text);
        let chart = c(json!({"title": "Sales", "filename": "sales.chart.json",
            "content": r#"{"type":"bar","x":"m","series":["v"],"data":[{"m":"a","v":1}]}"#}));
        assert!(!chart.failed, "{}", chart.text);
        let csv = c(json!({"title": "Prices", "filename": "prices.csv", "content": "a,b\n1,2\n"}));
        let net = c(json!({"title": "Net", "filename": "n.html", "content": "<script src=\"https://cdn.example/x.js\"></script>"}));
        assert!(net.text.contains("blocked"), "{}", net.text);
        let kinds: Vec<(ArtifactKind, String)> = list(ws, "c").into_iter().map(|a| (a.kind, a.filename)).collect();
        assert_eq!(
            kinds,
            vec![
                (ArtifactKind::Markdown, "q3.md".into()),
                (ArtifactKind::Chart, "sales.chart.json".into()),
                (ArtifactKind::Text, "prices.csv".into()),
                (ArtifactKind::Html, "n.html".into())
            ]
        );
        assert!(!csv.failed);
        assert!(Path::new(&id_of_path(&chart)).ends_with("v1.chart.json"));
        // no chat, no artifacts
        let cancel = AtomicBool::new(false);
        assert!(CreateArtifact::default().run(&json!({"title": "T", "filename": "a.md", "content": "x"}), &ToolContext::new(ws, &cancel)).failed);
    }

    /// A type registered from outside: its file names, check and label are used, its
    /// content type is kept (13.0 clients see text), and edits go through its check too.
    #[test]
    fn a_registered_type_is_used_end_to_end() {
        struct Rows;
        impl crate::ArtifactHooks for Rows {
            fn check(&self, content: &str) -> Result<(String, String), String> {
                if content.lines().all(|l| l.split(',').count() == 2) {
                    Ok((content.to_owned(), " Two columns.".into()))
                } else {
                    Err("every row needs two cells".into())
                }
            }
        }
        let types = ArtifactTypes::builtin();
        types.register(ArtifactType::new("text/csv", "table", ArtifactKind::Text).suffixes(&[".csv"]).hooks(std::sync::Arc::new(Rows)));
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        let create = CreateArtifact { types: types.clone() };
        assert!(run_in(&create, ws, "c", json!({"title": "P", "filename": "p.csv", "content": "a,b,c"})).failed);
        let out = run_in(&create, ws, "c", json!({"title": "P", "filename": "p.csv", "content": "a,b\n1,2"}));
        assert!(out.text.contains("Created the table artifact") && out.text.ends_with("Two columns."), "{}", out.text);
        let a = &list(ws, "c")[0];
        assert_eq!((a.kind, a.content_type.as_str()), (ArtifactKind::Text, "text/csv"));
        let update = UpdateArtifact { types: types.clone() };
        assert!(run_in(&update, ws, "c", json!({"id": a.id, "edits": [{"find": "1,2", "replace": "1,2,3"}]})).failed);
        assert!(!run_in(&update, ws, "c", json!({"id": a.id, "edits": [{"find": "1,2", "replace": "3,4"}]})).failed);
        assert!(prompt_list(&types, &list(ws, "c")).contains("(table, v2, p.csv)"));
        // Without the registration (say the plugin is gone) it is plain text again.
        assert!(prompt_list(&ArtifactTypes::builtin(), &list(ws, "c")).contains("(file, v2, p.csv)"));
    }

    #[cfg(unix)]
    #[test]
    fn never_writes_through_a_linked_artifact_folder() {
        let outside = tempfile::tempdir().unwrap();
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join(".byob")).unwrap();
        std::os::unix::fs::symlink(outside.path(), d.path().join(ARTIFACT_DIR)).unwrap();
        let out = run_in(&CreateArtifact::default(), d.path(), "c", json!({"title": "T", "filename": "a.md", "content": "x"}));
        assert!(out.failed, "{}", out.text);
        assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0);
    }

    #[test]
    fn charts_and_images_are_adopted() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        std::fs::create_dir(ws.join("charts")).unwrap();
        std::fs::write(ws.join("charts/Sales.chart.json"), "{}").unwrap();
        std::fs::write(ws.join("plot.png"), "png").unwrap();
        let media = vec![MediaRef::new("charts/Sales.chart.json", 2), MediaRef::new("plot.png", 3), MediaRef::new("notes.txt", 1)];
        let refs = for_call(ws, "c", &[], &media);
        assert_eq!(refs.len(), 2);
        let list = list(ws, "c");
        assert_eq!(list.iter().map(|a| (a.kind, a.title.as_str())).collect::<Vec<_>>(), vec![(ArtifactKind::Chart, "Sales"), (ArtifactKind::Image, "plot")]);
        assert_eq!(list[1].versions[0].path, "plot.png");
        // an artifact tool's own version is recognized, not adopted again
        let p = ws.join(".byob/artifacts/x-1/v3.md");
        assert_eq!(for_call(ws, "c", &[FileChange::Created(p)], &media), vec![ArtifactRef { id: "x-1".into(), version: 3 }]);
    }

    #[test]
    fn image_artifacts_are_shown_to_the_model() {
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        let mut png = Vec::new();
        image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
        std::fs::write(ws.join("plot.png"), &png).unwrap();
        for_call(ws, "c", &[], &[MediaRef::new("plot.png", png.len() as u64)]);
        let id = list(ws, "c")[0].id.clone();
        let out = run_in(&ReadArtifact { types: ArtifactTypes::builtin() }, ws, "c", json!({"id": id}));
        assert!(!out.failed && out.text.contains("an image"), "{}", out.text);
        assert_eq!(out.images, vec![format!("data:image/png;base64,{}", byob_protocol::media::encode(&png))]);
    }

    #[test]
    fn version_paths() {
        assert_eq!(parse_version_path(".byob/artifacts/a-1/v12.chart.json"), Some(ArtifactRef { id: "a-1".into(), version: 12 }));
        assert_eq!(parse_version_path("/w/.byob/artifacts/a/v1.html"), Some(ArtifactRef { id: "a".into(), version: 1 }));
        for bad in [".byob/artifacts/a/artifact.json", ".byob/artifacts/A/v1.md", ".byob/artifacts/a/v0.md", "charts/x.chart.json", ".byob/artifacts/a/b/v1.md"]
        {
            assert_eq!(parse_version_path(bad), None, "{bad}");
        }
    }

    #[test]
    fn prompt_lists_latest_versions() {
        let d = tempfile::tempdir().unwrap();
        let id = id_of(&run_in(&CreateArtifact::default(), d.path(), "c", json!({"title": "Calc", "filename": "calc.html", "content": HTML})));
        let p = prompt_list(&ArtifactTypes::builtin(), &list(d.path(), "c"));
        assert!(p.contains(&format!("{id}: \"Calc\" (app, v1, calc.html)")), "{p}");
        assert_eq!(prompt_list(&ArtifactTypes::builtin(), &[]), "");
    }

    /// Regression: one request that wrote a sheet in eight tool calls made eight versions.
    /// Saves within one request make one version (the notes joined); the next request, or
    /// a save after another one's, starts a new version.
    #[test]
    fn one_request_makes_one_version() {
        let d = tempfile::tempdir().unwrap();
        let types = ArtifactTypes::builtin();
        types.register(ArtifactType::new("text/csv", "table", ArtifactKind::Text).suffixes(&[".csv"]));
        let save = |s: SaveBytes<'_>| save_bytes(&types, d.path(), &s);
        let a =
            save(SaveBytes { chat: "c", title: Some("Sales"), filename: Some("s.csv"), bytes: b"a\n", note: "new", turn: Some("t1"), ..Default::default() })
                .unwrap();
        let id = a.artifact.id.clone();
        for (bytes, note) in [(&b"a,b\n"[..], "wrote B"), (b"a,b,c\n", "filled C"), (b"a,b,c,d\n", "filled C")] {
            let s = save(SaveBytes { chat: "c", id: Some(&id), bytes, note, turn: Some("t1"), ..Default::default() }).unwrap();
            assert_eq!((s.version, s.replaced), (1, true));
        }
        let v1 = load(d.path(), &id).unwrap().artifact.version(1).unwrap().clone();
        assert_eq!((v1.note.as_str(), v1.turn.as_str()), ("new; wrote B; filled C", "t1"), "notes joined, not repeated");
        assert_eq!(std::fs::read(d.path().join(&v1.path)).unwrap(), b"a,b,c,d\n");
        // The next request: a version of its own, and again one however many saves.
        assert_eq!(save(SaveBytes { chat: "c", id: Some(&id), bytes: b"x\n", turn: Some("t2"), ..Default::default() }).unwrap().version, 2);
        assert_eq!(save(SaveBytes { chat: "c", id: Some(&id), bytes: b"y\n", turn: Some("t2"), ..Default::default() }).unwrap().version, 2);
        // Without a request (the user's draft in between), and after it: new versions.
        assert_eq!(save(SaveBytes { chat: "c", id: Some(&id), bytes: b"z\n", ..Default::default() }).unwrap().version, 3);
        assert_eq!(save(SaveBytes { chat: "c", id: Some(&id), bytes: b"w\n", turn: Some("t2"), ..Default::default() }).unwrap().version, 4);
    }

    #[test]
    fn bytes_from_a_plugin_become_versions_and_drafts_replace_one() {
        let d = tempfile::tempdir().unwrap();
        let types = ArtifactTypes::builtin();
        types.register(ArtifactType::new("application/x-sheet", "spreadsheet", ArtifactKind::Text).suffixes(&[".xlsx"]).binary());
        types.register(ArtifactType::new("text/csv", "table", ArtifactKind::Text).suffixes(&[".csv"]));
        let save = |s: SaveBytes<'_>| save_bytes(&types, d.path(), &s);
        // New: needs a title.
        assert!(save(SaveBytes { chat: "c", bytes: b"a,b\n1,2\n", ..Default::default() }).unwrap_err().contains("title"));
        let a = save(SaveBytes { chat: "c", title: Some("Sales"), filename: Some("sales.csv"), bytes: b"a,b\n1,2\n", ..Default::default() }).unwrap();
        assert!(a.created && a.version == 1 && a.artifact.content_type == "text/csv", "{a:?}");
        let id = a.artifact.id.clone();
        assert_eq!(parse_version_path(&a.file.to_string_lossy()), Some(ArtifactRef { id: id.clone(), version: 1 }));
        // A new file name re-types it; binary bytes are kept as they are.
        let bin = [0u8, 159, 146, 150, 1, 2];
        let b = save(SaveBytes { chat: "c", id: Some(&id), filename: Some("sales.xlsx"), bytes: &bin, note: "imported", ..Default::default() }).unwrap();
        assert_eq!((b.version, b.created, b.replaced), (2, false, false));
        assert_eq!((b.artifact.filename.as_str(), b.artifact.content_type.as_str()), ("sales.xlsx", "application/x-sheet"));
        assert!(b.file.ends_with("v2.xlsx"));
        assert_eq!(std::fs::read(&b.file).unwrap(), bin);
        // A draft over the latest replaces it; over an older one it is a new version.
        let c = save(SaveBytes { chat: "c", id: Some(&id), bytes: b"draft", replace: Some(2), ..Default::default() }).unwrap();
        assert_eq!((c.version, c.replaced), (2, true));
        assert_eq!(std::fs::read(&c.file).unwrap(), b"draft");
        assert_eq!(load(d.path(), &id).unwrap().artifact.version(2).unwrap().size, 5);
        let e = save(SaveBytes { chat: "c", id: Some(&id), bytes: b"again", replace: Some(1), ..Default::default() }).unwrap();
        assert_eq!((e.version, e.replaced), (3, false));
        assert_eq!(e.artifact.versions.iter().map(|v| v.n).collect::<Vec<_>>(), [1, 2, 3]);
        // Another chat's artifact, or nothing to save: refused.
        assert!(save(SaveBytes { chat: "other", id: Some(&id), bytes: b"x", ..Default::default() }).is_err());
        assert!(save(SaveBytes { chat: "c", id: Some(&id), bytes: b"", ..Default::default() }).is_err());
        assert!(save(SaveBytes { chat: "c", id: Some("nope"), bytes: b"x", ..Default::default() }).is_err());
    }

    /// A live file: added from inside the folder only (never `.byob`, never outside), its
    /// first snapshot taken; a change becomes a new version; removing it from the Library
    /// leaves the file itself alone.
    #[test]
    fn live_files_follow_the_persons_file_and_never_touch_it() {
        let types = ArtifactTypes::builtin();
        let d = tempfile::tempdir().unwrap();
        let ws = d.path();
        std::fs::write(ws.join("budget.csv"), "a,b\n1,2\n").unwrap();
        assert!(add_live(&types, ws, "c1", "../escape.csv").is_err(), "outside the folder");
        assert!(add_live(&types, ws, "c1", ".byob/artifacts/x/v1.md").is_err(), "byob's own folder");
        // Regression: by its full path, byob's own folder was let through.
        std::fs::create_dir_all(ws.join(".byob/undo/t")).unwrap();
        std::fs::write(ws.join(".byob/undo/t/0-x.md"), "kept").unwrap();
        let full = ws.canonicalize().unwrap().join(".byob/undo/t/0-x.md");
        let got = add_live(&types, ws, "c1", &full.display().to_string());
        assert!(got.is_err(), "byob's own folder, by its full path: {got:?}");
        assert!(add_live(&types, ws, "c1", "missing.csv").is_err());
        let a = add_live(&types, ws, "c1", "budget.csv").unwrap();
        assert_eq!(a.versions.len(), 1);
        assert_eq!(add_live(&types, ws, "c1", "./budget.csv").unwrap().id, a.id, "added once");
        assert_eq!(refresh_live(&types, ws), 0, "nothing changed yet");
        // Changed (by byob or in another app): a new version, the old one kept.
        std::fs::write(ws.join("budget.csv"), "a,b\n1,3\n").unwrap();
        assert_eq!(refresh_live(&types, ws), 1);
        let meta = list_all_meta(ws).into_iter().find(|m| m.artifact.id == a.id).unwrap();
        assert_eq!(meta.live.as_deref(), Some("budget.csv"));
        assert_eq!(meta.artifact.versions.len(), 2);
        // Regression: only the file makes its versions. A plugin's save or update_artifact
        // put another file in front of it, taken back (or garbled) by the next snapshot.
        let save = SaveBytes { chat: "c1", id: Some(&a.id), bytes: b"x,y\n", ..Default::default() };
        let refused = save_bytes(&types, ws, &save).unwrap_err();
        assert!(refused.contains("budget.csv"), "{refused}");
        let out = run_in(&UpdateArtifact { types: types.clone() }, ws, "c1", json!({"id": a.id, "content": "x,y\n"}));
        assert!(out.failed && out.text.contains("edit_file"), "{}", out.text);
        assert_eq!(list_all_meta(ws).into_iter().find(|m| m.artifact.id == a.id).unwrap().artifact.versions.len(), 2);
        // Removed from the Library: the snapshots go, the file stays.
        remove(ws, "c1", &a.id).unwrap();
        assert!(list_all_meta(ws).is_empty());
        assert_eq!(std::fs::read_to_string(ws.join("budget.csv")).unwrap(), "a,b\n1,3\n");
    }
}