@alexgreensh/token-optimizer 5.13.67 → 5.13.69

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.
Files changed (75) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/package.json +1 -1
  5. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  6. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  7. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  8. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  9. package/skills/token-coach/SKILL.md +21 -23
  10. package/skills/token-dashboard/SKILL.md +5 -4
  11. package/skills/token-optimizer/SKILL.md +1 -1
  12. package/skills/token-optimizer/assets/dashboard.html +101 -50
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  15. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  16. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  17. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  18. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +8 -2
  19. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
  20. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
  21. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  22. package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
  23. package/skills/token-optimizer/scripts/_measure/daemon.py +34 -76
  24. package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
  25. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  26. package/skills/token-optimizer/scripts/_measure/lifecycle.py +88 -528
  27. package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
  28. package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
  29. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  30. package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
  31. package/skills/token-optimizer/scripts/antigravity_install.py +7 -0
  32. package/skills/token-optimizer/scripts/bash_compress.py +8 -40
  33. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
  34. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  35. package/skills/token-optimizer/scripts/cloud_kit.py +22 -22
  36. package/skills/token-optimizer/scripts/codex_doctor.py +34 -8
  37. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  38. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  39. package/skills/token-optimizer/scripts/command_filters.py +39 -309
  40. package/skills/token-optimizer/scripts/copilot_install.py +9 -0
  41. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  42. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  43. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  44. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  45. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  46. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  47. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  48. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  49. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  50. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  51. package/skills/token-optimizer/scripts/cursor_install.py +111 -19
  52. package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
  53. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  54. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  55. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  56. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  57. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  58. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  59. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  60. package/skills/token-optimizer/scripts/devin_source.py +17 -6
  61. package/skills/token-optimizer/scripts/devin_verify.py +17 -0
  62. package/skills/token-optimizer/scripts/grok_install.py +9 -0
  63. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  64. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  65. package/skills/token-optimizer/scripts/hermes_install.py +4 -1
  66. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  67. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  68. package/skills/token-optimizer/scripts/measure.py +2 -2
  69. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  70. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  71. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  72. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
  73. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
  74. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
  75. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +0 -10
@@ -5223,7 +5223,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
5223
5223
  "{then_n:,} in {month}, {growth:.1f}x, at about the same total spend) -- "
5224
5224
  "that extra capacity is real, but it is capacity gained, not dollars saved, "
5225
5225
  "so it is not in the headline. Model price/mix drift worth about "
5226
- "${drift:,.0f}/mo is also excluded: it would have happened without Token "
5226
+ "${drift:,.0f} this period is also excluded: it would have happened without Token "
5227
5227
  "Optimizer."
5228
5228
  + ("" if pinned else " The anchor month already had partial Token Optimizer "
5229
5229
  "coverage, so if anything this understates the full pre-tool gap.")
@@ -5249,6 +5249,7 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
5249
5249
  "counterfactual_usd": counterfactual,
5250
5250
  "transformation_usd": transformation,
5251
5251
  "crosscheck": crosscheck,
5252
+ "coverage": now.get("coverage"),
5252
5253
  "engine_priced_transformation_usd": engine_transformation,
5253
5254
  "engine_priced_actual_usd": n_usd,
5254
5255
  "price_mix_drift_usd": price_mix_drift,
@@ -5265,61 +5266,9 @@ def _session_weight_pool_savings(cutoff, days=None, tier=None, activity_window=N
5265
5266
 
5266
5267
 
5267
5268
  def _price_parent_activity_window(conn, start, end, tier):
5268
- """Use real in-window activity with the standard parent/child pricing rules.
5269
-
5270
- Reading transcripts here also keeps a weekly report correct while bounded
5271
- background collection catches up. Missing files produce an unavailable
5272
- estimate instead of silently treating missing work as zero cost.
5273
- """
5274
- _measure_facade = _compat.facade()
5275
- paths = conn.execute(
5276
- "SELECT jsonl_path, date FROM session_log WHERE input_tokens IS NOT NULL "
5277
- "AND COALESCE(is_sidechain,0)=0").fetchall()
5278
- # Include new sessions before bounded collection reaches them.
5279
- known = {str(name) for name, _ in paths}
5280
- for path, _mtime, _ in _measure_facade._find_all_jsonl_files(None):
5281
- if str(path) not in known:
5282
- paths.append((str(path), ""))
5283
- known.add(str(path))
5284
- rows = []
5285
- request_ledger = {} # a request repeated in another transcript counts once (largest usage)
5286
- for name, recorded_date in paths:
5287
- path = _measure_facade.Path(name)
5288
- if not path.exists():
5289
- if recorded_date and str(recorded_date) < start.date().isoformat():
5290
- continue
5291
- return None
5292
- children = _measure_facade._find_subagent_jsonl_files(path)
5293
- parsed = _measure_facade._parse_session_jsonl(path, window_start=start, window_end=end)
5294
- if parsed and parsed.get("is_sidechain"):
5295
- continue
5296
- if parsed:
5297
- parsed = _measure_facade._parsed_net_of_ledger(parsed, request_ledger)
5298
- if not parsed:
5299
- parsed = {"total_input_tokens": 0, "total_output_tokens": 0,
5300
- "total_cache_create_1h": 0, "total_cache_create_5m": 0,
5301
- "cache_hit_rate": 0, "model_usage": {}, "api_calls": 0,
5302
- "message_count": 0}
5303
- inp, out = parsed["total_input_tokens"], parsed["total_output_tokens"]
5304
- cw1, cw5 = parsed["total_cache_create_1h"], parsed["total_cache_create_5m"]
5305
- child_cache_read = 0
5306
- for child in children:
5307
- cp = _measure_facade._parse_session_jsonl(child, window_start=start, window_end=end)
5308
- if cp:
5309
- cp = _measure_facade._parsed_net_of_ledger(cp, request_ledger)
5310
- inp += cp["total_input_tokens"]
5311
- out += cp["total_output_tokens"]
5312
- cw1 += cp["total_cache_create_1h"]
5313
- cw5 += cp["total_cache_create_5m"]
5314
- child_cache_read += cp["total_cache_read"]
5315
- if not parsed["api_calls"] and inp + out == 0:
5316
- continue
5317
- usage = _measure_facade.json.dumps(parsed["model_usage"])
5318
- hit = (parsed["cache_hit_rate"] if parsed["api_calls"] else
5319
- child_cache_read / inp if inp else 0)
5320
- rows.append((inp, out, cw5, cw1, hit, usage, usage,
5321
- parsed["api_calls"], parsed["message_count"]))
5322
- return _measure_facade._price_parent_rows(rows, tier)
5269
+ """Price in-window activity and disclose incomplete transcript coverage."""
5270
+ from . import weekly_activity
5271
+ return weekly_activity.price(_compat.facade(), conn, start, end, tier)
5323
5272
 
5324
5273
 
5325
5274
  def _weekly_full_savings(resets_at=None, now=None):
@@ -5348,7 +5297,7 @@ def _weekly_full_savings(resets_at=None, now=None):
5348
5297
  age = end.timestamp() - float(cached["computed_at"])
5349
5298
  if (0 <= age < 60 and cached["start"] == start.isoformat()
5350
5299
  and cached["anchor_stamp"] == anchor_stamp
5351
- and cached.get("activity_basis") == 1
5300
+ and cached.get("activity_basis") == 2
5352
5301
  and cached["version"] == _measure_facade.TOKEN_OPTIMIZER_VERSION):
5353
5302
  return _measure_facade._positive_full_value(cached["value"])
5354
5303
  except (OSError, ValueError, TypeError, KeyError):
@@ -5369,13 +5318,14 @@ def _weekly_full_savings(resets_at=None, now=None):
5369
5318
  "uncapped_usd": round(pool["transformation_usd"], 2),
5370
5319
  "actual_usd": round(pool["actual_usd"], 2),
5371
5320
  "counterfactual_usd": round(pool["counterfactual_usd"], 2),
5372
- "api_calls": pool["now_units"], "anchor_month": pool["anchor_month"]}
5321
+ "api_calls": pool["now_units"], "anchor_month": pool["anchor_month"],
5322
+ "coverage": pool.get("coverage")}
5373
5323
  if now is None:
5374
5324
  try:
5375
5325
  _measure_facade._write_baseline_state(cache_path, {
5376
5326
  "computed_at": end.timestamp(), "start": start.isoformat(),
5377
5327
  "anchor_stamp": anchor_path.stat().st_mtime_ns if anchor_path.exists() else None,
5378
- "activity_basis": 1,
5328
+ "activity_basis": 2,
5379
5329
  "version": _measure_facade.TOKEN_OPTIMIZER_VERSION, "value": value})
5380
5330
  except OSError:
5381
5331
  pass
@@ -7051,7 +7001,7 @@ def savings_report(days=None, as_json=None):
7051
7001
  if float(ba.get("monthly_savings_usd", 0.0) or 0.0) > 0:
7052
7002
  wp = ba.get("session_weight_pool") or None
7053
7003
  print()
7054
- print(f" YOUR TRANSFORMATION: ~${ba['monthly_savings_usd']:,.0f}/mo")
7004
+ print(f" YOUR TRANSFORMATION: ~${ba['monthly_savings_usd']:,.0f} over {days} days")
7055
7005
  # Spend cap disclosure: when the counterfactual exceeds actual spend,
7056
7006
  # the headline is capped and the user must see why, not wonder why the
7057
7007
  # number stopped moving.
@@ -7080,7 +7030,7 @@ def savings_report(days=None, as_json=None):
7080
7030
  f"the old way) [estimated]")
7081
7031
  drift = float(wp.get("price_mix_drift_usd", 0.0) or 0.0)
7082
7032
  if abs(drift) >= 1.0:
7083
- print(f" Not claimed: ~${abs(drift):,.0f}/mo of model price/mix drift "
7033
+ print(f" Not claimed: ~${abs(drift):,.0f} this period of model price/mix drift "
7084
7034
  f"({'cheaper' if drift >= 0 else 'costlier'} models would have moved "
7085
7035
  f"your bill without Token Optimizer).")
7086
7036
  cross = wp.get("crosscheck") or {}
@@ -7092,11 +7042,11 @@ def savings_report(days=None, as_json=None):
7092
7042
  if isinstance(gap, (int, float)) else "")
7093
7043
  if _measure_facade._crosscheck_verdict(wp):
7094
7044
  print(f" Cross-check on {cross_unit}: "
7095
- f"{_measure_facade._signed_usd(cross_usd)}/mo "
7045
+ f"{_measure_facade._signed_usd(cross_usd)} this period "
7096
7046
  f"(independent unit, agrees within ~10%{gap_txt}).")
7097
7047
  else:
7098
7048
  print(f" Cross-check on {cross_unit}: "
7099
- f"{_measure_facade._signed_usd(cross_usd)}/mo "
7049
+ f"{_measure_facade._signed_usd(cross_usd)} this period "
7100
7050
  f"(independent unit, does not agree{gap_txt}).")
7101
7051
  else:
7102
7052
  print(f" Had you worked the way you did before Token Optimizer "
@@ -7111,7 +7061,7 @@ def savings_report(days=None, as_json=None):
7111
7061
  for lev in ba_breakdown:
7112
7062
  amt = float(lev.get("monthly_usd", 0) or 0)
7113
7063
  sign = "-" if amt < 0 else " "
7114
- print(f" {sign}${abs(amt):>8,.0f}/mo {lev.get('label', lev.get('key', ''))}")
7064
+ print(f" {sign}${abs(amt):>8,.0f} this period {lev.get('label', lev.get('key', ''))}")
7115
7065
  caveat = ba.get("breakdown_caveat") or ""
7116
7066
  if caveat:
7117
7067
  # Wrap the caveat so the CLI surfaces the same disclosure as the dashboard.
@@ -7122,7 +7072,7 @@ def savings_report(days=None, as_json=None):
7122
7072
  # session-weight pool delegated work is excluded from the headline entirely.
7123
7073
  prem = float(ba.get("premium_delegation_cost_usd", 0.0) or 0.0)
7124
7074
  if prem > 0:
7125
- print(f" Costlier delegation: ${prem:,.0f}/mo of premium-model "
7075
+ print(f" Costlier delegation: ${prem:,.0f} this period of premium-model "
7126
7076
  f"subagent spend. "
7127
7077
  + ("Not in the headline above (delegated work is measured separately)."
7128
7078
  if wp else "Included in the sidechain net above."))
@@ -7132,16 +7082,16 @@ def savings_report(days=None, as_json=None):
7132
7082
  print()
7133
7083
  print(" YOUR TRANSFORMATION: none to headline this period")
7134
7084
  print(f" Each request now carries more context than at your baseline "
7135
- f"(est. ${ba.get('actual_monthly_usd', 0):,.0f}/mo now vs "
7136
- f"${ba.get('counterfactual_monthly_usd', 0):,.0f}/mo at the baseline's cost "
7085
+ f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs "
7086
+ f"${ba.get('counterfactual_monthly_usd', 0):,.0f} this period at the baseline's cost "
7137
7087
  f"per request), so there is no whole-workload saving to headline. "
7138
7088
  f"The measured savings below are real and counted.")
7139
7089
  elif ba.get("reason") == "flat":
7140
7090
  print()
7141
7091
  print(" YOUR TRANSFORMATION: no measurable change this period")
7142
7092
  print(f" Cost per unit of work is about the same as before install "
7143
- f"(est. ${ba.get('actual_monthly_usd', 0):,.0f}/mo now vs "
7144
- f"${ba.get('counterfactual_monthly_usd', 0):,.0f}/mo the old way). "
7093
+ f"(est. ${ba.get('actual_monthly_usd', 0):,.0f} now vs "
7094
+ f"${ba.get('counterfactual_monthly_usd', 0):,.0f} this period the old way). "
7145
7095
  f"The savings below are counted action by action.")
7146
7096
  elif ba.get("reason") == "methods_disagree":
7147
7097
  # The two independent work-unit methods could not be reconciled, so the
@@ -7157,7 +7107,7 @@ def savings_report(days=None, as_json=None):
7157
7107
  print()
7158
7108
  print(" YOUR TRANSFORMATION: not headlined this period")
7159
7109
  print(f" The {main_unit} and {cross_unit} methods disagree "
7160
- f"({_measure_facade._signed_usd(main_usd)}/mo vs {_measure_facade._signed_usd(cross_usd)}/mo), "
7110
+ f"({_measure_facade._signed_usd(main_usd)} vs {_measure_facade._signed_usd(cross_usd)} this period), "
7161
7111
  f"so neither is headlined. The measured savings below are real "
7162
7112
  f"and counted.")
7163
7113
 
@@ -2377,7 +2377,7 @@ def _grok_summary():
2377
2377
  print(f" Cost: ~${total_cost:,.2f} ({cost_known} session(s) with authoritative cost)")
2378
2378
  else:
2379
2379
  print(" Cost: no authoritative billing data recorded (costUsdTicks scrubbed)")
2380
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2380
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2381
2381
  if top_models:
2382
2382
  print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2383
2383
  if incomplete:
@@ -2593,7 +2593,7 @@ def _copilot_summary():
2593
2593
  print(f" Cost: ~${total_cost:,.2f} (premium requests)")
2594
2594
  else:
2595
2595
  print(" Cost: no billing data recorded by Copilot for these sessions")
2596
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2596
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2597
2597
  if top_models:
2598
2598
  print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2599
2599
  if incomplete:
@@ -2819,13 +2819,9 @@ def _write_cursor_restore_context(sessions, quiet=None):
2819
2819
  import tempfile # noqa: PLC0415
2820
2820
 
2821
2821
  from runtime_env import cursor_home as _ch # noqa: PLC0415
2822
-
2823
- # Group the most recent COMPLETE session per workspace root. The key
2824
- # must match what the sessionStart hook looks up: workspace_roots[0]
2825
- # (the repo root Cursor exports) first, then cwd as a fallback. Using
2826
- # cwd alone would key the file by a tool's working_directory (often a
2827
- # subdirectory) while sessionStart looks up the repo root — a silent
2828
- # never-match.
2822
+ from cursor_bridge_checkpoint import normalize_workspace # noqa: PLC0415
2823
+ from datetime import datetime # noqa: PLC0415
2824
+ # Match sessionStart's workspace root and source-session end time.
2829
2825
  by_ws: dict = {}
2830
2826
  for s in sessions:
2831
2827
  if s.get("incomplete"):
@@ -2837,19 +2833,21 @@ def _write_cursor_restore_context(sessions, quiet=None):
2837
2833
  root = str(s.get("cwd") or s.get("slug") or "")
2838
2834
  if not root:
2839
2835
  continue
2840
- by_ws.setdefault(root, []).append(s)
2841
-
2836
+ by_ws.setdefault(normalize_workspace(root), []).append(s)
2842
2837
  def _clean(value):
2843
2838
  _measure_facade = _compat.facade()
2844
2839
  text = str(value or "")
2845
2840
  text = "".join(ch for ch in text if ch == " " or ch.isprintable())
2846
2841
  return text[:200]
2847
-
2848
2842
  base = _ch() / "token-optimizer" / "restore-context"
2849
2843
  base.mkdir(parents=True, exist_ok=True)
2850
2844
  for root, group in by_ws.items():
2851
- latest = max(group, key=lambda s: ((_measure_facade := _compat.facade()), (s.get("first_ts") is not None, s.get("first_ts") or ""))[1])
2852
- lines = [f"[Token Optimizer] Continuity from your previous Cursor session in {_clean(root)}:"]
2845
+ latest = max(group, key=lambda s: (s.get("last_ts") is not None, s.get("last_ts") or ""))
2846
+ try:
2847
+ end_ts = datetime.fromisoformat(str(latest.get("last_ts") or "").replace("Z", "+00:00")).timestamp()
2848
+ except (ValueError, OverflowError):
2849
+ continue
2850
+ lines = [f"<!-- source-end: {end_ts} -->", f"[Token Optimizer] Continuity from your previous Cursor session in {_clean(root)}:"]
2853
2851
  if latest.get("model"):
2854
2852
  lines.append(
2855
2853
  f"- Model: {_clean(latest['model'])}; "
@@ -2884,8 +2882,34 @@ def _cursor_summary():
2884
2882
  import cursor_state as _cst # noqa: PLC0415
2885
2883
 
2886
2884
  home = _ch() if _ch is not None else _measure_facade.Path.home() / ".cursor"
2887
- tallies = [t for p in _cst.find_tallies(home) if (t := _cst.read_tally(p)) is not None]
2888
- normalized = [s for t in tallies if (s := _measure_facade.cursor_session.normalize_session(t))]
2885
+ tallies = []
2886
+ for p in _cst.find_tallies(home):
2887
+ t = _cst.read_tally(p)
2888
+ if t is not None:
2889
+ tallies.append(_cst.idle_finalise(t))
2890
+
2891
+ # Resolve the same token sources _collect_cursor_sessions uses: raw tally
2892
+ # JSON never carries bubble_tokens/transcript_tokens, so without this the
2893
+ # summary always reports 0 tokens and mislabels every session "estimated".
2894
+ composer_ids = [
2895
+ str(t.get("conversation_id") or t.get("session_id") or "") for t in tallies
2896
+ ]
2897
+ try:
2898
+ bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids, db_path=_cst.state_vscdb_path_for_home(home))
2899
+ except Exception:
2900
+ bubble_tokens = {}
2901
+ normalized = []
2902
+ for t in tallies:
2903
+ t = dict(t)
2904
+ cid = str(t.get("conversation_id") or t.get("session_id") or "")
2905
+ t["bubble_tokens"] = bubble_tokens.get(cid)
2906
+ try:
2907
+ t["transcript_tokens"] = _cst.transcript_estimate(t.get("transcript_path"), home)
2908
+ except Exception:
2909
+ t["transcript_tokens"] = None
2910
+ s = _measure_facade.cursor_session.normalize_session(t)
2911
+ if s is not None:
2912
+ normalized.append(s)
2889
2913
 
2890
2914
  print("Token Optimizer — Cursor summary")
2891
2915
  if not normalized:
@@ -2899,7 +2923,12 @@ def _cursor_summary():
2899
2923
  total_in = sum(s.get("total_input_tokens", 0) for s in normalized)
2900
2924
  total_out = sum(s.get("total_output_tokens", 0) for s in normalized)
2901
2925
  incomplete = sum(1 for s in normalized if s.get("incomplete"))
2902
- estimated = sum(1 for s in normalized if s.get("estimated"))
2926
+ token_sources = {}
2927
+ for s in normalized:
2928
+ src = s.get("token_source") or "unknown"
2929
+ token_sources[src] = token_sources.get(src, 0) + 1
2930
+ estimated = token_sources.get("cursor_transcript_estimate", 0)
2931
+ unknown_tokens = token_sources.get("cursor_tally_only", 0)
2903
2932
  compactions = sum(s.get("compactions", 0) for s in normalized)
2904
2933
  surfaces = {}
2905
2934
  for s in normalized:
@@ -2907,7 +2936,11 @@ def _cursor_summary():
2907
2936
  surfaces[sur] = surfaces.get(sur, 0) + 1
2908
2937
 
2909
2938
  print(f" {len(normalized)} session(s)")
2910
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2939
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2940
+ if token_sources:
2941
+ print(" Token sources: " + ", ".join(
2942
+ f"{k} ({v})" for k, v in sorted(token_sources.items())
2943
+ ))
2911
2944
  if compactions:
2912
2945
  print(f" Compactions captured: {compactions}")
2913
2946
  if surfaces:
@@ -2917,7 +2950,12 @@ def _cursor_summary():
2917
2950
  if estimated:
2918
2951
  print(
2919
2952
  f" {estimated} session(s) use estimated token counts "
2920
- "(state.vscdb tokenCount is best-effort; transcripts carry no usage)"
2953
+ "(transcript chars-over-four; state.vscdb tokenCount is best-effort)"
2954
+ )
2955
+ if unknown_tokens:
2956
+ print(
2957
+ f" {unknown_tokens} session(s) have no token figures "
2958
+ "(tally only) — unknown, not zero"
2921
2959
  )
2922
2960
  print()
2923
2961
  print(" Cost: Cursor stores no local billing data — no savings headline is")
@@ -2972,7 +3010,7 @@ def _collect_cursor_sessions(days=None, quiet=None, rebuild=None):
2972
3010
  str(t.get("conversation_id") or t.get("session_id") or "") for t in tallies
2973
3011
  ]
2974
3012
  try:
2975
- bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids)
3013
+ bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids, db_path=_cst.state_vscdb_path_for_home(home))
2976
3014
  except Exception:
2977
3015
  bubble_tokens = {}
2978
3016
 
@@ -0,0 +1,69 @@
1
+ """Price a weekly activity window while reporting missing transcript coverage."""
2
+
3
+
4
+ def price(facade, conn, start, end, tier):
5
+ paths = conn.execute(
6
+ "SELECT jsonl_path, date, last_activity_day, cost_usd FROM session_log "
7
+ "WHERE input_tokens IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
8
+ known = {str(row[0]) for row in paths}
9
+ for path, _mtime, _ in facade._find_all_jsonl_files(None):
10
+ if str(path) not in known:
11
+ paths.append((str(path), '', None, None))
12
+ known.add(str(path))
13
+ rows, missing = [], 0
14
+ costs, missing_cost, cost_complete = 0.0, 0.0, True
15
+ request_ledger = {}
16
+ for name, recorded_date, last_day, recorded_cost in paths:
17
+ path = facade.Path(name)
18
+ if not path.exists():
19
+ if ((last_day or recorded_date) and str(last_day or recorded_date) < start.date().isoformat()) or (recorded_date and str(recorded_date) > end.date().isoformat()):
20
+ continue
21
+ missing += 1
22
+ if recorded_cost is None:
23
+ cost_complete = False
24
+ else:
25
+ missing_cost += max(0.0, float(recorded_cost))
26
+ continue
27
+ children = facade._find_subagent_jsonl_files(path)
28
+ parsed = facade._parse_session_jsonl(path, window_start=start, window_end=end)
29
+ if parsed and parsed.get('is_sidechain'):
30
+ continue
31
+ if parsed:
32
+ parsed = facade._parsed_net_of_ledger(parsed, request_ledger)
33
+ if not parsed:
34
+ parsed = {'total_input_tokens': 0, 'total_output_tokens': 0,
35
+ 'total_cache_create_1h': 0, 'total_cache_create_5m': 0,
36
+ 'cache_hit_rate': 0, 'model_usage': {}, 'api_calls': 0,
37
+ 'message_count': 0}
38
+ inp, out = parsed['total_input_tokens'], parsed['total_output_tokens']
39
+ cw1, cw5 = parsed['total_cache_create_1h'], parsed['total_cache_create_5m']
40
+ child_cache_read = 0
41
+ for child in children:
42
+ cp = facade._parse_session_jsonl(child, window_start=start, window_end=end)
43
+ if cp:
44
+ cp = facade._parsed_net_of_ledger(cp, request_ledger)
45
+ inp += cp['total_input_tokens']
46
+ out += cp['total_output_tokens']
47
+ cw1 += cp['total_cache_create_1h']
48
+ cw5 += cp['total_cache_create_5m']
49
+ child_cache_read += cp['total_cache_read']
50
+ if not parsed['api_calls'] and inp + out == 0:
51
+ continue
52
+ if recorded_cost is None:
53
+ cost_complete = False
54
+ else:
55
+ costs += max(0.0, float(recorded_cost))
56
+ usage = facade.json.dumps(parsed['model_usage'])
57
+ hit = parsed['cache_hit_rate'] if parsed['api_calls'] else child_cache_read / inp if inp else 0
58
+ rows.append((inp, out, cw5, cw1, hit, usage, usage,
59
+ parsed['api_calls'], parsed['message_count']))
60
+ total = len(rows) + missing
61
+ cost_share = missing_cost / (costs + missing_cost) if cost_complete and costs + missing_cost > 0 else None
62
+ # Beyond 5% missing, a partial workload is too incomplete to headline.
63
+ if not total or missing / total > 0.05 or (cost_share is not None and cost_share > 0.05):
64
+ return None
65
+ result = facade._price_parent_rows(rows, tier)
66
+ if result:
67
+ result['coverage'] = {'priced_sessions': len(rows), 'total_sessions': total,
68
+ 'missing_recorded_cost_share': cost_share}
69
+ return result
@@ -1,8 +1,159 @@
1
+ """Vendored Tomli 2.2.1 (MIT, Taneli Hukkinen) as a single flat module.
2
+
3
+ Full TOML 1.0 parser used as the Python 3.9/3.10 fallback where stdlib
4
+ tomllib is absent.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ # SPDX-License-Identifier: MIT
9
+ # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
10
+ # Licensed to PSF under a Contributor Agreement.
11
+ # MIT License
12
+ #
13
+ # Copyright (c) 2021 Taneli Hukkinen
14
+ #
15
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ # of this software and associated documentation files (the "Software"), to deal
17
+ # in the Software without restriction, including without limitation the rights
18
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ # copies of the Software, and to permit persons to whom the Software is
20
+ # furnished to do so, subject to the following conditions:
21
+ #
22
+ # The above copyright notice and this permission notice shall be included in all
23
+ # copies or substantial portions of the Software.
24
+ #
25
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ # SOFTWARE.
32
+
33
+ from typing import Any, Callable, Tuple
34
+
35
+ # Type annotations
36
+ ParseFloat = Callable[[str], Any]
37
+ Key = Tuple[str, ...]
38
+ Pos = int
39
+
40
+
41
+ # SPDX-License-Identifier: MIT
42
+ # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
43
+ # Licensed to PSF under a Contributor Agreement.
44
+
45
+
46
+ from datetime import date, datetime, time, timedelta, timezone, tzinfo
47
+ from functools import lru_cache
48
+ import re
49
+ from typing import Any, Final
50
+
51
+
52
+ # E.g.
53
+ # - 00:32:00.999999
54
+ # - 00:32:00
55
+ _TIME_RE_STR: Final = (
56
+ r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"
57
+ )
58
+
59
+ RE_NUMBER: Final = re.compile(
60
+ r"""
61
+ 0
62
+ (?:
63
+ x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex
64
+ |
65
+ b[01](?:_?[01])* # bin
66
+ |
67
+ o[0-7](?:_?[0-7])* # oct
68
+ )
69
+ |
70
+ [+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part
71
+ (?P<floatpart>
72
+ (?:\.[0-9](?:_?[0-9])*)? # optional fractional part
73
+ (?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part
74
+ )
75
+ """,
76
+ flags=re.VERBOSE,
77
+ )
78
+ RE_LOCALTIME: Final = re.compile(_TIME_RE_STR)
79
+ RE_DATETIME: Final = re.compile(
80
+ rf"""
81
+ ([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27
82
+ (?:
83
+ [Tt ]
84
+ {_TIME_RE_STR}
85
+ (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset
86
+ )?
87
+ """,
88
+ flags=re.VERBOSE,
89
+ )
90
+
91
+
92
+ def match_to_datetime(match: re.Match) -> datetime | date:
93
+ """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
94
+
95
+ Raises ValueError if the match does not correspond to a valid date
96
+ or datetime.
97
+ """
98
+ (
99
+ year_str,
100
+ month_str,
101
+ day_str,
102
+ hour_str,
103
+ minute_str,
104
+ sec_str,
105
+ micros_str,
106
+ zulu_time,
107
+ offset_sign_str,
108
+ offset_hour_str,
109
+ offset_minute_str,
110
+ ) = match.groups()
111
+ year, month, day = int(year_str), int(month_str), int(day_str)
112
+ if hour_str is None:
113
+ return date(year, month, day)
114
+ hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
115
+ micros = int(micros_str.ljust(6, "0")) if micros_str else 0
116
+ if offset_sign_str:
117
+ tz: tzinfo | None = cached_tz(
118
+ offset_hour_str, offset_minute_str, offset_sign_str
119
+ )
120
+ elif zulu_time:
121
+ tz = timezone.utc
122
+ else: # local date-time
123
+ tz = None
124
+ return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
125
+
126
+
127
+ # No need to limit cache size. This is only ever called on input
128
+ # that matched RE_DATETIME, so there is an implicit bound of
129
+ # 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.
130
+ @lru_cache(maxsize=None)
131
+ def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
132
+ sign = 1 if sign_str == "+" else -1
133
+ return timezone(
134
+ timedelta(
135
+ hours=sign * int(hour_str),
136
+ minutes=sign * int(minute_str),
137
+ )
138
+ )
139
+
140
+
141
+ def match_to_localtime(match: re.Match) -> time:
142
+ hour_str, minute_str, sec_str, micros_str = match.groups()
143
+ micros = int(micros_str.ljust(6, "0")) if micros_str else 0
144
+ return time(int(hour_str), int(minute_str), int(sec_str), micros)
145
+
146
+
147
+ def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:
148
+ if match.group("floatpart"):
149
+ return parse_float(match.group())
150
+ return int(match.group(), 0)
151
+
152
+
1
153
  # SPDX-License-Identifier: MIT
2
154
  # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
3
155
  # Licensed to PSF under a Contributor Agreement.
4
156
 
5
- from __future__ import annotations
6
157
 
7
158
  from collections.abc import Iterable
8
159
  import string
@@ -11,15 +162,6 @@ from types import MappingProxyType
11
162
  from typing import IO, Any, Final, NamedTuple
12
163
  import warnings
13
164
 
14
- from ._re import (
15
- RE_DATETIME,
16
- RE_LOCALTIME,
17
- RE_NUMBER,
18
- match_to_datetime,
19
- match_to_localtime,
20
- match_to_number,
21
- )
22
- from ._types import Key, ParseFloat, Pos
23
165
 
24
166
  # Inline tables/arrays are implemented using recursion. Pathologically
25
167
  # nested documents cause pure Python to raise RecursionError (which is OK),
@@ -768,3 +910,7 @@ def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:
768
910
  return float_value
769
911
 
770
912
  return safe_parse_float
913
+
914
+
915
+ __all__ = ("loads", "load", "TOMLDecodeError")
916
+ __version__ = "2.2.1" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
@@ -57,14 +57,21 @@ _PAYLOAD_MODULES = (
57
57
  "plugin_env.py",
58
58
  "bash_hook.py",
59
59
  "bash_compress.py",
60
+ "bash_search_results.py",
60
61
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
61
62
  "bash_whitelist.py",
62
63
  "command_filters.py",
64
+ # The 3.9/3.10 TOML parser command_filters lazy-imports when tomllib is
65
+ # absent; without it load_filters() silently returns an empty config.
66
+ "_tomli.py",
63
67
  "spawn_utils.py",
64
68
  "utf8_io.py",
65
69
  # credential_patterns: bash_compress's credential-preservation patterns
66
70
  # (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
67
71
  "credential_patterns.py",
72
+ # credential_patterns imports this at module import time (URL family split
73
+ # under the 1,000-line ratchet); missing = import failure in the payload.
74
+ "credential_url_patterns.py",
68
75
  )
69
76
 
70
77