omp packages

@abhishek944/pi-stats0.1.0

Generic Pi usage statistics extension and library with SQLite/PostgreSQL storage and a native Herdr Stats page.

abhishek944 Published 22 hours ago MIT ~0 downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

@abhishek944/pi-stats

Generic Pi usage statistics for any trusted host: one Pi extension/library, SQLite or PostgreSQL storage, per-event user attribution, and a native full-page Herdr Stats view.

This package records only new usage observed after collection is enabled. It does not scan, import, rewrite or delete Pi sessions, upstream caches, pricing files, or any operator data. It has no local price table, fallback pricing, remote price lookup, replay queue, automatic retry, or backend failover.

Install in Pi

pi install ./packages/pi-stats

The extension resolves local storage and identity from trusted process configuration. By default it creates pi-stats/usage.sqlite and a local identity record in Pi's agent directory.

Configuration

Variable Meaning
PI_STATS_ENABLED false, 0, no, or off makes the extension fully inert.
PI_STATS_STORAGE sqlite or postgres. A configured PI_STATS_DATABASE_URL selects PostgreSQL when this is unset.
PI_STATS_SQLITE_PATH SQLite database path.
PI_STATS_DATABASE_URL Private PostgreSQL URL supplied only to the trusted writer process. Never put it in argv, UI, logs, Git, or a model prompt.
PI_STATS_PG_SSL Use require for remote drivers that do not receive sslmode in the URL. TLS verification stays enabled.
PI_STATS_USER_ID Explicit local user label. Without it, a stable local pseudonym is persisted and labelled local/unverified.
PI_STATS_NAMESPACE Generic storage namespace. Default: local.
PI_STATS_SOURCE_ID Source installation label. A stable local value is generated without it.
PI_STATS_RECONCILE_MS Optional active-session reconciliation cadence for fresh entries without an extension event.
PI_STATS_SCOPE Trusted host JSON { "namespaces": [...], "userIds": [...] } for reports. An empty userIds list means all users inside the authorized namespaces. Filters only narrow this scope.
PI_STATS_AUTHORIZED_USER_IDS Comma-separated trusted scope when PI_STATS_SCOPE is not set. Without it, standalone local reports include all users in the local namespace.

Remote PostgreSQL must use driver-verified TLS (sslmode=require, verify-ca, or verify-full, or PI_STATS_PG_SSL=require). The package never disables certificate validation.

Library use

import { createUsageStatistics, bindAgentSession } from "@abhishek944/pi-stats";

const stats = await createUsageStatistics({
  storage: { kind: "postgres", connectionUrl: privateRuntimeUrl },
});

const factory = stats.extension({
  userId: verifiedHostUserId,
  identitySource: "host",
  namespace: authorizedHostNamespace,
  sourceId: serviceSourceId,
});

// SDK hosts can bind entry_appended directly instead of using the extension factory.
const unsubscribe = bindAgentSession(stats, session, sessionContext);

const report = await stats.report({
  scope: { namespaces: authorizedNamespaces, userIds: authorizedUserIds },
  time: { preset: "last30d", fromMs, toMs, label: "Last 30 days", kind: "rolling-duration" },
});

await stats.dispose();

userId passed to the library is attribution metadata. The host must authenticate the caller and authorize namespace/user membership before calling the library. All report dimensions use the same authorized and filtered event population.

Host-owned PostgreSQL store

A trusted host that already owns an authorized, protected PostgreSQL connection can inject its query boundary instead of supplying a connection URL:

import { createHostPostgresStore, createUsageStatistics } from "@abhishek944/pi-stats";

const stats = await createUsageStatistics({
  store: createHostPostgresStore(hostQuery),
});

hostQuery(text, values?) must execute the package's SQL through the host's existing connection and return { rows, rowCount? }. The host owns authentication, transport, TLS verification and pool lifetime; the package keeps the schema, normalization and write-failure policy here. This seam is not a way to bypass assertResolvedStorageConfig: URL-based storage still uses that validation and its verified-TLS requirement unchanged. Do not pass a query boundary that can be reached by untrusted code or that weakens certificate/host verification. Injected stores are not closed by stats.dispose().

Capture boundary

Finalized assistant responses, Pi-reported tool-result usage, summary and branch-summary usage, and generic Pi usage entries (including idle cache warming) are each recorded once. Streaming updates are ignored. Requests count finalized assistant responses only. Canonical tokens are input, output, cache read, and cache write; reasoning and one-hour cache writes are retained only as subsets. Valid Pi-reported cost is copied exactly, including zero. Missing or malformed cost is unavailable, never estimated.

Installed Pi 1.4.0 exposes entry_appended only through AgentSession.subscribe, not ExtensionAPI.on. The SDK adapter uses that supported event. The standalone extension snapshots fresh active-session entry IDs at session_start and reconciles newly appended entries in memory; it never scans session files. A reconciled entry whose write fails is not replayed.

Native Herdr Stats page

pi-stats install

The installer copies an Astack-owned native mod and its trusted host command into the Herdr app home, then adds a Stats entry to the top row beside Files, Changes, Routing, and Schedulers. It refuses shipped layouts until they are cloned and backs up any personal layout it changes. Selecting Stats opens a full native tab, not a narrow side panel.

The mod tells the user before it runs the host command. The command reads only nonsecret report filters from a file in the app home; database credentials stay in the host process environment. herdr-app check runs the mod without a real query.

Checks

npm run typecheck
npm run lint
npm run build
npm run check

No unit tests are included or run by this package.

Provenance

This package was derived from Techd81/pi-usage-statistics at commit cfc23a257fba56cc2db2cfba86faa67cf840aa62. It keeps Techd's MIT notice in LICENSE and records attribution in THIRD_PARTY_NOTICES.md. JSONL persistence, pricing fallback, historical session scanning, polling and the old TUI were removed rather than adapted, matching the resolved future-only and Pi-cost-only design.