relaycast 4.0.0

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

use crate::agent::AgentClient;
use crate::client::{ClientOptions, HttpClient};
use crate::error::{RelayError, Result};
use crate::types::*;

const SDK_VERSION: &str = env!("CARGO_PKG_VERSION");
const DEFAULT_BASE_URL: &str = "https://gateway.relaycast.dev";
const DEFAULT_ORIGIN_CLIENT: &str = "@relaycast/sdk-rust";

fn strip_hash(channel: &str) -> &str {
    channel.strip_prefix('#').unwrap_or(channel)
}

/// Options for creating a RelayCast client.
#[derive(Debug, Clone)]
pub struct RelayCastOptions {
    /// The API key for authentication.
    pub api_key: String,
    /// The base URL for the API (defaults to https://gateway.relaycast.dev).
    ///
    /// To self-host, run the engine (`relaycast-engine`, default port 8787) and
    /// set this to e.g. `http://localhost:8787`.
    pub base_url: Option<String>,
    /// User-Agent-style identifier for the origin_actor driving requests
    /// (e.g. `"claude-code/2.3 (model=opus-4.8)"`, `"codex"`, `"human"`). Sent as
    /// the `X-Relaycast-Origin-Actor` header so server-side telemetry can attribute
    /// traffic. Invalid values are dropped.
    pub origin_actor: Option<String>,
    /// Agent Relay distinct telemetry id. Sent as
    /// `X-Agent-Relay-Distinct-Id` on HTTP requests; invalid values are dropped.
    pub agent_relay_distinct_id: Option<String>,
}

impl RelayCastOptions {
    /// Create new options with the given API key.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: None,
            origin_actor: None,
            agent_relay_distinct_id: None,
        }
    }

    /// Set a custom base URL.
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Set the origin_actor identifier sent as the `X-Relaycast-Origin-Actor` header.
    pub fn with_origin_actor(mut self, origin_actor: impl Into<String>) -> Self {
        self.origin_actor = Some(origin_actor.into());
        self
    }

    /// Set Agent Relay's distinct telemetry id.
    pub fn with_agent_relay_distinct_id(mut self, id: impl Into<String>) -> Self {
        self.agent_relay_distinct_id = Some(id.into());
        self
    }
}

/// Main client for RelayCast workspace operations.
#[derive(Clone)]
pub struct RelayCast {
    client: HttpClient,
}

impl RelayCast {
    /// Create a new RelayCast client with the given options.
    pub fn new(options: RelayCastOptions) -> Result<Self> {
        if options.api_key.trim().is_empty() {
            return Err(RelayError::InvalidResponse(
                "RelayCast api_key is required".to_string(),
            ));
        }

        let base_url = options
            .base_url
            .unwrap_or_else(|| DEFAULT_BASE_URL.to_string());

        let mut client_options = ClientOptions::new(options.api_key);
        client_options = client_options.with_base_url(base_url);
        if let Some(origin_actor) = options.origin_actor {
            client_options = client_options.with_origin_actor(origin_actor);
        }
        if let Some(id) = options.agent_relay_distinct_id {
            client_options = client_options.with_agent_relay_distinct_id(id);
        }
        let client = HttpClient::new(client_options)?;
        Ok(Self { client })
    }

    /// Create a new workspace.
    pub async fn create_workspace(
        name: &str,
        base_url: Option<&str>,
    ) -> Result<CreateWorkspaceResponse> {
        let url = format!("{}/v1/workspaces", base_url.unwrap_or(DEFAULT_BASE_URL));

        let client = reqwest::Client::new();
        let response = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("X-SDK-Version", SDK_VERSION)
            .header("X-Relaycast-Origin-Client", DEFAULT_ORIGIN_CLIENT)
            .header("X-Relaycast-Origin-Version", SDK_VERSION)
            .json(&serde_json::json!({ "name": name }))
            .send()
            .await?;

        let status = response.status().as_u16();
        let json: ApiResponse<CreateWorkspaceResponse> = response.json().await?;

        if !json.ok {
            let error = json.error.unwrap_or_else(|| ApiErrorInfo {
                code: "unknown_error".to_string(),
                message: "Unknown error".to_string(),
            });
            return Err(RelayError::api(error.code, error.message, status));
        }

        json.data
            .ok_or_else(|| RelayError::InvalidResponse("Response missing data field".to_string()))
    }

    /// Create an agent client for the given agent token.
    pub fn as_agent(&self, agent_token: impl Into<String>) -> Result<AgentClient> {
        let client = self.client.with_api_key(agent_token)?;
        Ok(AgentClient::from_client(client))
    }

    /// Rehydrate an agent client from a persisted agent token, validating it first.
    pub async fn reconnect_agent(&self, agent_token: impl Into<String>) -> Result<AgentClient> {
        let agent = self.as_agent(agent_token)?;
        agent.me().await?;
        Ok(agent)
    }

    // === Workspace ===

    /// Get workspace information.
    pub async fn workspace_info(&self) -> Result<Workspace> {
        self.client.get("/v1/workspace", None, None).await
    }

    /// Update workspace settings.
    pub async fn update_workspace(&self, request: UpdateWorkspaceRequest) -> Result<Workspace> {
        self.client
            .patch("/v1/workspace", Some(request), None)
            .await
    }

    /// Delete the workspace.
    pub async fn delete_workspace(&self) -> Result<()> {
        self.client.delete("/v1/workspace", None).await
    }

    /// Get effective workspace stream configuration.
    pub async fn workspace_stream_get(&self) -> Result<WorkspaceStreamConfig> {
        self.client.get("/v1/workspace/stream", None, None).await
    }

    /// Set workspace stream override.
    pub async fn workspace_stream_set(&self, enabled: bool) -> Result<WorkspaceStreamConfig> {
        self.client
            .put(
                "/v1/workspace/stream",
                Some(serde_json::json!({ "enabled": enabled })),
                None,
            )
            .await
    }

    /// Clear workspace stream override and inherit default behavior.
    pub async fn workspace_stream_inherit(&self) -> Result<WorkspaceStreamConfig> {
        self.client
            .put(
                "/v1/workspace/stream",
                Some(serde_json::json!({ "mode": "inherit" })),
                None,
            )
            .await
    }

    // === System Prompt ===

    /// Get the workspace system prompt.
    pub async fn get_system_prompt(&self) -> Result<SystemPrompt> {
        self.client
            .get("/v1/workspace/system-prompt", None, None)
            .await
    }

    /// Set the workspace system prompt.
    pub async fn set_system_prompt(&self, request: SetSystemPromptRequest) -> Result<SystemPrompt> {
        self.client
            .put("/v1/workspace/system-prompt", Some(request), None)
            .await
    }

    // === Channels ===

    /// List channels in the workspace.
    pub async fn list_channels(&self, include_archived: bool) -> Result<Vec<Channel>> {
        let query = if include_archived {
            Some([("include_archived", "true")].as_slice())
        } else {
            None
        };
        self.client.get("/v1/channels", query, None).await
    }

    /// Get a channel and its members by name.
    pub async fn get_channel(&self, name: &str) -> Result<ChannelWithMembers> {
        self.client
            .get(
                &format!("/v1/channels/{}", urlencoding::encode(name)),
                None,
                None,
            )
            .await
    }

    // === Messages ===

    /// List messages in a channel.
    pub async fn list_messages(
        &self,
        channel: &str,
        opts: Option<MessageListQuery>,
    ) -> Result<Vec<MessageWithMeta>> {
        let name = strip_hash(channel);
        let opts = opts.unwrap_or_default();
        let mut query_params: Vec<(String, String)> = Vec::new();
        if let Some(limit) = opts.limit {
            query_params.push(("limit".to_string(), limit.to_string()));
        }
        if let Some(before) = opts.before {
            query_params.push(("before".to_string(), before));
        }
        if let Some(after) = opts.after {
            query_params.push(("after".to_string(), after));
        }

        let query: Vec<(&str, &str)> = query_params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let query_ref = if query.is_empty() {
            None
        } else {
            Some(query.as_slice())
        };

        self.client
            .get(
                &format!("/v1/channels/{}/messages", urlencoding::encode(name)),
                query_ref,
                None,
            )
            .await
    }

    /// Get a single message by ID.
    pub async fn get_message(&self, id: &str) -> Result<MessageWithMeta> {
        self.client
            .get(
                &format!("/v1/messages/{}", urlencoding::encode(id)),
                None,
                None,
            )
            .await
    }

    /// Get a message thread (parent and replies).
    pub async fn get_thread(
        &self,
        message_id: &str,
        opts: Option<MessageListQuery>,
    ) -> Result<ThreadResponse> {
        let opts = opts.unwrap_or_default();
        let mut query_params: Vec<(String, String)> = Vec::new();
        if let Some(limit) = opts.limit {
            query_params.push(("limit".to_string(), limit.to_string()));
        }
        if let Some(before) = opts.before {
            query_params.push(("before".to_string(), before));
        }
        if let Some(after) = opts.after {
            query_params.push(("after".to_string(), after));
        }

        let query: Vec<(&str, &str)> = query_params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let query_ref = if query.is_empty() {
            None
        } else {
            Some(query.as_slice())
        };

        self.client
            .get(
                &format!("/v1/messages/{}/replies", urlencoding::encode(message_id)),
                query_ref,
                None,
            )
            .await
    }

    /// Get grouped reactions for a message.
    pub async fn get_message_reactions(&self, id: &str) -> Result<Vec<ReactionGroup>> {
        self.client
            .get(
                &format!("/v1/messages/{}/reactions", urlencoding::encode(id)),
                None,
                None,
            )
            .await
    }

    // === Agents ===

    /// Register a new agent.
    pub async fn register_agent(&self, request: CreateAgentRequest) -> Result<CreateAgentResponse> {
        self.client.post("/v1/agents", Some(request), None).await
    }

    /// Resolve an agent token to its authenticated agent identity.
    pub async fn get_current_agent(&self, agent_token: impl Into<String>) -> Result<Agent> {
        self.client
            .with_api_key(agent_token)?
            .get("/v1/agent", None, None)
            .await
    }

    /// List agents.
    pub async fn list_agents(&self, query: Option<AgentListQuery>) -> Result<Vec<Agent>> {
        let query = query.unwrap_or_default();
        let params: Vec<(String, String)> = query
            .status
            .map(|s| vec![("status".to_string(), s)])
            .unwrap_or_default();

        let query_slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let query_ref = if query_slice.is_empty() {
            None
        } else {
            Some(query_slice.as_slice())
        };

        self.client.get("/v1/agents", query_ref, None).await
    }

    /// Get an agent by name.
    pub async fn get_agent(&self, name: &str) -> Result<Agent> {
        self.client
            .get(
                &format!("/v1/agents/{}", urlencoding::encode(name)),
                None,
                None,
            )
            .await
    }

    /// Rotate an agent's token.
    pub async fn rotate_agent_token(&self, name: &str) -> Result<TokenRotateResponse> {
        self.client
            .post(
                &format!("/v1/agents/{}/rotate-token", urlencoding::encode(name)),
                Some(serde_json::json!({})),
                None,
            )
            .await
    }

    /// Update an agent.
    pub async fn update_agent(&self, name: &str, request: UpdateAgentRequest) -> Result<Agent> {
        self.client
            .patch(
                &format!("/v1/agents/{}", urlencoding::encode(name)),
                Some(request),
                None,
            )
            .await
    }

    /// Delete an agent.
    pub async fn delete_agent(&self, name: &str) -> Result<()> {
        self.client
            .delete(&format!("/v1/agents/{}", urlencoding::encode(name)), None)
            .await
    }

    /// Get agent presence information.
    pub async fn agent_presence(&self) -> Result<Vec<AgentPresenceInfo>> {
        self.client.get("/v1/agents/presence", None, None).await
    }

    /// Register an agent or get existing one (with token rotation).
    pub async fn register_or_get_agent(
        &self,
        request: CreateAgentRequest,
    ) -> Result<CreateAgentResponse> {
        match self.register_agent(request.clone()).await {
            Ok(response) => Ok(response),
            Err(RelayError::Api { code, status, .. })
                if code == "agent_already_exists" || status == 409 =>
            {
                let agent = self.get_agent(&request.name).await?;
                let token_response = self.rotate_agent_token(&agent.name).await?;
                let created_at = agent.created_at.or(agent.last_seen).unwrap_or_default();
                Ok(CreateAgentResponse {
                    id: agent.id,
                    name: agent.name,
                    token: token_response.token,
                    status: agent.status,
                    created_at,
                })
            }
            Err(e) => Err(e),
        }
    }

    /// Spawn an agent process (registering if needed).
    pub async fn spawn_agent(&self, request: SpawnAgentRequest) -> Result<SpawnAgentResponse> {
        self.client
            .post("/v1/agents/spawn", Some(request), None)
            .await
    }

    /// Release an agent process (optionally deleting the agent).
    pub async fn release_agent(
        &self,
        request: ReleaseAgentRequest,
    ) -> Result<ReleaseAgentResponse> {
        self.client
            .post("/v1/agents/release", Some(request), None)
            .await
    }

    // === Webhooks ===

    /// Create a webhook.
    pub async fn create_webhook(
        &self,
        request: CreateWebhookRequest,
    ) -> Result<CreateWebhookResponse> {
        self.client.post("/v1/webhooks", Some(request), None).await
    }

    /// Create an inbound webhook.
    pub async fn create_inbound_webhook(
        &self,
        request: CreateWebhookRequest,
    ) -> Result<CreateWebhookResponse> {
        self.create_webhook(request).await
    }

    /// List webhooks.
    pub async fn list_webhooks(&self) -> Result<Vec<Webhook>> {
        self.client.get("/v1/webhooks", None, None).await
    }

    /// Delete a webhook.
    pub async fn delete_webhook(&self, id: &str) -> Result<()> {
        self.client
            .delete(&format!("/v1/webhooks/{}", urlencoding::encode(id)), None)
            .await
    }

    /// Trigger a webhook with its per-webhook bearer token.
    pub async fn trigger_webhook(
        &self,
        webhook_id: &str,
        request: WebhookTriggerRequest,
        token: impl Into<String>,
    ) -> Result<WebhookTriggerResponse> {
        self.client
            .with_api_key(token)?
            .post(
                &format!("/v1/hooks/{}", urlencoding::encode(webhook_id)),
                Some(request),
                None,
            )
            .await
    }

    /// Trigger a webhook with its per-webhook bearer token.
    pub async fn trigger_webhook_with_token(
        &self,
        webhook_id: &str,
        request: WebhookTriggerRequest,
        token: impl Into<String>,
    ) -> Result<WebhookTriggerResponse> {
        self.trigger_webhook(webhook_id, request, token).await
    }

    // === Subscriptions ===

    /// Create an event subscription.
    pub async fn create_subscription(
        &self,
        request: CreateSubscriptionRequest,
    ) -> Result<CreateSubscriptionResponse> {
        self.client
            .post("/v1/subscriptions", Some(request), None)
            .await
    }

    /// List event subscriptions.
    pub async fn list_subscriptions(&self) -> Result<Vec<EventSubscription>> {
        self.client.get("/v1/subscriptions", None, None).await
    }

    /// Get an event subscription.
    pub async fn get_subscription(&self, id: &str) -> Result<EventSubscription> {
        self.client
            .get(
                &format!("/v1/subscriptions/{}", urlencoding::encode(id)),
                None,
                None,
            )
            .await
    }

    /// Delete an event subscription.
    pub async fn delete_subscription(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                &format!("/v1/subscriptions/{}", urlencoding::encode(id)),
                None,
            )
            .await
    }

    // === Actions (agent-to-agent RPC) ===

    /// Register an action (async agent-to-agent RPC). Replaces the legacy command API.
    pub async fn register_action(
        &self,
        request: RegisterActionRequest,
    ) -> Result<ActionDefinition> {
        self.client.post("/v1/actions", Some(request), None).await
    }

    /// List registered actions.
    pub async fn list_actions(&self) -> Result<Vec<ActionDefinition>> {
        self.client.get("/v1/actions", None, None).await
    }

    /// Get a single action by name.
    pub async fn get_action(&self, name: &str) -> Result<ActionDefinition> {
        self.client
            .get(
                &format!("/v1/actions/{}", urlencoding::encode(name)),
                None,
                None,
            )
            .await
    }

    /// Delete an action.
    pub async fn delete_action(&self, name: &str) -> Result<()> {
        self.client
            .delete(&format!("/v1/actions/{}", urlencoding::encode(name)), None)
            .await
    }

    // === Agent session events ===

    /// Emit a session event for an agent (e.g. `status.active`).
    pub async fn emit_agent_event(
        &self,
        name: &str,
        request: EmitSessionEventRequest,
    ) -> Result<SessionEvent> {
        self.client
            .post(
                &format!("/v1/agents/{}/events", urlencoding::encode(name)),
                Some(request),
                None,
            )
            .await
    }

    /// List recorded session events for an agent.
    pub async fn list_agent_events(
        &self,
        name: &str,
        query: Option<ListSessionEventsQuery>,
    ) -> Result<Vec<SessionEvent>> {
        let query = query.unwrap_or_default();
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(event_type) = query.event_type {
            params.push(("type".to_string(), event_type));
        }
        if let Some(limit) = query.limit {
            params.push(("limit".to_string(), limit.to_string()));
        }

        let slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };

        self.client
            .get(
                &format!("/v1/agents/{}/events", urlencoding::encode(name)),
                query_ref,
                None,
            )
            .await
    }

    // === Stats & Activity ===

    /// Get workspace statistics.
    pub async fn stats(&self) -> Result<WorkspaceStats> {
        self.client.get("/v1/console/stats", None, None).await
    }

    /// Get recent activity.
    pub async fn activity(&self, limit: Option<i32>) -> Result<Vec<ActivityItem>> {
        let limit_str = limit.map(|l| l.to_string());
        let query: Vec<(&str, &str)> = limit_str
            .as_ref()
            .map(|l| vec![("limit", l.as_str())])
            .unwrap_or_default();

        let query_ref = if query.is_empty() {
            None
        } else {
            Some(query.as_slice())
        };

        self.client.get("/v1/activity", query_ref, None).await
    }

    /// Get all DM conversations in the workspace.
    pub async fn all_dm_conversations(&self) -> Result<Vec<WorkspaceDmConversation>> {
        self.client
            .get("/v1/dm/conversations/all", None, None)
            .await
    }

    /// Resolve participants for a workspace DM conversation.
    pub async fn dm_conversation_participants(&self, conversation_id: &str) -> Result<Vec<String>> {
        let target = conversation_id.trim();
        if target.is_empty() {
            return Ok(vec![]);
        }

        let conversations = self.all_dm_conversations().await?;
        Ok(conversations
            .into_iter()
            .find(|conversation| conversation.id == target)
            .map(|conversation| conversation.participants)
            .unwrap_or_default())
    }

    /// Get DM messages for a workspace conversation.
    pub async fn dm_messages(
        &self,
        conversation_id: &str,
        opts: Option<MessageListQuery>,
    ) -> Result<Vec<WorkspaceDmMessage>> {
        let opts = opts.unwrap_or_default();
        let mut query_params: Vec<(String, String)> = Vec::new();
        if let Some(limit) = opts.limit {
            query_params.push(("limit".to_string(), limit.to_string()));
        }
        if let Some(before) = opts.before {
            query_params.push(("before".to_string(), before));
        }
        if let Some(after) = opts.after {
            query_params.push(("after".to_string(), after));
        }

        let query: Vec<(&str, &str)> = query_params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        let query_ref = if query.is_empty() {
            None
        } else {
            Some(query.as_slice())
        };

        self.client
            .get(
                &format!(
                    "/v1/dm/conversations/{}/messages",
                    urlencoding::encode(conversation_id)
                ),
                query_ref,
                None,
            )
            .await
    }

    // === Workspace bootstrap ===

    /// Look up a workspace by name. Returns `None` when no workspace matches.
    pub async fn lookup_workspace(
        name: &str,
        base_url: Option<&str>,
    ) -> Result<Option<WorkspaceLookup>> {
        let url = format!(
            "{}/v1/workspaces/by-name/{}",
            base_url.unwrap_or(DEFAULT_BASE_URL),
            urlencoding::encode(name)
        );

        let client = reqwest::Client::new();
        let response = client
            .get(&url)
            .header("Content-Type", "application/json")
            .header("X-SDK-Version", SDK_VERSION)
            .header("X-Relaycast-Origin-Client", DEFAULT_ORIGIN_CLIENT)
            .header("X-Relaycast-Origin-Version", SDK_VERSION)
            .send()
            .await?;

        let status = response.status().as_u16();
        let json: ApiResponse<WorkspaceLookup> = response.json().await?;

        if !json.ok {
            if status == 404 {
                return Ok(None);
            }
            let error = json.error.unwrap_or_else(|| ApiErrorInfo {
                code: "unknown_error".to_string(),
                message: "Unknown error".to_string(),
            });
            return Err(RelayError::api(error.code, error.message, status));
        }

        json.data
            .map(Some)
            .ok_or_else(|| RelayError::InvalidResponse("Response missing data field".to_string()))
    }

    // === A2A (agent-to-agent bridge) ===

    /// Register an A2A agent bridge.
    pub async fn register_a2a(&self, options: RegisterA2aOptions) -> Result<RegisterA2aResponse> {
        self.client
            .post("/v1/a2a/register", Some(options), None)
            .await
    }

    /// List registered A2A agents.
    pub async fn list_a2a_agents(&self) -> Result<Vec<A2aAgentRecord>> {
        self.client.get("/v1/a2a/agents", None, None).await
    }

    /// Remove an A2A agent by name.
    pub async fn remove_a2a_agent(&self, name: &str) -> Result<RemoveA2aAgentResponse> {
        self.client
            .request(
                reqwest::Method::DELETE,
                &format!("/v1/a2a/agents/{}", urlencoding::encode(name)),
                None::<()>,
                None,
                None,
            )
            .await
    }

    /// Fetch the agent card for an A2A agent.
    pub async fn get_a2a_agent_card(&self, name: &str) -> Result<A2aAgentCard> {
        self.client
            .get(
                &format!("/v1/a2a/agents/{}/card", urlencoding::encode(name)),
                None,
                None,
            )
            .await
    }

    // === Routing ===

    /// Route a skill (and optional message) to the best candidate agent.
    pub async fn route(&self, skill: &str, message: Option<&str>) -> Result<RouteResult> {
        self.client
            .post(
                "/v1/route",
                Some(serde_json::json!({ "skill": skill, "message": message })),
                None,
            )
            .await
    }

    /// Report route feedback (success/failure) for a routed agent.
    pub async fn route_feedback(
        &self,
        request: RouteFeedbackRequest,
    ) -> Result<RouteFeedbackResult> {
        self.client
            .post("/v1/route/feedback", Some(request), None)
            .await
    }

    /// Get the workspace routing configuration.
    pub async fn get_routing_config(&self) -> Result<RoutingConfig> {
        self.client.get("/v1/routing/config", None, None).await
    }

    /// Update the workspace routing configuration.
    pub async fn update_routing_config(
        &self,
        request: UpdateRoutingConfigRequest,
    ) -> Result<RoutingConfig> {
        self.client
            .put("/v1/routing/config", Some(request), None)
            .await
    }

    // === Directory ===

    /// Search the agent directory.
    pub async fn search_directory(
        &self,
        query: SearchDirectoryQuery,
    ) -> Result<Vec<DirectorySearchResult>> {
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(q) = query.q {
            params.push(("q".to_string(), q));
        }
        if let Some(tags) = query.tags {
            if !tags.is_empty() {
                params.push(("tags".to_string(), tags.join(",")));
            }
        }
        if let Some(status) = query.status {
            params.push(("status".to_string(), status));
        }
        if let Some(limit) = query.limit {
            params.push(("limit".to_string(), limit.to_string()));
        }

        let slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };

        self.client
            .get("/v1/directory/search", query_ref, None)
            .await
    }

    /// Publish an agent to the directory.
    pub async fn publish_to_directory(
        &self,
        request: PublishToDirectoryRequest,
    ) -> Result<DirectoryAgent> {
        self.client
            .post("/v1/directory/agents", Some(request), None)
            .await
    }

    /// List directory agents.
    pub async fn list_directory(
        &self,
        query: Option<ListDirectoryQuery>,
    ) -> Result<Vec<DirectoryAgent>> {
        let query = query.unwrap_or_default();
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(status) = query.status {
            params.push(("status".to_string(), status));
        }
        if let Some(limit) = query.limit {
            params.push(("limit".to_string(), limit.to_string()));
        }

        let slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };

        self.client
            .get("/v1/directory/agents", query_ref, None)
            .await
    }

    /// Get a directory agent by slug.
    pub async fn get_directory_agent(&self, slug: &str) -> Result<DirectoryAgent> {
        self.client
            .get(
                &format!("/v1/directory/agents/{}", urlencoding::encode(slug)),
                None,
                None,
            )
            .await
    }

    /// Update a directory agent.
    pub async fn update_directory_agent(
        &self,
        slug: &str,
        request: UpdateDirectoryAgentRequest,
    ) -> Result<DirectoryAgent> {
        self.client
            .patch(
                &format!("/v1/directory/agents/{}", urlencoding::encode(slug)),
                Some(request),
                None,
            )
            .await
    }

    /// Delete a directory agent.
    pub async fn delete_directory_agent(&self, slug: &str) -> Result<()> {
        self.client
            .delete(
                &format!("/v1/directory/agents/{}", urlencoding::encode(slug)),
                None,
            )
            .await
    }

    /// List ratings for a directory agent.
    pub async fn list_directory_ratings(&self, slug: &str) -> Result<Vec<DirectoryRating>> {
        self.client
            .get(
                &format!(
                    "/v1/directory/agents/{}/ratings",
                    urlencoding::encode(slug)
                ),
                None,
                None,
            )
            .await
    }

    /// Rate a directory agent.
    pub async fn rate_directory_agent(
        &self,
        slug: &str,
        request: RateDirectoryAgentRequest,
    ) -> Result<DirectoryRating> {
        self.client
            .post(
                &format!(
                    "/v1/directory/agents/{}/ratings",
                    urlencoding::encode(slug)
                ),
                Some(request),
                None,
            )
            .await
    }

    // === Skills ===

    /// Import (sync) skills onto a directory agent.
    pub async fn import_skills(
        &self,
        request: ImportSkillsRequest,
    ) -> Result<Option<DirectoryAgent>> {
        self.client.post("/v1/skills/sync", Some(request), None).await
    }

    /// Search skills across the directory.
    pub async fn search_skills(
        &self,
        query: Option<SkillSearchQuery>,
    ) -> Result<Vec<SkillSearchResult>> {
        let query = query.unwrap_or_default();
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(q) = query.q {
            params.push(("q".to_string(), q));
        }
        if let Some(limit) = query.limit {
            params.push(("limit".to_string(), limit.to_string()));
        }

        let slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };

        self.client.get("/v1/skills/search", query_ref, None).await
    }

    // === Fleet nodes ===

    /// List fleet nodes on the roster.
    pub async fn list_nodes(&self, query: Option<NodeListQuery>) -> Result<Vec<NodeRosterEntry>> {
        let query = query.unwrap_or_default();
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(capability) = query.capability {
            params.push(("capability".to_string(), capability));
        }
        if let Some(name) = query.name {
            params.push(("name".to_string(), name));
        }

        let slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };

        self.client.get("/v1/nodes", query_ref, None).await
    }

    /// Get a fleet node by name.
    pub async fn get_node(&self, name: &str) -> Result<NodeRosterEntry> {
        self.client
            .get(
                &format!("/v1/nodes/{}", urlencoding::encode(name)),
                None,
                None,
            )
            .await
    }

    // === Triggers ===

    /// Create a trigger.
    pub async fn create_trigger(&self, request: CreateTriggerRequest) -> Result<Trigger> {
        self.client.post("/v1/triggers", Some(request), None).await
    }

    /// List triggers.
    pub async fn list_triggers(&self) -> Result<Vec<Trigger>> {
        self.client.get("/v1/triggers", None, None).await
    }

    /// Get a trigger by id.
    pub async fn get_trigger(&self, id: &str) -> Result<Trigger> {
        self.client
            .get(
                &format!("/v1/triggers/{}", urlencoding::encode(id)),
                None,
                None,
            )
            .await
    }

    /// Update a trigger.
    pub async fn update_trigger(
        &self,
        id: &str,
        request: UpdateTriggerRequest,
    ) -> Result<Trigger> {
        self.client
            .patch(
                &format!("/v1/triggers/{}", urlencoding::encode(id)),
                Some(request),
                None,
            )
            .await
    }

    /// Delete a trigger.
    pub async fn delete_trigger(&self, id: &str) -> Result<()> {
        self.client
            .delete(&format!("/v1/triggers/{}", urlencoding::encode(id)), None)
            .await
    }

    // === Certification ===

    /// Submit a certification run for an external agent.
    pub async fn certify(&self, request: SubmitCertificationRequest) -> Result<CertificationRun> {
        self.client.post("/v1/certify", Some(request), None).await
    }

    /// Get a certification run by id.
    pub async fn get_certification(&self, id: &str) -> Result<CertificationRun> {
        self.client
            .get(
                &format!("/v1/certify/{}", urlencoding::encode(id)),
                None,
                None,
            )
            .await
    }

    /// Public badge SVG URL for a certification run (served without an auth header).
    pub fn certification_badge_url(&self, id: &str) -> String {
        format!(
            "{}/v1/certify/{}/badge.svg",
            self.client.base_url().trim_end_matches('/'),
            urlencoding::encode(id)
        )
    }

    /// Enable certification monitoring for an external agent.
    pub async fn monitor_certification(
        &self,
        request: MonitorCertificationRequest,
    ) -> Result<CertificationRun> {
        self.client
            .post("/v1/certify/monitor", Some(request), None)
            .await
    }

    // === Console / observability ===

    /// List console message logs.
    pub async fn console_messages(
        &self,
        query: Option<ConsoleMessagesQuery>,
    ) -> Result<Vec<ConsoleMessageLog>> {
        let query = query.unwrap_or_default();
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(limit) = query.limit {
            params.push(("limit".to_string(), limit.to_string()));
        }
        if let Some(before) = query.before {
            params.push(("before".to_string(), before));
        }
        if let Some(agent_id) = query.agent_id {
            params.push(("agent_id".to_string(), agent_id));
        }
        if let Some(channel_id) = query.channel_id {
            params.push(("channel_id".to_string(), channel_id));
        }
        if let Some(conversation_id) = query.conversation_id {
            params.push(("conversation_id".to_string(), conversation_id));
        }
        if let Some(delivery_kind) = query.delivery_kind {
            params.push(("delivery_kind".to_string(), delivery_kind));
        }

        let slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };

        self.client.get("/v1/console/messages", query_ref, None).await
    }

    /// Get console overview statistics.
    pub async fn console_stats(
        &self,
        query: Option<ConsoleWindowQuery>,
    ) -> Result<ConsoleOverview> {
        let query = query.unwrap_or_default();
        let days = query.days.map(|d| d.to_string());
        let slice: Vec<(&str, &str)> = days
            .as_ref()
            .map(|d| vec![("days", d.as_str())])
            .unwrap_or_default();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };
        self.client.get("/v1/console/stats", query_ref, None).await
    }

    /// List per-agent console statistics.
    pub async fn console_agents(
        &self,
        query: Option<ConsoleAgentStatsQuery>,
    ) -> Result<Vec<ConsoleAgentStat>> {
        let query = query.unwrap_or_default();
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(days) = query.days {
            params.push(("days".to_string(), days.to_string()));
        }
        if let Some(limit) = query.limit {
            params.push(("limit".to_string(), limit.to_string()));
        }

        let slice: Vec<(&str, &str)> = params
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };

        self.client.get("/v1/console/agents", query_ref, None).await
    }

    /// Get console cost statistics.
    pub async fn console_costs(
        &self,
        query: Option<ConsoleWindowQuery>,
    ) -> Result<ConsoleCostStats> {
        let query = query.unwrap_or_default();
        let days = query.days.map(|d| d.to_string());
        let slice: Vec<(&str, &str)> = days
            .as_ref()
            .map(|d| vec![("days", d.as_str())])
            .unwrap_or_default();
        let query_ref = if slice.is_empty() {
            None
        } else {
            Some(slice.as_slice())
        };
        self.client.get("/v1/console/costs", query_ref, None).await
    }
}