httpapi

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 18 Imported by: ? 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.

README

hosts/httpapi

hosts/httpapi (package httpapi) is a standalone HTTP server for any web front end, with a small browser UI embedded. app/cmd/harness-web runs it:

harness-web -local                      # in a repository: coding agent on this directory, UI at http://127.0.0.1:8080/
HARNESS_WEB_ADDR=0.0.0.0:8080 HARNESS_WEB_TOKEN=secret OPENSANDBOX_URL=… harness-web   # remote sandbox, shared

-local sets SANDBOX_BACKEND=local and AGENT_PROFILE=coding (unless already set) and keeps sessions on disk (harness.OpenLocalStore). Flags: -addr (default HARNESS_WEB_ADDR, else 127.0.0.1:8080), -model, -local, -user (the single user's login, default local). A non-loopback address is refused unless HARNESS_WEB_TOKEN is set.

Routes (all under /api, also served without the prefix; errors are {"error":{"code","message"}}; the full table with bodies is the doc comment of hosts/httpapi/httpserver.go):

Route
GET /healthz liveness, no auth
GET /api/models allowed models and the default
GET /api/sessions saved conversations (durable file store only, else 501)
POST/GET /api/threads, GET/PATCH/DELETE /api/threads/{id} create, list, read with messages, rename, delete
POST /api/threads/{id}/runs send a message, 202 with the run
POST /api/threads/{id}/resume answer an approval (decision approve/deny, always) or an ask_user question (text)
GET /api/threads/{id}/files?path=, .../files/download?path= list and download /workspace of the thread's sandbox (read-only, confined, attachment)
GET /api/runs/{id}, GET /api/runs/{id}/events?after= run state; AG-UI events as SSE, resumed with Last-Event-ID or after
POST /api/runs/{id}/cancel, /steer stop a run; add a message to a running one

A foreign thread or run id is always a 404. Auth: Options.Authenticate (func(*http.Request) (user string, err error)) decides who calls; the default is one local user, with an optional static bearer token (HARNESS_WEB_TOKEN). HARNESS_WEB_ORIGINS is a comma-separated CORS allowlist; other cross-origin requests are refused (403), and without a token the server only answers loopback Host names. Every response carries a strict CSP (default-src 'self').

UI (hosts/httpapi/ui, go:embed, about 450 lines of plain HTML/CSS/JS, no build step, no CDN): conversation list, streamed transcript with basic markdown, collapsible tool calls (edit diffs), status line (model, steps, tokens, cache %), send / steer / cancel, approval and question prompts, a file panel with downloads, light and dark themes, phone-width layout. With a token set the UI asks for it once and keeps it for the tab.

Documentation

Overview

Package httpserver exposes a harness.Harness over HTTP for web front ends: a JSON API for threads, runs, approvals, files and models, the run's AG-UI events as Server-Sent Events (the SSE id is the event seq, so reconnects resume with Last-Event-ID or ?after= without loss or duplicates), and a small built-in browser UI (ui/) served at / and /ui/.

Every API route is served under /api and, for compatibility, without the prefix. Each route except /healthz needs an authenticated caller (see Authenticator) and answers 404 for threads and runs that belong to another user. Errors use {"error":{"code","message"}}.

GET    /healthz                                  → {"status":"ok"}            (no auth)
GET    /api/models                               → {"models":[…],"default"}
GET    /api/sessions?limit=                      → [Session]  (durable file store only, else 501)
POST   /api/threads            {"title"}         → 201 Thread
GET    /api/threads?limit=                       → [Thread]
GET    /api/threads/{id}                         → Thread + messages (+ pendingApproval, pendingQuestion, activeRun)
PATCH  /api/threads/{id}       {"title"}         → Thread
DELETE /api/threads/{id}                         → 204
POST   /api/threads/{id}/runs  {"message","model","reasoningEffort","skills","interactive","sandbox":"auto|off|on","mode":"build|plan","attachments":[{"name","mime","data":base64}]} → 202 Run
POST   /api/threads/{id}/resume {"interruptId","reason","decision":"approve|deny","always","text","model","interactive","mode"} → 202 Run
GET    /api/threads/{id}/files?path=             → [File]   (read-only, confined to /workspace)
GET    /api/threads/{id}/files/download?path=    → file bytes, Content-Disposition: attachment
GET    /api/runs/{id}                            → Run
GET    /api/runs/{id}/events?after=              → text/event-stream of AG-UI events (or Last-Event-ID)
POST   /api/runs/{id}/cancel                     → 202
POST   /api/runs/{id}/steer    {"text"}          → 202
GET    /api/commands                             → [Command]  (custom commands, skills, builtins)
POST   /api/commands/{name}/expand {"args"}      → {"prompt"}
GET    /, /ui/...                              → the embedded UI

Resuming: a run that ends with RUN_FINISHED outcome "interrupt" waits for an answer. Post it to /resume with the interrupt id (the approval id for reason "tool_approval", with decision approve|deny and always=true to approve the tool for the rest of the run chain; the question's interruptId for "ask_user", with text). The response is the run that continues; follow its events.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(w http.ResponseWriter, r *http.Request, v any) bool

Decode reads a JSON request body (at most 2 MiB; an empty body is fine).

func DecodeLimit

func DecodeLimit(w http.ResponseWriter, r *http.Request, v any, limit int64) bool

DecodeLimit is Decode with a size limit.

func Fail

func Fail(w http.ResponseWriter, err error)

Fail writes a client error with its own status and code, anything else as an internal error.

func LimitParam

func LimitParam(r *http.Request, def int) int

LimitParam reads the ?limit= query parameter (at most 200).

func New

func New(h *harness.Harness, o Options) http.Handler

New returns the HTTP handler. It panics when Options are inconsistent (OIDC that cannot be reached); use NewServer to get the error.

func NewServer

func NewServer(h *harness.Harness, o Options) (http.Handler, error)

NewServer is New returning the error.

func UI

func UI() fs.FS

UI is the embedded browser client: the build of web/ (make web). A checkout that has not built it embeds only a placeholder and serves a notice at /.

func WriteError

func WriteError(w http.ResponseWriter, status int, code, msg string)

WriteError writes the API's error body.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes v as JSON with the status.

Types

type Authenticator

type Authenticator func(*http.Request) (user string, err error)

Authenticator maps a request to the user it acts for. A non-nil error (or an empty user) answers 401. Plug in your own for multi-user deployments (a session cookie, a JWT, a proxy header).

func LocalAuthenticator

func LocalAuthenticator(user, token string) Authenticator

LocalAuthenticator is the default: a single user (default "local"). With a non-empty token every request must carry "Authorization: Bearer <token>".

type Caller

type Caller struct {
	// Login owns threads and runs: what store calls are scoped by. In team
	// mode it is the owner of the thread being acted on, which is not the
	// actor for a thread shared through a project.
	Login string
	// Actor is the authenticated user (equal to Login outside team mode).
	Actor string
	// ProjectID, Role and CreatedBy describe the project thread being acted on.
	ProjectID string
	Role      string
	CreatedBy string
}

Caller is an authenticated user.

type ClientConfig

type ClientConfig struct {
	SentryDSN string
	SentryEnv string
	SentryRel string
	UmamiURL  string
	UmamiID   string
	// contains filtered or unexported fields
}

ClientConfig tells the browser UI where to send its own errors and usage statistics. Both are optional and off by default; the UI reads them from GET /api/client-config at startup, so one build serves every install.

SentryDSN  a Sentry-protocol DSN (Rustrak, Sentry, GlitchTip) for errors raised in the browser
UmamiURL   the Umami server (https://umami.example.com); the UI loads <UmamiURL>/script.js
UmamiID    the Umami website id of this UI

The Content-Security-Policy stays at 'self' unless these are set; then it allows exactly the origins they name (script-src and connect-src for Umami, connect-src for the tracker) and nothing else.

type Extension

type Extension interface {
	Policy
	Setup(o *Options, mux *http.ServeMux) error
	Install(s *Server) error
}

Extension plugs a product into the server: a Policy and the routes that belong to it. Setup runs first (it may set the authenticator and mount login routes), Install after the core routes.

type Handler

type Handler func(w http.ResponseWriter, r *http.Request, c Caller)

Handler serves an authenticated request.

type Options

type Options struct {
	// Authenticate maps a request to the user it acts for; an error answers 401.
	// Takes precedence over User and Token.
	Authenticate Authenticator
	// User is the older form of Authenticate.
	User func(*http.Request) (Caller, error)
	// Token, when set (and no Authenticate/User), is the static bearer token every
	// API request must carry; all requests then act as LocalUser.
	Token string
	// LocalUser is the single user of the default authenticator (default "local").
	LocalUser string
	// AllowedOrigins are the browser origins (scheme://host[:port]) allowed to call the
	// API cross-origin; "*" allows any. Same-origin requests need no entry.
	AllowedOrigins []string
	// AllowedHosts, when set, restricts the Host header (DNS-rebinding guard for
	// token-less loopback servers), e.g. "localhost", "127.0.0.1".
	AllowedHosts []string
	// Models are the model ids offered by GET /api/models.
	Models []string
	// DefaultModel is used when a run request names none.
	DefaultModel string
	// ModelInfo (optional) describes the models for GET /api/models: context window, prices, capabilities.
	ModelInfo func(id string) (client.ModelInfo, bool)
	// PingEvery keeps idle event streams open through proxies (default 15 s).
	PingEvery time.Duration
	// NoUI leaves out the embedded UI (API only).
	NoUI bool
	// Extension plugs a product on top of the API: identity, shared projects,
	// connectors... (package product). Without it the server is the plain
	// single-user API.
	Extension Extension
	// Client is what the browser UI needs to report its own errors and usage (see ClientConfig). The zero value
	// reports nothing and leaves the Content-Security-Policy at 'self'.
	Client ClientConfig
}

Options configures the handler.

type Policy

type Policy interface {
	// Resolve turns the authenticated actor and the thread or run the request names into the Caller the handler works as.
	Resolve(r *http.Request, kind ResourceKind, actor string) (Caller, error)
	// FailAccess answers an error of Resolve.
	FailAccess(w http.ResponseWriter, err error)
	// Author is how the caller is recorded on what they send.
	Author(c Caller) harness.Author

	CreateThread(w http.ResponseWriter, r *http.Request, c Caller) bool
	ListThreads(w http.ResponseWriter, r *http.Request, c Caller) bool
	GetThread(w http.ResponseWriter, r *http.Request, c Caller) bool
	DeleteThread(w http.ResponseWriter, r *http.Request, c Caller) bool

	// BeforeRun may adjust the options of a run about to be sent on the thread.
	BeforeRun(r *http.Request, threadID string, o *client.SendOptions)
	// BeforeResume may adjust a resume request; it returns the name of the tool the approval is for, for the audit log.
	BeforeResume(r *http.Request, c Caller, threadID string, body *client.ResumeRequest) (tool string)
	// AfterRun runs once a run was queued by action "run.send" or "run.resume".
	AfterRun(c Caller, run *client.Run, action string, detail map[string]any)
	// AfterRunAction runs after a cancel or a steer of the run named by the route.
	AfterRunAction(r *http.Request, c Caller, action string)
	// AfterFork runs once a thread was forked; true means it failed and has answered.
	AfterFork(w http.ResponseWriter, r *http.Request, c Caller, th *client.Thread) bool
}

Policy is how a product specialises the core routes (who may see a thread, who is recorded as the author of a message, what is logged). The methods that take over a route return true once they have answered; false leaves the route to the plain single-user behaviour.

type ResourceKind

type ResourceKind int

ResourceKind says what {id} names in a route path.

const (
	KindNone ResourceKind = iota
	KindThread
	KindRun
)

type Server

type Server struct {
	H    *harness.Harness
	O    Options
	Auth Authenticator
	Mux  *http.ServeMux
	// contains filtered or unexported fields
}

Server is the HTTP API. An Extension receives it in Install to add routes: everything it needs (the harness, the options, the mux, the route helpers) is exported here.

func (*Server) API

func (s *Server) API(c Caller) client.Client

api is the engine as seen by the caller.

func (*Server) Authed

func (s *Server) Authed(kind ResourceKind, next Handler) http.HandlerFunc

func (*Server) Route

func (s *Server) Route(pattern string, h Handler)

Route registers an authenticated route under /api and without the prefix.

Jump to

Keyboard shortcuts

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