Documentation
¶
Overview ¶
Package harvey — skill_set.go implements the /skill-set command, which lets the user load, inspect, and manage named YAML bundles of skills stored in agents/skill-sets/.
Index ¶
- Constants
- Variables
- func AuditLog(event AuditEvent)
- func CatalogSystemPromptBlock(cat SkillCatalog) string
- func CompileSkill(ctx context.Context, client LLMClient, skill *SkillMeta, out io.Writer) error
- func CompiledBashPath(skillPath string) string
- func CompiledPS1Path(skillPath string) string
- func CountTokens(ctx context.Context, baseURL, model, text string) (count int, exact bool)
- func DefaultSessionPath(dir string) string
- func DispatchSkill(ctx context.Context, a *Agent, skill *SkillMeta, prompt string, ...) error
- func DispatchToEndpoint(ctx context.Context, ep *RouteEndpoint, history []Message, prompt string, ...) (string, error)
- func ExpandDynamicSections(content string, ws *Workspace) string
- func ExtractModelFromSession(path string) (string, error)
- func FmtHelp(src string, appName string, version string, releaseDate string, ...) string
- func HistoryText(messages []Message) string
- func IsStale(skill *SkillMeta) (stale bool, err error)
- func LlamacppAPIURL(u string) string
- func LlamafileAPIURL(u string) string
- func LlamafileHealthURL(u string) string
- func LoadHarveyMD() string
- func LoadHarveyYAML(ws *Workspace, cfg *Config) error
- func LoadRouteConfig(ws *Workspace, cfg *Config)
- func LogAudit(action AuditAction, details string, status AuditStatus)
- func LooksLikeSkillQuery(s string) bool
- func MatchesTrigger(skill *SkillMeta, prompt string) bool
- func ParseAtMention(input string) (name, prompt string, ok bool)
- func ParseEmbedderFlags(args []string) (kind, url string)
- func PrintOllamaEnv(out io.Writer)
- func ProbeEncoderfile(baseURL string) bool
- func ProbeEncoderfileModel(baseURL string) (string, error)
- func ProbeOllama(baseURL string) bool
- func RegisterBuiltinTools(r *ToolRegistry, a *Agent)
- func ResolveSessionsDir(ws *Workspace, customPath string) (string, error)
- func RunSkillWizard(ws *Workspace, reader *bufio.Reader, out io.Writer) (string, error)
- func SaveModelAliases(ws *Workspace, cfg *Config) error
- func SaveRAGConfig(ws *Workspace, cfg *Config) error
- func SaveRouteConfig(ws *Workspace, rr *RouteRegistry) error
- func SetGlobalAuditBuffer(buf *AuditBuffer)
- func SortedSkillNames(cat SkillCatalog) []string
- func StartOllamaService() error
- func ValidSkillName(name string) bool
- type Agent
- func (a *Agent) AddMessage(role, content string)
- func (a *Agent) CheckDeletePermission(path string) bool
- func (a *Agent) CheckExecPermission(path string) bool
- func (a *Agent) CheckReadPermission(path string) bool
- func (a *Agent) CheckWritePermission(path string) bool
- func (a *Agent) ClearHistory()
- func (a *Agent) ContinueFromFountain(path string) (int, error)
- func (a *Agent) HasPermission(path string, perm string) bool
- func (a *Agent) ReplayFromFountain(ctx context.Context, srcPath, outPath string, out io.Writer) error
- func (a *Agent) Run(out io.Writer) error
- type AnyLLMClient
- func (a *AnyLLMClient) BackendURL() string
- func (a *AnyLLMClient) Chat(ctx context.Context, messages []Message, out io.Writer) (ChatStats, error)
- func (a *AnyLLMClient) ChatWithTools(ctx context.Context, messages []Message, tools []anyllm.Tool, out io.Writer) (ChatStats, []anyllm.ToolCall, error)
- func (a *AnyLLMClient) Close() error
- func (a *AnyLLMClient) ModelName() string
- func (a *AnyLLMClient) Models(ctx context.Context) ([]string, error)
- func (a *AnyLLMClient) Name() string
- func (a *AnyLLMClient) ProviderName() string
- type AnyLLMEmbedder
- type AuditAction
- type AuditBuffer
- func (b *AuditBuffer) Add(event AuditEvent)
- func (b *AuditBuffer) Capacity() int
- func (b *AuditBuffer) Clear()
- func (b *AuditBuffer) Get(n int) []AuditEvent
- func (b *AuditBuffer) GetAll() []AuditEvent
- func (b *AuditBuffer) Log(action AuditAction, details string, status AuditStatus)
- func (b *AuditBuffer) Size() int
- type AuditEvent
- type AuditStatus
- type CapabilityStatus
- type ChatStats
- type Chunk
- type Command
- type Concept
- type Config
- func (c *Config) ActiveRagStore() *RagStoreEntry
- func (c *Config) AddAllowedCommand(cmd string)
- func (c *Config) AddOrUpdateRagStore(e RagStoreEntry)
- func (c *Config) AddPermission(prefix string, perm string)
- func (c *Config) HasPermission(path string, perm string) bool
- func (c *Config) IsCommandAllowed(cmd string) bool
- func (c *Config) PermissionString(prefix string) string
- func (c *Config) RagStoreByName(name string) *RagStoreEntry
- func (c *Config) RemoveAllowedCommand(cmd string)
- func (c *Config) RemovePermission(prefix string, perm string)
- func (c *Config) RemoveRagStore(name string)
- func (c *Config) ResetAllowedCommands()
- func (c *Config) ResetPermissions()
- func (c *Config) ResolveModelAlias(alias string) string
- func (c *Config) SetPermission(prefix string, perms []string)
- type Embedder
- type EncoderfileEmbedder
- type KBSearchResult
- type KnowledgeBase
- func (kb *KnowledgeBase) AddConcept(name, description string) (int64, error)
- func (kb *KnowledgeBase) AddObservation(projectID int64, kind, body string) (int64, error)
- func (kb *KnowledgeBase) AddProject(name, description string) (int64, error)
- func (kb *KnowledgeBase) Close() error
- func (kb *KnowledgeBase) Concepts() ([]Concept, error)
- func (kb *KnowledgeBase) FormatMarkdown(projectID int64) (string, error)
- func (kb *KnowledgeBase) LinkObservationConcept(observationID, conceptID int64) error
- func (kb *KnowledgeBase) LinkProjectConcept(projectID, conceptID int64) error
- func (kb *KnowledgeBase) Observations(projectID int64) ([]Observation, error)
- func (kb *KnowledgeBase) Path() string
- func (kb *KnowledgeBase) ProjectByName(name string) (*Project, error)
- func (kb *KnowledgeBase) ProjectConcepts(projectID int64) ([]Concept, error)
- func (kb *KnowledgeBase) Projects() ([]Project, error)
- func (kb *KnowledgeBase) Search(term string) ([]KBSearchResult, error)
- func (kb *KnowledgeBase) Summary() (string, error)
- type LLMClient
- type Message
- type ModelCache
- type ModelCapability
- type ModelDetail
- type ModelSummary
- type Observation
- type OllamaClient
- type OllamaEmbedder
- type PlaybackTurn
- type Project
- type RagStore
- type RagStoreEntry
- type Recorder
- func (r *Recorder) Close() error
- func (r *Recorder) Path() string
- func (r *Recorder) RecordAgentAction(kind, target, userChoice, outcome string) error
- func (r *Recorder) RecordShellCommand(cmdLine, output string, exitCode int) error
- func (r *Recorder) RecordSkillLoad(name, description, body string) error
- func (r *Recorder) RecordTurn(userInput, harveyReply string) error
- func (r *Recorder) RecordTurnWithStats(userInput, harveyReply string, stats ChatStats, models []string, ...) error
- func (r *Recorder) Rename(newPath string) error
- func (r *Recorder) StartAgentScene(description string) error
- type RouteEndpoint
- type RouteKind
- type RouteRegistry
- type SessionFileInfo
- type SkillCatalog
- type SkillMeta
- type SkillSearchDir
- type SkillSetMeta
- type SkillSource
- type SkillVariable
- type Spinner
- type ToolCapable
- type ToolExecutor
- type ToolHandler
- type ToolRegistry
- func (r *ToolRegistry) Dispatch(ctx context.Context, name, argsJSON string, maxBytes int) (string, error)
- func (r *ToolRegistry) GetTool(name string) (anyllm.Tool, ToolHandler, bool)
- func (r *ToolRegistry) GetToolSchemas() []anyllm.Tool
- func (r *ToolRegistry) Len() int
- func (r *ToolRegistry) RegisterTool(name, description string, parameters map[string]any, handler ToolHandler)
- type Workspace
- func (ws *Workspace) AbsPath(rel string) (string, error)
- func (ws *Workspace) HarveyDir() string
- func (ws *Workspace) ListDir(path string) ([]fs.DirEntry, error)
- func (ws *Workspace) MkdirAll(path string) error
- func (ws *Workspace) ReadFile(path string) ([]byte, error)
- func (ws *Workspace) WriteFile(path string, data []byte, perm fs.FileMode) error
Constants ¶
const ( PermRead = "read" PermWrite = "write" PermExec = "exec" PermDelete = "delete" )
Permission types
const ( // Version number of release Version = "0.0.3" // ReleaseDate, the date version.go was generated ReleaseDate = "2026-05-12" // ReleaseHash, the Git hash when version.go was generated ReleaseHash = "e8d588e" LicenseText = `` /* 724-byte string literal not displayed */ )
const DefaultAuditBufferCapacity = 1000
DefaultAuditBufferCapacity is the default size of the audit ring buffer.
const RecentContextN = 10
RecentContextN is the number of recent non-system history messages sent alongside a dispatched prompt. Excludes system messages. Tune over time.
Variables ¶
var ( // SkillsHelpText explains the Agent Skills feature and is displayed by // /help skills (REPL) or harvey --help skills (CLI). SkillsHelpText = `` /* 5043-byte string literal not displayed */ RoutingHelpText = `%{app_name}(7) user manual | version {version} {release_hash} % R. S. Doiel % {release_date} # NAME ROUTING # SYNOPSIS @name prompt text # DESCRIPTION Harvey can dispatch individual prompts to remote LLM endpoints — other Ollama instances on a Pi cluster, Llamafile servers, or cloud providers — using @mention syntax. Prefix any prompt with @name to send it to the named endpoint instead of the local model. The reply is streamed back and lands in the local conversation history so future turns retain full context. Routing is explicitly user-driven: there is no automatic classification. You choose which endpoint handles each prompt by using (or omitting) an @mention. # CONTEXT WINDOW When a prompt is dispatched to a remote endpoint, Harvey sends the last 10 non-system messages from the local history alongside it. System messages are excluded. This gives the remote model enough context to be useful without sending the entire conversation over the network. The window size is a starting point and will be tuned over time. # ENDPOINT TYPES Local providers (no API key): ollama://host:port A remote Ollama server (also accepts http:// and https://). llamafile://host:port A Llamafile binary server (OpenAI-compatible, port 8080). llamacpp://host:port A llama.cpp server (OpenAI-compatible, port 8080). Cloud providers (API key read from environment): anthropic:// Anthropic Claude (ANTHROPIC_API_KEY) deepseek:// DeepSeek (DEEPSEEK_API_KEY) gemini:// Google Gemini (GEMINI_API_KEY or GOOGLE_API_KEY) mistral:// Mistral (MISTRAL_API_KEY) openai:// OpenAI (OPENAI_API_KEY) # EXAMPLE SESSION ~~~ # Register a Pi cluster node /route add pi2 ollama://192.168.1.12:11434 llama3.1:8b # Register the Anthropic cloud endpoint /route add claude anthropic:// claude-sonnet-4-20250514 # Enable routing /route on # Dispatch a complex task to the cloud @claude refactor this module to use the repository pattern # Run a quick task on a Pi node @pi2 write a unit test for the Parse function # Local model handles everything else (no @mention) what does this error mean? ~~~ # SLASH COMMANDS ~~~ /route add NAME URL [MODEL] register a remote endpoint @pi2 ollama://192.168.1.12:11434 llama3.1:8b @claude anthropic:// claude-sonnet-4-20250514 /route rm NAME remove a registered endpoint /route list show all endpoints with reachability status /route on enable @mention dispatch (persisted) /route off disable @mention dispatch (persisted) /route status show routing state and endpoint count ~~~ Registered endpoints and the on/off state persist across sessions in ` + "`" + `<workspace>/agents/routes.json.` + "`" + ` ` OllamaHelpText = `` /* 2561-byte string literal not displayed */ ClearHelpText = `` /* 1527-byte string literal not displayed */ EditingHelpText = `` /* 1777-byte string literal not displayed */ SessionHelpText = `` /* 2376-byte string literal not displayed */ ContextHelpText = `` /* 1994-byte string literal not displayed */ KBHelpText = `` /* 3672-byte string literal not displayed */ RecordHelpText = `` /* 1679-byte string literal not displayed */ RagHelpText = `` /* 7800-byte string literal not displayed */ RenameHelpText = `` /* 957-byte string literal not displayed */ ModelAliasHelpText = `` /* 1166-byte string literal not displayed */ FileTreeHelpText = `` /* 857-byte string literal not displayed */ ReadDirHelpText = `` /* 1461-byte string literal not displayed */ SkillSetHelpText = `` /* 1912-byte string literal not displayed */ HelpText = `` /* 4421-byte string literal not displayed */ )
var AllPermissions = []string{PermRead, PermWrite, PermExec, PermDelete}
AllPermissions is a slice of all valid permission types.
var DefaultAllowedCommands = []string{
"ls", "cat", "grep", "head", "tail", "wc",
"find", "stat", "jq", "htmlq", "bat", "batcat",
}
* DefaultConfig returns a Config populated with sensible defaults. WorkDir
- defaults to "." (the process working directory at startup). AutoRecord
- defaults to true so every session is saved to harvey/sessions/. *
- Returns:
- *Config — configuration with default values pre-filled. *
- Example:
- cfg := DefaultConfig()
- fmt.Println(cfg.OllamaURL) // "http://localhost:11434"
DefaultAllowedCommands is the default list of commands allowed when SafeMode is enabled. These are considered safe read-only or low-risk utilities.
var LearMessages = []string{}/* 449 elements not displayed */
learMessages are whimsical waiting messages in the style of Edward Lear's Book of Nonsense, displayed while the Harvey or the LLM is thinking.
var ValidObservationKinds = []string{"note", "finding", "decision", "question", "hypothesis"}
ValidObservationKinds lists the accepted values for Observation.Kind.
Functions ¶
func AuditLog ¶
func AuditLog(event AuditEvent)
AuditLog logs an audit event to the global buffer if initialized.
func CatalogSystemPromptBlock ¶
func CatalogSystemPromptBlock(cat SkillCatalog) string
* CatalogSystemPromptBlock returns the XML catalog block and load
- instructions to append to Harvey's system prompt. Returns an empty string
- when cat is empty so callers need not special-case the no-skills case. *
- Parameters:
- cat (SkillCatalog) — skills to include; may be nil or empty. *
- Returns:
- string — system-prompt fragment; "" if no skills. *
- Example:
- block := CatalogSystemPromptBlock(cat)
- if block != "" {
- agent.AddMessage("system", block)
- }
func CompileSkill ¶
* CompileSkill sends the skill body to the LLM with a meta-prompt that instructs
- it to produce compiled.bash and compiled.ps1 scripts. The generated scripts are
- written to the skill's scripts/ directory, which is created if absent. *
- If the LLM response does not contain both expected code blocks, an error is
- returned and no files are written. *
- Parameters:
- ctx (context.Context) — for LLM call cancellation.
- client (LLMClient) — the connected LLM backend.
- skill (*SkillMeta) — skill to compile; skill.Path and skill.Body must be set.
- out (io.Writer) — receives streamed LLM output during generation. *
- Returns:
- error — on LLM failure, missing code blocks, or file write failure. *
- Example:
- err := CompileSkill(ctx, agent.Client, skill, os.Stdout)
- if err != nil { log.Fatal(err) }
func CompiledBashPath ¶
* CompiledBashPath returns the absolute path to the compiled bash script
- for the skill whose SKILL.md lives at skillPath. *
- Parameters:
- skillPath (string) — absolute path to a SKILL.md file. *
- Returns:
- string — absolute path to scripts/compiled.bash sibling. *
- Example:
- p := CompiledBashPath("/proj/.agents/skills/my-skill/SKILL.md")
- // returns "/proj/.agents/skills/my-skill/scripts/compiled.bash"
func CompiledPS1Path ¶
* CompiledPS1Path returns the absolute path to the compiled PowerShell script
- for the skill whose SKILL.md lives at skillPath. *
- Parameters:
- skillPath (string) — absolute path to a SKILL.md file. *
- Returns:
- string — absolute path to scripts/compiled.ps1 sibling. *
- Example:
- p := CompiledPS1Path("/proj/.agents/skills/my-skill/SKILL.md")
- // returns "/proj/.agents/skills/my-skill/scripts/compiled.ps1"
func CountTokens ¶
* CountTokens estimates the number of tokens in text for the named model.
- It first tries the Ollama /api/tokenize endpoint; if that is unavailable
- or fails, it falls back to a character-based heuristic (len(text)/4). *
- Parameters:
- ctx (context.Context) — controls the HTTP request lifetime.
- baseURL (string) — Ollama server base URL.
- model (string) — model name (sent with the tokenize request).
- text (string) — text to count. *
- Returns:
- count (int) — number of tokens.
- exact (bool) — true when the count came from Ollama, false for the heuristic. *
- Example:
- n, exact := CountTokens(ctx, "http://localhost:11434", "llama3", prompt)
- fmt.Printf("%d tokens (exact=%v)\n", n, exact)
func DefaultSessionPath ¶
DefaultSessionPath returns a timestamped default filename for a session script in the given directory, using the .spmd extension.
Parameters:
dir (string) — directory in which to place the file.
Returns:
string — path of the form "<dir>/harvey-session-YYYYMMDD-HHMMSS.spmd".
Example:
path := DefaultSessionPath("/home/user/project/harvey/sessions")
// "/home/user/project/harvey/sessions/harvey-session-20260415-142300.spmd"
func DispatchSkill ¶
func DispatchSkill(ctx context.Context, a *Agent, skill *SkillMeta, prompt string, reader *bufio.Reader, out io.Writer) error
* DispatchSkill handles the full lifecycle when a skill is triggered:
- checks for compiled scripts, handles staleness prompts, offers compilation,
- and either runs the compiled script or falls back to LLM loading. *
- Dispatch states:
- 1. No compiled scripts → offer to compile; if declined fall back to LLM.
- 2. Scripts exist but SKILL.md is newer → offer to recompile; then run.
- 3. Scripts exist and up to date → run directly. *
- Parameters:
- ctx (context.Context) — for LLM calls if compilation is needed.
- a (*Agent) — the running agent (client, workspace, history).
- skill (*SkillMeta) — the skill to dispatch.
- prompt (string) — the user's triggering prompt text (HARVEY_PROMPT).
- reader (*bufio.Reader) — reads Y/n confirmations from the user.
- out (io.Writer) — destination for status messages and script output. *
- Returns:
- error — on unexpected I/O or execution failure; non-zero script exit is reported but not returned. *
- Example:
- err := DispatchSkill(ctx, agent, skill, input, reader, os.Stdout)
func DispatchToEndpoint ¶
func DispatchToEndpoint(ctx context.Context, ep *RouteEndpoint, history []Message, prompt string, cfg *Config, out io.Writer) (string, error)
* DispatchToEndpoint sends the recent conversation context plus prompt to ep,
- streams the reply to out, and returns the full reply text. The context window
- is capped at RecentContextN non-system messages from history. *
- Parameters:
- ctx (context.Context) — controls the HTTP request lifetime.
- ep (*RouteEndpoint) — registered endpoint to send to.
- history ([]Message) — full local conversation history.
- prompt (string) — current user prompt (already stripped of @mention).
- cfg (*Config) — used to resolve model defaults.
- out (io.Writer) — destination for streamed reply tokens. *
- Returns:
- reply (string) — full reply text.
- err (error) — non-nil on transport or API failure. *
- Example:
- reply, err := DispatchToEndpoint(ctx, ep, agent.History, "write a parser", cfg, os.Stdout)
func ExpandDynamicSections ¶
* ExpandDynamicSections replaces marker comments in content with live
- workspace data. Supported markers: *
- <!-- @date --> current date (YYYY-MM-DD)
- <!-- @files --> workspace file tree, skipping hidden directories
- <!-- @git-status --> output of "git status --short" in the workspace root *
- If ws is nil the content is returned unchanged. *
- Parameters:
- content (string) — text to expand (typically HARVEY.md contents).
- ws (*Workspace) — workspace used to resolve files and run git. *
- Returns:
- string — content with all recognised markers replaced. *
- Example:
- expanded := ExpandDynamicSections(raw, ws)
- agent.AddMessage("system", expanded)
func ExtractModelFromSession ¶
* ExtractModelFromSession parses a .spmd or .fountain session file and
- returns the model name recorded as a CHARACTER element. Returns an empty
- string when no model character can be identified. *
- Parameters:
- path (string) — path to a Harvey session file (.spmd or .fountain). *
- Returns:
- string — ALL-CAPS model name (e.g. "GEMMA4"), or "" if not found.
- error — on parse failure. *
- Example:
- model, err := ExtractModelFromSession("agents/sessions/session.spmd")
- // model == "GEMMA4"
func FmtHelp ¶
func FmtHelp(src string, appName string, version string, releaseDate string, releaseHash string) string
FmtHelp lets you process a text block with simple curly brace markup.
func HistoryText ¶
* HistoryText concatenates every message's content with a newline separator.
- Used to produce a single string for token-count estimation over the full
- conversation history. *
- Parameters:
- messages ([]Message) — conversation history. *
- Returns:
- string — all message bodies joined by newlines. *
- Example:
- text := HistoryText(agent.History)
- n, _ := CountTokens(ctx, baseURL, model, text)
func IsStale ¶
* IsStale reports whether SKILL.md is newer than the compiled scripts,
- meaning the scripts need recompilation. *
- Returns (true, nil) when either compiled script does not exist or when
- SKILL.md has a later modification time than either script.
- Returns (false, nil) when both scripts exist and are at least as new as SKILL.md.
- Returns (false, error) when SKILL.md itself cannot be stat'd. *
- Parameters:
- skill (*SkillMeta) — skill to check; skill.Path must be set. *
- Returns:
- stale (bool) — true when recompilation is needed.
- err (error) — non-nil only when SKILL.md itself is unreadable. *
- Example:
- stale, err := IsStale(skill)
- if err != nil { log.Fatal(err) }
- if stale { fmt.Println("needs recompile") }
func LlamacppAPIURL ¶
LlamacppAPIURL converts a "llamacpp://host:port" URL to "http://host:port/v1".
func LlamafileAPIURL ¶
LlamafileAPIURL converts a "llamafile://host:port" URL to the form "http://host:port/v1" expected by the any-llm-go llamafile provider. Already well-formed http(s):// URLs are left unchanged.
func LlamafileHealthURL ¶
LlamafileHealthURL returns the base URL (without /v1) suitable for health probing a llamafile or llama.cpp server.
func LoadHarveyMD ¶
func LoadHarveyMD() string
* LoadHarveyMD reads HARVEY.md from the current directory and returns the
- agent preamble followed by the file contents. The preamble is always
- included so the LLM knows it must use slash commands for real side-effects
- rather than narrating fake output. Returns only the preamble when HARVEY.md
- does not exist. *
- Returns:
- string — agentPreamble + HARVEY.md contents (or agentPreamble alone). *
- Example:
- prompt := LoadHarveyMD()
- cfg.SystemPrompt = prompt
func LoadHarveyYAML ¶
* LoadHarveyYAML reads agents/harvey.yaml from ws and applies any overrides
- to cfg. Missing fields are left unchanged. The file is optional — its
- absence is silently ignored. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is searched.
- cfg (*Config) — config to update in place. *
- Returns:
- error — only on YAML parse failure; a missing file returns nil. *
- Example:
- if err := LoadHarveyYAML(ws, cfg); err != nil {
- log.Fatal(err)
- }
func LoadRouteConfig ¶
* LoadRouteConfig reads agents/routes.json from the workspace and populates
- cfg.Routes and cfg.RoutingEnabled. Silently no-ops when the file does not
- exist or cannot be parsed, leaving cfg unchanged. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is searched.
- cfg (*Config) — config to populate; modified in place. *
- Example:
- cfg := DefaultConfig()
- LoadRouteConfig(ws, cfg)
func LogAudit ¶
func LogAudit(action AuditAction, details string, status AuditStatus)
LogAudit is a convenience function for logging audit events.
func LooksLikeSkillQuery ¶
* LooksLikeSkillQuery reports whether the user's input looks like a natural-
- language question about available skills so the REPL can intercept it and
- answer directly from the catalog rather than passing it to the LLM. *
- Parameters:
- s (string) — the raw user input. *
- Returns:
- bool — true when the input matches a known skill-query pattern. *
- Example:
- if LooksLikeSkillQuery("what skills do you know?") {
- cmdSkill(a, []string{"list"}, out)
- }
func MatchesTrigger ¶
* MatchesTrigger reports whether prompt matches the trigger pattern stored in
- skill.Trigger. Returns false when skill.Trigger is empty. *
- Two trigger modes are supported:
- Regexp mode — trigger value is wrapped in slashes: /pattern/
- Matched case-insensitively via (?i).
- Keyword mode — trigger value is a whitespace-separated list of words.
- Any single word present in the lowercased prompt triggers. *
- A malformed regexp returns false rather than panicking. *
- Parameters:
- skill (*SkillMeta) — skill with optional Trigger field.
- prompt (string) — raw user input to match against. *
- Returns:
- bool — true when prompt matches the trigger. *
- Example:
- skill.Trigger = "pdf extract"
- MatchesTrigger(skill, "please extract the pdf") // true
func ParseAtMention ¶
* ParseAtMention extracts the @name prefix and remaining prompt from input.
- Returns ok=false when input does not start with "@" followed by a non-empty
- word. Leading and trailing whitespace is trimmed before parsing. *
- Parameters:
- input (string) — raw user input, potentially starting with "@name ". *
- Returns:
- name (string) — endpoint name without the "@" sigil.
- prompt (string) — remaining input after the @name token; may be empty.
- ok (bool) — false when no @mention is present. *
- Example:
- name, prompt, ok := ParseAtMention("@pi2 write a Go parser")
- // name="pi2", prompt="write a Go parser", ok=true *
- _, _, ok = ParseAtMention("just a normal prompt")
- // ok=false
func ParseEmbedderFlags ¶
* ParseEmbedderFlags extracts --embedder and --embedder-url values from args.
- Unrecognised tokens are silently ignored. Both values default to "". *
- Parameters:
- args ([]string) — remaining arguments after the store name. *
- Returns:
- kind (string) — embedder kind: "ollama", "encoderfile", or "".
- url (string) — embedder base URL, or "". *
- Example:
- kind, url := ParseEmbedderFlags([]string{"--embedder", "encoderfile", "--embedder-url", "http://localhost:8080"})
func PrintOllamaEnv ¶
* PrintOllamaEnv writes the currently active Ollama environment variables to
- out, skipping any that are not set. It never modifies the environment. *
- Parameters:
- out (io.Writer) — destination for the variable listing. *
- Example:
- PrintOllamaEnv(os.Stdout)
func ProbeEncoderfile ¶
* ProbeEncoderfile returns true if an Encoderfile server is reachable at
- baseURL by calling GET /health. *
- Parameters:
- baseURL (string) — Encoderfile HTTP base URL, e.g. "http://localhost:8080". *
- Returns:
- bool — true when the server responds with HTTP 200. *
- Example:
- if ProbeEncoderfile("http://localhost:8080") {
- fmt.Println("Encoderfile is running")
- }
func ProbeEncoderfileModel ¶
* ProbeEncoderfileModel queries the Encoderfile server's GET /model endpoint
- and returns the model_id. Returns an error if the server is unreachable or
- returns an unexpected response. *
- Parameters:
- baseURL (string) — Encoderfile HTTP base URL. *
- Returns:
- string — model_id from the server, e.g. "nomic-embed-text-v1_5".
- error — on transport failure, non-200 status, or missing model_id. *
- Example:
- id, err := ProbeEncoderfileModel("http://localhost:8080")
- fmt.Println(id) // "nomic-embed-text-v1_5"
func ProbeOllama ¶
ProbeOllama returns true if an Ollama server is reachable at baseURL.
func RegisterBuiltinTools ¶
func RegisterBuiltinTools(r *ToolRegistry, a *Agent)
* RegisterBuiltinTools registers all of Harvey's built-in schema-based tools
- with the given registry. Every handler enforces the workspace boundary,
- agent permission checks, safe-type assertions, and the output size cap. *
- Parameters:
- r (*ToolRegistry) — registry to populate.
- a (*Agent) — agent providing workspace, config, and permissions. *
- Example:
- RegisterBuiltinTools(agent.Tools, agent)
func ResolveSessionsDir ¶
* ResolveSessionsDir returns the absolute path to the sessions directory,
- creating it if it does not exist. customPath overrides the default location
- (harvey/sessions/ inside the workspace); pass an empty string for the default. *
- Parameters:
- ws (*Workspace) — the Harvey workspace.
- customPath (string) — override path; may be relative (to workspace root) or absolute. *
- Returns:
- string — absolute path to the sessions directory.
- error — if the directory cannot be created. *
- Example:
- dir, err := ResolveSessionsDir(ws, cfg.SessionsDir)
func RunSkillWizard ¶
* RunSkillWizard interactively collects skill metadata from the user,
- opens $EDITOR/$VISUAL for the instructions body, and writes the resulting
- SKILL.md into ws at .agents/skills/<name>/SKILL.md. *
- Short fields (name, description, license, compatibility, author, version,
- trigger) are collected via the provided reader. The instructions body is
- edited in $VISUAL or $EDITOR (falling back to vi). *
- Parameters:
- ws (*Workspace) — workspace for path resolution and file writes.
- reader (*bufio.Reader) — reads short field responses; use bufio.NewReaderSize(os.Stdin, 1).
- out (io.Writer) — destination for prompts and status messages. *
- Returns:
- relPath (string) — relative path to the created SKILL.md, e.g. ".agents/skills/my-skill/SKILL.md".
- err (error) — on validation failure, editor error, or write failure. *
- Example:
- relPath, err := RunSkillWizard(ws, bufio.NewReaderSize(os.Stdin, 1), os.Stdout)
- if err != nil { log.Fatal(err) }
- fmt.Println("created:", relPath)
func SaveModelAliases ¶
* SaveModelAliases writes the model_aliases map back to harvey.yaml,
- merging with any existing content so that unrelated keys are preserved. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is written.
- cfg (*Config) — source of ModelAliases to persist. *
- Returns:
- error — on path resolution, YAML parse, or file write failure. *
- Example:
- if err := SaveModelAliases(ws, cfg); err != nil {
- fmt.Println("could not save aliases:", err)
- }
func SaveRAGConfig ¶
* SaveRAGConfig writes the RAG-related config fields back to
- harvey/harvey.yaml, merging with any existing content so that non-RAG keys
- are preserved. *
- Parameters:
- ws (*Workspace) — workspace whose harvey/ directory is written.
- cfg (*Config) — source of RAG fields to persist. *
- Returns:
- error — on path resolution, YAML parse, or file write failure. *
- Example:
- if err := SaveRAGConfig(ws, cfg); err != nil {
- fmt.Println("could not save RAG config:", err)
- }
func SaveRouteConfig ¶
func SaveRouteConfig(ws *Workspace, rr *RouteRegistry) error
* SaveRouteConfig persists rr to agents/routes.json in the workspace,
- creating the directory if necessary. Endpoints are written in alphabetical
- name order for stable diffs. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is written.
- rr (*RouteRegistry) — registry to persist; nil is treated as empty+disabled. *
- Returns:
- error — on path resolution, directory creation, or file write failure. *
- Example:
- if err := SaveRouteConfig(ws, agent.Routes); err != nil {
- fmt.Println("warning:", err)
- }
func SetGlobalAuditBuffer ¶
func SetGlobalAuditBuffer(buf *AuditBuffer)
SetGlobalAuditBuffer sets the global audit buffer used by AuditLog.
func SortedSkillNames ¶
func SortedSkillNames(cat SkillCatalog) []string
* SortedSkillNames returns the skill names from cat in sorted order.
- Used to provide deterministic first-match semantics when scanning triggers. *
- Parameters:
- cat (SkillCatalog) — the catalog to sort. *
- Returns:
- []string — skill names in ascending alphabetical order. *
- Example:
- for _, name := range SortedSkillNames(a.Skills) {
- if MatchesTrigger(a.Skills[name], input) { ... }
- }
func StartOllamaService ¶
func StartOllamaService() error
StartOllamaService launches "ollama serve" as a background process and waits up to 5 seconds for it to become reachable.
func ValidSkillName ¶
* ValidSkillName reports whether name is a valid skill identifier:
- lowercase letters, digits, and hyphens only, non-empty. *
- Parameters:
- name (string) — candidate skill name. *
- Returns:
- bool — true when name matches ^[a-z0-9-]+$. *
- Example:
- ValidSkillName("go-review") // true
- ValidSkillName("My Skill") // false
Types ¶
type Agent ¶
type Agent struct {
Client LLMClient
Config *Config
History []Message
Workspace *Workspace
KB *KnowledgeBase
ModelCache *ModelCache // capability cache for installed Ollama models; nil until initModelCache runs
Rag *RagStore // RAG chunk store; nil when RAG is not configured
RagOn bool // when true, top-K chunks are injected before each Chat call
SessionsDir string // absolute path to the sessions directory
Skills SkillCatalog // skills discovered at startup; nil until loadSkills runs
Recorder *Recorder
In io.Reader // source for interactive prompts; defaults to os.Stdin
PinnedContext string // persists across /clear; re-injected after system prompt
Routes *RouteRegistry // registered remote endpoints; nil when routing not configured
ActiveSkill string // name of the most recently loaded skill; "" when none
ActiveSkillSet string // name of the currently loaded skill-set bundle; "" when none
Tools *ToolRegistry // schema-based tool registry; nil when tools are disabled
AuditBuffer *AuditBuffer // in-memory audit log ring buffer; nil until initialized
// contains filtered or unexported fields
}
* Agent holds the state of an active Harvey session, including the LLM
- backend, conversation history, workspace, knowledge base, and registered
- slash commands. *
- Fields:
- SessionsDir (string) — absolute path to the sessions directory resolved at startup.
- Skills (SkillCatalog) — skills discovered at startup; nil until loadSkills runs. *
- Example:
- cfg := DefaultConfig()
- ws, _ := NewWorkspace(".")
- agent := NewAgent(cfg, ws)
func NewAgent ¶
* NewAgent creates an Agent from cfg and ws with an empty conversation
- history. The knowledge base is opened lazily — it is nil if
- OpenKnowledgeBase has not been called. *
- Parameters:
- cfg (*Config) — runtime configuration.
- ws (*Workspace) — workspace that anchors all file I/O. *
- Returns:
- *Agent — initialised agent ready for Run(). *
- Example:
- ws, _ := NewWorkspace(".")
- agent := NewAgent(DefaultConfig(), ws)
func (*Agent) AddMessage ¶
- AddMessage appends a message to the conversation history. *
- Parameters:
- role (string) — "system", "user", or "assistant".
- content (string) — message body. *
- Example:
- agent.AddMessage("user", "What is the capital of France?")
func (*Agent) CheckDeletePermission ¶
CheckDeletePermission returns true if delete is allowed for the given path.
func (*Agent) CheckExecPermission ¶
CheckExecPermission returns true if exec is allowed for the given path.
func (*Agent) CheckReadPermission ¶
CheckReadPermission returns true if read is allowed for the given path.
func (*Agent) CheckWritePermission ¶
CheckWritePermission returns true if write is allowed for the given path.
func (*Agent) ClearHistory ¶
func (a *Agent) ClearHistory()
* ClearHistory resets the conversation, re-injecting the system prompt if
- one is configured. *
- Example:
- agent.ClearHistory()
func (*Agent) ContinueFromFountain ¶
ContinueFromFountain loads the chat history from a Harvey Fountain session file and appends it to the Agent's current history so the conversation can be resumed. Call this after the system prompt has been added to history.
Parameters:
path (string) — path to a Harvey .fountain session file.
Returns:
int — number of chat turns loaded. error — if the file cannot be parsed.
Example:
n, err := agent.ContinueFromFountain("session.fountain")
fmt.Printf("Loaded %d turns\n", n)
func (*Agent) HasPermission ¶
* HasPermission checks if the given permission is allowed for a path.
- This delegates to the Config's permission system. *
- Parameters:
- path (string) — the path to check (relative to workspace root).
- perm (string) — the permission to check (read, write, exec, delete). *
- Returns:
- bool — true if the permission is allowed. *
- Example:
- if a.HasPermission("src/main.go", PermRead) {
- // read is allowed
- }
func (*Agent) ReplayFromFountain ¶
func (a *Agent) ReplayFromFountain(ctx context.Context, srcPath, outPath string, out io.Writer) error
ReplayFromFountain re-sends each user message from srcPath to the current LLM backend, records fresh responses to a new Fountain file at outPath, and streams progress to out.
Tagged code blocks in replies are applied with backup protection: if a target file already exists it is renamed to <path>.bak.<YYYYMMDD-HHMMSS> before the new content is written. Files that cannot be backed up or written are noted as skipped in the new Fountain recording.
Parameters:
ctx (context.Context) — cancellable context for LLM calls. srcPath (string) — Harvey Fountain session file to replay. outPath (string) — destination for the new session recording. out (io.Writer) — progress and streaming output.
Returns:
error — on parse failure, recorder creation failure, or unrecoverable LLM error.
Example:
err := agent.ReplayFromFountain(ctx, "old.fountain", "new.fountain", os.Stdout)
func (*Agent) Run ¶
* Run prints the startup banner, initialises the workspace and knowledge base,
- runs the backend selection sequence, then starts the interactive REPL. It
- reads from os.Stdin and writes to out. *
- Parameters:
- out (io.Writer) — destination for all REPL output. *
- Returns:
- error — only on fatal startup errors; normal exit returns nil. *
- Example:
- agent := NewAgent(DefaultConfig(), ws)
- if err := agent.Run(os.Stdout); err != nil {
- log.Fatal(err)
- }
type AnyLLMClient ¶
type AnyLLMClient struct {
// contains filtered or unexported fields
}
* AnyLLMClient wraps an anyllm.Provider and implements Harvey's LLMClient
- interface. It bridges any-llm-go's channel-based streaming to Harvey's
- io.Writer-based streaming, and maps anyllm.Usage to ChatStats. *
- Fields:
- provider (anyllm.Provider) — underlying provider (e.g. ollama, anthropic).
- modelName (string) — model name sent in every completion request.
- provName (string) — provider identifier, e.g. "ollama".
- backendURL (string) — base URL for local backends; empty for cloud. *
- Example:
- p, _ := ollama.New()
- client := NewAnyLLMClient(p, "llama3.1:8b", "ollama", "http://localhost:11434")
- stats, err := client.Chat(ctx, history, os.Stdout)
func NewAnyLLMClient ¶
func NewAnyLLMClient(provider anyllm.Provider, modelName, provName, backendURL string) *AnyLLMClient
- NewAnyLLMClient creates an AnyLLMClient wrapping provider. *
- Parameters:
- provider (anyllm.Provider) — underlying any-llm-go provider.
- modelName (string) — model to request in completions.
- provName (string) — short provider name for display (e.g. "ollama").
- backendURL (string) — base URL; pass "" for cloud providers. *
- Returns:
- *AnyLLMClient — ready to use. *
- Example:
- client := NewAnyLLMClient(p, "llama3.1:8b", "ollama", "http://localhost:11434")
func (*AnyLLMClient) BackendURL ¶
func (a *AnyLLMClient) BackendURL() string
- BackendURL returns the base URL for local backends, or "" for cloud providers. *
- Returns:
- string — base URL, e.g. "http://localhost:11434". *
- Example:
- fmt.Println(client.BackendURL()) // "http://localhost:11434"
func (*AnyLLMClient) Chat ¶
func (a *AnyLLMClient) Chat(ctx context.Context, messages []Message, out io.Writer) (ChatStats, error)
* Chat sends the conversation history to the provider, streams reply tokens to
- out, and returns timing and token stats. Harvey's []Message is converted to
- anyllm.Message before dispatch; the provider's channel-based stream is
- drained into out. *
- Parameters:
- ctx (context.Context) — controls the request lifetime.
- messages ([]Message) — full conversation history.
- out (io.Writer) — destination for streamed reply tokens. *
- Returns:
- ChatStats — timing and token counts (zero where provider does not report).
- error — non-nil on transport or API failure. *
- Example:
- stats, err := client.Chat(ctx, agent.History, os.Stdout)
func (*AnyLLMClient) ChatWithTools ¶
func (a *AnyLLMClient) ChatWithTools(ctx context.Context, messages []Message, tools []anyllm.Tool, out io.Writer) (ChatStats, []anyllm.ToolCall, error)
* ChatWithTools sends the conversation history with tool schemas to the
- provider, streams reply tokens to out, and returns accumulated tool calls
- (if the model requests them) alongside timing stats. *
- Parameters:
- ctx (context.Context) — controls the request lifetime.
- messages ([]Message) — full conversation history including tool results.
- tools ([]anyllm.Tool) — tool schemas to send in CompletionParams.
- out (io.Writer) — destination for streamed reply tokens. *
- Returns:
- ChatStats — timing and token counts.
- []anyllm.ToolCall — tool calls requested by the model (nil if none).
- error — non-nil on transport or API failure. *
- Example:
- stats, calls, err := client.ChatWithTools(ctx, history, registry.GetToolSchemas(), os.Stdout)
func (*AnyLLMClient) Close ¶
func (a *AnyLLMClient) Close() error
Close satisfies LLMClient. any-llm-go providers hold no closeable resources.
func (*AnyLLMClient) ModelName ¶
func (a *AnyLLMClient) ModelName() string
- ModelName returns the model name this client sends in every request. *
- Returns:
- string — model name, e.g. "llama3.1:8b". *
- Example:
- fmt.Println(client.ModelName()) // "llama3.1:8b"
func (*AnyLLMClient) Models ¶
func (a *AnyLLMClient) Models(ctx context.Context) ([]string, error)
* Models returns the names of models available on this backend. For providers
- that implement ModelLister the live list is fetched; others return a
- single-element slice containing the configured model name. *
- Parameters:
- ctx (context.Context) — controls the request lifetime. *
- Returns:
- []string — model names.
- error — non-nil on request failure. *
- Example:
- names, err := client.Models(ctx)
func (*AnyLLMClient) Name ¶
func (a *AnyLLMClient) Name() string
Name satisfies LLMClient. Returns "provider (model)".
func (*AnyLLMClient) ProviderName ¶
func (a *AnyLLMClient) ProviderName() string
- ProviderName returns the short provider identifier. *
- Returns:
- string — e.g. "ollama", "anthropic", "openai". *
- Example:
- fmt.Println(client.ProviderName()) // "ollama"
type AnyLLMEmbedder ¶
type AnyLLMEmbedder struct {
// contains filtered or unexported fields
}
* AnyLLMEmbedder wraps an anyllm.EmbeddingProvider and implements Harvey's
- Embedder interface. *
- Example:
- p, _ := ollama.New()
- e, _ := NewAnyLLMEmbedder(p, "nomic-embed-text")
- vec, err := e.Embed("hello world")
func NewAnyLLMEmbedder ¶
func NewAnyLLMEmbedder(provider anyllm.Provider, modelName string) (*AnyLLMEmbedder, error)
* NewAnyLLMEmbedder creates an AnyLLMEmbedder from provider. Returns an error
- if provider does not implement EmbeddingProvider. *
- Parameters:
- provider (anyllm.Provider) — provider to wrap; must implement EmbeddingProvider.
- modelName (string) — embedding model name. *
- Returns:
- *AnyLLMEmbedder — ready to call Embed.
- error — if provider does not support embeddings. *
- Example:
- p, _ := ollama.New()
- e, err := NewAnyLLMEmbedder(p, "nomic-embed-text")
func (*AnyLLMEmbedder) Embed ¶
func (e *AnyLLMEmbedder) Embed(text string) ([]float64, error)
* Embed sends text to the provider's embedding endpoint and returns the
- embedding vector. *
- Parameters:
- text (string) — text to embed. *
- Returns:
- []float64 — embedding vector.
- error — on transport failure or empty response. *
- Example:
- vec, err := e.Embed("The sky is blue")
- fmt.Printf("dims: %d\n", len(vec))
func (*AnyLLMEmbedder) Name ¶
func (e *AnyLLMEmbedder) Name() string
Name satisfies Embedder. Returns the embedding model name.
type AuditAction ¶
type AuditAction string
AuditAction represents the type of action being audited.
const ( // Command-related actions ActionCommand AuditAction = "command" // File operation actions ActionFileRead AuditAction = "file_read" ActionFileWrite AuditAction = "file_write" ActionFileDelete AuditAction = "file_delete" ActionFileList AuditAction = "file_list" // Skill-related actions ActionSkillRun AuditAction = "skill_run" // Security-related actions ActionSecurity AuditAction = "security" )
type AuditBuffer ¶
type AuditBuffer struct {
// contains filtered or unexported fields
}
AuditBuffer is a thread-safe ring buffer for storing audit events.
func NewAuditBuffer ¶
func NewAuditBuffer(capacity int) *AuditBuffer
NewAuditBuffer creates a new AuditBuffer with the specified capacity.
func (*AuditBuffer) Add ¶
func (b *AuditBuffer) Add(event AuditEvent)
Add appends an event to the buffer, overwriting the oldest event if full.
func (*AuditBuffer) Capacity ¶
func (b *AuditBuffer) Capacity() int
Capacity returns the maximum number of events the buffer can hold.
func (*AuditBuffer) Get ¶
func (b *AuditBuffer) Get(n int) []AuditEvent
Get returns the last n events, most recent first.
func (*AuditBuffer) GetAll ¶
func (b *AuditBuffer) GetAll() []AuditEvent
GetAll returns all events in the buffer, most recent first.
func (*AuditBuffer) Log ¶
func (b *AuditBuffer) Log(action AuditAction, details string, status AuditStatus)
Log is a convenience method that creates and adds an event in one call.
func (*AuditBuffer) Size ¶
func (b *AuditBuffer) Size() int
Size returns the current number of events in the buffer.
type AuditEvent ¶
type AuditEvent struct {
Timestamp time.Time // When the event occurred
Action AuditAction // Type of action (command, file_read, etc.)
Details string // Description of what happened (command line, file path, etc.)
Status AuditStatus // Outcome (allowed, denied, error, etc.)
}
AuditEvent represents a single audit log entry.
func (AuditEvent) Format ¶
func (e AuditEvent) Format() string
Format returns a human-readable string representation of the event.
type AuditStatus ¶
type AuditStatus string
AuditStatus represents the outcome of an audited action.
const ( StatusAllowed AuditStatus = "allowed" StatusDenied AuditStatus = "denied" StatusError AuditStatus = "error" StatusSuccess AuditStatus = "success" StatusWarning AuditStatus = "warning" )
type CapabilityStatus ¶
type CapabilityStatus int
* CapabilityStatus records whether a model capability has been confirmed,
- denied, or not yet probed. *
- Values:
- CapUnknown (-1) — not yet probed.
- CapNo (0) — confirmed absent.
- CapYes (1) — confirmed present. *
- Example:
- if cap.SupportsTools == CapYes { fmt.Println("tools supported") }
const ( CapUnknown CapabilityStatus = -1 CapNo CapabilityStatus = 0 CapYes CapabilityStatus = 1 )
func (CapabilityStatus) String ¶
func (c CapabilityStatus) String() string
* String returns a display symbol for the capability status:
- "✓" for yes, "—" for no, "?" for unknown. *
- Returns:
- string — one of "✓", "—", "?". *
- Example:
- fmt.Println(CapYes.String()) // "✓"
type ChatStats ¶
type ChatStats struct {
PromptTokens int
ReplyTokens int
Elapsed time.Duration
TokensPerSec float64
}
* ChatStats holds timing and token-count data returned by a backend after
- each Chat call. Fields are zero for backends that do not report them. *
- Fields:
- PromptTokens (int) — tokens in the prompt/history sent.
- ReplyTokens (int) — tokens in the generated response.
- Elapsed (time.Duration) — wall-clock time for the full call.
- TokensPerSec (float64) — generation throughput (reply tokens / s). *
- Example:
- stats, err := client.Chat(ctx, history, &buf)
- fmt.Println(stats.Format())
func (ChatStats) Format ¶
* Format returns a human-readable one-line summary of the stats, e.g.
- "26 prompt + 42 reply tokens · 8.3s · 5.1 tok/s".
- If token counts are zero (backend does not report them) only elapsed time
- is returned. *
- Returns:
- string — formatted stats line. *
- Example:
- fmt.Println(stats.Format()) // "26 prompt + 42 reply tokens · 8.3s · 5.1 tok/s"
func (ChatStats) FormatWithModels ¶
* FormatWithModels returns a one-line summary that includes the model name(s)
- that handled the turn, reply token count, context (prompt) token count,
- elapsed time, and throughput. Returns an empty string when there are no
- token counts and no model names — used to suppress the stat block when no
- meaningful data is available. *
- Parameters:
- models ([]string) — ordered list of model names, e.g. ["llama3.2:1b", "Ollama (llama3.1:8b)"].
- Pass nil or empty for single-model sessions without routing. *
- Returns:
- string — formatted stat line, or "" when both models and token counts are absent. *
- Example:
- line := stats.FormatWithModels([]string{"llama3.2:1b", "Ollama (llama3.1:8b)"})
- // "llama3.2:1b → Ollama (llama3.1:8b) · 312 reply + 1840 ctx · 18.4s · 16.9 tok/s"
type Chunk ¶
- Chunk is a retrieved text chunk returned by RagStore.Query. *
- Fields:
- ID (int64) — row ID in the chunks table.
- Content (string) — the original ingested text.
- Score (float64) — cosine similarity score [0,1]; 0 when not from Query.
- Source (string) — source file path set at ingest time; empty when unknown. *
- Example:
- chunks, _ := store.Query("sky colour", embedder, 3)
- for _, c := range chunks { fmt.Printf("[%.2f] %s\n", c.Score, c.Content) }
type Command ¶
type Command struct {
Usage string
Description string
UserDefined bool
// Handler is nil for commands handled directly in the REPL (exit, quit).
Handler func(a *Agent, args []string, out io.Writer) error
}
- Command describes a slash command available in the Harvey REPL. *
- Fields:
- Usage (string) — short usage synopsis shown by /help.
- Description (string) — one-line description shown by /help.
- UserDefined (bool) — true for commands generated from compiled skills.
- Handler (func) — called when the command is dispatched; nil for
- commands handled directly in the REPL (exit, quit). *
- Example:
- cmd := &Command{
- Usage: "/greet NAME",
- Description: "Print a greeting",
- Handler: func(a *Agent, args []string, out io.Writer) error {
- fmt.Fprintln(out, "Hello,", args[0])
- return nil
- },
- }
type Concept ¶
* Concept represents a named idea or term that can be linked to projects and
- observations. *
- Example:
- concepts, err := kb.Concepts()
- for _, c := range concepts {
- fmt.Println(c.Name, "-", c.Description)
- }
type Config ¶
type Config struct {
WorkDir string // workspace root; all file I/O is constrained to this tree
SessionsDir string // directory for .spmd session files; empty = harvey/sessions/
KnowledgeDB string // path to knowledge.db; empty = harvey/knowledge.db
AgentsDir string // agents/skills tree root; empty = agents/
CurrentProjectID int64 // ID of the active knowledge-base project (0 = none)
SystemPrompt string // contents of HARVEY.md, injected as the system prompt
OllamaURL string // Ollama base URL (default: http://localhost:11434)
OllamaModel string // currently selected Ollama model
OllamaContextLength int // context window size in tokens; 0 = unknown
Routes []RouteEndpoint // registered remote endpoints; persisted across sessions
RoutingEnabled bool // when false, @mentions are rejected with a warning
AutoRecord bool // record every session to a .spmd file automatically
RecordPath string // file path for auto-recording; empty = auto-generated timestamped name
ContinuePath string // session file to load as pre-history when starting the REPL
ReplayPath string // session file to replay instead of entering the REPL
ReplayOutputPath string // output path for replay recording; empty = auto-generated
ModelCacheDB string // path to model_cache.db; empty = harvey/model_cache.db
RagStores []RagStoreEntry // all registered named RAG stores
RagActive string // name of the currently active store; "" = none
RagEnabled bool // when true, inject top-K chunks before each Chat call
// Security settings
SafeMode bool // when true, only commands in AllowedCommands can be executed via ! or /run
AllowedCommands []string // list of command names permitted when SafeMode is enabled; default: ls, cat, grep, head, tail, wc, find, stat, jq, htmlq, bat, batcat
// Permissions: map from path prefix to list of allowed actions (read, write, exec, delete)
Permissions map[string][]string // e.g., {".": ["read", "write", "exec", "delete"], "src/": ["read"]}
// Timeout settings
RunTimeout time.Duration // timeout for shell commands run via ! or /run; 0 means no timeout
OllamaTimeout time.Duration // HTTP client timeout for local LLM providers (Ollama, Llamafile, llama.cpp); 0 means no timeout
// Model aliases: short name → full Ollama model identifier
ModelAliases map[string]string // e.g. {"qwen-coder": "qwen2.5-coder:7b"}
// Tool settings
ToolsEnabled bool // when true, send tool schemas to models that support it
MaxToolCallsPerTurn int // hard limit on tool call rounds per user turn; 0 = defaultMaxToolCallsPerTurn
MaxOutputBytes int // cap on tool output injected into context; 0 = defaultMaxOutputBytes
}
- Config holds Harvey's runtime configuration. *
- Fields:
- WorkDir (string) — root directory Harvey is allowed to read/write; defaults to ".".
- SessionsDir (string) — directory for session .spmd files; empty = harvey/sessions/.
- KnowledgeDB (string) — path to the knowledge base SQLite file; empty = harvey/knowledge.db.
- AgentsDir (string) — base directory for the agents/skills tree; empty = agents/.
- SystemPrompt (string) — contents of HARVEY.md, injected as the system prompt.
- OllamaURL (string) — Ollama base URL (default: http://localhost:11434).
- OllamaModel (string) — currently selected Ollama model.
- AutoRecord (bool) — record every session to a .spmd file (default true).
- RagStores ([]RagStoreEntry) — all registered named RAG stores.
- RagActive (string) — name of the currently active store; "" = none.
- RagEnabled (bool) — when true, inject top-K chunks before each Chat call. *
- Example:
- cfg := DefaultConfig()
- cfg.WorkDir = "/home/user/myproject"
func DefaultConfig ¶
func DefaultConfig() *Config
func (*Config) ActiveRagStore ¶
func (c *Config) ActiveRagStore() *RagStoreEntry
* ActiveRagStore returns a pointer to the active RagStoreEntry, or nil when
- no store is configured. *
- Returns:
- *RagStoreEntry — the active entry, or nil. *
- Example:
- if e := cfg.ActiveRagStore(); e != nil {
- fmt.Println(e.DBPath)
- }
func (*Config) AddAllowedCommand ¶
- AddAllowedCommand adds a command to the AllowedCommands list if not already present. *
- Parameters:
- cmd (string) — command name to add. *
- Example:
- cfg.AddAllowedCommand("git")
func (*Config) AddOrUpdateRagStore ¶
func (c *Config) AddOrUpdateRagStore(e RagStoreEntry)
* AddOrUpdateRagStore inserts e into the registry if its name is new, or
- replaces the existing entry if one with the same name already exists. *
- Parameters:
- e (RagStoreEntry) — the entry to add or replace. *
- Example:
- cfg.AddOrUpdateRagStore(RagStoreEntry{Name: "golang", DBPath: "agents/rag/golang.db"})
func (*Config) AddPermission ¶
* AddPermission adds a permission to a path prefix.
- Creates the prefix entry if it doesn't exist. *
- Parameters:
- prefix (string) — the path prefix.
- perm (string) — the permission to add (read, write, exec, delete). *
- Example:
- cfg.AddPermission("src/", "read")
func (*Config) HasPermission ¶
* HasPermission checks if the given permission is allowed for a path.
- It checks the most specific matching path prefix first. *
- Parameters:
- path (string) — the path to check (relative to workspace root).
- perm (string) — the permission to check (read, write, exec, delete). *
- Returns:
- bool — true if the permission is allowed. *
- Example:
- if cfg.HasPermission("src/main.go", "read") {
- // read is allowed
- }
func (*Config) IsCommandAllowed ¶
* IsCommandAllowed returns true if cmd is in the AllowedCommands list.
- When SafeMode is false, all commands are allowed (returns true).
- When SafeMode is true, only commands in AllowedCommands are permitted. *
- Parameters:
- cmd (string) — the command name to check. *
- Returns:
- bool — true if the command is allowed. *
- Example:
- if !cfg.IsCommandAllowed("git") {
- fmt.Println("git is not allowed in safe mode")
- }
func (*Config) PermissionString ¶
- PermissionString returns a comma-separated string of permissions for a prefix. *
- Parameters:
- prefix (string) — the path prefix. *
- Returns:
- string — comma-separated permissions, or "none" if no permissions.
func (*Config) RagStoreByName ¶
func (c *Config) RagStoreByName(name string) *RagStoreEntry
* RagStoreByName returns a pointer to the named store entry, or nil when not
- found. *
- Parameters:
- name (string) — store name to look up. *
- Returns:
- *RagStoreEntry — matching entry, or nil. *
- Example:
- if e := cfg.RagStoreByName("golang"); e != nil {
- fmt.Println(e.EmbeddingModel)
- }
func (*Config) RemoveAllowedCommand ¶
* RemoveAllowedCommand removes a command from the AllowedCommands list.
- It is a no-op if the command is not present. *
- Parameters:
- cmd (string) — command name to remove. *
- Example:
- cfg.RemoveAllowedCommand("git")
func (*Config) RemovePermission ¶
* RemovePermission removes a permission from a path prefix.
- It is a no-op if the prefix or permission doesn't exist. *
- Parameters:
- prefix (string) — the path prefix.
- perm (string) — the permission to remove. *
- Example:
- cfg.RemovePermission("src/", "write")
func (*Config) RemoveRagStore ¶
* RemoveRagStore removes the store with the given name from the registry.
- It is a no-op when no store with that name exists. *
- Parameters:
- name (string) — name of the store to remove. *
- Example:
- cfg.RemoveRagStore("research-llm")
func (*Config) ResetAllowedCommands ¶
func (c *Config) ResetAllowedCommands()
- ResetAllowedCommands replaces AllowedCommands with the default list. *
- Example:
- cfg.ResetAllowedCommands()
func (*Config) ResetPermissions ¶
func (c *Config) ResetPermissions()
- ResetPermissions resets permissions to the default (full access to root). *
- Example:
- cfg.ResetPermissions()
func (*Config) ResolveModelAlias ¶
* ResolveModelAlias returns the full Ollama model identifier for alias, or
- alias itself when no mapping is defined. Lookup is case-insensitive. *
- Parameters:
- alias (string) — short name typed by the user (e.g. "qwen-coder"). *
- Returns:
- string — full model identifier (e.g. "qwen2.5-coder:7b") or alias unchanged. *
- Example:
- full := cfg.ResolveModelAlias("qwen-coder") // → "qwen2.5-coder:7b"
- same := cfg.ResolveModelAlias("llama3.2:latest") // → "llama3.2:latest"
func (*Config) SetPermission ¶
* SetPermission sets the permissions for a path prefix.
- Replaces any existing permissions for that prefix. *
- Parameters:
- prefix (string) — the path prefix (e.g., "src/", ".", "docs/"").
- perms ([]string) — list of permissions (read, write, exec, delete). *
- Example:
- cfg.SetPermission("src/", []string{"read"})
type Embedder ¶
- Embedder produces vector embeddings for text strings. *
- Methods:
- Embed(text string) ([]float64, error) — return a vector for text.
- Name() string — return the embedding model name. *
- Example:
- var e Embedder = NewOllamaEmbedder("http://localhost:11434", "nomic-embed-text")
- vec, err := e.Embed("hello world")
func NewEmbedderForEntry ¶
func NewEmbedderForEntry(entry *RagStoreEntry, ollamaURL string) Embedder
* NewEmbedderForEntry constructs the correct Embedder for entry based on its
- EmbedderKind field. "encoderfile" uses EncoderfileEmbedder; anything else
- (including "" and "ollama") uses OllamaEmbedder. *
- Parameters:
- entry (*RagStoreEntry) — store configuration entry.
- ollamaURL (string) — Ollama base URL, used when kind is "ollama". *
- Returns:
- Embedder — the appropriate embedder for this entry. *
- Example:
- emb := NewEmbedderForEntry(cfg.ActiveRagStore(), cfg.OllamaURL)
- vec, err := emb.Embed("hello world")
type EncoderfileEmbedder ¶
type EncoderfileEmbedder struct {
// contains filtered or unexported fields
}
* EncoderfileEmbedder implements Embedder using an Encoderfile binary's
- HTTP REST endpoint. The binary must be a model of type "embedding"
- built with encoderfile. It is scoped to one Encoderfile server. *
- Example:
- e := NewEncoderfileEmbedder("http://localhost:8080", "nomic-embed-text-v1_5")
- vec, err := e.Embed("hello world")
func NewEncoderfileEmbedder ¶
func NewEncoderfileEmbedder(baseURL, modelName string) *EncoderfileEmbedder
* NewEncoderfileEmbedder returns an EncoderfileEmbedder targeting the
- given Encoderfile server. modelName must match the model_id from the
- server's GET /model response; use ProbeEncoderfileModel to fetch it. *
- Parameters:
- baseURL (string) — Encoderfile HTTP base URL, e.g. "http://localhost:8080".
- modelName (string) — model_id that identifies this embedding model. *
- Returns:
- *EncoderfileEmbedder — ready to call Embed. *
- Example:
- e := NewEncoderfileEmbedder("http://localhost:8080", "nomic-embed-text-v1_5")
func (*EncoderfileEmbedder) Embed ¶
func (e *EncoderfileEmbedder) Embed(text string) ([]float64, error)
* Embed sends text to the Encoderfile server's POST /predict endpoint and
- returns the embedding vector for the first (CLS) token, which is the
- standard sentence representation for BERT-style encoder models. *
- Parameters:
- text (string) — text to embed. *
- Returns:
- []float64 — embedding vector.
- error — on transport failure, non-200 status, or empty response. *
- Example:
- vec, err := e.Embed("The sky is blue")
- fmt.Printf("dims: %d\n", len(vec))
func (*EncoderfileEmbedder) Name ¶
func (e *EncoderfileEmbedder) Name() string
Name satisfies Embedder. Returns the model name used to identify this embedder.
type KBSearchResult ¶
- KBSearchResult holds one row returned by Search. *
- Fields:
- Kind (string) — observation kind ("note", "finding", etc.) or "project" / "concept".
- Label (string) — project name for observations; entity name for projects and concepts.
- Snippet (string) — observation body; or description for projects and concepts. *
- Example:
- results, _ := kb.Search("WAL mode")
- for _, r := range results {
- fmt.Printf("[%s] %s — %s\n", r.Kind, r.Label, r.Snippet)
- }
type KnowledgeBase ¶
type KnowledgeBase struct {
// contains filtered or unexported fields
}
* KnowledgeBase is a SQLite3-backed store for projects, observations, and
- concepts within a Harvey workspace. The database file lives at
- <workspace>/harvey/knowledge.db (or a path overridden in harvey.yaml) and
- is created automatically on first use. *
- Example:
- kb, err := OpenKnowledgeBase(ws, "")
- if err != nil {
- log.Fatal(err)
- }
- defer kb.Close()
func OpenKnowledgeBase ¶
func OpenKnowledgeBase(ws *Workspace, customPath string) (*KnowledgeBase, error)
* OpenKnowledgeBase opens (or creates) the SQLite knowledge base. customPath
- overrides the default location (harvey/knowledge.db inside the workspace);
- pass an empty string to use the default. The schema is applied on every open
- so that tables are created on first use without manual migration. *
- Parameters:
- ws (*Workspace) — the Harvey workspace that owns the database file.
- customPath (string) — override path; empty = harvey/knowledge.db. *
- Returns:
- *KnowledgeBase — ready-to-use knowledge base handle.
- error — if the database file cannot be opened or the schema
- cannot be applied. *
- Example:
- kb, err := OpenKnowledgeBase(ws, "")
- if err != nil {
- log.Fatal(err)
- }
- defer kb.Close()
func (*KnowledgeBase) AddConcept ¶
func (kb *KnowledgeBase) AddConcept(name, description string) (int64, error)
* AddConcept inserts a new concept or, if a concept with the same name exists,
- returns its ID unchanged. *
- Parameters:
- name (string) — unique concept name.
- description (string) — human-readable explanation of the concept. *
- Returns:
- int64 — ID of the inserted or existing concept.
- error — on database failure. *
- Example:
- id, err := kb.AddConcept("WAL mode", "SQLite write-ahead logging for concurrency")
func (*KnowledgeBase) AddObservation ¶
func (kb *KnowledgeBase) AddObservation(projectID int64, kind, body string) (int64, error)
- AddObservation inserts a new observation for a project and returns its ID. *
- Parameters:
- projectID (int64) — ID of the owning project.
- kind (string) — one of: note, finding, decision, question, hypothesis.
- body (string) — the observation text. *
- Returns:
- int64 — ID of the new observation.
- error — if kind is invalid or the insert fails. *
- Example:
- id, err := kb.AddObservation(1, "finding", "WAL mode doubles write throughput")
func (*KnowledgeBase) AddProject ¶
func (kb *KnowledgeBase) AddProject(name, description string) (int64, error)
* AddProject inserts a new project row and returns its auto-assigned ID. If a
- project with the same name already exists, its ID is returned instead. *
- Parameters:
- name (string) — unique project name.
- description (string) — short human-readable description. *
- Returns:
- int64 — ID of the inserted or existing project.
- error — on database failure. *
- Example:
- id, err := kb.AddProject("harvey", "Terminal coding agent backed by Ollama")
func (*KnowledgeBase) Close ¶
func (kb *KnowledgeBase) Close() error
* Close releases the database connection. It should be deferred immediately
- after a successful OpenKnowledgeBase call. *
- Returns:
- error — from the underlying sql.DB.Close call. *
- Example:
- kb, _ := OpenKnowledgeBase(ws)
- defer kb.Close()
func (*KnowledgeBase) Concepts ¶
func (kb *KnowledgeBase) Concepts() ([]Concept, error)
- Concepts returns all concepts ordered by name. *
- Returns:
- []Concept — all concept rows; empty (not nil) if none exist.
- error — on database failure. *
- Example:
- concepts, err := kb.Concepts()
- for _, c := range concepts {
- fmt.Println(c.Name)
- }
func (*KnowledgeBase) FormatMarkdown ¶
func (kb *KnowledgeBase) FormatMarkdown(projectID int64) (string, error)
* FormatMarkdown returns the knowledge base contents as Markdown, suitable for
- injecting into a conversation as context. When projectID > 0 only that project
- is included; when projectID == 0 all projects are included. Each project gets
- a ## heading, and observations are listed with their kind in bold. *
- Parameters:
- projectID (int64) — project to export; 0 = all projects. *
- Returns:
- string — Markdown-formatted knowledge base contents; "" if no data.
- error — on database failure. *
- Example:
- md, err := kb.FormatMarkdown(0) // all projects
- md, err := kb.FormatMarkdown(1) // project id=1 only
func (*KnowledgeBase) LinkObservationConcept ¶
func (kb *KnowledgeBase) LinkObservationConcept(observationID, conceptID int64) error
* LinkObservationConcept associates an observation with a concept. Duplicate
- links are silently ignored. *
- Parameters:
- observationID (int64) — ID of the observation.
- conceptID (int64) — ID of the concept. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.LinkObservationConcept(obsID, conceptID)
func (*KnowledgeBase) LinkProjectConcept ¶
func (kb *KnowledgeBase) LinkProjectConcept(projectID, conceptID int64) error
* LinkProjectConcept associates a project with a concept. Duplicate links are
- silently ignored. *
- Parameters:
- projectID (int64) — ID of the project.
- conceptID (int64) — ID of the concept. *
- Returns:
- error — on database failure. *
- Example:
- err := kb.LinkProjectConcept(projectID, conceptID)
func (*KnowledgeBase) Observations ¶
func (kb *KnowledgeBase) Observations(projectID int64) ([]Observation, error)
- Observations returns all observations for a project, newest first. *
- Parameters:
- projectID (int64) — ID of the project to query. *
- Returns:
- []Observation — slice of matching rows; empty (not nil) if none exist.
- error — on database failure. *
- Example:
- obs, err := kb.Observations(1)
- for _, o := range obs {
- fmt.Printf("[%s] %s\n", o.Kind, o.Body)
- }
func (*KnowledgeBase) Path ¶
func (kb *KnowledgeBase) Path() string
Path returns the absolute path of the open knowledge base file.
func (*KnowledgeBase) ProjectByName ¶
func (kb *KnowledgeBase) ProjectByName(name string) (*Project, error)
- ProjectByName returns the project with the given name, or nil if not found. *
- Parameters:
- name (string) — exact project name. *
- Returns:
- *Project — the matching project, or nil.
- error — on database failure. *
- Example:
- p, err := kb.ProjectByName("harvey")
func (*KnowledgeBase) ProjectConcepts ¶
func (kb *KnowledgeBase) ProjectConcepts(projectID int64) ([]Concept, error)
- ProjectConcepts returns all concepts linked to a project, ordered by name. *
- Parameters:
- projectID (int64) — ID of the project. *
- Returns:
- []Concept — linked concepts; empty (not nil) if none.
- error — on database failure. *
- Example:
- concepts, err := kb.ProjectConcepts(1)
func (*KnowledgeBase) Projects ¶
func (kb *KnowledgeBase) Projects() ([]Project, error)
- Projects returns all projects ordered by creation date. *
- Returns:
- []Project — slice of all project rows; empty (not nil) if none exist.
- error — on database failure. *
- Example:
- projects, err := kb.Projects()
- for _, p := range projects {
- fmt.Println(p.Name, p.Status)
- }
func (*KnowledgeBase) Search ¶
func (kb *KnowledgeBase) Search(term string) ([]KBSearchResult, error)
* Search performs a full-text search across observations, projects, and concepts
- using the FTS5 index. Results are ranked by relevance (best match first).
- Returns an error wrapping ErrFTSUnavailable when the FTS index is not present. *
- The term uses standard FTS5 query syntax: multiple words are ANDed, phrases
- can be quoted ("WAL mode"), and prefix search is supported (docker*). *
- Parameters:
- term (string) — FTS5 query term. *
- Returns:
- []KBSearchResult — ranked results; nil if none found.
- error — on query failure or when FTS is unavailable. *
- Example:
- results, err := kb.Search("docker")
- for _, r := range results {
- fmt.Printf("[%-10s] %s — %s\n", r.Kind, r.Label, r.Snippet)
- }
func (*KnowledgeBase) Summary ¶
func (kb *KnowledgeBase) Summary() (string, error)
* Summary returns a human-readable text summary of all projects and their
- recent observations, suitable for printing in the Harvey REPL. *
- Returns:
- string — formatted multi-line summary.
- error — on database failure. *
- Example:
- s, err := kb.Summary()
- fmt.Print(s)
type LLMClient ¶
type LLMClient interface {
// Name returns a human-readable identifier shown in the UI.
Name() string
// Chat sends the full conversation history, streams the response to out,
// and returns timing and token-count stats for the call.
Chat(ctx context.Context, messages []Message, out io.Writer) (ChatStats, error)
// Models lists models available on this backend.
Models(ctx context.Context) ([]string, error)
// Close releases any resources held by the client.
Close() error
}
* LLMClient is the interface implemented by each LLM backend (Ollama,
- Llamafile, Anthropic, OpenAI, etc.). *
- Methods:
- Name() string — human-readable backend identifier.
- Chat() func(ctx, messages, out) (ChatStats, error) — send history, stream reply to out.
- Models() func(ctx) ([]string, error) — list available models.
- Close() error — release held resources. *
- Example:
- var c LLMClient = NewOllamaClient("http://localhost:11434", "llama3")
- stats, err := c.Chat(ctx, history, os.Stdout)
type Message ¶
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
ToolCalls []anyllm.ToolCall `json:"tool_calls,omitempty"` // assistant → tool requests
ToolCallID string `json:"tool_call_id,omitempty"` // tool → result correlation
}
- Message represents a single chat message exchanged with a backend. *
- Fields:
- Role (string) — "system", "user", or "assistant".
- Content (string) — the message body. *
- Example:
- msg := Message{Role: "user", Content: "Hello!"}
type ModelCache ¶
type ModelCache struct {
// contains filtered or unexported fields
}
* ModelCache is a SQLite3-backed store for Ollama model capability metadata.
- The database file lives at harvey/model_cache.db inside the workspace and
- is created automatically on first use. *
- Example:
- mc, err := OpenModelCache(ws, "")
- if err != nil {
- log.Fatal(err)
- }
- defer mc.Close()
func OpenModelCache ¶
func OpenModelCache(ws *Workspace, customPath string) (*ModelCache, error)
* OpenModelCache opens (or creates) the model capability cache. customPath
- overrides the default location (harvey/model_cache.db inside the workspace);
- pass an empty string to use the default. *
- Parameters:
- ws (*Workspace) — the Harvey workspace that owns the cache file.
- customPath (string) — override path; empty = harvey/model_cache.db. *
- Returns:
- *ModelCache — ready-to-use cache handle.
- error — if the file cannot be opened or the schema cannot be applied. *
- Example:
- mc, err := OpenModelCache(ws, "")
- if err != nil {
- log.Fatal(err)
- }
- defer mc.Close()
func (*ModelCache) All ¶
func (mc *ModelCache) All() ([]ModelCapability, error)
- All returns every ModelCapability entry in the cache, ordered by name. *
- Returns:
- []ModelCapability — all cached entries; empty slice when the cache is empty.
- error — non-nil on database read failure. *
- Example:
- caps, err := mc.All()
- for _, c := range caps { fmt.Println(c.Name) }
func (*ModelCache) Close ¶
func (mc *ModelCache) Close() error
* Close releases the database connection. Defer immediately after a
- successful OpenModelCache call. *
- Returns:
- error — from the underlying sql.DB.Close call. *
- Example:
- mc, _ := OpenModelCache(ws, "")
- defer mc.Close()
func (*ModelCache) Delete ¶
func (mc *ModelCache) Delete(name string) error
* Delete removes the cache entry for the named model. It is a no-op when
- the model is not in the cache. *
- Parameters:
- name (string) — full model name, e.g. "llama3.2:latest". *
- Returns:
- error — non-nil on database write failure. *
- Example:
- _ = mc.Delete("llama3.2:latest")
func (*ModelCache) Get ¶
func (mc *ModelCache) Get(name string) (*ModelCapability, error)
* Get returns the cached ModelCapability for the named model, or nil when
- no entry exists. The name must be the full model identifier including tag,
- e.g. "llama3.2:latest". *
- Parameters:
- name (string) — full model name. *
- Returns:
- *ModelCapability — cached entry; nil if not found.
- error — non-nil on database error (not on missing row). *
- Example:
- cap, err := mc.Get("llama3.2:latest")
- if cap == nil { fmt.Println("not cached") }
func (*ModelCache) Path ¶
func (mc *ModelCache) Path() string
Path returns the absolute path of the open model cache file.
func (*ModelCache) Set ¶
func (mc *ModelCache) Set(cap *ModelCapability) error
* Set upserts a ModelCapability into the cache. An existing entry for the
- same model name is completely replaced. ProbeLevel and ProbedAt are written
- as supplied; the caller is responsible for setting them correctly. *
- Parameters:
- cap (*ModelCapability) — capability record to store. *
- Returns:
- error — non-nil on database write failure. *
- Example:
- err := mc.Set(&ModelCapability{Name: "llama3.2:latest", SupportsTools: CapYes})
type ModelCapability ¶
type ModelCapability struct {
Name string
Family string
ParameterSize string
Quantization string
SizeBytes int64
ContextLength int
SupportsTools CapabilityStatus
SupportsEmbed CapabilityStatus
SupportsTaggedBlocks CapabilityStatus
ProbeLevel string
ProbedAt time.Time
}
* ModelCapability holds the cached capability metadata for a single Ollama
- model. It is stored in harvey/model_cache.db and populated by
- FastProbeModel or ThoroughProbeModel. *
- Fields:
- Name (string) — full model identifier, e.g. "llama3.2:latest".
- Family (string) — model family, e.g. "llama".
- ParameterSize (string) — human-readable size, e.g. "8.0B".
- Quantization (string) — quantization level, e.g. "Q4_K_M".
- SizeBytes (int64) — bytes on disk.
- ContextLength (int) — context window in tokens; 0 = unknown.
- SupportsTools (CapabilityStatus) — whether the model supports tool/function calling.
- SupportsEmbed (CapabilityStatus) — whether the model can produce embeddings.
- SupportsTaggedBlocks (CapabilityStatus) — whether the model reliably emits path-tagged code blocks.
- ProbeLevel (string) — "none", "fast", or "thorough".
- ProbedAt (time.Time) — when the last probe ran. *
- Example:
- caps, _ := cache.Get("llama3.2:latest")
- fmt.Printf("tools: %s embed: %s tagged: %s\n", caps.SupportsTools, caps.SupportsEmbed, caps.SupportsTaggedBlocks)
func FastProbeModel ¶
func FastProbeModel(ctx context.Context, baseURL, name string) (*ModelCapability, error)
* FastProbeModel calls /api/show for the named model and applies heuristics
- to determine tool and embedding capability. It does not make additional
- network calls beyond the single /api/show request. *
- Tool support is determined by:
- 1. The Capabilities array from /api/show (authoritative on Ollama >= 0.3).
- 2. Known tool-call template markers as a fallback for older Ollama. *
- Embedding support is determined by:
- 1. A known embedding-model keyword in the model name.
- 2. An empty or absent Template field combined with the keyword heuristic.
- Both signals must agree to avoid false positives from base chat models
- that happen to have a minimal template. *
- Parameters:
- ctx (context.Context) — controls the HTTP request lifetime.
- baseURL (string) — Ollama server base URL, e.g. "http://localhost:11434".
- name (string) — full model name, e.g. "llama3.2:latest". *
- Returns:
- *ModelCapability — populated capability record with ProbeLevel "fast".
- error — non-nil if /api/show fails or the model is not found. *
- Example:
- cap, err := FastProbeModel(ctx, "http://localhost:11434", "llama3.2:latest")
- fmt.Printf("tools: %s embed: %s\n", cap.SupportsTools, cap.SupportsEmbed)
func ThoroughProbeModel ¶
func ThoroughProbeModel(ctx context.Context, baseURL, name string) (*ModelCapability, error)
* ThoroughProbeModel runs FastProbeModel and then makes a live /api/embed
- request to confirm or deny embedding support definitively. A successful
- response with a non-empty embeddings array sets SupportsEmbed = CapYes;
- any error or empty response sets it to CapNo. Tool support is not re-tested
- beyond what FastProbeModel determines — the capabilities API is authoritative. *
- Parameters:
- ctx (context.Context) — controls the HTTP request lifetime.
- baseURL (string) — Ollama server base URL.
- name (string) — full model name. *
- Returns:
- *ModelCapability — populated capability record with ProbeLevel "thorough".
- error — non-nil if FastProbeModel fails; embed test errors are
- absorbed into SupportsEmbed = CapNo rather than returned. *
- Example:
- cap, err := ThoroughProbeModel(ctx, "http://localhost:11434", "nomic-embed-text")
- fmt.Printf("embed: %s\n", cap.SupportsEmbed)
type ModelDetail ¶
type ModelDetail struct {
ModelSummary
ContextLength int
RawParameters string
Template string
Capabilities []string // e.g. ["completion", "tools", "vision"]; nil on older Ollama
}
* ModelDetail holds the full inspection output for a single Ollama model,
- extending ModelSummary with context-window size and Modelfile parameters. *
- Fields:
- ModelSummary — embedded summary fields.
- ContextLength (int) — context window in tokens (0 if not reported).
- RawParameters (string) — raw parameter block from the Modelfile.
- Template (string) — chat template string. *
- Example:
- detail, _ := client.ShowModel(ctx, "llama3.1:8b")
- fmt.Printf("context: %d tokens\n", detail.ContextLength)
type ModelSummary ¶
type ModelSummary struct {
Name string
Family string
ParameterSize string
Quantization string
SizeBytes int64
Running bool
}
- ModelSummary holds the key properties of an installed Ollama model. *
- Fields:
- Name (string) — model identifier, e.g. "llama3.1:8b".
- Family (string) — model family, e.g. "llama", "phi", "mistral".
- ParameterSize (string) — human-readable parameter count, e.g. "8.0B".
- Quantization (string) — quantization level, e.g. "Q4_K_M".
- SizeBytes (int64) — bytes consumed on disk.
- Running (bool) — true when the model is currently loaded by Ollama. *
- Example:
- summaries, _ := client.ModelSummaries(ctx)
- for _, s := range summaries { fmt.Println(s.Name) }
type Observation ¶
* Observation represents a single timestamped note, finding, decision,
- question, or hypothesis attached to a project. *
- Example:
- obs, err := kb.Observations(projectID)
- for _, o := range obs {
- fmt.Printf("[%s] %s\n", o.Kind, o.Body)
- }
type OllamaClient ¶
type OllamaClient struct {
// contains filtered or unexported fields
}
OllamaClient is a utility type for Ollama-specific operations (model inspection, capability probing) that are not part of the LLMClient interface. For chat and embeddings use newOllamaLLMClient instead.
func NewOllamaClient ¶
func NewOllamaClient(baseURL, model string) *OllamaClient
NewOllamaClient returns an OllamaClient for Ollama-specific utility calls (ShowModel, ModelSummaries, probing). Pass model="" when only inspecting.
func (*OllamaClient) ModelSummaries ¶
func (o *OllamaClient) ModelSummaries(ctx context.Context) ([]ModelSummary, error)
* ModelSummaries returns a ModelSummary for every model installed on the
- Ollama server. It also marks which models are currently loaded (running)
- by querying /api/ps. *
- Parameters:
- ctx (context.Context) — controls the HTTP request lifetime. *
- Returns:
- []ModelSummary — one entry per installed model, sorted as Ollama returns them.
- error — non-nil if the /api/tags request fails. *
- Example:
- summaries, err := client.ModelSummaries(ctx)
func (*OllamaClient) ShowModel ¶
func (o *OllamaClient) ShowModel(ctx context.Context, model string) (ModelDetail, error)
* ShowModel fetches the full detail for a single installed model by calling
- /api/show. The context window length is extracted from the model_info
- metadata by searching for any key ending in ".context_length". *
- Parameters:
- ctx (context.Context) — controls the HTTP request lifetime.
- model (string) — model name, e.g. "llama3.1:8b". *
- Returns:
- ModelDetail — full model detail; zero value on error.
- error — non-nil if the request fails or the model is not found. *
- Example:
- detail, err := client.ShowModel(ctx, "llama3.1:8b")
- fmt.Printf("context: %d tokens\n", detail.ContextLength)
type OllamaEmbedder ¶
type OllamaEmbedder struct {
// contains filtered or unexported fields
}
* OllamaEmbedder implements Embedder using Ollama's /api/embed endpoint.
- It is scoped to a single embedding model on one Ollama server. *
- Example:
- e := NewOllamaEmbedder("http://localhost:11434", "nomic-embed-text")
- vec, err := e.Embed("The sky is blue")
func NewOllamaEmbedder ¶
func NewOllamaEmbedder(baseURL, model string) *OllamaEmbedder
* NewOllamaEmbedder returns an OllamaEmbedder targeting the given Ollama
- server and embedding model. *
- Parameters:
- baseURL (string) — Ollama server base URL, e.g. "http://localhost:11434".
- model (string) — embedding model name, e.g. "nomic-embed-text". *
- Returns:
- *OllamaEmbedder — ready to call Embed. *
- Example:
- e := NewOllamaEmbedder("http://localhost:11434", "nomic-embed-text")
func (*OllamaEmbedder) Embed ¶
func (e *OllamaEmbedder) Embed(text string) ([]float64, error)
* Embed sends text to Ollama's /api/embed endpoint and returns the embedding
- vector. Returns an error if the server is unreachable, returns a non-200
- status, or returns no embeddings. *
- Parameters:
- ctx (context.Context) — controls the HTTP request lifetime.
- text (string) — text to embed. *
- Returns:
- []float64 — embedding vector from the model.
- error — on transport failure, HTTP error, or empty response. *
- Example:
- vec, err := e.Embed(ctx, "The sky is blue")
- fmt.Printf("dims: %d\n", len(vec))
func (*OllamaEmbedder) Name ¶
func (e *OllamaEmbedder) Name() string
- Name returns the embedding model name, satisfying the Embedder interface. *
- Returns:
- string — model name, e.g. "nomic-embed-text". *
- Example:
- fmt.Println(e.Name()) // "nomic-embed-text"
type PlaybackTurn ¶
type PlaybackTurn struct {
UserInput string // USER's message text
ModelReply string // model's original response (kept for comparison in replay)
}
PlaybackTurn holds one chat exchange extracted from a Harvey Fountain file.
type Project ¶
- Project represents a single project row in the knowledge base. *
- Example:
- projects, err := kb.Projects()
- for _, p := range projects {
- fmt.Printf("%d %s [%s]\n", p.ID, p.Name, p.Status)
- }
type RagStore ¶
type RagStore struct {
// contains filtered or unexported fields
}
* RagStore is a SQLite-backed store for text chunks and their vector
- embeddings. The database is scoped to one embedding model; mixing
- models in the same database is prevented by an explicit consistency check. *
- Example:
- store, err := NewRagStore("rag_nomic_v1.db", "nomic-embed-text")
- if err != nil { log.Fatal(err) }
func NewRagStore ¶
* NewRagStore opens (or creates) the RAG SQLite database at dbPath and
- associates it with embeddingModel. The schema is applied on every open so
- that the table is created on first use without manual migration. *
- Parameters:
- dbPath (string) — path to the SQLite database file.
- embeddingModel (string) — name of the embedding model used to produce
- vectors in this database; used for consistency
- checks on every Ingest and Query call. *
- Returns:
- *RagStore — ready-to-use store.
- error — if the file cannot be opened or the schema cannot be applied. *
- Example:
- store, err := NewRagStore("rag_nomic_v1.db", "nomic-embed-text")
func (*RagStore) Close ¶
- Close releases the database connection held by the RagStore. *
- Returns:
- error — if the database cannot be closed cleanly. *
- Example:
- if err := store.Close(); err != nil {
- log.Println("rag store close:", err)
- }
func (*RagStore) Count ¶
- Count returns the total number of chunks stored in the database. *
- Returns:
- int64 — total chunk count.
- error — on database failure. *
- Example:
- n, _ := store.Count()
- fmt.Printf("store has %d chunks\n", n)
func (*RagStore) Ingest ¶
* Ingest embeds each text string using embedder and stores the resulting
- vectors in a single transaction. Returns an error if the embedder's name
- does not match the store's embedding model. *
- Parameters:
- source (string) — file path or identifier recorded alongside each chunk;
- pass "" when the source is not known.
- texts ([]string) — text strings to embed and store.
- embedder (Embedder) — must satisfy embedder.Name() == store's model name. *
- Returns:
- error — on model mismatch, embedding failure, or database write failure. *
- Example:
- err := store.Ingest("harvey/README.md", []string{"The sky is blue"}, embedder)
func (*RagStore) Query ¶
* Query embeds query using embedder, computes cosine similarity against every
- stored chunk, and returns the topK highest-scoring chunks in descending order.
- Returns an error if the embedder's name does not match the store's model. *
- Parameters:
- query (string) — text to find similar chunks for.
- embedder (Embedder) — must satisfy embedder.Name() == store's model name.
- topK (int) — maximum number of chunks to return. *
- Returns:
- []Chunk — up to topK chunks ordered by descending similarity score.
- error — on model mismatch, embedding failure, or database read failure. *
- Example:
- chunks, err := store.Query("What colour is the sky?", embedder, 3)
type RagStoreEntry ¶
type RagStoreEntry struct {
Name string
DBPath string
EmbeddingModel string
ModelMap map[string]string
EmbedderKind string // "ollama" (default) or "encoderfile"
EmbedderURL string // base URL for the embedder when EmbedderKind == "encoderfile"
}
- RagStoreEntry describes one named RAG knowledge store in the registry. *
- Fields:
- Name (string) — short identifier used with /rag switch and /rag new.
- DBPath (string) — path to the SQLite database, relative to workspace root.
- EmbeddingModel (string) — embedding model name bound to this store.
- ModelMap (map[string]string) — generation model → embedding model overrides.
- EmbedderKind (string) — "ollama" (default) or "encoderfile".
- EmbedderURL (string) — base URL for the embedder; used when EmbedderKind is "encoderfile". *
- Example:
- e := RagStoreEntry{Name: "golang", DBPath: "agents/rag/golang.db", EmbeddingModel: "nomic-embed-text"}
- e2 := RagStoreEntry{Name: "docs", DBPath: "agents/rag/docs.db", EmbeddingModel: "nomic-embed-text-v1_5",
- EmbedderKind: "encoderfile", EmbedderURL: "http://localhost:8080"}
type Recorder ¶
type Recorder struct {
// contains filtered or unexported fields
}
Recorder writes a Harvey session to a Fountain screenplay source file, using append-writes so in-progress sessions survive crashes.
Three characters appear in the script:
- USER — the human operator (name from $USER env, ALL CAPS)
- HARVEY — the agent program
- MODEL — the LLM backend (model name, ALL CAPS, e.g. GEMMA4)
Example:
r, err := NewRecorder("session.fountain", "Ollama (gemma4:latest)", "/home/user/proj")
if err != nil { log.Fatal(err) }
defer r.Close()
r.RecordTurnWithStats("Hi", "Hello!", stats, []string{"Ollama (gemma4:latest)"}, "")
r.StartAgentScene("Harvey proposes to write 1 file.")
r.RecordAgentAction("write", "hello.bash", "yes", "ok")
func NewRecorder ¶
NewRecorder creates (or truncates) the Fountain file at path, writes the title page and FADE IN:, and returns a ready-to-use Recorder.
Parameters:
path (string) — .fountain file path for the session script. model (string) — backend string from Client.Name(), e.g. "Ollama (gemma4:latest)". workspace (string) — absolute path of the Harvey workspace root.
Returns:
*Recorder — open recorder; caller must call Close() when done. error — if the file cannot be created or the header cannot be written.
Example:
r, err := NewRecorder("harvey-session.fountain", "Ollama (gemma4:latest)", "/home/user/proj")
func (*Recorder) Close ¶
Close writes THE END. and closes the session file. After Close, the Recorder must not be used.
Returns:
error — if the file cannot be closed.
Example:
defer r.Close()
func (*Recorder) Path ¶
Path returns the file path this recorder is writing to.
Returns:
string — the file path passed to NewRecorder.
Example:
fmt.Println(r.Path()) // "/home/user/harvey-session.fountain"
func (*Recorder) RecordAgentAction ¶
RecordAgentAction records one agent action as HARVEY proposing, USER confirming, and a note with the outcome.
Parameters:
kind (string) — "write", "run", etc. target (string) — file path or command line. userChoice (string) — "yes", "no", "all", or "quit". outcome (string) — "ok", "skipped", "aborted", or "error: <msg>".
Returns:
error — if the write fails.
Example:
r.RecordAgentAction("write", "testout/hello.bash", "yes", "ok")
func (*Recorder) RecordShellCommand ¶
RecordShellCommand appends a shell-execution scene to the recording.
Scene structure:
INT. SHELL {TIMESTAMP}
{USER}
! cmdLine ← dialogue (the command the user ran)
SHELL
(output text) ← dialogue (combined stdout+stderr)
[[shell: cmdLine — exit N]] ← Fountain note with exit code
Parameters:
cmdLine (string) — the shell command as typed by the user (without "!"). output (string) — combined stdout+stderr captured from the command. exitCode (int) — process exit code; 0 means success.
Returns:
error — if the write fails.
Example:
r.RecordShellCommand("git status", "On branch main\n...", 0)
func (*Recorder) RecordSkillLoad ¶
RecordSkillLoad appends a skill-activation scene to the recording.
Scene structure:
INT. SKILL {NAME} {TIMESTAMP}
Harvey executes the {name} skill. ← action (Harvey's action)
{description} ← action (what the skill does)
{NAME}
{body} ← dialogue (skill's output/instructions)
The skill name is uppercased to form the Fountain character name, e.g. "go-review" → "GO-REVIEW". The description is rendered as a stage-direction action block so it reads as the skill taking action. The body is the skill's dialogue — what it delivers to Harvey.
Parameters:
name (string) — skill identifier, e.g. "go-review". description (string) — one-line description from the skill's frontmatter. body (string) — full markdown body of the SKILL.md file.
Returns:
error — if the write fails.
Example:
r.RecordSkillLoad("go-review", "Review Go source code for quality issues.", body)
func (*Recorder) RecordTurn ¶
RecordTurn appends a chat turn without stats. See RecordTurnWithStats.
Parameters:
userInput (string) — the user's raw input text. harveyReply (string) — the LLM's complete response text.
Returns:
error — if the write fails.
Example:
err := r.RecordTurn("What is 2+2?", "2 + 2 = 4.")
func (*Recorder) RecordTurnWithStats ¶
func (r *Recorder) RecordTurnWithStats(userInput, harveyReply string, stats ChatStats, models []string, routeStep string) error
RecordTurnWithStats appends a full chat turn as a Fountain scene.
Scene structure:
INT. HARVEY AND {USER} TALKING {TIMESTAMP}
Harvey and {USER} are in chat mode. Model: {MODEL}. Workspace: {ws}.
{USER}
(user's input)
HARVEY
Forwarding to {MODEL}.
{MODEL}
(LLM reply)
Routing to llama3.1:8b ← routeStep action block (omitted when empty)
{models} · {reply} reply + {ctx} ctx · {elapsed} · {tok/s} tok/s
Parameters:
userInput (string) — the user's raw input text.
harveyReply (string) — the LLM's complete response text.
stats (ChatStats) — LLM call stats; omitted when empty.
models ([]string) — ordered model names that handled the turn; nil for single-model sessions.
routeStep (string) — routing decision text, e.g. "Routing to llama3.1:8b" or
"Answered by llama3.2:1b"; empty when routing is disabled.
Returns:
error — if the write fails.
Example:
err := r.RecordTurnWithStats("Hello", "Hi!", stats, []string{"llama3.2:1b", "Ollama (llama3.1:8b)"}, "Routing to llama3.1:8b")
func (*Recorder) Rename ¶
* Rename renames the session file on disk to newPath without ending the
- session. The recorder continues appending to the renamed file.
- On failure it attempts to reopen the original file so recording can continue. *
- Parameters:
- newPath (string) — absolute destination path for the renamed file. *
- Returns:
- error — if sync, close, rename, or reopen fails. *
- Example:
- err := r.Rename("/sessions/my-feature.spmd")
func (*Recorder) StartAgentScene ¶
StartAgentScene opens a new INT. AGENT MODE scene with an action block describing the proposed actions. Call this before the first RecordAgentAction of a group.
Parameters:
description (string) — one-sentence description of what Harvey proposes to do.
Returns:
error — if the write fails.
Example:
r.StartAgentScene("Harvey proposes to write 2 file(s) to the workspace.")
type RouteEndpoint ¶
- RouteEndpoint is a named remote LLM endpoint registered for @mention dispatch. *
- Fields:
- Name (string) — identifier used in @mention syntax (e.g. "pi2").
- URL (string) — endpoint URL; e.g. "ollama://host:port" or "anthropic://".
- Model (string) — default model on this endpoint; empty falls back to Config defaults.
- Kind (RouteKind) — KindOllama, KindLlamafile, KindLlamaCpp, etc. *
- Example:
- ep := RouteEndpoint{Name: "pi2", URL: "ollama://192.168.1.12:11434", Model: "llama3.1:8b", Kind: KindOllama}
type RouteKind ¶
type RouteKind string
RouteKind identifies the protocol used to reach a registered endpoint.
const ( // Local providers — no API key required. KindOllama RouteKind = "ollama" KindLlamafile RouteKind = "llamafile" KindLlamaCpp RouteKind = "llamacpp" // Cloud providers — credentials read from environment variables. KindAnthropic RouteKind = "anthropic" KindDeepSeek RouteKind = "deepseek" KindGemini RouteKind = "gemini" KindMistral RouteKind = "mistral" KindOpenAI RouteKind = "openai" )
func InferRouteKind ¶
- InferRouteKind returns the RouteKind implied by rawURL. *
- Local providers (no API key):
- ollama://host:port, http://, https:// → KindOllama
- llamafile://host:port → KindLlamafile
- llamacpp://host:port → KindLlamaCpp *
- Cloud providers (API key from environment):
- anthropic:// → KindAnthropic (ANTHROPIC_API_KEY)
- deepseek:// → KindDeepSeek (DEEPSEEK_API_KEY)
- gemini:// → KindGemini (GEMINI_API_KEY or GOOGLE_API_KEY)
- mistral:// → KindMistral (MISTRAL_API_KEY)
- openai:// → KindOpenAI (OPENAI_API_KEY) *
- Parameters:
- rawURL (string) — URL as typed by the user. *
- Returns:
- RouteKind — inferred kind.
- error — when the URL scheme is unrecognised. *
- Example:
- kind, err := InferRouteKind("ollama://192.168.1.12:11434")
- // kind = KindOllama, err = nil
- kind, err = InferRouteKind("anthropic://")
- // kind = KindAnthropic, err = nil
type RouteRegistry ¶
type RouteRegistry struct {
Endpoints map[string]*RouteEndpoint
Enabled bool
}
- RouteRegistry holds all registered endpoints and the routing-enabled flag. *
- Example:
- rr := NewRouteRegistry()
- rr.Add(&RouteEndpoint{Name: "pi2", URL: "ollama://192.168.1.12:11434", Kind: KindOllama})
func NewRouteRegistry ¶
func NewRouteRegistry() *RouteRegistry
- NewRouteRegistry returns an empty registry with routing enabled. *
- Returns:
- *RouteRegistry — empty, enabled registry. *
- Example:
- rr := NewRouteRegistry()
func (*RouteRegistry) Add ¶
func (rr *RouteRegistry) Add(ep *RouteEndpoint)
* Add registers ep in the registry, replacing any existing endpoint with the
- same name. *
- Parameters:
- ep (*RouteEndpoint) — endpoint to register. *
- Example:
- rr.Add(&RouteEndpoint{Name: "pi2", URL: "ollama://192.168.1.12:11434", Kind: KindOllama})
func (*RouteRegistry) Lookup ¶
func (rr *RouteRegistry) Lookup(name string) *RouteEndpoint
- Lookup returns the endpoint registered under name, or nil if not found. *
- Parameters:
- name (string) — endpoint name. *
- Returns:
- *RouteEndpoint — registered endpoint; nil if not found. *
- Example:
- ep := rr.Lookup("pi2")
- if ep == nil { fmt.Println("not registered") }
func (*RouteRegistry) Remove ¶
func (rr *RouteRegistry) Remove(name string)
- Remove deletes the endpoint with the given name. No-op if not found. *
- Parameters:
- name (string) — endpoint name to remove. *
- Example:
- rr.Remove("pi2")
type SessionFileInfo ¶
type SessionFileInfo struct {
Path string // absolute path to the file
Name string // basename without extension
ModTime time.Time // file modification time
}
SessionFileInfo describes a single session file found on disk.
func ListSessionFiles ¶
func ListSessionFiles(dir string) ([]SessionFileInfo, error)
* ListSessionFiles returns all .spmd and .fountain files in dir, sorted
- newest first by modification time. Returns nil (not an error) when dir does
- not exist. *
- Parameters:
- dir (string) — directory to scan. *
- Returns:
- []SessionFileInfo — session files, newest first; nil if none found.
- error — on read failure (not on missing dir). *
- Example:
- files, err := ListSessionFiles("agents/sessions")
- for _, f := range files {
- fmt.Printf("%s %s\n", f.ModTime.Format("2006-01-02 15:04"), f.Name)
- }
type SkillCatalog ¶
* SkillCatalog maps skill names to their parsed metadata.
- Project-scope entries override user-scope entries when names collide. *
- Example:
- cat := ScanSkills("/home/user/myproject")
- skill, ok := cat["pdf-processing"]
func ScanSkillDirs ¶
func ScanSkillDirs(dirs []SkillSearchDir) SkillCatalog
* ScanSkillDirs discovers skills from an explicit list of search directories.
- Directories are scanned in order; later entries override earlier ones on
- name collision, so callers should place higher-priority paths last. *
- Parameters:
- dirs ([]SkillSearchDir) — ordered list of directories to scan. *
- Returns:
- SkillCatalog — all discovered skills, keyed by name. *
- Example:
- dirs := []SkillSearchDir{
- {Path: "/home/user/agents/skills", Source: SkillSourceUser},
- {Path: "/proj/agents/skills", Source: SkillSourceProject},
- }
- cat := ScanSkillDirs(dirs)
func ScanSkills ¶
func ScanSkills(workDir, agentsDir string) SkillCatalog
* ScanSkills discovers skills from the workspace agents/skills/ directory.
- agentsDir overrides the agents directory name (default "agents"); pass an
- empty string to use the default. *
- Path scanned:
- <workDir>/<agentsDir>/skills/ *
- Parameters:
- workDir (string) — absolute path to the Harvey workspace root.
- agentsDir (string) — override for the agents directory name; empty = "agents". *
- Returns:
- SkillCatalog — all discovered skills. *
- Example:
- cat := ScanSkills("/home/user/myproject", "")
- fmt.Println(len(cat), "skills found")
type SkillMeta ¶
type SkillMeta struct {
Name string
Description string
License string
Compatibility string
AllowedTools string
Trigger string
Variables []SkillVariable
Metadata map[string]string
Path string
Body string
Source SkillSource
}
- SkillMeta holds the parsed contents of a single SKILL.md file. *
- Fields:
- Name (string) — skill identifier from frontmatter (or inferred from dir).
- Description (string) — when/why to use this skill; injected into the catalog.
- License (string) — optional license identifier.
- Compatibility (string) — optional environment requirements.
- AllowedTools (string) — optional space-separated tool allowlist (experimental).
- Trigger (string) — optional regex or keywords for auto-dispatch.
- Variables ([]SkillVariable) — input variables declared in frontmatter variables: block.
- Metadata (map[string]string) — arbitrary key-value metadata from frontmatter.
- Path (string) — absolute path to the SKILL.md file.
- Body (string) — markdown body after the YAML frontmatter.
- Source (SkillSource) — "user" or "project" (for precedence tracking). *
- Example:
- meta, err := ParseSkillFile("/home/user/agents/skills/pdf-processing/SKILL.md")
- fmt.Println(meta.Name, meta.Description)
func ParseSkillFile ¶
- ParseSkillFile reads and parses a SKILL.md file. *
- The file must begin with YAML frontmatter (--- ... ---) containing at
- minimum a non-empty description field. If the name field is absent the
- parent directory name is used instead. Malformed frontmatter (unparseable
- YAML, missing description) returns a non-nil error and the skill is skipped
- by callers. *
- Parameters:
- path (string) — absolute path to a SKILL.md file. *
- Returns:
- *SkillMeta — parsed skill; nil on error.
- error — parse failure; nil on success. *
- Example:
- meta, err := ParseSkillFile("/home/user/agents/skills/my-skill/SKILL.md")
- if err != nil { log.Println("skip:", err) }
type SkillSearchDir ¶
type SkillSearchDir struct {
Path string
Source SkillSource
}
- SkillSearchDir pairs a filesystem path with its discovery scope. *
- Fields:
- Path (string) — directory to scan for skill subdirectories.
- Source (SkillSource) — "user" or "project". *
- Example:
- dirs := []SkillSearchDir{
- {Path: "/tmp/skills", Source: SkillSourceProject},
- }
- cat := ScanSkillDirs(dirs)
type SkillSetMeta ¶
type SkillSetMeta struct {
Name string
Description string
Skills []string
Metadata map[string]string
Path string
}
- SkillSetMeta holds the parsed contents of a skill-set YAML file. *
- Fields:
- Name (string) — identifier used in /skill-set load.
- Description (string) — human-readable purpose of the bundle.
- Skills ([]string) — ordered list of skill names to load.
- Metadata (map[string]string) — arbitrary key-value pairs (version, author…).
- Path (string) — absolute path to the source YAML file. *
- Example:
- ss, err := ParseSkillSet("/path/to/agents/skill-sets/go-dev.yaml")
- fmt.Println(ss.Name, ss.Skills)
func ParseSkillSet ¶
func ParseSkillSet(path string) (*SkillSetMeta, error)
- ParseSkillSet reads and parses a skill-set YAML file at path. *
- Parameters:
- path (string) — absolute path to the .yaml file. *
- Returns:
- *SkillSetMeta — parsed skill-set.
- error — if the file cannot be read or parsed. *
- Example:
- ss, err := ParseSkillSet("/agents/skill-sets/fountain.yaml")
type SkillSource ¶
type SkillSource string
SkillSource labels the discovery scope that produced a skill entry.
const ( SkillSourceUser SkillSource = "user" SkillSourceProject SkillSource = "project" )
type SkillVariable ¶
* SkillVariable holds metadata for one input variable declared in a skill's
- SKILL.md frontmatter variables: block. *
- Fields:
- Name (string) — variable name as declared (e.g. "EDIR").
- Description (string) — human-readable description of what the variable controls.
- Example (string) — example value shown in help text. *
- Example:
- v := SkillVariable{Name: "EDIR", Description: "experiment directory", Example: "my_exp"}
type Spinner ¶
type Spinner struct {
// contains filtered or unexported fields
}
Spinner displays an animated 3-line block while the LLM backend processes a request:
<model source and name>
⎿ <Edward Lear message> (updates every ~6 s)
⎿ <braille> [elapsed] (updates every 100 ms)
The label line is omitted when label is empty. When an estimate is provided the timer shows elapsed vs. estimated (e.g. "[8s / ~12s]"); once elapsed exceeds the estimate only elapsed is shown.
type ToolCapable ¶
type ToolCapable interface {
ChatWithTools(ctx context.Context, messages []Message, tools []anyllm.Tool, out io.Writer) (ChatStats, []anyllm.ToolCall, error)
}
* ToolCapable is satisfied by LLM clients that support schema-based tool
- calling. AnyLLMClient implements this interface; other backends that do not
- support tools do not need to implement it. *
- Example:
- if tc, ok := agent.Client.(ToolCapable); ok {
- stats, calls, err := tc.ChatWithTools(ctx, history, schemas, out)
- }
type ToolExecutor ¶
type ToolExecutor struct {
Registry *ToolRegistry
Client LLMClient
MaxIterations int
MaxOutputBytes int
}
* ToolExecutor drives the multi-turn tool call loop between the LLM and the
- tool registry. It handles streaming, tool execution, and re-submission of
- results until the LLM produces a final text response or the iteration limit
- is reached. *
- Fields:
- Registry (*ToolRegistry) — registered tool handlers.
- Client (LLMClient) — LLM backend; must implement ToolCapable for tool calls.
- MaxIterations (int) — hard limit on tool call rounds per user turn.
- MaxOutputBytes (int) — cap on tool output sent back to the LLM. *
- Example:
- ex := NewToolExecutor(agent.Tools, agent.Client, cfg)
- stats, err := ex.RunToolLoop(ctx, agent.History, os.Stdout)
func NewToolExecutor ¶
func NewToolExecutor(registry *ToolRegistry, client LLMClient, cfg *Config) *ToolExecutor
* NewToolExecutor creates a ToolExecutor from the agent's tool registry,
- client, and config. *
- Parameters:
- registry (*ToolRegistry) — registered tools.
- client (LLMClient) — LLM backend.
- cfg (*Config) — source of MaxToolCallsPerTurn and MaxOutputBytes. *
- Returns:
- *ToolExecutor — ready to use. *
- Example:
- ex := NewToolExecutor(agent.Tools, agent.Client, agent.Config)
func (*ToolExecutor) ExecuteToolCalls ¶
func (e *ToolExecutor) ExecuteToolCalls(ctx context.Context, toolCalls []anyllm.ToolCall) ([]Message, error)
* ExecuteToolCalls runs each tool call from the LLM and returns tool-role
- messages ready to append to the conversation history. Each message has
- Role="tool" and ToolCallID set so the next LLM turn can correlate results. *
- Parameters:
- ctx (context.Context) — controls the request lifetime.
- toolCalls ([]anyllm.ToolCall) — tool calls from the LLM's response. *
- Returns:
- []Message — one tool-role message per call.
- error — if any tool execution fails (first error wins). *
- Example:
- results, err := ex.ExecuteToolCalls(ctx, calls)
func (*ToolExecutor) RunToolLoop ¶
func (e *ToolExecutor) RunToolLoop(ctx context.Context, messages []Message, out io.Writer) ([]Message, ChatStats, error)
* RunToolLoop drives the full multi-turn tool conversation:
- 1. Sends messages + tool schemas to the LLM.
- 2. If the LLM returns tool calls, executes them and appends results.
- 3. Repeats until the LLM returns a plain text response or MaxIterations
- is reached — at which point an error is returned (not a silent stop). *
- If the client does not implement ToolCapable, falls back to regular Chat. *
- Parameters:
- ctx (context.Context) — controls the request lifetime.
- messages ([]Message) — full conversation history (modified in place).
- out (io.Writer) — destination for streamed reply tokens. *
- Returns:
- []Message — updated history including tool results and the final reply.
- ChatStats — stats from the final LLM call.
- error — non-nil on transport failure or iteration limit exceeded. *
- Example:
- history, stats, err := ex.RunToolLoop(ctx, agent.History, os.Stdout)
type ToolHandler ¶
* ToolHandler executes a named tool and returns its result as a string.
- It receives the raw argument map decoded from the LLM's JSON arguments. *
- Parameters:
- ctx (context.Context) — controls the request lifetime.
- args (map[string]any) — decoded JSON arguments from the LLM. *
- Returns:
- string — tool output to be sent back to the LLM.
- error — non-nil if the tool failed; the error message is sent back as a tool error. *
- Example:
- handler := func(ctx context.Context, args map[string]any) (string, error) {
- path, ok := args["path"].(string)
- if !ok { return "", fmt.Errorf("path must be a string") }
- data, err := os.ReadFile(path)
- return string(data), err
- }
type ToolRegistry ¶
type ToolRegistry struct {
// contains filtered or unexported fields
}
* ToolRegistry manages all available schema-based tools. It is safe for
- concurrent use. *
- Example:
- r := NewToolRegistry()
- r.RegisterTool("echo", "Return the input", map[string]any{...}, handler)
- schemas := r.GetToolSchemas()
func NewToolRegistry ¶
func NewToolRegistry() *ToolRegistry
- NewToolRegistry creates an empty ToolRegistry. *
- Returns:
- *ToolRegistry — empty, ready to register tools. *
- Example:
- r := NewToolRegistry()
func (*ToolRegistry) Dispatch ¶
func (r *ToolRegistry) Dispatch(ctx context.Context, name, argsJSON string, maxBytes int) (string, error)
* Dispatch looks up the named tool and executes it with args decoded from
- the LLM's raw JSON argument string. Output is capped at maxBytes. *
- Parameters:
- ctx (context.Context) — controls the request lifetime.
- name (string) — tool name from the LLM's tool_call.
- argsJSON (string) — raw JSON argument string from FunctionCall.Arguments.
- maxBytes (int) — output size cap; 0 uses defaultMaxOutputBytes. *
- Returns:
- string — tool result (possibly truncated).
- error — if the tool is unknown, arguments are invalid, or the handler fails. *
- Example:
- result, err := r.Dispatch(ctx, "read_file", `{"path":"main.go"}`, 65536)
func (*ToolRegistry) GetTool ¶
func (r *ToolRegistry) GetTool(name string) (anyllm.Tool, ToolHandler, bool)
- GetTool returns the schema and handler for a tool by name. *
- Parameters:
- name (string) — the tool name. *
- Returns:
- anyllm.Tool — the JSON Schema definition.
- ToolHandler — the executor function.
- bool — false if the name is not registered. *
- Example:
- schema, handler, ok := r.GetTool("read_file")
func (*ToolRegistry) GetToolSchemas ¶
func (r *ToolRegistry) GetToolSchemas() []anyllm.Tool
* GetToolSchemas returns all registered anyllm.Tool schemas in alphabetical
- order, ready to pass in CompletionParams.Tools. *
- Returns:
- []anyllm.Tool — tool schema slice. *
- Example:
- params.Tools = r.GetToolSchemas()
func (*ToolRegistry) Len ¶
func (r *ToolRegistry) Len() int
- Len returns the number of registered tools. *
- Returns:
- int — tool count. *
- Example:
- fmt.Println(r.Len())
func (*ToolRegistry) RegisterTool ¶
func (r *ToolRegistry) RegisterTool(name, description string, parameters map[string]any, handler ToolHandler)
- RegisterTool adds or replaces a tool in the registry. *
- Parameters:
- name (string) — unique function name (must be a valid identifier).
- description (string) — human-readable description sent to the LLM.
- parameters (map[string]any) — JSON Schema object describing the tool's parameters.
- handler (ToolHandler) — Go function that executes the tool. *
- Example:
- r.RegisterTool("read_file", "Read a file", map[string]any{
- "type": "object",
- "properties": map[string]any{
- "path": map[string]any{"type": "string"},
- },
- "required": []string{"path"},
- }, myHandler)
type Workspace ¶
type Workspace struct {
// Root is the absolute, canonicalised path of the working directory.
Root string
}
* Workspace anchors Harvey to a single root directory and enforces that all
- file operations remain within it. The root is resolved to an absolute,
- symlink-free path at construction time so that later checks cannot be
- bypassed by symlinks or relative ".." components. *
- Harvey's internal state directory is always at <Root>/harvey/. *
- Example:
- ws, err := NewWorkspace(".")
- if err != nil {
- log.Fatal(err)
- }
- data, err := ws.ReadFile("README.md")
func NewWorkspace ¶
* NewWorkspace creates a Workspace rooted at dir, resolving the path to an
- absolute, symlink-free form. The agents/ sub-directory is created if it
- does not exist. *
- Parameters:
- dir (string) — path to use as the workspace root; "." uses the current
- working directory. *
- Returns:
- *Workspace — the initialised workspace.
- error — if dir cannot be resolved or agents/ cannot be created. *
- Example:
- ws, err := NewWorkspace(".")
- if err != nil {
- log.Fatal(err)
- }
func (*Workspace) AbsPath ¶
* AbsPath resolves rel relative to the workspace root and verifies that the
- resulting path lies inside the root. It returns an error for any path that
- would escape the workspace (e.g. via ".." components or absolute paths
- outside Root). *
- Security: Uses filepath.Clean to resolve ".." and "." components, then verifies
- the cleaned path is a subtree of ws.Root. This prevents path traversal attacks. *
- Parameters:
- rel (string) — relative path to resolve; may use "/" as separator. *
- Returns:
- string — absolute, cleaned path inside the workspace.
- error — if the resolved path escapes the workspace root. *
- Example:
- p, err := ws.AbsPath("src/main.go")
- // p == "/home/user/myproject/src/main.go"
- _, err = ws.AbsPath("../../etc/passwd") // returns error
func (*Workspace) HarveyDir ¶
* HarveyDir returns the absolute path of Harvey's internal state directory
- (agents/) inside the workspace root. *
- Returns:
- string — absolute path to <Root>/agents/ *
- Example:
- fmt.Println(ws.HarveyDir()) // "/home/user/myproject/agents"
func (*Workspace) ListDir ¶
* ListDir returns the directory entries at path (relative to the workspace
- root). The path must not escape the workspace. *
- Parameters:
- path (string) — relative path of the directory to list; use "." for root. *
- Returns:
- []fs.DirEntry — sorted directory entries.
- error — if the path escapes the workspace or the read fails. *
- Example:
- entries, err := ws.ListDir(".")
- for _, e := range entries {
- fmt.Println(e.Name())
- }
func (*Workspace) MkdirAll ¶
* MkdirAll creates path (relative to the workspace root) and any missing
- parent directories. The path must not escape the workspace. *
- Parameters:
- path (string) — relative directory path to create. *
- Returns:
- error — if the path escapes the workspace or directory creation fails. *
- Example:
- err := ws.MkdirAll("docs/api")
func (*Workspace) ReadFile ¶
* ReadFile reads the file at path (relative to the workspace root) and
- returns its contents. The path must not escape the workspace. *
- Parameters:
- path (string) — relative path to the file. *
- Returns:
- []byte — file contents.
- error — if the path escapes the workspace or the file cannot be read. *
- Example:
- data, err := ws.ReadFile("HARVEY.md")
func (*Workspace) WriteFile ¶
* WriteFile writes data to path (relative to the workspace root), creating
- parent directories as needed. The path must not escape the workspace. *
- Parameters:
- path (string) — relative path to write; parent dirs are created.
- data ([]byte) — bytes to write.
- perm (fs.FileMode) — file permission bits (e.g. 0o644). *
- Returns:
- error — if the path escapes the workspace or the write fails. *
- Example:
- err := ws.WriteFile("notes/todo.md", []byte("# TODO\n"), 0o644)
Source Files
¶
- anyllm_client.go
- audit.go
- builtin_tools.go
- commands.go
- config.go
- encoderfile_embedder.go
- harvey.go
- helptext.go
- knowledge.go
- lear_messages.go
- model_cache.go
- ollama.go
- permissions.go
- rag_support.go
- recorder.go
- replay.go
- route_persist.go
- routing.go
- sessions_files.go
- skill_compile.go
- skill_dispatch.go
- skill_set.go
- skill_wizard.go
- skills.go
- spinner.go
- terminal.go
- tool_executor.go
- tool_registry.go
- tools.go
- version.go
- workspace.go