queen-hive 0.2.0__py3-none-any.whl

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 (55) hide show
  1. hive/.claude-plugin/marketplace.json +11 -0
  2. hive/__init__.py +13 -0
  3. hive/claude.py +51 -0
  4. hive/cli.py +512 -0
  5. hive/codex.py +409 -0
  6. hive/compare.py +147 -0
  7. hive/core/.claude-plugin/plugin.json +9 -0
  8. hive/core/agents/builder.md +24 -0
  9. hive/core/agents/reviewer.md +22 -0
  10. hive/core/agents/scout.md +18 -0
  11. hive/core/commands/hive.md +18 -0
  12. hive/core/commands/retro.md +4 -0
  13. hive/core/hooks/hooks.json +66 -0
  14. hive/core/rules/queen.md +123 -0
  15. hive/core/scripts/changes.py +50 -0
  16. hive/core/scripts/check.py +38 -0
  17. hive/core/scripts/events.py +188 -0
  18. hive/core/scripts/hivecore.py +199 -0
  19. hive/core/scripts/hivepath.py +16 -0
  20. hive/core/scripts/lastrun.py +60 -0
  21. hive/core/scripts/protect.py +177 -0
  22. hive/core/skills/init/SKILL.md +16 -0
  23. hive/core/skills/review/SKILL.md +22 -0
  24. hive/core/skills/waggle/SKILL.md +23 -0
  25. hive/dashboard/__init__.py +1 -0
  26. hive/dashboard/process.py +97 -0
  27. hive/dashboard/server.py +286 -0
  28. hive/dashboard/static/app.js +324 -0
  29. hive/dashboard/static/index.html +24 -0
  30. hive/dashboard/static/style.css +123 -0
  31. hive/folders.py +123 -0
  32. hive/gemini.py +298 -0
  33. hive/init.py +170 -0
  34. hive/job.py +138 -0
  35. hive/launch.py +197 -0
  36. hive/memory.py +49 -0
  37. hive/models.py +348 -0
  38. hive/modes.py +46 -0
  39. hive/portable.py +97 -0
  40. hive/pricing.py +66 -0
  41. hive/providers.py +109 -0
  42. hive/records.py +147 -0
  43. hive/render.py +121 -0
  44. hive/router.py +202 -0
  45. hive/stats.py +202 -0
  46. hive/transcript.py +285 -0
  47. hive/translate.py +102 -0
  48. hive/ui.py +47 -0
  49. hive/verify.py +47 -0
  50. queen_hive-0.2.0.dist-info/METADATA +296 -0
  51. queen_hive-0.2.0.dist-info/RECORD +55 -0
  52. queen_hive-0.2.0.dist-info/WHEEL +5 -0
  53. queen_hive-0.2.0.dist-info/entry_points.txt +2 -0
  54. queen_hive-0.2.0.dist-info/licenses/LICENSE +21 -0
  55. queen_hive-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "hive-local",
3
+ "owner": { "name": "Roman Zadvornov" },
4
+ "plugins": [
5
+ {
6
+ "name": "queen-hive",
7
+ "source": "./core",
8
+ "description": "Queen Hive: a Queen model directs cheap worker bees."
9
+ }
10
+ ]
11
+ }
hive/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """Queen Hive: a Queen model directs cheap worker bees, in Claude Code, Codex or the Gemini CLI."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ __version__ = "0.2.0"
7
+
8
+ CORE_DIR = Path(__file__).parent / "core" # the rules, bees, hooks and skills; a Claude Code plugin
9
+ SCRIPTS_DIR = CORE_DIR / "scripts"
10
+
11
+ # hivecore lives inside the plugin so its hooks can use it without this package.
12
+ if str(SCRIPTS_DIR) not in sys.path:
13
+ sys.path.insert(0, str(SCRIPTS_DIR))
hive/claude.py ADDED
@@ -0,0 +1,51 @@
1
+ """Find and run Claude Code, the one runtime behind every hive session."""
2
+
3
+ import json
4
+ import shutil
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+
9
+ def binary() -> str:
10
+ """Claude Code on PATH, else the copy bundled with the SDK (the optional `bundled` extra)."""
11
+ found = shutil.which("claude")
12
+ if found:
13
+ return found
14
+ try:
15
+ import claude_agent_sdk
16
+ except ImportError:
17
+ claude_agent_sdk = None
18
+ bundled = Path(claude_agent_sdk.__file__).parent / "_bundled" / "claude" if claude_agent_sdk else None
19
+ if bundled and bundled.is_file():
20
+ return str(bundled)
21
+ raise SystemExit("Claude Code not found. Install it (https://code.claude.com), or install the hive with its own "
22
+ "copy: pip install -e \".[bundled]\"")
23
+
24
+
25
+ def print_mode(args: list[str], prompt: str, cwd: Path | None = None, env: dict | None = None,
26
+ timeout: float | None = None) -> dict:
27
+ """Run `claude -p` to the end and return its JSON result; failures come back as is_error results."""
28
+ argv = [binary(), "-p", "--output-format", "json", "--permission-prompts", "none", *args, "--", prompt]
29
+ try:
30
+ done = subprocess.run(argv, cwd=cwd, env=env, capture_output=True, text=True, timeout=timeout,
31
+ stdin=subprocess.DEVNULL)
32
+ except subprocess.TimeoutExpired:
33
+ return {"is_error": True, "subtype": "timeout", "result": f"timed out after {timeout}s"}
34
+ try:
35
+ return json.loads(done.stdout.strip().splitlines()[-1])
36
+ except (ValueError, IndexError):
37
+ error = (done.stderr or done.stdout).strip().splitlines()
38
+ return {"is_error": True, "subtype": "no_result", "result": error[-1] if error else f"exit code {done.returncode}"}
39
+
40
+
41
+ HIVE_PLUGIN_NAMES = ("queen-hive", "haiku-hive") # haiku-hive: its name before 0.2, maybe still installed
42
+
43
+
44
+ def installed_plugins(*names: str) -> list[str]:
45
+ """Enabled installed plugins with one of these names, e.g. ["queen-hive@hive-local"]."""
46
+ try:
47
+ done = subprocess.run([binary(), "plugin", "list", "--json"], capture_output=True, text=True, timeout=30)
48
+ plugins = json.loads(done.stdout)
49
+ except (OSError, ValueError, subprocess.TimeoutExpired):
50
+ return []
51
+ return [p["id"] for p in plugins if isinstance(p, dict) and p.get("enabled") and p.get("id", "").split("@")[0] in names]
hive/cli.py ADDED
@@ -0,0 +1,512 @@
1
+ """The `hive` command."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from hive import CORE_DIR, __version__, memory, models, providers, stats
12
+ from hive.modes import MODES
13
+
14
+ SUBCOMMANDS = ("run", "review", "init", "models", "provider", "stats", "dashboard", "waggle", "retro", "doctor",
15
+ "install-plugin")
16
+
17
+ EPILOG = """In a terminal, the hive opens your provider's CLI (Claude Code, Codex or the Gemini CLI) with the Queen's
18
+ rules and the bees loaded. The first run asks which one; `hive provider` changes it.
19
+ Without a terminal (scripts, CI), or with --headless, it runs the goal on its own and prints progress.
20
+
21
+ examples:
22
+ hive # pick a folder, then work in Claude Code
23
+ hive "Fix the failing tests in ~/projects/api"
24
+ hive "Объясни, как устроен этот проект" --mode auto
25
+ hive "Add a /health endpoint" --headless --done "npm test"
26
+ hive "Add a /health endpoint" --queen fable-5.1 --compare sonnet-5.5,opus-5.5
27
+ hive "Add a /health endpoint" --provider gemini
28
+ hive stats
29
+
30
+ other commands: review, init, models, provider, stats, dashboard, waggle (alias retro), doctor, install-plugin
31
+ run `hive <command> -h` for details."""
32
+
33
+
34
+ def _job_args(parser: argparse.ArgumentParser) -> None:
35
+ parser.add_argument("-d", "--dir", type=Path, action="append", default=[],
36
+ help="folder to grant access to (repeatable). Default: folders named in the goal, else asked in a terminal (Enter = the current folder).")
37
+ parser.add_argument("--provider", choices=list(providers.PROVIDERS),
38
+ help="AI for this run only: claude, gpt or gemini. Default: your saved choice (`hive provider`).")
39
+ parser.add_argument("--queen", help=f"Queen model ({', '.join(m.key for m in models.queens(None))}). "
40
+ "Default: the last one for the provider.")
41
+ parser.add_argument("--workers", default=None, help="worker bee model. Default: the last one, else the provider's "
42
+ f"cheapest ({', '.join(w for _, w in models.DEFAULTS.values())}).")
43
+ parser.add_argument("--mode", choices=list(MODES), help="autonomy mode. Default: the last one.")
44
+ for bee in ("scout", "builder", "reviewer"):
45
+ parser.add_argument(f"--{bee}", metavar="MODEL", help=f"model for the {bee} bees only, e.g. a local model "
46
+ "from `hive models add` (default: the bee model).")
47
+ parser.add_argument("--review", choices=["full", "light", "off"],
48
+ help="independent review level. Default: the Queen's own, full for most, light for Sonnet 5.5.")
49
+ parser.add_argument("--lenses", help="comma-separated review lenses, e.g. goal,correctness,tests,arch,perf,rules,security")
50
+ parser.add_argument("--budget", type=float, default=5.0,
51
+ help="hard spending cap in USD per headless run and per --compare run (default 5; Claude only).")
52
+ parser.add_argument("--no-init", action="store_true", help="don't draft a project profile on first use.")
53
+ parser.add_argument("--no-waggle", action="store_true", help="don't run the retro (waggle) after each finished job.")
54
+ parser.add_argument("--sandbox", action="store_true",
55
+ help="run shell commands in the CLI's sandbox: writes only inside the granted folders and temp "
56
+ "(Claude Code also limits the network). Codex always sandboxes them.")
57
+
58
+
59
+ def _choose(args, goal: str = "", ask_folder: bool = False, save: bool = True):
60
+ """Resolve folders, Queen, workers and mode, asking only for what wasn't given.
61
+
62
+ The provider comes first: --provider, else the provider of --queen, else the saved choice, asked once.
63
+ With ask_folder, the folder is asked when neither -d nor the goal names one. With save, the choices become
64
+ the next run's defaults: interactive runs only, so a script's flags don't change what `hive` offers you."""
65
+ from hive import folders as folders_mod, init, ui
66
+ from hive.models import choose_queen, choose_workers
67
+ from hive.modes import DEFAULT_MODE, choose_mode
68
+
69
+ provider = providers.current(args.provider or (_model(args.queen, "--queen").provider if args.queen else None))
70
+ if provider != "claude":
71
+ providers.binary(provider) # fail early, with how to install it
72
+ named = args.dir or folders_mod.folders_in(goal)
73
+ default = folders_mod.ask_folder(Path.cwd()) if ask_folder and not named else Path.cwd()
74
+ folders = folders_mod.resolve(goal, args.dir, default)
75
+ if not args.no_init:
76
+ asyncio.run(init.run(folders[0], use_ai=provider == "claude")) # the others' Queens draft it with the init skill
77
+ state = memory.load_state()
78
+ last_queen, last_workers = models.remembered(state, provider)
79
+ queen = _of_provider(args.queen, provider, "--queen") or last_queen
80
+ workers = _of_provider(args.workers, provider, "--workers") or last_workers
81
+ mode = args.mode or state.get("last_mode") or DEFAULT_MODE
82
+ if not args.queen and models.is_available(state, queen) is False:
83
+ queen = next((m for m in models.queens(provider) if models.is_available(state, m) is not False), queen)
84
+ asked = not (args.queen and args.workers and args.mode)
85
+ who = providers.PROVIDERS[provider]
86
+ if asked and not ui.confirm(f"Run with {who.name} ({who.product}): 👑 {queen.name} · 🐝 {workers.name} bees · "
87
+ f"🛡 mode {mode}?"):
88
+ queen = queen if args.queen else choose_queen(queen.key, provider)
89
+ workers = workers if args.workers else choose_workers(workers.key, provider)
90
+ mode = args.mode or choose_mode(mode)
91
+ if models.is_available(state, queen) is False:
92
+ print(f"⚠️ {queen.name} was not available last time it was checked (`hive models --check` re-checks).")
93
+ if save:
94
+ models.remember(state, queen, workers)
95
+ state["last_mode"] = mode
96
+ memory.save_state(state)
97
+ return folders, queen, workers, mode
98
+
99
+
100
+ def _model(key: str, flag: str) -> models.Model:
101
+ """A model named on the command line, or a clear error instead of a traceback."""
102
+ try:
103
+ return models.get(key)
104
+ except KeyError:
105
+ raise SystemExit(f"{flag}: unknown model '{key}'. `hive models --all` lists the models.") from None
106
+
107
+
108
+ def _of_provider(key: str | None, provider: str, flag: str) -> models.Model | None:
109
+ """A model given on the command line, which must run in the provider's CLI."""
110
+ if not key:
111
+ return None
112
+ model = _model(key, flag)
113
+ if model.provider != provider and not model.local:
114
+ raise SystemExit(f"{flag} {model.key} is a {providers.PROVIDERS[model.provider].name} model, but this run uses "
115
+ f"{providers.PROVIDERS[provider].name}. Pick one of: "
116
+ f"{', '.join(m.key for m in models.catalog(provider))}, or add --provider {model.provider}.")
117
+ return model
118
+
119
+
120
+ def cmd_run(argv: list[str]) -> None:
121
+ from hive import launch, ui
122
+ from hive.job import Job
123
+
124
+ parser = argparse.ArgumentParser(prog="hive", description="Run the hive: a Queen model and cheap worker bees, "
125
+ "in Claude Code, Codex or the Gemini CLI.",
126
+ epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
127
+ parser.add_argument("goal", nargs="?", default="",
128
+ help="what you want done (optional in a terminal). Folders mentioned here are granted access.")
129
+ _job_args(parser)
130
+ parser.add_argument("--done", action="append", default=[], metavar="CMD",
131
+ help="acceptance command that must pass (repeatable). Default: the Queen's final checks or the profile's test command.")
132
+ parser.add_argument("--compare", nargs="?", const="default", metavar="MODELS",
133
+ help=f"also run the goal with single models alone in copies of the folder "
134
+ f"(default {','.join(models.DEFAULT_COMPARE)}; 'all' = every available Queen model).")
135
+ parser.add_argument("--yes", action="store_true", help="don't ask to confirm --compare costs.")
136
+ parser.add_argument("--headless", action="store_true",
137
+ help="run the goal without the CLI's interface and stop at the end (the default without a terminal).")
138
+ parser.add_argument("--version", action="version", version=f"hive {__version__}")
139
+ args = parser.parse_args(argv)
140
+
141
+ headless = args.headless or not ui.interactive()
142
+ if headless and not args.goal:
143
+ parser.error("a goal is required for a headless run (no terminal, or --headless)")
144
+ if args.compare and not args.goal:
145
+ parser.error("--compare needs a goal")
146
+ folders, queen, workers, mode = _choose(args, args.goal, ask_folder=not headless, save=not headless)
147
+ if args.compare and queen.provider != "claude":
148
+ raise SystemExit("--compare runs Claude models only for now.")
149
+ roles = _roles(args, queen.provider)
150
+ if headless and mode != "auto":
151
+ print(f"🛡 headless: nobody can approve a plan or a risky action, so mode {mode} runs as auto"
152
+ + (" (risky actions are refused)." if mode == "ask" else "."))
153
+ mode = "auto" if mode == "plan" else mode
154
+ compare = _compare_keys(args.compare)
155
+ if compare:
156
+ cap = f"${args.budget:g} each" if args.budget else "no cap"
157
+ print(f"⚖️ comparison: {', '.join(models.get(k).name for k in compare)} will each redo the job alone ({cap}).")
158
+ if not args.yes and not _confirm(" run the comparison?"):
159
+ compare = []
160
+ job = Job(goal=args.goal, folders=folders, queen=queen, workers=workers, mode=mode, review=args.review or queen.review,
161
+ lenses=_split(args.lenses), done=args.done, budget=args.budget, compare=compare,
162
+ waggle=not args.no_waggle and not headless, sandbox=args.sandbox, roles=roles)
163
+ records = launch.run(job, headless=headless)
164
+ if headless and not records:
165
+ sys.exit(1) # no job came out of it: the run failed
166
+ last = records[-1] if records else None
167
+ sys.exit(1 if last and (last["acceptance"]["passed"] is False or last["status"] == "failed") else 0)
168
+
169
+
170
+ def _roles(args, provider: str = "claude") -> dict:
171
+ """Per-bee models from --scout/--builder/--reviewer."""
172
+ return {bee: _of_provider(getattr(args, bee), provider, f"--{bee}")
173
+ for bee in ("scout", "builder", "reviewer") if getattr(args, bee, None)}
174
+
175
+
176
+ def _compare_keys(value: str | None) -> list[str]:
177
+ if not value:
178
+ return []
179
+ state = memory.load_state()
180
+ if value == "default":
181
+ keys = list(models.DEFAULT_COMPARE)
182
+ elif value == "all":
183
+ keys = [m.key for m in models.queens()]
184
+ else:
185
+ keys = [_model(k, "--compare").key for k in _split(value)]
186
+ available = [k for k in keys if models.is_available(state, models.get(k)) is not False]
187
+ skipped = set(keys) - set(available)
188
+ if skipped:
189
+ print(f"⚖️ skipping models without access: {', '.join(sorted(skipped))}")
190
+ return available
191
+
192
+
193
+ def _split(value: str | None) -> list[str]:
194
+ return [v.strip() for v in (value or "").split(",") if v.strip()]
195
+
196
+
197
+ def _confirm(question: str) -> bool:
198
+ from hive import ui
199
+
200
+ return ui.confirm(question)
201
+
202
+
203
+ def cmd_waggle(argv: list[str], prog: str) -> None:
204
+ """A retro of the project's last run, in the provider's CLI."""
205
+ from hive import launch, ui
206
+ from hive.job import Job
207
+
208
+ parser = argparse.ArgumentParser(prog=prog, description="Retro of the project's last run, with proposed rule and memory edits.")
209
+ parser.add_argument("note", nargs="?", default="", help="what to focus the retro on (optional).")
210
+ _job_args(parser)
211
+ args = parser.parse_args(argv)
212
+ folders, queen, workers, mode = _choose(args, ask_folder=True, save=ui.interactive())
213
+ job = Job(goal=_waggle_prompt(args.note, queen.provider), folders=folders, queen=queen, workers=workers, mode=mode,
214
+ review=args.review or queen.review, lenses=_split(args.lenses), budget=args.budget, waggle=False,
215
+ roles=_roles(args, queen.provider))
216
+ launch.run(job)
217
+
218
+
219
+ def cmd_review(argv: list[str]) -> None:
220
+ """An independent review of existing changes, in the provider's CLI."""
221
+ from hive import launch, ui
222
+ from hive.job import Job
223
+
224
+ parser = argparse.ArgumentParser(prog="hive review", description="Independent review of changes by reviewer bees; builds nothing.")
225
+ parser.add_argument("target", nargs="?", default="",
226
+ help="what to review: nothing for uncommitted changes, a branch, a commit range, or a PR number/URL.")
227
+ _job_args(parser)
228
+ args = parser.parse_args(argv)
229
+ folders, queen, workers, mode = _choose(args, ask_folder=True, save=ui.interactive())
230
+ job = Job(goal=_skill_prompt("review", args.target, queen.provider), folders=folders, queen=queen, workers=workers,
231
+ mode=mode, review=args.review or queen.review, lenses=_split(args.lenses), budget=args.budget, waggle=False,
232
+ roles=_roles(args, queen.provider))
233
+ launch.run(job)
234
+
235
+
236
+ def _waggle_prompt(note: str, provider: str = "claude") -> str:
237
+ """The skill reads the last recorded run itself (scripts/lastrun.py)."""
238
+ return _skill_prompt("waggle", f"Review the last recorded hive run in this project. {note}".strip(), provider)
239
+
240
+
241
+ def _skill_prompt(skill: str, arguments: str, provider: str) -> str:
242
+ """A slash command in Claude Code; the other CLIs are asked to use the skill."""
243
+ if provider == "claude":
244
+ return f"/queen-hive:{skill} {arguments}".strip()
245
+ return f"Use the `{skill}` skill" + (f" with: {arguments}" if arguments else ".")
246
+
247
+
248
+ def cmd_init(argv: list[str]) -> None:
249
+ from hive import init
250
+
251
+ parser = argparse.ArgumentParser(prog="hive init", description="Draft or refresh a folder's hive profile.")
252
+ parser.add_argument("folder", nargs="?", type=Path, default=Path.cwd())
253
+ parser.add_argument("--no-ai", action="store_true", help="only detect from manifest files; no scout (Claude only).")
254
+ parser.add_argument("--force", action="store_true", help="redraft even if a profile exists.")
255
+ args = parser.parse_args(argv)
256
+ claude_runs = providers.current(ask=False) == "claude" # the scout is a Claude Code bee
257
+ if not args.no_ai and not claude_runs:
258
+ print(" drafting from manifest files only (the scout runs in Claude Code). Answer n to keep the empty template "
259
+ "instead, and the Queen drafts the profile with the `init` skill in your first session.")
260
+ pdir = asyncio.run(init.run(args.folder, use_ai=not args.no_ai and claude_runs, force=args.force))
261
+ print(f"memory folder: {pdir}")
262
+
263
+
264
+ def cmd_models(argv: list[str]) -> None:
265
+ if argv[:1] in (["add"], ["remove"]):
266
+ return _local_model(argv)
267
+ parser = argparse.ArgumentParser(prog="hive models", description="Model catalog, prices and your access.",
268
+ epilog="local models: hive models add KEY MODEL_ID [--url URL] · hive models remove KEY")
269
+ parser.add_argument("--check", action="store_true", help="probe each model with a tiny request (costs a fraction of a cent).")
270
+ parser.add_argument("--provider", choices=list(providers.PROVIDERS), help="this provider's models (default: your saved one).")
271
+ parser.add_argument("--all", action="store_true", help="every provider's models.")
272
+ args = parser.parse_args(argv)
273
+ provider = providers.current(args.provider, ask=False)
274
+ shown = list(providers.PROVIDERS) if args.all else [provider]
275
+ fresh = {} # this check's results, also those not saved (a sign-in failure keeps the last real result)
276
+ if args.check:
277
+ print("checking access…")
278
+ for key in shown:
279
+ fresh.update(asyncio.run(models.check_access(provider=key)))
280
+ state = memory.load_state()
281
+ for key in shown:
282
+ p = providers.PROVIDERS[key]
283
+ queen = models.remembered(state, key)[0]
284
+ print(f"\n{p.name} ({p.product}) · last Queen: {queen.name} · {models.prices_note(key)}")
285
+ print(f"{'model':22} {'id':24} {'in/out $/M':12} {'role':10} access")
286
+ for m in models.catalog(key):
287
+ entry = fresh.get(m.key) or models.access(state).get(m.key)
288
+ access = "not checked" if entry is None else "✅" if entry["ok"] else f"✗ {entry.get('error', '')[:50]}"
289
+ role = "queen" if m.queen_effort else "local bees" if m.local else "bees"
290
+ print(f"{m.key:22} {m.id:24} {f'{m.input:g}/{m.output:g}':12} {role:10} {access}")
291
+ signed_out = next((e["error"] for k, e in fresh.items() if not e["ok"] and models.SIGN_IN_ERRORS.search(e["error"])
292
+ and models.find(k) and models.find(k).provider == key), None)
293
+ if signed_out: # the table cuts errors short; this one says what to do
294
+ print(f"⚠️ {p.product} couldn't sign in, so these results say nothing about the models: {signed_out}")
295
+ if not args.check:
296
+ print("\nRun `hive models --check` to test access" + ("" if args.all else ", `--all` for every provider") + ".")
297
+
298
+
299
+ def cmd_provider(argv: list[str]) -> None:
300
+ parser = argparse.ArgumentParser(prog="hive provider", description="Show or change which AI runs the hive.")
301
+ parser.add_argument("name", nargs="?", help="claude, gpt or gemini. Without it: show the providers and pick one.")
302
+ args = parser.parse_args(argv)
303
+ from hive import ui
304
+
305
+ if args.name:
306
+ key = providers.get(args.name).key
307
+ providers.save(key)
308
+ elif ui.interactive():
309
+ key = providers.choose()
310
+ else:
311
+ key = providers.saved()
312
+ for p in providers.PROVIDERS.values():
313
+ mark = "❯" if p.key == key else " "
314
+ print(f"{mark} {p.key:7} {p.name:7} {p.product:12} " + ("installed" if providers.installed(p.key) else
315
+ f"not installed: {p.install}"))
316
+ print("" if key else "no provider chosen yet: the next `hive` asks.")
317
+ return
318
+ p = providers.PROVIDERS[key]
319
+ queen, workers = models.remembered(memory.load_state(), key)
320
+ print(f"🤖 the hive now runs on {p.name} ({p.product}): 👑 {queen.name} · 🐝 {workers.name} bees.")
321
+ if not providers.installed(key):
322
+ print(f" {p.product} isn't installed yet: {p.install}, then sign in: {p.login}")
323
+
324
+
325
+ def _local_model(argv: list[str]) -> None:
326
+ parser = argparse.ArgumentParser(prog=f"hive models {argv[0]}", description="Add or remove a local model for bees.")
327
+ parser.add_argument("key", help="short name for --scout/--builder/--reviewer/--workers, e.g. qwen-coder")
328
+ if argv[0] == "add":
329
+ parser.add_argument("model_id", help="the model as the server names it, e.g. qwen2.5-coder:14b")
330
+ parser.add_argument("--url", default=models.OLLAMA_URL, help=f"the local server, with Anthropic and OpenAI APIs such as Ollama's (default {models.OLLAMA_URL})")
331
+ parser.add_argument("--name", help="display name")
332
+ args = parser.parse_args(argv[1:])
333
+ if argv[0] == "remove":
334
+ print(f"removed {args.key}" if models.remove_local(args.key) else f"no local model called {args.key}")
335
+ return
336
+ model = models.add_local(args.key, args.model_id, args.url, args.name)
337
+ print(f"added {model.key}: {model.id} at {model.base_url}. Check it with `hive models --check`, "
338
+ f"then use it with e.g. `--scout {model.key}`.")
339
+
340
+
341
+ def cmd_stats(argv: list[str]) -> None:
342
+ parser = argparse.ArgumentParser(prog="hive stats", description="History of hive runs.")
343
+ parser.add_argument("folder", nargs="?", type=Path, help="only this project (default: all projects).")
344
+ parser.add_argument("--last", action="store_true", help="show the full report of the last run.")
345
+ args = parser.parse_args(argv)
346
+ if args.last:
347
+ runs = stats.load_runs([memory.project_dir(args.folder)] if args.folder else memory.all_projects())
348
+ if runs:
349
+ stats.print_report(runs[-1])
350
+ else:
351
+ print("No hive runs yet.")
352
+ return
353
+ stats.print_history(args.folder.expanduser().resolve() if args.folder else None)
354
+
355
+
356
+ def cmd_dashboard(argv: list[str]) -> None:
357
+ from hive.dashboard import process
358
+
359
+ parser = argparse.ArgumentParser(prog="hive dashboard", description="Local dashboard for hive runs, in a background process.")
360
+ parser.add_argument("action", nargs="?", choices=["up", "down", "status"], default="up",
361
+ help="up starts it (default), down stops it, status shows whether it runs.")
362
+ parser.add_argument("--port", type=int, default=7777)
363
+ parser.add_argument("--no-open", action="store_true", help="don't open the browser.")
364
+ parser.add_argument("--foreground", action="store_true", help="run in this terminal until Ctrl-C instead.")
365
+ args = parser.parse_args(argv)
366
+ if args.action == "down":
367
+ process.down()
368
+ elif args.action == "status":
369
+ process.status()
370
+ elif args.foreground:
371
+ from hive.dashboard.server import serve
372
+
373
+ print(f"🐝 hive dashboard on http://localhost:{args.port} (Ctrl-C to stop)")
374
+ serve(args.port, open_browser=not args.no_open)
375
+ else:
376
+ process.up(args.port, open_browser=not args.no_open)
377
+
378
+
379
+ def cmd_doctor(argv: list[str]) -> None:
380
+ from hive import claude
381
+
382
+ chosen = providers.saved()
383
+ print(f"provider: {providers.PROVIDERS[chosen].name if chosen else 'not chosen yet (the next `hive` asks)'}")
384
+ for key in ("gpt", "gemini"):
385
+ _provider_check(key, key == chosen)
386
+ try:
387
+ binary = claude.binary()
388
+ except SystemExit as missing:
389
+ print(f"{'⚠️ ' if chosen in (None, 'claude') else ''}Claude Code: {missing}")
390
+ print(f"hive {__version__} · python {sys.version.split()[0]} · hive home: {memory.hive_home()}")
391
+ return
392
+ version = subprocess.run([binary, "--version"], capture_output=True, text=True).stdout.strip()
393
+ print(f"hive {__version__} · Claude Code {version or '?'} ({binary}) · python {sys.version.split()[0]}")
394
+ out = subprocess.run([binary, "plugin", "validate", str(CORE_DIR)], capture_output=True, text=True)
395
+ lines = (out.stdout + out.stderr).strip().splitlines()
396
+ print("plugin validate: " + (lines[-1] if lines else "?"))
397
+ print(f"plugin: {CORE_DIR}")
398
+ installed = claude.installed_plugins(*claude.HIVE_PLUGIN_NAMES)
399
+ if installed:
400
+ print(f"installed in Claude Code too: {', '.join(installed)} (switched off inside `hive` sessions)")
401
+ print(f"hive home: {memory.hive_home()}")
402
+ for leftover in ("CLAUDE_CODE_SUBAGENT_MODEL_FORCE", "CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_EFFORT_LEVEL"):
403
+ if os.environ.get(leftover):
404
+ print(f"⚠️ {leftover} is set and overrides per-bee settings")
405
+ print(_transcript_check())
406
+ print(_access_summary())
407
+
408
+
409
+ def _access_summary() -> str:
410
+ """One line per provider from the last `hive models --check`: how many models answered, and which didn't."""
411
+ access = models.access(memory.load_state())
412
+ lines = []
413
+ for key, p in providers.PROVIDERS.items():
414
+ checked = [m for m in models.catalog(key) if m.key in access]
415
+ if checked:
416
+ missing = [m.key for m in checked if not access[m.key]["ok"]]
417
+ lines.append(f" {p.name}: {len(checked) - len(missing)} of {len(checked)} ✅"
418
+ + (f" · no access: {', '.join(missing)}" if missing else ""))
419
+ return ("model access (last `hive models --check`):\n" + "\n".join(lines)) if lines else \
420
+ "model access: not checked (run `hive models --check`)"
421
+
422
+
423
+ def _provider_check(key: str, chosen: bool) -> None:
424
+ p = providers.PROVIDERS[key]
425
+ if not providers.installed(key):
426
+ if chosen:
427
+ print(f"⚠️ {p.product} is not installed: {p.install}")
428
+ return
429
+ binary = providers.binary(key)
430
+ version = subprocess.run([binary, "--version"], capture_output=True, text=True).stdout.strip()
431
+ line = f"{p.product} {version or '?'} ({binary})"
432
+ if key == "gpt":
433
+ from hive import codex
434
+
435
+ line += f" · login (hive's Codex home {codex.home()}): {codex.login_status()}"
436
+ line += ("\n hooks: approved" if codex.hooks_trusted() else
437
+ "\n⚠️ hooks: not approved, so protected paths aren't guarded: " + codex.TRUST_HINT.format(home=codex.home()))
438
+ else:
439
+ from hive import gemini
440
+
441
+ line += f" · hive's Gemini home: {gemini.home()}" + ("" if os.environ.get("GEMINI_API_KEY") else
442
+ " · GEMINI_API_KEY not set")
443
+ print(line)
444
+
445
+
446
+ def _transcript_check() -> str:
447
+ """Read the last run's Claude Code transcript again: the stats depend on its format, which isn't a stable API."""
448
+ from hive import transcript
449
+
450
+ runs = [r for r in stats.load_runs(memory.all_projects())
451
+ if r.get("session_id") and r.get("provider", "claude") == "claude"]
452
+ if not runs:
453
+ return "transcripts: no recorded session yet"
454
+ path = transcript.locate(runs[-1]["session_id"])
455
+ if not path:
456
+ return "transcripts: the last run's transcript is gone (Claude Code may have cleaned it up)"
457
+ traces, exact = transcript.jobs(path)
458
+ tokens = sum(t.input + t.output for trace in traces for t in trace.tracker.usage.values())
459
+ if not traces or not tokens:
460
+ return ("⚠️ transcripts: the last session reads as empty. Claude Code's transcript format may have changed, "
461
+ "so hive statistics will be wrong until hive/transcript.py is updated.")
462
+ return f"transcripts: ok (last session: {len(traces)} job(s), {tokens:,} tokens" + (f", ${exact:.2f})" if exact else ")")
463
+
464
+
465
+ def cmd_install_plugin(argv: list[str]) -> None:
466
+ claude = shutil.which("claude")
467
+ if not claude:
468
+ raise SystemExit("claude CLI not found on PATH.")
469
+ marketplace = CORE_DIR.parent
470
+ for cmd in ([claude, "plugin", "marketplace", "add", str(marketplace)],
471
+ [claude, "plugin", "install", "queen-hive@hive-local"]):
472
+ print("$ " + " ".join(cmd), flush=True)
473
+ subprocess.run(cmd, check=False)
474
+ print("In Claude Code: /queen-hive:hive <goal>, /queen-hive:waggle or /queen-hive:retro")
475
+
476
+
477
+ def main() -> None:
478
+ argv = sys.argv[1:]
479
+ if not argv:
480
+ cmd_run([])
481
+ return
482
+ first, rest = argv[0], argv[1:]
483
+ if first == "--version":
484
+ print(f"hive {__version__}")
485
+ elif first == "run":
486
+ cmd_run(rest)
487
+ elif first == "chat":
488
+ raise SystemExit("`hive chat` was removed: run `hive` (add -d DIR or a goal), which opens Claude Code with the hive loaded.")
489
+ elif first == "review":
490
+ cmd_review(rest)
491
+ elif first in ("waggle", "retro"):
492
+ cmd_waggle(rest, prog=f"hive {first}")
493
+ elif first == "init":
494
+ cmd_init(rest)
495
+ elif first == "models":
496
+ cmd_models(rest)
497
+ elif first == "provider":
498
+ cmd_provider(rest)
499
+ elif first == "stats":
500
+ cmd_stats(rest)
501
+ elif first == "dashboard":
502
+ cmd_dashboard(rest)
503
+ elif first == "doctor":
504
+ cmd_doctor(rest)
505
+ elif first == "install-plugin":
506
+ cmd_install_plugin(rest)
507
+ else:
508
+ cmd_run(argv)
509
+
510
+
511
+ if __name__ == "__main__":
512
+ main()