airouter

package
v1.2.9 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package airouter manages one or more embedded "AI router" backends — local OpenAI-compatible proxy dashboards (9router, OmniRoute, …) that ship as npm packages and serve a web dashboard on a loopback port. airouter installs/updates each package on demand, starts/stops/restarts its process, and reverse-proxies its dashboard so it can be embedded in an iframe — the host never exposes the underlying port.

Each router lives in its own subpackage (internal/agents/airouter/<id>) and registers a Descriptor via Register at init. The core is generic: adding a router is "new folder + Register", never a core edit. Multiple routers run concurrently, each on its own loopback port, mounted at /airouter/<id>/, so the UI can switch between them and check any of them live.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIProxy

func APIProxy(id string) http.Handler

APIProxy returns the OpenAI-compatible API reverse-proxy handler for router id, mounted UNAUTHENTICATED at /airouter/<id>/v1/. 404s when off/unknown.

func ActiveAssetRouter

func ActiveAssetRouter() string

ActiveAssetRouter returns the router ID that should serve a bare /_next/* asset request, or "" when none has been resolved yet.

func AnyAutostartEnabled

func AnyAutostartEnabled() bool

AnyAutostartEnabled reports whether at least one router has auto-start on, so server.go can decide whether to add a boot-gate step.

func Autostart

func Autostart(logf func(string))

Autostart starts each router whose stored auto-start flag is on and whose package is installed. Safe to call in a goroutine at boot.

func IDs

func IDs() []string

IDs returns the registered router IDs in stable order.

func Init

func Init()

Init wires the provider-side spawn injection so agent spawners can route through a router without importing this package (which would be an import cycle — airouter imports provider). Call once at boot, after RegisterBuiltins.

func NextAssetProxy

func NextAssetProxy() http.Handler

NextAssetProxy handles bare root-absolute /_next/* asset requests that a router's Next.js bundle assembles at runtime and which slip past the body rewriter. It re-roots the path under the active router's prefix (the one whose dashboard HTML was last served) and hands it to that router's proxy. Admin auth is applied at the mount in server.go.

func RedirectTargetFor

func RedirectTargetFor(path, referer string) string

RedirectTargetFor returns the wick-root redirect target for a request that escaped an embedded router's mount — a root-absolute app route (e.g. /home) that a router SPA navigated to client-side, which would otherwise 404 at the wick root (directly, or relayed by wick's service worker). It resolves which router the request belongs to from the Referer (…/airouter/<id>/…), falling back to the last-viewed dashboard router, then checks the path against that router's declared RoutePrefixes. Returns "" when nothing matches, so normal wick routing / 404s are unaffected. server.go 302-redirects to the result.

func Register

func Register(d Descriptor)

Register adds a router to the process-wide registry, constructing its Manager. Idempotent: a duplicate ID is ignored so a double blank-import can't panic. Called from each router subpackage's RegisterBuiltins.

func RegisterRoutes

func RegisterRoutes(r tool.Router, cfg ConfigStore)

RegisterRoutes wires the generic control + stream endpoints for every registered router under /airouter/<id>/… (relative to the hosting tool base) and backs each Manager's external-API decision with the config store. The dashboard iframe + /v1 API proxies are mounted at the wick root by server.go via RootProxy / APIProxy — not here.

func RootProxy

func RootProxy(id string) http.Handler

RootProxy returns the dashboard reverse-proxy handler for router id, mounted at the wick root (/airouter/<id>/) behind admin auth in server.go. 404s when the master switch is off or the id is unknown.

func SetSecretDecrypter

func SetSecretDecrypter(fn func(string) (string, error))

SetSecretDecrypter wires the boot-time secret decrypter used to unwrap a stored router API key at spawn. Backed by configs.Service.DecryptSecret.

func StopAll

func StopAll()

StopAll kills every running router process. Exposed for shutdown hooks.

Types

type ConfigStore

type ConfigStore interface {
	// Enabled is the master switch — false disables every router surface.
	Enabled() bool
	// AccessAllowed reports whether the request's user may drive controls
	// (admin only today).
	AccessAllowed(ctx context.Context) bool
	// GetAutostart reports whether router id should auto-start on boot.
	GetAutostart(id string) bool
	SetAutostart(ctx context.Context, id string, on bool) error
	// GetExternalAPI reports the per-router external-API toggle.
	GetExternalAPI(id string) bool
	SetExternalAPI(ctx context.Context, id string, on bool) error
	// ExternalAPIAllowed reports whether router id's /v1 API may be reached
	// off-machine (master switch AND the per-router toggle).
	ExternalAPIAllowed(id string) bool
}

ConfigStore persists the small set of airouter knobs and answers the access questions the control endpoints need. The hosting package backs it with the app's config service + auth so this package stays free of storage/login imports. Per-router knobs are keyed by router ID.

type Descriptor

type Descriptor struct {
	// ID is the stable identifier used in the URL path (/airouter/<ID>) and
	// config keys (airouter_<ID>_autostart). Lowercase, no spaces.
	ID string
	// DisplayName is the human label shown in the switcher/menu.
	DisplayName string
	// Blurb is a one-line description shown under the title.
	Blurb string
	// NpmPackage is the npm package installed with `npm i -g <pkg>@latest`.
	NpmPackage string
	// BinName is the command resolved on PATH once installed (usually == NpmPackage).
	BinName string
	// PrefPort is the dashboard port the router prefers. When taken (two
	// routers default to the same port), the core remaps to the next free
	// loopback port at start.
	PrefPort int
	// IdentitySubstr, when set, is matched case-insensitively against the
	// name / short_name in the backend's /manifest.webmanifest to confirm that
	// a process wick did NOT spawn — one merely found listening on the port —
	// is really THIS router, not a different router that happens to hold the
	// same default port (both 9router and OmniRoute default to 20128). Empty =
	// skip the identity check and trust port-reachability alone.
	IdentitySubstr string
	// IconSVG is inline SVG markup (the inner shapes, no <svg> wrapper) for
	// the switcher tile. Empty = a default router glyph.
	IconSVG string
	// RoutePrefixes are this router SPA's app-specific top-level routes (root-
	// absolute, e.g. OmniRoute's "/home") that must be re-rooted under the
	// mount prefix in the rewrite pass — on top of baseRewritePrefixes. Add a
	// route here if a client-side navigation to it escapes to the wick root.
	RoutePrefixes []string
	// Launch builds the exec args + extra env to start the process listening
	// on `port`, bound to loopback. Routers differ: 9router takes --port /
	// --host flags, OmniRoute takes a PORT env var. The core resolves the bin
	// and prepends it; Launch returns only the args after the bin and any
	// extra env (KEY=VALUE) to add to the child environment.
	Launch func(port int) (args []string, env []string)
	// Hook contributes the CLI args + env an agent needs to route through this
	// router at spawn time. nil = this router can't be used as a spawn target.
	Hook SpawnHook
}

Descriptor is everything the core needs to manage one router backend. A router subpackage builds one and hands it to Register.

type Manager

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

Manager owns the lifecycle of one router's child process and the reverse proxy fronting its dashboard. Construct via newManager (done by Register).

func (*Manager) APIProxyHandler

func (m *Manager) APIProxyHandler() http.Handler

APIProxyHandler serves the OpenAI-compatible API subtree, mounted UNAUTHENTICATED so local AI CLIs reach the router without a wick session cookie — auth is the router's own API key. Body pass-through (no rewrite).

func (*Manager) Install

func (m *Manager) Install(w http.ResponseWriter, r *http.Request)

Install installs or updates the router package.

func (*Manager) Installed

func (m *Manager) Installed(ctx context.Context) bool

Installed reports whether the npm package is present.

func (*Manager) LogStream

func (m *Manager) LogStream(w http.ResponseWriter, r *http.Request)

LogStream is the SSE endpoint tailing live process output: a snapshot on connect, then incremental chunks, plus a reset sentinel on (re)start.

func (*Manager) Logs

func (m *Manager) Logs(w http.ResponseWriter, r *http.Request)

Logs returns the retained tail of the process output.

func (*Manager) MountPrefix

func (m *Manager) MountPrefix() string

MountPrefix is the wick-root path this router's dashboard is proxied under.

func (*Manager) ProxyHandler

func (m *Manager) ProxyHandler() http.Handler

ProxyHandler serves the dashboard subtree by proxying to the local router process, handling WebSocket upgrades for live updates. It strips the per-router mount prefix before forwarding.

func (*Manager) ReqStream

func (m *Manager) ReqStream(w http.ResponseWriter, r *http.Request)

ReqStream is the SSE endpoint the Requests tab connects to. It subscribes the caller to live request events until the client disconnects.

func (*Manager) Restart

func (m *Manager) Restart(w http.ResponseWriter, r *http.Request)

Restart stops then starts, waiting for readiness.

func (*Manager) SetExternalAllowed

func (m *Manager) SetExternalAllowed(fn func() bool)

SetExternalAllowed wires the getter backing the external-API decision.

func (*Manager) Start

func (m *Manager) Start(w http.ResponseWriter, r *http.Request)

Start spawns the process and waits for the dashboard to answer.

func (*Manager) StartAndWait

func (m *Manager) StartAndWait(ctx context.Context) error

StartAndWait spawns the process (if not running) and blocks until the dashboard answers or ctx expires.

func (*Manager) Status

func (m *Manager) Status(w http.ResponseWriter, r *http.Request)

Status reports install + run state as JSON. Non-blocking.

func (*Manager) Stop

func (m *Manager) Stop(w http.ResponseWriter, r *http.Request)

Stop kills the process.

func (*Manager) StopProcess

func (m *Manager) StopProcess()

StopProcess kills the process. Exposed for shutdown hooks.

type ReqEvent

type ReqEvent struct {
	Time       string `json:"time"`        // wall-clock "15:04:05" of when the request landed
	Method     string `json:"method"`      // HTTP method
	Path       string `json:"path"`        // request path (already stripped of the /airouter/<id> prefix)
	Host       string `json:"host"`        // inbound Host header
	RemoteAddr string `json:"remote_addr"` // TCP peer as wick saw it
	ClientIP   string `json:"client_ip"`   // best-effort real client IP
	External   bool   `json:"external"`    // true when the caller reached us from off-machine
	Auth       string `json:"auth"`        // redacted Authorization / x-api-key ("" when none)
	UserAgent  string `json:"user_agent"`  // caller UA
	Model      string `json:"model"`       // model name sniffed from the request body ("" when unknown)
	Status     int    `json:"status"`      // upstream response status
	DurationMS int64  `json:"duration_ms"` // round-trip duration in milliseconds
	ReqBody    string `json:"req_body"`    // FULL request body
	RespBody   string `json:"resp_body"`   // FULL response body
}

ReqEvent is one proxied API request, streamed live to subscribers. It carries the FULL request and response bodies (never truncated) — they are held only in the receiving browser, so size is the client's concern, not the server's. Field names are the JSON keys the UI reads.

type Router

type Router struct {
	Desc Descriptor
	Mgr  *Manager
}

Router is one registered backend: its descriptor plus the process/proxy manager the core built for it.

func Get

func Get(id string) (*Router, bool)

Get returns the router with the given ID.

func List

func List() []*Router

List returns every registered router in stable (ID-sorted) order.

type SpawnHook

type SpawnHook interface {
	// Contribute returns the extra args + env for agent type t routed through
	// this router. base is the wick-origin API base ("http://127.0.0.1:<port>/
	// airouter/<id>/v1"); key is the resolved plaintext API key. A router that
	// doesn't support t returns (nil, nil, nil).
	Contribute(t provider.Type, ins provider.Instance, base, key string) (args, env []string, err error)
	// Slots are the model-picker slots this router exposes for agent type t
	// (claude → opus/sonnet/haiku; codex → model/subagent). Empty = unsupported.
	Slots(t provider.Type) []provider.RouterSlot
	// DefaultKey is the credential used when the instance sets none. 9router
	// accepts a documented default ("sk_9router"); routers with no default
	// return "".
	DefaultKey() string
}

SpawnHook lets a router inject what an agent CLI needs to route through it. It is the "on spawn, add what" extension point: the spawner calls one generic function and each router supplies its own base-URL wiring, env var names, and flags — so per-provider spawners barely change and differences between routers (and between agent types) are absorbed here.

Directories

Path Synopsis
Package omniroute registers the OmniRoute backend with airouter.
Package omniroute registers the OmniRoute backend with airouter.
Package router9 registers the 9router backend with airouter.
Package router9 registers the 9router backend with airouter.

Jump to

Keyboard shortcuts

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