api

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 37 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 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

View Source
const CookieName = "ka_token"

CookieName holds the local token in browsers.

View Source
const DefaultAddr = "127.0.0.1:7711"

DefaultAddr is where the daemon listens unless told otherwise.

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

View Source
const MaxAskWait = 5 * time.Minute

MaxAskWait caps ka_ask's wait over HTTP.

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

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

This section is empty.

Functions

func Config

func Config(version string) huma.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

func Listen(addr string) (net.Listener, error)

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

func ListenRemote(addr string) (net.Listener, error)

ListenRemote listens on any address, for remote mode. The caller must have configured authentication (Remote.Configured).

func NewToken

func NewToken() string

NewToken returns a random local token.

func ParseCIDRs

func ParseCIDRs(vals []string) ([]*net.IPNet, error)

ParseCIDRs parses --trusted-proxy values (CIDRs or single IPs).

func Probe

func Probe(ctx context.Context, r *Runtime) bool

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

func RuntimePath(hash string) string

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

func WorkspaceHash(source string) string

WorkspaceHash identifies a workspace by its source path.

func WriteRuntime

func WriteRuntime(r *Runtime) error

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

func (p *Problem) ContentType(ct string) string

ContentType implements huma.ContentTypeFilter.

func (*Problem) Error

func (p *Problem) Error() string

func (*Problem) GetStatus

func (p *Problem) GetStatus() int

GetStatus implements huma.StatusError.

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

func (r *Remote) Configured() bool

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 Discover

func Discover(ctx context.Context, source string) *Runtime

Discover returns the running daemon for a workspace, or nil.

func ReadRuntime

func ReadRuntime(hash string) (*Runtime, error)

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

func New(svc *engine.Service, opts Options) *Server

New builds the server and its routes. Call SetAddr once the listener is bound (Serve does it).

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler is the full HTTP handler with the security checks in front.

func (*Server) OpenAPI

func (s *Server) OpenAPI() *huma.OpenAPI

OpenAPI returns the API's OpenAPI document.

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, ln net.Listener) error

Serve runs the server on ln until ctx is canceled, then shuts down gracefully.

func (*Server) SetAddr

func (s *Server) SetAddr(addr string)

SetAddr records the bound address.

func (*Server) Token

func (s *Server) Token() string

Token is the local token clients must present.

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

func (ts *TokenStore) Count() int

Count returns how many tokens exist.

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.

Jump to

Keyboard shortcuts

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