cli

package
v0.25.2 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 26 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 cli implements the marbor CLI - a thin client of the Admin API. The CLI never talks to a Marbor Agent directly; every command is exactly one Admin API request.

Index

Constants

View Source
const (
	ExitOK          = 0
	ExitUserError   = 1
	ExitServerError = 2
	ExitAttention   = 3
	ExitAuthError   = 4
)

Exit codes: 0 ok, 1 user error, 2 server error, 3 the command worked but found something that needs attention (only `marbor backup list --check` today), 4 auth error.

Variables

View Source
var ErrReplicaDetailUnavailable = errors.New("runtime action succeeded, but the response could not be read, so replica details are unavailable")

ErrReplicaDetailUnavailable is returned by RuntimeAction, together with a nil ReplicaInfo, when the action succeeded but the response body could not be decoded. It is not a failure of the action.

View Source
var Version = "dev"

Version is set at process startup from main.Version (main.go's cli.Version = Version assignment). Defaults to "dev".

Functions

func HelpRows

func HelpRows() [][2]string

HelpRows returns (name[+args], short-description) pairs for every non-hidden top-level CLI command, in registry declaration order - the exact same rows writeRootHelp's own command table renders (via childRows(c.Sub) below), exposed so main.go's top-level --help/bare-command output can fold the real Admin API CLI command list into its own combined table instead of hand-maintaining a second, independently-drifting copy of this same data (see the CLI hardening review's findings: main.go previously hand-listed a stale subset of these names). Hidden commands (e.g. "completion") are intentionally omitted here, matching childRows' own Hidden check - main.go should not advertise them either. Reusing childRows rather than writing a second row-builder is deliberate: two independent implementations computing "the same" rows is exactly the kind of duplication finding #3's fix eliminated once already.

func Run

func Run(args []string, stdout, stderr io.Writer) int

Run parses args and dispatches to the requested subcommand, returning the process exit code (0 ok, 1 user error, 2 server error, 4 auth error). It delegates entirely to the registry-driven dispatcher (dispatch.go). The old hand-rolled switch statement that used to live here has been deleted now that every leaf command's Run is wired to its real implementation. Behavioral equivalence with that old switch was verified during the migration via a differential test (dispatch_differential_test.go) that compared dispatch()'s output against the legacy switch across ~190 argument vectors; that test was deleted once this function started delegating directly to dispatch() (comparing the dispatcher against itself would have been tautological). Current coverage is the registry-wide trailing-argument test plus the full internal/cli test suite.

func SuggestTopLevel

func SuggestTopLevel(input string) []string

SuggestTopLevel returns up to 3 "did you mean" candidates for a mistyped top-level command word (os.Args[1] in main.go), using the same suggest() engine that already powers in-CLI typo correction (reportUnknownToken in dispatch.go) - so a typo of a top-level word and a typo of an in-CLI action get identical suggestion behavior.

The candidate set is every name main.go's resolveCommand would actually route somewhere useful: TopLevelCommandNames() (every registered CLI command, INCLUDING Hidden ones like "completion" - a typo of a hidden command should still surface a correct suggestion, since Hidden only means "not advertised in --help", never "unreachable") unioned with the four other real top-level words resolveCommand recognizes that are not part of the internal/cli registry at all: "help", "bench", "agent", "uninstall". Dash-prefixed flag forms are deliberately never included - resolveCommand's dash check (main.go) runs before "unknown" is ever reached, so a dash-prefixed input never gets here to be suggested against.

func TopLevelCommandNames

func TopLevelCommandNames() []string

TopLevelCommandNames returns the Name of every direct child of root() - the set of bare words that main.go's resolveCommand must route to "cli". Backed by the same registry that the dispatcher, help writer, and man/completion generators read, so main.go's whitelist cannot drift out of sync with the commands actually implemented in cli.Run (see registry_tree.go's buildRoot - this is what makes "key", "spill", and "requests" reachable from the real binary).

Deliberately includes Hidden commands (e.g. "completion") - Hidden only controls whether a command is advertised in root --help, never whether it is dispatchable. Filtering hidden commands out here would silently reintroduce the exact unreachable-command bug this function exists to fix. Callers that want the advertised subset for display (root help) should filter root().Sub themselves, not rely on this function to do it.

Types

type ApproveUserRequest added in v0.21.0

type ApproveUserRequest struct {
	APIKeyName string `json:"api_key_name,omitempty"`
	CreateKey  *struct {
		Name         string   `json:"name,omitempty"`
		RateLimit    int      `json:"rate_limit_per_hour,omitempty"`
		DailyLimit   int      `json:"daily_limit,omitempty"`
		MonthlyLimit int      `json:"monthly_limit,omitempty"`
		Models       []string `json:"models,omitempty"`
	} `json:"create_key,omitempty"`
}

ApproveUserRequest mirrors handleApproveUser JSON.

type ApproveUserResp added in v0.21.0

type ApproveUserResp struct {
	User        UserResp `json:"user"`
	APIKeyValue string   `json:"api_key_value,omitempty"`
}

ApproveUserResp mirrors handleApproveUser response.

type ArgSpec

type ArgSpec struct {
	Name     string
	Optional bool
	Variadic bool
}

ArgSpec describes one positional argument slot.

type AuditEntry added in v0.21.0

type AuditEntry struct {
	// ID is the row id, usable as a --before-id / --after-id cursor. Zero when
	// talking to a server that predates cursor paging.
	ID            int64     `json:"id,omitempty"`
	Time          time.Time `json:"time"`
	RequestID     string    `json:"request_id"`
	KeyName       string    `json:"key_name"`
	Model         string    `json:"model"`
	Node          string    `json:"node"`
	Status        string    `json:"status"`
	LatencyMs     int       `json:"latency_ms"`
	Cloud         bool      `json:"cloud"`
	CloudModel    string    `json:"cloud_model,omitempty"`
	RoutingReason string    `json:"routing_reason,omitempty"`
}

AuditEntry mirrors internal/audit.Entry - a persisted, filterable request audit row (distinct from SystemAuditEntry, which covers operator actions like drain/agent/runtime, not individual proxied requests).

type AuditFilter added in v0.21.0

type AuditFilter struct {
	Limit  int
	Model  string
	Key    string
	Node   string
	Status string // success | client_error | server_error
	Cloud  *bool
	Since  string // RFC3339
	Until  string // RFC3339
	// BeforeID (older rows) and AfterID (newer rows) are optional, mutually
	// exclusive row-id cursors. Values <= 0 are not sent.
	BeforeID int64
	AfterID  int64
}

AuditFilter mirrors the query params for GET /admin/audit.

type AuditResult added in v0.21.0

type AuditResult struct {
	Entries      []AuditEntry `json:"entries"`
	Total        int          `json:"total"`
	Truncated    bool         `json:"truncated"`
	NextBeforeID int64        `json:"next_before_id,omitempty"`
	PrevAfterID  int64        `json:"prev_after_id,omitempty"`
}

AuditResult mirrors GET /admin/audit's wrapped response shape. NextBeforeID and PrevAfterID are the cursors for the older and newer page; zero means there is none.

type BackupFileInfo added in v0.21.0

type BackupFileInfo struct {
	Name       string    `json:"name"`
	SizeBytes  int64     `json:"size_bytes"`
	ModifiedAt time.Time `json:"modified_at"`
	Compressed bool      `json:"compressed"`
	// Uploaded marks a file an operator uploaded (as opposed to one the
	// scheduler or an on-demand backup made).
	Uploaded bool `json:"uploaded"`
	// Integrity is "ok" (read in full and checked by the server), "unverified"
	// (looks like a backup but has not been read in full) or "invalid".
	Integrity string `json:"integrity"`
}

BackupFileInfo mirrors the admin API's backup list entry.

type BackupOutcome added in v0.25.2

type BackupOutcome struct {
	Result    string `json:"result"`
	AttemptAt string `json:"attempt_at,omitempty"`
	SuccessAt string `json:"success_at,omitempty"`
	Error     string `json:"error,omitempty"`
	// Warning marks a success that needs a look; Note says what happened after
	// the backup was made (for example a download that was cut short).
	Warning string `json:"warning,omitempty"`
	Note    string `json:"note,omitempty"`
}

BackupOutcome is what one source (scheduled or manual) last did.

type BackupRestoreStatus added in v0.25.2

type BackupRestoreStatus struct {
	Result string `json:"result"`
	At     string `json:"at,omitempty"`
	Error  string `json:"error,omitempty"`
	Note   string `json:"note,omitempty"`
	Ref    string `json:"ref,omitempty"`
}

BackupRestoreStatus is the outcome of the last restore.

type BackupStatus added in v0.25.2

type BackupStatus struct {
	LastResult    string `json:"last_result"`
	LastAttemptAt string `json:"last_attempt_at,omitempty"`
	LastSuccessAt string `json:"last_success_at,omitempty"`
	LastError     string `json:"last_error,omitempty"`
	LastSource    string `json:"last_source,omitempty"`

	Scheduled BackupOutcome `json:"scheduled"`
	Manual    BackupOutcome `json:"manual"`

	Running        bool                 `json:"running"`
	DirExists      bool                 `json:"dir_exists"`
	DirWarning     string               `json:"dir_warning,omitempty"`
	StatusNotSaved string               `json:"status_not_saved,omitempty"`
	PruneError     string               `json:"prune_error,omitempty"`
	LeftoverFiles  int                  `json:"leftover_files,omitempty"`
	DirScanError   string               `json:"dir_scan_error,omitempty"`
	LastRestore    *BackupRestoreStatus `json:"last_restore,omitempty"`

	// RunningSince is when the running backup started. ScheduleEnabled and
	// ScheduleIntervalHours are what the scheduler is set to do.
	RunningSince          string `json:"running_since,omitempty"`
	ScheduleEnabled       bool   `json:"schedule_enabled"`
	ScheduleIntervalHours int    `json:"schedule_interval_hours,omitempty"`

	// Notice is a one-off remark (for example that the backup directory was
	// changed); UploadPruneError is the retention problem of the uploads pool.
	Notice           string `json:"notice,omitempty"`
	UploadPruneError string `json:"upload_prune_error,omitempty"`

	// Skipped counts directory entries the server listed by name but could not
	// show (not regular files, or unreadable). It is a top-level field of the
	// response, copied here so callers see it with the rest.
	Skipped int `json:"skipped,omitempty"`
}

BackupStatus mirrors the "status" object of GET /admin/backup/list.

type CLIError

type CLIError struct {
	Code int
	Msg  string
}

CLIError carries the exit code a failure should produce, so cli.go's dispatcher is the only place that translates errors into os.Exit calls.

func (*CLIError) Error

func (e *CLIError) Error() string

type Client

type Client struct {
	BaseURL    string
	Token      string
	HTTPClient *http.Client

	// Warn receives non-fatal warnings (a temporary file that could not be
	// removed, a directory that could not be flushed); nil means standard error.
	Warn io.Writer

	// Username, Role, and ExpiresAt are populated by Login from the
	// /admin/v1/login response body - empty when the client was instead
	// built from a --token flag/env or a saved session (neither of those
	// paths calls Login, and the Admin API has no session-introspection
	// endpoint today to recover identity from a bare token - see the
	// runWhoami doc comment in auth_cmds.go).
	Username  string
	Role      string
	ExpiresAt string
	// contains filtered or unexported fields
}

Client is a thin wrapper over the Admin API's HTTP surface.

func NewClient

func NewClient(baseURL, token string) *Client

NewClient builds a Client for baseURL. token may be empty; Login can be used to obtain one.

func (*Client) AcknowledgeRestoreResult added in v0.25.2

func (c *Client) AcknowledgeRestoreResult(ref string) error

AcknowledgeRestoreResult calls DELETE /admin/backup/restore-result?ref= - clears the remembered outcome of the last restore once the operator has seen it. ref names the result being cleared (as shown by `backup list`); "" means a result that carries no reference and is sent as "-". The server refuses (409) when the stored result is a different one, so a result nobody has seen is never cleared by accident.

func (*Client) ActivePulls added in v0.21.0

func (c *Client) ActivePulls() ([]PullJobSnapshot, error)

ActivePulls calls GET /admin/pulls - every currently-active pull job across the fleet, mirroring the UI's pullProgress.ts tracking. "models pull-progress" (a single node+model) filters this same list client-side rather than following the separate SSE progress stream, per the "one CLI command is exactly one Admin API request" contract.

func (*Client) AddCloudProvider added in v0.21.0

func (c *Client) AddCloudProvider(req CloudProviderRequest) error

AddCloudProvider calls POST /admin/cloud/providers.

func (*Client) AddFavorite added in v0.21.0

func (c *Client) AddFavorite(modelID string) error

AddFavorite calls POST /admin/favorites - stars a model for the calling user.

func (*Client) AddNode added in v0.21.0

func (c *Client) AddNode(req NodeAddRequest) (created bool, err error)

AddNode calls POST /admin/nodes - fleet membership add, mirroring the UI's GPUNodes.tsx "Add Node" action. handleAddNode upserts by name in place, so this can also update an existing node's declared fields; the returned bool reports which happened (201 Created vs 200 OK), matching the server's own isUpdate distinction.

func (*Client) AddRoutingRule added in v0.21.0

func (c *Client) AddRoutingRule(rule RoutingRule) error

AddRoutingRule calls POST /admin/routing/rules.

func (*Client) AnalyticsExport added in v0.21.0

func (c *Client) AnalyticsExport(exportType, format string) (filename string, data []byte, err error)

AnalyticsExport downloads GET /admin/analytics/export?type=X, returning the raw CSV bytes and the server-suggested filename.

func (*Client) AnalyticsSummary added in v0.21.0

func (c *Client) AnalyticsSummary() (json.RawMessage, error)

AnalyticsSummary calls GET /admin/analytics, returning the raw JSON body (hourly analytics + per-model stats - a large, purely-informational dashboard aggregate; see ModelCatalog's doc comment for why this stays raw JSON).

func (*Client) ApproveUser added in v0.21.0

func (c *Client) ApproveUser(id int64, req ApproveUserRequest) (*ApproveUserResp, error)

ApproveUser calls POST /admin/v1/users/{id}/approve (session-authed).

func (*Client) AuditQuery added in v0.21.0

func (c *Client) AuditQuery(f AuditFilter) (*AuditResult, error)

AuditQuery calls GET /admin/audit with the request audit log's own filter set (distinct from SystemAuditFiltered's operator-action filters), mirroring the UI's Requests.tsx audit view.

func (*Client) BackupNow added in v0.21.0

func (c *Client) BackupNow(output string, force bool) (string, int64, error)

BackupNow calls POST /admin/backup - an on-demand backup streamed back as a gzip .db.gz download. The body is streamed to disk (never held in memory) through a temporary file that is moved into place only when the transfer completed, so a cut connection never leaves a plausible-looking short file. output empty means the server-suggested name in the current directory. An existing file is never replaced unless force is set. Returns the final path and the number of bytes written.

func (*Client) BenchmarkProgress added in v0.21.0

func (c *Client) BenchmarkProgress(jobID string) (json.RawMessage, error)

BenchmarkProgress calls GET /admin/benchmark/{id}/progress - a point-in-time snapshot from the SSE progress stream's underlying data, not a live follow (see ActivePulls' doc comment for the same one-request rationale). The endpoint itself is SSE-only, so this reads the first event off the stream and returns its raw JSON payload.

func (*Client) BenchmarkRuns added in v0.21.0

func (c *Client) BenchmarkRuns() (json.RawMessage, error)

BenchmarkRuns calls GET /admin/benchmark/runs, returning the raw JSON {"runs":[...]} body - store.BenchmarkRun has many percentile/TPOT fields, kept as raw JSON rather than mirrored (see ModelCatalog's doc comment).

func (*Client) CancelBenchmark added in v0.21.0

func (c *Client) CancelBenchmark(jobID string) (cancelled bool, err error)

CancelBenchmark calls DELETE /admin/benchmark/{id}.

func (*Client) CancelPull added in v0.21.0

func (c *Client) CancelPull(node, model string) (cancelled bool, err error)

CancelPull calls DELETE /admin/nodes/{name}/pull?model=X - cancels an in-flight pull.

func (*Client) ChangePassword added in v0.21.0

func (c *Client) ChangePassword(currentPassword, newPassword string) error

ChangePassword calls POST /change-password (session-role-agnostic, same route choice as Logout's doc comment explains). currentPassword may be empty only on a forced first-login change (MustChangePassword=true) - the server itself enforces that, not this client. The endpoint invalidates every existing session for the user and issues a fresh one, so this updates c.Token in place from the response's Set-Cookie, mirroring Login.

func (*Client) ClearNodeControl added in v0.21.0

func (c *Client) ClearNodeControl(node string) error

ClearNodeControl calls DELETE /admin/nodes/{name}/control - clears the accepted control driver config.

func (*Client) CloudBudgetStatus added in v0.21.0

func (c *Client) CloudBudgetStatus() (*CloudBudgetStatus, error)

CloudBudgetStatus calls GET /admin/cloud-budget-status.

func (*Client) CloudProviders added in v0.21.0

func (c *Client) CloudProviders() ([]CloudProvider, error)

CloudProviders calls GET /admin/cloud/providers.

func (*Client) ConfigReload added in v0.21.0

func (c *Client) ConfigReload() (*ConfigReloadResult, error)

ConfigReload calls POST /admin/config/reload - re-syncs live router/auth state from SQLite.

func (*Client) CreateKey added in v0.21.0

func (c *Client) CreateKey(req KeyCreateRequest) (*KeyResp, error)

CreateKey calls POST /admin/v1/keys (session-authed).

func (*Client) CreateSchedule added in v0.21.0

func (c *Client) CreateSchedule(req ScheduleCreateRequest) (*Schedule, error)

CreateSchedule calls POST /admin/schedules.

func (*Client) CreateUser added in v0.21.0

func (c *Client) CreateUser(req CreateUserRequest) (*CreateUserResp, error)

CreateUser calls POST /admin/v1/users (session-authed).

func (*Client) DeleteBackup added in v0.25.2

func (c *Client) DeleteBackup(name string) error

DeleteBackup calls DELETE /admin/backup?name= - removes one stored backup file (destructive; the caller confirms with the operator first).

func (*Client) DeleteCloudProvider added in v0.21.0

func (c *Client) DeleteCloudProvider(name string) error

DeleteCloudProvider calls DELETE /admin/cloud/providers/{name}.

func (*Client) DeleteModelAlias added in v0.22.0

func (c *Client) DeleteModelAlias(alias string) error

DeleteModelAlias calls DELETE /admin/model-aliases?alias=X.

func (*Client) DeleteModelConfig added in v0.21.0

func (c *Client) DeleteModelConfig(model, node string) error

DeleteModelConfig calls DELETE /admin/model-config?model=X&node=Y.

func (*Client) DeleteNode added in v0.21.0

func (c *Client) DeleteNode(name string) error

DeleteNode calls DELETE /admin/nodes/{name} - fleet membership remove (cascades marbor_agent + warmup settings server-side, see handleRemoveNode), mirroring the UI's GPUNodes.tsx "Remove" action.

func (*Client) DeleteNodeModel

func (c *Client) DeleteNodeModel(node, model string) (*NodeDeleteModelResult, error)

DeleteNodeModel calls DELETE /admin/nodes/{name}/models/{model} - capability "models.delete", mirroring the UI's Models.tsx delete action.

Deliberately bypasses doRequestBody (unlike every other mutating Client method): a replica-wide delete's 409/502 response body itself carries structured per-member detail (Members/Results) a caller may want, but doRequestBody's shared >=400 branch reads and discards the body before any caller can see it - fine for every other endpoint, where the body is just a flat error string, but it would make this endpoint's structured detail permanently unreachable through the CLI. 401/403 classification is still replicated here (same authErrorf + savedSessionHint as doRequestBody) so an expired session behaves identically to every other command.

func (*Client) DeleteSchedule added in v0.21.0

func (c *Client) DeleteSchedule(id string) error

DeleteSchedule calls DELETE /admin/schedules/{id}.

func (*Client) DeleteUser added in v0.21.0

func (c *Client) DeleteUser(id int64) error

DeleteUser calls DELETE /admin/v1/users/{id} (session-authed).

func (*Client) DisableMarborAgent added in v0.21.0

func (c *Client) DisableMarborAgent(node string) error

DisableMarborAgent calls DELETE /admin/nodes/{name}/agent.

func (*Client) DownloadBackup added in v0.25.2

func (c *Client) DownloadBackup(name, output string, force bool) (string, int64, error)

DownloadBackup calls GET /admin/backup/download?name= - streams a backup already stored on the server to a local file, same safe write as BackupNow.

func (*Client) DrainNode

func (c *Client) DrainNode(node, reason string, graceSeconds int, force bool) (*DrainResult, error)

DrainNode calls POST /admin/nodes/{name}/drain - marks a node as draining (marbor-internal routing state; never sent to the Marbor Agent), mirroring the UI's GPUNodes.tsx "Drain" action. graceSeconds < 0 means "not set" (absent from the request body - infinite drain, today's frozen default). force sends force=true, which a drain needs when the node is the only server of a model.

func (*Client) EnableMarborAgent added in v0.21.0

func (c *Client) EnableMarborAgent(node string, port int, scheme string) (*MarborAgentEnableResult, error)

EnableMarborAgent calls POST /admin/nodes/{name}/agent - enables or reconfigures the marbor agent for a node. scheme empty means "keep the host's existing scheme, or http on first enable" (see handler doc).

func (*Client) ExplainRequest

func (c *Client) ExplainRequest(id string) (*RoutingDecision, error)

ExplainRequest calls GET /admin/v1/requests/{id}/explain, returning the full routing explanation for one request id.

func (*Client) Favorites added in v0.21.0

func (c *Client) Favorites() ([]string, error)

Favorites calls GET /admin/favorites - the calling user's starred model ids.

func (*Client) GetMarborAgent added in v0.21.0

func (c *Client) GetMarborAgent(node string) (*MarborAgentInfo, error)

GetMarborAgent calls GET /admin/nodes/{name}/agent.

func (*Client) GetModelConfig added in v0.21.0

func (c *Client) GetModelConfig(model, node string) (json.RawMessage, error)

GetModelConfig calls GET /admin/model-config?model=X&node=Y, returning the raw JSON body (store.ModelConfig has ~40 optional per-runtime sampling/ load-time fields - see internal/store/store.go - kept as raw JSON here rather than mirrored field-by-field into a CLI-local type, matching this method's read-only "pass through what the server sent" role; SetModelConfig takes the same raw-JSON shape for writes, deliberately not exposing 40 individual flags).

func (*Client) GetNodeWarmup added in v0.21.0

func (c *Client) GetNodeWarmup(node string) (*NodeWarmupInfo, error)

GetNodeWarmup calls GET /admin/nodes/{name}/warmup.

func (*Client) GetPinned added in v0.21.0

func (c *Client) GetPinned(node string) ([]string, error)

GetPinned calls GET /admin/nodes/{name}/pinned - the node's never-evict model list.

func (*Client) GetWarmupStatus added in v0.21.0

func (c *Client) GetWarmupStatus() (*WarmupStatus, error)

GetWarmupStatus calls GET /admin/warmup - global warmup engine status.

func (*Client) Health

func (c *Client) Health() (*HealthResp, error)

Health calls GET /health (unauthenticated).

func (*Client) HealthCheck

func (c *Client) HealthCheck(node string) (*HealthCheckResult, error)

HealthCheck calls GET /admin/nodes/{name}/health-check - mirroring the UI's GPUNodes.tsx checkNodeHealth action. A populated result with OK=false is a successful probe reporting a down runtime, not a request failure - only a transport/dispatch error returns a non-nil error.

func (*Client) ListBackups added in v0.21.0

func (c *Client) ListBackups() ([]BackupFileInfo, BackupStatus, error)

ListBackups calls GET /admin/backup/list.

func (*Client) ListKeys added in v0.21.0

func (c *Client) ListKeys() ([]KeyResp, error)

ListKeys calls GET /admin/v1/keys (session-authed).

func (*Client) ListModelAliases added in v0.22.0

func (c *Client) ListModelAliases() ([]ModelAlias, error)

ListModelAliases calls GET /admin/model-aliases.

func (*Client) ListModelConfigs added in v0.21.0

func (c *Client) ListModelConfigs() (json.RawMessage, error)

ListModelConfigs calls GET /admin/model-configs, returning the raw {"configs":[...]} JSON body (see GetModelConfig's doc comment for why this package keeps ModelConfig as raw JSON rather than a mirrored type).

func (*Client) ListSchedules added in v0.21.0

func (c *Client) ListSchedules() ([]Schedule, error)

ListSchedules calls GET /admin/schedules.

func (*Client) ListUsers added in v0.21.0

func (c *Client) ListUsers() ([]UserResp, error)

ListUsers calls GET /admin/v1/users (session-authed).

func (*Client) LiveRequests added in v0.21.0

func (c *Client) LiveRequests() ([]LiveRequestEntry, error)

LiveRequests calls GET /admin/requests/live - the same bounded in-memory ring as Requests, in its raw (non-dashboard-formatted) shape, mirroring the UI's live-updating request widget.

func (*Client) Login

func (c *Client) Login(username, password string) error

Login calls POST /admin/v1/login with username/password and captures the session token from the Set-Cookie response (the token is never echoed in the JSON body - admin.go:handleLoginForRole only sets it via cookie). On success it also stores the token on the Client for subsequent calls.

func (*Client) Logout

func (c *Client) Logout() error

Logout calls POST /logout to end the current session server-side. It uses the role-agnostic "/logout" route (sessionAuth, any valid session) rather than the admin-only "/admin/logout", since a CLI session may belong to any authenticated role, not just admin - "/admin/v1/logout" does not exist as a registered route (only "/admin/logout" and "/logout" do; see admin.go's mux registration), so this is the closest real endpoint that identifies and invalidates the bearer token's session the way logout needs. Deliberately just another doRequestBody call, classified the same as every other mutating call - the caller (runLogout) is what treats any error here as a soft, non-fatal warning, not this method.

func (*Client) MetricsSummary added in v0.21.0

func (c *Client) MetricsSummary() (*MetricsSummary, error)

MetricsSummary calls GET /admin/metrics/summary - the dashboard's top summary strip (nodes online, active requests, latency, tokens/min).

func (*Client) ModelCatalog added in v0.21.0

func (c *Client) ModelCatalog() (json.RawMessage, error)

ModelCatalog calls GET /admin/models/catalog, returning the raw JSON body - a nested {"catalog":[...],"nodes":[...]} shape (fleet-aware HF/local model catalog with per-node fit and downloaded-status data). Kept as raw JSON rather than mirrored field-by-field, same rationale as GetModelConfig: a large, purely-informational discovery response where a hand-mirrored type would only need updating every time the browsing UI gains a field.

func (*Client) ModelConfigCapabilities added in v0.21.0

func (c *Client) ModelConfigCapabilities() (map[string][]string, error)

ModelConfigCapabilities calls GET /admin/model-config/capabilities - per-runtime list of which ModelConfig fields actually take effect.

func (*Client) ModelFit added in v0.21.0

func (c *Client) ModelFit() ([]NodeFitEntry, error)

ModelFit calls GET /admin/nodes/model-fit - per-node VRAM fit analysis for models.

func (*Client) ModelRepo added in v0.21.0

func (c *Client) ModelRepo(opts ModelRepoOpts) (json.RawMessage, error)

ModelRepo calls GET /admin/models/repo, returning the raw JSON repo detail (see ModelCatalog's doc comment for why this stays raw JSON).

func (*Client) ModelSearch added in v0.21.0

func (c *Client) ModelSearch(opts ModelSearchOpts) (json.RawMessage, error)

ModelSearch calls GET /admin/models/search, returning the raw JSON array of Hugging Face search results (see ModelCatalog's doc comment for why this stays raw JSON).

func (*Client) Models

func (c *Client) Models() (*ModelsResp, error)

Models calls GET /admin/v1/models (session-authed).

func (*Client) NodeControlAccept

func (c *Client) NodeControlAccept(node, driver, identifier, startCommand string) error

NodeControlAccept calls POST /admin/nodes/{name}/control/accept - the operator's explicit confirmation of a discovered (or manually typed) control driver + identifier. startCommand is only meaningful for the Process driver's Start action; pass "" for every other driver.

func (*Client) NodeControlProbe

func (c *Client) NodeControlProbe(node string) (*NodeControlInfo, error)

NodeControlProbe calls GET /admin/nodes/{name}/control - a read, so it uses doRequest's GET path rather than doRequestBody.

func (*Client) NodeModels

func (c *Client) NodeModels(node string) ([]NodeModelEntry, error)

NodeModels calls GET /admin/nodes/{name}/models - capability "models.list", the per-node local inventory (as opposed to Models(), the fleet-wide summary).

func (*Client) NodeTLSProbe added in v0.21.0

func (c *Client) NodeTLSProbe(name string) (string, error)

NodeTLSProbe calls POST /admin/nodes/{name}/tls-probe - reads the node's Marbor Agent TLS certificate fingerprint WITHOUT pinning it (see handleNodeTLSProbe's doc comment: TOFU read only, no trust decision made). Pinning only happens via a subsequent "nodes patch" (clear) or "nodes confirm-tls" (set) call with the fingerprint the operator confirms out of band against this result.

func (*Client) Nodes

func (c *Client) Nodes() ([]NodeResp, error)

Nodes calls GET /admin/v1/nodes (session-authed).

func (*Client) NodesFiltered added in v0.25.1

func (c *Client) NodesFiltered(signals, search string) ([]NodeResp, error)

NodesFiltered calls GET /admin/v1/nodes with the server-side filter parameters: signals is a comma list (any match keeps a node) and search is a case-insensitive substring of the node name or GPU model. Empty values are not sent, so an unfiltered call is the plain list request.

func (*Client) PatchKey added in v0.21.0

func (c *Client) PatchKey(name string, patch KeyPatch) error

PatchKey calls PATCH /admin/v1/keys/{name} (session-authed) with a full patch.

func (*Client) PatchKeyAllowLocalDegradation

func (c *Client) PatchKeyAllowLocalDegradation(name string, allow bool) error

PatchKeyAllowLocalDegradation calls PATCH /admin/v1/keys/{name} with allow_local_degradation, the per-key policy gate on whether this key may be substituted with an operator-declared local alternate model - matches auth.KeyPatch's snake_case JSON tag, same as PatchKeyLocalOnly.

func (*Client) PatchKeyLocalOnly

func (c *Client) PatchKeyLocalOnly(name string, localOnly bool) error

PatchKeyLocalOnly calls PATCH /admin/v1/keys/{name} with local_only (the fail-closed policy toggle) - matches auth.KeyPatch's snake_case JSON tag (handlePatchKey decodes into that struct, unlike handleAddKey which decodes into config.KeyConfig's camelCase tags).

func (*Client) PatchNodeFields added in v0.21.0

func (c *Client) PatchNodeFields(name string, f NodePatchFields) error

PatchNodeFields is the visited-aware variant for `marbor nodes patch` - sends every visited field in ONE PATCH request/body, matching how handlePatchNode already applies them together atomically server-side. Splitting these into separate sequential requests would reopen a partial-failure window the single-PATCH admin handler doesn't have (code review finding).

func (*Client) PatchNodeTLSFingerprint

func (c *Client) PatchNodeTLSFingerprint(name, fingerprint string) error

PatchNodeTLSFingerprint calls PATCH /admin/v1/nodes/{name} with tls_fingerprint (headless enrollment confirmation) - matches router.NodePatch's snake_case JSON tag. fingerprint must be supplied by the caller (ultimately the operator, via the CLI's --fingerprint flag) - this method never probes or infers a value itself.

func (*Client) PatchSchedule added in v0.21.0

func (c *Client) PatchSchedule(id string, patch SchedulePatch) (*Schedule, error)

PatchSchedule calls PATCH /admin/schedules/{id}.

func (*Client) PatchUser added in v0.21.0

func (c *Client) PatchUser(id int64, req PatchUserRequest) (*UserResp, error)

PatchUser calls PATCH /admin/v1/users/{id} (session-authed).

func (*Client) PendingUserCount added in v0.21.0

func (c *Client) PendingUserCount() (int, error)

PendingUserCount calls GET /admin/v1/users/pending-count.

func (*Client) PredictiveDecisions

func (c *Client) PredictiveDecisions() ([]PredictiveDecision, error)

PredictiveDecisions calls GET /admin/predictive/decisions.

func (*Client) PrefixLocalityStats added in v0.24.1

func (c *Client) PrefixLocalityStats() (*PrefixLocalityStats, error)

PrefixLocalityStats calls GET /admin/prefix-locality/stats.

func (*Client) PullModel

func (c *Client) PullModel(node, model string) (*PullResult, error)

PullModel calls POST /admin/nodes/{name}/pull - starts an async model pull, mirroring the UI's Models.tsx pull flow. Like the UI, this does not block for completion; the caller should poll `models list` or watch the dashboard's pull progress for the terminal outcome.

func (*Client) RegenerateMarborAgentToken added in v0.21.0

func (c *Client) RegenerateMarborAgentToken(node string) (*MarborAgentEnableResult, error)

RegenerateMarborAgentToken calls POST /admin/nodes/{name}/agent/regenerate.

func (*Client) RemoveFavorite added in v0.21.0

func (c *Client) RemoveFavorite(modelID string) error

RemoveFavorite calls DELETE /admin/favorites/{modelId} - unstars a model.

func (*Client) RemoveRoutingRule added in v0.21.0

func (c *Client) RemoveRoutingRule(id string) error

RemoveRoutingRule calls DELETE /admin/routing/rules/{id}.

func (*Client) ReorderCloudProviders added in v0.21.0

func (c *Client) ReorderCloudProviders(order []string) error

ReorderCloudProviders calls PUT /admin/cloud/providers/reorder.

func (*Client) ReplicaSuggestions added in v0.24.0

func (c *Client) ReplicaSuggestions(includeDismissed bool) (ReplicaSuggestionsResponse, error)

ReplicaSuggestions calls GET /admin/v1/replica-suggestions.

func (*Client) Requests added in v0.21.0

func (c *Client) Requests() ([]RequestEntry, error)

Requests calls GET /admin/requests - the full in-memory request log ring, newest first, mirroring the UI's Dashboard.tsx/Requests.tsx table.

func (*Client) ResetUserPassword added in v0.21.0

func (c *Client) ResetUserPassword(id int64) (string, error)

ResetUserPassword calls POST /admin/v1/users/{id}/reset-password (session-authed).

func (*Client) RestoreBackup added in v0.21.0

func (c *Client) RestoreBackup(filename string) (string, error)

RestoreBackup calls POST /admin/backup/restore - restarts marbor onto the named backup file (destructive; the caller is responsible for confirming with the operator first). It returns the correlation reference the server gave the restore (empty if the server sent none, or one that is not a plain reference).

func (*Client) RevokeKey added in v0.21.0

func (c *Client) RevokeKey(name string) error

RevokeKey calls DELETE /admin/v1/keys/{name} (session-authed).

func (*Client) RoutingRules added in v0.21.0

func (c *Client) RoutingRules() ([]RoutingRule, error)

RoutingRules calls GET /admin/routing/rules.

func (*Client) RoutingStrategy added in v0.21.0

func (c *Client) RoutingStrategy() (string, error)

RoutingStrategy calls GET /admin/routing/strategy.

func (*Client) RunBenchmark added in v0.21.0

func (c *Client) RunBenchmark(node, model string, n int) (jobID string, err error)

RunBenchmark calls POST /admin/benchmark/run - starts a hardware benchmark job, returning its job id.

func (*Client) RuntimeAction

func (c *Client) RuntimeAction(node, action string, acknowledgeReplica, force bool) (*RuntimeActionResult, error)

RuntimeAction calls POST /admin/nodes/{name}/runtime/{action} (action is "start", "stop", or "restart") - the CLI's first mutating command, mirroring the Admin API's own dispatch-to-agent contract exactly (no business logic lives in the CLI). acknowledgeReplica sends acknowledge_replica=true, which the server requires for a stop or restart on a multi-host replica head, worker or unresolved member. force sends force=true, which a restart needs when it would leave a model with no other node able to serve it. The returned Replica is nil for a standalone node.

func (*Client) RuntimeLogs

func (c *Client) RuntimeLogs(node string, lines int) ([]string, error)

RuntimeLogs calls POST /admin/nodes/{name}/runtime/logs?lines=N - a pure read, still a POST since marbor injects driver/identifier into the agent-side request body, same as start/stop/restart. lines<=0 means "use the server-side default" - omitted from the query string.

func (*Client) Savings added in v0.21.0

func (c *Client) Savings() (*CloudSavings, error)

Savings calls GET /admin/metrics/savings.

func (*Client) SetModelAlias added in v0.22.0

func (c *Client) SetModelAlias(alias, target string) (ModelAlias, error)

SetModelAlias calls PUT /admin/model-aliases with {alias, target}. A 400 (invalid or chained alias) is reported as a user error with the server's own message.

func (*Client) SetModelConfig added in v0.21.0

func (c *Client) SetModelConfig(rawBody json.RawMessage) (json.RawMessage, error)

SetModelConfig calls PUT /admin/model-config with a raw JSON body (the full store.ModelConfig shape - model+node required, every other field is forwarded as-is; see GetModelConfig's doc comment for why this stays raw JSON instead of ~40 individual flags).

func (*Client) SetNodePrewarm added in v0.21.0

func (c *Client) SetNodePrewarm(node string, disabled bool) error

SetNodePrewarm calls POST /admin/nodes/{name}/prewarm - disables/re-enables predictive prewarm for one node.

func (*Client) SetNodeWarmup added in v0.21.0

func (c *Client) SetNodeWarmup(node string, enabled bool, models []string) (*NodeWarmupInfo, error)

SetNodeWarmup calls PUT /admin/nodes/{name}/warmup.

func (*Client) SetPinned added in v0.21.0

func (c *Client) SetPinned(node string, models []string) ([]string, error)

SetPinned calls PUT /admin/nodes/{name}/pinned (whole-list replace).

func (*Client) SetPredictiveEngine added in v0.21.0

func (c *Client) SetPredictiveEngine(enabled bool) error

SetPredictiveEngine calls PUT /admin/warmup/predictive.

func (*Client) SetRoutingStrategy added in v0.21.0

func (c *Client) SetRoutingStrategy(strategy string) error

SetRoutingStrategy calls PUT /admin/routing/strategy.

func (*Client) Settings added in v0.21.0

func (c *Client) Settings() (json.RawMessage, error)

Settings calls GET /admin/settings, returning the raw JSON body - the full control-plane config.Config struct with secret fields masked as "***" (see handleSettings). Stays raw JSON rather than a mirrored client-side struct: config.Config is large and changes shape often, and the CLI has no independent business logic over its fields (same rationale as SystemInfo/ModelCatalog).

func (*Client) SkipPasswordChange added in v0.21.0

func (c *Client) SkipPasswordChange() error

SkipPasswordChange calls POST /skip-password-change - dismisses the forced-password-change prompt for this session only, up to maxSkipPasswordChanges times server-side. Also rotates the session token.

func (*Client) SoleReplica added in v0.25.1

func (c *Client) SoleReplica(node string) (*SoleReplicaImpact, error)

SoleReplica calls GET /admin/nodes/{name}/sole-replica - the read-only check a drain or runtime restart runs before changing anything.

func (*Client) SpillCounters

func (c *Client) SpillCounters() ([]SpillCounterRow, error)

SpillCounters calls GET /admin/v1/spill, returning every (key_name, served_by) row fleet-wide.

func (*Client) SuspendUser added in v0.21.0

func (c *Client) SuspendUser(id int64) error

SuspendUser calls POST /admin/v1/users/{id}/suspend (session-authed).

func (*Client) SystemAudit

func (c *Client) SystemAudit(limit int) ([]SystemAuditEntry, error)

SystemAudit calls GET /admin/system-audit?limit=N. N <=0 uses server default.

func (*Client) SystemAuditFiltered added in v0.21.0

func (c *Client) SystemAuditFiltered(f SystemAuditFilter) ([]SystemAuditEntry, error)

SystemAuditFiltered calls GET /admin/system-audit with enterprise filters.

func (*Client) SystemInfo added in v0.21.0

func (c *Client) SystemInfo() (json.RawMessage, error)

SystemInfo calls GET /admin/system-info, returning the raw JSON body - control-plane host system info plus per-node GPU summary (see ModelCatalog's doc comment for why this stays raw JSON).

func (*Client) TestCloudProvider added in v0.21.0

func (c *Client) TestCloudProvider(provider, baseURL, apiKey string) error

TestCloudProvider calls POST /admin/cloud/providers/test - verifies a base_url+api_key pair authenticates against the provider before saving. The api_key is sent once, on the wire, for this one-shot probe only - it is never persisted or echoed back by this call.

func (*Client) ToggleRoutingRule added in v0.21.0

func (c *Client) ToggleRoutingRule(id string) error

ToggleRoutingRule calls PUT /admin/routing/rules/{id}/toggle.

func (*Client) UndrainNode

func (c *Client) UndrainNode(node string) (*DrainResult, error)

UndrainNode calls DELETE /admin/nodes/{name}/drain - reverses DrainNode, mirroring the UI's GPUNodes.tsx "Undrain" action.

func (*Client) UnloadModel

func (c *Client) UnloadModel(node, model string) error

UnloadModel calls POST /admin/nodes/{name}/unload - evicts a model from a node's warm state, mirroring the UI's GPUNodes.tsx card action.

func (*Client) UpdateCloudProvider added in v0.21.0

func (c *Client) UpdateCloudProvider(name string, req CloudProviderRequest) error

UpdateCloudProvider calls PUT /admin/cloud/providers/{name}.

func (*Client) UpdateSettings added in v0.21.0

func (c *Client) UpdateSettings(body json.RawMessage) error

UpdateSettings calls PUT /admin/settings with a raw JSON body - a (typically partial) config.Config payload, merged server-side onto the current config (handleUpdateSettings). Passing back a "***" mask value for a secret field the caller didn't intend to change preserves the real stored secret (server-side mask-preserve behavior).

func (*Client) UploadBackup added in v0.21.0

func (c *Client) UploadBackup(filename string, r io.Reader, size int64) (string, error)

UploadBackup calls POST /admin/backup/upload with r's content as a multipart/form-data "file" field, mirroring the UI's Settings.tsx upload picker. Only the base name of filename is sent (informational to the server, which names the stored file itself). A failure reading the local file is reported as such, and an upload that stops making progress is abandoned after uploadIdleTimeout. size is the file's length (0 when unknown) and sizes the wait for the server's verdict. The returned warning is the server's note about a saved file that needs a look ("" when there is none).

func (*Client) WarmupPing added in v0.21.0

func (c *Client) WarmupPing() error

WarmupPing calls POST /admin/warmup/ping - manually triggers a warmup cycle.

type CloudBudgetEntry added in v0.21.0

type CloudBudgetEntry struct {
	Name         string  `json:"name,omitempty"`
	DailySpent   float64 `json:"dailySpent"`
	DailyCap     float64 `json:"dailyCap"`
	DailyPct     float64 `json:"dailyPct"`
	MonthlySpent float64 `json:"monthlySpent"`
	MonthlyCap   float64 `json:"monthlyCap"`
	MonthlyPct   float64 `json:"monthlyPct"`
}

CloudBudgetEntry mirrors admin.go's BudgetEntry.

type CloudBudgetStatus added in v0.21.0

type CloudBudgetStatus struct {
	SoftBudgetPct float64            `json:"softBudgetPct"`
	Global        CloudBudgetEntry   `json:"global"`
	PerKey        []CloudBudgetEntry `json:"perKey"`
}

CloudBudgetStatus mirrors admin.go's CloudBudgetStatusResp.

type CloudProvider added in v0.21.0

type CloudProvider struct {
	Name            string  `json:"name"`
	Provider        string  `json:"provider"`
	BaseURL         string  `json:"base_url"`
	DefaultModel    string  `json:"default_model"`
	CostPer1KTokens float64 `json:"cost_per_1k_tokens"`
	Enabled         bool    `json:"enabled"`
	Priority        int     `json:"priority"`
}

CloudProvider mirrors handleCloudProviders' response shape (GET /admin/cloud/providers) - the API key itself is NEVER returned by the server, so this type deliberately has no APIKey field.

type CloudProviderRequest added in v0.21.0

type CloudProviderRequest struct {
	Name            string  `json:"name"`
	Provider        string  `json:"provider"`
	BaseURL         string  `json:"base_url"`
	APIKey          string  `json:"api_key,omitempty"`
	DefaultModel    string  `json:"default_model,omitempty"`
	CostPer1KTokens float64 `json:"cost_per_1k_tokens,omitempty"`
	Enabled         bool    `json:"enabled"`
	Priority        int     `json:"priority,omitempty"`
}

CloudProviderRequest is the body for POST /admin/cloud/providers and PUT /admin/cloud/providers/{name}. APIKey is write-only: pass "" on an update to leave the currently stored key unchanged (handleUpdateCloudProvider preserves the existing value for both "" and the UI's "***" placeholder - never round-trip the real secret through a read).

type CloudSavings added in v0.21.0

type CloudSavings struct {
	LocalRequests int64    `json:"local_requests"`
	CloudRequests int64    `json:"cloud_requests"`
	TotalRequests int64    `json:"total_requests"`
	CloudSpentUSD *float64 `json:"cloud_spent_usd"`
	SavedUSD      *float64 `json:"saved_usd"`
	Since         string   `json:"since"` // process start time, not a counting window; the totals are all time
}

CloudSavings mirrors GET /admin/metrics/savings' response shape. CloudSpentUSD and SavedUSD are nullable pointers because the server sends JSON null (not 0.0) when requests exist but no token data was ever parsed - a non-pointer float64 would silently decode that null as a fabricated $0.00.

type ColdLoadModel added in v0.25.1

type ColdLoadModel struct {
	Model   string   `json:"model"`
	Runtime string   `json:"runtime"`
	Peers   []string `json:"peers"`
}

ColdLoadModel is a model only an Ollama peer could load on demand.

type Command

type Command struct {
	Name    string
	Aliases []string

	Short  string // one line, used in parent's command table and man
	Long   string // optional paragraph for man/--help
	Footer string // optional trailing note (e.g. auth requirement callout)

	Args  []ArgSpec
	Flags []FlagSpec
	Sub   []*Command

	Run RunFunc

	Hidden    bool // omitted from the root command table, still reachable
	NeedsAuth bool

	Examples []string
	// contains filtered or unexported fields
}

Command is a node in the CLI command tree. Metadata is data, not code, so the dispatcher, help writer, completion writer, man generator, and main.go's command whitelist can all derive from the same declaration instead of drifting independently (see plan context).

func Root

func Root() *Command

Root returns the full CLI command tree (registry_tree.go's root()), built exactly once. Exported so a different package - cmd/gen-docs, which generates man pages/docs/cli.md/the README CLI table and cannot call the unexported root() - can walk the same tree the dispatcher and help writer use, with parent pointers already set by finalize (so Path() and UsageLine() work correctly on every node reached from here).

func (*Command) MaxArgs

func (c *Command) MaxArgs() int

MaxArgs returns the maximum number of positionals, or -1 if the last ArgSpec is variadic (unbounded).

func (*Command) MinArgs

func (c *Command) MinArgs() int

MinArgs returns the number of required positionals - the count of leading ArgSpecs with Optional == false. Derived, not stored, so it can never disagree with Args.

func (*Command) Path

func (c *Command) Path() string

Path walks the parent chain and returns the full invocation path, e.g. "marbor models pull". Requires finalize to have run first (parent pointers set); before that it returns just c.Name. The root command's own Name ("marbor") supplies the leading token - callers must not also prepend it.

func (*Command) UsageLine

func (c *Command) UsageLine() string

UsageLine renders a one-line "usage: <path> <args> [flags]" string from Args, matching the hand-written usage strings already used throughout cli.go (e.g. "usage: marbor models pull <node> <model> [flags]").

type ConfigReloadResult added in v0.21.0

type ConfigReloadResult struct {
	Reloaded       bool `json:"reloaded"`
	AuthKeys       int  `json:"auth_keys"`
	NodesAdded     int  `json:"nodes_added"`
	NodesRemoved   int  `json:"nodes_removed"`
	CloudProviders int  `json:"cloud_providers"`
}

ConfigReloadResult mirrors POST /admin/config/reload's response shape.

type CreateUserRequest added in v0.21.0

type CreateUserRequest struct {
	Username string `json:"username"`
	Email    string `json:"email,omitempty"`
	Role     string `json:"role,omitempty"`
}

CreateUserRequest mirrors handleCreateUser JSON.

type CreateUserResp added in v0.21.0

type CreateUserResp struct {
	UserResp
	InitialPassword string `json:"initial_password"`
}

CreateUserResp mirrors handleCreateUser 201 response: flat User plus initial_password.

type DrainResult

type DrainResult struct {
	Node               string `json:"node"`
	Draining           bool   `json:"draining"`
	Reason             string `json:"reason,omitempty"`
	GracePeriodSeconds int    `json:"grace_period_seconds,omitempty"`
	// Replica is set when the drained node is a multi-host replica head,
	// worker or unresolved member; its Warning states what the drain does.
	Replica *ReplicaInfo `json:"replica,omitempty"`
	// SoleReplica lists models the drain took out of service, or that could not
	// be checked. Nil when there was nothing to report.
	SoleReplica *SoleReplicaBody `json:"sole_replica,omitempty"`
}

DrainResult mirrors handleDrainNode/handleUndrainNode's response body.

type ExcludedCandidate added in v0.21.0

type ExcludedCandidate struct {
	Node   string `json:"node"`
	Reason string `json:"reason"`
}

ExcludedCandidate mirrors router.ExcludedCandidate. Reason is the machine-readable identifier from the Admin API (unhealthy, draining, runtime_mismatch, ineligible_model, over_capacity, insufficient_gpu_group, replica_worker, replica_unresolved, replica_member_unreachable) - excludedReasonText (requests.go) translates it for display.

type FlagKind

type FlagKind int

FlagKind identifies the Go type backing a FlagSpec.

const (
	FlagString FlagKind = iota
	FlagBool
	FlagInt
)

type FlagSpec

type FlagSpec struct {
	Name  string
	Kind  FlagKind
	Usage string

	DefString string
	DefInt    int
	DefBool   bool

	// Repeatable lets a FlagString be given more than once; the values are
	// joined with commas, so "--x a --x b" and "--x a,b" read the same.
	// FlagString only (DefString is ignored), and unsuitable for values that
	// themselves contain commas.
	Repeatable bool

	// Required, if true, means the dispatcher must reject a run where this
	// flag was left at its zero value. RequiredMsg is the exact message to
	// print (e.g. "error: --driver and --identifier are required") - kept
	// as a single message per group of required flags rather than derived,
	// because today's wording spans multiple flags in one sentence (node
	// control accept) and must not silently reformat into something no
	// existing test or user expects.
	Required    bool
	RequiredMsg string

	// Hidden omits the flag from generated help/man output while still
	// accepting it on the command line (no current flag needs this; it
	// exists so a future internal/debug flag doesn't have to touch this
	// type again).
	Hidden bool
}

FlagSpec describes one command-specific flag. Global flags (--server, --json, --username, --password) are not represented here - they are added by the dispatcher via newFlagSet for every command.

type HealthCheckResult

type HealthCheckResult struct {
	OK        bool   `json:"ok"`
	Error     string `json:"error,omitempty"`
	LatencyMs int64  `json:"latencyMs"`
}

HealthCheckResult mirrors admin.go's nodeHealthCheckResult - an on-demand active liveness probe result, capability "runtime.health_check".

type HealthResp

type HealthResp struct {
	Status        string `json:"status"`
	Version       string `json:"version"`
	ProxyPort     int    `json:"proxy_port"`
	UptimeSeconds int    `json:"uptime_seconds"`
	// StartedAt identifies this run of the process; it changes on every restart.
	StartedAt string `json:"started_at,omitempty"`
	Nodes     struct {
		Total   int `json:"total"`
		Healthy int `json:"healthy"`
	} `json:"nodes"`
}

HealthResp mirrors GET /health's response shape (admin.go handleHealth).

type KeyCreateRequest added in v0.21.0

type KeyCreateRequest struct {
	Name                  string   `json:"name"`
	Key                   string   `json:"key,omitempty"`
	RateLimit             int      `json:"rateLimit,omitempty"`
	DailyLimit            int      `json:"dailyLimit,omitempty"`
	MonthlyLimit          int      `json:"monthlyLimit,omitempty"`
	DailyUsdCap           float64  `json:"dailyUsdCap,omitempty"`
	MonthlyUsdCap         float64  `json:"monthlyUsdCap,omitempty"`
	Models                []string `json:"models,omitempty"`
	ExpiresAt             string   `json:"expiresAt,omitempty"`
	LocalOnly             bool     `json:"localOnly,omitempty"`
	AllowLocalDegradation bool     `json:"allowLocalDegradation,omitempty"`
}

KeyCreateRequest mirrors config.KeyConfig JSON shape for POST /admin/v1/keys.

type KeyPatch added in v0.21.0

type KeyPatch struct {
	RateLimit             *int      `json:"rate_limit,omitempty"`
	DailyLimit            *int      `json:"daily_limit,omitempty"`
	MonthlyLimit          *int      `json:"monthly_limit,omitempty"`
	DailyUsdCap           *float64  `json:"daily_usd_cap,omitempty"`
	MonthlyUsdCap         *float64  `json:"monthly_usd_cap,omitempty"`
	Models                *[]string `json:"models,omitempty"`
	ExpiresAt             *string   `json:"expires_at,omitempty"`
	LocalOnly             *bool     `json:"local_only,omitempty"`
	AllowLocalDegradation *bool     `json:"allow_local_degradation,omitempty"`
}

KeyPatch mirrors auth.KeyPatch for PATCH /admin/v1/keys/{name}.

type KeyResp added in v0.21.0

type KeyResp struct {
	ID                    string   `json:"id"`
	Name                  string   `json:"name"`
	Key                   string   `json:"key"`
	Created               string   `json:"created"`
	RequestsToday         int      `json:"requestsToday"`
	RequestsThisMonth     int      `json:"requestsThisMonth"`
	TokensThisMonth       int64    `json:"tokensThisMonth"`
	EstimatedCostUsd      float64  `json:"estimatedCostUsd"`
	RateLimit             int      `json:"rateLimit"`
	DailyLimit            int      `json:"dailyLimit"`
	MonthlyLimit          int      `json:"monthlyLimit"`
	DailyUsdCap           float64  `json:"dailyUsdCap,omitempty"`
	MonthlyUsdCap         float64  `json:"monthlyUsdCap,omitempty"`
	Status                string   `json:"status"`
	AllowedModels         []string `json:"allowedModels"`
	ExpiresAt             string   `json:"expiresAt,omitempty"`
	LocalOnly             bool     `json:"localOnly,omitempty"`
	AllowLocalDegradation bool     `json:"allowLocalDegradation,omitempty"`
}

KeyResp mirrors admin.go's keyResp for LIST and mirrors config.KeyConfig for CREATE.

type LiveRequestEntry added in v0.21.0

type LiveRequestEntry struct {
	ID            string    `json:"id"`
	ApiKey        string    `json:"apiKey"`
	SourceIP      string    `json:"sourceIP"`
	Model         string    `json:"model"`
	Node          string    `json:"routedTo"`
	Status        string    `json:"status"`
	HTTPStatus    int       `json:"httpStatus"`
	Latency       int       `json:"latency"`
	Tokens        int64     `json:"tokens"`
	TokensPerSec  float64   `json:"tokensPerSec"`
	Time          time.Time `json:"time"`
	RoutingReason string    `json:"routingReason,omitempty"`
}

LiveRequestEntry mirrors admin.go's RequestLog shape (GET /admin/requests/live) - a raw in-flight/recent request row, distinct from RequestEntry's dashboard-formatted shape (different status semantics: Status here is the "warm/loading/error/aborted/cloud" label, not an HTTP code).

type MarborAgentEnableResult added in v0.21.0

type MarborAgentEnableResult struct {
	Node                  string `json:"node"`
	Enabled               bool   `json:"enabled"`
	Port                  int    `json:"port"`
	Scheme                string `json:"scheme"`
	Token                 string `json:"token"`
	InstallCommand        string `json:"install_command"`
	InstallCommandWindows string `json:"install_command_windows"`
}

MarborAgentEnableResult mirrors handleEnableMarborAgent/ handleRegenerateMarborAgentToken's response shape - the ONLY response that ever carries the plaintext enrollment install command/token - never persisted or echoed back by GetMarborAgent.

type MarborAgentInfo added in v0.21.0

type MarborAgentInfo struct {
	Node    string `json:"node"`
	Enabled bool   `json:"enabled"`
	Port    int    `json:"port"`
	Scope   string `json:"scope,omitempty"`
	Scheme  string `json:"scheme,omitempty"`
}

MarborAgentInfo mirrors handleGetMarborAgent's response shape - never carries the token (only enable/regenerate return that, once).

type MetricsSummary added in v0.21.0

type MetricsSummary struct {
	ActiveRequests int32   `json:"active_requests"`
	NodesOnline    int     `json:"nodes_online"`
	NodesDraining  int     `json:"nodes_draining"`
	TotalNodes     int     `json:"total_nodes"`
	QueueDepth     int     `json:"queue_depth"`
	AvgLatency     float64 `json:"avg_latency"`
	TokensPerMin   int64   `json:"tokens_per_min"`
	ColdStarts     int64   `json:"cold_starts"`
	WarmHitRatio   float64 `json:"warm_hit_ratio"`
}

MetricsSummary mirrors GET /admin/metrics/summary's response shape.

type ModelAlias added in v0.22.0

type ModelAlias struct {
	Alias            string `json:"alias"`
	Target           string `json:"target"`
	TargetAvailable  bool   `json:"target_available"`
	TargetStatus     string `json:"target_status,omitempty"`
	ShadowsModel     bool   `json:"shadows_model"`
	InventoryChecked bool   `json:"inventory_checked"`
}

ModelAlias mirrors one row of GET /admin/model-aliases.

type ModelEntry

type ModelEntry struct {
	Name           string          `json:"name"`
	SizeVRAM       int64           `json:"size_vram"`
	SizeDisk       int64           `json:"size_disk,omitempty"`
	Nodes          []ModelNodeInfo `json:"nodes"`
	WarmCount      int             `json:"warm_count"`
	TotalNodes     int             `json:"total_nodes"`
	Family         string          `json:"family,omitempty"`
	DigestMismatch bool            `json:"digest_mismatch,omitempty"`
	TotalVRAMBytes int64           `json:"total_vram_bytes,omitempty"`
	DriftDetails   string          `json:"drift_details,omitempty"`
}

ModelEntry mirrors handleModels' modelEntry struct.

type ModelFitEntry added in v0.21.0

type ModelFitEntry struct {
	Name              string `json:"name"`
	SizeBytes         int64  `json:"size_bytes"`
	VRAMEstimateBytes int64  `json:"vram_estimate_bytes"`
	Fit               string `json:"fit"`
	Loaded            bool   `json:"loaded"`
}

ModelFitEntry mirrors handleModelFit's modelFitEntry.

type ModelNodeInfo

type ModelNodeInfo struct {
	Name      string `json:"name"`
	Healthy   bool   `json:"healthy"`
	Digest    string `json:"digest,omitempty"`
	Warm      bool   `json:"warm"`
	VRAMBytes int64  `json:"vram_bytes,omitempty"`
	Runtime   string `json:"runtime,omitempty"`
}

ModelNodeInfo mirrors handleModels' nested nodeInfo struct.

type ModelRepoOpts added in v0.21.0

type ModelRepoOpts struct {
	ID      string // required: owner/name
	Node    string
	Runtime string
	CtxLen  int
}

ModelRepoOpts mirrors the query params for GET /admin/models/repo.

type ModelSearchOpts added in v0.21.0

type ModelSearchOpts struct {
	Query   string
	Runtime string
	Sort    string // downloads (default) | likes | newest | oldest
}

ModelSearchOpts mirrors the query params for GET /admin/models/search.

type ModelsResp

type ModelsResp struct {
	Models       []ModelEntry `json:"models"`
	TotalModels  int          `json:"total_models"`
	TotalNodes   int          `json:"total_nodes"`
	HealthyNodes int          `json:"healthy_nodes"`
}

ModelsResp mirrors GET /admin/v1/models' wrapped response shape.

type NodeAddRequest added in v0.21.0

type NodeAddRequest struct {
	Name        string `json:"name"`
	URL         string `json:"url"`
	GPUModel    string `json:"gpu_model,omitempty"`
	VRAMTotalMB int64  `json:"vram_total_mb,omitempty"`
	Runtime     string `json:"runtime,omitempty"`
}

NodeAddRequest mirrors config.NodeConfig's JSON shape for POST /admin/nodes - kept as a local DTO (this package's existing convention, see NodeResp) rather than importing internal/config.

type NodeControlDiscovery

type NodeControlDiscovery struct {
	Driver     string   `json:"driver"`
	Identifier string   `json:"identifier"`
	Evidence   []string `json:"evidence"`
}

NodeControlDiscovery mirrors the "discovered" object in GET /admin/nodes/{name}/control's response.

type NodeControlInfo

type NodeControlInfo struct {
	Node         string               `json:"node"`
	Configured   bool                 `json:"configured"`
	Driver       string               `json:"driver"`
	Identifier   string               `json:"identifier"`
	StartCommand string               `json:"start_command"`
	Discovered   NodeControlDiscovery `json:"discovered"`
}

NodeControlInfo mirrors admin.go's handleGetNodeControl response shape.

type NodeDeleteMemberResult added in v0.21.0

type NodeDeleteMemberResult struct {
	Node  string `json:"node"`
	OK    bool   `json:"ok"`
	Error string `json:"error,omitempty"`
}

NodeDeleteMemberResult is one replica member's outcome inside a replica-wide delete's Results, mirroring admin.go's nodeDeleteMemberResult.

type NodeDeleteModelResult added in v0.21.0

type NodeDeleteModelResult struct {
	OK      bool                     `json:"ok"`
	Error   string                   `json:"error,omitempty"`
	Replica bool                     `json:"replica,omitempty"`
	Head    string                   `json:"head,omitempty"`
	Members []string                 `json:"members,omitempty"`
	Results []NodeDeleteMemberResult `json:"results,omitempty"`
}

NodeDeleteModelResult mirrors admin.go's handleNodeDeleteModel/ handleReplicaWideModelDelete response shape. Replica/Head/Members/Results are only populated when Replica is true (a delete issued against a resolved replica head, expanded server-side into one delete per member) - a standalone-node delete's response is just {"ok":true}, matching today's unchanged behavior. Error carries the server's message on a non-2xx response (409 worker/unresolved/invalid-component rejection, or 502 partial replica-wide failure) - populated alongside Replica/Head/Members/ Results even when DeleteNodeModel also returns a non-nil error, so a caller that wants the structured per-member breakdown on a partial failure (not just the flattened error string) can still read it.

type NodeDetectedGPUScope added in v0.24.0

type NodeDetectedGPUScope struct {
	Indices      []int    `json:"indices,omitempty"`
	UUIDs        []string `json:"uuids,omitempty"`
	Raw          string   `json:"raw,omitempty"`
	Source       string   `json:"source,omitempty"`
	CrossChecked bool     `json:"crossChecked"`
	Note         string   `json:"note,omitempty"`
}

NodeDetectedGPUScope mirrors the node API's detectedGPUScope object.

type NodeFitEntry added in v0.21.0

type NodeFitEntry struct {
	Name           string          `json:"name"`
	URL            string          `json:"url"`
	VRAMFreeBytes  int64           `json:"vram_free_bytes"`
	VRAMTotalBytes int64           `json:"vram_total_bytes"`
	VRAMSource     string          `json:"vram_source"`
	Models         []ModelFitEntry `json:"models"`
}

NodeFitEntry mirrors handleModelFit's nodeFitEntry.

type NodeModelEntry

type NodeModelEntry struct {
	Name      string `json:"name"`
	SizeBytes int64  `json:"sizeBytes,omitempty"`
	Source    string `json:"source"`
	Family    string `json:"family,omitempty"`
}

NodeModelEntry mirrors admin.go's nodeModelEntry - a single model in a node's local inventory (distinct from ModelEntry, which is the fleet-wide aggregate `models` uses).

type NodePatchFields added in v0.21.0

type NodePatchFields struct {
	ParallelismType  *string
	ParallelismWidth *int
	VRAMOverrides    *map[string]int64
	URL              *string
	Runtime          *string
	GPUModel         *string
	VRAMTotalMB      *int64
	GPUIndices       *[]int
	MaxInFlight      *int
	ClearTLS         bool
	// ReplicaPeers declares multi-host replica membership - nil means "flag
	// not visited, no change"; a non-nil pointer to a zero-value
	// NodeReplicaPeers{} explicitly clears a prior declaration, matching
	// every other field's convention here.
	ReplicaPeers *NodeReplicaPeers
}

NodePatchFields collects every visited-aware `marbor nodes patch` field in one place - see PatchNodeFields. nil means "flag not visited, no change"; a non-nil pointer to a zero-value ("" / 0 / an empty slice or map) explicitly clears that field, matching router.NodePatch's own convention. ClearTLS is a bool rather than a pointer because it is the only supported TLS operation from "nodes patch": clearing a pin, never setting one - a new fingerprint can only be pinned via "nodes confirm-tls", which requires the operator to have independently confirmed the value out of band.

type NodeReplicaPeers added in v0.21.0

type NodeReplicaPeers struct {
	Members []string `json:"members"`
	Head    string   `json:"head"`
}

NodeReplicaPeers mirrors store.ReplicaPeers' JSON shape as a local DTO (this package's existing convention - see NodeResp/NodeAddRequest rather than importing internal/store).

type NodeResp

type NodeResp struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Host        string `json:"host"`
	Port        int    `json:"port"`
	GPUModel    string `json:"gpuModel"`
	VRAMTotalMB int64  `json:"vramTotalMB"`
	VRAMUsedMB  int64  `json:"vramUsedMB"`
	// VRAMSource says where the VRAM figures came from ("nvidia", "agent",
	// "api", "declared", "none"). Used VRAM is only a reading for the first
	// three; for "declared" and "none" it is unknown, not zero.
	VRAMSource string `json:"vramSource"`
	Runtime    string `json:"runtime"`
	Health     string `json:"health"`
	Draining   bool   `json:"draining"`
	// Signals are the placement signals the server says this node matches
	// (healthy, degraded, draining, down, agent, warm, pressure). Absent
	// from servers that predate filtering, which is how the CLI tells. An
	// unfiltered --json against such a server therefore prints null.
	Signals       []string          `json:"signals"`
	LoadedModels  []json.RawMessage `json:"loadedModels"`
	ActiveConns   int32             `json:"activeConns"`
	RequestsTotal int64             `json:"requestsTotal"`
	// SchedulingRole is "standalone"|"head"|"worker"|"unresolved" - a
	// worker/unresolved node is never a placement target but still appears
	// in this list (visibility field, not a filter). ReplicaHead is the
	// resolved head node's name, present only for "head"/"worker".
	SchedulingRole string            `json:"schedulingRole,omitempty"`
	ReplicaHead    string            `json:"replicaHead,omitempty"`
	ReplicaPeers   *NodeReplicaPeers `json:"replicaPeers,omitempty"`
	// WarmupSupported reports whether keep-warm and scheduled warmup can act
	// on this node's runtime (Ollama only today). A pointer so an older
	// server that doesn't send the field prints "-" rather than a false "no".
	WarmupSupported *bool `json:"warmupSupported,omitempty"`
	// WarmupWarnings is the current per-model keep-warm notice that is not
	// a ping failure (digest drift, or a pair skipped on a replica worker or
	// an unresolved node).
	WarmupWarnings map[string]string `json:"warmupWarnings,omitempty"`

	// Detected* is what the agent saw for this runtime. DetectedGPUScope says
	// which GPUs and whether an independent per-process check confirmed it
	// (CrossChecked); absent means unknown.
	DetectedGPUGroup        []int                 `json:"detectedGPUGroup,omitempty"`
	DetectedGPUScope        *NodeDetectedGPUScope `json:"detectedGPUScope,omitempty"`
	DetectedDrivesPlacement bool                  `json:"detectedDrivesPlacement,omitempty"`
}

NodeResp mirrors admin.go's nodeResp - the fields a CLI table/JSON consumer cares about (a strict subset; unknown fields are ignored so this stays forward-compatible with new fields the server adds later).

type NodeSuggestionDeclared added in v0.24.0

type NodeSuggestionDeclared struct {
	Node    string   `json:"node"`
	Members []string `json:"members"`
	Head    string   `json:"head"`
}

NodeSuggestionDeclared mirrors a member's own declared replica_peers.

type NodeSuggestionEvidence added in v0.24.0

type NodeSuggestionEvidence struct {
	Node   string `json:"node"`
	Source string `json:"source"`
	Detail string `json:"detail"`
}

NodeSuggestionEvidence mirrors one evidence entry of a replica suggestion.

type NodeWarmupInfo added in v0.21.0

type NodeWarmupInfo struct {
	Enabled bool     `json:"enabled"`
	Models  []string `json:"models"`
}

NodeWarmupInfo mirrors handleGetNodeWarmup/handleSetNodeWarmup's response shape (GET/PUT /admin/nodes/{name}/warmup).

type PatchUserRequest added in v0.21.0

type PatchUserRequest struct {
	Email *string `json:"email,omitempty"`
	Role  *string `json:"role,omitempty"`
}

PatchUserRequest mirrors handlePatchUser JSON.

type PredictiveDecision

type PredictiveDecision struct {
	Timestamp       string `json:"timestamp"`
	PredictedModel  string `json:"predicted_model"`
	TriggerModel    string `json:"trigger_model"`
	Node            string `json:"node"`
	WasAlreadyWarm  bool   `json:"was_already_warm"`
	WarmupTriggered bool   `json:"warmup_triggered"`
	TransitionCount int    `json:"transition_count"`
	Hour            int    `json:"hour"`
}

PredictiveDecision mirrors the shape returned by GET /admin/predictive/decisions.

type PrefixLocalityStats added in v0.24.1

type PrefixLocalityStats struct {
	Enabled bool    `json:"enabled"`
	Hits    uint64  `json:"hits"`
	Misses  uint64  `json:"misses"`
	HitRate float64 `json:"hit_rate"`
}

PrefixLocalityStats mirrors the shape returned by GET /admin/prefix-locality/stats. HitRate is the server's own hit/(hit+miss) fraction, 0 when nothing was counted.

type PullJobSnapshot added in v0.21.0

type PullJobSnapshot struct {
	Node           string    `json:"node"`
	Model          string    `json:"model"`
	Method         string    `json:"method"`
	Status         string    `json:"status"`
	StartedAt      time.Time `json:"started_at"`
	FinishedAt     time.Time `json:"finished_at,omitempty"`
	BytesTotal     int64     `json:"bytes_total,omitempty"`
	BytesCompleted int64     `json:"bytes_completed,omitempty"`
	Error          string    `json:"error,omitempty"`
	VerifyLoad     bool      `json:"verify_load"`
}

PullJobSnapshot mirrors admin.go's pullJobSnapshot - one active/recent model pull job.

type PullResult

type PullResult struct {
	OK    bool   `json:"ok"`
	Node  string `json:"node"`
	Model string `json:"model"`
}

PullResult mirrors handleNodePull's 202-Accepted response body - the pull itself runs async server-side, so this only confirms the job started, same "one Admin API request" contract as RuntimeAction.

type ReplicaInfo added in v0.24.0

type ReplicaInfo struct {
	Role    string   `json:"role"`
	Head    string   `json:"head,omitempty"`
	Members []string `json:"members,omitempty"`
	Warning string   `json:"warning,omitempty"`
}

ReplicaInfo mirrors the Admin API's "replica" object: the multi-host replica a node belongs to. Absent (nil) for a standalone node.

type ReplicaSuggestion added in v0.24.0

type ReplicaSuggestion struct {
	Fingerprint string                   `json:"fingerprint"`
	Launcher    string                   `json:"launcher"`
	Runtime     string                   `json:"runtime"`
	State       string                   `json:"state"`
	Reason      string                   `json:"reason"`
	Head        string                   `json:"head"`
	Members     []string                 `json:"members"`
	Evidence    []NodeSuggestionEvidence `json:"evidence"`
	Missing     []string                 `json:"missing"`
	Declared    []NodeSuggestionDeclared `json:"declared"`
	Confirmable bool                     `json:"confirmable"`
	Dismissed   bool                     `json:"dismissed"`
}

ReplicaSuggestion mirrors one element of GET /admin/replica-suggestions.

type ReplicaSuggestionsResponse added in v0.24.0

type ReplicaSuggestionsResponse struct {
	Suggestions    []ReplicaSuggestion `json:"suggestions"`
	Coverage       []TopologyCoverage  `json:"coverage"`
	DismissedCount int                 `json:"dismissedCount"`
}

ReplicaSuggestionsResponse mirrors GET /admin/replica-suggestions.

type RequestEntry added in v0.21.0

type RequestEntry struct {
	ID            string    `json:"id"`
	Time          time.Time `json:"time"`
	KeyName       string    `json:"key_name"`
	SourceIP      string    `json:"source_ip"`
	Model         string    `json:"model"`
	Node          string    `json:"node"`
	Status        int       `json:"status"`
	LatencyMs     int       `json:"latency_ms"`
	Cloud         bool      `json:"cloud"`
	RoutingReason string    `json:"routingReason,omitempty"`
	PrefillMs     int64     `json:"prefillMs,omitempty"`
}

RequestEntry mirrors handleRequests' response entry shape (GET /admin/requests) - the dashboard's request log, newest first.

type RoutingDecision

type RoutingDecision struct {
	Node          string              `json:"node"`
	Reason        string              `json:"reason"`
	Detail        string              `json:"detail,omitempty"`
	AffinityLost  bool                `json:"affinityLost,omitempty"`
	Score         float64             `json:"score,omitempty"`
	Components    []ScoreComponent    `json:"components,omitempty"`
	Excluded      []ExcludedCandidate `json:"excluded,omitempty"`
	ExcludedTotal int                 `json:"excludedTotal,omitempty"`
}

RoutingDecision mirrors router.RoutingDecision for per-request routing explainability. Kept as a local DTO (not an import of internal/router) following this package's existing convention of decoding Admin API JSON into its own response types (see NodeResp) rather than depending on internal packages.

type RoutingRule added in v0.21.0

type RoutingRule struct {
	ID         string `json:"id"`
	Priority   int    `json:"priority"`
	Condition  string `json:"condition"`
	TargetNode string `json:"targetNode"`
	Strategy   string `json:"strategy,omitempty"`
	Enabled    bool   `json:"enabled"`
}

RoutingRule mirrors config.RoutingRule.

type RunCtx

type RunCtx struct {
	Flags *globalFlags
	Args  []string
	Cmd   *Command

	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

RunCtx carries everything a migrated Run function needs: the parsed global flags, the validated positional arguments, the matched Command (so a shared impl like "runtime start|stop|restart" can branch on ctx.Cmd.Name), the command-specific flag values, and the output streams.

Flag values are resolved into a plain map at parse time (Name -> value) rather than exposing the *flag.FlagSet directly: RunCtx's job is to be a simple, stable surface for command implementations, and a map keeps String/Bool/Int trivial and panic-free for callers that pass a flag name declared on the command.

func (*RunCtx) Bool

func (c *RunCtx) Bool(name string) bool

Bool returns the bool flag value for name, or false if name was not declared as a FlagBool on the matched command.

func (*RunCtx) Int

func (c *RunCtx) Int(name string) int

Int returns the int flag value for name, or 0 if name was not declared as a FlagInt on the matched command.

func (*RunCtx) IsSet added in v0.21.0

func (c *RunCtx) IsSet(name string) bool

IsSet reports whether the named flag was explicitly supplied on the command line (via fs.Visit). Used for PATCH semantics where only visited flags should be sent to the server.

func (*RunCtx) String

func (c *RunCtx) String(name string) string

String returns the string flag value for name, or "" if name was not declared as a FlagString on the matched command.

type RunFunc

type RunFunc func(ctx *RunCtx) int

RunFunc is the signature every leaf command's implementation satisfies once migrated onto the registry (later plan step - see registry_tree.go).

type RuntimeActionResult added in v0.25.1

type RuntimeActionResult struct {
	Replica     *ReplicaInfo     `json:"replica,omitempty"`
	SoleReplica *SoleReplicaBody `json:"sole_replica,omitempty"`
}

RuntimeActionResult is the optional detail on a successful runtime action: the replica the node belongs to, and any models the action took out of service. Both are nil when there is nothing to report.

type Schedule added in v0.21.0

type Schedule struct {
	ID         string   `json:"id"`
	Action     string   `json:"action"`
	Node       string   `json:"node"`
	Models     []string `json:"models,omitempty"`
	At         string   `json:"at"`
	Days       []int    `json:"days,omitempty"`
	Enabled    bool     `json:"enabled"`
	LastRunAt  string   `json:"last_run_at,omitempty"`
	LastStatus string   `json:"last_status,omitempty"`
	LastError  string   `json:"last_error,omitempty"`
}

Schedule mirrors router.Schedule - a time-of-day warmup/unload/drain/ undrain automation entry.

type ScheduleCreateRequest added in v0.21.0

type ScheduleCreateRequest struct {
	Action  string   `json:"action"`
	Node    string   `json:"node"`
	Models  []string `json:"models,omitempty"`
	At      string   `json:"at"`
	Days    []int    `json:"days,omitempty"`
	Enabled bool     `json:"enabled"`
}

ScheduleCreateRequest is the body for POST /admin/schedules.

type SchedulePatch added in v0.21.0

type SchedulePatch struct {
	Enabled *bool     `json:"enabled,omitempty"`
	Action  *string   `json:"action,omitempty"`
	Node    *string   `json:"node,omitempty"`
	Models  *[]string `json:"models,omitempty"`
	At      *string   `json:"at,omitempty"`
	Days    *[]int    `json:"days,omitempty"`
}

SchedulePatch is the body for PATCH /admin/schedules/{id} - nil fields are left unchanged server-side.

type ScoreComponent

type ScoreComponent struct {
	Name   string  `json:"name"`
	Raw    float64 `json:"raw"`
	Weight float64 `json:"weight"`
	Value  float64 `json:"value"`
	Phase  string  `json:"phase,omitempty"`
}

ScoreComponent mirrors one term of router.RoutingDecision.Components - a weighted factor contributing to a node's placement score.

type SoleReplicaBody added in v0.25.1

type SoleReplicaBody struct {
	SoleReplicaImpact
	Forced bool `json:"forced"`
}

SoleReplicaBody is the sole_replica object on a drain or restart response.

type SoleReplicaImpact added in v0.25.1

type SoleReplicaImpact struct {
	Models       []SoleReplicaModel   `json:"models"`
	ColdLoadOnly []ColdLoadModel      `json:"cold_load_only"`
	Unknown      []SoleReplicaUnknown `json:"unknown"`
}

SoleReplicaImpact mirrors the Admin API's sole_replica lists.

type SoleReplicaModel added in v0.25.1

type SoleReplicaModel struct {
	Model   string `json:"model"`
	Runtime string `json:"runtime"`
}

SoleReplicaModel is a model the node is the only possible server of.

type SoleReplicaUnknown added in v0.25.1

type SoleReplicaUnknown struct {
	Node   string `json:"node"`
	Model  string `json:"model,omitempty"`
	Reason string `json:"reason"`
}

SoleReplicaUnknown is a place where replica data could not be verified.

type SpillCounterRow

type SpillCounterRow struct {
	KeyName  string `json:"key_name"`
	ServedBy string `json:"served_by"`
	Requests int64  `json:"requests"`
}

SpillCounterRow mirrors one row of GET /admin/v1/spill - a per-key, per-served_by request count. served_by is "local", a cloud provider's name, or "blocked" (a local_only policy rejection).

type SystemAuditEntry

type SystemAuditEntry struct {
	Time     string `json:"time"`
	Username string `json:"username"`
	Action   string `json:"action"`
	Target   string `json:"target"`
	Details  string `json:"details"`
	SourceIP string `json:"source_ip"`
}

SystemAuditEntry mirrors the JSON returned by GET /admin/system-audit.

type SystemAuditFilter added in v0.21.0

type SystemAuditFilter struct {
	From     string
	To       string
	Before   string
	Limit    int
	Kind     string
	Action   string
	User     string
	Target   string
	SourceIP string
}

SystemAuditFilter mirrors the query params for GET /admin/system-audit.

type TopologyCoverage added in v0.24.0

type TopologyCoverage struct {
	Node     string `json:"node"`
	Host     string `json:"host"`
	State    string `json:"state"`
	Detected bool   `json:"detected"`
	Detail   string `json:"detail"`
}

TopologyCoverage mirrors one coverage row: whether detection can see a node.

type UserResp added in v0.21.0

type UserResp struct {
	ID                 int64   `json:"id"`
	Username           string  `json:"username"`
	Email              string  `json:"email"`
	Role               string  `json:"role"`
	Status             string  `json:"status"`
	APIKeyName         string  `json:"api_key_name"`
	MustChangePassword bool    `json:"must_change_password"`
	CreatedAt          string  `json:"created_at"`
	ApprovedAt         *string `json:"approved_at,omitempty"`
	ApprovedBy         string  `json:"approved_by,omitempty"`
}

UserResp mirrors store.User JSON for GET/POST/PATCH users.

type WarmupStatus added in v0.21.0

type WarmupStatus struct {
	Enabled                 bool     `json:"enabled"`
	IntervalMs              int      `json:"interval_ms"`
	KeepAlive               string   `json:"keep_alive"`
	Models                  []string `json:"models"`
	PredictiveEngineEnabled bool     `json:"predictive_engine_enabled"`
}

WarmupStatus mirrors GET /admin/warmup's response shape.

Jump to

Keyboard shortcuts

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