supercode-harness 0.4.17

The optional native Supercode agent and tool harness
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
//! Versioned public SDK contract shared by every Supercode surface.
//!
//! This module names the operations, capabilities, events, and errors that
//! transports project. CLI, JSON-RPC, HTTP, MCP, ACP, and language clients
//! may add correlation ids or wire metadata, but they must not define a
//! second execution contract or place those envelope fields in a session.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::Path;
use std::sync::Arc;

use crate::{
    Agent, Config, DiscoveryPage, DiscoveryQuery, Fidelity, HarnessCatalog, Result as CoreResult,
    Session, SessionDescriptor, SessionLocator,
};

/// Renderable prompt source configured on an SDK emulation component.
///
/// MCP implements this seam, but the SDK does not depend on MCP transport or
/// client types, so removing the MCP adapter leaves runtime semantics intact.
#[async_trait]
pub trait SdkPromptSource: Send + Sync {
    /// Render one prompt with its named arguments.
    async fn render(&self, args: std::collections::BTreeMap<String, String>) -> CoreResult<String>;
    /// Declared argument names in stable source order.
    fn arg_names(&self) -> &[String];
}

/// Current language-neutral SDK schema.
pub const SDK_SCHEMA_VERSION: &str = "supercode.sdk.v1";

/// Discover persisted sessions through the canonical SDK catalog owner.
pub fn discover_sessions(query: &DiscoveryQuery) -> CoreResult<Vec<SessionDescriptor>> {
    Ok(HarnessCatalog::new().discover(query)?)
}

/// Discover one persisted-session page with its opaque successor cursor.
pub fn discover_session_page(query: &DiscoveryQuery) -> CoreResult<DiscoveryPage> {
    Ok(HarnessCatalog::new().discover_page(query)?)
}

/// Load one durable locator through the canonical SDK catalog owner.
pub fn load_session(locator: &SessionLocator) -> CoreResult<Session> {
    Ok(HarnessCatalog::new().load(locator)?)
}

/// [`load_session`] at a declared fidelity.
///
/// Read-only surfaces pass [`Fidelity::Semantic`] so a transcript whose record
/// graph cannot be reconstructed exactly still renders, with the degradation
/// named in [`Session::load_residue`]. Continuation, transfer and export
/// callers keep the strict default of [`load_session`].
pub fn load_session_with_fidelity(
    locator: &SessionLocator,
    fidelity: Fidelity,
) -> CoreResult<Session> {
    Ok(HarnessCatalog::new().load_with_fidelity(locator, fidelity)?)
}

/// Load an explicit transcript/store path through the SDK import boundary.
/// An OpenCode selector is accepted only for its SQLite store.
pub fn load_session_path(path: &Path, opencode_session: Option<&str>) -> CoreResult<Session> {
    if opencode_session.is_some() {
        return Ok(Session::from_opencode_sqlite(path, opencode_session)?);
    }
    if let Some(session) = load_native_store_family(path)? {
        return Ok(session);
    }
    Ok(Session::load(path)?)
}

pub(crate) fn load_native_store_family(path: &Path) -> CoreResult<Option<Session>> {
    Ok(supercode_interchange::load_native_store_family(path)?)
}

/// SDK-owned emulation runtime component.
///
/// The wrapper makes ownership transfer explicit: public adapters receive an
/// SDK component, and [`crate::server::RpcEngine`] consumes that component as
/// the sole live-loop owner. It intentionally does not implement `Deref`:
/// model/tool-loop entry points stay unreachable outside the SDK/runtime
/// implementation boundary.
pub struct SdkAgent(Agent);

impl SdkAgent {
    pub(crate) fn from_agent(agent: Agent) -> Self {
        Self(agent)
    }

    pub(crate) fn inner(&self) -> &Agent {
        &self.0
    }

    pub(crate) fn inner_mut(&mut self) -> &mut Agent {
        &mut self.0
    }

    /// Read the resolved runtime configuration without acquiring loop ownership.
    pub fn config(&self) -> &Config {
        self.0.config()
    }

    /// Install the full-fidelity sidecar writer used by SDK persistence.
    pub fn set_recorder(&mut self, writer: crate::sidecar::SidecarWriter) {
        self.0.set_recorder(writer);
    }

    // ---- BP-8: session durability (catalog:150/151/152/154/156) ---------

    /// Install the append-only session journal — see
    /// [`crate::agent::Agent::set_journal`].
    pub fn set_journal(&mut self, journal: crate::session_journal::SessionJournal) {
        self.0.set_journal(journal);
    }

    /// Whether an append-only journal is installed.
    pub fn has_journal(&self) -> bool {
        self.0.has_journal()
    }

    /// Declare the durable view caught up at `messages` messages.
    pub fn journal_checkpoint(&self, messages: usize) {
        self.0.journal_checkpoint(messages);
    }

    /// This session's in-place conversation tree, when the module is on.
    pub fn session_tree(&self) -> Option<&crate::session_tree::SessionTree> {
        self.0.session_tree()
    }

    /// Install a tree loaded from the store.
    pub fn set_session_tree(&mut self, tree: crate::session_tree::SessionTree) {
        self.0.set_session_tree(tree);
    }

    /// Materialize the degenerate single-path tree from the live history.
    pub fn rebuild_session_tree_from_history(&mut self) {
        self.0.rebuild_session_tree_from_history();
    }

    /// Rewind THIS conversation to an earlier point, recorded and
    /// invertible — see [`crate::agent::Agent::rewind_conversation`].
    pub fn rewind_conversation(&mut self, keep: usize) -> crate::agent::RewindOutcome {
        self.0.rewind_conversation(keep)
    }

    /// Invert the most recent rewind.
    pub fn undo_rewind(&mut self) -> bool {
        self.0.undo_rewind()
    }

    /// How many rewinds are currently undoable.
    pub fn undoable_rewinds(&self) -> usize {
        self.0.undoable_rewinds()
    }

    /// Restore an undo stack recovered from the journal.
    pub fn restore_rewind_undo(&mut self, stack: Vec<Vec<crate::ChatMessage>>) {
        self.0.restore_rewind_undo(stack);
    }

    /// Re-queue pending inputs recovered from the journal.
    pub fn restore_queues(&mut self, steer: &[String], follow_up: &[String]) {
        self.0.restore_queues(steer, follow_up);
    }

    /// Append messages recovered from the journal after a crash.
    pub fn append_recovered_messages(&mut self, messages: &[crate::ChatMessage]) {
        self.0.append_recovered_messages(messages);
    }

    /// The session's `update_plan` checklist.
    pub fn plan(&self) -> Vec<crate::session_journal::PlanEntry> {
        self.0.plan()
    }

    /// Restore a plan read back from the store.
    pub fn set_plan(&mut self, steps: Vec<crate::session_journal::PlanEntry>) {
        self.0.set_plan(steps);
    }

    /// BP-8: arm `[core.session]`'s durability for `name` and restore what a
    /// previous process left — see [`crate::session_journal::arm`].
    pub fn arm_session_journal(
        &mut self,
        store: &crate::store::SessionStore,
        name: &str,
    ) -> crate::session_journal::RestoreReport {
        crate::session_journal::arm(&mut self.0, store, name)
    }

    /// BP-8: the mirror — see [`crate::session_journal::checkpoint`].
    pub fn checkpoint_session_journal(
        &self,
        store: &crate::store::SessionStore,
        name: &str,
        messages: usize,
    ) {
        crate::session_journal::checkpoint(&self.0, store, name, messages);
    }

    /// BP-3 (§2 module 8 `plan_mode`): the session's shared plan-mode state
    /// — what a composer's `/plan` toggles and the permission gate reads.
    /// Reading or toggling it acquires no loop ownership.
    pub fn plan_mode(&self) -> &std::sync::Arc<crate::tools::PlanModeState> {
        self.0.plan_mode()
    }

    /// Install the reversible provider-view reduction policy.
    pub fn set_reduction_policy(&mut self, policy: crate::reduce::ReductionPolicy) {
        self.0.set_reduction_policy(policy);
    }

    /// Inspect the current provider-view reduction policy.
    pub fn reduction_policy(&self) -> Option<&crate::reduce::ReductionPolicy> {
        self.0.reduction_policy()
    }

    /// Replace the reversible reduction log after an SDK-owned projection.
    pub fn set_reduction_log(&mut self, log: crate::reduce::ReductionLog) {
        self.0.set_reduction_log(log);
    }

    /// Inspect the reversible reduction log.
    pub fn reduction_log(&self) -> &crate::reduce::ReductionLog {
        self.0.reduction_log()
    }

    /// Prepare optional cleared-turn summary metadata without sending a turn.
    pub fn prepare_cleared_turns_summary(
        &self,
        messages: &[crate::ChatMessage],
        policy: &crate::reduce::ReductionPolicy,
        prior: &crate::reduce::ReductionLog,
    ) -> Option<crate::reduce::PreparedClearSummary> {
        self.0
            .prepare_cleared_turns_summary(messages, policy, prior)
    }

    /// Install a reduction span summarizer.
    pub fn set_span_summarizer(
        &mut self,
        summarizer: impl crate::reduce::summarize::SpanSummarizer + Send + Sync + 'static,
    ) {
        self.0.set_span_summarizer(summarizer);
    }

    /// Install the optional persisted-session title generator.
    pub fn set_session_titler(
        &mut self,
        titler: impl crate::session_title::SessionTitler + Send + Sync + 'static,
    ) {
        self.0.set_session_titler(titler);
    }

    /// Generate a title from canonical history when configured.
    pub fn auto_title(&self) -> Option<String> {
        self.0.auto_title()
    }

    /// Attach a session store for SDK-owned subagent persistence.
    pub fn set_subagent_store(
        &mut self,
        store: std::sync::Arc<crate::SessionStore>,
        session_name: impl Into<String>,
    ) {
        self.0.set_subagent_store(store, session_name);
    }

    /// Install restored Claude runtime state without activating a timer.
    pub fn set_claude_runtime_manifest(
        &mut self,
        manifest: crate::claude_runtime_state::ClaudeRuntimeManifest,
    ) {
        self.0.set_claude_runtime_manifest(manifest);
    }

    /// Inspect restored Claude runtime state.
    pub fn claude_runtime_manifest(
        &self,
    ) -> Option<&crate::claude_runtime_state::ClaudeRuntimeManifest> {
        self.0.claude_runtime_manifest()
    }

    /// Mutate Claude runtime state from the SDK scheduler/persistence driver.
    pub fn claude_runtime_manifest_mut(
        &mut self,
    ) -> Option<&mut crate::claude_runtime_state::ClaudeRuntimeManifest> {
        self.0.claude_runtime_manifest_mut()
    }

    /// Restore project-scoped Claude agent definitions after disk reload.
    pub fn restore_claude_project_agents(&mut self) -> CoreResult<usize> {
        self.0.restore_claude_project_agents()
    }

    /// Replace canonical history with a loaded normalized session.
    pub fn load_session(&mut self, session: Session) {
        self.0.load_session(session);
    }

    /// Load a Supercode transcript through the SDK component.
    pub fn load_transcript(&mut self, path: impl AsRef<Path>) -> CoreResult<()> {
        self.0.load_transcript(path)
    }

    /// Save the canonical transcript through the SDK component.
    pub fn save_transcript(&self, path: impl AsRef<Path>) -> CoreResult<()> {
        self.0.save_transcript(path)
    }

    /// Read canonical history at a quiescent boundary.
    pub fn history(&self) -> &[crate::ChatMessage] {
        self.0.history()
    }

    /// Rewind canonical history to a prior message boundary.
    pub fn rewind_to(&mut self, checkpoint: usize) {
        self.0.rewind_to(checkpoint);
    }

    /// BP-4 (catalog:98): compact now, with optional `/compact <focus>`
    /// steering text — see [`Agent::compact_now`].
    pub fn compact_now(&mut self, focus: Option<&str>) -> bool {
        self.0.compact_now(focus)
    }

    /// BP-4 (catalog:109): live context-window accounting — see
    /// [`Agent::context_usage`].
    pub fn context_usage(&self) -> crate::ContextUsage {
        self.0.context_usage()
    }

    /// BP-4 (catalog:106): reset the working view to a fresh objective plus
    /// a curated keep-set — see [`Agent::new_context`].
    pub fn new_context(&mut self, objective: &str, keep_recent: Option<usize>) -> usize {
        self.0.new_context(objective, keep_recent)
    }

    /// BP-4 (catalog:91): splice an ambient context block into the live
    /// session — see [`Agent::inject_context_block`].
    pub fn inject_context_block(
        &mut self,
        name: impl Into<String>,
        content: impl Into<String>,
    ) -> bool {
        self.0.inject_context_block(name, content)
    }

    /// BP-4 (catalog:90): re-derive and re-emit the environment context
    /// block if it changed — see [`Agent::refresh_env_context`].
    pub fn refresh_env_context(&mut self) -> bool {
        self.0.refresh_env_context()
    }

    /// Append an SDK-assembled system note.
    pub fn append_system_note(&mut self, text: &str) {
        self.0.append_system_note(text);
    }

    /// Register one configured tool before transferring live-loop ownership.
    pub fn register_tool(&mut self, tool: impl crate::Tool + 'static) {
        self.0.register_tool(tool);
    }

    /// Register one MCP prompt source before transferring loop ownership.
    pub fn register_mcp_prompt(
        &mut self,
        command_name: impl Into<String>,
        source: impl SdkPromptSource + 'static,
    ) {
        self.0.register_mcp_prompt(command_name, source);
    }

    /// Inspect the exact next-request tool schemas for preflight measurement.
    pub fn tool_schemas(&self) -> Vec<crate::ToolSchema> {
        self.0.tool_schemas()
    }

    /// Arm the per-request context limit guard.
    pub fn set_context_limit(&mut self, limit: u64) {
        self.0.set_context_limit(limit);
    }

    /// Inspect the armed context limit.
    pub fn context_limit(&self) -> Option<u64> {
        self.0.context_limit()
    }

    /// Switch the next-request model at a quiescent boundary.
    pub fn set_model(&mut self, model: impl Into<String>) {
        self.0.set_model(model);
    }

    /// BP-13 (catalog D9 "Fast mode / service tiers"): set or clear the
    /// session-level service-tier override — what `/fast` pulls. `None`
    /// restores whatever the routing table resolved for the model.
    pub fn set_service_tier(&mut self, tier: Option<String>) {
        self.0.set_service_tier(tier);
    }

    /// BP-13: the model this runtime sends on its next request.
    pub fn model(&self) -> &str {
        self.0.model()
    }

    /// BP-13 (catalog D9 "Mid-session model switching"): the GOVERNED
    /// switch — under `[core.model_switch] allow_switch` it strips model-A
    /// reasoning artifacts from the live history (dep 8), records the
    /// change in the session journal, and emits it, before moving
    /// `Config::model`. With the gate off it is exactly [`Self::set_model`].
    pub fn switch_model(&mut self, model: impl Into<String>) {
        self.0.switch_model(model);
    }

    /// Whether a provider request has actually been issued.
    pub fn request_issued(&self) -> bool {
        self.0.request_issued()
    }

    /// Configured durable session name.
    pub fn session_name(&self) -> Option<&str> {
        self.0.session_name()
    }

    /// Whether persistence is enabled for this component.
    pub fn session_persist(&self) -> bool {
        self.0.session_persist()
    }

    /// Captured git provenance.
    pub fn git_metadata(&self) -> Option<&crate::git_metadata::GitMetadataRecord> {
        self.0.git_metadata()
    }

    /// Save captured git provenance.
    pub fn save_git_metadata(&self, store: &crate::SessionStore, name: &str) -> CoreResult<()> {
        self.0.save_git_metadata(store, name)
    }

    /// BP-7: save the accumulated per-turn usage log (tokens + cost).
    pub fn save_usage_log(&self, store: &crate::SessionStore, name: &str) -> CoreResult<()> {
        self.0.save_usage_log(store, name)
    }

    /// BP-7: the per-round-trip marker log.
    pub fn turn_records(&self) -> &[crate::turn_record::TurnRecord] {
        self.0.turn_records()
    }

    /// BP-7: save the per-round-trip marker log.
    pub fn save_turn_records(&self, store: &crate::SessionStore, name: &str) -> CoreResult<()> {
        self.0.save_turn_records(store, name)
    }

    /// BP-7: record that the in-flight turn was interrupted.
    pub fn note_abort(&mut self, source: &str) {
        self.0.note_abort(source);
    }

    /// BP-7: dollars spent so far (see [`Self::model_priced`]).
    pub fn total_cost_usd(&self) -> f64 {
        self.0.total_cost_usd()
    }

    /// BP-7: whether this build can price this component's model.
    pub fn model_priced(&self) -> bool {
        self.0.model_priced()
    }

    /// BP-7: tool calls executed so far.
    pub fn total_steps(&self) -> usize {
        self.0.total_steps()
    }

    /// BP-7: set or revise the session's standing objective.
    pub fn set_goal(&mut self, objective: impl Into<String>) -> bool {
        self.0.set_goal(objective)
    }

    /// BP-7: the session's standing objective.
    pub fn goal(&self) -> Option<&crate::goals::GoalRecord> {
        self.0.goal()
    }

    /// BP-7: drop the standing objective.
    pub fn clear_goal(&mut self) -> bool {
        self.0.clear_goal()
    }

    /// BP-7: adopt a goal loaded from the store.
    pub fn restore_goal(&mut self, goal: Option<crate::goals::GoalRecord>) {
        self.0.restore_goal(goal);
    }

    /// BP-7: persist (or clear) the standing objective.
    pub fn save_goal(&self, store: &crate::SessionStore, name: &str) -> CoreResult<()> {
        self.0.save_goal(store, name)
    }

    /// BP-7: the reasoning-effort level in force, `None` when off.
    pub fn effort(&self) -> Option<&str> {
        self.0.effort()
    }

    /// BP-7: change reasoning effort mid-session; `None` turns it off.
    pub fn set_effort(&mut self, effort: Option<String>) -> Option<String> {
        self.0.set_effort(effort)
    }

    /// BP-7: this harness's review-turn prompt with `{args}` filled in.
    pub fn review_prompt(&self, args: &str) -> Option<String> {
        self.0.review_prompt(args)
    }

    /// BP-7: a tool-less question over the full context that records
    /// nothing.
    pub async fn side_question(&self, question: &str) -> CoreResult<String> {
        self.0.side_question(question).await
    }

    /// Number of non-system canonical messages.
    pub fn turn_count(&self) -> usize {
        self.0.turn_count()
    }

    /// Cumulative provider-reported output tokens.
    pub fn total_output_tokens(&self) -> u64 {
        self.0.total_output_tokens()
    }
}

impl From<Agent> for SdkAgent {
    fn from(agent: Agent) -> Self {
        Self::from_agent(agent)
    }
}

/// Construct the emulation component inside the SDK ownership boundary.
pub fn create_agent(config: Config) -> CoreResult<SdkAgent> {
    Agent::new(config).map(SdkAgent::from_agent)
}

/// Resume canonical history inside a fresh SDK-owned emulation component.
pub fn resume_agent(config: Config, session: Session) -> CoreResult<SdkAgent> {
    Agent::resume(config, session).map(SdkAgent::from_agent)
}

/// Submit one text turn through the SDK-owned emulation loop.
pub async fn submit_agent(agent: &mut SdkAgent, prompt: &str) -> CoreResult<String> {
    agent.0.send(prompt).await
}

/// BP-5 (catalog D2 "Prompt-input debugging"): render the exact model-visible
/// input `prompt` would produce, as JSON, without sending anything.
///
/// The prompt is expanded exactly as [`submit_agent`] would expand it and the
/// request is assembled by the loop's own `chat_request`, so this is the real
/// input rather than a second rendering of it. Nothing is recorded, nothing is
/// persisted, and no provider request is issued.
pub async fn show_model_input(agent: &mut SdkAgent, prompt: &str) -> serde_json::Value {
    let req = agent.0.model_input_for(prompt).await;
    Agent::render_model_input(&req)
}

/// Submit one multimodal turn through the SDK-owned emulation loop.
pub async fn submit_agent_with_images(
    agent: &mut SdkAgent,
    prompt: &str,
    image_urls: &[String],
) -> CoreResult<String> {
    agent.0.send_with_images(prompt, image_urls).await
}

/// One operation owned by the SDK facade.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SdkOperation {
    /// Discover persisted sessions.
    Discover,
    /// Load one persisted session without modifying it.
    Load,
    /// Start a harness-native runtime.
    Start,
    /// Resume a harness-native persisted runtime.
    Resume,
    /// Send input to an SDK-owned runtime connection.
    Input,
    /// Poll canonical runtime events.
    Events,
    /// Interrupt the active turn.
    Interrupt,
    /// Queue guidance at the next model-loop boundary.
    Steer,
    /// Answer a typed runtime request.
    Respond,
    /// Export a loaded session through a native serializer.
    Export,
    /// List the harness's scheduled jobs (observed tier, read-only).
    JobsList,
    /// Read one scheduled job's definition (observed tier, read-only).
    JobsGet,
    /// Create a scheduled job through the harness's own verb (ORCH-18).
    JobsCreate,
    /// Patch a scheduled job through the harness's own verb.
    JobsUpdate,
    /// Stop the harness's scheduler from firing a job.
    JobsPause,
    /// Let the harness's scheduler fire a job again.
    JobsResume,
    /// Fire a job now through the harness's own verb.
    JobsRun,
    /// Delete a scheduled job through the harness's own verb.
    JobsDelete,
    /// Open a fresh conversation through the harness's own door (ORCH-19).
    SessionsNew,
    /// Reset a conversation through the harness's own door.
    SessionsReset,
    /// Archive a conversation through the harness's own door.
    SessionsArchive,
    /// Delete a conversation through the harness's own door.
    SessionsDelete,
    /// List a job's past fires with their outcomes (ORCH-8, read-only).
    RunsList,
    /// Read one fire's outcome (ORCH-8, read-only).
    RunsGet,
    /// Close an SDK-owned runtime connection.
    Close,
    /// List the harnesses' named config homes (ORCH-10, read-only).
    ProfilesList,
    /// Read one named config home by harness and name.
    ProfilesGet,
    /// Create a named config home through the harness's own verb (ORCH-21).
    ProfilesCreate,
    /// Delete a named config home through the harness's own verb (ORCH-21).
    ProfilesDelete,
    /// List the skill packages each harness has installed (ORCH-11, read-only).
    SkillsList,
    /// Install a skill package through the harness's own door (ORCH-22).
    SkillsInstall,
    /// Remove a skill package through the harness's own door (ORCH-22).
    SkillsRemove,
    /// Read a harness's persistent memory documents (ORCH-12, read-only).
    MemoryShow,
    /// Search those same documents by substring or regex (ORCH-12, read-only).
    MemorySearch,
    /// List the approval requests waiting for an answer (ORCH-9, read-only).
    ApprovalsList,
    /// Answer one listed approval request with a uniform decision (ORCH-20).
    ApprovalsResolve,
    /// List the transports each gateway harness is reachable on (ORCH-14).
    ChannelsList,
    /// List the routes a gateway harness uses to pick a profile / agent (ORCH-15).
    RoutesList,
    /// List a gateway harness's inbound triggers — webhook routes and hook mappings (ORCH-16).
    TriggersList,
    /// Read one channel's row by harness and name (ORCH-14).
    ChannelsStatus,
    /// Read one home folder as one typed world value (ONT-4).
    WorldLoad,
    /// Write a world value back into our own folder (ONT-4).
    WorldSave,
    /// Compile another harness's home into a world value (ONT-4).
    WorldCompile,
    /// Decompile a world back into another harness's home (ONT-4).
    WorldDecompile,
    /// Another harness's home becomes our folder, credentials along (ONT-7).
    WorldImport,
    /// Our folder becomes another harness's home, credentials along (ONT-7).
    WorldExport,
}

impl SdkOperation {
    /// Complete v1 operation inventory in stable declaration order.
    pub const ALL: [Self; 46] = [
        Self::Discover,
        Self::Load,
        Self::Start,
        Self::Resume,
        Self::Input,
        Self::Events,
        Self::Interrupt,
        Self::Steer,
        Self::Respond,
        Self::Export,
        Self::JobsList,
        Self::JobsGet,
        Self::JobsCreate,
        Self::JobsUpdate,
        Self::JobsPause,
        Self::JobsResume,
        Self::JobsRun,
        Self::JobsDelete,
        Self::SessionsNew,
        Self::SessionsReset,
        Self::SessionsArchive,
        Self::SessionsDelete,
        Self::RunsList,
        Self::RunsGet,
        Self::Close,
        Self::ProfilesList,
        Self::ProfilesGet,
        Self::ProfilesCreate,
        Self::ProfilesDelete,
        Self::SkillsList,
        Self::SkillsInstall,
        Self::SkillsRemove,
        Self::MemoryShow,
        Self::MemorySearch,
        Self::ApprovalsList,
        Self::ApprovalsResolve,
        Self::ChannelsList,
        Self::RoutesList,
        Self::TriggersList,
        Self::ChannelsStatus,
        Self::WorldLoad,
        Self::WorldSave,
        Self::WorldCompile,
        Self::WorldDecompile,
        Self::WorldImport,
        Self::WorldExport,
    ];

    /// Canonical `harness.v1` method used by JSON transports, when the
    /// operation is request/response rather than a subscription poll.
    pub const fn method(self) -> Option<&'static str> {
        match self {
            Self::Discover => Some("harness.v1.sessions.discover"),
            Self::Load => Some("harness.v1.sessions.load"),
            Self::Start => Some("harness.v1.runtimes.start"),
            Self::Resume => Some("harness.v1.runtimes.resume"),
            Self::Input => Some("harness.v1.runtimes.send_input"),
            Self::Events => None,
            Self::Interrupt => Some("harness.v1.runtimes.interrupt"),
            Self::Steer => Some("harness.v1.runtimes.steer"),
            Self::Respond => Some("harness.v1.runtimes.respond"),
            Self::Export => Some("harness.v1.sessions.export"),
            Self::JobsList => Some("harness.v1.jobs.list"),
            Self::JobsGet => Some("harness.v1.jobs.get"),
            Self::JobsCreate => Some("harness.v1.jobs.create"),
            Self::JobsUpdate => Some("harness.v1.jobs.update"),
            Self::JobsPause => Some("harness.v1.jobs.pause"),
            Self::JobsResume => Some("harness.v1.jobs.resume"),
            Self::JobsRun => Some("harness.v1.jobs.run"),
            Self::JobsDelete => Some("harness.v1.jobs.delete"),
            Self::SessionsNew => Some("harness.v1.sessions.new"),
            Self::SessionsReset => Some("harness.v1.sessions.reset"),
            Self::SessionsArchive => Some("harness.v1.sessions.archive"),
            Self::SessionsDelete => Some("harness.v1.sessions.delete"),
            Self::RunsList => Some("harness.v1.runs.list"),
            Self::RunsGet => Some("harness.v1.runs.get"),
            Self::Close => Some("harness.v1.runtimes.close"),
            Self::ProfilesList => Some("harness.v1.profiles.list"),
            Self::ProfilesGet => Some("harness.v1.profiles.get"),
            Self::ProfilesCreate => Some("harness.v1.profiles.create"),
            Self::ProfilesDelete => Some("harness.v1.profiles.delete"),
            Self::SkillsList => Some("harness.v1.skills.list"),
            Self::SkillsInstall => Some("harness.v1.skills.install"),
            Self::SkillsRemove => Some("harness.v1.skills.remove"),
            Self::MemoryShow => Some("harness.v1.memory.show"),
            Self::MemorySearch => Some("harness.v1.memory.search"),
            Self::ApprovalsList => Some("harness.v1.approvals.list"),
            Self::ApprovalsResolve => Some("harness.v1.approvals.resolve"),
            Self::ChannelsList => Some("harness.v1.channels.list"),
            Self::RoutesList => Some("harness.v1.routes.list"),
            Self::TriggersList => Some("harness.v1.triggers.list"),
            Self::ChannelsStatus => Some("harness.v1.channels.status"),
            Self::WorldLoad => Some("harness.v1.world.load"),
            Self::WorldSave => Some("harness.v1.world.save"),
            Self::WorldCompile => Some("harness.v1.world.compile"),
            Self::WorldDecompile => Some("harness.v1.world.decompile"),
            Self::WorldImport => Some("harness.v1.world.import"),
            Self::WorldExport => Some("harness.v1.world.export"),
        }
    }

    /// Resolve one canonical method without accepting transport aliases.
    pub fn from_method(method: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|operation| operation.method() == Some(method))
    }

    /// Stable action spelling used by capability and error projections.
    pub const fn action_name(self) -> &'static str {
        match self {
            Self::Discover => "discover",
            Self::Load => "load",
            Self::Start => "start",
            Self::Resume => "resume",
            Self::Input => "input",
            Self::Events => "events",
            Self::Interrupt => "interrupt",
            Self::Steer => "steer",
            Self::Respond => "respond",
            Self::Export => "export",
            Self::JobsList => "jobs_list",
            Self::JobsGet => "jobs_get",
            Self::JobsCreate => "jobs_create",
            Self::JobsUpdate => "jobs_update",
            Self::JobsPause => "jobs_pause",
            Self::JobsResume => "jobs_resume",
            Self::JobsRun => "jobs_run",
            Self::JobsDelete => "jobs_delete",
            Self::SessionsNew => "sessions_new",
            Self::SessionsReset => "sessions_reset",
            Self::SessionsArchive => "sessions_archive",
            Self::SessionsDelete => "sessions_delete",
            Self::RunsList => "runs_list",
            Self::RunsGet => "runs_get",
            Self::Close => "close",
            Self::ProfilesList => "profiles_list",
            Self::ProfilesGet => "profiles_get",
            Self::ProfilesCreate => "profiles_create",
            Self::ProfilesDelete => "profiles_delete",
            Self::SkillsList => "skills_list",
            Self::SkillsInstall => "skills_install",
            Self::SkillsRemove => "skills_remove",
            Self::MemoryShow => "memory_show",
            Self::MemorySearch => "memory_search",
            Self::ApprovalsList => "approvals_list",
            Self::ApprovalsResolve => "approvals_resolve",
            Self::ChannelsList => "channels_list",
            Self::RoutesList => "routes_list",
            Self::TriggersList => "triggers_list",
            Self::ChannelsStatus => "channels_status",
            Self::WorldLoad => "world_load",
            Self::WorldSave => "world_save",
            Self::WorldCompile => "world_compile",
            Self::WorldDecompile => "world_decompile",
            Self::WorldImport => "world_import",
            Self::WorldExport => "world_export",
        }
    }

    /// Resolve a stable action spelling.
    pub fn from_action_name(action: &str) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|operation| operation.action_name() == action)
    }
}

/// One typed SDK request before a transport adds its envelope.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SdkRequest {
    /// Requested SDK operation.
    pub operation: SdkOperation,
    /// Operation-specific language-neutral parameters.
    #[serde(default)]
    pub params: Value,
}

/// Stable machine-readable SDK failure categories.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SdkErrorCode {
    /// No authenticated client context was supplied.
    Unauthenticated,
    /// The authenticated client lacks a required capability.
    Unauthorized,
    /// Another client owns control or no controller lease was claimed.
    ControllerRequired,
    /// The caller's controller lease expired before the mutation.
    LeaseExpired,
    /// Input did not satisfy the operation contract.
    InvalidArgument,
    /// The requested session, runtime, or request was not found.
    NotFound,
    /// A turn already owns the runtime.
    Busy,
    /// The selected adapter honestly does not implement the operation.
    UnsupportedAction,
    /// A runtime or provider operation failed.
    Execution,
    /// The transport closed or returned an invalid envelope.
    Transport,
}

/// Typed turn failure shared by local, HTTP, ACP, CLI, and language adapters.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RuntimeSubmitError {
    /// Another turn already owns the runtime.
    #[error("a turn is already in progress")]
    Busy,
    /// The active turn was cancelled through the SDK runtime handle.
    #[error("turn interrupted")]
    Interrupted,
    /// The model/provider/tool loop failed.
    #[error("{0}")]
    Agent(String),
}

/// Typed failure returned by every SDK adapter and compatibility projection.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SdkError {
    /// A runtime operation was attempted without authenticated client state.
    #[error("SDK runtime authentication required")]
    Unauthenticated,
    /// The authenticated client lacks a required runtime permission.
    #[error("SDK runtime permission `{permission}` is required")]
    Unauthorized {
        /// Stable permission spelling.
        permission: String,
    },
    /// Mutation requires the controller lease. When another client owns it,
    /// its opaque identity and deadline are included for deterministic retry.
    #[error("controller lease required")]
    ControllerRequired {
        /// Current controller, when known.
        holder: Option<String>,
        /// Current controller deadline, when known.
        expires_at_ms: Option<u64>,
    },
    /// This client previously controlled the runtime but its lease expired.
    #[error("controller lease expired")]
    LeaseExpired,
    /// Input did not satisfy an operation contract.
    #[error("invalid SDK argument for {operation:?}: {message}")]
    InvalidArgument {
        /// Operation being decoded.
        operation: SdkOperation,
        /// Validation detail.
        message: String,
    },
    /// A stable identity was not found.
    #[error("SDK target for {operation:?} was not found: {message}")]
    NotFound {
        /// Operation being executed.
        operation: SdkOperation,
        /// Lookup detail.
        message: String,
    },
    /// The active adapter does not implement the requested action.
    #[error("SDK action `{0}` is not supported by this runtime")]
    UnsupportedAction(&'static str),
    /// The requested catalog operation is absent or has no typed route.
    #[error("SDK operation `{0}` is not supported by this runtime")]
    UnsupportedOperation(String),
    /// A slow consumer fell behind the bounded live-event channel.
    #[error("SDK event stream lost {0} event(s); reattach for a fresh snapshot")]
    ReplayGap(u64),
    /// The runtime closed its event stream.
    #[error("SDK runtime event stream closed")]
    Closed,
    /// An authenticated remote transport failed or returned an invalid value.
    #[error("SDK transport failed: {0}")]
    Transport(String),
    /// No live request exists for the supplied response id.
    #[error("SDK request {0} is not pending")]
    UnknownRequest(u64),
    /// The response kind or value does not match the pending request.
    #[error("invalid SDK response: {0}")]
    InvalidResponse(String),
    /// The canonical runtime rejected or failed a turn.
    #[error(transparent)]
    Submit(#[from] RuntimeSubmitError),
    /// A session/runtime implementation failed after validation.
    #[error("SDK execution failed for {operation:?}: {message}")]
    Execution {
        /// Operation being executed.
        operation: SdkOperation,
        /// Implementation detail.
        message: String,
    },
}

impl SdkError {
    /// Construct a typed failure for an SDK operation.
    pub fn new(code: SdkErrorCode, operation: SdkOperation, message: impl Into<String>) -> Self {
        let message = message.into();
        match code {
            SdkErrorCode::Unauthenticated => Self::Unauthenticated,
            SdkErrorCode::Unauthorized => Self::Unauthorized {
                permission: message,
            },
            SdkErrorCode::ControllerRequired => Self::ControllerRequired {
                holder: None,
                expires_at_ms: None,
            },
            SdkErrorCode::LeaseExpired => Self::LeaseExpired,
            SdkErrorCode::InvalidArgument => Self::InvalidArgument { operation, message },
            SdkErrorCode::NotFound => Self::NotFound { operation, message },
            SdkErrorCode::Busy => Self::Submit(RuntimeSubmitError::Busy),
            SdkErrorCode::UnsupportedAction => Self::unsupported(operation),
            SdkErrorCode::Execution => Self::Execution { operation, message },
            SdkErrorCode::Transport => Self::Transport(message),
        }
    }

    /// Construct a named unsupported-action failure.
    pub fn unsupported(operation: SdkOperation) -> Self {
        Self::UnsupportedAction(operation.action_name())
    }

    /// Stable machine-readable category.
    pub fn code(&self) -> SdkErrorCode {
        match self {
            Self::Unauthenticated => SdkErrorCode::Unauthenticated,
            Self::Unauthorized { .. } => SdkErrorCode::Unauthorized,
            Self::ControllerRequired { .. } => SdkErrorCode::ControllerRequired,
            Self::LeaseExpired => SdkErrorCode::LeaseExpired,
            Self::InvalidArgument { .. } | Self::InvalidResponse(_) => {
                SdkErrorCode::InvalidArgument
            }
            Self::NotFound { .. } | Self::UnknownRequest(_) => SdkErrorCode::NotFound,
            Self::Submit(RuntimeSubmitError::Busy) => SdkErrorCode::Busy,
            Self::UnsupportedAction(_) | Self::UnsupportedOperation(_) => {
                SdkErrorCode::UnsupportedAction
            }
            Self::Transport(_) | Self::ReplayGap(_) | Self::Closed => SdkErrorCode::Transport,
            Self::Submit(_) | Self::Execution { .. } => SdkErrorCode::Execution,
        }
    }

    /// Operation associated with this failure when it is unambiguous.
    pub fn operation(&self) -> Option<SdkOperation> {
        match self {
            Self::InvalidArgument { operation, .. }
            | Self::NotFound { operation, .. }
            | Self::Execution { operation, .. } => Some(*operation),
            Self::UnsupportedAction(action) => SdkOperation::from_action_name(action),
            Self::Unauthenticated
            | Self::Unauthorized { .. }
            | Self::ControllerRequired { .. }
            | Self::LeaseExpired => None,
            Self::UnknownRequest(_) | Self::InvalidResponse(_) => Some(SdkOperation::Respond),
            Self::Submit(_) => Some(SdkOperation::Input),
            Self::UnsupportedOperation(_)
            | Self::ReplayGap(_)
            | Self::Closed
            | Self::Transport(_) => None,
        }
    }
}

/// Capability inventory for the complete v1 SDK, independent of transport.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SdkCapabilities {
    /// Schema identifier governing this descriptor.
    pub schema_version: String,
    /// Operations understood by the facade. A concrete runtime may still
    /// return `unsupported_action` for a mechanically unavailable action.
    pub operations: Vec<SdkOperation>,
    /// Stable error categories clients must preserve by name.
    pub error_codes: Vec<SdkErrorCode>,
    /// Whether events preserve unknown native payloads losslessly.
    pub opaque_events: bool,
}

impl Default for SdkCapabilities {
    fn default() -> Self {
        Self {
            schema_version: SDK_SCHEMA_VERSION.into(),
            operations: SdkOperation::ALL.to_vec(),
            error_codes: vec![
                SdkErrorCode::Unauthenticated,
                SdkErrorCode::Unauthorized,
                SdkErrorCode::ControllerRequired,
                SdkErrorCode::LeaseExpired,
                SdkErrorCode::InvalidArgument,
                SdkErrorCode::NotFound,
                SdkErrorCode::Busy,
                SdkErrorCode::UnsupportedAction,
                SdkErrorCode::Execution,
                SdkErrorCode::Transport,
            ],
            opaque_events: true,
        }
    }
}

/// Canonical event before a wire transport adds subscription metadata.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SdkEvent {
    /// Monotonic sequence scoped to the SDK runtime.
    pub sequence: u64,
    /// Normalized or native event kind.
    pub kind: String,
    /// Complete payload, including unknown fields.
    pub payload: Value,
}

impl SdkEvent {
    pub(crate) fn new(sequence: u64, payload: Value) -> Self {
        let kind = payload
            .get("type")
            .or_else(|| payload.get("method"))
            .and_then(Value::as_str)
            .unwrap_or("unknown")
            .to_string();
        Self {
            sequence,
            kind,
            payload,
        }
    }
}

/// One runtime event paired with its durable SDK identity.
///
/// A transport may add a connection or subscription id around this value,
/// but those routing fields never become part of [`SdkEvent`] or a session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SdkRuntimeEvent {
    /// Stable SDK session identity, never a transport-local connection id.
    pub session_id: String,
    /// Canonical event shared by local and remote runtime adapters.
    pub event: SdkEvent,
}

/// Canonical live-runtime contract owned by the SDK.
///
/// Frontend modules are projections of this trait. They may render events or
/// add transport envelopes, but they do not own a second model loop.
#[async_trait]
pub trait SdkRuntime: Send + Sync {
    /// Describe runtime identity, modules, commands, actions, and state.
    async fn describe(&self) -> Result<crate::frontend::FrontendRuntimeDescriptor, SdkError>;
    /// Atomically attach at the canonical history/live-event boundary.
    async fn attach(
        &self,
        history_limit: usize,
    ) -> Result<crate::frontend::FrontendAttachment, SdkError>;
    /// Atomically accept a new user turn and return once ownership is claimed.
    ///
    /// Exactly one simultaneous caller succeeds. The accepted turn continues
    /// on the SDK-owned runtime and publishes its result through the canonical
    /// event stream; a competing caller receives [`SdkErrorCode::Busy`]
    /// synchronously from this operation.
    async fn send_input(self: Arc<Self>, prompt: String) -> Result<(), SdkError>;
    /// Atomically accept a multimodal user turn and return once ownership is
    /// claimed. Implementations must preserve images natively or reject the
    /// action; silently folding them into text is never allowed.
    async fn send_input_with_images(
        self: Arc<Self>,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<(), SdkError> {
        if image_urls.is_empty() {
            self.send_input(prompt).await
        } else {
            Err(SdkError::UnsupportedAction("send_input_attachments"))
        }
    }
    /// Submit a new user turn.
    async fn submit(&self, prompt: String) -> Result<String, SdkError>;
    /// Submit a new user turn with canonical multimodal image inputs.
    ///
    /// Frontends must pass only runtime-resolved URLs or data URIs here; the
    /// SDK runtime, not a remote display client, owns input interpretation.
    async fn submit_with_images(
        &self,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<String, SdkError> {
        if image_urls.is_empty() {
            self.submit(prompt).await
        } else {
            Err(SdkError::UnsupportedAction("submit_attachments"))
        }
    }
    /// Interrupt an active turn.
    async fn interrupt(&self) -> Result<bool, SdkError>;
    /// Queue a steering instruction when supported.
    async fn steer(&self, prompt: String) -> Result<(), SdkError>;
    /// Answer a typed runtime request when supported.
    async fn respond(&self, response: crate::frontend::FrontendResponse) -> Result<(), SdkError>;
    /// Invoke one operation from the descriptor's explicit catalog.
    async fn invoke(
        &self,
        operation: crate::frontend::FrontendOperationInvocation,
    ) -> Result<crate::frontend::FrontendOperationResult, SdkError> {
        Err(SdkError::UnsupportedOperation(
            operation.operation_id().to_string(),
        ))
    }
    /// Read the one-controller/many-observer ownership state.
    async fn lease_snapshot(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation("runtime.lease".into()))
    }
    /// Explicitly acquire the controller lease from another interactive
    /// client. Ordinary mutations never perform an implicit takeover.
    async fn take_control(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation(
            "runtime.take_control".into(),
        ))
    }
    /// Refresh observer activity and a controller lease owned by this client.
    async fn heartbeat(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation("runtime.heartbeat".into()))
    }
    /// Release this client's observer/controller state without stopping the
    /// runtime.
    async fn detach(&self) -> Result<crate::RuntimeLeaseSnapshot, SdkError> {
        Err(SdkError::UnsupportedOperation("runtime.detach".into()))
    }
    /// Explicitly close the SDK-owned runtime when the negotiated descriptor
    /// grants that owner-level action. Dropping an attachment is always a
    /// detach and never calls this operation implicitly.
    async fn close(&self) -> Result<(), SdkError> {
        Err(SdkError::unsupported(SdkOperation::Close))
    }
}

/// Stateful SDK facade consumed by public transport adapters.
#[async_trait]
pub trait SdkService: Send {
    /// Describe the versioned contract without invoking a runtime.
    fn capabilities(&self) -> SdkCapabilities {
        SdkCapabilities::default()
    }

    /// Execute one typed request. Transport correlation fields are not part
    /// of this API and therefore cannot contaminate canonical state.
    async fn execute(&mut self, request: SdkRequest) -> Result<Value, SdkError>;

    /// Poll canonical runtime events without a transport envelope.
    async fn events(&mut self) -> Result<Vec<SdkRuntimeEvent>, SdkError>;
}