agent

package
v0.23.3 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 46 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 submits the message on the conversation wire.

Nanite serves embedded agents on the durable conversation wire.

Index

Constants

View Source
const (
	DialectLLMGateway = "llm-gateway"
	DialectTether     = "tether"
)

Classifier gateway dialects.

View Source
const (
	// ProfileDefault pins the app's own seat.
	ProfileDefault = "default"
	// ProfileAuto clears a pin: the window in front chooses again.
	ProfileAuto = "auto"
)

Profile choices that are not a module.

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

Run statuses as the bus carries them.

View Source
const LateErrand = "late-answer"

LateErrand is the errand name a late answer's turn carries.

View Source
const Owner = "owner"

Owner is the one person a Surface app serves. Surface apps are single-user and loopback-only; conversations belong to this owner.

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.

View Source
const TopicCompacted = "agent.compacted"

TopicCompacted reports successful Nanite compaction on the app bus.

View Source
const TopicProfile = "agent.profile"

TopicProfile is published when a conversation's profile pin changes.

Variables

This section is empty.

Functions

func ConfigPath

func ConfigPath(app string) string

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

func ModuleGateway added in v0.4.0

func ModuleGateway(app string) (module.Gateway, error)

ModuleGateway is the model gateway the app's agent config names, as a module is given it (module.Agent.Gateway): the model, the gateway URL and the key file's path, never the key. It reads the config file now, so an edit takes effect without a restart.

func ParseBindings added in v0.10.0

func ParseBindings(value any) (map[string]string, error)

ParseBindings checks the persisted module-to-folder setting without coercing paths.

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 runner asks the owner in the panel, which is the default.

type BindingInfo added in v0.10.0

type BindingInfo struct {
	ID             string   `json:"id"`
	Title          string   `json:"title"`
	Dir            string   `json:"dir,omitempty"`
	Name           string   `json:"name,omitempty"`
	Error          string   `json:"error,omitempty"`
	IgnoredRuntime []string `json:"ignored_runtime,omitempty"`
}

BindingInfo includes modules without built-in profiles so any module can be bound.

type ClassifierConfig added in v0.2.0

type ClassifierConfig struct {
	// GatewayURL is the gateway's base URL (or unix:///path.sock).
	GatewayURL string `json:"gateway_url,omitempty"`
	// Dialect is how the gateway is spoken to:
	//   - "llm-gateway" (default): JEV's System-1 API at <url>/v1/systemone and
	//     OpenAI-compatible <url>/v1/embeddings, with the gateway's model aliases.
	//   - "tether": a decision gateway's <url>/ai/decide and <url>/ai/embeddings.
	Dialect string `json:"dialect,omitempty"`
	// KeyFile holds the gateway's bearer key ("~/" is the home directory). The key needs
	// the decide scope for DecideModel and the embed scope for EmbedModel.
	KeyFile string `json:"key_file,omitempty"`
	// Warden, instead of KeyFile: mint short-lived gateway tokens from a Warden parent
	// credential (rotate-on-use). Set exactly one of KeyFile and Warden.
	Warden *WardenConfig `json:"warden,omitempty"`
	// DecideModel turns on the JEV judge: the gateway's decision route ("jev"). Pinned
	// models keep results comparable.
	DecideModel string `json:"decide_model,omitempty"`
	// EmbedModel turns on the centroid judges and the emerging-label report: the gateway's
	// embedding route ("embed-local", "embed-openai"). Vectors from different models do not
	// compare, so changing it refits the centroids from scratch.
	EmbedModel string `json:"embed_model,omitempty"`
	// Purpose is what a decision gateway accounts the spend to; default surface_classify.
	Purpose string `json:"purpose,omitempty"`
}

ClassifierConfig is the classifier's async tier: a model gateway asked about each message after the turn, off its path. With no GatewayURL there is no async tier.

type FileConfig

type FileConfig struct {
	// Tether attaches the page to an app-bound CLI seat instead of the embedded runner.
	Tether TetherConfig `json:"tether,omitempty"`

	// 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"`
	// ProvidersFile is the app's providers.yaml (Nanite's format: named providers and a
	// provider and model per use), kept by the app or its owner rather than authored in the
	// agent directory: a module's settings page may write it. The Nanite runner stages it
	// into the agent directory before each turn, so an edit takes effect on the next turn.
	// When it selects use.chat, model, gateway_url and key_file are optional. Default:
	// <app data dir>/agent/providers.yaml. "~/" is the home directory.
	ProvidersFile string `json:"providers_file,omitempty"`
	// 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"`
	// AutoApprove bypasses approval asks for testing; explicit denies still apply.
	AutoApprove bool `json:"auto_approve,omitempty"`
	// FrontDesk opts into Nanite planning and paced background deliveries.
	FrontDesk *FrontDeskConfig `json:"front_desk,omitempty"`
	// MCP lists outside MCP servers whose tools the agent gets. Reserved: the engine does
	// not use this field; configure MCP in the Nanite agent directory.
	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"`

	// Mailbox gives the Nanite agent a Tether mailbox of its own: the agent directory's
	// host.yaml names the address (identity.tether), and this names Tether and the
	// credential. Unread mail to that address arrives in the conversation as notice turns.
	Mailbox *MailboxConfig `json:"mailbox,omitempty"`

	// Classifier configures the classifier's async tier: a decision gateway (JEV) asked
	// about each message after the turn. Without GatewayURL 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.

func (FileConfig) ProvidersPath added in v0.17.0

func (c FileConfig) ProvidersPath(dataDir string) string

ProvidersPath is where the app's providers file is read from.

type FrontDeskConfig added in v0.11.0

type FrontDeskConfig struct {
	Mode                 string `json:"mode,omitempty"`
	PlanWithModel        bool   `json:"plan_with_model,omitempty"`
	PlannerInstructions  string `json:"planner_instructions,omitempty"`
	IntakeTimeoutSeconds int    `json:"intake_timeout_seconds,omitempty"`
	MergeWindowMS        int    `json:"merge_window_ms,omitempty"`
	ResumeInterrupted    bool   `json:"resume_interrupted,omitempty"`
}

FrontDeskConfig is optional host policy; nil keeps the existing chat behavior. Mode off enables paced deliveries without intake planning. Planning and automatic restart resume are explicit opt-ins and never change tool approvals.

type MailboxConfig added in v0.14.0

type MailboxConfig struct {
	// URL is Tether's HTTP API (registry and messages), HTTPS except on loopback.
	URL string `json:"url"`
	// CredentialFile holds the agent's bearer credential ("~/" is the home directory), read
	// by Nanite; it is never put in the environment or sent to the page. 0600.
	CredentialFile string `json:"credential_file"`
	// PollSeconds is how often unread mail is looked for (default 30).
	PollSeconds int `json:"poll_seconds,omitempty"`
}

MailboxConfig is where the agent's own Tether mail is read (Nanite's mailbox).

type Options

type Options struct {
	// Bindings reads live module-to-agent directory settings. Modules lists all bindable modules.
	Bindings func() map[string]string
	Modules  map[string]string
	// Approver, when set, replaces the in-panel question for write and confirm calls.
	Approver Approver
	// 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 ProfileChoice added in v0.4.0

type ProfileChoice struct {
	// ID is the module whose profile it is; "" is the app's own seat.
	ID       string `json:"id"`
	AgentDir string `json:"agent_dir,omitempty"`
	// Why is "pinned", "focus", "default" or "off" (the runner does not run profiles).
	Why string `json:"why"`
}

ProfileChoice is the profile a turn runs as, and why.

type ProfileInfo added in v0.4.0

type ProfileInfo struct {
	*profile.Profile
	Active bool `json:"active"`
}

ProfileInfo is one profile, for the panel and profile_switch.

type ProfileState added in v0.4.0

type ProfileState struct {
	// On says turns run as profiles (the Nanite runner); off, every turn is the seat.
	On     bool          `json:"on"`
	Runner string        `json:"runner,omitempty"`
	Active ProfileChoice `json:"active"`
	// Pinned is the conversation's pin: a module id, "default", or "".
	Pinned   string        `json:"pinned,omitempty"`
	Profiles []ProfileInfo `json:"profiles"`
	Bindings []BindingInfo `json:"bindings"`
}

ProfileState is what GET /api/agent/profiles says.

type Request

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

Request is one call put to an Approver.

type RunRecord added in v0.4.0

type RunRecord struct {
	RunID     string `json:"run_id"`
	StartedAt string `json:"started_at"`
	EndedAt   string `json:"ended_at,omitempty"`
	Status    string `json:"status,omitempty"`
	Reason    string `json:"reason,omitempty"`
	Origin    string `json:"origin,omitempty"`
	Slot      string `json:"slot,omitempty"`
	// Profile is the agent profile the run acted as: a module's id, or "default" (the seat).
	AgentDir  string   `json:"agent_dir,omitempty"`
	Profile   string   `json:"profile,omitempty"`
	Provider  string   `json:"provider,omitempty"`
	Model     string   `json:"model,omitempty"`
	Uncached  int      `json:"uncached_input"`
	CacheRead int      `json:"cache_read"`
	CacheWrit int      `json:"cache_write"`
	Output    int      `json:"output"`
	Tools     []string `json:"tools"`
	Ms        int64    `json:"ms"`
}

RunRecord is one run as the log keeps 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) AskFrom added in v0.4.0

func (s *Service) AskFrom(ctx context.Context, mod string, a module.Ask) (string, error)

AskFrom runs a module's errand as a turn on the agent's conversation (kernel.Asker).

func (*Service) Close

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

Close stops the runner and the worker.

func (*Service) Mount

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

Mount serves conversation transport and the agent configuration/context routes.

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/profiles             the module agent profiles, the active one and the pin (ProfileState)
POST   /api/agent/profiles/pin         {profile}: a module id, "default" (the app's own) or "auto"/"" (unpin)
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) PruneBindingSnapshots added in v0.10.1

func (s *Service) PruneBindingSnapshots()

PruneBindingSnapshots refreshes current bindings before collecting old unused snapshots. A missing or invalid bound folder skips pruning altogether.

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 StandingState added in v0.4.0

type StandingState struct {
	Path string `json:"path"`
	Text string `json:"text"`
	// InSystemPrompt reports that Nanite reads this text on its next turn.
	InSystemPrompt bool `json:"in_system_prompt"`
	Chars          int  `json:"chars"`
}

StandingState is what standing_get says.

type TetherConfig added in v0.4.0

type TetherConfig struct {
	URL     string `json:"url"`
	Seat    string `json:"seat"`
	KeyFile string `json:"key_file,omitempty"`
}

TetherConfig names the chat wire endpoint and the statically app-bound seat. KeyFile stays on the server and is read per request; it is never sent to the page.

type ToolBinding added in v0.4.0

type ToolBinding 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)
}

ToolBinding is a server tool offered to Nanite.

type WardenConfig added in v0.4.0

type WardenConfig struct {
	// URL is Warden's base URL.
	URL string `json:"url"`
	// CredentialFile holds the parent credential ("~/" is the home directory). It is
	// rewritten on every mint; keep it 0600. Apps may share one file: mints take a lock.
	CredentialFile string `json:"credential_file"`
	// Audience is the tokens' audience ("llm-gateway").
	Audience string `json:"audience"`
	// Scopes narrows the tokens; empty asks for what the grant allows.
	Scopes []string `json:"scopes,omitempty"`
}

WardenConfig names a Warden and the parent credential the classifier mints gateway tokens from.

Directories

Path Synopsis
Package profile reads, checks and stages module agent profiles.
Package profile reads, checks and stages module agent profiles.

Jump to

Keyboard shortcuts

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