sdk

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package sdk provides SDK agent integration for engram.

Package sdk provides SDK agent integration for engram.

Package sdk provides SDK agent integration for engram.

Index

Constants

View Source
const DefaultConcurrentLLMCalls = 4

DefaultConcurrentLLMCalls is the default number of concurrent LLM calls. Override with ENGRAM_LLM_CONCURRENCY env var.

View Source
const MaxPromptSize = 100 * 1024 // 100KB

MaxPromptSize is the maximum size of a prompt that can be passed to the LLM. This prevents resource exhaustion from extremely large prompts.

View Source
const MaxVectorSyncWorkers = 8

MaxVectorSyncWorkers is the maximum number of concurrent vector sync operations. This prevents unbounded goroutine spawning during high-volume observation ingestion.

Variables

View Source
var ObservationConcepts = []string{
	"how-it-works",
	"why-it-exists",
	"what-changed",
	"problem-solution",
	"gotcha",
	"pattern",
	"trade-off",
}

ObservationConcepts defines valid observation concepts.

View Source
var ObservationTypes = []string{"bugfix", "feature", "refactor", "change", "discovery", "decision"}

ObservationTypes defines valid observation types.

Functions

func BuildObservationPrompt

func BuildObservationPrompt(exec ToolExecution) string

BuildObservationPrompt builds a prompt for processing a tool observation.

func BuildSummaryPrompt

func BuildSummaryPrompt(req SummaryRequest) string

BuildSummaryPrompt builds a prompt requesting a session summary.

func GetFileContent

func GetFileContent(path, cwd string) (string, bool)

GetFileContent reads file content for verification purposes. Returns content and ok status. In Docker/remote mode, files don't exist → ("", false).

func GetFileMtimes

func GetFileMtimes(paths []string, cwd string) map[string]int64

GetFileMtimes returns current modification times for a list of file paths. This is used for staleness checking when injecting context. In Docker/remote mode, os.Stat on client paths returns error → empty map (no-op).

func ParseObservations

func ParseObservations(text string, correlationID string) []*models.ParsedObservation

ParseObservations parses observation XML blocks from SDK response text.

func ParseSummary

func ParseSummary(text string, sessionID int64) *models.ParsedSummary

ParseSummary parses a summary XML block from SDK response text.

Types

type BroadcastFunc

type BroadcastFunc func(event map[string]any)

BroadcastFunc is a callback for broadcasting events to SSE clients.

type CircuitBreaker

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

CircuitBreaker implements a simple circuit breaker pattern for CLI calls.

func NewCircuitBreaker

func NewCircuitBreaker(threshold int64, resetTimeout int64) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() bool

Allow checks if a request should be allowed through.

func (*CircuitBreaker) Metrics

func (cb *CircuitBreaker) Metrics() CircuitBreakerMetrics

Metrics returns the current metrics of the circuit breaker.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed call.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful call.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() string

State returns the current state as a string.

type CircuitBreakerMetrics

type CircuitBreakerMetrics struct {
	State             string `json:"state"`
	Failures          int64  `json:"failures"`
	Threshold         int64  `json:"threshold"`
	ResetTimeoutSecs  int64  `json:"reset_timeout_secs"`
	LastFailureUnix   int64  `json:"last_failure_unix,omitempty"`
	SecondsUntilReset int64  `json:"seconds_until_reset,omitempty"`
}

CircuitBreakerMetrics contains metrics about the circuit breaker state.

type Processor

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

Processor handles SDK agent processing of observations and summaries. Uses LLM API (OpenAI-compatible) as primary backend, with Claude CLI as optional fallback. Field order optimized for memory alignment (fieldalignment).

func NewProcessor

func NewProcessor(observationStore *gorm.ObservationStore, summaryStore *gorm.SummaryStore) (*Processor, error)

NewProcessor creates a new SDK processor. It requires at least one LLM backend: either an OpenAI-compatible API (ENGRAM_LLM_URL) or a local Claude CLI binary. If neither is available, it returns an error.

func (*Processor) CircuitBreakerMetrics

func (p *Processor) CircuitBreakerMetrics() CircuitBreakerMetrics

CircuitBreakerMetrics returns detailed metrics about the circuit breaker.

func (*Processor) IsAvailable

func (p *Processor) IsAvailable() bool

IsAvailable checks if an LLM backend (API or CLI) is available for processing.

func (*Processor) ProcessObservation

func (p *Processor) ProcessObservation(ctx context.Context, sdkSessionID, project string, toolName string, toolInput, toolResponse any, promptNumber int, cwd string) error

ProcessObservation processes a single tool observation and extracts insights.

func (*Processor) ProcessSummary

func (p *Processor) ProcessSummary(ctx context.Context, sessionDBID int64, sdkSessionID, project, userPrompt, lastUserMsg, lastAssistantMsg string) error

ProcessSummary processes a session summary request.

func (*Processor) SetBroadcastFunc

func (p *Processor) SetBroadcastFunc(fn BroadcastFunc)

SetBroadcastFunc sets the broadcast callback for SSE events.

func (*Processor) SetDedupConfig added in v0.4.0

func (p *Processor) SetDedupConfig(threshold float64, windowSize int)

SetDedupConfig sets deduplication parameters.

func (*Processor) SetSyncObservationFunc

func (p *Processor) SetSyncObservationFunc(fn SyncObservationFunc)

SetSyncObservationFunc sets the callback for syncing observations to vector DB.

func (*Processor) SetSyncSummaryFunc

func (p *Processor) SetSyncSummaryFunc(fn SyncSummaryFunc)

SetSyncSummaryFunc sets the callback for syncing summaries to vector DB.

func (*Processor) StartVectorSyncWorkers

func (p *Processor) StartVectorSyncWorkers()

StartVectorSyncWorkers starts the bounded worker pool for vector sync operations. Call this after setting the sync function via SetSyncObservationFunc.

func (*Processor) StopVectorSyncWorkers

func (p *Processor) StopVectorSyncWorkers()

StopVectorSyncWorkers gracefully stops the worker pool.

func (*Processor) VerifyObservation

func (p *Processor) VerifyObservation(ctx context.Context, obs *models.Observation, cwd string) bool

VerifyObservation checks if an observation is still valid given the current file contents. Returns true if the observation is still accurate, false if it should be deleted.

type RequestDeduplicator

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

RequestDeduplicator tracks recent requests to prevent duplicates.

func NewRequestDeduplicator

func NewRequestDeduplicator(ttlSecs int64, maxSize int) *RequestDeduplicator

NewRequestDeduplicator creates a new deduplicator.

func (*RequestDeduplicator) IsDuplicate

func (d *RequestDeduplicator) IsDuplicate(hash string) bool

IsDuplicate checks if a request hash was seen recently.

func (*RequestDeduplicator) Record

func (d *RequestDeduplicator) Record(hash string)

Record marks a request hash as seen.

type SummaryRequest

type SummaryRequest struct {
	SDKSessionID         string
	Project              string
	UserPrompt           string
	LastUserMessage      string
	LastAssistantMessage string
	SessionDBID          int64
}

SummaryRequest contains data for building a summary prompt.

type SyncObservationFunc

type SyncObservationFunc func(obs *models.Observation)

SyncObservationFunc is a callback for syncing observations to vector DB.

type SyncSummaryFunc

type SyncSummaryFunc func(summary *models.SessionSummary)

SyncSummaryFunc is a callback for syncing summaries to vector DB.

type ToolExecution

type ToolExecution struct {
	ToolName       string
	ToolInput      string
	ToolOutput     string
	CWD            string
	ID             int64
	CreatedAtEpoch int64
}

ToolExecution represents a tool execution for observation.

Jump to

Keyboard shortcuts

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