agent

package
v1.23.13 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatSessionTime

func FormatSessionTime(ts string) string

FormatSessionTime formats a timestamp string into a human-friendly relative time display.

Types

type Agent

type Agent interface {
	// Initialize handles first-run configuration (model/reasoning setup).
	Initialize(ctx context.Context, opts ...InitOption) (*InitResult, error)
	// SendMessage sends a prompt and returns per-turn results.
	SendMessage(ctx context.Context, prompt string, opts ...SendOption) (*AgentResult, error)
	// SendMessageWithRetry wraps SendMessage with interactive retry-on-error UX.
	SendMessageWithRetry(ctx context.Context, prompt string, opts ...SendOption) (*AgentResult, error)
	// ListSessions returns previous sessions for the given working directory.
	ListSessions(ctx context.Context, cwd string) ([]SessionMetadata, error)
	// GetMetrics returns cumulative session metrics (usage + file changes).
	GetMetrics() AgentMetrics
	// GetMessages returns the session event log from the Copilot SDK.
	GetMessages(ctx context.Context) ([]SessionEvent, error)
	// SessionID returns the current session ID, or empty if no session exists.
	SessionID() string
	// Stop terminates the agent and releases resources.
	Stop() error
}

Agent defines the interface for Copilot agent operations. Used by the gRPC service layer to decouple from the concrete CopilotAgent implementation.

type AgentDisplay

type AgentDisplay struct {
	// contains filtered or unexported fields
}

AgentDisplay handles UX rendering for Copilot SDK session events. It subscribes directly to session.On() and manages a Canvas with Spinner and VisualElement layers to render tool execution, thinking, streaming response tokens, errors, and other agent activity.

func NewAgentDisplay

func NewAgentDisplay(console input.Console) *AgentDisplay

NewAgentDisplay creates a new AgentDisplay.

func (*AgentDisplay) GetUsageMetrics

func (d *AgentDisplay) GetUsageMetrics() UsageMetrics

GetUsageMetrics returns the accumulated usage metrics for this display session.

func (*AgentDisplay) HandleEvent

func (d *AgentDisplay) HandleEvent(event copilot.SessionEvent)

HandleEvent processes a Copilot SDK SessionEvent and updates the UX. This is called synchronously by the SDK for each event.

func (*AgentDisplay) Pause

func (d *AgentDisplay) Pause()

Pause stops canvas updates for interactive prompts. Write-locks renderGuard so any in-flight ticker render completes and future renders are blocked until Resume().

func (*AgentDisplay) Resume

func (d *AgentDisplay) Resume()

Resume restarts canvas updates after an interactive prompt.

func (*AgentDisplay) Start

func (d *AgentDisplay) Start(ctx context.Context) (func(), error)

Start initializes the canvas and spinner for rendering. Returns a cleanup function that must be called when done.

func (*AgentDisplay) WaitForIdle

func (d *AgentDisplay) WaitForIdle(ctx context.Context) error

WaitForIdle blocks until the session becomes idle or the context is cancelled. Returns the final assistant message content.

type AgentFactory

type AgentFactory interface {
	// Create builds a new Agent with the given options.
	Create(ctx context.Context, opts ...AgentOption) (Agent, error)
}

AgentFactory creates Agent instances with all dependencies wired.

func NewCopilotAgentFactory

func NewCopilotAgentFactory(
	clientManager *agentcopilot.CopilotClientManager,
	sessionConfigBuilder *agentcopilot.SessionConfigBuilder,
	cli *agentcopilot.CopilotCLI,
	consentManager consent.ConsentManager,
	console input.Console,
	configManager config.UserConfigManager,
) AgentFactory

NewCopilotAgentFactory creates a new factory.

type AgentMetrics

type AgentMetrics struct {
	// Usage contains cumulative token and cost metrics.
	Usage UsageMetrics
	// FileChanges contains accumulated file changes across all SendMessage calls.
	FileChanges watch.FileChanges
}

AgentMetrics contains cumulative session metrics for usage and file changes.

func (AgentMetrics) String

func (m AgentMetrics) String() string

String returns a formatted display of file changes followed by usage metrics.

type AgentMode

type AgentMode string

AgentMode represents the operating mode for the agent.

const (
	// AgentModeInteractive asks for approval before executing tools.
	AgentModeInteractive AgentMode = "interactive"
	// AgentModeAutopilot executes tools automatically without approval.
	AgentModeAutopilot AgentMode = "autopilot"
	// AgentModePlan creates a plan first, then executes after approval.
	AgentModePlan AgentMode = "plan"
)

type AgentOption

type AgentOption func(*CopilotAgent)

AgentOption configures agent creation via the factory.

func OnSessionStarted

func OnSessionStarted(fn func(sessionID string)) AgentOption

OnSessionStarted registers a callback that fires when a session is created or resumed.

func WithDebug

func WithDebug(debug bool) AgentOption

WithDebug enables debug logging.

func WithHeadless

func WithHeadless(headless bool) AgentOption

WithHeadless enables headless mode, suppressing all console output. In headless mode, the agent uses a silent collector instead of the interactive display, and defaults to autopilot mode.

func WithMode

func WithMode(mode AgentMode) AgentOption

WithMode sets the agent mode.

func WithModel

func WithModel(model string) AgentOption

WithModel overrides the configured model for this agent.

func WithReasoningEffort

func WithReasoningEffort(effort string) AgentOption

WithReasoningEffort overrides the configured reasoning effort.

func WithSystemMessage

func WithSystemMessage(msg string) AgentOption

WithSystemMessage appends a custom system message to the agent's default system prompt.

type AgentResult

type AgentResult struct {
	// SessionID is the session identifier for resuming later.
	SessionID string
	// Usage contains token and cost metrics for this turn.
	Usage UsageMetrics
	// FileChanges contains files created/modified/deleted during this turn.
	FileChanges watch.FileChanges
}

AgentResult is returned by SendMessage with session and usage metadata.

type CopilotAgent

type CopilotAgent struct {
	// contains filtered or unexported fields
}

CopilotAgent is a self-contained agent backed by the GitHub Copilot SDK. It encapsulates initialization, session management, display, and usage tracking.

func (*CopilotAgent) EnsureStarted

func (a *CopilotAgent) EnsureStarted(ctx context.Context) error

EnsureStarted starts the Copilot SDK client and verifies authentication. Call this eagerly to catch startup errors (missing binary, auth failures) before entering a chat loop. Idempotent — safe to call multiple times.

func (*CopilotAgent) GetMessages

func (a *CopilotAgent) GetMessages(ctx context.Context) ([]SessionEvent, error)

GetMessages returns the session event log from the Copilot SDK. Returns an error if no session exists.

func (*CopilotAgent) GetMetrics

func (a *CopilotAgent) GetMetrics() AgentMetrics

GetMetrics returns cumulative session metrics (usage + file changes).

func (*CopilotAgent) Initialize

func (a *CopilotAgent) Initialize(ctx context.Context, opts ...InitOption) (result *InitResult, err error)

Initialize handles first-run configuration (model/reasoning prompts), plugin install, and Copilot client startup. If config already exists, returns current values without prompting. Use WithForcePrompt() to always show prompts.

func (*CopilotAgent) ListSessions

func (a *CopilotAgent) ListSessions(ctx context.Context, cwd string) ([]SessionMetadata, error)

ListSessions returns previous sessions for the given working directory.

func (*CopilotAgent) SelectSession

func (a *CopilotAgent) SelectSession(ctx context.Context) (*SessionMetadata, error)

SelectSession shows a UX picker with previous sessions for the current directory. Returns the selected session metadata, or nil if user chose "new session".

func (*CopilotAgent) SendMessage

func (a *CopilotAgent) SendMessage(ctx context.Context, prompt string, opts ...SendOption) (*AgentResult, error)

SendMessage sends a prompt to the agent and returns the result. Creates a new session or resumes one if WithSessionID is provided.

func (*CopilotAgent) SendMessageWithRetry

func (a *CopilotAgent) SendMessageWithRetry(ctx context.Context, prompt string, opts ...SendOption) (*AgentResult, error)

SendMessageWithRetry wraps SendMessage with interactive retry-on-error UX.

func (*CopilotAgent) SessionID

func (a *CopilotAgent) SessionID() string

SessionID returns the current session ID, or empty if no session exists.

func (*CopilotAgent) Stop

func (a *CopilotAgent) Stop() error

Stop terminates the agent, cleans up the Copilot SDK client and runtime process. Cleanup tasks run in reverse registration order. Safe to call multiple times.

type CopilotAgentFactory

type CopilotAgentFactory struct {
	// contains filtered or unexported fields
}

CopilotAgentFactory creates CopilotAgent instances with all dependencies wired. Designed for IoC injection — register with container, inject into commands.

func (*CopilotAgentFactory) Create

func (f *CopilotAgentFactory) Create(ctx context.Context, opts ...AgentOption) (Agent, error)

Create builds a new CopilotAgent with all dependencies wired. Use AgentOption functions to override model, reasoning, mode, etc.

type HeadlessCollector

type HeadlessCollector struct {
	// contains filtered or unexported fields
}

HeadlessCollector silently collects Copilot SDK session events without producing any console output. It tracks usage metrics and signals completion, making it suitable for gRPC/headless agent sessions.

func NewHeadlessCollector

func NewHeadlessCollector() *HeadlessCollector

NewHeadlessCollector creates a new HeadlessCollector.

func (*HeadlessCollector) GetUsageMetrics

func (h *HeadlessCollector) GetUsageMetrics() UsageMetrics

GetUsageMetrics returns the accumulated usage metrics.

func (*HeadlessCollector) HandleEvent

func (h *HeadlessCollector) HandleEvent(event copilot.SessionEvent)

HandleEvent processes a Copilot session event silently, collecting usage metrics and tracking completion state.

func (*HeadlessCollector) WaitForIdle

func (h *HeadlessCollector) WaitForIdle(ctx context.Context) error

WaitForIdle blocks until the session becomes idle or the context is cancelled.

type InitOption

type InitOption func(*initOptions)

InitOption configures the Initialize call.

func WithForcePrompt

func WithForcePrompt() InitOption

WithForcePrompt forces the config prompts even if config exists.

type InitResult

type InitResult struct {
	// Model is the selected model name (empty = default).
	Model string
	// ReasoningEffort is the selected reasoning level.
	ReasoningEffort string
	// IsFirstRun is true if the user was prompted for configuration.
	IsFirstRun bool
}

InitResult is returned by Initialize with configuration state.

type SendOption

type SendOption func(*sendOptions)

SendOption configures a SendMessage call.

func WithSessionID

func WithSessionID(id string) SendOption

WithSessionID resumes the specified session instead of creating a new one.

type SessionEvent

type SessionEvent = copilot.SessionEvent

SessionEvent represents a single event from the Copilot session log.

type SessionMetadata

type SessionMetadata = copilot.SessionMetadata

SessionMetadata contains metadata about a previous session.

type UsageMetrics

type UsageMetrics struct {
	Model           string
	InputTokens     float64
	OutputTokens    float64
	BillingRate     float64 // per-request cost multiplier (e.g., 1.0x, 2.0x)
	PremiumRequests float64
	DurationMS      float64
}

UsageMetrics tracks resource consumption for an agent session.

func (UsageMetrics) String

func (u UsageMetrics) String() string

String returns a multi-line formatted string for display.

func (UsageMetrics) TotalTokens

func (u UsageMetrics) TotalTokens() float64

TotalTokens returns input + output tokens.

Directories

Path Synopsis
tools
mcp

Jump to

Keyboard shortcuts

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