Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

masking: a record names the provider the request went to, not the group's first member (Max You and Linka on Discord)

yetone49f15d124471
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 18c997a47..d8b60c3fd 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -94,7 +94,7 @@ recorded as a prediction failure (`noPrediction`).
- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (`options` in [`internal/masking`](../../internal/masking/masking.go)), so a change applies to the next request.
- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`. Insights › Masking and Settings' *Try it* mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (`maskMatches` in `plugins/redact/page.js`; #3599, masking-records and mask-actions GUI tests).
- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.
- - Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent, session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`).
+ - Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent, session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (`noteMaskedUntil`, `maskrec.Hold`), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`).
- `DecidesModel` gives a 400.
- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model.
- A model the user disabled (#1867) gets a 403 for every caller (`idOff`), before anything is sent; see [Disabled models](#disabled-models).
diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go
index 17671a097..d5b85af3a 100644
--- a/internal/gateway/embeddings.go
+++ b/internal/gateway/embeddings.go
@@ -173,6 +173,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
}
tries = probeOne(tries) // of those resting, only the one back soonest (#1799)
var skipped []string
+ went := asked // the model the last try asked for
// unless every try is on this machine or the local network, set
// to go unmasked (provider.SkipsRedaction)
if slices.ContainsFunc(tries, func(c candidate) bool { return !c.p.SkipsRedaction() }) {
@@ -192,11 +193,14 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
if _, audio := req.(*audioForm); audio {
what = "audio"
}
- noteMasked(r, what, hits, sent, 0, tries[0].p.ID, asked)
+ // the record names the try that had it last, not the first
+ // planned (noteMaskedUntil)
+ _, noted := noteMaskedUntil(r, what, hits, sent, 0, tries[0].p.ID, asked)
+ defer func() { noted(call.Provider, went) }()
}
for i, c := range tries {
last := i == len(tries)-1
- call.Provider = c.p.ID
+ call.Provider, went = c.p.ID, c.model
base := strings.TrimRight(c.p.Base(provider.Chat), "/")
if base == "" {
msg := fmt.Sprintf("%s has no OpenAI-style API for %s", c.p.Name, path)
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 0f1e908ab..78c2e1c54 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -2380,11 +2380,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
watched.routeID = tr.ID
}
// what masking swapped, recorded for Settings → Privacy, unless the
- // request went as written
+ // request went as written. The record names the provider and model
+ // the last try went to, not the group's first member, which a
+ // failover may never have reached
if masked == nil {
- if m := noteMasked(r, "chat", maskedHits, string(body), tr.ID, p.ID, call.Model); m != nil {
+ m, done := noteMaskedUntil(r, "chat", maskedHits, string(body), tr.ID, p.ID, call.Model)
+ if m != nil {
s.trace.update(tr, func(t *Route) { t.Masked = m })
}
+ defer func() { done(call.Provider, model) }()
}
// the card's text is the masked body, even where the request went
// unmasked
diff --git a/internal/gateway/masked.go b/internal/gateway/masked.go
index 895f303b9..d8fa16739 100644
--- a/internal/gateway/masked.go
+++ b/internal/gateway/masked.go
@@ -46,8 +46,18 @@ func (h *maskHits) add(o maskHits) {
// route it is in the trace (0 for none), and the provider and model it
// went to. It returns its summary, nil when nothing was masked.
func noteMasked(r *http.Request, what string, h maskHits, sent string, route int64, prov, model string) *Masked {
+ m, done := noteMaskedUntil(r, what, h, sent, route, prov, model)
+ done("", "")
+ return m
+}
+
+// noteMaskedUntil is noteMasked for a request with more than one provider
+// to try: prov and model are the first planned, and done, called once the
+// request is over, names the provider and model that had it last, which
+// the record keeps (maskrec.Hold).
+func noteMaskedUntil(r *http.Request, what string, h maskHits, sent string, route int64, prov, model string) (*Masked, func(prov, model string)) {
if h.n == 0 && len(h.hits) == 0 {
- return nil
+ return nil, func(string, string) {}
}
rec := maskrec.Record{What: what, Route: route, Provider: prov, Model: model, N: h.n}
if r != nil {
@@ -57,7 +67,7 @@ func noteMasked(r *http.Request, what string, h maskHits, sent string, route int
rec.Snips = snipsOf(sent, h.hits)
rec.Took = h.took.Microseconds()
rec.Sent = sent
- rec = maskrec.Add(rec)
+ rec, done := maskrec.Hold(rec)
if h.key != nil {
*h.key = rec.Key
}
@@ -74,7 +84,7 @@ func noteMasked(r *http.Request, what string, h maskHits, sent string, route int
m.Kinds[v.Kind]++
m.By[v.By]++
}
- return m
+ return m, done
}
// noteBlocked records a request held back for a value the user set to
diff --git a/internal/gateway/masked_sent_test.go b/internal/gateway/masked_sent_test.go
index a92cba014..2100b6351 100644
--- a/internal/gateway/masked_sent_test.go
+++ b/internal/gateway/masked_sent_test.go
@@ -57,3 +57,47 @@ func TestMaskedRecordKeepsSentAndBack(t *testing.T) {
t.Fatalf("sent %q %v", sent, ok)
}
}
+
+// A masked request a group's first member fails is recorded on the member
+// that had it last, not on the first: Max You and Linka on Discord found
+// Privacy's records, and the flow on Insights › Masking, naming the
+// group's first provider, which no request had reached. A chat and an
+// embedding both.
+func TestMaskedRecordNamesTheProviderThatHadIt(t *testing.T) {
+ const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
+ const embedded = `{"object":"list","data":[{"object":"embedding","index":0,"embedding":[0.1,0.2]}],"model":"m","usage":{"prompt_tokens":3,"total_tokens":3}}`
+ for _, x := range []struct{ path, body, ok string }{
+ {"/v1/chat/completions", `{"model":"group/g","messages":[{"role":"user","content":"key ` + key + `"}]}`, chatOK},
+ {"/v1/embeddings", `{"model":"group/g","input":"key ` + key + `"}`, embedded},
+ } {
+ t.Run(x.path, func(t *testing.T) {
+ fresh(t)
+ a := &scripted{replies: []reply{{500, "", `{"error":{"message":"down"}}`}}}
+ b := &scripted{replies: []reply{{200, "", x.ok}}}
+ scriptedOn(t, "a", provider.Chat, a)
+ scriptedOn(t, "b", provider.Chat, b)
+ if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
+ t.Fatal(err)
+ }
+ if err := settings.Save(settings.Settings{Redact: true}); err != nil {
+ t.Fatal(err)
+ }
+ s := New()
+ rec := httptest.NewRecorder()
+ s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", x.path, strings.NewReader(x.body)))
+ if rec.Code != 200 || a.n != 1 || b.n != 1 {
+ t.Fatalf("%d %s (a %d, b %d)", rec.Code, rec.Body, a.n, b.n)
+ }
+ rs, _ := maskrec.List(0, 1, maskrec.Filter{})
+ if len(rs) != 1 || rs[0].N == 0 {
+ t.Fatalf("records %+v", rs)
+ }
+ if got := rs[0].Provider; got != "b" {
+ t.Fatalf("recorded on %q, the request went to b", got)
+ }
+ if r, _ := maskrec.Get(rs[0].Key); r.Provider != "b" || r.Model != "m" {
+ t.Fatalf("record %s/%s", r.Provider, r.Model)
+ }
+ })
+ }
+}
diff --git a/internal/gateway/video.go b/internal/gateway/video.go
index 17808b106..d8fc823d2 100644
--- a/internal/gateway/video.go
+++ b/internal/gateway/video.go
@@ -750,7 +750,9 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
if b, e := json.Marshal(f.Extra); e == nil && extra.n > 0 {
sent += " " + string(b)
}
- noteMasked(r, "video", hits, sent, 0, call.Provider, call.Model)
+ // the record names the member that had it last (noteMaskedUntil)
+ _, noted := noteMaskedUntil(r, "video", hits, sent, 0, cmp.Or(call.Provider, p.ID), call.Model)
+ defer func() { noted(call.Provider, model) }()
if n > 0 && f.Prompt == prompt { // the prompt's mask wraps w already
var done func()
w, done = restoring(w)
diff --git a/internal/maskrec/maskrec.go b/internal/maskrec/maskrec.go
index 5c6413ae6..b12339389 100644
--- a/internal/maskrec/maskrec.go
+++ b/internal/maskrec/maskrec.go
@@ -16,6 +16,7 @@ package maskrec
import (
"bufio"
"bytes"
+ "cmp"
"encoding/json"
"os"
"path/filepath"
@@ -120,8 +121,21 @@ var ownTest = false
// placeholder, counted. It returns r as recorded. Errors are swallowed:
// keeping the record must never break a request.
func Add(r Record) Record {
+ r, done := Hold(r)
+ done("", "")
+ return r
+}
+
+// Hold is Add for a request whose provider isn't known yet: a group's
+// member that fails passes it to the next, so the one it is planned for
+// may never get it (Max You and Linka on Discord: the records named the
+// group's first member, which no request had reached). r is in memory at
+// once, for its route's badge and the answer's Restored, and goes on disk,
+// where the summary counts it, once done is told the provider and model
+// that had it last ("" keeps r's). Only done's first call counts.
+func Hold(r Record) (Record, func(provider, model string)) {
if len(r.Values) == 0 && r.N == 0 {
- return r
+ return r, func(string, string) {}
}
r.Values = merged(r.Values)
if r.Time.IsZero() {
@@ -154,23 +168,36 @@ func Add(r Record) Record {
store.snips = append([]Record(nil), store.snips[len(store.snips)-keepSnips:]...)
}
r.Sent = ""
+ var once sync.Once
+ return r, func(provider, model string) { once.Do(func() { settle(r, provider, model) }) }
+}
+
+// settle gives r the provider and model that had it, in memory, and
+// writes it to its day.
+func settle(r Record, provider, model string) {
+ r.Provider, r.Model = cmp.Or(provider, r.Provider), cmp.Or(model, r.Model)
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ if i := at(r.Key); i >= 0 {
+ store.snips[i].Provider, store.snips[i].Model = r.Provider, r.Model
+ }
if inTest() {
- return r
+ return
}
disk := r
disk.Snips, disk.Back = nil, nil
b, err := json.Marshal(disk)
if err != nil {
- return r
+ return
}
dir := Dir()
if os.MkdirAll(dir, 0o700) != nil {
- return r
+ return
}
path := filepath.Join(dir, r.Time.Local().Format(dayForm)+".jsonl")
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
- return r
+ return
}
before, _ := f.Seek(0, 2)
_, err = f.Write(append(b, '\n'))
@@ -185,7 +212,6 @@ func Add(r Record) Record {
store.pruned = now
prune(dir, now)
}
- return r
}
// merged is vs with one Value for each placeholder, its N the sum, in the
@@ -374,6 +400,10 @@ func List(before int64, limit int, f Filter) ([]Record, bool) {
day = append(day, r)
}
})
+ // a record goes on disk once its request is done (Hold), so a
+ // long one comes after later ones: the list is in key order, as
+ // the next page's before needs
+ slices.SortStableFunc(day, func(a, b Record) int { return cmp.Compare(a.Key, b.Key) })
for j := len(day) - 1; j >= 0; j-- {
if len(out) == limit {
return out, true
diff --git a/internal/maskrec/maskrec_test.go b/internal/maskrec/maskrec_test.go
index d20482705..d3d6821db 100644
--- a/internal/maskrec/maskrec_test.go
+++ b/internal/maskrec/maskrec_test.go
@@ -152,3 +152,43 @@ func TestSumWarnedAndBlocked(t *testing.T) {
t.Fatalf("held back: %+v", got)
}
}
+
+// A held record goes on disk with the provider and model done names, and
+// the summary counts that provider, never the planned one. A long request
+// held before a short one is written after it, and the list is still in
+// key order, so the next page's before skips nothing.
+func TestHoldNamesWhoHadIt(t *testing.T) {
+ now := time.Date(2026, 10, 26, 12, 0, 0, 0, time.Local)
+ sandbox(t, now)
+ v := []Value{{Placeholder: "{{API_KEY_aaaabbbb}}", Kind: "API_KEY", By: "rule", Head: "sk-", Len: 40}}
+ long, done := Hold(Record{Time: now, What: "chat", Provider: "first", Model: "m1", N: 1, Values: v})
+ if got, ok := Get(long.Key); !ok || got.Provider != "first" {
+ t.Fatalf("held record not in memory: %+v %v", got, ok)
+ }
+ short := Add(Record{Time: now, What: "chat", Provider: "other", N: 1, Values: v})
+ done("second", "m2")
+ done("third", "m3") // only the first call counts
+ sum := Sum(1)
+ names := []string{}
+ for _, p := range sum.Providers {
+ names = append(names, p.Name)
+ }
+ if strings.Join(names, ",") != "other,second" && strings.Join(names, ",") != "second,other" {
+ t.Fatalf("summary counts %v", names)
+ }
+ store.mu.Lock()
+ store.snips = nil // after a restart: what disk has
+ store.mu.Unlock()
+ got, ok := Get(long.Key)
+ if !ok || got.Provider != "second" || got.Model != "m2" {
+ t.Fatalf("on disk: %+v %v", got, ok)
+ }
+ page, more := List(0, 1, Filter{})
+ if len(page) != 1 || page[0].Key != short.Key || !more {
+ t.Fatalf("first page %+v %v", page, more)
+ }
+ page, _ = List(page[0].Key, 1, Filter{})
+ if len(page) != 1 || page[0].Key != long.Key {
+ t.Fatalf("second page %+v", page)
+ }
+}