Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
settings: an unchanged settings.json is parsed once, and a gateway request reads the shared settings
yetone9329c89c95b8
diff --git a/internal/gateway/conversations.go b/internal/gateway/conversations.goindex 6a6ead333..fe88e54be 100644--- a/internal/gateway/conversations.go+++ b/internal/gateway/conversations.go@@ -61,7 +61,7 @@ func (w *conversationWriter) WriteHeader(status int) {func recordConversation(w http.ResponseWriter, r *http.Request, proto provider.Protocol, body []byte) (http.ResponseWriter, func()) {id := sessionOf(r.Header)generation := sessions.GatewayRecordingGeneration()- if !settings.Load().GatewayConversations || id == "" {+ if !settings.Shared().GatewayConversations || id == "" {return w, func() {}}at := time.Now()diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 2a7311465..ee54c162e 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -111,7 +111,7 @@ type wiresKey struct{}// only where something asks for one: a request refused before any name is// looked up pays for nothing.func withWires(r *http.Request) *http.Request {- load := sync.OnceValue(func() map[string]string { return settings.Load().ModelWires })+ load := sync.OnceValue(func() map[string]string { return settings.Shared().ModelWires })return r.WithContext(context.WithValue(r.Context(), wiresKey{}, load))}@@ -122,7 +122,7 @@ func wiresOf(ctx context.Context) map[string]string {if load, ok := ctx.Value(wiresKey{}).(func() map[string]string); ok {return load()}- return settings.Load().ModelWires+ return settings.Shared().ModelWires}// standIn is StandIn's model for one magpie shows no entry for: not a@@ -1340,7 +1340,7 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov}// the names in force, read at most once however many candidates are// counted, and not at all where there are none- wires := sync.OnceValue(func() map[string]string { return settings.Load().ModelWires })+ wires := sync.OnceValue(func() map[string]string { return settings.Shared().ModelWires })for i, c := range counts {res, err := s.forward(r.Context(), c.p, provider.Anthropic, "/v1/messages/count_tokens", rewriteModel(body, provider.UpstreamNameIn(wires(), c.p.ID, model)), r.Header)if tooMany := (*errRPM)(nil); errors.As(err, &tooMany) {diff --git a/internal/gateway/member.go b/internal/gateway/member.goindex 6b728d2ba..69b35c7aa 100644--- a/internal/gateway/member.go+++ b/internal/gateway/member.go@@ -66,7 +66,7 @@ func namesMember(r *http.Request, agent string) bool {case "vendor":return false}- if !settings.Load().MemberModel {+ if !settings.Shared().MemberModel {return false}for _, a := range vendorNamed {diff --git a/internal/gateway/redact.go b/internal/gateway/redact.goindex 8d3ba70e9..d1d8c8c16 100644--- a/internal/gateway/redact.go+++ b/internal/gateway/redact.go@@ -118,7 +118,7 @@ func restoring(w http.ResponseWriter) (http.ResponseWriter, func()) {// the core's own reading, so a request isn't sent unmasked when the plugin// isn't there to mask it.func redactionWanted() bool {- return masking.Wanted(settings.Load())+ return masking.Wanted(settings.Shared())}// maskedQuery masks a web search's query, as the settings say, before itdiff --git a/internal/gateway/request_settings_once_test.go b/internal/gateway/request_settings_once_test.gonew file mode 100644index 000000000..1d687076b--- /dev/null+++ b/internal/gateway/request_settings_once_test.go@@ -0,0 +1,81 @@+package gateway++import (+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/settings"+)++// A heap profile of a gateway at work (~1,000 requests in 10 minutes)+// had settings.json parsed many times for each request, ~800 MB in all:+// redaction, the model wires, efforts, images, conversations and member+// names each read the settings again. An unchanged file is parsed once+// however many requests are served, and what the requests share of it is+// left as the file says.+//+// Counted, not timed: before, each request parsed it seven times.+func TestRequestsParseUnchangedSettingsOnce(t *testing.T) {+ fresh(t)+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ io.ReadAll(r.Body)+ w.Header().Set("Content-Type", "application/json")+ io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"pong"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1,"total_tokens":4}}`)+ }))+ t.Cleanup(up.Close)+ if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {+ t.Fatal(err)+ }+ // a long-used magpie's settings: answers about many models+ images := map[string]bool{}+ for i := range 200 {+ images[fmt.Sprintf("p%d/model-%d", i%30, i)] = i%2 == 0+ }+ raw, err := json.Marshal(map[string]any{"modelImages": images, "redactWords": []string{"hunter2"}, "modelWires": map[string]string{"relay/m1": "m1"}})+ if err != nil {+ t.Fatal(err)+ }+ was, _ := os.ReadFile(settings.Path())+ t.Cleanup(func() { os.WriteFile(settings.Path(), was, 0o600) })+ os.MkdirAll(filepath.Dir(settings.Path()), 0o755)+ if err := os.WriteFile(settings.Path(), raw, 0o600); err != nil {+ t.Fatal(err)+ }+ gw := httptest.NewServer(New().Handler())+ t.Cleanup(gw.Close)+ ask := func() {+ t.Helper()+ res, err := http.Post(gw.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"relay/m1","messages":[{"role":"user","content":"my password is hunter2"}]}`))+ if err != nil {+ t.Fatal(err)+ }+ b, _ := io.ReadAll(res.Body)+ res.Body.Close()+ if res.StatusCode != 200 {+ t.Fatalf("status %d: %s", res.StatusCode, b)+ }+ }+ ask()+ const requests = 30+ before := settings.Parses()+ for range requests {+ ask()+ }+ if n := settings.Parses() - before; n >= requests {+ t.Fatalf("settings.json parsed %d times for %d requests with the file unchanged", n, requests)+ }+ var want settings.Settings+ json.Unmarshal(raw, &want)+ if got := settings.Shared(); !reflect.DeepEqual(got.ModelImages, want.ModelImages) || !reflect.DeepEqual(got.RedactWords, want.RedactWords) || !reflect.DeepEqual(got.ModelWires, want.ModelWires) {+ t.Fatalf("the requests changed the shared settings: %v %v", got.RedactWords, got.ModelWires)+ }+}diff --git a/internal/masking/masking.go b/internal/masking/masking.goindex 1cacf52b1..27d2021da 100644--- a/internal/masking/masking.go+++ b/internal/masking/masking.go@@ -22,7 +22,7 @@ func Wanted(st settings.Settings) bool {}func options() redact.Options {- st := settings.Load()+ st := settings.Shared()o := redact.Options{Secrets: st.Redact, Personal: st.RedactPersonal, Kinds: st.RedactKinds, Words: st.RedactWords, Rules: st.RedactRules}if st.RedactModel {o.Model = modeldiff --git a/internal/provider/modelprefs.go b/internal/provider/modelprefs.goindex 209343737..ea04f6482 100644--- a/internal/provider/modelprefs.go+++ b/internal/provider/modelprefs.go@@ -621,7 +621,7 @@ func setModelSame(ref, same string) (bool, error) {// ImageOverride is the user's answer for whether pid's model takes images.func ImageOverride(pid, model string) (bool, bool) {- return ImageOverrideIn(settings.Load(), pid, model)+ return ImageOverrideIn(settings.Shared(), pid, model)}// ImageOverrideIn is ImageOverride from settings s already read: a list ofdiff --git a/internal/provider/models.go b/internal/provider/models.goindex 3f816b5d3..07771049e 100644--- a/internal/provider/models.go+++ b/internal/provider/models.go@@ -1602,7 +1602,7 @@ func (p Provider) Efforts(model string) []string {if all := p.Known(model); len(all) > 0 {return all}- return effortsKept(nil, settings.Load().ModelEfforts[p.ID+"/"+model])+ return effortsKept(nil, settings.Shared().ModelEfforts[p.ID+"/"+model])}// Thinks reports whether the model reasons: it has levels, its list saysdiff --git a/internal/settings/clone.go b/internal/settings/clone.gonew file mode 100644index 000000000..6fbc79c26--- /dev/null+++ b/internal/settings/clone.go@@ -0,0 +1,109 @@+package settings++import "reflect"++// clone is a deep copy of s: every map, slice and pointer it holds is its+// own, so a caller changing what Load gave it changes nothing another+// caller holds, nor the settings parse keeps for the file's bytes.+func (s Settings) clone() Settings {+ var out Settings+ deepCopy(reflect.ValueOf(&out).Elem(), reflect.ValueOf(s))+ return out+}++// deepCopy sets dst, a settable value of src's type, to a copy of src+// sharing no map, slice or pointer with it. A nil map or slice stays nil+// and an empty one stays empty, as normal and Save tell the two apart.+func deepCopy(dst, src reflect.Value) {+ switch src.Kind() {+ case reflect.Map:+ if src.IsNil() {+ return+ }+ t := src.Type()+ m := reflect.MakeMapWithSize(t, src.Len())+ // one key and value, set from each entry in turn: SetMapIndex+ // copies them into the map+ k, v := reflect.New(t.Key()).Elem(), reflect.New(t.Elem()).Elem()+ var kc, vc reflect.Value+ if !plain(t.Key()) {+ kc = reflect.New(t.Key()).Elem()+ }+ if !plain(t.Elem()) {+ vc = reflect.New(t.Elem()).Elem()+ }+ it := src.MapRange()+ for it.Next() {+ k.SetIterKey(it)+ v.SetIterValue(it)+ key, val := k, v+ if kc.IsValid() {+ kc.SetZero()+ deepCopy(kc, k)+ key = kc+ }+ if vc.IsValid() {+ vc.SetZero()+ deepCopy(vc, v)+ val = vc+ }+ m.SetMapIndex(key, val)+ }+ dst.Set(m)+ case reflect.Slice:+ if src.IsNil() {+ return+ }+ n := reflect.MakeSlice(src.Type(), src.Len(), src.Len())+ if plain(src.Type().Elem()) {+ reflect.Copy(n, src)+ } else {+ for i := range src.Len() {+ deepCopy(n.Index(i), src.Index(i))+ }+ }+ dst.Set(n)+ case reflect.Pointer:+ if src.IsNil() {+ return+ }+ p := reflect.New(src.Type().Elem())+ deepCopy(p.Elem(), src.Elem())+ dst.Set(p)+ case reflect.Interface:+ if src.IsNil() {+ return+ }+ v := reflect.New(src.Elem().Type()).Elem()+ deepCopy(v, src.Elem())+ dst.Set(v)+ case reflect.Struct:+ if plain(src.Type()) {+ dst.Set(src)+ return+ }+ for i := range src.NumField() {+ deepCopy(dst.Field(i), src.Field(i))+ }+ default:+ dst.Set(src)+ }+}++// plain is whether a value of t holds nothing shared: no map, slice,+// pointer or interface anywhere in it, so a plain assignment copies it.+func plain(t reflect.Type) bool {+ switch t.Kind() {+ case reflect.Map, reflect.Slice, reflect.Pointer, reflect.Interface, reflect.Chan, reflect.Func, reflect.UnsafePointer:+ return false+ case reflect.Array:+ return plain(t.Elem())+ case reflect.Struct:+ for i := range t.NumField() {+ if !plain(t.Field(i).Type) {+ return false+ }+ }+ }+ return true+}diff --git a/internal/settings/settings.go b/internal/settings/settings.goindex eabe5807e..75fe1796e 100644--- a/internal/settings/settings.go+++ b/internal/settings/settings.go@@ -1096,6 +1096,46 @@ func LoadChecked() (Settings, error) {return loadChecked()}+// Shared is Load without a copy of its own: the settings every caller of+// Shared is given for the same settings.json, for a look made on each+// gateway request (redaction, wires, efforts, images). Only for reading:+// a caller never writes into its maps or slices (append reallocates, as+// each slice is held at its length), and one that changes anything takes+// Load's copy instead. Unreadable, it is Load's defaults as they are.+func Shared() Settings {+ fileMu.RLock()+ defer fileMu.RUnlock()+ b, err := filememo.Read("settings", Path(), func(b []byte) ([]byte, error) { return b, nil })+ if err != nil {+ return load()+ }+ if s, ok := sharedFor(b); ok {+ return s+ }+ s, err := parse(b)+ if err != nil {+ return s+ }+ if s, ok := sharedFor(b); ok {+ return s+ }+ return s+}++// sharedFor is the shared Settings parse keeps for contents b, when it+// keeps them.+func sharedFor(b []byte) (Settings, bool) {+ parsed.Lock()+ defer parsed.Unlock()+ if parsed.raw == nil || !bytes.Equal(parsed.raw, b) {+ return Settings{}, false+ }+ if !parsed.normed {+ parsed.norm, parsed.normed = parsed.s.clone().normal().clone(), true+ }+ return parsed.norm, true+}+// load is called with fileMu held for reading or writing.func load() Settings {s, _ := loadChecked()@@ -1115,26 +1155,52 @@ func loadChecked() (Settings, error) {}return s.normal(), fmt.Errorf("could not read settings at %s: %w", Path(), err)}- // parsed on every call: a caller that asks many times in one look holds- // what it read (provider.Hold's heldSettings) rather than asking againreturn parse(b)}+// parsed is the last settings.json that parsed whole and what it read as,+// before normal (s), and after it for Shared (norm, once asked): a+// gateway request asks for the settings a dozen times over, and parsing+// the file each time was most of what a request allocated. Keyed on the+// bytes themselves, so only the same contents read as the same settings.+var parsed struct {+ sync.Mutex+ raw []byte+ s Settings+ norm Settings+ normed bool+}+// parse is settings.json's contents b read as Settings, from its last good-// generation when b doesn't parse.+// generation when b doesn't parse. Each call has a Settings of its own to+// change: the one kept for the same bytes is cloned, never handed out.func parse(b []byte) (Settings, error) {+ parsed.Lock()+ if parsed.raw != nil && bytes.Equal(parsed.raw, b) {+ s := parsed.s+ parsed.Unlock()+ return s.clone().normal(), nil+ }+ parsed.Unlock()var s Settingsvar err errorparses.Add(1)- if perr := json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s); perr != nil {- // one left all zero by a crash (#1505) is its last good generation- bak, ferr := lastgood.Fallback(Path(), b, validSettings)- if ferr == nil {- s = Settings{}- _ = json.Unmarshal(bytes.TrimPrefix(bak, []byte("\xef\xbb\xbf")), &s)- } else if len(bytes.TrimSpace(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")))) != 0 {- err = fmt.Errorf("could not read settings at %s: %w", Path(), perr)- }+ perr := json.Unmarshal(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")), &s)+ if perr == nil {+ // only what parsed whole is kept: a last good generation read in+ // its place is read again, as is a file that can't be read at all+ parsed.Lock()+ parsed.raw, parsed.s, parsed.norm, parsed.normed = bytes.Clone(b), s, Settings{}, false+ parsed.Unlock()+ return s.clone().normal(), nil+ }+ // one left all zero by a crash (#1505) is its last good generation+ bak, ferr := lastgood.Fallback(Path(), b, validSettings)+ if ferr == nil {+ s = Settings{}+ _ = json.Unmarshal(bytes.TrimPrefix(bak, []byte("\xef\xbb\xbf")), &s)+ } else if len(bytes.TrimSpace(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")))) != 0 {+ err = fmt.Errorf("could not read settings at %s: %w", Path(), perr)}return s.normal(), err}diff --git a/internal/settings/shared_test.go b/internal/settings/shared_test.gonew file mode 100644index 000000000..660c7e17c--- /dev/null+++ b/internal/settings/shared_test.go@@ -0,0 +1,192 @@+package settings++import (+ "os"+ "path/filepath"+ "reflect"+ "runtime"+ "testing"+ "time"+)++// writeRaw puts b in settings.json as another program would, no .bak+// kept, with a time of its own so the file is seen as changed.+func writeRaw(t *testing.T, b string) {+ t.Helper()+ os.MkdirAll(filepath.Dir(Path()), 0o755)+ if err := os.WriteFile(Path(), []byte(b), 0o600); err != nil {+ t.Fatal(err)+ }+ at := time.Now().Add(time.Duration(len(b)) * time.Second)+ os.Chtimes(Path(), at, at)+}++// A gateway request asks for the settings a dozen times over; parsing+// settings.json for each was ~800 MB a 10-minute profile. An unchanged+// file is parsed once, by Load and by Shared, and a change is read.+func TestUnchangedSettingsParsedOnce(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ writeRaw(t, `{"proxy":"direct","modelImages":{"a/m":true},"redactWords":["x"]}`)+ Load()+ n := Parses()+ for range 100 {+ if Load().Proxy != "direct" || Shared().Proxy != "direct" {+ t.Fatal("read the wrong settings")+ }+ LoadChecked()+ }+ if got := Parses() - n; got != 0 {+ t.Fatalf("an unchanged settings.json was parsed %d more times in 300 reads", got)+ }+ writeRaw(t, `{"proxy":"http://127.0.0.1:7890"}`)+ if Load().Proxy != "http://127.0.0.1:7890" || Shared().Proxy != "http://127.0.0.1:7890" {+ t.Fatalf("a change is not read: %q %q", Load().Proxy, Shared().Proxy)+ }+ if Shared().ModelImages != nil {+ t.Fatal("the old file's settings are still shared")+ }+}++// What Load gives is the caller's to change: a write into its maps or+// slices reaches neither the next Load nor Shared.+func TestLoadIsTheCallersOwn(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ writeRaw(t, `{"modelImages":{"a/m":true},"pickedModels":{"codex":["a/m"]},"redactWords":["x"],"refusalRetries":2,"otel":{"headers":{"k":"v"}}}`)+ s := Load()+ s.ModelImages["a/m"] = false+ s.ModelImages["b/m"] = true+ s.PickedModels["codex"][0] = "changed"+ s.RedactWords[0] = "changed"+ *s.RefusalRetries = 9+ s.OTel.Headers["k"] = "changed"+ for name, got := range map[string]Settings{"Load": Load(), "Shared": Shared()} {+ if !got.ModelImages["a/m"] || len(got.ModelImages) != 1 || got.PickedModels["codex"][0] != "a/m" ||+ got.RedactWords[0] != "x" || *got.RefusalRetries != 2 || got.OTel.Headers["k"] != "v" {+ t.Errorf("%s after a caller changed Load's: %+v %+v %v %d %v", name, got.ModelImages, got.PickedModels, got.RedactWords, *got.RefusalRetries, got.OTel.Headers)+ }+ }+}++// Shared's slices are held at their length: a caller appending to one+// gets a new array and leaves the next caller's alone.+func TestSharedAppendReallocates(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ writeRaw(t, `{"fetchPrivate":["10.0.0.1","10.0.0.2","10.0.0.3"],"codexWarmAts":["7:00","6:00"]}`)+ a := append(Shared().FetchPrivate, "evil")+ b := append(Shared().FetchPrivate, "other")+ c := append(Shared().CodexWarmAts, "23:00")+ if a[3] != "evil" || len(Shared().FetchPrivate) != 3 || c[2] != "23:00" {+ t.Fatalf("appends reached the shared list: %v %v %v", a, b, Shared().FetchPrivate)+ }+}++// A file that can't be read or parsed is unknown, a memo of the file read+// before notwithstanding: LoadChecked says so, and Shared is Load's+// defaults, not the old file's settings.+func TestUnreadableSettingsNotTheLastParsed(t *testing.T) {+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ writeRaw(t, `{"allowIPs":["10.0.0.1"]}`)+ if _, err := LoadChecked(); err != nil {+ t.Fatal(err)+ }+ Shared()+ writeRaw(t, `{"allowIPs":["10.0.0.1"`)+ if _, err := LoadChecked(); err == nil {+ t.Fatal("a file that doesn't parse read as known")+ }+ if got := Shared().AllowIPs; got != nil {+ t.Fatalf("Shared kept the last file's list: %v", got)+ }+ if runtime.GOOS == "windows" || os.Getuid() == 0 {+ return+ }+ writeRaw(t, `{"allowIPs":["10.0.0.9"]}`)+ if _, err := LoadChecked(); err != nil {+ t.Fatal(err)+ }+ os.Chmod(Path(), 0)+ t.Cleanup(func() { os.Chmod(Path(), 0o600) })+ at := time.Now().Add(time.Hour)+ os.Chtimes(Path(), at, at)+ if _, err := LoadChecked(); err == nil {+ t.Fatal("an unreadable file read as known")+ }+}++// clone copies every field: each map, slice and pointer of a Settings+// with all of them set is a new one, and the copy is equal. A field of a+// kind clone can't copy (an unexported field in a struct it holds)+// panics here first.+func TestCloneSharesNothing(t *testing.T) {+ var s Settings+ fill(reflect.ValueOf(&s).Elem())+ c := s.clone()+ if !reflect.DeepEqual(s, c) {+ t.Fatal("the clone differs")+ }+ apart(t, "Settings", reflect.ValueOf(s), reflect.ValueOf(c))+}++// fill sets every field of v, each map and slice with one entry.+func fill(v reflect.Value) {+ switch v.Kind() {+ case reflect.Map:+ m := reflect.MakeMap(v.Type())+ k, e := reflect.New(v.Type().Key()).Elem(), reflect.New(v.Type().Elem()).Elem()+ fill(k)+ fill(e)+ m.SetMapIndex(k, e)+ v.Set(m)+ case reflect.Slice:+ s := reflect.MakeSlice(v.Type(), 1, 1)+ fill(s.Index(0))+ v.Set(s)+ case reflect.Pointer:+ p := reflect.New(v.Type().Elem())+ fill(p.Elem())+ v.Set(p)+ case reflect.Struct:+ for i := range v.NumField() {+ fill(v.Field(i))+ }+ case reflect.String:+ v.SetString("x")+ case reflect.Bool:+ v.SetBool(true)+ case reflect.Int, reflect.Int64, reflect.Int32:+ v.SetInt(1)+ case reflect.Float64, reflect.Float32:+ v.SetFloat(1)+ }+}++// apart fails when a and b share a map, slice or pointer anywhere.+func apart(t *testing.T, path string, a, b reflect.Value) {+ t.Helper()+ switch a.Kind() {+ case reflect.Map:+ if a.UnsafePointer() == b.UnsafePointer() {+ t.Errorf("%s is shared", path)+ }+ it := a.MapRange()+ for it.Next() {+ apart(t, path+"[]", it.Value(), b.MapIndex(it.Key()))+ }+ case reflect.Slice:+ if a.UnsafePointer() == b.UnsafePointer() {+ t.Errorf("%s is shared", path)+ }+ for i := range a.Len() {+ apart(t, path+"[i]", a.Index(i), b.Index(i))+ }+ case reflect.Pointer:+ if a.Pointer() == b.Pointer() {+ t.Errorf("%s is shared", path)+ }+ apart(t, path, a.Elem(), b.Elem())+ case reflect.Struct:+ for i := range a.NumField() {+ apart(t, path+"."+a.Type().Field(i).Name, a.Field(i), b.Field(i))+ }+ }+}