agent

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2026 License: Apache-2.0 Imports: 39 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 implements the conversation loop: it builds the prompt, calls the model, executes the tools it asks for, and streams every step out.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSessionBusy  = errors.New("a turn is already running for this session")
	ErrSessionLimit = errors.New("concurrent session limit reached")
)

Functions

func SubscribeSwarm

func SubscribeSwarm() (<-chan struct{}, func())

SubscribeSwarm returns a channel that fires when the active sub-agent set changes, plus a cancel func. Exported for the server's swarm-stream handler.

Types

type ActiveAgent

type ActiveAgent struct {
	ID        string    `json:"id"`
	Role      string    `json:"role"`
	Task      string    `json:"task"`
	Parent    string    `json:"parent"`
	StartedAt time.Time `json:"started_at"`
}

ActiveAgent is one sub-agent running right now.

type Agent

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

Agent owns the shared services a run needs.

func New

func New(cfg *config.Config, db store.Store, reg *tools.Registry, shell *tools.ShellManager, ragProvider tools.RAGProvider) *Agent

New builds an agent.

func (*Agent) ActiveAgents

func (a *Agent) ActiveAgents() []ActiveAgent

ActiveAgents lists the sub-agents running now, oldest first.

func (*Agent) ActiveAgentsFor

func (a *Agent) ActiveAgentsFor(parent string) []ActiveAgent

ActiveAgentsFor lists the sub-agents running now for one delegating session, oldest first. An empty parent returns all of them (the process-wide view). A non-empty parent scopes the list so one chat only sees the sub-agents IT spawned — otherwise a workers running for an old session leak into a new one.

func (*Agent) ActiveCount

func (a *Agent) ActiveCount() int

ActiveCount reports how many turns are running.

func (*Agent) BackgroundActivity

func (a *Agent) BackgroundActivity(sessionID string) []BgStat

BackgroundActivity exposes a session's background-tool usage for the API.

func (*Agent) BackgroundTasks

func (a *Agent) BackgroundTasks() []tools.TaskInfo

BackgroundTasks lists every task for the swarm/status views.

func (*Agent) Checkpoint

func (a *Agent) Checkpoint(sessionID string) (*checkpoint.Checkpoint, error)

Checkpoint reports what a session has changed so far.

func (*Agent) CompactNow added in v0.4.0

func (a *Agent) CompactNow(ctx context.Context, sessionID string, emit Emit) error

CompactNow summarises a session's older turns immediately, regardless of the usage threshold maybeCompact waits for, and streams its progress to emit. It is what the /compact command runs: unlike maybeCompact it does not defer the work to the next turn, and it finishes by emitting a usage event carrying the freed context so the gauge drops the moment compaction lands rather than only after the next model call. The summary is persisted, so the next turn loads head + summary + tail without re-summarising.

func (*Agent) Config

func (a *Agent) Config() *config.Config

Config exposes the live configuration.

func (*Agent) Distil

func (a *Agent) Distil(ctx context.Context, sessionID, hint string) (string, error)

Distil writes a skill from a session's transcript. It returns the Markdown, or an empty string when there was nothing worth keeping.

func (*Agent) Findings

func (a *Agent) Findings() *findings.Store

Findings exposes the engagement ledger.

func (*Agent) GetGoal

func (a *Agent) GetGoal(ctx context.Context, sessionID string) (*Goal, bool)

GetGoal reads the standing goal for a session, if there is one.

func (*Agent) Intel

func (a *Agent) Intel() *engagement.Store

Intel exposes the engagement's fact ledger.

func (*Agent) Interrupt

func (a *Agent) Interrupt(sessionID string) bool

Interrupt cancels a running turn for a session.

func (*Agent) KickAutonomousGoal added in v0.4.0

func (a *Agent) KickAutonomousGoal(ctx context.Context, sessionID, platform, channelID string)

KickAutonomousGoal starts the first turn of a just-set confident goal by firing the registered turn-end driver, so `/goal auto` begins working immediately instead of only after some later turn. It is a no-op when no host registered a driver or the goal is not an active autonomous one. Platform and channelID let a gateway-set goal deliver its turns back to the right chat.

func (*Agent) Models

func (a *Agent) Models(ctx context.Context, providerID string) ([]llm.ModelInfo, error)

Models lists the models a provider offers.

If providers.<id>.models is non-empty it is treated as a whitelist: only those ids are returned (no live /models merge). This keeps curated local gateways (e.g. Sub2API antigravity) from flooding the UI with broken or deprecated upstream catalog entries.

If the list is empty, the provider's /models endpoint is queried live. A live fetch that fails still yields any manual list rather than nothing.

func (*Agent) OnBackgroundDone

func (a *Agent) OnBackgroundDone(cb func(BackgroundDone))

OnBackgroundDone registers the callback invoked when a background sub-agent finishes. The server uses it to resume (or wake) the delegating session.

func (*Agent) OnTurnEnd added in v0.4.0

func (a *Agent) OnTurnEnd(cb func(TurnEnded))

OnTurnEnd registers the callback invoked when a top-level turn finishes.

func (*Agent) Panel

func (a *Agent) Panel(ctx context.Context, question string, models []string, emit Emit) (string, []PanelAnswer, error)

Panel asks several models the same question and synthesises one answer.

The value is in the disagreement: where independent answers diverge is usually where the question was ambiguous or the problem is genuinely hard, and that is exactly what a single sample hides.

func (*Agent) PendingApprovals

func (a *Agent) PendingApprovals() []ApprovalRequest

PendingApprovals lists what is waiting, oldest first.

func (*Agent) PendingAsks

func (a *Agent) PendingAsks() []pendingAsk

PendingAsks lists the questions currently waiting, so a client that connects mid-pause (a reload) can render them.

func (*Agent) Plugins

func (a *Agent) Plugins() *plugin.Manager

Plugins exposes the manager, or nil when none is attached. Callers must reuse the returned pointer for the whole operation rather than re-reading, so a concurrent SetPlugins cannot race a nil check against a later dereference.

func (*Agent) Prepare added in v0.4.0

func (a *Agent) Prepare(ctx context.Context, req Request) (*PreparedRun, error)

func (*Agent) PreviewChangesSince

func (a *Agent) PreviewChangesSince(sessionID, marker string) ([]checkpoint.ChangedSince, error)

PreviewChangesSince lists files a session changed at/after a message marker, for the "edit message → revert?" prompt.

func (*Agent) Probe

func (a *Agent) Probe(ctx context.Context) (bool, string)

Probe checks whether the configured provider answers, for /api/status.

func (*Agent) PruneCheckpoints

func (a *Agent) PruneCheckpoints(olderThan time.Duration) (int, error)

PruneCheckpoints drops the ones older than the given age.

func (*Agent) RAG

func (a *Agent) RAG() tools.RAGProvider

RAG returns the active retrieval provider (may be nil). Callers must reuse the returned value for the whole operation rather than re-reading, so a concurrent SetRAG cannot race a nil check against a later use.

func (*Agent) Registry

func (a *Agent) Registry() *tools.Registry

Registry exposes the tool registry.

func (*Agent) ResolveApproval

func (a *Agent) ResolveApproval(id string, allow bool) bool

ResolveApproval answers a pending request. It reports false when the id is unknown, which usually means it already timed out.

func (*Agent) ResolveAsk

func (a *Agent) ResolveAsk(id, answer string) bool

ResolveAsk delivers the person's answer to a waiting question set. It reports false when the id is unknown (already answered, or the run was cancelled).

func (*Agent) RolePerformance

func (a *Agent) RolePerformance() *roleperf.Tracker

RolePerformance exposes the per-role performance tracker.

func (*Agent) Roles

func (a *Agent) Roles() *roles.Registry

Roles exposes the registry. Callers must reuse the returned pointer for the whole operation rather than re-reading, so a concurrent SetRoles cannot race a nil check against a later use.

func (*Agent) Rollback

func (a *Agent) Rollback(sessionID string, paths []string) (*checkpoint.RestoreResult, error)

Rollback restores the files a session changed. Passing paths restores only those.

func (*Agent) RollbackSince

func (a *Agent) RollbackSince(sessionID, marker string, skipExternal bool) (*checkpoint.RestoreResult, error)

RollbackSince reverts files changed at/after a message marker to their state just before it, optionally skipping files edited outside the session.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, req Request, emit Emit) (*Result, error)

func (*Agent) RunQueued added in v0.4.0

func (a *Agent) RunQueued(ctx context.Context, req Request, emit Emit) (*Result, error)

RunQueued is for autonomous continuations that must retain their context while other sessions occupy capacity. User requests use nonblocking Run.

func (*Agent) SetConfig

func (a *Agent) SetConfig(cfg *config.Config)

SetConfig swaps in a reloaded configuration. The pointer is published atomically; callers that need a stable view for a whole operation should snapshot it once via config() rather than re-reading across steps.

func (*Agent) SetGoal

func (a *Agent) SetGoal(ctx context.Context, sessionID string, g *Goal) error

SetGoal stores or replaces the standing goal.

func (*Agent) SetPlugins

func (a *Agent) SetPlugins(m *plugin.Manager)

SetPlugins attaches the plugin manager. Passing nil disables hooks. Publishes under servicesMu so a concurrent reader always sees a consistent pointer during a live reload.

func (*Agent) SetRAG

func (a *Agent) SetRAG(p tools.RAGProvider)

SetRAG swaps the retrieval provider after a config change. Publishes under servicesMu so a concurrent reader always sees a consistent pointer.

func (*Agent) SetRoles

func (a *Agent) SetRoles(r *roles.Registry)

SetRoles attaches the role registry. Publishes under servicesMu so a concurrent reader always sees a consistent pointer during a live reload.

func (*Agent) SetSkills

func (a *Agent) SetSkills(m *skills.Manager)

SetSkills attaches the skill library. Publishes under servicesMu.

func (*Agent) SetSocialBrowser added in v0.4.0

func (a *Agent) SetSocialBrowser(m tools.SocialBrowserManager)

SetSocialBrowser attaches the persistent social media browser manager.

func (*Agent) Shell

func (a *Agent) Shell() *tools.ShellManager

Shell exposes the terminal manager for lifecycle handling.

func (*Agent) ShouldAutoContinueGoal added in v0.4.0

func (a *Agent) ShouldAutoContinueGoal(ctx context.Context, sessionID string) bool

ShouldAutoContinueGoal reports whether the session has a confident autonomous goal that is still running (not done, not paused) and so should drive another turn on its own.

func (*Agent) Skills

func (a *Agent) Skills() *skills.Manager

Skills returns the skill library (may be nil). Callers must reuse the returned pointer for the whole operation rather than re-reading, so a concurrent SetSkills cannot race a nil check against a later dereference.

func (*Agent) Steer

func (a *Agent) Steer(sessionID, note string) bool

Steer queues a note for a run in progress. It is delivered after the current batch of tools finishes, which is the first moment the model can act on it without discarding work already underway.

It reports false when nothing is running for that session, so a caller can fall back to sending an ordinary message.

type ApprovalRequest

type ApprovalRequest struct {
	ID        string `json:"id"`
	SessionID string `json:"session_id"`
	Tool      string `json:"tool"`
	Arguments string `json:"arguments"`
	// Reason names why this needs asking about, when it is more than the tool
	// simply being one that writes.
	Reason    string    `json:"reason,omitempty"`
	CreatedAt time.Time `json:"created_at"`
	// contains filtered or unexported fields
}

ApprovalRequest is one pending decision.

type AskQuestion

type AskQuestion struct {
	Question    string   `json:"question"`
	Header      string   `json:"header,omitempty"`
	Options     []string `json:"options,omitempty"`
	MultiSelect bool     `json:"multiSelect,omitempty"`
}

AskQuestion is one question put to the user.

type BackgroundDone

type BackgroundDone struct {
	ParentSession string
	TaskID        string
	Role          string
	Task          string
	Output        string
	Err           string
}

BackgroundDone is the signal a finished background sub-agent sends back to the session that delegated it, so the main agent can be resumed with the result instead of polling for it.

type BgStat

type BgStat struct {
	Name  string    `json:"name"`
	Count int       `json:"count"`
	Last  time.Time `json:"last"`
}

BgStat is one background action's usage in a session.

type Emit

type Emit func(Event) error

Emit sends events to the caller. Returning an error aborts the run.

type Event

type Event struct {
	Type EventType `json:"type"`

	// session
	ID    string `json:"id,omitempty"`
	Title string `json:"title,omitempty"`

	// text / reasoning
	Delta string `json:"delta,omitempty"`

	// tool_call / tool_progress / tool_result
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`
	Content   string `json:"content,omitempty"`
	Chunk     string `json:"chunk,omitempty"`
	Message   string `json:"message,omitempty"`
	IsError   bool   `json:"is_error,omitempty"`

	// turn
	Turn int `json:"turn,omitempty"`

	// usage — InputTokens/OutputTokens are the run's cumulative totals (for the
	// cost/token readout). ContextTokens is the latest turn's input alone, i.e.
	// what actually occupies the window right now, and is what the fill gauge
	// must plot — the cumulative total climbs past the window on long runs and
	// would peg the gauge at 100% even when the real context is nearly empty.
	InputTokens   int     `json:"input_tokens,omitempty"`
	OutputTokens  int     `json:"output_tokens,omitempty"`
	ContextTokens int     `json:"context_tokens,omitempty"`
	Cost          float64 `json:"cost,omitempty"`
	// ContextWindow is the active model's token budget, so the UI can show how
	// full the context is (context tokens / window).
	ContextWindow int `json:"context_window,omitempty"`

	// error
	Err string `json:"error,omitempty"`
}

Event is one streamed update. Fields are populated per Type.

type EventType

type EventType string

EventType enumerates what the agent streams to callers.

const (
	EventSession      EventType = "session"
	EventTurn         EventType = "turn"
	EventText         EventType = "text"
	EventReasoning    EventType = "reasoning"
	EventToolCall     EventType = "tool_call"
	EventToolProgress EventType = "tool_progress"
	EventToolResult   EventType = "tool_result"
	EventUsage        EventType = "usage"
	EventNotice       EventType = "notice"
	EventApproval     EventType = "approval"
	EventAsk          EventType = "ask"   // ask_user is waiting for the person's answer; the turn is paused
	EventReset        EventType = "reset" // discard the partial assistant turn (before a retry)
	EventError        EventType = "error"
	EventDone         EventType = "done"
)

type Goal

type Goal struct {
	Text       string `json:"text"`
	Iterations int    `json:"iterations"`
	Max        int    `json:"max"`
	Paused     bool   `json:"paused"`
	Done       bool   `json:"done"`
	Note       string `json:"note,omitempty"`

	// Autonomous marks a "confident" goal: instead of ending the turn and
	// waiting for the user after each judge step, the agent keeps starting new
	// turns on its own until the goal is met, the cap is reached, or it hits a
	// blocker only the user can clear. Opt-in (via `/goal auto`) because it
	// spends tokens unattended. Normal goals leave this false and behave as
	// before.
	Autonomous bool `json:"autonomous,omitempty"`
	// StuckCount rises each time the judge asks for the same next step again (or
	// the same step keeps failing). It drives tiered escalation: the higher it
	// climbs, the harder the agent is pushed to change tactics — read the docs,
	// search the web/tutorials, then delegate a research sub-agent. Reset to 0
	// whenever the next step actually changes (progress was made).
	StuckCount int `json:"stuck_count,omitempty"`
	// LastNext is the previous judge next-step, used to detect "stuck" (the same
	// instruction coming back unchanged).
	LastNext string `json:"last_next,omitempty"`
	// Platform and ChannelID record where an autonomous goal was started from a
	// messaging gateway, so its auto-continued turns can be delivered back to
	// that chat rather than only the dashboard. Empty for web/CLI goals.
	Platform  string `json:"platform,omitempty"`
	ChannelID string `json:"channel_id,omitempty"`
}

Goal is an objective that outlives a single turn.

type PanelAnswer

type PanelAnswer struct {
	Model  string `json:"model"`
	Answer string `json:"answer"`
	Err    string `json:"error,omitempty"`
}

PanelAnswer is one model's response to a panel question.

type PreparedRun added in v0.4.0

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

PreparedRun reserves capacity before a host starts streaming. Close also releases an unused reservation, for example when the client disconnects.

func (*PreparedRun) Close added in v0.4.0

func (p *PreparedRun) Close()

func (*PreparedRun) Run added in v0.4.0

func (p *PreparedRun) Run(emit Emit) (*Result, error)

func (*PreparedRun) SessionID added in v0.4.0

func (p *PreparedRun) SessionID() string

type Request

type Request struct {
	SessionID string
	Message   string
	Images    []llm.Part
	Platform  string
	UserID    string
	ChannelID string
	// UserName is the sender's platform handle (e.g. Discord username), and
	// UserDisplayName the friendliest name to address them by (server nickname
	// or display name). Both are shown to the model so it knows who it is
	// talking to; empty on surfaces without a distinct user (the CLI).
	UserName        string
	UserDisplayName string
	// Toolset overrides the configured toolset for this run.
	Toolset string
	// Model overrides the configured model for this run.
	Model string
	// ReasoningEffort overrides the configured reasoning effort for this run.
	ReasoningEffort string
	// MaxTurns overrides the configured turn budget.
	MaxTurns int
	// SystemExtra is appended to the system prompt (used by sub-agents).
	SystemExtra string
	// Role names a specialist whose prompt, toolset, and model are applied
	// before the run. Empty is the general assistant.
	Role string
	// Quiet suppresses persistence, used for one-shot internal runs.
	Quiet bool
	// Depth guards against unbounded delegation recursion.
	Depth int
	// Workspace overrides the working directory for this run, used by an
	// isolated sub-agent running in its own worktree.
	Workspace string
	// ProjectDir, when set on a session's first turn, makes it a PROJECT
	// session bound to that folder: the workspace becomes the project, writes
	// are confined to the project (plus the antares workspace), reads are allowed
	// anywhere, and the project's AGENTS.md/README are folded into the prompt.
	// Persisted in the session's Meta; ignored on later turns of the same
	// session (the session already carries it).
	ProjectDir string
	// IndexRAG, set with ProjectDir on a project session's first turn, opts the
	// project into RAG: the folder is indexed into its own collection and that
	// collection joins auto-context. Persisted in Meta as rag_indexed.
	IndexRAG bool
	// ContextInject is background context the agent should act on this turn —
	// currently a finished sub-agent's result. It is fed to the model as new
	// input (so the agent resumes and processes it), but it is NOT shown as a
	// user message in the transcript: it is persisted hidden, so it reads as the
	// agent simply continuing on its own rather than the user asking again.
	ContextInject string
	// contains filtered or unexported fields
}

Request starts or continues a conversation.

type Result

type Result struct {
	SessionID string
	Reply     string
	Turns     int
	Usage     llm.Usage
}

Result summarises a completed run.

type SubStream

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

SubStream is the live event log for one sub-agent.

func GetSubStream

func GetSubStream(id string) *SubStream

GetSubStream returns the live stream for a sub-agent id, or nil if none is running (or it already finished). Exported for the server's attach handler.

func (*SubStream) Follow

func (ss *SubStream) Follow(ctx context.Context, cursor int, send func(Event) error) error

Follow replays events from cursor, then blocks for new ones until the sub-agent finishes or ctx is cancelled. send stops the follow by erroring.

type TurnEnded added in v0.4.0

type TurnEnded struct {
	SessionID string
	Platform  string
	// ChannelID/UserID let a gateway deliver the continued turn to the right
	// place (empty on the web/CLI).
	ChannelID string
	UserID    string
}

TurnEnded is fired after a non-quiet top-level turn completes. A host uses it to auto-continue a confident autonomous goal — start the next turn on its own.

Jump to

Keyboard shortcuts

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