@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,261 @@
1
+ #!/usr/bin/env python3
2
+ """hivey.github: publish a swarm as two GitHub repos, the product and the workspace.
3
+
4
+ <owner>/<slug> the product the swarm builds (e.g. <root>/app), its own git repo
5
+ <owner>/<slug>-swarm the swarm workspace: agent folders and briefs, .swarm/ logs, shared/,
6
+ with the product folder, builders' worktrees, secrets and runtime
7
+ state excluded by .gitignore
8
+
9
+ Nothing is created until you confirm in the pane. Before the first push of each repo,
10
+ gitleaks (if installed) scans it and any finding aborts. Afterwards the pane offers
11
+ "push both" (commits a workspace snapshot, pushes the product's current branch and the
12
+ builders' swarm/* branches).
13
+
14
+ Config ($HERDR_PLUGIN_CONFIG_DIR/config.json, all optional):
15
+ {"owner": "<user or org>", "visibility": "private", "product_dirs": ["app"],
16
+ "product_repo": "{slug}", "swarm_repo": "{slug}-swarm"}
17
+ The manifest's "product_dir" (relative to the root) wins over product_dirs.
18
+ HIVEY_GITHUB_DRY_RUN=1 prints the commands instead of running them.
19
+ """
20
+ import json
21
+ import os
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ from pathlib import Path
27
+
28
+ DEFAULT_CONFIG = {
29
+ "owner": "",
30
+ "visibility": "private",
31
+ "product_dirs": ["app"],
32
+ "product_repo": "{slug}",
33
+ "swarm_repo": "{slug}-swarm",
34
+ }
35
+ # The workspace repo never carries these (the product has its own repo).
36
+ WORKSPACE_IGNORE = [
37
+ "# hivey.github: the product is published as its own repo",
38
+ "/{product}/",
39
+ "# builders' git worktrees of the product",
40
+ "/*/repo/",
41
+ "# secrets",
42
+ ".env",
43
+ ".env.*",
44
+ "*.pem",
45
+ "*.key",
46
+ "*.p12",
47
+ "# runtime state",
48
+ ".swarm/*.lock",
49
+ ".swarm/*.tmp",
50
+ ".swarm/dashboard_usage.json",
51
+ ".swarm/slack_relay_state.json",
52
+ ".swarm/relay_state.json",
53
+ "node_modules/",
54
+ ".DS_Store",
55
+ ]
56
+ MARKER = WORKSPACE_IGNORE[0]
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Pure planning (unit-tested in test_github.py)
61
+ # ---------------------------------------------------------------------------
62
+
63
+ def find_product(root, manifest, config):
64
+ """Relative product folder, or None when the swarm builds nothing to publish."""
65
+ candidates = [manifest.get("product_dir")] if manifest.get("product_dir") else []
66
+ candidates += config.get("product_dirs", [])
67
+ for rel in candidates:
68
+ if rel and (Path(root) / rel).is_dir():
69
+ return rel.strip("/")
70
+ # Else a top-level folder that is its own git repo and isn't an agent's home.
71
+ agents = set((manifest.get("agents") or {}).keys())
72
+ for child in sorted(Path(root).iterdir()):
73
+ if child.is_dir() and child.name not in agents and not child.name.startswith(".") \
74
+ and (child / ".git").exists():
75
+ return child.name
76
+ return None
77
+
78
+
79
+ def workspace_gitignore(existing, product):
80
+ """`existing` .gitignore text with hivey's block appended once."""
81
+ if MARKER in existing:
82
+ return existing
83
+ lines = [line.replace("{product}", product) for line in WORKSPACE_IGNORE
84
+ if product or "{product}" not in line]
85
+ block = "\n".join(lines) + "\n"
86
+ if existing and not existing.endswith("\n"):
87
+ existing += "\n"
88
+ return existing + ("\n" if existing else "") + block
89
+
90
+
91
+ def repo_names(slug, config):
92
+ return (config["product_repo"].format(slug=slug), config["swarm_repo"].format(slug=slug))
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Git / GitHub
97
+ # ---------------------------------------------------------------------------
98
+
99
+ DRY_RUN = os.environ.get("HIVEY_GITHUB_DRY_RUN") == "1"
100
+
101
+
102
+ def run(cmd, cwd, check=True):
103
+ shown = " ".join(cmd)
104
+ if DRY_RUN:
105
+ print(f" [dry-run] ({cwd}) {shown}")
106
+ return ""
107
+ out = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
108
+ if check and out.returncode != 0:
109
+ raise RuntimeError(f"{shown}: {(out.stderr or out.stdout).strip()}")
110
+ return out.stdout.strip()
111
+
112
+
113
+ def git(cwd, *args, check=True):
114
+ return run(["git", *args], cwd, check)
115
+
116
+
117
+ def is_repo(path):
118
+ return (Path(path) / ".git").exists()
119
+
120
+
121
+ def has_commits(path):
122
+ return subprocess.run(["git", "rev-parse", "HEAD"], cwd=path, capture_output=True).returncode == 0
123
+
124
+
125
+ def has_origin(path):
126
+ return subprocess.run(["git", "remote", "get-url", "origin"], cwd=path,
127
+ capture_output=True).returncode == 0
128
+
129
+
130
+ def scan_secrets(path):
131
+ if not shutil.which("gitleaks"):
132
+ print(" (gitleaks not installed: secret scan skipped)")
133
+ return
134
+ if DRY_RUN:
135
+ print(f" [dry-run] gitleaks git {path}")
136
+ return
137
+ # Scan what is committed (what gets pushed), not ignored files on disk.
138
+ out = subprocess.run(["gitleaks", "git", str(path), "--no-banner", "--redact"],
139
+ capture_output=True, text=True)
140
+ if out.returncode != 0:
141
+ raise RuntimeError(f"gitleaks found possible secrets in {path}; nothing was pushed.\n"
142
+ f"{(out.stdout or out.stderr)[-1500:]}")
143
+
144
+
145
+ def publish(path, full_name, visibility, message):
146
+ """Commit (if needed) and create + push the GitHub repo, or push to the existing origin."""
147
+ if not is_repo(path):
148
+ git(path, "init", "-b", "main")
149
+ if not has_commits(path) or git(path, "status", "--porcelain", check=False):
150
+ git(path, "add", "-A")
151
+ git(path, "commit", "-m", message, check=False)
152
+ scan_secrets(path)
153
+ if has_origin(path):
154
+ git(path, "push", "-u", "origin", "HEAD")
155
+ else:
156
+ run(["gh", "repo", "create", full_name, f"--{visibility}", "--source", str(path),
157
+ "--remote", "origin", "--push"], path)
158
+
159
+
160
+ def push_both(root, product):
161
+ if product and is_repo(root / product):
162
+ git(root / product, "push", "origin", "HEAD", check=False)
163
+ branches = git(root / product, "branch", "--list", "swarm/*", "--format=%(refname:short)",
164
+ check=False).split()
165
+ for branch in branches:
166
+ git(root / product, "push", "origin", branch, check=False)
167
+ print(f" ✓ product pushed ({1 + len(branches)} branch(es))")
168
+ if is_repo(root):
169
+ if git(root, "status", "--porcelain", check=False) or DRY_RUN:
170
+ git(root, "add", "-A")
171
+ git(root, "commit", "-m", f"swarm snapshot {time.strftime('%Y-%m-%d %H:%M')}", check=False)
172
+ git(root, "push", "origin", "HEAD", check=False)
173
+ print(" ✓ workspace pushed")
174
+
175
+
176
+ # ---------------------------------------------------------------------------
177
+ # Pane UI
178
+ # ---------------------------------------------------------------------------
179
+
180
+ def ask(prompt):
181
+ try:
182
+ return input(prompt).strip()
183
+ except EOFError:
184
+ return "q"
185
+
186
+
187
+ def main():
188
+ root = Path(os.environ.get("HIVEY_SWARM_ROOT") or (sys.argv[1] if len(sys.argv) > 1 else ""))
189
+ if not str(root):
190
+ sys.exit("HIVEY_SWARM_ROOT is not set (open with `hivey swarm addon <swarm> hivey.github`)")
191
+ manifest_path = root / ".swarm" / "agents.json"
192
+ manifest = json.loads(manifest_path.read_text())
193
+ slug = os.environ.get("HIVEY_SWARM_SLUG") or manifest["slug"]
194
+ config = dict(DEFAULT_CONFIG)
195
+ try:
196
+ config.update(json.loads((Path(os.environ.get("HERDR_PLUGIN_CONFIG_DIR", ".")) / "config.json").read_text()))
197
+ except (OSError, json.JSONDecodeError):
198
+ pass
199
+ # Read-only lookup: runs in dry-run mode too.
200
+ owner = config["owner"] or subprocess.run(
201
+ ["gh", "api", "user", "-q", ".login"], capture_output=True, text=True).stdout.strip() or "<you>"
202
+ product = find_product(root, manifest, config)
203
+ product_repo, swarm_repo = repo_names(slug, config)
204
+ published = manifest.get("github") or {}
205
+
206
+ print(f"hivey · GitHub for swarm {slug}{' (dry run)' if DRY_RUN else ''}\n")
207
+ if product:
208
+ print(f" product {root / product}\n → {published.get('product') or f'{owner}/{product_repo}'}")
209
+ else:
210
+ print(" product (none found: set product_dir in the manifest or product_dirs in config)")
211
+ print(f" workspace {root} (without {product + '/' if product else 'the product'}, worktrees, secrets)"
212
+ f"\n → {published.get('swarm') or f'{owner}/{swarm_repo}'}")
213
+ print(f" visibility {config['visibility']}\n")
214
+
215
+ if not published.get("swarm"):
216
+ answer = ask("create and push these repos? [y/N] ").lower()
217
+ if answer != "y":
218
+ print("nothing created.")
219
+ else:
220
+ try:
221
+ if product:
222
+ publish(root / product, f"{owner}/{product_repo}", config["visibility"],
223
+ "initial commit")
224
+ published["product"] = f"{owner}/{product_repo}"
225
+ gi = root / ".gitignore"
226
+ gi_text = workspace_gitignore(gi.read_text() if gi.exists() else "", product or "")
227
+ if DRY_RUN:
228
+ print(f" [dry-run] write {gi}:\n" + "\n".join(" " + l for l in gi_text.splitlines()))
229
+ else:
230
+ gi.write_text(gi_text)
231
+ publish(root, f"{owner}/{swarm_repo}", config["visibility"], "swarm workspace")
232
+ published["swarm"] = f"{owner}/{swarm_repo}"
233
+ if not DRY_RUN:
234
+ manifest = json.loads(manifest_path.read_text())
235
+ manifest["github"] = published
236
+ tmp = manifest_path.with_suffix(".tmp")
237
+ tmp.write_text(json.dumps(manifest, indent=2) + "\n")
238
+ tmp.replace(manifest_path)
239
+ print(f"\n ✓ published: {', '.join(published.values())}")
240
+ except RuntimeError as err:
241
+ print(f"\n ✗ {err}")
242
+
243
+ while True:
244
+ choice = ask("\n[p] push both now · [s] status · [q] quit: ").lower()
245
+ if choice == "p":
246
+ try:
247
+ push_both(root, product)
248
+ except RuntimeError as err:
249
+ print(f" ✗ {err}")
250
+ elif choice == "s":
251
+ for label, path in (("product", root / product if product else None), ("workspace", root)):
252
+ if path and is_repo(path):
253
+ status = git(path, "status", "--short", "--branch", check=False)
254
+ print(f" {label}: {status.splitlines()[0] if status else '?'}"
255
+ f" ({max(0, len(status.splitlines()) - 1)} changed)")
256
+ elif choice == "q":
257
+ return
258
+
259
+
260
+ if __name__ == "__main__":
261
+ main()
@@ -0,0 +1,14 @@
1
+ id = "hivey.github"
2
+ name = "Swarm GitHub"
3
+ version = "0.1.0"
4
+ min_herdr_version = "0.9.0"
5
+ description = "hivey swarm addon: publish the product and the swarm workspace as two separate GitHub repos"
6
+ platforms = ["linux", "macos"]
7
+
8
+ # `hivey swarm addon <swarm> hivey.github` (or `--addon hivey.github` at launch).
9
+ # Interactive: shows the plan and creates nothing until you confirm in the pane.
10
+ [[panes]]
11
+ id = "github"
12
+ title = "swarm github"
13
+ placement = "split"
14
+ command = ["sh", "-c", "exec python3 \"$HERDR_PLUGIN_ROOT/github.py\""]
@@ -0,0 +1,49 @@
1
+ """Tests for the hivey GitHub addon: python3 -m unittest plugins/github/test_github.py"""
2
+ import subprocess
3
+ import sys
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
9
+ import github # noqa: E402
10
+
11
+ CONFIG = dict(github.DEFAULT_CONFIG)
12
+
13
+
14
+ class Planning(unittest.TestCase):
15
+ def test_product_dir_from_manifest_config_or_a_nested_repo(self):
16
+ with tempfile.TemporaryDirectory() as tmp:
17
+ root = Path(tmp)
18
+ (root / "scout").mkdir()
19
+ (root / "site").mkdir()
20
+ self.assertIsNone(github.find_product(root, {"agents": {"scout": {}}}, CONFIG))
21
+ subprocess.run(["git", "init", "-q", str(root / "site")], check=True)
22
+ self.assertEqual(github.find_product(root, {"agents": {"scout": {}}}, CONFIG), "site")
23
+ (root / "app").mkdir()
24
+ self.assertEqual(github.find_product(root, {}, CONFIG), "app")
25
+ self.assertEqual(github.find_product(root, {"product_dir": "site/"}, CONFIG), "site")
26
+
27
+ def test_agent_worktrees_are_not_mistaken_for_the_product(self):
28
+ with tempfile.TemporaryDirectory() as tmp:
29
+ root = Path(tmp)
30
+ subprocess.run(["git", "init", "-q", str(root / "builder")], check=True)
31
+ self.assertIsNone(github.find_product(root, {"agents": {"builder": {}}}, CONFIG))
32
+
33
+ def test_workspace_gitignore_excludes_product_worktrees_and_secrets_once(self):
34
+ text = github.workspace_gitignore("node_modules/", "app")
35
+ self.assertTrue(text.startswith("node_modules/\n\n"))
36
+ for line in ("/app/", "/*/repo/", ".env", ".env.*", ".swarm/*.lock"):
37
+ self.assertIn(line + "\n", text)
38
+ self.assertEqual(github.workspace_gitignore(text, "app"), text, "idempotent")
39
+ self.assertNotIn("{product}", github.workspace_gitignore("", ""))
40
+ self.assertNotIn("\n//\n", github.workspace_gitignore("", ""))
41
+
42
+ def test_repo_names(self):
43
+ self.assertEqual(github.repo_names("habit", CONFIG), ("habit", "habit-swarm"))
44
+ custom = dict(CONFIG, product_repo="{slug}-app", swarm_repo="agents-{slug}")
45
+ self.assertEqual(github.repo_names("habit", custom), ("habit-app", "agents-habit"))
46
+
47
+
48
+ if __name__ == "__main__":
49
+ unittest.main()
@@ -0,0 +1,11 @@
1
+ id = "hivey.skills"
2
+ name = "Skills"
3
+ version = "0.1.0"
4
+ min_herdr_version = "0.9.0"
5
+ description = "Skills provider (built in): picks each new agent's skills from skylls, finds missing ones on skills.sh, installs them in the agent's own folder"
6
+ platforms = ["linux", "macos"]
7
+
8
+ # A skills provider is any plugin with a `skills.md` next to its manifest: the instructions swarm
9
+ # and agent creators follow to give every agent the skills its task needs. They read the chosen
10
+ # one with `hivey skills guide` (choose it in settings → plugins or with
11
+ # `hivey skills providers --default ID`). This plugin has no panes.
@@ -0,0 +1,41 @@
1
+ # Giving each agent its skills (hivey.skills)
2
+
3
+ Follow this for every agent you create, after its mission is clear and before you show the plan.
4
+ Skills go **only into the agent's own folder** (`<agent folder>/.claude/skills/`), never into
5
+ the global Claude Code skills: global skills load into every session and crowd its context.
6
+
7
+ 1. **skylls first.** The skills library is skylls: the user's published skills and the ones
8
+ friends shared with them. `hivey skills` says whether skylls is installed and whether online
9
+ search is on (if skylls is missing, ask the user before installing it; `hivey skills` shows
10
+ how). Search once per capability the agent needs, one or two words each (e.g. `slack`,
11
+ `pdf`, `browser`, `stock`):
12
+ `skylls --json find <words> --limit 5` (one JSON object per line: `name`, `owner`,
13
+ `summary`, `installed`). Pick only what the agent will really use (usually 2–6); each
14
+ extra skill costs context in every one of its sessions.
15
+ 2. **Missing capabilities.** If skylls has nothing for something the agent needs and
16
+ `hivey skills` says online search is on, search skills.sh, following the `find-skills`
17
+ skill (https://www.skills.sh/vercel-labs/skills/find-skills; installed globally):
18
+ - first the leaderboard, https://skills.sh/ (popular, battle-tested skills by domain);
19
+ - then `hivey skills find <query>` (runs `npx skills find <query>`), one query per
20
+ capability, e.g. `stock market news`, `pdf extraction`;
21
+ - see what a repo offers before choosing: `npx skills add <owner/repo> -l`.
22
+ Judge results: prefer 1,000+ installs, official or well-known sources (`vercel-labs`,
23
+ `anthropics`, the tool's own vendor) and GitHub stars; skip unmaintained or obscure ones.
24
+ Don't install anything yet.
25
+ 3. **Put the choice in the plan**: per agent, `Skills: a, b (skylls) · c (skylls, from
26
+ <owner>) · owner/repo@skill (skills.sh, to install)`. Ask the user to confirm; online
27
+ skills always need a yes, since they run with the agent's permissions.
28
+ 4. **Install, once the agent's folder exists:**
29
+ - skylls skills: `(cd <agent folder> && skylls add <name> -a claude)` (no `-g`: into that
30
+ folder only; add `--from <owner>` when several people have one with that name).
31
+ - skills.sh skills: `hivey skills add <agent folder> <owner/repo> --skill <name>`
32
+ (installs into that folder only).
33
+ Check `ls <agent folder>/.claude/skills`.
34
+ 5. **Tell the agent.** In its CLAUDE.md, list its skills under Method with one line on when to
35
+ use each, and pass them to `hivey swarm launch … --skills a,b` (or `hivey swarm profile`) so
36
+ `hivey swarm directory` shows them.
37
+ 6. **New skills are saved with skylls.** When you write a new skill for an agent (with
38
+ `/skill-creator`), also offer to publish it so the user can reuse and share it: confirm
39
+ first, then `skylls push <agent folder>/.claude/skills/<name> -m "<what it does>"`. Push
40
+ scans for secrets and personal data and refuses if it finds any: remove them, never pass
41
+ `--skip-scan`. Sharing (`skylls share <name> @user`) only when the user asks.
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env python3
2
+ """Connect hivey to the user's Slack workspace: ask for a bot token, check it, store it.
3
+
4
+ usage: connect.py [--force] interactive: create the Slack app, paste its token
5
+ connect.py --status is Slack connected? (exit 0 yes, 1 no) [--json]
6
+
7
+ Run by `hivey slack connect` / `hivey slack status` and by install.sh. The token is typed
8
+ hidden, checked with Slack (auth.test), saved to <config dir>/slack-token (mode 600) and
9
+ read through config.json's token_command, so the relay and create_channel.py use it. An
10
+ existing working token_command (e.g. a secrets manager) is kept unless --force.
11
+ """
12
+ import argparse
13
+ import getpass
14
+ import json
15
+ import os
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import urllib.error
20
+ import urllib.request
21
+ from pathlib import Path
22
+
23
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
24
+ import relay # noqa: E402 (same folder)
25
+
26
+ HERE = Path(__file__).resolve().parent
27
+ APP_MANIFEST = HERE / "slack-app-manifest.json"
28
+ NEW_APP_URL = "https://api.slack.com/apps?new_app=1"
29
+ NEEDED_SCOPES = {"channels:history", "channels:join", "channels:manage", "channels:read",
30
+ "chat:write"}
31
+
32
+
33
+ def config_dir():
34
+ path = os.environ.get("HERDR_PLUGIN_CONFIG_DIR") or str(
35
+ Path.home() / ".config" / "hivey" / "plugins" / "config" / "hivey.slack-relay")
36
+ return Path(path)
37
+
38
+
39
+ def auth_test(token):
40
+ """(auth.test reply, granted scopes) for a token; raises RuntimeError when Slack refuses it."""
41
+ req = urllib.request.Request("https://slack.com/api/auth.test", data=b"",
42
+ headers={"Authorization": f"Bearer {token}"})
43
+ with urllib.request.urlopen(req, timeout=30) as resp:
44
+ data = json.loads(resp.read().decode())
45
+ scopes = {s.strip() for s in (resp.headers.get("x-oauth-scopes") or "").split(",")}
46
+ if not data.get("ok"):
47
+ raise RuntimeError(data.get("error") or "unknown error")
48
+ return data, scopes - {""}
49
+
50
+
51
+ def current():
52
+ """{connected, team, user, missing_scopes, error} for the configured token."""
53
+ os.environ["HERDR_PLUGIN_CONFIG_DIR"] = str(config_dir())
54
+ token = relay.resolve_token(relay.load_config())
55
+ if not token:
56
+ return {"connected": False, "error": "no Slack token set"}
57
+ try:
58
+ data, scopes = auth_test(token)
59
+ except urllib.error.URLError as err:
60
+ # No network (or Slack is down): not a token problem, so `hivey slack check` stays quiet
61
+ return {"connected": False, "offline": True, "error": f"cannot reach Slack: {err.reason}"}
62
+ except (RuntimeError, OSError) as err:
63
+ return {"connected": False, "error": f"Slack refused the token: {err}"}
64
+ return {"connected": True, "team": data.get("team"), "user": data.get("user"),
65
+ "missing_scopes": sorted(NEEDED_SCOPES - scopes) if scopes else []}
66
+
67
+
68
+ def describe(state):
69
+ if not state["connected"]:
70
+ return f"Slack: not connected ({state['error']})"
71
+ line = f"Slack: connected to {state['team']} as @{state['user']}"
72
+ if state["missing_scopes"]:
73
+ line += ("\n missing scopes: " + ", ".join(state["missing_scopes"]) +
74
+ " (add them under OAuth & Permissions, reinstall the app, then "
75
+ "hivey slack connect --force)")
76
+ return line
77
+
78
+
79
+ def save_token(token):
80
+ directory = config_dir()
81
+ directory.mkdir(parents=True, exist_ok=True)
82
+ token_file = directory / "slack-token"
83
+ fd = os.open(token_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
84
+ with os.fdopen(fd, "w") as handle:
85
+ handle.write(token + "\n")
86
+ os.chmod(token_file, 0o600)
87
+ config_path = directory / "config.json"
88
+ config = relay.load_config() if config_path.exists() else {}
89
+ config["token_command"] = f"cat '{token_file}'"
90
+ config.setdefault("mirror", "masters")
91
+ config.setdefault("interval", 10)
92
+ config_path.write_text(json.dumps(config, indent=2) + "\n")
93
+ return token_file
94
+
95
+
96
+ def remember_you(token):
97
+ """Who hivey invites to the channels it creates (config "invite"), so they show up in your
98
+ Slack: the person the bot already shares channels with, else your member id, asked once."""
99
+ import create_channel # same folder
100
+ config = relay.load_config()
101
+ if config.get("invite"):
102
+ return
103
+ try:
104
+ found = create_channel.shared_people(relay.Slack(token))[:1]
105
+ except (RuntimeError, OSError):
106
+ found = []
107
+ if not found:
108
+ print("\nhivey invites you to the channels it creates, so they appear in your Slack.")
109
+ try:
110
+ answer = input("Your Slack member ID (your profile → ⋯ → Copy member ID; "
111
+ "Enter to skip): ").strip()
112
+ except (EOFError, KeyboardInterrupt):
113
+ answer = ""
114
+ found = [answer] if answer.startswith(("U", "W")) else []
115
+ if found:
116
+ config["invite"] = found
117
+ (config_dir() / "config.json").write_text(json.dumps(config, indent=2) + "\n")
118
+ print(f"new channels will invite: {', '.join(found)}")
119
+ else:
120
+ print("skipped: new channels won't invite anyone (set \"invite\" in "
121
+ f"{config_dir() / 'config.json'})")
122
+
123
+
124
+ def walk_through():
125
+ print(f"""
126
+ Connect hivey to Slack (about 2 minutes):
127
+ 1. Open {NEW_APP_URL}
128
+ → "From a manifest" → pick your workspace → paste the manifest below → Create.
129
+ 2. Click "Install to Workspace" → Allow.
130
+ 3. Copy the "Bot User OAuth Token" (starts with xoxb-) from OAuth & Permissions.
131
+
132
+ Manifest ({APP_MANIFEST}):
133
+ {APP_MANIFEST.read_text()}""")
134
+ if sys.platform == "darwin" and shutil.which("pbcopy"):
135
+ subprocess.run(["pbcopy"], input=APP_MANIFEST.read_bytes(), check=False)
136
+ print("(the manifest is on your clipboard)")
137
+ if sys.platform == "darwin" and shutil.which("open"):
138
+ subprocess.run(["open", NEW_APP_URL], check=False)
139
+ elif shutil.which("xdg-open"):
140
+ subprocess.run(["xdg-open", NEW_APP_URL], check=False,
141
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
142
+
143
+
144
+ def connect(force):
145
+ state = current()
146
+ if state["connected"] and not force:
147
+ print(describe(state))
148
+ print("(hivey slack connect --force to use another token)")
149
+ return 0
150
+ if not sys.stdin.isatty():
151
+ print("hivey slack connect needs a terminal to type the token in "
152
+ "(never paste it into a chat)", file=sys.stderr)
153
+ return 1
154
+ walk_through()
155
+ for _ in range(3):
156
+ try:
157
+ token = getpass.getpass("\nPaste the Bot User OAuth Token (hidden, empty to cancel): ")
158
+ except (EOFError, KeyboardInterrupt):
159
+ print()
160
+ return 1
161
+ token = token.strip()
162
+ if not token:
163
+ print("cancelled: Slack not connected (later: hivey slack connect)")
164
+ return 1
165
+ if not token.startswith(("xoxb-", "xoxp-")):
166
+ print("that is not a Slack token (it starts with xoxb-); try again")
167
+ continue
168
+ try:
169
+ data, scopes = auth_test(token)
170
+ except (RuntimeError, OSError) as err:
171
+ print(f"Slack refused it ({err}); try again")
172
+ continue
173
+ token_file = save_token(token)
174
+ print(f"saved (only you can read it): {token_file}")
175
+ missing = sorted(NEEDED_SCOPES - scopes) if scopes else []
176
+ print(describe({"connected": True, "team": data.get("team"), "user": data.get("user"),
177
+ "missing_scopes": missing}))
178
+ remember_you(token)
179
+ return 0
180
+ print("Slack not connected (later: hivey slack connect)")
181
+ return 1
182
+
183
+
184
+ def main():
185
+ parser = argparse.ArgumentParser(description="connect hivey to Slack")
186
+ parser.add_argument("--status", action="store_true")
187
+ parser.add_argument("--json", action="store_true")
188
+ parser.add_argument("--force", action="store_true")
189
+ args = parser.parse_args()
190
+ if args.status:
191
+ state = current()
192
+ print(json.dumps(state) if args.json else describe(state))
193
+ return 0 if state["connected"] else 1
194
+ return connect(args.force)
195
+
196
+
197
+ if __name__ == "__main__":
198
+ sys.exit(main())