@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51
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 +448 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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,486 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Read-only reader for Google Antigravity's conversation store.
|
|
3
|
+
|
|
4
|
+
Antigravity (CLI ``agy``, the Antigravity 2.0 desktop app, and the IDE) keeps
|
|
5
|
+
per-conversation SQLite databases under three surface directories inside the
|
|
6
|
+
Antigravity home (``~/.gemini`` by default):
|
|
7
|
+
|
|
8
|
+
<home>/antigravity-cli/conversations/<uuid>.db
|
|
9
|
+
<home>/antigravity/conversations/<uuid>.db
|
|
10
|
+
<home>/antigravity-ide/conversations/<uuid>.db
|
|
11
|
+
|
|
12
|
+
Each database carries a ``gen_metadata`` table (one protobuf blob per model
|
|
13
|
+
generation, decoded by ``antigravity_proto``) and a ``steps`` table (step_type
|
|
14
|
+
14 = user input; a step with a decoded tool name = tool call). Per-surface
|
|
15
|
+
topic/workspace metadata lives in ``<surface>/conversation_summaries.db``.
|
|
16
|
+
|
|
17
|
+
Design constraints (mirroring ``hermes_state.py`` / ``copilot_state.py``):
|
|
18
|
+
|
|
19
|
+
- **Pure stdlib only.** No third-party imports.
|
|
20
|
+
- **Strictly read-only.** Open with ``mode=ro`` (plus ``immutable=1`` for
|
|
21
|
+
databases idle over 60 s, the Hermes precedent, so no ``-wal``/``-shm`` side
|
|
22
|
+
files are created and no lock is taken across hundreds of databases).
|
|
23
|
+
- **Minimal reads.** Only ``gen_metadata.data``, ``steps.step_type`` and step
|
|
24
|
+
``metadata``, and the summaries columns in R21. Prompt text
|
|
25
|
+
(``history.jsonl`` ``display``, summaries ``preview``), tool arguments, and
|
|
26
|
+
``trajectory_metadata_blob`` are NEVER selected (R21).
|
|
27
|
+
- **Schema-defensive.** Missing tables/columns degrade to zero/None; a locked
|
|
28
|
+
or undecodable database is skipped or counted, never fatal.
|
|
29
|
+
- **No hardcoded user paths.** Home comes from ``runtime_env.antigravity_home()``.
|
|
30
|
+
|
|
31
|
+
The three surface directories are SEPARATE populations and are never summed:
|
|
32
|
+
the reader tags every session with its ``surface``.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import json
|
|
38
|
+
import logging
|
|
39
|
+
import sqlite3
|
|
40
|
+
import time
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from typing import Any, Optional
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger(__name__)
|
|
45
|
+
|
|
46
|
+
# ---------------------------------------------------------------------------
|
|
47
|
+
# Constants
|
|
48
|
+
# ---------------------------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
_SURFACES = ("antigravity-cli", "antigravity", "antigravity-ide")
|
|
51
|
+
_CONVERSATIONS_DIR = "conversations"
|
|
52
|
+
_SUMMARIES_DB = "conversation_summaries.db"
|
|
53
|
+
_BUSY_TIMEOUT_SECONDS = 0.25
|
|
54
|
+
_IDLE_SECONDS = 60.0
|
|
55
|
+
|
|
56
|
+
# step_type values observed in the current schema (2026-09-01). A step is a
|
|
57
|
+
# USER INPUT at step_type 14; a step is a TOOL CALL when its metadata decodes a
|
|
58
|
+
# tool name (metadata field 4 sub-field 2). We detect tool calls by the decoded
|
|
59
|
+
# name, not a fixed step_type list, because the tool step-type enum is large
|
|
60
|
+
# and has shifted between releases (e.g. run_command=21, view_file=8).
|
|
61
|
+
_USER_INPUT_STEP_TYPE = 14
|
|
62
|
+
|
|
63
|
+
# Summaries columns we read (R21); nothing else from that table.
|
|
64
|
+
_SUMMARY_COLUMNS = (
|
|
65
|
+
"title",
|
|
66
|
+
"workspace_uris",
|
|
67
|
+
"killed",
|
|
68
|
+
"not_fully_idle",
|
|
69
|
+
"last_modified_time",
|
|
70
|
+
"nesting_depth",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# ---------------------------------------------------------------------------
|
|
75
|
+
# Helpers
|
|
76
|
+
# ---------------------------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _safe_int(value: Any, default: int = 0) -> int:
|
|
80
|
+
try:
|
|
81
|
+
return int(float(value)) if value is not None else default
|
|
82
|
+
except (TypeError, ValueError, OverflowError):
|
|
83
|
+
return default
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _db_is_idle(db_path: Path) -> bool:
|
|
87
|
+
"""True when the db was not modified in the last ``_IDLE_SECONDS``."""
|
|
88
|
+
try:
|
|
89
|
+
return (time.time() - db_path.stat().st_mtime) > _IDLE_SECONDS
|
|
90
|
+
except OSError:
|
|
91
|
+
return True
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _ro_uri(db_path: Path, *, immutable: bool) -> str:
|
|
95
|
+
uri = f"file:{db_path}?mode=ro"
|
|
96
|
+
if immutable:
|
|
97
|
+
uri += "&immutable=1"
|
|
98
|
+
return uri
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _connect(db_path: Path, *, immutable: bool = True) -> sqlite3.Connection:
|
|
102
|
+
"""Open a conversation db read-only. Falls back to plain ``mode=ro`` when
|
|
103
|
+
``immutable=1`` refuses the file (e.g. a live ``-wal`` beside an idle db)."""
|
|
104
|
+
try:
|
|
105
|
+
conn = sqlite3.connect(
|
|
106
|
+
_ro_uri(db_path, immutable=immutable),
|
|
107
|
+
uri=True,
|
|
108
|
+
timeout=_BUSY_TIMEOUT_SECONDS,
|
|
109
|
+
)
|
|
110
|
+
except sqlite3.Error:
|
|
111
|
+
conn = sqlite3.connect(
|
|
112
|
+
_ro_uri(db_path, immutable=False),
|
|
113
|
+
uri=True,
|
|
114
|
+
timeout=_BUSY_TIMEOUT_SECONDS,
|
|
115
|
+
)
|
|
116
|
+
return conn
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _clean_workspace(raw: Any) -> Optional[str]:
|
|
120
|
+
"""Parse summaries ``workspace_uris`` (a JSON array of ``file://`` URIs)
|
|
121
|
+
into the first local path, or None. Never raises."""
|
|
122
|
+
if not isinstance(raw, str) or not raw.strip():
|
|
123
|
+
return None
|
|
124
|
+
try:
|
|
125
|
+
parsed = json.loads(raw)
|
|
126
|
+
except (ValueError, TypeError):
|
|
127
|
+
return None
|
|
128
|
+
if isinstance(parsed, str):
|
|
129
|
+
parsed = [parsed]
|
|
130
|
+
if not isinstance(parsed, list):
|
|
131
|
+
return None
|
|
132
|
+
for uri in parsed:
|
|
133
|
+
if not isinstance(uri, str):
|
|
134
|
+
continue
|
|
135
|
+
if uri.startswith("file://"):
|
|
136
|
+
path = uri[len("file://") :]
|
|
137
|
+
if path:
|
|
138
|
+
return path
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# ---------------------------------------------------------------------------
|
|
143
|
+
# Public API
|
|
144
|
+
# ---------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def home() -> Path:
|
|
148
|
+
"""Return Antigravity's home directory (no hardcoded user paths)."""
|
|
149
|
+
try:
|
|
150
|
+
from runtime_env import antigravity_home
|
|
151
|
+
|
|
152
|
+
return antigravity_home()
|
|
153
|
+
except Exception:
|
|
154
|
+
return Path("~/.gemini").expanduser()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def surface_dirs(explicit_home: Optional[Path] = None) -> list[tuple[str, Path]]:
|
|
158
|
+
"""Return existing ``(surface, path)`` pairs for the three surface dirs."""
|
|
159
|
+
base = explicit_home if explicit_home is not None else home()
|
|
160
|
+
result: list[tuple[str, Path]] = []
|
|
161
|
+
for surface in _SURFACES:
|
|
162
|
+
surface_path = base / surface
|
|
163
|
+
try:
|
|
164
|
+
if surface_path.is_dir() and not surface_path.is_symlink():
|
|
165
|
+
result.append((surface, surface_path))
|
|
166
|
+
except OSError:
|
|
167
|
+
continue
|
|
168
|
+
return result
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def read_summaries(surface_dir: Path) -> dict[str, dict]:
|
|
172
|
+
"""Return ``{conversation_id: summary}`` from ``conversation_summaries.db``.
|
|
173
|
+
|
|
174
|
+
Reads only the R21 columns. Absent/malformed summaries db -> ``{}``.
|
|
175
|
+
"""
|
|
176
|
+
db_path = surface_dir / _SUMMARIES_DB
|
|
177
|
+
if not db_path.is_file():
|
|
178
|
+
return {}
|
|
179
|
+
result: dict[str, dict] = {}
|
|
180
|
+
try:
|
|
181
|
+
conn = sqlite3.connect(
|
|
182
|
+
_ro_uri(db_path, immutable=True), uri=True, timeout=_BUSY_TIMEOUT_SECONDS
|
|
183
|
+
)
|
|
184
|
+
try:
|
|
185
|
+
cols = {
|
|
186
|
+
str(r[1])
|
|
187
|
+
for r in conn.execute("PRAGMA table_info(conversation_summaries)")
|
|
188
|
+
}
|
|
189
|
+
except sqlite3.Error:
|
|
190
|
+
return result
|
|
191
|
+
select_cols = [c for c in _SUMMARY_COLUMNS if c in cols]
|
|
192
|
+
if "conversation_id" not in cols or not select_cols:
|
|
193
|
+
return result
|
|
194
|
+
sql = f"SELECT conversation_id, {', '.join(select_cols)} FROM conversation_summaries"
|
|
195
|
+
try:
|
|
196
|
+
rows = conn.execute(sql).fetchall()
|
|
197
|
+
except sqlite3.Error:
|
|
198
|
+
return result
|
|
199
|
+
for row in rows:
|
|
200
|
+
conv_id = str(row[0])
|
|
201
|
+
summary: dict[str, Any] = {}
|
|
202
|
+
for i, col in enumerate(select_cols):
|
|
203
|
+
summary[col] = row[i + 1]
|
|
204
|
+
summary["workspace"] = _clean_workspace(summary.get("workspace_uris"))
|
|
205
|
+
summary["killed"] = bool(_safe_int(summary.get("killed")))
|
|
206
|
+
summary["not_fully_idle"] = bool(_safe_int(summary.get("not_fully_idle")))
|
|
207
|
+
result[conv_id] = summary
|
|
208
|
+
except (sqlite3.Error, OSError) as exc:
|
|
209
|
+
logger.debug("[antigravity_state] read_summaries(%s): %s", surface_dir, exc)
|
|
210
|
+
return result
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def read_conversation(db_path: Path, *, surface: str = "") -> Optional[dict]:
|
|
214
|
+
"""Read one conversation database into a raw session dict, or None.
|
|
215
|
+
|
|
216
|
+
Returns None when the file is a symlink, lacks a ``gen_metadata`` table,
|
|
217
|
+
or cannot be opened. Aggregates token totals across generations and counts
|
|
218
|
+
tool calls / user inputs from ``steps``. Never raises.
|
|
219
|
+
"""
|
|
220
|
+
try:
|
|
221
|
+
if not db_path.is_file() or db_path.is_symlink():
|
|
222
|
+
return None
|
|
223
|
+
except OSError:
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
conversation_id = db_path.stem
|
|
227
|
+
|
|
228
|
+
# Aggregates.
|
|
229
|
+
generations: list[dict] = []
|
|
230
|
+
totals = {
|
|
231
|
+
"input_tokens": 0,
|
|
232
|
+
"output_tokens": 0,
|
|
233
|
+
"cache_read_tokens": 0,
|
|
234
|
+
"thinking_tokens": 0,
|
|
235
|
+
}
|
|
236
|
+
credit_cost = 0
|
|
237
|
+
consumed_credits = 0
|
|
238
|
+
model_volumes: dict[str, int] = {}
|
|
239
|
+
undecodable_rows = 0
|
|
240
|
+
last_fill: Optional[float] = None
|
|
241
|
+
last_max_context: Optional[int] = None
|
|
242
|
+
|
|
243
|
+
tool_call_count = 0
|
|
244
|
+
user_input_count = 0
|
|
245
|
+
start_time: Optional[float] = None
|
|
246
|
+
end_time: Optional[float] = None
|
|
247
|
+
|
|
248
|
+
try:
|
|
249
|
+
from antigravity_proto import decode_generation, decode_step_metadata
|
|
250
|
+
except Exception:
|
|
251
|
+
return None
|
|
252
|
+
|
|
253
|
+
try:
|
|
254
|
+
conn = _connect(db_path, immutable=_db_is_idle(db_path))
|
|
255
|
+
except (sqlite3.Error, OSError) as exc:
|
|
256
|
+
logger.debug("[antigravity_state] open %s: %s", db_path, exc)
|
|
257
|
+
return None
|
|
258
|
+
|
|
259
|
+
try:
|
|
260
|
+
try:
|
|
261
|
+
tables = {
|
|
262
|
+
r[0]
|
|
263
|
+
for r in conn.execute(
|
|
264
|
+
"SELECT name FROM sqlite_master WHERE type='table'"
|
|
265
|
+
)
|
|
266
|
+
}
|
|
267
|
+
except sqlite3.Error:
|
|
268
|
+
return None
|
|
269
|
+
if "gen_metadata" not in tables:
|
|
270
|
+
return None
|
|
271
|
+
|
|
272
|
+
try:
|
|
273
|
+
gen_rows = conn.execute(
|
|
274
|
+
"SELECT data FROM gen_metadata ORDER BY idx"
|
|
275
|
+
).fetchall()
|
|
276
|
+
except sqlite3.Error:
|
|
277
|
+
gen_rows = []
|
|
278
|
+
for (data,) in gen_rows:
|
|
279
|
+
rec = decode_generation(data)
|
|
280
|
+
if rec is None:
|
|
281
|
+
undecodable_rows += 1
|
|
282
|
+
continue
|
|
283
|
+
generations.append(rec)
|
|
284
|
+
totals["input_tokens"] += rec["input_tokens"]
|
|
285
|
+
totals["output_tokens"] += rec["output_tokens"]
|
|
286
|
+
totals["cache_read_tokens"] += rec["cache_read_tokens"]
|
|
287
|
+
totals["thinking_tokens"] += rec["thinking_tokens"]
|
|
288
|
+
credit_cost += rec.get("credit_cost", 0)
|
|
289
|
+
consumed_credits += rec.get("consumed_credits", 0)
|
|
290
|
+
model = rec.get("model_display_name") or "unknown"
|
|
291
|
+
model_volumes[model] = model_volumes.get(model, 0) + rec["output_tokens"]
|
|
292
|
+
if rec["max_context_tokens"] and rec["max_context_tokens"] > 0:
|
|
293
|
+
last_fill = rec["estimated_tokens_used"] / rec["max_context_tokens"]
|
|
294
|
+
last_max_context = rec["max_context_tokens"]
|
|
295
|
+
|
|
296
|
+
if "steps" in tables:
|
|
297
|
+
try:
|
|
298
|
+
step_rows = conn.execute(
|
|
299
|
+
"SELECT step_type, metadata FROM steps ORDER BY idx"
|
|
300
|
+
).fetchall()
|
|
301
|
+
except sqlite3.Error:
|
|
302
|
+
step_rows = []
|
|
303
|
+
for step_type, metadata in step_rows:
|
|
304
|
+
if step_type == _USER_INPUT_STEP_TYPE:
|
|
305
|
+
user_input_count += 1
|
|
306
|
+
step_meta = decode_step_metadata(metadata) if metadata else None
|
|
307
|
+
if step_meta and step_meta["tool_name"]:
|
|
308
|
+
tool_call_count += 1
|
|
309
|
+
ts = step_meta["timestamp"] if step_meta else None
|
|
310
|
+
if ts is not None:
|
|
311
|
+
if start_time is None or ts < start_time:
|
|
312
|
+
start_time = ts
|
|
313
|
+
if end_time is None or ts > end_time:
|
|
314
|
+
end_time = ts
|
|
315
|
+
finally:
|
|
316
|
+
conn.close()
|
|
317
|
+
|
|
318
|
+
# Timestamp fallback: conversation db mtime when steps carried none.
|
|
319
|
+
if start_time is None:
|
|
320
|
+
try:
|
|
321
|
+
start_time = end_time = db_path.stat().st_mtime
|
|
322
|
+
except OSError:
|
|
323
|
+
pass
|
|
324
|
+
|
|
325
|
+
model_display_name = ""
|
|
326
|
+
if model_volumes:
|
|
327
|
+
model_display_name = max(model_volumes, key=model_volumes.get) # type: ignore[arg-type]
|
|
328
|
+
|
|
329
|
+
return {
|
|
330
|
+
"conversation_id": conversation_id,
|
|
331
|
+
"surface": surface,
|
|
332
|
+
"generations": generations,
|
|
333
|
+
"totals": totals,
|
|
334
|
+
"input_tokens": totals["input_tokens"],
|
|
335
|
+
"output_tokens": totals["output_tokens"],
|
|
336
|
+
"cache_read_tokens": totals["cache_read_tokens"],
|
|
337
|
+
"thinking_tokens": totals["thinking_tokens"],
|
|
338
|
+
"credit_cost": credit_cost,
|
|
339
|
+
"consumed_credits": consumed_credits,
|
|
340
|
+
"last_fill": last_fill,
|
|
341
|
+
"last_max_context": last_max_context,
|
|
342
|
+
"model_display_name": model_display_name,
|
|
343
|
+
"undecodable_rows": undecodable_rows,
|
|
344
|
+
"tool_call_count": tool_call_count,
|
|
345
|
+
"user_input_count": user_input_count,
|
|
346
|
+
"start_time": start_time,
|
|
347
|
+
"end_time": end_time,
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def read_live_conversation(db_path: Path) -> Optional[dict]:
|
|
352
|
+
"""Read a single, possibly-live conversation (the nudge hot path).
|
|
353
|
+
|
|
354
|
+
Same shape as ``read_conversation`` but always opens with plain ``mode=ro``
|
|
355
|
+
(never ``immutable=1``) and a short busy-timeout, for the conversation the
|
|
356
|
+
agent is writing RIGHT NOW. Returns None on any failure. May leave a
|
|
357
|
+
``-shm`` file beside a live database (documented carve-out, KTD6).
|
|
358
|
+
"""
|
|
359
|
+
if db_path is None:
|
|
360
|
+
return None
|
|
361
|
+
db_path = Path(db_path)
|
|
362
|
+
try:
|
|
363
|
+
if not db_path.is_file() or db_path.is_symlink():
|
|
364
|
+
return None
|
|
365
|
+
except OSError:
|
|
366
|
+
return None
|
|
367
|
+
# Read through a fresh connection; force mode=ro (no immutable) regardless
|
|
368
|
+
# of idleness. We reuse read_conversation's core by temporarily computing
|
|
369
|
+
# liveness is irrelevant here -> small wrapper opens without immutable.
|
|
370
|
+
try:
|
|
371
|
+
from antigravity_proto import decode_generation
|
|
372
|
+
except Exception:
|
|
373
|
+
return None
|
|
374
|
+
|
|
375
|
+
try:
|
|
376
|
+
conn = sqlite3.connect(
|
|
377
|
+
f"file:{db_path}?mode=ro", uri=True, timeout=_BUSY_TIMEOUT_SECONDS
|
|
378
|
+
)
|
|
379
|
+
except (sqlite3.Error, OSError):
|
|
380
|
+
return None
|
|
381
|
+
try:
|
|
382
|
+
try:
|
|
383
|
+
conn.execute("PRAGMA query_only = ON")
|
|
384
|
+
except sqlite3.Error:
|
|
385
|
+
pass
|
|
386
|
+
tables = {
|
|
387
|
+
r[0]
|
|
388
|
+
for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
|
389
|
+
}
|
|
390
|
+
if "gen_metadata" not in tables:
|
|
391
|
+
return None
|
|
392
|
+
gen_rows = conn.execute("SELECT data FROM gen_metadata ORDER BY idx").fetchall()
|
|
393
|
+
except sqlite3.Error:
|
|
394
|
+
return None
|
|
395
|
+
finally:
|
|
396
|
+
conn.close()
|
|
397
|
+
|
|
398
|
+
totals = {
|
|
399
|
+
"input_tokens": 0,
|
|
400
|
+
"output_tokens": 0,
|
|
401
|
+
"cache_read_tokens": 0,
|
|
402
|
+
"thinking_tokens": 0,
|
|
403
|
+
}
|
|
404
|
+
last_fill: Optional[float] = None
|
|
405
|
+
for (data,) in gen_rows:
|
|
406
|
+
rec = decode_generation(data)
|
|
407
|
+
if rec is None:
|
|
408
|
+
continue
|
|
409
|
+
totals["input_tokens"] += rec["input_tokens"]
|
|
410
|
+
totals["output_tokens"] += rec["output_tokens"]
|
|
411
|
+
totals["cache_read_tokens"] += rec["cache_read_tokens"]
|
|
412
|
+
totals["thinking_tokens"] += rec["thinking_tokens"]
|
|
413
|
+
if rec["max_context_tokens"] and rec["max_context_tokens"] > 0:
|
|
414
|
+
last_fill = rec["estimated_tokens_used"] / rec["max_context_tokens"]
|
|
415
|
+
return {"last_fill": last_fill, "totals": totals, "conversation_id": db_path.stem}
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def read_all_sessions(explicit_home: Optional[Path] = None) -> list[dict]:
|
|
419
|
+
"""Read every conversation across the three surfaces into raw dicts.
|
|
420
|
+
|
|
421
|
+
Attaches summaries (title/workspace/killed/...) to each session by
|
|
422
|
+
conversation id. Returns [] when home is absent or empty. Never raises.
|
|
423
|
+
"""
|
|
424
|
+
results: list[dict] = []
|
|
425
|
+
for surface, surface_path in surface_dirs(explicit_home):
|
|
426
|
+
summaries = read_summaries(surface_path)
|
|
427
|
+
conv_dir = surface_path / _CONVERSATIONS_DIR
|
|
428
|
+
if not conv_dir.is_dir():
|
|
429
|
+
continue
|
|
430
|
+
try:
|
|
431
|
+
dbs = sorted(conv_dir.glob("*.db"))
|
|
432
|
+
except OSError:
|
|
433
|
+
continue
|
|
434
|
+
for db_path in dbs:
|
|
435
|
+
try:
|
|
436
|
+
session = read_conversation(db_path, surface=surface)
|
|
437
|
+
except Exception as exc:
|
|
438
|
+
logger.debug(
|
|
439
|
+
"[antigravity_state] read_conversation(%s): %s", db_path, exc
|
|
440
|
+
)
|
|
441
|
+
continue
|
|
442
|
+
if session is None:
|
|
443
|
+
continue
|
|
444
|
+
summary = summaries.get(session["conversation_id"], {})
|
|
445
|
+
session["title"] = summary.get("title") or ""
|
|
446
|
+
session["workspace"] = summary.get("workspace")
|
|
447
|
+
session["killed"] = bool(summary.get("killed"))
|
|
448
|
+
session["not_fully_idle"] = bool(summary.get("not_fully_idle"))
|
|
449
|
+
session["last_modified_time"] = summary.get("last_modified_time")
|
|
450
|
+
session["nesting_depth"] = _safe_int(summary.get("nesting_depth"))
|
|
451
|
+
results.append(session)
|
|
452
|
+
return results
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
if __name__ == "__main__":
|
|
456
|
+
sessions = read_all_sessions()
|
|
457
|
+
print(f"surfaces: {[s for s, _ in surface_dirs()]}")
|
|
458
|
+
print(f"sessions: {len(sessions)}")
|
|
459
|
+
with_tokens = [
|
|
460
|
+
s
|
|
461
|
+
for s in sessions
|
|
462
|
+
if s["totals"]["input_tokens"] or s["totals"]["output_tokens"]
|
|
463
|
+
]
|
|
464
|
+
print(f"sessions with any tokens: {len(with_tokens)}")
|
|
465
|
+
if with_tokens:
|
|
466
|
+
s = with_tokens[0]
|
|
467
|
+
print(
|
|
468
|
+
"sample:",
|
|
469
|
+
json.dumps(
|
|
470
|
+
{
|
|
471
|
+
k: s[k]
|
|
472
|
+
for k in (
|
|
473
|
+
"conversation_id",
|
|
474
|
+
"surface",
|
|
475
|
+
"totals",
|
|
476
|
+
"model_display_name",
|
|
477
|
+
"tool_call_count",
|
|
478
|
+
"user_input_count",
|
|
479
|
+
"last_fill",
|
|
480
|
+
"killed",
|
|
481
|
+
)
|
|
482
|
+
},
|
|
483
|
+
default=str,
|
|
484
|
+
indent=2,
|
|
485
|
+
),
|
|
486
|
+
)
|