marona 5.5.0

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

pub const D2A_PROTOCOL_VERSION: &str = "1.0";
pub type D2AMessageStream = Pin<Box<dyn Stream<Item = Result<D2AMessage>> + Send>>;
fn invalid(message: impl Into<String>) -> Error {
    Error::Validation(message.into())
}
fn nonempty(value: &str) -> bool {
    !value.trim().is_empty() && value.len() <= 256
}
fn timestamp() -> String {
    OffsetDateTime::now_utc()
        .format(&Rfc3339)
        .expect("valid clock")
}

/// One canonical envelope is used in both directions. Content is never an implicit command.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct D2AMessage {
    pub protocol: String,
    pub version: String,
    #[serde(rename = "type")]
    pub message_type: String,
    pub source: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    pub message_id: String,
    pub timestamp: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sequence: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correlation_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    pub payload: Value,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}
impl D2AMessage {
    /// Construct the shared envelope from a source and an explicit payload.
    pub fn from_payload(source: impl Into<String>, payload: Value) -> Result<Self> {
        let mut result = Self::new(source, "coordination", vec![])?;
        result.payload = payload;
        result.validate()?;
        Ok(result)
    }

    pub fn new(source: impl Into<String>, kind: &str, content: Vec<Value>) -> Result<Self> {
        let result = Self {
            protocol: "d2a".into(),
            version: "1.0".into(),
            message_type: "message".into(),
            source: source.into(),
            target: None,
            message_id: uuid::Uuid::new_v4().to_string(),
            timestamp: timestamp(),
            session_id: None,
            sequence: None,
            correlation_id: None,
            expires_at: None,
            payload: json!({"kind":kind,"content":content}),
            extra: serde_json::Map::new(),
        };
        result.validate()?;
        Ok(result)
    }
    pub fn observation(source: impl Into<String>, content: Vec<Value>) -> Result<Self> {
        Self::new(source, "data", content)
    }
    pub fn action(
        target: impl Into<String>,
        capability: impl Into<String>,
        arguments: Value,
    ) -> Result<Self> {
        let mut message = Self::new(
            "agent",
            "coordination",
            vec![json!({"type":"control","data":arguments})],
        )?;
        message.target = Some(target.into());
        message.payload = json!({"kind":"action","content":message.payload["content"],"action_id":uuid::Uuid::new_v4().to_string(),"capability":capability.into(),"arguments":arguments});
        message.validate()?;
        Ok(message)
    }
    pub fn feedback(action: &Self, status: &str, result: Value) -> Result<Self> {
        let mut message = Self::new(
            action.target.as_deref().unwrap_or("device"),
            "coordination",
            vec![json!({"type":"control","data":{"status":status,"result":result}})],
        )?;
        message.target = Some(action.source.clone());
        message.correlation_id = action
            .correlation_id
            .clone()
            .or_else(|| Some(action.message_id.clone()));
        message.payload["kind"] = json!("feedback");
        message.payload["action_id"] = action.payload["action_id"].clone();
        message.payload["status"] = json!(status);
        message.payload["result"] = result;
        message.validate()?;
        Ok(message)
    }
    pub fn from_value(value: Value) -> Result<Self> {
        for key in [
            "target",
            "session_id",
            "sequence",
            "correlation_id",
            "expires_at",
        ] {
            if value.get(key).is_some_and(Value::is_null) {
                return Err(invalid("Optional D2A fields cannot be null"));
            }
        }
        let result: Self = serde_json::from_value(value).map_err(|e| invalid(e.to_string()))?;
        result.validate()?;
        Ok(result)
    }
    pub fn to_value(&self) -> Value {
        serde_json::to_value(self).expect("message is JSON")
    }
    pub fn validate(&self) -> Result<()> {
        if self.protocol != "d2a"
            || self.version != "1.0"
            || self.message_type != "message"
            || !nonempty(&self.source)
            || !nonempty(&self.message_id)
            || self.target.as_ref().is_some_and(|v| !nonempty(v))
        {
            return Err(invalid("Invalid D2A envelope"));
        }
        OffsetDateTime::parse(&self.timestamp, &Rfc3339)
            .map_err(|_| invalid("Invalid D2A timestamp"))?;
        if self.session_id.is_some() != self.sequence.is_some()
            || self.session_id.as_ref().is_some_and(|v| !nonempty(v))
            || self.correlation_id.as_ref().is_some_and(|v| !nonempty(v))
        {
            return Err(invalid(
                "Session/sequence must be paired and identities nonempty",
            ));
        }
        if self.extra.keys().any(|key| key != "stream") {
            return Err(invalid("Unknown D2A envelope property"));
        }
        if let Some(stream) = self.extra.get("stream") {
            if !stream["id"].as_str().is_some_and(nonempty)
                || stream["index"].as_u64().is_none()
                || !stream["final"].is_boolean()
                || stream
                    .get("mode")
                    .is_some_and(|v| v != "snapshot" && v != "delta")
            {
                return Err(invalid("Invalid D2A stream metadata"));
            }
        }
        if self.sequence == Some(0) {
            return Err(invalid("D2A sequence must be positive"));
        }
        if let Some(expires) = &self.expires_at {
            OffsetDateTime::parse(expires, &Rfc3339).map_err(|_| invalid("Invalid D2A expiry"))?;
        }
        let kind = self.payload["kind"].as_str().unwrap_or("");
        if ![
            "data",
            "observation",
            "state",
            "action",
            "feedback",
            "coordination",
        ]
        .contains(&kind)
        {
            return Err(invalid("Invalid D2A message kind"));
        }
        for item in self.payload["content"].as_array().into_iter().flatten() {
            if let Some(uri) = item.get("uri") {
                if !uri
                    .as_str()
                    .is_some_and(|v| url::Url::parse(v).is_ok_and(|url| url.scheme() == "https"))
                {
                    return Err(invalid(
                        "D2A resources require HTTPS; resolve private resources in the provider",
                    ));
                }
            }
        }
        let mut validation = self.to_value();
        validation["source"] = json!("device");
        if self.payload["content"]
            .as_array()
            .is_some_and(Vec::is_empty)
            && ["action", "feedback", "coordination"].contains(&kind)
        {
            validation["payload"]["content"] = json!([{"type":"protocol:metadata","data":{}}]);
        }
        crate::b2a::content::validate(&validation)?;
        if kind == "action"
            && (self.source != "agent"
                || self.target.is_none()
                || !self.payload["action_id"].as_str().is_some_and(nonempty)
                || !self.payload["capability"].as_str().is_some_and(nonempty)
                || !self.payload["arguments"].is_object())
        {
            return Err(invalid("Invalid D2A action"));
        }
        if kind == "feedback"
            && (self.payload.get("result").is_none()
                || !self.payload["action_id"].as_str().is_some_and(nonempty)
                || ![
                    "accepted",
                    "executing",
                    "succeeded",
                    "rejected",
                    "failed",
                    "cancelled",
                    "expired",
                    "unknown",
                ]
                .contains(&self.payload["status"].as_str().unwrap_or("")))
        {
            return Err(invalid("Invalid D2A feedback"));
        }
        Ok(())
    }
    fn expired(&self) -> bool {
        self.expires_at
            .as_ref()
            .and_then(|v| OffsetDateTime::parse(v, &Rfc3339).ok())
            .is_some_and(|v| v <= OffsetDateTime::now_utc())
    }
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct D2ACapability {
    pub name: String,
    pub input_schema: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<Value>,
    #[serde(default)]
    pub requires_approval: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct D2ADeviceDescriptor {
    pub id: String,
    pub kind: String,
    pub capabilities: Vec<D2ACapability>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct D2ADiscovery {
    pub devices: Vec<D2ADeviceDescriptor>,
}
impl D2ADiscovery {
    pub fn validate(&self) -> Result<()> {
        if self.devices.len() > 1024 {
            return Err(invalid("Discovery supports at most 1024 devices"));
        }
        let mut ids = HashSet::new();
        for device in &self.devices {
            if !nonempty(&device.id) || !nonempty(&device.kind) || !ids.insert(&device.id) {
                return Err(invalid("Device IDs must be unique and nonempty"));
            }
            let mut names = HashSet::new();
            for capability in &device.capabilities {
                if !nonempty(&capability.name) || !names.insert(&capability.name) {
                    return Err(invalid("Capability names must be unique per device"));
                }
                validate_schema(&capability.input_schema)?;
                if let Some(schema) = &capability.output_schema {
                    validate_schema(schema)?;
                }
            }
        }
        Ok(())
    }
}
fn validate_schema(schema: &Value) -> Result<()> {
    if !schema.is_object() {
        return Err(invalid("Capability schema must be an object"));
    }
    fn remote(value: &Value) -> bool {
        match value {
            Value::Object(m) => m.iter().any(|(k, v)| {
                (["$ref", "$dynamicRef", "$recursiveRef"].contains(&k.as_str())
                    && !v.as_str().is_some_and(|r| r.starts_with('#')))
                    || remote(v)
            }),
            Value::Array(a) => a.iter().any(remote),
            _ => false,
        }
    }
    if remote(schema) {
        return Err(invalid("Device schemas must not fetch remote references"));
    }
    jsonschema::validator_for(schema).map_err(|_| invalid("Invalid device JSON schema"))?;
    Ok(())
}
/// Implement this interface for native vendor SDKs, MQTT, ROS 2 or any other device bus.
#[async_trait]
pub trait D2AProvider: Send + Sync {
    async fn discover(&self) -> Result<D2ADiscovery>;
    async fn events(&self, session_id: &str, cursor: Option<&str>) -> Result<D2AMessageStream>;
    async fn execute(&self, message: &D2AMessage) -> Result<D2AMessage>;
    async fn get_action(&self, action_id: &str) -> Result<D2AMessage>;
    async fn cancel(&self, action_id: &str) -> Result<D2AMessage>;
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct D2APolicy {
    pub allow_actions: bool,
    pub allowed_devices: Vec<String>,
    pub allowed_capabilities: Vec<String>,
}
#[derive(Clone)]
pub struct D2A {
    pub provider: Arc<dyn D2AProvider>,
    pub policy: D2APolicy,
    pub context: Value,
}
impl D2A {
    pub fn new(provider: impl D2AProvider + 'static) -> Self {
        Self {
            provider: Arc::new(provider),
            policy: D2APolicy::default(),
            context: json!({}),
        }
    }
    pub fn with_policy(mut self, policy: D2APolicy) -> Self {
        self.policy = policy;
        self
    }
    async fn open(
        &self,
        agent: &Agent,
        user_id: &str,
        session_id: &str,
        live: bool,
    ) -> Result<D2ASession> {
        if !nonempty(user_id) || !nonempty(session_id) || !self.context.is_object() {
            return Err(invalid(
                "D2A requires user and application session identity",
            ));
        }
        let discovery = self.provider.discover().await?;
        discovery.validate()?;
        let core = agent.marona.b2a.core.clone();
        let capabilities: Value = core
            .json(
                &core.runtime_url,
                Method::GET,
                "/runtime/d2a/capabilities",
                None,
            )
            .await?;
        if !capabilities["transports"]
            .as_array()
            .is_some_and(|v| v.contains(&json!("http-sse")))
        {
            return Err(invalid("Runtime does not support D2A realtime streaming"));
        }
        let snapshot:Value=core.json(&core.runtime_url,Method::POST,"/runtime/d2a/sessions",Some(&json!({"protocol_version":"1.0","user_id":user_id,"session_id":session_id,"agent":crate::b2a_agent_config(agent)?,"devices":discovery.devices,"context":self.context,"policy":self.policy}))).await?;
        let id = snapshot["session_id"]
            .as_str()
            .filter(|v| nonempty(v))
            .ok_or_else(|| invalid("Missing D2A session identity"))?
            .to_owned();
        if snapshot["protocol"] != "d2a"
            || snapshot["version"] != "1.0"
            || snapshot["state"] != "active"
            || snapshot["user_id"] != user_id
        {
            return Err(invalid("Invalid D2A session response"));
        }
        let provider_events = if live {
            match self.provider.events(session_id, None).await {
                Ok(s) => Some(s),
                Err(error) => {
                    let _: Result<Value> = core
                        .json(
                            &core.runtime_url,
                            Method::DELETE,
                            &format!("/runtime/d2a/sessions/{id}"),
                            None,
                        )
                        .await;
                    return Err(error);
                }
            }
        } else {
            None
        };
        let (commands, rx) = mpsc::channel(32);
        let (events, out) = mpsc::channel(128);
        let worker = D2AWorker {
            core,
            config: self.clone(),
            discovery,
            snapshot,
            agent: agent.clone(),
            application_id: session_id.into(),
            events,
            actions: HashMap::new(),
            requests: HashMap::new(),
            approved: HashSet::new(),
            seen: HashSet::new(),
        };
        let task = tokio::spawn(worker.run(rx, provider_events));
        Ok(D2ASession {
            session_id: session_id.into(),
            protocol_session_id: id,
            commands,
            events: out,
            task: Some(task),
            last_result: None,
            closed: false,
        })
    }
}
#[async_trait]
impl AgentProtocol for D2A {
    fn name(&self) -> &str {
        "d2a"
    }
    async fn capabilities(&self) -> Result<Value> {
        let devices = self.provider.discover().await?;
        devices.validate()?;
        Ok(json!({"devices":devices.devices,"policy":self.policy}))
    }
    async fn connect(
        &self,
        agent: &Agent,
        user_id: &str,
        session_id: &str,
    ) -> Result<Box<dyn ProtocolSession>> {
        Ok(Box::new(self.open(agent, user_id, session_id, true).await?))
    }
    async fn run(
        &self,
        agent: &Agent,
        input: Input,
        user_id: &str,
        session_id: &str,
    ) -> Result<RunResult> {
        let Input::Message(input) = input else {
            return Err(invalid("D2A input must be a canonical message"));
        };
        let mut session = self.open(agent, user_id, session_id, false).await?;
        let outcome = async {
            session.send(&input).await?;
            while let Some(event) = session.next_event().await? {
                if event.event_type == "exchange.completed" {
                    if let Some(status) = event.data.get("action_status").and_then(Value::as_str) {
                        if status != "succeeded" {
                            return Err(Error::Protocol(format!("D2A action outcome: {status}")));
                        }
                    }
                    return session
                        .last_result
                        .clone()
                        .ok_or_else(|| invalid("D2A exchange did not produce agent output"));
                }
            }
            Err(invalid("D2A closed before completion"))
        }
        .await;
        let close = session.close().await;
        match outcome {
            Ok(result) => {
                close?;
                Ok(result)
            }
            Err(e) => Err(e),
        }
    }
}
#[derive(Clone, Debug)]
pub struct D2AEvent {
    pub event_type: String,
    pub data: Value,
    pub message: Option<D2AMessage>,
    pub output: Value,
}
enum D2ACommand {
    Reconcile(String, bool, oneshot::Sender<Result<D2AMessage>>),
    Approve(String, bool, oneshot::Sender<Result<()>>),
    Send(Value, oneshot::Sender<Result<()>>),
    Close(oneshot::Sender<Result<()>>),
}
struct D2AItem {
    event: RunEvent,
    result: Option<RunResult>,
}
pub struct D2ASession {
    pub session_id: String,
    pub protocol_session_id: String,
    commands: mpsc::Sender<D2ACommand>,
    events: mpsc::Receiver<Result<D2AItem>>,
    task: Option<tokio::task::JoinHandle<Result<()>>>,
    last_result: Option<RunResult>,
    closed: bool,
}
impl D2ASession {
    pub async fn get_action(&mut self, action_id: &str) -> Result<D2AMessage> {
        self.reconcile(action_id, false).await
    }
    pub async fn cancel(&mut self, action_id: &str) -> Result<D2AMessage> {
        self.reconcile(action_id, true).await
    }
    async fn reconcile(&mut self, action_id: &str, cancel: bool) -> Result<D2AMessage> {
        if !nonempty(action_id) || self.closed {
            return Err(invalid("Active session and action ID required"));
        }
        let (tx, rx) = oneshot::channel();
        self.commands
            .send(D2ACommand::Reconcile(action_id.into(), cancel, tx))
            .await
            .map_err(|_| invalid("D2A session stopped"))?;
        rx.await.map_err(|_| invalid("D2A session stopped"))?
    }
    pub async fn approve_action(&mut self, action_id: &str, approved: bool) -> Result<()> {
        if !nonempty(action_id) || self.closed {
            return Err(invalid("Active session and action ID required"));
        }
        let (tx, rx) = oneshot::channel();
        self.commands
            .send(D2ACommand::Approve(action_id.into(), approved, tx))
            .await
            .map_err(|_| invalid("D2A session stopped"))?;
        rx.await.map_err(|_| invalid("D2A session stopped"))?
    }

    pub async fn send_message(&mut self, message: &D2AMessage) -> Result<()> {
        self.send(&message.to_value()).await
    }
    async fn request(&mut self, input: &Value) -> Result<()> {
        if self.closed {
            return Err(invalid("D2A session is closed"));
        }
        D2AMessage::from_value(input.clone())?;
        let (tx, rx) = oneshot::channel();
        self.commands
            .send(D2ACommand::Send(input.clone(), tx))
            .await
            .map_err(|_| invalid("D2A session stopped"))?;
        rx.await.map_err(|_| invalid("D2A session stopped"))?
    }
    fn consume(&mut self, item: Result<D2AItem>) -> Result<RunEvent> {
        let item = item?;
        if item.event.event_type == "exchange.started" {
            self.last_result = None;
        }
        if item.result.is_some() {
            self.last_result = item.result;
        }
        Ok(item.event)
    }
}
#[async_trait]
impl ProtocolSession for D2ASession {
    fn supports_feedback(&self) -> bool {
        true
    }
    fn supports_delivery(&self) -> bool {
        true
    }
    fn result(&self) -> Option<RunResult> {
        self.last_result.clone()
    }
    async fn send(&mut self, input: &Value) -> Result<()> {
        self.request(input).await
    }
    async fn deliver(&mut self, input: &Value) -> Result<()> {
        self.request(input).await
    }
    async fn deliver_feedback(&mut self, original: &Value) -> Result<()> {
        let mut message = D2AMessage::new(
            "agent",
            "coordination",
            original["payload"]["content"]
                .as_array()
                .cloned()
                .unwrap_or_default(),
        )?;
        message.correlation_id = original["correlation_id"]
            .as_str()
            .or_else(|| original["message_id"].as_str())
            .map(str::to_owned);
        message.payload["execute"] = json!(false);
        message.payload["source_protocol"] = original["protocol"].clone();
        message.payload["feedback"] = original["payload"].clone();
        self.request(&message.to_value()).await
    }
    async fn next_event(&mut self) -> Result<Option<RunEvent>> {
        match self.events.recv().await {
            Some(item) => Ok(Some(self.consume(item)?)),
            None => Ok(None),
        }
    }
    async fn poll_event(&mut self) -> Result<Option<RunEvent>> {
        match self.events.try_recv() {
            Ok(item) => Ok(Some(self.consume(item)?)),
            Err(mpsc::error::TryRecvError::Empty) => Ok(None),
            Err(_) => Ok(None),
        }
    }
    async fn close(&mut self) -> Result<()> {
        if self.closed {
            return Ok(());
        }
        self.closed = true;
        let (tx, rx) = oneshot::channel();
        let closing = self.commands.send(D2ACommand::Close(tx));
        tokio::pin!(closing);
        let sent = loop {
            tokio::select! {sent=&mut closing=>break sent,_=self.events.recv()=>{}}
        };
        // Drain bounded events while the worker finishes; otherwise a full queue could block close.
        let result = if sent.is_ok() {
            tokio::select! {value=rx=>value.unwrap_or(Ok(())),_ = async {while self.events.recv().await.is_some(){}}=>Ok(())}
        } else {
            Ok(())
        };
        let cleanup = if let Some(task) = self.task.take() {
            task.await
                .map_err(|_| invalid("D2A session task stopped unexpectedly"))?
        } else {
            Ok(())
        };
        result?;
        cleanup
    }
    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}
impl Drop for D2ASession {
    fn drop(&mut self) {
        if let Some(task) = self.task.take() {
            task.abort();
        }
    }
}
struct D2AWorker {
    core: Arc<crate::core::Core>,
    config: D2A,
    discovery: D2ADiscovery,
    snapshot: Value,
    agent: Agent,
    application_id: String,
    events: mpsc::Sender<Result<D2AItem>>,
    actions: HashMap<String, D2AMessage>,
    requests: HashMap<String, Value>,
    approved: HashSet<String>,
    seen: HashSet<String>,
}
impl D2AWorker {
    fn path(&self, suffix: &str) -> String {
        format!(
            "/runtime/d2a/sessions/{}{suffix}",
            self.snapshot["session_id"].as_str().unwrap_or("")
        )
    }
    async fn emit(&self, kind: &str, data: Value, result: Option<RunResult>) -> Result<()> {
        let output = result
            .as_ref()
            .map(|r| r.output.clone())
            .unwrap_or(Value::Null);
        self.events
            .send(Ok(D2AItem {
                event: RunEvent {
                    event_type: kind.into(),
                    delta: None,
                    output,
                    data: data.as_object().cloned().unwrap_or_default(),
                },
                result,
            }))
            .await
            .map_err(|_| invalid("D2A receiver closed"))
    }
    async fn run(
        mut self,
        mut commands: mpsc::Receiver<D2ACommand>,
        mut provider_events: Option<D2AMessageStream>,
    ) -> Result<()> {
        loop {
            tokio::select! {
                command=commands.recv()=>{match command {Some(D2ACommand::Send(input,reply))=>{let _=reply.send(Ok(()));if let Err(error)=self.exchange(input).await {let _=self.events.send(Err(error)).await;break;}},Some(D2ACommand::Approve(id,approved,reply))=>{let _=reply.send(Ok(()));if let Err(error)=self.approve(&id,approved).await{let _=self.events.send(Err(error)).await;break;}},Some(D2ACommand::Reconcile(id,cancel,reply))=>{let result=self.reconcile(&id,cancel).await;let _=reply.send(result);},Some(D2ACommand::Close(reply))=>{let result=self.close().await;let _=reply.send(result);return Ok(());},None=>break}},
                next=async {match &mut provider_events {Some(stream)=>stream.next().await,None=>std::future::pending().await}}=>{
                    match next {Some(Ok(message))=>{if let Err(error)=self.ingest(message).await {let _=self.events.send(Err(error)).await;break;}},Some(Err(error))=>{let _=self.events.send(Err(error)).await;break;},None=>{provider_events=None;let _=self.emit("provider.disconnected",json!({"protocol":"d2a"}),None).await;}}
                }
            }
        }
        self.close().await
    }
    async fn reconcile(&mut self, id: &str, cancel: bool) -> Result<D2AMessage> {
        if !self.requests.contains_key(id) {
            return Err(invalid("No reserved device action"));
        }
        let message = if cancel {
            self.config.provider.cancel(id).await?
        } else {
            self.config.provider.get_action(id).await?
        };
        self.ingest(message.clone()).await?;
        Ok(message)
    }
    async fn ingest(&mut self, message: D2AMessage) -> Result<()> {
        message.validate()?;
        let device = self
            .discovery
            .devices
            .iter()
            .find(|d| d.id == message.source)
            .ok_or_else(|| invalid("Provider event source was not discovered"))?;
        if message.source == "agent"
            || !["data", "observation", "state", "feedback"]
                .contains(&message.payload["kind"].as_str().unwrap_or(""))
            || [
                "routes",
                "approved",
                "coordination",
                "source_protocol",
                "route_id",
                "hops",
            ]
            .iter()
            .any(|key| message.payload.get(key).is_some())
        {
            return Err(invalid(
                "Provider events cannot request actions or protocol coordination",
            ));
        }
        if message.payload["kind"] == "feedback" {
            let id = message.payload["action_id"].as_str().unwrap_or("");
            let request = self
                .requests
                .get(id)
                .ok_or_else(|| invalid("Provider feedback has no reserved action"))?;
            if request["target"] != message.source {
                return Err(invalid("Provider feedback source mismatch"));
            }
            let cap = device
                .capabilities
                .iter()
                .find(|c| c.name == request["capability"])
                .ok_or_else(|| invalid("Feedback capability not advertised"))?;
            if message.payload["status"] == "succeeded" {
                if let Some(schema) = &cap.output_schema {
                    if !jsonschema::validator_for(schema)
                        .map_err(|_| invalid("Invalid output schema"))?
                        .is_valid(&message.payload["result"])
                    {
                        return Err(invalid("Device result does not match capability schema"));
                    }
                }
            }
            if let Some(previous) = self.actions.get(id) {
                let status = previous.payload["status"].as_str().unwrap_or("unknown");
                if !["accepted", "executing", "unknown"].contains(&status)
                    && previous.payload["status"] != message.payload["status"]
                {
                    return Err(invalid("Terminal device outcome cannot change"));
                }
            }
            self.actions.insert(id.into(), message.clone());
        }
        self.exchange(message.to_value()).await
    }
    async fn close(&self) -> Result<()> {
        let _: Value = self
            .core
            .json(&self.core.runtime_url, Method::DELETE, &self.path(""), None)
            .await?;
        Ok(())
    }
    fn bind(&self, mut message: D2AMessage) -> Result<D2AMessage> {
        message.session_id = self.snapshot["session_id"].as_str().map(str::to_owned);
        if ["feedback", "coordination"].contains(&message.payload["kind"].as_str().unwrap_or("")) {
            message.payload["execute"] = json!(false);
        }
        message.sequence = self.snapshot["next_sequence"].as_u64();
        if message.sequence.is_none() {
            return Err(invalid("Invalid D2A sequence state"));
        }
        message.validate()?;
        Ok(message)
    }
    async fn exchange(&mut self, input: Value) -> Result<()> {
        let message = self.bind(D2AMessage::from_value(input)?)?;
        if message.expired() {
            return Err(invalid("D2A message expired"));
        }
        self.emit(
            "exchange.started",
            json!({"message_id":message.message_id,"protocol":"d2a"}),
            None,
        )
        .await?;
        let response = self
            .core
            .stream_client
            .post(format!(
                "{}{}",
                self.core.runtime_url,
                self.path("/messages/stream")
            ))
            .headers(self.core.headers.clone())
            .bearer_auth(self.core.require_api_key()?)
            .json(&message)
            .send()
            .await?;
        self.core.check_response(&response)?;
        let mut stream = json_events(response);
        let mut completed = None;
        let mut pending = Vec::new();
        while let Some(event) = stream.next().await {
            let event = event?;
            match event["type"].as_str() {
                Some("message") => {
                    let output = D2AMessage::from_value(event["message"].clone())?;
                    self.check_identity(&output)?;
                    if output.extra.get("stream").and_then(|v| v.get("final"))
                        == Some(&json!(false))
                    {
                        self.emit(
                            "message",
                            json!({"message":output,"protocol":"d2a","source":output.source}),
                            None,
                        )
                        .await?;
                        continue;
                    }
                    pending.push(output);
                }
                Some("protocol.route") => {
                    self.emit("protocol.route", event["data"].clone(), None)
                        .await?;
                }
                Some("exchange.completed") => {
                    completed = Some(event["exchange"].clone());
                }
                Some("stream.failed") => {
                    return Err(Error::Protocol(
                        "D2A stream failed; no action was replayed".into(),
                    ))
                }
                _ => {}
            }
        }
        let exchange =
            completed.ok_or_else(|| invalid("D2A stream ended before exchange completion"))?;
        if exchange["session_id"] != self.snapshot["session_id"]
            || exchange["ack"]["message_id"] != message.message_id
        {
            return Err(invalid("D2A exchange correlation mismatch"));
        }
        self.process(exchange, pending).await
    }
    async fn approve(&mut self, id: &str, approved: bool) -> Result<()> {
        let encoded = url::form_urlencoded::byte_serialize(id.as_bytes()).collect::<String>();
        let exchange: Value = self
            .core
            .json(
                &self.core.runtime_url,
                Method::POST,
                &self.path(&format!("/actions/{encoded}/approve")),
                Some(&json!({"approved":approved})),
            )
            .await?;
        if approved {
            self.approved.insert(id.into());
        }
        let result = self.process(exchange, Vec::new()).await;
        self.approved.remove(id);
        result
    }
    async fn process(&mut self, exchange: Value, mut pending: Vec<D2AMessage>) -> Result<()> {
        if exchange["session_id"] != self.snapshot["session_id"]
            || exchange["session"]["session_id"] != self.snapshot["session_id"]
            || exchange["session"]["state"] != "active"
        {
            return Err(invalid("Invalid D2A exchange snapshot"));
        }
        let mut result = None;
        let mut action_status: Option<String> = None;
        self.snapshot = exchange["session"].clone();
        for event in exchange["events"].as_array().into_iter().flatten() {
            if event["type"] == "protocol.route" {
                self.emit("protocol.route", event["data"].clone(), None)
                    .await?;
            } else {
                let item = D2AMessage::from_value(event.clone())?;
                self.check_identity(&item)?;
                pending.push(item);
            }
        }
        for output in pending {
            if !self.seen.insert(output.message_id.clone()) {
                continue;
            }
            if self.seen.len() > 4096 {
                return Err(invalid(
                    "D2A event history capacity reached; open a new session",
                ));
            }
            if output.payload["status"] == "failed" && output.payload.get("error").is_some() {
                action_status = Some("failed".into());
            }
            if output.payload["status"] == "approval_required" {
                action_status = Some("approval_required".into());
            }
            if output.payload["kind"] == "feedback" {
                let status = output.payload["status"].as_str().unwrap_or("unknown");
                if action_status.is_none() || action_status.as_deref() == Some("succeeded") {
                    action_status = Some(status.into());
                }
                self.emit(
                    "feedback",
                    json!({"message":output,"source":output.source}),
                    None,
                )
                .await?;
            }
            if output.payload["response"].is_object() {
                result = crate::b2a_runner::completed_result(
                    &self.agent,
                    &json!({"status":"completed","response":output.payload["response"]}),
                    &self.application_id,
                )
                .await?;
            }
            self.emit(
                "message",
                json!({"message":output,"protocol":"d2a","source":output.source}),
                result.clone(),
            )
            .await?;
            for route in output.payload["routes"].as_array().into_iter().flatten() {
                self.emit("protocol.route", route.clone(), None).await?;
            }
            if output.source == "agent" && output.payload["kind"] == "action" {
                let feedback = self.execute(&output).await?;
                if action_status.is_none() || action_status.as_deref() == Some("succeeded") {
                    action_status = feedback.payload["status"].as_str().map(str::to_owned);
                }
                let feedback = self.bind(feedback)?;
                let mut body = feedback.to_value();
                body["payload"]["execute"] = json!(false);
                let saved: Value = self
                    .core
                    .json(
                        &self.core.runtime_url,
                        Method::POST,
                        &self.path("/messages"),
                        Some(&body),
                    )
                    .await?;
                if saved["session_id"] != self.snapshot["session_id"]
                    || saved["ack"]["message_id"] != feedback.message_id
                {
                    return Err(invalid("D2A feedback correlation mismatch"));
                }
                self.snapshot = saved["session"].clone();
                self.emit(
                    "feedback",
                    json!({"message":feedback,"protocol":"d2a","source":feedback.source}),
                    None,
                )
                .await?;
            }
        }
        self.emit(
            "exchange.completed",
            json!({"exchange":exchange,"protocol":"d2a","action_status":action_status}),
            result,
        )
        .await?;
        Ok(())
    }
    fn check_identity(&self, message: &D2AMessage) -> Result<()> {
        if message.session_id.as_deref() != self.snapshot["session_id"].as_str() {
            return Err(invalid("D2A event session mismatch"));
        }
        Ok(())
    }
    async fn execute(&mut self, action: &D2AMessage) -> Result<D2AMessage> {
        let id = action.payload["action_id"]
            .as_str()
            .ok_or_else(|| invalid("Missing action ID"))?
            .to_owned();
        let identity = json!({"target":action.target,"capability":action.payload["capability"],"arguments":action.payload["arguments"],"expected_revision":action.payload["expected_revision"]});
        if self.requests.get(&id).is_some_and(|v| v != &identity) {
            return Err(invalid("Action ID reused for different request"));
        }
        if let Some(previous) = self.actions.get(&id) {
            return Ok(previous.clone());
        }
        if self.actions.len() >= 10000 {
            return Err(invalid(
                "Action history capacity reached; open a new session",
            ));
        }
        let feedback = match self.authorize(action) {
            Err(reason) => D2AMessage::feedback(
                action,
                if action.expired() {
                    "expired"
                } else {
                    "rejected"
                },
                json!({"reason":reason.to_string()}),
            )?,
            Ok(capability) => {
                self.requests.insert(id.clone(), identity);
                // Reserve before I/O. Never replay a physical action after an uncertain transport outcome.
                self.actions.insert(
                    id.clone(),
                    D2AMessage::feedback(
                        action,
                        "unknown",
                        json!({"reason":"Execution outcome is not confirmed"}),
                    )?,
                );
                let received = match self.config.provider.execute(action).await {
                    Ok(value) => Ok(value),
                    Err(_) => self.config.provider.get_action(&id).await,
                };
                match received {
                    Ok(value) => {
                        value.validate()?;
                        if [
                            "routes",
                            "coordination",
                            "approved",
                            "source_protocol",
                            "route_id",
                            "hops",
                        ]
                        .iter()
                        .any(|key| value.payload.get(key).is_some())
                        {
                            return Err(invalid(
                                "Provider feedback cannot supply coordination or approval metadata",
                            ));
                        }
                        if value.payload["kind"] != "feedback"
                            || value.payload["action_id"] != id
                            || value.source != action.target.clone().unwrap_or_default()
                        {
                            return Err(invalid("Device feedback identity mismatch"));
                        }
                        if value.payload["status"] == "succeeded" {
                            if let Some(schema) = capability.output_schema {
                                let validator = jsonschema::validator_for(&schema)
                                    .map_err(|_| invalid("Invalid output schema"))?;
                                if !validator.is_valid(&value.payload["result"]) {
                                    return Err(invalid(
                                        "Device result does not match capability schema",
                                    ));
                                }
                            }
                        }
                        value
                    }
                    Err(_) => self.actions[&id].clone(),
                }
            }
        };
        // Retain IDs for the entire session. Fail closed rather than evict execution history.
        if self.actions.len() >= 10000 && !self.actions.contains_key(&id) {
            return Err(invalid(
                "D2A action history capacity reached; open a new session",
            ));
        }
        self.actions.insert(id, feedback.clone());
        Ok(feedback)
    }
    fn authorize(&self, action: &D2AMessage) -> Result<D2ACapability> {
        if action.expired() {
            return Err(invalid("Action expired"));
        }
        if !self.config.policy.allow_actions {
            return Err(Error::PermissionRequired("D2A actions are disabled".into()));
        }
        let device = self
            .discovery
            .devices
            .iter()
            .find(|v| Some(v.id.as_str()) == action.target.as_deref())
            .ok_or_else(|| invalid("Action target was not discovered"))?;
        let name = action.payload["capability"].as_str().unwrap_or("");
        let capability = device
            .capabilities
            .iter()
            .find(|v| v.name == name)
            .ok_or_else(|| invalid("Undeclared device capability"))?;
        if (!self.config.policy.allowed_devices.is_empty()
            && !self.config.policy.allowed_devices.contains(&device.id))
            || (!self.config.policy.allowed_capabilities.is_empty()
                && !self
                    .config
                    .policy
                    .allowed_capabilities
                    .contains(&capability.name))
        {
            return Err(Error::PermissionRequired(
                "Action is outside the allowlist".into(),
            ));
        }
        if capability.requires_approval
            && !self
                .approved
                .contains(action.payload["action_id"].as_str().unwrap_or(""))
        {
            return Err(Error::ApprovalRequired(
                "Device capability requires separate approval".into(),
            ));
        }
        if let Some(expected) = action.payload.get("expected_revision") {
            if device.revision.as_ref() != Some(expected) {
                return Err(invalid("Device state revision changed"));
            }
        }
        let schema = jsonschema::validator_for(&capability.input_schema)
            .map_err(|_| invalid("Invalid input schema"))?;
        if !schema.is_valid(&action.payload["arguments"]) {
            return Err(invalid("Action arguments do not match capability schema"));
        }
        Ok(capability.clone())
    }
}

/// HTTP/SSE device gateway. MCP command tools may share a separately configured SSE event URL.
#[derive(Clone)]
pub struct D2ADevice {
    url: String,
    client: reqwest::Client,
    transport: D2ATransport,
    event_url: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum D2ATransport {
    Http,
    Mcp,
}
impl D2ADevice {
    pub fn new(url: impl Into<String>, token: impl Into<String>) -> Result<Self> {
        Self::with_transport(url, token, D2ATransport::Http, None)
    }
    pub fn with_transport(
        url: impl Into<String>,
        token: impl Into<String>,
        transport: D2ATransport,
        event_url: Option<String>,
    ) -> Result<Self> {
        let url = url.into().trim_end_matches('/').to_owned();
        let token = token.into();
        if token.trim().is_empty() {
            return Err(invalid("Device credential is required"));
        }
        validate_gateway_url(&url)?;
        if let Some(value) = &event_url {
            validate_gateway_url(value)?;
        }
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::AUTHORIZATION,
            reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
                .map_err(|_| invalid("Invalid provider credential"))?,
        );
        headers.insert(
            reqwest::header::ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json, text/event-stream"),
        );
        Ok(Self {
            url,
            transport,
            event_url,
            client: reqwest::Client::builder()
                .default_headers(headers)
                .redirect(Policy::none())
                .connect_timeout(Duration::from_secs(15))
                .read_timeout(Duration::from_secs(60))
                .build()?,
        })
    }
    async fn call(
        &self,
        method: Method,
        path: &str,
        operation: &str,
        body: Option<Value>,
    ) -> Result<Value> {
        if self.transport == D2ATransport::Http {
            let mut request = self.client.request(method, format!("{}{path}", self.url));
            if let Some(body) = body {
                request = request.json(&body);
            }
            let response = request.send().await?;
            if !response.status().is_success() {
                return Err(invalid(format!(
                    "Device gateway request failed ({})",
                    response.status()
                )));
            }
            return bounded_json(response).await;
        }
        let response=self.client.post(&self.url).json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"marona","version":env!("CARGO_PKG_VERSION")}}})).send().await?;
        let mut headers = reqwest::header::HeaderMap::new();
        if let Some(id) = response.headers().get("mcp-session-id") {
            headers.insert("mcp-session-id", id.clone());
        }
        let initialized = crate::b2a_codec::rpc(response, 1).await?;
        let version = initialized["protocolVersion"]
            .as_str()
            .ok_or_else(|| invalid("Missing MCP protocol version"))?;
        if !["2025-11-25", "2025-06-18", "2025-03-26"].contains(&version) {
            return Err(invalid("Unsupported MCP protocol version"));
        }
        headers.insert(
            "MCP-Protocol-Version",
            reqwest::header::HeaderValue::from_str(version)
                .map_err(|_| invalid("Invalid MCP version"))?,
        );
        let outcome=async {let ready=self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","method":"notifications/initialized"})).send().await?;if !ready.status().is_success(){return Err(invalid("MCP initialization rejected"));}let response=self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":operation,"arguments":body.unwrap_or_else(||json!({}))}})).send().await?;let result=crate::b2a_codec::rpc(response,2).await?;if result["isError"]==true{return Err(invalid("D2A MCP tool failed"));}let value=result.get("structuredContent").ok_or_else(||invalid("D2A MCP requires structuredContent"))?;Ok(value.get("data").filter(|_|value["success"]==true).unwrap_or(value).clone())}.await;
        if headers.contains_key("mcp-session-id") {
            let _ = self
                .client
                .delete(&self.url)
                .headers(headers)
                .timeout(Duration::from_secs(2))
                .send()
                .await;
        }
        outcome
    }
}
fn validate_gateway_url(value: &str) -> Result<()> {
    let url = url::Url::parse(value).map_err(|_| invalid("Invalid device gateway URL"))?;
    let local = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
    if !(url.scheme() == "https" || url.scheme() == "http" && local)
        || !url.username().is_empty()
        || url.password().is_some()
        || url.fragment().is_some()
        || url.query().is_some()
    {
        return Err(invalid(
            "Device gateways require HTTPS except loopback development",
        ));
    }
    Ok(())
}
#[async_trait]
impl D2AProvider for D2ADevice {
    async fn discover(&self) -> Result<D2ADiscovery> {
        let result: D2ADiscovery = serde_json::from_value(
            self.call(Method::GET, "/v1/devices", "discover", None)
                .await?,
        )
        .map_err(|_| invalid("Invalid device discovery"))?;
        result.validate()?;
        Ok(result)
    }
    async fn events(&self, session_id: &str, cursor: Option<&str>) -> Result<D2AMessageStream> {
        let endpoint=match (&self.event_url,self.transport){(Some(url),_)=>url.clone(),(None,D2ATransport::Http)=>format!("{}/v1/events",self.url),_=>return Err(invalid("MCP request tools require an explicit persistent event URL or native streaming provider"))};
        let mut query = vec![("session_id", session_id)];
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor));
        }
        let response = self.client.get(endpoint).query(&query).send().await?;
        if !response.status().is_success() {
            return Err(invalid("Device event stream rejected"));
        }
        let mut stream = json_events(response);
        Ok(Box::pin(
            async_stream::try_stream! {while let Some(value)=stream.next().await{let value=value?;yield D2AMessage::from_value(value.get("message").unwrap_or(&value).clone())?;}},
        ))
    }
    async fn execute(&self, message: &D2AMessage) -> Result<D2AMessage> {
        D2AMessage::from_value(
            self.call(
                Method::POST,
                "/v1/actions",
                "execute",
                Some(if self.transport == D2ATransport::Mcp {
                    json!({"message":message})
                } else {
                    message.to_value()
                }),
            )
            .await?,
        )
    }
    async fn get_action(&self, id: &str) -> Result<D2AMessage> {
        if !nonempty(id) {
            return Err(invalid("Action ID is required"));
        }
        let id_path = url::form_urlencoded::byte_serialize(id.as_bytes()).collect::<String>();
        D2AMessage::from_value(
            self.call(
                Method::GET,
                &format!("/v1/actions/{id_path}"),
                "get_action",
                Some(json!({"action_id":id})),
            )
            .await?,
        )
    }
    async fn cancel(&self, id: &str) -> Result<D2AMessage> {
        if !nonempty(id) {
            return Err(invalid("Action ID is required"));
        }
        let id_path = url::form_urlencoded::byte_serialize(id.as_bytes()).collect::<String>();
        D2AMessage::from_value(
            self.call(
                Method::POST,
                &format!("/v1/actions/{id_path}/cancel"),
                "cancel",
                Some(json!({"action_id":id})),
            )
            .await?,
        )
    }
}
async fn bounded_json(response: reqwest::Response) -> Result<Value> {
    let mut body = Vec::new();
    let mut stream = response.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        if body.len() + chunk.len() > 2_097_152 {
            return Err(invalid("Device response exceeds 2 MiB"));
        }
        body.extend_from_slice(&chunk);
    }
    serde_json::from_slice(&body).map_err(|_| invalid("Invalid device JSON response"))
}
fn json_events(response: reqwest::Response) -> Pin<Box<dyn Stream<Item = Result<Value>> + Send>> {
    Box::pin(
        async_stream::try_stream! {let mut bytes=response.bytes_stream();let mut buffer=Vec::new();let mut data=Vec::new();while let Some(chunk)=bytes.next().await{buffer.extend_from_slice(&chunk?);if buffer.len()+data.len()>1_048_576{Err(invalid("D2A event exceeds 1 MiB"))?;}while let Some(end)=buffer.iter().position(|b|*b==b'\n'){let mut line:Vec<u8>=buffer.drain(..=end).collect();line.pop();if line.last()==Some(&b'\r'){line.pop();}if line.is_empty(){if !data.is_empty(){let event:Value=serde_json::from_slice(&data).map_err(|_|invalid("Invalid D2A SSE JSON"))?;data.clear();yield event;}}else if line.starts_with(b"data:"){if !data.is_empty(){data.push(b'\n');}let value=&line[5..];data.extend_from_slice(value.strip_prefix(b" ").unwrap_or(value));}}}if !buffer.is_empty()||!data.is_empty(){Err(invalid("D2A SSE ended mid-event"))?;}},
    )
}

/// Compatibility spelling for applications using a device gateway.
pub type D2AGateway = D2ADevice;