hub

package
v0.1.16 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 45 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrCodeNetwork          = "network"
	ErrCodeAuthentication   = "authentication"
	ErrCodeAuthorization    = "authorization"
	ErrCodeAgentUnavailable = "agent_unavailable"
	ErrCodeUnsupported      = "unsupported_version"
	ErrCodeSessionConflict  = "session_conflict"
	ErrCodeHostPolicy       = "host_policy"
	ErrCodeAgentProtocol    = "agent_protocol"
	ErrCodeProcessCrash     = "process_crash"
	ErrCodeTimeout          = "timeout"
	ErrCodeDatabase         = "database"
	ErrCodeUpdate           = "update"
	ErrCodeInternal         = "internal"
)

Run error codes are stable, machine-readable categories. They describe what the hub observed and intentionally do not attempt to replace the agent's own message.

Variables

View Source
var ErrSetupComplete = errors.New("hub is already set up")

ErrSetupComplete is returned when a first-run setup request loses the race against another one. It maps to HTTP 409.

View Source
var Version = "alpha"

Version is overridden at build time for release images and binaries.

Functions

func ClassifyRunError

func ClassifyRunError(message string) string

ClassifyRunError maps an observed error message to one stable code. The classification is deliberately keyword-based and only runs against text the host or agent already produced.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword returns an Argon2id PHC string.

func NewTOTPSecret

func NewTOTPSecret() string

NewTOTPSecret returns a base32-encoded 160-bit secret.

func TOTPURL

func TOTPURL(issuer, account, secret string) string

TOTPURL returns an otpauth:// URI for authenticator apps.

func ValidatePairingCode

func ValidatePairingCode(code string) bool

ValidatePairingCode checks the XXXX-XXXX format used by the CLI.

func ValidateTOTP

func ValidateTOTP(secret, code string) bool

ValidateTOTP accepts the current time step and one step of drift.

func VerifyPassword

func VerifyPassword(encoded, password string) bool

func VerifyPasswordBounded

func VerifyPasswordBounded(encoded, password string) bool

VerifyPasswordBounded verifies a password while holding one of the bounded Argon2 slots. It returns false when the slot cannot be acquired in time, so a flood cannot grow the queue indefinitely.

Types

type APIToken

type APIToken struct {
	ID        string     `json:"id"`
	Name      string     `json:"name"`
	Scopes    []string   `json:"scopes"`
	CreatedAt time.Time  `json:"created_at"`
	LastUsed  *time.Time `json:"last_used,omitempty"`
}

type ActivityDay

type ActivityDay struct {
	Date     string   `json:"date"`
	Sessions int      `json:"sessions"`
	Runs     int      `json:"runs"`
	Agents   []string `json:"agents"`
	Hosts    []string `json:"hosts"`
}

type ActivityView

type ActivityView struct {
	Days     []ActivityDay `json:"days"`
	Sessions int           `json:"sessions"`
	Runs     int           `json:"runs"`
	From     time.Time     `json:"from"`
	To       time.Time     `json:"to"`
}

type AuditEvent

type AuditEvent struct {
	Seq      int64     `json:"seq"`
	At       time.Time `json:"at"`
	Actor    string    `json:"actor"`
	Action   string    `json:"action"`
	Details  string    `json:"details"`
	PrevHash string    `json:"prev_hash"`
	Hash     string    `json:"hash"`
}

type Config

type Config struct {
	Addr      string
	DataDir   string
	PublicURL string
	TLSCert   string
	TLSKey    string
	HubName   string
	// MetricsEnabled exposes /metrics. MetricsToken is the required bearer
	// token; an empty token disables the endpoint even when enabled is true.
	MetricsEnabled bool
	MetricsToken   string
	// Concurrency limits for new runs. Zero disables the corresponding check.
	MaxRunsPerHost    int
	MaxRunsPerUser    int
	MaxRunsPerProject int
	// RequireSignedCommands rejects prompt/approval/stop writes unless the
	// browser or native client signs them with a registered device key.
	RequireSignedCommands bool
}

Config is the hub runtime configuration.

type Device

type Device struct {
	ID        string     `json:"id"`
	Name      string     `json:"name"`
	CreatedAt time.Time  `json:"created_at"`
	LastSeen  time.Time  `json:"last_seen"`
	RevokedAt *time.Time `json:"revoked_at,omitempty"`
}

type DiagnosticsCounts

type DiagnosticsCounts struct {
	Hosts         int `json:"hosts"`
	Sessions      int `json:"sessions"`
	ActiveRuns    int `json:"active_runs"`
	Tasks         int `json:"tasks"`
	Users         int `json:"users"`
	QueuedPrompts int `json:"queued_prompts"`
}

DiagnosticsCounts is a small, content-free summary for the admin diagnostics page and export. It never includes session ids, host names or prompts.

type FanoutRunView

type FanoutRunView struct {
	RunID     string `json:"run_id"`
	SessionID string `json:"session_id,omitempty"`
	HostID    string `json:"host_id"`
	HostName  string `json:"host_name"`
	Agent     string `json:"agent"`
	Cwd       string `json:"cwd"`
	Title     string `json:"title,omitempty"`
	State     string `json:"state"`
	Error     string `json:"error,omitempty"`
}

type FanoutView

type FanoutView struct {
	ID        string          `json:"id"`
	Prompt    string          `json:"prompt"`
	CreatedAt time.Time       `json:"created_at"`
	Runs      []FanoutRunView `json:"runs"`
}

type Host

type Host struct {
	protocol.HostView
	OwnerID    string
	PublicKey  []byte
	RevokedAt  *time.Time
	DisabledAt *time.Time
	Policy     *protocol.PolicySummary
	CreatedAt  time.Time
}

type HostGrant

type HostGrant struct {
	UserID      string `json:"user_id"`
	Username    string `json:"username"`
	Permissions string `json:"permissions"`
}

type HubSigner

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

HubSigner is the hub's command-signing identity. It is independent of the host identity keys and is pinned by hosts during pairing or first connection.

func OpenHubSigner

func OpenHubSigner(dataDir string) (*HubSigner, error)

OpenHubSigner loads or creates the hub signing key next to the database. Losing this file invalidates signed commands until hosts re-pin the key; a damaged file fails startup instead of silently rotating.

func (*HubSigner) PublicKey

func (s *HubSigner) PublicKey() string

func (*HubSigner) Sign

func (s *HubSigner) Sign(envelope *protocol.Envelope) error

type NotificationChannel

type NotificationChannel struct {
	ID        string            `json:"id"`
	Kind      string            `json:"kind"`
	Name      string            `json:"name"`
	Enabled   bool              `json:"enabled"`
	Target    string            `json:"target,omitempty"`
	Config    map[string]string `json:"-"`
	UpdatedAt time.Time         `json:"updated_at"`
}

type PromptTemplate

type PromptTemplate struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Body      string    `json:"body"`
	Shared    bool      `json:"shared"`
	Owner     bool      `json:"owner"`
	UpdatedAt time.Time `json:"updated_at"`
}

type PushSubscription

type PushSubscription struct {
	ID       string `json:"id"`
	UserID   string `json:"-"`
	DeviceID string `json:"-"`
	Endpoint string `json:"endpoint"`
	P256DH   string `json:"p256dh"`
	Auth     string `json:"auth"`
}

type SecretBox

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

SecretBox encrypts small hub secrets at rest (TOTP secrets, the VAPID private key). The key lives next to the SQLite database with 0600 permissions. A database copy without the key file cannot recover them.

func OpenSecretBox

func OpenSecretBox(dataDir string) (*SecretBox, error)

OpenSecretBox loads or creates the hub key file. An existing key must be exactly 32 bytes; a damaged key is a hard error rather than silently replacing it and losing every stored secret.

func (*SecretBox) Open

func (b *SecretBox) Open(value string) (string, error)

func (*SecretBox) Seal

func (b *SecretBox) Seal(value string) (string, error)

Seal encrypts a small secret. Encryption never falls back to plaintext: a random-source failure is returned to the caller so the write can be aborted.

type Server

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

Server is the AgentNexus hub: REST API, browser WebSocket gateway, host link gateway, relay and metadata index.

func NewServer

func NewServer(cfg Config, store *Store, logger *slog.Logger) *Server

func (*Server) Handler

func (s *Server) Handler() http.Handler

func (*Server) SetAssets

func (s *Server) SetAssets(h http.Handler)

func (*Server) SetSigner

func (s *Server) SetSigner(signer *HubSigner)

type SessionFilter

type SessionFilter struct {
	HostID  string
	Agent   string
	Project string
	RepoURL string
	State   string
	Query   string
	Tag     string
	Sort    string
	Order   string
	Since   time.Time
	Until   time.Time
	Limit   int
	Offset  int
}

SessionFilter narrows and orders a session listing. Sorting is a closed whitelist so no caller input reaches ORDER BY as SQL.

type SessionInfo

type SessionInfo struct {
	User        User
	Device      Device
	ExpiresAt   time.Time
	StepUpUntil time.Time
}

type SessionUsage

type SessionUsage struct {
	InputTokens      int64   `json:"input_tokens"`
	OutputTokens     int64   `json:"output_tokens"`
	CacheReadTokens  int64   `json:"cache_read_tokens"`
	CacheWriteTokens int64   `json:"cache_write_tokens"`
	CostUSD          float64 `json:"cost_usd"`
	Runs             int     `json:"runs"`
	RunsWithUsage    int     `json:"runs_with_usage"`
	UnavailableRuns  int     `json:"unavailable_runs"`
}

type Store

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

Store is the hub's metadata database. Transcript content is never written here; only session metadata, runs, devices, hosts and the audit log.

func OpenStore

func OpenStore(path string) (*Store, error)

func (*Store) APITokenUser

func (s *Store) APITokenUser(raw string) (User, string, bool)

APITokenUser validates a bearer token and returns the owner. The scope set is deliberately fixed to read-only for this version.

func (*Store) ActiveRunForSession

func (s *Store) ActiveRunForSession(sessionID string) (string, bool)

func (*Store) ActiveRuns

func (s *Store) ActiveRuns(hostID string) ([]protocol.RunView, error)

func (*Store) ActiveRunsForUser

func (s *Store) ActiveRunsForUser(userID string, all bool) ([]protocol.RunView, error)

ActiveRunsForUser lists live runs visible through host ownership or a view grant. It is intentionally bounded: the dashboard only needs recent runs.

func (*Store) AddFanoutRun

func (s *Store) AddFanoutRun(fanoutID, runID, hostID, agent, lastError string) error

func (*Store) AddNotification

func (s *Store) AddNotification(userID, kind, title, body, runID, link string) error

func (*Store) AddSessionTag

func (s *Store) AddSessionTag(userID, sessionID, tag string) error

func (*Store) AddTaskDependency

func (s *Store) AddTaskDependency(taskID, dependsOn string) error

AddTaskDependency rejects a dependency that would create a cycle. The recursive query follows existing dependency edges from the proposed parent.

func (*Store) AdoptRunState

func (s *Store) AdoptRunState(id, state string)

AdoptRunState records the state a host reports for a run it still owns. It clears a previous terminal state so an agent process that survived a hub restart or host reconnect is active again in the database, which keeps the per-session uniqueness check effective.

func (*Store) AppendAudit

func (s *Store) AppendAudit(actor, action string, details any) error

func (*Store) ApplyHostSessionDelta

func (s *Store) ApplyHostSessionDelta(hostID string, sessions []protocol.Session, removed []protocol.SessionKey) (upserted, deleted int, err error)

ApplyHostSessionDelta applies changed sessions and explicit removals. It never deletes rows that are absent from the payload; only a full snapshot may do that.

func (*Store) AttachTaskSession

func (s *Store) AttachTaskSession(runID, sessionID string)

AttachTaskSession updates the session id after a structured new/fork run reported its native session.

func (*Store) AuditForHost

func (s *Store) AuditForHost(hostID string, limit int) ([]AuditEvent, error)

AuditForHost returns recent audit entries whose details mention the host. Host ids are random hex, so a LIKE pattern cannot be widened by caller input.

func (*Store) Backup

func (s *Store) Backup(path string) error

Backup writes a consistent SQLite snapshot while the hub is running. The caller should copy secret.key alongside it; encrypted secrets are useless without that key.

func (*Store) ChildSessions

func (s *Store) ChildSessions(userID, hostID, agent, nativeID string, all bool) ([]protocol.SessionView, error)

ChildSessions lists sessions whose native parent is nativeID.

func (*Store) ClaimPromptQueueItem

func (s *Store) ClaimPromptQueueItem(id string) (protocol.PromptQueueItem, bool, error)

ClaimPromptQueueItem atomically moves one queued item to sending. Only the goroutine that wins this update may deliver it to the host.

func (*Store) Close

func (s *Store) Close() error

func (*Store) ConfirmHost

func (s *Store) ConfirmHost(ownerID, hostID string) error

func (*Store) ConsumeDevicePairing

func (s *Store) ConsumeDevicePairing(token string) (string, error)

func (*Store) ConsumePairingCode

func (s *Store) ConsumePairingCode(code string) (ownerID string, err error)

func (*Store) CountActiveRuns

func (s *Store) CountActiveRuns() (int, error)

CountActiveRuns is used by the metrics endpoint only; it never returns transcript or session metadata.

func (*Store) CountActiveRunsForHost

func (s *Store) CountActiveRunsForHost(hostID string) int

func (*Store) CountActiveRunsForProject

func (s *Store) CountActiveRunsForProject(hostID, cwd string) int

func (*Store) CountActiveRunsForUser

func (s *Store) CountActiveRunsForUser(userID string) int

func (*Store) CountQueuedPrompts

func (s *Store) CountQueuedPrompts(runID string) int

CountQueuedPrompts bounds one run's queue before a new item is accepted.

func (*Store) CountSessionsFiltered

func (s *Store) CountSessionsFiltered(userID string, f SessionFilter, all bool) (int, error)

CountSessionsFiltered returns the total number of rows matching a filter, independent of the page size. The virtualized browser list uses it to show an exact "x of y" count without loading every row.

func (*Store) CountTasks

func (s *Store) CountTasks(userID string, all bool) (int, error)

func (*Store) CreateAPIToken

func (s *Store) CreateAPIToken(userID, name string) (APIToken, string, error)

func (*Store) CreateDevicePairing

func (s *Store) CreateDevicePairing(userID, token string, ttl time.Duration) error

func (*Store) CreateFanout

func (s *Store) CreateFanout(userID, prompt string) (string, error)

func (*Store) CreateFirstUser

func (s *Store) CreateFirstUser(username, passwordHash, totpSecret string) (User, error)

CreateFirstUser creates the owner account only while the users table is empty. The conditional INSERT is evaluated by SQLite in one statement, so two concurrent first-run requests cannot both create an owner.

func (*Store) CreateHost

func (s *Store) CreateHost(ownerID, name string, publicKey []byte, osName, arch, version string) (string, error)

func (*Store) CreateHostConfirmation

func (s *Store) CreateHostConfirmation(hostID, sas string) error

func (*Store) CreateNotificationChannel

func (s *Store) CreateNotificationChannel(userID, kind, name string, config map[string]string) (NotificationChannel, error)

func (*Store) CreatePairingCode

func (s *Store) CreatePairingCode(ownerID, code string, ttl time.Duration) error

func (*Store) CreatePromptTemplate

func (s *Store) CreatePromptTemplate(userID, name, body string, shared bool) (PromptTemplate, error)

func (*Store) CreateRun

func (s *Store) CreateRun(id, sessionID, hostID, mode, userID, deviceID string) error

func (*Store) CreateRunAt

func (s *Store) CreateRunAt(id, sessionID, hostID, cwd, mode, userID, deviceID string) error

CreateRunAt records the working directory so per-project concurrency limits can be enforced without joining the session row. The insert is a single statement that refuses a second active row for the same native session, so two concurrent requests cannot both pass ActiveRunForSession and start two writer runs. A new session has no id yet and is exempt.

func (*Store) CreateSession

func (s *Store) CreateSession(userID, deviceName string) (token string, device Device, err error)

func (*Store) CreateTask

func (s *Store) CreateTask(t protocol.Task, dependsOn []string) (protocol.Task, error)

func (*Store) CreateUser

func (s *Store) CreateUser(username, passwordHash, totpSecret string) (User, error)

func (*Store) CreateUserWithRole

func (s *Store) CreateUserWithRole(username, passwordHash, totpSecret, role string) (User, error)

func (*Store) DeleteDevicePublicKey

func (s *Store) DeleteDevicePublicKey(userID, deviceID string) error

func (*Store) DeleteHostGrant

func (s *Store) DeleteHostGrant(hostID, userID string) error

func (*Store) DeleteNotificationChannel

func (s *Store) DeleteNotificationChannel(userID, id string) error

func (*Store) DeleteNotificationHostPrefs

func (s *Store) DeleteNotificationHostPrefs(userID, hostID string) error

func (*Store) DeletePromptQueueItem

func (s *Store) DeletePromptQueueItem(runID, itemID, deviceID string) error

DeletePromptQueueItem removes an item, but rechecks the run state and lease in the same statement: a host reconnect can clear ended_at between the handler's authorization check and this delete, and an active run must still require the controller lease.

func (*Store) DeletePromptTemplate

func (s *Store) DeletePromptTemplate(userID, id string) error

func (*Store) DeletePushSubscription

func (s *Store) DeletePushSubscription(userID, endpoint string) error

func (*Store) DeletePushSubscriptionByID

func (s *Store) DeletePushSubscriptionByID(id string)

func (*Store) DeleteSessionTag

func (s *Store) DeleteSessionTag(userID, sessionID, tag string) error

func (*Store) DeleteTask

func (s *Store) DeleteTask(id string) error

func (*Store) DevicePublicKey

func (s *Store) DevicePublicKey(deviceID string) (algorithm, publicKey string, err error)

DevicePublicKey returns the registered signing key for a device.

func (*Store) DiagnosticsCounts

func (s *Store) DiagnosticsCounts() (DiagnosticsCounts, error)

func (*Store) DuePromptQueue

func (s *Store) DuePromptQueue(now time.Time) ([]protocol.PromptQueueItem, error)

DuePromptQueue returns queued items whose schedule has arrived for runs that can accept them now. Filtering in SQL keeps the worker from loading large attachment payloads for every busy or paused run on every two-second pass.

func (*Store) EffectiveNotificationPrefs

func (s *Store) EffectiveNotificationPrefs(userID, hostID string) (map[string]bool, error)

EffectiveNotificationPrefs merges the global defaults, the user's global preferences and the per-host override in that order. An unset value stays enabled so notifications keep working for older accounts.

func (*Store) EnabledNotificationChannels

func (s *Store) EnabledNotificationChannels(userID string) ([]NotificationChannel, error)

EnabledNotificationChannels decrypts the channel configuration for delivery only. Callers must not log the returned config.

func (*Store) EnqueuePrompt

func (s *Store) EnqueuePrompt(runID, userID, deviceID, text string, options *protocol.PromptOptions, scheduledAt *time.Time, maxBytes int64) (protocol.PromptQueueItem, error)

EnqueuePrompt stores one prompt at the end of a run's queue. Options may contain bounded attachments; they are stored as JSON only on the hub. The byte budget is checked inside the insert transaction so concurrent requests cannot all pass a stale check.

func (*Store) EnsureForkedSession

func (s *Store) EnsureForkedSession(hostID, agent, nativeID, title, cwd, forkedFrom string) (string, error)

EnsureForkedSession creates the row for a native session that a structured fork just produced and returns its hub ID. An existing row (for example from the next discovery snapshot) is left untouched.

func (*Store) FailPendingPromptQueue

func (s *Store) FailPendingPromptQueue(runID, reason string)

FailPendingPromptQueue marks every queued or in-flight item of a finished run. In-flight items are never retried automatically.

func (*Store) Fanout

func (s *Store) Fanout(id, userID string, all bool) (FanoutView, error)

func (*Store) FavoriteHostIDs

func (s *Store) FavoriteHostIDs(userID string) (map[string]bool, error)

func (*Store) FavoriteSessionIDs

func (s *Store) FavoriteSessionIDs(userID string) (map[string]bool, error)

func (*Store) FavoriteSessions

func (s *Store) FavoriteSessions(userID string, all bool) ([]protocol.SessionView, error)

func (*Store) FinishPromptQueueItem

func (s *Store) FinishPromptQueueItem(id, state, lastError string)

func (*Store) ForkedSessions

func (s *Store) ForkedSessions(userID, hostID, agent, nativeID string, all bool) ([]protocol.SessionView, error)

ForkedSessions lists sessions whose native fork source is nativeID.

func (*Store) GetSetting

func (s *Store) GetSetting(key string) (string, error)

func (*Store) HasQueuedPrompts

func (s *Store) HasQueuedPrompts() (bool, error)

HasQueuedPrompts reports whether any queue item survived a restart.

func (*Store) HasQueuedPromptsForRun

func (s *Store) HasQueuedPromptsForRun(runID string) bool

HasQueuedPromptsForRun avoids waking the queue worker on every idle event.

func (*Store) HostAgents

func (s *Store) HostAgents(hostID string) ([]protocol.AgentInfo, error)

func (*Store) HostByID

func (s *Store) HostByID(hostID string) (Host, error)

func (*Store) HostConfirmation

func (s *Store) HostConfirmation(hostID string) (sas string, confirmed bool, exists bool, err error)

func (*Store) HostGrantPermissions

func (s *Store) HostGrantPermissions(hostID, userID string) (string, error)

func (*Store) HostPublicKey

func (s *Store) HostPublicKey(hostID string) ([]byte, error)

func (*Store) HostStats

func (s *Store) HostStats(hostID string) (sessions, projects, activeRuns int, err error)

HostStats returns metadata counts for the host detail view. It uses one query so the single SQLite connection is not held by a nested cursor.

func (*Store) LinkTaskRun

func (s *Store) LinkTaskRun(taskID, runID, sessionID string) error

LinkTaskRun attaches a delegated run and records the native session once it is known.

func (*Store) ListAPITokens

func (s *Store) ListAPITokens(userID string) ([]APIToken, error)

func (*Store) ListAudit

func (s *Store) ListAudit(limit int) ([]AuditEvent, error)

func (*Store) ListDevices

func (s *Store) ListDevices(userID string) ([]Device, error)

func (*Store) ListFanouts

func (s *Store) ListFanouts(userID string, all bool, limit int) ([]FanoutView, error)

func (*Store) ListHostGrants

func (s *Store) ListHostGrants(hostID string) ([]HostGrant, error)

func (*Store) ListHosts

func (s *Store) ListHosts(userID string, all bool) ([]protocol.HostView, error)

func (*Store) ListNotificationChannels

func (s *Store) ListNotificationChannels(userID string) ([]NotificationChannel, error)

func (*Store) ListNotificationHostPrefs

func (s *Store) ListNotificationHostPrefs(userID string) (map[string]map[string]bool, error)

ListNotificationHostPrefs returns every stored override for a user.

func (*Store) ListNotifications

func (s *Store) ListNotifications(userID string, limit int) ([]protocol.Notification, int, error)

func (*Store) ListProjects

func (s *Store) ListProjects(userID string, all bool, limit int) ([]protocol.ProjectView, error)

ListProjects groups session metadata by host and working directory. It never reads transcripts and is bounded by the same host permissions as sessions.

func (*Store) ListPromptQueue

func (s *Store) ListPromptQueue(runID string) ([]protocol.PromptQueueItem, error)

ListPromptQueue returns the pending and failed items for a run.

func (*Store) ListPromptTemplates

func (s *Store) ListPromptTemplates(userID string) ([]PromptTemplate, error)

func (*Store) ListSessions

func (s *Store) ListSessions(userID, hostID, agent, project, state, query string, limit, offset int, all bool) ([]protocol.SessionView, error)

func (*Store) ListSessionsFiltered

func (s *Store) ListSessionsFiltered(userID string, f SessionFilter, all bool) ([]protocol.SessionView, error)

func (*Store) ListTasks

func (s *Store) ListTasks(userID string, all bool, f TaskFilter) ([]protocol.Task, error)

func (*Store) ListUsers

func (s *Store) ListUsers() ([]User, error)

func (*Store) MarkNotificationsRead

func (s *Store) MarkNotificationsRead(userID, id string) (int, error)

MarkNotificationsRead marks one notification (id != "") or every unread notification for the user. It returns the remaining unread count.

func (*Store) MarkStepUp

func (s *Store) MarkStepUp(token string, window time.Duration) error

MarkStepUp extends the step-up window for one signed-in session.

func (*Store) MigrateSecrets

func (s *Store) MigrateSecrets() error

MigrateSecrets encrypts legacy plaintext values in place. It is idempotent and must run after SetSecretBox.

func (*Store) NotificationChannelByID

func (s *Store) NotificationChannelByID(userID, id string) (NotificationChannel, error)

func (*Store) NotificationExists

func (s *Store) NotificationExists(userID, runID, kind string) (bool, error)

func (*Store) NotificationHostPrefs

func (s *Store) NotificationHostPrefs(userID, hostID string) (map[string]bool, error)

NotificationHostPrefs returns the stored per-host override for one user. Missing entries are absent rather than defaulted: the caller merges them over the global preferences.

func (*Store) NotificationPrefs

func (s *Store) NotificationPrefs(userID string) (map[string]bool, error)

NotificationPrefs returns the push opt-outs for one user. Missing keys mean enabled; the in-app inbox is never filtered by these preferences.

func (*Store) PasskeyCount

func (s *Store) PasskeyCount(userID string) (int, error)

func (*Store) Passkeys

func (s *Store) Passkeys(userID string) ([]webauthn.Credential, error)

func (*Store) Ping

func (s *Store) Ping() error

Ping checks that the metadata database accepts a query.

func (*Store) PromptQueueBytes added in v0.1.16

func (s *Store) PromptQueueBytes(runID string) int64

PromptQueueBytes reports the stored text and option bytes retained for one run.

func (*Store) PromptQueueItem

func (s *Store) PromptQueueItem(id string) (protocol.PromptQueueItem, error)

func (*Store) PromptQueuePaused

func (s *Store) PromptQueuePaused(runID string) (bool, error)

func (*Store) PromptTemplate

func (s *Store) PromptTemplate(userID, id string) (PromptTemplate, error)

func (*Store) PropagateTaskReadiness

func (s *Store) PropagateTaskReadiness()

PropagateTaskReadiness moves tasks between blocked and ready when their dependencies change. Runtime-owned states (running, waiting, terminal) are never rewritten.

func (*Store) PurgeExpiredSessions

func (s *Store) PurgeExpiredSessions() int

PurgeExpiredSessions removes auth sessions past their expiry. It runs at hub start and never touches unexpired device sessions.

func (*Store) PushSubscriptions

func (s *Store) PushSubscriptions(userID string) ([]PushSubscription, error)

func (*Store) RebindRunSession

func (s *Store) RebindRunSession(runID, sessionID string) error

RebindRunSession points a run at the session a structured fork created.

func (*Store) ReconcileTasks

func (s *Store) ReconcileTasks() int

ReconcileTasks runs at hub start. A task whose run is gone can no longer be trusted to be running; leave tasks with a live run untouched so a reconnecting host can continue them.

func (*Store) RecoverPromptQueue

func (s *Store) RecoverPromptQueue()

RecoverPromptQueue runs at hub start. A crash can leave an item in sending; it is ambiguous whether the host received it, so it must not be resent.

func (*Store) RecoverStaleRuns

func (s *Store) RecoverStaleRuns() int

RecoverStaleRuns closes runs that a previous hub process left active. The host is authoritative about whether the agent process survived, so a reconnecting host re-adopts the run through AdoptRunState. Without this, a hub restart while a host is offline would block its sessions forever.

func (*Store) RemoveTaskDependency

func (s *Store) RemoveTaskDependency(taskID, dependsOn string) error

func (*Store) RenameHost

func (s *Store) RenameHost(hostID, name string) error

RenameHost changes only the hub-visible display name. The daemon keeps its own configured name until it reconnects with one.

func (*Store) ReorderPromptQueue

func (s *Store) ReorderPromptQueue(runID string, ids []string) error

ReorderPromptQueue applies a complete new order of the queued items.

func (*Store) ReplaceHostSessions

func (s *Store) ReplaceHostSessions(hostID string, sessions []protocol.Session) (upserted, deleted int, err error)

ReplaceHostSessions applies a full snapshot from one host. It returns the number of upserted and deleted records. A full snapshot is also the repair path after a reconnect because it removes rows the host no longer reports.

func (*Store) ResetTransientSessionStates

func (s *Store) ResetTransientSessionStates()

ResetTransientSessionStates clears live states left behind by a hub crash. No run survives a hub restart without a host reconnect, and the host's next discovery snapshot reports the real state again.

func (*Store) RevokeAPIToken

func (s *Store) RevokeAPIToken(userID, id string) error

func (*Store) RevokeDevice

func (s *Store) RevokeDevice(userID, deviceID string) error

func (*Store) RevokeHost

func (s *Store) RevokeHost(ownerID, hostID string) error

func (*Store) RevokeHostByID

func (s *Store) RevokeHostByID(hostID string) error

func (*Store) RevokeOtherDevices

func (s *Store) RevokeOtherDevices(userID, currentDeviceID string) ([]string, error)

RevokeOtherDevices signs out every device except the current one. The caller closes their WebSockets after the store change.

func (*Store) RevokeSession

func (s *Store) RevokeSession(token string) error

func (*Store) RunByID

func (s *Store) RunByID(id string) (protocol.RunView, string, error)

func (*Store) SavePasskey

func (s *Store) SavePasskey(userID, name string, cred *webauthn.Credential) error

func (*Store) SavePushSubscription

func (s *Store) SavePushSubscription(userID, deviceID, endpoint, p256dh, auth string) error

func (*Store) SessionByID

func (s *Store) SessionByID(userID, id string, all bool) (protocol.SessionView, error)

SessionByID returns one session and its per-user local metadata.

func (*Store) SessionByNativeID

func (s *Store) SessionByNativeID(userID, hostID, agent, nativeID string, all bool) (protocol.SessionView, error)

SessionByNativeID resolves a native relationship without exposing a second identity mapping. The host, agent and native id together are the key.

func (*Store) SessionByToken

func (s *Store) SessionByToken(token string) (SessionInfo, error)

func (*Store) SessionIDForNative

func (s *Store) SessionIDForNative(hostID, agent, nativeID string) (string, error)

SessionIDForNative maps a host-local native session to its hub ID.

func (*Store) SessionMetadata

func (s *Store) SessionMetadata(userID, sessionID string) (string, []string)

func (*Store) SessionTags

func (s *Store) SessionTags(userID string) ([]string, error)

SessionTags returns the tags in use by one user, for the filter control.

func (*Store) SessionUsage

func (s *Store) SessionUsage(sessionID string) (SessionUsage, error)

SessionUsage aggregates only measurements reported for runs of one session.

func (*Store) SetDevicePublicKey

func (s *Store) SetDevicePublicKey(userID, deviceID, algorithm, publicKey string) error

SetDevicePublicKey stores or replaces the command-signing key for one of the user's own devices. Keys are scoped to the device session, so revoking the device removes the key capability with it.

func (*Store) SetHostDisabled

func (s *Store) SetHostDisabled(hostID string, disabled bool) error

SetHostDisabled blocks new runs and host reconnects. Disabling is reversible; revocation is not and requires pairing again.

func (*Store) SetHostFavorite

func (s *Store) SetHostFavorite(userID, hostID string, favorite bool) error

func (*Store) SetHostGrant

func (s *Store) SetHostGrant(hostID, userID, permissions string) error

func (*Store) SetHostInventory

func (s *Store) SetHostInventory(hostID, version string, agents []protocol.AgentInfo, policy *protocol.PolicySummary) error

func (*Store) SetNotificationHostPrefs

func (s *Store) SetNotificationHostPrefs(userID, hostID string, prefs map[string]bool) error

func (*Store) SetNotificationPrefs

func (s *Store) SetNotificationPrefs(userID string, prefs map[string]bool) error

func (*Store) SetPromptQueuePaused

func (s *Store) SetPromptQueuePaused(runID string, paused bool) error

SetPromptQueuePaused toggles delivery for one run. Authorization is enforced by the caller: owners and admins may pause, so the store must not filter by the acting user.

func (*Store) SetRunError

func (s *Store) SetRunError(id, code, message string)

SetRunError stores a stable classification and a bounded message. Callers pass text that agents or the host reported; the hub does not synthesize errors for successful runs.

func (*Store) SetSecretBox

func (s *Store) SetSecretBox(box *SecretBox)

SetSecretBox enables encryption of sensitive values at rest. Existing plaintext values remain readable and are encrypted on their next write.

func (*Store) SetSessionFavorite

func (s *Store) SetSessionFavorite(userID, sessionID string, favorite bool) error

func (*Store) SetSessionLocalTitle

func (s *Store) SetSessionLocalTitle(userID, sessionID, title string) error

func (*Store) SetSessionState

func (s *Store) SetSessionState(id, state string)

SetSessionState updates the live state of a session.

func (*Store) SetSetting

func (s *Store) SetSetting(key, value string) error

func (*Store) SetTOTP

func (s *Store) SetTOTP(userID, secret string, enabled bool) error

func (*Store) SetTaskStatus

func (s *Store) SetTaskStatus(id, status, result, taskErr string) error

func (*Store) SetUserRole

func (s *Store) SetUserRole(id, role string) error

func (*Store) SetUserTheme

func (s *Store) SetUserTheme(userID, theme string) error

func (*Store) SyncReportedHostName added in v0.1.4

func (s *Store) SyncReportedHostName(hostID, name string) (bool, error)

SyncReportedHostName applies the hostname a daemon reports when it differs from the last reported value; the display name follows it. An administrator's rename changes only name, so reconnects do not revert it. Returns true when the display name changed.

func (*Store) SyncTaskRunState

func (s *Store) SyncTaskRunState(runID, runState string)

SyncTaskRunState mirrors run lifecycle changes onto the delegating task.

func (*Store) TaskByID

func (s *Store) TaskByID(id string) (protocol.Task, error)

func (*Store) TaskByRunID

func (s *Store) TaskByRunID(runID string) (protocol.Task, error)

TaskByRunID maps a live run back to the task that delegated it.

func (*Store) TaskDependencies

func (s *Store) TaskDependencies(taskID string) ([]protocol.TaskRef, error)

func (*Store) TaskDependents

func (s *Store) TaskDependents(taskID string) ([]protocol.TaskRef, error)

func (*Store) TaskOwnedBy

func (s *Store) TaskOwnedBy(taskID, userID string) (protocol.Task, error)

func (*Store) TouchSession

func (s *Store) TouchSession(token, deviceID string)

func (*Store) UpdateFanoutRunError

func (s *Store) UpdateFanoutRunError(fanoutID, runID, lastError string) error

func (*Store) UpdateHostSeen

func (s *Store) UpdateHostSeen(hostID string)

func (*Store) UpdateNotificationChannel

func (s *Store) UpdateNotificationChannel(userID, id, kind, name string, config map[string]string, enabled bool) (NotificationChannel, error)

func (*Store) UpdatePasskey

func (s *Store) UpdatePasskey(cred *webauthn.Credential) error

func (*Store) UpdatePromptQueueItem

func (s *Store) UpdatePromptQueueItem(runID, itemID, text string, scheduledAt *time.Time, maxBytes int64) error

func (*Store) UpdatePromptTemplate

func (s *Store) UpdatePromptTemplate(userID, id, name, body string, shared bool) (PromptTemplate, error)

func (*Store) UpdateRunState

func (s *Store) UpdateRunState(id, state string)

func (*Store) UpdateTask

func (s *Store) UpdateTask(id string, p TaskPatch) (protocol.Task, error)

func (*Store) UpsertRunUsage

func (s *Store) UpsertRunUsage(runID string, usage protocol.Usage) error

func (*Store) UsageReport

func (s *Store) UsageReport(userID string, all bool, since, until time.Time, hostID, agent string) (UsageReport, error)

UsageReport aggregates reported usage only. Runs without measurements are counted as unavailable rather than estimated.

func (*Store) UserByID

func (s *Store) UserByID(id string) (User, error)

func (*Store) UserByUsername

func (s *Store) UserByUsername(username string) (User, error)

func (*Store) UserCount

func (s *Store) UserCount() (int, error)

func (*Store) UserTheme

func (s *Store) UserTheme(userID string) (string, error)

func (*Store) VerifyAudit

func (s *Store) VerifyAudit() (int64, error)

VerifyAudit recomputes the hash chain. It returns the first broken sequence number, or 0 if the chain is intact.

type TaskFilter

type TaskFilter struct {
	Status  string
	HostID  string
	Agent   string
	Project string
	Query   string
	Limit   int
	Offset  int
}

TaskFilter narrows the task listing. Sorting is fixed to recent updates.

type TaskPatch

type TaskPatch struct {
	Title       *string   `json:"title"`
	Description *string   `json:"description"`
	Project     *string   `json:"project"`
	HostID      *string   `json:"host_id"`
	Agent       *string   `json:"agent"`
	Model       *string   `json:"model"`
	Mode        *string   `json:"mode"`
	Priority    *string   `json:"priority"`
	Status      *string   `json:"status"`
	Result      *string   `json:"result"`
	Error       *string   `json:"error"`
	Tags        *[]string `json:"tags"`
}

TaskPatch updates only fields that were explicitly supplied.

type UsageDay

type UsageDay struct {
	Date         string  `json:"date"`
	InputTokens  int64   `json:"input_tokens"`
	OutputTokens int64   `json:"output_tokens"`
	CostUSD      float64 `json:"cost_usd"`
	Runs         int     `json:"runs"`
}

type UsageGroup

type UsageGroup struct {
	Name             string  `json:"name"`
	InputTokens      int64   `json:"input_tokens"`
	OutputTokens     int64   `json:"output_tokens"`
	CacheReadTokens  int64   `json:"cache_read_tokens"`
	CacheWriteTokens int64   `json:"cache_write_tokens"`
	CostUSD          float64 `json:"cost_usd"`
	Runs             int     `json:"runs"`
	RunsWithUsage    int     `json:"runs_with_usage"`
}

type UsageReport

type UsageReport struct {
	Summary   UsageTotals  `json:"summary"`
	ByAgent   []UsageGroup `json:"by_agent"`
	ByHost    []UsageGroup `json:"by_host"`
	ByProject []UsageGroup `json:"by_project"`
	BySession []UsageGroup `json:"by_session"`
	Daily     []UsageDay   `json:"daily"`
	Runs      []UsageRun   `json:"runs"`
}

type UsageRun

type UsageRun struct {
	RunID        string    `json:"run_id"`
	SessionID    string    `json:"session_id"`
	SessionTitle string    `json:"session_title"`
	Agent        string    `json:"agent"`
	HostID       string    `json:"host_id"`
	HostName     string    `json:"host_name"`
	StartedAt    time.Time `json:"started_at"`
	InputTokens  int64     `json:"input_tokens"`
	OutputTokens int64     `json:"output_tokens"`
	CostUSD      *float64  `json:"cost_usd,omitempty"`
	Source       string    `json:"source"`
}

type UsageTotals

type UsageTotals struct {
	InputTokens      int64   `json:"input_tokens"`
	OutputTokens     int64   `json:"output_tokens"`
	CacheReadTokens  int64   `json:"cache_read_tokens"`
	CacheWriteTokens int64   `json:"cache_write_tokens"`
	CostUSD          float64 `json:"cost_usd"`
	CostRuns         int     `json:"cost_runs"`
	Runs             int     `json:"runs"`
	RunsWithUsage    int     `json:"runs_with_usage"`
	ReportedRuns     int     `json:"reported_runs"`
	EstimatedRuns    int     `json:"estimated_runs"`
	UnavailableRuns  int     `json:"unavailable_runs"`
}

type User

type User struct {
	ID           string    `json:"id"`
	Username     string    `json:"username"`
	PasswordHash string    `json:"-"`
	TOTPSecret   string    `json:"-"`
	TOTPEnabled  bool      `json:"totp_enabled"`
	Role         string    `json:"role"`
	CreatedAt    time.Time `json:"created_at"`
}

Jump to

Keyboard shortcuts

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