agents_control 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "net/http"
4
4
  require "json"
5
+ require "rbconfig"
5
6
 
6
7
  module AgentsControl
7
8
  # Brings everything together: receiving hooks from agents and talking to Telegram.
@@ -15,11 +16,16 @@ module AgentsControl
15
16
  # daemon restart, or every restart would leave hooks firing into nothing.
16
17
  DEFAULT_PORT = 47_653
17
18
 
18
- def initialize(config: nil, store: nil, secrets: nil, logger: $stdout)
19
+ # Overridden in tests: the real one replaces the running process outright.
20
+ REEXEC = ->(ruby, script, *args) { Kernel.exec(ruby, script, *args) }
21
+
22
+ def initialize(config: nil, store: nil, secrets: nil, logger: $stdout, reexec: REEXEC, executor: Executor.new)
19
23
  @config = config || Config.load
20
24
  @store = store || Store.new
21
25
  @secrets = secrets || Secrets.new
22
26
  @logger = logger
27
+ @reexec = reexec
28
+ @executor = executor
23
29
 
24
30
  # Without this, output buffers until the process exits. Under
25
31
  # launchd that means an empty log for a daemon that's actually
@@ -45,6 +51,9 @@ module AgentsControl
45
51
  start_anchors
46
52
  start_screen_watcher
47
53
  start_rate_limit_watcher
54
+ start_auto_reloader
55
+ start_auto_updater
56
+ trap_reload
48
57
  install_agents
49
58
  verify_hooks
50
59
  publish_commands
@@ -65,6 +74,8 @@ module AgentsControl
65
74
  @scheduler&.stop
66
75
  @screen_watcher&.stop
67
76
  @rate_limit_watcher&.stop
77
+ @auto_reloader&.stop
78
+ @auto_updater&.stop
68
79
  remove_agents
69
80
  end
70
81
 
@@ -167,6 +178,47 @@ module AgentsControl
167
178
  ).start
168
179
  end
169
180
 
181
+ def start_auto_reloader
182
+ @auto_reloader = AutoReloader.new(config: @config, logger: @logger) { reload! }.start
183
+ end
184
+
185
+ def start_auto_updater
186
+ @auto_updater = AutoUpdater.new(
187
+ interval: @config.get("daemon.update_check_interval", 7 * 86_400),
188
+ delay: @config.get("daemon.update_delay", 2 * 86_400),
189
+ config: @config, logger: @logger
190
+ ) { reload! }.start
191
+ end
192
+
193
+ # `agents_control reload` and Router's /reload both send HUP here.
194
+ # The trap only spawns a thread — same reasoning as Bot#trap_signals'
195
+ # bare Queue#push: real work doesn't belong in signal-handler context.
196
+ def trap_reload
197
+ Signal.trap("HUP") { Thread.new { reload! } }
198
+ end
199
+
200
+ # exec, not fork, into the same entry point and arguments this
201
+ # process started with.
202
+ def reload!
203
+ script = $PROGRAM_NAME
204
+ return log("couldn't find #{script} to restart into — restart by hand") unless File.exist?(script)
205
+
206
+ failure = boot_failure(script)
207
+ return log("updated code doesn't start up — not restarting into it: #{failure}") if failure
208
+
209
+ log("restarting to pick up updated code")
210
+ stop
211
+ @reexec.call(RbConfig.ruby, script, *ARGV)
212
+ end
213
+
214
+ # stop tears down hooks and the bot before exec runs — no going back
215
+ # if the new code can't even boot, so `version` proves it first,
216
+ # side-effect-free and through the exact same require chain.
217
+ def boot_failure(script)
218
+ result = @executor.run(RbConfig.ruby, script, "version", timeout: 20)
219
+ result.success? ? nil : result.stderr.lines.last&.strip
220
+ end
221
+
170
222
  def api = @api ||= Channels::Telegram::Api.new(@secrets.get(:telegram_token))
171
223
 
172
224
  def install_agents
@@ -249,8 +301,13 @@ module AgentsControl
249
301
  end
250
302
 
251
303
  def start_bot
304
+ # Two independent Registry instances, not one shared: Router
305
+ # reaches one of them from its poll thread and the other from
306
+ # its attachment queue's own worker thread, and each scans iTerm2
307
+ # (and the process tree) on its own, so neither ever shares —
308
+ # or races — the other's cache. See Router#registry.
252
309
  router = Channels::Telegram::Router.new(
253
- api: api, registry: Registry.new, store: @store,
310
+ api: api, registry: Registry.new, attachment_registry: Registry.new, store: @store,
254
311
  config: @config, pending: pending, logger: @logger
255
312
  )
256
313
 
@@ -33,6 +33,8 @@ module AgentsControl
33
33
  event = agent.to_event(payload)
34
34
  return {} unless event
35
35
 
36
+ remember_session(event)
37
+
36
38
  reply = decide(event)
37
39
  return {} unless reply
38
40
 
@@ -44,6 +46,17 @@ module AgentsControl
44
46
 
45
47
  private
46
48
 
49
+ # Run for every event, even the ones that never make a sound
50
+ # (SessionStart is silent — see notifiable?) — that's the one
51
+ # moment Channel can tie this session to a specific tab without
52
+ # guessing. A failure here is ours, not the agent's: notify/ask
53
+ # still have to run, same reasoning as notify's own rescue below.
54
+ def remember_session(event)
55
+ @channel.remember_session(event)
56
+ rescue StandardError => e
57
+ log("couldn't remember session: #{e.class}")
58
+ end
59
+
47
60
  def decide(event)
48
61
  unless event.question?
49
62
  notify(event)
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgentsControl
4
+ # A git checkout's root, shared by whatever polls it — AutoReloader
5
+ # (restarts into code already pulled by someone else) and AutoUpdater
6
+ # (pulls it itself). Both need the same three things: find the
7
+ # binary, confirm there's actually a checkout here, run a command in
8
+ # it — this is that, written once.
9
+ class GitRoot
10
+ def initialize(root:, executor: Executor.new)
11
+ @root = root
12
+ @executor = executor
13
+ end
14
+
15
+ def checkout? = path && File.directory?(File.join(@root, ".git"))
16
+
17
+ def run(*args, timeout: 30)
18
+ return Executor::Result.new(stdout: "", stderr: "git not found", status: 127) unless path
19
+
20
+ @executor.run(path, "-C", @root, *args, timeout: timeout)
21
+ end
22
+
23
+ private
24
+
25
+ # false means "looked and didn't find it", so we don't search again on every call.
26
+ def path
27
+ @path = Which.find("git") || false if @path.nil?
28
+ @path || nil
29
+ end
30
+ end
31
+ end
@@ -57,11 +57,14 @@ module AgentsControl
57
57
 
58
58
  class TooLarge < StandardError; end
59
59
 
60
- # Seconds between attempts. A dropped connection on a phone's
61
- # network or a reconnecting VPN is gone again within seconds, and
62
- # the alternative is asking someone away from home to send the
63
- # file again.
64
- RETRY_AFTER = [1, 3, 5].freeze
60
+ # Doubling backoff: fast while a drop is likely to clear itself
61
+ # (a train going through a tunnel), spaced out once it looks like
62
+ # a real outage. Bounded by MAX_RETRY_ATTEMPTS, not left to grow
63
+ # forever, even though Router now runs this off its own queue and
64
+ # a slow retry no longer holds up anything else in the chat.
65
+ INITIAL_RETRY_DELAY = 2
66
+ MAX_RETRY_ATTEMPTS = 4
67
+ RETRY_AFTER = Array.new(MAX_RETRY_ATTEMPTS) { |attempt| INITIAL_RETRY_DELAY * (2**attempt) }.freeze
65
68
 
66
69
  def initialize(api:, dir: self.class.path, keep_days: 14, sleeper: ->(seconds) { sleep(seconds) })
67
70
  @api = api
@@ -241,7 +241,7 @@ module AgentsControl
241
241
  def read
242
242
  return {} unless ::File.exist?(@path)
243
243
 
244
- parsed = JSON.parse(::File.read(@path))
244
+ parsed = JSON.parse(::File.read(@path, encoding: "UTF-8"))
245
245
  parsed.is_a?(Hash) ? parsed : {}
246
246
  rescue JSON::ParserError
247
247
  {}
@@ -107,7 +107,7 @@ module AgentsControl
107
107
  def load_file
108
108
  return {} unless File.exist?(path)
109
109
 
110
- parsed = JSON.parse(File.read(path))
110
+ parsed = JSON.parse(File.read(path, encoding: "UTF-8"))
111
111
  parsed.is_a?(Hash) ? parsed : {}
112
112
  rescue JSON::ParserError, Errno::ENOENT
113
113
  # A corrupt file must not keep the daemon from starting. Losing
@@ -65,6 +65,15 @@ module AgentsControl
65
65
  entries.map { |entry| "#{prefix(entry[:role])} #{entry[:text]}" }.join("\n\n")
66
66
  end
67
67
 
68
+ SINGLE_FILE_TOOLS = %w[Read Edit Write NotebookEdit].freeze
69
+
70
+ # The N most recently touched files, most recent first and deduplicated.
71
+ def recent_files(count = 2)
72
+ return [] unless exists?
73
+
74
+ touched_file_paths(tail).reverse.uniq.first(count)
75
+ end
76
+
68
77
  private
69
78
 
70
79
  def tail
@@ -112,6 +121,22 @@ module AgentsControl
112
121
  end.join("\n").strip
113
122
  end
114
123
 
124
+ def touched_file_paths(raw)
125
+ raw.each_line.flat_map do |line|
126
+ blocks = JSON.parse(line).dig("message", "content")
127
+ blocks.is_a?(Array) ? blocks.filter_map { |block| touched_file_path(block) } : []
128
+ rescue JSON::ParserError
129
+ []
130
+ end
131
+ end
132
+
133
+ def touched_file_path(block)
134
+ return nil unless block["type"] == "tool_use" && SINGLE_FILE_TOOLS.include?(block["name"])
135
+
136
+ path = block.dig("input", "file_path")
137
+ path unless path.to_s.empty?
138
+ end
139
+
115
140
  def prefix(role)
116
141
  case role.to_s
117
142
  when "user" then "🙋"
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module AgentsControl
4
- VERSION = "0.4.0"
4
+ VERSION = "0.5.0"
5
5
  end
@@ -14,6 +14,7 @@ end
14
14
  require_relative "agents_control/version"
15
15
  require_relative "agents_control/executor"
16
16
  require_relative "agents_control/which"
17
+ require_relative "agents_control/git_root"
17
18
  require_relative "agents_control/session"
18
19
  require_relative "agents_control/process_probe"
19
20
  require_relative "agents_control/terminals/base"
@@ -47,6 +48,8 @@ require_relative "agents_control/channels/telegram/bot"
47
48
  require_relative "agents_control/anchors/scheduler"
48
49
  require_relative "agents_control/screen_watcher"
49
50
  require_relative "agents_control/rate_limit_watcher"
51
+ require_relative "agents_control/auto_updater"
52
+ require_relative "agents_control/auto_reloader"
50
53
  require_relative "agents_control/doctor"
51
54
  require_relative "agents_control/service"
52
55
  require_relative "agents_control/daemon"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: agents_control
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Sapar Kurmanov
@@ -40,6 +40,8 @@ files:
40
40
  - lib/agents_control/agents/base.rb
41
41
  - lib/agents_control/agents/claude_code.rb
42
42
  - lib/agents_control/anchors/scheduler.rb
43
+ - lib/agents_control/auto_reloader.rb
44
+ - lib/agents_control/auto_updater.rb
43
45
  - lib/agents_control/channels/base.rb
44
46
  - lib/agents_control/channels/telegram/api.rb
45
47
  - lib/agents_control/channels/telegram/bot.rb
@@ -57,6 +59,7 @@ files:
57
59
  - lib/agents_control/doctor.rb
58
60
  - lib/agents_control/event.rb
59
61
  - lib/agents_control/executor.rb
62
+ - lib/agents_control/git_root.rb
60
63
  - lib/agents_control/hooks/server.rb
61
64
  - lib/agents_control/inbox.rb
62
65
  - lib/agents_control/keyboard.rb