-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathtypes.rs
More file actions
5447 lines (5007 loc) · 212 KB
/
Copy pathtypes.rs
File metadata and controls
5447 lines (5007 loc) · 212 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
//! Protocol types shared between the SDK and the GitHub Copilot CLI.
//!
//! These types map directly to the JSON-RPC request/response payloads
//! defined by the GitHub Copilot CLI protocol. They are used for session
//! configuration, event handling, tool invocations, and model queries.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::canvas::{CanvasDeclaration, CanvasHandler};
use crate::generated::api_types::OpenCanvasInstance;
/// Context window tier for models that support tiered context windows.
pub use crate::generated::session_events::ContextTier;
use crate::generated::session_events::ReasoningSummary;
use crate::handler::{
AutoModeSwitchHandler, ElicitationHandler, ExitPlanModeHandler, PermissionHandler,
UserInputHandler,
};
use crate::hooks::SessionHooks;
pub use crate::session_fs::{
DirEntry, DirEntryKind, FileInfo, FsError, SessionFsCapabilities, SessionFsConfig,
SessionFsConventions, SessionFsProvider, SessionFsSqliteProvider, SessionFsSqliteQueryResult,
SessionFsSqliteQueryType,
};
pub use crate::trace_context::{TraceContext, TraceContextProvider};
use crate::transforms::SystemMessageTransform;
/// Lifecycle state of a [`Client`](crate::Client) connection. Internal —
/// not part of the public API.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(dead_code)]
#[non_exhaustive]
pub(crate) enum ConnectionState {
/// No CLI process is attached or the process has exited cleanly.
Disconnected,
/// The client is starting up (spawning the CLI, negotiating protocol).
Connecting,
/// The client is connected and ready to handle RPC traffic.
Connected,
/// Startup failed or the connection encountered an unrecoverable error.
Error,
}
/// Type of [`SessionLifecycleEvent`] received via [`Client::subscribe_lifecycle`](crate::Client::subscribe_lifecycle).
///
/// Values serialize as the dotted JSON strings the CLI sends (e.g.
/// `"session.created"`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SessionLifecycleEventType {
/// A new session was created.
#[serde(rename = "session.created")]
Created,
/// A session was deleted.
#[serde(rename = "session.deleted")]
Deleted,
/// A session's metadata was updated (e.g. summary regenerated).
#[serde(rename = "session.updated")]
Updated,
/// A session moved into the foreground.
#[serde(rename = "session.foreground")]
Foreground,
/// A session moved into the background.
#[serde(rename = "session.background")]
Background,
}
/// Optional metadata attached to a [`SessionLifecycleEvent`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionLifecycleEventMetadata {
/// ISO-8601 timestamp the session was created.
#[serde(rename = "startTime")]
pub start_time: String,
/// ISO-8601 timestamp the session was last modified.
#[serde(rename = "modifiedTime")]
pub modified_time: String,
/// Optional generated summary of the session conversation so far.
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<String>,
}
/// A `session.lifecycle` notification dispatched to subscribers obtained via
/// [`Client::subscribe_lifecycle`](crate::Client::subscribe_lifecycle).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionLifecycleEvent {
/// The kind of lifecycle change this event represents.
#[serde(rename = "type")]
pub event_type: SessionLifecycleEventType,
/// Identifier of the session this event refers to.
#[serde(rename = "sessionId")]
pub session_id: SessionId,
/// Optional metadata describing the session at the time of the event.
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<SessionLifecycleEventMetadata>,
}
/// Opaque session identifier assigned by the CLI.
///
/// A newtype wrapper around `String` that provides type safety — prevents
/// accidentally passing a workspace ID or request ID where a session ID
/// is expected. Derefs to `str` for zero-friction borrowing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionId(String);
impl SessionId {
/// Create a new session ID from any string-like value.
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
/// Borrow the inner string.
pub fn as_str(&self) -> &str {
&self.0
}
/// Consume the wrapper, returning the inner string.
pub fn into_inner(self) -> String {
self.0
}
}
impl std::ops::Deref for SessionId {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for SessionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for SessionId {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for SessionId {
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
impl AsRef<str> for SessionId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for SessionId {
fn borrow(&self) -> &str {
&self.0
}
}
impl From<SessionId> for String {
fn from(id: SessionId) -> String {
id.0
}
}
impl PartialEq<str> for SessionId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<String> for SessionId {
fn eq(&self, other: &String) -> bool {
&self.0 == other
}
}
impl PartialEq<SessionId> for String {
fn eq(&self, other: &SessionId) -> bool {
self == &other.0
}
}
impl PartialEq<&str> for SessionId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
impl PartialEq<&SessionId> for SessionId {
fn eq(&self, other: &&SessionId) -> bool {
self.0 == other.0
}
}
impl PartialEq<SessionId> for &SessionId {
fn eq(&self, other: &SessionId) -> bool {
self.0 == other.0
}
}
/// Opaque request identifier for pending CLI requests (permission, user-input, etc.).
///
/// A newtype wrapper around `String` that provides type safety — prevents
/// accidentally passing a session ID or workspace ID where a request ID
/// is expected. Derefs to `str` for zero-friction borrowing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RequestId(String);
impl RequestId {
/// Create a new request ID from any string-like value.
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
/// Consume the wrapper, returning the inner string.
pub fn into_inner(self) -> String {
self.0
}
}
impl std::ops::Deref for RequestId {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for RequestId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for RequestId {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for RequestId {
fn from(s: &str) -> Self {
Self(s.to_owned())
}
}
impl AsRef<str> for RequestId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for RequestId {
fn borrow(&self) -> &str {
&self.0
}
}
impl From<RequestId> for String {
fn from(id: RequestId) -> String {
id.0
}
}
impl PartialEq<str> for RequestId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<String> for RequestId {
fn eq(&self, other: &String) -> bool {
&self.0 == other
}
}
impl PartialEq<RequestId> for String {
fn eq(&self, other: &RequestId) -> bool {
self == &other.0
}
}
impl PartialEq<&str> for RequestId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
/// A tool that the client exposes to the Copilot agent.
///
/// Sent to the CLI as part of [`SessionConfig::tools`] / [`ResumeSessionConfig::tools`]
/// at session creation/resume time. The Rust SDK hand-authors this struct
/// (rather than using the schema-generated form) so it can carry runtime
/// hints — `overrides_built_in_tool`, `skip_permission` — that don't appear
/// in the wire schema but are honored by the CLI.
///
/// A `Tool` may optionally carry a [`handler`](Self::handler): an
/// `Arc<dyn ToolHandler>` that implements the tool's runtime behavior.
/// When present, the SDK dispatches matching `external_tool.requested`
/// broadcasts to it automatically. When absent (`None`), the tool is
/// declaration-only — another connected client must service incoming
/// invocations.
#[derive(Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Tool {
/// Tool identifier (e.g., `"bash"`, `"grep"`, `"str_replace_editor"`).
pub name: String,
/// Optional namespaced name for declarative filtering (e.g., `"playwright/navigate"`
/// for MCP tools).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespaced_name: Option<String>,
/// Description of what the tool does.
#[serde(default)]
pub description: String,
/// Optional instructions for how to use this tool effectively.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
/// JSON Schema for the tool's input parameters.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub parameters: HashMap<String, Value>,
/// When `true`, this tool replaces a built-in tool of the same name
/// (e.g. supplying a custom `grep` that the agent uses in place of the
/// CLI's built-in implementation).
#[serde(default, skip_serializing_if = "is_false")]
pub overrides_built_in_tool: bool,
/// When `true`, the CLI does not request permission before invoking
/// this tool. Use with caution — the tool is responsible for any
/// access control.
#[serde(default, skip_serializing_if = "is_false")]
pub skip_permission: bool,
/// Optional runtime implementation. When `Some`, the SDK dispatches
/// matching `external_tool.requested` broadcasts to this handler.
/// When `None`, the tool is declaration-only.
///
/// Skipped during serialization — the handler is runtime behavior,
/// not part of the wire representation.
///
/// Crate-private to enforce builder semantics: external callers must
/// install a handler through [`Tool::with_handler`] and inspect via
/// [`Tool::handler`], so an already-attached handler cannot be
/// silently overwritten by direct field assignment.
#[serde(skip)]
pub(crate) handler: Option<Arc<dyn crate::tool::ToolHandler>>,
}
#[inline]
fn is_false(b: &bool) -> bool {
!*b
}
impl Tool {
/// Construct a new [`Tool`] with the given name and otherwise default
/// values. The struct is `#[non_exhaustive]`, so external callers
/// cannot use struct-literal syntax — use this builder or
/// [`Default::default`] plus mut-let.
///
/// # Example
///
/// ```
/// # use github_copilot_sdk::types::Tool;
/// # use serde_json::json;
/// let tool = Tool::new("greet")
/// .with_description("Say hello to a user")
/// .with_parameters(json!({
/// "type": "object",
/// "properties": { "name": { "type": "string" } },
/// "required": ["name"]
/// }));
/// # let _ = tool;
/// ```
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
/// Set the namespaced name for declarative filtering (e.g.
/// `"playwright/navigate"` for MCP tools).
pub fn with_namespaced_name(mut self, namespaced_name: impl Into<String>) -> Self {
self.namespaced_name = Some(namespaced_name.into());
self
}
/// Set the human-readable description of what the tool does.
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = description.into();
self
}
/// Set optional instructions for how to use this tool effectively.
pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
/// Set the JSON Schema for the tool's input parameters.
///
/// Accepts a JSON Schema as a `serde_json::Value`, typically built with
/// `serde_json::json!({...})` or returned by `schema_for` (available
/// with the `derive` feature). Tool parameter schemas are always
/// top-level JSON objects (`{"type": "object", ...}`).
///
/// # Panics
///
/// Panics if `parameters` is not a JSON object. Use
/// [`crate::tool::try_tool_parameters`] and assign to
/// [`Tool::parameters`] directly when the schema comes from dynamic
/// input and should produce a recoverable error instead.
pub fn with_parameters(mut self, parameters: Value) -> Self {
self.parameters = crate::tool::tool_parameters(parameters);
self
}
/// Mark this tool as overriding a built-in tool of the same name.
/// E.g. supplying a custom `grep` that the agent uses in place of the
/// CLI's built-in implementation.
pub fn with_overrides_built_in_tool(mut self, overrides: bool) -> Self {
self.overrides_built_in_tool = overrides;
self
}
/// When `true`, the CLI will not request permission before invoking
/// this tool. Use with caution — the tool is responsible for any
/// access control.
pub fn with_skip_permission(mut self, skip: bool) -> Self {
self.skip_permission = skip;
self
}
/// Attach a runtime implementation. The SDK will dispatch matching
/// `external_tool.requested` broadcasts to `handler` for this tool's
/// name. Without a handler the tool is declaration-only.
pub fn with_handler(mut self, handler: Arc<dyn crate::tool::ToolHandler>) -> Self {
self.handler = Some(handler);
self
}
/// Returns the attached runtime handler, if any.
///
/// Read-only inspection — to install or replace a handler, use
/// [`Tool::with_handler`].
pub fn handler(&self) -> Option<&Arc<dyn crate::tool::ToolHandler>> {
self.handler.as_ref()
}
}
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("namespaced_name", &self.namespaced_name)
.field("description", &self.description)
.field("instructions", &self.instructions)
.field("parameters", &self.parameters)
.field("overrides_built_in_tool", &self.overrides_built_in_tool)
.field("skip_permission", &self.skip_permission)
.field(
"handler",
&self.handler.as_ref().map(|_| "<set>").unwrap_or("None"),
)
.finish()
}
}
/// Context passed to a [`CommandHandler`] when a registered slash command
/// is executed by the user.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct CommandContext {
/// Session ID where the command was invoked.
pub session_id: SessionId,
/// The full command text (e.g. `"/deploy production"`).
pub command: String,
/// Command name without the leading `/` (e.g. `"deploy"`).
pub command_name: String,
/// Raw argument string after the command name (e.g. `"production"`).
pub args: String,
}
/// Handler invoked when a registered slash command is executed.
///
/// Returning `Err(_)` causes the SDK to forward the error message back to
/// the CLI via `session.commands.handlePendingCommand` so the TUI can
/// surface it. Returning `Ok(())` reports success.
#[async_trait::async_trait]
pub trait CommandHandler: Send + Sync {
/// Called when the user invokes the command this handler is registered for.
async fn on_command(&self, ctx: CommandContext) -> Result<(), crate::Error>;
}
/// Definition of a slash command registered with the session.
///
/// When the CLI is running with a TUI, registered commands appear as
/// `/name` for the user to invoke. Only `name` and `description` are sent
/// over the wire — the handler is local to this SDK process.
#[non_exhaustive]
#[derive(Clone)]
pub struct CommandDefinition {
/// Command name (without leading `/`).
pub name: String,
/// Human-readable description shown in command-completion UI.
pub description: Option<String>,
/// Handler invoked when the command is executed.
pub handler: Arc<dyn CommandHandler>,
}
impl CommandDefinition {
/// Construct a new command definition. Use [`with_description`](Self::with_description)
/// to add a description.
pub fn new(name: impl Into<String>, handler: Arc<dyn CommandHandler>) -> Self {
Self {
name: name.into(),
description: None,
handler,
}
}
/// Set the human-readable description shown in the CLI's command-completion UI.
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
impl std::fmt::Debug for CommandDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CommandDefinition")
.field("name", &self.name)
.field("description", &self.description)
.field("handler", &"<set>")
.finish()
}
}
impl Serialize for CommandDefinition {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let len = if self.description.is_some() { 2 } else { 1 };
let mut state = serializer.serialize_struct("CommandDefinition", len)?;
state.serialize_field("name", &self.name)?;
if let Some(description) = &self.description {
state.serialize_field("description", description)?;
}
state.end()
}
}
/// Configures a custom agent (sub-agent) for the session.
///
/// Custom agents have their own prompt, tool allowlist, and optionally
/// their own MCP servers and skill set. The agent named in
/// [`SessionConfig::agent`] (or the runtime default) is the active one
/// when the session starts.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CustomAgentConfig {
/// Unique name of the custom agent.
pub name: String,
/// Display name for UI purposes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
/// Description of what the agent does.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// List of tool names the agent can use. `None` means all tools.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tools: Option<Vec<String>>,
/// Prompt content for the agent.
pub prompt: String,
/// MCP servers specific to this agent.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<HashMap<String, McpServerConfig>>,
/// Whether the agent is available for model inference.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub infer: Option<bool>,
/// Skill names to preload into this agent's context at startup.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skills: Option<Vec<String>>,
/// Model identifier for this agent (e.g. `"claude-haiku-4.5"`).
///
/// When set, the runtime will attempt to use this model for the agent,
/// falling back to the parent session model if unavailable.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
}
impl CustomAgentConfig {
/// Construct a custom agent configuration with the required `name`
/// and `prompt` fields populated.
///
/// All other fields default to unset; use the `with_*` chain to
/// customize them. Fields are also `pub` if direct assignment is
/// preferred for `Option<T>` pass-through.
pub fn new(name: impl Into<String>, prompt: impl Into<String>) -> Self {
Self {
name: name.into(),
prompt: prompt.into(),
..Self::default()
}
}
/// Set the display name shown in the CLI's agent-selection UI.
pub fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
self.display_name = Some(display_name.into());
self
}
/// Set the description of what the agent does.
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
/// Restrict the agent to a specific tool allowlist. When unset, the
/// agent inherits the parent session's tool set.
pub fn with_tools<I, S>(mut self, tools: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.tools = Some(tools.into_iter().map(Into::into).collect());
self
}
/// Configure agent-specific MCP servers.
pub fn with_mcp_servers(mut self, mcp_servers: HashMap<String, McpServerConfig>) -> Self {
self.mcp_servers = Some(mcp_servers);
self
}
/// Whether the agent participates in model inference.
pub fn with_infer(mut self, infer: bool) -> Self {
self.infer = Some(infer);
self
}
/// Set the skills preloaded into the agent's context at startup.
pub fn with_skills<I, S>(mut self, skills: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.skills = Some(skills.into_iter().map(Into::into).collect());
self
}
/// Set the model identifier for this agent.
pub fn with_model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
}
/// Configures the default (built-in) agent that handles turns when no
/// custom agent is selected.
///
/// Use [`Self::excluded_tools`] to hide tools from the default agent
/// while keeping them available to custom sub-agents that list them in
/// their [`CustomAgentConfig::tools`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DefaultAgentConfig {
/// Tool names to exclude from the default agent.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub excluded_tools: Option<Vec<String>>,
}
/// Configuration for large tool output handling.
///
/// When a tool produces output exceeding [`max_size_bytes`](Self::max_size_bytes),
/// the SDK writes the full output to a file in [`output_directory`](Self::output_directory)
/// and returns a truncated preview to the model.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LargeToolOutputConfig {
/// Whether large tool output handling is enabled. Defaults to `true` on the CLI.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
/// Maximum tool output size in bytes before it is redirected to a file.
/// Defaults to 50KB on the CLI.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_size_bytes: Option<u64>,
/// Directory where large tool output files are written. Defaults to
/// the OS temp directory on the CLI.
#[serde(default, rename = "outputDir", skip_serializing_if = "Option::is_none")]
pub output_directory: Option<PathBuf>,
}
impl LargeToolOutputConfig {
/// Construct an empty [`LargeToolOutputConfig`]; all fields default to
/// unset (the CLI applies its own defaults).
pub fn new() -> Self {
Self::default()
}
/// Toggle large tool output handling on or off.
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
/// Set the maximum tool output size in bytes before it is redirected to a file.
pub fn with_max_size_bytes(mut self, max_size_bytes: u64) -> Self {
self.max_size_bytes = Some(max_size_bytes);
self
}
/// Set the directory where large tool output files are written.
pub fn with_output_directory<P: Into<PathBuf>>(mut self, output_directory: P) -> Self {
self.output_directory = Some(output_directory.into());
self
}
}
/// Configures infinite sessions: persistent workspaces with automatic
/// context-window compaction.
///
/// When enabled (default), sessions automatically manage context limits
/// through background compaction and persist state to a workspace
/// directory.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct InfiniteSessionConfig {
/// Whether infinite sessions are enabled. Defaults to `true` on the CLI.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
/// Context utilization (0.0–1.0) at which background compaction starts.
/// Default: 0.80.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub background_compaction_threshold: Option<f64>,
/// Context utilization (0.0–1.0) at which the session blocks until
/// compaction completes. Default: 0.95.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub buffer_exhaustion_threshold: Option<f64>,
}
impl InfiniteSessionConfig {
/// Construct an empty [`InfiniteSessionConfig`]; all fields default to
/// unset (the CLI applies its own defaults).
pub fn new() -> Self {
Self::default()
}
/// Toggle infinite sessions on or off. Defaults to `true` on the CLI
/// when unset.
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = Some(enabled);
self
}
/// Set the context utilization (0.0–1.0) at which background
/// compaction starts.
pub fn with_background_compaction_threshold(mut self, threshold: f64) -> Self {
self.background_compaction_threshold = Some(threshold);
self
}
/// Set the context utilization (0.0–1.0) at which the session blocks
/// until compaction completes.
pub fn with_buffer_exhaustion_threshold(mut self, threshold: f64) -> Self {
self.buffer_exhaustion_threshold = Some(threshold);
self
}
}
/// GitHub repository metadata to associate with a cloud session.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CloudSessionRepository {
/// Repository owner.
pub owner: String,
/// Repository name.
pub name: String,
/// Optional branch name.
#[serde(skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
}
impl CloudSessionRepository {
/// Create repository metadata for a cloud session.
pub fn new(owner: impl Into<String>, name: impl Into<String>) -> Self {
Self {
owner: owner.into(),
name: name.into(),
branch: None,
}
}
/// Set the branch associated with the repository.
pub fn with_branch(mut self, branch: impl Into<String>) -> Self {
self.branch = Some(branch.into());
self
}
}
/// Options for creating a remote session in the cloud.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct CloudSessionOptions {
/// Optional GitHub repository metadata to associate with the cloud session.
#[serde(skip_serializing_if = "Option::is_none")]
pub repository: Option<CloudSessionRepository>,
}
impl CloudSessionOptions {
/// Create cloud session options with repository metadata.
pub fn with_repository(repository: CloudSessionRepository) -> Self {
Self {
repository: Some(repository),
}
}
}
/// Stable extension identity for session participants that provide canvases.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ExtensionInfo {
/// Extension namespace/source, e.g. `"github-app"`.
pub source: String,
/// Stable provider name within the source namespace.
pub name: String,
}
impl ExtensionInfo {
/// Create stable extension identity metadata.
pub fn new(source: impl Into<String>, name: impl Into<String>) -> Self {
Self {
source: source.into(),
name: name.into(),
}
}
}
/// Configuration for a single MCP server.
///
/// MCP (Model Context Protocol) servers expose external tools to the
/// agent. Local servers run as a subprocess over stdio; remote servers
/// speak HTTP or Server-Sent Events.
///
/// Serialized as a JSON object with a `type` discriminator (`"stdio"` |
/// `"http"` | `"sse"`).
///
/// # Example
///
/// ```
/// # use github_copilot_sdk::types::{McpServerConfig, McpStdioServerConfig, McpHttpServerConfig};
/// # use std::collections::HashMap;
/// let mut servers = HashMap::new();
/// servers.insert(
/// "playwright".to_string(),
/// McpServerConfig::Stdio(McpStdioServerConfig {
/// tools: Some(vec!["*".to_string()]),
/// command: "npx".to_string(),
/// args: vec!["-y".to_string(), "@playwright/mcp".to_string()],
/// ..Default::default()
/// }),
/// );
/// servers.insert(
/// "weather".to_string(),
/// McpServerConfig::Http(McpHttpServerConfig {
/// tools: Some(vec!["forecast".to_string()]),
/// url: "https://example.com/mcp".to_string(),
/// ..Default::default()
/// }),
/// );
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
#[non_exhaustive]
pub enum McpServerConfig {
/// Local MCP server launched as a subprocess and addressed over stdio.
/// On the wire this serializes as `{"type": "stdio", ...}`. The CLI
/// also accepts `"local"` as an alias on input.
#[serde(alias = "local")]
Stdio(McpStdioServerConfig),
/// Remote MCP server addressed over HTTP.
Http(McpHttpServerConfig),
/// Remote MCP server addressed over Server-Sent Events.
Sse(McpHttpServerConfig),
}
/// Configuration for a local/stdio MCP server.
///
/// See [`McpServerConfig::Stdio`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpStdioServerConfig {
/// Tools to expose from this server.
///
/// - `None` (field omitted on the wire) — expose **all** tools.
/// - `Some(vec![])` — expose **no** tools.
/// - `Some(vec!["a", ...])` — expose only the listed tools.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tools: Option<Vec<String>>,
/// Optional timeout in milliseconds for tool calls to this server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout: Option<i64>,
/// Subprocess executable.
pub command: String,
/// Arguments to pass to the subprocess.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub args: Vec<String>,
/// Environment variables to set on the subprocess. Values are passed
/// through literally to the child process.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub env: HashMap<String, String>,
/// Working directory for the subprocess.
#[serde(default, skip_serializing_if = "Option::is_none", rename = "cwd")]
pub working_directory: Option<String>,
}
/// Configuration for a remote MCP server (HTTP or SSE).
///
/// See [`McpServerConfig::Http`] and [`McpServerConfig::Sse`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpHttpServerConfig {
/// Tools to expose from this server.
///
/// - `None` (field omitted on the wire) — expose **all** tools.
/// - `Some(vec![])` — expose **no** tools.
/// - `Some(vec!["a", ...])` — expose only the listed tools.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tools: Option<Vec<String>>,
/// Optional timeout in milliseconds for tool calls to this server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout: Option<i64>,
/// Server URL.
pub url: String,
/// Optional HTTP headers to include on every request.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub headers: HashMap<String, String>,
}
/// Configures a custom inference provider (BYOK — Bring Your Own Key).
///
/// Routes session requests through an alternative model provider
/// (OpenAI-compatible, Azure, Anthropic, or local) instead of GitHub
/// Copilot's default routing.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProviderConfig {
/// Provider type: `"openai"`, `"azure"`, or `"anthropic"`. Defaults to
/// `"openai"` on the CLI.
#[serde(default, skip_serializing_if = "Option::is_none", rename = "type")]
pub provider_type: Option<String>,
/// API format (openai/azure only): `"completions"` or `"responses"`.
/// Defaults to `"completions"`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wire_api: Option<String>,
/// API endpoint URL.
pub base_url: String,
/// API key. Optional for local providers like Ollama.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_key: Option<String>,
/// Bearer token for authentication. Sets the `Authorization` header
/// directly. Use for services requiring bearer-token auth instead of
/// API key. Takes precedence over `api_key` when both are set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bearer_token: Option<String>,
/// Azure-specific options.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub azure: Option<AzureProviderOptions>,
/// Custom HTTP headers included in outbound provider requests.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub headers: Option<HashMap<String, String>>,
/// Well-known model ID used to look up agent config and default token
/// limits. Also used as the wire model when [`wire_model`](Self::wire_model)
/// is unset. Falls back to [`SessionConfig::model`](crate::SessionConfig::model).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_id: Option<String>,
/// Model name sent to the provider API for inference. Use this when
/// the provider's model name (e.g. an Azure deployment name or a
/// custom fine-tune name) differs from
/// [`model_id`](Self::model_id). Falls back to
/// [`model_id`](Self::model_id), then to
/// [`SessionConfig::model`](crate::SessionConfig::model).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wire_model: Option<String>,
/// Overrides the resolved model's default max prompt tokens. The
/// runtime triggers conversation compaction before sending a request
/// when the prompt (system message, history, tool definitions, user
/// message) would exceed this limit.
#[serde(default, skip_serializing_if = "Option::is_none")]