Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions bin/omarchy-agent
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,15 @@ pi)
command=(pi)
[[ -n ${prompt:-} ]] && command+=("$prompt")
;;
freebuff)
# Freebuff takes no positional prompt; seeding the TUI through stdin is the
# documented path, and the prompt lands as if typed.
if [[ -n ${prompt:-} ]]; then
command=(bash -c 'printf "%s\\n" "$1" | freebuff' _ "$prompt")
Comment thread
digitallamb marked this conversation as resolved.
Resolved
else
command=(freebuff)
fi
;;
*)
echo "Unsupported default agent: $agent" >&2
exit 1
Expand Down
340 changes: 340 additions & 0 deletions bin/omarchy-agent-usage-freebuff
Original file line number Diff line number Diff line change
@@ -0,0 +1,340 @@
#!/usr/bin/python3
# omarchy:summary=Print the Freebuff usage record as JSON
# omarchy:args=[--force] [--limits-only]
# omarchy:hidden=true
"""Collect Freebuff usage into one display-ready JSON record.

Freebuff keeps chats under ~/.config/manicode/projects/<project>/chats/<UTC
timestamp>/: chat-messages.json (a JSON array of user prompts and AI replies),
chat-meta.json, and a debug log. It records no per-message token usage — the
free tier meters credits server-side ("creditsCharged": "server") — so token
counts here are estimates from message text (~4 characters per token),
attributed to a single "freebuff" model bucket. Prompts, sessions, and active
days are exact counts, dated from the epoch milliseconds embedded in every
message id (user-1790830285538). The agents panel only ever reads the JSON
this prints.
"""

import argparse
import fcntl
import hashlib
import json
import os
import re
import sys
import tempfile
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path

AGENT_ID = "freebuff"
AGENT_NAME = "Freebuff"
AUTH_HELP = "Start Freebuff, or run `freebuff login`, to sign in."

# A scan this recent is only reused to dedup concurrent collector runs (the
# update command backgrounds one per agent while the panel refreshes on its
# own); every periodic widget refresh lands a real rescan, however low
# refreshIntervalSec is set. --limits-only promises only fresh limits, so it
# may reuse a scan for up to 15 minutes. Freebuff exposes no limits endpoint,
# so both windows exist purely to keep the rescan cost down.
SCAN_REUSE_SECONDS = 20
LIMITS_ONLY_REUSE_SECONDS = 900

CHARS_PER_TOKEN = 4
# Message ids look like user-1790830285538 / ai-1790830285726-8f3c26a13464e:
# the number after the variant is the creation time in epoch milliseconds
# (10-digit values would be seconds; accept both).
MESSAGE_ID_TS = re.compile(r"^(?:user|ai)-(\d{10,})")
# Escape-safe fallback for a chat-messages.json that fails to parse (a file
# caught mid-write): user messages in the real objects are never string-escaped,
# so this only ever undercounts transiently.
RAW_USER_VARIANT = re.compile(r'"variant"\s*:\s*"user"')

now = datetime.now()
today = now.strftime("%Y-%m-%d")
recent_dates = [(now - timedelta(days=offset)).strftime("%Y-%m-%d") for offset in range(6, -1, -1)]
recent = {day: {"date": day, "messageCount": 0} for day in recent_dates}


def manicode_dir():
# No official override env var is known for Freebuff's config dir; honor
# MANICODE_CONFIG_DIR so the path stays overridable for testing.
return Path(os.environ.get("MANICODE_CONFIG_DIR") or (Path.home() / ".config" / "manicode"))


def local_day_from_epoch(value):
try:
seconds = value / 1000.0 if value > 10_000_000_000 else float(value)
return datetime.fromtimestamp(seconds).strftime("%Y-%m-%d")
except (OverflowError, OSError, ValueError):
return None


def message_day(message):
match = MESSAGE_ID_TS.match(str(message.get("id") or ""))
if match:
day = local_day_from_epoch(int(match.group(1)))
if day:
return day
return None


def message_text(message):
"""User prompts are plain strings; AI replies keep text in typed blocks."""
parts = []
content = message.get("content")
if isinstance(content, str):
parts.append(content)
blocks = message.get("blocks")
if isinstance(blocks, list):
for block in blocks:
if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("content"), str):
parts.append(block["content"])
return "".join(parts)


def chat_fallback_day(path):
"""Day for messages whose id carries no timestamp: the file's last write."""
try:
return datetime.fromtimestamp(path.stat().st_mtime).strftime("%Y-%m-%d")
except OSError:
return today


def scan_chat_file(path):
"""Return {day: {"prompts": n, "inChars": n, "outChars": n}} for one chat.

Returns {} for a chat with no datable messages; the caller decides whether
that still counts as a session. A parse failure falls back to a raw prompt
count on the file's last-write day so a session never vanishes from the
totals while Freebuff is rewriting it.
"""
fallback_day = chat_fallback_day(path)
per_day = {}
try:
data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
except Exception:
data = None

if isinstance(data, list):
for message in data:
if not isinstance(message, dict):
continue
variant = message.get("variant")
if variant not in ("user", "ai"):
continue
text = message_text(message)
if not text:
continue
day = message_day(message) or fallback_day
bucket = per_day.setdefault(day, {"prompts": 0, "inChars": 0, "outChars": 0})
if variant == "user":
bucket["prompts"] += 1
bucket["inChars"] += len(text)
else:
bucket["outChars"] += len(text)
return per_day

# Mid-write or foreign file: prompts only, no token estimates.
try:
raw = path.read_text(encoding="utf-8", errors="replace")
prompts = len(RAW_USER_VARIANT.findall(raw))
except OSError:
return {}
if prompts:
return {fallback_day: {"prompts": prompts, "inChars": 0, "outChars": 0}}
return {}


def chat_roots():
root = manicode_dir() / "projects"
if not root.is_dir():
return []
try:
return sorted(root.glob("*/chats/*/chat-messages.json"))
except OSError:
return []


def cache_root():
root = Path(os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache")) / "omarchy" / "agent-usage"
root.mkdir(parents=True, exist_ok=True)
return root


def cache_paths():
digest = hashlib.sha1((str(Path.home()) + "\n" + str(manicode_dir())).encode("utf-8")).hexdigest()[:16]
root = cache_root()
return root / f"freebuff-scan-{digest}.json", root / f"freebuff-scan-{digest}.lock"


def read_fresh_cache(path, max_age_seconds):
if max_age_seconds <= 0 or not path.exists():
return None
try:
# A negative age means the mtime is in the future: the clock moved
# backwards since the write, so the cache's freshness cannot be trusted.
age = time.time() - path.stat().st_mtime
if 0 <= age <= max_age_seconds:
cached = json.loads(path.read_text(encoding="utf-8"))
if isinstance(cached, dict) and cached.get("schemaVersion") == 1 and cached.get("scanDate") == today:
files = cached.get("files")
if isinstance(files, dict):
return files
except Exception:
return None
return None


def write_cache(path, entries):
handle_fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=path.name + ".", suffix=".tmp")
tmp = Path(tmp_name)
try:
with os.fdopen(handle_fd, "w", encoding="utf-8") as handle:
payload = {
"schemaVersion": 1,
"scanDate": today,
"updatedAt": datetime.now(timezone.utc).isoformat(),
"files": entries,
}
handle.write(json.dumps(payload, separators=(",", ":")) + "\n")
tmp.chmod(0o644)
tmp.replace(path)
except BaseException:
tmp.unlink(missing_ok=True)
raise


def collect_entries(max_age):
"""Per-chat usage entries, reusing unchanged files across scans.

Each entry is {"mtime": float, "size": int, "perDay": {...}} keyed by the
chat-messages.json path. A file whose stat still matches its entry is reused
as-is; only new or rewritten chats are re-read, so the mid-session chat that
Freebuff rewrites on every message is the only recurring parse cost.
"""
cache_file, lock_file = cache_paths()

with lock_file.open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
fresh = read_fresh_cache(cache_file, max_age)
if fresh is not None:
return fresh

old_entries = {}
try:
cached = json.loads(cache_file.read_text(encoding="utf-8")) if cache_file.exists() else None
if isinstance(cached, dict) and cached.get("schemaVersion") == 1 and isinstance(cached.get("files"), dict):
old_entries = cached["files"]
except Exception:
old_entries = {}

entries = {}
for path in chat_roots():
key = str(path)
try:
stat = path.stat()
except OSError:
continue
old = old_entries.get(key)
if isinstance(old, dict) and old.get("size") == stat.st_size and abs(float(old.get("mtime") or -1) - stat.st_mtime) < 1e-6:
entries[key] = old
continue
per_day = scan_chat_file(path)
if per_day:
entries[key] = {"mtime": stat.st_mtime, "size": stat.st_size, "perDay": per_day}
Comment on lines +246 to +249

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Incomplete scans hide usage When a previously counted chat is caught mid-write, this scan omits it. The cache is invalidated, but the usage-update wrapper still replaces the panel’s last good record with the incomplete result. Prompts, sessions, and token estimates can appear to drop until a later successful scan. Keep the last good entry for that chat or avoid publishing an incomplete record.


try:
write_cache(cache_file, entries)
Comment thread
digitallamb marked this conversation as resolved.
Resolved
except Exception as exc:
print(f"omarchy-agent-usage-freebuff: could not write usage cache ({exc})", file=sys.stderr)
return entries


def signed_in():
return (manicode_dir() / "credentials.json").is_file()
Comment thread
digitallamb marked this conversation as resolved.
Resolved


def build_record(entries):
total_prompts = 0
total_input_tokens = 0
total_output_tokens = 0
total_sessions = set()
active_days = set()
today_prompts = 0
today_sessions = set()
today_total_tokens = 0
today_tokens_by_model = {}
model_usage_bucket = {"inputTokens": 0, "outputTokens": 0, "cacheReadInputTokens": 0, "cacheCreationInputTokens": 0}

for key, entry in entries.items():
per_day = entry.get("perDay") if isinstance(entry, dict) else None
if not isinstance(per_day, dict) or not per_day:
continue
total_sessions.add(key)
for day, bucket in per_day.items():
if not isinstance(bucket, dict):
continue
prompts = int(bucket.get("prompts") or 0)
input_tokens = int(bucket.get("inChars") or 0) // CHARS_PER_TOKEN
output_tokens = int(bucket.get("outChars") or 0) // CHARS_PER_TOKEN
total = input_tokens + output_tokens
total_prompts += prompts
total_input_tokens += input_tokens
total_output_tokens += output_tokens
model_usage_bucket["inputTokens"] += input_tokens
model_usage_bucket["outputTokens"] += output_tokens
active_days.add(day)
if day in recent:
recent[day]["messageCount"] += total
if day == today:
today_prompts += prompts
today_total_tokens += total
today_sessions.add(key)
today_tokens_by_model[AGENT_ID] = today_tokens_by_model.get(AGENT_ID, 0) + total

authenticated = signed_in()
has_tokens = (total_input_tokens + total_output_tokens) > 0
record = {
"schemaVersion": 1,
"id": AGENT_ID,
"name": AGENT_NAME,
"updatedAt": datetime.now(timezone.utc).isoformat(),
"ready": authenticated,
"hasLocalStats": True,
"hasPromptStats": True,
"tierLabel": "Free" if authenticated else "",
"usageStatusText": "" if authenticated else "Freebuff not signed in",
"authHelpText": "" if authenticated else AUTH_HELP,
"limits": [],
"todayPrompts": today_prompts,
"todaySessions": len(today_sessions),
"todayTotalTokens": today_total_tokens,
"todayTokensByModel": today_tokens_by_model,
"recentDays": [recent[day] for day in recent_dates],
"totalPrompts": total_prompts,
"totalSessions": len(total_sessions),
"activeDays": len(active_days),
"activeDates": sorted(active_days),
"modelUsage": {AGENT_ID: model_usage_bucket} if has_tokens else {},
}
return record


def main():
parser = argparse.ArgumentParser()
parser.add_argument("--force", action="store_true")
parser.add_argument("--limits-only", action="store_true")
args = parser.parse_args()

max_age = 0 if args.force else (LIMITS_ONLY_REUSE_SECONDS if args.limits_only else SCAN_REUSE_SECONDS)
try:
entries = collect_entries(max_age)
except Exception as exc:
print(f"omarchy-agent-usage-freebuff: scan unavailable ({exc})", file=sys.stderr)
entries = {}
print(json.dumps(build_record(entries), separators=(",", ":")))


if __name__ == "__main__":
main()
5 changes: 3 additions & 2 deletions bin/omarchy-default-agent
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/bin/bash

# omarchy:summary=Set and launch the default coding agent
# omarchy:args=[pi|omp|opencode|ori|claude|codex|grok|openclaw|agy|hermes|copilot|crush|cursor-agent|muse]
# omarchy:args=[pi|omp|opencode|ori|claude|codex|grok|freebuff|openclaw|agy|hermes|copilot|crush|cursor-agent|muse]
# omarchy:examples=omarchy default agent | omarchy default agent codex | omarchy default agent claude

installing=false
Expand Down Expand Up @@ -32,6 +32,7 @@ claude | claude-code) agent="claude"; name="Claude Code" ;;
codex) agent="codex"; name="Codex" ;;
crush) agent="crush"; name="Crush" ;;
grok) agent="grok"; name="Grok" ;;
freebuff) agent="freebuff"; name="Freebuff"; agent_package="npm:freebuff" ;;
openclaw) agent="openclaw"; name="OpenClaw"; agent_installer="omarchy-install-openclaw-cli" ;;
agy | antigravity | antigravity-cli | gemini | gemini-cli) agent="agy"; name="Antigravity"; agent_package="antigravity-cli" ;;
hermes) agent="hermes"; name="Hermes"; agent_installer="omarchy-install-hermes-cli" ;;
Expand All @@ -43,7 +44,7 @@ muse | muse-code | musecode)
;;
cursor | cursor-agent) agent="cursor-agent"; name="Cursor CLI" ;;
*)
echo "Usage: omarchy-default-agent <pi|omp|opencode|ori|claude|codex|grok|openclaw|agy|hermes|copilot|crush|cursor-agent|muse>"
echo "Usage: omarchy-default-agent <pi|omp|opencode|ori|claude|codex|grok|freebuff|openclaw|agy|hermes|copilot|crush|cursor-agent|muse>"
exit 1
;;
esac
Expand Down
2 changes: 2 additions & 0 deletions default/omarchy/omarchy-menu.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@
"setup.default.agent.opencode": {"icon":"","iconFont":"omarchy","label":"OpenCode","checked":"[[ \"$(omarchy-default-agent)\" == \"opencode\" ]]","action":"omarchy-default-agent opencode"},
"setup.default.agent.ori": {"icon":"","iconFont":"omarchy","label":"Ori","checked":"[[ \"$(omarchy-default-agent)\" == \"ori\" ]]","action":"omarchy-default-agent ori"},
"setup.default.agent.pi": {"icon":"","iconFont":"omarchy","label":"Pi","checked":"[[ \"$(omarchy-default-agent)\" == \"pi\" ]]","action":"omarchy-default-agent pi"},
"setup.default.agent.freebuff": {"icon":"󰙱","label":"Freebuff","checked":"[[ \"$(omarchy-default-agent)\" == \"freebuff\" ]]","action":"omarchy-default-agent freebuff"},
"setup.default.browser": {"icon":"","label":"Browser","title":"Default Browser"},
"setup.default.browser.chromium": {"icon":"","label":"Chromium","checked":"[[ \"$(omarchy-default-browser)\" == \"chromium\" ]]","action":"omarchy-default-browser chromium"},
"setup.default.browser.chrome": {"icon":"󰊯","label":"Chrome","checked":"[[ \"$(omarchy-default-browser)\" == \"chrome\" ]]","action":"omarchy-default-browser chrome"},
Expand Down Expand Up @@ -246,6 +247,7 @@
"install.ai.chatgpt": {"icon":"","iconFont":"omarchy","label":"ChatGPT Desktop","disabled":"omarchy-pkg-present openai-codex-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-ai-chatgpt"},
"install.ai.claude": {"icon":"","iconFont":"omarchy","label":"Claude Desktop","disabled":"omarchy-pkg-present claude-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-ai-claude"},
"install.ai.dictation": {"icon":"","label":"Dictation","disabled":"omarchy-pkg-present voxtype-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-voxtype-install"},
"install.ai.freebuff": {"icon":"󰙱","label":"Freebuff CLI","when":"! omarchy-cmd-present freebuff","action":"omarchy-launch-floating-terminal-with-presentation 'omarchy-default-agent --install freebuff'"},
Comment thread
digitallamb marked this conversation as resolved.
Resolved
"install.ai.grok-bot": {"icon":"","iconFont":"omarchy","label":"Grok Bot","disabled":"omarchy-pkg-present grok-bot","action":"omarchy-install-and-launch 'Grok Bot' grok-bot grok-bot"},
"install.ai.hermes": {"icon":"","iconFont":"omarchy","label":"Hermes Desktop","disabled":"omarchy-pkg-present hermes-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-ai-hermes"},
"install.ai.lm-studio": {"icon":"","iconFont":"omarchy","label":"LM Studio","disabled":"omarchy-pkg-present lmstudio-bin","action":"omarchy-install-app 'LM Studio' lmstudio-bin"},
Expand Down
Loading