Documentation
¶
Overview ¶
Package copilot provides a Go SDK for interacting with the GitHub Copilot CLI.
The copilot package enables Go applications to communicate with the Copilot CLI server, create and manage conversation sessions, and integrate custom tools.
Basic usage:
client := copilot.NewClient(nil)
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-4",
})
if err != nil {
log.Fatal(err)
}
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
fmt.Println(d.Content)
}
})
session.Send(copilot.MessageOptions{Prompt: "Hello!"})
Package copilot provides a Go SDK for interacting with the GitHub Copilot CLI.
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func Float64(v float64) *float64
- func GetSDKProtocolVersion() int
- func Int(v int) *int
- func String(v string) *string
- type AbortData
- type AbortReason
- type AgentMode
- type AssistantIntentData
- type AssistantMessageData
- type AssistantMessageDeltaData
- type AssistantMessageStartData
- type AssistantMessageToolRequest
- type AssistantMessageToolRequestType
- type AssistantReasoningData
- type AssistantReasoningDeltaData
- type AssistantStreamingDeltaData
- type AssistantTurnEndData
- type AssistantTurnStartData
- type AssistantUsageAPIEndpoint
- type AssistantUsageCopilotUsageTokenDetail
- type AssistantUsageData
- type Attachment
- type AttachmentBlob
- type AttachmentDirectory
- type AttachmentExtensionContext
- type AttachmentFile
- type AttachmentFileLineRange
- type AttachmentGitHubReference
- type AttachmentGitHubReferenceType
- type AttachmentSelection
- type AttachmentSelectionDetails
- type AttachmentSelectionDetailsEnd
- type AttachmentSelectionDetailsStart
- type AttachmentType
- type AutoModeSwitchCompletedData
- type AutoModeSwitchInvocation
- type AutoModeSwitchRequest
- type AutoModeSwitchRequestHandler
- type AutoModeSwitchRequestedData
- type AutoModeSwitchResponse
- type AutopilotObjectiveChangedOperation
- type AutopilotObjectiveChangedStatus
- type AzureProviderOptions
- type CanvasDeclaration
- type CanvasError
- type CanvasHandler
- type CanvasHandlerDefaults
- type CanvasOpenedAvailability
- type CanvasRegistryChangedCanvas
- type CanvasRegistryChangedCanvasAction
- type CapabilitiesChangedData
- type CapabilitiesChangedUI
- type Client
- func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Session, error)
- func (c *Client) DeleteSession(ctx context.Context, sessionID string) error
- func (c *Client) ForceStop()
- func (c *Client) GetAuthStatus(ctx context.Context) (*GetAuthStatusResponse, error)
- func (c *Client) GetForegroundSessionID(ctx context.Context) (*string, error)
- func (c *Client) GetLastSessionID(ctx context.Context) (*string, error)
- func (c *Client) GetSessionMetadata(ctx context.Context, sessionID string) (*SessionMetadata, error)
- func (c *Client) GetStatus(ctx context.Context) (*GetStatusResponse, error)
- func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error)
- func (c *Client) ListSessions(ctx context.Context, filter *SessionListFilter) ([]SessionMetadata, error)
- func (c *Client) On(handler SessionLifecycleHandler) func()
- func (c *Client) OnEventType(eventType SessionLifecycleEventType, handler SessionLifecycleHandler) func()
- func (c *Client) Ping(ctx context.Context, message string) (*PingResponse, error)
- func (c *Client) ResumeSession(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)
- func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)
- func (c *Client) RuntimePort() int
- func (c *Client) SetForegroundSessionID(ctx context.Context, sessionID string) error
- func (c *Client) Start(ctx context.Context) error
- func (c *Client) Stop() error
- type ClientMode
- type ClientOptions
- type CloudSessionOptions
- type CloudSessionRepository
- type CommandCompletedData
- type CommandContext
- type CommandDefinition
- type CommandExecuteData
- type CommandHandler
- type CommandQueuedData
- type CommandsChangedCommand
- type CommandsChangedData
- type CompactionCompleteCompactionTokensUsed
- type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail
- type ContextTier
- type CustomAgentConfig
- type CustomAgentsUpdatedAgent
- type CustomNotificationPayload
- type DefaultAgentConfig
- type ElicitationAction
- type ElicitationCompletedAction
- type ElicitationCompletedBooleanContent
- type ElicitationCompletedContent
- type ElicitationCompletedData
- type ElicitationCompletedNumberContent
- type ElicitationCompletedStringArrayContent
- type ElicitationCompletedStringContent
- type ElicitationContext
- type ElicitationFieldValue
- type ElicitationHandler
- type ElicitationRequestedData
- type ElicitationRequestedMode
- type ElicitationRequestedSchema
- type ElicitationRequestedSchemaType
- type ElicitationResult
- type ElicitationSchema
- type EmbeddedBlobResourceContents
- type EmbeddedTextResourceContents
- type ErrorOccurredHandler
- type ErrorOccurredHookInput
- type ErrorOccurredHookOutput
- type ExitPlanModeAction
- type ExitPlanModeCompletedData
- type ExitPlanModeInvocation
- type ExitPlanModeRequest
- type ExitPlanModeRequestHandler
- type ExitPlanModeRequestedData
- type ExitPlanModeResult
- type ExtensionInfo
- type ExtensionsLoadedExtension
- type ExtensionsLoadedExtensionSource
- type ExtensionsLoadedExtensionStatus
- type ExternalToolCompletedData
- type ExternalToolRequestedData
- type GetAuthStatusResponse
- type GetStatusResponse
- type HandoffRepository
- type HandoffSourceType
- type HookEndData
- type HookEndError
- type HookInvocation
- type HookProgressData
- type HookStartData
- type InfiniteSessionConfig
- type LargeToolOutputConfig
- type LogOptions
- type MCPAppToolCallCompleteData
- type MCPAppToolCallCompleteError
- type MCPAppToolCallCompleteToolMeta
- type MCPAppToolCallCompleteToolMetaUI
- type MCPHTTPServerConfig
- type MCPOauthCompletedData
- type MCPOauthRequiredData
- type MCPOauthRequiredStaticClientConfig
- type MCPOauthRequiredStaticClientConfigGrantType
- type MCPServerConfig
- type MCPServerSource
- type MCPServerStatus
- type MCPServerTransport
- type MCPServersLoadedServer
- type MCPStdioServerConfig
- type MessageOptions
- type ModelBilling
- type ModelCallFailureData
- type ModelCallFailureSource
- type ModelCapabilities
- type ModelCapabilitiesOverride
- type ModelCapabilitiesOverrideLimits
- type ModelCapabilitiesOverrideLimitsVision
- type ModelCapabilitiesOverrideSupports
- type ModelInfo
- type ModelLimits
- type ModelPolicy
- type ModelSupports
- type ModelVisionLimits
- type PendingMessagesModifiedData
- type PermissionApproved
- type PermissionApprovedForLocation
- type PermissionApprovedForSession
- type PermissionCancelled
- type PermissionCompletedData
- type PermissionDeniedByContentExclusionPolicy
- type PermissionDeniedByPermissionRequestHook
- type PermissionDeniedByRules
- type PermissionDeniedInteractivelyByUser
- type PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser
- type PermissionHandlerFunc
- type PermissionInvocation
- type PermissionPromptRequest
- type PermissionPromptRequestCommands
- type PermissionPromptRequestCustomTool
- type PermissionPromptRequestExtensionManagement
- type PermissionPromptRequestExtensionPermissionAccess
- type PermissionPromptRequestHook
- type PermissionPromptRequestKind
- type PermissionPromptRequestMCP
- type PermissionPromptRequestMemory
- type PermissionPromptRequestPath
- type PermissionPromptRequestPathAccessKind
- type PermissionPromptRequestRead
- type PermissionPromptRequestURL
- type PermissionPromptRequestWrite
- type PermissionRequest
- type PermissionRequestCommand
- type PermissionRequestCustomTool
- type PermissionRequestExtensionManagement
- type PermissionRequestExtensionPermissionAccess
- type PermissionRequestHook
- type PermissionRequestKind
- type PermissionRequestMCP
- type PermissionRequestMemory
- type PermissionRequestMemoryAction
- type PermissionRequestMemoryDirection
- type PermissionRequestRead
- type PermissionRequestShell
- type PermissionRequestShellCommand
- type PermissionRequestShellPossibleURL
- type PermissionRequestURL
- type PermissionRequestWrite
- type PermissionRequestedData
- type PermissionResult
- type PermissionResultKind
- type PermissionRule
- type PingResponse
- type PlanChangedOperation
- type PossibleURL
- type PostToolUseFailureHandler
- type PostToolUseFailureHookInput
- type PostToolUseFailureHookOutput
- type PostToolUseHandler
- type PostToolUseHookInput
- type PostToolUseHookOutput
- type PreMCPToolCallHandler
- type PreMCPToolCallHookInput
- type PreMCPToolCallHookOutput
- type PreToolUseHandler
- type PreToolUseHookInput
- type PreToolUseHookOutput
- type ProviderConfig
- type RawPermissionPromptRequest
- type RawPermissionRequest
- type RawPermissionResult
- type RawSessionEventData
- type RawSystemNotification
- type RawToolExecutionCompleteContent
- type ReasoningSummary
- type ResumeSessionConfig
- type RuntimeConnection
- type SamplingCompletedData
- type SamplingRequestedData
- type SectionOverride
- type SectionOverrideAction
- type SectionTransformFn
- type Session
- func (s *Session) Abort(ctx context.Context) error
- func (s *Session) Capabilities() SessionCapabilities
- func (s *Session) Disconnect() error
- func (s *Session) GetEvents(ctx context.Context) ([]SessionEvent, error)
- func (s *Session) Log(ctx context.Context, message string, opts *LogOptions) error
- func (s *Session) On(handler SessionEventHandler) func()
- func (s *Session) OpenCanvases() []rpc.OpenCanvasInstance
- func (s *Session) Send(ctx context.Context, options MessageOptions) (string, error)
- func (s *Session) SendAndWait(ctx context.Context, options MessageOptions) (*SessionEvent, error)
- func (s *Session) SendPrompt(ctx context.Context, prompt string) (string, error)
- func (s *Session) SendPromptAndWait(ctx context.Context, prompt string) (*SessionEvent, error)
- func (s *Session) SetModel(ctx context.Context, model string, opts *SetModelOptions) error
- func (s *Session) UI() *SessionUI
- func (s *Session) WorkspacePath() string
- type SessionAutopilotObjectiveChangedData
- type SessionBackgroundTasksChangedData
- type SessionCanvasOpenedData
- type SessionCanvasRegistryChangedData
- type SessionCapabilities
- type SessionCompactionCompleteData
- type SessionCompactionStartData
- type SessionConfig
- type SessionContext
- type SessionContextChangedData
- type SessionCustomAgentsUpdatedData
- type SessionCustomNotificationData
- type SessionEndHandler
- type SessionEndHookInput
- type SessionEndHookOutput
- type SessionErrorData
- type SessionEvent
- type SessionEventData
- type SessionEventHandler
- type SessionEventType
- type SessionExtensionsAttachmentsPushedData
- type SessionExtensionsLoadedData
- type SessionFSCapabilities
- type SessionFSConfig
- type SessionFSFileInfo
- type SessionFSProvider
- type SessionFSSqliteProvider
- type SessionFSSqliteQueryResult
- type SessionHandoffData
- type SessionHooks
- type SessionIdleData
- type SessionInfoData
- type SessionLifecycleEvent
- type SessionLifecycleEventMetadata
- type SessionLifecycleEventType
- type SessionLifecycleHandler
- type SessionListFilter
- type SessionMCPServerStatusChangedData
- type SessionMCPServersLoadedData
- type SessionMetadata
- type SessionMode
- type SessionModeChangedData
- type SessionModelChangeData
- type SessionPermissionsChangedData
- type SessionPlanChangedData
- type SessionRemoteSteerableChangedData
- type SessionResumeData
- type SessionScheduleCancelledData
- type SessionScheduleCreatedData
- type SessionShutdownData
- type SessionSkillsLoadedData
- type SessionSnapshotRewindData
- type SessionStartData
- type SessionStartHandler
- type SessionStartHookInput
- type SessionStartHookOutput
- type SessionTaskCompleteData
- type SessionTitleChangedData
- type SessionToolsUpdatedData
- type SessionTruncationData
- type SessionUI
- func (ui *SessionUI) Confirm(ctx context.Context, message string) (bool, error)
- func (ui *SessionUI) Elicitation(ctx context.Context, message string, requestedSchema ElicitationSchema) (*ElicitationResult, error)
- func (ui *SessionUI) Input(ctx context.Context, message string, opts *UIInputOptions) (string, bool, error)
- func (ui *SessionUI) Select(ctx context.Context, message string, options []string) (string, bool, error)
- type SessionUsageInfoData
- type SessionWarningData
- type SessionWorkspaceFileChangedData
- type SetModelOptions
- type ShutdownCodeChanges
- type ShutdownModelMetric
- type ShutdownModelMetricRequests
- type ShutdownModelMetricTokenDetail
- type ShutdownModelMetricUsage
- type ShutdownTokenDetail
- type ShutdownType
- type SkillInvokedData
- type SkillInvokedTrigger
- type SkillSource
- type SkillsLoadedSkill
- type StdioConnection
- type SubagentCompletedData
- type SubagentDeselectedData
- type SubagentFailedData
- type SubagentSelectedData
- type SubagentStartedData
- type SystemMessageAppendConfig
- type SystemMessageConfig
- type SystemMessageData
- type SystemMessageMetadata
- type SystemMessageReplaceConfig
- type SystemMessageRole
- type SystemNotification
- type SystemNotificationAgentCompleted
- type SystemNotificationAgentCompletedStatus
- type SystemNotificationAgentIdle
- type SystemNotificationData
- type SystemNotificationInstructionDiscovered
- type SystemNotificationNewInboxMessage
- type SystemNotificationShellCompleted
- type SystemNotificationShellDetachedCompleted
- type SystemNotificationType
- type TCPConnection
- type TelemetryConfig
- type Tool
- type ToolBinaryResult
- type ToolExecutionCompleteContent
- type ToolExecutionCompleteContentAudio
- type ToolExecutionCompleteContentImage
- type ToolExecutionCompleteContentResource
- type ToolExecutionCompleteContentResourceDetails
- type ToolExecutionCompleteContentResourceLink
- type ToolExecutionCompleteContentResourceLinkIcon
- type ToolExecutionCompleteContentResourceLinkIconTheme
- type ToolExecutionCompleteContentTerminal
- type ToolExecutionCompleteContentText
- type ToolExecutionCompleteContentType
- type ToolExecutionCompleteData
- type ToolExecutionCompleteError
- type ToolExecutionCompleteResult
- type ToolExecutionCompleteToolDescription
- type ToolExecutionCompleteToolDescriptionMeta
- type ToolExecutionCompleteToolDescriptionMetaUI
- type ToolExecutionCompleteToolDescriptionMetaUIVisibility
- type ToolExecutionCompleteUIResource
- type ToolExecutionCompleteUIResourceMeta
- type ToolExecutionCompleteUIResourceMetaUI
- type ToolExecutionCompleteUIResourceMetaUICsp
- type ToolExecutionCompleteUIResourceMetaUIPermissions
- type ToolExecutionCompleteUIResourceMetaUIPermissionsCamera
- type ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite
- type ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation
- type ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone
- type ToolExecutionPartialResultData
- type ToolExecutionProgressData
- type ToolExecutionStartData
- type ToolHandler
- type ToolInvocation
- type ToolResult
- type ToolSet
- type ToolUserRequestedData
- type UICapabilities
- type UIInputOptions
- type URIConnection
- type UserInputCompletedData
- type UserInputHandler
- type UserInputInvocation
- type UserInputRequest
- type UserInputRequestedData
- type UserInputResponse
- type UserMessageAgentMode
- type UserMessageData
- type UserPromptSubmittedHandler
- type UserPromptSubmittedHookInput
- type UserPromptSubmittedHookOutput
- type UserToolSessionApproval
- type UserToolSessionApprovalCommands
- type UserToolSessionApprovalCustomTool
- type UserToolSessionApprovalExtensionManagement
- type UserToolSessionApprovalExtensionPermissionAccess
- type UserToolSessionApprovalKind
- type UserToolSessionApprovalMCP
- type UserToolSessionApprovalMemory
- type UserToolSessionApprovalRead
- type UserToolSessionApprovalWrite
- type WorkingDirectoryContext
- type WorkingDirectoryContextHostType
- type WorkspaceFileChangedOperation
Constants ¶
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" )
Known system message section identifiers for the "customize" mode.
const ( AgentModeInteractive = rpc.SendAgentModeInteractive AgentModePlan = rpc.SendAgentModePlan AgentModeAutopilot = rpc.SendAgentModeAutopilot AgentModeShell = rpc.SendAgentModeShell )
AgentMode values supported by the runtime.
const ( AbortReasonRemoteCommand = rpc.AbortReasonRemoteCommand AbortReasonUserAbort = rpc.AbortReasonUserAbort AbortReasonUserInitiated = rpc.AbortReasonUserInitiated AssistantMessageToolRequestTypeCustom = rpc.AssistantMessageToolRequestTypeCustom AssistantMessageToolRequestTypeFunction = rpc.AssistantMessageToolRequestTypeFunction AssistantUsageAPIEndpointChatCompletions = rpc.AssistantUsageAPIEndpointChatCompletions AssistantUsageAPIEndpointResponses = rpc.AssistantUsageAPIEndpointResponses AssistantUsageAPIEndpointV1Messages = rpc.AssistantUsageAPIEndpointV1Messages AssistantUsageAPIEndpointWsResponses = rpc.AssistantUsageAPIEndpointWsResponses AttachmentGitHubReferenceTypeDiscussion = rpc.AttachmentGitHubReferenceTypeDiscussion AttachmentGitHubReferenceTypeIssue = rpc.AttachmentGitHubReferenceTypeIssue AttachmentGitHubReferenceTypePr = rpc.AttachmentGitHubReferenceTypePr AttachmentTypeBlob = rpc.AttachmentTypeBlob AttachmentTypeDirectory = rpc.AttachmentTypeDirectory AttachmentTypeExtensionContext = rpc.AttachmentTypeExtensionContext AttachmentTypeFile = rpc.AttachmentTypeFile AttachmentTypeGitHubReference = rpc.AttachmentTypeGitHubReference AttachmentTypeSelection = rpc.AttachmentTypeSelection AutoModeSwitchResponseNo = rpc.AutoModeSwitchResponseNo AutoModeSwitchResponseYes = rpc.AutoModeSwitchResponseYes AutoModeSwitchResponseYesAlways = rpc.AutoModeSwitchResponseYesAlways AutopilotObjectiveChangedOperationCreate = rpc.AutopilotObjectiveChangedOperationCreate AutopilotObjectiveChangedOperationDelete = rpc.AutopilotObjectiveChangedOperationDelete AutopilotObjectiveChangedOperationUpdate = rpc.AutopilotObjectiveChangedOperationUpdate AutopilotObjectiveChangedStatusActive = rpc.AutopilotObjectiveChangedStatusActive AutopilotObjectiveChangedStatusCapReached = rpc.AutopilotObjectiveChangedStatusCapReached AutopilotObjectiveChangedStatusCompleted = rpc.AutopilotObjectiveChangedStatusCompleted AutopilotObjectiveChangedStatusPaused = rpc.AutopilotObjectiveChangedStatusPaused CanvasOpenedAvailabilityReady = rpc.CanvasOpenedAvailabilityReady CanvasOpenedAvailabilityStale = rpc.CanvasOpenedAvailabilityStale ContextTierDefault = rpc.ContextTierDefault ContextTierLongContext = rpc.ContextTierLongContext ElicitationCompletedActionAccept = rpc.ElicitationCompletedActionAccept ElicitationCompletedActionCancel = rpc.ElicitationCompletedActionCancel ElicitationCompletedActionDecline = rpc.ElicitationCompletedActionDecline ElicitationRequestedModeForm = rpc.ElicitationRequestedModeForm ElicitationRequestedModeURL = rpc.ElicitationRequestedModeURL ElicitationRequestedSchemaTypeObject = rpc.ElicitationRequestedSchemaTypeObject ExitPlanModeActionAutopilot = rpc.ExitPlanModeActionAutopilot ExitPlanModeActionAutopilotFleet = rpc.ExitPlanModeActionAutopilotFleet ExitPlanModeActionExitOnly = rpc.ExitPlanModeActionExitOnly ExitPlanModeActionInteractive = rpc.ExitPlanModeActionInteractive ExtensionsLoadedExtensionSourceProject = rpc.ExtensionsLoadedExtensionSourceProject ExtensionsLoadedExtensionSourceUser = rpc.ExtensionsLoadedExtensionSourceUser ExtensionsLoadedExtensionStatusDisabled = rpc.ExtensionsLoadedExtensionStatusDisabled ExtensionsLoadedExtensionStatusFailed = rpc.ExtensionsLoadedExtensionStatusFailed ExtensionsLoadedExtensionStatusRunning = rpc.ExtensionsLoadedExtensionStatusRunning ExtensionsLoadedExtensionStatusStarting = rpc.ExtensionsLoadedExtensionStatusStarting HandoffSourceTypeLocal = rpc.HandoffSourceTypeLocal HandoffSourceTypeRemote = rpc.HandoffSourceTypeRemote MCPOauthRequiredStaticClientConfigGrantTypeClientCredentials = rpc.MCPOauthRequiredStaticClientConfigGrantTypeClientCredentials MCPServerSourceBuiltin = rpc.MCPServerSourceBuiltin MCPServerSourcePlugin = rpc.MCPServerSourcePlugin MCPServerSourceUser = rpc.MCPServerSourceUser MCPServerSourceWorkspace = rpc.MCPServerSourceWorkspace MCPServerStatusConnected = rpc.MCPServerStatusConnected MCPServerStatusDisabled = rpc.MCPServerStatusDisabled MCPServerStatusFailed = rpc.MCPServerStatusFailed MCPServerStatusNeedsAuth = rpc.MCPServerStatusNeedsAuth MCPServerStatusNotConfigured = rpc.MCPServerStatusNotConfigured MCPServerStatusPending = rpc.MCPServerStatusPending MCPServerTransportHTTP = rpc.MCPServerTransportHTTP MCPServerTransportMemory = rpc.MCPServerTransportMemory MCPServerTransportSSE = rpc.MCPServerTransportSSE MCPServerTransportStdio = rpc.MCPServerTransportStdio ModelCallFailureSourceMCPSampling = rpc.ModelCallFailureSourceMCPSampling ModelCallFailureSourceSubagent = rpc.ModelCallFailureSourceSubagent ModelCallFailureSourceTopLevel = rpc.ModelCallFailureSourceTopLevel PermissionPromptRequestKindCommands = rpc.PermissionPromptRequestKindCommands PermissionPromptRequestKindCustomTool = rpc.PermissionPromptRequestKindCustomTool PermissionPromptRequestKindExtensionManagement = rpc.PermissionPromptRequestKindExtensionManagement PermissionPromptRequestKindExtensionPermissionAccess = rpc.PermissionPromptRequestKindExtensionPermissionAccess PermissionPromptRequestKindHook = rpc.PermissionPromptRequestKindHook PermissionPromptRequestKindMCP = rpc.PermissionPromptRequestKindMCP PermissionPromptRequestKindMemory = rpc.PermissionPromptRequestKindMemory PermissionPromptRequestKindPath = rpc.PermissionPromptRequestKindPath PermissionPromptRequestKindRead = rpc.PermissionPromptRequestKindRead PermissionPromptRequestKindURL = rpc.PermissionPromptRequestKindURL PermissionPromptRequestKindWrite = rpc.PermissionPromptRequestKindWrite PermissionPromptRequestPathAccessKindRead = rpc.PermissionPromptRequestPathAccessKindRead PermissionPromptRequestPathAccessKindShell = rpc.PermissionPromptRequestPathAccessKindShell PermissionPromptRequestPathAccessKindWrite = rpc.PermissionPromptRequestPathAccessKindWrite PermissionRequestKindCustomTool = rpc.PermissionRequestKindCustomTool PermissionRequestKindExtensionManagement = rpc.PermissionRequestKindExtensionManagement PermissionRequestKindExtensionPermissionAccess = rpc.PermissionRequestKindExtensionPermissionAccess PermissionRequestKindHook = rpc.PermissionRequestKindHook PermissionRequestKindMCP = rpc.PermissionRequestKindMCP PermissionRequestKindMemory = rpc.PermissionRequestKindMemory PermissionRequestKindRead = rpc.PermissionRequestKindRead PermissionRequestKindShell = rpc.PermissionRequestKindShell PermissionRequestKindURL = rpc.PermissionRequestKindURL PermissionRequestKindWrite = rpc.PermissionRequestKindWrite PermissionRequestMemoryActionStore = rpc.PermissionRequestMemoryActionStore PermissionRequestMemoryActionVote = rpc.PermissionRequestMemoryActionVote PermissionRequestMemoryDirectionDownvote = rpc.PermissionRequestMemoryDirectionDownvote PermissionRequestMemoryDirectionUpvote = rpc.PermissionRequestMemoryDirectionUpvote PermissionResultKindApproved = rpc.PermissionResultKindApproved PermissionResultKindApprovedForLocation = rpc.PermissionResultKindApprovedForLocation PermissionResultKindApprovedForSession = rpc.PermissionResultKindApprovedForSession PermissionResultKindCancelled = rpc.PermissionResultKindCancelled PermissionResultKindDeniedByContentExclusionPolicy = rpc.PermissionResultKindDeniedByContentExclusionPolicy PermissionResultKindDeniedByPermissionRequestHook = rpc.PermissionResultKindDeniedByPermissionRequestHook PermissionResultKindDeniedByRules = rpc.PermissionResultKindDeniedByRules PermissionResultKindDeniedInteractivelyByUser = rpc.PermissionResultKindDeniedInteractivelyByUser PermissionResultKindDeniedNoApprovalRuleAndCouldNotRequestFromUser = rpc.PermissionResultKindDeniedNoApprovalRuleAndCouldNotRequestFromUser PlanChangedOperationCreate = rpc.PlanChangedOperationCreate PlanChangedOperationDelete = rpc.PlanChangedOperationDelete PlanChangedOperationUpdate = rpc.PlanChangedOperationUpdate ReasoningSummaryConcise = rpc.ReasoningSummaryConcise ReasoningSummaryDetailed = rpc.ReasoningSummaryDetailed ReasoningSummaryNone = rpc.ReasoningSummaryNone SessionEventTypeAbort = rpc.SessionEventTypeAbort SessionEventTypeAssistantIntent = rpc.SessionEventTypeAssistantIntent SessionEventTypeAssistantMessage = rpc.SessionEventTypeAssistantMessage SessionEventTypeAssistantMessageDelta = rpc.SessionEventTypeAssistantMessageDelta SessionEventTypeAssistantMessageStart = rpc.SessionEventTypeAssistantMessageStart SessionEventTypeAssistantReasoning = rpc.SessionEventTypeAssistantReasoning SessionEventTypeAssistantReasoningDelta = rpc.SessionEventTypeAssistantReasoningDelta SessionEventTypeAssistantStreamingDelta = rpc.SessionEventTypeAssistantStreamingDelta SessionEventTypeAssistantTurnEnd = rpc.SessionEventTypeAssistantTurnEnd SessionEventTypeAssistantTurnStart = rpc.SessionEventTypeAssistantTurnStart SessionEventTypeAssistantUsage = rpc.SessionEventTypeAssistantUsage SessionEventTypeAutoModeSwitchCompleted = rpc.SessionEventTypeAutoModeSwitchCompleted SessionEventTypeAutoModeSwitchRequested = rpc.SessionEventTypeAutoModeSwitchRequested SessionEventTypeCapabilitiesChanged = rpc.SessionEventTypeCapabilitiesChanged SessionEventTypeCommandCompleted = rpc.SessionEventTypeCommandCompleted SessionEventTypeCommandExecute = rpc.SessionEventTypeCommandExecute SessionEventTypeCommandQueued = rpc.SessionEventTypeCommandQueued SessionEventTypeCommandsChanged = rpc.SessionEventTypeCommandsChanged SessionEventTypeElicitationCompleted = rpc.SessionEventTypeElicitationCompleted SessionEventTypeElicitationRequested = rpc.SessionEventTypeElicitationRequested SessionEventTypeExitPlanModeCompleted = rpc.SessionEventTypeExitPlanModeCompleted SessionEventTypeExitPlanModeRequested = rpc.SessionEventTypeExitPlanModeRequested SessionEventTypeExternalToolCompleted = rpc.SessionEventTypeExternalToolCompleted SessionEventTypeExternalToolRequested = rpc.SessionEventTypeExternalToolRequested SessionEventTypeHookEnd = rpc.SessionEventTypeHookEnd SessionEventTypeHookProgress = rpc.SessionEventTypeHookProgress SessionEventTypeHookStart = rpc.SessionEventTypeHookStart SessionEventTypeMCPAppToolCallComplete = rpc.SessionEventTypeMCPAppToolCallComplete SessionEventTypeMCPOauthCompleted = rpc.SessionEventTypeMCPOauthCompleted SessionEventTypeMCPOauthRequired = rpc.SessionEventTypeMCPOauthRequired SessionEventTypeModelCallFailure = rpc.SessionEventTypeModelCallFailure SessionEventTypePendingMessagesModified = rpc.SessionEventTypePendingMessagesModified SessionEventTypePermissionCompleted = rpc.SessionEventTypePermissionCompleted SessionEventTypePermissionRequested = rpc.SessionEventTypePermissionRequested SessionEventTypeSamplingCompleted = rpc.SessionEventTypeSamplingCompleted SessionEventTypeSamplingRequested = rpc.SessionEventTypeSamplingRequested SessionEventTypeSessionAutopilotObjectiveChanged = rpc.SessionEventTypeSessionAutopilotObjectiveChanged SessionEventTypeSessionBackgroundTasksChanged = rpc.SessionEventTypeSessionBackgroundTasksChanged SessionEventTypeSessionCanvasOpened = rpc.SessionEventTypeSessionCanvasOpened SessionEventTypeSessionCanvasRegistryChanged = rpc.SessionEventTypeSessionCanvasRegistryChanged SessionEventTypeSessionCompactionComplete = rpc.SessionEventTypeSessionCompactionComplete SessionEventTypeSessionCompactionStart = rpc.SessionEventTypeSessionCompactionStart SessionEventTypeSessionContextChanged = rpc.SessionEventTypeSessionContextChanged SessionEventTypeSessionCustomAgentsUpdated = rpc.SessionEventTypeSessionCustomAgentsUpdated SessionEventTypeSessionCustomNotification = rpc.SessionEventTypeSessionCustomNotification SessionEventTypeSessionError = rpc.SessionEventTypeSessionError SessionEventTypeSessionExtensionsAttachmentsPushed = rpc.SessionEventTypeSessionExtensionsAttachmentsPushed SessionEventTypeSessionExtensionsLoaded = rpc.SessionEventTypeSessionExtensionsLoaded SessionEventTypeSessionHandoff = rpc.SessionEventTypeSessionHandoff SessionEventTypeSessionIdle = rpc.SessionEventTypeSessionIdle SessionEventTypeSessionInfo = rpc.SessionEventTypeSessionInfo SessionEventTypeSessionMCPServersLoaded = rpc.SessionEventTypeSessionMCPServersLoaded SessionEventTypeSessionMCPServerStatusChanged = rpc.SessionEventTypeSessionMCPServerStatusChanged SessionEventTypeSessionModeChanged = rpc.SessionEventTypeSessionModeChanged SessionEventTypeSessionModelChange = rpc.SessionEventTypeSessionModelChange SessionEventTypeSessionPermissionsChanged = rpc.SessionEventTypeSessionPermissionsChanged SessionEventTypeSessionPlanChanged = rpc.SessionEventTypeSessionPlanChanged SessionEventTypeSessionRemoteSteerableChanged = rpc.SessionEventTypeSessionRemoteSteerableChanged SessionEventTypeSessionResume = rpc.SessionEventTypeSessionResume SessionEventTypeSessionScheduleCancelled = rpc.SessionEventTypeSessionScheduleCancelled SessionEventTypeSessionScheduleCreated = rpc.SessionEventTypeSessionScheduleCreated SessionEventTypeSessionShutdown = rpc.SessionEventTypeSessionShutdown SessionEventTypeSessionSkillsLoaded = rpc.SessionEventTypeSessionSkillsLoaded SessionEventTypeSessionSnapshotRewind = rpc.SessionEventTypeSessionSnapshotRewind SessionEventTypeSessionStart = rpc.SessionEventTypeSessionStart SessionEventTypeSessionTaskComplete = rpc.SessionEventTypeSessionTaskComplete SessionEventTypeSessionTitleChanged = rpc.SessionEventTypeSessionTitleChanged SessionEventTypeSessionToolsUpdated = rpc.SessionEventTypeSessionToolsUpdated SessionEventTypeSessionTruncation = rpc.SessionEventTypeSessionTruncation SessionEventTypeSessionUsageInfo = rpc.SessionEventTypeSessionUsageInfo SessionEventTypeSessionWarning = rpc.SessionEventTypeSessionWarning SessionEventTypeSessionWorkspaceFileChanged = rpc.SessionEventTypeSessionWorkspaceFileChanged SessionEventTypeSkillInvoked = rpc.SessionEventTypeSkillInvoked SessionEventTypeSubagentCompleted = rpc.SessionEventTypeSubagentCompleted SessionEventTypeSubagentDeselected = rpc.SessionEventTypeSubagentDeselected SessionEventTypeSubagentFailed = rpc.SessionEventTypeSubagentFailed SessionEventTypeSubagentSelected = rpc.SessionEventTypeSubagentSelected SessionEventTypeSubagentStarted = rpc.SessionEventTypeSubagentStarted SessionEventTypeSystemMessage = rpc.SessionEventTypeSystemMessage SessionEventTypeSystemNotification = rpc.SessionEventTypeSystemNotification SessionEventTypeToolExecutionComplete = rpc.SessionEventTypeToolExecutionComplete SessionEventTypeToolExecutionPartialResult = rpc.SessionEventTypeToolExecutionPartialResult SessionEventTypeToolExecutionProgress = rpc.SessionEventTypeToolExecutionProgress SessionEventTypeToolExecutionStart = rpc.SessionEventTypeToolExecutionStart SessionEventTypeToolUserRequested = rpc.SessionEventTypeToolUserRequested SessionEventTypeUserInputCompleted = rpc.SessionEventTypeUserInputCompleted SessionEventTypeUserInputRequested = rpc.SessionEventTypeUserInputRequested SessionEventTypeUserMessage = rpc.SessionEventTypeUserMessage SessionModeAutopilot = rpc.SessionModeAutopilot SessionModeInteractive = rpc.SessionModeInteractive SessionModePlan = rpc.SessionModePlan ShutdownTypeError = rpc.ShutdownTypeError ShutdownTypeRoutine = rpc.ShutdownTypeRoutine SkillInvokedTriggerAgentInvoked = rpc.SkillInvokedTriggerAgentInvoked SkillInvokedTriggerContextLoad = rpc.SkillInvokedTriggerContextLoad SkillInvokedTriggerUserInvoked = rpc.SkillInvokedTriggerUserInvoked SkillSourceBuiltin = rpc.SkillSourceBuiltin SkillSourceCustom = rpc.SkillSourceCustom SkillSourceInherited = rpc.SkillSourceInherited SkillSourcePersonalAgents = rpc.SkillSourcePersonalAgents SkillSourcePersonalCopilot = rpc.SkillSourcePersonalCopilot SkillSourcePlugin = rpc.SkillSourcePlugin SkillSourceProject = rpc.SkillSourceProject SystemMessageRoleDeveloper = rpc.SystemMessageRoleDeveloper SystemMessageRoleSystem = rpc.SystemMessageRoleSystem SystemNotificationAgentCompletedStatusCompleted = rpc.SystemNotificationAgentCompletedStatusCompleted SystemNotificationAgentCompletedStatusFailed = rpc.SystemNotificationAgentCompletedStatusFailed SystemNotificationTypeAgentCompleted = rpc.SystemNotificationTypeAgentCompleted SystemNotificationTypeAgentIdle = rpc.SystemNotificationTypeAgentIdle SystemNotificationTypeInstructionDiscovered = rpc.SystemNotificationTypeInstructionDiscovered SystemNotificationTypeNewInboxMessage = rpc.SystemNotificationTypeNewInboxMessage SystemNotificationTypeShellCompleted = rpc.SystemNotificationTypeShellCompleted SystemNotificationTypeShellDetachedCompleted = rpc.SystemNotificationTypeShellDetachedCompleted ToolExecutionCompleteContentResourceLinkIconThemeDark = rpc.ToolExecutionCompleteContentResourceLinkIconThemeDark ToolExecutionCompleteContentResourceLinkIconThemeLight = rpc.ToolExecutionCompleteContentResourceLinkIconThemeLight ToolExecutionCompleteContentTypeAudio = rpc.ToolExecutionCompleteContentTypeAudio ToolExecutionCompleteContentTypeImage = rpc.ToolExecutionCompleteContentTypeImage ToolExecutionCompleteContentTypeResource = rpc.ToolExecutionCompleteContentTypeResource ToolExecutionCompleteContentTypeResourceLink = rpc.ToolExecutionCompleteContentTypeResourceLink ToolExecutionCompleteContentTypeTerminal = rpc.ToolExecutionCompleteContentTypeTerminal ToolExecutionCompleteContentTypeText = rpc.ToolExecutionCompleteContentTypeText ToolExecutionCompleteToolDescriptionMetaUIVisibilityApp = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibilityApp ToolExecutionCompleteToolDescriptionMetaUIVisibilityModel = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibilityModel UserMessageAgentModeAutopilot = rpc.UserMessageAgentModeAutopilot UserMessageAgentModeInteractive = rpc.UserMessageAgentModeInteractive UserMessageAgentModePlan = rpc.UserMessageAgentModePlan UserMessageAgentModeShell = rpc.UserMessageAgentModeShell UserToolSessionApprovalKindCommands = rpc.UserToolSessionApprovalKindCommands UserToolSessionApprovalKindCustomTool = rpc.UserToolSessionApprovalKindCustomTool UserToolSessionApprovalKindExtensionManagement = rpc.UserToolSessionApprovalKindExtensionManagement UserToolSessionApprovalKindExtensionPermissionAccess = rpc.UserToolSessionApprovalKindExtensionPermissionAccess UserToolSessionApprovalKindMCP = rpc.UserToolSessionApprovalKindMCP UserToolSessionApprovalKindMemory = rpc.UserToolSessionApprovalKindMemory UserToolSessionApprovalKindRead = rpc.UserToolSessionApprovalKindRead UserToolSessionApprovalKindWrite = rpc.UserToolSessionApprovalKindWrite WorkingDirectoryContextHostTypeADO = rpc.WorkingDirectoryContextHostTypeADO WorkingDirectoryContextHostTypeGitHub = rpc.WorkingDirectoryContextHostTypeGitHub WorkspaceFileChangedOperationCreate = rpc.WorkspaceFileChangedOperationCreate WorkspaceFileChangedOperationUpdate = rpc.WorkspaceFileChangedOperationUpdate )
Session-event constants are generated in the rpc package and re-exported here for source compatibility.
const SDKProtocolVersion = 3
SDKProtocolVersion is the SDK protocol version. This must match the version expected by the copilot-agent-runtime server.
Variables ¶
var BuiltInToolsIsolated = []string{
"ask_user",
"task_complete",
"exit_plan_mode",
"task",
"read_agent",
"write_agent",
"list_agents",
"send_inbox",
"context_board",
"skill",
}
BuiltInToolsIsolated lists built-in tools that operate only within the bounds of a single session — no host filesystem access outside the session, no cross-session state, no host environment access, no network. Safe to enable in ModeEmpty scenarios (e.g. multi-tenant servers) without leaking host capabilities.
Contract: tools in this set MUST NOT be extended (even behind options or args) to read or write state outside the session boundary. Adding cross-session or host-state behavior to one of these tools is a breaking change that requires removing it from this set.
var PermissionHandler = struct { // ApproveAll approves all permission requests. ApproveAll PermissionHandlerFunc }{ ApproveAll: func(_ PermissionRequest, _ PermissionInvocation) (rpc.PermissionDecision, error) { return &rpc.PermissionDecisionApproveOnce{}, nil }, }
PermissionHandler provides pre-built OnPermissionRequest implementations.
Functions ¶
func 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 Float64 ¶ added in v0.1.18
Float64 returns a pointer to the given float64 value. Use for setting thresholds: BackgroundCompactionThreshold: Float64(0.80)
func GetSDKProtocolVersion ¶ added in v1.0.0
func GetSDKProtocolVersion() int
GetSDKProtocolVersion returns the SDK protocol version.
Types ¶
type AbortData ¶ added in v0.2.2
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AbortReason ¶ added in v1.0.0
type AbortReason = rpc.AbortReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AgentMode ¶ added in v0.1.24
type AgentMode = rpc.SendAgentMode
AgentMode is the UI mode the agent is in for a given turn. See [MessageOptions.AgentMode].
type AssistantIntentData ¶ added in v0.2.2
type AssistantIntentData = rpc.AssistantIntentData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageData ¶ added in v0.2.2
type AssistantMessageData = rpc.AssistantMessageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageDeltaData ¶ added in v0.2.2
type AssistantMessageDeltaData = rpc.AssistantMessageDeltaData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageStartData ¶ added in v1.0.0
type AssistantMessageStartData = rpc.AssistantMessageStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageToolRequest ¶ added in v0.3.0
type AssistantMessageToolRequest = rpc.AssistantMessageToolRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageToolRequestType ¶ added in v0.3.0
type AssistantMessageToolRequestType = rpc.AssistantMessageToolRequestType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantReasoningData ¶ added in v0.2.2
type AssistantReasoningData = rpc.AssistantReasoningData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantReasoningDeltaData ¶ added in v0.2.2
type AssistantReasoningDeltaData = rpc.AssistantReasoningDeltaData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantStreamingDeltaData ¶ added in v0.2.2
type AssistantStreamingDeltaData = rpc.AssistantStreamingDeltaData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantTurnEndData ¶ added in v0.2.2
type AssistantTurnEndData = rpc.AssistantTurnEndData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantTurnStartData ¶ added in v0.2.2
type AssistantTurnStartData = rpc.AssistantTurnStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageAPIEndpoint ¶ added in v1.0.0
type AssistantUsageAPIEndpoint = rpc.AssistantUsageAPIEndpoint
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageCopilotUsageTokenDetail ¶ added in v0.3.0
type AssistantUsageCopilotUsageTokenDetail = rpc.AssistantUsageCopilotUsageTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageData ¶ added in v0.2.2
type AssistantUsageData = rpc.AssistantUsageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type Attachment ¶
type Attachment = rpc.Attachment
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentBlob ¶ added in v1.0.0
type AttachmentBlob = rpc.AttachmentBlob
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentDirectory ¶ added in v1.0.0
type AttachmentDirectory = rpc.AttachmentDirectory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentExtensionContext ¶ added in v1.0.0
type AttachmentExtensionContext = rpc.AttachmentExtensionContext
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentFile ¶ added in v1.0.0
type AttachmentFile = rpc.AttachmentFile
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentFileLineRange ¶ added in v1.0.0
type AttachmentFileLineRange = rpc.AttachmentFileLineRange
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubReference ¶ added in v1.0.0
type AttachmentGitHubReference = rpc.AttachmentGitHubReference
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubReferenceType ¶ added in v1.0.0
type AttachmentGitHubReferenceType = rpc.AttachmentGitHubReferenceType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelection ¶ added in v1.0.0
type AttachmentSelection = rpc.AttachmentSelection
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelectionDetails ¶ added in v1.0.0
type AttachmentSelectionDetails = rpc.AttachmentSelectionDetails
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelectionDetailsEnd ¶ added in v1.0.0
type AttachmentSelectionDetailsEnd = rpc.AttachmentSelectionDetailsEnd
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelectionDetailsStart ¶ added in v1.0.0
type AttachmentSelectionDetailsStart = rpc.AttachmentSelectionDetailsStart
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentType ¶ added in v0.1.15
type AttachmentType = rpc.AttachmentType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutoModeSwitchCompletedData ¶ added in v0.3.0
type AutoModeSwitchCompletedData = rpc.AutoModeSwitchCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutoModeSwitchInvocation ¶ added in v1.0.0
type AutoModeSwitchInvocation struct {
SessionID string
}
AutoModeSwitchInvocation provides context about an auto-mode-switch request.
type AutoModeSwitchRequest ¶ added in v1.0.0
type AutoModeSwitchRequest struct {
ErrorCode *string `json:"errorCode,omitempty"`
RetryAfterSeconds *float64 `json:"retryAfterSeconds,omitempty"`
}
AutoModeSwitchRequest represents a request to switch to auto mode after an eligible rate limit.
type AutoModeSwitchRequestHandler ¶ added in v1.0.0
type AutoModeSwitchRequestHandler func(request AutoModeSwitchRequest, invocation AutoModeSwitchInvocation) (AutoModeSwitchResponse, error)
AutoModeSwitchRequestHandler handles auto-mode-switch requests from the agent.
type AutoModeSwitchRequestedData ¶ added in v0.3.0
type AutoModeSwitchRequestedData = rpc.AutoModeSwitchRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutoModeSwitchResponse ¶ added in v1.0.0
type AutoModeSwitchResponse = rpc.AutoModeSwitchResponse
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutopilotObjectiveChangedOperation ¶ added in v1.0.0
type AutopilotObjectiveChangedOperation = rpc.AutopilotObjectiveChangedOperation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutopilotObjectiveChangedStatus ¶ added in v1.0.0
type AutopilotObjectiveChangedStatus = rpc.AutopilotObjectiveChangedStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AzureProviderOptions ¶
type AzureProviderOptions struct {
// APIVersion is the Azure API version. Defaults to "2024-10-21".
APIVersion string `json:"apiVersion,omitempty"`
}
AzureProviderOptions contains Azure-specific provider configuration
type CanvasDeclaration ¶ added in v1.0.0
type CanvasDeclaration struct {
// ID is the canvas identifier, unique within the declaring connection.
ID string `json:"id"`
// DisplayName is the human-readable name shown in host UI and canvas pickers.
DisplayName string `json:"displayName"`
// Description is a short, single-sentence description shown to the agent in canvas catalogs.
Description string `json:"description"`
// InputSchema is the JSON Schema for the `input` payload accepted by `canvas.open`.
InputSchema map[string]any `json:"inputSchema,omitzero"`
// Actions are the agent-callable actions this canvas exposes.
Actions []rpc.CanvasAction `json:"actions,omitempty"`
}
CanvasDeclaration is the declarative metadata for a single canvas, sent over the wire on `session.create` / `session.resume`.
Experimental: CanvasDeclaration is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
type CanvasError ¶ added in v1.0.0
type CanvasError struct {
// Code is the machine-readable error code.
Code string `json:"code"`
// Message is the human-readable message.
Message string `json:"message"`
}
CanvasError is a structured error returned from canvas handlers.
Wire envelope:
{ "code": "<code>", "message": "<message>" }
Experimental: CanvasError is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
func CanvasErrorNoHandler ¶ added in v1.0.0
func CanvasErrorNoHandler() *CanvasError
CanvasErrorNoHandler is the default error returned when a custom action has no handler.
func NewCanvasError ¶ added in v1.0.0
func NewCanvasError(code, message string) *CanvasError
NewCanvasError constructs a new error envelope with the given code and message.
func (*CanvasError) Error ¶ added in v1.0.0
func (e *CanvasError) Error() string
Error implements the error interface.
type CanvasHandler ¶ added in v1.0.0
type CanvasHandler interface {
OnOpen(ctx context.Context, c rpc.CanvasProviderOpenRequest) (rpc.CanvasProviderOpenResult, error)
OnClose(ctx context.Context, c rpc.CanvasProviderCloseRequest) error
OnAction(ctx context.Context, c rpc.CanvasProviderInvokeActionRequest) (any, error)
}
CanvasHandler is the provider-side canvas lifecycle handler.
A session installs a single CanvasHandler (via SessionConfig.CanvasHandler). The handler receives every inbound `canvas.open` / `canvas.close` / `canvas.action.invoke` JSON-RPC request the runtime issues for this session and decides — typically by inspecting CanvasProviderOpenRequest.CanvasID — which application-side canvas should handle the call.
The SDK does not maintain a per-canvas registry; multiplexing across declared canvases is the implementor's responsibility.
Embed CanvasHandlerDefaults to inherit no-op defaults for OnClose and a "no handler" error for OnAction.
Experimental: CanvasHandler is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
type CanvasHandlerDefaults ¶ added in v1.0.0
type CanvasHandlerDefaults struct{}
CanvasHandlerDefaults supplies default OnClose / OnAction implementations that consumers can inherit by embedding it in their CanvasHandler.
Example:
type myHandler struct {
copilot.CanvasHandlerDefaults
}
func (h *myHandler) OnOpen(ctx context.Context, c rpc.CanvasProviderOpenRequest) (rpc.CanvasProviderOpenResult, error) { ... }
Experimental: CanvasHandlerDefaults is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
func (CanvasHandlerDefaults) OnAction ¶ added in v1.0.0
func (CanvasHandlerDefaults) OnAction(ctx context.Context, c rpc.CanvasProviderInvokeActionRequest) (any, error)
OnAction returns CanvasErrorNoHandler() by default.
func (CanvasHandlerDefaults) OnClose ¶ added in v1.0.0
func (CanvasHandlerDefaults) OnClose(ctx context.Context, c rpc.CanvasProviderCloseRequest) error
OnClose returns nil by default.
type CanvasOpenedAvailability ¶ added in v1.0.0
type CanvasOpenedAvailability = rpc.CanvasOpenedAvailability
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CanvasRegistryChangedCanvas ¶ added in v1.0.0
type CanvasRegistryChangedCanvas = rpc.CanvasRegistryChangedCanvas
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CanvasRegistryChangedCanvasAction ¶ added in v1.0.0
type CanvasRegistryChangedCanvasAction = rpc.CanvasRegistryChangedCanvasAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CapabilitiesChangedData ¶ added in v0.2.2
type CapabilitiesChangedData = rpc.CapabilitiesChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CapabilitiesChangedUI ¶ added in v0.3.0
type CapabilitiesChangedUI = rpc.CapabilitiesChangedUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type Client ¶
type Client struct {
// RPC provides typed server-scoped RPC methods.
// This field is nil until the client is connected via Start().
RPC *rpc.ServerRPC
// contains filtered or unexported fields
}
Client manages the connection to the Copilot CLI server and provides session management.
The Client can either spawn a CLI server process or connect to an existing server. It handles JSON-RPC communication, session lifecycle, tool execution, and permission requests.
Example:
// Create a client with default options (spawns CLI server using stdio)
client := copilot.NewClient(nil)
// Or connect to an existing server
client := copilot.NewClient(&copilot.ClientOptions{
Connection: copilot.URIConnection{URL: "localhost:3000"},
})
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
func NewClient ¶
func NewClient(options *ClientOptions) *Client
NewClient creates a new Copilot runtime client with the given options.
If options is nil, default options are used (spawns the bundled runtime over stdio). The client is not connected after creation; call Client.Start to connect, or simply call Client.CreateSession/Client.ResumeSession, which auto-start the runtime on first use.
Example:
// Default options: bundled runtime over stdio
client := copilot.NewClient(nil)
// Custom CLI path over stdio
client := copilot.NewClient(&copilot.ClientOptions{
Connection: copilot.StdioConnection{Path: "/usr/local/bin/copilot"},
LogLevel: "debug",
})
// Connect to an already-running runtime
client := copilot.NewClient(&copilot.ClientOptions{
Connection: copilot.URIConnection{URL: "localhost:8080"},
})
func (*Client) CreateSession ¶
func (*Client) DeleteSession ¶ added in v0.1.19
DeleteSession permanently deletes a session and all its data from disk, including conversation history, planning state, and artifacts.
Unlike Session.Disconnect, which only releases in-memory resources and preserves session data for later resumption, DeleteSession is irreversible. The session cannot be resumed after deletion. If the session is in the local sessions map, it will be removed.
Example:
if err := client.DeleteSession(context.Background(), "session-123"); err != nil {
log.Fatal(err)
}
func (*Client) ForceStop ¶
func (c *Client) ForceStop()
ForceStop forcefully stops the CLI server without graceful cleanup.
Use this when Client.Stop fails or takes too long. This method:
- Clears all sessions immediately without destroying them
- Force closes the connection
- Kills the CLI process (if spawned by this client)
Example:
// If normal stop hangs, force stop
done := make(chan struct{})
go func() {
client.Stop()
close(done)
}()
select {
case <-done:
// Stopped successfully
case <-time.After(5 * time.Second):
client.ForceStop()
}
func (*Client) GetAuthStatus ¶ added in v0.1.15
func (c *Client) GetAuthStatus(ctx context.Context) (*GetAuthStatusResponse, error)
GetAuthStatus returns current authentication status
func (*Client) GetForegroundSessionID ¶ added in v0.1.21
GetForegroundSessionID returns the ID of the session currently displayed in the TUI.
This is only available when connecting to a server running in TUI+server mode (--ui-server). Returns nil if no foreground session is set.
Example:
sessionID, err := client.GetForegroundSessionID()
if err != nil {
log.Fatal(err)
}
if sessionID != nil {
fmt.Printf("TUI is displaying session: %s\n", *sessionID)
}
func (*Client) GetLastSessionID ¶ added in v0.1.31
GetLastSessionID returns the ID of the most recently updated session.
This is useful for resuming the last conversation when the session ID was not stored. Returns nil if no sessions exist.
Example:
lastID, err := client.GetLastSessionID(context.Background())
if err != nil {
log.Fatal(err)
}
if lastID != nil {
session, err := client.ResumeSession(context.Background(), *lastID, &copilot.ResumeSessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
}
func (*Client) GetSessionMetadata ¶ added in v0.2.1
func (c *Client) GetSessionMetadata(ctx context.Context, sessionID string) (*SessionMetadata, error)
GetSessionMetadata returns metadata for a specific session by ID.
This provides an efficient O(1) lookup of a single session's metadata instead of listing all sessions. Returns nil if the session is not found.
Example:
metadata, err := client.GetSessionMetadata(context.Background(), "session-123")
if err != nil {
log.Fatal(err)
}
if metadata != nil {
fmt.Printf("Session started at: %s\n", metadata.StartTime)
}
func (*Client) GetStatus ¶ added in v0.1.15
func (c *Client) GetStatus(ctx context.Context) (*GetStatusResponse, error)
GetStatus returns CLI status including version and protocol information
func (*Client) ListModels ¶ added in v0.1.15
ListModels returns available models with their metadata.
Results are cached after the first successful call to avoid rate limiting. The cache is cleared when the client disconnects.
func (*Client) ListSessions ¶ added in v0.1.19
func (c *Client) ListSessions(ctx context.Context, filter *SessionListFilter) ([]SessionMetadata, error)
ListSessions returns metadata about all sessions known to the server.
Returns a list of SessionMetadata for all available sessions, including their IDs, timestamps, optional summaries, and context information.
An optional filter can be provided to filter sessions by working directory, git root, repository, or branch.
Example:
sessions, err := client.ListSessions(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
for _, session := range sessions {
fmt.Printf("Session: %s\n", session.SessionID)
}
Example with filter:
sessions, err := client.ListSessions(context.Background(), &SessionListFilter{Repository: "owner/repo"})
func (*Client) On ¶ added in v0.1.21
func (c *Client) On(handler SessionLifecycleHandler) func()
On subscribes to all session lifecycle events.
Lifecycle events are emitted when sessions are created, deleted, updated, or change foreground/background state (in TUI+server mode).
Returns a function that, when called, unsubscribes the handler.
Example:
unsubscribe := client.On(func(event copilot.SessionLifecycleEvent) {
fmt.Printf("Session %s: %s\n", event.SessionID, event.Type)
})
defer unsubscribe()
func (*Client) OnEventType ¶ added in v0.1.21
func (c *Client) OnEventType(eventType SessionLifecycleEventType, handler SessionLifecycleHandler) func()
OnEventType subscribes to a specific session lifecycle event type.
Returns a function that, when called, unsubscribes the handler.
Example:
unsubscribe := client.OnEventType(copilot.SessionLifecycleForeground, func(event copilot.SessionLifecycleEvent) {
fmt.Printf("Session %s is now in foreground\n", event.SessionID)
})
defer unsubscribe()
func (*Client) Ping ¶
Ping sends a ping request to the server to verify connectivity.
The message parameter is optional and will be echoed back in the response. Returns a PingResponse containing the message and server timestamp, or an error.
Example:
resp, err := client.Ping(context.Background(), "health check")
if err != nil {
log.Printf("Server unreachable: %v", err)
} else {
log.Printf("Server responded at %s", resp.Timestamp)
}
func (*Client) ResumeSession ¶
func (c *Client) ResumeSession(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)
ResumeSession resumes an existing conversation session by its ID.
This is a convenience method that calls Client.ResumeSessionWithOptions. Example:
session, err := client.ResumeSession(context.Background(), "session-123", &copilot.ResumeSessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
func (*Client) ResumeSessionWithOptions ¶
func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)
ResumeSessionWithOptions resumes an existing conversation session with additional configuration.
This allows you to continue a previous conversation, maintaining all conversation history. The session must have been previously created and not deleted.
Example:
session, err := client.ResumeSessionWithOptions(context.Background(), "session-123", &copilot.ResumeSessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Tools: []copilot.Tool{myNewTool},
})
func (*Client) RuntimePort ¶ added in v1.0.0
RuntimePort returns the TCP port the runtime is listening on. Returns 0 if the client is not connected or using stdio transport.
func (*Client) SetForegroundSessionID ¶ added in v0.1.21
SetForegroundSessionID requests the TUI to switch to displaying the specified session.
This is only available when connecting to a server running in TUI+server mode (--ui-server).
Example:
if err := client.SetForegroundSessionID("session-123"); err != nil {
log.Fatal(err)
}
func (*Client) Start ¶
Start starts the CLI server (if not using an external server) and establishes a connection.
If connecting to an external server (via URIConnection), only establishes the connection. Otherwise, spawns the CLI server process and then connects.
This method is called automatically when creating a session if AutoStart is true (default).
Returns an error if the server fails to start or the connection fails.
Example:
client := copilot.NewClient(&copilot.ClientOptions{AutoStart: boolPtr(false)})
if err := client.Start(context.Background()); err != nil {
log.Fatal("Failed to start:", err)
}
// Now ready to create sessions
func (*Client) Stop ¶
Stop stops the CLI server and closes all active sessions.
This method performs graceful cleanup:
- Closes all active sessions (releases in-memory resources)
- Closes the JSON-RPC connection
- Terminates the CLI server process (if spawned by this client)
Note: session data on disk is preserved, so sessions can be resumed later. To permanently remove session data before stopping, call Client.DeleteSession for each session first.
Returns an error that aggregates all errors encountered during cleanup.
Example:
if err := client.Stop(); err != nil {
log.Printf("Cleanup error: %v", err)
}
type ClientMode ¶ added in v1.0.0
type ClientMode string
ClientMode controls the default surface presented to sessions created by the Client. The zero value is ModeCopilotCli, matching the legacy CLI defaults.
Set [ClientOptions.Mode] to ModeEmpty to opt in to multi-tenant safe defaults: no built-in tools by default (callers must specify [SessionConfig.AvailableTools] explicitly), no environment_context section in the system message, telemetry off, custom instructions and remote-custom agents disabled, etc.
const ( // ModeCopilotCli is the default mode; sessions inherit the full Copilot // CLI experience (all built-in tools, host environment_context, etc.). ModeCopilotCli ClientMode = "copilot-cli" // ModeEmpty is the multi-tenant safe-default mode. Sessions start with // no built-in tools, no environment context, and various features // (custom instructions, remote agents, telemetry, plugins) off by // default. Callers can opt back in field-by-field. ModeEmpty ClientMode = "empty" )
type ClientOptions ¶
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
// Mode controls the default tool surface and feature flags presented to
// sessions created by this client. The zero value ([ModeCopilotCli])
// matches legacy CLI defaults. Set to [ModeEmpty] to opt in to
// multi-tenant safe defaults — see [ClientMode] for details.
//
// When Mode is [ModeEmpty], NewClient requires either BaseDirectory,
// SessionFS, or a [URIConnection] so the runtime has persistent storage
// for session state.
Mode ClientMode
}
ClientOptions configures the Client.
type CloudSessionOptions ¶ added in v1.0.0
type CloudSessionOptions struct {
Repository *CloudSessionRepository `json:"repository,omitempty"`
}
CloudSessionOptions configures creation of a remote session in the cloud.
type CloudSessionRepository ¶ added in v1.0.0
type CloudSessionRepository struct {
Owner string `json:"owner"`
Name string `json:"name"`
Branch string `json:"branch,omitempty"`
}
CloudSessionRepository is GitHub repository metadata associated with a cloud session.
type CommandCompletedData ¶ added in v0.2.2
type CommandCompletedData = rpc.CommandCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandContext ¶ added in v0.2.1
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
}
CommandContext provides context about a slash-command invocation.
type CommandDefinition ¶ added in v0.2.1
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
}
CommandDefinition registers a slash-command. Name is shown in the CLI TUI as /name for the user to invoke.
type CommandExecuteData ¶ added in v0.2.2
type CommandExecuteData = rpc.CommandExecuteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandHandler ¶ added in v0.2.1
type CommandHandler func(ctx CommandContext) error
CommandHandler is invoked when a registered slash-command is executed.
type CommandQueuedData ¶ added in v0.2.2
type CommandQueuedData = rpc.CommandQueuedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandsChangedCommand ¶ added in v0.3.0
type CommandsChangedCommand = rpc.CommandsChangedCommand
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandsChangedData ¶ added in v0.2.2
type CommandsChangedData = rpc.CommandsChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompactionCompleteCompactionTokensUsed ¶ added in v0.3.0
type CompactionCompleteCompactionTokensUsed = rpc.CompactionCompleteCompactionTokensUsed
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail ¶ added in v0.3.0
type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail = rpc.CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ContextTier ¶ added in v1.0.0
type ContextTier = rpc.ContextTier
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CustomAgentConfig ¶
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 omits the field
// (all tools); an empty non-nil slice sends "tools": [] (no tools).
Tools []string `json:"tools,omitzero"`
// 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"`
}
CustomAgentConfig configures a custom agent.
type CustomAgentsUpdatedAgent ¶ added in v0.3.0
type CustomAgentsUpdatedAgent = rpc.CustomAgentsUpdatedAgent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CustomNotificationPayload ¶ added in v1.0.0
type CustomNotificationPayload = rpc.CustomNotificationPayload
Session-event types are generated in the rpc package and aliased here for source compatibility.
type DefaultAgentConfig ¶ added in v0.3.0
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"`
}
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 ElicitationAction ¶ added in v1.0.0
type ElicitationAction = rpc.UIElicitationResponseAction
ElicitationAction is the user response to an elicitation request.
const ( ElicitationActionAccept ElicitationAction = rpc.UIElicitationResponseActionAccept ElicitationActionCancel ElicitationAction = rpc.UIElicitationResponseActionCancel ElicitationActionDecline ElicitationAction = rpc.UIElicitationResponseActionDecline )
Elicitation action values.
type ElicitationCompletedAction ¶ added in v0.3.0
type ElicitationCompletedAction = rpc.ElicitationCompletedAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationCompletedBooleanContent ¶ added in v1.0.0
type ElicitationCompletedBooleanContent = rpc.ElicitationCompletedBooleanContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationCompletedContent ¶ added in v1.0.0
type ElicitationCompletedContent = rpc.ElicitationCompletedContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationCompletedData ¶ added in v0.2.2
type ElicitationCompletedData = rpc.ElicitationCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationCompletedNumberContent ¶ added in v1.0.0
type ElicitationCompletedNumberContent = rpc.ElicitationCompletedNumberContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationCompletedStringArrayContent ¶ added in v1.0.0
type ElicitationCompletedStringArrayContent = rpc.ElicitationCompletedStringArrayContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationCompletedStringContent ¶ added in v1.0.0
type ElicitationCompletedStringContent = rpc.ElicitationCompletedStringContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationContext ¶ added in v0.2.1
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 *ElicitationSchema
// Mode is "form" for structured input, "url" for browser redirect.
Mode *ElicitationRequestedMode
// 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
}
ElicitationContext describes an elicitation request from the server, combining the request data with session context. Mirrors the single-argument pattern of CommandContext.
type ElicitationFieldValue ¶ added in v1.0.0
type ElicitationFieldValue = any
ElicitationFieldValue is a primitive value submitted for an elicitation form field. Supported values are string, numeric types, bool, []string, and []any containing strings.
type ElicitationHandler ¶ added in v0.2.1
type ElicitationHandler func(ctx ElicitationContext) (ElicitationResult, error)
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 ElicitationRequestedData ¶ added in v0.2.2
type ElicitationRequestedData = rpc.ElicitationRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationRequestedMode ¶ added in v0.3.0
type ElicitationRequestedMode = rpc.ElicitationRequestedMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationRequestedSchema ¶ added in v0.3.0
type ElicitationRequestedSchema = rpc.ElicitationRequestedSchema
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationRequestedSchemaType ¶ added in v1.0.0
type ElicitationRequestedSchemaType = rpc.ElicitationRequestedSchemaType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationResult ¶ added in v0.2.1
type ElicitationResult struct {
// Action is the user response: accept, decline, or cancel.
Action ElicitationAction `json:"action"`
// Content holds form values submitted by the user when Action is accept.
Content map[string]ElicitationFieldValue `json:"content,omitzero"`
}
ElicitationResult is the user's response to an elicitation dialog.
type ElicitationSchema ¶ added in v1.0.0
type ElicitationSchema struct {
// Properties contains form field definitions keyed by field name.
Properties map[string]any `json:"properties"`
// Required lists field names that must be submitted.
Required []string `json:"required,omitzero"`
}
ElicitationSchema describes the form fields for an elicitation request.
type EmbeddedBlobResourceContents ¶ added in v1.0.0
type EmbeddedBlobResourceContents = rpc.EmbeddedBlobResourceContents
Session-event types are generated in the rpc package and aliased here for source compatibility.
type EmbeddedTextResourceContents ¶ added in v1.0.0
type EmbeddedTextResourceContents = rpc.EmbeddedTextResourceContents
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ErrorOccurredHandler ¶ added in v0.1.20
type ErrorOccurredHandler func(input ErrorOccurredHookInput, invocation HookInvocation) (*ErrorOccurredHookOutput, error)
ErrorOccurredHandler handles error-occurred hook invocations
type ErrorOccurredHookInput ¶ added in v0.1.20
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"`
}
ErrorOccurredHookInput is the input for an error-occurred hook
func (ErrorOccurredHookInput) MarshalJSON ¶ added in v1.0.0
func (h ErrorOccurredHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*ErrorOccurredHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *ErrorOccurredHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type ErrorOccurredHookOutput ¶ added in v0.1.20
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"`
}
ErrorOccurredHookOutput is the output for an error-occurred hook
type ExitPlanModeAction ¶ added in v1.0.0
type ExitPlanModeAction = rpc.ExitPlanModeAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExitPlanModeCompletedData ¶ added in v0.2.2
type ExitPlanModeCompletedData = rpc.ExitPlanModeCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExitPlanModeInvocation ¶ added in v1.0.0
type ExitPlanModeInvocation struct {
SessionID string
}
ExitPlanModeInvocation provides context about an exit-plan-mode request.
type ExitPlanModeRequest ¶ added in v1.0.0
type ExitPlanModeRequest struct {
Summary string `json:"summary"`
PlanContent string `json:"planContent,omitempty"`
Actions []string `json:"actions"`
RecommendedAction string `json:"recommendedAction"`
}
ExitPlanModeRequest represents a request to exit plan mode and continue with a selected action.
type ExitPlanModeRequestHandler ¶ added in v1.0.0
type ExitPlanModeRequestHandler func(request ExitPlanModeRequest, invocation ExitPlanModeInvocation) (ExitPlanModeResult, error)
ExitPlanModeRequestHandler handles exit-plan-mode requests from the agent.
type ExitPlanModeRequestedData ¶ added in v0.2.2
type ExitPlanModeRequestedData = rpc.ExitPlanModeRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExitPlanModeResult ¶ added in v1.0.0
type ExitPlanModeResult struct {
Approved bool `json:"approved"`
SelectedAction string `json:"selectedAction,omitempty"`
Feedback string `json:"feedback,omitempty"`
}
ExitPlanModeResult is the response to an exit-plan-mode request.
type ExtensionInfo ¶ added in v1.0.0
type ExtensionInfo struct {
// Source is the extension namespace/source, e.g. "github-app".
Source string `json:"source"`
// Name is the extension identifier within that source, e.g. "my-app".
Name string `json:"name"`
}
ExtensionInfo carries stable extension identity for session participants that provide canvases.
Experimental: ExtensionInfo is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
type ExtensionsLoadedExtension ¶ added in v0.3.0
type ExtensionsLoadedExtension = rpc.ExtensionsLoadedExtension
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExtensionsLoadedExtensionSource ¶ added in v0.3.0
type ExtensionsLoadedExtensionSource = rpc.ExtensionsLoadedExtensionSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExtensionsLoadedExtensionStatus ¶ added in v0.3.0
type ExtensionsLoadedExtensionStatus = rpc.ExtensionsLoadedExtensionStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExternalToolCompletedData ¶ added in v0.2.2
type ExternalToolCompletedData = rpc.ExternalToolCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExternalToolRequestedData ¶ added in v0.2.2
type ExternalToolRequestedData = rpc.ExternalToolRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type GetAuthStatusResponse ¶ added in v0.1.15
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"`
}
GetAuthStatusResponse is the response from auth.getStatus
type GetStatusResponse ¶ added in v0.1.15
type GetStatusResponse struct {
Version string `json:"version"`
ProtocolVersion int `json:"protocolVersion"`
}
GetStatusResponse is the response from status.get
type HandoffRepository ¶ added in v0.3.0
type HandoffRepository = rpc.HandoffRepository
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HandoffSourceType ¶ added in v0.3.0
type HandoffSourceType = rpc.HandoffSourceType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookEndData ¶ added in v0.2.2
type HookEndData = rpc.HookEndData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookEndError ¶ added in v0.3.0
type HookEndError = rpc.HookEndError
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookInvocation ¶ added in v0.1.20
type HookInvocation struct {
SessionID string
}
HookInvocation provides context about a hook invocation
type HookProgressData ¶ added in v1.0.0
type HookProgressData = rpc.HookProgressData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookStartData ¶ added in v0.2.2
type HookStartData = rpc.HookStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type InfiniteSessionConfig ¶ added in v0.1.18
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"`
}
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 LargeToolOutputConfig ¶ added in v1.0.0
type LargeToolOutputConfig struct {
// Enabled controls whether large output handling is enabled. Default: true.
Enabled *bool `json:"enabled,omitempty"`
// MaxSizeBytes is the maximum size in bytes before output is written to a
// temp file. Default: 50KB.
MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"`
// OutputDirectory is the directory to write temp files to. Defaults to the OS
// temp directory.
OutputDirectory string `json:"outputDir,omitempty"`
}
LargeToolOutputConfig configures handling of large tool outputs. When a tool produces output exceeding the configured size, the output is written to a temp file and a reference is returned to the model instead of the full payload.
type LogOptions ¶ added in v0.2.0
type LogOptions struct {
// Level sets the log severity. Valid values are [rpc.SessionLogLevelInfo] (default),
// [rpc.SessionLogLevelWarning], and [rpc.SessionLogLevelError].
Level rpc.SessionLogLevel
// Ephemeral marks the message as transient so it is not persisted
// to the session event log on disk. When nil the server decides the
// default; set to a non-nil value to explicitly control persistence.
Ephemeral *bool
}
type MCPAppToolCallCompleteData ¶ added in v1.0.0
type MCPAppToolCallCompleteData = rpc.MCPAppToolCallCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPAppToolCallCompleteError ¶ added in v1.0.0
type MCPAppToolCallCompleteError = rpc.MCPAppToolCallCompleteError
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPAppToolCallCompleteToolMeta ¶ added in v1.0.0
type MCPAppToolCallCompleteToolMeta = rpc.MCPAppToolCallCompleteToolMeta
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPAppToolCallCompleteToolMetaUI ¶ added in v1.0.0
type MCPAppToolCallCompleteToolMetaUI = rpc.MCPAppToolCallCompleteToolMetaUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPHTTPServerConfig ¶ added in v0.3.0
type MCPHTTPServerConfig struct {
Tools []string `json:"tools,omitzero"`
Timeout int `json:"timeout,omitempty"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitzero"`
}
MCPHTTPServerConfig configures a remote MCP server (HTTP or SSE).
See MCPStdioServerConfig for the semantics of the Tools field.
func (MCPHTTPServerConfig) MarshalJSON ¶ added in v0.3.0
func (c MCPHTTPServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
type MCPOauthCompletedData ¶ added in v1.0.0
type MCPOauthCompletedData = rpc.MCPOauthCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRequiredData ¶ added in v1.0.0
type MCPOauthRequiredData = rpc.MCPOauthRequiredData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRequiredStaticClientConfig ¶ added in v1.0.0
type MCPOauthRequiredStaticClientConfig = rpc.MCPOauthRequiredStaticClientConfig
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRequiredStaticClientConfigGrantType ¶ added in v1.0.0
type MCPOauthRequiredStaticClientConfigGrantType = rpc.MCPOauthRequiredStaticClientConfigGrantType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServerConfig ¶
type MCPServerConfig interface {
// contains filtered or unexported methods
}
MCPServerConfig is implemented by MCP server configuration types. Only MCPStdioServerConfig and MCPHTTPServerConfig implement this interface.
type MCPServerSource ¶ added in v1.0.0
type MCPServerSource = rpc.MCPServerSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServerStatus ¶ added in v1.0.0
type MCPServerStatus = rpc.MCPServerStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServerTransport ¶ added in v1.0.0
type MCPServerTransport = rpc.MCPServerTransport
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServersLoadedServer ¶ added in v1.0.0
type MCPServersLoadedServer = rpc.MCPServersLoadedServer
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPStdioServerConfig ¶ added in v0.3.0
type MCPStdioServerConfig struct {
Tools []string `json:"tools,omitzero"`
Timeout int `json:"timeout,omitempty"`
Command string `json:"command"`
Args []string `json:"args,omitzero"`
Env map[string]string `json:"env,omitzero"`
WorkingDirectory string `json:"cwd,omitempty"`
}
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
func (MCPStdioServerConfig) MarshalJSON ¶ added in v0.3.0
func (c MCPStdioServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
type MessageOptions ¶
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
// AgentMode is the UI mode the agent was in when this message was sent
// (for example "plan" or "autopilot"). Defaults to the session's current
// mode when empty.
AgentMode AgentMode
// RequestHeaders are custom per-turn HTTP headers for outbound model requests.
RequestHeaders map[string]string
// DisplayPrompt, if provided, is shown in the timeline instead of Prompt.
DisplayPrompt string
}
MessageOptions configures a message to send
type ModelBilling ¶ added in v0.1.15
type ModelBilling struct {
Multiplier *float64 `json:"multiplier,omitempty"`
}
ModelBilling contains model billing information
type ModelCallFailureData ¶ added in v1.0.0
type ModelCallFailureData = rpc.ModelCallFailureData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFailureSource ¶ added in v1.0.0
type ModelCallFailureSource = rpc.ModelCallFailureSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCapabilities ¶ added in v0.1.15
type ModelCapabilities struct {
Supports ModelSupports `json:"supports"`
Limits ModelLimits `json:"limits"`
}
ModelCapabilities contains model capabilities and limits
type ModelCapabilitiesOverride ¶ added in v0.2.2
type ModelCapabilitiesOverride = rpc.ModelCapabilitiesOverride
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelCapabilitiesOverrideLimits ¶ added in v0.2.2
type ModelCapabilitiesOverrideLimits = rpc.ModelCapabilitiesOverrideLimits
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelCapabilitiesOverrideLimitsVision ¶ added in v0.2.2
type ModelCapabilitiesOverrideLimitsVision = rpc.ModelCapabilitiesOverrideLimitsVision
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelCapabilitiesOverrideSupports ¶ added in v0.2.2
type ModelCapabilitiesOverrideSupports = rpc.ModelCapabilitiesOverrideSupports
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelInfo ¶ added in v0.1.15
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"`
}
ModelInfo contains information about an available model
type ModelLimits ¶ added in v0.1.15
type ModelLimits struct {
MaxPromptTokens *int `json:"max_prompt_tokens,omitempty"`
MaxContextWindowTokens *int `json:"max_context_window_tokens,omitempty"`
Vision *ModelVisionLimits `json:"vision,omitempty"`
}
ModelLimits contains model limits
type ModelPolicy ¶ added in v0.1.15
ModelPolicy contains model policy state
type ModelSupports ¶ added in v0.1.15
type ModelSupports struct {
Vision bool `json:"vision"`
ReasoningEffort bool `json:"reasoningEffort"`
}
ModelSupports contains model support flags
type ModelVisionLimits ¶ added in v0.1.15
type ModelVisionLimits struct {
SupportedMediaTypes []string `json:"supported_media_types"`
MaxPromptImages int `json:"max_prompt_images"`
MaxPromptImageSize int `json:"max_prompt_image_size"`
}
ModelVisionLimits contains vision-specific limits
type PendingMessagesModifiedData ¶ added in v0.2.2
type PendingMessagesModifiedData = rpc.PendingMessagesModifiedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApproved ¶ added in v1.0.0
type PermissionApproved = rpc.PermissionApproved
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovedForLocation ¶ added in v1.0.0
type PermissionApprovedForLocation = rpc.PermissionApprovedForLocation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovedForSession ¶ added in v1.0.0
type PermissionApprovedForSession = rpc.PermissionApprovedForSession
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionCancelled ¶ added in v1.0.0
type PermissionCancelled = rpc.PermissionCancelled
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionCompletedData ¶ added in v0.2.2
type PermissionCompletedData = rpc.PermissionCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedByContentExclusionPolicy ¶ added in v1.0.0
type PermissionDeniedByContentExclusionPolicy = rpc.PermissionDeniedByContentExclusionPolicy
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedByPermissionRequestHook ¶ added in v1.0.0
type PermissionDeniedByPermissionRequestHook = rpc.PermissionDeniedByPermissionRequestHook
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedByRules ¶ added in v1.0.0
type PermissionDeniedByRules = rpc.PermissionDeniedByRules
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedInteractivelyByUser ¶ added in v1.0.0
type PermissionDeniedInteractivelyByUser = rpc.PermissionDeniedInteractivelyByUser
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser ¶ added in v1.0.0
type PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser = rpc.PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionHandlerFunc ¶ added in v0.1.28
type PermissionHandlerFunc func(request PermissionRequest, invocation PermissionInvocation) (rpc.PermissionDecision, error)
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 PermissionInvocation ¶
type PermissionInvocation struct {
SessionID string
}
PermissionInvocation provides context about a permission request
type PermissionPromptRequest ¶ added in v0.3.0
type PermissionPromptRequest = rpc.PermissionPromptRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestCommands ¶ added in v1.0.0
type PermissionPromptRequestCommands = rpc.PermissionPromptRequestCommands
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestCustomTool ¶ added in v1.0.0
type PermissionPromptRequestCustomTool = rpc.PermissionPromptRequestCustomTool
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestExtensionManagement ¶ added in v1.0.0
type PermissionPromptRequestExtensionManagement = rpc.PermissionPromptRequestExtensionManagement
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestExtensionPermissionAccess ¶ added in v1.0.0
type PermissionPromptRequestExtensionPermissionAccess = rpc.PermissionPromptRequestExtensionPermissionAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestHook ¶ added in v1.0.0
type PermissionPromptRequestHook = rpc.PermissionPromptRequestHook
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestKind ¶ added in v0.3.0
type PermissionPromptRequestKind = rpc.PermissionPromptRequestKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestMCP ¶ added in v1.0.0
type PermissionPromptRequestMCP = rpc.PermissionPromptRequestMCP
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestMemory ¶ added in v1.0.0
type PermissionPromptRequestMemory = rpc.PermissionPromptRequestMemory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestPath ¶ added in v1.0.0
type PermissionPromptRequestPath = rpc.PermissionPromptRequestPath
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestPathAccessKind ¶ added in v0.3.0
type PermissionPromptRequestPathAccessKind = rpc.PermissionPromptRequestPathAccessKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestRead ¶ added in v1.0.0
type PermissionPromptRequestRead = rpc.PermissionPromptRequestRead
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestURL ¶ added in v1.0.0
type PermissionPromptRequestURL = rpc.PermissionPromptRequestURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestWrite ¶ added in v1.0.0
type PermissionPromptRequestWrite = rpc.PermissionPromptRequestWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequest ¶
type PermissionRequest = rpc.PermissionRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestCommand ¶ added in v0.2.0
type PermissionRequestCommand = rpc.PermissionRequestCommand
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestCustomTool ¶ added in v1.0.0
type PermissionRequestCustomTool = rpc.PermissionRequestCustomTool
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestExtensionManagement ¶ added in v1.0.0
type PermissionRequestExtensionManagement = rpc.PermissionRequestExtensionManagement
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestExtensionPermissionAccess ¶ added in v1.0.0
type PermissionRequestExtensionPermissionAccess = rpc.PermissionRequestExtensionPermissionAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestHook ¶ added in v1.0.0
type PermissionRequestHook = rpc.PermissionRequestHook
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestKind ¶ added in v0.1.31
type PermissionRequestKind = rpc.PermissionRequestKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMCP ¶ added in v1.0.0
type PermissionRequestMCP = rpc.PermissionRequestMCP
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMemory ¶ added in v1.0.0
type PermissionRequestMemory = rpc.PermissionRequestMemory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMemoryAction ¶ added in v0.3.0
type PermissionRequestMemoryAction = rpc.PermissionRequestMemoryAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMemoryDirection ¶ added in v0.3.0
type PermissionRequestMemoryDirection = rpc.PermissionRequestMemoryDirection
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestRead ¶ added in v1.0.0
type PermissionRequestRead = rpc.PermissionRequestRead
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestShell ¶ added in v1.0.0
type PermissionRequestShell = rpc.PermissionRequestShell
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestShellCommand ¶ added in v0.3.0
type PermissionRequestShellCommand = rpc.PermissionRequestShellCommand
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestShellPossibleURL ¶ added in v0.3.0
type PermissionRequestShellPossibleURL = rpc.PermissionRequestShellPossibleURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestURL ¶ added in v1.0.0
type PermissionRequestURL = rpc.PermissionRequestURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestWrite ¶ added in v1.0.0
type PermissionRequestWrite = rpc.PermissionRequestWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestedData ¶ added in v0.2.2
type PermissionRequestedData = rpc.PermissionRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionResult ¶ added in v1.0.0
type PermissionResult = rpc.PermissionResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionResultKind ¶ added in v1.0.0
type PermissionResultKind = rpc.PermissionResultKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRule ¶ added in v1.0.0
type PermissionRule = rpc.PermissionRule
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PingResponse ¶
type PingResponse struct {
Message string `json:"message"`
Timestamp time.Time `json:"timestamp"`
ProtocolVersion *int `json:"protocolVersion,omitempty"`
}
PingResponse is the response from a ping request
type PlanChangedOperation ¶ added in v0.3.0
type PlanChangedOperation = rpc.PlanChangedOperation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PossibleURL ¶ added in v0.1.31
type PossibleURL = rpc.PossibleURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PostToolUseFailureHandler ¶ added in v1.0.0
type PostToolUseFailureHandler func(input PostToolUseFailureHookInput, invocation HookInvocation) (*PostToolUseFailureHookOutput, error)
PostToolUseFailureHandler handles post-tool-use-failure hook invocations.
type PostToolUseFailureHookInput ¶ added in v1.0.0
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"`
}
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).
func (PostToolUseFailureHookInput) MarshalJSON ¶ added in v1.0.0
func (h PostToolUseFailureHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*PostToolUseFailureHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *PostToolUseFailureHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PostToolUseFailureHookOutput ¶ added in v1.0.0
type PostToolUseFailureHookOutput struct {
AdditionalContext string `json:"additionalContext,omitempty"`
}
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 PostToolUseHandler ¶ added in v0.1.20
type PostToolUseHandler func(input PostToolUseHookInput, invocation HookInvocation) (*PostToolUseHookOutput, error)
PostToolUseHandler handles post-tool-use hook invocations
type PostToolUseHookInput ¶ added in v0.1.20
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"`
}
PostToolUseHookInput is the input for a post-tool-use hook
func (PostToolUseHookInput) MarshalJSON ¶ added in v1.0.0
func (h PostToolUseHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*PostToolUseHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *PostToolUseHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PostToolUseHookOutput ¶ added in v0.1.20
type PostToolUseHookOutput struct {
ModifiedResult any `json:"modifiedResult,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
}
PostToolUseHookOutput is the output for a post-tool-use hook
type PreMCPToolCallHandler ¶ added in v1.0.0
type PreMCPToolCallHandler func(input PreMCPToolCallHookInput, invocation HookInvocation) (*PreMCPToolCallHookOutput, error)
PreMCPToolCallHandler handles pre-mcp-tool-call hook invocations
type PreMCPToolCallHookInput ¶ added in v1.0.0
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"`
}
PreMCPToolCallHookInput is the input for a pre-mcp-tool-call hook
func (PreMCPToolCallHookInput) MarshalJSON ¶ added in v1.0.0
func (h PreMCPToolCallHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*PreMCPToolCallHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *PreMCPToolCallHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PreMCPToolCallHookOutput ¶ added in v1.0.0
type PreMCPToolCallHookOutput struct {
MetaToUse any `json:"metaToUse"`
}
PreMCPToolCallHookOutput is the output for a pre-mcp-tool-call hook
type PreToolUseHandler ¶ added in v0.1.20
type PreToolUseHandler func(input PreToolUseHookInput, invocation HookInvocation) (*PreToolUseHookOutput, error)
PreToolUseHandler handles pre-tool-use hook invocations
type PreToolUseHookInput ¶ added in v0.1.20
type PreToolUseHookInput struct {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
}
PreToolUseHookInput is the input for a pre-tool-use hook
func (PreToolUseHookInput) MarshalJSON ¶ added in v1.0.0
func (h PreToolUseHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*PreToolUseHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *PreToolUseHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PreToolUseHookOutput ¶ added in v0.1.20
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"`
}
PreToolUseHookOutput is the output for a pre-tool-use hook
type ProviderConfig ¶
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"`
// Headers are custom HTTP headers included in outbound provider requests.
Headers map[string]string `json:"headers,omitempty"`
// ModelID is the well-known model name used by the runtime to look up
// agent configuration (tools, prompts, reasoning behavior) and default
// token limits. Also used as the wire model when WireModel is not set.
// Falls back to SessionConfig.Model.
ModelID string `json:"modelId,omitempty"`
// WireModel is the model name sent to the provider API for inference. Use
// this when the provider's model name (e.g. an Azure deployment name or a
// custom fine-tune name) differs from ModelID.
// Falls back to ModelID, then SessionConfig.Model.
WireModel string `json:"wireModel,omitempty"`
// MaxPromptTokens overrides the resolved model's default max prompt tokens.
// The runtime triggers conversation compaction before sending a request
// when the prompt (system message, history, tool definitions, user
// message) would exceed this limit.
MaxPromptTokens int `json:"maxPromptTokens,omitempty"`
// MaxOutputTokens overrides the resolved model's default max output
// tokens. When hit, the model stops generating and returns a truncated
// response.
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
}
type RawPermissionPromptRequest ¶ added in v1.0.0
type RawPermissionPromptRequest = rpc.RawPermissionPromptRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawPermissionRequest ¶ added in v1.0.0
type RawPermissionRequest = rpc.RawPermissionRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawPermissionResult ¶ added in v1.0.0
type RawPermissionResult = rpc.RawPermissionResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawSessionEventData ¶ added in v0.2.2
type RawSessionEventData = rpc.RawSessionEventData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawSystemNotification ¶ added in v1.0.0
type RawSystemNotification = rpc.RawSystemNotification
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawToolExecutionCompleteContent ¶ added in v1.0.0
type RawToolExecutionCompleteContent = rpc.RawToolExecutionCompleteContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ReasoningSummary ¶ added in v1.0.0
type ReasoningSummary = rpc.ReasoningSummary
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ResumeSessionConfig ¶
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. 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
// Provider configures a custom model provider
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
// SkipCustomInstructions, when non-nil, controls whether the runtime loads
// custom instruction files. See also [ClientOptions.Mode] = [ModeEmpty].
SkipCustomInstructions *bool
// CustomAgentsLocalOnly, when non-nil, restricts custom agents to those
// defined locally. See also [ClientOptions.Mode] = [ModeEmpty].
CustomAgentsLocalOnly *bool
// exposed. See also [ClientOptions.Mode] = [ModeEmpty].
CoauthorEnabled *bool
// ManageScheduleEnabled, when non-nil, controls whether the
// `manage_schedule` tool is exposed. See also [ClientOptions.Mode] =
// [ModeEmpty].
ManageScheduleEnabled *bool
// 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
// ReasoningSummary mode for models that support configurable reasoning summaries.
// Use ReasoningSummaryNone to suppress summary output regardless of whether reasoning is enabled.
ReasoningSummary ReasoningSummary
// ContextTier pins the session to a context window tier for models that support it.
// Use ContextTierDefault or ContextTierLongContext for the currently known tiers.
ContextTier ContextTier
// 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
// ConfigDirectory overrides the default configuration directory location.
ConfigDirectory string
// EnableConfigDiscovery, when non-nil, controls automatic discovery of 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.
// Nil leaves the runtime default unchanged; use Bool(false) to explicitly disable discovery.
// Custom instruction files (.github/copilot-instructions.md, AGENTS.md, etc.) are
// always loaded from the working directory regardless of this setting.
EnableConfigDiscovery *bool
// SkipEmbeddingRetrieval, when non-nil, controls embedding-based retrieval
// for this session. Use in multitenant deployments to prevent cross-session
// information leakage through the shared embedding cache.
SkipEmbeddingRetrieval *bool
// EmbeddingCacheStorage controls how the embedding cache is stored for this session.
// "persistent" caches on disk and shares across sessions/restarts.
// "in-memory" caches in memory only and discards when the session ends.
EmbeddingCacheStorage *string
// OrganizationCustomInstructions provides organization-level custom instructions
// to include in the system prompt.
OrganizationCustomInstructions *string
// EnableOnDemandInstructionDiscovery, when non-nil, controls on-demand discovery
// of instruction files after successful file views.
EnableOnDemandInstructionDiscovery *bool
// EnableFileHooks, when non-nil, controls loading of file-based hooks from
// .github/hooks/. This is separate from the Hooks callback parameter which
// gates SDK hook event registration.
EnableFileHooks *bool
// EnableHostGitOperations, when non-nil, controls git operations on the host
// filesystem.
EnableHostGitOperations *bool
// EnableSessionStore, when non-nil, controls the cross-session store for search
// and retrieval across sessions.
EnableSessionStore *bool
// EnableSkills, when non-nil, controls skill loading.
EnableSkills *bool
// 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
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// MCPOAuthTokenStorage controls how MCP OAuth tokens are stored for this session.
// When empty, the runtime default ("in-memory") is used.
MCPOAuthTokenStorage string
// 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).
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
// PluginDirectories is a list of local filesystem paths to Open Plugins-format
// directories (https://open-plugins.com/) to load for this session.
// Relative paths resolve against WorkingDirectory (or the runtime cwd if unset).
// Treated as an explicit opt-in: plugin agents and rules load even when
// EnableConfigDiscovery is false.
PluginDirectories []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.
InfiniteSessions *InfiniteSessionConfig
// LargeOutput configures handling of large tool outputs. When a tool produces
// output exceeding the configured size, the output is written to a temp file
// and a reference is returned to the model instead of the full payload.
LargeOutput *LargeToolOutputConfig
// 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.
// See SessionConfig.RemoteSession for details.
RemoteSession rpc.RemoteSessionMode
// SuppressResumeEvent, when true, skips emitting the session.resume event.
// Useful for reconnecting to a session without triggering resume-related side effects.
SuppressResumeEvent bool
// ContinuePendingWork, when non-nil, controls whether the runtime continues any
// tool calls or permission prompts that were still pending when the session was
// last suspended. Nil leaves the runtime default unchanged; use Bool(false) to
// explicitly treat pending work as interrupted on resume.
//
// For permission requests, the runtime re-emits permission.requested so the
// registered OnPermissionRequest handler can re-prompt; for external tool calls,
// the consumer is expected to supply the result via the corresponding low-level
// RPC method.
ContinuePendingWork *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
// 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. See SessionConfig.Commands.
Commands []CommandDefinition
// OnElicitationRequest is a handler for elicitation requests from the server.
// See SessionConfig.OnElicitationRequest.
OnElicitationRequest ElicitationHandler
// OnExitPlanModeRequest is a handler for exit-plan-mode requests from the server.
// See SessionConfig.OnExitPlanModeRequest.
OnExitPlanModeRequest ExitPlanModeRequestHandler
// OnAutoModeSwitchRequest is a handler for auto-mode-switch requests from the server.
// See SessionConfig.OnAutoModeSwitchRequest.
OnAutoModeSwitchRequest AutoModeSwitchRequestHandler
// EnableMCPApps enables MCP Apps (SEP-1865) UI passthrough on resume.
// See SessionConfig.EnableMCPApps.
//
// Experimental: EnableMCPApps is part of an experimental wire-protocol
// surface (SEP-1865) and may change or be removed in a future release.
EnableMCPApps bool
// Canvases declares canvases this session provides. Sent over the wire on
// `session.resume`. See SessionConfig.Canvases.
Canvases []CanvasDeclaration
// OpenCanvases declares canvas instances the caller knows were open before
// this resume so the runtime can re-attach them. Sent over the wire on
// `session.resume` as `openCanvases`.
OpenCanvases []rpc.OpenCanvasInstance
// 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
// ExtensionSDKPath optionally overrides the bundled `@github/copilot-sdk` drop
// injected into extension subprocesses. See SessionConfig.ExtensionSDKPath.
ExtensionSDKPath *string
// CanvasHandler receives inbound canvas.* requests for this session. See SessionConfig.CanvasHandler.
CanvasHandler CanvasHandler `json:"-"`
// ExtensionInfo identifies the stable extension providing this session's canvases.
ExtensionInfo *ExtensionInfo
}
ResumeSessionConfig configures options when resuming a session
type RuntimeConnection ¶ added in v1.0.0
type RuntimeConnection interface {
// contains filtered or unexported methods
}
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 SamplingCompletedData ¶ added in v0.2.2
type SamplingCompletedData = rpc.SamplingCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SamplingRequestedData ¶ added in v0.2.2
type SamplingRequestedData = rpc.SamplingRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SectionOverride ¶ added in v0.2.0
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:"-"`
}
SectionOverride defines an override operation for a single system message section.
type SectionOverrideAction ¶ added in v0.2.0
type SectionOverrideAction string
SectionOverrideAction represents the action to perform on a system message section.
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" )
type SectionTransformFn ¶ added in v0.2.0
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 Session ¶
type Session struct {
// SessionID is the unique identifier for this session.
SessionID string
// RPC provides typed session-scoped RPC methods.
RPC *rpc.SessionRPC
// contains filtered or unexported fields
}
Session represents a single conversation session with the Copilot CLI.
A session maintains conversation state, handles events, and manages tool execution. Sessions are created via Client.CreateSession or resumed via Client.ResumeSession.
The session provides methods to send messages, subscribe to events, retrieve conversation history, and manage the session lifecycle. All methods are safe for concurrent use.
Example usage:
session, err := client.CreateSession(copilot.SessionConfig{
Model: "gpt-4",
})
if err != nil {
log.Fatal(err)
}
defer session.Disconnect()
// Subscribe to events
unsubscribe := session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
fmt.Println("Assistant:", d.Content)
}
})
defer unsubscribe()
// Send a message
messageID, err := session.Send(copilot.MessageOptions{
Prompt: "Hello, world!",
})
func (*Session) Abort ¶
Abort aborts the currently processing message in this session.
Use this to cancel a long-running request. The session remains valid and can continue to be used for new messages.
Returns an error if the session has been disconnected or the connection fails.
Example:
// Start a long-running request in a goroutine
go func() {
session.Send(context.Background(), copilot.MessageOptions{
Prompt: "Write a very long story...",
})
}()
// Abort after 5 seconds
time.Sleep(5 * time.Second)
if err := session.Abort(context.Background()); err != nil {
log.Printf("Failed to abort: %v", err)
}
func (*Session) Capabilities ¶ added in v0.2.1
func (s *Session) Capabilities() SessionCapabilities
Capabilities returns the session capabilities reported by the server.
func (*Session) Disconnect ¶ added in v0.1.31
Disconnect closes this session and releases all in-memory resources (event handlers, tool handlers, permission handlers).
The caller should ensure the session is idle (e.g., Session.SendAndWait has returned) before disconnecting. If the session is not idle, in-flight event handlers or tool handlers may observe failures.
Session state on disk (conversation history, planning state, artifacts) is preserved, so the conversation can be resumed later by calling Client.ResumeSession with the session ID. To permanently remove all session data including files on disk, use Client.DeleteSession instead.
After calling this method, the session object can no longer be used.
Returns an error if the connection fails.
Example:
// Clean up when done — session can still be resumed later
if err := session.Disconnect(); err != nil {
log.Printf("Failed to disconnect session: %v", err)
}
func (*Session) GetEvents ¶ added in v1.0.0
func (s *Session) GetEvents(ctx context.Context) ([]SessionEvent, error)
GetEvents retrieves all events from this session's history.
This returns the complete conversation history including user messages, assistant responses, tool executions, and other session events in chronological order.
Returns an error if the session has been disconnected or the connection fails.
Example:
events, err := session.GetEvents(context.Background())
if err != nil {
log.Printf("Failed to get events: %v", err)
return
}
for _, event := range events {
if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
fmt.Println("Assistant:", d.Content)
}
}
func (*Session) Log ¶ added in v0.2.0
Log sends a log message to the session timeline. The message appears in the session event stream and is visible to SDK consumers and (for non-ephemeral messages) persisted to the session event log on disk.
Pass nil for opts to use defaults (info level, non-ephemeral).
Example:
// Simple info message
session.Log(ctx, "Processing started")
// Warning with options
session.Log(ctx, "Rate limit approaching", &copilot.LogOptions{Level: rpc.SessionLogLevelWarning})
// Ephemeral message (not persisted)
session.Log(ctx, "Working...", &copilot.LogOptions{Ephemeral: copilot.Bool(true)})
func (*Session) On ¶
func (s *Session) On(handler SessionEventHandler) func()
On subscribes to events from this session.
Events include assistant messages, tool executions, errors, and session state changes. Multiple handlers can be registered and will all receive events. Handlers are called synchronously in the order they were registered.
The returned function can be called to unsubscribe the handler. It is safe to call the unsubscribe function multiple times.
Example:
unsubscribe := session.On(func(event copilot.SessionEvent) {
switch d := event.Data.(type) {
case *copilot.AssistantMessageData:
fmt.Println("Assistant:", d.Content)
case *copilot.SessionErrorData:
fmt.Println("Error:", d.Message)
}
})
// Later, to stop receiving events:
unsubscribe()
func (*Session) OpenCanvases ¶ added in v1.0.0
func (s *Session) OpenCanvases() []rpc.OpenCanvasInstance
OpenCanvases returns the open-canvas snapshot last reported by the runtime. The snapshot is populated from session.resume and live session.canvas.opened events. The returned slice is a copy and is safe to mutate by the caller.
func (*Session) Send ¶
Send sends a message to this session and waits for the response.
The message is processed asynchronously. Subscribe to events via Session.On to receive streaming responses and other session events.
Parameters:
- options: The message options including the prompt and optional attachments.
Returns the message ID of the response, which can be used to correlate events, or an error if the session has been disconnected or the connection fails.
Example:
messageID, err := session.Send(context.Background(), copilot.MessageOptions{
Prompt: "Explain this code",
Attachments: []copilot.Attachment{
&copilot.AttachmentFile{DisplayName: "main.go", Path: "./main.go"},
},
})
if err != nil {
log.Printf("Failed to send message: %v", err)
}
func (*Session) SendAndWait ¶
func (s *Session) SendAndWait(ctx context.Context, options MessageOptions) (*SessionEvent, error)
SendAndWait sends a message to this session and waits until the session becomes idle.
This is a convenience method that combines Session.Send with waiting for the session.idle event. Use this when you want to block until the assistant has finished processing the message.
Events are still delivered to handlers registered via Session.On while waiting.
Parameters:
- options: The message options including the prompt and optional attachments.
- timeout: How long to wait for completion. Defaults to 60 seconds if zero. Controls how long to wait; does not abort in-flight agent work.
Returns the final assistant message event, or nil if none was received. Returns an error if the timeout is reached or the connection fails.
Example:
response, err := session.SendAndWait(context.Background(), copilot.MessageOptions{
Prompt: "What is 2+2?",
}) // Use default 60s timeout
if err != nil {
log.Printf("Failed: %v", err)
}
if response != nil {
if d, ok := response.Data.(*AssistantMessageData); ok {
fmt.Println(d.Content)
}
}
func (*Session) SendPrompt ¶ added in v1.0.0
SendPrompt is a convenience wrapper for Session.Send that takes a plain prompt string instead of a MessageOptions struct. Equivalent to:
session.Send(ctx, copilot.MessageOptions{Prompt: prompt})
func (*Session) SendPromptAndWait ¶ added in v1.0.0
SendPromptAndWait is a convenience wrapper for Session.SendAndWait that takes a plain prompt string instead of a MessageOptions struct. Equivalent to:
session.SendAndWait(ctx, copilot.MessageOptions{Prompt: prompt})
func (*Session) SetModel ¶ added in v0.1.30
SetModel changes the model for this session. The new model takes effect for the next message. Conversation history is preserved.
Example:
if err := session.SetModel(context.Background(), "gpt-4.1", nil); err != nil {
log.Printf("Failed to set model: %v", err)
}
if err := session.SetModel(context.Background(), "claude-sonnet-4.6", &SetModelOptions{ReasoningEffort: new("high")}); err != nil {
log.Printf("Failed to set model: %v", err)
}
func (*Session) UI ¶ added in v0.2.1
UI returns the interactive UI API for showing elicitation dialogs. Methods on the returned SessionUI will error if the host does not support elicitation (check Capabilities().UI.Elicitation first).
func (*Session) WorkspacePath ¶ added in v0.1.18
WorkspacePath returns the path to the session workspace directory when infinite sessions are enabled. Contains checkpoints/, plan.md, and files/ subdirectories. Returns empty string if infinite sessions are disabled.
type SessionAutopilotObjectiveChangedData ¶ added in v1.0.0
type SessionAutopilotObjectiveChangedData = rpc.SessionAutopilotObjectiveChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionBackgroundTasksChangedData ¶ added in v0.2.2
type SessionBackgroundTasksChangedData = rpc.SessionBackgroundTasksChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasOpenedData ¶ added in v1.0.0
type SessionCanvasOpenedData = rpc.SessionCanvasOpenedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasRegistryChangedData ¶ added in v1.0.0
type SessionCanvasRegistryChangedData = rpc.SessionCanvasRegistryChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCapabilities ¶ added in v0.2.1
type SessionCapabilities struct {
UI *UICapabilities `json:"ui,omitempty"`
}
SessionCapabilities describes what features the host supports.
type SessionCompactionCompleteData ¶ added in v0.2.2
type SessionCompactionCompleteData = rpc.SessionCompactionCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCompactionStartData ¶ added in v0.2.2
type SessionCompactionStartData = rpc.SessionCompactionStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionConfig ¶
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
// ReasoningSummary mode for models that support configurable reasoning summaries.
// Use ReasoningSummaryNone to suppress summary output regardless of whether reasoning is enabled.
ReasoningSummary ReasoningSummary
// ContextTier pins the session to a context window tier for models that support it.
// Use ContextTierDefault or ContextTierLongContext for the currently known tiers.
ContextTier ContextTier
// ConfigDirectory overrides the default configuration directory location.
// When specified, the session will use this directory for storing config and state.
ConfigDirectory string
// EnableConfigDiscovery, when non-nil, controls automatic discovery of 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.
// Nil leaves the runtime default unchanged; use Bool(false) to explicitly disable discovery.
// Custom instruction files (.github/copilot-instructions.md, AGENTS.md, etc.) are
// always loaded from the working directory regardless of this setting.
EnableConfigDiscovery *bool
// SkipEmbeddingRetrieval, when non-nil, controls embedding-based retrieval
// for this session. Use in multitenant deployments to prevent cross-session
// information leakage through the shared embedding cache.
SkipEmbeddingRetrieval *bool
// EmbeddingCacheStorage controls how the embedding cache is stored for this session.
// "persistent" caches on disk and shares across sessions/restarts.
// "in-memory" caches in memory only and discards when the session ends.
EmbeddingCacheStorage *string
// OrganizationCustomInstructions provides organization-level custom instructions
// to include in the system prompt. Allows hosts to inject organization-specific
// guidance without relying on filesystem-based instruction discovery.
OrganizationCustomInstructions *string
// EnableOnDemandInstructionDiscovery, when non-nil, controls on-demand discovery
// of instruction files (AGENTS.md, .github/copilot-instructions.md, etc.) after
// successful file views.
EnableOnDemandInstructionDiscovery *bool
// EnableFileHooks, when non-nil, controls loading of file-based hooks from
// .github/hooks/. This is separate from the Hooks callback parameter which
// gates SDK hook event registration.
EnableFileHooks *bool
// EnableHostGitOperations, when non-nil, controls git operations on the host
// filesystem (branch detection, file status, commit history). When false, no
// git context is surfaced in the system prompt.
EnableHostGitOperations *bool
// EnableSessionStore, when non-nil, controls the cross-session store for search
// and retrieval. When false, session content is not written to or read from the
// shared session store.
EnableSessionStore *bool
// EnableSkills, when non-nil, controls skill loading (including builtin skills
// and discovered skill directories). When false, no skills are loaded regardless
// of SkillDirectories or EnableConfigDiscovery settings.
EnableSkills *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
// SkipCustomInstructions, when non-nil, controls whether the runtime loads
// custom instruction files. See also [ClientOptions.Mode] = [ModeEmpty].
SkipCustomInstructions *bool
// CustomAgentsLocalOnly, when non-nil, restricts custom agents to those
// defined locally. See also [ClientOptions.Mode] = [ModeEmpty].
CustomAgentsLocalOnly *bool
// exposed. See also [ClientOptions.Mode] = [ModeEmpty].
CoauthorEnabled *bool
// ManageScheduleEnabled, when non-nil, controls whether the
// `manage_schedule` tool is exposed. See also [ClientOptions.Mode] =
// [ModeEmpty].
ManageScheduleEnabled *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
// MCPOAuthTokenStorage controls how MCP OAuth tokens are stored for this session.
// When empty, the runtime default ("in-memory") is used.
MCPOAuthTokenStorage string
// 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
// PluginDirectories is a list of local filesystem paths to Open Plugins-format
// directories (https://open-plugins.com/) to load for this session.
// Relative paths resolve against WorkingDirectory (or the runtime cwd if unset).
// Treated as an explicit opt-in: plugin agents and rules load even when
// EnableConfigDiscovery is false.
PluginDirectories []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
// LargeOutput configures handling of large tool outputs. When a tool produces
// output exceeding the configured size, the output is written to a temp file
// and a reference is returned to the model instead of the full payload.
LargeOutput *LargeToolOutputConfig
// 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
// EnableMCPApps enables MCP Apps (SEP-1865) UI passthrough on this session.
//
// Experimental: EnableMCPApps is part of an experimental wire-protocol
// surface (SEP-1865) and may change or be removed in a future release.
//
// When true AND the runtime has MCP Apps enabled (via the MCP_APPS feature
// flag or COPILOT_MCP_APPS=true environment override), the runtime adds the
// mcp-apps capability to the session, which causes it to advertise the
// extensions.io.modelcontextprotocol/ui extension to MCP servers (so they
// expose _meta.ui.resourceUri on tools) and to expose the
// session.rpc.mcp.apps.{listTools,callTool,readResource,setHostContext,
// getHostContext,diagnose} JSON-RPC methods.
//
// If the runtime gate is off, the opt-in is silently dropped server-side
// (the runtime logs a warning); the session is created normally but the
// MCP Apps surface is unavailable. Inspect the runtime's
// capabilities.ui.mcpApps on the create/resume response to detect this.
//
// SDK consumers MUST set this to true only when they have an iframe renderer
// that can display ui:// MCP App bundles. Setting it without a renderer will
// cause MCP servers to register UI-enabled tool variants the consumer cannot
// display.
EnableMCPApps bool
// 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
// ExtensionSDKPath optionally overrides the bundled `@github/copilot-sdk` drop
// injected into extension subprocesses. When set to an absolute path containing
// a valid `copilot-sdk/` folder (with `index.js` and `extension.js` at the
// root), the host injects the override into every forked extension; invalid or
// missing paths fall back to the bundled SDK silently.
ExtensionSDKPath *string
// CanvasHandler receives inbound canvas.open / canvas.close / canvas.action.invoke
// 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
}
SessionConfig configures a new session
type SessionContext ¶ added in v0.1.24
type SessionContext struct {
// WorkingDirectory is the working directory where the session was created
WorkingDirectory 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"`
}
SessionContext contains working directory context for a session
type SessionContextChangedData ¶ added in v0.2.2
type SessionContextChangedData = rpc.SessionContextChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCustomAgentsUpdatedData ¶ added in v0.2.2
type SessionCustomAgentsUpdatedData = rpc.SessionCustomAgentsUpdatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCustomNotificationData ¶ added in v1.0.0
type SessionCustomNotificationData = rpc.SessionCustomNotificationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEndHandler ¶ added in v0.1.20
type SessionEndHandler func(input SessionEndHookInput, invocation HookInvocation) (*SessionEndHookOutput, error)
SessionEndHandler handles session-end hook invocations
type SessionEndHookInput ¶ added in v0.1.20
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"`
}
SessionEndHookInput is the input for a session-end hook
func (SessionEndHookInput) MarshalJSON ¶ added in v1.0.0
func (h SessionEndHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*SessionEndHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *SessionEndHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type SessionEndHookOutput ¶ added in v0.1.20
type SessionEndHookOutput struct {
SuppressOutput bool `json:"suppressOutput,omitempty"`
CleanupActions []string `json:"cleanupActions,omitempty"`
SessionSummary string `json:"sessionSummary,omitempty"`
}
SessionEndHookOutput is the output for a session-end hook
type SessionErrorData ¶ added in v0.2.2
type SessionErrorData = rpc.SessionErrorData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEvent ¶
type SessionEvent = rpc.SessionEvent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEventData ¶ added in v0.2.2
type SessionEventData = rpc.SessionEventData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEventHandler ¶
type SessionEventHandler func(event SessionEvent)
SessionEventHandler is a callback for session events
type SessionEventType ¶ added in v0.1.15
type SessionEventType = rpc.SessionEventType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionExtensionsAttachmentsPushedData ¶ added in v1.0.0
type SessionExtensionsAttachmentsPushedData = rpc.SessionExtensionsAttachmentsPushedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionExtensionsLoadedData ¶ added in v0.2.2
type SessionExtensionsLoadedData = rpc.SessionExtensionsLoadedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionFSCapabilities ¶ added in v1.0.0
type SessionFSCapabilities struct {
// Sqlite indicates whether the provider supports SQLite query/exists operations.
Sqlite bool
}
SessionFSCapabilities declares optional provider capabilities.
type SessionFSConfig ¶ added in v1.0.0
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
}
SessionFSConfig configures a custom session filesystem provider.
type SessionFSFileInfo ¶ added in v1.0.0
type SessionFSFileInfo struct {
IsFile bool
IsDirectory bool
Size int64
Mtime time.Time
Birthtime time.Time
}
SessionFSFileInfo holds file metadata returned by SessionFSProvider.Stat.
type SessionFSProvider ¶ added in v1.0.0
type SessionFSProvider interface {
// ReadFile reads the full content of a file. Return os.ErrNotExist (or wrap it)
// if the file does not exist.
ReadFile(path string) (string, error)
// WriteFile writes content to a file, creating it and parent directories if needed.
// mode is an optional POSIX-style permission mode. Pass nil to use the OS default.
WriteFile(path string, content string, mode *int) error
// AppendFile appends content to a file, creating it and parent directories if needed.
// mode is an optional POSIX-style permission mode. Pass nil to use the OS default.
AppendFile(path string, content string, mode *int) error
// Exists checks whether the given path exists.
Exists(path string) (bool, error)
// Stat returns metadata about a file or directory.
// Return os.ErrNotExist if the path does not exist.
Stat(path string) (*SessionFSFileInfo, error)
// Mkdir creates a directory. If recursive is true, create parent directories as needed.
// mode is an optional POSIX-style permission mode (e.g., 0o755). Pass nil to use the OS default.
MakeDirectory(path string, recursive bool, mode *int) error
// Readdir lists the names of entries in a directory.
// Return os.ErrNotExist if the directory does not exist.
ReadDirectory(path string) ([]string, error)
// ReaddirWithTypes lists entries with type information.
// Return os.ErrNotExist if the directory does not exist.
ReadDirectoryWithTypes(path string) ([]rpc.SessionFSReaddirWithTypesEntry, error)
// Rm removes a file or directory. If recursive is true, remove contents too.
// If force is true, do not return an error when the path does not exist.
Remove(path string, recursive bool, force bool) error
// Rename moves/renames a file or directory.
Rename(src string, dest string) error
}
SessionFSProvider is the interface that SDK users implement to provide a session filesystem. Methods use idiomatic Go error handling: return an error for failures (the adapter maps os.ErrNotExist → ENOENT automatically).
To add SQLite support, also implement SessionFSSqliteProvider on the same type.
type SessionFSSqliteProvider ¶ added in v1.0.0
type SessionFSSqliteProvider interface {
// SqliteQuery executes a SQLite query against the provider's per-session database.
SqliteQuery(queryType rpc.SessionFSSqliteQueryType, query string, params map[string]any) (*SessionFSSqliteQueryResult, error)
// SqliteExists checks whether the provider has a SQLite database for the session.
SqliteExists() (bool, error)
}
SessionFSSqliteProvider is an optional interface that a SessionFSProvider may also implement to support per-session SQLite databases. The adapter checks for this interface at runtime using a type assertion. If the provider does not implement it, SQLite requests return an "unsupported" error.
Providers are already session-scoped (created per session by the factory), so these methods do not take a session ID parameter.
type SessionFSSqliteQueryResult ¶ added in v1.0.0
type SessionFSSqliteQueryResult struct {
Columns []string `json:"columns"`
Rows []map[string]any `json:"rows"`
RowsAffected int64 `json:"rowsAffected"`
LastInsertRowid *int64 `json:"lastInsertRowid,omitempty"`
}
SessionFSSqliteQueryResult holds the result of a SQLite query execution. Same shape as the generated RPC type but without the Error field, since providers signal errors by returning a Go error.
type SessionHandoffData ¶ added in v0.2.2
type SessionHandoffData = rpc.SessionHandoffData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionHooks ¶ added in v0.1.20
type SessionHooks struct {
OnPreToolUse PreToolUseHandler
OnPostToolUse PostToolUseHandler
OnPostToolUseFailure PostToolUseFailureHandler
OnUserPromptSubmitted UserPromptSubmittedHandler
OnSessionStart SessionStartHandler
OnSessionEnd SessionEndHandler
OnErrorOccurred ErrorOccurredHandler
OnPreMCPToolCall PreMCPToolCallHandler
}
SessionHooks configures hook handlers for a session
type SessionIdleData ¶ added in v0.2.2
type SessionIdleData = rpc.SessionIdleData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionInfoData ¶ added in v0.2.2
type SessionInfoData = rpc.SessionInfoData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionLifecycleEvent ¶ added in v0.1.21
type SessionLifecycleEvent struct {
Type SessionLifecycleEventType `json:"type"`
SessionID string `json:"sessionId"`
Metadata *SessionLifecycleEventMetadata `json:"metadata,omitempty"`
}
SessionLifecycleEvent represents a session lifecycle notification
type SessionLifecycleEventMetadata ¶ added in v0.1.21
type SessionLifecycleEventMetadata struct {
StartTime time.Time `json:"startTime"`
ModifiedTime time.Time `json:"modifiedTime"`
Summary *string `json:"summary,omitempty"`
}
SessionLifecycleEventMetadata contains optional metadata for lifecycle events
type SessionLifecycleEventType ¶ added in v0.1.21
type SessionLifecycleEventType string
SessionLifecycleEventType represents the type of session lifecycle event
const ( SessionLifecycleCreated SessionLifecycleEventType = "session.created" SessionLifecycleDeleted SessionLifecycleEventType = "session.deleted" SessionLifecycleUpdated SessionLifecycleEventType = "session.updated" SessionLifecycleForeground SessionLifecycleEventType = "session.foreground" SessionLifecycleBackground SessionLifecycleEventType = "session.background" )
type SessionLifecycleHandler ¶ added in v0.1.21
type SessionLifecycleHandler func(event SessionLifecycleEvent)
SessionLifecycleHandler is a callback for session lifecycle events
type SessionListFilter ¶ added in v0.1.24
type SessionListFilter struct {
// WorkingDirectory filters by exact working directory match
WorkingDirectory 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"`
}
SessionListFilter contains filter options for listing sessions
type SessionMCPServerStatusChangedData ¶ added in v1.0.0
type SessionMCPServerStatusChangedData = rpc.SessionMCPServerStatusChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionMCPServersLoadedData ¶ added in v1.0.0
type SessionMCPServersLoadedData = rpc.SessionMCPServersLoadedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionMetadata ¶ added in v0.1.19
type SessionMetadata struct {
SessionID string `json:"sessionId"`
StartTime time.Time `json:"startTime"`
ModifiedTime time.Time `json:"modifiedTime"`
Summary *string `json:"summary,omitempty"`
IsRemote bool `json:"isRemote"`
Context *SessionContext `json:"context,omitempty"`
}
SessionMetadata contains metadata about a session
type SessionMode ¶ added in v1.0.0
type SessionMode = rpc.SessionMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionModeChangedData ¶ added in v0.2.2
type SessionModeChangedData = rpc.SessionModeChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionModelChangeData ¶ added in v0.2.2
type SessionModelChangeData = rpc.SessionModelChangeData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionPermissionsChangedData ¶ added in v1.0.0
type SessionPermissionsChangedData = rpc.SessionPermissionsChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionPlanChangedData ¶ added in v0.2.2
type SessionPlanChangedData = rpc.SessionPlanChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionRemoteSteerableChangedData ¶ added in v0.2.2
type SessionRemoteSteerableChangedData = rpc.SessionRemoteSteerableChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionResumeData ¶ added in v0.2.2
type SessionResumeData = rpc.SessionResumeData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionScheduleCancelledData ¶ added in v1.0.0
type SessionScheduleCancelledData = rpc.SessionScheduleCancelledData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionScheduleCreatedData ¶ added in v1.0.0
type SessionScheduleCreatedData = rpc.SessionScheduleCreatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionShutdownData ¶ added in v0.2.2
type SessionShutdownData = rpc.SessionShutdownData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionSkillsLoadedData ¶ added in v0.2.2
type SessionSkillsLoadedData = rpc.SessionSkillsLoadedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionSnapshotRewindData ¶ added in v0.2.2
type SessionSnapshotRewindData = rpc.SessionSnapshotRewindData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionStartData ¶ added in v0.2.2
type SessionStartData = rpc.SessionStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionStartHandler ¶ added in v0.1.20
type SessionStartHandler func(input SessionStartHookInput, invocation HookInvocation) (*SessionStartHookOutput, error)
SessionStartHandler handles session-start hook invocations
type SessionStartHookInput ¶ added in v0.1.20
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"`
}
SessionStartHookInput is the input for a session-start hook
func (SessionStartHookInput) MarshalJSON ¶ added in v1.0.0
func (h SessionStartHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*SessionStartHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *SessionStartHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type SessionStartHookOutput ¶ added in v0.1.20
type SessionStartHookOutput struct {
AdditionalContext string `json:"additionalContext,omitempty"`
ModifiedConfig map[string]any `json:"modifiedConfig,omitempty"`
}
SessionStartHookOutput is the output for a session-start hook
type SessionTaskCompleteData ¶ added in v0.2.2
type SessionTaskCompleteData = rpc.SessionTaskCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionTitleChangedData ¶ added in v0.2.2
type SessionTitleChangedData = rpc.SessionTitleChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionToolsUpdatedData ¶ added in v0.2.2
type SessionToolsUpdatedData = rpc.SessionToolsUpdatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionTruncationData ¶ added in v0.2.2
type SessionTruncationData = rpc.SessionTruncationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionUI ¶ added in v0.2.1
type SessionUI struct {
// contains filtered or unexported fields
}
SessionUI provides convenience methods for showing elicitation dialogs to the user. Obtained via Session.UI. Methods error if the host does not support elicitation.
func (*SessionUI) Confirm ¶ added in v0.2.1
Confirm shows a confirmation dialog and returns the user's boolean answer. Returns false if the user declines or cancels.
func (*SessionUI) Elicitation ¶ added in v0.2.1
func (ui *SessionUI) Elicitation(ctx context.Context, message string, requestedSchema ElicitationSchema) (*ElicitationResult, error)
Elicitation shows a generic elicitation dialog with a custom schema.
type SessionUsageInfoData ¶ added in v0.2.2
type SessionUsageInfoData = rpc.SessionUsageInfoData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionWarningData ¶ added in v0.2.2
type SessionWarningData = rpc.SessionWarningData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionWorkspaceFileChangedData ¶ added in v0.2.2
type SessionWorkspaceFileChangedData = rpc.SessionWorkspaceFileChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SetModelOptions ¶ added in v0.2.0
type SetModelOptions struct {
// ReasoningEffort sets the reasoning effort level for the new model (e.g., "low", "medium", "high", "xhigh").
ReasoningEffort *string
// ReasoningSummary sets the reasoning summary mode for the new model.
// Use ReasoningSummaryNone to suppress summary output regardless of whether reasoning is enabled.
ReasoningSummary *ReasoningSummary
// ContextTier explicitly selects a context window tier for models that support it.
// Leave nil to use normal model behavior with no explicit tier.
ContextTier *ContextTier
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
}
SetModelOptions configures optional parameters for SetModel.
type ShutdownCodeChanges ¶ added in v0.3.0
type ShutdownCodeChanges = rpc.ShutdownCodeChanges
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetric ¶ added in v0.3.0
type ShutdownModelMetric = rpc.ShutdownModelMetric
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetricRequests ¶ added in v0.3.0
type ShutdownModelMetricRequests = rpc.ShutdownModelMetricRequests
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetricTokenDetail ¶ added in v1.0.0
type ShutdownModelMetricTokenDetail = rpc.ShutdownModelMetricTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetricUsage ¶ added in v0.3.0
type ShutdownModelMetricUsage = rpc.ShutdownModelMetricUsage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownTokenDetail ¶ added in v1.0.0
type ShutdownTokenDetail = rpc.ShutdownTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownType ¶ added in v0.1.21
type ShutdownType = rpc.ShutdownType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillInvokedData ¶ added in v0.2.2
type SkillInvokedData = rpc.SkillInvokedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillInvokedTrigger ¶ added in v1.0.0
type SkillInvokedTrigger = rpc.SkillInvokedTrigger
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillSource ¶ added in v1.0.0
type SkillSource = rpc.SkillSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillsLoadedSkill ¶ added in v0.3.0
type SkillsLoadedSkill = rpc.SkillsLoadedSkill
Session-event types are generated in the rpc package and aliased here for source compatibility.
type StdioConnection ¶ added in v1.0.0
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
}
StdioConnection spawns a runtime child process and communicates over its stdin/stdout pipes. This is the default when no connection is configured.
type SubagentCompletedData ¶ added in v0.2.2
type SubagentCompletedData = rpc.SubagentCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentDeselectedData ¶ added in v0.2.2
type SubagentDeselectedData = rpc.SubagentDeselectedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentFailedData ¶ added in v0.2.2
type SubagentFailedData = rpc.SubagentFailedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentSelectedData ¶ added in v0.2.2
type SubagentSelectedData = rpc.SubagentSelectedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentStartedData ¶ added in v0.2.2
type SubagentStartedData = rpc.SubagentStartedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemMessageAppendConfig ¶
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"`
}
SystemMessageAppendConfig is append mode: use CLI foundation with optional appended content.
type SystemMessageConfig ¶
type SystemMessageConfig struct {
Mode string `json:"mode,omitempty"`
Content string `json:"content,omitempty"`
Sections map[string]SectionOverride `json:"sections,omitempty"`
}
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 SystemMessageData ¶ added in v0.2.2
type SystemMessageData = rpc.SystemMessageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemMessageMetadata ¶ added in v0.3.0
type SystemMessageMetadata = rpc.SystemMessageMetadata
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemMessageReplaceConfig ¶
type SystemMessageReplaceConfig struct {
// Mode must be "replace"
Mode string `json:"mode"`
// Content is the complete system message (required)
Content string `json:"content"`
}
SystemMessageReplaceConfig is replace mode: use caller-provided system message entirely. Removes all SDK guardrails including security restrictions.
type SystemMessageRole ¶ added in v0.3.0
type SystemMessageRole = rpc.SystemMessageRole
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotification ¶ added in v0.3.0
type SystemNotification = rpc.SystemNotification
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationAgentCompleted ¶ added in v1.0.0
type SystemNotificationAgentCompleted = rpc.SystemNotificationAgentCompleted
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationAgentCompletedStatus ¶ added in v0.3.0
type SystemNotificationAgentCompletedStatus = rpc.SystemNotificationAgentCompletedStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationAgentIdle ¶ added in v1.0.0
type SystemNotificationAgentIdle = rpc.SystemNotificationAgentIdle
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationData ¶ added in v0.2.2
type SystemNotificationData = rpc.SystemNotificationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationInstructionDiscovered ¶ added in v1.0.0
type SystemNotificationInstructionDiscovered = rpc.SystemNotificationInstructionDiscovered
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationNewInboxMessage ¶ added in v1.0.0
type SystemNotificationNewInboxMessage = rpc.SystemNotificationNewInboxMessage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationShellCompleted ¶ added in v1.0.0
type SystemNotificationShellCompleted = rpc.SystemNotificationShellCompleted
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationShellDetachedCompleted ¶ added in v1.0.0
type SystemNotificationShellDetachedCompleted = rpc.SystemNotificationShellDetachedCompleted
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationType ¶ added in v0.3.0
type SystemNotificationType = rpc.SystemNotificationType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type TCPConnection ¶ added in v1.0.0
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
}
TCPConnection spawns a runtime child process that listens on a TCP socket and connects to it.
type TelemetryConfig ¶ added in v0.2.0
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
}
TelemetryConfig configures OpenTelemetry integration for the Copilot CLI process.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]any `json:"parameters,omitzero"`
OverridesBuiltInTool bool `json:"overridesBuiltInTool,omitempty"`
SkipPermission bool `json:"skipPermission,omitempty"`
// Handler is optional. When nil, the SDK exposes the tool declaration but does
// not automatically invoke it.
Handler ToolHandler `json:"-"`
}
func DefineTool ¶
func DefineTool[T any, U any](name, description string, handler func(T, ToolInvocation) (U, error)) Tool
DefineTool creates a Tool with automatic JSON schema generation from a typed handler function. The handler receives typed arguments (automatically unmarshaled from JSON) and the raw ToolInvocation. The handler can return any value - strings pass through directly, other types are JSON-serialized.
Example:
type GetWeatherParams struct {
City string `json:"city" jsonschema:"city name"`
Unit string `json:"unit" jsonschema:"temperature unit (celsius or fahrenheit)"`
}
tool := copilot.DefineTool("get_weather", "Get weather for a city",
func(params GetWeatherParams, inv copilot.ToolInvocation) (any, error) {
return fmt.Sprintf("Weather in %s: 22°%s", params.City, params.Unit), nil
})
type ToolBinaryResult ¶
type ToolBinaryResult struct {
Data string `json:"data"`
MIMEType string `json:"mimeType"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
}
ToolBinaryResult represents binary payloads returned by tools.
type ToolExecutionCompleteContent ¶ added in v0.3.0
type ToolExecutionCompleteContent = rpc.ToolExecutionCompleteContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentAudio ¶ added in v1.0.0
type ToolExecutionCompleteContentAudio = rpc.ToolExecutionCompleteContentAudio
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentImage ¶ added in v1.0.0
type ToolExecutionCompleteContentImage = rpc.ToolExecutionCompleteContentImage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResource ¶ added in v1.0.0
type ToolExecutionCompleteContentResource = rpc.ToolExecutionCompleteContentResource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceDetails ¶ added in v1.0.0
type ToolExecutionCompleteContentResourceDetails = rpc.ToolExecutionCompleteContentResourceDetails
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceLink ¶ added in v1.0.0
type ToolExecutionCompleteContentResourceLink = rpc.ToolExecutionCompleteContentResourceLink
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceLinkIcon ¶ added in v0.3.0
type ToolExecutionCompleteContentResourceLinkIcon = rpc.ToolExecutionCompleteContentResourceLinkIcon
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceLinkIconTheme ¶ added in v0.3.0
type ToolExecutionCompleteContentResourceLinkIconTheme = rpc.ToolExecutionCompleteContentResourceLinkIconTheme
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentTerminal ¶ added in v1.0.0
type ToolExecutionCompleteContentTerminal = rpc.ToolExecutionCompleteContentTerminal
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentText ¶ added in v1.0.0
type ToolExecutionCompleteContentText = rpc.ToolExecutionCompleteContentText
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentType ¶ added in v0.3.0
type ToolExecutionCompleteContentType = rpc.ToolExecutionCompleteContentType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteData ¶ added in v0.2.2
type ToolExecutionCompleteData = rpc.ToolExecutionCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteError ¶ added in v0.3.0
type ToolExecutionCompleteError = rpc.ToolExecutionCompleteError
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteResult ¶ added in v0.3.0
type ToolExecutionCompleteResult = rpc.ToolExecutionCompleteResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescription ¶ added in v1.0.0
type ToolExecutionCompleteToolDescription = rpc.ToolExecutionCompleteToolDescription
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescriptionMeta ¶ added in v1.0.0
type ToolExecutionCompleteToolDescriptionMeta = rpc.ToolExecutionCompleteToolDescriptionMeta
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescriptionMetaUI ¶ added in v1.0.0
type ToolExecutionCompleteToolDescriptionMetaUI = rpc.ToolExecutionCompleteToolDescriptionMetaUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescriptionMetaUIVisibility ¶ added in v1.0.0
type ToolExecutionCompleteToolDescriptionMetaUIVisibility = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibility
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResource ¶ added in v1.0.0
type ToolExecutionCompleteUIResource = rpc.ToolExecutionCompleteUIResource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMeta ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMeta = rpc.ToolExecutionCompleteUIResourceMeta
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUI ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMetaUI = rpc.ToolExecutionCompleteUIResourceMetaUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUICsp ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMetaUICsp = rpc.ToolExecutionCompleteUIResourceMetaUICsp
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissions ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMetaUIPermissions = rpc.ToolExecutionCompleteUIResourceMetaUIPermissions
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsCamera ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMetaUIPermissionsCamera = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsCamera
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone ¶ added in v1.0.0
type ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionPartialResultData ¶ added in v0.2.2
type ToolExecutionPartialResultData = rpc.ToolExecutionPartialResultData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionProgressData ¶ added in v0.2.2
type ToolExecutionProgressData = rpc.ToolExecutionProgressData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionStartData ¶ added in v0.2.2
type ToolExecutionStartData = rpc.ToolExecutionStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolHandler ¶
type ToolHandler func(invocation ToolInvocation) (ToolResult, error)
ToolHandler executes a tool invocation. The handler should return a ToolResult. Returning an error marks the tool execution as a failure.
type ToolInvocation ¶
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
}
ToolInvocation describes a tool call initiated by Copilot
type ToolResult ¶
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"`
}
ToolResult represents the result of a tool invocation.
func ConvertMCPCallToolResult ¶ added in v0.3.0
func ConvertMCPCallToolResult(value any) (ToolResult, bool)
ConvertMCPCallToolResult converts an MCP CallToolResult value (a map or struct with a "content" array and optional "isError" bool) into a ToolResult. Returns the converted ToolResult and true if the value matched the expected shape, or a zero ToolResult and false otherwise.
type ToolSet ¶ added in v1.0.0
type ToolSet struct {
// contains filtered or unexported fields
}
ToolSet builds a list of source-qualified tool filter patterns (`builtin:*`, `mcp:<name>`, `custom:*`, ...) for use with [SessionConfig.AvailableTools] or [SessionConfig.ExcludedTools].
Tools are classified by the runtime at registration time (not from name parsing), so AddBuiltIn("foo") matches only tools the runtime registered as built-in, even if an MCP server or custom-agent extension happens to register a tool with the same wire name.
ToolSet's zero value is ready to use. Convert to []string via ToolSet.ToSlice before passing to SessionConfig fields, e.g. `(&ToolSet{}).AddBuiltIn(...).ToSlice()`.
func (*ToolSet) AddBuiltIn ¶ added in v1.0.0
AddBuiltIn adds one or more built-in tool patterns. Pass a specific tool name (e.g. "bash") or "*" to match all built-in tools.
func (*ToolSet) AddCustom ¶ added in v1.0.0
AddCustom adds a custom-tool pattern. Matches tools registered via [SessionConfig.Tools] or via custom agents.
type ToolUserRequestedData ¶ added in v0.2.2
type ToolUserRequestedData = rpc.ToolUserRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UICapabilities ¶ added in v0.2.1
type UICapabilities struct {
// Elicitation indicates whether the host supports interactive elicitation dialogs.
Elicitation bool `json:"elicitation,omitempty"`
// MCPApps indicates whether the runtime has accepted the session's MCP Apps
// (SEP-1865) opt-in. True when the consumer set EnableMCPApps=true on
// create/resume AND the runtime's MCP_APPS feature flag (or
// COPILOT_MCP_APPS=true env override) is on. Otherwise false, indicating
// the runtime silently dropped the opt-in.
//
// Experimental: MCPApps is part of an experimental wire-protocol surface
// (SEP-1865) and may change or be removed in a future release.
MCPApps bool `json:"mcpApps,omitempty"`
}
UICapabilities describes host UI feature support.
type UIInputOptions ¶ added in v1.0.0
type UIInputOptions 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
}
UIInputOptions configures a text input field for the Input convenience method.
type URIConnection ¶ added in v1.0.0
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
}
URIConnection connects to an already-running runtime at the given URL. The SDK does not spawn a process in this mode.
type UserInputCompletedData ¶ added in v0.2.2
type UserInputCompletedData = rpc.UserInputCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserInputHandler ¶ added in v0.1.20
type UserInputHandler func(request UserInputRequest, invocation UserInputInvocation) (UserInputResponse, error)
UserInputHandler handles user input requests from the agent The handler should return a UserInputResponse. Returning an error fails the request.
type UserInputInvocation ¶ added in v0.1.20
type UserInputInvocation struct {
SessionID string
}
UserInputInvocation provides context about a user input request
type UserInputRequest ¶ added in v0.1.20
UserInputRequest represents a request for user input from the agent
type UserInputRequestedData ¶ added in v0.2.2
type UserInputRequestedData = rpc.UserInputRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserInputResponse ¶ added in v0.1.20
UserInputResponse represents the user's response to an input request
type UserMessageAgentMode ¶ added in v0.3.0
type UserMessageAgentMode = rpc.UserMessageAgentMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserMessageData ¶ added in v0.2.2
type UserMessageData = rpc.UserMessageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserPromptSubmittedHandler ¶ added in v0.1.20
type UserPromptSubmittedHandler func(input UserPromptSubmittedHookInput, invocation HookInvocation) (*UserPromptSubmittedHookOutput, error)
UserPromptSubmittedHandler handles user-prompt-submitted hook invocations
type UserPromptSubmittedHookInput ¶ added in v0.1.20
type UserPromptSubmittedHookInput struct {
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Prompt string `json:"prompt"`
}
UserPromptSubmittedHookInput is the input for a user-prompt-submitted hook
func (UserPromptSubmittedHookInput) MarshalJSON ¶ added in v1.0.0
func (h UserPromptSubmittedHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (*UserPromptSubmittedHookInput) UnmarshalJSON ¶ added in v1.0.0
func (h *UserPromptSubmittedHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type UserPromptSubmittedHookOutput ¶ added in v0.1.20
type UserPromptSubmittedHookOutput struct {
ModifiedPrompt string `json:"modifiedPrompt,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
}
UserPromptSubmittedHookOutput is the output for a user-prompt-submitted hook
type UserToolSessionApproval ¶ added in v1.0.0
type UserToolSessionApproval = rpc.UserToolSessionApproval
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalCommands ¶ added in v1.0.0
type UserToolSessionApprovalCommands = rpc.UserToolSessionApprovalCommands
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalCustomTool ¶ added in v1.0.0
type UserToolSessionApprovalCustomTool = rpc.UserToolSessionApprovalCustomTool
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalExtensionManagement ¶ added in v1.0.0
type UserToolSessionApprovalExtensionManagement = rpc.UserToolSessionApprovalExtensionManagement
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalExtensionPermissionAccess ¶ added in v1.0.0
type UserToolSessionApprovalExtensionPermissionAccess = rpc.UserToolSessionApprovalExtensionPermissionAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalKind ¶ added in v1.0.0
type UserToolSessionApprovalKind = rpc.UserToolSessionApprovalKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalMCP ¶ added in v1.0.0
type UserToolSessionApprovalMCP = rpc.UserToolSessionApprovalMCP
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalMemory ¶ added in v1.0.0
type UserToolSessionApprovalMemory = rpc.UserToolSessionApprovalMemory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalRead ¶ added in v1.0.0
type UserToolSessionApprovalRead = rpc.UserToolSessionApprovalRead
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalWrite ¶ added in v1.0.0
type UserToolSessionApprovalWrite = rpc.UserToolSessionApprovalWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkingDirectoryContext ¶ added in v0.3.0
type WorkingDirectoryContext = rpc.WorkingDirectoryContext
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkingDirectoryContextHostType ¶ added in v0.3.0
type WorkingDirectoryContextHostType = rpc.WorkingDirectoryContextHostType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkspaceFileChangedOperation ¶ added in v0.3.0
type WorkspaceFileChangedOperation = rpc.WorkspaceFileChangedOperation
Session-event types are generated in the rpc package and aliased here for source compatibility.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
bundler
command
Bundler downloads Copilot CLI binaries and packages them as a binary file, along with a Go source file that embeds the binary and metadata.
|
Bundler downloads Copilot CLI binaries and packages them as a binary file, along with a Go source file that embeds the binary and metadata. |
|
internal
|
|
|
samples
module
|