supercode-harness 0.4.13

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
//! Protocol-neutral frontend contract for one SDK-owned Supercode runtime.
//!
//! Terminal, HTTP, ACP, and future browser frontends consume this contract;
//! none of them owns an [`crate::Agent`] or a second model loop.  Events keep
//! their complete JSON payload and gain a monotonic sequence so a frontend can
//! cross the history-replay/live-stream boundary without duplicates.

use std::collections::{BTreeMap, VecDeque};
#[cfg(feature = "adapter-api")]
use std::sync::atomic::AtomicBool;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
#[cfg(feature = "adapter-api")]
use std::sync::Weak;

use async_trait::async_trait;
#[cfg(feature = "adapter-api")]
use futures::StreamExt;
use serde::{Deserialize, Serialize};
#[cfg(feature = "adapter-api")]
use serde_json::json;
use serde_json::Value;
use tokio::sync::broadcast;

#[cfg(feature = "adapter-api")]
use crate::sdk::RuntimeSubmitError;
pub use crate::sdk::SdkError as FrontendRuntimeError;
pub use crate::sdk::SdkEvent as FrontendEvent;
pub use crate::sdk::SdkRuntime as FrontendRuntime;
use crate::server::RpcEngine;
use crate::ChatMessage;

/// Frontend contract schema version.
pub const FRONTEND_RUNTIME_SCHEMA_VERSION: u32 = 2;

/// Runtime lifecycle-event schema version.
///
/// Operation descriptors evolve the attach contract independently from the
/// established event payloads consumed by machine frontends.
pub(crate) const FRONTEND_EVENT_SCHEMA_VERSION: u32 = 1;

/// Maximum sequenced events retained between canonical history snapshots.
pub const FRONTEND_REPLAY_CAPACITY: usize = 4096;

/// Whether a model/tool turn currently owns the runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendTurnState {
    /// The runtime accepts a new turn.
    Idle,
    /// A user, scheduler, or tool turn is active.
    Busy,
}

/// Frontend-visible runtime connection state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendConnectionState {
    /// The SDK runtime is reachable.
    Connected,
    /// Graceful shutdown has been requested.
    ShuttingDown,
}

/// Actions the current runtime adapter can actually perform.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendActions {
    /// Submit a new user turn.
    pub submit: bool,
    /// Interrupt an active turn.
    pub interrupt: bool,
    /// Queue a steering instruction during a turn.
    pub steer: bool,
    /// Answer an approval, elicitation, or other protocol request.
    pub respond: bool,
    /// Detach without stopping the runtime.
    pub detach: bool,
    /// Close the SDK-owned runtime.
    pub close: bool,
}

/// Display semantics emitted by the runtime.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendDisplayCapabilities {
    /// Known normalized event kinds at this schema version.
    pub event_kinds: Vec<String>,
    /// Whether unknown payloads remain available for generic rendering.
    pub opaque_fallback: bool,
}

/// One runtime-provided command surfaced by a composer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendCommandDescriptor {
    /// Command name without the leading slash.
    pub name: String,
    /// Optional short help text.
    pub description: Option<String>,
    /// Optional argument usage shown beside the command.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub argument_hint: Option<String>,
}

/// Stable family for an explicitly invocable frontend operation.
///
/// Families without a production [`FrontendRuntime::invoke`] implementation
/// are never advertised. Keeping the full vocabulary here lets frontends
/// render future file/model/session/subagent/image/reduction controls from the
/// catalog without inferring them from composable modules.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendOperationKind {
    /// Invoke a trusted runtime prompt template.
    Prompt,
    /// Attach or inspect a file through a typed runtime route.
    File,
    /// Inspect or switch the active model through a typed runtime route.
    Model,
    /// Perform a session operation through a typed runtime route.
    Session,
    /// Perform a subagent operation through a typed runtime route.
    Subagent,
    /// Attach an image through a typed runtime route.
    Image,
    /// Perform a reversible reduction operation through a typed runtime route.
    Reduction,
}

/// One operation the runtime can genuinely invoke.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendOperationDescriptor {
    /// Stable runtime-scoped identifier supplied back during invocation.
    pub id: String,
    /// Typed operation family.
    pub kind: FrontendOperationKind,
    /// Optional slash-command trigger rendered by terminal composers.
    pub command: Option<FrontendCommandDescriptor>,
}

/// Typed invocation accepted by [`FrontendRuntime::invoke`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FrontendOperationInvocation {
    /// Expand and submit one advertised trusted prompt template.
    Prompt {
        /// Identifier from [`FrontendOperationDescriptor::id`].
        operation_id: String,
        /// Free text replacing the prompt template's `{args}` placeholder.
        arguments: String,
    },
}

impl FrontendOperationInvocation {
    /// Identifier supplied by the runtime catalog.
    pub fn operation_id(&self) -> &str {
        match self {
            Self::Prompt { operation_id, .. } => operation_id,
        }
    }
}

/// Typed result returned by [`FrontendRuntime::invoke`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FrontendOperationResult {
    /// Reply from a prompt-template turn.
    Prompt {
        /// Final assistant reply.
        reply: String,
    },
}

/// Source/emulation identity supplied by the session-loading surface.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendRuntimeMetadata {
    /// Source harness whose session semantics are being continued.
    pub source_harness: Option<String>,
    /// Resolved composable preset/profile name, when one was selected.
    pub emulation_profile: Option<String>,
}

/// Complete frontend-facing description of one SDK-owned runtime.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendRuntimeDescriptor {
    /// Contract schema version.
    pub schema_version: u32,
    /// Stable SDK runtime/session identity.
    pub session_id: String,
    /// Source harness whose semantics are being emulated.
    pub source_harness: Option<String>,
    /// Resolved composable preset/profile name.
    pub emulation_profile: Option<String>,
    /// Active composable modules, using their stable config keys.
    pub active_modules: Vec<String>,
    /// Runtime-provided composer commands.
    pub commands: Vec<FrontendCommandDescriptor>,
    /// Explicit typed operation catalog. Missing on schema-v1 peers.
    #[serde(default)]
    pub operations: Vec<FrontendOperationDescriptor>,
    /// Supported control actions.
    pub actions: FrontendActions,
    /// Display/event capabilities.
    pub display: FrontendDisplayCapabilities,
    /// Current model label.
    pub model: String,
    /// Current turn state.
    pub turn_state: FrontendTurnState,
    /// Current connection state.
    pub connection_state: FrontendConnectionState,
    /// Compatible client/adapter metadata with no canonical-session meaning.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, Value>,
}

/// Serializable half of an attachment returned by an out-of-process runtime.
/// The live receiver is transport-owned and joined to this snapshot locally.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FrontendAttachSnapshot {
    /// Runtime description captured at attachment time.
    pub descriptor: FrontendRuntimeDescriptor,
    /// Bounded canonical history through `history_cursor`.
    pub history: Vec<ChatMessage>,
    /// Highest event sequence represented by `history`.
    pub history_cursor: u64,
    /// Events after the canonical history boundary and before the response.
    pub replay: VecDeque<FrontendEvent>,
}

/// Kind of interactive request surfaced by the SDK runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendRequestKind {
    /// A tool or sandbox action needs a policy-authorized human decision.
    Approval,
    /// An MCP server requested structured user input.
    Elicitation,
    /// Another versioned runtime request not known to this frontend build.
    /// Its complete payload remains available for a generic overlay.
    #[serde(other)]
    Other,
}

/// One pending interactive request, emitted as a sequenced frontend event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FrontendRequest {
    /// Runtime-scoped request identifier used exactly once by `respond`.
    pub id: u64,
    /// Typed request category.
    pub kind: FrontendRequestKind,
    /// Complete request payload, including raw tool arguments or schema.
    pub payload: Value,
}

/// Typed approval decision accepted by [`FrontendRuntime::respond`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendApprovalDecision {
    /// Refuse this request.
    Deny,
    /// Allow only this request.
    Allow,
    /// Allow this request and cache the exact policy key for the session.
    AllowForSession,
}

/// MCP elicitation outcome accepted by a frontend response.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendElicitationAction {
    /// Submit structured content.
    Accept,
    /// Explicitly decline the request.
    Decline,
    /// Dismiss the request without a decision.
    Cancel,
}

/// Typed response to one SDK-owned interactive request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FrontendResponse {
    /// Answer an approval request.
    Approval {
        /// Identifier from [`FrontendRequest::id`].
        request_id: u64,
        /// Human decision.
        decision: FrontendApprovalDecision,
    },
    /// Answer an MCP elicitation request.
    Elicitation {
        /// Identifier from [`FrontendRequest::id`].
        request_id: u64,
        /// MCP elicitation outcome.
        action: FrontendElicitationAction,
        /// Structured content for `accept`.
        content: Option<Value>,
    },
    /// Answer a generic runtime request without discarding its payload.
    Other {
        /// Identifier from [`FrontendRequest::id`].
        request_id: u64,
        /// Generic accept/decline/cancel outcome.
        action: FrontendElicitationAction,
        /// Optional structured response content.
        content: Option<Value>,
    },
}

impl FrontendResponse {
    pub(crate) fn request_id(&self) -> u64 {
        match self {
            Self::Approval { request_id, .. }
            | Self::Elicitation { request_id, .. }
            | Self::Other { request_id, .. } => *request_id,
        }
    }
}

/// Atomic history/replay/live attachment to one runtime.
pub struct FrontendAttachment {
    /// Runtime description captured at attachment time.
    pub descriptor: FrontendRuntimeDescriptor,
    /// Bounded canonical history through `history_cursor`.
    pub history: Vec<ChatMessage>,
    /// Highest event sequence already represented by `history`.
    pub history_cursor: u64,
    pub(crate) replay: VecDeque<FrontendEvent>,
    live: broadcast::Receiver<FrontendEvent>,
    delivered: u64,
    acknowledged: Option<Arc<AtomicU64>>,
    _transport_lease: Option<Arc<()>>,
}

impl FrontendAttachment {
    /// Build an in-process attachment from a serialized snapshot and a live
    /// SDK event receiver. Runtime adapters use this constructor in tests and
    /// protocol bridges without acquiring transport ownership.
    pub fn from_snapshot(
        snapshot: FrontendAttachSnapshot,
        live: broadcast::Receiver<FrontendEvent>,
    ) -> Self {
        Self::from_snapshot_after(snapshot, live, 0)
    }

    /// Build an attachment that resumes after a sequence acknowledged by a
    /// prior transport connection. Snapshot replay and any overlapping live
    /// events at or below the cursor are skipped without changing canonical
    /// history or event payloads.
    pub fn from_snapshot_after(
        snapshot: FrontendAttachSnapshot,
        live: broadcast::Receiver<FrontendEvent>,
        acknowledged_sequence: u64,
    ) -> Self {
        let delivered = snapshot.history_cursor.max(acknowledged_sequence);
        Self::new_with_delivered(
            snapshot.descriptor,
            snapshot.history,
            snapshot.history_cursor,
            snapshot.replay,
            live,
            None,
            delivered,
        )
    }

    pub(crate) fn new(
        descriptor: FrontendRuntimeDescriptor,
        history: Vec<ChatMessage>,
        history_cursor: u64,
        replay: VecDeque<FrontendEvent>,
        live: broadcast::Receiver<FrontendEvent>,
        transport_lease: Option<Arc<()>>,
    ) -> Self {
        let delivered = history_cursor;
        Self::new_with_delivered(
            descriptor,
            history,
            history_cursor,
            replay,
            live,
            transport_lease,
            delivered,
        )
    }

    fn new_with_delivered(
        descriptor: FrontendRuntimeDescriptor,
        history: Vec<ChatMessage>,
        history_cursor: u64,
        replay: VecDeque<FrontendEvent>,
        live: broadcast::Receiver<FrontendEvent>,
        transport_lease: Option<Arc<()>>,
        delivered: u64,
    ) -> Self {
        Self {
            descriptor,
            history,
            history_cursor,
            replay,
            live,
            delivered,
            acknowledged: None,
            _transport_lease: transport_lease,
        }
    }

    #[cfg(feature = "adapter-acp")]
    pub(crate) fn with_acknowledgement(mut self, acknowledged: Arc<AtomicU64>) -> Self {
        acknowledged.fetch_max(self.history_cursor, Ordering::SeqCst);
        self.acknowledged = Some(acknowledged);
        self
    }

    fn acknowledge(&self, event: &FrontendEvent) {
        if !event_advances_acknowledgement(event) {
            return;
        }
        if let Some(acknowledged) = &self.acknowledged {
            acknowledged.fetch_max(event.sequence, Ordering::SeqCst);
        }
    }

    /// Receive the next event not already represented by the history or a
    /// prior replay item. Duplicate events queued during attachment are
    /// skipped by sequence.
    pub async fn next_event(&mut self) -> Result<FrontendEvent, FrontendRuntimeError> {
        loop {
            let event = match self.next_replay_event() {
                Some(event) => return Ok(event),
                None => match self.live.recv().await {
                    Ok(event) => event,
                    Err(broadcast::error::RecvError::Lagged(count)) => {
                        return Err(FrontendRuntimeError::ReplayGap(count));
                    }
                    Err(broadcast::error::RecvError::Closed) => {
                        return Err(FrontendRuntimeError::Closed);
                    }
                },
            };
            if event.sequence <= self.delivered {
                continue;
            }
            self.delivered = event.sequence;
            self.acknowledge(&event);
            return Ok(event);
        }
    }

    /// Drain one event from the finite attachment replay without waiting for
    /// live input. Interactive frontends use this to project the complete
    /// atomic snapshot before accepting keystrokes, so a historical resolved
    /// request never appears transiently actionable.
    pub fn next_replay_event(&mut self) -> Option<FrontendEvent> {
        while let Some(event) = self.replay.pop_front() {
            if event.sequence <= self.delivered {
                continue;
            }
            self.delivered = event.sequence;
            self.acknowledge(&event);
            return Some(event);
        }
        None
    }
}

pub(crate) fn event_advances_acknowledgement(event: &FrontendEvent) -> bool {
    event
        .payload
        .pointer("/_meta/supercode/transient")
        .and_then(Value::as_bool)
        != Some(true)
}

/// State protected by `RpcEngine`'s short synchronous projection lock.
pub(crate) struct FrontendProjectionState {
    pub(crate) history: Vec<ChatMessage>,
    pub(crate) history_cursor: u64,
    pub(crate) next_sequence: u64,
    pub(crate) replay: VecDeque<FrontendEvent>,
}

#[async_trait]
impl FrontendRuntime for RpcEngine {
    async fn describe(&self) -> Result<FrontendRuntimeDescriptor, FrontendRuntimeError> {
        Ok(self.frontend_descriptor())
    }

    async fn attach(
        &self,
        history_limit: usize,
    ) -> Result<FrontendAttachment, FrontendRuntimeError> {
        self.frontend_attach(history_limit)
    }

    async fn send_input(self: Arc<Self>, prompt: String) -> Result<(), FrontendRuntimeError> {
        RpcEngine::send_input(&self, prompt)?;
        Ok(())
    }

    async fn send_input_with_images(
        self: Arc<Self>,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<(), FrontendRuntimeError> {
        RpcEngine::send_input_with_images(&self, prompt, image_urls)?;
        Ok(())
    }

    async fn submit(&self, prompt: String) -> Result<String, FrontendRuntimeError> {
        Ok(RpcEngine::submit(self, prompt).await?)
    }

    async fn submit_with_images(
        &self,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<String, FrontendRuntimeError> {
        Ok(RpcEngine::submit_with_images(self, prompt, image_urls).await?)
    }

    async fn interrupt(&self) -> Result<bool, FrontendRuntimeError> {
        Ok(RpcEngine::interrupt(self).await)
    }

    async fn steer(&self, prompt: String) -> Result<(), FrontendRuntimeError> {
        RpcEngine::steer(self, prompt)
    }

    async fn respond(&self, response: FrontendResponse) -> Result<(), FrontendRuntimeError> {
        RpcEngine::respond(self, response)
    }

    async fn invoke(
        &self,
        operation: FrontendOperationInvocation,
    ) -> Result<FrontendOperationResult, FrontendRuntimeError> {
        RpcEngine::invoke(self, operation).await
    }

    async fn close(&self) -> Result<(), FrontendRuntimeError> {
        RpcEngine::shutdown(self).await;
        Ok(())
    }
}

/// Authenticated HTTP implementation of [`FrontendRuntime`].
///
/// It owns only an RPC/SSE connection. The remote [`RpcEngine`] remains the
/// sole owner of the agent loop, transcript, scheduler, and persistence.
#[cfg(feature = "adapter-api")]
pub struct HttpFrontendRuntime {
    base_url: String,
    token: String,
    client_id: crate::RuntimeClientId,
    authorization: crate::RuntimeAuthorization,
    client: reqwest::Client,
    events: broadcast::Sender<FrontendEvent>,
    next_id: AtomicU64,
    lifecycle: Arc<()>,
    disconnected: AtomicBool,
}

#[cfg(feature = "adapter-api")]
impl HttpFrontendRuntime {
    /// Authenticate, verify the frontend descriptor, and establish the
    /// sequenced SSE stream before returning.
    pub async fn connect(
        base_url: impl Into<String>,
        token: impl Into<String>,
    ) -> Result<Arc<Self>, FrontendRuntimeError> {
        let mut random = [0_u8; 16];
        getrandom::getrandom(&mut random).map_err(|error| {
            FrontendRuntimeError::Transport(format!(
                "cannot generate runtime client identity: {error}"
            ))
        })?;
        let suffix = random
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>();
        let client_id = crate::RuntimeClientId::parse(format!("http-{suffix}"))
            .map_err(|error| FrontendRuntimeError::Transport(error.to_string()))?;
        Self::connect_with_client_id(base_url, token, client_id).await
    }

    /// Connect with a caller-owned stable client identity. Reconnect tests
    /// and external bindings use this to retain deterministic lease state.
    pub async fn connect_with_client_id(
        base_url: impl Into<String>,
        token: impl Into<String>,
        client_id: crate::RuntimeClientId,
    ) -> Result<Arc<Self>, FrontendRuntimeError> {
        Self::connect_with_authorization(
            base_url,
            token,
            client_id,
            crate::RuntimeAuthorization::owner(),
        )
        .await
    }

    /// Connect while requesting an exact subset of the bearer credential's
    /// permissions. The server intersects this with the authenticated grant;
    /// this header can narrow authority but can never elevate it.
    pub async fn connect_with_authorization(
        base_url: impl Into<String>,
        token: impl Into<String>,
        client_id: crate::RuntimeClientId,
        authorization: crate::RuntimeAuthorization,
    ) -> Result<Arc<Self>, FrontendRuntimeError> {
        Self::connect_inner(base_url, token, client_id, authorization, true)
            .await
            .map(|(runtime, _)| runtime)
    }

    /// Authenticated metadata probe that does not open an event stream or
    /// register an observer, returning the descriptor the connect handshake
    /// already fetched. Used by the local runtime registry, which runs this on
    /// every `harness serve` tick for every followed session: asking the same
    /// runtime to describe itself twice for one read is pure load on that
    /// path, and each round trip costs its own loopback connection.
    pub(crate) async fn probe_described(
        base_url: impl Into<String>,
        token: impl Into<String>,
        client_id: crate::RuntimeClientId,
    ) -> Result<(Arc<Self>, FrontendRuntimeDescriptor), FrontendRuntimeError> {
        Self::connect_inner(
            base_url,
            token,
            client_id,
            crate::RuntimeAuthorization::observer(),
            false,
        )
        .await
    }

    async fn connect_inner(
        base_url: impl Into<String>,
        token: impl Into<String>,
        client_id: crate::RuntimeClientId,
        authorization: crate::RuntimeAuthorization,
        stream_events: bool,
    ) -> Result<(Arc<Self>, FrontendRuntimeDescriptor), FrontendRuntimeError> {
        let runtime = Arc::new(Self {
            base_url: base_url.into().trim_end_matches('/').to_string(),
            token: token.into(),
            client_id,
            authorization,
            client: reqwest::Client::new(),
            events: broadcast::channel(1024).0,
            next_id: AtomicU64::new(1),
            lifecycle: Arc::new(()),
            disconnected: AtomicBool::new(false),
        });
        // Validate auth and schema before opening a long-lived connection.
        let descriptor: FrontendRuntimeDescriptor = runtime
            .rpc_typed(crate::FrontendFacadeMethod::Describe.wire_name(), json!({}))
            .await?;
        if stream_events {
            Self::start_event_stream(&runtime).await?;
        }
        Ok((runtime, descriptor))
    }

    async fn start_event_stream(runtime: &Arc<Self>) -> Result<(), FrontendRuntimeError> {
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
        let weak = Arc::downgrade(runtime);
        let lifecycle = Arc::downgrade(&runtime.lifecycle);
        tokio::spawn(async move {
            Self::run_event_stream(weak, lifecycle, ready_tx).await;
        });
        ready_rx.await.map_err(|_| {
            FrontendRuntimeError::Transport("frontend event stream exited before startup".into())
        })?
    }

    async fn run_event_stream(
        weak: Weak<Self>,
        lifecycle: Weak<()>,
        ready: tokio::sync::oneshot::Sender<Result<(), FrontendRuntimeError>>,
    ) {
        let Some(runtime) = weak.upgrade() else {
            let _ = ready.send(Err(FrontendRuntimeError::Closed));
            return;
        };
        let request = runtime
            .client
            .get(format!("{}/frontend/events", runtime.base_url))
            .bearer_auth(&runtime.token)
            .header("x-supercode-client-id", runtime.client_id.as_str())
            .header(
                "x-supercode-permissions",
                runtime.authorization.header_value(),
            );
        let events = runtime.events.clone();
        drop(runtime);
        let response = request.send().await;
        let response = match response {
            Ok(response) if response.status().is_success() => response,
            Ok(response) => {
                let _ = ready.send(Err(FrontendRuntimeError::Transport(format!(
                    "frontend event stream returned {}",
                    response.status()
                ))));
                return;
            }
            Err(error) => {
                let _ = ready.send(Err(FrontendRuntimeError::Transport(error.to_string())));
                return;
            }
        };
        let _ = ready.send(Ok(()));
        let mut stream = response.bytes_stream();
        let mut pending = Vec::<u8>::new();
        let mut liveness = tokio::time::interval(std::time::Duration::from_millis(100));
        loop {
            let chunk = tokio::select! {
                _ = liveness.tick() => {
                    if lifecycle.strong_count() == 0 {
                        break;
                    }
                    if weak
                        .upgrade()
                        .is_some_and(|runtime| runtime.disconnected.load(Ordering::SeqCst))
                    {
                        break;
                    }
                    continue;
                }
                chunk = stream.next() => chunk,
            };
            let Some(chunk) = chunk else {
                break;
            };
            let Ok(chunk) = chunk else {
                break;
            };
            pending.extend_from_slice(&chunk);
            while let Some(position) = pending.iter().position(|byte| *byte == b'\n') {
                let line = pending.drain(..=position).collect::<Vec<_>>();
                let line = String::from_utf8_lossy(&line);
                let Some(data) = line.trim_end().strip_prefix("data: ") else {
                    continue;
                };
                if let Ok(event) = serde_json::from_str::<FrontendEvent>(data) {
                    let _ = events.send(event);
                }
            }
        }
        if let Some(runtime) = weak.upgrade() {
            runtime.disconnected.store(true, Ordering::SeqCst);
            let _ = runtime.events.send(FrontendEvent::new(
                u64::MAX,
                json!({
                    "type": "runtime_disconnected",
                    "schema_version": FRONTEND_EVENT_SCHEMA_VERSION
                }),
            ));
        }
    }

    async fn rpc(&self, method: &str, params: Value) -> Result<Value, FrontendRuntimeError> {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let requested_operation = params
            .pointer("/operation/operation_id")
            .and_then(Value::as_str)
            .map(str::to_owned);
        let response = self
            .client
            .post(format!("{}/rpc", self.base_url))
            .bearer_auth(&self.token)
            .header("x-supercode-client-id", self.client_id.as_str())
            .header("x-supercode-permissions", self.authorization.header_value())
            .json(&json!({"id": id, "method": method, "params": params}))
            .send()
            .await
            .map_err(|error| FrontendRuntimeError::Transport(error.to_string()))?;
        if !response.status().is_success() {
            return Err(FrontendRuntimeError::Transport(format!(
                "SDK HTTP RPC returned {}",
                response.status()
            )));
        }
        let value: Value = response
            .json()
            .await
            .map_err(|error| FrontendRuntimeError::Transport(error.to_string()))?;
        if let Some(error) = value.get("error") {
            let code = error.get("code").and_then(Value::as_i64);
            let name = error.get("name").and_then(Value::as_str);
            let operation = error
                .get("operation")
                .and_then(Value::as_str)
                .and_then(crate::SdkOperation::from_action_name);
            let message = error
                .get("message")
                .and_then(Value::as_str)
                .unwrap_or("SDK runtime request failed")
                .to_string();
            return Err(match (name, code) {
                (Some("unauthenticated"), _) | (_, Some(-32030)) => {
                    FrontendRuntimeError::Unauthenticated
                }
                (Some("unauthorized"), _) | (_, Some(-32031)) => {
                    FrontendRuntimeError::Unauthorized {
                        permission: error
                            .get("permission")
                            .and_then(Value::as_str)
                            .unwrap_or("unknown")
                            .to_string(),
                    }
                }
                (Some("controller_required"), _) | (_, Some(-32032)) => {
                    FrontendRuntimeError::ControllerRequired {
                        holder: error
                            .get("holder")
                            .and_then(Value::as_str)
                            .map(str::to_owned),
                        expires_at_ms: error.get("expiresAtMs").and_then(Value::as_u64),
                    }
                }
                (Some("lease_expired"), _) | (_, Some(-32033)) => {
                    FrontendRuntimeError::LeaseExpired
                }
                (_, Some(-32023)) => FrontendRuntimeError::UnsupportedOperation(
                    requested_operation.unwrap_or(message),
                ),
                (Some("unsupported_action"), _) => FrontendRuntimeError::UnsupportedAction(
                    operation
                        .unwrap_or_else(|| {
                            crate::SdkOperation::from_action_name(method)
                                .unwrap_or(crate::SdkOperation::Respond)
                        })
                        .action_name(),
                ),
                (Some("not_found"), Some(-32021)) => {
                    let request_id = params
                        .pointer("/response/request_id")
                        .and_then(Value::as_u64)
                        .unwrap_or_default();
                    FrontendRuntimeError::UnknownRequest(request_id)
                }
                (Some("invalid_argument"), _) => FrontendRuntimeError::InvalidResponse(message),
                (_, Some(-32000)) => RuntimeSubmitError::Busy.into(),
                (_, Some(-32001)) => RuntimeSubmitError::Interrupted.into(),
                (_, Some(-32002)) => RuntimeSubmitError::Agent(message).into(),
                (_, Some(-32020)) => FrontendRuntimeError::UnsupportedAction(
                    crate::SdkOperation::from_action_name(method)
                        .unwrap_or(crate::SdkOperation::Respond)
                        .action_name(),
                ),
                (_, Some(-32021)) => {
                    let request_id = params
                        .pointer("/response/request_id")
                        .and_then(Value::as_u64)
                        .unwrap_or_default();
                    FrontendRuntimeError::UnknownRequest(request_id)
                }
                (_, Some(-32022)) => FrontendRuntimeError::InvalidResponse(message),
                _ => FrontendRuntimeError::Transport(message),
            });
        }
        Ok(value.get("result").cloned().unwrap_or(Value::Null))
    }

    async fn rpc_typed<T: serde::de::DeserializeOwned>(
        &self,
        method: &str,
        params: Value,
    ) -> Result<T, FrontendRuntimeError> {
        serde_json::from_value(self.rpc(method, params).await?)
            .map_err(|error| FrontendRuntimeError::Transport(error.to_string()))
    }

    /// Current authenticated client identity.
    pub fn client_id(&self) -> &crate::RuntimeClientId {
        &self.client_id
    }

    /// Whether the remote event stream has already ended or this client
    /// explicitly detached/closed.
    pub fn is_disconnected(&self) -> bool {
        self.disconnected.load(Ordering::SeqCst)
    }

    /// Explicitly acquire the controller lease, displacing another
    /// interactive client only through this named operation.
    pub async fn take_control(&self) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        self.rpc_typed(
            crate::FrontendFacadeMethod::TakeControl.wire_name(),
            json!({}),
        )
        .await
    }

    /// Renew observer activity and any controller lease owned by this client.
    pub async fn heartbeat(&self) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        self.rpc_typed(
            crate::FrontendFacadeMethod::Heartbeat.wire_name(),
            json!({}),
        )
        .await
    }

    /// Read the coordinated ownership state.
    pub async fn lease_snapshot(
        &self,
    ) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        self.rpc_typed(crate::FrontendFacadeMethod::Lease.wire_name(), json!({}))
            .await
    }

    /// Release observer and controller state without stopping the runtime.
    pub async fn detach(&self) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        let snapshot = self
            .rpc_typed(crate::FrontendFacadeMethod::Detach.wire_name(), json!({}))
            .await?;
        self.disconnected.store(true, Ordering::SeqCst);
        Ok(snapshot)
    }
}

#[async_trait]
#[cfg(feature = "adapter-api")]
impl FrontendRuntime for HttpFrontendRuntime {
    async fn describe(&self) -> Result<FrontendRuntimeDescriptor, FrontendRuntimeError> {
        self.rpc_typed(crate::FrontendFacadeMethod::Describe.wire_name(), json!({}))
            .await
    }

    async fn attach(
        &self,
        history_limit: usize,
    ) -> Result<FrontendAttachment, FrontendRuntimeError> {
        if self.disconnected.load(Ordering::SeqCst) {
            return Err(FrontendRuntimeError::Closed);
        }
        // Subscribe locally before asking the server for its atomic snapshot.
        // Anything concurrently received over SSE is either in snapshot.replay
        // or queued here; sequence filtering removes the overlap.
        let live = self.events.subscribe();
        let snapshot: FrontendAttachSnapshot = self
            .rpc_typed(
                crate::FrontendFacadeMethod::Attach.wire_name(),
                json!({"limit": history_limit}),
            )
            .await?;
        Ok(FrontendAttachment::new(
            snapshot.descriptor,
            snapshot.history,
            snapshot.history_cursor,
            snapshot.replay,
            live,
            Some(self.lifecycle.clone()),
        ))
    }

    async fn send_input(self: Arc<Self>, prompt: String) -> Result<(), FrontendRuntimeError> {
        self.send_input_with_images(prompt, Vec::new()).await
    }

    async fn send_input_with_images(
        self: Arc<Self>,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<(), FrontendRuntimeError> {
        self.rpc(
            crate::FrontendFacadeMethod::SendInput.wire_name(),
            json!({"prompt": prompt, "image_urls": image_urls}),
        )
        .await?;
        Ok(())
    }

    async fn submit(&self, prompt: String) -> Result<String, FrontendRuntimeError> {
        let result = self
            .rpc(
                crate::FrontendFacadeMethod::Submit.wire_name(),
                json!({"prompt": prompt}),
            )
            .await?;
        Ok(result
            .get("reply")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string())
    }

    async fn submit_with_images(
        &self,
        prompt: String,
        image_urls: Vec<String>,
    ) -> Result<String, FrontendRuntimeError> {
        let result = self
            .rpc(
                crate::FrontendFacadeMethod::Submit.wire_name(),
                json!({"prompt": prompt, "image_urls": image_urls}),
            )
            .await?;
        Ok(result
            .get("reply")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string())
    }

    async fn interrupt(&self) -> Result<bool, FrontendRuntimeError> {
        let result = self
            .rpc(
                crate::FrontendFacadeMethod::Interrupt.wire_name(),
                json!({}),
            )
            .await?;
        Ok(result
            .get("interrupted")
            .and_then(Value::as_bool)
            .unwrap_or(false))
    }

    async fn steer(&self, prompt: String) -> Result<(), FrontendRuntimeError> {
        self.rpc(
            crate::FrontendFacadeMethod::Steer.wire_name(),
            json!({"prompt": prompt}),
        )
        .await?;
        Ok(())
    }

    async fn respond(&self, response: FrontendResponse) -> Result<(), FrontendRuntimeError> {
        self.rpc(
            crate::FrontendFacadeMethod::Respond.wire_name(),
            json!({"response": response}),
        )
        .await?;
        Ok(())
    }

    async fn invoke(
        &self,
        operation: FrontendOperationInvocation,
    ) -> Result<FrontendOperationResult, FrontendRuntimeError> {
        self.rpc_typed(
            crate::FrontendFacadeMethod::Invoke.wire_name(),
            json!({"operation": operation}),
        )
        .await
    }

    async fn lease_snapshot(&self) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        HttpFrontendRuntime::lease_snapshot(self).await
    }

    async fn take_control(&self) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        HttpFrontendRuntime::take_control(self).await
    }

    async fn heartbeat(&self) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        HttpFrontendRuntime::heartbeat(self).await
    }

    async fn detach(&self) -> Result<crate::RuntimeLeaseSnapshot, FrontendRuntimeError> {
        HttpFrontendRuntime::detach(self).await
    }

    async fn close(&self) -> Result<(), FrontendRuntimeError> {
        self.rpc(crate::FrontendFacadeMethod::Close.wire_name(), json!({}))
            .await?;
        self.disconnected.store(true, Ordering::SeqCst);
        Ok(())
    }
}