agent

package
v0.3.0 Latest Latest
Warning

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

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

This section is empty.

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) 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) Models

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

Models lists the models a provider offers: whatever its /models endpoint reports, merged with any models added by hand in config (providers.<id>. models). Manually added ids that the endpoint does not return are appended, carrying a context window from providers.<id>.model_meta when set. A live fetch that fails still yields the 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) 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.

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).

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.

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)

Run executes one user turn to completion, streaming progress through emit.

func (*Agent) SetConfig

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

SetConfig swaps in a reloaded configuration.

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.

func (*Agent) SetRAG

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

SetRAG swaps the retrieval provider after a config change.

func (*Agent) SetRoles

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

SetRoles attaches the role registry.

func (*Agent) SetSkills

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

SetSkills attaches the skill library.

func (*Agent) Shell

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

Shell exposes the terminal manager for lifecycle handling.

func (*Agent) Skills

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

Skills returns the skill library (may be nil).

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"`
}

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 Request

type Request struct {
	SessionID string
	Message   string
	Images    []llm.Part
	Platform  string
	UserID    string
	ChannelID 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.

Jump to

Keyboard shortcuts

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