diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 11f7c75a1..87972cd3e 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -38,7 +38,7 @@ something else shows up as drift. | Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#` on Windows, `omp#@wsl:` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) | | omp's advisor | omp's advisor (`src/advisor`) is a second model, on the `advisor` role, that reviews the main agent's work and sends it notes; it runs only while `advisor.enabled` is true, which omp leaves off (#6408, Awad_Yoo on X). A model picked for the advisor role turns it on when the user hasn't set it, and the role's reset takes back only what that pick wrote (`ompAdvisorTurnedOn`, a stash mark). Three Quiet fields write the rest of `config.yml`'s `advisor` block as omp reads it (`ompAdvisorFields` in [`omp_advisor.go`](../../internal/agent/omp_advisor.go)): `advisor_review` (off, `turn`, `agent-end`: `enabled` with `reviewMode`; off keeps the mode), `advisor_wait` (`syncBacklog`: `off`, `"1"`, `"3"`, `"5"`, `strict`, written as strings since omp's enum settings take strings only) and `advisor_wake` (`continueSeverity`: `nit`, `concern`, `blocker`, omp 18.12.1 or later). They show in omp's opened row and sheet as three rows (`ompAdvisorIn`, drawn by `ompadvisor.js`, imported the first time), the last two only while it reviews; the roles square's advisor line says " · off" when it is off. A `WATCHDOG.yml` roster sets each advisor's own review and wait over these, and is not shown. Taking over from the main model after repeated failures is not omp's advisor's: omp has no such setting, and an omp extension (`pi.on("tool_result")`, `pi.setModel`) is where it goes. `TestOmpAdvisorPickTurnsItOn`, `TestOmpAdvisorSettings`, `omp-advisor.test.cjs`. | | Claude Code in more than one folder | A Claude Code kept elsewhere with `CLAUDE_CONFIG_DIR` (an alias per account or workspace) has its own settings.json. The claude row is the folder the variable names, else `~/.claude`; every other folder under the home folder named `.claude…` that holds Claude Code's own files (`settings.json`, `.credentials.json` or `projects/`) is a row of its own, `claude#` (`.claude-work` → `Claude Code · work`; the default `~/.claude` is `claude#default` while the variable points elsewhere), made by `claudeIn` at that folder (`place.dir`, as the `claude#launch` file is) and connected, set and checked there alone. The file `~/.claude.json`, another tool's `.claude-…` folder with none of those files and the launch file's folder are not listed. A folder outside the home folder is not found (BieJian21872 on X; `TestClaudeCodeInMoreThanOneFolder`). | [`claude_dirs.go`](../../internal/agent/claude_dirs.go) | -| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A distro with none of them is still kept, with no agent row, for what magpie only reads there: the Copilot CLI's folder (its sign-in, #723) and the Antigravity app's `~/.gemini/antigravity` (or `-insiders`), which the Windows app connected to WSL keeps in the distro, since its language server runs there (`wslKept`, `TestWSLAntigravityHome`; the Sessions page reads its conversations, `sessions.wslAgents`). A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). The probe runs `sh -l`, which reads `~/.profile` but not `~/.bashrc`, so a command off its PATH is looked for where Node's managers and installers keep one, as `proc.UserBinDirs` does here (`wslbin`): bun, `~/.local/bin`, volta, pnpm, nvm's default then the highest, fnm's default then the highest (`FNM_DIR`, `~/.local/share/fnm`, `~/.fnm`), mise's installs and shims, asdf, `~/.npmrc`'s prefix, cargo, deno and Homebrew (千里不再 on Discord: a Pi from fnm, not run yet so with no `~/.pi`, wasn't found). One on a Windows drive, which WSL's PATH reaches first when the distro's isn't on it, is looked past rather than taken as the only one (`wslcmd`, `wslwin`; `TestWSLProbeFindsNodeManagersBins`, `TestWSLProbeLooksPastWindowsCommand`). The shell isn't asked interactively for `~/.bashrc`'s PATH: under `timeout` such a bash stops itself on WSL and outlives the timeout. Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). While Codex on Windows is connected, `ConnectCodexTwins` (run by `SyncCatalog`, [`codex_wsl_auto.go`](../../internal/agent/codex_wsl_auto.go)) connects each running distro's Codex once, because the Codex app's work mode on a WSL project runs its app-server on the distro's `~/.codex`, not Windows': the twin is skipped when it is already connected or disconnected, when its config names a provider or base URL of the user's own, or when the distro is stopped; a mark in the stash (`.autoconnected`) keeps it from being done again after a Disconnect. With Settings' Detect agents in WSL off (`NoWSLAgents`, #1264) magpie starts no wsl.exe at all: `proc.Command`, `CommandContext` and `ProbeContext` refuse one by any name or path with `proc.ErrWSLOff` (`wslOff` in [`proc/wsl.go`](../../internal/proc/wsl.go)), where every command magpie runs is made, so a path past agent's and wslrun's own gates (a request's Claude Code stand-in and classifier, #4872: on a computer without WSL each ask put up Windows' install window) asks nothing either (`TestWSLOffStartsNoWSL`, `TestWSLRunnerRefusedWhenOff`, `TestRunRefusedWhenOff`, `TestWSLStandInAsksNothingWhenOff`). With detection on, the same gate refuses wsl.exe with `proc.ErrNoWSLDistro` while the registry has no distro for the user (`HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss`, a key with a `DistributionName` each, read at every start, so one installed later is listed at once; a read that fails is unknown and wsl.exe is asked as before), and agent's and wslrun's listings take that as none (TraderX219 on X: Windows' own wsl.exe without WSL's package put up its update console every 20 to 30 seconds). A failed run whose output says WSL must be installed or updated (`wsl.exe --update`, the inbox prompt, the optional component missing; `proc.WSLSaid`, told by agent's and wslrun's runners) writes `wsl-update` beside settings.json, and wsl.exe is then refused with `proc.ErrWSLNeedsUpdate` for six hours, by every magpie process, unless WSL's package version or the registered distros change; a refused listing is unknown, so nothing remembered of a distro is forgotten (`TestNoWSLDistroStartsNoWSL`, `TestWSLUpdateBacksOff`, `TestNoWSLDistroRunsNoWSL`, `TestWSLUpdateKeepsDistros`). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go), [`proc/wsl.go`](../../internal/proc/wsl.go) | +| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A distro with none of them is still kept, with no agent row, for what magpie only reads there: the Copilot CLI's folder (its sign-in, #723) and the Antigravity app's `~/.gemini/antigravity` (or `-insiders`), which the Windows app connected to WSL keeps in the distro, since its language server runs there (`wslKept`, `TestWSLAntigravityHome`; the Sessions page reads its conversations, `sessions.wslAgents`). A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). The probe runs `sh -l`, which reads `~/.profile` but not `~/.bashrc`, so a command off its PATH is looked for where Node's managers and installers keep one, as `proc.UserBinDirs` does here (`wslbin`): bun, `~/.local/bin`, volta, pnpm, nvm's default then the highest, fnm's default then the highest (`FNM_DIR`, `~/.local/share/fnm`, `~/.fnm`), mise's installs and shims, asdf, `~/.npmrc`'s prefix, cargo, deno and Homebrew (千里不再 on Discord: a Pi from fnm, not run yet so with no `~/.pi`, wasn't found). One on a Windows drive, which WSL's PATH reaches first when the distro's isn't on it, is looked past rather than taken as the only one (`wslcmd`, `wslwin`; `TestWSLProbeFindsNodeManagersBins`, `TestWSLProbeLooksPastWindowsCommand`). The shell isn't asked interactively for `~/.bashrc`'s PATH: under `timeout` such a bash stops itself on WSL and outlives the timeout. Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). While Codex on Windows is connected, `ConnectCodexTwins` (run by `SyncCatalog`, [`codex_wsl_auto.go`](../../internal/agent/codex_wsl_auto.go)) connects each running distro's Codex once, because the Codex app's work mode on a WSL project runs its app-server on the distro's `~/.codex`, not Windows': the twin is skipped when it is already connected or disconnected, when its config names a provider or base URL of the user's own, or when the distro is stopped; a mark in the stash (`.autoconnected`) keeps it from being done again after a Disconnect. With Settings' Detect agents in WSL off (`NoWSLAgents`, #1264) magpie starts no wsl.exe at all: `proc.Command`, `CommandContext` and `ProbeContext` refuse one by any name or path with `proc.ErrWSLOff` (`wslOff` in [`proc/wsl.go`](../../internal/proc/wsl.go)), where every command magpie runs is made, so a path past agent's and wslrun's own gates (a request's Claude Code stand-in and classifier, #4872: on a computer without WSL each ask put up Windows' install window) asks nothing either (`TestWSLOffStartsNoWSL`, `TestWSLRunnerRefusedWhenOff`, `TestRunRefusedWhenOff`, `TestWSLStandInAsksNothingWhenOff`). With detection on, the same gate refuses wsl.exe with `proc.ErrNoWSLDistro` while the registry has no distro for the user (`HKCU\Software\Microsoft\Windows\CurrentVersion\Lxss`, a key with a `DistributionName` each, read at every start, so one installed later is listed at once; a read that fails is unknown and wsl.exe is asked as before), and agent's and wslrun's listings take that as none (TraderX219 on X: Windows' own wsl.exe without WSL's package put up its update console every 20 to 30 seconds). A failed run whose output says WSL must be installed or updated (`wsl.exe --update`, the inbox prompt, the optional component missing; `proc.WSLSaid`, told by agent's and wslrun's runners) writes `wsl-update` beside settings.json, and wsl.exe is then refused with `proc.ErrWSLNeedsUpdate` for six hours, by every magpie process, unless WSL's package version or the registered distros change; a refused listing is unknown, so nothing remembered of a distro is forgotten (`TestNoWSLDistroStartsNoWSL`, `TestWSLUpdateBacksOff`, `TestNoWSLDistroRunsNoWSL`, `TestWSLUpdateKeepsDistros`). A look at WSL (`wslRefresh`) runs wsl.exe, each distro's probe and the open of its `\\wsl.localhost\` (`wslRoot`, bounded at `wslRootWait`, since a stat of WSL's share can't be cancelled) outside `wsl`'s lock, which is held only to read and write what is known; looks take turns on `wslRefreshMu`. What a request asks of WSL (a Codex or Claude stand-in, `wslUp`, `distroAt`, Copilot's folders) never waits on a look: whether a distro runs is asked once at a time in the background (`wslRunningWithin`) and waited for at most `wslRunningWait` (2s), and a distro wsl.exe hasn't said is running counts as stopped, so none is opened on a guess; Copilot's sign-in from WSL (`copilotCLILogin` in provider) is read the same way, single-flight with its last answer kept (`copilotWSLWait`). Before, the GUI's look held the lock through a hung wsl.exe or a wedged share, every request's stand-in and Copilot's sign-in queued behind it, and the gateway sent 504 after 30s until WSL was restarted (vsoullai on X, #6167; `TestWSLHangHoldsNoRequest`, `TestWSLRootHangFailsProbe`, `TestCopilotWSLHangHoldsNoRequest`). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go), [`proc/wsl.go`](../../internal/proc/wsl.go) | | WSL folders that are links | Through `\\wsl.localhost` Windows can't follow a link the distro has: with `~/.codex` a link to `/mnt/c/Users//.codex`, a mkdir of it says it exists and nothing below it can be made, written, read or listed (#4502, linusxiong). The probe asks `readlink -f` there where each agent folder, its `skills` and the folders beside them lead (`wslLinkPaths`, `distro.Links`; a `$HOME` that is itself through a link is left as it was) and which drive each Windows mount is (`distro.Drives`). `distro.open` opens a path at or below a link where it leads: on a Windows drive the drive's own path (`C:\Users\\.codex`), elsewhere in the distro through its root again; `native` spells such a path back through the link for the agent. A link `readlink -f` couldn't resolve is never guessed at: its agent is unreached (`Agent.Unreached`), says why in its notice and refuses each change and sync. Every writer goes through it: the agents' own files (`place.join`, `place.open`), the library's targets (`wslOpen`, a `wsl` problem per agent), RTK (`rtkAt`, `agent.WSLOpen`), the Sessions page's reads (`sessions.WSLHome.Open`) and the Copilot CLI's sign-in (`provider.CopilotWSLDirs`). Links deeper than the probed paths aren't resolved (`TestWSLOpenThroughLinks`, `TestWSLAgentFolderIsALink`, `TestWSLAgentFolderLinkUnresolved`, `TestWSLProbeLinks`, `TestWSLFolderIsALinkToC`, `TestRTKWSLFolderIsALink`). | [`wsl.go`](../../internal/agent/wsl.go), [`targets.go`](../../internal/library/targets.go), [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) | | WSL CLI versions and updates | A twin's CLI is read and updated in its distro, as the host's is (`cliupdate_wsl.go`; mewcoder on X): the Agents row shows the version, the newest and an Update button for every `cliSpecs` kind a distro has a command for, and Update all takes them in. Where the binary is comes from the probe (`distro.Paths`, else the command asked of the distro's PATH); one `wsl.exe -d -e sh` script says where its links lead, its `--version` and exit code (`wslCLIScript`, kept ten minutes in `wslProbes`, asked again by Rescan and after an update), with the CLI's own folder, its npm prefix, `~/.local/bin` and `~/.bun/bin` first on PATH, since `wsl.exe -e` has no login PATH and a node CLI would not find node. How it was installed is read from that Linux path by the same rules (`wslHowInstalled`: its own updater via `cliSpec.self`, Homebrew's Cellar, npm, bun or pnpm; volta, yarn and an npm prefix the user can't write, `/usr/lib`, are left alone), and the update runs in the distro through wsl.exe (`wslRunUpdate`) with a Linux brew asked for its newest in the distro too. A distro that isn't running is never started to be asked: its rows show no version and an update says to start it. Not carried over: the host's proxy settings (the distro has its own network), and Grok Build's newest is read from this computer's channel setting. Kinds with no command of their own (Goose, mu) show nothing, as on the host. | [`cliupdate_wsl.go`](../../internal/agent/cliupdate_wsl.go), [`cliupdate.go`](../../internal/agent/cliupdate.go) | | Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) | diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index c755c814e..bf47454bb 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -206,7 +206,7 @@ recorded as a prediction failure (`noPrediction`). 2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, 32 hex digits or more, or a digest of 16 to 31 hex digits in one case with letters and digits both, a cache key or a short commit, which went as a key before: _kaichen on X, 10-28; `digestShaped`), or an element token cua-driver hands the model for computer use (`s0000002a:14`, #3782), goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of `…-a13800138000`, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (`api_key=`, `refresh_token`), never one named for an id, a cursor, a request or a digest (`secret_id`, `next_page_token`, `Idempotency-Key`, `secret_hash`), nor cua-driver's own `element_token` (any other name with `element` in it, `element_api_key`, is a credential's as before), a bare `key` (not after api, access, secret, private, signing or license: `keyPhrase`), a field named for a cache, commit, object, blob, file, content, revision, partition, shard, bucket, dedup, lookup, row or sort key, a serial number, or what the model takes a UUID or an element token for, nor an element token known from before (one the model labelled in prose a turn earlier) (`noIDs`, [`internal/redact/ids.go`](../../internal/redact/ids.go)); and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then on the same route (the providers the request can reach: its model's, its fallbacks', or a group's members'; `maskedFor`, `masking.WithRoute`, `redact.Options.Route`), so neither a value a rule first finds later in a conversation nor a name the local model reads in a tool's output only after its first send (the default model's 2s wait, `pii.Partial`; vvrfxyz on X, dsh's cache hits) changes the prompt the vendor has cached and rewrites all of it to the cache; such a late find is masked in new text (`learnLate`), and another route, never sent the text, gets it masked with what is known and found now, `sentSpans`, `TestModelReadingLateKeepsTheSentPrefix`, `TestMaskedPrefixKeptOnlyOnItsRoute`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end, before the writer outside it that names the member, `memberWriter`, writes what it holds: the other way round a whole reply with a value masked in its request went out a 200 with an empty body, #4129, `TestMaskedWholeReplyNamesMember`): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). Every reply is read so, a request that masked nothing too: a vendor holding the conversation (Codex's compacted history, a server-side session) answers with placeholders sent turns before, and those came back as written (yapechan123 on Discord, a table of `{{PERSON_…}}、{{PERSON_…}}`; `TestReplyToAnUnmaskedTurnIsRestored`). Every string of an event is read, a tool call's `name`, `type` or `data` inside its arguments too, but for signatures, `data:` URLs and opaque blobs (`sealedText`); a held tail is kept per string, so a Responses event's random `obfuscation` never takes the hold from its `delta`; a whole body with a placeholder in no braces or one is restored as with two (`heldIn`); an audio, image or other binary reply goes through as it comes (`binaryType`). Past 200,000 values the half used longest ago is let go (`makeRoom`, `touch`; before, a random half, so a value just masked could be gone when its reply came). Values are held in memory only, so a placeholder from before a restart that only the vendor still holds comes back as written. A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, and has an address: the user's switch for each provider whatever its address, AcMilan on Discord, `http://llm.corp.lan:8000`; nothing is looked up to decide, `TestSkipsRedaction`, `TestLANNameUnredactedProvider`. A signed-in subscription and a plugin's provider take it too, kept with the account's model picks (`withPicks`; isee1_1 on Discord: a translation plugin as a provider); and so does another magpie (CrazyMouse_TT on X, his own model behind it): it is sent the request as written with no `X-Magpie-Masked-As` (`withMaskedAs` is never called), so it masks by its own Settings › Privacy and its own providers' switches (`TestUnredactedRemoteMagpieMasksOnItsOwnSide`); left off, it is sent the request masked here, as before. The editor shows it for every provider, another magpie with no caution, and, while it is on, a caution under it naming an address not on this computer or the local network, or, for a subscription or a plugin's provider, its name (`unmaskRow`, `awayHost` in app.js; a name of the user's own DNS is asked about, only while it is on, through `POST /api/local-hosts`, `provider.LocalHost`, which takes a name every address of which, looked up in 400ms and kept a minute, is loopback, private or link-local, `netproxy.LocalName`; no request asks it)) goes to them as the agent wrote it and isn't masked on its way, since a request is masked only once its route is known (#3973: masking a body whose masked copy was thrown away took up to minutes of magpie's own time). The log, recent calls and the request archive keep it as it went (the archive's bodies have their secrets taken out, `redact.ScrubJSON`, as every call's do), whether the archive is on or off; an observer that wants the bodies (the OTLP export, a JS plugin's) is handed it masked, masked once when it is first handed it after a try (`Call.maskIn`, `laterMasked`), never before the request is sent. A request turned away before it is routed is logged masked (`maskedCopy`). count_tokens, embeddings, speech, transcription, pictures and videos (`unmaskedMembers` over the models the picture or video may be made on: a group with one member left on is masked) and Ark's own API (`nativeArk`, as `nativeAny`) follow the same rule (`TestUnredactedProviderDrawsWhole`, `TestUnredactedProviderMakesVideosWhole`, `TestUnredactedProviderArkNativeWhole`); Settings › Privacy lists the providers set so, each opening its editor (*Sent unmasked*, `unmaskedRow` in plugins/redact/settings.js, `unmaskedProviders` in `/api/settings`). System One follows it too: a `/v1/systemone` request, and a `/v1/decisions` one translated to it, is masked once before its tries (`serveDecideTries`, `TestSystemOneMasked`). A request masking would change can go to such a model instead (jessyoungyu on X: 「{{百度}}这家公司怎么样」 can't be answered from a placeholder): with Settings › Privacy's *Instead of masking, send to* set (`RedactRouteTo`, `POST /api/settings/redact-route`, which takes only a model `MaskRoute` passes: `unredactedRoute` for its provider and fallbacks, or its group), an agent's turn that masking would change (`maskHits.n` > 0: a warn-only hit doesn't count, and a held-back one stays held back) goes as written to that model, the model asked for left alone, in `serve` after the request is masked (`maskRouteFor` in [`redact.go`](../../internal/gateway/redact.go); the masked copy is thrown away, so streaming and every API go as for any route). If it fails, the request fails: its fallbacks are all unmasked ones by `unredactedRoute`, and nothing is masked and sent to the model asked for. It is judged again on each request, so a route that has since got a vendor's address, a fallback elsewhere, was turned off, or isn't one of a gateway key's models is ignored and the request is masked as before. Only an agent's own turn is moved (`agentTurn`, set in `serveAgent` and cleared by `ownAsk`): a title, a search stand-in, a picture described, System One and Jev stay masked. count_tokens is counted on the route (`countTokens`), and a turn of Codex's own model on its ChatGPT sign-in goes there too (`codexMaskRoute` in `codexBackend`; masked once to decide, only while it is set). Such a turn, and ChatGPT's web search for it (`alphaSearchOn`), goes as written when the Codex subscription it is on is set to go unmasked (`codexRouteUnmasked`; `TestCodexSignInUnmaskedSwitch`); a plugin's provider is asked through `serve` (`TestPluginProviderUnmaskedSwitch`). Speech and video requests are never moved to that model: they are masked unless their own route is set to go unmasked (`maskTextHits`). Unset, as by default, nothing changes. Tests: `TestMaskedRequestGoesToTheModelSet`, `TestCodexSigninTurnGoesToTheModelSet`, `TestMaskRouteOnlyForTheAgentsTurn`, `TestMaskRouteTakesOnlyUnmaskedRoutes` ([`mask_route_test.go`](../../internal/gateway/mask_route_test.go)) and `TestRedactRouteSetting` in internal/gui. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`). A request masking swapped a value in (`maskHits.n`) is told, on each try, that the placeholders are used as written and filled in before anything runs (`placeholderNote`, [`placeholder_note.go`](../../internal/gateway/placeholder_note.go); treeMan on Discord: weaker models refused to search with one, asked to verify it, or rewrote it as an example). The note names neither magpie nor a vendor or client. It goes where placeholders first appear, after what is there, so it is new text the first time and the same on every later turn: in the instructions when they or the tools hold one (the last block of Anthropic's `system`, the end of Chat's first system or developer message, a part after Gemini's `systemInstruction`'s), else on the earliest message that holds one (a text block or part after its content; on Responses a developer message after that item and the tool outputs that follow it). Responses `instructions` (Codex's base_instructions) is never touched. A conversation's values are masked again each turn and a value found later is masked only in new text, so the note never lands in text the vendor has cached (`TestMaskedConversationKeepsItsCachedPrefix` goes red with the note in the system prompt). It is not added for a Claude subscription (the bridge puts the caller's instructions in the run's first message, which Anthropic classifies), for a ChatGPT account (Codex's own turns, `codexUpstreamOn`, never pass here either), or for a Responses turn with `previous_response_id`, where it would pile up in the stored conversation (`notesPlaceholders`; `TestPlaceholderNotePlaces`, `TestPlaceholderNoteNotOnClientPaths`, `TestMaskedRequestTold`, `TestPlaceholderNoteIsNeutral`). count_tokens counts without it. Inside a tool call's arguments (Anthropic's `tool_use` input, Gemini's `functionCall` args) and Gemini's `functionResponse` response, whose keys are the tool's, a field named for a secret (`SecretName`: `api_key`, `db_pass`, `Authorization`, not `sort_key` or `public_key`) has a value of 8 characters or more masked by its name whatever its shape, with secret masking on (#2946, `namedSecret`); a key anywhere else is the protocol's, `mcp_servers[].authorization_token` included, and never masks by its name (`TestMaskJSONSecretNamesOnlyInToolArgs`). - A routing group says how its requests are masked (`Group.Redact`, set in the group's editor under Masking; `provider.RedactOn`, `RedactOff`, unset follows providers). `off` sends to every member as written whatever its provider says, `on` masks to a member whose provider is set to go unmasked, and in a group in a group any `on` wins over `off` (`walk` passes it down in `Member.Redact`; `Member.Unmasked`, `provider.UnmaskedBy`). Every route that reaches the group asks the same way: `unredactedRoute(p, model, isGroup, ms)` (a provider's fallback groups and `provider.GroupsAfter`), `unmaskedMembers`, `maskedFor`/`MaskRoute`, `candidate.unmasked()` (embeddings, images, video, decide, count_tokens). Global masking off still masks nothing; a shared group never carries it (export and import clear it, an import over a group keeps the old one). A save that doesn't name it keeps it, `follow` clears it. Guarded by `TestGroupRedact*` in `group_redact_test.go`. - With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so (a date over a year ago: one in the last year or ahead is the day an agent runs on, `dateOK`); the word must be right before the date, so a log line's or a file name's date is none, and a time beside the date doesn't make it a log's: a date of birth stored as a time (`1990-05-11T16:00:00.000Z`) is one (`TestBirthdayLogDates`; #3878), MAC addresses, and serial numbers next to S/N or the like. Eleven digits from 13 to 19 are a mainland mobile's form and an id's too, so they are a phone only with +86 or 86 before them, as the value of a field whose name says phone (phone, mobile, tel, cell, contact, 手机, 电话, a field named `number`), or in prose with no id's word right before them (order, id, no., #, 订单号, 编号, 单号, 流水号); under order_id or uid, after 订单号, or with a letter or digit against them they go as written (`phoneAt` in [`internal/redact/phone.go`](../../internal/redact/phone.go); _kaichen on X, 10-28). Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. When the user name is on, it goes as a made-up name of 8 lowercase letters, the same for that name every turn and put back in replies like any placeholder (`standIn` in [`shape.go`](../../internal/redact/shape.go)), not as `{{USERNAME_…}}`: with mimo-v2.6-flash a model read `C:\Users\{{…}}` as a temporary folder and set out to delete it (eerttreeeert on X, 10-28). A user name found once is masked again as known (8 bytes or more) only where it stands as the user's name: a path's part, `name@host`, a git author, `ls -l`'s owner, `uid=501(name)`, prose, a quoted string; not where code has the same word as a name of its own, joined to another part (`developer_dir`, `self.developer`, `developer.go`), declared, assigned, called, a parameter or a JSON key (`nameAlone`). A `User:` line's unquoted value made of words one of which says it holds a user (`current_user`, `UserInfo`, `loginName`) is a variable's or a type's name, not a login (`notLineIdent`); a quoted one is masked (`TestUserNameInCodeIsNoUserName`, `TestUserLineInCodeIsNoUserName`; Tomyu_2034 on X). A public IPv4 or IPv6 address goes the same way as a name that says what it is, `public-ip-` and eight lowercase letters (`public-ip-kvxqmrtz`), the same one for that address while magpie runs and never another address's, put back only where it stands as a whole name, in a streamed tool call's arguments too (`ipStandIn`, `restoreAddr`; `TestIPGoesAsAPublicIPName`). Told `{{IP_…}}`, models asked the user for the real address or searched `~/.ssh` for it instead of running ssh (0x0_air on X, 10-28). Told an address from the documentation ranges (192.0.2.0/24 and the like, used from 10-28 to 10-31), they ran ssh but told the user, when asked why it failed, that it was an example address and not their server's, and a 192.0.2. one read as a LAN address (akic404 on Discord, 10-31). A name with no dot reaches nobody if the vendor tries it itself. An EVM address (`0x` and 40 hex digits) is public, so the local model's finds leave it as written unless a key's name is right before it; a 64-digit private key is still masked (`evmRe` in `modelFits`; `TestEVMAddressGoesAsWritten`). A number written in hex, `0x` and 1 to 16 hex digits (an address in reverse-engineering notes, a constant, a flag), is no value of any kind the local model finds, whatever is before it, since the function at an address is often named for a key; a longer one (a key in hex) is masked still (`hexLiteral` in `modelTakes`; `TestHexNumberGoesAsWritten`, TakaNaShi_ShiKi on X). A public video's id is no value of any kind the local model finds either: a Bilibili BV id (`BV1` and nine base58 characters) or av number by its own shape, and a YouTube video's, playlist's or channel's id only where its link is right before it (`watch?v=`, `list=`, `youtu.be/`, `/shorts/`, `/embed/`, `/live/`, `/channel/`), since 11 base64url characters alone may be a key's; both real models took every BV id in a script's list for a secret (`publicID` in `modelFits`; `TestPublicVideoIDGoesAsWritten`, eval case `bilibili-bvids`, jimlee0824v2 on X). A key with such a shape whose name is before it is still the rules'. Decimal digits alone that the local model calls a secret are a count, a time or an id unless the name right before them ends in a key's, a token's, a password's or a PIN's word (`api_key=`, `PIN:`, `密码是`): Claude Code's `14998720 tokens left`, `"total_tokens": …` and `max_tokens: …` go as written (`numberNamedSecret` in `modelFits`; `TestTokenCountIsNoSecret`, steven_4422 on Discord). Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `strings@base.json`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`icon@2x.zip`, `intro@1.5x.mov`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). A domain needs a dot and labels a host can have, so a disassembly's symbols go as written for both too: `system@plt`, `puts@got.plt`, `memcpy@GLIBC_2.14`, `foo@@GLIBC_2.2.5`, and `system@got` (`.got` is a top-level domain; `mailHost` in `realEmail`, `TestSymbolIsNoEmail`; ch35tnut_ on X, 10-28). `ops@files.zip` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults. - - With *Find with a local model* on (`masking.ModelWanted`: on by default since 10-28, `settings.RedactModel` the user turning it on and `RedactModelOff` off, this computer's own, kept by `KeepOwn`; a user with a model downloaded or picked and neither flag turned it off before the default, and `RedactModelAuto` marks the default's own download), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`), but for what the agent defines (its tools' and schemas' descriptions, under `defKeys`), which the rules alone mask, as with the model off, after the rest of the request so a value the model found in a message is masked there too as known: those were 52,577 of Claude Code 2.1.296's 67,532 bytes the model read, and a 4-core server's first request waited out the gateway's 2 minutes (niuniu_8964 on X; 11.5s cold at 4 procs on a Ryzen AI Max+, 2.6s without them, and on three real Claude Code requests the model masked nothing there the rules didn't); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor one word as a name where what is around it says a thing and nothing says a person: an app's name in a list of names alone, in a list of apps, or beside a thing's word (using, switched to, the … app, vs, 这个软件), so Privacy Filter's Cicada and Mimi in a chat about choosing apps go as written, while a full name, a Chinese name and a first name beside a relation, a greeting, said or he/she are masked as before, and a text of one first name alone goes as written by design (`thingNamed` in [`thingname.go`](../../internal/redact/thingname.go); ylorn. on Discord, whose follow-up questions had the names as written while the history had them as placeholders, so the vendor answered about another app), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). A package's name goes as written, for the model and the rules alike (dniray on Discord, v0.1.1917): the module a line of code loads (`from ' drizzle-orm '`, `require('jsonwebtoken')`, `from x import`, `use x::`, with an editor's line number or a diff's mark before it; `moduleAt`, `codeHead`), a manifest's dependency pinned at a version (`"drizzle-orm": "^0.36.4"`, TOML's `x = "9"`; `dependencyAt`), a folder under node_modules or site-packages, the module an error could not find (`Cannot find module 'x'`, `No module named 'x'`; `missingModuleAt`), a package an install names (`pnpm add x`; `installedAt`) or pins with @ (`x@0.36.4`; `pinnedAt`), all in `packageAt`; a value known from an earlier mask (`knownSpans`) goes as written there too, since once the model took the name for a secret anywhere in a request it was masked on the import line as known (dniray, v0.1.1965), a requirement's name before its pinned version (`django-rest-passwordreset==1.4.0`; `pinnedAfter`), a lock file's integrity hash (`sha512-…`; `sriRe` in `namesThing`), a version as the value of a field named for a secret (`"js-tokens": "^4.0.0-beta.1"`; `versionValue` in `fieldAt` and `keyAt`), and a package pinned at its version as user@host has it (`js-tokens@4.0.0:` in pnpm-lock.yaml; `notPackagePin`); `TestPackageNamesGoAsWritten` and `TestModelPackageNamesNotMasked` hold them. A field named for a secret and set to nothing takes nothing from the field after it: the SECRET rules let a space stand after `=` or `:` (`password = hunter2` in a config), and `env -i UI_PASSWORD= UI_ADDR=127.0.0.1:39117 ./syncer` went with `UI_ADDR=127.0.0.1` as UI_PASSWORD's value (mx_albert on Discord); a value that is an assignment of its own after a space (`UI_ADDR=`, `addr=`, `--listen=`) is the next field, read with its own name, so a token there still masks (`fieldMatches`, `nextField` in `internal/redact/fieldvalue.go`; `TestEmptyFieldTakesNotTheNext`, `TestSecretBesideEmptyFieldMasks`). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with Privacy Filter a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name; 和 or 与 says so only after a person, 吴敏和郑浩 but not 判断和边界, 发 or 打 only as the verb, 发了个 but not 关键发现, and a sentence starts after punctuation, not after a space after code, `gh pr view` 易触发; xuanwo on X; 一下 only after a verb that asks a person, 问一下张伟 but not 改一下文案, a word any subject takes after it, 已经, 明天 or 他, only with a person's cue before it, and 说明 is no 说; zeewell on X), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left, and so is a common word that starts with one (`zhWords`: 文案, 文档, 方案; 毛利, 毛重, 毛巾, since 毛利 is a margin far more often than the Japanese surname, so 毛利低 goes as written: _kaichen on X, 10-28; the model still finds 毛利兰, and neither model nor rule masks 毛利小五郎), the model's own name too when it is that word whole. A name the model or the cues take is also no name when it is an ordinary word (`zhWordShaped`, `zhWordNotName`, the one check both go through): a colour (黄绿色, 红色, any that ends in 色 or is colour characters alone: hh05928822 on X after v0.1.1850), a word that starts with a surname from `zhWords` or `zhDict` (about 1,550 two-character words from jieba's dictionary, [`zhdict.txt`](../../internal/redact/zhdict.txt), its header saying how they were chosen; 边界, 应该, 尚可), or such a word with what makes a longer word after it (关键词, 关键字: wangjunxiao128 on X; 应用层, 毛利率), unless a role before it or a title after it says a person is meant (客户方圆, 江山老师), where a name that is also a word is masked. The surnames stay (黄 starts 黄绿色 and 黄晓明), and 毛利兰, 关羽 and 黄晓明 are still masked. With AstrLink Guard only a nickname is (小王, 老李, `zhNick`; `redact.Options.NamesByModel`): Guard at 0.8 finds the full names those cues did in zhname_test's sentences (张伟, 陈建国, 欧阳娜娜…), and misses the nicknames, 孙经理, and all but the surname of 王老板 and 邓总; the cues took words for names (关键发现; xuanwo on X). The model is the user's pick (`settings.RedactModelName`, `pii.Choose`; the app's menu beside the switch, `pmPick`): AstrLink Guard (QuantumNous/astrlink-guard at a pinned revision, Apache-2.0, a 39 MB int8 Multilingual-MiniLM token classifier for Chinese and English), run in magpie's own process on the CPU by [`internal/pii/guard`](../../internal/pii/guard) (an ONNX reader, the XLM-R tokenizer and int8 kernels in Go, NEON/SDOT on arm64 and SSE2 on amd64; its labels named as Privacy Filter's, `guardLabels`); a text over one window, 510 tokens, is read in windows that overlap by 128, and on the CPU as many windows at once as it has cores, half of `GOMAXPROCS` and 4 at most (`guard.Cores`: on every core a long history unread kept a 32-core Linux box at 13 cores' worth for as long as requests came, xinvxueyuan and shensmart on Discord, 10-28): one window's matmuls split over the cores left them idle between, and a 4-core server's first Claude Code request waited minutes (niuniu_8964 on X; 22,488 tokens took 23.9s at 4 procs, 17.9s at once, and 48.8s against 30.5s at 2), and on a Mac through CoreML on the Neural Engine or the GPU ([`coreml.go`](../../internal/pii/guard/coreml.go), [`internal/pii/guard/coreml`](../../internal/pii/guard/coreml); yyhhyyyyyy on X; Settings › Privacy names which, from CoreML's own compute plan of the compiled model, `MLComputePlan` on macOS 14.4 and later, the device most of its program's estimated cost is on (`coreml.Plan`, `Model.Backend`, `Status.Via` and `Device`): it said "on the CPU" under CoreML, yyhhyyyyyy on Discord, 10-27; an M5 Pro's plan puts all of it on the GPU; after a CoreML read fails it says the CPU and why until one doesn't): the same network from the same int8 weights in float16, written from the downloaded model into a program made by `coreml_gen.py` and compiled once into the model's folder, 512 tokens in about 12 ms where the CPU takes 400, its probabilities within .07 of the publisher's fp32 model where the CPU's are within .13 (the CPU quantizes activations as the int8 model does, CoreML doesn't), so a span near the threshold can fall the other side (a go.mod module path is a secret at .81 on CoreML, .79 on the CPU, .785 in fp32); a window under 16 tokens (`coremlMin`), a Mac before macOS 13 or any failure goes to the CPU, loaded on the first request and let go after 10 minutes with none; or OpenAI's Privacy Filter. With no pick it is AstrLink Guard, the default; a user who had Privacy Filter on before there was a choice keeps it only while AstrLink Guard downloads, which the first masked request starts and which then saves AstrLink Guard as the pick (`masking.picked`, `toGuard`; an hour between tries after a failure). Measured for that default (#3578): on 234 segments of real code and config it found 2 spans where Privacy Filter found 100 (38 of them go.sum hashes after redact's own checks), and with the rules it found 42 of 42 test values to Privacy Filter's 41. Each model has its own download, cache file and turn (`backend`). AstrLink Guard's turn has `guard.Cores()` places (`guardTurn`), so that many requests read at once, and they share those cores: every window, of any request, takes one of `guard.Cores()` tokens before it reads and more only while they are free (`guard.take`), so requests together never read on more cores than one did (the 4 promised xinvxueyuan and shensmart above); the model loads once (`guardLoading`), the idle timer lets go only when no place is held (`guardIdle`), and a text one request is reading another waits for rather than reading it too (`backend.reading`). Before, one request read at a time, and an agent's parallel requests queued behind it (yyhhyyyyyy on Discord, 10-28, who asked for 16 at once). Measured at 1, 2, 4 and 8 requests at once (a Ryzen AI Max+ 395 under WSL, 4 cores): 512-byte requests 4.2, 6.1, 8.1 and 8.4 a second where one at a time was 4.2 whatever came, on 1.9 to 3.9 cores, memory flat at about 150 MB; 4 KB requests already read their 3 windows on 3.6 cores alone, so they stay at 0.6 a second (Windows on the same box: 7.5 to 12.1 a second at 1 to 8, 4 KB 0.7 to 0.8, on at most 3.8 cores). Each request on cores of its own would read 20 a second at 8, on 12 cores, and 4 KB at 8 took 20 cores and 521 MB (953 MB on an M5 Pro), so the bound is the cores, not the count, and there is no setting for it. Through CoreML the GPU is the bound: on an M5 Pro 4 KB requests read 23, 20, 25 and 25 a second at 1, 2, 4 and 8, a model per request no faster, so CoreML reads one window at a time, and only the windows under `coremlMin` or after a failure use the CPU's tokens. Both find at a floor of 0.5 (`pii.Floor`) and give each span its score (AstrLink Guard: the least of its tokens' probabilities, rounded to a float32 so a cached span reads back the same; Privacy Filter: pf-serve's own), and masking keeps those at the model's threshold or over (`pii.Threshold` in `masking.model`): the user's for that model (`settings.RedactModelScore`, this computer's own; Settings → Privacy's Confidence threshold, `pmScore`, 0.5 to 0.95), else the model's own (`MinScore`: Privacy Filter 0.5, AstrLink Guard 0.8, its publisher's). A value known from before follows the same threshold: each value masked remembers the highest score anything found it with (a rule's counts as sure), and one only the model found, under the threshold now, is no longer masked again as known (`noteScores`, `knownSpans` in [`known.go`](../../internal/redact/known.go); before, a raised slider changed nothing for a value masked once: _kaichen on X, 10-28). The defaults stay because on the eval a higher one mostly loses values the checks after the model would have kept (Privacy Filter at 0.85 lost a Chinese name; AstrLink Guard at 0.9 a phone in a tool result), while the false alarms it would drop are mostly dropped by those checks already (Yayoi_no_yume on X). Measured again on 2000 segments of real agent traffic (Codex and Claude Code sessions: prompts, tool arguments and results, a quarter with Chinese) and 30 more labelled cases: AstrLink Guard at 0.88 rather than 0.8 drops 3 false alarms (a model id, a sandbox path word, a token counter) and lets a colleague's name and a signed name through; Privacy Filter at 0.88 rather than 0.5 drops 11 (timestamps in paths, log lines, a plugin id) and lets 6 real names and a phone through (4 of the names in the real traffic). Lowering Guard to 0.5 finds 2 more names in the real traffic and 3 more labelled values, for 10 more false alarms (9 of them Claude Code's `` counter). Those false alarms are shapes a check can turn away; a threshold can't without losing real values. Privacy Filter is a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590; every pf-serve keeps the engine's own MoE chunk, `PF_MOE_CHUNK` at the window's 4096, which an RX 470 through Vulkan read 6-9% faster than 2048 in interleaved runs and Metal ~6% faster, and inherits a value the user set): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, through magpie's proxy (`netproxy.Func`, as its other requests; hh0592821 on Discord, whose download went direct before), from hf-mirror first in China (`source.chinaFirst`) and from hf-mirror after Hugging Face everywhere else, the switch off too (`source.modelMirror`), so a poisoned or blocked huggingface.co doesn't stop it; hf-mirror serves AstrLink Guard's files itself and sends Privacy Filter's back to Hugging Face) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request, in the model's folder and given the model's file name, never its path (a Windows C program's argv is in the ANSI code page and ggml reads it as UTF-8, so a user folder named in Chinese failed every load with the path in mojibake, AIMetaPhD on X; a pf-serve error that names the file is shown with the whole path) (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (`pieces`: after a line's end, else a space, of those in the piece's second half the one whose 48 bytes before it hash least (`landmark`), so a line edited early in a text leaves the pieces after it as they were, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (`merge`: one found twice is one, one cut by a piece's end is whole), and a value of 8 bytes or more found in a text is found wherever else it is in it, as sure as its surest find (`spread`: the model scored an address on 400 lines alike 0.9 on some and 0.5 on most, wangwu25685333 on X), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (`found-.bin` beside the model: hashes, offsets, labels and each span's score, never text; a `pfound01` file from before scores is read with every span sure, so it masks as it did; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, by the request waiting with the least left to read (`takeTurn`, `queue`), so a short request goes before the rest of every long one (wangwu25685333 on X: a 5 KB request behind two long ones on 4 cores waited 8.3s in the order they came, 4.5s now). The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). Until the model is on disk the rules mask alone, and its download starts (`masking.fetch`, an hour between tries; the default's, done, saved by `settings.UseDefaultRedactModel` unless the user picked or turned it off meanwhile; cancelling it is turning it off). A model the user turned on that fails (didn't start, isn't on disk, held back after a failure) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`, strict); the default's finds nothing then, and the rules mask alone. A model that is only slow is waited for at most 2 seconds from the request's masking start when on by default (`masking.defaultWait`) and 15 seconds when the user turned it on (`masking.strictWait`): its turn, its load and its reading. Past that, or when the request's context ends first, `pii.FindContext` answers with what was known of the request's texts by then (its cache: the history read on earlier turns, and the chunks read meanwhile) and a `*pii.Partial` saying how many it hadn't read; `masking.model` masks those with the model's finds and the rest with the rules alone, logging it at most once a minute (`notePartial`), and the request goes. Nothing the rules mask goes as written. Before, the user's model was waited for with no bound and any end of the wait held the request back whole, its known finds thrown away: in a burst of requests with text the model hadn't read, xRayySummers on X (0.1.1877, Linux) saw masking take 1.2s to 290s in one minute and each request it ended was "masking failed, so nothing was sent". Reproduced on 8 cores of a Linux CPU: AstrLink Guard reads about 6 KB a second there (a 125 KB history 20.8s), and six requests at once with 67 to 145 KB of new tool results each took 62 to 110s, all ending near the last, since the turn goes round between chunks; with the bound each went at 15.0s with the history's finds and the model's for 1 to 4 of its 9 texts. `masking.find` gives a model that doesn't stop for its context 100ms to answer with what it knew (`handBack`) before giving up on it. AstrLink Guard reads on the CPU, so a long Codex history it hasn't seen took minutes there, and every request queued behind it showed masking with no bound (shensmart on Discord, 10-28, magpie in Docker). The wait is given up even where `Find` doesn't stop for its context. A request that stops waiting leaves the chunks after the one being read (`backend.find`), so it doesn't hold the turn; that chunk's answers are kept for the next request. Each model reads a request's unread texts newest first, the last text and a long one's last piece before the rest (`backend.missing`), since an agent's history is oldest first and what a request adds is at its end; AstrLink Guard joins them into chunks of 4 KB, not Privacy Filter's 12 KB (`backend.chunk`, `guardChunk`), so the chunk a request leaves the model finishing past its wait is about a second on 4 cores. The default's request is `pii.Bounded`: what one went without the model's reading is remembered by hash (`backend.sent`), and a request after it reads what it adds first and that backlog `backlogCap` (4 KB) at most, nothing found for the rest, so a history resumed or never read is read a little a request rather than on every core for each one. Measured on a 2 MB, 200-turn Codex history never read, 30 requests 3s apart (`TestLiveHistoryCost`, gated on `MAGPIE_GUARD_FILES`): on a 32-core Linux box 33 to 60 CPU seconds a request before, 23 minutes of CPU over the session's 108s (13 cores busy), 6 to 10 after, 4 minutes over 90s (2.7 cores), and on an M5 Pro's CoreML 2.2 CPU seconds a request for the first three before, the first alone after; nothing runs on after the last request either way. A request the user turned the model on for still reads all of it, to `strictWait`, but goes once only that backlog is left (`afterSent`, a `*pii.Partial`): such a text goes as it went on the same route (`redact.sentSpans`), so the model's finds in it only make a value known for later text (`learnLate`), and the model reads on after the request, to the request's own bound, keeping what it finds for the next. Before, a resumed or never-read history was read until the 15s ran out on every request: a 60-turn Claude Code session resumed (`TestRealLatencyOfALongSession`, gated on `GUARD_REAL_DIR`) waited 15s, 15s, 15s, 7.8s on 4 cores of a 32-core Linux box and 15s on eight requests in a row on one core (gaubeebangeel on X, 11-13: first tokens at 30-40s with masking on, 10-15s off). On another route such a text has the model's finds of now, none until it is read, and goes with the rules' alone; a value the model would have found late in it masks new text from the request after the read, not the one it went with. What a request adds is still waited for: 16 KB of new tool output a turn is about 3s on 4 cores and 8s on one, the model's reading on the CPU. + - With *Find with a local model* on (`masking.ModelWanted`: on by default since 10-28, `settings.RedactModel` the user turning it on and `RedactModelOff` off, this computer's own, kept by `KeepOwn`; a user with a model downloaded or picked and neither flag turned it off before the default, and `RedactModelAuto` marks the default's own download), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`), but for what the agent defines (its tools' and schemas' descriptions, under `defKeys`), which the rules alone mask, as with the model off, after the rest of the request so a value the model found in a message is masked there too as known: those were 52,577 of Claude Code 2.1.296's 67,532 bytes the model read, and a 4-core server's first request waited out the gateway's 2 minutes (niuniu_8964 on X; 11.5s cold at 4 procs on a Ryzen AI Max+, 2.6s without them, and on three real Claude Code requests the model masked nothing there the rules didn't); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor one word as a name where what is around it says a thing and nothing says a person: an app's name in a list of names alone, in a list of apps, or beside a thing's word (using, switched to, the … app, vs, 这个软件), so Privacy Filter's Cicada and Mimi in a chat about choosing apps go as written, while a full name, a Chinese name and a first name beside a relation, a greeting, said or he/she are masked as before, and a text of one first name alone goes as written by design (`thingNamed` in [`thingname.go`](../../internal/redact/thingname.go); ylorn. on Discord, whose follow-up questions had the names as written while the history had them as placeholders, so the vendor answered about another app), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). A package's name goes as written, for the model and the rules alike (dniray on Discord, v0.1.1917): the module a line of code loads (`from ' drizzle-orm '`, `require('jsonwebtoken')`, `from x import`, `use x::`, with an editor's line number or a diff's mark before it; `moduleAt`, `codeHead`), a manifest's dependency pinned at a version (`"drizzle-orm": "^0.36.4"`, TOML's `x = "9"`; `dependencyAt`), a folder under node_modules or site-packages, the module an error could not find (`Cannot find module 'x'`, `No module named 'x'`; `missingModuleAt`), a package an install names (`pnpm add x`; `installedAt`) or pins with @ (`x@0.36.4`; `pinnedAt`), all in `packageAt`; a value known from an earlier mask (`knownSpans`) goes as written there too, since once the model took the name for a secret anywhere in a request it was masked on the import line as known (dniray, v0.1.1965), a requirement's name before its pinned version (`django-rest-passwordreset==1.4.0`; `pinnedAfter`), a lock file's integrity hash (`sha512-…`; `sriRe` in `namesThing`), a version as the value of a field named for a secret (`"js-tokens": "^4.0.0-beta.1"`; `versionValue` in `fieldAt` and `keyAt`), and a package pinned at its version as user@host has it (`js-tokens@4.0.0:` in pnpm-lock.yaml; `notPackagePin`); `TestPackageNamesGoAsWritten` and `TestModelPackageNamesNotMasked` hold them. A field named for a secret and set to nothing takes nothing from the field after it: the SECRET rules let a space stand after `=` or `:` (`password = hunter2` in a config), and `env -i UI_PASSWORD= UI_ADDR=127.0.0.1:39117 ./syncer` went with `UI_ADDR=127.0.0.1` as UI_PASSWORD's value (mx_albert on Discord); a value that is an assignment of its own after a space (`UI_ADDR=`, `addr=`, `--listen=`) is the next field, read with its own name, so a token there still masks (`fieldMatches`, `nextField` in `internal/redact/fieldvalue.go`; `TestEmptyFieldTakesNotTheNext`, `TestSecretBesideEmptyFieldMasks`). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with Privacy Filter a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name; 和 or 与 says so only after a person, 吴敏和郑浩 but not 判断和边界, 发 or 打 only as the verb, 发了个 but not 关键发现, and a sentence starts after punctuation, not after a space after code, `gh pr view` 易触发; xuanwo on X; 一下 only after a verb that asks a person, 问一下张伟 but not 改一下文案, a word any subject takes after it, 已经, 明天 or 他, only with a person's cue before it, and 说明 is no 说; zeewell on X), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left, and so is a common word that starts with one (`zhWords`: 文案, 文档, 方案; 毛利, 毛重, 毛巾, since 毛利 is a margin far more often than the Japanese surname, so 毛利低 goes as written: _kaichen on X, 10-28; the model still finds 毛利兰, and neither model nor rule masks 毛利小五郎), the model's own name too when it is that word whole. A name the model or the cues take is also no name when it is an ordinary word (`zhWordShaped`, `zhWordNotName`, the one check both go through): a colour (黄绿色, 红色, any that ends in 色 or is colour characters alone: hh05928822 on X after v0.1.1850), a word that starts with a surname from `zhWords` or `zhDict` (about 1,550 two-character words from jieba's dictionary, [`zhdict.txt`](../../internal/redact/zhdict.txt), its header saying how they were chosen; 边界, 应该, 尚可), or such a word with what makes a longer word after it (关键词, 关键字: wangjunxiao128 on X; 应用层, 毛利率), unless a role before it or a title after it says a person is meant (客户方圆, 江山老师), where a name that is also a word is masked. The surnames stay (黄 starts 黄绿色 and 黄晓明), and 毛利兰, 关羽 and 黄晓明 are still masked. With AstrLink Guard only a nickname is (小王, 老李, `zhNick`; `redact.Options.NamesByModel`): Guard at 0.8 finds the full names those cues did in zhname_test's sentences (张伟, 陈建国, 欧阳娜娜…), and misses the nicknames, 孙经理, and all but the surname of 王老板 and 邓总; the cues took words for names (关键发现; xuanwo on X). The model is the user's pick (`settings.RedactModelName`, `pii.Choose`; the app's menu beside the switch, `pmPick`): AstrLink Guard (QuantumNous/astrlink-guard at a pinned revision, Apache-2.0, a 39 MB int8 Multilingual-MiniLM token classifier for Chinese and English), run in magpie's own process on the CPU by [`internal/pii/guard`](../../internal/pii/guard) (an ONNX reader, the XLM-R tokenizer and int8 kernels in Go, NEON/SDOT on arm64 and SSE2 on amd64; its labels named as Privacy Filter's, `guardLabels`); a text over one window, 510 tokens, is read in windows that overlap by 128, and on the CPU as many windows at once as it has cores, half of `GOMAXPROCS` and 4 at most (`guard.Cores`: on every core a long history unread kept a 32-core Linux box at 13 cores' worth for as long as requests came, xinvxueyuan and shensmart on Discord, 10-28): one window's matmuls split over the cores left them idle between, and a 4-core server's first Claude Code request waited minutes (niuniu_8964 on X; 22,488 tokens took 23.9s at 4 procs, 17.9s at once, and 48.8s against 30.5s at 2), and on a Mac through CoreML on the Neural Engine or the GPU ([`coreml.go`](../../internal/pii/guard/coreml.go), [`internal/pii/guard/coreml`](../../internal/pii/guard/coreml); yyhhyyyyyy on X; Settings › Privacy names which, from CoreML's own compute plan of the compiled model, `MLComputePlan` on macOS 14.4 and later, the device most of its program's estimated cost is on (`coreml.Plan`, `Model.Backend`, `Status.Via` and `Device`): it said "on the CPU" under CoreML, yyhhyyyyyy on Discord, 10-27; an M5 Pro's plan puts all of it on the GPU; after a CoreML read fails it says the CPU and why until one doesn't): the same network from the same int8 weights in float16, written from the downloaded model into a program made by `coreml_gen.py` and compiled once into the model's folder, 512 tokens in about 12 ms where the CPU takes 400, its probabilities within .07 of the publisher's fp32 model where the CPU's are within .13 (the CPU quantizes activations as the int8 model does, CoreML doesn't), so a span near the threshold can fall the other side (a go.mod module path is a secret at .81 on CoreML, .79 on the CPU, .785 in fp32); a window under 16 tokens (`coremlMin`), a Mac before macOS 13 or any failure goes to the CPU, loaded on the first request and let go after 10 minutes with none; or OpenAI's Privacy Filter. With no pick it is AstrLink Guard, the default; a user who had Privacy Filter on before there was a choice keeps it only while AstrLink Guard downloads, which the first masked request starts and which then saves AstrLink Guard as the pick (`masking.picked`, `toGuard`; an hour between tries after a failure). Measured for that default (#3578): on 234 segments of real code and config it found 2 spans where Privacy Filter found 100 (38 of them go.sum hashes after redact's own checks), and with the rules it found 42 of 42 test values to Privacy Filter's 41. Each model has its own download, cache file and turn (`backend`). AstrLink Guard's turn has `guard.Cores()` places (`guardTurn`), so that many requests read at once, and they share those cores: every window, of any request, takes one of `guard.Cores()` tokens before it reads and more only while they are free (`guard.take`), so requests together never read on more cores than one did (the 4 promised xinvxueyuan and shensmart above); the model loads once (`guardLoading`), the idle timer lets go only when no place is held (`guardIdle`), and a text one request is reading another waits for rather than reading it too (`backend.reading`). Before, one request read at a time, and an agent's parallel requests queued behind it (yyhhyyyyyy on Discord, 10-28, who asked for 16 at once). Measured at 1, 2, 4 and 8 requests at once (a Ryzen AI Max+ 395 under WSL, 4 cores): 512-byte requests 4.2, 6.1, 8.1 and 8.4 a second where one at a time was 4.2 whatever came, on 1.9 to 3.9 cores, memory flat at about 150 MB; 4 KB requests already read their 3 windows on 3.6 cores alone, so they stay at 0.6 a second (Windows on the same box: 7.5 to 12.1 a second at 1 to 8, 4 KB 0.7 to 0.8, on at most 3.8 cores). Each request on cores of its own would read 20 a second at 8, on 12 cores, and 4 KB at 8 took 20 cores and 521 MB (953 MB on an M5 Pro), so the bound is the cores, not the count, and there is no setting for it. Through CoreML the GPU is the bound: on an M5 Pro 4 KB requests read 23, 20, 25 and 25 a second at 1, 2, 4 and 8, a model per request no faster, so CoreML reads one window at a time, and only the windows under `coremlMin` or after a failure use the CPU's tokens. Both find at a floor of 0.5 (`pii.Floor`) and give each span its score (AstrLink Guard: the least of its tokens' probabilities, rounded to a float32 so a cached span reads back the same; Privacy Filter: pf-serve's own), and masking keeps those at the model's threshold or over (`pii.Threshold` in `masking.model`): the user's for that model (`settings.RedactModelScore`, this computer's own; Settings → Privacy's Confidence threshold, `pmScore`, 0.5 to 0.95), else the model's own (`MinScore`: Privacy Filter 0.5, AstrLink Guard 0.8, its publisher's). A value known from before follows the same threshold: each value masked remembers the highest score anything found it with (a rule's counts as sure), and one only the model found, under the threshold now, is no longer masked again as known (`noteScores`, `knownSpans` in [`known.go`](../../internal/redact/known.go); before, a raised slider changed nothing for a value masked once: _kaichen on X, 10-28). The defaults stay because on the eval a higher one mostly loses values the checks after the model would have kept (Privacy Filter at 0.85 lost a Chinese name; AstrLink Guard at 0.9 a phone in a tool result), while the false alarms it would drop are mostly dropped by those checks already (Yayoi_no_yume on X). Measured again on 2000 segments of real agent traffic (Codex and Claude Code sessions: prompts, tool arguments and results, a quarter with Chinese) and 30 more labelled cases: AstrLink Guard at 0.88 rather than 0.8 drops 3 false alarms (a model id, a sandbox path word, a token counter) and lets a colleague's name and a signed name through; Privacy Filter at 0.88 rather than 0.5 drops 11 (timestamps in paths, log lines, a plugin id) and lets 6 real names and a phone through (4 of the names in the real traffic). Lowering Guard to 0.5 finds 2 more names in the real traffic and 3 more labelled values, for 10 more false alarms (9 of them Claude Code's `` counter). Those false alarms are shapes a check can turn away; a threshold can't without losing real values. Privacy Filter is a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590; every pf-serve keeps the engine's own MoE chunk, `PF_MOE_CHUNK` at the window's 4096, which an RX 470 through Vulkan read 6-9% faster than 2048 in interleaved runs and Metal ~6% faster, and inherits a value the user set): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, through magpie's proxy (`netproxy.Func`, as its other requests; hh0592821 on Discord, whose download went direct before), from hf-mirror first in China (`source.chinaFirst`) and from hf-mirror after Hugging Face everywhere else, the switch off too (`source.modelMirror`), so a poisoned or blocked huggingface.co doesn't stop it; hf-mirror serves AstrLink Guard's files itself and sends Privacy Filter's back to Hugging Face) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request, in the model's folder and given the model's file name, never its path (a Windows C program's argv is in the ANSI code page and ggml reads it as UTF-8, so a user folder named in Chinese failed every load with the path in mojibake, AIMetaPhD on X; a pf-serve error that names the file is shown with the whole path) (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (`pieces`: after a line's end, else a space, of those in the piece's second half the one whose 48 bytes before it hash least (`landmark`), so a line edited early in a text leaves the pieces after it as they were, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (`merge`: one found twice is one, one cut by a piece's end is whole), and a value of 8 bytes or more found in a text is found wherever else it is in it, as sure as its surest find (`spread`: the model scored an address on 400 lines alike 0.9 on some and 0.5 on most, wangwu25685333 on X), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (`found-.bin` beside the model: hashes, offsets, labels and each span's score, never text; a `pfound01` file from before scores is read with every span sure, so it masks as it did; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, by the request waiting with the least left to read (`takeTurn`, `queue`), so a short request goes before the rest of every long one (wangwu25685333 on X: a 5 KB request behind two long ones on 4 cores waited 8.3s in the order they came, 4.5s now). The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). Until the model is on disk the rules mask alone, and its download starts (`masking.fetch`, an hour between tries; the default's, done, saved by `settings.UseDefaultRedactModel` unless the user picked or turned it off meanwhile; cancelling it is turning it off). A model the user turned on that fails (didn't start, isn't on disk, held back after a failure) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`, strict); the default's finds nothing then, and the rules mask alone. A model that is only slow is waited for at most 2 seconds from the request's masking start when on by default (`masking.defaultWait`) and 15 seconds when the user turned it on (`masking.strictWait`): its turn, its load and its reading. Once a request the user turned it on for runs out its 15 seconds with texts unread, the model is behind, and the next requests wait only the default's 2 seconds until one is read whole or a minute passes (`masking.behind`, `waitFor`): before, each request in a burst waited the full 15 seconds while the backlog grew, serially, so routing waited past the gateway's 30s (vsoullai on X, #4856; `TestStrictModelBehindWaitsTheDefault`). 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, to `strictWait`, but goes once only that backlog is left (`afterSent`, a `*pii.Partial`): such a text goes as it went on the same route (`redact.sentSpans`), so the model's finds in it only make a value known for later text (`learnLate`), and the model reads on after the request, to the request's own bound, keeping what it finds for the next. Before, a resumed or never-read history was read until the 15s ran out on every request: a 60-turn Claude Code session resumed (`TestRealLatencyOfALongSession`, gated on `GUARD_REAL_DIR`) waited 15s, 15s, 15s, 7.8s on 4 cores of a 32-core Linux box and 15s on eight requests in a row on one core (gaubeebangeel on X, 11-13: first tokens at 30-40s with masking on, 10-15s off). On another route such a text has the model's finds of now, none until it is read, and goes with the rules' alone; a value the model would have found late in it masks new text from the request after the read, not the one it went with. What a request adds is still waited for: 16 KB of new tool output a turn is about 3s on 4 cores and 8s on one, the model's reading on the CPU. - 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/agent/wsl.go b/internal/agent/wsl.go index 75c851d18..a346962f5 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -1210,8 +1210,12 @@ func wslHomes() []sessions.WSLHome { if !wslLooks() { return nil } + return wslHomesOf(wslDistros()) +} + +func wslHomesOf(ds []distro) []sessions.WSLHome { var out []sessions.WSLHome - for _, d := range wslDistros() { + for _, d := range ds { if d.Root == "" || d.Home == "" { continue } @@ -1255,10 +1259,14 @@ var wslAntigravityDirs = []string{".gemini/antigravity", ".gemini/antigravity-in // copilotWSLDirs are the Copilot CLI's folders, as magpie opens them (where // a link leads, #4502), in the running distros it was found in, for // provider to read its sign-in in; none off Windows. A stopped distro is -// left out: reading it would start it. +// left out: reading it would start it. It is asked on a request's path +// (provider's accounts), so it waits for WSL at most wslRunningWait. func copilotWSLDirs() []string { + if !wslLooks() { + return nil + } var out []string - for _, h := range wslHomes() { + for _, h := range wslHomesOf(wslDistrosWithin(wslRunningWait)) { if h.Running && wslHasCopilot(h.Distro) { out = append(out, h.Open(filepath.Join(h.Home, wslCopilotDir))) } @@ -1301,8 +1309,7 @@ const ( // which would start it again (TJHHHH on Discord) wslRunningAge = 3 * time.Second // wslRunningFailedAge is how long wsl.exe failing to say is kept: each - // ask that times out holds wsl's lock, and so the GUI, for 10s, and - // leaves a wsl.exe behind (#2341) + // ask that times out takes 10s and leaves a wsl.exe behind (#2341) wslRunningFailedAge = 30 * time.Second ) @@ -1371,12 +1378,34 @@ var wslRun = func(timeout time.Duration, args ...string) ([]byte, error) { return out, err } -// wslRoot is where magpie opens a running distro's / from; a var for tests. +// wslRootWait is how long wslRoot waits for Windows to open a distro's +// /: a stat of WSL's file share can't be cancelled, and hangs while WSL +// does. A var for tests. +var wslRootWait = 5 * time.Second + +// wslStat is os.Stat, for wslRoot; a var for tests. +var wslStat = os.Stat + +// wslRoot is where magpie opens a running distro's / from, "" when +// Windows didn't open it within wslRootWait (the probe failed, and is +// tried again in wslRetryAge); a var for tests. var wslRoot = func(name string) string { - if _, err := os.Stat(`\\wsl.localhost\` + name + `\`); err == nil { - return `\\wsl.localhost\` + name + ok, stat := make(chan bool, 1), wslStat + go func() { + _, err := stat(`\\wsl.localhost\` + name + `\`) + ok <- err == nil + }() + t := time.NewTimer(wslRootWait) + defer t.Stop() + select { + case found := <-ok: + if found { + return `\\wsl.localhost\` + name + } + return `\\wsl$\` + name // before Windows 11 / WSL 0.50 + case <-t.C: + return "" } - return `\\wsl$\` + name // before Windows 11 / WSL 0.50 } // wslHungPath, while recent, says a wsl.exe listing timed out: each @@ -1405,39 +1434,48 @@ func wslHung(hung bool) { func wslStatePath() string { return filepath.Join(filepath.Dir(provider.Path()), "wsl.json") } -func wslDistros() []distro { +// wslRefreshMu is held by the one refresh of what magpie knows of WSL +// (wslRefresh) at a time. wsl.exe and the distros' files are asked while +// it is held, never under wsl's own lock: that is taken only to read and +// write what they said. A probe, a listing or an open of a distro's / +// that hangs held wsl's lock before, so the GUI listing agents, a +// request's stand-in and Copilot's sign-in all waited on a hung wsl.exe, +// and the gateway sent 504s after 30s (vsoullai on X, #6167). +var wslRefreshMu sync.Mutex + +// wslRefresh lists the distros again when the list is older than +// wslListAge, asks which run, and probes the running ones not probed yet. +func wslRefresh() { + wslRefreshMu.Lock() + defer wslRefreshMu.Unlock() wsl.Lock() - defer wsl.Unlock() - if wsl.seen == nil { - wsl.seen, wsl.probed, wsl.failed = map[string]*distro{}, map[string]bool{}, map[string]time.Time{} - if b, err := os.ReadFile(wslStatePath()); err == nil { - json.Unmarshal(b, &wsl.seen) - } - wslForgetOldBins() - } - if time.Since(wsl.at) > wslListAge { - if wsl.at.IsZero() && wslHungLately() { - // another magpie waited out a hung wsl.exe moments ago: a - // command doesn't wait 10s more (this one lists again in a minute) - wsl.names, wsl.listed = nil, false - } else { + wslLoadLocked() + list := time.Since(wsl.at) > wslListAge + // another magpie waited out a hung wsl.exe moments ago: a command + // doesn't wait 10s more (this one lists again in a minute) + skip := list && wsl.at.IsZero() && wslHungLately() + wsl.Unlock() + if list { + var names []string + var listed bool + if !skip { start := time.Now() - wsl.names, wsl.listed = wslList("-l", "-q") - wslHung(!wsl.listed && time.Since(start) >= wslHungAfter) + names, listed = wslList("-l", "-q") + wslHung(!listed && time.Since(start) >= wslHungAfter) } - wsl.at = time.Now() - if !wsl.listed || len(wsl.names) == 0 { + wsl.Lock() + wsl.names, wsl.listed, wsl.at = names, listed, time.Now() + if !listed || len(names) == 0 { // none to run: a wsl.exe that couldn't list them isn't asked - // again which run, another timeout under the lock the GUI waits on - wsl.running, wsl.runOK, wsl.runAt = map[string]bool{}, wsl.listed, time.Now() + // again which run + wsl.running, wsl.runOK, wsl.runAt = map[string]bool{}, listed, time.Now() } + wsl.Unlock() } - wslRunningLocked() - installed := map[string]bool{} - cfg := wslConfig() - var out []distro + wslRunningWithin(-1) + wsl.Lock() + var probe []string for _, n := range wsl.names { - installed[n] = true // a distro that stopped is probed again once it runs: WSL may have // been restarted meanwhile in another networking mode if !wsl.running[n] { @@ -1445,41 +1483,126 @@ func wslDistros() []distro { } if wsl.running[n] && !wsl.probed[n] { if t, ok := wsl.failed[n]; !ok || time.Since(t) > wslRetryAge { - if d := wslProbe(n); d == nil { - wsl.failed[n] = time.Now() - } else { - wsl.probed[n] = true - if wslKept(*d) { - if old := wsl.seen[n]; old != nil { - d.Values = old.Values - d.Was = wslWas(old.Was, old.Gateway, d.Gateway) - } - wsl.seen[n] = d - } else { - delete(wsl.seen, n) - } - wsl.dirty = true - } + probe = append(probe, n) } } + } + wsl.Unlock() + for _, n := range probe { + d := wslProbe(n) + wsl.Lock() + if d == nil { + wsl.failed[n] = time.Now() + } else { + wsl.probed[n] = true + if wslKept(*d) { + if old := wsl.seen[n]; old != nil { + d.Values = old.Values + d.Was = wslWas(old.Was, old.Gateway, d.Gateway) + } + wsl.seen[n] = d + } else { + delete(wsl.seen, n) + } + wsl.dirty = true + } + wsl.Unlock() + } + wsl.Lock() + defer wsl.Unlock() + // an unregistered distro is forgotten + if wsl.listed { + installed := map[string]bool{} + for _, n := range wsl.names { + installed[n] = true + } + for n := range wsl.seen { + if !installed[n] { + delete(wsl.seen, n) + wsl.dirty = true + } + } + } + wslSaveLocked() +} + +// wslLoadLocked reads wsl.json the first time it is wanted. +func wslLoadLocked() { + if wsl.seen != nil { + return + } + wsl.seen, wsl.probed, wsl.failed = map[string]*distro{}, map[string]bool{}, map[string]time.Time{} + if b, err := os.ReadFile(wslStatePath()); err == nil { + json.Unmarshal(b, &wsl.seen) + } + wslForgetOldBins() +} + +// wslDistros are the distros agents were found in, after a refresh +// (wslRefresh), which this waits for: for the GUI and what runs in the +// background. A request's path takes wslDistrosWithin. +func wslDistros() []distro { + wslRefresh() + return wslKnown() +} + +// wslBg is the refresh wslDistrosWithin started, while it runs. +var wslBg struct { + sync.Mutex + done chan struct{} +} + +// wslDistrosWithin is wslDistros waiting at most wait for the refresh, +// one at a time in the background: what is known then is answered, and +// a distro whose running wsl.exe hasn't said in time is taken as stopped. +func wslDistrosWithin(wait time.Duration) []distro { + wslBg.Lock() + if wslBg.done == nil { + done := make(chan struct{}) + wslBg.done = done + go func() { + wslRefresh() + wslBg.Lock() + wslBg.done = nil + wslBg.Unlock() + close(done) + }() + } + done := wslBg.done + wslBg.Unlock() + t := time.NewTimer(wait) + defer t.Stop() + select { + case <-done: + case <-t.C: + } + return wslKnown() +} + +// wslKnown are the distros as last refreshed, each with whether it runs: +// none does while wsl.exe is being asked and its last answer is older +// than wslRunningAge. +func wslKnown() []distro { + asking := wslRunAsking() + cfg := wslConfig() + wsl.Lock() + wslLoadLocked() + known := !asking || wslRunFreshLocked() + var out []distro + for _, n := range wsl.names { d := wsl.seen[n] if d == nil { continue } c := *d - c.Running = wsl.running[n] + c.Running = known && wsl.running[n] c.up = func() bool { return wslUp(n) } - c.mirror(cfg) out = append(out, c) } - // an unregistered distro is forgotten - for n := range wsl.seen { - if wsl.listed && !installed[n] { - delete(wsl.seen, n) - wsl.dirty = true - } + wsl.Unlock() + for i := range out { + out[i].mirror(cfg) } - wslSaveLocked() return out } @@ -1522,25 +1645,86 @@ func wslForgetOldBins() { } } -// wslRunningLocked lists the running distros again (wsl.exe -l --running, -// which starts none) when the last list is older than wslRunningAge. When -// wsl.exe can't say, none is taken to run: a distro is never opened on a -// guess. -func wslRunningLocked() { +// wslRunAsk is the wsl.exe -l --running in flight, and when it started. +// It is asked outside wsl's lock, once at a time however many wait on it. +var wslRunAsk struct { + sync.Mutex + done chan struct{} + start time.Time +} + +// wslRunningWait is how long what reads a distro's files waits for +// wsl.exe to say which run, from when it was asked: one that hangs is +// taken as running none, and a stand-in, a request's or Copilot's +// sign-in, goes without the distro's files rather than waiting out its +// 10s (vsoullai on X, #6167). A var for tests. +var wslRunningWait = 2 * time.Second + +// wslRunFreshLocked is whether which distros run is as wsl.exe said at +// most wslRunningAge ago (wslRunningFailedAge when it couldn't say). +func wslRunFreshLocked() bool { age := wslRunningAge if !wsl.runOK { age = wslRunningFailedAge } - if !wsl.runAt.IsZero() && time.Since(wsl.runAt) <= age { - return + return !wsl.runAt.IsZero() && time.Since(wsl.runAt) <= age +} + +// wslRunAsking is whether wsl.exe is being asked which distros run. +func wslRunAsking() bool { + wslRunAsk.Lock() + defer wslRunAsk.Unlock() + return wslRunAsk.done != nil +} + +// wslRunningWithin lists the running distros again (wsl.exe -l +// --running, which starts none) when the last list is older than +// wslRunningAge, and waits for the answer at most wait from when it was +// asked (a negative wait: until wsl.exe answers or times out). false: +// wsl.exe hasn't said in time, and none is to be taken to run. When +// wsl.exe can't say, none is taken to run either: a distro is never +// opened on a guess. Never called under wsl's lock. +func wslRunningWithin(wait time.Duration) bool { + wsl.Lock() + fresh := wslRunFreshLocked() + wsl.Unlock() + if fresh { + return true } - run, ok := wslList("-l", "--running", "-q") - wsl.runOK = ok - wsl.running = map[string]bool{} - for _, n := range run { - wsl.running[n] = true + wslRunAsk.Lock() + if wslRunAsk.done == nil { + done := make(chan struct{}) + wslRunAsk.done, wslRunAsk.start = done, time.Now() + go func() { + run, ok := wslList("-l", "--running", "-q") + wsl.Lock() + wsl.runOK = ok + wsl.running = map[string]bool{} + for _, n := range run { + wsl.running[n] = true + } + wsl.runAt = time.Now() + wsl.Unlock() + wslRunAsk.Lock() + wslRunAsk.done = nil + wslRunAsk.Unlock() + close(done) + }() + } + done, start := wslRunAsk.done, wslRunAsk.start + wslRunAsk.Unlock() + if wait < 0 { + <-done + return true + } + t := time.NewTimer(time.Until(start.Add(wait))) + defer t.Stop() + select { + case <-done: + return true + case <-t.C: + return false } - wsl.runAt = time.Now() } // wslUp is whether distro runs, as wsl.exe said at most wslRunningAge ago: @@ -1548,9 +1732,11 @@ func wslRunningLocked() { // catalog synced, requests counted, sessions listed) asks it first, so a // distro stopped since its agent was made isn't started again. func wslUp(distro string) bool { + if !wslRunningWithin(wslRunningWait) { + return false + } wsl.Lock() defer wsl.Unlock() - wslRunningLocked() return wsl.running[distro] } @@ -1623,7 +1809,7 @@ func wslLastSeen(name, key string) string { // wslReady are the distros running now that the probe found kind in, each // with its mirrored networking settled, ready for a read of its files. -// Only magpie's memory of them and which run (wslRunningLocked) are +// Only magpie's memory of them and which run (wslRunningWithin) are // asked — nothing is probed, and a stopped distro is never opened. // Detection off (wslLooks) reads none: a request's stand-in asks wsl.exe // nothing, which on a machine without WSL would answer with a console @@ -1632,8 +1818,10 @@ func wslReady(kind string) []distro { if !wslLooks() { return nil } + if !wslRunningWithin(wslRunningWait) { + return nil + } wsl.Lock() - wslRunningLocked() var ds []distro for _, n := range wsl.names { if d := wsl.seen[n]; d != nil && wsl.running[n] && wslKindOf(kind).found(*d) { @@ -1667,8 +1855,10 @@ func wslClaudeClassifier(model string) string { if !wslLooks() { return "" } + if !wslRunningWithin(wslRunningWait) { + return "" + } wsl.Lock() - wslRunningLocked() var ds []distro for _, n := range wsl.names { if d := wsl.seen[n]; d != nil && wsl.running[n] && wslKindOf("claude").found(*d) { @@ -1824,7 +2014,9 @@ func wslProbe(name string) *distro { return nil } if wslKept(*d) { - d.Root = wslRoot(name) + if d.Root = wslRoot(name); d.Root == "" { + return nil + } } return d } diff --git a/internal/agent/wsl_fake.go b/internal/agent/wsl_fake.go index 494ef4909..d6473c446 100644 --- a/internal/agent/wsl_fake.go +++ b/internal/agent/wsl_fake.go @@ -29,10 +29,13 @@ func FakeWSL(probes, roots map[string]string) func() { names = append(names, n) } list := []byte(strings.Join(names, "\n")) + var stoppedMu sync.Mutex // wsl.exe is asked outside wsl's lock stopped := map[string]bool{} fakeStop = func(name string, stop bool) { - wsl.Lock() + stoppedMu.Lock() stopped[name] = stop + stoppedMu.Unlock() + wsl.Lock() wsl.runAt = time.Time{} wsl.Unlock() } @@ -46,11 +49,13 @@ func FakeWSL(probes, roots map[string]string) func() { return list, nil case "-l --running -q": var run []string + stoppedMu.Lock() for _, n := range names { if !stopped[n] { run = append(run, n) } } + stoppedMu.Unlock() return []byte(strings.Join(run, "\n")), nil } if len(args) > 2 && args[0] == "-d" { diff --git a/internal/agent/wsl_hang_test.go b/internal/agent/wsl_hang_test.go new file mode 100644 index 000000000..f86996079 --- /dev/null +++ b/internal/agent/wsl_hang_test.go @@ -0,0 +1,153 @@ +package agent + +import ( + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// vsoullai on X, #6167: a WSL that hangs (a distro stopping, WSL's file +// share wedged) held wsl's lock while the GUI listed agents, so a +// request's stand-in and Copilot's sign-in (provider's accounts, on every +// request's path) waited on it, the gateway's unrouted watch sent 504s +// after 30s, and the Copilot sign-in's own lock queued every request +// behind the first. Whatever hangs, wsl.exe listing which run, a distro's +// probe or the open of its /, what a request asks of WSL answers within +// wslRunningWait, as running none when wsl.exe hasn't said. +func TestWSLHangHoldsNoRequest(t *testing.T) { + for _, hang := range []string{"-l --running -q", "-d Ubuntu", "stat"} { + t.Run(hang, func(t *testing.T) { + root, home := codexDistroHome(t, "model_provider = \"magpie\"\nmodel = \"relay/main\"\n") + os.MkdirAll(filepath.Join(home, ".copilot"), 0o755) + fakeWSL(t, "Ubuntu\r\n", "Ubuntu\r\n", map[string]string{ + "Ubuntu": "home:/home/me\ndir:.codex\ndir:.copilot\nroute:default via 172.20.0.1 dev eth0\n", + }, map[string]string{"Ubuntu": root}) + // a first look while WSL answered: Ubuntu is known, with Codex + if ds := wslDistros(); len(ds) != 1 || !ds[0].Running { + t.Fatalf("%+v", ds) + } + wait := wslRunningWait + wslRunningWait = 200 * time.Millisecond + t.Cleanup(func() { wslRunningWait = wait }) + + release := make(chan struct{}) + var once sync.Once + free := func() { once.Do(func() { close(release) }) } + hung := make(chan struct{}, 8) + run, root0 := wslRun, wslRoot + wslRun = func(d time.Duration, args ...string) ([]byte, error) { + if strings.HasPrefix(strings.Join(args, " "), hang) { + hung <- struct{}{} + <-release + } + return run(d, args...) + } + if hang == "stat" { + // Windows' open of the distro's / over WSL's share hangs + wslRoot = func(name string) string { + hung <- struct{}{} + <-release + return root0(name) + } + } + gui := make(chan struct{}) + t.Cleanup(func() { + free() + <-gui + wslSettle() + wslRun, wslRoot = run, root0 + }) + + // the GUI looks again (a rescan): it waits on the hung wsl.exe + wsl.Lock() + wsl.runAt = time.Time{} + wsl.probed, wsl.failed = map[string]bool{}, map[string]time.Time{} + wsl.Unlock() + go func() { defer close(gui); wslDistros() }() + select { + case <-hung: + case <-time.After(10 * time.Second): + t.Fatal("the hang was never reached") + } + + bar := wslRunningWait + 2*time.Second + within := func(name string, f func()) { + t.Helper() + done := make(chan struct{}) + start := time.Now() + go func() { defer close(done); f() }() + select { + case <-done: + case <-time.After(bar): + t.Errorf("%s waited on a hung WSL past %v", name, bar) + free() + <-done + } + if d := time.Since(start); d > bar { + t.Errorf("%s took %v", name, d) + } + } + within("a Codex stand-in", func() { wslCodexStandIn() }) + within("a Claude classifier stand-in", func() { wslClaudeClassifier("claude-haiku-4-5") }) + within("whether Ubuntu runs", func() { wslUp("Ubuntu") }) + within("Copilot's folders", func() { copilotWSLDirs() }) + within("a path's distro", func() { distroAt(filepath.Join(root, "home", "me")) }) + within("a host a distro reached Windows at", func() { wslHost("http://172.20.0.1:3425") }) + within("what WSLKeep kept", func() { WSLKept("Ubuntu", "x") }) + select { + case <-gui: + t.Fatal("the GUI's look didn't wait on the hung WSL") + default: + } + // many requests at once don't queue behind each other + var wg sync.WaitGroup + start := time.Now() + for range 13 { + wg.Add(1) + go func() { defer wg.Done(); copilotWSLDirs(); wslCodexStandIn() }() + } + wg.Wait() + if d := time.Since(start); d > bar { + t.Errorf("13 requests at once took %v", d) + } + }) + } +} + +// wslSettle waits for a look and an ask of wsl.exe started in the +// background to end. +func wslSettle() { + for _, m := range []func() chan struct{}{ + func() chan struct{} { wslBg.Lock(); defer wslBg.Unlock(); return wslBg.done }, + func() chan struct{} { wslRunAsk.Lock(); defer wslRunAsk.Unlock(); return wslRunAsk.done }, + } { + if ch := m(); ch != nil { + <-ch + } + } +} + +// A distro's / that Windows can't open in wslRootWait (a stat of WSL's +// share can't be cancelled) fails its probe, tried again in wslRetryAge, +// instead of holding the look for ever. +func TestWSLRootHangFailsProbe(t *testing.T) { + stat, w := wslStat, wslRootWait + release := make(chan struct{}) + t.Cleanup(func() { close(release); wslStat, wslRootWait = stat, w }) + wslRootWait = 100 * time.Millisecond + wslStat = func(string) (os.FileInfo, error) { <-release; return nil, os.ErrNotExist } + start := time.Now() + if r := wslRoot("Ubuntu"); r != "" { + t.Fatalf("root %q", r) + } + if d := time.Since(start); d > 2*time.Second { + t.Fatalf("waited %v", d) + } + wslStat = func(string) (os.FileInfo, error) { return nil, nil } + if r := wslRoot("Ubuntu"); r != `\\wsl.localhost\Ubuntu` { + t.Fatalf("root %q", r) + } +} diff --git a/internal/agent/wsl_links.go b/internal/agent/wsl_links.go index 7d0581857..894d9d8f1 100644 --- a/internal/agent/wsl_links.go +++ b/internal/agent/wsl_links.go @@ -26,10 +26,12 @@ var wslExec = func(distro string, argv ...string) ([]byte, error) { // distroAt is the running distro local, a path as magpie opens it, is in: // under its root, or under where one of its Links leads (distro.native). func distroAt(local string) (distro, bool) { + // a command run in a stopped distro would start it (wslUp) + if !wslRunningWithin(wslRunningWait) { + return distro{}, false + } wsl.Lock() defer wsl.Unlock() - // a command run in a stopped distro would start it (wslUp) - wslRunningLocked() for name, d := range wsl.seen { if d == nil || d.Root == "" || !wsl.running[name] { continue diff --git a/internal/agent/wsl_test.go b/internal/agent/wsl_test.go index e3d5af108..59a0e9922 100644 --- a/internal/agent/wsl_test.go +++ b/internal/agent/wsl_test.go @@ -327,7 +327,7 @@ func TestWSLListFails(t *testing.T) { // requests it made. None of them opens the stopped distro, which would // start it: its fields read as last seen, and the next look neither probes // #2341: wsl.exe failing to say which distros run (a hung WSL times out -// after 10s, under wsl's lock) is asked again only after +// after 10s) is asked again only after // wslRunningFailedAge, not every wslRunningAge; an answer still lasts only // wslRunningAge. func TestWSLRunningFailedKept(t *testing.T) { diff --git a/internal/masking/masking.go b/internal/masking/masking.go index ab888f292..5795b0068 100644 --- a/internal/masking/masking.go +++ b/internal/masking/masking.go @@ -192,11 +192,38 @@ var defaultWait = 2 * time.Second // the same history, finds it. A var for tests. var strictWait = 15 * time.Second +// behind is when a request last ran out its strictWait with text of its +// own the model hadn't read (0: none since one was read in full). The +// model is behind then, on a CPU too slow for what the agents send, and +// every request waited all of strictWait for it: on Windows, with +// AstrLink Guard turned on, each request sat 15s, one after another +// (vsoullai on X, #4856). For behindAge after, or until a request is read +// in full, a request waits defaultWait, as the model on by default does: +// what it read is masked with its finds and the rest by the rules, so +// nothing the rules mask goes as written, and what it reads meanwhile is +// kept for the next turn. +var behind atomic.Int64 + +const behindAge = time.Minute + +// waitFor is how long a request waits for the model: strictWait when the +// user turned it on, unless it is behind. +func waitFor(strict bool) time.Duration { + if !strict { + return defaultWait + } + if t := behind.Load(); t != 0 && time.Since(time.Unix(0, t)) < behindAge { + return min(defaultWait, strictWait) + } + return strictWait +} + // model is the local model m (internal/pii) as redact's Model, keeping // what it is at least min sure of, waited for until ctx ends or the wait // runs out: defaultWait for the model on by default, strictWait for one -// the user turned on (strict), from now. A wait that runs out, or a ctx -// that ends, keeps what the model had read of the texts by then (a +// the user turned on (strict) unless it is behind (waitFor), from now. A +// wait that runs out, or a ctx that ends, keeps what the model had read +// of the texts by then (a // pii.Partial), and the rules mask the rest alone. A model that fails // (didn't load, isn't on disk, held back after a failure) panics where // the user turned it on, and the request is held back (gwmw.Safely) @@ -204,10 +231,7 @@ var strictWait = 15 * time.Second // model's, and it is broken, not busy. On by default, it finds nothing // then: the rules mask alone. func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Model { - wait := defaultWait - if strict { - wait = strictWait - } + wait := waitFor(strict) by := time.Now().Add(wait) return func(texts []string) [][]redact.Found { if !strict { @@ -221,6 +245,11 @@ func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Mo switch { case errors.As(err, &p): notePartial(p, wait) + if strict && p.Missing > 0 && errors.Is(p.Err, context.DeadlineExceeded) { + // its own text wasn't read in time (not only a backlog + // sent before, nor a client that went away) + behind.Store(time.Now().UnixNano()) + } if len(got) != len(texts) { got = make([][]redact.Found, len(texts)) } @@ -228,6 +257,10 @@ func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Mo panic(err) case err != nil: return make([][]redact.Found, len(texts)) + default: + if strict { + behind.Store(0) + } } out := make([][]redact.Found, len(got)) for i, fs := range got { diff --git a/internal/masking/masking_test.go b/internal/masking/masking_test.go index 30fd1b0c5..e65fa8e21 100644 --- a/internal/masking/masking_test.go +++ b/internal/masking/masking_test.go @@ -220,6 +220,7 @@ func TestDefaultModelHangingIsTheRules(t *testing.T) { // TestStrictModelStalledIsTheRulesForWhatItDidntRead's) wasStrict := strictWait strictWait = time.Hour + behind.Store(0) // not behind: a strict wait is waited whole t.Cleanup(func() { strictWait = wasStrict }) done := make(chan any, 1) go func() { @@ -276,7 +277,7 @@ func TestStrictModelStalledIsTheRulesForWhatItDidntRead(t *testing.T) { fetch = func(pii.Model, bool) {} onDisk = func() bool { return true } strictWait = 200 * time.Millisecond - t.Cleanup(func() { picked, fetch, onDisk, strictWait = wasPicked, wasFetch, wasDisk, wasWait }) + t.Cleanup(func() { picked, fetch, onDisk, strictWait = wasPicked, wasFetch, wasDisk, wasWait; behind.Store(0) }) key := "sk-ant-api03-" + strings.Repeat("a", 40) mask := func(body []byte) ([]byte, int, any) { @@ -322,6 +323,56 @@ func TestStrictModelStalledIsTheRulesForWhatItDidntRead(t *testing.T) { } } +// slow is a model that reads a text it has "seen" at once and needs +// longer than any wait for one it hasn't: a CPU too slow for what the +// agents send. +type slow struct{ fake } + +func (slow) Find(ctx context.Context, texts []string) ([][]redact.Found, error) { + missing := 0 + for _, s := range texts { + if strings.Contains(s, "unread") { + missing++ + } + } + if missing == 0 { + return make([][]redact.Found, len(texts)), nil + } + <-ctx.Done() + return make([][]redact.Found, len(texts)), &pii.Partial{Missing: missing, Of: len(texts), Err: ctx.Err()} +} + +// vsoullai on X, #4856 (Windows, the local model turned on): the model +// couldn't keep up, and each request waited all of strictWait for it, one +// after another. Once a request's own text wasn't read in its strictWait, +// the next wait defaultWait, until a request is read in full again. The +// rules mask what the model didn't read either way. +func TestStrictModelBehindWaitsTheDefault(t *testing.T) { + wasStrict, wasDefault := strictWait, defaultWait + strictWait, defaultWait = 2*time.Second, 50*time.Millisecond + behind.Store(0) + t.Cleanup(func() { strictWait, defaultWait = wasStrict, wasDefault; behind.Store(0) }) + m := slow{fake{installed: true}} + took := func(text string) time.Duration { + start := time.Now() + model(context.Background(), m, 0.8, true)([]string{text}) + return time.Since(start) + } + if d := took("unread tool result"); d < strictWait { + t.Fatalf("the first request didn't wait strictWait: %v", d) + } + for i := range 3 { + if d := took("unread tool result"); d >= strictWait/2 { + t.Fatalf("request %d after the model fell behind waited %v", i+2, d) + } + } + // a request read in full: the model caught up, strictWait again + took("read before") + if d := took("unread tool result"); d < strictWait { + t.Fatalf("after one read in full, a request waited %v", d) + } +} + // bounds is a model that says whether it was asked Bounded. type bounds struct { fake diff --git a/internal/provider/copilot_cli.go b/internal/provider/copilot_cli.go index cb4de01c9..6802b4548 100644 --- a/internal/provider/copilot_cli.go +++ b/internal/provider/copilot_cli.go @@ -66,11 +66,21 @@ var CopilotWSLDirs func() []string // read: its files are read over WSL's file share, slower than a disk's. var copilotWSLAge = 20 * time.Second +// copilotWSLWait is how long a request waits for a distro's sign-in to +// be read again, from when that read started: one read at a time, outside +// copilotWSL's lock, and a read WSL holds up answers the sign-in read +// before. Held under the lock, a hung WSL queued every request behind +// the first, and the gateway sent 504s after 30s (vsoullai on X, #6167). +// A var for tests. +var copilotWSLWait = 2 * time.Second + var copilotWSL struct { sync.Mutex - at time.Time - app copilotApp - ok bool + at time.Time + app copilotApp + ok bool + done chan struct{} // closed when the read in flight ends + start time.Time // when it started } // copilotCLILogin is the account the Copilot CLI is signed in to, with its @@ -90,18 +100,38 @@ func copilotCLILogin() (copilotApp, bool) { } c := &copilotWSL c.Lock() - defer c.Unlock() if !c.at.IsZero() && time.Since(c.at) < copilotWSLAge { + defer c.Unlock() return c.app, c.ok } - c.app, c.ok = copilotApp{}, false - for _, dir := range CopilotWSLDirs() { - if app, ok := copilotCLILoginIn(dir, nil); ok { - c.app, c.ok = app, true - break - } + if c.done == nil { + done, dirs := make(chan struct{}), CopilotWSLDirs + c.done, c.start = done, time.Now() + go func() { + var found copilotApp + ok := false + for _, dir := range dirs() { + if app, in := copilotCLILoginIn(dir, nil); in { + found, ok = app, true + break + } + } + c.Lock() + c.app, c.ok, c.at, c.done = found, ok, time.Now(), nil + c.Unlock() + close(done) + }() } - c.at = time.Now() + done, start := c.done, c.start + c.Unlock() + t := time.NewTimer(time.Until(start.Add(copilotWSLWait))) + defer t.Stop() + select { + case <-done: + case <-t.C: + } + c.Lock() + defer c.Unlock() return c.app, c.ok } diff --git a/internal/provider/copilot_wsl_hang_test.go b/internal/provider/copilot_wsl_hang_test.go new file mode 100644 index 000000000..5cbd1ef0a --- /dev/null +++ b/internal/provider/copilot_wsl_hang_test.go @@ -0,0 +1,106 @@ +package provider + +import ( + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +// vsoullai on X, #6167: the Copilot CLI's sign-in in a WSL distro is read +// on every request's path (the accounts), and was read under +// copilotWSL's lock: a WSL that hung held the first request and queued +// every other behind it until the gateway sent 504s. A read that hangs +// holds no request past copilotWSLWait, all of them at once included, +// and the sign-in read before is answered meanwhile. +func TestCopilotWSLHangHoldsNoRequest(t *testing.T) { + home := signIn(t) + os.Remove(filepath.Join(home, ".config", "github-copilot", "apps.json")) + t.Setenv("COPILOT_HOME", filepath.Join(home, "no-copilot-here")) + oldSecret, oldDirs, oldWait := copilotCLISecret, CopilotWSLDirs, copilotWSLWait + copilotCLISecret = func(string) string { return "" } + copilotWSLWait = 200 * time.Millisecond + distro := filepath.Join(t.TempDir(), "home", "jia") + os.MkdirAll(filepath.Join(distro, ".copilot"), 0o700) + os.WriteFile(filepath.Join(distro, ".copilot", "config.json"), []byte(`{ + "lastLoggedInUser": {"host": "https://github.com", "login": "jia2"}, + "loggedInUsers": [{"host": "https://github.com", "login": "jia2"}], + "copilotTokens": {"https://github.com:jia2": "gho_wsl"} +}`), 0o600) + release := make(chan struct{}) + var mu sync.Mutex + hang := false + CopilotWSLDirs = func() []string { + mu.Lock() + h := hang + mu.Unlock() + if h { + <-release + } + return []string{filepath.Join(distro, ".copilot")} + } + copilotWSL.Lock() + copilotWSL.at = time.Time{} + copilotWSL.Unlock() + var once sync.Once + free := func() { once.Do(func() { close(release) }) } + t.Cleanup(func() { + free() + for { + copilotWSL.Lock() + busy := copilotWSL.done != nil + copilotWSL.Unlock() + if !busy { + break + } + time.Sleep(time.Millisecond) + } + copilotCLISecret, CopilotWSLDirs, copilotWSLWait = oldSecret, oldDirs, oldWait + copilotWSL.Lock() + copilotWSL.at = time.Time{} + copilotWSL.Unlock() + }) + + if app, ok := copilotCLILogin(); !ok || app.User != "jia2" { + t.Fatalf("first read: %+v %v", app, ok) + } + // older than copilotWSLAge, and WSL hangs now + mu.Lock() + hang = true + mu.Unlock() + copilotWSL.Lock() + copilotWSL.at = time.Now().Add(-copilotWSLAge - time.Second) + copilotWSL.Unlock() + + bar := copilotWSLWait + 2*time.Second + var wg sync.WaitGroup + start := time.Now() + errs := make(chan string, 13) + for range 13 { + wg.Add(1) + go func() { + defer wg.Done() + if app, ok := copilotCLILogin(); !ok || app.User != "jia2" { + errs <- "the sign-in read before wasn't answered" + } + }() + } + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(bar): + t.Errorf("13 requests waited on a hung WSL past %v", bar) + free() + <-done + } + if d := time.Since(start); d > bar { + t.Errorf("13 requests at once took %v", d) + } + close(errs) + for e := range errs { + t.Error(e) + break + } +}