@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +149 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +776 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +150 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3612 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +129 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +72 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +277 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +423 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +397 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +58739 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""GitHub Copilot session normalizer for Token Optimizer.
|
|
3
|
+
|
|
4
|
+
Converts raw session dicts from ``copilot_state.py`` (CLI plane) and
|
|
5
|
+
``copilot_vscode.py`` (VS Code plane) into TO's canonical session shape —
|
|
6
|
+
the keys measure.py, the savings engine, and the dashboard consume.
|
|
7
|
+
|
|
8
|
+
Token convention (the load-bearing math — see worked examples in
|
|
9
|
+
tests/test_copilot_session.py):
|
|
10
|
+
|
|
11
|
+
The savings engine expects ``total_input_tokens`` = TOTAL billed input
|
|
12
|
+
(fresh + cache_read + cache_write). Copilot's token fields are
|
|
13
|
+
community-reverse-engineered, and the two upstream conventions differ:
|
|
14
|
+
|
|
15
|
+
- OpenAI-style usage (most Copilot models): ``inputTokens`` is the
|
|
16
|
+
AGGREGATE prompt count and ``cacheReadTokens`` is a SUBSET of it.
|
|
17
|
+
Rolling up again would double-count.
|
|
18
|
+
- Anthropic-style usage: ``input_tokens`` is FRESH-ONLY with cache
|
|
19
|
+
fields separate (the Hermes case, which once overstated savings).
|
|
20
|
+
|
|
21
|
+
Detection heuristic: when ``cache_read > input`` the input field cannot
|
|
22
|
+
be an aggregate (a subset can't exceed its superset), so the source is
|
|
23
|
+
fresh-only and we roll up. Otherwise we treat input as aggregate (the
|
|
24
|
+
OpenAI convention Copilot's API surface follows). This is conservative
|
|
25
|
+
in the ambiguous zone: treating fresh-only data as aggregate UNDERSTATES
|
|
26
|
+
cost/savings, never overstates (per the savings-copy mandate: lean
|
|
27
|
+
understates).
|
|
28
|
+
|
|
29
|
+
Cost convention: platform-computed cost first, never
|
|
30
|
+
OpenAI list prices against Copilot sessions.
|
|
31
|
+
|
|
32
|
+
- VS Code plane: ``copilotUsageNanoAiu`` is authoritative.
|
|
33
|
+
1 AIU = 1e9 nanoAIU = 1 AI credit = $0.01 (June 2026 billing).
|
|
34
|
+
- CLI plane: ``session.shutdown.totalPremiumRequests`` × the premium-
|
|
35
|
+
request overage rate (default $0.04, override via
|
|
36
|
+
TOKEN_OPTIMIZER_COPILOT_PREMIUM_RATE). The multiplier for premium
|
|
37
|
+
models is already applied upstream in the count.
|
|
38
|
+
- No cost data → cost_usd 0.0 with cost_source "copilot_no_cost_data"
|
|
39
|
+
(never a fabricated estimate).
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import logging
|
|
45
|
+
import os
|
|
46
|
+
from datetime import datetime, timezone
|
|
47
|
+
from typing import Any, Optional
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger(__name__)
|
|
50
|
+
|
|
51
|
+
_UNKNOWN_MODEL = "unknown"
|
|
52
|
+
|
|
53
|
+
# Per-model context windows AS SERVED BY COPILOT (June 2026). Copilot caps
|
|
54
|
+
# most models at 128K regardless of what the raw model supports elsewhere;
|
|
55
|
+
# OpenAI reasoning models are served with their 200K windows. Default for
|
|
56
|
+
# unknown models under Copilot is 128K — NOT the 1M
|
|
57
|
+
# Claude Code fallback, which suppressed fill nudges by 7-8x.
|
|
58
|
+
_COPILOT_DEFAULT_CONTEXT_WINDOW = 128_000
|
|
59
|
+
_CONTEXT_WINDOW_PREFIXES = (
|
|
60
|
+
("o3", 200_000),
|
|
61
|
+
("o4", 200_000),
|
|
62
|
+
("gpt-4.1", 128_000),
|
|
63
|
+
("gpt-4o", 128_000),
|
|
64
|
+
("gpt-5", 128_000),
|
|
65
|
+
("claude", 128_000),
|
|
66
|
+
("gemini", 128_000),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
_NANO_AIU_PER_CREDIT = 1_000_000_000 # 1 AIU = 1e9 nanoAIU
|
|
70
|
+
_USD_PER_CREDIT_DEFAULT = 0.01
|
|
71
|
+
_USD_PER_PREMIUM_REQUEST_DEFAULT = 0.04
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def context_window_for_model(model: str) -> int:
|
|
75
|
+
"""Context window for a Copilot-served model. 128K default (Q8)."""
|
|
76
|
+
name = (model or "").strip().lower()
|
|
77
|
+
for prefix, window in _CONTEXT_WINDOW_PREFIXES:
|
|
78
|
+
if name.startswith(prefix):
|
|
79
|
+
return window
|
|
80
|
+
return _COPILOT_DEFAULT_CONTEXT_WINDOW
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _safe_topic(value: Any) -> Optional[str]:
|
|
84
|
+
"""Topic is user text persisted to session_log — redact or drop."""
|
|
85
|
+
if not value:
|
|
86
|
+
return None
|
|
87
|
+
try:
|
|
88
|
+
from credential_patterns import redact_credentials
|
|
89
|
+
return redact_credentials(str(value))
|
|
90
|
+
except Exception:
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _safe_int(value: Any, default: int = 0) -> int:
|
|
95
|
+
try:
|
|
96
|
+
return int(float(value)) if value is not None else default
|
|
97
|
+
except (TypeError, ValueError, OverflowError):
|
|
98
|
+
return default
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _safe_float(value: Any, default: float = 0.0) -> float:
|
|
102
|
+
# Contract: returns a numeric default on failure (cost math needs a number).
|
|
103
|
+
# copilot_state._safe_float intentionally differs: returns None (timestamps).
|
|
104
|
+
try:
|
|
105
|
+
return float(value) if value is not None else default
|
|
106
|
+
except (TypeError, ValueError):
|
|
107
|
+
return default
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _env_rate(env_var: str, default: float) -> float:
|
|
111
|
+
raw = os.environ.get(env_var, "").strip()
|
|
112
|
+
if not raw:
|
|
113
|
+
return default
|
|
114
|
+
try:
|
|
115
|
+
rate = float(raw)
|
|
116
|
+
return rate if rate >= 0 else default
|
|
117
|
+
except ValueError:
|
|
118
|
+
return default
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def usd_from_nano_aiu(nano_aiu: int) -> float:
|
|
122
|
+
"""Convert nanoAIU to USD: 1e9 nano = 1 credit = $0.01 (configurable)."""
|
|
123
|
+
usd_per_credit = _env_rate("TOKEN_OPTIMIZER_COPILOT_USD_PER_CREDIT", _USD_PER_CREDIT_DEFAULT)
|
|
124
|
+
return (max(0, nano_aiu) / _NANO_AIU_PER_CREDIT) * usd_per_credit
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def usd_from_premium_requests(premium_requests: float) -> float:
|
|
128
|
+
"""Convert premium-request count to USD at the overage rate (configurable)."""
|
|
129
|
+
rate = _env_rate("TOKEN_OPTIMIZER_COPILOT_PREMIUM_RATE", _USD_PER_PREMIUM_REQUEST_DEFAULT)
|
|
130
|
+
return max(0.0, premium_requests) * rate
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def resolve_billed_input(input_tokens: int, cache_read: int, cache_write: int) -> dict:
|
|
134
|
+
"""Resolve TOTAL billed input from possibly-ambiguous upstream fields.
|
|
135
|
+
|
|
136
|
+
Returns {"total_input": int, "cache_read": int, "cache_write": int,
|
|
137
|
+
"convention": "aggregate"|"fresh_rollup"}. See module docstring for the
|
|
138
|
+
heuristic; all inputs are clamped non-negative first.
|
|
139
|
+
"""
|
|
140
|
+
inp = max(0, input_tokens)
|
|
141
|
+
cr = max(0, cache_read)
|
|
142
|
+
cw = max(0, cache_write)
|
|
143
|
+
# >= not >: when cache_read EQUALS input, input cannot be an aggregate that
|
|
144
|
+
# contains it (a superset is strictly larger), so treat as fresh-only. The
|
|
145
|
+
# > form misread cr==inp as 100% cache hit and halved the cost.
|
|
146
|
+
if cr >= inp:
|
|
147
|
+
# input cannot be an aggregate that contains cache_read → fresh-only.
|
|
148
|
+
return {
|
|
149
|
+
"total_input": inp + cr + cw,
|
|
150
|
+
"cache_read": cr,
|
|
151
|
+
"cache_write": cw,
|
|
152
|
+
"convention": "fresh_rollup",
|
|
153
|
+
}
|
|
154
|
+
if cw <= inp:
|
|
155
|
+
# OpenAI aggregate convention: inp already contains the cache fields.
|
|
156
|
+
return {"total_input": inp, "cache_read": cr, "cache_write": cw, "convention": "aggregate"}
|
|
157
|
+
# cw > inp means cache_write cannot be a subset of inp, so it is a separate
|
|
158
|
+
# billed charge: inp + cw is the minimal consistent total (not a double
|
|
159
|
+
# count). Distinct label so a downstream caller can spot the odd shape.
|
|
160
|
+
return {"total_input": inp + cw, "cache_read": cr, "cache_write": cw, "convention": "aggregate_cw_separate"}
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _quality(input_tokens: int, output_tokens: int, message_count: int, model: str,
|
|
164
|
+
ctx_window: int, cache_read: int) -> dict:
|
|
165
|
+
"""Quality score from the signals Copilot exposes.
|
|
166
|
+
|
|
167
|
+
Reuses the runtime-agnostic scorer from hermes_session (same constrained-
|
|
168
|
+
signal situation: session-level fields only). Falls back to a minimal
|
|
169
|
+
fill-based score if that import ever breaks.
|
|
170
|
+
"""
|
|
171
|
+
try:
|
|
172
|
+
from hermes_session import compute_quality_score
|
|
173
|
+
|
|
174
|
+
return compute_quality_score(
|
|
175
|
+
input_tokens=input_tokens,
|
|
176
|
+
output_tokens=output_tokens,
|
|
177
|
+
message_count=message_count,
|
|
178
|
+
model=model,
|
|
179
|
+
context_window=ctx_window,
|
|
180
|
+
cache_read=cache_read,
|
|
181
|
+
)
|
|
182
|
+
except Exception as exc: # pragma: no cover - defensive fallback
|
|
183
|
+
logger.debug("[copilot_session] quality scorer unavailable: %s", exc)
|
|
184
|
+
fill = min(1.0, (input_tokens + cache_read) / ctx_window) if ctx_window else 0.0
|
|
185
|
+
score = max(0.0, 100.0 - fill * 50.0)
|
|
186
|
+
band = "healthy" if score >= 70 else ("watch" if score >= 50 else "critical")
|
|
187
|
+
grade = "A" if score >= 90 else ("B" if score >= 75 else ("C" if score >= 60 else "D"))
|
|
188
|
+
# Mirror the real scorer's top-level keys so downstream consumers
|
|
189
|
+
# (dashboard, tests) never KeyError on the degraded path.
|
|
190
|
+
return {
|
|
191
|
+
"score": round(score, 1),
|
|
192
|
+
"grade": grade,
|
|
193
|
+
"band": band,
|
|
194
|
+
"fill_ratio": round(fill, 4),
|
|
195
|
+
"context_window_used": ctx_window,
|
|
196
|
+
"signals": {"fill": round(fill, 4)},
|
|
197
|
+
"signal_scores": {"fill": round(fill * 100, 1)},
|
|
198
|
+
"signals_active": ["context_fill"],
|
|
199
|
+
"signals_omitted": [],
|
|
200
|
+
"estimated": True,
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _parse_ts(value: Any) -> Optional[str]:
|
|
205
|
+
"""Epoch seconds → ISO-8601 UTC string (None when absent/invalid)."""
|
|
206
|
+
if value is None:
|
|
207
|
+
return None
|
|
208
|
+
try:
|
|
209
|
+
return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat()
|
|
210
|
+
except (TypeError, ValueError, OSError, OverflowError):
|
|
211
|
+
return None
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _base_canonical(slug: str, runtime_source: str) -> dict:
|
|
215
|
+
"""Shared canonical skeleton with the placeholder keys measure.py checks."""
|
|
216
|
+
return {
|
|
217
|
+
"slug": slug,
|
|
218
|
+
"topic": None,
|
|
219
|
+
"first_ts": None,
|
|
220
|
+
"duration_minutes": 0.0,
|
|
221
|
+
"total_input_tokens": 0,
|
|
222
|
+
"total_output_tokens": 0,
|
|
223
|
+
"total_cache_read": 0,
|
|
224
|
+
"total_cache_create": 0,
|
|
225
|
+
"total_cache_create_1h": 0,
|
|
226
|
+
"total_cache_create_5m": 0,
|
|
227
|
+
"model_context_window": _COPILOT_DEFAULT_CONTEXT_WINDOW,
|
|
228
|
+
"cache_hit_rate": 0.0,
|
|
229
|
+
"cost_usd": 0.0,
|
|
230
|
+
"cost_source": "copilot_no_cost_data",
|
|
231
|
+
"credits": None,
|
|
232
|
+
"model": _UNKNOWN_MODEL,
|
|
233
|
+
"model_family": None,
|
|
234
|
+
"model_usage": {},
|
|
235
|
+
"model_usage_breakdown": {},
|
|
236
|
+
"message_count": 0,
|
|
237
|
+
"api_calls": 0,
|
|
238
|
+
"tool_calls": {"total": 0},
|
|
239
|
+
"estimated": False,
|
|
240
|
+
"token_source": runtime_source,
|
|
241
|
+
"runtime": "copilot",
|
|
242
|
+
"version": None,
|
|
243
|
+
"avg_call_gap_seconds": None,
|
|
244
|
+
"max_call_gap_seconds": None,
|
|
245
|
+
"p95_call_gap_seconds": None,
|
|
246
|
+
"rate_limits": None,
|
|
247
|
+
"effort": None,
|
|
248
|
+
"effort_breakdown": {},
|
|
249
|
+
"skills_used": {},
|
|
250
|
+
"subagents_used": {},
|
|
251
|
+
"tool_duration_p90_ms": None,
|
|
252
|
+
"task_duration_ms_max": None,
|
|
253
|
+
"ttft_ms_avg": None,
|
|
254
|
+
"end_reason": "",
|
|
255
|
+
"archived": False,
|
|
256
|
+
"cwd": None,
|
|
257
|
+
"billing_provider": "github-copilot",
|
|
258
|
+
"incomplete": False,
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def normalize_cli_session(raw: dict) -> Optional[dict]:
|
|
263
|
+
"""Normalize a copilot_state.read_session() dict (CLI plane)."""
|
|
264
|
+
if not raw:
|
|
265
|
+
return None
|
|
266
|
+
|
|
267
|
+
# isinstance guard, not `or {}`: a non-empty list is truthy and would crash
|
|
268
|
+
# the .items() loop below with AttributeError.
|
|
269
|
+
models = raw.get("models") if isinstance(raw.get("models"), dict) else {}
|
|
270
|
+
output_observed = max(0, _safe_int(raw.get("output_tokens_observed")))
|
|
271
|
+
message_count = _safe_int(raw.get("message_count"))
|
|
272
|
+
|
|
273
|
+
# Aggregate across models with per-model convention resolution.
|
|
274
|
+
total_input = 0
|
|
275
|
+
total_output = 0
|
|
276
|
+
total_cr = 0
|
|
277
|
+
total_cw = 0
|
|
278
|
+
api_calls = 0
|
|
279
|
+
model_usage = {}
|
|
280
|
+
model_usage_breakdown = {}
|
|
281
|
+
estimated = False
|
|
282
|
+
for model_name, entry in models.items():
|
|
283
|
+
if not isinstance(entry, dict):
|
|
284
|
+
continue
|
|
285
|
+
resolved = resolve_billed_input(
|
|
286
|
+
_safe_int(entry.get("input_tokens")),
|
|
287
|
+
_safe_int(entry.get("cache_read_tokens")),
|
|
288
|
+
_safe_int(entry.get("cache_write_tokens")),
|
|
289
|
+
)
|
|
290
|
+
out = max(0, _safe_int(entry.get("output_tokens")))
|
|
291
|
+
total_input += resolved["total_input"]
|
|
292
|
+
total_output += out
|
|
293
|
+
total_cr += resolved["cache_read"]
|
|
294
|
+
total_cw += resolved["cache_write"]
|
|
295
|
+
api_calls += max(0, _safe_int(entry.get("api_calls")))
|
|
296
|
+
billable = resolved["total_input"] + out
|
|
297
|
+
key = str(model_name) or _UNKNOWN_MODEL
|
|
298
|
+
model_usage[key] = billable
|
|
299
|
+
# Cap cache_create so fresh+cache_read+cache_create == total_input. In
|
|
300
|
+
# the aggregate convention cr+cw can exceed inp; without the cap the
|
|
301
|
+
# breakdown would sum higher than model_usage and the dashboard would
|
|
302
|
+
# show two conflicting totals for one session.
|
|
303
|
+
_avail_for_cw = max(0, resolved["total_input"] - resolved["cache_read"])
|
|
304
|
+
_cw = min(resolved["cache_write"], _avail_for_cw)
|
|
305
|
+
model_usage_breakdown[key] = {
|
|
306
|
+
"fresh_input": max(0, _avail_for_cw - _cw),
|
|
307
|
+
"cache_read": resolved["cache_read"],
|
|
308
|
+
"cache_create": _cw,
|
|
309
|
+
"output": out,
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
# Crash/incomplete sessions may have NO model totals; fall back to the
|
|
313
|
+
# persisted observations so the session still counts (honest "estimated").
|
|
314
|
+
if total_input == 0 and total_output == 0:
|
|
315
|
+
if output_observed == 0 and message_count == 0:
|
|
316
|
+
return None # genuinely empty session
|
|
317
|
+
total_output = output_observed
|
|
318
|
+
content_chars = max(0, _safe_int(raw.get("content_chars")))
|
|
319
|
+
checkpoint_tokens = raw.get("checkpoint_tokens")
|
|
320
|
+
if checkpoint_tokens is not None:
|
|
321
|
+
total_input = max(0, _safe_int(checkpoint_tokens))
|
|
322
|
+
elif content_chars:
|
|
323
|
+
total_input = content_chars // 4 # chars/4 estimate, flagged below
|
|
324
|
+
estimated = True
|
|
325
|
+
|
|
326
|
+
# Primary model = highest billable volume.
|
|
327
|
+
primary_model = _UNKNOWN_MODEL
|
|
328
|
+
if model_usage:
|
|
329
|
+
primary_model = max(model_usage, key=lambda k: model_usage[k])
|
|
330
|
+
ctx_window = context_window_for_model(primary_model)
|
|
331
|
+
|
|
332
|
+
# Cost: premium-request pass-through only (C5 — no list-price math).
|
|
333
|
+
premium = raw.get("total_premium_requests")
|
|
334
|
+
if premium is not None:
|
|
335
|
+
cost_usd = usd_from_premium_requests(_safe_float(premium))
|
|
336
|
+
cost_source = "copilot_premium_requests"
|
|
337
|
+
credits = None
|
|
338
|
+
else:
|
|
339
|
+
cost_usd = 0.0
|
|
340
|
+
cost_source = "copilot_no_cost_data"
|
|
341
|
+
credits = None
|
|
342
|
+
|
|
343
|
+
duration_minutes = 0.0
|
|
344
|
+
st, et = raw.get("start_time"), raw.get("end_time")
|
|
345
|
+
if st is not None and et is not None:
|
|
346
|
+
try:
|
|
347
|
+
duration_minutes = max(0.0, (float(et) - float(st)) / 60.0)
|
|
348
|
+
except (TypeError, ValueError):
|
|
349
|
+
duration_minutes = 0.0
|
|
350
|
+
|
|
351
|
+
cache_hit_rate = (total_cr / total_input) if total_input > 0 else 0.0
|
|
352
|
+
quality = _quality(total_input, total_output, message_count, primary_model, ctx_window, total_cr)
|
|
353
|
+
|
|
354
|
+
session = _base_canonical(str(raw.get("session_id") or ""), "copilot_cli_events")
|
|
355
|
+
session.update(
|
|
356
|
+
{
|
|
357
|
+
"first_ts": _parse_ts(st),
|
|
358
|
+
"last_ts": _parse_ts(et),
|
|
359
|
+
"duration_minutes": round(duration_minutes, 2),
|
|
360
|
+
"total_input_tokens": total_input,
|
|
361
|
+
"total_output_tokens": total_output,
|
|
362
|
+
"total_cache_read": total_cr,
|
|
363
|
+
"total_cache_create": total_cw,
|
|
364
|
+
"total_cache_create_1h": total_cw,
|
|
365
|
+
"model_context_window": ctx_window,
|
|
366
|
+
"cache_hit_rate": round(cache_hit_rate, 4),
|
|
367
|
+
"cost_usd": round(cost_usd, 6),
|
|
368
|
+
"cost_source": cost_source,
|
|
369
|
+
"credits": credits,
|
|
370
|
+
"model": primary_model,
|
|
371
|
+
"model_usage": model_usage,
|
|
372
|
+
"model_usage_breakdown": model_usage_breakdown,
|
|
373
|
+
"message_count": message_count,
|
|
374
|
+
"api_calls": api_calls,
|
|
375
|
+
"tool_calls": {"total": len(raw.get("tool_calls") or [])},
|
|
376
|
+
"estimated": estimated,
|
|
377
|
+
"version": raw.get("version"),
|
|
378
|
+
"cwd": raw.get("cwd"),
|
|
379
|
+
"incomplete": not bool(raw.get("complete")),
|
|
380
|
+
"end_reason": raw.get("incomplete_reason") or ("shutdown" if raw.get("complete") else ""),
|
|
381
|
+
"quality": quality,
|
|
382
|
+
"quality_score": quality.get("score"),
|
|
383
|
+
"quality_grade": quality.get("grade"),
|
|
384
|
+
"quality_band": quality.get("band"),
|
|
385
|
+
}
|
|
386
|
+
)
|
|
387
|
+
return session
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def normalize_vscode_session(raw: dict) -> Optional[dict]:
|
|
391
|
+
"""Normalize a copilot_vscode.read_sessions() dict (VS Code plane)."""
|
|
392
|
+
if not raw:
|
|
393
|
+
return None
|
|
394
|
+
totals = raw.get("totals") or {}
|
|
395
|
+
requests = raw.get("requests") or []
|
|
396
|
+
|
|
397
|
+
input_tokens = max(0, _safe_int(totals.get("input_tokens")))
|
|
398
|
+
output_tokens = max(0, _safe_int(totals.get("output_tokens")))
|
|
399
|
+
cached = max(0, _safe_int(totals.get("cached_tokens")))
|
|
400
|
+
nano_aiu = totals.get("nano_aiu")
|
|
401
|
+
request_count = max(0, _safe_int(totals.get("requests"), len(requests)))
|
|
402
|
+
|
|
403
|
+
if input_tokens == 0 and output_tokens == 0 and request_count == 0:
|
|
404
|
+
return None
|
|
405
|
+
|
|
406
|
+
resolved = resolve_billed_input(input_tokens, cached, 0)
|
|
407
|
+
total_input = resolved["total_input"]
|
|
408
|
+
|
|
409
|
+
# Per-model split from requests.
|
|
410
|
+
model_usage = {}
|
|
411
|
+
model_usage_breakdown = {}
|
|
412
|
+
ttft_values = []
|
|
413
|
+
for req in requests:
|
|
414
|
+
if not isinstance(req, dict):
|
|
415
|
+
continue
|
|
416
|
+
model = str(req.get("model") or _UNKNOWN_MODEL)
|
|
417
|
+
r = resolve_billed_input(
|
|
418
|
+
_safe_int(req.get("input_tokens")),
|
|
419
|
+
_safe_int(req.get("cached_tokens")),
|
|
420
|
+
0,
|
|
421
|
+
)
|
|
422
|
+
out = max(0, _safe_int(req.get("output_tokens")))
|
|
423
|
+
model_usage[model] = model_usage.get(model, 0) + r["total_input"] + out
|
|
424
|
+
slot = model_usage_breakdown.setdefault(
|
|
425
|
+
model, {"fresh_input": 0, "cache_read": 0, "cache_create": 0, "output": 0}
|
|
426
|
+
)
|
|
427
|
+
slot["fresh_input"] += max(0, r["total_input"] - r["cache_read"])
|
|
428
|
+
slot["cache_read"] += r["cache_read"]
|
|
429
|
+
slot["output"] += out
|
|
430
|
+
ttft = req.get("ttft_ms")
|
|
431
|
+
if ttft is not None:
|
|
432
|
+
ttft_values.append(_safe_float(ttft))
|
|
433
|
+
|
|
434
|
+
primary_model = max(model_usage, key=lambda k: model_usage[k]) if model_usage else _UNKNOWN_MODEL
|
|
435
|
+
ctx_window = context_window_for_model(primary_model)
|
|
436
|
+
|
|
437
|
+
# Cost: nanoAIU pass-through is authoritative (C5).
|
|
438
|
+
if nano_aiu is not None:
|
|
439
|
+
nano = max(0, _safe_int(nano_aiu))
|
|
440
|
+
cost_usd = usd_from_nano_aiu(nano)
|
|
441
|
+
credits = nano / _NANO_AIU_PER_CREDIT
|
|
442
|
+
cost_source = "copilot_nano_aiu"
|
|
443
|
+
else:
|
|
444
|
+
cost_usd = 0.0
|
|
445
|
+
credits = None
|
|
446
|
+
cost_source = "copilot_no_cost_data"
|
|
447
|
+
|
|
448
|
+
cache_hit_rate = (resolved["cache_read"] / total_input) if total_input > 0 else 0.0
|
|
449
|
+
# One user message typically drives one llm_request; summing them would
|
|
450
|
+
# ~2x the turn count and depress message-density quality signals. Take the
|
|
451
|
+
# larger of the two as the meaningful turn count.
|
|
452
|
+
user_messages = max(0, _safe_int(raw.get("user_messages")))
|
|
453
|
+
message_count = max(user_messages, request_count)
|
|
454
|
+
quality = _quality(total_input, output_tokens, message_count, primary_model, ctx_window, resolved["cache_read"])
|
|
455
|
+
|
|
456
|
+
session = _base_canonical(
|
|
457
|
+
f"vscode-{raw.get('workspace_hash', '')[:8]}-{raw.get('session_id', '')}",
|
|
458
|
+
str(raw.get("data_source") or "copilot_vscode_debuglogs"),
|
|
459
|
+
)
|
|
460
|
+
session.update(
|
|
461
|
+
{
|
|
462
|
+
"topic": _safe_topic(raw.get("title")),
|
|
463
|
+
"first_ts": _parse_ts(raw.get("first_ts_epoch")),
|
|
464
|
+
"total_input_tokens": total_input,
|
|
465
|
+
"total_output_tokens": output_tokens,
|
|
466
|
+
"total_cache_read": resolved["cache_read"],
|
|
467
|
+
"model_context_window": ctx_window,
|
|
468
|
+
"cache_hit_rate": round(cache_hit_rate, 4),
|
|
469
|
+
"cost_usd": round(cost_usd, 6),
|
|
470
|
+
"cost_source": cost_source,
|
|
471
|
+
"credits": round(credits, 4) if credits is not None else None,
|
|
472
|
+
"model": primary_model,
|
|
473
|
+
"model_usage": model_usage,
|
|
474
|
+
"model_usage_breakdown": model_usage_breakdown,
|
|
475
|
+
"message_count": message_count,
|
|
476
|
+
"api_calls": request_count,
|
|
477
|
+
"tool_calls": {"total": len(raw.get("tool_calls") or [])},
|
|
478
|
+
"ttft_ms_avg": round(sum(ttft_values) / len(ttft_values), 1) if ttft_values else None,
|
|
479
|
+
"quality": quality,
|
|
480
|
+
"quality_score": quality.get("score"),
|
|
481
|
+
"quality_grade": quality.get("grade"),
|
|
482
|
+
"quality_band": quality.get("band"),
|
|
483
|
+
}
|
|
484
|
+
)
|
|
485
|
+
return session
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def normalize_session(raw: dict) -> Optional[dict]:
|
|
489
|
+
"""Dispatch by data_source. The two planes are separate session
|
|
490
|
+
populations and are NEVER merged or summed."""
|
|
491
|
+
if not isinstance(raw, dict):
|
|
492
|
+
return None
|
|
493
|
+
source = str(raw.get("data_source") or "")
|
|
494
|
+
if source.startswith("copilot_vscode"):
|
|
495
|
+
return normalize_vscode_session(raw)
|
|
496
|
+
return normalize_cli_session(raw)
|