provider

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OpenCodePartText       = "text"
	OpenCodePartReasoning  = "reasoning"
	OpenCodePartTool       = "tool"
	OpenCodePartStepStart  = "step-start"
	OpenCodePartStepFinish = "step-finish"
)

OpenCode Part types (from research results)

Variables

This section is empty.

Functions

func InitGlobalProviderFactory

func InitGlobalProviderFactory()

InitGlobalProviderFactory initializes the global provider factory. This is called automatically on first use.

func ValidateProviderConfig

func ValidateProviderConfig(cfg ProviderConfig) error

ValidateProviderConfig validates a provider configuration.

Types

type AssistantMessage

type AssistantMessage struct {
	ID      string         `json:"id,omitempty"`
	Type    string         `json:"type,omitempty"`
	Role    string         `json:"role,omitempty"`
	Content []ContentBlock `json:"content,omitempty"`
}

AssistantMessage represents the structured message emitted by the model.

type ClaudeCodeProvider

type ClaudeCodeProvider struct {
	ProviderBase
	// contains filtered or unexported fields
}

ClaudeCodeProvider implements the Provider interface for Claude Code CLI. This is the default provider and maintains full backward compatibility with the existing HotPlex implementation.

func NewClaudeCodeProvider

func NewClaudeCodeProvider(cfg ProviderConfig, logger *slog.Logger) (*ClaudeCodeProvider, error)

NewClaudeCodeProvider creates a new Claude Code provider instance.

func (*ClaudeCodeProvider) BuildCLIArgs

func (p *ClaudeCodeProvider) BuildCLIArgs(providerSessionID string, opts *ProviderSessionOptions) []string

BuildCLIArgs constructs Claude Code CLI arguments.

func (*ClaudeCodeProvider) BuildEnvVars

func (p *ClaudeCodeProvider) BuildEnvVars(opts *ProviderSessionOptions) []string

BuildEnvVars constructs environment variables for Claude Code.

func (*ClaudeCodeProvider) BuildInputMessage

func (p *ClaudeCodeProvider) BuildInputMessage(prompt string, taskInstructions string) (map[string]any, error)

BuildInputMessage constructs the stream-json input message.

func (*ClaudeCodeProvider) CheckSessionMarker

func (p *ClaudeCodeProvider) CheckSessionMarker(providerSessionID string) bool

CheckSessionMarker checks if a session marker exists for the given ID.

func (*ClaudeCodeProvider) DetectTurnEnd

func (p *ClaudeCodeProvider) DetectTurnEnd(event *ProviderEvent) bool

DetectTurnEnd checks if the event signals turn completion.

func (*ClaudeCodeProvider) ExtractSessionID

func (p *ClaudeCodeProvider) ExtractSessionID(event *ProviderEvent) string

ExtractSessionID extracts the Claude session ID from events.

func (*ClaudeCodeProvider) GetMarkerDir

func (p *ClaudeCodeProvider) GetMarkerDir() string

GetMarkerDir returns the session marker directory path.

func (*ClaudeCodeProvider) ParseEvent

func (p *ClaudeCodeProvider) ParseEvent(line string) (*ProviderEvent, error)

ParseEvent parses a Claude Code stream-json line into a ProviderEvent.

func (*ClaudeCodeProvider) ValidateBinary

func (p *ClaudeCodeProvider) ValidateBinary() (string, error)

ValidateBinary checks if the Claude CLI is available.

type ContentBlock

type ContentBlock struct {
	Type      string         `json:"type"`
	Text      string         `json:"text,omitempty"`
	Name      string         `json:"name,omitempty"`
	ID        string         `json:"id,omitempty"`
	ToolUseID string         `json:"tool_use_id,omitempty"`
	Input     map[string]any `json:"input,omitempty"`
	Content   string         `json:"content,omitempty"`
	IsError   bool           `json:"is_error,omitempty"`
}

ContentBlock represents an atomic unit of model output.

func (*ContentBlock) GetUnifiedToolID

func (b *ContentBlock) GetUnifiedToolID() string

GetUnifiedToolID returns a tool identifier suitable for matching calls with results.

type EventMeta

type EventMeta struct {
	DurationMs       int64  `json:"duration_ms,omitempty"`
	TotalDurationMs  int64  `json:"total_duration_ms,omitempty"`
	ToolName         string `json:"tool_name,omitempty"`
	ToolID           string `json:"tool_id,omitempty"`
	Status           string `json:"status,omitempty"`
	ErrorMsg         string `json:"error_msg,omitempty"`
	InputTokens      int32  `json:"input_tokens,omitempty"`
	OutputTokens     int32  `json:"output_tokens,omitempty"`
	CacheWriteTokens int32  `json:"cache_write_tokens,omitempty"`
	CacheReadTokens  int32  `json:"cache_read_tokens,omitempty"`
	InputSummary     string `json:"input_summary,omitempty"`
	OutputSummary    string `json:"output_summary,omitempty"`
	FilePath         string `json:"file_path,omitempty"`
	LineCount        int32  `json:"line_count,omitempty"`
	Progress         int32  `json:"progress,omitempty"`
	TotalSteps       int32  `json:"total_steps,omitempty"`
	CurrentStep      int32  `json:"current_step,omitempty"`
}

EventMeta contains detailed metadata for streaming events.

type EventWithMeta

type EventWithMeta struct {
	EventType string     `json:"event_type"`
	EventData string     `json:"event_data"`
	Meta      *EventMeta `json:"meta,omitempty"`
}

EventWithMeta extends the basic event with metadata for observability.

func NewEventWithMeta

func NewEventWithMeta(eventType, eventData string, meta *EventMeta) *EventWithMeta

NewEventWithMeta creates a new EventWithMeta with guaranteed non-nil Meta.

type OpenCodeConfig

type OpenCodeConfig struct {
	// UseHTTPAPI enables HTTP API mode instead of CLI mode
	UseHTTPAPI bool `json:"use_http_api,omitempty" koanf:"use_http_api"`

	// Port for HTTP API server
	Port int `json:"port,omitempty" koanf:"port"`

	// PlanMode enables planning mode
	PlanMode bool `json:"plan_mode,omitempty" koanf:"plan_mode"`

	// Provider is the LLM provider to use
	Provider string `json:"provider,omitempty" koanf:"provider"`

	// Model is the model ID
	Model string `json:"model,omitempty" koanf:"model"`
}

OpenCodeConfig contains OpenCode-specific configuration.

type OpenCodeMessage

type OpenCodeMessage struct {
	ID      string         `json:"id,omitempty"`
	Role    string         `json:"role,omitempty"`
	Parts   []OpenCodePart `json:"parts,omitempty"`
	Content string         `json:"content,omitempty"`
	Status  string         `json:"status,omitempty"`
	Error   string         `json:"error,omitempty"`
}

OpenCodeMessage represents the output message structure from OpenCode.

type OpenCodePart

type OpenCodePart struct {
	Type    string         `json:"type"`
	Text    string         `json:"text,omitempty"`
	Name    string         `json:"name,omitempty"`
	ID      string         `json:"id,omitempty"`
	Input   map[string]any `json:"input,omitempty"`
	Output  string         `json:"output,omitempty"`
	Content string         `json:"content,omitempty"`
	Status  string         `json:"status,omitempty"`
	Error   string         `json:"error,omitempty"`

	// Step tracking
	StepNumber int `json:"step_number,omitempty"`
	TotalSteps int `json:"total_steps,omitempty"`

	// Token usage (in metadata)
	Usage *OpenCodeUsage `json:"usage,omitempty"`
}

OpenCodePart represents a single part in an OpenCode message.

type OpenCodeProvider

type OpenCodeProvider struct {
	ProviderBase
	// contains filtered or unexported fields
}

OpenCodeProvider implements the Provider interface for OpenCode CLI. OpenCode has a different architecture from Claude Code: - Supports both CLI mode and HTTP API mode - Uses Part-based output format instead of stream-json - Has Plan/Build dual modes - Supports multiple LLM providers

func NewOpenCodeProvider

func NewOpenCodeProvider(cfg ProviderConfig, logger *slog.Logger) (*OpenCodeProvider, error)

NewOpenCodeProvider creates a new OpenCode provider instance.

func (*OpenCodeProvider) BuildCLIArgs

func (p *OpenCodeProvider) BuildCLIArgs(providerSessionID string, opts *ProviderSessionOptions) []string

BuildCLIArgs constructs OpenCode CLI arguments.

func (*OpenCodeProvider) BuildEnvVars

func (p *OpenCodeProvider) BuildEnvVars(opts *ProviderSessionOptions) []string

BuildEnvVars constructs environment variables for OpenCode.

func (*OpenCodeProvider) BuildHTTPCommand

func (p *OpenCodeProvider) BuildHTTPCommand(prompt string, taskInstructions string) string

BuildHTTPCommand constructs the prompt as a command string for CLI mode. Unlike Claude Code, OpenCode takes the prompt as a CLI argument.

func (*OpenCodeProvider) BuildInputMessage

func (p *OpenCodeProvider) BuildInputMessage(prompt string, taskInstructions string) (map[string]any, error)

BuildInputMessage constructs the input for OpenCode. Note: OpenCode typically takes the prompt as a CLI argument, not stdin. For multi-turn sessions, this method may be used differently.

func (*OpenCodeProvider) DetectTurnEnd

func (p *OpenCodeProvider) DetectTurnEnd(event *ProviderEvent) bool

DetectTurnEnd checks if the event signals turn completion.

func (*OpenCodeProvider) ExtractSessionID

func (p *OpenCodeProvider) ExtractSessionID(event *ProviderEvent) string

ExtractSessionID extracts session ID from OpenCode events.

func (*OpenCodeProvider) GetHTTPAPIPort

func (p *OpenCodeProvider) GetHTTPAPIPort() int

GetHTTPAPIPort returns the configured HTTP API port.

func (*OpenCodeProvider) ParseEvent

func (p *OpenCodeProvider) ParseEvent(line string) (*ProviderEvent, error)

ParseEvent parses an OpenCode JSON output line into a ProviderEvent.

func (*OpenCodeProvider) SupportsHTTPAPI

func (p *OpenCodeProvider) SupportsHTTPAPI() bool

SupportsHTTPAPI returns true if HTTP API mode should be used.

func (*OpenCodeProvider) ValidateBinary

func (p *OpenCodeProvider) ValidateBinary() (string, error)

ValidateBinary checks if the OpenCode CLI is available.

type OpenCodeUsage

type OpenCodeUsage struct {
	InputTokens  int32 `json:"input_tokens,omitempty"`
	OutputTokens int32 `json:"output_tokens,omitempty"`
}

OpenCodeUsage represents token usage information.

type Provider

type Provider interface {
	// Metadata returns the provider's identity and capabilities.
	Metadata() ProviderMeta

	// BuildCLIArgs constructs the command-line arguments for starting the CLI process.
	// The sessionID is the internal SDK identifier, providerSessionID is the
	// provider-specific persistent session identifier (e.g., Claude's --session-id).
	BuildCLIArgs(providerSessionID string, opts *ProviderSessionOptions) []string

	// BuildEnvVars constructs environment variables for the CLI process.
	// Returns additional environment variables to be merged with os.Environ().
	BuildEnvVars(opts *ProviderSessionOptions) []string

	// BuildInputMessage constructs the stdin message payload for sending user input.
	// This handles provider-specific input formatting (e.g., stream-json for Claude).
	BuildInputMessage(prompt string, taskInstructions string) (map[string]any, error)

	// ParseEvent parses a raw output line into a normalized ProviderEvent.
	// Returns nil if the line should be ignored (e.g., system messages).
	// Returns an error if parsing fails critically.
	ParseEvent(line string) (*ProviderEvent, error)

	// DetectTurnEnd checks if the event indicates the end of a turn.
	// Different providers signal turn completion differently:
	// - Claude Code: type="result"
	// - OpenCode: step-finish or specific completion marker
	DetectTurnEnd(event *ProviderEvent) bool

	// ExtractSessionID extracts the provider-specific session ID from CLI output.
	// This is used during session startup to capture persistent session identifiers.
	ExtractSessionID(event *ProviderEvent) string

	// ValidateBinary checks if the CLI binary is available and returns its path.
	ValidateBinary() (string, error)

	// GetVersion returns the CLI version string.
	GetVersion() (string, error)

	// Name returns the provider name for logging and identification.
	Name() string
}

Provider defines the interface for AI CLI agent providers. Each provider (Claude Code, OpenCode) implements this interface to handle its specific CLI protocol, argument construction, and event parsing.

The interface follows the Strategy Pattern, allowing HotPlex Engine to switch between different AI CLI tools without modifying core logic.

func CreateDefaultProvider

func CreateDefaultProvider(t ProviderType) (Provider, error)

CreateDefaultProvider is a convenience function for creating providers with defaults.

func CreateProvider

func CreateProvider(cfg ProviderConfig) (Provider, error)

CreateProvider is a convenience function that uses the global factory.

type ProviderBase

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

ProviderBase provides common functionality for provider implementations. Embed this struct to reduce boilerplate in concrete providers.

func (*ProviderBase) GetVersion

func (p *ProviderBase) GetVersion() (string, error)

GetVersion returns the CLI version by executing --version.

func (*ProviderBase) Metadata

func (p *ProviderBase) Metadata() ProviderMeta

Metadata returns the provider metadata.

func (*ProviderBase) Name

func (p *ProviderBase) Name() string

Name returns the provider name.

func (*ProviderBase) ValidateBinary

func (p *ProviderBase) ValidateBinary() (string, error)

ValidateBinary checks if the CLI binary exists and returns its path.

type ProviderConfig

type ProviderConfig struct {
	// Type identifies the provider (required)
	Type ProviderType `json:"type" koanf:"type"`

	// Enabled controls whether this provider is available
	Enabled bool `json:"enabled" koanf:"enabled"`

	// ExplicitDisable explicitly disables the provider, overriding base config's Enabled=true.
	// This is needed because bool zero value (false) cannot be distinguished from "not set"
	// in config merging. Use this when you want to disable a provider in overlay config.
	ExplicitDisable bool `json:"explicit_disable,omitempty" koanf:"explicit_disable"`

	// BinaryPath overrides the default binary lookup path
	BinaryPath string `json:"binary_path,omitempty" koanf:"binary_path"`

	// DefaultModel is the default model to use
	DefaultModel string `json:"default_model,omitempty" koanf:"default_model"`

	// DefaultPermissionMode is the default permission mode
	DefaultPermissionMode string `json:"default_permission_mode,omitempty" koanf:"default_permission_mode"`

	// AllowedTools restricts available tools (provider-level override)
	AllowedTools []string `json:"allowed_tools,omitempty" koanf:"allowed_tools"`

	// DisallowedTools blocks specific tools (provider-level override)
	DisallowedTools []string `json:"disallowed_tools,omitempty" koanf:"disallowed_tools"`

	// ExtraArgs are additional CLI arguments
	ExtraArgs []string `json:"extra_args,omitempty" koanf:"extra_args"`

	// ExtraEnv are additional environment variables
	ExtraEnv map[string]string `json:"extra_env,omitempty" koanf:"extra_env"`

	// Timeout overrides the default execution timeout
	Timeout time.Duration `json:"timeout,omitempty" koanf:"timeout"`

	// OpenCode-specific options
	OpenCode *OpenCodeConfig `json:"opencode,omitempty" koanf:"opencode"`
}

ProviderConfig defines the configuration for a specific provider instance. This is used in the layered configuration system.

func MergeProviderConfigs

func MergeProviderConfigs(base, overlay ProviderConfig) ProviderConfig

MergeProviderConfigs merges multiple provider configurations with precedence. Later configurations override earlier ones for non-zero values.

Note: For boolean fields like Enabled, false cannot override true because false is the zero value. Use ExplicitDisable field in ProviderConfig if you need to explicitly disable a provider in an overlay config.

func (*ProviderConfig) Validate

func (c *ProviderConfig) Validate() error

Validate validates the provider configuration. Returns an error if required fields are missing or invalid.

type ProviderContentBlock

type ProviderContentBlock struct {
	Type      string         `json:"type"`
	Text      string         `json:"text,omitempty"`
	Name      string         `json:"name,omitempty"`
	ID        string         `json:"id,omitempty"`
	ToolUseID string         `json:"tool_use_id,omitempty"`
	Input     map[string]any `json:"input,omitempty"`
	Content   string         `json:"content,omitempty"`
	IsError   bool           `json:"is_error,omitempty"`
}

ProviderContentBlock represents a structured content block within an event.

type ProviderCreator

type ProviderCreator func(cfg ProviderConfig, logger *slog.Logger) (Provider, error)

ProviderCreator is a function that creates a new Provider instance.

type ProviderEvent

type ProviderEvent struct {
	// Type is the normalized event type
	Type ProviderEventType `json:"type"`

	// RawType is the original type string from the provider (for debugging)
	RawType string `json:"raw_type,omitempty"`

	// Timestamp of the event
	Timestamp time.Time `json:"timestamp,omitempty"`

	// SessionID is the provider-specific session identifier
	SessionID string `json:"session_id,omitempty"`

	// Content contains the main event payload
	Content string `json:"content,omitempty"`

	// Blocks contains structured content blocks (if applicable)
	Blocks []ProviderContentBlock `json:"blocks,omitempty"`

	// Tool information (for tool_use and tool_result events)
	ToolName  string         `json:"tool_name,omitempty"`
	ToolID    string         `json:"tool_id,omitempty"`
	ToolInput map[string]any `json:"tool_input,omitempty"`

	// Status indicates operation status ("running", "success", "error")
	Status string `json:"status,omitempty"`

	// Error contains error message if applicable
	Error   string `json:"error,omitempty"`
	IsError bool   `json:"is_error,omitempty"`

	// Metadata contains additional provider-specific information
	Metadata *ProviderEventMeta `json:"metadata,omitempty"`

	// RawLine preserves the original JSON line for debugging
	RawLine string `json:"-"`
}

ProviderEvent represents a normalized event from any AI CLI provider. This unified model allows the HotPlex Engine to handle events consistently regardless of the underlying provider.

func ParseProviderEvent

func ParseProviderEvent(line string) (*ProviderEvent, error)

ParseProviderEvent parses a JSON line into a ProviderEvent. This is a generic parser; providers should implement custom parsing for their specific event formats.

func (*ProviderEvent) GetFirstTextBlock

func (e *ProviderEvent) GetFirstTextBlock() string

GetFirstTextBlock extracts the first text block content from the event.

func (*ProviderEvent) HasToolInfo

func (e *ProviderEvent) HasToolInfo() bool

HasToolInfo returns true if this event contains tool information.

func (*ProviderEvent) IsTerminalEvent

func (e *ProviderEvent) IsTerminalEvent() bool

IsTerminalEvent returns true if this event indicates the turn is complete.

func (*ProviderEvent) ToEventWithMeta

func (e *ProviderEvent) ToEventWithMeta() *EventWithMeta

ToEventWithMeta converts ProviderEvent to the existing EventWithMeta type. This provides backward compatibility with the existing event system.

func (*ProviderEvent) ToJSON

func (e *ProviderEvent) ToJSON() (string, error)

ToJSON returns the JSON representation of the event.

type ProviderEventMeta

type ProviderEventMeta struct {
	// Timing information
	DurationMs      int64 `json:"duration_ms,omitempty"`
	TotalDurationMs int64 `json:"total_duration_ms,omitempty"`

	// Token usage
	InputTokens      int32 `json:"input_tokens,omitempty"`
	OutputTokens     int32 `json:"output_tokens,omitempty"`
	CacheWriteTokens int32 `json:"cache_write_tokens,omitempty"`
	CacheReadTokens  int32 `json:"cache_read_tokens,omitempty"`

	// Cost information
	TotalCostUSD float64 `json:"total_cost_usd,omitempty"`

	// Model information
	Model string `json:"model,omitempty"`

	// Progress tracking
	Progress    int32 `json:"progress,omitempty"`
	TotalSteps  int32 `json:"total_steps,omitempty"`
	CurrentStep int32 `json:"current_step,omitempty"`
}

ProviderEventMeta contains additional metadata for observability.

type ProviderEventParser

type ProviderEventParser interface {
	// Parse converts a raw output line to a normalized ProviderEvent.
	Parse(line string) (*ProviderEvent, error)

	// IsTurnEnd returns true if the event signals turn completion.
	IsTurnEnd(event *ProviderEvent) bool

	// ExtractSessionID extracts the provider session ID from an event.
	ExtractSessionID(event *ProviderEvent) string
}

ProviderEventParser defines the interface for parsing provider-specific events. Each provider implements this to convert their raw output to normalized events.

type ProviderEventType

type ProviderEventType string

ProviderEventType defines the normalized event types across all providers. These types abstract away provider-specific event names to provide a unified event model for the HotPlex Engine and downstream consumers.

const (
	// EventTypeThinking indicates the AI is reasoning or thinking.
	// Claude Code: type="thinking" or type="status"
	// OpenCode: Part.Type="reasoning"
	EventTypeThinking ProviderEventType = "thinking"

	// EventTypeAnswer indicates text output from the AI.
	// Claude Code: type="assistant" with text blocks
	// OpenCode: Part.Type="text"
	EventTypeAnswer ProviderEventType = "answer"

	// EventTypeToolUse indicates a tool invocation is starting.
	// Claude Code: type="tool_use"
	// OpenCode: Part.Type="tool"
	EventTypeToolUse ProviderEventType = "tool_use"

	// EventTypeToolResult indicates a tool execution result.
	// Claude Code: type="tool_result"
	// OpenCode: Part.Type="tool" with result content
	EventTypeToolResult ProviderEventType = "tool_result"

	// EventTypeError indicates an error occurred.
	EventTypeError ProviderEventType = "error"

	// EventTypeResult indicates the turn has completed with final result.
	// Claude Code: type="result"
	// OpenCode: step-finish or completion marker
	EventTypeResult ProviderEventType = "result"

	// EventTypeSystem indicates a system-level message (often filtered).
	EventTypeSystem ProviderEventType = "system"

	// EventTypeUser indicates a user message reflection (often filtered).
	EventTypeUser ProviderEventType = "user"

	// EventTypeStepStart indicates a new step/milestone (OpenCode specific).
	EventTypeStepStart ProviderEventType = "step_start"

	// EventTypeStepFinish indicates a step/milestone completed (OpenCode specific).
	EventTypeStepFinish ProviderEventType = "step_finish"

	// EventTypeRaw indicates unparsed raw output (fallback).
	EventTypeRaw ProviderEventType = "raw"
)

type ProviderFactory

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

ProviderFactory creates Provider instances based on configuration. It implements the Factory Pattern to decouple provider creation from usage.

var GlobalProviderFactory *ProviderFactory

GlobalProviderFactory is the default factory instance. It comes pre-registered with built-in providers.

func NewProviderFactory

func NewProviderFactory(logger *slog.Logger) *ProviderFactory

NewProviderFactory creates a new provider factory with default providers registered.

func (*ProviderFactory) Create

func (f *ProviderFactory) Create(cfg ProviderConfig) (Provider, error)

Create creates a new Provider instance based on the configuration.

func (*ProviderFactory) CreateDefault

func (f *ProviderFactory) CreateDefault(t ProviderType) (Provider, error)

CreateDefault creates a Provider with default configuration.

func (*ProviderFactory) IsRegistered

func (f *ProviderFactory) IsRegistered(t ProviderType) bool

IsRegistered checks if a provider type is registered.

func (*ProviderFactory) ListRegistered

func (f *ProviderFactory) ListRegistered() []ProviderType

ListRegistered returns a list of registered provider types.

func (*ProviderFactory) Register

func (f *ProviderFactory) Register(t ProviderType, creator ProviderCreator)

Register adds a new provider creator to the factory. If a creator for the given type already exists, it will be replaced.

type ProviderFeatures

type ProviderFeatures struct {
	SupportsResume             bool // Can resume existing sessions (e.g., --resume)
	SupportsStreamJSON         bool // Supports stream-json input/output format
	SupportsSSE                bool // Supports Server-Sent Events output
	SupportsHTTPAPI            bool // Has HTTP API mode
	SupportsSessionID          bool // Supports explicit session ID assignment
	SupportsPermissions        bool // Supports permission modes
	MultiTurnReady             bool // Can handle multiple turns in one session
	RequiresInitialPromptAsArg bool // Requires first prompt to be passed via CLI args instead of stdin
}

ProviderFeatures describes the capabilities of a provider.

type ProviderMeta

type ProviderMeta struct {
	Type        ProviderType // Provider type identifier
	DisplayName string       // Human-readable name (e.g., "Claude Code")
	BinaryName  string       // CLI binary name (e.g., "claude", "opencode")
	Version     string       // CLI version (if available)
	Features    ProviderFeatures
}

ProviderMeta contains metadata about a provider.

type ProviderRegistry

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

ProviderRegistry maintains a cache of initialized providers. This is useful for reusing provider instances across sessions.

func NewProviderRegistry

func NewProviderRegistry(factory *ProviderFactory, logger *slog.Logger) *ProviderRegistry

NewProviderRegistry creates a new provider registry.

func (*ProviderRegistry) Clear

func (r *ProviderRegistry) Clear()

Clear removes all providers from the cache.

func (*ProviderRegistry) Get

Get retrieves a cached provider or creates a new one.

func (*ProviderRegistry) GetOrCreate

func (r *ProviderRegistry) GetOrCreate(t ProviderType) (Provider, error)

GetOrCreate retrieves a cached provider or creates one with default config.

func (*ProviderRegistry) List

func (r *ProviderRegistry) List() []ProviderType

List returns all cached provider types.

func (*ProviderRegistry) Remove

func (r *ProviderRegistry) Remove(t ProviderType)

Remove removes a provider from the cache.

type ProviderSessionOptions

type ProviderSessionOptions struct {
	// Working directory for the CLI process
	WorkDir string

	// Permission mode (e.g., "bypass-permissions", "auto-accept")
	PermissionMode string

	// Tool restrictions
	AllowedTools    []string
	DisallowedTools []string

	// System prompts
	BaseSystemPrompt string // Engine-level foundational prompt
	TaskInstructions string // Per-task instructions (persisted per session)
	InitialPrompt    string // First prompt for cold start (sent as CLI arg if needed)

	// Session management
	SessionID         string // Internal SDK session ID
	ProviderSessionID string // Provider-specific persistent session ID
	ResumeSession     bool   // Whether to resume an existing session

	// Provider-specific flags
	// Claude Code specific
	Model string // Model override (e.g., "claude-3-5-sonnet")

	// OpenCode specific
	PlanMode bool // Use planning mode instead of build mode
	Port     int  // Port for HTTP API mode (if applicable)
}

ProviderSessionOptions configures a provider session. This is the provider-specific subset of session configuration, extracted from the global EngineOptions and per-request Config.

type ProviderType

type ProviderType string

ProviderType defines the type of AI CLI provider.

const (
	ProviderTypeClaudeCode ProviderType = "claude-code"
	ProviderTypeOpenCode   ProviderType = "opencode"
)

func (ProviderType) Valid

func (t ProviderType) Valid() bool

Valid checks if the provider type is a known valid type.

type StreamMessage

type StreamMessage struct {
	Message      *AssistantMessage `json:"message,omitempty"`
	Input        map[string]any    `json:"input,omitempty"`
	Type         string            `json:"type"`
	Timestamp    string            `json:"timestamp,omitempty"`
	SessionID    string            `json:"session_id,omitempty"`
	Role         string            `json:"role,omitempty"`
	Name         string            `json:"name,omitempty"`
	Output       string            `json:"output,omitempty"`
	Status       string            `json:"status,omitempty"`
	Error        string            `json:"error,omitempty"`
	Content      []ContentBlock    `json:"content,omitempty"`
	Duration     int               `json:"duration_ms,omitempty"`
	Subtype      string            `json:"subtype,omitempty"`
	IsError      bool              `json:"is_error,omitempty"`
	TotalCostUSD float64           `json:"total_cost_usd,omitempty"`
	Usage        *UsageStats       `json:"usage,omitempty"`
	Result       string            `json:"result,omitempty"`
}

StreamMessage represents a single event in the stream-json format emitted by CLI tools. This is a minimal copy for the provider package to avoid circular dependencies.

func (*StreamMessage) GetContentBlocks

func (m *StreamMessage) GetContentBlocks() []ContentBlock

GetContentBlocks returns the primary content blocks of the message.

type UsageStats

type UsageStats struct {
	InputTokens           int32 `json:"input_tokens"`
	OutputTokens          int32 `json:"output_tokens"`
	CacheWriteInputTokens int32 `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens  int32 `json:"cache_read_input_tokens,omitempty"`
}

UsageStats represents the token consumption breakdown.

Jump to

Keyboard shortcuts

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