-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtypes.go
More file actions
1751 lines (1577 loc) · 77.2 KB
/
types.go
File metadata and controls
1751 lines (1577 loc) · 77.2 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"
"time"
"github.com/github/copilot-sdk/go/rpc"
)
// connectionState is the internal client connection state.
type connectionState string
const (
stateDisconnected connectionState = "disconnected"
stateConnecting connectionState = "connecting"
stateConnected connectionState = "connected"
stateError connectionState = "error"
)
// RuntimeConnection describes how a [Client] connects to the Copilot runtime.
//
// Construct one with a [StdioConnection], [TcpConnection], or [UriConnection]
// literal and pass it via [ClientOptions.Connection]. When [ClientOptions.Connection]
// is nil, the default is an empty [StdioConnection] (the SDK spawns the bundled
// runtime and communicates over stdin/stdout).
type RuntimeConnection interface {
runtimeConnection()
}
// StdioConnection spawns a runtime child process and communicates over its
// stdin/stdout pipes. This is the default when no connection is configured.
type StdioConnection struct {
// Path is the runtime executable. When empty, the bundled runtime is used.
Path string
// Args are extra command-line arguments inserted before SDK-managed args.
Args []string
}
func (StdioConnection) runtimeConnection() {}
// TcpConnection spawns a runtime child process that listens on a TCP socket
// and connects to it.
type TcpConnection struct {
// Port is the TCP port the runtime listens on. 0 (the default) lets the
// runtime pick a free port; the chosen port is then available via
// [Client.RuntimePort] after [Client.Start] returns.
Port int
// ConnectionToken is an optional shared secret sent in the `connect`
// handshake. When empty, a UUID is generated automatically so the
// loopback listener is safe by default.
ConnectionToken string
// Path is the runtime executable. When empty, the bundled runtime is used.
Path string
// Args are extra command-line arguments inserted before SDK-managed args.
Args []string
}
func (TcpConnection) runtimeConnection() {}
// UriConnection connects to an already-running runtime at the given URL.
// The SDK does not spawn a process in this mode.
type UriConnection struct {
// URL of the runtime. Accepts "port", "host:port", or a full URL such
// as "http://host:port".
URL string
// ConnectionToken authenticates the connection; must match what the
// remote runtime expects.
ConnectionToken string
}
func (UriConnection) runtimeConnection() {}
// ClientOptions configures the [Client].
type ClientOptions struct {
// Connection describes how to connect to the Copilot runtime. When nil,
// defaults to an empty [StdioConnection] (spawn the bundled runtime over
// stdio).
Connection RuntimeConnection
// WorkingDirectory is the working directory for the runtime process.
// If empty, inherits the current process's working directory.
WorkingDirectory string
// BaseDirectory is the base directory for Copilot data (session state,
// config, etc.). Sets the COPILOT_HOME environment variable on the
// spawned runtime. When empty, the runtime defaults to ~/.copilot.
// This does not affect where the Go SDK extracts the embedded CLI
// binary; use embeddedcli.Config.Dir to control that install/cache
// location.
// Ignored when connecting to an existing runtime via [UriConnection].
BaseDirectory string
// LogLevel for the runtime. When empty (the default), the runtime
// uses its own default level; the SDK does not pass --log-level.
// Recognized values: "none", "error", "warning", "info", "debug", "all".
LogLevel string
// Env are the environment variables for the runtime process (default:
// inherits from current process). Each entry is of the form "KEY=VALUE".
// If Env contains duplicate keys, only the last value for each key is used.
Env []string
// GitHubToken is the GitHub token to use for authentication.
// When provided, the token is passed to the runtime 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 runtime attempts 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).
UseLoggedInUser *bool
// OnListModels is a custom handler for listing available models.
// When provided, [Client.ListModels] calls this handler instead of
// querying the runtime. 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 runtime.
// When non-nil, COPILOT_OTEL_ENABLED=true is set and any populated
// fields are mapped to the corresponding environment variables.
Telemetry *TelemetryConfig
// SessionIdleTimeoutSeconds configures the server-wide session idle
// timeout in seconds. Sessions without activity for this duration are
// automatically cleaned up. Set to 0 or leave unset to disable.
// Ignored when connecting to an existing runtime via [UriConnection].
SessionIdleTimeoutSeconds int
// EnableRemoteSessions enables remote session support (Mission Control
// integration). When true, sessions in a GitHub repository working
// directory are accessible from GitHub web and mobile.
// Ignored when connecting to an existing runtime via [UriConnection].
EnableRemoteSessions bool
}
// CloudSessionRepository is GitHub repository metadata associated with a cloud session.
type CloudSessionRepository struct {
Owner string `json:"owner"`
Name string `json:"name"`
Branch string `json:"branch,omitempty"`
}
// CloudSessionOptions configures creation of a remote session in the cloud.
type CloudSessionOptions struct {
Repository *CloudSessionRepository `json:"repository,omitempty"`
}
// 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 message section identifiers for the "customize" mode.
const (
// SectionIdentity is the agent identity preamble and mode statement.
SectionIdentity = "identity"
// SectionTone covers response style, conciseness rules, and output formatting preferences.
SectionTone = "tone"
// SectionToolEfficiency covers tool usage patterns, parallel calling, and batching guidelines.
SectionToolEfficiency = "tool_efficiency"
// SectionEnvironmentContext covers CWD, OS, git root, directory listing, and available tools.
SectionEnvironmentContext = "environment_context"
// SectionCodeChangeRules covers coding rules, linting/testing, ecosystem tools, and style.
SectionCodeChangeRules = "code_change_rules"
// SectionGuidelines covers tips, behavioral best practices, and behavioral guidelines.
SectionGuidelines = "guidelines"
// SectionSafety covers environment limitations, prohibited actions, and security policies.
SectionSafety = "safety"
// SectionToolInstructions covers per-tool usage instructions.
SectionToolInstructions = "tool_instructions"
// SectionCustomInstructions covers repository and organization custom instructions.
SectionCustomInstructions = "custom_instructions"
// SectionRuntimeInstructions targets runtime-provided context and instructions
// (e.g. system notifications, memories, workspace context, mode-specific instructions,
// content-exclusion policy).
SectionRuntimeInstructions = "runtime_instructions"
// SectionLastInstructions covers end-of-prompt instructions: parallel tool calling,
// persistence, and task completion.
SectionLastInstructions = "last_instructions"
)
// SectionOverrideAction represents the action to perform on a system message 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 message 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 message 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"`
}
// PermissionHandlerFunc executes a permission request.
// The handler should return a [rpc.PermissionDecision]. Returning an error
// causes the SDK to respond with [rpc.PermissionDecisionUserNotAvailable].
//
// Use the variant types directly:
//
// &rpc.PermissionDecisionApproveOnce{}
// &rpc.PermissionDecisionReject{Feedback: &feedback}
// &rpc.PermissionDecisionUserNotAvailable{}
// &rpc.PermissionDecisionNoResult{} // decline to respond; another client may answer
type PermissionHandlerFunc func(request PermissionRequest, invocation PermissionInvocation) (rpc.PermissionDecision, 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
}
// ExitPlanModeRequest represents a request to exit plan mode and continue with a selected action.
type ExitPlanModeRequest struct {
Summary string `json:"summary"`
PlanContent string `json:"planContent,omitempty"`
Actions []string `json:"actions"`
RecommendedAction string `json:"recommendedAction"`
}
// ExitPlanModeResult is the response to an exit-plan-mode request.
type ExitPlanModeResult struct {
Approved bool `json:"approved"`
SelectedAction string `json:"selectedAction,omitempty"`
Feedback string `json:"feedback,omitempty"`
}
// ExitPlanModeInvocation provides context about an exit-plan-mode request.
type ExitPlanModeInvocation struct {
SessionID string
}
// ExitPlanModeRequestHandler handles exit-plan-mode requests from the agent.
type ExitPlanModeRequestHandler func(request ExitPlanModeRequest, invocation ExitPlanModeInvocation) (ExitPlanModeResult, error)
// AutoModeSwitchRequest represents a request to switch to auto mode after an eligible rate limit.
type AutoModeSwitchRequest struct {
ErrorCode *string `json:"errorCode,omitempty"`
RetryAfterSeconds *float64 `json:"retryAfterSeconds,omitempty"`
}
// AutoModeSwitchInvocation provides context about an auto-mode-switch request.
type AutoModeSwitchInvocation struct {
SessionID string
}
// AutoModeSwitchRequestHandler handles auto-mode-switch requests from the agent.
type AutoModeSwitchRequestHandler func(request AutoModeSwitchRequest, invocation AutoModeSwitchInvocation) (AutoModeSwitchResponse, error)
// PreToolUseHookInput is the input for a pre-tool-use hook
type PreToolUseHookInput struct {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h PreToolUseHookInput) MarshalJSON() ([]byte, error) {
type alias PreToolUseHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *PreToolUseHookInput) UnmarshalJSON(data []byte) error {
type alias PreToolUseHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// 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 {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
ToolResult any `json:"toolResult"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h PostToolUseHookInput) MarshalJSON() ([]byte, error) {
type alias PostToolUseHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *PostToolUseHookInput) UnmarshalJSON(data []byte) error {
type alias PostToolUseHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// 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)
// PostToolUseFailureHookInput is the input for a post-tool-use-failure hook.
//
// Fires after a tool execution whose result was "failure". The CLI extracts
// the failure message from the tool result and passes it as the Error field
// (rather than passing the full result object).
type PostToolUseFailureHookInput struct {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
// Error is the failure message from the tool's result.
Error string `json:"error"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h PostToolUseFailureHookInput) MarshalJSON() ([]byte, error) {
type alias PostToolUseFailureHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *PostToolUseFailureHookInput) UnmarshalJSON(data []byte) error {
type alias PostToolUseFailureHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// PostToolUseFailureHookOutput is the output for a post-tool-use-failure hook.
//
// Only AdditionalContext is consumed by the host CLI — it is appended as
// hidden guidance to the model alongside the failed tool result.
type PostToolUseFailureHookOutput struct {
AdditionalContext string `json:"additionalContext,omitempty"`
}
// PostToolUseFailureHandler handles post-tool-use-failure hook invocations.
type PostToolUseFailureHandler func(input PostToolUseFailureHookInput, invocation HookInvocation) (*PostToolUseFailureHookOutput, error)
// UserPromptSubmittedHookInput is the input for a user-prompt-submitted hook
type UserPromptSubmittedHookInput struct {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Prompt string `json:"prompt"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h UserPromptSubmittedHookInput) MarshalJSON() ([]byte, error) {
type alias UserPromptSubmittedHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *UserPromptSubmittedHookInput) UnmarshalJSON(data []byte) error {
type alias UserPromptSubmittedHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// 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 {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Source string `json:"source"` // "startup", "resume", "new"
InitialPrompt string `json:"initialPrompt,omitempty"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h SessionStartHookInput) MarshalJSON() ([]byte, error) {
type alias SessionStartHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *SessionStartHookInput) UnmarshalJSON(data []byte) error {
type alias SessionStartHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// 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 {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Reason string `json:"reason"` // "complete", "error", "abort", "timeout", "user_exit"
FinalMessage string `json:"finalMessage,omitempty"`
Error string `json:"error,omitempty"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h SessionEndHookInput) MarshalJSON() ([]byte, error) {
type alias SessionEndHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *SessionEndHookInput) UnmarshalJSON(data []byte) error {
type alias SessionEndHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// 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 {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Error string `json:"error"`
ErrorContext string `json:"errorContext"` // "model_call", "tool_execution", "system", "user_input"
Recoverable bool `json:"recoverable"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h ErrorOccurredHookInput) MarshalJSON() ([]byte, error) {
type alias ErrorOccurredHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *ErrorOccurredHookInput) UnmarshalJSON(data []byte) error {
type alias ErrorOccurredHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// 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)
// PreMcpToolCallHookInput is the input for a pre-mcp-tool-call hook
type PreMcpToolCallHookInput struct {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ServerName string `json:"serverName"`
ToolName string `json:"toolName"`
Arguments any `json:"arguments,omitempty"`
ToolCallID string `json:"toolCallId,omitempty"`
Meta any `json:"_meta,omitempty"`
}
// MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h PreMcpToolCallHookInput) MarshalJSON() ([]byte, error) {
type alias PreMcpToolCallHookInput
return json.Marshal(&struct {
Timestamp int64 `json:"timestamp"`
alias
}{Timestamp: h.Timestamp.UnixMilli(), alias: alias(h)})
}
// UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
func (h *PreMcpToolCallHookInput) UnmarshalJSON(data []byte) error {
type alias PreMcpToolCallHookInput
aux := &struct {
Timestamp int64 `json:"timestamp"`
*alias
}{alias: (*alias)(h)}
if err := json.Unmarshal(data, aux); err != nil {
return err
}
h.Timestamp = time.UnixMilli(aux.Timestamp)
return nil
}
// PreMcpToolCallHookOutput is the output for a pre-mcp-tool-call hook
type PreMcpToolCallHookOutput struct {
MetaToUse any `json:"metaToUse"`
}
// PreMcpToolCallHandler handles pre-mcp-tool-call hook invocations
type PreMcpToolCallHandler func(input PreMcpToolCallHookInput, invocation HookInvocation) (*PreMcpToolCallHookOutput, 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
OnPostToolUseFailure PostToolUseFailureHandler
OnUserPromptSubmitted UserPromptSubmittedHandler
OnSessionStart SessionStartHandler
OnSessionEnd SessionEndHandler
OnErrorOccurred ErrorOccurredHandler
OnPreMcpToolCall PreMcpToolCallHandler
}
// 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.
//
// The Tools field controls which tools from the server are exposed:
// - nil (omitted from the wire): all tools (CLI default)
// - &[]string{"*"}: explicit "all tools"
// - &[]string{}: no tools
// - &[]string{"foo","bar"}: only those tools
//
// The pointer-to-slice form is required so that a nil pointer (omitted from
// the wire) is distinguishable from a non-nil pointer to an empty slice
// (sent as `"tools": []`).
type MCPStdioServerConfig struct {
Tools *[]string `json:"tools,omitempty"`
Timeout int `json:"timeout,omitempty"`
Command string `json:"command"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
WorkingDirectory 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).
//
// See [MCPStdioServerConfig] for the semantics of the Tools field.
type MCPHTTPServerConfig struct {
Tools *[]string `json:"tools,omitempty"`
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"`
// Skills is the list of skill names to preload into this agent's context at startup (opt-in; omit for none)
Skills []string `json:"skills,omitempty"`
// Model is the 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.
Model string `json:"model,omitempty"`
}
// DefaultAgentConfig configures the default agent (the built-in agent that handles turns when no custom agent is selected).
// Use ExcludedTools to hide specific tools from the default agent while keeping
// them available to custom sub-agents.
type DefaultAgentConfig struct {
// ExcludedTools is a list of tool names to exclude from the default agent.
// These tools remain available to custom sub-agents that reference them in their Tools list.
ExcludedTools []string `json:"excludedTools,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"`
}
// SessionFsCapabilities declares optional provider capabilities.
type SessionFsCapabilities struct {
// Sqlite indicates whether the provider supports SQLite query/exists operations.
Sqlite bool
}
// SessionFsConfig configures a custom session filesystem provider.
type SessionFsConfig struct {
// InitialWorkingDirectory is the initial working directory for sessions.
InitialWorkingDirectory 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.SessionFsSetProviderConventions
// Capabilities declares optional provider capabilities such as SQLite support.
Capabilities *SessionFsCapabilities
}
// 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. A Tool with a nil Handler
// is declaration-only; the consumer must resolve its calls via pending tool RPCs.
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 an optional handler for permission requests from the server.
// When nil, permission requests are surfaced as events and left pending for the
// consumer to resolve via pending permission RPCs.
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 non-nil and true, assistant.message_delta and assistant.reasoning_delta
// events with deltaContent are sent as the response is generated.
// When nil, the runtime decides (currently defaults to non-streaming).
Streaming *bool
// IncludeSubAgentStreamingEvents includes sub-agent streaming events in the
// event stream. When true, streaming delta events from sub-agents (e.g.,
// assistant.message_delta, assistant.reasoning_delta, assistant.streaming_delta
// with agentId set) are forwarded to this connection. When false, only
// non-streaming sub-agent events and subagent.* lifecycle events are forwarded;
// streaming deltas from sub-agents are suppressed. When nil, defaults to true.
IncludeSubAgentStreamingEvents *bool
// Provider configures a custom model provider (BYOK)
Provider *ProviderConfig
// EnableSessionTelemetry enables or disables internal session telemetry for this session.
// When false, disables session telemetry. When nil (the default) or true,
// telemetry is enabled for GitHub-authenticated sessions. When a custom
// Provider (BYOK) is configured, session telemetry is always disabled
// regardless of this setting. This is independent of the OpenTelemetry
// configuration in ClientOptions.Telemetry.
EnableSessionTelemetry *bool
// 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
// DefaultAgent configures the default agent (the built-in agent that handles turns when no custom agent is selected).
// Use ExcludedTools to hide tools from the default agent while keeping them available to sub-agents.
DefaultAgent *DefaultAgentConfig
// 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
// InstructionDirectories is a list of additional directories to search for custom instruction files
InstructionDirectories []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
// CreateSessionFsProvider supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFs is configured.
CreateSessionFsProvider func(session *Session) SessionFsProvider
// 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
// OnExitPlanModeRequest is a handler for exit-plan-mode requests from the server.
// When provided, enables exitPlanMode.request callbacks for the session.
OnExitPlanModeRequest ExitPlanModeRequestHandler
// OnAutoModeSwitchRequest is a handler for auto-mode-switch requests from the server.
// When provided, enables autoModeSwitch.request callbacks for the session.
OnAutoModeSwitchRequest AutoModeSwitchRequestHandler
// GitHubToken is an optional per-session GitHub token used for authentication.
// When provided, the session authenticates as the token's owner instead of
// using the global client-level auth.
GitHubToken string `json:"-"`
// RemoteSession controls per-session remote behavior:
// - "off" — local only, no remote export (default)
// - "export" — export session events to GitHub without enabling remote steering
// - "on" — export to GitHub AND enable remote steering
RemoteSession rpc.RemoteSessionMode
// Cloud creates a remote session in the cloud instead of a local session.
// The optional repository is associated with the cloud session.
Cloud *CloudSessionOptions
// Canvases declares canvases this session provides. Sent over the wire on
// `session.create`. CanvasHandler must be set when this is non-empty (the
// SDK does not enforce this — declarations without a handler will surface
// canvas RPCs that return a canvas_handler_unset error envelope).
Canvases []CanvasDeclaration
// RequestCanvasRenderer asks the host to enable canvas rendering for this session.
RequestCanvasRenderer *bool
// RequestExtensions asks the host to surface declared canvases as agent-visible extensions.
RequestExtensions *bool
// CanvasHandler receives inbound canvas.open / canvas.close / canvas.invokeAction
// requests for this session. The SDK does not maintain a per-canvas registry;
// the handler must dispatch on CanvasProviderOpenRequest.CanvasID itself.
CanvasHandler CanvasHandler `json:"-"`
// ExtensionInfo identifies the stable extension providing this session's canvases.
ExtensionInfo *ExtensionInfo
}
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
OverridesBuiltInTool bool `json:"overridesBuiltInTool,omitempty"`