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.
@@ -42,29 +42,89 @@ module AgentsControl
42
42
  ["away", "intercept agent questions"],
43
43
  ["settings", "settings"],
44
44
  ["context", "the agent's recent messages", "N"],
45
+ ["getfile", "send a file — a tab number lists recent ones", "[N|path]"],
45
46
  ["screen", "show a tab's screen", "N"],
46
47
  ["focus", "switch to a tab", "N"],
47
48
  ["run", "run a command in a tab", "N command"],
48
49
  ["new", "new tab", "[directory]"],
50
+ ["reload", "restart the daemon into updated code"],
49
51
  ["help", "this help text"]
50
52
  ].freeze
51
53
 
52
54
  HELP = (["Commands:", ""] +
53
55
  COMMANDS.map { |name, text, hint| "/#{name}#{hint ? " #{hint}" : ''} — #{text}" }).join("\n")
54
56
 
57
+ # A single worker, not a thread per job: an album's later parts
58
+ # depend on a Store write its first part makes (see
59
+ # deliver_file's album_session), so jobs stay FIFO instead of
60
+ # racing each other the way Channel's resend_later would.
61
+ class AttachmentQueue
62
+ STOP = :stop
63
+
64
+ # setup runs once, on the worker thread itself, before its
65
+ # first job — Router uses it to tag the thread with its own
66
+ # Registry (see Router#registry), without this generic queue
67
+ # needing to know what a Registry is.
68
+ def initialize(&setup)
69
+ @jobs = Thread::Queue.new
70
+ @worker = Thread.new do
71
+ setup&.call
72
+ run
73
+ end
74
+ end
75
+
76
+ def call(&job) = @jobs << job
77
+
78
+ # Lets a queue's owner shut its worker down cleanly — tests
79
+ # build a real queue to prove ordering and must not leak the
80
+ # thread once they're done with it.
81
+ def stop
82
+ @jobs << STOP
83
+ @worker.join
84
+ end
85
+
86
+ private
87
+
88
+ def run
89
+ while (job = @jobs.pop) != STOP
90
+ job.call
91
+ end
92
+ end
93
+ end
94
+
95
+ # reload_trigger: Daemon#trap_reload is what actually acts on
96
+ # it; overridden in tests, since the real HUP's default action
97
+ # is to kill whatever process gets sent it.
98
+ #
99
+ # attachment_registry defaults to the same Registry as the rest
100
+ # of Router: a caller that wants the two threads (poll loop,
101
+ # attachment queue worker) to stop sharing a cache — which is
102
+ # the whole point in production — passes a second, independent
103
+ # one. See Daemon#start_bot and Router#registry.
55
104
  def initialize(api:, registry:, store:, config:, keyboards: nil, pending: nil, logger: nil,
56
- passphrase: nil, inbox: nil)
105
+ passphrase: nil, inbox: nil, reload_trigger: -> { Process.kill("HUP", Process.pid) },
106
+ attachment_registry: registry, attachment_queue: nil)
57
107
  @api = api
58
108
  @registry = registry
109
+ @attachment_registry = attachment_registry
59
110
  @store = store
60
111
  @config = config
61
112
  @keyboards = keyboards || Keyboards.new(store: store)
62
113
  @pending = pending
63
114
  @logger = logger
64
115
  @passphrase = passphrase || Passphrase.new
116
+ @reload_trigger = reload_trigger
65
117
  @inbox = inbox
118
+ @attachment_queue = attachment_queue || AttachmentQueue.new { Thread.current[:registry] = @attachment_registry }
66
119
  end
67
120
 
121
+ # Not called by the daemon today — process exit takes the
122
+ # worker thread with it either way — but a Router built
123
+ # directly (every test that doesn't go through build_router's
124
+ # synchronous stub) owns a real thread and needs a way to let
125
+ # go of it.
126
+ def stop = @attachment_queue.stop
127
+
68
128
  # Called once by the daemon on start; everything else here is
69
129
  # driven by an incoming update.
70
130
  def announce(chat_ids)
@@ -90,6 +150,13 @@ module AgentsControl
90
150
 
91
151
  private
92
152
 
153
+ # Thread-tagged, not a plain @registry read: AttachmentQueue's
154
+ # worker tags itself with @attachment_registry once at startup
155
+ # (see its setup block in #initialize), so its scans use that
156
+ # instead — independently of, and never racing, the poll
157
+ # thread's own cache.
158
+ def registry = Thread.current[:registry] || @registry
159
+
93
160
  def allowed?(chat_id)
94
161
  allowed = @config.get("telegram.allowed_chat_ids", [])
95
162
 
@@ -152,49 +219,96 @@ module AgentsControl
152
219
  type_into_session(chat_id, target, text)
153
220
  end
154
221
 
155
- # First, the exact session by session_id — unambiguous even when
156
- # several tabs share one cwd, and works for any session type:
157
- # /run and /screen remember the terminal's own session id, not
158
- # an agent's hook id, so this resolves directly whether the
159
- # target is an agent or a plain shell tab. Matching by cwd is
160
- # the fallback for when that tab has already closed — an agent
161
- # match wins there if one exists (the common case: replying to
162
- # an agent's own notification), otherwise any matching tab does
163
- # (a plain tab mid-interactive-command has no agent to prefer).
164
- #
165
- # Returns the session it typed into, or nil once it has said why not.
222
+ # Returns the session it typed into, or nil once it has either
223
+ # said why not or offered disambiguation buttons.
166
224
  def type_into_session(chat_id, target, text)
167
- session = session_for(chat_id, target)
225
+ session = resolve_session(chat_id, target) { |candidates| offer_disambiguation(chat_id, target, candidates, text) }
168
226
  execute(chat_id, session, text, show_result: !session.agent?) if session
169
227
  session
170
228
  end
171
229
 
230
+ # Same resolution, but with no text to hand over once it's
231
+ # picked — a plain "several tabs" message is the best this can do.
172
232
  def session_for(chat_id, target)
173
- exact = @registry.refresh.find(target["session_id"])
174
- return exact if exact && !exact.terminalless?
233
+ resolve_session(chat_id, target) { |candidates| ask_to_pick_a_number(chat_id, candidates) }
234
+ end
175
235
 
176
- matching = tabs_for(target["cwd"])
236
+ # Exact match first (learned_session_id picks up a mapping even
237
+ # if it was learned after this target was stored), then cwd as a
238
+ # fallback for a closed tab, preferring an agent match if one exists.
239
+ def resolve_session(chat_id, target)
240
+ exact = registry.refresh.find(learned_session_id(target))
241
+ return exact if exact && !exact.terminalless?
177
242
 
243
+ matching = tabs_for(target["cwd"], agents_only: target["from_agent"])
178
244
  return matching.first if matching.size == 1
179
245
 
180
- say(chat_id, if matching.empty?
181
- "#{target['label']} isn't waiting anymore, and I couldn't find the tab."
182
- else
183
- "#{target['label']} has several tabs — use /run NUMBER to pick one."
184
- end)
246
+ if matching.empty?
247
+ say(chat_id, "#{target['label']} isn't waiting anymore, and I couldn't find the tab.")
248
+ return nil
249
+ end
250
+
251
+ tiebreak_by_last_interaction(chat_id, matching) || yield(matching)
252
+ end
253
+
254
+ def learned_session_id(target) = @store.get(agent_session_key(target["session_id"])) || target["session_id"]
255
+
256
+ def agent_session_key(hook_session_id) = "agent_session:#{hook_session_id}"
257
+
258
+ # Two real tabs sharing a cwd can't be told apart by directory
259
+ # alone — whichever one the chat was already talking to wins.
260
+ def tiebreak_by_last_interaction(chat_id, matching)
261
+ last = @store.get(last_target_key(chat_id))
262
+ last && matching.find { |session| session.id == last["session_id"] }
263
+ end
264
+
265
+ def ask_to_pick_a_number(chat_id, candidates)
266
+ say(chat_id, "#{candidates.first.label} has several tabs — use /run NUMBER to pick one.")
185
267
  nil
186
268
  end
187
269
 
270
+ # A tap both delivers the held-up text and teaches the mapping
271
+ # for next time: once a human points at the right tab for this
272
+ # agent's hook session, every later message it sends resolves on
273
+ # its own — see learned_session_id.
274
+ def offer_disambiguation(chat_id, target, candidates, text)
275
+ rows = candidates.map { |session| [disambiguation_button(session, target, text)] }
276
+ say(chat_id, "#{candidates.first.label} has several tabs — which one?", markup: { inline_keyboard: rows })
277
+ nil
278
+ end
279
+
280
+ def disambiguation_button(session, target, text)
281
+ payload = { "action" => "disambiguate", "hook_session_id" => target["session_id"],
282
+ "session_id" => session.id, "text" => text }
283
+ { text: session.tty.to_s.sub(%r{\A/dev/}, ""), callback_data: @store.put(payload, ttl: 600) }
284
+ end
285
+
286
+ def resolve_disambiguation(chat_id, payload)
287
+ session = registry.refresh.find(payload["session_id"])
288
+ return say(chat_id, "That tab closed before you picked.") unless session
289
+
290
+ @store.put(session.id, ttl: REPLY_TARGET_TTL, key: agent_session_key(payload["hook_session_id"]))
291
+ sent = execute(chat_id, session, payload["text"], show_result: !session.agent?)
292
+ remember_reply(chat_id, sent, session)
293
+ end
294
+
188
295
  # A hook reports the directory the agent is in now, while the
189
296
  # tab and the process only know the one it was started in — so
190
297
  # an agent that cd'd into a subfolder matches no tab exactly.
191
298
  # The agent in the nearest directory above is that same agent;
192
299
  # a plain shell up there is just a neighbour.
193
- def tabs_for(cwd)
194
- tabs = @registry.sessions.reject(&:terminalless?)
300
+ #
301
+ # A message that came from an agent is answered only to an agent:
302
+ # once that agent is gone, a shell left in the same folder is not
303
+ # its successor, and the reply would be run there as a command.
304
+ def tabs_for(cwd, agents_only: false)
305
+ tabs = registry.sessions.reject(&:terminalless?)
195
306
 
196
307
  same = tabs.select { |s| s.cwd == cwd }
197
- return same.select(&:agent?).then { |agents| agents.empty? ? same : agents } unless same.empty?
308
+ unless same.empty?
309
+ agents = same.select(&:agent?)
310
+ return agents.empty? && !agents_only ? same : agents
311
+ end
198
312
 
199
313
  above = tabs.select { |s| s.agent? && !s.cwd.to_s.empty? && cwd.to_s.start_with?(File.join(s.cwd, "")) }
200
314
  nearest = above.map { |s| s.cwd.length }.max
@@ -202,7 +316,7 @@ module AgentsControl
202
316
  end
203
317
 
204
318
  # A file from the phone becomes a file on disk, and the agent is
205
- # handed its path.
319
+ # handed its path — fetched via AttachmentQueue, not here directly.
206
320
  #
207
321
  # A path and not a link: Telegram serves file bytes from a URL
208
322
  # with the bot token in it, so pasting that into a pane would
@@ -210,21 +324,58 @@ module AgentsControl
210
324
  # the shell history — and a leaked token is remote code
211
325
  # execution on this machine.
212
326
  def receive(chat_id, message, attachment)
327
+ @attachment_queue.call { deliver_attachment(chat_id, message, attachment) }
328
+ end
329
+
330
+ def deliver_attachment(chat_id, message, attachment)
213
331
  path = inbox.fetch(attachment)
214
332
  log("received #{attachment.kind}: #{File.basename(path)}")
215
333
 
216
334
  deliver_file(chat_id, message, path)
217
335
  rescue Inbox::TooLarge => e
218
336
  say(chat_id, "That file is #{e.message}.")
219
- rescue Api::Error, SystemCallError => e
337
+ rescue Api::Unavailable, Api::TooManyRequests, SystemCallError => e
338
+ # All three are transient — outlasted Inbox's own retries,
339
+ # or Telegram rate-limiting for a moment — so the file_id is
340
+ # still good and a second try is worth offering. A non-network
341
+ # Api::Error below is not: whatever Telegram objected to will
342
+ # still be true next time.
343
+ offer_retry(chat_id, message, "Couldn't save that file: #{@api.redact(e.message)}")
344
+ rescue Api::Error => e
220
345
  say(chat_id, "Couldn't save that file: #{@api.redact(e.message)}")
346
+ rescue StandardError => e
347
+ # Runs on the queue's worker thread, away from Bot#handle's
348
+ # own backstop — without this, an escaped exception here
349
+ # would vanish silently instead of getting logged.
350
+ log("failed to handle #{attachment.kind}: #{e.class}: #{@api.redact(e.message)}")
351
+ end
352
+
353
+ RETRY_BUTTON_TTL = 1800
354
+
355
+ def offer_retry(chat_id, message, text)
356
+ payload = { "action" => "retry_attachment", "message" => message }
357
+ markup = { inline_keyboard: [[{ text: "🔄 Try again",
358
+ callback_data: @store.put(payload, ttl: RETRY_BUTTON_TTL) }]] }
359
+ say(chat_id, text, markup: markup)
360
+ end
361
+
362
+ # Stores the whole message, not just the file_id: deliver_file
363
+ # also reads its caption, reply, and album id.
364
+ def retry_attachment(chat_id, payload)
365
+ message = payload["message"]
366
+ attachment = Inbox.attachment(message)
367
+ return say(chat_id, "That file's gone now — send it again.") unless attachment
368
+
369
+ receive(chat_id, message, attachment)
221
370
  end
222
371
 
223
- # Three ways to say where it goes, in order of how explicit they
224
- # are: a caption naming a tab, a reply to something already tied
225
- # to a session, or neither — in which case the path is just
226
- # handed back, since guessing at a target for a file is how it
227
- # ends up pasted into the wrong project.
372
+ # Ways to say where it goes, in order of how explicit they are: a
373
+ # caption naming a tab, a reply to something already tied to a
374
+ # session, the rest of an album, or the session that spoke last —
375
+ # for an agent only, since a bare path typed into a shell is a
376
+ # command, not a file handed over. With none of those the path is
377
+ # just handed back: guessing further is how a file ends up pasted
378
+ # into the wrong project.
228
379
  def deliver_file(chat_id, message, path)
229
380
  caption = message["caption"].to_s.strip
230
381
  album = album_key(chat_id, message)
@@ -245,6 +396,16 @@ module AgentsControl
245
396
  return execute(chat_id, session, with_path("", path))
246
397
  end
247
398
 
399
+ if (last = @store.get(last_target_key(chat_id)))
400
+ session = session_for(chat_id, last)
401
+ return unless session
402
+
403
+ if session.agent?
404
+ execute(chat_id, session, with_path(caption, path))
405
+ return remember_album(album, session)
406
+ end
407
+ end
408
+
248
409
  say(chat_id, "Saved:\n\n`#{path}`\n\nReply to a session's message with a file to hand it " \
249
410
  "straight over, or caption it `/run N`.")
250
411
  end
@@ -267,7 +428,7 @@ module AgentsControl
267
428
 
268
429
  def album_session(key)
269
430
  id = key && @store.get(key)
270
- session = id && @registry.refresh.find(id)
431
+ session = id && registry.refresh.find(id)
271
432
  session if session&.agent? && !session.terminalless?
272
433
  end
273
434
 
@@ -316,6 +477,8 @@ module AgentsControl
316
477
  when "/away" then toggle_away(chat_id, argument)
317
478
  when "/settings" then show_settings(chat_id)
318
479
  when "/context" then context(chat_id, argument)
480
+ when "/getfile" then getfile(chat_id, argument)
481
+ when "/reload" then reload_daemon(chat_id)
319
482
  when "/status" then status(chat_id)
320
483
  else say(chat_id, "I don't know that command.\n\n#{HELP}")
321
484
  end
@@ -324,22 +487,23 @@ module AgentsControl
324
487
  # A shared refresh for both lists — otherwise the same session's
325
488
  # number could differ between "All tabs" and "Agents".
326
489
  def agents_list(chat_id)
327
- universe = @registry.refresh.sessions
490
+ universe = registry.refresh.sessions
328
491
  list(chat_id, universe.select(&:agent?), "🤖 Agent sessions", universe: universe)
329
492
  end
330
493
 
331
494
  def tabs_list(chat_id)
332
- universe = @registry.refresh.sessions
333
- list(chat_id, universe, "🖥 All tabs", universe: universe)
495
+ universe = registry.refresh.sessions
496
+ list(chat_id, universe, "🖥 All tabs", universe: universe, with_focus_buttons: true)
334
497
  end
335
498
 
336
- def list(chat_id, sessions, title, universe: sessions)
499
+ def list(chat_id, sessions, title, universe: sessions, with_focus_buttons: false)
337
500
  if sessions.empty?
338
501
  return say(chat_id, "#{title}\n\nEmpty.", markup: @keyboards.list_actions)
339
502
  end
340
503
 
504
+ markup = with_focus_buttons ? @keyboards.tabs_markup(sessions, universe: universe) : @keyboards.list_actions
341
505
  say(chat_id, @keyboards.render_list(sessions, universe: universe, chat_id: chat_id, title: title),
342
- markup: @keyboards.list_actions)
506
+ markup: markup)
343
507
  end
344
508
 
345
509
  def screen(chat_id, argument)
@@ -348,8 +512,9 @@ module AgentsControl
348
512
 
349
513
  def focus(chat_id, argument)
350
514
  with_session(chat_id, argument) do |session|
351
- ok = @registry.backend_for(session).focus(session.id)
352
- say(chat_id, ok ? "Switched to #{session.label}." : "Couldn't switch.")
515
+ ok = registry.backend_for(session).focus(session.id)
516
+ sent = say(chat_id, ok ? "Switched to #{session.label}." : "Couldn't switch.")
517
+ remember_reply(chat_id, sent, session) if ok
353
518
  end
354
519
  end
355
520
 
@@ -565,7 +730,7 @@ module AgentsControl
565
730
  "machine if it's lost.")
566
731
  end
567
732
 
568
- session = @registry.refresh.find(challenge["session_id"])
733
+ session = registry.refresh.find(challenge["session_id"])
569
734
  return say(chat_id, "That session is already closed.") unless session
570
735
 
571
736
  execute(chat_id, session, challenge["text"], show_result: !session.agent?, vetted: true)
@@ -627,7 +792,7 @@ module AgentsControl
627
792
  return confirm_policy(chat_id, session, command, verdict.reason) if verdict.confirm?
628
793
  end
629
794
 
630
- backend = @registry.backend_for(session)
795
+ backend = registry.backend_for(session)
631
796
  before ||= capture_screen(session, lines: run_result_lines) if show_result
632
797
 
633
798
  ok = backend.send_text(session.id, command, newline: false) &&
@@ -736,13 +901,18 @@ module AgentsControl
736
901
  end
737
902
 
738
903
  def create_tab(chat_id, directory)
739
- backend = @registry.available_backends.first
904
+ backend = registry.available_backends.first
740
905
  return say(chat_id, "No terminal available.") unless backend
741
906
 
742
907
  id = backend.create_tab(cwd: directory.empty? ? nil : directory)
743
908
  say(chat_id, id ? "Created tab #{id}." : "Couldn't create a tab.")
744
909
  end
745
910
 
911
+ def reload_daemon(chat_id)
912
+ say(chat_id, "🔄 Restarting…")
913
+ @reload_trigger.call
914
+ end
915
+
746
916
  # Interception is turned on explicitly: while a human is at the
747
917
  # keyboard, they'll answer in the terminal faster themselves, and
748
918
  # a busy hook keeps the dialog from ever reaching the screen at all.
@@ -784,6 +954,47 @@ module AgentsControl
784
954
  end
785
955
  end
786
956
 
957
+ RECENT_FILES_OFFERED = 2
958
+ TAB_NUMBER = /\A\d+\z/
959
+
960
+ def getfile(chat_id, argument)
961
+ argument = argument.to_s.strip
962
+ return send_file(chat_id, argument) unless argument.empty? || argument.match?(TAB_NUMBER)
963
+ return with_session(chat_id, argument) { |session| offer_recent_files(chat_id, session) } unless argument.empty?
964
+
965
+ target = @store.get(last_target_key(chat_id))
966
+ return say(chat_id, "No active conversation yet — try /getfile NUMBER or /getfile PATH.") unless target
967
+
968
+ session = session_for(chat_id, target)
969
+ offer_recent_files(chat_id, session) if session
970
+ end
971
+
972
+ def offer_recent_files(chat_id, session)
973
+ transcript = Transcript.for_cwd(session.cwd, root: transcript_root)
974
+ paths = transcript.recent_files(RECENT_FILES_OFFERED)
975
+
976
+ return say(chat_id, "No recently touched files found for #{session.label}.") if paths.empty?
977
+
978
+ markup = { inline_keyboard: paths.map { |path| [file_button(path)] } }
979
+ say(chat_id, "📄 Recent files in #{session.label}:", markup: markup)
980
+ end
981
+
982
+ def file_button(path)
983
+ { text: File.basename(path)[0, 60],
984
+ callback_data: @store.put({ "action" => "getfile", "path" => path }, ttl: 600) }
985
+ end
986
+
987
+ # No path restricted here, same as /run: anyone who can reach
988
+ # this chat can already `cat` anything via a shell.
989
+ def send_file(chat_id, path)
990
+ expanded = File.expand_path(path)
991
+ return say(chat_id, "No such file:\n\n`#{path}`") unless File.file?(expanded)
992
+
993
+ @api.send_document(chat_id: chat_id, path: expanded)
994
+ rescue Api::Error, SystemCallError, ArgumentError => e
995
+ say(chat_id, "Couldn't send that file: #{@api.redact(e.message)}")
996
+ end
997
+
787
998
  # Not necessarily an immediate reply, but whenever convenient — TTL 30 days, not a day.
788
999
  REPLY_TARGET_TTL = 30 * 86_400
789
1000
 
@@ -801,8 +1012,8 @@ module AgentsControl
801
1012
  def last_target_key(chat_id) = "last:#{chat_id}"
802
1013
 
803
1014
  def status(chat_id)
804
- sessions = @registry.refresh.sessions
805
- backends = @registry.available_backends.map(&:name).join(", ")
1015
+ sessions = registry.refresh.sessions
1016
+ backends = registry.available_backends.map(&:name).join(", ")
806
1017
 
807
1018
  say(chat_id, "Tabs: #{sessions.size}\nAgents: #{sessions.count(&:agent?)}\n" \
808
1019
  "Backends: #{backends.empty? ? 'none' : backends}\n" \
@@ -859,11 +1070,14 @@ module AgentsControl
859
1070
  when "answer" then answer_question(chat_id, payload)
860
1071
  when "compose" then start_compose(chat_id, payload)
861
1072
  when "transcript" then show_transcript(chat_id, payload)
1073
+ when "getfile" then send_file(chat_id, payload["path"])
862
1074
  when "setting" then change_setting(chat_id, payload)
863
1075
  when "menu_choice" then choose_menu_option(chat_id, payload)
864
1076
  when "passphrase_wizard" then start_wizard(chat_id)
865
1077
  when "passphrase_never" then stop_offering(chat_id)
866
1078
  when "ask_question_choice" then answer_ask_user_question(chat_id, payload)
1079
+ when "disambiguate" then resolve_disambiguation(chat_id, payload)
1080
+ when "retry_attachment" then retry_attachment(chat_id, payload)
867
1081
  else act_on_session(chat_id, payload)
868
1082
  end
869
1083
  end
@@ -902,10 +1116,10 @@ module AgentsControl
902
1116
  # way a human would from the keyboard. There's no structured
903
1117
  # reply here, unlike with hooks.
904
1118
  def choose_menu_option(chat_id, payload)
905
- session = @registry.refresh.find(payload["session_id"])
1119
+ session = registry.refresh.find(payload["session_id"])
906
1120
  return say(chat_id, "That session is already closed.") unless session
907
1121
 
908
- ok = @registry.backend_for(session).send_text(session.id, payload["choice"].to_s)
1122
+ ok = registry.backend_for(session).send_text(session.id, payload["choice"].to_s)
909
1123
  say(chat_id, ok ? "Chose \"#{payload['choice']}\" in #{session.label}." : "Couldn't send the choice.")
910
1124
  end
911
1125
 
@@ -914,10 +1128,10 @@ module AgentsControl
914
1128
  # through the hook — it's always been resolved by hand at the
915
1129
  # terminal, and this just sends the same keystroke a human would.
916
1130
  def answer_ask_user_question(chat_id, payload)
917
- session = @registry.refresh.find(payload["session_id"])
1131
+ session = registry.refresh.find(payload["session_id"])
918
1132
  return say(chat_id, "That session is already closed.") unless session
919
1133
 
920
- ok = @registry.backend_for(session).send_text(session.id, payload["choice"].to_s)
1134
+ ok = registry.backend_for(session).send_text(session.id, payload["choice"].to_s)
921
1135
  say(chat_id, ok ? "Sent to #{session.label}." : "Couldn't send the choice.")
922
1136
  end
923
1137
 
@@ -929,7 +1143,7 @@ module AgentsControl
929
1143
  end
930
1144
 
931
1145
  def act_on_session(chat_id, payload)
932
- session = @registry.refresh.find(payload["session_id"])
1146
+ session = registry.refresh.find(payload["session_id"])
933
1147
  return say(chat_id, "That session is already closed.") unless session
934
1148
 
935
1149
  case payload["action"]
@@ -944,8 +1158,9 @@ module AgentsControl
944
1158
  end
945
1159
 
946
1160
  def focus_session(chat_id, session)
947
- @registry.backend_for(session).focus(session.id)
948
- say(chat_id, "Switched to #{session.label}.")
1161
+ registry.backend_for(session).focus(session.id)
1162
+ sent = say(chat_id, "Switched to #{session.label}.")
1163
+ remember_reply(chat_id, sent, session)
949
1164
  end
950
1165
 
951
1166
  # The screen is the first choice, not a fallback: it shows what's
@@ -966,7 +1181,7 @@ module AgentsControl
966
1181
  end
967
1182
 
968
1183
  def capture_screen(session, lines: @config.get("terminal.context_lines", 80))
969
- @registry.backend_for(session).capture(session.id, lines: lines)
1184
+ registry.backend_for(session).capture(session.id, lines: lines)
970
1185
  rescue Terminals::Unsupported
971
1186
  nil
972
1187
  end
@@ -992,7 +1207,7 @@ module AgentsControl
992
1207
  end
993
1208
 
994
1209
  def close_session(chat_id, session)
995
- ok = @registry.backend_for(session).close(session.id)
1210
+ ok = registry.backend_for(session).close(session.id)
996
1211
  say(chat_id, ok ? "Closed #{session.label}." : "Couldn't close it.")
997
1212
  end
998
1213
 
@@ -1000,7 +1215,7 @@ module AgentsControl
1000
1215
  id = @keyboards.session_for(chat_id, number.to_s.strip)
1001
1216
  return say(chat_id, "No such number — pull up the list again.") unless id
1002
1217
 
1003
- session = @registry.refresh.find(id)
1218
+ session = registry.refresh.find(id)
1004
1219
  return say(chat_id, "That session is already closed.") unless session
1005
1220
 
1006
1221
  yield(session)
@@ -100,21 +100,16 @@ module AgentsControl
100
100
  Finds the process holding the hooks port and asks it to exit.
101
101
  Useful when an instance was left running somewhere and a new one won't start.
102
102
  TEXT
103
- def stop
104
- port = config.get("hooks.port", Daemon::DEFAULT_PORT).to_i
105
- # argv array, not a shell string: no reason to trust a shell to
106
- # parse a port number pulled from config.
107
- out, = Open3.capture3("lsof", "-nP", "-iTCP:#{port}", "-sTCP:LISTEN", "-t")
108
- pids = out.split
109
- return say("Nothing is running.", :yellow) if pids.empty?
103
+ def stop = signal_daemon("TERM", "Stopped", "stop")
110
104
 
111
- pids.each do |pid|
112
- Process.kill("TERM", pid.to_i)
113
- say("Stopped #{pid}", :green)
114
- rescue Errno::ESRCH, Errno::EPERM => e
115
- say("Couldn't stop #{pid}: #{e.message}", :red)
116
- end
117
- end
105
+ desc "reload", "Restart the running daemon into updated code"
106
+ long_desc <<~TEXT
107
+ Finds the process holding the hooks port and asks it to restart
108
+ itself in place — exec, not a fresh process, so it comes back up
109
+ in the same terminal tab if it was running in one. Run this after
110
+ a `git pull`, or after editing a file by hand.
111
+ TEXT
112
+ def reload = signal_daemon("HUP", "Asked to reload", "reload")
118
113
 
119
114
  desc "doctor", "Check that everything is in place"
120
115
  long_desc <<~TEXT
@@ -180,6 +175,22 @@ module AgentsControl
180
175
 
181
176
  private
182
177
 
178
+ # argv array, not a shell string: no reason to trust a shell to
179
+ # parse a port number pulled from config.
180
+ def signal_daemon(signal, verb, action)
181
+ port = config.get("hooks.port", Daemon::DEFAULT_PORT).to_i
182
+ out, = Open3.capture3("lsof", "-nP", "-iTCP:#{port}", "-sTCP:LISTEN", "-t")
183
+ pids = out.split
184
+ return say("Nothing is running.", :yellow) if pids.empty?
185
+
186
+ pids.each do |pid|
187
+ Process.kill(signal, pid.to_i)
188
+ say("#{verb} #{pid}", :green)
189
+ rescue Errno::ESRCH, Errno::EPERM => e
190
+ say("Couldn't #{action} #{pid}: #{e.message}", :red)
191
+ end
192
+ end
193
+
183
194
  # Offered at the end of setup rather than left to be found later:
184
195
  # finishing setup is the moment the bot can start typing into this
185
196
  # machine, and the only moment its owner is guaranteed to be
@@ -90,6 +90,20 @@ module AgentsControl
90
90
  "watch_menus" => true,
91
91
  "menu_poll_interval" => 20,
92
92
  "rate_limit_poll_interval" => 60
93
+ },
94
+ "daemon" => {
95
+ # auto_reload: restart into code someone already pulled by hand
96
+ # (or had an agent pull) — on by default, since nothing here
97
+ # decided on its own to trust new code, it's just not making
98
+ # you remember to restart after you already did. auto_update is
99
+ # the other half: fetching that code in the first place,
100
+ # unattended — off by default, since that part IS deciding to
101
+ # trust whatever's newest upstream without anyone looking.
102
+ # See AutoReloader and AutoUpdater.
103
+ "auto_reload" => true,
104
+ "auto_update" => false,
105
+ "update_check_interval" => 7 * 86_400,
106
+ "update_delay" => 2 * 86_400
93
107
  }
94
108
  }.freeze
95
109