meerkat 0.8.32

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

#![cfg(all(feature = "session-store", not(target_arch = "wasm32")))]

use std::sync::Arc;

use crate::LlmClient;
use meerkat_core::error::AgentError;
use meerkat_core::handles::GeneratedAuthLeaseHandle;
use meerkat_core::lifecycle::run_primitive::TurnMetadataOverride;
use meerkat_core::service::SessionError;
use meerkat_core::types::SessionId;
use meerkat_core::{
    AgentLlmClient, AgentLlmClientDecorator, Config, ConfigRuntime, ModelRegistry,
    SessionLlmIdentity, SessionToolVisibilityState,
};
use meerkat_runtime::{
    HydratedSessionLlmState, ResolvedSessionLlmReconfigure, RuntimeDriverError,
    SessionLlmCapabilitySurface, SessionLlmCapabilitySurfaceStatus, SessionLlmReconfigureHost,
    SessionLlmReconfigureRequest,
};
use meerkat_session::{EphemeralSessionService, PersistentSessionService};

use crate::StagedSessionRegistry;
use crate::factory::AgentFactory;
use crate::service_factory::FactoryAgentBuilder;
use crate::session_runtime::recovery::parse_provider_override;

/// Convert a session-service error into the runtime-driver error shape
/// expected by [`SessionLlmReconfigureHost`] callers.
pub fn session_error_to_runtime_driver(err: SessionError) -> RuntimeDriverError {
    match err {
        SessionError::NotFound { .. } => RuntimeDriverError::NotReady {
            state: meerkat_runtime::RuntimeState::Destroyed,
        },
        other => RuntimeDriverError::Internal(other.to_string()),
    }
}

/// Convert a runtime-driver error back into a session-service error.
pub fn runtime_driver_error_to_session_error(err: RuntimeDriverError) -> SessionError {
    SessionError::Agent(AgentError::InternalError(err.to_string()))
}

/// Resolve a model profile into the typed capability surface a session
/// LLM identity carries through reconfigurations.
pub fn profile_to_capability_surface(
    profile: &meerkat_core::model_profile::ModelProfile,
) -> SessionLlmCapabilitySurface {
    SessionLlmCapabilitySurface {
        supports_temperature: profile.supports_temperature,
        supports_thinking: profile.supports_thinking,
        supports_reasoning: profile.supports_reasoning,
        inline_video: profile.inline_video,
        vision: profile.vision,
        image_input: profile.image_input,
        image_tool_results: profile.image_tool_results,
        supports_web_search: profile.supports_web_search,
        supports_mid_conversation_system_messages: profile
            .supports_mid_conversation_system_messages,
        image_generation: profile.image_generation,
        realtime: profile.realtime,
        call_timeout_secs: profile.call_timeout_secs,
    }
}

/// Validate that the registered model entry for `(provider, model)` is
/// consistent with the request override; returns a human-readable
/// rejection reason on mismatch.
pub fn registered_model_provider_mismatch_reason(
    registry: &ModelRegistry,
    provider: meerkat_core::Provider,
    model: &str,
) -> Option<String> {
    registry.provider_override_mismatch_reason(provider, model)
}

/// Adapt the runtime request's wire-facing provider string onto the core-owned
/// session identity resolver. Model/provider ownership, self-hosted alias
/// resolution, metadata tri-state, and stale-auth clearing remain singular in
/// `meerkat_core::resolve_session_llm_identity_override`.
fn resolve_reconfigure_target_llm_identity(
    registry: &ModelRegistry,
    current: &SessionLlmIdentity,
    request: &SessionLlmReconfigureRequest,
) -> Result<SessionLlmIdentity, RuntimeDriverError> {
    let provider = request
        .provider
        .as_deref()
        .map(parse_provider_override)
        .transpose()
        .map_err(|reason| RuntimeDriverError::ValidationFailed { reason })?;

    meerkat_core::resolve_session_llm_identity_override(
        current,
        registry,
        meerkat_core::SessionLlmIdentityOverride {
            model: request.model.as_deref(),
            provider,
            self_hosted_server_id: request.self_hosted_server_id.as_deref(),
            provider_params: request
                .provider_params
                .as_ref()
                .map(TurnMetadataOverride::as_ref),
            auth_binding: request
                .auth_binding
                .as_ref()
                .map(TurnMetadataOverride::as_ref),
        },
    )
    .map_err(|error| RuntimeDriverError::ValidationFailed {
        reason: error.to_string(),
    })
}

fn preserve_credential_account_affinity(
    config: &Config,
    current: &SessionLlmIdentity,
    request: &SessionLlmReconfigureRequest,
    target: &mut SessionLlmIdentity,
) -> Result<(), RuntimeDriverError> {
    if request.auth_binding.is_some()
        || target.auth_binding.is_some()
        || target.provider == current.provider
    {
        return Ok(());
    }
    let Some(meerkat_core::AuthCredentialIdentity::Account(account)) =
        AgentFactory::credential_identity_for_llm_identity(config, current).map_err(|error| {
            RuntimeDriverError::ValidationFailed {
                reason: error.to_string(),
            }
        })?
    else {
        return Ok(());
    };
    let route = meerkat_core::resolve_credential_account_binding_for_provider(
        config,
        target.provider,
        &account,
    )
    .map_err(|error| RuntimeDriverError::ValidationFailed {
        reason: error.to_string(),
    })?
    .ok_or_else(|| RuntimeDriverError::ValidationFailed {
        reason: format!(
            "provider switch to '{}' has no route sharing credential account '{}:{}'; set auth_binding explicitly to change accounts",
            target.provider.as_str(),
            account.realm,
            account.account
        ),
    })?;
    target.auth_binding = Some(route.auth_binding);
    Ok(())
}

/// Resolve a model-only switch target through the canonical seams.
///
/// Model-only is the whole point: provider, provider parameters, and
/// credentials come from the session's current identity plus the existing
/// account-affinity rule, never from the caller. That is what makes it safe to
/// let a model name a target — it can move within what the session was already
/// entitled to, and nowhere else.
pub(crate) fn resolve_model_only_reconfigure_target_identity(
    config: &Config,
    registry: &ModelRegistry,
    current: &SessionLlmIdentity,
    target_model: &str,
) -> Result<SessionLlmIdentity, RuntimeDriverError> {
    let request = SessionLlmReconfigureRequest {
        model: Some(target_model.to_string()),
        provider: None,
        self_hosted_server_id: None,
        provider_params: None,
        auth_binding: None,
    };
    let mut target = resolve_reconfigure_target_llm_identity(registry, current, &request)?;
    preserve_credential_account_affinity(config, current, &request, &mut target)?;
    Ok(target)
}

/// Live-session operations required by the runtime-owned LLM reconfigure
/// transaction.
///
/// Keeping this as a surface-agnostic service capability lets embedded hosts
/// install the same canonical reconfigure host for persistent and ephemeral
/// session services. Persistence remains owned by the concrete service:
/// persistent sessions checkpoint the new identity, while ephemeral sessions
/// intentionally complete that phase as a no-op.
#[async_trait::async_trait]
pub trait SessionRuntimeLlmReconfigureService: Send + Sync {
    /// Acquire the stable outer boundary that serializes live identity changes
    /// with runtime-turn finalization for this exact session.
    async fn acquire_runtime_turn_finalization_guard(
        &self,
        session_id: &SessionId,
    ) -> Result<Box<dyn meerkat_core::lifecycle::CoreExecutorTurnFinalizationGuard>, SessionError>;

    async fn live_llm_identity(
        &self,
        session_id: &SessionId,
    ) -> Result<SessionLlmIdentity, SessionError>;

    /// Whether the live ordered transcript contains typed instruction
    /// activation rows whose placement the target model must preserve.
    async fn live_session_has_instruction_activations(
        &self,
        session_id: &SessionId,
    ) -> Result<bool, SessionError>;

    /// Return the exact realm that owned the live session's initial build.
    ///
    /// Hot-swap credential resolution must begin from this per-session realm,
    /// not from the service-wide config head, because one runtime can host
    /// sessions (notably mob members) from several child realms.
    async fn live_realm_id(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<meerkat_core::RealmId>, SessionError>;

    async fn live_tool_visibility_state(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<SessionToolVisibilityState>, SessionError>;

    async fn live_web_search_override(
        &self,
        session_id: &SessionId,
    ) -> Result<meerkat_core::ToolCategoryOverride, SessionError>;

    async fn live_tool_scope_snapshot(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<meerkat_core::ToolScopeSnapshot>, SessionError>;

    async fn apply_live_llm_identity_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
        client: Arc<dyn AgentLlmClient>,
        identity: SessionLlmIdentity,
        request_policy: meerkat_core::SessionLlmRequestPolicy,
    ) -> Result<(), SessionError>;

    async fn apply_live_tool_visibility_state_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
        state: Option<SessionToolVisibilityState>,
    ) -> Result<(), SessionError>;

    async fn persist_live_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
    ) -> Result<(), SessionError>;

    async fn discard_live_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
    ) -> Result<(), SessionError>;

    /// Read the committed model-routing handoff log from the live session.
    async fn live_model_routing_control_history(
        &self,
        session_id: &SessionId,
    ) -> Result<
        meerkat_core::session::model_routing_control::SessionModelRoutingControlHistory,
        SessionError,
    >;

    /// Append one resolution to that log and durably commit it as ONE guarded
    /// operation.
    ///
    /// Deliberately not `append` + `persist`: those interleave, and a failure
    /// between them leaves the live session reporting a resolution the durable
    /// log never received. Implementations must leave nothing settled in live
    /// state that is not on disk.
    ///
    /// Takes `Arc<Self>` so an implementation can move the transaction into a
    /// task it owns. Cancelling the caller must not be able to tear the pair in
    /// half, and an implementation cannot offer that if the only handle it has
    /// is borrowed from the caller's frame.
    async fn commit_model_routing_control_record_durable_first(
        self: Arc<Self>,
        session_id: &SessionId,
        record: meerkat_core::session::model_routing_control::SessionModelRoutingControlRecord,
    ) -> Result<(), SessionError>;
}

async fn preferred_hot_swap_realm(
    service: &dyn SessionRuntimeLlmReconfigureService,
    session_id: &SessionId,
    fallback_realm: Option<meerkat_core::RealmId>,
) -> Result<Option<meerkat_core::RealmId>, RuntimeDriverError> {
    Ok(service
        .live_realm_id(session_id)
        .await
        .map_err(session_error_to_runtime_driver)?
        .or(fallback_realm))
}

#[async_trait::async_trait]
impl SessionRuntimeLlmReconfigureService for PersistentSessionService<FactoryAgentBuilder> {
    async fn acquire_runtime_turn_finalization_guard(
        &self,
        session_id: &SessionId,
    ) -> Result<Box<dyn meerkat_core::lifecycle::CoreExecutorTurnFinalizationGuard>, SessionError>
    {
        Ok(Box::new(
            PersistentSessionService::<FactoryAgentBuilder>::acquire_runtime_turn_finalization_guard(
                self,
                session_id,
            )
            .await,
        ))
    }

    async fn live_llm_identity(
        &self,
        session_id: &SessionId,
    ) -> Result<SessionLlmIdentity, SessionError> {
        self.live_session_llm_identity(session_id).await
    }

    async fn live_session_has_instruction_activations(
        &self,
        session_id: &SessionId,
    ) -> Result<bool, SessionError> {
        Ok(self
            .export_live_session(session_id)
            .await?
            .messages()
            .iter()
            .any(|message| {
                matches!(
                    message,
                    meerkat_core::Message::System(system)
                        if system.instruction_activation.is_some()
                )
            }))
    }

    async fn live_realm_id(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<meerkat_core::RealmId>, SessionError> {
        Ok(self
            .export_live_session(session_id)
            .await?
            .session_metadata()
            .and_then(|metadata| metadata.realm_id))
    }

    async fn live_tool_visibility_state(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<SessionToolVisibilityState>, SessionError> {
        self.export_live_session(session_id)
            .await?
            .try_tool_visibility_state()
            .map_err(|error| {
                SessionError::Agent(AgentError::InternalError(format!(
                    "invalid canonical tool visibility state: {error}"
                )))
            })
    }

    async fn live_web_search_override(
        &self,
        session_id: &SessionId,
    ) -> Result<meerkat_core::ToolCategoryOverride, SessionError> {
        Ok(self
            .export_live_session(session_id)
            .await?
            .session_metadata()
            .map(|metadata| metadata.tooling.web_search)
            .unwrap_or(meerkat_core::ToolCategoryOverride::Inherit))
    }

    async fn live_tool_scope_snapshot(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<meerkat_core::ToolScopeSnapshot>, SessionError> {
        self.tool_scope_snapshot(session_id).await
    }

    async fn apply_live_llm_identity_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
        client: Arc<dyn AgentLlmClient>,
        identity: SessionLlmIdentity,
        request_policy: meerkat_core::SessionLlmRequestPolicy,
    ) -> Result<(), SessionError> {
        self.apply_runtime_session_llm_identity_under_runtime_turn_boundary(
            session_id,
            client,
            identity,
            request_policy,
        )
        .await
    }

    async fn apply_live_tool_visibility_state_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
        state: Option<SessionToolVisibilityState>,
    ) -> Result<(), SessionError> {
        self.apply_runtime_session_tool_visibility_state_under_runtime_turn_boundary(
            session_id, state,
        )
        .await
    }

    async fn persist_live_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
    ) -> Result<(), SessionError> {
        self.persist_live_session_now_under_runtime_turn_boundary(session_id)
            .await
            .map(|_| ())
    }

    async fn discard_live_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
    ) -> Result<(), SessionError> {
        self.discard_live_session_under_runtime_turn_boundary(session_id)
            .await
    }

    /// Read the committed handoff log, preferring the live actor and falling
    /// back to committed authority when no actor is materialized.
    ///
    /// `export_live_session` reports `SessionError::NotFound` for BOTH "this
    /// session does not exist" and "this session has no live actor right now"
    /// (its `NoLive` / `DurableAuthoritative` arms). Between turns — which is
    /// exactly when the pre-dequeue seam runs — having no live actor is an
    /// ordinary shape: the session may be staged, mid-materialization, or
    /// simply idle with its actor discarded.
    ///
    /// Treating that as a read failure stops the runtime loop; treating it as
    /// an empty log would be worse, because it would silently drop a committed
    /// handoff. So absence of a LIVE actor falls through to the COMMITTED
    /// authority, which is where committed records actually live. Only a
    /// session with no durable body at all yields an empty log, and such a
    /// session has by construction committed nothing.
    ///
    /// The classification matches the structured `NotFound` variant, never
    /// message text, and every other error propagates unchanged.
    async fn live_model_routing_control_history(
        &self,
        session_id: &SessionId,
    ) -> Result<
        meerkat_core::session::model_routing_control::SessionModelRoutingControlHistory,
        SessionError,
    > {
        // COMMITTED authority first, live only as a fallback.
        //
        // Every caller of this read is a pre-dequeue or realization decision,
        // and those must be made against what is actually on disk. Preferring
        // the live projection would let a terminal that exists live but never
        // committed answer "this request is settled" — and the request would
        // stop being owed with nothing durable behind it. Reading committed
        // authority makes a live-only terminal unobservable to the decision,
        // which is what keeps the debt visible until the commit truly lands.
        //
        // Safe precisely here: this runs between turns, under the held
        // turn-finalization boundary, so no run is mid-flight and committed
        // authority is complete rather than trailing a live session.
        //
        // The live fallback covers the session that has no durable row yet
        // (created, never persisted): committed authority reports nothing, and
        // the live actor is then the only carrier there is.
        let committed = self
            .observe_authoritative_session_body(session_id)
            .await?
            .map(|session| session.model_routing_control().clone());
        if let Some(committed) = committed {
            return Ok(committed);
        }
        match self.export_live_session(session_id).await {
            Ok(session) => Ok(session.model_routing_control().clone()),
            Err(SessionError::NotFound { .. }) => Ok(Default::default()),
            Err(error) => Err(error),
        }
    }

    async fn commit_model_routing_control_record_durable_first(
        self: Arc<Self>,
        session_id: &SessionId,
        record: meerkat_core::session::model_routing_control::SessionModelRoutingControlRecord,
    ) -> Result<(), SessionError> {
        PersistentSessionService::<FactoryAgentBuilder>::commit_model_routing_control_record_durable_first(
            self, session_id, record,
        )
        .await
    }
}

#[async_trait::async_trait]
impl SessionRuntimeLlmReconfigureService for EphemeralSessionService<FactoryAgentBuilder> {
    async fn acquire_runtime_turn_finalization_guard(
        &self,
        session_id: &SessionId,
    ) -> Result<Box<dyn meerkat_core::lifecycle::CoreExecutorTurnFinalizationGuard>, SessionError>
    {
        Ok(Box::new(
            EphemeralSessionService::<FactoryAgentBuilder>::acquire_runtime_turn_finalization_guard(
                self,
                session_id,
            )
            .await,
        ))
    }

    async fn live_llm_identity(
        &self,
        session_id: &SessionId,
    ) -> Result<SessionLlmIdentity, SessionError> {
        self.live_session_llm_identity(session_id).await
    }

    async fn live_session_has_instruction_activations(
        &self,
        session_id: &SessionId,
    ) -> Result<bool, SessionError> {
        Ok(self
            .export_session(session_id)
            .await?
            .messages()
            .iter()
            .any(|message| {
                matches!(
                    message,
                    meerkat_core::Message::System(system)
                        if system.instruction_activation.is_some()
                )
            }))
    }

    async fn live_realm_id(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<meerkat_core::RealmId>, SessionError> {
        Ok(self
            .export_session(session_id)
            .await?
            .session_metadata()
            .and_then(|metadata| metadata.realm_id))
    }

    async fn live_tool_visibility_state(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<SessionToolVisibilityState>, SessionError> {
        self.export_session(session_id)
            .await?
            .try_tool_visibility_state()
            .map_err(|error| {
                SessionError::Agent(AgentError::InternalError(format!(
                    "invalid canonical tool visibility state: {error}"
                )))
            })
    }

    async fn live_web_search_override(
        &self,
        session_id: &SessionId,
    ) -> Result<meerkat_core::ToolCategoryOverride, SessionError> {
        Ok(self
            .export_session(session_id)
            .await?
            .session_metadata()
            .map(|metadata| metadata.tooling.web_search)
            .unwrap_or(meerkat_core::ToolCategoryOverride::Inherit))
    }

    async fn live_tool_scope_snapshot(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<meerkat_core::ToolScopeSnapshot>, SessionError> {
        self.tool_scope_snapshot(session_id).await
    }

    async fn apply_live_llm_identity_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
        client: Arc<dyn AgentLlmClient>,
        identity: SessionLlmIdentity,
        request_policy: meerkat_core::SessionLlmRequestPolicy,
    ) -> Result<(), SessionError> {
        self.apply_runtime_session_llm_identity_under_runtime_turn_boundary(
            session_id,
            client,
            identity,
            request_policy,
        )
        .await
    }

    async fn apply_live_tool_visibility_state_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
        state: Option<SessionToolVisibilityState>,
    ) -> Result<(), SessionError> {
        self.apply_runtime_session_tool_visibility_state_under_runtime_turn_boundary(
            session_id, state,
        )
        .await
    }

    async fn persist_live_under_runtime_turn_boundary(
        &self,
        _session_id: &SessionId,
    ) -> Result<(), SessionError> {
        Ok(())
    }

    async fn discard_live_under_runtime_turn_boundary(
        &self,
        session_id: &SessionId,
    ) -> Result<(), SessionError> {
        self.discard_live_session(session_id).await
    }

    /// Ephemeral sessions have no durable boundary, so no committed cross-run
    /// handoff can exist for them. A structurally absent session therefore owes
    /// nothing, and reporting that as an empty log cannot lose a committed
    /// record — there is no durable carrier one could have been written to.
    /// Every other error still propagates.
    async fn live_model_routing_control_history(
        &self,
        session_id: &SessionId,
    ) -> Result<
        meerkat_core::session::model_routing_control::SessionModelRoutingControlHistory,
        SessionError,
    > {
        match self.export_session(session_id).await {
            Ok(session) => Ok(session.model_routing_control().clone()),
            Err(SessionError::NotFound { .. }) => Ok(Default::default()),
            Err(error) => Err(error),
        }
    }

    // Ephemeral sessions have no durable boundary, so a committed cross-run
    // handoff can never exist for them and this can never legitimately be
    // reached. Refusing keeps that impossibility loud instead of recording a
    // resolution into state that is about to disappear.
    async fn commit_model_routing_control_record_durable_first(
        self: Arc<Self>,
        _session_id: &SessionId,
        _record: meerkat_core::session::model_routing_control::SessionModelRoutingControlRecord,
    ) -> Result<(), SessionError> {
        Err(SessionError::Agent(AgentError::ConfigError(
            "ephemeral sessions cannot durably commit model-routing handoff resolutions"
                .to_string(),
        )))
    }
}

/// Captured construction inputs for installing the canonical runtime LLM
/// reconfigure host after a concrete session service has taken ownership of
/// its [`FactoryAgentBuilder`].
///
/// Embedded hosts create this blueprint immediately before moving the builder
/// into a persistent or ephemeral service, then call [`Self::install`] with
/// that concrete service. This keeps adapter/config/auth wiring in Meerkat
/// instead of duplicating it across MobKit and desktop surfaces.
pub struct SessionRuntimeLlmReconfigureHostBlueprint {
    factory: AgentFactory,
    config_store: Arc<dyn meerkat_core::ConfigStore>,
    config_state_path: std::path::PathBuf,
    default_llm_client: Arc<std::sync::RwLock<Option<Arc<dyn LlmClient>>>>,
    agent_llm_client_decorator: Arc<std::sync::RwLock<Option<AgentLlmClientDecorator>>>,
    realm_inheritance: Arc<std::sync::RwLock<Option<crate::RealmInheritance>>>,
}

impl SessionRuntimeLlmReconfigureHostBlueprint {
    pub fn new(
        builder: &FactoryAgentBuilder,
        config_state_path: std::path::PathBuf,
        default_llm_client: Arc<std::sync::RwLock<Option<Arc<dyn LlmClient>>>>,
    ) -> Self {
        Self {
            factory: builder.factory().clone(),
            config_store: builder.runtime_config_store(),
            config_state_path,
            default_llm_client,
            agent_llm_client_decorator: Arc::clone(&builder.default_agent_llm_client_decorator),
            realm_inheritance: Arc::clone(&builder.realm_inheritance),
        }
    }

    fn config_runtime(&self) -> Arc<ConfigRuntime> {
        Arc::new(ConfigRuntime::new(
            Arc::clone(&self.config_store),
            self.config_state_path.clone(),
        ))
    }

    pub fn install(
        self,
        runtime_adapter: &Arc<meerkat_runtime::MeerkatMachine>,
        service: Arc<dyn SessionRuntimeLlmReconfigureService>,
    ) {
        let config_runtime = self.config_runtime();
        runtime_adapter.set_session_llm_reconfigure_host(Arc::new(
            SessionRuntimeLlmReconfigureHost {
                service,
                staged_sessions: Arc::new(StagedSessionRegistry::new()),
                factory: self.factory,
                auth_lease: runtime_adapter.generated_auth_lease_handle(),
                default_llm_client: self.default_llm_client,
                agent_llm_client_decorator: self.agent_llm_client_decorator,
                config_runtime: Arc::new(std::sync::RwLock::new(Some(config_runtime))),
                realm_inheritance: self.realm_inheritance,
            },
        ));
    }
}

/// Surface-agnostic implementation of [`SessionLlmReconfigureHost`].
///
/// Surfaces construct one of these per-call (RPC, REST, MCP, …) so the
/// generated runtime-adapter reconfigure path can hydrate the live session, resolve target
/// identities, build adapters, and apply the swap without depending on
/// any RPC-specific wire shape.
pub struct SessionRuntimeLlmReconfigureHost {
    /// Live session service. Both persistent and ephemeral embedded runtimes
    /// implement the same reconfigure transaction contract.
    pub service: Arc<dyn SessionRuntimeLlmReconfigureService>,
    /// Staged session registry; consulted when the live session is
    /// missing but a staged identity is available.
    pub staged_sessions: Arc<StagedSessionRegistry>,
    /// Agent factory used to build LLM clients/adapters.
    pub factory: AgentFactory,
    /// Auth lease handle threaded into freshly-built clients.
    pub auth_lease: GeneratedAuthLeaseHandle,
    /// Override LLM client (test injection slot).
    pub default_llm_client: Arc<std::sync::RwLock<Option<Arc<dyn LlmClient>>>>,
    /// Default decorator applied to every freshly-built client.
    pub agent_llm_client_decorator: Arc<std::sync::RwLock<Option<AgentLlmClientDecorator>>>,
    /// Optional config runtime for resolving the model registry.
    pub config_runtime: Arc<std::sync::RwLock<Option<Arc<ConfigRuntime>>>>,
    /// Realm parent-chain inheritance (the same shared slot the builder reads).
    /// When populated, the hot-swap / reconfigure path composes the active realm
    /// chain over the raw head config so an inherited (global-owned) credential
    /// binding and self-hosted/provider capabilities resolve on a model swap —
    /// matching the initial agent build. Empty slot => no composition.
    pub realm_inheritance: Arc<std::sync::RwLock<Option<crate::RealmInheritance>>>,
}

impl SessionRuntimeLlmReconfigureHost {
    async fn capability_surface_for_identity(
        &self,
        identity: &SessionLlmIdentity,
    ) -> Result<
        (
            Option<SessionLlmCapabilitySurface>,
            SessionLlmCapabilitySurfaceStatus,
        ),
        RuntimeDriverError,
    > {
        let registry = self.model_registry().await?;
        Ok(
            match registry.profile_for_provider(identity.provider, &identity.model) {
                Some(profile) => (
                    Some(profile_to_capability_surface(&profile)),
                    SessionLlmCapabilitySurfaceStatus::Resolved,
                ),
                None => (None, SessionLlmCapabilitySurfaceStatus::Unresolved),
            },
        )
    }

    async fn hydrate_staged_session_llm_state(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<HydratedSessionLlmState>, RuntimeDriverError> {
        let Some(current_identity) = self
            .staged_sessions
            .effective_llm_identity(session_id)
            .await
            .map_err(|err| RuntimeDriverError::Internal(err.to_string()))?
        else {
            return Ok(None);
        };
        let (current_capability_surface, capability_surface_status) = self
            .capability_surface_for_identity(&current_identity)
            .await?;
        Ok(Some(HydratedSessionLlmState {
            current_identity,
            current_visibility_state: Default::default(),
            current_capability_surface,
            capability_surface_status,
            base_tool_names: std::collections::BTreeSet::new(),
        }))
    }

    async fn model_registry(&self) -> Result<ModelRegistry, RuntimeDriverError> {
        // Compose the realm chain so an inherited self-hosted/custom model entry
        // (e.g. defined in `global`) is visible to capability resolution on a
        // hot-swap, matching the agent build path.
        let config = self.load_config_for_hot_swap().await?;

        config
            .model_registry(meerkat_models::canonical())
            .map_err(|e| {
                RuntimeDriverError::Internal(format!("Failed to resolve model registry: {e}"))
            })
    }

    /// Build the per-identity LLM adapter used by the hot-swap and live
    /// orchestration flows. Public so surfaces (RPC, REST, …) can call
    /// it directly when they need to materialize an adapter outside the
    /// `SessionLlmReconfigureHost` trait surface.
    pub async fn build_adapter_for_llm_identity(
        &self,
        identity: &SessionLlmIdentity,
    ) -> Result<Arc<dyn AgentLlmClient>, RuntimeDriverError> {
        let preferred_realm = self.inheritance_head_realm();
        self.build_adapter_for_llm_identity_in_realm(identity, preferred_realm.as_ref())
            .await
    }

    async fn build_adapter_for_session_llm_identity(
        &self,
        session_id: &SessionId,
        identity: &SessionLlmIdentity,
    ) -> Result<Arc<dyn AgentLlmClient>, RuntimeDriverError> {
        let preferred_realm = preferred_hot_swap_realm(
            self.service.as_ref(),
            session_id,
            self.inheritance_head_realm(),
        )
        .await?;
        self.build_adapter_for_llm_identity_in_realm(identity, preferred_realm.as_ref())
            .await
    }

    fn inheritance_head_realm(&self) -> Option<meerkat_core::RealmId> {
        self.realm_inheritance
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_ref()
            .map(|inheritance| inheritance.head().clone())
    }

    async fn build_adapter_for_llm_identity_in_realm(
        &self,
        identity: &SessionLlmIdentity,
        preferred_realm: Option<&meerkat_core::RealmId>,
    ) -> Result<Arc<dyn AgentLlmClient>, RuntimeDriverError> {
        let default_llm_client = self
            .default_llm_client
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        let raw_client = if let Some(default) = default_llm_client {
            default
        } else {
            let config = self.load_config_for_hot_swap().await?;
            self.factory
                .build_llm_client_for_identity_with_auth_lease_in_realm(
                    &config,
                    identity,
                    Some(self.auth_lease.clone()),
                    preferred_realm,
                )
                .await
                .map_err(|e| {
                    RuntimeDriverError::Internal(format!(
                        "Failed to build LLM client for session identity hot-swap: {e}"
                    ))
                })?
        };

        let adapter = self
            .factory
            .build_llm_adapter_for_identity(raw_client, identity)
            .await
            .map_err(|error| {
                RuntimeDriverError::Internal(format!(
                    "Failed to bind LLM client to session identity hot-swap: {error}"
                ))
            })?;
        let adapter = Arc::new(adapter) as Arc<dyn AgentLlmClient>;
        let decorator = self
            .agent_llm_client_decorator
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        AgentFactory::decorate_agent_llm_client(adapter, decorator.as_ref()).map_err(|error| {
            RuntimeDriverError::Internal(format!(
                "Failed to preserve request-attempt authority during LLM hot-swap: {error}"
            ))
        })
    }

    async fn load_config_for_hot_swap(&self) -> Result<Config, RuntimeDriverError> {
        let config_runtime = self
            .config_runtime
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        let head_config = if let Some(runtime) = config_runtime {
            runtime
                .get()
                .await
                .map(|snapshot| snapshot.config)
                .map_err(|e| {
                    RuntimeDriverError::Internal(format!("Failed to load config for hot-swap: {e}"))
                })?
        } else {
            Config::default()
        };

        // Compose the active realm chain over the head snapshot so a model
        // hot-swap resolves the same inherited (e.g. global-owned) credential
        // binding and self-hosted/provider capabilities as the initial agent
        // build. Without this the swap rebuilds the LLM client from the RAW head
        // config and an inherited binding yields no candidate. Fail-closed: a
        // compose error propagates rather than silently using the raw head.
        let inheritance = self
            .realm_inheritance
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        if let Some(inheritance) = inheritance {
            return inheritance.compose_over(head_config).await.map_err(|e| {
                RuntimeDriverError::Internal(format!(
                    "Failed to compose realm config chain for hot-swap: {e}"
                ))
            });
        }
        Ok(head_config)
    }

    async fn build_request_policy_for_llm_identity(
        &self,
        session_id: &SessionId,
        identity: &SessionLlmIdentity,
    ) -> Result<meerkat_core::SessionLlmRequestPolicy, RuntimeDriverError> {
        let config = self.load_config_for_hot_swap().await?;
        // The session's persisted web-search disable intent
        // (`SessionMetadata.tooling.web_search`) must survive a model hot-swap —
        // otherwise reconfigure would silently re-enable the provider-native
        // web-search body that `--no-web-search` suppressed. Read it from the
        // live session metadata; fail closed to `Inherit` only when the metadata
        // is genuinely unavailable.
        let web_search = match self.service.live_web_search_override(session_id).await {
            Ok(web_search) => web_search,
            Err(_) => meerkat_core::ToolCategoryOverride::Inherit,
        };
        self.factory
            .request_policy_for_session_llm_identity(&config, identity, web_search, session_id)
            .map_err(|e| {
                RuntimeDriverError::Internal(format!(
                    "Failed to build LLM request policy for session {session_id} identity hot-swap: {e}"
                ))
            })
    }

    /// Resolve the target [`SessionLlmIdentity`] for a hot-swap request,
    /// validating provider/model overrides against the model registry.
    /// Public so surfaces that need to peek the resolved identity
    /// (e.g. live orchestration in W2-A) can call into it directly.
    pub async fn resolve_target_llm_identity(
        &self,
        current: &SessionLlmIdentity,
        request: &SessionLlmReconfigureRequest,
    ) -> Result<SessionLlmIdentity, RuntimeDriverError> {
        let registry = self.model_registry().await?;
        let mut target = resolve_reconfigure_target_llm_identity(&registry, current, request)?;
        let config = self.load_config_for_hot_swap().await?;
        preserve_credential_account_affinity(&config, current, request, &mut target)?;
        Ok(target)
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl SessionLlmReconfigureHost for SessionRuntimeLlmReconfigureHost {
    async fn acquire_turn_finalization_boundary(
        &self,
        session_id: &SessionId,
    ) -> Result<
        Box<dyn meerkat_core::lifecycle::CoreExecutorTurnFinalizationGuard>,
        RuntimeDriverError,
    > {
        self.service
            .acquire_runtime_turn_finalization_guard(session_id)
            .await
            .map_err(session_error_to_runtime_driver)
    }

    async fn hydrate_session_llm_state(
        &self,
        session_id: &SessionId,
    ) -> Result<HydratedSessionLlmState, RuntimeDriverError> {
        let current_identity = match self.service.live_llm_identity(session_id).await {
            Ok(identity) => identity,
            Err(err) => {
                if let Some(hydrated) = self.hydrate_staged_session_llm_state(session_id).await? {
                    return Ok(hydrated);
                }
                return Err(session_error_to_runtime_driver(err));
            }
        };
        let current_visibility_state =
            match self.service.live_tool_visibility_state(session_id).await {
                Ok(state) => state.unwrap_or_default(),
                Err(err) => {
                    if let Some(hydrated) =
                        self.hydrate_staged_session_llm_state(session_id).await?
                    {
                        return Ok(hydrated);
                    }
                    return Err(session_error_to_runtime_driver(err));
                }
            };
        let base_tool_names = self
            .service
            .live_tool_scope_snapshot(session_id)
            .await
            .map_err(session_error_to_runtime_driver)?
            .ok_or_else(|| {
                RuntimeDriverError::Internal(format!(
                    "session {session_id} missing live tool scope snapshot during llm reconfiguration"
                ))
            })?
            .known_base_names
            .into_iter()
            .collect();

        let (current_capability_surface, capability_surface_status) = self
            .capability_surface_for_identity(&current_identity)
            .await?;

        Ok(HydratedSessionLlmState {
            current_identity,
            current_visibility_state,
            current_capability_surface,
            capability_surface_status,
            base_tool_names,
        })
    }

    async fn resolve_target_session_llm_identity(
        &self,
        request: &SessionLlmReconfigureRequest,
        current_identity: &SessionLlmIdentity,
    ) -> Result<ResolvedSessionLlmReconfigure, RuntimeDriverError> {
        let target_identity = self
            .resolve_target_llm_identity(current_identity, request)
            .await?;
        let registry = self.model_registry().await?;
        let profile = registry
            .profile_for_provider(target_identity.provider, &target_identity.model)
            .ok_or_else(|| RuntimeDriverError::ValidationFailed {
                reason: format!(
                    "no capability profile is registered for provider '{}' and model '{}'",
                    target_identity.provider.as_str(),
                    target_identity.model
                ),
            })?;

        Ok(ResolvedSessionLlmReconfigure {
            target_identity,
            target_capability_surface: profile_to_capability_surface(&profile),
        })
    }

    async fn preflight_target_session_llm_identity(
        &self,
        session_id: &SessionId,
        target_identity: &SessionLlmIdentity,
    ) -> Result<(), RuntimeDriverError> {
        self.build_adapter_for_session_llm_identity(session_id, target_identity)
            .await
            .map(|_| ())
    }

    async fn apply_live_session_llm_identity(
        &self,
        session_id: &SessionId,
        identity: &SessionLlmIdentity,
        capability_surface: Option<&SessionLlmCapabilitySurface>,
    ) -> Result<(), RuntimeDriverError> {
        if self
            .service
            .live_session_has_instruction_activations(session_id)
            .await
            .map_err(session_error_to_runtime_driver)?
        {
            let supports_mid_conversation_system_messages = capability_surface
                .is_some_and(|surface| surface.supports_mid_conversation_system_messages);
            if !supports_mid_conversation_system_messages {
                return Err(RuntimeDriverError::ValidationFailed {
                    reason: format!(
                        "model '{}' cannot represent the ordered instruction activations already recorded for session {session_id}",
                        identity.model
                    ),
                });
            }
        }
        let adapter = self
            .build_adapter_for_session_llm_identity(session_id, identity)
            .await?;
        let request_policy = self
            .build_request_policy_for_llm_identity(session_id, identity)
            .await?;
        self.service
            .apply_live_llm_identity_under_runtime_turn_boundary(
                session_id,
                adapter,
                identity.clone(),
                request_policy,
            )
            .await
            .map_err(session_error_to_runtime_driver)
    }

    async fn apply_live_session_tool_visibility_state(
        &self,
        session_id: &SessionId,
        visibility_state: Option<SessionToolVisibilityState>,
    ) -> Result<(), RuntimeDriverError> {
        self.service
            .apply_live_tool_visibility_state_under_runtime_turn_boundary(
                session_id,
                visibility_state,
            )
            .await
            .map_err(session_error_to_runtime_driver)
    }

    async fn persist_live_session(&self, session_id: &SessionId) -> Result<(), RuntimeDriverError> {
        self.service
            .persist_live_under_runtime_turn_boundary(session_id)
            .await
            .map_err(session_error_to_runtime_driver)
    }

    async fn discard_live_session(&self, session_id: &SessionId) -> Result<(), RuntimeDriverError> {
        self.service
            .discard_live_under_runtime_turn_boundary(session_id)
            .await
            .map_err(session_error_to_runtime_driver)
    }

    async fn commit_session_model_routing_control_record_durable_first(
        &self,
        session_id: &SessionId,
        record: meerkat_core::session::model_routing_control::SessionModelRoutingControlRecord,
    ) -> Result<(), RuntimeDriverError> {
        Arc::clone(&self.service)
            .commit_model_routing_control_record_durable_first(session_id, record)
            .await
            .map_err(session_error_to_runtime_driver)
    }

    async fn load_live_session_model_routing_control_history(
        &self,
        session_id: &SessionId,
    ) -> Result<
        meerkat_core::session::model_routing_control::SessionModelRoutingControlHistory,
        RuntimeDriverError,
    > {
        self.service
            .live_model_routing_control_history(session_id)
            .await
            .map_err(session_error_to_runtime_driver)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use meerkat_core::{
        AuthBindingRef, BindingId, BindingOrigin, ConfigStore as _, Provider, RealmId,
    };

    struct RealmOnlyService {
        realm_id: Option<RealmId>,
    }

    #[async_trait::async_trait]
    impl SessionRuntimeLlmReconfigureService for RealmOnlyService {
        async fn acquire_runtime_turn_finalization_guard(
            &self,
            _session_id: &SessionId,
        ) -> Result<Box<dyn meerkat_core::lifecycle::CoreExecutorTurnFinalizationGuard>, SessionError>
        {
            unreachable!("realm selection does not acquire the turn boundary")
        }

        async fn live_llm_identity(
            &self,
            _session_id: &SessionId,
        ) -> Result<SessionLlmIdentity, SessionError> {
            unreachable!("realm selection does not read the LLM identity")
        }

        async fn live_session_has_instruction_activations(
            &self,
            _session_id: &SessionId,
        ) -> Result<bool, SessionError> {
            unreachable!("realm selection does not inspect the transcript")
        }

        async fn live_realm_id(
            &self,
            _session_id: &SessionId,
        ) -> Result<Option<RealmId>, SessionError> {
            Ok(self.realm_id.clone())
        }

        async fn live_tool_visibility_state(
            &self,
            _session_id: &SessionId,
        ) -> Result<Option<SessionToolVisibilityState>, SessionError> {
            unreachable!("realm selection does not read tool visibility")
        }

        async fn live_web_search_override(
            &self,
            _session_id: &SessionId,
        ) -> Result<meerkat_core::ToolCategoryOverride, SessionError> {
            unreachable!("realm selection does not read web-search policy")
        }

        async fn live_tool_scope_snapshot(
            &self,
            _session_id: &SessionId,
        ) -> Result<Option<meerkat_core::ToolScopeSnapshot>, SessionError> {
            unreachable!("realm selection does not read the tool scope")
        }

        async fn apply_live_llm_identity_under_runtime_turn_boundary(
            &self,
            _session_id: &SessionId,
            _client: Arc<dyn AgentLlmClient>,
            _identity: SessionLlmIdentity,
            _request_policy: meerkat_core::SessionLlmRequestPolicy,
        ) -> Result<(), SessionError> {
            unreachable!("realm selection does not mutate the LLM identity")
        }

        async fn apply_live_tool_visibility_state_under_runtime_turn_boundary(
            &self,
            _session_id: &SessionId,
            _state: Option<SessionToolVisibilityState>,
        ) -> Result<(), SessionError> {
            unreachable!("realm selection does not mutate tool visibility")
        }

        async fn persist_live_under_runtime_turn_boundary(
            &self,
            _session_id: &SessionId,
        ) -> Result<(), SessionError> {
            unreachable!("realm selection does not persist")
        }

        async fn discard_live_under_runtime_turn_boundary(
            &self,
            _session_id: &SessionId,
        ) -> Result<(), SessionError> {
            unreachable!("realm selection does not discard")
        }

        async fn live_model_routing_control_history(
            &self,
            _session_id: &SessionId,
        ) -> Result<
            meerkat_core::session::model_routing_control::SessionModelRoutingControlHistory,
            SessionError,
        > {
            unreachable!("realm selection does not read the handoff log")
        }

        async fn commit_model_routing_control_record_durable_first(
            self: Arc<Self>,
            _session_id: &SessionId,
            _record: meerkat_core::session::model_routing_control::SessionModelRoutingControlRecord,
        ) -> Result<(), SessionError> {
            unreachable!("realm selection does not commit handoff resolutions")
        }
    }

    fn anthropic_binding() -> AuthBindingRef {
        AuthBindingRef {
            realm: RealmId::parse("tenant_a").unwrap(),
            binding: BindingId::parse("anthropic_default").unwrap(),
            profile: None,
            origin: BindingOrigin::Configured,
        }
    }

    fn anthropic_identity() -> SessionLlmIdentity {
        SessionLlmIdentity {
            model: "claude-sonnet-4-5".to_string(),
            provider: Provider::Anthropic,
            self_hosted_server_id: None,
            provider_params: None,
            auth_binding: Some(anthropic_binding()),
        }
    }

    fn model_registry() -> ModelRegistry {
        ModelRegistry::from_config(&Config::default(), meerkat_models::canonical())
            .expect("canonical model registry")
    }

    fn reconfigure_request(
        model: Option<&str>,
        provider: Option<&str>,
        auth_binding: Option<TurnMetadataOverride<AuthBindingRef>>,
    ) -> SessionLlmReconfigureRequest {
        SessionLlmReconfigureRequest {
            model: model.map(str::to_string),
            provider: provider.map(str::to_string),
            self_hosted_server_id: None,
            provider_params: None,
            auth_binding,
        }
    }

    #[tokio::test]
    async fn live_session_realm_overrides_runtime_head_for_hot_swap() {
        let session_realm = RealmId::parse("mob.project.member").unwrap();
        let runtime_head = RealmId::parse("project").unwrap();
        let service = RealmOnlyService {
            realm_id: Some(session_realm.clone()),
        };
        let selected =
            preferred_hot_swap_realm(&service, &SessionId::new(), Some(runtime_head.clone()))
                .await
                .expect("select preferred realm");
        assert_eq!(selected, Some(session_realm));

        let service = RealmOnlyService { realm_id: None };
        let selected =
            preferred_hot_swap_realm(&service, &SessionId::new(), Some(runtime_head.clone()))
                .await
                .expect("fall back to runtime head");
        assert_eq!(selected, Some(runtime_head));
    }

    #[tokio::test]
    async fn embedded_blueprint_reads_store_updates_after_construction() {
        let initial_snapshot = Config {
            max_tokens: Some(11),
            ..Config::default()
        };
        let config_at_construction = Config {
            max_tokens: Some(22),
            ..Config::default()
        };
        let live_store = Arc::new(meerkat_core::MemoryConfigStore::new(
            config_at_construction,
            meerkat_models::canonical(),
        ));
        let builder = FactoryAgentBuilder::new_with_config_store(
            AgentFactory::minimal(),
            initial_snapshot,
            live_store.clone(),
        );
        let temp = tempfile::tempdir().expect("temporary config-runtime state root");
        let blueprint = SessionRuntimeLlmReconfigureHostBlueprint::new(
            &builder,
            temp.path().join("config_state.json"),
            Arc::new(std::sync::RwLock::new(None)),
        );

        let updated = Config {
            max_tokens: Some(33),
            ..Config::default()
        };
        live_store
            .set(updated)
            .await
            .expect("update canonical config store after blueprint construction");

        let snapshot = blueprint
            .config_runtime()
            .get()
            .await
            .expect("blueprint config runtime reads canonical store");
        assert_eq!(snapshot.config.max_tokens, Some(33));
    }

    #[tokio::test]
    async fn embedded_blueprint_lowers_snapshot_only_builder_to_memory_store() {
        let snapshot = Config {
            max_tokens: Some(44),
            ..Config::default()
        };
        let builder = FactoryAgentBuilder::new(AgentFactory::minimal(), snapshot);
        let temp = tempfile::tempdir().expect("temporary config-runtime state root");
        let blueprint = SessionRuntimeLlmReconfigureHostBlueprint::new(
            &builder,
            temp.path().join("config_state.json"),
            Arc::new(std::sync::RwLock::new(None)),
        );

        let snapshot = blueprint
            .config_runtime()
            .get()
            .await
            .expect("snapshot-only blueprint config runtime");
        assert_eq!(snapshot.config.max_tokens, Some(44));
    }

    #[test]
    fn model_only_reconfigure_uses_catalog_provider_and_clears_stale_binding() {
        let current = anthropic_identity();
        let request = reconfigure_request(Some("gpt-5.5"), None, None);

        let resolved =
            resolve_reconfigure_target_llm_identity(&model_registry(), &current, &request)
                .expect("catalog-owned model-only switch");

        assert_eq!(resolved.model, "gpt-5.5");
        assert_eq!(resolved.provider, Provider::OpenAI);
        assert!(
            resolved.auth_binding.is_none(),
            "provider switches must not inherit a binding from the previous provider"
        );
    }

    #[test]
    fn provider_switch_preserves_shared_credential_account_route() {
        let account =
            meerkat_core::CredentialAccountId::parse("github_copilot").expect("valid account");
        let mut section = meerkat_core::RealmConfigSection::default();
        for (route, provider, backend_kind, auth_method) in [
            (
                "copilot_anthropic",
                Provider::Anthropic,
                "copilot",
                "github_copilot_oauth",
            ),
            (
                "copilot_openai",
                Provider::OpenAI,
                "copilot",
                "github_copilot_oauth",
            ),
        ] {
            section.backend.insert(
                route.to_string(),
                meerkat_core::BackendProfileConfig {
                    provider: provider.as_str().to_string(),
                    backend_kind: backend_kind.to_string(),
                    base_url: None,
                    options: serde_json::Value::Null,
                    server: None,
                },
            );
            section.auth.insert(
                route.to_string(),
                meerkat_core::AuthProfileConfig {
                    provider: provider.as_str().to_string(),
                    auth_method: auth_method.to_string(),
                    source: meerkat_core::CredentialSourceSpec::ManagedStore,
                    constraints: meerkat_core::AuthConstraints {
                        allow_interactive_login: true,
                        ..Default::default()
                    },
                    metadata_defaults: Default::default(),
                },
            );
            section.binding.insert(
                route.to_string(),
                meerkat_core::ProviderBindingConfig {
                    backend_profile: route.to_string(),
                    auth_profile: route.to_string(),
                    credential_account: Some(account.clone()),
                    default_model: None,
                    policy: Default::default(),
                    provider_default: false,
                },
            );
        }
        let mut config = Config::default();
        config.realm.insert("global".to_string(), section);
        let current = SessionLlmIdentity {
            model: "claude-sonnet-4-5".to_string(),
            provider: Provider::Anthropic,
            self_hosted_server_id: None,
            provider_params: None,
            auth_binding: Some(AuthBindingRef {
                realm: RealmId::global(),
                binding: BindingId::parse("copilot_anthropic").unwrap(),
                profile: None,
                origin: BindingOrigin::Configured,
            }),
        };
        let request = reconfigure_request(Some("gpt-5.5"), None, None);
        let mut target =
            resolve_reconfigure_target_llm_identity(&model_registry(), &current, &request)
                .expect("catalog provider switch");

        preserve_credential_account_affinity(&config, &current, &request, &mut target)
            .expect("shared account route");

        assert_eq!(
            target
                .auth_binding
                .as_ref()
                .map(|binding| binding.binding.as_str()),
            Some("copilot_openai")
        );
    }

    #[test]
    fn same_provider_without_explicit_binding_inherits_durable_binding() {
        let current = anthropic_identity();
        let request = reconfigure_request(Some("claude-opus-4-8"), None, None);

        let resolved =
            resolve_reconfigure_target_llm_identity(&model_registry(), &current, &request)
                .expect("same-provider model-only switch");

        assert_eq!(resolved.provider, Provider::Anthropic);
        assert_eq!(resolved.auth_binding, Some(anthropic_binding()));
    }

    #[test]
    fn explicit_clear_drops_binding_even_without_provider_change() {
        let current = anthropic_identity();
        let request = reconfigure_request(None, None, Some(TurnMetadataOverride::Clear));

        let resolved =
            resolve_reconfigure_target_llm_identity(&model_registry(), &current, &request)
                .expect("explicit auth clear");

        assert!(resolved.auth_binding.is_none());
    }

    #[test]
    fn explicit_set_overrides_binding_across_provider_change() {
        let current = anthropic_identity();
        let target = AuthBindingRef {
            realm: RealmId::parse("tenant_b").unwrap(),
            binding: BindingId::parse("openai_default").unwrap(),
            profile: None,
            origin: BindingOrigin::Configured,
        };
        let request = reconfigure_request(
            Some("gpt-5.5"),
            None,
            Some(TurnMetadataOverride::Set(target.clone())),
        );

        let resolved =
            resolve_reconfigure_target_llm_identity(&model_registry(), &current, &request)
                .expect("explicit auth binding on catalog-owned switch");

        assert_eq!(resolved.provider, Provider::OpenAI);
        assert_eq!(resolved.auth_binding, Some(target));
    }
}