Skip to content

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

80.5 KB
Raw Blame
package agent

// DeepSeek Harness (dsh) boots from its shipped rows and then applies a
// personal patch list: a YAML list of {id, config} entries, each replacing
// the whole config of the row with that id. Since 0.1.5 every profile has
// its own, ~/.dsh/profiles/<name>/cordis.patch.yml (web and desktop read it
// live); before that there was one, ~/.dsh/config.yaml.
//
// Since 0.1.5 magpie is one of dsh's custom model providers: a route named
// magpie in the llm-pi-ai entry's providers (what dsh's Models page writes
// for "Add model provider"), with the gateway as its endpoint, the catalog
// as its models and, as the key, a credential named in apiKeyEnv, which
// magpie puts in ~/.dsh/.env and dsh's own key store (the desktop app reads
// only the store); agent-default-model names the model new
// sessions start on. dsh's own DeepSeek row (llm-deepseek) is left to dsh:
// taken over, it read as DeepSeek in dsh's Models page, and a DeepSeek key
// entered there went to the gateway under magpie's credential name, over
// magpie's own (Discord: 集成进 dsh 会被 dsh 覆写). A route of the user's in
// the same entry stays as it is, and so does one dsh adds beside magpie's.
//
// Before 0.1.5, which has no custom providers, magpie took over
// llm-deepseek, with the key in the entry, and set agent-loop's main agent
// (the TUI) and api-gateway's route (`dsh -p`, `dsh web`). Entries magpie
// writes whole are marked as magpie's, the user's own entries stay as they
// are, and one magpie replaces is stashed and put back when it steps out.

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"hash/maphash"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"slices"
	"strings"
	"sync"
	"time"

	"gopkg.in/yaml.v3"

	"github.com/yetone/magpie/internal/appdir"
	"github.com/yetone/magpie/internal/beat"
	"github.com/yetone/magpie/internal/catalog"
	"github.com/yetone/magpie/internal/edit"
	"github.com/yetone/magpie/internal/gateway"
	"github.com/yetone/magpie/internal/provider"
)

const dshMark = "# magpie"

// dshKeyRef is the credential dsh signs gateway requests with. It is not
// dshOldKeyRef, the one magpie's llm-deepseek entry named: dsh's Models page
// showed that entry as DeepSeek, so a DeepSeek key entered there may sit in
// dsh's own store under that name, which dsh reads over .env.
const (
	dshKeyRef    = "MAGPIE_GATEWAY_KEY"
	dshOldKeyRef = "MAGPIE_API_KEY"
)

// dshRoute is magpie's route among dsh's custom providers, and the
// provider agent-default-model names for a model through magpie.
const dshRoute = magpieID

// dshPiRow is the row custom providers are configured on, and its plugin.
const (
	dshPiRow    = "llm-pi-ai"
	dshPiPlugin = "@deepseek-ai/dsh-llm-pi-ai"
)

// dshModels are the models dsh reaches on its own, as it ships them — under
// its own name, not DeepSeek: magpie's DeepSeek provider is a group of that
// name too, and two would read as one listed twice (#115).
var dshModels = []Option{
	{Value: "deepseek-flash", Label: "DeepSeek-V41-Flash", Icon: "deepseek-color", Group: "DeepSeek Harness"},
	{Value: "deepseek-v4-pro", Label: "DeepSeek-V4-Pro", Icon: "deepseek-color", Group: "DeepSeek Harness"},
	{Value: "deepseek-v4-flash", Label: "DeepSeek-V4-Flash", Icon: "deepseek-color", Group: "DeepSeek Harness"},
}

func dsh(home string) *Agent { return dshAt(here(home)) }

// dshIn is DeepSeek Harness in a WSL distro (see wsl.go).
func dshIn(at place) *Agent { return dshAt(at) }

// dshAt is DeepSeek Harness with its home at at.home, reaching the gateway
// as at does. A distro's DSH_HOME can't be read, so there it is ~/.dsh.
func dshAt(at place) *Agent {
	gw := at.gw
	dir := at.getenv("DSH_HOME")
	if dir == "" {
		dir = filepath.Join(at.home, ".dsh")
	}
	// DeepSeek Harness Desktop, on this machine (a distro has none)
	desktop := func() bool { return at.spell == nil && (&Agent{ID: "dsh"}).HasApp() }
	path := filepath.Join(dir, "config.yaml")
	// a stopped distro's folder is never listed: that starts it (#3896)
	var files []string
	if !at.cold {
		files = dshProfiles(dir)
	}
	if len(files) > 0 {
		path = files[0]
	} else if desktop() {
		path = dshDesktopFile(dir)
	}
	return &Agent{
		ID: "dsh", Name: "DeepSeek Harness", Icon: "deepseek-color", Aliases: []string{"deepseek-harness"}, Spelled: prefixed,
		UA:  []string{"deepseek-harness"},
		Bin: "dsh", Dir: dir, Path: path,
		// the desktop app installed and not opened yet has no ~/.dsh (#2279)
		sign: desktop,
		Sync: func() error { return dshSync(dir, gw()) },
		Notice: func() string {
			var notes []string
			if desktop() && dshUnopened(dir) {
				// nothing of dsh's runs on it yet to be restarted
				notes = append(notes, noticeDsh5.String())
			} else if len(dshProfiles(dir)) > 0 {
				// a session dsh already has keeps the model it was on,
				// running or not: agent-default-model is read for new
				// ones only (#2359)
				notes = append(notes, noticeDsh1.String())
			} else if Running(`DeepSeek Harness\.app/`, `(^|/)dsh( |$)`) {
				notes = append(notes, noticeDsh2.String())
			}
			if dshSearchesHere(dir) && !gateway.CanSearch() {
				notes = append(notes, noticeDsh3.String())
			}
			// only before 0.1.5 does magpie go through llm-deepseek
			if len(dshProfiles(dir)) == 0 && dshSettingsEndpoint(filepath.Join(dir, "settings.yaml")) {
				notes = append(notes, noticeDsh4.String())
			}
			return strings.Join(notes, " ")
		},
		Check: func() string { return dshCheck(dir, gw()) },
		// a model of DeepSeek's own picked in dsh (saved in its settings)
		// leaves magpie's route in its list: dsh is still connected, its
		// /model has magpie's models beside DeepSeek's (Fate on Discord:
		// DSH went back to Not connected)
		Joined: func() bool {
			files := dshProfiles(dir)
			if len(files) == 0 {
				return false
			}
			_, items, err := dshRead(files[0])
			return err == nil && dshWired(dshOver(dir, items))
		},
		// connected so, Disconnect takes the route out, the start magpie
		// wrote and its key; the model picked in dsh stays its own
		Unwire: func() error {
			if usesMagpie(dshGet(dir)) {
				return nil // the model set back does it all
			}
			dshWrites.Lock()
			defer dshWrites.Unlock()
			for _, f := range dshProfiles(dir) {
				if err := dshKeepPick(f); err != nil {
					return err
				}
				if err := dshSetFile(f, "", true, nil, gw()); err != nil {
					return err
				}
			}
			if err := dshMirrorHome(dir, nil, gw(), true); err != nil {
				return err
			}
			return dshEnv(dir, gw(), false, false)
		},
		// what magpie made for a desktop app never opened goes (#2279)
		Restore: func() error { return dshTidyUnopened(dir) },
		Fields: []Field{{
			Key: "model", Label: "model",
			Get: func() string { return dshGet(dir) },
			Set: func(v string) error {
				// the desktop app not opened yet: its profile is made as
				// it makes it, and it keeps the patch list it finds (#2279)
				if v != "" && len(dshProfiles(dir)) == 0 && desktop() {
					if err := dshMakeDesktop(dir); err != nil {
						return err
					}
				}
				return dshSet(dir, v, gw())
			},
			Options: func(map[string]string) []Option {
				own := append([]Option{}, dshModels...)
				// since 0.1.5 dsh's own go to DeepSeek on its own key, its
				// llm-deepseek row left to it, and say so as every agent's
				// own do (EZN7L2C3, #955); before, magpie took that row over
				if len(dshProfiles(dir)) > 0 {
					for i := range own {
						own[i].Direct = "DeepSeek"
					}
				}
				return append(own, viaMagpie("dsh", magpieID+"/")...)
			},
		}, {
			// the thinking effort sessions start with: agent-default-model's
			// reasoningEffort since 0.1.5 (a model through magpie offers its
			// own levels), llm-deepseek's before (off, low, high or max;
			// dsh's own default is high)
			Key: "effort", Label: "thinking",
			Get: func() string { return dshGetEffort(dir) },
			Set: func(v string) error { return dshSetEffort(dir, v, gw()) },
			Options: func(cur map[string]string) []Option {
				// a model through magpie that lists no levels has none in
				// dsh (its route gives it no reasoningEfforts), so none is
				// offered: dsh's own four were, and each was turned away
				if ref, ok := strings.CutPrefix(cur["model"], magpieID+"/"); ok && len(dshProfiles(dir)) > 0 {
					return static(dshLevels(ref)...)
				}
				return static(dshEfforts...)
			},
		}},
	}
}

// dshProfiles are the profiles' patch lists (dsh 0.1.5 on), web's first.
func dshProfiles(dir string) []string {
	files, _ := filepath.Glob(filepath.Join(dir, "profiles", "*", "cordis.patch.yml"))
	var web, rest []string
	for _, f := range files {
		if filepath.Base(filepath.Dir(f)) == "web" {
			web = append(web, f)
		} else {
			rest = append(rest, f)
		}
	}
	return append(web, rest...)
}

// dshProfileTemplate is the patch list dsh writes for a new profile
// (PROFILE_PATCH_TEMPLATE in DeepSeek Harness Desktop 0.2.0-rc.2's
// lib/main.js, initProfile).
const dshProfileTemplate = "# Your patch layer for this dsh profile, applied after every bundle layer:\n" +
	"# a top-level YAML array of loader patch entries (id-targeted config\n" +
	"# overrides, disables, and insert lists; `!!js` expressions allowed).\n" +
	"[]\n"

// dshDesktopFile is the desktop app's profile's patch list: the app's
// profile is $DSH_HOME/profiles/desktop (resolveDesktopPaths).
func dshDesktopFile(dir string) string {
	return filepath.Join(dir, "profiles", "desktop", "cordis.patch.yml")
}

// dshMakeDesktop makes the desktop app's patch list, as dsh's template,
// for an app installed and never opened (#2279, liangjinyuan-sihan): with
// no profile at all magpie had nowhere to write, and DeepSeek Harness
// Desktop has no ~/.dsh until its first start. The app's initProfile
// writes each of a profile's files only where it is missing ("Existing
// files are never touched"), so on its first start it adds its
// package.json and pnpm-workspace.yaml beside this one and keeps
// magpie's entries. The folder is owner-only, as the app makes it.
func dshMakeDesktop(dir string) error {
	f := dshDesktopFile(dir)
	if err := os.MkdirAll(filepath.Dir(f), 0o700); err != nil {
		return err
	}
	if _, err := os.Stat(f); err == nil {
		return nil
	}
	return os.WriteFile(f, []byte(dshProfileTemplate), 0o644)
}

// dshUnopened says the desktop app's profile is one magpie made and the
// app hasn't started on yet: it has no package.json, which the app's first
// start writes.
func dshUnopened(dir string) bool {
	f := dshDesktopFile(dir)
	if !isFile(f) {
		return false
	}
	_, err := os.Stat(filepath.Join(filepath.Dir(f), "package.json"))
	return errors.Is(err, os.ErrNotExist)
}

// dshTidyUnopened takes out, on Disconnect, what magpie made for a desktop
// app never opened since: the profile's patch list back to dsh's template
// with nothing beside it, and the folders that leaves empty. A patch list
// holding anything else, or a profile the app has started on, stays.
func dshTidyUnopened(dir string) error {
	f := dshDesktopFile(dir)
	if !dshUnopened(dir) {
		return nil
	}
	b, err := os.ReadFile(f)
	if err != nil || strings.ReplaceAll(string(b), "\r\n", "\n") != dshProfileTemplate {
		return nil
	}
	if es, err := os.ReadDir(filepath.Dir(f)); err != nil || len(es) != 1 {
		return nil
	}
	if err := os.Remove(f); err != nil {
		return err
	}
	// only folders left empty: os.Remove refuses one that isn't
	for _, d := range []string{filepath.Dir(f), filepath.Join(dir, "profiles")} {
		if os.Remove(d) != nil {
			break
		}
	}
	return nil
}

// dshHomePatch is dsh's home patch layer, $DSH_HOME/cordis.patch.yml: it is
// applied over every profile's own, so an entry there replaces the profile's
// of the same id, whatever magpie wrote in that one (#804).
func dshHomePatch(dir string) string { return filepath.Join(dir, "cordis.patch.yml") }

// dshOver is a profile's patch list as dsh goes by it. A home patch only
// replaces the fields it supplies: config replaces the whole config, but
// disabled:false alone leaves the profile's config intact. For reading only.
func dshOver(dir string, items []dshItem) []dshItem {
	_, home, err := dshRead(dshHomePatch(dir))
	if err != nil || len(home) == 0 {
		return items
	}
	out := append([]dshItem{}, items...)
	for _, patch := range home {
		i := dshFindLast(out, patch.id)
		if i < 0 {
			out = append(out, patch)
			continue
		}
		n, err := dshNode(out[i])
		p, patchErr := dshNode(patch)
		if err != nil || patchErr != nil {
			out = append(out, patch)
			continue
		}
		if name, prev := yamlKey(p, "name"), yamlKey(n, "name"); name != nil && prev != nil && name.Value != "" && name.Value != prev.Value {
			continue // dsh ignores a patch naming a different plugin
		}
		for k := 0; k+1 < len(p.Content); k += 2 {
			if key := p.Content[k].Value; key != "id" && key != "name" {
				yamlSetKey(n, key, p.Content[k+1])
			}
		}
		if lines, err := dshNodeLines(n); err == nil {
			out[i].lines = lines
		}
	}
	return out
}

// dshConfigIndex is the last patch supplying this row's config. A later
// metadata-only patch must not hide it or acquire a replacement config.
func dshConfigIndex(items []dshItem, id string) int {
	for i := len(items) - 1; i >= 0; i-- {
		if items[i].id == id {
			if n, err := dshNode(items[i]); err == nil && yamlKey(n, "config") != nil {
				return i
			}
		}
	}
	return -1
}

// dshHomeHas reports whether the home layer overrides this row's config.
func dshHomeHas(dir, id string) bool {
	_, home, err := dshRead(dshHomePatch(dir))
	return err == nil && dshConfigIndex(home, id) >= 0
}

// dshMirrorHome gives the home layer what magpie wrote in the profiles, for
// the entries it overrides them with: magpie's route in a llm-pi-ai entry
// there (the user's routes beside it stay), and in an agent-default-model
// there the model magpie set. Without it dsh ran the home layer's snapshot
// while magpie read as connected (#804). An entry the home layer doesn't
// have is not added: the profiles' own then apply, as written. start is
// true only for an explicit model pick or disconnect. Catalog refreshes
// leave the home layer's start model alone, as they do the profiles'.
func dshMirrorHome(dir string, models []catalog.Model, gw string, start bool) error {
	files := dshProfiles(dir)
	if len(files) == 0 {
		return nil
	}
	home := dshHomePatch(dir)
	head, items, err := dshRead(home)
	if err != nil {
		return nil
	}
	_, web, err := dshRead(files[0])
	if err != nil {
		return nil
	}
	before := dshJoin(items)
	if dshConfigIndex(items, dshPiRow) >= 0 {
		on := dshWired(web)
		if !on || len(models) > 0 {
			if items, err = dshPutRoute(items, on, models, gw); err != nil {
				return err
			}
		}
	}
	// a start of the home layer's own on a model now on another route of
	// magpie's goes with it, as a profile's does (dshPutRoute)
	if len(models) > 0 {
		items = dshStartOnItsRoute(items, models)
	}
	if i := dshConfigIndex(items, "agent-default-model"); start && i >= 0 {
		j := dshFindLast(web, "agent-default-model")
		switch {
		case j >= 0 && dshOurs(web[j]):
			if !dshOurs(items[i]) {
				stash(map[string]string{dshStashKey(home, "agent-default-model"): strings.Join(items[i].lines, "\n")})
			}
			items[i] = dshItem{id: "agent-default-model", magpie: true, lines: append([]string{}, web[j].lines...)}
		case dshOurs(items[i]):
			// magpie's start gone from the profiles: the user's back, or none
			if old := unstash(dshStashKey(home, "agent-default-model")); old != "" {
				items[i] = dshItem{id: "agent-default-model", lines: strings.Split(old, "\n")}
			} else {
				items = append(items[:i], items[i+1:]...)
			}
		}
	}
	if dshJoin(items) == before {
		return nil
	}
	return dshWrite(home, head, items)
}

func dshJoin(items []dshItem) string {
	var b strings.Builder
	for _, it := range items {
		b.WriteString(strings.Join(it.lines, "\n"))
		b.WriteString("\n")
	}
	return b.String()
}

// dshItem is one entry of the patch list, as its lines.
type dshItem struct {
	id     string
	magpie bool
	lines  []string
}

var dshIDLine = regexp.MustCompile(`^(?:- |  )id:\s*['"]?([^'"#\s]+)['"]?\s*(#.*)?$`)

// dshParse splits the patch list at path into what comes before its first
// entry and the entries. A list written in flow style ([ {id: a} ], which
// dsh's own writers keep a profile's [] in) is read as the same list in block
// style, and written back so; a file that is no list is left alone.
func dshParse(path, raw string) (head []string, items []dshItem, err error) {
	if b, ok := edit.BlockList(raw); ok {
		raw = b
	}
	opened := false // a "---" or "[]" came before the first entry
	for _, l := range splitLinesKeep(raw) {
		// magpie's notes are left out, and dshWrite puts them back: a
		// route is compared with the lines magpie would write
		if edit.IsNote(l) {
			continue
		}
		t := strings.TrimSpace(l)
		switch {
		case strings.HasPrefix(l, "- ") || l == "-":
			items = append(items, dshItem{lines: []string{l}})
		case len(items) == 0:
			// "---" is YAML's document start marker: a patch list may open
			// with one (#2667), and it stays in the head it is written back
			// with, so the file keeps it. Only at the left edge and before
			// anything but comments: a second one starts a second
			// document, which is no list magpie can edit.
			marker := dshDocStart(l) && !opened
			if t != "" && !strings.HasPrefix(t, "#") && t != "[]" && !marker {
				return nil, nil, fmt.Errorf("%s is not a list of entries magpie can edit", path)
			}
			if t != "" && !strings.HasPrefix(t, "#") {
				opened = true
			}
			if t != "[]" {
				head = append(head, l)
			}
			continue
		case t != "" && !strings.HasPrefix(t, "#") && !strings.HasPrefix(l, " "):
			return nil, nil, fmt.Errorf("%s is not a list of entries magpie can edit", path)
		default:
			items[len(items)-1].lines = append(items[len(items)-1].lines, l)
		}
		it := &items[len(items)-1]
		if m := dshIDLine.FindStringSubmatch(l); m != nil && it.id == "" {
			it.id = m[1]
			it.magpie = strings.TrimSpace(m[2]) == dshMark
		}
	}
	return head, items, nil
}

func splitLinesKeep(s string) []string {
	s = strings.ReplaceAll(s, "\r\n", "\n")
	s = strings.TrimRight(s, "\n")
	if s == "" {
		return nil
	}
	return strings.Split(s, "\n")
}

func dshRead(path string) ([]string, []dshItem, error) {
	b, err := edit.Read(path)
	if err != nil {
		return nil, nil, err
	}
	return dshParse(path, string(b))
}

// dshWrite puts a patch list back together.
func dshWrite(path string, head []string, items []dshItem) error {
	out := append([]string{}, head...)
	for _, it := range items {
		out = append(out, it.lines...)
	}
	if len(items) == 0 {
		if _, err := os.Stat(path); err != nil {
			return nil // nothing was there, nothing to write
		}
		out = append(out, "[]") // dsh wants a list, even an empty one
	}
	// a route on the gateway says so (edit.Mark)
	orig, _ := edit.Read(path)
	out = edit.MarkYAMLLines(out, string(orig))
	return edit.WriteAtomic(path, []byte(strings.Join(out, "\n")+"\n"))
}

func dshFind(items []dshItem, id string) int {
	for i, it := range items {
		if it.id == id {
			return i
		}
	}
	return -1
}

// dshFindLast is the entry of that id dsh goes by: the last, as its own
// config editor edits.
func dshFindLast(items []dshItem, id string) int {
	for i := len(items) - 1; i >= 0; i-- {
		if items[i].id == id {
			return i
		}
	}
	return -1
}

// dshNode reads one entry as YAML: its mapping ({id, name, config}).
func dshNode(it dshItem) (*yaml.Node, error) {
	var doc yaml.Node
	if err := yaml.Unmarshal([]byte(strings.Join(it.lines, "\n")), &doc); err != nil {
		return nil, err
	}
	if len(doc.Content) == 0 || doc.Content[0].Kind != yaml.SequenceNode || len(doc.Content[0].Content) != 1 || doc.Content[0].Content[0].Kind != yaml.MappingNode {
		return nil, fmt.Errorf("the %s entry is not one magpie can edit", it.id)
	}
	return doc.Content[0].Content[0], nil
}

// dshNodeLines writes an entry read with dshNode back as lines.
func dshNodeLines(n *yaml.Node) ([]string, error) {
	var buf bytes.Buffer
	enc := yaml.NewEncoder(&buf)
	enc.SetIndent(2)
	if err := enc.Encode(&yaml.Node{Kind: yaml.SequenceNode, Content: []*yaml.Node{n}}); err != nil {
		return nil, err
	}
	enc.Close()
	return splitLinesKeep(buf.String()), nil
}

func yamlKey(n *yaml.Node, key string) *yaml.Node {
	if n == nil || n.Kind != yaml.MappingNode {
		return nil
	}
	for i := 0; i+1 < len(n.Content); i += 2 {
		if n.Content[i].Value == key {
			return n.Content[i+1]
		}
	}
	return nil
}

func yamlSetKey(n *yaml.Node, key string, v *yaml.Node) {
	for i := 0; i+1 < len(n.Content); i += 2 {
		if n.Content[i].Value == key {
			n.Content[i+1] = v
			return
		}
	}
	n.Content = append(n.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, v)
}

func yamlDelKey(n *yaml.Node, key string) {
	for i := 0; i+1 < len(n.Content); i += 2 {
		if n.Content[i].Value == key {
			n.Content = append(n.Content[:i], n.Content[i+2:]...)
			return
		}
	}
}

// yamlMapping is the mapping at key, made when there is none (or the value
// there is not one).
func yamlMapping(n *yaml.Node, key string) *yaml.Node {
	if v := yamlKey(n, key); v != nil && v.Kind == yaml.MappingNode {
		return v
	}
	v := &yaml.Node{Kind: yaml.MappingNode}
	yamlSetKey(n, key, v)
	return v
}

// dshConfig reads the scalar fields of an entry's config: dsh writes them
// as it likes, quoted or not.
func dshConfig(it dshItem) map[string]string {
	n, err := dshNode(it)
	if err != nil {
		return nil
	}
	out := map[string]string{}
	if c := yamlKey(n, "config"); c != nil && c.Kind == yaml.MappingNode {
		for i := 0; i+1 < len(c.Content); i += 2 {
			if v := c.Content[i+1]; v.Kind == yaml.ScalarNode {
				out[c.Content[i].Value] = v.Value
			}
		}
	}
	return out
}

// dshRoutesIn are magpie's routes among the custom providers of a patch
// list, by key: none when there are none.
func dshRoutesIn(items []dshItem) map[string]*yaml.Node {
	i := dshConfigIndex(items, dshPiRow)
	if i < 0 {
		return nil
	}
	n, err := dshNode(items[i])
	if err != nil {
		return nil
	}
	providers := yamlKey(yamlKey(n, "config"), "providers")
	var out map[string]*yaml.Node
	for _, k := range dshKinds {
		if r := yamlKey(providers, k.key); r != nil {
			if out == nil {
				out = map[string]*yaml.Node{}
			}
			out[k.key] = r
		}
	}
	return out
}

// dshOldWiring reports whether a profile still has what magpie wrote before
// it was a custom provider: dsh's own DeepSeek row taken over.
func dshOldWiring(items []dshItem) bool {
	i := dshFind(items, "llm-deepseek")
	return i >= 0 && items[i].magpie
}

// dshOurs reports whether an entry is magpie's: marked so, or — should dsh
// rewrite it without the mark — a model on magpie's route, which is gone
// with it.
func dshOurs(it dshItem) bool {
	return it.magpie || it.id == "agent-default-model" && isDshRoute(dshConfig(it)["provider"])
}

// dshWired reports whether a profile's patch list has a route of magpie's.
func dshWired(items []dshItem) bool { return len(dshRoutesIn(items)) > 0 }

// dshServes reports whether magpie gives dsh this model now: the route
// written again would list it, where one naming a model magpie no longer
// gives dsh would not.
func dshServes(id string) bool {
	for _, m := range magpieModels("dsh") {
		if m.ID == id {
			return true
		}
	}
	return false
}

// dshRouteLists reports whether a route of magpie's carries a model with
// this id; a route there is none of lists none.
func dshRouteLists(route *yaml.Node, id string) bool {
	models := yamlKey(route, "models")
	if models == nil {
		return false
	}
	for _, m := range models.Content {
		if v := yamlKey(m, "id"); v != nil && v.Value == id {
			return true
		}
	}
	return false
}

var dshModelLine = regexp.MustCompile(`^\s+model:\s*(.+?)\s*$`)

// dshGet reads the model new sessions start on: the one last picked in dsh,
// saved in its settings (0.1.x), else the patch list's.
func dshGet(dir string) string {
	files := dshProfiles(dir)
	if len(files) == 0 {
		return dshGetLegacy(filepath.Join(dir, "config.yaml"))
	}
	_, items, err := dshRead(files[0])
	if err != nil {
		return ""
	}
	return dshStart(dir, items)
}

// dshStart reads the model a profile's sessions start on: the one last picked
// in dsh, saved in its settings, which go over every profile, else the
// agent-default-model entry of the home layer or the profile's own. dsh 0.2
// keeps a pick in that entry itself: a settings.yaml left by 0.1.x is
// imported into the profile it next boots and renamed settings.yaml.imported,
// which nothing reads (#1392).
func dshStart(dir string, items []dshItem) string {
	items = dshOver(dir, items)
	sel := dshStartSel(dir, items)
	switch {
	case sel["model"] == "":
		return ""
	case isDshRoute(sel["provider"]),
		// set before magpie was a provider of its own, not yet moved
		sel["provider"] == "deepseek-official" && dshOldWiring(items):
		return magpieID + "/" + sel["model"]
	}
	return sel["model"]
}

// dshStartSel is the start of a profile's patch list read over the home
// layer (dshOver), as dsh names it: provider (the route) and model.
func dshStartSel(dir string, items []dshItem) map[string]string {
	sel := edit.GetYAMLMap(filepath.Join(dir, "settings.yaml"), "agent-default-model")
	if sel["model"] == "" {
		if i := dshFindLast(items, "agent-default-model"); i >= 0 {
			sel = dshConfig(items[i])
		}
	}
	return sel
}

// dshGetLegacy reads agent-loop's model from a config.yaml before 0.1.5.
func dshGetLegacy(path string) string {
	_, items, err := dshRead(path)
	if err != nil {
		return ""
	}
	model := ""
	if i := dshFind(items, "agent-loop"); i >= 0 {
		for _, l := range items[i].lines {
			if m := dshModelLine.FindStringSubmatch(l); m != nil {
				model = yamlScalar(m[1])
				break
			}
		}
	}
	if model != "" && dshOldWiring(items) {
		return magpieID + "/" + model
	}
	return model
}

// dshCheck says what keeps a dsh on one of magpie's models from reaching
// the gateway: magpie's route (its llm-deepseek entry before 0.1.5) pointed
// elsewhere, the model it starts on one the route doesn't list, or — since
// 0.1.5 — the key it names gone from .env, or another key under that name in
// dsh's own store, which it reads first.
func dshCheck(dir, gw string) string {
	if !usesMagpie(dshGet(dir)) {
		return ""
	}
	files := dshProfiles(dir)
	if len(files) == 0 {
		path := filepath.Join(dir, "config.yaml")
		_, items, _ := dshRead(path)
		base := ""
		if i := dshFind(items, "llm-deepseek"); i >= 0 {
			for _, l := range items[i].lines {
				if k, v, ok := strings.Cut(strings.TrimSpace(l), ":"); ok && k == "baseURL" {
					base = yamlScalar(strings.TrimSpace(v))
				}
			}
		}
		get := func(string) (string, bool) { return base, base != "" }
		return wiringOff("DeepSeek Harness", path, get, "baseURL", gw+"/v1")
	}
	_, items, _ := dshRead(files[0])
	routeFile := files[0]
	if dshHomeHas(dir, dshPiRow) {
		routeFile = dshHomePatch(dir)
		// the home layer's llm-pi-ai goes over every profile's: without
		// magpie's route it lists none of magpie's models anywhere
		if !dshWired(dshOver(dir, items)) && dshWired(items) {
			return "DeepSeek Harness's home patch layer (" + routeFile + ") sets llm-pi-ai over every profile without magpie's route, so sessions list none of magpie's models; Apply again writes it there too"
		}
	}
	// a profile of dsh's (its desktop app's) without magpie's route: where
	// the start still names one of magpie's models the route was stripped by
	// dsh's own save, and the serving round writes it back within a round of
	// magpie serving — so that one is not said, unless there is no catalog
	// for the round to write it from. A profile taken off magpie for real,
	// its start with it, is said as before, and so is one still on the old
	// wiring, which dshSync moves rather than this round writing beside.
	canWriteBack := len(magpieModels("dsh")) > 0
	for _, f := range files[1:] {
		_, items, err := dshRead(f)
		if err != nil || dshWired(dshOver(dir, items)) {
			continue
		}
		if canWriteBack && !dshOldWiring(items) && dshStartsOnMagpie(dir, items) {
			continue
		}
		return "DeepSeek Harness's " + filepath.Base(filepath.Dir(f)) + " profile (" + f + ") has none of magpie's models, so sessions there list DeepSeek's own alone"
	}
	routes := dshRoutesIn(dshOver(dir, items))
	// the route gone entirely while the start still names one of magpie's
	// models is dsh's own save stripping it: the round writes it back, so
	// the check is quiet unless nothing can write it (no catalog below). A
	// start of dsh's own or of the user's fell through usesMagpie already,
	// and one on the old wiring is not this route's to speak for.
	if len(routes) == 0 && !dshOldWiring(items) && dshStartsOnMagpie(dir, items) {
		return dshCheckStripped(dir, gw)
	}
	if len(routes) == 0 && dshOldWiring(items) {
		// not moved yet; the next sync does it. dsh's DeepSeek row taken
		// over speaks Chat Completions.
		get := func(k string) (string, bool) {
			v, ok := dshConfig(items[dshFind(items, "llm-deepseek")])[k]
			return v, ok
		}
		if off := wiringOff("DeepSeek Harness", routeFile, get, "baseURL", dshBaseURL(dshKinds[0].api, gw)); off != "" {
			return off
		}
	}
	for _, k := range dshKinds {
		route := routes[k.key]
		if route == nil {
			continue
		}
		get := func(key string) (string, bool) {
			if v := yamlKey(route, key); v != nil && v.Kind == yaml.ScalarNode {
				return v.Value, true
			}
			return "", false
		}
		api, _ := get("api")
		if off := wiringOff("DeepSeek Harness", routeFile, get, "baseURL", dshBaseURL(dshAPI(api, k.api), gw)); off != "" {
			return off
		}
	}
	// dsh counts a model its provider doesn't list as none at all and refuses
	// the turn, so a model of magpie's a profile's route has not is as
	// unusable there as a route pointed elsewhere: a catalog that moved on, a
	// profile written elsewhere, or one dsh's Models page wrote leave it that
	// way. Every profile carries a route of its own, and dsh runs whichever
	// one its session names, so every profile is asked.
	for _, f := range files {
		_, it, err := dshRead(f)
		if err != nil {
			continue
		}
		over := dshOver(dir, it)
		routes := dshRoutesIn(over)
		if len(routes) == 0 {
			continue // no route yet: the sync this asks for writes one
		}
		if dshHomeHas(dir, dshPiRow) {
			f = dshHomePatch(dir)
		}
		// the route the start names (magpie's first for one still on dsh's
		// DeepSeek row), which must list its model
		on := dshStartSel(dir, over)["provider"]
		if !isDshRoute(on) {
			on = dshRoute
		}
		if ref, ok := strings.CutPrefix(dshStart(dir, it), magpieID+"/"); ok && !dshRouteLists(routes[on], ref) {
			// a route out of date is written again — Apply again, or picking
			// a model of magpie's in dsh, does it; one naming a model magpie
			// no longer gives dsh is not, so that one asks for another model
			// rather than for a click that cannot help
			if dshServes(ref) {
				return "DeepSeek Harness starts on " + magpieID + "/" + ref + ", which magpie's route in " + f + " doesn't list: a session there fails with no such configured model until that route is written again (Apply again, or pick one of magpie's models in dsh)"
			}
			return "DeepSeek Harness starts on " + magpieID + "/" + ref + ", which magpie no longer gives dsh: a session there fails with no such configured model until another of magpie's is picked in dsh"
		}
	}
	env := filepath.Join(dir, ".env")
	if off := wiringOff("DeepSeek Harness", env, func(k string) (string, bool) { return edit.GetEnvFile(env, k) },
		dshKeyRef, keyAt(gw)); off != "" {
		return off
	}
	creds := filepath.Join(dir, ".credentials.yaml")
	if v, ok := edit.GetYAML(creds, "refs."+dshKeyRef); ok && v != keyAt(gw) && !gatewayTakes(v) {
		if onAnotherMachine(gw) {
			return "DeepSeek Harness's own key store (" + creds + ") holds another " + dshKeyRef + ", which it uses over magpie's; remove it there (dsh's Models page, Magpie's key) to go through magpie"
		}
		return "DeepSeek Harness's own key store (" + creds + ") holds another " + dshKeyRef + ", which it uses over magpie's and this magpie refuses; Apply again puts magpie's key there (Disconnect puts this one back)"
	} else if !ok && dshCredsOurs(creds) {
		// the desktop app doesn't read .env (#969)
		return "DeepSeek Harness's own key store (" + creds + ") doesn't hold " + dshKeyRef + ": the desktop app reads the key from there, not from .env, and its sessions fail with no credential for provider route " + dshRoute + " until it is written (Apply again)"
	}
	return ""
}

// dshCheckStripped says what a route dsh's own save stripped still stands on:
// quiet where a round of the serving loop can write it back, said only where
// nothing can (no catalog to write it from — the key check still runs, since
// a route written without its key would fail the turn all the same).
func dshCheckStripped(dir, gw string) string {
	if len(magpieModels("dsh")) == 0 {
		return "DeepSeek Harness starts on one of magpie's models, but magpie's route is out of " + dshHomePatch(dir) + " and the profiles' and there is no model list to write it back from; pick a model of magpie's again once it has one"
	}
	env := filepath.Join(dir, ".env")
	if off := wiringOff("DeepSeek Harness", env, func(k string) (string, bool) { return edit.GetEnvFile(env, k) },
		dshKeyRef, keyAt(gw)); off != "" {
		return off
	}
	return ""
}

// yamlScalar reads a plain or quoted YAML scalar.
func yamlScalar(v string) string {
	if i := strings.Index(v, " #"); i >= 0 {
		v = strings.TrimSpace(v[:i])
	}
	if strings.HasPrefix(v, `"`) {
		var s string
		if json.Unmarshal([]byte(v), &s) == nil {
			return s
		}
	}
	return strings.Trim(v, `'"`)
}

func dshStashKey(path, id string) string { return "dsh:" + path + ":" + id }

// dshWrites serializes magpie's own writers of dsh's patch lists: the sync a
// catalog change asks for, a model picked here, and the round magpie does
// while it serves the gateway. Two of them reading one file and then writing
// it would leave whichever read first as its content.
var dshWrites sync.Mutex

// dshSet writes v as the model new sessions start on: a catalog model
// through the gateway, one of dsh's own models directly, or "" for dsh's own
// default. Every profile gets it; config.yaml only where there are none.
func dshSet(dir, v, gw string) error {
	dshWrites.Lock()
	defer dshWrites.Unlock()
	ref, viaGateway := strings.CutPrefix(v, magpieID+"/")
	if viaGateway && !isMagpie(ref) {
		return fmt.Errorf("unknown model %q", v)
	}
	legacy := filepath.Join(dir, "config.yaml")
	models := magpieModels("dsh")
	files := dshProfiles(dir)
	if len(files) == 0 {
		return dshSetFile(legacy, v, false, models, gw)
	}
	for _, f := range files {
		if err := dshSetFile(f, v, true, models, gw); err != nil {
			return err
		}
	}
	if err := dshMirrorHome(dir, models, gw, true); err != nil {
		return err
	}
	// what an older dsh was given is no use now
	if _, err := os.Stat(legacy); err == nil {
		if err := dshSetFile(legacy, "", false, models, gw); err != nil {
			return err
		}
	}
	if err := dshEnv(dir, gw, viaGateway, true); err != nil {
		return err
	}
	// a model picked in dsh 0.1.x is saved in its settings and goes over
	// the patch list; picking one here takes over from it
	settings := filepath.Join(dir, "settings.yaml")
	if v != "" && edit.GetYAMLMap(settings, "agent-default-model") != nil {
		return edit.DelYAML(settings, "agent-default-model")
	}
	return nil
}

// dshKeepPick hands a profile's start back to the user where dsh saved their
// own pick into magpie's agent-default-model entry. Since 0.2 dsh no longer
// keeps a pick in ~/.dsh/settings.yaml: its /model (and the one-time import
// that renames settings.yaml to settings.yaml.imported) writes the config of
// the profile's last agent-default-model entry, which is magpie's, mark and
// all (#1392). A start there off magpie's route is the user's then, and
// Disconnect leaves it as it is, as it left a pick in settings.yaml before;
// what magpie stashed from before it wrote the entry is older than that pick.
// One still on the old wiring names DeepSeek's row for magpie's models and
// stays magpie's.
func dshKeepPick(f string) error {
	head, items, err := dshRead(f)
	if err != nil || dshOldWiring(items) {
		return nil
	}
	i := dshFind(items, "agent-default-model")
	if i < 0 || !items[i].magpie {
		return nil
	}
	if p := dshConfig(items[i])["provider"]; p == "" || isDshRoute(p) || dshConfig(items[i])["model"] == "" {
		return nil
	}
	lines := append([]string{}, items[i].lines...)
	lines[0] = strings.TrimRight(strings.Replace(lines[0], dshMark, "", 1), " ")
	items[i] = dshItem{id: items[i].id, lines: lines}
	unstash(dshStashKey(f, "agent-default-model"))
	return dshWrite(f, head, items)
}

// dshEnv puts the key for the gateway in $DSH_HOME/.env and dsh's own key
// store, or with on false takes it out; the name magpie's llm-deepseek entry
// used goes either way.
func dshEnv(dir, gw string, on, take bool) error {
	if err := dshCreds(dir, gw, on, take); err != nil {
		return err
	}
	env := filepath.Join(dir, ".env")
	if on {
		if v, ok := edit.GetEnvFile(env, dshKeyRef); !ok || v != keyAt(gw) {
			if err := edit.SetEnvFile(env, edit.KV{Path: dshKeyRef, Value: keyAt(gw)}); err != nil {
				return err
			}
		}
	}
	for _, k := range []string{dshKeyRef, dshOldKeyRef} {
		// the old name only as magpie left it
		if v, ok := edit.GetEnvFile(env, k); ok && !(k == dshKeyRef && on) && (k == dshKeyRef || ourKey(v)) {
			if err := edit.DelEnvFile(env, k); err != nil {
				return err
			}
		}
	}
	return nil
}

// dshCreds puts the key for the gateway in dsh's own key store,
// $DSH_HOME/.credentials.yaml (refs), or with on false takes magpie's out.
// Only the product CLI loads the .env files into what dsh resolves keys
// from: the desktop app reads this store and its own environment, and with
// the key in .env alone its sessions failed with "no credential for provider
// route magpie" (#969). The store wins over .env, so a key of the user's
// there is left as it is by the sync and the serving round (the check says
// so). take is a model picked, or Apply again: that replaces a key there
// this gateway refuses, which only fails every turn through magpie, and
// stashes it for Disconnect to put back (#1419, DannyJRu: Reconnect said
// done and the row stayed red). A key the gateway takes stays, and so does
// any key for a gateway on another machine, which only that one can judge.
// dsh refuses a store any other user can read, so a new one is made
// owner-only; one in a layout other than version 1 is dsh's to move and
// isn't touched.
func dshCreds(dir, gw string, on, take bool) error {
	creds := filepath.Join(dir, ".credentials.yaml")
	raw, err := os.ReadFile(creds)
	if err != nil && !errors.Is(err, os.ErrNotExist) {
		return err
	}
	if !dshCredsOurs(creds) {
		return nil
	}
	if on {
		v, ok := edit.GetYAML(creds, "refs."+dshKeyRef)
		if ok && v == keyAt(gw) {
			return nil
		}
		if ok && !ourKey(v) {
			if !take || gatewayTakes(v) || onAnotherMachine(gw) {
				return nil
			}
			stash(map[string]string{dshStashKey(creds, dshKeyRef): v})
		}
		if len(bytes.TrimSpace(raw)) == 0 {
			if err := os.MkdirAll(dir, 0o755); err != nil {
				return err
			}
			if err := os.WriteFile(creds, []byte("version: 1\n"), 0o600); err != nil {
				return err
			}
		}
		return edit.SetYAML(creds, edit.KV{Path: "refs." + dshKeyRef, Value: keyAt(gw)})
	}
	for _, k := range []string{dshKeyRef, dshOldKeyRef} {
		if v, ok := edit.GetYAML(creds, "refs."+k); ok && ourKey(v) {
			if err := edit.DelYAML(creds, "refs."+k); err != nil {
				return err
			}
		}
	}
	if v := unstash(dshStashKey(creds, dshKeyRef)); v != "" {
		if _, ok := edit.GetYAML(creds, "refs."+dshKeyRef); !ok {
			return edit.SetYAML(creds, edit.KV{Path: "refs." + dshKeyRef, Value: v})
		}
	}
	return nil
}

// dshCredsOurs says whether magpie may write dsh's key store: there is none
// yet, or it is in the version 1 layout.
func dshCredsOurs(creds string) bool {
	raw, err := os.ReadFile(creds)
	if errors.Is(err, os.ErrNotExist) {
		return true
	}
	if err != nil {
		return false
	}
	if len(bytes.TrimSpace(raw)) == 0 {
		return true
	}
	v, ok := edit.GetYAML(creds, "version")
	return ok && v == "1"
}

// dshSetFile writes v into one patch list; modern is the layout of dsh
// 0.1.5 on.
func dshSetFile(path, v string, modern bool, models []catalog.Model, gw string) error {
	head, items, err := dshRead(path)
	if err != nil {
		return err
	}
	ref, viaGateway := strings.CutPrefix(v, magpieID+"/")
	effort := ""
	if modern {
		effort = dshEffortOf(items)
	} else {
		effort = dshEffortIn(items)
	}
	put := func(id string, lines []string) {
		i := dshFind(items, id)
		if i >= 0 && !dshOurs(items[i]) {
			stash(map[string]string{dshStashKey(path, id): strings.Join(items[i].lines, "\n")})
		}
		it := dshItem{id: id, magpie: true, lines: lines}
		if i >= 0 {
			items[i] = it
		} else {
			items = append(items, it)
		}
	}
	drop := func(id string) {
		i := dshFind(items, id)
		if i < 0 || !dshOurs(items[i]) {
			return
		}
		if old := unstash(dshStashKey(path, id)); old != "" {
			items[i] = dshItem{id: id, lines: strings.Split(old, "\n")}
			return
		}
		items = append(items[:i], items[i+1:]...)
	}

	switch {
	case v == "":
		drop("agent-default-model")
		drop("api-gateway")
		drop("agent-loop")
		drop("llm-deepseek")
		if items, err = dshPutRoute(items, false, nil, gw); err != nil {
			return err
		}
		if modern {
			items = dshPutSearch(items, dshProfileHome(path), "", gw)
		}
	case modern && viaGateway:
		drop("llm-deepseek") // magpie's before it was a provider of its own
		if items, err = dshPutRoute(items, true, models, gw); err != nil {
			return err
		}
		if !contains(dshLevels(ref), effort) {
			effort = ""
		}
		put("agent-default-model", dshDefaultLines(dshRouteFor(ref, models), ref, effort))
		items = dshPutSearch(items, dshProfileHome(path), dshSearchModel(ref), gw)
	case modern:
		drop("llm-deepseek")
		if items, err = dshPutRoute(items, false, nil, gw); err != nil {
			return err
		}
		items = dshPutSearch(items, dshProfileHome(path), "", gw)
		if !contains(dshEfforts, effort) {
			effort = ""
		}
		put("agent-default-model", dshDefaultLines("deepseek-official", v, effort))
	case viaGateway:
		put("llm-deepseek", dshProviderLines(effort, models, gw))
		put("agent-loop", dshLoopLines(ref))
		put("api-gateway", dshRouteLines(ref))
	default:
		drop("api-gateway")
		drop("llm-deepseek")
		put("agent-loop", dshLoopLines(v))
	}
	return dshWrite(path, head, items)
}

// dshPutRoute puts magpie's route, with the catalog as it is now, among the
// custom providers of the llm-pi-ai entry, or with on false takes it out.
// Other routes there, the user's or ones dsh added beside magpie's, stay; an
// entry left with nothing goes.
func dshPutRoute(items []dshItem, on bool, models []catalog.Model, gw string) ([]dshItem, error) {
	i := dshConfigIndex(items, dshPiRow)
	if i < 0 {
		i = dshFindLast(items, dshPiRow)
	}
	if i < 0 && !on {
		return items, nil
	}
	var n *yaml.Node
	if i >= 0 {
		var err error
		if n, err = dshNode(items[i]); err != nil {
			return nil, err
		}
	} else {
		items = append(items, dshItem{id: dshPiRow, magpie: true, lines: []string{"- id: " + dshPiRow + " " + dshMark, "  name: " + yamlQuote(dshPiPlugin)}})
		i = len(items) - 1
		n, _ = dshNode(items[i])
	}
	config := yamlMapping(n, "config")
	providers := yamlMapping(config, "providers")
	if on {
		// each model on the route of the API it is best asked on; a route
		// left with none goes, the first stays when every one would
		byRoute := map[string][]catalog.Model{}
		for _, m := range models {
			byRoute[dshRouteOf(m)] = append(byRoute[dshRouteOf(m)], m)
		}
		for _, k := range dshKinds {
			ms := byRoute[k.key]
			if len(ms) == 0 && (k.key != dshRoute || len(models) > 0) {
				yamlDelKey(providers, k.key)
				continue
			}
			// the wire protocol the user picked for the route in dsh's
			// Models page stays, when it is one the gateway speaks
			api := ""
			if v := yamlKey(yamlKey(providers, k.key), "api"); v != nil && v.Kind == yaml.ScalarNode {
				api = v.Value
			}
			var route yaml.Node
			if err := route.Encode(dshKindConfig(k, ms, api, gw)); err != nil {
				return nil, err
			}
			// what dsh's Models page added to it (a default level, headers)
			// stays; magpie's fields are put as they are now
			if cur := yamlKey(providers, k.key); cur != nil && cur.Kind == yaml.MappingNode {
				dshKeepCompat(cur, &route)
				for j := 0; j+1 < len(route.Content); j += 2 {
					yamlSetKey(cur, route.Content[j].Value, route.Content[j+1])
				}
			} else {
				yamlSetKey(providers, k.key, &route)
			}
		}
		items = dshStartOnItsRoute(items, models)
	} else {
		for _, k := range dshKinds {
			yamlDelKey(providers, k.key)
		}
		if len(providers.Content) == 0 {
			yamlDelKey(config, "providers")
		}
		if len(config.Content) == 0 {
			yamlDelKey(n, "config")
		}
		if yamlKey(n, "config") == nil && len(n.Content) <= 4 { // id and name alone
			return append(items[:i], items[i+1:]...), nil
		}
	}
	lines, err := dshNodeLines(n)
	if err != nil {
		return nil, err
	}
	items[i] = dshItem{id: dshPiRow, magpie: items[i].magpie, lines: lines}
	return items, nil
}

// dshKeepCompat carries the compat switches set by hand in dsh's Models page
// (maxTokensField, say) from route cur, as it is in the file, into route,
// as magpie writes it now (#2504, h4rk8s): a model that works only with
// them would fail again after each sync. They stay on the same model of a
// route still on the same protocol; a model new to the route, or a route
// whose protocol changed, starts without them. A switch magpie sets itself
// is put as magpie has it now.
func dshKeepCompat(cur, route *yaml.Node) {
	api := yamlKey(cur, "api")
	if api == nil || yamlKey(route, "api") == nil || api.Value != yamlKey(route, "api").Value {
		return
	}
	old := map[string]*yaml.Node{}
	if ms := yamlKey(cur, "models"); ms != nil && ms.Kind == yaml.SequenceNode {
		for _, m := range ms.Content {
			c := yamlKey(m, "compat")
			if id := yamlKey(m, "id"); id != nil && c != nil && c.Kind == yaml.MappingNode {
				old[id.Value] = c
			}
		}
	}
	ms := yamlKey(route, "models")
	if ms == nil || ms.Kind != yaml.SequenceNode {
		return
	}
	for _, m := range ms.Content {
		id := yamlKey(m, "id")
		if id == nil || old[id.Value] == nil {
			continue
		}
		c := yamlMapping(m, "compat")
		for j := 0; j+1 < len(old[id.Value].Content); j += 2 {
			if yamlKey(c, old[id.Value].Content[j].Value) == nil {
				yamlSetKey(c, old[id.Value].Content[j].Value, old[id.Value].Content[j+1])
			}
		}
	}
}

// dshPiRoute is magpie's route as llm-pi-ai takes a custom provider (the
// shape dsh's Models page writes): one of the gateway's APIs (dshAPI), the
// key a credential named here, the catalog as its models.
type dshPiRoute struct {
	DisplayName string       `yaml:"displayName"`
	APIKeyEnv   string       `yaml:"apiKeyEnv"`
	API         string       `yaml:"api"`
	BaseURL     string       `yaml:"baseURL"`
	Models      []dshPiModel `yaml:"models"`
}

// dshPiModel is one model of the route. Without contextWindow and maxTokens
// dsh takes every model for a 128K one writing 16K at most, and without
// input for a text-only one; without reasoningEfforts it offers none.
type dshPiModel struct {
	ID               string       `yaml:"id"`
	Name             string       `yaml:"name,omitempty"`
	ContextWindow    int          `yaml:"contextWindow,omitempty"`
	MaxTokens        int          `yaml:"maxTokens,omitempty"`
	Input            []string     `yaml:"input,omitempty,flow"`
	ReasoningEfforts *dshPiLevels `yaml:"reasoningEfforts,omitempty"`
	Compat           *dshPiCompat `yaml:"compat,omitempty"`
}

// dshPiCompat is a model's compat switches. On Anthropic's Messages API
// pi-ai asks a model for a thinking budget unless forceAdaptiveThinking is
// set, and a Claude that thinks only adaptively turns a budget away. Z.ai's
// GLM-5.2 and GLM-5.3 are told so too: a budget can't ask them for max
// (dshKindConfig).
type dshPiCompat struct {
	ForceAdaptiveThinking bool `yaml:"forceAdaptiveThinking,omitempty"`
}

// dshAPIs are the wire protocols of llm-pi-ai's (pi-ai's api names) a route
// of magpie's may speak, the gateway serving each: openai-completions at
// /v1/chat/completions, openai-responses at /v1/responses and
// anthropic-messages at /v1/messages. dsh's Models page offers them as
// OpenAI Chat Completions, OpenAI Responses and Anthropic Messages, set for
// a route as a whole (llm-pi-ai has no api of a model's own); the gateway
// takes every model on each.
var dshAPIs = []string{"openai-completions", "openai-responses", "anthropic-messages"}

// dshKind is one of magpie's routes in llm-pi-ai: its key among the
// providers (what agent-default-model and a session name it by), the wire
// protocol it is written with, and the name dsh's model list groups it
// under.
type dshKind struct {
	key, api, name string
}

// dshKinds are magpie's routes, one per protocol a model is best asked on
// (Discord, 01huadalang: 可以按不同协议分成组来注入,例如 chat 一个组,response
// 一个组). llm-pi-ai sets the api for a route as a whole, so one route had
// every model on Chat Completions, and the gateway translated each turn of
// a GPT served on Responses or a Claude served on Messages from Chat: its
// sealed reasoning (Responses' encrypted_content, Messages' signed
// thinking) never went back to it between tool calls. A model goes on the
// route of the API its provider serves it on natively (catalog.Model.APIs,
// as Pi's, omp's and droid's are asked), and every other one — a group, a
// Chat provider's, a sign-in served through its agent's own API — on
// magpie's first route, which keeps its key.
var dshKinds = []dshKind{
	{dshRoute, "openai-completions", "Magpie"},
	{dshRoute + "-responses", "openai-responses", "Magpie · Responses"},
	{dshRoute + "-anthropic", "anthropic-messages", "Magpie · Anthropic"},
}

// isDshRoute reports whether a provider route dsh names is one of magpie's.
func isDshRoute(key string) bool {
	return dshKindOf(key) != nil
}

// dshKindOf is magpie's route of this key, nil for a route of anyone else's.
func dshKindOf(key string) *dshKind {
	for i := range dshKinds {
		if dshKinds[i].key == key {
			return &dshKinds[i]
		}
	}
	return nil
}

// dshRouteOf is the route of magpie's a model goes on: the one for the API
// its provider serves it on natively, the first otherwise.
func dshRouteOf(m catalog.Model) string {
	switch {
	case slices.Contains(m.APIs, string(provider.Responses)):
		return dshKinds[1].key
	case slices.Contains(m.APIs, string(provider.Anthropic)):
		return dshKinds[2].key
	}
	return dshRoute
}

// dshRouteFor is the route of magpie's the catalog model id goes on.
func dshRouteFor(id string, models []catalog.Model) string {
	for _, m := range models {
		if m.ID == id {
			return dshRouteOf(m)
		}
	}
	return dshRoute
}

// dshAPI is the wire protocol a route of magpie's speaks, given the one it
// has now and the one it is written with: the one it has when the gateway
// speaks it — a user who switched a route to OpenAI Responses in dsh's
// Models page keeps it, where each round put Chat Completions back
// (Discord, 01huadalang: 这些协议怎么改 responses,在 dsh 改了一会就会被 magpie
// 接管) — and the route's own otherwise, none or one the gateway has no
// endpoint for.
func dshAPI(cur, own string) string {
	if contains(dshAPIs, cur) {
		return cur
	}
	return own
}

// dshBaseURL is the gateway's address for a route on api. pi-ai hands the
// base to the vendor's SDK as it is, and Anthropic's adds /v1/messages
// itself, so Anthropic's Messages API is at the gateway's root; OpenAI's
// SDK adds only /chat/completions or /responses, so those are at its /v1.
func dshBaseURL(api, gw string) string {
	if api == "anthropic-messages" {
		return gw
	}
	return gw + "/v1"
}

// dshPiLevels maps each of dsh's thinking levels a model takes to the
// reasoning_effort sent for it; a level left out is not offered.
type dshPiLevels struct {
	Off     string `yaml:"off,omitempty"`
	Minimal string `yaml:"minimal,omitempty"`
	Low     string `yaml:"low,omitempty"`
	Medium  string `yaml:"medium,omitempty"`
	High    string `yaml:"high,omitempty"`
	XHigh   string `yaml:"xhigh,omitempty"`
	Max     string `yaml:"max,omitempty"`
}

// dshThinking are dsh's thinking levels (pi-ai's), in its order.
var dshThinking = []string{"off", "minimal", "low", "medium", "high", "xhigh", "max"}

// dshModelLevels are the levels of dsh's a catalog model takes, each with
// the effort sent for it: the model's own name for it (modelEffort), so a
// plugin's light and extra_high are dsh's low and xhigh and are sent as
// light and extra_high, and off for its none.
func dshModelLevels(efforts []string) ([]string, *dshPiLevels) {
	var levels []string
	var out dshPiLevels
	for _, l := range dshThinking {
		w := l
		if l == "off" {
			w = "none"
		}
		e := modelEffort(efforts, w)
		if e == "" {
			continue
		}
		levels = append(levels, l)
		switch l {
		case "off":
			out.Off = e
		case "minimal":
			out.Minimal = e
		case "low":
			out.Low = e
		case "medium":
			out.Medium = e
		case "high":
			out.High = e
		case "xhigh":
			out.XHigh = e
		case "max":
			out.Max = e
		}
	}
	// dsh turns away a model offering no level but off
	if len(levels) == 0 || len(levels) == 1 && levels[0] == "off" {
		return nil, nil
	}
	return levels, &out
}

// dshLevels are the thinking levels dsh offers for a catalog model.
func dshLevels(ref string) []string {
	for _, m := range magpieModels("dsh") {
		if m.ID == ref {
			levels, _ := dshModelLevels(m.Efforts)
			return levels
		}
	}
	return nil
}

// dshMaxTokens is the maxTokens magpie lists m with. dsh takes a listed
// maxTokens as every request's output and reserves it, with 65536 of
// headroom, out of contextWindow before it decides when to compact
// (compaction-basic's resolveCompactSpec: the threshold is the smaller of
// 80% of the window and window - maxTokens - 65536). A vendor's reply limit
// near its window leaves dsh compacting at a sliver of it, or failing to
// (#2823): 500000 with 393216 compacted at 41248; 524288 with 524288, and
// 131072 with 65536, left it no budget at all. So the vendor's figure is
// held to what leaves dsh half the window to compact in (window/2 - 65536),
// or to a quarter of the window, as VS Code's and Copilot's are, where that
// is more: a window under 262144 has no half to spare. A quarter alone cut
// DeepSeek's 393216 on its 1000000 window to 250000, where dsh compacts at
// 541248 with all of it (#3298); 500000 with 393216 is held to 184464 and
// compacts at 250000. A Max output the user set stays as they set it
// (outputOr).
func dshMaxTokens(m catalog.Model) int {
	if m.Context <= 0 {
		return maxTokens(m)
	}
	room := max(m.Context/4, m.Context/2-dshHeadroom)
	return outputOr(m, min(maxTokens(m), max(1, room)))
}

// dshHeadroom is compaction-basic's default headroomTokens: what dsh keeps
// free beside a request's maxTokens before it compacts.
const dshHeadroom = 65536

// dshRouteConfig is magpie's first route with every one of models on it.
func dshRouteConfig(models []catalog.Model, api, gw string) dshPiRoute {
	return dshKindConfig(dshKinds[0], models, api, gw)
}

// dshKindConfig is magpie's route k for models, of the catalog one round
// read: what the round decides from and what it writes come from the same
// list. api is the wire protocol the route has now, kept when the gateway
// speaks it (dshAPI). A model's reasoningEfforts go on every one of them:
// llm-pi-ai makes them pi-ai's thinkingLevelMap, sent as reasoning_effort
// on Chat Completions, reasoning.effort on Responses and, for a Claude
// thinking adaptively, output_config.effort on Messages.
func dshKindConfig(k dshKind, models []catalog.Model, api, gw string) dshPiRoute {
	api = dshAPI(api, k.api)
	r := dshPiRoute{DisplayName: k.name, APIKeyEnv: dshKeyRef, API: api, BaseURL: dshBaseURL(api, gw), Models: []dshPiModel{}}
	for _, m := range models {
		e := dshPiModel{ID: m.ID, Name: m.Name, ContextWindow: m.Context}
		if m.Output > 0 {
			e.MaxTokens = dshMaxTokens(m)
		}
		switch {
		case m.Images:
			e.Input = []string{"text", "image"}
		case m.ImageInput != nil:
			e.Input = []string{"text"}
		}
		_, e.ReasoningEfforts = dshModelLevels(m.Efforts)
		// pi-ai's budget path clamps max to high (16384), so a model that
		// takes adaptive thinking with its level (Z.ai's GLM-5.3) is asked
		// adaptively too: pi-ai then sends the level itself, max as max
		if api == "anthropic-messages" && (gateway.AdaptiveThinking(m.ID) || gateway.AdaptiveWithEffort(m.ID)) {
			e.Compat = &dshPiCompat{ForceAdaptiveThinking: true}
		}
		r.Models = append(r.Models, e)
	}
	return r
}

// dshStartOnItsRoute moves a start (agent-default-model) on a model of
// magpie's to the route that model is on now: dsh finds a model by its
// route and id, and fails a session started on a route that no longer has
// it. The model, effort and everything else in the entry stay, and so does
// a start on a model magpie no longer gives dsh (dshCheck says so).
func dshStartOnItsRoute(items []dshItem, models []catalog.Model) []dshItem {
	for i, it := range items {
		if it.id != "agent-default-model" {
			continue
		}
		c := dshConfig(it)
		if !isDshRoute(c["provider"]) || c["model"] == "" {
			continue
		}
		want := ""
		for _, m := range models {
			if m.ID == c["model"] {
				want = dshRouteOf(m)
			}
		}
		if want == "" || want == c["provider"] {
			continue
		}
		n, err := dshNode(it)
		if err != nil {
			continue
		}
		yamlSetKey(yamlMapping(n, "config"), "provider", &yaml.Node{Kind: yaml.ScalarNode, Value: want})
		if lines, err := dshNodeLines(n); err == nil {
			items[i].lines = lines
		}
	}
	return items
}

func yamlQuote(s string) string {
	b, _ := json.Marshal(s)
	return string(b)
}

// dshProviderLines is the llm-deepseek entry pointing a dsh before 0.1.5 at
// the gateway, with the catalog as the models its /model offers and the key
// in the entry. effort is the thinking effort sessions start with, high
// (dsh's own default) when "".
func dshProviderLines(effort string, models []catalog.Model, gw string) []string {
	if effort == "" {
		effort = "high"
	}
	lines := []string{
		"- id: llm-deepseek " + dshMark,
		"  config:",
		"    apiKey: " + yamlQuote(keyAt(gw)),
		"    baseURL: " + yamlQuote(gw+"/v1"),
		"    thinking: enabled",
		"    reasoningEffort: " + effort,
		"    models:",
	}
	ms := models
	if len(ms) == 0 {
		lines[len(lines)-1] = "    models: []"
	}
	for _, m := range ms {
		lines = append(lines, "      - id: "+yamlQuote(m.ID), "        name: "+yamlQuote(m.Name))
		// what dsh would otherwise take for every model: a million tokens
		// of context, 256K out, and text only
		if m.Context > 0 {
			lines = append(lines, fmt.Sprintf("        contextWindow: %d", m.Context))
		}
		if m.Output > 0 {
			lines = append(lines, fmt.Sprintf("        maxTokens: %d", dshMaxTokens(m)))
		}
		if m.Images {
			lines = append(lines, "        inputModalities: [text, image]")
		}
	}
	return lines
}

// dshDefaultLines is the agent-default-model entry: the model new sessions
// start on, in every entry point, on provider's route, and the thinking
// effort they start with when effort isn't "".
func dshDefaultLines(provider, model, effort string) []string {
	lines := []string{
		"- id: agent-default-model " + dshMark,
		"  config:",
		"    provider: " + provider,
		"    model: " + yamlQuote(model),
	}
	if effort != "" {
		lines = append(lines, "    reasoningEffort: "+yamlQuote(effort))
	}
	return lines
}

// dshLoopLines is the agent-loop entry dsh ships, with model in place.
func dshLoopLines(model string) []string {
	return []string{
		"- id: agent-loop " + dshMark,
		"  config:",
		"    agents:",
		"      - id: main",
		"        provider: deepseek-official",
		"        model: " + yamlQuote(model),
		"        cwd: !!js process.cwd()",
	}
}

// dshRouteLines is the api-gateway entry: the route headless and web
// sessions start on.
func dshRouteLines(model string) []string {
	return []string{
		"- id: api-gateway " + dshMark,
		"  config:",
		"    provider: deepseek-official",
		"    model: " + yamlQuote(model),
	}
}

// dshSync puts the catalog as it is now into magpie's route (its
// llm-deepseek entry before 0.1.5), in every patch list that has it; a
// profile still on dsh's DeepSeek row taken over moves to the route.
// Nothing else in the patch lists changes.
func dshSync(dir, gw string) error {
	dshWrites.Lock()
	defer dshWrites.Unlock()
	models := magpieModels("dsh")
	files := dshProfiles(dir)
	if len(files) == 0 {
		return dshSyncLegacy(filepath.Join(dir, "config.yaml"), models, gw)
	}
	defer func() {
		// the key under the name the route gives it, moved from the old one
		if _, items, err := dshRead(files[0]); err == nil && dshWired(items) {
			dshEnv(dir, gw, true, false)
		}
	}()
	for _, f := range files {
		_, items, err := dshRead(f)
		if err != nil {
			continue
		}
		if dshOldWiring(items) {
			if err := dshMove(f, items, models, gw); err != nil {
				return err
			}
			continue
		}
		if !dshWired(items) {
			continue
		}
		if _, err := dshRouteAgain(f, models, gw); err != nil {
			return err
		}
	}
	if err := dshFillNewProfiles(files, models, gw); err != nil {
		return err
	}
	return dshMirrorHome(dir, models, gw, false)
}

// dshStartsOnMagpie reports whether the model a profile's sessions start on
// is one of magpie's, read the way dsh starts sessions.
func dshStartsOnMagpie(dir string, items []dshItem) bool {
	return strings.HasPrefix(dshStart(dir, items), magpieID+"/")
}

// dshRouteAgain writes magpie's route again in one patch list where it is no
// longer what magpie would write, and says whether it wrote; magpie's web
// search entry in a profile goes to the gateway's address with it. It is the one
// thing that may be done again at any time: the route is magpie's list of
// its own models, while the model a session starts on is the user's pick
// (see dshCheck). A patch list without magpie's route is written back only
// while the start still names one of magpie's models — dsh's own save keeps
// a snapshot and can write the list back without the route, and stripping
// the route under a start magpie still owes is not the user taking magpie
// out; a start of dsh's own or of the user's says that they were. One
// written between the read and the write is left as it is: it is the newer
// of the two, and the next round reads it. models is the catalog the round
// read: with none there is no route to write, and writing an empty one
// would take a working list away.
func dshRouteAgain(f string, models []catalog.Model, gw string) (bool, error) {
	if len(models) == 0 {
		return false, nil
	}
	raw, err := edit.Read(f)
	if err != nil {
		return false, nil
	}
	head, items, err := dshParse(f, string(raw))
	if err != nil || !dshWired(items) {
		// no route of magpie's in the list: write it back only where the
		// start still names one of magpie's models — the route was stripped
		// under it, not taken out. dshPutRoute reads the entry dsh wrote in
		// its own style, so the route is added beside the user's own. A list
		// still on the old wiring is dshSync's to move (dshMove), not this
		// round's to write beside.
		if err != nil || dshOldWiring(items) || !dshStartsOnMagpie(dirOf(f), items) {
			return false, nil
		}
		return dshWriteParsed(f, head, items, models, gw, raw)
	}
	before := dshJoin(items)
	if items, err = dshPutRoute(items, true, models, gw); err != nil {
		return false, nil
	}
	if dshProfileList(f) {
		items = dshSearchAgain(items, dshProfileHome(f), gw)
	}
	if dshJoin(items) == before {
		return false, nil
	}
	if now, err := edit.Read(f); err != nil || !bytes.Equal(now, raw) {
		return false, nil
	}
	return true, dshWrite(f, head, items)
}

// dshProfileList reports whether f is a profile's own patch list rather than
// the home layer, which applies over every profile's.
func dshProfileList(f string) bool {
	return filepath.Base(filepath.Dir(filepath.Dir(f))) == "profiles"
}

// dirOf is the dsh home a patch list belongs to.
func dirOf(f string) string {
	if dshProfileList(f) {
		return filepath.Dir(filepath.Dir(filepath.Dir(f)))
	}
	return filepath.Dir(f)
}

// dshWriteParsed adds the route to the list as it was read, and writes it
// back when the file still holds what was read. The home layer is only
// written into where it already holds an llm-pi-ai entry of its own: its
// config replaces every profile's whole entry (dshOver), so one magpie added
// there would take the user's own providers out of dsh's list (#804). A
// profile's own list may be given the entry, as magpie's apply path does.
func dshWriteParsed(f string, head []string, items []dshItem, models []catalog.Model, gw string, raw []byte) (bool, error) {
	if !dshProfileList(f) && dshFindLast(items, dshPiRow) < 0 {
		return false, nil
	}
	before := dshJoin(items)
	if items, err := dshPutRoute(items, true, models, gw); err != nil {
		return false, nil
	} else if dshJoin(items) == before {
		return false, nil
	} else if now, err := edit.Read(f); err != nil || !bytes.Equal(now, raw) {
		return false, nil
	} else {
		return true, dshWrite(f, head, items)
	}
}

// dshWiredEvery is how often a magpie serving the gateway looks at dsh's
// patch lists.
const dshWiredEvery = 30 * time.Second

// KeepDshWired keeps magpie's route in dsh's patch lists as magpie's catalog
// is now, for as long as magpie serves the gateway. dsh reads a patch list
// live, so one left behind by something else writing the file — dsh's own
// Models page, an older magpie — fails every session there with no such
// configured model until the route is written again. What is written is
// magpie's own list, never the model a session starts on.
func KeepDshWired(ctx context.Context) {
	keepDshWired(ctx, dshWiredEvery)
}

// keepDshWired is KeepDshWired at an interval the tests can shorten. One
// round at a time, each after the one before it has finished, and a round
// 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 := rounds.once(); said.first(trouble) {
			log.Print(trouble)
		}
		select {
		case <-ctx.Done():
			return
		case <-beat.Next(every):
		}
	}
}

// dshSaidOnce is what a round could not write, as it was last said: a round
// repeating it says nothing, so a profile magpie cannot write to is reported
// once rather than every 30s.
type dshSaidOnce struct{ last string }

// first reports whether this trouble has not been said yet, and is to be said.
func (s *dshSaidOnce) first(trouble string) bool {
	if trouble == s.last {
		return false
	}
	s.last = trouble
	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()
	if dir == "" {
		return ""
	}
	files := dshProfiles(dir)
	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
	// 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
	// own models alone until magpie's next start (star on Discord). One with
	// entries of its own and no route is the user's, left to Reapply.
	fill := []string{}
	fresh := false
	for _, f := range files {
		_, items, err := dshRead(f)
		switch {
		case err != nil:
		case len(items) == 0:
			fill, fresh = append(fill, f), true
		case dshWired(items):
			fill = append(fill, f)
		}
	}
	if fresh {
		if err := dshFillNewProfiles(fill, models, gateway.URL()); err != nil {
			trouble = append(trouble, "giving dsh's new profile magpie's route: "+dshWriteError(err))
		}
	}
	files = append(files, dshHomePatch(dir)) // left as it is without magpie's route
	for _, f := range files {
		written, err := dshRouteAgain(f, models, gateway.URL())
		if err != nil {
			trouble = append(trouble, fmt.Sprintf("writing dsh's route again in %s: %s", f, dshWriteError(err)))
			continue
		}
		if written {
			log.Printf("wrote dsh's route again in %s", f)
		}
	}
	return strings.Join(trouble, "; ")
}

// dshWriteError is why a write failed, without the name of the temporary file
// the atomic write makes: that name is new every attempt, and a trouble that
// reads differently every round would be said every round (see dshSaidOnce).
func dshWriteError(err error) string {
	var pe *os.PathError
	if errors.As(err, &pe) {
		return pe.Op + ": " + pe.Err.Error()
	}
	return err.Error()
}

// dshHome is where dsh keeps its profiles: $DSH_HOME, or ~/.dsh.
func dshHome() string {
	if dir := appdir.Getenv("DSH_HOME"); dir != "" {
		return dir
	}
	home, err := os.UserHomeDir()
	if err != nil {
		return ""
	}
	return filepath.Join(home, ".dsh")
}

// dshMove moves a profile magpie wired by taking over dsh's DeepSeek row
// onto magpie's route, the model and effort kept.
func dshMove(f string, items []dshItem, models []catalog.Model, gw string) error {
	model := ""
	if i := dshFindLast(items, "agent-default-model"); i >= 0 {
		if c := dshConfig(items[i]); c["provider"] == "deepseek-official" {
			model = c["model"]
		}
	}
	if model == "" || !isMagpie(model) {
		// nothing of magpie's to start on: dsh's own row back alone
		head, items, err := dshRead(f)
		if err != nil {
			return err
		}
		if old := unstash(dshStashKey(f, "llm-deepseek")); old != "" {
			items[dshFind(items, "llm-deepseek")] = dshItem{id: "llm-deepseek", lines: strings.Split(old, "\n")}
		} else {
			i := dshFind(items, "llm-deepseek")
			items = append(items[:i], items[i+1:]...)
		}
		return dshWrite(f, head, items)
	}
	return dshSetFile(f, magpieID+"/"+model, true, models, gw)
}

// dshSyncLegacy is dshSync on a config.yaml before 0.1.5.
func dshSyncLegacy(f string, models []catalog.Model, gw string) error {
	head, items, err := dshRead(f)
	if err != nil {
		return nil
	}
	i := dshFind(items, "llm-deepseek")
	if i < 0 || !items[i].magpie {
		return nil
	}
	if len(models) == 0 {
		return nil
	}
	lines := dshProviderLines(dshEffortIn(items), models, gw)
	if strings.Join(lines, "\n") == strings.Join(items[i].lines, "\n") {
		return nil
	}
	items[i].lines = lines
	return dshWrite(f, head, items)
}

// dshFillNewProfiles gives a profile dsh made after magpie set it up — the
// desktop app's, opened for the first time after the web's was wired —
// magpie's route, and the model magpie set in the others when it starts on
// none of the user's: until then it lists dsh's own models alone.
func dshFillNewProfiles(files []string, models []catalog.Model, gw string) error {
	if len(models) == 0 {
		return nil
	}
	model := ""
	var bare []string
	for _, f := range files {
		_, items, err := dshRead(f)
		if err != nil {
			continue
		}
		if !dshWired(items) {
			bare = append(bare, f)
			continue
		}
		if i := dshFindLast(items, "agent-default-model"); i >= 0 && model == "" {
			if c := dshConfig(items[i]); isDshRoute(c["provider"]) {
				model = c["model"]
			}
		}
	}
	if model == "" {
		return nil
	}
	for _, f := range bare {
		head, items, err := dshRead(f)
		if err != nil {
			continue
		}
		if i := dshFind(items, "agent-default-model"); i < 0 || dshOurs(items[i]) {
			if err := dshSetFile(f, magpieID+"/"+model, true, models, gw); err != nil {
				return err
			}
			continue
		}
		// a model of the user's: magpie's are listed beside it
		if items, err = dshPutRoute(items, true, models, gw); err != nil {
			continue
		}
		if err := dshWrite(f, head, items); err != nil {
			return err
		}
	}
	return nil
}

// dshEfforts are the thinking efforts dsh's own DeepSeek row takes: its
// reasoningEffort is off, low, high or max (low since 0.1.1), sent as
// reasoning_effort before 0.1.7 and output_config.effort from it on.
var dshEfforts = []string{"off", "low", "high", "max"}

// dshEffortIn is the reasoningEffort of the llm-deepseek entry magpie
// wrote, "" when there is none.
func dshEffortIn(items []dshItem) string {
	i := dshFind(items, "llm-deepseek")
	if i < 0 || !items[i].magpie {
		return ""
	}
	for _, l := range items[i].lines {
		if k, v, ok := strings.Cut(strings.TrimSpace(l), ":"); ok && k == "reasoningEffort" {
			return yamlScalar(strings.TrimSpace(v))
		}
	}
	return ""
}

// dshEffortOf is the effort sessions start with in a profile (0.1.5 on):
// agent-default-model's, else, not yet moved, magpie's llm-deepseek's.
func dshEffortOf(items []dshItem) string {
	if i := dshFindLast(items, "agent-default-model"); i >= 0 {
		if e := dshConfig(items[i])["reasoningEffort"]; e != "" {
			return e
		}
	}
	return dshEffortIn(items)
}

// dshFiles are the patch lists magpie writes: every profile's, else
// config.yaml.
func dshFiles(dir string) []string {
	if files := dshProfiles(dir); len(files) > 0 {
		return files
	}
	return []string{filepath.Join(dir, "config.yaml")}
}

// DshPatchFiles are the patch lists of the dsh whose home is dir, as magpie
// writes them: every profile's (web's first), else config.yaml.
func DshPatchFiles(dir string) []string { return dshFiles(dir) }

// dshGetEffort reads the effort sessions start with.
func dshGetEffort(dir string) string {
	files := dshProfiles(dir)
	if len(files) == 0 {
		_, items, err := dshRead(filepath.Join(dir, "config.yaml"))
		if err != nil {
			return ""
		}
		return dshEffortIn(items)
	}
	_, items, err := dshRead(files[0])
	if err != nil {
		return ""
	}
	return dshEffortOf(dshOver(dir, items))
}

// dshSetEffort writes v as the effort sessions start with: into
// agent-default-model (0.1.5 on), or into magpie's llm-deepseek entry
// before, dsh's own row being used whole when there is none.
func dshSetEffort(dir, v, gw string) error {
	dshWrites.Lock()
	defer dshWrites.Unlock()
	files := dshProfiles(dir)
	if len(files) > 0 {
		if dshHomeHas(dir, "agent-default-model") {
			files = append(files, dshHomePatch(dir))
		}
		model := dshGet(dir)
		ref, viaGateway := strings.CutPrefix(model, magpieID+"/")
		levels := dshEfforts
		if viaGateway {
			levels = dshLevels(ref)
		}
		route := dshRoute
		if viaGateway {
			route = dshRouteFor(ref, magpieModels("dsh"))
		}
		if v != "" && len(levels) == 0 {
			return fmt.Errorf("DeepSeek Harness has no thinking levels for %s: magpie knows of none the model takes", ref)
		}
		if v != "" && !contains(levels, v) {
			return fmt.Errorf("DeepSeek Harness takes an effort of %s for this model, not %q", strings.Join(levels, ", "), v)
		}
		if model == "" {
			if v == "" {
				return nil
			}
			return fmt.Errorf("pick a model for DeepSeek Harness first; the effort is kept with it")
		}
		for _, f := range files {
			head, items, err := dshRead(f)
			if err != nil {
				continue
			}
			// each profile keeps the model it starts on
			p, m := "deepseek-official", ref
			if viaGateway {
				p = route
			}
			if i := dshConfigIndex(items, "agent-default-model"); i >= 0 {
				if c := dshConfig(items[i]); c["model"] != "" && c["provider"] != "" {
					p, m = c["provider"], c["model"]
				}
			}
			i := dshConfigIndex(items, "agent-default-model")
			if i < 0 {
				i = dshFindLast(items, "agent-default-model")
			}
			if i >= 0 && !dshOurs(items[i]) {
				stash(map[string]string{dshStashKey(f, "agent-default-model"): strings.Join(items[i].lines, "\n")})
			}
			it := dshItem{id: "agent-default-model", magpie: true, lines: dshDefaultLines(p, m, v)}
			if i >= 0 {
				items[i] = it
			} else {
				items = append(items, it)
			}
			if err := dshWrite(f, head, items); err != nil {
				return err
			}
		}
		return nil
	}

	if v != "" && !contains(dshEfforts, v) {
		return fmt.Errorf("DeepSeek Harness takes an effort of %s, not %q", strings.Join(dshEfforts, ", "), v)
	}
	f := filepath.Join(dir, "config.yaml")
	head, items, err := dshRead(f)
	if err == nil {
		if i := dshFind(items, "llm-deepseek"); i >= 0 && items[i].magpie {
			models := magpieModels("dsh")
			if len(models) == 0 {
				return fmt.Errorf("DeepSeek Harness has no models to write: magpie has none to hand it")
			}
			items[i].lines = dshProviderLines(v, models, gw)
			return dshWrite(f, head, items)
		}
	}
	if v != "" {
		return fmt.Errorf("pick a model through magpie for DeepSeek Harness first; the effort is kept with magpie's DeepSeek entry")
	}
	return nil
}

// dshSettingsEndpoint reports whether dsh's own settings carry an
// llm-deepseek section with an endpoint or key, which dsh puts over the
// patch list.
func dshSettingsEndpoint(path string) bool {
	b, err := os.ReadFile(path)
	if err != nil {
		return false
	}
	in := false
	for _, l := range splitLinesKeep(string(b)) {
		if l != "" && !strings.HasPrefix(l, " ") && !strings.HasPrefix(l, "#") {
			in = strings.HasPrefix(l, "llm-deepseek:")
			continue
		}
		t := strings.TrimSpace(l)
		if in && (strings.HasPrefix(t, "baseURL:") || strings.HasPrefix(t, "apiKey:")) {
			return true
		}
	}
	return false
}

// what dsh says after a change (notice.go)
var (
	noticeDsh1 = newNotice("New dsh sessions start on this. A session made before keeps its model, open now or reopened later, until you pick another in it with /model or the model button by its message box. A dsh started with -p or in a terminal reads it at start-up.")
	noticeDsh2 = newNotice("dsh reads its config at start-up — restart open dsh sessions to use this.")
	noticeDsh3 = newNotice("dsh's web search goes through magpie, which has nothing to search with yet: set up a provider that searches by itself (DeepSeek, Claude, Codex, …) or a search API under Settings › Web search.")
	noticeDsh4 = newNotice("~/.dsh/settings.yaml sets its own DeepSeek endpoint or key, which dsh puts over magpie's; clear it in dsh's Models page to go through magpie.")
	noticeDsh5 = newNotice("DeepSeek Harness Desktop hasn't been opened yet: it starts on this the first time it opens.")
)

// dshDocStart says whether l is YAML's document start marker, "---" at the
// left edge with at most a comment after it.
func dshDocStart(l string) bool {
	r, ok := strings.CutPrefix(l, "---")
	if !ok {
		return false
	}
	if r == "" {
		return true
	}
	if r[0] != ' ' && r[0] != '\t' {
		return false
	}
	r = strings.TrimSpace(r)
	return r == "" || strings.HasPrefix(r, "#")
}