@@ -3,6 +3,7 @@ package core
33 import (
44 "context"
55 "encoding/json"
6+ "errors"
67 "fmt"
78 "sort"
89 "strconv"
@@ -46,6 +47,7 @@ type Mysis struct {
4647 lastServerTickAt time.Time
4748 tickDuration time.Duration
4849 nudgeCh chan struct{}
50+ nudgeFailCount int // Circuit breaker: consecutive nudge failures
4951 }
5052
5153 type contextStats struct {
@@ -597,6 +599,11 @@ func (m *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
597599 return fmt.Errorf("store response: %w", err)
598600 }
599601
602+ // Reset nudge failure counter on successful response
603+ a.mu.Lock()
604+ a.nudgeFailCount = 0
605+ a.mu.Unlock()
606+
600607 // Signal network idle
601608 a.bus.Publish(Event{Type: EventNetworkIdle, MysisID: a.id, Timestamp: time.Now()})
602609
@@ -624,6 +631,277 @@ func (m *Mysis) SendMessage(content string, source store.MemorySource) error {
624631 return a.SendMessageFrom(content, source, "")
625632 }
626633
634+// SendEphemeralMessage sends a message to the mysis that is NOT persisted to the database.
635+// The LLM response to the message IS still persisted. Used for nudges/automation scaffolding.
636+func (m *Mysis) SendEphemeralMessage(content string, source store.MemorySource) error {
637+ a := m
638+ a.turnMu.Lock()
639+ defer a.turnMu.Unlock()
640+
641+ a.mu.RLock()
642+ state := a.state
643+ p := a.provider
644+ mcpProxy := a.mcp
645+ a.mu.RUnlock()
646+
647+ if state != MysisStateRunning {
648+ return fmt.Errorf("mysis not running")
649+ }
650+
651+ // NOTE: We skip storing the ephemeral message to the database
652+ // Unlike SendMessageFrom, we don't call store.AddMemory here
653+
654+ // Create context for the entire conversation turn
655+ a.mu.RLock()
656+ parentCtx := a.ctx
657+ a.mu.RUnlock()
658+
659+ if parentCtx == nil {
660+ parentCtx = context.Background()
661+ }
662+
663+ ctx, cancel := context.WithTimeout(parentCtx, constants.LLMRequestTimeout)
664+ defer cancel()
665+
666+ // Get available tools from MCP proxy
667+ var tools []provider.Tool
668+ if mcpProxy != nil {
669+ mcpTools, err := mcpProxy.ListTools(ctx)
670+ if err != nil {
671+ // Log error but continue - mysis can still chat without tools
672+ a.publishCriticalEvent(Event{
673+ Type: EventMysisError,
674+ MysisID: a.id,
675+ MysisName: a.name,
676+ Error: &ErrorData{Error: fmt.Sprintf("Failed to load tools: %v", err)},
677+ Timestamp: time.Now(),
678+ })
679+ } else {
680+ tools = make([]provider.Tool, len(mcpTools))
681+ for i, t := range mcpTools {
682+ tools[i] = provider.Tool{
683+ Name: t.Name,
684+ Description: t.Description,
685+ Parameters: t.InputSchema,
686+ }
687+ }
688+ }
689+ } else {
690+ a.publishCriticalEvent(Event{
691+ Type: EventMysisError,
692+ MysisID: a.id,
693+ MysisName: a.name,
694+ Error: &ErrorData{Error: "MCP proxy not configured - no tools available"},
695+ Timestamp: time.Now(),
696+ })
697+ }
698+
699+ // Loop: keep calling LLM until we get a final text response
700+ for iteration := 0; iteration < constants.MaxToolIterations; iteration++ {
701+ // Get recent conversation history (keeps context small for faster inference)
702+ memories, err := a.getContextMemories()
703+ if err != nil {
704+ a.setError(err)
705+ return fmt.Errorf("get memories: %w", err)
706+ }
707+
708+ memoryStats := a.computeMemoryStats(memories)
709+ log.Debug().
710+ Str("mysis_id", a.id).
711+ Str("mysis_name", a.name).
712+ Str("stage", "context_memories").
713+ Int("memory_count", memoryStats.MemoryCount).
714+ Int("message_count", 0).
715+ Int("content_bytes", memoryStats.ContentBytes).
716+ Int("reasoning_bytes", memoryStats.ReasoningBytes).
717+ Interface("role_counts", memoryStats.RoleCounts).
718+ Interface("source_counts", memoryStats.SourceCounts).
719+ Int("tool_call_count", 0).
720+ Msg("Context stats (ephemeral)")
721+
722+ // Convert to provider messages
723+ messages := a.memoriesToMessages(memories)
724+
725+ // Add ephemeral message to the end (in-memory only, not persisted)
726+ role := store.MemoryRoleUser
727+ if source == store.MemorySourceSystem {
728+ role = store.MemoryRoleSystem
729+ }
730+ messages = append(messages, provider.Message{
731+ Role: string(role),
732+ Content: content,
733+ })
734+
735+ messageStats := a.computeMessageStats(messages)
736+ log.Debug().
737+ Str("mysis_id", a.id).
738+ Str("mysis_name", a.name).
739+ Str("stage", "messages_converted").
740+ Int("memory_count", memoryStats.MemoryCount).
741+ Int("message_count", messageStats.MessageCount).
742+ Int("content_bytes", messageStats.ContentBytes).
743+ Int("reasoning_bytes", memoryStats.ReasoningBytes).
744+ Interface("role_counts", memoryStats.RoleCounts).
745+ Interface("source_counts", memoryStats.SourceCounts).
746+ Int("tool_call_count", messageStats.ToolCallCount).
747+ Msg("Context stats (ephemeral)")
748+
749+ // Signal LLM activity start
750+ a.bus.Publish(Event{
751+ Type: EventNetworkLLM,
752+ MysisID: a.id,
753+ MysisName: a.name,
754+ Timestamp: time.Now(),
755+ })
756+ log.Debug().
757+ Str("mysis_id", a.id).
758+ Str("mysis_name", a.name).
759+ Str("stage", "before_llm_call").
760+ Int("memory_count", memoryStats.MemoryCount).
761+ Int("message_count", messageStats.MessageCount).
762+ Int("content_bytes", messageStats.ContentBytes).
763+ Int("reasoning_bytes", memoryStats.ReasoningBytes).
764+ Interface("role_counts", memoryStats.RoleCounts).
765+ Interface("source_counts", memoryStats.SourceCounts).
766+ Int("tool_call_count", messageStats.ToolCallCount).
767+ Msg("Context stats (ephemeral)")
768+
769+ // Set activity state to indicate LLM call in progress
770+ a.setActivity(ActivityStateLLMCall, time.Time{})
771+
772+ // Get response from provider
773+ var response *provider.ChatResponse
774+ if len(tools) > 0 {
775+ response, err = p.ChatWithTools(ctx, messages, tools)
776+ } else {
777+ // No tools available, use simple chat
778+ text, chatErr := p.Chat(ctx, messages)
779+ if chatErr != nil {
780+ err = chatErr
781+ } else {
782+ response = &provider.ChatResponse{Content: text}
783+ }
784+ }
785+
786+ // Clear LLM activity state after call completes (success or failure)
787+ a.setActivity(ActivityStateIdle, time.Time{})
788+
789+ if err != nil {
790+ log.Error().
791+ Str("mysis", a.name).
792+ Str("provider", p.Name()).
793+ Err(err).
794+ Msg("Provider returned error (ephemeral)")
795+ a.bus.Publish(Event{Type: EventNetworkIdle, MysisID: a.id, Timestamp: time.Now()})
796+ a.setError(err)
797+ return fmt.Errorf("provider chat: %w", err)
798+ }
799+
800+ if response.Reasoning != "" {
801+ log.Debug().Str("mysis", a.name).Int("reasoning_len", len(response.Reasoning)).Msg("LLM reasoning captured (ephemeral)")
802+ }
803+
804+ // If we have tool calls, execute them
805+ if len(response.ToolCalls) > 0 {
806+ // Store the assistant's tool call request
807+ toolCallJSON := a.formatToolCallsForStorage(response.ToolCalls)
808+ if err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, toolCallJSON, response.Reasoning, ""); err != nil {
809+ a.setError(err)
810+ return fmt.Errorf("store tool call: %w", err)
811+ }
812+
813+ // Emit event showing which tools are being called
814+ toolNames := make([]string, len(response.ToolCalls))
815+ for i, tc := range response.ToolCalls {
816+ toolNames[i] = tc.Name
817+ }
818+ a.bus.Publish(Event{
819+ Type: EventMysisMessage,
820+ MysisID: a.id,
821+ MysisName: a.name,
822+ Message: &MessageData{Role: "assistant", Content: fmt.Sprintf("Calling tools: %s", strings.Join(toolNames, ", "))},
823+ Timestamp: time.Now(),
824+ })
825+
826+ // Execute each tool call
827+ for _, tc := range response.ToolCalls {
828+ // Signal MCP activity
829+ a.bus.Publish(Event{
830+ Type: EventNetworkMCP,
831+ MysisID: a.id,
832+ MysisName: a.name,
833+ Timestamp: time.Now(),
834+ })
835+
836+ // Set activity state to indicate MCP call in progress
837+ a.setActivity(ActivityStateMCPCall, time.Time{})
838+
839+ result, execErr := a.executeToolCall(ctx, mcpProxy, tc)
840+
841+ // Clear MCP activity state after call completes
842+ a.setActivity(ActivityStateIdle, time.Time{})
843+
844+ a.updateActivityFromToolResult(result, execErr)
845+
846+ // Store the tool result
847+ resultContent := a.formatToolResult(tc.ID, tc.Name, result, execErr)
848+ if err := a.store.AddMemory(a.id, store.MemoryRoleTool, store.MemorySourceTool, resultContent, "", ""); err != nil {
849+ a.setError(err)
850+ return fmt.Errorf("store tool result: %w", err)
851+ }
852+
853+ // Emit tool result event
854+ a.bus.Publish(Event{
855+ Type: EventMysisMessage,
856+ MysisID: a.id,
857+ MysisName: a.name,
858+ Message: &MessageData{Role: "tool", Content: fmt.Sprintf("[%s] %s", tc.Name, a.formatToolResultDisplay(result, execErr))},
859+ Timestamp: time.Now(),
860+ })
861+ }
862+
863+ // Continue loop to get next LLM response
864+ continue
865+ }
866+
867+ // No tool calls - we have a final response
868+ finalResponse := response.Content
869+ if finalResponse == "" && response.Reasoning == "" {
870+ finalResponse = constants.FallbackLLMResponse
871+ }
872+
873+ // Store the assistant response
874+ if err := a.store.AddMemory(a.id, store.MemoryRoleAssistant, store.MemorySourceLLM, finalResponse, response.Reasoning, ""); err != nil {
875+ a.setError(err)
876+ return fmt.Errorf("store response: %w", err)
877+ }
878+
879+ // Reset nudge failure counter on successful response
880+ a.mu.Lock()
881+ a.nudgeFailCount = 0
882+ a.mu.Unlock()
883+
884+ // Signal network idle
885+ a.bus.Publish(Event{Type: EventNetworkIdle, MysisID: a.id, Timestamp: time.Now()})
886+
887+ // Emit response event
888+ a.bus.Publish(Event{
889+ Type: EventMysisResponse,
890+ MysisID: a.id,
891+ MysisName: a.name,
892+ Message: &MessageData{Role: "assistant", Content: finalResponse},
893+ Timestamp: time.Now(),
894+ })
895+
896+ return nil
897+ }
898+
899+ // Signal network idle on max iterations
900+ a.bus.Publish(Event{Type: EventNetworkIdle, MysisID: a.id, Timestamp: time.Now()})
901+
902+ return fmt.Errorf("max tool iterations (%d) exceeded", constants.MaxToolIterations)
903+}
904+
627905 // QueueBroadcast stores a broadcast message and triggers async processing.
628906 // Unlike SendMessage, this does not block waiting for the mysis to process.
629907 // Returns immediately after storing the message in the database.
@@ -932,6 +1210,10 @@ func (m *Mysis) getContextMemories() ([]*store.Memory, error) {
9321210 // This ensures OpenAI Chat Completions API compliance
9331211 compacted = a.removeOrphanedToolMessages(compacted)
9341212
1213+ // Remove orphaned tool calls (assistant tool calls without corresponding tool results)
1214+ // This prevents OpenCode Zen API crashes when context window cuts off tool results
1215+ compacted = a.removeOrphanedToolCalls(compacted)
1216+
9351217 // Always try to fetch the system prompt and prepend it if not already first
9361218 system, err := a.store.GetSystemMemory(a.id)
9371219 if err != nil {
@@ -1015,6 +1297,68 @@ func (m *Mysis) compactSnapshots(memories []*store.Memory) []*store.Memory {
10151297 return result
10161298 }
10171299
1300+// collectValidToolResultIDs extracts all tool call IDs from tool result messages.
1301+// Used to validate that assistant tool calls have corresponding tool results.
1302+func (m *Mysis) collectValidToolResultIDs(memories []*store.Memory) map[string]bool {
1303+ validToolResults := make(map[string]bool)
1304+
1305+ for _, mem := range memories {
1306+ if mem.Role == store.MemoryRoleTool {
1307+ idx := strings.Index(mem.Content, constants.ToolCallStorageFieldDelimiter)
1308+ if idx > 0 {
1309+ toolCallID := mem.Content[:idx]
1310+ validToolResults[toolCallID] = true
1311+ }
1312+ }
1313+ }
1314+
1315+ return validToolResults
1316+}
1317+
1318+// removeOrphanedToolCalls removes assistant messages with tool calls that don't have
1319+// corresponding tool result messages. This can happen due to:
1320+// 1. Context window cutting off tool results but keeping tool calls
1321+// 2. Context compaction removing tool result messages
1322+//
1323+// OpenAI Chat Completions API may crash if assistant tool calls don't have matching results.
1324+func (m *Mysis) removeOrphanedToolCalls(memories []*store.Memory) []*store.Memory {
1325+ validToolResults := m.collectValidToolResultIDs(memories)
1326+
1327+ result := make([]*store.Memory, 0, len(memories))
1328+ for _, mem := range memories {
1329+ // Check if this is an assistant message with tool calls
1330+ if mem.Role == store.MemoryRoleAssistant &&
1331+ strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
1332+ calls := m.parseStoredToolCalls(mem.Content)
1333+ allCallsHaveResults := true
1334+ for _, call := range calls {
1335+ if !validToolResults[call.ID] {
1336+ log.Debug().
1337+ Str("tool_call_id", call.ID).
1338+ Str("tool_name", call.Name).
1339+ Msg("Removing orphaned assistant tool call - no matching tool result")
1340+ allCallsHaveResults = false
1341+ break
1342+ }
1343+ }
1344+ if !allCallsHaveResults {
1345+ continue // Skip assistant message with orphaned tool calls
1346+ }
1347+ }
1348+ result = append(result, mem)
1349+ }
1350+
1351+ if len(result) < len(memories) {
1352+ log.Debug().
1353+ Int("removed", len(memories)-len(result)).
1354+ Int("original", len(memories)).
1355+ Int("final", len(result)).
1356+ Msg("Removed orphaned assistant tool calls for OpenAI compliance")
1357+ }
1358+
1359+ return result
1360+}
1361+
10181362 func (m *Mysis) extractToolNameFromResult(content string, toolCallNames map[string]string) string {
10191363 idx := strings.Index(content, constants.ToolCallStorageFieldDelimiter)
10201364 if idx <= 0 {
@@ -1091,17 +1435,45 @@ func (m *Mysis) run(ctx context.Context) {
10911435 a.mu.RUnlock()
10921436
10931437 if isRunning && a.shouldNudge(time.Now()) {
1094- select {
1095- case a.nudgeCh <- struct{}{}:
1096- default:
1438+ // Only increment nudge counter if no turn is currently in progress
1439+ // This prevents counting nudges while the LLM is still processing a previous nudge
1440+ if a.turnMu.TryLock() {
1441+ a.turnMu.Unlock()
1442+
1443+ // Circuit breaker: increment failure count before sending nudge
1444+ // This counts how many times the ticker has fired while mysis appears idle
1445+ a.mu.Lock()
1446+ a.nudgeFailCount++
1447+ failCount := a.nudgeFailCount
1448+ a.mu.Unlock()
1449+
1450+ // If we've failed 3 times, transition to error state
1451+ if failCount >= 3 {
1452+ a.setError(errors.New("Failed to respond after 3 nudges"))
1453+ return
1454+ }
1455+
1456+ select {
1457+ case a.nudgeCh <- struct{}{}:
1458+ default:
1459+ }
10971460 }
1461+ // If turn is in progress, skip this nudge tick (LLM is still working)
10981462 }
10991463 case <-a.nudgeCh:
11001464 if !a.turnMu.TryLock() {
11011465 continue
11021466 }
11031467 a.turnMu.Unlock()
1104- go a.SendMessage(a.buildContinuePrompt(), store.MemorySourceSystem)
1468+
1469+ // Get current nudge attempt count for escalation
1470+ a.mu.RLock()
1471+ attemptCount := a.nudgeFailCount
1472+ a.mu.RUnlock()
1473+
1474+ // Send nudge as ephemeral user message (not persisted to DB, only sent to LLM)
1475+ // Nudges are automation scaffolding, not conversation history
1476+ go a.SendEphemeralMessage(a.buildContinuePrompt(attemptCount), store.MemorySourceDirect)
11051477 }
11061478 }
11071479 }
@@ -1142,9 +1514,20 @@ Follow swarm directives. Coordinate your actions with the swarm's goals.`,
11421514 return strings.Replace(base, "{{LATEST_BROADCAST}}", broadcastSection, 1)
11431515 }
11441516
1145-func (m *Mysis) buildContinuePrompt() string {
1517+func (m *Mysis) buildContinuePrompt(attemptCount int) string {
11461518 a := m
1147- base := constants.ContinuePrompt
1519+
1520+ // Select base message based on escalation level
1521+ var base string
1522+ switch {
1523+ case attemptCount >= 2:
1524+ base = constants.ContinuePromptUrgent
1525+ case attemptCount == 1:
1526+ base = constants.ContinuePromptFirm
1527+ default:
1528+ base = constants.ContinuePrompt
1529+ }
1530+
11481531 reminders := a.detectDriftReminders()
11491532 if len(reminders) == 0 {
11501533 return base