@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.
@@ -0,0 +1,222 @@
1
+ """hivey's layer on top of the archify pages, added after they are finalized:
2
+
3
+ - a navbar (Stats · Map · Logs) on every page, so each page reaches the others;
4
+ - on the map: each job/agent box coloured by its spend in the window (green: none, red: the most),
5
+ with a legend; a hover explanation on each column header; and, in the box's info card, what the
6
+ job or agent does, its tokens, cost, calls, models and last run.
7
+
8
+ Map boxes are tied to the snapshot by `map-meta.json` in the report folder
9
+ ({"nodes": {"<map node id>": {"refs": ["agent:x-content", "cron:x-ai-agents-trends"],
10
+ "description": "…"}}, "stages": {"<stage label>": "…"}}), written by the nightly model; a box
11
+ without refs is matched by its label. Python standard library only.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import html
16
+ import json
17
+ import math
18
+ import re
19
+ from pathlib import Path
20
+
21
+ STAGE_HELP = {
22
+ "scheduled jobs": "Jobs that start on their own at set times (cron or launchd), without anyone asking.",
23
+ "raw data": "What the jobs write: transcripts, Baserow tables, files. Other jobs and agents read them.",
24
+ "pipelines": "Jobs that read the raw data and turn it into something: wiki pages, reports, summaries.",
25
+ "knowledge & agents": "Wikis and vaults the pipelines keep up to date, and the agents that feed others.",
26
+ "knowledge": "Wikis and vaults the pipelines keep up to date.",
27
+ "agents": "hivey agents you talk to: they read the knowledge and data on the left and do the work.",
28
+ "outputs": "What leaves the system: posts, messages, published files.",
29
+ }
30
+
31
+ NAV_CSS = """
32
+ .hv-nav{position:relative;z-index:50;display:flex;gap:4px;align-items:center;justify-content:center;
33
+ padding:6px 10px;font:600 13px/1.2 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;
34
+ border-bottom:1px solid rgba(127,127,127,.25);background:rgba(127,127,127,.06)}
35
+ .hv-nav a{color:inherit;opacity:.65;text-decoration:none;padding:4px 12px;border-radius:999px}
36
+ .hv-nav a:hover{opacity:1;background:rgba(127,127,127,.14)}
37
+ .hv-nav a.on{opacity:1;background:rgba(47,111,236,.16);color:#2f6fec}
38
+ .hv-nav .hv-when{margin-left:12px;opacity:.5;font-weight:400;font-size:12px}
39
+ """
40
+
41
+ MAP_CSS = """
42
+ .hv-legend{position:fixed;left:14px;bottom:14px;z-index:40;padding:8px 10px;border-radius:10px;
43
+ font:12px/1.3 -apple-system,BlinkMacSystemFont,sans-serif;background:rgba(255,255,255,.92);color:#1d2330;
44
+ border:1px solid rgba(127,127,127,.3);box-shadow:0 2px 10px rgba(0,0,0,.08)}
45
+ html[data-theme="dark"] .hv-legend{background:rgba(22,27,34,.92);color:#e6edf3}
46
+ @media (prefers-color-scheme:dark){html:not([data-theme="light"]) .hv-legend{background:rgba(22,27,34,.92);color:#e6edf3}}
47
+ .hv-legend .bar{width:180px;height:9px;border-radius:5px;margin:5px 0 3px;
48
+ background:linear-gradient(90deg,hsl(120,65%,45%),hsl(60,75%,48%),hsl(0,70%,50%))}
49
+ .hv-legend .ends{display:flex;justify-content:space-between;opacity:.75}
50
+ .hv-info{margin-top:.7rem;padding-top:.6rem;border-top:1px solid rgba(127,127,127,.25);font-size:.78rem;line-height:1.45}
51
+ .hv-info .hv-desc{margin:0 0 .5rem;font-size:.85rem}
52
+ .hv-info dl{display:grid;grid-template-columns:auto 1fr;gap:.18rem .7rem;margin:0}
53
+ .hv-info dt{opacity:.6}.hv-info dd{margin:0;font-variant-numeric:tabular-nums}
54
+ .hv-info .hv-models{display:flex;flex-wrap:wrap;gap:.25rem}
55
+ .hv-info .hv-models span{padding:.05rem .4rem;border:1px solid rgba(127,127,127,.35);border-radius:999px;font-size:.7rem}
56
+ svg text.hv-stage{cursor:help;text-decoration:underline dotted;text-underline-offset:2px}
57
+ """
58
+
59
+
60
+ def nav(active: str, generated: str) -> str:
61
+ links = [("agent-stats.html", "Stats"), ("agent-map.html", "Map"), ("agent-logs.html", "Logs")]
62
+ items = "".join(f'<a href="{href}"{" class=on" if href == active else ""}>{label}</a>' for href, label in links)
63
+ return f'<nav class="hv-nav">{items}<span class="hv-when">scan {html.escape(generated[:16].replace("T", " "))}</span></nav>'
64
+
65
+
66
+ def inject(page: str, css: str, top: str, script: str = "") -> str:
67
+ """Adds hivey's pieces, each wrapped in <!--hv--> markers so a rerun replaces them."""
68
+ page = re.sub(r"<!--hv-->.*?<!--/hv-->", "", page, flags=re.S)
69
+ page = page.replace("</head>", f"<!--hv--><style>{css}</style><!--/hv--></head>", 1)
70
+ m = re.search(r"<body[^>]*>", page)
71
+ if m:
72
+ page = page[: m.end()] + f"<!--hv-->{top}<!--/hv-->" + page[m.end():]
73
+ if script:
74
+ block = f"<!--hv--><script>{script}</script><!--/hv-->"
75
+ page = page.replace("</body>", block + "</body>", 1) if "</body>" in page else page + block
76
+ return page
77
+
78
+
79
+ def money(v: float) -> str:
80
+ return f"${v:,.2f}"
81
+
82
+
83
+ def mtok(n: int) -> str:
84
+ return f"{n / 1e6:,.1f}M" if n >= 1e6 else f"{n / 1e3:,.0f}k" if n >= 1e3 else str(n)
85
+
86
+
87
+ def model_name(m: str) -> str:
88
+ m = m.rsplit("/", 1)[-1]
89
+ k = re.match(r"claude-(opus|sonnet|haiku)-(\d+)(?:-(\d{1,2}))?(?!\d)", m)
90
+ return (f"{k.group(1).title()} {k.group(2)}" + (f".{k.group(3)}" if k.group(3) else "")) if k else m
91
+
92
+
93
+ def node_data(snap: dict, spec: dict, meta: dict, job_state) -> dict:
94
+ usage = {a["agent"]: a for a in snap["usage"]["agents"]}
95
+ try: # what the nightly model (or you) wrote since the scan wins
96
+ overrides = json.loads((Path.home() / ".hivey/agent-map/descriptions.json").read_text())
97
+ except (OSError, ValueError):
98
+ overrides = {}
99
+ jobs = {j["id"]: j for j in snap["jobs"]}
100
+ jobs_by_name = {j["name"]: j for j in snap["jobs"]}
101
+ snodes = {n["id"]: n for n in snap["nodes"]}
102
+ snodes_by_label = {n["label"]: n for n in snap["nodes"]}
103
+ live = {}
104
+ for a in snap["live_agents"]:
105
+ live.setdefault(a["agent"], a)
106
+ out = {}
107
+ for n in spec.get("nodes", []):
108
+ m = (meta.get("nodes") or {}).get(n["id"], {})
109
+ refs = list(m.get("refs") or [])
110
+ if not refs:
111
+ label = n["label"]
112
+ for cand in (label, re.sub(r"\s+(vault|wiki|jobs?|agent)$", "", label)):
113
+ if cand in snodes_by_label:
114
+ refs.append(snodes_by_label[cand]["id"])
115
+ break
116
+ if cand in jobs_by_name:
117
+ refs.append(jobs_by_name[cand]["id"])
118
+ break
119
+ names, desc, states = [], m.get("description", ""), []
120
+ for ref in refs:
121
+ if overrides.get(ref) and not desc:
122
+ desc = overrides[ref]
123
+ j = jobs.get(ref)
124
+ if j:
125
+ # its own spend only: a job inside an agent's folder must not take the agent's cost
126
+ agent = j.get("agent") or ""
127
+ names += [j["name"]] + ([agent, agent.removeprefix("skill:")] if agent.startswith("skill:") else [])
128
+ desc = desc or j.get("description", "")
129
+ emo, words = job_state(j)
130
+ states.append(f"{emo} {words} · {(j.get('last_run') or j.get('log_modified') or '?').replace('T', ' ')}")
131
+ sn = snodes.get(ref)
132
+ if sn:
133
+ names.append(sn["label"])
134
+ desc = desc or sn.get("description", "")
135
+ if sn["type"] == "agent" and sn["label"] in live:
136
+ states.append(f"{live[sn['label']]['status']} in hivey")
137
+ seen, tot, models = set(), {"cost": 0.0, "tokens": 0, "out": 0, "calls": 0}, []
138
+ for name in names:
139
+ if name and name in usage and name not in seen:
140
+ seen.add(name)
141
+ a = usage[name]
142
+ tot["cost"] += a["cost_usd"]
143
+ tot["tokens"] += a["input"] + a["output"] + a["cache_read"] + a["cache_write"]
144
+ tot["out"] += a["output"]
145
+ tot["calls"] += a["calls"]
146
+ models += [model_name(x) for x in a["models"] if model_name(x) not in models]
147
+ out[n["id"]] = {"refs": refs, "desc": desc, "cost": round(tot["cost"], 2), "tokens": tot["tokens"],
148
+ "out": tot["out"], "calls": tot["calls"], "models": models[:4], "states": states[:3],
149
+ "subject": bool(refs) and n.get("type") != "database"}
150
+ spend = [d["cost"] for d in out.values() if d["subject"]]
151
+ top = max(spend, default=0.0)
152
+ for d in out.values():
153
+ if d["subject"]:
154
+ t = math.log1p(d["cost"]) / math.log1p(top) if top > 0 else 0.0
155
+ d["hue"] = round(120 * (1 - t))
156
+ return out, top
157
+
158
+
159
+ MAP_JS = r"""
160
+ (function(){
161
+ const D=__DATA__, STAGES=__STAGES__, DAYS=__DAYS__;
162
+ const fmt=v=>'$'+v.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
163
+ const tok=n=>n>=1e6?(n/1e6).toFixed(1)+'M':n>=1e3?Math.round(n/1e3)+'k':String(n);
164
+ const esc=s=>String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
165
+ document.querySelectorAll('g[data-node-id]').forEach(g=>{
166
+ const d=D[g.dataset.nodeId]; if(!d) return;
167
+ if(d.hue!=null){g.querySelectorAll(':scope > rect:not(.c-mask)').forEach(r=>{
168
+ r.style.fill='hsla('+d.hue+',75%,50%,.18)'; r.style.stroke='hsl('+d.hue+',68%,42%)';});}
169
+ const t=g.querySelector(':scope > title');
170
+ if(t){t.textContent=[g.dataset.nodeLabel, d.desc, d.subject?(fmt(d.cost)+' in '+DAYS+' days · '+tok(d.tokens)+' tokens'+(d.models.length?' · '+d.models.join(', '):'')):''].filter(Boolean).join('\n');}
171
+ });
172
+ document.querySelectorAll('svg text').forEach(t=>{
173
+ const m=/^\s*\d+\s*\/\s*(.+?)\s*$/.exec(t.textContent||''); if(!m) return;
174
+ const help=STAGES[m[1].toLowerCase()]; if(!help) return;
175
+ t.classList.add('hv-stage');
176
+ const ti=document.createElementNS('http://www.w3.org/2000/svg','title'); ti.textContent=m[1]+': '+help; t.appendChild(ti);
177
+ t.style.pointerEvents='auto';
178
+ });
179
+ let current=null;
180
+ const pick=e=>{const g=e.target.closest&&e.target.closest('g[data-node-id]'); if(g) current=g.dataset.nodeId;};
181
+ document.addEventListener('pointerdown',pick,true); document.addEventListener('focusin',pick,true);
182
+ function fill(meta){
183
+ const box=meta.parentElement; if(!box||box.querySelector('.hv-info')) return;
184
+ const d=D[current]; if(!d) return;
185
+ const rows=[];
186
+ if(d.subject){
187
+ rows.push(['Spend', fmt(d.cost)+' in '+DAYS+' days (API-equivalent)']);
188
+ rows.push(['Tokens', tok(d.tokens)+' ('+tok(d.out)+' output) · '+d.calls.toLocaleString()+' calls']);
189
+ rows.push(['Models', d.models.length?'<span class="hv-models">'+d.models.map(m=>'<span>'+esc(m)+'</span>').join('')+'</span>':'no LLM calls recorded']);
190
+ }
191
+ d.states.forEach(s=>rows.push(['Last run', esc(s)]));
192
+ const div=document.createElement('div'); div.className='hv-info';
193
+ div.innerHTML=(d.desc?'<p class="hv-desc">'+esc(d.desc)+'</p>':'')+(rows.length?'<dl>'+rows.map(r=>'<dt>'+r[0]+'</dt><dd>'+r[1]+'</dd>').join('')+'</dl>':'');
194
+ meta.insertAdjacentElement('afterend',div);
195
+ }
196
+ new MutationObserver(()=>document.querySelectorAll('.semantic-passport-meta').forEach(fill))
197
+ .observe(document.body,{childList:true,subtree:true});
198
+ })();
199
+ """
200
+
201
+
202
+ def enhance_folder(folder: Path, snap: dict, job_state) -> None:
203
+ generated = snap.get("generated", "")
204
+ stats = folder / "agent-stats.html"
205
+ if stats.is_file():
206
+ stats.write_text(inject(stats.read_text(), NAV_CSS, nav("agent-stats.html", generated)))
207
+ page, spec_path = folder / "agent-map.html", folder / "map.json"
208
+ if page.is_file() and spec_path.is_file():
209
+ spec = json.loads(spec_path.read_text())
210
+ try:
211
+ meta = json.loads((folder / "map-meta.json").read_text())
212
+ except (OSError, ValueError):
213
+ meta = {}
214
+ data, top = node_data(snap, spec, meta, job_state)
215
+ stages = dict(STAGE_HELP)
216
+ stages.update({k.lower(): v for k, v in (meta.get("stages") or {}).items()})
217
+ script = (MAP_JS.replace("__DATA__", json.dumps(data)).replace("__STAGES__", json.dumps(stages))
218
+ .replace("__DAYS__", json.dumps(snap.get("window_days", 7))))
219
+ legend = (f'<div class="hv-legend"><b>Spend, last {snap.get("window_days", 7)} days</b><div class="bar"></div>'
220
+ f'<div class="ends"><span>$0</span><span>{money(top)}</span></div>'
221
+ f'<div style="opacity:.65;margin-top:3px">click a box for what it does, tokens and models</div></div>')
222
+ page.write_text(inject(page.read_text(), NAV_CSS + MAP_CSS, nav("agent-map.html", generated) + legend, script))
@@ -0,0 +1,245 @@
1
+ #!/usr/bin/env python3
2
+ """hivey spend log: record the tokens and cost of every LLM API call a script makes.
3
+
4
+ One line per call in ~/.hivey/spend/ledger.jsonl, read by agent_map.py (the hivey agent map).
5
+ Calls made through Claude Code, Codex or Grok CLI are already counted from their own transcripts:
6
+ use this only for scripts that call an API directly (Anthropic SDK, OpenAI, OpenRouter, xAI,
7
+ DeepSeek, Gemini, a local server...).
8
+
9
+ From Python (standard library only; it never raises, so logging cannot break the caller):
10
+
11
+ import sys, os; sys.path.insert(0, os.path.expanduser("~/.claude/skills/hivey-agent-map/scripts"))
12
+ import hivey_spend
13
+ resp = client.messages.create(...) # or requests/httpx JSON, or a dict
14
+ hivey_spend.record(resp, agent="x-ai-agents-trends")
15
+
16
+ hivey_spend.record_usage(agent="n", provider="xai", model="grok-4.7", input=1200, output=300)
17
+
18
+ From a shell script, pipe the raw JSON response through it (it is printed back unchanged):
19
+
20
+ curl -s https://openrouter.ai/api/v1/chat/completions ... \
21
+ | python3 ~/.claude/skills/hivey-agent-map/scripts/hivey_spend.py --agent my-job
22
+
23
+ The agent name defaults to $HIVEY_AGENT, else the agent of the current folder (~/agents/<name>).
24
+ Understands: Anthropic Messages, OpenAI Chat Completions and Responses (also OpenRouter, xAI,
25
+ DeepSeek and other OpenAI-compatible APIs, with their reported `cost` when present), Gemini
26
+ `usageMetadata`. A streamed call: pass the final message / the last chunk that carries usage.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import datetime as dt
31
+ import json
32
+ import os
33
+ import sys
34
+ from pathlib import Path
35
+
36
+ HOME = Path.home()
37
+ STATE = HOME / ".hivey" / "agent-map"
38
+ SPEND_LOG = Path(os.environ.get("HIVEY_SPEND_LOG", HOME / ".hivey" / "spend" / "ledger.jsonl"))
39
+ ALIASES = STATE / "agents.json" # {"/path/prefix": "agent-name"} overrides
40
+
41
+ # USD per million tokens: (input, output, cache read, cache write). Substring match, longest wins.
42
+ # Override or extend in ~/.hivey/agent-map/prices.json: {"model-substring": [in, out, read, write]}.
43
+ PRICES = {
44
+ "claude-opus": (4.00, 20.00, 0.20, 5.00),
45
+ "claude-sonnet": (2.00, 10.00, 0.20, 2.50),
46
+ "claude-haiku": (0.10, 0.50, 0.01, 0.125),
47
+ "deepseek": (0.30, 1.20, 0.03, 0.30),
48
+ "gpt-": (1.25, 10.00, 0.125, 1.25),
49
+ "codex": (1.25, 10.00, 0.125, 1.25),
50
+ "grok": (3.00, 15.00, 0.75, 3.00),
51
+ "gemini": (1.25, 10.00, 0.31, 1.25),
52
+ "muse": (0.0, 0.0, 0.0, 0.0), # local MLX
53
+ "/users/": (0.0, 0.0, 0.0, 0.0), # local model served from a folder
54
+ }
55
+
56
+
57
+ def prices() -> dict:
58
+ p = dict(PRICES)
59
+ try:
60
+ for k, v in json.loads((STATE / "prices.json").read_text()).items():
61
+ p[k.lower()] = tuple(v)
62
+ except (OSError, ValueError):
63
+ pass
64
+ return p
65
+
66
+
67
+ def price_for(model: str, table: dict | None = None) -> tuple:
68
+ table = table or prices()
69
+ m = (model or "").lower()
70
+ best = max((k for k in table if k in m), key=len, default="")
71
+ return table.get(best, (0.0, 0.0, 0.0, 0.0))
72
+
73
+
74
+ def cost(model: str, inp: int, out: int, read: int = 0, write: int = 0, table: dict | None = None) -> float:
75
+ pi, po, pr, pw = price_for(model, table)
76
+ return (inp * pi + out * po + read * pr + write * pw) / 1e6
77
+
78
+
79
+ def agent_of(path: str | None) -> str:
80
+ """Name the agent a working folder belongs to (~/agents/<name>, ~/swarms/<name>, ...)."""
81
+ if not path:
82
+ return "unknown"
83
+ p = os.path.realpath(os.path.expanduser(path))
84
+ try:
85
+ aliases = json.loads(ALIASES.read_text())
86
+ except (OSError, ValueError):
87
+ aliases = {}
88
+ for prefix, name in sorted(aliases.items(), key=lambda kv: -len(kv[0])):
89
+ if p.startswith(os.path.realpath(os.path.expanduser(prefix))):
90
+ return name
91
+ rel = os.path.relpath(p, HOME)
92
+ parts = rel.split(os.sep)
93
+ if rel.startswith(".."):
94
+ return "tmp" if p.startswith(("/tmp", "/private/tmp", "/var/folders")) else p
95
+ if rel == ".":
96
+ return "home (headless)"
97
+ if parts[0] in ("agents", "swarms") and len(parts) > 1:
98
+ return parts[1] if parts[0] == "agents" else f"swarm:{parts[1]}"
99
+ if parts[:2] == [".hivey", "agent-map"]:
100
+ return "hivey-agent-map"
101
+ if parts[:2] == [".hivey", "agent"]:
102
+ return "hivey"
103
+ if parts[:2] == [".claude", "skills"] and len(parts) > 2:
104
+ return f"skill:{parts[2]}"
105
+ if parts[0] == "projects" and len(parts) > 1:
106
+ return f"project:{parts[1]}"
107
+ return "~/" + parts[0]
108
+
109
+
110
+ def _as_dict(obj):
111
+ if obj is None or isinstance(obj, dict):
112
+ return obj or {}
113
+ for attr in ("model_dump", "to_dict", "dict"): # pydantic / SDK objects
114
+ f = getattr(obj, attr, None)
115
+ if callable(f):
116
+ try:
117
+ return f()
118
+ except Exception:
119
+ pass
120
+ if hasattr(obj, "json") and callable(obj.json): # requests / httpx response
121
+ try:
122
+ return obj.json()
123
+ except Exception:
124
+ pass
125
+ return getattr(obj, "__dict__", {}) or {}
126
+
127
+
128
+ def _n(d: dict, *keys) -> int:
129
+ for k in keys:
130
+ v = d.get(k)
131
+ if isinstance(v, (int, float)):
132
+ return int(v)
133
+ return 0
134
+
135
+
136
+ def parse(response) -> dict | None:
137
+ """Tokens, model and reported cost from any supported response shape; None if no usage."""
138
+ d = _as_dict(response)
139
+ model = d.get("model") or d.get("modelVersion") or ""
140
+ meta = d.get("usageMetadata")
141
+ if isinstance(meta, dict): # Gemini
142
+ read = _n(meta, "cachedContentTokenCount")
143
+ return {"model": model, "provider": "google", "input": _n(meta, "promptTokenCount") - read,
144
+ "output": _n(meta, "candidatesTokenCount") + _n(meta, "thoughtsTokenCount"),
145
+ "cache_read": read, "cache_write": 0, "cost_usd": None}
146
+ u = _as_dict(d.get("usage"))
147
+ if not u:
148
+ return None
149
+ reported = u.get("cost")
150
+ if reported is None and isinstance(u.get("cost_in_usd_ticks"), (int, float)): # xAI
151
+ reported = u["cost_in_usd_ticks"] / 1e10
152
+ if "prompt_tokens" in u: # OpenAI Chat Completions and compatible APIs
153
+ details = _as_dict(u.get("prompt_tokens_details"))
154
+ read = _n(details, "cached_tokens") or _n(u, "prompt_cache_hit_tokens")
155
+ return {"model": model, "provider": None, "input": _n(u, "prompt_tokens") - read,
156
+ "output": _n(u, "completion_tokens"), "cache_read": read, "cache_write": 0, "cost_usd": reported}
157
+ if "cache_creation_input_tokens" in u or "cache_read_input_tokens" in u or str(model).startswith("claude"):
158
+ return {"model": model, "provider": "anthropic", "input": _n(u, "input_tokens"),
159
+ "output": _n(u, "output_tokens"), "cache_read": _n(u, "cache_read_input_tokens"),
160
+ "cache_write": _n(u, "cache_creation_input_tokens"), "cost_usd": reported}
161
+ if "input_tokens" in u: # OpenAI Responses
162
+ read = _n(_as_dict(u.get("input_tokens_details")), "cached_tokens")
163
+ return {"model": model, "provider": None, "input": _n(u, "input_tokens") - read,
164
+ "output": _n(u, "output_tokens"), "cache_read": read, "cache_write": 0, "cost_usd": reported}
165
+ return None
166
+
167
+
168
+ def guess_provider(model: str) -> str:
169
+ m = (model or "").lower()
170
+ for key, prov in (("claude", "anthropic"), ("deepseek", "deepseek"), ("grok", "xai"), ("gemini", "google"),
171
+ ("gpt", "openai"), ("o3", "openai"), ("o4", "openai"), ("muse", "local")):
172
+ if key in m:
173
+ return "openrouter" if "/" in m and not m.startswith("/") else prov
174
+ return "local" if m.startswith("/") else "?"
175
+
176
+
177
+ def record_usage(agent: str | None = None, provider: str | None = None, model: str = "", input: int = 0,
178
+ output: int = 0, cache_read: int = 0, cache_write: int = 0, cost_usd: float | None = None,
179
+ kind: str = "api", note: str | None = None) -> dict | None:
180
+ try:
181
+ entry = {
182
+ "at": dt.datetime.now(dt.timezone.utc).isoformat(),
183
+ "agent": agent or os.environ.get("HIVEY_AGENT") or agent_of(os.getcwd()),
184
+ "provider": provider or guess_provider(model), "model": model or "?", "kind": kind,
185
+ "input_tokens": int(input), "output_tokens": int(output),
186
+ "cache_read_tokens": int(cache_read), "cache_write_tokens": int(cache_write),
187
+ "cost_usd": round(cost_usd if cost_usd is not None else cost(model, input, output, cache_read, cache_write), 6),
188
+ "cost_source": "reported" if cost_usd is not None else "estimated",
189
+ }
190
+ if note:
191
+ entry["note"] = note
192
+ SPEND_LOG.parent.mkdir(parents=True, exist_ok=True)
193
+ with open(SPEND_LOG, "a") as fh:
194
+ fh.write(json.dumps(entry) + "\n")
195
+ return entry
196
+ except Exception as e: # never break the caller
197
+ print(f"hivey_spend: not logged: {e}", file=sys.stderr)
198
+ return None
199
+
200
+
201
+ def record(response, agent: str | None = None, provider: str | None = None, model: str | None = None,
202
+ kind: str = "api", note: str | None = None) -> dict | None:
203
+ """Log one API response. Returns the ledger entry, or None when it carried no usage."""
204
+ try:
205
+ u = parse(response)
206
+ except Exception:
207
+ u = None
208
+ if not u:
209
+ return None
210
+ m = model or u["model"]
211
+ return record_usage(agent, provider or u["provider"], m, u["input"], u["output"], u["cache_read"],
212
+ u["cache_write"], u["cost_usd"], kind, note)
213
+
214
+
215
+ def main() -> int:
216
+ import argparse
217
+ ap = argparse.ArgumentParser(description="Log the usage of a JSON API response read from stdin "
218
+ "(echoed back unchanged to stdout).")
219
+ ap.add_argument("--agent")
220
+ ap.add_argument("--provider")
221
+ ap.add_argument("--model")
222
+ ap.add_argument("--kind", default="api")
223
+ ap.add_argument("--note")
224
+ a = ap.parse_args()
225
+ raw = sys.stdin.read()
226
+ sys.stdout.write(raw)
227
+ try:
228
+ data = json.loads(raw)
229
+ except ValueError:
230
+ # a stream: the last data line carrying usage
231
+ data = None
232
+ for line in raw.splitlines():
233
+ line = line.removeprefix("data:").strip()
234
+ if '"usage' in line:
235
+ try:
236
+ data = json.loads(line)
237
+ except ValueError:
238
+ pass
239
+ if data is None or not record(data, a.agent, a.provider, a.model, a.kind, a.note):
240
+ print("hivey_spend: no usage found in the response", file=sys.stderr)
241
+ return 0
242
+
243
+
244
+ if __name__ == "__main__":
245
+ sys.exit(main())