agent

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 33 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 agent is the embedded agent of a Surface app: one agent the owner talks to in the agent panel, with every tool in the app, whose context changes with what is in front.

Per message it: routes (router: a rule may run a call directly), puts the conversation to the reflexes (reflex: reminders, a halt, actions), chooses the active context slots (slots.Selector: today the window in front), assembles the <context> block from them (slots.Assemble: top-of-mind tools, instructions, the module's knowledge, the agent's note, where things are kept), and hands the message to the Engine.

The engine is a seam (Engine): libs agent/host today, Nanite's embeddable package when it ships. Its wire, agent-host/1, is what the panel speaks; Surface serves it under /api/agent/ and overrides only the turn route, so the context is assembled here from the desk and never sent by the page.

Index

Constants

View Source
const (
	RunFinished = "finished"
	RunCanceled = "canceled"
	RunFailed   = "failed"
)

Run statuses as the bus carries them.

View Source
const Owner = "owner"

Owner is the one person a Surface app serves. Surface apps are single-user and loopback-only; the engine still wants a name to keep threads by.

View Source
const Prefix = "/api/agent"

Prefix is where the agent's routes are served.

View Source
const RunnerNanite = "nanite"

RunnerNanite names the Nanite runner.

View Source
const RunnerScripted = "scripted"

RunnerScripted names the library's scripted test runner.

Variables

View Source
var (
	ErrNotReady = errors.New("no model is configured for the agent")
	ErrBusy     = errors.New("the agent is still working on the last message")
)

The engine's refusals, whatever engine is in use.

Functions

func ConfigPath

func ConfigPath(app string) string

ConfigPath is where the agent config of app is read from.

Types

type Approver

type Approver interface {
	Approve(ctx context.Context, r Request) (bool, error)
}

Approver decides whether the agent may make a call that changes something (levels write and confirm). It is the hook for an outside approval service (Gatecrasher). With none, the engine asks the owner in the panel, which is the default.

type ClassifierConfig added in v0.2.0

type ClassifierConfig struct {
	// DecideURL is the AI gateway: the classifier posts to <url>/ai/decide, and to
	// <url>/ai/embeddings when EmbedModel is set. Also unix:///path.sock.
	DecideURL string `json:"decide_url,omitempty"`
	// EmbedModel turns on the centroid judges and the emerging-label report: the gateway's
	// embedding model to use ("text-embedding-3-small"). Pin it: vectors from different
	// models do not compare.
	EmbedModel string `json:"embed_model,omitempty"`
	// KeyFile holds the gateway's bearer key. "~/" is the home directory. Optional.
	KeyFile string `json:"key_file,omitempty"`
	// Model is the model hint; pin one (jev-1.13.0) to keep results comparable.
	Model string `json:"model,omitempty"`
	// Purpose is what the gateway accounts the spend to; default surface_classify.
	Purpose string `json:"purpose,omitempty"`
}

ClassifierConfig is the classifier's async tier.

type Engine

type Engine interface {
	// Ready reports whether a model is configured, so a message can be answered.
	Ready() bool
	Model() string
	// AddTools gives the agent tools it runs itself. Call before serving.
	AddTools(tools ...EngineTool) error
	// Start takes the owner's message and begins answering it; the answer is the run's
	// event stream, served by Handler.
	Start(ctx context.Context, t Turn) (runID string, err error)
	// History is the owner's conversation so far, most recent last.
	History(ctx context.Context, owner string) ([]Said, error)
	// Handler serves the wire under prefix: the thread, the run streams, tool results,
	// approvals, cancel. Surface overrides the turn route itself.
	Handler(prefix string, owner func(*http.Request) (string, error)) http.Handler
	Close()
}

Engine is the seam the embedded agent plugs into. Everything else in Surface (slots, router, reflexes, the panel's wire) talks to this, so the agent underneath can change without them: today libs agent/host, later Nanite's embeddable package.

The wire it serves is agent-host/1 (libs agent/host WIRE.md), which the page's @hollis-labs/ade-agent client speaks.

type EngineTool

type EngineTool struct {
	Name        string
	Description string
	InputSchema map[string]any
	// Level is read, act, write or confirm.
	Level string
	Run   func(ctx context.Context, input json.RawMessage) (string, error)
}

EngineTool is a tool the engine runs itself.

type FileConfig

type FileConfig struct {
	// Model is the gateway's model name ("anthropic-opus").
	Model string `json:"model"`
	// GatewayURL is an Anthropic-compatible endpoint; the engine posts to <url>/v1/messages.
	GatewayURL string `json:"gateway_url"`
	// KeyFile holds the bearer key. "~/" is the home directory.
	KeyFile string `json:"key_file"`
	// System is added to the agent's standing instructions.
	System    string `json:"system,omitempty"`
	MaxTokens int    `json:"max_tokens,omitempty"`
	MaxSteps  int    `json:"max_steps,omitempty"`
	CompactAt int    `json:"compact_at,omitempty"`
	// MCP lists outside MCP servers whose tools the agent gets. Reserved: the engine does
	// not speak MCP yet (libs agent/host has no MCP client).
	MCP map[string]json.RawMessage `json:"mcp,omitempty"`

	// Agents says where the agent's authored directory is kept, for a runner that has one
	// (Nanite): <dir>/<app>. Default: agents/ beside this file.
	Agents struct {
		Dir string `json:"dir,omitempty"`
	} `json:"agents,omitempty"`
	// Builtins turns on tool groups of the runner's own (Nanite: files-read, files-write,
	// shell, background, subagents, skills, notes, or all). None by default: the agent has
	// the app's tools.
	Builtins []string `json:"builtins,omitempty"`

	// Classifier configures the classifier's async tier: a decision gateway (JEV) asked
	// about each message after the turn. Without DecideURL there is no async tier.
	Classifier ClassifierConfig `json:"classifier,omitempty"`

	// Path is the file this was read from ("" when there was none).
	Path string `json:"-"`
}

FileConfig is the agent and harness configuration. It lives in a file, not the app's database (the app's own settings do): ~/.config/<app>/agent.json, or the file SURFACE_AGENT_CONFIG names. Environment variables override single fields for a development run: SURFACE_AGENT_GATEWAY, SURFACE_AGENT_MODEL, SURFACE_AGENT_KEY_FILE.

The key itself is never in this file: KeyFile names a file that holds it, read on every request, so it can be rotated without a restart.

func LoadConfig

func LoadConfig(app string) (FileConfig, error)

LoadConfig reads the agent config of app. A missing file is not an error: the agent is then not ready until one is written, and says so.

func (FileConfig) AgentDir added in v0.2.0

func (c FileConfig) AgentDir(app string) string

AgentDir is the authored directory of the app's agent: <agents.dir>/<app>, where agents.dir defaults to agents/ beside the agent config file.

type Options

type Options struct {
	// Approver, when set, replaces the in-panel question for write and confirm calls.
	Approver Approver
	// Engine, when set, is used instead of libs agent/host (tests, and Nanite later).
	Engine Engine
	// Selector, when set, replaces the default: the focus selector, overruled by the
	// classifier when the setting surface.agent_selector is "classifier".
	Selector slots.Selector
	// Decider, when set, is the classifier's async tier instead of the one the config file
	// names (tests).
	Decider decide.Decider
	// Embedder, when set, is the classifier's embedder instead of the gateway's (tests).
	Embedder classify.Embedder
}

Options are the service's optional parts.

type Request

type Request struct {
	Tool   string
	Module string
	Level  module.Level
	Input  json.RawMessage
}

Request is one call put to an Approver.

type Said

type Said struct {
	Role      string
	Text      string
	ToolNames []string
	CreatedAt string
}

Said is one message of the conversation, as the reflexes see it.

type Service

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

Service is the embedded agent.

func New

func New(k kernel.Kernel) (*Service, error)

New builds the agent service from the kernel. A missing agent config is not an error: the panel says the agent is not set up, and everything else works.

func NewWith

func NewWith(k kernel.Kernel, o Options) (*Service, error)

NewWith is New with options.

func (*Service) Close

func (s *Service) Close(context.Context) error

Close stops the engine and the worker.

func (*Service) Engine

func (s *Service) Engine() Engine

Engine is the engine in use.

func (*Service) Mount

func (s *Service) Mount(mux *http.ServeMux)

Mount serves the agent under /api/agent/: the agent-host/1 wire (engine), with the turn route Surface's own, plus the context, slots, reflexes and rules.

GET    /api/agent                      {available, ready, model} (engine)
GET    /api/agent/thread               the conversation (engine)
DELETE /api/agent/thread               start a new one (engine)
POST   /api/agent/turns                {text, client_id, auto?} → {run_id}; 422 {code:"halted"} when a reflex answered
GET    /api/agent/runs/{id}/events     the run's chatstream/v1 events (engine)
POST   /api/agent/runs/{id}/approvals  {approval_id, decision} (engine)
POST   /api/agent/runs/{id}/cancel     (engine)
GET    /api/agent/context              the context the next message would carry (slots.Assembly)
GET    /api/agent/setup                {ready, model, config_path, reason?}
GET    /api/agent/slots                every slot, with notes, the active one marked
POST   /api/agent/slots/pin            {slot} ("" unpins)
GET    /api/agent/reflexes             PUT/DELETE /api/agent/reflexes/{name}
GET    /api/agent/rules                PUT/DELETE /api/agent/rules/{id}
POST   /api/agent/classify             {text} → the classifier's result for a draft (classify.Result); records nothing
POST   /api/agent/classify/feedback    {text, facet, label, accepted}: the owner's answer to a hint (an accepted slot pins it)
GET    /api/agent/classify/replay      a fresh classifier replayed over the trace, against the selector
GET    /api/agent/classify/emerging    ?facet=act&limit=500: clusters among turns the facet abstained on (needs an embedder)

The app is loopback-only and single-user: every request is the owner's.

func (*Service) Preview

func (s *Service) Preview(ctx context.Context) slots.Assembly

Preview is the context the next message would carry, without reflexes or routing.

func (*Service) Send

func (s *Service) Send(ctx context.Context, text, clientID, auto string) (TurnResult, error)

Send takes a message from the owner and starts the agent on it.

func (*Service) SetupProblem

func (s *Service) SetupProblem() string

SetupProblem says, in a sentence for the owner, why the agent cannot answer, or "" when nothing is wrong that can be seen from here. It is worked out at each call: the key file is read at every request, so fixing it takes effect without a restart. The key itself is never read into the answer; only whether the file can be read.

func (*Service) Tools

func (s *Service) Tools() []kernel.BoundTool

Tools are the agent's own tools (slots, reflexes, routing rules), bound like the app's, for the app to offer outside agents too (/api/tools, MCP).

type SlotInfo

type SlotInfo struct {
	Name        string   `json:"name"`
	Module      string   `json:"module,omitempty"`
	About       string   `json:"about"`
	Views       []string `json:"views,omitempty"`
	Modes       []string `json:"modes,omitempty"`
	Tools       []string `json:"tools,omitempty"`
	Note        string   `json:"note,omitempty"`
	NoteUpdated string   `json:"note_updated,omitempty"`
	Active      bool     `json:"active"`
}

SlotInfo is one slot, for the panel and context_switch.

type StandingGrant added in v0.2.0

type StandingGrant struct {
	Agent   string `json:"agent"`
	Tool    string `json:"tool"`
	Reason  string `json:"reason,omitempty"`
	Created string `json:"created"`
}

StandingGrant is one kept approval, as the API lists it.

type Turn

type Turn struct {
	Owner string
	Text  string
	// ClientID identifies the page that sent it.
	ClientID string
	// Context is what the model sees with the message. Surface sends {"block": "<context>…"}
	// plus the assembly, for the panel to show.
	Context json.RawMessage
	// Auto marks a message the app wrote and the owner did not type.
	Auto string
}

Turn is one message from the owner.

type TurnResult

type TurnResult struct {
	RunID    string         `json:"run_id,omitempty"`
	Halted   string         `json:"halted,omitempty"`
	Routed   *router.Route  `json:"routed,omitempty"`
	Fired    []string       `json:"fired,omitempty"`
	Assembly slots.Assembly `json:"assembly"`
}

TurnResult is what Send did with a message.

Jump to

Keyboard shortcuts

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