client

package
v0.9.4 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: 15 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 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

View Source
const DefaultBase = "http://127.0.0.1:7777"

DefaultBase is where flockd listens unless local_api.listen says otherwise.

View Source
const TokenFile = "local_api_token"

TokenFile is the per-install bearer token's file name inside the data dir.

Variables

View Source
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

func DataDir(explicit string) string

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.

func ReadSSE

func ReadSSE(r io.Reader, fn func(Event) error) error

ReadSSE parses a text/event-stream body: `event:`/`data:` lines, blank line dispatches, `:` lines are comments. Multi-line data is joined with newlines per the spec. Events without a name (the OpenAI stream) are delivered with Name == "".

func Remedy

func Remedy(err error) string

Remedy is the one-line hint tera prints under an error from this package: what to run to fix it. Empty when there is nothing to suggest.

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) Error

func (e *APIError) Error() string

func (*APIError) NotServing

func (e *APIError) NotServing() bool

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

func FromResolved(r Resolved) (*Client, error)

FromResolved builds a client from an already-resolved endpoint (tests, or callers that resolved once and want several clients).

func New

func New(o Options) (*Client, error)

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) Activity

func (c *Client) Activity(ctx context.Context) (gen.ActivityList, error)

Activity is GET /api/v1/activity.

func (*Client) CancelDownload

func (c *Client) CancelDownload(ctx context.Context, id string) error

CancelDownload is DELETE /api/v1/models/{id}/download.

func (*Client) Catalog

func (c *Client) Catalog(ctx context.Context, refresh bool) (gen.CatalogList, error)

Catalog is GET /api/v1/catalog (refresh bypasses the daemon's cache).

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

func (c *Client) Check(status int, body []byte) error

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

func (c *Client) CheckUpdate(ctx context.Context) (gen.Update, error)

CheckUpdate is POST /api/v1/update/check.

func (*Client) DeleteModel

func (c *Client) DeleteModel(ctx context.Context, id string) error

DeleteModel is DELETE /api/v1/models/{id}.

func (*Client) Earnings

func (c *Client) Earnings(ctx context.Context) (gen.Earnings, error)

Earnings is GET /api/v1/earnings.

func (*Client) Enroll

func (c *Client) Enroll(ctx context.Context, claimCode string) (gen.EnrollResponse, error)

Enroll is POST /api/v1/enroll: enrollment plus a live tunnel (re)start.

func (*Client) Events

func (c *Client) Events(ctx context.Context, logs bool) (*Stream, error)

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

func (c *Client) FindModel(ctx context.Context, id string) (gen.ModelRow, bool, error)

FindModel returns the row for id from the model list (ok=false when the daemon does not know it).

func (*Client) Follow

func (c *Client) Follow(ctx context.Context, logs bool, fn func(Event) error) error

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) Health

func (c *Client) Health(ctx context.Context) (gen.Health, error)

Health probes the unauthenticated liveness route.

func (*Client) Limits

func (c *Client) Limits(ctx context.Context) (gen.Limits, error)

Limits is GET /api/v1/limits.

func (*Client) LoadModel

func (c *Client) LoadModel(ctx context.Context, id string) error

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

func (c *Client) Logs(ctx context.Context, n int) ([]gen.LogEntry, error)

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) Models

func (c *Client) Models(ctx context.Context) (gen.ModelList, error)

Models is GET /api/v1/models: the local cache merged with runtime state.

func (*Client) OpenAIModels

func (c *Client) OpenAIModels(ctx context.Context) ([]string, error)

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) PinModel

func (c *Client) PinModel(ctx context.Context, id string, pinned bool) error

PinModel is POST /api/v1/models/{id}/pin.

func (*Client) Requests added in v0.7.3

func (c *Client) Requests(ctx context.Context, recent int) (gen.RequestActivity, error)

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

func (c *Client) SetDefaultModel(ctx context.Context, id string) error

SetDefaultModel is POST /api/v1/models/{id}/default.

func (*Client) StartDownload

func (c *Client) StartDownload(ctx context.Context, id string) (gen.DownloadStatus, error)

StartDownload is POST /api/v1/models/{id}/download: State is "downloading" (202, started or already running) or "ready" (200).

func (*Client) Status

func (c *Client) Status(ctx context.Context) (gen.Status, error)

Status is GET /api/v1/status.

func (*Client) UnloadModel

func (c *Client) UnloadModel(ctx context.Context, id string) error

UnloadModel is POST /api/v1/models/{id}/unload.

func (*Client) UpdateLimits

func (c *Client) UpdateLimits(ctx context.Context, lim gen.Limits) (gen.Limits, error)

UpdateLimits is PUT /api/v1/limits; returns the applied limits.

type Delta

type Delta struct {
	Content   string
	Reasoning string
}

Delta is one streamed chunk: answer text and/or chain-of-thought.

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 Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message is one chat turn.

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

func Resolve(o Options) Resolved

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).

func (*Stream) Err

func (s *Stream) Err() error

Err is the terminal error once C is closed.

type UnreachableError

type UnreachableError struct {
	Base string
	Err  error
}

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

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Usage is the OpenAI usage frame.

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.

Jump to

Keyboard shortcuts

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