github-copilot-sdk 1.0.32-preview.2

Rust SDK for programmatic control of the GitHub Copilot CLI via JSON-RPC.
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
// Copyright (c) Microsoft Corporation. All rights reserved.

//! Lazy runtime installer for the CLI binary that build.rs embedded in this
//! crate (gated on the `bundled-cli` cargo feature, which is in the default
//! feature set).
//!
//! Builds embed two platform release payloads from GitHub Releases: the full
//! CLI archive and a filtered runtime archive containing the wrapper,
//! `runtime.node`, auxiliary runtime assets, and optionally the in-process
//! runtime library. Extraction to a real on-disk path is deferred until the
//! relevant installer is called.
//!
//! The embedded bytes are part of the consumer's signed binary and therefore
//! trusted *as the source of truth* — but the bytes that land on disk are not.
//! A non-atomic write, a multi-process race, or antivirus quarantining the
//! freshly-written executable can leave a truncated or corrupt image that, if
//! handed back as "good", fails to launch (e.g. Windows `ERROR_BAD_EXE_FORMAT`).
//! Full CLI installation therefore: extracts to a unique temp file in the target dir,
//! fsyncs and marks it executable, verifies the staged bytes against the
//! trusted in-memory image, atomically publishes it in place without replacing
//! an identical binary another process already published, re-verifies the
//! published file, and records an integrity marker. Subsequent runs trust an
//! existing install only after a cheap re-check (size marker + executable-image
//! header); anything that looks truncated or quarantined is re-extracted, and
//! the whole publish is retried before surfacing a clear, actionable error.
//!
//! Runtime assets are compared and extracted with bounded buffers rather than
//! whole-file allocations. Matching files need only read access and retain
//! their installed permissions, provided the wrapper remains executable by
//! the current process. Changed files are staged beside their targets and
//! published after archive validation, including the gzip trailer.
//! Installation is atomic per file, not across the entire runtime bundle.

// The atomic-publish + verify helpers (and their unit tests) are pure
// std-only logic that doesn't touch the embedded archive, so they compile
// whenever the binary is bundled *or* we're building the test harness —
// the standard `cargo test --no-default-features` job has `has_bundled_cli`
// off but still needs to exercise them.
#[cfg(any(has_bundled_cli, test))]
use std::collections::BTreeMap;
#[cfg(has_bundled_cli)]
use std::collections::HashSet;
#[cfg(any(has_bundled_cli, test))]
use std::fs;
#[cfg(has_bundled_cli)]
use std::io::Read;
#[cfg(any(has_bundled_cli, test))]
use std::io::Write;
use std::path::{Path, PathBuf};
#[cfg(any(has_bundled_cli, test))]
use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(any(has_bundled_cli, test))]
use std::sync::{Arc, Mutex};
#[cfg(any(has_bundled_cli, test))]
use std::time::{Duration, Instant};

#[cfg(has_bundled_cli)]
use tracing::{info, warn};

// When the `bundled-cli` cargo feature is enabled and the target platform is
// supported, build.rs generates `bundled_cli.rs` exposing both selected archives.
// The CLI version is exposed crate-wide via the
// `cargo:rustc-env=COPILOT_SDK_CLI_VERSION` emit (see `build.rs`), and the
// release-scoped cache identity is emitted separately to avoid destination
// collisions. The binary name is OS-derived.
#[cfg(has_bundled_cli)]
mod build_time {
    include!(concat!(env!("OUT_DIR"), "/bundled_cli.rs"));
}

// Keep the actual version for diagnostics and a release-scoped identity for
// cache paths. Legacy releases use the version unchanged for both.
#[cfg(has_bundled_cli)]
const CLI_VERSION: &str = env!("COPILOT_SDK_CLI_VERSION");
#[cfg(has_bundled_cli)]
const CLI_CACHE_ID: &str = env!("COPILOT_SDK_CLI_CACHE_ID");

// OS-derived; matches the release-archive entry name and the on-disk
// filename. No need to bake this — `cfg(windows)` reflects the target
// the runtime is running on, which by definition is the same target
// build.rs targeted.
#[cfg(all(has_bundled_cli, windows))]
const CLI_BINARY_NAME: &str = "copilot.exe";
#[cfg(all(has_bundled_cli, not(windows)))]
const CLI_BINARY_NAME: &str = "copilot";
#[cfg(all(has_bundled_cli, windows))]
const RUNTIME_BINARY_NAME: &str = "copilot-runtime.exe";
#[cfg(all(has_bundled_cli, not(windows)))]
const RUNTIME_BINARY_NAME: &str = "copilot-runtime";
#[cfg(has_bundled_cli)]
const RUNTIME_NODE_NAME: &str = "runtime.node";
#[cfg(any(has_bundled_cli, test))]
const RUNTIME_VERSION_MARKER: &str = ".copilot-runtime-version";
/// How long an installer waits for another installer to finish writing the
/// version marker it has just created.
#[cfg(any(has_bundled_cli, test))]
const RUNTIME_VERSION_MARKER_WAIT: Duration = Duration::from_secs(1);

#[cfg(has_bundled_cli)]
static INSTALLED_PATH: Mutex<Option<PathBuf>> = Mutex::new(None);
#[cfg(has_bundled_cli)]
static INSTALLED_RUNTIME_PATH: Mutex<Option<PathBuf>> = Mutex::new(None);
#[cfg(has_bundled_cli)]
static CLI_INSTALLS_AT: DirInstalls = Mutex::new(BTreeMap::new());
#[cfg(has_bundled_cli)]
static RUNTIME_INSTALLS_AT: DirInstalls = Mutex::new(BTreeMap::new());

/// Installs into caller-chosen directories, keyed by directory.
#[cfg(any(has_bundled_cli, test))]
type DirInstalls = Mutex<BTreeMap<PathBuf, Arc<DirInstall>>>;

/// Installs into one caller-chosen directory within this process.
#[cfg(any(has_bundled_cli, test))]
#[derive(Default)]
struct DirInstall {
    /// Number of installs into the directory that have finished.
    finished: AtomicU64,
    /// Held while an install runs; the path the last one returned, if it
    /// succeeded.
    published: Mutex<Option<PathBuf>>,
}

#[cfg(any(has_bundled_cli, test))]
struct DirInstallGuard<'a> {
    installs: &'a DirInstalls,
    key: PathBuf,
    entry: Arc<DirInstall>,
}

#[cfg(any(has_bundled_cli, test))]
impl Drop for DirInstallGuard<'_> {
    fn drop(&mut self) {
        let mut installs = self
            .installs
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if installs
            .get(&self.key)
            .is_some_and(|entry| Arc::ptr_eq(entry, &self.entry))
            && Arc::strong_count(&self.entry) == 2
        {
            // Only the registry and this last caller still own the entry.
            installs.remove(&self.key);
        }
    }
}

#[cfg(any(has_bundled_cli, test))]
impl DirInstall {
    fn for_dir<'a>(installs: &'a DirInstalls, dir: &Path) -> DirInstallGuard<'a> {
        // The install creates the directory anyway; creating it first lets
        // every spelling of the same directory resolve to one key.
        let _ = fs::create_dir_all(dir);
        let key = fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
        let entry = installs
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .entry(key.clone())
            .or_default()
            .clone();
        DirInstallGuard {
            installs,
            key,
            entry,
        }
    }

    /// Runs `install`, one at a time per directory. A caller that read
    /// `finished` as `arrived` and then waited for an install that succeeded
    /// takes that install's path instead of staging another copy; a caller
    /// that arrives after it runs `install` itself, so the installed files
    /// are still re-checked on every later call.
    fn run(
        &self,
        arrived: u64,
        install: impl FnOnce() -> Result<PathBuf, crate::Error>,
    ) -> Result<PathBuf, crate::Error> {
        let mut published = self
            .published
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if self.finished.load(Ordering::Acquire) != arrived
            && let Some(path) = published.as_ref()
        {
            return Ok(path.clone());
        }
        let result = install().and_then(|path| std::path::absolute(path).map_err(Into::into));
        *published = result.as_ref().ok().cloned();
        self.finished.fetch_add(1, Ordering::Release);
        result
    }
}

/// Runs `install` for `dir`, letting callers that start together on one
/// directory share a single install. See [`DirInstall::run`].
#[cfg(any(has_bundled_cli, test))]
fn install_once_at(
    installs: &DirInstalls,
    dir: &Path,
    install: impl FnOnce() -> Result<PathBuf, crate::Error>,
) -> Result<PathBuf, crate::Error> {
    let entry = DirInstall::for_dir(installs, dir);
    let arrived = entry.entry.finished.load(Ordering::Acquire);
    entry.entry.run(arrived, install)
}

/// Installs at most once per process at a time and remembers only a
/// successful install, so a failure reaches the caller and a later call
/// retries once the environment has been corrected.
#[cfg(any(has_bundled_cli, test))]
fn cached_install(
    cache: &Mutex<Option<PathBuf>>,
    select_dir: impl FnOnce() -> Result<PathBuf, crate::ErrorKind>,
    install: impl FnOnce(&Path) -> Result<PathBuf, crate::Error>,
) -> Result<PathBuf, crate::Error> {
    let mut installed = cache
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some(path) = installed.as_ref() {
        return Ok(path.clone());
    }
    let dir = select_dir()?;
    let path = install(&dir)?;
    *installed = Some(path.clone());
    Ok(path)
}

/// Reports an embedded artifact that could not be written to `dir`, keeping
/// the directory and the underlying I/O error for the caller.
#[cfg(any(has_bundled_cli, test))]
fn install_failed(binary_name: &str, dir: &Path, error: &EmbeddedCliError) -> crate::Error {
    crate::ErrorKind::BinaryNotFound {
        name: binary_name.into(),
        hint: Some(format!(
            "the bundled Copilot CLI could not be installed in '{}': {error}",
            dir.display()
        )),
    }
    .into()
}

/// Returns the path to the installed CLI binary, lazily extracting the
/// embedded archive on first call.
///
/// On first call this extracts the embedded archive to
/// `<platform cache dir>/github-copilot-sdk/cli/<version>/copilot[.exe]`
/// and returns the resulting path. The cache dir comes from
/// the OS's LocalAppData known folder on Windows,
/// `~/Library/Caches/` on macOS, `$XDG_CACHE_HOME` (or `~/.cache/`) on
/// Linux. If unavailable, Unix uses an owner-only cache under the trusted
/// temporary base; other platforms use their existing temporary directory.
/// Subsequent calls return the cached path. Extraction
/// is skipped when a previously-published binary is still present and
/// passes a cheap integrity re-check (size marker + executable-image
/// header); a truncated, empty, or quarantined binary is re-extracted
/// rather than returned. A failed installation is returned as an error and
/// is not cached, so a later call retries it.
///
/// Returns `None` if no CLI was embedded at build time.
#[cfg(feature = "bundled-cli")]
pub(crate) fn path() -> Result<Option<PathBuf>, crate::Error> {
    #[cfg(has_bundled_cli)]
    {
        cached_install(
            &INSTALLED_PATH,
            || {
                default_install_dir(CLI_CACHE_ID).map_err(|error| {
                    crate::ErrorKind::BinaryNotFound {
                        name: CLI_BINARY_NAME.into(),
                        hint: Some(error.to_string()),
                    }
                })
            },
            try_install_cli,
        )
        .map(Some)
    }
    #[cfg(not(has_bundled_cli))]
    {
        Ok(None)
    }
}

/// Install the embedded CLI binary into the given directory instead of the
/// default `<platform cache dir>/github-copilot-sdk/cli/<version>/` location
/// (see [`path`] for the per-platform mapping).
///
/// Idempotent: skips extraction when an already-published binary passes the
/// integrity re-check (size marker + executable-image header), and
/// re-extracts a corrupt or quarantined one. Callers in this process that
/// start together on the same directory share one installation.
/// Returns `None` when the SDK was built without a bundled CLI, and an error
/// naming the directory when installation fails.
#[cfg(feature = "bundled-cli")]
#[allow(dead_code)] // Used by resolve.rs when ClientOptions::bundled_cli_extract_dir is set.
pub(crate) fn install_at(extract_dir: &Path) -> Result<Option<PathBuf>, crate::Error> {
    #[cfg(has_bundled_cli)]
    {
        install_once_at(&CLI_INSTALLS_AT, extract_dir, || {
            try_install_cli(extract_dir)
        })
        .map(Some)
    }
    #[cfg(not(has_bundled_cli))]
    {
        let _ = extract_dir;
        Ok(None)
    }
}

#[cfg(has_bundled_cli)]
fn try_install_cli(dir: &Path) -> Result<PathBuf, crate::Error> {
    let path = install_cli(dir, build_time::CLI_ARCHIVE, build_time::CLI_BINARY_SIZE)
        .map_err(|error| install_failed(CLI_BINARY_NAME, dir, &error))?;
    info!(path = %path.display(), version = CLI_VERSION, "embedded CLI installed");
    Ok(path)
}

/// Returns the path to the bundled runtime wrapper, extracting the wrapper and
/// adjacent `runtime.node` on first call. A failed installation is returned
/// as an error and is not cached, so a later call retries it.
#[cfg(feature = "bundled-cli")]
pub(crate) fn runtime_path() -> Result<Option<PathBuf>, crate::Error> {
    #[cfg(has_bundled_cli)]
    {
        cached_install(
            &INSTALLED_RUNTIME_PATH,
            || {
                default_install_dir(CLI_CACHE_ID).map_err(|error| {
                    crate::ErrorKind::BinaryNotFound {
                        name: RUNTIME_BINARY_NAME.into(),
                        hint: Some(error.to_string()),
                    }
                })
            },
            try_install_runtime,
        )
        .map(Some)
    }
    #[cfg(not(has_bundled_cli))]
    {
        Ok(None)
    }
}

/// Installs the bundled runtime wrapper and adjacent `runtime.node` into a
/// caller-specified directory. Callers in this process that start together
/// on the same directory share one installation. Returns `None` when the SDK
/// was built without a bundled CLI, and an error naming the directory when
/// installation fails.
#[cfg(feature = "bundled-cli")]
pub(crate) fn install_runtime_at(extract_dir: &Path) -> Result<Option<PathBuf>, crate::Error> {
    #[cfg(has_bundled_cli)]
    {
        install_once_at(&RUNTIME_INSTALLS_AT, extract_dir, || {
            let install_dir = runtime_install_dir(extract_dir, CLI_CACHE_ID)
                .map_err(|error| install_failed(RUNTIME_BINARY_NAME, extract_dir, &error))?;
            try_install_runtime(&install_dir)
        })
        .map(Some)
    }
    #[cfg(not(has_bundled_cli))]
    {
        let _ = extract_dir;
        Ok(None)
    }
}

#[cfg(has_bundled_cli)]
fn try_install_runtime(dir: &Path) -> Result<PathBuf, crate::Error> {
    let path = install_runtime(dir, build_time::RUNTIME_ARCHIVE)
        .map_err(|error| install_failed(RUNTIME_BINARY_NAME, dir, &error))?;
    info!(path = %path.display(), version = CLI_VERSION, "embedded runtime installed");
    Ok(path)
}

/// Selects the directory the runtime for `version` is installed in: `base_dir`
/// when it is unclaimed or already holds `version`, and `base_dir/<version>`
/// when another version claimed it first.
#[cfg(any(has_bundled_cli, test))]
fn runtime_install_dir(base_dir: &Path, version: &str) -> Result<PathBuf, EmbeddedCliError> {
    runtime_install_dir_within(base_dir, version, RUNTIME_VERSION_MARKER_WAIT)
}

/// [`runtime_install_dir`] with an explicit wait budget, so a test can make the
/// wait independent of how the machine schedules its threads.
#[cfg(any(has_bundled_cli, test))]
fn runtime_install_dir_within(
    base_dir: &Path,
    version: &str,
    wait: Duration,
) -> Result<PathBuf, EmbeddedCliError> {
    fs::create_dir_all(base_dir)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::CreateDir, e))?;
    let deadline = Instant::now() + wait;
    loop {
        if let Some(dir) = try_runtime_install_dir(base_dir, version)? {
            return Ok(dir);
        }
        if runtime_marker_is_stale(&base_dir.join(RUNTIME_VERSION_MARKER), wait)
            || Instant::now() >= deadline
        {
            return Ok(base_dir.join(version));
        }
        std::thread::sleep(Duration::from_millis(5));
    }
}

/// One claim attempt. An empty or withdrawn marker needs another observation.
#[cfg(any(has_bundled_cli, test))]
fn try_runtime_install_dir(
    base_dir: &Path,
    version: &str,
) -> Result<Option<PathBuf>, EmbeddedCliError> {
    let marker = base_dir.join(RUNTIME_VERSION_MARKER);
    match fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&marker)
    {
        Ok(mut file) => {
            if let Err(error) = file
                .write_all(version.as_bytes())
                .and_then(|()| file.sync_all())
            {
                drop(file);
                let _ = fs::remove_file(&marker);
                return Err(EmbeddedCliError::new(EmbeddedCliErrorKind::Io, error));
            }
            Ok(Some(base_dir.to_path_buf()))
        }
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
            match fs::read_to_string(&marker) {
                Ok(installed) if !installed.is_empty() || version.is_empty() => {
                    Ok(Some(if installed == version {
                        base_dir.to_path_buf()
                    } else {
                        base_dir.join(version)
                    }))
                }
                Ok(_) => Ok(None),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
                Err(_) => Ok(Some(base_dir.join(version))),
            }
        }
        Err(error) => Err(EmbeddedCliError::new(EmbeddedCliErrorKind::Io, error)),
    }
}

#[cfg(any(has_bundled_cli, test))]
fn runtime_marker_is_stale(marker: &Path, wait: Duration) -> bool {
    // Reuse the same wait budget across calls for markers left by a crashed
    // writer. Unknown timestamps retain the bounded wait for live writers.
    fs::metadata(marker)
        .and_then(|metadata| metadata.modified())
        .ok()
        .and_then(|modified| modified.elapsed().ok())
        .is_some_and(|age| age >= wait)
}

#[cfg(has_bundled_cli)]
fn default_install_dir(version: &str) -> std::io::Result<PathBuf> {
    Ok(crate::cache_paths::cache_install_dir(
        &crate::cache_paths::platform_cache_root()?,
        "cli",
        if version.is_empty() {
            "unversioned"
        } else {
            version
        },
    ))
}

/// Number of times we re-extract + re-publish the binary before giving up.
/// A single transient failure (e.g. antivirus briefly locking or quarantining
/// the freshly-written file) is retried; a persistent one surfaces a clear
/// error rather than handing back a broken path.
#[cfg(has_bundled_cli)]
const MAX_PUBLISH_ATTEMPTS: u32 = 3;

// Natural platform shared-library name for the in-process FFI runtime.
#[cfg(all(has_bundled_cli, feature = "in-process", windows))]
const RUNTIME_LIBRARY_NAME: &str = "copilot_runtime.dll";
#[cfg(all(has_bundled_cli, feature = "in-process", target_os = "macos"))]
const RUNTIME_LIBRARY_NAME: &str = "libcopilot_runtime.dylib";
#[cfg(all(
    has_bundled_cli,
    feature = "in-process",
    not(windows),
    not(target_os = "macos")
))]
const RUNTIME_LIBRARY_NAME: &str = "libcopilot_runtime.so";

#[cfg(has_bundled_cli)]
fn install_runtime(install_dir: &Path, archive: &[u8]) -> Result<PathBuf, EmbeddedCliError> {
    fs::create_dir_all(install_dir)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::CreateDir, e))?;
    let root = fs::canonicalize(install_dir)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e))?;
    let mut required = vec![RUNTIME_BINARY_NAME, RUNTIME_NODE_NAME];
    #[cfg(feature = "in-process")]
    required.push(RUNTIME_LIBRARY_NAME);
    let mut seen = HashSet::new();
    let mut changed = HashSet::new();
    let mut pending = Vec::new();
    let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(archive));
    for entry in tar
        .entries()
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?
    {
        let mut entry =
            entry.map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
        if !entry.header().entry_type().is_file() {
            continue;
        }
        let path = entry
            .path()
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
        let path = runtime_asset_path(&path)?;
        if !seen.insert(path.as_os_str().to_ascii_lowercase()) {
            return Err(EmbeddedCliError::with_message(
                EmbeddedCliErrorKind::Archive,
                format!("duplicate embedded runtime asset path: {}", path.display()),
            ));
        }
        if !selected_runtime_asset(&path) {
            continue;
        }
        if let Some(index) = required.iter().position(|name| path == Path::new(name)) {
            if entry.size() == 0 {
                return Err(EmbeddedCliError::with_message(
                    EmbeddedCliErrorKind::Verification,
                    format!("embedded runtime artifact is empty: {}", path.display()),
                ));
            }
            required.remove(index);
        }
        let target = root.join(&path);
        let parent = target.parent().ok_or_else(|| {
            EmbeddedCliError::with_message(
                EmbeddedCliErrorKind::Archive,
                format!("embedded runtime asset has no parent: {}", path.display()),
            )
        })?;
        check_runtime_asset_parent(&root, parent, false)?;
        match existing_runtime_file(&target, entry.size())? {
            Some(mut installed) => {
                let matches = runtime_entry_matches(&mut entry, &mut installed)?;
                #[cfg(unix)]
                let matches = matches
                    && (path != Path::new(RUNTIME_BINARY_NAME)
                        || check_runtime_wrapper_execute_access(&target).is_ok());
                if !matches {
                    changed.insert(path);
                }
            }
            None => {
                check_runtime_asset_parent(&root, parent, true)?;
                pending.push(stage_runtime_entry(&mut entry, &target)?);
            }
        }
    }
    // TAR's end marker can precede gzip's CRC and size trailer.
    std::io::copy(&mut tar.into_inner(), &mut std::io::sink())
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
    if !required.is_empty() {
        return Err(EmbeddedCliErrorKind::BinaryNotFoundInArchive.into());
    }
    // Recover bytes consumed by failed comparisons without retaining their
    // prefixes in memory. Cold installs and valid warm caches need one pass.
    if !changed.is_empty() {
        let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(archive));
        for entry in tar
            .entries()
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?
        {
            let mut entry =
                entry.map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
            if !entry.header().entry_type().is_file() {
                continue;
            }
            let path = entry
                .path()
                .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
            let path = runtime_asset_path(&path)?;
            if changed.contains(&path) {
                pending.push(stage_runtime_entry(&mut entry, &root.join(path))?);
            }
        }
        std::io::copy(&mut tar.into_inner(), &mut std::io::sink())
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
    }
    for staged in pending {
        publish_staged(
            &staged.temporary,
            &staged.target,
            staged.target == root.join(RUNTIME_BINARY_NAME),
        )?;
    }
    #[cfg(unix)]
    check_runtime_wrapper_execute_access(&root.join(RUNTIME_BINARY_NAME))
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Verification, e))?;
    Ok(install_dir.join(RUNTIME_BINARY_NAME))
}

#[cfg(all(any(has_bundled_cli, test), unix))]
fn check_runtime_wrapper_execute_access(path: &Path) -> std::io::Result<()> {
    use std::ffi::{CString, c_char, c_int};
    use std::os::unix::ffi::OsStrExt;

    // std has no effective-credentials access check. Bind the POSIX libc API,
    // not a raw syscall: libc handles Linux kernel differences (glibc/musl).
    // These <fcntl.h>/<unistd.h> constants are shared by each OS's supported
    // x86_64 and aarch64 targets; macOS uses different AT_* values than Linux.
    #[cfg(target_os = "linux")]
    const AT_FDCWD: c_int = -100;
    #[cfg(target_os = "macos")]
    const AT_FDCWD: c_int = -2;
    #[cfg(target_os = "linux")]
    const AT_EACCESS: c_int = 0x200;
    #[cfg(target_os = "macos")]
    const AT_EACCESS: c_int = 0x10;
    const X_OK: c_int = 1;
    unsafe extern "C" {
        fn faccessat(dirfd: c_int, path: *const c_char, mode: c_int, flags: c_int) -> c_int;
    }

    let path = CString::new(path.as_os_str().as_bytes())
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
    // SAFETY: path is NUL-terminated and lives through the call. faccessat
    // only reads it and uses the platform's C integer ABI and flag values.
    if unsafe { faccessat(AT_FDCWD, path.as_ptr(), X_OK, AT_EACCESS) } == 0 {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

#[cfg(has_bundled_cli)]
fn selected_runtime_asset(path: &Path) -> bool {
    if path == Path::new(CLI_BINARY_NAME) {
        return false;
    }
    if matches!(
        path.file_name().and_then(|name| name.to_str()),
        Some("copilot_runtime.dll" | "libcopilot_runtime.dylib" | "libcopilot_runtime.so")
    ) {
        #[cfg(feature = "in-process")]
        return path == Path::new(RUNTIME_LIBRARY_NAME);
        #[cfg(not(feature = "in-process"))]
        return false;
    }
    true
}

#[cfg(has_bundled_cli)]
fn runtime_asset_path(path: &Path) -> Result<PathBuf, EmbeddedCliError> {
    let invalid = || {
        EmbeddedCliError::with_message(
            EmbeddedCliErrorKind::Archive,
            format!(
                "non-portable embedded runtime asset path: {}",
                path.display()
            ),
        )
    };
    // Bundled release assets use ASCII names. Apply the same conservative
    // naming rules on every filesystem, without probing a read-only cache.
    // Reject Unicode, DOS device/short names and trailing-dot/space aliases
    // rather than approximating platform-specific Unicode normalization.
    let name = path
        .to_str()
        .filter(|name| name.is_ascii())
        .ok_or_else(invalid)?;
    if name.starts_with(['/', '\\']) {
        return Err(invalid());
    }
    let mut normalized = PathBuf::new();
    for component in name.split(['/', '\\']) {
        if component.is_empty() || component == "." {
            continue;
        }
        if component == ".."
            || component.ends_with(['.', ' '])
            || component
                .bytes()
                .any(|byte| byte.is_ascii_control() || b"<>:\"|?*~".contains(&byte))
        {
            return Err(invalid());
        }
        let stem = component
            .split('.')
            .next()
            .expect("nonempty component")
            .trim_end_matches(' ')
            .to_ascii_uppercase();
        if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
            || (stem.len() == 4
                && (stem.starts_with("COM") || stem.starts_with("LPT"))
                && matches!(stem.as_bytes()[3], b'1'..=b'9'))
        {
            return Err(invalid());
        }
        normalized.push(component);
    }
    if normalized.as_os_str().is_empty() {
        return Err(invalid());
    }
    Ok(normalized)
}

#[cfg(has_bundled_cli)]
fn check_runtime_asset_parent(
    root: &Path,
    parent: &Path,
    create: bool,
) -> Result<(), EmbeddedCliError> {
    let mut current = root.to_path_buf();
    for component in parent
        .strip_prefix(root)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?
        .components()
    {
        current.push(component);
        if create {
            match fs::create_dir(&current) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
                Err(e) => return Err(EmbeddedCliError::new(EmbeddedCliErrorKind::CreateDir, e)),
            }
        }
        let metadata = match fs::symlink_metadata(&current) {
            Ok(metadata) => metadata,
            Err(e) if !create && e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(e) => return Err(EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e)),
        };
        if !metadata.is_dir() {
            return Err(EmbeddedCliError::with_message(
                EmbeddedCliErrorKind::Verification,
                format!(
                    "runtime asset parent is not a directory: {}",
                    current.display()
                ),
            ));
        }
    }
    Ok(())
}

#[cfg(has_bundled_cli)]
struct StagedRuntimeFile {
    temporary: PathBuf,
    target: PathBuf,
}

#[cfg(has_bundled_cli)]
impl Drop for StagedRuntimeFile {
    fn drop(&mut self) {
        if let Err(error) = fs::remove_file(&self.temporary)
            && error.kind() != std::io::ErrorKind::NotFound
        {
            warn!(path = %self.temporary.display(), %error, "failed to remove staged runtime asset");
        }
    }
}

#[cfg(has_bundled_cli)]
fn existing_runtime_file(target: &Path, size: u64) -> Result<Option<fs::File>, EmbeddedCliError> {
    let metadata = match fs::symlink_metadata(target) {
        Ok(metadata) if metadata.is_file() => Some(metadata),
        Ok(_) => {
            return Err(EmbeddedCliError::with_message(
                EmbeddedCliErrorKind::Verification,
                format!("runtime asset is not a regular file: {}", target.display()),
            ));
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e)),
    };
    let matches = metadata
        .as_ref()
        .is_some_and(|metadata| metadata.len() == size);
    if matches {
        match fs::File::open(target) {
            Ok(file) => return Ok(Some(file)),
            Err(e) => {
                tracing::debug!(path = %target.display(), error = %e,
                    "existing runtime asset cannot be read; repairing");
            }
        }
    }
    Ok(None)
}

#[cfg(has_bundled_cli)]
fn runtime_entry_matches<R: Read>(
    entry: &mut tar::Entry<'_, R>,
    installed: &mut fs::File,
) -> Result<bool, EmbeddedCliError> {
    let mut buffer = [0u8; 64 * 1024];
    let mut on_disk = [0u8; 64 * 1024];
    let mut remaining = entry.size();
    while remaining > 0 {
        let length = remaining.min(buffer.len() as u64) as usize;
        entry
            .read_exact(&mut buffer[..length])
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
        remaining -= length as u64;
        if let Err(error) = installed.read_exact(&mut on_disk[..length]) {
            tracing::debug!(%error, "existing runtime asset cannot be read; repairing");
            return Ok(false);
        }
        if on_disk[..length] != buffer[..length] {
            return Ok(false);
        }
    }
    match installed.read(&mut on_disk[..1]) {
        Ok(read) => Ok(read == 0),
        Err(error) => {
            tracing::debug!(%error, "existing runtime asset cannot be read; repairing");
            Ok(false)
        }
    }
}

#[cfg(has_bundled_cli)]
fn stage_runtime_entry<R: Read>(
    entry: &mut tar::Entry<'_, R>,
    target: &Path,
) -> Result<StagedRuntimeFile, EmbeddedCliError> {
    let parent = target.parent().expect("runtime asset has a checked parent");
    let (temporary, mut file) = create_temp_file(parent)?;
    let staged = StagedRuntimeFile {
        temporary,
        target: target.to_path_buf(),
    };
    let result = write_runtime_entry(entry, &mut file);
    // Close handles before cleanup or replacement, including on Windows.
    drop(file);
    result?;
    Ok(staged)
}

#[cfg(has_bundled_cli)]
fn write_runtime_entry<R: Read>(
    entry: &mut tar::Entry<'_, R>,
    file: &mut fs::File,
) -> Result<(), EmbeddedCliError> {
    let size = entry.size();
    let written = std::io::copy(&mut (&mut *entry).take(size), &mut *file)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e))?;
    if written != size {
        return Err(EmbeddedCliError::with_message(
            EmbeddedCliErrorKind::Verification,
            format!("runtime entry size mismatch: read {written} bytes, expected {size}"),
        ));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = entry
            .header()
            .mode()
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?
            & 0o777;
        file.set_permissions(fs::Permissions::from_mode(mode))
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e))?;
    }
    file.sync_all()
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e))
}

#[cfg(has_bundled_cli)]
fn install_cli(
    install_dir: &Path,
    archive: &[u8],
    expected_binary_size: u64,
) -> Result<PathBuf, EmbeddedCliError> {
    let verbose = std::env::var("COPILOT_CLI_INSTALL_VERBOSE").ok().as_deref() == Some("1");

    fs::create_dir_all(install_dir)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::CreateDir, e))?;

    let final_path = install_dir.join(CLI_BINARY_NAME);
    let marker_path = marker_path(install_dir);

    // Fast path: a previous install left both the binary and the integrity
    // marker we wrote *after* verifying it. Re-validate cheaply (size +
    // executable-image magic) so a binary that was later truncated or
    // quarantined by antivirus is re-extracted instead of trusted blindly.
    if existing_install_is_valid(&final_path, &marker_path, expected_binary_size) {
        if verbose {
            eprintln!("embedded CLI already installed at {}", final_path.display());
        }
        return Ok(final_path);
    }

    // The bytes extracted from the embedded archive are part of the
    // consumer's trusted, signed binary — so they are the known-good
    // reference we verify the on-disk file against after publishing.
    let start = std::time::Instant::now();
    let bytes = extract_cli_binary(archive)?;
    if bytes.is_empty() {
        return Err(EmbeddedCliError::with_message(
            EmbeddedCliErrorKind::Verification,
            "extracted CLI binary is empty",
        ));
    }

    let mut last_err: Option<EmbeddedCliError> = None;
    for attempt in 1..=MAX_PUBLISH_ATTEMPTS {
        match publish_verified(install_dir, &final_path, &marker_path, &bytes) {
            Ok(()) => {
                if verbose {
                    eprintln!(
                        "embedded CLI extracted to {} in {:?}",
                        final_path.display(),
                        start.elapsed()
                    );
                }
                return Ok(final_path);
            }
            Err(e) => {
                // Another process may have raced us and published the same
                // good binary; if what's on disk matches our trusted bytes,
                // accept its install rather than fighting over it.
                if verify_on_disk_matches(&final_path, &bytes).is_ok() {
                    let _ = write_marker(&marker_path, bytes.len() as u64);
                    return Ok(final_path);
                }
                warn!(attempt, error = %e, "embedded CLI publish attempt failed; retrying");
                last_err = Some(e);
            }
        }
    }

    Err(EmbeddedCliError::with_source(
        EmbeddedCliErrorKind::Blocked,
        last_err,
    ))
}

/// Path of the integrity marker written next to the installed binary. Its
/// presence (and recorded size) is proof a previous run published a verified
/// binary, letting the fast path skip re-extraction without trusting a bare
/// `is_file()` check.
#[cfg(any(has_bundled_cli, test))]
fn marker_path(install_dir: &Path) -> PathBuf {
    install_dir.join(".copilot-cli.ok")
}

/// Cheap, allocation-light validity check for an already-installed binary:
/// the file exists and is non-empty, an integrity marker recording its
/// expected size is present and matches, and the first bytes look like a
/// valid executable image for this platform. Catches the realistic failure
/// modes (zero-length / truncated / quarantined-to-garbage) without re-reading
/// the whole file.
#[cfg(any(has_bundled_cli, test))]
fn existing_install_is_valid(
    final_path: &Path,
    marker_path: &Path,
    expected_binary_size: u64,
) -> bool {
    let Ok(meta) = fs::metadata(final_path) else {
        return false;
    };
    if !meta.is_file() || meta.len() == 0 {
        return false;
    }
    match read_marker_len(marker_path) {
        Some(expected) if expected == expected_binary_size && expected == meta.len() => {
            looks_like_valid_image(final_path)
        }
        _ => false,
    }
}

/// Extract → stage in a unique temp file in the *same* directory → verify the
/// staged bytes → atomically publish into place (see [`publish_staged`]) →
/// re-verify the published file → write the integrity marker. Every step that
/// can leave a partial file cleans up after itself, so a failure never leaves a
/// half-written binary at the final path.
#[cfg(any(has_bundled_cli, test))]
fn publish_verified(
    install_dir: &Path,
    final_path: &Path,
    marker_path: &Path,
    bytes: &[u8],
) -> Result<(), EmbeddedCliError> {
    let tmp = write_temp_file(install_dir, bytes)?;

    // Verify the staged copy before it ever becomes the live binary, so a
    // short write or in-flight antivirus tampering is caught here.
    if let Err(e) = verify_on_disk_matches(&tmp, bytes) {
        let _ = fs::remove_file(&tmp);
        return Err(e);
    }

    if let Err(e) = publish_staged(&tmp, final_path, true) {
        let _ = fs::remove_file(&tmp);
        return Err(e);
    }

    // Re-verify after publishing: catches the window where antivirus
    // quarantines or rewrites the file between staging and publishing.
    verify_on_disk_matches(final_path, bytes)?;

    write_marker(marker_path, bytes.len() as u64)?;
    Ok(())
}

/// Write `contents` to a uniquely-named temp file in `dir` (same filesystem as
/// the final path so the later rename is atomic), flushing and fsync-ing the
/// bytes to disk and marking it executable on unix before returning its path.
#[cfg(any(has_bundled_cli, test))]
fn write_temp_file(dir: &Path, contents: &[u8]) -> Result<PathBuf, EmbeddedCliError> {
    let (tmp, mut file) = create_temp_file(dir)?;

    if let Err(e) = file
        .write_all(contents)
        .and_then(|()| file.flush())
        .and_then(|()| file.sync_all())
    {
        drop(file);
        let _ = fs::remove_file(&tmp);
        return Err(EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e));
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(e) = fs::set_permissions(&tmp, fs::Permissions::from_mode(0o755)) {
            drop(file);
            let _ = fs::remove_file(&tmp);
            return Err(EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e));
        }
    }

    drop(file);
    Ok(tmp)
}

#[cfg(any(has_bundled_cli, test))]
fn create_temp_file(dir: &Path) -> Result<(PathBuf, fs::File), EmbeddedCliError> {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let tmp = dir.join(format!(
        ".copilot-cli.tmp.{}.{}.{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed),
        nanos
    ));
    let file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&tmp)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e))?;
    Ok((tmp, file))
}

/// Atomically move the staged temp file onto `final_path`.
///
/// Rust uses rename on POSIX and MoveFileExW with MOVEFILE_REPLACE_EXISTING on
/// Windows. Never unlink the destination on failure: readers must retain the
/// previous complete file if replacement is blocked.
#[cfg(any(has_bundled_cli, test))]
fn publish(tmp: &Path, final_path: &Path) -> Result<(), EmbeddedCliError> {
    fs::rename(tmp, final_path).map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Publish, e))
}

/// Publish the staged file at `staged` as `target`, keeping a file already
/// there when it holds the same bytes and permissions, including effective
/// execute access when `executable` is required.
///
/// Installers that start on a cold cache at the same time all miss the fast
/// path and stage their own copy. Renaming each copy into place replaces the
/// file an earlier installer already published, and a process that earlier
/// installer started from it keeps running an unlinked executable (on Linux,
/// `/proc/<pid>/exe` ends in ` (deleted)`). On unix the staged file is
/// therefore hard-linked into place, which never replaces an existing file; an
/// identical file found there is kept and the staged copy discarded. A
/// different file is replaced by [`publish`] as before, as is any target when
/// the filesystem cannot hard-link.
#[cfg(any(has_bundled_cli, test))]
fn publish_staged(staged: &Path, target: &Path, executable: bool) -> Result<(), EmbeddedCliError> {
    #[cfg(not(unix))]
    let _ = executable;
    #[cfg(unix)]
    {
        let in_place = match fs::hard_link(staged, target) {
            Ok(()) => true,
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                same_contents_and_mode(staged, target)
                    && (!executable || check_runtime_wrapper_execute_access(target).is_ok())
            }
            Err(e) => {
                tracing::debug!(path = %target.display(), error = %e,
                    "cannot hard-link the staged file; replacing the target");
                false
            }
        };
        if in_place {
            if let Err(e) = fs::remove_file(staged)
                && e.kind() != std::io::ErrorKind::NotFound
            {
                tracing::debug!(path = %staged.display(), error = %e,
                    "failed to remove the staged file");
            }
            return Ok(());
        }
    }
    publish(staged, target)
}

/// True when `target` is a regular file with the same bytes and permission
/// bits as `staged`. Any I/O error counts as a difference, so the caller
/// replaces the target.
#[cfg(all(any(has_bundled_cli, test), unix))]
fn same_contents_and_mode(staged: &Path, target: &Path) -> bool {
    use std::io::Read as _;
    use std::os::unix::fs::PermissionsExt;

    let (Ok(staged_meta), Ok(target_meta)) = (fs::metadata(staged), fs::symlink_metadata(target))
    else {
        return false;
    };
    if !target_meta.is_file()
        || staged_meta.len() != target_meta.len()
        || staged_meta.permissions().mode() & 0o777 != target_meta.permissions().mode() & 0o777
    {
        return false;
    }
    let (Ok(mut staged), Ok(mut target)) = (fs::File::open(staged), fs::File::open(target)) else {
        return false;
    };
    let mut staged_buf = [0u8; 64 * 1024];
    let mut target_buf = [0u8; 64 * 1024];
    loop {
        let Ok(read) = staged.read(&mut staged_buf) else {
            return false;
        };
        if read == 0 {
            return matches!(target.read(&mut target_buf[..1]), Ok(0));
        }
        if target.read_exact(&mut target_buf[..read]).is_err()
            || staged_buf[..read] != target_buf[..read]
        {
            return false;
        }
    }
}

/// Read the file at `path` and confirm it byte-for-byte matches the trusted
/// `expected` image. Size is checked first so the common corruption case
/// (truncation) produces a precise error.
#[cfg(any(has_bundled_cli, test))]
fn verify_on_disk_matches(path: &Path, expected: &[u8]) -> Result<(), EmbeddedCliError> {
    let actual = fs::read(path).map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e))?;
    if actual.len() != expected.len() {
        return Err(EmbeddedCliError::with_message(
            EmbeddedCliErrorKind::Verification,
            format!(
                "size mismatch: on-disk {} bytes, expected {} bytes",
                actual.len(),
                expected.len()
            ),
        ));
    }
    if actual != expected {
        return Err(EmbeddedCliError::with_message(
            EmbeddedCliErrorKind::Verification,
            "on-disk binary differs from the embedded image",
        ));
    }
    Ok(())
}

/// Best-effort check that the first bytes of `path` are a valid executable
/// image header for the current platform (PE on Windows, Mach-O on macOS,
/// ELF elsewhere). Returns `false` on any I/O error or unrecognized header.
#[cfg(any(has_bundled_cli, test))]
fn looks_like_valid_image(path: &Path) -> bool {
    use std::io::Read as _;
    let mut buf = [0u8; 4];
    let Ok(mut file) = fs::File::open(path) else {
        return false;
    };
    let Ok(read) = file.read(&mut buf) else {
        return false;
    };
    let head = &buf[..read];

    #[cfg(windows)]
    {
        head.starts_with(b"MZ")
    }
    #[cfg(target_os = "macos")]
    {
        matches!(
            head,
            [0xfe, 0xed, 0xfa, 0xce] // Mach-O 32-bit
                | [0xfe, 0xed, 0xfa, 0xcf] // Mach-O 64-bit
                | [0xce, 0xfa, 0xed, 0xfe] // byte-swapped 32-bit
                | [0xcf, 0xfa, 0xed, 0xfe] // byte-swapped 64-bit
                | [0xca, 0xfe, 0xba, 0xbe] // universal (fat)
                | [0xbe, 0xba, 0xfe, 0xca] // byte-swapped universal
        )
    }
    #[cfg(all(not(windows), not(target_os = "macos")))]
    {
        head.starts_with(b"\x7fELF")
    }
}

/// Write the integrity marker recording the published binary's size. Best
/// effort: a torn write just means the next run can't parse it and re-extracts.
#[cfg(any(has_bundled_cli, test))]
fn write_marker(marker_path: &Path, size: u64) -> Result<(), EmbeddedCliError> {
    fs::write(marker_path, size.to_string())
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Io, e))
}

/// Parse the size recorded in the integrity marker, or `None` if it's missing
/// or unparsable.
#[cfg(any(has_bundled_cli, test))]
fn read_marker_len(marker_path: &Path) -> Option<u64> {
    fs::read_to_string(marker_path)
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
}

#[cfg(all(has_bundled_cli, not(windows)))]
fn extract_cli_binary(archive: &[u8]) -> Result<Vec<u8>, EmbeddedCliError> {
    extract_binary(archive, CLI_BINARY_NAME)
}

#[cfg(all(has_bundled_cli, windows))]
fn extract_cli_binary(archive: &[u8]) -> Result<Vec<u8>, EmbeddedCliError> {
    let reader = std::io::Cursor::new(archive);
    let mut zip = zip::ZipArchive::new(reader)
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
    for index in 0..zip.len() {
        let mut entry = zip
            .by_index(index)
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
        let name = entry
            .name()
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
        if name == CLI_BINARY_NAME || name.ends_with(&format!("/{CLI_BINARY_NAME}")) {
            let mut bytes = Vec::with_capacity(entry.size() as usize);
            entry
                .read_to_end(&mut bytes)
                .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
            return Ok(bytes);
        }
    }
    Err(EmbeddedCliErrorKind::BinaryNotFoundInArchive.into())
}

#[cfg(all(has_bundled_cli, any(not(windows), test)))]
fn extract_binary(archive: &[u8], binary_name: &str) -> Result<Vec<u8>, EmbeddedCliError> {
    let gz = flate2::read::GzDecoder::new(archive);
    let mut tar = tar::Archive::new(gz);
    for entry in tar
        .entries()
        .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?
    {
        let mut entry =
            entry.map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
        let path = entry
            .path()
            .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
        let name = path.to_string_lossy();
        if name == binary_name || name.ends_with(&format!("/{binary_name}")) {
            let mut bytes = Vec::with_capacity(entry.size() as usize);
            entry
                .read_to_end(&mut bytes)
                .map_err(|e| EmbeddedCliError::new(EmbeddedCliErrorKind::Archive, e))?;
            return Ok(bytes);
        }
    }
    Err(EmbeddedCliErrorKind::BinaryNotFoundInArchive.into())
}

#[cfg(any(has_bundled_cli, test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(dead_code)]
enum EmbeddedCliErrorKind {
    CreateDir,
    Archive,
    BinaryNotFoundInArchive,
    Io,
    /// Atomically renaming the staged temp file onto the final path failed.
    Publish,
    /// The published (or staged) file didn't match the trusted embedded image.
    Verification,
    /// Extraction kept producing a corrupt/missing binary across all retries —
    /// most likely antivirus interference.
    Blocked,
}

#[cfg(any(has_bundled_cli, test))]
impl std::fmt::Display for EmbeddedCliErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EmbeddedCliErrorKind::CreateDir => f.write_str("failed to create install directory"),
            EmbeddedCliErrorKind::Archive => f.write_str("failed to read archive entry"),
            EmbeddedCliErrorKind::BinaryNotFoundInArchive => {
                f.write_str("CLI binary not found in embedded archive")
            }
            EmbeddedCliErrorKind::Io => f.write_str("I/O error"),
            EmbeddedCliErrorKind::Publish => {
                f.write_str("failed to publish the extracted CLI binary")
            }
            EmbeddedCliErrorKind::Verification => {
                f.write_str("extracted CLI binary failed integrity verification")
            }
            EmbeddedCliErrorKind::Blocked => f.write_str(
                "bundled CLI appears blocked or corrupt after multiple attempts \
                 (possibly quarantined by antivirus)",
            ),
        }
    }
}

#[cfg(any(has_bundled_cli, test))]
#[allow(dead_code)]
struct EmbeddedCliError {
    repr: crate::errors::Repr<EmbeddedCliErrorKind>,
}

#[cfg(any(has_bundled_cli, test))]
#[allow(dead_code)]
impl EmbeddedCliError {
    fn new<E>(kind: EmbeddedCliErrorKind, error: E) -> Self
    where
        E: Into<Box<dyn std::error::Error + Send + Sync>>,
    {
        Self {
            repr: crate::errors::Repr::Custom(crate::errors::Custom {
                kind,
                error: error.into(),
            }),
        }
    }

    fn with_message(
        kind: EmbeddedCliErrorKind,
        message: impl Into<std::borrow::Cow<'static, str>>,
    ) -> Self {
        Self {
            repr: crate::errors::Repr::SimpleMessage(kind, message.into()),
        }
    }

    /// Build an error from `kind`, attaching the last failure as the source
    /// when one is available so the actionable message still carries context.
    fn with_source(kind: EmbeddedCliErrorKind, source: Option<EmbeddedCliError>) -> Self {
        match source {
            Some(source) => Self::new(kind, Box::new(source)),
            None => Self {
                repr: crate::errors::Repr::Simple(kind),
            },
        }
    }
}

#[cfg(any(has_bundled_cli, test))]
impl From<EmbeddedCliErrorKind> for EmbeddedCliError {
    fn from(kind: EmbeddedCliErrorKind) -> Self {
        Self {
            repr: crate::errors::Repr::Simple(kind),
        }
    }
}

#[cfg(any(has_bundled_cli, test))]
impl std::fmt::Display for EmbeddedCliError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.repr {
            crate::errors::Repr::Simple(kind) => write!(f, "{kind}"),
            crate::errors::Repr::SimpleMessage(_, msg) => write!(f, "{msg}"),
            crate::errors::Repr::Custom(crate::errors::Custom { kind, error }) => {
                write!(f, "{kind}: {error}")
            }
        }
    }
}

#[cfg(any(has_bundled_cli, test))]
impl std::fmt::Debug for EmbeddedCliError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "EmbeddedCliError({self})")
    }
}

#[cfg(any(has_bundled_cli, test))]
impl std::error::Error for EmbeddedCliError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.repr {
            crate::errors::Repr::Custom(crate::errors::Custom { error, .. }) => Some(&**error),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests;