@xerg/cli
v0.32.1
Published
Find wasted AI spend in OpenClaw, Hermes, QM, Claude Code, and Cursor — plus any framework via event ingest.
Maintainers
Readme
xerg
Find wasted AI spend in OpenClaw, Hermes, QM, Claude Code, Cursor, and any framework that can export a JSON event payload.
Copy/paste to your agent and go:
set up https://xerg.ai/skill.mdAudit data stays on your machine unless you choose to push it.
The skill walks a terminal-capable agent through permission-gated setup, a first audit, and optional hosted push. Agents follow its npx + doctor --json path, not the interactive init flow.
Keep your results. Connect a free workspace only when you want a durable dashboard record: npx @xerg/cli@latest activate --push-latest.
Xerg audits AI spend in dollars, surfaces provenance-aware waste findings, compares fixes, and optionally connects hosted follow-up after the first local result.
Xerg runs locally by default. Local audits and --compare are free. Local commands remain telemetry-free and add no analytics call. Explicit hosted pairing and push requests include a fixed, content-free execution-context envelope; audit data leaves your machine only when you explicitly push results to Xerg Cloud.
The npx @xerg/cli@latest path fetches and executes the published npm package before running Xerg. If you want to avoid a runtime fetch, install once with npm install -g @xerg/cli.
The CLI is publicly installable from npm, but it is not open source. The public machine-readable integration contract is the MIT-licensed @xerg/schemas package.
Fastest first run
This is the interactive human path. Agents: use the skill above instead — init is TTY-only.
npx @xerg/cli@latest initinit is the default first-run path. It:
- detects local OpenClaw, Hermes, or Claude Code data
- runs a first audit and stores the local snapshot
- prints the provenance-aware terminal summary
- offers optional browser-approved hosted follow-up and
mcp-setup
Prefer a global install?
npm install -g @xerg/cli
xerg initDirect commands for explicit control
If you already know what you want, skip init and use the direct flows:
npx @xerg/cli@latest doctor
npx @xerg/cli@latest doctor --runtime claude-code --json
npx @xerg/cli@latest audit
npx @xerg/cli@latest audit --details
npx @xerg/cli@latest audit --compare
npx @xerg/cli@latest audit --runtime claude-code
npx @xerg/cli@latest collect openclaw
npx @xerg/cli@latest collect hermes --state-db ~/.hermes/state.db
npx @xerg/cli@latest audit --runtime qm --fly-app <qm-core-app> --since 7d
npx @xerg/cli@latest audit --otlp-file ./openclaw.capture.jsonl
npx @xerg/cli@latest audit --cursor-usage-csv ./cursor-usage.csv
npx @xerg/cli@latest ingest --file payload.json
npx @xerg/cli@latest audit --json
npx @xerg/cli@latest audit --markdown
npx @xerg/cli@latest explain <item-id-or-prefix>Plain audits use a compact, width-aware human report. --details selects the exhaustive terminal projection for audit, ingest, each collect command, and doctor. Agents and scripts should use --json and must not parse compact, detailed, or Markdown reports; those human-facing projections may evolve between releases.
Use these when you need non-interactive behavior, CI gates, JSON/Markdown output, or explicit runtime and path flags.
Xerg reports agent-runtime economics from the evidence each runtime exposes. Costs may be observed, locally estimated, or unpriced; they are not provider-invoice reconciliation. Provider-billing ingestion and runtime-to-FOCUS conversion are not current capabilities. See the FOCUS retirement note.
Bundled skill
The published @xerg/cli package includes the portable Xerg skill bundle inside the installed package at:
skills/xerg/SKILL.mdFor a local project install, that usually resolves to:
node_modules/@xerg/cli/skills/xerg/SKILL.mdFor a global install, the same file lives inside the global npm package directory instead. The same canonical skill is also mirrored at xerg.ai/skill.md. Use it if your agent platform imports skills from disk; installing the npm package does not automatically register the skill with every agent product.
The bundled skill frontmatter declares the CLI/package surface plus optional Xerg Cloud and remote audit requirements so registries can distinguish the default local audit workflow from opt-in hosted sync and remote audit workflows.
Supported runtime
@xerg/cli supports Node 22.13.0 and newer.
If you have access to the private Xerg source repository, .nvmrc pins the default toolchain to Node 24.14.0.
Sample output
Xerg agent runtime audit
Runtime/source: openclaw; 1 file (openclaw-otlp)
Activity window: all observed activity
Measurement: observed and locally estimated economics; not invoice
reconciliation.
Truth limitations
[WARNING] COVERAGE WARNING: Some sequence-dependent waste detectors were not
fully assessed. Identified waste covers assessed evidence only; zero
identified waste is not conclusive.
Economics and outcomes
Total spend: $0.0100
Identified waste: $0.0000 (0%)
Runs: 1
Model calls: 1
Calls with pricing: 1 / 1 calls
Request-sequence coverage: 1 / 1 requests (full)
Cost per successful run: $0.0100
Action queue
- Fix now: none
- Test next: none
- Watch: none
Findings
- none detected
Signals - observations, not classified waste
- none observed
Top workflows
- openclaw-fixture: $0.0100 (100% observed)
Top models
- anthropic/claude-sonnet-4-6: $0.0100 (100% observed)
Coverage summary and notes
- Pricing: 1 priced, 0 unpriced calls
- Sequence detection: full; 1 / 1 requests eligible
- Source stability: stable
- Note: Cost per outcome uses observed terminal states and declared outcomes;
runs without an outcome signal are excluded.
More detail
- Compact view omits diagnostic appendices only.
[INFO] Run the full local report.
Next command:
xerg audit --runtime openclaw --otlp-file './capture.jsonl' --detailsCommon commands
xerg init
xerg audit --compare
xerg outcome --workflow my-workflow --status success
xerg activate --push-latest
xerg mcp-setupMore explicit examples:
xerg doctor --runtime openclaw
xerg audit --runtime hermes
xerg collect openclaw --output ./openclaw.capture.jsonl
xerg audit --otlp-file ./openclaw.capture.jsonl
xerg collect hermes --state-db ~/.hermes/state.db --output ./hermes.capture.jsonl
xerg audit --runtime hermes --state-db ~/.hermes/state.db --otlp-file ./hermes.capture.jsonl
xerg connect qm --fly-app <qm-core-app>
xerg collect qm --fly-app <qm-core-app> --since 7d --output ./qm.jsonl
xerg audit --runtime qm --qm-snapshot ./qm.jsonl
xerg audit --since 24h --compare
xerg audit --push
xerg pushWorks where your agent data lives
- Local/operator machine: OpenClaw logs/transcripts or an independent sanitized trace capture, Hermes, QM through a sanitized snapshot, strict direct reader, or Fly-contained exporter, Claude Code, and explicit Cursor usage CSV exports
- Any other framework: export a Xerg event payload and run
xerg ingest --file payload.json - VPS or remote server: OpenClaw only in this phase
- If OpenClaw runs remotely, you can audit it from your local machine with
xerg audit --remote user@host - Or point Xerg at exported files directly with flags
Remote prerequisites:
- SSH audits require
sshandrsyncon yourPATH - Optional legacy Railway audits require the
railwayCLI on yourPATH
Remote comparison identity includes the normalized --since window and, when mixed OpenClaw source authority is engaged, the source-authority version. 024h and 24h are equivalent, while a different window intentionally starts a separate comparison history. The first mixed remote --compare run after upgrading to 0.28.0 does not use a pre-0.28 baseline; the next mixed run with the same target, paths, and window compares normally. Single-kind remote audits retain their existing identity. A push across the mixed-source boundary has new economic and analysis fingerprints, so it may consume one Free snapshot or return the normal at-quota 429 response.
Default paths
By default, Xerg checks:
- OpenClaw:
/tmp/openclaw/openclaw-*.log - OpenClaw:
~/.openclaw/agents/*/sessions/*.jsonl - Hermes:
~/.hermes/state.db(preferred, read-only, v0.17-v0.20.1) - Hermes observer:
~/.hermes/xerg/events/when the optional plugin is enabled - Legacy Hermes logs/transcripts are fallback inputs only where those files still exist
- Claude Code:
~/.claude/projects/ - QM: no auto-probed path; configure explicitly with
xerg connect qm
Use explicit paths when needed:
xerg audit --runtime openclaw --log-file /path/to/openclaw.log
xerg audit --runtime openclaw --sessions-dir /path/to/sessions
xerg collect openclaw --output ./openclaw.capture.jsonl
xerg audit --otlp-file ./openclaw.capture.jsonl
xerg audit --runtime hermes --state-db ~/.hermes/state.db
xerg audit --runtime hermes --hermes-events-dir ~/.hermes/xerg/events
xerg collect hermes --state-db ~/.hermes/state.db --output ./hermes.capture.jsonl
xerg audit --runtime hermes --state-db ~/.hermes/state.db --otlp-file ./hermes.capture.jsonl
xerg audit --runtime claude-code --claude-code-dir /path/to/projects
xerg doctor --runtime qm --fly-app <qm-core-app>
xerg audit --runtime qm --fly-app <qm-core-app> --since 7d
xerg audit --cursor-usage-csv ./cursor-usage.csv
xerg ingest --file payload.jsonWhen both OpenClaw gateway logs and session transcripts produce calls in the requested audit window, Xerg uses transcripts as the sole authority for every audit calculation and excludes gateway runs. This avoids additive counting when both files describe overlapping activity. Transcripts preserve agent identity, lineage, and per-tool evidence, but they can omit gateway-only activity and do not retain gateway-observed iteration structure. The report names the source decision and warns that activity and spend may be understated and findings may differ from a fully reconciled view. Gateway-only and transcript-only audits are unchanged; pass only --log-file or only --sessions-dir to select one local source kind explicitly.
Monetary and detector-coverage gates evaluate only the authoritative transcript result. A passing gate does not certify gateway-only activity that the mixed audit may have omitted.
Optional content-free mechanical telemetry:
hermes plugins install xergai/hermes-observer --enableObserver events remain local and never contribute economic calls. Complete matching request evidence may split a state.db aggregate into ordered calls without changing authoritative requests, tokens, cost, or economicAuditId. The analysis auditId includes detector coverage and findings. Hermes and OpenClaw both expose detector coverage, tool activity, and workload economics; Hermes retains its additional mechanical section.
Xerg 0.24.2 certifies Hermes state schemas 16 through 25. Later schemas are read best-effort with a local warning. On Hermes v0.20.x, generated and truncated terminal quantities can be conservative byte floors and render as “At least”; returned bytes remain exact. Xerg never reads or retains a terminal spill path. Xerg 0.24.0 terminal mechanics were not certified for Hermes v0.20.x and could understate those values; 0.24.1 fixed those measurements.
State-only Hermes audits preserve aggregate spend, request/token/cache totals, workflows, models, tools, and delegated workload totals. They do not invent first-request cost, initial context, request-level growth, retries, or identical-input loop evidence. Xerg 0.24.2 uses a bounded per-process health sidecar for continuous liveness without adding heartbeat evidence. After installing or restarting the observer, run xerg doctor --runtime hermes --require-observer-live before new Xerg-directed activity. It exits 5 unless the observer is running and its writer is not known unhealthy. Historical aggregate sessions cannot be reconstructed; existing audits remain available with an aggregate-only warning before totals and conclusions.
Hermes v0.20.1 auxiliary tasks such as title_generation are economically recorded in state.db but are not exposed by Hermes's public per-request hooks. Xerg preserves them as separately attributed aggregates and marks their sequence analysis unavailable, while exact observer evidence for main and delegated requests remains usable.
xerg collect openclaw accepts OTLP/HTTP protobuf traces on 127.0.0.1, sanitizes them before writing a bounded owner-only capture, and audits that capture after Ctrl-C. It accepts traces only, never merges the capture with transcripts, and never pushes automatically. OpenClaw toolActivity and workloadEconomics blocks stay local and do not affect findings, recommendations, waste totals, or CI gates.
xerg collect hermes accepts the same loopback traces-only protocol for the exact certified briancaffey/hermes-otel commit. It HMACs identifiers with a persistent owner-only local key, rejects content and arbitrary attributes, and requires state.db for monetary authority. Cache-inclusive plugin prompt totals are reconciled into Xerg's separate input/cache buckets. Optional trace enrichment preserves economicAuditId; the analysis auditId changes if coverage or findings change. The command prints both the standard YAML and equivalent environment variables for non-default HERMES_HOME profiles, because the pinned plugin resolves YAML under ~/.hermes. A moved capture without its matching key remains descriptive only.
QM is an explicit, one-shot source with a host-independent qm-snapshot/v1 adapter. xerg connect qm --print-sql prints portable export views, indexes, and a strict direct-reader role. --print-views-sql prints only the portable contract for Fly-contained mode. Fly Managed Postgres uses a pinned one-shot exporter inside QM core and truthfully records a process boundary with databaseLeastPrivilege: false; no database URL leaves core. Profiles store no credential. Raw identifiers are HMACed before persistence, content fields are excluded, current tool evidence reflects QM's one-hour retention, and unresolved openrouter/auto or negative placeholders remain unpriced with monetary gates exiting 5.
If only one supported local runtime is present, Xerg auto-selects it. If more than one is present locally, rerun with --runtime openclaw, --runtime hermes, or --runtime claude-code.
If local defaults are empty, xerg init prints next-step commands for explicit local paths plus remote OpenClaw-only flows:
xerg audit --remote user@hostHosted follow-up
Pushed audits go to a hosted workspace; related incremental snapshots are grouped into expandable series, the free plan keeps the last 30 days of pushed audits, and hosted MCP requires Team, Growth, Scale, or Enterprise. The simplest hosted path is:
xerg activate --push-latest
xerg mcp-setupactivateopens Xerg for explicit workspace approval, shows the exact organization/plan/environment, encrypts the workspace credential to this CLI, stores it with owner-only permissions and API-environment binding, and pushes the latest auditmcp-setupprints or writes hosted MCP config for Cursor, Claude Code, Codex, or another client- hosted Optimizations provide a Fix with Xerg Markdown handoff; paid hosted MCP can retrieve the same safe handoff by Optimization ID without changing code automatically
- paid workspace admins can connect Linear and create one sanitized, one-way issue per Optimization; Xerg does not synchronize issue status or change the Optimization automatically
You can skip both and keep using local audits and compare.
If you have not run a local audit yet, use xerg activate. It connects the workspace, detects a supported local source, runs an audit, and pushes it.
Browser-approved activation
xerg activate creates a short-lived pairing code, opens Xerg, and waits while the signed-in user approves the active workspace. The page shows the workspace name, full Clerk organization ID, live plan, API environment, action, and CLI version. The browser never displays the workspace key. Xerg encrypts it to the initiating CLI's temporary key, and the CLI acknowledges the exchange only after live organization/plan verification and owner-only local storage.
Use xerg activate --organization-id org_... when you know the intended Clerk workspace. The browser organization switcher preserves the code, while both the page and API refuse approval for another organization. New credential files remember their API origin and approved organization so a staging credential cannot silently default to production; token-only legacy files remain supported.
Use xerg activate --connect-only --organization-id org_... when approval covers credential pairing but not an audit or push. The approval page says that no audit or push is requested, and the CLI returns immediately after live entitlement verification and owner-only credential storage. --connect-only is mutually exclusive with every audit and push source flag.
Use xerg activate --replace to pair a different workspace. If an exact organization was requested, use both flags. Re-pairing reuses the active recoverable workspace key; rotating the key in Dashboard Settings revokes the credential for every paired CLI.
Advanced authentication and config
The masked-paste flow remains a manual recovery path:
xerg login --replaceThe prompt masks workspace-key characters and verifies the replacement before atomically updating the existing credential.
For non-interactive CI only, store XERG_API_KEY in the CI provider's secret manager. Never place the key inline in a shell command, where shell history and same-user process listings can expose it.
Push commands still resolve advanced credentials in this order:
XERG_API_KEY- the credential stored by
xerg activateor advancedxerg login - legacy
~/.xerg/config.json
XERG_API_URL and apiUrl in ~/.xerg/config.json remain optional endpoint overrides.
Free stores up to 100 distinct snapshots per UTC month. At the limit, push output includes the current usage, UTC reset time, and upgrade URL. Identical retries are deduplicated before quota accounting and remain safe.
What the audit shows
- Total spend by workflow and model, in dollars, priced across all four token dimensions (input, output, cache read, cache write) with a catalog covering hundreds of current models
- Daily spend and identified-waste rollups in UTC
- Observed vs. estimated cost (always labeled)
- Evidence-strict monetary findings: correlated retry waste, exact no-progress tool loops, and net-negative cache lifecycles
- Separate neutral signals for deep loops, context outliers/growth, fixed cadence, premium-model routine labels, cache-read concentration, and Max Mode concentration
- Digest-only local evidence packets and
xerg explainfor findings, signals, and qualifying repeated tool chains - Argument-diversity diagnostics for contiguous two-to-five-tool chains; associated spend is non-additive and always labeled “not classified as waste”
- Per-finding affected and avoidable spend, evidence/impact basis, detector version, and component-level claim ownership so totals never double-count
- Cost per outcome when runs carry outcome signals: success rate, cost per successful run, and spend on failed runs (declare outcomes with
xerg outcome) - Cache/reasoning token economics rollups when the source reports them
- Ranked recommendations with where-to-change guidance and compare validation steps
- Before/after normalized rates on re-audit, including waste per run and waste per 1k calls
- Local-only OpenClaw tool activity and workload economics when transcript or trace evidence supports them
Local JSON and Push v7 separate findings from signals. Findings include affectedSpendUsd, avoidableSpendUsd, evidenceBasis, impactBasis, and detectorVersion; signals include bounded observed metrics, an optional human-readable scopeLabel, plus optional associated spend and its basis. Push v7 adds daily priced and unpriced call counts without changing known-spend semantics. Current producers also add the optional requested auditWindow, detector-attributed wasteByWorkflow, detector-versioned comparison finding changes, observed immediate parent-to-child agentDelegations, and comparison.spendComparisonAvailable, which is true only when both measurements had priced calls. Delegation spend is already included in child agent and audit totals and must not be added again. A missing spend-comparison availability flag is treated as unavailable, preventing an unpriced baseline's placeholder zero from becoming an exact delta. Older v7/v6 payloads remain valid without these optional fields. Chain-backed deep-loop-activity may carry a content-free distinct tool-input ratio. Associated spend is descriptive and never classified as waste. Local diagnostics, paths, tool/result digests, per-TTL cache buckets, and pricing-limit details do not cross the wire. Raw prompts, tool arguments, results, and cache content are never retained in evidence packets. Wire v5 history remains readable with a legacy-method marker but cannot create current optimization recurrence.
Privacy
Xerg stores economic metadata and audit summaries locally. It does not store prompt or response content. The OpenClaw trace collector also rejects content-bearing attributes even if the upstream exporter was misconfigured.
Pairing creation and explicit pushes send only a version, coarse execution context (ci, human, agent, or non_interactive), a bounded native-agent marker or skill-provided host hint when present, and the package invocation path. Pairing polling, acknowledgement, cancellation, entitlement verification, doctor, local audits, explain, outcome, and update-check suppression do not send this envelope. It is analytics metadata, not authentication, and excludes content, findings, costs, paths, source identifiers or hostnames, URLs, IP/geography, names, email addresses, user IDs, and Clerk organization IDs.
Exit codes
0: success1: general failure2: no economic runtime data was found, or activation is required3: a--fail-above-waste-rateor--fail-above-waste-usdthreshold was exceeded5: required observer liveness or detector coverage failed, a monetary threshold could not be evaluated because no active monetary detector assessed the source (or QM pricing was incomplete), or the standalonexerg pushcommand hit a hosted quota, member-limit, capability, or retained-history product condition
Monetary thresholds evaluate identified waste when at least one active monetary detector has partial or full coverage over positive eligible request evidence. They exit 5, rather than passing against a non-conclusive zero, when every active monetary detector is unassessed. Use --require-detection-coverage if CI requires stricter overall completeness.
The current release deliberately preserves one compatibility difference: standalone xerg push returns 5 for those hosted product conditions, while the same hosted rejection reached through xerg audit --push returns the general error code 1.
Troubleshooting
- If install fails with an unsupported engine warning, retry with Node 22.13.0 or newer.
xerg initis interactive in the current release. Use directdoctor/auditcommands when you need non-interactive control.--detailsselects the full human report foraudit,ingest, everycollectcommand, anddoctor; it does not alter JSON or raw payload output.--verboseprints audit/ingest operational progress, collector diagnostics, or doctor progress to stderr. Doctor keeps its local extraction-coverage appendix on stdout after the main report.xerg doctor --jsonreturns a common readiness envelope and shell-safe recommended audit command for every supported mode.- If
xerg audit --remote ...fails before pulling files, verify that bothsshandrsyncare installed and reachable on yourPATH. - If a legacy Railway audit fails immediately, verify that the
railwayCLI is installed, authenticated, and can access the target project.
Pricing and support
Hosted pricing follows known Monthly Audited Agent Spend in explicitly pushed audits: Free through $2,000 per UTC month, Team at $99 through $10,000, Growth at $299 through $50,000, Scale at $799 through $250,000, and custom Enterprise above $250,000. Team, Growth, and Scale include identical capabilities.
- Pricing: xerg.ai/pricing
- Service status: status.xerg.ai
- Support:
[email protected]
License
The @xerg/cli package is licensed under the Xerg CLI License Agreement,
also published at xerg.ai/cli-license. The separate
@xerg/schemas package remains available under the MIT License.
