brainiac-discord 0.0.27 → 0.0.29

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7563493f0aae0dd1ad5202d8678cfcf8fef45eaac9a2658bcc2a9d42e010724e
4
- data.tar.gz: 793c7afe6632a53152147e67ea9d71addd7c6ff785d4a3b2a76df3102a237f6e
3
+ metadata.gz: 9c8d83162c620164fbcc3a116fa304d2d54edd955bd34ebfb7e05e1e0698e842
4
+ data.tar.gz: 54eb4a5797ec5d2400b53874bf68079bfb7a3f93e81fe4f9ceeb2e5f0dfb1841
5
5
  SHA512:
6
- metadata.gz: 0a59d8cf3ad1d071e987a45ae79ef2364f5409f072354d127bbf8e69b6656888319bd13f86f7c600a9a615ef82f858ef9b69306a0f768cb889fe1eedec91137c
7
- data.tar.gz: 3074e7b2d22895f1218de2bf088ff5e9cd7c441c0836b59011081f04d6cb8c0ae573b8b4d705d31843b1191afa0d01eb3db1b7c8914338fe7f56593a1e79e892
6
+ metadata.gz: 5d2c443f8b84699dbd009d7e2e93410c7477bd65171cc881202c77feffc0cbc1e600cb89db15b0c48fcdfb098626a478295169abf6a59eea852afd3b8013352b
7
+ data.tar.gz: 63c0ec793904a0d07085a8cb61e2e02a2139b3170398761eba8f6dbd633b8776bb8113892c1304c8c0befd602c935881559f801a884ba7eb72c12df2ea571ac2
data/README.md CHANGED
@@ -138,6 +138,50 @@ Stored in `~/.brainiac/discord.json`:
138
138
 
139
139
  Bot tokens live in `~/.brainiac/agents.json` as each agent's `env.DISCORD_BOT_TOKEN`, not in `discord.json`.
140
140
 
141
+ ## Multi-machine
142
+
143
+ When Brainiac runs on several machines behind a `brainiac-hub`, only one of them (the leader) opens the Discord gateway connections. Two machines holding the same bot's gateway would both answer every message. The plugin follows the core's `:hub_leader_acquired` and `:hub_leader_lost` hooks: it starts every bot when this machine becomes the leader and closes them when it stops being the leader.
144
+
145
+ A machine that is not the leader can still post to Discord, because posting uses the REST API and the token in `agents.json`. Without a hub configured, nothing changes.
146
+
147
+ ### Sending work to a machine
148
+
149
+ The leader hears every message and decides which machine runs it:
150
+
151
+ 1. **`[machine:<name>]` in the message** sends it to that machine. In a thread, the tag also moves the thread there.
152
+ 2. **A thread stays with its machine.** The machine that holds a thread's worktree owns it (hub key `discord:<agent>:<thread id>`), and follow-ups go back to it without a tag.
153
+ 3. Anything else runs on the leader.
154
+
155
+ ```
156
+ @Galen [machine:mini] fix the flaky login test
157
+ ```
158
+
159
+ The leader hands the raw message to the other machine through the hub. That machine runs the agent in its own worktree and posts the reply itself. Each reply ends with a small `ran on <machine>` line; set `"machine_footer": false` in `discord.json` to drop it.
160
+
161
+ What the leader tells you in the channel:
162
+
163
+ | Situation | What happens |
164
+ |-----------|--------------|
165
+ | The tag names a machine the hub has never seen | Nothing runs. The leader lists the known machines |
166
+ | The machine you asked for is offline, new conversation | The hub's next machine by priority runs it, and the leader says which |
167
+ | The machine you asked for is offline, existing thread | The thread stays with its owner, and the leader says so |
168
+ | The thread's owner is offline | The message waits in the hub for it. Send it again with `[machine:<name>]` to move the thread |
169
+ | The hub cannot be reached while handing work over | Nothing runs. Send it again |
170
+
171
+ Messages sent while a session is running, and the ❌ ❔ ❓ 🧠 reactions, follow the message to the machine running it. A thread being archived is passed to the machine that holds its worktree so it can clean up.
172
+
173
+ Limits:
174
+
175
+ - Every machine that may be asked needs the agent in `agents.json` with the same `DISCORD_BOT_TOKEN`, the same `discord.json` (channel-to-project mappings, authorized users), the project registered, and the CLI logged in. A machine without the agent's token ignores the work and the channel sees no reply.
176
+ - Moving a thread carries over only what was pushed. The new machine makes its own worktree from the thread's branch on the remote (`discord-<agent>-<id>`), or from the default branch if nothing was pushed. A machine that already has the thread's branch (the thread is coming back to it) reuses its old worktree as it was, so pull there if another machine pushed since. The old machine keeps its worktree until the thread is archived.
177
+ - Direct messages have no thread, so they run on the leader unless each one carries the tag.
178
+ - The leader remembers which messages it handed off in memory. After the leader restarts or changes, reactions on those older messages are not forwarded.
179
+ - Fork reactions and emoji feedback are handled on the leader.
180
+ - A thread keeps its machine after it is archived and its worktree removed; the next message goes back there and gets a fresh worktree. The hub forgets an owner after 180 days without use, or right away with `brainiac hub release discord:<agent>:<thread id>`.
181
+ - If the hub is down when the leader asks who owns a thread, it gets no answer and runs an untagged message itself.
182
+
183
+ Every machine needs this version of the plugin. See `docs/multi-machine.md` in Brainiac.
184
+
141
185
  ## Development
142
186
 
143
187
  ```bash
@@ -57,6 +57,12 @@ module Brainiac
57
57
  @config["klipy_api_key"] || @config["giphy_api_key"]
58
58
  end
59
59
 
60
+ # Multi-machine: add a "ran on <machine>" line under each reply. On unless
61
+ # discord.json sets "machine_footer": false.
62
+ def machine_footer?
63
+ @config["machine_footer"] != false
64
+ end
65
+
60
66
  def channel_mappings
61
67
  @config["channel_mappings"] || {}
62
68
  end
@@ -116,6 +116,7 @@ module Brainiac
116
116
  agent_key = meta["agent_key"]
117
117
  agent_name = meta["agent_name"]
118
118
  response = File.read(response_file).strip
119
+ response = "#{response}\n#{machine_footer(meta["machine"])}" if meta["machine"] && !response.empty? && Config.machine_footer?
119
120
 
120
121
  if response.empty?
121
122
  Api.add_reaction(channel_id, message_id, "😶", token: bot_token) if message_id
@@ -127,6 +128,11 @@ module Brainiac
127
128
  end
128
129
  end
129
130
 
131
+ # Multi-machine: a small line under the reply naming the machine that wrote it.
132
+ def machine_footer(machine)
133
+ "-# 🖥️ ran on #{machine}"
134
+ end
135
+
130
136
  def archive_delivered(response_file, meta_file, lock_file, agent_name)
131
137
  FileUtils.mv(response_file, File.join(POSTED_DIR, File.basename(response_file))) if File.exist?(response_file)
132
138
  FileUtils.mv(meta_file, File.join(POSTED_DIR, File.basename(meta_file)))
@@ -34,6 +34,10 @@ module Brainiac
34
34
  @bots = {}
35
35
  @bots_mutex = Mutex.new
36
36
  @all_ready_logged = false
37
+ # Bot identities learned without a gateway. A multi-machine standby holds
38
+ # no connections, so it never sees READY; the leader sends each bot's id
39
+ # and username along with the work it hands over.
40
+ @identities = {}
37
41
 
38
42
  class << self
39
43
  attr_reader :bots, :bots_mutex
@@ -54,9 +58,26 @@ module Brainiac
54
58
  @bots_mutex.synchronize { @bots.dig(agent_key, :token) }
55
59
  end
56
60
 
61
+ # Get a bot's token whether or not its gateway runs on this machine.
62
+ def token_for(agent_key)
63
+ bot_token(agent_key) || discord_bot_tokens[agent_key]
64
+ end
65
+
57
66
  # Get a bot's user_id.
58
67
  def bot_user_id(agent_key)
59
- @bots_mutex.synchronize { @bots.dig(agent_key, :user_id) }
68
+ @bots_mutex.synchronize { @bots.dig(agent_key, :user_id) || @identities.dig(agent_key, :user_id) }
69
+ end
70
+
71
+ # Get a bot's Discord username.
72
+ def bot_username(agent_key)
73
+ @bots_mutex.synchronize { @bots.dig(agent_key, :username) || @identities.dig(agent_key, :username) }
74
+ end
75
+
76
+ # Record a bot's identity as reported by the machine that holds its gateway.
77
+ def remember_identity(agent_key, user_id:, username: nil)
78
+ return unless user_id
79
+
80
+ @bots_mutex.synchronize { @identities[agent_key] = { user_id: user_id.to_s, username: username } }
60
81
  end
61
82
 
62
83
  # Collect all agent Discord bot tokens from the registry.
@@ -114,9 +135,18 @@ module Brainiac
114
135
  return unless info
115
136
 
116
137
  info[:thread]&.kill
138
+ # Killing the reconnect loop is not enough: the socket has its own reader
139
+ # thread and would keep receiving (and dispatching) messages.
140
+ close_socket(info[:ws])
117
141
  LOG.info "[Discord] Gateway stopped for #{agent_key}" if defined?(LOG)
118
142
  end
119
143
 
144
+ # Stop every bot gateway (multi-machine: this machine gave up the leader role).
145
+ def stop_all!
146
+ keys = @bots_mutex.synchronize { @bots.keys }
147
+ keys.each { |agent_key| stop_bot!(agent_key) }
148
+ end
149
+
120
150
  # Summary of all bot statuses for the API endpoint.
121
151
  def bots_status
122
152
  @bots_mutex.synchronize do
@@ -261,6 +291,7 @@ module Brainiac
261
291
  heartbeat_thread = nil
262
292
  last_sequence = nil
263
293
  ws = WebSocket::Client::Simple.connect(gateway_url)
294
+ bots_mutex.synchronize { bots[agent_key][:ws] = ws if bots[agent_key] }
264
295
 
265
296
  ws.on :message do |msg|
266
297
  next if msg.data.nil? || msg.data.empty?
@@ -304,6 +335,12 @@ module Brainiac
304
335
  # Block until the socket closes. Returns promptly if a handshake error
305
336
  # is reported (the socket never opens in that case). Backoff between
306
337
  # reconnects is owned by the caller (start_gateway_for).
338
+ def close_socket(websocket)
339
+ websocket&.close
340
+ rescue StandardError => e
341
+ LOG.warn "[Discord] Error closing gateway socket: #{e.message}" if defined?(LOG)
342
+ end
343
+
307
344
  def wait_for_disconnect(websocket, agent_display)
308
345
  # Give the handshake a brief window to complete before deciding the
309
346
  # socket is dead, so we don't treat a still-connecting socket as lost.
@@ -41,19 +41,53 @@ module Brainiac
41
41
  # addressed should not activate — the message was directed at someone specific.
42
42
  return if is_thread_participant && other_agent_mentioned?(mentions, content, agent_key)
43
43
 
44
+ accept(message, agent_key, bot_token, bot_user_id,
45
+ mentioned: mentioned, is_reply_to_bot: is_reply_to_bot, in_own_thread: in_own_thread,
46
+ referenced_message: referenced_message, channel_info: channel_info, is_thread: is_thread, is_dm: is_dm)
47
+ end
48
+
49
+ # Run a message that has passed the "is this for me?" gates in handle.
50
+ # A message another machine handed over through the hub (relayed) enters
51
+ # here: the leader that heard it already made those decisions, and this
52
+ # machine has no gateway to make them with.
53
+ def accept(message, agent_key, bot_token, bot_user_id, mentioned:, is_reply_to_bot:, in_own_thread:,
54
+ referenced_message: nil, channel_info: nil, is_thread: false, is_dm: false, relayed: false)
55
+ channel_id = message["channel_id"]
56
+ message_id = message["id"]
57
+ author = message["author"]
58
+ content = message["content"] || ""
59
+ is_bot = !author["bot"].nil?
60
+ discord_user = author["username"]
61
+ discord_user_id = author["id"]
62
+ agent_name = agent_display_name(agent_key) || agent_key.capitalize
63
+
44
64
  record_human_comment("discord-#{channel_id}") unless is_bot
45
65
 
46
66
  clean_content = prepare_content(content, bot_user_id)
67
+ channel_info, is_thread, is_dm = ensure_channel_info(channel_info, is_thread, is_dm, channel_id, bot_token)
68
+
69
+ # Multi-machine: the work may belong on another machine. Decide before
70
+ # downloading attachments or touching a worktree here.
71
+ authorized = false
72
+ if !relayed && Routing.active? && !(clean_content.empty? && (message["attachments"] || []).empty?)
73
+ Config.reload!
74
+ return unless authorize_user(discord_user, discord_user_id, message, channel_id, message_id, agent_name, bot_token)
75
+
76
+ authorized = true
77
+ return if Routing.hand_off_message(
78
+ agent_key: agent_key, bot_token: bot_token, bot_user_id: bot_user_id, message: message,
79
+ requested: parse_inline_tags(clean_content)[:machine],
80
+ place: is_thread ? :thread : (is_dm ? :dm : :channel), # rubocop:disable Style/NestedTernaryOperator
81
+ verdict: { "mentioned" => mentioned, "is_reply_to_bot" => is_reply_to_bot,
82
+ "in_own_thread" => in_own_thread, "referenced_message" => referenced_message }
83
+ )
84
+ end
85
+
47
86
  attachment_paths = download_attachments(message, message_id, agent_key)
48
87
  clean_content = append_attachments(clean_content, attachment_paths)
49
88
  return if clean_content.empty? && attachment_paths.empty?
50
89
 
51
90
  reply_context = build_reply_context(referenced_message)
52
- discord_user = author["username"]
53
- discord_user_id = author["id"]
54
- agent_name = agent_display_name(agent_key) || agent_key.capitalize
55
-
56
- channel_info, is_thread, is_dm = ensure_channel_info(channel_info, is_thread, is_dm, channel_id, bot_token)
57
91
  parent_channel_id = is_thread ? channel_info&.dig("parent_id") || channel_id : channel_id
58
92
  channel_history = Api.fetch_channel_history(channel_id, message_id, token: bot_token, limit: is_thread ? 25 : 10)
59
93
  location = is_dm ? "DM" : (is_thread ? "thread" : "channel") # rubocop:disable Style/NestedTernaryOperator
@@ -63,7 +97,7 @@ module Brainiac
63
97
  reload_agent_registry!
64
98
  reload_profiles! if defined?(reload_profiles!)
65
99
  Config.reload!
66
- return unless authorize_user(discord_user, discord_user_id, message, channel_id, message_id, agent_name, bot_token)
100
+ return unless authorized || authorize_user(discord_user, discord_user_id, message, channel_id, message_id, agent_name, bot_token)
67
101
 
68
102
  tags = parse_inline_tags(clean_content)
69
103
 
@@ -328,8 +362,7 @@ module Brainiac
328
362
  def solo_in_thread?(channel_history, agent_key)
329
363
  return true unless channel_history.is_a?(String) && !channel_history.empty?
330
364
 
331
- own_username = nil
332
- Gateway.each_bot { |key, info| own_username = info[:username] if key == agent_key }
365
+ own_username = Gateway.bot_username(agent_key)
333
366
 
334
367
  channel_history.split("\n").none? do |line|
335
368
  author = line[/\A(.+?) \[bot\]: /, 1]
@@ -676,7 +709,8 @@ module Brainiac
676
709
  session_key: session_key, supersede_key: supersede_key,
677
710
  attachment_paths: attachment_paths, timestamp: timestamp, response_dir: response_dir,
678
711
  profile: resolve_thread_profile(thread_map_key, clean_content),
679
- explicit_model: explicit_model_tag?(clean_content, project_config, cli_provider_override: cli_provider_override)
712
+ explicit_model: explicit_model_tag?(clean_content, project_config, cli_provider_override: cli_provider_override),
713
+ title: clean_content
680
714
  )
681
715
  end
682
716
 
@@ -859,6 +893,7 @@ module Brainiac
859
893
  clean_content: clean_content[0..80],
860
894
  cli_provider: detect_cli_provider(text: clean_content),
861
895
  model: explicit_model, effort: explicit_effort,
896
+ machine: Routing.machine,
862
897
  created_at: Time.now.iso8601
863
898
  }))
864
899
  end
@@ -956,7 +991,7 @@ module Brainiac
956
991
  branch = "discord-#{agent_key}-#{effective_thread_id[-8..]}"
957
992
 
958
993
  debounced_repo_fetch(repo_path)
959
- worktree_path = create_or_reuse_worktree(repo_path: repo_path, branch: branch)
994
+ worktree_path = create_or_reuse_worktree(repo_path: repo_path, branch: branch, **moved_thread_base(repo_path, branch))
960
995
 
961
996
  # Register a work item so brainiac-github can route PR comments/reviews back
962
997
  # to the agent that actually owns this Discord thread's worktree. Without this,
@@ -976,6 +1011,19 @@ module Brainiac
976
1011
  [worktree_path, cli, model, effort]
977
1012
  end
978
1013
 
1014
+ # Multi-machine: a thread moved here from another machine already has its
1015
+ # branch on the remote. Start from what that machine pushed, not from the
1016
+ # default branch.
1017
+ def moved_thread_base(repo_path, branch)
1018
+ return {} unless Routing.active?
1019
+
1020
+ pushed = system("git", "rev-parse", "--verify", "--quiet", "origin/#{branch}^{commit}",
1021
+ chdir: repo_path, out: File::NULL, err: File::NULL)
1022
+ pushed ? { base_ref: "origin/#{branch}" } : {}
1023
+ rescue StandardError
1024
+ {}
1025
+ end
1026
+
979
1027
  def create_chat_mode_dir(agent_key, agent_name, effective_thread_id, project_config, clean_content, thread_map_key)
980
1028
  chat_tmp_dir = File.join(Delivery::BRAINIAC_DIR_PATH, "tmp", "chat", "#{agent_key}-#{effective_thread_id}")
981
1029
  FileUtils.mkdir_p(chat_tmp_dir)
@@ -1006,6 +1054,8 @@ module Brainiac
1006
1054
  map[thread_map_key] = entry
1007
1055
  Config.save_thread_map(map)
1008
1056
  end
1057
+ # Multi-machine: this thread's worktree lives here now, so its follow-ups should too.
1058
+ Routing.claim_thread(thread_map_key.split(":", 2).first, effective_thread_id)
1009
1059
  end
1010
1060
 
1011
1061
  def build_prompt(should_resume:, thread_worktree_path:, clean_content_for_prompt:,
@@ -1039,7 +1089,7 @@ module Brainiac
1039
1089
  work_dir:, prompt_file:, response_file:, meta_file:, model:, effort:,
1040
1090
  actual_resume:, resolved:, project_config:,
1041
1091
  session_key:, supersede_key:, attachment_paths:, timestamp:, response_dir:, profile: nil,
1042
- explicit_model: nil)
1092
+ explicit_model: nil, title: nil)
1043
1093
  agent_config_name = agent_key.downcase.gsub(/[^a-z0-9-]/, "-")
1044
1094
  log_file = File.join(response_dir, "discord-agent-#{timestamp}-#{agent_key}-#{message_id}.log")
1045
1095
 
@@ -1109,7 +1159,7 @@ module Brainiac
1109
1159
  message_id: message_id, channel_id: channel_id,
1110
1160
  supersede_key: supersede_key,
1111
1161
  draft_files: [response_file, meta_file],
1112
- agent_name: agent_name)
1162
+ agent_name: agent_name, title: title)
1113
1163
 
1114
1164
  monitor_agent(
1115
1165
  pid: pid, session_key: session_key, agent_name: agent_name,
@@ -22,7 +22,11 @@ module Brainiac
22
22
  FORK_DEDUP_TTL = 60 # seconds
23
23
 
24
24
  class << self
25
- def handle(reaction_data, agent_key, bot_token, bot_user_id)
25
+ SESSION_EMOJIS = ["❔", "❓", "🧠", "❌"].freeze
26
+
27
+ # relayed: the leader machine forwarded this reaction because the session
28
+ # it is about runs here.
29
+ def handle(reaction_data, agent_key, bot_token, bot_user_id, relayed: false)
26
30
  channel_id = reaction_data["channel_id"]
27
31
  message_id = reaction_data["message_id"]
28
32
  user_id = reaction_data["user_id"]
@@ -34,6 +38,13 @@ module Brainiac
34
38
  # Ignore reactions from bots (including self)
35
39
  return if user_id == bot_user_id
36
40
 
41
+ # Multi-machine: these act on a running session, which may be on the
42
+ # machine this message was handed to.
43
+ if !relayed && SESSION_EMOJIS.include?(emoji_name) &&
44
+ Routing.hand_off_reaction(agent_key: agent_key, bot_user_id: bot_user_id, reaction: reaction_data)
45
+ return
46
+ end
47
+
37
48
  case emoji_name
38
49
  when "❔", "❓"
39
50
  handle_thinking_peek(agent_key, agent_name, channel_id, message_id, bot_token, line_count: emoji_name == "❔" ? 10 : 20)
@@ -0,0 +1,265 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Brainiac
4
+ module Plugins
5
+ module Discord
6
+ # Multi-machine routing for Discord work.
7
+ #
8
+ # Only the leader machine holds the bot gateways, so it hears every message.
9
+ # It decides which machine should do the work and, when that is another
10
+ # machine, hands the raw event over through the brainiac-hub. The machine
11
+ # that receives it runs the agent in its own worktree and posts the reply
12
+ # itself over the REST API.
13
+ #
14
+ # Which machine:
15
+ # 1. `[machine:<name>]` in the message. In a thread this also moves the
16
+ # thread to that machine.
17
+ # 2. The thread's owner, recorded in the hub as `discord:<agent>:<thread id>`.
18
+ # 3. Otherwise this machine (the leader).
19
+ #
20
+ # Everything here is a no-op without a hub configured.
21
+ module Routing
22
+ MESSAGE_PATH = "/hub/discord/message"
23
+ REACTION_PATH = "/hub/discord/reaction"
24
+ ARCHIVE_PATH = "/hub/discord/thread-archive"
25
+ HANDED_OFF_LIMIT = 1000
26
+
27
+ @handed_off = {}
28
+ @claimed = {}
29
+ @mutex = Mutex.new
30
+
31
+ class << self
32
+ # True when this machine is a node of a brainiac-hub.
33
+ def active?
34
+ (defined?(Brainiac::Hub) && Brainiac::Hub.respond_to?(:enabled?) && Brainiac::Hub.enabled?) || false
35
+ end
36
+
37
+ # This machine's name in the hub, or nil without one.
38
+ def machine
39
+ active? ? Brainiac::Hub.machine_name : nil
40
+ end
41
+
42
+ def thread_key(agent_key, thread_id)
43
+ "discord:#{agent_key}:#{thread_id}"
44
+ end
45
+
46
+ # --- leader side ---
47
+
48
+ # Decide where a message runs. Returns true when it was handed to another
49
+ # machine (or refused with a note in the channel) and the caller must stop.
50
+ #
51
+ # @param requested [String, nil] machine named by a [machine:x] tag
52
+ # @param place [Symbol] :thread, :dm or :channel
53
+ # @param verdict [Hash] what the leader's gates decided (mentioned, own thread, ...)
54
+ def hand_off_message(agent_key:, bot_token:, bot_user_id:, message:, requested:, place:, verdict:)
55
+ return false unless active?
56
+
57
+ channel_id = message["channel_id"]
58
+ message_id = message["id"]
59
+ me = machine
60
+ key = work_key(agent_key, place, channel_id, message_id)
61
+ owner = place == :thread ? Brainiac::Hub.owner(key) : nil
62
+ say = ->(text) { Api.send_message(channel_id, text, token: bot_token, reply_to: message_id) }
63
+
64
+ requested = settle_request(requested, owner, me, say)
65
+ return true if requested == :refused
66
+
67
+ target = requested || owner
68
+ return false if target.nil?
69
+
70
+ if target == me
71
+ # A tag naming this machine takes the thread over from its old owner.
72
+ claim_thread(agent_key, channel_id, overwrite: true) if place == :thread && owner != me
73
+ return false
74
+ end
75
+
76
+ adopt_thread_depth(channel_id, message_id) if place == :channel
77
+ result = Brainiac::Hub.relay(
78
+ path: MESSAGE_PATH, keys: [key].compact, machine: requested,
79
+ reassign: !requested.nil? && !owner.nil? && requested != owner,
80
+ payload: { "agent_key" => agent_key, "bot_user_id" => bot_user_id,
81
+ "bot_username" => Gateway.bot_username(agent_key),
82
+ "from" => me, "message" => message, "verdict" => verdict }
83
+ )
84
+ report_relay(result, target, agent_key, message_id, say)
85
+ true
86
+ end
87
+
88
+ # Forward a session reaction (cancel, peek, stream) to the machine the
89
+ # message was handed to. Returns true when it was forwarded.
90
+ def hand_off_reaction(agent_key:, bot_user_id:, reaction:)
91
+ return false unless active?
92
+
93
+ target = @mutex.synchronize { @handed_off["#{agent_key}:#{reaction["message_id"]}"] }
94
+ return false unless target && target != machine
95
+
96
+ Brainiac::Hub.relay(path: REACTION_PATH, machine: target,
97
+ payload: { "agent_key" => agent_key, "bot_user_id" => bot_user_id, "reaction" => reaction })
98
+ true
99
+ end
100
+
101
+ # A thread this machine has no worktree for was archived or deleted. If
102
+ # another machine owns it, pass the event on so it can clean up.
103
+ def hand_off_archive(agent_key:, data:)
104
+ return false unless active?
105
+
106
+ key = thread_key(agent_key, data["id"])
107
+ owner = Brainiac::Hub.owner(key)
108
+ return false unless owner && owner != machine
109
+
110
+ Brainiac::Hub.relay(path: ARCHIVE_PATH, keys: [key], payload: { "agent_key" => agent_key, "thread" => data })
111
+ true
112
+ end
113
+
114
+ # --- receiving side ---
115
+
116
+ def receive_message(payload)
117
+ agent_key, token = receiving_agent(payload)
118
+ return unless token
119
+
120
+ verdict = payload["verdict"] || {}
121
+ Message.accept(
122
+ payload["message"], agent_key, token, payload["bot_user_id"],
123
+ mentioned: verdict["mentioned"] ? true : false,
124
+ is_reply_to_bot: verdict["is_reply_to_bot"] ? true : false,
125
+ in_own_thread: verdict["in_own_thread"] ? true : false,
126
+ referenced_message: verdict["referenced_message"], relayed: true
127
+ )
128
+ end
129
+
130
+ def receive_reaction(payload)
131
+ agent_key, token = receiving_agent(payload)
132
+ return unless token
133
+
134
+ Reactions.handle(payload["reaction"], agent_key, token, payload["bot_user_id"], relayed: true)
135
+ end
136
+
137
+ def receive_archive(payload)
138
+ agent_key = payload["agent_key"].to_s
139
+ ThreadCleanup.handle_archive(payload["thread"] || {}, agent_key, agent_display_name(agent_key) || agent_key.capitalize,
140
+ relayed: true)
141
+ end
142
+
143
+ # --- ownership ---
144
+
145
+ # Tell the hub this machine holds a thread's worktree, so follow-ups come
146
+ # back here whichever machine is the leader. Never takes a thread that
147
+ # already has an owner unless overwrite is set.
148
+ #
149
+ # Ownership outlives the worktree on purpose. Discord archives idle
150
+ # threads by itself and cleanup then removes a clean worktree; the next
151
+ # message should still come back to the machine that was chosen. The
152
+ # hub expires an assignment that goes unused.
153
+ def claim_thread(agent_key, thread_id, overwrite: false)
154
+ return unless active? && thread_id
155
+
156
+ key = thread_key(agent_key, thread_id)
157
+ return if !overwrite && @mutex.synchronize { @claimed[key] }
158
+
159
+ @mutex.synchronize { @claimed[key] = true }
160
+ name = machine
161
+ in_background { Brainiac::Hub.assign([key], name, overwrite: overwrite) }
162
+ end
163
+
164
+ def reset!
165
+ @mutex.synchronize do
166
+ @handed_off.clear
167
+ @claimed.clear
168
+ end
169
+ end
170
+
171
+ private
172
+
173
+ # A thread started from a message has that message's id, so a channel
174
+ # message already knows the key its thread will have.
175
+ def work_key(agent_key, place, channel_id, message_id)
176
+ case place
177
+ when :thread then thread_key(agent_key, channel_id)
178
+ when :channel then thread_key(agent_key, message_id)
179
+ end
180
+ end
181
+
182
+ # Check a [machine:x] tag against the machines the hub knows. Returns the
183
+ # machine to ask for, nil to follow the owner, or :refused after telling
184
+ # the user why nothing ran.
185
+ def settle_request(requested, owner, this_machine, say)
186
+ return nil if requested.nil? || requested == owner
187
+ return requested if requested == this_machine
188
+
189
+ nodes = (Brainiac::Hub.status || {})["nodes"]
190
+ return requested unless nodes.is_a?(Array) # hub did not answer; the relay will report it
191
+
192
+ node = nodes.find { |n| n["name"] == requested }
193
+ unless node
194
+ names = nodes.map { |n| "`#{n["name"]}`" }.join(", ")
195
+ say.call("⚠️ No machine named `#{requested}`. Known machines: #{names}. Nothing ran.")
196
+ return :refused
197
+ end
198
+ return requested if node["online"] || owner.nil?
199
+
200
+ # Moving a thread to a machine that is off would let the hub drop it
201
+ # on whichever machine is next in line. Leave it where its work is.
202
+ say.call("⚠️ `#{requested}` is offline, so this thread stays on `#{owner}`.")
203
+ nil
204
+ end
205
+
206
+ def report_relay(result, target, agent_key, message_id, say)
207
+ unless result
208
+ say.call("⚠️ Could not reach the hub to pass this to `#{target}`, so nothing ran. Send it again in a moment.")
209
+ return
210
+ end
211
+
212
+ taken_by = result["machine"]
213
+ remember_hand_off(agent_key, message_id, taken_by || target)
214
+ if result["status"] == "queued"
215
+ say.call("⏳ `#{taken_by || target}` is offline. This is queued and runs when it is back. " \
216
+ "To run it elsewhere, send it again with `[machine:<name>]`.")
217
+ elsif taken_by && taken_by != target
218
+ say.call("↪️ `#{target}` did not answer. Running on `#{taken_by}` instead.")
219
+ end
220
+ end
221
+
222
+ def remember_hand_off(agent_key, message_id, target)
223
+ @mutex.synchronize do
224
+ @handed_off["#{agent_key}:#{message_id}"] = target
225
+ @handed_off.shift while @handed_off.size > HANDED_OFF_LIMIT
226
+ end
227
+ end
228
+
229
+ # The thread a handed-off channel message starts is created on the other
230
+ # machine, so the leader never sees it being made. Give it the parent
231
+ # channel's dispatch-depth record here, or agent-to-agent mentions in
232
+ # that thread are refused until a human speaks in it.
233
+ def adopt_thread_depth(channel_id, message_id)
234
+ return unless defined?(AGENT_DISPATCH_DEPTH)
235
+
236
+ parent = AGENT_DISPATCH_DEPTH["discord-#{channel_id}"]
237
+ return unless parent
238
+
239
+ AGENT_DISPATCH_DEPTH["discord-#{message_id}"] ||= { count: 0, last_human_at: parent[:last_human_at] }
240
+ end
241
+
242
+ def receiving_agent(payload)
243
+ agent_key = payload["agent_key"].to_s
244
+ token = Gateway.token_for(agent_key)
245
+ unless token
246
+ LOG.warn "[Discord] Relayed work for '#{agent_key}' but this machine has no bot token for it — ignoring" if defined?(LOG)
247
+ return [agent_key, nil]
248
+ end
249
+
250
+ Gateway.remember_identity(agent_key, user_id: payload["bot_user_id"], username: payload["bot_username"])
251
+ [agent_key, token]
252
+ end
253
+
254
+ def in_background
255
+ Thread.new do
256
+ yield
257
+ rescue StandardError => e
258
+ LOG.warn "[Discord] Hub ownership update failed: #{e.message}" if defined?(LOG)
259
+ end
260
+ end
261
+ end
262
+ end
263
+ end
264
+ end
265
+ end
@@ -14,18 +14,26 @@ module Brainiac
14
14
  # the thread map entry.
15
15
  module ThreadCleanup
16
16
  class << self
17
- def handle_archive(data, agent_key, agent_display)
17
+ # relayed: the leader machine forwarded the event because this machine
18
+ # holds the thread's worktree.
19
+ def handle_archive(data, agent_key, agent_display, relayed: false)
18
20
  thread_id = data["id"]
19
21
  return unless thread_id
20
22
 
21
23
  thread_map_key = "#{agent_key}:#{thread_id}"
22
24
 
25
+ # Multi-machine: the thread may live on another machine (or, after a
26
+ # move, on both). Pass the event on; anything left here is still cleaned up.
27
+ handed_off = !relayed && Routing.hand_off_archive(agent_key: agent_key, data: data)
28
+
23
29
  entry = Config.thread_map_mutex.synchronize do
24
30
  map = Config.load_thread_map
25
31
  map[thread_map_key]
26
32
  end
27
33
 
28
34
  unless entry
35
+ return if handed_off
36
+
29
37
  LOG.info "[Discord:#{agent_display}] Thread #{thread_id} archived — no worktree tracked, nothing to clean up" if defined?(LOG)
30
38
  return
31
39
  end
@@ -3,7 +3,7 @@
3
3
  module Brainiac
4
4
  module Plugins
5
5
  module Discord
6
- VERSION = "0.0.27"
6
+ VERSION = "0.0.29"
7
7
  end
8
8
  end
9
9
  end
@@ -7,6 +7,7 @@ require_relative "discord/config"
7
7
  require_relative "discord/prompts"
8
8
  require_relative "discord/api"
9
9
  require_relative "discord/delivery"
10
+ require_relative "discord/routing"
10
11
  require_relative "discord/reactions"
11
12
  require_relative "discord/branching"
12
13
  require_relative "discord/message"
@@ -36,8 +37,14 @@ module Brainiac
36
37
  # Register agent lifecycle hooks
37
38
  register_agent_lifecycle_hooks!
38
39
 
39
- # Start all per-agent Discord bot gateway connections
40
- Brainiac::Plugins::Discord::Gateway.start_all!
40
+ # Start all per-agent Discord bot gateway connections. With a brainiac-hub
41
+ # only the leader machine holds them; the others wait for the role.
42
+ register_hub_leader_hooks!
43
+ if hub_standby?
44
+ LOG.info "[Discord] Multi-machine standby: gateways start when this machine becomes the leader"
45
+ else
46
+ Brainiac::Plugins::Discord::Gateway.start_all!
47
+ end
41
48
 
42
49
  # Start draft delivery poller
43
50
  Brainiac::Plugins::Discord::Delivery.start_poller!
@@ -48,8 +55,29 @@ module Brainiac
48
55
  LOG.info "[Discord] Plugin registered (#{Brainiac::Plugins::Discord::Gateway.bot_count} bots)"
49
56
  end
50
57
 
58
+ # True when a brainiac-hub is configured and another machine (or nobody
59
+ # yet) is the leader. Two machines holding the same bot's gateway would
60
+ # both answer every message, so a standby machine opens none. It can
61
+ # still post: sending uses the REST API and the token from agents.json.
62
+ def hub_standby?
63
+ defined?(Brainiac::Hub) && Brainiac::Hub.respond_to?(:enabled?) &&
64
+ Brainiac::Hub.enabled? && !Brainiac::Hub.leader?
65
+ end
66
+
51
67
  private
52
68
 
69
+ def register_hub_leader_hooks!
70
+ Brainiac.on(:hub_leader_acquired) do |_ctx|
71
+ LOG.info "[Discord] This machine is now the leader — starting gateways" if defined?(LOG)
72
+ Gateway.start_all!
73
+ end
74
+
75
+ Brainiac.on(:hub_leader_lost) do |_ctx|
76
+ LOG.info "[Discord] This machine is no longer the leader — stopping gateways" if defined?(LOG)
77
+ Gateway.stop_all!
78
+ end
79
+ end
80
+
53
81
  def register_agent_lifecycle_hooks!
54
82
  Brainiac.on(:agent_added) do |ctx|
55
83
  agent_key = ctx[:agent_key]
@@ -58,7 +86,7 @@ module Brainiac
58
86
  next unless entry.is_a?(Hash)
59
87
 
60
88
  token = (entry["env"] || {})["DISCORD_BOT_TOKEN"]
61
- if token
89
+ if token && !hub_standby?
62
90
  # Start a gateway connection for the new agent's bot
63
91
  Gateway.start_bot!(agent_key, token)
64
92
  LOG.info "[Discord] Started bot for new agent: #{display_name}" if defined?(LOG)
@@ -70,6 +98,7 @@ module Brainiac
70
98
  Brainiac.on(:agent_updated) do |ctx|
71
99
  agent_key = ctx[:agent_key]
72
100
  token = ((ctx[:entry].is_a?(Hash) && ctx[:entry]["env"]) || {})["DISCORD_BOT_TOKEN"]
101
+ next if hub_standby? # the leader machine picks the token up when it takes over
73
102
  next if token == Gateway.bot_token(agent_key)
74
103
 
75
104
  Config.reload! # pick up the user_mappings entry the setup step wrote
@@ -155,6 +184,19 @@ module Brainiac
155
184
  Brainiac::Plugins::Discord::Gateway.bots_status.to_json
156
185
  end
157
186
 
187
+ # Multi-machine: work the leader machine hands to this one through the
188
+ # brainiac-hub. Core only lets a request reach /hub/* with a valid hub
189
+ # signature, and has already acknowledged it by the time these run.
190
+ { Routing::MESSAGE_PATH => :receive_message,
191
+ Routing::REACTION_PATH => :receive_reaction,
192
+ Routing::ARCHIVE_PATH => :receive_archive }.each do |path, receiver|
193
+ app.post path do
194
+ content_type :json
195
+ Brainiac::Plugins::Discord::Routing.public_send(receiver, JSON.parse(request.body.read))
196
+ { status: "ok" }.to_json
197
+ end
198
+ end
199
+
158
200
  app.get "/api/gif" do
159
201
  content_type :json
160
202
  query = params["q"]
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: brainiac-discord
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.27
4
+ version: 0.0.29
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andy Davis
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: 0.0.14
18
+ version: 0.7.1
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - ">="
24
24
  - !ruby/object:Gem::Version
25
- version: 0.0.14
25
+ version: 0.7.1
26
26
  - !ruby/object:Gem::Dependency
27
27
  name: websocket-client-simple
28
28
  requirement: !ruby/object:Gem::Requirement
@@ -114,6 +114,7 @@ files:
114
114
  - lib/brainiac/plugins/discord/metadata.rb
115
115
  - lib/brainiac/plugins/discord/prompts.rb
116
116
  - lib/brainiac/plugins/discord/reactions.rb
117
+ - lib/brainiac/plugins/discord/routing.rb
117
118
  - lib/brainiac/plugins/discord/thread_cleanup.rb
118
119
  - lib/brainiac/plugins/discord/version.rb
119
120
  - lib/brainiac_discord.rb