@hivey/cli 0.9.48 → 0.9.51

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.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivey/cli",
3
- "version": "0.9.48",
3
+ "version": "0.9.51",
4
4
  "description": "All your AI swarms, one terminal: a workspace and lead agent for teams of Claude Code and Codex agents",
5
5
  "keywords": [
6
6
  "hivey",
package/repo/install.sh CHANGED
@@ -338,6 +338,16 @@ if [ "$SETUP" = 1 ]; then
338
338
  echo "skipped: not a terminal (later: hivey pet choose)"
339
339
  fi
340
340
 
341
+ say "nightly agent monitoring (optional)"
342
+ if [ "$(uname -s)" != Darwin ]; then
343
+ echo "uses launchd: macOS only, skipped"
344
+ elif [ -t 0 ]; then
345
+ # Asked once (the answer is kept in ~/.hivey/agent-map/offer.json); `hivey update` asks too.
346
+ "$BIN" agent-map schedule offer || echo "not set up (later: hivey agent-map schedule install)"
347
+ else
348
+ echo "skipped: not a terminal (asked at the next hivey update, or: hivey agent-map schedule install)"
349
+ fi
350
+
341
351
  say "the hivey agent (~/.hivey/agent)"
342
352
  if command -v claude >/dev/null; then
343
353
  # Turned on for the default session; it starts with hivey. With Slack: channel #hivey.
@@ -27,7 +27,7 @@ HERE = Path(__file__).resolve().parent
27
27
  APP_MANIFEST = HERE / "slack-app-manifest.json"
28
28
  NEW_APP_URL = "https://api.slack.com/apps?new_app=1"
29
29
  NEEDED_SCOPES = {"channels:history", "channels:join", "channels:manage", "channels:read",
30
- "chat:write"}
30
+ "chat:write", "groups:history", "groups:read", "groups:write"} # groups: private channels
31
31
 
32
32
 
33
33
  def config_dir():
@@ -1,15 +1,19 @@
1
1
  #!/usr/bin/env python3
2
- """Create (or find) a public Slack channel for a hivey swarm or agent; prints its id as JSON.
2
+ """Create (or find) a private Slack channel for a hivey swarm or agent; prints its id as JSON.
3
3
 
4
4
  usage: create_channel.py <name> [--purpose TEXT]
5
5
 
6
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`.
7
+ it); needs groups:write to create the channel private and invite people (only the people invited
8
+ see it, not everyone who joins the workspace), groups:read and channels:read to find an existing
9
+ one, and channels:join to join an existing public one. Run by `hivey slack add`, `hivey swarm launch --slack` and `hivey home setup --slack`.
9
10
  The user is invited, so the channel shows up in their Slack right away: config.json "invite"
10
11
  (Slack member ids; `hivey slack connect` sets it, else it's worked out once from the people in
11
12
  the channels the bot already shares with them).
12
- Output: {"ok": true, "channel_id": "C…", "name": "hivey", "existing": false, "invited": ["U…"]}
13
+ Output: {"ok": true, "channel_id": "C…", "name": "hivey", "existing": false, "private": true,
14
+ "invited": ["U…"]}
15
+ An existing public channel of that name is reused as it is ("private": false, with a note to change
16
+ it to private in Slack: a bot cannot convert it).
13
17
  """
14
18
  import argparse
15
19
  import json
@@ -20,11 +24,16 @@ from pathlib import Path
20
24
  sys.path.insert(0, str(Path(__file__).resolve().parent))
21
25
  import relay # noqa: E402 (same folder)
22
26
 
27
+ CHANNEL_TYPES = "public_channel,private_channel" # private: only the ones the bot is in
28
+ MISSING_WRITE = ("Slack needs the groups:write scope to create private channels: add it to the hivey "
29
+ "app under OAuth & Permissions → Bot Token Scopes, click Reinstall to Workspace, then "
30
+ "run hivey slack connect --force")
31
+
23
32
 
24
33
  def find(slack, name):
25
34
  cursor = ""
26
35
  while True:
27
- data = slack.call("conversations.list", http="GET", types="public_channel",
36
+ data = slack.call("conversations.list", http="GET", types=CHANNEL_TYPES,
28
37
  exclude_archived="true", limit=1000, cursor=cursor)
29
38
  for channel in data.get("channels", []):
30
39
  if channel.get("name") == name:
@@ -42,7 +51,7 @@ def shared_people(slack):
42
51
  """Humans in the channels the bot is in, most shared first (the bot itself excluded)."""
43
52
  bot = slack.call("auth.test").get("user_id")
44
53
  counts = {}
45
- data = slack.call("conversations.list", http="GET", types="public_channel",
54
+ data = slack.call("conversations.list", http="GET", types=CHANNEL_TYPES,
46
55
  exclude_archived="true", limit=1000)
47
56
  for channel in data.get("channels", []):
48
57
  if not channel.get("is_member"):
@@ -85,6 +94,30 @@ def invite(slack, channel_id, people):
85
94
  return invited
86
95
 
87
96
 
97
+ def create(slack, name):
98
+ """(channel, existing) for #name: created private, else the existing one (joined when public).
99
+ Raises RuntimeError with a message for the user."""
100
+ try:
101
+ return slack.call("conversations.create", name=name, is_private=True)["channel"], False
102
+ except RuntimeError as err:
103
+ if "missing_scope" in str(err):
104
+ raise RuntimeError(MISSING_WRITE) from err
105
+ if "name_taken" not in str(err):
106
+ raise
107
+ channel = find(slack, name)
108
+ if channel is None:
109
+ raise RuntimeError("name_taken (an archived channel, or a private one the bot is not in)")
110
+ if not channel.get("is_member"):
111
+ if channel.get("is_private"):
112
+ raise RuntimeError(f"#{name} is private and the bot is not in it: invite @hivey there")
113
+ # The relay reads the channel's history: the bot has to be in it.
114
+ try:
115
+ slack.call("conversations.join", channel=channel["id"])
116
+ except RuntimeError as err:
117
+ raise RuntimeError(f"cannot join #{name}: {err}") from err
118
+ return channel, True
119
+
120
+
88
121
  def main():
89
122
  parser = argparse.ArgumentParser()
90
123
  parser.add_argument("name")
@@ -101,24 +134,12 @@ def main():
101
134
  "in a terminal"}))
102
135
  return 1
103
136
  slack = relay.Slack(token)
104
- existing = False
105
137
  try:
106
- channel = slack.call("conversations.create", name=args.name, is_private=False)["channel"]
138
+ channel, existing = create(slack, args.name)
107
139
  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
140
+ print(json.dumps({"ok": False, "error": str(err)}))
141
+ return 1
142
+ private = bool(channel.get("is_private", not existing))
122
143
  if args.purpose and not existing:
123
144
  try:
124
145
  slack.call("conversations.setPurpose", channel=channel["id"], purpose=args.purpose[:250])
@@ -126,7 +147,7 @@ def main():
126
147
  pass
127
148
  invited = invite(slack, channel["id"], invitees(slack, config))
128
149
  print(json.dumps({"ok": True, "channel_id": channel["id"], "name": args.name,
129
- "existing": existing, "invited": invited}))
150
+ "existing": existing, "private": private, "invited": invited}))
130
151
  return 0
131
152
 
132
153
 
@@ -18,7 +18,9 @@
18
18
  "channels:manage",
19
19
  "channels:read",
20
20
  "chat:write",
21
- "groups:history"
21
+ "groups:history",
22
+ "groups:read",
23
+ "groups:write"
22
24
  ]
23
25
  }
24
26
  },
@@ -57,5 +57,55 @@ class InviteTest(unittest.TestCase):
57
57
  self.assertEqual(slack.invited, ["U2"])
58
58
 
59
59
 
60
+ class CreateSlack:
61
+ """conversations.create answers with `create_error`, else creates; #taken exists."""
62
+
63
+ def __init__(self, create_error=None, taken=None):
64
+ self.create_error, self.taken, self.calls = create_error, taken, []
65
+
66
+ def call(self, method, http="POST", **params):
67
+ self.calls.append((method, params))
68
+ if method == "conversations.create":
69
+ if self.create_error:
70
+ raise RuntimeError(f"slack conversations.create: {self.create_error}")
71
+ return {"channel": {"id": "Cnew", "is_private": params["is_private"]}}
72
+ if method == "conversations.list":
73
+ self.listed_types = params["types"]
74
+ return {"channels": [self.taken] if self.taken else []}
75
+ if method == "conversations.join":
76
+ return {"ok": True}
77
+ raise AssertionError(method)
78
+
79
+
80
+ class CreateTest(unittest.TestCase):
81
+ def test_new_channels_are_private(self):
82
+ slack = CreateSlack()
83
+ channel, existing = create_channel.create(slack, "hivey")
84
+ self.assertEqual(slack.calls[0], ("conversations.create", {"name": "hivey", "is_private": True}))
85
+ self.assertTrue(channel["is_private"])
86
+ self.assertFalse(existing)
87
+
88
+ def test_missing_scope_says_how_to_add_it(self):
89
+ with self.assertRaisesRegex(RuntimeError, "groups:write.*Reinstall"):
90
+ create_channel.create(CreateSlack(create_error="missing_scope"), "hivey")
91
+
92
+ def test_existing_private_channel_is_found_without_joining(self):
93
+ slack = CreateSlack("name_taken", {"id": "Cp", "name": "hivey", "is_private": True, "is_member": True})
94
+ channel, existing = create_channel.create(slack, "hivey")
95
+ self.assertEqual((channel["id"], existing), ("Cp", True))
96
+ self.assertIn("private_channel", slack.listed_types)
97
+ self.assertNotIn("conversations.join", [m for m, _ in slack.calls])
98
+
99
+ def test_existing_public_channel_is_joined(self):
100
+ slack = CreateSlack("name_taken", {"id": "Cq", "name": "hivey", "is_private": False, "is_member": False})
101
+ channel, existing = create_channel.create(slack, "hivey")
102
+ self.assertIn(("conversations.join", {"channel": "Cq"}), slack.calls)
103
+
104
+ def test_private_channel_the_bot_is_not_in_asks_for_an_invite(self):
105
+ slack = CreateSlack("name_taken", {"id": "Cr", "name": "hivey", "is_private": True, "is_member": False})
106
+ with self.assertRaisesRegex(RuntimeError, "invite @hivey"):
107
+ create_channel.create(slack, "hivey")
108
+
109
+
60
110
  if __name__ == "__main__":
61
111
  unittest.main()
@@ -32,6 +32,9 @@ for Codex, Grok and agy** below when the agent isn't on Claude Code.
32
32
  prompt or message, never ask for one in chat, and never read `.env` files.
33
33
  - **Docs:** look up any library, framework, API or CLI with the `hivey-context7` skill first
34
34
  (current docs in seconds), before a web search or your memory.
35
+ - **Spend:** a script you write that calls an LLM API directly (not through Claude Code, Codex
36
+ or Grok CLI) logs each call with `hivey_spend.record(response, agent="<agent name>")` from
37
+ `~/.claude/skills/hivey-agent-map/scripts/hivey_spend.py`, so the agent map counts its cost.
35
38
  - Ask before anything destructive or outward-facing (deleting data, publishing, sending
36
39
  email or posts, spending money). Draft first, then ask.
37
40
  - Commit your work in this folder; never push.
@@ -0,0 +1,181 @@
1
+ ---
2
+ name: hivey-agent-map
3
+ description: "Map everything that runs on this Mac: scheduled jobs (cron, cron-catchup, launchd), hivey agents and swarms, headless claude/codex/grok/agy runs, with tokens and estimated cost per agent, model and provider (Claude Code, DeepSeek/OpenRouter, Codex, Grok, Anthropic API, Gemini), daily cost trends, failing jobs, what is running now, and how the agents feed each other (which job writes the Baserow table or folder another agent reads); drawn as an archify graph plus a one-page stats explainer. Also the spend log: hivey_spend.py records the tokens and cost of LLM API calls that scripts make directly. Use whenever the user asks what runs on their machine, which agents or jobs exist, what is running now, how much each agent or provider costs or how many tokens it used, cost or token trends, why a scheduled job failed, how agents are connected or feed each other, wants an agent map, architecture graph or dependency diagram of their automations, or wants to track or log the spend of their scripts and agents, even if they don't say hivey."
4
+ ---
5
+
6
+ > Local additions: if `EXTRA_SKILL.md` exists in this skill's folder, read it too and follow it.
7
+ > It holds this machine's own additions; hivey updates never touch it, so put local changes
8
+ > there, never here.
9
+
10
+ # hivey agent map
11
+
12
+ One scan collects the facts; you confirm the links and draw them.
13
+
14
+ ```bash
15
+ M=~/.claude/skills/hivey-agent-map/scripts
16
+ python3 -I $M/agent_map.py stats --days 7 # summary in the terminal + snapshot JSON
17
+ python3 -I $M/agent_map.py scan --days 30 # snapshot only: ~/.hivey/agent-map/snapshot.json
18
+ ```
19
+
20
+ It reads, never changes: the crontab, `~/.config/cron-catchup/jobs.tsv` (and `cron-catchup.py list`
21
+ status), `~/Library/LaunchAgents` (non-Apple; `launchctl list` exit codes), each job's log (last
22
+ error line), `hivey agent list` plus stray claude/codex/grok/agy processes, and token use from
23
+ Claude Code transcripts (`~/.claude/projects`, which also hold the DeepSeek/OpenRouter and local Muse
24
+ agents hivey runs through Claude Code), Codex sessions, Grok `usage.json`, the claude-api-guard
25
+ ledger and the hivey spend log. It runs in about 2 s.
26
+
27
+ ## Snapshot fields
28
+
29
+ - `jobs[]`: `name, kind (cron | cron (cron-catchup) | launchd), schedule, command, agent, status,
30
+ last_run, log, log_modified, last_error`. `agent` is the agent folder the job runs in, if any.
31
+ - `live_agents[]`: `agent, cli, status (working/idle/blocked/done/running), where (hivey pane or pid,
32
+ headless), cwd, role`.
33
+ - `usage`: `agents[]` (tokens, `cost_usd`, calls, models, providers; sorted by cost),
34
+ `providers{}`, `models{}`, `kinds{}` (interactive vs headless vs api), `daily_cost_by_provider{}`,
35
+ totals, `sources_without_tokens`.
36
+ - `nodes[]`: every job and agent folder (`~/agents/*`, `~/swarms/*`), with `llm_api`
37
+ (`providers` it calls, the `unlogged` ones, `files`).
38
+ - `links_candidates.belongs_to[]`: jobs that run inside an agent's folder.
39
+ - `links_candidates.shared_stores[]`: a Baserow table (`baserow:table/<id>`) or data folder
40
+ (`dir:~/X/posts`) named by two or more nodes, its `owner` (the node whose folder holds it) and the
41
+ file that names it for each node (`evidence`).
42
+ - `links_confirmed[]`: links already confirmed (`~/.hivey/agent-map/links.json`).
43
+
44
+ Agent names come from folders: `~/agents/<n>` → `n`, `~/swarms/<n>` → `swarm:n`, `~/.hivey/agent` →
45
+ `hivey`, `~/projects/<n>` → `project:n`, `~/.claude/skills/<n>` → `skill:n`. Rename or group with
46
+ `~/.hivey/agent-map/agents.json` (`{"/path/prefix": "name"}`).
47
+
48
+ ## Workflow
49
+
50
+ 1. **Scan.** Run `stats` (default 7 days; Claude Code transcripts are purged after 15 days, so a
51
+ longer window undercounts Claude Code). Tell the user the headline: total estimated cost, top
52
+ agents, failing jobs, what runs now.
53
+ 2. **Confirm the links.** Candidates are heuristic: a shared table or folder only shows that two
54
+ nodes name it. For each `shared_stores` entry, read the evidence files (just enough lines) to
55
+ decide who **writes** and who **reads** it, then save each real edge:
56
+ `python3 -I $M/agent_map.py link <from-id> <to-id> --via "Baserow Tweets table" --evidence "<file:line>"`
57
+ (node ids as in `nodes[]`, e.g. `cron:x-ai-agents-trends` → `agent:x-content`). Drop
58
+ coincidences (a backup swarm, a path in a comment). Also add obvious edges the heuristic cannot
59
+ see when the evidence is clear: a job that runs a skill (`claude -p "/github-trending"`), an
60
+ agent brief that says it reads another agent's output. Ask the user only when the direction is
61
+ really unclear. Confirmed links are reused next time, so later maps are fast.
62
+ 3. **Draw** (archify, below).
63
+ 4. **Offer the spend gaps.** For each node with `llm_api.unlogged`, offer to add one
64
+ `hivey_spend.record(...)` line after its API call (see Spend log). These are the user's own
65
+ scripts: show the change and get a yes per script; never touch them unasked.
66
+
67
+ ## Drawing with archify
68
+
69
+ Needs the `archify` skill (`~/.claude/skills/archify`). Put both artifacts in
70
+ `~/.hivey/agent-map/reports/<YYYY-MM-DD-HHMM>/`, following archify's own SKILL.md (read it first:
71
+ schemas, `finalize`, repair rules).
72
+
73
+ - **The map: a `dataflow` diagram** (`map.json` → `agent-map.html`). The grid is at most 5 stages ×
74
+ rows 0–4, so **25 nodes at most**. A layout that works: stages *Scheduled jobs* → *Raw data* (the
75
+ stores jobs write: transcripts, Baserow tables) → *Pipelines* (jobs that read them) → *Knowledge &
76
+ agents* (vaults/wikis, upstream agents) → *Agents* (the consumers), one row per domain (YouTube/wikis,
77
+ X content, radars, trading, research swarms). Draw only confirmed links, labelled with what flows
78
+ (≤ 17 characters: "top-20 tweets", "transcripts"). Fold the rest: a job that belongs to an agent
79
+ merges into it ("+ nightly 03:15" in its sublabel), many similar jobs become one node ("12 trading
80
+ jobs"), and unlinked housekeeping (git auto-commits, upgrades, purges) goes in a "Not drawn" card.
81
+ **Node tags do not show at default zoom: put cost and status in the sublabel** ("$110 · posts → n8n",
82
+ "launchd 04:30 · exit 1"). Put an agent that shares no data at a free cell where no line crosses it.
83
+ Providers and totals go in cards (spend by provider and model, needs attention, spend gaps, not
84
+ drawn), not as edges: agent → provider edges cross everything.
85
+ - **The stats: an `explainer` page** (`stats.archify.md` → `agent-stats.html`; conclusion first): total
86
+ cost and tokens with the API-equivalent note in scope; cost by agent (`@chart type=bar` over an
87
+ `agents.csv` you write from the snapshot, plus a table with calls, tokens and model); why the top
88
+ spender costs what it does (`@facts`: cache reads, cache writes, output, fresh input, from its
89
+ `usage.agents[]` entry and the prices); daily cost (`@chart type=line` over `daily.csv`); job health
90
+ table (failing jobs and their last error); spend gaps (`@callout`) and a `- [ ]` checklist. Copy
91
+ `snapshot.json` into the folder and cite it as `@source scan … path=snapshot.json`. **Do not embed
92
+ the map** with `@diagram`: a map this dense fails the page's 10px readability check. Instead,
93
+ describe the main links in a list and name `agent-map.html` (it sits in the same folder).
94
+ - Finalize each one: `finalize dataflow map.json agent-map.html --quality showcase --json` and
95
+ `finalize explainer stats.archify.md agent-stats.html --json`. After a run that reached
96
+ browser-check, rerun with a fresh `--out-dir review-<n>`. Recompute every number you quote from the
97
+ snapshot (sums, shares, job counts by kind).
98
+
99
+ Lead your reply with links to both files and two or three findings (biggest spender, a failing job, a
100
+ surprising link). If archify is missing, give the stats as Markdown tables and the map as a Mermaid
101
+ `flowchart LR`, and say archify would render it properly.
102
+
103
+ ## Nightly report, menu and schedule
104
+
105
+ ```bash
106
+ hivey agent-map open # the latest report; builds the first one when none exists
107
+ hivey agent-map nightly [--model haiku] # a full report now (also: --no-llm, --open)
108
+ hivey agent-map schedule install [--at 06:30] [--model haiku] # | remove | status
109
+ ```
110
+
111
+ - **hivey menu → agent map** runs `hivey agent-map open`: it opens `agent-stats.html`,
112
+ `agent-map.html` and `agent-logs.html` from `~/.hivey/agent-map/reports/latest`.
113
+ - **hivey's layer on the archify pages** (`enhance.py`, after finalize; `agent_map.py enhance [folder]`
114
+ re-applies it): a Stats · Map · Logs navbar on every page; map boxes coloured by spend (green: none →
115
+ red: the most, log scale, with a legend); a hover explanation on each column header; and in each box's
116
+ info card what it does, spend, tokens, calls, models and last run. Boxes are tied to snapshot nodes by
117
+ `map-meta.json` (`{"nodes": {"<box id>": {"refs": [...], "description": "…"}}, "stages": {...}}`,
118
+ written by the nightly model), else by label. A job counts only its own spend, not its agent's.
119
+ - **Descriptions** ("what it does"): from a brief's mission, a skill's description or a script's module
120
+ docstring; the nightly model writes the missing or weak ones to `~/.hivey/agent-map/descriptions.json`
121
+ (kept, edit freely), which wins over the extracted ones. They show in the map's info cards and the run log.
122
+ - **Per day:** the stats page charts the top agents' cost per day and lists each day's cost, tokens and
123
+ top agents (`usage.daily_by_agent` in the snapshot).
124
+ - **`agent-logs.html`** (run log, written by code): every scheduled job with ✅ ran ok · ⚠️ errors in
125
+ its log or a missed run (a launchd log older than its schedule allows) · ❌ non-zero exit or not
126
+ loaded · ⏳ running · ❔ no log, its last run, the issue, and on click the error lines and last 40
127
+ log lines; then every agent with 🟢 working · 🔴 blocked · ⚪ idle · ✅ done · ⚫ not running, last
128
+ active, cost, and its newest `logs/` file. Dormant agents fold into one row. When the user asks
129
+ why a job or agent is not working, read its entry in `snapshot.json` (`jobs[].errors`, `tail`,
130
+ `agent_logs`) or open this page, then the full log it names.
131
+ - **`nightly`** (`report.py`): scan → stats page written and finalized by code (no LLM) → last night's
132
+ `map.json` copied in → one `claude -p --model haiku` run (in the report folder, limited tools) that
133
+ confirms new links and updates the map → if the model fails or breaks the map, last night's map is
134
+ rendered unchanged. `reports/latest` moves only when the stats page passed; the 30 newest reports
135
+ are kept. About 2 minutes and $0.03 with Haiku. Log: `nightly.log` and `llm.log` in the report.
136
+ - **`schedule install`** writes the LaunchAgent `com.hivey.agent-map` (launchd, not cron: `claude -p`
137
+ needs the login keychain; a run missed during sleep happens on wake). Its log is
138
+ `~/.hivey/agent-map/nightly.log`. Unattended runs need a long-lived Claude login: the user runs
139
+ `claude setup-token`, stores the token in their secret store (`envsave set CLAUDE_CODE_OAUTH_TOKEN`)
140
+ and points the run at it: `hivey agent-map schedule token --command "envsave get es_…"`. Only the
141
+ command is kept (`config.json`); the token is read each night and passed to `claude -p` as
142
+ `CLAUDE_CODE_OAUTH_TOKEN`, never written to a file. Without it, the normal login is used.
143
+ - **`schedule offer`** asks once, at the first install (`install.sh`) or the first `hivey update` that
144
+ has it, whether to set the schedule up; the answer is kept in `~/.hivey/agent-map/offer.json`, so it
145
+ is never asked again. Without a person at a terminal it asks nothing.
146
+ - When you are the nightly model: follow the prompt you were given, change only `map.json`,
147
+ `agent-map.html` and `links.json` (through `link`), and stop after the map passes.
148
+
149
+ ## Spend log (`hivey_spend.py`)
150
+
151
+ Calls made through Claude Code, Codex and Grok CLI are already counted from their own transcripts, and
152
+ claude-api-guard logs the Anthropic API calls that go through it. Everything else (scripts calling
153
+ OpenAI, OpenRouter/DeepSeek, xAI/Grok, Gemini, Anthropic without the guard, a local server) logs one
154
+ line per call to `~/.hivey/spend/ledger.jsonl` with the core function:
155
+
156
+ ```python
157
+ import os, sys; sys.path.insert(0, os.path.expanduser("~/.claude/skills/hivey-agent-map/scripts"))
158
+ import hivey_spend
159
+ resp = client.chat.completions.create(...) # an SDK object, a dict, or a requests/httpx response
160
+ hivey_spend.record(resp, agent="x-ai-agents-trends")
161
+ ```
162
+
163
+ It reads the usage block of Anthropic Messages, OpenAI Chat Completions and Responses (also
164
+ OpenRouter, xAI, DeepSeek and other compatible APIs, with their reported `cost` when present) and
165
+ Gemini `usageMetadata`, estimates the cost when none is reported, and never raises. Other entry
166
+ points: `hivey_spend.record_usage(agent=, provider=, model=, input=, output=, cache_read=, cache_write=,
167
+ cost_usd=)`, a shell pipe that echoes the response unchanged
168
+ (`curl … | python3 $M/hivey_spend.py --agent my-job`), and
169
+ `python3 -I $M/agent_map.py log --agent N --provider P --model M --in N --out N [--cost USD]`.
170
+ `agent` defaults to `$HIVEY_AGENT`, else the agent of the current folder. For a streamed call, pass
171
+ the final message (or the last chunk carrying usage).
172
+
173
+ ## Costs and limits
174
+
175
+ - Costs are list-price estimates (`hivey_spend.PRICES`; override in `~/.hivey/agent-map/prices.json`
176
+ as `{"model-substring": [in, out, cache_read, cache_write]}` per million tokens). Claude Code on a
177
+ Max plan and Codex on Plus are not billed per token: call their cost "API-equivalent". Grok CLI and
178
+ OpenRouter report real cost, used as is.
179
+ - Antigravity (`agy`) keeps no token data on disk: it shows as running, not as spend.
180
+ - Codex sessions are zstd-compressed; without `zstd` on PATH they are skipped.
181
+ - Read-only: the scan never edits jobs, plists or scripts.