Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
redact: a text sent on a route goes on it as it went, the model's late finds too (vvrfxyz on X)
yetone7632e1be1d5d
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 6672026a7..85a3bca65 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -137,7 +137,7 @@ recorded as a prediction failure (`noPrediction`).## Runtime path1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression` and `http-client/src/request.rs`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.-2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and 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, so a value a rule first finds later in a conversation doesn't change the prompt the vendor has cached and rewrite all of it to the cache, `sentKnownSpans`), 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)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it 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 and embeddings follow the same rule. 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). 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`).+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)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it 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 and embeddings follow the same rule. 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). 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`).- 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 public IP address goes the same way as an address from the documentation ranges (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24, host .101 to .254; 2001:db8::/32 for IPv6), the same one for that address while magpie runs and never another address's, put back only where it stands as a whole address, in a streamed tool call's arguments too (`ipStandIn`, `restoreAddr`; `TestIPGoesAsADocumentationAddress`). 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); past the 462 IPv4 stand-ins an address goes as its placeholder. 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`). Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `[email protected]`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`[email protected]`, `[email protected]`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). A domain needs a dot and labels a host can have, so a disassembly's symbols go as written for both too: `system@plt`, `[email protected]`, `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). `[email protected]` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.- With *Find with a local model* on (`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 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 @ (`[email protected]`; `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 (`[email protected]:` in pnpm-lock.yaml; `notPackagePin`); `TestPackageNamesGoAsWritten` and `TestModelPackageNamesNotMasked` hold them. 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 `<total_tokens>` 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 (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-<model>.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.goindex 098405c9d..a198050ef 100644--- a/internal/gateway/codex_backend.go+++ b/internal/gateway/codex_backend.go@@ -949,7 +949,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest stif r.Method == http.MethodPost {var unmask func()var err error- w, body, unmask, maskedHits, err = redactedHits(r.Context(), w, body)+ to := provider.Provider{ID: "codex"} // the ChatGPT backend+ if on != nil {+ to = *on+ }+ 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())diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex a86d0a479..3245e094a 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -1454,7 +1454,7 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) {// and the one as written where generation sends that, masked only// then (#3973)if _, ms, isGroup := provider.FindGroup(id); !ok || !unredactedRoute(p, isGroup, ms) {- rw, b, done, hits, err := redactedHits(r.Context(), w, body)+ rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, isGroup, ms), w, body)if err != nil {writeError(w, provider.Anthropic, maskStatus(err), err.Error())return@@ -2038,7 +2038,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro// 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 {- rw, b, done, hits, err := redactedHits(r.Context(), capture.ResponseWriter, body)+ rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, isGroup, ms), capture.ResponseWriter, body)if err != nil { // fails closed: never sent unmaskedlog.Printf("gateway: %v", err)call.Status, call.Error = maskStatus(err), err.Error()diff --git a/internal/gateway/masked_cache_prefix_test.go b/internal/gateway/masked_cache_prefix_test.goindex 53dfba3c3..1c17d20c1 100644--- a/internal/gateway/masked_cache_prefix_test.go+++ b/internal/gateway/masked_cache_prefix_test.go@@ -132,3 +132,56 @@ func TestMaskedConversationKeepsItsCachedPrefix(t *testing.T) {}}}++// A text goes as it went only where it went: the system prompt sent to+// one provider with a value as written, before a rule found the value,+// keeps it as written there, and has it masked on its way to another+// provider, which was never sent it (masking's route, maskedFor).+func TestMaskedPrefixKeptOnlyOnItsRoute(t *testing.T) {+ fresh(t)+ var mu sync.Mutex+ got := map[string][]string{}+ serve := func(name string) *httptest.Server {+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ b, _ := io.ReadAll(r.Body)+ mu.Lock()+ got[name] = append(got[name], string(b))+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"id":"m","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"output_tokens":1}}`)+ }))+ t.Cleanup(up.Close)+ if err := provider.Save(provider.Provider{ID: name, Name: name, Key: "k", Models: []string{"claude-opus-5-5"}, Anthropic: up.URL + "/v1"}); err != nil {+ t.Fatal(err)+ }+ return up+ }+ serve("first")+ serve("second")+ if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {+ t.Fatal(err)+ }+ s := New()+ const secret = "Zr5routeKeep42q"+ system := `"system":"You are Claude. Staging deploys with ` + secret + ` for now."`+ send := func(to, msgs string) {+ t.Helper()+ if code, raw := postJSON(t, s, "/v1/messages", `{"model":"`+to+`/claude-opus-5-5","max_tokens":64,`+system+`,"messages":[`+msgs+`]}`); code != 200 {+ t.Fatalf("%s: %d %s", to, code, raw)+ }+ }+ send("first", `{"role":"user","content":"hi"}`)+ send("first", `{"role":"user","content":"hi"},{"role":"assistant","content":"ok"},{"role":"user","content":"DB_PASSWORD=`+secret+`"}`)+ send("second", `{"role":"user","content":"hi"}`)+ mu.Lock()+ defer mu.Unlock()+ if len(got["first"]) != 2 || len(got["second"]) != 1 {+ t.Fatalf("upstream got %d and %d", len(got["first"]), len(got["second"]))+ }+ if !strings.Contains(got["first"][1], "deploys with "+secret) {+ t.Errorf("the first provider's system prompt, sent with the value as written, was rewritten: %s", got["first"][1])+ }+ if strings.Contains(got["second"][0], secret) {+ t.Errorf("another provider, never sent it, got the value as written: %s", got["second"][0])+ }+}diff --git a/internal/gateway/redact.go b/internal/gateway/redact.goindex 0f38c1f82..7f92886a2 100644--- a/internal/gateway/redact.go+++ b/internal/gateway/redact.go@@ -6,6 +6,7 @@ import ("fmt""net/http""net/http/httptest"+ "slices""strings""sync""time"@@ -315,6 +316,25 @@ func unredactedRoute(p provider.Provider, isGroup bool, ms []provider.Member) boreturn true}+// maskedFor is ctx for masking a request resolved to p, or to the group+// whose models are ms, that may go to the providers unredactedRoute walks:+// p and each of its fallbacks, or every model of the group. A text sent+// 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 {+ var ids []string+ if !isGroup {+ ids = append(ids, p.ID)+ ms = provider.FallbackModels(p)+ }+ for _, m := range ms {+ ids = append(ids, m.Provider.ID)+ }+ slices.Sort(ids)+ return masking.WithRoute(ctx, strings.Join(slices.Compact(ids), "\x00"))+}+// agentTurnKey marks a request an agent sent (serveAgent, count_tokens,// a Codex turn on its own sign-in), the ones the user's route for masked// requests is for (maskRouteFor); magpie's own asks made on an agent'sdiff --git a/internal/masking/masking.go b/internal/masking/masking.goindex 6de6eb78c..d7b51a9fa 100644--- a/internal/masking/masking.go+++ b/internal/masking/masking.go@@ -31,11 +31,24 @@ func Wanted(st settings.Settings) bool {func options() redact.Options { return optionsCtx(context.Background()) }-// optionsCtx is options with the model's wait ending with ctx.+// routeKey holds where a request masked on ctx may go (WithRoute).+type routeKey struct{}++// WithRoute is ctx for masking a request that may go only to route (the+// providers its model, the model's fallbacks or a routing group's members+// are served by): a text sent on it before goes as it went there+// (redact.Options.Route).+func WithRoute(ctx context.Context, route string) context.Context {+ return context.WithValue(ctx, routeKey{}, route)+}++// optionsCtx is options with the model's wait ending with ctx, for the+// route ctx has (WithRoute).func optionsCtx(ctx context.Context) redact.Options {st := settings.Shared()o := redact.Options{Secrets: st.Redact, Personal: st.RedactPersonal, Kinds: st.RedactKinds, Words: st.RedactWords, WordsAnyCase: st.RedactWordsAnyCase, WordsWhole: st.RedactWordsWhole, Rules: st.RedactRules,Actions: st.RedactActions, Allow: st.RedactAllow, Shape: st.RedactShape}+ o.Route, _ = ctx.Value(routeKey{}).(string)if (st.Redact || st.RedactPersonal) && ModelWanted(st) {// until the model is on disk the rules mask alone, and nothing is// held back for a download (it is started here)diff --git a/internal/masking/sent_route_test.go b/internal/masking/sent_route_test.gonew file mode 100644index 000000000..b9cbc908d--- /dev/null+++ b/internal/masking/sent_route_test.go@@ -0,0 +1,114 @@+package masking++import (+ "context"+ "encoding/json"+ "path/filepath"+ "strings"+ "sync"+ "testing"++ "github.com/yetone/magpie/internal/pii"+ "github.com/yetone/magpie/internal/redact"+ "github.com/yetone/magpie/internal/settings"+)++// slowReader is the local model on a slow CPU: a text it is asked about+// the first time isn't read in the request's wait (a pii.Partial, nothing+// found in it), and it has been read by the next request, which finds+// the name in it.+type slowReader struct {+ fake+ name string+ mu sync.Mutex+ read map[string]bool+}++func (m *slowReader) Find(_ context.Context, texts []string) ([][]redact.Found, error) {+ m.mu.Lock()+ defer m.mu.Unlock()+ out := make([][]redact.Found, len(texts))+ missing := 0+ for i, t := range texts {+ if !m.read[t] {+ m.read[t] = true // read after the request stopped waiting+ missing+++ continue+ }+ if at := strings.Index(t, m.name); at >= 0 {+ out[i] = []redact.Found{{Start: at, End: at + len(m.name), Label: "private_person", Score: 0.95}}+ }+ }+ if missing > 0 {+ return out, &pii.Partial{Missing: missing, Of: len(texts)}+ }+ return out, nil+}++// vvrfxyz on X: with masking on, dsh's prompt-cache hits fell. Replayed+// on a Linux CPU, a tool's output (customers.csv) the default model+// hadn't read in its 2s went with the rules' masking alone, and the next+// turn masked a name in it the model had read since: from that message on+// the prompt was new to the vendor. A text sent before on a route goes on+// it as it went; new text has the name masked, and another route, which+// was never sent the text, gets it masked.+func TestModelReadingLateKeepsTheSentPrefix(t *testing.T) {+ h := t.TempDir()+ t.Setenv("HOME", h)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))+ if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RedactModelAuto: true, RedactModelName: pii.AstrLinkGuard}); err != nil {+ t.Fatal(err)+ }+ const name = "Fatima Rossi"+ m := &slowReader{fake: fake{installed: true}, name: name, read: map[string]bool{}}+ wasPicked, wasFetch, wasDisk := picked, fetch, onDisk+ picked = func(settings.Settings) pii.Model { return m }+ fetch = func(pii.Model, bool) {}+ onDisk = func() bool { return true }+ t.Cleanup(func() { picked, fetch, onDisk = wasPicked, wasFetch, wasDisk })++ msg := func(role, text string) string {+ b, _ := json.Marshal(map[string]string{"role": role, "content": text})+ return string(b)+ }+ csv := "1: id,name,company,city\n2: 1000," + name + ",Client 0 GmbH,Berlin\n3: 1001,Kenji Ito,Client 1 SA,Lyon"+ turn1 := []string{msg("system", "You are dsh."), msg("user", "read customers.csv"), msg("tool", csv)}+ turn2 := append(append([]string{}, turn1...), msg("assistant", "Read."), msg("user", "who is "+name+"?"))+ body := func(ms []string) []byte { return []byte(`{"model":"m","messages":[` + strings.Join(ms, ",") + `]}`) }+ messages := func(b []byte) []string {+ var q struct{ Messages []json.RawMessage }+ if err := json.Unmarshal(b, &q); err != nil {+ t.Fatalf("%v: %s", err, b)+ }+ out := make([]string, len(q.Messages))+ for i, r := range q.Messages {+ out[i] = string(r)+ }+ return out+ }+ route := WithRoute(context.Background(), "deepseek")+ first, _ := Masker{}.JSONHitsContext(route, body(turn1))+ if !strings.Contains(string(first), name) {+ t.Fatalf("turn 1: the model hadn't read the tool's output, the rules alone mask it: %s", first)+ }+ second, _ := Masker{}.JSONHitsContext(route, body(turn2))+ a, b := messages(first), messages(second)+ for i := range a {+ if a[i] != b[i] {+ t.Errorf("turn 2 rewrote message %d the vendor has:\n%s\nwas\n%s", i, b[i], a[i])+ }+ }+ if strings.Contains(b[len(b)-1], name) {+ t.Errorf("the new turn has the name the model found as written: %s", b[len(b)-1])+ }++ // another route was never sent the text: masked with what is found now+ other, _ := Masker{}.JSONHitsContext(WithRoute(context.Background(), "another"), body(turn1))+ if strings.Contains(string(other), name) {+ t.Errorf("another route got the name as written: %s", other)+ }+ // nor is one without a route (a search, an embedding)+ if none, _ := (Masker{}).JSONHitsContext(context.Background(), body(turn1)); strings.Contains(string(none), name) {+ t.Errorf("no route got the name as written: %s", none)+ }+}diff --git a/internal/redact/json.go b/internal/redact/json.goindex f7726f069..99291c176 100644--- a/internal/redact/json.go+++ b/internal/redact/json.go@@ -462,7 +462,8 @@ func MaskJSON(body []byte, o Options) ([]byte, int) {// number or an address the vendor wrote of its own can be one// masked in another conversation (13800138000 is in many), and// masked, its text would no longer match its signature- t, n := apply(t, sentKnownSpans(t, Options{Secrets: o.Secrets}), o.put(), o)+ ko := Options{Secrets: o.Secrets, Route: o.Route}+ t, n := apply(t, sentSpans(sentKnown, t, ko, func() []span { return knownSpans(t, ko) }), o.put(), o)total += nreturn t})diff --git a/internal/redact/known.go b/internal/redact/known.goindex f57f3f0ab..6735bd803 100644--- a/internal/redact/known.go+++ b/internal/redact/known.go@@ -262,9 +262,11 @@ func standsAlone(kind, s string, a, b int) bool {return !(is(before, alnum) && is(s[a], alnum)) && !(is(after, alnum) && is(s[b-1], alnum))}-// A text sent before goes again as it went: the known values found in it-// the first time it was masked are the ones masked in it from then on,-// and a value that became known since is masked in new text only.+// A text sent before goes again as it went: the model's finds in it and+// the known values found in it the first time it was masked for a route+// are the ones masked in it there from then on. A value that became known+// since is masked in new text only, and so is one the model found in the+// text only since.//// An agent sends its whole conversation on every turn, and a vendor// caches it by its bytes up to a mark (Anthropic's cache_control, the@@ -274,28 +276,64 @@ func standsAlone(kind, s string, a, b int) bool {// the prefix changed at its first block, and a 400K-token conversation was// written to the cache whole instead of read (audie on Discord: cache_read// 0 and cache_write 412,081 to 426,782 on four turns, ten seconds apart).-// Masking it there keeps nothing from the vendor, which was sent that text-// as written already.+// The local model did the same: a tool's output it hadn't read in the+// request's wait (masking's defaultWait, pii.Partial) went with the rules'+// masking alone, and the next turn, the model having read it, masked a+// name in it, so everything from that message on was a new prompt to the+// vendor (vvrfxyz on X: dsh's cache hits fell with masking on; replayed+// on a Linux CPU, 12% of the history resent was rewritten).//-// What is remembered is a hash of the text and of what o covers, and the-// places of the known values in it; nothing of a value. A text no longer-// remembered (sentEntries, or magpie started again) is masked with what is-// known then.-const sentEntries = 1 << 16+// Masking it there keeps nothing from the vendor: the text went to it as+// written. That holds only where it went, so what is remembered is kept+// by Route, the providers the request could reach: on another route (the+// user picked another model, a provider of its own) the text is masked+// with what is known and found now. Within a route of several providers+// (fallbacks, a routing group's members) the text goes to a member that+// may not have had it, in the form any of them could have been sent it+// the first time. A request with no route (a search's query, an+// embedding's input: nothing a vendor caches) keeps the known values it+// first went with, and has the model's finds of now.+//+// What is remembered is a hash of the route, the text and of what o+// covers, and the places masked in it; nothing of a value. A text no+// longer remembered (sentEntries, or magpie started again) is masked with+// what is known and found then; a change to what o covers (a kind turned+// on, the model's threshold, the model itself) is another text.+const sentEntries = 1 << 17 // a text's model finds and its known values are two++// What sentSpans remembers of a text: the model's finds in it, or the+// known values in it.+const (+ sentModel byte = iota + 1+ sentKnown+)-var sentKnown struct {+var sentMemo struct {sync.Mutexcur, old map[[32]byte][]span}-// sentKnownSpans is knownSpans for text going to a vendor: the same as the-// first time s was masked under what o covers.-func sentKnownSpans(s string, o Options) []span {- if !o.Secrets && !o.Personal || len(s) < minKnown {- return nil+// sentSpans is find()'s spans (modelSpans or knownSpans, as what says) for+// text going to a vendor: the same as the first time s was masked on+// o.Route under what o covers.+func sentSpans(what byte, s string, o Options, find func() []span) []span {+ if !o.Secrets && !o.Personal || what == sentKnown && len(s) < minKnown {+ if what == sentKnown {+ return nil+ }+ return find()+ }+ if what == sentModel && (o.Model == nil || o.Route == "") {+ // no model: nothing to remember. No route (a search's query, an+ // embedding's input, nothing a vendor caches): what the model+ // finds now, wherever it goes+ return find()}h := sha256.New()- fmt.Fprintf(h, "%t\x00%t\x00", o.Secrets, o.Personal)+ fmt.Fprintf(h, "%d\x00%q\x00%t\x00%t\x00", what, o.Route, o.Secrets, o.Personal)+ if what == sentModel {+ fmt.Fprintf(h, "%t\x00%t\x00%g\x00", o.Model != nil, o.NamesByModel, o.MinScore)+ }kinds := make([]string, 0, len(o.Kinds))for k, on := range o.Kinds {kinds = append(kinds, fmt.Sprintf("%s=%t", k, on))@@ -305,36 +343,36 @@ func sentKnownSpans(s string, o Options) []span {h.Write([]byte(s))var k [32]byteh.Sum(k[:0])- sentKnown.Lock()- sp, ok := sentKnown.cur[k]+ sentMemo.Lock()+ sp, ok := sentMemo.cur[k]if !ok {- if sp, ok = sentKnown.old[k]; ok {- sentKnownAdd(k, sp) // still in use: kept past the next turnover+ if sp, ok = sentMemo.old[k]; ok {+ sentAdd(k, sp) // still in use: kept past the next turnover}}- sentKnown.Unlock()+ sentMemo.Unlock()if ok {return slices.Clone(sp)}- sp = knownSpans(s, o)- sentKnown.Lock()- sentKnownAdd(k, slices.Clone(sp))- sentKnown.Unlock()+ sp = find()+ sentMemo.Lock()+ sentAdd(k, slices.Clone(sp))+ sentMemo.Unlock()return sp}-// sentKnownAdd is called with sentKnown held. Two generations, as-// scrubMemo keeps: when the newer is full it becomes the older.-func sentKnownAdd(k [32]byte, sp []span) {- if sentKnown.cur == nil || len(sentKnown.cur) >= sentEntries {- sentKnown.old, sentKnown.cur = sentKnown.cur, make(map[[32]byte][]span)+// sentAdd is called with sentMemo held. Two generations, as scrubMemo+// keeps: when the newer is full it becomes the older.+func sentAdd(k [32]byte, sp []span) {+ if sentMemo.cur == nil || len(sentMemo.cur) >= sentEntries {+ sentMemo.old, sentMemo.cur = sentMemo.cur, make(map[[32]byte][]span)}- sentKnown.cur[k] = sp+ sentMemo.cur[k] = sp}// resetSent forgets the texts sent (a test starts from nothing).func resetSent() {- sentKnown.Lock()- defer sentKnown.Unlock()- sentKnown.cur, sentKnown.old = nil, nil+ sentMemo.Lock()+ defer sentMemo.Unlock()+ sentMemo.cur, sentMemo.old = nil, nil}diff --git a/internal/redact/redact.go b/internal/redact/redact.goindex 3ec4f5c60..82bd8e0ca 100644--- a/internal/redact/redact.go+++ b/internal/redact/redact.go@@ -55,6 +55,11 @@ type Options struct {Kinds map[string]bool// Model, where set, finds more in the texts to mask (model.go)Model Model+ // Route names where a request masked for a vendor may go (the gateway+ // sets it: the providers a model, its fallbacks or a routing group's+ // members are served by). A text sent on it before goes on it again+ // as it went (sentSpans); on another route it is masked afresh.+ Route string// MinScore is the score the user has Model's finds need (Settings →// Privacy's slider), which Model's own finds are held to already. A// value only the model found, masked before at a lower score, isn't@@ -83,7 +88,8 @@ type Options struct {// found are the spans Model found, by text, for one request's textsfound map[string][]Found// sent is masking for a vendor (Mask, MaskJSON): a text masked- // before has the known values it had then (sentKnownSpans)+ // before on Route has the model's finds and the known values it had+ // then (sentSpans)sent bool}@@ -1030,10 +1036,15 @@ func mask(raw string, o Options, put func(kind, v string) string, escaped bool)}// after the rules', so where a rule finds the same value it keeps the// kind it has always had- found = append(found, modelSpans(raw, o)...) // the model was asked about rawif o.sent {- found = append(found, sentKnownSpans(s, o)...)+ // the model was asked about raw+ now := modelSpans(raw, o)+ kept := sentSpans(sentModel, raw, o, func() []span { return now })+ learnLate(raw, now, kept, o, escaped)+ found = append(found, kept...)+ found = append(found, sentSpans(sentKnown, s, o, func() []span { return knownSpans(s, o) })...)} else {+ found = append(found, modelSpans(raw, o)...) // the model was asked about rawfound = append(found, knownSpans(s, o)...)}if escaped {@@ -1046,6 +1057,33 @@ func mask(raw string, o Options, put func(kind, v string) string, escaped bool)return apply(raw, found, put, o)}+// learnLate makes known what the model finds in raw now that it didn't+// the first time raw was sent on o.Route (now, beside kept): raw goes as+// it went, but a value in it the model has read since is masked in new+// text, as it would be had raw been masked with it (known.go). Nothing+// is told (o.Seen): it isn't masked here.+func learnLate(raw string, now, kept []span, o Options, escaped bool) {+ var late []span+ for _, f := range now {+ if !slices.ContainsFunc(kept, func(k span) bool { return k.start == f.start && k.end == f.end && k.kind == f.kind }) {+ late = append(late, f)+ }+ }+ if len(late) == 0 {+ return+ }+ if escaped {+ late = outsideEscapes(raw, late)+ }+ noteScores(raw, late)+ o.Seen = nil+ put := o.put()+ if escaped {+ put = unescapedPut(put)+ }+ apply(raw, late, put, o)+}+// unescapedView is s, JSON text, as long as s and read as the vendor reads// it once unescaped, as far as the finders tell: an escape that stands for// a newline, a tab or another control character has its letter read as