Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
masking: the local model is on by default; the rules mask alone until it is downloaded
yetoneae0327945803
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 25d848913..d3da50429 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -139,7 +139,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`). 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): 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. 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). Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `[email protected]`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`[email protected]`, `[email protected]`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). `[email protected]` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.- - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name; 和 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. 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`), 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): 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`). 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, 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 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, so a short request goes before the rest of a long one. 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). A model that is on and can't answer (not on disk, didn't start, hung, held back) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).+ - 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`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with 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. 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`), 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): 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`). 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, 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 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, so a short request goes before the rest of a long one. 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 can't answer (didn't start, hung, held back) 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.- 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.- The user's own masked words (`redactWords`, `Options.Words`; Settings → Privacy's *Masked words*) go as `{{TERM_…}}` whatever else is on, and come back as written. They match as written, inside longer words too, unless the user asks: *Masked words in any case* (`redactWordsAnyCase`, `WordsAnyCase`) matches in any capitals by Unicode simple folding, and *Whole words only* (`redactWordsWhole`, `WordsWhole`; acmilan_ on Discord) skips a match with a letter, digit or `_` beside it, and for a number a `.` and digit beside it, so `ABC` masks `name='ABC'` but not `XABCD`, and `123456` not `91234567`, `0.123456` or `123456.78` (`wholeWord` in [`redact.go`](../../internal/redact/redact.go)). Chinese and Japanese letters count as no letter there (`wordRune`): a word of theirs is found inside their text, and `ABC` in 用ABC做 is whole. Both are off by default; a page from before them that saves without the field keeps the user's choice (`api.go`). `TestWordsWhole`, `TestWordsWholeJSON`, `TestCountTokensRedacted`. A word that is a date (`1990-05-12`, `1990/5/12`, `1990年5月12日`, `May 12, 1990`; eight digits alone are not one) matches that calendar date in every common form instead (`dateSpans` in [`dateword.go`](../../internal/redact/dateword.go); JackyCcao on X, who masks their own birthday with birthdays off): `-` `/` `.` `、` or a space between, 年月日 or 년월일, with or without leading zeros, `19900512`, the month's English name, and day-first or month-first only where the day is over 12 or equals the month (`13/05/1990`, never `05/12/1990`, which is December 5th too; such a word matches only as written). A match never has a digit, or a dot and a digit, beside it, whatever *Whole words only* says, so `1990.5.12.1` and `11990-05-12` are not that date. `TestDateWordEveryForm`, `TestDateWordNotAnotherDate`, `TestDateWordDayMonthOrder`.- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`. Insights › Masking and Settings' *Try it* mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (`maskMatches` in `plugins/redact/page.js`; #3599, masking-records and mask-actions GUI tests).diff --git a/internal/gui/api.go b/internal/gui/api.goindex e4c552e6a..5d6ace58f 100644--- a/internal/gui/api.go+++ b/internal/gui/api.go@@ -1332,6 +1332,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {in.RedactModel = cur.RedactModel // set on its own (privacy-model)in.RedactModelName = cur.RedactModelName // set on its own (privacy-model)in.RedactModelScore = cur.RedactModelScore // set on its own (privacy-model)+ in.RedactModelOff = cur.RedactModelOff // set on its own (privacy-model)+ in.RedactModelAuto = cur.RedactModelAuto // set on its own (masking)in.RedactActions = cur.RedactActions // set on their own (redact-actions below)in.RedactAllow = cur.RedactAllow // set on its own (redact-allow below)in.DisabledModels = cur.DisabledModels // set on their own (disabled-models below, #1867)diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.jsindex 4a225c91e..4b8492b88 100644--- a/internal/gui/assets/app.js+++ b/internal/gui/assets/app.js@@ -22010,7 +22010,7 @@ function pmSub(m) {if (d) return t("Downloading the model: {done} of {total}", { done: fmtBytes(d.done), total: fmtBytes(d.total) });const bad = (m.models || []).find((x) => x.error) || (m.error ? m : null);if (bad) return t("The download stopped: {error}", { error: bad.error });- if (m.on && m.failed) return t("The model didn't answer, so requests are held back: {error}", { error: m.failed });+ if (m.on && m.failed) return m.chosen ? t("The model didn't answer, so requests are held back: {error}", { error: m.failed }) : t("The model didn't answer, so the rules mask requests alone: {error}", { error: m.failed });if (m.on && m.running) {if (m.gpu) return t("On, on the GPU ({device})", { device: m.device });return m.gpuError ? t("On, on the CPU: the GPU failed ({error})", { error: m.gpuError }) : t("On, on the CPU");diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 75c1029e8..3e1ffdbff 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -1233,6 +1233,7 @@ const I18N = {"Downloading the model: {done} of {total}": "正在下载模型:{done} / {total}","The download stopped: {error}": "下载已停止:{error}","The model didn't answer, so requests are held back: {error}": "模型没有响应,请求已暂缓发送:{error}",+ "The model didn't answer, so the rules mask requests alone: {error}": "模型没有响应,请求暂时只按规则脱敏:{error}","On, on the GPU ({device})": "已开启,运行在 GPU({device})","On, on the CPU: the GPU failed ({error})": "已开启,运行在 CPU:GPU 出错({error})","On, on the CPU": "已开启,运行在 CPU",@@ -5276,6 +5277,7 @@ const I18N = {"Downloading the model: {done} of {total}": "正在下載模型:{done} / {total}","The download stopped: {error}": "下載已停止:{error}","The model didn't answer, so requests are held back: {error}": "模型沒有回應,請求已暫緩送出:{error}",+ "The model didn't answer, so the rules mask requests alone: {error}": "模型沒有回應,請求暫時只按規則脫敏:{error}","On, on the GPU ({device})": "已開啟,執行於 GPU({device})","On, on the CPU: the GPU failed ({error})": "已開啟,執行於 CPU:GPU 出錯({error})","On, on the CPU": "已開啟,執行於 CPU",@@ -9289,6 +9291,7 @@ const I18N = {"Downloading the model: {done} of {total}": "モデルをダウンロード中:{done} / {total}","The download stopped: {error}": "ダウンロードが止まりました:{error}","The model didn't answer, so requests are held back: {error}": "モデルが応答しないため、リクエストを保留しています:{error}",+ "The model didn't answer, so the rules mask requests alone: {error}": "モデルが応答しないため、リクエストはルールだけでマスクしています:{error}","On, on the GPU ({device})": "オン、GPU で実行中({device})","On, on the CPU: the GPU failed ({error})": "オン、CPU で実行中:GPU が失敗しました({error})","On, on the CPU": "オン、CPU で実行中",@@ -13332,6 +13335,7 @@ const I18N = {"Downloading the model: {done} of {total}": "Modell wird geladen: {done} von {total}","The download stopped: {error}": "Download angehalten: {error}","The model didn't answer, so requests are held back: {error}": "Das Modell antwortet nicht, Anfragen werden zurückgehalten: {error}",+ "The model didn't answer, so the rules mask requests alone: {error}": "Das Modell antwortet nicht, Anfragen werden nur nach den Regeln maskiert: {error}","On, on the GPU ({device})": "An, auf der GPU ({device})","On, on the CPU: the GPU failed ({error})": "An, auf der CPU: die GPU ist ausgefallen ({error})","On, on the CPU": "An, auf der CPU",diff --git a/internal/gui/privacymodel.go b/internal/gui/privacymodel.goindex 0ba997846..8dacd2af6 100644--- a/internal/gui/privacymodel.go+++ b/internal/gui/privacymodel.go@@ -5,17 +5,21 @@ import ("fmt""net/http"+ "github.com/yetone/magpie/internal/masking""github.com/yetone/magpie/internal/pii""github.com/yetone/magpie/internal/settings")// privacyModelJSON is Settings → Privacy's local masking model: whether it-// is on, the model masking uses (or would, turned on) with its own status+// is on (masking.ModelWanted: the user's, or the default), the model masking uses (or would, turned on) with its own status// (downloaded, downloading, where it runs) and threshold (the one the// user set, else its default), and every model there is to pick, with// theirs.type privacyModelJSON struct {On bool `json:"on"`+ // Chosen says the user turned it on, not the default: only then is+ // a request held back for it (masking.ModelOn)+ Chosen bool `json:"chosen,omitempty"`pii.StatusMinScore float64 `json:"minScore"`DefaultScore float64 `json:"defaultScore"`@@ -27,8 +31,9 @@ var modelOf, models = pii.Of, pii.Modelsfunc privacyModelState() privacyModelJSON {st := settings.Load()- m := modelOf(pii.Choose(st.RedactModelName, st.RedactModel))- out := privacyModelJSON{On: st.RedactModel, Status: m.Now(), MinScore: pii.Threshold(st.RedactModelScore, m), DefaultScore: m.MinScore()}+ on := masking.ModelWanted(st)+ m := modelOf(pii.Choose(st.RedactModelName, on))+ out := privacyModelJSON{On: on, Chosen: st.RedactModel, Status: m.Now(), MinScore: pii.Threshold(st.RedactModelScore, m), DefaultScore: m.MinScore()}for _, m := range models() {out.Models = append(out.Models, m.Now())}@@ -64,14 +69,15 @@ func privacyModelRoutes(mux *http.ServeMux) {return}st := settings.Load()- was := pii.Choose(st.RedactModelName, st.RedactModel)+ on := masking.ModelWanted(st)+ was := pii.Choose(st.RedactModelName, on)var err errorswitch in.Do {case "pick":switch {case in.Model == "":err = fmt.Errorf("pick needs a model")- case st.RedactModel:+ case on:err = turnOn(in.Model, was)default:err = settings.SetRedactModelName(in.Model)@@ -104,6 +110,11 @@ func privacyModelRoutes(mux *http.ServeMux) {for _, m := range models() {m.Cancel()}+ // the download on by default, cancelled, is the model+ // turned off: it would start again on the next request+ if on && !st.RedactModel && !modelOf(was).Installed() {+ err = settings.SetRedactModel(false)+ }case "remove":if err = settings.SetRedactModel(false); err == nil {for _, m := range models() {diff --git a/internal/gui/privacymodel_test.go b/internal/gui/privacymodel_test.goindex 041f884a1..937cbe025 100644--- a/internal/gui/privacymodel_test.go+++ b/internal/gui/privacymodel_test.go@@ -33,7 +33,8 @@ func TestPrivacyModelOnlyOnOnceDownloaded(t *testing.T) {if rec := do("GET", "/api/privacy-model", ""); rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &st) != nil {t.Fatalf("state: %d %s", rec.Code, rec.Body)}- if st.On || st.Installed || st.Size == 0 {+ // on by default, not by the user, and not downloaded yet+ if !st.On || st.Chosen || st.Installed || st.Size == 0 {t.Fatalf("state %+v", st)}if !pii.Supported() {@@ -65,11 +66,31 @@ func TestPrivacyModelOnlyOnOnceDownloaded(t *testing.T) {if rec := do("POST", "/api/privacy-model", `{"do":"off"}`); rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &st) != nil || st.On {t.Fatalf("off: %d %s", rec.Code, rec.Body)}- if settings.Load().RedactModel {+ if st := settings.Load(); st.RedactModel || !st.RedactModelOff {t.Fatal("off not saved")}}+// The model on by default whose download is cancelled is turned off, the+// user's own off: the next request would start the download again.+func TestPrivacyModelCancelledDefaultIsOff(t *testing.T) {+ h := t.TempDir()+ t.Setenv("HOME", h)+ t.Setenv("USERPROFILE", h)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))+ srv := Handler(webHost{func() {}}, nil)+ rec := httptest.NewRecorder()+ srv.ServeHTTP(rec, httptest.NewRequest("POST", "/api/privacy-model", strings.NewReader(`{"do":"cancel"}`)))+ var st privacyModelJSON+ if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &st) != nil || st.On {+ t.Fatalf("cancel: %d %s", rec.Code, rec.Body)+ }+ if !settings.Load().RedactModelOff {+ t.Fatal("cancelled default not saved off")+ }+}+// fakeModel is a pii.Model that is on disk, or downloads at once, and// says what was done to it.type fakeModel struct {@@ -137,9 +158,13 @@ func TestPrivacyModelPick(t *testing.T) {}return st}- if st := do(""); st.On || st.Model != pii.AstrLinkGuard || len(st.Models) != 2 || st.Models[0].Model != pii.PrivacyFilter {+ if st := do(""); !st.On || st.Chosen || st.Model != pii.AstrLinkGuard || len(st.Models) != 2 || st.Models[0].Model != pii.PrivacyFilter {t.Fatalf("a new user's state: %+v", st)}+ if st := do(`{"do":"off"}`); st.On || !settings.Load().RedactModelOff {+ t.Fatalf("turned off: %+v", st)+ }+ did = nilif st := do(`{"do":"pick","model":"privacy-filter"}`); st.On || st.Model != pii.PrivacyFilter || len(did) != 0 {t.Fatalf("picked while off: %+v, %v", st, did)}diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.goindex 3caf872e2..c00ab0aaa 100644--- a/internal/gui/settings_keep_test.go+++ b/internal/gui/settings_keep_test.go@@ -184,6 +184,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {RedactModelName: "astrlink-guard",RedactModelScore: map[string]float64{"astrlink-guard": 0.9},}+ was.RedactModelOff, was.RedactModelAuto = true, truewas.DesktopSubagentEffort = "high"was.CodexAsyncCompact, was.CodexAsyncCompactPercent = true, 70was.ClaudeRunsMost = 3diff --git a/internal/masking/masking.go b/internal/masking/masking.goindex 92ebc23b9..5ff62562a 100644--- a/internal/masking/masking.go+++ b/internal/masking/masking.go@@ -8,7 +8,9 @@ import ("context""fmt""net/http"+ "sync""sync/atomic"+ "testing""time""github.com/yetone/magpie/internal/gwmw"@@ -32,14 +34,78 @@ 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}- if st.RedactModel {- m := picked(st)- o.MinScore = pii.Threshold(st.RedactModelScore, m)- o.Model = model(ctx, m, o.MinScore)+ 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)+ if m := picked(st); m.Installed() {+ o.MinScore = pii.Threshold(st.RedactModelScore, m)+ o.Model = model(ctx, m, o.MinScore, st.RedactModel)+ o.NamesByModel = m.ID() == pii.AstrLinkGuard+ } else {+ fetch(m, st.RedactModel)+ }}return o}+// ModelWanted says st has masking ask the local model: the user turned it+// on, or left it as it is, on by default. One who had a model downloaded,+// or picked, with it off before it was on by default had turned it off.+func ModelWanted(st settings.Settings) bool {+ switch {+ case st.RedactModel:+ return true+ case st.RedactModelOff:+ return false+ case st.RedactModelAuto:+ return true+ }+ return st.RedactModelName == "" && !onDisk()+}++// onDisk says a local model is downloaded; a var for tests.+var onDisk = func() bool {+ for _, m := range pii.Models() {+ if m.Installed() {+ return true+ }+ }+ return false+}++// fetched is when fetch last started each model's download, by id, so a+// failed one is tried again an hour later rather than on every request.+var fetched = struct {+ sync.Mutex+ at map[string]time.Time+}{at: map[string]time.Time{}}++// fetch downloads m, the model masking would ask but isn't on disk, and+// warms it once it is; the model on by default (on is false: the user+// didn't turn it on) is saved as the default's (UseDefaultRedactModel),+// unless the user picked or turned it off in between. Never in a test,+// which stays off the network (a test swaps it). A var for tests.+var fetch = func(m pii.Model, on bool) {+ if !m.Supported() || testing.Testing() {+ return+ }+ fetched.Lock()+ t, ok := fetched.at[m.ID()]+ if ok && time.Since(t) < time.Hour {+ fetched.Unlock()+ return+ }+ fetched.at[m.ID()] = time.Now()+ fetched.Unlock()+ m.Download(func() {+ if on {+ m.Warm()+ } else if ok, err := settings.UseDefaultRedactModel(m.ID()); ok && err == nil {+ m.Warm()+ }+ })+}+// picked is the local model st has masking use; a var for tests. One// that is Privacy Filter only because no model was picked (pii.Choose)// starts AstrLink Guard's download, the default, and is moved onto it@@ -74,14 +140,17 @@ func toGuard() {// model is the local model m (internal/pii) as redact's Model, waited for// until ctx ends, keeping what it is at least min sure of. One that can't-// answer, or isn't waited for any longer, panics, and the request is held-// back (gwmw.Safely) rather than sent with only the rules' masking: the-// user asked for the model's.-func model(ctx context.Context, m pii.Model, min float64) redact.Model {+// answer, or isn't waited for any longer, panics where the user turned it+// on (strict), and the request is held back (gwmw.Safely) rather than+// sent with only the rules' masking: the user asked for the model's. On+// by default, it finds nothing then, and the rules mask alone.+func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Model {return func(texts []string) [][]redact.Found {got, err := m.Find(ctx, texts)- if err != nil {+ if err != nil && strict {panic(err)+ } else if err != nil {+ return make([][]redact.Found, len(texts))}out := make([][]redact.Found, len(got))for i, fs := range got {@@ -95,7 +164,9 @@ func model(ctx context.Context, m pii.Model, min float64) redact.Model {}}-// ModelOn says Settings → Privacy's local model masks requests.+// ModelOn says Settings → Privacy's local model masks requests, as the+// user turned it on: only then is a request held back for it (model's+// strict).func ModelOn() bool { return settings.Shared().RedactModel }// ModelBusy says what the local model is doing that a request may waitdiff --git a/internal/masking/masking_test.go b/internal/masking/masking_test.goindex 81de9bb66..d5bd78dd9 100644--- a/internal/masking/masking_test.go+++ b/internal/masking/masking_test.go@@ -2,7 +2,10 @@ package maskingimport ("context"+ "errors"+ "path/filepath""slices"+ "strings""testing""github.com/yetone/magpie/internal/pii"@@ -47,7 +50,7 @@ func TestModelThreshold(t *testing.T) {} {var m pii.Model = scored{}var got []int- for _, f := range model(context.Background(), m, pii.Threshold(c.set, m))([]string{"a b c"})[0] {+ for _, f := range model(context.Background(), m, pii.Threshold(c.set, m), true)([]string{"a b c"})[0] {got = append(got, f.Start)}if !slices.Equal(got, c.want) {@@ -55,3 +58,95 @@ func TestModelThreshold(t *testing.T) {}}}++// The local model is on by default: for a user who neither turned it on+// nor off, and never had one downloaded or picked, which a user did who+// turned it off before it was on by default.+func TestModelOnByDefault(t *testing.T) {+ disk := false+ was := onDisk+ onDisk = func() bool { return disk }+ t.Cleanup(func() { onDisk = was })+ for _, c := range []struct {+ st settings.Settings+ disk bool+ want bool+ }{+ {settings.Settings{}, false, true},+ {settings.Settings{}, true, false},+ {settings.Settings{RedactModelName: pii.AstrLinkGuard}, false, false},+ {settings.Settings{RedactModelOff: true}, false, false},+ {settings.Settings{RedactModelOff: true, RedactModelAuto: true}, true, false},+ {settings.Settings{RedactModelAuto: true, RedactModelName: pii.AstrLinkGuard}, true, true},+ {settings.Settings{RedactModel: true, RedactModelName: pii.PrivacyFilter}, true, true},+ } {+ disk = c.disk+ if got := ModelWanted(c.st); got != c.want {+ t.Errorf("on %v, off %v, auto %v, name %q, on disk %v: wanted %v, want %v", c.st.RedactModel, c.st.RedactModelOff, c.st.RedactModelAuto, c.st.RedactModelName, c.disk, got, c.want)+ }+ }+}++// fake is a model that is on disk or not, and fails or finds a name.+type fake struct {+ pii.Model+ installed, fails bool+}++func (fake) ID() string { return pii.AstrLinkGuard }+func (fake) MinScore() float64 { return 0.8 }+func (f fake) Installed() bool { return f.installed }+func (f fake) Find(_ context.Context, texts []string) ([][]redact.Found, error) {+ if f.fails {+ return nil, errors.New("pf-serve exited")+ }+ return [][]redact.Found{{{Start: 0, End: 6, Label: "private_person", Score: 0.9}}}, nil+}++// Until the model is on disk the rules mask alone and its download is+// started, the default's too: nothing is held back for it. On disk,+// AstrLink Guard finds Chinese names itself (NamesByModel).+func TestNoModelYetMasksByTheRules(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}); err != nil {+ t.Fatal(err)+ }+ m := fake{}+ var fetches []bool+ wasPicked, wasFetch, wasDisk := picked, fetch, onDisk+ picked = func(settings.Settings) pii.Model { return m }+ fetch = func(_ pii.Model, on bool) { fetches = append(fetches, on) }+ onDisk = func() bool { return m.installed }+ t.Cleanup(func() { picked, fetch, onDisk = wasPicked, wasFetch, wasDisk })+ o := options()+ if o.Model != nil || !slices.Equal(fetches, []bool{false}) {+ t.Fatalf("not on disk: model %v, fetches %v", o.Model != nil, fetches)+ }+ if out, n := redact.Mask("key sk-ant-api03-"+strings.Repeat("a", 40), o); n != 1 || strings.Contains(out, "aaaa") {+ t.Fatalf("the rules didn't mask: %q", out)+ }+ m.installed = true+ if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RedactModelAuto: true, RedactModelName: pii.AstrLinkGuard}); err != nil {+ t.Fatal(err)+ }+ if o := options(); o.Model == nil || !o.NamesByModel || len(fetches) != 1 {+ t.Fatalf("on disk: model %v, names by model %v, fetches %v", o.Model != nil, o.NamesByModel, fetches)+ }+}++// A model that fails holds the request back only where the user turned+// it on; on by default, it finds nothing and the rules mask alone.+func TestDefaultModelFailingIsTheRules(t *testing.T) {+ m := fake{installed: true, fails: true}+ if got := model(context.Background(), m, 0.8, false)([]string{"a", "b"}); len(got) != 2 || len(got[0])+len(got[1]) != 0 {+ t.Fatalf("default: %v", got)+ }+ defer func() {+ if recover() == nil {+ t.Fatal("turned on by the user, a failing model didn't hold the request back")+ }+ }()+ model(context.Background(), m, 0.8, true)([]string{"a"})+}diff --git a/internal/redact/model.go b/internal/redact/model.goindex 6cde647e7..adf1177f9 100644--- a/internal/redact/model.go+++ b/internal/redact/model.go@@ -50,7 +50,8 @@ func modelCat(kind string) string {// modelSpans are o.found's spans for s that o covers, trimmed of the// spaces the model takes in with a word (and a Chinese name of what it// ran on into, zhTrim), and with what it gets wrong often left out-// (modelTakes); and the Chinese names it missed (zhNameSpans).+// (modelTakes); and the Chinese names it missed (zhNameSpans: only+// nicknames where the model finds names itself, o.NamesByModel).func modelSpans(s string, o Options) []span {if o.Model == nil || !o.covers(catPersonal) && len(o.found[s]) == 0 {return nil@@ -93,7 +94,7 @@ func modelSpans(s string, o Options) []span {person = append(person, f)}}- out = append(out, zhNameSpans(s, person)...)+ out = append(out, zhNameSpans(s, person, o.NamesByModel)...)}return out}diff --git a/internal/redact/redact.go b/internal/redact/redact.goindex 710befcaa..8687c5e6a 100644--- a/internal/redact/redact.go+++ b/internal/redact/redact.go@@ -60,6 +60,10 @@ type Options struct {// value only the model found, masked before at a lower score, isn't// masked again as known under it (knownSpans).MinScore float64+ // NamesByModel says Model finds Chinese names itself (AstrLink+ // Guard): beside it only a nickname (小王, 老李) is found by the+ // words around it (zhNameSpans)+ NamesByModel bool// Shape sends a key as a made-up key of its form, not a placeholder// (shape.go)Shape booldiff --git a/internal/redact/zhname.go b/internal/redact/zhname.goindex c691d93a8..e71a522d9 100644--- a/internal/redact/zhname.go+++ b/internal/redact/zhname.go@@ -125,8 +125,10 @@ func zhFirsts() string {}// zhNameSpans are the Chinese names in s the model didn't find, as-// PERSON spans; person are those it did.-func zhNameSpans(s string, person []span) []span {+// PERSON spans; person are those it did. With nicks, only a nickname+// (小王, 老李): AstrLink Guard finds the rest itself, and the cues here+// took words for names it didn't (关键发现, 易触发; xuanwo on X).+func zhNameSpans(s string, person []span, nicks bool) []span {if !hasHan(s) {return nil}@@ -138,12 +140,15 @@ func zhNameSpans(s string, person []span) []span {i += ncontinue}+ i = b+ if nicks && !zhNick(s[a:b]) {+ continue+ }kind := ""if ok {kind = "PERSON"}cs = append(cs, span{a, b, kind, ByModel, 0})- i = b}// a name joined by 和, 与, 跟, 及 or 、 to one that is a name is one// too: 李娜和刘洋, where only 刘洋 has a word after it that says so@@ -174,6 +179,13 @@ func zhNameSpans(s string, person []span) []span {return out}+// zhNick says name is a nickname: 小 or 老 and a surname (小王, 老李).+func zhNick(name string) bool {+ r, n := utf8.DecodeRuneInString(name)+ r2, n2 := utf8.DecodeRuneInString(name[n:])+ return (r == '小' || r == '老') && isNick[r2] && n+n2 == len(name)+}+// joined says only 和, 与, 跟, 及 or 、 is between c and a name, one// that ends in ends or starts in starts.func joined(s string, c span, starts, ends map[int]bool) bool {diff --git a/internal/redact/zhname_test.go b/internal/redact/zhname_test.goindex c59528cbb..0a6a3db80 100644--- a/internal/redact/zhname_test.go+++ b/internal/redact/zhname_test.go@@ -171,3 +171,23 @@ func TestMaoliIsAMargin(t *testing.T) {t.Errorf("the model's name not masked: %q", out)}}++// Where the model finds Chinese names itself (AstrLink Guard,+// NamesByModel), only a nickname is found beside it: a surname with a+// cue around it is the model's to find, and the cues took words for+// names (关键发现, 易触发; xuanwo on X).+func TestChineseNamesByModelOnlyNicks(t *testing.T) {+ f := &fakeModel{values: map[string]string{"龚秋实": "private_person"}}+ o := Options{Personal: true, Model: f.find, NamesByModel: true}+ for _, c := range []struct{ s, masked, kept string }{+ {"小邵说他明天到", "小邵", "说他明天到"},+ {"客户龚秋实和小邵反馈导出失败", "龚秋实和小邵", "反馈导出失败"},+ {"客户钟离夏反馈导出失败", "", "钟离夏"},+ {"## 关键发现", "", "关键发现"},+ } {+ out, _ := Mask(c.s, o)+ if strings.Contains(out, c.masked) && c.masked != "" || !strings.Contains(out, c.kept) {+ t.Errorf("%q: %q", c.s, out)+ }+ }+}diff --git a/internal/settings/redact_model_test.go b/internal/settings/redact_model_test.goindex 3fc476603..c099bca42 100644--- a/internal/settings/redact_model_test.go+++ b/internal/settings/redact_model_test.go@@ -41,3 +41,39 @@ func TestRedactModelIsThisComputers(t *testing.T) {t.Fatalf("off: %v %q", st.RedactModel, st.RedactModelName)}}++// Off is the user's own, which the model on by default never turns on+// again; the default's download, done, is saved as the default's only+// where the user neither picked a model nor turned it off meanwhile.+func TestRedactModelOffIsTheUsers(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ if ok, err := UseDefaultRedactModel("astrlink-guard"); !ok || err != nil {+ t.Fatalf("default not saved: %v %v", ok, err)+ }+ if st := Load(); st.RedactModel || !st.RedactModelAuto || st.RedactModelName != "astrlink-guard" {+ t.Fatalf("default: %+v", st)+ }+ if err := SetRedactModel(false); err != nil {+ t.Fatal(err)+ }+ if st := Load(); st.RedactModel || !st.RedactModelOff {+ t.Fatalf("off: %v %v", st.RedactModel, st.RedactModelOff)+ }+ if ok, _ := UseDefaultRedactModel("astrlink-guard"); ok {+ t.Fatal("the default turned on what the user turned off")+ }+ if err := UseRedactModel("privacy-filter"); err != nil {+ t.Fatal(err)+ }+ if st := Load(); !st.RedactModel || st.RedactModelOff {+ t.Fatalf("on: %v %v", st.RedactModel, st.RedactModelOff)+ }+ if ok, _ := UseDefaultRedactModel("astrlink-guard"); ok || Load().RedactModelName != "privacy-filter" {+ t.Fatal("the default changed the user's pick")+ }+ from := Settings{RedactModelOff: true, RedactModelAuto: true}+ from.KeepOwn(Settings{})+ if from.RedactModelOff || from.RedactModelAuto {+ t.Fatal("a sync turned the model off, or on by default")+ }+}diff --git a/internal/settings/settings.go b/internal/settings/settings.goindex 93d5c316f..fdd3a59ea 100644--- a/internal/settings/settings.go+++ b/internal/settings/settings.go@@ -114,12 +114,20 @@ type Settings struct {// set, by its id: masking drops what the model is less sure of (an// AstrLink Guard user on X found 0.85 to 0.95 right for it). A model// not in it has its own default (pii.Model.MinScore); this- // computer's too.+ // computer's too. RedactModelOff is the user turning the model off+ // (Settings → Privacy's Off, a download cancelled, the model deleted):+ // since 2026-10-28 it is on by default (masking.ModelWanted), and+ // RedactModel says the user turned it on. RedactModelAuto says the+ // default downloaded AstrLink Guard: a user who had a model on disk+ // with RedactModel off before then had turned it off, and this one+ // hasn't.Redact bool `json:"redact,omitempty"`RedactModelScore map[string]float64 `json:"redactModelScore,omitempty"`RedactShape bool `json:"redactShape,omitempty"`RedactModel bool `json:"redactModel,omitempty"`RedactModelName string `json:"redactModelName,omitempty"`+ RedactModelOff bool `json:"redactModelOff,omitempty"`+ RedactModelAuto bool `json:"redactModelAuto,omitempty"`RedactPersonal bool `json:"redactPersonal,omitempty"`RedactKinds map[string]bool `json:"redactKinds,omitempty"`RedactWords []string `json:"redactWords,omitempty"`@@ -1130,6 +1138,7 @@ func (s *Settings) KeepOwn(cur Settings) {s.FetchPrivate = cur.FetchPrivates.SessionTerminal = cur.SessionTerminals.RedactModel, s.RedactModelName, s.RedactModelScore = cur.RedactModel, cur.RedactModelName, cur.RedactModelScore+ s.RedactModelOff, s.RedactModelAuto = cur.RedactModelOff, cur.RedactModelAutos.ClaudeRunsMost = cur.ClaudeRunsMosts.RequestArchiveLocal, s.RequestArchiveLocalMB = cur.RequestArchiveLocal, cur.RequestArchiveLocalMB}@@ -1459,14 +1468,28 @@ func EditUsageAliases(edit func(map[string]string) (map[string]string, error)) e}// SetRedactModel turns the local masking model on or off, on its own, as-// Settings → Privacy does once the model is downloaded.+// Settings → Privacy does once the model is downloaded; off is the+// user's own (RedactModelOff), which the default never turns on again.func SetRedactModel(on bool) error {defer lockFile()()s := load()- s.RedactModel = on+ s.RedactModel, s.RedactModelOff = on, !onreturn save(s, false)}+// UseDefaultRedactModel saves name as the model on by default once it is+// downloaded (RedactModelAuto), unless the user picked one or turned it+// off in between: it says whether it did.+func UseDefaultRedactModel(name string) (bool, error) {+ defer lockFile()()+ s := load()+ if s.RedactModelName != "" || s.RedactModelOff || s.RedactModel {+ return false, nil+ }+ s.RedactModelName, s.RedactModelAuto = name, true+ return true, save(s, false)+}+// SetRedactModelName keeps the local model the user picked while it is// off, for turning it on.func SetRedactModelName(name string) error {@@ -1502,7 +1525,7 @@ func SetRedactModelScore(id string, score float64) error {func UseRedactModel(name string) error {defer lockFile()()s := load()- s.RedactModel, s.RedactModelName = true, name+ s.RedactModel, s.RedactModelName, s.RedactModelOff = true, name, falsereturn save(s, false)}diff --git a/site/public/docs/ja/masking.html b/site/public/docs/ja/masking.htmlindex 816fe6e81..f9d96d4e0 100644--- a/site/public/docs/ja/masking.html+++ b/site/public/docs/ja/masking.html@@ -113,7 +113,7 @@<tr><td><span class="ui">シークレットをマスク</span></td><td>秘密鍵のブロック(<code>-----BEGIN … PRIVATE KEY-----</code>)。形で見分ける API キー:<code>sk-…</code>(OpenAI、Anthropic、OpenRouter)、<code>ghp_</code>/<code>github_pat_</code>、<code>glpat-</code>、<code>AIza…</code>、<code>xox…-</code>、<code>sk_live_</code>、<code>AKIA</code>/<code>ASIA</code>、<code>hf_</code>、<code>gsk_</code>、<code>xai-</code>、<code>npm_</code>、<code>pypi-</code>、<code>dop_v1_</code>、<code>SG.</code>、それに <code>oc_sk_…</code> のような中継サービスのキー。JWT。<code>user:password@host</code> のパスワード。<code>.env</code> や設定ファイルでシークレットの名前が付いたフィールドの値:<code>DB_PASSWORD=…</code>、<code>api_key: …</code>、<code>client_secret</code>、<code>token</code>、<code>credential</code>。それと自分の <span class="ui">マスクルール</span>。</td></tr><tr><td><span class="ui">個人情報をマスク</span></td><td>メールアドレス、中国本土の携帯番号(11 桁の ID は別:<code>order_id</code> の値や 订单号 の後ろのものはそのまま)、チェックサムの合う中国の身分証番号と銀行カード番号。既定でオンのもの:米国の社会保障番号、パスポート番号(<em>passport</em>、护照、パスポートの後)、IBAN、誕生日(<em>birthday</em>、<em>DOB</em>、生日の近くにある、一年以上前の日付。今日の日付はそのまま)、MAC アドレス、シリアル番号(<em>S/N</em> の後)。エージェントがほぼ毎回送るので、自分でオンにするまでオフのもの:ホームフォルダのユーザー名(毎回同じ仮の名前で送るので、モデルにはプレースホルダーではなく普通のフォルダに見えます)、ユーザー名とコンピュータ名(<code>user@host</code>)、パブリック IP アドレス、クラウドストレージのバケット。</td></tr><tr><td><span class="ui">マスクする語</span></td><td>入れた語そのままを <code>{{TERM_…}}</code> に。日付(<em>1990-05-12</em> など)を入れると、同じ日のどの書き方もマスクされます:<em>1990/5/12</em>、<em>1990.05.12</em>、<em>1990年5月12日</em>、<em>19900512</em>、<em>May 12, 1990</em>。<em>13/05/1990</em> のような日が先の書き方は、日と月を取り違えようがないときだけです。別の日付や <em>1990.5.12.1</em> のようなバージョン番号はマスクされません。</td></tr>- <tr><td><span class="ui">ローカルモデルで検出</span></td><td><span class="ui">検出方法</span> の中にあります。このコンピュータで動くモデルが、ルールでは見つからない自由文中の名前や住所を見つけます。<span class="ui">シークレットをマスク</span> か <span class="ui">個人情報をマスク</span> がオンのときに使え、見つけたものは同じスイッチに従います。横のメニューでモデルを選べます:AstrLink Guard(中国語と英語、39 MB のダウンロード、コードでの誤検出が少ない、Mac では Neural Engine で動く。既定)か OpenAI の Privacy Filter(1.6 GB、GPU を使える、コード中の普通の値も多く隠す)。その下の <span class="ui">信頼度のしきい値</span> は、値をマスクするのにモデルがどれだけ確かである必要があるかです。既定は Privacy Filter が 0.5、AstrLink Guard が公開元の 0.8。上げると普通の値のマスクは減りますが、本物の名前や住所もそのまま送られやすくなります。誤検出の多くはモデルのあとのルールが既に外すので、既定値は測った中で本物の値を最も逃さない値です。</td></tr>+ <tr><td><span class="ui">ローカルモデルで検出</span></td><td><span class="ui">検出方法</span> の中にあります。このコンピュータで動くモデルが、ルールでは見つからない自由文中の名前や住所を見つけます。オフにしない限りオンで、最初にマスクするリクエストで AstrLink Guard をダウンロードします。ダウンロードが終わるまではルールだけでマスクします。<span class="ui">シークレットをマスク</span> か <span class="ui">個人情報をマスク</span> がオンのときに使え、見つけたものは同じスイッチに従います。横のメニューでモデルを選べます:AstrLink Guard(中国語と英語、39 MB のダウンロード、コードでの誤検出が少ない、Mac では Neural Engine で動く。既定)か OpenAI の Privacy Filter(1.6 GB、GPU を使える、コード中の普通の値も多く隠す)。その下の <span class="ui">信頼度のしきい値</span> は、値をマスクするのにモデルがどれだけ確かである必要があるかです。既定は Privacy Filter が 0.5、AstrLink Guard が公開元の 0.8。上げると普通の値のマスクは減りますが、本物の名前や住所もそのまま送られやすくなります。誤検出の多くはモデルのあとのルールが既に外すので、既定値は測った中で本物の値を最も逃さない値です。</td></tr></table></div><p>プレースホルダーは「種類 + 鍵付きハッシュの 8 文字」です。同じ値はいつも同じプレースホルダーになるので、会話は毎ターン同じに読め、ベンダーのプロンプトキャッシュも有効なままです。値はメモリにだけ置かれます。</p>@@ -151,7 +151,7 @@<li><b>思考はベンダーが書いたまま。</b>署名付きの thinking ブロック、Gemini の thoughts、Responses の暗号化された推論はベンダーが署名したものなので、署名が合うよう変えずに送り返します。中で置き換えるのは、リクエストの他の場所ですでにマスクした値だけです。</li><li><b>ID とツール定義はそのまま:</b>モデル ID、メッセージや呼び出しの ID、UUID、ツール名、MCP サーバー名、ツールのスキーマ(説明文はマスクされます)。ベンダーやツールが検証できるようにするためです。</li><li><b>画像とファイルのデータはそのまま送られます。</b>スクリーンショット内の文字はマスクされません。</li>- <li><b>動かなければ送りません。</b>マスクがオンなのに動かないとき(<span class="ui">プライバシーマスキング</span> プラグインを手で止めた、ローカルモデルがオンなのに応答しない)、リクエストは何も送らなかったことを示す 503 になります。マスクなしで送ることはありません。</li>+ <li><b>動かなければ送りません。</b>マスクがオンなのに動かないとき(<span class="ui">プライバシーマスキング</span> プラグインを手で止めた、自分でオンにしたローカルモデルが応答しない)、リクエストは何も送らなかったことを示す 503 になります。マスクなしで送ることはありません。既定でオンのモデルが応答しないときは、ルールだけでマスクします。</li><li><b>ローカルモデルは外せます。</b>すべてのアドレスがこのコンピュータかローカルネットワーク上にあるプロバイダ(Ollama、LM Studio)は、<span class="ui">リクエストをマスクしない</span> でそのまま送れます。CLI では <code>magpie provider set ollama unmasked=yes</code>。ログにはマスク後の内容が残ります。</li><li><b>モデルにはプレースホルダーしか見えません。</b>マスクされた値を読んだり推論したりはできず、受け渡すだけです。モデルが読む必要のある値は <span class="ui">マスクしない</span> へ。</li><li><b>ルールは形で見つけます。</b>他の国の形式の電話番号や自由文中の名前には、<span class="ui">ローカルモデルで検出</span>、または自分の <span class="ui">マスクする語</span> と <span class="ui">マスクルール</span> が必要です。まず自分のテキストを <span class="ui">試す</span> で確かめてください。</li>diff --git a/site/public/docs/masking.html b/site/public/docs/masking.htmlindex 200693c2f..d2145c2dc 100644--- a/site/public/docs/masking.html+++ b/site/public/docs/masking.html@@ -113,7 +113,7 @@<tr><td><span class="ui">Mask secrets</span></td><td>Private key blocks (<code>-----BEGIN … PRIVATE KEY-----</code>). API keys by their shape: <code>sk-…</code> (OpenAI, Anthropic, OpenRouter), <code>ghp_</code>/<code>github_pat_</code>, <code>glpat-</code>, <code>AIza…</code>, <code>xox…-</code>, <code>sk_live_</code>, <code>AKIA</code>/<code>ASIA</code>, <code>hf_</code>, <code>gsk_</code>, <code>xai-</code>, <code>npm_</code>, <code>pypi-</code>, <code>dop_v1_</code>, <code>SG.</code>, and relay keys like <code>oc_sk_…</code>. JWTs. The password in <code>user:password@host</code>. The value of a field named for a secret, as <code>.env</code> files and configs have them: <code>DB_PASSWORD=…</code>, <code>api_key: …</code>, <code>client_secret</code>, <code>token</code>, <code>credential</code>. Your own <span class="ui">Masking rules</span>.</td></tr><tr><td><span class="ui">Mask personal data</span></td><td>Emails, mainland China mobile numbers (not an 11-digit id: one under <code>order_id</code> or after 订单号 goes as written), Chinese ID numbers and bank card numbers whose checksum adds up. Also on by default: US Social Security numbers, passport numbers (after <em>passport</em>, 护照 or パスポート), IBANs, birthdays (next to <em>birthday</em>, <em>DOB</em> or 生日, and over a year ago, so today’s date stays), MAC addresses and serial numbers (after <em>S/N</em>). Off until you turn them on, since agents send them in nearly every request: the user name in home folders (sent as a made-up name, the same every turn, so the model reads a real folder rather than a placeholder), user and computer names (<code>user@host</code>), public IP addresses and cloud storage buckets.</td></tr><tr><td><span class="ui">Masked words</span></td><td>Each word you listed, exactly, as <code>{{TERM_…}}</code>. A date, such as <em>1990-05-12</em>, matches that day however it is written: <em>1990/5/12</em>, <em>1990.05.12</em>, <em>1990年5月12日</em>, <em>19900512</em>, <em>May 12, 1990</em>, and <em>13/05/1990</em> style only where the day can’t be read as a month. Never another date or a version like <em>1990.5.12.1</em>.</td></tr>- <tr><td><span class="ui">Find with a local model</span></td><td>Under <span class="ui">How it’s found</span>. A model on this computer finds what no rule can: a name or an address in free text. It needs <span class="ui">Mask secrets</span> or <span class="ui">Mask personal data</span> on, and finds under the same switches. The menu beside it picks the model: AstrLink Guard (Chinese and English, a 39 MB download, few false alarms in code, on a Mac it runs on the Neural Engine; the default) or OpenAI’s Privacy Filter (1.6 GB, uses the GPU, masks more ordinary values in code). <span class="ui">Confidence threshold</span> under it is how sure the model must be before a value is masked: Privacy Filter’s default is 0.5, AstrLink Guard’s 0.8, its publisher’s. Higher masks fewer ordinary values, and lets more real names and addresses through: the rules after the model drop most false alarms already, so the default is where we measured the fewest real values lost.</td></tr>+ <tr><td><span class="ui">Find with a local model</span></td><td>Under <span class="ui">How it’s found</span>. A model on this computer finds what no rule can: a name or an address in free text. It is on unless you turned it off, and AstrLink Guard downloads with the first masked request; until it is on disk, the rules mask alone. It needs <span class="ui">Mask secrets</span> or <span class="ui">Mask personal data</span> on, and finds under the same switches. The menu beside it picks the model: AstrLink Guard (Chinese and English, a 39 MB download, few false alarms in code, on a Mac it runs on the Neural Engine; the default) or OpenAI’s Privacy Filter (1.6 GB, uses the GPU, masks more ordinary values in code). <span class="ui">Confidence threshold</span> under it is how sure the model must be before a value is masked: Privacy Filter’s default is 0.5, AstrLink Guard’s 0.8, its publisher’s. Higher masks fewer ordinary values, and lets more real names and addresses through: the rules after the model drop most false alarms already, so the default is where we measured the fewest real values lost.</td></tr></table></div><p>A placeholder is the kind plus eight characters of a keyed hash. The same value gets the same placeholder every time, so the conversation reads the same turn after turn and the vendor’s prompt cache stays valid. The values are held in memory only.</p>@@ -151,7 +151,7 @@<li><b>Thinking stays as the vendor wrote it.</b> A thinking block with its signature, Gemini’s thoughts and Responses’ encrypted reasoning are sealed by the vendor and go back unchanged, so the signature still matches. Only values already masked elsewhere in the request are swapped in them.</li><li><b>Ids and tool definitions go as written:</b> model ids, message and call ids, UUIDs, tool names, MCP server names, and tool schemas (their descriptions are masked), so a vendor or a tool can still check them.</li><li><b>Images and file data are sent as they are.</b> Text inside a screenshot is not masked.</li>- <li><b>It fails closed.</b> If masking is on and can’t run (the <span class="ui">Privacy masking</span> plugin turned off by hand, or the local model is on and can’t answer), the request gets a 503 that says nothing was sent. It is never sent unmasked instead.</li>+ <li><b>It fails closed.</b> If masking is on and can’t run (the <span class="ui">Privacy masking</span> plugin turned off by hand, or the local model you turned on can’t answer), the request gets a 503 that says nothing was sent. It is never sent unmasked instead. The model on by default that can’t answer leaves the rules to mask alone.</li><li><b>Local models can skip it.</b> <span class="ui">Send requests unmasked</span> on a provider whose every address is on this computer or your local network (Ollama, LM Studio) sends its requests as written; <code>magpie provider set ollama unmasked=yes</code> does the same. The logs keep the masked body.</li><li><b>The model sees placeholders.</b> It can’t read or reason about a masked value; it can only pass it on. Put a value it must read under <span class="ui">Never mask</span>.</li><li><b>Rules find shapes.</b> A phone number in another country’s format or a name in free text needs <span class="ui">Find with a local model</span>, or your own <span class="ui">Masked words</span> and <span class="ui">Masking rules</span>. Try your own text in <span class="ui">Try it</span> first.</li>diff --git a/site/public/docs/zh/masking.html b/site/public/docs/zh/masking.htmlindex 5bd522387..344862824 100644--- a/site/public/docs/zh/masking.html+++ b/site/public/docs/zh/masking.html@@ -113,7 +113,7 @@<tr><td><span class="ui">脱敏密钥</span></td><td>私钥块(<code>-----BEGIN … PRIVATE KEY-----</code>)。按格式识别的 API Key:<code>sk-…</code>(OpenAI、Anthropic、OpenRouter)、<code>ghp_</code>/<code>github_pat_</code>、<code>glpat-</code>、<code>AIza…</code>、<code>xox…-</code>、<code>sk_live_</code>、<code>AKIA</code>/<code>ASIA</code>、<code>hf_</code>、<code>gsk_</code>、<code>xai-</code>、<code>npm_</code>、<code>pypi-</code>、<code>dop_v1_</code>、<code>SG.</code>,以及 <code>oc_sk_…</code> 这类中转站的 key。JWT。<code>user:password@host</code> 里的密码。<code>.env</code> 和配置文件里以密钥命名的字段的值:<code>DB_PASSWORD=…</code>、<code>api_key: …</code>、<code>client_secret</code>、<code>token</code>、<code>credential</code>。以及你的 <span class="ui">自定义脱敏规则</span>。</td></tr><tr><td><span class="ui">脱敏个人信息</span></td><td>邮箱、中国大陆手机号(11 位的编号不算:在 <code>order_id</code> 下或跟在「订单号」后面的照原样发出)、校验位对得上的身份证号和银行卡号。默认也开着的:美国社会安全号、护照号(跟在 <em>passport</em>、护照或パスポート后面)、IBAN、生日(旁边有 <em>birthday</em>、<em>DOB</em> 或「生日」,且是一年以前的日期,所以今天的日期不动)、MAC 地址、序列号(跟在 <em>S/N</em> 后面)。默认关闭、需要自己打开的(Agent 几乎每个请求都会带):主目录里的用户名(以一个每轮都相同的假名发出,模型看到的是正常的文件夹,而不是占位符)、用户名和主机名(<code>user@host</code>)、公网 IP 地址、云存储桶。</td></tr><tr><td><span class="ui">脱敏词</span></td><td>你填的每个词,精确匹配,换成 <code>{{TERM_…}}</code>。填的是日期(比如 <em>1990-05-12</em>)时,同一天的各种写法都会遮掉:<em>1990/5/12</em>、<em>1990.05.12</em>、<em>1990年5月12日</em>、<em>19900512</em>、<em>May 12, 1990</em>;<em>13/05/1990</em> 这种日在前的写法只在日和月不会混淆时才算。别的日期和 <em>1990.5.12.1</em> 这样的版本号不会被遮。</td></tr>- <tr><td><span class="ui">用本地模型查找</span></td><td>在 <span class="ui">怎么找</span> 下面。一个在这台电脑上运行的模型能找出规则找不到的东西:自由文本里的人名、地址。需要先打开 <span class="ui">脱敏密钥</span> 或 <span class="ui">脱敏个人信息</span>,找到的内容按同样的开关处理。旁边的菜单选择模型:AstrLink Guard(中英文,下载 39 MB,代码里很少误判,在 Mac 上用神经网络引擎运行;默认)或 OpenAI 的 Privacy Filter(1.6 GB,可用 GPU,代码里会遮盖更多普通值)。下面的 <span class="ui">置信度阈值</span> 是模型要多确定才遮盖一个值:Privacy Filter 默认 0.5,AstrLink Guard 默认 0.8(发布者的值)。调高会少遮一些普通值,也会让更多真实的人名、地址原样发出去;模型之后的规则已经去掉了大部分误判,所以默认值是我们测下来漏掉真实信息最少的那一档。</td></tr>+ <tr><td><span class="ui">用本地模型查找</span></td><td>在 <span class="ui">怎么找</span> 下面。一个在这台电脑上运行的模型能找出规则找不到的东西:自由文本里的人名、地址。除非你关掉,它默认打开:第一个要脱敏的请求开始下载 AstrLink Guard,下载完成前只用规则脱敏。需要先打开 <span class="ui">脱敏密钥</span> 或 <span class="ui">脱敏个人信息</span>,找到的内容按同样的开关处理。旁边的菜单选择模型:AstrLink Guard(中英文,下载 39 MB,代码里很少误判,在 Mac 上用神经网络引擎运行;默认)或 OpenAI 的 Privacy Filter(1.6 GB,可用 GPU,代码里会遮盖更多普通值)。下面的 <span class="ui">置信度阈值</span> 是模型要多确定才遮盖一个值:Privacy Filter 默认 0.5,AstrLink Guard 默认 0.8(发布者的值)。调高会少遮一些普通值,也会让更多真实的人名、地址原样发出去;模型之后的规则已经去掉了大部分误判,所以默认值是我们测下来漏掉真实信息最少的那一档。</td></tr></table></div><p>占位符是「类型 + 8 位带密钥的哈希」。同一个值每次得到同一个占位符,所以对话每一轮读起来都一样,厂商的提示词缓存也不会失效。原值只保存在内存里。</p>@@ -151,7 +151,7 @@<li><b>思考内容保持厂商原样。</b>带签名的 thinking 块、Gemini 的 thoughts、Responses 的加密推理都由厂商签过名,原样发回,签名才对得上。里面只会替换请求其他地方已经遮掉的值。</li><li><b>ID 和工具定义原样发送:</b>模型 ID、消息和调用 ID、UUID、工具名、MCP 服务名、工具 schema(其中的描述文字会脱敏),这样厂商和工具还能校验它们。</li><li><b>图片和文件数据原样发送。</b>截图里的文字不会被遮。</li>- <li><b>失败即不发送。</b>脱敏已打开却运行不了(手动关掉了 <span class="ui">隐私遮盖</span> 插件,或本地模型开着但没响应),请求返回 503,说明什么都没发出,绝不会退回成不脱敏直接发送。</li>+ <li><b>失败即不发送。</b>脱敏已打开却运行不了(手动关掉了 <span class="ui">隐私遮盖</span> 插件,或你打开的本地模型没响应),请求返回 503,说明什么都没发出,绝不会退回成不脱敏直接发送。默认打开的模型没响应时,只用规则脱敏。</li><li><b>本地模型可以跳过。</b>供应商的每个地址都在本机或局域网(Ollama、LM Studio)时,打开它的 <span class="ui">请求不脱敏</span>,请求就原样发出;命令行是 <code>magpie provider set ollama unmasked=yes</code>。日志里保存的仍是脱敏后的内容。</li><li><b>模型只看到占位符。</b>它无法读懂或推理被遮掉的值,只能原样传递。需要模型读的值放进 <span class="ui">从不脱敏</span>。</li><li><b>规则按格式匹配。</b>其他国家格式的电话号码、自由文本里的人名,需要 <span class="ui">用本地模型查找</span>,或者自己的 <span class="ui">脱敏词</span> 和 <span class="ui">自定义脱敏规则</span>。先用 <span class="ui">试一试</span> 测一下你自己的文本。</li>