diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 3961232c4..75e246a85 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -79,6 +79,11 @@ type Agent struct { // WSL is the distro an agent inside WSL lives in, "" for this // machine's own (see wsl.go). WSL string + // Import, for an app that takes magpie only through an import link of + // its own, which the user confirms there (Cindy), is that link; the app + // has no fields magpie sets. Added says whether it has magpie already. + Import func() string + Added func() bool // detect, when set, says whether the agent is here in place of looking // for its files and binary: a distro's, probed once. detect func() bool diff --git a/internal/agent/agents.go b/internal/agent/agents.go index ceb0fcb98..9eec1715b 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -79,6 +79,7 @@ func All() []*Agent { zcode(home), hanako(home), alma(), + cindy(), }, wslAgents()...) } diff --git a/internal/agent/cindy.go b/internal/agent/cindy.go new file mode 100644 index 000000000..ff0bd5c9d --- /dev/null +++ b/internal/agent/cindy.go @@ -0,0 +1,101 @@ +package agent + +// Cindy (a desktop app that runs Claude Code, Codex and Pi) keeps its +// providers in its own database, their keys encrypted, and takes a new one +// only through its import link, which the user confirms in Cindy: +// +// cindy://provider/import?v=1&data= +// +// So magpie has nothing to set there: its row is the link, magpie as one +// custom provider with an endpoint for each of Cindy's runtimes, and +// whether Cindy has it already, read from Cindy's database and never +// written. + +import ( + "database/sql" + "encoding/base64" + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" + + "github.com/yetone/magpie/internal/gateway" + _ "modernc.org/sqlite" +) + +// CindyScheme begins every Cindy import link. +const CindyScheme = "cindy://provider/import?" + +type cindyEndpoint struct { + Protocol string `json:"protocol"` + BaseURL string `json:"baseUrl"` + Targets []string `json:"targets"` + ModelsURL string `json:"modelsUrl"` +} + +// CindyLink is the link that adds the gateway at url to Cindy as the +// provider Magpie, keyed so that its requests are counted as Cindy's. +func CindyLink(url string) string { + v1 := url + "/v1" + models := v1 + "/models" + payload := struct { + Kind string `json:"kind"` + Name string `json:"name"` + ID string `json:"id"` + Auth map[string]any `json:"auth"` + Endpoints []cindyEndpoint `json:"endpoints"` + }{ + Kind: "custom", Name: "Magpie", ID: magpieID, + Auth: map[string]any{"method": "apiKey", "apiKey": gateway.TokenFor("cindy")}, + Endpoints: []cindyEndpoint{ + {"anthropic-messages", url, []string{"claude-code"}, models}, + {"openai-responses", v1, []string{"codex"}, models}, + {"openai-chat", v1, []string{"pi"}, models}, + }, + } + b, _ := json.Marshal(payload) + return CindyScheme + "v=1&data=" + base64.RawURLEncoding.EncodeToString(b) +} + +// cindyHas reports whether Cindy's database at path has magpie among its +// custom providers: by the id or name the link gives it, or by the +// gateway's address in its endpoints. Opened read-only; no database, or +// one that can't be read, is no. +func cindyHas(path, gw string) bool { + if _, err := os.Stat(path); err != nil { + return false + } + p := filepath.ToSlash(path) + if !strings.HasPrefix(p, "/") { + p = "/" + p // C:/… on Windows + } + u := url.URL{Scheme: "file", Path: p, RawQuery: "mode=ro&_pragma=busy_timeout(1000)"} + db, err := sql.Open("sqlite", u.String()) + if err != nil { + return false + } + defer db.Close() + var n int + err = db.QueryRow(`SELECT count(*) FROM custom_providers + WHERE id = ? OR lower(name) = ? OR instr(runtimes, ?) > 0`, magpieID, magpieID, gw).Scan(&n) + return err == nil && n > 0 +} + +func cindy() *Agent { + // where Cindy keeps its data (~/Library/Application Support/Cindy on a + // Mac): there once Cindy was installed and opened + dir := "" + if d, err := os.UserConfigDir(); err == nil { + dir = filepath.Join(d, "Cindy") + } + return &Agent{ + ID: "cindy", Name: "Cindy", Icon: "cindy", + UA: []string{"cindy"}, + Dir: dir, Path: dir, + Import: func() string { return CindyLink(gateway.URL()) }, + Added: func() bool { + return dir != "" && cindyHas(filepath.Join(dir, "cindy-local-v1.db"), gateway.URL()) + }, + } +} diff --git a/internal/agent/cindy_test.go b/internal/agent/cindy_test.go new file mode 100644 index 000000000..480b527e4 --- /dev/null +++ b/internal/agent/cindy_test.go @@ -0,0 +1,70 @@ +package agent + +import ( + "database/sql" + "encoding/base64" + "encoding/json" + "path/filepath" + "strings" + "testing" +) + +func TestCindyLink(t *testing.T) { + link := CindyLink("http://127.0.0.1:3425") + data, ok := strings.CutPrefix(link, CindyScheme+"v=1&data=") + if !ok { + t.Fatalf("link = %s", link) + } + b, err := base64.RawURLEncoding.DecodeString(data) + if err != nil { + t.Fatal(err) + } + var p struct { + Kind, Name, ID string + Auth struct{ Method, APIKey string } + Endpoints []struct { + Protocol, BaseURL string + Targets []string + } + } + if err := json.Unmarshal(b, &p); err != nil { + t.Fatal(err) + } + if p.Kind != "custom" || p.ID != "magpie" || p.Auth.Method != "apiKey" || p.Auth.APIKey != "magpie-cindy" || len(p.Endpoints) != 3 { + t.Fatalf("payload = %+v", p) + } + if p.Endpoints[0].BaseURL != "http://127.0.0.1:3425" || p.Endpoints[1].BaseURL != "http://127.0.0.1:3425/v1" { + t.Fatalf("endpoints = %+v", p.Endpoints) + } +} + +func TestCindyHas(t *testing.T) { + path := filepath.Join(t.TempDir(), "cindy-local-v1.db") + gw := "http://127.0.0.1:3425" + if cindyHas(path, gw) { + t.Fatal("no database, yet has magpie") + } + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.Exec(`CREATE TABLE custom_providers (id text PRIMARY KEY, name text, runtimes text DEFAULT '{}')`); err != nil { + t.Fatal(err) + } + if cindyHas(path, gw) { + t.Fatal("empty, yet has magpie") + } + if _, err := db.Exec(`INSERT INTO custom_providers VALUES ('p1', 'Other', '{"codex":{"baseUrl":"https://x"}}')`); err != nil { + t.Fatal(err) + } + if cindyHas(path, gw) { + t.Fatal("another provider taken for magpie") + } + if _, err := db.Exec(`INSERT INTO custom_providers VALUES ('p2', 'Mine', '{"codex":{"baseUrl":"http://127.0.0.1:3425/v1"}}')`); err != nil { + t.Fatal(err) + } + if !cindyHas(path, gw) { + t.Fatal("the gateway's provider not found") + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 410b49a25..caa63b751 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -70,6 +70,10 @@ type agentJSON struct { Fields []fieldJSON `json:"fields"` // Drift: its config no longer does what magpie set, and how to set it again Drift *agent.Drift `json:"drift,omitempty"` + // Import: an app that takes magpie by its own link (Cindy), and + // whether it has magpie already + Import string `json:"import,omitempty"` + Added bool `json:"added,omitempty"` } // clientJSON is an agent, or another client the gateway knows, as a @@ -462,6 +466,9 @@ func state() stateJSON { aj.Fields = append(aj.Fields, fieldJSON{Key: f.Key, Label: f.Label, Value: vals[f.Key], Options: opts}) } aj.Drift = a.Drift() + if a.Import != nil { + aj.Import, aj.Added = a.Import(), a.Added != nil && a.Added() + } s.Agents = append(s.Agents, aj) } if ps, err := profile.Load(); err == nil { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 894e1ed6e..d7a8ee039 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -90,6 +90,7 @@ const CHEV = "m5.5 6.5 2.5 2.5 2.5-2.5"; const CHEV_R = "m6.5 4.5 3 3.5-3 3.5"; const CHECK = "m3.5 8.5 3 3 6-7"; const PLUS = "M8 3.5v9M3.5 8h9"; +const OUT = "M6.5 3.5h-3v9h9v-3M9 3.5h3.5V7M12.5 3.5 7.5 8.5"; const COPY_ICON = "M5.5 5.5V3.5h7v7h-2M3.5 5.5h7v7h-7z"; // A brand icon: colour logos are images, mono logos take the text colour. @@ -113,9 +114,9 @@ function icon(name) { return e; } if (name) { - if (name.endsWith("-color") || name === "crush" || name === "zcode" || name === "alma" || name === "hanako" || name === "typesafe") { + if (name.endsWith("-color") || name === "crush" || name === "zcode" || name === "alma" || name === "hanako" || name === "cindy" || name === "typesafe") { const img = el("img"); - img.src = `icons/${name}.${name === "crush" || name === "zcode" || name === "alma" || name === "hanako" || name === "typesafe" ? "png" : "svg"}`; + img.src = `icons/${name}.${name === "crush" || name === "zcode" || name === "alma" || name === "hanako" || name === "cindy" || name === "typesafe" ? "png" : "svg"}`; img.alt = ""; img.draggable = false; e.append(img); @@ -229,11 +230,26 @@ function renderAgents() { fields.append(b); } if (extras.childNodes.length) fields.append(extras); + // an app that takes magpie by a link of its own (Cindy) has nothing to + // pick: its row opens the link, and the app asks to add magpie + if (a.import && mode !== "panel") fields.append(importButton(a)); // the panel shows what's set as words, and a row's controls only // once it's opened: one row at a time, in place let sum = null, openBox = null; const effortOf = (f) => f.key === "effort" || f.label === "effort" || f.label === "thinking"; - if (mode === "panel") { + if (mode === "panel" && a.import) { + // in words like the rest, the row itself the link + sum = el("span", "ag-sum"); + sum.append(el("span", "v" + (a.added ? "" : " empty"), a.added ? "magpie" : t("Add magpie")), el("span")); + const c = el("span", "chev"); + c.append(svg(OUT, 10, 1.6)); + sum.append(c); + row.title = importButton(a).title; + row.onclick = (ev) => { + if (ev.target.closest(".ag-handle, .ag-fix, .ag-show")) return; + importButton(a).click(); + }; + } else if (mode === "panel") { sum = el("span", "ag-sum"); const main = sorted.find((f) => !extra(f) && !f.menu && !effortOf(f)); const opt = main && optionFor(main, main.value); @@ -318,7 +334,7 @@ function renderAgents() { who.append(driftFix(a)); } row.append(agentHandle(a, row, inFold), who); - if (sum) row.append(sum, openBox); + if (sum) row.append(sum, ...(openBox ? [openBox] : [])); else row.append(fields); return row; }; @@ -472,7 +488,27 @@ async function reapplyAgent(a, btn) { let agentsGlide = null; // how the panel's edge moves after the next render let panelOpenAgent = null; // the one agent row the panel has opened -const agentUsed = (a) => a.fields.some((f) => f.value); +const agentUsed = (a) => a.added || a.fields.some((f) => f.value); + +// importButton: the one control of an app magpie is added to by its import +// link: magpie, once the app has it, or an offer to add it +function importButton(a) { + const b = el("button", "field solo import"); + b.type = "button"; + b.title = a.added + ? t("{name} has magpie as a provider · click to add it again", { name: a.name }) + : t("Opens {name} to add magpie as a provider — confirm it there", { name: a.name }); + b.append(icon("magpie"), el("span", "v" + (a.added ? "" : " empty"), a.added ? "magpie" : t("Add magpie"))); + const c = el("span", "chev"); + c.append(svg(OUT, 11, 1.6)); + b.append(c); + b.onclick = (ev) => { + ev.stopPropagation(); + if (web) location.href = a.import; + else api("open", { url: a.import }); + }; + return b; +} const isHidden = (a) => (state.settings?.agentsHidden || []).includes(a.id); // arrangeAgents: the rows in view, in order, and the folded rest. Folded is diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 15fa791a9..c0f0e9f48 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -28,6 +28,9 @@ const I18N = { "Hidden": "已隐藏", "Not set up": "未设置", "Hidden by you · show it in the list again": "你隐藏了它 · 点击放回列表", + "{name} has magpie as a provider · click to add it again": "{name} 已添加 magpie 作为提供商 · 点击可再次添加", + "Opens {name} to add magpie as a provider — confirm it there": "打开 {name} 添加 magpie 作为提供商——在那里确认即可", + "Add magpie": "添加 magpie", "{agent} hidden · find it under Hidden at the bottom": "已隐藏 {agent} · 可在列表底部「已隐藏」里找回", "Drag to reorder · click to move or hide": "拖动以调整顺序 · 点击可移动或隐藏", "Arrange {agent}": "调整 {agent}", diff --git a/internal/gui/assets/icons/cindy.png b/internal/gui/assets/icons/cindy.png new file mode 100644 index 000000000..31acb9a72 Binary files /dev/null and b/internal/gui/assets/icons/cindy.png differ diff --git a/internal/gui/providers.go b/internal/gui/providers.go index baaddd88a..dde9bb265 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -715,7 +715,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { mux.HandleFunc("POST /api/open", func(rw http.ResponseWriter, r *http.Request) { var in struct{ URL string } _ = json.NewDecoder(r.Body).Decode(&in) - if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") { + if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) { w.OpenURL(in.URL) } rw.WriteHeader(http.StatusNoContent) diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 1cc96917f..34f549a13 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -146,7 +146,15 @@ func Run() error { func newModel() model { // in the order the app lists them, those hidden there last - shown, hidden := settings.Arrange(settings.Load(), agent.Detected(), func(a *agent.Agent) string { return a.ID }) + // an app magpie has no fields in (Cindy, which takes it by a link) has + // nothing to pick here + var set []*agent.Agent + for _, a := range agent.Detected() { + if len(a.Fields) > 0 { + set = append(set, a) + } + } + shown, hidden := settings.Arrange(settings.Load(), set, func(a *agent.Agent) string { return a.ID }) m := model{agents: append(shown, hidden...), hidden: len(shown), period: usage.Week, srange: 1} m.reload() return m diff --git a/main.go b/main.go index 9dcff9135..9e4845de5 100644 --- a/main.go +++ b/main.go @@ -206,6 +206,16 @@ func run(args []string) error { if err != nil { return err } + if len(a.Fields) == 0 && a.Import != nil { + // `magpie cindy`: it takes magpie through its own link, confirmed there + if len(args) > 1 { + link := a.Import() + openInBrowser(link) + fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render("opened to add magpie — confirm it there")) + fmt.Println(muted.Render(" " + link)) + return nil + } + } switch len(args) { case 1: return list([]*agent.Agent{a}, true, -1) @@ -328,6 +338,13 @@ func list(agents []*agent.Agent, detectedOnly bool, dimFrom int) error { r.name = faint.Render(a.Name) + " " + faint.Render("hidden") } r.vals = strings.Join(parts, label.Render(" · ")) + if a.Import != nil { + if a.Added != nil && a.Added() { + r.vals = value.Render("magpie added") + } else { + r.vals = label.Render("magpie "+a.ID+" add") + faint.Render(" to add magpie") + } + } } nameW = max(nameW, lipgloss.Width(r.name)) valW = max(valW, lipgloss.Width(r.vals))