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 AssistantIntentData
- type AssistantMessageData
- type AssistantMessageDeltaData
- type AssistantMessageToolRequest
- type AssistantMessageToolRequestType
- type AssistantReasoningData
- type AssistantReasoningDeltaData
- type AssistantStreamingDeltaData
- type AssistantTurnEndData
- type AssistantTurnStartData
- type AssistantUsageCopilotUsage
- type AssistantUsageCopilotUsageTokenDetail
- type AssistantUsageData
- type AssistantUsageQuotaSnapshot
- type Attachment
- type AttachmentType
- type AutoModeSwitchCompletedData
- type AutoModeSwitchRequestedData
- type AzureProviderOptions
- type CapabilitiesChangedData
- type CapabilitiesChangedUI
- type Client
- func (c *Client) ActualPort() int
- 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) SetForegroundSessionID(ctx context.Context, sessionID string) error
- func (c *Client) Start(ctx context.Context) error
- func (c *Client) State() ConnectionState
- func (c *Client) Stop() error
- type ClientOptions
- type CommandCompletedData
- type CommandContext
- type CommandDefinition
- type CommandExecuteData
- type CommandHandler
- type CommandQueuedData
- type CommandsChangedCommand
- type CommandsChangedData
- type CompactionCompleteCompactionTokensUsed
- type CompactionCompleteCompactionTokensUsedCopilotUsage
- type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail
- type ConnectionState
- type CustomAgentConfig
- type CustomAgentsUpdatedAgent
- type DefaultAgentConfig
- type ElicitationCompletedAction
- type ElicitationCompletedData
- type ElicitationContext
- type ElicitationHandler
- type ElicitationRequestedData
- type ElicitationRequestedMode
- type ElicitationRequestedSchema
- type ElicitationResult
- type ErrorOccurredHandler
- type ErrorOccurredHookInput
- type ErrorOccurredHookOutput
- type ExitPlanModeCompletedData
- type ExitPlanModeRequestedData
- 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 HookStartData
- type InfiniteSessionConfig
- type InputOptions
- type LogOptions
- type MCPHTTPServerConfig
- type MCPServerConfig
- type MCPStdioServerConfig
- type McpOauthCompletedData
- type McpOauthRequiredData
- type McpOauthRequiredStaticClientConfig
- type McpServerStatusChangedStatus
- type McpServersLoadedServer
- type McpServersLoadedServerStatus
- type MessageOptions
- type ModelBilling
- type ModelCapabilities
- type ModelCapabilitiesOverride
- type ModelCapabilitiesOverrideLimits
- type ModelCapabilitiesOverrideLimitsVision
- type ModelCapabilitiesOverrideSupports
- type ModelInfo
- type ModelLimits
- type ModelPolicy
- type ModelSupports
- type ModelVisionLimits
- type PendingMessagesModifiedData
- type PermissionCompletedData
- type PermissionCompletedKind
- type PermissionCompletedResult
- type PermissionHandlerFunc
- type PermissionInvocation
- type PermissionPromptRequest
- type PermissionPromptRequestKind
- type PermissionPromptRequestMemoryAction
- type PermissionPromptRequestMemoryDirection
- type PermissionPromptRequestPathAccessKind
- type PermissionRequest
- type PermissionRequestCommand
- type PermissionRequestKind
- type PermissionRequestMemoryAction
- type PermissionRequestMemoryDirection
- type PermissionRequestResult
- type PermissionRequestResultKind
- type PermissionRequestShellCommand
- type PermissionRequestShellPossibleURL
- type PermissionRequestedData
- type PingResponse
- type PlanChangedOperation
- type PossibleURL
- type PostToolUseHandler
- type PostToolUseHookInput
- type PostToolUseHookOutput
- type PreToolUseHandler
- type PreToolUseHookInput
- type PreToolUseHookOutput
- type ProviderConfig
- type RawSessionEventData
- type ResumeSessionConfig
- 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) Destroy() errordeprecated
- func (s *Session) Disconnect() error
- func (s *Session) GetMessages(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) Send(ctx context.Context, options MessageOptions) (string, error)
- func (s *Session) SendAndWait(ctx context.Context, options MessageOptions) (*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 SessionBackgroundTasksChangedData
- type SessionCapabilities
- type SessionCompactionCompleteData
- type SessionCompactionStartData
- type SessionConfig
- type SessionContext
- type SessionContextChangedData
- type SessionCustomAgentsUpdatedData
- type SessionEndHandler
- type SessionEndHookInput
- type SessionEndHookOutput
- type SessionErrorData
- type SessionEvent
- type SessionEventData
- type SessionEventHandler
- type SessionEventType
- type SessionExtensionsLoadedData
- type SessionFsConfig
- type SessionFsFileInfo
- type SessionFsProvider
- 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 SessionModeChangedData
- type SessionModelChangeData
- type SessionPlanChangedData
- type SessionRemoteSteerableChangedData
- type SessionResumeData
- 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 rpc.UIElicitationSchema) (*ElicitationResult, error)
- func (ui *SessionUI) Input(ctx context.Context, message string, opts *InputOptions) (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 ShutdownModelMetricUsage
- type ShutdownType
- type SkillInvokedData
- type SkillsLoadedSkill
- 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 SystemNotificationAgentCompletedStatus
- type SystemNotificationData
- type SystemNotificationType
- type TelemetryConfig
- type Tool
- type ToolBinaryResult
- type ToolExecutionCompleteContent
- type ToolExecutionCompleteContentResourceLinkIcon
- type ToolExecutionCompleteContentResourceLinkIconTheme
- type ToolExecutionCompleteContentType
- type ToolExecutionCompleteData
- type ToolExecutionCompleteError
- type ToolExecutionCompleteResult
- type ToolExecutionPartialResultData
- type ToolExecutionProgressData
- type ToolExecutionStartData
- type ToolHandler
- type ToolInvocation
- type ToolResult
- type ToolUserRequestedData
- type UICapabilities
- type UserInputCompletedData
- type UserInputHandler
- type UserInputInvocation
- type UserInputRequest
- type UserInputRequestedData
- type UserInputResponse
- type UserMessageAgentMode
- type UserMessageAttachment
- type UserMessageAttachmentFileLineRange
- type UserMessageAttachmentGithubReferenceType
- type UserMessageAttachmentSelectionDetails
- type UserMessageAttachmentSelectionDetailsEnd
- type UserMessageAttachmentSelectionDetailsStart
- type UserMessageAttachmentType
- type UserMessageData
- type UserPromptSubmittedHandler
- type UserPromptSubmittedHookInput
- type UserPromptSubmittedHookOutput
- type WorkingDirectoryContext
- type WorkingDirectoryContextHostType
- type WorkspaceFileChangedOperation
Constants ¶
const ( AttachmentTypeFile = UserMessageAttachmentTypeFile AttachmentTypeDirectory = UserMessageAttachmentTypeDirectory AttachmentTypeSelection = UserMessageAttachmentTypeSelection AttachmentTypeGithubReference = UserMessageAttachmentTypeGithubReference AttachmentTypeBlob = UserMessageAttachmentTypeBlob )
Constant aliases for convenience.
const ( SectionIdentity = "identity" SectionTone = "tone" SectionToolEfficiency = "tool_efficiency" SectionEnvironmentContext = "environment_context" SectionCodeChangeRules = "code_change_rules" SectionGuidelines = "guidelines" SectionSafety = "safety" SectionToolInstructions = "tool_instructions" SectionCustomInstructions = "custom_instructions" SectionLastInstructions = "last_instructions" )
Known system prompt section identifiers for the "customize" mode.
const ( // PermissionRequestResultKindApproved indicates the permission was approved for this one instance. PermissionRequestResultKindApproved PermissionRequestResultKind = "approve-once" // PermissionRequestResultKindRejected indicates the permission was denied interactively by the user. PermissionRequestResultKindRejected PermissionRequestResultKind = "reject" // PermissionRequestResultKindUserNotAvailable indicates the permission was denied because // user confirmation was unavailable. PermissionRequestResultKindUserNotAvailable PermissionRequestResultKind = "user-not-available" // PermissionRequestResultKindNoResult indicates no permission decision was made. PermissionRequestResultKindNoResult PermissionRequestResultKind = "no-result" // Deprecated: Use PermissionRequestResultKindRejected instead. PermissionRequestResultKindDeniedInteractivelyByUser = PermissionRequestResultKindRejected // Deprecated: Use PermissionRequestResultKindUserNotAvailable instead. PermissionRequestResultKindDeniedCouldNotRequestFromUser = PermissionRequestResultKindUserNotAvailable // Deprecated: Use PermissionRequestResultKindUserNotAvailable instead. PermissionRequestResultKindDeniedByRules = PermissionRequestResultKindUserNotAvailable )
const SdkProtocolVersion = 3
SdkProtocolVersion is the SDK protocol version. This must match the version expected by the copilot-agent-runtime server.
Variables ¶
var PermissionHandler = struct { // ApproveAll approves all permission requests. ApproveAll PermissionHandlerFunc }{ ApproveAll: func(_ PermissionRequest, _ PermissionInvocation) (PermissionRequestResult, error) { return PermissionRequestResult{Kind: PermissionRequestResultKindApproved}, 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 ¶
func GetSdkProtocolVersion() int
GetSdkProtocolVersion returns the SDK protocol version.
Types ¶
type AbortData ¶ added in v0.2.2
type AbortData struct {
// Reason the current turn was aborted (e.g., "user initiated")
Reason string `json:"reason"`
}
Turn abort information including the reason for termination
type AssistantIntentData ¶ added in v0.2.2
type AssistantIntentData struct {
// Short description of what the agent is currently doing or planning to do
Intent string `json:"intent"`
}
Agent intent description for current activity or plan
type AssistantMessageData ¶ added in v0.2.2
type AssistantMessageData struct {
// The assistant's text response content
Content string `json:"content"`
// Encrypted reasoning content from OpenAI models. Session-bound and stripped on resume.
EncryptedContent *string `json:"encryptedContent,omitempty"`
// CAPI interaction ID for correlating this message with upstream telemetry
InteractionID *string `json:"interactionId,omitempty"`
// Unique identifier for this assistant message
MessageID string `json:"messageId"`
// Actual output token count from the API response (completion_tokens), used for accurate token accounting
OutputTokens *float64 `json:"outputTokens,omitempty"`
// Tool call ID of the parent tool invocation when this event originates from a sub-agent
// Deprecated: ParentToolCallID is deprecated.
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
// Generation phase for phased-output models (e.g., thinking vs. response phases)
Phase *string `json:"phase,omitempty"`
// Opaque/encrypted extended thinking data from Anthropic models. Session-bound and stripped on resume.
ReasoningOpaque *string `json:"reasoningOpaque,omitempty"`
// Readable reasoning text from the model's extended thinking
ReasoningText *string `json:"reasoningText,omitempty"`
// GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs
RequestID *string `json:"requestId,omitempty"`
// Tool invocations requested by the assistant in this message
ToolRequests []AssistantMessageToolRequest `json:"toolRequests,omitempty"`
}
Assistant response containing text content, optional tool requests, and interaction metadata
type AssistantMessageDeltaData ¶ added in v0.2.2
type AssistantMessageDeltaData struct {
// Incremental text chunk to append to the message content
DeltaContent string `json:"deltaContent"`
// Message ID this delta belongs to, matching the corresponding assistant.message event
MessageID string `json:"messageId"`
// Tool call ID of the parent tool invocation when this event originates from a sub-agent
// Deprecated: ParentToolCallID is deprecated.
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
}
Streaming assistant message delta for incremental response updates
type AssistantMessageToolRequest ¶ added in v0.3.0
type AssistantMessageToolRequest struct {
// Arguments to pass to the tool, format depends on the tool
Arguments any `json:"arguments,omitempty"`
// Resolved intention summary describing what this specific call does
IntentionSummary *string `json:"intentionSummary,omitempty"`
// Name of the MCP server hosting this tool, when the tool is an MCP tool
McpServerName *string `json:"mcpServerName,omitempty"`
// Name of the tool being invoked
Name string `json:"name"`
// Unique identifier for this tool call
ToolCallID string `json:"toolCallId"`
// Human-readable display title for the tool
ToolTitle *string `json:"toolTitle,omitempty"`
// Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent.
Type *AssistantMessageToolRequestType `json:"type,omitempty"`
}
A tool invocation request from the assistant
type AssistantMessageToolRequestType ¶ added in v0.3.0
type AssistantMessageToolRequestType string
Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent.
const ( AssistantMessageToolRequestTypeFunction AssistantMessageToolRequestType = "function" AssistantMessageToolRequestTypeCustom AssistantMessageToolRequestType = "custom" )
type AssistantReasoningData ¶ added in v0.2.2
type AssistantReasoningData struct {
// The complete extended thinking text from the model
Content string `json:"content"`
// Unique identifier for this reasoning block
ReasoningID string `json:"reasoningId"`
}
Assistant reasoning content for timeline display with complete thinking text
type AssistantReasoningDeltaData ¶ added in v0.2.2
type AssistantReasoningDeltaData struct {
// Incremental text chunk to append to the reasoning content
DeltaContent string `json:"deltaContent"`
// Reasoning block ID this delta belongs to, matching the corresponding assistant.reasoning event
ReasoningID string `json:"reasoningId"`
}
Streaming reasoning delta for incremental extended thinking updates
type AssistantStreamingDeltaData ¶ added in v0.2.2
type AssistantStreamingDeltaData struct {
// Cumulative total bytes received from the streaming response so far
TotalResponseSizeBytes float64 `json:"totalResponseSizeBytes"`
}
Streaming response progress with cumulative byte count
type AssistantTurnEndData ¶ added in v0.2.2
type AssistantTurnEndData struct {
// Identifier of the turn that has ended, matching the corresponding assistant.turn_start event
TurnID string `json:"turnId"`
}
Turn completion metadata including the turn identifier
type AssistantTurnStartData ¶ added in v0.2.2
type AssistantTurnStartData struct {
// CAPI interaction ID for correlating this turn with upstream telemetry
InteractionID *string `json:"interactionId,omitempty"`
// Identifier for this turn within the agentic loop, typically a stringified turn number
TurnID string `json:"turnId"`
}
Turn initialization metadata including identifier and interaction tracking
type AssistantUsageCopilotUsage ¶ added in v0.3.0
type AssistantUsageCopilotUsage struct {
// Itemized token usage breakdown
TokenDetails []AssistantUsageCopilotUsageTokenDetail `json:"tokenDetails"`
// Total cost in nano-AIU (AI Units) for this request
TotalNanoAiu float64 `json:"totalNanoAiu"`
}
Per-request cost and usage data from the CAPI copilot_usage response field
type AssistantUsageCopilotUsageTokenDetail ¶ added in v0.3.0
type AssistantUsageCopilotUsageTokenDetail struct {
// Number of tokens in this billing batch
BatchSize float64 `json:"batchSize"`
// Cost per batch of tokens
CostPerBatch float64 `json:"costPerBatch"`
// Total token count for this entry
TokenCount float64 `json:"tokenCount"`
// Token category (e.g., "input", "output")
TokenType string `json:"tokenType"`
}
Token usage detail for a single billing category
type AssistantUsageData ¶ added in v0.2.2
type AssistantUsageData struct {
// Completion ID from the model provider (e.g., chatcmpl-abc123)
APICallID *string `json:"apiCallId,omitempty"`
// Number of tokens read from prompt cache
CacheReadTokens *float64 `json:"cacheReadTokens,omitempty"`
// Number of tokens written to prompt cache
CacheWriteTokens *float64 `json:"cacheWriteTokens,omitempty"`
// Per-request cost and usage data from the CAPI copilot_usage response field
CopilotUsage *AssistantUsageCopilotUsage `json:"copilotUsage,omitempty"`
// Model multiplier cost for billing purposes
Cost *float64 `json:"cost,omitempty"`
// Duration of the API call in milliseconds
Duration *float64 `json:"duration,omitempty"`
// What initiated this API call (e.g., "sub-agent", "mcp-sampling"); absent for user-initiated calls
Initiator *string `json:"initiator,omitempty"`
// Number of input tokens consumed
InputTokens *float64 `json:"inputTokens,omitempty"`
// Average inter-token latency in milliseconds. Only available for streaming requests
InterTokenLatencyMs *float64 `json:"interTokenLatencyMs,omitempty"`
// Model identifier used for this API call
Model string `json:"model"`
// Number of output tokens produced
OutputTokens *float64 `json:"outputTokens,omitempty"`
// Parent tool call ID when this usage originates from a sub-agent
// Deprecated: ParentToolCallID is deprecated.
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
// GitHub request tracing ID (x-github-request-id header) for server-side log correlation
ProviderCallID *string `json:"providerCallId,omitempty"`
// Per-quota resource usage snapshots, keyed by quota identifier
QuotaSnapshots map[string]AssistantUsageQuotaSnapshot `json:"quotaSnapshots,omitempty"`
// Reasoning effort level used for model calls, if applicable (e.g. "low", "medium", "high", "xhigh")
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
// Number of output tokens used for reasoning (e.g., chain-of-thought)
ReasoningTokens *float64 `json:"reasoningTokens,omitempty"`
// Time to first token in milliseconds. Only available for streaming requests
TtftMs *float64 `json:"ttftMs,omitempty"`
}
LLM API call usage metrics including tokens, costs, quotas, and billing information
type AssistantUsageQuotaSnapshot ¶ added in v0.3.0
type AssistantUsageQuotaSnapshot struct {
// Total requests allowed by the entitlement
EntitlementRequests float64 `json:"entitlementRequests"`
// Whether the user has an unlimited usage entitlement
IsUnlimitedEntitlement bool `json:"isUnlimitedEntitlement"`
// Number of requests over the entitlement limit
Overage float64 `json:"overage"`
// Whether overage is allowed when quota is exhausted
OverageAllowedWithExhaustedQuota bool `json:"overageAllowedWithExhaustedQuota"`
// Percentage of quota remaining (0.0 to 1.0)
RemainingPercentage float64 `json:"remainingPercentage"`
// Date when the quota resets
ResetDate *time.Time `json:"resetDate,omitempty"`
// Whether usage is still permitted after quota exhaustion
UsageAllowedWithExhaustedQuota bool `json:"usageAllowedWithExhaustedQuota"`
// Number of requests already consumed
UsedRequests float64 `json:"usedRequests"`
}
type AttachmentType ¶ added in v0.1.15
type AttachmentType = UserMessageAttachmentType
Type aliases for convenience.
type AutoModeSwitchCompletedData ¶ added in v0.3.0
type AutoModeSwitchCompletedData struct {
// Request ID of the resolved request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
// The user's choice: 'yes', 'yes_always', or 'no'
Response string `json:"response"`
}
Auto mode switch completion notification
type AutoModeSwitchRequestedData ¶ added in v0.3.0
type AutoModeSwitchRequestedData struct {
// The rate limit error code that triggered this request
ErrorCode *string `json:"errorCode,omitempty"`
// Unique identifier for this request; used to respond via session.respondToAutoModeSwitch()
RequestID string `json:"requestId"`
}
Auto mode switch request notification requiring user approval
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 CapabilitiesChangedData ¶ added in v0.2.2
type CapabilitiesChangedData struct {
// UI capability changes
UI *CapabilitiesChangedUI `json:"ui,omitempty"`
}
Session capability change notification
type CapabilitiesChangedUI ¶ added in v0.3.0
type CapabilitiesChangedUI struct {
// Whether elicitation is now supported
Elicitation *bool `json:"elicitation,omitempty"`
}
UI capability changes
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{
CLIUrl: "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 CLI client with the given options.
If options is nil, default options are used (spawns CLI server using stdio). The client is not connected after creation; call Client.Start to connect.
Example:
// Default options
client := copilot.NewClient(nil)
// Custom options
client := copilot.NewClient(&copilot.ClientOptions{
CLIPath: "/usr/local/bin/copilot",
LogLevel: "debug",
})
func (*Client) ActualPort ¶ added in v0.1.31
ActualPort returns the TCP port the CLI server is listening on. Returns 0 if the client is not connected or using stdio transport.
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 cwd, 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 %d", 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. The config must include an OnPermissionRequest handler.
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) 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 CLIUrl), 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) State ¶ added in v0.1.21
func (c *Client) State() ConnectionState
State returns the current connection state of the client.
Possible states: StateDisconnected, StateConnecting, StateConnected, StateError.
Example:
if client.State() == copilot.StateConnected {
session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
}
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 ClientOptions ¶
type ClientOptions struct {
// CLIPath is the path to the Copilot CLI executable (default: "copilot")
CLIPath string
// CLIArgs are extra arguments to pass to the CLI executable (inserted before SDK-managed args)
CLIArgs []string
// Cwd is the working directory for the CLI process (default: "" = inherit from current process)
Cwd string
// Port for TCP transport (default: 0 = random port)
Port int
// UseStdio controls whether to use stdio transport instead of TCP.
// Default: nil (use default = true, i.e. stdio). Use Bool(false) to explicitly select TCP.
UseStdio *bool
// CLIUrl is the URL of an existing Copilot CLI server to connect to over TCP
// Format: "host:port", "http://host:port", or just "port" (defaults to localhost)
// Examples: "localhost:8080", "http://127.0.0.1:9000", "8080"
// Mutually exclusive with CLIPath, UseStdio
CLIUrl string
// LogLevel for the CLI server
LogLevel string
// AutoStart automatically starts the CLI server on first use (default: true).
// Use Bool(false) to disable.
AutoStart *bool
// Deprecated: AutoRestart has no effect and will be removed in a future release.
AutoRestart *bool
// Env is the environment variables for the CLI process (default: inherits from current process).
// Each entry is of the form "key=value".
// If Env is nil, the new process uses the current process's environment.
// If Env contains duplicate environment keys, only the last value in the
// slice for each duplicate key is used.
Env []string
// GitHubToken is the GitHub token to use for authentication.
// When provided, the token is passed to the CLI server via environment variable.
// This takes priority over other authentication methods.
GitHubToken string
// UseLoggedInUser controls whether to use the logged-in user for authentication.
// When true, the CLI server will attempt to use stored OAuth tokens or gh CLI auth.
// When false, only explicit tokens (GitHubToken or environment variables) are used.
// Default: true (but defaults to false when GitHubToken is provided).
// Use Bool(false) to explicitly disable.
UseLoggedInUser *bool
// OnListModels is a custom handler for listing available models.
// When provided, client.ListModels() calls this handler instead of
// querying the CLI server. Useful in BYOK mode to return models
// available from your custom provider.
OnListModels func(ctx context.Context) ([]ModelInfo, error)
// SessionFs configures a custom session filesystem provider.
// When provided, the client registers as the session filesystem provider
// on connection, routing session-scoped file I/O through per-session handlers.
SessionFs *SessionFsConfig
// Telemetry configures OpenTelemetry integration for the Copilot CLI process.
// When non-nil, COPILOT_OTEL_ENABLED=true is set and any populated fields
// are mapped to the corresponding environment variables.
Telemetry *TelemetryConfig
// 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 (sessions live indefinitely).
// This option is only used when the SDK spawns the CLI process; it is ignored
// when connecting to an external server via CLIUrl.
SessionIdleTimeoutSeconds int
}
ClientOptions configures the CopilotClient
type CommandCompletedData ¶ added in v0.2.2
type CommandCompletedData struct {
// Request ID of the resolved command request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
}
Queued command completion notification signaling UI dismissal
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 struct {
// Raw argument string after the command name
Args string `json:"args"`
// The full command text (e.g., /deploy production)
Command string `json:"command"`
// Command name without leading /
CommandName string `json:"commandName"`
// Unique identifier; used to respond via session.commands.handlePendingCommand()
RequestID string `json:"requestId"`
}
Registered command dispatch request routed to the owning client
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 struct {
// The slash command text to be executed (e.g., /help, /clear)
Command string `json:"command"`
// Unique identifier for this request; used to respond via session.respondToQueuedCommand()
RequestID string `json:"requestId"`
}
Queued slash command dispatch request for client execution
type CommandsChangedCommand ¶ added in v0.3.0
type CommandsChangedData ¶ added in v0.2.2
type CommandsChangedData struct {
// Current list of registered SDK commands
Commands []CommandsChangedCommand `json:"commands"`
}
SDK command registration change notification
type CompactionCompleteCompactionTokensUsed ¶ added in v0.3.0
type CompactionCompleteCompactionTokensUsed struct {
// Cached input tokens reused in the compaction LLM call
CacheReadTokens *float64 `json:"cacheReadTokens,omitempty"`
// Tokens written to prompt cache in the compaction LLM call
CacheWriteTokens *float64 `json:"cacheWriteTokens,omitempty"`
// Per-request cost and usage data from the CAPI copilot_usage response field
CopilotUsage *CompactionCompleteCompactionTokensUsedCopilotUsage `json:"copilotUsage,omitempty"`
// Duration of the compaction LLM call in milliseconds
Duration *float64 `json:"duration,omitempty"`
// Input tokens consumed by the compaction LLM call
InputTokens *float64 `json:"inputTokens,omitempty"`
// Model identifier used for the compaction LLM call
Model *string `json:"model,omitempty"`
// Output tokens produced by the compaction LLM call
OutputTokens *float64 `json:"outputTokens,omitempty"`
}
Token usage breakdown for the compaction LLM call (aligned with assistant.usage format)
type CompactionCompleteCompactionTokensUsedCopilotUsage ¶ added in v0.3.0
type CompactionCompleteCompactionTokensUsedCopilotUsage struct {
// Itemized token usage breakdown
TokenDetails []CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail `json:"tokenDetails"`
// Total cost in nano-AIU (AI Units) for this request
TotalNanoAiu float64 `json:"totalNanoAiu"`
}
Per-request cost and usage data from the CAPI copilot_usage response field
type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail ¶ added in v0.3.0
type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail struct {
// Number of tokens in this billing batch
BatchSize float64 `json:"batchSize"`
// Cost per batch of tokens
CostPerBatch float64 `json:"costPerBatch"`
// Total token count for this entry
TokenCount float64 `json:"tokenCount"`
// Token category (e.g., "input", "output")
TokenType string `json:"tokenType"`
}
Token usage detail for a single billing category
type ConnectionState ¶
type ConnectionState string
ConnectionState represents the client connection state
const ( StateDisconnected ConnectionState = "disconnected" StateConnecting ConnectionState = "connecting" StateConnected ConnectionState = "connected" StateError ConnectionState = "error" )
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 for all tools)
Tools []string `json:"tools,omitempty"`
// Prompt is the prompt content for the agent
Prompt string `json:"prompt"`
// MCPServers are MCP servers specific to this agent
MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"`
// Infer indicates whether the agent should be available for model inference
Infer *bool `json:"infer,omitempty"`
// Skills is the list of skill names to preload into this agent's context at startup (opt-in; omit for none)
Skills []string `json:"skills,omitempty"`
}
CustomAgentConfig configures a custom agent
type CustomAgentsUpdatedAgent ¶ added in v0.3.0
type CustomAgentsUpdatedAgent struct {
// Description of what the agent does
Description string `json:"description"`
// Human-readable display name
DisplayName string `json:"displayName"`
// Unique identifier for the agent
ID string `json:"id"`
// Model override for this agent, if set
Model *string `json:"model,omitempty"`
// Internal name of the agent
Name string `json:"name"`
// Source location: user, project, inherited, remote, or plugin
Source string `json:"source"`
// List of tool names available to this agent
Tools []string `json:"tools"`
// Whether the agent can be selected by the user
UserInvocable bool `json:"userInvocable"`
}
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 ElicitationCompletedAction ¶ added in v0.3.0
type ElicitationCompletedAction string
The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed)
const ( ElicitationCompletedActionAccept ElicitationCompletedAction = "accept" ElicitationCompletedActionDecline ElicitationCompletedAction = "decline" ElicitationCompletedActionCancel ElicitationCompletedAction = "cancel" )
type ElicitationCompletedData ¶ added in v0.2.2
type ElicitationCompletedData struct {
// The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed)
Action *ElicitationCompletedAction `json:"action,omitempty"`
// The submitted form data when action is 'accept'; keys match the requested schema fields
Content map[string]any `json:"content,omitempty"`
// Request ID of the resolved elicitation request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
}
Elicitation request completion with the user's response
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 map[string]any
// Mode is "form" for structured input, "url" for browser redirect.
Mode string
// ElicitationSource is the source that initiated the request (e.g. MCP server name).
ElicitationSource string
// URL to open in the user's browser (url mode only).
URL string
}
ElicitationContext describes an elicitation request from the server, combining the request data with session context. Mirrors the single-argument pattern of CommandContext.
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 struct {
// The source that initiated the request (MCP server name, or absent for agent-initiated)
ElicitationSource *string `json:"elicitationSource,omitempty"`
// Message describing what information is needed from the user
Message string `json:"message"`
// Elicitation mode; "form" for structured input, "url" for browser-based. Defaults to "form" when absent.
Mode *ElicitationRequestedMode `json:"mode,omitempty"`
// JSON Schema describing the form fields to present to the user (form mode only)
RequestedSchema *ElicitationRequestedSchema `json:"requestedSchema,omitempty"`
// Unique identifier for this elicitation request; used to respond via session.respondToElicitation()
RequestID string `json:"requestId"`
// Tool call ID from the LLM completion; used to correlate with CompletionChunk.toolCall.id for remote UIs
ToolCallID *string `json:"toolCallId,omitempty"`
// URL to open in the user's browser (url mode only)
URL *string `json:"url,omitempty"`
}
Elicitation request; may be form-based (structured input) or URL-based (browser redirect)
type ElicitationRequestedMode ¶ added in v0.3.0
type ElicitationRequestedMode string
Elicitation mode; "form" for structured input, "url" for browser-based. Defaults to "form" when absent.
const ( ElicitationRequestedModeForm ElicitationRequestedMode = "form" ElicitationRequestedModeURL ElicitationRequestedMode = "url" )
type ElicitationRequestedSchema ¶ added in v0.3.0
type ElicitationRequestedSchema struct {
// Form field definitions, keyed by field name
Properties map[string]any `json:"properties"`
// List of required field names
Required []string `json:"required,omitempty"`
// Schema type indicator (always 'object')
Type string `json:"type"`
}
JSON Schema describing the form fields to present to the user (form mode only)
type ElicitationResult ¶ added in v0.2.1
type ElicitationResult struct {
// Action is the user response: "accept" (submitted), "decline" (rejected), or "cancel" (dismissed).
Action string `json:"action"`
// Content holds form values submitted by the user (present when Action is "accept").
Content map[string]any `json:"content,omitempty"`
}
ElicitationResult is the user's response to an elicitation dialog.
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 {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Error string `json:"error"`
ErrorContext string `json:"errorContext"` // "model_call", "tool_execution", "system", "user_input"
Recoverable bool `json:"recoverable"`
}
ErrorOccurredHookInput is the input for an error-occurred hook
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 ExitPlanModeCompletedData ¶ added in v0.2.2
type ExitPlanModeCompletedData struct {
// Whether the plan was approved by the user
Approved *bool `json:"approved,omitempty"`
// Whether edits should be auto-approved without confirmation
AutoApproveEdits *bool `json:"autoApproveEdits,omitempty"`
// Free-form feedback from the user if they requested changes to the plan
Feedback *string `json:"feedback,omitempty"`
// Request ID of the resolved exit plan mode request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
// Which action the user selected (e.g. 'autopilot', 'interactive', 'exit_only')
SelectedAction *string `json:"selectedAction,omitempty"`
}
Plan mode exit completion with the user's approval decision and optional feedback
type ExitPlanModeRequestedData ¶ added in v0.2.2
type ExitPlanModeRequestedData struct {
// Available actions the user can take (e.g., approve, edit, reject)
Actions []string `json:"actions"`
// Full content of the plan file
PlanContent string `json:"planContent"`
// The recommended action for the user to take
RecommendedAction string `json:"recommendedAction"`
// Unique identifier for this request; used to respond via session.respondToExitPlanMode()
RequestID string `json:"requestId"`
// Summary of the plan that was created
Summary string `json:"summary"`
}
Plan approval request with plan content and available user actions
type ExtensionsLoadedExtension ¶ added in v0.3.0
type ExtensionsLoadedExtension struct {
// Source-qualified extension ID (e.g., 'project:my-ext', 'user:auth-helper')
ID string `json:"id"`
// Extension name (directory name)
Name string `json:"name"`
// Discovery source
Source ExtensionsLoadedExtensionSource `json:"source"`
// Current status: running, disabled, failed, or starting
Status ExtensionsLoadedExtensionStatus `json:"status"`
}
type ExtensionsLoadedExtensionSource ¶ added in v0.3.0
type ExtensionsLoadedExtensionSource string
Discovery source
const ( ExtensionsLoadedExtensionSourceProject ExtensionsLoadedExtensionSource = "project" ExtensionsLoadedExtensionSourceUser ExtensionsLoadedExtensionSource = "user" )
type ExtensionsLoadedExtensionStatus ¶ added in v0.3.0
type ExtensionsLoadedExtensionStatus string
Current status: running, disabled, failed, or starting
const ( ExtensionsLoadedExtensionStatusRunning ExtensionsLoadedExtensionStatus = "running" ExtensionsLoadedExtensionStatusDisabled ExtensionsLoadedExtensionStatus = "disabled" ExtensionsLoadedExtensionStatusFailed ExtensionsLoadedExtensionStatus = "failed" ExtensionsLoadedExtensionStatusStarting ExtensionsLoadedExtensionStatus = "starting" )
type ExternalToolCompletedData ¶ added in v0.2.2
type ExternalToolCompletedData struct {
// Request ID of the resolved external tool request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
}
External tool completion notification signaling UI dismissal
type ExternalToolRequestedData ¶ added in v0.2.2
type ExternalToolRequestedData struct {
// Arguments to pass to the external tool
Arguments any `json:"arguments,omitempty"`
// Unique identifier for this request; used to respond via session.respondToExternalTool()
RequestID string `json:"requestId"`
// Session ID that this external tool request belongs to
SessionID string `json:"sessionId"`
// Tool call ID assigned to this external tool invocation
ToolCallID string `json:"toolCallId"`
// Name of the external tool to invoke
ToolName string `json:"toolName"`
// W3C Trace Context traceparent header for the execute_tool span
Traceparent *string `json:"traceparent,omitempty"`
// W3C Trace Context tracestate header for the execute_tool span
Tracestate *string `json:"tracestate,omitempty"`
}
External tool invocation request for client-side tool execution
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 struct {
// Git branch name, if applicable
Branch *string `json:"branch,omitempty"`
// Repository name
Name string `json:"name"`
// Repository owner (user or organization)
Owner string `json:"owner"`
}
Repository context for the handed-off session
type HandoffSourceType ¶ added in v0.3.0
type HandoffSourceType string
Origin type of the session being handed off
const ( HandoffSourceTypeRemote HandoffSourceType = "remote" HandoffSourceTypeLocal HandoffSourceType = "local" )
type HookEndData ¶ added in v0.2.2
type HookEndData struct {
// Error details when the hook failed
Error *HookEndError `json:"error,omitempty"`
// Identifier matching the corresponding hook.start event
HookInvocationID string `json:"hookInvocationId"`
// Type of hook that was invoked (e.g., "preToolUse", "postToolUse", "sessionStart")
HookType string `json:"hookType"`
// Output data produced by the hook
Output any `json:"output,omitempty"`
// Whether the hook completed successfully
Success bool `json:"success"`
}
Hook invocation completion details including output, success status, and error information
type HookEndError ¶ added in v0.3.0
type HookEndError struct {
// Human-readable error message
Message string `json:"message"`
// Error stack trace, when available
Stack *string `json:"stack,omitempty"`
}
Error details when the hook failed
type HookInvocation ¶ added in v0.1.20
type HookInvocation struct {
SessionID string
}
HookInvocation provides context about a hook invocation
type HookStartData ¶ added in v0.2.2
type HookStartData struct {
// Unique identifier for this hook invocation
HookInvocationID string `json:"hookInvocationId"`
// Type of hook being invoked (e.g., "preToolUse", "postToolUse", "sessionStart")
HookType string `json:"hookType"`
// Input data passed to the hook
Input any `json:"input,omitempty"`
}
Hook invocation start details including type and input data
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 InputOptions ¶ added in v0.2.1
type InputOptions struct {
// Title label for the input field.
Title string
// Description text shown below the field.
Description string
// MinLength is the minimum character length.
MinLength *int
// MaxLength is the maximum character length.
MaxLength *int
// Format is a semantic format hint: "email", "uri", "date", or "date-time".
Format string
// Default is the pre-populated value.
Default string
}
InputOptions configures a text input field for the Input convenience method.
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 MCPHTTPServerConfig ¶ added in v0.3.0
type MCPHTTPServerConfig struct {
Tools []string `json:"tools"`
Timeout int `json:"timeout,omitempty"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
MCPHTTPServerConfig configures a remote MCP server (HTTP or SSE).
func (MCPHTTPServerConfig) MarshalJSON ¶ added in v0.3.0
func (c MCPHTTPServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
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 MCPStdioServerConfig ¶ added in v0.3.0
type MCPStdioServerConfig struct {
Tools []string `json:"tools"`
Timeout int `json:"timeout,omitempty"`
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env,omitempty"`
Cwd string `json:"cwd,omitempty"`
}
MCPStdioServerConfig configures a local/stdio MCP server.
func (MCPStdioServerConfig) MarshalJSON ¶ added in v0.3.0
func (c MCPStdioServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
type McpOauthCompletedData ¶ added in v0.2.2
type McpOauthCompletedData struct {
// Request ID of the resolved OAuth request
RequestID string `json:"requestId"`
}
MCP OAuth request completion notification
type McpOauthRequiredData ¶ added in v0.2.2
type McpOauthRequiredData struct {
// Unique identifier for this OAuth request; used to respond via session.respondToMcpOAuth()
RequestID string `json:"requestId"`
// Display name of the MCP server that requires OAuth
ServerName string `json:"serverName"`
// URL of the MCP server that requires OAuth
ServerURL string `json:"serverUrl"`
// Static OAuth client configuration, if the server specifies one
StaticClientConfig *McpOauthRequiredStaticClientConfig `json:"staticClientConfig,omitempty"`
}
OAuth authentication request for an MCP server
type McpOauthRequiredStaticClientConfig ¶ added in v0.3.0
type McpOauthRequiredStaticClientConfig struct {
// OAuth client ID for the server
ClientID string `json:"clientId"`
// Whether this is a public OAuth client
PublicClient *bool `json:"publicClient,omitempty"`
}
Static OAuth client configuration, if the server specifies one
type McpServerStatusChangedStatus ¶ added in v0.3.0
type McpServerStatusChangedStatus string
New connection status: connected, failed, needs-auth, pending, disabled, or not_configured
const ( McpServerStatusChangedStatusConnected McpServerStatusChangedStatus = "connected" McpServerStatusChangedStatusFailed McpServerStatusChangedStatus = "failed" McpServerStatusChangedStatusNeedsAuth McpServerStatusChangedStatus = "needs-auth" McpServerStatusChangedStatusPending McpServerStatusChangedStatus = "pending" McpServerStatusChangedStatusDisabled McpServerStatusChangedStatus = "disabled" McpServerStatusChangedStatusNotConfigured McpServerStatusChangedStatus = "not_configured" )
type McpServersLoadedServer ¶ added in v0.3.0
type McpServersLoadedServer struct {
// Error message if the server failed to connect
Error *string `json:"error,omitempty"`
// Server name (config key)
Name string `json:"name"`
// Configuration source: user, workspace, plugin, or builtin
Source *string `json:"source,omitempty"`
// Connection status: connected, failed, needs-auth, pending, disabled, or not_configured
Status McpServersLoadedServerStatus `json:"status"`
}
type McpServersLoadedServerStatus ¶ added in v0.3.0
type McpServersLoadedServerStatus string
Connection status: connected, failed, needs-auth, pending, disabled, or not_configured
const ( McpServersLoadedServerStatusConnected McpServersLoadedServerStatus = "connected" McpServersLoadedServerStatusFailed McpServersLoadedServerStatus = "failed" McpServersLoadedServerStatusNeedsAuth McpServersLoadedServerStatus = "needs-auth" McpServersLoadedServerStatusPending McpServersLoadedServerStatus = "pending" McpServersLoadedServerStatusDisabled McpServersLoadedServerStatus = "disabled" McpServersLoadedServerStatusNotConfigured McpServersLoadedServerStatus = "not_configured" )
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
// RequestHeaders are custom per-turn HTTP headers for outbound model requests.
RequestHeaders map[string]string
}
MessageOptions configures a message to send
type ModelBilling ¶ added in v0.1.15
type ModelBilling struct {
Multiplier float64 `json:"multiplier"`
}
ModelBilling contains model billing information
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"`
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 struct {
}
Empty payload; the event signals that the pending message queue has changed
type PermissionCompletedData ¶ added in v0.2.2
type PermissionCompletedData struct {
// Request ID of the resolved permission request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
// The result of the permission request
Result PermissionCompletedResult `json:"result"`
// Optional tool call ID associated with this permission prompt; clients may use it to correlate UI created from tool-scoped prompts
ToolCallID *string `json:"toolCallId,omitempty"`
}
Permission request completion notification signaling UI dismissal
type PermissionCompletedKind ¶ added in v0.3.0
type PermissionCompletedKind string
The outcome of the permission request
const ( PermissionCompletedKindApproved PermissionCompletedKind = "approved" PermissionCompletedKindApprovedForSession PermissionCompletedKind = "approved-for-session" PermissionCompletedKindApprovedForLocation PermissionCompletedKind = "approved-for-location" PermissionCompletedKindDeniedByRules PermissionCompletedKind = "denied-by-rules" PermissionCompletedKindDeniedNoApprovalRuleAndCouldNotRequestFromUser PermissionCompletedKind = "denied-no-approval-rule-and-could-not-request-from-user" PermissionCompletedKindDeniedInteractivelyByUser PermissionCompletedKind = "denied-interactively-by-user" PermissionCompletedKindDeniedByContentExclusionPolicy PermissionCompletedKind = "denied-by-content-exclusion-policy" PermissionCompletedKindDeniedByPermissionRequestHook PermissionCompletedKind = "denied-by-permission-request-hook" )
type PermissionCompletedResult ¶ added in v0.3.0
type PermissionCompletedResult struct {
// The outcome of the permission request
Kind PermissionCompletedKind `json:"kind"`
}
The result of the permission request
type PermissionHandlerFunc ¶ added in v0.1.28
type PermissionHandlerFunc func(request PermissionRequest, invocation PermissionInvocation) (PermissionRequestResult, error)
PermissionHandlerFunc executes a permission request The handler should return a PermissionRequestResult. Returning an error denies the permission.
type PermissionInvocation ¶
type PermissionInvocation struct {
SessionID string
}
PermissionInvocation provides context about a permission request
type PermissionPromptRequest ¶ added in v0.3.0
type PermissionPromptRequest struct {
// Kind discriminator
Kind PermissionPromptRequestKind `json:"kind"`
// Underlying permission kind that needs path approval
AccessKind *PermissionPromptRequestPathAccessKind `json:"accessKind,omitempty"`
// Whether this is a store or vote memory operation
Action *PermissionPromptRequestMemoryAction `json:"action,omitempty"`
// Arguments to pass to the MCP tool
Args *any `json:"args,omitempty"`
// Whether the UI can offer session-wide approval for this command pattern
CanOfferSessionApproval *bool `json:"canOfferSessionApproval,omitempty"`
// Source references for the stored fact (store only)
Citations *string `json:"citations,omitempty"`
// Command identifiers covered by this approval prompt
CommandIdentifiers []string `json:"commandIdentifiers,omitempty"`
// Unified diff showing the proposed changes
Diff *string `json:"diff,omitempty"`
// Vote direction (vote only)
Direction *PermissionPromptRequestMemoryDirection `json:"direction,omitempty"`
// The fact being stored or voted on
Fact *string `json:"fact,omitempty"`
// Path of the file being written to
FileName *string `json:"fileName,omitempty"`
// The complete shell command text to be executed
FullCommandText *string `json:"fullCommandText,omitempty"`
// Optional message from the hook explaining why confirmation is needed
HookMessage *string `json:"hookMessage,omitempty"`
// Human-readable description of what the command intends to do
Intention *string `json:"intention,omitempty"`
// Complete new file contents for newly created files
NewFileContents *string `json:"newFileContents,omitempty"`
// Path of the file or directory being read
Path *string `json:"path,omitempty"`
// File paths that require explicit approval
Paths []string `json:"paths,omitempty"`
// Reason for the vote (vote only)
Reason *string `json:"reason,omitempty"`
// Name of the MCP server providing the tool
ServerName *string `json:"serverName,omitempty"`
// Topic or subject of the memory (store only)
Subject *string `json:"subject,omitempty"`
// Arguments of the tool call being gated
ToolArgs any `json:"toolArgs,omitempty"`
// Tool call ID that triggered this permission request
ToolCallID *string `json:"toolCallId,omitempty"`
// Description of what the custom tool does
ToolDescription *string `json:"toolDescription,omitempty"`
// Internal name of the MCP tool
ToolName *string `json:"toolName,omitempty"`
// Human-readable title of the MCP tool
ToolTitle *string `json:"toolTitle,omitempty"`
// URL to be fetched
URL *string `json:"url,omitempty"`
// Optional warning message about risks of running this command
Warning *string `json:"warning,omitempty"`
}
Derived user-facing permission prompt details for UI consumers
type PermissionPromptRequestKind ¶ added in v0.3.0
type PermissionPromptRequestKind string
Kind discriminator for PermissionPromptRequest.
const ( PermissionPromptRequestKindCommands PermissionPromptRequestKind = "commands" PermissionPromptRequestKindWrite PermissionPromptRequestKind = "write" PermissionPromptRequestKindRead PermissionPromptRequestKind = "read" PermissionPromptRequestKindMcp PermissionPromptRequestKind = "mcp" PermissionPromptRequestKindURL PermissionPromptRequestKind = "url" PermissionPromptRequestKindMemory PermissionPromptRequestKind = "memory" PermissionPromptRequestKindCustomTool PermissionPromptRequestKind = "custom-tool" PermissionPromptRequestKindPath PermissionPromptRequestKind = "path" PermissionPromptRequestKindHook PermissionPromptRequestKind = "hook" )
type PermissionPromptRequestMemoryAction ¶ added in v0.3.0
type PermissionPromptRequestMemoryAction string
Whether this is a store or vote memory operation
const ( PermissionPromptRequestMemoryActionStore PermissionPromptRequestMemoryAction = "store" PermissionPromptRequestMemoryActionVote PermissionPromptRequestMemoryAction = "vote" )
type PermissionPromptRequestMemoryDirection ¶ added in v0.3.0
type PermissionPromptRequestMemoryDirection string
Vote direction (vote only)
const ( PermissionPromptRequestMemoryDirectionUpvote PermissionPromptRequestMemoryDirection = "upvote" PermissionPromptRequestMemoryDirectionDownvote PermissionPromptRequestMemoryDirection = "downvote" )
type PermissionPromptRequestPathAccessKind ¶ added in v0.3.0
type PermissionPromptRequestPathAccessKind string
Underlying permission kind that needs path approval
const ( PermissionPromptRequestPathAccessKindRead PermissionPromptRequestPathAccessKind = "read" PermissionPromptRequestPathAccessKindShell PermissionPromptRequestPathAccessKind = "shell" PermissionPromptRequestPathAccessKindWrite PermissionPromptRequestPathAccessKind = "write" )
type PermissionRequest ¶
type PermissionRequest struct {
// Kind discriminator
Kind PermissionRequestKind `json:"kind"`
// Whether this is a store or vote memory operation
Action *PermissionRequestMemoryAction `json:"action,omitempty"`
// Arguments to pass to the MCP tool
Args any `json:"args,omitempty"`
// Whether the UI can offer session-wide approval for this command pattern
CanOfferSessionApproval *bool `json:"canOfferSessionApproval,omitempty"`
// Source references for the stored fact (store only)
Citations *string `json:"citations,omitempty"`
// Parsed command identifiers found in the command text
Commands []PermissionRequestShellCommand `json:"commands,omitempty"`
// Unified diff showing the proposed changes
Diff *string `json:"diff,omitempty"`
// Vote direction (vote only)
Direction *PermissionRequestMemoryDirection `json:"direction,omitempty"`
// The fact being stored or voted on
Fact *string `json:"fact,omitempty"`
// Path of the file being written to
FileName *string `json:"fileName,omitempty"`
// The complete shell command text to be executed
FullCommandText *string `json:"fullCommandText,omitempty"`
// Whether the command includes a file write redirection (e.g., > or >>)
HasWriteFileRedirection *bool `json:"hasWriteFileRedirection,omitempty"`
// Optional message from the hook explaining why confirmation is needed
HookMessage *string `json:"hookMessage,omitempty"`
// Human-readable description of what the command intends to do
Intention *string `json:"intention,omitempty"`
// Complete new file contents for newly created files
NewFileContents *string `json:"newFileContents,omitempty"`
// Path of the file or directory being read
Path *string `json:"path,omitempty"`
// File paths that may be read or written by the command
PossiblePaths []string `json:"possiblePaths,omitempty"`
// URLs that may be accessed by the command
PossibleUrls []PermissionRequestShellPossibleURL `json:"possibleUrls,omitempty"`
// Whether this MCP tool is read-only (no side effects)
ReadOnly *bool `json:"readOnly,omitempty"`
// Reason for the vote (vote only)
Reason *string `json:"reason,omitempty"`
// Name of the MCP server providing the tool
ServerName *string `json:"serverName,omitempty"`
// Topic or subject of the memory (store only)
Subject *string `json:"subject,omitempty"`
// Arguments of the tool call being gated
ToolArgs any `json:"toolArgs,omitempty"`
// Tool call ID that triggered this permission request
ToolCallID *string `json:"toolCallId,omitempty"`
// Description of what the custom tool does
ToolDescription *string `json:"toolDescription,omitempty"`
// Internal name of the MCP tool
ToolName *string `json:"toolName,omitempty"`
// Human-readable title of the MCP tool
ToolTitle *string `json:"toolTitle,omitempty"`
// URL to be fetched
URL *string `json:"url,omitempty"`
// Optional warning message about risks of running this command
Warning *string `json:"warning,omitempty"`
}
Details of the permission being requested
type PermissionRequestCommand ¶ added in v0.2.0
type PermissionRequestCommand = PermissionRequestShellCommand
Type aliases for convenience.
type PermissionRequestKind ¶ added in v0.1.31
type PermissionRequestKind string
Kind discriminator for PermissionRequest.
const ( PermissionRequestKindShell PermissionRequestKind = "shell" PermissionRequestKindWrite PermissionRequestKind = "write" PermissionRequestKindRead PermissionRequestKind = "read" PermissionRequestKindMcp PermissionRequestKind = "mcp" PermissionRequestKindURL PermissionRequestKind = "url" PermissionRequestKindMemory PermissionRequestKind = "memory" PermissionRequestKindCustomTool PermissionRequestKind = "custom-tool" PermissionRequestKindHook PermissionRequestKind = "hook" )
type PermissionRequestMemoryAction ¶ added in v0.3.0
type PermissionRequestMemoryAction string
Whether this is a store or vote memory operation
const ( PermissionRequestMemoryActionStore PermissionRequestMemoryAction = "store" PermissionRequestMemoryActionVote PermissionRequestMemoryAction = "vote" )
type PermissionRequestMemoryDirection ¶ added in v0.3.0
type PermissionRequestMemoryDirection string
Vote direction (vote only)
const ( PermissionRequestMemoryDirectionUpvote PermissionRequestMemoryDirection = "upvote" PermissionRequestMemoryDirectionDownvote PermissionRequestMemoryDirection = "downvote" )
type PermissionRequestResult ¶
type PermissionRequestResult struct {
Kind PermissionRequestResultKind `json:"kind"`
Rules []any `json:"rules,omitempty"`
}
PermissionRequestResult represents the result of a permission request
type PermissionRequestResultKind ¶ added in v0.1.31
type PermissionRequestResultKind string
PermissionRequestResultKind represents the kind of a permission request result.
type PermissionRequestShellCommand ¶ added in v0.3.0
type PermissionRequestShellPossibleURL ¶ added in v0.3.0
type PermissionRequestShellPossibleURL struct {
// URL that may be accessed by the command
URL string `json:"url"`
}
type PermissionRequestedData ¶ added in v0.2.2
type PermissionRequestedData struct {
// Details of the permission being requested
PermissionRequest PermissionRequest `json:"permissionRequest"`
// Derived user-facing permission prompt details for UI consumers
PromptRequest *PermissionPromptRequest `json:"promptRequest,omitempty"`
// Unique identifier for this permission request; used to respond via session.respondToPermission()
RequestID string `json:"requestId"`
// When true, this permission was already resolved by a permissionRequest hook and requires no client action
ResolvedByHook *bool `json:"resolvedByHook,omitempty"`
}
Permission request notification requiring client approval with request details
type PingResponse ¶
type PingResponse struct {
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
ProtocolVersion *int `json:"protocolVersion,omitempty"`
}
PingResponse is the response from a ping request
type PlanChangedOperation ¶ added in v0.3.0
type PlanChangedOperation string
The type of operation performed on the plan file
const ( PlanChangedOperationCreate PlanChangedOperation = "create" PlanChangedOperationUpdate PlanChangedOperation = "update" PlanChangedOperationDelete PlanChangedOperation = "delete" )
type PossibleURL ¶ added in v0.1.31
type PossibleURL = PermissionRequestShellPossibleURL
Type aliases for convenience.
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 {
Timestamp int64 `json:"timestamp"`
Cwd 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
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 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 {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
}
PreToolUseHookInput is the input for a pre-tool-use hook
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"`
}
type RawSessionEventData ¶ added in v0.2.2
type RawSessionEventData struct {
Raw json.RawMessage
}
RawSessionEventData holds unparsed JSON data for unrecognized event types.
func (RawSessionEventData) MarshalJSON ¶ added in v0.2.2
func (r RawSessionEventData) MarshalJSON() ([]byte, error)
MarshalJSON returns the original raw JSON so round-tripping preserves the payload.
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
Tools []Tool
// SystemMessage configures system message customization
SystemMessage *SystemMessageConfig
// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
// Takes precedence over ExcludedTools.
AvailableTools []string
// ExcludedTools is a list of tool names to disable. All other tools remain available.
// Ignored if AvailableTools is specified.
ExcludedTools []string
// Provider configures a custom model provider
Provider *ProviderConfig
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// ReasoningEffort level for models that support it.
// Valid values: "low", "medium", "high", "xhigh"
ReasoningEffort string
// OnPermissionRequest is a handler for permission requests from the server.
// If nil, all permission requests are denied by default.
// Provide a handler to approve operations (file writes, shell commands, URL fetches, etc.).
OnPermissionRequest PermissionHandlerFunc
// OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool)
OnUserInputRequest UserInputHandler
// Hooks configures hook handlers for session lifecycle events
Hooks *SessionHooks
// WorkingDirectory is the working directory for the session.
// Tool operations will be relative to this directory.
WorkingDirectory string
// ConfigDir overrides the default configuration directory location.
ConfigDir string
// EnableConfigDiscovery, when true, automatically discovers MCP server configurations
// (e.g. .mcp.json, .vscode/mcp.json) and skill directories from the working directory
// and merges them with any explicitly provided MCPServers and SkillDirectories, with
// explicit values taking precedence on name collision.
// Custom instruction files (.github/copilot-instructions.md, AGENTS.md, etc.) are
// always loaded from the working directory regardless of this setting.
EnableConfigDiscovery bool
// Streaming enables streaming of assistant message and reasoning chunks.
// When true, assistant.message_delta and assistant.reasoning_delta events
// with deltaContent are sent as the response is generated.
Streaming bool
// 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
// 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
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
InfiniteSessions *InfiniteSessionConfig
// 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:"-"`
// DisableResume, when true, skips emitting the session.resume event.
// Useful for reconnecting to a session without triggering resume-related side effects.
DisableResume bool
// OnEvent is an optional event handler registered before the session.resume RPC
// is issued, ensuring early events are delivered. See SessionConfig.OnEvent.
OnEvent SessionEventHandler
// CreateSessionFsHandler supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFs is configured.
CreateSessionFsHandler func(session *Session) 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
}
ResumeSessionConfig configures options when resuming a session
type SamplingCompletedData ¶ added in v0.2.2
type SamplingCompletedData struct {
// Request ID of the resolved sampling request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
}
Sampling request completion notification signaling UI dismissal
type SamplingRequestedData ¶ added in v0.2.2
type SamplingRequestedData struct {
// The JSON-RPC request ID from the MCP protocol
McpRequestID any `json:"mcpRequestId"`
// Unique identifier for this sampling request; used to respond via session.respondToSampling()
RequestID string `json:"requestId"`
// Name of the MCP server that initiated the sampling request
ServerName string `json:"serverName"`
}
Sampling request from an MCP server; contains the server name and a requestId for correlation
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 prompt section.
type SectionOverrideAction ¶ added in v0.2.0
type SectionOverrideAction string
SectionOverrideAction represents the action to perform on a system prompt 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 prompt 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) Destroy
deprecated
Deprecated: Use Session.Disconnect instead. Destroy will be removed in a future release.
Destroy closes this session and releases all in-memory resources. Session data on disk is preserved for later resumption.
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) GetMessages ¶
func (s *Session) GetMessages(ctx context.Context) ([]SessionEvent, error)
GetMessages retrieves all events and messages 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.GetMessages(context.Background())
if err != nil {
log.Printf("Failed to get messages: %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) 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{
{Type: "file", 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) 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 SessionBackgroundTasksChangedData ¶ added in v0.2.2
type SessionBackgroundTasksChangedData struct {
}
SessionBackgroundTasksChangedData holds the payload for session.background_tasks_changed events.
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 struct {
// Checkpoint snapshot number created for recovery
CheckpointNumber *float64 `json:"checkpointNumber,omitempty"`
// File path where the checkpoint was stored
CheckpointPath *string `json:"checkpointPath,omitempty"`
// Token usage breakdown for the compaction LLM call (aligned with assistant.usage format)
CompactionTokensUsed *CompactionCompleteCompactionTokensUsed `json:"compactionTokensUsed,omitempty"`
// Token count from non-system messages (user, assistant, tool) after compaction
ConversationTokens *float64 `json:"conversationTokens,omitempty"`
// Error message if compaction failed
Error *string `json:"error,omitempty"`
// Number of messages removed during compaction
MessagesRemoved *float64 `json:"messagesRemoved,omitempty"`
// Total tokens in conversation after compaction
PostCompactionTokens *float64 `json:"postCompactionTokens,omitempty"`
// Number of messages before compaction
PreCompactionMessagesLength *float64 `json:"preCompactionMessagesLength,omitempty"`
// Total tokens in conversation before compaction
PreCompactionTokens *float64 `json:"preCompactionTokens,omitempty"`
// GitHub request tracing ID (x-github-request-id header) for the compaction LLM call
RequestID *string `json:"requestId,omitempty"`
// Whether compaction completed successfully
Success bool `json:"success"`
// LLM-generated summary of the compacted conversation history
SummaryContent *string `json:"summaryContent,omitempty"`
// Token count from system message(s) after compaction
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Number of tokens removed during compaction
TokensRemoved *float64 `json:"tokensRemoved,omitempty"`
// Token count from tool definitions after compaction
ToolDefinitionsTokens *float64 `json:"toolDefinitionsTokens,omitempty"`
}
Conversation compaction results including success status, metrics, and optional error details
type SessionCompactionStartData ¶ added in v0.2.2
type SessionCompactionStartData struct {
// Token count from non-system messages (user, assistant, tool) at compaction start
ConversationTokens *float64 `json:"conversationTokens,omitempty"`
// Token count from system message(s) at compaction start
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Token count from tool definitions at compaction start
ToolDefinitionsTokens *float64 `json:"toolDefinitionsTokens,omitempty"`
}
Context window breakdown at the start of LLM-powered conversation compaction
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
// ConfigDir overrides the default configuration directory location.
// When specified, the session will use this directory for storing config and state.
ConfigDir string
// EnableConfigDiscovery, when true, automatically discovers MCP server configurations
// (e.g. .mcp.json, .vscode/mcp.json) and skill directories from the working directory
// and merges them with any explicitly provided MCPServers and SkillDirectories, with
// explicit values taking precedence on name collision.
// Custom instruction files (.github/copilot-instructions.md, AGENTS.md, etc.) are
// always loaded from the working directory regardless of this setting.
EnableConfigDiscovery bool
// Tools exposes caller-implemented tools to the CLI
Tools []Tool
// SystemMessage configures system message customization
SystemMessage *SystemMessageConfig
// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
// Takes precedence over ExcludedTools.
AvailableTools []string
// ExcludedTools is a list of tool names to disable. All other tools remain available.
// Ignored if AvailableTools is specified.
ExcludedTools []string
// OnPermissionRequest is a handler for permission requests from the server.
// If nil, all permission requests are denied by default.
// Provide a handler to approve operations (file writes, shell commands, URL fetches, etc.).
OnPermissionRequest PermissionHandlerFunc
// OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool)
OnUserInputRequest UserInputHandler
// Hooks configures hook handlers for session lifecycle events
Hooks *SessionHooks
// WorkingDirectory is the working directory for the session.
// Tool operations will be relative to this directory.
WorkingDirectory string
// Streaming enables streaming of assistant message and reasoning chunks.
// When true, assistant.message_delta and assistant.reasoning_delta events
// with deltaContent are sent as the response is generated.
Streaming bool
// 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
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// CustomAgents configures custom agents for the session
CustomAgents []CustomAgentConfig
// DefaultAgent configures the default agent (the built-in agent that handles turns when no custom agent is selected).
// Use ExcludedTools to hide tools from the default agent while keeping them available to sub-agents.
DefaultAgent *DefaultAgentConfig
// Agent is the name of the custom agent to activate when the session starts.
// Must match the Name of one of the agents in CustomAgents.
Agent string
// SkillDirectories is a list of directories to load skills from
SkillDirectories []string
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
// When enabled (default), sessions automatically manage context limits and persist state.
InfiniteSessions *InfiniteSessionConfig
// OnEvent is an optional event handler that is registered on the session before
// the session.create RPC is issued. This guarantees that early events emitted
// by the CLI during session creation (e.g. session.start) are delivered to the
// handler. Equivalent to calling session.On(handler) immediately after creation,
// but executes earlier in the lifecycle so no events are missed.
OnEvent SessionEventHandler
// CreateSessionFsHandler supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFs is configured.
CreateSessionFsHandler func(session *Session) 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
// 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:"-"`
}
SessionConfig configures a new session
type SessionContext ¶ added in v0.1.24
type SessionContext struct {
// Cwd is the working directory where the session was created
Cwd string `json:"cwd"`
// GitRoot is the git repository root (if in a git repo)
GitRoot string `json:"gitRoot,omitempty"`
// Repository is the GitHub repository in "owner/repo" format
Repository string `json:"repository,omitempty"`
// Branch is the current git branch
Branch string `json:"branch,omitempty"`
}
SessionContext contains working directory context for a session
type SessionContextChangedData ¶ added in v0.2.2
type SessionContextChangedData struct {
// Base commit of current git branch at session start time
BaseCommit *string `json:"baseCommit,omitempty"`
// Current git branch name
Branch *string `json:"branch,omitempty"`
// Current working directory path
Cwd string `json:"cwd"`
// Root directory of the git repository, resolved via git rev-parse
GitRoot *string `json:"gitRoot,omitempty"`
// Head commit of current git branch at session start time
HeadCommit *string `json:"headCommit,omitempty"`
// Hosting platform type of the repository (github or ado)
HostType *WorkingDirectoryContextHostType `json:"hostType,omitempty"`
// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps)
Repository *string `json:"repository,omitempty"`
// Raw host string from the git remote URL (e.g. "github.com", "mycompany.ghe.com", "dev.azure.com")
RepositoryHost *string `json:"repositoryHost,omitempty"`
}
Working directory and git context at session start
type SessionCustomAgentsUpdatedData ¶ added in v0.2.2
type SessionCustomAgentsUpdatedData struct {
// Array of loaded custom agent metadata
Agents []CustomAgentsUpdatedAgent `json:"agents"`
// Fatal errors from agent loading
Errors []string `json:"errors"`
// Non-fatal warnings from agent loading
Warnings []string `json:"warnings"`
}
SessionCustomAgentsUpdatedData holds the payload for session.custom_agents_updated events.
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 {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Reason string `json:"reason"` // "complete", "error", "abort", "timeout", "user_exit"
FinalMessage string `json:"finalMessage,omitempty"`
Error string `json:"error,omitempty"`
}
SessionEndHookInput is the input for a session-end hook
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 struct {
// Category of error (e.g., "authentication", "authorization", "quota", "rate_limit", "context_limit", "query")
ErrorType string `json:"errorType"`
// Human-readable error message
Message string `json:"message"`
// GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs
ProviderCallID *string `json:"providerCallId,omitempty"`
// Error stack trace, when available
Stack *string `json:"stack,omitempty"`
// HTTP status code from the upstream request, if applicable
StatusCode *int64 `json:"statusCode,omitempty"`
// Optional URL associated with this error that the user can open in a browser
URL *string `json:"url,omitempty"`
}
Error details for timeline display including message and optional diagnostic information
type SessionEvent ¶
type SessionEvent struct {
// Unique event identifier (UUID v4), generated when the event is emitted.
ID string `json:"id"`
// ISO 8601 timestamp when the event was created.
Timestamp time.Time `json:"timestamp"`
// ID of the preceding event in the session. Null for the first event.
ParentID *string `json:"parentId"`
// When true, the event is transient and not persisted.
Ephemeral *bool `json:"ephemeral,omitempty"`
// The event type discriminator.
Type SessionEventType `json:"type"`
// Typed event payload. Use a type switch to access per-event fields.
Data SessionEventData `json:"-"`
}
SessionEvent represents a single session event with a typed data payload.
func UnmarshalSessionEvent ¶ added in v0.1.15
func UnmarshalSessionEvent(data []byte) (SessionEvent, error)
UnmarshalSessionEvent parses JSON bytes into a SessionEvent.
func (*SessionEvent) Marshal ¶ added in v0.1.15
func (r *SessionEvent) Marshal() ([]byte, error)
Marshal serializes the SessionEvent to JSON.
func (SessionEvent) MarshalJSON ¶ added in v0.2.2
func (e SessionEvent) MarshalJSON() ([]byte, error)
func (*SessionEvent) UnmarshalJSON ¶ added in v0.2.2
func (e *SessionEvent) UnmarshalJSON(data []byte) error
type SessionEventData ¶ added in v0.2.2
type SessionEventData interface {
// contains filtered or unexported methods
}
SessionEventData is the interface implemented by all per-event data types.
type SessionEventHandler ¶
type SessionEventHandler func(event SessionEvent)
SessionEventHandler is a callback for session events
type SessionEventType ¶ added in v0.1.15
type SessionEventType string
SessionEventType identifies the kind of session event.
const ( SessionEventTypeSessionStart SessionEventType = "session.start" SessionEventTypeSessionResume SessionEventType = "session.resume" SessionEventTypeSessionRemoteSteerableChanged SessionEventType = "session.remote_steerable_changed" SessionEventTypeSessionError SessionEventType = "session.error" SessionEventTypeSessionIdle SessionEventType = "session.idle" SessionEventTypeSessionTitleChanged SessionEventType = "session.title_changed" SessionEventTypeSessionInfo SessionEventType = "session.info" SessionEventTypeSessionWarning SessionEventType = "session.warning" SessionEventTypeSessionModelChange SessionEventType = "session.model_change" SessionEventTypeSessionModeChanged SessionEventType = "session.mode_changed" SessionEventTypeSessionPlanChanged SessionEventType = "session.plan_changed" SessionEventTypeSessionWorkspaceFileChanged SessionEventType = "session.workspace_file_changed" SessionEventTypeSessionHandoff SessionEventType = "session.handoff" SessionEventTypeSessionTruncation SessionEventType = "session.truncation" SessionEventTypeSessionSnapshotRewind SessionEventType = "session.snapshot_rewind" SessionEventTypeSessionShutdown SessionEventType = "session.shutdown" SessionEventTypeSessionContextChanged SessionEventType = "session.context_changed" SessionEventTypeSessionUsageInfo SessionEventType = "session.usage_info" SessionEventTypeSessionCompactionStart SessionEventType = "session.compaction_start" SessionEventTypeSessionCompactionComplete SessionEventType = "session.compaction_complete" SessionEventTypeSessionTaskComplete SessionEventType = "session.task_complete" SessionEventTypeUserMessage SessionEventType = "user.message" SessionEventTypePendingMessagesModified SessionEventType = "pending_messages.modified" SessionEventTypeAssistantTurnStart SessionEventType = "assistant.turn_start" SessionEventTypeAssistantIntent SessionEventType = "assistant.intent" SessionEventTypeAssistantReasoning SessionEventType = "assistant.reasoning" SessionEventTypeAssistantReasoningDelta SessionEventType = "assistant.reasoning_delta" SessionEventTypeAssistantStreamingDelta SessionEventType = "assistant.streaming_delta" SessionEventTypeAssistantMessage SessionEventType = "assistant.message" SessionEventTypeAssistantMessageDelta SessionEventType = "assistant.message_delta" SessionEventTypeAssistantTurnEnd SessionEventType = "assistant.turn_end" SessionEventTypeAssistantUsage SessionEventType = "assistant.usage" SessionEventTypeAbort SessionEventType = "abort" SessionEventTypeToolUserRequested SessionEventType = "tool.user_requested" SessionEventTypeToolExecutionStart SessionEventType = "tool.execution_start" SessionEventTypeToolExecutionPartialResult SessionEventType = "tool.execution_partial_result" SessionEventTypeToolExecutionProgress SessionEventType = "tool.execution_progress" SessionEventTypeToolExecutionComplete SessionEventType = "tool.execution_complete" SessionEventTypeSkillInvoked SessionEventType = "skill.invoked" SessionEventTypeSubagentStarted SessionEventType = "subagent.started" SessionEventTypeSubagentCompleted SessionEventType = "subagent.completed" SessionEventTypeSubagentFailed SessionEventType = "subagent.failed" SessionEventTypeSubagentSelected SessionEventType = "subagent.selected" SessionEventTypeSubagentDeselected SessionEventType = "subagent.deselected" SessionEventTypeHookStart SessionEventType = "hook.start" SessionEventTypeHookEnd SessionEventType = "hook.end" SessionEventTypeSystemMessage SessionEventType = "system.message" SessionEventTypeSystemNotification SessionEventType = "system.notification" SessionEventTypePermissionRequested SessionEventType = "permission.requested" SessionEventTypePermissionCompleted SessionEventType = "permission.completed" SessionEventTypeUserInputRequested SessionEventType = "user_input.requested" SessionEventTypeUserInputCompleted SessionEventType = "user_input.completed" SessionEventTypeElicitationRequested SessionEventType = "elicitation.requested" SessionEventTypeElicitationCompleted SessionEventType = "elicitation.completed" SessionEventTypeSamplingRequested SessionEventType = "sampling.requested" SessionEventTypeSamplingCompleted SessionEventType = "sampling.completed" SessionEventTypeMcpOauthRequired SessionEventType = "mcp.oauth_required" SessionEventTypeMcpOauthCompleted SessionEventType = "mcp.oauth_completed" SessionEventTypeExternalToolRequested SessionEventType = "external_tool.requested" SessionEventTypeExternalToolCompleted SessionEventType = "external_tool.completed" SessionEventTypeCommandQueued SessionEventType = "command.queued" SessionEventTypeCommandExecute SessionEventType = "command.execute" SessionEventTypeCommandCompleted SessionEventType = "command.completed" SessionEventTypeAutoModeSwitchRequested SessionEventType = "auto_mode_switch.requested" SessionEventTypeAutoModeSwitchCompleted SessionEventType = "auto_mode_switch.completed" SessionEventTypeCommandsChanged SessionEventType = "commands.changed" SessionEventTypeCapabilitiesChanged SessionEventType = "capabilities.changed" SessionEventTypeExitPlanModeRequested SessionEventType = "exit_plan_mode.requested" SessionEventTypeExitPlanModeCompleted SessionEventType = "exit_plan_mode.completed" SessionEventTypeSessionToolsUpdated SessionEventType = "session.tools_updated" SessionEventTypeSessionBackgroundTasksChanged SessionEventType = "session.background_tasks_changed" SessionEventTypeSessionSkillsLoaded SessionEventType = "session.skills_loaded" SessionEventTypeSessionCustomAgentsUpdated SessionEventType = "session.custom_agents_updated" SessionEventTypeSessionMcpServersLoaded SessionEventType = "session.mcp_servers_loaded" SessionEventTypeSessionMcpServerStatusChanged SessionEventType = "session.mcp_server_status_changed" SessionEventTypeSessionExtensionsLoaded SessionEventType = "session.extensions_loaded" )
type SessionExtensionsLoadedData ¶ added in v0.2.2
type SessionExtensionsLoadedData struct {
// Array of discovered extensions and their status
Extensions []ExtensionsLoadedExtension `json:"extensions"`
}
SessionExtensionsLoadedData holds the payload for session.extensions_loaded events.
type SessionFsConfig ¶ added in v0.2.2
type SessionFsConfig struct {
// InitialCwd is the initial working directory for sessions.
InitialCwd string
// SessionStatePath is the path within each session's filesystem where the runtime stores
// session-scoped files such as events, checkpoints, and temp files.
SessionStatePath string
// Conventions identifies the path conventions used by this filesystem provider.
Conventions rpc.SessionFSSetProviderConventions
}
SessionFsConfig configures a custom session filesystem provider.
type SessionFsFileInfo ¶ added in v0.3.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 v0.3.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.
Mkdir(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.
Readdir(path string) ([]string, error)
// ReaddirWithTypes lists entries with type information.
// Return os.ErrNotExist if the directory does not exist.
ReaddirWithTypes(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.
Rm(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).
type SessionHandoffData ¶ added in v0.2.2
type SessionHandoffData struct {
// Additional context information for the handoff
Context *string `json:"context,omitempty"`
// ISO 8601 timestamp when the handoff occurred
HandoffTime time.Time `json:"handoffTime"`
// GitHub host URL for the source session (e.g., https://github.com or https://tenant.ghe.com)
Host *string `json:"host,omitempty"`
// Session ID of the remote session being handed off
RemoteSessionID *string `json:"remoteSessionId,omitempty"`
// Repository context for the handed-off session
Repository *HandoffRepository `json:"repository,omitempty"`
// Origin type of the session being handed off
SourceType HandoffSourceType `json:"sourceType"`
// Summary of the work done in the source session
Summary *string `json:"summary,omitempty"`
}
Session handoff metadata including source, context, and repository information
type SessionHooks ¶ added in v0.1.20
type SessionHooks struct {
OnPreToolUse PreToolUseHandler
OnPostToolUse PostToolUseHandler
OnUserPromptSubmitted UserPromptSubmittedHandler
OnSessionStart SessionStartHandler
OnSessionEnd SessionEndHandler
OnErrorOccurred ErrorOccurredHandler
}
SessionHooks configures hook handlers for a session
type SessionIdleData ¶ added in v0.2.2
type SessionIdleData struct {
// True when the preceding agentic loop was cancelled via abort signal
Aborted *bool `json:"aborted,omitempty"`
}
Payload indicating the session is idle with no background agents in flight
type SessionInfoData ¶ added in v0.2.2
type SessionInfoData struct {
// Category of informational message (e.g., "notification", "timing", "context_window", "mcp", "snapshot", "configuration", "authentication", "model")
InfoType string `json:"infoType"`
// Human-readable informational message for display in the timeline
Message string `json:"message"`
// Optional URL associated with this message that the user can open in a browser
URL *string `json:"url,omitempty"`
}
Informational message for timeline display with categorization
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 string `json:"startTime"`
ModifiedTime string `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 {
// Cwd filters by exact working directory match
Cwd string `json:"cwd,omitempty"`
// GitRoot filters by git root
GitRoot string `json:"gitRoot,omitempty"`
// Repository filters by repository (owner/repo format)
Repository string `json:"repository,omitempty"`
// Branch filters by branch
Branch string `json:"branch,omitempty"`
}
SessionListFilter contains filter options for listing sessions
type SessionMcpServerStatusChangedData ¶ added in v0.2.2
type SessionMcpServerStatusChangedData struct {
// Name of the MCP server whose status changed
ServerName string `json:"serverName"`
// New connection status: connected, failed, needs-auth, pending, disabled, or not_configured
Status McpServerStatusChangedStatus `json:"status"`
}
SessionMcpServerStatusChangedData holds the payload for session.mcp_server_status_changed events.
type SessionMcpServersLoadedData ¶ added in v0.2.2
type SessionMcpServersLoadedData struct {
// Array of MCP server status summaries
Servers []McpServersLoadedServer `json:"servers"`
}
SessionMcpServersLoadedData holds the payload for session.mcp_servers_loaded events.
type SessionMetadata ¶ added in v0.1.19
type SessionMetadata struct {
SessionID string `json:"sessionId"`
StartTime string `json:"startTime"`
ModifiedTime string `json:"modifiedTime"`
Summary *string `json:"summary,omitempty"`
IsRemote bool `json:"isRemote"`
Context *SessionContext `json:"context,omitempty"`
}
SessionMetadata contains metadata about a session
type SessionModeChangedData ¶ added in v0.2.2
type SessionModeChangedData struct {
// Agent mode after the change (e.g., "interactive", "plan", "autopilot")
NewMode string `json:"newMode"`
// Agent mode before the change (e.g., "interactive", "plan", "autopilot")
PreviousMode string `json:"previousMode"`
}
Agent mode change details including previous and new modes
type SessionModelChangeData ¶ added in v0.2.2
type SessionModelChangeData struct {
// Newly selected model identifier
NewModel string `json:"newModel"`
// Model that was previously selected, if any
PreviousModel *string `json:"previousModel,omitempty"`
// Reasoning effort level before the model change, if applicable
PreviousReasoningEffort *string `json:"previousReasoningEffort,omitempty"`
// Reasoning effort level after the model change, if applicable
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
}
Model change details including previous and new model identifiers
type SessionPlanChangedData ¶ added in v0.2.2
type SessionPlanChangedData struct {
// The type of operation performed on the plan file
Operation PlanChangedOperation `json:"operation"`
}
Plan file operation details indicating what changed
type SessionRemoteSteerableChangedData ¶ added in v0.2.2
type SessionRemoteSteerableChangedData struct {
// Whether this session now supports remote steering via Mission Control
RemoteSteerable bool `json:"remoteSteerable"`
}
Notifies Mission Control that the session's remote steering capability has changed
type SessionResumeData ¶ added in v0.2.2
type SessionResumeData struct {
// Whether the session was already in use by another client at resume time
AlreadyInUse *bool `json:"alreadyInUse,omitempty"`
// Updated working directory and git context at resume time
Context *WorkingDirectoryContext `json:"context,omitempty"`
// Total number of persisted events in the session at the time of resume
EventCount float64 `json:"eventCount"`
// Reasoning effort level used for model calls, if applicable (e.g. "low", "medium", "high", "xhigh")
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
// Whether this session supports remote steering via Mission Control
RemoteSteerable *bool `json:"remoteSteerable,omitempty"`
// ISO 8601 timestamp when the session was resumed
ResumeTime time.Time `json:"resumeTime"`
// Model currently selected at resume time
SelectedModel *string `json:"selectedModel,omitempty"`
}
Session resume metadata including current context and event count
type SessionShutdownData ¶ added in v0.2.2
type SessionShutdownData struct {
// Aggregate code change metrics for the session
CodeChanges ShutdownCodeChanges `json:"codeChanges"`
// Non-system message token count at shutdown
ConversationTokens *float64 `json:"conversationTokens,omitempty"`
// Model that was selected at the time of shutdown
CurrentModel *string `json:"currentModel,omitempty"`
// Total tokens in context window at shutdown
CurrentTokens *float64 `json:"currentTokens,omitempty"`
// Error description when shutdownType is "error"
ErrorReason *string `json:"errorReason,omitempty"`
// Per-model usage breakdown, keyed by model identifier
ModelMetrics map[string]ShutdownModelMetric `json:"modelMetrics"`
// Unix timestamp (milliseconds) when the session started
SessionStartTime float64 `json:"sessionStartTime"`
// Whether the session ended normally ("routine") or due to a crash/fatal error ("error")
ShutdownType ShutdownType `json:"shutdownType"`
// System message token count at shutdown
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Tool definitions token count at shutdown
ToolDefinitionsTokens *float64 `json:"toolDefinitionsTokens,omitempty"`
// Cumulative time spent in API calls during the session, in milliseconds
TotalAPIDurationMs float64 `json:"totalApiDurationMs"`
// Total number of premium API requests used during the session
TotalPremiumRequests float64 `json:"totalPremiumRequests"`
}
Session termination metrics including usage statistics, code changes, and shutdown reason
type SessionSkillsLoadedData ¶ added in v0.2.2
type SessionSkillsLoadedData struct {
// Array of resolved skill metadata
Skills []SkillsLoadedSkill `json:"skills"`
}
SessionSkillsLoadedData holds the payload for session.skills_loaded events.
type SessionSnapshotRewindData ¶ added in v0.2.2
type SessionSnapshotRewindData struct {
// Number of events that were removed by the rewind
EventsRemoved float64 `json:"eventsRemoved"`
// Event ID that was rewound to; this event and all after it were removed
UpToEventID string `json:"upToEventId"`
}
Session rewind details including target event and count of removed events
type SessionStartData ¶ added in v0.2.2
type SessionStartData struct {
// Whether the session was already in use by another client at start time
AlreadyInUse *bool `json:"alreadyInUse,omitempty"`
// Working directory and git context at session start
Context *WorkingDirectoryContext `json:"context,omitempty"`
// Version string of the Copilot application
CopilotVersion string `json:"copilotVersion"`
// Identifier of the software producing the events (e.g., "copilot-agent")
Producer string `json:"producer"`
// Reasoning effort level used for model calls, if applicable (e.g. "low", "medium", "high", "xhigh")
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
// Whether this session supports remote steering via Mission Control
RemoteSteerable *bool `json:"remoteSteerable,omitempty"`
// Model selected at session creation time, if any
SelectedModel *string `json:"selectedModel,omitempty"`
// Unique identifier for the session
SessionID string `json:"sessionId"`
// ISO 8601 timestamp when the session was created
StartTime time.Time `json:"startTime"`
// Schema version number for the session event format
Version float64 `json:"version"`
}
Session initialization metadata including context and configuration
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 {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Source string `json:"source"` // "startup", "resume", "new"
InitialPrompt string `json:"initialPrompt,omitempty"`
}
SessionStartHookInput is the input for a session-start hook
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 struct {
// Whether the tool call succeeded. False when validation failed (e.g., invalid arguments)
Success *bool `json:"success,omitempty"`
// Summary of the completed task, provided by the agent
Summary *string `json:"summary,omitempty"`
}
Task completion notification with summary from the agent
type SessionTitleChangedData ¶ added in v0.2.2
type SessionTitleChangedData struct {
// The new display title for the session
Title string `json:"title"`
}
Session title change payload containing the new display title
type SessionToolsUpdatedData ¶ added in v0.2.2
type SessionToolsUpdatedData struct {
Model string `json:"model"`
}
SessionToolsUpdatedData holds the payload for session.tools_updated events.
type SessionTruncationData ¶ added in v0.2.2
type SessionTruncationData struct {
// Number of messages removed by truncation
MessagesRemovedDuringTruncation float64 `json:"messagesRemovedDuringTruncation"`
// Identifier of the component that performed truncation (e.g., "BasicTruncator")
PerformedBy string `json:"performedBy"`
// Number of conversation messages after truncation
PostTruncationMessagesLength float64 `json:"postTruncationMessagesLength"`
// Total tokens in conversation messages after truncation
PostTruncationTokensInMessages float64 `json:"postTruncationTokensInMessages"`
// Number of conversation messages before truncation
PreTruncationMessagesLength float64 `json:"preTruncationMessagesLength"`
// Total tokens in conversation messages before truncation
PreTruncationTokensInMessages float64 `json:"preTruncationTokensInMessages"`
// Maximum token count for the model's context window
TokenLimit float64 `json:"tokenLimit"`
// Number of tokens removed by truncation
TokensRemovedDuringTruncation float64 `json:"tokensRemovedDuringTruncation"`
}
Conversation truncation statistics including token counts and removed content metrics
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 rpc.UIElicitationSchema) (*ElicitationResult, error)
Elicitation shows a generic elicitation dialog with a custom schema.
type SessionUsageInfoData ¶ added in v0.2.2
type SessionUsageInfoData struct {
// Token count from non-system messages (user, assistant, tool)
ConversationTokens *float64 `json:"conversationTokens,omitempty"`
// Current number of tokens in the context window
CurrentTokens float64 `json:"currentTokens"`
// Whether this is the first usage_info event emitted in this session
IsInitial *bool `json:"isInitial,omitempty"`
// Current number of messages in the conversation
MessagesLength float64 `json:"messagesLength"`
// Token count from system message(s)
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Maximum token count for the model's context window
TokenLimit float64 `json:"tokenLimit"`
// Token count from tool definitions
ToolDefinitionsTokens *float64 `json:"toolDefinitionsTokens,omitempty"`
}
Current context window usage statistics including token and message counts
type SessionWarningData ¶ added in v0.2.2
type SessionWarningData struct {
// Human-readable warning message for display in the timeline
Message string `json:"message"`
// Optional URL associated with this warning that the user can open in a browser
URL *string `json:"url,omitempty"`
// Category of warning (e.g., "subscription", "policy", "mcp")
WarningType string `json:"warningType"`
}
Warning message for timeline display with categorization
type SessionWorkspaceFileChangedData ¶ added in v0.2.2
type SessionWorkspaceFileChangedData struct {
// Whether the file was newly created or updated
Operation WorkspaceFileChangedOperation `json:"operation"`
// Relative path within the session workspace files directory
Path string `json:"path"`
}
Workspace file change details including path and operation type
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
// 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 struct {
// List of file paths that were modified during the session
FilesModified []string `json:"filesModified"`
// Total number of lines added during the session
LinesAdded float64 `json:"linesAdded"`
// Total number of lines removed during the session
LinesRemoved float64 `json:"linesRemoved"`
}
Aggregate code change metrics for the session
type ShutdownModelMetric ¶ added in v0.3.0
type ShutdownModelMetric struct {
// Request count and cost metrics
Requests ShutdownModelMetricRequests `json:"requests"`
// Token usage breakdown
Usage ShutdownModelMetricUsage `json:"usage"`
}
type ShutdownModelMetricRequests ¶ added in v0.3.0
type ShutdownModelMetricRequests struct {
// Cumulative cost multiplier for requests to this model
Cost float64 `json:"cost"`
// Total number of API requests made to this model
Count float64 `json:"count"`
}
Request count and cost metrics
type ShutdownModelMetricUsage ¶ added in v0.3.0
type ShutdownModelMetricUsage struct {
// Total tokens read from prompt cache across all requests
CacheReadTokens float64 `json:"cacheReadTokens"`
// Total tokens written to prompt cache across all requests
CacheWriteTokens float64 `json:"cacheWriteTokens"`
// Total input tokens consumed across all requests to this model
InputTokens float64 `json:"inputTokens"`
// Total output tokens produced across all requests to this model
OutputTokens float64 `json:"outputTokens"`
// Total reasoning tokens produced across all requests to this model
ReasoningTokens *float64 `json:"reasoningTokens,omitempty"`
}
Token usage breakdown
type ShutdownType ¶ added in v0.1.21
type ShutdownType string
Whether the session ended normally ("routine") or due to a crash/fatal error ("error")
const ( ShutdownTypeRoutine ShutdownType = "routine" ShutdownTypeError ShutdownType = "error" )
type SkillInvokedData ¶ added in v0.2.2
type SkillInvokedData struct {
// Tool names that should be auto-approved when this skill is active
AllowedTools []string `json:"allowedTools,omitempty"`
// Full content of the skill file, injected into the conversation for the model
Content string `json:"content"`
// Description of the skill from its SKILL.md frontmatter
Description *string `json:"description,omitempty"`
// Name of the invoked skill
Name string `json:"name"`
// File path to the SKILL.md definition
Path string `json:"path"`
// Name of the plugin this skill originated from, when applicable
PluginName *string `json:"pluginName,omitempty"`
// Version of the plugin this skill originated from, when applicable
PluginVersion *string `json:"pluginVersion,omitempty"`
}
Skill invocation details including content, allowed tools, and plugin metadata
type SkillsLoadedSkill ¶ added in v0.3.0
type SkillsLoadedSkill struct {
// Description of what the skill does
Description string `json:"description"`
// Whether the skill is currently enabled
Enabled bool `json:"enabled"`
// Unique identifier for the skill
Name string `json:"name"`
// Absolute path to the skill file, if available
Path *string `json:"path,omitempty"`
// Source location type of the skill (e.g., project, personal, plugin)
Source string `json:"source"`
// Whether the skill can be invoked by the user as a slash command
UserInvocable bool `json:"userInvocable"`
}
type SubagentCompletedData ¶ added in v0.2.2
type SubagentCompletedData struct {
// Human-readable display name of the sub-agent
AgentDisplayName string `json:"agentDisplayName"`
// Internal name of the sub-agent
AgentName string `json:"agentName"`
// Wall-clock duration of the sub-agent execution in milliseconds
DurationMs *float64 `json:"durationMs,omitempty"`
// Model used by the sub-agent
Model *string `json:"model,omitempty"`
// Tool call ID of the parent tool invocation that spawned this sub-agent
ToolCallID string `json:"toolCallId"`
// Total tokens (input + output) consumed by the sub-agent
TotalTokens *float64 `json:"totalTokens,omitempty"`
// Total number of tool calls made by the sub-agent
TotalToolCalls *float64 `json:"totalToolCalls,omitempty"`
}
Sub-agent completion details for successful execution
type SubagentDeselectedData ¶ added in v0.2.2
type SubagentDeselectedData struct {
}
Empty payload; the event signals that the custom agent was deselected, returning to the default agent
type SubagentFailedData ¶ added in v0.2.2
type SubagentFailedData struct {
// Human-readable display name of the sub-agent
AgentDisplayName string `json:"agentDisplayName"`
// Internal name of the sub-agent
AgentName string `json:"agentName"`
// Wall-clock duration of the sub-agent execution in milliseconds
DurationMs *float64 `json:"durationMs,omitempty"`
// Error message describing why the sub-agent failed
Error string `json:"error"`
// Model used by the sub-agent (if any model calls succeeded before failure)
Model *string `json:"model,omitempty"`
// Tool call ID of the parent tool invocation that spawned this sub-agent
ToolCallID string `json:"toolCallId"`
// Total tokens (input + output) consumed before the sub-agent failed
TotalTokens *float64 `json:"totalTokens,omitempty"`
// Total number of tool calls made before the sub-agent failed
TotalToolCalls *float64 `json:"totalToolCalls,omitempty"`
}
Sub-agent failure details including error message and agent information
type SubagentSelectedData ¶ added in v0.2.2
type SubagentSelectedData struct {
// Human-readable display name of the selected custom agent
AgentDisplayName string `json:"agentDisplayName"`
// Internal name of the selected custom agent
AgentName string `json:"agentName"`
// List of tool names available to this agent, or null for all tools
Tools []string `json:"tools"`
}
Custom agent selection details including name and available tools
type SubagentStartedData ¶ added in v0.2.2
type SubagentStartedData struct {
// Description of what the sub-agent does
AgentDescription string `json:"agentDescription"`
// Human-readable display name of the sub-agent
AgentDisplayName string `json:"agentDisplayName"`
// Internal name of the sub-agent
AgentName string `json:"agentName"`
// Tool call ID of the parent tool invocation that spawned this sub-agent
ToolCallID string `json:"toolCallId"`
}
Sub-agent startup details including parent tool call and agent information
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 struct {
// The system or developer prompt text sent as model input
Content string `json:"content"`
// Metadata about the prompt template and its construction
Metadata *SystemMessageMetadata `json:"metadata,omitempty"`
// Optional name identifier for the message source
Name *string `json:"name,omitempty"`
// Message role: "system" for system prompts, "developer" for developer-injected instructions
Role SystemMessageRole `json:"role"`
}
System/developer instruction content with role and optional template metadata
type SystemMessageMetadata ¶ added in v0.3.0
type SystemMessageMetadata struct {
// Version identifier of the prompt template used
PromptVersion *string `json:"promptVersion,omitempty"`
// Template variables used when constructing the prompt
Variables map[string]any `json:"variables,omitempty"`
}
Metadata about the prompt template and its construction
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 string
Message role: "system" for system prompts, "developer" for developer-injected instructions
const ( SystemMessageRoleSystem SystemMessageRole = "system" SystemMessageRoleDeveloper SystemMessageRole = "developer" )
type SystemNotification ¶ added in v0.3.0
type SystemNotification struct {
// Type discriminator
Type SystemNotificationType `json:"type"`
// Unique identifier of the background agent
AgentID *string `json:"agentId,omitempty"`
// Type of the agent (e.g., explore, task, general-purpose)
AgentType *string `json:"agentType,omitempty"`
// Human-readable description of the agent task
Description *string `json:"description,omitempty"`
// Unique identifier of the inbox entry
EntryID *string `json:"entryId,omitempty"`
// Exit code of the shell command, if available
ExitCode *float64 `json:"exitCode,omitempty"`
// The full prompt given to the background agent
Prompt *string `json:"prompt,omitempty"`
// Human-readable name of the sender
SenderName *string `json:"senderName,omitempty"`
// Category of the sender (e.g., ambient-agent, plugin, hook)
SenderType *string `json:"senderType,omitempty"`
// Unique identifier of the shell session
ShellID *string `json:"shellId,omitempty"`
// Whether the agent completed successfully or failed
Status *SystemNotificationAgentCompletedStatus `json:"status,omitempty"`
// Short summary shown before the agent decides whether to read the inbox
Summary *string `json:"summary,omitempty"`
}
Structured metadata identifying what triggered this notification
type SystemNotificationAgentCompletedStatus ¶ added in v0.3.0
type SystemNotificationAgentCompletedStatus string
Whether the agent completed successfully or failed
const ( SystemNotificationAgentCompletedStatusCompleted SystemNotificationAgentCompletedStatus = "completed" SystemNotificationAgentCompletedStatusFailed SystemNotificationAgentCompletedStatus = "failed" )
type SystemNotificationData ¶ added in v0.2.2
type SystemNotificationData struct {
// The notification text, typically wrapped in <system_notification> XML tags
Content string `json:"content"`
// Structured metadata identifying what triggered this notification
Kind SystemNotification `json:"kind"`
}
System-generated notification for runtime events like background task completion
type SystemNotificationType ¶ added in v0.3.0
type SystemNotificationType string
Type discriminator for SystemNotification.
const ( SystemNotificationTypeAgentCompleted SystemNotificationType = "agent_completed" SystemNotificationTypeAgentIdle SystemNotificationType = "agent_idle" SystemNotificationTypeNewInboxMessage SystemNotificationType = "new_inbox_message" SystemNotificationTypeShellCompleted SystemNotificationType = "shell_completed" SystemNotificationTypeShellDetachedCompleted SystemNotificationType = "shell_detached_completed" )
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,omitempty"`
OverridesBuiltInTool bool `json:"overridesBuiltInTool,omitempty"`
SkipPermission bool `json:"skipPermission,omitempty"`
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 struct {
// Type discriminator
Type ToolExecutionCompleteContentType `json:"type"`
// Working directory where the command was executed
Cwd *string `json:"cwd,omitempty"`
// Base64-encoded image data
Data *string `json:"data,omitempty"`
// Human-readable description of the resource
Description *string `json:"description,omitempty"`
// Process exit code, if the command has completed
ExitCode *float64 `json:"exitCode,omitempty"`
// Icons associated with this resource
Icons []ToolExecutionCompleteContentResourceLinkIcon `json:"icons,omitempty"`
// MIME type of the image (e.g., image/png, image/jpeg)
MIMEType *string `json:"mimeType,omitempty"`
// Resource name identifier
Name *string `json:"name,omitempty"`
// The embedded resource contents, either text or base64-encoded binary
Resource any `json:"resource,omitempty"`
// Size of the resource in bytes
Size *float64 `json:"size,omitempty"`
// The text content
Text *string `json:"text,omitempty"`
// Human-readable display title for the resource
Title *string `json:"title,omitempty"`
// URI identifying the resource
URI *string `json:"uri,omitempty"`
}
A content block within a tool result, which may be text, terminal output, image, audio, or a resource
type ToolExecutionCompleteContentResourceLinkIcon ¶ added in v0.3.0
type ToolExecutionCompleteContentResourceLinkIcon struct {
// MIME type of the icon image
MIMEType *string `json:"mimeType,omitempty"`
// Available icon sizes (e.g., ['16x16', '32x32'])
Sizes []string `json:"sizes,omitempty"`
// URL or path to the icon image
Src string `json:"src"`
// Theme variant this icon is intended for
Theme *ToolExecutionCompleteContentResourceLinkIconTheme `json:"theme,omitempty"`
}
Icon image for a resource
type ToolExecutionCompleteContentResourceLinkIconTheme ¶ added in v0.3.0
type ToolExecutionCompleteContentResourceLinkIconTheme string
Theme variant this icon is intended for
const ( ToolExecutionCompleteContentResourceLinkIconThemeLight ToolExecutionCompleteContentResourceLinkIconTheme = "light" ToolExecutionCompleteContentResourceLinkIconThemeDark ToolExecutionCompleteContentResourceLinkIconTheme = "dark" )
type ToolExecutionCompleteContentType ¶ added in v0.3.0
type ToolExecutionCompleteContentType string
Type discriminator for ToolExecutionCompleteContent.
const ( ToolExecutionCompleteContentTypeText ToolExecutionCompleteContentType = "text" ToolExecutionCompleteContentTypeTerminal ToolExecutionCompleteContentType = "terminal" ToolExecutionCompleteContentTypeImage ToolExecutionCompleteContentType = "image" ToolExecutionCompleteContentTypeAudio ToolExecutionCompleteContentType = "audio" ToolExecutionCompleteContentTypeResourceLink ToolExecutionCompleteContentType = "resource_link" ToolExecutionCompleteContentTypeResource ToolExecutionCompleteContentType = "resource" )
type ToolExecutionCompleteData ¶ added in v0.2.2
type ToolExecutionCompleteData struct {
// Error details when the tool execution failed
Error *ToolExecutionCompleteError `json:"error,omitempty"`
// CAPI interaction ID for correlating this tool execution with upstream telemetry
InteractionID *string `json:"interactionId,omitempty"`
// Whether this tool call was explicitly requested by the user rather than the assistant
IsUserRequested *bool `json:"isUserRequested,omitempty"`
// Model identifier that generated this tool call
Model *string `json:"model,omitempty"`
// Tool call ID of the parent tool invocation when this event originates from a sub-agent
// Deprecated: ParentToolCallID is deprecated.
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
// Tool execution result on success
Result *ToolExecutionCompleteResult `json:"result,omitempty"`
// Whether the tool execution completed successfully
Success bool `json:"success"`
// Unique identifier for the completed tool call
ToolCallID string `json:"toolCallId"`
// Tool-specific telemetry data (e.g., CodeQL check counts, grep match counts)
ToolTelemetry map[string]any `json:"toolTelemetry,omitempty"`
}
Tool execution completion results including success status, detailed output, and error information
type ToolExecutionCompleteError ¶ added in v0.3.0
type ToolExecutionCompleteError struct {
// Machine-readable error code
Code *string `json:"code,omitempty"`
// Human-readable error message
Message string `json:"message"`
}
Error details when the tool execution failed
type ToolExecutionCompleteResult ¶ added in v0.3.0
type ToolExecutionCompleteResult struct {
// Concise tool result text sent to the LLM for chat completion, potentially truncated for token efficiency
Content string `json:"content"`
// Structured content blocks (text, images, audio, resources) returned by the tool in their native format
Contents []ToolExecutionCompleteContent `json:"contents,omitempty"`
// Full detailed tool result for UI/timeline display, preserving complete content such as diffs. Falls back to content when absent.
DetailedContent *string `json:"detailedContent,omitempty"`
}
Tool execution result on success
type ToolExecutionPartialResultData ¶ added in v0.2.2
type ToolExecutionPartialResultData struct {
// Incremental output chunk from the running tool
PartialOutput string `json:"partialOutput"`
// Tool call ID this partial result belongs to
ToolCallID string `json:"toolCallId"`
}
Streaming tool execution output for incremental result display
type ToolExecutionProgressData ¶ added in v0.2.2
type ToolExecutionProgressData struct {
// Human-readable progress status message (e.g., from an MCP server)
ProgressMessage string `json:"progressMessage"`
// Tool call ID this progress notification belongs to
ToolCallID string `json:"toolCallId"`
}
Tool execution progress notification with status message
type ToolExecutionStartData ¶ added in v0.2.2
type ToolExecutionStartData struct {
// Arguments passed to the tool
Arguments any `json:"arguments,omitempty"`
// Name of the MCP server hosting this tool, when the tool is an MCP tool
McpServerName *string `json:"mcpServerName,omitempty"`
// Original tool name on the MCP server, when the tool is an MCP tool
McpToolName *string `json:"mcpToolName,omitempty"`
// Tool call ID of the parent tool invocation when this event originates from a sub-agent
// Deprecated: ParentToolCallID is deprecated.
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
// Unique identifier for this tool call
ToolCallID string `json:"toolCallId"`
// Name of the tool being executed
ToolName string `json:"toolName"`
}
Tool execution startup details including MCP server information when applicable
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 ToolUserRequestedData ¶ added in v0.2.2
type ToolUserRequestedData struct {
// Arguments for the tool invocation
Arguments any `json:"arguments,omitempty"`
// Unique identifier for this tool call
ToolCallID string `json:"toolCallId"`
// Name of the tool the user wants to invoke
ToolName string `json:"toolName"`
}
User-initiated tool invocation request with tool name and arguments
type UICapabilities ¶ added in v0.2.1
type UICapabilities struct {
// Elicitation indicates whether the host supports interactive elicitation dialogs.
Elicitation bool `json:"elicitation,omitempty"`
}
UICapabilities describes host UI feature support.
type UserInputCompletedData ¶ added in v0.2.2
type UserInputCompletedData struct {
// The user's answer to the input request
Answer *string `json:"answer,omitempty"`
// Request ID of the resolved user input request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
// Whether the answer was typed as free-form text rather than selected from choices
WasFreeform *bool `json:"wasFreeform,omitempty"`
}
User input request completion with the user's response
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 struct {
// Whether the user can provide a free-form text response in addition to predefined choices
AllowFreeform *bool `json:"allowFreeform,omitempty"`
// Predefined choices for the user to select from, if applicable
Choices []string `json:"choices,omitempty"`
// The question or prompt to present to the user
Question string `json:"question"`
// Unique identifier for this input request; used to respond via session.respondToUserInput()
RequestID string `json:"requestId"`
// The LLM-assigned tool call ID that triggered this request; used by remote UIs to correlate responses
ToolCallID *string `json:"toolCallId,omitempty"`
}
User input request notification with question and optional predefined choices
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 string
The agent mode that was active when this message was sent
const ( UserMessageAgentModeInteractive UserMessageAgentMode = "interactive" UserMessageAgentModePlan UserMessageAgentMode = "plan" UserMessageAgentModeAutopilot UserMessageAgentMode = "autopilot" UserMessageAgentModeShell UserMessageAgentMode = "shell" )
type UserMessageAttachment ¶ added in v0.3.0
type UserMessageAttachment struct {
// Type discriminator
Type UserMessageAttachmentType `json:"type"`
// Base64-encoded content
Data *string `json:"data,omitempty"`
// User-facing display name for the attachment
DisplayName *string `json:"displayName,omitempty"`
// Absolute path to the file containing the selection
FilePath *string `json:"filePath,omitempty"`
// Optional line range to scope the attachment to a specific section of the file
LineRange *UserMessageAttachmentFileLineRange `json:"lineRange,omitempty"`
// MIME type of the inline data
MIMEType *string `json:"mimeType,omitempty"`
// Issue, pull request, or discussion number
Number *float64 `json:"number,omitempty"`
// Absolute file path
Path *string `json:"path,omitempty"`
// Type of GitHub reference
ReferenceType *UserMessageAttachmentGithubReferenceType `json:"referenceType,omitempty"`
// Position range of the selection within the file
Selection *UserMessageAttachmentSelectionDetails `json:"selection,omitempty"`
// Current state of the referenced item (e.g., open, closed, merged)
State *string `json:"state,omitempty"`
// The selected text content
Text *string `json:"text,omitempty"`
// Title of the referenced item
Title *string `json:"title,omitempty"`
// URL to the referenced item on GitHub
URL *string `json:"url,omitempty"`
}
A user message attachment — a file, directory, code selection, blob, or GitHub reference
type UserMessageAttachmentFileLineRange ¶ added in v0.3.0
type UserMessageAttachmentFileLineRange struct {
// End line number (1-based, inclusive)
End float64 `json:"end"`
// Start line number (1-based)
Start float64 `json:"start"`
}
Optional line range to scope the attachment to a specific section of the file
type UserMessageAttachmentGithubReferenceType ¶ added in v0.3.0
type UserMessageAttachmentGithubReferenceType string
Type of GitHub reference
const ( UserMessageAttachmentGithubReferenceTypeIssue UserMessageAttachmentGithubReferenceType = "issue" UserMessageAttachmentGithubReferenceTypePr UserMessageAttachmentGithubReferenceType = "pr" UserMessageAttachmentGithubReferenceTypeDiscussion UserMessageAttachmentGithubReferenceType = "discussion" )
type UserMessageAttachmentSelectionDetails ¶ added in v0.3.0
type UserMessageAttachmentSelectionDetails struct {
// End position of the selection
End UserMessageAttachmentSelectionDetailsEnd `json:"end"`
// Start position of the selection
Start UserMessageAttachmentSelectionDetailsStart `json:"start"`
}
Position range of the selection within the file
type UserMessageAttachmentSelectionDetailsEnd ¶ added in v0.3.0
type UserMessageAttachmentSelectionDetailsEnd struct {
// End character offset within the line (0-based)
Character float64 `json:"character"`
// End line number (0-based)
Line float64 `json:"line"`
}
End position of the selection
type UserMessageAttachmentSelectionDetailsStart ¶ added in v0.3.0
type UserMessageAttachmentSelectionDetailsStart struct {
// Start character offset within the line (0-based)
Character float64 `json:"character"`
// Start line number (0-based)
Line float64 `json:"line"`
}
Start position of the selection
type UserMessageAttachmentType ¶ added in v0.3.0
type UserMessageAttachmentType string
Type discriminator for UserMessageAttachment.
const ( UserMessageAttachmentTypeFile UserMessageAttachmentType = "file" UserMessageAttachmentTypeDirectory UserMessageAttachmentType = "directory" UserMessageAttachmentTypeSelection UserMessageAttachmentType = "selection" UserMessageAttachmentTypeGithubReference UserMessageAttachmentType = "github_reference" UserMessageAttachmentTypeBlob UserMessageAttachmentType = "blob" )
type UserMessageData ¶ added in v0.2.2
type UserMessageData struct {
// The agent mode that was active when this message was sent
AgentMode *UserMessageAgentMode `json:"agentMode,omitempty"`
// Files, selections, or GitHub references attached to the message
Attachments []UserMessageAttachment `json:"attachments,omitempty"`
// The user's message text as displayed in the timeline
Content string `json:"content"`
// CAPI interaction ID for correlating this user message with its turn
InteractionID *string `json:"interactionId,omitempty"`
// Path-backed native document attachments that stayed on the tagged_files path flow because native upload would exceed the request size limit
NativeDocumentPathFallbackPaths []string `json:"nativeDocumentPathFallbackPaths,omitempty"`
// Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user)
Source *string `json:"source,omitempty"`
// Normalized document MIME types that were sent natively instead of through tagged_files XML
SupportedNativeDocumentMIMETypes []string `json:"supportedNativeDocumentMimeTypes,omitempty"`
// Transformed version of the message sent to the model, with XML wrapping, timestamps, and other augmentations for prompt caching
TransformedContent *string `json:"transformedContent,omitempty"`
}
UserMessageData holds the payload for user.message events.
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 {
Timestamp int64 `json:"timestamp"`
Cwd string `json:"cwd"`
Prompt string `json:"prompt"`
}
UserPromptSubmittedHookInput is the input for a user-prompt-submitted hook
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 WorkingDirectoryContext ¶ added in v0.3.0
type WorkingDirectoryContext struct {
// Base commit of current git branch at session start time
BaseCommit *string `json:"baseCommit,omitempty"`
// Current git branch name
Branch *string `json:"branch,omitempty"`
// Current working directory path
Cwd string `json:"cwd"`
// Root directory of the git repository, resolved via git rev-parse
GitRoot *string `json:"gitRoot,omitempty"`
// Head commit of current git branch at session start time
HeadCommit *string `json:"headCommit,omitempty"`
// Hosting platform type of the repository (github or ado)
HostType *WorkingDirectoryContextHostType `json:"hostType,omitempty"`
// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps)
Repository *string `json:"repository,omitempty"`
// Raw host string from the git remote URL (e.g. "github.com", "mycompany.ghe.com", "dev.azure.com")
RepositoryHost *string `json:"repositoryHost,omitempty"`
}
Working directory and git context at session start
type WorkingDirectoryContextHostType ¶ added in v0.3.0
type WorkingDirectoryContextHostType string
Hosting platform type of the repository (github or ado)
const ( WorkingDirectoryContextHostTypeGithub WorkingDirectoryContextHostType = "github" WorkingDirectoryContextHostTypeAdo WorkingDirectoryContextHostType = "ado" )
type WorkspaceFileChangedOperation ¶ added in v0.3.0
type WorkspaceFileChangedOperation string
Whether the file was newly created or updated
const ( WorkspaceFileChangedOperationCreate WorkspaceFileChangedOperation = "create" WorkspaceFileChangedOperationUpdate WorkspaceFileChangedOperation = "update" )
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
|