api

package
v1.0.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: GPL-3.0 Imports: 53 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 api provides HTTP handlers for the PiWorker API.

Package api provides HTTP handlers for the PiWorker REST API.

Package api provides the HTTP REST API for PiWorker.

Index

Constants

View Source
const (
	AgentTokenActive  = "active"
	AgentTokenExpired = "expired"
	AgentTokenRevoked = "revoked"
	// AgentTokenUnknown is reported for an approval whose token does not exist.
	AgentTokenUnknown = "unknown"
)

Token statuses reported to the editor.

View Source
const (
	GrantConfirm = "confirm" // accept the tool's current fingerprint and resume: step-up when it widens
	GrantSuspend = "suspend"
	GrantRemove  = "remove"
	GrantAdd     = "add" // widens the token: needs password step-up
)

Grant actions for POST /api/agent/tokens/{id}/grants.

View Source
const BackgroundRequestHeader = "X-PiWorker-Background"

BackgroundRequestHeader marks a request the editor sends by itself (a refresh triggered by polling), not on the admin's behalf. Set to "1", the session is authenticated without extending its idle expiry. A client can only shorten its own session with it, so every guarded path accepts it.

View Source
const CACertPath = "/piworker-ca.crt"

CACertPath serves the local CA certificate. It is public, answered by the plain HTTP listener too and, like webhooks, reachable under any Host name, so a device can fetch the CA before trusting it.

View Source
const ContextKeyUser contextKey = "user"
View Source
const DefaultHostCacheTTL = 30 * time.Second

DefaultHostCacheTTL is how long the hostname and interface addresses are cached before being read again.

View Source
const MaxAgentTokenDays = int(storage.MaxAPITokenLifetime / (24 * time.Hour))

MaxAgentTokenDays bounds expiresInDays on token creation.

View Source
const MaxBackupUploadSize = 64 << 20

MaxBackupUploadSize bounds a backup uploaded to restore. The JSON body carries it in base64 (the request guard admits only JSON).

View Source
const MaxRequestBodySize = 1 << 20

MaxRequestBodySize is the maximum size of request bodies (1MB).

View Source
const MaxStoresImportSize = 8 << 20

MaxStoresImportSize bounds an import request: the variables of a busy installation can outgrow MaxRequestBodySize.

View Source
const MaxUsernameLength = 128

MaxUsernameLength bounds account names for setup, recovery and bootstrap.

View Source
const PendingApprovalsCountPath = "/api/agent/approvals/pending-count"

PendingApprovalsCountPath serves the editor badge's poll. AuthMiddleware authenticates it without extending the session's idle expiry (see passiveSessionPaths), so an open tab alone does not keep a session alive.

Variables

View Source
var ErrApprovalExecutionUnavailable = errors.New("not available")

ErrApprovalExecutionUnavailable is returned by the default ApprovalExecutor.

Functions

func AuthMiddleware

func AuthMiddleware(h *AuthHandler) mux.MiddlewareFunc

AuthMiddleware requires a valid session on guarded /api paths and extends its idle expiry, except on passiveSessionPaths and background requests (BackgroundRequestHeader), which it authenticates with the non-touching variant.

func AuthStatusHandler

func AuthStatusHandler(enabled bool) http.HandlerFunc

func CleanPathsAsSent

func CleanPathsAsSent(router *mux.Router)

CleanPathsAsSent makes router clean request paths as gorilla/mux does (a 301 to the canonical path when it has "//", "/./" or "/../", or lacks the leading '/'), but judges the path as the client sent it (URL.EscapedPath), not decoded. An escaped '/' (%2F) or '.' (%2E) is part of a path segment: a conversation key or knowledge document ID the editor path-escapes (a URL, "docs/../faq") reaches its route unchanged, where mux's own cleaning, on the decoded path, would redirect it to another key (and a DELETE would delete another item, or none). Routes still match the decoded path, so every handler reads its variables as before.

It must be called before any route is registered: the redirect is the router's first route. It runs behind the router's middleware (Host allowlist, request guard, session), where mux's redirect ran before it.

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (*storage.Session, bool)

func HashPassword

func HashPassword(password string) (string, error)

func LoggingMiddleware

func LoggingMiddleware(logger zerolog.Logger) mux.MiddlewareFunc

LoggingMiddleware logs every request, with its method and path as requested (a handler may rewrite r.URL.Path), cut to maxLogField bytes; at info level, or debug for refusals marked with quietAccessLog.

func MethodNotAllowedHandler

func MethodNotAllowedHandler(w http.ResponseWriter, r *http.Request)

MethodNotAllowedHandler handles 405 responses.

func MetricsMiddleware

func MetricsMiddleware(next http.Handler) http.Handler

MetricsMiddleware records HTTP request count and latency, labelled by the mux route template (not the raw path) to keep Prometheus cardinality bounded.

func NormalizeNewCredentials

func NormalizeNewCredentials(username, password string) (string, bool)

NormalizeNewCredentials applies the same rules as browser setup: the username is trimmed (login trims too) and must be 1..MaxUsernameLength bytes, and the password must be 8..72 bytes (bcrypt's limit).

func NotFoundHandler

func NotFoundHandler(w http.ResponseWriter, r *http.Request)

NotFoundHandler handles 404 responses.

func RecoveryMiddleware

func RecoveryMiddleware(logger zerolog.Logger) mux.MiddlewareFunc

RecoveryMiddleware recovers from panics in downstream handlers, logs the panic with a stack trace, and returns a structured 500 JSON response instead of a dropped/empty connection. Register it as the outermost middleware.

func RequestGuardMiddleware

func RequestGuardMiddleware(secure bool, allowedOrigins []string) mux.MiddlewareFunc

RequestGuardMiddleware enforces the CSRF check and a JSON Content-Type on every unsafe /api/ request, independently of whether authentication is enabled. Without it a page open in the admin's browser could blind-POST a text/plain "simple request" to create and deploy a flow when auth is off.

Types

type APIResponse

type APIResponse struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Error   string      `json:"error,omitempty"`
	Message string      `json:"message,omitempty"`
}

APIResponse is a standard API response wrapper.

type AgentHandler

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

AgentHandler serves /api/agent/*.

func NewAgentHandler

func NewAgentHandler(store AgentStore, auth *AuthHandler, tokens *agentauth.TokenVerifier, opts AgentHandlerOptions) *AgentHandler

NewAgentHandler returns the agent administration handler. auth provides the password step-up and its limiter; tokens applies revocations and grant changes to the verifier cache immediately.

func (*AgentHandler) Approve

func (h *AgentHandler) Approve(w http.ResponseWriter, r *http.Request)

Approve records the approval, then asks the ApprovalExecutor to run it. POST /api/agent/approvals/{id}/approve

func (*AgentHandler) CreateToken

func (h *AgentHandler) CreateToken(w http.ResponseWriter, r *http.Request)

CreateToken creates a token after password step-up and returns its plaintext once. POST /api/agent/tokens

func (*AgentHandler) GetSettings

func (h *AgentHandler) GetSettings(w http.ResponseWriter, _ *http.Request)

GetSettings returns the agent settings. GET /api/agent/settings

func (*AgentHandler) ListApprovals

func (h *AgentHandler) ListApprovals(w http.ResponseWriter, r *http.Request)

ListApprovals expires stale approvals, then lists them newest first. GET /api/agent/approvals?status=pending|approved|rejected|expired|all&limit=N

func (*AgentHandler) ListAudit

func (h *AgentHandler) ListAudit(w http.ResponseWriter, r *http.Request)

ListAudit returns audited agent calls (most recently recorded first) and rejection counters. Filters: tokenId, tool, flowId, outcome, since and until (RFC 3339 on the call time; since inclusive, until exclusive), beforeId (paging: pass the id of the last entry of the previous page) and limit. GET /api/agent/audit

func (*AgentHandler) ListRejectionTotals

func (h *AgentHandler) ListRejectionTotals(w http.ResponseWriter, r *http.Request)

ListRejectionTotals sums the rejected calls (busy, cooldown, invalid arguments…) per token and reason over a window. Filters: tokenId, since (inclusive, of its whole minute) and until (exclusive), RFC 3339. GET /api/agent/audit/rejections

func (*AgentHandler) ListTokens

func (h *AgentHandler) ListTokens(w http.ResponseWriter, _ *http.Request)

ListTokens returns every token, newest first. GET /api/agent/tokens

func (*AgentHandler) PendingCount

func (h *AgentHandler) PendingCount(w http.ResponseWriter, _ *http.Request)

PendingCount counts the approvals and the drafts still awaiting a decision. It is read-only: approvals past their expiry are not counted but are left for the expiry pass (ListApprovals, CreateAgentApproval) to close. GET /api/agent/approvals/pending-count

func (*AgentHandler) PutSettings

func (h *AgentHandler) PutSettings(w http.ResponseWriter, r *http.Request)

PutSettings changes the agent deploy level after password step-up: raising it is an explicit acceptance of risk (docs/design/mcp.md §10). PUT /api/agent/settings

func (*AgentHandler) RegisterRoutes

func (h *AgentHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the agent administration routes.

func (*AgentHandler) Reject

func (h *AgentHandler) Reject(w http.ResponseWriter, r *http.Request)

Reject records the rejection; nothing runs. POST /api/agent/approvals/{id}/reject

func (*AgentHandler) RevokeAllTokens

func (h *AgentHandler) RevokeAllTokens(w http.ResponseWriter, r *http.Request)

RevokeAllTokens revokes every token in one transaction, which also rejects their pending approvals and bumps the tokens epoch, and stops every cached verification at once. Like revoking one token it needs no password: it only narrows access (docs/design/mcp.md §7). POST /api/agent/tokens/revoke-all

func (*AgentHandler) RevokeToken

func (h *AgentHandler) RevokeToken(w http.ResponseWriter, r *http.Request)

RevokeToken revokes a token; it stops working immediately. DELETE /api/agent/tokens/{id}

func (*AgentHandler) UpdateGrant

func (h *AgentHandler) UpdateGrant(w http.ResponseWriter, r *http.Request)

UpdateGrant confirms, suspends, removes or adds one grant of a token. Changes that widen what the token may do need password step-up: adding a grant, and confirming one that is suspended or bound to another fingerprint (§7: a redeploy that raised the risk or widened the schema suspends the grant until the admin re-approves it). Suspending and removing only narrow, so they need no password. The change is applied to the stored grants in one transaction, so concurrent updates never overwrite each other. POST /api/agent/tokens/{id}/grants

type AgentHandlerOptions

type AgentHandlerOptions struct {
	// AuthorEnabled mirrors mcp.author_enabled: only then can tokens get the
	// author scope.
	AuthorEnabled bool
	// MCPEnabled and LANAccess mirror mcp.enabled and mcp.lan_access, so the
	// agent pages can say whether agents can connect at all.
	MCPEnabled bool
	LANAccess  bool
	// Executor runs approved requests (default: unavailable).
	Executor ApprovalExecutor
	// Now is the clock (default time.Now).
	Now func() time.Time
	// Logger reports internal failures.
	Logger zerolog.Logger
}

AgentHandlerOptions configures an AgentHandler.

type AgentSettings

type AgentSettings struct {
	AgentDeploy   storage.AgentDeployLevel `json:"agentDeploy"`
	AuthorEnabled bool                     `json:"authorEnabled"`
	MCPEnabled    bool                     `json:"mcpEnabled"`
	LANAccess     bool                     `json:"lanAccess"`
}

AgentSettings is the GET/PUT /api/agent/settings payload. AuthorEnabled, MCPEnabled and LANAccess reflect mcp.author_enabled, mcp.enabled and mcp.lan_access and are read-only here (they live in the TOML).

type AgentStore

type AgentStore interface {
	AgentDeployLevel() (storage.AgentDeployLevel, error)
	SetAgentDeployLevel(level storage.AgentDeployLevel) error
	CreateAPIToken(req storage.NewAPIToken, now time.Time) (*storage.APIToken, string, error)
	ListAPITokens() ([]storage.APIToken, error)
	UpdateAPITokenGrants(id string, fn func([]storage.TokenGrant) ([]storage.TokenGrant, error)) (*storage.APIToken, error)
	GetAgentApproval(id string) (*storage.AgentApproval, error)
	ListAgentApprovals(f storage.AgentApprovalFilter) ([]storage.AgentApproval, error)
	CountPendingAgentApprovals(now time.Time) (int, error)
	DecideAgentApproval(id string, approve bool, decidedBy string, now time.Time) (*storage.AgentApproval, error)
	ExpireAgentApprovals(now time.Time) (int, error)
	CountPendingFlowDrafts() (int, error)
	ListMCPAudit(f storage.MCPAuditFilter) ([]storage.MCPAuditEntry, error)
	ListMCPRejections(f storage.MCPAuditFilter) ([]storage.MCPRejection, error)
	MCPRejectionTotals(f storage.MCPRejectionFilter) ([]storage.MCPRejectionTotal, bool, error)
}

AgentStore is what the agent administration routes store: tokens and their grants, approvals, the audit and the agent deploy level.

type AgentTokenList

type AgentTokenList struct {
	Tokens []AgentTokenView `json:"tokens"`
}

AgentTokenList is the GET /api/agent/tokens payload.

type AgentTokenRevoker

type AgentTokenRevoker interface {
	// RevokeAllInTx revokes every token inside tx, the transaction that
	// changes the password, so both commit together or neither does.
	RevokeAllInTx(tx *sql.Tx) error
	// EvictAll drops cached verifications once that transaction committed.
	EvictAll()
}

AgentTokenRevoker revokes every agent API token as part of a credential reset (agentauth.TokenVerifier).

type AgentTokenView

type AgentTokenView struct {
	storage.APIToken
	Status string `json:"status"`
}

AgentTokenView is a stored token as listed in the editor (never the secret or its hash).

type AgentTool

type AgentTool struct {
	FlowID        string           `json:"flowId"`
	FlowName      string           `json:"flowName"`
	TriggerNodeID string           `json:"triggerNodeId"`
	ToolName      string           `json:"toolName"`
	Title         string           `json:"title"`
	Description   string           `json:"description"`
	Risk          node.Risk        `json:"risk"`
	Annotations   flow.Annotations `json:"annotations"`
	Fingerprint   string           `json:"fingerprint"`
	Confirm       string           `json:"confirm"`
	InputSchema   json.RawMessage  `json:"inputSchema"`
}

AgentTool is one published tool as the editor sees it.

type AgentToolList

type AgentToolList struct {
	Version uint64      `json:"version"`
	Tools   []AgentTool `json:"tools"`
}

AgentToolList is the GET /api/agent/tools payload. Version changes with every deploy, undeploy or stop.

type AgentToolsHandler

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

AgentToolsHandler serves GET /api/agent/tools: the published tools, for the editor's grant pickers (docs/design/mcp.md §7).

func NewAgentToolsHandler

func NewAgentToolsHandler(tools ToolLister) *AgentToolsHandler

NewAgentToolsHandler returns the published-tools handler.

func (*AgentToolsHandler) List

List answers the published tools. GET /api/agent/tools

func (*AgentToolsHandler) RegisterRoutes

func (h *AgentToolsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers GET /api/agent/tools.

type ApprovalDecision

type ApprovalDecision struct {
	Approval       ApprovalView `json:"approval"`
	Executed       bool         `json:"executed"`
	ExecutionError string       `json:"executionError,omitempty"`
}

ApprovalDecision is the payload of approve/reject. Executed reports whether the ApprovalExecutor ran the approved request; ExecutionError says why not.

type ApprovalExecutor

type ApprovalExecutor interface {
	ExecuteApproval(ctx context.Context, approval storage.AgentApproval) error
}

ApprovalExecutor runs what an approved request asked for (a confirm:admin tool call). It is called after the decision is recorded; the default returns ErrApprovalExecutionUnavailable until the MCP service is wired in.

type ApprovalList

type ApprovalList struct {
	Approvals []ApprovalView `json:"approvals"`
	Pending   int            `json:"pending"`
}

ApprovalList is the GET /api/agent/approvals payload. Pending counts the approvals still awaiting a decision (the editor badge), whatever the filter.

type ApprovalView

type ApprovalView struct {
	storage.AgentApproval
	TokenStatus string `json:"tokenStatus"`
}

ApprovalView is an approval as shown in the editor. TokenStatus is the requesting token's state now (active, expired, revoked or unknown): only a request from an active token can be approved.

type ApproveDraftRequest

type ApproveDraftRequest struct {
	Deploy bool `json:"deploy"`
}

ApproveDraftRequest is the body of an approval: whether to deploy the saved version (a running flow is redeployed whatever it says).

type AssistantHandler

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

AssistantHandler serves the editor's flow assistant. It is a thin adapter: the service stores, deploys and runs nothing; the editor shows the proposal and the admin applies it to the canvas.

func NewAssistantHandler

func NewAssistantHandler(svc FlowAssistant, logger zerolog.Logger) *AssistantHandler

NewAssistantHandler creates an AssistantHandler.

func (*AssistantHandler) ProposeFlow

func (h *AssistantHandler) ProposeFlow(w http.ResponseWriter, r *http.Request)

ProposeFlow answers the assistant's proposal (service.AssistantFlowResult). A refused request is 400, a busy assistant 409 (one request at a time), a spent daily token limit 429, the time bound 504 and any other failure of the model request (the provider's error, an answer that is not a flow) 502, each with the service's message: it never holds a key or a secret value. POST /api/llm/assistant/flow {connection, model?, description, flow?}

func (*AssistantHandler) RegisterRoutes

func (h *AssistantHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers POST /api/llm/assistant/flow.

type AuditPage

type AuditPage struct {
	Entries    []storage.MCPAuditEntry `json:"entries"`
	Rejections []storage.MCPRejection  `json:"rejections"`
}

AuditPage is the GET /api/agent/audit payload.

type AuthHandler

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

func NewAuthHandler

func NewAuthHandler(store *storage.SQLiteUserStore, secure bool, origins []string, opts ...AuthOption) *AuthHandler

func (*AuthHandler) CurrentSession

func (h *AuthHandler) CurrentSession(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Login

func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Logout

func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Password

func (h *AuthHandler) Password(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Recover

func (h *AuthHandler) Recover(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) RegisterRoutes

func (h *AuthHandler) RegisterRoutes(router *mux.Router)

func (*AuthHandler) SetAgentTokenRevoker

func (h *AuthHandler) SetAgentTokenRevoker(r AgentTokenRevoker)

SetAgentTokenRevoker makes account recovery, and password changes that do not ask to keep them, revoke every agent token in this process.

func (*AuthHandler) Setup

func (h *AuthHandler) Setup(w http.ResponseWriter, r *http.Request)

func (*AuthHandler) Status

func (h *AuthHandler) Status(w http.ResponseWriter, r *http.Request)

type AuthOption

type AuthOption func(*AuthHandler)

AuthOption configures an AuthHandler.

func WithSecureCookies

func WithSecureCookies(on bool) AuthOption

WithSecureCookies marks session cookies Secure regardless of how a request arrived. PiWorker enables it whenever it serves HTTPS itself.

type AuthStatusResponse

type AuthStatusResponse struct {
	Enabled       bool `json:"enabled"`
	SetupRequired bool `json:"setupRequired"`
}

type BackupDownloadRequest

type BackupDownloadRequest struct {
	Passphrase string `json:"passphrase"`
	Password   string `json:"password"`
}

BackupDownloadRequest: the passphrase that encrypts the copy and the account password.

type BackupRestoreRequest

type BackupRestoreRequest struct {
	Password string `json:"password"`
}

BackupRestoreRequest confirms the account password.

type BackupRestoreResponse

type BackupRestoreResponse struct {
	Manifest   backup.Manifest `json:"manifest"`
	Restarting bool            `json:"restarting"`
}

BackupRestoreResponse: the backup that will be restored; PiWorker is restarting to apply it.

type BackupSettingsRequest

type BackupSettingsRequest struct {
	backup.Settings
	Password string `json:"password"`
}

BackupSettingsRequest is PUT /api/backups/settings's body: the settings, and the account password when the directory changes.

type BackupUploadRequest

type BackupUploadRequest struct {
	Data       string `json:"data"`
	Passphrase string `json:"passphrase"`
	Password   string `json:"password"`
	Code       string `json:"code"`
}

BackupUploadRequest is a backup file in base64: a plain archive or an encrypted copy with its passphrase.

type BackupsHandler

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

BackupsHandler serves /api/backups.

func NewBackupsHandler

func NewBackupsHandler(opts BackupsOptions) *BackupsHandler

NewBackupsHandler creates the handler.

func (*BackupsHandler) BackUpNow

func (h *BackupsHandler) BackUpNow(w http.ResponseWriter, r *http.Request)

BackUpNow makes a manual backup.

func (*BackupsHandler) Delete

func (h *BackupsHandler) Delete(w http.ResponseWriter, r *http.Request)

Delete removes a backup.

func (*BackupsHandler) Download

func (h *BackupsHandler) Download(w http.ResponseWriter, r *http.Request)

Download answers a local backup encrypted with the passphrase (age): a copy that leaves the device is always encrypted. It carries every secret, so it needs the account password, and is refused while authentication is disabled.

func (*BackupsHandler) ListRemote

func (h *BackupsHandler) ListRemote(w http.ResponseWriter, r *http.Request)

ListRemote lists the copies at the remote destination.

func (*BackupsHandler) Overview

func (h *BackupsHandler) Overview(w http.ResponseWriter, r *http.Request)

Overview answers BackupsOverview.

func (*BackupsHandler) RegisterRoutes

func (h *BackupsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the routes.

func (*BackupsHandler) Restore

func (h *BackupsHandler) Restore(w http.ResponseWriter, r *http.Request)

Restore stages a backup (after backing up the current state) and asks the process to restart; the restore is applied before the database is opened again. It replaces accounts, flows and secrets, so it needs the account password (when authentication is enabled).

func (*BackupsHandler) RestoreRemote

func (h *BackupsHandler) RestoreRemote(w http.ResponseWriter, r *http.Request)

RestoreRemote downloads, decrypts and stages a remote copy, then restarts.

func (*BackupsHandler) SaveRemote

func (h *BackupsHandler) SaveRemote(w http.ResponseWriter, r *http.Request)

SaveRemote stores the remote destination. It decides where encrypted copies of every secret go: the account password is confirmed.

func (*BackupsHandler) SaveSettings

func (h *BackupsHandler) SaveSettings(w http.ResponseWriter, r *http.Request)

SaveSettings stores the settings. Changing the directory decides where copies of every secret and of the CA key are written, so it needs the account password (when authentication is enabled).

func (*BackupsHandler) SetupRestore

func (h *BackupsHandler) SetupRestore(w http.ResponseWriter, r *http.Request)

SetupRestore restores a backup on the setup page of a fresh installation instead of creating an account. The setup code authorises it; it is used up only once the backup was accepted.

func (*BackupsHandler) TestRemote

func (h *BackupsHandler) TestRemote(w http.ResponseWriter, r *http.Request)

TestRemote checks a destination. The stored secret key is used only for the stored endpoint and key ID, so it is never signed into a request to a host the admin did not save.

func (*BackupsHandler) Upload

func (h *BackupsHandler) Upload(w http.ResponseWriter, r *http.Request)

Upload restores an uploaded backup on a running installation (after backing up the current state), then restarts.

type BackupsOptions

type BackupsOptions struct {
	Service *backup.Service
	// Auth confirms the account password before a restore or a change of
	// the backup directory; nil while authentication is disabled.
	Auth *AuthHandler
	// Restart asks the process to stop so it starts again and applies a
	// staged restore.
	Restart func()
	Logger  zerolog.Logger
}

BackupsOptions wires the automatic backups (ADR-0032).

type BackupsOverview

type BackupsOverview struct {
	Settings       backup.Settings `json:"settings"`
	Dir            string          `json:"dir"`
	DefaultDir     string          `json:"defaultDir"`
	Status         backup.Status   `json:"status"`
	NextRun        *time.Time      `json:"nextRun"`
	Backups        []backup.Info   `json:"backups"`
	RestorePending bool            `json:"restorePending"`
	// Remote is the S3-compatible destination, without its secrets.
	Remote backup.RemoteState `json:"remote"`
}

BackupsOverview is GET /api/backups: the settings, where backups go, the last outcome, the next scheduled run and the backups, newest first.

type ConnectionItem

type ConnectionItem struct {
	Name        string `json:"name"`
	Broker      string `json:"broker"`
	Username    string `json:"username"`
	HasPassword bool   `json:"hasPassword"`
	BaseTopic   string `json:"baseTopic"`
}

ConnectionItem is a connection as the API shows it: never its password.

type ConnectionStoredResponse

type ConnectionStoredResponse struct {
	Restarted []FlowRef            `json:"restarted"`
	Failed    []FlowRestartFailure `json:"failed"`
}

ConnectionStoredResponse is PUT's answer: the running flows that use the connection and were restarted with its new settings, and those that could not start again (now failed). Both are lists, empty when none.

type ConnectionTester

type ConnectionTester interface {
	TestConnection(ctx context.Context, c brokers.Connection) error
}

ConnectionTester tries a broker connection (connect, then disconnect).

type ConnectionUsers

type ConnectionUsers interface {
	// RestartFlowsUsing restarts the running flows that use the connection.
	RestartFlowsUsing(ctx context.Context, names []string) ([]FlowRef, []FlowRestartFailure)
	// UnlessRunningFlowsUse runs fn unless a running flow uses the
	// connection; then it returns those flows and fn does not run.
	UnlessRunningFlowsUse(name string, fn func() error) ([]FlowRef, error)
}

ConnectionUsers is the lifecycle path as the connections see it (service.Lifecycle, ADR-0029).

type ConnectionsHandler

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

ConnectionsHandler manages the named MQTT broker connections (ADR-0026). Passwords are write-only: set or replaced, never returned.

func NewConnectionsHandler

func NewConnectionsHandler(store *brokers.Store, tester ConnectionTester, logger zerolog.Logger) *ConnectionsHandler

NewConnectionsHandler creates a ConnectionsHandler.

func (*ConnectionsHandler) Delete

Delete removes a connection, unless a running flow uses it (409, with the flows in data.flows): stopping it would be the next deploy's refusal arriving unannounced (ADR-0029). Stopped flows that name it are refused at their next deploy (undefined_connection).

func (*ConnectionsHandler) List

List returns the connections sorted by name.

func (*ConnectionsHandler) Put

Put creates or replaces a connection, then restarts the running flows that use it so they run with the new settings (ADR-0029).

func (*ConnectionsHandler) RegisterRoutes

func (h *ConnectionsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the connection routes.

func (*ConnectionsHandler) Test

Test tries the settings sent (with the stored password when none is sent) without storing them, and answers {ok, error}.

func (*ConnectionsHandler) WithFlows

WithFlows makes a change restart the running flows that use the connection and refuses deleting one a running flow uses.

type CreatedAgentToken

type CreatedAgentToken struct {
	Token string           `json:"token"`
	Info  storage.APIToken `json:"info"`
}

CreatedAgentToken is the POST /api/agent/tokens payload. Token is the plaintext, returned only here.

type DeployRequest

type DeployRequest struct {
	Version int `json:"version,omitempty"`
}

DeployRequest is the optional request body of a deploy: the definition version the client shows (0 or absent: no check).

type DraftService

type DraftService interface {
	ListDrafts(ctx context.Context, actor service.Actor, q service.DraftQuery) (service.DraftList, error)
	GetDraftDetail(ctx context.Context, actor service.Actor, draftID string) (service.DraftDetail, error)
	ApproveDraft(ctx context.Context, actor service.Actor, draftID string, deploy bool) (service.ApplyResult, error)
	RejectDraft(ctx context.Context, actor service.Actor, draftID, reason string) error
	Rollback(ctx context.Context, actor service.Actor, flowID string) (service.ApplyResult, error)
	Versions(ctx context.Context, actor service.Actor, flowID string, limit int) (service.VersionList, error)
}

DraftService is the editor's side of drafts and versions (*service.Authoring).

type DraftsHandler

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

DraftsHandler serves /api/agent/drafts* and /api/flows/{id}/versions and /rollback.

func NewDraftsHandler

func NewDraftsHandler(svc DraftService, logger zerolog.Logger) *DraftsHandler

NewDraftsHandler returns the drafts and versions handler.

func (*DraftsHandler) Approve

func (h *DraftsHandler) Approve(w http.ResponseWriter, r *http.Request)

Approve saves a pending draft as a new admin-approved version and, when asked or when the flow runs, deploys it. POST /api/agent/drafts/{id}/approve {"deploy": bool}

func (*DraftsHandler) Get

Get shows one draft with its diff and alerts. GET /api/agent/drafts/{id}

func (*DraftsHandler) List

func (h *DraftsHandler) List(w http.ResponseWriter, r *http.Request)

List lists drafts, newest first. GET /api/agent/drafts?status=pending|decided|all&limit=&beforeId=

func (*DraftsHandler) RegisterRoutes

func (h *DraftsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the drafts routes (they exist only with authentication, like every /api/agent route).

func (*DraftsHandler) RegisterVersionRoutes

func (h *DraftsHandler) RegisterVersionRoutes(r *mux.Router)

RegisterVersionRoutes registers the version history and rollback routes.

func (*DraftsHandler) Reject

func (h *DraftsHandler) Reject(w http.ResponseWriter, r *http.Request)

Reject rejects a pending draft. POST /api/agent/drafts/{id}/reject {"reason"?}

func (*DraftsHandler) Rollback

func (h *DraftsHandler) Rollback(w http.ResponseWriter, r *http.Request)

Rollback restores the version the admin last approved as a new version, redeploying a running flow. POST /api/flows/{id}/rollback

func (*DraftsHandler) Versions

func (h *DraftsHandler) Versions(w http.ResponseWriter, r *http.Request)

Versions lists a flow's versions, newest first. GET /api/flows/{id}/versions?limit=

type EventsHandler

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

EventsHandler serves the live SSE stream of node-execution events plus the persisted run/event history.

func NewEventsHandler

func NewEventsHandler(hub *events.Hub, store HistoryReader, logger zerolog.Logger) *EventsHandler

NewEventsHandler creates a new EventsHandler.

func (*EventsHandler) ListRunEvents

func (h *EventsHandler) ListRunEvents(w http.ResponseWriter, r *http.Request)

ListRunEvents returns the node events for a single run. GET /api/flows/{id}/runs/{runId}/events

func (*EventsHandler) ListRuns

func (h *EventsHandler) ListRuns(w http.ResponseWriter, r *http.Request)

ListRuns returns a flow's recent runs. GET /api/flows/{id}/runs?limit=&offset=

func (*EventsHandler) RegisterRoutes

func (h *EventsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the observability routes on the given router.

func (*EventsHandler) StreamEvents

func (h *EventsHandler) StreamEvents(w http.ResponseWriter, r *http.Request)

StreamEvents streams a flow's live node-execution events as Server-Sent Events. GET /api/flows/{id}/events

type FlowAssistant

type FlowAssistant interface {
	ProposeFlow(ctx context.Context, req service.AssistantFlowRequest) (service.AssistantFlowResult, error)
}

FlowAssistant proposes a flow from a description (*service.Assistant, docs/design/llm.md §7, ADR-0041).

type FlowDetailResponse

type FlowDetailResponse struct {
	Flow    service.FlowWithMarks `json:"flow"`
	Running bool                  `json:"running"`
}

FlowDetailResponse is GET /api/flows/{id}: the flow with its marks.

type FlowLister

type FlowLister interface {
	ListFlows(state *flow.FlowState) ([]*flow.Flow, error)
}

FlowLister lists the stored flows (the SQLite store implements it).

type FlowReader

type FlowReader interface {
	GetFlow(id string) (*flow.Flow, error)
}

FlowReader reads one stored flow (the node test's flow context).

type FlowRef

type FlowRef = service.FlowRef

FlowRef names a flow in a response.

type FlowRestartFailure

type FlowRestartFailure = service.FlowRestartFailure

FlowRestartFailure is a flow that a restart stopped and could not deploy again.

type FlowStatusResponse

type FlowStatusResponse struct {
	Flow    *flow.Flow `json:"flow"`
	Running bool       `json:"running"`
	// Warnings, on a deploy (POST /deploy, or a toggle that deploys), are
	// what the flow deployed with but the admin should know: the warning
	// issues the deploy found (FlowRuntime.Warnings, Lint's), such as an undefined secret an
	// optional credential references (unresolved_secret, with the secret's
	// name in its secret field). Always a list:
	// empty when there are none and on a stop.
	Warnings []flow.DeployWarning `json:"warnings"`
}

FlowStatusResponse contains the status of a flow.

type FlowStore

type FlowStore interface {
	service.MarksStore
	ListFlows(state *flow.FlowState) ([]*flow.Flow, error)
	GetFlow(id string) (*flow.Flow, error)
	CreateFlow(f *flow.Flow) error
	UpdateFlowVersioned(f *flow.Flow, expected int, meta storage.VersionMeta) (int, error)
	DeleteFlow(id string) error
}

FlowStore is what the flow routes store.

type FlowsHandler

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

FlowsHandler handles HTTP requests for flow operations.

func NewFlowsHandler

func NewFlowsHandler(store FlowStore, lifecycle *service.Lifecycle, registry *node.Registry, logger zerolog.Logger, flowVars *flowvars.FlowStores) *FlowsHandler

NewFlowsHandler creates the editor's flow routes over the lifecycle path. flowVars are the per-flow variable stores of the runtimes lifecycle deploys.

func (*FlowsHandler) CreateFlow

func (h *FlowsHandler) CreateFlow(w http.ResponseWriter, r *http.Request)

CreateFlow creates a new flow. POST /api/flows

func (*FlowsHandler) DeleteFlow

func (h *FlowsHandler) DeleteFlow(w http.ResponseWriter, r *http.Request)

DeleteFlow deletes a flow. DELETE /api/flows/{id}

func (*FlowsHandler) DeployFlow

func (h *FlowsHandler) DeployFlow(w http.ResponseWriter, r *http.Request)

DeployFlow deploys a saved definition; repeated explicit deployment conflicts. An optional body {"version": N} names the version the client shows: a stale one is a 409 with the current version, so nobody deploys a definition they never saw (an approved draft or an agent's version saved meanwhile). Without it there is no check.

func (*FlowsHandler) DuplicateFlow

func (h *FlowsHandler) DuplicateFlow(w http.ResponseWriter, r *http.Request)

DuplicateFlow creates an inactive copy of an existing flow under a new ID. POST /api/flows/{id}/duplicate

func (*FlowsHandler) ExportFlow

func (h *FlowsHandler) ExportFlow(w http.ResponseWriter, r *http.Request)

ExportFlow returns a flow's portable JSON definition for download. GET /api/flows/{id}/export

func (*FlowsHandler) FlowVariables

func (h *FlowsHandler) FlowVariables(w http.ResponseWriter, r *http.Request)

FlowVariables serializes management with flow deletion and validates ownership.

func (*FlowsHandler) GetFlow

func (h *FlowsHandler) GetFlow(w http.ResponseWriter, r *http.Request)

GetFlow returns a specific flow by ID. GET /api/flows/{id}

func (*FlowsHandler) ImportFlow

func (h *FlowsHandler) ImportFlow(w http.ResponseWriter, r *http.Request)

ImportFlow creates a new flow from an uploaded definition, always assigning a fresh ID so an import never clobbers an existing flow. POST /api/flows/import

func (*FlowsHandler) InjectNode

func (h *FlowsHandler) InjectNode(w http.ResponseWriter, r *http.Request)

InjectNode triggers a manual trigger node in a running flow. POST /api/flows/{id}/inject/{nodeId}

func (*FlowsHandler) ListFlows

func (h *FlowsHandler) ListFlows(w http.ResponseWriter, r *http.Request)

ListFlows returns all flows. GET /api/flows

func (*FlowsHandler) RegisterRoutes

func (h *FlowsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the flow routes on the given router.

func (*FlowsHandler) StopFlow

func (h *FlowsHandler) StopFlow(w http.ResponseWriter, r *http.Request)

StopFlow stops a running flow and removes its restart intent.

func (*FlowsHandler) ToggleFlow

func (h *FlowsHandler) ToggleFlow(w http.ResponseWriter, r *http.Request)

ToggleFlow toggles a flow on or off. PATCH /api/flows/{id}/toggle

func (*FlowsHandler) UpdateFlow

func (h *FlowsHandler) UpdateFlow(w http.ResponseWriter, r *http.Request)

UpdateFlow updates an existing flow. PUT /api/flows/{id}

type HealthHandler

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

HealthHandler handles health check requests.

func NewHealthHandler

func NewHealthHandler(store HealthStore) *HealthHandler

NewHealthHandler creates a new HealthHandler.

func (*HealthHandler) Health

func (h *HealthHandler) Health(w http.ResponseWriter, r *http.Request)

Health returns the health status of the API. GET /api/health

type HealthStore

type HealthStore interface {
	IsClosed() bool
}

HealthStore tells whether the storage is still open.

type HistoryReader

type HistoryReader interface {
	ListFlowRuns(flowID string, limit, offset int) ([]storage.FlowRun, error)
	ListFlowRunEvents(flowID, runID string) ([]storage.NodeEventRecord, error)
}

HistoryReader reads the recorded runs and their node events.

type HostGuard

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

HostGuard rejects requests whose Host header is not a name of this server. It defeats DNS rebinding: a malicious page whose DNS name is re-pointed at PiWorker still sends its own name ("Host: attacker.example"), so it cannot use the browser to reach the API, the MCP endpoint or the web UI.

Accepted: localhost, the hostname, <hostname>.local (also for the first label of a dotted hostname), the current interface addresses, the configured AllowedHosts, and any IP literal (rebinding needs a DNS name, and a page served from an IP address is same-origin with it anyway).

func NewHostGuard

func NewHostGuard(opts HostGuardOptions) *HostGuard

NewHostGuard builds a HostGuard. Nothing is read from the system until the first request needs it.

func (*HostGuard) Allowed

func (g *HostGuard) Allowed(host string) bool

Allowed reports whether host (a Host header value, with or without port) names this server.

func (*HostGuard) Middleware

func (g *HostGuard) Middleware(next http.Handler) http.Handler

Middleware rejects requests with an unknown Host with a 403 JSON error, except on the webhook endpoints and the CA certificate download, which external devices reach under any name.

func (*HostGuard) Names

func (g *HostGuard) Names() []string

Names returns every accepted name (besides arbitrary IP literals), sorted; useful for logging what the guard accepts.

type HostGuardOptions

type HostGuardOptions struct {
	// AllowedHosts are extra accepted names (allowed_hosts); a port and a
	// trailing dot are ignored, and matching is case-insensitive.
	AllowedHosts []string
	// Hostname returns the machine's name (default os.Hostname).
	Hostname func() (string, error)
	// Interfaces returns the machine's addresses (default: every interface).
	Interfaces func() ([]net.IP, error)
	// Now is the clock used for the cache (default time.Now).
	Now func() time.Time
	// CacheTTL is how long Hostname/Interfaces results are reused
	// (default DefaultHostCacheTTL).
	CacheTTL time.Duration
}

HostGuardOptions configures a HostGuard. Zero values use the real machine.

type InjectRequest

type InjectRequest struct {
	Payload interface{} `json:"payload,omitempty"`
}

InjectRequest is the request body for injecting a message into a manual trigger.

type KnowledgeBase

type KnowledgeBase interface {
	Collections() []llm.CollectionInfo
	Collection(name string) (llm.CollectionInfo, bool)
	Documents(collection string, offset, limit int) ([]llm.Document, int)
	Delete(collection, id string) error
	DeleteCollection(collection string) error
}

KnowledgeBase is the knowledge base (ADR-0038) the editor browses and prunes.

type KnowledgeCollectionsResponse

type KnowledgeCollectionsResponse struct {
	Collections []llm.CollectionInfo `json:"collections"`
}

KnowledgeCollectionsResponse is GET /api/llm/knowledge's answer, sorted by name.

type KnowledgeDocumentPage

type KnowledgeDocumentPage struct {
	Documents []llm.Document `json:"documents"`
	Total     int            `json:"total"`
}

KnowledgeDocumentPage is a page of a collection's documents (oldest first; never their embeddings) and how many it holds.

type LLMConnectionItem

type LLMConnectionItem struct {
	Name     string `json:"name"`
	Provider string `json:"provider"`
	// BaseURL is "" for the provider's default endpoint.
	BaseURL   string `json:"baseUrl"`
	HasAPIKey bool   `json:"hasApiKey"`
	Model     string `json:"model"`
	// DailyTokenLimit caps input plus output tokens per local day (0: none).
	DailyTokenLimit int64     `json:"dailyTokenLimit"`
	UsageToday      llm.Usage `json:"usageToday"`
}

LLMConnectionItem is an LLM connection as the API shows it: never its API key, only whether one is stored, and what it used today.

type LLMConnectionTest

type LLMConnectionTest struct {
	OK     bool            `json:"ok"`
	Error  string          `json:"error,omitempty"`
	Models []llm.ModelInfo `json:"models,omitempty"`
}

LLMConnectionTest is a test's answer: whether the models could be listed with the settings sent, why not, and the models.

type LLMConnectionUsers

type LLMConnectionUsers interface {
	// UnlessRunningFlowsUseLLMConnection runs fn (the deletion of the LLM
	// connection name) under the lifecycle lock unless a running flow uses
	// the connection; then it returns those flows and fn does not run.
	UnlessRunningFlowsUseLLMConnection(name string, fn func() error) ([]FlowRef, error)
}

LLMConnectionUsers is the lifecycle path as the LLM connections see it.

type LLMConnectionsHandler

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

LLMConnectionsHandler manages the named LLM connections (ADR-0038, docs/design/llm.md §6). API keys are write-only: set, replaced or cleared, never returned. Changing a connection restarts nothing: the nodes resolve it on every call.

func NewLLMConnectionsHandler

func NewLLMConnectionsHandler(store *llm.Store, secretStore *secrets.Store, logger zerolog.Logger) *LLMConnectionsHandler

NewLLMConnectionsHandler creates an LLMConnectionsHandler over the connections in store, resolving secret references in keys through secretStore (nil: none).

func (*LLMConnectionsHandler) Delete

Delete removes a connection, unless a running flow uses it (409, with the flows in data.flows): the flow would fail on its next call. Stopped flows that name it are refused at their next deploy (undefined_llm_connection).

func (*LLMConnectionsHandler) List

List returns the connections sorted by name, with today's usage.

func (*LLMConnectionsHandler) Models

Models lists the models of a stored connection (the editor's suggestions for a node's model): 404 for an unknown connection, 400 when its client cannot be built, 502 when the provider fails (its message, redacted).

func (*LLMConnectionsHandler) Put

Put creates or replaces a connection and answers it as stored.

func (*LLMConnectionsHandler) RegisterRoutes

func (h *LLMConnectionsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the LLM connection routes.

func (*LLMConnectionsHandler) Test

Test lists the models with the settings sent (the stored key when none is sent) without storing them, and answers {ok, error, models}: a listing checks the endpoint, the key and the provider without spending tokens. Errors never hold the key (the clients redact it).

func (*LLMConnectionsHandler) WithFlows

WithFlows refuses deleting a connection a running flow uses (the lifecycle path, service.Lifecycle).

type LLMConnectionsResponse

type LLMConnectionsResponse struct {
	Connections []LLMConnectionItem `json:"connections"`
}

LLMConnectionsResponse is GET /api/llm/connections' answer.

type LLMConversation

type LLMConversation struct {
	Key   string     `json:"key"`
	Turns []llm.Turn `json:"turns"`
}

LLMConversation is one conversation's turns, oldest first (text only).

type LLMConversations

type LLMConversations interface {
	List() []llm.ConversationInfo
	Turns(key string) []llm.Turn
	Clear(key string) error
}

LLMConversations is the conversation memory (ADR-0038) the editor lists, reads and clears.

type LLMConversationsResponse

type LLMConversationsResponse struct {
	Conversations []llm.ConversationInfo `json:"conversations"`
}

LLMConversationsResponse is GET /api/llm/conversations' answer, sorted by key.

type LLMMemoryHandler

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

LLMMemoryHandler shows and clears what the LLM nodes keep (ADR-0038, docs/design/llm.md §6): the conversations of the memory and the collections of the knowledge base. Conversation keys hold ':' and '/' and document IDs '#' and '/': the editor path-escapes them, the router matches the decoded path, so their routes take the rest of the path. The app's router cleans paths as sent (CleanPathsAsSent): a key or ID that holds "//" or ".." once decoded is never redirected to another one.

func NewLLMMemoryHandler

func NewLLMMemoryHandler(memory LLMConversations, knowledge KnowledgeBase, logger zerolog.Logger) *LLMMemoryHandler

NewLLMMemoryHandler creates an LLMMemoryHandler.

func (*LLMMemoryHandler) ClearConversation

func (h *LLMMemoryHandler) ClearConversation(w http.ResponseWriter, r *http.Request)

ClearConversation deletes a conversation: its next message starts afresh.

func (*LLMMemoryHandler) DeleteCollection

func (h *LLMMemoryHandler) DeleteCollection(w http.ResponseWriter, r *http.Request)

DeleteCollection deletes a collection and its documents.

func (*LLMMemoryHandler) DeleteDocument

func (h *LLMMemoryHandler) DeleteDocument(w http.ResponseWriter, r *http.Request)

DeleteDocument deletes one document of a collection (deleting one that is already gone succeeds: the knowledge base cannot tell it cheaply).

func (*LLMMemoryHandler) GetConversation

func (h *LLMMemoryHandler) GetConversation(w http.ResponseWriter, r *http.Request)

GetConversation answers one conversation's turns; 404 when it has none.

func (*LLMMemoryHandler) ListCollections

func (h *LLMMemoryHandler) ListCollections(w http.ResponseWriter, _ *http.Request)

ListCollections lists the knowledge base's collections.

func (*LLMMemoryHandler) ListConversations

func (h *LLMMemoryHandler) ListConversations(w http.ResponseWriter, _ *http.Request)

ListConversations lists the stored conversations.

func (*LLMMemoryHandler) ListDocuments

func (h *LLMMemoryHandler) ListDocuments(w http.ResponseWriter, r *http.Request)

ListDocuments answers a page of a collection's documents (?offset=&limit=, limit at most 100; 50 when absent or 0).

func (*LLMMemoryHandler) RegisterRoutes

func (h *LLMMemoryHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the conversation and knowledge base routes.

type LLMModelsResponse

type LLMModelsResponse struct {
	Models []llm.ModelInfo `json:"models"`
}

LLMModelsResponse is GET /api/llm/connections/{name}/models' answer.

type ListFlowsResponse

type ListFlowsResponse struct {
	Flows []service.FlowWithMarks `json:"flows"`
	Total int                     `json:"total"`
}

ListFlowsResponse contains the list of flows, each with its marks (the last deployment and whether an agent changed it, docs/design/mcp.md §10).

type ListNodeTypesResponse

type ListNodeTypesResponse struct {
	NodeTypes []NodeTypeResponse `json:"nodeTypes"`
	Total     int                `json:"total"`
}

ListNodeTypesResponse contains the list of available node types.

type LoginRequest

type LoginRequest struct {
	Username        string `json:"username"`
	Password        string `json:"password"`
	Code            string `json:"code"`
	CurrentPassword string `json:"currentPassword"`
	// KeepAgentTokens keeps agent API tokens valid across a password change.
	KeepAgentTokens bool `json:"keepAgentTokens"`
}

type NodeTypeResponse

type NodeTypeResponse struct {
	Type          string             `json:"type"`
	Name          string             `json:"name"`
	Description   string             `json:"description"`
	Documentation string             `json:"documentation,omitempty"`
	Category      string             `json:"category"`
	Inputs        []PortResponse     `json:"inputs"`
	Outputs       []PortResponse     `json:"outputs"`
	Config        *node.ConfigSchema `json:"config,omitempty"`
	Icon          string             `json:"icon,omitempty"`
	// Risk is what the type can affect outside the flow (node.Risk: safe,
	// external, privileged), as agents and the node reference see it; the
	// editor shows it in the palette and the settings panel. A node's own
	// settings can raise its instance's risk (flow.Risk), never lower it.
	Risk string `json:"risk"`
	// RiskCanRise: a setting can raise an instance above Risk
	// (flow.RiskCanRise), so the editor can say so where it is true.
	RiskCanRise bool `json:"riskCanRise"`
	// OutputsFrom names the array setting whose items are extra output
	// ports after Outputs (ADR-0040): the editor renders them from the
	// node's config. Omitted for the other types.
	OutputsFrom string `json:"outputsFrom,omitempty"`
}

NodeTypeResponse represents a node type in API responses.

type NodeTypesHandler

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

NodeTypesHandler handles HTTP requests for node type operations.

func NewNodeTypesHandler

func NewNodeTypesHandler(registry *node.Registry, logger zerolog.Logger, stores ...FlowReader) *NodeTypesHandler

NewNodeTypesHandler creates a new NodeTypesHandler. stores, when given, is the store a node test checks its flow in.

func (*NodeTypesHandler) GetNodeType

func (h *NodeTypesHandler) GetNodeType(w http.ResponseWriter, r *http.Request)

GetNodeType returns a specific node type by type identifier. GET /api/node-types/{type}

func (*NodeTypesHandler) ListNodeTypes

func (h *NodeTypesHandler) ListNodeTypes(w http.ResponseWriter, r *http.Request)

ListNodeTypes returns all available node types. GET /api/node-types

func (*NodeTypesHandler) RegisterRoutes

func (h *NodeTypesHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the node type routes on the given router.

func (*NodeTypesHandler) TestNode

func (h *NodeTypesHandler) TestNode(w http.ResponseWriter, r *http.Request)

TestNode runs a single node once against a sample payload, without deploying a flow, so the editor can preview a node's behaviour. It is restricted to the processing category in v1: action/trigger nodes have real side effects (HTTP calls, shell commands, emails) that a "test" must not fire blindly. POST /api/nodes/{type}/test

func (*NodeTypesHandler) WithVariables

func (h *NodeTypesHandler) WithVariables(globals *flowvars.Store, flowVars *flowvars.FlowStores) *NodeTypesHandler

WithVariables makes node tests preview these global and per-flow variables.

type PendingApprovalsCount

type PendingApprovalsCount struct {
	Pending int `json:"pending"`
	Drafts  int `json:"drafts"`
}

PendingApprovalsCount is the GET PendingApprovalsCountPath payload: the approvals and the agent drafts awaiting the admin.

type PortResponse

type PortResponse struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	DataType string `json:"dataType"`
	Multiple bool   `json:"multiple"`
	Required bool   `json:"required"`
}

PortResponse represents a port in API responses.

type RejectDraftRequest

type RejectDraftRequest struct {
	Reason string `json:"reason,omitempty"`
}

RejectDraftRequest is the body of a rejection: the reason shown to the agent.

type RejectionTotals

type RejectionTotals struct {
	Totals    []storage.MCPRejectionTotal `json:"totals"`
	Truncated bool                        `json:"truncated"`
}

RejectionTotals is the GET /api/agent/audit/rejections payload. Truncated reports that only the storage.MaxMCPRejectionTotals largest totals are listed.

type RemoteRequest

type RemoteRequest struct {
	backup.RemoteSettings
	SecretKey  string `json:"secretKey"`
	Passphrase string `json:"passphrase"`
	Password   string `json:"password"`
}

RemoteRequest is the remote destination with its write-only secrets (empty keeps the stored ones) and the account password.

type ResponseWriter

type ResponseWriter struct {
	http.ResponseWriter
	StatusCode int
}

ResponseWriter wraps http.ResponseWriter to capture status code.

func (*ResponseWriter) Flush

func (w *ResponseWriter) Flush()

Flush delegates to the underlying writer's Flusher so streaming handlers (Server-Sent Events) keep working when wrapped by logging/metrics middleware. Without this, the embedded http.ResponseWriter's Flush is not promoted (the interface has no Flush method) and the SSE handler's http.Flusher assertion fails.

func (*ResponseWriter) Unwrap

func (w *ResponseWriter) Unwrap() http.ResponseWriter

Unwrap lets http.ResponseController reach the underlying connection through the logging and metrics wrappers (for example, to manage SSE deadlines).

func (*ResponseWriter) WriteHeader

func (w *ResponseWriter) WriteHeader(code int)

WriteHeader captures the status code and delegates to the underlying writer.

type RevokedTokens

type RevokedTokens struct {
	Revoked int `json:"revoked"`
}

RevokedTokens is the POST /api/agent/tokens/revoke-all payload: how many active tokens were revoked (expired ones are revoked too, uncounted).

type RunEventsResponse

type RunEventsResponse struct {
	Events []storage.NodeEventRecord `json:"events"`
}

RunEventsResponse is the payload for a single run's node events.

type RunsResponse

type RunsResponse struct {
	Runs []storage.FlowRun `json:"runs"`
}

RunsResponse is the payload for the run-history listing.

type SecretItem

type SecretItem struct {
	Name  string      `json:"name"`
	Short bool        `json:"short"`
	Uses  []SecretUse `json:"uses,omitempty"` // with ?usage=1; omitted when none
}

SecretItem is a stored secret as the listing shows it: its name, whether its value is short (secrets.IsShort) and where it is used, never the value or its length.

type SecretUse

type SecretUse struct {
	FlowID        string `json:"flowId,omitempty"`
	FlowName      string `json:"flowName,omitempty"`
	FlowRunning   bool   `json:"flowRunning,omitempty"`
	NodeID        string `json:"nodeId,omitempty"`
	NodeType      string `json:"nodeType,omitempty"`
	NodeDisabled  bool   `json:"nodeDisabled,omitempty"`
	Connection    string `json:"connection,omitempty"`
	LLMConnection string `json:"llmConnection,omitempty"`
	Setting       string `json:"setting"`
}

SecretUse is one place a secret is referenced ({{secret.NAME}}): a node setting of a flow (FlowID, FlowName, NodeID, NodeType, Setting; NodeDisabled when the node does not run; FlowRunning when the flow is deployed), a broker connection's credential (Connection, Setting) or an LLM connection's API key (LLMConnection, Setting "apiKey"). Connections are always in use: a node resolves them, and their secrets, when it runs.

type SecretsHandler

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

SecretsHandler exposes CRUD for named secrets. Values are write-only over the API: they can be set, but the listing returns names and short marks only, never values or lengths.

func NewSecretsHandler

func NewSecretsHandler(store *secrets.Store, logger zerolog.Logger) *SecretsHandler

NewSecretsHandler creates a new SecretsHandler.

func (*SecretsHandler) DeleteSecret

func (h *SecretsHandler) DeleteSecret(w http.ResponseWriter, r *http.Request)

DeleteSecret removes a secret.

func (*SecretsHandler) ListSecrets

func (h *SecretsHandler) ListSecrets(w http.ResponseWriter, r *http.Request)

ListSecrets returns the stored secrets, each marked short or not, so the editor can tell the admin which values an agent could confirm a guess of (ADR-0021), and where each is used (WithUsage), so deleting or renaming one is not a surprise. Uses are listed broker connections first (by name), then LLM connections (by name), then flows (by name, then node order).

Uses are computed only with ?usage=1 (the Secrets dialog): they read every stored flow, and the editor lists the names on every node it selects.

func (*SecretsHandler) RegisterRoutes

func (h *SecretsHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the secret routes on the given router.

func (*SecretsHandler) SetSecret

func (h *SecretsHandler) SetSecret(w http.ResponseWriter, r *http.Request)

SetSecret stores or replaces a secret value.

func (*SecretsHandler) WithLLMConnections

func (h *SecretsHandler) WithLLMConnections(conns *llm.Store) *SecretsHandler

WithLLMConnections makes the usage listing also name the LLM connections of conns (ADR-0038) whose API key references a secret (nil: none).

func (*SecretsHandler) WithUsage

func (h *SecretsHandler) WithUsage(flows FlowLister, conns *brokers.Store) *SecretsHandler

WithUsage makes the listing say where each secret is referenced: in the settings of the flows of flows and in the credentials of the broker connections of conns (either may be nil).

type SecretsListResponse

type SecretsListResponse struct {
	Secrets    []SecretItem      `json:"secrets"`
	Undefined  []UndefinedSecret `json:"undefined,omitempty"` // with ?usage=1; omitted when none
	ShortBelow int               `json:"shortBelow"`
}

SecretsListResponse lists the stored secrets by name with where each is used, and the references to secrets that are not defined. ShortBelow is the threshold (secrets.ShortValueRunes) the editor names when it asks for a longer value.

type StoresBackupHandler

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

StoresBackupHandler exports and restores the global and flow variables, the broker and LLM connections and the secrets (internal/storesbackup).

func NewStoresBackupHandler

func NewStoresBackupHandler(opts StoresBackupOptions) *StoresBackupHandler

NewStoresBackupHandler creates the handler.

func (*StoresBackupHandler) Export

Export answers the stores file as an attachment (the bundle itself, not the {success, data} envelope). Without a passphrase it carries no secret value, password or API key. With one, the account password must be confirmed: secrets are otherwise write-only, and a stolen session must not read them all in one request. With authentication disabled such an export is refused (403).

func (*StoresBackupHandler) Import

Import restores a stores file. A wrong passphrase or an invalid file is a 400 and writes nothing; the report counts what was added, replaced and kept, and never echoes a value.

func (*StoresBackupHandler) RegisterRoutes

func (h *StoresBackupHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the routes.

type StoresBackupOptions

type StoresBackupOptions struct {
	Flows         FlowLister       // the flows whose variables are exported
	Globals       *vars.Store      // global variables
	FlowVariables *vars.FlowStores // each flow's variables
	Secrets       *secrets.Store
	Connections   *brokers.Store
	// LLMConnections are exported like the broker connections, the API key
	// only sealed (ADR-0038); nil leaves them out of exports and skips them
	// on import.
	LLMConnections *llm.Store
	// Auth verifies the account password before secret values leave the
	// device; nil (authentication disabled) refuses such an export.
	Auth *AuthHandler
	// Restarter restarts the running flows that use a connection the
	// import changed (ADR-0029); nil restarts nothing.
	Restarter ConnectionUsers
	Logger    zerolog.Logger
}

StoresBackupOptions wires the export and restore of the stores (ADR-0031).

type StoresExportRequest

type StoresExportRequest struct {
	Passphrase string `json:"passphrase"`
	Password   string `json:"password"`
}

StoresExportRequest is POST /api/stores/export's body. With a passphrase the secret values and the connections with their passwords and API keys are sealed in the file, which needs the account password (step-up).

type StoresImportRequest

type StoresImportRequest struct {
	Bundle     *storesbackup.Bundle `json:"bundle"`
	Passphrase string               `json:"passphrase"`
	Overwrite  bool                 `json:"overwrite"`
}

StoresImportRequest is POST /api/stores/import's body: the file, the passphrase that opens its sealed part (empty: restore the readable part only) and whether existing values are replaced.

type StoresImportResponse

type StoresImportResponse struct {
	Report storesbackup.Report `json:"report"`
	ConnectionStoredResponse
}

StoresImportResponse is what the import did, and the running flows it restarted because a connection they use changed.

type TLSHandler

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

TLSHandler serves the CA certificate download and the TLS status.

func NewTLSHandler

func NewTLSHandler(mode string, status func() tlsca.Status, caPEM []byte) *TLSHandler

NewTLSHandler creates a handler for the given tls.mode. status is nil when TLS is off; caPEM is nil without a local CA (custom or off).

func (*TLSHandler) CACert

func (h *TLSHandler) CACert(w http.ResponseWriter, r *http.Request)

CACert returns the CA certificate in PEM form. The x509-ca-cert media type lets Firefox, iOS and Android offer their certificate import flow directly.

func (*TLSHandler) RegisterRoutes

func (h *TLSHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the CA download (public) and /api/tls (behind the API's authentication).

func (*TLSHandler) SetPorts

func (h *TLSHandler) SetPorts(httpsPort, httpPort int)

SetPorts records the ports the listeners are bound to (0 = not served), once they are known: HTTPS, and plain HTTP.

func (*TLSHandler) Status

func (h *TLSHandler) Status(w http.ResponseWriter, r *http.Request)

Status returns the TLS mode, CA fingerprint and server certificate details. GET /api/tls

type TLSInfo

type TLSInfo struct {
	Mode          string     `json:"mode"`
	CAFingerprint string     `json:"caFingerprint"`
	SANs          []string   `json:"sans"`
	NotAfter      *time.Time `json:"notAfter"`
	CACertURL     string     `json:"caCertUrl"`
	// HTTPSPort is the port HTTPS is served on; null when TLS is off or the
	// port is not known yet.
	HTTPSPort *int `json:"httpsPort"`
	// HTTPPort is the plain HTTP port (the redirect listener, or the main
	// listener when TLS is off); null when there is none.
	HTTPPort *int `json:"httpPort"`
	// Warning tells the admin the local CA is about to expire (or expired).
	Warning string `json:"warning,omitempty"`
}

TLSInfo is the GET /api/tls payload: how this server is reached over HTTPS and what a client must trust.

type TestNodeRequest

type TestNodeRequest struct {
	FlowID  string                 `json:"flowId,omitempty"`
	Config  map[string]interface{} `json:"config"`
	Payload interface{}            `json:"payload"`
	Topic   string                 `json:"topic,omitempty"`
	Meta    map[string]interface{} `json:"meta,omitempty"`
}

TestNodeRequest is the body of a test-node request: the candidate config and a sample input payload.

type TestNodeResult

type TestNodeResult struct {
	Outputs []*types.Message `json:"outputs"`
	Error   string           `json:"error,omitempty"`
	DurMs   float64          `json:"durMs"`
}

TestNodeResult is the outcome of a one-shot node execution.

type ToggleRequest

type ToggleRequest struct {
	Enabled bool `json:"enabled"`
	Version int  `json:"version,omitempty"`
}

ToggleRequest is the request body for toggling a flow. Version, when set, is the definition version the client shows: turning the flow on fails with 409 when another one was saved since.

type ToolCallErrorData

type ToolCallErrorData struct {
	Code           string             `json:"code"`
	Issues         []toolschema.Issue `json:"issues,omitempty"`
	FlowIssues     []flow.Issue       `json:"flowIssues,omitempty"`
	CurrentVersion int                `json:"currentVersion,omitempty"`
	RetryAfterMs   int64              `json:"retryAfterMs,omitempty"`
}

ToolCallErrorData is the data of a refused service call (a tool call, and the authoring and deploy operations): the error kind's code, the schema issues of invalid arguments, a flow's Lint issues, the current version of a stale base version, and how long a cooldown lasts.

type ToolCallHandler

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

ToolCallHandler is the editor's REST twin of an MCP tool call ("Test tool"): the same service call as an agent's, as the editor actor, so the input schema, concurrency limits and cooldown apply but confirm does not.

func NewToolCallHandler

func NewToolCallHandler(tools ToolCaller, logger zerolog.Logger) *ToolCallHandler

NewToolCallHandler returns the REST twin handler.

func (*ToolCallHandler) Call

Call runs the tool of a trigger-tool node with the given arguments and answers its flow.CallResult. POST /api/flows/{id}/call/{nodeId} {"args": {…}}

func (*ToolCallHandler) RegisterRoutes

func (h *ToolCallHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers POST /api/flows/{id}/call/{nodeId}.

type ToolCallRequest

type ToolCallRequest struct {
	Args map[string]any `json:"args"`
}

ToolCallRequest is the body of a test call; no body means no arguments.

type ToolCaller

type ToolCaller interface {
	Call(ctx context.Context, actor service.Actor, ref service.ToolRef, args map[string]any) (flow.CallResult, error)
}

ToolCaller calls a published tool (*service.Tools).

type ToolLister

type ToolLister interface {
	Tools() (uint64, []flow.ToolInfo)
	GetRuntime(flowID string) (*flow.FlowRuntime, bool)
}

ToolLister lists the tools of running flows (*flow.RuntimeManager).

type UndefinedSecret

type UndefinedSecret struct {
	Name string      `json:"name"`
	Uses []SecretUse `json:"uses"`
}

UndefinedSecret is a secret name referenced somewhere that the store does not define, with the places that reference it.

type VariablesHandler

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

VariablesHandler manages the same global store used by Get/Set Variable nodes. Values are ordinary JSON data; credential values belong in the secret store.

func NewVariablesHandler

func NewVariablesHandler(store *flowvars.Store) *VariablesHandler

func (*VariablesHandler) Delete

func (h *VariablesHandler) Delete(w http.ResponseWriter, r *http.Request)

func (*VariablesHandler) List

func (*VariablesHandler) RegisterRoutes

func (h *VariablesHandler) RegisterRoutes(r *mux.Router)

func (*VariablesHandler) Set

type VersionConflictData

type VersionConflictData struct {
	CurrentVersion int `json:"currentVersion"`
}

VersionConflictData is the data of a 409 from a save whose version is not the stored one.

type ZigbeeHandler

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

ZigbeeHandler serves device discovery for the editor and the bridge's permit join (docs/design/zigbee.md, phase 2). Admin session only; no MCP tool reaches it.

func NewZigbeeHandler

func NewZigbeeHandler(nets ZigbeeNetworks) *ZigbeeHandler

NewZigbeeHandler creates a ZigbeeHandler.

func (*ZigbeeHandler) Get

Get returns one connection's network.

func (*ZigbeeHandler) List

func (h *ZigbeeHandler) List(w http.ResponseWriter, _ *http.Request)

List returns the network of every connection.

func (*ZigbeeHandler) PermitJoin

func (h *ZigbeeHandler) PermitJoin(w http.ResponseWriter, r *http.Request)

PermitJoin opens the network to new devices for seconds (0 closes it).

func (*ZigbeeHandler) RegisterRoutes

func (h *ZigbeeHandler) RegisterRoutes(r *mux.Router)

RegisterRoutes registers the Zigbee routes.

type ZigbeeNetworks

type ZigbeeNetworks interface {
	Connections() []string
	Network(name string) (zigbee.Network, bool)
	PermitJoin(name string, seconds int) error
}

ZigbeeNetworks is what the Zigbee API reads and does (*zigbee.Manager).

Jump to

Keyboard shortcuts

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