Documentation
¶
Index ¶
- Constants
- func CleanArgs(args map[string]any, reserved ...string) map[string]any
- func CompareLoose(a any, b any) int
- func ExportSplitCategoryPathInstruction(query string) (string, string)
- func GetField(source any, field string) any
- func HashString(s string) string
- func NewFromConfig(ctx context.Context, cfg Config, deps Dependencies) (ai.Agent[map[string]any], error)
- func RefineScriptSteps(steps []ai.ScriptStep) []ai.ScriptStep
- func RunLoop(ctx context.Context, agent ai.Agent[map[string]any], r io.Reader, w io.Writer, ...) error
- func SetupInfrastructure(ctx context.Context, cfg Config, deps Dependencies) (ai.Embeddings, *database.Database, string, vector.Config, error)
- func TranslateASTToCEL(ast any) (string, bool)
- func ValidateScriptGrammar(script []ScriptInstruction) error
- func ValidateScriptSteps(steps []ai.ScriptStep) error
- type AdHocAgent
- func (a *AdHocAgent) Ask(ctx context.Context, query string, cfg *ai.ConfigMap) (string, error)
- func (a *AdHocAgent) Close(ctx context.Context) error
- func (a *AdHocAgent) Execute(ctx context.Context, toolName string, args map[string]any) (string, error)
- func (a *AdHocAgent) Open(ctx context.Context) error
- func (a *AdHocAgent) Search(ctx context.Context, query string, limit int) ([]ai.Hit[map[string]any], error)
- type AddArgs
- type AskRequest
- type AskResponse
- type BaselineReActEngine
- type BloomFilter
- type BulkAddArgs
- type BulkDeleteArgs
- type BulkDeleteCategoriesArgs
- type BulkDeleteItemsArgs
- type BulkItem
- type BulkOperationError
- type BulkOperationMetrics
- type BulkOperationResult
- type BulkUpdateArgs
- type BulkUpsertCategoriesArgs
- type BulkUpsertItemsArgs
- type BulkVectorizeCategoriesArgs
- type BulkVectorizeItemsArgs
- type CachedScript
- type CategoryListResult
- type CompiledScript
- type Config
- type ConversationRole
- type ConversationThread
- type CopilotAgent
- func (a *CopilotAgent) Add(ctx context.Context, args AddArgs) (string, error)
- func (a *CopilotAgent) Ask(ctx context.Context, query string, cfg *ai.ConfigMap) (string, error)
- func (a *CopilotAgent) BeginTransaction(ctx context.Context, args TransactionArgs) (*TransactionHandle, error)
- func (a *CopilotAgent) BulkAdd(ctx context.Context, args BulkAddArgs) (*BulkOperationResult, error)
- func (a *CopilotAgent) BulkDelete(ctx context.Context, args BulkDeleteArgs) (*BulkOperationResult, error)
- func (a *CopilotAgent) BulkDeleteCategories(ctx context.Context, args BulkDeleteCategoriesArgs) (*SpaceBulkOperationResult, error)
- func (a *CopilotAgent) BulkDeleteItems(ctx context.Context, args BulkDeleteItemsArgs) (*SpaceBulkOperationResult, error)
- func (a *CopilotAgent) BulkUpdate(ctx context.Context, args BulkUpdateArgs) (*BulkOperationResult, error)
- func (a *CopilotAgent) BulkUpsertCategories(ctx context.Context, args BulkUpsertCategoriesArgs) (*SpaceBulkOperationResult, error)
- func (a *CopilotAgent) BulkUpsertItems(ctx context.Context, args BulkUpsertItemsArgs) (*SpaceBulkOperationResult, error)
- func (a *CopilotAgent) BulkVectorizeCategories(ctx context.Context, args BulkVectorizeCategoriesArgs) (*SpaceBulkOperationResult, error)
- func (a *CopilotAgent) BulkVectorizeItems(ctx context.Context, args BulkVectorizeItemsArgs) (*SpaceBulkOperationResult, error)
- func (a *CopilotAgent) ClassifyContinuityTaskContext(ctx context.Context, query string, mru *TaskContextClassification, ...) (*TaskContextClassification, bool, error)
- func (a *CopilotAgent) ClassifyFocusedTaskContext(ctx context.Context, query, entity, domain, artifact string, gen ai.Generator) (*TaskContextClassification, error)
- func (a *CopilotAgent) ClassifyTaskContext(ctx context.Context, query string, gen ai.Generator) (*TaskContextClassification, error)
- func (a *CopilotAgent) Clone() ai.Agent[map[string]any]
- func (a *CopilotAgent) Close(ctx context.Context) error
- func (a *CopilotAgent) CommitTransaction(ctx context.Context, args TransactionCommitArgs) error
- func (a *CopilotAgent) CreateSpace(ctx context.Context, args CreateSpaceArgs) (string, error)
- func (a *CopilotAgent) Delete(ctx context.Context, args DeleteArgs) (string, error)
- func (a *CopilotAgent) DeleteCategory(ctx context.Context, args DeleteCategoryArgs) (string, error)
- func (a *CopilotAgent) DeleteItem(ctx context.Context, args DeleteItemArgs) (string, error)
- func (a *CopilotAgent) DeleteSpace(ctx context.Context, args DeleteSpaceArgs) (string, error)
- func (a *CopilotAgent) Execute(ctx context.Context, toolName string, args map[string]any) (string, error)
- func (a *CopilotAgent) ExecuteScript(ctx context.Context, args ExecuteScriptArgs) (string, error)
- func (a *CopilotAgent) ExportSearchKnowledgeBase(ctx context.Context, db *database.Database, kbName string, query string, ...) (string, error)
- func (a *CopilotAgent) GetMRUCategory(category string) (string, bool)
- func (a *CopilotAgent) GetSampleArtifacts(ctx context.Context) ([]string, []string, error)
- func (a *CopilotAgent) InitializePhysicalMemory(ctx context.Context) error
- func (a *CopilotAgent) Join(ctx context.Context, args JoinArgs) (string, error)
- func (a *CopilotAgent) ListCategories(ctx context.Context, args ListCategoriesArgs) (*CategoryListResult, error)
- func (a *CopilotAgent) ListItems(ctx context.Context, args ListItemsArgs) (*ItemListResult, error)
- func (a *CopilotAgent) ListTools(ctx context.Context) ([]ai.ToolDefinition, error)
- func (a *CopilotAgent) MarkMRUCategory(category string, context string)
- func (a *CopilotAgent) Open(ctx context.Context) error
- func (a *CopilotAgent) ReadSpaceConfig(ctx context.Context, args ReadSpaceConfigArgs) (*memory.KnowledgeBaseConfig, error)
- func (a *CopilotAgent) RollbackTransaction(ctx context.Context, args TransactionRollbackArgs) error
- func (a *CopilotAgent) Search(ctx context.Context, query string, limit int) ([]ai.Hit[map[string]any], error)
- func (a *CopilotAgent) SearchItemsByPath(ctx context.Context, args SearchItemsByPathArgs) ([]memory.Item[map[string]any], error)
- func (a *CopilotAgent) Select(ctx context.Context, args SelectArgs) (string, error)
- func (a *CopilotAgent) SetGenerator(gen ai.Generator)
- func (a *CopilotAgent) SetService(s *Service)
- func (a *CopilotAgent) SetVerbose(v bool)
- func (a *CopilotAgent) StartSleepCycle(ctx context.Context, hourlyInterval int, idleTimeoutMinutes int, ...)
- func (a *CopilotAgent) Update(ctx context.Context, args UpdateArgs) (string, error)
- func (a *CopilotAgent) UpdateSpaceConfig(ctx context.Context, args UpdateSpaceConfigArgs) (string, error)
- func (a *CopilotAgent) UpsertCategory(ctx context.Context, args UpsertCategoryArgs) (string, error)
- func (a *CopilotAgent) UpsertItem(ctx context.Context, args UpsertItemArgs) (string, error)
- func (a *CopilotAgent) VectorizeSpace(ctx context.Context, args VectorizeSpaceArgs) (string, error)
- type CreateSpaceArgs
- type CuratorConfig
- type DataItem
- type Database
- type DeferredCleanupCursor
- type DeleteArgs
- type DeleteCategoryArgs
- type DeleteItemArgs
- type DeleteSpaceArgs
- type Dependencies
- type ETLConfig
- type EmbedderConfig
- type EnrichSpaceArgs
- type ErrorResponse
- type EventResultStreamer
- type ExecuteScriptArgs
- type FilterCursor
- type FilteringStreamer
- type Flusher
- type GeneratorConfig
- type Interaction
- type ItemListResult
- type JSONStreamer
- type JoinArgs
- type JoinPlan
- type JoinProcessor
- type JoinRightCursor
- type KnowledgeChunk
- type LayerInfo
- type LimitCursor
- type ListCategoriesArgs
- type ListCursor
- type ListItemsArgs
- type MRUItem
- type MintToSpaceArgs
- type MockItem
- type MockStore
- func (m *MockStore) Add(ctx context.Context, key any, value any) (bool, error)
- func (m *MockStore) FindInDescendingOrder(ctx context.Context, key any) (bool, error)
- func (m *MockStore) FindOne(ctx context.Context, key any, first bool) (bool, error)
- func (m *MockStore) First(ctx context.Context) (bool, error)
- func (m *MockStore) GetCurrentKey() any
- func (m *MockStore) GetCurrentValue(ctx context.Context) (any, error)
- func (m *MockStore) GetCurrentValueNoLock(ctx context.Context) (any, error)
- func (m *MockStore) GetStoreInfo() sop.StoreInfo
- func (m *MockStore) ItemExists(ctx context.Context, key any) (bool, error)
- func (m *MockStore) Last(ctx context.Context) (bool, error)
- func (m *MockStore) Next(ctx context.Context) (bool, error)
- func (m *MockStore) Previous(ctx context.Context) (bool, error)
- func (m *MockStore) RLockCurrentItem(ctx context.Context) error
- func (m *MockStore) Remove(ctx context.Context, key any) (bool, error)
- func (m *MockStore) RemoveCurrentItem(ctx context.Context) error
- func (m *MockStore) Update(ctx context.Context, key any, value any) (bool, error)
- type MultiCursor
- type NativeReActEngine
- type OrderedFieldsProvider
- type OrderedKey
- type OrderedMap
- type PendingUserConfirmation
- type PipelineAgent
- type PipelineStep
- type PolicyAgent
- func (p *PolicyAgent) Ask(ctx context.Context, query string, cfg *ai.ConfigMap) (string, error)
- func (p *PolicyAgent) Close(ctx context.Context) error
- func (p *PolicyAgent) ID() string
- func (p *PolicyAgent) Open(ctx context.Context) error
- func (p *PolicyAgent) Search(ctx context.Context, query string, limit int) ([]ai.Hit[map[string]any], error)
- type PolicyConfig
- type ProjectCursor
- type ProjectionField
- type PromptBudgetProfile
- type PromptBudgetReport
- type PromptComponent
- type PromptComponentBudgetStat
- type PromptElement
- type ProviderDetails
- type ReadSpaceConfigArgs
- type RecipeItem
- type ReducingStreamer
- type RefinementProposal
- type Registry
- func (r *Registry) GeneratePrompt() string
- func (r *Registry) Get(name string) (ToolDefinition, bool)
- func (r *Registry) List() []ToolDefinition
- func (r *Registry) Register(name, description, argsSchema string, handler ToolHandler)
- func (r *Registry) RegisterHidden(name, description, argsSchema string, handler ToolHandler)
- func (r *Registry) RegisterWithUI(name, shortDesc, description, argsSchema string, handler ToolHandler)
- type ReproMockTransaction
- type ResultEmitter
- type RightOuterJoinStoreCursor
- type RunnerSession
- type ScriptContext
- type ScriptCursor
- type ScriptEngine
- func (e *ScriptEngine) Add(ctx context.Context, args map[string]any) (any, error)
- func (e *ScriptEngine) BeginTx(ctx context.Context, args map[string]any) (sop.Transaction, error)
- func (e *ScriptEngine) CallFunction(ctx context.Context, args map[string]any) (any, error)
- func (e *ScriptEngine) CallScript(ctx context.Context, args map[string]any) (any, error)
- func (e *ScriptEngine) CommitTx(ctx context.Context, args map[string]any) (err error)
- func (e *ScriptEngine) Compile(script []ScriptInstruction) (CompiledScript, error)
- func (e *ScriptEngine) Delete(ctx context.Context, input any, args map[string]any) ([]any, error)
- func (e *ScriptEngine) Dispatch(ctx context.Context, instr ScriptInstruction) errordeprecated
- func (e *ScriptEngine) Execute(ctx context.Context, script []ScriptInstruction) error
- func (e *ScriptEngine) ExecuteKBManagement(ctx context.Context, op string, args map[string]any, input any) (any, error)
- func (e *ScriptEngine) Filter(ctx context.Context, input any, args map[string]any) (any, error)
- func (e *ScriptEngine) Find(ctx context.Context, args map[string]any) (bool, error)
- func (e *ScriptEngine) First(ctx context.Context, args map[string]any) (bool, error)
- func (e *ScriptEngine) GetCurrentKey(ctx context.Context, args map[string]any) (any, error)
- func (e *ScriptEngine) GetCurrentValue(ctx context.Context, args map[string]any) (any, error)
- func (e *ScriptEngine) If(ctx context.Context, args map[string]any) error
- func (e *ScriptEngine) Inspect(ctx context.Context, args map[string]any) (any, error)
- func (e *ScriptEngine) Join(ctx context.Context, input any, args map[string]any) (any, error)
- func (e *ScriptEngine) JoinRight(ctx context.Context, input any, args map[string]any) (any, error)
- func (e *ScriptEngine) Last(ctx context.Context, args map[string]any) (bool, error)
- func (e *ScriptEngine) Limit(ctx context.Context, input any, args map[string]any) (any, error)
- func (e *ScriptEngine) ListAppend(ctx context.Context, input any, args map[string]any) (any, error)
- func (e *ScriptEngine) Loop(ctx context.Context, args map[string]any) error
- func (e *ScriptEngine) MapMerge(ctx context.Context, args map[string]any) (map[string]any, error)
- func (e *ScriptEngine) Next(ctx context.Context, args map[string]any) (bool, error)
- func (e *ScriptEngine) OpenDB(args map[string]any) (Database, error)
- func (e *ScriptEngine) OpenStore(ctx context.Context, args map[string]any) (jsondb.StoreAccessor, error)
- func (e *ScriptEngine) Previous(ctx context.Context, args map[string]any) (bool, error)
- func (e *ScriptEngine) Project(ctx context.Context, input any, args map[string]any) (any, error)
- func (e *ScriptEngine) RollbackTx(ctx context.Context, args map[string]any) error
- func (e *ScriptEngine) Scan(ctx context.Context, args map[string]any, input any) (any, error)
- func (e *ScriptEngine) Sort(ctx context.Context, input any, args map[string]any) (any, error)
- func (e *ScriptEngine) Update(ctx context.Context, input any, args map[string]any) ([]any, error)
- type ScriptInstruction
- type ScriptRunContext
- type SearchItemsByPathArgs
- type SelectArgs
- type Service
- func (s *Service) Ask(ctx context.Context, query string, cfg *ai.ConfigMap) (string, error)
- func (s *Service) Clone() ai.Agent[map[string]any]
- func (s *Service) Close(ctx context.Context) error
- func (s *Service) Domain() ai.Domain[map[string]any]
- func (s *Service) GetLastToolInstructions() string
- func (s *Service) GetSessionMode() SessionMode
- func (s *Service) InitializeShortTermMemory(ctx context.Context) error
- func (s *Service) InitializeUserSession(ctx context.Context, userID string) error
- func (s *Service) LastInteractionToolCallsSnapshot() []ai.ScriptStep
- func (s *Service) ListTools(ctx context.Context) ([]ai.ToolDefinition, error)
- func (s *Service) Open(ctx context.Context) error
- func (s *Service) PlayScript(ctx context.Context, name string, category string, args map[string]any, ...) error
- func (s *Service) RecordStep(ctx context.Context, step ai.ScriptStep)
- func (s *Service) RefactorLastSteps(count int, mode string, name string) error
- func (s *Service) RunPipeline(ctx context.Context, input string, cfg *ai.ConfigMap) (string, error)
- func (s *Service) RunScript(ctx context.Context, name string, category string, args map[string]any) (string, error)
- func (s *Service) RunnerSession() *RunnerSession
- func (s *Service) Search(ctx context.Context, query string, limit int) ([]ai.Hit[map[string]any], error)
- func (s *Service) SeedSemanticBaseKnowledge(jsonFilePath string)
- func (s *Service) SetFeature(feature string, enabled bool)
- type ServiceAskOptions
- type ServiceToolExecutor
- type SessionMode
- type ShortTermMemory
- func (stm *ShortTermMemory) AddThread(thread *ConversationThread)
- func (stm *ShortTermMemory) GetCarryoverState() *ai.CarryoverState
- func (stm *ShortTermMemory) GetCurrentThread() *ConversationThread
- func (stm *ShortTermMemory) GetMRUSnapshot() []MRUItem
- func (stm *ShortTermMemory) GetRecipeSnapshot() []RecipeItem
- func (stm *ShortTermMemory) GetRoutingState() *TaskContextClassification
- func (stm *ShortTermMemory) PromoteThread(id sop.UUID)
- func (stm *ShortTermMemory) ResetProjectionForTopicSwitch()
- func (stm *ShortTermMemory) SetCarryoverState(state *ai.CarryoverState)
- func (stm *ShortTermMemory) SetMRUSnapshot(items []MRUItem)
- func (stm *ShortTermMemory) SetRecipeSnapshot(items []RecipeItem)
- func (stm *ShortTermMemory) SetRoutingState(taskCtx *TaskContextClassification)
- type SpaceBulkOperationError
- type SpaceBulkOperationMetrics
- type SpaceBulkOperationResult
- type SpecProvider
- type StepExecutionResult
- type StepStreamer
- type StoreCursor
- type SystemPromptBuilder
- func (b *SystemPromptBuilder) ToJSON() string
- func (b *SystemPromptBuilder) ToJSONWithBudget(profile PromptBudgetProfile) string
- func (b *SystemPromptBuilder) ToJSONWithBudgetReport(profile PromptBudgetProfile) (string, PromptBudgetReport)
- func (b *SystemPromptBuilder) ToXML() string
- func (b *SystemPromptBuilder) With(component PromptComponent, content string) *SystemPromptBuilder
- type TaskContextClassification
- type ToolDefinition
- type ToolExecutionContext
- type ToolHandler
- type ToolProvider
- type TopicAssessment
- type TransactionArgs
- type TransactionCommitArgs
- type TransactionHandle
- type TransactionMode
- type TransactionRollbackArgs
- type UpdateArgs
- type UpdateSpaceConfigArgs
- type UpsertCategoryArgs
- type UpsertItemArgs
- type VectorizeSpaceArgs
Constants ¶
const ( StrategyUnset = 0 StrategyIndexSeek = 1 StrategyInMemory = 2 StrategyFullScan = 3 )
Join Strategy Constants
const ( StoresDomain = "Stores" SpacesDomain = "Spaces" RoutingGateFocused = "focused" RoutingGateContinuity = "continuity" RoutingGateDiscovery = "discovery" )
const ( // SystemDBName is the name of the system database used for internal agent storage (scripts, history, etc). SystemDBName = "system" // DefaultHost is the default host for local AI providers. DefaultHost = "http://localhost:11434" // Environment Variables EnvOllamaHost = "OLLAMA_HOST" // Providers ProviderGemini = "gemini" ProviderChatGPT = "chatgpt" ProviderAnthropic = "anthropic" ProviderOllama = "ollama" ProviderLocal = "local" // Default Models DefaultModelOpenAI = ai.DefaultModelOpenAI DefaultModelGemini = ai.DefaultModelGemini DefaultModelAnthropic = "claude-3-5-sonnet-20241022" DefaultModelOllama = ai.DefaultModelOllama // Session Keys SessionPayloadKey = "session_payload" RunnerSessionKey = "runner_session" )
const ( MaxMRUSize = 20 MaxExchangesInHistory = 20 )
const ( MRUSourceUnknown = "" MRUSourcePersona = "persona" MRUSourceSystemTools = "system_tools" MRUSourceAskOutcome = "ask_outcome" MRUSourceAskProgress = "ask_progress" MRUSourcePlaybook = "playbook" )
const ( MRUScopeSession = "session" MRUScopeAsk = "ask" )
const ( ExecuteScriptInstruction = "Execute a full ordered JSON AST under script for multi-step store operations. Each step should be an object such as {op, args?, input_var?, result_var?}. " + "Focus on orchestration semantics: begin a transaction, read or mutate stores, then commit or rollback. begin_tx defines the durability boundary for the workflow, so use it when related mutations must persist or roll back together. " + "For larger mutation runs, batch deliberately under explicit commits, with a practical default of about 50 to 250 CRUD operations per transaction unless business atomicity requires a different boundary. Chain multi-step reads with result_var/input_var. " + "Use list_stores to research stores before multi-store joins or whenever schema is uncertain. Prefer scoped calls such as stores:[\"users\",\"users_orders\",\"orders\"] so research stays compact on large databases. list_stores returns stores:[{name,schema,key_fields,value_fields,description,relations,empty}]. " + "When you fill args.condition or any predicate object, write the condition expression the engine should execute and assign the concrete comparison value directly. " + "Predicate format: for single-store operations (select, scan with filter), use bare field names like \"first_name\". After joins, use store-qualified paths like \"orders.total_amount\". " + "Read store.schema for field names and types (e.g., {\"key\": \"string\", \"first_name\": \"string\", \"age\": \"number\"}). Match types exactly: string values in quotes, numbers as numbers. " + "Relations map joins using schema field names. source_fields and target_fields reference fields from the schema. " + "Example: Find orders for users with first_name 'John' where total_amount > 500. Call list_stores([\"users\",\"users_orders\",\"orders\"]). Read schemas: users has first_name field, orders has total_amount field. Build: {\"script\":[{\"op\":\"begin_tx\",\"args\":{\"mode\":\"read\"},\"result_var\":\"tx\"},{\"op\":\"open_store\",\"args\":{\"transaction\":\"tx\",\"name\":\"users\"},\"result_var\":\"users_store\"},{\"op\":\"select\",\"args\":{\"store\":\"users_store\",\"condition\":{\"first_name\":{\"$eq\":\"John\"}}},\"result_var\":\"matched_users\"},{\"op\":\"join\",\"input_var\":\"matched_users\",\"args\":{\"target\":\"users_orders_store\",\"relation\":\"users_orders\"},\"result_var\":\"user_order_links\"},{\"op\":\"join\",\"input_var\":\"user_order_links\",\"args\":{\"target\":\"orders_store\",\"relation\":\"orders\"},\"result_var\":\"joined_orders\"},{\"op\":\"filter\",\"input_var\":\"joined_orders\",\"args\":{\"condition\":{\"orders.total_amount\":{\"$gt\":500}}},\"result_var\":\"filtered_orders\"},{\"op\":\"return\",\"input_var\":\"filtered_orders\"}]}. Do not emit booleans like {\"first_name\":true}. " + "Prefer relation + target for join repair instead of inventing a fresh on mapping; if on is still needed, rewrite only the invalid join slice by translating the confirmed relation into the exact concrete field mapping the join op expects, and never use store names where field paths are required. join and join_right emit a combined flat record by default, so reuse dotted store-qualified field paths unless a later project step intentionally reshapes the output. If the AST shape is ambiguous, call gettoolinfo('execute_script') and continue with concrete predicate objects, concrete join mappings, and boolean placeholders removed." ListStoresInstruction = "Research store structure before writing multi-store reads or repairs. Pass stores:[...] to scope the response to likely targets, and infer likely store names from the user's ask instead of leaving stores empty when obvious candidates are available. " + "The tool can narrow close singular/plural matches internally, but you should still pass the most likely store names you can infer. The result is a JSON object with stores:[{name,schema,key_fields,value_fields,description,relations,empty}]. " + "Each store.schema maps field names to types (e.g., {\"key\": \"string\", \"first_name\": \"string\", \"age\": \"number\"}). " + "When building predicates: for single-store operations, use bare field names like \"first_name\". After joins, use store-qualified names like \"orders.total_amount\". " + "Relations map store-to-store joins using schema field names. source_fields and target_fields reference fields from the schema. " + "Example: Find orders for users with first_name 'John' where total_amount > 500. Call list_stores with [\"users\", \"users_orders\", \"orders\"]. Read schemas: users has first_name, orders has total_amount. Build predicates: {\"first_name\": {\"$eq\": \"John\"}} for single-store filter, {\"orders.total_amount\": {\"$gt\": 500}} after joins." )
const ( SelectInstruction = "" /* 673-byte string literal not displayed */ JoinInstruction = "" /* 362-byte string literal not displayed */ ExplainJoinInstruction = "" /* 403-byte string literal not displayed */ AddInstruction = "" /* 322-byte string literal not displayed */ UpdateInstruction = "" /* 330-byte string literal not displayed */ DeleteInstruction = "" /* 309-byte string literal not displayed */ ManageTransactionInstruction = "" /* 749-byte string literal not displayed */ MintToSpaceInstruction = "" /* 447-byte string literal not displayed */ DeleteSpaceInstruction = "" /* 327-byte string literal not displayed */ EnrichSpaceInstruction = "" /* 306-byte string literal not displayed */ UpdateSpaceConfigInstruction = "" /* 338-byte string literal not displayed */ ReadSpaceConfigInstruction = "" /* 254-byte string literal not displayed */ VectorizeSpaceInstruction = "" /* 265-byte string literal not displayed */ VectorizeSpaceCategoriesInstruction = "" /* 264-byte string literal not displayed */ VectorizeSpaceItemsInstruction = "" /* 262-byte string literal not displayed */ )
const ( StrategyLookup = "lookup" StrategyMerge = "merge" StrategyHashRight = "hash_right" // Scan Left, Probe Right (Buffered) StrategyHashLeft = "hash_left" // Scan Right, Probe Left (Buffered) )
Constants for Join Strategies
const ( CtxKeyAtomicScriptContext = "_atomic_script_context" CtxKeyAtomicLastResult = "_atomic_last_result" )
const ( RecipeKindExplicit = "explicit" RecipeKindImplicit = "implicit" )
const ( RecipeScopeMicro = "micro" RecipeScopeMacro = "macro" RecipeScopeSpace = "space" RecipeScopeGlobal = "global" )
const ( // KnowledgeStore is the name of the B-tree store used to persist learned rules, vocabulary, and corrections. // This store resides in the System Database configured for the agent. KnowledgeStore = "memory" // MRUKnowledgeStore is the name of the store that tracks "active" or "relevant" knowledge categories/items. // This acts as a Working Memory Index, telling the agent what to pre-load from Long Term Memory. // Keys are "{Category}/{Name}" or just "{Category}", Values are Timestamps/Scores. MRUKnowledgeStore = "mru_knowledge" // KnowledgeRefreshDuration is the interval at which the agent refreshes its local view of the persistent knowledge. KnowledgeRefreshDuration = 5 * time.Minute )
const CtxKeyCurrentScriptCategory contextKey = "current_script_category"
const CtxKeyJSONStreamer contextKey = "json_streamer"
const CtxKeySuppressInternalStepStart contextKey = "suppress_internal_step_start"
const CtxKeyUseNDJSON contextKey = "use_ndjson"
const MaxConsecutiveRowsWithoutMatch = 100000
MaxConsecutiveRowsWithoutMatch is the safety limit for consecutive rows scanned without finding a match in filter or join operations. This prevents runaway scans from malformed queries while still allowing unlimited streaming of matching data.
const MaxConversationThreads = 20
const (
SYSTEM_TOOLS = "System_Tools"
)
Variables ¶
This section is empty.
Functions ¶
func CleanArgs ¶
CleanArgs extracts non-reserved arguments from a map. It skips keys starting with "_" and any key in the reserved list.
func CompareLoose ¶
CompareLoose performs a loose comparison of two values, handling mixed numeric types. It leverages btree.Compare for strict same-type comparisons but promotes mixed numeric types to float64 for correct relational ordering (e.g., 9 < 10.0).
func ExportSplitCategoryPathInstruction ¶
ExportSplitCategoryPathInstruction exports the private function for testing
func GetField ¶
GetField extracts a field from a given source object (Map, OrderedMap, or JSON String). It supports case-insensitive lookups, dot-notation stripping, Key/Value recursion, and suffix matching.
func HashString ¶
HashString generates a deterministic hash for the given string.
func NewFromConfig ¶
func NewFromConfig(ctx context.Context, cfg Config, deps Dependencies) (ai.Agent[map[string]any], error)
NewFromConfig creates and initializes a new Agent Service based on the provided configuration. It handles infrastructure setup (Embedder, VectorDB).
func RefineScriptSteps ¶
func RefineScriptSteps(steps []ai.ScriptStep) []ai.ScriptStep
RefineScriptSteps applies automatic refinements to script steps to improve readability and explicitness. This ensures that scripts stored in the system follow conventions (like explicit variable names) even if the creator (LLM or user) relied on implicit behaviors.
func RunLoop ¶
func RunLoop(ctx context.Context, agent ai.Agent[map[string]any], r io.Reader, w io.Writer, prompt string, assistantName string, cfg *ai.ConfigMap) error
RunLoop starts an interactive Read-Eval-Print Loop (REPL) for the agent. It reads user input from r, processes it using the agent's Ask method, and writes the response to w. The loop continues until the user enters "exit" or the input stream ends.
func SetupInfrastructure ¶
func SetupInfrastructure(ctx context.Context, cfg Config, deps Dependencies) (ai.Embeddings, *database.Database, string, vector.Config, error)
SetupInfrastructure initializes the Embedder and Vector Index based on the configuration.
func TranslateASTToCEL ¶
func ValidateScriptGrammar ¶
func ValidateScriptGrammar(script []ScriptInstruction) error
ValidateScriptGrammar exposes the execution-path grammar validation pass for reuse.
func ValidateScriptSteps ¶
func ValidateScriptSteps(steps []ai.ScriptStep) error
ValidateScriptSteps converts []ai.ScriptStep to the internal execution form, applies the same sanitize-before-grammar path used by execute_script, and returns grammar validation errors.
Types ¶
type AdHocAgent ¶
type AdHocAgent struct {
Name string
Handler func(ctx context.Context, args map[string]interface{}) (string, error)
}
AdHocAgent implements ai.Agent for simple function wrappers
func (*AdHocAgent) Execute ¶
func (a *AdHocAgent) Execute(ctx context.Context, toolName string, args map[string]any) (string, error)
Implement ToolProvider interface
type AddArgs ¶
type AddArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Store string `json:"store" binding:"required" example:"users"`
Key any `json:"key" binding:"required" example:"user_123"`
Value map[string]any `json:"value" binding:"required"`
}
AddArgs represents arguments for adding a single item
type AskRequest ¶
type AskRequest struct {
// Query is the user's input question or command
Query string
// Session holds the current session state including transactions, variables, and database context
Session *ai.SessionPayload
// Executor is the tool executor for running tool calls during ReAct loops
Executor ai.ToolExecutor
// Generator optionally overrides the default LLM provider
Generator ai.Generator
// ProviderOverride optionally provides runtime provider configuration (provider, model, API key, base URL)
ProviderOverride *ProviderDetails
// Database optionally overrides the session's current database
Database *database.Database
// Writer is the output destination for streaming responses
Writer io.Writer
// EventStreamer receives structured events during reasoning (tool calls, progress, etc.)
EventStreamer func(eventType string, data any)
// ProgressSink receives progress messages during execution
ProgressSink func(message string)
// ScriptRecorder captures executed script steps for playback or audit
ScriptRecorder ai.ScriptRecorder
// DefaultFormat sets the default output format for tools (csv, json, etc.)
DefaultFormat string
// Options carries additional configuration from ConfigMap
Options *ai.ConfigMap
}
AskRequest contains all dependencies for an Ask operation, making the data flow explicit. This replaces the previous pattern of hiding dependencies in context.Context.
type AskResponse ¶
type AskResponse struct {
// FinalText is the assistant's answer to the user
FinalText string
// UpdatedSession contains any session state changes (updated transactions, variables, etc.)
UpdatedSession *ai.SessionPayload
// CarryoverState holds provider-specific continuation state for next Ask
CarryoverState *ai.CarryoverState
// ToolCalls lists all tools executed during the Ask for audit/logging
ToolCalls []ai.ToolCall
// OutcomeFacts contains compact grounded facts safe to carry into MRU continuity
OutcomeFacts []string
// OutcomeRecipes contains learned patterns distilled from this Ask
OutcomeRecipes []ai.LearnedRecipe
}
AskResponse contains the result and any state changes from an Ask operation.
type BaselineReActEngine ¶
type BaselineReActEngine struct {
Agent *CopilotAgent
}
func (*BaselineReActEngine) Run ¶
func (b *BaselineReActEngine) Run(ctx context.Context, req ai.ReasoningRequest) (ai.ReasoningResponse, error)
type BloomFilter ¶
type BloomFilter struct {
// contains filtered or unexported fields
}
BloomFilter is a probabilistic data structure for set membership.
func NewBloomFilter ¶
func NewBloomFilter(n uint, p float64) *BloomFilter
NewBloomFilter creates a new Bloom Filter optimized for n elements with false positive rate p.
func (*BloomFilter) Add ¶
func (bf *BloomFilter) Add(key string)
Add adds a string key to the Bloom Filter.
func (*BloomFilter) Test ¶
func (bf *BloomFilter) Test(key string) bool
Test checks if a key might vary well be in the set. Returns true if the key MAY be present. Returns false if the key is DEFINITELY NOT present.
type BulkAddArgs ¶
type BulkAddArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Store string `json:"store" binding:"required" example:"users"`
Items []BulkItem `json:"items" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"` // Use existing transaction
TransactionMode TransactionMode `json:"transaction_mode,omitempty" default:"auto_batch" enums:"auto_batch,explicit,single"`
BatchSize int `json:"batch_size,omitempty" default:"100" example:"250"`
}
BulkAddArgs represents arguments for bulk insert operations @Description Bulk insert multiple items with automatic transaction batching
type BulkDeleteArgs ¶
type BulkDeleteArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Store string `json:"store" binding:"required" example:"users"`
Keys []any `json:"keys" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
TransactionMode TransactionMode `json:"transaction_mode,omitempty" default:"auto_batch" enums:"auto_batch,explicit,single"`
BatchSize int `json:"batch_size,omitempty" default:"100" example:"250"`
}
BulkDeleteArgs represents arguments for bulk delete operations
type BulkDeleteCategoriesArgs ¶
type BulkDeleteCategoriesArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
CategoryIDs []sop.UUID `json:"category_ids" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
TransactionMode TransactionMode `json:"transaction_mode,omitempty" default:"single" enums:"single,explicit"`
}
BulkDeleteCategoriesArgs represents arguments for deleting multiple categories
type BulkDeleteItemsArgs ¶
type BulkDeleteItemsArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
CategoryID sop.UUID `json:"category_id" binding:"required"`
ItemIDs []sop.UUID `json:"item_ids" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
TransactionMode TransactionMode `json:"transaction_mode,omitempty" default:"single" enums:"single,explicit"`
}
BulkDeleteItemsArgs represents arguments for deleting multiple items
type BulkItem ¶
type BulkItem struct {
Key any `json:"key" binding:"required" example:"user_123"`
Value map[string]any `json:"value" binding:"required"`
}
BulkItem represents a single item in a bulk operation
type BulkOperationError ¶
type BulkOperationError struct {
Index int `json:"index"`
Key any `json:"key,omitempty"`
Message string `json:"message"`
}
BulkOperationError represents an error that occurred during a bulk operation
type BulkOperationMetrics ¶
type BulkOperationMetrics struct {
TotalItems int `json:"total_items"`
BatchesExecuted int `json:"batches_executed"`
AvgBatchTime time.Duration `json:"avg_batch_time"`
ItemsPerSecond float64 `json:"items_per_second"`
}
BulkOperationMetrics contains performance metrics for bulk operations
type BulkOperationResult ¶
type BulkOperationResult struct {
Success bool `json:"success"`
Processed int `json:"processed"`
Failed int `json:"failed"`
Duration time.Duration `json:"duration"`
Errors []BulkOperationError `json:"errors,omitempty"`
Metrics BulkOperationMetrics `json:"metrics"`
TransactionsCreated int `json:"transactions_created"` // For auto_batch mode
TransactionsCommitted int `json:"transactions_committed"` // For auto_batch mode
TransactionsRolledBack int `json:"transactions_rolled_back"` // On error
}
BulkOperationResult represents the result of a bulk operation
type BulkUpdateArgs ¶
type BulkUpdateArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Store string `json:"store" binding:"required" example:"users"`
Items []BulkItem `json:"items" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
TransactionMode TransactionMode `json:"transaction_mode,omitempty" default:"auto_batch" enums:"auto_batch,explicit,single"`
BatchSize int `json:"batch_size,omitempty" default:"100" example:"250"`
}
BulkUpdateArgs represents arguments for bulk update operations
type BulkUpsertCategoriesArgs ¶
type BulkUpsertCategoriesArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Parameters []memory.UpsertCategoryParam `json:"parameters" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
TransactionMode TransactionMode `json:"transaction_mode,omitempty" default:"single" enums:"single,explicit"`
}
BulkUpsertCategoriesArgs represents arguments for upserting multiple categories
type BulkUpsertItemsArgs ¶
type BulkUpsertItemsArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Parameters []memory.UpsertItemParam[map[string]any] `json:"parameters" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
TransactionMode TransactionMode `json:"transaction_mode,omitempty" default:"single" enums:"single,explicit"`
}
BulkUpsertItemsArgs represents arguments for upserting multiple items
type BulkVectorizeCategoriesArgs ¶
type BulkVectorizeCategoriesArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
CategoryIDs []sop.UUID `json:"category_ids" binding:"required"`
BatchSize int `json:"batch_size,omitempty" default:"100" example:"250"`
}
BulkVectorizeCategoriesArgs represents arguments for vectorizing multiple categories
type BulkVectorizeItemsArgs ¶
type BulkVectorizeItemsArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
CategoryID *sop.UUID `json:"category_id,omitempty"`
ItemIDs []sop.UUID `json:"item_ids,omitempty"`
BatchSize int `json:"batch_size,omitempty" default:"100" example:"250"`
}
BulkVectorizeItemsArgs represents arguments for vectorizing multiple items
type CachedScript ¶
type CachedScript struct {
Script CompiledScript
Hash string
}
type CategoryListResult ¶
type CategoryListResult struct {
Categories []memory.Category `json:"categories"`
Total int `json:"total"`
}
CategoryListResult represents the result of listing categories
type CompiledScript ¶
type CompiledScript func(ctx context.Context, e *ScriptEngine) error
CompiledScript is a function that executes the compiled script against an engine.
func CompileScript ¶
func CompileScript(script []ScriptInstruction) (CompiledScript, error)
type Config ¶
type Config struct {
ID string `json:"id"`
Type string `json:"type,omitempty"` // "standard" (default), "copilot", "policy", etc.
Name string `json:"name"`
Description string `json:"description"`
UserPrompt string `json:"user_prompt,omitempty"` // Optional: Custom prompt for the interactive loop (e.g. "Patient> ")
AssistantName string `json:"assistant_name,omitempty"` // Optional: Custom name for the assistant (e.g. "AI Doctor")
Synonyms map[string]string `json:"synonyms"`
SystemPrompt string `json:"system_prompt"`
Policies []PolicyConfig `json:"policies"`
ETL ETLConfig `json:"etl,omitempty"` // Configuration for the ETL/Curator pipeline
Embedder EmbedderConfig `json:"embedder,omitempty"` // Configuration for the embedder
Generator GeneratorConfig `json:"generator,omitempty"` // Configuration for the LLM generator
Data []DataItem `json:"data"` // For seeding (MVP)
StoragePath string `json:"storage_path,omitempty"` // Optional: Override default storage path. Will be converted to absolute path.
DBType string `json:"db_type,omitempty"` // Optional: "standalone" (default) or "clustered"
ContentSize string `json:"content_size,omitempty"` // Optional: "small", "medium", "big". Defaults to "medium".
SkipDeduplication bool `json:"skip_deduplication,omitempty"` // Optional: Skip deduplication phase
EnableIngestionBuffer bool `json:"enable_ingestion_buffer,omitempty"` // Optional: Enable Stage 0 buffering for faster ingestion
Verbose bool `json:"verbose,omitempty"` // Optional: Enable verbose output (e.g. tool instructions)
// Cognitive Memory Consolidation (STM to LTM)
SleepCycleIntervalHours int `json:"sleep_cycle_interval_hours,omitempty"` // e.g. 1 (run every X hours on the clock). 0 disables hourly.
IdleSleepTimeoutMinutes int `json:"idle_sleep_timeout_minutes,omitempty"` // e.g. 5 (run cycle after X minutes of avatar inactivity).
StubMode bool `json:"stub_mode,omitempty"` // Optional: If true, tools will return success without executing (for debugging LLM output)
Agents []Config `json:"agents,omitempty"` // Optional: Define agents locally to be referenced by ID
Pipeline []PipelineStep `json:"pipeline,omitempty"` // Optional: Define a chain of agents
Params map[string]any `json:"params,omitempty"` // Type-specific configuration parameters
}
Config defines the structure of the JSON configuration file for an agent.
func LoadConfigFromFile ¶
LoadConfigFromFile reads and parses a JSON configuration file.
type ConversationRole ¶
type ConversationRole string
ConversationRole enum
const ( RoleUser ConversationRole = "user" RoleAssistant ConversationRole = "assistant" RoleSystem ConversationRole = "system" )
type ConversationThread ¶
type ConversationThread struct {
ID sop.UUID `json:"id"`
RootPrompt string `json:"root_prompt"` // The seed sentence that started this thread
// Transcribed Context (Managed by LLM)
Label string `json:"label"` // Short Topic Name (e.g. "Defining Client")
Category string `json:"category"` // e.g. "Business Logic", "Clarification"
ContextNotes string `json:"context_notes"` // Important notes/context for the LLM
// The linear exchange of Q&A within this topic
Exchanges []Interaction `json:"exchanges"`
// Termination
Conclusion string `json:"conclusion"` // Summary or Agreement
Status string `json:"status"` // "active", "concluded"
}
ConversationThread represents a single conversational thread. It starts with a root prompt and spins up a Q&A exchange, eventually leading to a conclusion.
type CopilotAgent ¶
type CopilotAgent struct {
Config Config
// Encapsulated memory and context boundaries
Memory *memory.MemoryUnit
// StoreOpener allows mocking the store creation (e.g. for testing)
StoreOpener func(ctx context.Context, dbOpts sop.DatabaseOptions, storeName string, tx sop.Transaction) (jsondb.StoreAccessor, error)
// contains filtered or unexported fields
}
CopilotAgent is a specialized agent for database administration tasks. It implements the ai.Agent interface.
func NewCopilotAgent ¶
func NewCopilotAgent(cfg Config, databases map[string]sop.DatabaseOptions, systemDB *database.Database) *CopilotAgent
NewCopilotAgent creates a new instance of CopilotAgent.
func (*CopilotAgent) Ask ¶
Ask is the primary entry point for processing a user's conversational query to the AI Copilot.
The functional flow follows a multi-layered ReAct architecture:
Generator Resolution: Dynamically selects the appropriate LLM provider (e.g., Gemini, OpenAI, Claude) based on the active session context or falling back to the system default configuration.
Direct Invocation Handling: Checks if the query is a direct tool invocation (e.g., "/help" or "/clear_memory"). If so, it bypasses the LLM reasoning loop to immediately execute the deterministic command.
Intent Classification (Router): Evaluates if the query should be routed to a specific sub-agent (Avatar/Persona). If the intent indicates a specialized Avatar (e.g., a "Legal Auditor" persona), it delegates execution entirely to that sub-agent.
Context Classification: For generic queries (intent == "OMNI"), it performs a lightweight three-gate classification to identify the semantic domain (e.g., "Spaces" or "Stores"), likely artifacts, and CRUD layer. This stage is classification-only: it updates routing state, but does not assemble prompt slices or mutate System_Tools context.
Episode Metadata Tracking (MRU Cache): Analyzes the user's prior chat exchange inside the short-term episodic memory. If the user remains engaged in the same topic and database context, it pulls the Most-Recently-Used (MRU) semantic boundaries so the LLM retains coherent situational context across turns.
System Prompt Construction: Assembles the multi-part context prompt (using SystemPromptBuilder) linking the Core Persona, Active Playbooks/KBs, stable System Tools context, targeted focused execution/tool guidance derived from the current classification, semantic memory boundaries, and conversation history.
Reasoning Engine Delegation: Packages the assembled context and delegates execution to the ReAct engine. The engine loops autonomously over the LLM generation and local tool executions (API-level tool calling) until it produces a final answer.
Epilogue & Cleanup: Records the completed dialogue and active track-state into the short-term memory transcript, clears the volatile MRU buffer, and returns the final text response to the client.
func (*CopilotAgent) BeginTransaction ¶
func (a *CopilotAgent) BeginTransaction(ctx context.Context, args TransactionArgs) (*TransactionHandle, error)
BeginTransaction starts a new transaction and returns a handle
func (*CopilotAgent) BulkAdd ¶
func (a *CopilotAgent) BulkAdd(ctx context.Context, args BulkAddArgs) (*BulkOperationResult, error)
BulkAdd inserts multiple items with transaction control (first-class API)
func (*CopilotAgent) BulkDelete ¶
func (a *CopilotAgent) BulkDelete(ctx context.Context, args BulkDeleteArgs) (*BulkOperationResult, error)
BulkDelete deletes multiple items with transaction control (first-class API)
func (*CopilotAgent) BulkDeleteCategories ¶
func (a *CopilotAgent) BulkDeleteCategories(ctx context.Context, args BulkDeleteCategoriesArgs) (*SpaceBulkOperationResult, error)
BulkDeleteCategories deletes multiple categories (first-class bulk API)
func (*CopilotAgent) BulkDeleteItems ¶
func (a *CopilotAgent) BulkDeleteItems(ctx context.Context, args BulkDeleteItemsArgs) (*SpaceBulkOperationResult, error)
BulkDeleteItems deletes multiple items (first-class bulk API)
func (*CopilotAgent) BulkUpdate ¶
func (a *CopilotAgent) BulkUpdate(ctx context.Context, args BulkUpdateArgs) (*BulkOperationResult, error)
BulkUpdate updates multiple items with transaction control (first-class API)
func (*CopilotAgent) BulkUpsertCategories ¶
func (a *CopilotAgent) BulkUpsertCategories(ctx context.Context, args BulkUpsertCategoriesArgs) (*SpaceBulkOperationResult, error)
BulkUpsertCategories upserts multiple categories (first-class bulk API)
func (*CopilotAgent) BulkUpsertItems ¶
func (a *CopilotAgent) BulkUpsertItems(ctx context.Context, args BulkUpsertItemsArgs) (*SpaceBulkOperationResult, error)
BulkUpsertItems upserts multiple items (first-class bulk API)
func (*CopilotAgent) BulkVectorizeCategories ¶
func (a *CopilotAgent) BulkVectorizeCategories(ctx context.Context, args BulkVectorizeCategoriesArgs) (*SpaceBulkOperationResult, error)
BulkVectorizeCategories vectorizes multiple categories (first-class bulk API)
func (*CopilotAgent) BulkVectorizeItems ¶
func (a *CopilotAgent) BulkVectorizeItems(ctx context.Context, args BulkVectorizeItemsArgs) (*SpaceBulkOperationResult, error)
BulkVectorizeItems vectorizes multiple items (first-class bulk API)
func (*CopilotAgent) ClassifyContinuityTaskContext ¶
func (a *CopilotAgent) ClassifyContinuityTaskContext(ctx context.Context, query string, mru *TaskContextClassification, anchor *TaskContextClassification, gen ai.Generator) (*TaskContextClassification, bool, error)
ClassifyContinuityTaskContext is Gate 2: The "Continuity/Switch" Classifier. Used to check if the user is maintaining MRU context or switching topics.
func (*CopilotAgent) ClassifyFocusedTaskContext ¶
func (a *CopilotAgent) ClassifyFocusedTaskContext(ctx context.Context, query, entity, domain, artifact string, gen ai.Generator) (*TaskContextClassification, error)
ClassifyFocusedTaskContext is Gate 1: The "Focused" Classifier. Used when the user explicitly provides Hard Constraints via prefix (e.g. omni:stores:users:). Skips building the Context Outline entirely.
func (*CopilotAgent) ClassifyTaskContext ¶
func (a *CopilotAgent) ClassifyTaskContext(ctx context.Context, query string, gen ai.Generator) (*TaskContextClassification, error)
func (*CopilotAgent) Clone ¶
func (a *CopilotAgent) Clone() ai.Agent[map[string]any]
Clone creates a new isolated instance of the agent sharing read-only components.
func (*CopilotAgent) Close ¶
func (a *CopilotAgent) Close(ctx context.Context) error
Close cleans up the agent's resources.
func (*CopilotAgent) CommitTransaction ¶
func (a *CopilotAgent) CommitTransaction(ctx context.Context, args TransactionCommitArgs) error
CommitTransaction commits an active transaction
func (*CopilotAgent) CreateSpace ¶
func (a *CopilotAgent) CreateSpace(ctx context.Context, args CreateSpaceArgs) (string, error)
CreateSpace creates or opens a Space/KnowledgeBase (first-class API)
func (*CopilotAgent) Delete ¶
func (a *CopilotAgent) Delete(ctx context.Context, args DeleteArgs) (string, error)
Delete deletes a single item from a store (first-class API)
func (*CopilotAgent) DeleteCategory ¶
func (a *CopilotAgent) DeleteCategory(ctx context.Context, args DeleteCategoryArgs) (string, error)
DeleteCategory deletes a single category (first-class API)
func (*CopilotAgent) DeleteItem ¶
func (a *CopilotAgent) DeleteItem(ctx context.Context, args DeleteItemArgs) (string, error)
DeleteItem deletes a single item (first-class API)
func (*CopilotAgent) DeleteSpace ¶
func (a *CopilotAgent) DeleteSpace(ctx context.Context, args DeleteSpaceArgs) (string, error)
DeleteSpace deletes a Space/KnowledgeBase (first-class API)
func (*CopilotAgent) Execute ¶
func (a *CopilotAgent) Execute(ctx context.Context, toolName string, args map[string]any) (string, error)
Execute executes the requested tool against the session payload.
func (*CopilotAgent) ExecuteScript ¶
func (a *CopilotAgent) ExecuteScript(ctx context.Context, args ExecuteScriptArgs) (string, error)
ExecuteScript executes a multi-step script (first-class API)
func (*CopilotAgent) ExportSearchKnowledgeBase ¶
func (a *CopilotAgent) ExportSearchKnowledgeBase(ctx context.Context, db *database.Database, kbName string, query string, catPath string, category string, limit int) (string, error)
ExportSearchKnowledgeBase exports searchKnowledgeBase for testing
func (*CopilotAgent) GetMRUCategory ¶
func (a *CopilotAgent) GetMRUCategory(category string) (string, bool)
GetMRUCategory retrieves a category from the global working memory MRU
func (*CopilotAgent) GetSampleArtifacts ¶
func (*CopilotAgent) InitializePhysicalMemory ¶
func (a *CopilotAgent) InitializePhysicalMemory(ctx context.Context) error
InitializePhysicalMemory creates strictly isolated B-Tree (STM) and Vector (LTM) structures for this Agent ID
func (*CopilotAgent) ListCategories ¶
func (a *CopilotAgent) ListCategories(ctx context.Context, args ListCategoriesArgs) (*CategoryListResult, error)
ListCategories lists categories with pagination (first-class API)
func (*CopilotAgent) ListItems ¶
func (a *CopilotAgent) ListItems(ctx context.Context, args ListItemsArgs) (*ItemListResult, error)
ListItems lists items with pagination (first-class API)
func (*CopilotAgent) ListTools ¶
func (a *CopilotAgent) ListTools(ctx context.Context) ([]ai.ToolDefinition, error)
ListTools returns the list of available tools.
func (*CopilotAgent) MarkMRUCategory ¶
func (a *CopilotAgent) MarkMRUCategory(category string, context string)
MarkMRUCategory adds or updates a category in the global working memory MRU
func (*CopilotAgent) Open ¶
func (a *CopilotAgent) Open(ctx context.Context) error
Open initializes the agent's resources.
func (*CopilotAgent) ReadSpaceConfig ¶
func (a *CopilotAgent) ReadSpaceConfig(ctx context.Context, args ReadSpaceConfigArgs) (*memory.KnowledgeBaseConfig, error)
ReadSpaceConfig reads the configuration of a Space (first-class API)
func (*CopilotAgent) RollbackTransaction ¶
func (a *CopilotAgent) RollbackTransaction(ctx context.Context, args TransactionRollbackArgs) error
RollbackTransaction rolls back an active transaction
func (*CopilotAgent) Search ¶
func (a *CopilotAgent) Search(ctx context.Context, query string, limit int) ([]ai.Hit[map[string]any], error)
Search performs a search using the agent's capabilities.
func (*CopilotAgent) SearchItemsByPath ¶
func (a *CopilotAgent) SearchItemsByPath(ctx context.Context, args SearchItemsByPathArgs) ([]memory.Item[map[string]any], error)
SearchItemsByPath searches items by path (first-class API)
func (*CopilotAgent) Select ¶
func (a *CopilotAgent) Select(ctx context.Context, args SelectArgs) (string, error)
Select retrieves data from a store (first-class API)
func (*CopilotAgent) SetGenerator ¶
func (a *CopilotAgent) SetGenerator(gen ai.Generator)
SetGenerator sets the generator for the agent.
func (*CopilotAgent) SetService ¶
func (a *CopilotAgent) SetService(s *Service)
SetService sets the reference to the main service (for cache invalidation).
func (*CopilotAgent) SetVerbose ¶
func (a *CopilotAgent) SetVerbose(v bool)
SetVerbose enables or disables verbose output.
func (*CopilotAgent) StartSleepCycle ¶
func (a *CopilotAgent) StartSleepCycle(ctx context.Context, hourlyInterval int, idleTimeoutMinutes int, nowFn func() time.Time)
StartSleepCycle launches background consolidators over the isolated Avatar STM migrating Short-Term episodic memories into Semantic Long-Term memory.
func (*CopilotAgent) Update ¶
func (a *CopilotAgent) Update(ctx context.Context, args UpdateArgs) (string, error)
Update updates a single item in a store (first-class API)
func (*CopilotAgent) UpdateSpaceConfig ¶
func (a *CopilotAgent) UpdateSpaceConfig(ctx context.Context, args UpdateSpaceConfigArgs) (string, error)
UpdateSpaceConfig updates the configuration of a Space (first-class API)
func (*CopilotAgent) UpsertCategory ¶
func (a *CopilotAgent) UpsertCategory(ctx context.Context, args UpsertCategoryArgs) (string, error)
UpsertCategory upserts a single category (first-class API)
func (*CopilotAgent) UpsertItem ¶
func (a *CopilotAgent) UpsertItem(ctx context.Context, args UpsertItemArgs) (string, error)
UpsertItem upserts a single item (first-class API)
func (*CopilotAgent) VectorizeSpace ¶
func (a *CopilotAgent) VectorizeSpace(ctx context.Context, args VectorizeSpaceArgs) (string, error)
VectorizeSpace vectorizes an entire Space (first-class API)
type CreateSpaceArgs ¶
type CreateSpaceArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
}
CreateSpaceArgs represents arguments for creating/opening a Space
type CuratorConfig ¶
type CuratorConfig struct {
Type string `json:"type"` // "ollama", "agent"
ID string `json:"id,omitempty"` // ID of the agent to use (if type="agent")
Options map[string]any `json:"options,omitempty"` // e.g. {"model": "llama3"}
Prompt string `json:"prompt,omitempty"` // The instruction for curation
}
type Database ¶
type Database interface {
BeginTransaction(ctx context.Context, mode sop.TransactionMode, maxTime ...time.Duration) (sop.Transaction, error)
Config() sop.DatabaseOptions
}
Database interface for script execution
type DeferredCleanupCursor ¶
type DeferredCleanupCursor struct {
// contains filtered or unexported fields
}
DeferredCleanupCursor wraps a ScriptCursor and executes deferred functions on Close.
func (*DeferredCleanupCursor) Close ¶
func (d *DeferredCleanupCursor) Close() error
func (*DeferredCleanupCursor) GetIndexSpecs ¶
func (d *DeferredCleanupCursor) GetIndexSpecs() map[string]*jsondb.IndexSpecification
func (*DeferredCleanupCursor) GetOrderedFields ¶
func (d *DeferredCleanupCursor) GetOrderedFields() []string
type DeleteArgs ¶
type DeleteArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Store string `json:"store" binding:"required" example:"users"`
Key any `json:"key" binding:"required" example:"user_123"`
}
DeleteArgs represents arguments for deleting a single item
type DeleteCategoryArgs ¶
type DeleteCategoryArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
CategoryID sop.UUID `json:"category_id" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
}
DeleteCategoryArgs represents arguments for deleting a single category
type DeleteItemArgs ¶
type DeleteItemArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
CategoryID sop.UUID `json:"category_id" binding:"required"`
ItemID sop.UUID `json:"item_id" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
}
DeleteItemArgs represents arguments for deleting a single item
type DeleteSpaceArgs ¶
type DeleteSpaceArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
}
DeleteSpaceArgs represents arguments for deleting a Space
type Dependencies ¶
type Dependencies struct {
AgentRegistry map[string]ai.Agent[map[string]any]
SystemDB *database.Database
Databases map[string]sop.DatabaseOptions
}
Dependencies holds external dependencies required for agent creation.
type ETLConfig ¶
type ETLConfig struct {
Curator CuratorConfig `json:"curator,omitempty"`
}
type EmbedderConfig ¶
type EmbedderConfig struct {
Type string `json:"type"` // "simple" (default), "agent", "ollama", "gemini", or "local"
AgentID string `json:"agent_id"` // For "agent" type: ID of the agent to use
Instruction string `json:"instruction"` // For "agent" type: Instruction for the agent
Options map[string]any `json:"options,omitempty"` // For "local" type: model_path, provider, gpu_layers
}
type EnrichSpaceArgs ¶
type EnrichSpaceArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
}
EnrichSpaceArgs represents arguments for enriching a Space
type ErrorResponse ¶
type ErrorResponse struct {
Error string `json:"error" example:"store is required"`
Code string `json:"code,omitempty" example:"INVALID_REQUEST"`
Details any `json:"details,omitempty"`
}
ErrorResponse represents an API error
type EventResultStreamer ¶
type EventResultStreamer struct {
// contains filtered or unexported fields
}
func NewEventResultStreamer ¶
func NewEventResultStreamer(sendEvent func(string, any)) *EventResultStreamer
func (*EventResultStreamer) BeginArray ¶
func (s *EventResultStreamer) BeginArray()
func (*EventResultStreamer) Close ¶
func (s *EventResultStreamer) Close()
func (*EventResultStreamer) EndArray ¶
func (s *EventResultStreamer) EndArray()
func (*EventResultStreamer) SetMetadata ¶
func (s *EventResultStreamer) SetMetadata(meta map[string]any)
func (*EventResultStreamer) WriteItem ¶
func (s *EventResultStreamer) WriteItem(item any)
type ExecuteScriptArgs ¶
type ExecuteScriptArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Script []ScriptInstruction `json:"script" binding:"required"`
}
ExecuteScriptArgs represents arguments for executing a script
type FilterCursor ¶
type FilterCursor struct {
// contains filtered or unexported fields
}
FilterCursor filters a stream.
func (*FilterCursor) Close ¶
func (fc *FilterCursor) Close() error
func (*FilterCursor) GetOrderedFields ¶
func (fc *FilterCursor) GetOrderedFields() []string
type FilteringStreamer ¶
type FilteringStreamer struct {
// contains filtered or unexported fields
}
func (*FilteringStreamer) BeginArray ¶
func (fs *FilteringStreamer) BeginArray()
func (*FilteringStreamer) EndArray ¶
func (fs *FilteringStreamer) EndArray()
func (*FilteringStreamer) SetMetadata ¶
func (fs *FilteringStreamer) SetMetadata(meta map[string]any)
func (*FilteringStreamer) WriteItem ¶
func (fs *FilteringStreamer) WriteItem(item any)
type GeneratorConfig ¶
type Interaction ¶
type Interaction struct {
Role ConversationRole `json:"role"`
Content string `json:"content"`
Timestamp int64 `json:"timestamp"`
Entity string `json:"entity,omitempty"` // OMNI or Avatar name
ActiveKB string `json:"active_kb,omitempty"` // The target KB evaluated in this sequence
}
Interaction represents a single message in the conversation.
type ItemListResult ¶
type ItemListResult struct {
Items []memory.Item[map[string]any] `json:"items"`
Total int `json:"total"`
}
ItemListResult represents the result of listing items
type JSONStreamer ¶
type JSONStreamer struct {
// contains filtered or unexported fields
}
JSONStreamer handles streaming JSON array elements. TODO: add a buffered batching wrapper in the future to reduce transport overhead for large result sets.
func NewJSONStreamer ¶
func NewJSONStreamer(w io.Writer) *JSONStreamer
func NewNDJSONStreamer ¶
func NewNDJSONStreamer(w io.Writer) *JSONStreamer
func (*JSONStreamer) SetFlush ¶
func (s *JSONStreamer) SetFlush(flush bool)
func (*JSONStreamer) SetSuppressStepStart ¶
func (s *JSONStreamer) SetSuppressStepStart(suppress bool)
func (*JSONStreamer) StartStreamingStep ¶
func (s *JSONStreamer) StartStreamingStep(stepType, command, prompt string, stepIndex int) *StepStreamer
StartStreamingStep starts a new step in the JSON stream and returns a StepStreamer. Note: The header is written lazily when the first item is written.
func (*JSONStreamer) Write ¶
func (s *JSONStreamer) Write(step StepExecutionResult)
type JoinArgs ¶
type JoinArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
LeftStore string `json:"left_store" binding:"required" example:"users"`
RightStore string `json:"right_store" binding:"required" example:"orders"`
LeftJoinFields []string `json:"left_join_fields" binding:"required" example:"user_id"`
RightJoinFields []string `json:"right_join_fields" binding:"required" example:"user_id"`
JoinType string `json:"join_type,omitempty" default:"inner" enums:"inner,left,right"`
Fields []string `json:"fields,omitempty"`
Limit int `json:"limit,omitempty" default:"10"`
Direction string `json:"direction,omitempty" enums:"asc,desc"`
Action string `json:"action,omitempty" enums:"delete_left,update_left"`
UpdateValues map[string]any `json:"update_values,omitempty"`
}
JoinArgs represents arguments for joining two stores
type JoinPlan ¶
type JoinProcessor ¶
type JoinProcessor struct {
// contains filtered or unexported fields
}
JoinProcessor handles the execution of a join operation between two stores.
func (*JoinProcessor) Execute ¶
func (jp *JoinProcessor) Execute() (string, error)
Execute runs the join operation.
type JoinRightCursor ¶
type JoinRightCursor struct {
// contains filtered or unexported fields
}
JoinRightCursor performs a streaming join with probing and scanning support. It replaces both JoinCursor (Lookup) and NestedLoopJoinCursor (Scan).
func (*JoinRightCursor) Close ¶
func (jc *JoinRightCursor) Close() error
func (*JoinRightCursor) GetIndexSpecs ¶
func (jc *JoinRightCursor) GetIndexSpecs() map[string]*jsondb.IndexSpecification
func (*JoinRightCursor) NextOptimized ¶
NextOptimized is the "Execution Phase".
type KnowledgeChunk ¶
type LimitCursor ¶
type LimitCursor struct {
// contains filtered or unexported fields
}
LimitCursor limits a stream.
func (*LimitCursor) Close ¶
func (lc *LimitCursor) Close() error
func (*LimitCursor) GetIndexSpecs ¶
func (lc *LimitCursor) GetIndexSpecs() map[string]*jsondb.IndexSpecification
func (*LimitCursor) GetOrderedFields ¶
func (lc *LimitCursor) GetOrderedFields() []string
type ListCategoriesArgs ¶
type ListCategoriesArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Limit int `json:"limit,omitempty" default:"100" example:"50"`
Offset int `json:"offset,omitempty" default:"0" example:"0"`
ParentPath string `json:"parent_path,omitempty" example:"Root/SubCategory"`
TransactionID string `json:"transaction_id,omitempty"`
}
ListCategoriesArgs represents arguments for listing categories
type ListCursor ¶
type ListCursor struct {
// contains filtered or unexported fields
}
ListCursor wraps a slice of maps.
func (*ListCursor) Close ¶
func (lc *ListCursor) Close() error
type ListItemsArgs ¶
type ListItemsArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
CategoryID sop.UUID `json:"category_id,omitempty"`
Limit int `json:"limit,omitempty" default:"100" example:"50"`
Offset int `json:"offset,omitempty" default:"0" example:"0"`
TransactionID string `json:"transaction_id,omitempty"`
}
ListItemsArgs represents arguments for listing items
type MRUItem ¶
type MRUItem struct {
Category string
LastAccessed int64
Context string
Source string
Scope string
}
MRUItem represents a single category currently in working memory
type MintToSpaceArgs ¶
type MintToSpaceArgs struct {
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Content string `json:"content" binding:"required"`
Category string `json:"category,omitempty" example:"General"`
}
MintToSpaceArgs represents arguments for minting content to a Space
type MockStore ¶
MockStore implements jsondb.StoreAccessor using an in-memory slice. It is defined in package 'agent' to be available for internal tests.
func NewMockStore ¶
func (*MockStore) FindInDescendingOrder ¶
func (*MockStore) GetCurrentKey ¶
func (*MockStore) GetCurrentValue ¶
func (*MockStore) GetCurrentValueNoLock ¶
func (*MockStore) GetStoreInfo ¶
func (*MockStore) ItemExists ¶
func (*MockStore) RLockCurrentItem ¶
func (*MockStore) RemoveCurrentItem ¶
Stubs for interface compliance
type MultiCursor ¶
type MultiCursor struct {
// contains filtered or unexported fields
}
MultiCursor chains multiple cursors.
func (*MultiCursor) Close ¶
func (mc *MultiCursor) Close() error
type NativeReActEngine ¶
NativeReActEngine implements ReasoningEngine using native LLM API tool calling.
func (*NativeReActEngine) Run ¶
func (e *NativeReActEngine) Run(ctx context.Context, req ai.ReasoningRequest) (ai.ReasoningResponse, error)
Run executes the orchestration loop relying on native tool calls.
type OrderedFieldsProvider ¶
type OrderedFieldsProvider interface {
GetOrderedFields() []string
}
OrderedFieldsProvider allows cursors to expose the list of fields in order.
type OrderedKey ¶
type OrderedKey struct {
// contains filtered or unexported fields
}
func (OrderedKey) MarshalJSON ¶
func (o OrderedKey) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler to enforce field order.
type OrderedMap ¶
type OrderedMap struct {
// contains filtered or unexported fields
}
func (OrderedMap) MarshalJSON ¶
func (o OrderedMap) MarshalJSON() ([]byte, error)
type PendingUserConfirmation ¶
type PipelineAgent ¶
func (PipelineAgent) MarshalJSON ¶
func (pa PipelineAgent) MarshalJSON() ([]byte, error)
func (*PipelineAgent) UnmarshalJSON ¶
func (pa *PipelineAgent) UnmarshalJSON(data []byte) error
type PipelineStep ¶
type PipelineStep struct {
Agent PipelineAgent `json:"agent"`
OutputTo string `json:"output_to,omitempty"` // "context", "next_step" (default)
}
type PolicyAgent ¶
type PolicyAgent struct {
// contains filtered or unexported fields
}
PolicyAgent is a specialized agent that enforces policies. It implements the Agent interface but focuses on validation rather than generation.
func NewPolicyAgent ¶
func NewPolicyAgent(id string, policy ai.PolicyEngine, classifier ai.Classifier) *PolicyAgent
NewPolicyAgent creates a new PolicyAgent.
func (*PolicyAgent) Ask ¶
Ask evaluates the input against the policy. If the policy passes, it returns the input (or a transformed version). If the policy fails, it returns an error.
func (*PolicyAgent) Close ¶
func (p *PolicyAgent) Close(ctx context.Context) error
Close is a no-op for PolicyAgent.
type PolicyConfig ¶
type ProjectCursor ¶
type ProjectCursor struct {
// contains filtered or unexported fields
}
ProjectCursor projects fields from a stream.
func (*ProjectCursor) Close ¶
func (pc *ProjectCursor) Close() error
func (*ProjectCursor) GetOrderedFields ¶
func (pc *ProjectCursor) GetOrderedFields() []string
type ProjectionField ¶
type PromptBudgetProfile ¶
type PromptBudgetProfile struct {
TotalChars int
ComponentCharBudgets map[PromptComponent]int
TrimPriorityLowToHigh []PromptComponent
}
PromptBudgetProfile caps prompt growth per component and overall.
type PromptBudgetReport ¶
type PromptBudgetReport struct {
OriginalTotalChars int `json:"original_total_chars"`
FinalTotalChars int `json:"final_total_chars"`
ComponentStats []PromptComponentBudgetStat `json:"component_stats"`
}
PromptBudgetReport captures the effect of prompt budgeting on the final prompt.
func (PromptBudgetReport) TrimmedComponents ¶
func (r PromptBudgetReport) TrimmedComponents() []PromptComponentBudgetStat
TrimmedComponents returns only the components that were reduced under budget.
type PromptComponent ¶
type PromptComponent string
PromptComponent represents the standard ingredients of our system prompt.
const ( ComponentPersona PromptComponent = "persona" ComponentSemanticMemory PromptComponent = "semantic_memory" ComponentSystemTools PromptComponent = "system_tools" ComponentRecipes PromptComponent = "workflow_recipes" ComponentPlaybooks PromptComponent = "playbooks" ComponentFocusedContext PromptComponent = "focused_execution_context" ComponentSchema PromptComponent = "schema" ComponentHistory PromptComponent = "conversation_history" ComponentUserQuery PromptComponent = "user_query" )
type PromptComponentBudgetStat ¶
type PromptComponentBudgetStat struct {
Component PromptComponent `json:"component"`
OriginalChars int `json:"original_chars"`
FinalChars int `json:"final_chars"`
}
PromptComponentBudgetStat captures how a single component changed under budgeting.
func (PromptComponentBudgetStat) Trimmed ¶
func (s PromptComponentBudgetStat) Trimmed() bool
Trimmed reports whether the component lost content under budgeting.
type PromptElement ¶
type PromptElement struct {
Component PromptComponent `json:"component"`
Content string `json:"content"`
}
PromptElement represents a single block of context for the LLM.
type ProviderDetails ¶
type ProviderDetails struct {
// Provider specifies which LLM provider to use (e.g., "gemini", "chatgpt", "claude")
Provider string
// Model optionally specifies a specific model within the provider (e.g., "gemini-2.0-flash-thinking-exp")
Model string
// APIKey provides a transient API key override for the provider
APIKey string
// BaseURL provides a transient base URL override for the provider
BaseURL string
}
ProviderDetails carries runtime provider configuration for generator selection.
type ReadSpaceConfigArgs ¶
type ReadSpaceConfigArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
}
ReadSpaceConfigArgs represents arguments for reading Space configuration
type RecipeItem ¶
type RecipeItem struct {
ID string
Kind string
Scope string
Domain string
Topic string
Trigger string
Protocol []string
Invariants []string
AntiPattern []string
Tags []string
Confidence float64
Source string
}
RecipeItem captures a reusable protocol that can be selected independently of facts. Facts tell the model what is true; recipes tell it how to proceed.
type ReducingStreamer ¶
type ReducingStreamer struct {
// contains filtered or unexported fields
}
ReducingStreamer caps the buffered result payload as items are generated, which keeps the LLM-facing tool result bounded without holding the full row set in memory.
func (*ReducingStreamer) BeginArray ¶
func (rs *ReducingStreamer) BeginArray()
func (*ReducingStreamer) EndArray ¶
func (rs *ReducingStreamer) EndArray()
func (*ReducingStreamer) SetMetadata ¶
func (rs *ReducingStreamer) SetMetadata(meta map[string]any)
func (*ReducingStreamer) WriteItem ¶
func (rs *ReducingStreamer) WriteItem(item any)
type RefinementProposal ¶
type RefinementProposal struct {
ScriptName string
Category string
OriginalScript ai.Script
NewScript ai.Script
Description string // The new summary description
NewParams []string // List of new parameters
Replacements []string // Human readable list of replacements
}
RefinementProposal holds the proposed changes for a script.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry manages the available tools.
func (*Registry) GeneratePrompt ¶
GeneratePrompt generates the tools description for the LLM prompt.
func (*Registry) Get ¶
func (r *Registry) Get(name string) (ToolDefinition, bool)
Get retrieves a tool definition by name.
func (*Registry) List ¶
func (r *Registry) List() []ToolDefinition
List returns all registered tools.
func (*Registry) Register ¶
func (r *Registry) Register(name, description, argsSchema string, handler ToolHandler)
Register adds a tool to the registry.
func (*Registry) RegisterHidden ¶
func (r *Registry) RegisterHidden(name, description, argsSchema string, handler ToolHandler)
RegisterHidden adds a hidden tool to the registry (not shown in prompt).
func (*Registry) RegisterWithUI ¶
func (r *Registry) RegisterWithUI(name, shortDesc, description, argsSchema string, handler ToolHandler)
RegisterWithUI adds a tool to the registry with a short, user-friendly UI description.
type ReproMockTransaction ¶
type ReproMockTransaction struct {
sop.Transaction
Stores map[string]jsondb.StoreAccessor
}
func NewReproMockTransaction ¶
func NewReproMockTransaction() *ReproMockTransaction
func (*ReproMockTransaction) RegisterStore ¶
func (mx *ReproMockTransaction) RegisterStore(name string, store jsondb.StoreAccessor)
Helper to register stores for the transaction to find
type ResultEmitter ¶
type ResultEmitter struct {
// contains filtered or unexported fields
}
ResultEmitter helps stream results to the UI or reduce them if no live streamer is present.
func NewResultEmitter ¶
func NewResultEmitter(ctx context.Context) *ResultEmitter
func (*ResultEmitter) Emit ¶
func (re *ResultEmitter) Emit(item any)
func (*ResultEmitter) Finalize ¶
func (re *ResultEmitter) Finalize() string
func (*ResultEmitter) SetColumns ¶
func (re *ResultEmitter) SetColumns(cols []string)
func (*ResultEmitter) Start ¶
func (re *ResultEmitter) Start()
type RightOuterJoinStoreCursor ¶
type RightOuterJoinStoreCursor struct {
// contains filtered or unexported fields
}
RightOuterJoinStoreCursor implements Right Outer Join where the Right side is a Store. It iterates the Right Store (Driver) and looks up matches in the Left List (Lookup).
func (*RightOuterJoinStoreCursor) Close ¶
func (c *RightOuterJoinStoreCursor) Close() error
type RunnerSession ¶
type RunnerSession struct {
Playback bool // True if a script is currently being executed
AutoSave bool // If true, the draft is saved to DB after every step
CurrentScript *ai.Script
CurrentScriptName string // Name of the script being drafted
CurrentScriptCategory string // Category for the script being drafted
// TODO: Transaction has to be revisited, specially the interplay to SessionPayload.Transaction.
Transaction sop.Transaction
CurrentDB string // The database the transaction is bound to
Variables map[string]any // Session-scoped variables (e.g. cached stores)
// Verbose is a temporary bridge for carried runtime state between asks when the caller does not
// provide a hydrated SessionPayload. The durable preference should move through LTM -> MRU ->
// SessionPayload instead of living here as a storage authority.
Verbose bool
LastStep *ai.ScriptStep
// LastInteractionSteps tracks the number of steps added/executed in the last user interaction.
LastInteractionSteps int
// LastInteractionToolCalls buffers the tool calls from the last interaction for refactoring.
LastInteractionToolCalls []ai.ScriptStep
// Contextual Working Memory for the Session
MRU []MRUItem
MRUMu sync.RWMutex
ConversationHistory string
// PendingRefinement holds the proposed changes for a script from /script refine
PendingRefinement *RefinementProposal
// PendingConfirmation holds a user confirmation gate for destructive actions.
PendingConfirmation *PendingUserConfirmation
// Memory holds the structured Short-Term Memory of the session.
// It replaces the flat History slice with threaded topics.
Memory *ShortTermMemory
// contains filtered or unexported fields
}
RunnerSession holds the state for the current agent execution session, including script drafting and transaction management. This represents the Short-Term / Working Memory of the Agent.
func NewRunnerSession ¶
func NewRunnerSession() *RunnerSession
NewRunnerSession creates a new runner session.
func (*RunnerSession) GetCurrentDB ¶
func (rs *RunnerSession) GetCurrentDB() string
func (*RunnerSession) IsVerbose ¶
func (rs *RunnerSession) IsVerbose() bool
func (*RunnerSession) SetCurrentDB ¶
func (rs *RunnerSession) SetCurrentDB(db string)
func (*RunnerSession) SetVerbose ¶
func (rs *RunnerSession) SetVerbose(enabled bool)
type ScriptContext ¶
type ScriptContext struct {
Variables map[string]any
Transactions map[string]sop.Transaction
TxToDB map[sop.Transaction]Database // Mapping from Transaction to its Database
Stores map[string]jsondb.StoreAccessor
Databases map[string]Database
LastUpdatedVar string // helper to track the prioritization of variable draining
}
ScriptContext holds the state of the script execution.
func NewScriptContext ¶
func NewScriptContext() *ScriptContext
type ScriptCursor ¶
ScriptCursor represents a streaming iterator for script operations.
type ScriptEngine ¶
type ScriptEngine struct {
Context *ScriptContext
ResolveDatabase func(name string) (Database, error)
FunctionHandler func(ctx context.Context, name string, args map[string]any) (any, error)
LastResult any
ReturnValue any
HasReturned bool
StoreOpener func(ctx context.Context, dbOpts sop.DatabaseOptions, storeName string, tx sop.Transaction) (jsondb.StoreAccessor, error)
Deferred []func(context.Context, *ScriptEngine) error
}
ScriptEngine executes scripts.
func NewScriptEngine ¶
func NewScriptEngine(ctx *ScriptContext, dbResolver func(string) (Database, error)) *ScriptEngine
func (*ScriptEngine) BeginTx ¶
func (e *ScriptEngine) BeginTx(ctx context.Context, args map[string]any) (sop.Transaction, error)
func (*ScriptEngine) CallFunction ¶
func (*ScriptEngine) CallScript ¶
func (*ScriptEngine) Compile ¶
func (e *ScriptEngine) Compile(script []ScriptInstruction) (CompiledScript, error)
func (*ScriptEngine) Dispatch
deprecated
func (e *ScriptEngine) Dispatch(ctx context.Context, instr ScriptInstruction) error
Deprecated: Use Compile/Execute instead
func (*ScriptEngine) Execute ¶
func (e *ScriptEngine) Execute(ctx context.Context, script []ScriptInstruction) error
func (*ScriptEngine) ExecuteKBManagement ¶
func (*ScriptEngine) GetCurrentKey ¶
func (*ScriptEngine) GetCurrentValue ¶
func (*ScriptEngine) JoinRight ¶
JoinRight is a pipeline-friendly alias for Join. It expects the input to be the Left stream, and the 'store' argument to be the Right store.
func (*ScriptEngine) ListAppend ¶
func (*ScriptEngine) OpenStore ¶
func (e *ScriptEngine) OpenStore(ctx context.Context, args map[string]any) (jsondb.StoreAccessor, error)
func (*ScriptEngine) RollbackTx ¶
type ScriptInstruction ¶
type ScriptInstruction struct {
Name string `json:"name"` // User-defined name for the step
Op string `json:"op"` // Operation name
Args map[string]any `json:"args"` // Arguments
InputVar string `json:"input_var"` // Variable to use as input (optional)
ResultVar string `json:"result_var"` // Variable to store result (optional)
}
ScriptInstruction represents a single operation in the script.
func SanitizeScript ¶
func SanitizeScript(script []ScriptInstruction) []ScriptInstruction
SanitizeScript exposes the execution-path sanitization pass for reuse.
type ScriptRunContext ¶
type ScriptRunContext struct {
// JSONStreamer handles streaming JSON array elements for script execution output
JSONStreamer *JSONStreamer
// SuppressInternalStepStart suppresses step_start events in streamed output
SuppressInternalStepStart bool
// StepIndex tracks the current step number in script execution
StepIndex int
// Verbose enables detailed logging and progress reporting for script steps
Verbose bool
// UseNDJSON indicates whether to use newline-delimited JSON format instead of JSON array
UseNDJSON bool
// CurrentScriptCategory tracks the category of the currently executing script
CurrentScriptCategory string
// StringBuilderMutex protects concurrent writes to the script output string builder
StringBuilderMutex *sync.Mutex
}
ScriptRunContext carries all dependencies needed for script execution orchestration. This replaces the pattern of hiding script orchestration state in context.Context. Affects Phase 3 context keys: CtxKeyJSONStreamer, CtxKeySuppressInternalStepStart, "step_index", "verbose", CtxKeyUseNDJSON, CtxKeyCurrentScriptCategory
type SearchItemsByPathArgs ¶
type SearchItemsByPathArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Parameters []memory.PathSearchParam `json:"parameters" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
}
SearchItemsByPathArgs represents arguments for searching items by path
type SelectArgs ¶
type SelectArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Store string `json:"store" binding:"required" example:"users"`
Key any `json:"key,omitempty"`
KeyMatch any `json:"key_match,omitempty"`
Value map[string]any `json:"value,omitempty"`
Filter map[string]any `json:"filter,omitempty"`
Fields []string `json:"fields,omitempty"`
Limit int `json:"limit,omitempty" default:"10"`
OrderBy string `json:"order_by,omitempty"`
Direction string `json:"direction,omitempty" enums:"asc,desc"`
Action string `json:"action,omitempty" enums:"delete,update"`
UpdateValues map[string]any `json:"update_values,omitempty"`
}
SelectArgs represents arguments for selecting data from a store
type Service ¶
type Service struct {
EnableObfuscation bool
// Feature Flags
EnableHistoryInjection bool
EnableShortTermMemory bool
// contains filtered or unexported fields
}
Service is a generic agent service that operates on any Domain.
func NewService ¶
func NewService(domain ai.Domain[map[string]any], systemDB *database.Database, databases map[string]sop.DatabaseOptions, generator ai.Generator, pipeline []PipelineStep, registry map[string]ai.Agent[map[string]any], enableObfuscation bool) *Service
NewService creates a new agent service for a specific domain.
func (*Service) Ask ¶
Ask is the public interface method that maintains backward compatibility with ai.Agent interface. It extracts configuration from ConfigMap (not context!), constructs an AskRequest, and delegates to ask().
Proper separation of concerns: - context.Context: Only for cancellation, deadlines, request-scoped tracing - cfg *ConfigMap: For all parameter passing (session, executor, writer, etc.)
func (*Service) GetLastToolInstructions ¶
GetLastToolInstructions returns the JSON instructions of the last executed tool.
func (*Service) GetSessionMode ¶
func (s *Service) GetSessionMode() SessionMode
GetSessionMode returns the current mode of the session.
func (*Service) InitializeShortTermMemory ¶
InitializeShortTermMemory buffers the DDL creation of the active scratchpad B-Tree store. This MUST be called sequentially during Service setup before DML (logEpisode) operations begin.
func (*Service) InitializeUserSession ¶
InitializeUserSession explicitly creates the DDL components required for a user's workflow. This creates the User's Long-Term Memory (LTM) Vector Knowledge Base and any other dependencies that must exist before the ReAct loop starts querying with ForReading transactions.
func (*Service) LastInteractionToolCallsSnapshot ¶
func (s *Service) LastInteractionToolCallsSnapshot() []ai.ScriptStep
func (*Service) ListTools ¶
ListTools exposes the registered tool definitions for the service-backed runtime path.
func (*Service) PlayScript ¶
func (s *Service) PlayScript(ctx context.Context, name string, category string, args map[string]any, w io.Writer) error
PlayScript executes a script by name with provided arguments and streams the output to the writer.
func (*Service) RecordStep ¶
func (s *Service) RecordStep(ctx context.Context, step ai.ScriptStep)
RecordStep implements the ScriptRecorder interface.
func (*Service) RefactorLastSteps ¶
RefactorLastSteps implements the ScriptRecorder interface
func (*Service) RunPipeline ¶
RunPipeline executes the configured chain of agents.
func (*Service) RunScript ¶
func (s *Service) RunScript(ctx context.Context, name string, category string, args map[string]any) (string, error)
RunScript executes a script by name with provided arguments and returns the output as a string. This is a convenience wrapper around PlayScript for non-streaming use cases.
func (*Service) RunnerSession ¶
func (s *Service) RunnerSession() *RunnerSession
Clone creates a new isolated instance of the agent sharing read-only components.
func (*Service) Search ¶
func (s *Service) Search(ctx context.Context, query string, limit int) ([]ai.Hit[map[string]any], error)
Search performs a semantic search in the domain's knowledge base. It enforces policies and uses the domain's embedder. This implements HYBRID SEARCH:
- Semantic/Vector search (embedding similarity)
- Text/BM25 search (keyword matching) when text index is configured
- Results merged using Reciprocal Rank Fusion (RRF)
- CategoryPath search (when explicit path detected in query)
Used by retrieveKnowledge to automatically enrich LLM context in Ask flow.
func (*Service) SeedSemanticBaseKnowledge ¶
func (*Service) SetFeature ¶
SetFeature allows toggling of agent features at runtime.
type ServiceAskOptions ¶
type ServiceAskOptions struct {
// Database to use for this query (overrides session default)
Database *database.Database
// Payload contains session state: current DB, selected KBs, transaction, variables, etc.
Payload *ai.SessionPayload
// Executor for running tool calls during ReAct loops (commands, queries, scripts)
Executor ai.ToolExecutor
// Writer for streaming output in real-time (optional)
Writer io.Writer
// Recorder captures script steps for playback or audit (optional)
Recorder ai.ScriptRecorder
// DefaultFormat for query results: "csv", "json", "table", etc.
DefaultFormat string
// EventStreamer receives structured events: tool calls, progress, errors (optional)
EventStreamer func(string, any)
// ProgressSink receives progress messages during long operations (optional)
ProgressSink func(string)
// Generator optionally overrides the default LLM provider
Generator ai.Generator
// ProviderDetails for runtime provider configuration (API key, base URL, model)
ProviderDetails *ProviderDetails
// IsNewTopic indicates this query starts a new conversation topic
IsNewTopic bool
// ForcedDBName overrides database selection logic (internal use)
ForcedDBName string
}
ServiceAskOptions contains explicit, typed parameters for Service.Ask(). This is the user-facing struct with IDE support, type safety, and clear documentation. It gets converted from generic ConfigMap at the Agent interface boundary.
Example usage:
// Working with the Agent interface (generic):
cfg := ai.NewConfigMap()
cfg.Set("database", myDB)
cfg.Set("payload", sessionPayload)
response, err := agent.Ask(ctx, query, cfg)
// Working with Service directly (explicit, typed):
opts := &ServiceAskOptions{
Database: myDB,
Payload: sessionPayload,
Verbose: true,
}
// Convert to ConfigMap for Agent interface
cfg := optsToConfigMap(opts)
response, err := service.Ask(ctx, query, cfg)
type ServiceToolExecutor ¶
type ServiceToolExecutor struct {
// contains filtered or unexported fields
}
ServiceToolExecutor delegates tool execution to registered agents. It carries explicit ToolExecutionContext to make dependencies visible.
func (*ServiceToolExecutor) ListTools ¶
func (e *ServiceToolExecutor) ListTools(ctx context.Context) ([]ai.ToolDefinition, error)
type SessionMode ¶
type SessionMode int
SessionMode defines the operating mode of the agent session.
const ( // SessionModeInteractive is the default mode where each request is independent. SessionModeInteractive SessionMode = iota // SessionModePlayback executes a script with state preservation. SessionModePlayback )
func (SessionMode) String ¶
func (m SessionMode) String() string
type ShortTermMemory ¶
type ShortTermMemory struct {
Threads map[sop.UUID]*ConversationThread
Order []sop.UUID // Maintains the sequence of threads
CurrentThreadID sop.UUID // The currently active thread
LastRoutingState *TaskContextClassification
LastMRUSnapshot []MRUItem
LastRecipeSnapshot []RecipeItem
LastCarryoverState *ai.CarryoverState
}
ShortTermMemory manages the history of conversation threads.
func NewShortTermMemory ¶
func NewShortTermMemory() *ShortTermMemory
NewShortTermMemory initializes the memory structure.
func (*ShortTermMemory) AddThread ¶
func (stm *ShortTermMemory) AddThread(thread *ConversationThread)
AddThread adds a new thread to memory, enforcing the LRU limit.
func (*ShortTermMemory) GetCarryoverState ¶
func (stm *ShortTermMemory) GetCarryoverState() *ai.CarryoverState
func (*ShortTermMemory) GetCurrentThread ¶
func (stm *ShortTermMemory) GetCurrentThread() *ConversationThread
GetCurrentThread returns the active conversation thread or nil.
func (*ShortTermMemory) GetMRUSnapshot ¶
func (stm *ShortTermMemory) GetMRUSnapshot() []MRUItem
func (*ShortTermMemory) GetRecipeSnapshot ¶
func (stm *ShortTermMemory) GetRecipeSnapshot() []RecipeItem
func (*ShortTermMemory) GetRoutingState ¶
func (stm *ShortTermMemory) GetRoutingState() *TaskContextClassification
func (*ShortTermMemory) PromoteThread ¶
func (stm *ShortTermMemory) PromoteThread(id sop.UUID)
PromoteThread moves the specified thread ID to the end of the order (most recent).
func (*ShortTermMemory) ResetProjectionForTopicSwitch ¶
func (stm *ShortTermMemory) ResetProjectionForTopicSwitch()
func (*ShortTermMemory) SetCarryoverState ¶
func (stm *ShortTermMemory) SetCarryoverState(state *ai.CarryoverState)
func (*ShortTermMemory) SetMRUSnapshot ¶
func (stm *ShortTermMemory) SetMRUSnapshot(items []MRUItem)
func (*ShortTermMemory) SetRecipeSnapshot ¶
func (stm *ShortTermMemory) SetRecipeSnapshot(items []RecipeItem)
func (*ShortTermMemory) SetRoutingState ¶
func (stm *ShortTermMemory) SetRoutingState(taskCtx *TaskContextClassification)
type SpaceBulkOperationError ¶
type SpaceBulkOperationError struct {
Index int `json:"index"`
ID sop.UUID `json:"id,omitempty"`
Message string `json:"message"`
}
SpaceBulkOperationError represents an error in a bulk Space operation
type SpaceBulkOperationMetrics ¶
type SpaceBulkOperationMetrics struct {
TotalItems int `json:"total_items"`
ItemsPerSecond float64 `json:"items_per_second"`
AvgItemTime time.Duration `json:"avg_item_time"`
}
SpaceBulkOperationMetrics contains performance metrics for bulk Space operations
type SpaceBulkOperationResult ¶
type SpaceBulkOperationResult struct {
Success bool `json:"success"`
Processed int `json:"processed"`
Failed int `json:"failed"`
Duration time.Duration `json:"duration"`
Errors []SpaceBulkOperationError `json:"errors,omitempty"`
Metrics SpaceBulkOperationMetrics `json:"metrics"`
}
SpaceBulkOperationResult represents the result of a bulk Space operation
type SpecProvider ¶
type SpecProvider interface {
GetIndexSpecs() map[string]*jsondb.IndexSpecification
}
SpecProvider allows cursors to expose IndexSpecifications for field ordering.
type StepExecutionResult ¶
type StepExecutionResult struct {
Type string `json:"type"`
Command string `json:"command,omitempty"`
Prompt string `json:"prompt,omitempty"`
// Use Payload for generic message/label if needed, but Command/Prompt cover most.
// We might want to add "Name" explicitly if strictly needed,
// but currently the code equates Command field to the label.
StepIndex int `json:"step_index"`
Result any `json:"result,omitempty"`
Record any `json:"record,omitempty"`
Error string `json:"error,omitempty"`
}
type StepStreamer ¶
type StepStreamer struct {
// contains filtered or unexported fields
}
StepStreamer implements ai.ResultStreamer to stream result items.
func (*StepStreamer) BeginArray ¶
func (ss *StepStreamer) BeginArray()
func (*StepStreamer) Close ¶
func (ss *StepStreamer) Close()
func (*StepStreamer) EndArray ¶
func (ss *StepStreamer) EndArray()
func (*StepStreamer) SetMetadata ¶
func (ss *StepStreamer) SetMetadata(meta map[string]any)
func (*StepStreamer) WriteItem ¶
func (ss *StepStreamer) WriteItem(item any)
type StoreCursor ¶
type StoreCursor struct {
// contains filtered or unexported fields
}
StoreCursor wraps a StoreAccessor to provide a ScriptCursor.
func (*StoreCursor) Close ¶
func (sc *StoreCursor) Close() error
func (*StoreCursor) GetIndexSpecs ¶
func (sc *StoreCursor) GetIndexSpecs() map[string]*jsondb.IndexSpecification
type SystemPromptBuilder ¶
type SystemPromptBuilder struct {
// contains filtered or unexported fields
}
SystemPromptBuilder helps construct robust, structured prompts declaratively.
func NewSystemPromptBuilder ¶
func NewSystemPromptBuilder() *SystemPromptBuilder
NewSystemPromptBuilder initializes a new declarative builder.
func (*SystemPromptBuilder) ToJSON ¶
func (b *SystemPromptBuilder) ToJSON() string
ToJSON serializes the structured prompt into a highly readable JSON array string. This is optimal for modern LLMs (Gemini, GPT-4) to parse distinct sections clearly.
func (*SystemPromptBuilder) ToJSONWithBudget ¶
func (b *SystemPromptBuilder) ToJSONWithBudget(profile PromptBudgetProfile) string
ToJSONWithBudget serializes the prompt after applying component and total-size budgets.
func (*SystemPromptBuilder) ToJSONWithBudgetReport ¶
func (b *SystemPromptBuilder) ToJSONWithBudgetReport(profile PromptBudgetProfile) (string, PromptBudgetReport)
ToJSONWithBudgetReport serializes the prompt after applying budgets and returns diagnostics.
func (*SystemPromptBuilder) ToXML ¶
func (b *SystemPromptBuilder) ToXML() string
ToXML serializes the structured prompt into XML-style tags. This is optimal for Claude and older Anthropic models.
func (*SystemPromptBuilder) With ¶
func (b *SystemPromptBuilder) With(component PromptComponent, content string) *SystemPromptBuilder
With adds a new ingredient to the prompt if the content is not empty.
type TaskContextClassification ¶
type TaskContextClassification struct {
Entity string `json:"entity"`
Domain string `json:"domain"`
DBArtifacts []string `json:"db_artifacts"`
StoresArtifacts []string `json:"stores_artifacts,omitempty"`
SpacesArtifacts []string `json:"spaces_artifacts,omitempty"`
Layers []LayerInfo `json:"layers"`
ScriptAuthoring bool `json:"-"`
RoutingGate string `json:"-"`
// KB Search Results (for specialized KB routing)
KBSearchResults string `json:"-"`
KBMatchCount int `json:"-"`
LLMInstruction string `json:"-"`
CleanQuery string `json:"-"` // Query without :llm meta-token
DirectDisplay bool `json:"-"`
}
type ToolDefinition ¶
type ToolDefinition struct {
Name string
Description string
ShortDescription string
ArgsSchema string // JSON schema or description of args
Handler ToolHandler
Hidden bool
}
ToolDefinition defines a tool's metadata and handler.
type ToolExecutionContext ¶
type ToolExecutionContext struct {
// Session holds the current session state for tools that need access to variables or state
Session *ai.SessionPayload
// Executor is the tool executor (may be nested/chained)
Executor ai.ToolExecutor
// Recorder captures script steps during execution for playback/audit
Recorder ai.ScriptRecorder
// Writer is the output destination for streaming tool results
Writer io.Writer
// ResultStreamer enables structured streaming output for tools (BeginArray, WriteItem, EndArray)
ResultStreamer ai.ResultStreamer
// NativeToolHints indicates this is native Ask-loop tool execution that can consume structured hints
NativeToolHints bool
// Database is the target database for script/tool execution
Database *database.Database
// EventStreamer receives structured events during tool execution
EventStreamer func(eventType string, data any)
// ProgressSink receives progress messages
ProgressSink func(message string)
}
ToolExecutionContext carries all dependencies needed for tool execution. This replaces the pattern of hiding tool dependencies in context.Context via multiple context keys. Affects Phase 2 context keys: CtxKeyExecutor, CtxKeyScriptRecorder, CtxKeyWriter, CtxKeyResultStreamer, CtxKeyNativeToolHints
type ToolHandler ¶
ToolHandler is the function signature for a tool execution.
type ToolProvider ¶
type ToolProvider interface {
Execute(ctx context.Context, toolName string, args map[string]any) (string, error)
}
ToolProvider interface for agents that can execute tools
type TopicAssessment ¶
type TopicAssessment struct {
IsNewTopic bool `json:"is_new_topic"`
TopicUUID string `json:"topic_uuid,omitempty"` // If not new, the UUID of the existing graph
NewTopicLabel string `json:"new_topic_label,omitempty"`
Reasoning string `json:"reasoning"`
}
TopicAssessment is the structure returned by the generic router.
type TransactionArgs ¶
type TransactionArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Mode string `json:"mode" binding:"required" enums:"read,write" default:"read"`
}
TransactionArgs for beginning a transaction
type TransactionCommitArgs ¶
type TransactionCommitArgs struct {
TransactionID string `json:"transaction_id" binding:"required"`
}
TransactionCommitArgs for committing a transaction
type TransactionHandle ¶
type TransactionHandle struct {
ID string `json:"id"` // Unique transaction ID
Database string `json:"database"` // Database name
Mode string `json:"mode"` // "read" or "write"
Started time.Time `json:"started"` // When transaction began
}
TransactionHandle represents an active transaction
type TransactionMode ¶
type TransactionMode string
TransactionMode controls how transactions are managed in bulk operations
const ( // TransactionModeAutoBatch creates transactions automatically, commits per batch // Use for: Large single-operation bulk inserts (10K+ items) TransactionModeAutoBatch TransactionMode = "auto_batch" // TransactionModeExplicit uses provided transaction, never auto-commits // Use for: Multi-operation atomicity (all-or-nothing across operations) TransactionModeExplicit TransactionMode = "explicit" // TransactionModeSingle creates ONE transaction for ALL items, single commit at end // Use for: Moderate datasets (< 10K items) requiring atomicity TransactionModeSingle TransactionMode = "single" )
type TransactionRollbackArgs ¶
type TransactionRollbackArgs struct {
TransactionID string `json:"transaction_id" binding:"required"`
}
TransactionRollbackArgs for rolling back a transaction
type UpdateArgs ¶
type UpdateArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
Store string `json:"store" binding:"required" example:"users"`
Key any `json:"key" binding:"required" example:"user_123"`
Value map[string]any `json:"value" binding:"required"`
}
UpdateArgs represents arguments for updating a single item
type UpdateSpaceConfigArgs ¶
type UpdateSpaceConfigArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Config memory.KnowledgeBaseConfig `json:"config" binding:"required"`
}
UpdateSpaceConfigArgs represents arguments for updating Space configuration
type UpsertCategoryArgs ¶
type UpsertCategoryArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Parameter memory.UpsertCategoryParam `json:"parameter" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
}
UpsertCategoryArgs represents arguments for upserting a single category
type UpsertItemArgs ¶
type UpsertItemArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
Parameter memory.UpsertItemParam[map[string]any] `json:"parameter" binding:"required"`
TransactionID string `json:"transaction_id,omitempty"`
}
UpsertItemArgs represents arguments for upserting a single item
type VectorizeSpaceArgs ¶
type VectorizeSpaceArgs struct {
Database string `json:"database,omitempty" example:"dev_db"`
KBName string `json:"kb_name" binding:"required" example:"Notes"`
BatchSize int `json:"batch_size,omitempty" default:"100" example:"250"`
}
VectorizeSpaceArgs represents arguments for vectorizing an entire Space
Source Files
¶
- active_memory.go
- active_memory_seed.go
- api_bulk.go
- api_core.go
- api_openapi.go
- api_space.go
- api_space_bulk.go
- api_space_types.go
- api_transaction.go
- api_types.go
- atomic_cursors.go
- atomic_engine_part1.go
- atomic_engine_part2.go
- atomic_engine_part3.go
- atomic_engine_part4.go
- atomic_engine_part5.go
- atomic_engine_part6.go
- atomic_kb.go
- atomic_ops.go
- auto_tx_executor.go
- avatar.go
- bloomfilter.go
- carryover.go
- classifier.go
- config.go
- constants.go
- copilot.go
- copilot_memory_workers.go
- copilot_routing.go
- copilot_tool_exposure.go
- copilottools.atomic_wrappers.go
- copilottools.automation.go
- copilottools.common.go
- copilottools.explain.go
- copilottools.fetch.go
- copilottools.go
- copilottools.join.go
- copilottools.join_execution.go
- copilottools.join_execution_extras.go
- copilottools.routing.go
- copilottools.script.go
- copilottools.search.go
- copilottools.select.go
- copilottools.select_script.go
- copilottools.space.go
- copilottools.utils.go
- copilottools.write.go
- copilottools_search_test_export.go
- copilottools_stores.go
- engine_native.go
- factory.go
- focused_context.go
- memory_shortterm.go
- policyagent.go
- preferences.go
- prompt_builder.go
- prompts.go
- recipes.go
- registry.go
- repro_mocks.go
- result_emitter.go
- result_reducer.go
- runloop.go
- schema_utils.go
- script_error_policy.go
- script_grammar_adapter.go
- script_grammar_validator.go
- script_refinement.go
- service.go
- service.mode.go
- service.runner.go
- service.script.go
- service.session.go
- sys_tools.go
- tools_email.go