imp-core 0.2.0

Agent engine for imp: loop, tools, sessions, hooks, context, and SDK
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
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
//! High-level session API for driving imp programmatically.
//!
//! `ImpSession` is the primary public interface for embedding imp in other
//! Rust programs, building custom UIs, or driving agents from orchestrators.
//! It wires together config, auth, model resolution, agent construction,
//! session persistence, and the event stream — eliminating the boilerplate
//! that each run mode (interactive, print, headless, RPC) otherwise
//! duplicates.
//!
//! # Example
//!
//! ```no_run
//! use imp_core::imp_session::{ImpSession, SessionOptions, SessionChoice};
//!
//! # async fn example() -> imp_core::Result<()> {
//! let mut session = ImpSession::create(SessionOptions {
//!     cwd: std::env::current_dir()?,
//!     ..Default::default()
//! }).await?;
//!
//! session.prompt("What files are in the current directory?").await?;
//!
//! while let Some(event) = session.recv_event().await {
//!     println!("{event:?}");
//! }
//! # Ok(())
//! # }
//! ```

use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::Arc;

use tokio::sync::mpsc;
use tokio::task::JoinHandle;

use imp_llm::auth::{ApiKey, AuthStore};
use imp_llm::model::{ModelMeta, ModelRegistry};
use imp_llm::providers::create_provider;
use imp_llm::{Model, ThinkingLevel};

use crate::agent::{Agent, AgentCommand, AgentEvent, AgentHandle};
use crate::builder::AgentBuilder;
use crate::config::{AgentMode, Config};
use crate::error::{Error, Result};
use crate::policy::RunPolicy;
use crate::session::{SessionCheckpointRecord, SessionEntry, SessionManager};
use crate::storage;
use crate::system_prompt::{Fact, TaskContext};
use crate::ui::UserInterface;

// ── Options ─────────────────────────────────────────────────────

/// How to initialize the session file.
#[derive(Debug, Clone, Default)]
pub enum SessionChoice {
    /// Fresh session, persisted to disk.
    #[default]
    New,
    /// No persistence.
    InMemory,
    /// Continue the most recent session for the working directory.
    Continue,
    /// Open a specific session file.
    Open(PathBuf),
}

use crate::tools::LuaToolLoader;
use crate::workflow::{AutonomyMode, VerificationGate};

/// Configuration for creating an `ImpSession`.
///
/// All fields have sensible defaults — only `cwd` is typically required.
pub struct SessionOptions {
    /// Working directory. Tools resolve paths relative to this.
    pub cwd: PathBuf,

    /// Prebuilt model override for deterministic tests or embedded callers.
    /// When set, ImpSession skips runtime model/provider/auth resolution.
    pub model_override: Option<Model>,

    /// Model hint — alias ("sonnet") or full ID. Resolved against the
    /// model registry. Falls back to config, then "sonnet".
    pub model: Option<String>,

    /// Provider override. Usually auto-detected from the model.
    pub provider: Option<String>,

    /// Runtime API key override (not persisted).
    pub api_key: Option<String>,

    /// Thinking level override.
    pub thinking: Option<ThinkingLevel>,

    /// Agent mode (full, worker, orchestrator, …).
    pub mode: Option<AgentMode>,

    /// Autonomy mode for workflow/runtime policy. Defaults to safe.
    pub autonomy_mode: Option<AutonomyMode>,

    /// Verification gates declared by CLI/config/user input.
    pub verification_gates: Vec<VerificationGate>,

    /// Maximum turns before the agent stops.
    pub max_turns: Option<u32>,

    /// Max output tokens per response.
    pub max_tokens: Option<u32>,

    /// Replace the assembled system prompt entirely.
    pub system_prompt: Option<String>,

    /// Skip native tool registration.
    pub no_tools: bool,

    /// Session persistence strategy.
    pub session: SessionChoice,

    /// Task context for headless / unit mode.
    pub task: Option<TaskContext>,

    /// Task-specific facts to inject into the system prompt.
    pub facts: Vec<Fact>,

    /// Lua extension loader. Called after native tools are registered.
    /// The binary crate typically provides this; library callers can
    /// pass `None` to skip Lua extensions.
    pub lua_loader: Option<LuaToolLoader>,

    /// Per-run tool/write policy layered on top of AgentMode.
    pub run_policy: RunPolicy,

    /// Custom UI implementation. Defaults to `NullInterface`.
    pub ui: Option<Arc<dyn UserInterface>>,

    /// Path to auth.json. Defaults to `~/.config/imp/auth.json`.
    pub auth_path: Option<PathBuf>,

    /// Pre-assembled context messages injected before the first prompt.
    /// Built by `context_prefill::assemble_context()` at dispatch time.
    /// The agent starts with these files already in its cached prefix.
    pub context_prefill: Vec<imp_llm::Message>,
}

impl Default for SessionOptions {
    fn default() -> Self {
        Self {
            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            model_override: None,
            model: None,
            provider: None,
            api_key: None,
            thinking: None,
            mode: None,
            autonomy_mode: None,
            verification_gates: Vec::new(),
            max_turns: None,
            max_tokens: None,
            system_prompt: None,
            no_tools: false,
            session: SessionChoice::default(),
            task: None,
            facts: Vec::new(),
            lua_loader: None,
            run_policy: RunPolicy::default(),
            ui: None,
            auth_path: None,
            context_prefill: Vec::new(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct RuntimeConnectionIntent<'a> {
    pub model_hint: Option<&'a str>,
    pub config_model: Option<&'a str>,
    pub provider_override: Option<&'a str>,
    pub api_key_override_present: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedRuntimeConnection {
    pub model_id: String,
    pub provider_name: String,
}

/// Resolve the model-first runtime connection (model id + provider route/surface)
/// shared by CLI and session startup.
pub fn resolve_runtime_connection(
    intent: RuntimeConnectionIntent<'_>,
    auth_store: &AuthStore,
    registry: &ModelRegistry,
) -> std::result::Result<ResolvedRuntimeConnection, String> {
    let model_hint = intent
        .model_hint
        .or(intent.config_model)
        .unwrap_or("sonnet");

    let meta = registry
        .resolve_meta(model_hint, intent.provider_override)
        .ok_or_else(|| format!("Unknown model: {model_hint}"))?;

    let provider_name = intent
        .provider_override
        .unwrap_or(&meta.provider)
        .to_string();

    if let Some(oauth_route) = auth_preferred_oauth_route(
        intent.provider_override,
        intent.api_key_override_present,
        auth_store,
        registry,
        &meta,
        &provider_name,
    ) {
        return Ok(oauth_route);
    }

    Ok(ResolvedRuntimeConnection {
        model_id: meta.id.clone(),
        provider_name,
    })
}

// ── ImpSession ──────────────────────────────────────────────────

/// A fully wired agent session.
///
/// Manages the lifecycle of a single agent: config resolution, model
/// selection, session persistence, and the event/command channels.
pub struct ImpSession {
    agent: Option<Agent>,
    handle: AgentHandle,
    session_mgr: SessionManager,
    config: Config,
    model: Model,
    auth_store: AuthStore,
    model_registry: ModelRegistry,
    cwd: PathBuf,
    /// Task handle for the currently running agent loop, if any.
    agent_task: Option<JoinHandle<(Agent, Result<()>)>>,
    completed_run_result: Option<Result<()>>,
    pending_persistence_errors: VecDeque<String>,
    /// Context prefill messages, injected once before the first prompt.
    context_prefill: Vec<imp_llm::Message>,
    context_prefill_injected: bool,
}

impl ImpSession {
    /// Create a new session by resolving config, auth, model, and tools.
    ///
    /// This is the main factory — mirrors pi's `createAgentSession()`.
    pub async fn create(options: SessionOptions) -> Result<Self> {
        let cwd = options.cwd.clone();

        let _ = storage::reconcile_legacy_into_global_root();

        // 1. Load config (user + project, merged)
        let mut config = Config::resolve(&Config::user_config_dir(), Some(&cwd))?;

        // Apply option overrides
        if let Some(thinking) = options.thinking {
            config.thinking = Some(thinking);
        }
        if let Some(mode) = options.mode {
            config.mode = mode;
        }

        // 2. Resolve auth
        let auth_path = options
            .auth_path
            .clone()
            .or_else(storage::existing_global_auth_path)
            .unwrap_or_else(storage::global_auth_path);
        let mut auth_store =
            AuthStore::load(&auth_path).unwrap_or_else(|_| AuthStore::new(auth_path));

        if let Some(ref key) = options.api_key {
            // We'll set this after we know the provider name
            // Store it temporarily
            let _ = key; // handled below
        }

        // 3. Resolve model + provider route
        let model_registry = ModelRegistry::with_builtins();
        let (model, _provider_name, api_key) = if let Some(model) = options.model_override.as_ref()
        {
            (
                clone_model(model),
                model.meta.provider.clone(),
                String::new(),
            )
        } else {
            let runtime_connection = resolve_runtime_connection(
                RuntimeConnectionIntent {
                    model_hint: options.model.as_deref(),
                    config_model: config.model.as_deref(),
                    provider_override: options.provider.as_deref(),
                    api_key_override_present: options.api_key.is_some(),
                },
                &auth_store,
                &model_registry,
            )
            .map_err(Error::Config)?;

            let meta = model_registry
                .resolve_meta(
                    &runtime_connection.model_id,
                    Some(&runtime_connection.provider_name),
                )
                .ok_or_else(|| {
                    Error::Config(format!(
                        "Unknown model/provider route: {} via {}",
                        runtime_connection.model_id, runtime_connection.provider_name
                    ))
                })?;

            let provider_name = runtime_connection.provider_name.clone();

            if let Some(ref key) = options.api_key {
                auth_store.set_runtime_key(&provider_name, key.clone());
            }

            let provider = create_provider(&provider_name)
                .ok_or_else(|| Error::Config(format!("Unknown provider: {provider_name}")))?;

            let api_key = resolve_api_key(&mut auth_store, &provider_name).await?;
            (
                Model {
                    meta,
                    provider: Arc::from(provider),
                },
                provider_name,
                api_key,
            )
        };

        // 5. Build agent
        let mut builder =
            AgentBuilder::new(config.clone(), cwd.clone(), clone_model(&model), api_key);

        if let Some(task) = &options.task {
            builder = builder.task(task.clone());
        }
        if !options.facts.is_empty() {
            builder = builder.facts(options.facts.clone());
        }
        if let Some(prompt) = &options.system_prompt {
            builder = builder.system_prompt(prompt.clone());
        }
        if let Some(lua_loader) = options.lua_loader {
            builder = builder.lua_tool_loader(move |policy, tools| lua_loader(policy, tools));
        }
        if let Some(autonomy_mode) = options.autonomy_mode {
            builder = builder.autonomy_mode(autonomy_mode);
        }
        builder = builder.verification_gates(options.verification_gates.clone());
        builder = builder.run_policy(options.run_policy.clone());

        let (mut agent, handle) = builder.build()?;

        if options.no_tools {
            agent.tools.retain(|_| false);
        }

        if options.no_tools {
            agent.thinking_level = config.thinking.unwrap_or(ThinkingLevel::Off);
            if let Some(max_tokens) = options.max_tokens.or(config.max_tokens) {
                agent.max_tokens = Some(max_tokens);
            }
        } else if let Some(max_tokens) = options.max_tokens {
            agent.max_tokens = Some(max_tokens);
        }
        if let Some(ui) = &options.ui {
            agent.ui = Arc::clone(ui);
        }

        // 6. Set up session persistence
        let session_dir = storage::global_sessions_dir();
        let session_mgr = match options.session {
            SessionChoice::New => SessionManager::new(&cwd, &session_dir)?,
            SessionChoice::InMemory => SessionManager::in_memory(),
            SessionChoice::Continue => SessionManager::continue_recent(&cwd, &session_dir)?
                .unwrap_or_else(|| SessionManager::new(&cwd, &session_dir).unwrap()),
            SessionChoice::Open(ref path) => SessionManager::open(path)?,
        };

        Ok(Self {
            agent: Some(agent),
            handle,
            session_mgr,
            config,
            model,
            auth_store,
            model_registry,
            cwd,
            context_prefill: options.context_prefill,
            context_prefill_injected: false,
            agent_task: None,
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
        })
    }

    // ── Prompting ───────────────────────────────────────────────

    /// Send a prompt and run the agent loop.
    ///
    /// The agent runs on a background task. Use [`recv_event`] to consume
    /// events, and [`steer`] / [`follow_up`] / [`cancel`] to control it.
    ///
    /// Returns an error if the agent is already running.
    pub async fn prompt(&mut self, text: &str) -> Result<()> {
        if self.agent_task.is_some() {
            return Err(Error::Config(
                "Agent is already running. Cancel or wait for it to finish.".into(),
            ));
        }

        self.completed_run_result = None;
        self.pending_persistence_errors.clear();

        // Persist user message to session
        let msg_id = uuid::Uuid::new_v4().to_string();
        let _ = self.session_mgr.append(SessionEntry::Message {
            id: msg_id,
            parent_id: None,
            message: imp_llm::Message::user(text),
        });

        // Load prior messages from session history into agent
        let mut agent = self
            .agent
            .take()
            .ok_or_else(|| Error::Config("Agent already consumed".into()))?;

        let mut history: Vec<imp_llm::Message> = self.session_mgr.get_active_messages();

        // The prompt was already appended to session history so resume/tree state
        // is correct, but Agent::run() will push the active prompt itself. Remove
        // the just-appended trailing user message to avoid duplicating it in the
        // model context for this run.
        if matches!(
            history.last(),
            Some(imp_llm::Message::User(user))
                if matches!(
                    user.content.as_slice(),
                    [imp_llm::ContentBlock::Text { text: last_text }] if last_text == text
                )
        ) {
            history.pop();
        }

        // Inject context prefill (once, before the first prompt). These messages
        // form the cached prefix: file contents the agent needs, assembled at
        // dispatch time by context_prefill::assemble_context(). Subsequent turns
        // get cache_read on this prefix instead of re-reading files.
        if !self.context_prefill_injected && !self.context_prefill.is_empty() {
            for msg in &self.context_prefill {
                history.push(msg.clone());
            }
            // Assistant acknowledgment to maintain user/assistant alternation
            history.push(imp_llm::Message::Assistant(imp_llm::AssistantMessage {
                content: vec![imp_llm::ContentBlock::Text {
                    text: "Context loaded. Ready to work.".into(),
                }],
                usage: None,
                stop_reason: imp_llm::StopReason::EndTurn,
                timestamp: imp_llm::now(),
            }));
            self.context_prefill_injected = true;
        }

        // Replace agent messages with session history. Agent::run() will append
        // the active prompt as the next user message.
        agent.messages = history;

        let prompt = text.to_string();
        let task = tokio::spawn(async move {
            let result = agent.run(prompt).await;
            (agent, result)
        });
        self.agent_task = Some(task);

        Ok(())
    }

    /// Send a prompt and block until the agent finishes.
    ///
    /// Events are still emitted via [`recv_event`], but this method
    /// does not return until the agent loop completes.
    pub async fn prompt_and_wait(&mut self, text: &str) -> Result<()> {
        self.prompt(text).await?;
        self.wait().await
    }

    /// Wait for the running agent to finish.
    pub async fn wait(&mut self) -> Result<()> {
        if let Some(task) = self.agent_task.take() {
            let (agent, result) = task
                .await
                .map_err(|e| Error::Config(format!("Agent task panicked: {e}")))?;
            self.agent = Some(agent);
            self.completed_run_result = Some(result);
            self.drain_pending_events_for_persistence();
        }

        if let Some(result) = self.completed_run_result.take() {
            return result;
        }

        Ok(())
    }

    /// Interrupt the agent: delivered after the current tool finishes,
    /// remaining queued tools are skipped.
    pub async fn steer(&self, text: &str) -> Result<()> {
        self.handle
            .command_tx
            .send(AgentCommand::Steer(text.into()))
            .await
            .map_err(|_| Error::Config("Agent not running".into()))
    }

    /// Follow-up: delivered only after the agent finishes all current work.
    pub async fn follow_up(&self, text: &str) -> Result<()> {
        self.handle
            .command_tx
            .send(AgentCommand::FollowUp(text.into()))
            .await
            .map_err(|_| Error::Config("Agent not running".into()))
    }

    /// Cancel the current agent run.
    pub async fn cancel(&self) -> Result<()> {
        self.handle
            .command_tx
            .send(AgentCommand::Cancel)
            .await
            .map_err(|_| Error::Config("Agent not running".into()))
    }

    /// Force-abort the current agent task when graceful cancellation does not finish.
    pub fn abort(&mut self) {
        if let Some(task) = self.agent_task.take() {
            task.abort();
            self.completed_run_result = Some(Err(Error::Cancelled));
        }
    }

    // ── Events ──────────────────────────────────────────────────

    /// Receive the next event from the agent.
    ///
    /// Returns `None` when the agent has finished and all events have
    /// been consumed.
    pub async fn recv_event(&mut self) -> Option<AgentEvent> {
        if let Some(error) = self.take_persistence_error() {
            return Some(AgentEvent::Error { error });
        }

        if self.agent_task.is_none() && self.completed_run_result.is_some() {
            return None;
        }

        let event = self.handle.event_rx.recv().await?;
        let events = self.persist_event_entries(&event);

        if matches!(event, AgentEvent::AgentEnd { .. }) {
            if let Some(task) = self.agent_task.take() {
                match task.await {
                    Ok((agent, result)) => {
                        self.agent = Some(agent);
                        self.completed_run_result = Some(result);
                    }
                    Err(join_error) => {
                        self.push_persistence_error(
                            events,
                            format!("agent task panicked: {join_error}"),
                        );
                    }
                }
            }
        }

        Some(event)
    }

    /// Get mutable access to the raw event receiver.
    ///
    /// Use this when you need `select!` or other channel combinators.
    pub fn event_rx(&mut self) -> &mut mpsc::Receiver<AgentEvent> {
        &mut self.handle.event_rx
    }

    // ── Model ───────────────────────────────────────────────────

    /// Switch the model for subsequent prompts.
    ///
    /// The change takes effect on the next `prompt()` call.
    pub async fn set_model(&mut self, hint: &str) -> Result<()> {
        let meta = self
            .model_registry
            .resolve_meta(hint, None)
            .ok_or_else(|| Error::Config(format!("Unknown model: {hint}")))?;

        let provider_name = meta.provider.clone();
        let provider = create_provider(&provider_name)
            .ok_or_else(|| Error::Config(format!("Unknown provider: {provider_name}")))?;
        let api_key = resolve_api_key(&mut self.auth_store, &provider_name).await?;

        self.model = Model {
            meta,
            provider: Arc::from(provider),
        };

        // If we still have the agent (not currently running), update it
        if let Some(ref mut agent) = self.agent {
            agent.model = clone_model(&self.model);
            agent.api_key = api_key;
        }

        Ok(())
    }

    /// Set the thinking level for subsequent prompts.
    pub fn set_thinking(&mut self, level: ThinkingLevel) {
        self.config.thinking = Some(level);
        if let Some(ref mut agent) = self.agent {
            agent.thinking_level = level;
        }
    }

    // ── Accessors ───────────────────────────────────────────────

    /// The current model.
    pub fn model(&self) -> &Model {
        &self.model
    }

    /// The resolved config.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// The session manager (tree, entries, persistence).
    pub fn session_manager(&self) -> &SessionManager {
        &self.session_mgr
    }

    /// Mutable access to the session manager.
    pub fn session_manager_mut(&mut self) -> &mut SessionManager {
        &mut self.session_mgr
    }

    /// The working directory.
    pub fn cwd(&self) -> &PathBuf {
        &self.cwd
    }

    /// The auth store (for checking credentials, OAuth status, etc).
    pub fn auth_store(&self) -> &AuthStore {
        &self.auth_store
    }

    /// Mutable access to the auth store.
    pub fn auth_store_mut(&mut self) -> &mut AuthStore {
        &mut self.auth_store
    }

    /// The model registry.
    pub fn model_registry(&self) -> &ModelRegistry {
        &self.model_registry
    }

    /// Whether the agent is currently running a prompt.
    pub fn is_running(&self) -> bool {
        self.agent_task.is_some()
    }

    /// Get the raw command sender for advanced use cases.
    pub fn command_tx(&self) -> &mpsc::Sender<AgentCommand> {
        &self.handle.command_tx
    }

    fn persist_event_entries(&mut self, event: &AgentEvent) -> Vec<&'static str> {
        let persisted = match self
            .session_mgr
            .persist_agent_event_entries(&self.model, event)
        {
            Ok(persisted) => persisted,
            Err(error) => {
                self.push_persistence_error(
                    Vec::new(),
                    format!("failed to persist agent event entries: {error}"),
                );
                Vec::new()
            }
        };

        if let Some(agent) = self.agent.as_ref() {
            if let Err(error) =
                persist_checkpoint_records(&mut self.session_mgr, &agent.checkpoint_state)
            {
                self.push_persistence_error(
                    persisted.clone(),
                    format!("failed to persist checkpoint records: {error}"),
                );
            }
        }

        persisted
    }

    fn drain_pending_events_for_persistence(&mut self) {
        while let Ok(event) = self.handle.event_rx.try_recv() {
            self.persist_event_entries(&event);
        }
    }

    fn push_persistence_error(&mut self, persisted: Vec<&'static str>, error: String) {
        let prefix = if persisted.is_empty() {
            "session persistence warning".to_string()
        } else {
            format!("session persistence warning after {}", persisted.join(", "))
        };
        self.pending_persistence_errors
            .push_back(format!("{prefix}: {error}"));
    }

    fn take_persistence_error(&mut self) -> Option<String> {
        self.pending_persistence_errors.pop_front()
    }
}
// ── Helpers ─────────────────────────────────────────────────────

/// Resolve the API key for a provider, handling OAuth refresh.
async fn resolve_api_key(auth_store: &mut AuthStore, provider: &str) -> Result<ApiKey> {
    let result = match provider {
        "openai-codex" => auth_store.resolve_chatgpt_oauth().await,
        "anthropic" | "kimi-code" => auth_store.resolve_with_refresh(provider).await,
        _ => auth_store.resolve(provider),
    };
    result.map_err(|e| Error::Config(format!("Auth failed for {provider}: {e}")))
}

fn auth_preferred_oauth_route(
    provider_override: Option<&str>,
    api_key_override_present: bool,
    auth_store: &AuthStore,
    registry: &ModelRegistry,
    meta: &ModelMeta,
    provider_name: &str,
) -> Option<ResolvedRuntimeConnection> {
    if should_use_openai_chatgpt_route(
        provider_override,
        api_key_override_present,
        auth_store,
        registry,
        &meta.id,
        provider_name,
    ) {
        return Some(ResolvedRuntimeConnection {
            model_id: meta.id.clone(),
            provider_name: "openai-codex".to_string(),
        });
    }

    if should_use_kimi_code_route(
        provider_override,
        api_key_override_present,
        auth_store,
        registry,
        meta,
        provider_name,
    ) {
        return Some(ResolvedRuntimeConnection {
            model_id: "kimi2.6".to_string(),
            provider_name: "kimi-code".to_string(),
        });
    }

    None
}
fn should_use_openai_chatgpt_route(
    provider_override: Option<&str>,
    api_key_override_present: bool,
    auth_store: &AuthStore,
    registry: &ModelRegistry,
    model_id: &str,
    provider_name: &str,
) -> bool {
    let provider_allows_fallback = match provider_override {
        None => true,
        Some("openai") => true,
        Some(_) => false,
    };

    provider_allows_fallback
        && !api_key_override_present
        && provider_name == "openai"
        && auth_store.resolve_api_key_only("openai").is_err()
        && (auth_store.get_oauth("openai").is_some()
            || auth_store.get_oauth("openai-codex").is_some())
        && codex_supports_model(registry, model_id)
}

fn should_use_kimi_code_route(
    provider_override: Option<&str>,
    api_key_override_present: bool,
    auth_store: &AuthStore,
    registry: &ModelRegistry,
    meta: &ModelMeta,
    provider_name: &str,
) -> bool {
    let provider_allows_fallback = match provider_override {
        None => true,
        Some("moonshot") => true,
        Some("kimi-code") => true,
        Some(_) => false,
    };

    provider_allows_fallback
        && !api_key_override_present
        && provider_name == "moonshot"
        && auth_store.resolve_api_key_only("moonshot").is_err()
        && auth_store.get_oauth("kimi-code").is_some()
        && registry.find("kimi2.6").is_some()
        && is_kimi_moonshot_model(&meta.id)
}

fn is_kimi_moonshot_model(model_id: &str) -> bool {
    matches!(
        model_id,
        "kimi-k2.6"
            | "kimi-k2.5"
            | "kimi-k2-0905-preview"
            | "kimi-k2-turbo-preview"
            | "kimi-k2-thinking"
            | "kimi-k2-thinking-turbo"
    )
}
fn clone_model(model: &Model) -> Model {
    Model {
        meta: model.meta.clone(),
        provider: Arc::clone(&model.provider),
    }
}

fn persist_checkpoint_records(
    session_mgr: &mut SessionManager,
    checkpoint_state: &crate::tools::CheckpointState,
) -> Result<Vec<String>> {
    let existing: std::collections::HashSet<String> = session_mgr
        .checkpoint_records()
        .into_iter()
        .map(|record| record.checkpoint_id)
        .collect();

    let mut persisted = Vec::new();
    for record in checkpoint_state.checkpoints() {
        if existing.contains(&record.id) {
            continue;
        }
        session_mgr.append_checkpoint_record(SessionCheckpointRecord {
            version: crate::session::CHECKPOINT_RECORD_VERSION,
            checkpoint_id: record.id.clone(),
            created_at: record.created_at,
            label: record.label.clone(),
            files: record
                .files
                .iter()
                .map(|path| path.to_string_lossy().to_string())
                .collect(),
        })?;
        persisted.push(record.id);
    }

    Ok(persisted)
}

fn codex_supports_model(_registry: &ModelRegistry, model_id: &str) -> bool {
    imp_llm::model::builtin_openai_codex_models()
        .iter()
        .any(|m| m.id == model_id)
}

#[cfg(test)]
mod tests {
    use super::*;
    use imp_llm::{
        auth::{ApiKey, AuthStore},
        model::{Capabilities, ModelPricing},
        provider::{Context, Provider, RequestOptions},
        AssistantMessage, ContentBlock, ModelMeta, StopReason, StreamEvent, Usage,
    };
    use serde_json::json;
    use tempfile::TempDir;

    struct NoopProvider {
        models: Vec<ModelMeta>,
    }

    struct SingleResponseProvider {
        models: Vec<ModelMeta>,
        events: std::sync::Mutex<Option<Vec<imp_llm::Result<StreamEvent>>>>,
    }

    #[async_trait::async_trait]
    impl Provider for NoopProvider {
        fn stream(
            &self,
            _model: &Model,
            _context: Context,
            _options: RequestOptions,
            _api_key: &str,
        ) -> std::pin::Pin<Box<dyn futures_core::Stream<Item = imp_llm::Result<StreamEvent>> + Send>>
        {
            Box::pin(futures::stream::empty())
        }

        async fn resolve_auth(&self, _auth: &AuthStore) -> imp_llm::Result<ApiKey> {
            Ok(String::new())
        }

        fn id(&self) -> &str {
            "noop"
        }

        fn models(&self) -> &[ModelMeta] {
            &self.models
        }
    }

    #[async_trait::async_trait]
    impl Provider for SingleResponseProvider {
        fn stream(
            &self,
            _model: &Model,
            _context: Context,
            _options: RequestOptions,
            _api_key: &str,
        ) -> std::pin::Pin<Box<dyn futures_core::Stream<Item = imp_llm::Result<StreamEvent>> + Send>>
        {
            let events = self
                .events
                .lock()
                .expect("single response provider lock")
                .take()
                .unwrap_or_default();
            Box::pin(futures::stream::iter(events))
        }

        async fn resolve_auth(&self, _auth: &AuthStore) -> imp_llm::Result<ApiKey> {
            Ok(String::new())
        }

        fn id(&self) -> &str {
            "single-response"
        }

        fn models(&self) -> &[ModelMeta] {
            &self.models
        }
    }

    fn test_model() -> Model {
        let meta = ModelMeta {
            id: "test-model".into(),
            provider: "test-provider".into(),
            name: "Test Model".into(),
            context_window: 8192,
            max_output_tokens: 2048,
            pricing: ModelPricing {
                input_per_mtok: 2.0,
                output_per_mtok: 4.0,
                cache_read_per_mtok: 0.5,
                cache_write_per_mtok: 1.0,
            },
            capabilities: Capabilities {
                reasoning: false,
                images: false,
                tool_use: true,
            },
        };
        Model {
            meta: meta.clone(),
            provider: Arc::new(NoopProvider { models: vec![meta] }),
        }
    }

    fn test_model_with_events(events: Vec<imp_llm::Result<StreamEvent>>) -> Model {
        let meta = ModelMeta {
            id: "test-model".into(),
            provider: "test-provider".into(),
            name: "Test Model".into(),
            context_window: 8192,
            max_output_tokens: 2048,
            pricing: ModelPricing {
                input_per_mtok: 2.0,
                output_per_mtok: 4.0,
                cache_read_per_mtok: 0.5,
                cache_write_per_mtok: 1.0,
            },
            capabilities: Capabilities {
                reasoning: false,
                images: false,
                tool_use: true,
            },
        };
        Model {
            meta: meta.clone(),
            provider: Arc::new(SingleResponseProvider {
                models: vec![meta],
                events: std::sync::Mutex::new(Some(events)),
            }),
        }
    }

    fn test_assistant_message(timestamp: u64, usage: Option<Usage>) -> AssistantMessage {
        AssistantMessage {
            content: vec![ContentBlock::Text {
                text: "done".into(),
            }],
            usage,
            stop_reason: StopReason::EndTurn,
            timestamp,
        }
    }

    #[test]
    fn session_options_default_is_sensible() {
        let opts = SessionOptions::default();
        assert!(opts.model.is_none());
        assert!(opts.max_tokens.is_none());
        assert!(!opts.no_tools);
        assert!(matches!(opts.session, SessionChoice::New));
    }

    #[test]
    fn resolve_runtime_connection_prefers_openai_chatgpt_route_when_oauth_exists() {
        let dir = tempfile::tempdir().unwrap();
        let auth_path = dir.path().join("auth.json");
        let mut auth_store = AuthStore::new(auth_path);
        auth_store
            .store(
                "openai",
                imp_llm::auth::StoredCredential::OAuth(imp_llm::auth::OAuthCredential {
                    access_token: "oauth-token".into(),
                    refresh_token: "refresh-token".into(),
                    expires_at: imp_llm::now() + 3600,
                }),
            )
            .unwrap();
        let registry = ModelRegistry::with_builtins();

        let resolved = resolve_runtime_connection(
            RuntimeConnectionIntent {
                model_hint: Some("gpt-5.4"),
                config_model: None,
                provider_override: Some("openai"),
                api_key_override_present: false,
            },
            &auth_store,
            &registry,
        )
        .unwrap();

        assert_eq!(resolved.model_id, "gpt-5.4");
        assert_eq!(resolved.provider_name, "openai-codex");
    }

    #[test]
    fn resolve_runtime_connection_respects_forced_non_openai_provider() {
        let auth_path = PathBuf::from("/tmp/nonexistent-auth.json");
        let auth_store = AuthStore::new(auth_path);
        let registry = ModelRegistry::with_builtins();

        let resolved = resolve_runtime_connection(
            RuntimeConnectionIntent {
                model_hint: Some("gpt-5.4"),
                config_model: None,
                provider_override: Some("anthropic"),
                api_key_override_present: false,
            },
            &auth_store,
            &registry,
        )
        .unwrap();

        assert_eq!(resolved.provider_name, "anthropic");
    }

    #[test]
    fn resolve_runtime_connection_does_not_switch_when_model_is_not_codex_supported() {
        let dir = tempfile::tempdir().unwrap();
        let auth_path = dir.path().join("auth.json");
        let mut auth_store = AuthStore::new(auth_path);
        auth_store
            .store(
                "openai",
                imp_llm::auth::StoredCredential::OAuth(imp_llm::auth::OAuthCredential {
                    access_token: "oauth-token".into(),
                    refresh_token: "refresh-token".into(),
                    expires_at: imp_llm::now() + 3600,
                }),
            )
            .unwrap();
        let registry = ModelRegistry::with_builtins();

        let resolved = resolve_runtime_connection(
            RuntimeConnectionIntent {
                model_hint: Some("gpt-4o"),
                config_model: None,
                provider_override: Some("openai"),
                api_key_override_present: false,
            },
            &auth_store,
            &registry,
        )
        .unwrap();

        assert_eq!(resolved.model_id, "gpt-4o");
        assert_eq!(resolved.provider_name, "openai");
    }

    #[test]
    fn resolve_runtime_connection_does_not_switch_when_api_key_override_is_present() {
        let dir = tempfile::tempdir().unwrap();
        let auth_path = dir.path().join("auth.json");
        let mut auth_store = AuthStore::new(auth_path);
        auth_store
            .store(
                "openai",
                imp_llm::auth::StoredCredential::OAuth(imp_llm::auth::OAuthCredential {
                    access_token: "oauth-token".into(),
                    refresh_token: "refresh-token".into(),
                    expires_at: imp_llm::now() + 3600,
                }),
            )
            .unwrap();
        let registry = ModelRegistry::with_builtins();

        let resolved = resolve_runtime_connection(
            RuntimeConnectionIntent {
                model_hint: Some("gpt-5.4"),
                config_model: None,
                provider_override: None,
                api_key_override_present: true,
            },
            &auth_store,
            &registry,
        )
        .unwrap();

        assert_eq!(resolved.model_id, "gpt-5.4");
        assert_eq!(resolved.provider_name, "openai");
    }

    #[test]
    fn resolve_runtime_connection_prefers_kimi_code_route_when_oauth_exists_without_api_key() {
        let dir = tempfile::tempdir().unwrap();
        let auth_path = dir.path().join("auth.json");
        let mut auth_store = AuthStore::new(auth_path);
        auth_store
            .store(
                "kimi-code",
                imp_llm::auth::StoredCredential::OAuth(imp_llm::auth::OAuthCredential {
                    access_token: "oauth-token".into(),
                    refresh_token: "refresh-token".into(),
                    expires_at: imp_llm::now() + 3600,
                }),
            )
            .unwrap();
        let registry = ModelRegistry::with_builtins();

        let resolved = resolve_runtime_connection(
            RuntimeConnectionIntent {
                model_hint: Some("kimi"),
                config_model: None,
                provider_override: None,
                api_key_override_present: false,
            },
            &auth_store,
            &registry,
        )
        .unwrap();

        assert_eq!(resolved.model_id, "kimi2.6");
        assert_eq!(resolved.provider_name, "kimi-code");
    }

    #[test]
    fn resolve_runtime_connection_keeps_moonshot_kimi_when_api_key_exists() {
        let dir = tempfile::tempdir().unwrap();
        let auth_path = dir.path().join("auth.json");
        let mut auth_store = AuthStore::new(auth_path);
        auth_store
            .store(
                "moonshot",
                imp_llm::auth::StoredCredential::ApiKey {
                    key: "sk-moonshot".into(),
                },
            )
            .unwrap();
        auth_store
            .store(
                "kimi-code",
                imp_llm::auth::StoredCredential::OAuth(imp_llm::auth::OAuthCredential {
                    access_token: "oauth-token".into(),
                    refresh_token: "refresh-token".into(),
                    expires_at: imp_llm::now() + 3600,
                }),
            )
            .unwrap();
        let registry = ModelRegistry::with_builtins();

        let resolved = resolve_runtime_connection(
            RuntimeConnectionIntent {
                model_hint: Some("kimi"),
                config_model: None,
                provider_override: None,
                api_key_override_present: false,
            },
            &auth_store,
            &registry,
        )
        .unwrap();

        assert_eq!(resolved.model_id, "kimi-k2.6");
        assert_eq!(resolved.provider_name, "moonshot");
    }

    #[tokio::test]
    async fn no_tools_session_surfaces_auth_failure_instead_of_empty_api_key() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let auth_path = tmp.path().join("auth.json");
        std::fs::create_dir_all(&cwd).unwrap();

        let result = ImpSession::create(SessionOptions {
            cwd: cwd.clone(),
            auth_path: Some(auth_path),
            provider: Some("openai-codex".into()),
            model: Some("gpt-5.4".into()),
            no_tools: true,
            session: SessionChoice::InMemory,
            ..Default::default()
        })
        .await;

        match result {
            Ok(_) => panic!("missing auth should fail clearly"),
            Err(Error::Config(message)) => {
                assert!(message.contains("Auth failed for openai-codex"));
                assert!(!message.contains("Incorrect API key provided: ''"));
            }
            Err(other) => panic!("expected config error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn no_tools_session_builds_assembled_system_prompt_when_task_present() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let auth_path = tmp.path().join("auth.json");
        std::fs::create_dir_all(&cwd).unwrap();

        let mut auth_store = AuthStore::new(auth_path.clone());
        auth_store
            .store(
                "openai",
                imp_llm::auth::StoredCredential::OAuth(imp_llm::auth::OAuthCredential {
                    access_token: "oauth-token".into(),
                    refresh_token: "refresh-token".into(),
                    expires_at: imp_llm::now() + 3600,
                }),
            )
            .unwrap();

        let session = ImpSession::create(SessionOptions {
            cwd: cwd.clone(),
            auth_path: Some(auth_path),
            provider: Some("openai".into()),
            model: Some("gpt-5.4".into()),
            no_tools: true,
            session: SessionChoice::InMemory,
            task: Some(TaskContext {
                title: "Test task".into(),
                description: "Verify headless prompt assembly".into(),
                design: None,
                acceptance: Some("Prompt includes task guidance".into()),
                verify: None,
                verify_timeout_secs: None,
                fail_first: false,
                notes: None,
                attempts: vec![],
                dependencies: vec![],
                decisions: vec![],
                context_paths: vec![],
                constraints: vec![],
            }),
            ..Default::default()
        })
        .await
        .expect("no-tools session should build with saved auth");

        let prompt = session
            .agent
            .as_ref()
            .expect("agent present")
            .system_prompt
            .clone();
        assert!(!prompt.trim().is_empty());
        assert!(prompt.contains("Test task"));
        assert!(prompt.contains("Verify headless prompt assembly"));
    }

    #[tokio::test]
    async fn recv_event_returns_none_after_agent_end_even_if_sender_is_still_owned() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let (agent, handle) = Agent::new(
            clone_model(&test_model_with_events(vec![Ok(StreamEvent::MessageEnd {
                message: AssistantMessage {
                    content: vec![ContentBlock::Text {
                        text: "done".into(),
                    }],
                    usage: None,
                    stop_reason: StopReason::EndTurn,
                    timestamp: 1,
                },
            })])),
            cwd.clone(),
        );

        let mut session = ImpSession {
            agent: Some(agent),
            handle,
            session_mgr: SessionManager::in_memory(),
            config: Config::default(),
            model: test_model_with_events(vec![Ok(StreamEvent::MessageEnd {
                message: AssistantMessage {
                    content: vec![ContentBlock::Text {
                        text: "done".into(),
                    }],
                    usage: None,
                    stop_reason: StopReason::EndTurn,
                    timestamp: 1,
                },
            })]),
            auth_store: AuthStore::new(tmp.path().join("auth.json")),
            model_registry: ModelRegistry::with_builtins(),
            cwd,
            agent_task: None,
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
            context_prefill: Vec::new(),
            context_prefill_injected: false,
        };

        session.prompt("latest").await.unwrap();
        while let Some(event) = session.recv_event().await {
            if matches!(event, AgentEvent::AgentEnd { .. }) {
                break;
            }
        }

        let next = tokio::time::timeout(std::time::Duration::from_secs(1), session.recv_event())
            .await
            .expect("recv_event should not hang after agent end");
        assert!(next.is_none());

        session.wait().await.unwrap();
    }

    #[tokio::test]
    async fn abort_marks_wait_as_cancelled() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let (agent, handle) = Agent::new(
            test_model_with_events(vec![Ok(StreamEvent::MessageEnd {
                message: AssistantMessage {
                    content: vec![ContentBlock::Text {
                        text: "done".into(),
                    }],
                    usage: None,
                    stop_reason: StopReason::EndTurn,
                    timestamp: 1,
                },
            })]),
            cwd.clone(),
        );
        let mut session = ImpSession {
            agent: Some(agent),
            handle,
            session_mgr: SessionManager::in_memory(),
            config: Config::default(),
            model: test_model_with_events(vec![Ok(StreamEvent::MessageEnd {
                message: AssistantMessage {
                    content: vec![ContentBlock::Text {
                        text: "done".into(),
                    }],
                    usage: None,
                    stop_reason: StopReason::EndTurn,
                    timestamp: 1,
                },
            })]),
            auth_store: AuthStore::new(tmp.path().join("auth.json")),
            model_registry: ModelRegistry::with_builtins(),
            cwd,
            agent_task: Some(tokio::spawn(async move {
                tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                (
                    Agent::new(
                        test_model_with_events(vec![Ok(StreamEvent::MessageEnd {
                            message: AssistantMessage {
                                content: vec![ContentBlock::Text {
                                    text: "done".into(),
                                }],
                                usage: None,
                                stop_reason: StopReason::EndTurn,
                                timestamp: 1,
                            },
                        })]),
                        PathBuf::from("/tmp"),
                    )
                    .0,
                    Ok(()),
                )
            })),
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
            context_prefill: Vec::new(),
            context_prefill_injected: false,
        };

        session.abort();
        let result = session.wait().await;
        assert!(matches!(result, Err(Error::Cancelled)));
    }

    #[tokio::test]
    async fn prompt_uses_session_history_without_duplicate_active_prompt() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let session_dir = tmp.path().join("sessions");
        let model = test_model_with_events(vec![Ok(StreamEvent::MessageEnd {
            message: AssistantMessage {
                content: vec![ContentBlock::Text {
                    text: "done".into(),
                }],
                usage: None,
                stop_reason: StopReason::EndTurn,
                timestamp: 42,
            },
        })]);
        let mut session_mgr = SessionManager::new(&cwd, &session_dir).unwrap();
        session_mgr
            .append(SessionEntry::Message {
                id: "existing-user".into(),
                parent_id: None,
                message: imp_llm::Message::user("earlier"),
            })
            .unwrap();

        let (agent, handle) = Agent::new(clone_model(&model), cwd.clone());
        let mut session = ImpSession {
            agent: Some(agent),
            handle,
            session_mgr,
            config: Config::default(),
            model,
            auth_store: AuthStore::new(tmp.path().join("auth.json")),
            model_registry: ModelRegistry::with_builtins(),
            cwd,
            agent_task: None,
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
            context_prefill: Vec::new(),
            context_prefill_injected: false,
        };

        session.prompt("latest").await.unwrap();
        while let Some(event) = session.recv_event().await {
            if matches!(event, AgentEvent::AgentEnd { .. }) {
                break;
            }
        }
        session.wait().await.unwrap();

        let messages: Vec<_> = session.session_mgr.get_active_messages();
        assert_eq!(messages.len(), 3);
        match &messages[0] {
            imp_llm::Message::User(user) => match user.content.as_slice() {
                [ContentBlock::Text { text }] => assert_eq!(text, "earlier"),
                other => panic!("unexpected user content: {other:?}"),
            },
            other => panic!("unexpected message: {other:?}"),
        }
        match &messages[1] {
            imp_llm::Message::User(user) => match user.content.as_slice() {
                [ContentBlock::Text { text }] => assert_eq!(text, "latest"),
                other => panic!("unexpected user content: {other:?}"),
            },
            other => panic!("unexpected message: {other:?}"),
        }
        match &messages[2] {
            imp_llm::Message::Assistant(assistant) => match assistant.content.as_slice() {
                [ContentBlock::Text { text }] => assert_eq!(text, "done"),
                other => panic!("unexpected assistant content: {other:?}"),
            },
            other => panic!("unexpected message: {other:?}"),
        }
    }

    #[tokio::test]
    async fn prompt_uses_compacted_active_history_for_follow_up_turns() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let session_dir = tmp.path().join("sessions");
        let model = test_model_with_events(vec![Ok(StreamEvent::MessageEnd {
            message: AssistantMessage {
                content: vec![ContentBlock::Text {
                    text: "follow-up done".into(),
                }],
                usage: None,
                stop_reason: StopReason::EndTurn,
                timestamp: 99,
            },
        })]);
        let mut session_mgr = SessionManager::new(&cwd, &session_dir).unwrap();
        session_mgr
            .append(SessionEntry::Message {
                id: "u1".into(),
                parent_id: None,
                message: imp_llm::Message::user("older request"),
            })
            .unwrap();
        session_mgr
            .append(SessionEntry::Message {
                id: "a1".into(),
                parent_id: None,
                message: imp_llm::Message::Assistant(AssistantMessage {
                    content: vec![ContentBlock::Text {
                        text: "older answer".into(),
                    }],
                    usage: None,
                    stop_reason: StopReason::EndTurn,
                    timestamp: 1,
                }),
            })
            .unwrap();
        session_mgr
            .append(SessionEntry::Message {
                id: "u2".into(),
                parent_id: None,
                message: imp_llm::Message::user("recent request"),
            })
            .unwrap();
        session_mgr
            .append(SessionEntry::Compaction {
                id: "c1".into(),
                parent_id: None,
                summary: "[CONTEXT COMPACTION] compacted summary".into(),
                first_kept_id: "u2".into(),
                tokens_before: 100,
                tokens_after: 40,
            })
            .unwrap();

        let (agent, handle) = Agent::new(clone_model(&model), cwd.clone());
        let mut session = ImpSession {
            agent: Some(agent),
            handle,
            session_mgr,
            config: Config::default(),
            model,
            auth_store: AuthStore::new(tmp.path().join("auth.json")),
            model_registry: ModelRegistry::with_builtins(),
            cwd,
            agent_task: None,
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
            context_prefill: Vec::new(),
            context_prefill_injected: false,
        };

        session.prompt("new follow-up").await.unwrap();
        while let Some(event) = session.recv_event().await {
            if matches!(event, AgentEvent::AgentEnd { .. }) {
                break;
            }
        }
        session.wait().await.unwrap();

        let messages = session.session_mgr.get_active_messages();
        assert_eq!(messages.len(), 4);
        match &messages[0] {
            imp_llm::Message::User(user) => match user.content.as_slice() {
                [ContentBlock::Text { text }] => assert!(text.contains("CONTEXT COMPACTION")),
                other => panic!("unexpected summary content: {other:?}"),
            },
            other => panic!("unexpected message: {other:?}"),
        }
        match &messages[1] {
            imp_llm::Message::User(user) => match user.content.as_slice() {
                [ContentBlock::Text { text }] => assert_eq!(text, "recent request"),
                other => panic!("unexpected recent user content: {other:?}"),
            },
            other => panic!("unexpected message: {other:?}"),
        }
        match &messages[2] {
            imp_llm::Message::User(user) => match user.content.as_slice() {
                [ContentBlock::Text { text }] => assert_eq!(text, "new follow-up"),
                other => panic!("unexpected follow-up content: {other:?}"),
            },
            other => panic!("unexpected message: {other:?}"),
        }
    }

    #[test]
    fn persist_event_entries_writes_assistant_and_canonical_usage() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let session_dir = tmp.path().join("sessions");
        let model = test_model();
        let session_mgr = SessionManager::new(&cwd, &session_dir).unwrap();
        let (_agent, handle) = Agent::new(clone_model(&model), cwd.clone());

        let mut session = ImpSession {
            agent: None,
            handle,
            session_mgr,
            config: Config::default(),
            model,
            auth_store: AuthStore::new(tmp.path().join("auth.json")),
            model_registry: ModelRegistry::with_builtins(),
            cwd,
            agent_task: None,
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
            context_prefill: Vec::new(),
            context_prefill_injected: false,
        };

        let message = test_assistant_message(
            123,
            Some(Usage {
                input_tokens: 1_000,
                output_tokens: 250,
                cache_read_tokens: 100,
                cache_write_tokens: 50,
            }),
        );

        let persisted = session.persist_event_entries(&AgentEvent::TurnEnd {
            index: 2,
            message: message.clone(),
            mana_review: crate::mana_review::TurnManaReview::no_change(2),
        });

        assert_eq!(persisted, vec!["assistant message", "canonical usage"]);

        let usage_records = session.session_mgr.usage_records();
        assert_eq!(usage_records.len(), 1);
        let record = &usage_records[0];
        assert_eq!(record.turn_index, Some(2));
        assert_eq!(record.provider.as_deref(), Some("test-provider"));
        assert_eq!(record.model.as_deref(), Some("test-model"));
        assert!(record.request_id.starts_with("assistant:"));
        assert!(record.assistant_message_id.is_some());
        let cost = record.cost.as_ref().unwrap();
        assert!((cost.input - 0.002).abs() < 1e-12);
        assert!((cost.output - 0.001).abs() < 1e-12);
        assert!((cost.cache_read - 0.00005).abs() < 1e-12);
        assert!((cost.cache_write - 0.00005).abs() < 1e-12);
        assert!((cost.total - 0.0031).abs() < 1e-12);
    }

    #[test]
    fn persist_event_entries_skips_usage_record_when_usage_missing() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let session_dir = tmp.path().join("sessions");
        let model = test_model();
        let session_mgr = SessionManager::new(&cwd, &session_dir).unwrap();
        let (_agent, handle) = Agent::new(clone_model(&model), cwd.clone());

        let mut session = ImpSession {
            agent: None,
            handle,
            session_mgr,
            config: Config::default(),
            model,
            auth_store: AuthStore::new(tmp.path().join("auth.json")),
            model_registry: ModelRegistry::with_builtins(),
            cwd,
            agent_task: None,
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
            context_prefill: Vec::new(),
            context_prefill_injected: false,
        };

        let persisted = session.persist_event_entries(&AgentEvent::TurnEnd {
            index: 0,
            message: test_assistant_message(456, None),
            mana_review: crate::mana_review::TurnManaReview::no_change(0),
        });

        assert_eq!(persisted, vec!["assistant message"]);
        assert!(session.session_mgr.usage_records().is_empty());
    }

    #[test]
    fn persist_event_entries_writes_tool_results() {
        let tmp = TempDir::new().unwrap();
        let cwd = tmp.path().join("project");
        let session_dir = tmp.path().join("sessions");
        let model = test_model();
        let session_mgr = SessionManager::new(&cwd, &session_dir).unwrap();
        let (agent, handle) = Agent::new(clone_model(&model), cwd.clone());
        std::fs::create_dir_all(&cwd).unwrap();
        let file = cwd.join("tracked.rs");
        std::fs::write(&file, "original").unwrap();
        let checkpoint = agent
            .checkpoint_state
            .snapshot_paths(
                std::slice::from_ref(&file),
                Some("before tool result".into()),
            )
            .unwrap()
            .unwrap();
        std::fs::write(&file, "modified").unwrap();

        let mut session = ImpSession {
            agent: Some(agent),
            handle,
            session_mgr,
            config: Config::default(),
            model,
            auth_store: AuthStore::new(tmp.path().join("auth.json")),
            model_registry: ModelRegistry::with_builtins(),
            cwd,
            agent_task: None,
            completed_run_result: None,
            pending_persistence_errors: VecDeque::new(),
            context_prefill: Vec::new(),
            context_prefill_injected: false,
        };

        let persisted = session.persist_event_entries(&AgentEvent::ToolExecutionEnd {
            tool_call_id: "call-1".into(),
            result: imp_llm::ToolResultMessage {
                tool_call_id: "call-1".into(),
                tool_name: "bash".into(),
                content: vec![ContentBlock::Text { text: "ok".into() }],
                is_error: false,
                details: json!({"exit_code": 0}),
                timestamp: 999,
            },
            provenance: None,
        });

        assert_eq!(persisted, vec!["tool result"]);
        assert!(session.session_mgr.entries().iter().any(|entry| matches!(
            entry,
            SessionEntry::Message {
                message: imp_llm::Message::ToolResult(_),
                ..
            }
        )));
        let checkpoints = session.session_mgr.checkpoint_records();
        assert_eq!(checkpoints.len(), 1);
        assert_eq!(checkpoints[0].checkpoint_id, checkpoint.id);
        let restored = session
            .session_mgr
            .restore_checkpoint(
                session
                    .agent
                    .as_ref()
                    .expect("agent retained for persistence test")
                    .checkpoint_state
                    .as_ref(),
                &checkpoints[0].checkpoint_id,
            )
            .unwrap();
        assert_eq!(restored, vec![file.clone()]);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "original");
    }
}