Class: Clacky::Advisor::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/clacky/default_extensions/advisor/hooks/advisor.rb

Overview

One per agent. observe_tool runs on the main agent thread (must stay cheap); the analysis runs on a detached thread spawned once per round from finish_run (the on_complete hook).

Instance Method Summary collapse

Constructor Details

#initialize(agent) ⇒ Worker

Returns a new instance of Worker.



108
109
110
111
112
113
# File 'lib/clacky/default_extensions/advisor/hooks/advisor.rb', line 108

def initialize(agent)
  @agent = agent
  @mutex = Mutex.new
  @trail = []
  @tools_this_run = 0
end

Instance Method Details

#finish_runObject

on_complete callback: a run ended. Snapshot this round's state and analyse asynchronously — one recommendation per round, including rounds with no tool calls at all (e.g. the very first "hi"). The pending event is emitted synchronously so the UI can show a "working" state immediately instead of the card popping in out of nowhere.



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/clacky/default_extensions/advisor/hooks/advisor.rb', line 130

def finish_run
  snapshot = @mutex.synchronize do
    snap = {
      tools: @tools_this_run,
      trail: @trail.dup,
      user_message: recent_user_message,
      conversation: recent_conversation
    }
    @trail.clear
    @tools_this_run = 0
    snap
  end
  Clacky::Logger.info("[Advisor] finish_run",
                      session: @agent.session_id.to_s,
                      tools: snapshot[:tools],
                      trail: snapshot[:trail].size,
                      user: snapshot[:user_message].to_s[0, 80])
  emit_pending
  ThreadRegistry.spawn(name: "advisor-#{@agent.session_id}", daemon: true) do
    analyze(snapshot)
  end
rescue StandardError => e
  warn_error("schedule", e)
end

#observe_tool(call, result) ⇒ Object

after_tool_use callback. O(1): append to the trail for the brief.



116
117
118
119
120
121
122
123
# File 'lib/clacky/default_extensions/advisor/hooks/advisor.rb', line 116

def observe_tool(call, result)
  name = call[:name].to_s
  @mutex.synchronize do
    @tools_this_run += 1
    @trail << [name, summarize(result)]
    @trail = @trail.last(TRAIL_LIMIT)
  end
end