Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

pii: pf-serve is pf-v2, which holds the model once on a GPU (#3590)

yetone5df62c5cda12
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 40fa17d4d..f3ca67c03 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -90,7 +90,7 @@ recorded as a prediction failure (`noPrediction`).
1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression` and `http-client/src/request.rs`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.
2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, or 32 hex digits or more) goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of `…-a13800138000`, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (`api_key=`, `refresh_token`), never one named for an id, a cursor, a request or a digest (`secret_id`, `next_page_token`, `Idempotency-Key`, `secret_hash`), a bare `key`, a serial number, or what the model takes a UUID for (`noIDs`, [`internal/redact/ids.go`](../../internal/redact/ids.go)); and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then, so a value a rule first finds later in a conversation doesn't change the prompt the vendor has cached and rewrite all of it to the cache, `sentKnownSpans`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).
- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so, MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `[email protected]`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`[email protected]`, `[email protected]`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). `[email protected]` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.
- - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is OpenAI's Privacy Filter as a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU is started on the CPU for the rest of the run), joins short texts into 12 KB chunks and maps the spans back, keeps the last 20000 answers by hash, and ends it after 10 minutes with no request ([`internal/pii`](../../internal/pii)). A model that is on and can't answer (not on disk, didn't start, hung) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).
+ - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is OpenAI's Privacy Filter as a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU is started on the CPU for the rest of the run), joins short texts into 12 KB chunks and maps the spans back, keeps the last 20000 answers by hash, and ends it after 10 minutes with no request; 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 model that is on and can't answer (not on disk, didn't start, hung) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).
- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (`options` in [`internal/masking`](../../internal/masking/masking.go)), so a change applies to the next request.
- 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).
- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.
diff --git a/internal/pii/fetch.go b/internal/pii/fetch.go
index ed23cb597..70fcfd809 100644
--- a/internal/pii/fetch.go
+++ b/internal/pii/fetch.go
@@ -89,11 +89,10 @@ func install(ctx context.Context) error {
if err := os.MkdirAll(dir(), 0o755); err != nil {
return err
}
- if _, err := os.Stat(exe("pf-serve")); err != nil {
- if err := installServe(ctx); err != nil {
- return fmt.Errorf("downloading pf-serve: %w", err)
- }
+ if err := ensureServe(ctx); err != nil {
+ return fmt.Errorf("downloading pf-serve: %w", err)
}
+ removeOld()
if fi, err := os.Stat(modelPath()); err == nil && fi.Size() == modelSize {
dl.done.Store(modelSize)
return nil
@@ -104,6 +103,53 @@ func install(ctx context.Context) error {
return nil
}
+// serveMu keeps install and upgrade from fetching serveTag's pf-serve at
+// once.
+var serveMu sync.Mutex
+
+// ensureServe fetches serveTag's pf-serve unless it is on disk.
+func ensureServe(ctx context.Context) error {
+ serveMu.Lock()
+ defer serveMu.Unlock()
+ if _, err := os.Stat(exeIn(serveDir(), "pf-serve")); err == nil {
+ return nil
+ }
+ return installServe(ctx)
+}
+
+// upgrading is set while upgrade runs.
+var upgrading atomic.Bool
+
+// upgrade fetches serveTag's pf-serve where only an older one is on disk
+// (magpie was updated since the model was downloaded), ends the old one so
+// that the next request starts the new, and deletes the old. One that
+// can't be fetched leaves the old to run, and is tried again on the next
+// start.
+func upgrade() {
+ if binDir() == serveDir() {
+ removeOld() // what a pf-serve still running kept (Windows)
+ return
+ }
+ if !upgrading.CompareAndSwap(false, true) {
+ return
+ }
+ defer upgrading.Store(false)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
+ defer cancel()
+ if err := ensureServe(ctx); err != nil {
+ return
+ }
+ Stop()
+ removeOld()
+}
+
+// removeOld deletes oldTags' pf-serve.
+func removeOld() {
+ for _, tag := range oldTags {
+ os.RemoveAll(tagDir(tag))
+ }
+}
+
// installServe fetches pf-serve's zip and puts what is in it in
// serveDir: each file by its name alone, so nothing lands outside it.
func installServe(ctx context.Context) error {
diff --git a/internal/pii/fetch_test.go b/internal/pii/fetch_test.go
index 072807d1d..a7f692320 100644
--- a/internal/pii/fetch_test.go
+++ b/internal/pii/fetch_test.go
@@ -10,6 +10,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "reflect"
"strings"
"sync"
"sync/atomic"
@@ -147,14 +148,17 @@ func TestDownloadInstalls(t *testing.T) {
d := t.TempDir()
root := filepath.Join(d, "cache")
wasDir, wasURL, wasSize, wasSHA := dir, modelURL, modelSize, modelSHA
- wasTag, wasBase, wasServe := serveTag, serveBase, serveSHA
+ wasTag, wasOld, wasBase, wasServe := serveTag, oldTags, serveBase, serveSHA
t.Cleanup(func() {
dir, modelURL, modelSize, modelSHA = wasDir, wasURL, wasSize, wasSHA
- serveTag, serveBase, serveSHA = wasTag, wasBase, wasServe
+ serveTag, oldTags, serveBase, serveSHA = wasTag, wasOld, wasBase, wasServe
})
dir = func() string { return root }
modelURL, modelSize, modelSHA = s.URL+"/model.gguf", int64(len(model)), sum(model)
- serveTag, serveBase, serveSHA = "pf-v9", s.URL+"/rel/", map[string]string{target(): sum(zb.Bytes())}
+ serveTag, oldTags, serveBase, serveSHA = "pf-v9", []string{"pf-v8"}, s.URL+"/rel/", map[string]string{target(): sum(zb.Bytes())}
+ // an older tag's pf-serve, left from before: the download replaces it
+ os.MkdirAll(tagDir("pf-v8"), 0o755)
+ os.WriteFile(exeIn(tagDir("pf-v8"), "pf-serve"), []byte("old"), 0o755)
if Installed() {
t.Fatal("installed before the download")
@@ -180,6 +184,9 @@ func TestDownloadInstalls(t *testing.T) {
if b, _ := os.ReadFile(exe("pf-serve")); string(b) != "serve" {
t.Fatalf("pf-serve = %q", b)
}
+ if _, err := os.Stat(tagDir("pf-v8")); err == nil {
+ t.Fatal("the older tag's pf-serve was left")
+ }
if b, _ := os.ReadFile(filepath.Join(serveDir(), "LICENSE-ggml")); string(b) != "mit" {
t.Fatalf("LICENSE-ggml = %q", b)
}
@@ -209,3 +216,93 @@ func TestDownloadUnsupported(t *testing.T) {
t.Fatalf("err = %v", err)
}
}
+
+// oldInstall is fakeInstall's, in the folder of a tag pinned before
+// (pf-old), and serveTag (pf-new) is fetched from a server serving want's
+// paths; it gives the stand-in's log and the server.
+func oldInstall(t *testing.T, want map[string][]byte) (string, *files) {
+ t.Helper()
+ wasTag, wasOld, wasBase, wasServe := serveTag, oldTags, serveBase, serveSHA
+ t.Cleanup(func() { serveTag, oldTags, serveBase, serveSHA = wasTag, wasOld, wasBase, wasServe })
+ serveTag = "pf-old"
+ log := fakeInstall(t, "ok", false)
+ f := &files{m: want}
+ s := httptest.NewServer(f)
+ t.Cleanup(s.Close)
+ zipSum := sum([]byte("nothing"))
+ if z, ok := want["/rel/pf-new/pf-serve-"+target()+".zip"]; ok {
+ zipSum = sum(z)
+ }
+ serveTag, oldTags, serveBase, serveSHA = "pf-new", []string{"pf-old"}, s.URL+"/rel/", map[string]string{target(): zipSum}
+ return log, f
+}
+
+// A pf-serve of a tag pinned before magpie was updated answers while
+// serveTag's is fetched; then it is ended, the next request starts
+// serveTag's, and the old one is deleted.
+func TestOldServeRunsUntilUpgraded(t *testing.T) {
+ self, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := os.ReadFile(self)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var zb bytes.Buffer
+ zw := zip.NewWriter(&zb)
+ w, _ := zw.Create(filepath.Base(exeIn("", "pf-serve")))
+ w.Write(b)
+ zw.Close()
+ log, _ := oldInstall(t, map[string][]byte{"/rel/pf-new/pf-serve-" + target() + ".zip": zb.Bytes()})
+ if !Installed() {
+ t.Fatal("the old pf-serve wasn't taken for installed")
+ }
+ if _, err := Find([]string{"hi Alice"}); err != nil {
+ t.Fatal(err)
+ }
+ for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(10 * time.Millisecond) {
+ _, err := os.Stat(tagDir("pf-old"))
+ if os.IsNotExist(err) && !upgrading.Load() {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("not upgraded: old folder %v, upgrading %v", err, upgrading.Load())
+ }
+ }
+ if _, err := Find([]string{"new Alice"}); err != nil {
+ t.Fatal(err)
+ }
+ want := []string{"path pf-old-" + target(), "path pf-new-" + target()}
+ if got := fakeLines(t, log, "path "); !reflect.DeepEqual(got, want) {
+ t.Fatalf("started from %q, want %q", got, want)
+ }
+}
+
+// One that can't be fetched leaves the old pf-serve on disk, answering.
+func TestUpgradeThatFailsKeepsTheOld(t *testing.T) {
+ log, f := oldInstall(t, map[string][]byte{})
+ if _, err := Find([]string{"hi Alice"}); err != nil {
+ t.Fatal(err)
+ }
+ for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(10 * time.Millisecond) {
+ f.mu.Lock()
+ asked := len(f.ranges) > 0
+ f.mu.Unlock()
+ if asked && !upgrading.Load() {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("the upgrade never tried")
+ }
+ }
+ if _, err := os.Stat(exeIn(tagDir("pf-old"), "pf-serve")); err != nil {
+ t.Fatalf("the old pf-serve was deleted: %v", err)
+ }
+ if _, err := Find([]string{"new Alice"}); err != nil {
+ t.Fatal(err)
+ }
+ if n := len(fakeLines(t, log, "start")); n != 1 {
+ t.Fatalf("pf-serve started %d times, want once: the old one runs on", n)
+ }
+}
diff --git a/internal/pii/main_test.go b/internal/pii/main_test.go
index 95c08a1e7..d127e8271 100644
--- a/internal/pii/main_test.go
+++ b/internal/pii/main_test.go
@@ -56,6 +56,7 @@ func fakeServe(mode string) {
}
}
logf("start %s %s", name, device)
+ logf("path %s", filepath.Base(filepath.Dir(os.Args[0])))
logf("residency %s", os.Getenv("GGML_METAL_NO_RESIDENCY"))
if mode == "noload" || mode == "novulkan" && name == "pf-serve-vulkan" {
json.NewEncoder(os.Stdout).Encode(map[string]string{"error": "can't load " + mode})
diff --git a/internal/pii/pii.go b/internal/pii/pii.go
index f04be7a95..d92a473c6 100644
--- a/internal/pii/pii.go
+++ b/internal/pii/pii.go
@@ -37,15 +37,18 @@ var (
// pf-serve, as the privacy-filter workflow built it at serveTag: a zip for
// each system, by its sha256. A system with none can't run the model.
+// oldTags are the tags pinned before, newest first: one of theirs on disk
+// is run until serveTag's is downloaded (upgrade).
var (
- serveTag = "pf-v1"
+ serveTag = "pf-v2"
+ oldTags = []string{"pf-v1"}
serveBase = "https://github.com/yetone/magpie/releases/download/"
serveSHA = map[string]string{
- "darwin-amd64": "7d5512ed24ff865bb0e84009b0adecd3addf0444891990cbc78634d78390c607",
- "darwin-arm64": "07eb79dd1d74a6dc8e2e59eefed1094a4c1dafa27051343fac65d6c2172617f0",
- "linux-amd64": "b172f39b2b5446cb92ef14f996b65157f5e1c0e4e673ee9c61a0214cc67c78af",
- "linux-arm64": "7a344515e35676d0da21b448c6c4bc49de7cf34f8f28604c6889c092ae963961",
- "windows-amd64": "dd06aa4e656cbebff348ad3fdfd66eca5f899b244dff65235d47a2c878b49c6c",
+ "darwin-amd64": "4b68c9f06b14b909ec35e491ba58fcb06df500a5a0985465dd1115f9e7a5d753",
+ "darwin-arm64": "13ea258cc139dd0fc024f8eab70ee3566aa12ce6b5ab71f890b68bc8507159d3",
+ "linux-amd64": "ff0af5cd1a3d350e7c93ca45c0b5285088c9666340826e87fbb14e5dcb23f772",
+ "linux-arm64": "05970f7c5ba202e0e577cb22e0d12f009789c321583574a1ae1196d9522f7181",
+ "windows-amd64": "f4993000cc09500c907d3dd7042d783fa0b9310f272bc0bdf323ba9d012556f0",
}
)
@@ -65,13 +68,28 @@ var dir = func() string { return filepath.Join(appdir.Cache(), "privacy-filter")
func modelPath() string { return filepath.Join(dir(), "privacy-filter-q8-"+modelSHA[:12]+".gguf") }
-func serveDir() string { return filepath.Join(dir(), serveTag+"-"+target()) }
+func serveDir() string { return tagDir(serveTag) }
-func exe(name string) string {
+func tagDir(tag string) string { return filepath.Join(dir(), tag+"-"+target()) }
+
+// exe is a program of pf-serve's: serveTag's, or, until that is
+// downloaded, the newest of oldTags' on disk.
+func exe(name string) string { return exeIn(binDir(), name) }
+
+func exeIn(d, name string) string {
if runtime.GOOS == "windows" {
name += ".exe"
}
- return filepath.Join(serveDir(), name)
+ return filepath.Join(d, name)
+}
+
+func binDir() string {
+ for _, tag := range append([]string{serveTag}, oldTags...) {
+ if _, err := os.Stat(exeIn(tagDir(tag), "pf-serve")); err == nil {
+ return tagDir(tag)
+ }
+ }
+ return serveDir()
}
// Installed says the model and pf-serve are on disk, as downloaded and
diff --git a/internal/pii/serve.go b/internal/pii/serve.go
index 70a83713a..a43d6d26f 100644
--- a/internal/pii/serve.go
+++ b/internal/pii/serve.go
@@ -80,6 +80,7 @@ func start(cpu bool) (*helper, error) {
if !Installed() {
return nil, ErrNotInstalled
}
+ go upgrade()
var errs []error
for _, path := range candidates(cpu) {
h, err := startOne(path, cpu)