-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathtypes.go
More file actions
935 lines (823 loc) · 38.9 KB
/
types.go
File metadata and controls
935 lines (823 loc) · 38.9 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
package copilot
import (
"context"
"encoding/json"
)
// 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)
// 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
}
// 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"
)
// SectionOverride defines an override operation for a single system prompt section.
type SectionOverride struct {
// Action is the operation to perform: "replace", "remove", "append", or "prepend".
Action string `json:"action"`
// Content for the override. Optional for all actions. Ignored for "remove".
Content string `json:"content,omitempty"`
}
// 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
}
// MCPLocalServerConfig configures a local/stdio MCP server
type MCPLocalServerConfig struct {
Tools []string `json:"tools"`
Type string `json:"type,omitempty"` // "local" or "stdio"
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"`
}
// MCPRemoteServerConfig configures a remote MCP server (HTTP or SSE)
type MCPRemoteServerConfig struct {
Tools []string `json:"tools"`
Type string `json:"type"` // "http" or "sse"
Timeout int `json:"timeout,omitempty"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
// MCPServerConfig can be either MCPLocalServerConfig or MCPRemoteServerConfig
// Use a map[string]any for flexibility, or create separate configs
type MCPServerConfig map[string]any
// 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"`
}
// 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
// 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
// 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
}
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"`
}
// 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
// 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
// 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
}
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"`
}
// 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"`
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"`
SkillDirectories []string `json:"skillDirectories,omitempty"`
DisabledSkills []string `json:"disabledSkills,omitempty"`
InfiniteSessions *InfiniteSessionConfig `json:"infiniteSessions,omitempty"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
// createSessionResponse is the response from session.create
type createSessionResponse struct {
SessionID string `json:"sessionId"`
WorkspacePath string `json:"workspacePath"`
}
// 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"`
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"`
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"`
SkillDirectories []string `json:"skillDirectories,omitempty"`
DisabledSkills []string `json:"disabledSkills,omitempty"`
InfiniteSessions *InfiniteSessionConfig `json:"infiniteSessions,omitempty"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
// resumeSessionResponse is the response from session.resume
type resumeSessionResponse struct {
SessionID string `json:"sessionId"`
WorkspacePath string `json:"workspacePath"`
}
type hooksInvokeRequest struct {
SessionID string `json:"sessionId"`
Type string `json:"hookType"`
Input json.RawMessage `json:"input"`
}
// listSessionsRequest is the request for session.list
type listSessionsRequest struct {
Filter *SessionListFilter `json:"filter,omitempty"`
}
// listSessionsResponse is the response from session.list
type listSessionsResponse struct {
Sessions []SessionMetadata `json:"sessions"`
}
// deleteSessionRequest is the request for session.delete
type deleteSessionRequest struct {
SessionID string `json:"sessionId"`
}
// deleteSessionResponse is the response from session.delete
type deleteSessionResponse struct {
Success bool `json:"success"`
Error *string `json:"error,omitempty"`
}
// getLastSessionIDRequest is the request for session.getLastId
type getLastSessionIDRequest struct{}
// getLastSessionIDResponse is the response from session.getLastId
type getLastSessionIDResponse struct {
SessionID *string `json:"sessionId,omitempty"`
}
// getForegroundSessionRequest is the request for session.getForeground
type getForegroundSessionRequest struct{}
// getForegroundSessionResponse is the response from session.getForeground
type getForegroundSessionResponse struct {
SessionID *string `json:"sessionId,omitempty"`
WorkspacePath *string `json:"workspacePath,omitempty"`
}
// setForegroundSessionRequest is the request for session.setForeground
type setForegroundSessionRequest struct {
SessionID string `json:"sessionId"`
}
// setForegroundSessionResponse is the response from session.setForeground
type setForegroundSessionResponse struct {
Success bool `json:"success"`
Error *string `json:"error,omitempty"`
}
type pingRequest struct {
Message string `json:"message,omitempty"`
}
// PingResponse is the response from a ping request
type PingResponse struct {
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
ProtocolVersion *int `json:"protocolVersion,omitempty"`
}
// getStatusRequest is the request for status.get
type getStatusRequest struct{}
// GetStatusResponse is the response from status.get
type GetStatusResponse struct {
Version string `json:"version"`
ProtocolVersion int `json:"protocolVersion"`
}
// getAuthStatusRequest is the request for auth.getStatus
type getAuthStatusRequest struct{}
// GetAuthStatusResponse is the response from auth.getStatus
type GetAuthStatusResponse struct {
IsAuthenticated bool `json:"isAuthenticated"`
AuthType *string `json:"authType,omitempty"`
Host *string `json:"host,omitempty"`
Login *string `json:"login,omitempty"`
StatusMessage *string `json:"statusMessage,omitempty"`
}
// listModelsRequest is the request for models.list
type listModelsRequest struct{}
// listModelsResponse is the response from models.list
type listModelsResponse struct {
Models []ModelInfo `json:"models"`
}
// sessionGetMessagesRequest is the request for session.getMessages
type sessionGetMessagesRequest struct {
SessionID string `json:"sessionId"`
}
// sessionGetMessagesResponse is the response from session.getMessages
type sessionGetMessagesResponse struct {
Events []SessionEvent `json:"events"`
}
// sessionDestroyRequest is the request for session.destroy
type sessionDestroyRequest struct {
SessionID string `json:"sessionId"`
}
// sessionAbortRequest is the request for session.abort
type sessionAbortRequest struct {
SessionID string `json:"sessionId"`
}
type sessionSendRequest struct {
SessionID string `json:"sessionId"`
Prompt string `json:"prompt"`
Attachments []Attachment `json:"attachments,omitempty"`
Mode string `json:"mode,omitempty"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
// sessionSendResponse is the response from session.send
type sessionSendResponse struct {
MessageID string `json:"messageId"`
}
// sessionEventRequest is the request for session event notifications
type sessionEventRequest struct {
SessionID string `json:"sessionId"`
Event SessionEvent `json:"event"`
}
// userInputRequest represents a request for user input from the agent
type userInputRequest struct {
SessionID string `json:"sessionId"`
Question string `json:"question"`
Choices []string `json:"choices,omitempty"`
AllowFreeform *bool `json:"allowFreeform,omitempty"`
}
// userInputResponse represents the user's response to an input request
type userInputResponse struct {
Answer string `json:"answer"`
WasFreeform bool `json:"wasFreeform"`
}