Files
magpie/internal/agent/grokapp.go
T
yetone ee7a9b24a6 agent: Grok App is an agent magpie connects: a magpie provider channel with magpie's models and their efforts (#1625, fjrtdk)
fjrtdk asked for Grok App (RongleCat/grok-app, a desktop GUI over the Grok
Build CLI) as a full agent: MCP, skills, RTK, models and effort.

What was already there, read in the App's source:
- MCP: the App reads ~/.grok/config.toml's [mcp_servers] in both of its
  modes and hands them to the CLI it starts, so the Grok Build row's MCP
  sync already reaches it.
- Skills: Grok Build's ~/.agents/skills, synced from the Grok Build row.
- RTK: rtk has no installer for Grok Build, so there is nothing to wire.

What was missing is models, and that is what changed:
- internal/agent/grokapp.go: a new agent, "grok-app" (alias grokapp), for
  the App's agent-home/config.toml under its data folder: GROK_APP_HOME,
  else ~/Library/Application Support/com.grokapp.grok-app or ~/.grok-app
  on a Mac, %APPDATA%\grokapp\grok-app\data (and two older places) on
  Windows, $XDG_DATA_HOME/grok-app or ~/.grok-app on Linux; the first
  that exists.
  - Connecting writes a [model.magpie] channel in the App's own format
    (its custom routes): model, base_url = the gateway's /v1, name,
    api_key (magpie-grok-app, so usage says the App), api_backend =
    "chat_completions", app_provider_mode = "generic", app_models and
    app_efforts as JSON strings (the App unquotes them with serde_json),
    supports_reasoning_effort, app_supports_vision for a model that takes
    images, and context_window when magpie knows it. app_models lists
    magpie's models with their effort levels ("none" left out), so the
    App's model and effort pickers show them.
  - It sets [models] default = "magpie"; what was there is stashed, and
    Disconnect puts it back and drops the channel: the file is
    byte-identical to before (TestGrokApp).
  - A sync keeps the model and the default effort the user picked in the
    App while magpie still serves them, and writes nothing when nothing
    changed.
  - Picking one of the App's own routes (the official "grok", or a
    channel of the user's with a base_url) takes magpie out.
  - The notice says to start a new chat or restart the App, which reads
    its providers when it starts an agent; translated in i18n.js (zh-CN,
    zh-TW, ja, de) and listed in NOTICES.
- agents.go, agentenv.go (GROK_APP_HOME), docs/reference.md,
  docs/subsystems/agent-wiring.md, both READMEs' agent lists.

Picking magpie in the App is a custom route, so the App runs that agent in
its independent mode (its own #557): it clears agent-home's auth.json
rather than syncing the official sign-in. ~/.grok is never written.

What was run:
- go test -tags nogui ./internal/agent ./internal/agentenv ./internal/gui:
  ok. Full go test -tags nogui ./... under a temp HOME: ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui: ok.
- Broken by hand, each red: context_window written quoted (TestGrokApp);
  the user's picked model ignored (TestGrokAppSyncKeepsTheirs); their
  default effort dropped (SyncKeepsTheirs); Disconnect not unstashing
  (TestGrokApp); a no-op sync writing (SyncKeepsTheirs); "none" listed
  as an effort (TestGrokApp).
- Real use in a sandbox HOME: a built magpie on 127.0.0.1:3681 with a
  fake upstream; `magpie grok-app magpie/fake/echo-1` wrote the channel;
  the real grok 1.0.50, started as the App starts it on a custom route
  (GROK_HOME=agent-home, --model magpie), answered through magpie, the
  upstream saw echo-1 and usage.jsonl counted agent "grok-app". `magpie
  grok-app default` restored the file (the only difference was grok's own
  [marketplace] line written while it ran). ~/.grok/config.toml untouched.

Not tried: the real Grok App GUI (it would sign in through the keychain
and ~/.grok), a model with effort levels end to end, Windows and Linux
paths beyond TestGrokAppDir.
2026-10-12 01:55:04 +08:00

400 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package agent
// Grok App (RongleCat/grok-app, Tauri) is a desktop front end for the grok
// CLI, which it starts over ACP. Most of what the CLI reads it reads where
// Grok Build's own row writes it: MCP servers from ~/.grok/config.toml,
// which the App reads and hands each session itself in either of its modes,
// skills from ~/.agents/skills, instructions from AGENTS.md. Its models are
// its own, though: its composer lists only Grok Build's official catalog
// (models_cache.json), never a [model."<id>"] table of config.toml, and a
// model of the user's choosing is a "provider channel" of its Settings ›
// Providers page, a [model.<id>] table with the App's own keys in
// agent-home/config.toml under its data folder. That file is the CLI's
// config.toml while a channel is on: [models] default naming a channel is
// what the App takes as the route, and it then starts the CLI with
// GROK_HOME at agent-home, switching itself to its independent mode
// (grok-app's providers.rs, ensure_independent_for_custom_route).
//
// So magpie adds itself as the channel "magpie", written as the App writes
// one (upsert_custom_provider): the gateway as base_url with Grok App's own
// key, chat completions, app_models a JSON list of magpie's models with each
// one's context window, images and effort levels, so the composer offers
// them and their efforts. The model picked is the channel's model and
// [models] default is "magpie"; what default was before is stashed and put
// back on Disconnect. A model the user picks in the App's composer since is
// theirs and stays through a sync.
import (
"encoding/json"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/edit"
)
// grokAppChannel is magpie's channel's table in the App's config.toml.
const grokAppChannel = "model." + magpieID
// what Grok App says after a change (notice.go)
var noticeGrokApp = newNotice("Grok App reads its providers when it starts an agent — start a new chat in Grok App, or restart it, to use this.")
// grokAppOS is the system grokAppDir looks for the App's data on; a test
// sets it.
var grokAppOS = runtime.GOOS
// grokAppDir is the App's data folder: $GROK_APP_HOME, else where the
// directories crate's ProjectDirs("com", "grokapp", "grok-app") puts its
// data (grok-app's paths.rs app_data_root) — on a Mac ~/Library/Application
// Support/com.grokapp.grok-app, on Windows %APPDATA%\grokapp\grok-app\data,
// on Linux $XDG_DATA_HOME/grok-app. The App's README names ~/.grok-app on
// Linux and %APPDATA%\grokapp\grok-app on Windows, and the App falls back to
// ~/.grok-app (%APPDATA%\grok-app) itself, so those are looked for too; the
// first that is there wins, else the App's own default.
func grokAppDir(home, goos string) string {
if d := strings.TrimSpace(appdir.Getenv("GROK_APP_HOME")); d != "" {
return d
}
var dirs []string
switch goos {
case "darwin":
dirs = []string{filepath.Join(home, "Library", "Application Support", "com.grokapp.grok-app"), filepath.Join(home, ".grok-app")}
case "windows":
app := appdir.Getenv("APPDATA")
if app == "" {
app = filepath.Join(home, "AppData", "Roaming")
}
dirs = []string{filepath.Join(app, "grokapp", "grok-app", "data"), filepath.Join(app, "grokapp", "grok-app"), filepath.Join(app, "grok-app")}
default:
data := appdir.Getenv("XDG_DATA_HOME")
if data == "" {
data = filepath.Join(home, ".local", "share")
}
dirs = []string{filepath.Join(data, "grok-app"), filepath.Join(home, ".grok-app")}
}
for _, d := range dirs {
if isDir(d) {
return d
}
}
return dirs[0]
}
// grokAppEffort is one effort level of a channel's model, as the App's
// ProviderEffortEntry reads it.
type grokAppEffort struct {
ID string `json:"id"`
Name string `json:"name"`
IsDefault bool `json:"isDefault"`
}
// grokAppModel is one entry of a channel's app_models, as the App's
// ProviderModelEntry reads it.
type grokAppModel struct {
ID string `json:"id"`
Name string `json:"name"`
ContextWindow int `json:"contextWindow,omitempty"`
SupportsVision *bool `json:"supportsVision,omitempty"`
Efforts []grokAppEffort `json:"efforts,omitempty"`
}
// grokAppWant is magpie's models as the App is told them, was the
// app_models the channel has now. Grok Build has no effort "none" of a
// channel's: the levels are the model's others, and the one the composer
// starts on is the default the user marked in the App's Providers page
// while the model has it, else medium (the middle one without it).
func grokAppWant(was string) []grokAppModel {
var before []grokAppModel
_ = json.Unmarshal([]byte(was), &before) // a list not there or not the App's: no defaults kept
kept := map[string]string{}
for _, m := range before {
for _, e := range m.Efforts {
if e.IsDefault {
kept[m.ID] = e.ID
}
}
}
var out []grokAppModel
for _, m := range magpieModels("grok-app") {
e := grokAppModel{ID: m.ID, Name: m.Name, ContextWindow: m.Context}
if e.Name == "" {
e.Name = m.ID
}
if m.Images {
yes := true
e.SupportsVision = &yes
}
var levels []string
for _, l := range m.Efforts {
if l != "none" {
levels = append(levels, l)
}
}
if len(levels) > 0 {
def := keptEffort(kept[m.ID], levels, zcodeDefaultLevel(levels))
for _, l := range levels {
e.Efforts = append(e.Efforts, grokAppEffort{ID: l, Name: l, IsDefault: l == def})
}
}
out = append(out, e)
}
return out
}
// grokAppRead is the App's config.toml's [models] default and magpie's
// channel's keys, nil when there is none. A file that doesn't parse is an
// error, never taken as empty.
func grokAppRead(path string) (def string, ch map[string]string, err error) {
models, err := edit.GetTOMLTable(path, "models")
if err != nil {
return "", nil, err
}
ch, err = edit.GetTOMLTable(path, grokAppChannel)
return models["default"], ch, err
}
func grokApp(home string) *Agent {
dir := grokAppDir(home, grokAppOS)
path := filepath.Join(dir, "agent-home", "config.toml")
keyDefault := "grok-app:" + path + ":default"
at := here(home)
key := func() string { return agentKeyAt("grok-app", at.gw()) }
get := func() string {
def, ch, _ := grokAppRead(path)
if def == magpieID && ch != nil && ch["model"] != "" {
return magpieID + "/" + ch["model"]
}
return def
}
// wire writes magpie's channel, model, if given, its model, and
// nothing when the file has it all already. The channel's own extras
// (context window, images, efforts) are the model's, as the App copies
// them onto the channel when a model is picked in its composer.
wire := func(model string) error {
_, ch, err := grokAppRead(path)
if err != nil {
return err
}
want := grokAppWant(ch["app_models"])
if len(want) == 0 {
return nil
}
if model == "" {
model = ch["model"]
}
i := slices.IndexFunc(want, func(m grokAppModel) bool { return m.ID == model })
if i < 0 {
// a model magpie no longer has: the channel moves to its first
i = 0
}
picked := want[i]
list, _ := json.Marshal(want)
efforts := "[]"
if len(picked.Efforts) > 0 {
b, _ := json.Marshal(picked.Efforts)
efforts = string(b)
}
// key, value, and whether it is written bare (a TOML bool or
// integer, as the App and Grok Build read it) rather than a string
type kv struct {
k, v string
bare bool
}
kvs := []kv{
{"model", picked.ID, false},
{"base_url", at.v1(), false},
{"name", "magpie", false},
{"api_key", key(), false},
{"api_backend", "chat_completions", false},
{"app_provider_mode", "generic", false},
{"app_models", string(list), false},
{"app_efforts", efforts, false},
{"supports_reasoning_effort", strconv.FormatBool(len(picked.Efforts) > 0), true},
}
var gone []string
if picked.SupportsVision != nil && *picked.SupportsVision {
kvs = append(kvs, kv{"app_supports_vision", "true", false})
} else {
gone = append(gone, "app_supports_vision")
}
if picked.ContextWindow > 0 {
kvs = append(kvs, kv{"context_window", strconv.Itoa(picked.ContextWindow), true})
} else {
gone = append(gone, "context_window")
}
same := ch != nil
for _, x := range kvs {
if v, ok := ch[x.k]; !ok || v != x.v {
same = false
}
}
for _, k := range gone {
if _, ok := ch[k]; ok {
same = false
}
}
if same {
return nil
}
for _, x := range kvs {
var v any = x.v
if x.bare {
v = edit.Raw(x.v)
}
if err := edit.SetTOMLKey(path, grokAppChannel, x.k, v); err != nil {
return err
}
}
for _, k := range gone {
if err := edit.DelTOMLKey(path, grokAppChannel, k); err != nil {
return err
}
}
return nil
}
// setDefault names the route the App starts on, the key taken out for ""
setDefault := func(v string) error {
if v == "" {
return edit.DelTOMLKey(path, "models", "default")
}
return edit.SetTOMLKey(path, "models", "default", v)
}
// unwire takes magpie's channel out, and the App back to the route it
// was on before — when it is still on magpie: a route picked in the App
// since is the user's and stands
unwire := func(own string) error {
def, _, err := grokAppRead(path)
if err != nil {
return err
}
if def == magpieID {
was := unstash(keyDefault)
if own != "" {
was = own
}
if err := setDefault(was); err != nil {
return err
}
} else {
forget(keyDefault)
if own != "" {
if err := setDefault(own); err != nil {
return err
}
}
}
return edit.SetTOMLTablesMatching(path, []string{grokAppChannel}, []string{grokAppChannel + "."}, nil)
}
return atomic(&Agent{
ID: "grok-app", Name: "Grok App", Icon: "grok", Aliases: []string{"grokapp"}, Spelled: prefixed,
Dir: dir, Path: path,
Notice: func() string {
if Running(`(^|/)grok-app( |$)`) {
return noticeGrokApp.String()
}
return ""
},
Sync: func() error {
_, ch, err := grokAppRead(path)
if err != nil || ch == nil {
return err
}
return wire("")
},
Check: func() string {
def, ch, err := grokAppRead(path)
if err != nil {
return err.Error()
}
if def != magpieID {
return ""
}
if ch == nil {
return "Grok App's [" + grokAppChannel + "] (config.toml) is gone, so it no longer reaches magpie"
}
return wiringOff("Grok App", path, func(k string) (string, bool) { v, ok := ch[k]; return v, ok },
"base_url", at.v1(), "api_key", key())
},
Fields: []Field{{
// the route the App starts on: one of magpie's models is
// magpie/<provider>/<model>, magpie's channel with the model in
// it; anything else is the App's own route ("grok", or a
// channel of the user's)
Key: "model", Label: "model",
Get: get,
Set: func(v string) error {
def, ch, err := grokAppRead(path)
if err != nil {
return err
}
if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {
if def != magpieID {
stash(map[string]string{keyDefault: def})
}
if err := wire(ref); err != nil {
return err
}
return setDefault(magpieID)
}
if ch != nil || def == magpieID {
return unwire(v)
}
return setDefault(v)
},
Options: func(cur map[string]string) []Option {
return append(grokAppOwn(path, keyDefault, cur["model"]), viaMagpie("grok-app", magpieID+"/")...)
},
}},
}, path)
}
// grokAppOwn is the App's own routes for the picker: its official one
// ("grok", Grok Build's sign-in), the channels the user added, and the one
// it was on before magpie.
func grokAppOwn(path, keyDefault, cur string) []Option {
var out []Option
add := func(v, label, direct string) {
if v == "" || v == magpieID || prefixed(v) || slices.ContainsFunc(out, func(o Option) bool { return o.Value == v }) {
return
}
o := Option{Value: v, Icon: "xai", Direct: direct}
if label != "" && label != v {
o.Label = label
}
out = append(out, o)
}
add("grok", "Grok (official)", "xAI")
if tables, err := edit.TOMLTables(path); err == nil {
for _, t := range tables {
id, ok := strings.CutPrefix(t, "model.")
if !ok {
continue
}
if u, err := unquoteTOML(id); err == nil {
id = u
}
kv, _ := edit.GetTOMLTable(path, t)
if kv["base_url"] == "" {
continue
}
direct := hostOf(kv["base_url"])
add(id, kv["name"], direct)
}
}
add(stashLoad()[keyDefault], "", "")
add(cur, "", "")
return group("Grok App", out)
}
// unquoteTOML is a table name's quoted part without its quotes.
func unquoteTOML(s string) (string, error) {
if len(s) >= 2 && (s[0] == '"' || s[0] == '\'') && s[len(s)-1] == s[0] {
return s[1 : len(s)-1], nil
}
return s, os.ErrInvalid
}