Documentation
¶
Overview ¶
Package api is the daemon's HTTP surface (PRD §12, §15): REST under /api/v1 with an OpenAPI 3.1 document, the token exchange for browsers, and the Host and Origin checks that keep other web pages out.
Index ¶
- Constants
- Variables
- func Config(version string) huma.Config
- func Listen(addr string) (net.Listener, error)
- func ListenRemote(addr string) (net.Listener, error)
- func NewToken() string
- func ParseCIDRs(vals []string) ([]*net.IPNet, error)
- func Probe(ctx context.Context, r *Runtime) bool
- func RemoveRuntime(r *Runtime)
- func RuntimeDir() string
- func RuntimePath(hash string) string
- func TokensPath() string
- func WorkspaceHash(source string) string
- func WriteRuntime(r *Runtime) error
- type CallerHeaders
- type Health
- type Options
- type Problem
- type Remote
- type Runtime
- type Server
- func (s *Server) Handler() http.Handler
- func (s *Server) OpenAPI() *huma.OpenAPI
- func (s *Server) Serve(ctx context.Context, ln net.Listener) error
- func (s *Server) SetAddr(addr string)
- func (s *Server) SetUI(fsys fs.FS, origin string)
- func (s *Server) Token() string
- func (s *Server) UIOrigin() string
- type TicketID
- type Token
- type TokenStore
- type UIManifest
Constants ¶
const CookieName = "ka_token"
CookieName holds the local token in browsers.
const DefaultAddr = "127.0.0.1:7711"
DefaultAddr is where the daemon listens unless told otherwise.
const GitHubHookPath = "/api/v1/hooks/github"
GitHubHookPath receives GitHub push webhooks (PRD §10.1: webhooks are preferred to polling for remote daemons). GitHub cannot send the API token, so the request is authenticated by its X-Hub-Signature-256 HMAC with the configured secret instead.
const MaxAskWait = 5 * time.Minute
MaxAskWait caps ka_ask's wait over HTTP.
const PrincipalHeader = "X-Ka-Principal"
PrincipalHeader carries the authenticated principal from the HTTP layer to handlers and the MCP server. The server always overwrites it, so clients cannot set it.
const SeqHeader = "Ka-Event-Seq"
SeqHeader carries the hub's last event ID on every API response, so a client can take a snapshot and then subscribe from exactly that point.
Variables ¶
var APIHash = sync.OnceValue(func() string { doc, _ := json.Marshal(New(nil, Options{Version: "-"}).OpenAPI()) sum := sha256.Sum256(doc) return hex.EncodeToString(sum[:8]) })
APIHash identifies the REST API's shape: a hash of the OpenAPI document without the version number, so a release that leaves the API alone keeps it, and a UI built against it still fits.
var EmbeddedUI, _ = fs.Sub(ka.UI, "ui")
EmbeddedUI is the web UI built into the binary (ui/ at the repository root), so the daemon serves it offline (PRD §13.1).
Functions ¶
func Config ¶
Config is the Huma configuration: OpenAPI 3.1 at /api/v1/openapi.json, no hosted docs page (it would load scripts from a CDN), no $schema links.
func Listen ¶
Listen binds addr. Only loopback addresses are accepted until remote mode (M4). When addr is the default and its port is taken, a free port is used; the runtime file tells clients which.
func ListenRemote ¶
ListenRemote listens on any address, for remote mode. The caller must have configured authentication (Remote.Configured).
func ParseCIDRs ¶
ParseCIDRs parses --trusted-proxy values (CIDRs or single IPs).
func Probe ¶
Probe reports whether the daemon described by r answers on its address for the same workspace.
func RemoveRuntime ¶
func RemoveRuntime(r *Runtime)
RemoveRuntime removes the runtime file if it still belongs to this daemon.
func RuntimeDir ¶
func RuntimeDir() string
RuntimeDir is where runtime files live: $KA_RUNTIME_DIR, else $XDG_RUNTIME_DIR/ka, else the user cache directory's ka/run.
func RuntimePath ¶
RuntimePath is the runtime file for a workspace hash. There is one per workspace, so daemons for different workspaces can run side by side.
func TokensPath ¶
func TokensPath() string
TokensPath is where API tokens live: <ka config dir>/tokens.json.
func WorkspaceHash ¶
WorkspaceHash identifies a workspace by its source path.
func WriteRuntime ¶
WriteRuntime writes the runtime file atomically, readable only by the user.
Types ¶
type CallerHeaders ¶
type CallerHeaders struct {
Actor string `` /* 183-byte string literal not displayed */
Session string `header:"X-Ka-Session" doc:"A session ID, recorded in the Ka-Session trailer."`
// Principal is set by the server after authentication (never by clients).
Principal string `header:"X-Ka-Principal" hidden:"true"`
}
Caller headers, accepted on every operation.
type Health ¶
type Health struct {
Status string `json:"status"`
Version string `json:"version"`
PID int `json:"pid"`
WorkspaceHash string `json:"workspace_hash"`
}
Health is GET /healthz.
type Options ¶
type Options struct {
Token string
Version string
Logger *slog.Logger
// Shutdown is called by POST /api/v1/daemon/shutdown.
Shutdown func()
// Events is the hub SSE clients read; New creates one (10,000 events)
// and connects it to the service when nil.
Events *engine.EventHub
// Heartbeat is the SSE keep-alive interval (default 15 s).
Heartbeat time.Duration
// MCP, when set, is mounted at /mcp (MCP over Streamable HTTP).
MCP http.Handler
// Presence lists live agent sessions (GET /api/v1/presence).
Presence *presence.Tracker
// Remote enables remote mode: API tokens and trusted proxies (PRD §15).
Remote *Remote
// WebhookSecret verifies GitHub webhooks at POST /api/v1/hooks/github.
WebhookSecret string
}
Options configures a Server.
type Problem ¶
type Problem struct {
Type string `json:"type,omitempty" doc:"Always about:blank; use code."`
Status int `json:"status" doc:"The HTTP status."`
Title string `json:"title" doc:"The HTTP status text."`
Code string `json:"code" doc:"The ka error code, the same as in MCP and the CLI (not_found, claim_lost, unknown_status, ...)."`
Detail string `json:"detail,omitempty" doc:"What went wrong."`
Fix string `json:"fix,omitempty" doc:"What to do about it."`
Data map[string]any `json:"data,omitempty" doc:"Structured details, such as the index of the failing item in a batch."`
Errors []*huma.ErrorDetail `json:"errors,omitempty" doc:"Request validation failures."`
}
Problem is an RFC 9457 problem document carrying the engine's error code and fix, so REST clients see the same errors as MCP and the CLI.
func (*Problem) ContentType ¶
ContentType implements huma.ContentTypeFilter.
type Remote ¶
type Remote struct {
// Tokens are the API tokens accepted (ka token create).
Tokens *TokenStore
// TrustedProxies may assert the user in ProxyUserHeader.
TrustedProxies []*net.IPNet
// ProxyUserHeader names the header a trusted proxy sets (default
// X-Forwarded-User; X-Forwarded-Email and similar work too).
ProxyUserHeader string
// Hosts are the host names clients use (from --public-url); empty
// accepts any Host, with Origin required to match it.
Hosts []string
}
Remote configures remote mode.
func (*Remote) Configured ¶
Configured reports whether some form of authentication is set up.
type Runtime ¶
type Runtime struct {
Version string `json:"version"`
PID int `json:"pid"`
Addr string `json:"addr"` // host:port
URL string `json:"url"`
Workspace string `json:"workspace"` // the workspace source (file or directory)
WorkspaceHash string `json:"workspace_hash"`
Token string `json:"token"`
Started string `json:"started"`
}
Runtime is the daemon's runtime file (PRD §8.3). Clients find a running daemon for their workspace through it; the token authenticates them.
func ReadRuntime ¶
ReadRuntime reads a workspace's runtime file.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server serves one workspace's service over HTTP.
func New ¶
New builds the server and its routes. Call SetAddr once the listener is bound (Serve does it).
func (*Server) Serve ¶
Serve runs the server on ln until ctx is canceled, then shuts down gracefully.
func (*Server) SetUI ¶ added in v1.0.4
SetUI serves the UI from fsys from now on (origin is for logs and /api/v1/daemon). A nil fsys goes back to the embedded UI.
type TicketID ¶
type TicketID struct {
ID string `path:"id" doc:"A ticket ID, such as KA-6FVER." example:"KA-6FVER"`
}
type Token ¶
type Token struct {
ID string `json:"id"`
Actor string `json:"actor"`
Hash string `json:"hash"` // sha256 of the token, hex
Note string `json:"note,omitempty"`
Created string `json:"created"`
}
Token is one API token, as stored (hashed).
type TokenStore ¶
type TokenStore struct {
Path string
// contains filtered or unexported fields
}
TokenStore reads tokens from a JSON file, reloading it when it changes so ka token create takes effect without a restart.
func NewTokenStore ¶
func NewTokenStore(path string) *TokenStore
NewTokenStore opens the token file at path (which may not exist yet).
func (*TokenStore) Create ¶
func (ts *TokenStore) Create(actor, note string) (string, Token, error)
Create makes a token for actor and returns it; only its hash is stored.
func (*TokenStore) List ¶
func (ts *TokenStore) List() []Token
List returns the stored tokens (hashes only).
func (*TokenStore) Lookup ¶
func (ts *TokenStore) Lookup(tok string) (string, bool)
Lookup returns the actor of a valid token.
func (*TokenStore) Remove ¶
func (ts *TokenStore) Remove(id string) error
Remove deletes a token by ID.
type UIManifest ¶ added in v1.0.4
type UIManifest struct {
// API is the APIHash of the API the UI was generated against.
API string `json:"api"`
}
UIManifest is ui/ka-ui.json, written by the UI build.
func ReadUIManifest ¶ added in v1.0.4
func ReadUIManifest(fsys fs.FS) (UIManifest, error)
ReadUIManifest reads ka-ui.json from a built UI.