agent

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTurnLimit = errors.New("turn limit reached")

ErrTurnLimit indicates the session exceeded its configured MaxTurns budget.

Functions

func ApplyPatch

func ApplyPatch(rootDir string, patch string) (string, error)

ApplyPatch applies a codex-rs-style apply_patch v4a patch to files under rootDir. This is a best-effort implementation intended for local agent loops.

func RegisterProfileFamily

func RegisterProfileFamily(family string, factory func(string) ProviderProfile)

Types

type DirEntry

type DirEntry struct {
	Name  string `json:"name"`
	IsDir bool   `json:"is_dir"`
	Size  int64  `json:"size,omitempty"`
}

type EnvironmentInfo

type EnvironmentInfo struct {
	WorkingDir            string
	Platform              string
	OSVersion             string
	Today                 string // YYYY-MM-DD
	KnowledgeCutoff       string // YYYY-MM-DD
	IsGitRepo             bool
	GitBranch             string
	GitModifiedFiles      int
	GitUntrackedFiles     int
	GitRecentCommitTitles []string
}

type EventKind

type EventKind string
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"
	EventWarning             EventKind = "WARNING"
	EventError               EventKind = "ERROR"
)

type ExecResult

type ExecResult struct {
	Stdout     string `json:"stdout"`
	Stderr     string `json:"stderr"`
	ExitCode   int    `json:"exit_code"`
	TimedOut   bool   `json:"timed_out"`
	DurationMS int64  `json:"duration_ms"`
}

type ExecutionEnvironment

type ExecutionEnvironment interface {
	WorkingDirectory() string
	Platform() string
	OSVersion() string

	ReadFile(path string, offsetLine *int, limitLines *int) (string, error)
	WriteFile(path string, content string) (string, error)
	EditFile(path string, oldString string, newString string, replaceAll bool) (string, error)
	FileExists(path string) bool

	Glob(pattern string, basePath string) ([]string, error)
	Grep(pattern string, path string, globFilter string, caseInsensitive bool, maxResults int) (string, error)
	ListDirectory(path string, depth int) ([]DirEntry, error)

	ExecCommand(ctx context.Context, command string, timeoutMS int, workingDir string, envVars map[string]string) (ExecResult, error)
}

ExecutionEnvironment abstracts the filesystem and command runner used by tools.

type LocalExecutionEnvironment

type LocalExecutionEnvironment struct {
	RootDir      string
	BaseEnv      map[string]string
	StripEnvKeys []string
}

func NewLocalExecutionEnvironment

func NewLocalExecutionEnvironment(rootDir string) *LocalExecutionEnvironment

func NewLocalExecutionEnvironmentWithBaseEnv

func NewLocalExecutionEnvironmentWithBaseEnv(rootDir string, baseEnv map[string]string) *LocalExecutionEnvironment

func NewLocalExecutionEnvironmentWithPolicy

func NewLocalExecutionEnvironmentWithPolicy(rootDir string, baseEnv map[string]string, stripKeys []string) *LocalExecutionEnvironment

func (*LocalExecutionEnvironment) EditFile

func (e *LocalExecutionEnvironment) EditFile(path string, oldString string, newString string, replaceAll bool) (string, error)

func (*LocalExecutionEnvironment) ExecCommand

func (e *LocalExecutionEnvironment) ExecCommand(ctx context.Context, command string, timeoutMS int, workingDir string, envVars map[string]string) (ExecResult, error)

func (*LocalExecutionEnvironment) FileExists

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

func (*LocalExecutionEnvironment) Glob

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

func (*LocalExecutionEnvironment) Grep

func (e *LocalExecutionEnvironment) Grep(pattern string, path string, globFilter string, caseInsensitive bool, maxResults int) (string, error)

func (*LocalExecutionEnvironment) ListDirectory

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

func (*LocalExecutionEnvironment) OSVersion

func (e *LocalExecutionEnvironment) OSVersion() string

func (*LocalExecutionEnvironment) Platform

func (e *LocalExecutionEnvironment) Platform() string

func (*LocalExecutionEnvironment) ReadFile

func (e *LocalExecutionEnvironment) ReadFile(path string, offsetLine *int, limitLines *int) (string, error)

func (*LocalExecutionEnvironment) WorkingDirectory

func (e *LocalExecutionEnvironment) WorkingDirectory() string

func (*LocalExecutionEnvironment) WriteFile

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

type ProjectDoc

type ProjectDoc struct {
	// Path is a stable, human-friendly identifier for the instruction file (relative to git root when available).
	Path string
	// Content is the raw file content (may be truncated when total budget is exceeded).
	Content string
}

func LoadProjectDocs

func LoadProjectDocs(env ExecutionEnvironment, filenames ...string) ([]ProjectDoc, bool)

LoadProjectDocs discovers and loads project instruction files from git root (or working directory when not in a git repo) down to the current working directory. Files are loaded in depth order (root first; deeper files have higher precedence) and filtered by the active provider profile (caller-provided list).

type ProviderProfile

type ProviderProfile interface {
	ID() string
	Model() string
	ToolDefinitions() []llm.ToolDefinition
	SupportsParallelToolCalls() bool
	ContextWindowSize() int
	ProjectDocFiles() []string
	BuildSystemPrompt(env EnvironmentInfo, docs []ProjectDoc) string
}

func NewAnthropicProfile

func NewAnthropicProfile(model string) ProviderProfile

func NewCodexAppServerProfile

func NewCodexAppServerProfile(model string) ProviderProfile

func NewGeminiProfile

func NewGeminiProfile(model string) ProviderProfile

func NewOpenAIProfile

func NewOpenAIProfile(model string) ProviderProfile

func NewProfileForFamily

func NewProfileForFamily(family string, model string) (ProviderProfile, error)

type RegisteredTool

type RegisteredTool struct {
	Definition llm.ToolDefinition
	Schema     *jsonschema.Schema
	Exec       func(ctx context.Context, env ExecutionEnvironment, args map[string]any) (any, error)

	Limit ToolOutputLimit
}

type Session

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

func NewSession

func NewSession(client *llm.Client, profile ProviderProfile, env ExecutionEnvironment, cfg SessionConfig) (*Session, error)

func (*Session) Close

func (s *Session) Close()

func (*Session) Events

func (s *Session) Events() <-chan SessionEvent

func (*Session) FollowUp

func (s *Session) FollowUp(msg string)

FollowUp queues a message to process after the current input completes.

func (*Session) ProcessInput

func (s *Session) ProcessInput(ctx context.Context, input string) (string, error)

func (*Session) SetReasoningEffort

func (s *Session) SetReasoningEffort(effort string)

SetReasoningEffort updates the reasoning effort used for future LLM calls. Takes effect on the next request (spec).

func (*Session) Steer

func (s *Session) Steer(msg string)

Steer queues a message to inject after the current tool round completes.

type SessionConfig

type SessionConfig struct {
	MaxToolRoundsPerInput          int
	MaxTurns                       int
	DefaultCommandTimeoutMS        int
	MaxCommandTimeoutMS            int
	RepeatedMalformedToolCallLimit int
	RepeatedErrorToolCallLimit     int
	MaxSubagentDepth               int

	// ToolOutputLimits overrides default per-tool truncation behavior.
	ToolOutputLimits map[string]ToolOutputLimit

	// UserInstructionOverride is appended to the end of the system prompt (highest priority).
	UserInstructionOverride string

	// ReasoningEffort is passed through to the Unified LLM request when non-empty.
	// Valid values are provider-dependent but typically include: low|medium|high.
	ReasoningEffort string

	// MaxTokens overrides the provider adapter's default max_tokens when non-nil.
	// Use this to allow larger outputs (e.g., large write_file tool calls).
	MaxTokens *int

	// ProviderOptions is merged into every LLM request as provider_options.
	// Use this for provider-specific parameters (e.g., Cerebras clear_thinking).
	ProviderOptions map[string]any

	// ToolCallFilter, when non-nil, is invoked before each tool call is executed.
	// It receives the tool name, call ID, and arguments JSON. If it returns a
	// non-empty string, the tool call is skipped and the returned string is used
	// as the tool result (with IsError=true). This enables pre-hook scripts to
	// veto tool calls.
	ToolCallFilter func(toolName, callID, argsJSON string) (skipReason string)

	EnableLoopDetection *bool
	LoopDetectionWindow int

	// LLMRetryPolicy controls retries for retryable Unified LLM errors (429, 5xx, etc).
	// Nil means use llm.DefaultRetryPolicy().
	LLMRetryPolicy *llm.RetryPolicy
	LLMSleep       llm.SleepFunc
}

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

type ToolExecResult

type ToolExecResult struct {
	ToolName string
	CallID   string

	// Output is the truncated output sent back to the model.
	Output string

	// FullOutput is the untruncated output (available via TOOL_CALL_END).
	FullOutput string

	IsError bool
}

type ToolOutputLimit

type ToolOutputLimit struct {
	MaxChars int
	MaxLines int
	Strategy TruncationStrategy
}

type ToolRegistry

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

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

func (*ToolRegistry) Definitions

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

func (*ToolRegistry) ExecuteCall

func (*ToolRegistry) Register

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

type TruncationStrategy

type TruncationStrategy string
const (
	TruncHeadTail TruncationStrategy = "head_tail"
	TruncTail     TruncationStrategy = "tail"
)

type Turn

type Turn struct {
	Kind    TurnKind
	Message llm.Message
}

Turn is the Session's typed history item. Steering turns are kept distinct for observability, but are converted to user-role messages when building the LLM request.

type TurnKind

type TurnKind string
const (
	TurnUserInput TurnKind = "USER_INPUT"
	TurnSteering  TurnKind = "STEERING"
	TurnAssistant TurnKind = "ASSISTANT"
	TurnTool      TurnKind = "TOOL"
)

Jump to

Keyboard shortcuts

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