localapi

package
v0.9.5 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 37 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package localapi is the daemon's loopback HTTP surface on localhost:7777: the OpenAI-compatible /v1 endpoints (Phase 0 exit criterion) and the management /api/v1 REST+SSE API that the CLI, TUI and embedded web dashboard all consume (SPEC §A1.2: one source of truth).

Index

Constants

This section is empty.

Variables

View Source
var ErrEnrollInProgress = errors.New("enrollment already in progress")

ErrEnrollInProgress is returned by the Enroll dep while another enrollment is running; the handler maps it to 409.

Functions

func LoadOrCreateToken

func LoadOrCreateToken(dataDir string) (string, error)

LoadOrCreateToken returns the per-install bearer token, generating it with 0600 on first run.

TODO(keychain): store in macOS Keychain / Windows DPAPI / secret service instead of a file (SPEC §A1.2); file+0600 is the Phase 0 baseline.

Types

type Deps

type Deps struct {
	Engine   *engine.Engine
	Governor *governor.Governor // may be nil
	Models   *models.Manager    // may be nil
	ModelOps *modelops.Service  // may be nil (mock runtime)
	Events   *events.Hub        // may be nil (SSE then ticks status only)
	LogRing  *logging.Ring      // may be nil
	Hardware *typesv1.CapabilityProfile
	// RuntimeAccel reports the accelerator of the llama-server build in
	// use (hardware.AccelPreference's first published lane). Nil for the
	// mock runtime: status then omits runtime_accel.
	RuntimeAccel func() string
	Log          *slog.Logger
	WebFS        fs.FS // embedded dashboard dist; may be nil
	NodeID       string
	Version      string
	Standalone   bool
	// DataDir persists live limit edits (limits.toml overlay); empty
	// disables persistence.
	DataDir string
	// Mesh reports live mesh membership (enrolled, node id, cert expiry).
	// Nil falls back to the static NodeID with enrolled=false.
	Mesh func() MeshStatus
	// BootPending reports that the default model is still being fetched
	// or loaded: status says `starting` rather than `no-model` while a
	// node has nothing loaded (flockd#48). Nil = never pending.
	BootPending func() bool
	// Enroll submits a claim code to the running daemon: enrollment plus
	// tunnel (re)start. Nil (standalone) answers 501.
	Enroll func(ctx context.Context, claimCode string) error
	// Earnings returns the operator account's ledger position as last
	// pushed by the coordinator (docs#24); ok is false before the first
	// snapshot. Nil = never enrolled anywhere that pushes one.
	Earnings func() (LedgerEarnings, bool)
	// Assign exposes coordinator placement status (model rows carry it).
	// May be nil.
	Assign *assign.Service
	// MeshManaged / SetMeshManaged back the limits toggle that lets the
	// coordinator place models on this node. Nil = not switchable (reads
	// as on).
	MeshManaged    func() bool
	SetMeshManaged func(bool)
	// Defaults seeds the model/budget limits persisted by PUT /limits when
	// the live sources (Models, ModelOps) are absent (mock runtime).
	Defaults config.LiveLimits
	// Activity is the recent-activity ring (GET /api/v1/activity). May be nil.
	Activity *activity.Ring
	// Update is the version checker (status.update, POST /update/check).
	// May be nil.
	Update *update.Checker
	// RequireAuthV1 extends bearer auth to the OpenAI /v1 endpoints (the
	// value at startup; the limits API can switch it on a running daemon).
	RequireAuthV1 bool
	// Settings wires the settings the limits API exposes beyond the
	// governor, store and memory knobs (flockd#55).
	Settings SettingsDeps
	// Token authenticates /api/v1 (and /v1 when RequireAuthV1).
	Token string
}

Deps wires the server to the daemon internals.

type LedgerEarnings added in v0.6.1

type LedgerEarnings struct {
	// Settled is the vested main balance (redeemable); Pending is escrow
	// (vesting after the canary window).
	Settled, Pending int64
	// Payout credits earned since 00:00 UTC / trailing 7 days / ever.
	EarnedToday, Earned7d, Lifetime int64
	CreditsPerUSD                   int64
	// AsOf is the coordinator's read time; NextVestAt is zero with
	// nothing in escrow.
	AsOf, NextVestAt time.Time
	// ReceivedAt (local clock) and PushInterval decide freshness: the
	// ledger figure is shown only while the snapshot is younger than two
	// intervals.
	ReceivedAt   time.Time
	PushInterval time.Duration
}

LedgerEarnings is the coordinator's EarningsSnapshot as the local API consumes it: the OPERATOR account's position (every node of the operator together), in integer ledger credits at CreditsPerUSD.

func (LedgerEarnings) Fresh added in v0.6.1

func (e LedgerEarnings) Fresh(now time.Time) bool

Fresh reports whether the snapshot is young enough to show.

type MeshStatus added in v0.3.0

type MeshStatus struct {
	Enrolled      bool
	NodeID        string
	CertExpiresAt time.Time
	// RotationError is why the last due client-cert rotation failed; ""
	// when rotation is not due or succeeded. The node keeps serving on
	// the current cert and drops off the mesh when it expires.
	RotationError string
}

MeshStatus is the node's mesh membership, surfaced in /api/v1/status. Before enrollment NodeID is the key fingerprint; after, the coordinator-assigned id.

type Server

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

Server is the loopback HTTP server.

func New

func New(deps Deps) *Server

New assembles routes.

func (*Server) CancelModelDownload added in v0.3.0

func (s *Server) CancelModelDownload(w http.ResponseWriter, _ *http.Request, id gen.ModelID)

CancelModelDownload implements gen.ServerInterface.

func (*Server) CheckUpdate added in v0.4.0

func (s *Server) CheckUpdate(w http.ResponseWriter, r *http.Request)

CheckUpdate implements gen.ServerInterface: an on-demand version check. A feed that is unreachable (or not built yet) is a 502 here because the operator asked explicitly; the background checks stay silent.

func (*Server) DeleteModel added in v0.3.0

func (s *Server) DeleteModel(w http.ResponseWriter, r *http.Request, id gen.ModelID)

DeleteModel implements gen.ServerInterface.

func (*Server) EnrollNode added in v0.3.0

func (s *Server) EnrollNode(w http.ResponseWriter, r *http.Request)

EnrollNode implements gen.ServerInterface: submit a claim code to the running daemon — enrollment (or re-enrollment, the one path that works while old credentials exist) plus a tunnel (re)start, no restart required.

func (*Server) GetActivity added in v0.4.0

func (s *Server) GetActivity(w http.ResponseWriter, _ *http.Request)

GetActivity implements gen.ServerInterface.

func (*Server) GetCatalog added in v0.3.0

func (s *Server) GetCatalog(w http.ResponseWriter, r *http.Request, params gen.GetCatalogParams)

GetCatalog implements gen.ServerInterface.

func (*Server) GetEarnings added in v0.3.0

func (s *Server) GetEarnings(w http.ResponseWriter, _ *http.Request)

GetEarnings implements gen.ServerInterface. Ledger-backed when the coordinator has pushed a fresh EarningsSnapshot over the tunnel (docs#24): the operator account's settled/pending position, at the coordinator's credits_per_usd peg. Otherwise — standalone, not enrolled, or the tunnel has been down for two push intervals — the local estimate from this node's own counters, labelled simulated.

func (*Server) GetHealth added in v0.3.0

func (s *Server) GetHealth(w http.ResponseWriter, _ *http.Request)

GetHealth is the one unauthenticated route: liveness for `tera up`, service managers, and the desktop app's daemon probe.

func (*Server) GetLimits added in v0.3.0

func (s *Server) GetLimits(w http.ResponseWriter, _ *http.Request)

GetLimits implements gen.ServerInterface.

func (*Server) GetLogs added in v0.3.0

func (s *Server) GetLogs(w http.ResponseWriter, _ *http.Request, params gen.GetLogsParams)

GetLogs implements gen.ServerInterface.

func (*Server) GetRequests added in v0.7.3

func (s *Server) GetRequests(w http.ResponseWriter, _ *http.Request, params gen.GetRequestsParams)

GetRequests implements gen.ServerInterface: the live activity view.

func (*Server) GetStatus added in v0.3.0

func (s *Server) GetStatus(w http.ResponseWriter, _ *http.Request)

GetStatus implements gen.ServerInterface.

func (*Server) Handler

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

Handler exposes the mux (tests).

func (*Server) ListModels added in v0.3.0

func (s *Server) ListModels(w http.ResponseWriter, _ *http.Request)

ListModels implements gen.ServerInterface.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(ctx context.Context, addr string) error

ListenAndServe binds addr (must be loopback unless the operator opted out in config, which docs warn about) and serves until ctx is cancelled.

func (*Server) LoadModel added in v0.3.0

func (s *Server) LoadModel(w http.ResponseWriter, r *http.Request, id gen.ModelID)

LoadModel implements gen.ServerInterface. Synchronous: llama-server startup is seconds, and the caller wants the verdict.

func (*Server) PinModel added in v0.3.0

func (s *Server) PinModel(w http.ResponseWriter, r *http.Request, id gen.ModelID)

PinModel implements gen.ServerInterface.

func (*Server) SetDefaultModel added in v0.3.0

func (s *Server) SetDefaultModel(w http.ResponseWriter, _ *http.Request, id gen.ModelID)

SetDefaultModel implements gen.ServerInterface.

func (*Server) StartModelDownload added in v0.3.0

func (s *Server) StartModelDownload(w http.ResponseWriter, r *http.Request, id gen.ModelID)

StartModelDownload implements gen.ServerInterface.

func (*Server) UnloadModel added in v0.3.0

func (s *Server) UnloadModel(w http.ResponseWriter, r *http.Request, id gen.ModelID)

UnloadModel implements gen.ServerInterface.

func (*Server) UpdateLimits added in v0.3.0

func (s *Server) UpdateLimits(w http.ResponseWriter, r *http.Request)

UpdateLimits implements gen.ServerInterface.

type SettingsDeps added in v0.7.4

type SettingsDeps struct {
	// Boot is what the daemon started with: the running value of the
	// settings that only a restart applies.
	Boot SettingsValues
	// Overlay is the keys limits.toml already held at startup; a save
	// carries them forward and adds whatever a PUT sets.
	Overlay config.LimitsExtra
	// ApplyPlan applies the slot ceiling and context limits to a running
	// daemon: later loads, the mesh dispatch cap, and a reload of idle
	// loaded models. Nil = nothing to apply (they are still saved).
	ApplyPlan func(modelops.PlanLimits)
	// SetExclude replaces models.exclude for later placements. May be nil.
	SetExclude func([]string)
	// SetLogLevel changes the daemon's log level. Nil = the level is only
	// saved (and reported as pending a restart).
	SetLogLevel func(string)
	// BudgetChanged is called after a PUT that may have moved a field of
	// the coordinator's ResourceBudget (max_disk_mb, max_ram_mb, the slot
	// ceiling, the serve policy), so the tunnel can send a BudgetUpdate
	// and placement follows the app without a reconnect. May be nil.
	BudgetChanged func()
}

SettingsDeps is what the daemon hands the limits API for them.

type SettingsValues added in v0.7.4

type SettingsValues struct {
	MaxConcurrent  int // budget.max_concurrent, 0 = auto
	MinConcurrent  int // budget.min_concurrent, 0 = auto
	MaxVRAMPercent int
	MaxContext     int
	MinContext     int
	ContextLength  int
	Exclude        []string
	DefaultModel   string // "" = none
	RequireAuthV1  bool
	LogLevel       string
}

SettingsValues are the settings added by flockd#55, as plain values.

Directories

Path Synopsis
Package client is the loopback client of the daemon's local API on localhost:7777 — the one client the tera CLI, the TUI, `tera mcp` and any Go tooling share (SPEC §A1.2: CLI, TUI and web dash are all clients of one API).
Package client is the loopback client of the daemon's local API on localhost:7777 — the one client the tera CLI, the TUI, `tera mcp` and any Go tooling share (SPEC §A1.2: CLI, TUI and web dash are all clients of one API).
clienttest
Package clienttest stands up a real localapi.Server on an httptest listener — the generated router, the mock runtime, a governor with fake signal sources, the event hub and the log ring — so client, CLI, TUI and `tera mcp` tests talk to the actual API contract rather than a hand-rolled fake that could drift from it.
Package clienttest stands up a real localapi.Server on an httptest listener — the generated router, the mock runtime, a governor with fake signal sources, the event hub and the log ring — so client, CLI, TUI and `tera mcp` tests talk to the actual API contract rather than a hand-rolled fake that could drift from it.
Package gen provides primitives to interact with the openapi HTTP API.
Package gen provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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