copilot

package module
v0.1.32 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 20 Imported by: 0

README

Copilot CLI SDK for Go

A Go SDK for programmatic access to the GitHub Copilot CLI.

Note: This SDK is in technical preview and may change in breaking ways.

Installation

go get github.com/github/copilot-sdk/go

Run the Sample

Try the interactive chat sample (from the repo root):

cd go/samples
go run chat.go

Quick Start

package main

import (
	"context"
    "fmt"
    "log"

    copilot "github.com/github/copilot-sdk/go"
)

func main() {
    // Create client
    client := copilot.NewClient(&copilot.ClientOptions{
        LogLevel: "error",
    })

    // Start the client
    if err := client.Start(context.Background()); err != nil {
        log.Fatal(err)
    }
    defer client.Stop()

    // Create a session
    session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
        Model: "gpt-5",
    })
    if err != nil {
        log.Fatal(err)
    }
    defer session.Disconnect()

    // Set up event handler
    done := make(chan bool)
    session.On(func(event copilot.SessionEvent) {
        if event.Type == "assistant.message" {
            if event.Data.Content != nil {
                fmt.Println(*event.Data.Content)
            }
        }
        if event.Type == "session.idle" {
            close(done)
        }
    })

    // Send a message
    _, err = session.Send(context.Background(), copilot.MessageOptions{
        Prompt: "What is 2+2?",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Wait for completion
    <-done
}

Distributing your application with an embedded GitHub Copilot CLI

The SDK supports bundling, using Go's embed package, the Copilot CLI binary within your application's distribution. This allows you to bundle a specific CLI version and avoid external dependencies on the user's system.

Follow these steps to embed the CLI:

  1. Run go get -tool github.com/github/copilot-sdk/go/cmd/bundler. This is a one-time setup step per project.
  2. Run go tool bundler in your build environment just before building your application.

That's it! When your application calls copilot.NewClient without a CLIPath nor the COPILOT_CLI_PATH environment variable, the SDK will automatically install the embedded CLI to a cache directory and use it for all operations.

API Reference

Client
  • NewClient(options *ClientOptions) *Client - Create a new client
  • Start(ctx context.Context) error - Start the CLI server
  • Stop() error - Stop the CLI server
  • ForceStop() - Forcefully stop without graceful cleanup
  • CreateSession(config *SessionConfig) (*Session, error) - Create a new session
  • ResumeSession(sessionID string, config *ResumeSessionConfig) (*Session, error) - Resume an existing session
  • ResumeSessionWithOptions(sessionID string, config *ResumeSessionConfig) (*Session, error) - Resume with additional configuration
  • ListSessions(filter *SessionListFilter) ([]SessionMetadata, error) - List sessions (with optional filter)
  • DeleteSession(sessionID string) error - Delete a session permanently
  • GetLastSessionID(ctx context.Context) (*string, error) - Get the ID of the most recently updated session
  • GetState() ConnectionState - Get connection state
  • Ping(message string) (*PingResponse, error) - Ping the server
  • GetForegroundSessionID(ctx context.Context) (*string, error) - Get the session ID currently displayed in TUI (TUI+server mode only)
  • SetForegroundSessionID(ctx context.Context, sessionID string) error - Request TUI to display a specific session (TUI+server mode only)
  • On(handler SessionLifecycleHandler) func() - Subscribe to all lifecycle events; returns unsubscribe function
  • OnEventType(eventType SessionLifecycleEventType, handler SessionLifecycleHandler) func() - Subscribe to specific lifecycle event type

Session Lifecycle Events:

// Subscribe to all lifecycle events
unsubscribe := client.On(func(event copilot.SessionLifecycleEvent) {
    fmt.Printf("Session %s: %s\n", event.SessionID, event.Type)
})
defer unsubscribe()

// Subscribe to specific event type
unsubscribe := client.OnEventType(copilot.SessionLifecycleForeground, func(event copilot.SessionLifecycleEvent) {
    fmt.Printf("Session %s is now in foreground\n", event.SessionID)
})

Event types: SessionLifecycleCreated, SessionLifecycleDeleted, SessionLifecycleUpdated, SessionLifecycleForeground, SessionLifecycleBackground

ClientOptions:

  • CLIPath (string): Path to CLI executable (default: "copilot" or COPILOT_CLI_PATH env var)
  • CLIUrl (string): URL of existing CLI server (e.g., "localhost:8080", "http://127.0.0.1:9000", or just "8080"). When provided, the client will not spawn a CLI process.
  • Cwd (string): Working directory for CLI process
  • Port (int): Server port for TCP mode (default: 0 for random)
  • UseStdio (bool): Use stdio transport instead of TCP (default: true)
  • LogLevel (string): Log level (default: "info")
  • AutoStart (*bool): Auto-start server on first use (default: true). Use Bool(false) to disable.
  • AutoRestart (*bool): Auto-restart on crash (default: true). Use Bool(false) to disable.
  • Env ([]string): Environment variables for CLI process (default: inherits from current process)
  • GitHubToken (string): GitHub token for authentication. When provided, takes priority over other auth methods.
  • UseLoggedInUser (*bool): Whether to use logged-in user for authentication (default: true, but false when GitHubToken is provided). Cannot be used with CLIUrl.

SessionConfig:

  • Model (string): Model to use ("gpt-5", "claude-sonnet-4.5", etc.). Required when using custom provider.
  • ReasoningEffort (string): Reasoning effort level for models that support it ("low", "medium", "high", "xhigh"). Use ListModels() to check which models support this option.
  • SessionID (string): Custom session ID
  • Tools ([]Tool): Custom tools exposed to the CLI
  • SystemMessage (*SystemMessageConfig): System message configuration
  • Provider (*ProviderConfig): Custom API provider configuration (BYOK). See Custom Providers section.
  • Streaming (bool): Enable streaming delta events
  • InfiniteSessions (*InfiniteSessionConfig): Automatic context compaction configuration
  • OnUserInputRequest (UserInputHandler): Handler for user input requests from the agent (enables ask_user tool). See User Input Requests section.
  • Hooks (*SessionHooks): Hook handlers for session lifecycle events. See Session Hooks section.

ResumeSessionConfig:

  • Tools ([]Tool): Tools to expose when resuming
  • ReasoningEffort (string): Reasoning effort level for models that support it
  • Provider (*ProviderConfig): Custom API provider configuration (BYOK). See Custom Providers section.
  • Streaming (bool): Enable streaming delta events
Session
  • Send(ctx context.Context, options MessageOptions) (string, error) - Send a message
  • On(handler SessionEventHandler) func() - Subscribe to events (returns unsubscribe function)
  • Abort(ctx context.Context) error - Abort the currently processing message
  • GetMessages(ctx context.Context) ([]SessionEvent, error) - Get message history
  • Disconnect() error - Disconnect the session (releases in-memory resources, preserves disk state)
  • Destroy() error - (Deprecated) Use Disconnect() instead
Helper Functions
  • Bool(v bool) *bool - Helper to create bool pointers for AutoStart/AutoRestart options

Image Support

The SDK supports image attachments via the Attachments field in MessageOptions. You can attach images by providing their file path:

_, err = session.Send(context.Background(), copilot.MessageOptions{
    Prompt: "What's in this image?",
    Attachments: []copilot.Attachment{
        {
            Type: "file",
            Path: "/path/to/image.jpg",
        },
    },
})

Supported image formats include JPG, PNG, GIF, and other common image types. The agent's view tool can also read images directly from the filesystem, so you can also ask questions like:

_, err = session.Send(context.Background(), copilot.MessageOptions{
    Prompt: "What does the most recent jpg in this directory portray?",
})
Tools

Expose your own functionality to Copilot by attaching tools to a session.

Use DefineTool for type-safe tools with automatic JSON schema generation:

type LookupIssueParams struct {
    ID string `json:"id" jsonschema:"Issue identifier"`
}

lookupIssue := copilot.DefineTool("lookup_issue", "Fetch issue details from our tracker",
    func(params LookupIssueParams, inv copilot.ToolInvocation) (any, error) {
        // params is automatically unmarshaled from the LLM's arguments
        issue, err := fetchIssue(params.ID)
        if err != nil {
            return nil, err
        }
        return issue.Summary, nil
    })

session, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-5",
    Tools: []copilot.Tool{lookupIssue},
})
Using Tool struct directly

For more control over the JSON schema, use the Tool struct directly:

lookupIssue := copilot.Tool{
    Name:        "lookup_issue",
    Description: "Fetch issue details from our tracker",
    Parameters: map[string]any{
        "type": "object",
        "properties": map[string]any{
            "id": map[string]any{
                "type":        "string",
                "description": "Issue identifier",
            },
        },
        "required": []string{"id"},
    },
    Handler: func(invocation copilot.ToolInvocation) (copilot.ToolResult, error) {
        args := invocation.Arguments.(map[string]any)
        issue, err := fetchIssue(args["id"].(string))
        if err != nil {
            return copilot.ToolResult{}, err
        }
        return copilot.ToolResult{
            TextResultForLLM: issue.Summary,
            ResultType:       "success",
            SessionLog:       fmt.Sprintf("Fetched issue %s", issue.ID),
        }, nil
    },
}

session, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-5",
    Tools: []copilot.Tool{lookupIssue},
})

When the model selects a tool, the SDK automatically runs your handler (in parallel with other calls) and responds to the CLI's tool.call with the handler's result.

Overriding Built-in Tools

If you register a tool with the same name as a built-in CLI tool (e.g. edit_file, read_file), the SDK will throw an error unless you explicitly opt in by setting OverridesBuiltInTool = true. This flag signals that you intend to replace the built-in tool with your custom implementation.

editFile := copilot.DefineTool("edit_file", "Custom file editor with project-specific validation",
    func(params EditFileParams, inv copilot.ToolInvocation) (any, error) {
        // your logic
    })
editFile.OverridesBuiltInTool = true

Streaming

Enable streaming to receive assistant response chunks as they're generated:

package main

import (
	"context"
    "fmt"
    "log"

    copilot "github.com/github/copilot-sdk/go"
)

func main() {
    client := copilot.NewClient(nil)

    if err := client.Start(context.Background()); err != nil {
        log.Fatal(err)
    }
    defer client.Stop()

    session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
        Model:     "gpt-5",
        Streaming: true,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer session.Disconnect()

    done := make(chan bool)

    session.On(func(event copilot.SessionEvent) {
        if event.Type == "assistant.message_delta" {
            // Streaming message chunk - print incrementally
            if event.Data.DeltaContent != nil {
                fmt.Print(*event.Data.DeltaContent)
            }
        } else if event.Type == "assistant.reasoning_delta" {
            // Streaming reasoning chunk (if model supports reasoning)
            if event.Data.DeltaContent != nil {
                fmt.Print(*event.Data.DeltaContent)
            }
        } else if event.Type == "assistant.message" {
            // Final message - complete content
            fmt.Println("\n--- Final message ---")
            if event.Data.Content != nil {
                fmt.Println(*event.Data.Content)
            }
        } else if event.Type == "assistant.reasoning" {
            // Final reasoning content (if model supports reasoning)
            fmt.Println("--- Reasoning ---")
            if event.Data.Content != nil {
                fmt.Println(*event.Data.Content)
            }
        }
        if event.Type == "session.idle" {
            close(done)
        }
    })

    _, err = session.Send(context.Background(), copilot.MessageOptions{
        Prompt: "Tell me a short story",
    })
    if err != nil {
        log.Fatal(err)
    }

    <-done
}

When Streaming: true:

  • assistant.message_delta events are sent with DeltaContent containing incremental text
  • assistant.reasoning_delta events are sent with DeltaContent for reasoning/chain-of-thought (model-dependent)
  • Accumulate DeltaContent values to build the full response progressively
  • The final assistant.message and assistant.reasoning events contain the complete content

Note: assistant.message and assistant.reasoning (final events) are always sent regardless of streaming setting.

Infinite Sessions

By default, sessions use infinite sessions which automatically manage context window limits through background compaction and persist state to a workspace directory.

// Default: infinite sessions enabled with default thresholds
session, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-5",
})

// Access the workspace path for checkpoints and files
fmt.Println(session.WorkspacePath())
// => ~/.copilot/session-state/{sessionId}/

// Custom thresholds
session, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-5",
    InfiniteSessions: &copilot.InfiniteSessionConfig{
        Enabled:                       copilot.Bool(true),
        BackgroundCompactionThreshold: copilot.Float64(0.80), // Start compacting at 80% context usage
        BufferExhaustionThreshold:     copilot.Float64(0.95), // Block at 95% until compaction completes
    },
})

// Disable infinite sessions
session, _ := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-5",
    InfiniteSessions: &copilot.InfiniteSessionConfig{
        Enabled: copilot.Bool(false),
    },
})

When enabled, sessions emit compaction events:

  • session.compaction_start - Background compaction started
  • session.compaction_complete - Compaction finished (includes token counts)

Custom Providers

The SDK supports custom OpenAI-compatible API providers (BYOK - Bring Your Own Key), including local providers like Ollama. When using a custom provider, you must specify the Model explicitly.

ProviderConfig:

  • Type (string): Provider type - "openai", "azure", or "anthropic" (default: "openai")
  • BaseURL (string): API endpoint URL (required)
  • APIKey (string): API key (optional for local providers like Ollama)
  • BearerToken (string): Bearer token for authentication (takes precedence over APIKey)
  • WireApi (string): API format for OpenAI/Azure - "completions" or "responses" (default: "completions")
  • Azure.APIVersion (string): Azure API version (default: "2024-10-21")

Example with Ollama:

session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "deepseek-coder-v2:16b", // Required when using custom provider
    Provider: &copilot.ProviderConfig{
        Type:    "openai",
        BaseURL: "http://localhost:11434/v1", // Ollama endpoint
        // APIKey not required for Ollama
    },
})

Example with custom OpenAI-compatible API:

session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-4",
    Provider: &copilot.ProviderConfig{
        Type:    "openai",
        BaseURL: "https://my-api.example.com/v1",
        APIKey:  os.Getenv("MY_API_KEY"),
    },
})

Example with Azure OpenAI:

session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-4",
    Provider: &copilot.ProviderConfig{
        Type:    "azure",  // Must be "azure" for Azure endpoints, NOT "openai"
        BaseURL: "https://my-resource.openai.azure.com",  // Just the host, no path
        APIKey:  os.Getenv("AZURE_OPENAI_KEY"),
        Azure: &copilot.AzureProviderOptions{
            APIVersion: "2024-10-21",
        },
    },
})

Important notes:

  • When using a custom provider, the Model parameter is required. The SDK will return an error if no model is specified.
  • For Azure OpenAI endpoints (*.openai.azure.com), you must use Type: "azure", not Type: "openai".
  • The BaseURL should be just the host (e.g., https://my-resource.openai.azure.com). Do not include /openai/v1 in the URL - the SDK handles path construction automatically.

User Input Requests

Enable the agent to ask questions to the user using the ask_user tool by providing an OnUserInputRequest handler:

session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-5",
    OnUserInputRequest: func(request copilot.UserInputRequest, invocation copilot.UserInputInvocation) (copilot.UserInputResponse, error) {
        // request.Question - The question to ask
        // request.Choices - Optional slice of choices for multiple choice
        // request.AllowFreeform - Whether freeform input is allowed (default: true)

        fmt.Printf("Agent asks: %s\n", request.Question)
        if len(request.Choices) > 0 {
            fmt.Printf("Choices: %v\n", request.Choices)
        }

        // Return the user's response
        return copilot.UserInputResponse{
            Answer:      "User's answer here",
            WasFreeform: true, // Whether the answer was freeform (not from choices)
        }, nil
    },
})

Session Hooks

Hook into session lifecycle events by providing handlers in the Hooks configuration:

session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    Model: "gpt-5",
    Hooks: &copilot.SessionHooks{
        // Called before each tool execution
        OnPreToolUse: func(input copilot.PreToolUseHookInput, invocation copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {
            fmt.Printf("About to run tool: %s\n", input.ToolName)
            // Return permission decision and optionally modify args
            return &copilot.PreToolUseHookOutput{
                PermissionDecision: "allow", // "allow", "deny", or "ask"
                ModifiedArgs:       input.ToolArgs, // Optionally modify tool arguments
                AdditionalContext:  "Extra context for the model",
            }, nil
        },

        // Called after each tool execution
        OnPostToolUse: func(input copilot.PostToolUseHookInput, invocation copilot.HookInvocation) (*copilot.PostToolUseHookOutput, error) {
            fmt.Printf("Tool %s completed\n", input.ToolName)
            return &copilot.PostToolUseHookOutput{
                AdditionalContext: "Post-execution notes",
            }, nil
        },

        // Called when user submits a prompt
        OnUserPromptSubmitted: func(input copilot.UserPromptSubmittedHookInput, invocation copilot.HookInvocation) (*copilot.UserPromptSubmittedHookOutput, error) {
            fmt.Printf("User prompt: %s\n", input.Prompt)
            return &copilot.UserPromptSubmittedHookOutput{
                ModifiedPrompt: input.Prompt, // Optionally modify the prompt
            }, nil
        },

        // Called when session starts
        OnSessionStart: func(input copilot.SessionStartHookInput, invocation copilot.HookInvocation) (*copilot.SessionStartHookOutput, error) {
            fmt.Printf("Session started from: %s\n", input.Source) // "startup", "resume", "new"
            return &copilot.SessionStartHookOutput{
                AdditionalContext: "Session initialization context",
            }, nil
        },

        // Called when session ends
        OnSessionEnd: func(input copilot.SessionEndHookInput, invocation copilot.HookInvocation) (*copilot.SessionEndHookOutput, error) {
            fmt.Printf("Session ended: %s\n", input.Reason)
            return nil, nil
        },

        // Called when an error occurs
        OnErrorOccurred: func(input copilot.ErrorOccurredHookInput, invocation copilot.HookInvocation) (*copilot.ErrorOccurredHookOutput, error) {
            fmt.Printf("Error in %s: %s\n", input.ErrorContext, input.Error)
            return &copilot.ErrorOccurredHookOutput{
                ErrorHandling: "retry", // "retry", "skip", or "abort"
            }, nil
        },
    },
})

Available hooks:

  • OnPreToolUse - Intercept tool calls before execution. Can allow/deny or modify arguments.
  • OnPostToolUse - Process tool results after execution. Can modify results or add context.
  • OnUserPromptSubmitted - Intercept user prompts. Can modify the prompt before processing.
  • OnSessionStart - Run logic when a session starts or resumes.
  • OnSessionEnd - Cleanup or logging when session ends.
  • OnErrorOccurred - Handle errors with retry/skip/abort strategies.

Transport Modes

stdio (Default)

Communicates with CLI via stdin/stdout pipes. Recommended for most use cases.

client := copilot.NewClient(nil) // Uses stdio by default
TCP

Communicates with CLI via TCP socket. Useful for distributed scenarios.

Environment Variables

  • COPILOT_CLI_PATH - Path to the Copilot CLI executable

License

MIT

Documentation

Overview

Package copilot provides a Go SDK for interacting with the GitHub Copilot CLI.

The copilot package enables Go applications to communicate with the Copilot CLI server, create and manage conversation sessions, and integrate custom tools.

Basic usage:

client := copilot.NewClient(nil)
if err := client.Start(); err != nil {
    log.Fatal(err)
}
defer client.Stop()

session, err := client.CreateSession(&copilot.SessionConfig{
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
    Model: "gpt-4",
})
if err != nil {
    log.Fatal(err)
}

session.On(func(event copilot.SessionEvent) {
    if 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

View Source
const SdkProtocolVersion = 3

SdkProtocolVersion is the SDK protocol version. This must match the version expected by the copilot-agent-runtime server.

Variables

View Source
var PermissionHandler = struct {
	// ApproveAll approves all permission requests.
	ApproveAll PermissionHandlerFunc
}{
	ApproveAll: func(_ PermissionRequest, _ PermissionInvocation) (PermissionRequestResult, error) {
		return PermissionRequestResult{Kind: PermissionRequestResultKindApproved}, nil
	},
}

PermissionHandler provides pre-built OnPermissionRequest implementations.

Functions

func Bool

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 added in v0.1.18

func Float64(v float64) *float64

Float64 returns a pointer to the given float64 value. Use for setting thresholds: BackgroundCompactionThreshold: Float64(0.80)

func GetSdkProtocolVersion

func GetSdkProtocolVersion() int

GetSdkProtocolVersion returns the SDK protocol version.

func String added in v0.1.24

func String(v string) *string

String returns a pointer to the given string value. Use for setting optional string parameters in RPC calls.

Types

type Agent added in v0.1.31

type Agent struct {
	// Unique identifier of the background agent
	AgentID string `json:"agentId"`
	// Type of the background agent
	AgentType string `json:"agentType"`
	// Human-readable description of the agent task
	Description *string `json:"description,omitempty"`
}

type AgentMode added in v0.1.24

type AgentMode string

The agent mode that was active when this message was sent

const (
	AgentModeShell AgentMode = "shell"
	Autopilot      AgentMode = "autopilot"
	Interactive    AgentMode = "interactive"
	Plan           AgentMode = "plan"
)

type Attachment

type Attachment struct {
	// User-facing display name for the attachment
	//
	// User-facing display name for the selection
	DisplayName *string `json:"displayName,omitempty"`
	// Optional line range to scope the attachment to a specific section of the file
	LineRange *LineRange `json:"lineRange,omitempty"`
	// Absolute file or directory path
	Path *string `json:"path,omitempty"`
	// Attachment type discriminator
	Type AttachmentType `json:"type"`
	// Absolute path to the file containing the selection
	FilePath *string `json:"filePath,omitempty"`
	// Position range of the selection within the file
	Selection *SelectionClass `json:"selection,omitempty"`
	// The selected text content
	Text *string `json:"text,omitempty"`
	// Issue, pull request, or discussion number
	Number *float64 `json:"number,omitempty"`
	// Type of GitHub reference
	ReferenceType *ReferenceType `json:"referenceType,omitempty"`
	// Current state of the referenced item (e.g., open, closed, merged)
	State *string `json:"state,omitempty"`
	// Title of the referenced item
	Title *string `json:"title,omitempty"`
	// URL to the referenced item on GitHub
	URL *string `json:"url,omitempty"`
}

type AttachmentType added in v0.1.15

type AttachmentType string
const (
	Directory       AttachmentType = "directory"
	File            AttachmentType = "file"
	GithubReference AttachmentType = "github_reference"
	Selection       AttachmentType = "selection"
)

type AzureProviderOptions

type AzureProviderOptions struct {
	// APIVersion is the Azure API version. Defaults to "2024-10-21".
	APIVersion string `json:"apiVersion,omitempty"`
}

AzureProviderOptions contains Azure-specific provider configuration

type BackgroundTasks added in v0.1.31

type BackgroundTasks struct {
	// Currently running background agents
	Agents []Agent `json:"agents"`
	// Currently running background shell commands
	Shells []Shell `json:"shells"`
}

Background tasks still running when the agent became idle

type Client

type Client struct {

	// RPC provides typed server-scoped RPC methods.
	// This field is nil until the client is connected via Start().
	RPC *rpc.ServerRpc
	// contains filtered or unexported fields
}

Client manages the connection to the Copilot CLI server and provides session management.

The Client can either spawn a CLI server process or connect to an existing server. It handles JSON-RPC communication, session lifecycle, tool execution, and permission requests.

Example:

// Create a client with default options (spawns CLI server using stdio)
client := copilot.NewClient(nil)

// Or connect to an existing server
client := copilot.NewClient(&copilot.ClientOptions{
    CLIUrl: "localhost:3000",
})

if err := client.Start(); err != nil {
    log.Fatal(err)
}
defer client.Stop()

func NewClient

func NewClient(options *ClientOptions) *Client

NewClient creates a new Copilot CLI client with the given options.

If options is nil, default options are used (spawns CLI server using stdio). The client is not connected after creation; call Client.Start to connect.

Example:

// Default options
client := copilot.NewClient(nil)

// Custom options
client := copilot.NewClient(&copilot.ClientOptions{
    CLIPath:  "/usr/local/bin/copilot",
    LogLevel: "debug",
})

func (*Client) ActualPort added in v0.1.31

func (c *Client) ActualPort() int

ActualPort returns the TCP port the CLI server is listening on. Returns 0 if the client is not connected or using stdio transport.

func (*Client) CreateSession

func (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 required and must include an OnPermissionRequest handler.

Returns the created session or an error if session creation fails.

Example:

// Basic session
session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})

// Session with model and tools
session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
    Model: "gpt-4",
    Tools: []copilot.Tool{
        {
            Name:        "get_weather",
            Description: "Get weather for a location",
            Handler:     weatherHandler,
        },
    },
})

func (*Client) DeleteSession added in v0.1.19

func (c *Client) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession permanently deletes a session and all its data from disk, including conversation history, planning state, and artifacts.

Unlike Session.Disconnect, which only releases in-memory resources and preserves session data for later resumption, DeleteSession is irreversible. The session cannot be resumed after deletion. If the session is in the local sessions map, it will be removed.

Example:

if err := client.DeleteSession(context.Background(), "session-123"); err != nil {
    log.Fatal(err)
}

func (*Client) ForceStop

func (c *Client) ForceStop()

ForceStop forcefully stops the CLI server without graceful cleanup.

Use this when Client.Stop fails or takes too long. This method:

  • Clears all sessions immediately without destroying them
  • Force closes the connection
  • Kills the CLI process (if spawned by this client)

Example:

// If normal stop hangs, force stop
done := make(chan struct{})
go func() {
    client.Stop()
    close(done)
}()

select {
case <-done:
    // Stopped successfully
case <-time.After(5 * time.Second):
    client.ForceStop()
}

func (*Client) GetAuthStatus added in v0.1.15

func (c *Client) GetAuthStatus(ctx context.Context) (*GetAuthStatusResponse, error)

GetAuthStatus returns current authentication status

func (*Client) GetForegroundSessionID added in v0.1.21

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) GetLastSessionID added in v0.1.31

func (c *Client) GetLastSessionID(ctx context.Context) (*string, error)

GetLastSessionID returns the ID of the most recently updated session.

This is useful for resuming the last conversation when the session ID was not stored. Returns nil if no sessions exist.

Example:

lastID, err := client.GetLastSessionID(context.Background())
if err != nil {
    log.Fatal(err)
}
if lastID != nil {
    session, err := client.ResumeSession(context.Background(), *lastID, &copilot.ResumeSessionConfig{
        OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
    })
}

func (*Client) GetStatus added in v0.1.15

func (c *Client) GetStatus(ctx context.Context) (*GetStatusResponse, error)

GetStatus returns CLI status including version and protocol information

func (*Client) ListModels added in v0.1.15

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 added in v0.1.19

func (c *Client) ListSessions(ctx context.Context, filter *SessionListFilter) ([]SessionMetadata, error)

ListSessions returns metadata about all sessions known to the server.

Returns a list of SessionMetadata for all available sessions, including their IDs, timestamps, optional summaries, and context information.

An optional filter can be provided to filter sessions by cwd, git root, repository, or branch.

Example:

sessions, err := client.ListSessions(context.Background(), nil)
if err != nil {
    log.Fatal(err)
}
for _, session := range sessions {
    fmt.Printf("Session: %s\n", session.SessionID)
}

Example with filter:

sessions, err := client.ListSessions(context.Background(), &SessionListFilter{Repository: "owner/repo"})

func (*Client) On added in v0.1.21

func (c *Client) On(handler SessionLifecycleHandler) func()

On subscribes to all session lifecycle events.

Lifecycle events are emitted when sessions are created, deleted, updated, or change foreground/background state (in TUI+server mode).

Returns a function that, when called, unsubscribes the handler.

Example:

unsubscribe := client.On(func(event copilot.SessionLifecycleEvent) {
    fmt.Printf("Session %s: %s\n", event.SessionID, event.Type)
})
defer unsubscribe()

func (*Client) OnEventType added in v0.1.21

func (c *Client) OnEventType(eventType SessionLifecycleEventType, handler SessionLifecycleHandler) func()

OnEventType subscribes to a specific session lifecycle event type.

Returns a function that, when called, unsubscribes the handler.

Example:

unsubscribe := client.OnEventType(copilot.SessionLifecycleForeground, func(event copilot.SessionLifecycleEvent) {
    fmt.Printf("Session %s is now in foreground\n", event.SessionID)
})
defer unsubscribe()

func (*Client) Ping

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

func (c *Client) ResumeSession(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)

ResumeSession resumes an existing conversation session by its ID.

This is a convenience method that calls Client.ResumeSessionWithOptions. The config must include an OnPermissionRequest handler.

Example:

session, err := client.ResumeSession(context.Background(), "session-123", &copilot.ResumeSessionConfig{
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})

func (*Client) ResumeSessionWithOptions

func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)

ResumeSessionWithOptions resumes an existing conversation session with additional configuration.

This allows you to continue a previous conversation, maintaining all conversation history. The session must have been previously created and not deleted.

Example:

session, err := client.ResumeSessionWithOptions(context.Background(), "session-123", &copilot.ResumeSessionConfig{
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
    Tools: []copilot.Tool{myNewTool},
})

func (*Client) SetForegroundSessionID added in v0.1.21

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

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 added in v0.1.21

func (c *Client) State() ConnectionState

State returns the current connection state of the client.

Possible states: StateDisconnected, StateConnecting, StateConnected, StateError.

Example:

if client.State() == copilot.StateConnected {
    session, err := client.CreateSession(context.Background(), &copilot.SessionConfig{
        OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
    })
}

func (*Client) Stop

func (c *Client) Stop() error

Stop stops the CLI server and closes all active sessions.

This method performs graceful cleanup:

  1. Closes all active sessions (releases in-memory resources)
  2. Closes the JSON-RPC connection
  3. Terminates the CLI server process (if spawned by this client)

Note: session data on disk is preserved, so sessions can be resumed later. To permanently remove session data before stopping, call Client.DeleteSession for each session first.

Returns an error that aggregates all errors encountered during cleanup.

Example:

if err := client.Stop(); err != nil {
    log.Printf("Cleanup error: %v", err)
}

type ClientOptions

type ClientOptions struct {
	// CLIPath is the path to the Copilot CLI executable (default: "copilot")
	CLIPath string
	// CLIArgs are extra arguments to pass to the CLI executable (inserted before SDK-managed args)
	CLIArgs []string
	// Cwd is the working directory for the CLI process (default: "" = inherit from current process)
	Cwd string
	// Port for TCP transport (default: 0 = random port)
	Port int
	// UseStdio controls whether to use stdio transport instead of TCP.
	// Default: nil (use default = true, i.e. stdio). Use Bool(false) to explicitly select TCP.
	UseStdio *bool
	// CLIUrl is the URL of an existing Copilot CLI server to connect to over TCP
	// Format: "host:port", "http://host:port", or just "port" (defaults to localhost)
	// Examples: "localhost:8080", "http://127.0.0.1:9000", "8080"
	// Mutually exclusive with CLIPath, UseStdio
	CLIUrl string
	// LogLevel for the CLI server
	LogLevel string
	// AutoStart automatically starts the CLI server on first use (default: true).
	// Use Bool(false) to disable.
	AutoStart *bool
	// 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
}

ClientOptions configures the CopilotClient

type CodeChanges added in v0.1.21

type CodeChanges struct {
	// List of file paths that were modified during the session
	FilesModified []string `json:"filesModified"`
	// Total number of lines added during the session
	LinesAdded float64 `json:"linesAdded"`
	// Total number of lines removed during the session
	LinesRemoved float64 `json:"linesRemoved"`
}

Aggregate code change metrics for the session

type Command added in v0.1.31

type Command struct {
	// Command identifier (e.g., executable name)
	Identifier string `json:"identifier"`
	// Whether this command is read-only (no side effects)
	ReadOnly bool `json:"readOnly"`
}

type CompactionTokensUsed added in v0.1.15

type CompactionTokensUsed struct {
	// Cached input tokens reused in the compaction LLM call
	CachedInput float64 `json:"cachedInput"`
	// Input tokens consumed by the compaction LLM call
	Input float64 `json:"input"`
	// Output tokens produced by the compaction LLM call
	Output float64 `json:"output"`
}

Token usage breakdown for the compaction LLM call

type ConnectionState

type ConnectionState string

ConnectionState represents the client connection state

const (
	StateDisconnected ConnectionState = "disconnected"
	StateConnecting   ConnectionState = "connecting"
	StateConnected    ConnectionState = "connected"
	StateError        ConnectionState = "error"
)

type Content added in v0.1.24

type Content struct {
	// The text content
	//
	// Terminal/shell output text
	Text *string `json:"text,omitempty"`
	// Content block type discriminator
	Type ContentType `json:"type"`
	// Working directory where the command was executed
	Cwd *string `json:"cwd,omitempty"`
	// Process exit code, if the command has completed
	ExitCode *float64 `json:"exitCode,omitempty"`
	// Base64-encoded image data
	//
	// Base64-encoded audio data
	Data *string `json:"data,omitempty"`
	// MIME type of the image (e.g., image/png, image/jpeg)
	//
	// MIME type of the audio (e.g., audio/wav, audio/mpeg)
	//
	// MIME type of the resource content
	MIMEType *string `json:"mimeType,omitempty"`
	// Human-readable description of the resource
	Description *string `json:"description,omitempty"`
	// Icons associated with this resource
	Icons []Icon `json:"icons,omitempty"`
	// Resource name identifier
	Name *string `json:"name,omitempty"`
	// Size of the resource in bytes
	Size *float64 `json:"size,omitempty"`
	// Human-readable display title for the resource
	Title *string `json:"title,omitempty"`
	// URI identifying the resource
	URI *string `json:"uri,omitempty"`
	// The embedded resource contents, either text or base64-encoded binary
	Resource *ResourceClass `json:"resource,omitempty"`
}

type ContentType added in v0.1.24

type ContentType string
const (
	Audio        ContentType = "audio"
	Image        ContentType = "image"
	Resource     ContentType = "resource"
	ResourceLink ContentType = "resource_link"
	Terminal     ContentType = "terminal"
	Text         ContentType = "text"
)

type ContextClass added in v0.1.15

type ContextClass struct {
	// Current git branch name
	Branch *string `json:"branch,omitempty"`
	// Current working directory path
	Cwd string `json:"cwd"`
	// Root directory of the git repository, resolved via git rev-parse
	GitRoot *string `json:"gitRoot,omitempty"`
	// Repository identifier in "owner/name" format, derived from the git remote URL
	Repository *string `json:"repository,omitempty"`
}

Working directory and git context at session start

Updated working directory and git context at resume time

type ContextUnion added in v0.1.15

type ContextUnion struct {
	ContextClass *ContextClass
	String       *string
}

func (*ContextUnion) MarshalJSON added in v0.1.15

func (x *ContextUnion) MarshalJSON() ([]byte, error)

func (*ContextUnion) UnmarshalJSON added in v0.1.15

func (x *ContextUnion) UnmarshalJSON(data []byte) error

type CopilotUsage added in v0.1.29

type CopilotUsage struct {
	// Itemized token usage breakdown
	TokenDetails []TokenDetail `json:"tokenDetails"`
	// Total cost in nano-AIU (AI Units) for this request
	TotalNanoAiu float64 `json:"totalNanoAiu"`
}

Per-request cost and usage data from the CAPI copilot_usage response field

type CustomAgentConfig

type CustomAgentConfig struct {
	// Name is the unique name of the custom agent
	Name string `json:"name"`
	// DisplayName is the display name for UI purposes
	DisplayName string `json:"displayName,omitempty"`
	// Description of what the agent does
	Description string `json:"description,omitempty"`
	// Tools is the list of tool names the agent can use (nil for all tools)
	Tools []string `json:"tools,omitempty"`
	// Prompt is the prompt content for the agent
	Prompt string `json:"prompt"`
	// MCPServers are MCP servers specific to this agent
	MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"`
	// Infer indicates whether the agent should be available for model inference
	Infer *bool `json:"infer,omitempty"`
}

CustomAgentConfig configures a custom agent

type Data added in v0.1.15

type Data struct {
	// Working directory and git context at session start
	//
	// Updated working directory and git context at resume time
	//
	// Additional context information for the handoff
	Context *ContextUnion `json:"context"`
	// Version string of the Copilot application
	CopilotVersion *string `json:"copilotVersion,omitempty"`
	// Identifier of the software producing the events (e.g., "copilot-agent")
	Producer *string `json:"producer,omitempty"`
	// Model selected at session creation time, if any
	SelectedModel *string `json:"selectedModel,omitempty"`
	// Unique identifier for the session
	//
	// Session ID that this external tool request belongs to
	SessionID *string `json:"sessionId,omitempty"`
	// ISO 8601 timestamp when the session was created
	StartTime *time.Time `json:"startTime,omitempty"`
	// Schema version number for the session event format
	Version *float64 `json:"version,omitempty"`
	// Total number of persisted events in the session at the time of resume
	EventCount *float64 `json:"eventCount,omitempty"`
	// ISO 8601 timestamp when the session was resumed
	ResumeTime *time.Time `json:"resumeTime,omitempty"`
	// Category of error (e.g., "authentication", "authorization", "quota", "rate_limit",
	// "query")
	ErrorType *string `json:"errorType,omitempty"`
	// Human-readable error message
	//
	// Human-readable informational message for display in the timeline
	//
	// Human-readable warning message for display in the timeline
	//
	// Message describing what information is needed from the user
	Message *string `json:"message,omitempty"`
	// GitHub request tracing ID (x-github-request-id header) for correlating with server-side
	// logs
	//
	// GitHub request tracing ID (x-github-request-id header) for server-side log correlation
	ProviderCallID *string `json:"providerCallId,omitempty"`
	// Error stack trace, when available
	Stack *string `json:"stack,omitempty"`
	// HTTP status code from the upstream request, if applicable
	StatusCode *int64 `json:"statusCode,omitempty"`
	// Background tasks still running when the agent became idle
	BackgroundTasks *BackgroundTasks `json:"backgroundTasks,omitempty"`
	// The new display title for the session
	Title *string `json:"title,omitempty"`
	// Category of informational message (e.g., "notification", "timing", "context_window",
	// "mcp", "snapshot", "configuration", "authentication", "model")
	InfoType *string `json:"infoType,omitempty"`
	// Category of warning (e.g., "subscription", "policy", "mcp")
	WarningType *string `json:"warningType,omitempty"`
	// Newly selected model identifier
	NewModel *string `json:"newModel,omitempty"`
	// Model that was previously selected, if any
	PreviousModel *string `json:"previousModel,omitempty"`
	// Agent mode after the change (e.g., "interactive", "plan", "autopilot")
	NewMode *string `json:"newMode,omitempty"`
	// Agent mode before the change (e.g., "interactive", "plan", "autopilot")
	PreviousMode *string `json:"previousMode,omitempty"`
	// The type of operation performed on the plan file
	//
	// Whether the file was newly created or updated
	Operation *Operation `json:"operation,omitempty"`
	// Relative path within the session workspace files directory
	//
	// File path to the SKILL.md definition
	Path *string `json:"path,omitempty"`
	// ISO 8601 timestamp when the handoff occurred
	HandoffTime *time.Time `json:"handoffTime,omitempty"`
	// Session ID of the remote session being handed off
	RemoteSessionID *string `json:"remoteSessionId,omitempty"`
	// Repository context for the handed-off session
	//
	// Repository identifier in "owner/name" format, derived from the git remote URL
	Repository *RepositoryUnion `json:"repository"`
	// Origin type of the session being handed off
	SourceType *SourceType `json:"sourceType,omitempty"`
	// Summary of the work done in the source session
	//
	// Optional summary of the completed task, provided by the agent
	//
	// Summary of the plan that was created
	Summary *string `json:"summary,omitempty"`
	// Number of messages removed by truncation
	MessagesRemovedDuringTruncation *float64 `json:"messagesRemovedDuringTruncation,omitempty"`
	// Identifier of the component that performed truncation (e.g., "BasicTruncator")
	PerformedBy *string `json:"performedBy,omitempty"`
	// Number of conversation messages after truncation
	PostTruncationMessagesLength *float64 `json:"postTruncationMessagesLength,omitempty"`
	// Total tokens in conversation messages after truncation
	PostTruncationTokensInMessages *float64 `json:"postTruncationTokensInMessages,omitempty"`
	// Number of conversation messages before truncation
	PreTruncationMessagesLength *float64 `json:"preTruncationMessagesLength,omitempty"`
	// Total tokens in conversation messages before truncation
	PreTruncationTokensInMessages *float64 `json:"preTruncationTokensInMessages,omitempty"`
	// Maximum token count for the model's context window
	TokenLimit *float64 `json:"tokenLimit,omitempty"`
	// Number of tokens removed by truncation
	TokensRemovedDuringTruncation *float64 `json:"tokensRemovedDuringTruncation,omitempty"`
	// Number of events that were removed by the rewind
	EventsRemoved *float64 `json:"eventsRemoved,omitempty"`
	// Event ID that was rewound to; all events after this one were removed
	UpToEventID *string `json:"upToEventId,omitempty"`
	// Aggregate code change metrics for the session
	CodeChanges *CodeChanges `json:"codeChanges,omitempty"`
	// Model that was selected at the time of shutdown
	CurrentModel *string `json:"currentModel,omitempty"`
	// Error description when shutdownType is "error"
	ErrorReason *string `json:"errorReason,omitempty"`
	// Per-model usage breakdown, keyed by model identifier
	ModelMetrics map[string]ModelMetric `json:"modelMetrics,omitempty"`
	// Unix timestamp (milliseconds) when the session started
	SessionStartTime *float64 `json:"sessionStartTime,omitempty"`
	// Whether the session ended normally ("routine") or due to a crash/fatal error ("error")
	ShutdownType *ShutdownType `json:"shutdownType,omitempty"`
	// Cumulative time spent in API calls during the session, in milliseconds
	TotalAPIDurationMS *float64 `json:"totalApiDurationMs,omitempty"`
	// Total number of premium API requests used during the session
	TotalPremiumRequests *float64 `json:"totalPremiumRequests,omitempty"`
	// Current git branch name
	Branch *string `json:"branch,omitempty"`
	// Current working directory path
	Cwd *string `json:"cwd,omitempty"`
	// Root directory of the git repository, resolved via git rev-parse
	GitRoot *string `json:"gitRoot,omitempty"`
	// Current number of tokens in the context window
	CurrentTokens *float64 `json:"currentTokens,omitempty"`
	// Current number of messages in the conversation
	MessagesLength *float64 `json:"messagesLength,omitempty"`
	// Checkpoint snapshot number created for recovery
	CheckpointNumber *float64 `json:"checkpointNumber,omitempty"`
	// File path where the checkpoint was stored
	CheckpointPath *string `json:"checkpointPath,omitempty"`
	// Token usage breakdown for the compaction LLM call
	CompactionTokensUsed *CompactionTokensUsed `json:"compactionTokensUsed,omitempty"`
	// Error message if compaction failed
	//
	// Error details when the tool execution failed
	//
	// Error message describing why the sub-agent failed
	//
	// Error details when the hook failed
	Error *ErrorUnion `json:"error"`
	// Number of messages removed during compaction
	MessagesRemoved *float64 `json:"messagesRemoved,omitempty"`
	// Total tokens in conversation after compaction
	PostCompactionTokens *float64 `json:"postCompactionTokens,omitempty"`
	// Number of messages before compaction
	PreCompactionMessagesLength *float64 `json:"preCompactionMessagesLength,omitempty"`
	// Total tokens in conversation before compaction
	PreCompactionTokens *float64 `json:"preCompactionTokens,omitempty"`
	// GitHub request tracing ID (x-github-request-id header) for the compaction LLM call
	//
	// Unique identifier for this permission request; used to respond via
	// session.respondToPermission()
	//
	// Request ID of the resolved permission request; clients should dismiss any UI for this
	// request
	//
	// Unique identifier for this input request; used to respond via
	// session.respondToUserInput()
	//
	// Request ID of the resolved user input request; clients should dismiss any UI for this
	// request
	//
	// Unique identifier for this elicitation request; used to respond via
	// session.respondToElicitation()
	//
	// Request ID of the resolved elicitation request; clients should dismiss any UI for this
	// request
	//
	// Unique identifier for this request; used to respond via session.respondToExternalTool()
	//
	// Request ID of the resolved external tool request; clients should dismiss any UI for this
	// request
	//
	// Unique identifier for this request; used to respond via session.respondToQueuedCommand()
	//
	// Request ID of the resolved command request; clients should dismiss any UI for this
	// request
	//
	// Unique identifier for this request; used to respond via session.respondToExitPlanMode()
	//
	// Request ID of the resolved exit plan mode request; clients should dismiss any UI for this
	// request
	RequestID *string `json:"requestId,omitempty"`
	// Whether compaction completed successfully
	//
	// Whether the tool execution completed successfully
	//
	// Whether the hook completed successfully
	Success *bool `json:"success,omitempty"`
	// LLM-generated summary of the compacted conversation history
	SummaryContent *string `json:"summaryContent,omitempty"`
	// Number of tokens removed during compaction
	TokensRemoved *float64 `json:"tokensRemoved,omitempty"`
	// The agent mode that was active when this message was sent
	AgentMode *AgentMode `json:"agentMode,omitempty"`
	// Files, selections, or GitHub references attached to the message
	Attachments []Attachment `json:"attachments,omitempty"`
	// The user's message text as displayed in the timeline
	//
	// The complete extended thinking text from the model
	//
	// The assistant's text response content
	//
	// Full content of the skill file, injected into the conversation for the model
	//
	// The system or developer prompt text
	Content *string `json:"content,omitempty"`
	// CAPI interaction ID for correlating this user message with its turn
	//
	// CAPI interaction ID for correlating this turn with upstream telemetry
	//
	// CAPI interaction ID for correlating this message with upstream telemetry
	//
	// CAPI interaction ID for correlating this tool execution with upstream telemetry
	InteractionID *string `json:"interactionId,omitempty"`
	// Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected
	// messages that should be hidden from the user)
	Source *string `json:"source,omitempty"`
	// Transformed version of the message sent to the model, with XML wrapping, timestamps, and
	// other augmentations for prompt caching
	TransformedContent *string `json:"transformedContent,omitempty"`
	// Identifier for this turn within the agentic loop, typically a stringified turn number
	//
	// Identifier of the turn that has ended, matching the corresponding assistant.turn_start
	// event
	TurnID *string `json:"turnId,omitempty"`
	// Short description of what the agent is currently doing or planning to do
	Intent *string `json:"intent,omitempty"`
	// Unique identifier for this reasoning block
	//
	// Reasoning block ID this delta belongs to, matching the corresponding assistant.reasoning
	// event
	ReasoningID *string `json:"reasoningId,omitempty"`
	// Incremental text chunk to append to the reasoning content
	//
	// Incremental text chunk to append to the message content
	DeltaContent *string `json:"deltaContent,omitempty"`
	// Cumulative total bytes received from the streaming response so far
	TotalResponseSizeBytes *float64 `json:"totalResponseSizeBytes,omitempty"`
	// Encrypted reasoning content from OpenAI models. Session-bound and stripped on resume.
	EncryptedContent *string `json:"encryptedContent,omitempty"`
	// Unique identifier for this assistant message
	//
	// Message ID this delta belongs to, matching the corresponding assistant.message event
	MessageID *string `json:"messageId,omitempty"`
	// Actual output token count from the API response (completion_tokens), used for accurate
	// token accounting
	//
	// Number of output tokens produced
	OutputTokens *float64 `json:"outputTokens,omitempty"`
	// Tool call ID of the parent tool invocation when this event originates from a sub-agent
	//
	// Parent tool call ID when this usage originates from a sub-agent
	ParentToolCallID *string `json:"parentToolCallId,omitempty"`
	// Generation phase for phased-output models (e.g., thinking vs. response phases)
	Phase *string `json:"phase,omitempty"`
	// Opaque/encrypted extended thinking data from Anthropic models. Session-bound and stripped
	// on resume.
	ReasoningOpaque *string `json:"reasoningOpaque,omitempty"`
	// Readable reasoning text from the model's extended thinking
	ReasoningText *string `json:"reasoningText,omitempty"`
	// Tool invocations requested by the assistant in this message
	ToolRequests []ToolRequest `json:"toolRequests,omitempty"`
	// Completion ID from the model provider (e.g., chatcmpl-abc123)
	APICallID *string `json:"apiCallId,omitempty"`
	// Number of tokens read from prompt cache
	CacheReadTokens *float64 `json:"cacheReadTokens,omitempty"`
	// Number of tokens written to prompt cache
	CacheWriteTokens *float64 `json:"cacheWriteTokens,omitempty"`
	// Per-request cost and usage data from the CAPI copilot_usage response field
	CopilotUsage *CopilotUsage `json:"copilotUsage,omitempty"`
	// Model multiplier cost for billing purposes
	Cost *float64 `json:"cost,omitempty"`
	// Duration of the API call in milliseconds
	Duration *float64 `json:"duration,omitempty"`
	// What initiated this API call (e.g., "sub-agent"); absent for user-initiated calls
	Initiator *string `json:"initiator,omitempty"`
	// Number of input tokens consumed
	InputTokens *float64 `json:"inputTokens,omitempty"`
	// Model identifier used for this API call
	//
	// Model identifier that generated this tool call
	Model *string `json:"model,omitempty"`
	// Per-quota resource usage snapshots, keyed by quota identifier
	QuotaSnapshots map[string]QuotaSnapshot `json:"quotaSnapshots,omitempty"`
	// Reason the current turn was aborted (e.g., "user initiated")
	Reason *string `json:"reason,omitempty"`
	// Arguments for the tool invocation
	//
	// Arguments passed to the tool
	//
	// Arguments to pass to the external tool
	Arguments interface{} `json:"arguments"`
	// Unique identifier for this tool call
	//
	// Tool call ID this partial result belongs to
	//
	// Tool call ID this progress notification belongs to
	//
	// Unique identifier for the completed tool call
	//
	// Tool call ID of the parent tool invocation that spawned this sub-agent
	//
	// Tool call ID assigned to this external tool invocation
	ToolCallID *string `json:"toolCallId,omitempty"`
	// Name of the tool the user wants to invoke
	//
	// Name of the tool being executed
	//
	// Name of the external tool to invoke
	ToolName *string `json:"toolName,omitempty"`
	// Name of the MCP server hosting this tool, when the tool is an MCP tool
	MCPServerName *string `json:"mcpServerName,omitempty"`
	// Original tool name on the MCP server, when the tool is an MCP tool
	MCPToolName *string `json:"mcpToolName,omitempty"`
	// Incremental output chunk from the running tool
	PartialOutput *string `json:"partialOutput,omitempty"`
	// Human-readable progress status message (e.g., from an MCP server)
	ProgressMessage *string `json:"progressMessage,omitempty"`
	// Whether this tool call was explicitly requested by the user rather than the assistant
	IsUserRequested *bool `json:"isUserRequested,omitempty"`
	// Tool execution result on success
	//
	// The result of the permission request
	Result *Result `json:"result,omitempty"`
	// Tool-specific telemetry data (e.g., CodeQL check counts, grep match counts)
	ToolTelemetry map[string]interface{} `json:"toolTelemetry,omitempty"`
	// Tool names that should be auto-approved when this skill is active
	AllowedTools []string `json:"allowedTools,omitempty"`
	// Name of the invoked skill
	//
	// Optional name identifier for the message source
	Name *string `json:"name,omitempty"`
	// Name of the plugin this skill originated from, when applicable
	PluginName *string `json:"pluginName,omitempty"`
	// Version of the plugin this skill originated from, when applicable
	PluginVersion *string `json:"pluginVersion,omitempty"`
	// Description of what the sub-agent does
	AgentDescription *string `json:"agentDescription,omitempty"`
	// Human-readable display name of the sub-agent
	//
	// Human-readable display name of the selected custom agent
	AgentDisplayName *string `json:"agentDisplayName,omitempty"`
	// Internal name of the sub-agent
	//
	// Internal name of the selected custom agent
	AgentName *string `json:"agentName,omitempty"`
	// List of tool names available to this agent, or null for all tools
	Tools []string `json:"tools"`
	// Unique identifier for this hook invocation
	//
	// Identifier matching the corresponding hook.start event
	HookInvocationID *string `json:"hookInvocationId,omitempty"`
	// Type of hook being invoked (e.g., "preToolUse", "postToolUse", "sessionStart")
	//
	// Type of hook that was invoked (e.g., "preToolUse", "postToolUse", "sessionStart")
	HookType *string `json:"hookType,omitempty"`
	// Input data passed to the hook
	Input interface{} `json:"input"`
	// Output data produced by the hook
	Output interface{} `json:"output"`
	// Metadata about the prompt template and its construction
	Metadata *Metadata `json:"metadata,omitempty"`
	// Message role: "system" for system prompts, "developer" for developer-injected instructions
	Role *Role `json:"role,omitempty"`
	// Details of the permission being requested
	PermissionRequest *PermissionRequest `json:"permissionRequest,omitempty"`
	// Whether the user can provide a free-form text response in addition to predefined choices
	AllowFreeform *bool `json:"allowFreeform,omitempty"`
	// Predefined choices for the user to select from, if applicable
	Choices []string `json:"choices,omitempty"`
	// The question or prompt to present to the user
	Question *string `json:"question,omitempty"`
	// Elicitation mode; currently only "form" is supported. Defaults to "form" when absent.
	Mode *Mode `json:"mode,omitempty"`
	// JSON Schema describing the form fields to present to the user
	RequestedSchema *RequestedSchema `json:"requestedSchema,omitempty"`
	// The slash command text to be executed (e.g., /help, /clear)
	Command *string `json:"command,omitempty"`
	// Available actions the user can take (e.g., approve, edit, reject)
	Actions []string `json:"actions,omitempty"`
	// Full content of the plan file
	PlanContent *string `json:"planContent,omitempty"`
	// The recommended action for the user to take
	RecommendedAction *string `json:"recommendedAction,omitempty"`
}

Payload indicating the agent is idle; includes any background tasks still in flight

Empty payload; the event signals that LLM-powered conversation compaction has begun

Empty payload; the event signals that the pending message queue has changed

Empty payload; the event signals that the custom agent was deselected, returning to the default agent

type End added in v0.1.19

type End struct {
	// End character offset within the line (0-based)
	Character float64 `json:"character"`
	// End line number (0-based)
	Line float64 `json:"line"`
}

type ErrorClass added in v0.1.15

type ErrorClass struct {
	// Machine-readable error code
	Code *string `json:"code,omitempty"`
	// Human-readable error message
	Message string `json:"message"`
	// Error stack trace, when available
	Stack *string `json:"stack,omitempty"`
}

Error details when the tool execution failed

Error details when the hook failed

type ErrorOccurredHandler added in v0.1.20

type ErrorOccurredHandler func(input ErrorOccurredHookInput, invocation HookInvocation) (*ErrorOccurredHookOutput, error)

ErrorOccurredHandler handles error-occurred hook invocations

type ErrorOccurredHookInput added in v0.1.20

type ErrorOccurredHookInput struct {
	Timestamp    int64  `json:"timestamp"`
	Cwd          string `json:"cwd"`
	Error        string `json:"error"`
	ErrorContext string `json:"errorContext"` // "model_call", "tool_execution", "system", "user_input"
	Recoverable  bool   `json:"recoverable"`
}

ErrorOccurredHookInput is the input for an error-occurred hook

type ErrorOccurredHookOutput added in v0.1.20

type ErrorOccurredHookOutput struct {
	SuppressOutput   bool   `json:"suppressOutput,omitempty"`
	ErrorHandling    string `json:"errorHandling,omitempty"` // "retry", "skip", "abort"
	RetryCount       int    `json:"retryCount,omitempty"`
	UserNotification string `json:"userNotification,omitempty"`
}

ErrorOccurredHookOutput is the output for an error-occurred hook

type ErrorUnion added in v0.1.15

type ErrorUnion struct {
	ErrorClass *ErrorClass
	String     *string
}

func (*ErrorUnion) MarshalJSON added in v0.1.15

func (x *ErrorUnion) MarshalJSON() ([]byte, error)

func (*ErrorUnion) UnmarshalJSON added in v0.1.15

func (x *ErrorUnion) UnmarshalJSON(data []byte) error

type GetAuthStatusResponse added in v0.1.15

type GetAuthStatusResponse struct {
	IsAuthenticated bool    `json:"isAuthenticated"`
	AuthType        *string `json:"authType,omitempty"`
	Host            *string `json:"host,omitempty"`
	Login           *string `json:"login,omitempty"`
	StatusMessage   *string `json:"statusMessage,omitempty"`
}

GetAuthStatusResponse is the response from auth.getStatus

type GetStatusResponse added in v0.1.15

type GetStatusResponse struct {
	Version         string `json:"version"`
	ProtocolVersion int    `json:"protocolVersion"`
}

GetStatusResponse is the response from status.get

type HookInvocation added in v0.1.20

type HookInvocation struct {
	SessionID string
}

HookInvocation provides context about a hook invocation

type Icon added in v0.1.24

type Icon struct {
	// MIME type of the icon image
	MIMEType *string `json:"mimeType,omitempty"`
	// Available icon sizes (e.g., ['16x16', '32x32'])
	Sizes []string `json:"sizes,omitempty"`
	// URL or path to the icon image
	Src string `json:"src"`
	// Theme variant this icon is intended for
	Theme *Theme `json:"theme,omitempty"`
}

type InfiniteSessionConfig added in v0.1.18

type InfiniteSessionConfig struct {
	// Enabled controls whether infinite sessions are enabled (default: true)
	Enabled *bool `json:"enabled,omitempty"`
	// BackgroundCompactionThreshold is the context utilization (0.0-1.0) at which
	// background compaction starts. Default: 0.80
	BackgroundCompactionThreshold *float64 `json:"backgroundCompactionThreshold,omitempty"`
	// BufferExhaustionThreshold is the context utilization (0.0-1.0) at which
	// the session blocks until compaction completes. Default: 0.95
	BufferExhaustionThreshold *float64 `json:"bufferExhaustionThreshold,omitempty"`
}

InfiniteSessionConfig configures infinite sessions with automatic context compaction and workspace persistence. When enabled, sessions automatically manage context window limits through background compaction and persist state to a workspace directory.

type LineRange added in v0.1.24

type LineRange struct {
	// End line number (1-based, inclusive)
	End float64 `json:"end"`
	// Start line number (1-based)
	Start float64 `json:"start"`
}

Optional line range to scope the attachment to a specific section of the file

type MCPLocalServerConfig

type MCPLocalServerConfig struct {
	Tools   []string          `json:"tools"`
	Type    string            `json:"type,omitempty"` // "local" or "stdio"
	Timeout int               `json:"timeout,omitempty"`
	Command string            `json:"command"`
	Args    []string          `json:"args"`
	Env     map[string]string `json:"env,omitempty"`
	Cwd     string            `json:"cwd,omitempty"`
}

MCPLocalServerConfig configures a local/stdio MCP server

type MCPRemoteServerConfig

type MCPRemoteServerConfig struct {
	Tools   []string          `json:"tools"`
	Type    string            `json:"type"` // "http" or "sse"
	Timeout int               `json:"timeout,omitempty"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

MCPRemoteServerConfig configures a remote MCP server (HTTP or SSE)

type MCPServerConfig

type MCPServerConfig map[string]any

MCPServerConfig can be either MCPLocalServerConfig or MCPRemoteServerConfig Use a map[string]any for flexibility, or create separate configs

type MessageOptions

type MessageOptions struct {
	// Prompt is the message to send
	Prompt string
	// Attachments are file or directory attachments
	Attachments []Attachment
	// Mode is the message delivery mode (default: "enqueue")
	Mode string
}

MessageOptions configures a message to send

type Metadata added in v0.1.15

type Metadata struct {
	// Version identifier of the prompt template used
	PromptVersion *string `json:"promptVersion,omitempty"`
	// Template variables used when constructing the prompt
	Variables map[string]interface{} `json:"variables,omitempty"`
}

Metadata about the prompt template and its construction

type Mode added in v0.1.31

type Mode string
const (
	Form Mode = "form"
)

type ModelBilling added in v0.1.15

type ModelBilling struct {
	Multiplier float64 `json:"multiplier"`
}

ModelBilling contains model billing information

type ModelCapabilities added in v0.1.15

type ModelCapabilities struct {
	Supports ModelSupports `json:"supports"`
	Limits   ModelLimits   `json:"limits"`
}

ModelCapabilities contains model capabilities and limits

type ModelInfo added in v0.1.15

type ModelInfo struct {
	ID                        string            `json:"id"`
	Name                      string            `json:"name"`
	Capabilities              ModelCapabilities `json:"capabilities"`
	Policy                    *ModelPolicy      `json:"policy,omitempty"`
	Billing                   *ModelBilling     `json:"billing,omitempty"`
	SupportedReasoningEfforts []string          `json:"supportedReasoningEfforts,omitempty"`
	DefaultReasoningEffort    string            `json:"defaultReasoningEffort,omitempty"`
}

ModelInfo contains information about an available model

type ModelLimits added in v0.1.15

type ModelLimits struct {
	MaxPromptTokens        *int               `json:"max_prompt_tokens,omitempty"`
	MaxContextWindowTokens int                `json:"max_context_window_tokens"`
	Vision                 *ModelVisionLimits `json:"vision,omitempty"`
}

ModelLimits contains model limits

type ModelMetric added in v0.1.21

type ModelMetric struct {
	// Request count and cost metrics
	Requests Requests `json:"requests"`
	// Token usage breakdown
	Usage Usage `json:"usage"`
}

type ModelPolicy added in v0.1.15

type ModelPolicy struct {
	State string `json:"state"`
	Terms string `json:"terms"`
}

ModelPolicy contains model policy state

type ModelSupports added in v0.1.15

type ModelSupports struct {
	Vision          bool `json:"vision"`
	ReasoningEffort bool `json:"reasoningEffort"`
}

ModelSupports contains model support flags

type ModelVisionLimits added in v0.1.15

type ModelVisionLimits struct {
	SupportedMediaTypes []string `json:"supported_media_types"`
	MaxPromptImages     int      `json:"max_prompt_images"`
	MaxPromptImageSize  int      `json:"max_prompt_image_size"`
}

ModelVisionLimits contains vision-specific limits

type Operation added in v0.1.25

type Operation string

The type of operation performed on the plan file

Whether the file was newly created or updated

const (
	Create Operation = "create"
	Delete Operation = "delete"
	Update Operation = "update"
)

type PermissionHandlerFunc added in v0.1.28

type PermissionHandlerFunc func(request PermissionRequest, invocation PermissionInvocation) (PermissionRequestResult, error)

PermissionHandlerFunc executes a permission request The handler should return a PermissionRequestResult. Returning an error denies the permission.

type PermissionInvocation

type PermissionInvocation struct {
	SessionID string
}

PermissionInvocation provides context about a permission request

type PermissionRequest

type PermissionRequest struct {
	// Whether the UI can offer session-wide approval for this command pattern
	CanOfferSessionApproval *bool `json:"canOfferSessionApproval,omitempty"`
	// Parsed command identifiers found in the command text
	Commands []Command `json:"commands,omitempty"`
	// The complete shell command text to be executed
	FullCommandText *string `json:"fullCommandText,omitempty"`
	// Whether the command includes a file write redirection (e.g., > or >>)
	HasWriteFileRedirection *bool `json:"hasWriteFileRedirection,omitempty"`
	// Human-readable description of what the command intends to do
	//
	// Human-readable description of the intended file change
	//
	// Human-readable description of why the file is being read
	//
	// Human-readable description of why the URL is being accessed
	Intention *string `json:"intention,omitempty"`
	// Permission kind discriminator
	Kind PermissionRequestKind `json:"kind"`
	// File paths that may be read or written by the command
	PossiblePaths []string `json:"possiblePaths,omitempty"`
	// URLs that may be accessed by the command
	PossibleUrls []PossibleURL `json:"possibleUrls,omitempty"`
	// Tool call ID that triggered this permission request
	ToolCallID *string `json:"toolCallId,omitempty"`
	// Optional warning message about risks of running this command
	Warning *string `json:"warning,omitempty"`
	// Unified diff showing the proposed changes
	Diff *string `json:"diff,omitempty"`
	// Path of the file being written to
	FileName *string `json:"fileName,omitempty"`
	// Complete new file contents for newly created files
	NewFileContents *string `json:"newFileContents,omitempty"`
	// Path of the file or directory being read
	Path *string `json:"path,omitempty"`
	// Arguments to pass to the MCP tool
	//
	// Arguments to pass to the custom tool
	Args interface{} `json:"args"`
	// Whether this MCP tool is read-only (no side effects)
	ReadOnly *bool `json:"readOnly,omitempty"`
	// Name of the MCP server providing the tool
	ServerName *string `json:"serverName,omitempty"`
	// Internal name of the MCP tool
	//
	// Name of the custom tool
	ToolName *string `json:"toolName,omitempty"`
	// Human-readable title of the MCP tool
	ToolTitle *string `json:"toolTitle,omitempty"`
	// URL to be fetched
	URL *string `json:"url,omitempty"`
	// Source references for the stored fact
	Citations *string `json:"citations,omitempty"`
	// The fact or convention being stored
	Fact *string `json:"fact,omitempty"`
	// Topic or subject of the memory being stored
	Subject *string `json:"subject,omitempty"`
	// Description of what the custom tool does
	ToolDescription *string `json:"toolDescription,omitempty"`
}

Details of the permission being requested

type PermissionRequestKind added in v0.1.31

type PermissionRequestKind string
const (
	CustomTool PermissionRequestKind = "custom-tool"
	KindShell  PermissionRequestKind = "shell"
	MCP        PermissionRequestKind = "mcp"
	Memory     PermissionRequestKind = "memory"
	Read       PermissionRequestKind = "read"
	URL        PermissionRequestKind = "url"
	Write      PermissionRequestKind = "write"
)

type PermissionRequestResult

type PermissionRequestResult struct {
	Kind  PermissionRequestResultKind `json:"kind"`
	Rules []any                       `json:"rules,omitempty"`
}

PermissionRequestResult represents the result of a permission request

type PermissionRequestResultKind added in v0.1.31

type PermissionRequestResultKind string

PermissionRequestResultKind represents the kind of a permission request result.

const (
	// PermissionRequestResultKindApproved indicates the permission was approved.
	PermissionRequestResultKindApproved PermissionRequestResultKind = "approved"

	// PermissionRequestResultKindDeniedByRules indicates the permission was denied by rules.
	PermissionRequestResultKindDeniedByRules PermissionRequestResultKind = "denied-by-rules"

	// PermissionRequestResultKindDeniedCouldNotRequestFromUser indicates the permission was denied because
	// no approval rule was found and the user could not be prompted.
	PermissionRequestResultKindDeniedCouldNotRequestFromUser PermissionRequestResultKind = "denied-no-approval-rule-and-could-not-request-from-user"

	// PermissionRequestResultKindDeniedInteractivelyByUser indicates the permission was denied interactively by the user.
	PermissionRequestResultKindDeniedInteractivelyByUser PermissionRequestResultKind = "denied-interactively-by-user"
)

type PingResponse

type PingResponse struct {
	Message         string `json:"message"`
	Timestamp       int64  `json:"timestamp"`
	ProtocolVersion *int   `json:"protocolVersion,omitempty"`
}

PingResponse is the response from a ping request

type PossibleURL added in v0.1.31

type PossibleURL struct {
	// URL that may be accessed by the command
	URL string `json:"url"`
}

type PostToolUseHandler added in v0.1.20

type PostToolUseHandler func(input PostToolUseHookInput, invocation HookInvocation) (*PostToolUseHookOutput, error)

PostToolUseHandler handles post-tool-use hook invocations

type PostToolUseHookInput added in v0.1.20

type PostToolUseHookInput struct {
	Timestamp  int64  `json:"timestamp"`
	Cwd        string `json:"cwd"`
	ToolName   string `json:"toolName"`
	ToolArgs   any    `json:"toolArgs"`
	ToolResult any    `json:"toolResult"`
}

PostToolUseHookInput is the input for a post-tool-use hook

type PostToolUseHookOutput added in v0.1.20

type PostToolUseHookOutput struct {
	ModifiedResult    any    `json:"modifiedResult,omitempty"`
	AdditionalContext string `json:"additionalContext,omitempty"`
	SuppressOutput    bool   `json:"suppressOutput,omitempty"`
}

PostToolUseHookOutput is the output for a post-tool-use hook

type PreToolUseHandler added in v0.1.20

type PreToolUseHandler func(input PreToolUseHookInput, invocation HookInvocation) (*PreToolUseHookOutput, error)

PreToolUseHandler handles pre-tool-use hook invocations

type PreToolUseHookInput added in v0.1.20

type PreToolUseHookInput struct {
	Timestamp int64  `json:"timestamp"`
	Cwd       string `json:"cwd"`
	ToolName  string `json:"toolName"`
	ToolArgs  any    `json:"toolArgs"`
}

PreToolUseHookInput is the input for a pre-tool-use hook

type PreToolUseHookOutput added in v0.1.20

type PreToolUseHookOutput struct {
	PermissionDecision       string `json:"permissionDecision,omitempty"` // "allow", "deny", "ask"
	PermissionDecisionReason string `json:"permissionDecisionReason,omitempty"`
	ModifiedArgs             any    `json:"modifiedArgs,omitempty"`
	AdditionalContext        string `json:"additionalContext,omitempty"`
	SuppressOutput           bool   `json:"suppressOutput,omitempty"`
}

PreToolUseHookOutput is the output for a pre-tool-use hook

type ProviderConfig

type ProviderConfig struct {
	// Type is the provider type: "openai", "azure", or "anthropic". Defaults to "openai".
	Type string `json:"type,omitempty"`
	// WireApi is the API format (openai/azure only): "completions" or "responses". Defaults to "completions".
	WireApi string `json:"wireApi,omitempty"`
	// BaseURL is the API endpoint URL
	BaseURL string `json:"baseUrl"`
	// APIKey is the API key. Optional for local providers like Ollama.
	APIKey string `json:"apiKey,omitempty"`
	// BearerToken for authentication. Sets the Authorization header directly.
	// Use this for services requiring bearer token auth instead of API key.
	// Takes precedence over APIKey when both are set.
	BearerToken string `json:"bearerToken,omitempty"`
	// Azure contains Azure-specific options
	Azure *AzureProviderOptions `json:"azure,omitempty"`
}

ProviderConfig configures a custom model provider

type QuotaSnapshot added in v0.1.15

type QuotaSnapshot struct {
	// Total requests allowed by the entitlement
	EntitlementRequests float64 `json:"entitlementRequests"`
	// Whether the user has an unlimited usage entitlement
	IsUnlimitedEntitlement bool `json:"isUnlimitedEntitlement"`
	// Number of requests over the entitlement limit
	Overage float64 `json:"overage"`
	// Whether overage is allowed when quota is exhausted
	OverageAllowedWithExhaustedQuota bool `json:"overageAllowedWithExhaustedQuota"`
	// Percentage of quota remaining (0.0 to 1.0)
	RemainingPercentage float64 `json:"remainingPercentage"`
	// Date when the quota resets
	ResetDate *time.Time `json:"resetDate,omitempty"`
	// Whether usage is still permitted after quota exhaustion
	UsageAllowedWithExhaustedQuota bool `json:"usageAllowedWithExhaustedQuota"`
	// Number of requests already consumed
	UsedRequests float64 `json:"usedRequests"`
}

type ReferenceType added in v0.1.29

type ReferenceType string

Type of GitHub reference

const (
	Discussion ReferenceType = "discussion"
	Issue      ReferenceType = "issue"
	PR         ReferenceType = "pr"
)

type RepositoryClass added in v0.1.24

type RepositoryClass struct {
	// Git branch name, if applicable
	Branch *string `json:"branch,omitempty"`
	// Repository name
	Name string `json:"name"`
	// Repository owner (user or organization)
	Owner string `json:"owner"`
}

Repository context for the handed-off session

type RepositoryUnion added in v0.1.24

type RepositoryUnion struct {
	RepositoryClass *RepositoryClass
	String          *string
}

func (*RepositoryUnion) MarshalJSON added in v0.1.24

func (x *RepositoryUnion) MarshalJSON() ([]byte, error)

func (*RepositoryUnion) UnmarshalJSON added in v0.1.24

func (x *RepositoryUnion) UnmarshalJSON(data []byte) error

type RequestedSchema added in v0.1.31

type RequestedSchema struct {
	// Form field definitions, keyed by field name
	Properties map[string]interface{} `json:"properties"`
	// List of required field names
	Required []string            `json:"required,omitempty"`
	Type     RequestedSchemaType `json:"type"`
}

JSON Schema describing the form fields to present to the user

type RequestedSchemaType added in v0.1.31

type RequestedSchemaType string
const (
	Object RequestedSchemaType = "object"
)

type Requests added in v0.1.21

type Requests struct {
	// Cumulative cost multiplier for requests to this model
	Cost float64 `json:"cost"`
	// Total number of API requests made to this model
	Count float64 `json:"count"`
}

Request count and cost metrics

type ResourceClass added in v0.1.24

type ResourceClass struct {
	// MIME type of the text content
	//
	// MIME type of the blob content
	MIMEType *string `json:"mimeType,omitempty"`
	// Text content of the resource
	Text *string `json:"text,omitempty"`
	// URI identifying the resource
	URI string `json:"uri"`
	// Base64-encoded binary content of the resource
	Blob *string `json:"blob,omitempty"`
}

The embedded resource contents, either text or base64-encoded binary

type Result added in v0.1.15

type Result struct {
	// Concise tool result text sent to the LLM for chat completion, potentially truncated for
	// token efficiency
	Content *string `json:"content,omitempty"`
	// Structured content blocks (text, images, audio, resources) returned by the tool in their
	// native format
	Contents []Content `json:"contents,omitempty"`
	// Full detailed tool result for UI/timeline display, preserving complete content such as
	// diffs. Falls back to content when absent.
	DetailedContent *string `json:"detailedContent,omitempty"`
	// The outcome of the permission request
	Kind *ResultKind `json:"kind,omitempty"`
}

Tool execution result on success

The result of the permission request

type ResultKind added in v0.1.31

type ResultKind string

The outcome of the permission request

const (
	Approved                                       ResultKind = "approved"
	DeniedByContentExclusionPolicy                 ResultKind = "denied-by-content-exclusion-policy"
	DeniedByRules                                  ResultKind = "denied-by-rules"
	DeniedInteractivelyByUser                      ResultKind = "denied-interactively-by-user"
	DeniedNoApprovalRuleAndCouldNotRequestFromUser ResultKind = "denied-no-approval-rule-and-could-not-request-from-user"
)

type ResumeSessionConfig

type ResumeSessionConfig struct {
	// ClientName identifies the application using the SDK.
	// Included in the User-Agent header for API requests.
	ClientName string
	// Model to use for this session. Can change the model when resuming.
	Model string
	// Tools exposes caller-implemented tools to the CLI
	Tools []Tool
	// SystemMessage configures system message customization
	SystemMessage *SystemMessageConfig
	// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
	// Takes precedence over ExcludedTools.
	AvailableTools []string
	// ExcludedTools is a list of tool names to disable. All other tools remain available.
	// Ignored if AvailableTools is specified.
	ExcludedTools []string
	// Provider configures a custom model provider
	Provider *ProviderConfig
	// ReasoningEffort level for models that support it.
	// Valid values: "low", "medium", "high", "xhigh"
	ReasoningEffort string
	// OnPermissionRequest is a handler for permission requests from the server.
	// If nil, all permission requests are denied by default.
	// Provide a handler to approve operations (file writes, shell commands, URL fetches, etc.).
	OnPermissionRequest PermissionHandlerFunc
	// OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool)
	OnUserInputRequest UserInputHandler
	// Hooks configures hook handlers for session lifecycle events
	Hooks *SessionHooks
	// WorkingDirectory is the working directory for the session.
	// Tool operations will be relative to this directory.
	WorkingDirectory string
	// ConfigDir overrides the default configuration directory location.
	ConfigDir string
	// 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
}

ResumeSessionConfig configures options when resuming a session

type Role added in v0.1.15

type Role string

Message role: "system" for system prompts, "developer" for developer-injected instructions

const (
	Developer Role = "developer"
	System    Role = "system"
)

type SelectionClass added in v0.1.19

type SelectionClass struct {
	End   End   `json:"end"`
	Start Start `json:"start"`
}

Position range of the selection within the file

type Session

type Session struct {
	// SessionID is the unique identifier for this session.
	SessionID string

	// RPC provides typed session-scoped RPC methods.
	RPC *rpc.SessionRpc
	// contains filtered or unexported fields
}

Session represents a single conversation session with the Copilot CLI.

A session maintains conversation state, handles events, and manages tool execution. Sessions are created via Client.CreateSession or resumed via Client.ResumeSession.

The session provides methods to send messages, subscribe to events, retrieve conversation history, and manage the session lifecycle. All methods are safe for concurrent use.

Example usage:

session, err := client.CreateSession(copilot.SessionConfig{
    Model: "gpt-4",
})
if err != nil {
    log.Fatal(err)
}
defer session.Disconnect()

// Subscribe to events
unsubscribe := session.On(func(event copilot.SessionEvent) {
    if event.Type == "assistant.message" {
        fmt.Println("Assistant:", event.Data.Content)
    }
})
defer unsubscribe()

// Send a message
messageID, err := session.Send(copilot.MessageOptions{
    Prompt: "Hello, world!",
})

func (*Session) Abort

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 disconnected or the connection fails.

Example:

// Start a long-running request in a goroutine
go func() {
    session.Send(context.Background(), copilot.MessageOptions{
        Prompt: "Write a very long story...",
    })
}()

// Abort after 5 seconds
time.Sleep(5 * time.Second)
if err := session.Abort(context.Background()); err != nil {
    log.Printf("Failed to abort: %v", err)
}

func (*Session) Destroy deprecated

func (s *Session) Destroy() error

Deprecated: Use Session.Disconnect instead. Destroy will be removed in a future release.

Destroy closes this session and releases all in-memory resources. Session data on disk is preserved for later resumption.

func (*Session) Disconnect added in v0.1.31

func (s *Session) Disconnect() error

Disconnect closes this session and releases all in-memory resources (event handlers, tool handlers, permission handlers).

Session state on disk (conversation history, planning state, artifacts) is preserved, so the conversation can be resumed later by calling Client.ResumeSession with the session ID. To permanently remove all session data including files on disk, use Client.DeleteSession instead.

After calling this method, the session object can no longer be used.

Returns an error if the connection fails.

Example:

// Clean up when done — session can still be resumed later
if err := session.Disconnect(); err != nil {
    log.Printf("Failed to disconnect session: %v", err)
}

func (*Session) GetMessages

func (s *Session) GetMessages(ctx context.Context) ([]SessionEvent, error)

GetMessages retrieves all events and messages from this session's history.

This returns the complete conversation history including user messages, assistant responses, tool executions, and other session events in chronological order.

Returns an error if the session has been disconnected or the connection fails.

Example:

events, err := session.GetMessages(context.Background())
if err != nil {
    log.Printf("Failed to get messages: %v", err)
    return
}
for _, event := range events {
    if event.Type == "assistant.message" {
        fmt.Println("Assistant:", event.Data.Content)
    }
}

func (*Session) On

func (s *Session) On(handler SessionEventHandler) func()

On subscribes to events from this session.

Events include assistant messages, tool executions, errors, and session state changes. Multiple handlers can be registered and will all receive events. Handlers are called synchronously in the order they were registered.

The returned function can be called to unsubscribe the handler. It is safe to call the unsubscribe function multiple times.

Example:

unsubscribe := session.On(func(event copilot.SessionEvent) {
    switch 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

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 to receive streaming responses and other session events.

Parameters:

  • options: The message options including the prompt and optional attachments.

Returns the message ID of the response, which can be used to correlate events, or an error if the session has been disconnected or the connection fails.

Example:

messageID, err := session.Send(context.Background(), copilot.MessageOptions{
    Prompt: "Explain this code",
    Attachments: []copilot.Attachment{
        {Type: "file", Path: "./main.go"},
    },
})
if err != nil {
    log.Printf("Failed to send message: %v", err)
}

func (*Session) SendAndWait

func (s *Session) SendAndWait(ctx context.Context, options MessageOptions) (*SessionEvent, error)

SendAndWait sends a message to this session and waits until the session becomes idle.

This is a convenience method that combines Session.Send with waiting for the session.idle event. Use this when you want to block until the assistant has finished processing the message.

Events are still delivered to handlers registered via Session.On while waiting.

Parameters:

  • options: The message options including the prompt and optional attachments.
  • timeout: How long to wait for completion. Defaults to 60 seconds if zero. Controls how long to wait; does not abort in-flight agent work.

Returns the final assistant message event, or nil if none was received. Returns an error if the timeout is reached or the connection fails.

Example:

response, err := session.SendAndWait(context.Background(), copilot.MessageOptions{
    Prompt: "What is 2+2?",
}) // Use default 60s timeout
if err != nil {
    log.Printf("Failed: %v", err)
}
if response != nil {
    fmt.Println(*response.Data.Content)
}

func (*Session) SetModel added in v0.1.30

func (s *Session) SetModel(ctx context.Context, model string) error

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"); err != nil {
    log.Printf("Failed to set model: %v", err)
}

func (*Session) WorkspacePath added in v0.1.18

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

type SessionConfig struct {
	// SessionID is an optional custom session ID
	SessionID string
	// ClientName identifies the application using the SDK.
	// Included in the User-Agent header for API requests.
	ClientName string
	// Model to use for this session
	Model string
	// ReasoningEffort level for models that support it.
	// Valid values: "low", "medium", "high", "xhigh"
	// Only applies to models where capabilities.supports.reasoningEffort is true.
	ReasoningEffort string
	// ConfigDir overrides the default configuration directory location.
	// When specified, the session will use this directory for storing config and state.
	ConfigDir string
	// Tools exposes caller-implemented tools to the CLI
	Tools []Tool
	// SystemMessage configures system message customization
	SystemMessage *SystemMessageConfig
	// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
	// Takes precedence over ExcludedTools.
	AvailableTools []string
	// ExcludedTools is a list of tool names to disable. All other tools remain available.
	// Ignored if AvailableTools is specified.
	ExcludedTools []string
	// OnPermissionRequest is a handler for permission requests from the server.
	// If nil, all permission requests are denied by default.
	// Provide a handler to approve operations (file writes, shell commands, URL fetches, etc.).
	OnPermissionRequest PermissionHandlerFunc
	// OnUserInputRequest is a handler for user input requests from the agent (enables ask_user tool)
	OnUserInputRequest UserInputHandler
	// Hooks configures hook handlers for session lifecycle events
	Hooks *SessionHooks
	// WorkingDirectory is the working directory for the session.
	// Tool operations will be relative to this directory.
	WorkingDirectory string
	// Streaming enables streaming of assistant message and reasoning chunks.
	// When true, assistant.message_delta and assistant.reasoning_delta events
	// with deltaContent are sent as the response is generated.
	Streaming bool
	// Provider configures a custom model provider (BYOK)
	Provider *ProviderConfig
	// 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
}

SessionConfig configures a new session

type SessionContext added in v0.1.24

type SessionContext struct {
	// Cwd is the working directory where the session was created
	Cwd string `json:"cwd"`
	// GitRoot is the git repository root (if in a git repo)
	GitRoot string `json:"gitRoot,omitempty"`
	// Repository is the GitHub repository in "owner/repo" format
	Repository string `json:"repository,omitempty"`
	// Branch is the current git branch
	Branch string `json:"branch,omitempty"`
}

SessionContext contains working directory context for a session

type SessionEndHandler added in v0.1.20

type SessionEndHandler func(input SessionEndHookInput, invocation HookInvocation) (*SessionEndHookOutput, error)

SessionEndHandler handles session-end hook invocations

type SessionEndHookInput added in v0.1.20

type SessionEndHookInput struct {
	Timestamp    int64  `json:"timestamp"`
	Cwd          string `json:"cwd"`
	Reason       string `json:"reason"` // "complete", "error", "abort", "timeout", "user_exit"
	FinalMessage string `json:"finalMessage,omitempty"`
	Error        string `json:"error,omitempty"`
}

SessionEndHookInput is the input for a session-end hook

type SessionEndHookOutput added in v0.1.20

type SessionEndHookOutput struct {
	SuppressOutput bool     `json:"suppressOutput,omitempty"`
	CleanupActions []string `json:"cleanupActions,omitempty"`
	SessionSummary string   `json:"sessionSummary,omitempty"`
}

SessionEndHookOutput is the output for a session-end hook

type SessionEvent

type SessionEvent struct {
	// Payload indicating the agent is idle; includes any background tasks still in flight
	//
	// Empty payload; the event signals that LLM-powered conversation compaction has begun
	//
	// Empty payload; the event signals that the pending message queue has changed
	//
	// Empty payload; the event signals that the custom agent was deselected, returning to the
	// default agent
	Data Data `json:"data"`
	// When true, the event is transient and not persisted to the session event log on disk
	Ephemeral *bool `json:"ephemeral,omitempty"`
	// Unique event identifier (UUID v4), generated when the event is emitted
	ID string `json:"id"`
	// ID of the chronologically preceding event in the session, forming a linked chain. Null
	// for the first event.
	ParentID *string `json:"parentId"`
	// ISO 8601 timestamp when the event was created
	Timestamp time.Time        `json:"timestamp"`
	Type      SessionEventType `json:"type"`
}

func UnmarshalSessionEvent added in v0.1.15

func UnmarshalSessionEvent(data []byte) (SessionEvent, error)

func (*SessionEvent) Marshal added in v0.1.15

func (r *SessionEvent) Marshal() ([]byte, error)

type SessionEventHandler

type SessionEventHandler func(event SessionEvent)

SessionEventHandler is a callback for session events

type SessionEventType added in v0.1.15

type SessionEventType string
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"
	AssistantStreamingDelta     SessionEventType = "assistant.streaming_delta"
	AssistantTurnEnd            SessionEventType = "assistant.turn_end"
	AssistantTurnStart          SessionEventType = "assistant.turn_start"
	AssistantUsage              SessionEventType = "assistant.usage"
	CommandCompleted            SessionEventType = "command.completed"
	CommandQueued               SessionEventType = "command.queued"
	ElicitationCompleted        SessionEventType = "elicitation.completed"
	ElicitationRequested        SessionEventType = "elicitation.requested"
	ExitPlanModeCompleted       SessionEventType = "exit_plan_mode.completed"
	ExitPlanModeRequested       SessionEventType = "exit_plan_mode.requested"
	ExternalToolCompleted       SessionEventType = "external_tool.completed"
	ExternalToolRequested       SessionEventType = "external_tool.requested"
	HookEnd                     SessionEventType = "hook.end"
	HookStart                   SessionEventType = "hook.start"
	PendingMessagesModified     SessionEventType = "pending_messages.modified"
	PermissionCompleted         SessionEventType = "permission.completed"
	PermissionRequested         SessionEventType = "permission.requested"
	SessionCompactionComplete   SessionEventType = "session.compaction_complete"
	SessionCompactionStart      SessionEventType = "session.compaction_start"
	SessionContextChanged       SessionEventType = "session.context_changed"
	SessionError                SessionEventType = "session.error"
	SessionHandoff              SessionEventType = "session.handoff"
	SessionIdle                 SessionEventType = "session.idle"
	SessionInfo                 SessionEventType = "session.info"
	SessionModeChanged          SessionEventType = "session.mode_changed"
	SessionModelChange          SessionEventType = "session.model_change"
	SessionPlanChanged          SessionEventType = "session.plan_changed"
	SessionResume               SessionEventType = "session.resume"
	SessionShutdown             SessionEventType = "session.shutdown"
	SessionSnapshotRewind       SessionEventType = "session.snapshot_rewind"
	SessionStart                SessionEventType = "session.start"
	SessionTaskComplete         SessionEventType = "session.task_complete"
	SessionTitleChanged         SessionEventType = "session.title_changed"
	SessionTruncation           SessionEventType = "session.truncation"
	SessionUsageInfo            SessionEventType = "session.usage_info"
	SessionWarning              SessionEventType = "session.warning"
	SessionWorkspaceFileChanged SessionEventType = "session.workspace_file_changed"
	SkillInvoked                SessionEventType = "skill.invoked"
	SubagentCompleted           SessionEventType = "subagent.completed"
	SubagentDeselected          SessionEventType = "subagent.deselected"
	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"
	UserInputCompleted          SessionEventType = "user_input.completed"
	UserInputRequested          SessionEventType = "user_input.requested"
	UserMessage                 SessionEventType = "user.message"
)

type SessionHooks added in v0.1.20

type SessionHooks struct {
	OnPreToolUse          PreToolUseHandler
	OnPostToolUse         PostToolUseHandler
	OnUserPromptSubmitted UserPromptSubmittedHandler
	OnSessionStart        SessionStartHandler
	OnSessionEnd          SessionEndHandler
	OnErrorOccurred       ErrorOccurredHandler
}

SessionHooks configures hook handlers for a session

type SessionLifecycleEvent added in v0.1.21

type SessionLifecycleEvent struct {
	Type      SessionLifecycleEventType      `json:"type"`
	SessionID string                         `json:"sessionId"`
	Metadata  *SessionLifecycleEventMetadata `json:"metadata,omitempty"`
}

SessionLifecycleEvent represents a session lifecycle notification

type SessionLifecycleEventMetadata added in v0.1.21

type SessionLifecycleEventMetadata struct {
	StartTime    string  `json:"startTime"`
	ModifiedTime string  `json:"modifiedTime"`
	Summary      *string `json:"summary,omitempty"`
}

SessionLifecycleEventMetadata contains optional metadata for lifecycle events

type SessionLifecycleEventType added in v0.1.21

type SessionLifecycleEventType string

SessionLifecycleEventType represents the type of session lifecycle event

const (
	SessionLifecycleCreated    SessionLifecycleEventType = "session.created"
	SessionLifecycleDeleted    SessionLifecycleEventType = "session.deleted"
	SessionLifecycleUpdated    SessionLifecycleEventType = "session.updated"
	SessionLifecycleForeground SessionLifecycleEventType = "session.foreground"
	SessionLifecycleBackground SessionLifecycleEventType = "session.background"
)

type SessionLifecycleHandler added in v0.1.21

type SessionLifecycleHandler func(event SessionLifecycleEvent)

SessionLifecycleHandler is a callback for session lifecycle events

type SessionListFilter added in v0.1.24

type SessionListFilter struct {
	// Cwd filters by exact working directory match
	Cwd string `json:"cwd,omitempty"`
	// GitRoot filters by git root
	GitRoot string `json:"gitRoot,omitempty"`
	// Repository filters by repository (owner/repo format)
	Repository string `json:"repository,omitempty"`
	// Branch filters by branch
	Branch string `json:"branch,omitempty"`
}

SessionListFilter contains filter options for listing sessions

type SessionMetadata added in v0.1.19

type SessionMetadata struct {
	SessionID    string          `json:"sessionId"`
	StartTime    string          `json:"startTime"`
	ModifiedTime string          `json:"modifiedTime"`
	Summary      *string         `json:"summary,omitempty"`
	IsRemote     bool            `json:"isRemote"`
	Context      *SessionContext `json:"context,omitempty"`
}

SessionMetadata contains metadata about a session

type SessionStartHandler added in v0.1.20

type SessionStartHandler func(input SessionStartHookInput, invocation HookInvocation) (*SessionStartHookOutput, error)

SessionStartHandler handles session-start hook invocations

type SessionStartHookInput added in v0.1.20

type SessionStartHookInput struct {
	Timestamp     int64  `json:"timestamp"`
	Cwd           string `json:"cwd"`
	Source        string `json:"source"` // "startup", "resume", "new"
	InitialPrompt string `json:"initialPrompt,omitempty"`
}

SessionStartHookInput is the input for a session-start hook

type SessionStartHookOutput added in v0.1.20

type SessionStartHookOutput struct {
	AdditionalContext string         `json:"additionalContext,omitempty"`
	ModifiedConfig    map[string]any `json:"modifiedConfig,omitempty"`
}

SessionStartHookOutput is the output for a session-start hook

type Shell added in v0.1.24

type Shell struct {
	// Human-readable description of the shell command
	Description *string `json:"description,omitempty"`
	// Unique identifier of the background shell
	ShellID string `json:"shellId"`
}

type ShutdownType added in v0.1.21

type ShutdownType string

Whether the session ended normally ("routine") or due to a crash/fatal error ("error")

const (
	Error   ShutdownType = "error"
	Routine ShutdownType = "routine"
)

type SourceType added in v0.1.15

type SourceType string

Origin type of the session being handed off

const (
	Local  SourceType = "local"
	Remote SourceType = "remote"
)

type Start added in v0.1.19

type Start struct {
	// Start character offset within the line (0-based)
	Character float64 `json:"character"`
	// Start line number (0-based)
	Line float64 `json:"line"`
}

type SystemMessageAppendConfig

type SystemMessageAppendConfig struct {
	// Mode is optional, defaults to "append"
	Mode string `json:"mode,omitempty"`
	// Content provides additional instructions appended after SDK-managed sections
	Content string `json:"content,omitempty"`
}

SystemMessageAppendConfig is append mode: use CLI foundation with optional appended content.

type SystemMessageConfig

type SystemMessageConfig struct {
	Mode    string `json:"mode,omitempty"`
	Content string `json:"content,omitempty"`
}

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.

type SystemMessageReplaceConfig

type SystemMessageReplaceConfig struct {
	// Mode must be "replace"
	Mode string `json:"mode"`
	// Content is the complete system message (required)
	Content string `json:"content"`
}

SystemMessageReplaceConfig is replace mode: use caller-provided system message entirely. Removes all SDK guardrails including security restrictions.

type Theme added in v0.1.24

type Theme string

Theme variant this icon is intended for

const (
	Dark  Theme = "dark"
	Light Theme = "light"
)

type TokenDetail added in v0.1.29

type TokenDetail struct {
	// Number of tokens in this billing batch
	BatchSize float64 `json:"batchSize"`
	// Cost per batch of tokens
	CostPerBatch float64 `json:"costPerBatch"`
	// Total token count for this entry
	TokenCount float64 `json:"tokenCount"`
	// Token category (e.g., "input", "output")
	TokenType string `json:"tokenType"`
}

type Tool

type Tool struct {
	Name                 string         `json:"name"`
	Description          string         `json:"description,omitempty"`
	Parameters           map[string]any `json:"parameters,omitempty"`
	OverridesBuiltInTool bool           `json:"overridesBuiltInTool,omitempty"`
	Handler              ToolHandler    `json:"-"`
}

Tool describes a caller-implemented tool that can be invoked by Copilot

func DefineTool

func DefineTool[T any, U any](name, description string, handler func(T, ToolInvocation) (U, error)) Tool

DefineTool creates a Tool with automatic JSON schema generation from a typed handler function. The handler receives typed arguments (automatically unmarshaled from JSON) and the raw ToolInvocation. The handler can return any value - strings pass through directly, other types are JSON-serialized.

Example:

type GetWeatherParams struct {
    City string `json:"city" jsonschema:"city name"`
    Unit string `json:"unit" jsonschema:"temperature unit (celsius or fahrenheit)"`
}

tool := copilot.DefineTool("get_weather", "Get weather for a city",
    func(params GetWeatherParams, inv copilot.ToolInvocation) (any, error) {
        return fmt.Sprintf("Weather in %s: 22°%s", params.City, params.Unit), nil
    })

type ToolBinaryResult

type ToolBinaryResult struct {
	Data        string `json:"data"`
	MimeType    string `json:"mimeType"`
	Type        string `json:"type"`
	Description string `json:"description,omitempty"`
}

ToolBinaryResult represents binary payloads returned by tools.

type ToolHandler

type ToolHandler func(invocation ToolInvocation) (ToolResult, error)

ToolHandler executes a tool invocation. The handler should return a ToolResult. Returning an error marks the tool execution as a failure.

type ToolInvocation

type ToolInvocation struct {
	SessionID  string
	ToolCallID string
	ToolName   string
	Arguments  any
}

ToolInvocation describes a tool call initiated by Copilot

type ToolRequest added in v0.1.15

type ToolRequest struct {
	// Arguments to pass to the tool, format depends on the tool
	Arguments interface{} `json:"arguments"`
	// Name of the tool being invoked
	Name string `json:"name"`
	// Unique identifier for this tool call
	ToolCallID string `json:"toolCallId"`
	// Tool call type: "function" for standard tool calls, "custom" for grammar-based tool
	// calls. Defaults to "function" when absent.
	Type *ToolRequestType `json:"type,omitempty"`
}

type ToolRequestType added in v0.1.15

type ToolRequestType string

Tool call type: "function" for standard tool calls, "custom" for grammar-based tool calls. Defaults to "function" when absent.

const (
	Custom   ToolRequestType = "custom"
	Function ToolRequestType = "function"
)

type ToolResult

type ToolResult struct {
	TextResultForLLM    string             `json:"textResultForLlm"`
	BinaryResultsForLLM []ToolBinaryResult `json:"binaryResultsForLlm,omitempty"`
	ResultType          string             `json:"resultType"`
	Error               string             `json:"error,omitempty"`
	SessionLog          string             `json:"sessionLog,omitempty"`
	ToolTelemetry       map[string]any     `json:"toolTelemetry,omitempty"`
}

ToolResult represents the result of a tool invocation.

type Usage added in v0.1.21

type Usage struct {
	// Total tokens read from prompt cache across all requests
	CacheReadTokens float64 `json:"cacheReadTokens"`
	// Total tokens written to prompt cache across all requests
	CacheWriteTokens float64 `json:"cacheWriteTokens"`
	// Total input tokens consumed across all requests to this model
	InputTokens float64 `json:"inputTokens"`
	// Total output tokens produced across all requests to this model
	OutputTokens float64 `json:"outputTokens"`
}

Token usage breakdown

type UserInputHandler added in v0.1.20

type UserInputHandler func(request UserInputRequest, invocation UserInputInvocation) (UserInputResponse, error)

UserInputHandler handles user input requests from the agent The handler should return a UserInputResponse. Returning an error fails the request.

type UserInputInvocation added in v0.1.20

type UserInputInvocation struct {
	SessionID string
}

UserInputInvocation provides context about a user input request

type UserInputRequest added in v0.1.20

type UserInputRequest struct {
	Question      string
	Choices       []string
	AllowFreeform *bool
}

UserInputRequest represents a request for user input from the agent

type UserInputResponse added in v0.1.20

type UserInputResponse struct {
	Answer      string
	WasFreeform bool
}

UserInputResponse represents the user's response to an input request

type UserPromptSubmittedHandler added in v0.1.20

type UserPromptSubmittedHandler func(input UserPromptSubmittedHookInput, invocation HookInvocation) (*UserPromptSubmittedHookOutput, error)

UserPromptSubmittedHandler handles user-prompt-submitted hook invocations

type UserPromptSubmittedHookInput added in v0.1.20

type UserPromptSubmittedHookInput struct {
	Timestamp int64  `json:"timestamp"`
	Cwd       string `json:"cwd"`
	Prompt    string `json:"prompt"`
}

UserPromptSubmittedHookInput is the input for a user-prompt-submitted hook

type UserPromptSubmittedHookOutput added in v0.1.20

type UserPromptSubmittedHookOutput struct {
	ModifiedPrompt    string `json:"modifiedPrompt,omitempty"`
	AdditionalContext string `json:"additionalContext,omitempty"`
	SuppressOutput    bool   `json:"suppressOutput,omitempty"`
}

UserPromptSubmittedHookOutput is the output for a user-prompt-submitted hook

Directories

Path Synopsis
cmd
bundler command
Bundler downloads Copilot CLI binaries and packages them as a binary file, along with a Go source file that embeds the binary and metadata.
Bundler downloads Copilot CLI binaries and packages them as a binary file, along with a Go source file that embeds the binary and metadata.
internal
samples module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL