Class: Binocs::AgentManager

Inherits:
Object
  • Object
show all
Defined in:
lib/binocs/agent_manager.rb

Class Method Summary collapse

Class Method Details

.cleanup(agent) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/binocs/agent_manager.rb', line 186

def cleanup(agent)
  # Stop the process if running
  agent.stop! if agent.running?

  # Remove the worktree
  if agent.worktree_path && Dir.exist?(agent.worktree_path)
    repo_root = find_git_root

    Dir.chdir(repo_root) do
      system("git worktree remove #{agent.worktree_path.shellescape} --force",
             out: File::NULL, err: File::NULL)
    end

    # Also delete the branch if it exists
    if agent.branch_name
      Dir.chdir(repo_root) do
        system("git branch -D #{agent.branch_name.shellescape}",
               out: File::NULL, err: File::NULL)
      end
    end
  end

  # Remove from registry
  Agent.remove(agent)
end

.continue_session(agent:, prompt:, tool: nil) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/binocs/agent_manager.rb', line 84

def continue_session(agent:, prompt:, tool: nil)
  tool ||= agent.tool

  # Update agent for new session
  agent.prompt = prompt
  agent.tool = tool
  agent.status = :pending
  agent.created_at = Time.now

  # Log continuation
  log_to_agent(agent, "")
  log_to_agent(agent, "=" * 60)
  log_to_agent(agent, "Continuing Session")
  log_to_agent(agent, "Time: #{Time.now}")
  log_to_agent(agent, "Tool: #{tool}")
  log_to_agent(agent, "=" * 60)
  log_to_agent(agent, "")

  log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Continuing in: #{agent.worktree_path}")
  log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] New prompt: #{prompt[0, 50]}...")
  log_to_agent(agent, "")

  # Spawn the process in the same directory
  log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Starting #{agent.tool_command}...")
  log_to_agent(agent, "")
  log_to_agent(agent, "-" * 60)
  log_to_agent(agent, "Agent Output:")
  log_to_agent(agent, "-" * 60)
  log_to_agent(agent, "")
  spawn_agent(agent)

  agent
end

.create_worktree(agent, worktree_name) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/binocs/agent_manager.rb', line 123

def create_worktree(agent, worktree_name)
  base_dir = worktree_base_path
  worktree_path = File.join(base_dir, worktree_name)
  branch_name = "agent/#{worktree_name}"

  # Get current repo root
  repo_root = find_git_root

  # Create the worktree with a new branch, capturing output
  Dir.chdir(repo_root) do
    output = `git worktree add -b #{branch_name.shellescape} #{worktree_path.shellescape} HEAD 2>&1`
    unless $?.success?
      log_to_agent(agent, "[ERROR] Git worktree creation failed:")
      log_to_agent(agent, output)
      raise "Failed to create git worktree at #{worktree_path}: #{output}"
    end
    log_to_agent(agent, output) unless output.strip.empty?
  end

  [worktree_path, branch_name]
end

.generate_slug(prompt) ⇒ Object



145
146
147
148
149
150
151
152
153
# File 'lib/binocs/agent_manager.rb', line 145

def generate_slug(prompt)
  return 'task' if prompt.nil? || prompt.empty?

  # Take first few words, remove special chars, join with dashes
  words = prompt.downcase.gsub(/[^a-z0-9\s]/, '').split.first(4)
  slug = words.join('-')
  slug = slug[0, 25] if slug.length > 25
  slug.empty? ? 'task' : slug
end

.launch(request:, prompt:, tool: nil, branch_name: nil, use_worktree: false) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/binocs/agent_manager.rb', line 10

def launch(request:, prompt:, tool: nil, branch_name: nil, use_worktree: false)
  tool ||= Binocs.configuration.agent_tool

  # Create agent record
  agent = Agent.new(
    request_id: request.id,
    prompt: prompt,
    tool: tool,
    request_context: AgentContext.build(request)
  )

  # Set up output file path early so we can log to it
  base_dir = worktree_base_path
  FileUtils.mkdir_p(base_dir)

  # Generate a name for logs
  timestamp = Time.now.strftime('%m%d-%H%M%S')
  prompt_slug = generate_slug(agent.prompt)
  log_name = "#{timestamp}-#{prompt_slug}"
  agent.output_file = File.join(base_dir, "#{log_name}.log")

  # Start logging
  log_to_agent(agent, "=" * 60)
  log_to_agent(agent, "Binocs Agent Started")
  log_to_agent(agent, "Time: #{Time.now}")
  log_to_agent(agent, "Tool: #{agent.tool}")
  log_to_agent(agent, "Mode: #{use_worktree ? 'New Worktree' : 'Current Branch'}")
  log_to_agent(agent, "=" * 60)
  log_to_agent(agent, "")

  if use_worktree
    # Create worktree for isolated work
    worktree_name = branch_name && !branch_name.empty? ? branch_name : log_name
    log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Creating git worktree...")
    worktree_path, branch_name = create_worktree(agent, worktree_name)
    agent.worktree_path = worktree_path
    agent.branch_name = branch_name
    log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Worktree created: #{worktree_path}")
    log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Branch: #{branch_name}")
    log_to_agent(agent, "")

    # Write context file for the agent
    context_file = File.join(worktree_path, '.binocs-context.md')
    File.write(context_file, agent.request_context)
    log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Context file written: .binocs-context.md")
  else
    # Run in current directory on current branch
    agent.worktree_path = find_git_root
    agent.branch_name = current_branch_name
    log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Running on current branch: #{agent.branch_name}")
    log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Directory: #{agent.worktree_path}")
    log_to_agent(agent, "")

    # Write context file in current directory
    context_file = File.join(agent.worktree_path, '.binocs-context.md')
    File.write(context_file, agent.request_context)
    log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Context file written: .binocs-context.md")
  end

  # Register agent
  Agent.add(agent)

  # Spawn the process
  log_to_agent(agent, "[#{Time.now.strftime('%H:%M:%S')}] Starting #{agent.tool_command}...")
  log_to_agent(agent, "")
  log_to_agent(agent, "-" * 60)
  log_to_agent(agent, "Agent Output:")
  log_to_agent(agent, "-" * 60)
  log_to_agent(agent, "")
  spawn_agent(agent)

  agent
end

.log_to_agent(agent, message) ⇒ Object



118
119
120
121
# File 'lib/binocs/agent_manager.rb', line 118

def log_to_agent(agent, message)
  return unless agent.output_file
  File.open(agent.output_file, 'a') { |f| f.puts(message) }
end

.open_worktree(agent) ⇒ Object



212
213
214
215
216
217
218
219
220
221
# File 'lib/binocs/agent_manager.rb', line 212

def open_worktree(agent)
  return unless agent.worktree_path && Dir.exist?(agent.worktree_path)

  # Open in file manager
  if RbConfig::CONFIG['host_os'] =~ /darwin/
    system("open", agent.worktree_path)
  elsif RbConfig::CONFIG['host_os'] =~ /linux/
    system("xdg-open", agent.worktree_path)
  end
end

.spawn_agent(agent) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/binocs/agent_manager.rb', line 155

def spawn_agent(agent)
  return unless agent.worktree_path && Dir.exist?(agent.worktree_path)

  # Build the full prompt including context
  full_prompt = build_full_prompt(agent)

  # Create a prompt file for the agent to read
  prompt_file = File.join(agent.worktree_path, '.binocs-prompt.md')
  File.write(prompt_file, full_prompt)

  # Build command arguments based on tool
  cmd_args = build_agent_command_args(agent, prompt_file)

  # Spawn the process
  pid = Process.spawn(
    *cmd_args,
    chdir: agent.worktree_path,
    out: [agent.output_file, 'a'],
    err: [agent.output_file, 'a'],
    pgroup: true
  )

  Process.detach(pid)

  agent.pid = pid
  agent.status = :running

  # Start a monitor thread
  start_monitor_thread(agent)
end