48e9242f8f
display.format_token_count now rounds half-up to whole numbers with tier rollover (999999 -> "1M", never "1000k"; 275860 -> "276k"). display.format_token_line renders '-- I:<s>+<t> O:<s>+<t> C:<s>+<t>': the +N suffixes come from new last_turn token fields in the report (CLI --json raw counts + token_display last_turn_* keys; Hermes plugin passes its in-memory turn bucket), render +0 on zero increments, and fail soft when absent - every display path (CLI, --display-lines, GUI, Vibe hooks, Hermes plugin) changes together per the display-parity rule. Docs and tests updated; 125 pass. MINOR bump to 0.8.0. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
928 lines
35 KiB
Python
928 lines
35 KiB
Python
"""Command-line interface for agent_cost_estimator."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import logging
|
|
import pathlib
|
|
import sys
|
|
|
|
from .core import compute_cost
|
|
from .display import format_display_lines
|
|
from .harnesses import available_harnesses, get_harness
|
|
from .pricing import (
|
|
DEFAULT_PRICING_PATH,
|
|
RATES_KEYS,
|
|
display_key_for,
|
|
get_harness_pool,
|
|
get_model_prices,
|
|
get_url_pool,
|
|
load_pricing,
|
|
update_pricing,
|
|
)
|
|
from .utils.formatting import format_token_count
|
|
|
|
LOG = logging.getLogger("agent_cost_estimator.cli")
|
|
|
|
# SKILL.md is in the skill/ subdirectory of the package
|
|
SKILL_PATH = pathlib.Path(__file__).parent / "skill" / "SKILL.md"
|
|
|
|
|
|
def parse_args(argv):
|
|
parser = argparse.ArgumentParser(
|
|
prog="agent-cost-estimator",
|
|
description="Report token usage and estimated USD cost of "
|
|
"an AI agent session, from the harness's local logs.",
|
|
)
|
|
parser.add_argument(
|
|
"--harness", default="vibe",
|
|
help="which AI harness to read (default: vibe; run "
|
|
"--list-harnesses to see all)",
|
|
)
|
|
parser.add_argument(
|
|
"--list-harnesses", action="store_true",
|
|
help="print the available harness names and exit",
|
|
)
|
|
parser.add_argument(
|
|
"--skill", action="store_true",
|
|
help="print the SKILL.md usage instructions (for LLMs) "
|
|
"and exit; no session is read",
|
|
)
|
|
parser.add_argument(
|
|
"--integrate", type=str, default=None, metavar="HARNESS",
|
|
help="install hooks for the specified harness "
|
|
"(e.g., 'mistral', 'mistral-vibe-cli', 'mistral-vibe-code')",
|
|
)
|
|
parser.add_argument(
|
|
"--session-id", default=None,
|
|
help="session id or session directory (default: most "
|
|
"recently active session)",
|
|
)
|
|
parser.add_argument(
|
|
"--home", default=None,
|
|
help="harness data root, e.g. the Vibe home (default: "
|
|
"harness-specific, e.g. $VIBE_HOME or ~/.vibe)",
|
|
)
|
|
parser.add_argument(
|
|
"--pricing", default=None,
|
|
help="path to a pricing JSON file (default: the bundled "
|
|
"pricing.json)",
|
|
)
|
|
parser.add_argument(
|
|
"--model", default=None,
|
|
help="force the pricing lookup key for this run "
|
|
"(default: the session's model name, then alias, "
|
|
'then "default")',
|
|
)
|
|
parser.add_argument("--input-price", type=float, default=None,
|
|
help="override: USD per million input tokens")
|
|
parser.add_argument("--cached-input-price", type=float, default=None,
|
|
help="override: USD per million cached input "
|
|
"tokens")
|
|
parser.add_argument("--output-price", type=float, default=None,
|
|
help="override: USD per million output tokens")
|
|
parser.add_argument(
|
|
"-d", "--details", action="store_true",
|
|
help="the full report table (cost lines, sources, notes)",
|
|
)
|
|
parser.add_argument(
|
|
"--display-lines", action="store_true",
|
|
help="print exactly the display lines (cost line plus "
|
|
"token line) the hooks and plugins render - the "
|
|
"canonical format, same as the default output",
|
|
)
|
|
parser.add_argument(
|
|
"-s", "--session", action="store_true",
|
|
help="print only the session cost, as a bare number",
|
|
)
|
|
parser.add_argument(
|
|
"-t", "--turn", action="store_true",
|
|
help="print only the latest turn's cost, as a bare number",
|
|
)
|
|
parser.add_argument("--turns", action="store_true",
|
|
help="with --details: also print a per-turn "
|
|
"breakdown")
|
|
parser.add_argument("--json", action="store_true",
|
|
help="print one JSON object instead of a table")
|
|
parser.add_argument(
|
|
"--update-pricing", action="store_true",
|
|
help="persist the effective rates (file rates plus price "
|
|
"overrides) for the model into the pricing file; "
|
|
"requires at least one price override",
|
|
)
|
|
parser.add_argument(
|
|
"--dry-run", action="store_true",
|
|
help="with --update-pricing: print what would change "
|
|
"without writing",
|
|
)
|
|
parser.add_argument(
|
|
"--rm-integrate", type=str, default=None, metavar="HARNESS",
|
|
help="remove hooks integration for the specified harness "
|
|
"(e.g., 'mistral-vibe-cli', 'mistral-vibe-code')",
|
|
)
|
|
return parser.parse_args(argv)
|
|
|
|
|
|
def integrate_hooks(harness_name):
|
|
"""Install hooks for the specified harness.
|
|
|
|
Currently supports:
|
|
- mistral-vibe-cli: Installs hooks for Mistral Vibe CLI
|
|
- mistral-vibe-code: Installs hooks for Mistral Vibe VSCodium extension
|
|
- mistral: Alias for mistral-vibe-cli (backward compatibility)
|
|
|
|
This function:
|
|
1. Creates harness-specific directories
|
|
2. Installs hook scripts from modular hook directory
|
|
3. Creates/updates hook configuration
|
|
4. Adds agent-cost-estimator to bash allowlist
|
|
|
|
Args:
|
|
harness_name: Name of the harness to integrate
|
|
|
|
Returns 0 on success, 1 on error.
|
|
"""
|
|
import os
|
|
import stat
|
|
|
|
# Validate harness name
|
|
# Map aliases to canonical names
|
|
harness_aliases = {
|
|
"mistral": "mistral-vibe-cli", # Backward compatibility
|
|
"vibe": "mistral-vibe-cli",
|
|
"cli": "mistral-vibe-cli",
|
|
"vscodium": "mistral-vibe-code",
|
|
"code": "mistral-vibe-code",
|
|
"hermes": "hermes",
|
|
"hermes-agent": "hermes",
|
|
}
|
|
canonical_name = harness_aliases.get(harness_name, harness_name)
|
|
|
|
if canonical_name == "hermes":
|
|
# Hermes integration is a plugin, not a hook script: one call
|
|
# copies the plugin, ships pricing.json, enables it, and
|
|
# restarts a running gateway daemon so it re-imports it.
|
|
from agent_cost_estimator.integration.hermes.install import main as hermes_install
|
|
return hermes_install([])
|
|
|
|
supported_harnesses = ["mistral-vibe-cli", "mistral-vibe-code"]
|
|
if canonical_name not in supported_harnesses:
|
|
print(f"error: unsupported harness '{harness_name}'. "
|
|
f"Supported harnesses: {', '.join(supported_harnesses + list(harness_aliases.keys()))}",
|
|
file=sys.stderr)
|
|
return 1
|
|
|
|
# For mistral-vibe-cli, use version-aware integration
|
|
if canonical_name == "mistral-vibe-cli":
|
|
from agent_cost_estimator.integration.vibe_cli import integrate_vibe_cli
|
|
return integrate_vibe_cli(harness_name)
|
|
|
|
# For mistral-vibe-code, use the existing code path (VSCodium extension)
|
|
# Get the hook script path (from the package's modular structure)
|
|
hook_script_src = pathlib.Path(__file__).parent / "hooks" / canonical_name / "post_turn.py"
|
|
|
|
# Determine harness home directory (both use ~/.vibe)
|
|
harness_home = pathlib.Path(os.environ.get("VIBE_HOME", "~/.vibe")).expanduser()
|
|
hooks_dir = harness_home / "hooks"
|
|
|
|
try:
|
|
# Create hooks directory
|
|
hooks_dir.mkdir(parents=True, exist_ok=True)
|
|
print(f"Created hooks directory: {hooks_dir}")
|
|
|
|
# Install hook script from modular location
|
|
hook_dest = hooks_dir / "post_turn.py"
|
|
if hook_script_src.exists():
|
|
# Copy from package
|
|
hook_content = hook_script_src.read_text(encoding="utf-8")
|
|
hook_dest.write_text(hook_content, encoding="utf-8")
|
|
# Make executable
|
|
hook_dest.chmod(hook_dest.stat().st_mode | stat.S_IEXEC)
|
|
print(f"Installed hook script: {hook_dest}")
|
|
else:
|
|
# Fallback: Generate inline hook script (a thin relay;
|
|
# the display format lives in the package - see
|
|
# agent_cost_estimator.display)
|
|
hook_content = '''#!/usr/bin/env python3
|
|
import os, sys, json, subprocess
|
|
from pathlib import Path
|
|
|
|
def get_session_dir():
|
|
try:
|
|
payload = json.load(sys.stdin)
|
|
if session_id := payload.get("session_id"):
|
|
home = Path(os.environ.get("VIBE_HOME", "~/.vibe")).expanduser()
|
|
unified = home / "logs" / "session" / "unified" / session_id
|
|
if unified.is_dir():
|
|
return unified
|
|
if tp := payload.get("transcript_path"):
|
|
return Path(tp).parent
|
|
except: pass
|
|
return Path(os.environ.get("VIBE_SESSION_DIR", "~/.vibe/logs/session/active")).expanduser()
|
|
|
|
session_dir = get_session_dir()
|
|
cmd = ["agent-cost-estimator", "--session-id", str(session_dir), "--display-lines"]
|
|
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
|
if result.returncode == 0:
|
|
message = result.stdout.strip()
|
|
print(json.dumps({"system_message": f"-- {message}"}))
|
|
'''
|
|
hook_dest.write_text(hook_content, encoding="utf-8")
|
|
hook_dest.chmod(hook_dest.stat().st_mode | stat.S_IEXEC)
|
|
print(f"Generated hook script: {hook_dest}")
|
|
|
|
# Create/update hooks.toml with harness-specific config.
|
|
# Vibe reads user-level hooks from ~/.vibe/hooks.toml (NOT
|
|
# ~/.vibe/hooks/hooks.toml). See the hooks documentation.
|
|
hooks_toml = harness_home / "hooks.toml"
|
|
if canonical_name == "mistral-vibe-cli":
|
|
hooks_config = """# Vibe CLI Hooks Configuration
|
|
# Automatically generated by agent-cost-estimator --integrate mistral-vibe-cli
|
|
|
|
[[hooks]]
|
|
name = "cost-tracker"
|
|
type = "post_agent"
|
|
command = "python ~/.vibe/hooks/post_turn.py"
|
|
timeout = 30
|
|
strict = false
|
|
description = "Display cost after each assistant turn (Vibe CLI)"
|
|
"""
|
|
else: # mistral-vibe-code
|
|
hooks_config = """# Vibe VSCodium Extension Hooks Configuration
|
|
# Automatically generated by agent-cost-estimator --integrate mistral-vibe-code
|
|
|
|
[[hooks]]
|
|
name = "cost-tracker-vscodium"
|
|
type = "post_agent"
|
|
command = "python ~/.vibe/hooks/post_turn.py"
|
|
timeout = 30
|
|
strict = false
|
|
description = "Display cost after each assistant turn (VSCodium)"
|
|
"""
|
|
hooks_toml.write_text(hooks_config, encoding="utf-8")
|
|
print(f"Installed hooks configuration: {hooks_toml}")
|
|
|
|
# Update config.toml to add agent-cost-estimator to bash allowlist
|
|
config_toml = harness_home / "config.toml"
|
|
if config_toml.exists():
|
|
config_text = config_toml.read_text(encoding="utf-8")
|
|
|
|
# Check if already in allowlist
|
|
if "agent-cost-estimator" in config_text:
|
|
print(f"agent-cost-estimator already in bash allowlist")
|
|
else:
|
|
# Try to add it to existing tools.bash.allowlist
|
|
import re
|
|
# Pattern to match allowlist array
|
|
allowlist_match = re.search(
|
|
r'(allowlist\s*=\s*\[[^\]]*\])',
|
|
config_text,
|
|
re.MULTILINE | re.DOTALL
|
|
)
|
|
if allowlist_match:
|
|
# Found allowlist, insert agent-cost-estimator
|
|
old_allowlist = allowlist_match.group(1)
|
|
# Check if it ends with ]
|
|
if old_allowlist.rstrip().endswith(']'):
|
|
new_allowlist = old_allowlist.rstrip()[:-1] + ',\n "agent-cost-estimator",\n "python",\n]'
|
|
new_config = config_text[:allowlist_match.start()] + new_allowlist + config_text[allowlist_match.end():]
|
|
config_toml.write_text(new_config, encoding="utf-8")
|
|
print(f"Updated bash allowlist in: {config_toml}")
|
|
else:
|
|
print(f"Warning: Could not parse allowlist in {config_toml}")
|
|
else:
|
|
# No existing allowlist, add tools.bash section
|
|
new_entry = """
|
|
[tools.bash]
|
|
allowlist = ["agent-cost-estimator", "python"]
|
|
"""
|
|
if config_text.strip():
|
|
new_config = config_text.rstrip() + "\n" + new_entry
|
|
else:
|
|
new_config = new_entry
|
|
config_toml.write_text(new_config, encoding="utf-8")
|
|
print(f"Added bash allowlist to: {config_toml}")
|
|
else:
|
|
print(f"Warning: {config_toml} does not exist, skipping allowlist update")
|
|
|
|
# For VSCodium extension, patch the extension to add hooks support
|
|
if canonical_name == "mistral-vibe-code":
|
|
print("\nPatching VSCodium extension for hooks support...")
|
|
ext_dirs = find_vscodium_extensions()
|
|
if not ext_dirs:
|
|
print("Warning: VSCodium extension not found. Hooks will not work until you install the extension.",
|
|
file=sys.stderr)
|
|
else:
|
|
for ext_dir in ext_dirs:
|
|
success = patch_vscodium_extension(ext_dir, action="install")
|
|
if not success:
|
|
print(f"Warning: Failed to patch {ext_dir}", file=sys.stderr)
|
|
|
|
print(f"\nIntegration complete for {harness_name}!")
|
|
if harness_name == "mistral":
|
|
print("To use: Start a new Vibe session and costs will be displayed after each turn.")
|
|
else:
|
|
print(f"To use: Start a new {harness_name} session and costs will be displayed.")
|
|
if canonical_name == "mistral-vibe-code":
|
|
print("IMPORTANT: Restart VSCodium for the hooks patch to take effect.")
|
|
return 0
|
|
|
|
except Exception as exc:
|
|
print(f"error: integration failed: {exc}", file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
def remove_integrate_hooks(harness_name):
|
|
"""Remove hooks integration for the specified harness.
|
|
|
|
Args:
|
|
harness_name: Name of the harness to remove
|
|
|
|
Returns 0 on success, 1 on error.
|
|
"""
|
|
# Map aliases to canonical names
|
|
harness_aliases = {
|
|
"mistral": "mistral-vibe-cli",
|
|
"vibe": "mistral-vibe-cli",
|
|
"cli": "mistral-vibe-cli",
|
|
"vscodium": "mistral-vibe-code",
|
|
"code": "mistral-vibe-code",
|
|
"hermes": "hermes",
|
|
"hermes-agent": "hermes",
|
|
}
|
|
canonical_name = harness_aliases.get(harness_name, harness_name)
|
|
|
|
if canonical_name == "hermes":
|
|
from agent_cost_estimator.integration.hermes.install import main as hermes_install
|
|
return hermes_install(["--uninstall"])
|
|
|
|
# For mistral-vibe-cli, use version-aware removal
|
|
if canonical_name == "mistral-vibe-cli":
|
|
from agent_cost_estimator.integration.vibe_cli import remove_vibe_cli_integration
|
|
return remove_vibe_cli_integration(harness_name)
|
|
|
|
supported_harnesses = ["mistral-vibe-cli", "mistral-vibe-code"]
|
|
if canonical_name not in supported_harnesses:
|
|
print(f"error: unsupported harness '{harness_name}'. "
|
|
f"Supported harnesses: {', '.join(supported_harnesses + list(harness_aliases.keys()))}",
|
|
file=sys.stderr)
|
|
return 1
|
|
|
|
try:
|
|
# For VSCodium extension, remove the patch
|
|
if canonical_name == "mistral-vibe-code":
|
|
print("Removing VSCodium extension patch...")
|
|
ext_dirs = find_vscodium_extensions()
|
|
if not ext_dirs:
|
|
print("Warning: VSCodium extension not found.", file=sys.stderr)
|
|
else:
|
|
for ext_dir in ext_dirs:
|
|
success = patch_vscodium_extension(ext_dir, action="remove")
|
|
if not success:
|
|
print(f"Warning: Failed to unpatch {ext_dir}", file=sys.stderr)
|
|
|
|
print(f"\nRemoved integration for {harness_name}!")
|
|
print(f"To complete removal: Restart VSCodium.")
|
|
return 0
|
|
|
|
except Exception as exc:
|
|
print(f"error: removal failed: {exc}", file=sys.stderr)
|
|
return 1
|
|
|
|
|
|
def find_vscodium_extensions():
|
|
"""Find all VSCodium extension installations."""
|
|
import os
|
|
|
|
# Possible VSCodium extension locations
|
|
vscodium_paths = [
|
|
pathlib.Path.home() / ".vscode-oss" / "extensions",
|
|
pathlib.Path.home() / ".vscode" / "extensions",
|
|
pathlib.Path(os.environ.get("HOME", "~")).expanduser() / ".var" / "app" / "com.vscodium.codium" / "data" / "codium" / "extensions",
|
|
]
|
|
|
|
extensions = []
|
|
for base_path in vscodium_paths:
|
|
if not base_path.exists():
|
|
continue
|
|
|
|
# Find extension directories matching mistralai.mistral-vibe-code*
|
|
for ext_dir in base_path.iterdir():
|
|
if ext_dir.is_dir() and ext_dir.name.startswith("mistralai.mistral-vibe-code"):
|
|
extensions.append(ext_dir)
|
|
|
|
return extensions
|
|
|
|
|
|
def patch_vscodium_extension(ext_dir, action="install"):
|
|
"""Patch VSCodium extension to add hooks support.
|
|
|
|
Actions:
|
|
- "install": Replace vibe-acp with wrapper that sets VIBE_HOME
|
|
- "remove": Restore original vibe-acp binary
|
|
|
|
The wrapper sets VIBE_HOME so the Vibe core loads hooks from ~/.vibe/hooks/.
|
|
The Vibe core will then automatically execute post_agent hooks after each
|
|
assistant turn, which will display the cost tracker.
|
|
|
|
Args:
|
|
ext_dir: Path to the extension directory
|
|
action: "install" or "remove"
|
|
|
|
Returns True on success, False on error.
|
|
"""
|
|
import os
|
|
import shutil
|
|
import stat
|
|
|
|
# Find the real vibe-acp binary
|
|
bin_dir = pathlib.Path(ext_dir) / "bin"
|
|
real_acp = None
|
|
|
|
if bin_dir.exists():
|
|
for f in bin_dir.iterdir():
|
|
if "vibe-acp" in f.name and f.is_file():
|
|
real_acp = f
|
|
break
|
|
|
|
if not real_acp:
|
|
print(f"Warning: vibe-acp not found in {ext_dir}", file=sys.stderr)
|
|
return False
|
|
|
|
if action == "install":
|
|
# Save the original vibe-acp binary and its supporting files
|
|
backup_dir = bin_dir / "_backup"
|
|
backup_dir.mkdir(parents=True, exist_ok=True)
|
|
backup_acp = backup_dir / real_acp.name
|
|
|
|
# Only backup if not already there
|
|
if not backup_acp.exists():
|
|
# Copy the vibe-acp binary
|
|
shutil.copy2(real_acp, backup_acp)
|
|
# Also copy the _internal directory which contains PyInstaller runtime files
|
|
internal_dir = bin_dir / "_internal"
|
|
backup_internal_dir = backup_dir / "_internal"
|
|
if internal_dir.exists():
|
|
if backup_internal_dir.exists():
|
|
shutil.rmtree(backup_internal_dir)
|
|
shutil.copytree(internal_dir, backup_internal_dir)
|
|
print(f"Backed up: {real_acp} -> {backup_acp}")
|
|
|
|
# Create Python wrapper that monitors journal files and injects hook messages
|
|
vibe_home = str(pathlib.Path.home() / ".vibe")
|
|
|
|
# Generate Python wrapper with embedded backup path
|
|
python_wrapper = f'''#!/usr/bin/env python3
|
|
import os
|
|
import sys
|
|
import json
|
|
import subprocess
|
|
import threading
|
|
import pathlib
|
|
|
|
VIBE_HOME = "{vibe_home}"
|
|
REAL_ACP = "{backup_acp}"
|
|
|
|
from watchdog.observers import Observer
|
|
from watchdog.events import FileSystemEventHandler
|
|
|
|
vibe_acp_process = None
|
|
stop_observer = False
|
|
|
|
|
|
def forward_stdin():
|
|
# Forward data from our stdin to vibe-acp's stdin.
|
|
# This is crucial for VSCodium to communicate with the real vibe-acp.
|
|
# Without this, VSCodium hangs during initialization.
|
|
global vibe_acp_process
|
|
try:
|
|
for line in sys.stdin:
|
|
if vibe_acp_process and vibe_acp_process.stdin:
|
|
vibe_acp_process.stdin.write(line)
|
|
vibe_acp_process.stdin.flush()
|
|
except Exception as e:
|
|
print(f"stdin forwarder error: {{e}}", file=sys.stderr)
|
|
|
|
|
|
class TurnCompletionHandler(FileSystemEventHandler):
|
|
def on_created(self, event):
|
|
self._check_journal(event)
|
|
|
|
def on_modified(self, event):
|
|
self._check_journal(event)
|
|
|
|
def _check_journal(self, event):
|
|
if not event.is_directory and ("journal" in str(event.src_path) or "messages" in str(event.src_path)) and event.src_path.endswith(".jsonl"):
|
|
session_dir = pathlib.Path(event.src_path).parent.parent
|
|
self._run_hooks(session_dir)
|
|
|
|
def _run_hooks(self, session_dir):
|
|
global vibe_acp_process
|
|
hook_script = pathlib.Path(VIBE_HOME) / "hooks" / "post_turn.py"
|
|
if not hook_script.exists():
|
|
return
|
|
try:
|
|
payload = {{"session_id": session_dir.name, "hook_event_name": "post_agent"}}
|
|
result = subprocess.run(
|
|
[sys.executable, str(hook_script)],
|
|
input=json.dumps(payload),
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=30
|
|
)
|
|
if result.stdout:
|
|
# Send hook output to vibe-acp's stdin instead of printing to stdout
|
|
# This prevents breaking the ACP protocol
|
|
try:
|
|
if vibe_acp_process and vibe_acp_process.stdin:
|
|
vibe_acp_process.stdin.write(result.stdout)
|
|
vibe_acp_process.stdin.flush()
|
|
except Exception:
|
|
# If we can't write to stdin, print to stderr for debugging
|
|
print(result.stdout, end='', flush=True, file=sys.stderr)
|
|
except Exception as e:
|
|
print(f"Hook error: {{e}}", file=sys.stderr)
|
|
|
|
|
|
def start_monitor():
|
|
observer = Observer()
|
|
handler = TurnCompletionHandler()
|
|
for d in ["unified", "active"]:
|
|
p = pathlib.Path(VIBE_HOME) / "logs" / "session" / d
|
|
p.mkdir(parents=True, exist_ok=True)
|
|
observer.schedule(handler, str(p), recursive=True)
|
|
observer.start()
|
|
return observer
|
|
|
|
|
|
def main():
|
|
global vibe_acp_process, stop_observer
|
|
observer = start_monitor()
|
|
try:
|
|
vibe_acp_process = subprocess.Popen(
|
|
[REAL_ACP] + sys.argv[1:],
|
|
stdin=subprocess.PIPE,
|
|
stdout=sys.stdout,
|
|
stderr=sys.stderr,
|
|
bufsize=1,
|
|
text=True
|
|
)
|
|
|
|
# Start stdin forwarder thread - CRITICAL for ACP protocol
|
|
# Without this, VSCodium cannot communicate with vibe-acp
|
|
stdin_thread = threading.Thread(
|
|
target=forward_stdin,
|
|
name="vibe-acp-stdin-forwarder",
|
|
daemon=True
|
|
)
|
|
stdin_thread.start()
|
|
|
|
# Wait for vibe-acp to complete (or until VSCodium terminates us)
|
|
vibe_acp_process.wait()
|
|
sys.exit(vibe_acp_process.returncode)
|
|
except KeyboardInterrupt:
|
|
stop_observer = True
|
|
if vibe_acp_process:
|
|
vibe_acp_process.terminate()
|
|
observer.stop()
|
|
sys.exit(0)
|
|
finally:
|
|
stop_observer = True
|
|
observer.stop()
|
|
observer.join()
|
|
if vibe_acp_process:
|
|
try:
|
|
vibe_acp_process.stdin.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
'''
|
|
|
|
# Write the wrapper script
|
|
try:
|
|
real_acp.write_text(python_wrapper)
|
|
real_acp.chmod(real_acp.stat().st_mode | stat.S_IEXEC)
|
|
except OSError as e:
|
|
if e.errno == 26: # Text file busy
|
|
print(f"Warning: {real_acp} is currently running.", file=sys.stderr)
|
|
print(f"Close VSCodium and re-run this command to complete the patch.", file=sys.stderr)
|
|
return False
|
|
else:
|
|
raise
|
|
|
|
print(f"Patched: {real_acp}")
|
|
print(f" -> Monitors journal files for turn completions")
|
|
print(f" -> Injects hook messages to vibe-acp stdin")
|
|
print(f" -> Original backed up: {backup_acp}")
|
|
return True
|
|
|
|
elif action == "remove":
|
|
# Restore from backup
|
|
backup_dir = bin_dir / "_backup"
|
|
backup_acp = None
|
|
|
|
if backup_dir.exists():
|
|
for f in backup_dir.iterdir():
|
|
if "vibe-acp" in f.name:
|
|
backup_acp = f
|
|
break
|
|
|
|
if not backup_acp:
|
|
print(f"Warning: No backup found for {real_acp}, cannot restore", file=sys.stderr)
|
|
return False
|
|
|
|
# Restore original
|
|
try:
|
|
# Restore the vibe-acp binary
|
|
shutil.copy2(backup_acp, real_acp)
|
|
real_acp.chmod(real_acp.stat().st_mode | stat.S_IEXEC)
|
|
|
|
# Also restore the _internal directory if it exists in backup
|
|
backup_internal_dir = backup_dir / "_internal"
|
|
internal_dir = bin_dir / "_internal"
|
|
if backup_internal_dir.exists():
|
|
if internal_dir.exists():
|
|
shutil.rmtree(internal_dir)
|
|
shutil.copytree(backup_internal_dir, internal_dir)
|
|
|
|
# Remove Python wrapper if it exists
|
|
wrapper_path = real_acp.with_suffix(".py")
|
|
if wrapper_path.exists():
|
|
wrapper_path.unlink()
|
|
|
|
print(f"Restored: {backup_acp} -> {real_acp}")
|
|
print(f" -> Restored _internal directory")
|
|
return True
|
|
except OSError as e:
|
|
if e.errno == 26: # Text file busy
|
|
print(f"Warning: {real_acp} is currently running.", file=sys.stderr)
|
|
print(f"Close VSCodium and re-run this command to complete the removal.", file=sys.stderr)
|
|
return False
|
|
else:
|
|
raise
|
|
|
|
return False
|
|
|
|
|
|
def effective_rates(args, pricing, meta):
|
|
"""Return (rates, key, currency, is_default) after table lookup and CLI overrides."""
|
|
result = get_model_prices(pricing, args.model or meta.alias,
|
|
meta.model_name)
|
|
# Handle different return value counts for backward compatibility
|
|
if len(result) == 4:
|
|
rates, key, currency, is_default = result
|
|
elif len(result) == 3:
|
|
rates, key, currency = result
|
|
is_default = False
|
|
else:
|
|
rates, key = result
|
|
currency = pricing.get("currency", "USD")
|
|
is_default = False
|
|
overrides = {
|
|
"input_price": args.input_price,
|
|
"cached_input_price": args.cached_input_price,
|
|
"output_price": args.output_price,
|
|
}
|
|
rates.update({k: v for k, v in overrides.items() if v is not None})
|
|
return rates, key, currency, is_default
|
|
|
|
|
|
def main(argv=None):
|
|
args = parse_args(argv)
|
|
logging.basicConfig(
|
|
level=logging.WARNING,
|
|
stream=sys.stderr,
|
|
format="%(levelname)s %(name)s %(message)s",
|
|
)
|
|
if args.skill:
|
|
try:
|
|
print(SKILL_PATH.read_text(encoding="utf-8"), end="")
|
|
except OSError as exc:
|
|
print(f"error: cannot read the skill doc: {exc}",
|
|
file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
if args.list_harnesses:
|
|
for name in sorted(available_harnesses()):
|
|
print(name)
|
|
return 0
|
|
if args.integrate:
|
|
if not args.integrate:
|
|
print("error: --integrate requires a harness name argument (e.g., 'mistral')",
|
|
file=sys.stderr)
|
|
return 1
|
|
return integrate_hooks(args.integrate)
|
|
if args.rm_integrate:
|
|
if not args.rm_integrate:
|
|
print("error: --rm-integrate requires a harness name argument (e.g., 'mistral-vibe-code')",
|
|
file=sys.stderr)
|
|
return 1
|
|
return remove_integrate_hooks(args.rm_integrate)
|
|
if args.dry_run and not args.update_pricing:
|
|
print("error: --dry-run needs --update-pricing",
|
|
file=sys.stderr)
|
|
return 1
|
|
if args.update_pricing and not any(
|
|
getattr(args, flag) is not None
|
|
for flag in ("input_price", "cached_input_price", "output_price")
|
|
):
|
|
print("error: --update-pricing needs at least one of "
|
|
"--input-price, --cached-input-price, --output-price",
|
|
file=sys.stderr)
|
|
return 1
|
|
pricing_path = pathlib.Path(args.pricing) if args.pricing else None
|
|
try:
|
|
harness = get_harness(args.harness)
|
|
home = (pathlib.Path(args.home).expanduser()
|
|
if args.home else harness.default_home())
|
|
session_dir = harness.resolve_session_dir(args.session_id, home)
|
|
meta = harness.read_meta(session_dir)
|
|
usage = harness.collect_usage(session_dir)
|
|
pricing = load_pricing(pricing_path)
|
|
result = effective_rates(args, pricing, meta)
|
|
# Handle different return value counts
|
|
if len(result) == 4:
|
|
rates, key, currency, is_default = result
|
|
elif len(result) == 3:
|
|
rates, key, currency = result
|
|
is_default = False
|
|
else:
|
|
rates, key = result
|
|
currency = "USD"
|
|
is_default = False
|
|
except (FileNotFoundError, TypeError, ValueError) as exc:
|
|
print(f"error: {exc}", file=sys.stderr)
|
|
return 1
|
|
if args.update_pricing:
|
|
target = args.model or meta.model_name or meta.alias or "default"
|
|
write_path, written = update_pricing(
|
|
pricing_path or DEFAULT_PRICING_PATH,
|
|
target,
|
|
{k: rates[k] for k in RATES_KEYS},
|
|
dry_run=args.dry_run,
|
|
)
|
|
state = "updated" if written else "would update"
|
|
print(f"{state} {target} in {write_path}", file=sys.stderr)
|
|
tokens = {
|
|
"fresh": usage.fresh_input_tokens,
|
|
"cached": usage.cached_input_tokens,
|
|
"output": usage.output_tokens,
|
|
}
|
|
cost = compute_cost(tokens, rates)
|
|
# Display form of the pricing key: provider_alias/model_alias
|
|
# applied, then the credit pool (e.g. mistral-api vs mistral-vibe)
|
|
# overriding the provider part; the raw key still drives
|
|
# --update-pricing above.
|
|
pool = get_url_pool(pricing, meta.base_url) or get_harness_pool(
|
|
pricing, harness.name)
|
|
display_key = display_key_for(pricing, key, pool=pool)
|
|
last_turn = next(
|
|
(t for t in reversed(usage.turns) if t.calls), None)
|
|
turn_cost = compute_cost(
|
|
{"fresh": last_turn.fresh_input_tokens,
|
|
"cached": last_turn.cached_input_tokens,
|
|
"output": last_turn.output_tokens},
|
|
rates,
|
|
) if last_turn else {
|
|
"input_usd": 0.0, "cached_usd": 0.0, "output_usd": 0.0,
|
|
"total_usd": 0.0,
|
|
}
|
|
# One report object feeds every output shape: --json prints it
|
|
# verbatim; the default and --display-lines output are rendered
|
|
# from it by agent_cost_estimator.display.
|
|
# Extract provider from the display key
|
|
provider_model = (display_key.split(":", 1)
|
|
if ":" in display_key else (None, display_key))
|
|
report = {
|
|
"harness": harness.name,
|
|
"session_id": session_dir.name,
|
|
"title": meta.title,
|
|
"model": meta.model_name,
|
|
"provider": provider_model[0],
|
|
"credit_pool": pool,
|
|
"provider_model": display_key,
|
|
"calls": usage.calls,
|
|
"input_tokens": usage.input_tokens,
|
|
"cached_input_tokens": usage.cached_input_tokens,
|
|
"fresh_input_tokens": usage.fresh_input_tokens,
|
|
"output_tokens": usage.output_tokens,
|
|
"pricing": {
|
|
"file": str(pricing_path) if pricing_path
|
|
else "bundled",
|
|
"model_key": display_key,
|
|
"model_key_raw": key,
|
|
"currency": currency,
|
|
"rates_usd_per_million": rates,
|
|
},
|
|
"usage_source": usage.usage_source,
|
|
"cost_usd": cost,
|
|
"model_price_unavailable": is_default,
|
|
"token_display": {
|
|
"input": format_token_count(usage.input_tokens),
|
|
"cached": format_token_count(usage.cached_input_tokens),
|
|
"output": format_token_count(usage.output_tokens),
|
|
"fresh": format_token_count(usage.fresh_input_tokens),
|
|
"last_turn_input":
|
|
format_token_count(last_turn.input_tokens)
|
|
if last_turn else None,
|
|
"last_turn_cached":
|
|
format_token_count(last_turn.cached_input_tokens)
|
|
if last_turn else None,
|
|
"last_turn_output":
|
|
format_token_count(last_turn.output_tokens)
|
|
if last_turn else None,
|
|
},
|
|
"last_turn": {
|
|
"label": last_turn.label if last_turn else None,
|
|
"cost_usd": turn_cost,
|
|
"input_tokens":
|
|
last_turn.input_tokens if last_turn else None,
|
|
"cached_input_tokens":
|
|
last_turn.cached_input_tokens if last_turn else None,
|
|
"output_tokens":
|
|
last_turn.output_tokens if last_turn else None,
|
|
} if last_turn else None,
|
|
"turns": [
|
|
{"label": t.label, "calls": t.calls,
|
|
"input_tokens": t.input_tokens,
|
|
"cached_input_tokens": t.cached_input_tokens,
|
|
"output_tokens": t.output_tokens,
|
|
"fresh_input_tokens": t.fresh_input_tokens}
|
|
for t in usage.turns if t.calls
|
|
],
|
|
}
|
|
if args.json:
|
|
print(json.dumps(report, indent=2))
|
|
return 0
|
|
if args.session and not args.turn:
|
|
print(f"{cost['total_usd']:.4f}")
|
|
return 0
|
|
if args.turn and not args.session:
|
|
print(f"{turn_cost['total_usd']:.4f}")
|
|
return 0
|
|
if args.display_lines or not args.details:
|
|
# One canonical format for every display path (CLI default,
|
|
# GUI display fields, Vibe hooks, Hermes plugin):
|
|
# agent_cost_estimator.display.format_display_lines.
|
|
for line in format_display_lines(report):
|
|
print(line)
|
|
return 0
|
|
label = f" ({meta.title})" if meta.title else ""
|
|
print(f"harness: {harness.name}")
|
|
print(f"session: {session_dir.name}{label}")
|
|
print(f"model: {display_key}") # display key: pool + aliases applied
|
|
if pool:
|
|
print(f"credit pool: {pool}")
|
|
if is_default:
|
|
print(" **model price not available**")
|
|
print(f"model calls: {usage.calls} "
|
|
f"(window on disk; pruned calls not counted)")
|
|
print(f"usage source: {usage.usage_source} "
|
|
f"(session-wide totals)")
|
|
print(f"input tokens: {usage.input_tokens:,} "
|
|
f"(cached {usage.cached_input_tokens:,}, "
|
|
f"fresh {usage.fresh_input_tokens:,})")
|
|
print(f"output tokens: {usage.output_tokens:,}")
|
|
# Add formatted token counts
|
|
print(f"input tokens (fmt): {format_token_count(usage.input_tokens)} "
|
|
f"(cached {format_token_count(usage.cached_input_tokens)}, "
|
|
f"fresh {format_token_count(usage.fresh_input_tokens)})")
|
|
print(f"output tokens (fmt):{format_token_count(usage.output_tokens)}")
|
|
print(f"pricing: {key} from "
|
|
f"{pricing_path if pricing_path else 'bundled pricing.json'}")
|
|
print(f"currency: {currency}")
|
|
print(f"prices ({currency}/M): input {rates['input_price']} "
|
|
f"cached {rates['cached_input_price']} "
|
|
f"output {rates['output_price']}")
|
|
print(f"input cost: ${cost['input_usd']:.4f}")
|
|
print(f"cached input cost: ${cost['cached_usd']:.4f}")
|
|
print(f"output cost: ${cost['output_usd']:.4f}")
|
|
print(f"TOTAL: ${cost['total_usd']:.4f}")
|
|
print("note: local estimate at the given rates; authoritative")
|
|
print(" usage is the provider's console")
|
|
if args.turns:
|
|
print()
|
|
print("turns:")
|
|
for turn in usage.turns:
|
|
if not turn.calls:
|
|
continue
|
|
turn_cost = compute_cost(
|
|
{"fresh": turn.fresh_input_tokens,
|
|
"cached": turn.cached_input_tokens,
|
|
"output": turn.output_tokens},
|
|
rates)
|
|
print(f" {turn.calls:>3} calls | "
|
|
f"in {turn.input_tokens:>8,} "
|
|
f"(cached {turn.cached_input_tokens:>8,}) | "
|
|
f"out {turn.output_tokens:>7,} | "
|
|
f"${turn_cost['total_usd']:.4f} | {turn.label!r}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|