harn-serve 0.10.121

Shared outbound workflow server core for Harn adapters
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
//! Public ACP wire helpers for Rust embedders.
//!
//! These types cover the stable request shapes embedders most often send to
//! `harn serve acp` or [`crate::EmbeddedAgent`]. They intentionally preserve
//! ACP's JSON field names so callers can serialize them directly onto the wire.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

pub const ACP_METHOD_INITIALIZE: &str = "initialize";
pub const ACP_METHOD_SESSION_NEW: &str = "session/new";
pub const ACP_METHOD_SESSION_LOAD: &str = "session/load";
pub const ACP_METHOD_SESSION_RESUME: &str = "session/resume";
pub const ACP_METHOD_SESSION_PROMPT: &str = "session/prompt";
pub const ACP_METHOD_SESSION_CANCEL: &str = "session/cancel";
pub const ACP_METHOD_SESSION_CANCEL_TOOL_CALL: &str = "session/cancel_tool_call";
pub const ACP_METHOD_SESSION_CLOSE: &str = "session/close";
pub const ACP_METHOD_SESSION_INJECT: &str = "session/inject";
pub const ACP_METHOD_SESSION_INJECT_HOST_EVENT: &str = "session/inject_host_event";
pub const ACP_METHOD_SESSION_REPLACE_INJECT: &str = "session/replace_inject";
pub const ACP_METHOD_SESSION_REVOKE_INJECT: &str = "session/revoke_inject";
pub const ACP_METHOD_SESSION_PENDING_INJECTIONS: &str = "session/pending_injections";
pub const ACP_METHOD_SESSION_PLAN_DOCUMENT_MUTATE: &str = "session/plan_document/mutate";
pub const ACP_PLAN_REVISION_CONFLICT_CODE: i64 = -32009;
pub const ACP_PLAN_MUTATION_BUSY_CODE: i64 = -32010;
pub const ACP_PLAN_REVISION_CONFLICT_SCHEMA: &str = "harn.plan_document_conflict.v1";
pub const ACP_PROMPT_ERROR_DATA_SCHEMA: &str = "harn.acp.prompt_error.v1";

/// Params for Harn's collaborative plan-document mutation extension.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AcpPlanDocumentMutationParams {
    pub session_id: String,
    pub document_id: String,
    pub expected_revision_id: String,
    pub mutation: AcpPlanDocumentMutation,
}

/// One optimistic mutation against a canonical collaborative plan document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    tag = "kind",
    rename_all = "snake_case",
    rename_all_fields = "camelCase",
    deny_unknown_fields
)]
pub enum AcpPlanDocumentMutation {
    Edit {
        markdown: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        plan: Option<Box<harn_vm::llm::plan::PlanArtifact>>,
    },
    AddComment {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        comment_id: Option<String>,
        anchor: harn_vm::llm::plan::PlanCommentAnchor,
        body: String,
    },
    ChangeCommentState {
        comment_id: String,
        state: harn_vm::llm::plan::PlanCommentState,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_run_id: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        explanation: Option<String>,
    },
    Approve {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reviewer: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reason: Option<String>,
    },
}

/// Result returned after Harn has persisted and emitted a plan mutation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcpPlanDocumentMutationResult {
    pub plan_document: harn_vm::llm::plan::PlanDocument,
}

/// JSON-RPC id values accepted by ACP requests and responses.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum AcpJsonRpcId {
    Number(u64),
    String(String),
    Null,
}

impl From<u64> for AcpJsonRpcId {
    fn from(value: u64) -> Self {
        Self::Number(value)
    }
}

impl From<&str> for AcpJsonRpcId {
    fn from(value: &str) -> Self {
        Self::String(value.to_string())
    }
}

impl From<String> for AcpJsonRpcId {
    fn from(value: String) -> Self {
        Self::String(value)
    }
}

/// A typed JSON-RPC request envelope for ACP methods.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpJsonRpcRequest<P = serde_json::Value> {
    pub jsonrpc: String,
    pub id: AcpJsonRpcId,
    pub method: String,
    pub params: P,
}

impl<P> AcpJsonRpcRequest<P> {
    pub fn new(id: impl Into<AcpJsonRpcId>, method: impl Into<String>, params: P) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id: id.into(),
            method: method.into(),
            params,
        }
    }
}

impl<P: Serialize> AcpJsonRpcRequest<P> {
    /// Serialize this request into the `serde_json::Value` expected by the
    /// in-process ACP channel transport.
    pub fn into_json_value(self) -> Result<serde_json::Value, serde_json::Error> {
        serde_json::to_value(self)
    }

    /// Serialize this request as one JSON-RPC line for stdio or WebSocket
    /// text-frame transports.
    pub fn into_json_line(self) -> Result<String, serde_json::Error> {
        serde_json::to_string(&self)
    }
}

impl AcpJsonRpcRequest<serde_json::Value> {
    pub fn initialize(id: impl Into<AcpJsonRpcId>) -> Self {
        Self::new(id, ACP_METHOD_INITIALIZE, serde_json::json!({}))
    }
}

impl AcpJsonRpcRequest<AcpSessionNewParams> {
    pub fn session_new(id: impl Into<AcpJsonRpcId>, params: AcpSessionNewParams) -> Self {
        Self::new(id, ACP_METHOD_SESSION_NEW, params)
    }
}

impl AcpJsonRpcRequest<AcpSessionPromptParams> {
    pub fn session_prompt(id: impl Into<AcpJsonRpcId>, params: AcpSessionPromptParams) -> Self {
        Self::new(id, ACP_METHOD_SESSION_PROMPT, params)
    }
}

impl AcpJsonRpcRequest<AcpSessionIdParams> {
    pub fn session_load(id: impl Into<AcpJsonRpcId>, params: AcpSessionIdParams) -> Self {
        Self::new(id, ACP_METHOD_SESSION_LOAD, params)
    }

    pub fn session_resume(id: impl Into<AcpJsonRpcId>, params: AcpSessionIdParams) -> Self {
        Self::new(id, ACP_METHOD_SESSION_RESUME, params)
    }

    pub fn session_cancel(id: impl Into<AcpJsonRpcId>, params: AcpSessionIdParams) -> Self {
        Self::new(id, ACP_METHOD_SESSION_CANCEL, params)
    }

    pub fn session_close(id: impl Into<AcpJsonRpcId>, params: AcpSessionIdParams) -> Self {
        Self::new(id, ACP_METHOD_SESSION_CLOSE, params)
    }

    pub fn session_pending_injections(
        id: impl Into<AcpJsonRpcId>,
        params: AcpSessionIdParams,
    ) -> Self {
        Self::new(id, ACP_METHOD_SESSION_PENDING_INJECTIONS, params)
    }
}

impl AcpJsonRpcRequest<AcpSessionInjectParams> {
    pub fn session_inject(id: impl Into<AcpJsonRpcId>, params: AcpSessionInjectParams) -> Self {
        Self::new(id, ACP_METHOD_SESSION_INJECT, params)
    }
}

impl AcpJsonRpcRequest<AcpSessionInjectHostEventParams> {
    pub fn session_inject_host_event(
        id: impl Into<AcpJsonRpcId>,
        params: AcpSessionInjectHostEventParams,
    ) -> Self {
        Self::new(id, ACP_METHOD_SESSION_INJECT_HOST_EVENT, params)
    }
}

impl AcpJsonRpcRequest<AcpSessionReplaceInjectParams> {
    pub fn session_replace_inject(
        id: impl Into<AcpJsonRpcId>,
        params: AcpSessionReplaceInjectParams,
    ) -> Self {
        Self::new(id, ACP_METHOD_SESSION_REPLACE_INJECT, params)
    }
}

impl AcpJsonRpcRequest<AcpSessionMessageIdParams> {
    pub fn session_revoke_inject(
        id: impl Into<AcpJsonRpcId>,
        params: AcpSessionMessageIdParams,
    ) -> Self {
        Self::new(id, ACP_METHOD_SESSION_REVOKE_INJECT, params)
    }
}

impl AcpJsonRpcRequest<AcpSessionCancelToolCallParams> {
    pub fn session_cancel_tool_call(
        id: impl Into<AcpJsonRpcId>,
        params: AcpSessionCancelToolCallParams,
    ) -> Self {
        Self::new(id, ACP_METHOD_SESSION_CANCEL_TOOL_CALL, params)
    }
}

/// Response envelope for successful ACP JSON-RPC calls.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpJsonRpcResponse<R = serde_json::Value> {
    pub jsonrpc: String,
    pub id: AcpJsonRpcId,
    pub result: R,
}

/// Common JSON-RPC error payload returned by ACP.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpJsonRpcError {
    pub code: i64,
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

/// Harn-owned machine data attached to a failed `session/prompt` response.
///
/// `message` remains lossless human diagnostics on the JSON-RPC error itself;
/// hosts branch only on this stable class and never reconstruct it from prose.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AcpPromptErrorSchema {
    #[serde(rename = "harn.acp.prompt_error.v1")]
    V1,
}

/// Machine-branchable facts projected from a terminal prompt failure.
///
/// Every field is optional and omitted when unknown, so the payload stays
/// additive on the `harn.acp.prompt_error.v1` envelope: a host that only reads
/// `schema` + `terminalClass` keeps working, while a routing-aware host reads
/// the authoritative provider/model of the route that actually failed instead
/// of inferring it from the session's UI model selection or parsing prose.
///
/// A non-provider failure (compile, setup, protocol) carries the same shape
/// with `provider`/`model` absent — the absence is itself the signal that no
/// route is responsible. These names mirror the structured error dict
/// `llm_call` throws (`category`/`kind`/`reason`/`code`/`retryAfterMs`/
/// `provider`/`model`), so the projection never invents a parallel vocabulary.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcpPromptFailureFacts {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retryable: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_after_ms: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// The per-route ledger the routing failure recorded: which provider/model
    /// each attempt used and how it ended. Empty for a single-route call or any
    /// non-routing failure. Lets a host render the full failover chain instead
    /// of just the terminal route.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attempts: Vec<AcpRoutingAttempt>,
    /// Set when no single route is responsible for the terminal outcome (e.g.
    /// both racers hit the deadline). It is the machine signal that the absence
    /// of `provider`/`model` is authoritative, not merely unknown — a host must
    /// not infer a route from its own model selection.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub route_unknown: bool,
}

/// One route the routing failure tried, projected from the thrown error's
/// `attempts` ledger. Only the machine-branchable identity/outcome fields are
/// carried (no floating-point cost) so the facts stay `Eq`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcpRoutingAttempt {
    pub index: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl AcpPromptFailureFacts {
    /// Project the structured error dict `llm_call`/routing throws into the
    /// stable failure facts. Non-object input (a bare thrown string, or a
    /// compile/setup error) yields empty facts, so provider/model are absent
    /// rather than fabricated.
    pub fn from_thrown(thrown: &serde_json::Value) -> Self {
        let Some(object) = thrown.as_object() else {
            return Self::default();
        };
        let string_field = |key: &str| {
            object
                .get(key)
                .and_then(|value| value.as_str())
                .map(str::to_string)
        };
        let kind = string_field("kind");
        let retry_after_ms = object
            .get("retry_after_ms")
            .and_then(serde_json::Value::as_i64);
        // `retryable` is only asserted when the producer gave us a signal for
        // it: an explicit `transient`/`terminal` kind, or a `retry-after` hint.
        // Otherwise it stays absent — we do not guess a boolean.
        let retryable = match kind.as_deref() {
            Some("transient") => Some(true),
            Some("terminal") => Some(false),
            _ => retry_after_ms.map(|_| true),
        };
        // `no_single_route` is the routing layer's no-fabrication signal (both
        // racers hit the deadline). Project it as `routeUnknown` so a host reads
        // the absent provider/model as authoritative, not merely missing.
        let route_unknown = object
            .get("no_single_route")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false);
        let attempts = object
            .get("attempts")
            .and_then(serde_json::Value::as_array)
            .map(|items| items.iter().map(AcpRoutingAttempt::from_value).collect())
            .unwrap_or_default();
        Self {
            category: string_field("category"),
            kind,
            reason: string_field("reason"),
            code: string_field("code"),
            retryable,
            retry_after_ms,
            provider: string_field("provider"),
            model: string_field("model"),
            attempts,
            route_unknown,
        }
    }
}

impl AcpRoutingAttempt {
    /// Project one entry of the thrown `attempts` ledger. The nested `error`
    /// object (when present) carries the per-route category/reason.
    fn from_value(value: &serde_json::Value) -> Self {
        let string_field = |key: &str| {
            value
                .get(key)
                .and_then(serde_json::Value::as_str)
                .map(str::to_string)
        };
        let error = value.get("error");
        let error_field = |key: &str| {
            error
                .and_then(|err| err.get(key))
                .and_then(serde_json::Value::as_str)
                .map(str::to_string)
        };
        Self {
            index: value
                .get("index")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0),
            provider: string_field("provider"),
            model: string_field("model"),
            status: string_field("status"),
            category: error_field("category"),
            reason: error_field("reason"),
        }
    }
}

/// Harn-owned typed `error.data` for a failed `session/prompt` response.
///
/// One terminal failure produces exactly one JSON-RPC error carrying this
/// payload and never an assistant `agent_message_chunk`; `message` remains
/// lossless human diagnostics on the JSON-RPC error itself, while this data is
/// the stable machine contract hosts branch on. Fields beyond `terminalClass`
/// are flattened onto the envelope and additive, so the complementary
/// success-path terminal outcome (harn#4834) can later reuse the same
/// `terminalClass`/`reason` spine on the success frame without another breaking
/// change to this shape.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcpPromptErrorData {
    pub schema: AcpPromptErrorSchema,
    pub terminal_class: harn_vm::llm::AgentTerminalClass,
    #[serde(flatten)]
    pub facts: AcpPromptFailureFacts,
}

impl AcpPromptErrorData {
    pub fn new(terminal_class: harn_vm::llm::AgentTerminalClass) -> Self {
        Self::with_facts(terminal_class, AcpPromptFailureFacts::default())
    }

    pub fn with_facts(
        terminal_class: harn_vm::llm::AgentTerminalClass,
        facts: AcpPromptFailureFacts,
    ) -> Self {
        Self {
            schema: AcpPromptErrorSchema::V1,
            terminal_class,
            facts,
        }
    }
}

/// Response envelope for failed ACP JSON-RPC calls.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpJsonRpcErrorResponse {
    pub jsonrpc: String,
    pub id: AcpJsonRpcId,
    pub error: AcpJsonRpcError,
}

/// The environment policy a client declares on `session/new`. Omission means
/// `inherited`. Harn resolves it once into a
/// [`harn_vm::security::SessionEnvironment`].
///
/// The launcher parses its own `--grant name=spec` strings at ITS boundary and
/// sends harn this already-typed, value-free shape; harn does not parse flag
/// strings. Only the `granted` kind accepts grants.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionEnvironmentConfig {
    pub kind: harn_vm::security::EnvironmentPolicyKind,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub grants: Vec<harn_vm::security::GrantSpec>,
}

/// `session/new` params.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionNewParams {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<String>,
    /// The session's environment policy. Omitted means `inherited`. See
    /// [`AcpSessionEnvironmentConfig`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[serde(rename = "environmentPolicy")]
    pub environment_policy: Option<AcpSessionEnvironmentConfig>,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

impl AcpSessionNewParams {
    pub fn cwd(cwd: impl Into<String>) -> Self {
        Self {
            cwd: Some(cwd.into()),
            environment_policy: None,
            extra: BTreeMap::new(),
        }
    }
}

/// `session/new`, `session/load`, and `session/resume` result fields Harn
/// returns for an active ACP session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionRestoreResult {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modes: Option<serde_json::Value>,
    #[serde(
        rename = "configOptions",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub config_options: Option<serde_json::Value>,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// Params containing only an ACP session id.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionIdParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
}

impl AcpSessionIdParams {
    pub fn new(session_id: impl Into<String>) -> Self {
        Self {
            session_id: session_id.into(),
        }
    }
}

/// `session/prompt` params.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionPromptParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    pub prompt: Vec<AcpContentBlock>,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

impl AcpSessionPromptParams {
    pub fn new(session_id: impl Into<String>, prompt: Vec<AcpContentBlock>) -> Self {
        Self {
            session_id: session_id.into(),
            prompt,
            extra: BTreeMap::new(),
        }
    }

    pub fn text(session_id: impl Into<String>, text: impl Into<String>) -> Self {
        Self::new(session_id, vec![AcpContentBlock::text(text)])
    }
}

/// `session/prompt` result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionPromptResult {
    #[serde(rename = "stopReason")]
    pub stop_reason: String,
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<AcpMeta>,
}

/// ACP content blocks accepted by Harn prompt and injection requests.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum AcpContentBlock {
    Text {
        text: String,
    },
    Image {
        #[serde(rename = "mimeType", alias = "media_type")]
        mime_type: String,
        #[serde(default, alias = "base64", skip_serializing_if = "Option::is_none")]
        data: Option<String>,
        #[serde(
            default,
            alias = "url",
            alias = "source_uri",
            skip_serializing_if = "Option::is_none"
        )]
        uri: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detail: Option<String>,
    },
    Audio {
        #[serde(rename = "mimeType", alias = "media_type")]
        mime_type: String,
        #[serde(default, alias = "base64", skip_serializing_if = "Option::is_none")]
        data: Option<String>,
        #[serde(
            default,
            alias = "url",
            alias = "source_uri",
            skip_serializing_if = "Option::is_none"
        )]
        uri: Option<String>,
    },
    Resource {
        resource: AcpEmbeddedResource,
    },
    ResourceLink {
        uri: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(
            rename = "mimeType",
            alias = "media_type",
            default,
            skip_serializing_if = "Option::is_none"
        )]
        mime_type: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        size: Option<u64>,
    },
}

impl AcpContentBlock {
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    pub fn image_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
        Self::Image {
            mime_type: mime_type.into(),
            data: Some(data.into()),
            uri: None,
            detail: None,
        }
    }

    pub fn image_uri(mime_type: impl Into<String>, uri: impl Into<String>) -> Self {
        Self::Image {
            mime_type: mime_type.into(),
            data: None,
            uri: Some(uri.into()),
            detail: None,
        }
    }

    pub fn audio_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
        Self::Audio {
            mime_type: mime_type.into(),
            data: Some(data.into()),
            uri: None,
        }
    }

    pub fn audio_uri(mime_type: impl Into<String>, uri: impl Into<String>) -> Self {
        Self::Audio {
            mime_type: mime_type.into(),
            data: None,
            uri: Some(uri.into()),
        }
    }

    pub fn embedded_text_resource(
        uri: impl Into<String>,
        mime_type: impl Into<String>,
        text: impl Into<String>,
    ) -> Self {
        Self::Resource {
            resource: AcpEmbeddedResource {
                uri: uri.into(),
                mime_type: Some(mime_type.into()),
                text: Some(text.into()),
                blob: None,
            },
        }
    }

    pub fn resource_link(uri: impl Into<String>) -> Self {
        Self::ResourceLink {
            uri: uri.into(),
            name: None,
            title: None,
            description: None,
            mime_type: None,
            size: None,
        }
    }
}

/// Embedded resource payload nested under an ACP `resource` content block.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpEmbeddedResource {
    pub uri: String,
    #[serde(rename = "mimeType", alias = "media_type")]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blob: Option<String>,
}

/// Delivery mode for `session/inject` queued user messages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AcpSessionInjectMode {
    Queue,
    Steer,
    #[serde(alias = "interrupt")]
    InterruptImmediate,
}

/// `session/inject` content accepts either a plain string or ACP content blocks.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum AcpSessionInjectContent {
    Text(String),
    Blocks(Vec<AcpContentBlock>),
}

impl From<String> for AcpSessionInjectContent {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&str> for AcpSessionInjectContent {
    fn from(value: &str) -> Self {
        Self::Text(value.to_string())
    }
}

impl From<Vec<AcpContentBlock>> for AcpSessionInjectContent {
    fn from(value: Vec<AcpContentBlock>) -> Self {
        Self::Blocks(value)
    }
}

/// Standard ACP `_meta` wrapper for Harn-owned extension fields.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpMeta {
    pub harn: AcpHarnMeta,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

impl AcpMeta {
    pub fn actor(actor: serde_json::Value) -> Self {
        Self {
            harn: AcpHarnMeta {
                actor: Some(actor),
                terminal: None,
                extra: BTreeMap::new(),
            },
            extra: BTreeMap::new(),
        }
    }

    pub fn terminal(terminal: harn_vm::agent_events::AgentTerminalOutcome) -> Self {
        Self {
            harn: AcpHarnMeta {
                actor: None,
                terminal: Some(terminal),
                extra: BTreeMap::new(),
            },
            extra: BTreeMap::new(),
        }
    }
}

/// Harn-owned ACP `_meta.harn` extension fields.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpHarnMeta {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actor: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub terminal: Option<harn_vm::agent_events::AgentTerminalOutcome>,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// `session/inject` params.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionInjectParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    pub mode: AcpSessionInjectMode,
    pub content: AcpSessionInjectContent,
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<AcpMeta>,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

/// Harn ACP extension params for injecting a typed, provenance-bearing host event.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcpSessionInjectHostEventParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    pub event: harn_vm::agent_sessions::HostInjectionRequest,
}

impl AcpSessionInjectHostEventParams {
    pub fn new(
        session_id: impl Into<String>,
        event: harn_vm::agent_sessions::HostInjectionRequest,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            event,
        }
    }
}

impl AcpSessionInjectParams {
    pub fn new(
        session_id: impl Into<String>,
        mode: AcpSessionInjectMode,
        content: impl Into<AcpSessionInjectContent>,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            mode,
            content: content.into(),
            meta: None,
            extra: BTreeMap::new(),
        }
    }
}

/// `session/replace_inject` params.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionReplaceInjectParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    #[serde(rename = "messageId")]
    pub message_id: String,
    pub content: AcpSessionInjectContent,
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<AcpMeta>,
    #[serde(flatten, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, serde_json::Value>,
}

impl AcpSessionReplaceInjectParams {
    pub fn new(
        session_id: impl Into<String>,
        message_id: impl Into<String>,
        content: impl Into<AcpSessionInjectContent>,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            message_id: message_id.into(),
            content: content.into(),
            meta: None,
            extra: BTreeMap::new(),
        }
    }
}

/// Params for pending-message operations such as `session/revoke_inject`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionMessageIdParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    #[serde(rename = "messageId")]
    pub message_id: String,
}

impl AcpSessionMessageIdParams {
    pub fn new(session_id: impl Into<String>, message_id: impl Into<String>) -> Self {
        Self {
            session_id: session_id.into(),
            message_id: message_id.into(),
        }
    }
}

/// `session/cancel_tool_call` params.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AcpSessionCancelToolCallParams {
    #[serde(rename = "sessionId")]
    pub session_id: String,
    #[serde(rename = "toolCallId")]
    pub tool_call_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(
        rename = "injectReminder",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub inject_reminder: Option<bool>,
}

impl AcpSessionCancelToolCallParams {
    pub fn new(session_id: impl Into<String>, tool_call_id: impl Into<String>) -> Self {
        Self {
            session_id: session_id.into(),
            tool_call_id: tool_call_id.into(),
            reason: None,
            inject_reminder: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn session_new_environment_policy_uses_the_harn_extension_field() {
        let params = AcpSessionNewParams {
            cwd: Some("/workspace".to_string()),
            environment_policy: Some(AcpSessionEnvironmentConfig {
                kind: harn_vm::security::EnvironmentPolicyKind::Isolated,
                grants: Vec::new(),
            }),
            extra: BTreeMap::new(),
        };
        let value = serde_json::to_value(params).unwrap();
        assert_eq!(value["environmentPolicy"]["kind"], "isolated");
        assert!(value.get("profile").is_none());
    }

    #[test]
    fn session_prompt_request_serializes_to_acp_wire_shape() {
        let value =
            AcpJsonRpcRequest::session_prompt(7, AcpSessionPromptParams::text("sess-1", "hello"))
                .into_json_value()
                .expect("request serializes");

        assert_eq!(
            value,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 7,
                "method": "session/prompt",
                "params": {
                    "sessionId": "sess-1",
                    "prompt": [{"type": "text", "text": "hello"}],
                },
            })
        );
    }

    #[test]
    fn session_prompt_result_round_trips_typed_terminal_truth() {
        let result = AcpSessionPromptResult {
            stop_reason: "max_turn_requests".to_string(),
            meta: Some(AcpMeta::terminal(
                harn_vm::agent_events::AgentTerminalOutcome::new(
                    harn_vm::agent_events::AgentTerminalKind::PolicyBudget,
                    "max_iterations",
                ),
            )),
        };

        let wire = serde_json::to_value(&result).expect("serialize prompt result");
        assert_eq!(
            wire,
            serde_json::json!({
                "stopReason": "max_turn_requests",
                "_meta": {
                    "harn": {
                        "terminal": {
                            "kind": "policy_budget",
                            "reason": "max_iterations",
                            "owner": "policy",
                        },
                    },
                },
            })
        );
        let restored: AcpSessionPromptResult =
            serde_json::from_value(wire).expect("deserialize prompt result");
        assert_eq!(restored, result);
    }

    #[test]
    fn a_failed_turn_carries_its_class_onto_the_prompt_result_wire() {
        // The point of the change: an embedder reading a COMPLETED
        // `session/prompt` whose turn failed can now name the cause, not just
        // the owner. Before this, the class was computed at the finalize
        // boundary and dropped here, so a missing provider credential and a
        // rate limit were indistinguishable on this frame.
        let result = AcpSessionPromptResult {
            stop_reason: "refusal".to_string(),
            meta: Some(AcpMeta::terminal(
                harn_vm::agent_events::AgentTerminalOutcome::new(
                    harn_vm::agent_events::AgentTerminalKind::ProviderError,
                    "exception",
                )
                .with_terminal_class(Some(
                    harn_vm::llm::AgentTerminalClass::ProviderMisconfigured,
                )),
            )),
        };

        let wire = serde_json::to_value(&result).expect("serialize prompt result");
        assert_eq!(
            wire,
            serde_json::json!({
                "stopReason": "refusal",
                "_meta": {
                    "harn": {
                        "terminal": {
                            "kind": "provider_error",
                            "reason": "exception",
                            "owner": "provider",
                            "terminalClass": "provider_misconfigured",
                        },
                    },
                },
            })
        );
        // Same key the failed-prompt frame uses, so one cause is named the same
        // way on either side of the JSON-RPC boundary.
        let error_frame = serde_json::to_value(AcpPromptErrorData::new(
            harn_vm::llm::AgentTerminalClass::ProviderMisconfigured,
        ))
        .expect("serialize prompt error data");
        assert_eq!(
            wire["_meta"]["harn"]["terminal"]["terminalClass"],
            error_frame["terminalClass"]
        );

        let restored: AcpSessionPromptResult =
            serde_json::from_value(wire).expect("deserialize prompt result");
        assert_eq!(restored, result);
    }

    #[test]
    fn a_terminal_without_a_class_keeps_the_bytes_it_already_had() {
        let result = AcpSessionPromptResult {
            stop_reason: "max_turn_requests".to_string(),
            meta: Some(AcpMeta::terminal(
                harn_vm::agent_events::AgentTerminalOutcome::new(
                    harn_vm::agent_events::AgentTerminalKind::PolicyBudget,
                    "max_iterations",
                ),
            )),
        };

        assert_eq!(
            serde_json::to_value(&result).expect("serialize prompt result"),
            serde_json::json!({
                "stopReason": "max_turn_requests",
                "_meta": {
                    "harn": {
                        "terminal": {
                            "kind": "policy_budget",
                            "reason": "max_iterations",
                            "owner": "policy",
                        },
                    },
                },
            }),
            "additive means absent, not null, for every outcome that has no class"
        );
    }

    #[test]
    fn session_prompt_result_preserves_unknown_exception_and_legacy_shape() {
        let unknown: AcpSessionPromptResult = serde_json::from_value(serde_json::json!({
            "stopReason": "end_turn",
            "_meta": {
                "harn": {
                    "terminal": {
                        "kind": "unknown",
                        "reason": "exception",
                        "owner": "unknown",
                    },
                },
            },
        }))
        .expect("deserialize unknown terminal");
        assert_eq!(
            unknown.meta.expect("terminal metadata").harn.terminal,
            Some(harn_vm::agent_events::AgentTerminalOutcome::new(
                harn_vm::agent_events::AgentTerminalKind::Unknown,
                "exception",
            ))
        );

        let legacy: AcpSessionPromptResult =
            serde_json::from_value(serde_json::json!({"stopReason": "end_turn"}))
                .expect("deserialize legacy prompt result");
        assert!(legacy.meta.is_none());
    }

    #[test]
    fn session_inject_request_serializes_mode_and_content() {
        let value = AcpJsonRpcRequest::session_inject(
            "inject-1",
            AcpSessionInjectParams::new(
                "sess-1",
                AcpSessionInjectMode::Steer,
                vec![AcpContentBlock::text("interrupt after this step")],
            ),
        )
        .into_json_value()
        .expect("request serializes");

        assert_eq!(
            value,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": "inject-1",
                "method": "session/inject",
                "params": {
                    "sessionId": "sess-1",
                    "mode": "steer",
                    "content": [{"type": "text", "text": "interrupt after this step"}],
                },
            })
        );
    }

    #[test]
    fn session_inject_interrupt_mode_accepts_the_bridge_alias() {
        let params: AcpSessionInjectParams = serde_json::from_value(serde_json::json!({
            "sessionId": "sess-1",
            "mode": "interrupt",
            "content": "stop before dispatch",
        }))
        .expect("interrupt alias deserializes");

        assert_eq!(params.mode, AcpSessionInjectMode::InterruptImmediate);
        assert_eq!(
            serde_json::to_value(params.mode).expect("mode serializes"),
            serde_json::json!("interrupt_immediate")
        );
        assert_eq!(
            super::super::bridge_mode_for_session_inject(&serde_json::json!({"mode": "interrupt"})),
            Ok("interrupt_immediate")
        );
    }

    #[test]
    fn resource_link_content_serializes_to_acp_wire_shape() {
        let value = serde_json::to_value(AcpContentBlock::resource_link("file:///tmp/report.md"))
            .expect("resource link block serializes");

        assert_eq!(
            value,
            serde_json::json!({
                "type": "resource_link",
                "uri": "file:///tmp/report.md",
            })
        );
    }

    #[test]
    fn prompt_failure_facts_project_the_routed_provider_and_model() {
        let facts = AcpPromptFailureFacts::from_thrown(&serde_json::json!({
            "category": "generic",
            "kind": "transient",
            "reason": "rate_limit",
            "code": "provider_exhausted",
            "message": "429 from the backup route",
            "retry_after_ms": 1200,
            // The route that actually failed after a ladder advance — distinct
            // from any base/requested route the session selected.
            "provider": "backup-provider",
            "model": "escalated-model",
        }));

        assert_eq!(facts.category.as_deref(), Some("generic"));
        assert_eq!(facts.kind.as_deref(), Some("transient"));
        assert_eq!(facts.reason.as_deref(), Some("rate_limit"));
        assert_eq!(facts.code.as_deref(), Some("provider_exhausted"));
        assert_eq!(facts.retryable, Some(true));
        assert_eq!(facts.retry_after_ms, Some(1200));
        assert_eq!(facts.provider.as_deref(), Some("backup-provider"));
        assert_eq!(facts.model.as_deref(), Some("escalated-model"));
    }

    #[test]
    fn prompt_failure_facts_are_empty_for_non_object_throws() {
        let facts = AcpPromptFailureFacts::from_thrown(&serde_json::json!("bare string throw"));
        assert_eq!(facts, AcpPromptFailureFacts::default());
    }

    #[test]
    fn terminal_kind_marks_failure_not_retryable() {
        let facts = AcpPromptFailureFacts::from_thrown(&serde_json::json!({
            "kind": "terminal",
            "reason": "provider_exhausted",
        }));
        assert_eq!(facts.retryable, Some(false));
    }

    #[test]
    fn prompt_failure_facts_project_the_routing_attempt_ledger() {
        // A provider-exhausted routing failure carries the per-route ledger plus
        // the authoritative terminal provider/model. The facts project both, so
        // a host can render the full failover chain.
        let facts = AcpPromptFailureFacts::from_thrown(&serde_json::json!({
            "kind": "terminal",
            "reason": "provider_exhausted",
            "provider": "backup-provider",
            "model": "backup-model",
            "attempts": [
                {
                    "index": 1,
                    "provider": "primary-provider",
                    "model": "primary-model",
                    "status": "failed",
                    "error": {"category": "circuit_open", "reason": "overloaded"},
                },
                {
                    "index": 2,
                    "provider": "backup-provider",
                    "model": "backup-model",
                    "status": "failed",
                    "error": {"category": "timeout", "reason": "deadline"},
                },
            ],
        }));

        assert_eq!(facts.provider.as_deref(), Some("backup-provider"));
        assert!(!facts.route_unknown);
        assert_eq!(facts.attempts.len(), 2);
        assert_eq!(facts.attempts[0].index, 1);
        assert_eq!(
            facts.attempts[0].provider.as_deref(),
            Some("primary-provider")
        );
        assert_eq!(facts.attempts[0].status.as_deref(), Some("failed"));
        assert_eq!(facts.attempts[0].category.as_deref(), Some("circuit_open"));
        assert_eq!(facts.attempts[1].model.as_deref(), Some("backup-model"));
        assert_eq!(facts.attempts[1].reason.as_deref(), Some("deadline"));
    }

    #[test]
    fn composite_failure_projects_route_unknown_with_no_provider() {
        // No single route is responsible: `no_single_route` becomes `routeUnknown`
        // and no provider/model is present or fabricated.
        let facts = AcpPromptFailureFacts::from_thrown(&serde_json::json!({
            "kind": "terminal",
            "reason": "provider_exhausted",
            "no_single_route": true,
            "attempts": [
                {"index": 1, "provider": "primary-provider", "model": "primary-model", "status": "failed"},
                {"index": 2, "provider": "backup-provider", "model": "backup-model", "status": "failed"},
            ],
        }));

        assert!(facts.route_unknown, "composite failure sets routeUnknown");
        assert!(
            facts.provider.is_none(),
            "composite must not carry a provider"
        );
        assert!(facts.model.is_none(), "composite must not carry a model");
        assert_eq!(facts.attempts.len(), 2);
    }

    #[test]
    fn route_unknown_and_attempts_are_omitted_when_absent() {
        // The additive fields must not appear on a plain single-route failure,
        // keeping the envelope byte-identical for existing hosts.
        let facts = AcpPromptFailureFacts::from_thrown(&serde_json::json!({
            "kind": "terminal",
            "reason": "timeout",
            "provider": "acme",
            "model": "acme-large",
        }));
        assert!(facts.attempts.is_empty());
        assert!(!facts.route_unknown);

        let wire = serde_json::to_value(&facts).expect("serialize");
        let object = wire.as_object().expect("facts serialize to an object");
        assert!(!object.contains_key("attempts"));
        assert!(!object.contains_key("routeUnknown"));
    }

    #[test]
    fn prompt_error_data_round_trips_through_the_flattened_envelope() {
        let data = AcpPromptErrorData::with_facts(
            harn_vm::llm::AgentTerminalClass::RateLimited,
            AcpPromptFailureFacts::from_thrown(&serde_json::json!({
                "kind": "transient",
                "reason": "rate_limit",
                "provider": "acme",
                "model": "acme-large",
            })),
        );

        let wire = serde_json::to_value(&data).expect("serialize");
        assert_eq!(
            wire,
            serde_json::json!({
                "schema": ACP_PROMPT_ERROR_DATA_SCHEMA,
                "terminalClass": "rate_limited",
                "kind": "transient",
                "reason": "rate_limit",
                "retryable": true,
                "provider": "acme",
                "model": "acme-large",
            })
        );

        let restored: AcpPromptErrorData = serde_json::from_value(wire).expect("deserialize");
        assert_eq!(restored, data);
    }

    #[test]
    fn minimal_prompt_error_data_omits_absent_facts() {
        let wire = serde_json::to_value(AcpPromptErrorData::new(
            harn_vm::llm::AgentTerminalClass::GenericThrow,
        ))
        .expect("serialize");

        // A bare failure stays byte-for-byte compatible with the pre-enrichment
        // `{schema, terminalClass}` shape so v1 consumers keep parsing.
        assert_eq!(
            wire,
            serde_json::json!({
                "schema": ACP_PROMPT_ERROR_DATA_SCHEMA,
                "terminalClass": "generic_throw",
            })
        );
    }
}