@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,119 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import tempfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def atomic_write(path: Path, content: str, mode: int = 0o600, *, crlf: bool = False,
|
|
11
|
+
replace_symlink: bool = False) -> None:
|
|
12
|
+
"""Write content to path atomically via tempfile+rename.
|
|
13
|
+
|
|
14
|
+
When ``crlf`` is True, ``\\n`` in *content* is converted to ``\\r\\n``
|
|
15
|
+
before writing so that CRLF line endings are preserved through the
|
|
16
|
+
install/uninstall round-trip.
|
|
17
|
+
|
|
18
|
+
By default a symlinked *path* is followed and its TARGET is replaced
|
|
19
|
+
(dotfile managers point configs at a master copy and expect that).
|
|
20
|
+
Callers that must replace the symlink ITSELF (never write through it to an
|
|
21
|
+
attacker-chosen target) pass ``replace_symlink=True``.
|
|
22
|
+
"""
|
|
23
|
+
if crlf:
|
|
24
|
+
content = content.replace("\n", "\r\n")
|
|
25
|
+
write_path = path if replace_symlink or not path.is_symlink() else path.resolve(strict=False)
|
|
26
|
+
write_path.parent.mkdir(parents=True, exist_ok=True)
|
|
27
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{write_path.name}.", dir=str(write_path.parent), text=True)
|
|
28
|
+
try:
|
|
29
|
+
with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
|
|
30
|
+
handle.write(content)
|
|
31
|
+
os.chmod(tmp_name, mode)
|
|
32
|
+
os.replace(tmp_name, write_path)
|
|
33
|
+
except BaseException:
|
|
34
|
+
try:
|
|
35
|
+
os.unlink(tmp_name)
|
|
36
|
+
except OSError:
|
|
37
|
+
pass
|
|
38
|
+
raise
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def read_config_text(path: Path) -> tuple[str, bool]:
|
|
42
|
+
"""Read a TOML config file, returning ``(text_with_lf, uses_crlf)``.
|
|
43
|
+
|
|
44
|
+
The text is decoded as UTF-8 with ``\\r\\n`` normalized to ``\\n`` so
|
|
45
|
+
that downstream regex patterns (which assume LF) work unchanged.
|
|
46
|
+
``uses_crlf`` is ``True`` when the original file contained ``\\r\\n``,
|
|
47
|
+
so callers can pass it to :func:`atomic_write` to restore CRLF on write.
|
|
48
|
+
Raises ``OSError`` if the file cannot be read.
|
|
49
|
+
"""
|
|
50
|
+
raw = path.read_bytes()
|
|
51
|
+
crlf = b"\r\n" in raw
|
|
52
|
+
text = raw.decode("utf-8")
|
|
53
|
+
if crlf:
|
|
54
|
+
text = text.replace("\r\n", "\n")
|
|
55
|
+
return text, crlf
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def atomic_write_json(path: Path, data: Any, mode: int = 0o600,
|
|
59
|
+
replace_symlink: bool = False) -> None:
|
|
60
|
+
"""Serialize data as JSON and write to path atomically."""
|
|
61
|
+
atomic_write(path, json.dumps(data, indent=2, sort_keys=False) + "\n", mode=mode,
|
|
62
|
+
replace_symlink=replace_symlink)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def validate_codex_path(path: Path, home: Path) -> None:
|
|
66
|
+
"""Raise ValueError if path or its parent escapes home or is a symlink."""
|
|
67
|
+
if home.exists():
|
|
68
|
+
if home.is_symlink() or not home.is_dir():
|
|
69
|
+
raise ValueError(f"{home} must be a real directory")
|
|
70
|
+
home_resolved = home.resolve(strict=True)
|
|
71
|
+
else:
|
|
72
|
+
home_resolved = home.resolve(strict=False)
|
|
73
|
+
|
|
74
|
+
parent = path.parent
|
|
75
|
+
if parent.exists():
|
|
76
|
+
if parent.is_symlink() or not parent.is_dir():
|
|
77
|
+
raise ValueError(f"{parent} must be a real directory")
|
|
78
|
+
if not parent.resolve(strict=True).is_relative_to(home_resolved):
|
|
79
|
+
raise ValueError(f"{parent} escapes Codex home")
|
|
80
|
+
if path.exists():
|
|
81
|
+
if path.is_symlink():
|
|
82
|
+
target_resolved = path.resolve(strict=False)
|
|
83
|
+
user_home = Path.home().resolve(strict=True)
|
|
84
|
+
if not target_resolved.is_relative_to(user_home):
|
|
85
|
+
raise ValueError(f"{path} symlink target escapes user home")
|
|
86
|
+
return
|
|
87
|
+
if not path.resolve(strict=True).is_relative_to(home_resolved):
|
|
88
|
+
raise ValueError(f"{path} escapes Codex home")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def ensure_codex_child(home: Path, *parts: str, create: bool = True) -> Path:
|
|
92
|
+
"""Return a path under home, creating missing directories and validating symlinks."""
|
|
93
|
+
if home.exists():
|
|
94
|
+
if home.is_symlink() or not home.is_dir():
|
|
95
|
+
raise ValueError(f"{home} must be a real directory")
|
|
96
|
+
elif create:
|
|
97
|
+
home.mkdir(mode=0o700)
|
|
98
|
+
home_resolved = home.resolve(strict=home.exists())
|
|
99
|
+
|
|
100
|
+
target = home.joinpath(*parts)
|
|
101
|
+
parent = target.parent
|
|
102
|
+
if parent.exists():
|
|
103
|
+
if parent.is_symlink() or not parent.is_dir():
|
|
104
|
+
raise ValueError(f"{parent} must be a real directory")
|
|
105
|
+
parent_resolved = parent.resolve(strict=True)
|
|
106
|
+
if not parent_resolved.is_relative_to(home_resolved):
|
|
107
|
+
raise ValueError(f"{parent} escapes Codex home")
|
|
108
|
+
elif create:
|
|
109
|
+
parent.mkdir(mode=0o700)
|
|
110
|
+
if target.exists() and target.is_symlink():
|
|
111
|
+
target_resolved = target.resolve(strict=False)
|
|
112
|
+
user_home = Path.home().resolve(strict=True)
|
|
113
|
+
if not target_resolved.is_relative_to(user_home):
|
|
114
|
+
raise ValueError(f"{target} symlink target escapes user home")
|
|
115
|
+
return target
|
|
116
|
+
target_resolved = target.resolve(strict=target.exists())
|
|
117
|
+
if not target_resolved.is_relative_to(home_resolved):
|
|
118
|
+
raise ValueError(f"{target} escapes Codex home")
|
|
119
|
+
return target
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Incremental, bounded-memory telemetry index for large Codex transcripts.
|
|
2
|
+
|
|
3
|
+
Raw tool output is never copied into the index. Each pass commits at most
|
|
4
|
+
64 MiB of new input; pending files are revisited even when their mtime is idle.
|
|
5
|
+
"""
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import sqlite3
|
|
9
|
+
import time
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from plugin_env import resolve_snapshot_dir
|
|
13
|
+
|
|
14
|
+
PASS_BYTES = 64 * 1024 * 1024
|
|
15
|
+
LINE_BYTES = 16 * 1024 * 1024
|
|
16
|
+
SCHEMA_VERSION = 2
|
|
17
|
+
|
|
18
|
+
_SCHEMA = '''
|
|
19
|
+
CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, identity TEXT, offset INTEGER,
|
|
20
|
+
size INTEGER, skipped INTEGER, revision INTEGER, mtime INTEGER);
|
|
21
|
+
CREATE TABLE IF NOT EXISTS records(path TEXT, offset INTEGER, data TEXT,
|
|
22
|
+
PRIMARY KEY(path, offset));
|
|
23
|
+
'''
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _open_db(db_path):
|
|
27
|
+
conn = sqlite3.connect(db_path, timeout=5.0)
|
|
28
|
+
try:
|
|
29
|
+
conn.execute('PRAGMA busy_timeout=5000')
|
|
30
|
+
conn.execute('PRAGMA journal_mode=WAL')
|
|
31
|
+
conn.executescript(_SCHEMA)
|
|
32
|
+
if 'mtime' not in {row[1] for row in conn.execute('PRAGMA table_info(files)')}:
|
|
33
|
+
try:
|
|
34
|
+
conn.execute('ALTER TABLE files ADD COLUMN mtime INTEGER')
|
|
35
|
+
except sqlite3.OperationalError:
|
|
36
|
+
pass # concurrent migration: column already added
|
|
37
|
+
except Exception:
|
|
38
|
+
# On Windows an abandoned handle pins the file and defeats the
|
|
39
|
+
# unlink-and-rebuild below, so a failed open must not leak it.
|
|
40
|
+
conn.close()
|
|
41
|
+
raise
|
|
42
|
+
return conn
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _connect():
|
|
46
|
+
root = resolve_snapshot_dir()
|
|
47
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
48
|
+
db_path = root / 'codex-log-index.db'
|
|
49
|
+
# Locked/contended is not corruption: never delete a live index. A burst
|
|
50
|
+
# of concurrent first-opens races the journal_mode/schema setup and a
|
|
51
|
+
# writer mid-commit owns the file, so a lock can outlast the in-connection
|
|
52
|
+
# busy_timeout (and lock-upgrade deadlocks return BUSY without consulting
|
|
53
|
+
# the busy handler at all). Wait it out on a deadline before giving up.
|
|
54
|
+
deadline = time.monotonic() + 5
|
|
55
|
+
while True:
|
|
56
|
+
try:
|
|
57
|
+
return _open_db(db_path)
|
|
58
|
+
except sqlite3.OperationalError:
|
|
59
|
+
if time.monotonic() >= deadline:
|
|
60
|
+
raise
|
|
61
|
+
time.sleep(0.1)
|
|
62
|
+
except sqlite3.DatabaseError:
|
|
63
|
+
break # corrupt DB: self-heal by removing and rebuilding
|
|
64
|
+
# Windows refuses to unlink a file while any handle is open -- _open_db
|
|
65
|
+
# already closed the broken connection, but an indexer or another process
|
|
66
|
+
# can hold a transient share lock, so retry each file briefly.
|
|
67
|
+
for suffix in ('', '-wal', '-shm'):
|
|
68
|
+
target = db_path.parent / (db_path.name + suffix)
|
|
69
|
+
for _ in range(10):
|
|
70
|
+
try:
|
|
71
|
+
target.unlink()
|
|
72
|
+
break
|
|
73
|
+
except FileNotFoundError:
|
|
74
|
+
break
|
|
75
|
+
except OSError:
|
|
76
|
+
time.sleep(0.1)
|
|
77
|
+
return _open_db(db_path)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def pending(filepath):
|
|
81
|
+
path = Path(filepath).resolve()
|
|
82
|
+
try:
|
|
83
|
+
conn = _connect()
|
|
84
|
+
try:
|
|
85
|
+
row = conn.execute('SELECT offset,revision,mtime FROM files WHERE path=?', (str(path),)).fetchone()
|
|
86
|
+
stat = path.stat()
|
|
87
|
+
return (row is None or row[0] != stat.st_size or
|
|
88
|
+
row[1] != SCHEMA_VERSION or row[2] != stat.st_mtime_ns)
|
|
89
|
+
finally:
|
|
90
|
+
conn.close()
|
|
91
|
+
except (OSError, sqlite3.Error):
|
|
92
|
+
return True
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _slim(record):
|
|
96
|
+
from codex_session import _extract_text, _event_output_text
|
|
97
|
+
payload = record.get('payload')
|
|
98
|
+
if not isinstance(payload, dict):
|
|
99
|
+
return None
|
|
100
|
+
kind = payload.get('type')
|
|
101
|
+
if record.get('type') in ('session_meta', 'turn_context'):
|
|
102
|
+
fields = ('id', 'cwd', 'cli_version', 'model', 'effort', 'thread_settings', 'collaboration_mode')
|
|
103
|
+
payload = {k: payload[k] for k in fields if k in payload}
|
|
104
|
+
elif kind in ('user_message', 'agent_message', 'message'):
|
|
105
|
+
text = _extract_text(payload)
|
|
106
|
+
payload = {'type': kind, 'role': payload.get('role'), 'message': text[:1000],
|
|
107
|
+
'content': text[:1000], '_optimizer_chars': len(text)}
|
|
108
|
+
elif kind in ('function_call_output', 'custom_tool_call_output', 'exec_command_end', 'patch_apply_end'):
|
|
109
|
+
chars = len(str(payload.get('output') or '')) if kind.endswith('call_output') else len(_event_output_text(payload))
|
|
110
|
+
payload = {'type': kind, '_optimizer_output_chars': chars, 'duration': payload.get('duration')}
|
|
111
|
+
elif kind in ('function_call', 'custom_tool_call'):
|
|
112
|
+
payload = {'type': kind, 'name': payload.get('name'),
|
|
113
|
+
'arguments': payload.get('arguments') if payload.get('name') == 'spawn_agent' else None}
|
|
114
|
+
elif kind not in ('token_count', 'task_complete', 'collab_agent_spawn_end', 'mcp_tool_call_end'):
|
|
115
|
+
return None
|
|
116
|
+
# Bound metadata as well as outputs; abnormal records are diagnosed as skipped.
|
|
117
|
+
compact = {'type': record.get('type'), 'timestamp': record.get('timestamp'), 'payload': payload}
|
|
118
|
+
return compact
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def records(filepath):
|
|
122
|
+
path = Path(filepath).resolve()
|
|
123
|
+
key = str(path)
|
|
124
|
+
conn = _connect()
|
|
125
|
+
try:
|
|
126
|
+
# Read the file and parse OUTSIDE the write transaction to avoid
|
|
127
|
+
# holding the SQLite write lock during the (potentially multi-second)
|
|
128
|
+
# JSON parse loop. The parsed records are buffered in memory (bounded
|
|
129
|
+
# by PASS_BYTES of compact metadata per pass), then committed in a
|
|
130
|
+
# tight transaction.
|
|
131
|
+
try:
|
|
132
|
+
handle = path.open('rb')
|
|
133
|
+
except OSError:
|
|
134
|
+
# Missing/deleted/directory: degrade gracefully like pending().
|
|
135
|
+
conn.close()
|
|
136
|
+
def empty_iter():
|
|
137
|
+
if False:
|
|
138
|
+
yield
|
|
139
|
+
return empty_iter(), {'incomplete': True, 'scan_mode': 'indexing',
|
|
140
|
+
'indexed_bytes': 0, 'source_bytes': 0, 'skipped_records': 0}
|
|
141
|
+
with handle:
|
|
142
|
+
stat = path.stat()
|
|
143
|
+
identity = f'{SCHEMA_VERSION}:{stat.st_dev}:{stat.st_ino}:' + hashlib.sha256(handle.readline(65536)).hexdigest()
|
|
144
|
+
# Decide whether to re-index BEFORE acquiring the write lock.
|
|
145
|
+
row = conn.execute('SELECT identity,offset,skipped,mtime FROM files WHERE path=?', (key,)).fetchone()
|
|
146
|
+
# mtime check is UNCONDITIONAL: a truncate-and-regrow (same first
|
|
147
|
+
# line, larger size) changes mtime and must trigger a full re-index.
|
|
148
|
+
# Gating mtime behind offset==size missed that case.
|
|
149
|
+
if not row or row[0] != identity or row[1] > stat.st_size or row[3] != stat.st_mtime_ns:
|
|
150
|
+
offset, skipped = 0, 0
|
|
151
|
+
else:
|
|
152
|
+
offset, skipped = row[1], row[2]
|
|
153
|
+
handle.seek(offset)
|
|
154
|
+
end = min(stat.st_size, offset + PASS_BYTES)
|
|
155
|
+
parsed = []
|
|
156
|
+
while handle.tell() < end:
|
|
157
|
+
start = handle.tell()
|
|
158
|
+
line = handle.readline(LINE_BYTES + 1)
|
|
159
|
+
if not line:
|
|
160
|
+
break
|
|
161
|
+
if len(line) > LINE_BYTES:
|
|
162
|
+
while line and not line.endswith(b'\n'):
|
|
163
|
+
line = handle.readline(65536)
|
|
164
|
+
if not line or not line.endswith(b'\n'):
|
|
165
|
+
handle.seek(start)
|
|
166
|
+
break
|
|
167
|
+
skipped += 1
|
|
168
|
+
else:
|
|
169
|
+
try:
|
|
170
|
+
record = json.loads(line)
|
|
171
|
+
except (ValueError, UnicodeError):
|
|
172
|
+
if not line.endswith(b'\n'):
|
|
173
|
+
handle.seek(start) # writer has not completed this record
|
|
174
|
+
break
|
|
175
|
+
skipped += 1
|
|
176
|
+
record = None
|
|
177
|
+
if isinstance(record, dict):
|
|
178
|
+
compact = _slim(record)
|
|
179
|
+
if compact:
|
|
180
|
+
value = json.dumps(compact, ensure_ascii=False)
|
|
181
|
+
if len(value) <= 65536:
|
|
182
|
+
parsed.append((key, start, value))
|
|
183
|
+
else:
|
|
184
|
+
skipped += 1
|
|
185
|
+
offset = handle.tell()
|
|
186
|
+
# Now acquire the write lock for a tight batch commit only. A losing
|
|
187
|
+
# thread can still outlast busy_timeout under heavy contention (or hit
|
|
188
|
+
# the no-retry lock-upgrade deadlock path), so retry the transaction
|
|
189
|
+
# on a deadline instead of surfacing a transient BUSY.
|
|
190
|
+
deadline = time.monotonic() + 5
|
|
191
|
+
while True:
|
|
192
|
+
try:
|
|
193
|
+
conn.execute('BEGIN IMMEDIATE')
|
|
194
|
+
if not row or row[0] != identity or row[1] > stat.st_size or row[3] != stat.st_mtime_ns:
|
|
195
|
+
conn.execute('DELETE FROM records WHERE path=?', (key,))
|
|
196
|
+
conn.executemany('INSERT OR REPLACE INTO records(path, offset, data) VALUES (?,?,?)', parsed)
|
|
197
|
+
conn.execute('INSERT OR REPLACE INTO files(path, identity, offset, size, skipped, revision, mtime) VALUES (?,?,?,?,?,?,?)',
|
|
198
|
+
(key, identity, offset, stat.st_size, skipped, SCHEMA_VERSION, stat.st_mtime_ns))
|
|
199
|
+
conn.commit()
|
|
200
|
+
break
|
|
201
|
+
except sqlite3.OperationalError:
|
|
202
|
+
conn.rollback()
|
|
203
|
+
if time.monotonic() >= deadline:
|
|
204
|
+
raise
|
|
205
|
+
time.sleep(0.1)
|
|
206
|
+
info = {'incomplete': offset < stat.st_size or skipped > 0,
|
|
207
|
+
'scan_mode': 'indexing' if offset < stat.st_size else 'indexed_full',
|
|
208
|
+
'indexed_bytes': offset, 'source_bytes': stat.st_size, 'skipped_records': skipped}
|
|
209
|
+
# Cursor iteration keeps memory bounded even for years of tool events.
|
|
210
|
+
def iterate():
|
|
211
|
+
try:
|
|
212
|
+
for (value,) in conn.execute('SELECT data FROM records WHERE path=? ORDER BY offset', (key,)):
|
|
213
|
+
yield json.loads(value)
|
|
214
|
+
finally:
|
|
215
|
+
conn.close()
|
|
216
|
+
return iterate(), info
|
|
217
|
+
except Exception:
|
|
218
|
+
conn.close()
|
|
219
|
+
raise
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Codex model metadata from the client's catalog, never API window guesses."""
|
|
2
|
+
import json
|
|
3
|
+
from runtime_env import codex_home
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def catalog():
|
|
7
|
+
try:
|
|
8
|
+
path = codex_home() / 'models_cache.json'
|
|
9
|
+
if path.stat().st_size > 8 * 1024 * 1024:
|
|
10
|
+
return []
|
|
11
|
+
data = json.loads(path.read_text(encoding='utf-8'))
|
|
12
|
+
return [m for m in data.get('models', []) if isinstance(m, dict) and isinstance(m.get('slug'), str)]
|
|
13
|
+
except (OSError, ValueError, TypeError, AttributeError):
|
|
14
|
+
return []
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def effective_window(model):
|
|
18
|
+
for entry in catalog():
|
|
19
|
+
if entry['slug'] == model:
|
|
20
|
+
try:
|
|
21
|
+
window = int(entry['context_window'])
|
|
22
|
+
percent = int(entry.get('effective_context_window_percent', 100))
|
|
23
|
+
if window > 0 and 0 < percent <= 100:
|
|
24
|
+
return window * percent // 100
|
|
25
|
+
except (KeyError, ValueError, TypeError, OverflowError):
|
|
26
|
+
pass
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def visible_models():
|
|
31
|
+
return [{'id': m['slug'], 'name': m.get('display_name') or m['slug'],
|
|
32
|
+
'effective_context_window': effective_window(m['slug']),
|
|
33
|
+
'reasoning_efforts': m.get('supported_reasoning_levels', [])}
|
|
34
|
+
for m in catalog() if m.get('visibility') == 'list']
|