From 4cc20f93c02790ef936dd5c0284b2060475bb3e5 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 17:52:37 +0800 Subject: [PATCH] routing: a group says whether its requests are masked (1dwsdqwd2 on X) Group.Redact: unset follows each member's provider (Send requests unmasked), "on" masks as Settings say whichever provider, "off" sends to every member as written. In a group in a group any "on" wins over "off"; Settings with masking off still masks nothing. Every route that reaches a group asks the same way: unredactedRoute (a provider's fallback groups and provider.GroupsAfter), unmaskedMembers, maskedFor and MaskRoute, and candidate.unmasked() for embeddings, images, video, decide and count_tokens. A shared group never carries it (export and import clear it; an import over a group keeps the old one). A save that doesn't name it keeps it; "follow" clears it. The Routing group editor gets a Masking row (menu, no select) in zh, zh-TW, ja, de, reusing core strings; the Privacy page's unmasked warning counts groups set to off. Run at the pushed head's parent (rebased on origin/main): gofmt -l, go vet provider/gateway/gui, go test provider gateway gui cli (gateway ok 1091s, gui ok, cli ok); provider red only in TestCancelledPluginSignInSavesNothing, open as #5047, green alone x10, not touched here. group_redact_test.go broken by hand (UnmaskedBy's on/off cases deleted): 5 tests red. group-redact.test.cjs: 5 languages x 2 widths x chromium and webkit, 30 of 30; i18n-keys green. Not tried: a real vendor request through a masked group. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/codex_backend.go | 6 +- internal/gateway/decide_group.go | 2 +- internal/gateway/embeddings.go | 2 +- internal/gateway/fallback.go | 8 + internal/gateway/fallback_group_test.go | 4 +- internal/gateway/gateway.go | 8 +- internal/gateway/group_redact_test.go | 157 ++++++++++++++++++ internal/gateway/redact.go | 71 ++++---- internal/gui/api.go | 5 +- internal/gui/assets/plugins/routing/client.js | 25 ++- internal/gui/assets/plugins/routing/i18n.js | 12 ++ .../gui/assets/plugins/routing/routing.css | 1 + internal/gui/tests/group-redact.test.cjs | 148 +++++++++++++++++ internal/provider/group.go | 93 ++++++++++- internal/provider/group_share.go | 3 + 16 files changed, 492 insertions(+), 54 deletions(-) create mode 100644 internal/gateway/group_redact_test.go create mode 100644 internal/gui/tests/group-redact.test.cjs diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 12950d968..ea69742d7 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -177,6 +177,7 @@ recorded as a prediction failure (`noPrediction`). 1. `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`). Codex's own path (`codexBackend`, the relay, its WebSocket, and `keyLimited` on it) reads to `codexBodyLimit` instead: a sixteenth of the machine's memory (`memLimit`, else `proc.MemTotal`), 512 MB at least and 2 GB at most, since Codex keeps every image it generated in the conversation as base64 and over HTTP resends it whole each turn; a session that generated and revised images went past 512 MB while Codex signed in to OpenAI went on (dallascao on Discord). One of Codex's own models is relayed at about 2 to 5 times the body in Go heap at its peak (1000 MB took ~12s and ~2 GB of heap past the body); a turn for a magpie model is translated at several times that and is still held to 512 MB once its model is read, its 413 saying Codex's own models take more (`TestCodexGeneratedImagesPastOldLimit`). 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. A JSON body's text that isn't text, bytes that aren't UTF-8 (a GBK file, a surrogate written as UTF-8) and a lone surrogate's escape (`"\ud800"`), becomes U+FFFD there, one per bad byte, as Go's decoder reads it (`textBody` in [`body_text.go`](../../internal/gateway/body_text.go)); a surrogate pair's escapes, an escaped backslash and a multipart or audio body are left as they came. magpie sent such bytes on as they were, and DeepSeek and OpenAI answered 400 while MiniMax answered 200 with nothing, so a group's request worked or failed by its member (laincatx on X). A turn isn't refused for them: a tool result holds a file's bytes, and every later turn of the session resends it (`TestBadTextReachesVendorsAsReplacement`, `TestBadTextOnSocketAndGemini`). `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`. 2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, 32 hex digits or more, or a digest of 16 to 31 hex digits in one case with letters and digits both, a cache key or a short commit, which went as a key before: _kaichen on X, 10-28; `digestShaped`), or an element token cua-driver hands the model for computer use (`s0000002a:14`, #3782), 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`), nor cua-driver's own `element_token` (any other name with `element` in it, `element_api_key`, is a credential's as before), a bare `key` (not after api, access, secret, private, signing or license: `keyPhrase`), a field named for a cache, commit, object, blob, file, content, revision, partition, shard, bucket, dedup, lookup, row or sort key, a serial number, or what the model takes a UUID or an element token for, nor an element token known from before (one the model labelled in prose a turn earlier) (`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`; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then on the same route (the providers the request can reach: its model's, its fallbacks', or a group's members'; `maskedFor`, `masking.WithRoute`, `redact.Options.Route`), so neither a value a rule first finds later in a conversation nor a name the local model reads in a tool's output only after its first send (the default model's 2s wait, `pii.Partial`; vvrfxyz on X, dsh's cache hits) changes the prompt the vendor has cached and rewrites all of it to the cache; such a late find is masked in new text (`learnLate`), and another route, never sent the text, gets it masked with what is known and found now, `sentSpans`, `TestModelReadingLateKeepsTheSentPrefix`, `TestMaskedPrefixKeptOnlyOnItsRoute`), 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, before the writer outside it that names the member, `memberWriter`, writes what it holds: the other way round a whole reply with a value masked in its request went out a 200 with an empty body, #4129, `TestMaskedWholeReplyNamesMember`): 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)). Every reply is read so, a request that masked nothing too: a vendor holding the conversation (Codex's compacted history, a server-side session) answers with placeholders sent turns before, and those came back as written (yapechan123 on Discord, a table of `{{PERSON_…}}、{{PERSON_…}}`; `TestReplyToAnUnmaskedTurnIsRestored`). Every string of an event is read, a tool call's `name`, `type` or `data` inside its arguments too, but for signatures, `data:` URLs and opaque blobs (`sealedText`); a held tail is kept per string, so a Responses event's random `obfuscation` never takes the hold from its `delta`; a whole body with a placeholder in no braces or one is restored as with two (`heldIn`); an audio, image or other binary reply goes through as it comes (`binaryType`). Past 200,000 values the half used longest ago is let go (`makeRoom`, `touch`; before, a random half, so a value just masked could be gone when its reply came). Values are held in memory only, so a placeholder from before a restart that only the vendor still holds comes back as written. A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, and has an address: the user's switch for each provider whatever its address, AcMilan on Discord, `http://llm.corp.lan:8000`; nothing is looked up to decide, `TestSkipsRedaction`, `TestLANNameUnredactedProvider`. A signed-in subscription and a plugin's provider take it too, kept with the account's model picks (`withPicks`; isee1_1 on Discord: a translation plugin as a provider); and so does another magpie (CrazyMouse_TT on X, his own model behind it): it is sent the request as written with no `X-Magpie-Masked-As` (`withMaskedAs` is never called), so it masks by its own Settings › Privacy and its own providers' switches (`TestUnredactedRemoteMagpieMasksOnItsOwnSide`); left off, it is sent the request masked here, as before. The editor shows it for every provider, another magpie with no caution, and, while it is on, a caution under it naming an address not on this computer or the local network, or, for a subscription or a plugin's provider, its name (`unmaskRow`, `awayHost` in app.js; a name of the user's own DNS is asked about, only while it is on, through `POST /api/local-hosts`, `provider.LocalHost`, which takes a name every address of which, looked up in 400ms and kept a minute, is loopback, private or link-local, `netproxy.LocalName`; no request asks it)) goes to them as the agent wrote it and isn't masked on its way, since a request is masked only once its route is known (#3973: masking a body whose masked copy was thrown away took up to minutes of magpie's own time). The log, recent calls and the request archive keep it as it went (the archive's bodies have their secrets taken out, `redact.ScrubJSON`, as every call's do), whether the archive is on or off; an observer that wants the bodies (the OTLP export, a JS plugin's) is handed it masked, masked once when it is first handed it after a try (`Call.maskIn`, `laterMasked`), never before the request is sent. A request turned away before it is routed is logged masked (`maskedCopy`). count_tokens, embeddings, speech, transcription, pictures and videos (`unmaskedMembers` over the models the picture or video may be made on: a group with one member left on is masked) and Ark's own API (`nativeArk`, as `nativeAny`) follow the same rule (`TestUnredactedProviderDrawsWhole`, `TestUnredactedProviderMakesVideosWhole`, `TestUnredactedProviderArkNativeWhole`); Settings › Privacy lists the providers set so, each opening its editor (*Sent unmasked*, `unmaskedRow` in plugins/redact/settings.js, `unmaskedProviders` in `/api/settings`). System One follows it too: a `/v1/systemone` request, and a `/v1/decisions` one translated to it, is masked once before its tries (`serveDecideTries`, `TestSystemOneMasked`). A request masking would change can go to such a model instead (jessyoungyu on X: 「{{百度}}这家公司怎么样」 can't be answered from a placeholder): with Settings › Privacy's *Instead of masking, send to* set (`RedactRouteTo`, `POST /api/settings/redact-route`, which takes only a model `MaskRoute` passes: `unredactedRoute` for its provider and fallbacks, or its group), an agent's turn that masking would change (`maskHits.n` > 0: a warn-only hit doesn't count, and a held-back one stays held back) goes as written to that model, the model asked for left alone, in `serve` after the request is masked (`maskRouteFor` in [`redact.go`](../../internal/gateway/redact.go); the masked copy is thrown away, so streaming and every API go as for any route). If it fails, the request fails: its fallbacks are all unmasked ones by `unredactedRoute`, and nothing is masked and sent to the model asked for. It is judged again on each request, so a route that has since got a vendor's address, a fallback elsewhere, was turned off, or isn't one of a gateway key's models is ignored and the request is masked as before. Only an agent's own turn is moved (`agentTurn`, set in `serveAgent` and cleared by `ownAsk`): a title, a search stand-in, a picture described, System One and Jev stay masked. count_tokens is counted on the route (`countTokens`), and a turn of Codex's own model on its ChatGPT sign-in goes there too (`codexMaskRoute` in `codexBackend`; masked once to decide, only while it is set). Such a turn, and ChatGPT's web search for it (`alphaSearchOn`), goes as written when the Codex subscription it is on is set to go unmasked (`codexRouteUnmasked`; `TestCodexSignInUnmaskedSwitch`); a plugin's provider is asked through `serve` (`TestPluginProviderUnmaskedSwitch`). Speech and video requests are never moved to that model: they are masked unless their own route is set to go unmasked (`maskTextHits`). Unset, as by default, nothing changes. Tests: `TestMaskedRequestGoesToTheModelSet`, `TestCodexSigninTurnGoesToTheModelSet`, `TestMaskRouteOnlyForTheAgentsTurn`, `TestMaskRouteTakesOnlyUnmaskedRoutes` ([`mask_route_test.go`](../../internal/gateway/mask_route_test.go)) and `TestRedactRouteSetting` in internal/gui. 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`). A request masking swapped a value in (`maskHits.n`) is told, on each try, that the placeholders are used as written and filled in before anything runs (`placeholderNote`, [`placeholder_note.go`](../../internal/gateway/placeholder_note.go); treeMan on Discord: weaker models refused to search with one, asked to verify it, or rewrote it as an example). The note names neither magpie nor a vendor or client. It goes where placeholders first appear, after what is there, so it is new text the first time and the same on every later turn: in the instructions when they or the tools hold one (the last block of Anthropic's `system`, the end of Chat's first system or developer message, a part after Gemini's `systemInstruction`'s), else on the earliest message that holds one (a text block or part after its content; on Responses a developer message after that item and the tool outputs that follow it). Responses `instructions` (Codex's base_instructions) is never touched. A conversation's values are masked again each turn and a value found later is masked only in new text, so the note never lands in text the vendor has cached (`TestMaskedConversationKeepsItsCachedPrefix` goes red with the note in the system prompt). It is not added for a Claude subscription (the bridge puts the caller's instructions in the run's first message, which Anthropic classifies), for a ChatGPT account (Codex's own turns, `codexUpstreamOn`, never pass here either), or for a Responses turn with `previous_response_id`, where it would pile up in the stored conversation (`notesPlaceholders`; `TestPlaceholderNotePlaces`, `TestPlaceholderNoteNotOnClientPaths`, `TestMaskedRequestTold`, `TestPlaceholderNoteIsNeutral`). count_tokens counts without it. Inside a tool call's arguments (Anthropic's `tool_use` input, Gemini's `functionCall` args) and Gemini's `functionResponse` response, whose keys are the tool's, a field named for a secret (`SecretName`: `api_key`, `db_pass`, `Authorization`, not `sort_key` or `public_key`) has a value of 8 characters or more masked by its name whatever its shape, with secret masking on (#2946, `namedSecret`); a key anywhere else is the protocol's, `mcp_servers[].authorization_token` included, and never masks by its name (`TestMaskJSONSecretNamesOnlyInToolArgs`). + - A routing group says how its requests are masked (`Group.Redact`, set in the group's editor under Masking; `provider.RedactOn`, `RedactOff`, unset follows providers). `off` sends to every member as written whatever its provider says, `on` masks to a member whose provider is set to go unmasked, and in a group in a group any `on` wins over `off` (`walk` passes it down in `Member.Redact`; `Member.Unmasked`, `provider.UnmaskedBy`). Every route that reaches the group asks the same way: `unredactedRoute(p, model, isGroup, ms)` (a provider's fallback groups and `provider.GroupsAfter`), `unmaskedMembers`, `maskedFor`/`MaskRoute`, `candidate.unmasked()` (embeddings, images, video, decide, count_tokens). Global masking off still masks nothing; a shared group never carries it (export and import clear it, an import over a group keeps the old one). A save that doesn't name it keeps it, `follow` clears it. Guarded by `TestGroupRedact*` in `group_redact_test.go`. - 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 (a date over a year ago: one in the last year or ahead is the day an agent runs on, `dateOK`); the word must be right before the date, so a log line's or a file name's date is none, and a time beside the date doesn't make it a log's: a date of birth stored as a time (`1990-05-11T16:00:00.000Z`) is one (`TestBirthdayLogDates`; #3878), MAC addresses, and serial numbers next to S/N or the like. Eleven digits from 13 to 19 are a mainland mobile's form and an id's too, so they are a phone only with +86 or 86 before them, as the value of a field whose name says phone (phone, mobile, tel, cell, contact, 手机, 电话, a field named `number`), or in prose with no id's word right before them (order, id, no., #, 订单号, 编号, 单号, 流水号); under order_id or uid, after 订单号, or with a letter or digit against them they go as written (`phoneAt` in [`internal/redact/phone.go`](../../internal/redact/phone.go); _kaichen on X, 10-28). 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. When the user name is on, it goes as a made-up name of 8 lowercase letters, the same for that name every turn and put back in replies like any placeholder (`standIn` in [`shape.go`](../../internal/redact/shape.go)), not as `{{USERNAME_…}}`: with mimo-v2.6-flash a model read `C:\Users\{{…}}` as a temporary folder and set out to delete it (eerttreeeert on X, 10-28). A user name found once is masked again as known (8 bytes or more) only where it stands as the user's name: a path's part, `name@host`, a git author, `ls -l`'s owner, `uid=501(name)`, prose, a quoted string; not where code has the same word as a name of its own, joined to another part (`developer_dir`, `self.developer`, `developer.go`), declared, assigned, called, a parameter or a JSON key (`nameAlone`). A `User:` line's unquoted value made of words one of which says it holds a user (`current_user`, `UserInfo`, `loginName`) is a variable's or a type's name, not a login (`notLineIdent`); a quoted one is masked (`TestUserNameInCodeIsNoUserName`, `TestUserLineInCodeIsNoUserName`; Tomyu_2034 on X). A public IPv4 or IPv6 address goes the same way as a name that says what it is, `public-ip-` and eight lowercase letters (`public-ip-kvxqmrtz`), the same one for that address while magpie runs and never another address's, put back only where it stands as a whole name, in a streamed tool call's arguments too (`ipStandIn`, `restoreAddr`; `TestIPGoesAsAPublicIPName`). Told `{{IP_…}}`, models asked the user for the real address or searched `~/.ssh` for it instead of running ssh (0x0_air on X, 10-28). Told an address from the documentation ranges (192.0.2.0/24 and the like, used from 10-28 to 10-31), they ran ssh but told the user, when asked why it failed, that it was an example address and not their server's, and a 192.0.2. one read as a LAN address (akic404 on Discord, 10-31). A name with no dot reaches nobody if the vendor tries it itself. An EVM address (`0x` and 40 hex digits) is public, so the local model's finds leave it as written unless a key's name is right before it; a 64-digit private key is still masked (`evmRe` in `modelFits`; `TestEVMAddressGoesAsWritten`). A number written in hex, `0x` and 1 to 16 hex digits (an address in reverse-engineering notes, a constant, a flag), is no value of any kind the local model finds, whatever is before it, since the function at an address is often named for a key; a longer one (a key in hex) is masked still (`hexLiteral` in `modelTakes`; `TestHexNumberGoesAsWritten`, TakaNaShi_ShiKi on X). Decimal digits alone that the local model calls a secret are a count, a time or an id unless the name right before them ends in a key's, a token's, a password's or a PIN's word (`api_key=`, `PIN:`, `密码是`): Claude Code's `14998720 tokens left`, `"total_tokens": …` and `max_tokens: …` go as written (`numberNamedSecret` in `modelFits`; `TestTokenCountIsNoSecret`, steven_4422 on Discord). 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`, `strings@base.json`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`icon@2x.zip`, `intro@1.5x.mov`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). A domain needs a dot and labels a host can have, so a disassembly's symbols go as written for both too: `system@plt`, `puts@got.plt`, `memcpy@GLIBC_2.14`, `foo@@GLIBC_2.2.5`, and `system@got` (`.got` is a top-level domain; `mailHost` in `realEmail`, `TestSymbolIsNoEmail`; ch35tnut_ on X, 10-28). `ops@files.zip` 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 (`masking.ModelWanted`: on by default since 10-28, `settings.RedactModel` the user turning it on and `RedactModelOff` off, this computer's own, kept by `KeepOwn`; a user with a model downloaded or picked and neither flag turned it off before the default, and `RedactModelAuto` marks the default's own download), 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`), but for what the agent defines (its tools' and schemas' descriptions, under `defKeys`), which the rules alone mask, as with the model off, after the rest of the request so a value the model found in a message is masked there too as known: those were 52,577 of Claude Code 2.1.296's 67,532 bytes the model read, and a 4-core server's first request waited out the gateway's 2 minutes (niuniu_8964 on X; 11.5s cold at 4 procs on a Ryzen AI Max+, 2.6s without them, and on three real Claude Code requests the model masked nothing there the rules didn't); 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 one word as a name where what is around it says a thing and nothing says a person: an app's name in a list of names alone, in a list of apps, or beside a thing's word (using, switched to, the … app, vs, 这个软件), so Privacy Filter's Cicada and Mimi in a chat about choosing apps go as written, while a full name, a Chinese name and a first name beside a relation, a greeting, said or he/she are masked as before, and a text of one first name alone goes as written by design (`thingNamed` in [`thingname.go`](../../internal/redact/thingname.go); ylorn. on Discord, whose follow-up questions had the names as written while the history had them as placeholders, so the vendor answered about another app), 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). A package's name goes as written, for the model and the rules alike (dniray on Discord, v0.1.1917): the module a line of code loads (`from ' drizzle-orm '`, `require('jsonwebtoken')`, `from x import`, `use x::`, with an editor's line number or a diff's mark before it; `moduleAt`, `codeHead`), a manifest's dependency pinned at a version (`"drizzle-orm": "^0.36.4"`, TOML's `x = "9"`; `dependencyAt`), a folder under node_modules or site-packages, the module an error could not find (`Cannot find module 'x'`, `No module named 'x'`; `missingModuleAt`), a package an install names (`pnpm add x`; `installedAt`) or pins with @ (`x@0.36.4`; `pinnedAt`), all in `packageAt`; a value known from an earlier mask (`knownSpans`) goes as written there too, since once the model took the name for a secret anywhere in a request it was masked on the import line as known (dniray, v0.1.1965), a requirement's name before its pinned version (`django-rest-passwordreset==1.4.0`; `pinnedAfter`), a lock file's integrity hash (`sha512-…`; `sriRe` in `namesThing`), a version as the value of a field named for a secret (`"js-tokens": "^4.0.0-beta.1"`; `versionValue` in `fieldAt` and `keyAt`), and a package pinned at its version as user@host has it (`js-tokens@4.0.0:` in pnpm-lock.yaml; `notPackagePin`); `TestPackageNamesGoAsWritten` and `TestModelPackageNamesNotMasked` hold them. A field named for a secret and set to nothing takes nothing from the field after it: the SECRET rules let a space stand after `=` or `:` (`password = hunter2` in a config), and `env -i UI_PASSWORD= UI_ADDR=127.0.0.1:39117 ./syncer` went with `UI_ADDR=127.0.0.1` as UI_PASSWORD's value (mx_albert on Discord); a value that is an assignment of its own after a space (`UI_ADDR=`, `addr=`, `--listen=`) is the next field, read with its own name, so a token there still masks (`fieldMatches`, `nextField` in `internal/redact/fieldvalue.go`; `TestEmptyFieldTakesNotTheNext`, `TestSecretBesideEmptyFieldMasks`). 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 Privacy Filter 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; 和 or 与 says so only after a person, 吴敏和郑浩 but not 判断和边界, 发 or 打 only as the verb, 发了个 but not 关键发现, and a sentence starts after punctuation, not after a space after code, `gh pr view` 易触发; xuanwo on X; 一下 only after a verb that asks a person, 问一下张伟 but not 改一下文案, a word any subject takes after it, 已经, 明天 or 他, only with a person's cue before it, and 说明 is no 说; zeewell on X), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left, and so is a common word that starts with one (`zhWords`: 文案, 文档, 方案; 毛利, 毛重, 毛巾, since 毛利 is a margin far more often than the Japanese surname, so 毛利低 goes as written: _kaichen on X, 10-28; the model still finds 毛利兰, and neither model nor rule masks 毛利小五郎), the model's own name too when it is that word whole. A name the model or the cues take is also no name when it is an ordinary word (`zhWordShaped`, `zhWordNotName`, the one check both go through): a colour (黄绿色, 红色, any that ends in 色 or is colour characters alone: hh05928822 on X after v0.1.1850), a word that starts with a surname from `zhWords` or `zhDict` (about 1,550 two-character words from jieba's dictionary, [`zhdict.txt`](../../internal/redact/zhdict.txt), its header saying how they were chosen; 边界, 应该, 尚可), or such a word with what makes a longer word after it (关键词, 关键字: wangjunxiao128 on X; 应用层, 毛利率), unless a role before it or a title after it says a person is meant (客户方圆, 江山老师), where a name that is also a word is masked. The surnames stay (黄 starts 黄绿色 and 黄晓明), and 毛利兰, 关羽 and 黄晓明 are still masked. With AstrLink Guard only a nickname is (小王, 老李, `zhNick`; `redact.Options.NamesByModel`): Guard at 0.8 finds the full names those cues did in zhname_test's sentences (张伟, 陈建国, 欧阳娜娜…), and misses the nicknames, 孙经理, and all but the surname of 王老板 and 邓总; the cues took words for names (关键发现; xuanwo on X). The model is the user's pick (`settings.RedactModelName`, `pii.Choose`; the app's menu beside the switch, `pmPick`): AstrLink Guard (QuantumNous/astrlink-guard at a pinned revision, Apache-2.0, a 39 MB int8 Multilingual-MiniLM token classifier for Chinese and English), run in magpie's own process on the CPU by [`internal/pii/guard`](../../internal/pii/guard) (an ONNX reader, the XLM-R tokenizer and int8 kernels in Go, NEON/SDOT on arm64 and SSE2 on amd64; its labels named as Privacy Filter's, `guardLabels`); a text over one window, 510 tokens, is read in windows that overlap by 128, and on the CPU as many windows at once as it has cores, half of `GOMAXPROCS` and 4 at most (`guard.Cores`: on every core a long history unread kept a 32-core Linux box at 13 cores' worth for as long as requests came, xinvxueyuan and shensmart on Discord, 10-28): one window's matmuls split over the cores left them idle between, and a 4-core server's first Claude Code request waited minutes (niuniu_8964 on X; 22,488 tokens took 23.9s at 4 procs, 17.9s at once, and 48.8s against 30.5s at 2), and on a Mac through CoreML on the Neural Engine or the GPU ([`coreml.go`](../../internal/pii/guard/coreml.go), [`internal/pii/guard/coreml`](../../internal/pii/guard/coreml); yyhhyyyyyy on X; Settings › Privacy names which, from CoreML's own compute plan of the compiled model, `MLComputePlan` on macOS 14.4 and later, the device most of its program's estimated cost is on (`coreml.Plan`, `Model.Backend`, `Status.Via` and `Device`): it said "on the CPU" under CoreML, yyhhyyyyyy on Discord, 10-27; an M5 Pro's plan puts all of it on the GPU; after a CoreML read fails it says the CPU and why until one doesn't): the same network from the same int8 weights in float16, written from the downloaded model into a program made by `coreml_gen.py` and compiled once into the model's folder, 512 tokens in about 12 ms where the CPU takes 400, its probabilities within .07 of the publisher's fp32 model where the CPU's are within .13 (the CPU quantizes activations as the int8 model does, CoreML doesn't), so a span near the threshold can fall the other side (a go.mod module path is a secret at .81 on CoreML, .79 on the CPU, .785 in fp32); a window under 16 tokens (`coremlMin`), a Mac before macOS 13 or any failure goes to the CPU, loaded on the first request and let go after 10 minutes with none; or OpenAI's Privacy Filter. With no pick it is AstrLink Guard, the default; a user who had Privacy Filter on before there was a choice keeps it only while AstrLink Guard downloads, which the first masked request starts and which then saves AstrLink Guard as the pick (`masking.picked`, `toGuard`; an hour between tries after a failure). Measured for that default (#3578): on 234 segments of real code and config it found 2 spans where Privacy Filter found 100 (38 of them go.sum hashes after redact's own checks), and with the rules it found 42 of 42 test values to Privacy Filter's 41. Each model has its own download, cache file and turn (`backend`). AstrLink Guard's turn has `guard.Cores()` places (`guardTurn`), so that many requests read at once, and they share those cores: every window, of any request, takes one of `guard.Cores()` tokens before it reads and more only while they are free (`guard.take`), so requests together never read on more cores than one did (the 4 promised xinvxueyuan and shensmart above); the model loads once (`guardLoading`), the idle timer lets go only when no place is held (`guardIdle`), and a text one request is reading another waits for rather than reading it too (`backend.reading`). Before, one request read at a time, and an agent's parallel requests queued behind it (yyhhyyyyyy on Discord, 10-28, who asked for 16 at once). Measured at 1, 2, 4 and 8 requests at once (a Ryzen AI Max+ 395 under WSL, 4 cores): 512-byte requests 4.2, 6.1, 8.1 and 8.4 a second where one at a time was 4.2 whatever came, on 1.9 to 3.9 cores, memory flat at about 150 MB; 4 KB requests already read their 3 windows on 3.6 cores alone, so they stay at 0.6 a second (Windows on the same box: 7.5 to 12.1 a second at 1 to 8, 4 KB 0.7 to 0.8, on at most 3.8 cores). Each request on cores of its own would read 20 a second at 8, on 12 cores, and 4 KB at 8 took 20 cores and 521 MB (953 MB on an M5 Pro), so the bound is the cores, not the count, and there is no setting for it. Through CoreML the GPU is the bound: on an M5 Pro 4 KB requests read 23, 20, 25 and 25 a second at 1, 2, 4 and 8, a model per request no faster, so CoreML reads one window at a time, and only the windows under `coremlMin` or after a failure use the CPU's tokens. Both find at a floor of 0.5 (`pii.Floor`) and give each span its score (AstrLink Guard: the least of its tokens' probabilities, rounded to a float32 so a cached span reads back the same; Privacy Filter: pf-serve's own), and masking keeps those at the model's threshold or over (`pii.Threshold` in `masking.model`): the user's for that model (`settings.RedactModelScore`, this computer's own; Settings → Privacy's Confidence threshold, `pmScore`, 0.5 to 0.95), else the model's own (`MinScore`: Privacy Filter 0.5, AstrLink Guard 0.8, its publisher's). A value known from before follows the same threshold: each value masked remembers the highest score anything found it with (a rule's counts as sure), and one only the model found, under the threshold now, is no longer masked again as known (`noteScores`, `knownSpans` in [`known.go`](../../internal/redact/known.go); before, a raised slider changed nothing for a value masked once: _kaichen on X, 10-28). The defaults stay because on the eval a higher one mostly loses values the checks after the model would have kept (Privacy Filter at 0.85 lost a Chinese name; AstrLink Guard at 0.9 a phone in a tool result), while the false alarms it would drop are mostly dropped by those checks already (Yayoi_no_yume on X). Measured again on 2000 segments of real agent traffic (Codex and Claude Code sessions: prompts, tool arguments and results, a quarter with Chinese) and 30 more labelled cases: AstrLink Guard at 0.88 rather than 0.8 drops 3 false alarms (a model id, a sandbox path word, a token counter) and lets a colleague's name and a signed name through; Privacy Filter at 0.88 rather than 0.5 drops 11 (timestamps in paths, log lines, a plugin id) and lets 6 real names and a phone through (4 of the names in the real traffic). Lowering Guard to 0.5 finds 2 more names in the real traffic and 3 more labelled values, for 10 more false alarms (9 of them Claude Code's `` counter). Those false alarms are shapes a check can turn away; a threshold can't without losing real values. Privacy Filter is 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; on a GPU it holds the model once, in the device's memory, #3590; every pf-serve keeps the engine's own MoE chunk, `PF_MOE_CHUNK` at the window's 4096, which an RX 470 through Vulkan read 6-9% faster than 2048 in interleaved runs and Metal ~6% faster, and inherits a value the user set): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, through magpie's proxy (`netproxy.Func`, as its other requests; hh0592821 on Discord, whose download went direct before), from hf-mirror first in China (`source.chinaFirst`) and from hf-mirror after Hugging Face everywhere else, the switch off too (`source.modelMirror`), so a poisoned or blocked huggingface.co doesn't stop it; hf-mirror serves AstrLink Guard's files itself and sends Privacy Filter's back to Hugging Face) 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, in the model's folder and given the model's file name, never its path (a Windows C program's argv is in the ANSI code page and ggml reads it as UTF-8, so a user folder named in Chinese failed every load with the path in mojibake, AIMetaPhD on X; a pf-serve error that names the file is shown with the whole path) (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (`pieces`: after a line's end, else a space, of those in the piece's second half the one whose 48 bytes before it hash least (`landmark`), so a line edited early in a text leaves the pieces after it as they were, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (`merge`: one found twice is one, one cut by a piece's end is whole), and a value of 8 bytes or more found in a text is found wherever else it is in it, as sure as its surest find (`spread`: the model scored an address on 400 lines alike 0.9 on some and 0.5 on most, wangwu25685333 on X), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (`found-.bin` beside the model: hashes, offsets, labels and each span's score, never text; a `pfound01` file from before scores is read with every span sure, so it masks as it did; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, by the request waiting with the least left to read (`takeTurn`, `queue`), so a short request goes before the rest of every long one (wangwu25685333 on X: a 5 KB request behind two long ones on 4 cores waited 8.3s in the order they came, 4.5s now). The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). Until the model is on disk the rules mask alone, and its download starts (`masking.fetch`, an hour between tries; the default's, done, saved by `settings.UseDefaultRedactModel` unless the user picked or turned it off meanwhile; cancelling it is turning it off). A model the user turned on that fails (didn't start, isn't on disk, held back after a failure) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`, strict); the default's finds nothing then, and the rules mask alone. A model that is only slow is waited for at most 2 seconds from the request's masking start when on by default (`masking.defaultWait`) and 15 seconds when the user turned it on (`masking.strictWait`): its turn, its load and its reading. Past that, or when the request's context ends first, `pii.FindContext` answers with what was known of the request's texts by then (its cache: the history read on earlier turns, and the chunks read meanwhile) and a `*pii.Partial` saying how many it hadn't read; `masking.model` masks those with the model's finds and the rest with the rules alone, logging it at most once a minute (`notePartial`), and the request goes. Nothing the rules mask goes as written. Before, the user's model was waited for with no bound and any end of the wait held the request back whole, its known finds thrown away: in a burst of requests with text the model hadn't read, xRayySummers on X (0.1.1877, Linux) saw masking take 1.2s to 290s in one minute and each request it ended was "masking failed, so nothing was sent". Reproduced on 8 cores of a Linux CPU: AstrLink Guard reads about 6 KB a second there (a 125 KB history 20.8s), and six requests at once with 67 to 145 KB of new tool results each took 62 to 110s, all ending near the last, since the turn goes round between chunks; with the bound each went at 15.0s with the history's finds and the model's for 1 to 4 of its 9 texts. `masking.find` gives a model that doesn't stop for its context 100ms to answer with what it knew (`handBack`) before giving up on it. AstrLink Guard reads on the CPU, so a long Codex history it hasn't seen took minutes there, and every request queued behind it showed masking with no bound (shensmart on Discord, 10-28, magpie in Docker). The wait is given up even where `Find` doesn't stop for its context. A request that stops waiting leaves the chunks after the one being read (`backend.find`), so it doesn't hold the turn; that chunk's answers are kept for the next request. Each model reads a request's unread texts newest first, the last text and a long one's last piece before the rest (`backend.missing`), since an agent's history is oldest first and what a request adds is at its end; AstrLink Guard joins them into chunks of 4 KB, not Privacy Filter's 12 KB (`backend.chunk`, `guardChunk`), so the chunk a request leaves the model finishing past its wait is about a second on 4 cores. The default's request is `pii.Bounded`: what one went without the model's reading is remembered by hash (`backend.sent`), and a request after it reads what it adds first and that backlog `backlogCap` (4 KB) at most, nothing found for the rest, so a history resumed or never read is read a little a request rather than on every core for each one. Measured on a 2 MB, 200-turn Codex history never read, 30 requests 3s apart (`TestLiveHistoryCost`, gated on `MAGPIE_GUARD_FILES`): on a 32-core Linux box 33 to 60 CPU seconds a request before, 23 minutes of CPU over the session's 108s (13 cores busy), 6 to 10 after, 4 minutes over 90s (2.7 cores), and on an M5 Pro's CoreML 2.2 CPU seconds a request for the first three before, the first alone after; nothing runs on after the last request either way. A request the user turned the model on for still reads all of it, waited for `strictWait`. - 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/gateway/codex_backend.go b/internal/gateway/codex_backend.go index eed328a76..cda5d63c6 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1026,7 +1026,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st if on != nil { to = *on } - w, body, unmask, maskedHits, err = redactedHits(maskedFor(r.Context(), to, false, nil), w, body) + w, body, unmask, maskedHits, err = redactedHits(maskedFor(r.Context(), to, "", false, nil), w, body) defer unmask() if err != nil { writeError(w, provider.Responses, maskStatus(err), err.Error()) @@ -1677,13 +1677,13 @@ func codexBusy(status int, msg []byte) bool { // unmasked, and every fallback of it too (unredactedRoute). func codexRouteUnmasked(on *provider.Provider) bool { if on != nil { - return unredactedRoute(*on, false, nil) + return unredactedRoute(*on, "", false, nil) } p, err := provider.Find("codex") if err != nil || p.Account == nil || p.Account.Agent != "codex" { return false } - return unredactedRoute(*p, false, nil) + return unredactedRoute(*p, "", false, nil) } // codexAccountOut says the ChatGPT backend turned away a turn on Codex's diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index c70891ad0..57d98feb0 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -193,7 +193,7 @@ func (s *Server) serveDecideTries(w http.ResponseWriter, r *http.Request, body [ // translated here (decisions_systemone.go), was masked on its own // route. A masker that fails or is wanted and missing sends nothing. went := asked // the model the last try asked for - if slices.ContainsFunc(cs, func(c candidate) bool { return !c.p.SkipsRedaction() }) { + if slices.ContainsFunc(cs, func(c candidate) bool { return !c.unmasked() }) { mw, masked, done, hits, err := redactedHits(r.Context(), w, body) defer done() if err != nil { // fails closed diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go index b89f5050f..95d5de0ad 100644 --- a/internal/gateway/embeddings.go +++ b/internal/gateway/embeddings.go @@ -222,7 +222,7 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op side := s.beginSide(r, start, asked, tries[0].p.ID, grp) // 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() }) { + if slices.ContainsFunc(tries, func(c candidate) bool { return !c.unmasked() }) { var done func() var err error var hits maskHits diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index 6e2265a7f..b6715560d 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -95,6 +95,9 @@ type candidate struct { // what a member listed after it stands in for (standsInFor) member string place int + // redact is what the groups the member is in say of masking + // (Member.Masking): "" for one that is in none, or none says + redact string // reserve is set, to the provider's AtOnce, on an account or key held // back past the first that many (keepAtOnce): tried after them, never // given a request for want of a slot (laneMate) nor kept on by a @@ -102,6 +105,10 @@ type candidate struct { reserve int } +// unmasked says a request to the try goes as written: its groups say so, +// or none says otherwise and its provider is set to (provider.UnmaskedBy). +func (c candidate) unmasked() bool { return provider.UnmaskedBy(c.redact, c.p) } + // capHold is how an account is held at its usage cap: the cap of the // fullest window at or past its own cap, that window's share used, and when the last such window // renews (zero when one doesn't say). noCredits: it is a Codex account @@ -781,6 +788,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. for i := range l { l[i].effort, l[i].levels, l[i].effortMap, l[i].fast = m.Effort, m.Levels, m.EffortMap, m.Fast l[i].firstToken = innerFirstToken(m) + l[i].redact = m.Masking() l[i].patience = innerPatience(m) if len(m.Path) > 0 { l[i].member = m.Path[0] diff --git a/internal/gateway/fallback_group_test.go b/internal/gateway/fallback_group_test.go index 605598c41..26d7f21cd 100644 --- a/internal/gateway/fallback_group_test.go +++ b/internal/gateway/fallback_group_test.go @@ -148,13 +148,13 @@ func TestFallbackGroupKeepsMasking(t *testing.T) { if err != nil { t.Fatal(err) } - if !unredactedRoute(*near, false, nil) { + if !unredactedRoute(*near, "", false, nil) { t.Fatal("a group of unmasked local models masked the request") } if err := provider.SaveGroup(provider.Group{ID: "backup", Name: "Backup", Members: []string{"near2/m", "far/m"}}); err != nil { t.Fatal(err) } - if unredactedRoute(*near, false, nil) { + if unredactedRoute(*near, "", false, nil) { t.Fatal("a fallback group with a remote member left the request unmasked") } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 88a8ec148..589a99f3d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1988,12 +1988,12 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { // Count the same masked prompt that generation sends to the vendor, // and the one as written where generation sends that, masked only // then (#3973) - if _, ms, isGroup := provider.FindGroup(id); !ok || !unredactedRoute(p, isGroup, ms) { + if _, ms, isGroup := provider.FindGroup(id); !ok || !unredactedRoute(p, model, isGroup, ms) { if fp, before := maskedBefore(r); before { // masked by the magpie that passed it on (serve) r = withMaskedAs(r, fp) } else { - rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, isGroup, ms), w, body) + rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, model, isGroup, ms), w, body) if err != nil { writeError(w, provider.Anthropic, maskStatus(err), err.Error()) return @@ -2682,14 +2682,14 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // keeps it as it went, its secrets taken out as every archived body's // are, and an observer that wants the bodies is handed a copy masked // when it is first handed one, after the try (maskIn, #3973) - if sentWhole = unredactedRoute(p, isGroup, ms); !sentWhole { + if sentWhole = unredactedRoute(p, model, isGroup, ms); !sentWhole { if fp, before := maskedBefore(r); before { // masked by the magpie that passed it on, by the same // settings: it goes on as it came, that magpie puts its // values back, and a further magpie is told so too r = withMaskedAs(r, fp) } else { - rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, isGroup, ms), capture.ResponseWriter, body) + rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, model, isGroup, ms), capture.ResponseWriter, body) if err != nil { // fails closed: never sent unmasked log.Printf("gateway: %v", err) call.Status, call.Error = maskStatus(err), err.Error() diff --git a/internal/gateway/group_redact_test.go b/internal/gateway/group_redact_test.go new file mode 100644 index 000000000..b812a127a --- /dev/null +++ b/internal/gateway/group_redact_test.go @@ -0,0 +1,157 @@ +package gateway + +import ( + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A routing group says whether a request through it is masked +// (Group.Redact, 1dwsdqwd2 on X): off sends it as written to every member +// whatever its provider says, on masks it to a member set to go unmasked, +// and unset leaves each member's provider to say. Every route that reaches +// the group asks: the group asked for, a provider's fallback that names it, +// a group in a group, and a group built around the model that the request +// goes on to (provider.GroupsAfter). +func groupRedactFixture(t *testing.T, near, far string) { + t.Helper() + fresh(t) + for _, p := range []provider.Provider{ + {ID: "near", Name: "Near", Key: "k1", Models: []string{"m"}, Chat: "http://127.0.0.1:1/v1", Unredacted: true}, + {ID: "near2", Name: "Near2", Key: "k2", Models: []string{"m"}, Chat: "http://127.0.0.1:2/v1", Unredacted: true}, + {ID: "far", Name: "Far", Key: "k3", Models: []string{"m"}, Chat: "https://api.example.com/v1"}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ID: "mixed", Name: "Mixed", Members: []string{"near/m", "far/m"}, Redact: far}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{ID: "local", Name: "Local", Members: []string{"near/m", "near2/m"}, Redact: near}); err != nil { + t.Fatal(err) + } +} + +func TestGroupRedactOffSendsAsWritten(t *testing.T) { + groupRedactFixture(t, "", provider.RedactOff) + _, ms, ok := provider.FindGroup("group/mixed") + if !ok || !unmaskedMembers(ms) { + t.Fatalf("a group set to go as written masked a member of a remote provider (ok %v)", ok) + } +} + +func TestGroupRedactUnsetFollowsProviders(t *testing.T) { + groupRedactFixture(t, "", "") + _, mixed, _ := provider.FindGroup("group/mixed") + _, local, _ := provider.FindGroup("group/local") + if unmaskedMembers(mixed) || !unmaskedMembers(local) { + t.Fatalf("unset: mixed unmasked %v, local unmasked %v", unmaskedMembers(mixed), unmaskedMembers(local)) + } +} + +func TestGroupRedactOnMasksUnmaskedProviders(t *testing.T) { + groupRedactFixture(t, provider.RedactOn, "") + _, local, _ := provider.FindGroup("group/local") + if unmaskedMembers(local) { + t.Fatal("a group set to be masked sent as written to providers set to go unmasked") + } + p, model, ok := provider.Resolve("group/local") + if !ok { + t.Fatal("group/local doesn't resolve") + } + if _, ms, isGroup := provider.FindGroup("group/local"); unredactedRoute(p, model, isGroup, ms) || MaskRoute("group/local") { + t.Fatal("the route of a masked group is unredacted") + } +} + +// A provider's fallback that names a group is that group's members as the +// group has them. +func TestGroupRedactReachesAFallbackGroup(t *testing.T) { + for _, tc := range []struct { + group, want string + unmasked bool + }{{provider.RedactOff, "off", true}, {"", "unset", false}, {provider.RedactOn, "on", false}} { + groupRedactFixture(t, "", tc.group) + near, err := provider.Find("near") + if err != nil { + t.Fatal(err) + } + near.Fallback = []string{"group/mixed"} + if err := provider.Save(*near); err != nil { + t.Fatal(err) + } + near, _ = provider.Find("near") + if got := unredactedRoute(*near, "m", false, nil); got != tc.unmasked { + t.Errorf("a fallback group %s: unredacted %v, want %v", tc.want, got, tc.unmasked) + } + } +} + +// A provider set to go unmasked keeps its requests masked when a group +// built around its model may send them on to a model that is masked (the +// request that can't be taken goes on, provider.GroupsAfter), and a group +// that sends as written lets it keep them. +func TestGroupRedactReachesAGroupAfterTheModel(t *testing.T) { + for _, tc := range []struct { + group string + unmasked bool + }{{provider.RedactOff, true}, {"", false}, {provider.RedactOn, false}} { + groupRedactFixture(t, "", tc.group) + near, err := provider.Find("near") + if err != nil { + t.Fatal(err) + } + if got := unredactedRoute(*near, "m", false, nil); got != tc.unmasked { + t.Errorf("a group after near/m set %q: unredacted %v, want %v", tc.group, got, tc.unmasked) + } + } +} + +// Of a group in a group, any group set to be masked masks its members, and +// otherwise any set to send as written does. +func TestGroupRedactInANestedGroup(t *testing.T) { + for _, tc := range []struct { + outer, inner string + unmasked bool + }{{provider.RedactOff, "", true}, {"", provider.RedactOff, true}, {provider.RedactOff, provider.RedactOn, false}, {provider.RedactOn, provider.RedactOff, false}, {"", "", false}} { + groupRedactFixture(t, "", "") + if err := provider.SaveGroup(provider.Group{ID: "mixed", Name: "Mixed", Members: []string{"near/m", "far/m"}, Redact: tc.inner}); err != nil { + t.Fatal(err) + } + if tc.inner == "" { + if err := provider.SaveGroup(provider.Group{ID: "mixed", Name: "Mixed", Members: []string{"near/m", "far/m"}, Redact: provider.RedactFollow}); err != nil { + t.Fatal(err) + } + } + if err := provider.SaveGroup(provider.Group{ID: "outer", Name: "Outer", Members: []string{"group/mixed"}, Redact: tc.outer}); err != nil { + t.Fatal(err) + } + _, ms, ok := provider.FindGroup("group/outer") + if !ok || len(ms) == 0 { + t.Fatalf("outer %q inner %q: no members", tc.outer, tc.inner) + } + if got := unmaskedMembers(ms); got != tc.unmasked { + t.Errorf("outer %q inner %q: unmasked %v, want %v", tc.outer, tc.inner, got, tc.unmasked) + } + } +} + +// A group saved by a caller that doesn't know of the setting keeps it; +// "follow" clears it. +func TestGroupRedactSurvivesASaveThatDoesNotKnowIt(t *testing.T) { + groupRedactFixture(t, "", provider.RedactOff) + if err := provider.SaveGroup(provider.Group{ID: "mixed", Name: "Mixed", Members: []string{"near/m", "far/m"}}); err != nil { + t.Fatal(err) + } + g, _, _ := provider.FindGroup("group/mixed") + if g.Redact != provider.RedactOff { + t.Fatalf("a save that didn't name it left %q", g.Redact) + } + if err := provider.SaveGroup(provider.Group{ID: "mixed", Name: "Mixed", Members: []string{"near/m", "far/m"}, Redact: provider.RedactFollow}); err != nil { + t.Fatal(err) + } + if g, _, _ = provider.FindGroup("group/mixed"); g.Redact != "" { + t.Fatalf("follow left %q", g.Redact) + } +} diff --git a/internal/gateway/redact.go b/internal/gateway/redact.go index bc2df7d83..63cb0bf68 100644 --- a/internal/gateway/redact.go +++ b/internal/gateway/redact.go @@ -347,42 +347,51 @@ func (l *laterMasked) body() []byte { return l.b } -// unredactedRoute says a request resolved to p, or to the group whose -// models are ms, goes only where the user set requests to go unmasked -// (provider.SkipsRedaction): p and each of its fallbacks, or every model of -// the group (a member's own fallbacks are not the group's, see planGroup). -// One that may go on to anyone else stays masked for all of them. -func unredactedRoute(p provider.Provider, isGroup bool, ms []provider.Member) bool { +// unredactedRoute says a request resolved to model of p, or to the group +// whose models are ms, goes only where the user set requests to go +// unmasked (provider.SkipsRedaction, or a group's Redact): p and each of +// its fallbacks, the groups built around the model that it goes on to when +// it can't take the request (provider.GroupsAfter, for a model named), or +// every model of the group (a member's own fallbacks are not the group's, +// see planGroup). One that may go on to anyone else stays masked for all +// of them. model is "" for a route with none to name. +func unredactedRoute(p provider.Provider, model string, isGroup bool, ms []provider.Member) bool { if isGroup { - if len(ms) == 0 { - return false - } - for _, m := range ms { - if !m.Provider.SkipsRedaction() { - return false - } - } - return true + return unmaskedMembers(ms) } if !p.SkipsRedaction() { return false } - // one that resolves to nothing isn't tried (plan); a routing group - // among them is each of its members - for _, m := range provider.FallbackModels(p) { - if !m.Provider.SkipsRedaction() { - return false - } - } - return true + after := afterMembers(p, model) + return len(after) == 0 || unmaskedMembers(after) } -// unmaskedMembers says every model in ms, the ones a picture, a video or -// a vendor's own route may go to, is a provider the user set to go -// unmasked (provider.SkipsRedaction), so the request goes as written, as -// a chat's does on such a route (unredactedRoute). None is masked. +// afterMembers are the models a request to model of p may go on to: its +// fallbacks (a routing group among them is each of its members; one that +// resolves to nothing isn't tried, see plan) and the members of the groups +// built around it (provider.GroupsAfter), each as its groups' Redact has +// it. +func afterMembers(p provider.Provider, model string) []provider.Member { + ms := provider.FallbackModels(p) + if model == "" { + return ms + } + for _, gid := range provider.GroupsAfter(p.ID + "/" + model) { + if !slices.Contains(p.Fallback, gid) { + _, gms, _ := provider.FallbackGroup(gid) + ms = append(ms, gms...) + } + } + return ms +} + +// unmaskedMembers says every model in ms, the ones a picture, a video, a +// group or a vendor's own route may go to, goes as written: its provider +// is one the user set to go unmasked (provider.SkipsRedaction), or its +// group says so (Group.Redact), so the request goes as written, as a +// chat's does on such a route (unredactedRoute). None is masked. func unmaskedMembers(ms []provider.Member) bool { - return len(ms) > 0 && !slices.ContainsFunc(ms, func(m provider.Member) bool { return !m.Provider.SkipsRedaction() }) + return len(ms) > 0 && !slices.ContainsFunc(ms, func(m provider.Member) bool { return !m.Unmasked() }) } // maskedFor is ctx for masking a request resolved to p, or to the group @@ -391,11 +400,11 @@ func unmaskedMembers(ms []provider.Member) bool { // on that route before goes on it again as it went (masking.WithRoute), // so a prefix a vendor cached isn't rewritten by what was found in it // since; another route masks it afresh. -func maskedFor(ctx context.Context, p provider.Provider, isGroup bool, ms []provider.Member) context.Context { +func maskedFor(ctx context.Context, p provider.Provider, model string, isGroup bool, ms []provider.Member) context.Context { var ids []string if !isGroup { ids = append(ids, p.ID) - ms = provider.FallbackModels(p) + ms = afterMembers(p, model) } for _, m := range ms { ids = append(ids, m.Provider.ID) @@ -437,7 +446,7 @@ func MaskRoute(id string) bool { return false } _, ms, isGroup := provider.FindGroup(id) - return unredactedRoute(p, isGroup, ms) + return unredactedRoute(p, model, isGroup, ms) } // maskRouteFor is the model the user set for an agent's request that diff --git a/internal/gui/api.go b/internal/gui/api.go index 2136cab04..628cf31dc 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -910,8 +910,9 @@ func settingsState() settingsJSON { } } s.TitleModels, s.MaskRouteModels = []modelRef{}, []modelRef{} - // only a provider set to go unmasked can take one (most have none) - unmaskedAny := slices.ContainsFunc(provider.All(), provider.Provider.SkipsRedaction) + // only a provider or a group set to go unmasked can take one (most have none) + unmaskedAny := slices.ContainsFunc(provider.All(), provider.Provider.SkipsRedaction) || + slices.ContainsFunc(provider.Groups(), func(g provider.Group) bool { return g.Redact == provider.RedactOff }) s.UnmaskedProviders = []modelRef{} for _, p := range provider.All() { if p.SkipsRedaction() { diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index d1de045a3..bc6b49c89 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6202,7 +6202,7 @@ function routingPage(part) { // there, rather than leaving the slot empty. const openGroupEditor = async (g) => { if (groupDirty() && !(await confirmDiscard())) return false; - gEdit = { id: g.id, draft: { name: g.name, note: g.note || "", members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], keys: [...(g.keys || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: sinkModeOf(g), unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: g.patience || 0, context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; + gEdit = { id: g.id, draft: { name: g.name, note: g.note || "", members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], keys: [...(g.keys || [])], redact: g.redact || "", routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: sinkModeOf(g), unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: g.patience || 0, context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; renderGroups(); return true; }; @@ -7695,6 +7695,27 @@ function routingPage(part) { }; drawKeys(); + // masking (1dwsdqwd2 on X): the group follows each member's provider + // ("Send requests unmasked") and Settings, or is masked as Settings say + // whichever provider it has, or is sent as written (Group.Redact) + const redactLabel = el("label", "rt-gredact", t("Masking")), redactBox = el("div", "rt-gredact"); + ed.append(redactLabel, redactBox); + const REDACT = { "": "Follow providers", on: "Always masked", off: "Sent as written" }; + const drawRedact = () => { + const b = el("button", "rt-cond rt-gredact-b" + (d.redact ? " on" : "")); + b.type = "button"; + b.append(el("span", "", t(REDACT[d.redact] || REDACT[""]))); + b.setAttribute("aria-label", `${t("Masking")}: ${b.textContent}`); + b.onclick = (ev) => pickFrom("masking", b, ev, Object.entries(REDACT).map(([value, label]) => ({ value, label: t(label), note: d.redact === value ? "✓" : "" })), (v) => { + d.redact = v === "on" || v === "off" ? v : ""; + drawRedact(); + }, d.redact); + const row = el("div", "rt-pickrow"); + row.append(b, infoTip(t("Whether requests through this group are masked. Follow providers: each model's own setting, Send requests unmasked, decides. Always masked: as Settings say, even to a provider set to go unmasked. Sent as written: not masked, to every model in it. Masking turned off in Settings masks nothing."))); + redactBox.replaceChildren(row); + }; + drawRedact(); + // patterns: models found by their ids, now and as providers list new // ones (#766): after the models named, in the catalog's order, until // the user puts them in another; then each keeps its place, one gone @@ -8756,7 +8777,7 @@ function routingPage(part) { if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn"); saveBtn.classList.add("busy"); // refused, Add can be pressed again (busy, it takes no clicks) - groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), note: (d.note || "").trim(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: d.sink === "sink" && sinkable(d.routing), noSink: d.sink === "", firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), keys: d.keys, unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) + groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), note: (d.note || "").trim(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: d.sink === "sink" && sinkable(d.routing), noSink: d.sink === "", firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), keys: d.keys, redact: d.redact || "follow", unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) .then(() => saveBtn.classList.remove("busy")); }; // what goes wrong is said where it is seen, never a click that does nothing diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index f4bb0996a..53981f7a4 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -731,6 +731,9 @@ magpie.strings({ "This group spends only {accounts} of {provider}": "这个组只消耗 {provider} 的 {accounts}", "This group may spend every account of {provider}": "这个组可以消耗 {provider} 的每个账号", "Any gateway key": "任意网关密钥", + "Follow providers": "跟随各供应商", + "Always masked": "始终脱敏", + "Whether requests through this group are masked. Follow providers: each model's own setting, Send requests unmasked, decides. Always masked: as Settings say, even to a provider set to go unmasked. Sent as written: not masked, to every model in it. Masking turned off in Settings masks nothing.": "请求经过这个组时是否脱敏。跟随各供应商:由每个模型自己的“请求不脱敏”设置决定。始终脱敏:按设置里的规则脱敏,即使供应商设为不脱敏。按原文发送:组里每个模型都不脱敏。设置里关闭脱敏时,什么都不会脱敏。", "Only {keys} may see and use this group": "只有 {keys} 能看到和使用这个组", "Every gateway key may use this group": "每个网关密钥都能使用这个组", "key deleted": "密钥已删除", @@ -1466,6 +1469,9 @@ magpie.strings({ "This group spends only {accounts} of {provider}": "這個組只消耗 {provider} 的 {accounts}", "This group may spend every account of {provider}": "這個組可以消耗 {provider} 的每個帳號", "Any gateway key": "任意閘道金鑰", + "Follow providers": "跟隨各供應商", + "Always masked": "一律脫敏", + "Whether requests through this group are masked. Follow providers: each model's own setting, Send requests unmasked, decides. Always masked: as Settings say, even to a provider set to go unmasked. Sent as written: not masked, to every model in it. Masking turned off in Settings masks nothing.": "請求經過這個組時是否脫敏。跟隨各供應商:由每個模型自己的「請求不脫敏」設定決定。一律脫敏:依設定的規則脫敏,即使供應商設為不脫敏。照原文送出:組裡每個模型都不脫敏。設定中關閉脫敏時,什麼都不會脫敏。", "Only {keys} may see and use this group": "只有 {keys} 能看到和使用這個組", "Every gateway key may use this group": "每個閘道金鑰都能使用這個組", "key deleted": "金鑰已刪除", @@ -2201,6 +2207,9 @@ magpie.strings({ "This group spends only {accounts} of {provider}": "このグループは {provider} の {accounts} だけを使います", "This group may spend every account of {provider}": "このグループは {provider} のすべてのアカウントを使えます", "Any gateway key": "どのゲートウェイキーでも", + "Follow providers": "プロバイダに従う", + "Always masked": "常にマスクする", + "Whether requests through this group are masked. Follow providers: each model's own setting, Send requests unmasked, decides. Always masked: as Settings say, even to a provider set to go unmasked. Sent as written: not masked, to every model in it. Masking turned off in Settings masks nothing.": "このグループを通るリクエストをマスクするかどうか。プロバイダに従う:各モデルの「リクエストをマスクしない」の設定で決まります。常にマスクする:マスクしない設定のプロバイダでも、設定どおりにマスクします。そのまま送る:グループ内のどのモデルにもマスクせずに送ります。設定でマスキングをオフにしていると、何もマスクされません。", "Only {keys} may see and use this group": "{keys} だけがこのグループを見て使えます", "Every gateway key may use this group": "どのゲートウェイキーでもこのグループを使えます", "key deleted": "削除されたキー", @@ -2936,6 +2945,9 @@ magpie.strings({ "This group spends only {accounts} of {provider}": "Diese Gruppe verbraucht nur {accounts} von {provider}", "This group may spend every account of {provider}": "Diese Gruppe darf jedes Konto von {provider} verbrauchen", "Any gateway key": "Jeder Zugangsschlüssel", + "Follow providers": "Den Anbietern folgen", + "Always masked": "Immer maskiert", + "Whether requests through this group are masked. Follow providers: each model's own setting, Send requests unmasked, decides. Always masked: as Settings say, even to a provider set to go unmasked. Sent as written: not masked, to every model in it. Masking turned off in Settings masks nothing.": "Ob Anfragen über diese Gruppe maskiert werden. Den Anbietern folgen: Die Einstellung „Anfragen unmaskiert senden“ des jeweiligen Modells entscheidet. Immer maskiert: wie in den Einstellungen, auch zu einem Anbieter, der unmaskiert sendet. Unverändert gesendet: an jedes Modell der Gruppe unmaskiert. Ist die Maskierung in den Einstellungen aus, wird nichts maskiert.", "Only {keys} may see and use this group": "Nur {keys} sieht und nutzt diese Gruppe", "Every gateway key may use this group": "Jeder Zugangsschlüssel darf diese Gruppe nutzen", "key deleted": "Schlüssel entfernt", diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 78c369ceb..5bbbf672c 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -822,6 +822,7 @@ body.window .rt-gedit > .bar { --vfoot: 8px; } /* a group bound to gateway keys (Group.Keys): a long key name ellipsizes */ .rt-gedit > .rt-gkeys[hidden] { display: none; } .rt-gkey { min-width: 0; } +.rt-gredact-b { min-width: 0; } .rt-gadd { justify-self: start; display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 11px 0 9px; border-radius: 8px; diff --git a/internal/gui/tests/group-redact.test.cjs b/internal/gui/tests/group-redact.test.cjs new file mode 100644 index 000000000..69e48de16 --- /dev/null +++ b/internal/gui/tests/group-redact.test.cjs @@ -0,0 +1,148 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A routing group can be masked or not on its own (1dwsdqwd2 on X): the +// group editor has a Masking row whose button says "Follow providers" +// until the app's menu picks "Always masked" or "Sent as written", and +// Save sends the pick as Group.Redact ("follow" clears it). A group that +// has one shows it. In every language, Chromium and WebKit, at a wide and +// a narrow window; nothing sticks out of the editor. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const models = [{ id: "rl/glm-5", name: "glm-5", provider: "rl", providerName: "Relay", icon: "generic" }]; +const groups = (red) => ({ + models, pools: [], accounts: {}, gatewayKeys: [], + groups: [{ id: "work", name: "Work", members: ["rl/glm-5"], routing: "order", ready: true, accounts: [], ...(red ? { redact: red } : {}), + memberInfo: [{ id: "rl/glm-5", ready: true }] }], +}); + +const words = { + en: { edit: "Edit", save: "Save", label: "Masking", follow: "Follow providers", on: "Always masked", off: "Sent as written" }, + zh: { edit: "编辑", save: "保存", label: "脱敏", follow: "跟随各供应商", on: "始终脱敏", off: "按原样发送" }, + "zh-TW": { edit: "編輯", save: "儲存", label: "脫敏", follow: "跟隨各供應商", on: "一律脫敏", off: "照原樣送出" }, + ja: { edit: "編集", save: "保存", label: "マスク", follow: "プロバイダに従う", on: "常にマスクする", off: "そのまま送信" }, + de: { edit: "Bearbeiten", save: "Speichern", label: "Maskierung", follow: "Den Anbietern folgen", on: "Immer maskiert", off: "Unverändert gesendet" }, +}; + +function serve(lang, posts, red) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json(groups(red)); + if (url.pathname.startsWith("/api/groups/")) { + posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") }); + return json(groups(red)); + } + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +async function open(engine, lang, width, red, t) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width, height: 1600 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-group-redact.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts, red)); + await page.goto("http://magpie.test/?view=groups"); + const card = page.locator(".rt-group", { hasText: "Work" }); + await card.waitFor(); + return { page, card, errors, posts }; +} + +const option = (page, text) => page.locator("#pop:not([hidden]) #list li:not(.group)", { has: page.locator(".v", { hasText: new RegExp("^" + text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "$") }) }); + +async function save(page, w) { + const b = page.locator(".rt-gedit button.primary", { hasText: w.save }); + await b.scrollIntoViewIfNeeded(); + await b.click(); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); +} + + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [1100, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: a group is masked, or not, on its own`, async (t) => { + const { page, card, errors, posts } = await open(engine, lang, width, "", t); + await card.locator("button", { hasText: w.edit }).click(); + const ed = page.locator(".rt-gedit"); + const label = ed.locator("> label.rt-gredact"); + await label.waitFor(); + assert.equal((await label.textContent()).trim(), w.label); + const chip = ed.locator("button.rt-gredact-b"); + const said = async () => (await chip.textContent()).trim(); + assert.equal(await said(), w.follow); + assert.doesNotMatch((await chip.getAttribute("class")) || "", /\bon\b/); + assert.equal(await ed.locator("select").count(), 0); + + await chip.scrollIntoViewIfNeeded(); + await chip.click(); + await option(page, w.off).waitFor(); + assert.deepEqual(await page.locator("#pop #list li:not(.group) .v").allTextContents(), [w.follow, w.on, w.off]); + await option(page, w.off).click(); + await page.waitForFunction(() => document.querySelector("#pop").hidden); + assert.equal(await said(), w.off); + assert.match((await chip.getAttribute("class")) || "", /\bon\b/); + + const over = await page.evaluate(() => { + const ed = document.querySelector(".rt-gedit"), b = ed.querySelector(".rt-gredact-b"); + return { page: document.documentElement.scrollWidth - document.documentElement.clientWidth, row: b.getBoundingClientRect().right - ed.getBoundingClientRect().right }; + }); + assert(over.page <= 0, `the page scrolls sideways by ${over.page}px`); + assert(over.row <= 1, `the button sticks out of the editor by ${over.row}px`); + + await save(page, w); + assert.equal(posts.filter((p) => p.path === "/api/groups/save").at(-1).body.redact, "off"); + assert.deepEqual(errors, []); + }); + + if (width === 1100) { + test(`${engine} ${lang}: a group that masks always shows it, and goes back to following`, async (t) => { + const { page, card, errors, posts } = await open(engine, lang, width, "on", t); + await card.locator("button", { hasText: w.edit }).click(); + const chip = page.locator(".rt-gedit button.rt-gredact-b"); + await chip.waitFor(); + assert.equal((await chip.textContent()).trim(), w.on); + await save(page, w); + assert.equal(posts.filter((p) => p.path === "/api/groups/save").at(-1).body.redact, "on", "saved as it was"); + await card.locator("button", { hasText: w.edit }).click(); + await chip.waitFor(); + await chip.click(); + await option(page, w.follow).click(); + await page.waitForFunction(() => document.querySelector("#pop").hidden); + assert.equal((await chip.textContent()).trim(), w.follow); + await save(page, w); + assert.equal(posts.filter((p) => p.path === "/api/groups/save").at(-1).body.redact, "follow"); + assert.deepEqual(errors, []); + }); + } + } + } +} diff --git a/internal/provider/group.go b/internal/provider/group.go index 5538ba393..bec70f596 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -335,6 +335,16 @@ type Group struct { // (SaveGroup), so a caller that doesn't know of them leaves them be; // empty clears them. Keys []string `json:"keys,omitempty"` + // Redact is whether a request through the group is masked (1dwsdqwd2 + // on X: some groups masked, some not): "" follows each member's + // provider ("Send requests unmasked") and Settings, RedactOn masks it + // as Settings say whichever provider, RedactOff sends it as written. + // It is the user's alone: Settings with masking off mask nothing, a + // shared group carries none, and in a group inside a group any RedactOn + // among them wins over RedactOff. Saved, "" keeps the group's + // (SaveGroup) and RedactFollow clears it, so a caller that doesn't + // know of it leaves it be. + Redact string `json:"redact,omitempty"` // Auto is set on a group magpie found: one model served by several // providers. It is derived, never stored. Auto bool `json:"auto,omitempty"` @@ -369,7 +379,11 @@ type Member struct { Path []string // Via are the groups in the group it is of, the outermost first: the // group each of Path's members but the last names. - Via []Group + Via []Group + // Redact is what the groups it is reached through say of masking, the + // group itself and each in Via (Group.Redact): RedactOn if any says so, + // else RedactOff if any does, else "". + Redact string Provider Provider Model string // what the vendor is asked for // Effort is the reasoning the member is fixed at ("provider/model:low"), @@ -459,7 +473,7 @@ func (m Member) Groups() []string { // Below is the member as the group at depth (0 the group itself, 1 the // group in it Path[0] names, …) has it. func (m Member) Below(depth int) Member { - out := Member{ID: m.Path[depth], Path: m.Path[depth:], Via: m.Via[depth:], Provider: m.Provider, Model: m.Model, Effort: m.Effort, Levels: m.Levels, EffortMap: m.EffortMap, Fast: m.Fast, Account: m.Account, At: m.At} + out := Member{ID: m.Path[depth], Path: m.Path[depth:], Via: m.Via[depth:], Redact: m.Redact, Provider: m.Provider, Model: m.Model, Effort: m.Effort, Levels: m.Levels, EffortMap: m.EffortMap, Fast: m.Fast, Account: m.Account, At: m.At} // its other places in the same group at depth for _, o := range m.Also { if len(o.Path) > depth && slices.Equal(o.Path[:depth], m.Path[:depth]) { @@ -1281,8 +1295,9 @@ func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func( out := make([]Member, 0, n) seen := make(map[string]int, n) // where in out at := 0 - var walk func(g Group, path []string, via []Group, in []string) - walk = func(g Group, path []string, via []Group, in []string) { + var walk func(g Group, path []string, via []Group, in []string, redact string) + walk = func(g Group, path []string, via []Group, in []string, redact string) { + redact = RedactWith(redact, g.Redact) for _, id := range g.routes() { if gid, ok := strings.CutPrefix(id, GroupPrefix); ok { sub, ok := groupOf(all, gid) @@ -1292,7 +1307,7 @@ func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func( // its own copy: all may be the groups held (sharedGroupsIn), // and a member's Via and EffortMap are its caller's sub = cloneGroup(sub).Within(g) - walk(sub, append(slices.Clone(path), id), append(slices.Clone(via), sub.Live()), append(slices.Clone(in), gid)) + walk(sub, append(slices.Clone(path), id), append(slices.Clone(via), sub.Live()), append(slices.Clone(in), gid), redact) continue } model, effort := memberEffortIn(entries, id) @@ -1309,7 +1324,7 @@ func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func( key := WithMemberAccount(WithMemberEffort(p.ID+"/"+m, effort), acct) here := append(slices.Clone(path), id) fixed, levels := MemberLevels(effort) - mem := Member{ID: here[0], Path: here, Via: via, Provider: p, Model: m, Effort: fixed, Levels: levels, Fast: g.IsFast(id), Account: acct, At: at} + mem := Member{ID: here[0], Path: here, Via: via, Redact: redact, Provider: p, Model: m, Effort: fixed, Levels: levels, Fast: g.IsFast(id), Account: acct, At: at} if fixed == "" && levels == nil { mem.EffortMap = g.MemberEffortMap(id) } @@ -1327,7 +1342,7 @@ func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func( out = append(out, mem) } } - walk(g, nil, nil, []string{g.ID}) + walk(g, nil, nil, []string{g.ID}, "") if len(out) == 0 { return nil // none, as before it was made at its size } @@ -1795,8 +1810,16 @@ func SaveGroup(g Group) error { return err } var was, keysWas, formerWas []string + var redactWas string if i := slices.IndexFunc(f.Groups, func(x Group) bool { return x.ID == g.ID }); i >= 0 { - was, keysWas, formerWas = f.Groups[i].Accounts, f.Groups[i].Keys, f.Groups[i].Former + was, keysWas, formerWas, redactWas = f.Groups[i].Accounts, f.Groups[i].Keys, f.Groups[i].Former, f.Groups[i].Redact + } + switch g.Redact { + case "": + g.Redact = redactWas // a caller that doesn't know of it + case RedactOn, RedactOff: + default: + g.Redact = "" // RedactFollow, or a word it doesn't know } if g.Former == nil { g.Former = slices.Clone(formerWas) // a caller that doesn't know of them @@ -2386,3 +2409,57 @@ func renameGroupPicks(old, now string) error { catalog.Touched() return nil } + +// A Group's Redact: what a request through it is masked by. +const ( + RedactOn = "on" // masked as Settings say, whatever its provider says + RedactOff = "off" // sent as written + RedactFollow = "follow" // saved: clears it, the providers' own say +) + +// RedactWith is what two say of masking together: on wins over off, and +// either over nothing. +func RedactWith(a, b string) string { + if a == RedactOn || b == RedactOn { + return RedactOn + } + if a == RedactOff || b == RedactOff { + return RedactOff + } + return "" +} + +// Masking is what the groups the member is reached through say of +// masking, all its places counted (Also, the same model met again in +// another group): RedactOn if any says so, RedactOff only if all do, else +// "". The model's provider is the same in each place. +func (m Member) Masking() string { + out := m.Redact + for _, o := range m.Also { + switch o := o.Masking(); { + case o == RedactOn || out == RedactOn: + out = RedactOn + case o != out: + out = "" + } + } + return out +} + +// Unmasked says a request to the member goes as written: its groups say +// so (Masking), or none says otherwise and its provider is set to send +// unmasked (Provider.SkipsRedaction). +func (m Member) Unmasked() bool { return UnmaskedBy(m.Masking(), m.Provider) } + +// UnmaskedBy says a request to p goes as written under what groups say of +// masking (Group.Redact, Member.Masking): RedactOn never, RedactOff +// always, else as p is set. +func UnmaskedBy(redact string, p Provider) bool { + switch redact { + case RedactOn: + return false + case RedactOff: + return true + } + return p.SkipsRedaction() +} diff --git a/internal/provider/group_share.go b/internal/provider/group_share.go index 14822eeee..53735bc84 100644 --- a/internal/provider/group_share.go +++ b/internal/provider/group_share.go @@ -55,6 +55,7 @@ func ShareGroup(id string) (string, error) { g.Accounts = nil // this magpie's accounts: another has its own withoutMemberAccounts(&g) // a member's own account too g.Keys = nil // this magpie's gateway keys, the same + g.Redact = "" // and whether it masks: the receiver's call g.Seen = nil // what this magpie found: another finds its own g.Rules = slices.DeleteFunc(g.Rules, Rule.ByFolder) out, err := json.Marshal(SharedGroup{Magpie: ShareMark, Version: ShareVersion, Group: g}) @@ -163,6 +164,7 @@ func importGroup(text string, over bool) (Imported, error) { g := s.Group g.Accounts = nil // another magpie's accounts, never this one's g.Keys = []string{} // its gateway keys too; over, the user's are kept below + g.Redact = "" // whether it masks is the receiver's call, never a text's withoutMemberAccounts(&g) // and a member's own account (a text made before ShareGroup dropped them) entries := providerEntries() all := Groups() @@ -265,6 +267,7 @@ func importGroup(text string, over bool) (Imported, error) { g.ID = old.ID g.Accounts = old.Accounts g.Keys = slices.Clone(old.Keys) + g.Redact = old.Redact for _, r := range old.Rules { if !r.ByFolder() { continue