Documentation
¶
Overview ¶
Package harvey — llamafile.go implements the /llamafile slash command family for registering, switching, and managing llamafile model backends.
Package harvey — llamafile_service.go provides helpers for managing a llamafile inference server process: probing whether one is running and launching it as a background service when it is not.
Package harvey — plan.go implements bounded-context plan-execute support. Plans are stored as GFM checklists in agents/plan.md so they survive /clear and session restarts. Each step is executed with a fresh context containing only the system prompt + current plan state, keeping turn times flat regardless of how many steps have been completed.
Package harvey — plan_cmd.go implements the /plan slash command family for generating and executing bounded-context task plans.
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 BuildFountainBody(timestamp string, turns [][2]string) string
- 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 CompressHistory(a *Agent, keepTurns int, out io.Writer) error
- func CountTokens(ctx context.Context, baseURL, model, text string) (count int, exact bool)
- func DefaultLlamafileModelsDir() string
- func DefaultSessionPath(dir string) string
- func DispatchSkill(ctx context.Context, a *Agent, skill *SkillMeta, prompt string, ...) (bool, 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 FindArXivIDs(text string) []string
- func FindDOIs(text string) []string
- func FindFundRefIDs(text string) []string
- func FindISBNs(text string) []string
- func FindISNIs(text string) []string
- func FindISSNs(text string) []string
- func FindIdentifiers(text string) map[IdentifierType][]string
- func FindLCNAFs(text string) []string
- func FindORCIDs(text string) []string
- func FindPMCIDs(text string) []string
- func FindPMIDs(text string) []string
- func FindRAiDs(text string) []string
- func FindRORs(text string) []string
- func FindSNACs(text string) []string
- func FindVIAFs(text string) []string
- func FmtHelp(src string, appName string, version string, releaseDate string, ...) string
- func FormatContext(results []UnifiedResult) string
- func GenerateMemoryID(t MemoryType) string
- func HelpTopicsText() 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 LlamafileModelNameFromPath(path string) string
- func LoadHarveyMD() string
- func LoadHarveyYAML(ws *Workspace, cfg *Config) error
- func LoadHelpGuide(name string) ([]byte, error)
- func LoadRouteConfig(ws *Workspace, cfg *Config)
- func LoadTemplate(name string) ([]byte, error)
- func LogAudit(action AuditAction, details string, status AuditStatus)
- func LooksLikeSkillQuery(s string) bool
- func MatchesTrigger(skill *SkillMeta, prompt string) bool
- func NeedsOnboarding(store *MemoryStore) bool
- func ParseAtMention(input string) (name, prompt string, ok bool)
- func ParseEmbedderFlags(args []string) (kind, url string)
- func ParseProseToolCalls(blocks []CodeBlock) []anyllm.ToolCall
- func PrintHelpTopic(w io.Writer, topic, appName, version, releaseDate, releaseHash string) bool
- func PrintOllamaEnv(out io.Writer)
- func PrintPlan(p *Plan, out io.Writer)
- func ProbeEncoderfile(baseURL string) bool
- func ProbeEncoderfileModel(baseURL string) (string, error)
- func ProbeLlamafile(baseURL string) bool
- func ProbeOllama(baseURL string) bool
- func RegisterBuiltinTools(r *ToolRegistry, a *Agent)
- func ResolveHandoffDir(ws *Workspace) (string, error)
- func ResolveSessionsDir(ws *Workspace, customPath string) (string, error)
- func RunOnboarding(a *Agent, store *MemoryStore, embedder Embedder, out io.Writer, in io.Reader) error
- func RunSkillWizard(ws *Workspace, agentsDir string, reader *bufio.Reader, out io.Writer) (string, error)
- func SaveLlamafileConfig(ws *Workspace, cfg *Config) error
- func SaveMemoryConfig(ws *Workspace, cfg *Config) error
- func SaveModelAliases(ws *Workspace, cfg *Config) error
- func SavePlan(ws *Workspace, p *Plan) error
- func SaveRAGConfig(ws *Workspace, cfg *Config) error
- func SaveRouteConfig(ws *Workspace, rr *RouteRegistry) error
- func ScrubDoc(doc *MemoryDoc, workspacePath string) (*MemoryDoc, ScrubResult, error)
- func SetGlobalAuditBuffer(buf *AuditBuffer)
- func ShouldCompress(historyTokens, contextLen int, warnAtPct float64) bool
- func SortedSkillNames(cat SkillCatalog) []string
- func StartLlamafileService(path, baseURL, logPath string, timeout time.Duration, gpuLayers int, ...) (*os.Process, error)
- func StartOllamaService(ollamaLogPath string) error
- func TemplateNoteField(content []byte) string
- func ValidSkillName(name string) bool
- type Agent
- func (a *Agent) AddMessage(role, content string)
- func (a *Agent) AddMessageParts(role string, parts []anyllm.ContentPart)
- 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
- func (a *Agent) WriteHandoff(store *MemoryStore, handoffDir string) (string, 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) ProviderCapabilities() anyllm.Capabilities
- 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 BasicChunker
- type BasicDocExtractor
- type BuiltinFormatter
- type CChunker
- type CDocExtractor
- type CapabilityStatus
- type ChatStats
- type Chunk
- type CodeBlock
- type CodeChunker
- type CodeFormatter
- type CombinedDetector
- type Command
- type Concept
- type Config
- func (c *Config) ActiveLlamafileEntry() *LlamafileEntry
- func (c *Config) AddAllowedCommand(cmd string)
- func (c *Config) AddOrUpdateLlamafileEntry(e LlamafileEntry)
- 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) LlamafileEntryByName(name string) *LlamafileEntry
- func (c *Config) PermissionString(prefix string) string
- func (c *Config) RemoveAllowedCommand(cmd string)
- func (c *Config) RemovePermission(prefix string, perm 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 ContentDetector
- type DebugLog
- func (d *DebugLog) Close() error
- func (d *DebugLog) Log(fields map[string]any)
- func (d *DebugLog) LogError(source, message string)
- func (d *DebugLog) LogLLMRequest(model string, messageCount, toolCount int)
- func (d *DebugLog) LogLLMResponse(stats ChatStats, toolCallCount int)
- func (d *DebugLog) LogOllamaStart(debugMode bool, logPath string)
- func (d *DebugLog) LogRAGInject(store, query string, chunkCount int, topScore float64)
- func (d *DebugLog) LogSessionStart(modelID, modelDisplay, provider, workspace, version string)
- func (d *DebugLog) LogSkillDispatch(name, trigger string)
- func (d *DebugLog) LogToolCall(name string, outputBytes int, elapsed time.Duration, callErr string)
- func (d *DebugLog) OllamaLogPath() string
- func (d *DebugLog) Path() string
- type DocExtractor
- type DocumentationBlock
- type Embedder
- type EncoderfileEmbedder
- type EnrichedChunk
- type ExtensionDetector
- type FileExternalFormatter
- type FormatIssue
- type FormatterMode
- type HighlightStyle
- type IdentifierType
- type KBSearchResult
- type KnowledgeBase
- func (kb *KnowledgeBase) AddConcept(name, description string) (int64, error)
- func (kb *KnowledgeBase) AddConceptWithIdentifier(name, description, identifierType, identifierValue string) (int64, error)
- func (kb *KnowledgeBase) AddObservation(projectID int64, kind, body string) (int64, error)
- func (kb *KnowledgeBase) AddObservationWithSource(projectID int64, kind, body, sourceDOI 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 LanguageDetector
- type LanguageInfo
- type LanguageRegistry
- func (r *LanguageRegistry) DetectFromExtension(ext string) (string, bool)
- func (r *LanguageRegistry) DetectLanguage(filePath string, content []byte) (string, float64)
- func (r *LanguageRegistry) GetChunker(id string) CodeChunker
- func (r *LanguageRegistry) GetDetector(id string) LanguageDetector
- func (r *LanguageRegistry) GetExtractor(id string) DocExtractor
- func (r *LanguageRegistry) GetFormatter(id string) CodeFormatter
- func (r *LanguageRegistry) GetHighlighter(id string) SyntaxHighlighter
- func (r *LanguageRegistry) GetLanguageInfo(id string) (LanguageInfo, bool)
- func (r *LanguageRegistry) HasExtension(ext string) bool
- func (r *LanguageRegistry) LanguageIDs() []string
- func (r *LanguageRegistry) RegisterLanguage(info LanguageInfo, detector LanguageDetector, chunker CodeChunker, ...)
- func (r *LanguageRegistry) SetChunker(id string, c CodeChunker)
- func (r *LanguageRegistry) SetExtractor(id string, e DocExtractor)
- func (r *LanguageRegistry) SetFormatter(id string, f CodeFormatter)
- func (r *LanguageRegistry) SetHighlighter(id string, h SyntaxHighlighter)
- type LispChunker
- type LispDocExtractor
- type LlamafileEntry
- type Manifest
- type ManifestEntry
- type MemoryConfig
- type MemoryDoc
- type MemoryMeta
- type MemoryStore
- func (s *MemoryStore) Archive(id string) error
- func (s *MemoryStore) BudgetStats(n int) (avgSaturation, compressionRate, avgToksPerSec float64, err error)
- func (s *MemoryStore) ByID(id string) (*MemoryDoc, error)
- func (s *MemoryStore) Close() error
- func (s *MemoryStore) Count() (int64, error)
- func (s *MemoryStore) Dir() string
- func (s *MemoryStore) List(typeFilter string) ([]MemoryMeta, error)
- func (s *MemoryStore) ListDocs(typeFilter string) ([]MemoryDoc, error)
- func (s *MemoryStore) Query(query string, embedder Embedder, topK int) ([]MemoryDoc, error)
- func (s *MemoryStore) Recent(n int) ([]MemoryDoc, error)
- func (s *MemoryStore) RecordSessionStats(sessionID string, budgetTokens, injectedTokens int, compressed bool, ...) error
- func (s *MemoryStore) Save(doc *MemoryDoc, embedder Embedder) error
- func (s *MemoryStore) SearchFTS(query string, topK int) ([]ScoredDoc, error)
- func (s *MemoryStore) SetConfidence(id string, delta float64) (float64, error)
- func (s *MemoryStore) StatsCount() (int64, error)
- func (s *MemoryStore) WriteDigest(path string) error
- type MemoryType
- type Message
- type Miner
- type ModelCache
- type ModelCapability
- type ModelDetail
- type ModelSummary
- type OberonChunker
- type OberonDocExtractor
- type Observation
- type OllamaClient
- type OllamaEmbedder
- type PDFInfo
- type PDFResult
- type PascalChunker
- type PascalDocExtractor
- type PipeExternalFormatter
- type Plan
- type PlanStep
- type PlaybackTurn
- type Project
- type RagStore
- func (r *RagStore) Close() error
- func (r *RagStore) Count() (int64, error)
- func (r *RagStore) Ingest(source string, texts []string, embedder Embedder) error
- func (r *RagStore) IngestEnriched(source string, chunks []EnrichedChunk, embedder Embedder) error
- func (r *RagStore) Query(query string, embedder Embedder, topK int) ([]Chunk, error)
- 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 RemoteObjectInfo
- type RemoteReader
- type RollingSummaryConfig
- type RouteEndpoint
- type RouteKind
- type RouteRegistry
- type ScoredDoc
- type ScrubResult
- type SessionFileInfo
- type SkillCatalog
- type SkillMeta
- type SkillSearchDir
- type SkillSetMeta
- type SkillSource
- type SkillVariable
- type Spinner
- type SyntaxHighlighter
- type TemplateEntry
- type TerminalHighlighter
- type ToolCallRecord
- 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 UnifiedMemory
- type UnifiedResult
- 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.12" // ReleaseDate, the date version.go was generated ReleaseDate = "2026-06-17" // ReleaseHash, the Git hash when version.go was generated ReleaseHash = "9cc2c0a" 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 = `` /* 5763-byte string literal not displayed */ RoutingHelpText = `%{app_name}(7) user manual | version {version} {release_hash} % R. S. Doiel % {release_date} # NAME ROUTING # SYNOPSIS /route <add NAME URL [MODEL]|rm NAME|models URL|probe NAME|set NAME tools on|off|list|on|off|status> @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 models URL list models available at a provider URL useful before /route add to choose a model /route probe NAME show reachability, model, and tool-call capability for a registered endpoint /route set NAME tools on|off toggle tool calling for a registered endpoint (only for providers that support tool use) /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.` + "`" + ` ` LlamafileHelpText = `` /* 4056-byte string literal not displayed */ OllamaHelpText = `` /* 3077-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 = `` /* 8220-byte string literal not displayed */ RenameHelpText = `` /* 957-byte string literal not displayed */ FileTreeHelpText = `` /* 857-byte string literal not displayed */ ReadDirHelpText = `` /* 1587-byte string literal not displayed */ SkillSetHelpText = `` /* 1912-byte string literal not displayed */ StatusHelpText = `` /* 2192-byte string literal not displayed */ FilesHelpText = `` /* 1064-byte string literal not displayed */ ReadHelpText = `` /* 1792-byte string literal not displayed */ AttachHelpText = `` /* 2411-byte string literal not displayed */ ReadPDFHelpText = `` /* 2203-byte string literal not displayed */ WriteHelpText = `` /* 1323-byte string literal not displayed */ FormatHelpText = `` /* 3421-byte string literal not displayed */ RunHelpText = `` /* 1670-byte string literal not displayed */ SearchHelpText = `` /* 1315-byte string literal not displayed */ GitHelpText = `` /* 1534-byte string literal not displayed */ SummarizeHelpText = `` /* 1813-byte string literal not displayed */ MemoryHelpText = `` /* 6894-byte string literal not displayed */ PipelineHelpText = `` /* 2498-byte string literal not displayed */ InspectHelpText = `` /* 1375-byte string literal not displayed */ SecurityHelpText = `` /* 3183-byte string literal not displayed */ HelpText = `` /* 8051-byte string literal not displayed */ LearnHelpText = `` /* 3037-byte string literal not displayed */ LoopHelpText = `` /* 2834-byte string literal not displayed */ PlanHelpText = `` /* 2788-byte string literal not displayed */ BuiltinToolsHelpText = `` /* 3122-byte string literal not displayed */ HintHelpText = `` /* 2346-byte string literal not displayed */ )
var ( PDFToolsHelpText string GettingStartedHelpText string )
Package-level help text vars loaded from embedded guides at init time. These are accessible to cmdHelp alongside the other HelpText vars in helptext.go.
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 agents/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 EmbeddedTemplates embed.FS
var ErrAutoArchived = errors.New("memory auto-archived: confidence below threshold")
ErrAutoArchived is returned by SetConfidence when the memory's confidence fell to or below the auto-archive threshold (0.2) and Archive was called.
var ErrToolLoopExceeded = errors.New("tool loop limit exceeded")
ErrToolLoopExceeded is returned by RunToolLoop when the LLM exceeds the per-turn tool call iteration limit without producing a plain text response.
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 ValidMemoryTypes = []MemoryType{ MemoryTypeToolUse, MemoryTypeWorkflow, MemoryTypeUserPreference, MemoryTypeWorkspaceProfile, MemoryTypeProjectFact, }
ValidMemoryTypes lists the accepted values for MemoryMeta.Type.
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 BuildFountainBody ¶ added in v0.0.6
* BuildFountainBody constructs a minimal valid Fountain body for a memory
- document. The scene heading uses the INT. MEMORY convention with the
- provided timestamp. *
- Parameters:
- timestamp (string) — ISO-style timestamp, e.g. "2026-05-25 12:00:00".
- turns ([][2]string) — sequence of [character, dialogue] pairs. *
- Returns:
- string — the complete Fountain body from FADE IN: to THE END. *
- Example:
- body := BuildFountainBody("2026-05-25 12:00:00", [][2]string{
- {"RSDOIEL", "I got: fatal: not a git repository"},
- {"HARVEY", "Running git init to initialize the repository."},
- {"RSDOIEL", "That fixed it."},
- })
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 CompressHistory ¶ added in v0.0.6
* CompressHistory replaces all but the last keepTurns conversation turns with
- a single synthetic summary message produced by the current LLM. The system
- prompt (if present) is preserved at the front. The compression call is not
- recorded in the session file; existing recording entries are unaffected. *
- Parameters:
- a (*Agent) — the Harvey agent whose History is compressed.
- keepTurns (int) — number of recent turns to keep verbatim.
- out (io.Writer) — status output (unused in current implementation;
- callers print the warning line before calling). *
- Returns:
- error — if the LLM summarisation call fails. *
- Example:
- if ShouldCompress(tokens, limit, 0.80) {
- fmt.Fprintln(out, "[context ~82% full — compressing older turns]")
- CompressHistory(agent, 6, out)
- }
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 DefaultLlamafileModelsDir ¶ added in v0.0.12
func DefaultLlamafileModelsDir() string
* DefaultLlamafileModelsDir returns the default discovery directory ($HOME/Models).
- Exported so cmd/harvey/main.go can detect whether the user has overridden it
- before applying the HARVEY_LLAMAFILE_DIR environment variable. *
- Returns:
- string — default models directory path. *
- Example:
- if cfg.LlamafileModelsDir == harvey.DefaultLlamafileModelsDir() { ... }
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/agents/sessions")
// "/home/user/project/agents/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) (bool, 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:
- bool — true when the skill used the LLM fallback path and the caller should
- send the enriched history to the LLM to generate a response.
- false when a compiled script handled everything autonomously.
- error — on unexpected I/O or execution failure; non-zero script exit is reported but not returned. *
- Example:
- llmNeeded, err := DispatchSkill(ctx, agent, skill, input, reader, os.Stdout)
func DispatchToEndpoint ¶
func DispatchToEndpoint(ctx context.Context, ep *RouteEndpoint, history []Message, prompt string, cfg *Config, registry *ToolRegistry, 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. *
- When ep.Tools is true and registry is non-nil, the call goes through
- ToolExecutor so the remote model can invoke Harvey's local tools. Harvey's
- existing permission constraints (safe_mode, allowed_commands, permissions)
- are enforced by the registry — the remote model cannot bypass them. *
- 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 and tool limits.
- registry (*ToolRegistry) — Harvey's tool registry; nil disables tool calling.
- 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, agent.Tools, 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 FindArXivIDs ¶ added in v0.0.11
* FindArXivIDs scans text for arXiv preprint identifiers, either as an
- "arXiv:" CURIE (arXiv:2412.03631) or an arxiv.org/abs/ URL. A bare
- numeric identifier with no "arxiv:" label or URL is not matched —
- the YYMM.NNNNN shape alone is too easily confused with version
- numbers or other decimals. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated arXiv identifiers as lower-case "arxiv:"
- CURIEs (e.g. "arxiv:2412.03631"), in first-seen order. *
- Example:
- ids := FindArXivIDs("see arXiv:2412.03631 for the preprint")
- // ids == []string{"arxiv:2412.03631"}
func FindDOIs ¶ added in v0.0.11
* FindDOIs scans text for DOIs in any common form — extended URLs
- (https://doi.org/...), "doi:"/"DOI:" labeled CURIEs, or bare short
- form (10.xxxx/yyyy), which is the most common form in running text.
- Every match is normalized to the extended URL form via
- metadatatools.NormalizeDOI. *
- Note: a https://raid.org/10.xxxx/yyyy URL is also picked up here
- (its local identifier is a real DOI too) — see FindRAiDs for the
- RAiD-specific extraction rule. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated DOIs in extended URL form
- (https://doi.org/10.xxxx/yyyy), in first-seen order. *
- Example:
- dois := FindDOIs("See DOI: 10.1234/abcd.5678 for details.")
- // dois == []string{"https://doi.org/10.1234/abcd.5678"}
func FindFundRefIDs ¶ added in v0.0.11
* FindFundRefIDs scans text for Crossref Funder Registry identifiers —
- DOIs under the reserved 10.13039 prefix that identify a funding
- organization. *
- A 10.13039/xxxxx string is simultaneously a real DOI and a funder
- identifier (unlike the RAiD/DOI case, there is no ambiguity to
- resolve), so the same string is correctly returned by both FindDOIs
- and FindFundRefIDs. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated FundRef identifiers in bare DOI-shaped
- form (e.g. "10.13039/100006961"), in first-seen order. *
- Example:
- ids := FindFundRefIDs("Funder: 10.13039/100006961 (Caltech Library)")
- // ids == []string{"10.13039/100006961"}
func FindISBNs ¶ added in v0.0.11
* FindISBNs scans text for ISBN-10 and ISBN-13 identifiers. A match
- requires either an explicit "ISBN"/"ISBN-10"/"ISBN-13" label, or the
- hyphen-grouped form beginning with the reserved 978/979 bookland
- prefix — a bare run of digits alone is too ambiguous to scan
- reliably. Each candidate is confirmed via its ISBN-10 (Mod 11) or
- ISBN-13 (Mod 10 / EAN-13) checksum. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated ISBNs in hyphenated normalized form, in
- first-seen order. *
- Example:
- isbns := FindISBNs("ISBN: 978-3-16-148410-0")
- // isbns == []string{"978-3-1-61-484100-0"} // see metadatatools.NormalizeISBN
func FindISNIs ¶ added in v0.0.11
- FindISNIs scans text for International Standard Name Identifiers. *
- ISNI shares its exact shape and ISO 7064 Mod 11-2 checksum with
- ORCID (16 digits in four groups, optional trailing X) — a bare match
- is ambiguous between the two. Per the convention in
- towards_a_scholarly_memory_design.md, a bare grouped+checksum match
- defaults to ORCID (see FindORCIDs); FindISNIs only matches when an
- explicit "ISNI:" label or isni.org URL provides disambiguating
- context. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated ISNIs in space-grouped form
- (e.g. "0000 0003 0900 6903"), in first-seen order. *
- Example:
- isnis := FindISNIs("ISNI: 0000 0003 0900 6903")
- // isnis == []string{"0000 0003 0900 6903"}
func FindISSNs ¶ added in v0.0.11
* FindISSNs scans text for International Standard Serial Numbers in
- their NNNN-NNNX hyphenated form. The 8-character hyphenated shape
- with a Mod 11 checksum digit (validated via
- metadatatools.ValidateISSN) is distinctive enough to scan without
- requiring a label. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated ISSNs in NNNN-NNNX form, in first-seen
- order. *
- Example:
- issns := FindISSNs("Journal ISSN 1058-6180, online edition.")
- // issns == []string{"1058-6180"}
func FindIdentifiers ¶ added in v0.0.11
func FindIdentifiers(text string) map[IdentifierType][]string
* FindIdentifiers scans text for every identifier type
- scholarly_identifiers.go supports and returns them grouped by
- IdentifierType. Each value is normalized via the corresponding
- metadatatools Normalize* function (see the per-type canonical-form
- table in towards_a_scholarly_memory_design.md). Types with no matches
- are omitted from the result map, keeping it compact for storage in
- the `chunks.identifiers` JSON column. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- map[IdentifierType][]string — identifiers found, keyed by type. *
- Example:
- ids := FindIdentifiers("DOI: 10.1234/abcd.5678, ORCID: 0000-0003-0900-6903")
- // ids[IdentifierDOI] == []string{"https://doi.org/10.1234/abcd.5678"}
- // ids[IdentifierORCID] == []string{"0000-0003-0900-6903"}
func FindLCNAFs ¶ added in v0.0.11
* FindLCNAFs scans text for Library of Congress Name Authority File
- identifiers. metadatatools' LCNAFPattern (any alphanumeric string)
- is far too permissive for bare scanning, so FindLCNAFs only matches
- when an explicit "LCNAF:" label or an id.loc.gov/authorities/names/
- URL provides context, using the conventional LC control number shape
- (1-3 letters followed by 8-10 digits). *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated LCNAF identifiers, in first-seen order. *
- Example:
- ids := FindLCNAFs("LCNAF: n79021164")
- // ids == []string{"n79021164"}
func FindORCIDs ¶ added in v0.0.11
* FindORCIDs scans text for ORCID iDs in URL form
- (https://orcid.org/...), "ORCID:"/"orcid:" labeled form, or bare
- hyphenated form (0000-0003-0900-6903) — the common form next to an
- author's name in a byline. A bare match must pass the ISO 7064
- Mod 11-2 checksum (via metadatatools.ValidateORCID) to be accepted,
- which keeps false positives from incidental 16-digit groups low. *
- Note: this is also the default classification for any bare
- 16-digit, hyphen-grouped, checksum-valid identifier — see FindISNIs
- for why ISNI requires explicit context to be recognized separately. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated ORCID iDs in bare hyphenated form
- (e.g. "0000-0003-0900-6903"), in first-seen order. *
- Example:
- ids := FindORCIDs("R. S. Doiel (ORCID: 0000-0003-0900-6903)")
- // ids == []string{"0000-0003-0900-6903"}
func FindPMCIDs ¶ added in v0.0.11
* FindPMCIDs scans text for PubMed Central identifiers. The "PMC"
- prefix is part of the identifier itself, so the bare PMCxxxxxxx form
- is self-distinctive and needs no label or URL context. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated PMCIDs (e.g. "PMC1234567"), in first-seen
- order. *
- Example:
- pmcids := FindPMCIDs("available at PMC1234567")
- // pmcids == []string{"PMC1234567"}
func FindPMIDs ¶ added in v0.0.11
* FindPMIDs scans text for PubMed identifiers. metadatatools'
- PMIDPattern is "one or more digits", which alone matches any integer,
- so FindPMIDs only matches when an explicit "PMID:" label or a
- pubmed.ncbi.nlm.nih.gov URL provides context. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated PMIDs (bare digit strings), in first-seen
- order. *
- Example:
- pmids := FindPMIDs("PMID: 33417889")
- // pmids == []string{"33417889"}
func FindRAiDs ¶ added in v0.0.11
- FindRAiDs scans text for Research Activity Identifiers (RAiDs). *
- RAiD and DOI are format-identical (10.xxxx/yyyy — a RAiD is a
- DataCite DOI per ISO 23527), so format alone cannot disambiguate
- them. Per the convention recorded in
- towards_a_scholarly_memory_design.md, FindRAiDs matches ONLY an
- explicit https://raid.org/10.xxxx/yyyy resolver URL. A bare or
- "DOI:"-labeled 10.xxxx/yyyy is always classified as a DOI (see
- FindDOIs), never as a RAiD. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated RAiDs in extended URL form
- (https://raid.org/10.xxxx/yyyy), in first-seen order. *
- Example:
- raids := FindRAiDs("Project RAiD: https://raid.org/10.83962/fb5be317")
- // raids == []string{"https://raid.org/10.83962/fb5be317"}
func FindRORs ¶ added in v0.0.11
* FindRORs scans text for Research Organization Registry identifiers,
- either as a ror.org URL (https://ror.org/05dxps055) or an explicit
- "ROR:" label followed by the bare identifier. A bare 9-character
- token with no URL or label is not matched — the shape alone is too
- generic to scan reliably. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated ROR identifiers in extended URL form
- (https://ror.org/05dxps055), in first-seen order. *
- Example:
- rors := FindRORs("Affiliation: https://ror.org/05dxps055")
- // rors == []string{"https://ror.org/05dxps055"}
func FindSNACs ¶ added in v0.0.11
* FindSNACs scans text for Social Networks and Archival Context
- identifiers. metadatatools' SNACPattern is "one or more digits",
- which alone matches any integer, so FindSNACs only matches when an
- explicit "SNAC:" label or a snaccooperative.org/view/ URL provides
- context. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated SNAC identifiers (bare digit strings), in
- first-seen order. *
- Example:
- ids := FindSNACs("SNAC: 12345678")
- // ids == []string{"12345678"}
func FindVIAFs ¶ added in v0.0.11
* FindVIAFs scans text for Virtual International Authority File
- identifiers. metadatatools' VIAFPattern is "one or more digits",
- which alone matches any integer, so FindVIAFs only matches when an
- explicit "VIAF:" label or a viaf.org/viaf/ URL provides context. *
- Parameters:
- text (string) — the text to scan. *
- Returns:
- []string — deduplicated VIAF identifiers (bare digit strings), in
- first-seen order. *
- Example:
- ids := FindVIAFs("VIAF: 12345678")
- // ids == []string{"12345678"}
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 FormatContext ¶ added in v0.0.6
func FormatContext(results []UnifiedResult) string
* FormatContext formats a slice of UnifiedResults into a context injection
- string grouped by source silo. Returns an empty string when results is empty. *
- Parameters:
- results ([]UnifiedResult) — results from Recall. *
- Returns:
- string — formatted context block ready to inject as a user message;
- empty string when results is empty. *
- Example:
- block := FormatContext(results)
- if block != "" { agent.AddMessage("user", block) }
func GenerateMemoryID ¶ added in v0.0.6
func GenerateMemoryID(t MemoryType) string
* GenerateMemoryID returns a new unique memory ID for the given type.
- The format is {type}_{6-hex-suffix} where the suffix is derived from
- the current nanosecond timestamp. *
- Parameters:
- t (MemoryType) — the memory type used as a prefix. *
- Returns:
- string — a new unique ID, e.g. "tool_use_a3f891". *
- Example:
- id := GenerateMemoryID(MemoryTypeToolUse) // "tool_use_a3f891"
func HelpTopicsText ¶ added in v0.0.12
func HelpTopicsText() string
* HelpTopicsText returns a formatted index of all help topics with one-line
- descriptions, suitable for printing to stdout or an io.Writer. *
- Returns:
- string — formatted topic listing. *
- Example:
- fmt.Print(HelpTopicsText())
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 LlamafileModelNameFromPath ¶ added in v0.0.12
* LlamafileModelNameFromPath is the exported form of llamafileModelName,
- used by cmd/harvey/main.go when building a session-only registry entry
- from the --llamafile CLI flag. *
- Parameters:
- path (string) — path to a llamafile binary. *
- Returns:
- string — name derived from the filename with ".llamafile" stripped. *
- Example:
- name := harvey.LlamafileModelNameFromPath("/home/user/Models/Qwen3.5-4B.llamafile")
- // name == "Qwen3.5-4B"
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 LoadHelpGuide ¶ added in v0.0.8
* LoadHelpGuide reads an embedded help guide by stem name (the filename
- without directory or extension). *
- Parameters:
- name (string) — guide stem, e.g. "ollama", "pdf-tools", "getting-started". *
- Returns:
- []byte — raw guide file contents (Markdown).
- error — if the guide is not found in the embedded FS. *
- Example:
- data, err := LoadHelpGuide("pdf-tools")
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 LoadTemplate ¶ added in v0.0.8
* LoadTemplate reads a built-in profile template by stem name (the filename
- without directory or extension). Returns the raw file bytes for display or
- editing. Does not load workspace-local templates; callers that need those
- can read the file directly using the path derived from TemplateEntry.File. *
- Parameters:
- name (string) — template stem, e.g. "backend-developer". *
- Returns:
- []byte — raw template file contents.
- error — if the template is not found in the embedded FS. *
- Example:
- data, err := LoadTemplate("backend-developer")
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 NeedsOnboarding ¶ added in v0.0.6
func NeedsOnboarding(store *MemoryStore) bool
* NeedsOnboarding reports whether the workspace has no workspace_profile
- memory documents. When true, RunOnboarding should be called before the
- REPL starts. *
- Parameters:
- store (*MemoryStore) — the open memory store for the workspace. *
- Returns:
- bool — true when workspace_profile/ contains no .fountain files. *
- Example:
- if NeedsOnboarding(store) {
- RunOnboarding(a, store, embedder, os.Stdout, os.Stdin)
- }
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 ParseProseToolCalls ¶ added in v0.0.6
ParseProseToolCalls converts tool-call code blocks into anyllm.ToolCall values. It handles both qwen2.5 ("arguments") and llama3.2 ("parameters") key names. Blocks that do not parse as tool calls are silently skipped.
func PrintHelpTopic ¶ added in v0.0.12
* PrintHelpTopic writes the help guide for the named topic to w, substituting
- appName, version, releaseDate, and releaseHash into man-page-style headers.
- Pass empty strings when version metadata is not needed (e.g. inside the REPL). *
- Parameters:
- w (io.Writer) — destination writer.
- topic (string) — topic name or alias (case-insensitive).
- appName (string) — binary name, e.g. "harvey".
- version (string) — semver string, e.g. "0.0.12".
- releaseDate (string) — ISO date, e.g. "2026-06-17".
- releaseHash (string) — short git hash. *
- Returns:
- bool — true if the topic was recognized, false if unknown. *
- Example:
- ok := PrintHelpTopic(os.Stdout, "rag", "harvey", Version, ReleaseDate, ReleaseHash)
- if !ok {
- fmt.Fprintln(os.Stderr, "unknown topic")
- }
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 PrintPlan ¶ added in v0.0.12
- PrintPlan writes a human-readable plan checklist to out. *
- Parameters:
- p (*Plan) — plan to display.
- out (io.Writer) — destination for output. *
- Example:
- PrintPlan(p, 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 ProbeLlamafile ¶ added in v0.0.12
* ProbeLlamafile returns true if a llamafile HTTP server is reachable at
- baseURL. It sends a GET request to the /v1/models endpoint with a short
- timeout so that Harvey's startup sequence does not stall when nothing is
- listening. *
- Parameters:
- baseURL (string) — llamafile server base URL, e.g. "http://localhost:8080". *
- Returns:
- bool — true when the server responds with HTTP 200. *
- Example:
- if ProbeLlamafile("http://localhost:8080") {
- fmt.Println("llamafile is ready")
- }
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 ResolveHandoffDir ¶ added in v0.0.8
* ResolveHandoffDir returns the absolute path to the hand-off directory
- (agents/hand-off/ inside the workspace), creating it if it does not exist.
- Hand-off documents are written there by /profile use when switching profiles. *
- Parameters:
- ws (*Workspace) — the Harvey workspace. *
- Returns:
- string — absolute path to the hand-off directory.
- error — if the directory cannot be created. *
- Example:
- dir, err := ResolveHandoffDir(ws)
func ResolveSessionsDir ¶
* ResolveSessionsDir returns the absolute path to the sessions directory,
- creating it if it does not exist. customPath overrides the default location
- (agents/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 RunOnboarding ¶ added in v0.0.6
func RunOnboarding(a *Agent, store *MemoryStore, embedder Embedder, out io.Writer, in io.Reader) error
* RunOnboarding presents a profile template picker, optionally opens the
- chosen template in $EDITOR, and saves the result as a workspace_profile
- memory document. A project_fact is also extracted and saved when the
- workspace contains a recognisable manifest file. *
- The editor step is skipped when stdin is not an interactive terminal
- (e.g. replay mode, pipes, or test runners). The selected template is
- saved as-is in that case. *
- Parameters:
- a (*Agent) — the Harvey agent (provides workspace root).
- store (*MemoryStore) — the open memory store for the workspace.
- embedder (Embedder) — used to compute embedding vectors; may be nil.
- out (io.Writer) — output writer for prompts and status.
- in (io.Reader) — input reader for user responses. *
- Returns:
- error — if the workspace_profile cannot be saved. *
- Example:
- if NeedsOnboarding(store) {
- err := RunOnboarding(a, store, embedder, os.Stdout, os.Stdin)
- }
func RunSkillWizard ¶
func RunSkillWizard(ws *Workspace, agentsDir string, reader *bufio.Reader, out io.Writer) (string, error)
* RunSkillWizard interactively collects skill metadata from the user,
- opens $EDITOR/$VISUAL for the instructions body, and writes the resulting
- SKILL.md into ws at <agentsDir>/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.
- agentsDir (string) — agents directory name; empty defaults to "agents".
- 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 SaveLlamafileConfig ¶ added in v0.0.12
* SaveLlamafileConfig writes the llamafile registry back to agents/harvey.yaml,
- merging with existing content so that unrelated keys are preserved. Only the
- llamafile: section is updated. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is written.
- cfg (*Config) — source of llamafile fields to persist. *
- Returns:
- error — on path resolution, YAML parse, or file write failure. *
- Example:
- if err := SaveLlamafileConfig(ws, cfg); err != nil {
- fmt.Println("could not save llamafile config:", err)
- }
func SaveMemoryConfig ¶ added in v0.0.6
* SaveMemoryConfig writes the memory-related config fields back to
- agents/harvey.yaml, merging with any existing content so that unrelated keys
- are preserved. It writes only to the memory: section; any legacy top-level
- rag: or knowledge_db: keys are cleared from the file on write. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is written.
- cfg (*Config) — source of Memory fields to persist. *
- Returns:
- error — on path resolution, YAML parse, or file write failure. *
- Example:
- if err := SaveMemoryConfig(ws, cfg); err != nil {
- fmt.Println("could not save memory config:", err)
- }
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 SavePlan ¶ added in v0.0.12
- SavePlan writes the plan to agents/plan.md as a GFM checklist. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is written.
- p (*Plan) — plan to persist. *
- Returns:
- error — on path resolution or file write failure. *
- Example:
- err := SavePlan(agent.Workspace, p)
func SaveRAGConfig ¶
* SaveRAGConfig is an alias for SaveMemoryConfig, retained for call-site
- compatibility. All RAG state now lives in cfg.Memory. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is written.
- cfg (*Config) — source of Memory 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 ScrubDoc ¶ added in v0.0.6
func ScrubDoc(doc *MemoryDoc, workspacePath string) (*MemoryDoc, ScrubResult, error)
* ScrubDoc applies Scrub to both the YAML front matter text and the
- FountainBody of a MemoryDoc, returning a new doc with normalised content
- and combined flags from both sections. *
- Parameters:
- doc (*MemoryDoc) — document to scrub.
- workspacePath (string) — workspace root to normalise away. *
- Returns:
- *MemoryDoc — new document with scrubbed content (original is unchanged).
- ScrubResult — flags from the combined scrub of both sections.
- error — if the doc cannot be re-serialised after scrubbing. *
- Example:
- scrubbed, result, err := ScrubDoc(proposed, ws.Root())
- if len(result.Flags) > 0 {
- showWarnings(result.Flags)
- }
func SetGlobalAuditBuffer ¶
func SetGlobalAuditBuffer(buf *AuditBuffer)
SetGlobalAuditBuffer sets the global audit buffer used by AuditLog.
func ShouldCompress ¶ added in v0.0.6
* ShouldCompress reports whether the conversation history has grown large
- enough to trigger rolling summary compression. Returns true when
- historyTokens >= contextLen * warnAtPct. Returns false when contextLen or
- warnAtPct is zero or negative. *
- Parameters:
- historyTokens (int) — estimated token count of the full history.
- contextLen (int) — model's context window size in tokens.
- warnAtPct (float64) — fraction of contextLen at which to compress
- (e.g. 0.80 = 80%). *
- Returns:
- bool — true when compression is needed. *
- Example:
- if ShouldCompress(1640, 2048, 0.80) {
- CompressHistory(agent, 6, os.Stdout)
- }
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 StartLlamafileService ¶ added in v0.0.12
func StartLlamafileService(path, baseURL, logPath string, timeout time.Duration, gpuLayers int, progress io.Writer) (*os.Process, error)
* StartLlamafileService launches the llamafile binary at path as a background
- HTTP server and waits up to timeout for it to become reachable. The
- listening port is derived from baseURL; port 8080 is used when none is
- present. When logPath is non-empty, subprocess stdout and stderr are
- redirected to that file so output is captured rather than discarded.
- Progress dots are written to progress every 5 seconds while waiting;
- pass nil to suppress them. *
- The binary is invoked with:
- /bin/sh <path> --server --host 127.0.0.1 --port <port> [-ngl N] *
- Parameters:
- path (string) — absolute path to the llamafile executable.
- baseURL (string) — llamafile API base URL used to derive the port
- and probe readiness, e.g. "http://localhost:8080".
- logPath (string) — file path for subprocess output; "" discards output.
- timeout (time.Duration) — how long to wait for the server; 0 uses 120s.
- gpuLayers (int) — layers to offload to GPU via -ngl; negative = omit flag (CPU).
- progress (io.Writer) — receives a dot every 5 s while waiting; nil = silent. *
- Returns:
- *os.Process — the started process; nil on failure.
- error — non-nil if the process fails to start or does not respond within timeout. *
- Example:
- proc, err := StartLlamafileService("/models/gemma3.llamafile", "http://localhost:8080", "", 120*time.Second, 99, os.Stdout)
func StartOllamaService ¶
StartOllamaService launches "ollama serve" as a background process and waits up to 5 seconds for it to become reachable. OLLAMA_DEBUG is inherited from Harvey's process environment (set via --debug at startup). When ollamaLogPath is non-empty, subprocess stdout and stderr are redirected to that file so debug output is captured rather than discarded.
func TemplateNoteField ¶ added in v0.0.8
* TemplateNoteField extracts the content of the NOTE: field from a template
- file. The NOTE: block begins at the line starting with "NOTE:" and ends at
- the next line that starts a new all-caps field (e.g. "NAME:", "ROLE:") or
- at end of file. Returns "" when no NOTE: field is present. *
- Parameters:
- content ([]byte) — raw template file bytes. *
- Returns:
- string — trimmed note text, or "" if absent. *
- Example:
- data, _ := LoadTemplate("backend-developer")
- note := TemplateNoteField(data)
- // "Recommended model: qwen2.5-coder:7b · ingest project source and deps"
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
DebugLog *DebugLog // JSONL diagnostic log; nil when --debug not set
OllamaStartedByHarvey bool // true when Harvey launched the Ollama subprocess this session
// 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 plain-text 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) AddMessageParts ¶ added in v0.0.5
func (a *Agent) AddMessageParts(role string, parts []anyllm.ContentPart)
* AddMessageParts appends a multimodal message to the conversation history.
- Use this when the message contains image or mixed text+image content.
- Parts override Content — do not set Content when using this method. *
- Parameters:
- role (string) — "user" (multimodal messages are always user-role).
- parts ([]anyllm.ContentPart) — ordered content parts (text, image_url, etc.). *
- Example:
- agent.AddMessageParts("user", []anyllm.ContentPart{
- {Type: "text", Text: "[attached: photo.jpg]"},
- {Type: "image_url", ImageURL: &anyllm.ImageURL{URL: "data:image/jpeg;base64,..."}},
- })
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)
- }
func (*Agent) WriteHandoff ¶ added in v0.0.8
func (a *Agent) WriteHandoff(store *MemoryStore, handoffDir string) (string, error)
* WriteHandoff extracts a structural summary from the current conversation
- history and writes it as a Fountain document to handoffDir. The file is
- named by timestamp and uses the .spmd extension so the memory miner can
- process it in a future session. *
- No LLM call is made. The summary is built from three heuristics:
- - Last topics: first line of the last three assistant messages.
- - Files touched: path-like tokens (containing "/" but not "://") from
- the last twenty turns, capped at five unique paths.
- - Open questions: user messages whose first line ends with "?", capped
- at three. *
- Parameters:
- store (*MemoryStore) — open memory store; used to read the current
- profile name. May be nil.
- handoffDir (string) — directory to write the file into. *
- Returns:
- string — absolute path of the file written.
- error — on write failure. *
- Example:
- path, err := a.WriteHandoff(store, handoffDir)
type AnyLLMClient ¶
type AnyLLMClient struct {
DebugLog *DebugLog
// 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) ProviderCapabilities ¶ added in v0.0.4
func (a *AnyLLMClient) ProviderCapabilities() anyllm.Capabilities
* ProviderCapabilities returns the feature flags reported by the underlying
- provider. When the provider does not implement CapabilityProvider, a
- conservative set with only Completion and CompletionStreaming is returned.
- No network call is made — all providers return static capability data. *
- Returns:
- anyllm.Capabilities — static flags for this provider. *
- Example:
- caps := client.ProviderCapabilities()
- if caps.CompletionTools { fmt.Println("tools supported") }
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 BasicChunker ¶ added in v0.0.10
type BasicChunker struct{}
* BasicChunker splits Basic (FreeBasic / QB64) source into enriched chunks
- at SUB and FUNCTION boundaries. *
- Example:
- b := NewBasicChunker()
- chunks := b.Chunk("SUB Hello()\n PRINT \"Hi\"\nEND SUB", "prog.bas")
func NewBasicChunker ¶ added in v0.0.10
func NewBasicChunker() *BasicChunker
- NewBasicChunker returns a BasicChunker. *
- Returns:
- *BasicChunker — ready-to-use chunker. *
- Example:
- b := NewBasicChunker()
func (*BasicChunker) Chunk ¶ added in v0.0.10
func (b *BasicChunker) Chunk(content string, _ string) []EnrichedChunk
- Chunk splits Basic source into SUB/FUNCTION chunks and code sections. *
- Parameters:
- content (string) — Basic source text.
- filePath (string) — source path; used for context only. *
- Returns:
- []EnrichedChunk — chunks with location and symbol metadata. *
- Example:
- chunks := b.Chunk(src, "prog.bas")
func (*BasicChunker) Language ¶ added in v0.0.10
func (b *BasicChunker) Language() string
- Language returns "basic". *
- Returns:
- string — "basic". *
- Example:
- b.Language() // "basic"
type BasicDocExtractor ¶ added in v0.0.10
type BasicDocExtractor struct{}
* BasicDocExtractor extracts documentation from FreeBasic / QB64 source code.
- It recognises REM statements (case-insensitive) and single-quote (') comments.
- Consecutive comment lines are grouped into one DocumentationBlock. *
- Example:
- e := NewBasicDocExtractor()
- docs := e.ExtractDocs("' Prints a greeting.\nSUB Hello()\n PRINT \"Hi\"\nEND SUB\n")
func NewBasicDocExtractor ¶ added in v0.0.10
func NewBasicDocExtractor() *BasicDocExtractor
- NewBasicDocExtractor returns a BasicDocExtractor. *
- Returns:
- *BasicDocExtractor — ready-to-use extractor. *
- Example:
- e := NewBasicDocExtractor()
func (*BasicDocExtractor) ExtractDocs ¶ added in v0.0.10
func (e *BasicDocExtractor) ExtractDocs(content string) []DocumentationBlock
- ExtractDocs returns all DocumentationBlocks found in Basic source. *
- Parameters:
- content (string) — Basic source text. *
- Returns:
- []DocumentationBlock — blocks with line range and symbol association. *
- Example:
- docs := e.ExtractDocs("' Adds a and b.\nFUNCTION Add(a As Integer, b As Integer)\n")
func (*BasicDocExtractor) ExtractSymbols ¶ added in v0.0.10
func (e *BasicDocExtractor) ExtractSymbols(content string) map[string]string
- ExtractSymbols returns a map of symbol name → documentation text for Basic. *
- Parameters:
- content (string) — Basic source text. *
- Returns:
- map[string]string — symbol → doc text. *
- Example:
- syms := e.ExtractSymbols("REM Adds two numbers.\nFUNCTION Add(a, b)\n")
- // syms["Add"] == "Adds two numbers."
func (*BasicDocExtractor) Language ¶ added in v0.0.10
func (e *BasicDocExtractor) Language() string
- Language returns "basic". *
- Returns:
- string — "basic". *
- Example:
- e.Language() // "basic"
type BuiltinFormatter ¶ added in v0.0.10
type BuiltinFormatter struct {
// contains filtered or unexported fields
}
* BuiltinFormatter applies a pure-Go formatting function to source text.
- It implements the PipeFormatter mode and requires no external tools, safe
- mode, or workspace access. *
- Example:
- f := newBuiltinFormatter("pascal", normaliseText)
- formatted, err := f.Format(" x := 1; \n", "module.pas")
func (*BuiltinFormatter) Check ¶ added in v0.0.10
func (f *BuiltinFormatter) Check(content string, _ string) (bool, []FormatIssue)
- Check reports whether content matches its formatted form. *
- Parameters:
- content (string) — source code to check.
- filePath (string) — unused. *
- Returns:
- bool — true when already formatted.
- []FormatIssue — empty on pass.
func (*BuiltinFormatter) Format ¶ added in v0.0.10
func (f *BuiltinFormatter) Format(content string, _ string) (string, error)
- Format applies the built-in formatting function to content. *
- Parameters:
- content (string) — source code to format.
- filePath (string) — unused; present for interface conformance. *
- Returns:
- string — formatted content.
- error — always nil. *
- Example:
- out, _ := f.Format("var x: integer; \n", "prog.pas")
func (*BuiltinFormatter) Language ¶ added in v0.0.10
func (f *BuiltinFormatter) Language() string
- Language returns the language ID. *
- Returns:
- string — language ID.
func (*BuiltinFormatter) Mode ¶ added in v0.0.10
func (f *BuiltinFormatter) Mode() FormatterMode
- Mode returns PipeFormatter (built-ins are pure in-process formatters). *
- Returns:
- FormatterMode — always PipeFormatter.
type CChunker ¶ added in v0.0.10
type CChunker struct {
// contains filtered or unexported fields
}
* CChunker splits C or C++ source code into enriched chunks at brace-balanced
- top-level boundaries. Function definitions, struct/class definitions, and
- preprocessor/declaration sections each become their own chunk. *
- Example:
- c := NewCChunker("c")
- chunks := c.Chunk("#include <stdio.h>\nint main(){return 0;}\n", "main.c")
func NewCChunker ¶ added in v0.0.10
- NewCChunker returns a CChunker for the given language ID ("c" or "cpp"). *
- Parameters:
- langID (string) — "c" or "cpp". *
- Returns:
- *CChunker — ready-to-use chunker. *
- Example:
- c := NewCChunker("cpp")
func (*CChunker) Chunk ¶ added in v0.0.10
func (c *CChunker) Chunk(content string, _ string) []EnrichedChunk
* Chunk splits C/C++ source into enriched chunks. Brace depth is tracked
- through strings and comments so function bodies are never split. *
- Parameters:
- content (string) — C/C++ source text.
- filePath (string) — source path; used for context only. *
- Returns:
- []EnrichedChunk — source chunks with location and symbol metadata. *
- Example:
- chunks := c.Chunk("void foo(){}\nvoid bar(){}\n", "lib.c")
type CDocExtractor ¶ added in v0.0.10
type CDocExtractor struct {
// contains filtered or unexported fields
}
* CDocExtractor extracts documentation blocks from C or C++ source code.
- It recognises line comments (//), block comments (/* * /), and
- Doxygen-style doc-comments (/** * / and /*! * /). Comments immediately
- preceding (no intervening blank line) a code line are associated with the
- symbol defined on that line. *
- Example:
- e := NewCDocExtractor("c")
- docs := e.ExtractDocs("// foo docs\nvoid foo(){}\n")
func NewCDocExtractor ¶ added in v0.0.10
func NewCDocExtractor(langID string) *CDocExtractor
- NewCDocExtractor returns a CDocExtractor for the given language ID. *
- Parameters:
- langID (string) — "c" or "cpp". *
- Returns:
- *CDocExtractor — ready-to-use extractor. *
- Example:
- e := NewCDocExtractor("c")
func (*CDocExtractor) ExtractDocs ¶ added in v0.0.10
func (e *CDocExtractor) ExtractDocs(content string) []DocumentationBlock
- ExtractDocs returns all DocumentationBlocks found in C/C++ source. *
- Parameters:
- content (string) — C or C++ source text. *
- Returns:
- []DocumentationBlock — blocks with type, line range, and symbol association. *
- Example:
- docs := e.ExtractDocs("/** Foo does X. * /\nvoid foo(){}\n")
func (*CDocExtractor) ExtractSymbols ¶ added in v0.0.10
func (e *CDocExtractor) ExtractSymbols(content string) map[string]string
- ExtractSymbols returns a map of symbol name → documentation text for C/C++. *
- Parameters:
- content (string) — C or C++ source text. *
- Returns:
- map[string]string — symbol → doc text; only symbols with comments are included. *
- Example:
- syms := e.ExtractSymbols("// Returns x.\nint getX(){return x;}\n")
- // syms["getX"] == "Returns x."
func (*CDocExtractor) Language ¶ added in v0.0.10
func (e *CDocExtractor) Language() string
- Language returns the language ID this extractor handles. *
- Returns:
- string — "c" or "cpp". *
- Example:
- e.Language() // "c"
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 CodeBlock ¶ added in v0.0.6
- CodeBlock holds a single fenced code block parsed from a markdown response. *
- Fields:
- Lang (string) — language hint from the opening fence (e.g. "go", "bash"); may be empty.
- Content (string) — text inside the fence with the trailing newline stripped. *
- Example:
- blocks := extractCodeBlocks("```go\npackage main\n```")
- // blocks[0].Lang == "go", blocks[0].Content == "package main"
type CodeChunker ¶ added in v0.0.10
type CodeChunker interface {
// Chunk splits content into enriched units. filePath is used for context only.
Chunk(content string, filePath string) []EnrichedChunk
// Language returns the language ID this chunker handles.
Language() string
}
* CodeChunker splits source code into semantically meaningful chunks for
- RAG ingestion. Each chunk preserves code boundaries (functions, procedures,
- etc.) and carries source-location metadata in EnrichedChunk. *
- Example:
- chunks := chunker.Chunk(src, "main.go")
type CodeFormatter ¶ added in v0.0.10
type CodeFormatter interface {
// Format returns formatted source code.
// PipeFormatter: content → formatted string (file not touched).
// FileFormatter: Harvey writes the file first; Format is called after and
// returns the re-read file content.
Format(content string, filePath string) (string, error)
// Check returns true when content is already properly formatted,
// plus a list of issues if it is not.
Check(content string, filePath string) (bool, []FormatIssue)
// Language returns the language ID this formatter handles.
Language() string
// Mode returns PipeFormatter or FileFormatter.
Mode() FormatterMode
}
- CodeFormatter formats source code according to language conventions. *
- Two modes are supported; see FormatterMode for details. *
- Example:
- formatted, err := f.Format(src, "main.go")
type CombinedDetector ¶ added in v0.0.10
type CombinedDetector struct {
// contains filtered or unexported fields
}
* CombinedDetector implements LanguageDetector by trying extension-based
- detection first (confidence 1.0) and falling back to content-based detection
- when the extension is absent or unrecognised. *
- Example:
- d := NewCombinedDetector("python", []string{".py"})
- lang, conf := d.Detect("script", []byte("#!/usr/bin/env python3\n"))
- // "python", 0.9 (no extension → content fallback)
func NewCombinedDetector ¶ added in v0.0.10
func NewCombinedDetector(langID string, exts []string) *CombinedDetector
- NewCombinedDetector returns a CombinedDetector for the given language. *
- Parameters:
- langID (string) — language identifier, e.g. "go".
- exts ([]string) — file extensions for this language, e.g. [".go"]. *
- Returns:
- *CombinedDetector — ready-to-use detector. *
- Example:
- d := NewCombinedDetector("oberon", []string{".Mod", ".obn"})
func (*CombinedDetector) Detect ¶ added in v0.0.10
func (d *CombinedDetector) Detect(filePath string, content []byte) (string, float64)
* Detect returns the language and confidence, trying extension first.
- If the extension yields no match, content inspection is attempted. *
- Parameters:
- filePath (string) — path to the file.
- content ([]byte) — file contents. *
- Returns:
- language (string) — language ID or "".
- confidence (float64) — 1.0 for extension match; content confidence otherwise. *
- Example:
- lang, conf := d.Detect("main.go", data) // "go", 1.0
func (*CombinedDetector) DetectFromExtension ¶ added in v0.0.10
func (d *CombinedDetector) DetectFromExtension(ext string) (string, bool)
- DetectFromExtension delegates to the embedded ExtensionDetector. *
- Parameters:
- ext (string) — file extension with leading dot. *
- Returns:
- language (string) — language ID or "".
- ok (bool) — true on match. *
- Example:
- lang, ok := d.DetectFromExtension(".go") // "go", true
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 ¶
type Concept struct {
ID int64
Name string
Description string
IdentifierType string
IdentifierValue string
}
* Concept represents a named idea or term that can be linked to projects and
- observations. A concept may also represent a scholarly entity — a paper,
- person, institution, or funder — in which case IdentifierType is one of
- the IdentifierType values (e.g. "doi", "orcid", "ror", "fundref") and
- IdentifierValue is that identifier's normalized (extended) form. Both
- fields are "" for concepts that are plain ideas/terms, not entities. *
- Example:
- concepts, err := kb.Concepts()
- for _, c := range concepts {
- fmt.Println(c.Name, "-", c.Description)
- if c.IdentifierType != "" {
- fmt.Printf(" %s: %s\n", c.IdentifierType, c.IdentifierValue)
- }
- }
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 = agents/sessions/
AgentsDir string // agents/skills tree root; 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
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
ReplayContinue bool // when true, drop into the REPL after replay finishes
ModelCacheDB string // path to model_cache.db; empty = harvey/model_cache.db
// 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
// Permissions: map from path prefix to list of allowed actions (read, write, exec, delete)
Permissions map[string][]string
// 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; 0 means no timeout
// Llamafile backend settings
LlamafileModels []LlamafileEntry // registered llamafile models
LlamafileActive string // name of the active model; "" = none
LlamafileURL string // API base URL; default "http://localhost:8080"
LlamafileModelsDir string // discovery directory; default "$HOME/Models"
LlamafileStartupTimeout time.Duration // how long to wait for the server to respond; default 120s
LlamafileGPULayers int // layers to offload to GPU via -ngl; -1 = let llamafile decide (CPU), 99 = maximise GPU
// Model aliases: short name → full Ollama model identifier
ModelAliases map[string]string
// 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
ToolResultCompaction bool // when true, prior tool-call rounds are compacted before each new LLM turn
// Debug mode: set by --debug at startup; enables JSONL debug log and OLLAMA_DEBUG
Debug bool
// SyntaxHighlight enables ANSI colour highlighting of code blocks in responses.
SyntaxHighlight bool
// AutoFormat enables automatic code formatting after write_file writes a source file.
AutoFormat bool
// Memory system: RAG stores, knowledge base, and retrieval settings
Memory MemoryConfig
}
- 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 = agents/sessions/.
- 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).
- Memory (MemoryConfig) — unified memory system settings, including RAG and knowledge base. *
- Example:
- cfg := DefaultConfig()
- cfg.WorkDir = "/home/user/myproject"
func DefaultConfig ¶
func DefaultConfig() *Config
func (*Config) ActiveLlamafileEntry ¶ added in v0.0.12
func (c *Config) ActiveLlamafileEntry() *LlamafileEntry
* ActiveLlamafileEntry returns a pointer to the active LlamafileEntry in the
- config, or nil when no active model is set or the name is not found. *
- Returns:
- *LlamafileEntry — the active entry, or nil. *
- Example:
- if e := cfg.ActiveLlamafileEntry(); e != nil {
- fmt.Println(e.Path)
- }
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) AddOrUpdateLlamafileEntry ¶ added in v0.0.12
func (c *Config) AddOrUpdateLlamafileEntry(e LlamafileEntry)
* AddOrUpdateLlamafileEntry inserts e into the registry if its name is new,
- or replaces the existing entry if one with the same name exists. *
- Parameters:
- e (LlamafileEntry) — the entry to add or replace. *
- Example:
- cfg.AddOrUpdateLlamafileEntry(LlamafileEntry{Name: "qwen", Path: "/home/user/Models/qwen.llamafile"})
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) LlamafileEntryByName ¶ added in v0.0.12
func (c *Config) LlamafileEntryByName(name string) *LlamafileEntry
* LlamafileEntryByName returns a pointer to the named LlamafileEntry, or nil
- when not found. *
- Parameters:
- name (string) — registry name to look up. *
- Returns:
- *LlamafileEntry — matching entry, or nil. *
- Example:
- if e := cfg.LlamafileEntryByName("qwen"); e != nil {
- fmt.Println(e.Path)
- }
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) 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) 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 ContentDetector ¶ added in v0.0.10
type ContentDetector struct {
// contains filtered or unexported fields
}
* ContentDetector implements LanguageDetector using shebang and keyword
- pattern matching. It is language-specific: it only returns its own langID
- so that it can be registered per-language in the registry. *
- Example:
- d := NewContentDetector("python")
- lang, conf := d.Detect("script", []byte("#!/usr/bin/env python3\n"))
- // "python", 0.9
func NewContentDetector ¶ added in v0.0.10
func NewContentDetector(langID string) *ContentDetector
- NewContentDetector returns a ContentDetector for the given language. *
- Parameters:
- langID (string) — language identifier, e.g. "python". *
- Returns:
- *ContentDetector — ready-to-use detector. *
- Example:
- d := NewContentDetector("lisp")
func (*ContentDetector) Detect ¶ added in v0.0.10
func (d *ContentDetector) Detect(_ string, content []byte) (string, float64)
* Detect scans content for shebang lines and keyword patterns. It returns
- a non-zero confidence only when the detected language matches this
- detector's langID. Binary content always returns ("", 0.0). *
- Parameters:
- filePath (string) — path to the file; used only for context, not parsed.
- content ([]byte) — file contents to inspect. *
- Returns:
- language (string) — this detector's langID or "".
- confidence (float64) — 0.9 for shebang, keyword confidence otherwise; 0 on no match. *
- Example:
- lang, conf := d.Detect("", []byte("(defun hello () nil)"))
- // "lisp", 0.95
func (*ContentDetector) DetectFromExtension ¶ added in v0.0.10
func (d *ContentDetector) DetectFromExtension(_ string) (string, bool)
* DetectFromExtension always returns ("", false) for a ContentDetector because
- content-based detection does not use file extensions. *
- Parameters:
- ext (string) — ignored. *
- Returns:
- language (string) — always "".
- ok (bool) — always false. *
- Example:
- lang, ok := d.DetectFromExtension(".py") // "", false
type DebugLog ¶ added in v0.0.4
type DebugLog struct {
// contains filtered or unexported fields
}
* DebugLog writes structured JSONL diagnostic events to a per-session log
- file. Every method is nil-safe: calling any method on a nil *DebugLog is
- a no-op, so callers never need to guard with if statements. *
- Each line written is a JSON object with at least a "time" field (RFC3339Nano)
- and an "event" field identifying the event type. Additional fields vary by
- event type. The file is safe for concurrent writes. *
- Example:
- dl, err := OpenDebugLog("/path/to/agents/logs")
- if err != nil { log.Fatal(err) }
- defer dl.Close()
- dl.LogSessionStart("gemma4:e2b", "ollama", "/workspace", "0.0.3")
func OpenDebugLog ¶ added in v0.0.4
* OpenDebugLog creates agents/logs/harvey-TIMESTAMP.jsonl in logsDir.
- The directory is created with 0755 permissions if it does not exist. *
- Parameters:
- logsDir (string) — directory to write the log file into. *
- Returns:
- *DebugLog — open log ready for writing.
- error — on directory creation or file creation failure. *
- Example:
- dl, err := OpenDebugLog(filepath.Join(workspace.Root, "agents", "logs"))
func (*DebugLog) Close ¶ added in v0.0.4
* Close flushes and closes the underlying file. Safe to call on nil.
func (*DebugLog) Log ¶ added in v0.0.4
Log writes a single JSONL line. fields must include "event". The "time" key is always overwritten with the current UTC time.
func (*DebugLog) LogError ¶ added in v0.0.4
* LogError records a non-fatal diagnostic error from a named source.
func (*DebugLog) LogLLMRequest ¶ added in v0.0.4
* LogLLMRequest records outgoing LLM request parameters.
func (*DebugLog) LogLLMResponse ¶ added in v0.0.4
* LogLLMResponse records the outcome of an LLM call.
func (*DebugLog) LogOllamaStart ¶ added in v0.0.4
* LogOllamaStart records when Harvey launches the Ollama subprocess.
func (*DebugLog) LogRAGInject ¶ added in v0.0.4
- LogRAGInject records a RAG context augmentation event. *
- Parameters:
- store (string) — name of the active RAG store.
- query (string) — the user prompt used as the retrieval query.
- chunkCount (int) — number of chunks injected above the score threshold.
- topScore (float64) — cosine similarity of the best matching chunk.
func (*DebugLog) LogSessionStart ¶ added in v0.0.4
- LogSessionStart records Harvey startup information. *
- Parameters:
- modelID (string) — bare model identifier, e.g. "gemma4:e2b".
- modelDisplay (string) — full display name, e.g. "ollama (gemma4:e2b)".
- provider (string) — provider name, e.g. "ollama".
- workspace (string) — absolute workspace root path.
- version (string) — Harvey version string.
func (*DebugLog) LogSkillDispatch ¶ added in v0.0.4
* LogSkillDispatch records a skill execution event.
func (*DebugLog) LogToolCall ¶ added in v0.0.4
- LogToolCall records a single tool invocation. *
- Parameters:
- name (string) — tool name.
- outputBytes (int) — byte length of the tool's output.
- elapsed (time.Duration) — wall time for the call.
- callErr (string) — error message, or "" on success.
func (*DebugLog) OllamaLogPath ¶ added in v0.0.4
* OllamaLogPath returns the companion path for capturing Ollama subprocess
- output, derived from the Harvey log filename by substituting the prefix.
- Returns "" when called on a nil receiver. *
- Example:
- // dl.path == "agents/logs/harvey-20260514-094620.jsonl"
- // dl.OllamaLogPath() == "agents/logs/ollama-20260514-094620.log"
type DocExtractor ¶ added in v0.0.10
type DocExtractor interface {
// ExtractDocs returns all documentation blocks found in content.
ExtractDocs(content string) []DocumentationBlock
// ExtractSymbols returns a map of symbol name → documentation text.
ExtractSymbols(content string) map[string]string
// Language returns the language ID this extractor handles.
Language() string
}
* DocExtractor pulls documentation blocks out of source code and associates
- them with the symbols they document. *
- Example:
- docs := extractor.ExtractDocs(src)
type DocumentationBlock ¶ added in v0.0.10
type DocumentationBlock struct {
Content string
StartLine int
EndLine int
Symbol string
Type string
}
- DocumentationBlock represents a comment or docstring extracted from source. *
- Fields:
- Content (string) — the documentation text (comment markers stripped).
- StartLine (int) — first line of the block, 1-indexed.
- EndLine (int) — last line of the block, 1-indexed.
- Symbol (string) — name of the associated symbol, or "" if free-standing.
- Type (string) — "line_comment", "block_comment", or "docstring". *
- Example:
- doc := DocumentationBlock{Content: "Foo does X.", StartLine: 9, EndLine: 9,
- Symbol: "Foo", Type: "line_comment"}
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.Memory.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 EnrichedChunk ¶ added in v0.0.10
type EnrichedChunk struct {
Content string
StartLine int
StartCol int
EndLine int
EndCol int
ChunkType string
Symbols []string
Docs string
Identifiers map[string][]string
Citations []string
}
* EnrichedChunk is a fragment of source code or document text with location
- and semantic metadata. StartLine/StartCol and EndLine/EndCol give a precise
- re-location address so a reader can jump directly to the chunk in the source
- file. Columns are 0-indexed byte offsets from the start of the line. *
- Fields:
- Content (string) — the text of this chunk.
- StartLine (int) — first line of the chunk, 1-indexed.
- StartCol (int) — byte offset from the start of StartLine, 0-indexed.
- EndLine (int) — last line of the chunk, 1-indexed.
- EndCol (int) — byte offset from the start of EndLine, 0-indexed.
- ChunkType (string) — "function", "class", "procedure", "comment", "code",
- or for scholarly documents: "abstract", "introduction",
- "methods", "results", "discussion", "conclusion",
- "references", "body".
- Symbols ([]string) — identifiers defined in this chunk.
- Docs (string) — extracted comment/docstring text associated with the chunk.
- Identifiers (map[string][]string) — the source document's own scholarly identifiers
- (DOI, ORCID, ROR, FundRef, etc.), keyed by
- IdentifierType string; shared across every chunk
- from the same document. Empty/nil for non-scholarly chunks.
- Citations ([]string) — scholarly identifiers found in this chunk's text that
- point to OTHER works (e.g. DOIs cited in a references
- section). Empty/nil for non-scholarly chunks. *
- Example:
- chunk := EnrichedChunk{Content: "func Foo() {}", StartLine: 10, StartCol: 0,
- EndLine: 10, EndCol: 14, ChunkType: "function", Symbols: []string{"Foo"}}
type ExtensionDetector ¶ added in v0.0.10
type ExtensionDetector struct {
// contains filtered or unexported fields
}
* ExtensionDetector implements LanguageDetector using file-extension matching.
- It is language-specific: it only returns its own langID. *
- Example:
- d := NewExtensionDetector("go", []string{".go", ".mod", ".sum"})
- lang, conf := d.Detect("main.go", nil) // "go", 1.0
func NewExtensionDetector ¶ added in v0.0.10
func NewExtensionDetector(langID string, exts []string) *ExtensionDetector
- NewExtensionDetector returns an ExtensionDetector for the given language. *
- Parameters:
- langID (string) — language identifier, e.g. "go".
- exts ([]string) — file extensions including the dot, e.g. [".go"]. *
- Returns:
- *ExtensionDetector — ready-to-use detector. *
- Example:
- d := NewExtensionDetector("pascal", []string{".pas", ".p"})
func (*ExtensionDetector) Detect ¶ added in v0.0.10
func (d *ExtensionDetector) Detect(filePath string, content []byte) (string, float64)
* Detect returns (langID, 1.0) when the file extension matches, otherwise
- ("", 0.0). content is ignored. *
- Parameters:
- filePath (string) — path to the file; only the extension is used.
- content ([]byte) — ignored. *
- Returns:
- language (string) — language ID or "".
- confidence (float64) — 1.0 on match, 0.0 otherwise. *
- Example:
- lang, conf := d.Detect("hello.pas", nil) // "pascal", 1.0
func (*ExtensionDetector) DetectFromExtension ¶ added in v0.0.10
func (d *ExtensionDetector) DetectFromExtension(ext string) (string, bool)
* DetectFromExtension returns the language ID when ext exactly matches one of
- the registered extensions for this language. A case-insensitive comparison
- is also tried as a fallback (e.g., ".Mod" and ".mod" both match Oberon). *
- Parameters:
- ext (string) — file extension with leading dot, e.g. ".go". *
- Returns:
- language (string) — language ID or "".
- ok (bool) — true on match. *
- Example:
- lang, ok := d.DetectFromExtension(".Mod") // "oberon", true
type FileExternalFormatter ¶ added in v0.0.10
type FileExternalFormatter struct {
// contains filtered or unexported fields
}
* FileExternalFormatter invokes an external tool that reads and rewrites a
- file in-place. The caller MUST write the file to disk first, then call
- Format. This mode requires safe mode to be disabled at the call site; the
- formatter itself does not enforce that constraint. *
- If the executable is not found on $PATH, Format returns (content, nil). *
- Example:
- f := newFileExtFormatter("pascal", "ptop", "-")
- formatted, err := f.Format(content, "/abs/path/module.pas")
func (*FileExternalFormatter) Check ¶ added in v0.0.10
func (f *FileExternalFormatter) Check(content string, filePath string) (bool, []FormatIssue)
- Check reports whether the file is already formatted. *
- Parameters:
- content (string) — source code to check.
- filePath (string) — absolute path hint. *
- Returns:
- bool — true when already formatted.
- []FormatIssue — empty on pass.
func (*FileExternalFormatter) Format ¶ added in v0.0.10
func (f *FileExternalFormatter) Format(content string, filePath string) (string, error)
* Format runs the external formatter on filePath (which must already be
- written to disk) and returns the re-read content. *
- Parameters:
- content (string) — original content; returned unchanged on tool error.
- filePath (string) — absolute path to the already-written file. *
- Returns:
- string — reformatted file content, or original content on error.
- error — non-nil when the tool ran but failed. *
- Example:
- out, err := f.Format(src, "/workspace/module.pas")
func (*FileExternalFormatter) Language ¶ added in v0.0.10
func (f *FileExternalFormatter) Language() string
- Language returns the language ID this formatter targets. *
- Returns:
- string — language ID.
func (*FileExternalFormatter) Mode ¶ added in v0.0.10
func (f *FileExternalFormatter) Mode() FormatterMode
- Mode returns FileFormatter. *
- Returns:
- FormatterMode — always FileFormatter.
type FormatIssue ¶ added in v0.0.10
- FormatIssue describes a formatting problem found by a CodeFormatter. *
- Fields:
- Line (int) — 1-indexed line number.
- Column (int) — 0-indexed byte offset from line start.
- Message (string) — human-readable description.
- Severity (string) — "error", "warning", or "info". *
- Example:
- issue := FormatIssue{Line: 3, Column: 0, Message: "missing newline", Severity: "warning"}
type FormatterMode ¶ added in v0.0.10
type FormatterMode int
- FormatterMode describes how a CodeFormatter exchanges content with Harvey. *
- Two modes are supported:
- PipeFormatter — content is piped to the formatter's stdin; formatted
- output is read from its stdout. Works with safe mode on.
- FileFormatter — Harvey writes the file first, then invokes the formatter
- on the path so it can rewrite the file in place.
- Requires safe mode off; the executable is validated
- against allowed_commands before invocation. *
- Example:
- if f.Mode() == PipeFormatter { ... }
const ( // PipeFormatter reads from stdin and writes to stdout. PipeFormatter FormatterMode = iota // FileFormatter reads and rewrites the file at the given path. FileFormatter )
type HighlightStyle ¶ added in v0.0.10
type HighlightStyle struct {
Keyword string
String string
Comment string
Number string
Operator string
Function string
Type string
Builtin string
Reset string
}
* HighlightStyle defines ANSI terminal colors for syntax elements.
- Each field holds an ANSI escape prefix, e.g. "\033[34m" for blue.
- Empty string means "no color". *
- Fields:
- Keyword — color for language keywords.
- String — color for string literals.
- Comment — color for comments.
- Number — color for numeric literals.
- Operator — color for operators and punctuation.
- Function — color for function/procedure names.
- Type — color for type names.
- Builtin — color for built-in identifiers.
- Reset — ANSI reset sequence; normally "\033[0m". *
- Example:
- style := HighlightStyle{Keyword: "\033[34m", Reset: "\033[0m"}
type IdentifierType ¶ added in v0.0.11
type IdentifierType string
* IdentifierType names a kind of scholarly identifier that
- scholarly_identifiers.go can find and normalize. Values are the
- lower-case strings used as keys in FindIdentifiers' result map and,
- later, in the `chunks.identifiers` JSON column and
- `concepts.identifier_type` column described in
- towards_a_scholarly_memory_design.md. *
- Example:
- var t IdentifierType = IdentifierDOI
- fmt.Println(string(t)) // "doi"
const ( // IdentifierDOI is a Digital Object Identifier (10.xxxx/yyyy). IdentifierDOI IdentifierType = "doi" // IdentifierORCID is a researcher ORCID iD (0000-0003-0900-6903). IdentifierORCID IdentifierType = "orcid" // IdentifierROR is a Research Organization Registry identifier. IdentifierROR IdentifierType = "ror" // IdentifierRAiD is a Research Activity Identifier (DataCite DOI // resolved via raid.org). IdentifierRAiD IdentifierType = "raid" // IdentifierArXiv is an arXiv preprint identifier. IdentifierArXiv IdentifierType = "arxiv" // IdentifierFundRef is a Crossref Funder Registry identifier // (a DOI under the reserved 10.13039 prefix). IdentifierFundRef IdentifierType = "fundref" // IdentifierISBN is an International Standard Book Number // (10 or 13 digit). IdentifierISBN IdentifierType = "isbn" // IdentifierISSN is an International Standard Serial Number. IdentifierISSN IdentifierType = "issn" // IdentifierISNI is an International Standard Name Identifier. IdentifierISNI IdentifierType = "isni" // IdentifierPMID is a PubMed identifier. IdentifierPMID IdentifierType = "pmid" // IdentifierPMCID is a PubMed Central identifier (PMCxxxxxxx). IdentifierPMCID IdentifierType = "pmcid" // IdentifierVIAF is a Virtual International Authority File identifier. IdentifierVIAF IdentifierType = "viaf" // IdentifierSNAC is a Social Networks and Archival Context identifier. IdentifierSNAC IdentifierType = "snac" // IdentifierLCNAF is a Library of Congress Name Authority File // identifier. IdentifierLCNAF IdentifierType = "lcnaf" )
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>/agents/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 (agents/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 = agents/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. It is equivalent to calling AddConceptWithIdentifier
- with identifierType = identifierValue = "", which leaves any identifier
- already recorded for an existing concept untouched. *
- 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) AddConceptWithIdentifier ¶ added in v0.0.11
func (kb *KnowledgeBase) AddConceptWithIdentifier(name, description, identifierType, identifierValue string) (int64, error)
* AddConceptWithIdentifier inserts a new concept, or updates an existing
- concept with the same name, optionally recording a scholarly identifier
- (e.g. a paper's DOI, a person's ORCID, an institution's ROR) that the
- concept represents. If identifierType or identifierValue is "" on an
- update, the existing stored value (if any) is preserved rather than
- cleared. *
- Parameters:
- name (string) — unique concept name.
- description (string) — human-readable explanation of the concept.
- identifierType (string) — one of the IdentifierType values (e.g. "doi", "orcid"), or "".
- identifierValue (string) — normalized (extended) identifier value, or "". *
- Returns:
- int64 — ID of the inserted or existing concept.
- error — on database failure. *
- Example:
- id, err := kb.AddConceptWithIdentifier("Jane Doe", "paper author",
- string(IdentifierORCID), "0000-0003-0900-6903")
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.
- It is equivalent to calling AddObservationWithSource with sourceDOI = "". *
- 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) AddObservationWithSource ¶ added in v0.0.11
func (kb *KnowledgeBase) AddObservationWithSource(projectID int64, kind, body, sourceDOI string) (int64, error)
* AddObservationWithSource inserts a new observation for a project,
- recording the normalized DOI of the paper it was extracted from, 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.
- sourceDOI (string) — normalized DOI of the source paper, or "" if none. *
- Returns:
- int64 — ID of the new observation.
- error — if kind is invalid or the insert fails. *
- Example:
- id, err := kb.AddObservationWithSource(1, "finding",
- "This paper found X", "https://doi.org/10.1234/abcd.5678")
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 LanguageDetector ¶ added in v0.0.10
type LanguageDetector interface {
// Detect returns the language ID and a confidence score in [0, 1].
// A score below 0.5 should be treated as a non-match.
Detect(filePath string, content []byte) (language string, confidence float64)
// DetectFromExtension returns the language ID for a file extension (with dot).
// ok is false when the extension is not recognised.
DetectFromExtension(ext string) (language string, ok bool)
}
- LanguageDetector identifies the programming language of a file. *
- Example:
- lang, conf := d.Detect("main.go", data)
type LanguageInfo ¶ added in v0.0.10
type LanguageInfo struct {
ID string
Name string
Extensions []string
CommentMarkers []string
BlockStart string
BlockEnd string
Shebang string
HasChunking bool
HasExtraction bool
HasFormatting bool
HasHighlighting bool
}
- LanguageInfo holds static metadata about a programming or markup language. *
- Fields:
- ID (string) — canonical lowercase identifier, e.g. "go", "c".
- Name (string) — display name, e.g. "Go", "C".
- Extensions ([]string) — file extensions including the dot, e.g. [".go"].
- Extensions are stored as-is (case-preserving);
- see LanguageRegistry.HasExtension for matching rules.
- CommentMarkers ([]string) — line and block comment delimiters.
- BlockStart (string) — token that opens a code block, e.g. "{" or "begin".
- BlockEnd (string) — token that closes a code block, e.g. "}" or "end".
- Shebang (string) — typical shebang line when used as a script, or "".
- HasChunking (bool) — code-aware chunker planned/available.
- HasExtraction (bool) — documentation extractor planned/available.
- HasFormatting (bool) — formatter planned/available.
- HasHighlighting (bool) — syntax highlighter planned/available. *
- Example:
- info := LanguageInfo{ID: "go", Name: "Go", Extensions: []string{".go"}}
type LanguageRegistry ¶ added in v0.0.10
type LanguageRegistry struct {
// contains filtered or unexported fields
}
* LanguageRegistry is a central catalogue that maps language identifiers to
- their metadata and optional handlers (chunker, extractor, formatter,
- highlighter, detector). *
- The registry is populated once at package initialisation via init() and is
- read-only thereafter. No mutex is required for concurrent reads. *
- Example:
- lang, ok := globalRegistry.DetectFromExtension(".go")
- chunker := globalRegistry.GetChunker("go") // nil until Phase 3
func NewLanguageRegistry ¶ added in v0.0.10
func NewLanguageRegistry() *LanguageRegistry
- NewLanguageRegistry returns an empty, ready-to-use registry. *
- Returns:
- *LanguageRegistry — empty registry. *
- Example:
- r := NewLanguageRegistry()
- r.RegisterLanguage(goInfo, nil, nil, nil, nil, nil)
func (*LanguageRegistry) DetectFromExtension ¶ added in v0.0.10
func (r *LanguageRegistry) DetectFromExtension(ext string) (string, bool)
* DetectFromExtension returns the language ID for the given file extension.
- ext must include the leading dot, e.g. ".go". Matching is case-sensitive
- (exact) first; if no exact match is found, a case-insensitive fallback is
- tried. Returns ("", false) when no language owns that extension. *
- Parameters:
- ext (string) — file extension with leading dot, e.g. ".go", ".Mod". *
- Returns:
- language (string) — language ID, or "".
- ok (bool) — true when a match was found. *
- Example:
- lang, ok := r.DetectFromExtension(".go") // "go", true
- lang, ok = r.DetectFromExtension(".Mod") // "oberon", true
- lang, ok = r.DetectFromExtension(".xyz") // "", false
func (*LanguageRegistry) DetectLanguage ¶ added in v0.0.10
func (r *LanguageRegistry) DetectLanguage(filePath string, content []byte) (string, float64)
* DetectLanguage identifies the language of a file using a three-stage pipeline:
- (1) binary check — returns ("", 0) for binary content,
- (2) extension-based detection (confidence 1.0),
- (3) shebang detection (confidence 0.9),
- (4) keyword pattern detection (variable confidence).
- Returns ("", 0) when no language can be identified. *
- Parameters:
- filePath (string) — path to the file; extension is extracted with filepath.Ext.
- content ([]byte) — file contents; only the first maxKeywordScan bytes are scanned. *
- Returns:
- language (string) — language ID or "".
- confidence (float64) — confidence in [0, 1]; 0 means "not detected". *
- Example:
- lang, conf := globalRegistry.DetectLanguage("main.go", data) // "go", 1.0
- lang, conf = globalRegistry.DetectLanguage("script", shData) // "python", 0.9
func (*LanguageRegistry) GetChunker ¶ added in v0.0.10
func (r *LanguageRegistry) GetChunker(id string) CodeChunker
- GetChunker returns the CodeChunker registered for id, or nil. *
- Parameters:
- id (string) — language ID. *
- Returns:
- CodeChunker — handler, or nil. *
- Example:
- c := r.GetChunker("c")
func (*LanguageRegistry) GetDetector ¶ added in v0.0.10
func (r *LanguageRegistry) GetDetector(id string) LanguageDetector
- GetDetector returns the LanguageDetector registered for id, or nil. *
- Parameters:
- id (string) — language ID. *
- Returns:
- LanguageDetector — handler, or nil. *
- Example:
- d := r.GetDetector("go")
func (*LanguageRegistry) GetExtractor ¶ added in v0.0.10
func (r *LanguageRegistry) GetExtractor(id string) DocExtractor
- GetExtractor returns the DocExtractor registered for id, or nil. *
- Parameters:
- id (string) — language ID. *
- Returns:
- DocExtractor — handler, or nil. *
- Example:
- e := r.GetExtractor("pascal")
func (*LanguageRegistry) GetFormatter ¶ added in v0.0.10
func (r *LanguageRegistry) GetFormatter(id string) CodeFormatter
- GetFormatter returns the CodeFormatter registered for id, or nil. *
- Parameters:
- id (string) — language ID. *
- Returns:
- CodeFormatter — handler, or nil. *
- Example:
- f := r.GetFormatter("go")
func (*LanguageRegistry) GetHighlighter ¶ added in v0.0.10
func (r *LanguageRegistry) GetHighlighter(id string) SyntaxHighlighter
- GetHighlighter returns the SyntaxHighlighter registered for id, or nil. *
- Parameters:
- id (string) — language ID. *
- Returns:
- SyntaxHighlighter — handler, or nil. *
- Example:
- h := r.GetHighlighter("lisp")
func (*LanguageRegistry) GetLanguageInfo ¶ added in v0.0.10
func (r *LanguageRegistry) GetLanguageInfo(id string) (LanguageInfo, bool)
* GetLanguageInfo returns the LanguageInfo for the given language ID.
- ok is false when the language is not registered. *
- Parameters:
- id (string) — language ID, e.g. "go". *
- Returns:
- LanguageInfo — metadata struct.
- bool — true when the language is registered. *
- Example:
- info, ok := r.GetLanguageInfo("pascal")
func (*LanguageRegistry) HasExtension ¶ added in v0.0.10
func (r *LanguageRegistry) HasExtension(ext string) bool
* HasExtension returns true when ext (matched case-insensitively) belongs to
- any registered language. Use this for membership tests when you do not need
- to know which language owns the extension. *
- Parameters:
- ext (string) — file extension with leading dot, e.g. ".mod". *
- Returns:
- bool — true when the extension is known. *
- Example:
- r.HasExtension(".go") // true
- r.HasExtension(".Mod") // true (Oberon, case-insensitive)
- r.HasExtension(".xyz") // false
func (*LanguageRegistry) LanguageIDs ¶ added in v0.0.10
func (r *LanguageRegistry) LanguageIDs() []string
- LanguageIDs returns the IDs of all registered languages in an unspecified order. *
- Returns:
- []string — slice of language IDs. *
- Example:
- for _, id := range r.LanguageIDs() { fmt.Println(id) }
func (*LanguageRegistry) RegisterLanguage ¶ added in v0.0.10
func (r *LanguageRegistry) RegisterLanguage( info LanguageInfo, detector LanguageDetector, chunker CodeChunker, extractor DocExtractor, formatter CodeFormatter, highlighter SyntaxHighlighter, )
* RegisterLanguage adds a language and its optional handlers to the registry.
- Any handler may be nil; nil handlers are silently ignored in later lookups
- (GetChunker etc. return nil). Calling RegisterLanguage for the same ID a
- second time overwrites the previous entry. *
- Parameters:
- info (LanguageInfo) — language metadata.
- detector (LanguageDetector) — content/extension detector, or nil.
- chunker (CodeChunker) — code-aware chunker, or nil.
- extractor (DocExtractor) — documentation extractor, or nil.
- formatter (CodeFormatter) — code formatter, or nil.
- highlighter (SyntaxHighlighter)— syntax highlighter, or nil. *
- Example:
- r.RegisterLanguage(goInfo, nil, nil, nil, nil, nil)
func (*LanguageRegistry) SetChunker ¶ added in v0.0.10
func (r *LanguageRegistry) SetChunker(id string, c CodeChunker)
* SetChunker registers a CodeChunker for an already-registered language ID.
- Calling SetChunker for an unregistered ID is a no-op (the chunker is stored
- but no language metadata exists to associate it with). *
- Parameters:
- id (string) — language identifier, e.g. "c".
- c (CodeChunker) — chunker to register. *
- Example:
- r.SetChunker("c", NewCChunker("c"))
func (*LanguageRegistry) SetExtractor ¶ added in v0.0.10
func (r *LanguageRegistry) SetExtractor(id string, e DocExtractor)
* SetExtractor registers a DocExtractor for an already-registered language ID.
- Calling SetExtractor for an unregistered ID is a no-op (the extractor is
- stored but no language metadata exists to associate it with). *
- Parameters:
- id (string) — language identifier, e.g. "c".
- e (DocExtractor)— extractor to register. *
- Example:
- r.SetExtractor("c", NewCDocExtractor("c"))
func (*LanguageRegistry) SetFormatter ¶ added in v0.0.10
func (r *LanguageRegistry) SetFormatter(id string, f CodeFormatter)
- SetFormatter registers a CodeFormatter for an already-registered language ID. *
- Parameters:
- id (string) — language identifier, e.g. "go".
- f (CodeFormatter) — formatter to register. *
- Example:
- r.SetFormatter("go", newPipeExtFormatter("go", "gofmt"))
func (*LanguageRegistry) SetHighlighter ¶ added in v0.0.10
func (r *LanguageRegistry) SetHighlighter(id string, h SyntaxHighlighter)
* SetHighlighter registers a SyntaxHighlighter for an already-registered
- language ID. *
- Parameters:
- id (string) — language identifier, e.g. "c".
- h (SyntaxHighlighter)— highlighter to register. *
- Example:
- r.SetHighlighter("c", NewTerminalHighlighter())
type LispChunker ¶ added in v0.0.10
type LispChunker struct{}
* LispChunker splits Lisp/Common Lisp/Emacs Lisp source into enriched chunks
- at parenthesis-balanced top-level form boundaries. Each defun, defmacro,
- defvar, defclass, etc. becomes its own chunk. *
- Example:
- l := NewLispChunker()
- chunks := l.Chunk("(defun hello () (print \"hi\"))", "greet.lisp")
func NewLispChunker ¶ added in v0.0.10
func NewLispChunker() *LispChunker
- NewLispChunker returns a LispChunker. *
- Returns:
- *LispChunker — ready-to-use chunker. *
- Example:
- l := NewLispChunker()
func (*LispChunker) Chunk ¶ added in v0.0.10
func (l *LispChunker) Chunk(content string, _ string) []EnrichedChunk
- Chunk splits Lisp source into enriched chunks at top-level form boundaries. *
- Parameters:
- content (string) — Lisp source text.
- filePath (string) — source path; used for context only. *
- Returns:
- []EnrichedChunk — chunks with location and symbol metadata. *
- Example:
- chunks := l.Chunk(src, "funcs.lisp")
func (*LispChunker) Language ¶ added in v0.0.10
func (l *LispChunker) Language() string
- Language returns "lisp". *
- Returns:
- string — "lisp". *
- Example:
- l.Language() // "lisp"
type LispDocExtractor ¶ added in v0.0.10
type LispDocExtractor struct{}
* LispDocExtractor extracts documentation from Lisp/Common Lisp/Emacs Lisp source.
- It recognises semicolon line comments (;, ;;, ;;;), block comments (#| |#),
- and docstrings embedded in DEFUN/DEFMACRO/DEFMETHOD forms. *
- Example:
- e := NewLispDocExtractor()
- docs := e.ExtractDocs(";; Add two numbers.\n(defun add (a b) \"Add a and b.\" (+ a b))\n")
func NewLispDocExtractor ¶ added in v0.0.10
func NewLispDocExtractor() *LispDocExtractor
- NewLispDocExtractor returns a LispDocExtractor. *
- Returns:
- *LispDocExtractor — ready-to-use extractor. *
- Example:
- l := NewLispDocExtractor()
func (*LispDocExtractor) ExtractDocs ¶ added in v0.0.10
func (e *LispDocExtractor) ExtractDocs(content string) []DocumentationBlock
- ExtractDocs returns all DocumentationBlocks found in Lisp source. *
- Parameters:
- content (string) — Lisp source text. *
- Returns:
- []DocumentationBlock — blocks including semicolon comments, #| |# blocks,
- and DEFUN docstrings. *
- Example:
- docs := e.ExtractDocs(";; Returns x.\n(defun get-x () x)\n")
func (*LispDocExtractor) ExtractSymbols ¶ added in v0.0.10
func (e *LispDocExtractor) ExtractSymbols(content string) map[string]string
- ExtractSymbols returns a map of symbol name → documentation text for Lisp. *
- Parameters:
- content (string) — Lisp source text. *
- Returns:
- map[string]string — symbol → doc text. *
- Example:
- syms := e.ExtractSymbols(";; Returns x.\n(defun get-x () x)\n")
- // syms["get-x"] == "Returns x."
func (*LispDocExtractor) Language ¶ added in v0.0.10
func (e *LispDocExtractor) Language() string
- Language returns "lisp". *
- Returns:
- string — "lisp". *
- Example:
- e.Language() // "lisp"
type LlamafileEntry ¶ added in v0.0.12
- LlamafileEntry describes one registered llamafile model in Harvey's registry. *
- Fields:
- Name (string) — short identifier used with /llamafile use, e.g. "qwen-coding".
- Path (string) — path to the binary; absolute or workspace-relative. *
- Example:
- e := LlamafileEntry{Name: "qwen", Path: "/home/user/Models/Qwen3.5-4B.llamafile"}
type Manifest ¶ added in v0.0.6
type Manifest struct {
Sessions []ManifestEntry `yaml:"sessions"`
}
* Manifest tracks which session files have been fully reviewed for memory
- extraction. It is stored as agents/memories/manifest.yaml so it is
- human-readable and version-controllable alongside the memory files. *
- A session is recorded only after the full interactive review completes;
- an interrupted review leaves the session absent from the manifest so it
- will be offered again on the next /memory mine run. *
- Example:
- m, err := LoadManifest(store.Dir())
- if m.IsMined("agents/sessions/foo.spmd") {
- fmt.Println("already reviewed")
- }
func LoadManifest ¶ added in v0.0.6
* LoadManifest reads the manifest from dir/manifest.yaml. If the file does
- not exist an empty Manifest is returned without error. *
- Parameters:
- dir (string) — absolute path to agents/memories/. *
- Returns:
- *Manifest — loaded or empty manifest.
- error — on read or YAML parse failure (not on missing file). *
- Example:
- m, err := LoadManifest(store.Dir())
func (*Manifest) IsMined ¶ added in v0.0.6
* IsMined returns true if sessionPath appears in the manifest, indicating
- that it has already been fully reviewed. *
- Parameters:
- sessionPath (string) — path to the session file (any form; compared
- as a string against stored paths). *
- Returns:
- bool — true if the session has a completed review entry. *
- Example:
- if !m.IsMined("agents/sessions/foo.spmd") {
- // offer for review
- }
func (*Manifest) Record ¶ added in v0.0.6
* Record appends a completed review entry for sessionPath. created is the
- list of memory IDs that were accepted; skipped is the count that were
- declined. *
- Parameters:
- sessionPath (string) — path to the reviewed session file.
- created ([]string) — IDs of memories saved during review.
- skipped (int) — number of proposed memories the user declined. *
- Example:
- m.Record("agents/sessions/foo.spmd", []string{"tool_use_a1b2c3"}, 2)
- m.Save(store.Dir())
func (*Manifest) Save ¶ added in v0.0.6
* Save writes the manifest to dir/manifest.yaml, creating the file if it
- does not exist. *
- Parameters:
- dir (string) — absolute path to agents/memories/. *
- Returns:
- error — on YAML marshal or file write failure. *
- Example:
- err := m.Save(store.Dir())
func (*Manifest) UnminedSessions ¶ added in v0.0.6
* UnminedSessions returns all .spmd files under sessionsDir that do not
- appear in the manifest, in filesystem order. This is the set of sessions
- that /memory mine would process. *
- Parameters:
- sessionsDir (string) — absolute path to the sessions directory. *
- Returns:
- []string — absolute paths to unmined session files.
- error — on directory read failure. *
- Example:
- paths, err := m.UnminedSessions("/home/user/project/agents/sessions")
- for _, p := range paths {
- fmt.Println(p)
- }
type ManifestEntry ¶ added in v0.0.6
type ManifestEntry struct {
Path string `yaml:"path"`
MinedAt string `yaml:"mined_at"`
MemoriesCreated []string `yaml:"memories_created"`
MemoriesSkipped int `yaml:"memories_skipped"`
}
- ManifestEntry records the result of mining a single session file. *
- Fields:
- Path (string) — workspace-relative path to the session file.
- MinedAt (string) — RFC3339 timestamp when review completed.
- MemoriesCreated ([]string) — IDs of memories accepted during review.
- MemoriesSkipped (int) — count of proposed memories the user skipped. *
- Example:
- fmt.Printf("mined %s: created %d, skipped %d\n",
- e.Path, len(e.MemoriesCreated), e.MemoriesSkipped)
type MemoryConfig ¶ added in v0.0.6
type MemoryConfig struct {
Enabled bool
TopK int
InjectOnStart bool
BudgetPct float64 // fraction of model context window for memory injection
RollingSummary RollingSummaryConfig // working-memory compression settings
RagStores []RagStoreEntry // all registered named RAG stores
RagActive string // name of the currently active RAG store; "" = none
RagEnabled bool // when true, inject top-K chunks before each Chat call
KnowledgeDB string // path to knowledge.db; empty = agents/knowledge.db
CurrentProjectID int64 // in-session active knowledge-base project ID (0 = none)
}
- MemoryConfig controls the behaviour of Harvey's memory system. *
- Fields:
- Enabled (bool) — when false the entire memory system is skipped; default true.
- TopK (int) — number of memories retrieved at session start; default 5.
- InjectOnStart (bool) — inject memory context block in ClearHistory; default true.
- BudgetPct (float64) — fraction of model context window allocated to memory
- injection (default 0.25); falls back to 512 tokens when
- OllamaContextLength is unknown.
- RollingSummary (RollingSummaryConfig) — working-memory compression settings.
- RagStores ([]RagStoreEntry) — all registered named RAG stores.
- RagActive (string) — name of the currently active RAG store; "" = none.
- RagEnabled (bool) — when true, inject top-K chunks before each Chat call.
- KnowledgeDB (string) — path to knowledge.db; empty = agents/knowledge.db.
- CurrentProjectID (int64) — in-session active knowledge-base project ID (0 = none). *
- Example:
- cfg.Memory = MemoryConfig{Enabled: true, TopK: 5, InjectOnStart: true, BudgetPct: 0.25}
func (*MemoryConfig) ActiveRagStore ¶ added in v0.0.6
func (m *MemoryConfig) ActiveRagStore() *RagStoreEntry
* ActiveRagStore returns a pointer to the active RagStoreEntry in the memory
- config, or nil when no store is configured. *
- Returns:
- *RagStoreEntry — the active entry, or nil. *
- Example:
- if e := cfg.Memory.ActiveRagStore(); e != nil {
- fmt.Println(e.DBPath)
- }
func (*MemoryConfig) AddOrUpdateRagStore ¶ added in v0.0.6
func (m *MemoryConfig) AddOrUpdateRagStore(e RagStoreEntry)
* AddOrUpdateRagStore inserts e into the memory config registry if its name
- is new, or replaces the existing entry if one with the same name exists. *
- Parameters:
- e (RagStoreEntry) — the entry to add or replace. *
- Example:
- cfg.Memory.AddOrUpdateRagStore(RagStoreEntry{Name: "golang", DBPath: "agents/rag/golang.db"})
func (*MemoryConfig) RagStoreByName ¶ added in v0.0.6
func (m *MemoryConfig) RagStoreByName(name string) *RagStoreEntry
* RagStoreByName returns a pointer to the named store entry in the memory
- config, or nil when not found. *
- Parameters:
- name (string) — store name to look up. *
- Returns:
- *RagStoreEntry — matching entry, or nil. *
- Example:
- if e := cfg.Memory.RagStoreByName("golang"); e != nil {
- fmt.Println(e.EmbeddingModel)
- }
func (*MemoryConfig) RemoveRagStore ¶ added in v0.0.6
func (m *MemoryConfig) RemoveRagStore(name string)
* RemoveRagStore removes the store with the given name from the memory config
- registry. It is a no-op when no store with that name exists. *
- Parameters:
- name (string) — name of the store to remove. *
- Example:
- cfg.Memory.RemoveRagStore("research-llm")
type MemoryDoc ¶ added in v0.0.6
type MemoryDoc struct {
Meta MemoryMeta
FountainBody string // everything after the closing ---\n
}
* MemoryDoc is a parsed memory file: structured YAML metadata plus a
- Fountain-format body. The FountainBody begins at "FADE IN:" and ends
- with "THE END." and uses the INT. MEMORY <TIMESTAMP> scene heading. *
- Example:
- doc, err := ParseMemoryDoc(data)
- fmt.Println(doc.Meta.Description)
func NewMemoryDoc ¶ added in v0.0.6
func NewMemoryDoc(id string, memType MemoryType, description, summary string, tags []string) *MemoryDoc
* NewMemoryDoc creates a new MemoryDoc with the given fields and sets
- CreatedAt, UpdatedAt, empty Supersedes, and default Confidence of 0.5.
- The caller is responsible for populating FountainBody, Kind, and Action
- before saving. *
- Parameters:
- id (string) — unique identifier (see GenerateMemoryID).
- memType (MemoryType) — one of MemoryTypeToolUse, etc.
- description (string) — one-sentence human summary.
- summary (string) — 2-3 sentence explanation of what happened and why it matters.
- tags ([]string) — keyword tags for filtering. *
- Returns:
- *MemoryDoc — new document with empty FountainBody, Kind, Action and Confidence 0.5. *
- Example:
- doc := NewMemoryDoc("git_fix_a3f891", MemoryTypeToolUse,
- "Fixed fatal: not a git repository", "...", []string{"git","fix"})
- doc.Meta.Kind = "pitfall"
- doc.Meta.Action = "Run `git init` in project root, then retry."
func ParseMemoryDoc ¶ added in v0.0.6
* ParseMemoryDoc parses a memory file from raw bytes. The file must begin
- with a --- delimited YAML front matter block. Everything after the closing
- --- is the Fountain body. *
- Parameters:
- data ([]byte) — raw file contents. *
- Returns:
- *MemoryDoc — parsed document.
- error — if the front matter is missing, malformed, or the YAML
- cannot be decoded. *
- Example:
- data, _ := os.ReadFile("agents/memories/tool_use/git_fix_a3f891.fountain")
- doc, err := ParseMemoryDoc(data)
func (*MemoryDoc) ArchivePath ¶ added in v0.0.6
* ArchivePath returns the file path for this memory document when archived.
- Archived files live under {baseDir}/archive/{type}/{id}.fountain. *
- Parameters:
- baseDir (string) — absolute path to the memories root directory. *
- Returns:
- string — absolute archive file path. *
- Example:
- path := doc.ArchivePath("/home/user/project/agents/memories")
- // → "/home/user/project/agents/memories/archive/tool_use/git_fix_a3f891.fountain"
func (*MemoryDoc) Bytes ¶ added in v0.0.6
* Bytes serialises the MemoryDoc back to its file representation:
- YAML front matter delimited by --- followed by the Fountain body. *
- Returns:
- []byte — the file contents ready to write to disk.
- error — if the YAML cannot be marshalled. *
- Example:
- data, err := doc.Bytes()
- os.WriteFile(doc.FilePath("agents/memories"), data, 0o644)
func (*MemoryDoc) EmbedText ¶ added in v0.0.6
* EmbedText returns the text used to generate the embedding for this
- memory. It combines description, tags, summary, and action (when present)
- to produce a compact, semantically rich representation. *
- Returns:
- string — the text to pass to the embedder. *
- Example:
- vec, err := embedder.Embed(doc.EmbedText())
func (*MemoryDoc) FilePath ¶ added in v0.0.6
* FilePath returns the canonical file path for this memory document under
- baseDir. The path follows the pattern {baseDir}/{type}/{id}.fountain. *
- Parameters:
- baseDir (string) — absolute path to the memories root directory
- (e.g. agents/memories resolved to absolute). *
- Returns:
- string — absolute file path for this memory. *
- Example:
- path := doc.FilePath("/home/user/project/agents/memories")
- // → "/home/user/project/agents/memories/tool_use/git_fix_a3f891.fountain"
type MemoryMeta ¶ added in v0.0.6
type MemoryMeta struct {
ID string `yaml:"id"`
Type MemoryType `yaml:"type"`
Kind string `yaml:"kind,omitempty"`
CreatedAt string `yaml:"created_at"`
UpdatedAt string `yaml:"updated_at"`
Supersedes []string `yaml:"supersedes"`
Tags []string `yaml:"tags"`
Description string `yaml:"description"`
Summary string `yaml:"summary"`
Action string `yaml:"action,omitempty"`
Confidence float64 `yaml:"confidence,omitempty"`
SourceSession string `yaml:"source_session,omitempty"`
Metadata map[string]any `yaml:"metadata,omitempty"`
}
* MemoryMeta holds the structured YAML front matter of a memory document.
- It replaces the standard Fountain title block, so the file begins with
- a --- delimited YAML section followed by a proper Fountain body. *
- Kind classifies why the knowledge matters: "pitfall" (permanent gotcha),
- "workaround" (useful now, may be superseded), "recommendation" (preferred
- approach), "pattern" (recurring success), or "" (unclassified). *
- Action is the imperative step a future agent should take. Empty when no
- clear action applies. *
- Confidence is a reliability score in [0.0, 1.0]. New memories default to
- 0.5. Memories that fall to or below 0.2 are auto-archived. *
- Example:
- meta := MemoryMeta{
- ID: "git_fix_a3f891",
- Type: MemoryTypeToolUse,
- Kind: "pitfall",
- Description: "Fixed 'fatal: not a git repository' with git init",
- Action: "Run `git init` in project root, then retry.",
- Confidence: 0.5,
- }
type MemoryStore ¶ added in v0.0.6
type MemoryStore struct {
// contains filtered or unexported fields
}
* MemoryStore manages a workspace's memory documents: the on-disk
- .fountain files under agents/memories/ and a companion SQLite index
- (memories.db) that stores metadata, FTS5 tokens, and embedding vectors
- for fast retrieval. *
- The .fountain files are the source of truth. If memories.db is absent,
- NewMemoryStore rebuilds it by walking the directory tree. *
- Example:
- store, err := NewMemoryStore(ws)
- if err != nil { log.Fatal(err) }
- defer store.Close()
func NewMemoryStore ¶ added in v0.0.6
func NewMemoryStore(ws *Workspace) (*MemoryStore, error)
* NewMemoryStore opens (or creates) the memory store for the given
- workspace. It creates the directory tree, opens memories.db, applies
- the schema, and rebuilds the index from files if the database is empty. *
- Parameters:
- ws (*Workspace) — the Harvey workspace. *
- Returns:
- *MemoryStore — ready-to-use store.
- error — if directories cannot be created or the database fails. *
- Example:
- store, err := NewMemoryStore(ws)
- if err != nil { log.Fatal(err) }
- defer store.Close()
func (*MemoryStore) Archive ¶ added in v0.0.6
func (s *MemoryStore) Archive(id string) error
* Archive moves a memory from the active store to the archive directory
- and marks it as archived in the database. The original file is removed
- from its type subdirectory. *
- Parameters:
- id (string) — ID of the memory to archive. *
- Returns:
- error — if the memory is not found, the file cannot be moved, or the
- database update fails. *
- Example:
- err := store.Archive("git_fix_a3f891")
func (*MemoryStore) BudgetStats ¶ added in v0.0.6
func (s *MemoryStore) BudgetStats(n int) (avgSaturation, compressionRate, avgToksPerSec float64, err error)
* BudgetStats computes aggregate memory budget statistics from the last n rows
- of memory_stats. Used by /memory status to generate tuning suggestions. *
- Parameters:
- n (int) — number of most-recent sessions to include; e.g. 10. *
- Returns:
- avgSaturation (float64) — mean(injected_tokens/budget_tokens); 0 when budget was 0.
- compressionRate (float64) — fraction of sessions where rolling summary fired.
- avgToksPerSec (float64) — mean generation throughput across sessions.
- error — on database failure. *
- Example:
- sat, compRate, tps, err := store.BudgetStats(10)
- fmt.Printf("avg utilisation %.0f%%\n", sat*100)
func (*MemoryStore) ByID ¶ added in v0.0.6
func (s *MemoryStore) ByID(id string) (*MemoryDoc, error)
* ByID returns the MemoryDoc with the given ID, reading it from its file.
- Returns (nil, nil) when the ID is not found. *
- Parameters:
- id (string) — memory ID to look up. *
- Returns:
- *MemoryDoc — the memory, or nil if not found.
- error — on database or file read failure. *
- Example:
- doc, err := store.ByID("git_fix_a3f891")
func (*MemoryStore) Close ¶ added in v0.0.6
func (s *MemoryStore) Close() error
- Close releases the database connection. *
- Returns:
- error — from the underlying sql.DB.Close call. *
- Example:
- defer store.Close()
func (*MemoryStore) Count ¶ added in v0.0.6
func (s *MemoryStore) Count() (int64, error)
- Count returns the number of non-archived memories in the store. *
- Returns:
- int64 — total active memory count.
- error — on database failure. *
- Example:
- n, _ := store.Count()
- fmt.Printf("%d memories\n", n)
func (*MemoryStore) Dir ¶ added in v0.0.6
func (s *MemoryStore) Dir() string
- Dir returns the absolute path to the memories root directory. *
- Returns:
- string — e.g. "/home/user/project/agents/memories". *
- Example:
- fmt.Println(store.Dir())
func (*MemoryStore) List ¶ added in v0.0.6
func (s *MemoryStore) List(typeFilter string) ([]MemoryMeta, error)
* List returns metadata for all non-archived memories. When typeFilter is
- non-empty only memories of that type are returned. Results are ordered
- by updated_at descending. *
- Parameters:
- typeFilter (string) — memory type to filter on, or "" for all types. *
- Returns:
- []MemoryMeta — metadata rows; empty (not nil) if none found.
- error — on database failure. *
- Example:
- metas, err := store.List("tool_use")
- for _, m := range metas {
- fmt.Printf("%s %s\n", m.ID, m.Description)
- }
func (*MemoryStore) ListDocs ¶ added in v0.0.6
func (s *MemoryStore) ListDocs(typeFilter string) ([]MemoryDoc, error)
* ListDocs returns full MemoryDoc objects for all non-archived memories.
- When typeFilter is non-empty only memories of that type are returned.
- Results are ordered by updated_at descending. *
- Parameters:
- typeFilter (string) — memory type to filter on, or "" for all types. *
- Returns:
- []MemoryDoc — documents with parsed front matter and Fountain body.
- error — on database or file read failure. *
- Example:
- docs, err := store.ListDocs("workspace_profile")
- for _, d := range docs { fmt.Println(d.Meta.Description) }
func (*MemoryStore) Query ¶ added in v0.0.6
* Query embeds the query string and returns the topK non-archived memories
- with the highest cosine similarity to the query embedding. *
- Parameters:
- query (string) — the search query.
- embedder (Embedder) — used to embed the query.
- topK (int) — maximum number of results to return. *
- Returns:
- []MemoryDoc — up to topK documents ordered by descending similarity.
- error — on embedding or database failure. *
- Example:
- docs, err := store.Query("git repository error", embedder, 5)
func (*MemoryStore) Recent ¶ added in v0.0.6
func (s *MemoryStore) Recent(n int) ([]MemoryDoc, error)
* Recent returns the n most recently updated non-archived MemoryDocs,
- reading each document from its file. *
- Parameters:
- n (int) — maximum number of documents to return. *
- Returns:
- []MemoryDoc — up to n documents ordered by updated_at descending.
- error — on database or file read failure. *
- Example:
- docs, err := store.Recent(5)
func (*MemoryStore) RecordSessionStats ¶ added in v0.0.6
func (s *MemoryStore) RecordSessionStats(sessionID string, budgetTokens, injectedTokens int, compressed bool, avgToksPerSec float64) error
* RecordSessionStats appends one row to the memory_stats table for the
- session that just ended. Called at session exit by the REPL. *
- Parameters:
- sessionID (string) — filename of the session .spmd file; may be empty.
- budgetTokens (int) — token budget allocated for memory injection.
- injectedTokens (int) — tokens actually injected this session.
- compressed (bool) — true if rolling summary fired at least once.
- avgToksPerSec (float64) — average generation throughput across all turns. *
- Returns:
- error — on database write failure. *
- Example:
- _ = store.RecordSessionStats("harvey-session-20260526.spmd", 512, 123, false, 14.2)
func (*MemoryStore) Save ¶ added in v0.0.6
func (s *MemoryStore) Save(doc *MemoryDoc, embedder Embedder) error
* Save writes a MemoryDoc to disk and indexes it in the database. If a
- row with the same ID already exists it is replaced. The embedding is
- computed from doc.EmbedText() using the provided embedder. *
- Parameters:
- doc (*MemoryDoc) — the memory document to persist.
- embedder (Embedder) — used to compute the embedding vector. *
- Returns:
- error — on file write, embedding, or database failure. *
- Example:
- err := store.Save(doc, embedder)
func (*MemoryStore) SearchFTS ¶ added in v0.0.6
func (s *MemoryStore) SearchFTS(query string, topK int) ([]ScoredDoc, error)
* SearchFTS returns non-archived memories matching query using FTS5 full-text
- search. Results are ordered by relevance (best match first). Returns nil when
- FTS5 is unavailable or query is empty. *
- Parameters:
- query (string) — search text passed to the FTS5 MATCH operator.
- topK (int) — maximum number of results to return. *
- Returns:
- []ScoredDoc — up to topK documents ordered by descending relevance.
- error — on database failure. *
- Example:
- docs, err := store.SearchFTS("git repository", 5)
func (*MemoryStore) SetConfidence ¶ added in v0.0.12
func (s *MemoryStore) SetConfidence(id string, delta float64) (float64, error)
* SetConfidence adjusts the confidence of an active memory by delta and
- clamps the result to [0.0, 1.0]. Both the database row and the on-disk
- .fountain file are updated so that a database rebuild preserves the value.
- If the resulting confidence is <= 0.2 the memory is automatically archived
- and ErrAutoArchived is returned alongside the final confidence value. *
- Parameters:
- id (string) — ID of the memory to adjust.
- delta (float64) — positive to increase, negative to decrease confidence. *
- Returns:
- float64 — the clamped confidence value after adjustment.
- error — ErrAutoArchived when auto-archival triggered; other errors on
- database or file failure; nil on success. *
- Example:
- newConf, err := store.SetConfidence("git_fix_a3f891", -0.1)
- if errors.Is(err, ErrAutoArchived) {
- fmt.Println("memory archived due to low confidence")
- }
func (*MemoryStore) StatsCount ¶ added in v0.0.6
func (s *MemoryStore) StatsCount() (int64, error)
- StatsCount returns the total number of rows in the memory_stats table. *
- Returns:
- int64 — row count.
- error — on database failure. *
- Example:
- n, _ := store.StatsCount()
- if n >= 10 { /* show advice */ }
func (*MemoryStore) WriteDigest ¶ added in v0.0.12
func (s *MemoryStore) WriteDigest(path string) error
* WriteDigest renders a Markdown summary of all active memories to path.
- Memories are grouped by kind (pitfall → workaround → recommendation →
- pattern → unclassified) and sorted by confidence descending within each
- group. The file is not written when there are no active memories. *
- Parameters:
- path (string) — absolute path to write the digest file. *
- Returns:
- error — on database query or file write failure. *
- Example:
- _ = store.WriteDigest(filepath.Join(store.Dir(), "DIGEST.md"))
type MemoryType ¶ added in v0.0.6
type MemoryType string
- MemoryType identifies the category of a memory document. *
- Example:
- doc := &MemoryDoc{Meta: MemoryMeta{Type: MemoryTypeToolUse}}
const ( MemoryTypeToolUse MemoryType = "tool_use" MemoryTypeWorkflow MemoryType = "workflow" MemoryTypeUserPreference MemoryType = "user_preference" MemoryTypeWorkspaceProfile MemoryType = "workspace_profile" MemoryTypeProjectFact MemoryType = "project_fact" )
type Message ¶
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
Parts []anyllm.ContentPart `json:"parts,omitempty"`
ToolCalls []anyllm.ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
}
- Message represents a single chat message exchanged with a backend. *
- Fields:
- Role (string) — "system", "user", or "assistant".
- Content (string) — message body; ignored when Parts is non-empty.
- Parts ([]anyllm.ContentPart) — multimodal content parts (e.g. image + text);
- when non-empty, overrides Content.
- ToolCalls ([]anyllm.ToolCall) — tool call requests from the assistant.
- ToolCallID (string) — correlates a tool-result message to its request. *
- Example:
- msg := Message{Role: "user", Content: "Hello!"}
type Miner ¶ added in v0.0.6
type Miner struct {
// contains filtered or unexported fields
}
* Miner drives the mining and interactive review pipeline for a Harvey
- session file. It calls the LLM once to propose memories, then runs an
- interactive REPL for the user to accept, edit, skip, or supersede each
- proposed memory. The session is recorded in the manifest only after the
- full review completes. *
- Example:
- miner := NewMiner(store, manifest, ws)
- err := miner.Mine(ctx, "agents/sessions/foo.spmd", agent, embedder, os.Stdout, os.Stdin)
func NewMiner ¶ added in v0.0.6
func NewMiner(store *MemoryStore, manifest *Manifest, ws *Workspace) *Miner
* NewMiner creates a Miner that writes to store, tracks sessions in
- manifest, and normalises workspace paths using ws. *
- Parameters:
- store (*MemoryStore) — destination memory store.
- manifest (*Manifest) — manifest tracking mined sessions.
- ws (*Workspace) — workspace for path normalisation. *
- Returns:
- *Miner — ready miner. *
- Example:
- miner := NewMiner(store, manifest, ws)
func (*Miner) Mine ¶ added in v0.0.6
func (m *Miner) Mine(ctx context.Context, sessionPath string, agent *Agent, embedder Embedder, out io.Writer, in io.Reader) error
* Mine reads sessionPath, asks the LLM to propose memories, runs the
- interactive review loop, and records the session in the manifest when
- the review completes fully. An interrupted review (quit) leaves the
- session absent from the manifest so it is re-offered on the next run. *
- Parameters:
- ctx (context.Context) — cancellation context.
- sessionPath (string) — absolute path to the .spmd session file.
- agent (*Agent) — Harvey agent providing the LLM client.
- embedder (Embedder) — used for near-duplicate detection and
- embedding; nil disables both.
- out (io.Writer) — where prompts and results are written.
- in (io.Reader) — where user input is read. *
- Returns:
- error — on session read, LLM, or store failure. *
- Example:
- err := miner.Mine(ctx, "agents/sessions/foo.spmd", agent, embedder, os.Stdout, os.Stdin)
func (*Miner) MineAuto ¶ added in v0.0.6
func (m *Miner) MineAuto(ctx context.Context, sessionPath string, agent *Agent, embedder Embedder, out io.Writer) error
* MineAuto runs non-interactive memory extraction on sessionPath. All
- proposed memories that are not near-duplicates of existing memories are
- saved without user review. The session is recorded in the manifest so that
- a subsequent /memory mine run skips it (or reports "already mined"). *
- Parameters:
- ctx (context.Context) — cancellation context.
- sessionPath (string) — absolute path to the session file.
- agent (*Agent) — provides the LLM client for extraction.
- embedder (Embedder) — used for near-duplicate detection; may be nil.
- out (io.Writer) — status output. *
- Returns:
- error — on session read, LLM, or store failure. *
- Example:
- miner.MineAuto(ctx, "/agents/sessions/foo.spmd", agent, embedder, os.Stdout)
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 OberonChunker ¶ added in v0.0.10
type OberonChunker struct{}
* OberonChunker splits Oberon source into enriched chunks at PROCEDURE
- boundaries. MODULE headers and IMPORT/CONST/TYPE/VAR sections are emitted
- as "code" chunks; each PROCEDURE is its own chunk. *
- Note: Oberon supports nested comment delimiters (* (* *) *); this chunker
- treats them as non-nested (known approximation). *
- Example:
- o := NewOberonChunker()
- chunks := o.Chunk("MODULE Foo;\nPROCEDURE Bar;\nBEGIN END Bar;\nEND Foo.", "Foo.Mod")
func NewOberonChunker ¶ added in v0.0.10
func NewOberonChunker() *OberonChunker
- NewOberonChunker returns an OberonChunker. *
- Returns:
- *OberonChunker — ready-to-use chunker. *
- Example:
- o := NewOberonChunker()
func (*OberonChunker) Chunk ¶ added in v0.0.10
func (o *OberonChunker) Chunk(content string, _ string) []EnrichedChunk
- Chunk splits Oberon source into PROCEDURE chunks and code sections. *
- Parameters:
- content (string) — Oberon source text.
- filePath (string) — source path; used for context only. *
- Returns:
- []EnrichedChunk — chunks with location and symbol metadata. *
- Example:
- chunks := o.Chunk(src, "Foo.Mod")
func (*OberonChunker) Language ¶ added in v0.0.10
func (o *OberonChunker) Language() string
- Language returns "oberon". *
- Returns:
- string — "oberon". *
- Example:
- o.Language() // "oberon"
type OberonDocExtractor ¶ added in v0.0.10
type OberonDocExtractor struct{}
* OberonDocExtractor extracts documentation from Oberon source code.
- It recognises only (* *) block comments; Oberon has no line-comment syntax.
- Note: nested (* (* *) *) comments are treated as non-nested (same
- approximation as OberonChunker). *
- Example:
- e := NewOberonDocExtractor()
- docs := e.ExtractDocs("(* Adds a to b. *)\nPROCEDURE Add*(a,b:INTEGER):INTEGER;\n")
func NewOberonDocExtractor ¶ added in v0.0.10
func NewOberonDocExtractor() *OberonDocExtractor
- NewOberonDocExtractor returns an OberonDocExtractor. *
- Returns:
- *OberonDocExtractor — ready-to-use extractor. *
- Example:
- e := NewOberonDocExtractor()
func (*OberonDocExtractor) ExtractDocs ¶ added in v0.0.10
func (e *OberonDocExtractor) ExtractDocs(content string) []DocumentationBlock
- ExtractDocs returns all DocumentationBlocks found in Oberon source. *
- Parameters:
- content (string) — Oberon source text. *
- Returns:
- []DocumentationBlock — blocks with line range and symbol association. *
- Example:
- docs := e.ExtractDocs("(* Greet the user. *)\nPROCEDURE Greet*;\n")
func (*OberonDocExtractor) ExtractSymbols ¶ added in v0.0.10
func (e *OberonDocExtractor) ExtractSymbols(content string) map[string]string
- ExtractSymbols returns a map of symbol name → documentation text for Oberon. *
- Parameters:
- content (string) — Oberon source text. *
- Returns:
- map[string]string — symbol → doc text. *
- Example:
- syms := e.ExtractSymbols("(* Greet user. *)\nPROCEDURE Greet*;\n")
- // syms["Greet"] == "Greet user."
func (*OberonDocExtractor) Language ¶ added in v0.0.10
func (e *OberonDocExtractor) Language() string
- Language returns "oberon". *
- Returns:
- string — "oberon". *
- Example:
- e.Language() // "oberon"
type Observation ¶
type Observation struct {
ID int64
ProjectID int64
Kind string
Body string
SourceDOI string
CreatedAt time.Time
}
* Observation represents a single timestamped note, finding, decision,
- question, or hypothesis attached to a project. SourceDOI records the
- normalized DOI of the paper the observation was extracted from, if any;
- it is "" for observations not tied to a specific source document. *
- 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 PDFInfo ¶ added in v0.0.5
- PDFInfo holds document-level metadata produced by pdfinfo. *
- Fields:
- Title (string) — document title from PDF metadata; may be empty.
- Author (string) — document author from PDF metadata; may be empty.
- Pages (int) — total page count.
- CreatedAt (string) — creation date string as reported by pdfinfo.
type PDFResult ¶ added in v0.0.5
- PDFResult holds all content extracted from a PDF by pdfExtract. *
- Fields:
- Info (PDFInfo) — document metadata from pdfinfo.
- Text (string) — full extracted text from pdftotext -layout; pages
- are separated by the form-feed character (\f).
- DiagramPages ([]int) — 1-based page numbers that appear to contain only
- vector graphics (sparse text, no raster images).
- Content on these pages is incomplete; flag them
- for follow-up with a vision-capable model.
type PascalChunker ¶ added in v0.0.10
type PascalChunker struct{}
* PascalChunker splits Pascal source into enriched chunks at PROCEDURE and
- FUNCTION boundaries, tracking nested BEGIN/END blocks. *
- Example:
- p := NewPascalChunker()
- chunks := p.Chunk("PROCEDURE Foo;\nBEGIN\nWRITELN('hi');\nEND;", "foo.pas")
func NewPascalChunker ¶ added in v0.0.10
func NewPascalChunker() *PascalChunker
- NewPascalChunker returns a PascalChunker. *
- Returns:
- *PascalChunker — ready-to-use chunker. *
- Example:
- p := NewPascalChunker()
func (*PascalChunker) Chunk ¶ added in v0.0.10
func (p *PascalChunker) Chunk(content string, _ string) []EnrichedChunk
- Chunk splits Pascal source into PROCEDURE/FUNCTION chunks and code sections. *
- Parameters:
- content (string) — Pascal source text.
- filePath (string) — source path; used for context only. *
- Returns:
- []EnrichedChunk — chunks with location and symbol metadata. *
- Example:
- chunks := p.Chunk(src, "prog.pas")
func (*PascalChunker) Language ¶ added in v0.0.10
func (p *PascalChunker) Language() string
- Language returns "pascal". *
- Returns:
- string — "pascal". *
- Example:
- p.Language() // "pascal"
type PascalDocExtractor ¶ added in v0.0.10
type PascalDocExtractor struct{}
* PascalDocExtractor extracts documentation from Pascal source code.
- It recognises line comments (//), brace block comments ({ }),
- and parenthesis-star block comments ((* *)). {$...} compiler directives
- are ignored. *
- Example:
- e := NewPascalDocExtractor()
- docs := e.ExtractDocs("{ Adds a and b. }\nFUNCTION Add(a,b:Integer):Integer;\n")
func NewPascalDocExtractor ¶ added in v0.0.10
func NewPascalDocExtractor() *PascalDocExtractor
- NewPascalDocExtractor returns a PascalDocExtractor. *
- Returns:
- *PascalDocExtractor — ready-to-use extractor. *
- Example:
- e := NewPascalDocExtractor()
func (*PascalDocExtractor) ExtractDocs ¶ added in v0.0.10
func (e *PascalDocExtractor) ExtractDocs(content string) []DocumentationBlock
- ExtractDocs returns all DocumentationBlocks found in Pascal source. *
- Parameters:
- content (string) — Pascal source text. *
- Returns:
- []DocumentationBlock — blocks with type, line range, and symbol association. *
- Example:
- docs := e.ExtractDocs("{ Sort the list. }\nPROCEDURE Sort(var L:TList);\n")
func (*PascalDocExtractor) ExtractSymbols ¶ added in v0.0.10
func (e *PascalDocExtractor) ExtractSymbols(content string) map[string]string
- ExtractSymbols returns a map of symbol name → documentation text for Pascal. *
- Parameters:
- content (string) — Pascal source text. *
- Returns:
- map[string]string — symbol → doc text. *
- Example:
- syms := e.ExtractSymbols("(* Sort items. *)\nPROCEDURE Sort;\n")
- // syms["Sort"] == "Sort items."
func (*PascalDocExtractor) Language ¶ added in v0.0.10
func (e *PascalDocExtractor) Language() string
- Language returns "pascal". *
- Returns:
- string — "pascal". *
- Example:
- e.Language() // "pascal"
type PipeExternalFormatter ¶ added in v0.0.10
type PipeExternalFormatter struct {
// contains filtered or unexported fields
}
* PipeExternalFormatter invokes an external tool that reads source code from
- stdin and writes formatted code to stdout. This is the pipe-mode path and
- does not require safe mode to be disabled; the caller is responsible for any
- allowed-command checks before invoking Format. *
- If the executable is not found on $PATH, Format returns (content, nil)
- (identity) so that a missing tool degrades gracefully. *
- Fields (set via newPipeExtFormatter):
- langID — language this formatter targets, e.g. "go".
- exe — executable name, e.g. "gofmt".
- args — additional arguments appended before content is piped in.
- timeout — per-invocation deadline; 0 = 30 s default. *
- Example:
- f := newPipeExtFormatter("go", "gofmt")
- formatted, err := f.Format("package main\n", "main.go")
func (*PipeExternalFormatter) Check ¶ added in v0.0.10
func (f *PipeExternalFormatter) Check(content string, filePath string) (bool, []FormatIssue)
* Check reports whether content is already formatted. Returns true and no
- issues when content matches its formatted form; false and a single FormatIssue
- when it differs or the tool is unavailable. *
- Parameters:
- content (string) — source code to check.
- filePath (string) — file path hint. *
- Returns:
- bool — true when content is already properly formatted.
- []FormatIssue — empty on pass; single entry on fail. *
- Example:
- ok, issues := f.Check("package main\n", "main.go")
func (*PipeExternalFormatter) Format ¶ added in v0.0.10
func (f *PipeExternalFormatter) Format(content string, filePath string) (string, error)
* Format passes content through the external formatter and returns the result.
- filePath is used for context (e.g. to pick a parser) but is not read or
- written; content is passed via stdin. *
- Parameters:
- content (string) — source code to format.
- filePath (string) — file path hint passed to the formatter if needed. *
- Returns:
- string — formatted content, or original content when the tool is absent.
- error — non-nil only when the tool ran but returned an error. *
- Example:
- out, err := f.Format("package main\n", "main.go")
func (*PipeExternalFormatter) Language ¶ added in v0.0.10
func (f *PipeExternalFormatter) Language() string
- Language returns the language ID this formatter targets. *
- Returns:
- string — language ID, e.g. "go". *
- Example:
- fmt.Println(f.Language()) // "go"
func (*PipeExternalFormatter) Mode ¶ added in v0.0.10
func (f *PipeExternalFormatter) Mode() FormatterMode
- Mode returns PipeFormatter, indicating this formatter uses stdin/stdout. *
- Returns:
- FormatterMode — always PipeFormatter. *
- Example:
- fmt.Println(f.Mode() == PipeFormatter) // true
type Plan ¶ added in v0.0.12
- Plan represents a multi-step task decomposed into ordered, checkable steps. *
- Fields:
- Goal (string) — short description of the overall objective.
- Steps ([]PlanStep) — ordered list of steps.
- Created (time.Time) — when the plan was first generated.
- Updated (time.Time) — when the plan was last modified. *
- Example:
- p := &Plan{Goal: "Create a web component demo", Steps: []PlanStep{...}}
func LoadPlan ¶ added in v0.0.12
* LoadPlan reads agents/plan.md from the workspace and returns the parsed Plan.
- Returns an error when the file does not exist or cannot be parsed. *
- Parameters:
- ws (*Workspace) — workspace whose agents/ directory is read. *
- Returns:
- *Plan — parsed plan.
- error — if file is missing or unreadable. *
- Example:
- p, err := LoadPlan(agent.Workspace)
func PlanFromLLMResponse ¶ added in v0.0.12
* PlanFromLLMResponse parses a Plan from raw LLM output. It looks for a
- GFM checklist (lines beginning with "- [ ]" or "- [x]") and an optional
- goal heading ("# Plan: ..." or "## Goal: ..."). Falls back to a numbered
- list ("1. Step") when no checklist is found. goal is used as a fallback
- when the response contains no heading. *
- Parameters:
- text (string) — raw model response.
- goal (string) — fallback goal text when none is found in the response. *
- Returns:
- *Plan — parsed plan; may have zero steps if none could be extracted.
- error — always nil; included for future validation. *
- Example:
- p, _ := PlanFromLLMResponse(response, "build the web component demo")
func (*Plan) AllDone ¶ added in v0.0.12
- AllDone reports whether every step in the plan is marked complete. *
- Returns:
- bool — true when all steps are done. *
- Example:
- if p.AllDone() { fmt.Println("Task complete") }
func (*Plan) MarkDone ¶ added in v0.0.12
- MarkDone marks step at index i as complete and updates the Updated timestamp. *
- Parameters:
- i (int) — zero-based step index to mark done. *
- Example:
- p.MarkDone(0)
func (*Plan) NextStep ¶ added in v0.0.12
- NextStep returns the first uncompleted step, or nil if all are done. *
- Returns:
- *PlanStep — pointer to the first step where Done is false; nil when all done. *
- Example:
- if s := p.NextStep(); s != nil { fmt.Println("next:", s.Title) }
type PlanStep ¶ added in v0.0.12
- PlanStep represents a single actionable step within a Plan. *
- Fields:
- Index (int) — zero-based position in the plan.
- Done (bool) — true when the step has been executed successfully.
- Title (string) — one-line description of the action to perform. *
- Example:
- step := PlanStep{Index: 0, Done: false, Title: "Create demo/ directory"}
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) IngestEnriched ¶ added in v0.0.10
func (r *RagStore) IngestEnriched(source string, chunks []EnrichedChunk, embedder Embedder) error
* IngestEnriched embeds each EnrichedChunk using embedder and stores the
- resulting vectors alongside source-location and semantic metadata. The
- chunks table is lazily migrated with ALTER TABLE … ADD COLUMN on first use,
- so existing RAG stores without the new columns continue to work.
- Returns an error if the embedder's name does not match the store's model. *
- Parameters:
- source (string) — file path or identifier recorded with each chunk.
- chunks ([]EnrichedChunk)— enriched chunks 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.IngestEnriched("main.c", chunks, 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 use 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, toolCalls []ToolCallRecord) 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}.
Harvey calls tool_name: {...} ← action block per tool call (omitted when nil)
{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; empty when routing is disabled. toolCalls ([]ToolCallRecord) — structured tool invocations from the tool loop; nil when none.
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", nil)
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 RemoteObjectInfo ¶ added in v0.0.6
- RemoteObjectInfo describes a single remote object. *
- Fields:
- URI (string) — the full URI of the object
- Size (int64) — size in bytes; -1 when unknown
- ContentType (string) — MIME type; may be empty
- IsDir (bool) — true when the entry represents a prefix/directory *
- Example:
- info, err := r.Stat(ctx, "s3://mybucket/file.md")
- fmt.Println(info.Size) // e.g. 4096
type RemoteReader ¶ added in v0.0.6
type RemoteReader interface {
Stat(ctx context.Context, uri string) (RemoteObjectInfo, error)
Get(ctx context.Context, uri string, dst io.Writer) error
List(ctx context.Context, prefix string) ([]RemoteObjectInfo, error)
}
* RemoteReader provides read-only access to a remote storage backend.
- All Harvey remote access is read-only; no write operations are exposed.
- Implementations are returned by NewRemoteReader based on the URI scheme. *
- Methods:
- Stat(ctx, uri) — metadata for a single object
- Get(ctx, uri, dst) — download a single object into dst
- List(ctx, prefix) — enumerate objects under a prefix URI (trailing /) *
- Example:
- r, err := NewRemoteReader("s3://mybucket/docs/spec.md")
- if err != nil { ... }
- var buf bytes.Buffer
- if err := r.Get(ctx, "s3://mybucket/docs/spec.md", &buf); err != nil { ... }
func NewRemoteReader ¶ added in v0.0.6
func NewRemoteReader(uri string) (RemoteReader, error)
* NewRemoteReader returns a RemoteReader appropriate for the URI scheme.
- Supported schemes: s3, http, https, sftp, scp.
- Returns an error when the scheme is unsupported or required credentials
- are absent. *
- Parameters:
- uri (string) — any URI with a "scheme://" prefix. *
- Returns:
- RemoteReader — backend implementation for the scheme.
- error — when the scheme is unsupported or construction fails. *
- Example:
- r, err := NewRemoteReader("https://example.com/file.txt")
- // r is an *httpReader
type RollingSummaryConfig ¶ added in v0.0.6
* RollingSummaryConfig controls automatic working-memory compression.
- When history token count exceeds WarnAtPct of the model context window,
- Harvey warns then compresses all but the last KeepTurns turns into a
- short summary via a separate low-temperature LLM call. *
- Fields:
- Enabled (bool) — when false compression never fires; default true.
- WarnAtPct (float64) — compress when history exceeds this fraction of the
- model context window; default 0.80.
- KeepTurns (int) — number of recent turns to keep verbatim; default 6. *
- Example:
- cfg.Memory.RollingSummary = RollingSummaryConfig{Enabled: true, WarnAtPct: 0.80, KeepTurns: 6}
type RouteEndpoint ¶
type RouteEndpoint struct {
Name string
URL string
Model string
Kind RouteKind
Tools bool `json:",omitempty"` // opt-in tool calling via ToolExecutor
}
- 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.
- Tools (bool) — when true, dispatch uses ToolExecutor for tool calling. *
- 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 ScoredDoc ¶ added in v0.0.6
- ScoredDoc is a MemoryDoc paired with a retrieval score. *
- Fields:
- Doc (MemoryDoc) — the parsed memory document.
- Score (float64) — relevance score; higher is a better match. *
- Example:
- docs, _ := store.SearchFTS("git repository", 5)
- for _, d := range docs { fmt.Printf("[%.2f] %s\n", d.Score, d.Doc.Meta.Description) }
type ScrubResult ¶ added in v0.0.6
- ScrubResult holds the privacy-scrubbed content and any warning flags. *
- Fields:
- Content (string) — content with workspace paths normalised to
- <workspace>. No other automatic redaction is
- performed; sensitive patterns are only flagged.
- Flags ([]string) — human-readable descriptions of detected patterns,
- e.g. ["contains \"password\"", "contains \"token\""].
- Empty when nothing suspicious was found. *
- Example:
- result := Scrub(rawText, "/home/alice/myproject")
- if len(result.Flags) > 0 {
- fmt.Println("⚠ Sensitive content detected:")
- for _, f := range result.Flags { fmt.Println(" -", f) }
- }
func Scrub ¶ added in v0.0.6
func Scrub(content, workspacePath string) ScrubResult
* Scrub normalises workspace paths in content and checks for sensitive
- patterns. Path normalisation is silent and automatic; pattern detection
- produces flags that are surfaced to the human reviewer before a memory
- is saved. *
- Parameters:
- content (string) — raw text to scrub (YAML front matter or
- Fountain body, or the combined file content).
- workspacePath (string) — absolute workspace root path that will be
- replaced with the placeholder <workspace>.
- Pass "" to skip path normalisation. *
- Returns:
- ScrubResult — normalised content and any warning flags. *
- Example:
- r := Scrub("path: /home/alice/project/src", "/home/alice/project")
- // r.Content == "path: <workspace>/src"
- // r.Flags == []
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 SyntaxHighlighter ¶ added in v0.0.10
type SyntaxHighlighter interface {
// Highlight returns ANSI-coloured content for terminal display.
Highlight(content string, lang string) string
// GetStyle returns the colour configuration for a language.
GetStyle(lang string) *HighlightStyle
}
* SyntaxHighlighter adds ANSI colour codes to source code for terminal display.
- Implementations must strip existing ANSI sequences from the input before
- adding their own, to avoid corrupting the terminal. *
- Example:
- coloured := h.Highlight(src, "go")
type TemplateEntry ¶ added in v0.0.8
- TemplateEntry describes one profile template available to the user. *
- Parameters: (none — struct fields)
- Name (string) — human-readable display name, e.g. "Back End Developer".
- File (string) — filename without directory, e.g. "backend-developer.fountain".
- Source (string) — "builtin" for embedded templates, "workspace" for
- templates found in agents/templates/profiles/.
- Recommended (string) — content of the NOTE: field, or "" if absent.
- Displayed during template selection as a non-enforced suggestion. *
- Example:
- entries := ListTemplates("/home/user/myproject")
- for _, e := range entries {
- fmt.Printf("[%s] %s\n", e.Source, e.Name)
- }
func ListTemplates ¶ added in v0.0.8
func ListTemplates(wsRoot string) []TemplateEntry
* ListTemplates returns all available profile templates, merging built-in
- (embedded) templates with any .fountain files found in
- agents/templates/profiles/ within the workspace. Workspace-local entries
- appear after built-ins; a workspace entry with the same filename as a
- built-in shadows the built-in. *
- Parameters:
- wsRoot (string) — absolute path to the workspace root. Pass "" to skip
- workspace-local template discovery. *
- Returns:
- []TemplateEntry — ordered list: built-ins first (in directory order),
- then workspace-local additions. *
- Example:
- entries := ListTemplates(agent.Workspace.Root)
- for i, e := range entries {
- fmt.Printf(" [%d] %s\n", i+1, e.Name)
- }
type TerminalHighlighter ¶ added in v0.0.10
type TerminalHighlighter struct {
// contains filtered or unexported fields
}
* TerminalHighlighter applies ANSI syntax highlighting to source code for
- terminal display. A single instance handles all registered languages by
- dispatching to per-language tokenisers based on the lang parameter. *
- Implementations must strip existing ANSI sequences from the input before
- adding their own — this is satisfied here because code blocks extracted from
- LLM responses are not expected to contain prior ANSI codes. *
- Example:
- h := NewTerminalHighlighter()
- coloured := h.Highlight("int main(){return 0;}", "c")
func NewTerminalHighlighter ¶ added in v0.0.10
func NewTerminalHighlighter() *TerminalHighlighter
* NewTerminalHighlighter returns a TerminalHighlighter pre-loaded with
- highlighters for all supported languages. *
- Returns:
- *TerminalHighlighter — ready-to-use multi-language highlighter. *
- Example:
- h := NewTerminalHighlighter()
func (*TerminalHighlighter) GetStyle ¶ added in v0.0.10
func (h *TerminalHighlighter) GetStyle(lang string) *HighlightStyle
* GetStyle returns the HighlightStyle for the given language, or nil when the
- language is not registered. *
- Parameters:
- lang (string) — language ID. *
- Returns:
- *HighlightStyle — colour configuration, or nil. *
- Example:
- style := h.GetStyle("go")
func (*TerminalHighlighter) Highlight ¶ added in v0.0.10
func (h *TerminalHighlighter) Highlight(content string, lang string) string
* Highlight returns content with ANSI colour codes for the given language.
- Returns content unchanged when lang is not recognised. *
- Parameters:
- content (string) — source text to highlight.
- lang (string) — language ID (e.g. "go", "c", "python"). *
- Returns:
- string — highlighted text, or content unchanged when lang is unknown. *
- Example:
- coloured := h.Highlight("void foo(){}", "c")
type ToolCallRecord ¶ added in v0.0.6
type ToolCallRecord struct {
Name string // tool function name, e.g. "read_file"
Args string // raw JSON arguments string
}
ToolCallRecord holds the name and raw JSON arguments of a single tool invocation, for use in session recording.
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
DebugLog *DebugLog
ToolResultCompaction bool // when true, compact prior tool rounds before each new LLM turn
}
* 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 UnifiedMemory ¶ added in v0.0.6
type UnifiedMemory struct {
// contains filtered or unexported fields
}
* UnifiedMemory provides budget-aware retrieval across all memory silos:
- workspace_profile and project_fact (factual, always first), experiential
- memories (FTS5 + optional cosine similarity), RAG chunks, and KB
- observations. *
- Example:
- um := NewUnifiedMemory(store, &cfg.Memory, ws)
- results, err := um.Recall("git error", embedder, 512)
- agent.AddMessage("user", FormatContext(results))
func NewUnifiedMemory ¶ added in v0.0.6
func NewUnifiedMemory(store *MemoryStore, cfg *MemoryConfig, ws *Workspace) *UnifiedMemory
- NewUnifiedMemory creates a UnifiedMemory instance backed by the given store. *
- Parameters:
- store (*MemoryStore) — open memory store.
- cfg (*MemoryConfig) — memory configuration for RAG and KB access.
- ws (*Workspace) — workspace for resolving database paths; may be nil
- to disable RAG and KB retrieval. *
- Returns:
- *UnifiedMemory — ready to call Recall. *
- Example:
- um := NewUnifiedMemory(store, &cfg.Memory, ws)
- results, _ := um.Recall("context query", nil, 512)
func (*UnifiedMemory) Recall ¶ added in v0.0.6
func (u *UnifiedMemory) Recall(query string, embedder Embedder, budget int) ([]UnifiedResult, error)
* Recall retrieves memories from all silos in priority order, stopping when
- the token budget is exhausted. Factual types (workspace_profile,
- project_fact) always appear first with score 1.0. Experiential types are
- ranked by FTS5 text match and optionally by cosine similarity. RAG chunks
- and KB observations are appended last if budget permits. *
- Parameters:
- query (string) — search text; may be empty to return factual-only.
- embedder (Embedder) — cosine similarity embedder; nil disables the slow
- path for experiential memories and RAG.
- budget (int) — maximum estimated tokens to return; 0 means no limit. *
- Returns:
- []UnifiedResult — results in priority order, each within the budget.
- error — on store or retrieval failure. *
- Example:
- results, err := um.Recall("git error", embedder, 512)
- fmt.Println(FormatContext(results))
type UnifiedResult ¶ added in v0.0.6
- UnifiedResult is one retrieved item from any memory silo. *
- Fields:
- Source (string) — origin silo: "workspace_profile", "project_fact",
- "experiential", "rag", or "kb".
- ID (string) — identifier within the silo (memory ID, chunk ID, etc.).
- Content (string) — text to inject into the context window.
- Score (float64) — similarity or relevance score; 1.0 for factual types.
- Tokens (int) — estimated token count for Content (set by Recall). *
- Example:
- results, err := um.Recall("git error", embedder, 512)
- for _, r := range results {
- fmt.Printf("[%s %.2f] %s\n", r.Source, r.Score, r.Content)
- }
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
- code_chunkers.go
- code_formatters.go
- codeblock.go
- commands.go
- config.go
- debuglog.go
- doc_extractors.go
- encoderfile_embedder.go
- harvey.go
- help_dispatch.go
- helptext.go
- knowledge.go
- language_detector.go
- language_registry.go
- lear_messages.go
- llamafile.go
- llamafile_service.go
- loop.go
- memory.go
- memory_manifest.go
- memory_miner.go
- memory_onboarding.go
- memory_rolling.go
- memory_scrub.go
- memory_store.go
- memory_unified.go
- model_cache.go
- ollama.go
- pdf_extract.go
- permissions.go
- pipeline.go
- plan.go
- plan_cmd.go
- rag_support.go
- recorder.go
- remote.go
- remote_http.go
- remote_s3.go
- remote_sftp.go
- replay.go
- route_persist.go
- routing.go
- scholarly_identifiers.go
- scholarly_pdf.go
- sessions_files.go
- skill_compile.go
- skill_dispatch.go
- skill_set.go
- skill_wizard.go
- skills.go
- spinner.go
- syntax_highlighters.go
- templates.go
- terminal.go
- tool_executor.go
- tool_registry.go
- tools.go
- version.go
- workspace.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
assay
command
assay runs evaluation prompts from a corpus YAML against one or more Ollama models and writes a Markdown report plus JSON results for human review and machine processing.
|
assay runs evaluation prompts from a corpus YAML against one or more Ollama models and writes a Markdown report plus JSON results for human review and machine processing. |
|
harvey
command
|