server

package
v0.23.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

ABOUTME: Manages server state files so CLI commands can detect ABOUTME: a running agentsview server instance.

ABOUTME: POST /api/v1/sessions/sync runs a one-off sync for the ABOUTME: session identified by body.path or body.id and returns ABOUTME: the resulting session detail.

ABOUTME: GET /api/v1/sessions/{id}/tool-calls returns a ABOUTME: flat list of tool calls across all messages in a session.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindAvailablePort

func FindAvailablePort(host string, start int) int

FindAvailablePort finds an available port starting from the given port, binding to the specified host.

func IsLocalServerActive added in v0.23.0

func IsLocalServerActive(dataDir string) bool

IsLocalServerActive reports whether a writable local daemon is managing the SQLite archive in dataDir. Unlike IsServerActive, it ignores read-only state files (pg serve) so commands that need an up-to-date local DB don't skip on-demand sync when only a pg serve daemon is running.

func IsServerActive added in v0.15.0

func IsServerActive(dataDir string) bool

IsServerActive reports whether a server process is managing the database in dataDir. Returns true if:

  • a state file with a live PID exists (even if the port probe fails due to a transient issue), or
  • a startup lock with a live PID exists (server is still syncing / binding its port).

This check does NOT distinguish a writable local daemon from a read-only pg serve. Callers that rely on a fresh local SQLite archive (e.g. `usage`, `token-use`) should use IsLocalServerActive instead.

func IsStartupLocked added in v0.15.0

func IsStartupLocked(dataDir string) bool

IsStartupLocked reports whether the startup lock file exists with a live PID. Callers use this to distinguish "server is starting up" from "server is running but TCP probe failed".

func RemoveStartupLock added in v0.15.0

func RemoveStartupLock(dataDir string)

RemoveStartupLock removes the startup lock file for the current process.

func RemoveStateFile added in v0.15.0

func RemoveStateFile(dataDir string, port int)

RemoveStateFile removes the state file for the given port.

func WaitForStartup added in v0.15.0

func WaitForStartup(dataDir string, timeout time.Duration) bool

WaitForStartup polls until the startup lock clears or a running server is detected, up to the given timeout. Returns true if a server became ready, false on timeout.

func WriteStartupLock added in v0.15.0

func WriteStartupLock(dataDir string)

WriteStartupLock creates a lock file indicating a server is starting up (syncing, binding port). Each server uses a PID-specific filename so concurrent startups on different ports don't clobber each other. Written via a temp file and atomic rename to prevent partial reads.

func WriteStateFile added in v0.15.0

func WriteStateFile(
	dataDir string, host string, port int, version string,
	readOnly bool,
) (string, error)

WriteStateFile writes a state file to dataDir for the running server. Returns the path written. StartedAt is set to the actual process creation time so it passes processStartTime validation even when startup is slow. readOnly indicates whether the server is read-only (e.g. pg serve) versus read/write (local serve).

Types

type AgentTotal added in v0.21.0

type AgentTotal struct {
	Agent               string  `json:"agent"`
	InputTokens         int     `json:"inputTokens"`
	OutputTokens        int     `json:"outputTokens"`
	CacheCreationTokens int     `json:"cacheCreationTokens"`
	CacheReadTokens     int     `json:"cacheReadTokens"`
	Cost                float64 `json:"cost"`
}

AgentTotal holds range-wide token and cost totals per agent.

type Broadcaster added in v0.23.0

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

Broadcaster fans out Event values from the sync engine to all connected SSE clients. It implements sync.Emitter.

func NewBroadcaster added in v0.23.0

func NewBroadcaster() *Broadcaster

NewBroadcaster creates an empty broadcaster.

func (*Broadcaster) Emit added in v0.23.0

func (b *Broadcaster) Emit(scope string)

Emit sends an event to every current subscriber. Delivery is non-blocking: if a subscriber's buffer is full, the event is dropped for that subscriber. The engine never blocks on slow clients.

func (*Broadcaster) Subscribe added in v0.23.0

func (b *Broadcaster) Subscribe() (<-chan Event, func())

Subscribe returns a receive channel for events and an unsubscribe function. Calling unsubscribe closes the channel and removes the subscription. It is safe to call unsubscribe multiple times.

type CacheStats added in v0.21.0

type CacheStats struct {
	CacheReadTokens     int     `json:"cacheReadTokens"`
	CacheCreationTokens int     `json:"cacheCreationTokens"`
	UncachedInputTokens int     `json:"uncachedInputTokens"`
	OutputTokens        int     `json:"outputTokens"`
	HitRate             float64 `json:"hitRate"`
	SavingsVsUncached   float64 `json:"savingsVsUncached"`
}

CacheStats summarizes cache hit/miss for the period.

type Comparison added in v0.21.0

type Comparison struct {
	PriorFrom      string  `json:"priorFrom"`
	PriorTo        string  `json:"priorTo"`
	PriorTotalCost float64 `json:"priorTotalCost"`
	DeltaPct       float64 `json:"deltaPct"`
}

Comparison holds the prior-period cost comparison.

type Event added in v0.23.0

type Event struct {
	Scope string
}

Event is a refresh signal sent by the sync engine after a pass that wrote data. Scope is advisory — subscribers may filter on it but are free to treat it as "refetch now".

type ModelTotal added in v0.21.0

type ModelTotal struct {
	Model               string  `json:"model"`
	InputTokens         int     `json:"inputTokens"`
	OutputTokens        int     `json:"outputTokens"`
	CacheCreationTokens int     `json:"cacheCreationTokens"`
	CacheReadTokens     int     `json:"cacheReadTokens"`
	Cost                float64 `json:"cost"`
}

ModelTotal holds range-wide token and cost totals per model.

type Opener added in v0.12.0

type Opener struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Kind string `json:"kind"` // "editor", "terminal", "files", "action"
	Bin  string `json:"bin"`
}

Opener represents an application that can open a project directory.

type Option

type Option func(*Server)

Option configures a Server.

func WithBaseContext added in v0.13.0

func WithBaseContext(ctx context.Context) Option

WithBaseContext sets the base context for all incoming HTTP requests. When this context is cancelled, request contexts are also cancelled, causing long-lived handlers (SSE) to exit and unblocking graceful shutdown.

func WithBasePath added in v0.16.0

func WithBasePath(path string) Option

WithBasePath sets a URL prefix for reverse-proxy deployments. The path must start with "/" and not end with "/" (e.g. "/agentsview"). When set, the server strips this prefix from incoming requests and injects a <base href> tag into the SPA.

func WithBroadcaster added in v0.23.0

func WithBroadcaster(b *Broadcaster) Option

WithBroadcaster wires an event broadcaster into the server so the /api/v1/events handler has something to subscribe to. Required for live-refresh SSE; absent in PG serve mode where the engine is nil.

func WithDataDir added in v0.12.0

func WithDataDir(dir string) Option

WithDataDir sets the data directory used for update caching.

func WithGenerateFunc added in v0.4.0

func WithGenerateFunc(f insight.GenerateFunc) Option

WithGenerateFunc overrides the insight generation function, allowing tests to substitute a stub. Nil is ignored.

func WithGenerateStreamFunc added in v0.10.0

func WithGenerateStreamFunc(f insight.GenerateStreamFunc) Option

WithGenerateStreamFunc overrides the streaming insight generation function used by the SSE handler. Nil is ignored.

func WithUpdateChecker added in v0.12.0

func WithUpdateChecker(f UpdateCheckFunc) Option

WithUpdateChecker overrides the update check function, allowing tests to substitute a deterministic stub.

func WithVersion

func WithVersion(v VersionInfo) Option

WithVersion sets the build-time version metadata.

type ProjectTotal added in v0.21.0

type ProjectTotal struct {
	Project             string  `json:"project"`
	InputTokens         int     `json:"inputTokens"`
	OutputTokens        int     `json:"outputTokens"`
	CacheCreationTokens int     `json:"cacheCreationTokens"`
	CacheReadTokens     int     `json:"cacheReadTokens"`
	Cost                float64 `json:"cost"`
}

ProjectTotal holds range-wide token and cost totals per project.

type SSEStream

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

SSEStream manages a Server-Sent Events connection.

func NewSSEStream

func NewSSEStream(w http.ResponseWriter) (*SSEStream, error)

NewSSEStream initializes an SSE connection by setting the required headers and flushing them to the client. Returns an error if the ResponseWriter does not support streaming.

func (*SSEStream) ForceWriteDeadlineNow added in v0.10.0

func (s *SSEStream) ForceWriteDeadlineNow()

ForceWriteDeadlineNow asks the underlying writer (when supported) to expire write deadlines immediately. This is used during shutdown to unblock stalled writes.

func (*SSEStream) Send

func (s *SSEStream) Send(event, data string) bool

Send writes an SSE event with the given name and string data. It returns false when the write fails.

func (*SSEStream) SendJSON

func (s *SSEStream) SendJSON(event string, v any) bool

SendJSON writes an SSE event with JSON-serialized data. Logs and skips the event if marshaling fails.

type Server

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

Server is the HTTP server that serves the SPA and REST API.

func New

func New(
	cfg config.Config, database db.Store, engine *sync.Engine,
	opts ...Option,
) *Server

New creates a new Server.

func (*Server) Handler

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

Handler returns the http.Handler with middleware applied.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the HTTP server.

func (*Server) SetGithubToken

func (s *Server) SetGithubToken(token string)

SetGithubToken updates the GitHub token for testing.

func (*Server) SetPort

func (s *Server) SetPort(port int)

SetPort updates the listen port (for testing).

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the HTTP server.

type StateFile added in v0.15.0

type StateFile struct {
	PID       int    `json:"pid"`
	Port      int    `json:"port"`
	Host      string `json:"host"`
	Version   string `json:"version"`
	StartedAt string `json:"started_at"`
	ReadOnly  bool   `json:"read_only,omitempty"`
}

StateFile records a running server instance.

func FindRunningServer added in v0.15.0

func FindRunningServer(dataDir string) *StateFile

FindRunningServer scans dataDir for server state files and returns one whose process is still alive and whose port is accepting connections. When both a writable local daemon and a read-only pg serve daemon are running against the same data dir, the writable one is preferred so CLI sync/write operations don't silently land on a read-only target. Stale state files are cleaned up automatically.

type UpdateCheckFunc added in v0.12.0

type UpdateCheckFunc func(
	currentVersion string,
	forceCheck bool,
	cacheDir string,
) (*update.UpdateInfo, error)

UpdateCheckFunc is the signature for functions that check for available updates. The default is update.CheckForUpdate.

type UsageSummaryResponse added in v0.21.0

type UsageSummaryResponse struct {
	From          string                `json:"from"`
	To            string                `json:"to"`
	Totals        db.UsageTotals        `json:"totals"`
	Daily         []db.DailyUsageEntry  `json:"daily"`
	ProjectTotals []ProjectTotal        `json:"projectTotals"`
	ModelTotals   []ModelTotal          `json:"modelTotals"`
	AgentTotals   []AgentTotal          `json:"agentTotals"`
	SessionCounts db.UsageSessionCounts `json:"sessionCounts"`
	CacheStats    CacheStats            `json:"cacheStats"`
	Comparison    *Comparison           `json:"comparison,omitempty"`
}

UsageSummaryResponse is the JSON shape for GET /api/v1/usage/summary.

type VersionInfo

type VersionInfo struct {
	Version   string `json:"version"`
	Commit    string `json:"commit"`
	BuildDate string `json:"build_date"`
	ReadOnly  bool   `json:"read_only,omitempty"`
}

VersionInfo holds build-time version metadata.

Jump to

Keyboard shortcuts

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