forked from 0xeb/copilot-sdk-rust
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtypes.rs
More file actions
1608 lines (1437 loc) · 52.8 KB
/
types.rs
File metadata and controls
1608 lines (1437 loc) · 52.8 KB
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
// Copyright (c) 2026 Elias Bachaalany
// SPDX-License-Identifier: MIT
//! Core types for the Copilot SDK.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
fn is_false(value: &bool) -> bool {
!*value
}
// =============================================================================
// Protocol Version
// =============================================================================
/// Maximum protocol version this SDK supports.
/// This must match the version expected by the copilot-agent-runtime server.
pub const SDK_PROTOCOL_VERSION: u32 = 3;
/// Minimum protocol version this SDK can communicate with.
/// Servers reporting a version below this are rejected.
pub const MIN_PROTOCOL_VERSION: u32 = 2;
// =============================================================================
// Enums
// =============================================================================
/// Connection state of the client.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConnectionState {
#[default]
Disconnected,
Connecting,
Connected,
Error,
}
/// System message mode for session configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SystemMessageMode {
Append,
Replace,
}
/// Attachment type for user messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AttachmentType {
File,
Directory,
Selection,
}
/// Log level for the CLI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LogLevel {
None,
Debug,
#[default]
Info,
Warn,
Error,
All,
}
impl std::fmt::Display for LogLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LogLevel::None => write!(f, "none"),
LogLevel::Debug => write!(f, "debug"),
LogLevel::Info => write!(f, "info"),
LogLevel::Warn => write!(f, "warn"),
LogLevel::Error => write!(f, "error"),
LogLevel::All => write!(f, "all"),
}
}
}
// =============================================================================
// Tool Types
// =============================================================================
/// Binary result from a tool execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolBinaryResult {
pub data: String,
pub mime_type: String,
#[serde(rename = "type")]
pub result_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
/// Result object returned from tool execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolResultObject {
pub text_result_for_llm: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub binary_results_for_llm: Option<Vec<ToolBinaryResult>>,
#[serde(default = "default_result_type")]
pub result_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_log: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_telemetry: Option<HashMap<String, serde_json::Value>>,
}
fn default_result_type() -> String {
"success".to_string()
}
impl ToolResultObject {
/// Create a success result with text.
pub fn text(result: impl Into<String>) -> Self {
Self {
text_result_for_llm: result.into(),
binary_results_for_llm: None,
result_type: "success".to_string(),
error: None,
session_log: None,
tool_telemetry: None,
}
}
/// Create an error result.
pub fn error(message: impl Into<String>) -> Self {
Self {
text_result_for_llm: String::new(),
binary_results_for_llm: None,
result_type: "error".to_string(),
error: Some(message.into()),
session_log: None,
tool_telemetry: None,
}
}
}
/// Convenient alias for tool results.
pub type ToolResult = ToolResultObject;
/// Information about a tool invocation from the server.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolInvocation {
pub session_id: String,
pub tool_call_id: String,
pub tool_name: String,
#[serde(default)]
pub arguments: Option<serde_json::Value>,
}
impl ToolInvocation {
/// Get an argument by name, deserializing to the specified type.
pub fn arg<T: serde::de::DeserializeOwned>(&self, name: &str) -> crate::Result<T> {
let args = self
.arguments
.as_ref()
.ok_or_else(|| crate::CopilotError::ToolError("No arguments provided".into()))?;
let value = args
.get(name)
.ok_or_else(|| crate::CopilotError::ToolError(format!("Missing argument: {}", name)))?;
serde_json::from_value(value.clone()).map_err(|e| {
crate::CopilotError::ToolError(format!("Invalid argument '{}': {}", name, e))
})
}
}
// =============================================================================
// Permission Types
// =============================================================================
/// Permission request from the server.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PermissionRequest {
pub kind: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub tool_call_id: Option<String>,
#[serde(flatten)]
pub extension_data: HashMap<String, serde_json::Value>,
}
/// Result of a permission request (response to CLI).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PermissionRequestResult {
pub kind: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub rules: Option<Vec<serde_json::Value>>,
}
impl PermissionRequestResult {
/// Create an approved permission result.
pub fn approved() -> Self {
Self {
kind: "approved".to_string(),
rules: None,
}
}
/// Create a denied permission result.
pub fn denied() -> Self {
Self {
kind: "denied-no-approval-rule-and-could-not-request-from-user".to_string(),
rules: None,
}
}
/// Returns true if the permission was approved.
pub fn is_approved(&self) -> bool {
self.kind == "approved"
}
/// Returns true if the permission was denied.
pub fn is_denied(&self) -> bool {
self.kind.starts_with("denied")
}
}
// =============================================================================
// Configuration Types
// =============================================================================
/// System message configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SystemMessageConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<SystemMessageMode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
}
/// Azure-specific provider options.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AzureOptions {
#[serde(skip_serializing_if = "Option::is_none")]
pub api_version: Option<String>,
}
/// Provider configuration for BYOK (Bring Your Own Key).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderConfig {
pub base_url: String,
#[serde(skip_serializing_if = "Option::is_none", rename = "type")]
pub provider_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub wire_api: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bearer_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub azure: Option<AzureOptions>,
}
// Environment variable names for BYOK configuration
impl ProviderConfig {
/// Environment variable for API key
pub const ENV_API_KEY: &'static str = "COPILOT_SDK_BYOK_API_KEY";
/// Environment variable for base URL
pub const ENV_BASE_URL: &'static str = "COPILOT_SDK_BYOK_BASE_URL";
/// Environment variable for provider type
pub const ENV_PROVIDER_TYPE: &'static str = "COPILOT_SDK_BYOK_PROVIDER_TYPE";
/// Environment variable for model
pub const ENV_MODEL: &'static str = "COPILOT_SDK_BYOK_MODEL";
/// Check if BYOK environment variables are configured.
///
/// Returns true if `COPILOT_SDK_BYOK_API_KEY` is set and non-empty.
pub fn is_env_configured() -> bool {
std::env::var(Self::ENV_API_KEY)
.map(|v| !v.is_empty())
.unwrap_or(false)
}
/// Load ProviderConfig from `COPILOT_SDK_BYOK_*` environment variables.
///
/// Returns `Some(ProviderConfig)` if API key is set, `None` otherwise.
///
/// Environment variables:
/// - `COPILOT_SDK_BYOK_API_KEY` (required): API key for the provider
/// - `COPILOT_SDK_BYOK_BASE_URL` (optional): Base URL (defaults to OpenAI)
/// - `COPILOT_SDK_BYOK_PROVIDER_TYPE` (optional): Provider type (defaults to "openai")
pub fn from_env() -> Option<Self> {
if !Self::is_env_configured() {
return None;
}
let api_key = std::env::var(Self::ENV_API_KEY).ok();
let base_url = std::env::var(Self::ENV_BASE_URL)
.unwrap_or_else(|_| "https://api.openai.com/v1".to_string());
let provider_type = std::env::var(Self::ENV_PROVIDER_TYPE)
.ok()
.or_else(|| Some("openai".to_string()));
Some(Self {
base_url,
provider_type,
api_key,
wire_api: None,
bearer_token: None,
azure: None,
})
}
/// Load model from `COPILOT_SDK_BYOK_MODEL` environment variable.
///
/// Returns `Some(model)` if set and non-empty, `None` otherwise.
pub fn model_from_env() -> Option<String> {
std::env::var(Self::ENV_MODEL)
.ok()
.filter(|v| !v.is_empty())
}
}
// =============================================================================
// MCP Server Configuration
// =============================================================================
/// Configuration for a local/stdio MCP server.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpLocalServerConfig {
pub tools: Vec<String>,
pub command: String,
#[serde(default)]
pub args: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "type")]
pub server_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub env: Option<HashMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cwd: Option<String>,
}
/// Configuration for a remote MCP server (HTTP or SSE).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpRemoteServerConfig {
pub tools: Vec<String>,
pub url: String,
#[serde(default = "default_mcp_type", rename = "type")]
pub server_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub headers: Option<HashMap<String, String>>,
}
fn default_mcp_type() -> String {
"http".to_string()
}
/// MCP server configuration (either local or remote).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum McpServerConfig {
Local(McpLocalServerConfig),
Remote(McpRemoteServerConfig),
}
// =============================================================================
// Custom Agent Configuration
// =============================================================================
/// Configuration for a custom agent.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomAgentConfig {
pub name: String,
pub prompt: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tools: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<HashMap<String, serde_json::Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub infer: Option<bool>,
}
// =============================================================================
// Attachment Types
// =============================================================================
/// Attachment item for user messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserMessageAttachment {
#[serde(rename = "type")]
pub attachment_type: AttachmentType,
pub path: String,
pub display_name: String,
}
// =============================================================================
// Tool Definition (SDK-side)
// =============================================================================
/// Tool definition for registration with a session.
///
/// Use the builder pattern to create tools:
/// ```no_run
/// use copilot_sdk::{Client, SessionConfig, Tool, ToolHandler, ToolResultObject};
/// use std::sync::Arc;
///
/// #[tokio::main]
/// async fn main() -> copilot_sdk::Result<()> {
/// let client = Client::builder().build()?;
/// client.start().await?;
///
/// let tool = Tool::new("get_weather")
/// .description("Get weather for a city")
/// .schema(serde_json::json!({
/// "type": "object",
/// "properties": { "city": { "type": "string" } },
/// "required": ["city"]
/// }));
///
/// let session = client.create_session(SessionConfig {
/// tools: vec![tool.clone()],
/// ..Default::default()
/// }).await?;
///
/// let handler: ToolHandler = Arc::new(|_name, args| {
/// let city = args.get("city").and_then(|v| v.as_str()).unwrap_or("unknown");
/// ToolResultObject::text(format!("Weather in {}: sunny", city))
/// });
/// session.register_tool_with_handler(tool, Some(handler)).await;
/// client.stop().await;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Tool {
pub name: String,
pub description: String,
pub parameters_schema: serde_json::Value,
// Handler is stored separately in Session since it's not Clone-friendly
}
impl Tool {
/// Create a new tool with the given name.
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
description: String::new(),
parameters_schema: serde_json::json!({}),
}
}
/// Set the tool description.
pub fn description(mut self, desc: impl Into<String>) -> Self {
self.description = desc.into();
self
}
/// Set the parameters JSON schema.
pub fn schema(mut self, schema: serde_json::Value) -> Self {
self.parameters_schema = schema;
self
}
/// Add a parameter to the tool's JSON schema.
///
/// Builds the schema incrementally using the builder pattern.
pub fn parameter(
mut self,
name: impl Into<String>,
param_type: impl Into<String>,
description: impl Into<String>,
required: bool,
) -> Self {
let name = name.into();
// Ensure schema has the right shape
if self.parameters_schema.get("type").is_none() {
self.parameters_schema["type"] = serde_json::json!("object");
}
if self.parameters_schema.get("properties").is_none() {
self.parameters_schema["properties"] = serde_json::json!({});
}
self.parameters_schema["properties"][&name] = serde_json::json!({
"type": param_type.into(),
"description": description.into(),
});
if required {
if self.parameters_schema.get("required").is_none() {
self.parameters_schema["required"] = serde_json::json!([]);
}
if let Some(arr) = self.parameters_schema["required"].as_array_mut() {
arr.push(serde_json::json!(name));
}
}
self
}
/// Derive the parameters JSON schema from a Rust type (requires the `schemars` feature).
#[cfg(feature = "schemars")]
pub fn typed_schema<T: schemars::JsonSchema>(mut self) -> Self {
let schema = schemars::schema_for!(T);
match serde_json::to_value(&schema) {
Ok(value) => self.parameters_schema = value,
Err(err) => {
tracing::warn!("Failed to serialize schemars schema: {err}");
self.parameters_schema = serde_json::json!({});
}
}
self
}
}
impl std::fmt::Debug for Tool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Tool")
.field("name", &self.name)
.field("description", &self.description)
.finish()
}
}
// Serialization for sending tool definitions to the CLI
impl Serialize for Tool {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("Tool", 3)?;
state.serialize_field("name", &self.name)?;
state.serialize_field("description", &self.description)?;
state.serialize_field("parametersSchema", &self.parameters_schema)?;
state.end()
}
}
// =============================================================================
// Infinite Session Configuration
// =============================================================================
/// Configuration for infinite sessions (automatic context compaction).
///
/// When enabled, the SDK will automatically manage conversation context to prevent
/// buffer exhaustion. Thresholds are expressed as fractions (0.0 to 1.0).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InfiniteSessionConfig {
/// Enable infinite sessions.
#[serde(skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
/// Threshold for background compaction (0.0 to 1.0).
#[serde(skip_serializing_if = "Option::is_none")]
pub background_compaction_threshold: Option<f64>,
/// Threshold for buffer exhaustion handling (0.0 to 1.0).
#[serde(skip_serializing_if = "Option::is_none")]
pub buffer_exhaustion_threshold: Option<f64>,
}
impl InfiniteSessionConfig {
/// Create an enabled infinite session config with default thresholds.
pub fn enabled() -> Self {
Self {
enabled: Some(true),
background_compaction_threshold: None,
buffer_exhaustion_threshold: None,
}
}
/// Create an infinite session config with custom thresholds.
pub fn with_thresholds(background: f64, exhaustion: f64) -> Self {
Self {
enabled: Some(true),
background_compaction_threshold: Some(background),
buffer_exhaustion_threshold: Some(exhaustion),
}
}
}
// =============================================================================
// Session Hooks
// =============================================================================
/// Input for the pre-tool-use hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreToolUseHookInput {
pub timestamp: i64,
pub cwd: String,
pub tool_name: String,
pub tool_args: serde_json::Value,
}
/// Output for the pre-tool-use hook.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreToolUseHookOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub permission_decision: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub permission_decision_reason: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub modified_args: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_context: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub suppress_output: Option<bool>,
}
/// Input for the post-tool-use hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PostToolUseHookInput {
pub timestamp: i64,
pub cwd: String,
pub tool_name: String,
pub tool_args: serde_json::Value,
pub tool_result: serde_json::Value,
}
/// Output for the post-tool-use hook.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PostToolUseHookOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub modified_result: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_context: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub suppress_output: Option<bool>,
}
/// Input for the user-prompt-submitted hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserPromptSubmittedHookInput {
pub timestamp: i64,
pub cwd: String,
pub prompt: String,
}
/// Output for the user-prompt-submitted hook.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserPromptSubmittedHookOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub modified_prompt: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_context: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub suppress_output: Option<bool>,
}
/// Input for the session-start hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionStartHookInput {
pub timestamp: i64,
pub cwd: String,
pub source: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub initial_prompt: Option<String>,
}
/// Output for the session-start hook.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionStartHookOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_context: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub modified_config: Option<serde_json::Value>,
}
/// Input for the session-end hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionEndHookInput {
pub timestamp: i64,
pub cwd: String,
pub reason: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub final_message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
/// Output for the session-end hook.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionEndHookOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub suppress_output: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cleanup_actions: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_summary: Option<String>,
}
/// Input for the error-occurred hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorOccurredHookInput {
pub timestamp: i64,
pub cwd: String,
pub error: String,
pub error_context: String,
pub recoverable: bool,
}
/// Output for the error-occurred hook.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorOccurredHookOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub suppress_output: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_handling: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub retry_count: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub user_notification: Option<String>,
}
/// Handler types for session hooks.
pub type PreToolUseHandler = Arc<dyn Fn(PreToolUseHookInput) -> PreToolUseHookOutput + Send + Sync>;
pub type PostToolUseHandler =
Arc<dyn Fn(PostToolUseHookInput) -> PostToolUseHookOutput + Send + Sync>;
pub type UserPromptSubmittedHandler =
Arc<dyn Fn(UserPromptSubmittedHookInput) -> UserPromptSubmittedHookOutput + Send + Sync>;
pub type SessionStartHandler =
Arc<dyn Fn(SessionStartHookInput) -> SessionStartHookOutput + Send + Sync>;
pub type SessionEndHandler = Arc<dyn Fn(SessionEndHookInput) -> SessionEndHookOutput + Send + Sync>;
pub type ErrorOccurredHandler =
Arc<dyn Fn(ErrorOccurredHookInput) -> ErrorOccurredHookOutput + Send + Sync>;
/// Configuration for session hooks.
///
/// Hooks allow intercepting and modifying behavior at key points in the session lifecycle.
#[derive(Clone, Default)]
pub struct SessionHooks {
pub on_pre_tool_use: Option<PreToolUseHandler>,
pub on_post_tool_use: Option<PostToolUseHandler>,
pub on_user_prompt_submitted: Option<UserPromptSubmittedHandler>,
pub on_session_start: Option<SessionStartHandler>,
pub on_session_end: Option<SessionEndHandler>,
pub on_error_occurred: Option<ErrorOccurredHandler>,
}
impl SessionHooks {
/// Returns true if any hook handler is registered.
pub fn has_any(&self) -> bool {
self.on_pre_tool_use.is_some()
|| self.on_post_tool_use.is_some()
|| self.on_user_prompt_submitted.is_some()
|| self.on_session_start.is_some()
|| self.on_session_end.is_some()
|| self.on_error_occurred.is_some()
}
}
impl std::fmt::Debug for SessionHooks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionHooks")
.field("on_pre_tool_use", &self.on_pre_tool_use.is_some())
.field("on_post_tool_use", &self.on_post_tool_use.is_some())
.field(
"on_user_prompt_submitted",
&self.on_user_prompt_submitted.is_some(),
)
.field("on_session_start", &self.on_session_start.is_some())
.field("on_session_end", &self.on_session_end.is_some())
.field("on_error_occurred", &self.on_error_occurred.is_some())
.finish()
}
}
// =============================================================================
// Session Configuration
// =============================================================================
/// Configuration for creating a new session.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub config_dir: Option<PathBuf>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<Tool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub system_message: Option<SystemMessageConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub available_tools: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub excluded_tools: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provider: Option<ProviderConfig>,
#[serde(default, skip_serializing_if = "is_false")]
pub streaming: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<HashMap<String, serde_json::Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub custom_agents: Option<Vec<CustomAgentConfig>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub skill_directories: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled_skills: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none", rename = "requestPermission")]
pub request_permission: Option<bool>,
/// Infinite session configuration for automatic context compaction.
#[serde(skip_serializing_if = "Option::is_none")]
pub infinite_sessions: Option<InfiniteSessionConfig>,
/// Whether to request user input forwarding from the server.
/// When true, `userInput.request` callbacks will be sent to the SDK.
#[serde(skip_serializing_if = "Option::is_none", rename = "requestUserInput")]
pub request_user_input: Option<bool>,
/// Reasoning effort level: "low", "medium", "high", or "xhigh".
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning_effort: Option<String>,
/// Working directory for the session.
#[serde(skip_serializing_if = "Option::is_none")]
pub working_directory: Option<String>,
/// Session hooks for pre/post tool use, session lifecycle, etc.
#[serde(skip)]
pub hooks: Option<SessionHooks>,
/// If true and provider/model not explicitly set, load from `COPILOT_SDK_BYOK_*` env vars.
///
/// Default: false (explicit configuration preferred over environment variables)
#[serde(skip)]
pub auto_byok_from_env: bool,
}
/// Configuration for resuming an existing session.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResumeSessionConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub tools: Vec<Tool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provider: Option<ProviderConfig>,
#[serde(default, skip_serializing_if = "is_false")]
pub streaming: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<HashMap<String, serde_json::Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub custom_agents: Option<Vec<CustomAgentConfig>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub skill_directories: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled_skills: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none", rename = "requestPermission")]
pub request_permission: Option<bool>,
/// Whether to request user input forwarding from the server.
#[serde(skip_serializing_if = "Option::is_none", rename = "requestUserInput")]
pub request_user_input: Option<bool>,
/// Reasoning effort level: "low", "medium", "high", or "xhigh".
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning_effort: Option<String>,
/// Working directory for the session.
#[serde(skip_serializing_if = "Option::is_none")]
pub working_directory: Option<String>,
/// If true, skip resuming and create a new session instead.
#[serde(default, skip_serializing_if = "is_false")]
pub disable_resume: bool,
/// Infinite session configuration for resumed sessions
#[serde(skip_serializing_if = "Option::is_none")]
pub infinite_sessions: Option<InfiniteSessionConfig>,
/// Session hooks for pre/post tool use, session lifecycle, etc.
#[serde(skip)]
pub hooks: Option<SessionHooks>,
/// If true and provider not explicitly set, load from `COPILOT_SDK_BYOK_*` env vars.
///
/// Default: false (explicit configuration preferred over environment variables)
#[serde(skip)]
pub auto_byok_from_env: bool,
}
/// Options for sending a message.
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MessageOptions {
pub prompt: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub attachments: Option<Vec<UserMessageAttachment>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
}
impl From<&str> for MessageOptions {
fn from(prompt: &str) -> Self {
Self {
prompt: prompt.to_string(),
attachments: None,
mode: None,
}
}
}
impl From<String> for MessageOptions {
fn from(prompt: String) -> Self {
Self {
prompt,
attachments: None,
mode: None,
}
}
}
// =============================================================================
// Client Options
// =============================================================================
/// Options for creating a CopilotClient.
#[derive(Debug, Clone)]
pub struct ClientOptions {
pub cli_path: Option<PathBuf>,
pub cli_args: Option<Vec<String>>,
pub cwd: Option<PathBuf>,
pub port: u16,
pub use_stdio: bool,
pub cli_url: Option<String>,
pub log_level: LogLevel,
pub auto_start: bool,
pub auto_restart: bool,
pub environment: Option<HashMap<String, String>>,
/// GitHub personal access token for authentication.
/// Cannot be used together with `cli_url`.
pub github_token: Option<String>,
/// Whether to use the logged-in user for auth.
/// Defaults to true when github_token is empty. Cannot be used with `cli_url`.
pub use_logged_in_user: Option<bool>,
/// Tool specifications to deny (passed as `--deny-tool` arguments to the CLI).
///
/// Each entry follows the CLI's tool specification format:
/// - `"shell(git push)"` — deny a specific shell command
/// - `"shell(git)"` — deny all git commands
/// - `"shell(rm)"` — deny rm commands
/// - `"shell"` — deny all shell commands
/// - `"write"` — deny file write operations
/// - `"MCP_SERVER(tool_name)"` — deny a specific MCP tool
///
/// `--deny-tool` takes precedence over `--allow-tool` and `--allow-all-tools`.
pub deny_tools: Option<Vec<String>>,
/// Tool specifications to allow without manual approval
/// (passed as `--allow-tool` arguments to the CLI).
///
/// Each entry follows the same format as `deny_tools`.
pub allow_tools: Option<Vec<String>>,
/// If true, passes `--allow-all-tools` to the CLI.
///
/// This allows Copilot to use any tool without asking for approval.
/// Use `deny_tools` in combination to create an allowlist with exceptions.
pub allow_all_tools: bool,
}
impl Default for ClientOptions {
fn default() -> Self {
Self {
cli_path: None,
cli_args: None,