daemon

package
v0.0.0-...-d3c6f9c Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Overview

Package daemon provides background task management.

Package daemon provides HTTP handlers for file management.

Index

Constants

View Source
const (
	OpPing         = "ping"
	OpStatus       = "status"
	OpActorStart   = "actor.start"
	OpActorStop    = "actor.stop"
	OpActorList    = "actor.list"
	OpActorWrite   = "actor.write"
	OpLedgerAppend = "ledger.append"
	OpLedgerRead   = "ledger.read"
	OpLedgerTail   = "ledger.tail"
	OpShutdown     = "shutdown"
)

Common operation names

Variables

This section is empty.

Functions

func DefaultLedgerPath

func DefaultLedgerPath() string

DefaultLedgerPath returns the default ledger path.

func DefaultSocketPath

func DefaultSocketPath() string

DefaultSocketPath returns the default socket path.

func InitLogger

func InitLogger(logDir string, level LogLevel) error

InitLogger initializes the global logger

func IsRunning

func IsRunning(socketPath string) bool

IsRunning checks if the daemon is running.

func LogDebug

func LogDebug(component string, message string, fields ...map[string]interface{})

func LogError

func LogError(component string, message string, fields ...map[string]interface{})

func LogInfo

func LogInfo(component string, message string, fields ...map[string]interface{})

func LogWarn

func LogWarn(component string, message string, fields ...map[string]interface{})

func SanitizeString

func SanitizeString(s string) string

SanitizeString removes potentially dangerous characters

func ValidateID

func ValidateID(id string) error

ValidateID validates an identifier

func ValidateTitle

func ValidateTitle(title string, maxLen int) error

ValidateTitle validates a title string

func ValidateTopic

func ValidateTopic(topic string) error

ValidateTopic validates a topic string

Types

type ActorAddArgs

type ActorAddArgs struct {
	GroupID  string            `json:"group_id"`
	ID       string            `json:"id"`
	Role     actor.Role        `json:"role"`
	CostTier actor.CostTier    `json:"cost_tier,omitempty"`
	Title    string            `json:"title,omitempty"`
	Command  []string          `json:"command"`
	Env      map[string]string `json:"env,omitempty"`
	Model    string            `json:"model,omitempty"`
	Provider string            `json:"provider,omitempty"`
	Runner   actor.RunnerKind  `json:"runner,omitempty"`
}

ActorAddArgs contains arguments for actor.add.

type ActorIDArgs

type ActorIDArgs struct {
	ID string `json:"id"`
}

ActorIDArgs contains an actor ID argument.

type ActorListArgs

type ActorListArgs struct {
	GroupID string `json:"group_id,omitempty"`
}

ActorListArgs contains arguments for actor.list.

type ActorRegistry

type ActorRegistry interface {
	Add(a *actor.Actor) error
	Get(id string) (*actor.Actor, bool)
	Update(id string, fn func(*actor.Actor)) error
	Remove(id string) error
	List() []*actor.Actor
	ListByGroup(groupID string) []*actor.Actor
	ListByRole(role actor.Role) []*actor.Actor
	ListByState(state actor.ActorState) []*actor.Actor
	Count() int
	CountByGroup(groupID string) int
	CountRunning() int
	SetState(id string, state actor.ActorState) error
	SetSession(id string, sessionID string) error
	SetGroup(id string, groupID string) error
}

ActorRegistry defines actor registry operations

type ActorStartArgs

type ActorStartArgs struct {
	ID      string            `json:"id"`
	Command string            `json:"command"`
	Args    []string          `json:"args,omitempty"`
	Cwd     string            `json:"cwd,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
}

ActorStartArgs contains arguments for starting an actor.

type ActorStopArgs

type ActorStopArgs struct {
	ID string `json:"id"`
}

ActorStopArgs contains arguments for stopping an actor.

type ActorUpdateArgs

type ActorUpdateArgs struct {
	ID       string            `json:"id"`
	Title    string            `json:"title,omitempty"`
	Enabled  *bool             `json:"enabled,omitempty"`
	Env      map[string]string `json:"env,omitempty"`
	Autonomy string            `json:"autonomy,omitempty"` // high/medium/low for orchestrator
}

ActorUpdateArgs contains arguments for actor.update.

type ActorWriteArgs

type ActorWriteArgs struct {
	ID   string `json:"id"`
	Data string `json:"data"`
}

ActorWriteArgs contains arguments for writing to an actor.

type AdaptiveBatchConfig

type AdaptiveBatchConfig struct {
	MinBatchSize      int
	MaxBatchSize      int
	MinInterval       time.Duration
	MaxInterval       time.Duration
	HighLoadThreshold int // Events per second
}

AdaptiveBatchConfig adjusts batch configuration based on load.

func DefaultAdaptiveConfig

func DefaultAdaptiveConfig() AdaptiveBatchConfig

DefaultAdaptiveConfig returns default adaptive configuration.

type AdaptiveBatcher

type AdaptiveBatcher struct {
	*sync.RWMutex
	// contains filtered or unexported fields
}

AdaptiveBatcher adjusts batch size based on event rate.

func NewAdaptiveBatcher

func NewAdaptiveBatcher(config AdaptiveBatchConfig) *AdaptiveBatcher

NewAdaptiveBatcher creates a new adaptive batcher.

func (*AdaptiveBatcher) Adjust

func (ab *AdaptiveBatcher) Adjust()

Adjust adjusts batch configuration based on current load.

func (*AdaptiveBatcher) Config

func (ab *AdaptiveBatcher) Config() BatchConfig

Config returns current batch configuration.

func (*AdaptiveBatcher) RecordEvent

func (ab *AdaptiveBatcher) RecordEvent()

RecordEvent records an event for load calculation.

type AuthOverride

type AuthOverride struct {
	APIKey  string `json:"api_key,omitempty"`
	BaseURL string `json:"base_url,omitempty"`
	Enabled bool   `json:"enabled"`
}

AuthOverride represents a project-level auth override for a provider.

type BackgroundManager

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

BackgroundManager manages background tasks for the daemon.

func NewBackgroundManager

func NewBackgroundManager(
	tokenManager *auth.TokenManager,
	providers func() map[string]extension.DeviceCodeAuth,
) *BackgroundManager

NewBackgroundManager creates a new background manager.

func (*BackgroundManager) Start

func (bm *BackgroundManager) Start()

Start starts all background tasks.

func (*BackgroundManager) Stop

func (bm *BackgroundManager) Stop()

Stop stops all background tasks.

func (*BackgroundManager) TriggerTokenRefresh

func (bm *BackgroundManager) TriggerTokenRefresh()

TriggerTokenRefresh manually triggers token refresh check.

type BatchConfig

type BatchConfig struct {
	MaxBatchSize  int           // Maximum events per batch
	FlushInterval time.Duration // Maximum time to wait before flushing
	Enabled       bool          // Whether batching is enabled
}

BatchConfig configures event batching behavior.

func DefaultBatchConfig

func DefaultBatchConfig() BatchConfig

DefaultBatchConfig returns default batch configuration.

type BatchStats

type BatchStats struct {
	TotalBatches   int64
	TotalEvents    int64
	AvgBatchSize   float64
	FlushesBySize  int64
	FlushesByTime  int64
	DroppedBatches int64
}

BatchStats holds batching statistics.

type BatchedBroadcaster

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

BatchedBroadcaster wraps EventBroadcaster with batching support.

func NewBatchedBroadcaster

func NewBatchedBroadcaster(config BatchConfig) *BatchedBroadcaster

NewBatchedBroadcaster creates a new batched broadcaster.

func (*BatchedBroadcaster) FlushAll

func (bb *BatchedBroadcaster) FlushAll()

FlushAll flushes all pending batches.

func (*BatchedBroadcaster) OnAppend

func (bb *BatchedBroadcaster) OnAppend(event map[string]any)

OnAppend handles a new event with batching.

func (*BatchedBroadcaster) Stats

func (bb *BatchedBroadcaster) Stats() BatchStats

Stats returns batching statistics.

func (*BatchedBroadcaster) Subscribe

Subscribe creates a new batched subscription.

func (*BatchedBroadcaster) Unsubscribe

func (bb *BatchedBroadcaster) Unsubscribe(bs *BatchedSubscription)

Unsubscribe removes a batched subscription.

type BatchedSubscription

type BatchedSubscription struct {
	*Subscription
	// contains filtered or unexported fields
}

BatchedSubscription extends Subscription with batching support.

func NewBatchedSubscription

func NewBatchedSubscription(sub *Subscription, config BatchConfig) *BatchedSubscription

NewBatchedSubscription creates a new batched subscription.

func (*BatchedSubscription) Add

func (bs *BatchedSubscription) Add(event map[string]any) bool

Add adds an event to the batch.

type Client

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

Client is a client for communicating with the daemon.

func NewClient

func NewClient(socketPath string) *Client

NewClient creates a new daemon client.

func (*Client) ActorList

func (c *Client) ActorList() ([]map[string]any, error)

ActorList lists all actors.

func (*Client) ActorStart

func (c *Client) ActorStart(args ActorStartArgs) error

ActorStart starts an actor.

func (*Client) ActorStop

func (c *Client) ActorStop(id string) error

ActorStop stops an actor.

func (*Client) ActorWrite

func (c *Client) ActorWrite(id, data string) error

ActorWrite writes to an actor.

func (*Client) Call

func (c *Client) Call(op string, args any) (Response, error)

Call sends a request and returns the response.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Connect

func (c *Client) Connect() error

Connect connects to the daemon using auto-detected transport.

func (*Client) Ping

func (c *Client) Ping() error

Ping sends a ping request.

func (*Client) Shutdown

func (c *Client) Shutdown() error

Shutdown requests daemon shutdown.

func (*Client) Status

func (c *Client) Status() (map[string]any, error)

Status gets the daemon status.

type Config

type Config struct {
	SocketPath     string
	LedgerPath     string
	WorkspaceRoot  string
	WorkDir        string
	ArtifactsDir   string
	CacheDir       string
	TmpDir         string
	MetaDir        string
	NetworkMode    string
	NetworkAllow   []string
	NetworkDeny    []string
	NetworkLog     string
	GroupStatePath string   // Path for group persistence (default: <meta>/groups.json)
	HTTPAddr       string   // HTTP server address (default: localhost:8080)
	AuthToken      string   // Bearer token for HTTP API authentication
	CORSOrigins    []string // Allowed origins, empty = same-origin only
	CORSMode       string   // "strict", "development", or empty

	// Connection pool settings
	MaxConnections int           // Maximum concurrent connections (0 = unlimited)
	ReadTimeout    time.Duration // HTTP read timeout
	WriteTimeout   time.Duration // HTTP write timeout
	IdleTimeout    time.Duration // HTTP idle timeout
	MaxHeaderBytes int           // Maximum header bytes (default: 1MB)

	// Rate limiting settings
	RateLimitRequests int           // Maximum requests per window (0 = unlimited)
	RateLimitWindow   time.Duration // Rate limit window duration

	// Transport configuration (for daemon RPC, not HTTP API)
	TransportMode string // "auto", "unix", "tcp", "pipe" (default: "auto")
	TCPPort       int    // TCP port for daemon RPC when TransportMode is "tcp" (default: 9876)
}

Config holds configuration for the daemon server.

type ConnectionLimiter

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

ConnectionLimiter limits concurrent connections

func NewConnectionLimiter

func NewConnectionLimiter(maxConns int) *ConnectionLimiter

NewConnectionLimiter creates a new connection limiter

func (*ConnectionLimiter) Acquire

func (cl *ConnectionLimiter) Acquire() bool

Acquire attempts to acquire a connection slot

func (*ConnectionLimiter) Current

func (cl *ConnectionLimiter) Current() int64

Current returns the current number of connections

func (*ConnectionLimiter) MaxConnections

func (cl *ConnectionLimiter) MaxConnections() int

MaxConnections returns the maximum number of connections

func (*ConnectionLimiter) Release

func (cl *ConnectionLimiter) Release()

Release releases a connection slot

type DecisionCreateArgs

type DecisionCreateArgs struct {
	GroupID     string              `json:"group_id"`
	Title       string              `json:"title"`
	Description string              `json:"description,omitempty"`
	Context     string              `json:"context,omitempty"`
	Options     []decision.Option   `json:"options"`
	Importance  decision.Importance `json:"importance,omitempty"`
	CreatedBy   string              `json:"created_by"`
}

DecisionCreateArgs contains arguments for decision.create.

type DecisionDecideArgs

type DecisionDecideArgs struct {
	CardID    string `json:"card_id"`
	OptionID  string `json:"option_id"`
	Reason    string `json:"reason,omitempty"`
	DecidedBy string `json:"decided_by"`
}

DecisionDecideArgs contains arguments for decision.decide.

type DecisionGetArgs

type DecisionGetArgs struct {
	CardID string `json:"card_id"`
}

DecisionGetArgs contains arguments for decision.get.

type DecisionListArgs

type DecisionListArgs struct {
	GroupID string              `json:"group_id,omitempty"`
	Status  decision.CardStatus `json:"status,omitempty"`
}

DecisionListArgs contains arguments for decision.list.

type DecisionVoteArgs

type DecisionVoteArgs struct {
	CardID    string `json:"card_id"`
	ActorID   string `json:"actor_id"`
	ActorRole string `json:"actor_role"`
	OptionID  string `json:"option_id"`
	Reason    string `json:"reason,omitempty"`
}

DecisionVoteArgs contains arguments for decision.vote.

type EventBroadcaster

type EventBroadcaster interface {
	Subscribe(opts SubscribeOptions) *Subscription
	Unsubscribe(sub *Subscription)
	UnsubscribeByID(id string)
	OnAppend(event map[string]any)
	Count() int
	CountByGroup(groupID string) int
	CloseAll()
}

EventBroadcaster defines event broadcasting

func NewEventBroadcaster

func NewEventBroadcaster() EventBroadcaster

NewEventBroadcaster creates a new event broadcaster.

type EventsStreamArgs

type EventsStreamArgs struct {
	GroupID string   `json:"group_id,omitempty"` // Filter by group
	ActorID string   `json:"actor_id,omitempty"` // Filter by actor
	Kinds   []string `json:"kinds,omitempty"`    // Filter by kinds
}

EventsStreamArgs contains arguments for events.stream.

type FileContentResponse

type FileContentResponse struct {
	Path     string `json:"path"`
	Content  string `json:"content"`
	Size     int64  `json:"size"`
	Modified string `json:"modified"`
	MimeType string `json:"mime_type"`
	Encoding string `json:"encoding"`
	IsBinary bool   `json:"is_binary"`
}

FileContentResponse represents file content response.

type FileEntry

type FileEntry struct {
	Name          string    `json:"name"`
	Type          string    `json:"type"` // "file" or "directory"
	Size          int64     `json:"size"`
	Modified      time.Time `json:"modified"`
	MimeType      string    `json:"mime_type,omitempty"`
	ChildrenCount int       `json:"children_count,omitempty"`
}

FileEntry represents a file or directory entry.

type GroupCreateArgs

type GroupCreateArgs struct {
	ID          string                 `json:"id,omitempty"`
	Title       string                 `json:"title"`
	Topic       string                 `json:"topic,omitempty"`
	Scopes      []group.Scope          `json:"scopes,omitempty"`
	ActiveScope string                 `json:"active_scope,omitempty"`
	Automation  group.AutomationConfig `json:"automation,omitempty"`
	Delivery    group.DeliveryConfig   `json:"delivery,omitempty"`
}

GroupCreateArgs contains arguments for group.create.

type GroupIDArgs

type GroupIDArgs struct {
	ID string `json:"id"`
}

GroupIDArgs contains a group ID argument.

type GroupManager

type GroupManager interface {
	Create(cfg group.Config) (*group.Group, error)
	Get(id string) (*group.Group, bool)
	List() []*group.Group
	Delete(id string) error
	Start(id string) error
	Stop(id string) error
	Pause(id string) error
	Resume(id string) error
	ListByState(state group.State) []*group.Group
	Count() int
	CountByState(state group.State) int
	AddActorToGroup(groupID, actorID string) error
	RemoveActorFromGroup(groupID, actorID string) error
	GetActorsInGroup(groupID string) ([]string, error)
	SetState(id string, state group.State) error
	ImportDiscoveredGroups(wsCfg workspace.Config) ([]*group.Group, []error)
	SetOnStart(fn func(g *group.Group))
	SetOnStop(fn func(g *group.Group))
	SetOnResume(fn func(g *group.Group))
}

GroupManager defines group operations

type GroupSetStateArgs

type GroupSetStateArgs struct {
	ID    string      `json:"id"`
	State group.State `json:"state"`
}

GroupSetStateArgs contains arguments for group.set_state.

type HTTPServer

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

HTTPServer provides HTTP API for the WebUI.

func NewHTTPServer

func NewHTTPServer(addr string, daemon *Server, authToken string, corsOrigins []string, corsMode string, maxConns int, readTimeout, writeTimeout, idleTimeout time.Duration, maxHeaderBytes int, rateLimitRequests int, rateLimitWindow time.Duration) *HTTPServer

NewHTTPServer creates a new HTTP server.

func (*HTTPServer) Addr

func (h *HTTPServer) Addr() string

Addr returns the server address.

func (*HTTPServer) Start

func (h *HTTPServer) Start() error

Start starts the HTTP server.

func (*HTTPServer) Stop

func (h *HTTPServer) Stop(ctx context.Context) error

Stop stops the HTTP server.

type Handler

type Handler func(ctx context.Context, req Request) Response

Handler is a function that handles a request and returns a response.

type InboxListArgs

type InboxListArgs struct {
	ActorID    string `json:"actor_id"`
	UnreadOnly bool   `json:"unread_only,omitempty"`
}

InboxListArgs contains arguments for inbox.list.

type InboxMarkReadArgs

type InboxMarkReadArgs struct {
	ActorID   string `json:"actor_id"`
	MessageID string `json:"message_id,omitempty"` // Empty = mark all
}

InboxMarkReadArgs contains arguments for inbox.mark_read.

type Ledger

type Ledger interface {
	Append(event ledger.Event) error
	ReadAll() ([]ledger.Event, error)
	ReadFrom(offset int) ([]ledger.Event, error)
	Tail(n int) ([]ledger.Event, error)
	FilterByKind(kind string) ([]ledger.Event, error)
	FilterByActor(actorID string) ([]ledger.Event, error)
	LastN(n int) ([]ledger.Event, error)
	Count() (int, error)
}

Ledger defines ledger operations

type LedgerAppendArgs

type LedgerAppendArgs struct {
	Kind    string         `json:"kind"`
	ActorID string         `json:"actor_id,omitempty"`
	Data    map[string]any `json:"data,omitempty"`
}

LedgerAppendArgs contains arguments for appending to the ledger.

type LedgerReadArgs

type LedgerReadArgs struct {
	Offset int    `json:"offset,omitempty"`
	Limit  int    `json:"limit,omitempty"`
	Kind   string `json:"kind,omitempty"`
}

LedgerReadArgs contains arguments for reading from the ledger.

type LedgerTailArgs

type LedgerTailArgs struct {
	N int `json:"n"`
}

LedgerTailArgs contains arguments for tailing the ledger.

type LogEntry

type LogEntry struct {
	Timestamp string                 `json:"timestamp"`
	Level     LogLevel               `json:"level"`
	Message   string                 `json:"message"`
	Component string                 `json:"component,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
}

LogEntry represents a structured log entry

type LogLevel

type LogLevel string

LogLevel represents the severity of a log message

const (
	LogLevelDebug LogLevel = "DEBUG"
	LogLevelInfo  LogLevel = "INFO"
	LogLevelWarn  LogLevel = "WARN"
	LogLevelError LogLevel = "ERROR"
	LogLevelFatal LogLevel = "FATAL"
)

type Logger

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

Logger provides structured logging

func GetLogger

func GetLogger() *Logger

GetLogger returns the global logger

func NewFileLogger

func NewFileLogger(logDir string, level LogLevel) (*Logger, error)

NewFileLogger creates a logger that writes to a file

func NewLogger

func NewLogger(writer io.Writer, level LogLevel) *Logger

NewLogger creates a new structured logger

func (*Logger) Debug

func (l *Logger) Debug(component string, message string, fields ...map[string]interface{})

Debug logs a debug message

func (*Logger) Error

func (l *Logger) Error(component string, message string, fields ...map[string]interface{})

Error logs an error message

func (*Logger) Fatal

func (l *Logger) Fatal(component string, message string, fields ...map[string]interface{})

Fatal logs a fatal message and exits

func (*Logger) Info

func (l *Logger) Info(component string, message string, fields ...map[string]interface{})

Info logs an info message

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel changes the log level

func (*Logger) Warn

func (l *Logger) Warn(component string, message string, fields ...map[string]interface{})

Warn logs a warning message

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *Logger

WithField returns a new logger with the given field

type MessageReplyArgs

type MessageReplyArgs struct {
	GroupID   string         `json:"group_id"`
	From      string         `json:"from"`
	ReplyToID string         `json:"reply_to_id"`
	Content   string         `json:"content"`
	Data      map[string]any `json:"data,omitempty"`
}

MessageReplyArgs contains arguments for message.reply.

type MessageSendArgs

type MessageSendArgs struct {
	GroupID string         `json:"group_id"`
	From    string         `json:"from"`
	To      string         `json:"to,omitempty"` // Empty = broadcast
	Kind    string         `json:"kind"`
	Content string         `json:"content"`
	Data    map[string]any `json:"data,omitempty"`
}

MessageSendArgs contains arguments for message.send.

type MetricsCollector

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

MetricsCollector collects and exposes Prometheus-compatible metrics

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a new metrics collector

func (*MetricsCollector) GetMetrics

func (m *MetricsCollector) GetMetrics() map[string]interface{}

GetMetrics returns current metrics as a map

func (*MetricsCollector) PrometheusHandler

func (m *MetricsCollector) PrometheusHandler(w http.ResponseWriter, r *http.Request)

PrometheusHandler returns metrics in Prometheus format

func (*MetricsCollector) RecordActorCrash

func (m *MetricsCollector) RecordActorCrash()

RecordActorCrash records an actor crash

func (*MetricsCollector) RecordActorStart

func (m *MetricsCollector) RecordActorStart()

RecordActorStart records an actor start

func (*MetricsCollector) RecordActorStop

func (m *MetricsCollector) RecordActorStop()

RecordActorStop records an actor stop

func (*MetricsCollector) RecordConnectionAccepted

func (m *MetricsCollector) RecordConnectionAccepted()

RecordConnectionAccepted records an accepted connection

func (*MetricsCollector) RecordConnectionClosed

func (m *MetricsCollector) RecordConnectionClosed()

RecordConnectionClosed records a closed connection

func (*MetricsCollector) RecordConnectionRejected

func (m *MetricsCollector) RecordConnectionRejected()

RecordConnectionRejected records a rejected connection

func (*MetricsCollector) RecordDecisionCreated

func (m *MetricsCollector) RecordDecisionCreated()

RecordDecisionCreated records a created decision

func (*MetricsCollector) RecordDecisionResolved

func (m *MetricsCollector) RecordDecisionResolved()

RecordDecisionResolved records a resolved decision

func (*MetricsCollector) RecordMessageReceived

func (m *MetricsCollector) RecordMessageReceived()

RecordMessageReceived records a received message

func (*MetricsCollector) RecordMessageSent

func (m *MetricsCollector) RecordMessageSent(latencyMs float64)

RecordMessageSent records a sent message

func (*MetricsCollector) SetActiveConnections

func (m *MetricsCollector) SetActiveConnections(n int64)

SetActiveConnections sets the current active connections

func (*MetricsCollector) SetGroupsActive

func (m *MetricsCollector) SetGroupsActive(n int)

SetGroupsActive sets the number of active groups

func (*MetricsCollector) SetMaxConnections

func (m *MetricsCollector) SetMaxConnections(n int)

SetMaxConnections sets the maximum connections limit

func (*MetricsCollector) SetMessagesInQueue

func (m *MetricsCollector) SetMessagesInQueue(n int)

SetMessagesInQueue sets the number of messages in queue

type RateLimiter

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

RateLimiter implements token bucket algorithm

func NewRateLimiter

func NewRateLimiter(limit int, window time.Duration) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(ip string) bool

Allow checks if the request from the given IP is allowed

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the rate limiter's cleanup goroutine

type Request

type Request struct {
	Op   string          `json:"op"`
	Args json.RawMessage `json:"args,omitempty"`
}

Request represents a request to the daemon.

func (*Request) ParseArgs

func (r *Request) ParseArgs(target any) error

ParseArgs unmarshals request arguments into the target struct.

type Response

type Response struct {
	OK    bool            `json:"ok"`
	Data  json.RawMessage `json:"data,omitempty"`
	Error string          `json:"error,omitempty"`
}

Response represents a response from the daemon.

func NewErrorResponse

func NewErrorResponse(err string) Response

NewErrorResponse creates an error response.

func NewOKResponse

func NewOKResponse(data any) Response

NewOKResponse creates a successful response with data.

type RoleDefaultsRequest

type RoleDefaultsRequest struct {
	Command          string            `json:"command"`
	Args             []string          `json:"args"`
	WorkingDir       string            `json:"working_dir"`
	Env              map[string]string `json:"env"`
	AutoStart        bool              `json:"auto_start"`
	RestartOnFailure bool              `json:"restart_on_failure"`
	ModelOverride    string            `json:"model_override,omitempty"`
	MaxConcurrent    int               `json:"max_concurrent,omitempty"`
	TimeoutMinutes   int               `json:"timeout_minutes,omitempty"`
}

RoleDefaultsRequest represents the request body for updating role defaults

type RoleDefaultsResponse

type RoleDefaultsResponse struct {
	Role             string            `json:"role"`
	Command          string            `json:"command"`
	Args             []string          `json:"args"`
	WorkingDir       string            `json:"working_dir"`
	Env              map[string]string `json:"env"`
	AutoStart        bool              `json:"auto_start"`
	RestartOnFailure bool              `json:"restart_on_failure"`
	ModelOverride    string            `json:"model_override,omitempty"`
	MaxConcurrent    int               `json:"max_concurrent,omitempty"`
	TimeoutMinutes   int               `json:"timeout_minutes,omitempty"`
}

RoleDefaultsResponse represents a role defaults response

type ScheduledTask

type ScheduledTask struct {
	ID       string
	Name     string
	Interval time.Duration
	LastRun  time.Time
	NextRun  time.Time
	Handler  func() error
	Enabled  bool
}

ScheduledTask represents a scheduled task.

type Scheduler

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

Scheduler handles scheduled tasks.

func NewScheduler

func NewScheduler(checkInterval time.Duration) *Scheduler

NewScheduler creates a new scheduler.

func (*Scheduler) AddTask

func (s *Scheduler) AddTask(task *ScheduledTask)

AddTask adds a scheduled task.

func (*Scheduler) RemoveTask

func (s *Scheduler) RemoveTask(id string)

RemoveTask removes a scheduled task.

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop stops the scheduler.

type Server

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

Server is the daemon server that handles IPC requests.

func New

func New(cfg Config) (*Server, error)

New creates a new daemon server (backward compatible).

func NewServer

func NewServer(cfg Config, opts ...ServerOption) (*Server, error)

NewServer creates a new Server with dependency injection.

func (*Server) ApplyNetworkPolicy

func (s *Server) ApplyNetworkPolicy(groupID string, policy docker.NetworkPolicy) error

ApplyNetworkPolicy applies network policy for a group.

func (*Server) ApplyNetworkPolicyToContainer

func (s *Server) ApplyNetworkPolicyToContainer(containerID, groupID string) error

ApplyNetworkPolicyToContainer applies network policy to a specific container.

func (*Server) DeleteAuthOverride

func (s *Server) DeleteAuthOverride(provider string) error

DeleteAuthOverride removes an auth override for a provider.

func (*Server) Done

func (s *Server) Done() <-chan struct{}

Done returns a channel that's closed when the server is stopped.

func (*Server) GetAuthOverrides

func (s *Server) GetAuthOverrides() map[string]*AuthOverride

GetAuthOverrides returns the current project-level auth overrides.

func (*Server) GetNetworkStatus

func (s *Server) GetNetworkStatus() map[string]any

GetNetworkStatus returns network policy status.

func (*Server) GetRoleModelAssignments

func (s *Server) GetRoleModelAssignments() map[string]struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
}

GetRoleModelAssignments returns the current role-model assignments.

func (*Server) GetSettings

func (s *Server) GetSettings() map[string]any

GetSettings returns current daemon settings.

func (*Server) GetStatus

func (s *Server) GetStatus() map[string]any

GetStatus returns the current daemon status.

func (*Server) SetAuthOverride

func (s *Server) SetAuthOverride(provider string, override *AuthOverride) error

SetAuthOverride sets or updates an auth override for a provider.

func (*Server) SetRoleModelAssignments

func (s *Server) SetRoleModelAssignments(assignments map[string]struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
}) error

SetRoleModelAssignments updates the role-model assignments.

func (*Server) SocketPath

func (s *Server) SocketPath() string

SocketPath returns the socket path.

func (*Server) Start

func (s *Server) Start() error

Start starts the daemon server.

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the daemon server.

func (*Server) UpdateSettings

func (s *Server) UpdateSettings(settings map[string]any) error

UpdateSettings updates daemon settings.

type ServerOption

type ServerOption func(*Server)

ServerOption configures the Server

func WithActorRegistry

func WithActorRegistry(ar ActorRegistry) ServerOption

WithActorRegistry sets the actor registry

func WithBroadcaster

func WithBroadcaster(b EventBroadcaster) ServerOption

WithBroadcaster sets the event broadcaster

func WithGroupManager

func WithGroupManager(gm GroupManager) ServerOption

WithGroupManager sets the group manager

func WithLedger

func WithLedger(l Ledger) ServerOption

WithLedger sets the ledger

type StreamHandler

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

StreamHandler handles streaming connections.

func NewStreamHandler

func NewStreamHandler(broadcaster EventBroadcaster) *StreamHandler

NewStreamHandler creates a new stream handler.

func (*StreamHandler) HandleEventsStream

func (h *StreamHandler) HandleEventsStream(ctx context.Context, conn net.Conn, args EventsStreamArgs) error

HandleEventsStream handles the events.stream operation. This upgrades the connection to streaming mode.

type StreamingConnection

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

StreamingConnection wraps a connection for bidirectional streaming.

func NewStreamingConnection

func NewStreamingConnection(conn net.Conn, sub *Subscription) *StreamingConnection

NewStreamingConnection creates a new streaming connection.

func (*StreamingConnection) Close

func (sc *StreamingConnection) Close()

Close closes the streaming connection.

func (*StreamingConnection) Done

func (sc *StreamingConnection) Done() <-chan struct{}

Done returns a channel that's closed when the connection is closed.

func (*StreamingConnection) ReadLoop

func (sc *StreamingConnection) ReadLoop(ctx context.Context) error

ReadLoop reads input from the client (for terminal attach).

func (*StreamingConnection) Send

func (sc *StreamingConnection) Send(event map[string]any) error

Send sends an event over the streaming connection.

func (*StreamingConnection) SendError

func (sc *StreamingConnection) SendError(err error) error

SendError sends an error over the streaming connection.

func (*StreamingConnection) SendOutput

func (sc *StreamingConnection) SendOutput(data []byte) error

SendOutput sends terminal output over the streaming connection.

func (*StreamingConnection) SetInputHandler

func (sc *StreamingConnection) SetInputHandler(handler func(data []byte))

SetInputHandler sets the callback for terminal input.

type SubscribeOptions

type SubscribeOptions struct {
	ID        string   // Subscription ID (auto-generated if empty)
	GroupID   string   // Only events from this group
	ActorID   string   // Only events from this actor
	Kinds     []string // Only these event kinds
	QueueSize int      // Queue buffer size (default 100)
}

SubscribeOptions configures a subscription.

type Subscription

type Subscription struct {
	ID      string
	GroupID string          // Filter by group (empty = all groups)
	By      string          // Filter by actor (empty = all actors)
	Kinds   map[string]bool // Filter by kind (empty = all kinds)
	Queue   chan map[string]any
	// contains filtered or unexported fields
}

Subscription represents an event subscription.

func (*Subscription) Done

func (s *Subscription) Done() <-chan struct{}

Done returns a channel that's closed when the subscription is cancelled.

type TermAttachArgs

type TermAttachArgs struct {
	ActorID string `json:"actor_id"`
}

TermAttachArgs contains arguments for term.attach.

type TerminalSession

type TerminalSession struct {
	ID       string
	GroupID  string
	FilePath string
	Editor   string // "vim" or "nano"

	// Channels for I/O
	InputCh  chan []byte
	OutputCh chan []byte
	DoneCh   chan struct{}
	// contains filtered or unexported fields
}

TerminalSession represents a WebSocket-based terminal session with PTY

func (*TerminalSession) Close

func (s *TerminalSession) Close()

Close terminates the session

func (*TerminalSession) IsRunning

func (s *TerminalSession) IsRunning() bool

IsRunning returns true if the session is still active

func (*TerminalSession) ReadOutput

func (s *TerminalSession) ReadOutput() ([]byte, bool)

ReadOutput reads data from terminal output (non-blocking)

func (*TerminalSession) SetSize

func (s *TerminalSession) SetSize(cols, rows uint16) error

SetSize updates the terminal size

func (*TerminalSession) WriteInput

func (s *TerminalSession) WriteInput(data []byte) error

WriteInput writes data to the terminal input

type TerminalSessionManager

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

TerminalSessionManager manages active terminal sessions

func NewTerminalSessionManager

func NewTerminalSessionManager(workspaceRoot string) *TerminalSessionManager

NewTerminalSessionManager creates a new session manager

func (*TerminalSessionManager) CreateSession

func (m *TerminalSessionManager) CreateSession(groupID, filePath, editor string) (*TerminalSession, error)

CreateSession creates a new terminal session for editing a file

func (*TerminalSessionManager) GetSession

func (m *TerminalSessionManager) GetSession(id string) (*TerminalSession, bool)

GetSession retrieves a session by ID

func (*TerminalSessionManager) ListSessions

func (m *TerminalSessionManager) ListSessions() []string

ListSessions returns all active session IDs

type TerminalWSMessage

type TerminalWSMessage struct {
	Type string `json:"type"`
	Data string `json:"data"`
	Cols int    `json:"cols,omitempty"`
	Rows int    `json:"rows,omitempty"`
}

TerminalWSMessage represents a WebSocket message for terminal communication

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

ValidationError represents a validation error

func (ValidationError) Error

func (e ValidationError) Error() string

type WhiteboardApproveArgs

type WhiteboardApproveArgs struct {
	GroupID    string `json:"group_id"`
	ProposalID string `json:"proposal_id"`
	ApprovedBy string `json:"approved_by"`
	Role       string `json:"role"`
}

WhiteboardApproveArgs contains arguments for whiteboard.approve.

type WhiteboardGetArgs

type WhiteboardGetArgs struct {
	GroupID string `json:"group_id"`
	Section string `json:"section,omitempty"`
}

WhiteboardGetArgs contains arguments for whiteboard.get.

type WhiteboardMergeArgs

type WhiteboardMergeArgs struct {
	GroupID    string `json:"group_id"`
	ProposalID string `json:"proposal_id"`
	MergedBy   string `json:"merged_by"`
	Role       string `json:"role"`
}

WhiteboardMergeArgs contains arguments for whiteboard.merge.

type WhiteboardProposeArgs

type WhiteboardProposeArgs struct {
	GroupID     string `json:"group_id"`
	By          string `json:"by"`
	Section     string `json:"section"`
	Content     string `json:"content"`
	Description string `json:"description,omitempty"`
}

WhiteboardProposeArgs contains arguments for whiteboard.propose.

Jump to

Keyboard shortcuts

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