api

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 47 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: Agent-to-Agent (A2A) delegation -- native sub-agent delegation where an agent calls another agent via the same Agent Protocol API, with real semantics for auth context propagation between agents, recursion limits, and cost attribution.

The mechanism is deliberately NOT a new client-facing endpoint -- it's the exact same POST /threads/{id}/runs + wait-for-result path any client uses, just reachable from inside a runner's own process via one new /internal/* route instead of a public one. A running agent's own code (e.g. a LangGraph node) calls this to invoke another agent as a sub-task, wait for its result, and continue -- "agent calls agent via the same Agent Protocol API" in the most literal sense: createRunCtx and waitForRunResult are the identical functions every client-facing run-creation path already uses.

Three things this endpoint adds on top of that shared path:

  1. Auth context propagation: on_behalf_of forwards identity/ permissions into the sub-run (propagation, not enforcement -- the body is trusted from the runner; runs don't persist the original caller's auth to compare against). Tenant is derived from the PARENT run's own tenant_id (looked up server-side), never from the request body. Parent lookup uses SystemContext (runner-trusted /internal/*), so a compromised runner that knows another tenant's run UUID could attach a child there -- same trust boundary as the rest of /internal/*, stated plainly.
  2. Recursion limits: parent_run_id is required, and createRunCtx (see runs.go) enforces a2a.max_depth against the parent's own depth, failing a chain that's gone too deep (accidental cycle or runaway delegation) with 400, not a resource leak.
  3. Cost attribution: every delegated run's root_run_id points at the top of its delegation tree (persisted + indexed). RunSearchRequest exposes this as a client-facing filter (root_run_id) so any run in a tree can be used to find every other run in it with one query, and GET /runs/{runID}/cost (below) aggregates best-effort token/cost usage across the whole tree from it.

Runner-authenticated (mounted under /internal/*, not client-facing) -- this is infrastructure a runner's own SDK helper calls on an agent's behalf, not something an end-user client should ever call directly.

Cancelling a run cascades to everything it delegated, directly or transitively (see runs.go's cancelRunCore/cascadeCancelDescendants) -- a cancelled parent can't leave orphaned children still executing.

Package api: Admin API -- a web dashboard for managing agents, viewing runs/threads, debugging, connector status, metrics, and user management.

Scope, stated plainly: this covers the OPERATIONAL half of that list -- agents, threads, runs (with live debugging via the same SSE stream clients use), connector status, cron schedules, policy audit search (SQL backends), and a summary overview. "User management" is explicitly NOT built here: there is no persisted user/API-key table today (auth.APIKeyEntry is static langgraph.json config, not a DB-backed model) -- building real user CRUD means inventing that persistence subsystem first, which is its own separate piece of work, not a UI feature to bolt on. Every /admin-api/* route sees across every tenant (auth.Middleware enforces "admin" permission specifically for this path prefix; see internal/auth/auth.go) -- an operator managing the whole deployment, not one tenant's own view.

Most routes are thin system-context wrappers around the exact same handlers the client-facing API already uses (see withSystemContext) -- reusing them instead of duplicating list/search/get logic. Agents and threads get dedicated admin views instead, specifically to surface tenant_id (models.Agent/Thread/Run.TenantID is deliberately hidden from the public Agent Protocol response shape via `json:"-"`, but an admin managing a multi-tenant deployment needs to see which tenant owns each row).

Deliberately namespaced /admin-api/* rather than /admin/*: the built React dashboard's static assets are served at /admin/* (see cmd/serve.go's embed.FS wiring) -- a JSON API and a static SPA sharing one path prefix would collide (e.g. GET /admin/agents meaning both "the agents API" and "a static file named agents").

Package api: A/B deployment routing via agent aliases. A client-facing name resolves to one of several REAL, independently-registered agent_ids at run-creation time, weighted by langgraph.json's "agent_aliases" config -- e.g. rolling a new graph version out to 10% of traffic while the stable one keeps serving 90%, both deployed as ordinary agents with no special "candidate" flag or code path of their own.

Package api: MCP-server support -- the reverse direction of the Connectors feature. Connectors let a Runkite AGENT consume external MCP tool servers (MCP-client direction); this file exposes Runkite's OWN configured agents AS MCP tools, so an external MCP client (an IDE, desktop app, or any other MCP-speaking application) can call them directly.

Mounted as a normal client-facing route (POST/GET/DELETE /mcp, not under /internal/*), so it goes through the exact same auth middleware (API key/JWT) every other client-facing endpoint does -- no separate auth mechanism to build or maintain. Each configured agent becomes one MCP tool; calling it dispatches a real run through the same createRunCtx + waitForRunResult path every client-facing create-and-wait endpoint already uses (the same pattern the internal A2A endpoint reuses for agent-to-agent calls), and waits for the result before responding -- MCP tool calls are inherently request/response, there's no streaming variant in the protocol to map onto Runkite's own SSE/WebSocket paths.

Package api: Agent marketplace / registry -- publish, discover, and deploy agent definitions. Deliberately scoped to a "minimal viable registry": a metadata catalog with publish/search/get/version-history, no security review workflow, and no automatic clone-and-execute deploy pipeline. A RegistryEntry's source_ref (a git URL, a plain URL, or an inline langgraph.json snippet) is where a human -- or their own separate tooling -- goes to actually deploy it, same as a package registry's listing page versus its install step. Running arbitrary fetched code is a fundamentally different trust/sandboxing problem than a searchable catalog, and out of scope here.

Package api implements the Agent Protocol HTTP endpoints. Each resource group (agents, threads, runs, store, streaming) is in its own file.

Vector/semantic store HTTP surface. Mirrors store.go's shape (PUT/DELETE/POST-search over a simple resource), and the Store Dual Mode convention: the exact same handlers are mounted again under /internal/vectors/* (see server.go) so a non-Python or POSTGRES_DSN-less runner can reach it with its runner token instead of a client credential it may not have.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetGovernancePendingTTLForTest

func SetGovernancePendingTTLForTest(d time.Duration) (restore func())

SetGovernancePendingTTLForTest sets the embedded approval ceiling and returns a restore func. Production code does not call this.

Types

type A2ARunRequest

type A2ARunRequest struct {
	AgentID     string                 `json:"agent_id"`
	ThreadID    string                 `json:"thread_id,omitempty"` // auto-generated if empty
	Input       json.RawMessage        `json:"input,omitempty"`
	Config      json.RawMessage        `json:"config,omitempty"`
	ParentRunID string                 `json:"parent_run_id"` // required
	OnBehalfOf  *transport.UserContext `json:"on_behalf_of,omitempty"`
	Wait        bool                   `json:"wait,omitempty"`
}

A2ARunRequest is the body for POST /internal/a2a/runs.

type AdminOverview

type AdminOverview struct {
	TotalAgents       int            `json:"total_agents"`
	TotalThreads      int            `json:"total_threads"`
	ThreadsByStatus   map[string]int `json:"threads_by_status"`
	TotalRuns         int            `json:"total_runs"`
	RunsByStatus      map[string]int `json:"runs_by_status"`
	ConnectorCount    int            `json:"connector_count"`
	CronScheduleCount int            `json:"cron_schedule_count"`
}

AdminOverview is the dashboard's summary view. Totals and by-status breakdowns come from store COUNT / GROUP BY aggregates (not fetch-then-len of a Search* page), so a soak that creates tens of thousands of rows still reports honest numbers.

type AdmissionLimits

type AdmissionLimits struct {
	TenantConcurrent int
	TenantDaily      int
	AgentConcurrent  int
	AgentDaily       int
}

AdmissionLimits is the runtime occupancy/quota config (values <= 0 = unlimited). Distinct from rate_limit token buckets.

func (*AdmissionLimits) Enabled

func (l *AdmissionLimits) Enabled() bool

Enabled reports whether any ceiling is configured.

type AliasResolver

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

AliasResolver picks a real agent_id for a configured alias name, weighted-random per call. Not goroutine-unsafe to construct fresh per server (the underlying map is read-only after construction); Resolve itself is safe for concurrent use since math/rand's package-level functions are.

func NewAliasResolver

func NewAliasResolver(cfg map[string]config.AgentAliasEntry) *AliasResolver

NewAliasResolver builds a resolver from langgraph.json's "agent_aliases" section. A nil/empty cfg produces a resolver whose Resolve is a pure pass-through (Resolve(x) == x, x, always) -- aliasing is entirely opt-in.

func (*AliasResolver) Resolve

func (r *AliasResolver) Resolve(agentID string) (string, bool)

Resolve returns (resolvedAgentID, wasAlias). wasAlias is false for any agentID that isn't a configured alias -- the caller passes it through unchanged, so a real agent_id that happens to not collide with any alias name behaves exactly as if aliasing didn't exist.

type ErrA2ABreadthExceeded

type ErrA2ABreadthExceeded struct {
	ParentRunID string
	Breadth     int
	MaxBreadth  int
}

ErrA2ABreadthExceeded means the parent already has max_breadth direct children -- client-actionable 400 (fan-out cap), not a server fault.

func (*ErrA2ABreadthExceeded) Error

func (e *ErrA2ABreadthExceeded) Error() string

type ErrA2ADepthExceeded

type ErrA2ADepthExceeded struct {
	Depth    int
	MaxDepth int
}

ErrA2ADepthExceeded means creating this run would exceed the configured Agent-to-Agent delegation chain limit (see A2AEntry.MaxDepth in internal/config/loader.go) -- a client-actionable 400, not a server error: the caller's delegation chain is too deep, nothing is broken.

func (*ErrA2ADepthExceeded) Error

func (e *ErrA2ADepthExceeded) Error() string

type RunCostDetail

type RunCostDetail struct {
	RunID   string   `json:"run_id"`
	AgentID string   `json:"agent_id"`
	Depth   int      `json:"depth"`
	Usage   RunUsage `json:"usage"`
}

RunCostDetail is one run's contribution to a RunCostSummary.

type RunCostSummary

type RunCostSummary struct {
	RootRunID string          `json:"root_run_id"`
	RunCount  int             `json:"run_count"`
	Usage     RunUsage        `json:"usage"`
	Runs      []RunCostDetail `json:"runs"`
}

RunCostSummary is the response for GET /runs/{runID}/cost: a rollup of usage across an entire A2A delegation tree, keyed by whichever run's ID the caller happened to have on hand -- any run in the tree resolves to the same root and the same aggregate.

Deliberately convention-based, not a new required field on Run or a Runner Protocol change: it reads whatever a run's own Output JSON already contains. If a runner's output happens to include a top-level "usage" object -- the same shape most LLM APIs already return (common LLM API-style prompt_tokens/completion_tokens/ total_tokens), plus an optional cost_usd -- it's picked up and summed across the tree. This ships real value against what agents already emit today; a future Runner Protocol version could make usage reporting authoritative instead of best-effort without changing this endpoint's shape, only extractRunUsage's source.

type RunUsage

type RunUsage struct {
	PromptTokens     int64   `json:"prompt_tokens,omitempty"`
	CompletionTokens int64   `json:"completion_tokens,omitempty"`
	TotalTokens      int64   `json:"total_tokens,omitempty"`
	CostUSD          float64 `json:"cost_usd,omitempty"`
	// Unmetered is set by a runner when it found an AI-shaped reply (a
	// real model turn happened) but could not extract any token/cost data
	// from it at all -- distinct from zero usage meaning "no LLM call
	// happened". Surfaces as a usage_unmetered audit alert (see
	// persistTerminalUsage) instead of silently looking free. The runner
	// side (python/runkite_runner/usage.py's usage_payload /
	// usage_or_unmetered) is where this gets set; it exists specifically
	// for a provider/framework integration whose usage-reporting shape
	// this codebase has never seen.
	Unmetered bool `json:"unmetered,omitempty"`
}

RunUsage is LLM token/cost usage for one run. Every field is best- effort: nothing in the Runner Protocol requires a runner to report usage today (deliberately, to ship this without a protocol version bump -- see RunCostSummary's doc comment), so a run that never reported any of this simply contributes all zeros to a rollup.

type Server

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

Server is the HTTP API server for the Agent Protocol.

func NewServer

func NewServer(store state.Store, queue transport.JobQueue, broker transport.EventBroker, cancel transport.CancelBroker) *Server

NewServer creates the HTTP API server.

func (*Server) BeginRunAttempt

func (s *Server) BeginRunAttempt(ctx context.Context, id string, generation int64) (bool, error)

BeginRunAttempt is called before a dequeued assignment is delivered. The durable fence makes a completion from a superseded dispatch harmless even when reclaim races a SQL write or a runner reconnects to another replica.

func (*Server) CompleteReclaimedRun

func (s *Server) CompleteReclaimedRun(ctx context.Context, pill transport.PoisonPill, errorMsg string) (bool, error)

CompleteReclaimedRun finalizes an exhausted assignment before the reaper removes its retained lease. Backend and finalization failures are retried by the next reclaim tick, including after a control-plane process restarts.

func (*Server) CompleteRun

func (s *Server) CompleteRun(ctx context.Context, c *state.RunCompletion) (bool, error)

CompleteRun is retryable after either an RPC failure or a lost response. The state store commits the result before the bridge removes its queue lease.

func (*Server) DispatchScheduledRun

func (s *Server) DispatchScheduledRun(ctx context.Context, scheduleName, agentID string, input, config json.RawMessage) (*models.Run, error)

DispatchScheduledRun creates and enqueues a run with no HTTP request involved at all -- for the cron scheduler (see cmd/cron.go) or any other non-HTTP caller. Uses a fixed thread per schedule name ("cron:<name>") so a schedule's run history is browsable as one continuous thread the same way any other Agent Protocol thread is, rather than a fresh disconnected thread per fire.

func (*Server) FinOps

func (s *Server) FinOps() *finops.Config

FinOps returns the effective (file ∪ overlay) config. Nil when FinOps is unset. Safe for concurrent readers; overlays swap via atomic store.

func (*Server) Handler

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

Handler returns an http.Handler with all Agent Protocol routes registered.

func (*Server) RegisterAdmissionGate

func (s *Server) RegisterAdmissionGate(d *hooks.Dispatcher)

RegisterAdmissionGate installs the run-admission Gate on dispatcher. Safe when policy is nil (authz + kill + budgets still apply).

func (*Server) ReloadFinOpsOverlays

func (s *Server) ReloadFinOpsOverlays(ctx context.Context)

ReloadFinOpsOverlays loads the SQL overlay and swaps the effective config (file baseline ∪ overlay). Called after Admin PUT/DELETE on the writing replica, and by the background poll for siblings.

func (*Server) ReloadMandatoryHITL

func (s *Server) ReloadMandatoryHITL(ctx context.Context)

ReloadMandatoryHITL loads durable SQL rules into the in-process engine. Called after Admin CRUD on the writing replica, and by the overlay poll.

func (*Server) ReloadPolicyOverlays

func (s *Server) ReloadPolicyOverlays(ctx context.Context)

ReloadPolicyOverlays loads durable SQL grants into the in-process engine. Called after Admin grant CRUD on the writing replica, and by the background overlay poll so sibling replicas converge without a restart. No-op when policy is off or the store has no grant table.

func (*Server) SetA2AMaxBreadth

func (s *Server) SetA2AMaxBreadth(breadth int)

SetA2AMaxBreadth configures the maximum number of direct children one parent run may create via A2A. Never called (or <= 0) → defaultA2AMaxBreadth.

func (*Server) SetA2AMaxDepth

func (s *Server) SetA2AMaxDepth(depth int)

SetA2AMaxDepth configures the maximum Agent-to-Agent delegation chain depth. Called after NewServer when an "a2a" config section is present; never called (or called with <= 0) means defaultA2AMaxDepth applies.

func (*Server) SetAdminSessions

func (s *Server) SetAdminSessions(h *auth.AdminSessionHandlers)

SetAdminSessions wires Admin UI httpOnly cookie session endpoints.

func (*Server) SetAdmissionLimits

func (s *Server) SetAdmissionLimits(l *AdmissionLimits)

SetAdmissionLimits attaches occupancy/quota ceilings from admission_limits config. Nil or all-zero disables checks.

func (*Server) SetAliasResolver

func (s *Server) SetAliasResolver(r *AliasResolver)

SetAliasResolver attaches A/B deployment routing (see alias.go). Called after NewServer when an "agent_aliases" config section is present; a never-set resolver means every agent_id passes through unchanged, same as before this feature existed.

func (*Server) SetConnectorRegistry

func (s *Server) SetConnectorRegistry(r *connector.Registry)

SetConnectorRegistry attaches a connector registry to the server. Called after NewServer when connectors are configured.

func (*Server) SetConnectorSessionStore

func (s *Server) SetConnectorSessionStore(store connector.ConnectorSessionStore)

SetConnectorSessionStore wires short-lived MCP capability tokens (minted on GetSession, required on /mcp). Production always sets this (Redis when REDIS_URL is set, else memory).

func (*Server) SetCustomRoutesProxy

func (s *Server) SetCustomRoutesProxy(proxy http.Handler, mount string)

SetCustomRoutesProxy attaches a reverse proxy for user-defined routes. mount is the external URL prefix (e.g. "/custom" or "/sales-assistant"); empty means customroutes.DefaultMount. Called after NewServer when custom_routes is configured; nil proxy (the default) means the mount 404s.

Mount is read on every request (same reason as the proxy field itself — Handler() is often built before SetCustomRoutesProxy in tests).

func (*Server) SetFinOps

func (s *Server) SetFinOps(cfg *finops.Config)

SetFinOps attaches the file-baseline FinOps config and seeds the effective pointer. Overlay reload (Admin write / sibling poll) re-merges on top of this baseline without a process restart.

func (*Server) SetHookDispatcher

func (s *Server) SetHookDispatcher(d *hooks.Dispatcher)

SetHookDispatcher attaches an event-hook dispatcher to the server. Called after NewServer when webhooks (or other hook sinks) are configured.

func (*Server) SetPayloadShrink

func (s *Server) SetPayloadShrink(cfg payloadshrink.Settings, store payloadshrink.Store)

func (*Server) SetPolicyEngine

func (s *Server) SetPolicyEngine(e *policy.Engine)

SetPolicyEngine attaches the connector/tool policy engine. Nil keeps V1 open connector access (after runner auth + run-binding).

func (*Server) SetPolicyRunEvents

func (s *Server) SetPolicyRunEvents(on bool)

SetPolicyRunEvents toggles publishing method "tool_auth" RunEvents when a connector session or tools/call is denied by policy.

func (*Server) SetRateLimiter

func (s *Server) SetRateLimiter(l *ratelimit.Limiter)

SetRateLimiter attaches a rate limiter to the server. Called after NewServer when a rate_limit config is present; a nil/never-set limiter means per-agent limiting in createRun is a no-op (global/per-user limiting is a separate HTTP middleware layer -- see ratelimit.Middleware in cmd/serve.go).

func (*Server) SetStrictPermissions

func (s *Server) SetStrictPermissions(strict bool)

SetStrictPermissions stores auth.strict_permissions for AllowsSimulation at create-run time. Pass the same value given to MiddlewareOpts.

func (*Server) SetVectorStore

func (s *Server) SetVectorStore(vs vectorstore.VectorStore)

SetVectorStore attaches a vector/semantic store. Called after NewServer when vector_store is configured; a nil vectors field (the default) means /vectors/* responds 501 Not Implemented instead of silently 404ing -- "this feature isn't turned on" is a different, more actionable signal than "this route doesn't exist".

func (*Server) SetWSOriginPatterns

func (s *Server) SetWSOriginPatterns(origins []string)

SetWSOriginPatterns configures WebSocket Origin checks for /threads/{id}/websocket. Pass the same list as cors.allow_origins. A nil/empty list leaves AcceptOptions nil (any Origin).

func (*Server) StatusCallback

func (s *Server) StatusCallback() func(runID, status, errorMsg string)

StatusCallback is a legacy trusted control-plane completion entry point. Production runners use generation-bearing lifecycle callbacks, and the reaper uses CompleteReclaimedRun so persistence failures retain the lease.

func (*Server) TimeoutOverdueRuns

func (s *Server) TimeoutOverdueRuns(ctx context.Context, maxDuration time.Duration, limit int) (int, error)

TimeoutOverdueRuns finds pending/running runs whose created_at is older than maxDuration and forces each to status "timeout". Multi-instance safe: the shared completion transaction selects one transition winner and atomically releases the thread. Queue removal follows successful finalization. The count includes newly committed timeouts, even if their finalization fails; an error reports incomplete bookkeeping that ordinary reclaim can retry.

Distinct from crash reclaim (heartbeat lease): reclaim covers a dead runner; this covers a live one that never finishes (stuck tool loop, etc.). Opt-in via langgraph.json's "run_timeout" section -- see cmd/run_timeout.go.

Jump to

Keyboard shortcuts

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