diff --git a/docs/reference.md b/docs/reference.md index bf62d2639..aeade3153 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -92,6 +92,7 @@ line; agents connected to magpie lose it when it quits. | OpenChamber | `~/.config/openchamber/preferences.json` (`$OPENCHAMBER_DATA_DIR`; magpie's provider in OpenCode's config) | model, small (its own defaults, over OpenCode's) | | MiMo Code | `~/.config/mimocode/mimocode.json(c)` | model, small | | Pi | `~/.pi/agent/settings.json` | model | +| StepCode | `~/.stepcode/config.toml` (+ `models.json`; `$STEP_CODING_AGENT_DIR`, `$STEPCODE_CONFIG_DIR`) | model | | Aside | `~/.aside/u/0/settings.json` (+ `models.json`; the first account, the only one magpie wires) | model, effort, fast, standard, deep, visual, image | | OmO (omo-ai) | `~/.omo/agent/settings.json` (+ `models.json`; `$OMO_CODING_AGENT_DIR`, `$SENPI_CODING_AGENT_DIR`) | model | | Prime Agent | `~/.prime/agent/settings.json` (+ `models.json`; `$PRIME_AGENT_CODING_AGENT_DIR`) | model, thinking (Pi's fields; its key `magpie-prime-agent` names it, since its requests carry no User-Agent; the global settings alone, `allowedModels` and `subagentDefaultModel` left as they are) | @@ -135,11 +136,17 @@ line; agents connected to magpie lose it when it quits. | Snow CLI | `~/.snow/profiles/magpie.json` (`$SNOW_CONFIG_DIR`), made the active profile and copied to `config.json` | model (the user's other profiles' models too; Snow App takes the profile in with "Sync Snow CLI API config") | | Alma | Alma's local API (`localhost:23001`, while Alma runs; alma-server's data in `$ALMA_DATA_DIR`, `$XDG_DATA_HOME/alma` or `~/.local/share/alma` on Linux) | model (Alma's default; magpie's models as a provider), and Image Generation's model when it is Auto: the one magpie draws with | -Provider-scoped agents (OpenCode, MiMo Code, Pi, OmO, Aside, Goose, Crush, omp, Hermes Agent) take `provider/model`. +Provider-scoped agents (OpenCode, MiMo Code, Pi, OmO, StepCode, Aside, Goose, Crush, omp, Hermes Agent) take `provider/model`. Only agents that are installed or configured are shown. ### Notes on some agents +#### StepCode + +StepCode is configured via [`stepcode.go`](../internal/agent/stepcode.go). Magpie manages global `defaultProvider` and `defaultModel` in `~/.stepcode/config.toml` (or the parent of an absolute `STEP_CODING_AGENT_DIR`) and writes its catalog into `~/.stepcode/models.json` using Pi's provider format. Magpie only manages model selection; StepCode controls thinking levels itself. Project-local `.stepcode/config.toml` overlays take precedence over global settings. Restart StepCode or begin a new session after changing models. Detection is strictly directory-based (`~/.stepcode`), so having Smallstep's unrelated `step` certificate CLI on `PATH` is never mistaken for StepCode. + +The optional real CLI verification test is run with `MAGPIE_TEST_STEPCODE_BIN=/path/to/step go test ./internal/agent -run '^TestStepCodeRealCLISandbox$' -count=1`. It runs StepCode in an isolated temporary sandbox with telemetry disabled and without live credentials. + #### Reasonix Studio Reasonix Studio is detected from its desktop installation or a native Go diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index ecd5e2e6f..e8b7298dd 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -63,11 +63,13 @@ something else shows up as drift. - An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says. - Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune..[.]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise. - A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. What each key held before the first write is stashed under `plugin::`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). +- StepCode config root resolves to the parent of an absolute `STEP_CODING_AGENT_DIR` (agent resources directory differs from config root; relative values ignored), or `STEPCODE_CONFIG_DIR` under home when native, defaulting to `~/.stepcode` ([`stepcode.go`](../../internal/agent/stepcode.go)). Project configs override global configs in StepCode, but magpie manages global configuration only (`config.toml` and `models.json`). Detection is strictly directory-only via `agentDir`, avoiding collision with Smallstep's bare `step` command on `PATH`. Wiring performs an atomic two-file edit (`models.json` provider block and `config.toml` top-level defaults/scope) backed by `stash.json`. Custom fields within `providers.magpie` are preserved during sync, and the original provider block is restored on disconnect. Disconnect restores original defaults, preserves user native changes and custom scope edits, and removes newly created files only when empty. - Tests never touch the real machine. `TestMain` uses `testenv`, which points HOME, USERPROFILE, the XDG folders and APPDATA into a temporary folder, clears `agentenv.Vars` and puts failing stand-ins for keychain tools and agent CLIs on PATH. Agent-specific side effects (Aside, the Zed keychain, Codex's usage check) are also stubbed in `TestMain`. ## Verification ```sh +go test -tags nogui ./internal/agent -run '^TestStepCode' go test -tags nogui ./internal/agent -run 'TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress' go test -tags nogui ./internal/agent go test -tags nogui ./internal/agent -run '^TestAir' diff --git a/internal/agent/agents.go b/internal/agent/agents.go index c5153b6cc..0ea6790d1 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -91,6 +91,7 @@ func builtins(home, cfg string) []*Agent { openChamber(home, cfg), mimocode(home, cfg), pi(home), + stepcode(home), aside(home), omo(home), primeAgent(home), diff --git a/internal/agent/stepcode.go b/internal/agent/stepcode.go new file mode 100644 index 000000000..6e14077e7 --- /dev/null +++ b/internal/agent/stepcode.go @@ -0,0 +1,584 @@ +package agent + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/pelletier/go-toml/v2" + "github.com/tidwall/gjson" + "github.com/tidwall/jsonc" + + "github.com/yetone/magpie/internal/edit" +) + +// StepCode keeps its configuration in ~/.stepcode/config.toml (or +// the parent of an absolute STEP_CODING_AGENT_DIR) and its models in +// models.json using Pi's provider format. +// magpie manages defaultProvider and defaultModel in config.toml, and one +// providers.magpie entry in models.json. + +func stepcode(home string) *Agent { return stepcodeIn(here(home)) } + +func stepcodeDir(at place) string { + if d := strings.TrimSpace(at.getenv("STEP_CODING_AGENT_DIR")); filepath.IsAbs(d) { + return filepath.Dir(filepath.Clean(d)) + } + name := ".stepcode" + if at.spell == nil { + if custom := strings.TrimSpace(at.getenv("STEPCODE_CONFIG_DIR")); custom != "" { + name = custom + } + } + return filepath.Join(at.home, name) +} + +func stepcodeProvider(at place) any { + ms := make([]map[string]any, 0) + for _, m := range magpieModels("stepcode") { + ms = append(ms, piModelJSON(m, at.gw(), true)) + } + return map[string]any{ + "name": "magpie", + "baseUrl": at.v1(), + "api": "openai-completions", + "apiKey": agentKeyAt("stepcode", at.gw()), + "models": ms, + } +} + +type stepcodeTOML struct { + Provider *string `toml:"defaultProvider"` + Model *string `toml:"defaultModel"` + Scope *[]string `toml:"enabledModels"` +} + +func readStepcodeTOML(path string) (stepcodeTOML, error) { + var out stepcodeTOML + b, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return out, nil + } + return out, err + } + if len(bytes.TrimSpace(b)) == 0 { + return out, nil + } + if err := toml.Unmarshal(b, &out); err != nil { + return out, fmt.Errorf("%s: %w", path, err) + } + return out, nil +} + +func stepcodeValue(s *string) string { + if s == nil { + return "" + } + return *s +} + +func stepcodeSetString(path, key string, val *string) error { + if val == nil { + return edit.DelTOMLTop(path, key) + } + return edit.SetTOMLTopPreserving(path, edit.KV{Path: key, Value: *val}) +} + +func stepcodeScopeRaw(pats []string) (edit.Raw, error) { + b, err := toml.Marshal(map[string]any{"enabledModels": pats}) + if err != nil { + return "", err + } + _, rhs, ok := strings.Cut(string(b), "=") + if !ok { + return "", fmt.Errorf("unexpected toml output for enabledModels: %s", string(b)) + } + return edit.Raw(strings.TrimSpace(rhs)), nil +} + +func stepcodeValidateModels(path string) error { + b, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + if len(bytes.TrimSpace(b)) == 0 { + return nil + } + normalized := jsonc.ToJSON(b) + if !gjson.ValidBytes(normalized) { + return fmt.Errorf("%s: invalid JSON", path) + } + root := gjson.ParseBytes(normalized) + if !root.IsObject() { + return fmt.Errorf("%s: root must be a JSON object", path) + } + if prov := root.Get("providers"); prov.Exists() { + if !prov.IsObject() { + return fmt.Errorf("%s: 'providers' must be a JSON object", path) + } + if mag := prov.Get(magpieID); mag.Exists() { + if !mag.IsObject() { + return fmt.Errorf("%s: 'providers.%s' must be a JSON object", path, magpieID) + } + } + } + return nil +} + +func stepcodeJSONEmpty(b []byte) bool { + if len(bytes.TrimSpace(b)) == 0 { + return true + } + if bytes.Contains(b, []byte("//")) || bytes.Contains(b, []byte("/*")) { + return false + } + normalized := jsonc.ToJSON(b) + res := gjson.ParseBytes(normalized) + if !res.IsObject() { + return false + } + return len(res.Map()) == 0 +} + +func stepcodeFileExists(p string) bool { + _, err := os.Stat(p) + return err == nil +} + +type stepcodeState struct { + OrigProvider *string `json:"orig_provider,omitempty"` + OrigModel *string `json:"orig_model,omitempty"` + OrigHasScope bool `json:"orig_has_scope"` + OrigScope []string `json:"orig_scope,omitempty"` + LastHasScope bool `json:"last_has_scope"` + LastScope []string `json:"last_scope,omitempty"` + AppendedScope []string `json:"appended_scope,omitempty"` + OrigMagpieRaw *string `json:"orig_magpie_raw,omitempty"` + ConfigFileExisted bool `json:"config_file_existed"` + ModelsFileExisted bool `json:"models_file_existed"` + ProvidersMapExisted bool `json:"providers_map_existed"` +} + +func stepcodeReadStash() (map[string]string, error) { + b, err := os.ReadFile(stashPath()) + if errors.Is(err, fs.ErrNotExist) { + return map[string]string{}, nil + } + if err != nil { + return nil, fmt.Errorf("stepcode stash: %w", err) + } + var m map[string]string + if err := json.Unmarshal(b, &m); err != nil { + return nil, fmt.Errorf("stepcode stash: %w", err) + } + if m == nil { + return nil, fmt.Errorf("stepcode stash: expected an object") + } + return m, nil +} + +func loadStepcodeState(at place) (*stepcodeState, error) { + m, err := stepcodeReadStash() + if err != nil { + return nil, err + } + raw, ok := m[at.key("stepcode.wiring")] + if !ok { + return nil, nil + } + var state *stepcodeState + if err := json.Unmarshal([]byte(raw), &state); err != nil { + return nil, fmt.Errorf("stepcode wiring state: %w", err) + } + if state == nil { + return nil, fmt.Errorf("stepcode wiring state: expected an object") + } + return state, nil +} + +func stepcodeStoreState(at place, state *stepcodeState) error { + m, err := stepcodeReadStash() + if err != nil { + return err + } + key := at.key("stepcode.wiring") + if state == nil { + delete(m, key) + } else { + b, err := json.Marshal(state) + if err != nil { + return err + } + m[key] = string(b) + } + data, err := json.MarshalIndent(m, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(stashPath()), 0o700); err != nil { + return err + } + f, err := os.OpenFile(stashPath(), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err == nil { + if err := f.Close(); err != nil { + return err + } + } else if !errors.Is(err, fs.ErrExist) { + return err + } + return edit.WriteAtomic(stashPath(), data) +} + +func stepcodeStartup(cfg stepcodeTOML) string { + p := stepcodeValue(cfg.Provider) + m := stepcodeValue(cfg.Model) + def := "" + switch { + case m == "": + def = "" + case p == "": + def = m + default: + def = p + "/" + m + } + if cfg.Scope == nil || len(*cfg.Scope) == 0 { + return def + } + scope := *cfg.Scope + if def != "" && slices.ContainsFunc(scope, func(pat string) bool { return piTakes(pat, def) }) { + return def + } + first := strings.TrimSpace(scope[0]) + if i := strings.LastIndex(first, ":"); i >= 0 && slices.Contains(piLevels, first[i+1:]) { + first = first[:i] + } + if strings.ContainsAny(first, "*?[") || !strings.Contains(first, "/") { + return def + } + return first +} + +func stepcodeIn(at place) *Agent { + dir := stepcodeDir(at) + path := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + authPath := filepath.Join(dir, "auth.json") + + block := theirsKept(modelsPath, "providers."+magpieID, func() any { return stepcodeProvider(at) }, "models") + + startup := func() string { + curTOML, err := readStepcodeTOML(path) + if err != nil { + return "" + } + return stepcodeStartup(curTOML) + } + + unwire := func() error { + state, err := loadStepcodeState(at) + if err != nil { + return err + } + if state == nil { + return nil + } + curTOML, err := readStepcodeTOML(path) + if err != nil { + return err + } + if err := stepcodeValidateModels(modelsPath); err != nil { + return err + } + + if stepcodeValue(curTOML.Provider) == magpieID { + if err := stepcodeSetString(path, "defaultProvider", state.OrigProvider); err != nil { + return err + } + if err := stepcodeSetString(path, "defaultModel", state.OrigModel); err != nil { + return err + } + } + + curTOML, err = readStepcodeTOML(path) + if err != nil { + return err + } + curHasScope := (curTOML.Scope != nil) + var curList []string + if curHasScope { + curList = *curTOML.Scope + } + + if curHasScope == state.LastHasScope && slices.Equal(curList, state.LastScope) { + if state.OrigHasScope { + raw, err := stepcodeScopeRaw(state.OrigScope) + if err != nil { + return err + } + if err := edit.SetTOMLTopPreserving(path, edit.KV{Path: "enabledModels", Value: raw}); err != nil { + return err + } + } else { + if err := edit.DelTOMLTop(path, "enabledModels"); err != nil { + return err + } + } + } else if curHasScope && len(state.AppendedScope) > 0 { + kept := slices.DeleteFunc(slices.Clone(curList), func(p string) bool { + return slices.Contains(state.AppendedScope, p) + }) + if !slices.Equal(kept, curList) { + raw, err := stepcodeScopeRaw(kept) + if err != nil { + return err + } + if err := edit.SetTOMLTopPreserving(path, edit.KV{Path: "enabledModels", Value: raw}); err != nil { + return err + } + } + } + + if state.OrigMagpieRaw != nil { + if err := edit.SetJSON(modelsPath, edit.KV{Path: "providers." + magpieID, Value: json.RawMessage(*state.OrigMagpieRaw)}); err != nil { + return err + } + } else { + if err := edit.DelJSON(modelsPath, "providers."+magpieID); err != nil { + return err + } + if !state.ProvidersMapExisted { + if rawP, ok := edit.GetJSON(modelsPath, "providers"); ok && strings.TrimSpace(rawP) == "{}" { + if err := edit.DelJSON(modelsPath, "providers"); err != nil { + return err + } + } + } + } + + if !state.ModelsFileExisted { + if b, err := os.ReadFile(modelsPath); err == nil { + if stepcodeJSONEmpty(b) { + if err := edit.Remove(modelsPath); err != nil { + return err + } + } + } + } + if !state.ConfigFileExisted { + if b, err := os.ReadFile(path); err == nil { + if len(bytes.TrimSpace(b)) == 0 { + if err := edit.Remove(path); err != nil { + return err + } + } + } + } + + return stepcodeStoreState(at, nil) + } + + a := &Agent{ + ID: "stepcode", + Name: "StepCode", + Icon: "stepfun-color", + Bin: "step", + Aliases: []string{"step"}, + Dir: dir, + Path: path, + Spelled: prefixed, + UA: []string{"stepcode"}, + detect: func() bool { + return agentDir(dir) + }, + Beside: func() bool { + s, err := loadStepcodeState(at) + return err == nil && s != nil + }, + Unwire: unwire, + Check: func() string { + cur, err := readStepcodeTOML(path) + if err != nil { + return "StepCode's config (config.toml) is unreadable or malformed" + } + if err := stepcodeValidateModels(modelsPath); err != nil { + return "StepCode's models.json is unreadable or malformed" + } + if stepcodeValue(cur.Provider) != magpieID { + return "" + } + return wiringOff("StepCode", modelsPath, func(k string) (string, bool) { + return edit.GetJSON(modelsPath, "providers."+magpieID+"."+k) + }, "baseUrl", at.v1(), "apiKey", agentKeyAt("stepcode", at.gw())) + }, + Sync: func() error { + state, err := loadStepcodeState(at) + if err != nil { + return err + } + if state == nil { + return nil + } + if err := stepcodeValidateModels(modelsPath); err != nil { + return err + } + return syncJSON(modelsPath, "providers."+magpieID, block) + }, + Fields: []Field{ + { + Key: "model", + Label: "model", + Get: startup, + Set: func(v string) error { + if v == "" { + return unwire() + } + ref, isMag := strings.CutPrefix(v, magpieID+"/") + if !isMag || !isMagpie(ref) { + p, m, ok := strings.Cut(v, "/") + if !ok || p == "" || m == "" { + return fmt.Errorf("expected provider/model, got %q", v) + } + if err := unwire(); err != nil { + return err + } + cur, err := readStepcodeTOML(path) + if err != nil { + return err + } + if err := edit.SetTOMLTopPreserving(path, edit.KV{Path: "defaultProvider", Value: p}, edit.KV{Path: "defaultModel", Value: m}); err != nil { + return err + } + if cur.Scope != nil && len(*cur.Scope) > 0 { + if !slices.ContainsFunc(*cur.Scope, func(pat string) bool { return piTakes(pat, v) }) { + newScope := append(*cur.Scope, v) + raw, err := stepcodeScopeRaw(newScope) + if err != nil { + return err + } + if err := edit.SetTOMLTopPreserving(path, edit.KV{Path: "enabledModels", Value: raw}); err != nil { + return err + } + } + } + return nil + } + + curTOML, err := readStepcodeTOML(path) + if err != nil { + return err + } + if err := stepcodeValidateModels(modelsPath); err != nil { + return err + } + state, err := loadStepcodeState(at) + if err != nil { + return err + } + if state == nil { + state = &stepcodeState{} + state.ConfigFileExisted = stepcodeFileExists(path) + state.ModelsFileExisted = stepcodeFileExists(modelsPath) + if rawP, ok := edit.GetJSON(modelsPath, "providers"); ok && rawP != "" { + state.ProvidersMapExisted = true + } + if rawMagpie, ok := edit.GetJSON(modelsPath, "providers."+magpieID); ok { + state.OrigMagpieRaw = &rawMagpie + } + state.OrigProvider = curTOML.Provider + state.OrigModel = curTOML.Model + if curTOML.Scope != nil { + state.OrigHasScope = true + state.OrigScope = slices.Clone(*curTOML.Scope) + } + } else { + if stepcodeValue(curTOML.Provider) != magpieID { + state.OrigProvider = curTOML.Provider + state.OrigModel = curTOML.Model + } + curHasScope := (curTOML.Scope != nil) + var curList []string + if curHasScope { + curList = *curTOML.Scope + } + scopeChanged := false + if curHasScope != state.LastHasScope { + scopeChanged = true + } else if curHasScope && !slices.Equal(curList, state.LastScope) { + scopeChanged = true + } + if scopeChanged { + state.OrigHasScope = curHasScope + if curHasScope { + filtered := slices.DeleteFunc(slices.Clone(curList), func(p string) bool { + return slices.Contains(state.AppendedScope, p) + }) + state.OrigScope = filtered + } else { + state.OrigScope = nil + } + } + } + + // Update target scope + if curTOML.Scope != nil && len(*curTOML.Scope) > 0 { + pats := *curTOML.Scope + if !slices.ContainsFunc(pats, func(p string) bool { return piTakes(p, v) }) { + newScope := append(slices.Clone(pats), v) + state.AppendedScope = append(state.AppendedScope, v) + state.LastHasScope = true + state.LastScope = newScope + } else { + state.LastHasScope = true + state.LastScope = slices.Clone(pats) + } + } else { + state.LastHasScope = (curTOML.Scope != nil) + if curTOML.Scope != nil { + state.LastScope = slices.Clone(*curTOML.Scope) + } else { + state.LastScope = nil + } + } + + // Save state before config edits + if err := stepcodeStoreState(at, state); err != nil { + return err + } + + if err := edit.SetJSON(modelsPath, edit.KV{Path: "providers." + magpieID, Value: block()}); err != nil { + return err + } + if err := edit.SetTOMLTopPreserving(path, edit.KV{Path: "defaultProvider", Value: magpieID}, edit.KV{Path: "defaultModel", Value: ref}); err != nil { + return err + } + if state.LastHasScope && (curTOML.Scope == nil || !slices.Equal(*curTOML.Scope, state.LastScope)) { + raw, err := stepcodeScopeRaw(state.LastScope) + if err != nil { + return err + } + if err := edit.SetTOMLTopPreserving(path, edit.KV{Path: "enabledModels", Value: raw}); err != nil { + return err + } + } + + return nil + }, + Options: func(cur map[string]string) []Option { + return append(ownOptions(authPath, cur["model"]), viaMagpie("stepcode", magpieID+"/")...) + }, + }, + }, + } + + return atomic(a, path, modelsPath, stashPath()) +} diff --git a/internal/agent/stepcode_test.go b/internal/agent/stepcode_test.go new file mode 100644 index 000000000..e9cf312e6 --- /dev/null +++ b/internal/agent/stepcode_test.go @@ -0,0 +1,1043 @@ +package agent + +import ( + "context" + "encoding/json" + "errors" + "io/fs" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + "time" + + "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +func stepcodeWriteTestFile(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatalf("mkdir %s: %v", filepath.Dir(path), err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +func stepcodeReadTestFile(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(b) +} + +func TestStepCodeRegistered(t *testing.T) { + byID, err := Find("stepcode") + if err != nil || byID == nil { + t.Fatalf("Find(\"stepcode\") failed: %v", err) + } + if byID.ID != "stepcode" { + t.Fatalf("Find(\"stepcode\").ID = %q, want \"stepcode\"", byID.ID) + } + + byBin, err := Find("step") + if err != nil || byBin == nil { + t.Fatalf("Find(\"step\") failed: %v", err) + } + if byBin.ID != "stepcode" { + t.Fatalf("Find(\"step\").ID = %q, want \"stepcode\"", byBin.ID) + } + // StepCode 0.1.3's requests say "step (darwin 25.2.0; arm64)", read off + // a real turn through the gateway; they count as StepCode's + for _, ua := range []string{"step (darwin 25.2.0; arm64)", "step (linux 6.8.0; x64)"} { + if got := usage.AgentOf(ua); got != "stepcode" { + t.Fatalf("usage.AgentOf(%q) = %q, want stepcode", ua, got) + } + } +} + +func TestStepCodeLifecycle(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + authPath := filepath.Join(dir, "auth.json") + + origTOML := `# StepCode user settings +theme = "dark" +defaultProvider = "anthropic" +defaultModel = "claude-3-7-sonnet" +defaultThinkingLevel = "high" +enabledModels = ["anthropic/*", "custom/fast"] + +[mcp_servers.test] +command = "node" +` + origModels := `{ + "providers": { + "anthropic": { + "name": "Anthropic", + "models": [ + {"id": "claude-3-7-sonnet"} + ] + } + } +} +` + origAuth := `{"apiKey":"secret-123"}` + + stepcodeWriteTestFile(t, configPath, origTOML) + stepcodeWriteTestFile(t, modelsPath, origModels) + stepcodeWriteTestFile(t, authPath, origAuth) + + a := stepcode(home) + if a.Wired() { + t.Fatalf("initially expected unwired") + } + + if err := a.Connect(); err != nil { + t.Fatalf("Connect: %v", err) + } + if !a.Wired() { + t.Fatalf("expected wired after Connect") + } + + cfgStr := stepcodeReadTestFile(t, configPath) + if !strings.Contains(cfgStr, "# StepCode user settings") { + t.Errorf("leading comment lost in config.toml:\n%s", cfgStr) + } + if !strings.Contains(cfgStr, `[mcp_servers.test]`) || !strings.Contains(cfgStr, `theme = "dark"`) { + t.Errorf("unrelated settings lost in config.toml:\n%s", cfgStr) + } + if !strings.Contains(cfgStr, `defaultThinkingLevel = "high"`) { + t.Errorf("defaultThinkingLevel lost during connect:\n%s", cfgStr) + } + + var parsedCfg map[string]any + if err := toml.Unmarshal([]byte(cfgStr), &parsedCfg); err != nil { + t.Fatalf("config.toml invalid TOML: %v", err) + } + if parsedCfg["defaultProvider"] != "magpie" { + t.Errorf("defaultProvider = %v, want magpie", parsedCfg["defaultProvider"]) + } + + if stepcodeReadTestFile(t, authPath) != origAuth { + t.Errorf("auth.json modified during connect") + } + if _, err := os.Stat(filepath.Join(dir, "settings.json")); err == nil { + t.Errorf("unexpected settings.json created during connect") + } + + if err := a.Apply("model", "magpie/deepseek/flash"); err != nil { + t.Fatalf("Apply(model flash): %v", err) + } + + if err := a.Disconnect(); err != nil { + t.Fatalf("Disconnect: %v", err) + } + if a.Wired() { + t.Fatalf("still wired after Disconnect") + } + + restoredCfgStr := stepcodeReadTestFile(t, configPath) + var restoredCfg map[string]any + if err := toml.Unmarshal([]byte(restoredCfgStr), &restoredCfg); err != nil { + t.Fatalf("restored config.toml invalid: %v", err) + } + if restoredCfg["defaultProvider"] != "anthropic" || restoredCfg["defaultModel"] != "claude-3-7-sonnet" { + t.Errorf("defaults not restored: %v / %v", restoredCfg["defaultProvider"], restoredCfg["defaultModel"]) + } + if restoredCfg["defaultThinkingLevel"] != "high" { + t.Errorf("defaultThinkingLevel not preserved after disconnect: %v", restoredCfg["defaultThinkingLevel"]) + } + + if stepcodeReadTestFile(t, authPath) != origAuth { + t.Errorf("auth.json modified after disconnect") + } + if _, err := os.Stat(filepath.Join(dir, "settings.json")); err == nil { + t.Errorf("unexpected settings.json created after disconnect") + } + + var restoredModels map[string]any + if err := json.Unmarshal([]byte(stepcodeReadTestFile(t, modelsPath)), &restoredModels); err != nil { + t.Fatalf("restored models.json invalid: %v", err) + } + provs := restoredModels["providers"].(map[string]any) + if provs["anthropic"] == nil { + t.Errorf("native provider anthropic lost from models.json") + } + if provs["magpie"] != nil { + t.Errorf("magpie provider not removed on disconnect") + } + + if err := a.Connect(); err != nil { + t.Fatalf("reconnect Connect: %v", err) + } + if !a.Wired() { + t.Fatalf("expected wired after reconnect") + } + if err := a.Disconnect(); err != nil { + t.Fatalf("disconnect second time: %v", err) + } +} + +func TestStepCodeScopeRetention(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + + initialTOML := `defaultProvider = "native" +defaultModel = "one" +enabledModels = ["native/one"] +` + stepcodeWriteTestFile(t, configPath, initialTOML) + stepcodeWriteTestFile(t, modelsPath, `{"providers":{"native":{"name":"Native","models":[{"id":"one"}]}}}`) + + a := stepcode(home) + + // 1. native/one -> apply magpie/pro + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatalf("Apply pro: %v", err) + } + + cfg, err := readStepcodeTOML(configPath) + if err != nil || cfg.Scope == nil { + t.Fatalf("failed reading scope after pro: %v", err) + } + if !slices.Contains(*cfg.Scope, "magpie/deepseek/pro") { + t.Errorf("scope missing magpie/deepseek/pro: %v", *cfg.Scope) + } + + // 2. user adds native/two + userScope := append(*cfg.Scope, "native/two") + raw, err := stepcodeScopeRaw(userScope) + if err != nil { + t.Fatal(err) + } + if err := edit.SetTOMLTopPreserving(configPath, edit.KV{Path: "enabledModels", Value: raw}); err != nil { + t.Fatal(err) + } + + // 3. apply flash + if err := a.Apply("model", "magpie/deepseek/flash"); err != nil { + t.Fatalf("Apply flash: %v", err) + } + + // 4. user adds native/three + cfg2, err := readStepcodeTOML(configPath) + if err != nil || cfg2.Scope == nil { + t.Fatal(err) + } + userScope2 := append(*cfg2.Scope, "native/three") + raw2, err := stepcodeScopeRaw(userScope2) + if err != nil { + t.Fatal(err) + } + if err := edit.SetTOMLTopPreserving(configPath, edit.KV{Path: "enabledModels", Value: raw2}); err != nil { + t.Fatal(err) + } + + // 5. Disconnect + if err := a.Disconnect(); err != nil { + t.Fatalf("Disconnect: %v", err) + } + + cfgRestored, err := readStepcodeTOML(configPath) + if err != nil || cfgRestored.Scope == nil { + t.Fatalf("failed reading restored scope: %v", err) + } + expected := []string{"native/one", "native/two", "native/three"} + if !slices.Equal(*cfgRestored.Scope, expected) { + t.Errorf("restored scope = %v, want %v", *cfgRestored.Scope, expected) + } + + // User deleting scope entirely + stepcodeWriteTestFile(t, configPath, `defaultProvider = "native" +defaultModel = "one" +enabledModels = ["native/one"] +`) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if err := edit.DelTOMLTop(configPath, "enabledModels"); err != nil { + t.Fatal(err) + } + if err := a.Apply("model", "magpie/deepseek/flash"); err != nil { + t.Fatal(err) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + cfgNoScope, err := readStepcodeTOML(configPath) + if err != nil { + t.Fatal(err) + } + if cfgNoScope.Scope != nil { + t.Errorf("expected deleted scope to remain deleted on disconnect, got: %v", *cfgNoScope.Scope) + } +} + +func TestStepCodeScopeWildcardMatch(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + + initialTOML := `defaultProvider = "native" +defaultModel = "one" +enabledModels = ["magpie/*/*"] +` + stepcodeWriteTestFile(t, configPath, initialTOML) + stepcodeWriteTestFile(t, modelsPath, `{"providers":{"native":{"name":"Native","models":[{"id":"one"}]}}}`) + + a := stepcode(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + + cfg, err := readStepcodeTOML(configPath) + if err != nil || cfg.Scope == nil { + t.Fatal(err) + } + if len(*cfg.Scope) != 1 || (*cfg.Scope)[0] != "magpie/*/*" { + t.Errorf("wildcard scope modified: %v", *cfg.Scope) + } +} + +func TestStepCodeNativeChangedAndPreexisting(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + + stepcodeWriteTestFile(t, configPath, "defaultProvider = \"anthropic\"\ndefaultModel = \"claude-3-5\"\ncustom_opt = \"keep-me\"\n") + stepcodeWriteTestFile(t, modelsPath, "{\n \"providers\": {\n \"magpie\": {\n \"name\": \"my-preexisting-magpie\",\n \"baseUrl\": \"https://custom.endpoint/v1\",\n \"customKey\": \"keep-me-too\"\n }\n }\n}\n") + + a := stepcode(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + + stepcodeWriteTestFile(t, configPath, "defaultProvider = \"user-openai\"\ndefaultModel = \"gpt-4o\"\ncustom_opt = \"keep-me\"\n") + + if !a.Beside() { + t.Fatalf("expected Beside() == true after user changed native provider") + } + + if err := a.Disconnect(); err != nil { + t.Fatalf("Disconnect: %v", err) + } + + cfg, err := readStepcodeTOML(configPath) + if err != nil { + t.Fatal(err) + } + if stepcodeValue(cfg.Provider) != "user-openai" || stepcodeValue(cfg.Model) != "gpt-4o" { + t.Errorf("user native model was not retained: %v / %v", cfg.Provider, cfg.Model) + } + + modelsContent := stepcodeReadTestFile(t, modelsPath) + var parsedModels map[string]any + if err := json.Unmarshal([]byte(modelsContent), &parsedModels); err != nil { + t.Fatal(err) + } + provs := parsedModels["providers"].(map[string]any) + magpieProv := provs["magpie"].(map[string]any) + if magpieProv["name"] != "my-preexisting-magpie" || magpieProv["customKey"] != "keep-me-too" { + t.Errorf("preexisting providers.magpie was not restored: %v", magpieProv) + } + + if err := a.Unwire(); err != nil { + t.Errorf("repeat Unwire failed: %v", err) + } + + if err := a.Sync(); err != nil { + t.Errorf("Sync after disconnect failed: %v", err) + } + modelsContent2 := stepcodeReadTestFile(t, modelsPath) + if modelsContent != modelsContent2 { + t.Errorf("Sync re-wired after disconnect") + } + + emptyHome := t.TempDir() + t.Setenv("HOME", emptyHome) + t.Setenv("USERPROFILE", emptyHome) + aEmpty := stepcode(emptyHome) + if err := aEmpty.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + emptyConfig := filepath.Join(emptyHome, ".stepcode", "config.toml") + emptyModels := filepath.Join(emptyHome, ".stepcode", "models.json") + if _, err := os.Stat(emptyConfig); err != nil { + t.Fatalf("expected config.toml created") + } + if _, err := os.Stat(emptyModels); err != nil { + t.Fatalf("expected models.json created") + } + if err := aEmpty.Disconnect(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(emptyConfig); !errors.Is(err, fs.ErrNotExist) { + t.Errorf("expected empty config.toml removed on disconnect") + } + if _, err := os.Stat(emptyModels); !errors.Is(err, fs.ErrNotExist) { + t.Errorf("expected empty models.json removed on disconnect") + } +} + +func TestStepCodeJSONCCommentsAndTrailingComma(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + + jsoncModels := `{ + // User comments in models.json + "providers": { + "my-openai": { + "name": "My OpenAI", + "models": [ + {"id": "gpt-4o",}, // trailing comma + ], + }, + }, +} +` + stepcodeWriteTestFile(t, configPath, "defaultProvider = \"my-openai\"\ndefaultModel = \"gpt-4o\"\n") + stepcodeWriteTestFile(t, modelsPath, jsoncModels) + + a := stepcode(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatalf("Apply on JSONC models.json failed: %v", err) + } + + content := stepcodeReadTestFile(t, modelsPath) + if !strings.Contains(content, "// User comments in models.json") { + t.Errorf("JSONC comments lost in models.json:\n%s", content) + } + + if err := a.Disconnect(); err != nil { + t.Fatalf("Disconnect: %v", err) + } + + contentAfter := stepcodeReadTestFile(t, modelsPath) + if !strings.Contains(contentAfter, "// User comments in models.json") { + t.Errorf("JSONC comments lost after disconnect:\n%s", contentAfter) + } +} + +func TestStepCodeSyncAndDrift(t *testing.T) { + home, _ := museHome(t) + a := stepcode(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + + modelsPath := filepath.Join(home, ".stepcode", "models.json") + + modelsContent := stepcodeReadTestFile(t, modelsPath) + var parsed map[string]any + if err := json.Unmarshal([]byte(modelsContent), &parsed); err != nil { + t.Fatal(err) + } + magpieProv := parsed["providers"].(map[string]any)["magpie"].(map[string]any) + magpieProv["customUnknownKey"] = "keep-this" + b, err := json.MarshalIndent(parsed, "", " ") + if err != nil { + t.Fatal(err) + } + stepcodeWriteTestFile(t, modelsPath, string(b)) + + if err := a.Sync(); err != nil { + t.Fatalf("Sync: %v", err) + } + + modelsContent = stepcodeReadTestFile(t, modelsPath) + if err := json.Unmarshal([]byte(modelsContent), &parsed); err != nil { + t.Fatal(err) + } + magpieProv = parsed["providers"].(map[string]any)["magpie"].(map[string]any) + if magpieProv["customUnknownKey"] != "keep-this" { + t.Errorf("Sync dropped unknown key in providers.magpie: %v", magpieProv) + } + + fixedTime := time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC) + if err := os.Chtimes(modelsPath, fixedTime, fixedTime); err != nil { + t.Fatal(err) + } + bytesBefore := stepcodeReadTestFile(t, modelsPath) + + if err := a.Sync(); err != nil { + t.Fatalf("second Sync: %v", err) + } + info, err := os.Stat(modelsPath) + if err != nil { + t.Fatal(err) + } + if !info.ModTime().Equal(fixedTime) { + t.Errorf("idempotent Sync touched mtime: got %v, want %v", info.ModTime(), fixedTime) + } + if stepcodeReadTestFile(t, modelsPath) != bytesBefore { + t.Errorf("idempotent Sync changed file bytes") + } + + magpieProv["baseUrl"] = "http://127.0.0.1:9999/v1" + b, _ = json.MarshalIndent(parsed, "", " ") + stepcodeWriteTestFile(t, modelsPath, string(b)) + checkMsg := a.Check() + if !strings.Contains(checkMsg, "baseUrl") { + t.Errorf("Check() did not report URL drift: %q", checkMsg) + } + + magpieProv["baseUrl"] = here(home).v1() + magpieProv["apiKey"] = "drifted-key" + b, _ = json.MarshalIndent(parsed, "", " ") + stepcodeWriteTestFile(t, modelsPath, string(b)) + checkKeyMsg := a.Check() + if !strings.Contains(checkKeyMsg, "apiKey") && !strings.Contains(checkKeyMsg, "changed") { + t.Errorf("Check() did not report apiKey drift: %q", checkKeyMsg) + } + + if err := a.Reapply(); err != nil { + t.Fatalf("Reapply: %v", err) + } + if a.Check() != "" { + t.Errorf("Check() still reports drift after Reapply: %q", a.Check()) + } +} + +func TestStepCodeCatalogUpdateSync(t *testing.T) { + home, _ := museHome(t) + a := stepcode(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + + modelsPath := filepath.Join(home, ".stepcode", "models.json") + if !strings.Contains(stepcodeReadTestFile(t, modelsPath), "deepseek/pro") { + t.Fatalf("models.json missing initial model") + } + + if err := provider.Save(provider.Provider{ + ID: "deepseek", + Name: "DeepSeek", + Chat: "https://api.deepseek.com/v1", + Key: "k", + Models: []string{"pro-v2"}, + }); err != nil { + t.Fatal(err) + } + + if err := a.Sync(); err != nil { + t.Fatalf("Sync with updated catalog: %v", err) + } + + updated := stepcodeReadTestFile(t, modelsPath) + if !strings.Contains(updated, "deepseek/pro-v2") { + t.Errorf("Sync did not add new catalog model deepseek/pro-v2:\n%s", updated) + } + if strings.Contains(updated, "\"id\": \"deepseek/pro\"") { + t.Errorf("Sync did not prune removed catalog model deepseek/pro:\n%s", updated) + } +} + +func TestStepCodeMetadataAndLANKey(t *testing.T) { + home, _ := museHome(t) + if err := provider.Save(provider.Provider{ + ID: "resp-prov", + Name: "RespProv", + Key: "k", + Responses: "https://resp.example.com/v1", + Models: []string{"resp-mod"}, + }); err != nil { + t.Fatal(err) + } + if err := catalog.SaveLive("resp-prov", "https://resp.example.com/v1", []catalog.Model{ + { + ID: "resp-mod", + Name: "Resp Mod", + Context: 128000, + Output: 4096, + APIs: []string{string(provider.Responses)}, + }, + }); err != nil { + t.Fatal(err) + } + a := stepcode(home) + if err := a.Apply("model", "magpie/resp-prov/resp-mod"); err != nil { + t.Fatal(err) + } + + modelsPath := filepath.Join(home, ".stepcode", "models.json") + var parsed map[string]any + if err := json.Unmarshal([]byte(stepcodeReadTestFile(t, modelsPath)), &parsed); err != nil { + t.Fatal(err) + } + magpieProv := parsed["providers"].(map[string]any)["magpie"].(map[string]any) + if magpieProv["api"] != "openai-completions" { + t.Errorf("api = %v, want openai-completions", magpieProv["api"]) + } + modelsList := magpieProv["models"].([]any) + if len(modelsList) == 0 { + t.Fatalf("empty models list") + } + var targetModel map[string]any + for _, m := range modelsList { + mm := m.(map[string]any) + if mm["id"] == "resp-prov/resp-mod" { + targetModel = mm + break + } + } + if targetModel == nil { + t.Fatalf("resp-prov/resp-mod not found in models: %v", modelsList) + } + if targetModel["contextWindow"] != float64(128000) { + t.Errorf("contextWindow = %v, want 128000", targetModel["contextWindow"]) + } + if targetModel["maxTokens"] != float64(4096) { + t.Errorf("maxTokens = %v, want 4096", targetModel["maxTokens"]) + } + if targetModel["api"] != "openai-responses" { + t.Errorf("native protocol api = %v, want openai-responses", targetModel["api"]) + } + + // WSL NAT key runtime test: actually Apply in separate WSL home + wslAddr := "http://172.23.80.1:3425" + if err := access.ConfigureLAN(true, false); err != nil { + t.Fatal(err) + } + lanKey := access.LANSecret() + + wslHome := t.TempDir() + wslPl := place{home: wslHome, spell: func(s string) string { return s }, base: func() string { return wslAddr }} + wslAgent := stepcodeIn(wslPl) + if err := wslAgent.Apply("model", "magpie/resp-prov/resp-mod"); err != nil { + t.Fatalf("wslAgent.Apply: %v", err) + } + + wslModelsPath := filepath.Join(wslHome, ".stepcode", "models.json") + var wslParsed map[string]any + if err := json.Unmarshal([]byte(stepcodeReadTestFile(t, wslModelsPath)), &wslParsed); err != nil { + t.Fatal(err) + } + wslMagpieProv := wslParsed["providers"].(map[string]any)["magpie"].(map[string]any) + if wslMagpieProv["baseUrl"] != wslAddr+"/v1" { + t.Errorf("wsl baseUrl = %v, want %v", wslMagpieProv["baseUrl"], wslAddr+"/v1") + } + if wslMagpieProv["apiKey"] != lanKey { + t.Errorf("wsl apiKey = %v, want lanKey %v", wslMagpieProv["apiKey"], lanKey) + } + if err := wslAgent.Disconnect(); err != nil { + t.Fatalf("wslAgent.Disconnect: %v", err) + } +} + +func TestStepCodeStrictValidationAndRollback(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + + stepcodeWriteTestFile(t, configPath, "bad toml [[ [") + a := stepcode(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err == nil { + t.Errorf("expected error applying on malformed TOML") + } + if a.Check() == "" { + t.Errorf("Check() should report malformed config as wiring error") + } + + stepcodeWriteTestFile(t, configPath, "defaultProvider = 12345\n") + if err := a.Apply("model", "magpie/deepseek/pro"); err == nil { + t.Errorf("expected error on non-string defaultProvider") + } + + stepcodeWriteTestFile(t, configPath, "enabledModels = \"not-a-list\"\n") + if err := a.Apply("model", "magpie/deepseek/pro"); err == nil { + t.Errorf("expected error on non-array enabledModels") + } + + stepcodeWriteTestFile(t, configPath, "defaultProvider = \"anthropic\"\ndefaultModel = \"claude\"\n") + stepcodeWriteTestFile(t, modelsPath, "not valid json {") + if err := a.Apply("model", "magpie/deepseek/pro"); err == nil { + t.Errorf("expected error applying on malformed models.json") + } + + stepcodeWriteTestFile(t, modelsPath, `{"providers": 12345}`) + if err := a.Apply("model", "magpie/deepseek/pro"); err == nil { + t.Errorf("expected error applying on non-object providers in models.json") + } + stepcodeWriteTestFile(t, modelsPath, `{"providers": {"magpie": "not-an-object"}}`) + if err := a.Apply("model", "magpie/deepseek/pro"); err == nil { + t.Errorf("expected error applying on non-object providers.magpie in models.json") + } + + stepcodeWriteTestFile(t, configPath, "defaultProvider = \"\"\ndefaultModel = \"\"\n") + stepcodeWriteTestFile(t, modelsPath, `{"providers": {}}`) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatalf("Apply: %v", err) + } + if err := a.Disconnect(); err != nil { + t.Fatalf("Disconnect: %v", err) + } + cfg, err := readStepcodeTOML(configPath) + if err != nil { + t.Fatal(err) + } + if cfg.Provider == nil || *cfg.Provider != "" || cfg.Model == nil || *cfg.Model != "" { + t.Errorf("empty defaults not restored as empty strings: %v / %v", cfg.Provider, cfg.Model) + } +} + +func TestStepCodeStashSafety(t *testing.T) { + cases := []struct { + name string + raw string + }{ + {"null", "null"}, + {"array", "[]"}, + {"null_entry", `{"stepcode.wiring":"null"}`}, + {"invalid_entry", `{"stepcode.wiring":"invalid"}`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + initialTOML := "defaultProvider = \"native\"\ndefaultModel = \"test\"\n" + initialModels := `{"providers":{"native":{"name":"Native"}}}` + + stepcodeWriteTestFile(t, configPath, initialTOML) + stepcodeWriteTestFile(t, modelsPath, initialModels) + stepcodeWriteTestFile(t, stashPath(), tc.raw) + + a := stepcode(home) + err := a.Field("model").Set("magpie/deepseek/pro") + if err == nil { + t.Fatalf("expected error with corrupted stash %s", tc.raw) + } + + if got := stepcodeReadTestFile(t, configPath); got != initialTOML { + t.Errorf("config.toml modified on stash error: %s", got) + } + if got := stepcodeReadTestFile(t, modelsPath); got != initialModels { + t.Errorf("models.json modified on stash error: %s", got) + } + if got := stepcodeReadTestFile(t, stashPath()); got != tc.raw { + t.Errorf("stash.json modified on stash error: %s", got) + } + }) + } + + t.Run("permission_and_unwire", func(t *testing.T) { + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + stepcodeWriteTestFile(t, configPath, "defaultProvider = \"native\"\ndefaultModel = \"test\"\n") + stepcodeWriteTestFile(t, modelsPath, `{"providers":{"native":{"name":"Native"}}}`) + + _ = os.Remove(stashPath()) + + a := stepcode(home) + if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil { + t.Fatalf("Field.Set failed: %v", err) + } + + if runtime.GOOS != "windows" { + info, err := os.Stat(stashPath()) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm()&0o077 != 0 { + t.Errorf("stash permissions not 0600: %v", info.Mode().Perm()) + } + } + + if err := a.Unwire(); err != nil { + t.Fatalf("Unwire failed: %v", err) + } + }) + + t.Run("directory_failure", func(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("skipping directory permission failure test on windows or as root") + } + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + initialTOML := "defaultProvider = \"native\"\ndefaultModel = \"test\"\n" + stepcodeWriteTestFile(t, configPath, initialTOML) + stepcodeWriteTestFile(t, modelsPath, `{"providers":{"native":{"name":"Native"}}}`) + + stashDir := filepath.Dir(stashPath()) + if err := os.MkdirAll(stashDir, 0o755); err != nil { + t.Fatal(err) + } + _ = os.Remove(stashPath()) + if err := os.Chmod(stashDir, 0o500); err != nil { + t.Fatal(err) + } + defer func() { _ = os.Chmod(stashDir, 0o755) }() + + a := stepcode(home) + err := a.Field("model").Set("magpie/deepseek/pro") + if err == nil { + t.Fatalf("expected error with unwritable stash directory") + } + + _ = os.Chmod(stashDir, 0o755) + if got := stepcodeReadTestFile(t, configPath); got != initialTOML { + t.Errorf("config.toml modified on stash dir failure: %s", got) + } + }) +} + +func TestStepCodeAtomicRollbackOnSecondFileFailure(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("skipping symlink directory permission failure test on windows or as root") + } + + home, _ := museHome(t) + dir := filepath.Join(home, ".stepcode") + configPath := filepath.Join(dir, "config.toml") + modelsPath := filepath.Join(dir, "models.json") + + initialModels := `{"providers": {"native": {"name": "Native"}}}` + initialConfig := "defaultProvider = \"native\"\ndefaultModel = \"test\"\n" + initialStash := "{}" + stepcodeWriteTestFile(t, modelsPath, initialModels) + stepcodeWriteTestFile(t, stashPath(), initialStash) + + // Create separate read-only folder holding target config file + targetDir := filepath.Join(home, "target-readonly") + targetConfig := filepath.Join(targetDir, "real-config.toml") + stepcodeWriteTestFile(t, targetConfig, initialConfig) + + // Symlink config.toml to targetConfig + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(targetConfig, configPath); err != nil { + t.Fatal(err) + } + + // Make target directory read-only so atomic temporary write for config.toml fails + if err := os.Chmod(targetConfig, 0o400); err != nil { + t.Fatal(err) + } + if err := os.Chmod(targetDir, 0o500); err != nil { + t.Fatal(err) + } + defer func() { + _ = os.Chmod(targetDir, 0o755) + _ = os.Chmod(targetConfig, 0o644) + }() + + a := stepcode(home) + err := a.Apply("model", "magpie/deepseek/pro") + if err == nil { + t.Fatalf("expected error writing to read-only symlink target") + } + if !strings.Contains(err.Error(), targetDir) { + t.Errorf("expected error to contain targetDir %q, got: %v", targetDir, err) + } + + _ = os.Chmod(targetDir, 0o755) + _ = os.Chmod(targetConfig, 0o644) + + currentModels := stepcodeReadTestFile(t, modelsPath) + if currentModels != initialModels { + t.Errorf("atomic rollback failed: models.json was not restored:\n%s", currentModels) + } + currentConfig := stepcodeReadTestFile(t, targetConfig) + if currentConfig != initialConfig { + t.Errorf("atomic rollback failed: config.toml was not restored:\n%s", currentConfig) + } + currentStash := stepcodeReadTestFile(t, stashPath()) + if currentStash != initialStash { + t.Errorf("atomic rollback failed: stash.json was not restored:\n%s", currentStash) + } + state, loadErr := loadStepcodeState(here(home)) + if loadErr != nil { + t.Fatalf("loadStepcodeState error: %v", loadErr) + } + if state != nil { + t.Errorf("atomic rollback failed: stash record was left behind") + } +} + +func TestStepCodeDirectoryAndWSL(t *testing.T) { + home := t.TempDir() + + d := stepcodeDir(here(home)) + if d != filepath.Join(home, ".stepcode") { + t.Errorf("default dir = %q, want %q", d, filepath.Join(home, ".stepcode")) + } + + absTarget := filepath.Join(home, "custom", "agent") + t.Setenv("STEP_CODING_AGENT_DIR", absTarget) + d = stepcodeDir(here(home)) + if d != filepath.Join(home, "custom") { + t.Errorf("abs STEP_CODING_AGENT_DIR dir = %q, want %q", d, filepath.Join(home, "custom")) + } + + t.Setenv("STEP_CODING_AGENT_DIR", "rel/agent") + d = stepcodeDir(here(home)) + if d != filepath.Join(home, ".stepcode") { + t.Errorf("rel STEP_CODING_AGENT_DIR dir = %q, want default %q", d, filepath.Join(home, ".stepcode")) + } + t.Setenv("STEP_CODING_AGENT_DIR", "") + + t.Setenv("STEPCODE_CONFIG_DIR", ".my-step") + d = stepcodeDir(here(home)) + if d != filepath.Join(home, ".my-step") { + t.Errorf("STEPCODE_CONFIG_DIR dir = %q, want %q", d, filepath.Join(home, ".my-step")) + } + t.Setenv("STEPCODE_CONFIG_DIR", "") + + t.Setenv("STEP_CODING_AGENT_DIR", absTarget) + t.Setenv("STEPCODE_CONFIG_DIR", ".my-step") + wslPlace := place{home: home, spell: func(s string) string { return s }} + d = stepcodeDir(wslPlace) + if d != filepath.Join(home, ".stepcode") { + t.Errorf("WSL dir = %q, want .stepcode %q", d, filepath.Join(home, ".stepcode")) + } + t.Setenv("STEP_CODING_AGENT_DIR", "") + t.Setenv("STEPCODE_CONFIG_DIR", "") + + stepDir := filepath.Join(home, "bin") + dummyStep := filepath.Join(stepDir, "step") + stepcodeWriteTestFile(t, dummyStep, "#!/bin/sh\nexit 0\n") + _ = os.Chmod(dummyStep, 0o755) + t.Setenv("PATH", stepDir+string(os.PathListSeparator)+os.Getenv("PATH")) + + a := stepcode(home) + if a.Detected() { + t.Errorf("Detected() = true with only bare step CLI on PATH") + } + + stepcodeWriteTestFile(t, filepath.Join(home, ".stepcode", "config.toml"), "theme = \"dark\"\n") + if !a.Detected() { + t.Errorf("Detected() = false after .stepcode directory created") + } +} + +func TestStepCodeRealCLISandbox(t *testing.T) { + stepBin := os.Getenv("MAGPIE_TEST_STEPCODE_BIN") + if stepBin == "" { + t.Skip("skipping real CLI sandbox test: MAGPIE_TEST_STEPCODE_BIN not set") + } + if !filepath.IsAbs(stepBin) { + t.Fatalf("MAGPIE_TEST_STEPCODE_BIN must be an absolute path, got %q", stepBin) + } + if _, err := os.Stat(stepBin); err != nil { + t.Fatalf("MAGPIE_TEST_STEPCODE_BIN binary not found: %v", err) + } + + home, _ := museHome(t) + agentDir := filepath.Join(home, ".stepcode", "agent") + if err := os.MkdirAll(agentDir, 0o755); err != nil { + t.Fatal(err) + } + + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("STEP_CODING_AGENT_DIR", agentDir) + + stepcodeWriteTestFile(t, filepath.Join(home, ".stepcode", "config.toml"), "[telemetry]\nenabled = false\n") + + a := stepcode(home) + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatalf("Apply: %v", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + cmdPath := exec.CommandContext(ctx, stepBin, "config", "path", "--json") + cmdPath.Dir = home + cmdPath.Env = []string{ + "HOME=" + home, + "USERPROFILE=" + home, + "STEP_CODING_AGENT_DIR=" + agentDir, + "PATH=" + os.Getenv("PATH"), + } + outPath, err := cmdPath.CombinedOutput() + if err != nil { + t.Fatalf("step config path --json failed: %v, output:\n%s", err, string(outPath)) + } + t.Logf("step config path output:\n%s", string(outPath)) + + var pathResult struct { + GlobalSettingsPath string `json:"globalSettingsPath"` + GlobalModelsPath string `json:"globalModelsPath"` + } + if err := json.Unmarshal(outPath, &pathResult); err != nil { + t.Fatalf("failed parsing step config path JSON: %v", err) + } + expectedCfg := filepath.Join(home, ".stepcode", "config.toml") + expectedModels := filepath.Join(home, ".stepcode", "models.json") + if pathResult.GlobalSettingsPath != expectedCfg { + t.Errorf("globalSettingsPath = %q, want %q", pathResult.GlobalSettingsPath, expectedCfg) + } + if pathResult.GlobalModelsPath != expectedModels { + t.Errorf("globalModelsPath = %q, want %q", pathResult.GlobalModelsPath, expectedModels) + } + + cmdList := exec.CommandContext(ctx, stepBin, "--list-models") + cmdList.Dir = home + cmdList.Env = cmdPath.Env + outList, err := cmdList.CombinedOutput() + if err != nil { + t.Fatalf("step --list-models failed: %v, output:\n%s", err, string(outList)) + } + listStr := string(outList) + t.Logf("step --list-models output:\n%s", listStr) + if !stepcodeListsMagpie(listStr) || !strings.Contains(listStr, "deepseek/pro") { + t.Errorf("step --list-models did not list magpie/deepseek/pro:\n%s", listStr) + } + + if err := a.Disconnect(); err != nil { + t.Fatalf("Disconnect: %v", err) + } + + cmdListAfter := exec.CommandContext(ctx, stepBin, "--list-models") + cmdListAfter.Dir = home + cmdListAfter.Env = cmdPath.Env + outListAfter, err := cmdListAfter.CombinedOutput() + if err != nil { + t.Fatalf("step --list-models after disconnect failed: %v, output:\n%s", err, string(outListAfter)) + } + // a row of the list is " …"; the folder step prints + // its docs from may itself have "magpie" in it, so only a row counts + if stepcodeListsMagpie(string(outListAfter)) { + t.Errorf("step --list-models still lists magpie after Disconnect:\n%s", string(outListAfter)) + } +} + +// stepcodeListsMagpie is whether step --list-models has a row under the +// magpie provider. +func stepcodeListsMagpie(out string) bool { + for _, line := range strings.Split(out, "\n") { + if f := strings.Fields(line); len(f) > 0 && f[0] == "magpie" { + return true + } + } + return false +} diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index 1c92afa41..1de809152 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -301,6 +301,8 @@ var wslKinds = []wslKind{ } return nil }}, + {id: "stepcode", name: "StepCode", dir: ".stepcode", in: stepcodeIn, + asleep: wslOwnAsleep("stepcode", "model")}, // only its settings.json: its sign-in, sessions and prompt history, // read on this machine for Claude Code here, aren't read in a distro {id: "claude", name: "Claude Code", dir: ".claude", bin: "claude", in: claudeIn, diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go index 615fed85f..c20a2288a 100644 --- a/internal/agentenv/agentenv.go +++ b/internal/agentenv/agentenv.go @@ -44,6 +44,8 @@ var Vars = []string{ "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "PI_CONFIG_DIR", "PI_PROFILE", "OMO_CODING_AGENT_DIR", "SENPI_CODING_AGENT_DIR", "PRIME_AGENT_CODING_AGENT_DIR", + // StepCode: config root resolution and folder overrides + "STEP_CODING_AGENT_DIR", "STEPCODE_CONFIG_DIR", // omp "OMP_PROFILE", // Qoder's two builds, the global site's and China's @@ -94,5 +96,6 @@ var NotPaths = map[string]bool{ "PI_PROFILE": true, "OMP_PROFILE": true, "WINDSURF_API_SERVER_URL": true, "ZCODE_CREDENTIAL_SECRET": true, "PI_CONFIG_DIR": true, "OPENCODE_DB": true, - "MAGPIE_ZED_BIN": true, "MAGPIE_ZED_PROCESS_NAMES": true, + "STEPCODE_CONFIG_DIR": true, + "MAGPIE_ZED_BIN": true, "MAGPIE_ZED_PROCESS_NAMES": true, }