@hivey/cli 0.9.47 → 0.9.50

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,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())