Class: Legion::CLI::Chat::Tools::SaveMemory

Inherits:
Tools::Base
  • Object
show all
Defined in:
lib/legion/cli/chat/tools/save_memory.rb

Constant Summary collapse

DEFAULT_PORT =
4567
DEFAULT_HOST =
'127.0.0.1'

Class Method Summary collapse

Methods inherited from Tools::Base

deferred, deferred?, description, error_response, extension, handle_exception, input_schema, log, mcp_category, mcp_tier, runner, sticky, tags, text_response, tool_name, trigger_words

Class Method Details

.api_portObject



65
66
67
68
69
70
71
# File 'lib/legion/cli/chat/tools/save_memory.rb', line 65

def self.api_port
  return DEFAULT_PORT unless defined?(Legion::Settings)

  Legion::Settings[:api]&.dig(:port) || DEFAULT_PORT
rescue StandardError
  DEFAULT_PORT
end

.call(text:, scope: 'project') ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/legion/cli/chat/tools/save_memory.rb', line 27

def self.call(text:, scope: 'project')
  require 'legion/cli/chat/memory_store'
  sym_scope = scope.to_s == 'global' ? :global : :project
  path = MemoryStore.add(text, scope: sym_scope)
  apollo_status = ingest_to_apollo(text, sym_scope)

  parts = ["Saved to #{sym_scope} memory (#{path})"]
  parts << apollo_status if apollo_status
  parts.join("\n")
rescue StandardError => e
  Legion::Logging.warn("SaveMemory#execute failed: #{e.message}") if defined?(Legion::Logging)
  "Error saving memory: #{e.message}"
end

.ingest_to_apollo(text, scope) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/legion/cli/chat/tools/save_memory.rb', line 41

def self.ingest_to_apollo(text, scope)
  require 'net/http'
  require 'json'

  uri = URI("http://#{DEFAULT_HOST}:#{api_port}/api/apollo/ingest")
  http = Net::HTTP.new(uri.host, uri.port)
  http.open_timeout = 2
  http.read_timeout = 5
  request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
  request.body = ::JSON.generate({
                                   content: text,
                                   source:  "chat:#{scope}",
                                   tags:    ['memory', scope.to_s]
                                 })
  response = http.request(request)
  data = ::JSON.parse(response.body, symbolize_names: true)
  return nil if data[:error]

  'Also ingested into Apollo knowledge graph.'
rescue StandardError => e
  Legion::Logging.debug("SaveMemory#ingest_to_apollo failed: #{e.message}") if defined?(Legion::Logging)
  nil
end