artifactize-core 0.26.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
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
//! 3-tier ACP Chat agent catalog: built-in presets, official ACP Registry pinned installs,
//! and machine-local custom ACP agents (`$STATE/chat/agents.json` + `$STATE/chat/secrets.json`).
//!
//! Never loads ACP commands, arguments or environment from repository-committed files.
//! All status, version and model probes run exclusively in empty private tempdirs.

use std::{
    collections::BTreeMap,
    ffi::OsString,
    path::{Path, PathBuf},
    sync::{
        Mutex, OnceLock,
        atomic::{AtomicU64, Ordering},
    },
    time::{Duration, Instant, SystemTime},
};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tokio_util::sync::CancellationToken;

use crate::{
    auth::storage::{Storage, Tokens},
    llm::models::ListedModel,
    platform, process,
};

use super::{
    AgentId, ConfigOption, Problem,
    trust::{self, LauncherFingerprint},
    wire::{Connection, INITIALIZE_TIMEOUT},
};

const AGENTS_FILE: &str = "agents.json";
const AGENTS_LOCK: &str = "agents";
const SECRETS_FILE: &str = "secrets.json";
const SECRETS_LOCK: &str = "secrets";
const AGENTS_SCHEMA_VERSION: u32 = 1;
/// Official ACP Registry discovery URL (latest is discovery-only; installs pin exact versions).
pub const DEFAULT_REGISTRY_URL: &str =
    "https://raw.githubusercontent.com/agentclientprotocol/registry/main/registry.json";
/// Environment override for offline Registry discovery tests.
const REGISTRY_URL_ENV: &str = "ARTIFACTIZE_ACP_REGISTRY_URL";
/// Probe results are cached per `(agent_id, resolved_executable, args_hash, mtime_or_version, auth_generation)`.
pub const PROBE_CACHE_TTL: Duration = Duration::from_secs(2 * 60);
/// Interactive probe timeout (matches model listing timeout).
pub const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
/// Network fetch timeout for Registry catalog discovery and pinned artifact downloads.
const REGISTRY_FETCH_TIMEOUT: Duration = Duration::from_secs(30);
/// Maximum size of a single custom secret env value.
const MAX_SECRET_VALUE_BYTES: usize = 16 * 1024;
/// Maximum Registry artifact download size (256 MiB) to bound local disk usage.
const MAX_REGISTRY_ARTIFACT_BYTES: usize = 256 * 1024 * 1024;
/// Antigravity minimum CLI version for ACP model support.
pub const ANTIGRAVITY_MINIMUM: semver::Version = semver::Version::new(1, 5, 1);

/// Alternate Google auth env vars removed for Antigravity so its own Google login is used.
pub(crate) const ANTIGRAVITY_ALTERNATE_AUTH: &[&str] = &[
    "GEMINI_API_KEY",
    "GOOGLE_API_KEY",
    "GOOGLE_APPLICATION_CREDENTIALS",
    "GOOGLE_GENAI_USE_VERTEXAI",
];

static AUTH_GENERATION: AtomicU64 = AtomicU64::new(1);

/// Bump after any native CLI login/logout so probe caches and runtime fingerprints refresh.
pub fn bump_auth_generation() -> u64 {
    AUTH_GENERATION.fetch_add(1, Ordering::SeqCst) + 1
}

pub fn auth_generation() -> u64 {
    AUTH_GENERATION.load(Ordering::SeqCst)
}

/// Isolation and transport metadata declared by each built-in ACP preset.
#[derive(Debug, Clone)]
pub struct Preset {
    pub id: &'static str,
    pub display_name: &'static str,
    pub program: &'static str,
    pub args: &'static [&'static str],
    pub version_args: &'static [&'static str],
    pub minimum_version: Option<semver::Version>,
    pub env_denylist: &'static [&'static str],
    pub extra_env: &'static [(&'static str, &'static str)],
    pub mcp_stdio: bool,
    pub supports_same_child_load: bool,
    pub can_disable_project_config: bool,
    pub native_sandbox_note: &'static str,
    pub hide_always_options: bool,
    pub install_hint: &'static str,
    pub login_action: &'static str,
}

/// Built-in 3-OS ACP Chat presets.
pub const PRESETS: &[Preset] = &[
    Preset {
        id: "antigravity",
        display_name: "Antigravity",
        program: "agy",
        args: &["acp"],
        version_args: &["--version"],
        minimum_version: Some(ANTIGRAVITY_MINIMUM),
        env_denylist: ANTIGRAVITY_ALTERNATE_AUTH,
        extra_env: &[("AGY_CLI_DISABLE_AUTO_UPDATE", "1")],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: true,
        native_sandbox_note: "Runs natively in the worktree via `agy acp`; ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: false,
        install_hint: "Install the Antigravity CLI (`agy`), then sign in via `artifactize login antigravity` or Settings → Chat Agents.",
        login_action: "artifactize login antigravity",
    },
    Preset {
        id: "claude-acp",
        display_name: "Claude ACP",
        program: "claude-agent-acp",
        args: &[],
        version_args: &["--version"],
        minimum_version: None,
        env_denylist: &[],
        extra_env: &[],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: false,
        native_sandbox_note: "Runs Claude Code's native harness via ACP in the worktree; may read repository `.claude/` settings and hooks on startup. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: false,
        install_hint: "Install `claude-agent-acp` (or install from Settings → Chat Agents → Browse Registry) and sign in with `claude auth login`.",
        login_action: "claude auth login",
    },
    Preset {
        id: "codex-acp",
        display_name: "Codex ACP",
        program: "codex-acp",
        args: &[],
        version_args: &["--version"],
        minimum_version: None,
        env_denylist: &[],
        extra_env: &[],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: false,
        native_sandbox_note: "Runs Codex's native harness via ACP in the worktree; native sandbox/approval modes are exposed via `configOptions`. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: false,
        install_hint: "Install `codex-acp` (or install from Settings → Chat Agents → Browse Registry) and sign in with Codex.",
        login_action: "codex login",
    },
    Preset {
        id: "gemini-cli",
        display_name: "Gemini CLI",
        program: "gemini",
        args: &["--experimental-acp"],
        version_args: &["--version"],
        minimum_version: None,
        env_denylist: &[],
        extra_env: &[],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: false,
        native_sandbox_note: "Runs Gemini CLI natively via ACP in the worktree; may read `.gemini/settings.json` on startup. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: false,
        install_hint: "Install Gemini CLI (`gemini`) and complete its login in a terminal.",
        login_action: "gemini",
    },
    Preset {
        id: "opencode",
        display_name: "OpenCode",
        program: "opencode",
        args: &["acp"],
        version_args: &["--version"],
        minimum_version: None,
        env_denylist: &[],
        extra_env: &[],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: false,
        native_sandbox_note: "Runs OpenCode natively via ACP in the worktree; may read `opencode.json` on startup. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: false,
        install_hint: "Install OpenCode (`opencode`) and configure its credentials.",
        login_action: "opencode auth login",
    },
    Preset {
        id: "copilot",
        display_name: "GitHub Copilot",
        program: "copilot",
        args: &["--acp"],
        version_args: &["--version"],
        minimum_version: None,
        env_denylist: &[],
        extra_env: &[],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: false,
        native_sandbox_note: "Runs GitHub Copilot CLI natively via ACP in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: true,
        install_hint: "Install GitHub Copilot CLI (`copilot`) and sign in with GitHub.",
        login_action: "copilot auth login",
    },
    Preset {
        id: "cursor",
        display_name: "Cursor Agent",
        program: "cursor-agent",
        args: &["acp"],
        version_args: &["--version"],
        minimum_version: None,
        env_denylist: &[],
        extra_env: &[],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: false,
        native_sandbox_note: "Runs Cursor Agent natively via ACP in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: true,
        install_hint: "Install Cursor Agent (`cursor-agent`) and sign in.",
        login_action: "cursor-agent login",
    },
    Preset {
        id: "goose",
        display_name: "Goose",
        program: "goose",
        args: &["acp"],
        version_args: &["--version"],
        minimum_version: None,
        env_denylist: &[],
        extra_env: &[],
        mcp_stdio: true,
        supports_same_child_load: true,
        can_disable_project_config: false,
        native_sandbox_note: "Runs Goose natively via ACP in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).",
        hide_always_options: true,
        install_hint: "Install Goose (`goose`) and run `goose configure`.",
        login_action: "goose configure",
    },
];

pub fn preset_by_id(id: &str) -> Option<&'static Preset> {
    PRESETS.iter().find(|preset| preset.id == id)
}

pub fn is_builtin_preset(id: &str) -> bool {
    preset_by_id(id).is_some()
}

/// Whether `name` matches a built-in ACP preset or a saved machine-local ACP agent.
/// Used by eval routing to give a targeted diagnostic when an unknown backend is a Chat agent.
pub fn is_chat_agent(name: &str, state: Option<&Path>, repo: Option<&Path>) -> bool {
    if is_builtin_preset(name) {
        return true;
    }
    list_custom(state, repo)
        .map(|agents| agents.iter().any(|agent| agent.id.as_str() == name))
        .unwrap_or(false)
}

/// Distribution kind for an official ACP Registry entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DistributionKind {
    Binary,
    Archive,
    Npx,
    Uvx,
}

/// Complete resolved specification bound to user consent before installing from the ACP Registry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegistryInstallSpec {
    pub registry_id: AgentId,
    pub display_name: String,
    pub exact_version: String,
    pub platform: String,
    pub distribution_kind: DistributionKind,
    pub package_or_url: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub env_pairs: BTreeMap<String, String>,
    #[serde(default)]
    pub build_scripts_allowed: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_sha256: Option<String>,
    /// Explicitly true only when the user confirmed the computed SHA-256 of an unsigned entry.
    #[serde(default)]
    pub allow_unsigned_digest: bool,
}

/// One discovered entry from the official ACP Registry (discovery-only; never auto-executed).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegistryEntry {
    pub id: AgentId,
    pub name: String,
    pub version: String,
    #[serde(default)]
    pub description: String,
    pub spec: RegistryInstallSpec,
}

/// Tier of an ACP Chat agent in the catalog.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AgentTier {
    Preset,
    Registry,
    Custom,
}

/// A machine-local custom or Registry-installed ACP agent saved in `$STATE/chat/agents.json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomAgent {
    pub id: AgentId,
    pub name: String,
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Secret env variable names whose values live in `$STATE/chat/secrets.json` (never echoed here).
    #[serde(default)]
    pub secret_env_keys: Vec<String>,
    #[serde(default = "default_true")]
    pub mcp_stdio: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<RegistryInstallSpec>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entrypoint_sha256: Option<String>,
}

fn default_true() -> bool {
    true
}

/// A secret env value redacted in `Debug` and stored separately in `$STATE/chat/secrets.json`.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SecretEnvValue(String);

impl SecretEnvValue {
    pub fn parse(raw: &str) -> Result<Self, String> {
        if raw.is_empty() || raw.len() > MAX_SECRET_VALUE_BYTES {
            return Err(format!(
                "Secret environment value must be 1–{MAX_SECRET_VALUE_BYTES} bytes."
            ));
        }
        if raw.bytes().any(|byte| byte == 0) {
            return Err("Secret environment value cannot contain NUL bytes.".into());
        }
        Ok(Self(raw.to_owned()))
    }

    pub(crate) fn expose(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Debug for SecretEnvValue {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("SecretEnvValue(…)")
    }
}

/// Unified descriptor of any ACP agent (preset, Registry-installed, or custom) resolved for launch.
#[derive(Debug, Clone)]
pub struct AgentSpec {
    pub id: AgentId,
    pub name: String,
    pub tier: AgentTier,
    pub program: String,
    pub args: Vec<String>,
    pub version_args: Vec<String>,
    pub minimum_version: Option<semver::Version>,
    pub env_denylist: Vec<String>,
    pub extra_env: BTreeMap<String, String>,
    pub secret_env: BTreeMap<String, SecretEnvValue>,
    pub mcp_stdio: bool,
    pub supports_same_child_load: bool,
    pub reject_worktree_executable: bool,
    pub hide_always_options: bool,
    pub native_sandbox_note: String,
    pub can_disable_project_config: bool,
    pub install_hint: String,
    pub login_action: String,
}

impl AgentSpec {
    pub fn from_preset(preset: &Preset) -> Self {
        Self {
            id: preset.id.parse().expect("built-in preset id is valid"),
            name: preset.display_name.to_owned(),
            tier: AgentTier::Preset,
            program: preset.program.to_owned(),
            args: preset.args.iter().map(|arg| (*arg).to_owned()).collect(),
            version_args: preset
                .version_args
                .iter()
                .map(|arg| (*arg).to_owned())
                .collect(),
            minimum_version: preset.minimum_version.clone(),
            env_denylist: preset
                .env_denylist
                .iter()
                .map(|name| (*name).to_owned())
                .collect(),
            extra_env: preset
                .extra_env
                .iter()
                .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
                .collect(),
            secret_env: BTreeMap::new(),
            mcp_stdio: preset.mcp_stdio,
            supports_same_child_load: preset.supports_same_child_load,
            reject_worktree_executable: true,
            hide_always_options: preset.hide_always_options,
            native_sandbox_note: preset.native_sandbox_note.to_owned(),
            can_disable_project_config: preset.can_disable_project_config,
            install_hint: preset.install_hint.to_owned(),
            login_action: preset.login_action.to_owned(),
        }
    }

    /// Build the child environment following the #145 env contract uniformly across probe,
    /// login, Chat, and resume. Relative `PATH` entries and denylisted auth keys are stripped
    /// after applying custom/secret overrides so custom env cannot re-introduce them
    /// (`C-TRUST-BEFORE-WORKTREE`).
    pub fn build_env(&self, for_worktree: bool) -> BTreeMap<OsString, OsString> {
        let mut env = platform::environment::for_command();
        for (key, value) in &self.extra_env {
            platform::environment::set(&mut env, key, value);
        }
        for (key, secret) in &self.secret_env {
            platform::environment::set(&mut env, key, secret.expose());
        }
        if for_worktree {
            platform::environment::strip_relative_path_entries(&mut env);
        }
        for name in &self.env_denylist {
            platform::environment::remove(&mut env, name);
        }
        env
    }

    /// All secret values injected into this agent's environment (for `StreamRedactor`).
    pub fn known_secrets(&self) -> Vec<String> {
        self.secret_env
            .values()
            .map(|secret| secret.expose().to_owned())
            .collect()
    }
}

/// Summary of an ACP agent for Settings → Chat Agents and CLI `chat-agent list`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CatalogEntry {
    pub id: AgentId,
    pub name: String,
    pub tier: AgentTier,
    pub command: String,
    pub args: Vec<String>,
    pub env: BTreeMap<String, String>,
    pub secret_env_keys: Vec<String>,
    pub mcp_stdio: bool,
    pub can_disable_project_config: bool,
    pub native_sandbox_note: String,
    pub login_action: String,
    pub install_hint: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<RegistryInstallSpec>,
}

/// Result of probing an ACP agent in an empty private tempdir.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    rename_all = "camelCase",
    rename_all_fields = "camelCase"
)]
pub enum AgentAvailability {
    Ready {
        #[serde(with = "crate::platform::path_serde")]
        executable: PathBuf,
        version: Option<String>,
        models: Vec<ListedModel>,
        config_options: Vec<ConfigOption>,
    },
    NotSetUp {
        #[serde(with = "crate::platform::path_serde::option")]
        executable: Option<PathBuf>,
        version: Option<String>,
        reason: String,
        login_action: String,
    },
    Missing {
        reason: String,
    },
    TooOld {
        #[serde(with = "crate::platform::path_serde")]
        executable: PathBuf,
        version: String,
        required_version: String,
        reason: String,
    },
    Failed {
        #[serde(with = "crate::platform::path_serde::option")]
        executable: Option<PathBuf>,
        version: Option<String>,
        error: String,
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SavedAgents {
    version: u32,
    #[serde(default)]
    agents: Vec<CustomAgent>,
}

impl Default for SavedAgents {
    fn default() -> Self {
        Self {
            version: AGENTS_SCHEMA_VERSION,
            agents: Vec::new(),
        }
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SavedSecrets {
    #[serde(default)]
    by_agent: BTreeMap<String, BTreeMap<String, SecretEnvValue>>,
}

/// List all saved custom and Registry-installed ACP agents in `$STATE/chat/agents.json`.
pub fn list_custom(state: Option<&Path>, repo: Option<&Path>) -> Result<Vec<CustomAgent>, String> {
    let storage = Storage::inspect(state, repo, Tokens::ChatAgents)?;
    Ok(storage
        .read::<SavedAgents>(AGENTS_FILE)?
        .unwrap_or_default()
        .agents)
}

/// List the full 3-tier catalog (built-in presets + Registry-installed + custom agents).
pub fn list_catalog(
    state: Option<&Path>,
    repo: Option<&Path>,
) -> Result<Vec<CatalogEntry>, String> {
    let mut entries: Vec<CatalogEntry> = PRESETS
        .iter()
        .map(|preset| CatalogEntry {
            id: preset.id.parse().expect("preset id is valid"),
            name: preset.display_name.to_owned(),
            tier: AgentTier::Preset,
            command: preset.program.to_owned(),
            args: preset.args.iter().map(|arg| (*arg).to_owned()).collect(),
            env: BTreeMap::new(),
            secret_env_keys: Vec::new(),
            mcp_stdio: preset.mcp_stdio,
            can_disable_project_config: preset.can_disable_project_config,
            native_sandbox_note: preset.native_sandbox_note.to_owned(),
            login_action: preset.login_action.to_owned(),
            install_hint: preset.install_hint.to_owned(),
            registry: None,
        })
        .collect();
    for custom in list_custom(state, repo)? {
        let tier = if custom.registry.is_some() {
            AgentTier::Registry
        } else {
            AgentTier::Custom
        };
        entries.push(CatalogEntry {
            id: custom.id,
            name: custom.name,
            tier,
            command: custom.command,
            args: custom.args,
            env: custom.env,
            secret_env_keys: custom.secret_env_keys,
            mcp_stdio: custom.mcp_stdio,
            can_disable_project_config: false,
            native_sandbox_note: "Custom ACP agent running natively in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).".into(),
            login_action: String::new(),
            install_hint: String::new(),
            registry: custom.registry,
        });
    }
    Ok(entries)
}

/// Resolve an `AgentId` to its launchable `AgentSpec` (loading secret env values from
/// `$STATE/chat/secrets.json` when applicable).
pub fn resolve_spec(
    agent_id: &AgentId,
    state: Option<&Path>,
    repo: Option<&Path>,
) -> Result<AgentSpec, String> {
    if let Some(preset) = preset_by_id(agent_id.as_str()) {
        return Ok(AgentSpec::from_preset(preset));
    }
    let custom = list_custom(state, repo)?
        .into_iter()
        .find(|agent| &agent.id == agent_id)
        .ok_or_else(|| format!("No ACP Chat agent named {agent_id:?} is configured."))?;
    let secret_storage = Storage::inspect(state, repo, Tokens::ChatSecrets)?;
    let secret_env = secret_storage
        .read::<SavedSecrets>(SECRETS_FILE)?
        .unwrap_or_default()
        .by_agent
        .remove(agent_id.as_str())
        .unwrap_or_default();
    let tier = if custom.registry.is_some() {
        AgentTier::Registry
    } else {
        AgentTier::Custom
    };
    Ok(AgentSpec {
        id: custom.id,
        name: custom.name,
        tier,
        program: custom.command,
        args: custom.args,
        version_args: vec!["--version".into()],
        minimum_version: None,
        env_denylist: Vec::new(),
        extra_env: custom.env,
        secret_env,
        mcp_stdio: custom.mcp_stdio,
        supports_same_child_load: true,
        reject_worktree_executable: false,
        hide_always_options: false,
        native_sandbox_note: "Custom ACP agent running natively in the worktree. ACP client fs/terminal callbacks are disabled (not an OS sandbox).".into(),
        can_disable_project_config: false,
        install_hint: String::new(),
        login_action: String::new(),
    })
}

/// Save or update a machine-local custom ACP agent and its optional secret env values.
pub async fn save_custom_agent(
    state: Option<&Path>,
    repo: Option<&Path>,
    mut agent: CustomAgent,
    set_secrets: BTreeMap<String, SecretEnvValue>,
    remove_secret_keys: &[String],
) -> Result<CustomAgent, String> {
    if is_builtin_preset(agent.id.as_str()) {
        return Err(format!(
            "{} is a built-in ACP preset and cannot be shadowed by a custom agent.",
            agent.id
        ));
    }
    if agent.name.trim().is_empty() {
        return Err("Custom ACP agent display name cannot be empty.".into());
    }
    if agent.command.trim().is_empty() {
        return Err("Custom ACP agent command cannot be empty.".into());
    }
    let secrets_storage = Storage::new(state, repo, Tokens::ChatSecrets)?;
    let _secrets_lock = secrets_storage.lock(SECRETS_LOCK).await?;
    let mut secrets: SavedSecrets = secrets_storage.read(SECRETS_FILE)?.unwrap_or_default();
    let agent_secrets = secrets
        .by_agent
        .entry(agent.id.as_str().to_owned())
        .or_default();
    for key in remove_secret_keys {
        agent_secrets.remove(key);
    }
    for (key, value) in set_secrets {
        agent_secrets.insert(key, value);
    }
    agent.secret_env_keys = agent_secrets.keys().cloned().collect();
    secrets_storage.save(SECRETS_FILE, &secrets)?;

    let agents_storage = Storage::new(state, repo, Tokens::ChatAgents)?;
    let _agents_lock = agents_storage.lock(AGENTS_LOCK).await?;
    let mut saved: SavedAgents = agents_storage.read(AGENTS_FILE)?.unwrap_or_default();
    saved.agents.retain(|existing| existing.id != agent.id);
    saved.agents.push(agent.clone());
    agents_storage.save(AGENTS_FILE, &saved)?;
    invalidate_probe_cache(&agent.id);
    Ok(agent)
}

/// Remove a custom or Registry-installed ACP agent and its stored secrets.
pub async fn remove_custom_agent(
    state: Option<&Path>,
    repo: Option<&Path>,
    id: &AgentId,
) -> Result<bool, String> {
    if is_builtin_preset(id.as_str()) {
        return Err(format!(
            "{id} is a built-in ACP preset and cannot be removed."
        ));
    }
    let agents_storage = Storage::new(state, repo, Tokens::ChatAgents)?;
    let _agents_lock = agents_storage.lock(AGENTS_LOCK).await?;
    let mut saved: SavedAgents = agents_storage.read(AGENTS_FILE)?.unwrap_or_default();
    let before = saved.agents.len();
    saved.agents.retain(|existing| &existing.id != id);
    let removed = saved.agents.len() != before;
    if removed {
        agents_storage.save(AGENTS_FILE, &saved)?;
    }

    let secrets_storage = Storage::new(state, repo, Tokens::ChatSecrets)?;
    let _secrets_lock = secrets_storage.lock(SECRETS_LOCK).await?;
    let mut secrets: SavedSecrets = secrets_storage.read(SECRETS_FILE)?.unwrap_or_default();
    if secrets.by_agent.remove(id.as_str()).is_some() {
        secrets_storage.save(SECRETS_FILE, &secrets)?;
    }
    invalidate_probe_cache(id);
    Ok(removed)
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct ProbeCacheKey {
    agent_id: AgentId,
    resolved_executable: PathBuf,
    args_hash: String,
    mtime_secs: Option<u64>,
    auth_generation: u64,
}

struct CachedProbe {
    recorded_at: Instant,
    availability: AgentAvailability,
}

fn probe_cache() -> &'static Mutex<BTreeMap<ProbeCacheKey, CachedProbe>> {
    static CACHE: OnceLock<Mutex<BTreeMap<ProbeCacheKey, CachedProbe>>> = OnceLock::new();
    CACHE.get_or_init(Mutex::default)
}

pub fn invalidate_probe_cache(agent_id: &AgentId) {
    if let Ok(mut cache) = probe_cache().lock() {
        cache.retain(|key, _| &key.agent_id != agent_id);
    }
}

/// Probe an ACP agent strictly inside an empty private tempdir (never `cwd = worktree`),
/// returning availability, models, and live `configOptions` without triggering interactive auth.
pub async fn probe_agent(
    agent_id: &AgentId,
    state: Option<&Path>,
    repo: Option<&Path>,
    force_refresh: bool,
) -> AgentAvailability {
    let spec = match resolve_spec(agent_id, state, repo) {
        Ok(spec) => spec,
        Err(error) => {
            return AgentAvailability::Failed {
                executable: None,
                version: None,
                error,
            };
        }
    };
    probe_spec(&spec, force_refresh).await
}

pub async fn probe_spec(spec: &AgentSpec, force_refresh: bool) -> AgentAvailability {
    let probe_dir = match platform::private_tempdir_in(
        "artifactize-acp-probe-",
        &platform::temporary_directory(),
    ) {
        Ok(dir) => dir,
        Err(error) => {
            return AgentAvailability::Failed {
                executable: None,
                version: None,
                error: format!("Cannot create ACP probe directory: {error}."),
            };
        }
    };
    let program_path = match platform::program_path(&spec.program) {
        Ok(path) => path,
        Err(error) => {
            return AgentAvailability::Failed {
                executable: None,
                version: None,
                error: format!("Invalid ACP command {:?}: {error}.", spec.program),
            };
        }
    };
    let resolved = match platform::program::resolve(&program_path, probe_dir.path()) {
        Ok(path) => platform::canonicalize(&path).unwrap_or(path),
        Err(_) => {
            return AgentAvailability::Missing {
                reason: if spec.install_hint.is_empty() {
                    format!("Executable {:?} is not on PATH.", spec.program)
                } else {
                    format!(
                        "{} (`{}`) is not on PATH. {}",
                        spec.name, spec.program, spec.install_hint
                    )
                },
            };
        }
    };
    let mtime_secs = std::fs::metadata(&resolved)
        .ok()
        .and_then(|meta| meta.modified().ok())
        .and_then(|modified| modified.duration_since(SystemTime::UNIX_EPOCH).ok())
        .map(|duration| duration.as_secs());
    let cache_key = ProbeCacheKey {
        agent_id: spec.id.clone(),
        resolved_executable: resolved.clone(),
        args_hash: trust::hash_args(&spec.args),
        mtime_secs,
        auth_generation: auth_generation(),
    };
    if !force_refresh
        && let Ok(cache) = probe_cache().lock()
        && let Some(entry) = cache.get(&cache_key)
        && entry.recorded_at.elapsed() < PROBE_CACHE_TTL
    {
        return entry.availability.clone();
    }

    let availability = run_live_probe(spec, &resolved, probe_dir.path()).await;
    if let Ok(mut cache) = probe_cache().lock() {
        cache.insert(
            cache_key,
            CachedProbe {
                recorded_at: Instant::now(),
                availability: availability.clone(),
            },
        );
    }
    availability
}

async fn run_live_probe(
    spec: &AgentSpec,
    executable: &Path,
    probe_dir: &Path,
) -> AgentAvailability {
    let cancel = CancellationToken::new();
    let deadline = tokio::time::Instant::now() + PROBE_TIMEOUT;

    let detected_version = probe_version(spec, executable, probe_dir, deadline, &cancel).await;
    if let Some(minimum) = &spec.minimum_version {
        match &detected_version {
            None => {
                return AgentAvailability::Failed {
                    executable: Some(executable.to_path_buf()),
                    version: None,
                    error: format!(
                        "Cannot read the {} CLI version; requires {minimum} or newer.",
                        spec.name
                    ),
                };
            }
            Some(found) if found < minimum => {
                return AgentAvailability::TooOld {
                    executable: executable.to_path_buf(),
                    version: found.to_string(),
                    required_version: minimum.to_string(),
                    reason: format!(
                        "{} {found} is too old; update to {minimum} or newer.",
                        spec.name
                    ),
                };
            }
            Some(_) => {}
        }
    }

    let mut args: Vec<OsString> = spec.args.iter().map(OsString::from).collect();
    // For Antigravity empty-tempdir probes, disable default customizations cleanly.
    if spec.id.as_str() == "antigravity" {
        args.push("--sandbox".into());
        args.push("--include-default-customizations=false".into());
    }
    let command = process::Command {
        program: executable.as_os_str().to_owned(),
        args,
        cwd: probe_dir.to_path_buf(),
        env: spec.build_env(false),
        timeout: PROBE_TIMEOUT,
    };
    let process_cancel = CancellationToken::new();
    let mut child = match process::spawn_supervised(&command, &process_cancel).await {
        Ok(child) => child,
        Err(error) => {
            return AgentAvailability::Failed {
                executable: Some(executable.to_path_buf()),
                version: detected_version.map(|v| v.to_string()),
                error: format!("Cannot start {}: {error}.", spec.name),
            };
        }
    };
    let stdout = child.stdout().take().expect("probe stdout piped");
    let stdin = child.stdin().take().expect("probe stdin piped");
    let mut stderr = child.stderr().take().expect("probe stderr piped");
    let stderr_task = tokio::spawn(async move { read_bounded_stderr(&mut stderr).await });
    let mut conn = Connection::new(
        &spec.name,
        &spec.install_hint,
        stdout,
        stdin,
        spec.hide_always_options,
        spec.known_secrets(),
    );
    let result = tokio::time::timeout(PROBE_TIMEOUT, conn.inspect_models(probe_dir))
        .await
        .unwrap_or_else(|_| {
            Err(Problem::Failed(format!(
                "{} did not answer the ACP probe in time.",
                spec.name
            )))
        });
    drop(conn);
    let _ = process::terminate(&mut child).await;
    let _ = child.cleanup().await;
    let stderr_bytes = crate::task::joined(stderr_task.await).unwrap_or_default();
    let stderr_text = platform::output_text(&stderr_bytes);

    let version_str = detected_version.map(|v| v.to_string());
    match result {
        Ok((models, config_options)) => AgentAvailability::Ready {
            executable: executable.to_path_buf(),
            version: version_str,
            models,
            config_options,
        },
        Err(problem) => {
            let classified = if stderr_text.contains(super::wire::AUTH_LINK_MARKER) {
                Problem::SignedOut {
                    agent: spec.name.clone(),
                    hint: spec.install_hint.clone(),
                }
            } else if matches!(problem, Problem::Failed(_)) {
                Problem::classify_text(&spec.name, &spec.install_hint, &stderr_text)
                    .unwrap_or(problem)
            } else {
                problem
            };
            match classified {
                Problem::SignedOut { .. } => AgentAvailability::NotSetUp {
                    executable: Some(executable.to_path_buf()),
                    version: version_str,
                    reason: format!("Sign in to {}.", spec.name),
                    login_action: spec.login_action.clone(),
                },
                other => AgentAvailability::Failed {
                    executable: Some(executable.to_path_buf()),
                    version: version_str,
                    error: crate::agent::error::Failure::from(other).message,
                },
            }
        }
    }
}

/// Maximum stderr bytes retained from a short-lived ACP probe or logout child (`C-ACP-EDGE-ISOLATION`).
const PROBE_STDERR_LIMIT: usize = 64 * 1024;
const PROBE_STDERR_CHUNK: usize = 4 * 1024;

pub(crate) async fn read_bounded_stderr(stderr: &mut tokio::process::ChildStderr) -> Vec<u8> {
    use tokio::io::AsyncReadExt;
    let mut kept = Vec::new();
    let mut buf = [0u8; PROBE_STDERR_CHUNK];
    while let Ok(count) = stderr.read(&mut buf).await {
        if count == 0 {
            break;
        }
        kept.extend_from_slice(&buf[..count]);
        if kept.len() > PROBE_STDERR_LIMIT {
            kept.drain(..kept.len() - PROBE_STDERR_LIMIT);
        }
    }
    kept
}

async fn probe_version(
    spec: &AgentSpec,
    executable: &Path,
    probe_dir: &Path,
    deadline: tokio::time::Instant,
    cancel: &CancellationToken,
) -> Option<semver::Version> {
    if spec.version_args.is_empty() {
        return None;
    }
    let command = process::Command {
        program: executable.as_os_str().to_owned(),
        args: spec.version_args.iter().map(OsString::from).collect(),
        cwd: probe_dir.to_path_buf(),
        env: spec.build_env(false),
        timeout: deadline
            .saturating_duration_since(tokio::time::Instant::now())
            .min(INITIALIZE_TIMEOUT),
    };
    let output = process::run(command, cancel.clone(), |_| async { Ok(()) })
        .await
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = platform::output_text(&output.stdout);
    text.split_whitespace()
        .find_map(|word| semver::Version::parse(word.trim_start_matches('v')).ok())
}

/// Discover official ACP Registry entries (`latest` is discovery-only; never auto-executed).
pub async fn discover_registry() -> Result<Vec<RegistryEntry>, String> {
    let url = platform::environment::var_text(REGISTRY_URL_ENV)
        .filter(|value| !value.trim().is_empty())
        .unwrap_or_else(|| DEFAULT_REGISTRY_URL.to_owned());
    let client = reqwest::Client::builder()
        .timeout(REGISTRY_FETCH_TIMEOUT)
        .redirect(reqwest::redirect::Policy::limited(5))
        .build()
        .map_err(|error| format!("Cannot build HTTP client for ACP Registry: {error}."))?;
    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|error| format!("Cannot fetch ACP Registry from {url}: {error}."))?;
    if !response.status().is_success() {
        return Err(format!(
            "ACP Registry returned HTTP {} for {url}.",
            response.status()
        ));
    }
    let raw: RawRegistryFeed = response
        .json()
        .await
        .map_err(|error| format!("Cannot parse ACP Registry feed: {error}."))?;
    let platform_key = current_platform_key();
    let mut entries = Vec::new();
    for item in raw.agents {
        let Ok(id) = item.id.parse::<AgentId>() else {
            continue;
        };
        if let Some(spec) = resolve_registry_spec(&id, &item, platform_key) {
            entries.push(RegistryEntry {
                id,
                name: item.name,
                version: item.version,
                description: item.description.unwrap_or_default(),
                spec,
            });
        }
    }
    Ok(entries)
}

/// Install a pinned ACP Registry entry into `$STATE/chat/runtimes/<agent>/<exact-version>/`
/// after explicit full-spec consent. Checks MSIX constraints, verifies SHA-256, rejects
/// symlinks/reparse points/zip-slip, and defaults to `--ignore-scripts` / `--only-binary=:all:`.
pub async fn install_registry_agent(
    state: Option<&Path>,
    repo: Option<&Path>,
    spec: RegistryInstallSpec,
) -> Result<CustomAgent, String> {
    if is_builtin_preset(spec.registry_id.as_str()) {
        return Err(format!(
            "{} matches a built-in ACP preset and cannot shadow it.",
            spec.registry_id
        ));
    }
    if platform::install::is_msix() {
        return Err(
            "Microsoft Store (MSIX) installations restrict dynamic runtime execution under state directories; install the agent CLI onto PATH instead."
                .into(),
        );
    }
    if spec.exact_version.trim().is_empty()
        || spec.exact_version.eq_ignore_ascii_case("latest")
        || !spec
            .exact_version
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_' | b'+'))
    {
        return Err(format!(
            "Registry installs require an exact pinned version (got {:?}).",
            spec.exact_version
        ));
    }
    let chat_storage = Storage::new(state, repo, Tokens::ChatAgents)?;
    let runtimes_root = chat_storage.directory.join("runtimes");
    platform::create_private_dir_all(&runtimes_root).map_err(|e| e.to_string())?;
    let target_dir = runtimes_root
        .join(spec.registry_id.as_str())
        .join(&spec.exact_version);
    platform::create_private_dir_all(&target_dir).map_err(|e| e.to_string())?;

    let entrypoint = match spec.distribution_kind {
        DistributionKind::Binary => install_pinned_binary(&spec, &target_dir).await?,
        DistributionKind::Archive => {
            return Err(
                "Archive extraction requires a verified binary or npm/uvx package entrypoint; unpack manually or choose a Binary/Npx/Uvx distribution."
                    .into(),
            );
        }
        DistributionKind::Npx => install_pinned_npm(&spec, &target_dir).await?,
        DistributionKind::Uvx => install_pinned_uv(&spec, &target_dir).await?,
    };

    // Verify no symlink/reparse point escape and that final executable stays within target_dir.
    verify_tree_no_links(&target_dir)?;
    let canonical_target = platform::canonicalize(&target_dir).map_err(|e| e.to_string())?;
    let canonical_entry = platform::canonicalize(&entrypoint).map_err(|e| e.to_string())?;
    if !platform::is_within(&canonical_entry, &canonical_target) {
        return Err(
            "Installed ACP runtime entrypoint escaped its pinned runtime directory.".into(),
        );
    }
    let entrypoint_sha256 = trust::hash_executable(&canonical_entry)?;

    let agent = CustomAgent {
        id: spec.registry_id.clone(),
        name: spec.display_name.clone(),
        command: platform::path_text(&canonical_entry),
        args: spec.args.clone(),
        env: spec.env_pairs.clone(),
        secret_env_keys: Vec::new(),
        mcp_stdio: true,
        registry: Some(spec),
        entrypoint_sha256: Some(entrypoint_sha256),
    };
    save_custom_agent(state, repo, agent, BTreeMap::new(), &[]).await
}

async fn install_pinned_binary(
    spec: &RegistryInstallSpec,
    target_dir: &Path,
) -> Result<PathBuf, String> {
    let url = url::Url::parse(&spec.package_or_url)
        .map_err(|_| format!("Invalid binary URL {:?}.", spec.package_or_url))?;
    if !matches!(url.scheme(), "https" | "http") {
        return Err("Registry binary downloads require an http(s) URL.".into());
    }
    let client = reqwest::Client::builder()
        .timeout(REGISTRY_FETCH_TIMEOUT)
        .build()
        .map_err(|error| format!("Cannot build HTTP client: {error}."))?;
    let response = client
        .get(url)
        .send()
        .await
        .map_err(|error| format!("Cannot download Registry binary: {error}."))?;
    if !response.status().is_success() {
        return Err(format!(
            "Registry binary download failed with HTTP {}.",
            response.status()
        ));
    }
    let bytes = response
        .bytes()
        .await
        .map_err(|error| format!("Cannot read Registry binary bytes: {error}."))?;
    if bytes.len() > MAX_REGISTRY_ARTIFACT_BYTES {
        return Err("Registry binary exceeds the 256 MiB safety limit.".into());
    }
    let computed = hex_sha256(&bytes);
    match &spec.artifact_sha256 {
        Some(expected) if expected.eq_ignore_ascii_case(&computed) => {}
        Some(expected) => {
            return Err(format!(
                "SHA-256 mismatch for {}: expected {expected}, got {computed}.",
                spec.registry_id
            ));
        }
        None if spec.allow_unsigned_digest => {}
        None => {
            return Err(format!(
                "Unsigned Registry binary blocked by default. Re-confirm install with computed SHA-256 {computed}."
            ));
        }
    }
    let final_path = platform::install_executable(target_dir, spec.registry_id.as_str(), &bytes)
        .map_err(|e| format!("Cannot install {}: {e}.", spec.registry_id))?;
    Ok(final_path)
}

async fn install_pinned_npm(
    spec: &RegistryInstallSpec,
    target_dir: &Path,
) -> Result<PathBuf, String> {
    let empty_cwd = platform::private_tempdir_in("acp-npm-", &platform::temporary_directory())
        .map_err(|e| e.to_string())?;
    let mut args = vec![
        OsString::from("install"),
        OsString::from("--prefix"),
        target_dir.as_os_str().to_owned(),
        OsString::from("--no-audit"),
        OsString::from("--no-fund"),
        OsString::from("--save-exact"),
    ];
    if !spec.build_scripts_allowed {
        args.push(OsString::from("--ignore-scripts"));
    }
    args.push(OsString::from(format!(
        "{}@{}",
        spec.package_or_url, spec.exact_version
    )));
    let command = process::Command {
        program: OsString::from("npm"),
        args,
        cwd: empty_cwd.path().to_path_buf(),
        env: platform::environment::for_command(),
        timeout: Duration::from_secs(120),
    };
    let output = process::run(command, CancellationToken::new(), |_| async { Ok(()) })
        .await
        .map_err(|error| format!("Pinned npm install failed: {error}."))?;
    if !output.status.success() {
        return Err(format!(
            "Pinned npm install failed: {}",
            platform::output_text(&output.stderr).trim()
        ));
    }
    let bin_dir = target_dir.join("node_modules").join(".bin");
    if let Ok(resolved) =
        platform::program::resolve(&bin_dir.join(spec.registry_id.as_str()), &bin_dir)
    {
        Ok(resolved)
    } else {
        // Fall back to the first runnable entrypoint in node_modules/.bin via platform lookup.
        let handle = platform::open_directory(&bin_dir).map_err(|e| e.to_string())?;
        let entries = platform::read_dir(&handle).map_err(|e| e.to_string())?;
        let mut found = None;
        for entry in entries {
            let entry = entry.map_err(|e| e.to_string())?;
            if let Ok(resolved) =
                platform::program::resolve(&bin_dir.join(entry.file_name()), &bin_dir)
            {
                found = Some(resolved);
                break;
            }
        }
        found.ok_or_else(|| {
            "Pinned npm install produced no runnable binary in node_modules/.bin.".into()
        })
    }
}

async fn install_pinned_uv(
    spec: &RegistryInstallSpec,
    target_dir: &Path,
) -> Result<PathBuf, String> {
    let empty_cwd = platform::private_tempdir_in("acp-uv-", &platform::temporary_directory())
        .map_err(|e| e.to_string())?;
    let venv_dir = target_dir.join("venv");
    let create = process::Command {
        program: OsString::from("uv"),
        args: vec![OsString::from("venv"), venv_dir.as_os_str().to_owned()],
        cwd: empty_cwd.path().to_path_buf(),
        env: platform::environment::for_command(),
        timeout: Duration::from_secs(60),
    };
    let created = process::run(create, CancellationToken::new(), |_| async { Ok(()) })
        .await
        .map_err(|error| format!("Cannot create pinned uv venv: {error}."))?;
    if !created.status.success() {
        return Err(format!(
            "uv venv failed: {}",
            platform::output_text(&created.stderr).trim()
        ));
    }
    let mut args = vec![
        OsString::from("pip"),
        OsString::from("install"),
        OsString::from("--python"),
        venv_dir.as_os_str().to_owned(),
    ];
    if !spec.build_scripts_allowed {
        args.push(OsString::from("--only-binary=:all:"));
    }
    args.push(OsString::from(format!(
        "{}=={}",
        spec.package_or_url, spec.exact_version
    )));
    let install = process::Command {
        program: OsString::from("uv"),
        args,
        cwd: empty_cwd.path().to_path_buf(),
        env: platform::environment::for_command(),
        timeout: Duration::from_secs(120),
    };
    let installed = process::run(install, CancellationToken::new(), |_| async { Ok(()) })
        .await
        .map_err(|error| format!("Pinned uv install failed: {error}."))?;
    if !installed.status.success() {
        return Err(format!(
            "Pinned uv install failed: {}",
            platform::output_text(&installed.stderr).trim()
        ));
    }
    let bin_dir = platform::venv_bin_dir(&venv_dir);
    platform::program::resolve(&bin_dir.join(spec.registry_id.as_str()), &bin_dir).map_err(|_| {
        "Pinned uv install produced no runnable entrypoint in the isolated venv.".into()
    })
}

/// Reject symlinks and reparse points anywhere inside a pinned runtime directory.
fn verify_tree_no_links(root: &Path) -> Result<(), String> {
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let handle = platform::open_directory(&dir).map_err(|e| e.to_string())?;
        for entry in platform::read_dir(&handle).map_err(|e| e.to_string())? {
            let entry = entry.map_err(|e| e.to_string())?;
            let child = dir.join(entry.file_name());
            match entry.file_type().map_err(|e| e.to_string())? {
                platform::FileKind::Directory => stack.push(child),
                platform::FileKind::File => {}
                platform::FileKind::Symlink | platform::FileKind::Other => {
                    return Err(format!(
                        "Refusing symlink or special file {} inside pinned ACP runtime.",
                        platform::path_text(&child)
                    ));
                }
            }
        }
    }
    Ok(())
}

fn hex_sha256(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let digest = Sha256::digest(bytes);
    let mut out = String::with_capacity(64);
    for &byte in digest.as_slice() {
        out.push(HEX[(byte >> 4) as usize] as char);
        out.push(HEX[(byte & 0x0f) as usize] as char);
    }
    out
}

fn current_platform_key() -> &'static str {
    platform::registry_platform()
}

#[derive(Deserialize)]
struct RawRegistryFeed {
    #[serde(default)]
    agents: Vec<RawRegistryAgent>,
}

#[derive(Deserialize)]
struct RawRegistryAgent {
    id: String,
    name: String,
    version: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    distribution: RawDistribution,
}

#[derive(Default, Deserialize)]
struct RawDistribution {
    #[serde(default)]
    binary: BTreeMap<String, RawBinaryTarget>,
    #[serde(default)]
    npx: Option<RawPackageTarget>,
    #[serde(default)]
    uvx: Option<RawPackageTarget>,
}

#[derive(Deserialize)]
struct RawBinaryTarget {
    archive: String,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    env: BTreeMap<String, String>,
    #[serde(default)]
    sha256: Option<String>,
}

#[derive(Deserialize)]
struct RawPackageTarget {
    package: String,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    env: BTreeMap<String, String>,
}

fn resolve_registry_spec(
    id: &AgentId,
    item: &RawRegistryAgent,
    platform_key: &str,
) -> Option<RegistryInstallSpec> {
    if let Some(bin) = item.distribution.binary.get(platform_key) {
        return Some(RegistryInstallSpec {
            registry_id: id.clone(),
            display_name: item.name.clone(),
            exact_version: item.version.clone(),
            platform: platform_key.to_owned(),
            distribution_kind: if bin.archive.ends_with(".tar.gz")
                || bin.archive.ends_with(".zip")
                || bin.archive.ends_with(".tgz")
            {
                DistributionKind::Archive
            } else {
                DistributionKind::Binary
            },
            package_or_url: bin.archive.clone(),
            args: bin.args.clone(),
            env_pairs: bin.env.clone(),
            build_scripts_allowed: false,
            artifact_sha256: bin.sha256.clone(),
            allow_unsigned_digest: false,
        });
    }
    if let Some(npx) = &item.distribution.npx {
        return Some(RegistryInstallSpec {
            registry_id: id.clone(),
            display_name: item.name.clone(),
            exact_version: item.version.clone(),
            platform: platform_key.to_owned(),
            distribution_kind: DistributionKind::Npx,
            package_or_url: npx.package.clone(),
            args: npx.args.clone(),
            env_pairs: npx.env.clone(),
            build_scripts_allowed: false,
            artifact_sha256: None,
            allow_unsigned_digest: false,
        });
    }
    if let Some(uvx) = &item.distribution.uvx {
        return Some(RegistryInstallSpec {
            registry_id: id.clone(),
            display_name: item.name.clone(),
            exact_version: item.version.clone(),
            platform: platform_key.to_owned(),
            distribution_kind: DistributionKind::Uvx,
            package_or_url: uvx.package.clone(),
            args: uvx.args.clone(),
            env_pairs: uvx.env.clone(),
            build_scripts_allowed: false,
            artifact_sha256: None,
            allow_unsigned_digest: false,
        });
    }
    None
}

/// Helper to read the executable's launcher fingerprint for an agent spec.
pub fn compute_launcher_fingerprint(
    spec: &AgentSpec,
    worktree: &Path,
) -> Result<LauncherFingerprint, String> {
    let resolved = trust::resolve_executable(
        &spec.program,
        Some(worktree),
        spec.reject_worktree_executable,
    )?;
    LauncherFingerprint::compute(&resolved, &spec.args)
}

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

    #[tokio::test]
    async fn custom_agent_roundtrip_stores_secrets_separately_and_blocks_preset_shadowing() {
        let root = crate::test_os::tempdir();
        let state = root.path().join("state");
        let worktree = root.path().join("work");
        std::fs::create_dir_all(&worktree).unwrap();

        let shadow = CustomAgent {
            id: "antigravity".parse().unwrap(),
            name: "Shadow".into(),
            command: "fake".into(),
            args: Vec::new(),
            env: BTreeMap::new(),
            secret_env_keys: Vec::new(),
            mcp_stdio: true,
            registry: None,
            entrypoint_sha256: None,
        };
        assert!(
            save_custom_agent(Some(&state), Some(&worktree), shadow, BTreeMap::new(), &[])
                .await
                .is_err()
        );

        let custom = CustomAgent {
            id: "my-acp".parse().unwrap(),
            name: "My ACP".into(),
            command: "my-acp-bin".into(),
            args: vec!["--stdio".into()],
            env: BTreeMap::from([("PLAIN_FLAG".into(), "1".into())]),
            secret_env_keys: Vec::new(),
            mcp_stdio: true,
            registry: None,
            entrypoint_sha256: None,
        };
        let mut secrets = BTreeMap::new();
        secrets.insert(
            "MY_SECRET".into(),
            SecretEnvValue::parse("top-secret-value-999").unwrap(),
        );
        let saved = save_custom_agent(Some(&state), Some(&worktree), custom, secrets, &[])
            .await
            .unwrap();
        assert_eq!(saved.secret_env_keys, vec!["MY_SECRET".to_owned()]);

        // agents.json must never contain the secret value.
        let agents_json = std::fs::read_to_string(state.join("chat/agents.json")).unwrap();
        assert!(!agents_json.contains("top-secret-value-999"));
        assert!(agents_json.contains("MY_SECRET"));

        let spec = resolve_spec(&saved.id, Some(&state), Some(&worktree)).unwrap();
        assert_eq!(
            spec.known_secrets(),
            vec!["top-secret-value-999".to_owned()]
        );
        assert!(is_chat_agent("my-acp", Some(&state), Some(&worktree)));

        assert!(
            remove_custom_agent(Some(&state), Some(&worktree), &saved.id)
                .await
                .unwrap()
        );
        assert!(!is_chat_agent("my-acp", Some(&state), Some(&worktree)));
    }
}