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