# copilot ```go import "github.com/github/copilot-sdk/go" ``` 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{ Model: "gpt-4.1", }) if err != nil { log.Fatal(err) } session.On(func(event copilot.SessionEvent) { if event.Type == "assistant.message" { fmt.Println(event.Data.Content) } }) session.Send(copilot.MessageOptions{Prompt: "Hello!"}) ``` Package copilot provides a Go SDK for interacting with the GitHub Copilot CLI. ## Index - [Constants](<#constants>) - [func Bool\(v bool\) \*bool](<#Bool>) - [func Float64\(v float64\) \*float64](<#Float64>) - [func GetSdkProtocolVersion\(\) int](<#GetSdkProtocolVersion>) - [type Attachment](<#Attachment>) - [type AttachmentType](<#AttachmentType>) - [type AzureProviderOptions](<#AzureProviderOptions>) - [type Client](<#Client>) - [func NewClient\(options \*ClientOptions\) \*Client](<#NewClient>) - [func \(c \*Client\) CreateSession\(ctx context.Context, config \*SessionConfig\) \(\*Session, error\)](<#Client.CreateSession>) - [func \(c \*Client\) DeleteSession\(ctx context.Context, sessionID string\) error](<#Client.DeleteSession>) - [func \(c \*Client\) ForceStop\(\)](<#Client.ForceStop>) - [func \(c \*Client\) GetAuthStatus\(ctx context.Context\) \(\*GetAuthStatusResponse, error\)](<#Client.GetAuthStatus>) - [func \(c \*Client\) GetForegroundSessionID\(ctx context.Context\) \(\*string, error\)](<#Client.GetForegroundSessionID>) - [func \(c \*Client\) GetStatus\(ctx context.Context\) \(\*GetStatusResponse, error\)](<#Client.GetStatus>) - [func \(c \*Client\) ListModels\(ctx context.Context\) \(\[\]ModelInfo, error\)](<#Client.ListModels>) - [func \(c \*Client\) ListSessions\(ctx context.Context\) \(\[\]SessionMetadata, error\)](<#Client.ListSessions>) - [func \(c \*Client\) On\(handler SessionLifecycleHandler\) func\(\)](<#Client.On>) - [func \(c \*Client\) OnEventType\(eventType SessionLifecycleEventType, handler SessionLifecycleHandler\) func\(\)](<#Client.OnEventType>) - [func \(c \*Client\) Ping\(ctx context.Context, message string\) \(\*PingResponse, error\)](<#Client.Ping>) - [func \(c \*Client\) ResumeSession\(ctx context.Context, sessionID string\) \(\*Session, error\)](<#Client.ResumeSession>) - [func \(c \*Client\) ResumeSessionWithOptions\(ctx context.Context, sessionID string, config \*ResumeSessionConfig\) \(\*Session, error\)](<#Client.ResumeSessionWithOptions>) - [func \(c \*Client\) SetForegroundSessionID\(ctx context.Context, sessionID string\) error](<#Client.SetForegroundSessionID>) - [func \(c \*Client\) Start\(ctx context.Context\) error](<#Client.Start>) - [func \(c \*Client\) State\(\) ConnectionState](<#Client.State>) - [func \(c \*Client\) Stop\(\) error](<#Client.Stop>) - [type ClientOptions](<#ClientOptions>) - [type CodeChanges](<#CodeChanges>) - [type CompactionTokensUsed](<#CompactionTokensUsed>) - [type ConnectionState](<#ConnectionState>) - [type ContextClass](<#ContextClass>) - [type ContextUnion](<#ContextUnion>) - [func \(x \*ContextUnion\) MarshalJSON\(\) \(\[\]byte, error\)](<#ContextUnion.MarshalJSON>) - [func \(x \*ContextUnion\) UnmarshalJSON\(data \[\]byte\) error](<#ContextUnion.UnmarshalJSON>) - [type CustomAgentConfig](<#CustomAgentConfig>) - [type Data](<#Data>) - [type End](<#End>) - [type ErrorClass](<#ErrorClass>) - [type ErrorOccurredHandler](<#ErrorOccurredHandler>) - [type ErrorOccurredHookInput](<#ErrorOccurredHookInput>) - [type ErrorOccurredHookOutput](<#ErrorOccurredHookOutput>) - [type ErrorUnion](<#ErrorUnion>) - [func \(x \*ErrorUnion\) MarshalJSON\(\) \(\[\]byte, error\)](<#ErrorUnion.MarshalJSON>) - [func \(x \*ErrorUnion\) UnmarshalJSON\(data \[\]byte\) error](<#ErrorUnion.UnmarshalJSON>) - [type GetAuthStatusResponse](<#GetAuthStatusResponse>) - [type GetStatusResponse](<#GetStatusResponse>) - [type HookInvocation](<#HookInvocation>) - [type InfiniteSessionConfig](<#InfiniteSessionConfig>) - [type MCPLocalServerConfig](<#MCPLocalServerConfig>) - [type MCPRemoteServerConfig](<#MCPRemoteServerConfig>) - [type MCPServerConfig](<#MCPServerConfig>) - [type MessageOptions](<#MessageOptions>) - [type Metadata](<#Metadata>) - [type ModelBilling](<#ModelBilling>) - [type ModelCapabilities](<#ModelCapabilities>) - [type ModelInfo](<#ModelInfo>) - [type ModelLimits](<#ModelLimits>) - [type ModelMetric](<#ModelMetric>) - [type ModelPolicy](<#ModelPolicy>) - [type ModelSupports](<#ModelSupports>) - [type ModelVisionLimits](<#ModelVisionLimits>) - [type PermissionHandler](<#PermissionHandler>) - [type PermissionInvocation](<#PermissionInvocation>) - [type PermissionRequest](<#PermissionRequest>) - [type PermissionRequestResult](<#PermissionRequestResult>) - [type PingResponse](<#PingResponse>) - [type PostToolUseHandler](<#PostToolUseHandler>) - [type PostToolUseHookInput](<#PostToolUseHookInput>) - [type PostToolUseHookOutput](<#PostToolUseHookOutput>) - [type PreToolUseHandler](<#PreToolUseHandler>) - [type PreToolUseHookInput](<#PreToolUseHookInput>) - [type PreToolUseHookOutput](<#PreToolUseHookOutput>) - [type ProviderConfig](<#ProviderConfig>) - [type QuotaSnapshot](<#QuotaSnapshot>) - [type Repository](<#Repository>) - [type Requests](<#Requests>) - [type Result](<#Result>) - [type ResumeSessionConfig](<#ResumeSessionConfig>) - [type Role](<#Role>) - [type SelectionClass](<#SelectionClass>) - [type Session](<#Session>) - [func \(s \*Session\) Abort\(ctx context.Context\) error](<#Session.Abort>) - [func \(s \*Session\) Destroy\(\) error](<#Session.Destroy>) - [func \(s \*Session\) GetMessages\(ctx context.Context\) \(\[\]SessionEvent, error\)](<#Session.GetMessages>) - [func \(s \*Session\) On\(handler SessionEventHandler\) func\(\)](<#Session.On>) - [func \(s \*Session\) Send\(ctx context.Context, options MessageOptions\) \(string, error\)](<#Session.Send>) - [func \(s \*Session\) SendAndWait\(ctx context.Context, options MessageOptions\) \(\*SessionEvent, error\)](<#Session.SendAndWait>) - [func \(s \*Session\) WorkspacePath\(\) string](<#Session.WorkspacePath>) - [type SessionConfig](<#SessionConfig>) - [type SessionEndHandler](<#SessionEndHandler>) - [type SessionEndHookInput](<#SessionEndHookInput>) - [type SessionEndHookOutput](<#SessionEndHookOutput>) - [type SessionEvent](<#SessionEvent>) - [func UnmarshalSessionEvent\(data \[\]byte\) \(SessionEvent, error\)](<#UnmarshalSessionEvent>) - [func \(r \*SessionEvent\) Marshal\(\) \(\[\]byte, error\)](<#SessionEvent.Marshal>) - [type SessionEventHandler](<#SessionEventHandler>) - [type SessionEventType](<#SessionEventType>) - [type SessionHooks](<#SessionHooks>) - [type SessionLifecycleEvent](<#SessionLifecycleEvent>) - [type SessionLifecycleEventMetadata](<#SessionLifecycleEventMetadata>) - [type SessionLifecycleEventType](<#SessionLifecycleEventType>) - [type SessionLifecycleHandler](<#SessionLifecycleHandler>) - [type SessionMetadata](<#SessionMetadata>) - [type SessionStartHandler](<#SessionStartHandler>) - [type SessionStartHookInput](<#SessionStartHookInput>) - [type SessionStartHookOutput](<#SessionStartHookOutput>) - [type ShutdownType](<#ShutdownType>) - [type SourceType](<#SourceType>) - [type Start](<#Start>) - [type SystemMessageAppendConfig](<#SystemMessageAppendConfig>) - [type SystemMessageConfig](<#SystemMessageConfig>) - [type SystemMessageReplaceConfig](<#SystemMessageReplaceConfig>) - [type Tool](<#Tool>) - [func DefineTool\[T any, U any\]\(name, description string, handler func\(T, ToolInvocation\) \(U, error\)\) Tool](<#DefineTool>) - [type ToolBinaryResult](<#ToolBinaryResult>) - [type ToolHandler](<#ToolHandler>) - [type ToolInvocation](<#ToolInvocation>) - [type ToolRequest](<#ToolRequest>) - [type ToolRequestType](<#ToolRequestType>) - [type ToolResult](<#ToolResult>) - [type Usage](<#Usage>) - [type UserInputHandler](<#UserInputHandler>) - [type UserInputInvocation](<#UserInputInvocation>) - [type UserInputRequest](<#UserInputRequest>) - [type UserInputResponse](<#UserInputResponse>) - [type UserPromptSubmittedHandler](<#UserPromptSubmittedHandler>) - [type UserPromptSubmittedHookInput](<#UserPromptSubmittedHookInput>) - [type UserPromptSubmittedHookOutput](<#UserPromptSubmittedHookOutput>) ## Constants SdkProtocolVersion is the SDK protocol version. This must match the version expected by the copilot\-agent\-runtime server. ```go const SdkProtocolVersion = 2 ``` ## func [Bool]() ```go func Bool(v bool) *bool ``` Bool returns a pointer to the given bool value. Use for setting AutoStart or AutoRestart: AutoStart: Bool\(false\) ## func [Float64]() ```go func Float64(v float64) *float64 ``` Float64 returns a pointer to the given float64 value. Use for setting thresholds: BackgroundCompactionThreshold: Float64\(0.80\) ## func [GetSdkProtocolVersion]() ```go func GetSdkProtocolVersion() int ``` GetSdkProtocolVersion returns the SDK protocol version. ## type [Attachment]() ```go type Attachment struct { DisplayName string `json:"displayName"` Path *string `json:"path,omitempty"` Type AttachmentType `json:"type"` FilePath *string `json:"filePath,omitempty"` Selection *SelectionClass `json:"selection,omitempty"` Text *string `json:"text,omitempty"` } ``` ## type [AttachmentType]() ```go type AttachmentType string ``` ```go const ( Directory AttachmentType = "directory" File AttachmentType = "file" Selection AttachmentType = "selection" ) ``` ## type [AzureProviderOptions]() AzureProviderOptions contains Azure\-specific provider configuration ```go type AzureProviderOptions struct { // APIVersion is the Azure API version. Defaults to "2024-10-21". APIVersion string `json:"apiVersion,omitempty"` } ``` ## type [Client]() 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() ``` ```go type Client struct { // contains filtered or unexported fields } ``` ### func [NewClient]() ```go 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](<#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\) [CreateSession]() ```go func (c *Client) CreateSession(ctx context.Context, config *SessionConfig) (*Session, error) ``` CreateSession creates a new conversation session with the Copilot CLI. Sessions maintain conversation state, handle events, and manage tool execution. If the client is not connected and AutoStart is enabled, this will automatically start the connection. The config parameter is optional; pass nil for default settings. Returns the created session or an error if session creation fails. Example: ``` // Basic session session, err := client.CreateSession(context.Background(), nil) // Session with model and tools session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{ Model: "gpt-4.1", Tools: []copilot.Tool{ { Name: "get_weather", Description: "Get weather for a location", Handler: weatherHandler, }, }, }) ``` ### func \(\*Client\) [DeleteSession]() ```go func (c *Client) DeleteSession(ctx context.Context, sessionID string) error ``` DeleteSession permanently deletes a session and all its conversation history. 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]() ```go func (c *Client) ForceStop() ``` ForceStop forcefully stops the CLI server without graceful cleanup. Use this when [Client.Stop](<#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]() ```go func (c *Client) GetAuthStatus(ctx context.Context) (*GetAuthStatusResponse, error) ``` GetAuthStatus returns current authentication status ### func \(\*Client\) [GetForegroundSessionID]() ```go func (c *Client) GetForegroundSessionID(ctx context.Context) (*string, error) ``` 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\) [GetStatus]() ```go func (c *Client) GetStatus(ctx context.Context) (*GetStatusResponse, error) ``` GetStatus returns CLI status including version and protocol information ### func \(\*Client\) [ListModels]() ```go func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error) ``` 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]() ```go func (c *Client) ListSessions(ctx context.Context) ([]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, and optional summaries. Example: ``` sessions, err := client.ListSessions(context.Background()) if err != nil { log.Fatal(err) } for _, session := range sessions { fmt.Printf("Session: %s\n", session.SessionID) } ``` ### func \(\*Client\) [On]() ```go 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]() ```go 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]() ```go func (c *Client) Ping(ctx context.Context, message string) (*PingResponse, error) ``` 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]() ```go func (c *Client) ResumeSession(ctx context.Context, sessionID string) (*Session, error) ``` ResumeSession resumes an existing conversation session by its ID using default options. This is a convenience method that calls [Client.ResumeSessionWithOptions](<#Client.ResumeSessionWithOptions>) with nil config. Example: ``` session, err := client.ResumeSession(context.Background(), "session-123") ``` ### func \(\*Client\) [ResumeSessionWithOptions]() ```go 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{ Tools: []copilot.Tool{myNewTool}, }) ``` ### func \(\*Client\) [SetForegroundSessionID]() ```go func (c *Client) SetForegroundSessionID(ctx context.Context, sessionID string) error ``` 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]() ```go func (c *Client) Start(ctx context.Context) error ``` 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]() ```go 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(), nil) } ``` ### func \(\*Client\) [Stop]() ```go func (c *Client) Stop() error ``` Stop stops the CLI server and closes all active sessions. This method performs graceful cleanup: 1. Destroys all active sessions 2. Closes the JSON\-RPC connection 3. Terminates the CLI server process \(if spawned by this client\) 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]() ClientOptions configures the CopilotClient ```go type ClientOptions struct { // CLIPath is the path to the Copilot CLI executable (default: "copilot") CLIPath 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 // AutoRestart automatically restarts the CLI server if it crashes (default: true). // Use Bool(false) to disable. 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 } ``` ## type [CodeChanges]() ```go type CodeChanges struct { FilesModified []string `json:"filesModified"` LinesAdded float64 `json:"linesAdded"` LinesRemoved float64 `json:"linesRemoved"` } ``` ## type [CompactionTokensUsed]() ```go type CompactionTokensUsed struct { CachedInput float64 `json:"cachedInput"` Input float64 `json:"input"` Output float64 `json:"output"` } ``` ## type [ConnectionState]() ConnectionState represents the client connection state ```go type ConnectionState string ``` ```go const ( StateDisconnected ConnectionState = "disconnected" StateConnecting ConnectionState = "connecting" StateConnected ConnectionState = "connected" StateError ConnectionState = "error" ) ``` ## type [ContextClass]() ```go type ContextClass struct { Branch *string `json:"branch,omitempty"` Cwd string `json:"cwd"` GitRoot *string `json:"gitRoot,omitempty"` Repository *string `json:"repository,omitempty"` } ``` ## type [ContextUnion]() ```go type ContextUnion struct { ContextClass *ContextClass String *string } ``` ### func \(\*ContextUnion\) [MarshalJSON]() ```go func (x *ContextUnion) MarshalJSON() ([]byte, error) ``` ### func \(\*ContextUnion\) [UnmarshalJSON]() ```go func (x *ContextUnion) UnmarshalJSON(data []byte) error ``` ## type [CustomAgentConfig]() CustomAgentConfig configures a custom agent ```go 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"` } ``` ## type [Data]() ```go type Data struct { Context *ContextUnion `json:"context"` CopilotVersion *string `json:"copilotVersion,omitempty"` Producer *string `json:"producer,omitempty"` SelectedModel *string `json:"selectedModel,omitempty"` SessionID *string `json:"sessionId,omitempty"` StartTime *time.Time `json:"startTime,omitempty"` Version *float64 `json:"version,omitempty"` EventCount *float64 `json:"eventCount,omitempty"` ResumeTime *time.Time `json:"resumeTime,omitempty"` ErrorType *string `json:"errorType,omitempty"` Message *string `json:"message,omitempty"` ProviderCallID *string `json:"providerCallId,omitempty"` Stack *string `json:"stack,omitempty"` StatusCode *int64 `json:"statusCode,omitempty"` InfoType *string `json:"infoType,omitempty"` NewModel *string `json:"newModel,omitempty"` PreviousModel *string `json:"previousModel,omitempty"` HandoffTime *time.Time `json:"handoffTime,omitempty"` RemoteSessionID *string `json:"remoteSessionId,omitempty"` Repository *Repository `json:"repository,omitempty"` SourceType *SourceType `json:"sourceType,omitempty"` Summary *string `json:"summary,omitempty"` MessagesRemovedDuringTruncation *float64 `json:"messagesRemovedDuringTruncation,omitempty"` PerformedBy *string `json:"performedBy,omitempty"` PostTruncationMessagesLength *float64 `json:"postTruncationMessagesLength,omitempty"` PostTruncationTokensInMessages *float64 `json:"postTruncationTokensInMessages,omitempty"` PreTruncationMessagesLength *float64 `json:"preTruncationMessagesLength,omitempty"` PreTruncationTokensInMessages *float64 `json:"preTruncationTokensInMessages,omitempty"` TokenLimit *float64 `json:"tokenLimit,omitempty"` TokensRemovedDuringTruncation *float64 `json:"tokensRemovedDuringTruncation,omitempty"` EventsRemoved *float64 `json:"eventsRemoved,omitempty"` UpToEventID *string `json:"upToEventId,omitempty"` CodeChanges *CodeChanges `json:"codeChanges,omitempty"` CurrentModel *string `json:"currentModel,omitempty"` ErrorReason *string `json:"errorReason,omitempty"` ModelMetrics map[string]ModelMetric `json:"modelMetrics,omitempty"` SessionStartTime *float64 `json:"sessionStartTime,omitempty"` ShutdownType *ShutdownType `json:"shutdownType,omitempty"` TotalAPIDurationMS *float64 `json:"totalApiDurationMs,omitempty"` TotalPremiumRequests *float64 `json:"totalPremiumRequests,omitempty"` CurrentTokens *float64 `json:"currentTokens,omitempty"` MessagesLength *float64 `json:"messagesLength,omitempty"` CheckpointNumber *float64 `json:"checkpointNumber,omitempty"` CheckpointPath *string `json:"checkpointPath,omitempty"` CompactionTokensUsed *CompactionTokensUsed `json:"compactionTokensUsed,omitempty"` Error *ErrorUnion `json:"error"` MessagesRemoved *float64 `json:"messagesRemoved,omitempty"` PostCompactionTokens *float64 `json:"postCompactionTokens,omitempty"` PreCompactionMessagesLength *float64 `json:"preCompactionMessagesLength,omitempty"` PreCompactionTokens *float64 `json:"preCompactionTokens,omitempty"` RequestID *string `json:"requestId,omitempty"` Success *bool `json:"success,omitempty"` SummaryContent *string `json:"summaryContent,omitempty"` TokensRemoved *float64 `json:"tokensRemoved,omitempty"` Attachments []Attachment `json:"attachments,omitempty"` Content *string `json:"content,omitempty"` Source *string `json:"source,omitempty"` TransformedContent *string `json:"transformedContent,omitempty"` TurnID *string `json:"turnId,omitempty"` Intent *string `json:"intent,omitempty"` ReasoningID *string `json:"reasoningId,omitempty"` DeltaContent *string `json:"deltaContent,omitempty"` EncryptedContent *string `json:"encryptedContent,omitempty"` MessageID *string `json:"messageId,omitempty"` ParentToolCallID *string `json:"parentToolCallId,omitempty"` ReasoningOpaque *string `json:"reasoningOpaque,omitempty"` ReasoningText *string `json:"reasoningText,omitempty"` ToolRequests []ToolRequest `json:"toolRequests,omitempty"` TotalResponseSizeBytes *float64 `json:"totalResponseSizeBytes,omitempty"` APICallID *string `json:"apiCallId,omitempty"` CacheReadTokens *float64 `json:"cacheReadTokens,omitempty"` CacheWriteTokens *float64 `json:"cacheWriteTokens,omitempty"` Cost *float64 `json:"cost,omitempty"` Duration *float64 `json:"duration,omitempty"` Initiator *string `json:"initiator,omitempty"` InputTokens *float64 `json:"inputTokens,omitempty"` Model *string `json:"model,omitempty"` OutputTokens *float64 `json:"outputTokens,omitempty"` QuotaSnapshots map[string]QuotaSnapshot `json:"quotaSnapshots,omitempty"` Reason *string `json:"reason,omitempty"` Arguments interface{} `json:"arguments"` ToolCallID *string `json:"toolCallId,omitempty"` ToolName *string `json:"toolName,omitempty"` MCPServerName *string `json:"mcpServerName,omitempty"` MCPToolName *string `json:"mcpToolName,omitempty"` PartialOutput *string `json:"partialOutput,omitempty"` ProgressMessage *string `json:"progressMessage,omitempty"` IsUserRequested *bool `json:"isUserRequested,omitempty"` Result *Result `json:"result,omitempty"` ToolTelemetry map[string]interface{} `json:"toolTelemetry,omitempty"` AllowedTools []string `json:"allowedTools,omitempty"` Name *string `json:"name,omitempty"` Path *string `json:"path,omitempty"` AgentDescription *string `json:"agentDescription,omitempty"` AgentDisplayName *string `json:"agentDisplayName,omitempty"` AgentName *string `json:"agentName,omitempty"` Tools []string `json:"tools"` HookInvocationID *string `json:"hookInvocationId,omitempty"` HookType *string `json:"hookType,omitempty"` Input interface{} `json:"input"` Output interface{} `json:"output"` Metadata *Metadata `json:"metadata,omitempty"` Role *Role `json:"role,omitempty"` } ``` ## type [End]() ```go type End struct { Character float64 `json:"character"` Line float64 `json:"line"` } ``` ## type [ErrorClass]() ```go type ErrorClass struct { Code *string `json:"code,omitempty"` Message string `json:"message"` Stack *string `json:"stack,omitempty"` } ``` ## type [ErrorOccurredHandler]() ErrorOccurredHandler handles error\-occurred hook invocations ```go type ErrorOccurredHandler func(input ErrorOccurredHookInput, invocation HookInvocation) (*ErrorOccurredHookOutput, error) ``` ## type [ErrorOccurredHookInput]() ErrorOccurredHookInput is the input for an error\-occurred hook ```go 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"` } ``` ## type [ErrorOccurredHookOutput]() ErrorOccurredHookOutput is the output for an error\-occurred hook ```go 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"` } ``` ## type [ErrorUnion]() ```go type ErrorUnion struct { ErrorClass *ErrorClass String *string } ``` ### func \(\*ErrorUnion\) [MarshalJSON]() ```go func (x *ErrorUnion) MarshalJSON() ([]byte, error) ``` ### func \(\*ErrorUnion\) [UnmarshalJSON]() ```go func (x *ErrorUnion) UnmarshalJSON(data []byte) error ``` ## type [GetAuthStatusResponse]() GetAuthStatusResponse is the response from auth.getStatus ```go 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"` } ``` ## type [GetStatusResponse]() GetStatusResponse is the response from status.get ```go type GetStatusResponse struct { Version string `json:"version"` ProtocolVersion int `json:"protocolVersion"` } ``` ## type [HookInvocation]() HookInvocation provides context about a hook invocation ```go type HookInvocation struct { SessionID string } ``` ## type [InfiniteSessionConfig]() 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. ```go 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"` } ``` ## type [MCPLocalServerConfig]() MCPLocalServerConfig configures a local/stdio MCP server ```go 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"` } ``` ## type [MCPRemoteServerConfig]() MCPRemoteServerConfig configures a remote MCP server \(HTTP or SSE\) ```go 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"` } ``` ## type [MCPServerConfig]() MCPServerConfig can be either MCPLocalServerConfig or MCPRemoteServerConfig Use a map\[string\]any for flexibility, or create separate configs ```go type MCPServerConfig map[string]any ``` ## type [MessageOptions]() MessageOptions configures a message to send ```go 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 } ``` ## type [Metadata]() ```go type Metadata struct { PromptVersion *string `json:"promptVersion,omitempty"` Variables map[string]interface{} `json:"variables,omitempty"` } ``` ## type [ModelBilling]() ModelBilling contains model billing information ```go type ModelBilling struct { Multiplier float64 `json:"multiplier"` } ``` ## type [ModelCapabilities]() ModelCapabilities contains model capabilities and limits ```go type ModelCapabilities struct { Supports ModelSupports `json:"supports"` Limits ModelLimits `json:"limits"` } ``` ## type [ModelInfo]() ModelInfo contains information about an available model ```go 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"` } ``` ## type [ModelLimits]() ModelLimits contains model limits ```go type ModelLimits struct { MaxPromptTokens *int `json:"max_prompt_tokens,omitempty"` MaxContextWindowTokens int `json:"max_context_window_tokens"` Vision *ModelVisionLimits `json:"vision,omitempty"` } ``` ## type [ModelMetric]() ```go type ModelMetric struct { Requests Requests `json:"requests"` Usage Usage `json:"usage"` } ``` ## type [ModelPolicy]() ModelPolicy contains model policy state ```go type ModelPolicy struct { State string `json:"state"` Terms string `json:"terms"` } ``` ## type [ModelSupports]() ModelSupports contains model support flags ```go type ModelSupports struct { Vision bool `json:"vision"` ReasoningEffort bool `json:"reasoningEffort"` } ``` ## type [ModelVisionLimits]() ModelVisionLimits contains vision\-specific limits ```go type ModelVisionLimits struct { SupportedMediaTypes []string `json:"supported_media_types"` MaxPromptImages int `json:"max_prompt_images"` MaxPromptImageSize int `json:"max_prompt_image_size"` } ``` ## type [PermissionHandler]() PermissionHandler executes a permission request The handler should return a PermissionRequestResult. Returning an error denies the permission. ```go type PermissionHandler func(request PermissionRequest, invocation PermissionInvocation) (PermissionRequestResult, error) ``` ## type [PermissionInvocation]() PermissionInvocation provides context about a permission request ```go type PermissionInvocation struct { SessionID string } ``` ## type [PermissionRequest]() PermissionRequest represents a permission request from the server ```go type PermissionRequest struct { Kind string `json:"kind"` ToolCallID string `json:"toolCallId,omitempty"` Extra map[string]any `json:"-"` // Additional fields vary by kind } ``` ## type [PermissionRequestResult]() PermissionRequestResult represents the result of a permission request ```go type PermissionRequestResult struct { Kind string `json:"kind"` Rules []any `json:"rules,omitempty"` } ``` ## type [PingResponse]() PingResponse is the response from a ping request ```go type PingResponse struct { Message string `json:"message"` Timestamp int64 `json:"timestamp"` ProtocolVersion *int `json:"protocolVersion,omitempty"` } ``` ## type [PostToolUseHandler]() PostToolUseHandler handles post\-tool\-use hook invocations ```go type PostToolUseHandler func(input PostToolUseHookInput, invocation HookInvocation) (*PostToolUseHookOutput, error) ``` ## type [PostToolUseHookInput]() PostToolUseHookInput is the input for a post\-tool\-use hook ```go type PostToolUseHookInput struct { Timestamp int64 `json:"timestamp"` Cwd string `json:"cwd"` ToolName string `json:"toolName"` ToolArgs any `json:"toolArgs"` ToolResult any `json:"toolResult"` } ``` ## type [PostToolUseHookOutput]() PostToolUseHookOutput is the output for a post\-tool\-use hook ```go type PostToolUseHookOutput struct { ModifiedResult any `json:"modifiedResult,omitempty"` AdditionalContext string `json:"additionalContext,omitempty"` SuppressOutput bool `json:"suppressOutput,omitempty"` } ``` ## type [PreToolUseHandler]() PreToolUseHandler handles pre\-tool\-use hook invocations ```go type PreToolUseHandler func(input PreToolUseHookInput, invocation HookInvocation) (*PreToolUseHookOutput, error) ``` ## type [PreToolUseHookInput]() PreToolUseHookInput is the input for a pre\-tool\-use hook ```go type PreToolUseHookInput struct { Timestamp int64 `json:"timestamp"` Cwd string `json:"cwd"` ToolName string `json:"toolName"` ToolArgs any `json:"toolArgs"` } ``` ## type [PreToolUseHookOutput]() PreToolUseHookOutput is the output for a pre\-tool\-use hook ```go 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"` } ``` ## type [ProviderConfig]() ProviderConfig configures a custom model provider ```go 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 [QuotaSnapshot]() ```go type QuotaSnapshot struct { EntitlementRequests float64 `json:"entitlementRequests"` IsUnlimitedEntitlement bool `json:"isUnlimitedEntitlement"` Overage float64 `json:"overage"` OverageAllowedWithExhaustedQuota bool `json:"overageAllowedWithExhaustedQuota"` RemainingPercentage float64 `json:"remainingPercentage"` ResetDate *time.Time `json:"resetDate,omitempty"` UsageAllowedWithExhaustedQuota bool `json:"usageAllowedWithExhaustedQuota"` UsedRequests float64 `json:"usedRequests"` } ``` ## type [Repository]() ```go type Repository struct { Branch *string `json:"branch,omitempty"` Name string `json:"name"` Owner string `json:"owner"` } ``` ## type [Requests]() ```go type Requests struct { Cost float64 `json:"cost"` Count float64 `json:"count"` } ``` ## type [Result]() ```go type Result struct { Content string `json:"content"` DetailedContent *string `json:"detailedContent,omitempty"` } ``` ## type [ResumeSessionConfig]() ResumeSessionConfig configures options when resuming a session ```go type ResumeSessionConfig struct { // Model to use for this session. Can change the model when resuming. Model string // Tools exposes caller-implemented tools to the CLI Tools []Tool // SystemMessage configures system message customization SystemMessage *SystemMessageConfig // AvailableTools is a list of tool names to allow. When specified, only these tools will be available. // Takes precedence over ExcludedTools. AvailableTools []string // ExcludedTools is a list of tool names to disable. All other tools remain available. // Ignored if AvailableTools is specified. ExcludedTools []string // Provider configures a custom model provider Provider *ProviderConfig // ReasoningEffort level for models that support it. // Valid values: "low", "medium", "high", "xhigh" ReasoningEffort string // OnPermissionRequest is a handler for permission requests from the server OnPermissionRequest PermissionHandler // OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool) OnUserInputRequest UserInputHandler // Hooks configures hook handlers for session lifecycle events Hooks *SessionHooks // WorkingDirectory is the working directory for the session. // Tool operations will be relative to this directory. WorkingDirectory string // ConfigDir overrides the default configuration directory location. ConfigDir string // Streaming enables streaming of assistant message and reasoning chunks. // When true, assistant.message_delta and assistant.reasoning_delta events // with deltaContent are sent as the response is generated. Streaming bool // MCPServers configures MCP servers for the session MCPServers map[string]MCPServerConfig // CustomAgents configures custom agents for the session CustomAgents []CustomAgentConfig // 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 } ``` ## type [Role]() ```go type Role string ``` ```go const ( Developer Role = "developer" System Role = "system" ) ``` ## type [SelectionClass]() ```go type SelectionClass struct { End End `json:"end"` Start Start `json:"start"` } ``` ## type [Session]() 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](<#Client.CreateSession>) or resumed via [Client.ResumeSession](<#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.1", }) if err != nil { log.Fatal(err) } defer session.Destroy() // Subscribe to events unsubscribe := session.On(func(event copilot.SessionEvent) { if event.Type == "assistant.message" { fmt.Println("Assistant:", event.Data.Content) } }) defer unsubscribe() // Send a message messageID, err := session.Send(copilot.MessageOptions{ Prompt: "Hello, world!", }) ``` ```go type Session struct { // SessionID is the unique identifier for this session. SessionID string // contains filtered or unexported fields } ``` ### func \(\*Session\) [Abort]() ```go func (s *Session) Abort(ctx context.Context) error ``` 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 destroyed 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\) [Destroy]() ```go func (s *Session) Destroy() error ``` Destroy destroys this session and releases all associated resources. After calling this method, the session can no longer be used. All event handlers and tool handlers are cleared. To continue the conversation, use [Client.ResumeSession](<#Client.ResumeSession>) with the session ID. Returns an error if the connection fails. Example: ``` // Clean up when done if err := session.Destroy(); err != nil { log.Printf("Failed to destroy session: %v", err) } ``` ### func \(\*Session\) [GetMessages]() ```go 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 destroyed 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 event.Type == "assistant.message" { fmt.Println("Assistant:", event.Data.Content) } } ``` ### func \(\*Session\) [On]() ```go 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 event.Type { case "assistant.message": fmt.Println("Assistant:", event.Data.Content) case "session.error": fmt.Println("Error:", event.Data.Message) } }) // Later, to stop receiving events: unsubscribe() ``` ### func \(\*Session\) [Send]() ```go func (s *Session) Send(ctx context.Context, options MessageOptions) (string, error) ``` Send sends a message to this session and waits for the response. The message is processed asynchronously. Subscribe to events via [Session.On](<#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 destroyed 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]() ```go 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](<#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](<#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 { fmt.Println(*response.Data.Content) } ``` ### func \(\*Session\) [WorkspacePath]() ```go func (s *Session) WorkspacePath() string ``` 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 [SessionConfig]() SessionConfig configures a new session ```go type SessionConfig struct { // SessionID is an optional custom session ID SessionID string // Model to use for this session Model string // ReasoningEffort level for models that support it. // Valid values: "low", "medium", "high", "xhigh" // Only applies to models where capabilities.supports.reasoningEffort is true. ReasoningEffort string // ConfigDir overrides the default configuration directory location. // When specified, the session will use this directory for storing config and state. ConfigDir string // Tools exposes caller-implemented tools to the CLI Tools []Tool // SystemMessage configures system message customization SystemMessage *SystemMessageConfig // AvailableTools is a list of tool names to allow. When specified, only these tools will be available. // Takes precedence over ExcludedTools. AvailableTools []string // ExcludedTools is a list of tool names to disable. All other tools remain available. // Ignored if AvailableTools is specified. ExcludedTools []string // OnPermissionRequest is a handler for permission requests from the server OnPermissionRequest PermissionHandler // OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool) OnUserInputRequest UserInputHandler // Hooks configures hook handlers for session lifecycle events Hooks *SessionHooks // WorkingDirectory is the working directory for the session. // Tool operations will be relative to this directory. WorkingDirectory string // Streaming enables streaming of assistant message and reasoning chunks. // When true, assistant.message_delta and assistant.reasoning_delta events // with deltaContent are sent as the response is generated. Streaming bool // Provider configures a custom model provider (BYOK) Provider *ProviderConfig // MCPServers configures MCP servers for the session MCPServers map[string]MCPServerConfig // CustomAgents configures custom agents for the session CustomAgents []CustomAgentConfig // 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 } ``` ## type [SessionEndHandler]() SessionEndHandler handles session\-end hook invocations ```go type SessionEndHandler func(input SessionEndHookInput, invocation HookInvocation) (*SessionEndHookOutput, error) ``` ## type [SessionEndHookInput]() SessionEndHookInput is the input for a session\-end hook ```go 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"` } ``` ## type [SessionEndHookOutput]() SessionEndHookOutput is the output for a session\-end hook ```go type SessionEndHookOutput struct { SuppressOutput bool `json:"suppressOutput,omitempty"` CleanupActions []string `json:"cleanupActions,omitempty"` SessionSummary string `json:"sessionSummary,omitempty"` } ``` ## type [SessionEvent]() ```go type SessionEvent struct { Data Data `json:"data"` Ephemeral *bool `json:"ephemeral,omitempty"` ID string `json:"id"` ParentID *string `json:"parentId"` Timestamp time.Time `json:"timestamp"` Type SessionEventType `json:"type"` } ``` ### func [UnmarshalSessionEvent]() ```go func UnmarshalSessionEvent(data []byte) (SessionEvent, error) ``` ### func \(\*SessionEvent\) [Marshal]() ```go func (r *SessionEvent) Marshal() ([]byte, error) ``` ## type [SessionEventHandler]() SessionEventHandler is a callback for session events ```go type SessionEventHandler func(event SessionEvent) ``` ## type [SessionEventType]() ```go type SessionEventType string ``` ```go const ( Abort SessionEventType = "abort" AssistantIntent SessionEventType = "assistant.intent" AssistantMessage SessionEventType = "assistant.message" AssistantMessageDelta SessionEventType = "assistant.message_delta" AssistantReasoning SessionEventType = "assistant.reasoning" AssistantReasoningDelta SessionEventType = "assistant.reasoning_delta" AssistantTurnEnd SessionEventType = "assistant.turn_end" AssistantTurnStart SessionEventType = "assistant.turn_start" AssistantUsage SessionEventType = "assistant.usage" HookEnd SessionEventType = "hook.end" HookStart SessionEventType = "hook.start" PendingMessagesModified SessionEventType = "pending_messages.modified" SessionCompactionComplete SessionEventType = "session.compaction_complete" SessionCompactionStart SessionEventType = "session.compaction_start" SessionError SessionEventType = "session.error" SessionHandoff SessionEventType = "session.handoff" SessionIdle SessionEventType = "session.idle" SessionInfo SessionEventType = "session.info" SessionModelChange SessionEventType = "session.model_change" SessionResume SessionEventType = "session.resume" SessionShutdown SessionEventType = "session.shutdown" SessionSnapshotRewind SessionEventType = "session.snapshot_rewind" SessionStart SessionEventType = "session.start" SessionTruncation SessionEventType = "session.truncation" SessionUsageInfo SessionEventType = "session.usage_info" SkillInvoked SessionEventType = "skill.invoked" SubagentCompleted SessionEventType = "subagent.completed" SubagentFailed SessionEventType = "subagent.failed" SubagentSelected SessionEventType = "subagent.selected" SubagentStarted SessionEventType = "subagent.started" SystemMessage SessionEventType = "system.message" ToolExecutionComplete SessionEventType = "tool.execution_complete" ToolExecutionPartialResult SessionEventType = "tool.execution_partial_result" ToolExecutionProgress SessionEventType = "tool.execution_progress" ToolExecutionStart SessionEventType = "tool.execution_start" ToolUserRequested SessionEventType = "tool.user_requested" UserMessage SessionEventType = "user.message" ) ``` ## type [SessionHooks]() SessionHooks configures hook handlers for a session ```go type SessionHooks struct { OnPreToolUse PreToolUseHandler OnPostToolUse PostToolUseHandler OnUserPromptSubmitted UserPromptSubmittedHandler OnSessionStart SessionStartHandler OnSessionEnd SessionEndHandler OnErrorOccurred ErrorOccurredHandler } ``` ## type [SessionLifecycleEvent]() SessionLifecycleEvent represents a session lifecycle notification ```go type SessionLifecycleEvent struct { Type SessionLifecycleEventType `json:"type"` SessionID string `json:"sessionId"` Metadata *SessionLifecycleEventMetadata `json:"metadata,omitempty"` } ``` ## type [SessionLifecycleEventMetadata]() SessionLifecycleEventMetadata contains optional metadata for lifecycle events ```go type SessionLifecycleEventMetadata struct { StartTime string `json:"startTime"` ModifiedTime string `json:"modifiedTime"` Summary *string `json:"summary,omitempty"` } ``` ## type [SessionLifecycleEventType]() SessionLifecycleEventType represents the type of session lifecycle event ```go type SessionLifecycleEventType string ``` ```go const ( SessionLifecycleCreated SessionLifecycleEventType = "session.created" SessionLifecycleDeleted SessionLifecycleEventType = "session.deleted" SessionLifecycleUpdated SessionLifecycleEventType = "session.updated" SessionLifecycleForeground SessionLifecycleEventType = "session.foreground" SessionLifecycleBackground SessionLifecycleEventType = "session.background" ) ``` ## type [SessionLifecycleHandler]() SessionLifecycleHandler is a callback for session lifecycle events ```go type SessionLifecycleHandler func(event SessionLifecycleEvent) ``` ## type [SessionMetadata]() SessionMetadata contains metadata about a session ```go type SessionMetadata struct { SessionID string `json:"sessionId"` StartTime string `json:"startTime"` ModifiedTime string `json:"modifiedTime"` Summary *string `json:"summary,omitempty"` IsRemote bool `json:"isRemote"` } ``` ## type [SessionStartHandler]() SessionStartHandler handles session\-start hook invocations ```go type SessionStartHandler func(input SessionStartHookInput, invocation HookInvocation) (*SessionStartHookOutput, error) ``` ## type [SessionStartHookInput]() SessionStartHookInput is the input for a session\-start hook ```go type SessionStartHookInput struct { Timestamp int64 `json:"timestamp"` Cwd string `json:"cwd"` Source string `json:"source"` // "startup", "resume", "new" InitialPrompt string `json:"initialPrompt,omitempty"` } ``` ## type [SessionStartHookOutput]() SessionStartHookOutput is the output for a session\-start hook ```go type SessionStartHookOutput struct { AdditionalContext string `json:"additionalContext,omitempty"` ModifiedConfig map[string]any `json:"modifiedConfig,omitempty"` } ``` ## type [ShutdownType]() ```go type ShutdownType string ``` ```go const ( Error ShutdownType = "error" Routine ShutdownType = "routine" ) ``` ## type [SourceType]() ```go type SourceType string ``` ```go const ( Local SourceType = "local" Remote SourceType = "remote" ) ``` ## type [Start]() ```go type Start struct { Character float64 `json:"character"` Line float64 `json:"line"` } ``` ## type [SystemMessageAppendConfig]() SystemMessageAppendConfig is append mode: use CLI foundation with optional appended content. ```go 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"` } ``` ## type [SystemMessageConfig]() SystemMessageConfig represents system message configuration for session creation. Use SystemMessageAppendConfig for default behavior, SystemMessageReplaceConfig for full control. In Go, use one struct or the other based on your needs. ```go type SystemMessageConfig struct { Mode string `json:"mode,omitempty"` Content string `json:"content,omitempty"` } ``` ## type [SystemMessageReplaceConfig]() SystemMessageReplaceConfig is replace mode: use caller\-provided system message entirely. Removes all SDK guardrails including security restrictions. ```go type SystemMessageReplaceConfig struct { // Mode must be "replace" Mode string `json:"mode"` // Content is the complete system message (required) Content string `json:"content"` } ``` ## type [Tool]() Tool describes a caller\-implemented tool that can be invoked by Copilot ```go type Tool struct { Name string `json:"name"` Description string `json:"description,omitempty"` Parameters map[string]any `json:"parameters,omitempty"` Handler ToolHandler `json:"-"` } ``` ### func [DefineTool]() ```go 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]() ToolBinaryResult represents binary payloads returned by tools. ```go type ToolBinaryResult struct { Data string `json:"data"` MimeType string `json:"mimeType"` Type string `json:"type"` Description string `json:"description,omitempty"` } ``` ## type [ToolHandler]() ToolHandler executes a tool invocation. The handler should return a ToolResult. Returning an error marks the tool execution as a failure. ```go type ToolHandler func(invocation ToolInvocation) (ToolResult, error) ``` ## type [ToolInvocation]() ToolInvocation describes a tool call initiated by Copilot ```go type ToolInvocation struct { SessionID string ToolCallID string ToolName string Arguments any } ``` ## type [ToolRequest]() ```go type ToolRequest struct { Arguments interface{} `json:"arguments"` Name string `json:"name"` ToolCallID string `json:"toolCallId"` Type *ToolRequestType `json:"type,omitempty"` } ``` ## type [ToolRequestType]() ```go type ToolRequestType string ``` ```go const ( Custom ToolRequestType = "custom" Function ToolRequestType = "function" ) ``` ## type [ToolResult]() ToolResult represents the result of a tool invocation. ```go 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"` } ``` ## type [Usage]() ```go type Usage struct { CacheReadTokens float64 `json:"cacheReadTokens"` CacheWriteTokens float64 `json:"cacheWriteTokens"` InputTokens float64 `json:"inputTokens"` OutputTokens float64 `json:"outputTokens"` } ``` ## type [UserInputHandler]() UserInputHandler handles user input requests from the agent The handler should return a UserInputResponse. Returning an error fails the request. ```go type UserInputHandler func(request UserInputRequest, invocation UserInputInvocation) (UserInputResponse, error) ``` ## type [UserInputInvocation]() UserInputInvocation provides context about a user input request ```go type UserInputInvocation struct { SessionID string } ``` ## type [UserInputRequest]() UserInputRequest represents a request for user input from the agent ```go type UserInputRequest struct { Question string Choices []string AllowFreeform *bool } ``` ## type [UserInputResponse]() UserInputResponse represents the user's response to an input request ```go type UserInputResponse struct { Answer string WasFreeform bool } ``` ## type [UserPromptSubmittedHandler]() UserPromptSubmittedHandler handles user\-prompt\-submitted hook invocations ```go type UserPromptSubmittedHandler func(input UserPromptSubmittedHookInput, invocation HookInvocation) (*UserPromptSubmittedHookOutput, error) ``` ## type [UserPromptSubmittedHookInput]() UserPromptSubmittedHookInput is the input for a user\-prompt\-submitted hook ```go type UserPromptSubmittedHookInput struct { Timestamp int64 `json:"timestamp"` Cwd string `json:"cwd"` Prompt string `json:"prompt"` } ``` ## type [UserPromptSubmittedHookOutput]() UserPromptSubmittedHookOutput is the output for a user\-prompt\-submitted hook ```go type UserPromptSubmittedHookOutput struct { ModifiedPrompt string `json:"modifiedPrompt,omitempty"` AdditionalContext string `json:"additionalContext,omitempty"` SuppressOutput bool `json:"suppressOutput,omitempty"` } ``` # jsonrpc2 ```go import "github.com/github/copilot-sdk/go/internal/jsonrpc2" ``` ## Index - [type Client](<#Client>) - [func NewClient\(stdin io.WriteCloser, stdout io.ReadCloser\) \*Client](<#NewClient>) - [func \(c \*Client\) Notify\(method string, params any\) error](<#Client.Notify>) - [func \(c \*Client\) Request\(method string, params any\) \(json.RawMessage, error\)](<#Client.Request>) - [func \(c \*Client\) SetRequestHandler\(method string, handler RequestHandler\)](<#Client.SetRequestHandler>) - [func \(c \*Client\) Start\(\)](<#Client.Start>) - [func \(c \*Client\) Stop\(\)](<#Client.Stop>) - [type Error](<#Error>) - [func \(e \*Error\) Error\(\) string](<#Error.Error>) - [type NotificationHandler](<#NotificationHandler>) - [type Request](<#Request>) - [func \(r \*Request\) IsCall\(\) bool](<#Request.IsCall>) - [type RequestHandler](<#RequestHandler>) - [func NotificationHandlerFor\[In any\]\(handler func\(params In\)\) RequestHandler](<#NotificationHandlerFor>) - [func RequestHandlerFor\[In, Out any\]\(handler func\(params In\) \(Out, \*Error\)\) RequestHandler](<#RequestHandlerFor>) - [type Response](<#Response>) ## type [Client]() Client is a minimal JSON\-RPC 2.0 client for stdio transport ```go type Client struct { // contains filtered or unexported fields } ``` ### func [NewClient]() ```go func NewClient(stdin io.WriteCloser, stdout io.ReadCloser) *Client ``` NewClient creates a new JSON\-RPC client ### func \(\*Client\) [Notify]() ```go func (c *Client) Notify(method string, params any) error ``` Notify sends a JSON\-RPC notification \(no response expected\) ### func \(\*Client\) [Request]() ```go func (c *Client) Request(method string, params any) (json.RawMessage, error) ``` Request sends a JSON\-RPC request and waits for the response ### func \(\*Client\) [SetRequestHandler]() ```go func (c *Client) SetRequestHandler(method string, handler RequestHandler) ``` SetRequestHandler registers a handler for incoming requests from the server ### func \(\*Client\) [Start]() ```go func (c *Client) Start() ``` Start begins listening for messages in a background goroutine ### func \(\*Client\) [Stop]() ```go func (c *Client) Stop() ``` Stop stops the client and cleans up ## type [Error]() Error represents a JSON\-RPC error response ```go type Error struct { Code int `json:"code"` Message string `json:"message"` Data map[string]any `json:"data,omitempty"` } ``` ### func \(\*Error\) [Error]() ```go func (e *Error) Error() string ``` ## type [NotificationHandler]() NotificationHandler handles incoming notifications ```go type NotificationHandler func(method string, params json.RawMessage) ``` ## type [Request]() Request represents a JSON\-RPC 2.0 request ```go type Request struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id"` // nil for notifications Method string `json:"method"` Params json.RawMessage `json:"params"` } ``` ### func \(\*Request\) [IsCall]() ```go func (r *Request) IsCall() bool ``` ## type [RequestHandler]() RequestHandler handles incoming server requests and returns a result or error ```go type RequestHandler func(params json.RawMessage) (json.RawMessage, *Error) ``` ### func [NotificationHandlerFor]() ```go func NotificationHandlerFor[In any](handler func(params In)) RequestHandler ``` ### func [RequestHandlerFor]() ```go func RequestHandlerFor[In, Out any](handler func(params In) (Out, *Error)) RequestHandler ``` RequestHandlerFor creates a RequestHandler from a typed function ## type [Response]() Response represents a JSON\-RPC 2.0 response ```go type Response struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` Result json.RawMessage `json:"result,omitempty"` Error *Error `json:"error,omitempty"` } ``` # testharness ```go import "github.com/github/copilot-sdk/go/internal/e2e/testharness" ``` ## Index - [func CLIPath\(\) string](<#CLIPath>) - [func GetFinalAssistantMessage\(ctx context.Context, session \*copilot.Session\) \(\*copilot.SessionEvent, error\)](<#GetFinalAssistantMessage>) - [func GetNextEventOfType\(session \*copilot.Session, eventType copilot.SessionEventType, timeout time.Duration\) \(\*copilot.SessionEvent, error\)](<#GetNextEventOfType>) - [type CapiProxy](<#CapiProxy>) - [func NewCapiProxy\(\) \*CapiProxy](<#NewCapiProxy>) - [func \(p \*CapiProxy\) Configure\(filePath, workDir string\) error](<#CapiProxy.Configure>) - [func \(p \*CapiProxy\) GetExchanges\(\) \(\[\]ParsedHttpExchange, error\)](<#CapiProxy.GetExchanges>) - [func \(p \*CapiProxy\) Start\(\) \(string, error\)](<#CapiProxy.Start>) - [func \(p \*CapiProxy\) Stop\(\) error](<#CapiProxy.Stop>) - [func \(p \*CapiProxy\) StopWithOptions\(skipWritingCache bool\) error](<#CapiProxy.StopWithOptions>) - [func \(p \*CapiProxy\) URL\(\) string](<#CapiProxy.URL>) - [type ChatCompletionChoice](<#ChatCompletionChoice>) - [type ChatCompletionMessage](<#ChatCompletionMessage>) - [type ChatCompletionRequest](<#ChatCompletionRequest>) - [type ChatCompletionResponse](<#ChatCompletionResponse>) - [type ChatCompletionTool](<#ChatCompletionTool>) - [type ChatCompletionToolFunction](<#ChatCompletionToolFunction>) - [type FunctionCall](<#FunctionCall>) - [type Message](<#Message>) - [type ParsedHttpExchange](<#ParsedHttpExchange>) - [type TestContext](<#TestContext>) - [func NewTestContext\(t \*testing.T\) \*TestContext](<#NewTestContext>) - [func \(c \*TestContext\) Close\(testFailed bool\)](<#TestContext.Close>) - [func \(c \*TestContext\) ConfigureForTest\(t \*testing.T\)](<#TestContext.ConfigureForTest>) - [func \(c \*TestContext\) Env\(\) \[\]string](<#TestContext.Env>) - [func \(c \*TestContext\) GetExchanges\(\) \(\[\]ParsedHttpExchange, error\)](<#TestContext.GetExchanges>) - [func \(c \*TestContext\) NewClient\(\) \*copilot.Client](<#TestContext.NewClient>) - [type ToolCall](<#ToolCall>) ## func [CLIPath]() ```go func CLIPath() string ``` CLIPath returns the path to the Copilot CLI, discovering it once and caching. ## func [GetFinalAssistantMessage]() ```go func GetFinalAssistantMessage(ctx context.Context, session *copilot.Session) (*copilot.SessionEvent, error) ``` GetFinalAssistantMessage waits for and returns the final assistant message from a session turn. ## func [GetNextEventOfType]() ```go func GetNextEventOfType(session *copilot.Session, eventType copilot.SessionEventType, timeout time.Duration) (*copilot.SessionEvent, error) ``` GetNextEventOfType waits for and returns the next event of the specified type from a session. ## type [CapiProxy]() CapiProxy manages a child process that acts as a replaying proxy to AI endpoints. It spawns the shared test harness server from test/harness/server.ts. ```go type CapiProxy struct { // contains filtered or unexported fields } ``` ### func [NewCapiProxy]() ```go func NewCapiProxy() *CapiProxy ``` NewCapiProxy creates a new proxy instance. ### func \(\*CapiProxy\) [Configure]() ```go func (p *CapiProxy) Configure(filePath, workDir string) error ``` Configure sends configuration to the proxy. ### func \(\*CapiProxy\) [GetExchanges]() ```go func (p *CapiProxy) GetExchanges() ([]ParsedHttpExchange, error) ``` GetExchanges retrieves the captured HTTP exchanges from the proxy. ### func \(\*CapiProxy\) [Start]() ```go func (p *CapiProxy) Start() (string, error) ``` Start launches the proxy server and returns its URL. ### func \(\*CapiProxy\) [Stop]() ```go func (p *CapiProxy) Stop() error ``` Stop gracefully shuts down the proxy server. ### func \(\*CapiProxy\) [StopWithOptions]() ```go func (p *CapiProxy) StopWithOptions(skipWritingCache bool) error ``` StopWithOptions gracefully shuts down the proxy server. If skipWritingCache is true, the proxy won't write captured exchanges to disk. ### func \(\*CapiProxy\) [URL]() ```go func (p *CapiProxy) URL() string ``` URL returns the proxy URL, or empty if not started. ## type [ChatCompletionChoice]() ChatCompletionChoice represents a choice in the response. ```go type ChatCompletionChoice struct { Index int `json:"index"` Message ChatCompletionMessage `json:"message"` FinishReason string `json:"finish_reason"` } ``` ## type [ChatCompletionMessage]() ChatCompletionMessage represents a message in the chat completion request. ```go type ChatCompletionMessage struct { Role string `json:"role"` Content string `json:"content,omitempty"` ToolCallID string `json:"tool_call_id,omitempty"` ToolCalls []ToolCall `json:"tool_calls,omitempty"` } ``` ## type [ChatCompletionRequest]() ChatCompletionRequest represents an OpenAI chat completion request. ```go type ChatCompletionRequest struct { Model string `json:"model"` Messages []ChatCompletionMessage `json:"messages"` Tools []ChatCompletionTool `json:"tools,omitempty"` } ``` ## type [ChatCompletionResponse]() ChatCompletionResponse represents an OpenAI chat completion response. ```go type ChatCompletionResponse struct { ID string `json:"id"` Model string `json:"model"` Choices []ChatCompletionChoice `json:"choices"` } ``` ## type [ChatCompletionTool]() ChatCompletionTool represents a tool in the chat completion request. ```go type ChatCompletionTool struct { Type string `json:"type"` Function ChatCompletionToolFunction `json:"function"` } ``` ## type [ChatCompletionToolFunction]() ChatCompletionToolFunction represents a function tool. ```go type ChatCompletionToolFunction struct { Name string `json:"name"` Description string `json:"description,omitempty"` } ``` ## type [FunctionCall]() FunctionCall represents the function details in a tool call. ```go type FunctionCall struct { Name string `json:"name"` Arguments string `json:"arguments"` } ``` ## type [Message]() Message is an alias for ChatCompletionMessage for test convenience. ```go type Message = ChatCompletionMessage ``` ## type [ParsedHttpExchange]() ParsedHttpExchange represents a captured HTTP exchange. ```go type ParsedHttpExchange struct { Request ChatCompletionRequest `json:"request"` Response *ChatCompletionResponse `json:"response,omitempty"` } ``` ## type [TestContext]() TestContext holds shared resources for E2E tests. ```go type TestContext struct { CLIPath string HomeDir string WorkDir string ProxyURL string // contains filtered or unexported fields } ``` ### func [NewTestContext]() ```go func NewTestContext(t *testing.T) *TestContext ``` NewTestContext creates a new test context with isolated directories and a replaying proxy. ### func \(\*TestContext\) [Close]() ```go func (c *TestContext) Close(testFailed bool) ``` Close cleans up the test context resources. ### func \(\*TestContext\) [ConfigureForTest]() ```go func (c *TestContext) ConfigureForTest(t *testing.T) ``` ConfigureForTest configures the proxy for a specific subtest. Call this at the start of each t.Run subtest. ### func \(\*TestContext\) [Env]() ```go func (c *TestContext) Env() []string ``` Env returns environment variables configured for isolated testing. ### func \(\*TestContext\) [GetExchanges]() ```go func (c *TestContext) GetExchanges() ([]ParsedHttpExchange, error) ``` GetExchanges retrieves the captured HTTP exchanges from the proxy. ### func \(\*TestContext\) [NewClient]() ```go func (c *TestContext) NewClient() *copilot.Client ``` NewClient creates a CopilotClient configured for this test context. ## type [ToolCall]() ToolCall represents a tool call in an assistant message. ```go type ToolCall struct { ID string `json:"id"` Type string `json:"type"` Function FunctionCall `json:"function"` } ``` Generated by [gomarkdoc]()