workbuddy: with the provider left out of the names, a model's id is its name (elis_pina on X)

WorkBuddy's model list read "GLM-5.3:workbuddy/glm-5.3" with Provider in
model names Off. WorkBuddy (5.5.6 renderer, getModelDisplayName) shows
every custom model as "name:id" unless the name is empty or equal to
the id, and magpie wrote the catalog id (provider/model) as the id. So
the provider came back after the colon whatever the names said.

- agent (buddyIDs): for WorkBuddy and WorkBuddy AI under Off or Own,
  each magpie entry in models.json gets the name as its id too, so the
  list shows "GLM-5.3" alone. The catalog id stays when two models
  share a name, when the name is another model's id, when the entries
  point at a magpie on another machine or in WSL, and in On mode.
  A model turned off in WorkBuddy, its default effort and a reply limit
  typed in carry across the change of id: an old id is mapped back
  through every label form (Label, PlainName, the list's name).
- provider.AgentNamed: the catalog id of the one model an agent's list
  names so.
- gateway (namedFor): a request with WorkBuddy's or WorkBuddy AI's key
  for such a name goes to that model before any other resolution, so a
  bare id that another provider serves first is not asked instead. The
  reply keeps the name that was asked for. Other agents' keys are not
  mapped.

Siblings: CodeBuddy Code shares the writer and keeps catalog ids. Its
settings.json names the model by the catalog id (codebuddy.go), and its
CLI picker shows the name alone (no name:id template in its bundle).

What users meet: a change of mode, or of a model's name, changes the
id. WorkBuddy then picks another model for a session that had the old
one, as it does for any model that leaves its list.

Run:
- Unit tests: TestWorkBuddyNamesAreIDsWithoutProvider covers Off, Own,
  back to On, WorkBuddy AI and CodeBuddy. TestWorkBuddyAsksByName uses
  the real handler: a name equal to a bare id that a provider listed
  first serves (hidden from WorkBuddy) reaches the named model, and
  OpenCode's key for the same name does not.
- Broken by hand (on mica), each red:
  - buddyIDs always returning the catalog id: the test sees
    id deepseek/pro under Off.
  - namedFor's mapping skipped: the request went to provider "first".
  - The old-id mapping skipped: Own lost disabled.
- Sandbox HOME, built binary:
  - magpie provider add zai (fake upstream) and magpie workbuddy
    provider magpie wrote "zai/glm-5.3 | GLM-5.3 · Z.ai".
  - magpie model suffix workbuddy off rewrote the file to
    "GLM-5.3 | GLM-5.3".
  - magpie serve on a spare port, then a curl with magpie-workbuddy for
    "GLM-5.2" reached upstream as glm-5.2 (reply model GLM-5.2).
  - WorkBuddy 5.5.6's own CLI (app.asar.unpacked/cli/bin/codebuddy -p
    --model GLM-5.3), with HOME set to the sandbox, answered "pong", and
    upstream saw glm-5.3, streamed.
- Full suite on mote at this tree (go test -count=1 -timeout 45m ./...):
  every package ok (agent 369s, gateway 1062s, provider 230s,
  sessions 254s), log kept whole. The doc line in agent-wiring.md was
  added after the run; no test reads that file. gofmt -l is empty,
  and go vet ./... passes. On mica, GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./..., and the linux nogui and windows
  builds pass.
- That suite ran at base ac0b5c287. The change was then rebased onto
  5211fd3ba (usage currency; no file in common). At the pushed head,
  on mica: go build, go vet of agent, gateway and provider, and
  -run "WorkBuddy|CodeBuddy|AgentSuffix|Labels" in those three
  packages all pass.

Not tried: WorkBuddy's window itself (the name:id rule is read from
its renderer source, not seen on screen), and WorkBuddy AI's app.
This commit is contained in:
yetone
2026-11-13 22:49:39 +08:00
parent 5211fd3ba2
commit a97c8191bc
6 changed files with 356 additions and 12 deletions
+1
View File
@@ -97,6 +97,7 @@ something else shows up as drift.
- 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` or `AdaptiveWithEffort`, so Max reaches GLM-5.3 as max) 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. For a custom provider with more than one URL that is the API its Base URL was given as (`BaseAPI`), after the vendor rules (an OpenAI model on OpenAI's API, a Claude where Messages is served): a relay set to Responses whose Chat URL Detect found beside it had its GPTs on dsh's Chat route (nb5p on Discord, `TestDshCustomResponsesProvider`). dsh's bundled pi-ai (`@earendil-works/pi-ai`, dsh 0.2.1-rc.2) takes `openai-responses` as a route's `api`. A routing group has `responses` when a member is best on Responses and every other member takes a Responses request as it is too, or translates every request anyway (`provider.GroupAPI`, #1594; zyh6036 on X: a group of subscriptions that all serve Responses, not all best there, was asked on Chat), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, so a member only Chat reaches keeps being relayed, and a Messages-only group stays there 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. A model of a route whose api stands as `openai-responses` carries `compat.supportsStrictMode` (#3055): OpenAI's Responses API takes a function tool whose `strict` is left out as a strict-mode one, every property required, so a tool's optional parameters come back filled; pi-ai says `strict: false` on an ordinary tool only when the compat says so, by the api the route has, not by its name. 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. A start on a model by an id magpie lists it by no longer, a found group's `group/auto-<slug>` (now `auto/<model>`, `provider.PublicRef`) or a renamed provider's (`provider.RenamedRef`), moves onto the id its route lists, in every profile and the home layer: dsh finds the start by that id, and the desktop app showed no model picked while its patch list held every route (zyh6036 on X, `TestDshStartOnAFoundGroupsOldIdMovesOntoItsId`). `renameFoundGroups` moves only a value applied.json records, and the start dsh read was not one (none on the owner's install either), nor is a pick made in dsh. 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.
- The names every agent's model list gets are `provider.Labels`' ([`modelprefs.go`](../../internal/provider/modelprefs.go)). With Provider in model names off (or own, for names the user gave), a name stands alone unless another model in the same list reads the same, when both keep their provider's after it. A routing group named as anything else in the list keeps "· routing group", and the model it shares the name with stays plain: the group found for a model served by two providers, one of them hidden from the agent, had the shown model read "GPT-6.1 Terra · MyGateway" beside its provider's plain "GPT-6.1 Sol" (nb5p on Discord; `TestPlainNames`, `TestSuffixMode`, `TestPlainOwnNamesGroups`).
- An agent can have its own Provider in model names, set in its Details on the Agents page or with `magpie model suffix <agent> on|own|off|every` (KillTry27355 on X). `settings.AgentSuffix` keeps it by the id the agent's lists are kept by (`Agent.ListsFor`, lower-cased, without `@wsl:` or `#profile`); with none the agent follows Settings'. Every list magpie writes or serves an agent goes through `provider.LabelsFor(agent, …)`, which reads that agent's mode (`suffixModeOf`); the gateway's `/v1/models` takes the agent from the request (`agentOf`). Setting it rewrites the agents' configs as Settings' does (`catalog.Touched`). (`TestAgentSuffix`, `TestAgentSuffixReachesItsFileAlone`, `TestModelsListFollowsAgentSuffix`, agent-suffix.test.cjs.)
- WorkBuddy and WorkBuddy AI show a custom model as `name:id` whenever the two differ (the renderer's `getModelDisplayName`, 5.5.6), so a catalog id put the provider back after every plain name ("GLM-5.3:workbuddy/glm-5.3", elis_pina on X). With their Provider in model names Off or Own, `buddyIDs` writes each model's name as its `id` too, unless two models share the name or it is another model's id, or the entries point at a magpie on another machine or in WSL (`place`), whose names this one cannot answer for. The gateway takes a name back to its model by the agent's key before any other resolution (`namedFor`, `provider.AgentNamed`), so a bare id another provider serves first is not asked instead. A disabled model and its default effort carry over when the id changes (`modelOf` maps every label form back). A change of mode or of a name changes the id, and WorkBuddy then picks another model for a session that had it. CodeBuddy Code keeps catalog ids: its settings.json names the model by them and its picker shows the name alone. (`TestWorkBuddyNamesAreIDsWithoutProvider`, `TestWorkBuddyAsksByName`.)
- 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 what leaves dsh half the window to compact in (window/2 − 65536), or to a quarter of the window where that is more (every window under 262144, as VS Code and Copilot in JetBrains hold it), on every route and in the older `llm-deepseek` entry (`dshMaxTokens`). A quarter alone cut DeepSeek's 393216 on its 1000000 window to 250000 (#3298); now it keeps all of it and dsh compacts at 541248, while 500000/393216 is held to 184464 and compacts at 250000. A Max output the user set stays as they set it (`outputOr`), even one that leaves dsh no budget. `TestDshOutputLeavesCompactionRoom`.
- dsh compacts on the session's latest model (compaction-basic with no `summarizationModel`), so a switch away from a model whose provider is out of its limit failed on the compaction (Musikrv77852 on X, #5395). dsh's opened row has a compaction model square (`compact_model`, `dshCompactField` in [`dsh.go`](../../internal/agent/dsh.go)), offered once dsh is on magpie's route: magpie's own `Live` setting (`settings.DshCompactModel`, `provider.SetDshCompactModel`), which the gateway reads on each request (`dshCompactTo`), so nothing is written into dsh's profiles. DS Bot's requests can't be told from dsh's, so it has no square of its own and its compactions follow the same setting (`TestDshCompactionModelField`, `dsh-compact-model.test.cjs`). With no compaction model set, a compaction on a model whose provider is out of its limit goes to the same model from another provider when one serves it (`dshCompactElsewhere` in the gateway, `dsh-compact-rested`; qtwaiter on X: a WorkBuddy rate limit refused a switch to Trae CN's model).
- Codex's compaction can be put on a model of its own (0neB1aze on X; its memories already could). Codex's opened row has a compaction model square (`compact_model` in [`codex.go`](../../internal/agent/codex.go)): magpie's `Live` setting (`settings.CodexCompactModel`, `provider.SetCodexCompactModel`), read by the gateway on each compaction (`codexCompactTo` in [`codex_compact_model.go`](../../internal/gateway/codex_compact_model.go), called from the Codex backend's `/responses` branch before `codexCompact`), so nothing is written into Codex's config. Only a compaction magpie makes is moved: it asks a model for a plain-text summary any model reads back. One a ChatGPT account seals (`nativeCompactionFor`) stays where it is, and so does one that would be put on such a model, since only the account that wrote the summary reads it (#1099); a model that is disabled, not served by its exact id or not the key's is left too, with a log line (`compactRefused`). Other agents' compactions are moved by a routing group's Compact rule (`provider.Rule.Compact`) (`TestCodexCompactOnItsOwnModel`, `TestCodexCompactToLeavesNative`).
+85 -11
View File
@@ -41,8 +41,10 @@ import (
"strings"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
func workbuddy(home string) *Agent {
@@ -249,6 +251,42 @@ func buddyWriteAt(path, agent string, on bool, where place) error {
keys[e.APIKey] = true
}
}
var models []catalog.Model
if on {
models = sharedModels(agent)
}
// the model each entry is, by the id it has now: magpie's catalog id,
// or the name it was given as its id (buddyIDs) under this Provider in
// model names or another, so what was set on it in WorkBuddy stays
// when the setting changes
modelOf := func(id string) string { return id }
if len(models) > 0 {
isID, byName := map[string]bool{}, map[string]string{}
named := func(name, id string) {
if name == "" {
return
}
if was, ok := byName[name]; ok && was != id {
id = "" // two models' name: neither's
}
byName[name] = id
}
shown, _ := provider.CatalogFor(agent)
for _, e := range shown {
named(e.Label(), e.ID)
named(e.PlainName(), e.ID)
}
for _, m := range models {
isID[m.ID] = true
named(m.Name, m.ID)
}
modelOf = func(id string) string {
if c := byName[id]; c != "" && !isID[id] {
return c
}
return id
}
}
var kept []json.RawMessage
var ours []string
off := map[string]bool{}
@@ -272,12 +310,13 @@ func buddyWriteAt(path, agent string, on bool, where place) error {
remote, remoteKey = e.URL, e.APIKey
}
ours = append(ours, e.ID)
haveOut[e.ID] = e.MaxOutputTokens
m := modelOf(e.ID)
haveOut[m] = e.MaxOutputTokens
if e.Disabled != nil && *e.Disabled {
off[e.ID] = true
off[m] = true
}
if r := e.Reasoning; r != nil {
effort[e.ID] = cmp.Or(r.DefaultEffort, r.Effort)
effort[m] = cmp.Or(r.DefaultEffort, r.Effort)
}
continue
}
@@ -289,7 +328,7 @@ func buddyWriteAt(path, agent string, on bool, where place) error {
var add []json.RawMessage
var ids []string
if on {
models := sharedModels(agent)
idOf := buddyIDs(agent, models, away || remote != "")
// a reply limit typed into the file stays; magpie's is put where
// the user set none (outputsKept)
wantOut := map[string]int{}
@@ -300,7 +339,7 @@ func buddyWriteAt(path, agent string, on bool, where place) error {
}
keptOut := outputsKept(path, wantOut, haveOut)
for _, m := range models {
e := buddyModel(agent, m.ID, m.Name, m.Context, keptOut[m.ID], m.Images, m.Efforts)
e := buddyModel(agent, idOf(m), m.Name, m.Context, keptOut[m.ID], m.Images, m.Efforts)
if off[m.ID] {
e["disabled"] = true
}
@@ -329,18 +368,18 @@ func buddyWriteAt(path, agent string, on bool, where place) error {
return err
}
add = append(add, b)
ids = append(ids, m.ID)
ids = append(ids, idOf(m))
}
}
if at < 0 {
at = len(kept)
}
models := slices.Concat(kept[:at], add, kept[at:])
if models == nil {
models = []json.RawMessage{}
list := slices.Concat(kept[:at], add, kept[at:])
if list == nil {
list = []json.RawMessage{}
}
var out any = models
var out any = list
if d.rest != nil {
// a list of the models to show keeps showing magpie's
if raw, ok := d.rest["availableModels"]; ok {
@@ -352,7 +391,7 @@ func buddyWriteAt(path, agent string, on bool, where place) error {
d.rest["availableModels"] = b
}
}
b, err := json.Marshal(models)
b, err := json.Marshal(list)
if err != nil {
return err
}
@@ -366,6 +405,41 @@ func buddyWriteAt(path, agent string, on bool, where place) error {
return edit.WriteAtomic(path, append(b, '\n'))
}
// buddyIDs is the id each of models is written under in the agent's
// models.json. WorkBuddy's picker shows a model it was given as
// "name:id" whenever the two differ (its renderer's getModelDisplayName,
// 5.5.6), so magpie's catalog id put the provider back after every name
// the user had asked to see without it ("GLM-5.3:workbuddy/glm-5.3",
// elis_pina on X). With Provider in model names Off or Own (LabelsFor),
// WorkBuddy and WorkBuddy AI are given the name as the id too, and show
// it alone; the gateway takes a name back to its model by the agent's key
// (provider.AgentNamed). Else, and for a magpie on another machine (whose
// own names this one cannot answer for), the catalog id, as CodeBuddy
// Code's always is: its settings.json names the model by it, and its
// picker shows the name alone.
func buddyIDs(agent string, models []catalog.Model, away bool) func(catalog.Model) string {
catalogID := func(m catalog.Model) string { return m.ID }
if agent != "workbuddy" && agent != "workbuddy-ai" || away {
return catalogID
}
if mode := provider.SuffixModeFor(agent); mode != provider.SuffixOff && mode != provider.SuffixOwn {
return catalogID
}
// a name two models share, or one that is another model's id, stays
// the catalog id: the gateway could not tell which was asked for
n, isID := map[string]int{}, map[string]bool{}
for _, m := range models {
n[m.Name]++
isID[m.ID] = true
}
return func(m catalog.Model) string {
if m.Name == "" || n[m.Name] != 1 || isID[m.Name] && m.Name != m.ID {
return m.ID
}
return m.Name
}
}
// buddySmallWindow is the smaller context WorkBuddy offers beside a
// model's whole window, the size its own models offer.
const buddySmallWindow = 200000
+127
View File
@@ -4,6 +4,8 @@ import (
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
@@ -266,3 +268,128 @@ func TestWorkBuddyAIWritesItsOwnFolder(t *testing.T) {
t.Fatal("WorkBuddy AI followed WORKBUDDY_CONFIG_DIR")
}
}
// WorkBuddy shows a custom model as "name:id" whenever the two differ, so
// with the provider left out of the names, the name is the id too, and
// what was set on a model in WorkBuddy stays across the change of its id
// (elis_pina on X: "GLM-5.3:workbuddy/glm-5.3"). CodeBuddy Code, whose
// settings.json names a model by its catalog id, keeps it.
func TestWorkBuddyNamesAreIDsWithoutProvider(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("WORKBUDDY_CONFIG_DIR", "")
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil {
t.Fatal(err)
}
path := filepath.Join(home, ".workbuddy", "models.json")
os.MkdirAll(filepath.Dir(path), 0o755)
os.WriteFile(path, []byte(`{"models":[],"availableModels":["x"]}`), 0o600)
type doc struct {
Models []map[string]any `json:"models"`
Available []string `json:"availableModels"`
}
read := func() doc {
var d doc
b, _ := os.ReadFile(path)
if err := json.Unmarshal(b, &d); err != nil {
t.Fatalf("%v\n%s", err, b)
}
return d
}
write := func(d doc) {
b, _ := json.Marshal(d)
os.WriteFile(path, b, 0o600)
}
byName := func(d doc, name string) map[string]any {
for _, m := range d.Models {
if m["name"] == name {
return m
}
}
t.Fatalf("no %q in %v", name, d.Models)
return nil
}
notOnMac(t)
a := workbuddy(home)
if err := a.Field("provider").Set("magpie"); err != nil {
t.Fatal(err)
}
labels := listLabels("workbuddy")
pro := labels["deepseek/pro"]
d := read()
if m := byName(d, pro); m["id"] != "deepseek/pro" {
t.Fatalf("with the provider in the names: %v", m)
}
byName(d, pro)["disabled"] = true
write(d)
for _, mode := range []string{provider.SuffixOff, provider.SuffixOwn} {
if err := provider.SetAgentSuffix("workbuddy", mode); err != nil {
t.Fatal(err)
}
plain := listLabels("workbuddy")["deepseek/pro"]
// Own leaves the provider after a name the user did not give
if plain == "" || mode == provider.SuffixOff && plain == pro {
t.Fatalf("%s: name %q", mode, plain)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
d = read()
m := byName(d, plain)
if m["id"] != plain || m["disabled"] != true {
t.Fatalf("%s: %v", mode, m)
}
if !slices.Contains(d.Available, plain) || slices.Contains(d.Available, "deepseek/pro") {
t.Fatalf("%s: available %v", mode, d.Available)
}
// the gateway takes the name back to the model
if id, ok := provider.AgentNamed("workbuddy", plain); !ok || id != "deepseek/pro" {
t.Fatalf("%s: AgentNamed(%q) = %q, %v", mode, plain, id, ok)
}
if len(d.Models) != 2 {
t.Fatalf("%s: %v", mode, d.Models)
}
}
// WorkBuddy AI, the same app, the same
if err := provider.SetAgentSuffix("workbuddy-ai", provider.SuffixOff); err != nil {
t.Fatal(err)
}
ai := filepath.Join(home, "workbuddy-ai-models.json")
if err := buddyWrite(ai, "workbuddy-ai", true); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(ai); strings.Contains(string(b), `"id": "deepseek/pro"`) {
t.Fatalf("workbuddy-ai: %s", b)
}
// CodeBuddy Code's ids stay the catalog's under its own Off
if err := provider.SetAgentSuffix("codebuddy", provider.SuffixOff); err != nil {
t.Fatal(err)
}
cb := filepath.Join(home, "codebuddy-models.json")
if err := buddyWrite(cb, "codebuddy", true); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(cb)
if !strings.Contains(string(b), `"id": "deepseek/pro"`) {
t.Fatalf("codebuddy: %s", b)
}
// back on, the catalog ids, and still off in WorkBuddy
if err := provider.SetAgentSuffix("workbuddy", provider.SuffixOn); err != nil {
t.Fatal(err)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
d = read()
if m := byName(d, pro); m["id"] != "deepseek/pro" || m["disabled"] != true || len(d.Models) != 2 {
t.Fatalf("on again: %v", d.Models)
}
if _, ok := provider.AgentNamed("workbuddy", "nothing"); ok {
t.Fatal("a name no model has")
}
}
+25 -1
View File
@@ -1949,6 +1949,20 @@ func askedAt(id string) (string, string) {
return m, e
}
// namedFor is the catalog id of the model an agent that is given its
// models' names as their ids asked for by name: WorkBuddy and WorkBuddy AI
// (buddyIDs in internal/agent), by their keys.
func namedFor(r *http.Request, model string) (string, bool) {
if model == "" {
return "", false
}
switch agent := agentOf(r); agent {
case "workbuddy", "workbuddy-ai":
return provider.AgentNamed(agent, model)
}
return "", false
}
// estimatedMoved are the built-ins that estimated a count, as their
// plugins do, moved or beside the built-in (kiro-plugin); Command Code's
// whatever its plan, as the plugin alone knows a Go key.
@@ -2430,9 +2444,19 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// request is already whole in memory, so keep it as it came, and the
// reply goes to a spool as it streams
wholeBodies := usage.ObservedBodies() == usage.WholeBodies
// WorkBuddy names a model by the name its list shows it under, given
// as its id with the provider left out of the names (buddyIDs in
// internal/agent): the model of that name, before any other a bare
// id would find. The reply keeps the name asked for (askedFor)
byName := askedFor
if id, ok := namedFor(r, askedFor); ok {
body = rewriteModel(body, id)
plain = rewriteModel(plain, id)
byName = id
}
// a model asked for at an effort of its own (a Claude Code tier, #536)
// is the model, every try of it asked for that effort
asked, askedEffort := askedAt(askedFor)
asked, askedEffort := askedAt(byName)
if askedEffort != "" {
body = rewriteModel(body, asked)
plain = rewriteModel(plain, asked)
+98
View File
@@ -0,0 +1,98 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// With the provider left out of WorkBuddy's names, magpie gives it each
// model's name as its id (buddyIDs in internal/agent), as WorkBuddy shows
// a custom model "name:id" (elis_pina on X). WorkBuddy asks for the model
// by that name, which reaches the model it names, before a model another
// provider serves under the same bare id. Any
// other agent's request for that name is not taken to it.
func TestWorkBuddyAsksByName(t *testing.T) {
fresh(t)
var mu sync.Mutex
got := map[string][]string{}
upstream := func(name string) *httptest.Server {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
mu.Lock()
got[name] = append(got[name], gjson.GetBytes(b, "model").String())
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c","model":"x","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)
}))
t.Cleanup(srv.Close)
return srv
}
first := upstream("first").URL + "/v1"
if err := provider.Save(provider.Provider{ID: "first", Name: "First", Key: "k", Models: []string{"other"}, Chat: first}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "second", Name: "Second", Key: "k", Models: []string{"glm-5.3"}, Chat: upstream("second").URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := provider.SetAgentSuffix("workbuddy", provider.SuffixOff); err != nil {
t.Fatal(err)
}
shown, _ := provider.CatalogFor("workbuddy")
var name string
for i, l := range provider.LabelsFor("workbuddy", shown) {
if shown[i].ID == "second/glm-5.3" {
name = l
}
}
if name == "" || strings.Contains(name, "Second") {
t.Fatalf("name %q", name)
}
// the provider listed first serves a model under that same bare id,
// hidden from WorkBuddy's list, which a bare id finds first
if err := provider.Save(provider.Provider{ID: "first", Name: "First", Key: "k", Models: []string{name}, Chat: first}); err != nil {
t.Fatal(err)
}
if err := provider.SetHiddenModels("workbuddy", []string{"first/" + name}); err != nil {
t.Fatal(err)
}
if p, _, ok := provider.Resolve(name); !ok || p.ID != "first" {
t.Fatalf("setup: a bare %q goes to %q, not the provider listed first", name, p.ID)
}
if id, ok := provider.AgentNamed("workbuddy", name); !ok || id != "second/glm-5.3" {
t.Fatalf("AgentNamed(%q) = %q, %v", name, id, ok)
}
handler := lanGuard(New().Handler())
send := func(key string) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+name+`","messages":[{"role":"user","content":"hi"}]}`))
req.RemoteAddr = "127.0.0.1:5000"
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "CLI/2.161.0 WorkBuddy/2.161.0")
req.Header.Set("Authorization", "Bearer "+key)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
rec := send(TokenFor("workbuddy"))
if rec.Code != http.StatusOK {
t.Fatalf("status %d: %s", rec.Code, rec.Body)
}
mu.Lock()
if len(got["second"]) != 1 || got["second"][0] != "glm-5.3" || len(got["first"]) != 0 {
t.Fatalf("asked for %q, upstreams saw %v", name, got)
}
mu.Unlock()
// another agent's key: the name is no id of its list's
send(TokenFor("opencode"))
mu.Lock()
defer mu.Unlock()
if len(got["second"]) != 1 || len(got["first"]) != 1 {
t.Fatalf("another agent's request was taken by WorkBuddy's names: %v", got)
}
}
+20
View File
@@ -958,6 +958,26 @@ func LabelsFor(agent string, es []Entry) []string {
return out
}
// AgentNamed is the catalog id of the one model the agent of that id's
// list names name (LabelsFor), for an agent that asks for a model by the
// name its list shows: WorkBuddy shows a model's id after its name
// ("GLM-5.3:workbuddy/glm-5.3", elis_pina on X), so with the provider left
// out of the names it is given the name as the id too. false when no model
// shown, or more than one, is named so.
func AgentNamed(agent, name string) (string, bool) {
if name == "" {
return "", false
}
shown := catalogKept(agent).shown
id, n := "", 0
for i, l := range LabelsFor(agent, shown) {
if l == name {
id, n = shown[i].ID, n+1
}
}
return id, n == 1
}
// PlainName is the entry's name alone: a remote magpie's model's without
// the provider its list put after it by that magpie's own setting, which
// this one's Provider in model names Off leaves out as well (ARNO on