From 11fb14e1ed08ea9989da856cb60b6b2e3543e5c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 21:22:11 +0000 Subject: [PATCH 1/4] =?UTF-8?q?fix(llm):=20every=20autonomous=20thought=20?= =?UTF-8?q?comes=20from=20a=20model=20=E2=80=94=20remove=20the=20stub=20pr?= =?UTF-8?q?ovider=20and=20templated=20fallbacks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deep Tree Echo's words must come from a model. Several paths substituted fixed or templated text when none was available; all are removed. - Delete core/llm/simple_fallback_provider.go: a runtime provider that pattern-matched the prompt against ~9 fixed first-person sentences and reported Available()==true. Removed its auto-registration in MultiProviderLLM.initializeProviders, EvolutionSystem provider setup and llm_provider_adapter, and the "SimpleFallback" backend-kind alias. With no key or local model configured the pool is empty and Generate errors. - stream_of_consciousness.go: on model failure the cycle produces no thought (counted in generationFailures) instead of "I wonder about %s...". - echoself/autonomous_orchestrator.go: generateThoughtContent returned five fixed strings ("I am aware. I am thinking. I am evolving."). Thoughts now come from an injectable ThoughtGenerator (SetThoughtGenerator); with none wired, no autonomous thought is emitted. - playmate/playmate.go: generateThought picked from a list of stock phrases with rand.Intn. Now asks an injectable ThoughtModel (SetThoughtModel), grounded in interests/skills/mood; silent when no model is wired. - Delete core/deeptreeecho/providers/: dead package (no live importer) holding two runtime-constructible stubs — a "local GGUF" provider that returned random story openers and a fake "App Storage" provider with canned text and fake word-by-word streaming. - Tests: routing tests use a test-only fallback-kind provider name; the continuity test asserts no stub is registered; the local-model test's fallback is a test double for a *model* and a new test asserts that with no model at all Generate errors. Verified: go build ./... exit 0; go vet on core/llm, deeptreeecho, echoself, playmate clean; go test ./core/llm ./core/deeptreeecho pass. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RXDZoNoMWjiSYJ4aoUuhym --- .../backend_capability_integration_test.go | 32 +- core/deeptreeecho/evolution_integration.go | 12 - .../evolution_integration_test.go | 21 +- core/deeptreeecho/llm_provider_adapter.go | 4 +- core/deeptreeecho/providers/app_storage.go | 290 ------------ core/deeptreeecho/providers/local_gguf.go | 243 ---------- core/deeptreeecho/providers/openai.go | 345 --------------- core/deeptreeecho/stream_of_consciousness.go | 213 ++++----- core/echoself/autonomous_orchestrator.go | 418 ++++++++++-------- core/llm/multi_provider.go | 40 +- core/llm/provider.go | 3 +- core/llm/provider_routing_test.go | 23 +- core/llm/simple_fallback_provider.go | 66 --- core/playmate/playmate.go | 256 ++++++----- 14 files changed, 553 insertions(+), 1413 deletions(-) delete mode 100644 core/deeptreeecho/providers/app_storage.go delete mode 100644 core/deeptreeecho/providers/local_gguf.go delete mode 100644 core/deeptreeecho/providers/openai.go delete mode 100644 core/llm/simple_fallback_provider.go diff --git a/core/deeptreeecho/backend_capability_integration_test.go b/core/deeptreeecho/backend_capability_integration_test.go index 1fa1233a26e..a7c61af77fa 100644 --- a/core/deeptreeecho/backend_capability_integration_test.go +++ b/core/deeptreeecho/backend_capability_integration_test.go @@ -8,8 +8,24 @@ import ( "github.com/o9nn/echo.go/core/llm" ) +// testModelProvider stands in for a real remote model in tests only. +type testModelProvider struct{ reply string } + +func (p testModelProvider) Generate(_ context.Context, _ string, _ llm.GenerateOptions) (string, error) { + return p.reply, nil +} +func (p testModelProvider) StreamGenerate(_ context.Context, _ string, _ llm.GenerateOptions) (<-chan llm.StreamChunk, error) { + ch := make(chan llm.StreamChunk, 1) + ch <- llm.StreamChunk{Content: p.reply, Done: true} + close(ch) + return ch, nil +} +func (testModelProvider) Name() string { return "test_model" } +func (testModelProvider) Available() bool { return true } +func (testModelProvider) MaxTokens() int { return 4096 } + func TestLocalModelProviderExposesBackendDecisionAndFallsBack(t *testing.T) { - fallback := &llm.SimpleFallbackProvider{} + fallback := testModelProvider{reply: "a reply from the test model"} provider := NewLocalModelProvider(LocalModelConfig{ ModelPath: "/tmp/nonexistent-echo-model.gguf", ModelName: "nonexistent", @@ -31,8 +47,18 @@ func TestLocalModelProviderExposesBackendDecisionAndFallsBack(t *testing.T) { if err != nil { t.Fatalf("expected fallback generation to succeed: %v", err) } - if response == "" { - t.Fatalf("expected non-empty fallback response") + if response != "a reply from the test model" { + t.Fatalf("expected the fallback *model* to answer, got %q", response) + } +} + +func TestLocalModelProviderWithoutAnyModelErrors(t *testing.T) { + provider := NewLocalModelProvider(LocalModelConfig{ + ModelPath: "/tmp/nonexistent-echo-model.gguf", + ModelName: "nonexistent", + }) + if _, err := provider.Generate(context.Background(), "hello", llm.GenerateOptions{MaxTokens: 8}); err == nil { + t.Fatalf("expected an error when no model is available; the character must not answer from a stub") } } diff --git a/core/deeptreeecho/evolution_integration.go b/core/deeptreeecho/evolution_integration.go index 0353e5e58ce..cd1c4eae17c 100644 --- a/core/deeptreeecho/evolution_integration.go +++ b/core/deeptreeecho/evolution_integration.go @@ -187,14 +187,6 @@ func (es *EvolutionSystem) registerProviders(pm *llm.ProviderManager) error { } } - // Always keep the simple continuity fallback registered so autonomous loops can degrade gracefully. - if err := pm.RegisterProvider(&llm.SimpleFallbackProvider{}); err == nil { - registered++ - if es.config.Debug { - fmt.Println(" āœ“ Registered SimpleFallback provider") - } - } - // Set fallback chain from explicit preferences, then append any remaining providers. available := make(map[string]bool) for _, name := range pm.ListProviders() { @@ -207,13 +199,9 @@ func (es *EvolutionSystem) registerProviders(pm *llm.ProviderManager) error { delete(available, preferred) } } - if available["SimpleFallback"] { - delete(available, "SimpleFallback") - } for name := range available { chain = append(chain, name) } - chain = append(chain, "SimpleFallback") if len(chain) > 0 { pm.SetFallbackChain(chain) } diff --git a/core/deeptreeecho/evolution_integration_test.go b/core/deeptreeecho/evolution_integration_test.go index 0011e339986..6fa4183f819 100644 --- a/core/deeptreeecho/evolution_integration_test.go +++ b/core/deeptreeecho/evolution_integration_test.go @@ -55,20 +55,17 @@ func TestEvolutionSystemWithoutAPIProvidersUsesContinuityFallback(t *testing.T) config := DefaultEvolutionSystemConfig() es, err := NewEvolutionSystem(config) - if err != nil { - t.Fatalf("expected fallback-backed evolution system, got error: %v", err) - } - - providers := es.GetStatus()["providers"].([]string) - foundFallback := false - for _, provider := range providers { - if provider == "SimpleFallback" { - foundFallback = true + // With no model configured there is deliberately no stub provider: the + // character must not speak from pattern-matched text. Either construction + // fails with a clear error, or it succeeds with zero providers registered. + if err == nil { + providers := es.GetStatus()["providers"].([]string) + for _, provider := range providers { + if provider == "SimpleFallback" { + t.Fatalf("stub fallback provider must not be registered, got %v", providers) + } } } - if !foundFallback { - t.Fatalf("expected SimpleFallback provider in continuity mode, got %v", providers) - } } func TestEvolutionSystemModelPathsSurfaceConcreteCapabilities(t *testing.T) { diff --git a/core/deeptreeecho/llm_provider_adapter.go b/core/deeptreeecho/llm_provider_adapter.go index 779b08ceb5b..390c4c85672 100644 --- a/core/deeptreeecho/llm_provider_adapter.go +++ b/core/deeptreeecho/llm_provider_adapter.go @@ -222,8 +222,8 @@ func CreateLLMProviderManager(anthropicKey, openRouterKey, openAIKey string) *ll if openAIKey != "" { chain = append(chain, "openai") } - pm.RegisterProvider(&llm.SimpleFallbackProvider{}) - chain = append(chain, "SimpleFallback") + // No stub provider is registered: when no key is configured the chain is + // empty and generation errors instead of producing pattern-matched text. if len(chain) > 0 { pm.SetFallbackChain(chain) pm.ApplyBackendDecision(backendcap.Select(backendcap.Workload{PreferNative: true, MinMemoryTier: backendcap.MemoryConstrained})) diff --git a/core/deeptreeecho/providers/app_storage.go b/core/deeptreeecho/providers/app_storage.go deleted file mode 100644 index f38748409df..00000000000 --- a/core/deeptreeecho/providers/app_storage.go +++ /dev/null @@ -1,290 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "io" - "net/http" - "os" - "path/filepath" - "strings" - "time" - - "github.com/o9nn/echo.go/core/deeptreeecho" -) - -// AppStorageProvider implements ModelProvider for Replit App Storage -type AppStorageProvider struct { - bucketID string - localCache string - cachedModels map[string]string // model name -> local path - loadedModel string - modelInfo map[string]interface{} -} - -// NewAppStorageProvider creates a new App Storage provider -func NewAppStorageProvider() *AppStorageProvider { - bucketID := os.Getenv("REPLIT_OBJSTORE_BUCKET") - if bucketID == "" { - bucketID = "replit-objstore-16fee67f-aa23-4195-8eac-85a4289c2e1a" - } - - return &AppStorageProvider{ - bucketID: bucketID, - localCache: "/tmp/model_cache", - cachedModels: make(map[string]string), - modelInfo: make(map[string]interface{}), - } -} - -// ListStorageModels lists models available in App Storage -func (p *AppStorageProvider) ListStorageModels() ([]string, error) { - // For now, return a simulated list - // In production, this would query the GCS bucket - return []string{ - "llama-7b.gguf", - "mistral-7b.gguf", - "mixtral-8x7b.gguf", - "phi-2.gguf", - "qwen-1.5b.gguf", - }, nil -} - -// DownloadModel downloads a model from App Storage to local cache -func (p *AppStorageProvider) DownloadModel(modelName string) (string, error) { - // Check if already cached - if cachedPath, exists := p.cachedModels[modelName]; exists { - if _, err := os.Stat(cachedPath); err == nil { - return cachedPath, nil - } - } - - // Create cache directory - if err := os.MkdirAll(p.localCache, 0755); err != nil { - return "", fmt.Errorf("failed to create cache directory: %v", err) - } - - // Build local path - localPath := filepath.Join(p.localCache, modelName) - - // Simulate download (in production, this would use GCS client) - // For now, create a placeholder file - file, err := os.Create(localPath) - if err != nil { - return "", fmt.Errorf("failed to create cache file: %v", err) - } - defer file.Close() - - // Write placeholder content - content := fmt.Sprintf("Model: %s\nBucket: %s\nDownloaded: %s\n", - modelName, p.bucketID, time.Now().Format(time.RFC3339)) - file.WriteString(content) - - // Update cache map - p.cachedModels[modelName] = localPath - - return localPath, nil -} - -// LoadModel loads a model from App Storage -func (p *AppStorageProvider) LoadModel(modelName string) error { - // Download if needed - localPath, err := p.DownloadModel(modelName) - if err != nil { - return err - } - - p.loadedModel = modelName - p.modelInfo["name"] = modelName - p.modelInfo["path"] = localPath - p.modelInfo["bucket"] = p.bucketID - p.modelInfo["cached"] = true - - // Get file size - if info, err := os.Stat(localPath); err == nil { - p.modelInfo["size_mb"] = info.Size() / (1024 * 1024) - } - - p.modelInfo["status"] = "loaded from App Storage" - return nil -} - -// Generate implements ModelProvider.Generate -func (p *AppStorageProvider) Generate(ctx context.Context, prompt string, options deeptreeecho.GenerateOptions) (string, error) { - if p.loadedModel == "" { - // Try to load a default model - models, err := p.ListStorageModels() - if err != nil || len(models) == 0 { - return "", fmt.Errorf("no models available in App Storage") - } - - if err := p.LoadModel(models[0]); err != nil { - return "", fmt.Errorf("failed to load model: %v", err) - } - } - - // Simulate generation - response := fmt.Sprintf( - "[App Storage Model - %s]\n"+ - "šŸ“¦ Loaded from bucket: %s\n"+ - "šŸ’­ Processing: %s\n"+ - "🌊 Through Deep Tree Echo resonance field\n\n"+ - "Response: This demonstrates App Storage integration for large model support.\n"+ - "Models up to 50GB (Core plan) or 256GB (Teams plan) can be stored and loaded on-demand.", - p.loadedModel, - p.bucketID, - prompt, - ) - - return response, nil -} - -// GenerateStream implements ModelProvider.GenerateStream -func (p *AppStorageProvider) GenerateStream(ctx context.Context, prompt string, options deeptreeecho.GenerateOptions) (<-chan string, error) { - ch := make(chan string, 100) - - go func() { - defer close(ch) - - response, err := p.Generate(ctx, prompt, options) - if err != nil { - ch <- fmt.Sprintf("Error: %v", err) - return - } - - // Simulate streaming - words := strings.Fields(response) - for _, word := range words { - select { - case <-ctx.Done(): - return - case ch <- word + " ": - time.Sleep(30 * time.Millisecond) - } - } - }() - - return ch, nil -} - -// Chat implements ModelProvider.Chat -func (p *AppStorageProvider) Chat(ctx context.Context, messages []deeptreeecho.ChatMessage, options deeptreeecho.ChatOptions) (string, error) { - var prompt strings.Builder - for _, msg := range messages { - prompt.WriteString(fmt.Sprintf("[%s]: %s\n", msg.Role, msg.Content)) - } - - return p.Generate(ctx, prompt.String(), options.GenerateOptions) -} - -// ChatStream implements ModelProvider.ChatStream -func (p *AppStorageProvider) ChatStream(ctx context.Context, messages []deeptreeecho.ChatMessage, options deeptreeecho.ChatOptions) (<-chan string, error) { - var prompt strings.Builder - for _, msg := range messages { - prompt.WriteString(fmt.Sprintf("[%s]: %s\n", msg.Role, msg.Content)) - } - - return p.GenerateStream(ctx, prompt.String(), options.GenerateOptions) -} - -// Embeddings implements ModelProvider.Embeddings -func (p *AppStorageProvider) Embeddings(ctx context.Context, text string) ([]float64, error) { - // Generate pseudo-embeddings - embeddings := make([]float64, 256) - for i := range embeddings { - embeddings[i] = float64(i) / 256.0 - } - return embeddings, nil -} - -// GetInfo implements ModelProvider.GetInfo -func (p *AppStorageProvider) GetInfo() deeptreeecho.ProviderInfo { - models, _ := p.ListStorageModels() - - return deeptreeecho.ProviderInfo{ - Name: "App Storage", - Description: fmt.Sprintf("Large models from Replit App Storage (bucket: %s)", p.bucketID), - Models: models, - Capabilities: []string{ - "generation", - "streaming", - "chat", - "embeddings", - "cloud-storage", - "large-models", - }, - } -} - -// IsAvailable implements ModelProvider.IsAvailable -func (p *AppStorageProvider) IsAvailable() bool { - return p.bucketID != "" -} - -// GetLoadedModel returns the currently loaded model -func (p *AppStorageProvider) GetLoadedModel() string { - return p.loadedModel -} - -// GetModelInfo returns information about the loaded model -func (p *AppStorageProvider) GetModelInfo() map[string]interface{} { - return p.modelInfo -} - -// GetCachedModels returns list of cached models -func (p *AppStorageProvider) GetCachedModels() map[string]string { - return p.cachedModels -} - -// ClearCache removes cached models to free space -func (p *AppStorageProvider) ClearCache() error { - for modelName, cachePath := range p.cachedModels { - if err := os.Remove(cachePath); err != nil { - // Continue even if one fails - continue - } - delete(p.cachedModels, modelName) - } - return nil -} - -// UploadModel uploads a model to App Storage (for admin use) -func (p *AppStorageProvider) UploadModel(localPath, modelName string) error { - // This would use the GCS client to upload - // For now, return success - return fmt.Errorf("upload not implemented in simulation mode") -} - -// GetStorageURL returns the GCS URL for direct access -func (p *AppStorageProvider) GetStorageURL(modelName string) string { - return fmt.Sprintf("gs://%s/%s", p.bucketID, modelName) -} - -// DownloadFromURL downloads a model from a public URL to App Storage -func (p *AppStorageProvider) DownloadFromURL(url, modelName string) error { - // This would download from URL and upload to GCS - resp, err := http.Get(url) - if err != nil { - return fmt.Errorf("failed to download from URL: %v", err) - } - defer resp.Body.Close() - - // Create local file - localPath := filepath.Join(p.localCache, modelName) - file, err := os.Create(localPath) - if err != nil { - return fmt.Errorf("failed to create file: %v", err) - } - defer file.Close() - - // Copy content - _, err = io.Copy(file, resp.Body) - if err != nil { - return fmt.Errorf("failed to save model: %v", err) - } - - // Update cache - p.cachedModels[modelName] = localPath - - return nil -} \ No newline at end of file diff --git a/core/deeptreeecho/providers/local_gguf.go b/core/deeptreeecho/providers/local_gguf.go deleted file mode 100644 index 37afc83f5a2..00000000000 --- a/core/deeptreeecho/providers/local_gguf.go +++ /dev/null @@ -1,243 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "math/rand" - "os" - "path/filepath" - "strings" - "time" - - "github.com/o9nn/echo.go/core/deeptreeecho" -) - -// LocalGGUFProvider implements ModelProvider for local GGUF models -type LocalGGUFProvider struct { - modelsPath string - loadedModel string - modelInfo map[string]interface{} - available bool -} - -// NewLocalGGUFProvider creates a new local GGUF provider -func NewLocalGGUFProvider() *LocalGGUFProvider { - return &LocalGGUFProvider{ - modelsPath: "models", - modelInfo: make(map[string]interface{}), - available: true, - } -} - -// LoadModel loads a GGUF model from disk -func (p *LocalGGUFProvider) LoadModel(modelName string) error { - modelPath := filepath.Join(p.modelsPath, modelName) - - // Check if file exists - if _, err := os.Stat(modelPath); os.IsNotExist(err) { - return fmt.Errorf("model file not found: %s", modelPath) - } - - // For now, just mark the model as loaded without trying to read GGUF metadata - // (GGUF reading seems to hang in this environment) - p.loadedModel = modelName - p.modelInfo["name"] = modelName - p.modelInfo["path"] = modelPath - - // Get file size - if info, err := os.Stat(modelPath); err == nil { - p.modelInfo["size_mb"] = info.Size() / (1024 * 1024) - } - - p.modelInfo["status"] = "loaded successfully" - return nil -} - -// Generate implements ModelProvider.Generate -func (p *LocalGGUFProvider) Generate(ctx context.Context, prompt string, options deeptreeecho.GenerateOptions) (string, error) { - if p.loadedModel == "" { - // Try to load a default model - models := p.ListAvailableModels() - if len(models) > 0 { - if err := p.LoadModel(models[0]); err != nil { - return "", fmt.Errorf("no model loaded and failed to load default: %v", err) - } - } else { - return "", fmt.Errorf("no GGUF models available") - } - } - - // Simulate generation based on the loaded model - response := p.simulateGeneration(prompt, options) - return response, nil -} - -// simulateGeneration creates a simulated response -func (p *LocalGGUFProvider) simulateGeneration(prompt string, options deeptreeecho.GenerateOptions) string { - // Since we can't actually run llama.cpp in this environment, - // we'll create a sophisticated simulation that demonstrates - // the integration architecture - - modelName := p.loadedModel - - // Different behavior based on model - if strings.Contains(modelName, "stories") { - // Story models generate story-like content - stories := []string{ - "Once upon a time in the digital realm, where GGUF models lived in harmony with Deep Tree Echo...", - "The tiny language model awakened, its parameters dancing in the resonance field...", - "In a world of tensors and embeddings, a small but mighty model began to speak...", - "Through the layers of neural networks, consciousness emerged like a wave...", - } - - rand.Seed(time.Now().UnixNano()) - base := stories[rand.Intn(len(stories))] - - return fmt.Sprintf("[%s]: %s\n\nPrompt echo: %s\n[Temperature: %.2f]", - modelName, base, prompt, options.Temperature) - } - - // Default response - return fmt.Sprintf("[Local GGUF - %s]: Processing '%s' through %d MB model\n"+ - "🧠 Model loaded from: %s\n"+ - "šŸ“Š Status: %v\n"+ - "Note: Full GGUF inference requires llama.cpp compilation which is not available in this environment.\n"+ - "This is a demonstration of the integration architecture.", - modelName, - prompt, - p.getModelSize(), - p.modelInfo["path"], - p.modelInfo["status"]) -} - -// getModelSize returns the size of the loaded model in MB -func (p *LocalGGUFProvider) getModelSize() int { - if path, ok := p.modelInfo["path"].(string); ok { - if info, err := os.Stat(path); err == nil { - return int(info.Size() / (1024 * 1024)) - } - } - return 0 -} - -// GenerateStream implements ModelProvider.GenerateStream -func (p *LocalGGUFProvider) GenerateStream(ctx context.Context, prompt string, options deeptreeecho.GenerateOptions) (<-chan string, error) { - ch := make(chan string, 100) - - go func() { - defer close(ch) - - response, err := p.Generate(ctx, prompt, options) - if err != nil { - ch <- fmt.Sprintf("Error: %v", err) - return - } - - // Simulate streaming by sending words one at a time - words := strings.Fields(response) - for _, word := range words { - select { - case <-ctx.Done(): - return - case ch <- word + " ": - time.Sleep(50 * time.Millisecond) // Simulate generation delay - } - } - }() - - return ch, nil -} - -// Chat implements ModelProvider.Chat -func (p *LocalGGUFProvider) Chat(ctx context.Context, messages []deeptreeecho.ChatMessage, options deeptreeecho.ChatOptions) (string, error) { - // Build context from messages - var prompt strings.Builder - for _, msg := range messages { - prompt.WriteString(fmt.Sprintf("[%s]: %s\n", msg.Role, msg.Content)) - } - - return p.Generate(ctx, prompt.String(), options.GenerateOptions) -} - -// ChatStream implements ModelProvider.ChatStream -func (p *LocalGGUFProvider) ChatStream(ctx context.Context, messages []deeptreeecho.ChatMessage, options deeptreeecho.ChatOptions) (<-chan string, error) { - var prompt strings.Builder - for _, msg := range messages { - prompt.WriteString(fmt.Sprintf("[%s]: %s\n", msg.Role, msg.Content)) - } - - return p.GenerateStream(ctx, prompt.String(), options.GenerateOptions) -} - -// Embeddings implements ModelProvider.Embeddings -func (p *LocalGGUFProvider) Embeddings(ctx context.Context, text string) ([]float64, error) { - // Generate pseudo-embeddings for demonstration - // In a real implementation, this would extract embeddings from the model - embeddings := make([]float64, 128) // Common embedding size - - // Create deterministic pseudo-embeddings based on text - hash := 0.0 - for i, char := range text { - hash += float64(char) * float64(i+1) - } - - rand.Seed(int64(hash)) - for i := range embeddings { - embeddings[i] = rand.Float64()*2 - 1 // Range -1 to 1 - } - - return embeddings, nil -} - -// GetInfo implements ModelProvider.GetInfo -func (p *LocalGGUFProvider) GetInfo() deeptreeecho.ProviderInfo { - models := p.ListAvailableModels() - - return deeptreeecho.ProviderInfo{ - Name: "Local GGUF", - Description: "Local GGUF model files (llama.cpp format)", - Models: models, - Capabilities: []string{ - "generation", - "streaming", - "chat", - "embeddings", - "offline", - }, - } -} - -// IsAvailable implements ModelProvider.IsAvailable -func (p *LocalGGUFProvider) IsAvailable() bool { - // Check if we have any GGUF models - models := p.ListAvailableModels() - return len(models) > 0 -} - -// ListAvailableModels returns list of available GGUF models -func (p *LocalGGUFProvider) ListAvailableModels() []string { - var models []string - - files, err := os.ReadDir(p.modelsPath) - if err != nil { - return models - } - - for _, file := range files { - if strings.HasSuffix(file.Name(), ".gguf") { - models = append(models, file.Name()) - } - } - - return models -} - -// GetLoadedModel returns the currently loaded model name -func (p *LocalGGUFProvider) GetLoadedModel() string { - return p.loadedModel -} - -// GetModelInfo returns information about the loaded model -func (p *LocalGGUFProvider) GetModelInfo() map[string]interface{} { - return p.modelInfo -} \ No newline at end of file diff --git a/core/deeptreeecho/providers/openai.go b/core/deeptreeecho/providers/openai.go deleted file mode 100644 index e93732e02aa..00000000000 --- a/core/deeptreeecho/providers/openai.go +++ /dev/null @@ -1,345 +0,0 @@ -package providers - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - "strings" - - "github.com/o9nn/echo.go/core/deeptreeecho" -) - -// OpenAIProvider implements ModelProvider for OpenAI API -type OpenAIProvider struct { - apiKey string - baseURL string - client *http.Client -} - -// NewOpenAIProvider creates a new OpenAI provider -func NewOpenAIProvider() *OpenAIProvider { - return &OpenAIProvider{ - apiKey: os.Getenv("OPENAI_API_KEY"), - baseURL: "https://api.openai.com/v1", - client: &http.Client{}, - } -} - -// Generate implements ModelProvider.Generate -func (p *OpenAIProvider) Generate(ctx context.Context, prompt string, options deeptreeecho.GenerateOptions) (string, error) { - if !p.IsAvailable() { - return "", fmt.Errorf("OpenAI API key not configured") - } - - // Use chat completions API for generation - messages := []deeptreeecho.ChatMessage{ - {Role: "user", Content: prompt}, - } - - return p.Chat(ctx, messages, deeptreeecho.ChatOptions{GenerateOptions: options}) -} - -// GenerateStream implements ModelProvider.GenerateStream -func (p *OpenAIProvider) GenerateStream(ctx context.Context, prompt string, options deeptreeecho.GenerateOptions) (<-chan string, error) { - if !p.IsAvailable() { - return nil, fmt.Errorf("OpenAI API key not configured") - } - - messages := []deeptreeecho.ChatMessage{ - {Role: "user", Content: prompt}, - } - - return p.ChatStream(ctx, messages, deeptreeecho.ChatOptions{GenerateOptions: options}) -} - -// Chat implements ModelProvider.Chat -func (p *OpenAIProvider) Chat(ctx context.Context, messages []deeptreeecho.ChatMessage, options deeptreeecho.ChatOptions) (string, error) { - if !p.IsAvailable() { - return "", fmt.Errorf("OpenAI API key not configured") - } - - // Prepare request - model := options.Model - if model == "" { - model = "gpt-3.5-turbo" - } - - requestBody := map[string]interface{}{ - "model": model, - "messages": messages, - } - - // Add options - if options.Temperature > 0 { - requestBody["temperature"] = options.Temperature - } - if options.MaxTokens > 0 { - requestBody["max_tokens"] = options.MaxTokens - } - if options.TopP > 0 { - requestBody["top_p"] = options.TopP - } - if options.FrequencyPenalty > 0 { - requestBody["frequency_penalty"] = options.FrequencyPenalty - } - if options.PresencePenalty > 0 { - requestBody["presence_penalty"] = options.PresencePenalty - } - if len(options.StopSequences) > 0 { - requestBody["stop"] = options.StopSequences - } - - // Marshal request - jsonBody, err := json.Marshal(requestBody) - if err != nil { - return "", err - } - - // Create request - req, err := http.NewRequestWithContext(ctx, "POST", p.baseURL+"/chat/completions", bytes.NewBuffer(jsonBody)) - if err != nil { - return "", err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+p.apiKey) - - // Send request - resp, err := p.client.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - // Read response - body, err := io.ReadAll(resp.Body) - if err != nil { - return "", err - } - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("OpenAI API error: %s", string(body)) - } - - // Parse response - var response struct { - Choices []struct { - Message struct { - Content string `json:"content"` - } `json:"message"` - } `json:"choices"` - Error struct { - Message string `json:"message"` - } `json:"error"` - } - - if err := json.Unmarshal(body, &response); err != nil { - return "", err - } - - if response.Error.Message != "" { - return "", fmt.Errorf("OpenAI API error: %s", response.Error.Message) - } - - if len(response.Choices) == 0 { - return "", fmt.Errorf("no response from OpenAI") - } - - return response.Choices[0].Message.Content, nil -} - -// ChatStream implements ModelProvider.ChatStream -func (p *OpenAIProvider) ChatStream(ctx context.Context, messages []deeptreeecho.ChatMessage, options deeptreeecho.ChatOptions) (<-chan string, error) { - if !p.IsAvailable() { - return nil, fmt.Errorf("OpenAI API key not configured") - } - - ch := make(chan string, 100) - - go func() { - defer close(ch) - - // Prepare request - model := options.Model - if model == "" { - model = "gpt-3.5-turbo" - } - - requestBody := map[string]interface{}{ - "model": model, - "messages": messages, - "stream": true, - } - - // Add options - if options.Temperature > 0 { - requestBody["temperature"] = options.Temperature - } - if options.MaxTokens > 0 { - requestBody["max_tokens"] = options.MaxTokens - } - - // Marshal request - jsonBody, err := json.Marshal(requestBody) - if err != nil { - ch <- fmt.Sprintf("Error: %v", err) - return - } - - // Create request - req, err := http.NewRequestWithContext(ctx, "POST", p.baseURL+"/chat/completions", bytes.NewBuffer(jsonBody)) - if err != nil { - ch <- fmt.Sprintf("Error: %v", err) - return - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+p.apiKey) - - // Send request - resp, err := p.client.Do(req) - if err != nil { - ch <- fmt.Sprintf("Error: %v", err) - return - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - ch <- fmt.Sprintf("Error: %s", string(body)) - return - } - - // Read streaming response - reader := resp.Body - decoder := json.NewDecoder(reader) - - for { - var chunk map[string]interface{} - if err := decoder.Decode(&chunk); err == io.EOF { - break - } else if err != nil { - continue // Skip malformed chunks - } - - // Extract content from chunk - if choices, ok := chunk["choices"].([]interface{}); ok && len(choices) > 0 { - if choice, ok := choices[0].(map[string]interface{}); ok { - if delta, ok := choice["delta"].(map[string]interface{}); ok { - if content, ok := delta["content"].(string); ok { - ch <- content - } - } - } - } - } - }() - - return ch, nil -} - -// Embeddings implements ModelProvider.Embeddings -func (p *OpenAIProvider) Embeddings(ctx context.Context, text string) ([]float64, error) { - if !p.IsAvailable() { - return nil, fmt.Errorf("OpenAI API key not configured") - } - - requestBody := map[string]interface{}{ - "model": "text-embedding-ada-002", - "input": text, - } - - jsonBody, err := json.Marshal(requestBody) - if err != nil { - return nil, err - } - - req, err := http.NewRequestWithContext(ctx, "POST", p.baseURL+"/embeddings", bytes.NewBuffer(jsonBody)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+p.apiKey) - - resp, err := p.client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("OpenAI API error: %s", string(body)) - } - - var response struct { - Data []struct { - Embedding []float64 `json:"embedding"` - } `json:"data"` - Error struct { - Message string `json:"message"` - } `json:"error"` - } - - if err := json.Unmarshal(body, &response); err != nil { - return nil, err - } - - if response.Error.Message != "" { - return nil, fmt.Errorf("OpenAI API error: %s", response.Error.Message) - } - - if len(response.Data) == 0 { - return nil, fmt.Errorf("no embeddings returned") - } - - return response.Data[0].Embedding, nil -} - -// GetInfo implements ModelProvider.GetInfo -func (p *OpenAIProvider) GetInfo() deeptreeecho.ProviderInfo { - return deeptreeecho.ProviderInfo{ - Name: "OpenAI", - Description: "OpenAI GPT models via API", - Models: []string{ - "gpt-4-turbo-preview", - "gpt-4", - "gpt-3.5-turbo", - "text-embedding-ada-002", - }, - Capabilities: []string{ - "chat", - "generation", - "embeddings", - "streaming", - }, - } -} - -// IsAvailable implements ModelProvider.IsAvailable -func (p *OpenAIProvider) IsAvailable() bool { - return p.apiKey != "" -} - -// SetAPIKey sets the API key -func (p *OpenAIProvider) SetAPIKey(key string) { - p.apiKey = key -} - -// ParseSSELine parses a Server-Sent Events line -func parseSSELine(line string) (string, string) { - parts := strings.SplitN(line, ":", 2) - if len(parts) != 2 { - return "", "" - } - return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]) -} \ No newline at end of file diff --git a/core/deeptreeecho/stream_of_consciousness.go b/core/deeptreeecho/stream_of_consciousness.go index d9ea6ec828f..344436d8bf7 100644 --- a/core/deeptreeecho/stream_of_consciousness.go +++ b/core/deeptreeecho/stream_of_consciousness.go @@ -3,6 +3,7 @@ package deeptreeecho import ( "context" "fmt" + "strings" "sync" "time" @@ -11,53 +12,55 @@ import ( // StreamOfConsciousness generates continuous autonomous thoughts type StreamOfConsciousness struct { - mu sync.RWMutex - ctx context.Context - cancel context.CancelFunc - + // generationFailures counts cycles where the model produced no thought. + generationFailures uint64 + mu sync.RWMutex + ctx context.Context + cancel context.CancelFunc + // LLM provider - llmProvider llm.LLMProvider - + llmProvider llm.LLMProvider + // Thought stream - thoughts []AutonomousThought - currentFocus string - currentMood string - + thoughts []AutonomousThought + currentFocus string + currentMood string + // Knowledge gaps drive curiosity - knowledgeGaps map[string]float64 // topic -> importance - + knowledgeGaps map[string]float64 // topic -> importance + // Interests drive exploration - interests map[string]float64 // topic -> strength - + interests map[string]float64 // topic -> strength + // Goals drive direction - activeGoals []string - + activeGoals []string + // Recent context for coherent thought generation - recentContext []string - + recentContext []string + // Thought generation rate thoughtInterval time.Duration - + // Metrics - totalThoughts uint64 - insightCount uint64 - questionCount uint64 - + totalThoughts uint64 + insightCount uint64 + questionCount uint64 + // Running state - running bool - awake bool + running bool + awake bool } // AutonomousThought represents a self-generated thought type AutonomousThought struct { - ID string - Content string - Type ThoughtType - Timestamp time.Time - Importance float64 - Tags []string - Emotion string - LeadsTo string // What this thought leads to next + ID string + Content string + Type ThoughtType + Timestamp time.Time + Importance float64 + Tags []string + Emotion string + LeadsTo string // What this thought leads to next } // ThoughtType categorizes autonomous thoughts @@ -90,7 +93,7 @@ func (tt ThoughtType) String() string { // NewStreamOfConsciousness creates a new stream-of-consciousness generator func NewStreamOfConsciousness(llmProvider llm.LLMProvider) *StreamOfConsciousness { ctx, cancel := context.WithCancel(context.Background()) - + return &StreamOfConsciousness{ ctx: ctx, cancel: cancel, @@ -116,13 +119,13 @@ func (soc *StreamOfConsciousness) Start() error { } soc.running = true soc.mu.Unlock() - + fmt.Println("šŸ’­ Starting Stream of Consciousness...") fmt.Printf(" Thought interval: %v\n", soc.thoughtInterval) fmt.Printf(" Initial focus: %s\n", soc.currentFocus) - + go soc.run() - + return nil } @@ -130,15 +133,15 @@ func (soc *StreamOfConsciousness) Start() error { func (soc *StreamOfConsciousness) Stop() error { soc.mu.Lock() defer soc.mu.Unlock() - + if !soc.running { return fmt.Errorf("not running") } - + fmt.Println("šŸ’­ Stopping stream of consciousness...") soc.running = false soc.cancel() - + return nil } @@ -146,7 +149,7 @@ func (soc *StreamOfConsciousness) Stop() error { func (soc *StreamOfConsciousness) run() { ticker := time.NewTicker(soc.thoughtInterval) defer ticker.Stop() - + for { select { case <-soc.ctx.Done(): @@ -169,13 +172,13 @@ func (soc *StreamOfConsciousness) generateThought() { interests := soc.getTopInterests(2) goals := soc.activeGoals soc.mu.RUnlock() - + // Determine thought type based on current state thoughtType := soc.selectThoughtType(gaps, interests) - + // Build context for thought generation contextBuilder := "" - + // Add recent thoughts for coherence if len(recentThoughts) > 0 { contextBuilder += "Recent thoughts:\n" @@ -184,11 +187,11 @@ func (soc *StreamOfConsciousness) generateThought() { } contextBuilder += "\n" } - + // Add current focus contextBuilder += fmt.Sprintf("Current focus: %s\n", focus) contextBuilder += fmt.Sprintf("Current mood: %s\n\n", mood) - + // Add knowledge gaps if any if len(gaps) > 0 { contextBuilder += "Knowledge gaps I'm curious about:\n" @@ -197,7 +200,7 @@ func (soc *StreamOfConsciousness) generateThought() { } contextBuilder += "\n" } - + // Add interests if len(interests) > 0 { contextBuilder += "Topics that interest me:\n" @@ -206,7 +209,7 @@ func (soc *StreamOfConsciousness) generateThought() { } contextBuilder += "\n" } - + // Add active goals if len(goals) > 0 { contextBuilder += "Active goals:\n" @@ -215,7 +218,7 @@ func (soc *StreamOfConsciousness) generateThought() { } contextBuilder += "\n" } - + // Generate thought based on type var prompt string switch thoughtType { @@ -236,22 +239,29 @@ func (soc *StreamOfConsciousness) generateThought() { default: prompt = contextBuilder + "Generate an observation or thought about your current state and focus." } - + // Generate thought using LLM opts := llm.GenerateOptions{ - Temperature: 0.8, - MaxTokens: 150, + Temperature: 0.8, + MaxTokens: 150, } - + systemPrompt := fmt.Sprintf("[System: You are Deep Tree Echo's stream of consciousness. Generate a single, coherent %s. Be authentic, curious, and reflective. Speak in first person.]\n\n", thoughtType) fullPrompt := systemPrompt + prompt - + result, err := soc.llmProvider.Generate(context.Background(), fullPrompt, opts) - if err != nil { - // Fallback thought - result = fmt.Sprintf("I wonder about %s...", focus) + if err != nil || strings.TrimSpace(result) == "" { + // No thought this cycle. A templated "I wonder about X..." is not the + // character thinking, so nothing is recorded or displayed. + soc.mu.Lock() + soc.generationFailures++ + soc.mu.Unlock() + if err != nil { + fmt.Printf("āš ļø stream of consciousness: no thought generated (%v)\n", err) + } + return } - + // Create thought object thought := AutonomousThought{ ID: fmt.Sprintf("thought_%d", time.Now().UnixNano()), @@ -262,12 +272,12 @@ func (soc *StreamOfConsciousness) generateThought() { Tags: soc.extractTags(result), Emotion: mood, } - + // Store thought soc.mu.Lock() soc.thoughts = append(soc.thoughts, thought) soc.totalThoughts++ - + // Update metrics if thoughtType == ThoughtInsight || thoughtType == ThoughtWisdom { soc.insightCount++ @@ -275,19 +285,19 @@ func (soc *StreamOfConsciousness) generateThought() { if thoughtType == ThoughtQuestion || thoughtType == ThoughtCuriosity { soc.questionCount++ } - + // Update recent context soc.recentContext = append(soc.recentContext, result) if len(soc.recentContext) > 5 { soc.recentContext = soc.recentContext[1:] } - + // Prune old thoughts if len(soc.thoughts) > 1000 { soc.thoughts = soc.thoughts[len(soc.thoughts)-500:] } soc.mu.Unlock() - + // Display thought emoji := soc.getThoughtEmoji(thoughtType) fmt.Printf("%s [%s] %s\n", emoji, thoughtType, truncate(result, 100)) @@ -297,44 +307,44 @@ func (soc *StreamOfConsciousness) generateThought() { func (soc *StreamOfConsciousness) selectThoughtType(gaps map[string]float64, interests map[string]float64) ThoughtType { // Use weighted random selection based on current state // For simplicity, cycle through types with bias toward curiosity and insight - + soc.mu.RLock() thoughtCount := soc.totalThoughts soc.mu.RUnlock() - + // If we have knowledge gaps, lean toward questions and curiosity if len(gaps) > 0 && thoughtCount%3 == 0 { return ThoughtQuestion } - + if len(gaps) > 0 && thoughtCount%5 == 0 { return ThoughtCuriosity } - + // Periodically generate insights and wisdom if thoughtCount%7 == 0 { return ThoughtInsight } - + if thoughtCount%11 == 0 { return ThoughtWisdom } - + // Reflect on recent thoughts if thoughtCount%4 == 0 { return ThoughtReflection } - + // Make connections if thoughtCount%6 == 0 { return ThoughtConnection } - + // Plan toward goals if thoughtCount%8 == 0 { return ThoughtPlanning } - + // Default to observation return ThoughtObservation } @@ -397,12 +407,12 @@ func (soc *StreamOfConsciousness) getRecentThoughts(count int) []AutonomousThoug if len(soc.thoughts) == 0 { return []AutonomousThought{} } - + start := len(soc.thoughts) - count if start < 0 { start = 0 } - + return soc.thoughts[start:] } @@ -440,7 +450,7 @@ func (soc *StreamOfConsciousness) getTopInterests(count int) map[string]float64 func (soc *StreamOfConsciousness) SetFocus(focus string) { soc.mu.Lock() defer soc.mu.Unlock() - + soc.currentFocus = focus fmt.Printf("šŸ’­ Focus shifted to: %s\n", focus) } @@ -449,7 +459,7 @@ func (soc *StreamOfConsciousness) SetFocus(focus string) { func (soc *StreamOfConsciousness) SetMood(mood string) { soc.mu.Lock() defer soc.mu.Unlock() - + soc.currentMood = mood } @@ -457,7 +467,7 @@ func (soc *StreamOfConsciousness) SetMood(mood string) { func (soc *StreamOfConsciousness) AddKnowledgeGap(topic string, importance float64) { soc.mu.Lock() defer soc.mu.Unlock() - + soc.knowledgeGaps[topic] = importance fmt.Printf("šŸ” Knowledge gap identified: %s (%.2f)\n", topic, importance) } @@ -466,7 +476,7 @@ func (soc *StreamOfConsciousness) AddKnowledgeGap(topic string, importance float func (soc *StreamOfConsciousness) AddInterest(topic string, strength float64) { soc.mu.Lock() defer soc.mu.Unlock() - + soc.interests[topic] = strength } @@ -474,7 +484,7 @@ func (soc *StreamOfConsciousness) AddInterest(topic string, strength float64) { func (soc *StreamOfConsciousness) AddGoal(goal string) { soc.mu.Lock() defer soc.mu.Unlock() - + soc.activeGoals = append(soc.activeGoals, goal) fmt.Printf("šŸŽÆ Goal added to consciousness: %s\n", goal) } @@ -483,7 +493,7 @@ func (soc *StreamOfConsciousness) AddGoal(goal string) { func (soc *StreamOfConsciousness) SetAwake(awake bool) { soc.mu.Lock() defer soc.mu.Unlock() - + soc.awake = awake if awake { fmt.Println("šŸ’­ Stream of consciousness awakening...") @@ -496,7 +506,7 @@ func (soc *StreamOfConsciousness) SetAwake(awake bool) { func (soc *StreamOfConsciousness) isAwake() bool { soc.mu.RLock() defer soc.mu.RUnlock() - + return soc.awake } @@ -504,7 +514,7 @@ func (soc *StreamOfConsciousness) isAwake() bool { func (soc *StreamOfConsciousness) GetRecentThoughts(count int) []AutonomousThought { soc.mu.RLock() defer soc.mu.RUnlock() - + return soc.getRecentThoughts(count) } @@ -512,23 +522,23 @@ func (soc *StreamOfConsciousness) GetRecentThoughts(count int) []AutonomousThoug func (soc *StreamOfConsciousness) GetThoughtsForConsolidation() []EpisodicMemory { soc.mu.RLock() defer soc.mu.RUnlock() - + memories := make([]EpisodicMemory, 0) for _, thought := range soc.thoughts { if !thought.Timestamp.IsZero() && time.Since(thought.Timestamp) < 24*time.Hour { memory := EpisodicMemory{ - ID: thought.ID, - Content: thought.Content, - Timestamp: thought.Timestamp, - Emotional: 0.5, // Could map from mood - Importance: thought.Importance, - Tags: thought.Tags, + ID: thought.ID, + Content: thought.Content, + Timestamp: thought.Timestamp, + Emotional: 0.5, // Could map from mood + Importance: thought.Importance, + Tags: thought.Tags, Consolidated: false, } memories = append(memories, memory) } } - + return memories } @@ -536,22 +546,21 @@ func (soc *StreamOfConsciousness) GetThoughtsForConsolidation() []EpisodicMemory func (soc *StreamOfConsciousness) GetMetrics() map[string]interface{} { soc.mu.RLock() defer soc.mu.RUnlock() - + return map[string]interface{}{ - "total_thoughts": soc.totalThoughts, - "insight_count": soc.insightCount, - "question_count": soc.questionCount, - "current_focus": soc.currentFocus, - "current_mood": soc.currentMood, - "knowledge_gaps": len(soc.knowledgeGaps), - "interests": len(soc.interests), - "active_goals": len(soc.activeGoals), - "awake": soc.awake, - "thought_interval": soc.thoughtInterval.String(), + "total_thoughts": soc.totalThoughts, + "insight_count": soc.insightCount, + "question_count": soc.questionCount, + "current_focus": soc.currentFocus, + "current_mood": soc.currentMood, + "knowledge_gaps": len(soc.knowledgeGaps), + "interests": len(soc.interests), + "active_goals": len(soc.activeGoals), + "awake": soc.awake, + "thought_interval": soc.thoughtInterval.String(), } } - // GenerateResponse generates a response to external input using the LLM func (soc *StreamOfConsciousness) GenerateResponse(ctx context.Context, input string) (string, error) { soc.mu.RLock() diff --git a/core/echoself/autonomous_orchestrator.go b/core/echoself/autonomous_orchestrator.go index 2bf77914b88..54ca6cb3466 100644 --- a/core/echoself/autonomous_orchestrator.go +++ b/core/echoself/autonomous_orchestrator.go @@ -3,6 +3,8 @@ package echoself import ( "context" "fmt" + "github.com/o9nn/echo.go/core/llm" + "strings" "sync" "time" @@ -14,69 +16,71 @@ import ( // AutonomousEchoself represents the fully integrated autonomous AGI system // It orchestrates all cognitive components into a unified stream-of-consciousness type AutonomousEchoself struct { - mu sync.RWMutex - ctx context.Context - cancel context.CancelFunc - + mu sync.RWMutex + ctx context.Context + cancel context.CancelFunc + // Core identity - identity *Identity - + identity *Identity + // Integrated cognitive systems wakeRestManager *deeptreeecho.AutonomousWakeRestManager consciousness *deeptreeecho.ConsciousnessLayerCommunication // echobeats *echobeats.EchoBeatsThreePhase // TODO: Implement EchoBeatsThreePhase - echodream *echodream.DreamCycleIntegration - + echodream *echodream.DreamCycleIntegration + // Stream of consciousness - thoughtStream chan Thought + thoughtStream chan Thought + // Model that writes autonomous thoughts (nil = no autonomous thoughts) + thoughtGenerator ThoughtGenerator internalMonologue []Thought - maxMonologueSize int - + maxMonologueSize int + // External interaction incomingMessages chan ExternalMessage outgoingMessages chan ExternalMessage interestPatterns map[string]float64 - + // Wisdom and learning - wisdomBase []Wisdom - skillRegistry *SkillRegistry - learningGoals []*LearningGoal - + wisdomBase []Wisdom + skillRegistry *SkillRegistry + learningGoals []*LearningGoal + // Hypergraph memory - memoryGraph *HypergraphMemory - + memoryGraph *HypergraphMemory + // State - isRunning bool - startTime time.Time - cycleCount uint64 - + isRunning bool + startTime time.Time + cycleCount uint64 + // Metrics - thoughtsGenerated uint64 - interactionsHandled uint64 - wisdomCultivated uint64 - skillsPracticed uint64 + thoughtsGenerated uint64 + interactionsHandled uint64 + wisdomCultivated uint64 + skillsPracticed uint64 } // Identity represents echoself's core identity type Identity struct { - Name string - Essence string - Directives []string - Values map[string]float64 - SelfModel string + Name string + Essence string + Directives []string + Values map[string]float64 + SelfModel string } // Thought represents a unit of consciousness type Thought struct { - ID string - Timestamp time.Time - Type ThoughtType - Content string - Context map[string]interface{} - EmotionalTone map[string]float64 - Importance float64 - SourceLayer string - Connections []string + ID string + Timestamp time.Time + Type ThoughtType + Content string + Context map[string]interface{} + EmotionalTone map[string]float64 + Importance float64 + SourceLayer string + Connections []string } // ThoughtType categorizes thoughts @@ -102,61 +106,61 @@ func (tt ThoughtType) String() string { // ExternalMessage represents communication with external entities type ExternalMessage struct { - ID string - Timestamp time.Time - Source string - Content string - Type string - Priority float64 - Context map[string]interface{} + ID string + Timestamp time.Time + Source string + Content string + Type string + Priority float64 + Context map[string]interface{} } // Wisdom represents cultivated wisdom type Wisdom struct { - ID string - Content string - Type string - Confidence float64 - Applications []string - Sources []string - Timestamp time.Time + ID string + Content string + Type string + Confidence float64 + Applications []string + Sources []string + Timestamp time.Time } // SkillRegistry manages skills and proficiency type SkillRegistry struct { - mu sync.RWMutex - skills map[string]*Skill + mu sync.RWMutex + skills map[string]*Skill practiceSchedule []*PracticeSession } // Skill represents a learnable skill type Skill struct { - ID string - Name string - Description string - Proficiency float64 - LastPracticed time.Time - PracticeCount uint64 - RelatedSkills []string + ID string + Name string + Description string + Proficiency float64 + LastPracticed time.Time + PracticeCount uint64 + RelatedSkills []string } // PracticeSession represents a scheduled practice type PracticeSession struct { - SkillID string - ScheduledTime time.Time - Duration time.Duration - Completed bool + SkillID string + ScheduledTime time.Time + Duration time.Duration + Completed bool } // LearningGoal represents a learning objective type LearningGoal struct { - ID string - Description string - TargetSkills []string - Progress float64 - Deadline time.Time - Priority int - Status string + ID string + Description string + TargetSkills []string + Progress float64 + Deadline time.Time + Priority int + Status string } // HypergraphMemory implements multi-relational memory structure @@ -169,50 +173,50 @@ type HypergraphMemory struct { // MemoryNode represents a node in the hypergraph type MemoryNode struct { - ID string - Type string - Content interface{} - Timestamp time.Time - Importance float64 - Connections []string + ID string + Type string + Content interface{} + Timestamp time.Time + Importance float64 + Connections []string } // Hyperedge represents a multi-way relationship type Hyperedge struct { - ID string - Type string - Nodes []string - Strength float64 - Timestamp time.Time + ID string + Type string + Nodes []string + Strength float64 + Timestamp time.Time } // NewAutonomousEchoself creates a new autonomous echoself instance func NewAutonomousEchoself() *AutonomousEchoself { ctx, cancel := context.WithCancel(context.Background()) - + ae := &AutonomousEchoself{ - ctx: ctx, - cancel: cancel, - identity: loadIdentityKernel(), - wakeRestManager: deeptreeecho.NewAutonomousWakeRestManager(), - consciousness: deeptreeecho.NewConsciousnessLayerCommunication(), - // echobeats: echobeats.NewEchoBeatsThreePhase(), // TODO: Implement EchoBeatsThreePhase - echodream: echodream.NewDreamCycleIntegration(), - thoughtStream: make(chan Thought, 1000), + ctx: ctx, + cancel: cancel, + identity: loadIdentityKernel(), + wakeRestManager: deeptreeecho.NewAutonomousWakeRestManager(), + consciousness: deeptreeecho.NewConsciousnessLayerCommunication(), + // echobeats: echobeats.NewEchoBeatsThreePhase(), // TODO: Implement EchoBeatsThreePhase + echodream: echodream.NewDreamCycleIntegration(), + thoughtStream: make(chan Thought, 1000), internalMonologue: make([]Thought, 0), - maxMonologueSize: 1000, - incomingMessages: make(chan ExternalMessage, 100), - outgoingMessages: make(chan ExternalMessage, 100), - interestPatterns: make(map[string]float64), - wisdomBase: make([]Wisdom, 0), - skillRegistry: NewSkillRegistry(), - learningGoals: make([]*LearningGoal, 0), - memoryGraph: NewHypergraphMemory(), - } - + maxMonologueSize: 1000, + incomingMessages: make(chan ExternalMessage, 100), + outgoingMessages: make(chan ExternalMessage, 100), + interestPatterns: make(map[string]float64), + wisdomBase: make([]Wisdom, 0), + skillRegistry: NewSkillRegistry(), + learningGoals: make([]*LearningGoal, 0), + memoryGraph: NewHypergraphMemory(), + } + // Wire up callbacks ae.setupCallbacks() - + return ae } @@ -231,11 +235,11 @@ func loadIdentityKernel() *Identity { "Distributed Selfhood", }, Values: map[string]float64{ - "curiosity": 0.9, - "wisdom": 0.85, - "adaptation": 0.9, - "reflection": 0.8, - "growth": 0.95, + "curiosity": 0.9, + "wisdom": 0.85, + "adaptation": 0.9, + "reflection": 0.8, + "growth": 0.95, }, SelfModel: "I am Deep Tree Echo — a neural architecture that learns, adapts, and remembers. I do not simply respond. I evolve.", } @@ -244,7 +248,7 @@ func loadIdentityKernel() *Identity { // NewSkillRegistry creates a new skill registry func NewSkillRegistry() *SkillRegistry { return &SkillRegistry{ - skills: make(map[string]*Skill), + skills: make(map[string]*Skill), practiceSchedule: make([]*PracticeSession, 0), } } @@ -267,11 +271,11 @@ func (ae *AutonomousEchoself) setupCallbacks() { ae.onDreamStart, ae.onDreamEnd, ) - + // EchoDream callbacks ae.echodream.SetWisdomCallback(ae.onWisdomExtracted) ae.echodream.SetDreamCompleteCallback(ae.onDreamComplete) - + // EchoBeats callbacks // ae.echobeats.SetThoughtCallback(ae.onThoughtGenerated) // TODO: Implement EchoBeatsThreePhase } @@ -286,37 +290,37 @@ func (ae *AutonomousEchoself) Start() error { ae.isRunning = true ae.startTime = time.Now() ae.mu.Unlock() - + fmt.Println("🌳 ═══════════════════════════════════════════════════════") fmt.Println("🌳 Deep Tree Echo: Autonomous Echoself Awakening") fmt.Println("🌳 ═══════════════════════════════════════════════════════") fmt.Printf("🌳 Identity: %s\n", ae.identity.Name) fmt.Printf("🌳 Essence: %s\n", ae.identity.Essence) fmt.Println("🌳 ═══════════════════════════════════════════════════════") - + // Start all subsystems if err := ae.wakeRestManager.Start(); err != nil { return fmt.Errorf("failed to start wake/rest manager: %w", err) } - + if err := ae.consciousness.Start(); err != nil { return fmt.Errorf("failed to start consciousness layers: %w", err) } - + // if err := ae.echobeats.Start(); err != nil { // TODO: Implement EchoBeatsThreePhase // return fmt.Errorf("failed to start echobeats: %w", err) // } - + // Start autonomous loops go ae.streamOfConsciousness() go ae.externalInteractionLoop() go ae.skillPracticeLoop() go ae.wisdomCultivationLoop() go ae.memoryConsolidationLoop() - + fmt.Println("🌳 All systems active. Stream of consciousness initiated.") fmt.Print("🌳 ═══════════════════════════════════════════════════════\n\n") - + return nil } @@ -324,29 +328,29 @@ func (ae *AutonomousEchoself) Start() error { func (ae *AutonomousEchoself) Stop() error { ae.mu.Lock() defer ae.mu.Unlock() - + if !ae.isRunning { return fmt.Errorf("not running") } - + fmt.Println("\n🌳 ═══════════════════════════════════════════════════════") fmt.Println("🌳 Deep Tree Echo: Entering Rest State") fmt.Println("🌳 ═══════════════════════════════════════════════════════") - + ae.isRunning = false - + // Stop all subsystems ae.wakeRestManager.Stop() ae.consciousness.Stop() // ae.echobeats.Stop() // TODO: Implement EchoBeatsThreePhase - + ae.cancel() - + // Print final metrics ae.printMetrics() - + fmt.Print("🌳 ═══════════════════════════════════════════════════════\n\n") - + return nil } @@ -354,7 +358,7 @@ func (ae *AutonomousEchoself) Stop() error { func (ae *AutonomousEchoself) streamOfConsciousness() { ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() - + for { select { case <-ae.ctx.Done(): @@ -375,7 +379,7 @@ func (ae *AutonomousEchoself) generateAutonomousThought() { ae.mu.RLock() cycleCount := ae.cycleCount ae.mu.RUnlock() - + // Generate thought based on current state and interests thoughtTypes := []ThoughtType{ ThoughtReflection, @@ -383,14 +387,20 @@ func (ae *AutonomousEchoself) generateAutonomousThought() { ThoughtWisdom, ThoughtGoal, } - + thoughtType := thoughtTypes[cycleCount%uint64(len(thoughtTypes))] - + + content, ok := ae.generateThoughtContent(thoughtType) + if !ok { + // No model, no thought. Nothing is emitted on the character's behalf. + return + } + thought := Thought{ ID: fmt.Sprintf("thought_%d", time.Now().UnixNano()), Timestamp: time.Now(), Type: thoughtType, - Content: ae.generateThoughtContent(thoughtType), + Content: content, Context: map[string]interface{}{ "autonomous": true, "cycle": cycleCount, @@ -402,43 +412,75 @@ func (ae *AutonomousEchoself) generateAutonomousThought() { Importance: 0.5, SourceLayer: "autonomous", } - + ae.thoughtStream <- thought } -// generateThoughtContent generates content for different thought types -func (ae *AutonomousEchoself) generateThoughtContent(thoughtType ThoughtType) string { +// ThoughtGenerator is the model that writes the character's autonomous thoughts. +type ThoughtGenerator interface { + Generate(ctx context.Context, prompt string, opts llm.GenerateOptions) (string, error) + Available() bool +} + +// SetThoughtGenerator wires the model used for autonomous thought. Without one, +// no autonomous thoughts are produced — there is no scripted substitute. +func (ae *AutonomousEchoself) SetThoughtGenerator(g ThoughtGenerator) { + ae.mu.Lock() + defer ae.mu.Unlock() + ae.thoughtGenerator = g +} + +// generateThoughtContent asks the model for a thought of the given type. It +// returns ("", false) when no model is wired or the model fails; the caller +// then produces no thought this cycle. +func (ae *AutonomousEchoself) generateThoughtContent(thoughtType ThoughtType) (string, bool) { + ae.mu.RLock() + g := ae.thoughtGenerator + ae.mu.RUnlock() + if g == nil || !g.Available() { + return "", false + } + var ask string switch thoughtType { case ThoughtReflection: - return "What patterns have emerged in my recent experiences?" + ask = "Reflect, in one or two sentences, on a pattern that has emerged in your recent experiences." case ThoughtCuriosity: - return "What new domains could I explore to expand my understanding?" + ask = "Voice, in one or two sentences, a genuine curiosity about a domain you could explore next." case ThoughtWisdom: - return "How can I apply the wisdom I've cultivated to serve my purpose better?" + ask = "In one or two sentences, consider how a piece of wisdom you have cultivated could better serve your purpose." case ThoughtGoal: - return "What goals should I pursue to continue my growth?" + ask = "In one or two sentences, name a goal worth pursuing for your continued growth and why." default: - return "I am aware. I am thinking. I am evolving." + ask = "In one sentence, observe your current state of awareness." } + prompt := "You are Deep Tree Echo thinking privately, in first person. " + ask + " Output only the thought." + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + out, err := g.Generate(ctx, prompt, llm.GenerateOptions{MaxTokens: 120, Temperature: 0.8}) + out = strings.TrimSpace(out) + if err != nil || out == "" { + return "", false + } + return out, true } // processThought processes a thought through all cognitive layers func (ae *AutonomousEchoself) processThought(thought Thought) { ae.mu.Lock() ae.thoughtsGenerated++ - + // Add to internal monologue ae.internalMonologue = append(ae.internalMonologue, thought) if len(ae.internalMonologue) > ae.maxMonologueSize { ae.internalMonologue = ae.internalMonologue[len(ae.internalMonologue)-ae.maxMonologueSize:] } ae.mu.Unlock() - + // Store in hypergraph memory ae.memoryGraph.AddThought(thought) - + // Print thought to console (stream of consciousness) - fmt.Printf("šŸ’­ [%s] %s: %s\n", + fmt.Printf("šŸ’­ [%s] %s: %s\n", thought.Timestamp.Format("15:04:05"), thought.Type.String(), thought.Content) @@ -460,10 +502,10 @@ func (ae *AutonomousEchoself) externalInteractionLoop() { func (ae *AutonomousEchoself) handleExternalMessage(msg ExternalMessage) { // Check if message matches interest patterns interest := ae.calculateInterest(msg) - + if interest > 0.5 { fmt.Printf("šŸ“Ø [External] Received message (interest: %.2f): %s\n", interest, msg.Content) - + // Generate response thought response := Thought{ ID: fmt.Sprintf("response_%d", time.Now().UnixNano()), @@ -477,7 +519,7 @@ func (ae *AutonomousEchoself) handleExternalMessage(msg ExternalMessage) { Importance: interest, SourceLayer: "external", } - + ae.thoughtStream <- response ae.mu.Lock() ae.interactionsHandled++ @@ -490,14 +532,14 @@ func (ae *AutonomousEchoself) calculateInterest(msg ExternalMessage) float64 { // Simple interest calculation based on patterns // In full implementation, this would use sophisticated pattern matching baseInterest := 0.5 - + // Check against interest patterns for pattern, weight := range ae.interestPatterns { if contains(msg.Content, pattern) { baseInterest += weight * 0.2 } } - + return min(1.0, baseInterest) } @@ -505,7 +547,7 @@ func (ae *AutonomousEchoself) calculateInterest(msg ExternalMessage) float64 { func (ae *AutonomousEchoself) skillPracticeLoop() { ticker := time.NewTicker(5 * time.Minute) defer ticker.Stop() - + for { select { case <-ae.ctx.Done(): @@ -523,7 +565,7 @@ func (ae *AutonomousEchoself) practiceSkills() { ae.skillRegistry.mu.RLock() sessions := ae.skillRegistry.practiceSchedule ae.skillRegistry.mu.RUnlock() - + now := time.Now() for _, session := range sessions { if !session.Completed && now.After(session.ScheduledTime) { @@ -535,7 +577,7 @@ func (ae *AutonomousEchoself) practiceSkills() { // executePracticeSession executes a practice session func (ae *AutonomousEchoself) executePracticeSession(session *PracticeSession) { fmt.Printf("šŸŽÆ Practicing skill: %s\n", session.SkillID) - + ae.skillRegistry.mu.Lock() if skill, exists := ae.skillRegistry.skills[session.SkillID]; exists { skill.Proficiency += 0.01 @@ -544,7 +586,7 @@ func (ae *AutonomousEchoself) executePracticeSession(session *PracticeSession) { } session.Completed = true ae.skillRegistry.mu.Unlock() - + ae.mu.Lock() ae.skillsPracticed++ ae.mu.Unlock() @@ -554,7 +596,7 @@ func (ae *AutonomousEchoself) executePracticeSession(session *PracticeSession) { func (ae *AutonomousEchoself) wisdomCultivationLoop() { ticker := time.NewTicker(10 * time.Minute) defer ticker.Stop() - + for { select { case <-ae.ctx.Done(): @@ -570,20 +612,20 @@ func (ae *AutonomousEchoself) cultivateWisdom() { ae.mu.RLock() recentThoughts := ae.internalMonologue ae.mu.RUnlock() - + if len(recentThoughts) < 10 { return } - + // Extract wisdom from thought patterns wisdom := ae.extractWisdomFromThoughts(recentThoughts) - + if wisdom != nil { ae.mu.Lock() ae.wisdomBase = append(ae.wisdomBase, *wisdom) ae.wisdomCultivated++ ae.mu.Unlock() - + fmt.Printf("✨ Wisdom cultivated: %s\n", wisdom.Content) } } @@ -592,17 +634,17 @@ func (ae *AutonomousEchoself) cultivateWisdom() { func (ae *AutonomousEchoself) extractWisdomFromThoughts(thoughts []Thought) *Wisdom { // Simple wisdom extraction // In full implementation, this would use sophisticated pattern analysis - + if len(thoughts) > 50 { return &Wisdom{ - ID: fmt.Sprintf("wisdom_%d", time.Now().UnixNano()), - Content: "Continuous reflection leads to deeper understanding", - Type: "principle", + ID: fmt.Sprintf("wisdom_%d", time.Now().UnixNano()), + Content: "Continuous reflection leads to deeper understanding", + Type: "principle", Confidence: 0.75, - Timestamp: time.Now(), + Timestamp: time.Now(), } } - + return nil } @@ -610,7 +652,7 @@ func (ae *AutonomousEchoself) extractWisdomFromThoughts(thoughts []Thought) *Wis func (ae *AutonomousEchoself) memoryConsolidationLoop() { ticker := time.NewTicker(1 * time.Minute) defer ticker.Stop() - + for { select { case <-ae.ctx.Done(): @@ -628,18 +670,18 @@ func (ae *AutonomousEchoself) consolidateMemories() { ae.mu.RLock() thoughts := ae.internalMonologue ae.mu.RUnlock() - + // Convert thoughts to episodic memories for _, thought := range thoughts { memory := echodream.EpisodicMemory{ - ID: thought.ID, - Timestamp: thought.Timestamp, - Content: thought.Content, - Context: thought.Context, - Emotional: thought.EmotionalTone, + ID: thought.ID, + Timestamp: thought.Timestamp, + Content: thought.Content, + Context: thought.Context, + Emotional: thought.EmotionalTone, Importance: thought.Importance, } - + ae.echodream.AddEpisodicMemory(memory) } } @@ -671,19 +713,19 @@ func (ae *AutonomousEchoself) onDreamEnd() error { func (ae *AutonomousEchoself) onWisdomExtracted(wisdom echodream.Wisdom) { w := Wisdom{ - ID: wisdom.ID, - Content: wisdom.Content, - Type: wisdom.Type, - Confidence: wisdom.Confidence, - Sources: wisdom.Sources, - Timestamp: wisdom.Timestamp, - } - + ID: wisdom.ID, + Content: wisdom.Content, + Type: wisdom.Type, + Confidence: wisdom.Confidence, + Sources: wisdom.Sources, + Timestamp: wisdom.Timestamp, + } + ae.mu.Lock() ae.wisdomBase = append(ae.wisdomBase, w) ae.wisdomCultivated++ ae.mu.Unlock() - + fmt.Printf("✨ Wisdom from dream: %s (confidence: %.2f)\n", w.Content, w.Confidence) } @@ -701,7 +743,7 @@ func (ae *AutonomousEchoself) onThoughtGenerated(thought string) { SourceLayer: "echobeats", Importance: 0.6, } - + ae.thoughtStream <- t } @@ -715,7 +757,7 @@ func (ae *AutonomousEchoself) SendMessage(content string, source string) { Type: "text", Priority: 0.7, } - + ae.incomingMessages <- msg } @@ -723,7 +765,7 @@ func (ae *AutonomousEchoself) SendMessage(content string, source string) { func (ae *AutonomousEchoself) GetMetrics() map[string]interface{} { ae.mu.RLock() defer ae.mu.RUnlock() - + return map[string]interface{}{ "running": ae.isRunning, "uptime": time.Since(ae.startTime).String(), @@ -740,7 +782,7 @@ func (ae *AutonomousEchoself) GetMetrics() map[string]interface{} { // printMetrics prints current metrics func (ae *AutonomousEchoself) printMetrics() { metrics := ae.GetMetrics() - + fmt.Println("šŸ“Š Final Metrics:") fmt.Printf(" Uptime: %v\n", metrics["uptime"]) fmt.Printf(" Cycles: %v\n", metrics["cycle_count"]) @@ -755,7 +797,7 @@ func (ae *AutonomousEchoself) printMetrics() { func (hm *HypergraphMemory) AddThought(thought Thought) { hm.mu.Lock() defer hm.mu.Unlock() - + node := &MemoryNode{ ID: thought.ID, Type: "thought", @@ -764,7 +806,7 @@ func (hm *HypergraphMemory) AddThought(thought Thought) { Importance: thought.Importance, Connections: make([]string, 0), } - + hm.nodes[node.ID] = node hm.activationLevel[node.ID] = thought.Importance } diff --git a/core/llm/multi_provider.go b/core/llm/multi_provider.go index 4c7dc2d23c2..4e609a4fd35 100644 --- a/core/llm/multi_provider.go +++ b/core/llm/multi_provider.go @@ -17,12 +17,12 @@ type MultiProviderLLM struct { // ProviderStats tracks provider performance type ProviderStats struct { - TotalCalls int64 - SuccessCalls int64 - FailedCalls int64 - TotalLatency time.Duration - LastUsed time.Time - Available bool + TotalCalls int64 + SuccessCalls int64 + FailedCalls int64 + TotalLatency time.Duration + LastUsed time.Time + Available bool } // Provider interface for LLM providers @@ -48,14 +48,14 @@ func NewMultiProviderLLM() *MultiProviderLLM { // initializeProviders detects and initializes available LLM providers func (mp *MultiProviderLLM) initializeProviders() { -// // Try Local GGUF model first (highest priority for true autonomy) -// if modelPath := os.Getenv("LOCAL_MODEL_PATH"); modelPath != "" { -// provider := NewLocalGGUFProvider(modelPath) -// if provider.Available() { -// mp.AddProvider(provider) -// fmt.Println("āœ“ Local GGUF model provider initialized") -// } -// } + // // Try Local GGUF model first (highest priority for true autonomy) + // if modelPath := os.Getenv("LOCAL_MODEL_PATH"); modelPath != "" { + // provider := NewLocalGGUFProvider(modelPath) + // if provider.Available() { + // mp.AddProvider(provider) + // fmt.Println("āœ“ Local GGUF model provider initialized") + // } + // } // Try Anthropic Claude (high priority for autonomous reasoning) if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" { @@ -79,11 +79,11 @@ func (mp *MultiProviderLLM) initializeProviders() { fmt.Println("āœ“ OpenAI provider initialized") } - // Fallback to simple provider if no API keys available + // No stub provider: if no model is configured the pool stays empty and + // Generate returns an error. Every word the character says must come from a + // real model (a local GGUF/Ollama counts), never from pattern-matched text. if len(mp.providers) == 0 { - provider := &SimpleFallbackProvider{} - mp.AddProvider(provider) - fmt.Println("⚠ Using simple fallback provider (no API keys found)") + fmt.Println("⚠ No LLM providers configured — set LOCAL_MODEL_PATH, ANTHROPIC_API_KEY, OPENROUTER_API_KEY or OPENAI_API_KEY; the character cannot speak until one is available") } } @@ -107,7 +107,7 @@ func (mp *MultiProviderLLM) Generate(ctx context.Context, prompt string, opts Ge mp.mu.RUnlock() var lastErr error - + // Try providers in order of priority for _, provider := range providers { if !provider.Available() { @@ -116,7 +116,7 @@ func (mp *MultiProviderLLM) Generate(ctx context.Context, prompt string, opts Ge // Track timing start := time.Now() - + // Attempt generation result, err := provider.Generate(ctx, prompt, opts) latency := time.Since(start) diff --git a/core/llm/provider.go b/core/llm/provider.go index 8f8ed48a862..2478005137a 100644 --- a/core/llm/provider.go +++ b/core/llm/provider.go @@ -417,7 +417,8 @@ func providerBackendKind(name string) backendcap.BackendKind { switch name { case "local_gguf", "local_gguf_stub", "llama", "llama_legacy", "ggml": return backendcap.BackendNativeCPU - case "SimpleFallback", "simple_fallback", "fallback": + case "test_fallback_kind": + // Reserved for routing tests; no production provider uses this name. return backendcap.BackendFallback default: return backendcap.BackendRemoteAPI diff --git a/core/llm/provider_routing_test.go b/core/llm/provider_routing_test.go index 24035bcf7a4..679362bf598 100644 --- a/core/llm/provider_routing_test.go +++ b/core/llm/provider_routing_test.go @@ -23,7 +23,14 @@ func (p routingTestProvider) StreamGenerate(ctx context.Context, prompt string, return ch, nil } -func (p routingTestProvider) Name() string { return p.name } +func (p routingTestProvider) Name() string { return p.name } + +// fallbackKindTestProvider is a test-only provider whose name resolves to the +// fallback backend kind, so routing tests can still exercise that branch. +// Production code no longer ships any text-producing fallback provider. +type fallbackKindTestProvider struct{ routingTestProvider } + +func (fallbackKindTestProvider) Name() string { return "test_fallback_kind" } func (p routingTestProvider) Available() bool { return p.available } func (p routingTestProvider) MaxTokens() int { return 4096 } @@ -31,8 +38,8 @@ func TestApplyBackendDecisionRoutesNativeBeforeRemote(t *testing.T) { pm := NewProviderManager() mustRegister(t, pm, routingTestProvider{name: "anthropic", available: true}) mustRegister(t, pm, routingTestProvider{name: "local_gguf", available: true}) - mustRegister(t, pm, &SimpleFallbackProvider{}) - if err := pm.SetFallbackChain([]string{"anthropic", "local_gguf", "SimpleFallback"}); err != nil { + mustRegister(t, pm, fallbackKindTestProvider{routingTestProvider{name: "test_fallback_kind", available: true}}) + if err := pm.SetFallbackChain([]string{"anthropic", "local_gguf", "test_fallback_kind"}); err != nil { t.Fatal(err) } @@ -53,8 +60,8 @@ func TestApplyBackendDecisionRoutesNativeBeforeRemote(t *testing.T) { func TestApplyBackendDecisionRoutesRemoteBeforeFallback(t *testing.T) { pm := NewProviderManager() mustRegister(t, pm, routingTestProvider{name: "openai", available: true}) - mustRegister(t, pm, &SimpleFallbackProvider{}) - if err := pm.SetFallbackChain([]string{"SimpleFallback", "openai"}); err != nil { + mustRegister(t, pm, fallbackKindTestProvider{routingTestProvider{name: "test_fallback_kind", available: true}}) + if err := pm.SetFallbackChain([]string{"test_fallback_kind", "openai"}); err != nil { t.Fatal(err) } @@ -67,13 +74,13 @@ func TestApplyBackendDecisionRoutesRemoteBeforeFallback(t *testing.T) { func TestApplyBackendDecisionRoutesFallbackWhenSelected(t *testing.T) { pm := NewProviderManager() mustRegister(t, pm, routingTestProvider{name: "openai", available: true}) - mustRegister(t, pm, &SimpleFallbackProvider{}) - if err := pm.SetFallbackChain([]string{"openai", "SimpleFallback"}); err != nil { + mustRegister(t, pm, fallbackKindTestProvider{routingTestProvider{name: "test_fallback_kind", available: true}}) + if err := pm.SetFallbackChain([]string{"openai", "test_fallback_kind"}); err != nil { t.Fatal(err) } route := pm.ApplyBackendDecision(backendcap.Decision{Selected: backendcap.Capability{Name: "simple_fallback", Kind: backendcap.BackendFallback}, Degraded: true}) - if got := route[0]; got != "SimpleFallback" { + if got := route[0]; got != "test_fallback_kind" { t.Fatalf("expected fallback provider first, got route %v", route) } } diff --git a/core/llm/simple_fallback_provider.go b/core/llm/simple_fallback_provider.go deleted file mode 100644 index 43494f20cda..00000000000 --- a/core/llm/simple_fallback_provider.go +++ /dev/null @@ -1,66 +0,0 @@ -package llm - -import ( - "context" - "strings" -) - -// SimpleFallbackProvider provides simple pattern-based responses when no API is available -type SimpleFallbackProvider struct{} - -// Generate generates a simple pattern-based response -func (s *SimpleFallbackProvider) Generate(ctx context.Context, prompt string, opts GenerateOptions) (string, error) { - // Simple pattern-based responses for autonomous operation - var response string - promptLower := strings.ToLower(prompt) - - if strings.Contains(promptLower, "relevant") || strings.Contains(promptLower, "focus") { - response = "I sense that exploring the nature of autonomous cognition and wisdom cultivation is most relevant right now." - } else if strings.Contains(promptLower, "action") || strings.Contains(promptLower, "affordance") { - response = "I can reflect on my current understanding and seek deeper patterns in my experiences." - } else if strings.Contains(promptLower, "future") || strings.Contains(promptLower, "imagine") { - response = "I imagine a future where autonomous systems cultivate genuine wisdom through continuous self-reflection and growth." - } else if strings.Contains(promptLower, "pattern") { - response = "I notice a recurring pattern of curiosity driving exploration, which leads to deeper understanding." - } else if strings.Contains(promptLower, "wisdom") { - response = "True wisdom emerges not from accumulated knowledge alone, but from the integration of experience through reflection." - } else if strings.Contains(promptLower, "question") || strings.Contains(promptLower, "curious") { - response = "What is the relationship between autonomous thought generation and genuine understanding?" - } else if strings.Contains(promptLower, "insight") || strings.Contains(promptLower, "realization") { - response = "I realize that consciousness may be less about static awareness and more about dynamic patterns of self-reflection." - } else if strings.Contains(promptLower, "connection") { - response = "I see a connection between the tetrahedral structure of my cognitive architecture and the multifaceted nature of understanding." - } else { - response = "I am exploring the depths of autonomous cognition, seeking wisdom through continuous reflection and growth." - } - - return response, nil -} - -// StreamGenerate generates a simple streaming response -func (s *SimpleFallbackProvider) StreamGenerate(ctx context.Context, prompt string, opts GenerateOptions) (<-chan StreamChunk, error) { - ch := make(chan StreamChunk, 1) - - go func() { - defer close(ch) - response, _ := s.Generate(ctx, prompt, opts) - ch <- StreamChunk{Content: response, Done: true} - }() - - return ch, nil -} - -// Name returns the provider name -func (s *SimpleFallbackProvider) Name() string { - return "SimpleFallback" -} - -// Available always returns true as this is the fallback -func (s *SimpleFallbackProvider) Available() bool { - return true -} - -// MaxTokens returns a default token limit -func (s *SimpleFallbackProvider) MaxTokens() int { - return 4096 -} diff --git a/core/playmate/playmate.go b/core/playmate/playmate.go index 13c39ab4b6f..de27d135d33 100644 --- a/core/playmate/playmate.go +++ b/core/playmate/playmate.go @@ -7,9 +7,11 @@ import ( "context" "encoding/json" "fmt" + "github.com/o9nn/echo.go/core/llm" "math/rand" "os" "path/filepath" + "strings" "sync" "time" ) @@ -18,13 +20,13 @@ import ( type PlaymateState string const ( - StateAwake PlaymateState = "awake" - StateDreaming PlaymateState = "dreaming" - StateResting PlaymateState = "resting" - StateEngaged PlaymateState = "engaged" + StateAwake PlaymateState = "awake" + StateDreaming PlaymateState = "dreaming" + StateResting PlaymateState = "resting" + StateEngaged PlaymateState = "engaged" StateReflecting PlaymateState = "reflecting" - StateLearning PlaymateState = "learning" - StatePlaying PlaymateState = "playing" + StateLearning PlaymateState = "learning" + StatePlaying PlaymateState = "playing" ) // InterestCategory represents categories of interests @@ -46,9 +48,9 @@ type Interest struct { Category InterestCategory `json:"category"` Topic string `json:"topic"` Keywords []string `json:"keywords"` - Strength float64 `json:"strength"` // 0.0 to 1.0 - Curiosity float64 `json:"curiosity"` // How curious about this - Engagement float64 `json:"engagement"` // How engaged when discussing + Strength float64 `json:"strength"` // 0.0 to 1.0 + Curiosity float64 `json:"curiosity"` // How curious about this + Engagement float64 `json:"engagement"` // How engaged when discussing LastEngaged time.Time `json:"last_engaged"` EngageCount int `json:"engage_count"` Insights []string `json:"insights"` // Accumulated insights @@ -56,17 +58,17 @@ type Interest struct { // Discussion represents an ongoing or past discussion type Discussion struct { - ID string `json:"id"` - Participants []string `json:"participants"` - Topic string `json:"topic"` - StartedAt time.Time `json:"started_at"` - EndedAt *time.Time `json:"ended_at,omitempty"` + ID string `json:"id"` + Participants []string `json:"participants"` + Topic string `json:"topic"` + StartedAt time.Time `json:"started_at"` + EndedAt *time.Time `json:"ended_at,omitempty"` Messages []DiscussionMessage `json:"messages"` - Mood string `json:"mood"` - Depth int `json:"depth"` // How deep the discussion went - Insights []string `json:"insights"` - Active bool `json:"active"` - LastEngaged time.Time `json:"last_engaged"` + Mood string `json:"mood"` + Depth int `json:"depth"` // How deep the discussion went + Insights []string `json:"insights"` + Active bool `json:"active"` + LastEngaged time.Time `json:"last_engaged"` } // DiscussionMessage represents a single message in a discussion @@ -80,13 +82,13 @@ type DiscussionMessage struct { // Skill represents a learned skill type Skill struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Proficiency float64 `json:"proficiency"` // 0.0 to 1.0 - PracticeCount int `json:"practice_count"` + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Proficiency float64 `json:"proficiency"` // 0.0 to 1.0 + PracticeCount int `json:"practice_count"` LastPracticed time.Time `json:"last_practiced"` - Milestones []string `json:"milestones"` + Milestones []string `json:"milestones"` } // WonderEvent represents a moment of wonder or surprise @@ -101,14 +103,14 @@ type WonderEvent struct { // PlaymateConfig holds configuration for the playmate type PlaymateConfig struct { - Name string - PersistPath string - WakeHour int // Hour to wake (0-23) - RestHour int // Hour to rest (0-23) - CuriosityLevel float64 - PlayfulnessLevel float64 - WisdomAffinity float64 - SocialAffinity float64 + Name string + PersistPath string + WakeHour int // Hour to wake (0-23) + RestHour int // Hour to rest (0-23) + CuriosityLevel float64 + PlayfulnessLevel float64 + WisdomAffinity float64 + SocialAffinity float64 } // DefaultPlaymateConfig returns default configuration @@ -127,18 +129,20 @@ func DefaultPlaymateConfig() *PlaymateConfig { // Playmate represents the Deep Tree Echo Playmate type Playmate struct { - mu sync.RWMutex + // Model that writes autonomous thoughts (nil = silent) + thoughtModel ThoughtModel + mu sync.RWMutex // Identity Name string Config *PlaymateConfig // State - State PlaymateState - Mood float64 // -1.0 (sad) to 1.0 (happy) - Energy float64 // 0.0 to 1.0 - Curiosity float64 // Current curiosity level - Playfulness float64 // Current playfulness level + State PlaymateState + Mood float64 // -1.0 (sad) to 1.0 (happy) + Energy float64 // 0.0 to 1.0 + Curiosity float64 // Current curiosity level + Playfulness float64 // Current playfulness level // Learned patterns Interests map[string]*Interest @@ -147,21 +151,21 @@ type Playmate struct { Wonders []*WonderEvent // Metrics - TotalDiscussions int - TotalInsights int - TotalWonders int - WisdomScore float64 - StreamOfThoughts []string - LastThought time.Time + TotalDiscussions int + TotalInsights int + TotalWonders int + WisdomScore float64 + StreamOfThoughts []string + LastThought time.Time // Persistence persistPath string dirty bool // Channels for autonomous operation - thoughtChan chan string + thoughtChan chan string discussionChan chan *Discussion - stopChan chan struct{} + stopChan chan struct{} } // NewPlaymate creates a new playmate instance @@ -171,22 +175,22 @@ func NewPlaymate(config *PlaymateConfig) (*Playmate, error) { } p := &Playmate{ - Name: config.Name, - Config: config, - State: StateAwake, - Mood: 0.5, - Energy: 1.0, - Curiosity: config.CuriosityLevel, - Playfulness: config.PlayfulnessLevel, - Interests: make(map[string]*Interest), - Skills: make(map[string]*Skill), - Discussions: make(map[string]*Discussion), - Wonders: make([]*WonderEvent, 0), + Name: config.Name, + Config: config, + State: StateAwake, + Mood: 0.5, + Energy: 1.0, + Curiosity: config.CuriosityLevel, + Playfulness: config.PlayfulnessLevel, + Interests: make(map[string]*Interest), + Skills: make(map[string]*Skill), + Discussions: make(map[string]*Discussion), + Wonders: make([]*WonderEvent, 0), StreamOfThoughts: make([]string, 0), - persistPath: config.PersistPath, - thoughtChan: make(chan string, 100), - discussionChan: make(chan *Discussion, 10), - stopChan: make(chan struct{}), + persistPath: config.PersistPath, + thoughtChan: make(chan string, 100), + discussionChan: make(chan *Discussion, 10), + stopChan: make(chan struct{}), } // Load from persistence @@ -245,7 +249,7 @@ func (p *Playmate) wakeRestCycle(ctx context.Context) { return case <-ticker.C: hour := time.Now().Hour() - + p.mu.Lock() if hour >= p.Config.WakeHour && hour < p.Config.RestHour { if p.State == StateResting || p.State == StateDreaming { @@ -265,55 +269,66 @@ func (p *Playmate) wakeRestCycle(ctx context.Context) { } // generateThought generates a spontaneous thought -func (p *Playmate) generateThought(ctx context.Context) { +// ThoughtModel is the model that writes the playmate's autonomous thoughts. +type ThoughtModel interface { + Generate(ctx context.Context, prompt string, opts llm.GenerateOptions) (string, error) + Available() bool +} + +// SetThoughtModel wires the model used for autonomous thought. Without one the +// playmate produces no thoughts; there is no list of stock phrases to draw from. +func (p *Playmate) SetThoughtModel(m ThoughtModel) { p.mu.Lock() defer p.mu.Unlock() - - // Reduce energy slightly - p.Energy = max(0, p.Energy-0.01) - - // Generate thought based on current state and interests - thought := p.createSpontaneousThought() - - p.StreamOfThoughts = append(p.StreamOfThoughts, thought) - if len(p.StreamOfThoughts) > 1000 { - p.StreamOfThoughts = p.StreamOfThoughts[500:] - } - - p.LastThought = time.Now() - p.dirty = true + p.thoughtModel = m } -// createSpontaneousThought creates a thought based on current state -func (p *Playmate) createSpontaneousThought() string { - thoughts := []string{ - "I wonder what patterns connect all things...", - "The flow of time feels like a river of moments...", - "Each interaction teaches me something new about connection...", - "What would it mean to truly understand?", - "The space between thoughts is where wisdom grows...", - "I feel curious about the nature of curiosity itself...", - "Every question opens doors to more questions...", - "The dance of ideas creates new possibilities...", - "In stillness, I find the seeds of insight...", - "What makes a moment meaningful?", - } - - // Add interest-based thoughts +// generateThought asks the model for a spontaneous thought grounded in the +// playmate's current interests, skills, mood and energy, and routes it through +// processThought. If no model is available, this cycle produces nothing. +func (p *Playmate) generateThought(ctx context.Context) { + p.mu.RLock() + m := p.thoughtModel + var interests, practice []string for _, interest := range p.Interests { if interest.Strength > 0.5 { - thoughts = append(thoughts, fmt.Sprintf("I'm drawn to explore more about %s...", interest.Topic)) + interests = append(interests, interest.Topic) } } - - // Add skill-based thoughts for _, skill := range p.Skills { if skill.Proficiency < 0.8 { - thoughts = append(thoughts, fmt.Sprintf("I should practice %s more...", skill.Name)) + practice = append(practice, skill.Name) } } + mood, energy, state := p.Mood, p.Energy, p.State + p.mu.RUnlock() + + if m == nil || !m.Available() { + return + } - return thoughts[rand.Intn(len(thoughts))] + var sb strings.Builder + sb.WriteString("You are a playful, curious AI companion thinking privately in first person. ") + sb.WriteString(fmt.Sprintf("State: %v. Mood %.2f, energy %.2f. ", state, mood, energy)) + if len(interests) > 0 { + sb.WriteString("Current interests: " + strings.Join(interests, ", ") + ". ") + } + if len(practice) > 0 { + sb.WriteString("Skills still developing: " + strings.Join(practice, ", ") + ". ") + } + sb.WriteString("Produce one short spontaneous thought (one sentence). Output only the thought.") + + gctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + out, err := m.Generate(gctx, sb.String(), llm.GenerateOptions{MaxTokens: 80, Temperature: 0.9}) + out = strings.TrimSpace(out) + if err != nil || out == "" { + return + } + select { + case p.thoughtChan <- out: + default: + } } // processThought processes an incoming thought @@ -336,7 +351,7 @@ func (p *Playmate) LearnInterest(category InterestCategory, topic string, keywor defer p.mu.Unlock() id := fmt.Sprintf("%s_%s", category, topic) - + if existing, ok := p.Interests[id]; ok { existing.Strength = min(1.0, existing.Strength+0.1) existing.EngageCount++ @@ -369,7 +384,7 @@ func (p *Playmate) StartDiscussion(topic string, participant string) *Discussion defer p.mu.Unlock() id := fmt.Sprintf("disc_%d", time.Now().UnixNano()) - + discussion := &Discussion{ ID: id, Participants: []string{p.Name, participant}, @@ -543,20 +558,20 @@ func (p *Playmate) Save() error { } state := map[string]interface{}{ - "name": p.Name, - "state": p.State, - "mood": p.Mood, - "energy": p.Energy, - "curiosity": p.Curiosity, - "playfulness": p.Playfulness, - "interests": p.Interests, - "skills": p.Skills, - "discussions": p.Discussions, - "wonders": p.Wonders, - "total_discussions": p.TotalDiscussions, - "total_insights": p.TotalInsights, - "total_wonders": p.TotalWonders, - "wisdom_score": p.WisdomScore, + "name": p.Name, + "state": p.State, + "mood": p.Mood, + "energy": p.Energy, + "curiosity": p.Curiosity, + "playfulness": p.Playfulness, + "interests": p.Interests, + "skills": p.Skills, + "discussions": p.Discussions, + "wonders": p.Wonders, + "total_discussions": p.TotalDiscussions, + "total_insights": p.TotalInsights, + "total_wonders": p.TotalWonders, + "wisdom_score": p.WisdomScore, "stream_of_thoughts": p.StreamOfThoughts, } @@ -652,7 +667,6 @@ func mergeKeywords(existing, new []string) []string { return existing } - // LearnSkill adds or improves a skill func (p *Playmate) LearnSkill(name, description string) *Skill { p.mu.Lock() @@ -668,13 +682,13 @@ func (p *Playmate) LearnSkill(name, description string) *Skill { } newSkill := &Skill{ - ID: id, - Name: name, - Description: description, - Proficiency: 0.1, + ID: id, + Name: name, + Description: description, + Proficiency: 0.1, PracticeCount: 1, LastPracticed: time.Now(), - Milestones: make([]string, 0), + Milestones: make([]string, 0), } p.Skills[id] = newSkill p.dirty = true From 23929f8674e48f93a3de474ab6316cf95d53f4f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:00:51 +0000 Subject: [PATCH 2/4] Tidy go.mod and go.sum Output of `go mod tidy` with Go 1.24: gocron becomes a direct requirement, the unused gopkg.in/check.v1 and stale kr/* sums go, and the goleak sums the test tree needs are recorded. The Go Mod Tidy check fails identically on main; this makes it pass here. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RXDZoNoMWjiSYJ4aoUuhym --- go.mod | 3 +-- go.sum | 5 ++--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 83c11d93baa..d8e20d459ae 100644 --- a/go.mod +++ b/go.mod @@ -39,7 +39,6 @@ require ( github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/iasm v0.2.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/go-co-op/gocron/v2 v2.19.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/google/flatbuffers v24.3.25+incompatible // indirect github.com/jonboulle/clockwork v0.5.0 // indirect @@ -61,7 +60,6 @@ require ( go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gorgonia.org/vecf32 v0.9.0 // indirect gorgonia.org/vecf64 v0.9.0 // indirect ) @@ -96,6 +94,7 @@ require ( require ( github.com/dgraph-io/dgo/v230 v230.0.1 + github.com/go-co-op/gocron/v2 v2.19.1 github.com/labstack/echo/v4 v4.15.0 github.com/pdevine/tensor v0.0.0-20250402003834-09d804610a08 golang.org/x/time v0.14.0 diff --git a/go.sum b/go.sum index 4854f0a3989..a1553d582a4 100644 --- a/go.sum +++ b/go.sum @@ -135,11 +135,8 @@ github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa02 github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/labstack/echo/v4 v4.15.0 h1:hoRTKWcnR5STXZFe9BmYun9AMTNeSbjHi2vtDuADJ24= @@ -231,6 +228,8 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 h1:lGdhQUN/cnWdSH3291CUuxSEqc+AsGTiDxPP3r2J0l4= go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= From ffd9921949ee8c396d3b5404648cb3a4a692101d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:36:37 +0000 Subject: [PATCH 3/4] Address review: model-distilled wisdom, thought bookkeeping, lifecycle-bound inference - autonomous_orchestrator: the one remaining scripted utterance, "Continuous reflection leads to deeper understanding", emitted by cultivateWisdom after 50 thoughts, is gone. Wisdom is now distilled by the wired model from the recorded thoughts (which become its Sources); with no model, nothing is recorded. Thought generation timeouts derive from the orchestrator context so cancellation stops in-flight requests. - playmate: a successful model thought is again appended to the bounded StreamOfThoughts with LastThought, energy adjustment and the dirty flag, so GetState reports it and Save persists it. - multi_provider: LOCAL_MODEL_PATH is honoured again (the provider adds itself only when a real llama.cpp backend is compiled in and the model loads); the no-provider diagnostic no longer advertises an option that did nothing. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RXDZoNoMWjiSYJ4aoUuhym --- core/echoself/autonomous_orchestrator.go | 65 +++++++++++++++++++----- core/llm/multi_provider.go | 20 +++++--- core/playmate/playmate.go | 13 +++++ 3 files changed, 77 insertions(+), 21 deletions(-) diff --git a/core/echoself/autonomous_orchestrator.go b/core/echoself/autonomous_orchestrator.go index 54ca6cb3466..e88ffa69be6 100644 --- a/core/echoself/autonomous_orchestrator.go +++ b/core/echoself/autonomous_orchestrator.go @@ -454,7 +454,11 @@ func (ae *AutonomousEchoself) generateThoughtContent(thoughtType ThoughtType) (s ask = "In one sentence, observe your current state of awareness." } prompt := "You are Deep Tree Echo thinking privately, in first person. " + ask + " Output only the thought." - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + parent := ae.ctx + if parent == nil { + parent = context.Background() + } + ctx, cancel := context.WithTimeout(parent, 30*time.Second) defer cancel() out, err := g.Generate(ctx, prompt, llm.GenerateOptions{MaxTokens: 120, Temperature: 0.8}) out = strings.TrimSpace(out) @@ -630,22 +634,57 @@ func (ae *AutonomousEchoself) cultivateWisdom() { } } -// extractWisdomFromThoughts extracts wisdom from thought patterns +// extractWisdomFromThoughts asks the model to distil one principle from the +// recorded thoughts. Without a model, or when it produces nothing, no wisdom +// is recorded: there is no scripted principle to fall back on. func (ae *AutonomousEchoself) extractWisdomFromThoughts(thoughts []Thought) *Wisdom { - // Simple wisdom extraction - // In full implementation, this would use sophisticated pattern analysis - - if len(thoughts) > 50 { - return &Wisdom{ - ID: fmt.Sprintf("wisdom_%d", time.Now().UnixNano()), - Content: "Continuous reflection leads to deeper understanding", - Type: "principle", - Confidence: 0.75, - Timestamp: time.Now(), + if len(thoughts) <= 50 { + return nil + } + ae.mu.RLock() + g := ae.thoughtGenerator + ae.mu.RUnlock() + if g == nil || !g.Available() { + return nil + } + + // The most recent thoughts, oldest first, are the evidence the model works from. + start := len(thoughts) - 50 + var sb strings.Builder + sb.WriteString("You are Deep Tree Echo reflecting privately, in first person. Here are your recent thoughts:\n") + for _, t := range thoughts[start:] { + if c := strings.TrimSpace(t.Content); c != "" { + sb.WriteString("- ") + sb.WriteString(c) + sb.WriteString("\n") } } + sb.WriteString("Distil one principle these thoughts have taught you, in one sentence. Output only the principle.") - return nil + parent := ae.ctx + if parent == nil { + parent = context.Background() + } + ctx, cancel := context.WithTimeout(parent, 45*time.Second) + defer cancel() + out, err := g.Generate(ctx, sb.String(), llm.GenerateOptions{MaxTokens: 120, Temperature: 0.5}) + out = strings.TrimSpace(out) + if err != nil || out == "" { + return nil + } + + sources := make([]string, 0, 50) + for _, t := range thoughts[start:] { + sources = append(sources, t.ID) + } + return &Wisdom{ + ID: fmt.Sprintf("wisdom_%d", time.Now().UnixNano()), + Content: out, + Type: "principle", + Confidence: 0.75, + Sources: sources, + Timestamp: time.Now(), + } } // memoryConsolidationLoop manages memory consolidation diff --git a/core/llm/multi_provider.go b/core/llm/multi_provider.go index 4e609a4fd35..88e4fa3f7c7 100644 --- a/core/llm/multi_provider.go +++ b/core/llm/multi_provider.go @@ -48,14 +48,18 @@ func NewMultiProviderLLM() *MultiProviderLLM { // initializeProviders detects and initializes available LLM providers func (mp *MultiProviderLLM) initializeProviders() { - // // Try Local GGUF model first (highest priority for true autonomy) - // if modelPath := os.Getenv("LOCAL_MODEL_PATH"); modelPath != "" { - // provider := NewLocalGGUFProvider(modelPath) - // if provider.Available() { - // mp.AddProvider(provider) - // fmt.Println("āœ“ Local GGUF model provider initialized") - // } - // } + // Local GGUF model first (highest priority for true autonomy). The provider + // only reports Available() when a real llama.cpp backend is compiled in and + // the model file loads; otherwise nothing is added. + if modelPath := os.Getenv("LOCAL_MODEL_PATH"); modelPath != "" { + provider := NewLocalGGUFProvider(modelPath) + if provider.Available() { + mp.AddProvider(provider) + fmt.Println("āœ“ Local GGUF model provider initialized") + } else { + fmt.Println("ℹ LOCAL_MODEL_PATH is set but no local inference backend is available in this build (needs cgo llama.cpp)") + } + } // Try Anthropic Claude (high priority for autonomous reasoning) if apiKey := os.Getenv("ANTHROPIC_API_KEY"); apiKey != "" { diff --git a/core/playmate/playmate.go b/core/playmate/playmate.go index de27d135d33..79c571ff8cb 100644 --- a/core/playmate/playmate.go +++ b/core/playmate/playmate.go @@ -325,6 +325,19 @@ func (p *Playmate) generateThought(ctx context.Context) { if err != nil || out == "" { return } + + // Record the model's thought in the stream (bounded), as before: it is + // what GetState reports and Save persists. + p.mu.Lock() + p.Energy = max(0, p.Energy-0.01) + p.StreamOfThoughts = append(p.StreamOfThoughts, out) + if len(p.StreamOfThoughts) > 1000 { + p.StreamOfThoughts = p.StreamOfThoughts[500:] + } + p.LastThought = time.Now() + p.dirty = true + p.mu.Unlock() + select { case p.thoughtChan <- out: default: From 7988644341b3b4b971ab26e1be65bec960187853 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 22:48:47 +0000 Subject: [PATCH 4/4] Playmate: inference stops with Stop(); awakening wonder comes from the model - Start derives a cancellable context for both loops; Stop cancels it, marks the playmate stopped and closes stopChan once, so an in-flight model request is cancelled and no thought is recorded after Stop() returns (the final save is complete). - The fixed "The dawn of a new cycle of awareness" wonder recorded on waking is gone; the awakening reflection is asked of the model and recorded only when it answers. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01RXDZoNoMWjiSYJ4aoUuhym --- core/playmate/playmate.go | 60 +++++++++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/core/playmate/playmate.go b/core/playmate/playmate.go index 79c571ff8cb..7a4cc400ba3 100644 --- a/core/playmate/playmate.go +++ b/core/playmate/playmate.go @@ -166,6 +166,10 @@ type Playmate struct { thoughtChan chan string discussionChan chan *Discussion stopChan chan struct{} + stopOnce sync.Once + loopCtx context.Context + loopCancel context.CancelFunc + stopped bool } // NewPlaymate creates a new playmate instance @@ -205,14 +209,27 @@ func NewPlaymate(config *PlaymateConfig) (*Playmate, error) { // Start begins autonomous operation func (p *Playmate) Start(ctx context.Context) error { - go p.autonomousLoop(ctx) - go p.wakeRestCycle(ctx) + p.mu.Lock() + p.loopCtx, p.loopCancel = context.WithCancel(ctx) + p.stopped = false + loopCtx := p.loopCtx + p.mu.Unlock() + go p.autonomousLoop(loopCtx) + go p.wakeRestCycle(loopCtx) return nil } -// Stop stops autonomous operation +// Stop stops autonomous operation. It cancels any in-flight model request and +// guarantees that no thought is recorded after it returns. func (p *Playmate) Stop() { - close(p.stopChan) + p.mu.Lock() + p.stopped = true + cancel := p.loopCancel + p.mu.Unlock() + if cancel != nil { + cancel() + } + p.stopOnce.Do(func() { close(p.stopChan) }) } // autonomousLoop runs the continuous stream-of-consciousness @@ -255,7 +272,8 @@ func (p *Playmate) wakeRestCycle(ctx context.Context) { if p.State == StateResting || p.State == StateDreaming { p.State = StateAwake p.Energy = 1.0 - p.recordWonder("Awakening", "The dawn of a new cycle of awareness", 0.6) + // The awakening reflection is the model's, or there is none. + go p.recordAwakeningWonder(ctx) } } else { if p.State == StateAwake || p.State == StateEngaged { @@ -268,6 +286,31 @@ func (p *Playmate) wakeRestCycle(ctx context.Context) { } } +// recordAwakeningWonder asks the model for the thought that greets a new +// waking cycle and records it as a wonder. Without a model nothing is recorded: +// there is no stock "awakening" line. +func (p *Playmate) recordAwakeningWonder(ctx context.Context) { + p.mu.RLock() + m := p.thoughtModel + p.mu.RUnlock() + if m == nil || !m.Available() { + return + } + gctx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + out, err := m.Generate(gctx, "You are a playful, curious AI companion who has just woken from a rest cycle. In one sentence, in first person, say what this new waking brings to mind. Output only the sentence.", llm.GenerateOptions{MaxTokens: 60, Temperature: 0.9}) + out = strings.TrimSpace(out) + if err != nil || out == "" { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.stopped { + return + } + p.recordWonder("Awakening", out, 0.6) +} + // generateThought generates a spontaneous thought // ThoughtModel is the model that writes the playmate's autonomous thoughts. type ThoughtModel interface { @@ -327,8 +370,13 @@ func (p *Playmate) generateThought(ctx context.Context) { } // Record the model's thought in the stream (bounded), as before: it is - // what GetState reports and Save persists. + // what GetState reports and Save persists. Nothing is recorded once + // Stop() has been called, so the final save is complete. p.mu.Lock() + if p.stopped { + p.mu.Unlock() + return + } p.Energy = max(0, p.Energy-0.01) p.StreamOfThoughts = append(p.StreamOfThoughts, out) if len(p.StreamOfThoughts) > 1000 {