-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtypes.go
More file actions
1174 lines (1038 loc) · 49.8 KB
/
types.go
File metadata and controls
1174 lines (1038 loc) · 49.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
package copilot
import (
"context"
"encoding/json"
"github.com/github/copilot-sdk/go/rpc"
)
// ConnectionState represents the client connection state
type ConnectionState string
const (
StateDisconnected ConnectionState = "disconnected"
StateConnecting ConnectionState = "connecting"
StateConnected ConnectionState = "connected"
StateError ConnectionState = "error"
)
// ClientOptions configures the CopilotClient
type ClientOptions struct {
// CLIPath is the path to the Copilot CLI executable (default: "copilot")
CLIPath string
// CLIArgs are extra arguments to pass to the CLI executable (inserted before SDK-managed args)
CLIArgs []string
// Cwd is the working directory for the CLI process (default: "" = inherit from current process)
Cwd string
// Port for TCP transport (default: 0 = random port)
Port int
// UseStdio controls whether to use stdio transport instead of TCP.
// Default: nil (use default = true, i.e. stdio). Use Bool(false) to explicitly select TCP.
UseStdio *bool
// CLIUrl is the URL of an existing Copilot CLI server to connect to over TCP
// Format: "host:port", "http://host:port", or just "port" (defaults to localhost)
// Examples: "localhost:8080", "http://127.0.0.1:9000", "8080"
// Mutually exclusive with CLIPath, UseStdio
CLIUrl string
// LogLevel for the CLI server
LogLevel string
// AutoStart automatically starts the CLI server on first use (default: true).
// Use Bool(false) to disable.
AutoStart *bool
// Deprecated: AutoRestart has no effect and will be removed in a future release.
AutoRestart *bool
// Env is the environment variables for the CLI process (default: inherits from current process).
// Each entry is of the form "key=value".
// If Env is nil, the new process uses the current process's environment.
// If Env contains duplicate environment keys, only the last value in the
// slice for each duplicate key is used.
Env []string
// GitHubToken is the GitHub token to use for authentication.
// When provided, the token is passed to the CLI server via environment variable.
// This takes priority over other authentication methods.
GitHubToken string
// UseLoggedInUser controls whether to use the logged-in user for authentication.
// When true, the CLI server will attempt to use stored OAuth tokens or gh CLI auth.
// When false, only explicit tokens (GitHubToken or environment variables) are used.
// Default: true (but defaults to false when GitHubToken is provided).
// Use Bool(false) to explicitly disable.
UseLoggedInUser *bool
// OnListModels is a custom handler for listing available models.
// When provided, client.ListModels() calls this handler instead of
// querying the CLI server. Useful in BYOK mode to return models
// available from your custom provider.
OnListModels func(ctx context.Context) ([]ModelInfo, error)
// SessionFs configures a custom session filesystem provider.
// When provided, the client registers as the session filesystem provider
// on connection, routing session-scoped file I/O through per-session handlers.
SessionFs *SessionFsConfig
// Telemetry configures OpenTelemetry integration for the Copilot CLI process.
// When non-nil, COPILOT_OTEL_ENABLED=true is set and any populated fields
// are mapped to the corresponding environment variables.
Telemetry *TelemetryConfig
}
// TelemetryConfig configures OpenTelemetry integration for the Copilot CLI process.
type TelemetryConfig struct {
// OTLPEndpoint is the OTLP HTTP endpoint URL for trace/metric export.
// Sets OTEL_EXPORTER_OTLP_ENDPOINT.
OTLPEndpoint string
// FilePath is the file path for JSON-lines trace output.
// Sets COPILOT_OTEL_FILE_EXPORTER_PATH.
FilePath string
// ExporterType is the exporter backend type: "otlp-http" or "file".
// Sets COPILOT_OTEL_EXPORTER_TYPE.
ExporterType string
// SourceName is the instrumentation scope name.
// Sets COPILOT_OTEL_SOURCE_NAME.
SourceName string
// CaptureContent controls whether to capture message content (prompts, responses).
// Sets OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT.
CaptureContent *bool
}
// Bool returns a pointer to the given bool value.
// Use for option fields such as AutoStart, AutoRestart, or LogOptions.Ephemeral:
//
// AutoStart: Bool(false)
// Ephemeral: Bool(true)
func Bool(v bool) *bool {
return &v
}
// String returns a pointer to the given string value.
// Use for setting optional string parameters in RPC calls.
func String(v string) *string {
return &v
}
// Float64 returns a pointer to the given float64 value.
// Use for setting thresholds: BackgroundCompactionThreshold: Float64(0.80)
func Float64(v float64) *float64 {
return &v
}
// Int returns a pointer to the given int value.
// Use for setting optional int parameters: MinLength: Int(1)
func Int(v int) *int {
return &v
}
// Known system prompt section identifiers for the "customize" mode.
const (
SectionIdentity = "identity"
SectionTone = "tone"
SectionToolEfficiency = "tool_efficiency"
SectionEnvironmentContext = "environment_context"
SectionCodeChangeRules = "code_change_rules"
SectionGuidelines = "guidelines"
SectionSafety = "safety"
SectionToolInstructions = "tool_instructions"
SectionCustomInstructions = "custom_instructions"
SectionLastInstructions = "last_instructions"
)
// SectionOverrideAction represents the action to perform on a system prompt section.
type SectionOverrideAction string
const (
// SectionActionReplace replaces section content entirely.
SectionActionReplace SectionOverrideAction = "replace"
// SectionActionRemove removes the section.
SectionActionRemove SectionOverrideAction = "remove"
// SectionActionAppend appends to existing section content.
SectionActionAppend SectionOverrideAction = "append"
// SectionActionPrepend prepends to existing section content.
SectionActionPrepend SectionOverrideAction = "prepend"
)
// SectionTransformFn is a callback that receives the current content of a system prompt section
// and returns the transformed content. Used with the "transform" action to read-then-write
// modify sections at runtime.
type SectionTransformFn func(currentContent string) (string, error)
// SectionOverride defines an override operation for a single system prompt section.
type SectionOverride struct {
// Action is the operation to perform: "replace", "remove", "append", "prepend", or "transform".
Action SectionOverrideAction `json:"action,omitempty"`
// Content for the override. Optional for all actions. Ignored for "remove".
Content string `json:"content,omitempty"`
// Transform is a callback invoked when Action is "transform".
// The runtime calls this with the current section content and uses the returned string.
// Excluded from JSON serialization; the SDK registers it as an RPC callback internally.
Transform SectionTransformFn `json:"-"`
}
// SystemMessageAppendConfig is append mode: use CLI foundation with optional appended content.
type SystemMessageAppendConfig struct {
// Mode is optional, defaults to "append"
Mode string `json:"mode,omitempty"`
// Content provides additional instructions appended after SDK-managed sections
Content string `json:"content,omitempty"`
}
// SystemMessageReplaceConfig is replace mode: use caller-provided system message entirely.
// Removes all SDK guardrails including security restrictions.
type SystemMessageReplaceConfig struct {
// Mode must be "replace"
Mode string `json:"mode"`
// Content is the complete system message (required)
Content string `json:"content"`
}
// SystemMessageConfig represents system message configuration for session creation.
// - Append mode (default): SDK foundation + optional custom content
// - Replace mode: Full control, caller provides entire system message
// - Customize mode: Section-level overrides with graceful fallback
//
// In Go, use one struct and set fields appropriate for the desired mode.
type SystemMessageConfig struct {
Mode string `json:"mode,omitempty"`
Content string `json:"content,omitempty"`
Sections map[string]SectionOverride `json:"sections,omitempty"`
}
// PermissionRequestResultKind represents the kind of a permission request result.
type PermissionRequestResultKind string
const (
// PermissionRequestResultKindApproved indicates the permission was approved.
PermissionRequestResultKindApproved PermissionRequestResultKind = "approved"
// PermissionRequestResultKindDeniedByRules indicates the permission was denied by rules.
PermissionRequestResultKindDeniedByRules PermissionRequestResultKind = "denied-by-rules"
// PermissionRequestResultKindDeniedCouldNotRequestFromUser indicates the permission was denied because
// no approval rule was found and the user could not be prompted.
PermissionRequestResultKindDeniedCouldNotRequestFromUser PermissionRequestResultKind = "denied-no-approval-rule-and-could-not-request-from-user"
// PermissionRequestResultKindDeniedInteractivelyByUser indicates the permission was denied interactively by the user.
PermissionRequestResultKindDeniedInteractivelyByUser PermissionRequestResultKind = "denied-interactively-by-user"
// PermissionRequestResultKindNoResult indicates no permission decision was made.
PermissionRequestResultKindNoResult PermissionRequestResultKind = "no-result"
)
// PermissionRequestResult represents the result of a permission request
type PermissionRequestResult struct {
Kind PermissionRequestResultKind `json:"kind"`
Rules []any `json:"rules,omitempty"`
}
// PermissionHandlerFunc executes a permission request
// The handler should return a PermissionRequestResult. Returning an error denies the permission.
type PermissionHandlerFunc func(request PermissionRequest, invocation PermissionInvocation) (PermissionRequestResult, error)
// PermissionInvocation provides context about a permission request
type PermissionInvocation struct {
SessionID string
}
// UserInputRequest represents a request for user input from the agent
type UserInputRequest struct {
Question string
Choices []string
AllowFreeform *bool
}
// UserInputResponse represents the user's response to an input request
type UserInputResponse struct {
Answer string
WasFreeform bool
}
// UserInputHandler handles user input requests from the agent
// The handler should return a UserInputResponse. Returning an error fails the request.
type UserInputHandler func(request UserInputRequest, invocation UserInputInvocation) (UserInputResponse, error)
// UserInputInvocation provides context about a user input request
type UserInputInvocation struct {
SessionID string
}
// PreToolUseHookInput is the input for a pre-tool-use hook
type PreToolUseHookInput struct {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
}
// PreToolUseHookOutput is the output for a pre-tool-use hook
type PreToolUseHookOutput struct {
PermissionDecision string `json:"permissionDecision,omitempty"` // "allow", "deny", "ask"
PermissionDecisionReason string `json:"permissionDecisionReason,omitempty"`
ModifiedArgs any `json:"modifiedArgs,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
}
// PreToolUseHandler handles pre-tool-use hook invocations
type PreToolUseHandler func(input PreToolUseHookInput, invocation HookInvocation) (*PreToolUseHookOutput, error)
// PostToolUseHookInput is the input for a post-tool-use hook
type PostToolUseHookInput struct {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
ToolResult any `json:"toolResult"`
}
// PostToolUseHookOutput is the output for a post-tool-use hook
type PostToolUseHookOutput struct {
ModifiedResult any `json:"modifiedResult,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
}
// PostToolUseHandler handles post-tool-use hook invocations
type PostToolUseHandler func(input PostToolUseHookInput, invocation HookInvocation) (*PostToolUseHookOutput, error)
// UserPromptSubmittedHookInput is the input for a user-prompt-submitted hook
type UserPromptSubmittedHookInput struct {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Prompt string `json:"prompt"`
}
// UserPromptSubmittedHookOutput is the output for a user-prompt-submitted hook
type UserPromptSubmittedHookOutput struct {
ModifiedPrompt string `json:"modifiedPrompt,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
}
// UserPromptSubmittedHandler handles user-prompt-submitted hook invocations
type UserPromptSubmittedHandler func(input UserPromptSubmittedHookInput, invocation HookInvocation) (*UserPromptSubmittedHookOutput, error)
// SessionStartHookInput is the input for a session-start hook
type SessionStartHookInput struct {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Source string `json:"source"` // "startup", "resume", "new"
InitialPrompt string `json:"initialPrompt,omitempty"`
}
// SessionStartHookOutput is the output for a session-start hook
type SessionStartHookOutput struct {
AdditionalContext string `json:"additionalContext,omitempty"`
ModifiedConfig map[string]any `json:"modifiedConfig,omitempty"`
}
// SessionStartHandler handles session-start hook invocations
type SessionStartHandler func(input SessionStartHookInput, invocation HookInvocation) (*SessionStartHookOutput, error)
// SessionEndHookInput is the input for a session-end hook
type SessionEndHookInput struct {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Reason string `json:"reason"` // "complete", "error", "abort", "timeout", "user_exit"
FinalMessage string `json:"finalMessage,omitempty"`
Error string `json:"error,omitempty"`
}
// SessionEndHookOutput is the output for a session-end hook
type SessionEndHookOutput struct {
SuppressOutput bool `json:"suppressOutput,omitempty"`
CleanupActions []string `json:"cleanupActions,omitempty"`
SessionSummary string `json:"sessionSummary,omitempty"`
}
// SessionEndHandler handles session-end hook invocations
type SessionEndHandler func(input SessionEndHookInput, invocation HookInvocation) (*SessionEndHookOutput, error)
// ErrorOccurredHookInput is the input for an error-occurred hook
type ErrorOccurredHookInput struct {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Error string `json:"error"`
ErrorContext string `json:"errorContext"` // "model_call", "tool_execution", "system", "user_input"
Recoverable bool `json:"recoverable"`
}
// ErrorOccurredHookOutput is the output for an error-occurred hook
type ErrorOccurredHookOutput struct {
SuppressOutput bool `json:"suppressOutput,omitempty"`
ErrorHandling string `json:"errorHandling,omitempty"` // "retry", "skip", "abort"
RetryCount int `json:"retryCount,omitempty"`
UserNotification string `json:"userNotification,omitempty"`
}
// ErrorOccurredHandler handles error-occurred hook invocations
type ErrorOccurredHandler func(input ErrorOccurredHookInput, invocation HookInvocation) (*ErrorOccurredHookOutput, error)
// HookInvocation provides context about a hook invocation
type HookInvocation struct {
SessionID string
}
// SessionHooks configures hook handlers for a session
type SessionHooks struct {
OnPreToolUse PreToolUseHandler
OnPostToolUse PostToolUseHandler
OnUserPromptSubmitted UserPromptSubmittedHandler
OnSessionStart SessionStartHandler
OnSessionEnd SessionEndHandler
OnErrorOccurred ErrorOccurredHandler
}
// MCPServerConfig is implemented by MCP server configuration types.
// Only MCPStdioServerConfig and MCPHTTPServerConfig implement this interface.
type MCPServerConfig interface {
mcpServerConfig()
}
// MCPStdioServerConfig configures a local/stdio MCP server.
type MCPStdioServerConfig struct {
Tools []string `json:"tools"`
Timeout int `json:"timeout,omitempty"`
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env,omitempty"`
Cwd string `json:"cwd,omitempty"`
}
func (MCPStdioServerConfig) mcpServerConfig() {}
// MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
func (c MCPStdioServerConfig) MarshalJSON() ([]byte, error) {
type alias MCPStdioServerConfig
return json.Marshal(struct {
Type string `json:"type"`
alias
}{
Type: "stdio",
alias: alias(c),
})
}
// MCPHTTPServerConfig configures a remote MCP server (HTTP or SSE).
type MCPHTTPServerConfig struct {
Tools []string `json:"tools"`
Timeout int `json:"timeout,omitempty"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
func (MCPHTTPServerConfig) mcpServerConfig() {}
// MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
func (c MCPHTTPServerConfig) MarshalJSON() ([]byte, error) {
type alias MCPHTTPServerConfig
return json.Marshal(struct {
Type string `json:"type"`
alias
}{
Type: "http",
alias: alias(c),
})
}
// CustomAgentConfig configures a custom agent
type CustomAgentConfig struct {
// Name is the unique name of the custom agent
Name string `json:"name"`
// DisplayName is the display name for UI purposes
DisplayName string `json:"displayName,omitempty"`
// Description of what the agent does
Description string `json:"description,omitempty"`
// Tools is the list of tool names the agent can use (nil for all tools)
Tools []string `json:"tools,omitempty"`
// Prompt is the prompt content for the agent
Prompt string `json:"prompt"`
// MCPServers are MCP servers specific to this agent
MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"`
// Infer indicates whether the agent should be available for model inference
Infer *bool `json:"infer,omitempty"`
}
// InfiniteSessionConfig configures infinite sessions with automatic context compaction
// and workspace persistence. When enabled, sessions automatically manage context window
// limits through background compaction and persist state to a workspace directory.
type InfiniteSessionConfig struct {
// Enabled controls whether infinite sessions are enabled (default: true)
Enabled *bool `json:"enabled,omitempty"`
// BackgroundCompactionThreshold is the context utilization (0.0-1.0) at which
// background compaction starts. Default: 0.80
BackgroundCompactionThreshold *float64 `json:"backgroundCompactionThreshold,omitempty"`
// BufferExhaustionThreshold is the context utilization (0.0-1.0) at which
// the session blocks until compaction completes. Default: 0.95
BufferExhaustionThreshold *float64 `json:"bufferExhaustionThreshold,omitempty"`
}
// SessionFsConfig configures a custom session filesystem provider.
type SessionFsConfig struct {
// InitialCwd is the initial working directory for sessions.
InitialCwd string
// SessionStatePath is the path within each session's filesystem where the runtime stores
// session-scoped files such as events, checkpoints, and temp files.
SessionStatePath string
// Conventions identifies the path conventions used by this filesystem provider.
Conventions rpc.Conventions
}
// SessionConfig configures a new session
type SessionConfig struct {
// SessionID is an optional custom session ID
SessionID string
// ClientName identifies the application using the SDK.
// Included in the User-Agent header for API requests.
ClientName string
// Model to use for this session
Model string
// ReasoningEffort level for models that support it.
// Valid values: "low", "medium", "high", "xhigh"
// Only applies to models where capabilities.supports.reasoningEffort is true.
ReasoningEffort string
// ConfigDir overrides the default configuration directory location.
// When specified, the session will use this directory for storing config and state.
ConfigDir string
// EnableConfigDiscovery, when true, automatically discovers MCP server configurations
// (e.g. .mcp.json, .vscode/mcp.json) and skill directories from the working directory
// and merges them with any explicitly provided MCPServers and SkillDirectories, with
// explicit values taking precedence on name collision.
// Custom instruction files (.github/copilot-instructions.md, AGENTS.md, etc.) are
// always loaded from the working directory regardless of this setting.
EnableConfigDiscovery bool
// Tools exposes caller-implemented tools to the CLI
Tools []Tool
// SystemMessage configures system message customization
SystemMessage *SystemMessageConfig
// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
// Takes precedence over ExcludedTools.
AvailableTools []string
// ExcludedTools is a list of tool names to disable. All other tools remain available.
// Ignored if AvailableTools is specified.
ExcludedTools []string
// OnPermissionRequest is a handler for permission requests from the server.
// If nil, all permission requests are denied by default.
// Provide a handler to approve operations (file writes, shell commands, URL fetches, etc.).
OnPermissionRequest PermissionHandlerFunc
// OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool)
OnUserInputRequest UserInputHandler
// Hooks configures hook handlers for session lifecycle events
Hooks *SessionHooks
// WorkingDirectory is the working directory for the session.
// Tool operations will be relative to this directory.
WorkingDirectory string
// Streaming enables streaming of assistant message and reasoning chunks.
// When true, assistant.message_delta and assistant.reasoning_delta events
// with deltaContent are sent as the response is generated.
Streaming bool
// Provider configures a custom model provider (BYOK)
Provider *ProviderConfig
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// CustomAgents configures custom agents for the session
CustomAgents []CustomAgentConfig
// Agent is the name of the custom agent to activate when the session starts.
// Must match the Name of one of the agents in CustomAgents.
Agent string
// SkillDirectories is a list of directories to load skills from
SkillDirectories []string
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
// When enabled (default), sessions automatically manage context limits and persist state.
InfiniteSessions *InfiniteSessionConfig
// OnEvent is an optional event handler that is registered on the session before
// the session.create RPC is issued. This guarantees that early events emitted
// by the CLI during session creation (e.g. session.start) are delivered to the
// handler. Equivalent to calling session.On(handler) immediately after creation,
// but executes earlier in the lifecycle so no events are missed.
OnEvent SessionEventHandler
// CreateSessionFsHandler supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFs is configured.
CreateSessionFsHandler func(session *Session) rpc.SessionFsHandler
// Commands registers slash-commands for this session. Each command appears as
// /name in the CLI TUI for the user to invoke. The Handler is called when the
// command is executed.
Commands []CommandDefinition
// OnElicitationRequest is a handler for elicitation requests from the server.
// When provided, the server may call back to this client for form-based UI dialogs
// (e.g. from MCP tools). Also enables the elicitation capability on the session.
OnElicitationRequest ElicitationHandler
}
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
OverridesBuiltInTool bool `json:"overridesBuiltInTool,omitempty"`
SkipPermission bool `json:"skipPermission,omitempty"`
Handler ToolHandler `json:"-"`
}
// ToolInvocation describes a tool call initiated by Copilot
type ToolInvocation struct {
SessionID string
ToolCallID string
ToolName string
Arguments any
// TraceContext carries the W3C Trace Context propagated from the CLI's
// execute_tool span. Pass this to OpenTelemetry-aware code so that
// child spans created inside the handler are parented to the CLI span.
// When no trace context is available this will be context.Background().
TraceContext context.Context
}
// ToolHandler executes a tool invocation.
// The handler should return a ToolResult. Returning an error marks the tool execution as a failure.
type ToolHandler func(invocation ToolInvocation) (ToolResult, error)
// ToolResult represents the result of a tool invocation.
type ToolResult struct {
TextResultForLLM string `json:"textResultForLlm"`
BinaryResultsForLLM []ToolBinaryResult `json:"binaryResultsForLlm,omitempty"`
ResultType string `json:"resultType"`
Error string `json:"error,omitempty"`
SessionLog string `json:"sessionLog,omitempty"`
ToolTelemetry map[string]any `json:"toolTelemetry,omitempty"`
}
// CommandContext provides context about a slash-command invocation.
type CommandContext struct {
// SessionID is the session where the command was invoked.
SessionID string
// Command is the full command text (e.g. "/deploy production").
Command string
// CommandName is the command name without the leading / (e.g. "deploy").
CommandName string
// Args is the raw argument string after the command name.
Args string
}
// CommandHandler is invoked when a registered slash-command is executed.
type CommandHandler func(ctx CommandContext) error
// CommandDefinition registers a slash-command. Name is shown in the CLI TUI
// as /name for the user to invoke.
type CommandDefinition struct {
// Name is the command name (without leading /).
Name string
// Description is a human-readable description shown in command completion UI.
Description string
// Handler is invoked when the command is executed.
Handler CommandHandler
}
// SessionCapabilities describes what features the host supports.
type SessionCapabilities struct {
UI *UICapabilities `json:"ui,omitempty"`
}
// UICapabilities describes host UI feature support.
type UICapabilities struct {
// Elicitation indicates whether the host supports interactive elicitation dialogs.
Elicitation bool `json:"elicitation,omitempty"`
}
// ElicitationResult is the user's response to an elicitation dialog.
type ElicitationResult struct {
// Action is the user response: "accept" (submitted), "decline" (rejected), or "cancel" (dismissed).
Action string `json:"action"`
// Content holds form values submitted by the user (present when Action is "accept").
Content map[string]any `json:"content,omitempty"`
}
// ElicitationContext describes an elicitation request from the server,
// combining the request data with session context. Mirrors the
// single-argument pattern of CommandContext.
type ElicitationContext struct {
// SessionID is the identifier of the session that triggered the request.
SessionID string
// Message describes what information is needed from the user.
Message string
// RequestedSchema is a JSON Schema describing the form fields (form mode only).
RequestedSchema map[string]any
// Mode is "form" for structured input, "url" for browser redirect.
Mode string
// ElicitationSource is the source that initiated the request (e.g. MCP server name).
ElicitationSource string
// URL to open in the user's browser (url mode only).
URL string
}
// ElicitationHandler handles elicitation requests from the server (e.g. from MCP tools).
// It receives an ElicitationContext and must return an ElicitationResult.
// If the handler returns an error the SDK auto-cancels the request.
type ElicitationHandler func(ctx ElicitationContext) (ElicitationResult, error)
// InputOptions configures a text input field for the Input convenience method.
type InputOptions struct {
// Title label for the input field.
Title string
// Description text shown below the field.
Description string
// MinLength is the minimum character length.
MinLength *int
// MaxLength is the maximum character length.
MaxLength *int
// Format is a semantic format hint: "email", "uri", "date", or "date-time".
Format string
// Default is the pre-populated value.
Default string
}
// SessionUI provides convenience methods for showing elicitation dialogs to the user.
// Obtained via [Session.UI]. Methods error if the host does not support elicitation.
type SessionUI struct {
session *Session
}
// ResumeSessionConfig configures options when resuming a session
type ResumeSessionConfig struct {
// ClientName identifies the application using the SDK.
// Included in the User-Agent header for API requests.
ClientName string
// Model to use for this session. Can change the model when resuming.
Model string
// Tools exposes caller-implemented tools to the CLI
Tools []Tool
// SystemMessage configures system message customization
SystemMessage *SystemMessageConfig
// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
// Takes precedence over ExcludedTools.
AvailableTools []string
// ExcludedTools is a list of tool names to disable. All other tools remain available.
// Ignored if AvailableTools is specified.
ExcludedTools []string
// Provider configures a custom model provider
Provider *ProviderConfig
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// ReasoningEffort level for models that support it.
// Valid values: "low", "medium", "high", "xhigh"
ReasoningEffort string
// OnPermissionRequest is a handler for permission requests from the server.
// If nil, all permission requests are denied by default.
// Provide a handler to approve operations (file writes, shell commands, URL fetches, etc.).
OnPermissionRequest PermissionHandlerFunc
// OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool)
OnUserInputRequest UserInputHandler
// Hooks configures hook handlers for session lifecycle events
Hooks *SessionHooks
// WorkingDirectory is the working directory for the session.
// Tool operations will be relative to this directory.
WorkingDirectory string
// ConfigDir overrides the default configuration directory location.
ConfigDir string
// EnableConfigDiscovery, when true, automatically discovers MCP server configurations
// (e.g. .mcp.json, .vscode/mcp.json) and skill directories from the working directory
// and merges them with any explicitly provided MCPServers and SkillDirectories, with
// explicit values taking precedence on name collision.
// Custom instruction files (.github/copilot-instructions.md, AGENTS.md, etc.) are
// always loaded from the working directory regardless of this setting.
EnableConfigDiscovery bool
// Streaming enables streaming of assistant message and reasoning chunks.
// When true, assistant.message_delta and assistant.reasoning_delta events
// with deltaContent are sent as the response is generated.
Streaming bool
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// CustomAgents configures custom agents for the session
CustomAgents []CustomAgentConfig
// Agent is the name of the custom agent to activate when the session starts.
// Must match the Name of one of the agents in CustomAgents.
Agent string
// SkillDirectories is a list of directories to load skills from
SkillDirectories []string
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
InfiniteSessions *InfiniteSessionConfig
// DisableResume, when true, skips emitting the session.resume event.
// Useful for reconnecting to a session without triggering resume-related side effects.
DisableResume bool
// OnEvent is an optional event handler registered before the session.resume RPC
// is issued, ensuring early events are delivered. See SessionConfig.OnEvent.
OnEvent SessionEventHandler
// CreateSessionFsHandler supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFs is configured.
CreateSessionFsHandler func(session *Session) rpc.SessionFsHandler
// Commands registers slash-commands for this session. See SessionConfig.Commands.
Commands []CommandDefinition
// OnElicitationRequest is a handler for elicitation requests from the server.
// See SessionConfig.OnElicitationRequest.
OnElicitationRequest ElicitationHandler
}
type ProviderConfig struct {
// Type is the provider type: "openai", "azure", or "anthropic". Defaults to "openai".
Type string `json:"type,omitempty"`
// WireApi is the API format (openai/azure only): "completions" or "responses". Defaults to "completions".
WireApi string `json:"wireApi,omitempty"`
// BaseURL is the API endpoint URL
BaseURL string `json:"baseUrl"`
// APIKey is the API key. Optional for local providers like Ollama.
APIKey string `json:"apiKey,omitempty"`
// BearerToken for authentication. Sets the Authorization header directly.
// Use this for services requiring bearer token auth instead of API key.
// Takes precedence over APIKey when both are set.
BearerToken string `json:"bearerToken,omitempty"`
// Azure contains Azure-specific options
Azure *AzureProviderOptions `json:"azure,omitempty"`
}
// AzureProviderOptions contains Azure-specific provider configuration
type AzureProviderOptions struct {
// APIVersion is the Azure API version. Defaults to "2024-10-21".
APIVersion string `json:"apiVersion,omitempty"`
}
// ToolBinaryResult represents binary payloads returned by tools.
type ToolBinaryResult struct {
Data string `json:"data"`
MimeType string `json:"mimeType"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
}
// MessageOptions configures a message to send
type MessageOptions struct {
// Prompt is the message to send
Prompt string
// Attachments are file or directory attachments
Attachments []Attachment
// Mode is the message delivery mode (default: "enqueue")
Mode string
}
// SessionEventHandler is a callback for session events
type SessionEventHandler func(event SessionEvent)
// ModelVisionLimits contains vision-specific limits
type ModelVisionLimits struct {
SupportedMediaTypes []string `json:"supported_media_types"`
MaxPromptImages int `json:"max_prompt_images"`
MaxPromptImageSize int `json:"max_prompt_image_size"`
}
// ModelLimits contains model limits
type ModelLimits struct {
MaxPromptTokens *int `json:"max_prompt_tokens,omitempty"`
MaxContextWindowTokens int `json:"max_context_window_tokens"`
Vision *ModelVisionLimits `json:"vision,omitempty"`
}
// ModelSupports contains model support flags
type ModelSupports struct {
Vision bool `json:"vision"`
ReasoningEffort bool `json:"reasoningEffort"`
}
// ModelCapabilities contains model capabilities and limits
type ModelCapabilities struct {
Supports ModelSupports `json:"supports"`
Limits ModelLimits `json:"limits"`
}
// Type aliases for model capabilities overrides, re-exported from the rpc
// package for ergonomic use without requiring a separate rpc import.
type (
ModelCapabilitiesOverride = rpc.ModelCapabilitiesOverride
ModelCapabilitiesOverrideSupports = rpc.ModelCapabilitiesOverrideSupports
ModelCapabilitiesOverrideLimits = rpc.ModelCapabilitiesOverrideLimits
ModelCapabilitiesOverrideLimitsVision = rpc.ModelCapabilitiesOverrideLimitsVision
)
// ModelPolicy contains model policy state
type ModelPolicy struct {
State string `json:"state"`
Terms string `json:"terms"`
}
// ModelBilling contains model billing information
type ModelBilling struct {
Multiplier float64 `json:"multiplier"`
}
// ModelInfo contains information about an available model
type ModelInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Capabilities ModelCapabilities `json:"capabilities"`
Policy *ModelPolicy `json:"policy,omitempty"`
Billing *ModelBilling `json:"billing,omitempty"`
SupportedReasoningEfforts []string `json:"supportedReasoningEfforts,omitempty"`
DefaultReasoningEffort string `json:"defaultReasoningEffort,omitempty"`
}
// SessionContext contains working directory context for a session
type SessionContext struct {
// Cwd is the working directory where the session was created
Cwd string `json:"cwd"`
// GitRoot is the git repository root (if in a git repo)
GitRoot string `json:"gitRoot,omitempty"`
// Repository is the GitHub repository in "owner/repo" format
Repository string `json:"repository,omitempty"`
// Branch is the current git branch
Branch string `json:"branch,omitempty"`
}
// SessionListFilter contains filter options for listing sessions
type SessionListFilter struct {
// Cwd filters by exact working directory match
Cwd string `json:"cwd,omitempty"`
// GitRoot filters by git root
GitRoot string `json:"gitRoot,omitempty"`
// Repository filters by repository (owner/repo format)
Repository string `json:"repository,omitempty"`
// Branch filters by branch
Branch string `json:"branch,omitempty"`
}
// SessionMetadata contains metadata about a session
type SessionMetadata struct {
SessionID string `json:"sessionId"`
StartTime string `json:"startTime"`
ModifiedTime string `json:"modifiedTime"`
Summary *string `json:"summary,omitempty"`
IsRemote bool `json:"isRemote"`
Context *SessionContext `json:"context,omitempty"`
}
// SessionLifecycleEventType represents the type of session lifecycle event
type SessionLifecycleEventType string
const (
SessionLifecycleCreated SessionLifecycleEventType = "session.created"
SessionLifecycleDeleted SessionLifecycleEventType = "session.deleted"
SessionLifecycleUpdated SessionLifecycleEventType = "session.updated"
SessionLifecycleForeground SessionLifecycleEventType = "session.foreground"
SessionLifecycleBackground SessionLifecycleEventType = "session.background"
)
// SessionLifecycleEvent represents a session lifecycle notification
type SessionLifecycleEvent struct {
Type SessionLifecycleEventType `json:"type"`
SessionID string `json:"sessionId"`
Metadata *SessionLifecycleEventMetadata `json:"metadata,omitempty"`
}
// SessionLifecycleEventMetadata contains optional metadata for lifecycle events
type SessionLifecycleEventMetadata struct {
StartTime string `json:"startTime"`
ModifiedTime string `json:"modifiedTime"`
Summary *string `json:"summary,omitempty"`
}
// SessionLifecycleHandler is a callback for session lifecycle events
type SessionLifecycleHandler func(event SessionLifecycleEvent)
// createSessionRequest is the request for session.create
type createSessionRequest struct {
Model string `json:"model,omitempty"`
SessionID string `json:"sessionId,omitempty"`
ClientName string `json:"clientName,omitempty"`
ReasoningEffort string `json:"reasoningEffort,omitempty"`
Tools []Tool `json:"tools,omitempty"`
SystemMessage *SystemMessageConfig `json:"systemMessage,omitempty"`
AvailableTools []string `json:"availableTools"`
ExcludedTools []string `json:"excludedTools,omitempty"`
Provider *ProviderConfig `json:"provider,omitempty"`
ModelCapabilities *rpc.ModelCapabilitiesOverride `json:"modelCapabilities,omitempty"`
RequestPermission *bool `json:"requestPermission,omitempty"`
RequestUserInput *bool `json:"requestUserInput,omitempty"`
Hooks *bool `json:"hooks,omitempty"`
WorkingDirectory string `json:"workingDirectory,omitempty"`
Streaming *bool `json:"streaming,omitempty"`
MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"`
EnvValueMode string `json:"envValueMode,omitempty"`
CustomAgents []CustomAgentConfig `json:"customAgents,omitempty"`
Agent string `json:"agent,omitempty"`
ConfigDir string `json:"configDir,omitempty"`
EnableConfigDiscovery *bool `json:"enableConfigDiscovery,omitempty"`
SkillDirectories []string `json:"skillDirectories,omitempty"`
DisabledSkills []string `json:"disabledSkills,omitempty"`
InfiniteSessions *InfiniteSessionConfig `json:"infiniteSessions,omitempty"`
Commands []wireCommand `json:"commands,omitempty"`
RequestElicitation *bool `json:"requestElicitation,omitempty"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
// wireCommand is the wire representation of a command (name + description only, no handler).
type wireCommand struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
// createSessionResponse is the response from session.create
type createSessionResponse struct {
SessionID string `json:"sessionId"`
WorkspacePath string `json:"workspacePath"`
Capabilities *SessionCapabilities `json:"capabilities,omitempty"`
}
// resumeSessionRequest is the request for session.resume
type resumeSessionRequest struct {
SessionID string `json:"sessionId"`
ClientName string `json:"clientName,omitempty"`
Model string `json:"model,omitempty"`
ReasoningEffort string `json:"reasoningEffort,omitempty"`
Tools []Tool `json:"tools,omitempty"`
SystemMessage *SystemMessageConfig `json:"systemMessage,omitempty"`
AvailableTools []string `json:"availableTools"`
ExcludedTools []string `json:"excludedTools,omitempty"`
Provider *ProviderConfig `json:"provider,omitempty"`
ModelCapabilities *rpc.ModelCapabilitiesOverride `json:"modelCapabilities,omitempty"`
RequestPermission *bool `json:"requestPermission,omitempty"`
RequestUserInput *bool `json:"requestUserInput,omitempty"`
Hooks *bool `json:"hooks,omitempty"`
WorkingDirectory string `json:"workingDirectory,omitempty"`
ConfigDir string `json:"configDir,omitempty"`
EnableConfigDiscovery *bool `json:"enableConfigDiscovery,omitempty"`
DisableResume *bool `json:"disableResume,omitempty"`
Streaming *bool `json:"streaming,omitempty"`
MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"`
EnvValueMode string `json:"envValueMode,omitempty"`
CustomAgents []CustomAgentConfig `json:"customAgents,omitempty"`
Agent string `json:"agent,omitempty"`