opi-coding-agent 0.5.0

Interactive coding agent CLI with file editing and shell execution
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
//! Interactive CLI harness (S8.4).
//!
//! Wires together config, tools, system prompt, hooks, and Agent into a
//! single entry point for the interactive coding agent.

use std::path::{Path, PathBuf};

use opi_agent::Agent;
use opi_agent::event::AgentEvent;
use opi_agent::extension::ExtensionRegistry;
use opi_agent::hooks::AgentHooks;
use opi_agent::loop_types::{AgentError, AgentLoopConfig};
use opi_agent::message::AgentMessage;
use opi_agent::tool::Tool;
use opi_ai::message::Message;
use opi_ai::provider::{EventStream, ModelInfo, Provider, ThinkingConfig};

use crate::config::OpiConfig;
use crate::context_files;
use crate::policy::{RunMode, ToolRuntimeConfig, ToolSelection};
use crate::prompt::SystemPromptBuilder;
use crate::resource::{ExplicitResourcePaths, ResourceDiscoveryLayers, standard_discovery_layers};
use crate::session_coordinator::{SessionCoordinator, to_wire_result};
use crate::tool::{BashTool, EditTool, FindTool, GlobTool, GrepTool, LsTool, ReadTool, WriteTool};

/// Optional pre-existing session the harness can adopt instead of creating
/// a new JSONL file. Produced by `--resume` flows.
pub struct ResumeInfo {
    pub path: PathBuf,
    pub session_id: String,
    pub entries: Vec<opi_agent::session::SessionEntry>,
    /// The workspace cwd recorded in the session header. Used to restore the
    /// correct workspace root when resuming from a different directory.
    pub original_cwd: PathBuf,
}

/// Harness wiring config, tools, system prompt, hooks, and Agent.
pub struct CodingHarness {
    agent: Agent,
    config: OpiConfig,
    system_prompt: String,
    resources: HarnessResources,
    model_registry: opi_ai::ProviderRegistry,
    session: Option<SessionCoordinator>,
    /// Message count before the current turn — used to slice only new messages for persistence.
    turn_offset: usize,
    /// Images queued from --image CLI flag, injected into the first prompt.
    pending_images: Vec<opi_ai::message::InputContent>,
}

pub struct RuntimeThinkingState {
    pub level: String,
    pub enabled: bool,
    pub budget_tokens: Option<u64>,
}

/// Public metadata for resources discovered by the coding harness.
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct DiscoveredResourceMetadata {
    pub extensions: Vec<ResourceMetadataEntry>,
    pub packages: Vec<ResourceMetadataEntry>,
    pub skills: Vec<ResourceMetadataEntry>,
    pub fragments: Vec<ResourceMetadataEntry>,
    pub themes: Vec<ResourceMetadataEntry>,
    pub diagnostics: Vec<String>,
}

/// One metadata entry exposed to prompts, RPC clients, and embedders.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct ResourceMetadataEntry {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

#[derive(Debug, Clone, Default)]
struct HarnessResources {
    metadata: DiscoveredResourceMetadata,
    theme_resources: Vec<crate::theme_discovery::ThemeResource>,
}

struct MetadataProvider {
    id: String,
    models: Vec<ModelInfo>,
}

impl MetadataProvider {
    fn from_provider(provider: &dyn Provider) -> Self {
        Self {
            id: provider.id().to_owned(),
            models: provider.models().to_vec(),
        }
    }
}

impl Provider for MetadataProvider {
    fn id(&self) -> &str {
        &self.id
    }

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

    fn stream(&self, _request: opi_ai::provider::Request) -> EventStream {
        Box::pin(futures_util::stream::empty())
    }
}

impl DiscoveredResourceMetadata {
    fn format_for_system_prompt(&self) -> String {
        let mut sections = Vec::new();
        push_metadata_section(&mut sections, "Discovered packages", &self.packages);
        push_metadata_section(&mut sections, "Discovered extensions", &self.extensions);
        push_metadata_section(&mut sections, "Discovered skills", &self.skills);
        push_metadata_section(
            &mut sections,
            "Discovered prompt fragments",
            &self.fragments,
        );
        push_metadata_section(&mut sections, "Discovered themes", &self.themes);
        if !self.diagnostics.is_empty() {
            sections.push(format!(
                "Resource discovery diagnostics:\n{}",
                self.diagnostics
                    .iter()
                    .map(|diagnostic| format!("- {diagnostic}"))
                    .collect::<Vec<_>>()
                    .join("\n")
            ));
        }
        sections.join("\n\n")
    }

    pub fn to_rpc_json(&self) -> serde_json::Value {
        serde_json::json!({
            "extensions": metadata_names(&self.extensions),
            "packages": metadata_names(&self.packages),
            "skills": metadata_names(&self.skills),
            "fragments": metadata_names(&self.fragments),
            "themes": metadata_names(&self.themes),
            "diagnostics": self.diagnostics.clone(),
        })
    }

    fn add_extension_name(&mut self, name: String) {
        if self.extensions.iter().any(|entry| entry.name == name) {
            return;
        }
        self.extensions.push(ResourceMetadataEntry {
            name,
            description: None,
            version: None,
        });
        self.extensions.sort_by(|a, b| a.name.cmp(&b.name));
    }
}

fn metadata_names(entries: &[ResourceMetadataEntry]) -> Vec<&str> {
    entries.iter().map(|entry| entry.name.as_str()).collect()
}

fn push_metadata_section(
    sections: &mut Vec<String>,
    title: &str,
    entries: &[ResourceMetadataEntry],
) {
    if entries.is_empty() {
        return;
    }
    let lines = entries
        .iter()
        .map(|entry| {
            let mut line = format!("- {}", entry.name);
            if let Some(description) = &entry.description {
                line.push_str(": ");
                line.push_str(description);
            }
            if let Some(version) = &entry.version {
                line.push_str(" v");
                line.push_str(version);
            }
            line
        })
        .collect::<Vec<_>>()
        .join("\n");
    sections.push(format!("{title}:\n{lines}"));
}

fn filter_extension_tools(
    tools: Vec<Box<dyn Tool>>,
    selection: &ToolSelection,
) -> Vec<Box<dyn Tool>> {
    match selection {
        ToolSelection::Default | ToolSelection::NoBuiltin => tools,
        ToolSelection::Disabled => Vec::new(),
        ToolSelection::Allowlist(names) => tools
            .into_iter()
            .filter(|tool| {
                let name = tool.definition().name;
                names.iter().any(|allowed| allowed == &name)
            })
            .collect(),
    }
}

/// Builder for SDK embedders that need to inject extension registries or
/// precomputed discovery metadata without dynamic loading.
pub struct CodingHarnessBuilder {
    provider: Box<dyn Provider>,
    model: String,
    config: OpiConfig,
    workspace_root: PathBuf,
    hooks: Option<Box<dyn AgentHooks>>,
    user_system_prompt: Option<String>,
    initial_messages: Vec<AgentMessage>,
    resume: Option<ResumeInfo>,
    tool_config: Option<ToolRuntimeConfig>,
    tool_selection: ToolSelection,
    global_config_dir: Option<PathBuf>,
    extension_registry: Option<ExtensionRegistry>,
    resource_layers: Option<ResourceDiscoveryLayers>,
    resource_metadata: Option<DiscoveredResourceMetadata>,
}

impl CodingHarnessBuilder {
    fn new(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
    ) -> Self {
        Self {
            provider,
            model,
            config,
            workspace_root,
            hooks: None,
            user_system_prompt: None,
            initial_messages: Vec::new(),
            resume: None,
            tool_config: None,
            tool_selection: ToolSelection::Default,
            global_config_dir: None,
            extension_registry: None,
            resource_layers: None,
            resource_metadata: None,
        }
    }

    pub fn hooks(mut self, hooks: Box<dyn AgentHooks>) -> Self {
        self.hooks = Some(hooks);
        self
    }

    pub fn user_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.user_system_prompt = Some(prompt.into());
        self
    }

    pub fn initial_messages(mut self, messages: Vec<AgentMessage>) -> Self {
        self.initial_messages = messages;
        self
    }

    pub fn resume(mut self, resume: ResumeInfo) -> Self {
        self.resume = Some(resume);
        self
    }

    pub fn tool_selection(mut self, selection: ToolSelection) -> Self {
        self.tool_selection = selection;
        self
    }

    pub fn tool_config(mut self, config: ToolRuntimeConfig) -> Self {
        self.tool_config = Some(config);
        self
    }

    pub fn global_config_dir(mut self, dir: PathBuf) -> Self {
        self.global_config_dir = Some(dir);
        self
    }

    pub fn extension_registry(mut self, registry: ExtensionRegistry) -> Self {
        self.extension_registry = Some(registry);
        self
    }

    pub fn resource_layers(mut self, layers: ResourceDiscoveryLayers) -> Self {
        self.resource_layers = Some(layers);
        self
    }

    pub fn resource_metadata(mut self, metadata: DiscoveredResourceMetadata) -> Self {
        self.resource_metadata = Some(metadata);
        self
    }

    pub fn build(self) -> CodingHarness {
        let tool_selection = self.tool_selection;
        let tool_config = self.tool_config.unwrap_or_else(|| {
            ToolRuntimeConfig::resolve(RunMode::Interactive, true, tool_selection.clone())
                .expect("interactive tool config should be valid")
        });
        CodingHarness::new_with_build_options(
            self.provider,
            self.model,
            self.config,
            self.workspace_root,
            self.hooks.unwrap_or_else(|| Box::new(CodingAgentHooks)),
            self.user_system_prompt,
            self.initial_messages,
            self.resume,
            tool_config,
            self.global_config_dir,
            HarnessBuildOptions {
                extension_registry: self.extension_registry,
                resource_layers: self.resource_layers,
                resource_metadata: self.resource_metadata,
                tool_selection,
            },
        )
    }
}

struct HarnessBuildOptions {
    extension_registry: Option<ExtensionRegistry>,
    resource_layers: Option<ResourceDiscoveryLayers>,
    resource_metadata: Option<DiscoveredResourceMetadata>,
    tool_selection: ToolSelection,
}

impl Default for HarnessBuildOptions {
    fn default() -> Self {
        Self {
            extension_registry: None,
            resource_layers: None,
            resource_metadata: None,
            tool_selection: ToolSelection::Default,
        }
    }
}

impl CodingHarness {
    /// Start building a harness for SDK/embedder use.
    pub fn builder(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
    ) -> CodingHarnessBuilder {
        CodingHarnessBuilder::new(provider, model, config, workspace_root)
    }

    /// Create a new harness with the given provider, model, config, and workspace root.
    pub fn new(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
    ) -> Self {
        Self::new_with_hooks(
            provider,
            model,
            config,
            workspace_root,
            Box::new(CodingAgentHooks),
            None,
            Vec::new(),
            ToolSelection::Default,
        )
    }

    /// Create a new harness with an explicit tool selection.
    pub fn new_with_selection(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        tool_selection: ToolSelection,
    ) -> Self {
        Self::new_with_hooks(
            provider,
            model,
            config,
            workspace_root,
            Box::new(CodingAgentHooks),
            None,
            Vec::new(),
            tool_selection,
        )
    }

    /// Create a new harness with already resolved tool runtime config.
    pub fn new_with_tool_config(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        tool_config: ToolRuntimeConfig,
    ) -> Self {
        Self::new_with_hooks_and_resume_tool_config(
            provider,
            model,
            config,
            workspace_root,
            Box::new(CodingAgentHooks),
            None,
            Vec::new(),
            None,
            tool_config,
        )
    }

    /// Create a new harness with custom hooks.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_hooks(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        hooks: Box<dyn AgentHooks>,
        user_system_prompt: Option<String>,
        initial_messages: Vec<AgentMessage>,
        tool_selection: ToolSelection,
    ) -> Self {
        Self::new_with_hooks_and_resume(
            provider,
            model,
            config,
            workspace_root,
            hooks,
            user_system_prompt,
            initial_messages,
            None,
            tool_selection,
        )
    }

    /// Create a new harness, optionally adopting an existing session (resume).
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_hooks_and_resume(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        hooks: Box<dyn AgentHooks>,
        user_system_prompt: Option<String>,
        initial_messages: Vec<AgentMessage>,
        resume: Option<ResumeInfo>,
        tool_selection: ToolSelection,
    ) -> Self {
        let tool_config = ToolRuntimeConfig::resolve(RunMode::Interactive, true, tool_selection)
            .expect("interactive tool config should be valid");
        Self::new_with_hooks_and_resume_tool_config(
            provider,
            model,
            config,
            workspace_root,
            hooks,
            user_system_prompt,
            initial_messages,
            resume,
            tool_config,
        )
    }

    /// Create a new harness, optionally adopting an existing session (resume),
    /// with already resolved tool runtime config.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_hooks_and_resume_tool_config(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        hooks: Box<dyn AgentHooks>,
        user_system_prompt: Option<String>,
        initial_messages: Vec<AgentMessage>,
        resume: Option<ResumeInfo>,
        tool_config: ToolRuntimeConfig,
    ) -> Self {
        Self::new_with_global_config_dir_tool_config(
            provider,
            model,
            config,
            workspace_root,
            hooks,
            user_system_prompt,
            initial_messages,
            resume,
            tool_config,
            None,
        )
    }

    /// Create a new harness with an explicit global config directory override.
    ///
    /// When `global_config_dir` is `None`, uses the platform default from
    /// [`crate::config::user_config_dir`]. Pass `Some(path)` in tests to
    /// isolate global context file discovery from the real user config dir.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_global_config_dir(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        hooks: Box<dyn AgentHooks>,
        user_system_prompt: Option<String>,
        initial_messages: Vec<AgentMessage>,
        resume: Option<ResumeInfo>,
        tool_selection: ToolSelection,
        global_config_dir: Option<PathBuf>,
    ) -> Self {
        let tool_config = ToolRuntimeConfig::resolve(RunMode::Interactive, true, tool_selection)
            .expect("interactive tool config should be valid");
        Self::new_with_global_config_dir_tool_config(
            provider,
            model,
            config,
            workspace_root,
            hooks,
            user_system_prompt,
            initial_messages,
            resume,
            tool_config,
            global_config_dir,
        )
    }

    /// Create a new harness with an explicit global config directory override
    /// and already resolved tool runtime config.
    #[allow(clippy::too_many_arguments)]
    pub fn new_with_global_config_dir_tool_config(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        hooks: Box<dyn AgentHooks>,
        user_system_prompt: Option<String>,
        initial_messages: Vec<AgentMessage>,
        resume: Option<ResumeInfo>,
        tool_config: ToolRuntimeConfig,
        global_config_dir: Option<PathBuf>,
    ) -> Self {
        Self::new_with_build_options(
            provider,
            model,
            config,
            workspace_root,
            hooks,
            user_system_prompt,
            initial_messages,
            resume,
            tool_config,
            global_config_dir,
            HarnessBuildOptions::default(),
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn new_with_build_options(
        provider: Box<dyn Provider>,
        model: String,
        config: OpiConfig,
        workspace_root: PathBuf,
        hooks: Box<dyn AgentHooks>,
        user_system_prompt: Option<String>,
        initial_messages: Vec<AgentMessage>,
        resume: Option<ResumeInfo>,
        tool_config: ToolRuntimeConfig,
        global_config_dir: Option<PathBuf>,
        build_options: HarnessBuildOptions,
    ) -> Self {
        let mut hooks = hooks;
        let mut extension_tools = Vec::new();
        let mut injected_extension_names = Vec::new();
        let mut extension_event_registry = None;
        let extension_registry = build_options.extension_registry;
        let (model_registry, model_registry_diagnostics) =
            Self::build_model_registry(provider.as_ref(), extension_registry.as_ref());
        if let Some(registry) = extension_registry {
            extension_event_registry = Some(registry.clone());
            injected_extension_names = registry
                .names()
                .into_iter()
                .map(str::to_owned)
                .collect::<Vec<_>>();
            extension_tools =
                filter_extension_tools(registry.collect_tools(), &build_options.tool_selection);
            hooks = registry.wrap_hooks(hooks);
        }

        let mut tools = Self::build_tools(&workspace_root, &tool_config);
        tools.extend(extension_tools);
        let tool_defs: Vec<_> = tools.iter().map(|t| t.definition()).collect();
        let mut builder = SystemPromptBuilder::new().tools(tool_defs);
        if let Some(content) = user_system_prompt {
            builder = builder.user_system(content);
        }
        let resolved_global_dir = global_config_dir.unwrap_or_else(crate::config::user_config_dir);
        let mut resources = match build_options.resource_metadata {
            Some(metadata) => HarnessResources {
                metadata,
                theme_resources: Vec::new(),
            },
            None => Self::discover_resources(
                &workspace_root,
                &config,
                Some(resolved_global_dir.as_path()),
                build_options.resource_layers,
            ),
        };
        resources
            .metadata
            .diagnostics
            .extend(model_registry_diagnostics);
        for name in injected_extension_names {
            resources.metadata.add_extension_name(name);
        }

        let context = context_files::discover_context_files(
            &workspace_root,
            Some(resolved_global_dir.as_path()),
        );
        let resource_prompt = resources.metadata.format_for_system_prompt();
        let mut context_content = context.content;
        if !resource_prompt.is_empty() {
            if !context_content.is_empty() {
                context_content.push_str("\n\n");
            }
            context_content.push_str(&resource_prompt);
        }
        if !context_content.is_empty() {
            builder = builder.context_files(context_content);
        }
        let system_prompt = builder.build();

        let (thinking, max_tokens) =
            initial_thinking_request_config(&model_registry, &model, &config);
        let agent_config = AgentLoopConfig {
            max_turns: config.defaults.max_iterations,
            max_tokens,
            retry: Some(config.retry.clone()),
            thinking,
            ..Default::default()
        };

        let mut agent = Agent::new(
            provider,
            tools,
            model.clone(),
            Some(system_prompt.clone()),
            agent_config,
            hooks,
        );
        if let Some(registry) = extension_event_registry {
            agent.subscribe(Box::new(move |event| registry.dispatch_event(event)));
        }

        let initial_len = initial_messages.len();
        if !initial_messages.is_empty() {
            agent.set_initial_messages(initial_messages);
        }

        let cwd = if let Some(ref info) = resume {
            // When resuming, use the workspace cwd from the session header so
            // tools operate in the correct workspace even if the process was
            // launched from a different directory.
            info.original_cwd.to_string_lossy().into_owned()
        } else {
            std::env::current_dir()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned()
        };
        let compaction_config = opi_agent::compaction::CompactionConfig {
            enabled: config.compaction.enabled,
            threshold_tokens: config.compaction.threshold_tokens,
        };

        let session = if let Some(info) = resume {
            SessionCoordinator::open_existing(
                info.path,
                info.session_id,
                &info.entries,
                initial_len,
                compaction_config,
                model.clone(),
            )
            .ok()
        } else {
            let session_dir = crate::session_cli::session_dir();
            SessionCoordinator::new(&session_dir, &cwd, compaction_config, model.clone()).ok()
        };

        Self {
            agent,
            config,
            system_prompt,
            resources,
            model_registry,
            session,
            turn_offset: initial_len,
            pending_images: Vec::new(),
        }
    }

    /// Add an extra tool to the harness (for testing with mock tools).
    pub fn add_tool(&mut self, tool: Box<dyn Tool>) {
        self.agent.add_tool(tool);
    }

    /// Queue images to be injected into the next prompt.
    pub fn queue_images(&mut self, images: Vec<opi_ai::message::InputContent>) {
        self.pending_images.extend(images);
    }

    /// Take and clear queued images.
    pub fn take_pending_images(&mut self) -> Vec<opi_ai::message::InputContent> {
        std::mem::take(&mut self.pending_images)
    }

    /// Return model picker items from the active provider.
    pub fn model_picker_items(&self) -> Vec<opi_tui::SelectItem> {
        let current_provider = self.agent.provider().id();
        crate::picker::model_picker_items(&self.model_registry)
            .into_iter()
            .filter(|item| item.metadata == current_provider)
            .collect()
    }

    /// Change the model used by subsequent prompts.
    pub fn set_model(&mut self, model: String) {
        self.agent.set_model(model);
    }

    /// Validate and change the model used by subsequent prompts.
    pub fn set_model_validated(&mut self, model: String) -> Result<&str, String> {
        let (requested_provider, requested_model) = parse_model_spec(&model)?;
        let current_provider = self.agent.provider().id();
        if requested_provider != current_provider {
            return Err(format!(
                "cannot switch provider from {current_provider} to {requested_provider} at runtime"
            ));
        }

        let requested_model_info = self.model_info(requested_model);
        let Some(requested_model_info) = requested_model_info else {
            return Err(format!(
                "unknown model '{requested_model}' for provider '{requested_provider}'"
            ));
        };

        self.validate_current_thinking_for_model(&requested_model_info)?;

        self.agent.set_model(model);
        Ok(self.agent.model())
    }

    /// Change the thinking level used by subsequent provider requests.
    pub fn set_thinking_level(&mut self, level: &str) -> Result<RuntimeThinkingState, String> {
        let default_budget = self.config.thinking.budget_tokens as u64;
        let budget_tokens = match level {
            "off" => None,
            "low" => Some(2_048),
            "medium" => Some(default_budget),
            "high" => Some(default_budget.max(20_000)),
            _ => {
                return Err(format!(
                    "invalid thinking level '{level}': expected off, low, medium, or high"
                ));
            }
        };

        let (thinking, max_tokens) = match budget_tokens {
            Some(budget_tokens) => {
                let (thinking, max_tokens) = request_config_for_thinking_budget(budget_tokens)?;
                if let Some(model) = self.active_model_info() {
                    validate_thinking_budget_for_model(&model, budget_tokens, max_tokens)?;
                }
                (Some(thinking), Some(max_tokens))
            }
            None => (None, None),
        };

        self.agent.set_max_tokens(max_tokens);
        self.agent.set_thinking_config(thinking);
        let state = self.agent.thinking_config();
        Ok(RuntimeThinkingState {
            level: level.to_owned(),
            enabled: state.enabled,
            budget_tokens: state.budget_tokens,
        })
    }

    fn active_model_info(&self) -> Option<ModelInfo> {
        let Ok((provider_id, model_id)) = parse_model_spec(self.agent.model()) else {
            return None;
        };
        if provider_id != self.agent.provider().id() {
            return None;
        }
        self.model_info(model_id)
    }

    fn model_info(&self, model_id: &str) -> Option<ModelInfo> {
        let spec = format!("{}:{model_id}", self.agent.provider().id());
        self.model_registry
            .resolve(&spec)
            .ok()
            .map(|(_, model)| model.clone())
    }

    fn validate_current_thinking_for_model(&self, model: &ModelInfo) -> Result<(), String> {
        let thinking = self.agent.thinking_config();
        if !thinking.enabled {
            return Ok(());
        }
        let Some(budget_tokens) = thinking.budget_tokens else {
            return Ok(());
        };
        let max_tokens = max_tokens_for_thinking_budget(budget_tokens)?;
        validate_thinking_budget_for_model(model, budget_tokens, max_tokens)
    }

    /// Resume an existing session by ID into this harness.
    pub fn resume_session_id(&mut self, session_id: &str) -> Result<usize, String> {
        let dir = crate::session_cli::session_dir();
        let session =
            crate::session_cli::resume_session(&dir, session_id).map_err(|e| e.to_string())?;
        let messages = crate::session_cli::reconstruct_context(&session.entries);
        let message_count = messages.len();
        self.agent.replace_messages(messages);

        let compaction_config = opi_agent::compaction::CompactionConfig {
            enabled: self.config.compaction.enabled,
            threshold_tokens: self.config.compaction.threshold_tokens,
        };
        self.session = SessionCoordinator::open_existing(
            session.path,
            session.header.id,
            &session.entries,
            message_count,
            compaction_config,
            self.agent.model().to_string(),
        )
        .ok();
        self.turn_offset = message_count;
        Ok(message_count)
    }

    /// Return branch picker items for the currently active session.
    pub fn branch_picker_items(&self) -> Result<Vec<opi_tui::SelectItem>, String> {
        let session = self
            .session
            .as_ref()
            .ok_or_else(|| "no active session".to_owned())?;
        let (_, entries) = opi_agent::session::SessionReader::read_all(session.session_path())
            .map_err(|e| format!("failed to read session: {e}"))?;
        let tree = opi_agent::session_branch::SessionTree::from_entries(&entries);
        Ok(crate::picker::branch_picker_items(&tree))
    }

    /// Switch the current session to the branch ending at `tip_id`.
    pub fn resume_session_branch_tip(&mut self, tip_id: &str) -> Result<usize, String> {
        let session = self
            .session
            .as_mut()
            .ok_or_else(|| "no active session".to_owned())?;
        let path = session.session_path().to_path_buf();
        let session_id = session.session_id().to_owned();
        let (_, entries) = opi_agent::session::SessionReader::read_all(&path)
            .map_err(|e| format!("failed to read session: {e}"))?;
        let tree = opi_agent::session_branch::SessionTree::from_entries(&entries);
        if !tree.branches().iter().any(|branch| branch.tip_id == tip_id) {
            return Err(format!("unknown branch tip: {tip_id}"));
        }

        session
            .append_leaf(tip_id)
            .map_err(|e| format!("failed to select branch: {e}"))?;
        let (_, entries) = opi_agent::session::SessionReader::read_all(&path)
            .map_err(|e| format!("failed to read selected branch: {e}"))?;
        let messages = crate::session_cli::reconstruct_context(&entries);
        let message_count = messages.len();
        self.agent.replace_messages(messages);

        let compaction_config = opi_agent::compaction::CompactionConfig {
            enabled: self.config.compaction.enabled,
            threshold_tokens: self.config.compaction.threshold_tokens,
        };
        self.session = Some(
            SessionCoordinator::open_existing(
                path,
                session_id,
                &entries,
                message_count,
                compaction_config,
                self.agent.model().to_string(),
            )
            .map_err(|e| format!("failed to reopen selected branch: {e}"))?,
        );
        self.turn_offset = message_count;
        Ok(message_count)
    }

    /// Send a user prompt and run the agent loop.
    pub async fn prompt(&mut self, text: &str) -> Result<Vec<AgentMessage>, AgentError> {
        let offset = self.turn_offset;
        let messages = self.agent.prompt(text).await?;
        let new = &messages[offset..];
        self.persist_turn(new, offset);
        let final_messages = self.current_messages();
        self.turn_offset = final_messages.len();
        Ok(final_messages)
    }

    /// Send a user message with arbitrary content (text + images) and run the
    /// agent loop.
    pub async fn prompt_with_content(
        &mut self,
        content: Vec<opi_ai::message::InputContent>,
    ) -> Result<Vec<AgentMessage>, AgentError> {
        let offset = self.turn_offset;
        let messages = self.agent.prompt_with_content(content).await?;
        let new = &messages[offset..];
        self.persist_turn(new, offset);
        let final_messages = self.current_messages();
        self.turn_offset = final_messages.len();
        Ok(final_messages)
    }

    /// Continue the conversation with an additional message.
    pub async fn continue_(&mut self, text: &str) -> Result<Vec<AgentMessage>, AgentError> {
        let offset = self.turn_offset;
        let messages = self.agent.continue_(text).await?;
        let new = &messages[offset..];
        self.persist_turn(new, offset);
        let final_messages = self.current_messages();
        self.turn_offset = final_messages.len();
        Ok(final_messages)
    }

    /// Sum usage across every assistant message produced during a turn.
    ///
    /// A single user prompt can drive multiple provider calls (e.g.
    /// tool-call response followed by a final response). Each emitted
    /// assistant message carries its own `usage`; the cumulative session
    /// total must include all of them, not just the last one.
    fn aggregate_turn_usage(messages: &[AgentMessage]) -> opi_ai::stream::Usage {
        let mut total = opi_ai::stream::Usage::default();
        for m in messages {
            if let AgentMessage::Llm(Message::Assistant(a)) = m {
                total.input_tokens = total.input_tokens.saturating_add(a.usage.input_tokens);
                total.output_tokens = total.output_tokens.saturating_add(a.usage.output_tokens);
                total.cache_read_tokens = total
                    .cache_read_tokens
                    .saturating_add(a.usage.cache_read_tokens);
                total.cache_write_tokens = total
                    .cache_write_tokens
                    .saturating_add(a.usage.cache_write_tokens);
            }
        }
        total
    }

    /// Aggregate usage across all assistant messages in a turn and persist.
    ///
    /// If compaction was triggered during persistence, this also rewrites
    /// the Agent's message buffer to `[summary, ...kept]` so subsequent
    /// provider calls no longer carry the compacted history. Emits
    /// `CompactionStart`/`CompactionEnd` events for subscribers.
    fn persist_turn(&mut self, messages: &[AgentMessage], turn_start_agent_index: usize) {
        if let Some(session) = &mut self.session {
            let usage = Self::aggregate_turn_usage(messages);
            let compaction_reason =
                match session.on_turn_end(messages, &usage, turn_start_agent_index) {
                    Ok(reason) => reason,
                    Err(e) => {
                        self.agent.emit_event(AgentEvent::SessionPersistError {
                            message: format!("session write failed: {e}"),
                        });
                        return;
                    }
                };

            if let Some(reason) = compaction_reason {
                self.agent
                    .emit_event(AgentEvent::CompactionStart { reason });
                match session.execute_compaction(reason) {
                    Ok(Some(out)) => {
                        let wire = to_wire_result(&out);
                        self.agent.replace_messages(out.new_agent_messages);
                        self.agent.emit_event(AgentEvent::CompactionEnd {
                            reason,
                            result: Some(wire),
                            aborted: false,
                            error_message: None,
                        });
                    }
                    Ok(None) => {
                        self.agent.emit_event(AgentEvent::CompactionEnd {
                            reason,
                            result: None,
                            aborted: true,
                            error_message: Some("compaction produced no output".into()),
                        });
                    }
                    Err(e) => {
                        // Compaction marker failed to persist — leave in-memory
                        // state un-compacted (SessionCoordinator already skipped
                        // the mutation) and surface the error to subscribers.
                        self.agent.emit_event(AgentEvent::CompactionEnd {
                            reason,
                            result: None,
                            aborted: true,
                            error_message: Some(format!("compaction persist failed: {e}")),
                        });
                        self.agent.emit_event(AgentEvent::SessionPersistError {
                            message: format!("compaction write failed: {e}"),
                        });
                    }
                }
            }
        }
    }

    /// Return the current message buffer (after any compaction).
    fn current_messages(&self) -> Vec<AgentMessage> {
        // The Agent's `set_initial_messages` / `replace_messages` API doesn't
        // expose a getter, so we re-derive the buffer from what was returned
        // by the loop plus any post-loop mutation. Simplest correct option:
        // ask the Agent via a new getter.
        self.agent.messages_snapshot()
    }

    /// Return the current model name.
    pub fn model(&self) -> &str {
        self.agent.model()
    }

    /// Queue a steering message for the next provider call.
    pub fn steer(&self, message: String) {
        self.agent.steer(message);
    }

    /// Queue a follow-up message for when the agent would otherwise stop.
    pub fn follow_up(&self, message: String) {
        self.agent.follow_up(message);
    }

    /// Register an event subscriber.
    pub fn subscribe(&mut self, callback: Box<dyn Fn(&AgentEvent) + Send + Sync>) {
        self.agent.subscribe(callback);
    }

    /// Return the assembled system prompt (for testing).
    pub fn system_prompt(&self) -> &str {
        &self.system_prompt
    }

    /// Return read-only discovered resource metadata.
    pub fn resource_metadata(&self) -> &DiscoveredResourceMetadata {
        &self.resources.metadata
    }

    /// Return resource metadata in the compact RPC/session-info shape.
    pub fn resource_metadata_json(&self) -> serde_json::Value {
        self.resources.metadata.to_rpc_json()
    }

    /// Resolve a theme using discovered themes first, then built-ins.
    pub fn resolve_theme(
        &self,
        name: &str,
    ) -> Result<opi_tui::Theme, crate::theme_discovery::ThemeDiscoveryError> {
        crate::theme_discovery::ThemeRegistry::from_resources(
            self.resources.theme_resources.clone(),
        )
        .resolve_theme(name)
    }

    /// Return a reference to the config.
    pub fn config(&self) -> &OpiConfig {
        &self.config
    }

    /// Cancel the running operation.
    pub fn cancel(&self) {
        self.agent.abort();
    }

    /// Return a clonable cancellation token for external cancellation.
    pub fn cancel_token(&self) -> tokio_util::sync::CancellationToken {
        self.agent.cancel_token()
    }

    /// Return a clonable control handle for an active agent turn.
    pub fn control_handle(&self) -> opi_agent::agent::AgentControl {
        self.agent.control_handle()
    }

    /// Reset cancellation state before cloning a control handle for a new turn.
    pub fn reset_cancel_if_cancelled(&mut self) {
        self.agent.reset_cancel_if_cancelled();
    }

    /// Return the session coordinator, if active.
    pub fn session(&self) -> Option<&SessionCoordinator> {
        self.session.as_ref()
    }

    /// Execute manual compaction on the session, if one is active.
    /// Returns the compaction result, or None if compaction produced no output
    /// or no session exists.
    pub fn compact(
        &mut self,
        reason: opi_agent::session_event::CompactionReason,
    ) -> Result<Option<opi_agent::session_event::CompactionResult>, String> {
        let session = match &mut self.session {
            Some(s) => s,
            None => return Err("no active session".into()),
        };
        let result = session
            .execute_compaction(reason)
            .map_err(|e| format!("compaction failed: {e}"))?;
        if let Some(out) = &result {
            self.agent.replace_messages(out.new_agent_messages.clone());
        }
        Ok(result.map(|out| crate::session_coordinator::to_wire_result(&out)))
    }

    fn build_tools(workspace_root: &Path, tool_config: &ToolRuntimeConfig) -> Vec<Box<dyn Tool>> {
        let read_policy = match tool_config.run_mode {
            RunMode::Interactive => crate::tool::PathPolicy::AllowOutsideWorkspace,
            RunMode::NonInteractive => crate::tool::PathPolicy::WorkspaceOnly,
        };

        let mut tools: Vec<(&str, Box<dyn Tool>)> = vec![
            (
                "read",
                Box::new(ReadTool::new_with_policy(
                    workspace_root.to_path_buf(),
                    read_policy,
                )),
            ),
            (
                "write",
                Box::new(WriteTool::new(workspace_root.to_path_buf())),
            ),
            (
                "edit",
                Box::new(EditTool::new(workspace_root.to_path_buf())),
            ),
            (
                "bash",
                Box::new(BashTool::new(workspace_root.to_path_buf())),
            ),
            (
                "grep",
                Box::new(GrepTool::new(workspace_root.to_path_buf())),
            ),
            (
                "find",
                Box::new(FindTool::new(workspace_root.to_path_buf())),
            ),
            ("ls", Box::new(LsTool::new(workspace_root.to_path_buf()))),
            (
                "glob",
                Box::new(GlobTool::new(workspace_root.to_path_buf())),
            ),
        ];

        tools
            .drain(..)
            .filter(|(name, _)| {
                tool_config
                    .active_tool_names
                    .iter()
                    .any(|active| active == name)
            })
            .map(|(_, tool)| tool)
            .collect()
    }

    fn discover_resources(
        workspace_root: &Path,
        config: &OpiConfig,
        user_config_dir: Option<&Path>,
        resource_layers: Option<ResourceDiscoveryLayers>,
    ) -> HarnessResources {
        let explicit = ExplicitResourcePaths {
            extensions: config.extensions.paths.clone(),
            packages: config.packages.paths.clone(),
            ..Default::default()
        };
        let mut layers = resource_layers.unwrap_or_else(|| {
            standard_discovery_layers(workspace_root, user_config_dir, explicit)
        });
        let mut metadata = DiscoveredResourceMetadata::default();

        let packages = match crate::package_discovery::discover_packages(&layers.packages) {
            Ok(packages) => packages,
            Err(e) => {
                metadata
                    .diagnostics
                    .push(format!("package discovery failed: {e}"));
                Vec::new()
            }
        };
        metadata.packages = packages
            .iter()
            .map(|package| ResourceMetadataEntry {
                name: package.manifest.name.clone(),
                description: Some(package.manifest.description.clone()),
                version: package.manifest.version.clone(),
            })
            .collect();

        let package_layers = crate::package_discovery::package_composed_resource_layers(&packages);
        metadata.diagnostics.extend(package_layers.diagnostics);
        layers.extensions.extend(package_layers.extensions);
        layers.skills.extend(package_layers.skills);
        layers.fragments.extend(package_layers.fragments);
        layers.themes.extend(package_layers.themes);

        match crate::resource::discover_extension_resources(&layers.extensions) {
            Ok(extensions) => {
                metadata.extensions = extensions
                    .iter()
                    .map(|extension| ResourceMetadataEntry {
                        name: extension.manifest.name.clone(),
                        description: extension.manifest.description.clone(),
                        version: extension.manifest.version.clone(),
                    })
                    .collect();
            }
            Err(e) => metadata
                .diagnostics
                .push(format!("extension discovery failed: {e}")),
        }

        match crate::skill::discover_skills(&layers.skills) {
            Ok(skills) => {
                metadata.skills = skills
                    .iter()
                    .map(|skill| ResourceMetadataEntry {
                        name: skill.manifest.name.clone(),
                        description: Some(skill.manifest.description.clone()),
                        version: None,
                    })
                    .collect();
            }
            Err(e) => metadata
                .diagnostics
                .push(format!("skill discovery failed: {e}")),
        }

        match crate::prompt_fragment::discover_fragments(&layers.fragments) {
            Ok(fragments) => {
                metadata.fragments = fragments
                    .iter()
                    .map(|fragment| ResourceMetadataEntry {
                        name: fragment.manifest.name.clone(),
                        description: Some(fragment.manifest.description.clone()),
                        version: None,
                    })
                    .collect();
            }
            Err(e) => metadata
                .diagnostics
                .push(format!("fragment discovery failed: {e}")),
        }

        let theme_resources = match crate::theme_discovery::discover_themes(&layers.themes) {
            Ok(themes) => {
                metadata.themes = themes
                    .iter()
                    .map(|theme| ResourceMetadataEntry {
                        name: theme.manifest.name.clone(),
                        description: Some(theme.manifest.description.clone()),
                        version: None,
                    })
                    .collect();
                themes
            }
            Err(e) => {
                metadata
                    .diagnostics
                    .push(format!("theme discovery failed: {e}"));
                Vec::new()
            }
        };

        HarnessResources {
            metadata,
            theme_resources,
        }
    }

    fn build_model_registry(
        provider: &dyn Provider,
        extension_registry: Option<&ExtensionRegistry>,
    ) -> (opi_ai::ProviderRegistry, Vec<String>) {
        let mut registry = opi_ai::ProviderRegistry::new();
        let mut diagnostics = Vec::new();

        if let Some(extension_registry) = extension_registry {
            for provider in extension_registry.collect_providers() {
                if let Err(e) = registry.register_provider(provider) {
                    diagnostics.push(format!("extension provider registration failed: {e}"));
                }
            }
        }

        if let Err(e) =
            registry.register_provider(Box::new(MetadataProvider::from_provider(provider)))
        {
            diagnostics.push(format!("active provider metadata registration failed: {e}"));
        }

        if let Some(extension_registry) = extension_registry {
            for (provider_id, model) in extension_registry.collect_model_overrides() {
                if let Err(e) = registry.register_model(&provider_id, model) {
                    diagnostics.push(format!("extension model override registration failed: {e}"));
                }
            }
        }

        (registry, diagnostics)
    }
}

fn parse_model_spec(spec: &str) -> Result<(&str, &str), String> {
    let Some((provider, model)) = spec.split_once(':') else {
        return Err("invalid model spec: expected provider:model".into());
    };
    if provider.is_empty() || model.is_empty() {
        return Err("invalid model spec: expected provider:model".into());
    }
    Ok((provider, model))
}

fn initial_thinking_request_config(
    registry: &opi_ai::ProviderRegistry,
    model: &str,
    config: &OpiConfig,
) -> (Option<ThinkingConfig>, Option<u64>) {
    if !config.thinking.enabled {
        return (None, None);
    }

    let budget_tokens = config.thinking.budget_tokens as u64;
    let Ok((mut thinking, mut max_tokens)) = request_config_for_thinking_budget(budget_tokens)
    else {
        return (None, None);
    };

    if let Ok((_, model)) = registry.resolve(model) {
        if !model.supports_thinking {
            return (None, None);
        }
        if max_tokens > model.max_output_tokens {
            if model.max_output_tokens <= 1 {
                return (None, None);
            }
            let adjusted_budget = model.max_output_tokens - 1;
            let Ok((adjusted_thinking, adjusted_max_tokens)) =
                request_config_for_thinking_budget(adjusted_budget)
            else {
                return (None, None);
            };
            thinking = adjusted_thinking;
            max_tokens = adjusted_max_tokens;
        }
    }

    (Some(thinking), Some(max_tokens))
}

fn request_config_for_thinking_budget(budget_tokens: u64) -> Result<(ThinkingConfig, u64), String> {
    let max_tokens = max_tokens_for_thinking_budget(budget_tokens)?;
    Ok((
        ThinkingConfig {
            enabled: true,
            budget_tokens: Some(budget_tokens),
        },
        max_tokens,
    ))
}

fn max_tokens_for_thinking_budget(budget_tokens: u64) -> Result<u64, String> {
    budget_tokens.checked_add(1).ok_or_else(|| {
        format!("thinking budget {budget_tokens} cannot fit a valid max_tokens value")
    })
}

fn validate_thinking_budget_for_model(
    model: &ModelInfo,
    budget_tokens: u64,
    max_tokens: u64,
) -> Result<(), String> {
    if !model.supports_thinking {
        return Err(model_does_not_support_thinking(&model.id));
    }
    if max_tokens > model.max_output_tokens {
        return Err(thinking_budget_exceeds_model_limit(
            budget_tokens,
            max_tokens,
            model.max_output_tokens,
            &model.id,
        ));
    }
    Ok(())
}

fn model_does_not_support_thinking(model_id: &str) -> String {
    format!("model '{model_id}' does not support thinking")
}

fn thinking_budget_exceeds_model_limit(
    budget_tokens: u64,
    max_tokens: u64,
    max_output_tokens: u64,
    model_id: &str,
) -> String {
    format!(
        "thinking budget {budget_tokens} requires max_tokens {max_tokens}, exceeding max output tokens {max_output_tokens} for model '{model_id}'"
    )
}

// ---------------------------------------------------------------------------
// Hooks
// ---------------------------------------------------------------------------

/// Shared conversion of agent-level messages to the provider-facing Message
/// stream. Used by every hook in this crate so resume/compaction semantics
/// stay consistent between interactive and non-interactive paths.
///
/// - `AgentMessage::Llm` is forwarded directly.
/// - `AgentMessage::CompactionSummary` is rendered as a synthetic user
///   message so the provider sees a textual marker for context that was
///   compacted away.
/// - Other variants (`BranchSummary`, `Custom`) are dropped — they have no
///   provider-facing representation yet.
pub(crate) fn agent_messages_to_llm(messages: &[AgentMessage]) -> Vec<Message> {
    let mut result = Vec::with_capacity(messages.len());
    for msg in messages {
        match msg {
            AgentMessage::Llm(m) => result.push(m.clone()),
            AgentMessage::CompactionSummary(summary) => {
                result.push(Message::User(opi_ai::message::UserMessage {
                    content: vec![opi_ai::message::InputContent::Text {
                        text: format!(
                            "[Context was compacted. Summary of earlier conversation: {}]",
                            summary.summary
                        ),
                    }],
                    timestamp_ms: 0,
                }));
            }
            _ => {}
        }
    }
    result
}

/// Default hooks for the coding agent -- pass-through message conversion.
pub struct CodingAgentHooks;

impl AgentHooks for CodingAgentHooks {
    fn convert_to_llm(&self, messages: &[AgentMessage]) -> Result<Vec<Message>, AgentError> {
        Ok(agent_messages_to_llm(messages))
    }
}

/// Interactive hooks for the coding agent.
///
/// Tool safety is controlled by active tool selection and extension hooks, not
/// by a core interactive permission popup.
pub struct InteractiveCodingHooks;

impl InteractiveCodingHooks {
    pub fn new(_allow_mutating: bool) -> Self {
        Self
    }
}

impl AgentHooks for InteractiveCodingHooks {
    fn convert_to_llm(&self, messages: &[AgentMessage]) -> Result<Vec<Message>, AgentError> {
        Ok(agent_messages_to_llm(messages))
    }
}