What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
one record or an array, in usage.jsonl's shape:
- the post may carry up to 5000 records and 32 MiB;
- t, agent, provider, model and rid are required.
Each field is checked: unknown fields, quoted numbers, negative or absurd
counts, a status outside 100-599, a cost over 10000 USD, and a t more
than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
whole post with a 400 that names error.index and error.param, and nothing
is written. A past t is otherwise taken as given, so history can be
backfilled. The reply gives accepted and skipped counts and each
record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
shared, behind the Host check). A browser page also needs a key, since
corsGuard lets localhost pages and Origin null through. A held key is
refused.
- usage.IngestReported writes under usage.mu to the same file as
usage.Append. Rows carry source "reported" and no caller key. A rid
already reported is skipped, as is one repeated in the post. The set of
reported rids is read back from the log: one scan after a restart (lines
without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
flag; packed flags widened to uint16). Otherwise it is priced at
magpie's prices.
- Display:
- SourceReported is a source of its own: RequestPage.Reported,
?via=reported, and Ledger now honours via.
- The Requests tab gains a fourth cell "reported by apps", shown once
there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
- a key's budget/spend limit (budget.counts);
- window holds, and the log start that decides whether a window can be
reckoned (logSnapshot.firstOwn);
- gateway sessions and Vias;
- Codex's sealed answers and remembered model.
There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
site integrate.html (en, zh).
Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.
Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
- usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
languages, 1180 and 420 wide, light and dark);
- usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
- 40 posts of 5000 took 0.40 s (worst batch 18 ms);
- the first post after a restart took 0.45 s (rid rescan), a later one
1.6 ms;
- the cold index build took 2.1 s (as for gateway rows);
- page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
- summary all took 215 ms, 30d 20 ms.
Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
cost; the block pricer overwriting own cost; the Reported split;
fromBrowser's key rule; skipping bad records instead of refusing; the
max-records and body limits; the ingest lock (race); both locks;
firstOwn -> first; the IsReported guards in windowHolds,
buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.
Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
8.2 KiB
Integrating your app or agent with magpie
For developers of an AI app, agent or client who want it to work well with magpie. There are three levels, from no work on magpie's side to a row of your own on the Agents page. The web version is https://usemagpie.ai/docs/integrate.
| You want | Route | Change to magpie |
|---|---|---|
| Your app's requests served by magpie, counted under its own name in Usage | Talk to the gateway | none |
| A row on the Agents page: detected, its model picked there, put back on disconnect | An agent adapter | a pull request |
| A new model source (a subscription, a vendor), or rewriting requests | A plugin | none |
1. Talk to the gateway
magpie runs a local LLM gateway. Every model the user has in magpie (subscriptions, API keys, local models, routing groups) is served there under one id each, so your app needs one provider entry, not one per vendor.
Find it. The gateway listens on 127.0.0.1:3425, or on the port in
port of magpie's settings.json (~/.config/magpie/settings.json, the
same path under the user's folder on Windows; $XDG_CONFIG_HOME/magpie
when that is set). GET /api/hello answers
{"name":"magpie","version":"…"} when it is magpie. Read that file, never
write it. magpie must be running (the app or magpie serve). An app that
finds nothing there should offer its own providers as usual.
Endpoints. Requests go straight through when the vendor speaks your API, and are translated otherwise, streaming, tool calls, images and reasoning included:
| Path | API |
|---|---|
/v1/chat/completions |
OpenAI Chat Completions |
/v1/responses |
OpenAI Responses |
/v1/messages, /v1/messages/count_tokens |
Anthropic Messages |
/v1beta/models/{model}:generateContent (and :streamGenerateContent) |
Google Gemini |
/v1/models |
the catalog |
So the base URL is http://127.0.0.1:<port>/v1 for an OpenAI client and
http://127.0.0.1:<port> for an Anthropic or Gemini one.
The key names your app. On this machine the gateway takes any key.
Send magpie-<your-app-id> (Authorization: Bearer magpie-acme, or
x-api-key) and every call is counted as acme in Usage, the Requests
log and the routing rules that match on agents. Without it, magpie counts
the call by the first word of your User-Agent (Acme/1.4 (darwin) is
Acme); an SDK's own User-Agent (OpenAI/JS …, ai-sdk/…) would count it
as that SDK. From another computer (Settings → Share on local network) the
key must be one of the user's gateway keys, and the User-Agent names your
app.
Models. GET /v1/models lists what the user has turned on: id
(provider/model, or a routing group's name, which you send as it is),
display_name, owned_by (the provider), reasoning and
supported_reasoning_levels ([{"effort":"low"},…]), context_window
and max_output_tokens when known, modalities when magpie knows whether
it takes images. List them from there rather than shipping a list: the
user adds and removes providers in magpie. Reasoning is asked in your
API's own field (reasoning_effort, reasoning.effort, Anthropic's
thinking or output_config.effort). ?format=text gives the ids one a
line.
Optional. Send X-Magpie-Session: <id> with a conversation's requests
and GET /v1/magpie/route?session=<id> says which model a routing group
picked for the turn and the fallbacks it tried, before the first token
(long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the
user's subscription allowances, and GET /v1/magpie/usage and
/v1/magpie/usage/requests the Usage page's numbers and its requests
(with session, and subagent/parent_agent for a Claude Code
subagent's call). They answer only this machine, or another with a gateway
key; a key held to a budget, models or accounts sees its own calls alone.
Calls your app makes to its vendor itself can be reported with POST /v1/magpie/usage/requests (one record or up to 5000 a post, in
usage.jsonl's shape, each with a rid; past times are kept, so a
history can be backfilled). They show on the Usage page as reported, and
never count against a key's limit. Connecting anything else
has the details.
Keep the user's providers. Add magpie as one more provider (named Magpie) beside the ones the user set up in your app, rather than replacing them, so turning magpie off is picking another provider.
2. A row on the Agents page
The agents magpie lists (Claude Code, Codex, OpenCode, dsh, Alma, Cindy…)
are adapters in internal/agent, one file each,
listed in agents.go. A row gets your
app's name and icon, shows when your app is installed, lets the user pick
its model (and reasoning) from magpie's catalog, follows the catalog as
providers change, and on disconnect puts back what your app had before.
There is no runtime registration: a row is added by a pull request to
this repository, and ships in the next release.
An adapter is an Agent value. What your
app offers decides its shape:
- magpie edits your config file (most adapters;
fx.go,empryo.go).Dir,PathandBinfind the app; eachField(model,effort, …) hasGet,SetandOptions. Connecting adds amagpieprovider at the gateway, keyedmagpie-<id>, and sets your model to one of magpie's;Set("")(the agent's default) orUnwiretakes magpie's entries out and restores what was there. Only the keys magpie sets are touched; the user's other settings, providers and comments stay.Noticesays when your app must be restarted to see a change;Syncrewrites a model list your app keeps in a file rather than asking/v1/models. - Your app takes a provider only through its own import link, which the
user confirms in your app (
cindy.go).Importreturns the link (yourapp://provider/import?…carrying the gateway's URL, the keymagpie-<id>and the endpoints), the row's button opens it, and the user says yes once, in your app.Addedreads, read-only, whether your app has magpie already. magpie writes nothing of yours. This suits an app that keeps its providers in a database or encrypted. - Your app has a local API while it runs (Alma, at
localhost:23001): magpie adds itself as a provider and sets the default model through it.
A pull request needs: the adapter and its registration, UA (what your
User-Agent begins with, lower-case) so Usage knows your calls, an icon in
internal/gui/assets/icons, tests that run under a temporary HOME
(connect, switch, disconnect restoring the original file), and a row in
the Agents table. What helps us most is a stable,
documented config format or import link, and where your app keeps it on
each system.
3. Plugins
A plugin is an npm package magpie runs; the user installs it from
Settings → Plugins or with magpie plugin add <package>. There are two
kinds (plugin guide):
- Provider plugins, OpenCode's
authhook or a pi package: a new source of models, such as a subscription magpie doesn't sign in to itself. They sign in, list models and make requests. - Gateway middleware: rewrites requests and replies as they pass
(
onRequest,onEvent,onResponse).
A plugin can't add a row to the Agents page or write another app's config, so it is not how an app registers itself.
What isn't there
- No API or link lets another app register itself as an agent, or install a plugin, without the user: plugins are installed in magpie by the user, and agent rows come from adapters in magpie's source.
magpie://importlinks add a provider (a source of models, with its key), not an agent or an app; see Import links.
Questions, or an adapter you'd like to discuss first: open an issue at https://github.com/yetone/magpie/issues or ask on Discord.