cost-bubble 0.1.3 → 0.3.0

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.
package/session_cost.py DELETED
@@ -1,402 +0,0 @@
1
- """Resolve a visible desktop route to a local CodeBurn session estimate."""
2
- from collections import deque
3
- from datetime import datetime
4
- import json
5
- import math
6
- import os
7
- from pathlib import Path
8
- import shutil
9
- import sqlite3
10
- import subprocess
11
- import sys
12
- import uuid
13
-
14
- import antigravity_context
15
- import codex_sessions
16
- from local_database import read_database
17
- import usage_activity
18
-
19
- HOME = Path.home()
20
- SUPPORT = HOME / "Library/Application Support"
21
-
22
-
23
- def valid_id(value):
24
- if not isinstance(value, str) or len(value) != 36:
25
- return False
26
- try:
27
- return str(uuid.UUID(value)) == value.lower()
28
- except ValueError:
29
- return False
30
-
31
-
32
- def agy_session(route):
33
- root = HOME / ".gemini/antigravity"
34
- storage = SUPPORT / "Antigravity/app_storage.json"
35
- layouts = json.loads(storage.read_bytes())
36
- layout = json.loads(layouts.get("antigravity-multi-conversation-layout-v3-" + route, "{}"))
37
- pane = layout.get("focusedPaneId")
38
- pending = [layout.get("rootNode")]
39
- target = route
40
- found = False
41
- while pending:
42
- node = pending.pop()
43
- if not isinstance(node, dict):
44
- continue
45
- if node.get("type") == "pane" and node.get("id") == pane:
46
- target = node.get("cascadeId")
47
- found = True
48
- break
49
- for child in node.values():
50
- if isinstance(child, dict):
51
- pending.append(child)
52
- elif isinstance(child, list):
53
- pending.extend(child)
54
- if pane and not found or not valid_id(target):
55
- return None
56
- db = root / "conversation_summaries.db"
57
- with read_database(db) as conn:
58
- row = conn.execute("SELECT title FROM conversation_summaries WHERE conversation_id=?", (target,)).fetchone()
59
- return (target, row[0] or "Antigravity session") if row else None
60
-
61
-
62
- def claude_record(route):
63
- files = list((SUPPORT / "Claude/claude-code-sessions").glob("*/*/local_" + route + ".json"))
64
- if len(files) != 1:
65
- return None
66
- return files[0]
67
-
68
-
69
- def claude_session(route):
70
- record = claude_record(route)
71
- if not record:
72
- return None
73
- data = json.loads(record.read_bytes())
74
- target = data.get("cliSessionId")
75
- if data.get("sessionId") != "local_" + route or not valid_id(target):
76
- return None
77
- return target, data.get("title") or "Claude Code session"
78
-
79
-
80
- def picker_title(session):
81
- db = HOME / ".gemini/antigravity/conversation_summaries.db"
82
- with read_database(db) as conn:
83
- row = conn.execute("""
84
- SELECT title FROM conversation_summaries main WHERE conversation_id = ?
85
- AND title != '' AND NOT EXISTS (
86
- SELECT 1 FROM conversation_summaries other
87
- WHERE other.conversation_id != main.conversation_id AND
88
- (other.title = main.title OR instr(other.title, main.title || ' ') = 1))
89
- """, (session,)).fetchone()
90
- return row[0] if row else None
91
-
92
-
93
- def recent_sessions(provider, route, limit=12, extra_ids=()):
94
- if provider == "codex":
95
- return codex_sessions.chats(codex_sessions.codex_home(), limit=limit, extra_ids=extra_ids)
96
- if provider == "antigravity":
97
- db = HOME / ".gemini/antigravity/conversation_summaries.db"
98
- with read_database(db) as conn:
99
- rows = conn.execute("""
100
- SELECT conversation_id, title, unixepoch(last_modified_time) FROM conversation_summaries
101
- WHERE coalesce(parent_conversation_id, '') = '' AND coalesce(nesting_depth, 0) = 0
102
- AND coalesce(source, '') != 'CORTEX_TRAJECTORY_SOURCE_CLI'
103
- AND coalesce(killed, 0) = 0
104
- ORDER BY julianday(last_modified_time) DESC, conversation_id LIMIT ?
105
- """, (-1 if extra_ids else limit,)).fetchall()
106
- return [{"id": session, "title": title or "Antigravity session", "updated": stamp or 0}
107
- for i, (session, title, stamp) in enumerate(rows) if i < limit or session in extra_ids]
108
- if provider != "claude":
109
- return []
110
- current = claude_record(route)
111
- if not current:
112
- return []
113
- sessions = {}
114
- duplicates = set()
115
- for record in current.parent.glob("local_*.json"):
116
- try:
117
- data = json.loads(record.read_bytes())
118
- session = data.get("cliSessionId")
119
- if (data.get("isArchived") or data.get("sessionId") != record.stem or not valid_id(session)):
120
- continue
121
- updated = data.get("lastActivityAt") or data.get("createdAt") or 0
122
- if session in sessions:
123
- duplicates.add(session)
124
- sessions[session] = (int(updated), data.get("title") or "Claude Code session", record.stem[6:])
125
- except (OSError, ValueError, TypeError, AttributeError):
126
- continue
127
- ordered = sorted(sessions.keys() - duplicates, key=lambda key: (-sessions[key][0], key))
128
- return [{"id": key, "title": sessions[key][1], "updated": sessions[key][0] / 1000,
129
- "route": sessions[key][2]} for i, key in enumerate(ordered) if i < limit or key in extra_ids]
130
-
131
-
132
- def token_sum(usage, first, *cached):
133
- value = usage.get(first)
134
- extras = [usage.get(key, 0) for key in cached]
135
- if type(value) is int and value >= 0 and all(type(n) is int and n >= 0 for n in extras):
136
- return value + sum(extras)
137
- return None
138
-
139
-
140
- def claude_detail(session):
141
- root = Path(os.environ.get("CLAUDE_CONFIG_DIR") or HOME / ".claude") / "projects"
142
- paths = list(root.glob("*/" + session + ".jsonl"))
143
- if len(paths) != 1:
144
- return {}
145
- source = paths[0]
146
- result = {}
147
- # Look at the tail only. A partial line or trailing progress event is common.
148
- with source.open("rb") as stream:
149
- start = max(0, source.stat().st_size - 8 * 1024 * 1024)
150
- stream.seek(start)
151
- if start:
152
- stream.readline()
153
- lines = deque(stream, maxlen=8192)
154
- for line in reversed(lines):
155
- try:
156
- event = json.loads(line)
157
- if event.get("sessionId") != session or event.get("type") != "assistant" or event.get("isSidechain"):
158
- continue
159
- msg = event.get("message") or {}
160
- if msg.get("model") == "<synthetic>":
161
- continue
162
- tokens = token_sum(msg.get("usage") or {}, "input_tokens", "cache_read_input_tokens",
163
- "cache_creation_input_tokens")
164
- if tokens is not None and tokens > 0:
165
- result.update(context=tokens, model=msg.get("model"))
166
- window = (msg.get("usage") or {}).get("context_window_size")
167
- if type(window) is int and window > 0:
168
- result["contextWindow"] = window
169
- break
170
- except (ValueError, TypeError, AttributeError):
171
- continue
172
- return result
173
-
174
-
175
- def agy_detail(session, cascades=None):
176
- result = {}
177
- calls = agy_calls(session, cascades)
178
- latest = None
179
- for call in calls:
180
- try:
181
- stamp = datetime.fromisoformat(call["timestamp"].replace("Z", "+00:00")).timestamp()
182
- except (ValueError, TypeError, KeyError, AttributeError):
183
- continue
184
- if latest is None or stamp >= latest[0]:
185
- latest = stamp, call
186
- if latest:
187
- call = latest[1]
188
- result.update(context=token_sum(call, "inputTokens", "cacheReadInputTokens", "cacheCreationInputTokens"),
189
- model=call.get("model"))
190
- window = call.get("contextWindow")
191
- if not (type(window) is int and window > 0) and valid_id(session):
192
- key = call.get("deduplicationKey")
193
- prefix = "antigravity:" + session + ":"
194
- if isinstance(key, str) and key.startswith(prefix):
195
- paths = [HOME / ".gemini" / app / "conversations" / (session + ".db")
196
- for app in ("antigravity", "antigravity-cli", "antigravity-ide")]
197
- matches = [path for path in paths if path.is_file()]
198
- if len(matches) == 1:
199
- window = antigravity_context.request_window(matches[0], key[len(prefix):])
200
- if type(window) is int and window > 0:
201
- result["contextWindow"] = window
202
- return result
203
-
204
-
205
- def agy_cascades():
206
- folder = Path(os.environ.get("CODEBURN_CACHE_DIR") or HOME / ".cache/codeburn")
207
- cache = folder / "antigravity-results.v11.json"
208
- if not cache.is_file():
209
- return {}
210
- data = json.loads(cache.read_bytes())
211
- return data.get("cascades", {}) if data.get("version") == 11 else {}
212
-
213
-
214
- def agy_calls(session, cascades=None):
215
- if cascades is None:
216
- cascades = agy_cascades()
217
- calls = cascades.get(session, {}).get("calls", [])
218
- return [call for call in calls if call.get("provider") == "antigravity"
219
- and call.get("sessionId") == session and not call.get("costIsEstimated")]
220
-
221
-
222
- def spend_stats(events, unit, now=None):
223
- if not events:
224
- return {}
225
- events.sort()
226
- now = datetime.now().timestamp() if now is None else now
227
- amounts = [cost for _, cost in events]
228
- return {"average": sum(amounts) / len(amounts), "peak": max(amounts), "last": amounts[-1],
229
- "unit": unit, "asOf": now,
230
- "score": sum(cost * 0.5 ** (max(0, now - when) / 150) for when, cost in events)}
231
-
232
-
233
- def cost_event(stamp, cost):
234
- if not isinstance(stamp, str) or type(cost) not in (int, float) or not math.isfinite(cost) or cost < 0:
235
- return None
236
- try:
237
- return datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp(), cost
238
- except (ValueError, OverflowError):
239
- return None
240
-
241
-
242
- def session_spend(provider, session):
243
- if provider == "antigravity":
244
- events = [cost_event(call.get("timestamp"), call.get("costUSD")) for call in agy_calls(session)]
245
- return spend_stats([event for event in events if event is not None], "requests")
246
- report = codeburn_json(["sessions", "--provider", "claude", "--id", session, "--why", "--format", "json"])
247
- if not isinstance(report, dict) or report.get("sessionId") != session:
248
- return {}
249
- events = [cost_event(turn.get("ts"), turn.get("cost")) for turn in report.get("turns", [])]
250
- result = spend_stats([event for event in events if event is not None], "turns")
251
- # CodeBurn steps are offsets in milliseconds from the start of the turn.
252
- # Only model steps carry request prices. Adding the turn total again would double-count.
253
- requests = []
254
- helpers = {}
255
-
256
- def model_steps(base, steps):
257
- if base is None:
258
- return
259
- for step in steps:
260
- offset, cost = step.get("end"), step.get("cost")
261
- if step.get("kind") == "model" and usage_activity.amount(offset) and usage_activity.amount(cost):
262
- requests.append((base + offset / 1000, cost))
263
-
264
- for turn in report.get("turns", []):
265
- model_steps(usage_activity.event_time(turn.get("ts")), turn.get("steps", []))
266
- for entry in turn.get("helpers", []):
267
- key = entry.get("id")
268
- if not key or key in helpers:
269
- continue
270
- item = usage_activity.helper(key, entry.get("agentType"), entry.get("model"))
271
- for field in ("cost", "calls"):
272
- if usage_activity.amount(entry.get(field)):
273
- item[field] = entry[field]
274
- helpers[key] = item
275
- steps = entry.get("steps") or []
276
- model = next((s for s in steps if s.get("kind") == "model"), {})
277
- base = usage_activity.event_time(entry.get("delegatedAt"))
278
- first = usage_activity.event_time(entry.get("firstCallAt"))
279
- if base is None and first is not None and usage_activity.amount(model.get("start")):
280
- base = first - model["start"] / 1000
281
- model_steps(base, steps)
282
- # A single priced request still has an exact timestamp when step details are omitted.
283
- if not steps and entry.get("calls") == 1:
284
- event = cost_event(entry.get("lastCallAt"), item.get("cost"))
285
- if event is not None:
286
- requests.append(event)
287
- result.update(usage_activity.rollup(requests, datetime.now().timestamp()))
288
- if helpers:
289
- result["helpers"] = list(helpers.values())
290
- helper_cost = report.get("helperCost")
291
- if type(helper_cost) in (int, float) and math.isfinite(helper_cost) and helper_cost >= 0:
292
- result["agentCost"] = helper_cost
293
- return result
294
-
295
-
296
- def codeburn_json(arguments):
297
- binary = os.environ.get("CODEBURN_BIN") or shutil.which("codeburn") or next((str(p) for p in (Path("/opt/homebrew/bin/codeburn"), Path("/usr/local/bin/codeburn")) if p.is_file()), None)
298
- if not binary:
299
- raise FileNotFoundError("CodeBurn is unavailable")
300
- env = dict(os.environ)
301
- env["PATH"] = os.pathsep.join(dict.fromkeys([*os.get_exec_path(env), str(Path(binary).parent)]))
302
- run = subprocess.run([binary] + arguments,
303
- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env, timeout=20, check=True)
304
- return json.loads(run.stdout)
305
-
306
-
307
- def session_report(provider, period="lifetime"):
308
- rows = codeburn_json(["sessions", "--provider", provider, "--period", period, "--format", "json"])
309
- if not isinstance(rows, list):
310
- raise ValueError("Unexpected CodeBurn session report")
311
- report = {}
312
- duplicates = set()
313
- for row in rows:
314
- session = row.get("sessionId")
315
- if row.get("provider") != provider or not isinstance(session, str) or not session:
316
- continue
317
- if session in report:
318
- duplicates.add(session)
319
- continue
320
- cost = row.get("cost")
321
- priced = usage_activity.amount(cost) and (cost > 0 or bool(row.get("costBasis")))
322
- report[session] = {
323
- "cost": cost if priced else None,
324
- **{k: row[k] for k in ("calls", "inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens")
325
- if type(row.get(k)) is int and row[k] >= 0},
326
- }
327
- ended = usage_activity.event_time(row.get("endedAt"))
328
- if ended is not None:
329
- report[session]["ended"] = ended
330
- for session in duplicates:
331
- del report[session]
332
- return report
333
-
334
-
335
- def read_cost(provider, session):
336
- return session_report(provider).get(session, {}).get("cost")
337
-
338
-
339
- def main():
340
- if sys.argv[1:2] in (["--overview"], ["--helpers"]) and len(sys.argv) == 3:
341
- return usage_activity.overview(sys.argv[2], HOME, metadata_only=sys.argv[1] == "--helpers")
342
- if sys.argv[1:] == ["--check-bundle"]:
343
- return {"reader": True}
344
- if sys.argv[1:2] in (["--report"], ["--today"]) and sys.argv[2:] in (["claude"], ["antigravity"], ["codex"]):
345
- return session_report(sys.argv[2], "today" if sys.argv[1] == "--today" else "lifetime")
346
- if sys.argv[1:2] == ["--picker-title"] and len(sys.argv) == 3 and valid_id(sys.argv[2]):
347
- return picker_title(sys.argv[2])
348
- if sys.argv[1:2] == ["--spend"] and len(sys.argv) == 4:
349
- provider, session = sys.argv[2:]
350
- return session_spend(provider, session) if provider in ("claude", "antigravity") and valid_id(session) else {}
351
- if sys.argv[1:2] in (["--details"], ["--detail"]) and len(sys.argv) >= 4:
352
- provider = sys.argv[2]
353
- results = {}
354
- cascades = agy_cascades() if provider == "antigravity" else None
355
- for session in dict.fromkeys(sys.argv[3:]):
356
- if not valid_id(session):
357
- continue
358
- try:
359
- if provider == "codex":
360
- results[session] = codex_sessions.detail(codex_sessions.codex_home(), session)
361
- elif provider == "claude":
362
- results[session] = claude_detail(session)
363
- elif provider == "antigravity":
364
- results[session] = agy_detail(session, cascades)
365
- except (OSError, ValueError, sqlite3.Error):
366
- continue
367
- return results if sys.argv[1] == "--details" else results.get(sys.argv[3], {})
368
- if sys.argv[1:2] == ["--list"] and len(sys.argv) >= 4:
369
- provider, route = sys.argv[2:4]
370
- extra_ids = {key for key in sys.argv[4:] if valid_id(key)}
371
- return recent_sessions(provider, route, extra_ids=extra_ids) if (provider == "codex" and route == "current") or valid_id(route) else []
372
- provider, route = sys.argv[1:3]
373
- if provider == "codex":
374
- home = codex_sessions.codex_home()
375
- selected = codex_sessions.selected_id(home, HOME / "Library/Logs/com.openai.codex") if route == "current" else route
376
- rows = codex_sessions.chats(home, selected, 1) if selected and valid_id(selected) else []
377
- return rows[0] if rows else {}
378
- if not valid_id(route):
379
- return {}
380
- if provider == "claude":
381
- found = claude_session(route)
382
- elif provider == "antigravity":
383
- found = agy_session(route)
384
- else:
385
- return {}
386
- if not found:
387
- return {}
388
- session, title = found
389
- result = {"id": session, "title": title}
390
- if "--identity" not in sys.argv[3:]:
391
- try:
392
- result["cost"] = read_cost(provider, session)
393
- except (subprocess.SubprocessError, OSError, ValueError, KeyError):
394
- result["cost"] = None
395
- return result
396
-
397
-
398
- if __name__ == "__main__":
399
- try:
400
- print(json.dumps(main(), allow_nan=False))
401
- except (ValueError, OSError, TypeError, KeyError, sqlite3.Error, subprocess.SubprocessError):
402
- sys.exit(1)
package/usage_activity.py DELETED
@@ -1,189 +0,0 @@
1
- """Normalize priced usage and explicit helper roles for the shared HUD."""
2
- from collections import defaultdict
3
- from datetime import datetime
4
- import json
5
- import math
6
- import os
7
- from pathlib import Path
8
- import re
9
- import sqlite3
10
- import time
11
-
12
- import codex_sessions
13
- from local_database import read_database
14
- from reviewer_records import review_index
15
-
16
-
17
- def is_reviewer(*roles):
18
- known = {"guardian", "guardian-review", "auto-review", "auto-reviewer", "codex-auto-review",
19
- "automatic-reviewer", "permission-reviewer"}
20
- return any(isinstance(role, str) and role.lower().replace("_", "-") in known for role in roles)
21
-
22
-
23
- def helper(key, *roles):
24
- return {"id": key, "reviewer": is_reviewer(*roles)}
25
-
26
-
27
- def codex_helpers(home):
28
- with codex_sessions.connect(home) as conn:
29
- conn.row_factory = sqlite3.Row
30
- cols = {r[1] for r in conn.execute("pragma table_info(threads)")}
31
- fields = [c for c in ("id", "thread_source", "model", "source", "attached_thread_parent_id", "agent_role", "rollout_path") if c in cols]
32
- parents = {}
33
- if conn.execute("select 1 from sqlite_master where name='thread_spawn_edges'").fetchone():
34
- parents.update(conn.execute("select child_thread_id,parent_thread_id from thread_spawn_edges"))
35
- groups = defaultdict(list)
36
- reviews = {}
37
- review_parents = {}
38
- for row in conn.execute("select " + ",".join(fields) + " from threads"):
39
- record = dict(row)
40
- key = record["id"]
41
- source = record.get("source") or ""
42
- try:
43
- origin = json.loads(source) if source.startswith("{") else {}
44
- sub = origin.get("subagent", {}) if isinstance(origin, dict) else {}
45
- except ValueError:
46
- sub = {}
47
- role = sub.get("other") if isinstance(sub, dict) else sub
48
- item = helper(key, role, record.get("thread_source"), record.get("model"), record.get("agent_role"))
49
- parent = parents.get(key) or record.get("attached_thread_parent_id")
50
- if item["reviewer"] and record.get("rollout_path"):
51
- reviews[key] = record["rollout_path"]
52
- review_parents[key] = parent
53
- elif parent and parent != key:
54
- groups[parent].append(item)
55
- cache = Path.home() / "Library/Caches/io.github.anopows.cost-bubble/review-index.json"
56
- index = review_index(reviews, cache)
57
- for key in reviews:
58
- record = index.get(key, {})
59
- parent = review_parents[key] or record.get("parent")
60
- if parent and key != parent:
61
- item = helper(key, "guardian")
62
- if "calls" in record:
63
- item["calls"] = record["calls"]
64
- groups[parent].append(item)
65
- return groups
66
-
67
-
68
- def agy_helpers(db):
69
- with read_database(db) as conn:
70
- cols = {row[1] for row in conn.execute("pragma table_info(conversation_summaries)")}
71
- role = "agent_name" if "agent_name" in cols else "NULL"
72
- rows = conn.execute("select parent_conversation_id, conversation_id, " + role +
73
- ", source from conversation_summaries where coalesce(parent_conversation_id,'') != ''")
74
- groups = defaultdict(list)
75
- for parent, key, agent, source in rows:
76
- if parent != key:
77
- groups[parent].append(helper(key, agent, source))
78
- return groups
79
-
80
-
81
- def claude_helpers(projects):
82
- groups = defaultdict(list)
83
- for folder in projects.glob("*/*/subagents"):
84
- session = folder.parent.name
85
- for transcript in folder.rglob("agent-*.jsonl"):
86
- try:
87
- meta = json.loads(transcript.with_suffix(".meta.json").read_bytes())
88
- except (OSError, ValueError):
89
- meta = {}
90
- # CodeBurn identifies a helper by the complete transcript stem.
91
- groups[session].append(helper(transcript.stem, meta.get("agentType")))
92
- return groups
93
-
94
-
95
- def event_time(stamp):
96
- if isinstance(stamp, str):
97
- try:
98
- # Python 3.9 accepts three or six fractional digits; providers also emit nanoseconds.
99
- stamp = re.sub(r"\.(\d+)", lambda m: "." + m[1][:6].ljust(6, "0"), stamp, count=1)
100
- return datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp()
101
- except (ValueError, OverflowError):
102
- pass
103
- return None
104
-
105
-
106
- def amount(value):
107
- return type(value) in (int, float) and math.isfinite(value) and value >= 0
108
-
109
-
110
- def priced_calls(provider, cache):
111
- filename, version, section = {"codex": ("codex-results.v25.json", 25, "files"),
112
- "antigravity": ("antigravity-results.v11.json", 11, "cascades")}[provider]
113
- data = json.loads((cache / filename).read_bytes())
114
- if data.get("version") != version:
115
- raise ValueError("Unsupported CodeBurn usage cache")
116
- seen = set()
117
- for key, group in data.get(section, {}).items():
118
- for call in group.get("calls", []):
119
- session = call.get("sessionId")
120
- if call.get("provider") != provider or not session or (provider == "antigravity" and key != session):
121
- continue
122
- uid = call.get("deduplicationKey")
123
- if uid and (session, uid) in seen:
124
- continue
125
- if uid:
126
- seen.add((session, uid))
127
- yield session, call
128
-
129
-
130
- def rollup(events, now):
131
- ordered = sorted(events)
132
- return {"recent": [[stamp, cost] for stamp, cost in ordered if now - 3600 < stamp <= now + 60 and cost > 0]}
133
-
134
-
135
- def descendants(groups, root):
136
- seen = {root}
137
- pending = list(groups.get(root, []))
138
- result = []
139
- while pending:
140
- item = pending.pop()
141
- key = item["id"]
142
- if key in seen:
143
- continue
144
- seen.add(key)
145
- result.append(dict(item))
146
- pending.extend(groups.get(key, []))
147
- return sorted(result, key=lambda item: item["id"])
148
-
149
-
150
- def overview(provider, home, now=None, metadata_only=False):
151
- cache = Path(os.environ.get("CODEBURN_CACHE_DIR") or home / ".cache/codeburn")
152
- if provider == "codex":
153
- groups = codex_helpers(codex_sessions.codex_home())
154
- elif provider == "antigravity":
155
- groups = agy_helpers(home / ".gemini/antigravity/conversation_summaries.db")
156
- elif provider == "claude":
157
- projects = Path(os.environ.get("CLAUDE_CONFIG_DIR") or home / ".claude") / "projects"
158
- return {key: {"helpers": items} for key, items in claude_helpers(projects).items()}
159
- else:
160
- return {}
161
- if metadata_only:
162
- return {key: {"helpers": descendants(groups, key)} for key in groups}
163
- events = defaultdict(list)
164
- counts = defaultdict(int)
165
- for session, call in priced_calls(provider, cache):
166
- cost, stamp = call.get("costUSD"), event_time(call.get("timestamp"))
167
- counts[session] += 1
168
- if stamp is not None and amount(cost) and not call.get("costIsEstimated"):
169
- events[session].append((stamp, cost))
170
- now = time.time() if now is None else now
171
- result = {}
172
- for session in groups.keys() | events.keys():
173
- children = descendants(groups, session)
174
- own = events.get(session, [])
175
- combined = list(own)
176
- for child in children:
177
- detail = events.get(child["id"], [])
178
- combined.extend(detail)
179
- if counts.get(child["id"]):
180
- child["calls"] = counts[child["id"]]
181
- if len(detail) == child["calls"]:
182
- child["cost"] = sum(cost for _, cost in detail)
183
- record = rollup(combined, now) if combined else {}
184
- record["helpers"] = children
185
- if own:
186
- costs = [cost for _, cost in own]
187
- record.update(average=sum(costs)/len(costs), peak=max(costs), last=max(own)[1], unit="requests")
188
- result[session] = record
189
- return result