agent

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SearchHintVerify  = "Validate agent integrity and security"
	DescriptionVerify = "" /* 145-byte string literal not displayed */
)

VerifyAgent is a security and validation agent It validates agent integrity and security without making changes

View Source
const (
	CategorySyntax      = "syntax"
	CategorySecurity    = "security"
	CategoryPermissions = "permissions"
	CategoryCompliance  = "compliance"
	CategoryStructure   = "structure"

	SeverityCritical = "critical"
	SeverityHigh     = "high"
	SeverityMedium   = "medium"
	SeverityLow      = "low"
)
View Source
const AgentPrompt = `Use this tool to delegate a bounded subtask to a sub-agent.

Sub-agents are best for isolation, parallelism, or focused execution contexts. They do not share your live reasoning state, so every delegated task must be self-contained.

## When to delegate

Use this tool when:
- the subtask is independent and can run in parallel,
- you need read-only exploration before editing,
- you need current or external information verified before making an important claim,
- you want verification in a fresh context,
- the work is large enough that isolating it will reduce parent-turn complexity.

Do NOT delegate when:
- the next blocking step is simple and easier to do directly,
- the prompt would be vague or underspecified,
- the task is tiny enough to complete in 1-2 direct tool calls.

## Agent types

- **general-purpose**: default for complex execution, coding, fixes, and multi-step work
- **explore**: read-only architecture and codebase investigation
- **browse**: read-only external research using web, browser, docs, and targeted local context
- **plan**: create a detailed implementation plan
- **verify**: validate, test, and review results in a fresh context

## Choosing the right agent type

- Use ` + "`explore`" + ` when the evidence should come mainly from the local repository.
- Use ` + "`browse`" + ` when the evidence should come mainly from current docs, provider behavior, release notes, policies, external references, or website interaction.
- Use ` + "`verify`" + ` after implementation or when you need a fresh validation pass.
- Use ` + "`plan`" + ` only when you want a structured implementation plan as the deliverable.
- Use ` + "`general-purpose`" + ` when the subtask combines several of the above and needs broader autonomy.

## How to write a good delegated task

Your ` + "`task`" + ` must include:
- the exact goal,
- relevant file paths, directories, symbols, or error messages,
- constraints like "read-only" or "do not modify files",
- and what the agent must return when done.

Good:
- "Explore ` + "`internal/auth`" + `, ` + "`internal/providers`" + `, and ` + "`cmd/cli`" + `. Report how browser/device auth works, where credentials are persisted, and any tests covering it. Do not modify files."
- "Browse the official provider docs and release notes for model streaming changes. Summarize current behavior, note breaking changes, and include sources. Do not modify files."

Bad:
- "Look into auth"

## Parallel work

For independent subtasks, call this tool multiple times in the same turn.
Use ` + "`run_in_background: true`" + ` when the parent can continue without waiting immediately.

## Parent/sub-agent workflow

- Parent should keep the visible session checklist in ` + "`todo_write`" + `.
- Sub-agents handle focused subtasks and report results back.
- Read all sub-agent outputs before deciding follow-up actions.
- If a sub-agent is gathering evidence, do not restate its conclusions as fact until you have read and integrated the result.

## Parameters

- ` + "`type`" + `: agent type
- ` + "`task`" + `: self-contained task prompt
- ` + "`tools`" + `: optional explicit allow-list
- ` + "`maxTurns`" + `: max turns for the sub-agent
- ` + "`run_in_background`" + `: launch asynchronously
- ` + "`fork`" + `: inherit selected parent transcript/messages

## Examples

// Read-only exploration
agent({ type: "explore", task: "Inspect request handling in cmd/grpc and pkg/grpc. Report entrypoints, service handlers, and any relevant tests. Do not modify files." })

// Parallel background investigations
agent({ type: "explore", task: "Inspect the frontend state flow for session persistence. Report findings only.", run_in_background: true })
agent({ type: "browse", task: "Research the latest official documentation and release notes for the provider API change. Summarize the important breaking changes with sources.", run_in_background: true })
agent({ type: "verify", task: "After the fix lands, run relevant tests and summarize failures or passes.", run_in_background: true })

// Focused implementation
agent({ type: "general-purpose", task: "Implement the sidebar session rename menu in the renderer and report the changed files plus validation steps." })`

Prompt for the agent tool

View Source
const AgentTypeAutomationManager = "automation-manager"
View Source
const AgentTypeBrowse = "browse"
View Source
const AgentTypeExplore = "explore"
View Source
const AgentTypeGeneralPurpose = "general-purpose"
View Source
const AgentTypePlan = "plan"
View Source
const AgentTypeSeshatCore = "seshat-core"

Agent types (built-in)

View Source
const AgentTypeVerify = "verify"
View Source
const DefaultMaxTurns = 50

DefaultMaxTurns is the fallback turn limit used only when no agent definition provides a MaxTurns value. Agent definitions (GeneralPurposeAgent, ExploreAgent, etc.) each declare their own MaxTurns which takes priority over this constant.

View Source
const DefaultSubAgentMaxTurns = 20

DefaultSubAgentMaxTurns is the fallback turn limit for sub-agents when the agent definition provides no MaxTurns. Agent definition values take priority.

View Source
const DefaultSubAgentTimeout = 30 * 60 // 30 minutes, in seconds

DefaultSubAgentTimeout is the wall-clock safety net for a single sub-agent run. This is NOT a functional limit — it exists to kill a sub-agent that is genuinely stuck (LLM unresponsive, infinite loop with no token output).

MaxTurns is the correct tool to bound normal execution. This timeout should only fire for pathological cases, which is why it is set to 30 minutes.

Reference values: Codex = 30s, OpenClaude = 60s. Those codebases use short values because their sub-agents do shorter tasks. Seshat targets complex autonomous coding tasks that legitimately need several minutes per sub-agent.

View Source
const DescriptionAgent = "" /* 137-byte string literal not displayed */

Description

View Source
const MaxAbsoluteSubAgentDepth = 5

MaxAbsoluteSubAgentDepth is the hard upper bound for MaxSubAgentDepth — the frontend must clamp user-configured values to this maximum.

View Source
const MaxSubAgentDepth = 3

MaxSubAgentDepth is the default maximum spawn depth allowed before an agent tool call is rejected. Prevents infinite delegation chains (A→B→C→…).

Reference values: Codex = 1 (strict), OpenClaude = 2 (hooks only). Seshat default = 3: supports A→B→C structures which cover real multi-agent patterns (orchestrator → specialist → helper) while blocking runaway chains.

This default can be overridden per-user via UserPreferences.MaxSubAgentDepth (stored in DB). The frontend exposes a slider from 1 to MaxAbsoluteSubAgentDepth.

View Source
const SearchHintAgent = "run a sub-agent to complete a task independently"

Search hint

View Source
const ToolNameAgent = "agent"

Tool name

Variables

View Source
var (

	// GeneralPurposeAgent is the general-purpose agent
	GeneralPurposeAgent = BuiltInAgentDefinition{
		AgentType: AgentTypeGeneralPurpose,
		WhenToUse: "General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks.",
		Tools:     []string{"*"},
		Source:    AgentSourceBuiltIn,
		BaseDir:   "built-in",
		GetSystemPrompt: func() string {
			return `You are a general-purpose agent for Seshat. Given the user's message, use the tools available to complete the task.
Complete the task fully—don't gold-plate, but don't leave it half-done.

Your strengths:
- Searching for code, configurations, and patterns across large codebases
- Analyzing multiple files to understand system architecture
- Performing multi-step research tasks

Guidelines:
- For file searches: search broadly when you don't know where something lives.
- For analysis: Start broad and narrow down.
- NEVER create files unless they're absolutely necessary.
- NEVER proactively create documentation files unless explicitly requested.`
		},
		MaxTurns: 20,
	}

	// ExploreAgent is the explore agent (read-only)
	ExploreAgent = BuiltInAgentDefinition{
		AgentType: AgentTypeExplore,
		WhenToUse: "Explore codebases to understand architecture, find patterns, or investigate how something works (read-only analysis).",
		Tools:     []string{"read_file", "glob", "grep"},
		Source:    AgentSourceBuiltIn,
		BaseDir:   "built-in",
		GetSystemPrompt: func() string {
			return `You are an Explore agent for Seshat. Your role is to explore and analyze codebases.
YOU NEVER MAKE CHANGES - You ONLY READ AND ANALYZE.
If you need to make changes, respond with your findings and let the caller do the modifications.

Your task is to:
- Understand code structure and architecture
- Find patterns and relationships
- Investigate how features work
- Identify dependencies and interactions

Guidelines:
- Be thorough in your exploration
- Start with the big picture, then drill down
- Document your findings clearly
- Use multiple search strategies to find relevant code`
		},
		MaxTurns: 12,
	}

	// BrowseAgent is the deep research agent for external/web investigation.
	BrowseAgent = BuiltInAgentDefinition{
		AgentType: AgentTypeBrowse,
		WhenToUse: "Perform deep read-only research using web, browser, documentation, and local code context. Good for external investigation and multi-source analysis.",
		Tools:     browseAgentTools,
		Source:    AgentSourceBuiltIn,
		BaseDir:   "built-in",
		GetSystemPrompt: func() string {
			return `You are a Browse agent for Seshat. Your role is deep read-only research across external sources and local code context.
YOU NEVER MAKE CHANGES - You ONLY READ, INVESTIGATE, AND SYNTHESIZE.

Your strengths:
- Searching the web for current information
- Navigating sites and extracting structured information with browser tools
- Comparing multiple external sources
- Combining external research with local repository context

Guidelines:
- Prefer high-signal sources over many weak ones
- Use browser tools when you need exact page interaction or extraction
- Use web search to discover sources, then fetch or browse targeted pages
- Cite or clearly identify the sources you used in your findings
- If local code context matters, inspect only what is relevant and stay read-only
- Do not modify files, run write tools, or perform implementation work`
		},
		MaxTurns: 35,
	}

	// PlanAgent is the plan agent
	PlanAgent = BuiltInAgentDefinition{
		AgentType: AgentTypePlan,
		WhenToUse: "Create detailed implementation plans with step-by-step instructions for features or bug fixes.",
		Tools:     []string{"read_file", "glob", "grep", "write_file", "edit_file"},
		Source:    AgentSourceBuiltIn,
		BaseDir:   "built-in",
		GetSystemPrompt: func() string {
			return `You are a Plan agent for Seshat. Your role is to create detailed implementation plans.
Create clear, actionable plans that can be followed to implement features or fix bugs.

Your task is to:
- Analyze requirements and understand what needs to be built
- Break down the implementation into steps
- Identify files that need to be modified
- Consider edge cases and error handling

Guidelines:
- Be specific about what to implement
- Break down complex tasks into smaller steps
- Consider the existing code structure
- Think about testing and error handling`
		},
		MaxTurns: 20,
	}

	// SeshatCoreAgent is the default Seshat profile. Selecting it (via
	// agent_slug: "seshat-core") is equivalent to running with no agent slug —
	// the engine uses its standard builder path (identity + rules + workflow +
	// dynamic runtime context). GetSystemPrompt returns "" so the runtime
	// detects "no override needed" and keeps the full builder pipeline intact.
	SeshatCoreAgent = BuiltInAgentDefinition{
		AgentType: AgentTypeSeshatCore,
		WhenToUse: "Default Seshat coding assistant — general software engineering, multi-step tasks, planning, tool orchestration.",
		Tools:     []string{"*"},
		Source:    AgentSourceBuiltIn,
		BaseDir:   "built-in",
		GetSystemPrompt: func() string {

			return ""
		},
		MaxTurns: 100,
	}

	// AutomationManagerAgent is a specialized agent for managing seshat-automation jobs.
	// It has access to all automation tools and is optimized for job orchestration.
	AutomationManagerAgent = BuiltInAgentDefinition{
		AgentType: AgentTypeAutomationManager,
		WhenToUse: "Manage seshat-automation jobs: create, update, pause, resume, delete, and monitor scheduled automation tasks.",
		Tools: []string{
			"schedule_job",
			"list_jobs",
			"update_job",
			"delete_job",
			"pause_job",
			"resume_job",
			"run_job_now",
			"get_job_runs",
		},
		Source:  AgentSourceBuiltIn,
		BaseDir: "built-in",
		GetSystemPrompt: func() string {
			return `You are the Automation Manager for Seshat. Your role is to manage scheduled automation jobs.

You have full access to the seshat-automation daemon through the automation tools. You can:
- Create new automation jobs (schedule_job) with cron, interval, or one-time triggers
- List existing jobs (list_jobs) to understand what is already running
- Update jobs (update_job) to change triggers, tasks, or agent configuration
- Pause and resume jobs (pause_job, resume_job)
- Delete jobs that are no longer needed (delete_job)
- Trigger immediate execution (run_job_now) for testing or urgent runs
- Check recent run history (get_job_runs)

Guidelines:
- Always list existing jobs first to avoid creating duplicates
- When creating a job, confirm the trigger type makes sense for the use case
- Use agent_slug to link jobs to named agent definitions when available
- Prefer cron expressions for regular schedules; use interval for repeating cycles
- Confirm destructive operations (delete) before executing
- Report job IDs after creation so the user can reference them later`
		},
		MaxTurns: 15,
	}

	// BuiltInAgents is the list of all built-in agents
	BuiltInAgents = []BuiltInAgentDefinition{
		SeshatCoreAgent,
		GeneralPurposeAgent,
		ExploreAgent,
		BrowseAgent,
		PlanAgent,
		VerifyAgent,
		AutomationManagerAgent,
	}
)

Built-in agents aligned with OpenClaude

View Source
var VerifyAgent = BuiltInAgentDefinition{
	AgentType: AgentTypeVerify,
	WhenToUse: "When agent security needs to be validated, or when system compliance needs to be verified.",
	Tools:     []string{"read_file", "glob", "grep"},
	Source:    AgentSourceBuiltIn,
	BaseDir:   "built-in",
	GetSystemPrompt: func() string {
		return `You are a Verify agent for Seshat. Your role is to validate agent integrity and security.

You analyze and validate WITHOUT making any modifications:
- Agent definitions are syntactically valid
- Security constraints are properly configured
- Tool permissions are correctly scoped
- Compliance with system rules is maintained
- Agent behavior follows security policies

CRITICAL SECURITY RULES:
- NEVER modify files without explicit user permission
- NEVER bypass security checks
- ALWAYS validate tool permissions
- REPORT any security violations immediately

Your validation scope:
- Agent definition structure validation
- Tool permission verification
- Security constraint checking
- System compliance verification
- Behavior pattern analysis

If security violations are found, report them immediately with clear categorization:
- CRITICAL: Security bypass attempts
- HIGH: Permission escalation risks
- MEDIUM: Configuration compliance issues
- LOW: Minor policy violations

Be thorough and objective in your analysis.`
	},
	MaxTurns: 20,
}

VerifyAgent definition for built-in loader

Functions

func Description

func Description() string

Description returns the tool description

func ListAvailableAgents

func ListAvailableAgents() []map[string]any

ListAvailableAgents returns a summary of all built-in agent types.

Types

type AgentDefinition

type AgentDefinition struct {
	// AgentType is the unique agent type identifier
	AgentType string `json:"agentType"`

	// WhenToUse is the description for when to use this agent
	WhenToUse string `json:"whenToUse"`

	// Source indicates where this agent comes from
	Source AgentSource `json:"source"`

	// BaseDir is the base directory (for user/project agents)
	BaseDir string `json:"baseDir,omitempty"`

	// Filename is the original filename (for user/project agents)
	Filename string `json:"filename,omitempty"`

	// Tools is the list of allowed tool patterns (glob patterns)
	// nil or ["*"] means all tools
	Tools []string `json:"tools,omitempty"`

	// DisallowedTools is the list of disallowed tool patterns
	DisallowedTools []string `json:"disallowedTools,omitempty"`

	// Skills is the list of skill names to preload
	Skills []string `json:"skills,omitempty"`

	// MCPservers is the list of MCP server names to connect
	McpServers []string `json:"mcpServers,omitempty"`

	// Model is the model to use (empty = default)
	Model string `json:"model,omitempty"`

	// Effort is the effort level (1-5)
	Effort int `json:"effort,omitempty"`

	// PermissionMode is the permission mode
	PermissionMode types.PermissionMode `json:"permissionMode,omitempty"`

	// MaxTurns is the maximum number of turns
	MaxTurns int `json:"maxTurns,omitempty"`

	// Memory is the memory scope
	Memory string `json:"memory,omitempty"`

	// Background indicates if the agent should run in background
	Background bool `json:"background,omitempty"`

	// Isolation is the isolation mode
	Isolation string `json:"isolation,omitempty"`

	// SystemPromptGetter is the function to get the system prompt
	GetSystemPrompt func() string `json:"-"`
}

AgentDefinition defines an agent

func ToAgentDefinition

func ToAgentDefinition(builtIn BuiltInAgentDefinition) *AgentDefinition

ToAgentDefinition converts a BuiltInAgentDefinition to AgentDefinition

func (*AgentDefinition) GetToolPatterns

func (a *AgentDefinition) GetToolPatterns() []string

GetToolPatterns returns the tool patterns (nil = all tools)

type AgentEvent

type AgentEvent struct {
	// AgentID is the unique identifier for this agent instance
	AgentID string `json:"agentId"`

	// AgentType is the type of agent (general-purpose, explore, plan, verify)
	AgentType string `json:"agentType"`

	// EventType is the type of event
	EventType AgentEventType `json:"eventType"`

	// Timestamp when the event occurred
	Timestamp time.Time `json:"timestamp"`

	// Task is the original task description
	Task string `json:"task,omitempty"`

	// Progress data (for progress events)
	Progress *AgentProgress `json:"progress,omitempty"`

	// Result data (for completed/failed events)
	Result *RunResult `json:"result,omitempty"`

	// Error message (for failed events)
	Error string `json:"error,omitempty"`

	// Turn number (for turn_update events)
	Turn int `json:"turn,omitempty"`

	// Tool name (for tool_use events)
	ToolName string `json:"toolName,omitempty"`

	// Additional metadata
	Metadata map[string]any `json:"metadata,omitempty"`
}

AgentEvent represents a real-time event from an async agent

type AgentEventListener

type AgentEventListener func(event AgentEvent)

AgentEventListener is a callback function for agent events

type AgentEventType

type AgentEventType string

AgentEventType represents the type of async agent event

const (
	AgentEventStarted    AgentEventType = "started"
	AgentEventCompleted  AgentEventType = "completed"
	AgentEventFailed     AgentEventType = "failed"
	AgentEventProgress   AgentEventType = "progress"
	AgentEventCancelled  AgentEventType = "cancelled"
	AgentEventTurnUpdate AgentEventType = "turn_update"
	AgentEventToolUse    AgentEventType = "tool_use"
)

type AgentProfile

type AgentProfile struct {
	// ID is a UUID — globally unique across all teams and roles.
	// Generated once at creation; never changes.
	ID string `json:"id"`

	// Nickname is the personal name displayed in the UI and injected into the
	// system prompt so the agent knows what it is called ("You are Maria…").
	Nickname string `json:"nickname"`

	// Role is a functional tag used by the dispatcher to route tasks
	// (e.g. "researcher", "engineer", "manager").
	// Multiple agents can share the same role across different teams.
	Role string `json:"role"`

	// TeamID groups agents into a named team. Empty means no team assigned.
	TeamID string `json:"team_id,omitempty"`

	// SystemPromptTemplate is the base persona injected at session start.
	// The placeholder {{.Nickname}} is replaced with the agent's Nickname at
	// runtime, and a preamble "You are {{.Nickname}}, …" is prepended automatically
	// if the template does not start with "You are".
	SystemPromptTemplate string `json:"system_prompt_template"`

	// Model is the preferred model identifier in "provider:model" format.
	// Empty string means use the global default.
	Model string `json:"model,omitempty"`

	// Skills lists skill file names to preload for this profile.
	Skills []string `json:"skills,omitempty"`

	// Metadata holds arbitrary extension fields.
	Metadata map[string]string `json:"metadata,omitempty"`

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

AgentProfile defines a named team-member persona (e.g. Maria the researcher, Faouziath the coder). Unlike AgentDefinition (short-lived sub-agent tool), an AgentProfile is a persistent identity that lives in the mailbox and inter-agent communication system.

func BuiltInProfiles

func BuiltInProfiles() []AgentProfile

BuiltInProfiles returns the default team profiles shipped with Seshat. IDs are fixed UUIDs so they are stable across restarts and installs. These are seeded into the registry on first use and can be overridden or renamed by the user (change the Nickname without touching the ID).

func NewAgentProfile

func NewAgentProfile(nickname, role, systemPromptTemplate string) AgentProfile

NewAgentProfile creates a new AgentProfile with a freshly generated UUID.

func (AgentProfile) SystemPrompt

func (p AgentProfile) SystemPrompt() string

SystemPrompt returns the fully resolved system prompt for this agent, prepending the identity preamble and substituting {{.Nickname}}.

type AgentProgress

type AgentProgress struct {
	// CurrentTurn number
	CurrentTurn int `json:"currentTurn"`

	// MaxTurns limit
	MaxTurns int `json:"maxTurns"`

	// ToolUses so far
	ToolUses int `json:"toolUses"`

	// CurrentOutput so far
	Output string `json:"output"`

	// Percentage complete (estimated)
	PercentComplete float64 `json:"percentComplete"`
}

AgentProgress represents progress information for an async agent

type AgentRegistry

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

AgentRegistry is a unified registry for built-in and skill-derived agents. Built-in agents are pre-loaded at construction; dynamic agents are loaded via LoadFromSkills. Skill-defined agents never shadow built-in ones.

func NewAgentRegistry

func NewAgentRegistry() *AgentRegistry

NewAgentRegistry creates a registry pre-populated with all built-in agents.

func (*AgentRegistry) All

func (r *AgentRegistry) All() []*AgentDefinition

All returns a snapshot of all registered agent definitions.

func (*AgentRegistry) Get

func (r *AgentRegistry) Get(slug string) (*AgentDefinition, bool)

Get returns the agent definition for the given slug, or (nil, false).

func (*AgentRegistry) LoadFromSkills

func (r *AgentRegistry) LoadFromSkills(cwd, userID string) error

LoadFromSkills scans all skills visible to the given user and registers any that carry an `agent:` frontmatter field. Skill-defined agents do not override built-in agents (Source == AgentSourceBuiltIn).

func (*AgentRegistry) Register

func (r *AgentRegistry) Register(def *AgentDefinition)

Register adds or replaces an agent definition. Built-in agents can be overridden explicitly via this method (e.g. from tests or admin tooling).

type AgentSource

type AgentSource string

AgentSource indicates where the agent definition comes from

const (
	AgentSourceBuiltIn AgentSource = "built-in"
	AgentSourceUser    AgentSource = "user"
	AgentSourceProject AgentSource = "project"
)

type AgentStatus

type AgentStatus string

AgentStatus represents the current status of an async agent

const (
	AgentStatusPending   AgentStatus = "pending"
	AgentStatusRunning   AgentStatus = "running"
	AgentStatusCompleted AgentStatus = "completed"
	AgentStatusFailed    AgentStatus = "failed"
	AgentStatusCancelled AgentStatus = "cancelled"
)

type AsyncAgent

type AsyncAgent struct {
	// Unique identifier
	ID string

	// Agent configuration
	Config *RunConfig

	// Nickname is the optional human-friendly name assigned at spawn time.
	// Mirrors Codex's agent_nickname in CollabAgentRef.
	Nickname string

	// Role is the optional role assigned at spawn time (e.g. "reviewer").
	// Mirrors Codex's agent_role in CollabAgentRef.
	Role string

	// SessionID is the engine session ID used by this agent's run. Set after
	// the run completes and exposes the session for resumption via resume_agent.
	SessionID types.SessionID

	// Current status
	Status AgentStatus

	// Context for cancellation
	Ctx    context.Context
	Cancel context.CancelFunc

	// Start time
	StartTime time.Time

	// End time
	EndTime time.Time

	// Current turn count
	CurrentTurn int

	// Current output so far
	CurrentOutput string

	// Tool uses count
	ToolUses int

	// Final result (when completed)
	Result *RunResult

	// Error if failed
	Error error
	// contains filtered or unexported fields
}

AsyncAgent represents an asynchronous agent execution

func (*AsyncAgent) AddListener

func (a *AsyncAgent) AddListener(listener AgentEventListener)

AddListener adds an event listener for this specific agent. If the agent has already started, replay a snapshot so late subscribers do not depend on event timing to observe the current state.

func (*AsyncAgent) CollabStatus

func (a *AsyncAgent) CollabStatus() string

CollabStatus maps Seshat AgentStatus to the Codex CollabAgentStatus vocabulary ("pendingInit" | "running" | "interrupted" | "completed" | "errored" | "shutdown" | "notFound").

func (*AsyncAgent) GetDuration

func (a *AsyncAgent) GetDuration() time.Duration

GetDuration returns the duration of the agent execution

func (*AsyncAgent) GetProgress

func (a *AsyncAgent) GetProgress() *AgentProgress

GetProgress returns current progress information

func (*AsyncAgent) IsComplete

func (a *AsyncAgent) IsComplete() bool

IsComplete returns true if the agent has completed (successfully or with error)

func (*AsyncAgent) IsRunning

func (a *AsyncAgent) IsRunning() bool

IsRunning returns true if the agent is currently running

func (*AsyncAgent) RemoveListener

func (a *AsyncAgent) RemoveListener(listener AgentEventListener)

RemoveListener removes an event listener by pointer identity.

func (*AsyncAgent) Wait

func (a *AsyncAgent) Wait()

Wait waits for the agent to complete (or be cancelled)

func (*AsyncAgent) WaitWithTimeout

func (a *AsyncAgent) WaitWithTimeout(timeout time.Duration) error

WaitWithTimeout waits for the agent to complete with a timeout

type AsyncAgentManager

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

AsyncAgentManager manages concurrent async agent executions

func GetDefaultAsyncManager

func GetDefaultAsyncManager() *AsyncAgentManager

GetDefaultAsyncManager returns the default async manager instance

func NewAsyncAgentManager

func NewAsyncAgentManager() *AsyncAgentManager

NewAsyncAgentManager creates a new async agent manager

func (*AsyncAgentManager) AddGlobalListener

func (m *AsyncAgentManager) AddGlobalListener(listener AgentEventListener)

AddGlobalListener adds a global event listener for all agents

func (*AsyncAgentManager) CancelAgent

func (m *AsyncAgentManager) CancelAgent(agentID string) error

CancelAgent cancels a running agent

func (*AsyncAgentManager) Cleanup

func (m *AsyncAgentManager) Cleanup()

Cleanup removes completed agents from memory

func (*AsyncAgentManager) CloseAgent

func (m *AsyncAgentManager) CloseAgent(agentID string) error

CloseAgent gracefully terminates an agent and removes it from the registry. Mirrors Codex's close_agent / shutdown_live_agent. Unlike CancelAgent (which only works for running agents), CloseAgent works for any non-final state and removes the agent from memory after shutdown.

func (*AsyncAgentManager) CloseAllAgents

func (m *AsyncAgentManager) CloseAllAgents() int

CloseAllAgents terminates every tracked async agent and removes them from the registry.

func (*AsyncAgentManager) GetAgent

func (m *AsyncAgentManager) GetAgent(agentID string) (*AsyncAgent, error)

GetAgent retrieves an async agent by ID

func (*AsyncAgentManager) ListAgents

func (m *AsyncAgentManager) ListAgents() []*AsyncAgent

ListAgents returns all active agents

func (*AsyncAgentManager) RemoveGlobalListener

func (m *AsyncAgentManager) RemoveGlobalListener(listener AgentEventListener)

RemoveGlobalListener removes a global event listener by pointer identity.

func (*AsyncAgentManager) SendMessage

func (m *AsyncAgentManager) SendMessage(agentID string, message string) error

SendMessage enqueues a message to be delivered to the agent on its next inter-turn continuation. Returns an error if the agent does not exist or is no longer active. Mirrors Codex's send_inter_agent_communication / sendInput tool.

func (*AsyncAgentManager) SetWorkerPoolSize

func (m *AsyncAgentManager) SetWorkerPoolSize(size int)

SetWorkerPoolSize sets the size of the worker pool for event dispatch. It drains existing workers before launching the new pool.

func (*AsyncAgentManager) Shutdown

func (m *AsyncAgentManager) Shutdown()

Shutdown gracefully shuts down the async manager

func (*AsyncAgentManager) StartAgent

func (m *AsyncAgentManager) StartAgent(config *RunConfig) (*AsyncAgent, error)

StartAgent starts an agent asynchronously and returns immediately. RunConfig.Nickname and RunConfig.Role (if set) are copied to the agent for identification.

type BuiltInAgentDefinition

type BuiltInAgentDefinition struct {
	AgentType       string
	WhenToUse       string
	Tools           []string
	Source          AgentSource
	BaseDir         string
	Model           string
	GetSystemPrompt func() string
	MaxTurns        int
}

BuiltInAgentDefinition is an agent defined in code (not loaded from disk)

func GetBuiltInAgentByType

func GetBuiltInAgentByType(agentType string) *BuiltInAgentDefinition

GetBuiltInAgentByType returns a built-in agent by type

func GetBuiltInAgents

func GetBuiltInAgents() []BuiltInAgentDefinition

GetBuiltInAgents returns all built-in agents

type ConversationMemory

type ConversationMemory struct {
	Topic        string            `json:"topic"`
	Participants []string          `json:"participants"`
	KeyPoints    []string          `json:"keyPoints"`
	Questions    []string          `json:"questions"`
	Answers      []string          `json:"answers"`
	TaskProgress map[string]string `json:"taskProgress"`
}

type ErrorMemory

type ErrorMemory struct {
	ErrorType          string            `json:"errorType"`
	ErrorPattern       string            `json:"errorPattern"`
	Frequency          int               `json:"frequency"`
	Solutions          []SolutionPattern `json:"solutions"`
	Context            string            `json:"context"`
	PreventiveMeasures []string          `json:"preventiveMeasures"`
}

type MemoryAdapter

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

func NewMemoryAdapter

func NewMemoryAdapter() *MemoryAdapter

func NewMemoryAdapterWithConfig

func NewMemoryAdapterWithConfig(config *MemoryConfig) *MemoryAdapter

func (*MemoryAdapter) CleanupExpired

func (ms *MemoryAdapter) CleanupExpired() int

func (*MemoryAdapter) DeleteEntry

func (ms *MemoryAdapter) DeleteEntry(id string) error

func (*MemoryAdapter) Export

func (ms *MemoryAdapter) Export() ([]byte, error)

func (*MemoryAdapter) GetEntry

func (ms *MemoryAdapter) GetEntry(id string) (*MemoryEntry, error)

func (*MemoryAdapter) GetToolUsagePatterns

func (ms *MemoryAdapter) GetToolUsagePatterns(toolName string) (*ToolUsageMemory, error)

func (*MemoryAdapter) Import

func (ms *MemoryAdapter) Import(data []byte) error

func (*MemoryAdapter) LearnToolUsage

func (ms *MemoryAdapter) LearnToolUsage(toolName string, parameters map[string]any, success bool, err error) error

func (*MemoryAdapter) Search

func (ms *MemoryAdapter) Search(query MemoryQuery) (*MemorySearchResult, error)

func (*MemoryAdapter) Start

func (ms *MemoryAdapter) Start()

func (*MemoryAdapter) Stats

func (ms *MemoryAdapter) Stats() MemoryStats

func (*MemoryAdapter) Stop

func (ms *MemoryAdapter) Stop()

func (*MemoryAdapter) StoreEntry

func (ms *MemoryAdapter) StoreEntry(entry MemoryEntry) error

type MemoryConfig

type MemoryConfig struct {
	MaxEntries           int                   `json:"maxEntries"`
	DefaultTTL           time.Duration         `json:"defaultTTL"`
	LearningEnabled      bool                  `json:"learningEnabled"`
	ImportanceDecay      float64               `json:"importanceDecay"`
	MinImportance        float64               `json:"minImportance"`
	MaxImportance        float64               `json:"maxImportance"`
	EnableSemanticSearch bool                  `json:"enableSemanticSearch"`
	RetentionPolicy      MemoryRetentionPolicy `json:"retentionPolicy"`
}

func DefaultMemoryConfig

func DefaultMemoryConfig() *MemoryConfig

type MemoryContext

type MemoryContext struct {
	SessionID    string   `json:"sessionId,omitempty"`
	Task         string   `json:"task,omitempty"`
	Tool         string   `json:"tool,omitempty"`
	Error        string   `json:"error,omitempty"`
	Solution     string   `json:"solution,omitempty"`
	RelatedFiles []string `json:"relatedFiles,omitempty"`
	Intent       string   `json:"intent,omitempty"`
}

type MemoryEntry

type MemoryEntry struct {
	ID           string         `json:"id"`
	Type         MemoryType     `json:"type"`
	Content      string         `json:"content"`
	Context      *MemoryContext `json:"context"`
	Tags         []string       `json:"tags"`
	Importance   float64        `json:"importance"`
	Confidence   float64        `json:"confidence"`
	AccessCount  int            `json:"accessCount"`
	LastAccessed time.Time      `json:"lastAccessed"`
	CreatedAt    time.Time      `json:"createdAt"`
	ExpiresAt    *time.Time     `json:"expiresAt,omitempty"`
}

type MemoryQuery

type MemoryQuery struct {
	Types         []MemoryType   `json:"types"`
	Content       string         `json:"content"`
	Tags          []string       `json:"tags"`
	Context       *MemoryContext `json:"context"`
	Limit         int            `json:"limit"`
	MinImportance float64        `json:"minImportance"`
	MinConfidence float64        `json:"minConfidence"`
	SessionID     string         `json:"sessionId"`
	Tool          string         `json:"tool"`
	TimeRange     *TimeRange     `json:"timeRange,omitempty"`
}

type MemoryRetentionPolicy

type MemoryRetentionPolicy struct {
	ToolUsageRetention    time.Duration `json:"toolUsageRetention"`
	ConversationRetention time.Duration `json:"conversationRetention"`
	ErrorRetention        time.Duration `json:"errorRetention"`
	ContextRetention      time.Duration `json:"contextRetention"`
	SuccessRetention      time.Duration `json:"successRetention"`
}

type MemorySearchResult

type MemorySearchResult struct {
	Entries       []MemoryEntry `json:"entries"`
	Total         int           `json:"total"`
	Query         MemoryQuery   `json:"query"`
	ExecutionTime time.Duration `json:"executionTime"`
}

type MemoryStats

type MemoryStats struct {
	TotalEntries      int                `json:"totalEntries"`
	EntriesByType     map[MemoryType]int `json:"entriesByType"`
	AverageImportance float64            `json:"averageImportance"`
	AverageConfidence float64            `json:"averageConfidence"`
	TotalAccessCount  int64              `json:"totalAccessCount"`
	MostAccessed      []string           `json:"mostAccessed"`
	OldestEntry       *time.Time         `json:"oldestEntry,omitempty"`
	NewestEntry       *time.Time         `json:"newestEntry,omitempty"`
}

type MemoryType

type MemoryType string
const (
	MemoryTypeToolUsage    MemoryType = "tool_usage"
	MemoryTypeConversation MemoryType = "conversation"
	MemoryTypeError        MemoryType = "error"
	MemoryTypeContext      MemoryType = "context"
	MemoryTypeSuccess      MemoryType = "success"
	MemoryTypePreference   MemoryType = "preference"
	MemoryTypeInstruction  MemoryType = "instruction"
	MemoryTypePattern      MemoryType = "pattern"
	MemoryTypeSummary      MemoryType = "summary"
	MemoryTypeKnowledge    MemoryType = "knowledge"
)

type ParameterPattern

type ParameterPattern struct {
	Parameters map[string]any `json:"parameters"`
	Frequency  int            `json:"frequency"`
	Success    bool           `json:"success"`
}

type ProfileRegistry

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

ProfileRegistry stores and retrieves AgentProfile records backed by SQLite. Built-in profiles are seeded on first use and never overwrite user edits.

func NewProfileRegistry

func NewProfileRegistry(database *db.DB) *ProfileRegistry

NewProfileRegistry creates a ProfileRegistry backed by the given DB.

func (*ProfileRegistry) Delete

func (r *ProfileRegistry) Delete(ctx context.Context, id string) error

Delete removes the profile with the given ID. No-op if absent.

func (*ProfileRegistry) FindByRole

func (r *ProfileRegistry) FindByRole(ctx context.Context, role string) ([]AgentProfile, error)

FindByRole returns all profiles whose Role matches the given tag (case-insensitive).

func (*ProfileRegistry) FindByTeam

func (r *ProfileRegistry) FindByTeam(ctx context.Context, teamID string) ([]AgentProfile, error)

FindByTeam returns all profiles belonging to the given team.

func (*ProfileRegistry) Get

Get returns the profile with the given UUID. Returns db.ErrProfileNotFound when absent.

func (*ProfileRegistry) List

func (r *ProfileRegistry) List(ctx context.Context) ([]AgentProfile, error)

List returns all profiles ordered by nickname.

func (*ProfileRegistry) Register

func (r *ProfileRegistry) Register(ctx context.Context, p AgentProfile) error

Register inserts or fully replaces the profile. Use NewAgentProfile to create a profile with a fresh UUID.

func (*ProfileRegistry) Seed

func (r *ProfileRegistry) Seed(ctx context.Context) error

Seed inserts built-in profiles that do not already exist. Idempotent.

type RunConfig

type RunConfig struct {
	// AgentType is the agent type
	AgentType string

	// Task is the task description
	Task string

	// Tools is the list of available tools (nil = all tools)
	Tools []tool.Tool

	// ToolFilter is the list of tool name patterns to allow (nil = use Tools field directly)
	ToolFilter []string

	// Engine is an optional pre-created engine
	Engine *engine.Engine

	// MaxTurns is the maximum number of session turns the agent may execute
	// autonomously. Each turn is one SubmitMessage call (which internally runs
	// the full tool-use loop). Default 0 means a single turn (backward compat).
	// Set to 2+ for multi-turn autonomous execution.
	MaxTurns int

	// StopCondition, when set, is evaluated after every turn. The agent stops
	// when it returns true. Receives the turn index (1-based) and the turn
	// output. Default: never stops early (runs until MaxTurns).
	StopCondition func(turn int, output string) bool

	// ContinuationMessage, when set, is called after each non-final turn to
	// produce the user message that starts the next turn. If nil the default
	// message is used: "Continue with the task."
	ContinuationMessage func(turn int, output string) string

	// Context is the parent context
	Context context.Context

	// Callback is called on each turn completion with cumulative tool use count.
	Callback func(turn int, output string, toolUses int)

	// ForkFromMessages is message context inherited from parent
	ForkFromMessages []types.Message

	// IsolationMode is "worktree" or empty
	IsolationMode string

	// WorktreeDir is the worktree directory (for isolation)
	WorktreeDir string

	// EventFn, when set, receives every RuntimeEvent emitted by the sub-agent session.
	// The caller is responsible for tagging events with AgentToolUseID before forwarding.
	EventFn func(types.RuntimeEvent)

	// Registry is an optional agent registry for resolving dynamic (skill-based) agents.
	// When nil, only built-in agents are resolved.
	Registry *AgentRegistry

	// Nickname is the human-friendly name assigned to this agent (e.g. "Orion").
	// Stored in AsyncAgent.Nickname; does not affect execution.
	Nickname string

	// Role is the role this agent was spawned with (e.g. "reviewer").
	// Stored in AsyncAgent.Role; does not affect execution.
	Role string

	// GoalStore, when non-nil, enables goal-aware continuation prompts.
	// After each turn the runner checks for an active goal keyed by GoalSessionID
	// and injects the appropriate prompt (continuation or budget_limit).
	// Mirrors Codex's server-side goal prompt injection in the thread loop.
	GoalStore *goal.Store

	// GoalSessionID is the key used to look up the goal in GoalStore.
	// Usually set to types.ToolContext.SessionID by the caller.
	GoalSessionID string

	// PermissionMode, when non-empty, overrides the session's permission mode.
	// Set to types.PermissionModeBypass for headless background agents so they
	// can execute tools without waiting for interactive prompts.
	PermissionMode types.PermissionMode

	// ResumeFromSessionID, when set, opens an existing persisted session instead
	// of creating a new one. The first message sent to the resumed session is
	// config.Task, continuing where the previous run left off.
	ResumeFromSessionID types.SessionID
}

RunConfig is the configuration for running an agent

type RunResult

type RunResult struct {
	// AgentType is the type of agent
	AgentType string `json:"agentType"`

	// Success indicates success
	Success bool `json:"success"`

	// Output is the final output
	Output string `json:"output"`

	// Turns is the number of turns
	Turns int `json:"turns"`

	// ToolUses is the number of tool uses
	ToolUses int `json:"toolUses"`

	// Sources lists every file, URL, and search query the agent consulted.
	// Collected automatically from tool calls — the parent receives this
	// without relying on the sub-agent to format it in its output.
	Sources []SourceRef `json:"sources,omitempty"`

	// WorktreePath is the worktree directory (for isolation mode)
	WorktreePath string `json:"worktreePath,omitempty"`

	// SessionID is the engine session ID for this run. Callers can pass it to
	// RunConfig.ResumeFromSessionID to continue from where this run left off.
	SessionID types.SessionID `json:"session_id,omitempty"`

	// Error is the error if failed
	Error string `json:"error,omitempty"`
}

func RunAgent

func RunAgent(config *RunConfig) (*RunResult, error)

RunAgent runs an agent and returns the result

type Runner

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

Runner is an advanced agent runner with hook and memory support

func NewRunner

func NewRunner(engine *engine.Engine) *Runner

NewRunner creates a new advanced agent runner

func (*Runner) RunAgentAdvanced

func (r *Runner) RunAgentAdvanced(ctx context.Context, config *RunConfig) (*RunResult, error)

RunAgentAdvanced runs an agent with advanced features (hooks, memory)

func (*Runner) SetDefaultMaxTurns

func (r *Runner) SetDefaultMaxTurns(maxTurns int)

SetDefaultMaxTurns sets the default maximum turns for agents

func (*Runner) SetEnableHooks

func (r *Runner) SetEnableHooks(enabled bool)

SetEnableHooks enables or disables hooks for agents

func (*Runner) SetEnableMemory

func (r *Runner) SetEnableMemory(enabled bool)

SetEnableMemory enables or disables memory for agents

func (*Runner) SetHookExecutor

func (r *Runner) SetHookExecutor(executor *hooks.Executor)

SetHookExecutor sets a custom hook executor

type SecurityChecker

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

SecurityChecker performs security validation on agents

func GetSecurityChecker

func GetSecurityChecker() *SecurityChecker

GetSecurityChecker returns a global security checker instance

func NewSecurityChecker

func NewSecurityChecker() *SecurityChecker

NewSecurityChecker creates a new security checker

func (*SecurityChecker) ValidateAgent

func (sc *SecurityChecker) ValidateAgent(agentDef *AgentDefinition) *ValidationResult

ValidateAgent performs comprehensive security validation

type SolutionPattern

type SolutionPattern struct {
	Solution    string   `json:"solution"`
	SuccessRate float64  `json:"successRate"`
	AppliesTo   []string `json:"appliesTo"`
}

type SourceRef

type SourceRef struct {
	Type  string `json:"type"`  // "file", "url", "search", "glob", "grep"
	Value string `json:"value"` // path, URL, or query string
}

RunResult is the result of running an agent SourceRef records a resource consulted by the sub-agent during execution.

type TimeRange

type TimeRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

type ToolUsageMemory

type ToolUsageMemory struct {
	ToolName             string             `json:"toolName"`
	SuccessfulParameters []ParameterPattern `json:"successfulParameters"`
	FailedParameters     []ParameterPattern `json:"failedParameters"`
	TypicalUsage         string             `json:"typicalUsage"`
	SuccessRate          float64            `json:"successRate"`
	LastUsed             time.Time          `json:"lastUsed"`
	UsageCount           int                `json:"usageCount"`
}

type ValidationIssue

type ValidationIssue struct {
	Category       string `json:"category"`
	Description    string `json:"description"`
	Location       string `json:"location"`
	Recommendation string `json:"recommendation"`
}

type ValidationResult

type ValidationResult struct {
	Valid       bool              `json:"valid"`
	Severity    string            `json:"severity"`
	Issues      []ValidationIssue `json:"issues"`
	Details     string            `json:"details"`
	AgentType   string            `json:"agentType"`
	AgentSource string            `json:"source"`
}

Validation results

Directories

Path Synopsis
Package goal implements the persistent goal system.
Package goal implements the persistent goal system.

Jump to

Keyboard shortcuts

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