This package is not in the latest version of its module.
Go to latest Published: Apr 24, 2026 License: MITThe Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Modules with tagged versions give importers more predictable builds.
When a project reaches major version v1 it is considered stable.
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.
Constant aliases for convenience.
Known system prompt section identifiers for the "customize" mode.
SdkProtocolVersion is the SDK protocol version. This must match the version expected by the copilot-agent-runtime server.
PermissionHandler provides pre-built OnPermissionRequest implementations.
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)Float64 returns a pointer to the given float64 value. Use for setting thresholds: BackgroundCompactionThreshold: Float64(0.80)
GetSdkProtocolVersion returns the SDK protocol version.
Int returns a pointer to the given int value. Use for setting optional int parameters: MinLength: Int(1)
String returns a pointer to the given string value. Use for setting optional string parameters in RPC calls.
Turn abort information including the reason for termination
Agent intent description for current activity or plan
Assistant response containing text content, optional tool requests, and interaction metadata
Streaming assistant message delta for incremental response updates
A tool invocation request from the assistant
Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent.
Assistant reasoning content for timeline display with complete thinking text
Streaming reasoning delta for incremental extended thinking updates
Streaming response progress with cumulative byte count
Turn completion metadata including the turn identifier
Turn initialization metadata including identifier and interaction tracking
Per-request cost and usage data from the CAPI copilot_usage response field
Token usage detail for a single billing category
LLM API call usage metrics including tokens, costs, quotas, and billing information
Type aliases for convenience.
Auto mode switch completion notification
Auto mode switch request notification requiring user approval
AzureProviderOptions contains Azure-specific provider configuration
Session capability change notification
UI capability changes
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()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", })ActualPort returns the TCP port the CLI server is listening on. Returns 0 if the client is not connected or using stdio transport.
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) }ForceStop forcefully stops the CLI server without graceful cleanup.
Use this when Client.Stop fails or takes too long. This method:
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() }GetAuthStatus returns current authentication status
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) }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, }) }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) }GetStatus returns CLI status including version and protocol information
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.
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"})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()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()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) }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, })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}, })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) }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 sessionsState 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, }) }Stop stops the CLI server and closes all active sessions.
This method performs graceful cleanup:
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) }ClientOptions configures the CopilotClient
Queued command completion notification signaling UI dismissal
CommandContext provides context about a slash-command invocation.
CommandDefinition registers a slash-command. Name is shown in the CLI TUI as /name for the user to invoke.
Registered command dispatch request routed to the owning client
CommandHandler is invoked when a registered slash-command is executed.
Queued slash command dispatch request for client execution
SDK command registration change notification
Token usage breakdown for the compaction LLM call (aligned with assistant.usage format)
Per-request cost and usage data from the CAPI copilot_usage response field
Token usage detail for a single billing category
ConnectionState represents the client connection state
CustomAgentConfig configures a custom agent
DefaultAgentConfig configures the default agent (the built-in agent that handles turns when no custom agent is selected). Use ExcludedTools to hide specific tools from the default agent while keeping them available to custom sub-agents.
The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed)
Elicitation request completion with the user's response
ElicitationContext describes an elicitation request from the server, combining the request data with session context. Mirrors the single-argument pattern of CommandContext.
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.
Elicitation request; may be form-based (structured input) or URL-based (browser redirect)
Elicitation mode; "form" for structured input, "url" for browser-based. Defaults to "form" when absent.
JSON Schema describing the form fields to present to the user (form mode only)
ElicitationResult is the user's response to an elicitation dialog.
ErrorOccurredHandler handles error-occurred hook invocations
ErrorOccurredHookInput is the input for an error-occurred hook
ErrorOccurredHookOutput is the output for an error-occurred hook
Plan mode exit completion with the user's approval decision and optional feedback
Plan approval request with plan content and available user actions
Discovery source
Current status: running, disabled, failed, or starting
External tool completion notification signaling UI dismissal
External tool invocation request for client-side tool execution
GetAuthStatusResponse is the response from auth.getStatus
GetStatusResponse is the response from status.get
Repository context for the handed-off session
Origin type of the session being handed off
Hook invocation completion details including output, success status, and error information
Error details when the hook failed
HookInvocation provides context about a hook invocation
Hook invocation start details including type and input data
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.
InputOptions configures a text input field for the Input convenience method.
MCPHTTPServerConfig configures a remote MCP server (HTTP or SSE).
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
MCPServerConfig is implemented by MCP server configuration types. Only MCPStdioServerConfig and MCPHTTPServerConfig implement this interface.
MCPStdioServerConfig configures a local/stdio MCP server.
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
MCP OAuth request completion notification
OAuth authentication request for an MCP server
Static OAuth client configuration, if the server specifies one
New connection status: connected, failed, needs-auth, pending, disabled, or not_configured
Connection status: connected, failed, needs-auth, pending, disabled, or not_configured
MessageOptions configures a message to send
ModelBilling contains model billing information
ModelCapabilities contains model capabilities and limits
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
ModelInfo contains information about an available model
ModelLimits contains model limits
ModelPolicy contains model policy state
ModelSupports contains model support flags
ModelVisionLimits contains vision-specific limits
Empty payload; the event signals that the pending message queue has changed
Permission request completion notification signaling UI dismissal
The outcome of the permission request
The result of the permission request
PermissionHandlerFunc executes a permission request The handler should return a PermissionRequestResult. Returning an error denies the permission.
PermissionInvocation provides context about a permission request
Derived user-facing permission prompt details for UI consumers
Kind discriminator for PermissionPromptRequest.
Whether this is a store or vote memory operation
Vote direction (vote only)
Underlying permission kind that needs path approval
Details of the permission being requested
Type aliases for convenience.
Kind discriminator for PermissionRequest.
Whether this is a store or vote memory operation
Vote direction (vote only)
PermissionRequestResult represents the result of a permission request
PermissionRequestResultKind represents the kind of a permission request result.
Permission request notification requiring client approval with request details
PingResponse is the response from a ping request
The type of operation performed on the plan file
Type aliases for convenience.
PostToolUseHandler handles post-tool-use hook invocations
PostToolUseHookInput is the input for a post-tool-use hook
PostToolUseHookOutput is the output for a post-tool-use hook
PreToolUseHandler handles pre-tool-use hook invocations
PreToolUseHookInput is the input for a pre-tool-use hook
PreToolUseHookOutput is the output for a pre-tool-use hook
RawSessionEventData holds unparsed JSON data for unrecognized event types.
MarshalJSON returns the original raw JSON so round-tripping preserves the payload.
ResumeSessionConfig configures options when resuming a session
Sampling request completion notification signaling UI dismissal
Sampling request from an MCP server; contains the server name and a requestId for correlation
SectionOverride defines an override operation for a single system prompt section.
SectionOverrideAction represents the action to perform on a system prompt section.
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.
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!", })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) }Capabilities returns the session capabilities reported by the server.
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.
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) }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) } }Log sends a log message to the session timeline. The message appears in the session event stream and is visible to SDK consumers and (for non-ephemeral messages) persisted to the session event log on disk.
Pass nil for opts to use defaults (info level, non-ephemeral).
Example:
// Simple info message session.Log(ctx, "Processing started") // Warning with options session.Log(ctx, "Rate limit approaching", &copilot.LogOptions{Level: rpc.SessionLogLevelWarning}) // Ephemeral message (not persisted) session.Log(ctx, "Working...", &copilot.LogOptions{Ephemeral: copilot.Bool(true)})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()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:
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) }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:
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) } }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) }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).
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.
SessionBackgroundTasksChangedData holds the payload for session.background_tasks_changed events.
SessionCapabilities describes what features the host supports.
Conversation compaction results including success status, metrics, and optional error details
Context window breakdown at the start of LLM-powered conversation compaction
SessionConfig configures a new session
SessionContext contains working directory context for a session
Working directory and git context at session start
SessionCustomAgentsUpdatedData holds the payload for session.custom_agents_updated events.
SessionEndHandler handles session-end hook invocations
SessionEndHookInput is the input for a session-end hook
SessionEndHookOutput is the output for a session-end hook
Error details for timeline display including message and optional diagnostic information
SessionEvent represents a single session event with a typed data payload.
UnmarshalSessionEvent parses JSON bytes into a SessionEvent.
SessionEventData is the interface implemented by all per-event data types.
SessionEventHandler is a callback for session events
SessionEventType identifies the kind of session event.
SessionExtensionsLoadedData holds the payload for session.extensions_loaded events.
SessionFsConfig configures a custom session filesystem provider.
SessionFsFileInfo holds file metadata returned by SessionFsProvider.Stat.
SessionFsProvider is the interface that SDK users implement to provide a session filesystem. Methods use idiomatic Go error handling: return an error for failures (the adapter maps os.ErrNotExist → ENOENT automatically).
Session handoff metadata including source, context, and repository information
SessionHooks configures hook handlers for a session
Payload indicating the session is idle with no background agents in flight
Informational message for timeline display with categorization
SessionLifecycleEvent represents a session lifecycle notification
SessionLifecycleEventMetadata contains optional metadata for lifecycle events
SessionLifecycleEventType represents the type of session lifecycle event
SessionLifecycleHandler is a callback for session lifecycle events
SessionListFilter contains filter options for listing sessions
SessionMcpServerStatusChangedData holds the payload for session.mcp_server_status_changed events.
SessionMcpServersLoadedData holds the payload for session.mcp_servers_loaded events.
SessionMetadata contains metadata about a session
Agent mode change details including previous and new modes
Model change details including previous and new model identifiers
Plan file operation details indicating what changed
Notifies Mission Control that the session's remote steering capability has changed
Session resume metadata including current context and event count
Session termination metrics including usage statistics, code changes, and shutdown reason
SessionSkillsLoadedData holds the payload for session.skills_loaded events.
Session rewind details including target event and count of removed events
Session initialization metadata including context and configuration
SessionStartHandler handles session-start hook invocations
SessionStartHookInput is the input for a session-start hook
SessionStartHookOutput is the output for a session-start hook
Task completion notification with summary from the agent
Session title change payload containing the new display title
SessionToolsUpdatedData holds the payload for session.tools_updated events.
Conversation truncation statistics including token counts and removed content metrics
SessionUI provides convenience methods for showing elicitation dialogs to the user. Obtained via Session.UI. Methods error if the host does not support elicitation.
Confirm shows a confirmation dialog and returns the user's boolean answer. Returns false if the user declines or cancels.
Elicitation shows a generic elicitation dialog with a custom schema.
Current context window usage statistics including token and message counts
Warning message for timeline display with categorization
Workspace file change details including path and operation type
SetModelOptions configures optional parameters for SetModel.
Aggregate code change metrics for the session
Request count and cost metrics
Token usage breakdown
Whether the session ended normally ("routine") or due to a crash/fatal error ("error")
Skill invocation details including content, allowed tools, and plugin metadata
Sub-agent completion details for successful execution
Empty payload; the event signals that the custom agent was deselected, returning to the default agent
Sub-agent failure details including error message and agent information
Custom agent selection details including name and available tools
Sub-agent startup details including parent tool call and agent information
SystemMessageAppendConfig is append mode: use CLI foundation with optional appended content.
SystemMessageConfig represents system message configuration for session creation.
In Go, use one struct and set fields appropriate for the desired mode.
System/developer instruction content with role and optional template metadata
Metadata about the prompt template and its construction
SystemMessageReplaceConfig is replace mode: use caller-provided system message entirely. Removes all SDK guardrails including security restrictions.
Message role: "system" for system prompts, "developer" for developer-injected instructions
Structured metadata identifying what triggered this notification
Whether the agent completed successfully or failed
System-generated notification for runtime events like background task completion
Type discriminator for SystemNotification.
TelemetryConfig configures OpenTelemetry integration for the Copilot CLI process.
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 })ToolBinaryResult represents binary payloads returned by tools.
A content block within a tool result, which may be text, terminal output, image, audio, or a resource
Icon image for a resource
Theme variant this icon is intended for
Type discriminator for ToolExecutionCompleteContent.
Tool execution completion results including success status, detailed output, and error information
Error details when the tool execution failed
Tool execution result on success
Streaming tool execution output for incremental result display
Tool execution progress notification with status message
Tool execution startup details including MCP server information when applicable
ToolHandler executes a tool invocation. The handler should return a ToolResult. Returning an error marks the tool execution as a failure.
ToolInvocation describes a tool call initiated by Copilot
ToolResult represents the result of a tool invocation.
ConvertMCPCallToolResult converts an MCP CallToolResult value (a map or struct with a "content" array and optional "isError" bool) into a ToolResult. Returns the converted ToolResult and true if the value matched the expected shape, or a zero ToolResult and false otherwise.
User-initiated tool invocation request with tool name and arguments
UICapabilities describes host UI feature support.
User input request completion with the user's response
UserInputHandler handles user input requests from the agent The handler should return a UserInputResponse. Returning an error fails the request.
UserInputInvocation provides context about a user input request
UserInputRequest represents a request for user input from the agent
User input request notification with question and optional predefined choices
UserInputResponse represents the user's response to an input request
The agent mode that was active when this message was sent
A user message attachment — a file, directory, code selection, blob, or GitHub reference
Optional line range to scope the attachment to a specific section of the file
Type of GitHub reference
Position range of the selection within the file
End position of the selection
Start position of the selection
Type discriminator for UserMessageAttachment.
UserMessageData holds the payload for user.message events.
UserPromptSubmittedHandler handles user-prompt-submitted hook invocations
UserPromptSubmittedHookInput is the input for a user-prompt-submitted hook
UserPromptSubmittedHookOutput is the output for a user-prompt-submitted hook
Working directory and git context at session start
Hosting platform type of the repository (github or ado)
Whether the file was newly created or updated
|
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
|
| ? | : This menu |
| / | : Search site |
| f or F | : Jump to |
| y or Y | : Canonical URL |