agent

package
v0.32.2 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CompactionSummaryMessagePrefix = "Conversation summary:\n"
	CompactionToolName             = "summary"
	CompactionToolCallID           = "ollama_compaction"
	CompactionContinueInstruction  = "continue the task in progress. the history has been compacted, do not mention compaction to the user"
)

Compaction wire-format. These constants and helpers are the single canonical definition of how a compacted turn is represented in message history.

View Source
const (
	// SkillsDirEnv overrides the user-level Ollama-owned skills directory. The
	// cross-client .agents/skills/ convention and project-level .ollama/skills/
	// are also scanned (see LoadDefaultSkills); on a name collision, Ollama-owned
	// directories take precedence over .agents/skills/, and project-level takes
	// precedence over user-level.
	SkillsDirEnv = "OLLAMA_SKILLS"
)

Variables

This section is empty.

Functions

func ApproximateTokens added in v0.32.2

func ApproximateTokens(n int) int

ApproximateTokens estimates token count from a character/byte count using the standard ~4 chars-per-token heuristic. It is intentionally rough; all callers use it only for sizing/truncation decisions, not billing.

func CompactionSkippedMessage

func CompactionSkippedMessage(reason string) string

func CompactionSummaryContent

func CompactionSummaryContent(msg api.Message) (string, bool)

CompactionSummaryContent returns the user-visible summary from msg when it is a canonical compaction summary.

func CompactionSummaryMessages

func CompactionSummaryMessages(summary string, continueTask bool) []api.Message

CompactionSummaryMessages renders a compaction summary as the assistant tool-call plus tool-result pair that represents a compacted turn in the message history.

func CompactionSummaryText

func CompactionSummaryText(content string) string

CompactionSummaryText reverses CompactionSummaryMessages, returning the user-visible summary text with the prefix and any continuation instruction removed.

func IsCompactionSummary

func IsCompactionSummary(msg api.Message) bool

IsCompactionSummary reports whether msg uses the canonical compaction summary message representation.

func IsCompactionToolCall

func IsCompactionToolCall(msg api.Message) bool

IsCompactionToolCall reports whether msg is the synthetic assistant tool call paired with a compaction summary result.

func IsCompactionToolResult

func IsCompactionToolResult(msg api.Message) bool

IsCompactionToolResult reports whether msg is the synthetic tool result used to represent compaction in message history.

func ResolveCompactionThreshold

func ResolveCompactionThreshold(configured float64) float64

func ResolveContextWindowTokens

func ResolveContextWindowTokens(options map[string]any, configured int) int

func SkillsDir added in v0.32.2

func SkillsDir() (string, error)

SkillsDir returns the canonical runtime-owned skill directory.

func ToolRequiresApproval

func ToolRequiresApproval(tool Tool, args map[string]any) bool

func TruncMarker added in v0.32.2

func TruncMarker(label string, head, tail, omitted int, headTail bool, hint string) string

TruncMarker formats a truncation marker with consistent wording. head and tail are rune counts; omitted is the count of runes removed. headTail selects the head+tail vs head-only format. hint is optional guidance text.

func Truncate added in v0.32.2

func Truncate(content string, cfg TruncateConfig) string

Truncate truncates content to at most cfg.MaxRunes runes. When HeadTail is true, it preserves the first HeadPct% and last (100-HeadPct)% of the budget with a marker between; otherwise it keeps only the head. MaxRunes <= 0 triggers full omission using FullOmissionPrefix. All token counts in markers use ApproximateTokens.

Types

type Approval

type Approval struct {
	Allow       bool
	AllowAll    bool
	AllowScopes []string
	Reason      string
}

type ApprovalPrompter

type ApprovalPrompter interface {
	PromptApproval(context.Context, ApprovalRequest) (Approval, error)
}

type ApprovalRequest

type ApprovalRequest struct {
	WorkingDir string
	Calls      []ApprovalToolCall
}

func (*ApprovalRequest) AddToolCall added in v0.32.0

func (r *ApprovalRequest) AddToolCall(id, name, scope string, args map[string]any)

type ApprovalRequired

type ApprovalRequired interface {
	RequiresApproval(map[string]any) bool
}

type ApprovalState added in v0.32.0

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

func (*ApprovalState) AllGranted added in v0.32.2

func (s *ApprovalState) AllGranted() bool

AllGranted reports whether blanket approval has been granted.

func (*ApprovalState) Allows added in v0.32.0

func (s *ApprovalState) Allows(scope string) bool

func (*ApprovalState) Apply added in v0.32.0

func (s *ApprovalState) Apply(result *Approval) bool

Apply merges an approval's scopes and allow-all flag into the state. It returns true if the approval grants permission (allow-all or at least one scope). It does not mutate the approval; the caller sets Allow based on the returned value.

func (*ApprovalState) GrantAll added in v0.32.2

func (s *ApprovalState) GrantAll()

GrantAll grants blanket approval for all future tool calls.

func (*ApprovalState) GrantScopes added in v0.32.2

func (s *ApprovalState) GrantScopes(scopes []string)

GrantScopes merges the given scopes into the state.

func (*ApprovalState) Set added in v0.32.0

func (s *ApprovalState) Set(allowAll bool, scopes map[string]bool)

type ApprovalToolCall

type ApprovalToolCall struct {
	ToolCallID    string
	ToolName      string
	Args          map[string]any
	ApprovalScope string
}

type ChatClient

type ChatClient interface {
	Chat(context.Context, *api.ChatRequest, api.ChatResponseFunc) error
}

type CompactionOptions

type CompactionOptions struct {
	ContextWindowTokens int
	KeepUserTurns       int
	Threshold           float64
}

type CompactionProgress

type CompactionProgress struct {
	Tokens int
}

type CompactionRequest

type CompactionRequest struct {
	ChatID        string
	Model         string
	SystemPrompt  string
	Messages      []api.Message
	Tools         api.Tools
	Format        string
	Latest        api.ChatResponse
	Options       map[string]any
	KeepAlive     *api.Duration
	Think         *api.ThinkValue
	Force         bool
	ContinueTask  bool
	KeepUserTurns *int
	Progress      func(CompactionProgress)
}

type CompactionResult

type CompactionResult struct {
	Messages  []api.Message
	Compacted bool
	Due       bool
	Summary   string
	Reason    string
}

type CompactionTrigger added in v0.32.2

type CompactionTrigger string

CompactionTrigger is the typed reason a compaction ran or was attempted, carried on Event.CompactionTrigger for compaction events.

const (
	CompactionTriggerForce      CompactionTrigger = "force"
	CompactionTriggerPromptEval CompactionTrigger = "prompt_eval"
	CompactionTriggerEstimate   CompactionTrigger = "estimate"
	CompactionTriggerToolOutput CompactionTrigger = "tool_output"
	CompactionTriggerError      CompactionTrigger = "error"
	CompactionTriggerDue        CompactionTrigger = "due"
)

type Compactor

type Compactor interface {
	MaybeCompact(context.Context, CompactionRequest) (CompactionResult, error)

	// ContextWindowTokens returns the effective context window size in
	// tokens, resolving runtime options against configured defaults.
	ContextWindowTokens(options map[string]any) int

	// Threshold returns the compaction threshold as a fraction of the
	// context window (e.g. 0.8 means compact at 80% capacity).
	Threshold() float64

	// ShouldCompact reports whether a compaction should run and returns the
	// trigger reason. An empty trigger means compaction is not needed.
	ShouldCompact(req CompactionRequest) (trigger string, should bool)
}

type Event

type Event struct {
	Type              EventType         `json:"type"`
	RunID             string            `json:"runId,omitempty"`
	ChatID            string            `json:"chatId,omitempty"`
	Model             string            `json:"model,omitempty"`
	Status            RunStatus         `json:"status,omitempty"`
	ToolStatus        ToolStatus        `json:"toolStatus,omitempty"`
	CompactionTrigger CompactionTrigger `json:"compactionTrigger,omitempty"`
	ToolCallID        string            `json:"toolCallId,omitempty"`
	ToolName          string            `json:"toolName,omitempty"`
	WorkingDir        string            `json:"workingDir,omitempty"`
	Content           string            `json:"content,omitempty"`
	Thinking          string            `json:"thinking,omitempty"`
	ToolCalls         []api.ToolCall    `json:"toolCalls,omitempty"`
	Messages          []api.Message     `json:"messages,omitempty"`
	Args              map[string]any    `json:"args,omitempty"`
	Tokens            int               `json:"tokens,omitempty"`
	Error             string            `json:"error,omitempty"`
}

type EventSink

type EventSink interface {
	Emit(Event) error
}

type EventSinkFunc

type EventSinkFunc func(Event) error

func (EventSinkFunc) Emit

func (fn EventSinkFunc) Emit(event Event) error

type EventType

type EventType string
const (
	EventMessageDelta       EventType = "message_delta"
	EventThinkingDelta      EventType = "thinking_delta"
	EventToolCallDetected   EventType = "tool_call_detected"
	EventToolStarted        EventType = "tool_started"
	EventToolFinished       EventType = "tool_finished"
	EventCompactionStarted  EventType = "compaction_started"
	EventCompactionProgress EventType = "compaction_progress"
	EventCompacted          EventType = "compacted"
	EventCompactionSkipped  EventType = "compaction_skipped"
	EventRunFinished        EventType = "run_finished"
	EventError              EventType = "error"
)

type Registry

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

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, toolCtx ToolContext, call api.ToolCall) (ToolResult, error)

func (*Registry) Get

func (r *Registry) Get(name string) (Tool, bool)

func (*Registry) Names

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

func (*Registry) Register

func (r *Registry) Register(tool Tool)

func (*Registry) Tools

func (r *Registry) Tools() api.Tools

type RunOptions

type RunOptions struct {
	ChatID       string
	Model        string
	SystemPrompt string
	Messages     []api.Message
	NewMessages  []api.Message
	Format       string
	Options      map[string]any
	Think        *api.ThinkValue
	KeepAlive    *api.Duration
	// SkillName loads a catalog skill as an ordered synthetic tool call/result
	// before the first model request for this run.
	SkillName string
	// MaxToolRounds limits consecutive model/tool cycles. A positive value is
	// an explicit limit. Zero selects the model-specific default: local models
	// use the default guard and cloud models are unlimited. A negative value
	// disables the guard for tests or special callers.
	MaxToolRounds int
}

type RunResult

type RunResult struct {
	Messages   []api.Message
	Latest     api.ChatResponse
	WorkingDir string
}

type RunStatus added in v0.32.2

type RunStatus string

RunStatus is the typed terminal outcome of a run, carried on Event.Status for run_finished events.

const (
	RunStatusDone     RunStatus = "done"
	RunStatusDenied   RunStatus = "denied"
	RunStatusCanceled RunStatus = "canceled"
)

type ScopedTool added in v0.32.2

type ScopedTool interface {
	ApprovalScope(args map[string]any) string
}

ScopedTool is implemented by tools that need per-invocation approval scoping beyond the tool name (e.g. shell commands scoped to the exact command string). Tools that don't implement this are scoped by name only.

type Session

type Session struct {
	Client           ChatClient
	EventSinks       []EventSink
	Tools            *Registry
	Skills           *SkillCatalog
	DisableTools     bool
	ApprovalPrompter ApprovalPrompter
	ApprovalState    *ApprovalState
	WorkingDir       string
	Compactor        Compactor
}

func (*Session) Run

func (s *Session) Run(ctx context.Context, opts RunOptions) (*RunResult, error)

type SimpleCompactor

type SimpleCompactor struct {
	Client  ChatClient
	Options CompactionOptions
}

func (*SimpleCompactor) ContextWindowTokens added in v0.32.2

func (c *SimpleCompactor) ContextWindowTokens(options map[string]any) int

ContextWindowTokens resolves the effective context window from runtime options or configured defaults. Satisfies the Compactor interface.

func (*SimpleCompactor) MaybeCompact

func (*SimpleCompactor) ShouldCompact added in v0.32.2

func (c *SimpleCompactor) ShouldCompact(req CompactionRequest) (string, bool)

ShouldCompact reports whether compaction is due and the trigger reason. Satisfies the Compactor interface.

func (*SimpleCompactor) Threshold added in v0.32.2

func (c *SimpleCompactor) Threshold() float64

Threshold returns the configured compaction threshold fraction. Satisfies the Compactor interface.

type Skill added in v0.32.2

type Skill struct {
	Name         string
	Description  string
	Instructions string
	Path         string
}

Skill is a validated, loadable instruction set. It never grants tool permissions; it is supplied to the model as ordinary tool-result content.

func (Skill) Content added in v0.32.2

func (s Skill) Content() string

type SkillCatalog added in v0.32.2

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

SkillCatalog contains valid skills and diagnostics for ignored invalid entries, so one malformed skill cannot hide the rest.

func DiscoverSkills added in v0.32.2

func DiscoverSkills(dir string) (*SkillCatalog, error)

func LoadDefaultSkills added in v0.32.2

func LoadDefaultSkills(projectDir string) (*SkillCatalog, error)

LoadDefaultSkills discovers skills from the spec's scopes, merged with deterministic precedence. Roots are scanned lowest-precedence first so later roots override earlier ones on name collisions (recording a diagnostic):

  1. ~/.agents/skills/ (user, cross-client)
  2. user Ollama skills dir (user, Ollama-owned; SkillsDir)
  3. <project>/.agents/skills/ (project, cross-client)
  4. <project>/.ollama/skills/ (project, Ollama-owned)

Project-level overrides user-level, and within a scope Ollama-owned directories override .agents/skills/. projectDir is the agent's working directory at startup (discovery is a session-start snapshot per the spec).

func (*SkillCatalog) Diagnostics added in v0.32.2

func (c *SkillCatalog) Diagnostics() []error

func (*SkillCatalog) Dir added in v0.32.2

func (c *SkillCatalog) Dir() string

func (*SkillCatalog) List added in v0.32.2

func (c *SkillCatalog) List() []Skill

func (*SkillCatalog) Load added in v0.32.2

func (c *SkillCatalog) Load(name string) (Skill, error)

func (*SkillCatalog) SystemContext added in v0.32.2

func (c *SkillCatalog) SystemContext() string

SystemContext advertises the catalog without expanding full instructions in every request. The skill call is the explicit loading boundary.

type Tool

type Tool interface {
	Name() string
	Description() string
	Schema() api.ToolFunction
	Execute(context.Context, ToolContext, map[string]any) (ToolResult, error)
}

type ToolContext

type ToolContext struct {
	WorkingDir string
}

type ToolResult

type ToolResult struct {
	Content    string
	WorkingDir string
}

type ToolStatus added in v0.32.2

type ToolStatus string

ToolStatus is the typed lifecycle state for a tool call, carried on Event.ToolStatus for tool events.

const (
	ToolStatusRunning  ToolStatus = "running"
	ToolStatusDone     ToolStatus = "done"
	ToolStatusFailed   ToolStatus = "failed"
	ToolStatusDenied   ToolStatus = "denied"
	ToolStatusDisabled ToolStatus = "disabled"
	ToolStatusSkipped  ToolStatus = "skipped"
)

type TruncateConfig added in v0.32.2

type TruncateConfig struct {
	MaxRunes           int    // rune limit; <= 0 means full omission
	HeadTail           bool   // true = head + tail split; false = head only
	HeadPct            int    // percentage of MaxRunes for head (e.g. 75); tail gets the rest
	Label              string // e.g. "tool output", "summary", "stdout"
	Hint               string // guidance text appended to marker (optional)
	FullOmissionPrefix string // marker prefix when MaxRunes <= 0
}

TruncateConfig configures content truncation via Truncate.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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