Skip to content

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

agent: dsh's wiring round does nothing when nothing it reads changed

yetone489d81621386
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index ce7f4e420..53ce23217 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -59,6 +59,7 @@ something else shows up as drift.
- Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it.
- dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking`) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. A routing group has `responses` when every member is best on Responses (`allResponses`, #1594), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, a Messages-only group too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id.
- dsh takes a model's listed `maxTokens` as every request's output and reserves it, with 65536 of headroom, out of `contextWindow` before deciding when to compact (compaction-basic's `resolveCompactSpec`: the smaller of 80% of the window and window − maxTokens − 65536). A vendor's reply limit near its window had dsh compact at 41248 of a 500000 group (#2823) or fail with no budget (524288/524288, LoKi on Discord; 131072/65536), so magpie lists it held to a quarter of the window on every route and in the older `llm-deepseek` entry (`dshMaxTokens`), as VS Code and Copilot in JetBrains do. A Max output the user set stays as they set it (`outputOr`), even one that leaves dsh no budget. `TestDshOutputLeavesCompactionRoom`.
+- While magpie serves, `KeepDshWired` writes the routes again every 30 seconds, since dsh writes over its patch list. A round that writes nothing is kept (`dshRounds`), and the next round does nothing when nothing it reads has changed since. It checks the bytes of dsh's files (every profile's `cordis.patch.yml`, the home layer, `settings.yaml`, `.env`, `.credentials.yaml`, `config.yaml`) and the gateway's address. It also checks `provider.StampNow`: no Changed, plugin change or `filememo.Forget`, the same environment, and the providers', settings' and catalog's files unchanged. The models are built again when that stamp moves, and at least every `dshModelsFor` (5 minutes) for what no stamp sees, such as another app's account file or a date-retired model. Building the whole catalog and every route each round allocated 12 GB of a user's 35.7 GB in 48 minutes (`TestDshRoundWithNothingChangedBuildsNothing`, `TestDshRoundAfterAChangeWritesAgain`).
- DeepSeek Harness Desktop (macOS arm64 and Windows x64; no Linux build) reads the same `$DSH_HOME` or `~/.dsh` as the CLI, as its own profile `profiles/desktop` (`resolveDshHome` and `resolveDesktopPaths` in the app's `lib/main.js`), so it takes magpie's routes with no wiring of its own (#2279, liangjinyuan-sihan). It is found by `/Applications/DeepSeek Harness.app`, by `%LOCALAPPDATA%\Programs\DeepSeek Harness`, or by the folder its current-user installer records under `HKCU\Software\1bf39983-50d0-5fe0-9ef4-cece76f67c5e` (`InstallLocation`), whose Uninstall key gives the version (`registered` in [`desktopapp.go`](../../internal/agent/desktopapp.go)), so a user who picked another folder is found. With the app installed but never opened there is no `~/.dsh`: the row is still listed, and connecting writes `profiles/desktop/cordis.patch.yml` from dsh's own template (`dshProfileTemplate`) with magpie's routes, which the app keeps on its first start, since it writes only the files that are missing. The notice says the app starts on it the first time it opens (`noticeDsh5`). Disconnect before that first start removes the profile magpie made when nothing else is in it (`dshTidyUnopened`); once the app has opened it, the profile stays and only magpie's entries go (`TestDshDesktopNeverOpened`, `TestDshDesktopRegisteredFolder`).
- Ante's `catalog.json` keeps user-added fields in `providers.magpie` the same way (`ante` in [`ante.go`](../../internal/agent/ante.go)); its `auth`, `http_headers`, `extra_body` and `stream_idle_timeout_secs` are what a gateway shared on the local network or reached from WSL needs to send a key. Ante starts a session on the `provider` and `model` of `settings.json`, not on what its catalog holds (#1210), so magpie sets that pair and puts back what it found there; a pick the user makes in Ante while magpie is wired is theirs and stands.
- AstrBot keeps its providers in `data/cmd_config.json` under its root (`$ASTRBOT_ROOT`, else `~/.astrbot`, the desktop app's, else `~/astrbot`), written with a UTF-8 BOM, which magpie keeps (`astrbot` in [`astrbot.go`](../../internal/agent/astrbot.go)). magpie adds a `magpie` entry to `provider_sources` and one `magpie/<model>` entry per model to `provider`, keeps the user's own entries byte for byte and keeps what the user changes in magpie's (timeout, proxy, enable), and sets the default chat model (`agent_runner.config.model.provider_id`, or `provider_settings.default_provider_id` before the agent runner), putting back what it found there. A pick the user makes while magpie is wired is theirs and stands. The first connect copies the file to `cmd_config.json.before-magpie`. AstrBot reads the file only at start-up and its WebUI writes it back whole on save, so the agent's notice says to restart AstrBot before saving in the WebUI. A Docker install's root is inside its container, which magpie doesn't reach.
diff --git a/internal/agent/dsh.go b/internal/agent/dsh.go
index 3a6bce4f3..a81ad2818 100644
--- a/internal/agent/dsh.go
+++ b/internal/agent/dsh.go
@@ -30,6 +30,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "hash/maphash"
"log"
"os"
"path/filepath"
@@ -1824,8 +1825,9 @@ func KeepDshWired(ctx context.Context) {
// that could not write something is said once rather than every round.
func keepDshWired(ctx context.Context, every time.Duration) {
var said dshSaidOnce
+ var rounds dshRounds
for {
- if trouble := dshWiredOnce(); said.first(trouble) {
+ if trouble := rounds.once(); said.first(trouble) {
log.Print(trouble)
}
select {
@@ -1850,9 +1852,91 @@ func (s *dshSaidOnce) first(trouble string) bool {
return trouble != ""
}
+// dshModelsFor is how long a round takes magpie's models as built before
+// while provider.StampNow says nothing changed: what the stamp can't see
+// (another app rewriting an account's file, a model retired by its date)
+// reaches dsh's lists within it.
+const dshModelsFor = 5 * time.Minute
+
+// dshRounds is what keepDshWired's last round read, so that a round with
+// nothing changed since does nothing. Every 30 seconds a round built
+// magpie's whole catalog and every route again to write nothing: 12 GB of
+// the 35.7 GB a user's magpie allocated in 48 minutes, with ~157 MB live.
+// A round is done again when dsh's files it reads, the gateway's address
+// or magpie's models are other than when the last one found nothing to
+// write. The zero dshRounds does every round.
+type dshRounds struct {
+ // the models, and the stamp and time they were built at
+ models []catalog.Model
+ stamp provider.Stamp
+ at time.Time
+ built bool
+ // what the last round went by, and whether it wrote nothing, nothing
+ // else wrote while it ran, and nothing troubled it
+ last dshRoundKey
+ done bool
+}
+
+// dshRoundKey is what a round goes by: dsh's files it reads, the gateway's
+// address and magpie's models, each as a sum.
+type dshRoundKey struct {
+ files uint64
+ gw string
+ models uint64
+}
+
+var dshSumSeed = maphash.MakeSeed()
+
+// dshFilesSum sums the files a round reads, by path and bytes: each
+// profile's patch list, the home layer, and the settings, keys and old
+// config dsh reads beside them. A file that can't be read for another
+// reason than not being there sums differently every time: unknown, never
+// taken for what it was last round.
+func dshFilesSum(dir string, files []string) uint64 {
+ var h maphash.Hash
+ h.SetSeed(dshSumSeed)
+ sum := func(f string) {
+ h.WriteString(f)
+ h.WriteByte(0)
+ switch b, err := os.ReadFile(f); {
+ case err == nil:
+ h.WriteByte(1)
+ h.Write(b)
+ case errors.Is(err, os.ErrNotExist):
+ h.WriteByte(2)
+ default:
+ h.WriteString(time.Now().String())
+ }
+ h.WriteByte(0)
+ }
+ for _, f := range files {
+ sum(f)
+ }
+ for _, name := range []string{"cordis.patch.yml", "settings.yaml", ".env", ".credentials.yaml", "config.yaml"} {
+ sum(filepath.Join(dir, name))
+ }
+ return h.Sum64()
+}
+
+// dshModelsSum sums the models a round writes the route from.
+func dshModelsSum(models []catalog.Model) uint64 {
+ b, err := json.Marshal(models)
+ if err != nil {
+ return uint64(time.Now().UnixNano()) // unknown: done again
+ }
+ return maphash.Bytes(dshSumSeed, b)
+}
+
// dshWiredOnce writes magpie's route again in every patch list whose route
// is not what magpie would write now, and says what could not be written.
func dshWiredOnce() string {
+ var r dshRounds
+ return r.once()
+}
+
+// once is dshWiredOnce, done only when something the round reads changed
+// since r's last round that found nothing to write.
+func (r *dshRounds) once() string {
dshWrites.Lock()
defer dshWrites.Unlock()
dir := dshHome()
@@ -1863,10 +1947,29 @@ func dshWiredOnce() string {
if len(files) == 0 {
// no dsh: the catalog isn't built for nothing every round, ~34 MB
// of garbage a minute in a magpie at rest
+ r.done = false
+ return ""
+ }
+ key := dshRoundKey{files: dshFilesSum(dir, files), gw: gateway.URL(), models: r.last.models}
+ // the stamp is read before the models are built: a change while they
+ // are moves it past the one kept, and the next round builds them again
+ if stamp := provider.StampNow(); !r.built || stamp != r.stamp || time.Since(r.at) >= dshModelsFor {
+ r.models, r.stamp, r.at, r.built = magpieModels("dsh"), stamp, time.Now(), true
+ key.models = dshModelsSum(r.models)
+ }
+ if r.done && key == r.last {
return ""
}
+ trouble := dshWiredWith(dir, files, r.models)
+ // kept only when the round wrote nothing and nothing else wrote while
+ // it ran: a file written by either is read again next round
+ r.last, r.done = key, trouble == "" && dshFilesSum(dir, dshProfiles(dir)) == key.files
+ return trouble
+}
+
+// dshWiredWith is a round's work, with the models it writes the route from.
+func dshWiredWith(dir string, files []string, models []catalog.Model) string {
var trouble []string
- models := magpieModels("dsh")
// a profile dsh has just made — the desktop app's, opened for the first
// time while magpie runs — is its empty template: given magpie's route
// and start as the catalog sync would, rather than left listing dsh's
diff --git a/internal/agent/dsh_rounds_test.go b/internal/agent/dsh_rounds_test.go
new file mode 100644
index 000000000..7852fe410
--- /dev/null
+++ b/internal/agent/dsh_rounds_test.go
@@ -0,0 +1,129 @@
+package agent
+
+import (
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// dshSettled is a profile with magpie's route, and keepDshWired's rounds
+// once the route is what magpie writes: the first round writes it, the
+// second finds nothing to write.
+func dshSettled(t *testing.T) (r *dshRounds, web string) {
+ t.Helper()
+ _, dir, web := dshRouteHome(t)
+ dshKeyFixture(dir)
+ os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+
+ dshRouteFixture("deepseek/pro")+
+ "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/flash\n"), 0o644)
+ r = &dshRounds{}
+ r.once()
+ r.once()
+ if !r.done {
+ t.Fatal("a round with nothing to write is not kept")
+ }
+ if !dshListed(web, "deepseek/pro") || !dshListed(web, "deepseek/flash") {
+ b, _ := os.ReadFile(web)
+ t.Fatalf("the route is not what magpie writes:\n%s", b)
+ }
+ return r, web
+}
+
+// dshListed reports whether the route in a patch list lists model.
+func dshListed(web, model string) bool {
+ b, _ := os.ReadFile(web)
+ return strings.Contains(string(b), "- id: "+model+"\n")
+}
+
+// A user's magpie allocated 35.7 GB in 48 minutes with ~157 MB live, its
+// heap peaking near 885 MB; 12 GB of it was keepDshWired's round, every 30
+// seconds building magpie's whole catalog and every route again to write
+// nothing. A round with nothing changed since does nothing of that.
+func TestDshRoundWithNothingChangedBuildsNothing(t *testing.T) {
+ r, web := dshSettled(t)
+ before, _ := os.ReadFile(web)
+ if n := testing.AllocsPerRun(10, func() { r.once() }); n > 300 {
+ t.Fatalf("a round with nothing changed made %.0f allocations", n)
+ }
+ if after, _ := os.ReadFile(web); string(after) != string(before) {
+ t.Fatalf("a round with nothing changed wrote:\n%s", after)
+ }
+}
+
+// What a round goes by changing has the next round write the route again:
+// a provider saved, a setting saved, the patch list written over by dsh,
+// and the providers' file written by another magpie (the CLI).
+func TestDshRoundAfterAChangeWritesAgain(t *testing.T) {
+ t.Run("provider", func(t *testing.T) {
+ r, web := dshSettled(t)
+ if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash", "max"}}); err != nil {
+ t.Fatal(err)
+ }
+ r.once()
+ if !dshListed(web, "deepseek/max") {
+ t.Fatal("a model added to a provider is not in dsh's route after the next round")
+ }
+ })
+ t.Run("setting", func(t *testing.T) {
+ r, web := dshSettled(t)
+ s := settings.Load()
+ s.HiddenModels = map[string][]string{"dsh": {"deepseek/pro"}}
+ if err := settings.Save(s); err != nil {
+ t.Fatal(err)
+ }
+ r.once()
+ if dshListed(web, "deepseek/pro") {
+ t.Fatal("a model hidden from dsh is still in its route after the next round")
+ }
+ })
+ t.Run("patch list", func(t *testing.T) {
+ r, web := dshSettled(t)
+ os.WriteFile(web, []byte("# Your patch layer for this dsh profile.\n"+
+ dshRouteFixture("deepseek/pro")+
+ "- id: agent-default-model\n config:\n provider: magpie\n model: deepseek/flash\n"), 0o644)
+ r.once()
+ if !dshListed(web, "deepseek/flash") {
+ t.Fatal("a route dsh wrote over is not written again by the next round")
+ }
+ })
+ t.Run("another magpie", func(t *testing.T) {
+ r, web := dshSettled(t)
+ b, err := os.ReadFile(provider.Path())
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := strings.Replace(string(b), `"flash"`, `"flash", "max"`, 1)
+ if s == string(b) {
+ t.Fatalf("no model list in the providers' file:\n%s", b)
+ }
+ if err := os.WriteFile(provider.Path(), []byte(s), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ r.once()
+ if !dshListed(web, "deepseek/max") {
+ t.Fatal("a provider another magpie saved is not in dsh's route after the next round")
+ }
+ })
+ // what the stamp can't see (another app's account file, a date) is
+ // written by a round once the models are dshModelsFor old
+ t.Run("unseen", func(t *testing.T) {
+ r, web := dshSettled(t)
+ if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash", "max"}}); err != nil {
+ t.Fatal(err)
+ }
+ r.stamp = provider.StampNow() // as if the stamp hadn't moved
+ r.once()
+ if dshListed(web, "deepseek/max") {
+ t.Fatal("a round with its stamp unmoved built the models again: the test sees no skip")
+ }
+ r.at = time.Now().Add(-dshModelsFor)
+ r.once()
+ if !dshListed(web, "deepseek/max") {
+ t.Fatal("models dshModelsFor old are not built again")
+ }
+ })
+}
diff --git a/internal/provider/hold.go b/internal/provider/hold.go
index 52ced4f9e..1e5314543 100644
--- a/internal/provider/hold.go
+++ b/internal/provider/hold.go
@@ -155,6 +155,29 @@ func dropHeld() {
held.Unlock()
}
+// Stamp marks what the catalog is built from, read without building it.
+// Two equal stamps mean nothing magpie wrote or was told of came between
+// them: no Changed (a provider, an account, a setting saved), no plugin's
+// change, no catalog.Reset or Touched, no filememo.Forget, the same
+// environment, and the providers', the settings' and the catalog's own
+// files with the same time and size, as another process leaves them.
+// What it can't see — another app rewriting an account's file, a model
+// retired by its date — a caller that keeps what it built across stamps
+// builds again now and then all the same.
+type Stamp struct {
+ gen, fgen, env uint64
+ roots [3]rootStamp
+}
+
+// StampNow is the Stamp as things are now.
+func StampNow() Stamp {
+ held.Lock()
+ gen := held.gen
+ held.Unlock()
+ return Stamp{gen: gen, fgen: filememo.Gen(), env: environSum(),
+ roots: [3]rootStamp{stampOf(Path()), stampOf(settings.Path()), stampOf(catalog.CachePath())}}
+}
+
// heldOf is what build gives, built once while a request holds it.
func heldOf[T any](key string, build func() T) T {
held.Lock()