gestalt-sdk 0.0.1-alpha.26

Rust SDK scaffolding and generated protocol bindings for Gestalt executable providers
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
// Code generated by sdkgen. DO NOT EDIT.

//! Generated native types and clients for app.proto.

use crate::codec::app::{
    from_wire_get_session_catalog_response, from_wire_invoke_frame, from_wire_operation_result,
    from_wire_provider_metadata, from_wire_resolve_http_subject_response,
    from_wire_start_provider_response, to_wire_app_invoke_graphql_request,
    to_wire_app_invoke_request, to_wire_execute_request, to_wire_get_session_catalog_request,
    to_wire_resolve_http_subject_request, to_wire_start_provider_request,
};
use crate::codec::host_service::{HostServiceChannel, connect_host_service, plain_channel};
use crate::generated::v1;
use crate::invoke_support::{InvokeError, decode_app_result};
use crate::rpc_support::GestaltError;

/// Open enum for `gestalt.provider.v1.ConnectionMode`; unknown numeric values are preserved.
pub type ConnectionMode = i32;

/// ConnectionMode describes which credential sources a provider accepts.
///
/// Named values of `ConnectionMode`.
pub mod connection_mode {
    /// CONNECTION_MODE_UNSPECIFIED.
    pub const CONNECTION_MODE_UNSPECIFIED: i32 = 0;
    /// CONNECTION_MODE_NONE.
    pub const CONNECTION_MODE_NONE: i32 = 1;
    /// CONNECTION_MODE_SUBJECT.
    pub const CONNECTION_MODE_SUBJECT: i32 = 2;
}

/// AccessContext describes the host-side access decision for an operation.
///
/// Native message type for `gestalt.provider.v1.AccessContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccessContext {
    /// The `policy` field.
    pub policy: String,
    /// The `role` field.
    pub role: String,
}

/// Native message type for `gestalt.provider.v1.AgentInvocationContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentInvocationContext {
    /// The `provider_name` field.
    pub provider_name: String,
    /// The `session_id` field.
    pub session_id: String,
    /// The `turn_id` field.
    pub turn_id: String,
}

/// Native message type for `gestalt.provider.v1.AgentToolRef`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentToolRef {
    /// The `app` field.
    pub app: String,
    /// The `operation` field.
    pub operation: String,
    /// The `connection` field.
    pub connection: String,
    /// The `instance` field.
    pub instance: String,
    /// The `title` field.
    pub title: String,
    /// The `description` field.
    pub description: String,
    /// The `credential_mode` field.
    pub credential_mode: String,
    /// The `system` field.
    pub system: String,
    /// The `run_as` field; None when unset.
    pub run_as: Option<SubjectContext>,
}

/// AppInvokeGraphQLRequest invokes the raw GraphQL surface on another plugin
/// through Gestalt.
///
/// Native message type for `gestalt.provider.v1.AppInvokeGraphQLRequest`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppInvokeGraphQLRequest {
    /// The `app` field.
    pub app: String,
    /// The `document` field.
    pub document: String,
    /// The `variables` field; None when unset.
    pub variables: Option<serde_json::Map<String, serde_json::Value>>,
    /// The `connection` field.
    pub connection: String,
    /// The `instance` field.
    pub instance: String,
    /// The `idempotency_key` field.
    pub idempotency_key: String,
    /// The `context` field; None when unset.
    pub context: Option<RequestContext>,
    /// headers overrides outbound static headers declared by the target provider.
    ///
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, String>,
}

/// AppInvokeRequest invokes a declared operation on another app through Gestalt.
///
/// Native message type for `gestalt.provider.v1.AppInvokeRequest`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppInvokeRequest {
    /// The `app` field.
    pub app: String,
    /// The `operation` field.
    pub operation: String,
    /// The `params` field; None when unset.
    pub params: Option<serde_json::Map<String, serde_json::Value>>,
    /// The `connection` field.
    pub connection: String,
    /// The `instance` field.
    pub instance: String,
    /// The `idempotency_key` field.
    pub idempotency_key: String,
    /// The `credential_mode` field.
    pub credential_mode: String,
    /// The `context` field; None when unset.
    pub context: Option<RequestContext>,
    /// The `run_as` field; None when unset.
    pub run_as: Option<SubjectContext>,
    /// headers overrides outbound static headers declared by the target provider.
    ///
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, String>,
}

/// Catalog is the static or request-scoped executable surface exposed by a
/// provider.
///
/// Native message type for `gestalt.provider.v1.Catalog`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Catalog {
    /// The `name` field.
    pub name: String,
    /// The `display_name` field.
    pub display_name: String,
    /// The `description` field.
    pub description: String,
    /// The `icon_svg` field.
    pub icon_svg: String,
    /// The `operations` field.
    pub operations: Vec<CatalogOperation>,
}

/// CatalogOperation is one executable operation exposed by an integration
/// provider.
///
/// Native message type for `gestalt.provider.v1.CatalogOperation`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CatalogOperation {
    /// The `id` field.
    pub id: String,
    /// The `method` field.
    pub method: String,
    /// The `title` field.
    pub title: String,
    /// The `description` field.
    pub description: String,
    /// The `input_schema` field.
    pub input_schema: String,
    /// The `annotations` field; None when unset.
    pub annotations: Option<OperationAnnotations>,
    /// The `parameters` field.
    pub parameters: Vec<CatalogParameter>,
    /// The `required_scopes` field.
    pub required_scopes: Vec<String>,
    /// The `tags` field.
    pub tags: Vec<String>,
    /// The `read_only` field.
    pub read_only: bool,
    /// The `visible` field; None when unset.
    pub visible: Option<bool>,
    /// The `transport` field.
    pub transport: String,
    /// The `allowed_roles` field.
    pub allowed_roles: Vec<String>,
    /// Response mode and schema for this operation. Replaces the former
    /// output_schema string; absent is equivalent to unary with no schema.
    ///
    /// The `response` field; None when unset.
    pub response: Option<OperationResponseSpec>,
}

/// CatalogParameter describes one input parameter surfaced in the generated
/// catalog for an operation.
///
/// Native message type for `gestalt.provider.v1.CatalogParameter`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CatalogParameter {
    /// The `name` field.
    pub name: String,
    /// The `type` field.
    pub r#type: String,
    /// The `description` field.
    pub description: String,
    /// The `required` field.
    pub required: bool,
    /// The `default` field; None when unset.
    pub default: Option<serde_json::Value>,
}

/// ConnectionParamDef describes one provider-defined connection parameter.
///
/// Native message type for `gestalt.provider.v1.ConnectionParamDef`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectionParamDef {
    /// The `required` field.
    pub required: bool,
    /// The `description` field.
    pub description: String,
    /// The `default_value` field.
    pub default_value: String,
    /// The `from` field.
    pub from: String,
    /// The `field` field.
    pub field: String,
}

/// CredentialContext describes the resolved credential used for an operation.
///
/// Native message type for `gestalt.provider.v1.CredentialContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CredentialContext {
    /// The `mode` field.
    pub mode: String,
    /// The `subject_id` field.
    pub subject_id: String,
    /// The `connection` field.
    pub connection: String,
    /// The `instance` field.
    pub instance: String,
}

/// ExecuteRequest invokes one executable operation.
///
/// Native message type for `gestalt.provider.v1.ExecuteRequest`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExecuteRequest {
    /// The `operation` field.
    pub operation: String,
    /// The `params` field; None when unset.
    pub params: Option<serde_json::Map<String, serde_json::Value>>,
    /// The `token` field.
    pub token: String,
    /// The `connection_params` field.
    pub connection_params: std::collections::BTreeMap<String, String>,
    /// The `invocation_id` field.
    pub invocation_id: String,
    /// The `context` field; None when unset.
    pub context: Option<RequestContext>,
    /// The `idempotency_key` field.
    pub idempotency_key: String,
}

/// GetSessionCatalogRequest asks a provider for request-scoped catalog
/// extensions.
///
/// Native message type for `gestalt.provider.v1.GetSessionCatalogRequest`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSessionCatalogRequest {
    /// The `token` field.
    pub token: String,
    /// The `connection_params` field.
    pub connection_params: std::collections::BTreeMap<String, String>,
    /// The `invocation_id` field.
    pub invocation_id: String,
    /// The `context` field; None when unset.
    pub context: Option<RequestContext>,
}

/// GetSessionCatalogResponse returns request-scoped catalog extensions.
///
/// Native message type for `gestalt.provider.v1.GetSessionCatalogResponse`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSessionCatalogResponse {
    /// The `catalog` field; None when unset.
    pub catalog: Option<Catalog>,
}

/// HTTPSubjectRequest carries one verified hosted HTTP request into an optional
/// plugin-local subject resolution hook.
///
/// Native message type for `gestalt.provider.v1.HTTPSubjectRequest`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HTTPSubjectRequest {
    /// The `binding` field.
    pub binding: String,
    /// The `method` field.
    pub method: String,
    /// The `path` field.
    pub path: String,
    /// The `content_type` field.
    pub content_type: String,
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, StringList>,
    /// The `query` field.
    pub query: std::collections::BTreeMap<String, StringList>,
    /// The `params` field; None when unset.
    pub params: Option<serde_json::Map<String, serde_json::Value>>,
    /// The `raw_body` field.
    pub raw_body: Vec<u8>,
    /// The `security_scheme` field.
    pub security_scheme: String,
    /// The `verified_subject` field.
    pub verified_subject: String,
    /// The `verified_claims` field.
    pub verified_claims: std::collections::BTreeMap<String, String>,
}

/// HostContext describes stable public host metadata available to provider code.
///
/// Native message type for `gestalt.provider.v1.HostContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HostContext {
    /// The `public_base_url` field.
    pub public_base_url: String,
}

/// Native message type for `gestalt.provider.v1.InvocationContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InvocationContext {
    /// The `request_id` field.
    pub request_id: String,
    /// The `depth` field.
    pub depth: i32,
    /// The `call_chain` field.
    pub call_chain: Vec<String>,
    /// The `surface` field.
    pub surface: String,
    /// The `internal_connection_access` field.
    pub internal_connection_access: bool,
    /// The `connection` field.
    pub connection: String,
}

/// Values of the `value` oneof in `InvokeFrame`; the message field is None when unset.
#[allow(clippy::enum_variant_names, clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum InvokeFrameValue {
    /// The `metadata` variant.
    Metadata(InvokeMetadata),
    /// The `data` variant.
    Data(Vec<u8>),
}

/// InvokeFrame is one frame in a streaming invocation. The first frame is always
/// metadata; subsequent frames carry data bytes produced by the operation
/// handler (after encoding, for typed item streams). A mid-stream error (for
/// example, a validation failure or a recovered panic) may emit a trailing
/// metadata frame with a non-2xx status followed by a data frame carrying a
/// JSON error body, after which the stream ends.
///
/// Native message type for `gestalt.provider.v1.InvokeFrame`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InvokeFrame {
    /// The `value` oneof; None when unset.
    pub value: Option<InvokeFrameValue>,
}

/// InvokeMetadata is the first frame of a streaming invocation. It carries the
/// HTTP-shaped status, headers, and the response media type (from the
/// operation's StreamResponseSpec).
///
/// Native message type for `gestalt.provider.v1.InvokeMetadata`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InvokeMetadata {
    /// The `status` field.
    pub status: i32,
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, StringList>,
    /// The `media_type` field.
    pub media_type: String,
}

/// OperationAnnotations carries optional host hints about how an operation
/// behaves.
///
/// Native message type for `gestalt.provider.v1.OperationAnnotations`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationAnnotations {
    /// The `read_only_hint` field; None when unset.
    pub read_only_hint: Option<bool>,
    /// The `idempotent_hint` field; None when unset.
    pub idempotent_hint: Option<bool>,
    /// The `destructive_hint` field; None when unset.
    pub destructive_hint: Option<bool>,
    /// The `open_world_hint` field; None when unset.
    pub open_world_hint: Option<bool>,
}

/// Values of the `kind` oneof in `OperationResponseSpec`; the message field is None when unset.
#[allow(clippy::enum_variant_names, clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum OperationResponseSpecKind {
    /// The `unary` variant.
    Unary(UnaryResponseSpec),
    /// The `stream` variant.
    Stream(StreamResponseSpec),
}

/// OperationResponseSpec declares how an operation responds. App authoring
/// defaults to unary; emitted catalogs always declare either unary or stream.
///
/// Native message type for `gestalt.provider.v1.OperationResponseSpec`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationResponseSpec {
    /// The `kind` oneof; None when unset.
    pub kind: Option<OperationResponseSpecKind>,
}

/// OperationResult is the serialized result returned from an Execute call.
///
/// Native message type for `gestalt.provider.v1.OperationResult`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OperationResult {
    /// The `status` field.
    pub status: i32,
    /// The `body` field.
    pub body: Vec<u8>,
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, StringList>,
}

/// ProviderContext identifies the provider process that received the request
/// context from the host and is trusted to propagate it back to host services.
///
/// Native message type for `gestalt.provider.v1.ProviderContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderContext {
    /// The `kind` field.
    pub kind: String,
    /// The `name` field.
    pub name: String,
}

/// ProviderMetadata describes an integration provider's static capabilities.
///
/// Native message type for `gestalt.provider.v1.ProviderMetadata`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderMetadata {
    /// The `name` field.
    pub name: String,
    /// The `display_name` field.
    pub display_name: String,
    /// The `description` field.
    pub description: String,
    /// The `connection_mode` field.
    pub connection_mode: ConnectionMode,
    /// The `auth_types` field.
    pub auth_types: Vec<String>,
    /// The `connection_params` field.
    pub connection_params: std::collections::BTreeMap<String, ConnectionParamDef>,
    /// The `static_catalog` field; None when unset.
    pub static_catalog: Option<Catalog>,
    /// The `supports_session_catalog` field.
    pub supports_session_catalog: bool,
    /// The `min_protocol_version` field.
    pub min_protocol_version: i32,
    /// The `max_protocol_version` field.
    pub max_protocol_version: i32,
    /// Workflow definitions this app declares as desired state. Each entry is a
    /// serialized gestalt.provider.v1.WorkflowDefinitionSpec (workflow.proto).
    /// Framed as bytes because workflow.proto imports app.proto, so this file
    /// cannot reference WorkflowDefinitionSpec directly. The spec `id` is the
    /// app-local id; stored ids look like app_notes_daily-summary (app name + local id)
    /// and are applied with gestaltd authority on the config-definitions reconcile path.
    ///
    /// The `workflow_definition_specs` field.
    pub workflow_definition_specs: Vec<Vec<u8>>,
}

/// RequestContext bundles the caller, credential, access, and host metadata for
/// one operation.
///
/// Native message type for `gestalt.provider.v1.RequestContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestContext {
    /// The `subject` field; None when unset.
    pub subject: Option<SubjectContext>,
    /// The `credential` field; None when unset.
    pub credential: Option<CredentialContext>,
    /// The `access` field; None when unset.
    pub access: Option<AccessContext>,
    /// The `workflow` field; None when unset.
    pub workflow: Option<serde_json::Map<String, serde_json::Value>>,
    /// The `host` field; None when unset.
    pub host: Option<HostContext>,
    /// Original agent caller when an agent tool executes with delegated run-as identity.
    ///
    /// The `agent_subject` field; None when unset.
    pub agent_subject: Option<SubjectContext>,
    /// The `caller` field; None when unset.
    pub caller: Option<ProviderContext>,
    /// The `invocation` field; None when unset.
    pub invocation: Option<InvocationContext>,
    /// Agent tool refs granted to the operation request, when the request is
    /// executing as an agent tool.
    ///
    /// The `tool_refs` field.
    pub tool_refs: Vec<AgentToolRef>,
    /// Preserves the distinction between an omitted tool-ref context and an
    /// explicitly empty inherited tool-ref context.
    ///
    /// The `tool_refs_set` field.
    pub tool_refs_set: bool,
    /// The `request_meta` field; None when unset.
    pub request_meta: Option<RequestMetaContext>,
    /// The `agent` field; None when unset.
    pub agent: Option<AgentInvocationContext>,
}

/// Native message type for `gestalt.provider.v1.RequestMetaContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestMetaContext {
    /// The `client_ip` field.
    pub client_ip: String,
    /// The `remote_addr` field.
    pub remote_addr: String,
    /// The `user_agent` field.
    pub user_agent: String,
}

/// ResolveHTTPSubjectRequest asks a provider to map a verified hosted HTTP
/// request to a concrete Gestalt subject before normal operation authorization
/// and dispatch.
///
/// Native message type for `gestalt.provider.v1.ResolveHTTPSubjectRequest`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveHTTPSubjectRequest {
    /// The `request` field; None when unset.
    pub request: Option<HTTPSubjectRequest>,
    /// The `context` field; None when unset.
    pub context: Option<RequestContext>,
}

/// ResolveHTTPSubjectResponse returns the concrete Gestalt subject a hosted HTTP
/// request should execute as. An unset subject means "fall back to the binding
/// subject". When reject_status is set, the host should reject the inbound
/// request with the provided status and message.
///
/// Native message type for `gestalt.provider.v1.ResolveHTTPSubjectResponse`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolveHTTPSubjectResponse {
    /// The `subject` field; None when unset.
    pub subject: Option<SubjectContext>,
    /// The `reject_status` field.
    pub reject_status: i32,
    /// The `reject_message` field.
    pub reject_message: String,
}

/// StartProviderRequest configures an integration provider for one runtime
/// session.
///
/// Native message type for `gestalt.provider.v1.StartProviderRequest`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartProviderRequest {
    /// The `name` field.
    pub name: String,
    /// The `config` field; None when unset.
    pub config: Option<serde_json::Map<String, serde_json::Value>>,
    /// The `protocol_version` field.
    pub protocol_version: i32,
}

/// StartProviderResponse confirms the protocol version the provider is serving.
///
/// Native message type for `gestalt.provider.v1.StartProviderResponse`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartProviderResponse {
    /// The `protocol_version` field.
    pub protocol_version: i32,
}

/// StreamResponseSpec describes a streaming operation response. The media type
/// names the representation (for example application/x-ndjson); the item schema
/// is optional and describes one yielded item when the stream is typed.
///
/// Native message type for `gestalt.provider.v1.StreamResponseSpec`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StreamResponseSpec {
    /// The `media_type` field.
    pub media_type: String,
    /// The `item_schema` field; None when unset.
    pub item_schema: Option<serde_json::Map<String, serde_json::Value>>,
}

/// StringList is a helper map value for repeated HTTP header and query values.
///
/// Native message type for `gestalt.provider.v1.StringList`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StringList {
    /// The `values` field.
    pub values: Vec<String>,
}

/// SubjectContext identifies the caller that initiated an operation.
///
/// Native message type for `gestalt.provider.v1.SubjectContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubjectContext {
    /// The `id` field.
    pub id: String,
    /// The `email` field.
    pub email: String,
    /// The `display_name` field.
    pub display_name: String,
    /// The `scopes` field.
    pub scopes: Vec<String>,
    /// The `permissions` field.
    pub permissions: Vec<SubjectPermissionContext>,
}

/// Native message type for `gestalt.provider.v1.SubjectPermissionContext`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubjectPermissionContext {
    /// The `app` field.
    pub app: String,
    /// The `operations` field.
    pub operations: Vec<String>,
    /// The `all_operations` field.
    pub all_operations: bool,
}

/// UnaryResponseSpec describes a unary (fully materialized) operation response.
///
/// Native message type for `gestalt.provider.v1.UnaryResponseSpec`.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UnaryResponseSpec {
    /// The `schema` field; None when unset.
    pub schema: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Client for the `gestalt.provider.v1.App` service.
pub struct App {
    inner: v1::app_client::AppClient<HostServiceChannel>,
    timeout: Option<std::time::Duration>,
    context: Option<RequestContext>,
}

impl App {
    /// Creates a client over an established channel.
    pub fn new(channel: tonic::transport::Channel) -> Self {
        Self {
            inner: v1::app_client::AppClient::new(plain_channel(channel)),
            timeout: None,
            context: None,
        }
    }

    /// Sets a deadline applied to every unary call; calls that run past it
    /// fail with DEADLINE_EXCEEDED. Streaming calls are unaffected.
    pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Sets the default request context, injected into outgoing requests
    /// that do not carry one.
    pub fn with_context(mut self, context: RequestContext) -> Self {
        self.context = Some(context);
        self
    }

    /// Connects to the `app` host service described by the environment.
    pub async fn connect() -> Result<Self, GestaltError> {
        Self::connect_named("").await
    }

    /// Connects to the named `app` host-service binding.
    pub async fn connect_named(name: &str) -> Result<Self, GestaltError> {
        Ok(Self {
            inner: v1::app_client::AppClient::new(connect_host_service("app", name).await?),
            timeout: None,
            context: None,
        })
    }

    /// Calls `gestalt.provider.v1.App.Invoke`.
    /// The result decodes with the standard JSON operation envelope
    /// semantics; payload failures surface as [`InvokeError`].
    pub async fn invoke(
        &mut self,
        app: String,
        operation: String,
        params: Option<serde_json::Map<String, serde_json::Value>>,
        options: AppInvokeOptions,
    ) -> Result<serde_json::Value, InvokeError> {
        let request = AppInvokeRequest {
            app,
            operation,
            params,
            connection: options.connection,
            instance: options.instance,
            idempotency_key: options.idempotency_key,
            credential_mode: options.credential_mode,
            run_as: options.run_as,
            headers: options.headers,
            context: self.context.clone(),
        };
        let invoke_context_app = request.app.clone();
        let invoke_context_operation = request.operation.clone();
        let mut tonic_request = tonic::Request::new(to_wire_app_invoke_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = from_wire_operation_result(
            self.inner
                .invoke(tonic_request)
                .await
                .map_err(GestaltError::from)?
                .into_inner(),
        );
        Ok(decode_app_result(
            &invoke_context_app,
            &invoke_context_operation,
            response.status,
            &response.body,
        )?)
    }

    /// Calls `gestalt.provider.v1.App.Invoke` with the full request and response messages.
    pub async fn invoke_raw(
        &mut self,
        request: AppInvokeRequest,
    ) -> Result<OperationResult, GestaltError> {
        let mut request = request;
        if request.context.is_none() {
            request.context = self.context.clone();
        }
        let mut tonic_request = tonic::Request::new(to_wire_app_invoke_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.invoke(tonic_request).await?;
        Ok(from_wire_operation_result(response.into_inner()))
    }

    /// InvokeStream is the streaming counterpart of Invoke. It is gRPC-only (no
    /// REST binding) and shares Invoke's request shape, authorization, and
    /// signature policy. The first response frame is always InvokeMetadata;
    /// subsequent frames carry data bytes from the operation's stream response.
    /// A mid-stream error may emit a trailing metadata frame with an error status
    /// followed by a JSON error body, after which the stream ends.
    ///
    /// Calls `gestalt.provider.v1.App.InvokeStream`, returning a stream of converted frames.
    pub async fn invoke_stream(
        &mut self,
        request: AppInvokeRequest,
    ) -> Result<AppInvokeStreamStream, GestaltError> {
        let mut request = request;
        if request.context.is_none() {
            request.context = self.context.clone();
        }
        let response = self
            .inner
            .invoke_stream(to_wire_app_invoke_request(request))
            .await?;
        Ok(AppInvokeStreamStream {
            inner: response.into_inner(),
        })
    }

    /// Calls `gestalt.provider.v1.App.InvokeGraphQL`.
    pub async fn invoke_graphql(
        &mut self,
        app: String,
        document: String,
        options: AppInvokeGraphQLOptions,
    ) -> Result<OperationResult, GestaltError> {
        let request = AppInvokeGraphQLRequest {
            app,
            document,
            connection: options.connection,
            instance: options.instance,
            idempotency_key: options.idempotency_key,
            variables: options.variables,
            headers: options.headers,
            context: self.context.clone(),
        };
        let mut tonic_request = tonic::Request::new(to_wire_app_invoke_graphql_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.invoke_graph_ql(tonic_request).await?;
        Ok(from_wire_operation_result(response.into_inner()))
    }

    /// Calls `gestalt.provider.v1.App.InvokeGraphQL` with the full request and response messages.
    pub async fn invoke_graphql_raw(
        &mut self,
        request: AppInvokeGraphQLRequest,
    ) -> Result<OperationResult, GestaltError> {
        let mut request = request;
        if request.context.is_none() {
            request.context = self.context.clone();
        }
        let mut tonic_request = tonic::Request::new(to_wire_app_invoke_graphql_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.invoke_graph_ql(tonic_request).await?;
        Ok(from_wire_operation_result(response.into_inner()))
    }
}

/// Optional parameters of [`App::invoke`]; the default value leaves every
/// option unset.
#[derive(Clone, Debug, Default)]
pub struct AppInvokeOptions {
    /// The `connection` field.
    pub connection: String,
    /// The `instance` field.
    pub instance: String,
    /// The `idempotency_key` field.
    pub idempotency_key: String,
    /// The `credential_mode` field.
    pub credential_mode: String,
    /// The `run_as` field; None when unset.
    pub run_as: Option<SubjectContext>,
    /// headers overrides outbound static headers declared by the target provider.
    ///
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, String>,
}

/// Optional parameters of [`App::invoke_stream`]; the default value leaves every
/// option unset.
#[derive(Clone, Debug, Default)]
pub struct AppInvokeStreamOptions {
    /// The `connection` field.
    pub connection: String,
    /// The `instance` field.
    pub instance: String,
    /// The `idempotency_key` field.
    pub idempotency_key: String,
    /// The `credential_mode` field.
    pub credential_mode: String,
    /// The `run_as` field; None when unset.
    pub run_as: Option<SubjectContext>,
    /// headers overrides outbound static headers declared by the target provider.
    ///
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, String>,
}

/// Optional parameters of [`App::invoke_graphql`]; the default value leaves every
/// option unset.
#[derive(Clone, Debug, Default)]
pub struct AppInvokeGraphQLOptions {
    /// The `connection` field.
    pub connection: String,
    /// The `instance` field.
    pub instance: String,
    /// The `idempotency_key` field.
    pub idempotency_key: String,
    /// The `variables` field; None when unset.
    pub variables: Option<serde_json::Map<String, serde_json::Value>>,
    /// headers overrides outbound static headers declared by the target provider.
    ///
    /// The `headers` field.
    pub headers: std::collections::BTreeMap<String, String>,
}

/// InvokeStream is the streaming counterpart of Invoke. It is gRPC-only (no
/// REST binding) and shares Invoke's request shape, authorization, and
/// signature policy. The first response frame is always InvokeMetadata;
/// subsequent frames carry data bytes from the operation's stream response.
/// A mid-stream error may emit a trailing metadata frame with an error status
/// followed by a JSON error body, after which the stream ends.
///
/// Stream of converted `InvokeFrame` frames; transport errors convert to GestaltError.
pub struct AppInvokeStreamStream {
    inner: tonic::Streaming<v1::InvokeFrame>,
}

impl AppInvokeStreamStream {
    /// Receives the next frame, or None when the stream ends.
    pub async fn recv(&mut self) -> Result<Option<InvokeFrame>, GestaltError> {
        Ok(self.inner.message().await?.map(from_wire_invoke_frame))
    }
}

/// AppProvider models the shared Gestalt integration-provider protocol.
///
/// Client for the `gestalt.provider.v1.AppProvider` service.
pub struct AppProvider {
    inner: v1::app_provider_client::AppProviderClient<tonic::transport::Channel>,
    timeout: Option<std::time::Duration>,
    context: Option<RequestContext>,
}

impl AppProvider {
    /// Creates a client over an established channel.
    pub fn new(channel: tonic::transport::Channel) -> Self {
        Self {
            inner: v1::app_provider_client::AppProviderClient::new(channel),
            timeout: None,
            context: None,
        }
    }

    /// Sets a deadline applied to every unary call; calls that run past it
    /// fail with DEADLINE_EXCEEDED. Streaming calls are unaffected.
    pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Sets the default request context, injected into outgoing requests
    /// that do not carry one.
    pub fn with_context(mut self, context: RequestContext) -> Self {
        self.context = Some(context);
        self
    }

    /// Calls `gestalt.provider.v1.AppProvider.GetMetadata`.
    pub async fn get_metadata(&mut self) -> Result<ProviderMetadata, GestaltError> {
        let mut tonic_request = tonic::Request::new(());
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.get_metadata(tonic_request).await?;
        Ok(from_wire_provider_metadata(response.into_inner()))
    }

    /// Calls `gestalt.provider.v1.AppProvider.StartProvider`.
    pub async fn start_provider(
        &mut self,
        name: String,
        protocol_version: i32,
        config: Option<serde_json::Map<String, serde_json::Value>>,
    ) -> Result<StartProviderResponse, GestaltError> {
        let request = StartProviderRequest {
            name,
            protocol_version,
            config,
        };
        let mut tonic_request = tonic::Request::new(to_wire_start_provider_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.start_provider(tonic_request).await?;
        Ok(from_wire_start_provider_response(response.into_inner()))
    }

    /// Calls `gestalt.provider.v1.AppProvider.StartProvider` with the full request and response messages.
    pub async fn start_provider_raw(
        &mut self,
        request: StartProviderRequest,
    ) -> Result<StartProviderResponse, GestaltError> {
        let mut tonic_request = tonic::Request::new(to_wire_start_provider_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.start_provider(tonic_request).await?;
        Ok(from_wire_start_provider_response(response.into_inner()))
    }

    /// Calls `gestalt.provider.v1.AppProvider.Execute`.
    pub async fn execute(
        &mut self,
        operation: String,
        token: String,
        invocation_id: String,
        idempotency_key: String,
        params: Option<serde_json::Map<String, serde_json::Value>>,
    ) -> Result<OperationResult, GestaltError> {
        let request = ExecuteRequest {
            operation,
            token,
            invocation_id,
            idempotency_key,
            params,
            context: self.context.clone(),
            ..Default::default()
        };
        let mut tonic_request = tonic::Request::new(to_wire_execute_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.execute(tonic_request).await?;
        Ok(from_wire_operation_result(response.into_inner()))
    }

    /// Calls `gestalt.provider.v1.AppProvider.Execute` with the full request and response messages.
    pub async fn execute_raw(
        &mut self,
        request: ExecuteRequest,
    ) -> Result<OperationResult, GestaltError> {
        let mut request = request;
        if request.context.is_none() {
            request.context = self.context.clone();
        }
        let mut tonic_request = tonic::Request::new(to_wire_execute_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.execute(tonic_request).await?;
        Ok(from_wire_operation_result(response.into_inner()))
    }

    /// ExecuteStream is the streaming counterpart of Execute. The first response
    /// frame is always InvokeMetadata; subsequent frames carry encoded data bytes.
    /// A mid-stream error may emit a trailing metadata frame with an error status
    /// followed by a JSON error body, after which the stream ends.
    ///
    /// Calls `gestalt.provider.v1.AppProvider.ExecuteStream`, returning a stream of converted frames.
    pub async fn execute_stream(
        &mut self,
        request: ExecuteRequest,
    ) -> Result<AppProviderExecuteStreamStream, GestaltError> {
        let mut request = request;
        if request.context.is_none() {
            request.context = self.context.clone();
        }
        let response = self
            .inner
            .execute_stream(to_wire_execute_request(request))
            .await?;
        Ok(AppProviderExecuteStreamStream {
            inner: response.into_inner(),
        })
    }

    /// Calls `gestalt.provider.v1.AppProvider.ResolveHTTPSubject`.
    pub async fn resolve_http_subject(
        &mut self,
        request: ResolveHTTPSubjectRequest,
    ) -> Result<ResolveHTTPSubjectResponse, GestaltError> {
        let mut request = request;
        if request.context.is_none() {
            request.context = self.context.clone();
        }
        let mut tonic_request = tonic::Request::new(to_wire_resolve_http_subject_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.resolve_http_subject(tonic_request).await?;
        Ok(from_wire_resolve_http_subject_response(
            response.into_inner(),
        ))
    }

    /// Calls `gestalt.provider.v1.AppProvider.GetSessionCatalog`.
    pub async fn get_session_catalog(
        &mut self,
        token: String,
        invocation_id: String,
    ) -> Result<GetSessionCatalogResponse, GestaltError> {
        let request = GetSessionCatalogRequest {
            token,
            invocation_id,
            context: self.context.clone(),
            ..Default::default()
        };
        let mut tonic_request = tonic::Request::new(to_wire_get_session_catalog_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.get_session_catalog(tonic_request).await?;
        Ok(from_wire_get_session_catalog_response(
            response.into_inner(),
        ))
    }

    /// Calls `gestalt.provider.v1.AppProvider.GetSessionCatalog` with the full request and response messages.
    pub async fn get_session_catalog_raw(
        &mut self,
        request: GetSessionCatalogRequest,
    ) -> Result<GetSessionCatalogResponse, GestaltError> {
        let mut request = request;
        if request.context.is_none() {
            request.context = self.context.clone();
        }
        let mut tonic_request = tonic::Request::new(to_wire_get_session_catalog_request(request));
        if let Some(timeout) = self.timeout {
            tonic_request.set_timeout(timeout);
        }
        let response = self.inner.get_session_catalog(tonic_request).await?;
        Ok(from_wire_get_session_catalog_response(
            response.into_inner(),
        ))
    }
}

/// ExecuteStream is the streaming counterpart of Execute. The first response
/// frame is always InvokeMetadata; subsequent frames carry encoded data bytes.
/// A mid-stream error may emit a trailing metadata frame with an error status
/// followed by a JSON error body, after which the stream ends.
///
/// Stream of converted `InvokeFrame` frames; transport errors convert to GestaltError.
pub struct AppProviderExecuteStreamStream {
    inner: tonic::Streaming<v1::InvokeFrame>,
}

impl AppProviderExecuteStreamStream {
    /// Receives the next frame, or None when the stream ends.
    pub async fn recv(&mut self) -> Result<Option<InvokeFrame>, GestaltError> {
        Ok(self.inner.message().await?.map(from_wire_invoke_frame))
    }
}