xonecas.io
60255
Zn

Zoea-Nova / commit 5e18ff4

feat(core): add tool call and tool result validation

- Validate tool result delimiter and tool_call_id presence
- Skip malformed tool result messages
- Validate assistant tool call parsing
- Keep original content if tool call parsing fails
- Add JSON validation for tool call arguments
- Ensures OpenAI Chat Completions API compliance

xonecas2026-02-06 5e18ff4a522490bb704a904ab6ce28d4c34cf1b9 parent 168f61e

1 file changed

internal/core/mysis.go+32−5
@@ -678,17 +678,36 @@ func (m *Mysis) memoriesToMessages(memories []*store.Memory) []provider.Message
678678 // Handle tool role - needs ToolCallID
679679 if m.Role == store.MemoryRoleTool {
680680 // Extract tool call ID from stored format: "tool_call_id:content"
681- if idx := strings.Index(m.Content, constants.ToolCallStorageFieldDelimiter); idx > 0 {
682- msg.ToolCallID = m.Content[:idx]
683- msg.Content = m.Content[idx+1:]
681+ idx := strings.Index(m.Content, constants.ToolCallStorageFieldDelimiter)
682+ if idx <= 0 {
683+ log.Warn().
684+ Str("content", m.Content).
685+ Msg("Skipping malformed tool result - missing delimiter")
686+ continue // Skip this message
687+ }
688+ toolCallID := m.Content[:idx]
689+ if toolCallID == "" {
690+ log.Warn().
691+ Str("content", m.Content).
692+ Msg("Skipping tool result with empty tool_call_id")
693+ continue // Skip this message
684694 }
695+ msg.ToolCallID = toolCallID
696+ msg.Content = m.Content[idx+1:]
685697 }
686698
687699 // Handle assistant messages with tool calls
688700 if m.Role == store.MemoryRoleAssistant && strings.HasPrefix(m.Content, constants.ToolCallStoragePrefix) {
689701 // Parse tool calls from stored format
690- msg.Content = ""
691702 msg.ToolCalls = a.parseStoredToolCalls(m.Content)
703+ if len(msg.ToolCalls) > 0 {
704+ msg.Content = "" // Only clear content if tool calls were parsed successfully
705+ } else {
706+ log.Warn().
707+ Str("content", m.Content).
708+ Msg("Failed to parse tool calls from assistant message - keeping original content")
709+ // Keep original content as fallback
710+ }
692711 }
693712
694713 messages = append(messages, msg)
@@ -779,10 +798,18 @@ func (m *Mysis) parseStoredToolCalls(stored string) []provider.ToolCall {
779798 for _, part := range parts {
780799 fields := strings.SplitN(part, constants.ToolCallStorageFieldDelimiter, constants.ToolCallStorageFieldCount)
781800 if len(fields) >= constants.ToolCallStorageFieldCount {
801+ args := json.RawMessage(fields[2])
802+ if !json.Valid(args) {
803+ log.Warn().
804+ Str("tool_call_id", fields[0]).
805+ Str("tool_name", fields[1]).
806+ Msg("Invalid JSON in tool call arguments - using empty object")
807+ args = json.RawMessage("{}")
808+ }
782809 calls = append(calls, provider.ToolCall{
783810 ID: fields[0],
784811 Name: fields[1],
785- Arguments: json.RawMessage(fields[2]),
812+ Arguments: args,
786813 })
787814 }
788815 }