clockwork-cli 0.2.0__py3-none-any.whl → 0.3.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.
clockwork_cli/__init__.py CHANGED
@@ -26,6 +26,7 @@ Options:
26
26
  form like 7d (7 days ago) or 2w (2 weeks ago)
27
27
  --detail <level> export granularity: raw | sessions | daily (default raw)
28
28
  --anonymize export: replace project paths with a hash id + generic name
29
+ --tokens Also report token usage and a per-model breakdown
29
30
 
30
31
  Examples:
31
32
  clockwork claude ~/code/myproject
@@ -37,6 +38,9 @@ Examples:
37
38
  clockwork both today
38
39
  clockwork claude export > clockwork.json
39
40
  clockwork codex export --detail sessions --anonymize > share.json
41
+ clockwork both today --tokens
42
+ clockwork claude all --tokens --since 7d
43
+ clockwork both export --tokens > clockwork.json
40
44
  clockwork claude all --since 7d
41
45
  clockwork claude ~/code/myproject --since 2026-07-01 --until 2026-07-05
42
46
  clockwork claude list
@@ -44,6 +48,20 @@ Examples:
44
48
  Data sources:
45
49
  claude → ~/.claude/projects/<encoded-path>/*.jsonl
46
50
  codex → $CODEX_HOME/sessions/**/rollout-*.jsonl (default ~/.codex/sessions)
51
+
52
+ Token usage (--tokens):
53
+ Both tools log per-response usage, counted differently, so clockwork
54
+ normalizes them before summing:
55
+
56
+ claude → `assistant` records carry message.model + message.usage. One API
57
+ response spans several lines (thinking, text, each tool_use), each
58
+ repeating the same usage block, so responses are deduplicated on
59
+ message id. Cache reads/writes sit outside input_tokens.
60
+ codex → `event_msg -> token_count` records carry a cumulative
61
+ total_token_usage; per-turn cost is read as the rise in that counter
62
+ because last_token_usage is re-emitted on aborted turns. The model
63
+ comes from the preceding `turn_context`, and cached_input_tokens is
64
+ subtracted out of input_tokens to match Claude's split.
47
65
  """
48
66
 
49
67
  import sys
@@ -55,7 +73,7 @@ import hashlib
55
73
  from datetime import datetime, timedelta, timezone
56
74
  from collections import defaultdict
57
75
 
58
- __version__ = "0.2.0"
76
+ __version__ = "0.3.0"
59
77
 
60
78
 
61
79
  def _resolve_claude_dir():
@@ -129,6 +147,92 @@ def _add_session_to_daily(daily, start, end):
129
147
  cursor = seg_end
130
148
 
131
149
 
150
+ # --------------------------------------------------------------------------- #
151
+ # Token accounting
152
+ # --------------------------------------------------------------------------- #
153
+ #
154
+ # Both providers log per-response token usage, but they count it differently,
155
+ # so every backend normalizes into one record shape before anything is summed:
156
+ #
157
+ # input fresh (uncached) input tokens
158
+ # output output tokens, thinking/reasoning included
159
+ # cache_read input served from cache
160
+ # cache_write input written to cache (Claude only; Codex never reports it)
161
+ # reasoning thinking tokens, a SUBSET of output (Codex only; Claude folds
162
+ # thinking into output without breaking it out)
163
+ #
164
+ # Claude reports cache reads and writes outside `input_tokens`; Codex reports
165
+ # `cached_input_tokens` *inside* `input_tokens`, so the Codex reader subtracts
166
+ # it back out. After that, total = input + output + cache_read + cache_write
167
+ # holds for both, and `reasoning` is deliberately left out of it to avoid
168
+ # double counting the part of output it already covers.
169
+
170
+ TOKEN_FIELDS = ("input", "output", "cache_read", "cache_write", "reasoning")
171
+
172
+
173
+ def _new_token_rec():
174
+ rec = {"responses": 0}
175
+ rec.update({f: 0 for f in TOKEN_FIELDS})
176
+ return rec
177
+
178
+
179
+ def _accumulate_tokens(rec, event):
180
+ rec["responses"] += 1
181
+ for f in TOKEN_FIELDS:
182
+ rec[f] += event[f]
183
+
184
+
185
+ def _sealed(rec):
186
+ """Copy a running record with its derived `total` filled in."""
187
+ out = dict(rec)
188
+ out["total"] = rec["input"] + rec["output"] + rec["cache_read"] + rec["cache_write"]
189
+ return out
190
+
191
+
192
+ def summarize_tokens(events):
193
+ """Aggregate token events into overall totals plus a per-model breakdown."""
194
+ overall = _new_token_rec()
195
+ per_model = defaultdict(_new_token_rec)
196
+ for event in events:
197
+ _accumulate_tokens(overall, event)
198
+ _accumulate_tokens(per_model[event["model"] or "unknown"], event)
199
+ summary = _sealed(overall)
200
+ models = []
201
+ for model, rec in per_model.items():
202
+ entry = {"model": model}
203
+ entry.update(_sealed(rec))
204
+ models.append(entry)
205
+ # Biggest consumer first, name as the tie-break so output is deterministic.
206
+ models.sort(key=lambda m: (-m["total"], m["model"]))
207
+ summary["by_model"] = models
208
+ return summary
209
+
210
+
211
+ def tokens_by_day(events):
212
+ """Bucket token events into per-day (UTC) sealed records."""
213
+ daily = defaultdict(_new_token_rec)
214
+ for event in events:
215
+ _accumulate_tokens(daily[event["ts"].date()], event)
216
+ return {day: _sealed(rec) for day, rec in daily.items()}
217
+
218
+
219
+ def _filter_events(events, since, until):
220
+ if since is None and until is None:
221
+ return events
222
+ return [
223
+ e for e in events
224
+ if (since is None or e["ts"] >= since) and (until is None or e["ts"] <= until)
225
+ ]
226
+
227
+
228
+ def fmt_tokens(n):
229
+ """Compact token count for table cells (1_234_567 -> '1.2M')."""
230
+ for cutoff, suffix in ((1e9, "B"), (1e6, "M"), (1e3, "k")):
231
+ if n >= cutoff:
232
+ return f"{n / cutoff:.1f}{suffix}"
233
+ return str(int(n))
234
+
235
+
132
236
  def fmt_duration(minutes):
133
237
  h = int(minutes) // 60
134
238
  m = int(minutes) % 60
@@ -266,11 +370,50 @@ def _claude_resolve_files(project_path):
266
370
  return None, []
267
371
 
268
372
 
269
- def _claude_timestamps_from_files(files):
270
- """Parse user/human turn timestamps from Claude .jsonl files."""
373
+ def _claude_token_event(record, dt, seen):
374
+ """Normalize one Claude assistant record into a token event, or None.
375
+
376
+ Claude Code writes one line per content block — thinking, text, and each
377
+ tool_use — and every line of a single API response repeats the *identical*
378
+ usage object. Counting per line inflates totals roughly 2.6x, so responses
379
+ are deduplicated on the message id (falling back to the request id).
380
+ """
381
+ message = record.get("message") or {}
382
+ usage = message.get("usage")
383
+ model = message.get("model")
384
+ # `<synthetic>` marks locally generated messages (errors, interrupts);
385
+ # they carry a zero usage block and never hit the API.
386
+ if not usage or not model or model == "<synthetic>" or dt is None:
387
+ return None
388
+ key = message.get("id") or record.get("requestId")
389
+ if key is not None:
390
+ if key in seen:
391
+ return None
392
+ seen.add(key)
393
+ return {
394
+ "ts": dt,
395
+ "model": model,
396
+ "input": usage.get("input_tokens") or 0,
397
+ "output": usage.get("output_tokens") or 0,
398
+ "cache_read": usage.get("cache_read_input_tokens") or 0,
399
+ "cache_write": usage.get("cache_creation_input_tokens") or 0,
400
+ "reasoning": 0, # Claude folds thinking into output_tokens
401
+ }
402
+
403
+
404
+ def _claude_scan_files(files):
405
+ """Return (prompt timestamps, token events) from Claude .jsonl files.
406
+
407
+ Both come out of a single pass: the files are already read end to end for
408
+ the timestamps, so picking up usage costs nothing extra. The dedup set is
409
+ shared across the whole file list so a response replayed into a resumed
410
+ session's log is still only counted once.
411
+ """
271
412
  timestamps = []
413
+ events = []
414
+ seen = set()
272
415
  for f in sorted(files):
273
- with open(f) as fh:
416
+ with open(f, encoding="utf-8") as fh:
274
417
  for line in fh:
275
418
  line = line.strip()
276
419
  if not line:
@@ -283,7 +426,16 @@ def _claude_timestamps_from_files(files):
283
426
  dt = _parse_ts(d.get("timestamp"))
284
427
  if dt and role in ("human", "user"):
285
428
  timestamps.append(dt)
286
- return sorted(timestamps)
429
+ elif role == "assistant":
430
+ event = _claude_token_event(d, dt, seen)
431
+ if event:
432
+ events.append(event)
433
+ return sorted(timestamps), events
434
+
435
+
436
+ def _claude_timestamps_from_files(files):
437
+ """Parse user/human turn timestamps from Claude .jsonl files."""
438
+ return _claude_scan_files(files)[0]
287
439
 
288
440
 
289
441
  def _claude_folder_to_pretty(folder):
@@ -293,23 +445,33 @@ def _claude_folder_to_pretty(folder):
293
445
  return "/" + folder.lstrip("-").replace("-", "/")
294
446
 
295
447
 
296
- def claude_single(project_path):
448
+ def claude_scan_single(project_path):
297
449
  folder, files = _claude_resolve_files(project_path)
298
450
  if not files:
299
- return None, 0, []
300
- return folder, len(files), _claude_timestamps_from_files(files)
451
+ return None, 0, [], []
452
+ ts, events = _claude_scan_files(files)
453
+ return folder, len(files), ts, events
301
454
 
302
455
 
303
- def claude_all():
456
+ def claude_single(project_path):
457
+ folder, count, ts, _ = claude_scan_single(project_path)
458
+ return folder, count, ts
459
+
460
+
461
+ def claude_scan():
304
462
  result = []
305
463
  for folder in _claude_list_folders():
306
464
  files = glob.glob(os.path.join(CLAUDE_DIR, folder, "*.jsonl"))
307
- ts = _claude_timestamps_from_files(files)
465
+ ts, events = _claude_scan_files(files)
308
466
  if ts:
309
- result.append((_claude_folder_to_pretty(folder), ts))
467
+ result.append((_claude_folder_to_pretty(folder), ts, events))
310
468
  return result
311
469
 
312
470
 
471
+ def claude_all():
472
+ return [(label, ts) for label, ts, _ in claude_scan()]
473
+
474
+
313
475
  def _claude_list_folders():
314
476
  return sorted(os.listdir(CLAUDE_DIR)) if os.path.exists(CLAUDE_DIR) else []
315
477
 
@@ -328,18 +490,66 @@ def _codex_files():
328
490
  return glob.glob(pattern, recursive=True)
329
491
 
330
492
 
331
- def _codex_parse_file(path):
332
- """Return (cwd, [timestamps]) for one rollout file.
493
+ _CODEX_TOKEN_KEYS = ("input_tokens", "cached_input_tokens",
494
+ "output_tokens", "reasoning_output_tokens")
495
+
496
+
497
+ def _codex_token_event(record, payload, running, model):
498
+ """Normalize one Codex `token_count` record into a token event, or None.
499
+
500
+ Codex reports both a per-turn `last_token_usage` and a cumulative
501
+ `total_token_usage`, and the per-turn number cannot be trusted on its own:
502
+ aborted and no-op turns re-emit a stale `last_token_usage` that the
503
+ cumulative counter never absorbs, so summing it overstates usage (by up to
504
+ 20% in a single session). The turn's real cost is the rise in the
505
+ cumulative counter, which is monotonic within a rollout and restarts at
506
+ zero in forked/resumed sessions — so no cross-file double counting either.
507
+ """
508
+ info = payload.get("info") or {}
509
+ total = info.get("total_token_usage") or {}
510
+ delta = {}
511
+ for k in _CODEX_TOKEN_KEYS:
512
+ value = total.get(k) or 0
513
+ delta[k] = max(0, value - running[k])
514
+ running[k] = value
515
+ if not any(delta.values()):
516
+ return None
517
+ dt = _parse_ts(record.get("timestamp") or payload.get("timestamp"))
518
+ if dt is None:
519
+ return None
520
+ cached = delta["cached_input_tokens"]
521
+ return {
522
+ "ts": dt,
523
+ "model": model,
524
+ # Codex counts cache reads inside input_tokens; split them back out so
525
+ # the number means the same thing it does on the Claude side.
526
+ "input": max(0, delta["input_tokens"] - cached),
527
+ "output": delta["output_tokens"],
528
+ "cache_read": cached,
529
+ "cache_write": 0, # not reported by Codex
530
+ "reasoning": delta["reasoning_output_tokens"],
531
+ }
532
+
533
+
534
+ def _codex_scan_file(path):
535
+ """Return (cwd, [timestamps], [token events]) for one rollout file.
333
536
 
334
537
  Uses the canonical `event_msg -> user_message` prompt records; only falls
335
538
  back to `response_item` user-role messages for files that contain no
336
539
  canonical prompt events, to avoid double counting the same input.
540
+
541
+ The model is not in `session_meta` (which only names the provider) — it
542
+ rides on `turn_context`, so each turn is attributed to the most recent one.
337
543
  """
338
544
  cwd = None
339
545
  canonical = []
340
546
  fallback = []
547
+ events = []
548
+ model = None
549
+ first_model = None
550
+ running = {k: 0 for k in _CODEX_TOKEN_KEYS}
341
551
  try:
342
- with open(path) as fh:
552
+ with open(path, encoding="utf-8") as fh:
343
553
  for line in fh:
344
554
  line = line.strip()
345
555
  if not line:
@@ -352,10 +562,18 @@ def _codex_parse_file(path):
352
562
  payload = d.get("payload") or {}
353
563
  if t == "session_meta":
354
564
  cwd = payload.get("cwd")
565
+ elif t == "turn_context":
566
+ model = payload.get("model") or model
567
+ if first_model is None:
568
+ first_model = model
355
569
  elif t == "event_msg" and payload.get("type") == "user_message":
356
570
  dt = _parse_ts(d.get("timestamp") or payload.get("timestamp"))
357
571
  if dt:
358
572
  canonical.append(dt)
573
+ elif t == "event_msg" and payload.get("type") == "token_count":
574
+ event = _codex_token_event(d, payload, running, model)
575
+ if event:
576
+ events.append(event)
359
577
  elif (t == "response_item"
360
578
  and payload.get("type") == "message"
361
579
  and payload.get("role") == "user"):
@@ -363,31 +581,56 @@ def _codex_parse_file(path):
363
581
  if dt:
364
582
  fallback.append(dt)
365
583
  except OSError:
366
- return None, []
367
- return cwd, sorted(canonical if canonical else fallback)
584
+ return None, [], []
585
+ # A few turns are logged before the first `turn_context`; credit them to
586
+ # the model the session went on to use rather than losing them to unknown.
587
+ if first_model:
588
+ for event in events:
589
+ if event["model"] is None:
590
+ event["model"] = first_model
591
+ return cwd, sorted(canonical if canonical else fallback), events
368
592
 
369
593
 
370
- def codex_single(project_path):
594
+ def _codex_parse_file(path):
595
+ """Return (cwd, [timestamps]) for one rollout file."""
596
+ cwd, timestamps, _ = _codex_scan_file(path)
597
+ return cwd, timestamps
598
+
599
+
600
+ def codex_scan_single(project_path):
371
601
  abs_path = os.path.abspath(os.path.expanduser(project_path))
372
602
  matched = 0
373
603
  timestamps = []
604
+ events = []
374
605
  for f in _codex_files():
375
- cwd, file_ts = _codex_parse_file(f)
606
+ cwd, file_ts, file_events = _codex_scan_file(f)
376
607
  if cwd == abs_path:
377
608
  matched += 1
378
609
  timestamps.extend(file_ts)
610
+ events.extend(file_events)
379
611
  if not matched:
380
- return None, 0, []
381
- return abs_path, matched, sorted(timestamps)
612
+ return None, 0, [], []
613
+ return abs_path, matched, sorted(timestamps), events
382
614
 
383
615
 
384
- def codex_all():
385
- groups = defaultdict(list)
616
+ def codex_single(project_path):
617
+ label, count, ts, _ = codex_scan_single(project_path)
618
+ return label, count, ts
619
+
620
+
621
+ def codex_scan():
622
+ ts_groups = defaultdict(list)
623
+ event_groups = defaultdict(list)
386
624
  for f in _codex_files():
387
- cwd, file_ts = _codex_parse_file(f)
625
+ cwd, file_ts, file_events = _codex_scan_file(f)
388
626
  if cwd and file_ts:
389
- groups[cwd].extend(file_ts)
390
- return [(cwd, sorted(ts)) for cwd, ts in groups.items()]
627
+ ts_groups[cwd].extend(file_ts)
628
+ event_groups[cwd].extend(file_events)
629
+ return [(cwd, sorted(ts), event_groups[cwd]) for cwd, ts in ts_groups.items()]
630
+
631
+
632
+ def codex_all():
633
+ return [(label, ts) for label, ts, _ in codex_scan()]
391
634
 
392
635
 
393
636
  def _codex_cwd_only(path):
@@ -397,7 +640,7 @@ def _codex_cwd_only(path):
397
640
  the `session_meta` record carrying `cwd` is at the top of the rollout.
398
641
  """
399
642
  try:
400
- with open(path) as fh:
643
+ with open(path, encoding="utf-8") as fh:
401
644
  for line in fh:
402
645
  line = line.strip()
403
646
  if not line:
@@ -435,13 +678,34 @@ def _merge_projects(*project_lists):
435
678
  return [(label, sorted(ts)) for label, ts in groups.items()]
436
679
 
437
680
 
438
- def both_single(project_path):
439
- _, c_count, c_ts = claude_single(project_path)
440
- _, x_count, x_ts = codex_single(project_path)
681
+ def _merge_scans(*scans):
682
+ """Merge [(label, timestamps, events)] lists, combining same-label projects."""
683
+ ts_groups = defaultdict(list)
684
+ event_groups = defaultdict(list)
685
+ for scan in scans:
686
+ for label, ts, events in scan:
687
+ ts_groups[label].extend(ts)
688
+ event_groups[label].extend(events)
689
+ return [(label, sorted(ts), event_groups[label])
690
+ for label, ts in ts_groups.items()]
691
+
692
+
693
+ def both_scan_single(project_path):
694
+ _, c_count, c_ts, c_events = claude_scan_single(project_path)
695
+ _, x_count, x_ts, x_events = codex_scan_single(project_path)
441
696
  count = c_count + x_count
442
697
  if count == 0:
443
- return None, 0, []
444
- return project_path, count, sorted(c_ts + x_ts)
698
+ return None, 0, [], []
699
+ return project_path, count, sorted(c_ts + x_ts), c_events + x_events
700
+
701
+
702
+ def both_single(project_path):
703
+ label, count, ts, _ = both_scan_single(project_path)
704
+ return label, count, ts
705
+
706
+
707
+ def both_scan():
708
+ return _merge_scans(claude_scan(), codex_scan())
445
709
 
446
710
 
447
711
  def both_all():
@@ -458,22 +722,31 @@ def both_list():
458
722
  # Provider dispatch
459
723
  # --------------------------------------------------------------------------- #
460
724
 
725
+ # `scan`/`scan_single` are the token-aware backends: same work as `all`/`single`
726
+ # plus the usage records picked up in the same pass. `all`/`single` remain the
727
+ # timing-only views, and are what the plain (no --tokens) commands read.
461
728
  PROVIDERS = {
462
729
  "claude": {
463
730
  "single": claude_single,
731
+ "scan_single": claude_scan_single,
464
732
  "all": claude_all,
733
+ "scan": claude_scan,
465
734
  "list": claude_list,
466
735
  "location": "~/.claude/projects/",
467
736
  },
468
737
  "codex": {
469
738
  "single": codex_single,
739
+ "scan_single": codex_scan_single,
470
740
  "all": codex_all,
741
+ "scan": codex_scan,
471
742
  "list": codex_list,
472
743
  "location": "$CODEX_HOME/sessions/",
473
744
  },
474
745
  "both": {
475
746
  "single": both_single,
747
+ "scan_single": both_scan_single,
476
748
  "all": both_all,
749
+ "scan": both_scan,
477
750
  "list": both_list,
478
751
  "location": "claude + codex",
479
752
  },
@@ -498,8 +771,72 @@ def _export_providers(provider):
498
771
  # Output modes
499
772
  # --------------------------------------------------------------------------- #
500
773
 
501
- def analyze_single(provider, project_path, idle_threshold, since, until, as_json):
502
- label, count, timestamps = PROVIDERS[provider]["single"](project_path)
774
+ MODEL_TABLE_WIDTH = 80
775
+
776
+
777
+ def _day_keys(daily, token_days):
778
+ """Every day either bucket knows about, in order.
779
+
780
+ A response can complete after midnight, past the last prompt that defines
781
+ the session's end — so a day can carry tokens without carrying active
782
+ minutes. Taking the union keeps the per-day rows summing to the totals.
783
+ """
784
+ return sorted(set(daily) | set(token_days))
785
+
786
+
787
+ def _day_entry(day, daily, prompts_per_day, token_days, show_tokens):
788
+ """One JSON day bucket, with tokens attached when they were collected."""
789
+ entry = {"date": str(day),
790
+ "minutes": round(daily[day], 2),
791
+ "prompts": prompts_per_day[day]}
792
+ if show_tokens:
793
+ entry["tokens"] = token_days.get(day) or _sealed(_new_token_rec())
794
+ return entry
795
+
796
+
797
+ def _print_token_lines(summary):
798
+ """The three-line token block used under a run's summary header."""
799
+ print(f" Tokens : {fmt_tokens(summary['total'])} across "
800
+ f"{summary['responses']:,} responses")
801
+ print(f" In/Out : {fmt_tokens(summary['input'])} in · "
802
+ f"{fmt_tokens(summary['output'])} out")
803
+ print(f" Cache : {fmt_tokens(summary['cache_read'])} read · "
804
+ f"{fmt_tokens(summary['cache_write'])} write")
805
+ if summary["reasoning"]:
806
+ print(f" Thinking: {fmt_tokens(summary['reasoning'])} "
807
+ f"(Codex only; already counted inside output)")
808
+
809
+
810
+ def _print_model_table(summary):
811
+ """Per-model token breakdown, biggest consumer first."""
812
+ if not summary["by_model"]:
813
+ return
814
+ print(f"\n {'MODEL':<20} {'RESP':>7} {'INPUT':>9} {'OUTPUT':>9} "
815
+ f"{'CACHE R':>9} {'CACHE W':>9} {'TOTAL':>9}")
816
+ print("-" * MODEL_TABLE_WIDTH)
817
+ for m in summary["by_model"]:
818
+ name = m["model"]
819
+ if len(name) > 19:
820
+ name = "…" + name[-18:]
821
+ print(f" {name:<20} {m['responses']:>7,} {fmt_tokens(m['input']):>9} "
822
+ f"{fmt_tokens(m['output']):>9} {fmt_tokens(m['cache_read']):>9} "
823
+ f"{fmt_tokens(m['cache_write']):>9} {fmt_tokens(m['total']):>9}")
824
+ print("-" * MODEL_TABLE_WIDTH)
825
+ print(f" {'TOTAL':<20} {summary['responses']:>7,} "
826
+ f"{fmt_tokens(summary['input']):>9} {fmt_tokens(summary['output']):>9} "
827
+ f"{fmt_tokens(summary['cache_read']):>9} "
828
+ f"{fmt_tokens(summary['cache_write']):>9} "
829
+ f"{fmt_tokens(summary['total']):>9}")
830
+
831
+
832
+ def analyze_single(provider, project_path, idle_threshold, since, until, as_json,
833
+ show_tokens=False):
834
+ if show_tokens:
835
+ label, count, timestamps, events = PROVIDERS[provider]["scan_single"](project_path)
836
+ events = _filter_events(events, since, until)
837
+ else:
838
+ label, count, timestamps = PROVIDERS[provider]["single"](project_path)
839
+ events = []
503
840
  timestamps = _filter_timestamps(timestamps, since, until)
504
841
 
505
842
  if count == 0:
@@ -539,8 +876,11 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
539
876
  for ts in timestamps:
540
877
  prompts_per_day[ts.date()] += 1
541
878
 
879
+ token_summary = summarize_tokens(events) if show_tokens else None
880
+ token_days = tokens_by_day(events) if show_tokens else {}
881
+
542
882
  if as_json:
543
- _print_json({
883
+ payload = {
544
884
  "provider": provider,
545
885
  "project": project_path,
546
886
  "label": label,
@@ -556,12 +896,13 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
556
896
  "active_days": len(daily),
557
897
  "total_minutes": round(total_minutes, 2),
558
898
  "days": [
559
- {"date": str(day),
560
- "minutes": round(daily[day], 2),
561
- "prompts": prompts_per_day[day]}
562
- for day in sorted(daily)
899
+ _day_entry(day, daily, prompts_per_day, token_days, show_tokens)
900
+ for day in _day_keys(daily, token_days)
563
901
  ],
564
- })
902
+ }
903
+ if show_tokens:
904
+ payload["tokens"] = token_summary
905
+ _print_json(payload)
565
906
  return
566
907
 
567
908
  print(f"✅ Found {count} session file(s) for: {label}\n")
@@ -577,35 +918,52 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
577
918
  print(f" Sessions: {len(sessions)} (idle threshold: {idle_threshold} min)")
578
919
  print(f" Active : {len(daily)} days")
579
920
  print(f" Total : {fmt_duration(total_minutes)}")
921
+ if show_tokens:
922
+ _print_token_lines(token_summary)
580
923
  print("=" * 52)
581
924
 
582
- print(f"\n{'DATE':<14} {'ACTIVE TIME':<14} {'PROMPTS':<10} BAR")
583
- print("-" * 52)
925
+ token_col = f" {'TOKENS':>9}" if show_tokens else ""
926
+ print(f"\n{'DATE':<14} {'ACTIVE TIME':<14} {'PROMPTS':<10}{token_col} BAR")
927
+ print("-" * (52 + len(token_col)))
584
928
 
585
929
  max_mins = max(daily.values())
586
- for day in sorted(daily):
930
+ for day in _day_keys(daily, token_days):
587
931
  mins = daily[day]
588
932
  bar_len = int((mins / max_mins) * 20) if max_mins else 0
589
933
  bar = "█" * bar_len
590
- print(f" {str(day):<12} {fmt_duration(mins):<14} {prompts_per_day[day]:<10} {bar}")
591
-
592
- print("-" * 52)
593
- print(f" {'TOTAL':<12} {fmt_duration(total_minutes):<14} {len(timestamps)}")
934
+ cell = (f" {fmt_tokens(token_days.get(day, {}).get('total', 0)):>9}"
935
+ if show_tokens else "")
936
+ print(f" {str(day):<12} {fmt_duration(mins):<14} "
937
+ f"{prompts_per_day[day]:<10}{cell} {bar}")
938
+
939
+ print("-" * (52 + len(token_col)))
940
+ total_cell = f" {fmt_tokens(token_summary['total']):>9}" if show_tokens else ""
941
+ # rstrip so the plain (no --tokens) row keeps its original width.
942
+ print(f" {'TOTAL':<12} {fmt_duration(total_minutes):<14} "
943
+ f"{len(timestamps):<10}{total_cell}".rstrip())
944
+ if show_tokens:
945
+ _print_model_table(token_summary)
594
946
  print()
595
947
 
596
948
 
597
- def analyze_all(provider, idle_threshold, since, until, as_json):
598
- projects = PROVIDERS[provider]["all"]()
949
+ def analyze_all(provider, idle_threshold, since, until, as_json,
950
+ show_tokens=False):
951
+ if show_tokens:
952
+ projects = PROVIDERS[provider]["scan"]()
953
+ else:
954
+ projects = [(label, ts, []) for label, ts in PROVIDERS[provider]["all"]()]
599
955
 
600
956
  rows = []
957
+ all_events = []
601
958
  grand_minutes = 0.0
602
959
  grand_prompts = 0
603
960
  grand_sessions = 0
604
961
 
605
- for label, timestamps in projects:
962
+ for label, timestamps, events in projects:
606
963
  timestamps = _filter_timestamps(timestamps, since, until)
607
964
  if not timestamps:
608
965
  continue
966
+ events = _filter_events(events, since, until)
609
967
  daily, sessions = compute_active_hours(timestamps, idle_threshold)
610
968
  total_minutes = sum(daily.values())
611
969
  rows.append({
@@ -613,7 +971,9 @@ def analyze_all(provider, idle_threshold, since, until, as_json):
613
971
  "minutes": total_minutes,
614
972
  "prompts": len(timestamps),
615
973
  "sessions": len(sessions),
974
+ "tokens": summarize_tokens(events) if show_tokens else None,
616
975
  })
976
+ all_events.extend(events)
617
977
  grand_minutes += total_minutes
618
978
  grand_prompts += len(timestamps)
619
979
  grand_sessions += len(sessions)
@@ -630,53 +990,86 @@ def analyze_all(provider, idle_threshold, since, until, as_json):
630
990
  sys.exit(1)
631
991
 
632
992
  rows.sort(key=lambda r: r["minutes"], reverse=True)
993
+ grand_tokens = summarize_tokens(all_events) if show_tokens else None
633
994
 
634
995
  if as_json:
996
+ projects_json = []
997
+ for r in rows:
998
+ entry = {"project": r["label"],
999
+ "minutes": round(r["minutes"], 2),
1000
+ "prompts": r["prompts"],
1001
+ "sessions": r["sessions"]}
1002
+ if show_tokens:
1003
+ entry["tokens"] = r["tokens"]
1004
+ projects_json.append(entry)
1005
+ totals = {
1006
+ "projects": len(rows),
1007
+ "minutes": round(grand_minutes, 2),
1008
+ "prompts": grand_prompts,
1009
+ "sessions": grand_sessions,
1010
+ }
1011
+ if show_tokens:
1012
+ totals["tokens"] = grand_tokens
635
1013
  _print_json({
636
1014
  "provider": provider,
637
1015
  "idle_threshold_min": idle_threshold,
638
1016
  "since": _iso(since),
639
1017
  "until": _iso(until),
640
- "projects": [
641
- {"project": r["label"],
642
- "minutes": round(r["minutes"], 2),
643
- "prompts": r["prompts"],
644
- "sessions": r["sessions"]}
645
- for r in rows
646
- ],
647
- "totals": {
648
- "projects": len(rows),
649
- "minutes": round(grand_minutes, 2),
650
- "prompts": grand_prompts,
651
- "sessions": grand_sessions,
652
- },
1018
+ "projects": projects_json,
1019
+ "totals": totals,
653
1020
  })
654
1021
  return
655
1022
 
656
1023
  max_mins = max(r["minutes"] for r in rows)
1024
+ width = 88 if show_tokens else 78
657
1025
 
658
- print("=" * 78)
1026
+ print("=" * width)
659
1027
  print(f" CLOCKWORK — ALL {_provider_label(provider)} PROJECTS (idle threshold: {idle_threshold} min)")
660
- print("=" * 78)
1028
+ print("=" * width)
661
1029
  print(f" Projects: {len(rows)} with activity")
662
1030
  print(f" Prompts : {grand_prompts} total")
663
1031
  print(f" Sessions: {grand_sessions} total")
664
1032
  print(f" Total : {fmt_duration(grand_minutes)}")
665
- print("=" * 78)
1033
+ if show_tokens:
1034
+ _print_token_lines(grand_tokens)
1035
+ print("=" * width)
666
1036
  print()
667
- print(f" {'PROJECT':<40} {'TIME':>9} {'PROMPTS':>8} {'SESS':>5} BAR")
668
- print("-" * 78)
1037
+
1038
+ if show_tokens:
1039
+ # Token columns replace the bar — the numbers carry the comparison.
1040
+ print(f" {'PROJECT':<30} {'TIME':>9} {'PROMPTS':>8} {'IN':>8} "
1041
+ f"{'OUT':>8} {'CACHE':>9} {'TOTAL':>9}")
1042
+ else:
1043
+ print(f" {'PROJECT':<40} {'TIME':>9} {'PROMPTS':>8} {'SESS':>5} BAR")
1044
+ print("-" * width)
669
1045
 
670
1046
  for r in rows:
671
1047
  name = r["label"]
672
- if len(name) > 39:
673
- name = "…" + name[-38:]
674
- bar_len = int((r["minutes"] / max_mins) * 12) if max_mins else 0
675
- bar = "█" * bar_len
676
- print(f" {name:<40} {fmt_duration(r['minutes']):>9} {r['prompts']:>8} {r['sessions']:>5} {bar}")
1048
+ if show_tokens:
1049
+ if len(name) > 29:
1050
+ name = "…" + name[-28:]
1051
+ t = r["tokens"]
1052
+ print(f" {name:<30} {fmt_duration(r['minutes']):>9} {r['prompts']:>8} "
1053
+ f"{fmt_tokens(t['input']):>8} {fmt_tokens(t['output']):>8} "
1054
+ f"{fmt_tokens(t['cache_read'] + t['cache_write']):>9} "
1055
+ f"{fmt_tokens(t['total']):>9}")
1056
+ else:
1057
+ if len(name) > 39:
1058
+ name = "…" + name[-38:]
1059
+ bar_len = int((r["minutes"] / max_mins) * 12) if max_mins else 0
1060
+ bar = "█" * bar_len
1061
+ print(f" {name:<40} {fmt_duration(r['minutes']):>9} {r['prompts']:>8} {r['sessions']:>5} {bar}")
677
1062
 
678
- print("-" * 78)
679
- print(f" {'TOTAL':<40} {fmt_duration(grand_minutes):>9} {grand_prompts:>8} {grand_sessions:>5}")
1063
+ print("-" * width)
1064
+ if show_tokens:
1065
+ print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} {grand_prompts:>8} "
1066
+ f"{fmt_tokens(grand_tokens['input']):>8} "
1067
+ f"{fmt_tokens(grand_tokens['output']):>8} "
1068
+ f"{fmt_tokens(grand_tokens['cache_read'] + grand_tokens['cache_write']):>9} "
1069
+ f"{fmt_tokens(grand_tokens['total']):>9}")
1070
+ _print_model_table(grand_tokens)
1071
+ else:
1072
+ print(f" {'TOTAL':<40} {fmt_duration(grand_minutes):>9} {grand_prompts:>8} {grand_sessions:>5}")
680
1073
  print()
681
1074
 
682
1075
 
@@ -694,28 +1087,35 @@ def _period_window(period):
694
1087
  return start_today - timedelta(days=6), now, "THIS WEEK (last 7 days)"
695
1088
 
696
1089
 
697
- def analyze_summary(provider, period, idle_threshold, as_json):
1090
+ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False):
698
1091
  since, until, title = _period_window(period)
699
- projects = PROVIDERS[provider]["all"]()
1092
+ if show_tokens:
1093
+ projects = PROVIDERS[provider]["scan"]()
1094
+ else:
1095
+ projects = [(label, ts, []) for label, ts in PROVIDERS[provider]["all"]()]
700
1096
 
701
1097
  rows = []
1098
+ all_events = []
702
1099
  combined_daily = defaultdict(float)
703
1100
  prompts_per_day = defaultdict(int)
704
1101
  grand_minutes = 0.0
705
1102
  grand_prompts = 0
706
1103
  grand_sessions = 0
707
1104
 
708
- for label, timestamps in projects:
1105
+ for label, timestamps, events in projects:
709
1106
  timestamps = _filter_timestamps(timestamps, since, until)
710
1107
  if not timestamps:
711
1108
  continue
1109
+ events = _filter_events(events, since, until)
712
1110
  daily, sessions = compute_active_hours(timestamps, idle_threshold)
713
1111
  rows.append({
714
1112
  "label": label,
715
1113
  "minutes": sum(daily.values()),
716
1114
  "prompts": len(timestamps),
717
1115
  "sessions": len(sessions),
1116
+ "tokens": summarize_tokens(events) if show_tokens else None,
718
1117
  })
1118
+ all_events.extend(events)
719
1119
  for day, mins in daily.items():
720
1120
  combined_daily[day] += mins
721
1121
  for ts in timestamps:
@@ -725,33 +1125,40 @@ def analyze_summary(provider, period, idle_threshold, as_json):
725
1125
  grand_sessions += len(sessions)
726
1126
 
727
1127
  rows.sort(key=lambda r: r["minutes"], reverse=True)
1128
+ grand_tokens = summarize_tokens(all_events) if show_tokens else None
1129
+ token_days = tokens_by_day(all_events) if show_tokens else {}
728
1130
 
729
1131
  if as_json:
1132
+ projects_json = []
1133
+ for r in rows:
1134
+ entry = {"project": r["label"],
1135
+ "minutes": round(r["minutes"], 2),
1136
+ "prompts": r["prompts"],
1137
+ "sessions": r["sessions"]}
1138
+ if show_tokens:
1139
+ entry["tokens"] = r["tokens"]
1140
+ projects_json.append(entry)
1141
+ totals = {
1142
+ "projects": len(rows),
1143
+ "minutes": round(grand_minutes, 2),
1144
+ "prompts": grand_prompts,
1145
+ "sessions": grand_sessions,
1146
+ }
1147
+ if show_tokens:
1148
+ totals["tokens"] = grand_tokens
730
1149
  _print_json({
731
1150
  "provider": provider,
732
1151
  "period": period,
733
1152
  "idle_threshold_min": idle_threshold,
734
1153
  "since": _iso(since),
735
1154
  "until": _iso(until),
736
- "projects": [
737
- {"project": r["label"],
738
- "minutes": round(r["minutes"], 2),
739
- "prompts": r["prompts"],
740
- "sessions": r["sessions"]}
741
- for r in rows
742
- ],
1155
+ "projects": projects_json,
743
1156
  "days": [
744
- {"date": str(day),
745
- "minutes": round(combined_daily[day], 2),
746
- "prompts": prompts_per_day[day]}
747
- for day in sorted(combined_daily)
1157
+ _day_entry(day, combined_daily, prompts_per_day,
1158
+ token_days, show_tokens)
1159
+ for day in _day_keys(combined_daily, token_days)
748
1160
  ],
749
- "totals": {
750
- "projects": len(rows),
751
- "minutes": round(grand_minutes, 2),
752
- "prompts": grand_prompts,
753
- "sessions": grand_sessions,
754
- },
1161
+ "totals": totals,
755
1162
  })
756
1163
  return
757
1164
 
@@ -766,34 +1173,60 @@ def analyze_summary(provider, period, idle_threshold, as_json):
766
1173
  return
767
1174
  print(f" Active : {fmt_duration(grand_minutes)} across {len(rows)} project(s)")
768
1175
  print(f" Prompts : {grand_prompts} Sessions: {grand_sessions}")
1176
+ if show_tokens:
1177
+ print(f" Tokens : {fmt_tokens(grand_tokens['total'])} across "
1178
+ f"{grand_tokens['responses']:,} responses")
1179
+ print(f" In/Out : {fmt_tokens(grand_tokens['input'])} in · "
1180
+ f"{fmt_tokens(grand_tokens['output'])} out · "
1181
+ f"{fmt_tokens(grand_tokens['cache_read'] + grand_tokens['cache_write'])} cache")
769
1182
  print("=" * width)
770
1183
  print()
771
1184
 
772
- print(f" {'PROJECT':<34} {'TIME':>9} {'PROMPTS':>7} BAR")
1185
+ if show_tokens:
1186
+ print(f" {'PROJECT':<30} {'TIME':>9} {'PROMPTS':>7} {'TOKENS':>9}")
1187
+ else:
1188
+ print(f" {'PROJECT':<34} {'TIME':>9} {'PROMPTS':>7} BAR")
773
1189
  print("-" * width)
774
1190
  max_mins = max(r["minutes"] for r in rows)
775
1191
  for r in rows:
776
1192
  name = r["label"]
777
- if len(name) > 33:
778
- name = "…" + name[-32:]
779
- bar = "█" * (int((r["minutes"] / max_mins) * 10) if max_mins else 0)
780
- print(f" {name:<34} {fmt_duration(r['minutes']):>9} {r['prompts']:>7} {bar}")
1193
+ if show_tokens:
1194
+ if len(name) > 29:
1195
+ name = "…" + name[-28:]
1196
+ print(f" {name:<30} {fmt_duration(r['minutes']):>9} "
1197
+ f"{r['prompts']:>7} {fmt_tokens(r['tokens']['total']):>9}")
1198
+ else:
1199
+ if len(name) > 33:
1200
+ name = "…" + name[-32:]
1201
+ bar = "█" * (int((r["minutes"] / max_mins) * 10) if max_mins else 0)
1202
+ print(f" {name:<34} {fmt_duration(r['minutes']):>9} {r['prompts']:>7} {bar}")
781
1203
  print("-" * width)
782
- print(f" {'TOTAL':<34} {fmt_duration(grand_minutes):>9} {grand_prompts:>7}")
1204
+ if show_tokens:
1205
+ print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} "
1206
+ f"{grand_prompts:>7} {fmt_tokens(grand_tokens['total']):>9}")
1207
+ else:
1208
+ print(f" {'TOTAL':<34} {fmt_duration(grand_minutes):>9} {grand_prompts:>7}")
783
1209
 
784
1210
  if period == "week":
785
1211
  print()
786
- print(f" {'DAY':<12} {'TIME':>9} {'PROMPTS':>7} BAR")
1212
+ token_col = f" {'TOKENS':>9}" if show_tokens else ""
1213
+ print(f" {'DAY':<12} {'TIME':>9} {'PROMPTS':>7}{token_col} BAR")
787
1214
  print("-" * width)
788
1215
  max_day = max(combined_daily.values())
789
- for day in sorted(combined_daily):
1216
+ for day in _day_keys(combined_daily, token_days):
790
1217
  mins = combined_daily[day]
791
1218
  bar = "█" * (int((mins / max_day) * 10) if max_day else 0)
792
- print(f" {str(day):<12} {fmt_duration(mins):>9} {prompts_per_day[day]:>7} {bar}")
1219
+ cell = (f" {fmt_tokens(token_days.get(day, {}).get('total', 0)):>9}"
1220
+ if show_tokens else "")
1221
+ print(f" {str(day):<12} {fmt_duration(mins):>9} "
1222
+ f"{prompts_per_day[day]:>7}{cell} {bar}")
1223
+ if show_tokens:
1224
+ _print_model_table(grand_tokens)
793
1225
  print()
794
1226
 
795
1227
 
796
- def export_data(provider, idle_threshold, since, until, detail, anonymize):
1228
+ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1229
+ show_tokens=False):
797
1230
  """Emit one versioned JSON bundle of every project for external tools.
798
1231
 
799
1232
  Always writes JSON to stdout. `detail` selects granularity:
@@ -811,25 +1244,35 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize):
811
1244
  daily, sessions, and prompts. Top-level `provider` is "both" when more than
812
1245
  one provider contributed; `providers` lists them, and `totals.by_provider`
813
1246
  breaks the grand totals down per provider.
1247
+
1248
+ With `show_tokens`, every project, day, provider and the grand totals also
1249
+ carry a normalized `tokens` record with a per-model breakdown. The token
1250
+ fields are purely additive — a v2 consumer reads a v3 bundle unchanged.
814
1251
  """
815
1252
  out_projects = []
816
1253
  by_provider = {}
817
1254
  grand_minutes = 0.0
818
1255
  grand_prompts = 0
819
1256
  grand_sessions = 0
1257
+ grand_events = []
820
1258
  name_counter = 0
821
1259
 
822
1260
  for prov in _export_providers(provider):
823
- projects = PROVIDERS[prov]["all"]()
1261
+ if show_tokens:
1262
+ projects = PROVIDERS[prov]["scan"]()
1263
+ else:
1264
+ projects = [(label, ts, []) for label, ts in PROVIDERS[prov]["all"]()]
824
1265
  p_minutes = 0.0
825
1266
  p_prompts = 0
826
1267
  p_sessions = 0
827
1268
  p_projects = 0
1269
+ p_events = []
828
1270
 
829
- for label, timestamps in sorted(projects, key=lambda p: p[0]):
1271
+ for label, timestamps, events in sorted(projects, key=lambda p: p[0]):
830
1272
  timestamps = _filter_timestamps(timestamps, since, until)
831
1273
  if not timestamps:
832
1274
  continue
1275
+ events = _filter_events(events, since, until)
833
1276
  daily, _ = compute_active_hours(timestamps, idle_threshold)
834
1277
  sessions = group_sessions(timestamps, idle_threshold)
835
1278
  total_minutes = sum(daily.values())
@@ -838,6 +1281,8 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize):
838
1281
  for ts in timestamps:
839
1282
  prompts_per_day[ts.date()] += 1
840
1283
 
1284
+ token_days = tokens_by_day(events) if show_tokens else {}
1285
+
841
1286
  name_counter += 1
842
1287
  proj = {
843
1288
  "id": _project_id(prov, label),
@@ -852,12 +1297,12 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize):
852
1297
  "last": int(timestamps[-1].timestamp()),
853
1298
  },
854
1299
  "daily": [
855
- {"date": str(day),
856
- "minutes": round(daily[day], 2),
857
- "prompts": prompts_per_day[day]}
858
- for day in sorted(daily)
1300
+ _day_entry(day, daily, prompts_per_day, token_days, show_tokens)
1301
+ for day in _day_keys(daily, token_days)
859
1302
  ],
860
1303
  }
1304
+ if show_tokens:
1305
+ proj["tokens"] = summarize_tokens(events)
861
1306
  if not anonymize:
862
1307
  proj["path"] = label
863
1308
  if detail in ("sessions", "raw"):
@@ -876,6 +1321,7 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize):
876
1321
  p_minutes += total_minutes
877
1322
  p_prompts += len(timestamps)
878
1323
  p_sessions += len(sessions)
1324
+ p_events.extend(events)
879
1325
 
880
1326
  if p_projects:
881
1327
  by_provider[prov] = {
@@ -884,9 +1330,12 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize):
884
1330
  "prompts": p_prompts,
885
1331
  "sessions": p_sessions,
886
1332
  }
1333
+ if show_tokens:
1334
+ by_provider[prov]["tokens"] = summarize_tokens(p_events)
887
1335
  grand_minutes += p_minutes
888
1336
  grand_prompts += p_prompts
889
1337
  grand_sessions += p_sessions
1338
+ grand_events.extend(p_events)
890
1339
 
891
1340
  # Report the providers that actually contributed activity; fall back to the
892
1341
  # requested set so a single-provider export is never emitted with an empty
@@ -895,25 +1344,31 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize):
895
1344
  providers = present if present else sorted(_export_providers(provider))
896
1345
  provider_field = "both" if len(providers) > 1 else providers[0]
897
1346
 
1347
+ grand_tokens = summarize_tokens(grand_events) if show_tokens else None
1348
+ totals = {
1349
+ "projects": len(out_projects),
1350
+ "minutes": round(grand_minutes, 2),
1351
+ "prompts": grand_prompts,
1352
+ "sessions": grand_sessions,
1353
+ "by_provider": by_provider,
1354
+ }
1355
+ if show_tokens:
1356
+ totals["tokens"] = grand_tokens
1357
+
898
1358
  _print_json({
899
- "schema": "clockwork/v2",
1359
+ "schema": "clockwork/v3",
900
1360
  "generated_at": datetime.now().astimezone().isoformat(),
901
1361
  "provider": provider_field,
902
1362
  "providers": providers,
903
1363
  "idle_threshold_min": idle_threshold,
904
1364
  "detail": detail,
905
1365
  "anonymized": anonymize,
1366
+ "tokens": show_tokens,
906
1367
  "daily_tz": "UTC",
907
1368
  "since": _iso(since),
908
1369
  "until": _iso(until),
909
1370
  "projects": out_projects,
910
- "totals": {
911
- "projects": len(out_projects),
912
- "minutes": round(grand_minutes, 2),
913
- "prompts": grand_prompts,
914
- "sessions": grand_sessions,
915
- "by_provider": by_provider,
916
- },
1371
+ "totals": totals,
917
1372
  })
918
1373
 
919
1374
  # A friendly receipt on stderr — keeps stdout pure JSON for redirection.
@@ -922,11 +1377,17 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize):
922
1377
  tags = [provider_field, f"detail={detail}"]
923
1378
  if anonymize:
924
1379
  tags.append("anonymized")
1380
+ if show_tokens:
1381
+ tags.append("tokens")
925
1382
  print(f"\n ✓ export complete → {where}", file=sys.stderr)
926
1383
  print(f" {' · '.join(tags)}", file=sys.stderr)
927
1384
  print(f" {len(out_projects)} projects · {grand_prompts:,} prompts "
928
1385
  f"· {grand_sessions:,} sessions · {grand_minutes / 60:.1f}h active",
929
1386
  file=sys.stderr)
1387
+ if show_tokens:
1388
+ print(f" {grand_tokens['total']:,} tokens · "
1389
+ f"{grand_tokens['responses']:,} responses · "
1390
+ f"{len(grand_tokens['by_model'])} model(s)", file=sys.stderr)
930
1391
 
931
1392
 
932
1393
  def list_projects(provider, as_json):
@@ -955,7 +1416,7 @@ def _die(msg):
955
1416
  def _parse_args(argv):
956
1417
  """Split flags from positionals. Returns (positionals, opts)."""
957
1418
  opts = {"json": False, "since": None, "until": None,
958
- "detail": "raw", "anonymize": False}
1419
+ "detail": "raw", "anonymize": False, "tokens": False}
959
1420
  positionals = []
960
1421
  i = 0
961
1422
  while i < len(argv):
@@ -964,6 +1425,8 @@ def _parse_args(argv):
964
1425
  opts["json"] = True
965
1426
  elif a == "--anonymize":
966
1427
  opts["anonymize"] = True
1428
+ elif a == "--tokens":
1429
+ opts["tokens"] = True
967
1430
  elif a in ("--since", "--until", "--detail"):
968
1431
  i += 1
969
1432
  if i >= len(argv):
@@ -983,7 +1446,25 @@ def _parse_args(argv):
983
1446
  return positionals, opts
984
1447
 
985
1448
 
1449
+ def _force_utf8_streams():
1450
+ """Write UTF-8 on stdout/stderr regardless of the platform locale.
1451
+
1452
+ Windows falls back to the locale codepage (usually cp1252) whenever output
1453
+ is redirected to a file or pipe, and the bar glyph and status marks used
1454
+ below are not encodable there. Reconfiguring keeps output byte-identical
1455
+ across platforms; the JSON export is pure ASCII either way.
1456
+ """
1457
+ for stream in (sys.stdout, sys.stderr):
1458
+ try:
1459
+ stream.reconfigure(encoding="utf-8")
1460
+ except (AttributeError, ValueError):
1461
+ # Detached or replaced streams (test capture, some launchers) have
1462
+ # nothing to reconfigure; whatever encoding they carry stands.
1463
+ pass
1464
+
1465
+
986
1466
  def main():
1467
+ _force_utf8_streams()
987
1468
  argv = sys.argv[1:]
988
1469
  if "-h" in argv or "--help" in argv:
989
1470
  print(__doc__.strip())
@@ -1012,13 +1493,16 @@ def main():
1012
1493
  _die(str(e))
1013
1494
 
1014
1495
  if target == "all":
1015
- analyze_all(provider, idle_threshold, since, until, opts["json"])
1496
+ analyze_all(provider, idle_threshold, since, until, opts["json"],
1497
+ opts["tokens"])
1016
1498
  elif target in ("today", "week"):
1017
- analyze_summary(provider, target, idle_threshold, opts["json"])
1499
+ analyze_summary(provider, target, idle_threshold, opts["json"],
1500
+ opts["tokens"])
1018
1501
  elif target == "export":
1019
1502
  export_data(provider, idle_threshold, since, until,
1020
- opts["detail"], opts["anonymize"])
1503
+ opts["detail"], opts["anonymize"], opts["tokens"])
1021
1504
  elif target == "list":
1022
1505
  list_projects(provider, opts["json"])
1023
1506
  else:
1024
- analyze_single(provider, target, idle_threshold, since, until, opts["json"])
1507
+ analyze_single(provider, target, idle_threshold, since, until,
1508
+ opts["json"], opts["tokens"])
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clockwork-cli
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Mine your Claude Code and Codex session logs to estimate active time
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/danielsich/clockwork
@@ -141,6 +141,7 @@ Options:
141
141
  form like 7d (7 days ago) or 2w (2 weeks ago)
142
142
  --detail <level> export granularity: raw | sessions | daily (default raw)
143
143
  --anonymize export: replace project paths with a hash id + generic name
144
+ --tokens Also report token usage and a per-model breakdown
144
145
  ```
145
146
 
146
147
  ### Examples
@@ -174,6 +175,10 @@ clockwork claude all --since 7d
174
175
  # A specific date range for one project
175
176
  clockwork claude ~/dev/myproject --since 2026-07-01 --until 2026-07-05
176
177
 
178
+ # Token and model usage, alongside the timings
179
+ clockwork claude all --tokens
180
+ clockwork both today --tokens
181
+
177
182
  # Machine-readable output — pipe into jq, a spreadsheet, or a dashboard
178
183
  clockwork codex all --json | jq '.projects[] | {project, minutes}'
179
184
  ```
@@ -206,6 +211,58 @@ usage still go to stderr), so clockwork composes with `jq`, cron jobs, or any
206
211
  dashboard. Exit codes are script-friendly: `0` on success, `1` when nothing
207
212
  matched, `2` for bad arguments.
208
213
 
214
+ ### Token & model usage (`--tokens`)
215
+
216
+ `--tokens` adds token counts and a per-model breakdown to any command. It reads
217
+ the usage each tool already records next to your prompts — nothing is estimated,
218
+ and no API is called.
219
+
220
+ ```
221
+ Tokens : 760.7M across 6,739 responses
222
+ In/Out : 1.6M in · 5.7M out
223
+ Cache : 731.7M read · 21.7M write
224
+ ========================================================================================
225
+
226
+ PROJECT TIME PROMPTS IN OUT CACHE TOTAL
227
+ ----------------------------------------------------------------------------------------
228
+ /Users/you/dev/alpha 54h 08m 3693 1.1M 2.8M 394.8M 398.7M
229
+ /Users/you/dev/beta 19h 01m 1414 196.4k 870.7k 121.5M 122.6M
230
+
231
+ MODEL RESP INPUT OUTPUT CACHE R CACHE W TOTAL
232
+ --------------------------------------------------------------------------------
233
+ claude-opus-4-8 4,732 1.4M 4.3M 572.0M 15.9M 593.7M
234
+ claude-sonnet-4-6 1,431 10.2k 786.0k 108.8M 2.8M 111.6M
235
+ ```
236
+
237
+ **The counts are normalized across the two tools**, because they don't report
238
+ the same way:
239
+
240
+ | field | meaning | claude | codex |
241
+ | ------------- | ------------------------------ | ------ | ----- |
242
+ | `input` | fresh (uncached) input tokens | as reported | `input_tokens` minus `cached_input_tokens`, which Codex nests inside it |
243
+ | `output` | output tokens | includes thinking | includes reasoning |
244
+ | `cache_read` | input served from cache | `cache_read_input_tokens` | `cached_input_tokens` |
245
+ | `cache_write` | input written to cache | `cache_creation_input_tokens` | never reported (always 0) |
246
+ | `reasoning` | thinking tokens, a *subset* of `output` | not broken out (always 0) | `reasoning_output_tokens` |
247
+
248
+ `total` is `input + output + cache_read + cache_write`; `reasoning` is
249
+ deliberately left out of it, since `output` already covers those tokens.
250
+
251
+ Two counting traps are handled for you, both of which inflate the numbers if
252
+ you read the logs naively:
253
+
254
+ - **Claude** writes one line per content block — thinking, text, and each tool
255
+ call — and every line of a single API response repeats the *identical* usage
256
+ block. Counting per line overstates usage roughly 2.6x, so responses are
257
+ deduplicated on their message id.
258
+ - **Codex** re-emits a stale `last_token_usage` on aborted and no-op turns that
259
+ its cumulative counter never absorbs, so a turn's real cost is read as the
260
+ rise in `total_token_usage` instead. The model name comes from the preceding
261
+ `turn_context` record (`session_meta` only names the provider).
262
+
263
+ What it can't tell you is cost — the logs carry no prices, and subscription
264
+ usage isn't billed per token anyway.
265
+
209
266
  ## Exporting for external tools
210
267
 
211
268
  `clockwork <provider> export` writes a single **self-describing, versioned**
@@ -258,17 +315,18 @@ for a combined view, so nothing is lost either way.
258
315
  - `totals.by_provider` breaks the grand totals down per provider; the grand
259
316
  `totals` stay the cross-provider sum.
260
317
 
261
- ### Export schema (`clockwork/v2`)
318
+ ### Export schema (`clockwork/v3`)
262
319
 
263
320
  ```jsonc
264
321
  {
265
- "schema": "clockwork/v2",
322
+ "schema": "clockwork/v3",
266
323
  "generated_at": "2026-07-06T00:30:00+02:00", // local ISO-8601
267
324
  "provider": "both", // "claude" | "codex" | "both"
268
325
  "providers": ["claude", "codex"], // sorted, distinct; ≥ 1 element
269
326
  "idle_threshold_min": 30,
270
327
  "detail": "raw", // raw | sessions | daily
271
328
  "anonymized": false,
329
+ "tokens": false, // true when --tokens was given (adds the fields below)
272
330
  "daily_tz": "UTC", // the "daily" buckets use UTC calendar dates
273
331
  "since": null, // ISO bound if --since was given, else null
274
332
  "until": null,
@@ -284,6 +342,19 @@ for a combined view, so nothing is lost either way.
284
342
  "first": 1780521570, "last": 1782130426 // epoch seconds
285
343
  },
286
344
  "daily": [ { "date": "2026-06-03", "minutes": 4.34, "prompts": 27 } ],
345
+ // every "tokens" block below appears only with --tokens
346
+ "tokens": {
347
+ "responses": 373, // API responses, deduplicated
348
+ "input": 31065, "output": 287747,
349
+ "cache_read": 20753836, "cache_write": 579725,
350
+ "reasoning": 0, // subset of output; Codex only
351
+ "total": 21652373, // input + output + cache_read + cache_write
352
+ "by_model": [ // biggest consumer first
353
+ { "model": "claude-opus-4-8", "responses": 238, "input": 30046,
354
+ "output": 177141, "cache_read": 13207329, "cache_write": 352749,
355
+ "reasoning": 0, "total": 13767265 }
356
+ ]
357
+ },
287
358
  "sessions": [ { "start": 1780521570, "end": 1780521830,
288
359
  "minutes": 4.34, "prompts": 27 } ], // detail >= sessions
289
360
  "prompts": [ 1780521570, 1780521582 ] // detail == raw
@@ -291,9 +362,12 @@ for a combined view, so nothing is lost either way.
291
362
  ],
292
363
  "totals": {
293
364
  "projects": 6, "minutes": 3392.97, "prompts": 4588, "sessions": 64,
365
+ "tokens": { /* same shape, summed across every project */ },
294
366
  "by_provider": {
295
- "claude": { "projects": 4, "minutes": 2500.0, "prompts": 3000, "sessions": 40 },
296
- "codex": { "projects": 2, "minutes": 892.97, "prompts": 1588, "sessions": 24 }
367
+ "claude": { "projects": 4, "minutes": 2500.0, "prompts": 3000, "sessions": 40,
368
+ "tokens": { /* ... */ } },
369
+ "codex": { "projects": 2, "minutes": 892.97, "prompts": 1588, "sessions": 24,
370
+ "tokens": { /* ... */ } }
297
371
  }
298
372
  }
299
373
  }
@@ -301,8 +375,14 @@ for a combined view, so nothing is lost either way.
301
375
 
302
376
  All instants are **UTC-based epoch seconds** (`new Date(sec * 1000)` in JS), so
303
377
  the consumer picks the display timezone. The `schema` field is the version
304
- contract — `clockwork/v2` is a breaking bump over `v1` (provider moved to the
305
- project level), so tools should guard on it.
378
+ contract — `clockwork/v2` was a breaking bump over `v1` (provider moved to the
379
+ project level), so tools should guard on it. `clockwork/v3` is **additive
380
+ only**: it adds the `tokens` flag and the `tokens` blocks described above, and a
381
+ v2 consumer reads a v3 bundle unchanged.
382
+
383
+ The per-day `tokens` buckets sum to the project's `tokens`, project totals sum
384
+ to `totals.by_provider`, and those sum to `totals.tokens` — at every level, and
385
+ per model.
306
386
 
307
387
  ## License
308
388
 
@@ -0,0 +1,8 @@
1
+ clockwork_cli/__init__.py,sha256=2BOKqQApGWawT7265tK_Gz24oUkxxdjpXIC7-Xn0mYA,55700
2
+ clockwork_cli/__main__.py,sha256=HcXz3nL5ocmXEASzCOKbjM3Sj6czPe8sqJSXglAjBw0,39
3
+ clockwork_cli-0.3.0.dist-info/licenses/LICENSE,sha256=pz4uy4Ra9e-Ks0T7UFFi8rGL86-f29m2ZOB0WgixjLY,1068
4
+ clockwork_cli-0.3.0.dist-info/METADATA,sha256=MBLUplu6eqywZQJateg9_c3GQvRWvi1f-AFTR6tSX2Y,16467
5
+ clockwork_cli-0.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
6
+ clockwork_cli-0.3.0.dist-info/entry_points.txt,sha256=wmiWdgLrHpNKK9wDwCOiX4zyLFx71_G5DzydSiu8DWs,49
7
+ clockwork_cli-0.3.0.dist-info/top_level.txt,sha256=g5lh3hqDChq8bNBmiN2Kze86weZTddLJspNABd-2ckg,14
8
+ clockwork_cli-0.3.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (83.0.0)
2
+ Generator: setuptools (84.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,8 +0,0 @@
1
- clockwork_cli/__init__.py,sha256=OlRHKN2tPx8eUEwBsEz_E3I9xCxNlppL1IQ9EBCuWCk,35644
2
- clockwork_cli/__main__.py,sha256=HcXz3nL5ocmXEASzCOKbjM3Sj6czPe8sqJSXglAjBw0,39
3
- clockwork_cli-0.2.0.dist-info/licenses/LICENSE,sha256=pz4uy4Ra9e-Ks0T7UFFi8rGL86-f29m2ZOB0WgixjLY,1068
4
- clockwork_cli-0.2.0.dist-info/METADATA,sha256=B4yV8lkbt1U3sfJ2yEm2WHJn4WBstIsJxCHfBnI6d0o,12227
5
- clockwork_cli-0.2.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
6
- clockwork_cli-0.2.0.dist-info/entry_points.txt,sha256=wmiWdgLrHpNKK9wDwCOiX4zyLFx71_G5DzydSiu8DWs,49
7
- clockwork_cli-0.2.0.dist-info/top_level.txt,sha256=g5lh3hqDChq8bNBmiN2Kze86weZTddLJspNABd-2ckg,14
8
- clockwork_cli-0.2.0.dist-info/RECORD,,