Files
magpie/internal/gateway/codex_memory.go
T
yetone d4c2512d2d usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
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.
2026-10-13 06:32:03 +08:00

105 lines
4.0 KiB
Go

package gateway
import (
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// isMemoryKind: a call Codex makes to write or consolidate its memories,
// however it names one (usage.PurposeOf's memory_consolidation).
func isMemoryKind(kind string) bool {
return usage.PurposeOf(kind) == "kind:memory_consolidation"
}
// codexTurnKey is whose turns codexTurns holds: the agent recorded and the
// gateway key it came with, so a Codex on another computer (its own key,
// #742's Codex-BWG and Codex-R4S) is told apart from this one's.
func codexTurnKey(r *http.Request, who string) string {
return who + "\x00" + access.Caller(r.Context()).KeyID
}
// rememberCodexTurn keeps the model a turn of Codex's own conversation
// was asked on, one magpie serves, for its memory calls.
func (s *Server) rememberCodexTurn(r *http.Request, who, agent, kind, asked string) {
if agent != "codex" || kind != "" {
return
}
s.codexTurns.Store(codexTurnKey(r, who), asked)
}
// isReviewCall: Codex's auto-review of an approval (the guardian), which
// it asks for on codex-auto-review, the reviewer model of OpenAI's, when
// its list has that or names it as a model's auto_review_model_override.
func isReviewCall(kind, asked string) bool {
return kind == "guardian" || asked == "codex-auto-review"
}
// freeOnChatGPT says whether a ChatGPT sign-in's call on model is free,
// counted in none of its usage windows: Codex's reviewer model,
// codex-auto-review, since OpenAI made Auto-review free for every ChatGPT
// sign-in on 2026-10-06 (#1593, hywang1230). A review run on another
// model, or through an API key, is counted as any call.
func freeOnChatGPT(model string) bool {
return strings.EqualFold(strings.TrimSpace(model), "codex-auto-review")
}
// codexMemoryStandIn is the model a Codex memory call goes to when magpie
// knows none by the name it came with (#742): Codex writes and
// consolidates its memories on models of its own (memories.extract_model
// and consolidation_model, gpt-5.6-luna and gpt-5.6-terra by default) by
// their bare names, whatever it is set to, so with magpie as its provider
// every one was turned away as an unknown model before it was routed. It
// goes to the model that Codex's own turns go to — the last one it had
// answered here, else the last in the ledger (a week back) from the same
// agent with the same key — so it is routed, and in the views, as the
// memory call it is. Its auto-review (isReviewCall) goes there too when
// Codex's config names no model magpie serves (StandIn): Codex reviews on
// the conversation's model when it has no reviewer, and a Codex whose
// config magpie doesn't read as its own — on magpie through another
// provider table or a profile, under a CODEX_HOME of its own, or on
// another computer — was answered 404 "magpie knows no model
// \"codex-auto-review\"" (Adam on Discord). "" for any other call, a model
// magpie serves, or a Codex that has had no turn answered here.
func (s *Server) codexMemoryStandIn(r *http.Request, who, agent, kind, asked string) string {
if agent != "codex" || !isMemoryKind(kind) && !isReviewCall(kind, asked) {
return ""
}
if _, _, ok := provider.Resolve(asked); ok {
return ""
}
key := codexTurnKey(r, who)
if m, ok := s.codexTurns.Load(key); ok {
if m, _ := m.(string); m != "" && m != asked {
if _, _, ok := provider.Resolve(m); ok {
return m
}
}
}
keyID := access.Caller(r.Context()).KeyID
var last usage.Record
usage.Visit(time.Now().Add(-7*24*time.Hour), func(rec usage.Record) {
if rec.Agent != who || rec.CallerKeyID != keyID || rec.Kind != "" || rec.Rejected || rec.IsReported() || rec.Failed() || rec.Requested == "" {
return
}
if rec.Time.After(last.Time) {
last = rec
}
})
m := last.Requested
if id, ok := provider.GroupFor(m); ok {
m = id
}
if m == "" || m == asked {
return ""
}
if _, _, ok := provider.Resolve(m); !ok {
return ""
}
return m
}