Files
magpie/internal/provider/zcode_models.go
T
yetone 2221b63f93 agent, provider: tests no longer read the machine's /Applications or Program Files, so a Mac with DeepSeek Harness.app installed keeps TestAsideOfflineDisconnectRestoresWithoutDaemon green (#1823)
What: every place magpie looks for installed apps outside the home folder
now goes through proc.SystemDirs, which in a test binary testenv isolated
puts the path under the test's home (as it already does for Homebrew's
bin, #1525):
- agent: a new macAppFolders(home) (/Applications via SystemDirs, plus
  ~/Applications) is used by appFolders (desktop apps: Codex, dsh),
  pencilApp, t3App and reasonixDetected;
- cursorLocalRoots: macOS through macAppFolders, Windows' ProgramFiles and
  Linux's /opt, /usr/share, /usr/lib through SystemDirs;
- zedAppPath's /Applications/Zed*.app, npmGlobalPrefix's ProgramFiles npm
  fallback, and provider's /Applications/ZCode.app builtin config.
Production behaviour is unchanged: SystemDirs returns paths as they are
outside a sandboxed test.

Why: HasApp/AppVersion read the real /Applications, so on a Mac with
DeepSeek Harness.app the dsh fixture's CLI was never "missing" and the test
failed every time; CI has no such app, so nobody else saw it. The same
shape was in five other readers.

Test: TestAppFoldersStayInTheTestHome checks every app folder lies under
testenv's home (all OSes), and on macOS that an app installed in the
sandbox's /Applications is the one found.

Run (go1.26.8, sandbox HOME, private GOCACHE):
- repro on old code: appFolders pointed at a temp folder holding a fake
  "DeepSeek Harness.app/Contents/Info.plist" (com.deepseek.dsh) ->
  TestAsideOfflineDisconnectRestoresWithoutDaemon FAIL "native fixture must
  report missing CLI".
- break check: macAppFolders put back to the literal /Applications ->
  TestAppFoldersStayInTheTestHome FAIL (appFolders, macAppFolders,
  cursorLocalRoots look in /Applications; sandbox app not found). Restored:
  pass.
- gofmt -l clean; go vet ./... (darwin), GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- go test -tags nogui ./internal/agent ./internal/proc ./internal/provider: ok.
- -race -count=5 on the touched agent tests: ok.
Not run: the full go test ./...; Windows and Linux test runs (vet only);
reasonix's Windows registry lookup and Zed's mdfind fallback still ask
the machine (not folder paths) and are left as they are.

Reported-by: mdwsk88
2026-10-12 23:56:20 +08:00

255 lines
7.5 KiB
Go

package provider
// PLUGIN-SERVED (see AGENTS.md): ZCode ("zcode") is a deprecated built-in
// subscription served by its plugin, @magpie-community/opencode-zcode-auth,
// once moved onto it (provider.Moved; the default for a new sign-in). A
// moved one's sign-ins, models, requests and usage are all the plugin's,
// never this code's (only the move, in migrate*.go, still reads its
// accounts). A fix here alone doesn't reach those users; fix the plugin
// (github.com/magpie-community/plugins, packages/zcode) and raise the
// mover's min in internal/provider/migrate_zcode.go.
// A coding plan's models are the ones ZCode offers for it, from ZCode's
// built-in provider config: zcode.z.ai names the release to use
// (/api/v1/client/configs, its configs.builtin_provider_config_json), a
// JSON on cdn-zcode.z.ai that lists each plan's models (by providerId,
// "account:zai-individual-coding-plan") and what each model is, by rules
// matched in turn on its id. ZCode keeps whichever of that release and the
// one it ships with (or cached last) is the later revision, and so does
// magpie. Nothing here is the account's: neither is signed.
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/proc"
)
type zcodeBuiltin struct {
Revision int `json:"revision"`
Config struct {
ProviderConfigRules struct {
ProviderRules []struct {
ProviderID string `json:"providerId"`
BuiltinModelIDs []string `json:"builtinModelIds"`
} `json:"providerRules"`
} `json:"providerConfigRules"`
ModelConfigRules struct {
ModelRules []struct {
Match string `json:"modelMatch"`
Config zcodeModelRule `json:"config"`
} `json:"modelRules"`
ProviderModels []struct {
ProviderID string `json:"providerId"`
ModelID string `json:"modelId"`
Config struct {
Enabled *bool `json:"enabled"`
} `json:"config"`
} `json:"builtinProviderModelRules"`
} `json:"modelConfigRules"`
} `json:"config"`
}
type zcodeModelRule struct {
Properties struct {
ContextWindow int `json:"contextWindow"`
InputFormat struct {
SupportsImage *bool `json:"supportsImage"`
} `json:"inputFormat"`
} `json:"properties"`
OptionSpecs struct {
MaxOutputTokens struct {
Max int `json:"max"`
} `json:"maxOutputTokens"`
ReasoningLevel struct {
Values []string `json:"values"`
} `json:"reasoningLevel"`
} `json:"optionSpecs"`
}
// zcodeEfforts are ZCode's reasoning levels for a model in magpie's words:
// "disabled" is none, and "enabled", a model's one level when it has no
// others (GLM-5-Turbo's), is high.
func zcodeEfforts(values []string) []string {
var out []string
for _, v := range values {
switch v {
case "disabled":
v = "none"
case "enabled":
v = "high"
}
if !slices.Contains(out, v) {
out = append(out, v)
}
}
return out
}
// zcodePlanID is ZCode's providerId for the coding plan served at base.
// A team's plan has the individual one's models.
func zcodePlanID(base string) string {
if strings.Contains(base, "/zcode-plan/") { // ZCode's Start Plan (zcode_start.go)
return "account:zai-start-plan"
}
if strings.Contains(base, "bigmodel.cn") {
return "account:bigmodel-individual-coding-plan"
}
return "account:zai-individual-coding-plan"
}
// zcodeFetchModels is the plan at base's models, as ZCode has them now.
func zcodeFetchModels(ctx context.Context, base string) ([]catalog.Model, error) {
b, err := zcodeRemoteBuiltin(ctx)
if l, ok := zcodeLocalBuiltin(); ok && (err != nil || l.Revision > b.Revision) {
b, err = l, nil
}
if err != nil {
return nil, err
}
ms := b.models(zcodePlanID(base))
if len(ms) == 0 {
return nil, fmt.Errorf("ZCode's config (revision %d) has no models for %s", b.Revision, zcodePlanID(base))
}
return ms, nil
}
func (b zcodeBuiltin) models(plan string) []catalog.Model {
var ids []string
on := map[string]bool{}
add := func(id string) {
if k := strings.ToLower(id); !on[k] {
on[k] = true
ids = append(ids, id)
}
}
for _, r := range b.Config.ProviderConfigRules.ProviderRules {
if r.ProviderID == plan {
for _, id := range r.BuiltinModelIDs {
add(id)
}
}
}
off := map[string]bool{}
for _, r := range b.Config.ModelConfigRules.ProviderModels {
if r.ProviderID != plan {
continue
}
if r.Config.Enabled != nil && !*r.Config.Enabled {
off[strings.ToLower(r.ModelID)] = true
continue
}
add(r.ModelID)
}
var out []catalog.Model
for _, id := range ids {
if off[strings.ToLower(id)] {
continue
}
m := catalog.Model{ID: id, Name: id}
// every rule that matches the id, later ones over earlier ones
for _, r := range b.Config.ModelConfigRules.ModelRules {
re, err := regexp.Compile("^(?i:" + r.Match + ")$")
if err != nil || !re.MatchString(id) {
continue
}
c := r.Config
if c.Properties.ContextWindow > 0 {
m.Context = c.Properties.ContextWindow
}
if c.OptionSpecs.MaxOutputTokens.Max > 0 {
m.Output = c.OptionSpecs.MaxOutputTokens.Max
}
if v := c.Properties.InputFormat.SupportsImage; v != nil {
m.Images, m.ImageInput = *v, v
}
if vs := c.OptionSpecs.ReasoningLevel.Values; len(vs) > 0 {
m.Efforts = zcodeEfforts(vs)
}
}
out = append(out, m)
}
return out
}
// zcodeRemoteBuiltin is the release zcode.z.ai names now.
func zcodeRemoteBuiltin(ctx context.Context) (zcodeBuiltin, error) {
var cfg struct {
Configs struct {
URL string `json:"builtin_provider_config_json"`
} `json:"configs"`
}
arch := runtime.GOARCH
if arch == "amd64" {
arch = "x64"
}
platform := runtime.GOOS
if platform == "windows" {
platform = "win32"
}
u := zcodeAPI + "/api/v1/client/configs?app_version=" + zcodeAppVersion + "&platform=" + platform + "-" + arch
if err := zcodeCall(ctx, http.MethodGet, u, "", nil, &cfg); err != nil {
return zcodeBuiltin{}, fmt.Errorf("ZCode's configs: %w", err)
}
if !strings.HasPrefix(cfg.Configs.URL, "https://") {
return zcodeBuiltin{}, errors.New("ZCode's configs name no provider config")
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, cfg.Configs.URL, nil)
if err != nil {
return zcodeBuiltin{}, err
}
req.Header.Set("User-Agent", "ZCode/"+zcodeAppVersion)
res, err := http.DefaultClient.Do(req)
if err != nil {
return zcodeBuiltin{}, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return zcodeBuiltin{}, fmt.Errorf("ZCode's provider config: %s", res.Status)
}
var b zcodeBuiltin
if err := json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&b); err != nil {
return zcodeBuiltin{}, fmt.Errorf("ZCode's provider config: %w", err)
}
return b, nil
}
// zcodeBuiltinFiles are where an installed ZCode keeps a release: the one
// it ships with, and the one it last took, under ~/.zcode.
var zcodeBuiltinFiles = func() []string {
home, _ := os.UserHomeDir()
fs, _ := filepath.Glob(filepath.Join(home, ".zcode", "v2", "runtime", "provider", "*", "*", "*", "zcode-builtin.json"))
if runtime.GOOS == "darwin" {
fs = append(fs, proc.SystemDirs("/Applications/ZCode.app/Contents/Resources/config/provider/zcode-builtin.json")...)
}
return fs
}
// zcodeLocalBuiltin is the latest release an installed ZCode has.
func zcodeLocalBuiltin() (zcodeBuiltin, bool) {
var best zcodeBuiltin
found := false
for _, f := range zcodeBuiltinFiles() {
raw, err := os.ReadFile(f)
if err != nil {
continue
}
var b zcodeBuiltin
if json.Unmarshal(raw, &b) == nil && (!found || b.Revision > best.Revision) {
best, found = b, true
}
}
return best, found
}