mxc-sdk 1.0.1

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! `IsolationSessionManager` — granular wrapper over the in-proc
//! isolation session lifecycle. Each method maps 1:1 to a single WinRT op.
//! `create_process` also drives the ConPTY relay setup + shutdown ladder
//! against the local console.

use std::sync::Arc;

use crate::mxc_common::audit::{AuditEvent, AuditEventName, KillMethod, TeardownStatus};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::process_util::{OwnedHandle, PipeReadCanceller};
use crate::mxc_common::sandbox_process::StreamCloser;
use crate::mxc_common::state_aware_backend::{ExecHandle, ExecOutcome};

use crate::isolation_session_bindings::bindings::{
    IsoSessionFeature, IsoSessionOps, IsoSessionProcess, IsoSessionProcessResult,
    IsoSessionUserResult,
};
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Com::{CoDecrementMTAUsage, CoIncrementMTAUsage, CO_MTA_USAGE_COOKIE};
use windows::Win32::System::Console::{
    GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
};
use windows::Win32::System::Threading::{CreateEventW, SetEvent, WaitForSingleObject};
use windows::UI::WindowId;
use windows_core::{HSTRING, PCWSTR};

use super::console_mode::{get_local_console_size, ConsoleModeRestorer, CtrlHandlerGuard};
use super::console_relay::{create_console_relay_thread, ConsoleRelayParams};
use super::error::{
    activation_error, check_result, format_iso_error, lifecycle_err, op, transport_err,
    IsolationSessionError, StalePromotion,
};
use super::owned_thread::{self, Impersonation};
use super::pipe_relay::{
    create_relay_thread, create_relay_thread_with_stop, duplicate_handle, PipeRelayWithStopParams,
};
use super::process_options::{build_iso_process_options, ProcessOptions};

// The OS account name is lifecycle addressing data, not diagnostic identity.
const AGENT_IDENTITY_MARKER: &str = "isolation-session-agent";

/// Keeps the process's MTA alive for as long as the lifecycle's WinRT objects,
/// which outlive the call that created them.
/// `CoIncrementMTAUsage` holds a reference releasable from any thread;
/// `CoUninitialize` is thread-affine and would tear the apartment down under a
/// live object.
pub(super) struct MtaReference {
    cookie: CO_MTA_USAGE_COOKIE,
}

impl MtaReference {
    pub(super) fn acquire() -> Result<Self, IsolationSessionError> {
        // SAFETY: the out-parameter is a valid, writable local.
        let cookie = unsafe { CoIncrementMTAUsage() }.map_err(|e| {
            transport_err(
                op::CO_INCREMENT_MTA_USAGE,
                "could not keep a multi-threaded apartment alive",
                &e,
            )
        })?;
        Ok(Self { cookie })
    }
}

impl Drop for MtaReference {
    fn drop(&mut self) {
        // SAFETY: balances the `CoIncrementMTAUsage` in `acquire`. The cookie is
        // not thread-affine, so this is sound on whichever thread drops it.
        unsafe {
            let _ = CoDecrementMTAUsage(self.cookie);
        }
    }
}

// SAFETY: the cookie is an opaque token, never dereferenced, and
// `CoDecrementMTAUsage` accepts it from any thread.
unsafe impl Send for MtaReference {}
unsafe impl Sync for MtaReference {}

/// Activates the in-proc IsolationSession runtime factory and returns the
/// instance.
fn check_service_available_and_activate() -> Result<IsoSessionOps, IsolationSessionError> {
    match IsoSessionOps::new() {
        Ok(ops) => Ok(ops),
        // The HRESULT→error mapping lives in `activation_error` so it stays
        // testable without depending on whether this host can activate the
        // API at all.
        Err(e) => Err(activation_error(e.code().0 as u32, &e.message())),
    }
}

/// `GetFeatureLevel` fails on a host that does not recognize the feature
/// value, so an error reads as not supported.
fn feature_supported_from(level: windows_core::Result<i32>) -> bool {
    matches!(level, Ok(level) if level > 0)
}

const ZERO_WINDOW_ID: WindowId = WindowId { Value: 0 };

/// The provision-time facts the OS assigns to a freshly-created agent user,
/// read from `IsoSessionUserResult` at `add_user`. The addressing key for
/// every later lifecycle op remains `agent_user_name`; the other two fields
/// are provision metadata surfaced to the caller.
pub(super) struct ProvisionedUser {
    /// The OS-assigned agent account name (also the `sandboxId` tail).
    pub agent_user_name: String,
    /// The security identifier (SID) of the agent user. Diagnostic only.
    pub agent_user_sid: String,
    /// A directory shared between the calling user and this isolated agent
    /// user, through which the caller can stage files into the session. Each
    /// isolated user can access only its own workspace; the caller can access
    /// all of them. Deleted when the agent user is deprovisioned.
    pub ephemeral_workspace_path: String,
}

/// Manages the isolation session lifecycle. Methods map 1:1 to the granular
/// API steps.
pub struct IsolationSessionManager {
    /// The OS-assigned agent user name returned by `add_user`. Used as the
    /// `agentUserName` argument to every subsequent lifecycle op.
    agent_user_name: HSTRING,
    /// The activated service instance. Held for the manager's lifetime so
    /// the WinRT factory is reused across calls.
    ops: IsoSessionOps,
    /// The impersonation of the thread that created this manager: every call
    /// the manager makes, and every call for a process it starts, is made
    /// under it.
    impersonation: Impersonation,
    /// Declared after `ops` so it drops last: the apartment outlives every
    /// object activated in it.
    _mta: MtaReference,
}

impl IsolationSessionManager {
    /// Start an interactive process whose ConPTY handles remain caller-driven.
    pub(super) fn pty_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&Logger>,
    ) -> Result<Arc<ClosingProcess>, IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            let mta = MtaReference::acquire()?;
            Ok(Arc::new(ClosingProcess::new(
                self.start_process(options, logger)?,
                self.impersonation.clone(),
                mta,
            )))
        })
    }

    /// Pegs a manager to an existing OS-assigned agent user name (the value
    /// returned by `add_user`). Activates the service factory once and
    /// reuses it for the manager's lifetime.
    pub(super) fn new(agent_user_name: &str) -> Result<Self, IsolationSessionError> {
        let impersonation = Impersonation::of_this_thread()?;
        owned_thread::call(&impersonation, || {
            let mta = MtaReference::acquire()?;
            let ops = check_service_available_and_activate()?;
            Ok(Self {
                agent_user_name: HSTRING::from(agent_user_name),
                ops,
                impersonation: impersonation.clone(),
                _mta: mta,
            })
        })
    }

    /// Provisions an agent user and returns its provision-time facts (the
    /// OS-assigned account name — which addresses every subsequent lifecycle
    /// op — plus the agent SID and the shared ephemeral workspace path),
    /// together with a manager already pegged to that account.
    ///
    /// The manager is returned rather than left to the caller to build with
    /// [`Self::new`] because building it separately would activate the service
    /// a second time. That second activation can fail *after* the agent user
    /// has been minted, and at that point the account cannot be removed —
    /// removal needs the very service instance that just failed to activate —
    /// so the sandbox would leak with no way to clean it up. Handing back the
    /// instance `add_user` already holds removes that window entirely.
    ///
    /// Once the API reports success the account exists, so every failure after
    /// that point deprovisions best-effort rather than abandoning it. The sole
    /// exception is a failure to read the account name itself, which leaves
    /// nothing to address a removal to.
    ///
    /// Note: the in-proc API exposes no session-lifetime knob, so `lifecycle`
    /// cannot be honored here. Unsupported values are refused by the calling
    /// surface rather than ignored — one-shot rejects `destroyOnExit: false`
    /// and `preservePolicy: true` in `validate_runner`, and the state-aware
    /// parser rejects the whole `lifecycle` section.
    pub(super) fn add_user(
        app_id: Option<&str>,
    ) -> Result<(ProvisionedUser, Self), IsolationSessionError> {
        let impersonation = Impersonation::of_this_thread()?;
        owned_thread::call(&impersonation, || {
            let mta = MtaReference::acquire()?;
            let ops = check_service_available_and_activate()?;
            // Prefer the newest overload the host advertises.
            let (op_add_user, started) = if feature_supported_from(
                ops.GetFeatureLevel(IsoSessionFeature::DeducedEnterpriseAgentUser),
            ) {
                (
                    op::ADD_USER_DEDUCED,
                    ops.AddUserAsync3(&HSTRING::from(app_id.unwrap_or_default()), ZERO_WINDOW_ID),
                )
            } else if feature_supported_from(
                ops.GetFeatureLevel(IsoSessionFeature::AppScopedRegistration),
            ) {
                (
                    op::ADD_USER,
                    ops.AddUserAsync2(
                        &HSTRING::from(app_id.unwrap_or_default()),
                        &HSTRING::new(),
                        &HSTRING::new(),
                    ),
                )
            } else {
                (
                    op::ADD_USER_LEGACY,
                    ops.AddUserAsync(&HSTRING::new(), &HSTRING::new()),
                )
            };
            let user_result: IsoSessionUserResult = owned_thread::wait_for(op_add_user, started)?;

            let err = user_result
                .Error()
                .map_err(|e| transport_err(op_add_user, "get Error failed", &e))?;
            let is_error = err
                .IsError()
                .map_err(|e| transport_err(op_add_user, "get IsError failed", &e))?;
            if is_error {
                // Provision mints the agent user, so `ERROR_NOT_FOUND` here can
                // never mean "the sandbox is gone" — there is no sandbox id yet.
                return Err(format_iso_error(
                    op_add_user,
                    &err,
                    StalePromotion::NotEligible,
                ));
            }

            let agent_user_name = user_result
                .AgentUserName()
                .map_err(|e| transport_err(op_add_user, "get AgentUserName failed", &e))?;

            // Past this point the OS account exists and `agent_user_name` is the
            // key that removes it, so build the manager now rather than after the
            // remaining getters. That makes every subsequent failure recoverable:
            // the removal key and a live service instance are both already in hand.
            //
            // A failure of `AgentUserName()` above is the one case with no
            // in-process remedy — without the name there is nothing to address a
            // removal to — so it is left to propagate.
            let manager = Self {
                agent_user_name: agent_user_name.clone(),
                ops,
                impersonation: impersonation.clone(),
                _mta: mta,
            };

            let provisioned =
                match Self::read_remaining_facts(&user_result, &agent_user_name, op_add_user) {
                    Ok(provisioned) => provisioned,
                    Err(e) => {
                        // Best-effort: returning here without this would abandon an
                        // account we are still able to remove.
                        let _ = manager.deprovision_agent_user();
                        return Err(e);
                    }
                };

            Ok((provisioned, manager))
        })
    }

    /// Reads the provision-time facts that remain after the agent user name.
    ///
    /// Split out of [`Self::add_user`] so that a failure in any of them lands
    /// on one error path, where the freshly created account can be removed
    /// instead of orphaned. `op_add_user` is the operation label of the
    /// provisioning overload actually invoked, so these getters' failures are
    /// attributed to the same API call in telemetry.
    fn read_remaining_facts(
        user_result: &IsoSessionUserResult,
        agent_user_name: &HSTRING,
        op_add_user: &'static str,
    ) -> Result<ProvisionedUser, IsolationSessionError> {
        let agent_user_sid = user_result
            .AgentUserSid()
            .map_err(|e| transport_err(op_add_user, "get AgentUserSid failed", &e))?;
        let ephemeral_workspace_path = user_result
            .EphemeralWorkspacePath()
            .map_err(|e| transport_err(op_add_user, "get EphemeralWorkspacePath failed", &e))?;

        Ok(ProvisionedUser {
            agent_user_name: agent_user_name.to_string(),
            agent_user_sid: agent_user_sid.to_string(),
            ephemeral_workspace_path: ephemeral_workspace_path.to_string(),
        })
    }

    /// Step 2: Start the isolation session for the pegged agent user.
    pub(super) fn start_session(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            // Prefer the newest overload the host advertises.
            let (op_start_session, started) = if feature_supported_from(
                self.ops
                    .GetFeatureLevel(IsoSessionFeature::DeducedEnterpriseAgentUser),
            ) {
                (
                    op::START_SESSION_DEDUCED,
                    self.ops
                        .StartSessionAsync2(&self.agent_user_name, ZERO_WINDOW_ID),
                )
            } else {
                (
                    op::START_SESSION,
                    self.ops
                        .StartSessionAsync(&self.agent_user_name, &HSTRING::new()),
                )
            };
            let result = owned_thread::wait_for(op_start_session, started)?;
            check_result(&result, op_start_session, StalePromotion::Eligible)
        })
    }

    /// Step 3a: Start a process inside the started isolation session, and
    /// return it **without waiting**.
    ///
    /// Split out of [`Self::create_process`] so the caller chooses how the
    /// streams are consumed: the relayed path bridges them with its own relay
    /// threads and blocks (see `create_process`), while an in-process SDK
    /// caller takes the raw handles and drives them itself.
    fn start_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&Logger>,
    ) -> Result<StartedProcess, IsolationSessionError> {
        let proc_options = build_iso_process_options(options)?;

        let result: IsoSessionProcessResult = owned_thread::wait_for(
            op::RUN_PROCESS,
            self.ops.RunProcessWithOptionsAsync(
                &self.agent_user_name,
                &HSTRING::from(&options.process_path),
                &HSTRING::from(&options.arguments),
                &proc_options,
            ),
        )?;

        let err = result
            .Error()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get Error failed", &e))?;
        let is_error = err
            .IsError()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get IsError failed", &e))?;
        if is_error {
            return Err(format_iso_error(
                op::RUN_PROCESS,
                &err,
                StalePromotion::Eligible,
            ));
        }

        let process: IsoSessionProcess = result
            .Process()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get Process failed", &e))?;

        // A getter that errors is a backend failure, not an absent stream:
        // propagate it rather than coercing to 0, which downstream treats as
        // "no handle" and silently skips the corresponding stdio relay. A
        // genuinely returned 0 still means absent and is preserved.
        let stdout = process
            .OutputHandle()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get OutputHandle failed", &e))?;
        let stderr = process
            .ErrorHandle()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get ErrorHandle failed", &e))?;
        let stdin = process
            .InputHandle()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get InputHandle failed", &e))?;

        Ok(StartedProcess {
            process,
            stdout,
            stderr,
            stdin,
            identity: AGENT_IDENTITY_MARKER,
            audit_logger: std::sync::Mutex::new(
                logger
                    .map(Logger::clone_diagnostic_sink)
                    .unwrap_or_else(Logger::inherit_thread_diagnostic_sink),
            ),
        })
    }

    /// Step 3: Create a process inside the started isolation session and run it
    /// to completion. Output is streamed live to the calling process's stdio via
    /// internal relay threads; only the exit code is returned.
    ///
    /// This is the **relay** path, reached by `wxc-exec` and by an in-process
    /// caller that asked to attach. A caller that wants the streams handed back
    /// uses [`Self::piped_exec_handle`] instead.
    pub(super) fn create_process(
        &self,
        options: &ProcessOptions,
        logger: Option<&mut Logger>,
    ) -> Result<i32, IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            // Everything fallible that does not need the workload runs first, so no
            // failure can strand a running one.
            let wxc_stdout = unsafe { GetStdHandle(STD_OUTPUT_HANDLE) }
                .map_err(|e| lifecycle_err(format!("GetStdHandle(stdout) failed: {}", e)))?;
            let wxc_stderr = unsafe { GetStdHandle(STD_ERROR_HANDLE) }
                .map_err(|e| lifecycle_err(format!("GetStdHandle(stderr) failed: {}", e)))?;
            let wxc_stdin = unsafe { GetStdHandle(STD_INPUT_HANDLE) }
                .map_err(|e| lifecycle_err(format!("GetStdHandle(stdin) failed: {}", e)))?;

            // Manual-reset stop event for the stdin relay. Effective for a waitable
            // `h_read` (console = TTY mode); for pipe handles it has no effect on a
            // blocked `ReadFile`, so that relay misses its join and ends only when
            // the calling process exits. Only `wxc-exec` reaches the non-TTY case.
            let stdin_stop_event = unsafe {
                CreateEventW(None, true, false, PCWSTR::null())
                    .map_err(|e| lifecycle_err(format!("CreateEventW(stdin stop): {}", e)))?
            };
            // Declared before `scope`, which holds a raw copy: it must drop last.
            let stdin_stop_owned = OwnedHandle::new(stdin_stop_event);

            // Relay threads bridge the calling process's stdio to
            // `IsoSessionProcess`'s pipes: console-handle inheritance cannot cross
            // the desktop-session boundary.
            //
            // Handle ownership across four sources:
            //   - Pipe handles owned by `IsoSessionProcess` (`OutputHandle()` /
            //     `ErrorHandle()` / `InputHandle()`, returned as u64): released
            //     by `process.Close()`. We do NOT close them. The output relays
            //     read their own duplicates, so `Close()` does not disturb them.
            //   - The calling process's std handles (`GetStdHandle`): OS-owned.
            //     We do NOT close them.
            //   - Stop event for stdin relay (`CreateEventW`): RAII-closed via
            //     `OwnedHandle`.
            //   - Relay thread handles: RAII-closed via `OwnedHandle` after we
            //     `WaitForSingleObject` on each.
            //
            // Lifetime: each relay's param struct is moved to the heap and owned
            // by its thread, which frees it on exit, so joining is not required
            // for memory safety.
            let started = self.start_process(options, logger.as_deref())?;
            let process = &started.process;
            let stdout_handle_val = started.stdout;
            let stderr_handle_val = started.stderr;
            let stdin_handle_val = started.stdin;

            let mut scope = RelayScope::new(process, stdin_stop_owned.get());

            // In interactive mode, switch the calling process's console to raw VT
            // so only the agent's ConPTY echoes and renders; otherwise both do.
            // RAII-restored on scope exit. No-op when stdio is not a console.
            let _console_guard = if options.interactive {
                Some(ConsoleModeRestorer::install_raw_vt())
            } else {
                None
            };

            // Install a console Ctrl handler that signals `stdin_stop_owned`
            // on Ctrl-C or terminal-close events, so the relay loops drain
            // cleanly instead of being terminated by the OS default
            // `ExitProcess`. Interactive mode only — non-interactive mode
            // wants the default behavior so the parent can terminate
            // wxc-exec via Ctrl-C. Installed after the workload starts: the
            // event is manual-reset and never cleared, so an earlier Ctrl-C
            // would stop the stdin relay for the session's lifetime.
            let _ctrl_guard = if options.interactive {
                Some(CtrlHandlerGuard::install(stdin_stop_owned.get()))
            } else {
                None
            };

            // Push the local console's viewport size into the agent's inner ConPTY.
            // Without it the inner HPCON keeps its default dimensions and VT-aware
            // agents (e.g. PSReadLine) anchor their prompt to that smaller last row,
            // overlaying text once they reach it. Mid-session resize is not handled
            // here.
            if options.interactive {
                if let Some((cols, rows)) = get_local_console_size() {
                    let _ = process.ResizeConsole(cols, rows);
                }
            }

            scope.stdout = if stdout_handle_val != 0 {
                let (thread, canceller) = unsafe {
                    create_relay_thread(
                        HANDLE(stdout_handle_val as *mut core::ffi::c_void),
                        wxc_stdout,
                    )
                }
                .map_err(|e| lifecycle_err(format!("create stdout relay: {}", e)))?;
                scope.output_cancellers.push(canceller);
                Some(thread)
            } else {
                None
            };
            scope.stderr = if stderr_handle_val != 0 {
                let (thread, canceller) = unsafe {
                    create_relay_thread(
                        HANDLE(stderr_handle_val as *mut core::ffi::c_void),
                        wxc_stderr,
                    )
                }
                .map_err(|e| lifecycle_err(format!("create stderr relay: {}", e)))?;
                scope.output_cancellers.push(canceller);
                Some(thread)
            } else {
                None
            };
            // Stdin: in interactive mode use the console-aware relay so
            // `WINDOW_BUFFER_SIZE_EVENT` records propagate as
            // `ResizeConsole(cols, rows)` calls on the agent's inner ConPTY.
            // In non-interactive mode the agent's stdin is plain byte-oriented
            // and the simpler stop-aware pipe relay is appropriate.
            enum StdinRelayKind {
                None,
                Pipe(PipeRelayWithStopParams),
                Console(ConsoleRelayParams),
            }

            let stdin_relay_state = if stdin_handle_val == 0 {
                StdinRelayKind::None
            } else {
                // Owned, like the output relays': `process.Close()` releases the
                // original while this relay may still be writing.
                let stdin_h_write =
                    duplicate_handle(HANDLE(stdin_handle_val as *mut core::ffi::c_void))
                        .map_err(|e| lifecycle_err(format!("duplicate stdin handle: {}", e)))?;
                // Shares the event object, so `signal_stop` still reaches the relay.
                let stdin_h_stop = duplicate_handle(stdin_stop_owned.get())
                    .map_err(|e| lifecycle_err(format!("duplicate stdin stop event: {}", e)))?;
                if options.interactive {
                    // Clone the WinRT process handle so the relay thread holds
                    // its own ref-counted reference (WinRT clone = AddRef),
                    // released when the thread frees the params it owns.
                    let process_for_resize = process.clone();
                    let impersonation = self.impersonation.clone();
                    StdinRelayKind::Console(ConsoleRelayParams {
                        h_read: wxc_stdin,
                        h_write: stdin_h_write,
                        h_stop_event: stdin_h_stop,
                        resize_callback: Box::new(move |cols, rows| {
                            let _ = owned_thread::call(&impersonation, || {
                                let _ = process_for_resize.ResizeConsole(cols, rows);
                                Ok(())
                            });
                        }),
                    })
                } else {
                    StdinRelayKind::Pipe(PipeRelayWithStopParams {
                        h_read: wxc_stdin,
                        h_write: stdin_h_write,
                        h_stop_event: stdin_h_stop,
                    })
                }
            };

            // Matched by value: the params move into the spawn call, which puts
            // them on the heap under the relay thread's ownership.
            scope.stdin = match stdin_relay_state {
                StdinRelayKind::None => None,
                StdinRelayKind::Pipe(params) => Some(
                    unsafe { create_relay_thread_with_stop(params) }
                        .map_err(|e| lifecycle_err(format!("create stdin relay: {}", e)))?,
                ),
                StdinRelayKind::Console(params) => {
                    Some(unsafe { create_console_relay_thread(params) }.map_err(|e| {
                        lifecycle_err(format!("create console-aware stdin relay: {}", e))
                    })?)
                }
            };

            let outcome = started.wait(options.timeout_ms)?;
            scope.stop_stdin();
            scope.finish();

            Ok(match outcome {
                ExecOutcome::Exited(exit_code) => exit_code,
                ExecOutcome::TimedOut => WAIT_FOR_EXIT_TIMEOUT,
            })
        })
    }

    /// Start a process and hand back its live pipes as an [`ExecHandle`].
    ///
    /// Shared by the state-aware `Piped` exec and the one-shot streaming
    /// backend.
    ///
    /// `timeout_ms` is the caller's deadline, enforced by the waiter. Arm the
    /// service-side timer with [`with_service_timeout_grace`] before calling:
    /// without that margin the two deadlines coincide, and a timeout can arrive
    /// as an ordinary exit.
    ///
    /// [`with_service_timeout_grace`]: super::process_options::with_service_timeout_grace
    pub(super) fn piped_exec_handle(
        &self,
        options: &ProcessOptions,
        timeout_ms: u32,
        logger: Option<&Logger>,
    ) -> Result<ExecHandle, IsolationSessionError> {
        let started = owned_thread::call(&self.impersonation, || {
            // Acquired before the workload starts, so a failure here cannot
            // leave one running with no handle to reach it.
            let mta = MtaReference::acquire()?;
            Ok(Arc::new(ClosingProcess::new(
                self.start_process(options, logger)?,
                self.impersonation.clone(),
                mta,
            )))
        })?;

        // Read the handles before the closures take ownership. A zero means the
        // stream is genuinely absent, which is exactly the sentinel the
        // consumer already treats as "no stream".
        let stdout = HANDLE(started.stdout as *mut std::ffi::c_void);
        let stderr = HANDLE(started.stderr as *mut std::ffi::c_void);
        let stdin = HANDLE(started.stdin as *mut std::ffi::c_void);

        // `IsoSessionProcess` answers `IAgileObject`, so the closures may hold it
        // on whatever thread runs them; the calls they make go through
        // `owned_thread`.
        let waiter_process = Arc::clone(&started);
        let stdin_process = Arc::clone(&started);
        Ok(ExecHandle {
            stdout,
            stderr,
            stdin,
            stdin_closer: Some(Box::new(move || {
                let _ = owned_thread::call(&stdin_process.impersonation, || {
                    let _ = stdin_process.process.CloseStandardInput();
                    Ok(())
                });
            })),
            // Reports `TimedOut` when the deadline elapsed with the process
            // still running — see `StartedProcess::wait`, which samples that
            // before the shutdown ladder destroys the evidence.
            waiter: Box::new(move || {
                owned_thread::call(&waiter_process.impersonation, || {
                    waiter_process.wait(timeout_ms)
                })
                .map_err(super::error::map_lifecycle_error)
            }),
            // Reports whether the platform *accepted* the kill: `terminate`'s
            // bounded post-kill wait is not consulted, so a `Terminate` that
            // was accepted and then did not take effect still reports success.
            terminator: Box::new(move || {
                owned_thread::call(&started.impersonation, || started.terminate())
                    .map_err(super::error::map_lifecycle_error)
            }),
        })
    }

    /// Step 4: Stop the isolation session.
    pub(super) fn stop_session(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            let result = owned_thread::wait_for(
                op::STOP_SESSION,
                self.ops.StopSessionAsync(&self.agent_user_name),
            )?;
            check_result(&result, op::STOP_SESSION, StalePromotion::Eligible)
        })
    }

    /// Step 5: Deprovision the agent user.
    pub(super) fn deprovision_agent_user(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            let result = owned_thread::wait_for(
                op::REMOVE_USER,
                self.ops.RemoveUserAsync(&self.agent_user_name),
            )?;
            check_result(&result, op::REMOVE_USER, StalePromotion::Eligible)
        })
    }
}

#[derive(Debug, Default, Clone, Copy)]
pub struct TeardownOutcome {
    pub session_stopped: Option<bool>,
    pub agent_user_deprovisioned: Option<bool>,
}

impl TeardownOutcome {
    fn status(&self) -> TeardownStatus {
        let steps = [self.session_stopped, self.agent_user_deprovisioned];
        if steps.contains(&Some(false)) {
            TeardownStatus::Failure
        } else if steps.iter().all(Option::is_none) {
            TeardownStatus::Skipped
        } else {
            TeardownStatus::Success
        }
    }
}

pub fn log_sandbox_torn_down(logger: &mut Logger, phase: &str, outcome: TeardownOutcome) {
    if !logger.has_diagnostic_sink() && !crate::mxc_common::telemetry::is_active() {
        return;
    }
    crate::mxc_common::telemetry::log_sandbox_torn_down(
        AGENT_IDENTITY_MARKER,
        outcome.status().as_str(),
        &format!(
            "session_stopped={},agent_user_deprovisioned={}",
            outcome.session_stopped == Some(true),
            outcome.agent_user_deprovisioned == Some(true),
        ),
    );
    let record = AuditEvent::new(AuditEventName::SandboxTornDown)
        .str("backend", "isolation_session")
        .str("identity", AGENT_IDENTITY_MARKER)
        .str("phase", phase)
        .str("status", outcome.status().as_str())
        .bool("session_stopped", outcome.session_stopped == Some(true))
        .bool(
            "agent_user_deprovisioned",
            outcome.agent_user_deprovisioned == Some(true),
        );
    logger.log_audit_event(&record);
}

/// A process started inside an isolation session but **not yet awaited**.
///
/// Separating start from wait is what makes streaming possible: the executor
/// path hands these handles to its own relay threads and blocks, while an
/// in-process SDK caller takes them and drives them itself.
///
/// **Handle ownership stays here.** The three pipe handles belong to the
/// `IsoSessionProcess` and are released by its `Close()`; a consumer duplicates
/// them and must never close the originals. A `0` means the stream is genuinely
/// absent, not that a getter failed — `start_process` propagates getter errors
/// rather than coercing them.
pub(super) struct StartedProcess {
    pub(super) process: IsoSessionProcess,
    pub(super) stdout: u64,
    pub(super) stderr: u64,
    pub(super) stdin: u64,
    identity: &'static str,
    audit_logger: std::sync::Mutex<Logger>,
}

impl StartedProcess {
    fn audit(&self, name: AuditEventName) -> AuditEvent {
        AuditEvent::new(name)
            .str("backend", "isolation_session")
            .str("identity", self.identity)
            .u64("pid", 0)
    }

    fn record_exited(&self, exit_code: i32) {
        crate::mxc_common::telemetry::log_process_event(
            self.identity,
            0,
            crate::mxc_common::telemetry::ProcessEvent::Exited(exit_code),
        );
        let mut logger = self.audit_logger.lock().unwrap_or_else(|e| e.into_inner());
        logger.log_audit_event(
            &self
                .audit(AuditEventName::ProcessExited)
                .i64("exit_code", exit_code as i64),
        );
    }

    fn record_timed_out(&self, timeout_ms: u32) {
        crate::mxc_common::telemetry::log_process_event(
            self.identity,
            0,
            crate::mxc_common::telemetry::ProcessEvent::TimedOut(timeout_ms as u64),
        );
        let mut logger = self.audit_logger.lock().unwrap_or_else(|e| e.into_inner());
        logger.log_audit_event(
            &self
                .audit(AuditEventName::ProcessTimedOut)
                .u64("timeout_ms", timeout_ms as u64),
        );
    }

    fn record_kill_failed(&self, error_code: i32) {
        crate::mxc_common::telemetry::log_process_event(
            self.identity,
            0,
            crate::mxc_common::telemetry::ProcessEvent::KillFailed(
                KillMethod::TerminateProcess.as_str(),
                error_code,
            ),
        );
        let mut logger = self.audit_logger.lock().unwrap_or_else(|e| e.into_inner());
        logger.log_audit_event(
            &self
                .audit(AuditEventName::ProcessKillFailed)
                .str("kill_method", KillMethod::TerminateProcess.as_str())
                .i64("error_code", error_code as i64),
        );
    }

    /// Block until the process exits and yield its exit code, escalating
    /// through the graceful-shutdown ladder if it outlives `timeout_ms`.
    ///
    /// The *instruction sequence* is the one the relayed path runs inline, but
    /// the ladder's first two tiers are **inert for a consumer that holds
    /// duplicates of the pipe handles**:
    ///
    /// - Tier 1 closes the backend's stdin write end, but a pipe reaches EOF
    ///   only when *every* write end is closed, so tier 1 alone does not
    ///   produce EOF.
    /// - Tier 2 (`SendCtrlClose`) is ConPTY-only and returns `E_NOTIMPL`
    ///   otherwise, and a piped exec never allocates one.
    ///
    /// The ladder therefore degrades to the full 5s + 3s stall followed by
    /// tier 3's hard terminate.
    ///
    /// # Telling a timeout from an exit
    ///
    /// Reported as [`ExecOutcome::TimedOut`] when the deadline elapsed with the
    /// process still running, and [`ExecOutcome::Exited`] otherwise.
    ///
    /// **Neither available signal is sound alone**, because each is also a legal
    /// exit code: `WaitForExit` answers `-1` on timeout, and a timed-out
    /// process still reads [`STILL_ACTIVE`] (259) from `ExitCode()`. A workload
    /// is untrusted code and can return either value at will.
    ///
    /// Their *conjunction* establishes **whether the process was still running
    /// when it was sampled**, which is what the ladder decision needs. A process
    /// that exited cannot have exited with both values at once, so requiring
    /// both pins the live case:
    ///
    /// | Case | `WaitForExit` | `ExitCode()` | Verdict |
    /// |---|---|---|---|
    /// | still running | `-1` | `259` | `TimedOut` (after the ladder confirms it died) |
    /// | exited after the deadline | `-1` | `7` | `TimedOut` (already gone; no ladder) |
    /// | ambiguous | `-1` | `-1` | `Exited(-1)` |
    /// | exited `259` | `259` | `259` | `Exited(259)` |
    ///
    /// # A spent deadline is sticky
    ///
    /// The two reads are not atomic, so a process can exit in the window between
    /// them. That still reports [`ExecOutcome::TimedOut`]: the sentinel proves
    /// the deadline elapsed while the process was running, and a later-observed
    /// exit code does not un-spend it. Reporting that code instead would hide a
    /// missed deadline from a caller who asked for one.
    ///
    /// `TimedOut` promises the process is **gone**, not that this code killed
    /// it — a process that died on its own satisfies that just as a killed one
    /// does. The sibling WSLc backend draws the same line, tracking
    /// `deadline_elapsed` separately from `timed_out` so a spent deadline is
    /// reported "stickily rather than a later-observed exit code", and treating
    /// an already-confirmed exit as satisfying its termination check.
    ///
    /// The one irreducible case is `-1`/`-1`, where the sentinel and the exit
    /// code collide: nothing distinguishes a timeout from a workload that
    /// exited with `-1`, so it is read as the exit.
    ///
    /// # How far "gone" reaches here
    ///
    /// Both timeout paths confirm **the foreground process only**, because that
    /// is the only thing this API exposes: `IsoSessionProcess` has `Terminate`
    /// and `ExitCode` for the process it represents and no tree primitive. A
    /// descendant the workload backgrounded can therefore outlive a reported
    /// timeout on either path — the live one, which checks `ExitCode()` after
    /// the ladder, and the late-exit one, which has nothing left to terminate.
    ///
    /// That is not a gap this layer can close: descendants live in the isolation
    /// session's own user context and are reclaimed when the session is stopped
    /// and deprovisioned. Stated rather than implied, because
    /// [`ExecOutcome::TimedOut`] leaves the reach to the backend and the SDK's
    /// `WaitOutcome::TimedOut` describes process-tree backends where the kill
    /// does cover the tree.
    ///
    /// A zero `timeout_ms` short-circuits the whole test: it means INFINITE, and
    /// a wait with no deadline cannot have missed one. This is the default, so
    /// without the guard the common configuration would be the one at risk.
    ///
    /// # Why the ladder does not run for an exit
    ///
    /// The ladder exists to kill a **survivor**. Running it for a process that
    /// already exited reintroduces the very ambiguity this function avoids: its
    /// first `ExitCode()` reads 259 for a workload that exited with 259, so it
    /// walks all three tiers and cannot then tell that exit from a live
    /// process. An exited process therefore returns its code directly.
    pub(super) fn wait(&self, timeout_ms: u32) -> Result<ExecOutcome, IsolationSessionError> {
        // `WaitForExit` is a Win32 `WaitForSingleObject` on a kernel handle —
        // no COM round-trip. On timeout it returns -1; the ladder below then
        // decides what to do about a process that is still running.
        let waited = self
            .process
            .WaitForExit(timeout_ms)
            .map_err(|e| transport_err(op::RUN_PROCESS, "WaitForExit failed", &e))?;

        // Sampled before the ladder, which kills a survivor and so destroys the
        // evidence. `?`-propagated for the same reason the ladder propagates its
        // first query: a failure here means the kernel handle is broken, and
        // guessing "it exited" would report a fabricated outcome.
        let plan = plan_wait(timeout_ms, waited, || {
            self.process
                .ExitCode()
                .map_err(|e| transport_err(op::RUN_PROCESS, "get ExitCode failed", &e))
        })?;

        // An exited process never reaches the ladder: the ladder cannot tell a
        // 259 exit from a live process, which is the ambiguity `plan_wait`
        // exists to resolve while the evidence is still intact.
        match plan {
            WaitPlan::Exited(exit_code) => {
                self.record_exited(exit_code);
                return Ok(ExecOutcome::Exited(exit_code));
            }
            // The deadline was spent and the process is already gone, so there
            // is nothing to kill and nothing to confirm — the sample that
            // produced this plan is the confirmation.
            WaitPlan::TimedOutAfterDeadline => {
                self.record_timed_out(timeout_ms);
                return Ok(ExecOutcome::TimedOut);
            }
            WaitPlan::KillThenReportTimeout => {}
        }

        // Timed out: the process was still running, so it must be dead before
        // this reports `TimedOut`, which promises exactly that.
        self.record_timed_out(timeout_ms);
        let (_, terminate_error) = wait_with_graceful_shutdown(&self.process)?;
        if let Some(error_code) = terminate_error {
            self.record_kill_failed(error_code);
        }
        let after = self
            .process
            .ExitCode()
            .map_err(|e| transport_err(op::RUN_PROCESS, "get ExitCode failed", &e))?;
        if after == STILL_ACTIVE {
            // Unlike the general case, 259 is not ambiguous here: the sample
            // above established the process was running, so this is the same
            // process still running rather than a stale exit code. (The one
            // exception is a workload that exits with 259 inside the ladder's
            // own window, which yields a conservative "could not determine"
            // rather than a false claim that it was killed.)
            return Err(lifecycle_err(
                "the sandboxed process was still running after close-stdin, Ctrl-Close and \
                 terminate; it timed out but could not be confirmed killed",
            ));
        }
        Ok(ExecOutcome::TimedOut)
    }

    /// Kill the process now, reporting whether the kill request was *accepted*.
    ///
    /// Deliberately **not** the graceful ladder [`Self::wait`] uses. That ladder
    /// gives a well-behaved child up to eight seconds to notice a closed stdin
    /// or a Ctrl-Close, which is right for a shutdown and wrong for a caller who
    /// asked to terminate: `SandboxProcess::kill` promises to kill, and a
    /// cancellation path that takes eight seconds to act reads as a hang.
    ///
    /// The post-kill wait is **bounded**. `WaitForExit(0)` means INFINITE here,
    /// so waiting on the assumption that `Terminate` succeeded would wedge this
    /// call forever if it ever failed against a live process.
    ///
    /// That bound covers *this call only*. A caller that also owns a waiter must
    /// not infer completion from `Ok(())` and unconditionally join it. The PTY
    /// streaming adapter joins only an already-finished waiter during drop and
    /// otherwise detaches it, keeping handle destruction bounded.
    ///
    /// **What this does not tell you.** The bounded wait's result is discarded,
    /// so a `Terminate` the platform accepted but that left the process running
    /// still yields `Ok(())`. What *is* now reported is the distinction between
    /// an accepted request and a refused one: the `Err` this returns reaches the
    /// caller through `ExecHandle::terminator` and `SandboxProcess::kill`.
    /// Confirming the process actually died would need the bounded wait's result
    /// as well, which this type does not carry.
    pub(super) fn terminate(&self) -> Result<(), IsolationSessionError> {
        if let Err(error) = self.process.Terminate() {
            self.record_kill_failed(error.code().0);
            return Err(transport_err(op::RUN_PROCESS, "Terminate failed", &error));
        }
        // Bounded rather than INFINITE so a `Terminate` that was accepted but
        // never took effect cannot park the caller inside this function. The
        // result is discarded because there is nowhere to report it; see the
        // note above, which also covers why this does not bound teardown.
        let _ = self.process.WaitForExit(TERMINATE_WAIT_MS);
        Ok(())
    }

    /// Force-terminate and confirm within a bounded wait that the process is gone.
    ///
    /// Setup-failure paths cannot return a public process handle, so unlike
    /// [`Self::terminate`] they must not report success merely because the
    /// terminate request was accepted.
    fn terminate_and_confirm(&self) -> Result<(), IsolationSessionError> {
        let termination_error = self.process.Terminate().err();
        if let Some(error) = &termination_error {
            self.record_kill_failed(error.code().0);
        }
        let waited = self
            .process
            .WaitForExit(TERMINATE_WAIT_MS)
            .map_err(|error| transport_err(op::RUN_PROCESS, "WaitForExit failed", &error))?;
        let exit_code =
            if waited == WAIT_FOR_EXIT_TIMEOUT {
                Some(self.process.ExitCode().map_err(|error| {
                    transport_err(op::RUN_PROCESS, "get ExitCode failed", &error)
                })?)
            } else {
                None
            };
        if termination_is_confirmed(waited, exit_code) {
            return Ok(());
        }
        if let Some(error) = termination_error {
            return Err(transport_err(op::RUN_PROCESS, "Terminate failed", &error));
        }
        Err(lifecycle_err(
            "the sandboxed process was still running after the bounded terminate wait",
        ))
    }
}

/// Owns the relay threads and the workload for the span of `create_process`.
///
/// [`finish`](Self::finish) tears down a workload that has already exited.
/// Dropping without it abandons the run: the workload is terminated so the
/// output relays reach EOF. Every join is bounded, so a relay whose read never
/// returns cannot wedge the caller's thread.
struct RelayScope<'a> {
    process: &'a IsoSessionProcess,
    stop_event: HANDLE,
    stdout: Option<OwnedHandle>,
    stderr: Option<OwnedHandle>,
    stdin: Option<OwnedHandle>,
    /// Ends the output relays' reads. A descendant that inherited the write
    /// ends keeps them open past the workload's exit, so EOF alone is not a
    /// bound.
    output_cancellers: Vec<PipeReadCanceller>,
    finished: bool,
}

impl<'a> RelayScope<'a> {
    const JOIN_MS: u32 = 1000;
    /// Expiry cancels the read, dropping an in-flight chunk.
    const DRAIN_MS: u32 = 5000;

    fn new(process: &'a IsoSessionProcess, stop_event: HANDLE) -> Self {
        Self {
            process,
            stop_event,
            stdout: None,
            stderr: None,
            stdin: None,
            output_cancellers: Vec::new(),
            finished: false,
        }
    }

    fn signal_stop(&self) {
        // SAFETY: the event outlives this scope.
        unsafe {
            let _ = SetEvent(self.stop_event);
        }
    }

    fn cancel_output_reads(&self) {
        for canceller in &self.output_cancellers {
            canceller.close();
        }
    }

    /// Whether the relay exited. An absent relay was never spawned.
    fn join(relay: &Option<OwnedHandle>, timeout_ms: u32) -> bool {
        match relay {
            // SAFETY: an owned thread handle held by this scope.
            Some(t) => (unsafe { WaitForSingleObject(t.get(), timeout_ms) }) == WAIT_OBJECT_0,
            None => true,
        }
    }

    /// Each relay reads its own duplicate, so one still running does not keep
    /// the pipe handles alive.
    fn close_handles(&self) {
        let _ = self.process.Close();
    }

    fn stop_stdin(&self) {
        self.signal_stop();
        Self::join(&self.stdin, Self::JOIN_MS);
    }

    /// Teardown for a workload that has already exited.
    fn finish(&mut self) {
        self.signal_stop();
        let stdout_drained = Self::join(&self.stdout, Self::DRAIN_MS);
        let stderr_drained = Self::join(&self.stderr, Self::DRAIN_MS);
        if !(stdout_drained && stderr_drained) {
            self.cancel_output_reads();
            Self::join(&self.stdout, Self::JOIN_MS);
            Self::join(&self.stderr, Self::JOIN_MS);
        }
        Self::join(&self.stdin, Self::JOIN_MS);
        self.close_handles();
        self.finished = true;
    }
}

impl Drop for RelayScope<'_> {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        self.signal_stop();
        self.cancel_output_reads();
        let _ = self.process.Terminate();
        Self::join(&self.stdout, Self::JOIN_MS);
        Self::join(&self.stderr, Self::JOIN_MS);
        Self::join(&self.stdin, Self::JOIN_MS);
        self.close_handles();
    }
}

/// A [`StartedProcess`] that releases the session process's pipe handles when
/// it goes out of scope.
///
/// Close-on-drop is **opt-in per consumer** rather than a property of
/// [`StartedProcess`] itself, because the two topologies need opposite things:
///
/// - The streaming consumer has no other teardown point — it hands the handles
///   to an in-process caller and never returns to this crate — so without this
///   a long-lived host would leak three handles per exec, and that host is
///   exactly who the streaming path exists for.
/// - [`IsolationSessionManager::create_process`] must **not** close on the way
///   out: `RelayScope` owns that teardown and runs it once the relays are done.
pub(super) struct ClosingProcess {
    started: StartedProcess,
    /// The impersonation of the manager that started the process.
    impersonation: Impersonation,
    /// Keeps the apartment alive: the threads that use the object may have none.
    _mta: MtaReference,
}

impl ClosingProcess {
    pub(super) fn new(
        started: StartedProcess,
        impersonation: Impersonation,
        mta: MtaReference,
    ) -> Self {
        Self {
            started,
            impersonation,
            _mta: mta,
        }
    }

    pub(super) fn resize_console(
        &self,
        columns: u16,
        rows: u16,
    ) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            self.process
                .ResizeConsole(columns, rows)
                .map_err(|error| lifecycle_err(format!("ResizeConsole failed: {error}")))
        })
    }

    pub(super) fn close_standard_input(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || {
            self.process
                .CloseStandardInput()
                .map_err(|error| lifecycle_err(format!("CloseStandardInput failed: {error}")))
        })
    }

    pub(super) fn wait_for_exit(
        &self,
        timeout_ms: u32,
    ) -> Result<ExecOutcome, IsolationSessionError> {
        owned_thread::call(&self.impersonation, || self.wait(timeout_ms))
    }

    pub(super) fn terminate_process(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || self.terminate())
    }

    pub(super) fn terminate_and_confirm_process(&self) -> Result<(), IsolationSessionError> {
        owned_thread::call(&self.impersonation, || self.terminate_and_confirm())
    }
}

impl std::ops::Deref for ClosingProcess {
    type Target = StartedProcess;

    fn deref(&self) -> &Self::Target {
        &self.started
    }
}

impl Drop for ClosingProcess {
    fn drop(&mut self) {
        let process = &self.started.process;
        let _ = owned_thread::call(&self.impersonation, || {
            let _ = process.Close();
            Ok(())
        });
    }
}

/// `STILL_ACTIVE` (0x103) is exposed by the `windows` crate as
/// `STATUS_PENDING: NTSTATUS` — same numeric value, different name. A process
/// whose `ExitCode()` reads this has not exited.
///
/// **Not sufficient on its own to prove a process is running.** 259 is a legal
/// exit code, so a workload that exits with it is indistinguishable here from
/// one that never exited. Every liveness decision in this file therefore pairs
/// this with a second, independent signal; see [`StartedProcess::wait`].
const STILL_ACTIVE: i32 = windows::Win32::Foundation::STATUS_PENDING.0;

/// What `WaitForExit` returns when the deadline elapses before the process
/// exits. Like [`STILL_ACTIVE`] this is a legal exit code in its own right, so
/// it is never used alone to conclude a timeout.
const WAIT_FOR_EXIT_TIMEOUT: i32 = -1;

/// How long [`StartedProcess::terminate`] waits for a kill to land before
/// reporting success anyway. Bounded so a failed `Terminate` cannot wedge that
/// call; generous enough that a normal kill is observed synchronously.
const TERMINATE_WAIT_MS: u32 = 5_000;

fn termination_is_confirmed(waited: i32, exit_code: Option<i32>) -> bool {
    waited != WAIT_FOR_EXIT_TIMEOUT || exit_code.is_some_and(|code| code != STILL_ACTIVE)
}

/// What [`StartedProcess::wait`] should do once its wait has returned.
///
/// A value rather than a branch inside `wait`, because `wait` needs a live COM
/// process object and cannot be exercised on a host without the OS-side
/// service — so the decision it hinges on would otherwise be untestable, and a
/// regression in it silently undetectable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum WaitPlan {
    /// The process exited within its deadline, or there was no deadline. This
    /// is its exit code. **The shutdown ladder must not run** — it cannot
    /// distinguish a 259 exit from a live process.
    Exited(i32),
    /// The deadline elapsed and the process is **still running**. It must be
    /// killed and confirmed dead before a timeout is reported.
    KillThenReportTimeout,
    /// The deadline elapsed, and the process then exited on its own before it
    /// could be sampled. There is nothing left to kill — the exit-code read is
    /// itself the confirmation the process is gone — but the outcome is still a
    /// timeout, because the caller's deadline was spent while it ran.
    ///
    /// Reporting the later-observed exit code here instead would hide a missed
    /// deadline. The sibling WSLc backend makes the same distinction, tracking
    /// `deadline_elapsed` separately from `timed_out` so a spent deadline is
    /// "reported stickily rather than a later-observed exit code".
    TimedOutAfterDeadline,
}

/// Decides what a completed `WaitForExit` means.
///
/// Split out from [`StartedProcess::wait`] so the rule is exercisable without an
/// OS-side isolation session: every input here is a plain integer, while the
/// call it guards needs a live process object.
///
/// `exit_code` is a closure rather than a value so the ordinary case costs no
/// extra COM round-trip — it is consulted only for the one `waited` value that
/// could mean a timeout. See [`StartedProcess::wait`] for why one signal alone
/// is not enough.
fn plan_wait(
    timeout_ms: u32,
    waited: i32,
    exit_code: impl FnOnce() -> Result<i32, IsolationSessionError>,
) -> Result<WaitPlan, IsolationSessionError> {
    // INFINITE: there was no deadline to miss, so the wait returned because the
    // process exited, and `waited` is its code.
    if timeout_ms == 0 || waited != WAIT_FOR_EXIT_TIMEOUT {
        return Ok(WaitPlan::Exited(waited));
    }
    // The sentinel alone proves nothing — a workload may exit with -1 — so the
    // exit code is the second, independent signal.
    let code = exit_code()?;
    match code {
        // Still running: the deadline is spent and the process must be killed.
        STILL_ACTIVE => Ok(WaitPlan::KillThenReportTimeout),
        // Genuinely ambiguous, and the one case that cannot be resolved: the
        // wait returned -1 and the process's code *is* -1, so the sentinel is
        // indistinguishable from a natural exit. Read as the exit.
        WAIT_FOR_EXIT_TIMEOUT => Ok(WaitPlan::Exited(WAIT_FOR_EXIT_TIMEOUT)),
        // The process is gone, and its code is not -1 — so the -1 the wait
        // returned cannot have been that code, and was therefore the timeout
        // sentinel. The deadline provably elapsed while the process ran, and it
        // exited in the window before this sample.
        _ => Ok(WaitPlan::TimedOutAfterDeadline),
    }
}

/// Three-tier graceful shutdown for an `IsoSessionProcess` that's still
/// running after `WaitForExit(timeout_ms)` returns. Tier 1: close stdin —
/// many REPLs exit on EOF alone. Tier 2: `SendCtrlClose` — ConPTY-only;
/// `E_NOTIMPL` outside ConPTY, benign. Tier 3: force-terminate, wait
/// infinitely (`WaitForExit(0)` = INFINITE) for the kill to land.
///
/// The first `ExitCode()` query is `?`-propagated: a failure there means
/// the kernel handle is broken, and the cleanup methods on the same
/// handle are unlikely to make progress — better to surface the COM error
/// than to fire blind. Per-tier subsequent queries fall back to
/// `STILL_ACTIVE` so a transient read failure does not short-circuit the
/// escalation.
///
/// # What this does not tell you
///
/// The returned code cannot distinguish a process that exited with 259 from
/// one that is still running, because `ExitCode()` reports 259 for both. A
/// caller that needs that distinction must establish it separately —
/// [`StartedProcess::wait`] does, which is why it only calls this once it has
/// independently determined the process was still running.
fn wait_with_graceful_shutdown(
    process: &IsoSessionProcess,
) -> Result<(i32, Option<i32>), IsolationSessionError> {
    let mut exit_code = process
        .ExitCode()
        .map_err(|e| transport_err(op::RUN_PROCESS, "get ExitCode failed", &e))?;
    if exit_code != STILL_ACTIVE {
        return Ok((exit_code, None));
    }

    let _ = process.CloseStandardInput();
    let _ = process.WaitForExit(5000);
    exit_code = process.ExitCode().unwrap_or(STILL_ACTIVE);
    if exit_code != STILL_ACTIVE {
        return Ok((exit_code, None));
    }

    let _ = process.SendCtrlClose();
    let _ = process.WaitForExit(3000);
    exit_code = process.ExitCode().unwrap_or(STILL_ACTIVE);
    if exit_code != STILL_ACTIVE {
        return Ok((exit_code, None));
    }

    let terminate_error = process.Terminate().err().map(|error| error.code().0);
    let _ = process.WaitForExit(0);
    // Unchanged from before the exec-handle reshape: this path serves the
    // executor, which needs an exit code and has no timeout channel. Failing
    // here on a 259 read would turn a workload that legitimately exited with
    // 259 into a backend error on the CLI.
    Ok((process.ExitCode().unwrap_or(-1), terminate_error))
}

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

    #[test]
    fn bounded_termination_requires_confirmation_after_a_timeout_sentinel() {
        assert!(termination_is_confirmed(0, None));
        assert!(termination_is_confirmed(
            WAIT_FOR_EXIT_TIMEOUT,
            Some(WAIT_FOR_EXIT_TIMEOUT)
        ));
        assert!(!termination_is_confirmed(
            WAIT_FOR_EXIT_TIMEOUT,
            Some(STILL_ACTIVE)
        ));
    }

    #[test]
    fn teardown_status_distinguishes_failure_success_and_skipped() {
        assert_eq!(TeardownOutcome::default().status(), TeardownStatus::Skipped);
        assert_eq!(
            TeardownOutcome {
                session_stopped: Some(true),
                agent_user_deprovisioned: Some(true),
            }
            .status(),
            TeardownStatus::Success
        );
        assert_eq!(
            TeardownOutcome {
                session_stopped: Some(true),
                ..Default::default()
            }
            .status(),
            TeardownStatus::Success
        );
        assert_eq!(
            TeardownOutcome {
                session_stopped: Some(true),
                agent_user_deprovisioned: Some(false),
            }
            .status(),
            TeardownStatus::Failure
        );
    }

    #[test]
    fn teardown_record_satisfies_the_requirement_contract() {
        let outcome = TeardownOutcome {
            session_stopped: Some(true),
            agent_user_deprovisioned: Some(false),
        };
        let event = AuditEvent::new(AuditEventName::SandboxTornDown)
            .str("backend", "isolation_session")
            .str("identity", AGENT_IDENTITY_MARKER)
            .str("phase", "deprovision")
            .str("status", outcome.status().as_str())
            .bool("agent_user_deprovisioned", false);
        assert!(event.missing_required_fields().is_empty());
        assert!(event.to_json_line().contains(r#""status":"failure""#));
    }

    /// The exit code a timed-out process reads, paired with the `WaitForExit`
    /// return that accompanies it.
    fn probe(value: i32) -> impl FnOnce() -> Result<i32, IsolationSessionError> {
        move || Ok(value)
    }

    #[test]
    fn timeout_needs_both_signals_not_either() {
        // The real timeout: both signals present, and the ladder must run.
        assert_eq!(
            plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(STILL_ACTIVE)).unwrap(),
            WaitPlan::KillThenReportTimeout
        );

        // A workload that exits with the wait sentinel's value. `WaitForExit`
        // reports the code rather than -1, so this is an exit.
        assert_eq!(
            plan_wait(5_000, -1, probe(-1)).unwrap(),
            WaitPlan::Exited(-1)
        );

        // A workload that exits 259 — the value `STILL_ACTIVE` also has. The
        // wait returned the code, not the sentinel, so this is an exit too.
        // Critically it must NOT be planned for the ladder: the ladder reads
        // 259 from `ExitCode()` and cannot tell it from a live process, which
        // is how a clean exit-259 became a backend error.
        assert_eq!(
            plan_wait(5_000, STILL_ACTIVE, probe(STILL_ACTIVE)).unwrap(),
            WaitPlan::Exited(STILL_ACTIVE)
        );

        // An ordinary exit.
        assert_eq!(plan_wait(5_000, 0, probe(0)).unwrap(), WaitPlan::Exited(0));
    }

    /// The sentinel with a non-`STILL_ACTIVE`, non-`-1` code means the deadline
    /// was spent and the process then exited on its own.
    ///
    /// The regression this pins: reporting that later-observed exit code hides
    /// a missed deadline. The `-1` the wait returned cannot have been the
    /// process's code (its code is 7), so it was the timeout sentinel and the
    /// deadline provably elapsed while the process ran.
    #[test]
    fn a_deadline_spent_before_a_late_exit_is_still_a_timeout() {
        assert_eq!(
            plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(7)).unwrap(),
            WaitPlan::TimedOutAfterDeadline
        );
        assert_eq!(
            plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(0)).unwrap(),
            WaitPlan::TimedOutAfterDeadline,
            "a clean exit past the deadline is still a missed deadline"
        );
    }

    /// The one irreducible collision: sentinel and exit code are both `-1`, so
    /// nothing distinguishes a timeout from a workload that exited with `-1`.
    #[test]
    fn the_sentinel_colliding_with_a_real_minus_one_exit_is_read_as_the_exit() {
        assert_eq!(
            plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, probe(-1)).unwrap(),
            WaitPlan::Exited(-1)
        );
    }

    #[test]
    fn infinite_timeout_can_never_be_a_timeout() {
        // 0 means INFINITE. Even with the sentinel apparently present, a wait
        // with no deadline did not miss one. This is the default, so the guard
        // covers the common configuration rather than an exotic one.
        assert_eq!(
            plan_wait(0, WAIT_FOR_EXIT_TIMEOUT, probe(STILL_ACTIVE)).unwrap(),
            WaitPlan::Exited(WAIT_FOR_EXIT_TIMEOUT)
        );
    }

    #[test]
    fn exit_code_is_not_queried_unless_it_could_change_the_answer() {
        let calls = std::cell::Cell::new(0);
        let counting = || {
            calls.set(calls.get() + 1);
            Ok(STILL_ACTIVE)
        };
        assert_eq!(plan_wait(5_000, 0, counting).unwrap(), WaitPlan::Exited(0));
        assert_eq!(calls.get(), 0, "no COM round-trip for a plain exit");
    }

    #[test]
    fn unreadable_exit_code_propagates_rather_than_guessing() {
        let err = plan_wait(5_000, WAIT_FOR_EXIT_TIMEOUT, || {
            Err(lifecycle_err("handle is broken"))
        });
        assert!(
            err.is_err(),
            "a failed probe must not be reported as an exit"
        );
    }

    #[test]
    fn feature_unavailable_returns_clean_error() {
        // Initialize COM (required for WinRT activation).
        let _ = unsafe {
            windows::Win32::System::Com::CoInitializeEx(
                None,
                windows::Win32::System::Com::COINIT_MULTITHREADED,
            )
        };

        match check_service_available_and_activate() {
            Ok(_ops) => {
                // Service IS available on this machine (e.g., a test VM
                // with the feature enabled). The test is not applicable
                // — skip.
            }
            Err(IsolationSessionError::ServiceUnavailable(failure)) => {
                // Service is NOT available. Verify the error is clean and
                // descriptive (not a panic or cryptic COM error), and that
                // it names the activation operation it failed on.
                assert!(
                    failure.message.contains("not available")
                        || failure.message.contains("activation failed"),
                    "Expected descriptive error message, got: {}",
                    failure.message
                );
                assert_eq!(failure.operation, op::ACTIVATE);
                assert!(
                    failure.code.is_some(),
                    "activation failure carries no HRESULT"
                );
            }
            Err(other) => {
                panic!("expected ServiceUnavailable variant, got: {:?}", other);
            }
        }
    }

    #[test]
    fn feature_support_requires_a_positive_feature_level() {
        // Supported: any positive level.
        assert!(feature_supported_from(Ok(1)));
        assert!(feature_supported_from(Ok(7)));

        // Not supported: the host knows the feature but does not offer it.
        assert!(!feature_supported_from(Ok(0)));
        assert!(!feature_supported_from(Ok(-1)));

        // Not supported: an older host rejects the unknown feature value.
        assert!(!feature_supported_from(Err(
            windows_core::Error::from_hresult(
                windows_core::HRESULT(0x8007_0057u32 as i32), // E_INVALIDARG
            )
        )));
    }
}