Documentation
¶
Overview ¶
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). The management half is generated from api/openapi.yaml (internal/localapi/gen, `make gen`), so it cannot drift from the daemon; this package adds what codegen cannot express: token and data-dir resolution, user-facing errors, the SSE event stream, and the OpenAI-compatible chat helper.
It is the loopback client only — the mesh tunnel client lives in internal/tunnel.
Index ¶
- Constants
- Variables
- func DataDir(explicit string) string
- func ReadSSE(r io.Reader, fn func(Event) error) error
- func Remedy(err error) string
- type APIError
- type ChatRequest
- type ChatResult
- type Client
- func (c *Client) Activity(ctx context.Context) (gen.ActivityList, error)
- func (c *Client) CancelDownload(ctx context.Context, id string) error
- func (c *Client) Catalog(ctx context.Context, refresh bool) (gen.CatalogList, error)
- func (c *Client) Chat(ctx context.Context, req ChatRequest) (ChatResult, error)
- func (c *Client) ChatStream(ctx context.Context, req ChatRequest, fn func(Delta) error) (ChatResult, error)
- func (c *Client) Check(status int, body []byte) error
- func (c *Client) CheckUpdate(ctx context.Context) (gen.Update, error)
- func (c *Client) DeleteModel(ctx context.Context, id string) error
- func (c *Client) Earnings(ctx context.Context) (gen.Earnings, error)
- func (c *Client) Enroll(ctx context.Context, claimCode string) (gen.EnrollResponse, error)
- func (c *Client) Events(ctx context.Context, logs bool) (*Stream, error)
- func (c *Client) FindModel(ctx context.Context, id string) (gen.ModelRow, bool, error)
- func (c *Client) Follow(ctx context.Context, logs bool, fn func(Event) error) error
- func (c *Client) Health(ctx context.Context) (gen.Health, error)
- func (c *Client) Limits(ctx context.Context) (gen.Limits, error)
- func (c *Client) LoadModel(ctx context.Context, id string) error
- func (c *Client) Logs(ctx context.Context, n int) ([]gen.LogEntry, error)
- func (c *Client) Models(ctx context.Context) (gen.ModelList, error)
- func (c *Client) OpenAIModels(ctx context.Context) ([]string, error)
- func (c *Client) PinModel(ctx context.Context, id string, pinned bool) error
- func (c *Client) Requests(ctx context.Context, recent int) (gen.RequestActivity, error)
- func (c *Client) SetDefaultModel(ctx context.Context, id string) error
- func (c *Client) StartDownload(ctx context.Context, id string) (gen.DownloadStatus, error)
- func (c *Client) Status(ctx context.Context) (gen.Status, error)
- func (c *Client) UnloadModel(ctx context.Context, id string) error
- func (c *Client) UpdateLimits(ctx context.Context, lim gen.Limits) (gen.Limits, error)
- type Delta
- type Event
- type Message
- type Options
- type Resolved
- type Stream
- type UnreachableError
- type Usage
Constants ¶
const DefaultBase = "http://127.0.0.1:7777"
DefaultBase is where flockd listens unless local_api.listen says otherwise.
const TokenFile = "local_api_token"
TokenFile is the per-install bearer token's file name inside the data dir.
Variables ¶
var ErrStop = errors.New("stop following")
ErrStop is returned by a Follow callback to end the stream cleanly; Follow returns it untouched so callers can tell "done" from "lost".
Functions ¶
func DataDir ¶
DataDir resolves the daemon's data directory the same way flockd does (defaults <- TOML <- FLOCKD_* env), so that files exchanged between the two processes — the claim code, the local API token — land where the daemon actually looks. Falling back to the built-in default would silently break enrollment for anyone who moved data_dir. An explicit value (the --data-dir flag) wins.
Types ¶
type APIError ¶
type APIError struct {
Status int
Type string
Message string
// contains filtered or unexported fields
}
APIError is a non-2xx answer from the daemon: the status and the message from its `{"error":{"message","type"}}` body (both halves of the API use that shape). Status 401 renders the token-source explanation instead — that error is about the client's setup, not the request.
func (*APIError) NotServing ¶
NotServing reports the governor's refusal (503 on /v1): the node is yielded, on battery, too hot, or outside its schedule.
type ChatRequest ¶
type ChatRequest struct {
// Model is the model id; empty means the daemon's default model.
Model string `json:"model,omitempty"`
Messages []Message `json:"messages"`
MaxTokens int `json:"max_tokens,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
Seed *uint64 `json:"seed,omitempty"`
}
ChatRequest is the request shape `scripts/smoke.sh` and the OpenAI SDKs send. Zero values are omitted so the daemon's defaults apply.
type ChatResult ¶
type ChatResult struct {
Model string
Content string
Reasoning string
FinishReason string
Usage Usage
Elapsed time.Duration
}
ChatResult is a finished completion: the assembled text, the usage frame, and how long it took (for tok/s).
func (ChatResult) TokensPerSec ¶
func (r ChatResult) TokensPerSec() float64
TokensPerSec is completion tokens over wall time (0 when unknown).
type Client ¶
type Client struct {
Resolved
// Mgmt is the generated client with a 10s deadline per request.
Mgmt *gen.ClientWithResponses
// MgmtLong is the same client without a deadline: synchronous loads
// (llama-server startup, download-then-load) outlive any sane fixed
// timeout, so callers bound those with a context instead.
MgmtLong *gen.ClientWithResponses
// contains filtered or unexported fields
}
Client talks to one daemon. Mgmt is the generated management client (every /api/v1 route in the spec); the typed helpers below wrap the routes tera uses and turn non-2xx responses into user-facing errors.
func FromResolved ¶
FromResolved builds a client from an already-resolved endpoint (tests, or callers that resolved once and want several clients).
func New ¶
New resolves Options and builds the client. It never fails on a missing token — the daemon's 401 says where the token was looked for — so a probe of an unauthenticated route still works.
func (*Client) CancelDownload ¶
CancelDownload is DELETE /api/v1/models/{id}/download.
func (*Client) Chat ¶
func (c *Client) Chat(ctx context.Context, req ChatRequest) (ChatResult, error)
Chat is a non-streaming POST /v1/chat/completions. A governor refusal comes back as an *APIError with NotServing() true; Remedy(err) says what to do about it.
func (*Client) ChatStream ¶
func (c *Client) ChatStream(ctx context.Context, req ChatRequest, fn func(Delta) error) (ChatResult, error)
ChatStream is a streaming POST /v1/chat/completions: fn is called for every delta as it arrives (returning an error stops the stream), and the result carries the assembled text plus the usage frame the daemon sends with the final chunk. An error frame mid-stream ends it with that message.
func (*Client) Check ¶
Check turns a response status + body into nil (2xx) or an *APIError. Every typed helper goes through it; callers using Mgmt directly can too.
func (*Client) CheckUpdate ¶
CheckUpdate is POST /api/v1/update/check.
func (*Client) DeleteModel ¶
DeleteModel is DELETE /api/v1/models/{id}.
func (*Client) Events ¶
Events opens the event stream and delivers events on a channel. The connection (and its auth) is established before Events returns, so a 401 or an unreachable daemon is an immediate error; C closes when the stream ends for any reason (ctx cancelled, daemon gone). Cancel ctx to stop it.
func (*Client) FindModel ¶
FindModel returns the row for id from the model list (ok=false when the daemon does not know it).
func (*Client) Follow ¶
Follow opens the daemon's event stream (`?logs=1` when logs is set) and calls fn for every event until fn returns an error, ctx is cancelled, or the daemon closes the stream. The bearer token goes in the Authorization header — only EventSource needs the `?token=` form. Matches handleEvents in internal/localapi/api.go.
func (*Client) LoadModel ¶
LoadModel is POST /api/v1/models/{id}/load. Synchronous on the daemon side and legitimately slow: no deadline, bound it with ctx.
func (*Client) Logs ¶
Logs is GET /api/v1/logs?n=: the last n entries of the ring, oldest first (n <= 0 leaves the daemon's default).
func (*Client) OpenAIModels ¶
OpenAIModels is GET /v1/models: the ids of the models the daemon serves right now (loaded, plus what it can load on demand).
func (*Client) Requests ¶ added in v0.7.3
Requests is GET /api/v1/requests: what is in flight on each model and the last `recent` finished requests (< 0 = the daemon's default).
func (*Client) SetDefaultModel ¶
SetDefaultModel is POST /api/v1/models/{id}/default.
func (*Client) StartDownload ¶
StartDownload is POST /api/v1/models/{id}/download: State is "downloading" (202, started or already running) or "ready" (200).
func (*Client) UnloadModel ¶
UnloadModel is POST /api/v1/models/{id}/unload.
type Event ¶
type Event struct {
Name string
Data json.RawMessage
}
Event is one server-sent event from GET /api/v1/events. Name is the event type documented in api/openapi.yaml (status, model_progress, models_changed, model_assignment, activity, update_available, log); Data is its JSON payload.
type Options ¶
type Options struct {
// API is the daemon base URL (default DefaultBase).
API string
// DataDir is an explicit data directory (the --data-dir flag). Empty
// resolves it like flockd does: config.toml -> FLOCKD_DATA_DIR ->
// ~/.teraflock. The desktop app mirrors that order in Rust; the two
// must keep agreeing.
DataDir string
// Token is an explicit bearer token (the --token flag). Empty falls
// back to $TERA_TOKEN, then <DataDir>/local_api_token.
Token string
}
Options is what a caller can pin explicitly (CLI flags); everything left empty is resolved the way `tera` always has.
type Resolved ¶
type Resolved struct {
Base string
Token string
DataDir string
// TokenSource says where the token was found — "--token", "$TERA_TOKEN",
// the file path — or, when none was, where it was looked for. It is
// user-facing: a 401 quotes it.
TokenSource string
}
Resolved is the outcome of Resolve: where the client will talk, with which token, and where that token came from (for error messages).
func Resolve ¶
Resolve applies the precedence rules: base URL from Options.API (default DefaultBase); token from Options.Token, then $TERA_TOKEN, then <dataDir>/local_api_token. The token is per install and lives beside the daemon's other state, so pointing at the wrong data dir is the usual cause of a 401 — TokenSource records where we looked so the error can say so.
type Stream ¶
type Stream struct {
C <-chan Event
// contains filtered or unexported fields
}
Stream is an open event stream: read C until it closes, then Err says why (nil when the daemon ended it or ctx was cancelled).
type UnreachableError ¶
UnreachableError means no daemon answered at Base (not running, wrong --api, or a request that timed out).
func (*UnreachableError) Error ¶
func (e *UnreachableError) Error() string
func (*UnreachableError) Unwrap ¶
func (e *UnreachableError) Unwrap() error
Directories
¶
| Path | Synopsis |
|---|---|
|
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. |