Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
redact: a backend's id (a UUID, 32+ hex digits) goes as written, never a piece of it
yetone0ddcf28a1d32
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 60f2bdc55..fd283da12 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -75,7 +75,7 @@ recorded as a prediction failure (`noPrediction`).## Runtime path1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression` and `http-client/src/request.rs`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.-2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).+2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, or 32 hex digits or more) goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of `…-a13800138000`, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (`api_key=`, `refresh_token`), never one named for an id, a cursor, a request or a digest (`secret_id`, `next_page_token`, `Idempotency-Key`, `secret_hash`), a bare `key`, a serial number, or what the model takes a UUID for (`noIDs`, [`internal/redact/ids.go`](../../internal/redact/ids.go)); and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `[email protected]`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`[email protected]`, `[email protected]`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). `[email protected]` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.- With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is OpenAI's Privacy Filter as a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU is started on the CPU for the rest of the run), joins short texts into 12 KB chunks and maps the spans back, keeps the last 20000 answers by hash, and ends it after 10 minutes with no request ([`internal/pii`](../../internal/pii)). A model that is on and can't answer (not on disk, didn't start, hung) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).- 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.diff --git a/internal/redact/ids.go b/internal/redact/ids.gonew file mode 100644index 000000000..511845224--- /dev/null+++ b/internal/redact/ids.go@@ -0,0 +1,156 @@+package redact++import (+ "slices"+ "strings"+)++// An id a backend made (a UUID, 32 hex digits or more: a row's, a+// request's, a session's, a commit's) goes as written. The vendor's model+// reads it, matches it and writes it back into a tool call, and a backend+// looks it up by every one of its characters: one masked, or a piece of one,+// is a lookup that finds nothing or the wrong row. A piece of one is never+// a value of its own: the phone rule found 13800138000 at the end of+// …-a13800138000, the bank card rule 4111-1111-1111-9007 across a UUID's+// groups, and the id went half a placeholder. A whole one is masked only+// as a credential, in a field named for one (password=, api_key:,+// "refresh_token":), never in one named for an id (secret_id, token_id),+// a cursor (next_page_token), a request (Idempotency-Key, csrf_token), a+// digest (secret_hash) or a bare "key"; never as a serial number (sn:),+// and never as what the model takes it for (a name, an account), but for+// hex digits without hyphens it calls a secret (an API key in prose). What+// the user chose (their words, their rules) stays theirs.++// noIDs is found without what is in an id of s, but for what the user+// chose and the credentials named for one.+func noIDs(s string, found []span) []span {+ return slices.DeleteFunc(found, func(f span) bool {+ if f.by == ByWord || f.by == ByYours {+ return false+ }+ l, r, ok := idAround(s, f.start, f.end)+ if !ok {+ return false+ }+ if f.start > l || f.end < r {+ return true // a piece of an id+ }+ switch f.by {+ case ByKnown:+ // masked before as what it is in full: a credential+ return false+ case ByModel:+ // a key the model found in prose: 32 hex digits it calls a+ // secret ("the api key is 9f8e…"); never a UUID+ return f.kind != "SECRET" || uuidRe.MatchString(s[l:r])+ case ByRule:+ switch f.kind {+ case "PASSWORD", "API_KEY", "TOKEN", "PRIVATE_KEY":+ return false+ case "SECRET":+ return !credentialField(s, l)+ }+ }+ return true+ })+}++// idAround is the id that s[a:b] is in, or is: the run of hex digits and+// hyphens around it, when that run is a UUID or 32 hex digits or more.+// ok is false where s[a:b] reaches past such a run.+func idAround(s string, a, b int) (l, r int, ok bool) {+ l, r = a, b+ for l > 0 && hexOrHyphen(s[l-1]) {+ l--+ }+ for r < len(s) && hexOrHyphen(s[r]) {+ r+++ }+ for l < r && s[l] == '-' {+ l+++ }+ for r > l && s[r-1] == '-' {+ r--+ }+ if a < l || b > r || strings.IndexFunc(s[l:r], func(c rune) bool { return c > 0x7f || !hexOrHyphen(byte(c)) }) >= 0 ||+ !idShaped(s[l:r]) {+ return 0, 0, false+ }+ return l, r, true+}++func hexOrHyphen(c byte) bool {+ return c == '-' || c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'+}++// idShaped says v, hex digits and hyphens, is a UUID or 32 hex digits or+// more without a hyphen.+func idShaped(v string) bool {+ return uuidRe.MatchString(v) || len(v) >= 32 && !strings.Contains(v, "-")+}++// credentialField says the field whose value starts at s[at] is named for+// a credential: refresh_token, DB_PASSWORD, x-api-key; not one named for+// an id, a cursor or a request, and not a bare "key".+func credentialField(s string, at int) bool {+ i := at+ for i > 0 && strings.IndexByte(" \t\"'\\", s[i-1]) >= 0 {+ i--+ }+ if i == 0 || s[i-1] != ':' && s[i-1] != '=' {+ return false+ }+ i--+ for i > 0 && strings.IndexByte(" \t\"'\\", s[i-1]) >= 0 {+ i--+ }+ j := i+ for j > 0 && strings.IndexByte(alnum+"_.-", s[j-1]) >= 0 {+ j--+ }+ words := nameWords(s[j:i])+ if len(words) < 2 && (len(words) == 0 || words[0] == "key") {+ return false+ }+ switch words[len(words)-1] {+ case "id", "ids", "uuid", "guid":+ return false+ }+ for _, w := range words {+ switch w {+ case "page", "next", "cursor", "continuation", "csrf", "xsrf", "trace", "request", "idempotency", "sync", "nonce",+ "hash", "digest", "checksum", "sha", "fingerprint", "etag":+ return false+ }+ }+ return true+}++// nameWords are a field's name's words in lower case: next_page_token,+// nextPageToken and X-Next-Page-Token are next, page, token.+func nameWords(name string) []string {+ var out []string+ w := []byte{}+ flush := func() {+ if len(w) > 0 {+ out = append(out, string(w))+ w = w[:0]+ }+ }+ for i := 0; i < len(name); i++ {+ c := name[i]+ switch {+ case c == '_' || c == '-' || c == '.':+ flush()+ case c >= 'A' && c <= 'Z':+ if i > 0 && name[i-1] >= 'a' && name[i-1] <= 'z' {+ flush()+ }+ w = append(w, c+'a'-'A')+ default:+ w = append(w, c)+ }+ }+ flush()+ return out+}diff --git a/internal/redact/ids_test.go b/internal/redact/ids_test.gonew file mode 100644index 000000000..818750d7c--- /dev/null+++ b/internal/redact/ids_test.go@@ -0,0 +1,94 @@+package redact++import (+ "strings"+ "testing"+)++// An id goes as written wherever it is and whatever is around it: a UUID,+// one whose last group holds a phone number's digits, one whose groups read+// as a card number, without hyphens, in capitals, a commit's hash. It is+// masked whole only in a field named for a credential.+func TestIDsGoAsWritten(t *testing.T) {+ forgetIDs := func() {+ mu.Lock()+ values = map[string]string{}+ reindexKnown()+ mu.Unlock()+ }+ ids := []string{+ "3f2b8c1e-9a4d-4e7b-b2c1-7d6e5f4a3b21",+ "3F2B8C1E-9A4D-4E7B-B2C1-7D6E5F4A3B21",+ "3f2b8c1e-9a4d-4e7b-b2c1-a13800138000", // PHONE in its last group+ "abcd4111-1111-1111-9007-abcdef123456", // BANK_CARD across its groups+ "3f2b8c1e9a4d4e7bb2c1a13800138000", // no hyphens+ "9f8e7d6cabcd4111111111111111900713800138000a", // a long hash with both+ "12345678-1234-1234-1234-123456789012",+ }+ kinds := map[string]bool{}+ for _, c := range Categories {+ kinds[c.ID] = true+ }+ o := Options{Secrets: true, Personal: true, Kinds: kinds}+ asWritten := []string{+ "%s", "id %s", `{"id":"%s"}`, "request_id: %s", "/users/%s/profile", "urn:uuid:%s", "{%s}",+ "next_page_token: %s", `"nextPageToken": "%s"`, `\"csrf_token\": \"%s\"`, `"token_id": "%s"`, "secret_id: %s",+ `"api_key_id": "%s"`, "access_key_id = %s", `"key": "%s"`, "Idempotency-Key: %s", "X-Request-Id: %s",+ "trace_token=%s", "secret_hash: %s", "sn: %s", "Serial Number: %s", "tel: %s",+ }+ for _, id := range ids {+ for _, c := range asWritten {+ forgetIDs()+ in := strings.ReplaceAll(c, "%s", id)+ if out, n := Mask(in, o); out != in || n != 0 {+ t.Errorf("%q went as %q", in, out)+ }+ }+ }+ credentials := []string{"password=%s", "api_key=%s", "X-Api-Key: %s", "token: %s", `"refresh_token": "%s"`, "session_token=%s", "postgres://app:%s@db:5432/x"}+ for _, id := range ids[:2] {+ for _, c := range credentials {+ forgetIDs()+ in := strings.ReplaceAll(c, "%s", id)+ if out, n := Mask(in, o); strings.Contains(out, id) || n != 1 {+ t.Errorf("a credential went out: %q as %q", in, out)+ }+ }+ }++ // the model takes an id for anything at all: it goes as written+ for label := range modelKinds {+ forgetIDs()+ id := ids[0]+ mo := o+ mo.Model = (&fakeModel{values: map[string]string{id: label}}).find+ body := `{"messages":[{"role":"user","content":"look at order ` + id + ` please"}]}`+ if got, n := MaskJSON([]byte(body), mo); string(got) != body || n != 0 {+ t.Errorf("the model's %s: %s", label, got)+ }+ }++ // a phone number masked before is not masked inside an id after+ forgetIDs()+ Mask("call 13800138000", o)+ if in := "order " + ids[2]; func() bool { out, _ := Mask(in, o); return out != in }() {+ t.Errorf("a known phone number was masked inside %q", ids[2])+ }++ // a phone number and a card number of their own are still masked+ for _, in := range []string{"call 13800138000", "card 4111-1111-1111-1111", "call a13800138000"} {+ forgetIDs()+ if out, n := Mask(in, o); n != 1 || out == in {+ t.Errorf("%q went as %q", in, out)+ }+ }++ // what the user chose stays theirs: their words, their rules+ forgetIDs()+ uo := o+ uo.Words = []string{ids[0]}+ if out, n := Mask("order "+ids[0], uo); strings.Contains(out, ids[0]) || n != 1 {+ t.Errorf("the user's word went out: %q", out)+ }+ forgetIDs()+}diff --git a/internal/redact/redact.go b/internal/redact/redact.goindex 49155b431..436b95bf7 100644--- a/internal/redact/redact.go+++ b/internal/redact/redact.go@@ -585,7 +585,7 @@ func mask(s string, o Options, put func(kind, v string) string) (string, int) {// kind it has always hadfound = append(found, modelSpans(s, o)...)found = append(found, knownSpans(s, o)...)- return apply(s, found, put, o)+ return apply(s, noIDs(s, found), put, o)}// by is the finder r is, for Hit.By.