agent

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 17, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultLineLimits = map[string]int{
	"shell": 256,
	"grep":  200,
	"glob":  500,
}

DefaultLineLimits maps tool names to their default line-count limits. A value of 0 means unlimited (no line-based truncation).

Functions

func BuildEnvironmentBlock

func BuildEnvironmentBlock(env ExecutionEnvironment, modelName string, knowledgeCutoff string) string

BuildEnvironmentBlock builds a complete <environment> block including git context. This is the enhanced version that includes git info, model name, and knowledge cutoff.

func BuildFullSystemPrompt

func BuildFullSystemPrompt(profile ProviderProfile, env ExecutionEnvironment, userOverride string) string

BuildFullSystemPrompt assembles the complete 5-layer system prompt. It takes the profile's base prompt and enhances it with git context, tool descriptions, filtered project docs, and user overrides.

The 5 layers are:

  1. Provider-specific base instructions (from profile.BuildSystemPrompt)
  2. Environment context with git info, model name, and knowledge cutoff
  3. Tool descriptions from the registry
  4. Project-specific instructions (filtered by provider)
  5. User instructions override

func BuildGitContext

func BuildGitContext(env ExecutionEnvironment) string

BuildGitContext returns a git context block with branch, is_repo flag, status summary, and recent commits. Uses the ExecutionEnvironment to run git commands. Returns empty string if not in a git repo.

func BuildToolDescriptions

func BuildToolDescriptions(registry *ToolRegistry) string

BuildToolDescriptions returns a formatted summary of available tools for the system prompt.

func ConvertHistoryToMessages

func ConvertHistoryToMessages(history []Turn) []llm.Message

ConvertHistoryToMessages converts a slice of Turn values into LLM messages suitable for sending to a language model.

func DetectLoop

func DetectLoop(history []Turn, windowSize int) bool

DetectLoop checks whether the recent tool call history contains a repeating pattern of length 1, 2, or 3. It extracts tool call signatures (name + args hash) from the last windowSize assistant turns that contain tool calls.

func DiscoverProjectDocs

func DiscoverProjectDocs(env ExecutionEnvironment) []string

DiscoverProjectDocs searches the working directory for recognized project documentation files and returns their contents. Recognized files: CLAUDE.md, README.md, .cursorrules, GEMINI.md, AGENTS.md.

func DiscoverProjectDocsWalk

func DiscoverProjectDocsWalk(env ExecutionEnvironment) map[string]string

DiscoverProjectDocsWalk searches from gitRoot (or working directory) down to cwd, collecting recognized instruction files at each level. Deeper files have higher precedence. Returns a map of filename->content for all discovered files.

func ExtractToolCallSignatures

func ExtractToolCallSignatures(history []Turn, count int) []string

ExtractToolCallSignatures extracts the last `count` tool call signatures from the history. A signature is "name:sha256(arguments)" for each tool call found in AssistantTurn entries.

func FilterProjectDocs

func FilterProjectDocs(docs map[string]string, providerID string) []string

FilterProjectDocs filters discovered project docs based on the provider profile ID. AGENTS.md is always included. Provider-specific files: - "openai": includes .codex/instructions.md - "anthropic": includes CLAUDE.md - "gemini": includes GEMINI.md All providers include README.md and .cursorrules. Applies 32KB total byte budget with truncation marker.

func ProcessInput

func ProcessInput(ctx context.Context, session *Session, profile ProviderProfile, env ExecutionEnvironment, client *llm.Client, userInput string) error

ProcessInput runs the core agentic loop: it appends the user input to the session, calls the LLM, executes any tool calls, and loops until the model produces a text-only response, a limit is hit, or the context is cancelled.

func RegisterCoreTools

func RegisterCoreTools(registry *ToolRegistry)

RegisterCoreTools registers all shared core tools with the given registry.

func RegisterSubAgentTools

func RegisterSubAgentTools(registry *ToolRegistry, manager *SubAgentManager, profile ProviderProfile, client *llm.Client)

RegisterSubAgentTools registers all 4 subagent tools on the given registry.

func TruncateLines

func TruncateLines(output string, maxLines int) string

TruncateLines truncates output that exceeds maxLines using a head/tail split. If maxLines is 0 or the output has fewer lines than maxLines, the output is returned unchanged. Otherwise the first half and last half of lines are kept with an omission marker in between.

func TruncateOutput

func TruncateOutput(output string, maxChars int, mode string) string

TruncateOutput truncates output that exceeds maxChars using the given mode. Supported modes: "head_tail" (keep first half + last half) and "tail" (keep last N chars). A truncation warning is inserted at the truncation point.

func TruncateToolOutput

func TruncateToolOutput(output, toolName string, limits map[string]int) string

TruncateToolOutput truncates tool output using per-tool defaults, optionally overridden by the limits map. Tools not found in defaults or overrides use defaultCharLimit with "tail" mode. Character truncation runs first, then line-based truncation is applied for tools that have a configured line limit.

Types

type AnthropicProfile

type AnthropicProfile struct {
	BaseProfile
}

AnthropicProfile is a ProviderProfile aligned to Claude Code conventions.

func NewAnthropicProfile

func NewAnthropicProfile(model string, opts ...ProfileOption) *AnthropicProfile

NewAnthropicProfile creates an Anthropic-aligned provider profile. If model is empty, defaults to "claude-sonnet-4-5".

func (*AnthropicProfile) BuildSystemPrompt

func (p *AnthropicProfile) BuildSystemPrompt(env ExecutionEnvironment, projectDocs []string) string

BuildSystemPrompt constructs the system prompt for Anthropic models, mirroring Claude Code conventions.

type AssistantTurn

type AssistantTurn struct {
	Content    string
	ToolCalls  []llm.ToolCallData
	Reasoning  string
	Usage      llm.Usage
	ResponseID string
	Timestamp  time.Time
}

AssistantTurn represents the model's response, optionally including tool calls.

func (AssistantTurn) TurnTimestamp

func (t AssistantTurn) TurnTimestamp() time.Time

func (AssistantTurn) TurnType

func (t AssistantTurn) TurnType() string

type BaseProfile

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

BaseProfile provides shared implementation for all provider profiles.

func (*BaseProfile) ContextWindowSize

func (b *BaseProfile) ContextWindowSize() int

func (*BaseProfile) ID

func (b *BaseProfile) ID() string

func (*BaseProfile) Model

func (b *BaseProfile) Model() string

func (*BaseProfile) ProviderOptions

func (b *BaseProfile) ProviderOptions() map[string]any

ProviderOptions returns provider-specific options for the LLM request.

func (*BaseProfile) SupportsParallelToolCalls

func (b *BaseProfile) SupportsParallelToolCalls() bool

func (*BaseProfile) SupportsReasoning

func (b *BaseProfile) SupportsReasoning() bool

func (*BaseProfile) SupportsStreaming

func (b *BaseProfile) SupportsStreaming() bool

func (*BaseProfile) ToolRegistry

func (b *BaseProfile) ToolRegistry() *ToolRegistry

func (*BaseProfile) Tools

func (b *BaseProfile) Tools() []llm.ToolDefinition

Tools returns all tool definitions from the profile's registry.

type DirEntry

type DirEntry struct {
	Name  string
	IsDir bool
	Size  int64
}

DirEntry represents a single entry when listing a directory.

type EnvPolicy

type EnvPolicy string

EnvPolicy controls how environment variables are inherited by child processes.

const (
	// EnvPolicyInheritCore inherits only safe environment variables (default).
	EnvPolicyInheritCore EnvPolicy = "inherit_core"
	// EnvPolicyInheritAll inherits all environment variables without filtering.
	EnvPolicyInheritAll EnvPolicy = "inherit_all"
	// EnvPolicyInheritNone starts with a clean environment, only explicit vars.
	EnvPolicyInheritNone EnvPolicy = "inherit_none"
)

type EventEmitter

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

EventEmitter delivers session events to subscribed channels.

func NewEventEmitter

func NewEventEmitter() *EventEmitter

NewEventEmitter creates a new EventEmitter.

func (*EventEmitter) Close

func (e *EventEmitter) Close()

Close closes the emitter and all subscriber channels.

func (*EventEmitter) Emit

func (e *EventEmitter) Emit(event SessionEvent)

Emit sends an event to all subscribers. Non-blocking: if a subscriber's channel buffer is full, the event is dropped for that subscriber.

func (*EventEmitter) Subscribe

func (e *EventEmitter) Subscribe() <-chan SessionEvent

Subscribe registers a new subscriber channel and returns it. The channel has a buffer of 64 to reduce the likelihood of blocking.

func (*EventEmitter) Unsubscribe

func (e *EventEmitter) Unsubscribe(ch <-chan SessionEvent)

Unsubscribe removes a subscriber channel and closes it.

type EventKind

type EventKind string

EventKind discriminates the type of session event.

const (
	EventSessionStart        EventKind = "session_start"
	EventSessionEnd          EventKind = "session_end"
	EventUserInput           EventKind = "user_input"
	EventAssistantTextStart  EventKind = "assistant_text_start"
	EventAssistantTextDelta  EventKind = "assistant_text_delta"
	EventAssistantTextEnd    EventKind = "assistant_text_end"
	EventToolCallStart       EventKind = "tool_call_start"
	EventToolCallOutputDelta EventKind = "tool_call_output_delta"
	EventToolCallEnd         EventKind = "tool_call_end"
	EventSteeringInjected    EventKind = "steering_injected"
	EventTurnLimit           EventKind = "turn_limit"
	EventLoopDetection       EventKind = "loop_detection"
	EventError               EventKind = "error"
)

type ExecResult

type ExecResult struct {
	Stdout     string
	Stderr     string
	ExitCode   int
	TimedOut   bool
	DurationMs int
}

ExecResult holds the outcome of a command execution.

type ExecutionEnvironment

type ExecutionEnvironment interface {
	// ReadFile reads a file with line numbers prepended. Offset is 1-based.
	// If limit is 0, a default of 2000 lines is used.
	ReadFile(path string, offset, limit int) (string, error)

	// WriteFile writes content to a file, creating parent directories as needed.
	WriteFile(path string, content string) error

	// FileExists checks whether a file or directory exists at the given path.
	FileExists(path string) (bool, error)

	// ListDirectory returns entries in a directory, optionally recursing to the given depth.
	// A depth of 0 means only the immediate children. A depth of -1 means unlimited.
	ListDirectory(path string, depth int) ([]DirEntry, error)

	// ExecCommand runs a shell command with timeout and environment controls.
	// If workingDir is empty, the environment's working directory is used.
	ExecCommand(command string, timeoutMs int, workingDir string, envVars map[string]string) (*ExecResult, error)

	// Grep searches file contents by regex pattern. Path defaults to the working directory.
	Grep(pattern, path string, opts GrepOptions) (string, error)

	// Glob finds files matching a glob pattern. Path defaults to the working directory.
	Glob(pattern, path string) ([]string, error)

	// Initialize prepares the execution environment (e.g., verifies working directory).
	Initialize() error

	// Cleanup releases resources held by the execution environment.
	Cleanup() error

	// WorkingDirectory returns the root working directory for this environment.
	WorkingDirectory() string

	// Platform returns the OS identifier (e.g., "darwin", "linux", "windows").
	Platform() string

	// OSVersion returns the OS version string (e.g., kernel version from uname -r).
	OSVersion() string
}

ExecutionEnvironment abstracts all file, command, and search operations so that tools are decoupled from the runtime (local, Docker, K8s, WASM, SSH).

type GeminiProfile

type GeminiProfile struct {
	BaseProfile
}

GeminiProfile is a ProviderProfile aligned to gemini-cli conventions.

func NewGeminiProfile

func NewGeminiProfile(model string, opts ...ProfileOption) *GeminiProfile

NewGeminiProfile creates a Gemini-aligned provider profile. If model is empty, defaults to "gemini-3-flash-preview".

func (*GeminiProfile) BuildSystemPrompt

func (p *GeminiProfile) BuildSystemPrompt(env ExecutionEnvironment, projectDocs []string) string

BuildSystemPrompt constructs the system prompt for Gemini models, mirroring gemini-cli conventions.

type GrepOptions

type GrepOptions struct {
	GlobFilter      string
	CaseInsensitive bool
	MaxResults      int
}

GrepOptions configures the behavior of a grep search.

type Hunk

type Hunk struct {
	ContextHint  string   // Optional search hint from @@@ ... @@@ or @@ ... markers
	ContextLines []string // Lines prefixed with space (context for matching)
	DeleteLines  []string // Lines prefixed with - (to remove)
	AddLines     []string // Lines prefixed with + (to insert)
	MatchLines   []string // Context + delete lines in original order (for file matching)
	ReplaceLines []string // Context + add lines in original order (replacement content)
}

Hunk represents a single change region within an Update operation. It contains context lines for locating the change, lines to delete, and lines to add. MatchLines and ReplaceLines preserve the interleaved order of context and change lines, which is required for correct matching against the file.

type LocalExecOption

type LocalExecOption func(*LocalExecutionEnvironment)

LocalExecOption configures a LocalExecutionEnvironment.

func WithEnvPolicy

func WithEnvPolicy(policy EnvPolicy) LocalExecOption

WithEnvPolicy sets the environment variable inheritance policy.

type LocalExecutionEnvironment

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

LocalExecutionEnvironment implements ExecutionEnvironment for the local machine.

func NewLocalExecutionEnvironment

func NewLocalExecutionEnvironment(workDir string, opts ...LocalExecOption) *LocalExecutionEnvironment

NewLocalExecutionEnvironment creates a new local execution environment rooted at workDir.

func (*LocalExecutionEnvironment) Cleanup

func (e *LocalExecutionEnvironment) Cleanup() error

Cleanup is a no-op for the local environment (placeholder for future use).

func (*LocalExecutionEnvironment) ExecCommand

func (e *LocalExecutionEnvironment) ExecCommand(command string, timeoutMs int, workingDir string, envVars map[string]string) (*ExecResult, error)

ExecCommand runs a shell command with timeout enforcement and environment filtering.

func (*LocalExecutionEnvironment) FileExists

func (e *LocalExecutionEnvironment) FileExists(path string) (bool, error)

FileExists checks if a file or directory exists at the given path.

func (*LocalExecutionEnvironment) Glob

func (e *LocalExecutionEnvironment) Glob(pattern, path string) ([]string, error)

Glob finds files matching a glob pattern relative to the given path.

func (*LocalExecutionEnvironment) Grep

func (e *LocalExecutionEnvironment) Grep(pattern, path string, opts GrepOptions) (string, error)

Grep searches file contents by regex pattern.

func (*LocalExecutionEnvironment) Initialize

func (e *LocalExecutionEnvironment) Initialize() error

Initialize verifies the working directory exists, creating it if needed.

func (*LocalExecutionEnvironment) ListDirectory

func (e *LocalExecutionEnvironment) ListDirectory(path string, depth int) ([]DirEntry, error)

ListDirectory returns entries in a directory. Depth 0 means immediate children only.

func (*LocalExecutionEnvironment) OSVersion

func (e *LocalExecutionEnvironment) OSVersion() string

OSVersion returns the OS version string from uname -r.

func (*LocalExecutionEnvironment) Platform

func (e *LocalExecutionEnvironment) Platform() string

Platform returns the operating system identifier.

func (*LocalExecutionEnvironment) ReadFile

func (e *LocalExecutionEnvironment) ReadFile(path string, offset, limit int) (string, error)

ReadFile reads a file and prepends line numbers. Offset is 1-based; limit of 0 defaults to 2000.

func (*LocalExecutionEnvironment) WorkingDirectory

func (e *LocalExecutionEnvironment) WorkingDirectory() string

WorkingDirectory returns the configured root working directory.

func (*LocalExecutionEnvironment) WriteFile

func (e *LocalExecutionEnvironment) WriteFile(path string, content string) error

WriteFile writes content to a file, creating parent directories as needed.

type OpenAIProfile

type OpenAIProfile struct {
	BaseProfile
}

OpenAIProfile is a ProviderProfile aligned to OpenAI's codex-rs conventions.

func NewOpenAIProfile

func NewOpenAIProfile(model string, opts ...ProfileOption) *OpenAIProfile

NewOpenAIProfile creates an OpenAI-aligned provider profile. If model is empty, defaults to "gpt-5.2-codex".

func (*OpenAIProfile) BuildSystemPrompt

func (p *OpenAIProfile) BuildSystemPrompt(env ExecutionEnvironment, projectDocs []string) string

BuildSystemPrompt constructs the system prompt for OpenAI models, mirroring codex-rs conventions.

type Patch

type Patch struct {
	Operations []PatchOperation
}

Patch represents a parsed v4a format patch containing one or more file operations.

func ParsePatch

func ParsePatch(input string) (*Patch, error)

ParsePatch parses a v4a format patch string into a structured Patch. The parser is lenient with trailing whitespace but strict on the *** markers.

type PatchOpType

type PatchOpType string

PatchOpType identifies the kind of file operation in a patch.

const (
	PatchOpAdd    PatchOpType = "add"
	PatchOpDelete PatchOpType = "delete"
	PatchOpUpdate PatchOpType = "update"
	PatchOpMove   PatchOpType = "move"
)

type PatchOperation

type PatchOperation struct {
	Type    PatchOpType
	Path    string
	MoveTo  string   // Only used for Move operations
	Content []string // Only used for Add operations (lines without the + prefix)
	Hunks   []Hunk   // Only used for Update operations
}

PatchOperation represents a single file operation within a patch.

type PatchResult

type PatchResult struct {
	Summary       string
	FilesCreated  int
	FilesDeleted  int
	FilesModified int
	FilesMoved    int
	Details       []string
}

PatchResult holds the outcome of applying a patch.

func ApplyPatch

func ApplyPatch(patch *Patch, env ExecutionEnvironment) (*PatchResult, error)

ApplyPatch applies a parsed Patch to the filesystem via the ExecutionEnvironment.

type ProfileOption

type ProfileOption func(*BaseProfile)

ProfileOption configures a BaseProfile during construction.

func WithProfileModel

func WithProfileModel(model string) ProfileOption

WithProfileModel overrides the default model for a profile.

func WithProfileProviderOptions

func WithProfileProviderOptions(opts map[string]any) ProfileOption

WithProfileProviderOptions sets provider-specific options on the profile.

type ProviderProfile

type ProviderProfile interface {
	ID() string
	Model() string
	BuildSystemPrompt(env ExecutionEnvironment, projectDocs []string) string
	Tools() []llm.ToolDefinition
	ProviderOptions() map[string]any
	ToolRegistry() *ToolRegistry
	SupportsParallelToolCalls() bool
	SupportsReasoning() bool
	SupportsStreaming() bool
	ContextWindowSize() int
}

ProviderProfile defines the interface for provider-specific tool and prompt configurations. Each profile aligns its tools and system prompts to how the provider's models work best.

type RegisteredTool

type RegisteredTool struct {
	Definition  llm.ToolDefinition
	Execute     func(args map[string]any, env ExecutionEnvironment) (string, error)
	Description string
}

RegisteredTool pairs a tool definition with its execute function.

func NewApplyPatchTool

func NewApplyPatchTool() *RegisteredTool

NewApplyPatchTool creates a RegisteredTool for applying v4a format patches. The v4a format supports creating, deleting, updating, and moving files in a single operation.

func NewCloseAgentTool

func NewCloseAgentTool(manager *SubAgentManager) *RegisteredTool

NewCloseAgentTool creates the close_agent tool.

func NewEditFileTool

func NewEditFileTool() *RegisteredTool

NewEditFileTool creates a RegisteredTool for search-and-replace editing of files.

func NewGlobTool

func NewGlobTool() *RegisteredTool

NewGlobTool creates a RegisteredTool for finding files by glob pattern.

func NewGrepTool

func NewGrepTool() *RegisteredTool

NewGrepTool creates a RegisteredTool for searching file contents by regex.

func NewReadFileTool

func NewReadFileTool() *RegisteredTool

NewReadFileTool creates a RegisteredTool for reading files with line numbers.

func NewSendInputTool

func NewSendInputTool(manager *SubAgentManager) *RegisteredTool

NewSendInputTool creates the send_input tool.

func NewShellTool

func NewShellTool() *RegisteredTool

NewShellTool creates a RegisteredTool for executing shell commands.

func NewSpawnAgentTool

func NewSpawnAgentTool(manager *SubAgentManager, profile ProviderProfile, client *llm.Client) *RegisteredTool

NewSpawnAgentTool creates the spawn_agent tool. The manager, profile, and client are captured in the closure.

func NewWaitTool

func NewWaitTool(manager *SubAgentManager) *RegisteredTool

NewWaitTool creates the wait tool.

func NewWriteFileTool

func NewWriteFileTool() *RegisteredTool

NewWriteFileTool creates a RegisteredTool for writing files.

type Session

type Session struct {
	ID           string
	Config       SessionConfig
	History      []Turn
	State        SessionState
	EventEmitter *EventEmitter
	// contains filtered or unexported fields
}

Session is the central orchestrator for the coding agent loop. It holds conversation state, manages queues, and dispatches events.

func NewSession

func NewSession(config SessionConfig) *Session

NewSession creates a new Session with a generated UUID and the given configuration.

func (*Session) AppendTurn

func (s *Session) AppendTurn(turn Turn)

AppendTurn adds a turn to the session history.

func (*Session) Close

func (s *Session) Close()

Close transitions the session to StateClosed and closes the event emitter.

func (*Session) DrainFollowup

func (s *Session) DrainFollowup() string

DrainFollowup removes and returns the first pending follow-up message. Returns an empty string if the queue is empty.

func (*Session) DrainSteering

func (s *Session) DrainSteering() []string

DrainSteering removes and returns all pending steering messages.

func (*Session) Emit

func (s *Session) Emit(kind EventKind, data map[string]any)

Emit emits a session event with the given kind and data, auto-populating the session ID and timestamp.

func (*Session) FollowUp

func (s *Session) FollowUp(message string)

FollowUp queues a follow-up message to be processed after the current input completes.

func (*Session) SetState

func (s *Session) SetState(state SessionState)

SetState transitions the session to the given state.

func (*Session) Steer

func (s *Session) Steer(message string)

Steer queues a steering message to be injected after the current tool round.

func (*Session) TurnCount

func (s *Session) TurnCount() int

TurnCount returns the number of turns in the session history.

type SessionConfig

type SessionConfig struct {
	MaxTurns                int            `json:"max_turns"`
	MaxToolRoundsPerInput   int            `json:"max_tool_rounds_per_input"`
	DefaultCommandTimeoutMs int            `json:"default_command_timeout_ms"`
	MaxCommandTimeoutMs     int            `json:"max_command_timeout_ms"`
	ReasoningEffort         string         `json:"reasoning_effort,omitempty"`
	ToolOutputLimits        map[string]int `json:"tool_output_limits,omitempty"`
	EnableLoopDetection     bool           `json:"enable_loop_detection"`
	LoopDetectionWindow     int            `json:"loop_detection_window"`
	MaxSubagentDepth        int            `json:"max_subagent_depth"`
	// FidelityMode controls how much conversation history is carried forward.
	// Valid values map to attractor fidelity modes: "full", "truncate", "compact",
	// "summary:low", "summary:medium", "summary:high". Empty string means no
	// fidelity filtering (equivalent to "full").
	FidelityMode string `json:"fidelity_mode,omitempty"`
	// UserOverride is appended to the system prompt as a "User Instructions"
	// section. This allows pipeline authors to inject per-node or per-pipeline
	// instructions into the coding agent's system prompt.
	UserOverride string `json:"user_override,omitempty"`
}

SessionConfig holds configuration for a session.

func DefaultSessionConfig

func DefaultSessionConfig() SessionConfig

DefaultSessionConfig returns a SessionConfig with spec-defined defaults.

type SessionEvent

type SessionEvent struct {
	Kind      EventKind      `json:"kind"`
	Timestamp time.Time      `json:"timestamp"`
	SessionID string         `json:"session_id"`
	Data      map[string]any `json:"data,omitempty"`
}

SessionEvent represents a typed event emitted by the agent loop.

type SessionState

type SessionState string

SessionState represents the lifecycle state of a session.

const (
	StateIdle          SessionState = "idle"
	StateProcessing    SessionState = "processing"
	StateAwaitingInput SessionState = "awaiting_input"
	StateClosed        SessionState = "closed"
)

type SteeringTurn

type SteeringTurn struct {
	Content   string
	Timestamp time.Time
}

SteeringTurn represents an injected steering message from the host application.

func (SteeringTurn) TurnTimestamp

func (t SteeringTurn) TurnTimestamp() time.Time

func (SteeringTurn) TurnType

func (t SteeringTurn) TurnType() string

type SubAgentHandle

type SubAgentHandle struct {
	ID      string
	Session *Session
	Status  SubAgentStatus
	Env     ExecutionEnvironment
	Profile ProviderProfile
	Client  *llm.Client
	// contains filtered or unexported fields
}

SubAgentHandle holds a reference to a spawned subagent.

type SubAgentManager

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

SubAgentManager manages the lifecycle of spawned subagents.

func NewSubAgentManager

func NewSubAgentManager(currentDepth, maxDepth int) *SubAgentManager

NewSubAgentManager creates a new SubAgentManager with the given depth constraints.

func (*SubAgentManager) Close

func (m *SubAgentManager) Close(agentID string) error

Close terminates a subagent by cancelling its context.

func (*SubAgentManager) CloseAll

func (m *SubAgentManager) CloseAll()

CloseAll terminates all running subagents.

func (*SubAgentManager) Get

func (m *SubAgentManager) Get(agentID string) (*SubAgentHandle, bool)

Get returns the handle for a given agent ID.

func (*SubAgentManager) SendInput

func (m *SubAgentManager) SendInput(agentID, message string) error

SendInput sends a message to a running subagent via the steering queue.

func (*SubAgentManager) Spawn

func (m *SubAgentManager) Spawn(ctx context.Context, task string, env ExecutionEnvironment, profile ProviderProfile, client *llm.Client, maxTurns int) (*SubAgentHandle, error)

Spawn creates a new subagent session, starts processing the task in a goroutine, and returns the agent's handle. Returns error if depth limit exceeded.

func (*SubAgentManager) Wait

func (m *SubAgentManager) Wait(agentID string) (*SubAgentResult, error)

Wait blocks until the subagent completes and returns its result.

type SubAgentResult

type SubAgentResult struct {
	Output    string `json:"output"`
	Success   bool   `json:"success"`
	TurnsUsed int    `json:"turns_used"`
}

SubAgentResult is the output from a completed subagent.

type SubAgentStatus

type SubAgentStatus string

SubAgentStatus represents the lifecycle state of a subagent.

const (
	SubAgentRunning   SubAgentStatus = "running"
	SubAgentCompleted SubAgentStatus = "completed"
	SubAgentFailed    SubAgentStatus = "failed"
)

type SystemTurn

type SystemTurn struct {
	Content   string
	Timestamp time.Time
}

SystemTurn represents a system-level message in the conversation.

func (SystemTurn) TurnTimestamp

func (t SystemTurn) TurnTimestamp() time.Time

func (SystemTurn) TurnType

func (t SystemTurn) TurnType() string

type ToolRegistry

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

ToolRegistry manages a thread-safe collection of registered tools.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates an empty ToolRegistry.

func (*ToolRegistry) Count

func (r *ToolRegistry) Count() int

Count returns the number of registered tools.

func (*ToolRegistry) Definitions

func (r *ToolRegistry) Definitions() []llm.ToolDefinition

Definitions returns all tool definitions from registered tools.

func (*ToolRegistry) Get

func (r *ToolRegistry) Get(name string) *RegisteredTool

Get returns the registered tool with the given name, or nil if not found.

func (*ToolRegistry) Has

func (r *ToolRegistry) Has(name string) bool

Has returns true if a tool with the given name is registered.

func (*ToolRegistry) Names

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

Names returns the names of all registered tools.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(tool *RegisteredTool) error

Register adds or replaces a tool in the registry. Returns an error if the tool's definition has an empty name.

func (*ToolRegistry) Unregister

func (r *ToolRegistry) Unregister(name string) bool

Unregister removes a tool by name. Returns true if the tool existed.

type ToolResultsTurn

type ToolResultsTurn struct {
	Results   []llm.ToolResult
	Timestamp time.Time
}

ToolResultsTurn holds results from executing one or more tool calls.

func (ToolResultsTurn) TurnTimestamp

func (t ToolResultsTurn) TurnTimestamp() time.Time

func (ToolResultsTurn) TurnType

func (t ToolResultsTurn) TurnType() string

type Turn

type Turn interface {
	// TurnType returns a string discriminator: "user", "assistant", "tool_results", "system", or "steering".
	TurnType() string

	// TurnTimestamp returns the time when the turn was created.
	TurnTimestamp() time.Time
}

Turn is the interface implemented by all conversation turn types.

func ApplyFidelity

func ApplyFidelity(history []Turn, mode string, contextWindow int) []Turn

ApplyFidelity filters or compresses conversation history based on the fidelity mode. It returns a (possibly reduced) copy of the history. The contextWindow parameter represents the provider's context window size in tokens, used as a heuristic for how aggressively to trim.

Modes:

  • "full" or "": preserve all history
  • "truncate": drop older turns from the middle, keeping system/first and recent
  • "compact": aggressively reduce, keeping only system and recent turns
  • "summary:low/medium/high": condense older turns into a summary, keeping recent

type UserTurn

type UserTurn struct {
	Content   string
	Timestamp time.Time
}

UserTurn represents a user-submitted message.

func (UserTurn) TurnTimestamp

func (t UserTurn) TurnTimestamp() time.Time

func (UserTurn) TurnType

func (t UserTurn) TurnType() string

Jump to

Keyboard shortcuts

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