host

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: Apache-2.0 Imports: 26 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

agent/host

The reusable host application core for the mcpkit agent module. It assembles agent/ (Provider, Runner, ToolSource, elicitation, injection/trigger policies) into a runnable host without committing to any particular UI. A terminal CLI and a future web-chat surface both build on it; the only thing that differs is the reader/writer you hand it (stdin/stdout versus a socket).

Nested Go module (github.com/panyam/mcpkit/agent/host) under agent/, so its heavier dependencies (ext/auth, ext/skills, ext/tasks, events client, gocurrent) stay out of the lean agent/ module.

What lives here

  • Config loading (config.go): Config, LoadConfig, and the provider / server / auth / event / trigger sub-configs. This is the bulk of the package. Where and how to load providers, servers (with per-server auth), tool allowlists, skills, events, and triggers.
  • The App (app.go): NewApp(cfg, out, in, opts...) builds the Runner, the aggregated tool sources, the FanIn event consumption loop, the injection and trigger policies, and background-task bookkeeping. RunTurn drives one turn; REPL drives an interactive loop; Close tears down.
  • Meta-tools (metatools.go): host-local tools the model calls to manage its own async work (subscribe_events, create_trigger, list_tasks, cancel_task, and friends), installed under source id host.
  • Surface seams: terminal elicitation UI (elicit.go) and rendering (render.go). Swap these for a different surface.
  • Subscriptions and background tasks (subscription.go, tasks_bg.go): event-stream lifecycle and detach-after-grace task execution.

Options

  • WithProvider(p) — supply the LLM Provider (e.g. StubProvider for tests, OpenAIProvider for a real model).
  • WithTracerProvider(tp) — SEP-414 tracing.
  • WithLogger(l) — structured logging.
  • WithRunStore(store) — session persistence. Every completed turn's messages and event stream append to a run in the store (agent.NewInMemoryRunStore for in-process resume/fork; agent/store/redis or agent/store/gorm — Postgres, or a serverless SQLite file — for restart-surviving sessions).
  • WithToolResultStore(store) — backing store for tool-result offloading (Config.Offload). Over-threshold results are stored out of band and the model gets a compact stub plus a read_tool_result tool; omit the option and offloading uses an in-memory store, pass a durable one for blobs that survive restarts. Durable options: agent/store/redis, agent/store/gorm, or the dependency-free agent.NewFileToolResultStore(dir) — the no-server local path where blobs are files the agent can also read directly. Config.Offload (nil = off) sets the byte threshold, preview length, and per-tool overrides. App.AttachRun names or resumes a session at startup; App.Resume and App.Fork switch runs mid-session (/resume <id>, /fork [id], /session in the REPL). A failed or cancelled turn persists nothing; persistence failures degrade to a rendered warning, never a turn failure.

Skills trust model

Skills are data, not code (ext/skills is enforced no-exec), so the risk a skills server carries is context-poisoning, not side effects. ServerConfig.SkillsMode is the trust lever. "eager" splices full skill bodies into the system prompt at connect time with no per-skill gate — reserve it for servers you trust. "catalog" is the safer default for a lower-trust server: a skill enters context only when the model calls load_skill, which is an ordinary tool, so it flows through the approval ladder (set Approval.Rules["load_skill"] = "ask" to confirm each activation — the prompt names the requested skill). The fetched body lands in tool history rather than the system prompt, so it carries less authority. See the SkillsMode godoc in config.go.

Testing

Fully offline: real in-process mcpkit servers plus a scripted StubProvider plus a canned reader. See examples/agent-async for a golden-transcript scenario and cmd/agentchat for the terminal CLI built on this package.

Run the module's tests with just test-agent from the repo root, or cd agent/host && go test ./... directly.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrUnknownCommand = errUnknownCommand{}

ErrUnknownCommand is returned by Dispatch when the line is not a registered command (so the caller treats it as a conversational turn, not an error to surface).

Functions

func BuildEmbedder

func BuildEmbedder(conn ConnectionConfig, tp core.TracerProvider) (agent.Embedder, error)

BuildEmbedder builds an agent.Embedder from an embedder connection, the counterpart of DefaultProviderBuilder for the embedder role. Embeddings are an OpenAI-wire concern (an /embeddings endpoint), so every supported type resolves through the OpenAI-compatible embedder — EXCEPT "anthropic", which exposes no embeddings API and is rejected. tp opts the embedder into its agent.embed span; nil is fine.

func DefaultProviderBuilder

func DefaultProviderBuilder(conn ConnectionConfig) (agent.Provider, error)

DefaultProviderBuilder builds the provider for a connection: the native Anthropic Messages-API provider when Type is "anthropic", otherwise an OpenAI-wire provider (lmstudio / openai / ollama / gemini / any BaseURL). The base URL resolves from BaseURL or the Type table and the key from APIKeyEnv.

Types

type App

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

App is agentchat's testable core: everything the binary does minus flag parsing and signal handling. Construct with NewApp, converse with RunTurn (one input, one rendered turn) or REPL (interactive loop).

func NewApp

func NewApp(cfg *Config, out io.Writer, in io.Reader, opts ...AppOption) (*App, error)

NewApp connects every configured server and assembles the agent. The returned App owns the client connections; call Close when done.

func (*App) AttachRun

func (a *App) AttachRun(ctx context.Context, runID string) error

AttachRun binds the session to runID with create-or-resume semantics: an existing run's history is loaded and threaded (resume), an absent one is created empty. This is the startup path for surfaces that name sessions ("continue yesterday's run-x or start it fresh"); for a must-exist switch mid-session, use Resume.

func (*App) Close

func (a *App) Close()

Close stops event streams and disconnects every server.

func (*App) Commands

func (a *App) Commands() *CommandRegistry

Commands exposes the registry so a surface can list commands or drive tab-completion.

func (*App) Dispatch

func (a *App) Dispatch(ctx context.Context, line string) (CmdResult, error)

Dispatch parses a "/name args" line, looks the command up, and runs it. A line that is not a known command returns (CmdResult{}, ErrUnknownCommand) so the caller can distinguish "not a command, treat as a turn" from a command that failed.

func (*App) Fork

func (a *App) Fork(ctx context.Context, newRunID string, atMessage int) (string, error)

Fork copies the current run's log into a new run (newRunID empty asks the store to generate one) and switches the session to the copy, which diverges from the next turn on while the original stays untouched. atMessage positive forks from an earlier point — only the first atMessage messages carry over (checkpoint/rewind), and the in-memory history rewinds to match by reloading the fork; zero or negative forks the whole log, and history is already the shared prefix so no reload is needed.

func (*App) LoginServer

func (a *App) LoginServer(id string)

LoginServer forces a fresh interactive login for an oauth-configured server: it drops any cached token and reconnects, so the client's next connect runs the browser authorization-code flow again. A server without an interactive (oauth) auth type, or an unknown id, is a no-op — canLogin / the server status CanLogin flag tells a surface when to offer it.

func (*App) ModelLabel

func (a *App) ModelLabel() string

ModelLabel is the human-facing name of the active model for a status line: the active connection name when a ConnectionRegistry is configured, else the single-model identifier.

func (*App) PageMore

func (a *App) PageMore(ctx context.Context) (SessionPage, error)

PageMore returns the next page after the last SessionsPage call (the /sessions "more" flow), or an empty page when there is nothing more.

func (*App) Providers

func (a *App) Providers() (names []string, active string)

Providers returns the configured connection names and the active one, or (nil, "") when no connection registry is configured. Structured so a surface (REPL, TUI, web) renders it however it likes.

func (*App) REPL

func (a *App) REPL(ctx context.Context, in io.Reader, turnCtx func() (context.Context, context.CancelFunc)) error

REPL runs the interactive loop until EOF or /quit. turnCtx wraps each turn so the caller's signal handling can cancel the in-flight turn without killing the loop.

func (*App) ReconnectServer

func (a *App) ReconnectServer(id string)

ReconnectServer forces the named MCP server to attempt connecting again: it wakes a failed server that is sleeping between backoff retries and un-parks a needs-login server (the caller has since logged in). A ready or unknown server is a no-op. It is the data-only capability behind the /servers reconnect command and the interactive /mcp overlay's reconnect action; the surface renders the resulting state transitions from the group observer.

func (*App) RespondToAsk

func (a *App) RespondToAsk(askOffset int, res core.ElicitationResult, by string) error

RespondToAsk resolves a pending elicitation, identified by the event-log offset the ask was announced at (a surface reads that offset from its Watch frame). Resolution rides the log's barrier, so the first responder wins and a stale or already-answered offset returns the log's ErrAlreadyResolved / ErrOffsetOutOfRange. This is the data-only capability a web surface's respond RPC calls (issue 1196); the local terminal UI resolves the same ask through barrierElicit below.

func (*App) Resume

func (a *App) Resume(ctx context.Context, runID string) error

Resume switches the session to an existing run: its persisted messages replace the in-memory history and subsequent turns append to it. An unknown runID is an error (nothing changes), so a typo cannot silently start an empty session — use AttachRun for create-or-resume.

func (*App) RunID

func (a *App) RunID() string

RunID returns the active persisted run, or "" when persistence is off or no run has been attached or created yet (the first turn creates one lazily).

func (*App) RunTurn

func (a *App) RunTurn(ctx context.Context, input string) error

RunTurn executes one user input, rendering events as they stream. History threads across turns; a cancelled or failed turn leaves history at its pre-turn state (and persists nothing) so the next attempt is clean.

func (*App) SearchSessions

func (a *App) SearchSessions(ctx context.Context, query string) ([]agent.RunInfo, error)

SearchSessions returns runs whose ID contains query (case-insensitive), newest-first, walking pages up to maxSessionSearchScan runs. The scan is bounded, so a match past the cap is not found — a deliberate limit until a real search index exists.

func (*App) ServerTools

func (a *App) ServerTools(ctx context.Context, id string) (defs []core.ToolDef, found bool, err error)

ServerTools returns the tools exposed by a single connected MCP server, in that server's own (unqualified) naming — the data behind the /mcp overlay's per-server tool view. found is false for an unknown or not-yet-ready server id (app state, not an error). Each server's source is registered in the aggregate under its own id, so looking it up by that id returns only that server's tools (respecting its Allow filter) and never the meta-tools or sub-agents registered under other ids.

func (*App) Sessions

func (a *App) Sessions(ctx context.Context) ([]agent.RunInfo, error)

Sessions lists the first page of persisted runs newest-first (the /sessions picker), or an error when no RunStore is configured. It is the first-page shim over SessionsPage; a surface that pages calls SessionsPage.

func (*App) SessionsPage

func (a *App) SessionsPage(ctx context.Context, cursor string) (SessionPage, error)

SessionsPage returns one page of runs newest-first (gorm / in-memory order recency for free; redis SCAN is unordered — see the runstore docs). An empty cursor starts from the most recent; any other value continues a prior page. The response's next cursor is remembered on the App so PageMore advances without the surface handling the opaque cursor. Errors when no RunStore is configured.

func (*App) Subscribe

func (a *App) Subscribe(ctx context.Context) <-chan HostEvent

Subscribe returns a channel that replays the session's history and then follows it live, so a surface attaching mid-session (a web streamer, issue 1196) sees the whole conversation and every subsequent event. The channel closes when ctx is cancelled; the caller must drain it or cancel ctx to release the backing goroutine and its Queue subscription. A dropped consumer that wants the stream again simply calls Subscribe once more.

Local observers stay synchronous (issue 1194, emit's in-line fan-out); this is the async seam kept separate so a slow remote consumer never stalls the terminal rendering contract. A slow consumer cannot block emit: emit only Appends (non-blocking) and fans out to local observers, while this drain goroutine reads the log independently and blocks only itself.

Replay is stitched from two sources so a bounded (evicting) event log stays lossless for a persisted session:

  • Deep history from the RunStore. When a RunStore is configured and the run has persisted events, each stored agent.Event is replayed wrapped as HostEvent{Kind: HostRunnerEvent} — the turns already written to the store, which may have since evicted from the in-memory Queue. Non-runner HostEvents (server-state, skills) from those turns are ephemeral and intentionally not replayed; the RunStore only holds the runner stream.
  • The unpersisted tail from the Queue, drained from persistedOffset — the in-progress turn plus any recent events not yet written to the store. With a generous retention window this range is always still retained.

The two halves meet exactly at persistedOffset with no overlap: the RunStore covers eventLog[0, persistedOffset), the Queue drain starts at persistedOffset. After the tail, the goroutine follows the Queue's Notify for live events.

Consistency (snapshot-then-stream): the snapshot — subscribing to the Queue, reading persistedOffset, and reading the RunStore — is taken under turnMu, which the turn-end persist site also holds while it advances persistedOffset and writes AppendEvents together. So a persist cannot interleave the snapshot: the RunStore contents and persistedOffset are always read as one consistent pair, ruling out the dup (RunStore ahead of persistedOffset) and gap (persistedOffset ahead of RunStore) a two-step read would race. Subscribing to the Queue before releasing turnMu means no live Append between the tail read and going live is missed. Once the snapshot is captured the lock is released and all delivery happens off-lock, so a slow consumer never blocks a turn.

When no RunStore is configured, persistedOffset stays 0, so the replay is simply the whole retained Queue window (ReadFrom(0)) followed by live.

Ask ids: HostElicitRequest is appended without an id, so its event-log offset is stamped onto the delivered copy here (stampAskID) — the offset is the id E2's RespondToAsk resolves through the log barrier. Deep-history events are runner events, never asks, so only the Queue tail and live events are stamped.

func (*App) SwitchProvider

func (a *App) SwitchProvider(name string) error

SwitchProvider makes name the active chat provider for subsequent turns. An unknown name or a build failure leaves the current provider in place (the error says which). The swap takes effect on the next model call; a turn already streaming finishes on its original provider.

func (*App) Tools

func (a *App) Tools(ctx context.Context) error

Tools renders the current merged tool list (the /tools command).

type AppOption

type AppOption func(*appOptions)

AppOption customizes construction. The provider override exists so tests (and offline demos) can run the full app on a scripted StubProvider.

func WithBrowserOpener

func WithBrowserOpener(fn func(string) error) AppOption

WithBrowserOpener overrides how the interactive (oauth) auth type opens the authorization URL. Nil (the default) uses the platform browser. A headless or kiosk deployment injects its own launcher; a test injects a scripted redirect-follower so the authorization-code flow runs without a real browser.

func WithConfigOverlay

func WithConfigOverlay(configPath string) AppOption

WithConfigOverlay enables runtime-config persistence: mutable picks changed via slash commands (the /provider active connection and the /approve mode) are written back to the sibling local-overlay file derived from configPath (kitchen-sink.json -> kitchen-sink.local.json), so they survive a restart once the launcher loads the config with LoadConfigWithOverlay. configPath is the base config path, not the overlay path. Without this option the picks are session-only. A persist failure degrades to a warning, never a failed command (mirrors the RunStore persistence contract).

func WithElicitationUI

func WithElicitationUI(ui agent.ElicitationUI) AppOption

WithElicitationUI overrides the terminal elicitation UI (tests script it).

func WithLogger

func WithLogger(l *slog.Logger) AppOption

WithLogger sets the operational slog logger (failover transitions, future policy events). The transcript renderer is UI, not logging, and never routes here. Nil discards.

func WithMemoryStore

func WithMemoryStore(store agent.MemoryStore) AppOption

WithMemoryStore supplies the backing store for working memory (Config.Memory). Omitted, memory uses an in-memory store that dies with the process; pass a durable one (agent/store/redis, agent/store/gorm) to survive restarts. Per-session isolation is orthogonal — set MemoryConfig.SessionScoped to namespace the store by run id. Ignored when Config.Memory is nil.

func WithMeterProvider

func WithMeterProvider(mp core.MeterProvider) AppOption

WithMeterProvider opts the agent Runner (and its sub-agents) into OTel metric emission (issue 1023): the per-turn and per-tool-call instruments that back the mcpkit-agent Grafana dashboard. Pair it with WithTracerProvider off the same OTLP endpoint so traces and metrics land in one collector. Nil means noop.

func WithObserver

func WithObserver(o Observer) AppOption

WithObserver registers an Observer for the host's event stream. Any WithObserver suppresses the default terminal renderer, so a TUI or web surface takes over rendering; add NewTerminalRenderer(out) explicitly alongside if you also want the terminal output (e.g. a renderer plus a tracer). Without any WithObserver, the App renders to the io.Writer passed to NewApp.

func WithProvider

func WithProvider(p agent.Provider) AppOption

WithProvider overrides the OpenAI-compatible provider built from config.

func WithProviderBuilder

func WithProviderBuilder(b ProviderBuilder) AppOption

WithProviderBuilder overrides how Config.Connections entries are turned into providers. Tests inject a builder returning StubProviders; production uses DefaultProviderBuilder (OpenAI-compatible). Ignored when Connections is nil or WithProvider is set.

func WithRunStore

func WithRunStore(store agent.RunStore) AppOption

WithRunStore enables session persistence: every completed turn's messages (and its event stream) are appended to a run in store, so a surface can resume or fork the session later — across process restarts when the store is durable. Nil (the default) keeps the pre-persistence behavior: history lives only in memory.

func WithSystemPromptBuilder

func WithSystemPromptBuilder(mutate func(*SystemPromptBuilder)) AppOption

WithSystemPromptBuilder customizes per-turn system-prompt assembly. The mutator receives the default builder (base instructions, then per-server skill blocks) after it is assembled in NewApp, so a caller can reorder sections, insert profile/domain-guide sections, or replace Sections wholesale. It runs once at construction; the resulting builder's Build runs each turn.

func WithToolResultStore

func WithToolResultStore(store agent.ToolResultStore) AppOption

WithToolResultStore supplies the backing store for tool-result offloading (Config.Offload). Omitted, offloading uses an in-memory store; pass a durable one (agent/store/redis, agent/store/gorm) so offloaded blobs survive restarts. Ignored when Config.Offload is nil.

func WithTracerProvider

func WithTracerProvider(tp core.TracerProvider) AppOption

WithTracerProvider opts every layer into SEP 414 spans: agent turn/step/ tool spans, client dispatch spans (stitched as children), and skills activation spans. Nil means noop.

type ApprovalConfig

type ApprovalConfig struct {
	// Mode is the default disposition for calls no rule covers: "ask"
	// (default), "read-only-auto" (auto-allow tools that declare the
	// readOnlyHint annotation, ask for the rest), or "allow" (run
	// everything, "yolo"). An unknown value falls back to "ask".
	Mode string `json:"mode,omitempty"`

	// Rules pins per-tool overrides that win over Mode: tool name ->
	// "allow" | "ask" | "deny". Unknown rule values are ignored.
	Rules map[string]string `json:"rules,omitempty"`

	// Remember caches a tool the user approved so later calls to it skip the
	// prompt for the life of the session.
	Remember bool `json:"remember,omitempty"`
}

ApprovalConfig is the host's view of the agent approval ladder. It maps to an agent.TieredApproval whose "ask" outcome is presented through the same terminal UI as elicitation (via ElicitationCoordinator.Confirm).

type AuthConfig

type AuthConfig struct {
	// Type is "bearer" (static token), "client-credentials" (OAuth
	// machine-to-machine via PRM/AS discovery), or "oauth"
	// (authorization-code browser flow: PRM/AS discovery + PKCE, DCR when no
	// client is pre-registered; the /mcp overlay's login action re-runs it).
	Type string `json:"type"`

	// TokenEnv names the env var holding the static bearer token.
	// Required for type "bearer".
	TokenEnv string `json:"tokenEnv,omitempty"`

	// ClientIDEnv / ClientSecretEnv name the env vars holding the OAuth
	// client credentials. Required for type "client-credentials".
	ClientIDEnv     string `json:"clientIdEnv,omitempty"`
	ClientSecretEnv string `json:"clientSecretEnv,omitempty"`

	// Scopes to request for OAuth types. Empty inherits the server's PRM
	// scopes_supported.
	Scopes []string `json:"scopes,omitempty"`

	// AllowInsecure permits an http:// authorization server (dev/test
	// only; production AS endpoints must be https).
	AllowInsecure bool `json:"allowInsecure,omitempty"`
}

AuthConfig selects one of the client auth modes MCP supports. Secrets are env-indirected like everything else in this config.

func (*AuthConfig) Validate

func (a *AuthConfig) Validate() error

Validate checks mode-specific requirements and that named env vars are actually set, so misconfiguration fails at startup rather than as a mid-conversation 401.

type BackupModelConfig

type BackupModelConfig struct {
	BaseURL   string `json:"baseUrl"`
	Model     string `json:"model"`
	APIKeyEnv string `json:"apiKeyEnv,omitempty"`
}

BackupModelConfig is the failover endpoint (same shape as the primary, minus further nesting).

type CmdKind

type CmdKind string

CmdKind tags a CmdResult so a surface renders it without re-parsing. One kind per distinct command output shape.

const (
	// CmdMessage is a plain informational or confirmation line (Message).
	CmdMessage CmdKind = "message"
	// CmdProviders lists model connections (Providers + ActiveProvider).
	CmdProviders CmdKind = "providers"
	// CmdSession reports the active run id (RunID; empty = persistence off).
	CmdSession CmdKind = "session"
	// CmdSessions lists persisted sessions (Sessions + RunID = active).
	CmdSessions CmdKind = "sessions"
	// CmdTools lists the merged tool set (Tools).
	CmdTools CmdKind = "tools"
	// CmdHistory dumps the conversation so far (Messages).
	CmdHistory CmdKind = "history"
	// CmdHealth reports provider failover state (Failover; nil = no backup).
	CmdHealth CmdKind = "health"
	// CmdTasks lists background tasks (Tasks).
	CmdTasks CmdKind = "tasks"
	// CmdApproval reports the approval policy (Approval; nil = gate off).
	CmdApproval CmdKind = "approval"
	// CmdServers lists the MCP servers and their connection state (Servers).
	CmdServers CmdKind = "servers"
	// CmdServerTools lists one server's own tools (Tools + ServerID = which).
	CmdServerTools CmdKind = "server-tools"
	// CmdQuit signals the loop to exit (Quit true).
	CmdQuit CmdKind = "quit"
)

type CmdResult

type CmdResult struct {
	Kind    CmdKind
	Message string

	Providers      []string
	ActiveProvider string
	RunID          string
	Tools          []core.ToolDef
	Messages       []agent.Message
	Failover       *agent.FailoverProvider
	Tasks          []*client.BackgroundTask
	Approval       *agent.TieredApproval
	Sessions       []agent.RunInfo
	SessionsNote   string
	Servers        []ServerStatus
	ServerID       string // the server a CmdServerTools result scopes to
	Quit           bool
}

CmdResult is the structured outcome of a command, rendered by the surface (terminal today, a web client later) rather than printed by the command. Only the fields for the result's Kind are set. Keeping command output as data — not io.Writer prints — is what lets every surface reuse one command set (the web-version unlock; see the render-seam follow-up issue 992, which folds these into the unified HostEvent stream).

type Command

type Command struct {
	Name     string
	Aliases  []string
	Help     string
	Run      func(ctx context.Context, args string) (CmdResult, error)
	Complete func(prefix string) []string
}

Command is one slash command. Run receives the raw argument string (everything after the command word, trimmed) and returns a structured result. Complete, when set, offers argument completions for a prefix — the seam the TUI tab-palette (issue 987) drives; nil means no argument completion.

type CommandRegistry

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

CommandRegistry holds the slash commands a surface dispatches. It is the single source of the command set: the REPL, the future TUI palette, and a web dispatcher all read from one registry, so a new command registered once appears on every surface.

func NewCommandRegistry

func NewCommandRegistry() *CommandRegistry

NewCommandRegistry returns an empty registry.

func (*CommandRegistry) Lookup

func (r *CommandRegistry) Lookup(name string) (*Command, bool)

Lookup resolves a command by name or alias (the leading "/" stripped).

func (*CommandRegistry) Match

func (r *CommandRegistry) Match(prefix string) []string

Match returns the canonical names beginning with prefix (the "/" is optional), sorted — the command-name completion the TUI palette uses.

func (*CommandRegistry) Names

func (r *CommandRegistry) Names() []string

Names returns the canonical command names in registration order.

func (*CommandRegistry) Register

func (r *CommandRegistry) Register(c *Command)

Register adds c under its name and aliases. A duplicate name/alias overwrites — last registration wins — so a surface can shadow a default.

type CompactionConfig

type CompactionConfig struct {
	// MaxTokens is the budget (estimated) above which compaction fires.
	// Required (must be > 0); NewApp fails if it is not set.
	MaxTokens int `json:"maxTokens"`

	// KeepRecent is how many trailing messages stay verbatim. Zero uses the
	// agent default (6).
	KeepRecent int `json:"keepRecent,omitempty"`
}

CompactionConfig is the host's view of history compaction; it maps to an agent.SummarizingCompactor over the chat provider. Its presence enables compaction.

type Config

type Config struct {
	// Model configures the OpenAI-compatible endpoint.
	Model ModelConfig `json:"model"`

	// Instructions is the system prompt. Optional.
	Instructions string `json:"instructions,omitempty"`

	// MaxSteps caps model calls per turn. Zero uses the agent default.
	MaxSteps int `json:"maxSteps,omitempty"`

	// MaxTreeSteps and MaxTreeTokens cap the AGGREGATE model steps / tokens
	// across a turn's whole sub-agent tree (parent + sub-agents + fan-out
	// members + handoff rounds), not just per-Runner MaxSteps. Zero means
	// unbounded. The safety rail for deep or chatty multi-agent trees.
	MaxTreeSteps  int `json:"maxTreeSteps,omitempty"`
	MaxTreeTokens int `json:"maxTreeTokens,omitempty"`

	// MaxEventLogRetention bounds the in-memory session event log (the
	// gocurrent.Queue emit appends to and Subscribe replays). Zero (the
	// default) keeps the log unbounded, preserving the pre-bound behavior for
	// embedders that never need eviction. A positive value caps the retained
	// window to that many entries, evicting the oldest as the session runs so
	// a long-lived process bounds its memory. Eviction is lossless for a
	// persisted session: Subscribe deep-replays turns already written to the
	// RunStore, so a subscriber attaching after eviction still sees full
	// history. Set it generously enough that a single turn never exceeds the
	// window (agentchat defaults to 100000 via --max-event-log).
	MaxEventLogRetention int `json:"maxEventLogRetention,omitempty"`

	// Interruptible opts the main agent's turn into breaking the fan-out join
	// barrier when a sub-agent raises a Signal mid-flight (issue 1167): the first
	// signal cancels the remaining in-flight calls and the model re-plans with
	// the partial results, instead of waiting for every sub-agent. Only useful
	// with signalling sub-agents (SubAgents + CanSignal). False (the default)
	// keeps the pure fan-out-then-join. Pairs with SignalPolicy: leave it unset
	// (inject) so the turn re-plans rather than aborts.
	Interruptible bool `json:"interruptible,omitempty"`

	// RunnerControl, when true, gives the main agent the runner-control
	// meta-tools (issue 1166): spawn_agent / await_agent / cancel_agent /
	// list_agents, over the configured sub-agent personas. The model can run a
	// persona in the background, get a handle, and await or cancel it — the
	// model-driven, handle-based counterpart to calling a persona as a blocking
	// tool. Only meaningful alongside SubAgents. False (the default) omits them.
	RunnerControl bool `json:"runnerControl,omitempty"`

	// SignalPolicy selects how the main agent reacts to an upward Signal a
	// signalling sub-agent raises (issue 1165), read at the dispatch join:
	//   - "" / "inject" — inject the signal as context and continue (default).
	//   - "abort_on_escalate" — end the turn when a child raises "escalate".
	// Either way the signal is injected so the main model sees it. Only meaningful
	// alongside a sub-agent with CanSignal.
	SignalPolicy string `json:"signalPolicy,omitempty"`

	// AllowPreempt lets a sub-agent's advisory "preempt" signal actually break
	// the interruptible barrier (cancel the other in-flight sub-agents) instead
	// of only being injected for the model to weigh (issue 1176). False (the
	// default) is safe: a preempt cannot cancel siblings, so a rogue or
	// prompt-injected sub-agent cannot unilaterally kill the parallel work — the
	// main model decides on re-plan. Only meaningful with Interruptible +
	// signalling sub-agents; "escalate" is unaffected (it always breaks).
	AllowPreempt bool `json:"allowPreempt,omitempty"`

	// Servers lists the MCP servers to connect.
	Servers []ServerConfig `json:"servers"`

	// Triggers lists proactive-turn bindings over the configured event
	// streams.
	Triggers []TriggerConfig `json:"triggers,omitempty"`

	// MetaTools exposes the async control-plane tools to the model
	// (subscribe_events, create_trigger, list_tasks, cancel_task, ...).
	// Auto-implied when any server has events or triggers configured.
	MetaTools bool `json:"metaTools,omitempty"`

	// TaskGraceSec is how long a task-backed tool call stays inline before
	// detaching to the background (completion arrives as injected context
	// and a transcript line; /tasks manages running tasks). Zero uses the
	// 10s default; negative disables detaching (wait inline forever).
	TaskGraceSec int `json:"taskGraceSec,omitempty"`

	// Approval configures the tool-call permission ladder. Nil means the
	// gate is off: every tool call the model makes runs (the pre-approval
	// behavior). Set it to gate calls behind a mode and per-tool rules,
	// with "ask" prompts routed through the terminal elicitation UI.
	Approval *ApprovalConfig `json:"approval,omitempty"`

	// Connections is a named registry of model connections with one
	// active. When set it supersedes Model for the chat provider and
	// enables runtime /provider switching; Model stays as the
	// single-connection quick-start path. See ConnectionsConfig.
	Connections *ConnectionsConfig `json:"connections,omitempty"`

	// Offload configures tool-result offloading. Nil means off: tool
	// results flow into the conversation verbatim. Set it to store
	// over-threshold results out of band and hand the model a compact
	// stub plus a read_tool_result tool. The backing ToolResultStore is
	// supplied by the surface via WithToolResultStore (in-memory when
	// omitted), the same split as WithRunStore.
	Offload *OffloadConfig `json:"offload,omitempty"`

	// Memory enables model-managed working memory: a remember/recall/forget
	// scratchpad the model reads and writes across turns. Nil means off.
	// The backing MemoryStore is supplied by the surface via
	// WithMemoryStore (in-memory when omitted), the same split as
	// WithRunStore and WithToolResultStore.
	Memory *MemoryConfig `json:"memory,omitempty"`

	// Compaction enables history compaction: when the conversation exceeds
	// MaxTokens, the head is summarized (by the chat provider) and a recent
	// tail is kept verbatim, before each turn. Nil means off — history is
	// sent verbatim. Lossy; complementary to Offload (lossless).
	Compaction *CompactionConfig `json:"compaction,omitempty"`

	// SubAgents declares specialist personas the main agent can delegate to
	// as tools (AgentSource). Each runs over the SAME provider and a filtered
	// view of the SAME server tools, with its own instructions — a persona,
	// not a separately-configured agent. Empty means no sub-agents.
	SubAgents []SubAgentConfig `json:"subAgents,omitempty"`

	// FanOut declares parallel-ensemble tools: each group is a single tool the
	// main agent calls once to broadcast a task to all its member personas
	// concurrently, receiving one aggregated result (agent.FanOutSource).
	// Empty means no fan-out tools.
	FanOut []FanOutGroupConfig `json:"fanOut,omitempty"`

	// Team, when set, drives the conversation as a handoff Team (agent.Team)
	// instead of the single main agent — control transfers between members and
	// persists across user turns. Mutually exclusive with SubAgents, FanOut, and
	// Memory (NewApp errors if combined). Nil means single-agent mode.
	Team *HostTeamConfig `json:"team,omitempty"`
}

Config is agentchat's JSON configuration. Secrets are never inlined: apiKeyEnv / authTokenEnv name environment variables to read at startup, following the same indirection convention the rest of the repo's example configs use.

func LoadConfig

func LoadConfig(path string) (*Config, error)

LoadConfig reads and validates a config file.

func LoadConfigWithOverlay

func LoadConfigWithOverlay(path string) (*Config, error)

LoadConfigWithOverlay loads the base config, then merges the sibling local-overlay file (overlayPathFor) over it when that file exists, then validates. This is the read side of runtime-config persistence: the overlay carries only the mutable picks a slash command changed (active connection, approval mode), written by WithConfigOverlay.

The merge is deliberately a second json.Unmarshal into the same struct, so the semantics are the standard library's, pinned by tests: a scalar present in the overlay overrides the base, a map merges by key (base entries the overlay omits survive), a slice present in the overlay REPLACES the base slice wholesale, and a key the overlay omits is left untouched. That last rule is what lets a one-line overlay (just active) leave servers and connections intact.

func (*Config) APIKey

func (c *Config) APIKey() string

APIKey resolves the model bearer key from the environment. Empty when unset or unconfigured.

func (*Config) Validate

func (c *Config) Validate() error

Validate enforces the invariants the app relies on.

type ConnectionConfig

type ConnectionConfig struct {
	// Type names a built-in endpoint profile ("lmstudio", "openai",
	// "ollama", "gemini", "anthropic", "openrouter", "litellm"). All but
	// "anthropic" speak the OpenAI wire; "anthropic" uses the native
	// Messages-API provider (x-api-key auth, /v1/messages). "openrouter" and
	// "litellm" are model-router gateways (set BaseURL to override the
	// litellm proxy's local default). Optional when BaseURL is set.
	Type string `json:"type,omitempty"`

	// BaseURL is the API root including any version prefix, e.g.
	// "http://localhost:1234/v1". Overrides Type's default.
	BaseURL string `json:"baseUrl,omitempty"`

	// Model is the model identifier sent on every request. Required.
	Model string `json:"model"`

	// APIKeyEnv names the environment variable holding the bearer key.
	// Empty means unauthenticated (local endpoints).
	APIKeyEnv string `json:"apiKeyEnv,omitempty"`

	// Dim is the embedding vector width, meaningful only when this
	// connection is used as an embedder (the ConnectionsConfig.Embedder
	// role). It must match the embedding model's true output width; the
	// durable pgvector store sizes its vector column from it. Ignored for
	// chat connections.
	Dim int `json:"dim,omitempty"`

	// ThinkingHint describes how this model delimits inline reasoning, for
	// models that emit it in the text stream (e.g. <think>…</think>). When
	// set, DefaultProviderBuilder wraps the provider so the delimited text is
	// re-tagged as reasoning (agent.NewThinkingProvider). A nil hint or empty
	// CloseTag leaves the provider unwrapped.
	ThinkingHint *ThinkingHint `json:"thinkingHint,omitempty"`
}

ConnectionConfig is one model endpoint. Type resolves to a base URL via the built-in table (lmstudio / openai / ollama); BaseURL overrides it for anything else. Exactly one of a known Type or a BaseURL must resolve, or construction fails.

type ConnectionRegistry

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

ConnectionRegistry holds the named connections, the active one, and a cache of built providers. Safe for concurrent use: SetActive and provider() are the runtime-switch surface. Providers are built lazily and cached, so switching back to a used connection is instant.

func NewConnectionRegistry

func NewConnectionRegistry(cfg *ConnectionsConfig, build ProviderBuilder) (*ConnectionRegistry, error)

NewConnectionRegistry validates cfg (Active must name a connection, every connection must resolve a base URL) and returns the registry. A nil build uses DefaultProviderBuilder. Providers are not built here — the first Provider/SetActive call builds the active one, so a misconfigured non-active connection does not fail startup.

func (*ConnectionRegistry) Active

func (r *ConnectionRegistry) Active() string

Active returns the name of the active connection.

func (*ConnectionRegistry) ActiveProvider

func (r *ConnectionRegistry) ActiveProvider() (agent.Provider, error)

ActiveProvider builds (or returns the cached) provider for the active connection.

func (*ConnectionRegistry) Names

func (r *ConnectionRegistry) Names() []string

Names lists the connection names in stable sorted order.

func (*ConnectionRegistry) SetActive

func (r *ConnectionRegistry) SetActive(name string) (agent.Provider, error)

SetActive switches the active connection and returns its provider. An unknown name is an error and leaves the active connection unchanged; a build failure likewise leaves the previous active in place, so a failed switch never strands the session without a provider.

type ConnectionsConfig

type ConnectionsConfig struct {
	// Active names the connection used for the chat provider at startup.
	// Must be a key in Connections.
	Active string `json:"active"`

	// Embedder names the connection used for the embedder role (semantic
	// memory), the counterpart of Active for embeddings. Optional; empty
	// means no config-provided embedder (a surface may still supply one by
	// flag). Must be a key in Connections, and that connection must speak an
	// embeddings API — Anthropic has none, so an "anthropic"-typed connection
	// is rejected. Set Dim on the named connection to the embedding width.
	Embedder string `json:"embedder,omitempty"`

	// Connections maps a caller-chosen name to its endpoint + model.
	Connections map[string]ConnectionConfig `json:"connections"`
}

ConnectionsConfig is a named registry of model connections with one active, the shape a playground config carries so the user can switch models at runtime (/provider). It supersedes Config.Model for the chat provider when set; Model stays as the single-connection quick-start.

The same registry is the seam later roles draw from: /embedder and /judgelm (epic 983) pick an active connection for their role from this one set — connections are model endpoints, roles are assignments over them.

func (*ConnectionsConfig) EmbedderConnection

func (c *ConnectionsConfig) EmbedderConnection() (ConnectionConfig, bool)

EmbedderConnection returns the connection named by Embedder and true, or a zero connection and false when no embedder role is set (or it names an undefined connection). It is the read side of the Embedder role, mirroring how the active connection is resolved for chat.

type EventConfig

type EventConfig struct {
	Name string `json:"name"`

	// Hint overrides how occurrences reach the model (priority,
	// aggregation window, template, retention, sensitivity).
	Hint *agent.ContextHint `json:"hint,omitempty"`
}

EventConfig subscribes one event name and optionally overrides its context hint (host config wins over the server-advertised _meta hint).

type FanOutGroupConfig

type FanOutGroupConfig struct {
	// Name is the tool the main agent calls to fan out. Required.
	Name string `json:"name"`

	// Description tells the main agent when to fan out to this group.
	Description string `json:"description,omitempty"`

	// Members are the personas the task is broadcast to. At least one required.
	Members []SubAgentConfig `json:"members,omitempty"`
}

FanOutGroupConfig declares one parallel-ensemble tool: the main agent calls Name once and the task is broadcast to every Member persona concurrently, the results aggregated in member order (agent.FanOutSource). Members are built exactly like SubAgents (shared provider, serverTools-only, own instructions) but are not also exposed as individual delegate tools — the group is one tool.

type HostEvent

type HostEvent struct {
	Kind HostEventKind

	RunnerEvent agent.Event
	Command     CmdResult
	Result      *agent.TurnResult
	Err         string
	RunID       string
	Label       string
	Message     string

	ServerID    string
	ServerState string // ConnState on HostServerStateChanged
	URI         string
	EventName   string
	Loaded      int
	Skipped     int

	TaskStatus *core.DetailedTask
	Task       *client.BackgroundTask

	// SubAgent is the nested sub-agent event on HostSubAgentEvent.
	SubAgent agent.SubAgentEvent

	// From and To name the agents on HostHandoff (the transfer source and the
	// new active agent).
	From string
	To   string

	// AskID identifies a pending ask on HostElicitRequest / HostElicitResolved;
	// a surface passes it back to RespondToAsk. Elicit carries the request on
	// HostElicitRequest; By names the resolving surface on HostElicitResolved.
	AskID  int64
	Elicit *core.ElicitationRequest
	By     string
}

HostEvent is one domain event the host announces: a thing that happened, fire-and-forget, fanned out to every Observer. It is a tagged union — only the fields named for the Kind (in each constant's doc) are set. The host never formats for a specific consumer; a renderer turns events into ANSI lines, a tracer into spans, a web surface into socket frames.

This is distinct from the two other host interaction shapes: input arrives INTO the host from a surface (a surface calls Dispatch/RunTurn when the user acts), and mid-turn input REQUESTS use the elicitation seam (an AskFunc / ElicitationUI, 1→1 and blocking). Events are the 1→N fire-and-forget half; neither of the others rides this stream.

Serializability note: most payloads are wire types (agent.Event, CmdResult, TurnResult, strings). The task/health events still carry live pointers (TaskStatus, Task, and the Failover inside a HostCommandResult) — a web surface needs serializable snapshots of those; that conversion is issue 994. The terminal renderer reads the pointers directly.

type HostEventKind

type HostEventKind string

HostEventKind tags a HostEvent. Each is a domain event — a thing that happened in the host lifecycle — not a render instruction; the same stream drives a renderer, a tracer, a metrics sink, or a web push.

const (
	// HostRunnerEvent carries one streaming turn event (RunnerEvent) — the
	// agent.Event flow (text/thinking/tool deltas) folded into this stream.
	HostRunnerEvent HostEventKind = "runner-event"
	// HostCommandResult carries a slash-command result (Command).
	HostCommandResult HostEventKind = "command-result"
	// HostTurnDone reports a finished turn (Result).
	HostTurnDone HostEventKind = "turn-done"
	// HostTurnFailed reports a failed turn or a command error (Err).
	HostTurnFailed HostEventKind = "turn-failed"
	// HostSessionChanged reports the active session id changing (RunID;
	// empty = none).
	HostSessionChanged HostEventKind = "session-changed"
	// HostSessionWarn reports degraded persistence (Err) — the turn still
	// succeeded.
	HostSessionWarn HostEventKind = "session-warn"
	// HostTriggerFired reports a proactive-turn trigger (Label).
	HostTriggerFired HostEventKind = "trigger-fired"
	// HostSkillsLoaded reports a server's skills load (ServerID, Loaded,
	// Skipped).
	HostSkillsLoaded HostEventKind = "skills-loaded"
	// HostSkillSkipped reports one skipped skill (ServerID, URI, Err).
	HostSkillSkipped HostEventKind = "skill-skipped"
	// HostEventDropped reports a dropped subscription event (ServerID,
	// EventName).
	HostEventDropped HostEventKind = "event-dropped"
	// HostTaskStatus reports a background task status change (TaskStatus).
	HostTaskStatus HostEventKind = "task-status"
	// HostTaskDetached reports a task detaching to the background (Task).
	HostTaskDetached HostEventKind = "task-detached"
	// HostTaskCompleted reports a background task finishing (Task).
	HostTaskCompleted HostEventKind = "task-completed"
	// HostMessage is a plain informational line (Message).
	HostMessage HostEventKind = "message"
	// HostSubAgentEvent carries a sub-agent's nested turn-lifecycle event
	// (SubAgent) — a persona's activity, scoped/depth on the envelope, for a
	// surface to render indented under the parent's turn.
	HostSubAgentEvent HostEventKind = "sub-agent-event"
	// HostServerStateChanged reports an MCP server's connection state changing
	// (ServerID, ServerState; Err on failed/needs-login) — the async
	// graceful-degrade surface (see docs/AGENT_SERVER_STATE.md).
	HostServerStateChanged HostEventKind = "server-state-changed"
	// HostHandoff reports a Team transferring control from one agent to another
	// (From, To) — Config.Team only. The active agent changes, so a surface
	// renders "→ handed off to <To>" and can update which agent is answering.
	HostHandoff HostEventKind = "handoff"
	// HostElicitRequest announces a pending elicitation/approval ask to every
	// surface (AskID, Elicit). Unlike the fire-and-forget kinds this one is
	// answerable: any surface reads it and calls RespondToAsk(AskID, ...); the
	// first responder wins. The local terminal UI is one such responder.
	HostElicitRequest HostEventKind = "elicit-request"
	// HostElicitResolved reports that a pending ask (AskID) was answered, by
	// which surface (By), so every other surface retracts its prompt.
	HostElicitResolved HostEventKind = "elicit-resolved"
)

type HostTeamConfig

type HostTeamConfig struct {
	// Members are the agents. At least one; Start must name one.
	Members []TeamMemberConfig `json:"members,omitempty"`

	// Start is the agent that receives a conversation's first turn. Required.
	Start string `json:"start"`

	// MaxHandoffs caps transfers within one user turn. Zero uses the agent
	// default.
	MaxHandoffs int `json:"maxHandoffs,omitempty"`
}

HostTeamConfig declares a handoff Team that drives the whole conversation instead of the single main agent (agent.Team). Control transfers between members and stays where it was transferred across user turns. Setting Team replaces the single-agent loop, so it may NOT be combined with SubAgents, FanOut, or Memory on the main agent (NewApp errors); team members are serverTools-only personas.

type MemoryConfig

type MemoryConfig struct {
	// InjectSummary, when true, prepends a summary of the current
	// scratchpad as a RoleSystem message before each turn, so the model
	// stays aware of what it saved without a recall call. It costs tokens
	// proportional to the injected slice, so it is opt-in; when false the
	// model still reaches memory through the recall tool on demand.
	InjectSummary bool `json:"injectSummary,omitempty"`

	// SummaryMaxItems bounds how many notes the injected summary carries,
	// keeping the newest. Zero means no item cap (the whole scratchpad).
	// Only meaningful with InjectSummary.
	SummaryMaxItems int `json:"summaryMaxItems,omitempty"`

	// SummaryMaxChars bounds the injected summary's rendered length (a cheap
	// token proxy), dropping the oldest kept notes until it fits. Zero means
	// no length cap. Only meaningful with InjectSummary.
	SummaryMaxChars int `json:"summaryMaxChars,omitempty"`

	// InjectRecall, when true, injects the notes RELEVANT to the current
	// user message as a RoleSystem message before each turn, so the model
	// "just knows" what matters without a recall call — the auto-push (RAG)
	// half of semantic recall. Complementary to InjectSummary (ambient,
	// recency-budgeted): a deployment usually picks one. Backend-agnostic,
	// but only useful with a relevance-ranking store (a semantic store);
	// over the substring default it injects notes literally containing the
	// query words.
	InjectRecall bool `json:"injectRecall,omitempty"`

	// RecallTopK caps how many relevant notes InjectRecall injects. Zero
	// uses the agent default (5).
	RecallTopK int `json:"recallTopK,omitempty"`

	// RecallMinScore drops recalled notes scoring below it (the poison guard
	// — a semantic store scores every note, so a floor keeps low-TopK recall
	// from injecting the least-irrelevant notes when nothing truly matches).
	// Zero means no floor.
	RecallMinScore float64 `json:"recallMinScore,omitempty"`

	// SessionScoped, when true, namespaces working memory by the active run
	// id, so each session (RunStore run) gets its own scratchpad and recall
	// never crosses sessions — a /sessions resume or fork carries its own
	// memory on a durable backend. Opt-in: the default is one shared
	// scratchpad across all sessions, which is often the point of persistent
	// memory. A no-op without a RunStore (the run id is always "", so every
	// turn shares the default namespace).
	SessionScoped bool `json:"sessionScoped,omitempty"`
}

MemoryConfig is the host's view of working memory. Its presence enables the MemorySource; the fields tune how memory reaches the turn.

type ModelConfig

type ModelConfig struct {
	BaseURL string `json:"baseUrl"`
	Model   string `json:"model"`
	// APIKeyEnv names the environment variable holding the bearer key.
	// Empty means unauthenticated (local servers).
	APIKeyEnv string `json:"apiKeyEnv,omitempty"`

	// Backup, when set, wraps the model in a FailoverProvider: a call
	// that fails cleanly on the primary retries here once, and the
	// primary is benched for a cooldown. See /health in the REPL.
	Backup *BackupModelConfig `json:"backup,omitempty"`
}

ModelConfig points at an OpenAI-compatible chat-completions endpoint.

type Observer

type Observer interface {
	On(HostEvent)
}

Observer receives the host's HostEvent stream and does whatever it wants with it — render to a terminal, emit spans, push to a socket, record for a test. Every event is also recorded on the retained event log (which a web surface replays and subscribes onto); an Observer is the synchronous local delivery of that same stream. The host fans every event out to all registered observers (WithObserver), so a renderer and a tracer coexist. On is called from the turn goroutine and from event goroutines; an Observer that is not inherently serialized must guard its own state.

This is the fire-and-forget half of the host's I/O. It is deliberately NOT the input path: getting user input back is either surface-driven (a surface calls Dispatch/RunTurn) or, mid-turn, the 1→1 blocking elicitation seam — neither of which is an Observer.

func NewTerminalRenderer

func NewTerminalRenderer(w io.Writer) Observer

NewTerminalRenderer returns the built-in terminal Observer — the ANSI line renderer, writing to w. A TUI reuses it by pointing w at a buffer and reading the formatted transcript back, rather than reimplementing every event's formatting. Color follows the environment (NO_COLOR / TERM); use NewTerminalRendererColor to force the decision.

func NewTerminalRendererColor

func NewTerminalRendererColor(w io.Writer, colorEnabled bool) Observer

NewTerminalRendererColor is NewTerminalRenderer with an explicit color decision, for a surface that has already resolved --no-color (or its own precedence chain) and wants the ANSI dim styling suppressed accordingly.

type OffloadConfig

type OffloadConfig struct {
	// ThresholdBytes is the model-visible size at or above which a
	// successful result is offloaded. Zero uses the agent default
	// (4 KB).
	ThresholdBytes int `json:"thresholdBytes,omitempty"`

	// PreviewLen is how many leading characters the stub carries inline.
	// Zero uses the agent default.
	PreviewLen int `json:"previewLen,omitempty"`

	// PerTool overrides ThresholdBytes for named tools; a value <= 0
	// pins that tool to never offload (always inline).
	PerTool map[string]int `json:"perTool,omitempty"`
}

OffloadConfig is the host's view of tool-result offloading; it maps to an agent.OffloadConfig. Its presence enables offloading.

type PersistingEmit

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

PersistingEmit tees a Runner event stream into a RunStore event log. Use its Emit as the emit argument to Runner.Run (wrapping the surface's own handler), then Flush once the turn completes. Events buffer in memory and land in one AppendEvents call per turn — the per-turn durability grain — rather than one store round-trip per text delta. Not safe for concurrent use, which matches the Runner's guarantee that emit is never called concurrently.

func NewPersistingEmit

func NewPersistingEmit(store agent.RunStore, runID string, next func(agent.Event)) *PersistingEmit

NewPersistingEmit wraps next (nil is allowed) for the given run.

func (*PersistingEmit) Emit

func (p *PersistingEmit) Emit(e agent.Event)

Emit forwards the event to the wrapped handler verbatim and buffers a persistence copy. The two differ only for turn-end: the buffered copy drops TurnResult.Messages (see redactForPersist), so live consumers (renderers) still see the whole event while the event log does not duplicate what the message log already holds.

func (*PersistingEmit) Flush

func (p *PersistingEmit) Flush(ctx context.Context) error

Flush appends the buffered events to the run and clears the buffer. A run the store does not know is reported as an error here (unlike the raw AppendEvents Found=false) because by construction the caller created the run before the turn began.

type PromptSection

type PromptSection interface {
	Section(ctx context.Context) string
}

PromptSection contributes one section of the per-turn system prompt. Returning "" omits the section (no stray blank lines). Sections run every turn, so a section may read live/dynamic state (late-connecting servers' skills, memory).

type PromptSectionFunc

type PromptSectionFunc func(ctx context.Context) string

PromptSectionFunc adapts a plain function to PromptSection (like http.HandlerFunc adapts a function to http.Handler).

func (PromptSectionFunc) Section

func (f PromptSectionFunc) Section(ctx context.Context) string

Section implements PromptSection.

type ProviderBuilder

type ProviderBuilder func(ConnectionConfig) (agent.Provider, error)

ProviderBuilder builds a Provider from a resolved connection. Injected for tests (a builder that returns StubProviders); DefaultProviderBuilder is the real OpenAI-compatible path.

type ServerConfig

type ServerConfig struct {
	// ID is the source identifier (used for collision-qualified tool
	// names). Must not contain underscores.
	ID string `json:"id"`

	// URL is the MCP endpoint (streamable HTTP).
	URL string `json:"url"`

	// Auth configures how to authenticate to this server. Nil means
	// unauthenticated.
	Auth *AuthConfig `json:"auth,omitempty"`

	// Allow, when non-empty, restricts this server to the named tools
	// (a FilterSource capability boundary, not a display preference).
	Allow []string `json:"allow,omitempty"`

	// Required makes boot block until this server is connected: NewApp waits
	// for it (up to the required-timeout) instead of returning while it is
	// still connecting. Use it for a server the agent is useless without.
	// Non-required servers (the default) connect in the background and never
	// block boot — the agent is usable immediately and their tools wire in as
	// they become ready. See docs/AGENT_SERVER_STATE.md.
	Required bool `json:"required,omitempty"`

	// Skills controls SEP-2640 skill loading for this server. Nil or true
	// auto-detects (servers without the capability are skipped silently);
	// false opts out even when the server advertises skills.
	Skills *bool `json:"skills,omitempty"`

	// SkillsMode selects how enabled skills enter context: "eager" (full
	// SKILL.md bodies in the system prompt), "catalog" (only name +
	// description; bodies fetched on demand via the load_skill tool), or ""
	// (auto — eager below a small skill count, catalog at/above). Progressive
	// disclosure keeps a large skill set from bloating every request. Ignored
	// when Skills is false.
	//
	// Mode is also the trust lever for a lower-trust skills server. Skills are
	// data, not code (ext/skills is enforced no-exec), so the risk they carry
	// is context-poisoning: a skill body is text the model reads as guidance.
	// "eager" splices that text into the system prompt at connect time, with no
	// per-skill gate. "catalog" is the safer default for a server you do not
	// fully trust: a skill enters context only when the model calls load_skill,
	// and load_skill is an ordinary tool, so it flows through the same approval
	// ladder as every other call (set Approval.Rules["load_skill"] = "ask" to
	// confirm each activation; the prompt shows the requested skill name). The
	// fetched body also lands in tool history rather than the system prompt, so
	// it carries less authority. Reserve "eager" for servers you trust.
	SkillsMode string `json:"skillsMode,omitempty"`

	// SkillsAllow, when non-empty, restricts this server to the named skills
	// (by skill Name), a hard capability boundary rather than a display
	// preference. The fetched index is narrowed to the allowed entries before
	// anything else, so both the injected block (eager or catalog) and the
	// load_skill tool only ever see allowed skills. Nil or empty means every
	// skill the server advertises. This is the skills analog of Allow.
	SkillsAllow []string `json:"skillsAllow,omitempty"`

	// Events lists the event streams to open on this server. Each event
	// feeds the injection policy (and any trigger bindings that match).
	Events []EventConfig `json:"events,omitempty"`

	// Agents controls experimental server-advertised agent discovery
	// (experimental/ext/agents). Nil or true auto-detects: a server that
	// advertises the io.modelcontextprotocol/agents extension has its roster
	// (agents/list) pulled and each agent added as a lazy delegate tool the
	// main agent can call; a server without the capability is skipped
	// silently. False opts out even when the server advertises it. Resolution
	// (agents/get: instructions + scoped tools) is deferred to first
	// delegation, so scoped tool schemas never enter the supervisor's context
	// (progressive disclosure, mirroring catalog-mode skills). The delegated
	// agent runs as a local child Runner whose tool calls loop back to the
	// advertising server — an agent.AgentSource like any other sub-agent.
	Agents *bool `json:"agents,omitempty"`
}

ServerConfig is one MCP server connection.

type ServerStatus

type ServerStatus struct {
	client.MemberStatus
	CanLogin bool
}

ServerStatus is one MCP server's state for the /mcp view: the client-layer connection status plus the host-layer CanLogin (an interactive oauth auth type is configured, so a needs-login server can be logged in). Kept a host-layer struct because CanLogin is a config fact the client layer does not carry.

type SessionPage

type SessionPage struct {
	Runs    []agent.RunInfo
	HasMore bool
}

SessionPage is one page of the session picker: the runs on this page and HasMore reporting whether another page exists (the underlying cursor is remembered on the App so the next SessionsPage("") advance-from-last works via the /sessions "more" flow — callers page by empty cursor for the first page, then let the host thread its remembered cursor).

type SubAgentConfig

type SubAgentConfig struct {
	// Name is the tool name the main agent calls to delegate. Required.
	Name string `json:"name"`

	// Description tells the main agent when to delegate to this persona.
	Description string `json:"description,omitempty"`

	// Instructions is the persona's system prompt. Empty means the sub-agent
	// is defined only by the task it is handed.
	Instructions string `json:"instructions,omitempty"`

	// Allow narrows which server tools this persona may use (by tool name).
	// Empty means all server tools.
	Allow []string `json:"allow,omitempty"`

	// MaxDepth caps sub-agent nesting for this persona. Zero uses the agent
	// default.
	MaxDepth int `json:"maxDepth,omitempty"`

	// InputSchema, when set, gives the persona a TYPED input tool instead of the
	// default {task} — the parent must pass arguments matching this JSON schema,
	// and the persona is seeded with them (structured input, 1033). Empty keeps
	// {task: string}.
	InputSchema json.RawMessage `json:"inputSchema,omitempty"`

	// ResponseSchema, when set, makes the persona return a JSON value coerced to
	// this schema instead of free text (structured output, 1033) — the parent
	// gets typed output back. Empty returns text.
	ResponseSchema json.RawMessage `json:"responseSchema,omitempty"`

	// CanSignal, when true, gives the persona the signal_parent control tool
	// (issue 1165), so it can raise an upward Signal to the main agent —
	// "escalate" or "custom" (reporting only its own state; it has no knowledge
	// of sibling agents). The main agent reacts per Config.SignalPolicy
	// (inject-and-continue by default). False (the default) keeps the persona
	// server-tools-only. Ignored for async personas (a detached child has no
	// live parent dispatch to signal).
	CanSignal bool `json:"canSignal,omitempty"`

	// Async, when true, builds the persona as the spawn-and-continue Task form
	// (agent.AsyncAgentSource, 1035): the delegate tool acks immediately and the
	// child runs in the background, its result injected as context on a later
	// turn — for long-running subtasks the parent should not block on. False
	// (the default) is the blocking Tool form (answer this turn).
	Async bool `json:"async,omitempty"`
}

SubAgentConfig is one delegatable persona. The host builds it into an agent.AgentSource over a child Runner that shares the main provider and a FilterSource-narrowed view of the server tools.

type SystemPromptBuilder

type SystemPromptBuilder struct {
	Sections []PromptSection
}

SystemPromptBuilder assembles the system prompt from ordered sections. It is the host-layer composition over the Runner's low-level InstructionsFunc hook: Build runs each turn and joins the non-empty sections, so prompt assembly is composable — reorder, insert profile/domain-guide sections, or replace the section list — instead of being hard-coded. The default builder mirrors the previous fixed assembly (base instructions, then per-server skill blocks in config order); WithSystemPromptBuilder lets a caller customize it.

func (*SystemPromptBuilder) Append

func (b *SystemPromptBuilder) Append(s PromptSection)

Append adds a section after the existing ones.

func (*SystemPromptBuilder) Build

func (b *SystemPromptBuilder) Build(ctx context.Context) string

Build joins every non-empty section in order, separated by a blank line, and runs each turn (wired as RunnerConfig.InstructionsFunc). A section that returns "" contributes nothing, so empty base instructions or a server with no skills leave no blank gap.

func (*SystemPromptBuilder) Prepend

func (b *SystemPromptBuilder) Prepend(s PromptSection)

Prepend adds a section before the existing ones.

type TeamMemberConfig

type TeamMemberConfig struct {
	SubAgentConfig

	// HandoffTo lists the member names this agent may transfer control to. Each
	// becomes a transfer_to_<name> tool offered only to this agent. Empty means
	// a terminal agent that must answer rather than transfer.
	HandoffTo []string `json:"handoffTo,omitempty"`
}

TeamMemberConfig is one Team agent: a persona (SubAgentConfig — shared provider, serverTools filtered by Allow, own instructions) plus the members it may hand off to.

type ThinkingHint

type ThinkingHint struct {
	OpenTag  string `json:"openTag,omitempty"`
	CloseTag string `json:"closeTag,omitempty"`
}

ThinkingHint delimits a model's inline reasoning. An empty OpenTag means reasoning starts at the stream head and runs until CloseTag (the "no open tag" models); an empty CloseTag means the hint is inert.

type TriggerConfig

type TriggerConfig struct {
	// Server and Event select the stream; Server empty matches any.
	Server string `json:"server,omitempty"`
	Event  string `json:"event"`

	// Filter is a set of top-level payload field equality checks (all
	// must match). The config-file rendition of the code-level filter
	// hook; embedders wanting richer predicates use the agent package
	// directly.
	Filter map[string]string `json:"filter,omitempty"`

	// Instructions seed the proactive turn.
	Instructions string `json:"instructions"`

	// Label names the binding in transcripts and logs.
	Label string `json:"label"`

	// CooldownSec is the re-arm floor in seconds (0 = default 300).
	CooldownSec int `json:"cooldownSec,omitempty"`
}

TriggerConfig declares one proactive-turn binding, mediated by the anti-nag policy (one firing per binding until user engagement plus the cooldown, session budget on top).

Jump to

Keyboard shortcuts

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