agentapp

package
v0.1.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const AgentsMdFilename = "AGENTS.md"

AgentsMdFilename is the name of the workspace-level agent instructions file per the agents.md convention (https://agents.md/).

View Source
const DefaultSystemPrompt = `` /* 4627-byte string literal not displayed */

DefaultSystemPrompt is the default system message for the BuildMax CLI agent.

Variables

This section is empty.

Functions

func BuildAgentTypes

func BuildAgentTypes(registry llm.ToolRegistry, userDefs []tools.SubAgentDef) map[string]tools.AgentTypeConfig

BuildAgentTypes merges built-in sub-agent definitions with caller-provided user defs into an AgentTypeConfig map ready for tools.NewTask.

func BuildEffectiveSystemPrompt

func BuildEffectiveSystemPrompt(workspaceDir, modelName string) string

BuildEffectiveSystemPrompt builds the agent system prompt for a workspace and optional model name. Reads ~/.buildmax/AGENTS.md (personal rules) and <ws>/AGENTS.md (project rules), appending both when present: global first, workspace second. Pass an empty modelName when not yet known.

func DefaultModelName

func DefaultModelName(settings config.Settings) string

func DeleteSession

func DeleteSession(dir, id string) error

DeleteSession removes a session from the index file and deletes its data file.

func DeleteSessionsByWorkspace

func DeleteSessionsByWorkspace(dir, workspace string) ([]string, error)

func LoadSession

func LoadSession(dir, id string) (*session.Session, error)

LoadSession reads a single session file from dir without requiring an AgentApp instance.

func LoadSessionList

func LoadSessionList(dir string) ([]session.SessionItem, error)

LoadSessionList reads the session index from dir without requiring an AgentApp instance.

func NewInteractivePolicy

func NewInteractivePolicy() agent.ToolPolicy

NewInteractivePolicy returns the policy for interactive surfaces (CLI TUI, Desktop). Tool-declared Ask actions will surface an approval prompt via the ApprovalHandler.

func NewNonInteractivePolicy

func NewNonInteractivePolicy() agent.ToolPolicy

NewNonInteractivePolicy returns the policy for non-interactive surfaces (worker, print mode, portal conversation). Tool-declared Ask actions collapse to Deny because no ApprovalHandler is set on these surfaces.

func ReadAgentsMd

func ReadAgentsMd(dir string) (string, error)

ReadAgentsMd reads AGENTS.md from the given directory. Returns ("", nil) when the file does not exist.

func RenameSession

func RenameSession(dir, id, title string) error

func ResolveAgentTypeTools

func ResolveAgentTypeTools(agentName string, toolNames []string, registry llm.ToolRegistry) []llm.Tool

ResolveAgentTypeTools resolves tool names from a registry; skips unknowns with a warning.

func SetSessionPinned

func SetSessionPinned(dir, id string, pinned bool) error

func UpsertSessionItem

func UpsertSessionItem(dir string, entry session.SessionItem) error

UpsertSessionItem adds or updates one entry in the session index at dir/sessions.json. Exported for test setup; production writes go through SessionManager.Save.

Types

type AgentApp

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

func NewAgentApp

func NewAgentApp(cfg AppConfig) (*AgentApp, error)

func (*AgentApp) AgentDefs

func (a *AgentApp) AgentDefs() []tools.SubAgentDef

AgentDefs returns the user-defined sub-agent definitions for this workspace.

func (*AgentApp) Close

func (a *AgentApp) Close() error

func (*AgentApp) CloseSession

func (a *AgentApp) CloseSession(sess *SessionContext)

CloseSession fires the SessionEnd hook for a finished session. Sessions persist on disk; this is the explicit signal for hooks/audit that the caller is done with that session. Safe to call with a nil session.

func (*AgentApp) DefaultModelName

func (a *AgentApp) DefaultModelName() string

func (*AgentApp) EstimateRunStatus

func (a *AgentApp) EstimateRunStatus(sess *SessionContext) (RunStatus, error)

func (*AgentApp) GenerateSessionTitle

func (a *AgentApp) GenerateSessionTitle(ctx context.Context, sess *SessionContext) (string, cllm.Usage, error)

func (*AgentApp) ListSessions

func (a *AgentApp) ListSessions() ([]session.SessionItem, error)

func (*AgentApp) MCPStatus

func (a *AgentApp) MCPStatus() MCPStatus

func (*AgentApp) ModelConfigs

func (a *AgentApp) ModelConfigs() []ModelConfig

func (*AgentApp) OpenOrCreateSession

func (a *AgentApp) OpenOrCreateSession(sessionID string) (*SessionContext, error)

OpenOrCreateSession loads sessionID when it has been persisted, or creates a new session with that ID. Remote task runs use this because the server assigns a session ID before the worker has written the first session file.

func (*AgentApp) OpenSession

func (a *AgentApp) OpenSession(sessionID string) (*SessionContext, error)

func (*AgentApp) RefreshMCP

func (a *AgentApp) RefreshMCP(ctx context.Context) (MCPStatus, error)

func (*AgentApp) RunPrompt

func (a *AgentApp) RunPrompt(ctx context.Context, sess *SessionContext, prompt string, stream cllm.StreamSink, approval agent.ApprovalHandler, eventSink func(agent.Event)) (RunResult, error)

func (*AgentApp) Sandbox

func (a *AgentApp) Sandbox() agent.SandboxView

Sandbox returns the SandboxView the agent will run with. In Phase A this is always NoopSandbox; Phase B will install the OS-backed manager.

func (*AgentApp) SandboxResolution

func (a *AgentApp) SandboxResolution() config.SandboxResolution

SandboxResolution returns the resolved config plus the per-layer source chain. Surfaced by `buildmax sandbox status`.

func (*AgentApp) SandboxStatus

func (a *AgentApp) SandboxStatus() SandboxStatus

SandboxStatus returns the resolved sandbox config plus runtime state.

func (*AgentApp) SessionsDir

func (a *AgentApp) SessionsDir() string

func (*AgentApp) SetDefaultModel

func (a *AgentApp) SetDefaultModel(name string)

SetDefaultModel overrides the model used for new turns in this AgentApp.

func (*AgentApp) SkillEntries

func (a *AgentApp) SkillEntries() []tools.SkillEntry

func (*AgentApp) ToolEntries

func (a *AgentApp) ToolEntries() []ToolEntry

ToolEntries returns the name and description of every tool available to the agent. It reuses the cached tool registry when available; otherwise it builds one.

func (*AgentApp) WorkspaceRoot

func (a *AgentApp) WorkspaceRoot() string

type AppConfig

type AppConfig struct {
	WorkspaceDir string
	EnableMCP    bool
	// ModelEntries overrides settings.yaml models for this AgentApp. Workers use
	// this to receive the server's resolved model without writing credentials to
	// a run directory that is later persisted as an artifact.
	ModelEntries []config.ModelEntry
	// Policy sets the tool permission policy for all runs in this AgentApp.
	// Nil defaults to AllowAllPolicy for backward compatibility.
	Policy agent.ToolPolicy
	// SandboxSurface picks the per-surface default sandbox baseline (see
	// config.SandboxSurfaceCLI / SandboxSurfaceWorker). Empty means
	// SandboxSurfaceCLI.
	SandboxSurface config.SandboxSurface
	// ManagedToken supplies the BuildMax credential for models configured with
	// transport "buildmax". Leaving it nil means this surface offers no managed
	// inference, and such an entry fails with a clear error instead of falling
	// back to a direct provider call.
	ManagedToken ManagedTokenFunc
	// Surface labels managed calls for correlation, e.g. "cli" or "desktop".
	Surface string
}

type HookManager

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

HookManager owns the merged hooks configuration, the per-type driver registry, and the matcher cache. It is the single object the agent runtime interacts with (via agent.HookRunner). Driver polymorphism is invisible above this layer.

Concurrency: HookManager is safe to call from multiple goroutines. The matcher cache uses a mutex; per-call execution is otherwise stateless.

func NewHookManager

func NewHookManager(cfg config.HooksConfig, drivers map[string]hook.Driver) *HookManager

NewHookManager constructs a manager from the already-merged hooks config and a driver registry. A nil registry is treated as empty; entries whose resolved type has no driver are skipped with a warning at dispatch time (logged once per event invocation).

func (*HookManager) Refresh

func (m *HookManager) Refresh(cfg config.HooksConfig)

Refresh swaps the merged config without rebuilding driver instances. The matcher cache is preserved so previously compiled regexes are still hot. Drivers that watch their own dependencies (HTTP transport, MCP catalog) pick up changes via their Deps.

func (*HookManager) Run

Run implements agent.HookRunner. See docs/design/hook-system.md §8.2 for the dispatch flow. The first matching entry that returns a block decision wins for the gate; every other matching entry still executes so audit hooks see every event.

func (*HookManager) Status

func (m *HookManager) Status() HookStatus

Status returns a snapshot describing what the manager currently dispatches.

type HookStatus

type HookStatus struct {
	EventCounts map[string]int `json:"event_counts"`
	Types       []string       `json:"types"`
	TotalHooks  int            `json:"total_hooks"`
}

HookStatus describes the visible state of the manager — counts per event and which transport types are configured. Suitable for a future `buildmax hooks` inspector or desktop activity view.

type LLMClientCache

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

func (*LLMClientCache) Get

func (r *LLMClientCache) Get(modelName string) (cllm.LLMClient, error)

type LLMCompactor

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

LLMCompactor implements agent.ContextCompactor using the same LLM client as the agent run. It calls the model once with a summarize prompt over the messages to compact.

func NewLLMCompactor

func NewLLMCompactor(client llm.LLMClient) *LLMCompactor

NewLLMCompactor creates a compactor backed by the given LLM client.

func (*LLMCompactor) Compact

func (c *LLMCompactor) Compact(ctx context.Context, msgs []llm.Message) (string, error)

Compact summarizes msgs into a short text suitable for injection into the system prompt.

type MCPManager

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

func NewMCPManager

func NewMCPManager(ctx context.Context, cfg *config.MCPConfigRoot) (*MCPManager, error)

NewMCPManager performs an initial Refresh with the provided config. Config load failures are returned as errors; individual server connection failures are surfaced only via Status().

func (*MCPManager) Close

func (m *MCPManager) Close() error

func (*MCPManager) Refresh

func (m *MCPManager) Refresh(ctx context.Context, cfg *config.MCPConfigRoot) error

Refresh reconnects to all servers in cfg. Individual server connection failures are non-fatal and are recorded in Status() instead.

func (*MCPManager) Registry

func (m *MCPManager) Registry() *mcp.Registry

func (*MCPManager) Status

func (m *MCPManager) Status() MCPStatus

type MCPStatus

type MCPStatus struct {
	LoadError string
	Servers   []mcp.MCPServerStatus
}

type ManagedTokenFunc

type ManagedTokenFunc func(serverURL string) (string, error)

ManagedTokenFunc returns the BuildMax credential to use for serverURL. It is expected to refuse when the stored login belongs to a different server.

type ModelConfig

type ModelConfig struct {
	Name          string
	ProviderModel string
	BaseURL       string
	APIKey        string
	ContextWindow int // 0 = no windowing; from settings.yaml model entry
	CallTimeout   int // seconds; 0 = uses DefaultCallTimeoutSecs
	// Transport is config.TransportDirect or config.TransportBuildMax. Empty
	// means direct.
	Transport string
	// ServerURL and TeamID are set on a managed entry. ProviderModel then holds
	// the team alias rather than a provider's model identifier.
	ServerURL string
	TeamID    string
}

ModelConfig is one resolved model entry usable for client creation.

func DefaultModelConfig

func DefaultModelConfig(settings config.Settings) (ModelConfig, bool)

func FindModelConfig

func FindModelConfig(settings config.Settings, name string) (ModelConfig, bool)

func ModelConfigFromEntry

func ModelConfigFromEntry(entry config.ModelEntry) ModelConfig

ModelConfigFromEntry resolves one settings.yaml model entry. Surfaces use it to describe a model without building a client for it.

func (ModelConfig) IsManaged

func (c ModelConfig) IsManaged() bool

IsManaged reports whether this model calls a BuildMax gateway.

type RunResult

type RunResult struct {
	Reply                 string
	Duration              time.Duration
	ToolCalls             int
	PromptTokens          int
	CompletionTokens      int
	TotalPromptTokens     int
	TotalCompletionTokens int
	ContextTokens         int
	ContextWindow         int
	SessionID             string
	Workspace             string
	ModelName             string
	// TraceID identifies the durable run trace written for this run, or "" when
	// tracing is disabled or failed to start. Points at
	// <DataDir>/traces/<session_id>/<trace_id>.jsonl.
	TraceID string
	// TracePath is that file's path on disk, or "" when no trace was written.
	// Callers that persist a reference to the trace use this instead of
	// rebuilding the layout from TraceID, so the stored path and the written
	// file cannot disagree.
	TracePath string
}

type RunStatus

type RunStatus struct {
	ContextTokens         int `json:"context_tokens"`
	ContextWindow         int `json:"context_window"`
	PromptTokens          int `json:"prompt_tokens"`
	CompletionTokens      int `json:"completion_tokens"`
	TotalPromptTokens     int `json:"total_prompt_tokens"`
	TotalCompletionTokens int `json:"total_completion_tokens"`
}

type SandboxStatus

type SandboxStatus struct {
	Resolution   config.SandboxResolution
	Deps         sandbox.DepsReport
	Backend      string              // backend currently active ("bwrap", "seatbelt", "none")
	Enabled      bool                // SandboxView.Enabled() — false when backend unavailable
	Mode         string              // "auto_allow" | "regular" | "" when disabled
	ProxyAddress string              // in-process HTTP proxy address ("" when not running)
	ProxyAllows  uint64              // cumulative allow decisions since proxy start
	ProxyDenies  uint64              // cumulative deny decisions since proxy start
	Recent       []sandbox.Violation // latest entries from the violation store
}

SandboxStatus is the snapshot returned by AgentApp.SandboxStatus(), used by `buildmax sandbox status` / `deps`. Mirrors what is shown by Claude Code's /sandbox panel: resolved config, source chain, backend, deps.

type SessionContext

type SessionContext struct {
	*session.Session
	// contains filtered or unexported fields
}

SessionContext wraps a persisted session with runtime helpers.

func NewSessionContext

func NewSessionContext(sess *session.Session, defaultModel string) *SessionContext

func (*SessionContext) ModelName

func (s *SessionContext) ModelName(fallback string) string

ModelName returns the selected model for this session, or the provided fallback.

func (*SessionContext) SetModel

func (s *SessionContext) SetModel(name string)

SetModel updates the selected model for this session.

type SessionManager

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

SessionManager manages file-based session lifecycle for AgentApp.

func (*SessionManager) Create

func (s *SessionManager) Create(defaultModel string) *SessionContext

func (*SessionManager) Finalize

func (s *SessionManager) Finalize(ctx context.Context, client llm.LLMClient, sess *SessionContext, workspace string, stats agent.RunStats) (TurnFinalizeResult, error)

Finalize runs the post-turn flow: accumulate token usage, persist the session, and generate a title via LLM if one is not yet set.

func (*SessionManager) GenerateTitle

func (s *SessionManager) GenerateTitle(ctx context.Context, client llm.LLMClient, sess *SessionContext) (string, llm.Usage, error)

func (*SessionManager) List

func (s *SessionManager) List() ([]session.SessionItem, error)

func (*SessionManager) Load

func (s *SessionManager) Load(id, defaultModel string) (*SessionContext, error)

func (*SessionManager) Save

func (s *SessionManager) Save(sess *SessionContext, workspace string) error

type SkillRegistry

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

func (*SkillRegistry) Entries

func (s *SkillRegistry) Entries() []tools.SkillEntry

func (*SkillRegistry) Load

func (s *SkillRegistry) Load(workspace string) error

func (*SkillRegistry) NewTool

func (s *SkillRegistry) NewTool() *tools.SkillTool

type SubAgentRegistry

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

func (*SubAgentRegistry) Definitions

func (s *SubAgentRegistry) Definitions() []tools.SubAgentDef

func (*SubAgentRegistry) Load

func (s *SubAgentRegistry) Load(workspace string) error

type ToolEntry

type ToolEntry struct {
	Name        string
	Description string
}

ToolEntry is a name+description pair for a tool available to the agent.

type TurnFinalizeResult

type TurnFinalizeResult struct {
	Title            string
	PromptTokens     int
	CompletionTokens int
}

Directories

Path Synopsis
Package taskrun provides task-run execution.
Package taskrun provides task-run execution.

Jump to

Keyboard shortcuts

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