agents_control 0.4.1 → 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.")
267
+ nil
268
+ end
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 })
185
277
  nil
186
278
  end
187
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,14 +324,49 @@ 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
372
  # Ways to say where it goes, in order of how explicit they are: a
@@ -279,7 +428,7 @@ module AgentsControl
279
428
 
280
429
  def album_session(key)
281
430
  id = key && @store.get(key)
282
- session = id && @registry.refresh.find(id)
431
+ session = id && registry.refresh.find(id)
283
432
  session if session&.agent? && !session.terminalless?
284
433
  end
285
434
 
@@ -328,6 +477,8 @@ module AgentsControl
328
477
  when "/away" then toggle_away(chat_id, argument)
329
478
  when "/settings" then show_settings(chat_id)
330
479
  when "/context" then context(chat_id, argument)
480
+ when "/getfile" then getfile(chat_id, argument)
481
+ when "/reload" then reload_daemon(chat_id)
331
482
  when "/status" then status(chat_id)
332
483
  else say(chat_id, "I don't know that command.\n\n#{HELP}")
333
484
  end
@@ -336,22 +487,23 @@ module AgentsControl
336
487
  # A shared refresh for both lists — otherwise the same session's
337
488
  # number could differ between "All tabs" and "Agents".
338
489
  def agents_list(chat_id)
339
- universe = @registry.refresh.sessions
490
+ universe = registry.refresh.sessions
340
491
  list(chat_id, universe.select(&:agent?), "🤖 Agent sessions", universe: universe)
341
492
  end
342
493
 
343
494
  def tabs_list(chat_id)
344
- universe = @registry.refresh.sessions
345
- 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)
346
497
  end
347
498
 
348
- def list(chat_id, sessions, title, universe: sessions)
499
+ def list(chat_id, sessions, title, universe: sessions, with_focus_buttons: false)
349
500
  if sessions.empty?
350
501
  return say(chat_id, "#{title}\n\nEmpty.", markup: @keyboards.list_actions)
351
502
  end
352
503
 
504
+ markup = with_focus_buttons ? @keyboards.tabs_markup(sessions, universe: universe) : @keyboards.list_actions
353
505
  say(chat_id, @keyboards.render_list(sessions, universe: universe, chat_id: chat_id, title: title),
354
- markup: @keyboards.list_actions)
506
+ markup: markup)
355
507
  end
356
508
 
357
509
  def screen(chat_id, argument)
@@ -360,8 +512,9 @@ module AgentsControl
360
512
 
361
513
  def focus(chat_id, argument)
362
514
  with_session(chat_id, argument) do |session|
363
- ok = @registry.backend_for(session).focus(session.id)
364
- 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
365
518
  end
366
519
  end
367
520
 
@@ -577,7 +730,7 @@ module AgentsControl
577
730
  "machine if it's lost.")
578
731
  end
579
732
 
580
- session = @registry.refresh.find(challenge["session_id"])
733
+ session = registry.refresh.find(challenge["session_id"])
581
734
  return say(chat_id, "That session is already closed.") unless session
582
735
 
583
736
  execute(chat_id, session, challenge["text"], show_result: !session.agent?, vetted: true)
@@ -639,7 +792,7 @@ module AgentsControl
639
792
  return confirm_policy(chat_id, session, command, verdict.reason) if verdict.confirm?
640
793
  end
641
794
 
642
- backend = @registry.backend_for(session)
795
+ backend = registry.backend_for(session)
643
796
  before ||= capture_screen(session, lines: run_result_lines) if show_result
644
797
 
645
798
  ok = backend.send_text(session.id, command, newline: false) &&
@@ -748,13 +901,18 @@ module AgentsControl
748
901
  end
749
902
 
750
903
  def create_tab(chat_id, directory)
751
- backend = @registry.available_backends.first
904
+ backend = registry.available_backends.first
752
905
  return say(chat_id, "No terminal available.") unless backend
753
906
 
754
907
  id = backend.create_tab(cwd: directory.empty? ? nil : directory)
755
908
  say(chat_id, id ? "Created tab #{id}." : "Couldn't create a tab.")
756
909
  end
757
910
 
911
+ def reload_daemon(chat_id)
912
+ say(chat_id, "🔄 Restarting…")
913
+ @reload_trigger.call
914
+ end
915
+
758
916
  # Interception is turned on explicitly: while a human is at the
759
917
  # keyboard, they'll answer in the terminal faster themselves, and
760
918
  # a busy hook keeps the dialog from ever reaching the screen at all.
@@ -796,6 +954,47 @@ module AgentsControl
796
954
  end
797
955
  end
798
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
+
799
998
  # Not necessarily an immediate reply, but whenever convenient — TTL 30 days, not a day.
800
999
  REPLY_TARGET_TTL = 30 * 86_400
801
1000
 
@@ -813,8 +1012,8 @@ module AgentsControl
813
1012
  def last_target_key(chat_id) = "last:#{chat_id}"
814
1013
 
815
1014
  def status(chat_id)
816
- sessions = @registry.refresh.sessions
817
- backends = @registry.available_backends.map(&:name).join(", ")
1015
+ sessions = registry.refresh.sessions
1016
+ backends = registry.available_backends.map(&:name).join(", ")
818
1017
 
819
1018
  say(chat_id, "Tabs: #{sessions.size}\nAgents: #{sessions.count(&:agent?)}\n" \
820
1019
  "Backends: #{backends.empty? ? 'none' : backends}\n" \
@@ -871,11 +1070,14 @@ module AgentsControl
871
1070
  when "answer" then answer_question(chat_id, payload)
872
1071
  when "compose" then start_compose(chat_id, payload)
873
1072
  when "transcript" then show_transcript(chat_id, payload)
1073
+ when "getfile" then send_file(chat_id, payload["path"])
874
1074
  when "setting" then change_setting(chat_id, payload)
875
1075
  when "menu_choice" then choose_menu_option(chat_id, payload)
876
1076
  when "passphrase_wizard" then start_wizard(chat_id)
877
1077
  when "passphrase_never" then stop_offering(chat_id)
878
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)
879
1081
  else act_on_session(chat_id, payload)
880
1082
  end
881
1083
  end
@@ -914,10 +1116,10 @@ module AgentsControl
914
1116
  # way a human would from the keyboard. There's no structured
915
1117
  # reply here, unlike with hooks.
916
1118
  def choose_menu_option(chat_id, payload)
917
- session = @registry.refresh.find(payload["session_id"])
1119
+ session = registry.refresh.find(payload["session_id"])
918
1120
  return say(chat_id, "That session is already closed.") unless session
919
1121
 
920
- 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)
921
1123
  say(chat_id, ok ? "Chose \"#{payload['choice']}\" in #{session.label}." : "Couldn't send the choice.")
922
1124
  end
923
1125
 
@@ -926,10 +1128,10 @@ module AgentsControl
926
1128
  # through the hook — it's always been resolved by hand at the
927
1129
  # terminal, and this just sends the same keystroke a human would.
928
1130
  def answer_ask_user_question(chat_id, payload)
929
- session = @registry.refresh.find(payload["session_id"])
1131
+ session = registry.refresh.find(payload["session_id"])
930
1132
  return say(chat_id, "That session is already closed.") unless session
931
1133
 
932
- 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)
933
1135
  say(chat_id, ok ? "Sent to #{session.label}." : "Couldn't send the choice.")
934
1136
  end
935
1137
 
@@ -941,7 +1143,7 @@ module AgentsControl
941
1143
  end
942
1144
 
943
1145
  def act_on_session(chat_id, payload)
944
- session = @registry.refresh.find(payload["session_id"])
1146
+ session = registry.refresh.find(payload["session_id"])
945
1147
  return say(chat_id, "That session is already closed.") unless session
946
1148
 
947
1149
  case payload["action"]
@@ -956,8 +1158,9 @@ module AgentsControl
956
1158
  end
957
1159
 
958
1160
  def focus_session(chat_id, session)
959
- @registry.backend_for(session).focus(session.id)
960
- 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)
961
1164
  end
962
1165
 
963
1166
  # The screen is the first choice, not a fallback: it shows what's
@@ -978,7 +1181,7 @@ module AgentsControl
978
1181
  end
979
1182
 
980
1183
  def capture_screen(session, lines: @config.get("terminal.context_lines", 80))
981
- @registry.backend_for(session).capture(session.id, lines: lines)
1184
+ registry.backend_for(session).capture(session.id, lines: lines)
982
1185
  rescue Terminals::Unsupported
983
1186
  nil
984
1187
  end
@@ -1004,7 +1207,7 @@ module AgentsControl
1004
1207
  end
1005
1208
 
1006
1209
  def close_session(chat_id, session)
1007
- ok = @registry.backend_for(session).close(session.id)
1210
+ ok = registry.backend_for(session).close(session.id)
1008
1211
  say(chat_id, ok ? "Closed #{session.label}." : "Couldn't close it.")
1009
1212
  end
1010
1213
 
@@ -1012,7 +1215,7 @@ module AgentsControl
1012
1215
  id = @keyboards.session_for(chat_id, number.to_s.strip)
1013
1216
  return say(chat_id, "No such number — pull up the list again.") unless id
1014
1217
 
1015
- session = @registry.refresh.find(id)
1218
+ session = registry.refresh.find(id)
1016
1219
  return say(chat_id, "That session is already closed.") unless session
1017
1220
 
1018
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