@hivey/cli 0.0.0-stage → 0.9.36

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.
Files changed (83) hide show
  1. package/README.md +235 -2
  2. package/bin/hivey.js +98 -0
  3. package/native/darwin-arm64/hivey +0 -0
  4. package/package.json +36 -4
  5. package/platforms.json +3 -0
  6. package/repo/LICENSE +201 -0
  7. package/repo/NOTICE +18 -0
  8. package/repo/README.md +148 -0
  9. package/repo/install.sh +365 -0
  10. package/repo/pets/README.md +25 -0
  11. package/repo/pets/hivey-dot/CLAUDE.md +55 -0
  12. package/repo/pets/hivey-dot/build.sh +34 -0
  13. package/repo/pets/hivey-dot/main.swift +750 -0
  14. package/repo/pets/hivey-h/CLAUDE.md +75 -0
  15. package/repo/pets/hivey-h/build.sh +34 -0
  16. package/repo/pets/hivey-h/main.swift +739 -0
  17. package/repo/pets/hivey-prompt/CLAUDE.md +59 -0
  18. package/repo/pets/hivey-prompt/build.sh +34 -0
  19. package/repo/pets/hivey-prompt/main.swift +691 -0
  20. package/repo/pets/pet.py +288 -0
  21. package/repo/pets/shared/HiveyWatch.swift +437 -0
  22. package/repo/pets/test_pet.py +122 -0
  23. package/repo/plugins/README.md +108 -0
  24. package/repo/plugins/agent-creator/herdr-plugin.toml +17 -0
  25. package/repo/plugins/dashboard/dashboard.py +507 -0
  26. package/repo/plugins/dashboard/herdr-plugin.toml +14 -0
  27. package/repo/plugins/dashboard/test_dashboard.py +134 -0
  28. package/repo/plugins/github/github.py +261 -0
  29. package/repo/plugins/github/herdr-plugin.toml +14 -0
  30. package/repo/plugins/github/test_github.py +49 -0
  31. package/repo/plugins/skills/herdr-plugin.toml +11 -0
  32. package/repo/plugins/skills/skills.md +41 -0
  33. package/repo/plugins/slack-relay/connect.py +198 -0
  34. package/repo/plugins/slack-relay/create_channel.py +134 -0
  35. package/repo/plugins/slack-relay/herdr-plugin.toml +15 -0
  36. package/repo/plugins/slack-relay/relay.py +401 -0
  37. package/repo/plugins/slack-relay/slack-app-manifest.json +30 -0
  38. package/repo/plugins/slack-relay/test_connect.py +66 -0
  39. package/repo/plugins/slack-relay/test_create_channel.py +61 -0
  40. package/repo/plugins/slack-relay/test_relay.py +254 -0
  41. package/repo/plugins/swarm-creator/herdr-plugin.toml +17 -0
  42. package/repo/plugins/swarm-watcher/dashboard.py +333 -0
  43. package/repo/plugins/swarm-watcher/herdr-plugin.toml +16 -0
  44. package/repo/plugins/swarm-watcher/usage.py +129 -0
  45. package/repo/plugins/swarm-watcher/watcher.py +191 -0
  46. package/repo/plugins/team-template/herdr-plugin.toml +15 -0
  47. package/repo/plugins/team-template/setup.py +211 -0
  48. package/repo/plugins/team-template/test_setup.py +73 -0
  49. package/repo/plugins/tts/herdr-plugin.toml +15 -0
  50. package/repo/skills/herdr/SKILL.md +214 -0
  51. package/repo/skills/hivey/SKILL.md +322 -0
  52. package/repo/skills/hivey/scripts/handoff.py +27 -0
  53. package/repo/skills/hivey/scripts/new_wiki.py +143 -0
  54. package/repo/skills/hivey-agent-creator/SKILL.md +303 -0
  55. package/repo/skills/hivey-agent-creator/references/agent-claude-md.md +256 -0
  56. package/repo/skills/hivey-agent-creator/references/global-guidelines.md +67 -0
  57. package/repo/skills/hivey-agent-creator/references/reviewer-agent.md +35 -0
  58. package/repo/skills/hivey-agent-creator/scripts/agent_context.py +76 -0
  59. package/repo/skills/hivey-agent-creator/scripts/agent_gate.py +78 -0
  60. package/repo/skills/hivey-agent-creator/scripts/setup_agent.py +288 -0
  61. package/repo/skills/hivey-agy/SKILL.md +123 -0
  62. package/repo/skills/hivey-agy/references/gemini-prompting.md +134 -0
  63. package/repo/skills/hivey-agy/scripts/agy_run.py +146 -0
  64. package/repo/skills/hivey-codex/SKILL.md +66 -0
  65. package/repo/skills/hivey-context7/SKILL.md +56 -0
  66. package/repo/skills/hivey-create-wiki/SKILL.md +329 -0
  67. package/repo/skills/hivey-grok/SKILL.md +101 -0
  68. package/repo/skills/hivey-grok/scripts/grok_run.py +139 -0
  69. package/repo/skills/hivey-swarm-creator/SKILL.md +384 -0
  70. package/repo/skills/hivey-swarm-creator/references/agent-claude-md.md +313 -0
  71. package/repo/skills/hivey-swarm-creator/references/archify-report.md +24 -0
  72. package/repo/skills/hivey-swarm-creator/references/dashboard.md +46 -0
  73. package/repo/skills/hivey-swarm-creator/references/retrospective.md +23 -0
  74. package/repo/skills/hivey-swarm-creator/references/shared-rules.md +39 -0
  75. package/repo/skills/hivey-swarm-creator/references/wiki-memory.md +30 -0
  76. package/repo/skills/hivey-swarm-creator/scripts/setup_agent.py +76 -0
  77. package/repo/skills/hivey-swarm-creator/scripts/shared_rules.py +50 -0
  78. package/repo/skills/hivey-swarm-creator/scripts/swarm_tasks.py +171 -0
  79. package/repo/skills/hivey-wiki-ingest/SKILL.md +45 -0
  80. package/repo/skills/hivey-wiki-lint/SKILL.md +38 -0
  81. package/repo/skills/hivey-wiki-list/SKILL.md +46 -0
  82. package/repo/skills/hivey-wiki-log/SKILL.md +45 -0
  83. package/repo/skills/hivey-wiki-query/SKILL.md +44 -0
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env python3
2
+ """Create (or find) a public Slack channel for a hivey swarm or agent; prints its id as JSON.
3
+
4
+ usage: create_channel.py <name> [--purpose TEXT]
5
+
6
+ Uses the relay's token (config.json token_command, or $SLACK_TOKEN; `hivey slack connect` sets
7
+ it); needs channels:manage, plus channels:read and channels:join to find and join an existing
8
+ channel. Run by `hivey slack add`, `hivey swarm launch --slack` and `hivey home setup --slack`.
9
+ The user is invited, so the channel shows up in their Slack right away: config.json "invite"
10
+ (Slack member ids; `hivey slack connect` sets it, else it's worked out once from the people in
11
+ the channels the bot already shares with them).
12
+ Output: {"ok": true, "channel_id": "C…", "name": "hivey", "existing": false, "invited": ["U…"]}
13
+ """
14
+ import argparse
15
+ import json
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
21
+ import relay # noqa: E402 (same folder)
22
+
23
+
24
+ def find(slack, name):
25
+ cursor = ""
26
+ while True:
27
+ data = slack.call("conversations.list", http="GET", types="public_channel",
28
+ exclude_archived="true", limit=1000, cursor=cursor)
29
+ for channel in data.get("channels", []):
30
+ if channel.get("name") == name:
31
+ return channel
32
+ cursor = data.get("response_metadata", {}).get("next_cursor", "")
33
+ if not cursor:
34
+ return None
35
+
36
+
37
+ def config_path():
38
+ return Path(os.environ["HERDR_PLUGIN_CONFIG_DIR"]) / "config.json"
39
+
40
+
41
+ def shared_people(slack):
42
+ """Humans in the channels the bot is in, most shared first (the bot itself excluded)."""
43
+ bot = slack.call("auth.test").get("user_id")
44
+ counts = {}
45
+ data = slack.call("conversations.list", http="GET", types="public_channel",
46
+ exclude_archived="true", limit=1000)
47
+ for channel in data.get("channels", []):
48
+ if not channel.get("is_member"):
49
+ continue
50
+ members = slack.call("conversations.members", http="GET", channel=channel["id"])
51
+ for member in members.get("members", []):
52
+ if member != bot:
53
+ counts[member] = counts.get(member, 0) + 1
54
+ return sorted(counts, key=lambda member: -counts[member])
55
+
56
+
57
+ def invitees(slack, config):
58
+ """Who to invite: config "invite", else the person the bot shares the most channels with
59
+ (then remembered in config.json)."""
60
+ people = config.get("invite")
61
+ if isinstance(people, str):
62
+ people = [people]
63
+ if people:
64
+ return people
65
+ try:
66
+ found = shared_people(slack)[:1]
67
+ except RuntimeError:
68
+ return []
69
+ if found:
70
+ config["invite"] = found
71
+ config_path().write_text(json.dumps(config, indent=2) + "\n")
72
+ return found
73
+
74
+
75
+ def invite(slack, channel_id, people):
76
+ """Invites the people not in the channel yet; returns the ones invited now."""
77
+ invited = []
78
+ for person in people:
79
+ try:
80
+ slack.call("conversations.invite", channel=channel_id, users=person)
81
+ invited.append(person)
82
+ except RuntimeError as err:
83
+ if "already_in_channel" not in str(err):
84
+ print(f"cannot invite {person}: {err}", file=sys.stderr)
85
+ return invited
86
+
87
+
88
+ def main():
89
+ parser = argparse.ArgumentParser()
90
+ parser.add_argument("name")
91
+ parser.add_argument("--purpose")
92
+ args = parser.parse_args()
93
+ if not os.environ.get("HERDR_PLUGIN_CONFIG_DIR"):
94
+ # Run outside a plugin pane: use the installed relay's config.
95
+ os.environ["HERDR_PLUGIN_CONFIG_DIR"] = str(
96
+ Path.home() / ".config" / "hivey" / "plugins" / "config" / "hivey.slack-relay")
97
+ config = relay.load_config()
98
+ token = relay.resolve_token(config)
99
+ if not token:
100
+ print(json.dumps({"ok": False, "error": "Slack is not connected: run hivey slack connect "
101
+ "in a terminal"}))
102
+ return 1
103
+ slack = relay.Slack(token)
104
+ existing = False
105
+ try:
106
+ channel = slack.call("conversations.create", name=args.name, is_private=False)["channel"]
107
+ except RuntimeError as err:
108
+ if "name_taken" not in str(err):
109
+ print(json.dumps({"ok": False, "error": str(err)}))
110
+ return 1
111
+ channel, existing = find(slack, args.name), True
112
+ if channel is None:
113
+ print(json.dumps({"ok": False, "error": "name_taken (archived or private channel)"}))
114
+ return 1
115
+ if not channel.get("is_member"):
116
+ # The relay reads the channel's history: the bot has to be in it.
117
+ try:
118
+ slack.call("conversations.join", channel=channel["id"])
119
+ except RuntimeError as err:
120
+ print(json.dumps({"ok": False, "error": f"cannot join #{args.name}: {err}"}))
121
+ return 1
122
+ if args.purpose and not existing:
123
+ try:
124
+ slack.call("conversations.setPurpose", channel=channel["id"], purpose=args.purpose[:250])
125
+ except RuntimeError:
126
+ pass
127
+ invited = invite(slack, channel["id"], invitees(slack, config))
128
+ print(json.dumps({"ok": True, "channel_id": channel["id"], "name": args.name,
129
+ "existing": existing, "invited": invited}))
130
+ return 0
131
+
132
+
133
+ if __name__ == "__main__":
134
+ sys.exit(main())
@@ -0,0 +1,15 @@
1
+ id = "hivey.slack-relay"
2
+ name = "Slack relay"
3
+ version = "0.1.0"
4
+ min_herdr_version = "0.9.0"
5
+ description = "hivey swarm addon: bridges a swarm's message bus and its Slack channel"
6
+ platforms = ["linux", "macos"]
7
+
8
+ # Opened by `hivey swarm launch --addon hivey.slack-relay` in the swarm's space, with
9
+ # HIVEY_SWARM_ROOT / HIVEY_SWARM_SLUG / HIVEY_SWARM_CHANNEL set. Runs with the swarm root
10
+ # as working directory, so the script is addressed through HERDR_PLUGIN_ROOT.
11
+ [[panes]]
12
+ id = "relay"
13
+ title = "slack relay"
14
+ placement = "split"
15
+ command = ["sh", "-c", "exec python3 \"$HERDR_PLUGIN_ROOT/relay.py\""]
@@ -0,0 +1,401 @@
1
+ #!/usr/bin/env python3
2
+ """hivey.slack-relay: bridge a hivey swarm's message bus and its Slack channel.
3
+
4
+ Slack → bus Human messages in the channel become bus messages from `human`:
5
+ `@scout` → scout, `@all`/`@here`/`@channel`/`@everyone` → @all,
6
+ `@coordinator`/`@master` → the master, no mention → the master.
7
+ Posts made by agents with the /swarm skill's swarm_slack.py
8
+ ("*[agent]* text") keep that agent as the sender.
9
+ bus → Slack Bus messages are mirrored into the channel. Scope (config "mirror"):
10
+ "masters" (default: only messages to/from a master or the human),
11
+ "all", or "off". Messages that came from Slack are never echoed.
12
+ Quiet mode While ~/.hivey/quiet exists (hivey menu → quiet mode, `hivey quiet on`), bus →
13
+ Slack posts are held; when it ends they go out as one catch-up message, with
14
+ posts agents held through swarm_slack.py (~/.hivey/quiet-held/<channel>.jsonl).
15
+ Slack → bus keeps working.
16
+
17
+ Environment (set by `hivey swarm launch --addon hivey.slack-relay`):
18
+ HIVEY_SWARM_ROOT swarm folder (required) HIVEY_SWARM_SLUG swarm slug
19
+ HIVEY_SWARM_CHANNEL Slack channel id (else the manifest's channel_id)
20
+ HERDR_BIN_PATH hivey binary (set by hivey for plugin panes)
21
+ Config: $HERDR_PLUGIN_CONFIG_DIR/config.json
22
+ {"token_command": "envsave get <id>", "mirror": "masters", "interval": 10}
23
+ The token comes from $SLACK_TOKEN if set, else from token_command's output.
24
+ Scopes needed: channels:history, chat:write (groups:history for private channels).
25
+ State: <root>/.swarm/slack_relay_state.json (last Slack ts, bus offset, echo guards).
26
+ """
27
+ import json
28
+ import os
29
+ import re
30
+ import subprocess
31
+ import sys
32
+ import time
33
+ import urllib.parse
34
+ import urllib.request
35
+ from pathlib import Path
36
+
37
+ SENDER_RE = re.compile(r"^(?:(?::[a-z0-9_+-]+:|[^\x00-\x7F]+)\s+)?\*\[([^\]]+)\]\*\s*")
38
+ MENTION_RE = re.compile(r"@([a-z][a-z0-9_-]*)")
39
+ # The relay's own posts: a mirror ("👤 *human → coordinator*: …") or a quiet-mode catch-up.
40
+ # Slack returns emoji as :shortcodes:. Agent posts ("*[scout]* …") don't match.
41
+ RELAY_POST_RE = re.compile(
42
+ r"^(?::[a-z0-9_+-]+:|[^\x00-\x7F]+)\s+\*(?:[^*\n]+ → [^*\n]+|Quiet mode ended[^*\n]*)\*")
43
+ BROADCAST = {"all", "everyone", "here", "channel"}
44
+ MASTER_ALIASES = {"coordinator", "master"}
45
+ ROLE_EMOJI = {"master": "🧭", "critic": "🧐", "script": "⚙️"}
46
+ FIXED_EMOJI = {"human": "👤", "hivey": "⚙️"}
47
+ PALETTE = ["🦊", "🐙", "🦉", "🐝", "🦄", "🐬", "🦖", "🐢", "🦜", "🐳", "🦋", "🐧"]
48
+ KEEP_GUARDS = 500 # echo-guard ids/timestamps remembered
49
+ KEEP_HELD = 500 # posts held in quiet mode
50
+ CATCH_UP_LINES = 40 # lines in the catch-up message; the rest are counted
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Pure logic (unit-tested in test_relay.py)
55
+ # ---------------------------------------------------------------------------
56
+
57
+ def roster(manifest):
58
+ """{agent key: role} from a /swarm or hivey manifest (master included)."""
59
+ roles = {}
60
+ for key, entry in (manifest.get("agents") or {}).items():
61
+ role = entry.get("role") or ("critic" if key == "critic" else "worker")
62
+ roles[key] = "master" if role in MASTER_ALIASES else role
63
+ if not any(role == "master" for role in roles.values()):
64
+ roles["coordinator"] = "master"
65
+ return roles
66
+
67
+
68
+ def master_key(roles):
69
+ return next((key for key, role in roles.items() if role == "master"), "coordinator")
70
+
71
+
72
+ def parse_slack(text, manifest):
73
+ """(sender key or 'human', body, [targets]) for one Slack message.
74
+
75
+ Targets are bus addresses inside the swarm: agent keys, '@all' or the master key.
76
+ """
77
+ roles = roster(manifest)
78
+ slug = manifest.get("slug", "")
79
+ match = SENDER_RE.match(text)
80
+ sender = match.group(1) if match else "human"
81
+ body = text[match.end():] if match else text
82
+ body = re.sub(r"<!(channel|here|everyone)[^>]*>", r"@\1", body)
83
+ by_name = {key: key for key in roles}
84
+ by_name.update({f"{slug}-{key}": key for key in roles})
85
+ targets = []
86
+ for word in MENTION_RE.findall(body.lower()):
87
+ if word in BROADCAST:
88
+ target = "@all"
89
+ elif word in MASTER_ALIASES:
90
+ target = master_key(roles)
91
+ else:
92
+ target = by_name.get(word)
93
+ if target and target not in targets and target != sender:
94
+ targets.append(target)
95
+ if not targets and sender == "human":
96
+ targets.append(master_key(roles))
97
+ return sender, body.strip(), targets
98
+
99
+
100
+ def is_relay_post(text):
101
+ """True for text this relay posted. Its ts guard can miss one (a second relay on the
102
+ channel, a restart between post and save); injecting it again starts an echo loop."""
103
+ return bool(RELAY_POST_RE.match(text or ""))
104
+
105
+
106
+ def involves_master(message, roles):
107
+ def is_master(label):
108
+ return label.split("/")[-1] in {k for k, r in roles.items() if r == "master"}
109
+ return (
110
+ message.get("from") in FIXED_EMOJI
111
+ or message.get("to") == "human"
112
+ or is_master(message.get("from", ""))
113
+ or is_master(message.get("to", ""))
114
+ )
115
+
116
+
117
+ def should_mirror(message, scope, roles, injected):
118
+ if scope == "off" or message.get("copy") or message.get("id") in injected:
119
+ return False
120
+ return scope == "all" or involves_master(message, roles)
121
+
122
+
123
+ def emoji(label, roles):
124
+ if label in FIXED_EMOJI:
125
+ return FIXED_EMOJI[label]
126
+ key = label.split("/")[-1]
127
+ if roles.get(key) in ROLE_EMOJI:
128
+ return ROLE_EMOJI[roles[key]]
129
+ return PALETTE[sum(map(ord, key)) % len(PALETTE)]
130
+
131
+
132
+ def format_mirror(message, roles, slug):
133
+ def short(label):
134
+ return label[len(slug) + 1:] if label.startswith(f"{slug}/") else label
135
+ target = message.get("to", "?")
136
+ if message.get("swarm") and message["swarm"] != slug:
137
+ target = f"{message['swarm']}/{target}"
138
+ kind = {"fyi": " _(fyi)_", "urgent": " *(urgent)*"}.get(message.get("kind"), "")
139
+ return (f"{emoji(message.get('from', '?'), roles)} *{short(message.get('from', '?'))} → "
140
+ f"{short(target)}*{kind}: {message.get('text', '')}")
141
+
142
+
143
+ def format_catch_up(lines):
144
+ """The one message that replaces the posts held while quiet mode was on."""
145
+ shown = [line if len(line) <= 600 else line[:600] + "…" for line in lines[-CATCH_UP_LINES:]]
146
+ head = f"🌙 *Quiet mode ended: {len(lines)} update{'s' if len(lines) != 1 else ''} while it was on*"
147
+ if len(lines) > len(shown):
148
+ head += f" _(last {len(shown)}; all of them: `hivey msg log`)_"
149
+ return "\n".join([head] + shown)
150
+
151
+
152
+ def new_bus_messages(path, offset):
153
+ """(messages appended since offset, new offset); tolerates a torn last line."""
154
+ try:
155
+ with open(path, "rb") as f:
156
+ f.seek(offset)
157
+ data = f.read()
158
+ except FileNotFoundError:
159
+ return [], offset
160
+ end = data.rfind(b"\n") + 1 # only complete lines
161
+ messages = []
162
+ for line in data[:end].splitlines():
163
+ try:
164
+ record = json.loads(line)
165
+ except json.JSONDecodeError:
166
+ continue
167
+ if record.get("ev") == "msg":
168
+ messages.append(record)
169
+ return messages, offset + end
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # I/O
174
+ # ---------------------------------------------------------------------------
175
+
176
+ class Slack:
177
+ def __init__(self, token):
178
+ self.token = token
179
+
180
+ def call(self, method, http="POST", **params):
181
+ url = f"https://slack.com/api/{method}"
182
+ headers = {"Authorization": f"Bearer {self.token}"}
183
+ if http == "GET":
184
+ req = urllib.request.Request(url + "?" + urllib.parse.urlencode(params), headers=headers)
185
+ else:
186
+ headers["Content-Type"] = "application/json; charset=utf-8"
187
+ req = urllib.request.Request(url, data=json.dumps(params).encode(), headers=headers)
188
+ with urllib.request.urlopen(req, timeout=30) as resp:
189
+ data = json.loads(resp.read().decode())
190
+ if not data.get("ok"):
191
+ raise RuntimeError(f"slack {method}: {data.get('error')}")
192
+ return data
193
+
194
+ def history(self, channel, oldest):
195
+ messages, cursor = [], ""
196
+ while True:
197
+ data = self.call("conversations.history", http="GET", channel=channel,
198
+ oldest=oldest, limit=200, cursor=cursor)
199
+ messages += data.get("messages", [])
200
+ cursor = data.get("response_metadata", {}).get("next_cursor", "")
201
+ if not data.get("has_more") or not cursor:
202
+ return sorted(messages, key=lambda m: float(m["ts"]))
203
+
204
+ def post(self, channel, text):
205
+ return self.call("chat.postMessage", channel=channel, text=text)["ts"]
206
+
207
+
208
+ class Hivey:
209
+ def __init__(self, binary, slug):
210
+ self.binary, self.slug = binary, slug
211
+
212
+ def send(self, target, text, sender):
213
+ frm = "human" if sender == "human" else f"{self.slug}/{sender}"
214
+ cmd = [self.binary, "msg", "send", target, text, "--swarm", self.slug, "--from", frm, "--json"]
215
+ out = subprocess.run(cmd, capture_output=True, text=True)
216
+ if out.returncode != 0:
217
+ raise RuntimeError((out.stderr or out.stdout).strip())
218
+ return [sent["id"] for sent in json.loads(out.stdout).get("sent", [])]
219
+
220
+
221
+ def load_config():
222
+ path = Path(os.environ.get("HERDR_PLUGIN_CONFIG_DIR", ".")) / "config.json"
223
+ try:
224
+ return json.loads(path.read_text())
225
+ except (OSError, json.JSONDecodeError):
226
+ return {}
227
+
228
+
229
+ def resolve_token(config):
230
+ if os.environ.get("SLACK_TOKEN"):
231
+ return os.environ["SLACK_TOKEN"]
232
+ command = config.get("token_command")
233
+ if not command:
234
+ return None
235
+ out = subprocess.run(command, shell=True, capture_output=True, text=True)
236
+ return out.stdout.strip() or None
237
+
238
+
239
+ def hivey_dir():
240
+ return Path(os.environ.get("HIVEY_HOME") or Path.home() / ".hivey")
241
+
242
+
243
+ def quiet_mode_on():
244
+ return (hivey_dir() / "quiet").exists()
245
+
246
+
247
+ def take_held_posts(channel):
248
+ """Posts agents held through swarm_slack.py in quiet mode for this channel (claimed by
249
+ renaming the file, so a concurrent writer starts a new one)."""
250
+ path = hivey_dir() / "quiet-held" / f"{channel}.jsonl"
251
+ claimed = path.with_suffix(f".{os.getpid()}.claimed")
252
+ try:
253
+ path.replace(claimed)
254
+ except FileNotFoundError:
255
+ return []
256
+ texts = []
257
+ for line in claimed.read_text().splitlines():
258
+ try:
259
+ texts.append(json.loads(line)["text"])
260
+ except (json.JSONDecodeError, KeyError, TypeError):
261
+ continue
262
+ claimed.unlink()
263
+ return texts
264
+
265
+
266
+ def log(line):
267
+ print(f"{time.strftime('%H:%M:%S')} {line}", flush=True)
268
+
269
+
270
+ class Relay:
271
+ def __init__(self, root, slack, hivey, channel, scope, quiet=quiet_mode_on,
272
+ held_posts=take_held_posts):
273
+ self.root, self.slack, self.hivey = Path(root), slack, hivey
274
+ self.channel, self.scope = channel, scope
275
+ self.quiet, self.held_posts = quiet, held_posts
276
+ self.state_path = self.root / ".swarm" / "slack_relay_state.json"
277
+ self.bus_path = self.root / ".swarm" / "bus.jsonl"
278
+ try:
279
+ self.state = json.loads(self.state_path.read_text())
280
+ except (OSError, json.JSONDecodeError):
281
+ # First run: start from now; don't replay history either way.
282
+ self.state = {"last_ts": f"{time.time():.6f}",
283
+ "bus_offset": self.bus_path.stat().st_size if self.bus_path.exists() else 0,
284
+ "injected": [], "posted": []}
285
+ self.state.setdefault("held", [])
286
+
287
+ def manifest(self):
288
+ return json.loads((self.root / ".swarm" / "agents.json").read_text())
289
+
290
+ def save(self):
291
+ for key in ("injected", "posted"):
292
+ self.state[key] = self.state[key][-KEEP_GUARDS:]
293
+ self.state["held"] = self.state["held"][-KEEP_HELD:]
294
+ tmp = self.state_path.with_suffix(".tmp")
295
+ tmp.write_text(json.dumps(self.state))
296
+ tmp.replace(self.state_path)
297
+
298
+ def slack_to_bus(self, manifest):
299
+ for msg in self.slack.history(self.channel, self.state["last_ts"]):
300
+ self.state["last_ts"] = msg["ts"]
301
+ if msg["ts"] in self.state["posted"] or msg.get("subtype") in ("channel_join", "bot_add"):
302
+ continue
303
+ if is_relay_post(msg.get("text", "")):
304
+ continue
305
+ sender, body, targets = parse_slack(msg.get("text", ""), manifest)
306
+ for target in targets:
307
+ try:
308
+ ids = self.hivey.send(target, body, sender)
309
+ self.state["injected"] += ids
310
+ log(f"slack → bus {sender} → {target}: {body[:70]!r}")
311
+ except RuntimeError as err:
312
+ log(f"slack → bus failed for {target}: {err}")
313
+
314
+ def bus_to_slack(self, manifest):
315
+ quiet = self.quiet()
316
+ if not quiet:
317
+ self.catch_up() # before reading the bus: if it fails, nothing new is lost
318
+ messages, self.state["bus_offset"] = new_bus_messages(self.bus_path, self.state["bus_offset"])
319
+ roles = roster(manifest)
320
+ for message in messages:
321
+ if not should_mirror(message, self.scope, roles, set(self.state["injected"])):
322
+ continue
323
+ text = format_mirror(message, roles, manifest.get("slug", ""))
324
+ if quiet:
325
+ self.state["held"].append(text)
326
+ log(f"bus → held {message.get('from')} → {message.get('to')} (quiet mode)")
327
+ continue
328
+ ts = self.slack.post(self.channel, text)
329
+ self.state["posted"].append(ts)
330
+ log(f"bus → slack {message.get('from')} → {message.get('to')}")
331
+
332
+ def catch_up(self):
333
+ """After quiet mode: everything held goes out as one message."""
334
+ held = self.state["held"] + self.held_posts(self.channel)
335
+ if not held:
336
+ return
337
+ # Saved until posted, so a failed post (or a restart) retries it
338
+ self.state["held"] = held
339
+ self.save()
340
+ ts = self.slack.post(self.channel, format_catch_up(held))
341
+ self.state["posted"].append(ts)
342
+ self.state["held"] = []
343
+ log(f"bus → slack catch-up of {len(held)} held post(s)")
344
+
345
+ def step(self):
346
+ manifest = self.manifest()
347
+ self.slack_to_bus(manifest)
348
+ self.bus_to_slack(manifest)
349
+ self.save()
350
+
351
+
352
+ def claim(pid_path):
353
+ """Make this process the swarm's relay. Returns a check that is False once a newer relay
354
+ has claimed it: closing a pane doesn't always stop the relay in it, and two relays on one
355
+ channel double every post and poll (HTTP 429) and can echo each other's posts."""
356
+ pid_path.write_text(str(os.getpid()))
357
+
358
+ def still_ours():
359
+ try:
360
+ return pid_path.read_text().strip() == str(os.getpid())
361
+ except OSError:
362
+ return True # unreadable for a moment: keep going, the next check decides
363
+ return still_ours
364
+
365
+
366
+ def main():
367
+ root = os.environ.get("HIVEY_SWARM_ROOT") or (sys.argv[1] if len(sys.argv) > 1 else "")
368
+ if not root:
369
+ sys.exit("HIVEY_SWARM_ROOT is not set (open this through `hivey swarm launch --addon`)")
370
+ config = load_config()
371
+ manifest = json.loads((Path(root) / ".swarm" / "agents.json").read_text())
372
+ slug = os.environ.get("HIVEY_SWARM_SLUG") or manifest["slug"]
373
+ channel = os.environ.get("HIVEY_SWARM_CHANNEL") or manifest.get("channel_id")
374
+ scope = config.get("mirror", "masters")
375
+ interval = float(config.get("interval", 10))
376
+ binary = os.environ.get("HERDR_BIN_PATH", "hivey")
377
+ log(f"hivey slack relay for swarm {slug!r}, channel {channel}, mirror={scope}")
378
+ if not channel:
379
+ log("no Slack channel (manifest channel_id / HIVEY_SWARM_CHANNEL); idle")
380
+ token = None
381
+ while not (channel and token):
382
+ token = token or resolve_token(config)
383
+ if channel and not token:
384
+ log(f"no Slack token: set SLACK_TOKEN or token_command in "
385
+ f"{os.environ.get('HERDR_PLUGIN_CONFIG_DIR', '?')}/config.json; retrying in 60s")
386
+ time.sleep(60 if not (channel and token) else 0)
387
+ relay = Relay(root, Slack(token), Hivey(binary, slug), channel, scope)
388
+ still_ours = claim(Path(root) / ".swarm" / "slack_relay.pid")
389
+ while True:
390
+ if not still_ours():
391
+ log("a newer relay took over this swarm; exiting")
392
+ return
393
+ try:
394
+ relay.step()
395
+ except Exception as err: # network blips, a bad manifest read: keep relaying
396
+ log(f"error: {err}")
397
+ time.sleep(interval)
398
+
399
+
400
+ if __name__ == "__main__":
401
+ main()
@@ -0,0 +1,30 @@
1
+ {
2
+ "display_information": {
3
+ "name": "hivey",
4
+ "description": "Talk to your hivey agents and swarms from Slack",
5
+ "background_color": "#2d2a3e"
6
+ },
7
+ "features": {
8
+ "bot_user": {
9
+ "display_name": "hivey",
10
+ "always_online": true
11
+ }
12
+ },
13
+ "oauth_config": {
14
+ "scopes": {
15
+ "bot": [
16
+ "channels:history",
17
+ "channels:join",
18
+ "channels:manage",
19
+ "channels:read",
20
+ "chat:write",
21
+ "groups:history"
22
+ ]
23
+ }
24
+ },
25
+ "settings": {
26
+ "org_deploy_enabled": false,
27
+ "socket_mode_enabled": false,
28
+ "token_rotation_enabled": false
29
+ }
30
+ }
@@ -0,0 +1,66 @@
1
+ """Tests for connect.py (no network: Slack calls are stubbed)."""
2
+ import io
3
+ import json
4
+ import os
5
+ import stat
6
+ import tempfile
7
+ import unittest
8
+ from contextlib import redirect_stderr
9
+ from pathlib import Path
10
+ from unittest import mock
11
+
12
+ import connect
13
+
14
+
15
+ class ConnectTest(unittest.TestCase):
16
+ def setUp(self):
17
+ self.dir = tempfile.TemporaryDirectory()
18
+ self.env = mock.patch.dict(os.environ, {"HERDR_PLUGIN_CONFIG_DIR": self.dir.name})
19
+ self.env.start()
20
+ os.environ.pop("SLACK_TOKEN", None)
21
+
22
+ def tearDown(self):
23
+ self.env.stop()
24
+ self.dir.cleanup()
25
+
26
+ def test_save_token_is_private_and_keeps_other_settings(self):
27
+ config = Path(self.dir.name) / "config.json"
28
+ config.write_text(json.dumps({"mirror": "all", "token_command": "old"}))
29
+ token_file = connect.save_token("xoxb-secret")
30
+ self.assertEqual(stat.S_IMODE(token_file.stat().st_mode), 0o600)
31
+ self.assertEqual(token_file.read_text().strip(), "xoxb-secret")
32
+ saved = json.loads(config.read_text())
33
+ self.assertEqual(saved["mirror"], "all")
34
+ self.assertEqual(saved["token_command"], f"cat '{token_file}'")
35
+ self.assertNotIn("xoxb-secret", config.read_text())
36
+
37
+ def test_not_connected_without_a_token(self):
38
+ state = connect.current()
39
+ self.assertFalse(state["connected"])
40
+ self.assertIn("not connected", connect.describe(state))
41
+
42
+ def test_connected_reports_missing_scopes(self):
43
+ connect.save_token("xoxb-ok")
44
+ reply = ({"ok": True, "team": "Acme", "user": "hivey"}, {"chat:write"})
45
+ with mock.patch.object(connect, "auth_test", return_value=reply):
46
+ state = connect.current()
47
+ self.assertTrue(state["connected"])
48
+ self.assertIn("channels:manage", state["missing_scopes"])
49
+ self.assertIn("missing scopes", connect.describe(state))
50
+
51
+ def test_refused_token_is_not_connected(self):
52
+ connect.save_token("xoxb-revoked")
53
+ with mock.patch.object(connect, "auth_test", side_effect=RuntimeError("token_revoked")):
54
+ state = connect.current()
55
+ self.assertFalse(state["connected"])
56
+ self.assertIn("token_revoked", state["error"])
57
+
58
+ def test_connect_needs_a_terminal(self):
59
+ err = io.StringIO()
60
+ with mock.patch("sys.stdin", io.StringIO("")), redirect_stderr(err):
61
+ self.assertEqual(connect.connect(force=False), 1)
62
+ self.assertIn("never paste it into a chat", err.getvalue())
63
+
64
+
65
+ if __name__ == "__main__":
66
+ unittest.main()