npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

margin-meter

v0.2.0

Published

Tiny dependency-free client that auto-instruments OpenAI/Anthropic/Gemini and emits LLM call + outcome economics to a Margin ingest API.

Readme

margin-meter (TypeScript SDK)

The tiny client a TypeScript/JavaScript project imports to connect to Margin — the TS twin of the Python margin-meter package. It wraps your LLM calls and records their outcomes, emitting each one over HTTP to a Margin ingest API (POST /api/ingest/calls / /api/ingest/outcomes), authenticated with a per-project ingest key.

  • Dependency-free. Uses the global fetch — nothing to install at runtime.
  • Fail-safe. A failed emit resolves to { ok: false, … } instead of throwing. Pass raiseOnError: true for strict/CI behaviour.
  • Provenance-honest. isSimulated is carried through untouched; the written source is forced server-side to your key's project — you cannot spoof another project's economics.

Install

From the npm registry:

npm install margin-meter

Check the version you get. This package ships from the registry, and the registry can lag the repo. Confirm with npm ls margin-meter, and compare it against sdk/ts/package.json on main. An older release silently omits newer capture (e.g. substrate, reasoning tokens), which under-reports your spend rather than failing loudly — the one failure mode this SDK exists to prevent.

Unlike the Python SDK, this package is not git-installable: npm has no equivalent of pip's #subdirectory=, dist/ is a build artifact that is not committed, and the entry points resolve to ./dist. Installing from a clone or a git URL therefore yields a package with no entry point. Use the registry, or publish a new version from sdk/ts (npm publish runs the build via prepublishOnly).

Configure

Two environment variables — the deployed API base and your project's key:

export MARGIN_INGEST_URL="https://margin-ai-rho.vercel.app"
export MARGIN_INGEST_KEY="mgk_…"   # issued by the Margin owner

The Margin owner issues your project a key with the provisioning CLI in the Margin repo (python3 scripts/issue_ingest_key.py <your-project-slug>). The raw mgk_… key is shown once — only its hash is stored.

Use

import { MarginMeter } from "margin-meter";

const meter = new MarginMeter(); // reads MARGIN_INGEST_URL + MARGIN_INGEST_KEY

// 1) Wrap the LLM call — latency is timed automatically, cost computed server-side.
const answer = await meter.measure(
  { workflowId: "cart-parse", provider: "google", model: "gemini-2.5-flash" },
  async (m) => {
    const resp = await callTheModel(/* … */);
    m.setTokens({ inputTokens: 1200, outputTokens: 300, cacheReadTokens: 800 });
    return resp;
  },
);

// 2) Record the outcome it produced (the unit of productivity).
await meter.recordOutcome({
  workflowId: "cart-parse",
  passed: true,
  qualityScore: 0.94,
  qualityMethod: "ground_truth",
});

Or record a call directly:

const res = await meter.recordCall({
  workflowId: "cart-parse",
  provider: "google",
  model: "gemini-2.5-flash",
  inputTokens: 1200,
  outputTokens: 300,
});
if (!res.ok) console.warn(`margin ingest failed: ${res.error} (${res.statusCode})`);

Auto-instrument (a few lines for a whole repo)

To instrument an existing agent you didn't write, don't edit every call site. Point the meter at the client the agent already constructed and every model call is timed and metered automatically — tokens are read straight off each provider's response, so there's no setTokens bookkeeping:

import OpenAI from "openai";
import { MarginMeter, instrumentOpenAI } from "margin-meter";

const client = new OpenAI();
const meter = new MarginMeter();
const undo = instrumentOpenAI(client, meter, { workflowId: "aider-fix" });

// ... the agent's normal client.chat.completions.create(...) calls are metered ...

await meter.recordOutcome({ workflowId: "aider-fix", passed: testsGreen });
undo(); // restore the original method

instrumentAnthropic(client, …) patches messages.create; instrumentGemini(model, …) patches a GenerativeModel's generateContent (recovering the model id off the instance). Each returns an undo() and throws MarginInstrumentError if the client shape has moved.

Two lower-level primitives when you want tighter control:

// Wrap ONE call (no monkeypatch) — returns a drop-in replacement.
const create = meter.wrap(client.chat.completions.create.bind(client.chat.completions), {
  workflowId: "cart-parse",
  provider: "openai",
});
const resp = await create({ model: "gpt-4o-mini", messages: [/* … */] }); // metered; resp untouched

// Or meter a response you already have.
await meter.recordResponse({ workflowId: "cart-parse", response: resp, provider: "openai" });

Honesty: tokens are read verbatim from the real response (extractUsage) — cache reads are billed separately, never double-counted as fresh input — and a metering failure is fail-safe (your call still returns / still throws). A failed provider call is still recorded with status:"error" so it appears in the chain.

API

| Method | Emits to | Notes | | --- | --- | --- | | recordCall(input) | POST /api/ingest/calls | cost computed from the pricing table when costUsd omitted | | recordOutcome(input) | POST /api/ingest/outcomes | qualityMethod records HOW the score was graded | | measure(input, fn) | recordCall on completion | times latency; status:"error" + rethrow if fn throws; returns fn's value, emit result on m.result | | recordResponse(input) | recordCall | meters straight off a provider response — no manual tokens | | wrap(fn, opts) | recordCall per call | returns an auto-metered drop-in for any LLM call | | instrumentOpenAI / instrumentAnthropic / instrumentGemini | — | monkeypatch a client instance's create method |

Every method resolves to an IngestResult { ok, statusCode, body?, error? }. ok is true only on HTTP 200; body holds call_id/outcome_id + source.

Testing against the ingest contract (no network)

The network boundary is a single post(path, { json, headers }) protocol, so a test can inject a fake that mimics the ingest API's documented 200/401/422/429 responses:

const meter = new MarginMeter({ apiKey: "mgk_…", transport: fakeIngest, raiseOnError: true });

See test/meter.test.mjs. Run with npm test (node --experimental-strip-types --test test/*.test.mjs — zero deps).

Rate + validation bounds

Ingest is auth'd, validated, and rate-bounded server-side: bad key → 401, malformed/implausible row → 422, full rolling per-project window → 429. In fail-safe mode these come back as { ok: false, statusCode }.