ukaf-cli 0.1.0__py3-none-any.whl

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.
ukaf/story.py ADDED
@@ -0,0 +1,459 @@
1
+ """Build the additive story.
2
+
3
+ Every feature is five consecutive stages. Stage durations telescope, so they add
4
+ up to the feature duration. Each usage event is placed in exactly one stage or
5
+ in overhead. Money and tokens move with the event, so the same identity holds
6
+ for list price, billed cost, and tokens.
7
+
8
+ DORA lead time is not a second clock. It is testing + deploy, the two stages
9
+ that sit between the first push and acceptance.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections import defaultdict
15
+ from dataclasses import dataclass, field
16
+ from datetime import UTC, date, datetime, timedelta
17
+
18
+ from ukaf.delivery import Deployment, Pull, measure
19
+ from ukaf.money import mul_div_half_even
20
+ from ukaf.timeutil import delta_us
21
+ from ukaf.usage import UsageEvent
22
+
23
+ STAGE_NAMES = ("planning", "development", "testing", "deploy", "fixes")
24
+
25
+ # Production-looking environment names. Anything else still counts when the
26
+ # pull has no production deployment and only one environment.
27
+ PROD_ENVS = {"production", "prod", "live"}
28
+
29
+
30
+ @dataclass
31
+ class Stage:
32
+ name: str
33
+ duration_us: int = 0
34
+ list_micro: int = 0
35
+ billed_micro: int = 0
36
+ tokens: int = 0
37
+ events: int = 0
38
+
39
+ def add(self, event: UsageEvent) -> None:
40
+ self.list_micro += event.list_micro
41
+ self.billed_micro += event.billed_micro
42
+ self.tokens += event.total_tokens
43
+ self.events += 1
44
+
45
+
46
+ @dataclass
47
+ class Feature:
48
+ repo: str
49
+ number: int
50
+ title: str
51
+ url: str
52
+ author: str
53
+ tier: str
54
+ sloc: int
55
+ sloc_excluded: int
56
+ files_counted: int
57
+ files_excluded: int
58
+ stages: list[Stage]
59
+ list_micro: int
60
+ billed_micro: int
61
+ tokens: int
62
+ events: int
63
+ duration_us: int
64
+ lead_time_us: int
65
+ failed: bool
66
+ deployed: bool
67
+ prod_deploys: int
68
+ merged: bool
69
+ fast_list_micro: int
70
+ fast_billed_micro: int
71
+ fast_saving_list_micro: int
72
+ fast_saving_billed_micro: int
73
+ bounds: tuple[datetime, datetime, datetime, datetime, datetime, datetime]
74
+
75
+
76
+ @dataclass
77
+ class ModelRollup:
78
+ model: str
79
+ priced_as: str
80
+ events: int = 0
81
+ tokens: int = 0
82
+ list_micro: int = 0
83
+ billed_micro: int = 0
84
+ fast: bool = False
85
+
86
+
87
+ @dataclass
88
+ class Overhead:
89
+ list_micro: int = 0
90
+ billed_micro: int = 0
91
+ tokens: int = 0
92
+ events: int = 0
93
+ on_demand_events: int = 0
94
+ on_demand_billed_micro: int = 0
95
+ on_demand_list_micro: int = 0
96
+ models: dict[str, int] = field(default_factory=dict)
97
+ on_demand_models: dict[str, int] = field(default_factory=dict)
98
+
99
+
100
+ @dataclass
101
+ class FastTotals:
102
+ events: int = 0
103
+ list_micro: int = 0
104
+ billed_micro: int = 0
105
+ saving_list_micro: int = 0
106
+ saving_billed_micro: int = 0
107
+ models: dict[str, int] = field(default_factory=dict)
108
+
109
+
110
+ @dataclass
111
+ class DailySpend:
112
+ day: date
113
+ list_micro: int = 0
114
+ billed_micro: int = 0
115
+ fast_list_micro: int = 0
116
+
117
+
118
+ @dataclass
119
+ class Story:
120
+ features: list[Feature]
121
+ overhead: Overhead
122
+ models: list[ModelRollup]
123
+ events: int
124
+ tokens: int
125
+ list_micro: int
126
+ billed_micro: int
127
+ window_start: datetime | None
128
+ window_end: datetime | None
129
+ fast: FastTotals
130
+ max_mode_events: int
131
+ max_mode_list_micro: int
132
+ max_mode_billed_micro: int
133
+ default_priced_models: tuple[str, ...]
134
+ assumptions: tuple[str, ...]
135
+ daily_spend: list[DailySpend] = field(default_factory=list)
136
+
137
+
138
+ def build_story(events: list[UsageEvent], pulls: list[Pull]) -> Story:
139
+ claims = _claim_agents(pulls)
140
+ by_pull, unassigned = _assign(events, pulls, claims)
141
+ features = [_feature(pull, by_pull.get(id(pull), [])) for pull in pulls]
142
+ features.sort(key=lambda item: (item.repo, item.number))
143
+
144
+ overhead = Overhead()
145
+ fast = FastTotals()
146
+ models: dict[tuple[str, str], ModelRollup] = {}
147
+ default_priced: set[str] = set()
148
+ max_events = max_list = max_billed = 0
149
+
150
+ def note_common(event: UsageEvent) -> None:
151
+ nonlocal max_events, max_list, max_billed
152
+ key = (event.model, event.priced_as)
153
+ roll = models.get(key)
154
+ if roll is None:
155
+ roll = ModelRollup(model=event.model, priced_as=event.priced_as, fast=event.fast)
156
+ models[key] = roll
157
+ roll.events += 1
158
+ roll.tokens += event.total_tokens
159
+ roll.list_micro += event.list_micro
160
+ roll.billed_micro += event.billed_micro
161
+ if event.used_default:
162
+ default_priced.add(event.model)
163
+ if event.max_mode:
164
+ max_events += 1
165
+ max_list += event.list_micro
166
+ max_billed += event.billed_micro
167
+ if event.fast:
168
+ fast.events += 1
169
+ fast.list_micro += event.list_micro
170
+ fast.billed_micro += event.billed_micro
171
+ delta = event.list_micro - event.non_fast_list_micro
172
+ fast.saving_list_micro += max(delta, 0)
173
+ if delta > 0 and event.list_micro > 0 and event.billed_micro > 0:
174
+ fast.saving_billed_micro += mul_div_half_even(event.billed_micro, delta, event.list_micro)
175
+ fast.models[event.model] = fast.models.get(event.model, 0) + 1
176
+
177
+ for event in unassigned:
178
+ overhead.events += 1
179
+ overhead.list_micro += event.list_micro
180
+ overhead.billed_micro += event.billed_micro
181
+ overhead.tokens += event.total_tokens
182
+ overhead.models[event.model] = overhead.models.get(event.model, 0) + 1
183
+ if event.billed_micro > 0:
184
+ overhead.on_demand_events += 1
185
+ overhead.on_demand_billed_micro += event.billed_micro
186
+ overhead.on_demand_list_micro += event.list_micro
187
+ overhead.on_demand_models[event.model] = overhead.on_demand_models.get(event.model, 0) + 1
188
+ note_common(event)
189
+
190
+ for feature_events in by_pull.values():
191
+ for event in feature_events:
192
+ note_common(event)
193
+
194
+ daily: dict[date, DailySpend] = {}
195
+ for event in events:
196
+ day = event.at.astimezone(UTC).date() if event.at.tzinfo else event.at.date()
197
+ row = daily.setdefault(day, DailySpend(day))
198
+ row.list_micro += event.list_micro
199
+ row.billed_micro += event.billed_micro
200
+ if event.fast:
201
+ row.fast_list_micro += event.list_micro
202
+
203
+ if events:
204
+ window_start = min(event.at for event in events)
205
+ window_end = max(event.at for event in events)
206
+ else:
207
+ window_start = window_end = None
208
+
209
+ assumptions = [
210
+ "Included and Free rows have billed cost 0. Their list price still comes from the pricing table.",
211
+ "List price is rounded half-even to a micro-dollar on each event, then summed. The total is the sum of the rows, not a re-price of the totals.",
212
+ "Fast savings assume the invoice scales with list price: billed saving = billed × (list − non-fast list) / list, per event.",
213
+ "Bot and Auto skus with no published rate are priced as Grok 4.7 standard. See the pricing file.",
214
+ "The fixes stage is only time after acceptance (a revert, a restore, or a later commit). Rework before the first green CI stays inside testing.",
215
+ "DORA lead time equals the testing stage plus the deploy stage. It is not a separate overlapping window.",
216
+ ]
217
+ if default_priced:
218
+ assumptions.append(
219
+ "These model ids were missing from the pricing table and used the default rate: "
220
+ + ", ".join(sorted(default_priced))
221
+ + "."
222
+ )
223
+
224
+ return Story(
225
+ features=features,
226
+ overhead=overhead,
227
+ models=sorted(models.values(), key=lambda item: (-item.list_micro, item.model)),
228
+ events=len(events),
229
+ tokens=sum(event.total_tokens for event in events),
230
+ list_micro=sum(event.list_micro for event in events),
231
+ billed_micro=sum(event.billed_micro for event in events),
232
+ window_start=window_start,
233
+ window_end=window_end,
234
+ fast=fast,
235
+ max_mode_events=max_events,
236
+ max_mode_list_micro=max_list,
237
+ max_mode_billed_micro=max_billed,
238
+ default_priced_models=tuple(sorted(default_priced)),
239
+ assumptions=tuple(assumptions),
240
+ daily_spend=sorted(daily.values(), key=lambda row: row.day),
241
+ )
242
+
243
+
244
+ def _claim_agents(pulls: list[Pull]) -> dict[str, Pull]:
245
+ claims: dict[str, Pull] = {}
246
+ for pull in pulls:
247
+ for agent_id in pull.agent_ids:
248
+ previous = claims.get(agent_id)
249
+ if previous is not None and previous is not pull:
250
+ raise ValueError(
251
+ f"agent {agent_id} is claimed by {previous.repo}#{previous.number} "
252
+ f"and {pull.repo}#{pull.number}; an event cannot sit in two features"
253
+ )
254
+ claims[agent_id] = pull
255
+ return claims
256
+
257
+
258
+ def _assign(
259
+ events: list[UsageEvent],
260
+ pulls: list[Pull],
261
+ claims: dict[str, Pull],
262
+ ) -> tuple[dict[int, list[UsageEvent]], list[UsageEvent]]:
263
+ grouped: dict[str, list[UsageEvent]] = defaultdict(list)
264
+ loose: list[UsageEvent] = []
265
+ for event in events:
266
+ if event.agent_id:
267
+ grouped[event.agent_id].append(event)
268
+ else:
269
+ loose.append(event)
270
+
271
+ by_pull: dict[int, list[UsageEvent]] = defaultdict(list)
272
+ unassigned: list[UsageEvent] = list(loose)
273
+
274
+ for agent_id, agent_events in grouped.items():
275
+ owner = claims.get(agent_id)
276
+ if owner is None:
277
+ owner = _time_match(agent_events[0].at, pulls, claims)
278
+ if owner is None:
279
+ unassigned.extend(agent_events)
280
+ continue
281
+ by_pull[id(owner)].extend(agent_events)
282
+ return by_pull, unassigned
283
+
284
+
285
+ def _time_match(moment: datetime, pulls: list[Pull], claims: dict[str, Pull]) -> Pull | None:
286
+ """Assign an unclaimed agent only when a single open PR has no agent id of its own.
287
+
288
+ Pulls that already name an agent do not absorb a second one. Events with no
289
+ agent id are never guessed; the caller leaves them in overhead.
290
+ """
291
+ del claims
292
+ hits: list[Pull] = []
293
+ for pull in pulls:
294
+ if pull.agent_ids:
295
+ continue
296
+ start = pull.issue_created_at or pull.created_at
297
+ end = pull.merged_at or pull.closed_at or pull.created_at
298
+ if start <= moment <= end:
299
+ hits.append(pull)
300
+ if len(hits) == 1:
301
+ return hits[0]
302
+ return None
303
+
304
+
305
+ def _feature(pull: Pull, events: list[UsageEvent]) -> Feature:
306
+ measured = measure(pull.files)
307
+ first_push = min(pull.commits) if pull.commits else pull.created_at
308
+ agent_launch = min(event.at for event in events) if events else first_push
309
+ feature_start = pull.issue_created_at or agent_launch
310
+ accepted = _accepted_at(pull, first_push)
311
+ ci_done = _ci_done(pull, first_push, accepted)
312
+ fixes_end = _fixes_end(pull, events, accepted)
313
+
314
+ # Later milestones win. Each earlier boundary is pulled back so the five
315
+ # intervals stay consecutive and non-overlapping. A milestone that would
316
+ # have landed out of order becomes a zero-length stage instead of a second
317
+ # overlapping clock.
318
+ end = max(feature_start, agent_launch, first_push, ci_done, accepted, fixes_end)
319
+ if events:
320
+ end = max(end, max(event.at for event in events))
321
+ accepted = min(accepted, end)
322
+ ci_done = min(ci_done, accepted)
323
+ first_push = min(first_push, ci_done)
324
+ agent_launch = min(agent_launch, first_push)
325
+ feature_start = min(feature_start, agent_launch)
326
+ fixes_end = end
327
+ bounds = (feature_start, agent_launch, first_push, ci_done, accepted, fixes_end)
328
+
329
+ stages = [Stage(name) for name in STAGE_NAMES]
330
+ for index in range(5):
331
+ stages[index].duration_us = delta_us(bounds[index], bounds[index + 1])
332
+
333
+ fast_list = fast_billed = fast_save_list = fast_save_billed = 0
334
+ for event in events:
335
+ stages[_stage_index(event.at, bounds)].add(event)
336
+ if event.fast:
337
+ fast_list += event.list_micro
338
+ fast_billed += event.billed_micro
339
+ delta = event.list_micro - event.non_fast_list_micro
340
+ if delta > 0:
341
+ fast_save_list += delta
342
+ if event.billed_micro > 0 and event.list_micro > 0:
343
+ fast_save_billed += mul_div_half_even(event.billed_micro, delta, event.list_micro)
344
+
345
+ list_micro = sum(stage.list_micro for stage in stages)
346
+ billed_micro = sum(stage.billed_micro for stage in stages)
347
+ tokens = sum(stage.tokens for stage in stages)
348
+ event_count = sum(stage.events for stage in stages)
349
+ duration = sum(stage.duration_us for stage in stages)
350
+ lead = stages[2].duration_us + stages[3].duration_us
351
+ failed = bool(pull.reverted or pull.incident)
352
+ prod_deploys = _prod_deploy_count(pull)
353
+ deployed = prod_deploys > 0
354
+ return Feature(
355
+ repo=pull.repo,
356
+ number=pull.number,
357
+ title=pull.title,
358
+ url=pull.url,
359
+ author=pull.author,
360
+ tier=measured.tier,
361
+ sloc=measured.hand_written,
362
+ sloc_excluded=measured.excluded,
363
+ files_counted=measured.files_counted,
364
+ files_excluded=measured.files_excluded,
365
+ stages=stages,
366
+ list_micro=list_micro,
367
+ billed_micro=billed_micro,
368
+ tokens=tokens,
369
+ events=event_count,
370
+ duration_us=duration,
371
+ lead_time_us=lead,
372
+ failed=failed,
373
+ deployed=deployed,
374
+ prod_deploys=prod_deploys,
375
+ merged=pull.merged_at is not None,
376
+ fast_list_micro=fast_list,
377
+ fast_billed_micro=fast_billed,
378
+ fast_saving_list_micro=fast_save_list,
379
+ fast_saving_billed_micro=fast_save_billed,
380
+ bounds=bounds,
381
+ )
382
+
383
+
384
+ def _stage_index(moment: datetime, bounds: tuple[datetime, ...]) -> int:
385
+ """Boundary instants belong to the stage that starts there. The last stage is closed."""
386
+ if moment <= bounds[0]:
387
+ return 0
388
+ for index in range(4):
389
+ if moment < bounds[index + 1]:
390
+ return index
391
+ return 4
392
+
393
+
394
+ def _accepted_at(pull: Pull, first_push: datetime) -> datetime:
395
+ prod = [
396
+ item.updated_at
397
+ for item in pull.deployments
398
+ if item.state.lower() in {"success", "active"}
399
+ and _is_prod(item, pull.deployments)
400
+ and item.updated_at >= first_push - timedelta(seconds=1)
401
+ ]
402
+ if prod:
403
+ return min(prod)
404
+ if pull.merged_at:
405
+ return pull.merged_at
406
+ if pull.closed_at:
407
+ return pull.closed_at
408
+ return first_push
409
+
410
+
411
+ def _is_prod(item: Deployment, all_items: tuple[Deployment, ...]) -> bool:
412
+ name = item.environment.strip().lower()
413
+ if name in PROD_ENVS:
414
+ return True
415
+ names = {deploy.environment.strip().lower() for deploy in all_items}
416
+ return names <= PROD_ENVS or names == {name}
417
+
418
+
419
+ def _prod_deploy_count(pull: Pull) -> int:
420
+ return sum(
421
+ 1
422
+ for item in pull.deployments
423
+ if item.state.lower() in {"success", "active"} and _is_prod(item, pull.deployments)
424
+ )
425
+
426
+
427
+ def _ci_done(pull: Pull, first_push: datetime, accepted: datetime) -> datetime:
428
+ completed = [
429
+ item.completed_at
430
+ for item in pull.checks
431
+ if item.completed_at is not None and first_push <= item.completed_at <= accepted
432
+ ]
433
+ successes = [
434
+ item.completed_at
435
+ for item in pull.checks
436
+ if item.completed_at is not None
437
+ and item.conclusion.lower() == "success"
438
+ and first_push <= item.completed_at <= accepted
439
+ ]
440
+ if successes:
441
+ return min(successes)
442
+ if completed:
443
+ return max(completed)
444
+ return first_push
445
+
446
+
447
+ def _fixes_end(pull: Pull, events: list[UsageEvent], accepted: datetime) -> datetime:
448
+ points = [accepted]
449
+ if pull.incident and pull.incident.resolved_at:
450
+ points.append(pull.incident.resolved_at)
451
+ if pull.reverted and pull.closed_at:
452
+ points.append(pull.closed_at)
453
+ for moment in pull.commits:
454
+ if moment > accepted:
455
+ points.append(moment)
456
+ for event in events:
457
+ if event.at > accepted:
458
+ points.append(event.at)
459
+ return max(points)
ukaf/timeutil.py ADDED
@@ -0,0 +1,65 @@
1
+ """UTC timestamps and durations stored as integer microseconds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+
7
+ US = 1_000_000
8
+
9
+
10
+ def parse_time(value: str) -> datetime:
11
+ text = value.strip()
12
+ if not text:
13
+ raise ValueError("empty timestamp")
14
+ if text.endswith("Z"):
15
+ text = text[:-1] + "+00:00"
16
+ dt = datetime.fromisoformat(text)
17
+ if dt.tzinfo is None:
18
+ dt = dt.replace(tzinfo=UTC)
19
+ return dt.astimezone(UTC)
20
+
21
+
22
+ def iso(dt: datetime) -> str:
23
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
24
+
25
+
26
+ def delta_us(start: datetime, end: datetime) -> int:
27
+ d = end - start
28
+ return d.days * 86_400 * US + d.seconds * US + d.microseconds
29
+
30
+
31
+ def fmt_duration(us: int, *, hebrew: bool = False) -> str:
32
+ """Human duration. Milliseconds are kept so adjacent stages still add up."""
33
+ sign = "-" if us < 0 else ""
34
+ us = abs(int(us))
35
+ ms_total, rem = divmod(us, 1000)
36
+ if rem >= 500:
37
+ ms_total += 1
38
+ seconds, ms = divmod(ms_total, 1000)
39
+ minutes, sec = divmod(seconds, 60)
40
+ hours, minutes = divmod(minutes, 60)
41
+ days, hours = divmod(hours, 24)
42
+ d, h, m = ("י", "ש", "ד") if hebrew else ("d", "h", "m")
43
+ parts: list[str] = []
44
+ if days:
45
+ parts.append(f"{days}{d}")
46
+ if days or hours:
47
+ parts.append(f"{hours}{h}")
48
+ if days or hours or minutes:
49
+ parts.append(f"{minutes}{m}")
50
+ if ms:
51
+ parts.append(f"{sec}.{ms:03d}s")
52
+ else:
53
+ parts.append(f"{sec}s")
54
+ return sign + " ".join(parts)
55
+
56
+
57
+ def fmt_seconds_exact(us: int) -> str:
58
+ """Decimal seconds with millisecond resolution (input timestamps are ms)."""
59
+ sign = "-" if us < 0 else ""
60
+ us = abs(int(us))
61
+ ms_total, rem = divmod(us, 1000)
62
+ if rem >= 500:
63
+ ms_total += 1
64
+ seconds, ms = divmod(ms_total, 1000)
65
+ return f"{sign}{seconds}.{ms:03d}"
ukaf/usage.py ADDED
@@ -0,0 +1,150 @@
1
+ """Parse a Cursor usage CSV export. Every data row becomes one event."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+ from decimal import Decimal, InvalidOperation
9
+ from pathlib import Path
10
+
11
+ from ukaf.money import usd_to_micro
12
+ from ukaf.pricing import PriceCard, price_tokens
13
+ from ukaf.timeutil import parse_time
14
+
15
+ REQUIRED = (
16
+ "Date",
17
+ "Cloud Agent ID",
18
+ "Automation ID",
19
+ "Kind",
20
+ "Model",
21
+ "Max Mode",
22
+ "Input (w/ Cache Write)",
23
+ "Input (w/o Cache Write)",
24
+ "Cache Read",
25
+ "Output Tokens",
26
+ "Total Tokens",
27
+ "Cost",
28
+ )
29
+
30
+ # Labels that mean the invoice for this row is zero. Anything else must be a number.
31
+ ZERO_BILLED = {"", "included", "free"}
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class UsageEvent:
36
+ row: int
37
+ at: datetime
38
+ agent_id: str | None
39
+ automation_id: str | None
40
+ kind: str
41
+ model: str
42
+ max_mode: bool
43
+ cache_write: int
44
+ input_tokens: int
45
+ cache_read: int
46
+ output_tokens: int
47
+ total_tokens: int
48
+ billed_micro: int
49
+ cost_label: str
50
+ list_micro: int
51
+ non_fast_list_micro: int
52
+ fast: bool
53
+ priced_as: str
54
+ used_default: bool
55
+
56
+ @property
57
+ def on_demand(self) -> bool:
58
+ return self.kind.strip().lower() == "on-demand" or self.billed_micro > 0
59
+
60
+
61
+ def load_usage(
62
+ path: Path,
63
+ card: PriceCard,
64
+ *,
65
+ team_token_rate: bool = False,
66
+ ) -> list[UsageEvent]:
67
+ with path.open(newline="", encoding="utf-8-sig") as handle:
68
+ reader = csv.DictReader(handle)
69
+ if reader.fieldnames is None:
70
+ raise ValueError(f"{path} has no header row")
71
+ missing = [name for name in REQUIRED if name not in reader.fieldnames]
72
+ if missing:
73
+ raise ValueError(f"{path} is missing columns: {', '.join(missing)}")
74
+ events: list[UsageEvent] = []
75
+ for index, raw in enumerate(reader, start=2):
76
+ events.append(_row(index, raw, card, team_token_rate))
77
+ events.sort(key=lambda event: (event.at, event.row))
78
+ return events
79
+
80
+
81
+ def _row(index: int, raw: dict[str, str | None], card: PriceCard, team_token_rate: bool) -> UsageEvent:
82
+ def cell(name: str) -> str:
83
+ value = raw.get(name)
84
+ return "" if value is None else value.strip()
85
+
86
+ cache_write = _int_tokens(cell("Input (w/ Cache Write)"))
87
+ input_tokens = _int_tokens(cell("Input (w/o Cache Write)"))
88
+ cache_read = _int_tokens(cell("Cache Read"))
89
+ output_tokens = _int_tokens(cell("Output Tokens"))
90
+ stated = cell("Total Tokens")
91
+ if stated:
92
+ total_tokens = _int_tokens(stated)
93
+ else:
94
+ total_tokens = cache_write + input_tokens + cache_read + output_tokens
95
+ model = cell("Model") or "unknown"
96
+ max_mode = cell("Max Mode").lower() in {"yes", "true", "1"}
97
+ priced = price_tokens(
98
+ card,
99
+ model,
100
+ cache_write=cache_write,
101
+ input_tokens=input_tokens,
102
+ cache_read=cache_read,
103
+ output_tokens=output_tokens,
104
+ max_mode=max_mode,
105
+ team_token_rate=team_token_rate,
106
+ )
107
+ agent = cell("Cloud Agent ID") or None
108
+ automation = cell("Automation ID") or None
109
+ return UsageEvent(
110
+ row=index,
111
+ at=parse_time(cell("Date")),
112
+ agent_id=agent,
113
+ automation_id=automation,
114
+ kind=cell("Kind") or "Unknown",
115
+ model=model,
116
+ max_mode=max_mode,
117
+ cache_write=cache_write,
118
+ input_tokens=input_tokens,
119
+ cache_read=cache_read,
120
+ output_tokens=output_tokens,
121
+ total_tokens=total_tokens,
122
+ billed_micro=_billed(cell("Cost")),
123
+ cost_label=cell("Cost"),
124
+ list_micro=priced.list_micro,
125
+ non_fast_list_micro=priced.non_fast_list_micro,
126
+ fast=priced.fast,
127
+ priced_as=priced.priced_as,
128
+ used_default=priced.used_default,
129
+ )
130
+
131
+
132
+ def _int_tokens(value: str) -> int:
133
+ if not value:
134
+ return 0
135
+ try:
136
+ number = Decimal(value)
137
+ except InvalidOperation as exc:
138
+ raise ValueError(f"not a token count: {value!r}") from exc
139
+ if number != number.to_integral_value():
140
+ raise ValueError(f"token count is not an integer: {value!r}")
141
+ return int(number)
142
+
143
+
144
+ def _billed(value: str) -> int:
145
+ if value.strip().lower() in ZERO_BILLED:
146
+ return 0
147
+ try:
148
+ return usd_to_micro(Decimal(value))
149
+ except InvalidOperation as exc:
150
+ raise ValueError(f"cost {value!r} is neither Included, Free, nor a dollar amount") from exc