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 AssistantMessageDataToolRequestsItem
- type AssistantMessageDataToolRequestsItemType
- type AssistantMessageDeltaData
- type AssistantReasoningData
- type AssistantReasoningDeltaData
- type AssistantStreamingDeltaData
- type AssistantTurnEndData
- type AssistantTurnStartData
- type AssistantUsageData
- type AssistantUsageDataCopilotUsage
- type AssistantUsageDataCopilotUsageTokenDetailsItem
- type AssistantUsageDataQuotaSnapshotsValue
- type Attachment
- type AttachmentType
- type AzureProviderOptions
- type CapabilitiesChangedData
- type CapabilitiesChangedDataUI
- 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 CommandsChangedData
- type CommandsChangedDataCommandsItem
- type ConnectionState
- type CustomAgentConfig
- type ElicitationCompletedData
- type ElicitationCompletedDataAction
- type ElicitationContext
- type ElicitationHandler
- type ElicitationRequestedData
- type ElicitationRequestedDataMode
- type ElicitationRequestedDataRequestedSchema
- type ElicitationResult
- type ErrorOccurredHandler
- type ErrorOccurredHookInput
- type ErrorOccurredHookOutput
- type ExitPlanModeCompletedData
- type ExitPlanModeRequestedData
- type ExternalToolCompletedData
- type ExternalToolRequestedData
- type GetAuthStatusResponse
- type GetStatusResponse
- type HookEndData
- type HookEndDataError
- type HookInvocation
- type HookStartData
- type InfiniteSessionConfig
- type InputOptions
- type LogOptions
- type MCPLocalServerConfig
- type MCPRemoteServerConfig
- type MCPServerConfig
- type McpOauthCompletedData
- type McpOauthRequiredData
- type McpOauthRequiredDataStaticClientConfig
- 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 PermissionCompletedDataResult
- type PermissionCompletedDataResultKind
- type PermissionHandlerFunc
- type PermissionInvocation
- type PermissionRequest
- type PermissionRequestCommand
- type PermissionRequestKind
- type PermissionRequestResult
- type PermissionRequestResultKind
- type PermissionRequestedData
- type PermissionRequestedDataPermissionRequest
- type PermissionRequestedDataPermissionRequestCommandsItem
- type PermissionRequestedDataPermissionRequestKind
- type PermissionRequestedDataPermissionRequestPossibleUrlsItem
- type PingResponse
- 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 SessionCompactionCompleteDataCompactionTokensUsed
- type SessionCompactionStartData
- type SessionConfig
- type SessionContext
- type SessionContextChangedData
- type SessionCustomAgentsUpdatedData
- type SessionCustomAgentsUpdatedDataAgentsItem
- type SessionEndHandler
- type SessionEndHookInput
- type SessionEndHookOutput
- type SessionErrorData
- type SessionEvent
- type SessionEventData
- type SessionEventHandler
- type SessionEventType
- type SessionExtensionsLoadedData
- type SessionExtensionsLoadedDataExtensionsItem
- type SessionExtensionsLoadedDataExtensionsItemSource
- type SessionExtensionsLoadedDataExtensionsItemStatus
- type SessionFsConfig
- type SessionHandoffData
- type SessionHandoffDataRepository
- type SessionHandoffDataSourceType
- type SessionHooks
- type SessionIdleData
- type SessionInfoData
- type SessionLifecycleEvent
- type SessionLifecycleEventMetadata
- type SessionLifecycleEventType
- type SessionLifecycleHandler
- type SessionListFilter
- type SessionMcpServerStatusChangedData
- type SessionMcpServersLoadedData
- type SessionMcpServersLoadedDataServersItem
- type SessionMcpServersLoadedDataServersItemStatus
- type SessionMetadata
- type SessionModeChangedData
- type SessionModelChangeData
- type SessionPlanChangedData
- type SessionPlanChangedDataOperation
- type SessionRemoteSteerableChangedData
- type SessionResumeData
- type SessionResumeDataContext
- type SessionShutdownData
- type SessionShutdownDataCodeChanges
- type SessionShutdownDataModelMetricsValue
- type SessionShutdownDataModelMetricsValueRequests
- type SessionShutdownDataModelMetricsValueUsage
- type SessionShutdownDataShutdownType
- type SessionSkillsLoadedData
- type SessionSkillsLoadedDataSkillsItem
- type SessionSnapshotRewindData
- type SessionStartData
- type SessionStartDataContext
- type SessionStartDataContextHostType
- 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.RequestedSchema) (*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 SessionWorkspaceFileChangedDataOperation
- type SetModelOptions
- type SkillInvokedData
- type SubagentCompletedData
- type SubagentDeselectedData
- type SubagentFailedData
- type SubagentSelectedData
- type SubagentStartedData
- type SystemMessageAppendConfig
- type SystemMessageConfig
- type SystemMessageData
- type SystemMessageDataMetadata
- type SystemMessageDataRole
- type SystemMessageReplaceConfig
- type SystemNotificationData
- type SystemNotificationDataKind
- type SystemNotificationDataKindStatus
- type SystemNotificationDataKindType
- type TelemetryConfig
- type Tool
- type ToolBinaryResult
- type ToolExecutionCompleteData
- type ToolExecutionCompleteDataError
- type ToolExecutionCompleteDataResult
- type ToolExecutionCompleteDataResultContentsItem
- type ToolExecutionCompleteDataResultContentsItemIconsItem
- type ToolExecutionCompleteDataResultContentsItemIconsItemTheme
- type ToolExecutionCompleteDataResultContentsItemType
- 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 UserMessageData
- type UserMessageDataAgentMode
- type UserMessageDataAttachmentsItem
- type UserMessageDataAttachmentsItemLineRange
- type UserMessageDataAttachmentsItemReferenceType
- type UserMessageDataAttachmentsItemSelection
- type UserMessageDataAttachmentsItemSelectionEnd
- type UserMessageDataAttachmentsItemSelectionStart
- type UserMessageDataAttachmentsItemType
- type UserPromptSubmittedHandler
- type UserPromptSubmittedHookInput
- type UserPromptSubmittedHookOutput
Constants ¶
const ( AttachmentTypeFile = UserMessageDataAttachmentsItemTypeFile AttachmentTypeDirectory = UserMessageDataAttachmentsItemTypeDirectory AttachmentTypeSelection = UserMessageDataAttachmentsItemTypeSelection AttachmentTypeGithubReference = UserMessageDataAttachmentsItemTypeGithubReference AttachmentTypeBlob = UserMessageDataAttachmentsItemTypeBlob PermissionRequestKindShell = PermissionRequestedDataPermissionRequestKindShell PermissionRequestKindWrite = PermissionRequestedDataPermissionRequestKindWrite PermissionRequestKindRead = PermissionRequestedDataPermissionRequestKindRead PermissionRequestKindMcp = PermissionRequestedDataPermissionRequestKindMcp PermissionRequestKindURL = PermissionRequestedDataPermissionRequestKindURL PermissionRequestKindMemory = PermissionRequestedDataPermissionRequestKindMemory PermissionRequestKindCustomTool = PermissionRequestedDataPermissionRequestKindCustomTool PermissionRequestKindHook = PermissionRequestedDataPermissionRequestKindHook )
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 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 {
// Unique identifier for this assistant message
MessageID string `json:"messageId"`
// The assistant's text response content
Content string `json:"content"`
// Tool invocations requested by the assistant in this message
ToolRequests []AssistantMessageDataToolRequestsItem `json:"toolRequests,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"`
// Encrypted reasoning content from OpenAI models. Session-bound and stripped on resume.
EncryptedContent *string `json:"encryptedContent,omitempty"`
// Generation phase for phased-output models (e.g., thinking vs. response phases)
Phase *string `json:"phase,omitempty"`
// Actual output token count from the API response (completion_tokens), used for accurate token accounting
OutputTokens *float64 `json:"outputTokens,omitempty"`
// CAPI interaction ID for correlating this message with upstream telemetry
InteractionID *string `json:"interactionId,omitempty"`
// GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs
RequestID *string `json:"requestId,omitempty"`
// Tool call ID of the parent tool invocation when this event originates from a sub-agent
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
}
Assistant response containing text content, optional tool requests, and interaction metadata
type AssistantMessageDataToolRequestsItem ¶ added in v0.2.2
type AssistantMessageDataToolRequestsItem struct {
// Unique identifier for this tool call
ToolCallID string `json:"toolCallId"`
// Name of the tool being invoked
Name string `json:"name"`
// Arguments to pass to the tool, format depends on the tool
Arguments any `json:"arguments,omitempty"`
// Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent.
Type *AssistantMessageDataToolRequestsItemType `json:"type,omitempty"`
// Human-readable display title for the tool
ToolTitle *string `json:"toolTitle,omitempty"`
// Name of the MCP server hosting this tool, when the tool is an MCP tool
McpServerName *string `json:"mcpServerName,omitempty"`
// Resolved intention summary describing what this specific call does
IntentionSummary *string `json:"intentionSummary,omitempty"`
}
A tool invocation request from the assistant
type AssistantMessageDataToolRequestsItemType ¶ added in v0.2.2
type AssistantMessageDataToolRequestsItemType string
Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent.
const ( AssistantMessageDataToolRequestsItemTypeFunction AssistantMessageDataToolRequestsItemType = "function" AssistantMessageDataToolRequestsItemTypeCustom AssistantMessageDataToolRequestsItemType = "custom" )
type AssistantMessageDeltaData ¶ added in v0.2.2
type AssistantMessageDeltaData struct {
// Message ID this delta belongs to, matching the corresponding assistant.message event
MessageID string `json:"messageId"`
// Incremental text chunk to append to the message content
DeltaContent string `json:"deltaContent"`
// Tool call ID of the parent tool invocation when this event originates from a sub-agent
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
}
Streaming assistant message delta for incremental response updates
type AssistantReasoningData ¶ added in v0.2.2
type AssistantReasoningData struct {
// Unique identifier for this reasoning block
ReasoningID string `json:"reasoningId"`
// The complete extended thinking text from the model
Content string `json:"content"`
}
Assistant reasoning content for timeline display with complete thinking text
type AssistantReasoningDeltaData ¶ added in v0.2.2
type AssistantReasoningDeltaData struct {
// Reasoning block ID this delta belongs to, matching the corresponding assistant.reasoning event
ReasoningID string `json:"reasoningId"`
// Incremental text chunk to append to the reasoning content
DeltaContent string `json:"deltaContent"`
}
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 {
// Identifier for this turn within the agentic loop, typically a stringified turn number
TurnID string `json:"turnId"`
// CAPI interaction ID for correlating this turn with upstream telemetry
InteractionID *string `json:"interactionId,omitempty"`
}
Turn initialization metadata including identifier and interaction tracking
type AssistantUsageData ¶ added in v0.2.2
type AssistantUsageData struct {
// Model identifier used for this API call
Model string `json:"model"`
// Number of input tokens consumed
InputTokens *float64 `json:"inputTokens,omitempty"`
// Number of output tokens produced
OutputTokens *float64 `json:"outputTokens,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"`
// Model multiplier cost for billing purposes
Cost *float64 `json:"cost,omitempty"`
// Duration of the API call in milliseconds
Duration *float64 `json:"duration,omitempty"`
// Time to first token in milliseconds. Only available for streaming requests
TtftMs *float64 `json:"ttftMs,omitempty"`
// Average inter-token latency in milliseconds. Only available for streaming requests
InterTokenLatencyMs *float64 `json:"interTokenLatencyMs,omitempty"`
// What initiated this API call (e.g., "sub-agent", "mcp-sampling"); absent for user-initiated calls
Initiator *string `json:"initiator,omitempty"`
// Completion ID from the model provider (e.g., chatcmpl-abc123)
APICallID *string `json:"apiCallId,omitempty"`
// GitHub request tracing ID (x-github-request-id header) for server-side log correlation
ProviderCallID *string `json:"providerCallId,omitempty"`
// Parent tool call ID when this usage originates from a sub-agent
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
// Per-quota resource usage snapshots, keyed by quota identifier
QuotaSnapshots map[string]AssistantUsageDataQuotaSnapshotsValue `json:"quotaSnapshots,omitempty"`
// Per-request cost and usage data from the CAPI copilot_usage response field
CopilotUsage *AssistantUsageDataCopilotUsage `json:"copilotUsage,omitempty"`
// Reasoning effort level used for model calls, if applicable (e.g. "low", "medium", "high", "xhigh")
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
}
LLM API call usage metrics including tokens, costs, quotas, and billing information
type AssistantUsageDataCopilotUsage ¶ added in v0.2.2
type AssistantUsageDataCopilotUsage struct {
// Itemized token usage breakdown
TokenDetails []AssistantUsageDataCopilotUsageTokenDetailsItem `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 AssistantUsageDataCopilotUsageTokenDetailsItem ¶ added in v0.2.2
type AssistantUsageDataCopilotUsageTokenDetailsItem 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 AssistantUsageDataQuotaSnapshotsValue ¶ added in v0.2.2
type AssistantUsageDataQuotaSnapshotsValue struct {
// Whether the user has an unlimited usage entitlement
IsUnlimitedEntitlement bool `json:"isUnlimitedEntitlement"`
// Total requests allowed by the entitlement
EntitlementRequests float64 `json:"entitlementRequests"`
// Number of requests already consumed
UsedRequests float64 `json:"usedRequests"`
// Whether usage is still permitted after quota exhaustion
UsageAllowedWithExhaustedQuota bool `json:"usageAllowedWithExhaustedQuota"`
// 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"`
}
type AttachmentType ¶ added in v0.1.15
type AttachmentType = UserMessageDataAttachmentsItemType
Type aliases for convenience.
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 *CapabilitiesChangedDataUI `json:"ui,omitempty"`
}
Session capability change notification
type CapabilitiesChangedDataUI ¶ added in v0.2.2
type CapabilitiesChangedDataUI 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
}
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 {
// Unique identifier; used to respond via session.commands.handlePendingCommand()
RequestID string `json:"requestId"`
// The full command text (e.g., /deploy production)
Command string `json:"command"`
// Command name without leading /
CommandName string `json:"commandName"`
// Raw argument string after the command name
Args string `json:"args"`
}
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 {
// Unique identifier for this request; used to respond via session.respondToQueuedCommand()
RequestID string `json:"requestId"`
// The slash command text to be executed (e.g., /help, /clear)
Command string `json:"command"`
}
Queued slash command dispatch request for client execution
type CommandsChangedData ¶ added in v0.2.2
type CommandsChangedData struct {
// Current list of registered SDK commands
Commands []CommandsChangedDataCommandsItem `json:"commands"`
}
SDK command registration change notification
type CommandsChangedDataCommandsItem ¶ added in v0.2.2
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"`
}
CustomAgentConfig configures a custom agent
type ElicitationCompletedData ¶ added in v0.2.2
type ElicitationCompletedData struct {
// Request ID of the resolved elicitation request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
// The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed)
Action *ElicitationCompletedDataAction `json:"action,omitempty"`
// The submitted form data when action is 'accept'; keys match the requested schema fields
Content map[string]any `json:"content,omitempty"`
}
Elicitation request completion with the user's response
type ElicitationCompletedDataAction ¶ added in v0.2.2
type ElicitationCompletedDataAction string
The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed)
const ( ElicitationCompletedDataActionAccept ElicitationCompletedDataAction = "accept" ElicitationCompletedDataActionDecline ElicitationCompletedDataAction = "decline" ElicitationCompletedDataActionCancel ElicitationCompletedDataAction = "cancel" )
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 {
// 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"`
// 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 *ElicitationRequestedDataMode `json:"mode,omitempty"`
// JSON Schema describing the form fields to present to the user (form mode only)
RequestedSchema *ElicitationRequestedDataRequestedSchema `json:"requestedSchema,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 ElicitationRequestedDataMode ¶ added in v0.2.2
type ElicitationRequestedDataMode string
Elicitation mode; "form" for structured input, "url" for browser-based. Defaults to "form" when absent.
const ( ElicitationRequestedDataModeForm ElicitationRequestedDataMode = "form" ElicitationRequestedDataModeURL ElicitationRequestedDataMode = "url" )
type ElicitationRequestedDataRequestedSchema ¶ added in v0.2.2
type ElicitationRequestedDataRequestedSchema struct {
// Schema type indicator (always 'object')
Type string `json:"type"`
// Form field definitions, keyed by field name
Properties map[string]any `json:"properties"`
// List of required field names
Required []string `json:"required,omitempty"`
}
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 {
// Request ID of the resolved exit plan mode request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
// Whether the plan was approved by the user
Approved *bool `json:"approved,omitempty"`
// Which action the user selected (e.g. 'autopilot', 'interactive', 'exit_only')
SelectedAction *string `json:"selectedAction,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"`
}
Plan mode exit completion with the user's approval decision and optional feedback
type ExitPlanModeRequestedData ¶ added in v0.2.2
type ExitPlanModeRequestedData struct {
// 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"`
// Full content of the plan file
PlanContent string `json:"planContent"`
// Available actions the user can take (e.g., approve, edit, reject)
Actions []string `json:"actions"`
// The recommended action for the user to take
RecommendedAction string `json:"recommendedAction"`
}
Plan approval request with plan content and available user actions
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 {
// 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"`
// Arguments to pass to the external tool
Arguments any `json:"arguments,omitempty"`
// 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 HookEndData ¶ added in v0.2.2
type HookEndData struct {
// 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"`
// Error details when the hook failed
Error *HookEndDataError `json:"error,omitempty"`
}
Hook invocation completion details including output, success status, and error information
type HookEndDataError ¶ added in v0.2.2
type HookEndDataError 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.LevelInfo] (default),
// [rpc.LevelWarning], and [rpc.LevelError].
Level rpc.Level
// 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
}
LogOptions configures optional parameters for Session.Log.
type MCPLocalServerConfig ¶
type MCPLocalServerConfig struct {
Tools []string `json:"tools"`
Type string `json:"type,omitempty"` // "local" or "stdio"
Timeout int `json:"timeout,omitempty"`
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env,omitempty"`
Cwd string `json:"cwd,omitempty"`
}
MCPLocalServerConfig configures a local/stdio MCP server
type MCPRemoteServerConfig ¶
type MCPRemoteServerConfig struct {
Tools []string `json:"tools"`
Type string `json:"type"` // "http" or "sse"
Timeout int `json:"timeout,omitempty"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitempty"`
}
MCPRemoteServerConfig configures a remote MCP server (HTTP or SSE)
type MCPServerConfig ¶
MCPServerConfig can be either MCPLocalServerConfig or MCPRemoteServerConfig Use a map[string]any for flexibility, or create separate configs
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 *McpOauthRequiredDataStaticClientConfig `json:"staticClientConfig,omitempty"`
}
OAuth authentication request for an MCP server
type McpOauthRequiredDataStaticClientConfig ¶ added in v0.2.2
type McpOauthRequiredDataStaticClientConfig 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 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
}
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 PermissionCompletedDataResult `json:"result"`
}
Permission request completion notification signaling UI dismissal
type PermissionCompletedDataResult ¶ added in v0.2.2
type PermissionCompletedDataResult struct {
// The outcome of the permission request
Kind PermissionCompletedDataResultKind `json:"kind"`
}
The result of the permission request
type PermissionCompletedDataResultKind ¶ added in v0.2.2
type PermissionCompletedDataResultKind string
The outcome of the permission request
const ( PermissionCompletedDataResultKindApproved PermissionCompletedDataResultKind = "approved" PermissionCompletedDataResultKindDeniedByRules PermissionCompletedDataResultKind = "denied-by-rules" PermissionCompletedDataResultKindDeniedNoApprovalRuleAndCouldNotRequestFromUser PermissionCompletedDataResultKind = "denied-no-approval-rule-and-could-not-request-from-user" PermissionCompletedDataResultKindDeniedInteractivelyByUser PermissionCompletedDataResultKind = "denied-interactively-by-user" PermissionCompletedDataResultKindDeniedByContentExclusionPolicy PermissionCompletedDataResultKind = "denied-by-content-exclusion-policy" PermissionCompletedDataResultKindDeniedByPermissionRequestHook PermissionCompletedDataResultKind = "denied-by-permission-request-hook" )
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 PermissionRequest ¶
type PermissionRequest = PermissionRequestedDataPermissionRequest
Type aliases for convenience.
type PermissionRequestCommand ¶ added in v0.2.0
type PermissionRequestCommand = PermissionRequestedDataPermissionRequestCommandsItem
Type aliases for convenience.
type PermissionRequestKind ¶ added in v0.1.31
type PermissionRequestKind = PermissionRequestedDataPermissionRequestKind
Type aliases for convenience.
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.
const ( // PermissionRequestResultKindApproved indicates the permission was approved. PermissionRequestResultKindApproved PermissionRequestResultKind = "approved" // PermissionRequestResultKindDeniedByRules indicates the permission was denied by rules. PermissionRequestResultKindDeniedByRules PermissionRequestResultKind = "denied-by-rules" // PermissionRequestResultKindDeniedCouldNotRequestFromUser indicates the permission was denied because // no approval rule was found and the user could not be prompted. PermissionRequestResultKindDeniedCouldNotRequestFromUser PermissionRequestResultKind = "denied-no-approval-rule-and-could-not-request-from-user" // PermissionRequestResultKindDeniedInteractivelyByUser indicates the permission was denied interactively by the user. PermissionRequestResultKindDeniedInteractivelyByUser PermissionRequestResultKind = "denied-interactively-by-user" // PermissionRequestResultKindNoResult indicates no permission decision was made. PermissionRequestResultKindNoResult PermissionRequestResultKind = "no-result" )
type PermissionRequestedData ¶ added in v0.2.2
type PermissionRequestedData struct {
// Unique identifier for this permission request; used to respond via session.respondToPermission()
RequestID string `json:"requestId"`
// Details of the permission being requested
PermissionRequest PermissionRequestedDataPermissionRequest `json:"permissionRequest"`
// 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 PermissionRequestedDataPermissionRequest ¶ added in v0.2.2
type PermissionRequestedDataPermissionRequest struct {
// Kind discriminator
Kind PermissionRequestedDataPermissionRequestKind `json:"kind"`
// Tool call ID that triggered this permission request
ToolCallID *string `json:"toolCallId,omitempty"`
// The complete shell command text to be executed
FullCommandText *string `json:"fullCommandText,omitempty"`
// Human-readable description of what the command intends to do
Intention *string `json:"intention,omitempty"`
// Parsed command identifiers found in the command text
Commands []PermissionRequestedDataPermissionRequestCommandsItem `json:"commands,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 []PermissionRequestedDataPermissionRequestPossibleUrlsItem `json:"possibleUrls,omitempty"`
// Whether the command includes a file write redirection (e.g., > or >>)
HasWriteFileRedirection *bool `json:"hasWriteFileRedirection,omitempty"`
// Whether the UI can offer session-wide approval for this command pattern
CanOfferSessionApproval *bool `json:"canOfferSessionApproval,omitempty"`
// Optional warning message about risks of running this command
Warning *string `json:"warning,omitempty"`
// Path of the file being written to
FileName *string `json:"fileName,omitempty"`
// Unified diff showing the proposed changes
Diff *string `json:"diff,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"`
// Name of the MCP server providing the tool
ServerName *string `json:"serverName,omitempty"`
// Internal name of the MCP tool
ToolName *string `json:"toolName,omitempty"`
// Human-readable title of the MCP tool
ToolTitle *string `json:"toolTitle,omitempty"`
// Arguments to pass to the MCP tool
Args any `json:"args,omitempty"`
// Whether this MCP tool is read-only (no side effects)
ReadOnly *bool `json:"readOnly,omitempty"`
// URL to be fetched
URL *string `json:"url,omitempty"`
// Topic or subject of the memory being stored
Subject *string `json:"subject,omitempty"`
// The fact or convention being stored
Fact *string `json:"fact,omitempty"`
// Source references for the stored fact
Citations *string `json:"citations,omitempty"`
// Description of what the custom tool does
ToolDescription *string `json:"toolDescription,omitempty"`
// Arguments of the tool call being gated
ToolArgs any `json:"toolArgs,omitempty"`
// Optional message from the hook explaining why confirmation is needed
HookMessage *string `json:"hookMessage,omitempty"`
}
Details of the permission being requested
type PermissionRequestedDataPermissionRequestCommandsItem ¶ added in v0.2.2
type PermissionRequestedDataPermissionRequestKind ¶ added in v0.2.2
type PermissionRequestedDataPermissionRequestKind string
Kind discriminator for PermissionRequestedDataPermissionRequest.
const ( PermissionRequestedDataPermissionRequestKindShell PermissionRequestedDataPermissionRequestKind = "shell" PermissionRequestedDataPermissionRequestKindWrite PermissionRequestedDataPermissionRequestKind = "write" PermissionRequestedDataPermissionRequestKindRead PermissionRequestedDataPermissionRequestKind = "read" PermissionRequestedDataPermissionRequestKindMcp PermissionRequestedDataPermissionRequestKind = "mcp" PermissionRequestedDataPermissionRequestKindURL PermissionRequestedDataPermissionRequestKind = "url" PermissionRequestedDataPermissionRequestKindMemory PermissionRequestedDataPermissionRequestKind = "memory" PermissionRequestedDataPermissionRequestKindCustomTool PermissionRequestedDataPermissionRequestKind = "custom-tool" PermissionRequestedDataPermissionRequestKindHook PermissionRequestedDataPermissionRequestKind = "hook" )
type PermissionRequestedDataPermissionRequestPossibleUrlsItem ¶ added in v0.2.2
type PermissionRequestedDataPermissionRequestPossibleUrlsItem struct {
// URL that may be accessed by the command
URL string `json:"url"`
}
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 PossibleURL ¶ added in v0.1.31
type PossibleURL = PermissionRequestedDataPermissionRequestPossibleUrlsItem
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"`
}
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
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// CustomAgents configures custom agents for the session
CustomAgents []CustomAgentConfig
// Agent is the name of the custom agent to activate when the session starts.
// Must match the Name of one of the agents in CustomAgents.
Agent string
// SkillDirectories is a list of directories to load skills from
SkillDirectories []string
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
InfiniteSessions *InfiniteSessionConfig
// DisableResume, when true, skips emitting the session.resume event.
// Useful for reconnecting to a session without triggering resume-related side effects.
DisableResume bool
// OnEvent is an optional event handler registered before the session.resume RPC
// is issued, ensuring early events are delivered. See SessionConfig.OnEvent.
OnEvent SessionEventHandler
// CreateSessionFsHandler supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFs is configured.
CreateSessionFsHandler func(session *Session) rpc.SessionFsHandler
// Commands registers slash-commands for this session. See SessionConfig.Commands.
Commands []CommandDefinition
// OnElicitationRequest is a handler for elicitation requests from the server.
// See SessionConfig.OnElicitationRequest.
OnElicitationRequest ElicitationHandler
}
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 {
// 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"`
// The JSON-RPC request ID from the MCP protocol
McpRequestID any `json:"mcpRequestId"`
}
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.LevelWarning})
// 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 {
// Whether compaction completed successfully
Success bool `json:"success"`
// Error message if compaction failed
Error *string `json:"error,omitempty"`
// Total tokens in conversation before compaction
PreCompactionTokens *float64 `json:"preCompactionTokens,omitempty"`
// Total tokens in conversation after compaction
PostCompactionTokens *float64 `json:"postCompactionTokens,omitempty"`
// Number of messages before compaction
PreCompactionMessagesLength *float64 `json:"preCompactionMessagesLength,omitempty"`
// Number of messages removed during compaction
MessagesRemoved *float64 `json:"messagesRemoved,omitempty"`
// Number of tokens removed during compaction
TokensRemoved *float64 `json:"tokensRemoved,omitempty"`
// LLM-generated summary of the compacted conversation history
SummaryContent *string `json:"summaryContent,omitempty"`
// 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
CompactionTokensUsed *SessionCompactionCompleteDataCompactionTokensUsed `json:"compactionTokensUsed,omitempty"`
// GitHub request tracing ID (x-github-request-id header) for the compaction LLM call
RequestID *string `json:"requestId,omitempty"`
// Token count from system message(s) after compaction
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Token count from non-system messages (user, assistant, tool) after compaction
ConversationTokens *float64 `json:"conversationTokens,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 SessionCompactionCompleteDataCompactionTokensUsed ¶ added in v0.2.2
type SessionCompactionCompleteDataCompactionTokensUsed struct {
// Input tokens consumed by the compaction LLM call
Input float64 `json:"input"`
// Output tokens produced by the compaction LLM call
Output float64 `json:"output"`
// Cached input tokens reused in the compaction LLM call
CachedInput float64 `json:"cachedInput"`
}
Token usage breakdown for the compaction LLM call
type SessionCompactionStartData ¶ added in v0.2.2
type SessionCompactionStartData struct {
// Token count from system message(s) at compaction start
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Token count from non-system messages (user, assistant, tool) at compaction start
ConversationTokens *float64 `json:"conversationTokens,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
// Provider configures a custom model provider (BYOK)
Provider *ProviderConfig
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// CustomAgents configures custom agents for the session
CustomAgents []CustomAgentConfig
// Agent is the name of the custom agent to activate when the session starts.
// Must match the Name of one of the agents in CustomAgents.
Agent string
// SkillDirectories is a list of directories to load skills from
SkillDirectories []string
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
// When enabled (default), sessions automatically manage context limits and persist state.
InfiniteSessions *InfiniteSessionConfig
// OnEvent is an optional event handler that is registered on the session before
// the session.create RPC is issued. This guarantees that early events emitted
// by the CLI during session creation (e.g. session.start) are delivered to the
// handler. Equivalent to calling session.On(handler) immediately after creation,
// but executes earlier in the lifecycle so no events are missed.
OnEvent SessionEventHandler
// CreateSessionFsHandler supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFs is configured.
CreateSessionFsHandler func(session *Session) rpc.SessionFsHandler
// Commands registers slash-commands for this session. Each command appears as
// /name in the CLI TUI for the user to invoke. The Handler is called when the
// command is executed.
Commands []CommandDefinition
// OnElicitationRequest is a handler for elicitation requests from the server.
// When provided, the server may call back to this client for form-based UI dialogs
// (e.g. from MCP tools). Also enables the elicitation capability on the session.
OnElicitationRequest ElicitationHandler
}
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 {
// Current working directory path
Cwd string `json:"cwd"`
// Root directory of the git repository, resolved via git rev-parse
GitRoot *string `json:"gitRoot,omitempty"`
// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps)
Repository *string `json:"repository,omitempty"`
// Hosting platform type of the repository (github or ado)
HostType *SessionStartDataContextHostType `json:"hostType,omitempty"`
// Current git branch name
Branch *string `json:"branch,omitempty"`
// Head commit of current git branch at session start time
HeadCommit *string `json:"headCommit,omitempty"`
// Base commit of current git branch at session start time
BaseCommit *string `json:"baseCommit,omitempty"`
}
Updated working directory and git context after the change
type SessionCustomAgentsUpdatedData ¶ added in v0.2.2
type SessionCustomAgentsUpdatedData struct {
// Array of loaded custom agent metadata
Agents []SessionCustomAgentsUpdatedDataAgentsItem `json:"agents"`
// Non-fatal warnings from agent loading
Warnings []string `json:"warnings"`
// Fatal errors from agent loading
Errors []string `json:"errors"`
}
SessionCustomAgentsUpdatedData holds the payload for session.custom_agents_updated events.
type SessionCustomAgentsUpdatedDataAgentsItem ¶ added in v0.2.2
type SessionCustomAgentsUpdatedDataAgentsItem struct {
// Unique identifier for the agent
ID string `json:"id"`
// Internal name of the agent
Name string `json:"name"`
// Human-readable display name
DisplayName string `json:"displayName"`
// Description of what the agent does
Description string `json:"description"`
// 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"`
// Model override for this agent, if set
Model *string `json:"model,omitempty"`
}
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"`
// Error stack trace, when available
Stack *string `json:"stack,omitempty"`
// HTTP status code from the upstream request, if applicable
StatusCode *int64 `json:"statusCode,omitempty"`
// GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs
ProviderCallID *string `json:"providerCallId,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" 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 []SessionExtensionsLoadedDataExtensionsItem `json:"extensions"`
}
SessionExtensionsLoadedData holds the payload for session.extensions_loaded events.
type SessionExtensionsLoadedDataExtensionsItem ¶ added in v0.2.2
type SessionExtensionsLoadedDataExtensionsItem 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 SessionExtensionsLoadedDataExtensionsItemSource `json:"source"`
// Current status: running, disabled, failed, or starting
Status SessionExtensionsLoadedDataExtensionsItemStatus `json:"status"`
}
type SessionExtensionsLoadedDataExtensionsItemSource ¶ added in v0.2.2
type SessionExtensionsLoadedDataExtensionsItemSource string
Discovery source
const ( SessionExtensionsLoadedDataExtensionsItemSourceProject SessionExtensionsLoadedDataExtensionsItemSource = "project" SessionExtensionsLoadedDataExtensionsItemSourceUser SessionExtensionsLoadedDataExtensionsItemSource = "user" )
type SessionExtensionsLoadedDataExtensionsItemStatus ¶ added in v0.2.2
type SessionExtensionsLoadedDataExtensionsItemStatus string
Current status: running, disabled, failed, or starting
const ( SessionExtensionsLoadedDataExtensionsItemStatusRunning SessionExtensionsLoadedDataExtensionsItemStatus = "running" SessionExtensionsLoadedDataExtensionsItemStatusDisabled SessionExtensionsLoadedDataExtensionsItemStatus = "disabled" SessionExtensionsLoadedDataExtensionsItemStatusFailed SessionExtensionsLoadedDataExtensionsItemStatus = "failed" SessionExtensionsLoadedDataExtensionsItemStatusStarting SessionExtensionsLoadedDataExtensionsItemStatus = "starting" )
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.Conventions
}
SessionFsConfig configures a custom session filesystem provider.
type SessionHandoffData ¶ added in v0.2.2
type SessionHandoffData struct {
// ISO 8601 timestamp when the handoff occurred
HandoffTime time.Time `json:"handoffTime"`
// Origin type of the session being handed off
SourceType SessionHandoffDataSourceType `json:"sourceType"`
// Repository context for the handed-off session
Repository *SessionHandoffDataRepository `json:"repository,omitempty"`
// Additional context information for the handoff
Context *string `json:"context,omitempty"`
// Summary of the work done in the source session
Summary *string `json:"summary,omitempty"`
// Session ID of the remote session being handed off
RemoteSessionID *string `json:"remoteSessionId,omitempty"`
// GitHub host URL for the source session (e.g., https://github.com or https://tenant.ghe.com)
Host *string `json:"host,omitempty"`
}
Session handoff metadata including source, context, and repository information
type SessionHandoffDataRepository ¶ added in v0.2.2
type SessionHandoffDataRepository struct {
// Repository owner (user or organization)
Owner string `json:"owner"`
// Repository name
Name string `json:"name"`
// Git branch name, if applicable
Branch *string `json:"branch,omitempty"`
}
Repository context for the handed-off session
type SessionHandoffDataSourceType ¶ added in v0.2.2
type SessionHandoffDataSourceType string
Origin type of the session being handed off
const ( SessionHandoffDataSourceTypeRemote SessionHandoffDataSourceType = "remote" SessionHandoffDataSourceTypeLocal SessionHandoffDataSourceType = "local" )
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 SessionMcpServersLoadedDataServersItemStatus `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 []SessionMcpServersLoadedDataServersItem `json:"servers"`
}
SessionMcpServersLoadedData holds the payload for session.mcp_servers_loaded events.
type SessionMcpServersLoadedDataServersItem ¶ added in v0.2.2
type SessionMcpServersLoadedDataServersItem struct {
// Server name (config key)
Name string `json:"name"`
// Connection status: connected, failed, needs-auth, pending, disabled, or not_configured
Status SessionMcpServersLoadedDataServersItemStatus `json:"status"`
// Configuration source: user, workspace, plugin, or builtin
Source *string `json:"source,omitempty"`
// Error message if the server failed to connect
Error *string `json:"error,omitempty"`
}
type SessionMcpServersLoadedDataServersItemStatus ¶ added in v0.2.2
type SessionMcpServersLoadedDataServersItemStatus string
Connection status: connected, failed, needs-auth, pending, disabled, or not_configured
const ( SessionMcpServersLoadedDataServersItemStatusConnected SessionMcpServersLoadedDataServersItemStatus = "connected" SessionMcpServersLoadedDataServersItemStatusFailed SessionMcpServersLoadedDataServersItemStatus = "failed" SessionMcpServersLoadedDataServersItemStatusNeedsAuth SessionMcpServersLoadedDataServersItemStatus = "needs-auth" SessionMcpServersLoadedDataServersItemStatusPending SessionMcpServersLoadedDataServersItemStatus = "pending" SessionMcpServersLoadedDataServersItemStatusDisabled SessionMcpServersLoadedDataServersItemStatus = "disabled" SessionMcpServersLoadedDataServersItemStatusNotConfigured SessionMcpServersLoadedDataServersItemStatus = "not_configured" )
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 before the change (e.g., "interactive", "plan", "autopilot")
PreviousMode string `json:"previousMode"`
// Agent mode after the change (e.g., "interactive", "plan", "autopilot")
NewMode string `json:"newMode"`
}
Agent mode change details including previous and new modes
type SessionModelChangeData ¶ added in v0.2.2
type SessionModelChangeData struct {
// Model that was previously selected, if any
PreviousModel *string `json:"previousModel,omitempty"`
// Newly selected model identifier
NewModel string `json:"newModel"`
// 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 SessionPlanChangedDataOperation `json:"operation"`
}
Plan file operation details indicating what changed
type SessionPlanChangedDataOperation ¶ added in v0.2.2
type SessionPlanChangedDataOperation string
The type of operation performed on the plan file
const ( SessionPlanChangedDataOperationCreate SessionPlanChangedDataOperation = "create" SessionPlanChangedDataOperationUpdate SessionPlanChangedDataOperation = "update" SessionPlanChangedDataOperationDelete SessionPlanChangedDataOperation = "delete" )
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 {
// ISO 8601 timestamp when the session was resumed
ResumeTime time.Time `json:"resumeTime"`
// Total number of persisted events in the session at the time of resume
EventCount float64 `json:"eventCount"`
// Model currently selected at resume time
SelectedModel *string `json:"selectedModel,omitempty"`
// Reasoning effort level used for model calls, if applicable (e.g. "low", "medium", "high", "xhigh")
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
// Updated working directory and git context at resume time
Context *SessionResumeDataContext `json:"context,omitempty"`
// Whether the session was already in use by another client at resume time
AlreadyInUse *bool `json:"alreadyInUse,omitempty"`
// Whether this session supports remote steering via Mission Control
RemoteSteerable *bool `json:"remoteSteerable,omitempty"`
}
Session resume metadata including current context and event count
type SessionResumeDataContext ¶ added in v0.2.2
type SessionResumeDataContext struct {
// Current working directory path
Cwd string `json:"cwd"`
// Root directory of the git repository, resolved via git rev-parse
GitRoot *string `json:"gitRoot,omitempty"`
// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps)
Repository *string `json:"repository,omitempty"`
// Hosting platform type of the repository (github or ado)
HostType *SessionStartDataContextHostType `json:"hostType,omitempty"`
// Current git branch name
Branch *string `json:"branch,omitempty"`
// Head commit of current git branch at session start time
HeadCommit *string `json:"headCommit,omitempty"`
// Base commit of current git branch at session start time
BaseCommit *string `json:"baseCommit,omitempty"`
}
Updated working directory and git context at resume time
type SessionShutdownData ¶ added in v0.2.2
type SessionShutdownData struct {
// Whether the session ended normally ("routine") or due to a crash/fatal error ("error")
ShutdownType SessionShutdownDataShutdownType `json:"shutdownType"`
// Error description when shutdownType is "error"
ErrorReason *string `json:"errorReason,omitempty"`
// Total number of premium API requests used during the session
TotalPremiumRequests float64 `json:"totalPremiumRequests"`
// Cumulative time spent in API calls during the session, in milliseconds
TotalAPIDurationMs float64 `json:"totalApiDurationMs"`
// Unix timestamp (milliseconds) when the session started
SessionStartTime float64 `json:"sessionStartTime"`
// Aggregate code change metrics for the session
CodeChanges SessionShutdownDataCodeChanges `json:"codeChanges"`
// Per-model usage breakdown, keyed by model identifier
ModelMetrics map[string]SessionShutdownDataModelMetricsValue `json:"modelMetrics"`
// 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"`
// System message token count at shutdown
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Non-system message token count at shutdown
ConversationTokens *float64 `json:"conversationTokens,omitempty"`
// Tool definitions token count at shutdown
ToolDefinitionsTokens *float64 `json:"toolDefinitionsTokens,omitempty"`
}
Session termination metrics including usage statistics, code changes, and shutdown reason
type SessionShutdownDataCodeChanges ¶ added in v0.2.2
type SessionShutdownDataCodeChanges struct {
// Total number of lines added during the session
LinesAdded float64 `json:"linesAdded"`
// Total number of lines removed during the session
LinesRemoved float64 `json:"linesRemoved"`
// List of file paths that were modified during the session
FilesModified []string `json:"filesModified"`
}
Aggregate code change metrics for the session
type SessionShutdownDataModelMetricsValue ¶ added in v0.2.2
type SessionShutdownDataModelMetricsValue struct {
// Request count and cost metrics
Requests SessionShutdownDataModelMetricsValueRequests `json:"requests"`
// Token usage breakdown
Usage SessionShutdownDataModelMetricsValueUsage `json:"usage"`
}
type SessionShutdownDataModelMetricsValueRequests ¶ added in v0.2.2
type SessionShutdownDataModelMetricsValueRequests struct {
// Total number of API requests made to this model
Count float64 `json:"count"`
// Cumulative cost multiplier for requests to this model
Cost float64 `json:"cost"`
}
Request count and cost metrics
type SessionShutdownDataModelMetricsValueUsage ¶ added in v0.2.2
type SessionShutdownDataModelMetricsValueUsage struct {
// 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 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"`
}
Token usage breakdown
type SessionShutdownDataShutdownType ¶ added in v0.2.2
type SessionShutdownDataShutdownType string
Whether the session ended normally ("routine") or due to a crash/fatal error ("error")
const ( SessionShutdownDataShutdownTypeRoutine SessionShutdownDataShutdownType = "routine" SessionShutdownDataShutdownTypeError SessionShutdownDataShutdownType = "error" )
type SessionSkillsLoadedData ¶ added in v0.2.2
type SessionSkillsLoadedData struct {
// Array of resolved skill metadata
Skills []SessionSkillsLoadedDataSkillsItem `json:"skills"`
}
SessionSkillsLoadedData holds the payload for session.skills_loaded events.
type SessionSkillsLoadedDataSkillsItem ¶ added in v0.2.2
type SessionSkillsLoadedDataSkillsItem struct {
// Unique identifier for the skill
Name string `json:"name"`
// Description of what the skill does
Description string `json:"description"`
// 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"`
// Whether the skill is currently enabled
Enabled bool `json:"enabled"`
// Absolute path to the skill file, if available
Path *string `json:"path,omitempty"`
}
type SessionSnapshotRewindData ¶ added in v0.2.2
type SessionSnapshotRewindData struct {
// Event ID that was rewound to; this event and all after it were removed
UpToEventID string `json:"upToEventId"`
// Number of events that were removed by the rewind
EventsRemoved float64 `json:"eventsRemoved"`
}
Session rewind details including target event and count of removed events
type SessionStartData ¶ added in v0.2.2
type SessionStartData struct {
// Unique identifier for the session
SessionID string `json:"sessionId"`
// Schema version number for the session event format
Version float64 `json:"version"`
// Identifier of the software producing the events (e.g., "copilot-agent")
Producer string `json:"producer"`
// Version string of the Copilot application
CopilotVersion string `json:"copilotVersion"`
// ISO 8601 timestamp when the session was created
StartTime time.Time `json:"startTime"`
// Model selected at session creation time, if any
SelectedModel *string `json:"selectedModel,omitempty"`
// Reasoning effort level used for model calls, if applicable (e.g. "low", "medium", "high", "xhigh")
ReasoningEffort *string `json:"reasoningEffort,omitempty"`
// Working directory and git context at session start
Context *SessionStartDataContext `json:"context,omitempty"`
// Whether the session was already in use by another client at start time
AlreadyInUse *bool `json:"alreadyInUse,omitempty"`
// Whether this session supports remote steering via Mission Control
RemoteSteerable *bool `json:"remoteSteerable,omitempty"`
}
Session initialization metadata including context and configuration
type SessionStartDataContext ¶ added in v0.2.2
type SessionStartDataContext struct {
// Current working directory path
Cwd string `json:"cwd"`
// Root directory of the git repository, resolved via git rev-parse
GitRoot *string `json:"gitRoot,omitempty"`
// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps)
Repository *string `json:"repository,omitempty"`
// Hosting platform type of the repository (github or ado)
HostType *SessionStartDataContextHostType `json:"hostType,omitempty"`
// Current git branch name
Branch *string `json:"branch,omitempty"`
// Head commit of current git branch at session start time
HeadCommit *string `json:"headCommit,omitempty"`
// Base commit of current git branch at session start time
BaseCommit *string `json:"baseCommit,omitempty"`
}
Working directory and git context at session start
type SessionStartDataContextHostType ¶ added in v0.2.2
type SessionStartDataContextHostType string
Hosting platform type of the repository (github or ado)
const ( SessionStartDataContextHostTypeGithub SessionStartDataContextHostType = "github" SessionStartDataContextHostTypeAdo SessionStartDataContextHostType = "ado" )
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 {
// Summary of the completed task, provided by the agent
Summary *string `json:"summary,omitempty"`
// Whether the tool call succeeded. False when validation failed (e.g., invalid arguments)
Success *bool `json:"success,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 {
// Maximum token count for the model's context window
TokenLimit float64 `json:"tokenLimit"`
// Total tokens in conversation messages before truncation
PreTruncationTokensInMessages float64 `json:"preTruncationTokensInMessages"`
// Number of conversation messages before truncation
PreTruncationMessagesLength float64 `json:"preTruncationMessagesLength"`
// Total tokens in conversation messages after truncation
PostTruncationTokensInMessages float64 `json:"postTruncationTokensInMessages"`
// Number of conversation messages after truncation
PostTruncationMessagesLength float64 `json:"postTruncationMessagesLength"`
// Number of tokens removed by truncation
TokensRemovedDuringTruncation float64 `json:"tokensRemovedDuringTruncation"`
// Number of messages removed by truncation
MessagesRemovedDuringTruncation float64 `json:"messagesRemovedDuringTruncation"`
// Identifier of the component that performed truncation (e.g., "BasicTruncator")
PerformedBy string `json:"performedBy"`
}
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.RequestedSchema) (*ElicitationResult, error)
Elicitation shows a generic elicitation dialog with a custom schema.
type SessionUsageInfoData ¶ added in v0.2.2
type SessionUsageInfoData struct {
// Maximum token count for the model's context window
TokenLimit float64 `json:"tokenLimit"`
// Current number of tokens in the context window
CurrentTokens float64 `json:"currentTokens"`
// Current number of messages in the conversation
MessagesLength float64 `json:"messagesLength"`
// Token count from system message(s)
SystemTokens *float64 `json:"systemTokens,omitempty"`
// Token count from non-system messages (user, assistant, tool)
ConversationTokens *float64 `json:"conversationTokens,omitempty"`
// Token count from tool definitions
ToolDefinitionsTokens *float64 `json:"toolDefinitionsTokens,omitempty"`
// Whether this is the first usage_info event emitted in this session
IsInitial *bool `json:"isInitial,omitempty"`
}
Current context window usage statistics including token and message counts
type SessionWarningData ¶ added in v0.2.2
type SessionWarningData struct {
// Category of warning (e.g., "subscription", "policy", "mcp")
WarningType string `json:"warningType"`
// 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"`
}
Warning message for timeline display with categorization
type SessionWorkspaceFileChangedData ¶ added in v0.2.2
type SessionWorkspaceFileChangedData struct {
// Relative path within the session workspace files directory
Path string `json:"path"`
// Whether the file was newly created or updated
Operation SessionWorkspaceFileChangedDataOperation `json:"operation"`
}
Workspace file change details including path and operation type
type SessionWorkspaceFileChangedDataOperation ¶ added in v0.2.2
type SessionWorkspaceFileChangedDataOperation string
Whether the file was newly created or updated
const ( SessionWorkspaceFileChangedDataOperationCreate SessionWorkspaceFileChangedDataOperation = "create" SessionWorkspaceFileChangedDataOperationUpdate SessionWorkspaceFileChangedDataOperation = "update" )
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 SkillInvokedData ¶ added in v0.2.2
type SkillInvokedData struct {
// Name of the invoked skill
Name string `json:"name"`
// File path to the SKILL.md definition
Path string `json:"path"`
// Full content of the skill file, injected into the conversation for the model
Content string `json:"content"`
// Tool names that should be auto-approved when this skill is active
AllowedTools []string `json:"allowedTools,omitempty"`
// 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"`
// Description of the skill from its SKILL.md frontmatter
Description *string `json:"description,omitempty"`
}
Skill invocation details including content, allowed tools, and plugin metadata
type SubagentCompletedData ¶ added in v0.2.2
type SubagentCompletedData struct {
// Tool call ID of the parent tool invocation that spawned this sub-agent
ToolCallID string `json:"toolCallId"`
// Internal name of the sub-agent
AgentName string `json:"agentName"`
// Human-readable display name of the sub-agent
AgentDisplayName string `json:"agentDisplayName"`
// Model used by the sub-agent
Model *string `json:"model,omitempty"`
// Total number of tool calls made by the sub-agent
TotalToolCalls *float64 `json:"totalToolCalls,omitempty"`
// Total tokens (input + output) consumed by the sub-agent
TotalTokens *float64 `json:"totalTokens,omitempty"`
// Wall-clock duration of the sub-agent execution in milliseconds
DurationMs *float64 `json:"durationMs,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 {
// Tool call ID of the parent tool invocation that spawned this sub-agent
ToolCallID string `json:"toolCallId"`
// Internal name of the sub-agent
AgentName string `json:"agentName"`
// Human-readable display name of the sub-agent
AgentDisplayName string `json:"agentDisplayName"`
// 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"`
// Total number of tool calls made before the sub-agent failed
TotalToolCalls *float64 `json:"totalToolCalls,omitempty"`
// Total tokens (input + output) consumed before the sub-agent failed
TotalTokens *float64 `json:"totalTokens,omitempty"`
// Wall-clock duration of the sub-agent execution in milliseconds
DurationMs *float64 `json:"durationMs,omitempty"`
}
Sub-agent failure details including error message and agent information
type SubagentSelectedData ¶ added in v0.2.2
type SubagentSelectedData struct {
// Internal name of the selected custom agent
AgentName string `json:"agentName"`
// Human-readable display name of the selected custom agent
AgentDisplayName string `json:"agentDisplayName"`
// 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 {
// Tool call ID of the parent tool invocation that spawned this sub-agent
ToolCallID string `json:"toolCallId"`
// Internal name of the sub-agent
AgentName string `json:"agentName"`
// Human-readable display name of the sub-agent
AgentDisplayName string `json:"agentDisplayName"`
// Description of what the sub-agent does
AgentDescription string `json:"agentDescription"`
}
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
Content string `json:"content"`
// Message role: "system" for system prompts, "developer" for developer-injected instructions
Role SystemMessageDataRole `json:"role"`
// Optional name identifier for the message source
Name *string `json:"name,omitempty"`
// Metadata about the prompt template and its construction
Metadata *SystemMessageDataMetadata `json:"metadata,omitempty"`
}
System or developer message content with role and optional template metadata
type SystemMessageDataMetadata ¶ added in v0.2.2
type SystemMessageDataMetadata 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 SystemMessageDataRole ¶ added in v0.2.2
type SystemMessageDataRole string
Message role: "system" for system prompts, "developer" for developer-injected instructions
const ( SystemMessageDataRoleSystem SystemMessageDataRole = "system" SystemMessageDataRoleDeveloper SystemMessageDataRole = "developer" )
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 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 SystemNotificationDataKind `json:"kind"`
}
System-generated notification for runtime events like background task completion
type SystemNotificationDataKind ¶ added in v0.2.2
type SystemNotificationDataKind struct {
// Type discriminator
Type SystemNotificationDataKindType `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"`
// Whether the agent completed successfully or failed
Status *SystemNotificationDataKindStatus `json:"status,omitempty"`
// Human-readable description of the agent task
Description *string `json:"description,omitempty"`
// The full prompt given to the background agent
Prompt *string `json:"prompt,omitempty"`
// Unique identifier of the shell session
ShellID *string `json:"shellId,omitempty"`
// Exit code of the shell command, if available
ExitCode *float64 `json:"exitCode,omitempty"`
}
Structured metadata identifying what triggered this notification
type SystemNotificationDataKindStatus ¶ added in v0.2.2
type SystemNotificationDataKindStatus string
Whether the agent completed successfully or failed
const ( SystemNotificationDataKindStatusCompleted SystemNotificationDataKindStatus = "completed" SystemNotificationDataKindStatusFailed SystemNotificationDataKindStatus = "failed" )
type SystemNotificationDataKindType ¶ added in v0.2.2
type SystemNotificationDataKindType string
Type discriminator for SystemNotificationDataKind.
const ( SystemNotificationDataKindTypeAgentCompleted SystemNotificationDataKindType = "agent_completed" SystemNotificationDataKindTypeAgentIdle SystemNotificationDataKindType = "agent_idle" SystemNotificationDataKindTypeShellCompleted SystemNotificationDataKindType = "shell_completed" SystemNotificationDataKindTypeShellDetachedCompleted SystemNotificationDataKindType = "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 ToolExecutionCompleteData ¶ added in v0.2.2
type ToolExecutionCompleteData struct {
// Unique identifier for the completed tool call
ToolCallID string `json:"toolCallId"`
// Whether the tool execution completed successfully
Success bool `json:"success"`
// Model identifier that generated this tool call
Model *string `json:"model,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"`
// Tool execution result on success
Result *ToolExecutionCompleteDataResult `json:"result,omitempty"`
// Error details when the tool execution failed
Error *ToolExecutionCompleteDataError `json:"error,omitempty"`
// Tool-specific telemetry data (e.g., CodeQL check counts, grep match counts)
ToolTelemetry map[string]any `json:"toolTelemetry,omitempty"`
// Tool call ID of the parent tool invocation when this event originates from a sub-agent
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
}
Tool execution completion results including success status, detailed output, and error information
type ToolExecutionCompleteDataError ¶ added in v0.2.2
type ToolExecutionCompleteDataError struct {
// Human-readable error message
Message string `json:"message"`
// Machine-readable error code
Code *string `json:"code,omitempty"`
}
Error details when the tool execution failed
type ToolExecutionCompleteDataResult ¶ added in v0.2.2
type ToolExecutionCompleteDataResult struct {
// Concise tool result text sent to the LLM for chat completion, potentially truncated for token efficiency
Content string `json:"content"`
// 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"`
// Structured content blocks (text, images, audio, resources) returned by the tool in their native format
Contents []ToolExecutionCompleteDataResultContentsItem `json:"contents,omitempty"`
}
Tool execution result on success
type ToolExecutionCompleteDataResultContentsItem ¶ added in v0.2.2
type ToolExecutionCompleteDataResultContentsItem struct {
// Type discriminator
Type ToolExecutionCompleteDataResultContentsItemType `json:"type"`
// The text content
Text *string `json:"text,omitempty"`
// Process exit code, if the command has completed
ExitCode *float64 `json:"exitCode,omitempty"`
// Working directory where the command was executed
Cwd *string `json:"cwd,omitempty"`
// Base64-encoded image data
Data *string `json:"data,omitempty"`
// MIME type of the image (e.g., image/png, image/jpeg)
MIMEType *string `json:"mimeType,omitempty"`
// Icons associated with this resource
Icons []ToolExecutionCompleteDataResultContentsItemIconsItem `json:"icons,omitempty"`
// Resource name identifier
Name *string `json:"name,omitempty"`
// Human-readable display title for the resource
Title *string `json:"title,omitempty"`
// URI identifying the resource
URI *string `json:"uri,omitempty"`
// Human-readable description of the resource
Description *string `json:"description,omitempty"`
// Size of the resource in bytes
Size *float64 `json:"size,omitempty"`
// The embedded resource contents, either text or base64-encoded binary
Resource any `json:"resource,omitempty"`
}
A content block within a tool result, which may be text, terminal output, image, audio, or a resource
type ToolExecutionCompleteDataResultContentsItemIconsItem ¶ added in v0.2.2
type ToolExecutionCompleteDataResultContentsItemIconsItem struct {
// URL or path to the icon image
Src string `json:"src"`
// MIME type of the icon image
MIMEType *string `json:"mimeType,omitempty"`
// Available icon sizes (e.g., ['16x16', '32x32'])
Sizes []string `json:"sizes,omitempty"`
// Theme variant this icon is intended for
Theme *ToolExecutionCompleteDataResultContentsItemIconsItemTheme `json:"theme,omitempty"`
}
Icon image for a resource
type ToolExecutionCompleteDataResultContentsItemIconsItemTheme ¶ added in v0.2.2
type ToolExecutionCompleteDataResultContentsItemIconsItemTheme string
Theme variant this icon is intended for
const ( ToolExecutionCompleteDataResultContentsItemIconsItemThemeLight ToolExecutionCompleteDataResultContentsItemIconsItemTheme = "light" ToolExecutionCompleteDataResultContentsItemIconsItemThemeDark ToolExecutionCompleteDataResultContentsItemIconsItemTheme = "dark" )
type ToolExecutionCompleteDataResultContentsItemType ¶ added in v0.2.2
type ToolExecutionCompleteDataResultContentsItemType string
Type discriminator for ToolExecutionCompleteDataResultContentsItem.
const ( ToolExecutionCompleteDataResultContentsItemTypeText ToolExecutionCompleteDataResultContentsItemType = "text" ToolExecutionCompleteDataResultContentsItemTypeTerminal ToolExecutionCompleteDataResultContentsItemType = "terminal" ToolExecutionCompleteDataResultContentsItemTypeImage ToolExecutionCompleteDataResultContentsItemType = "image" ToolExecutionCompleteDataResultContentsItemTypeAudio ToolExecutionCompleteDataResultContentsItemType = "audio" ToolExecutionCompleteDataResultContentsItemTypeResourceLink ToolExecutionCompleteDataResultContentsItemType = "resource_link" ToolExecutionCompleteDataResultContentsItemTypeResource ToolExecutionCompleteDataResultContentsItemType = "resource" )
type ToolExecutionPartialResultData ¶ added in v0.2.2
type ToolExecutionPartialResultData struct {
// Tool call ID this partial result belongs to
ToolCallID string `json:"toolCallId"`
// Incremental output chunk from the running tool
PartialOutput string `json:"partialOutput"`
}
Streaming tool execution output for incremental result display
type ToolExecutionProgressData ¶ added in v0.2.2
type ToolExecutionProgressData struct {
// Tool call ID this progress notification belongs to
ToolCallID string `json:"toolCallId"`
// Human-readable progress status message (e.g., from an MCP server)
ProgressMessage string `json:"progressMessage"`
}
Tool execution progress notification with status message
type ToolExecutionStartData ¶ added in v0.2.2
type ToolExecutionStartData struct {
// Unique identifier for this tool call
ToolCallID string `json:"toolCallId"`
// Name of the tool being executed
ToolName string `json:"toolName"`
// 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
ParentToolCallID *string `json:"parentToolCallId,omitempty"`
}
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.
type ToolUserRequestedData ¶ added in v0.2.2
type ToolUserRequestedData struct {
// Unique identifier for this tool call
ToolCallID string `json:"toolCallId"`
// Name of the tool the user wants to invoke
ToolName string `json:"toolName"`
// Arguments for the tool invocation
Arguments any `json:"arguments,omitempty"`
}
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 {
// Request ID of the resolved user input request; clients should dismiss any UI for this request
RequestID string `json:"requestId"`
// The user's answer to the input request
Answer *string `json:"answer,omitempty"`
// 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 {
// Unique identifier for this input request; used to respond via session.respondToUserInput()
RequestID string `json:"requestId"`
// The question or prompt to present to the user
Question string `json:"question"`
// Predefined choices for the user to select from, if applicable
Choices []string `json:"choices,omitempty"`
// Whether the user can provide a free-form text response in addition to predefined choices
AllowFreeform *bool `json:"allowFreeform,omitempty"`
// 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 UserMessageData ¶ added in v0.2.2
type UserMessageData struct {
// The user's message text as displayed in the timeline
Content string `json:"content"`
// Transformed version of the message sent to the model, with XML wrapping, timestamps, and other augmentations for prompt caching
TransformedContent *string `json:"transformedContent,omitempty"`
// Files, selections, or GitHub references attached to the message
Attachments []UserMessageDataAttachmentsItem `json:"attachments,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"`
// The agent mode that was active when this message was sent
AgentMode *UserMessageDataAgentMode `json:"agentMode,omitempty"`
// CAPI interaction ID for correlating this user message with its turn
InteractionID *string `json:"interactionId,omitempty"`
}
UserMessageData holds the payload for user.message events.
type UserMessageDataAgentMode ¶ added in v0.2.2
type UserMessageDataAgentMode string
The agent mode that was active when this message was sent
const ( UserMessageDataAgentModeInteractive UserMessageDataAgentMode = "interactive" UserMessageDataAgentModePlan UserMessageDataAgentMode = "plan" UserMessageDataAgentModeAutopilot UserMessageDataAgentMode = "autopilot" UserMessageDataAgentModeShell UserMessageDataAgentMode = "shell" )
type UserMessageDataAttachmentsItem ¶ added in v0.2.2
type UserMessageDataAttachmentsItem struct {
// Type discriminator
Type UserMessageDataAttachmentsItemType `json:"type"`
// Absolute file path
Path *string `json:"path,omitempty"`
// User-facing display name for the attachment
DisplayName *string `json:"displayName,omitempty"`
// Optional line range to scope the attachment to a specific section of the file
LineRange *UserMessageDataAttachmentsItemLineRange `json:"lineRange,omitempty"`
// Absolute path to the file containing the selection
FilePath *string `json:"filePath,omitempty"`
// The selected text content
Text *string `json:"text,omitempty"`
// Position range of the selection within the file
Selection *UserMessageDataAttachmentsItemSelection `json:"selection,omitempty"`
// Issue, pull request, or discussion number
Number *float64 `json:"number,omitempty"`
// Title of the referenced item
Title *string `json:"title,omitempty"`
// Type of GitHub reference
ReferenceType *UserMessageDataAttachmentsItemReferenceType `json:"referenceType,omitempty"`
// Current state of the referenced item (e.g., open, closed, merged)
State *string `json:"state,omitempty"`
// URL to the referenced item on GitHub
URL *string `json:"url,omitempty"`
// Base64-encoded content
Data *string `json:"data,omitempty"`
// MIME type of the inline data
MIMEType *string `json:"mimeType,omitempty"`
}
A user message attachment — a file, directory, code selection, blob, or GitHub reference
type UserMessageDataAttachmentsItemLineRange ¶ added in v0.2.2
type UserMessageDataAttachmentsItemLineRange struct {
// Start line number (1-based)
Start float64 `json:"start"`
// End line number (1-based, inclusive)
End float64 `json:"end"`
}
Optional line range to scope the attachment to a specific section of the file
type UserMessageDataAttachmentsItemReferenceType ¶ added in v0.2.2
type UserMessageDataAttachmentsItemReferenceType string
Type of GitHub reference
const ( UserMessageDataAttachmentsItemReferenceTypeIssue UserMessageDataAttachmentsItemReferenceType = "issue" UserMessageDataAttachmentsItemReferenceTypePr UserMessageDataAttachmentsItemReferenceType = "pr" UserMessageDataAttachmentsItemReferenceTypeDiscussion UserMessageDataAttachmentsItemReferenceType = "discussion" )
type UserMessageDataAttachmentsItemSelection ¶ added in v0.2.2
type UserMessageDataAttachmentsItemSelection struct {
// Start position of the selection
Start UserMessageDataAttachmentsItemSelectionStart `json:"start"`
// End position of the selection
End UserMessageDataAttachmentsItemSelectionEnd `json:"end"`
}
Position range of the selection within the file
type UserMessageDataAttachmentsItemSelectionEnd ¶ added in v0.2.2
type UserMessageDataAttachmentsItemSelectionEnd struct {
// End line number (0-based)
Line float64 `json:"line"`
// End character offset within the line (0-based)
Character float64 `json:"character"`
}
End position of the selection
type UserMessageDataAttachmentsItemSelectionStart ¶ added in v0.2.2
type UserMessageDataAttachmentsItemSelectionStart struct {
// Start line number (0-based)
Line float64 `json:"line"`
// Start character offset within the line (0-based)
Character float64 `json:"character"`
}
Start position of the selection
type UserMessageDataAttachmentsItemType ¶ added in v0.2.2
type UserMessageDataAttachmentsItemType string
Type discriminator for UserMessageDataAttachmentsItem.
const ( UserMessageDataAttachmentsItemTypeFile UserMessageDataAttachmentsItemType = "file" UserMessageDataAttachmentsItemTypeDirectory UserMessageDataAttachmentsItemType = "directory" UserMessageDataAttachmentsItemTypeSelection UserMessageDataAttachmentsItemType = "selection" UserMessageDataAttachmentsItemTypeGithubReference UserMessageDataAttachmentsItemType = "github_reference" UserMessageDataAttachmentsItemTypeBlob UserMessageDataAttachmentsItemType = "blob" )
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
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
|