diff --git a/build/darwin/Info.plist b/build/darwin/Info.plist index 62296b9c2..8cd2090b3 100644 --- a/build/darwin/Info.plist +++ b/build/darwin/Info.plist @@ -20,6 +20,10 @@ CFBundleURLNamecom.yetone.magpie.import CFBundleURLSchemesmagpie + + CFBundleURLNamecom.yetone.magpie.ccswitch + CFBundleURLSchemesccswitch + NSHumanReadableCopyrightyetone diff --git a/internal/gui/importlink.go b/internal/gui/importlink.go index ee1bbb303..c571dce6c 100644 --- a/internal/gui/importlink.go +++ b/internal/gui/importlink.go @@ -11,7 +11,8 @@ import ( "github.com/yetone/magpie/internal/provider" ) -// An import link (magpie://import?…, see provider.ParseImport) is parsed +// An import link (magpie://import?… or ccswitch://v1/import?…, see +// provider.ParseImport) is parsed // here, parked under a random id, and the window opens on the Providers tab // with that id; the page fetches it once and asks the user before saving // anything. @@ -44,10 +45,11 @@ func stashImport(link string) string { return id } -// ImportLink is the link among a launch's arguments, if any. +// ImportLink is the link among a launch's arguments, if any: a magpie:// one, +// or a ccswitch:// one, which relays put on their pages for CC Switch. func ImportLink(args []string) string { for _, a := range args { - if strings.HasPrefix(strings.ToLower(a), provider.Scheme+":") { + if l := strings.ToLower(a); strings.HasPrefix(l, provider.Scheme+":") || strings.HasPrefix(l, provider.CCSwitchScheme+":") { return a } } diff --git a/internal/gui/importlink_test.go b/internal/gui/importlink_test.go index 3236ce024..55fb4fb6e 100644 --- a/internal/gui/importlink_test.go +++ b/internal/gui/importlink_test.go @@ -31,6 +31,11 @@ func TestImportIsReadOnce(t *testing.T) { if rec, _ := get(id); rec.Code != 404 { t.Fatalf("second read: %d", rec.Code) } + // a relay's CC Switch link opens the same confirmation + id = stashImport("ccswitch://v1/import?resource=provider&app=claude&name=My%20Relay&endpoint=https%3A%2F%2Frelay.example&apiKey=sk-r") + if rec, in := get(id); rec.Code != 200 || in.Error != "" || in.Provider.ID != "my-relay" || in.Provider.Anthropic != "https://relay.example" || in.Provider.Key != "sk-r" { + t.Fatalf("%d %+v", rec.Code, in) + } if _, in := get(stashImport("magpie://import?name=x")); in.Error == "" { t.Fatal("a bad link reported no error") } @@ -68,4 +73,7 @@ func TestImportLink(t *testing.T) { if ImportLink([]string{"MAGPIE://import?preset=x"}) == "" { t.Fatal("missed an upper-case link") } + if ImportLink([]string{"ccswitch://v1/import?resource=provider&app=claude&name=x"}) == "" { + t.Fatal("missed a CC Switch link") + } } diff --git a/internal/gui/scheme_linux.go b/internal/gui/scheme_linux.go index 301b0933c..747cc5775 100644 --- a/internal/gui/scheme_linux.go +++ b/internal/gui/scheme_linux.go @@ -61,7 +61,7 @@ Terminal=false ` if old, err := os.ReadFile(path); err == nil && strings.Contains(string(old), "Exec="+exe+" %u") && strings.Contains(string(old), "x-scheme-handler/magpie") && strings.Contains(string(old), "\nStartupWMClass="+programName+"\n") { - return iconErr + return errors.Join(iconErr, registerCCSwitch(dir, exe)) } if err := os.MkdirAll(dir, 0o755); err != nil { return err @@ -70,7 +70,44 @@ Terminal=false return err } _ = proc.Command("update-desktop-database", dir).Run() - return errors.Join(iconErr, proc.Command("xdg-mime", "default", "magpie.desktop", "x-scheme-handler/magpie").Run()) + return errors.Join(iconErr, proc.Command("xdg-mime", "default", "magpie.desktop", "x-scheme-handler/magpie").Run(), registerCCSwitch(dir, exe)) +} + +// ccSwitchEntry is the desktop entry that claims ccswitch:// links, apart +// from magpie's own so that it can be left out. +const ccSwitchEntry = "magpie-ccswitch.desktop" + +// registerCCSwitch lets magpie open ccswitch:// links, the one-click import +// links relays make for CC Switch, but only when no other app has them: CC +// Switch installed here keeps its links. The desktop's default for the +// scheme is asked first; it is set to this entry only when empty or already +// this entry. No icon or window class of its own: it is never shown. +func registerCCSwitch(dir, exe string) error { + const mime = "x-scheme-handler/ccswitch" + out, _ := proc.Command("xdg-mime", "query", "default", mime).Output() + if def := strings.TrimSpace(string(out)); def != "" && def != ccSwitchEntry { + return nil + } + path := filepath.Join(dir, ccSwitchEntry) + entry := `[Desktop Entry] +Type=Application +Name=magpie (ccswitch:// links) +Exec=` + exe + ` %u +NoDisplay=true +MimeType=` + mime + `; +Terminal=false +` + if old, err := os.ReadFile(path); err == nil && string(old) == entry && strings.TrimSpace(string(out)) == ccSwitchEntry { + return nil + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + if err := os.WriteFile(path, []byte(entry), 0o644); err != nil { + return err + } + _ = proc.Command("update-desktop-database", dir).Run() + return proc.Command("xdg-mime", "default", ccSwitchEntry, mime).Run() } // installIcon puts magpie's icon where the entry's Icon=magpie is looked diff --git a/internal/gui/scheme_linux_test.go b/internal/gui/scheme_linux_test.go index c0194562d..733625dd2 100644 --- a/internal/gui/scheme_linux_test.go +++ b/internal/gui/scheme_linux_test.go @@ -11,6 +11,28 @@ import ( "github.com/yetone/magpie/internal/testenv" ) +// fakeDesktopTools puts update-desktop-database and an xdg-mime that +// remembers the defaults it is given and answers `query default` with them, +// each call logged to calls (names only, or with arguments). +func fakeDesktopTools(t *testing.T, bin, calls string, args bool) { + t.Helper() + t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls) + t.Setenv("PATH", bin) + for _, name := range []string{"update-desktop-database", "xdg-mime"} { + log := `printf '%s\n' '` + name + `'` + if args { + log = `printf '%s\n' '` + name + `' "$@"` + } + script := "#!/bin/sh\n" + log + ` >> "$MAGPIE_SCHEME_TEST_CALLS"` + "\n" + if name == "xdg-mime" { + script += `f="$MAGPIE_SCHEME_TEST_CALLS.${3##*/}"` + "\n" + // PATH holds only these two, so shell builtins + `[ "$1" = query ] && { [ -f "$f" ] && read -r v < "$f" && echo "$v"; exit 0; }` + "\n" + + `[ "$1" = default ] && echo "$2" > "$f"` + "\n" + } + testenv.Program(t, filepath.Join(bin, name), script) + } +} + func TestRegisterScheme(t *testing.T) { for _, tc := range []struct { name string @@ -35,12 +57,7 @@ func TestRegisterScheme(t *testing.T) { t.Fatal(err) } calls := filepath.Join(root, "calls") - t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls) - t.Setenv("PATH", bin) - for _, name := range []string{"update-desktop-database", "xdg-mime"} { - script := "#!/bin/sh\nprintf '%s\\n' '" + name + "' \"$@\" >> \"$MAGPIE_SCHEME_TEST_CALLS\"\n" - testenv.Program(t, filepath.Join(bin, name), script) - } + fakeDesktopTools(t, bin, calls, true) dir := filepath.Join(data, "applications") path := filepath.Join(dir, "magpie.desktop") const old = "[Desktop Entry]\nExec=/usr/bin/magpie %u\nMimeType=x-scheme-handler/magpie;\n" @@ -84,7 +101,13 @@ func TestRegisterScheme(t *testing.T) { if err := registerScheme(); err != nil { t.Fatal(err) } - want := "update-desktop-database\n" + dir + "\nxdg-mime\ndefault\nmagpie.desktop\nx-scheme-handler/magpie\n" + // ccswitch:// links are claimed too, asked first, and on the second + // run only asked + udd := "update-desktop-database\n" + dir + "\n" + want := udd + "xdg-mime\ndefault\nmagpie.desktop\nx-scheme-handler/magpie\n" + + "xdg-mime\nquery\ndefault\nx-scheme-handler/ccswitch\n" + + udd + "xdg-mime\ndefault\nmagpie-ccswitch.desktop\nx-scheme-handler/ccswitch\n" + + "xdg-mime\nquery\ndefault\nx-scheme-handler/ccswitch\n" if got, err := os.ReadFile(calls); err != nil || string(got) != want { t.Fatalf("registration calls: %q, want %q (%v)", got, want, err) } @@ -120,11 +143,7 @@ func TestRegisterSchemeBindsAnOlderEntry(t *testing.T) { t.Fatal(err) } calls := filepath.Join(root, "calls") - t.Setenv("MAGPIE_SCHEME_TEST_CALLS", calls) - t.Setenv("PATH", bin) - for _, name := range []string{"update-desktop-database", "xdg-mime"} { - testenv.Program(t, filepath.Join(bin, name), "#!/bin/sh\nprintf '%s\\n' '"+name+"' >> \"$MAGPIE_SCHEME_TEST_CALLS\"\n") - } + fakeDesktopTools(t, bin, calls, false) exe, err := os.Executable() if err != nil { t.Fatal(err) @@ -149,7 +168,7 @@ func TestRegisterSchemeBindsAnOlderEntry(t *testing.T) { t.Fatal(err) } checkDesktopBinding(t, data, string(got)) - if c, err := os.ReadFile(calls); err != nil || string(c) != "update-desktop-database\nxdg-mime\n" { + if c, err := os.ReadFile(calls); err != nil || string(c) != "update-desktop-database\nxdg-mime\nxdg-mime\nupdate-desktop-database\nxdg-mime\nxdg-mime\n" { t.Fatalf("registered %q, want once (%v)", c, err) } } @@ -202,3 +221,34 @@ func TestKeepWebData(t *testing.T) { }) } } + +// CC Switch installed here keeps ccswitch:// links: magpie leaves the +// desktop's default for the scheme alone, and writes no entry for it. +func TestRegisterSchemeLeavesCCSwitchItsLinks(t *testing.T) { + t.Setenv("FLATPAK_ID", "") + root := t.TempDir() + data := filepath.Join(root, "data") + t.Setenv("XDG_DATA_HOME", data) + bin := filepath.Join(root, "bin") + if err := os.Mkdir(bin, 0o755); err != nil { + t.Fatal(err) + } + calls := filepath.Join(root, "calls") + fakeDesktopTools(t, bin, calls, true) + if err := os.WriteFile(calls+".ccswitch", []byte("cc-switch.desktop\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := registerScheme(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(data, "applications", ccSwitchEntry)); !os.IsNotExist(err) { + t.Fatalf("an entry for ccswitch:// was written: %v", err) + } + if c, _ := os.ReadFile(calls); strings.Contains(string(c), "default\nmagpie-ccswitch.desktop") { + t.Fatalf("took the default from CC Switch: %q", c) + } + // magpie's own scheme is still registered + if _, err := os.Stat(filepath.Join(data, "applications", "magpie.desktop")); err != nil { + t.Fatal(err) + } +} diff --git a/internal/gui/scheme_other.go b/internal/gui/scheme_other.go index 0478ea06b..4ecd2f08c 100644 --- a/internal/gui/scheme_other.go +++ b/internal/gui/scheme_other.go @@ -2,7 +2,7 @@ package gui -// registerScheme: the Mac reads the scheme from the bundle's Info.plist. +// registerScheme: the Mac reads the schemes (magpie, ccswitch) from the bundle's Info.plist. func registerScheme() error { return nil } // keepWebData: the Mac's webview keeps its data by the bundle id. diff --git a/internal/gui/scheme_windows.go b/internal/gui/scheme_windows.go index 032ee8a26..711b1041d 100644 --- a/internal/gui/scheme_windows.go +++ b/internal/gui/scheme_windows.go @@ -1,7 +1,10 @@ package gui import ( + "errors" "os" + "path/filepath" + "strings" "golang.org/x/sys/windows/registry" ) @@ -13,12 +16,43 @@ func registerScheme() error { if err != nil { return err } - k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\magpie`, registry.SET_VALUE) + return errors.Join(setScheme("magpie", exe), registerCCSwitch(exe)) +} + +// registerCCSwitch lets magpie open ccswitch:// links, the one-click import +// links relays make for CC Switch, but only while no other program has +// them: CC Switch installed here, per user or for the machine, keeps its +// links. The merged view (HKEY_CLASSES_ROOT) is asked, so both count; a +// handler whose program is gone is replaced. +func registerCCSwitch(exe string) error { + if run := schemeCommand(registry.CLASSES_ROOT, "ccswitch"); run != "" && !strings.EqualFold(filepath.Clean(run), filepath.Clean(exe)) { + if _, err := os.Stat(run); err == nil { + return nil + } + } + return setScheme("ccswitch", exe) +} + +// schemeCommand is the program a scheme's open command runs, "" when none. +func schemeCommand(root registry.Key, scheme string) string { + k, err := registry.OpenKey(root, scheme+`\shell\open\command`, registry.QUERY_VALUE) + if err != nil { + return "" + } + defer k.Close() + v, _, _ := k.GetStringValue("") + run, _, _ := strings.Cut(strings.TrimPrefix(v, `"`), `"`) + return run +} + +// setScheme points the per-user handler of scheme at exe. +func setScheme(scheme, exe string) error { + k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Classes\`+scheme, registry.SET_VALUE) if err != nil { return err } defer k.Close() - _ = k.SetStringValue("", "URL:magpie") + _ = k.SetStringValue("", "URL:"+scheme) _ = k.SetStringValue("URL Protocol", "") icon, _, err := registry.CreateKey(k, `DefaultIcon`, registry.SET_VALUE) if err == nil { diff --git a/internal/provider/importccswitch.go b/internal/provider/importccswitch.go new file mode 100644 index 000000000..e59526bf0 --- /dev/null +++ b/internal/provider/importccswitch.go @@ -0,0 +1,312 @@ +package provider + +import ( + "encoding/base64" + "encoding/json" + "net/url" + "slices" + "strings" + + "github.com/pelletier/go-toml/v2" +) + +// CCSwitchScheme is the URL scheme CC Switch (github.com/farion1231/cc-switch) +// registers. Relays put its one-click import links on their pages, so magpie +// reads them too: +// +// ccswitch://v1/import?resource=provider&app=claude&name=My%20Relay&endpoint=https://relay.example&apiKey=sk-… +// ccswitch://v1/import?resource=provider&app=claude&name=…&configFormat=json&config= +// +// The format is read from CC Switch's own parser +// (src-tauri/src/deeplink/parser.rs, provider.rs). Only resource=provider +// is something magpie has (prompts, MCP servers and skills are other +// resources). Parameters: +// +// app claude, claude-desktop, codex, gemini, agy, copilot, +// grokbuild, opencode, openclaw, hermes, pi, mcode, kimi, dsh +// or omp; it picks which endpoint the address is (below) +// name required +// endpoint the base URL; with several, comma separated, the first +// apiKey the API key +// apiFormat anthropic, openai_chat, openai_responses or gemini_native: +// which API the endpoint speaks. Without it, the app's own: +// Anthropic for claude, Responses for codex and grokbuild, +// Gemini for gemini and agy, Chat Completions for the rest +// model, haikuModel, sonnetModel, opusModel the model ids to show +// homepage the vendor's site +// iconUrl a picture, fetched only after the user confirms +// configFormat json (the default) or toml, with config: the base64 of the +// app's own settings. Its address, key and models fill what +// the other parameters leave out, as CC Switch does (claude: +// env.ANTHROPIC_*; codex: auth.OPENAI_API_KEY and +// config.toml's model provider; gemini: GEMINI_API_KEY and +// GOOGLE_GEMINI_BASE_URL). The rest of that config is not +// taken: it is the app's settings, not a provider's +// +// Everything else (enabled, notes, usage*, the CC Switch icon names) is +// dropped. The link goes through the same checks and the same confirmation +// as a magpie:// one: it becomes a magpie://import's parameters (see +// ParseImport), so nothing is saved until the user says yes. +const CCSwitchScheme = "ccswitch" + +// ccSwitchLinkApps are the app= values CC Switch's parser accepts. +var ccSwitchLinkApps = []string{"agy", "copilot", "claude", "claude-desktop", "codex", "gemini", "grokbuild", "opencode", "openclaw", "hermes", "pi", "mcode", "kimi", "dsh", "omp"} + +// ccSwitchConfigMax bounds the base64 config: a provider's settings are a +// few hundred bytes, and a URL much past this is not one. +const ccSwitchConfigMax = 256 << 10 + +// ccSwitchQuery translates a ccswitch://v1/import link into the parameters +// of a magpie import. +func ccSwitchQuery(u *url.URL) (url.Values, error) { + if !strings.EqualFold(u.Host, "v1") { + return nil, errorf("ccswitch://%s: magpie reads ccswitch://v1/import links only", u.Host) + } + if u.Path != "/import" { + return nil, errorf("ccswitch link path %q is not /import", u.Path) + } + in := u.Query() + get := func(k string) string { return strings.TrimSpace(in.Get(k)) } + + if r := get("resource"); r != "provider" { + if r == "" { + return nil, errorf("the ccswitch link has no resource=") + } + return nil, errorf("magpie takes providers from a ccswitch link; this one is a %q", r) + } + app := get("app") + if !slices.Contains(ccSwitchLinkApps, app) { + return nil, errorf("the ccswitch link's app= is not an app CC Switch knows: %q", app) + } + name := get("name") + if name == "" { + return nil, errorf("the ccswitch link has no name=") + } + if in.Has("configUrl") { + return nil, errorf("the ccswitch link's configUrl= is not supported: the config is inline, or not at all") + } + + endpoint, key := get("endpoint"), get("apiKey") + format := strings.TrimSpace(in.Get("apiFormat")) + models := []string{get("model"), get("haikuModel"), get("sonnetModel"), get("opusModel")} + + if raw := get("config"); raw != "" { + cfg, err := ccSwitchConfig(raw, get("configFormat")) + if err != nil { + return nil, err + } + c, err := cfg.read(app) + if err != nil { + return nil, err + } + if key == "" { + key = c.key + } + if endpoint == "" { + endpoint = c.endpoint + } + if format == "" { + format = c.format + } + for i, m := range c.models { + if models[i] == "" { + models[i] = m + } + } + } + + if i := strings.IndexByte(endpoint, ','); i >= 0 { + endpoint = endpoint[:i] // the first is the one requests go to + } + endpoint = strings.TrimSpace(endpoint) + + kind, err := ccSwitchKind(app, format) + if err != nil { + return nil, err + } + out := url.Values{} + out.Set("name", name) + if endpoint != "" { + out.Set(kind, endpoint) + } + if key != "" { + out.Set("key", key) + } + var ids []string + for _, m := range models { + if m = strings.TrimSpace(m); m != "" && !slices.Contains(ids, m) { + ids = append(ids, m) + } + } + out.Set("models", strings.Join(ids, ",")) + // a picture or a site that isn't an https URL is dropped, not a reason + // to turn the whole link away: CC Switch does the same + if h := get("homepage"); h != "" && page(h) != "" { + out.Set("website", h) + } + if ic := get("iconUrl"); ic != "" { + if _, err := iconURL(ic); err == nil { + out.Set("icon", ic) + } + } + return out, nil +} + +// ccSwitchKind is which of magpie's endpoints the link's address is. +func ccSwitchKind(app, format string) (string, error) { + switch format { + case "": + switch app { + case "claude", "claude-desktop": + return "anthropic", nil + case "codex", "grokbuild": + return "responses", nil + case "gemini", "agy": + return "gemini", nil + } + return "chat", nil + case "anthropic": + return "anthropic", nil + case "openai_chat": + return "chat", nil + case "openai_responses": + return "responses", nil + case "gemini_native": + return "gemini", nil + } + return "", errorf("the ccswitch link's apiFormat= is anthropic, openai_chat, openai_responses or gemini_native, not %q", format) +} + +// ccSwitchSettings is what a link's config yields. +type ccSwitchSettings struct { + endpoint, key, format string + models [4]string // model, haiku, sonnet, opus +} + +type ccSwitchCfg map[string]any + +// ccSwitchConfig decodes the config parameter as CC Switch does: base64 +// with the quirks of a URL ("+" arriving as a space, padding left off, the +// URL-safe alphabet), then JSON or TOML. +func ccSwitchConfig(raw, format string) (ccSwitchCfg, error) { + if len(raw) > ccSwitchConfigMax { + return nil, errorf("the ccswitch link's config= is too large") + } + raw = strings.ReplaceAll(strings.Trim(raw, "\r\n"), " ", "+") + raw = strings.TrimRight(raw, "=") + b, err := base64.RawStdEncoding.DecodeString(raw) + if err != nil { + if b, err = base64.RawURLEncoding.DecodeString(raw); err != nil { + return nil, errorf("the ccswitch link's config= is not base64") + } + } + var m map[string]any + switch format { + case "", "json": + err = json.Unmarshal(b, &m) + case "toml": + err = toml.Unmarshal(b, &m) + default: + return nil, errorf("the ccswitch link's configFormat= is json or toml, not %q", format) + } + if err != nil || m == nil { + return nil, errorf("the ccswitch link's config= is not a %s object", orElse(format, "json")) + } + return m, nil +} + +func orElse(s, def string) string { + if s == "" { + return def + } + return s +} + +func (c ccSwitchCfg) str(path ...string) string { + var v any = map[string]any(c) + for _, k := range path { + m, ok := v.(map[string]any) + if !ok { + return "" + } + v = m[k] + } + s, _ := v.(string) + return strings.TrimSpace(s) +} + +func (c ccSwitchCfg) obj(k string) ccSwitchCfg { + m, _ := c[k].(map[string]any) + return m +} + +// read takes the address, key and models an app's own settings hold. +func (c ccSwitchCfg) read(app string) (ccSwitchSettings, error) { + var s ccSwitchSettings + switch app { + case "claude", "claude-desktop": + env := c.obj("env") + if env == nil { + return s, errorf("the ccswitch link's claude config needs an env object") + } + s.key = orElse(env.str("ANTHROPIC_AUTH_TOKEN"), env.str("ANTHROPIC_API_KEY")) + s.endpoint = env.str("ANTHROPIC_BASE_URL") + s.models = [4]string{env.str("ANTHROPIC_MODEL"), env.str("ANTHROPIC_DEFAULT_HAIKU_MODEL"), env.str("ANTHROPIC_DEFAULT_SONNET_MODEL"), env.str("ANTHROPIC_DEFAULT_OPUS_MODEL")} + case "gemini", "agy": + env := c + if e := c.obj("env"); e != nil { + env = e + } + s.key = env.str("GEMINI_API_KEY") + s.endpoint = orElse(env.str("GOOGLE_GEMINI_BASE_URL"), env.str("GEMINI_BASE_URL")) + s.models[0] = env.str("GEMINI_MODEL") + case "codex": + return c.readCodex() + } + return s, nil +} + +// readCodex reads {"auth":{"OPENAI_API_KEY":…},"config":""}, +// or a config.toml itself. The key a provider table reads from an +// environment variable (env_key) is the computer's own, not the link's, and +// is never taken. +func (c ccSwitchCfg) readCodex() (ccSwitchSettings, error) { + var s ccSwitchSettings + doc := map[string]any(c) + if text := c.str("config"); text != "" { + doc = nil + if err := toml.Unmarshal([]byte(text), &doc); err != nil { + return s, errorf("the ccswitch link's codex config is not TOML") + } + } else if c.obj("auth") != nil { + doc = nil + } + root := ccSwitchCfg(doc) + s.key = c.obj("auth").str("OPENAI_API_KEY") + s.models[0] = root.str("model") + id := root.str("model_provider") + var tbl ccSwitchCfg + if provs := root.obj("model_providers"); provs != nil { + if tbl = provs.obj(id); tbl == nil && len(provs) == 1 { + for _, v := range provs { + tbl, _ = v.(map[string]any) + } + } + } + if tbl != nil { + s.endpoint = tbl.str("base_url") + if s.key == "" { + s.key = tbl.str("experimental_bearer_token") + } + switch tbl.str("wire_api") { + case "chat": + s.format = "openai_chat" + case "responses": + s.format = "openai_responses" + } + if s.key == "" && tbl.str("env_key") != "" { + return s, errorf("the ccswitch link gives its key through the environment variable %s, which a link can't read: add the key yourself", tbl.str("env_key")) + } + } + return s, nil +} diff --git a/internal/provider/importccswitch_test.go b/internal/provider/importccswitch_test.go new file mode 100644 index 000000000..b2e5dd397 --- /dev/null +++ b/internal/provider/importccswitch_test.go @@ -0,0 +1,167 @@ +package provider + +import ( + "os" + "reflect" + "strings" + "testing" +) + +// testdata/ccswitch_links.txt holds CC Switch's own example links, copied +// as written from its repository (deplink.html and the site integration +// guide at 3c76d3b), one per line. +func ccSwitchLinks(t *testing.T) []string { + t.Helper() + b, err := os.ReadFile("testdata/ccswitch_links.txt") + if err != nil { + t.Fatal(err) + } + var out []string + for _, l := range strings.Split(string(b), "\n") { + if strings.TrimSpace(l) != "" { + out = append(out, l) + } + } + return out +} + +func TestCCSwitchOwnExamples(t *testing.T) { + type want struct { + Name, Chat, Responses, Anthropic, Gemini, Key string + Models []string + } + got := map[string]want{} + n := 0 + for _, l := range ccSwitchLinks(t) { + p, err := ParseImport(l) + if !strings.Contains(l, "resource=provider") { + // prompts, MCP servers and skills are not providers + if err == nil || !strings.Contains(err.Error(), "providers") { + t.Errorf("%.60s: %v", l, err) + } + continue + } + if err != nil { + t.Errorf("%.90s: %v", l, err) + continue + } + n++ + if p.ID != "example-ai" && p.ID != "example-gemini" { + t.Errorf("%.90s: id %q", l, p.ID) + } + app := l[strings.Index(l, "app=")+4:] + app = app[:strings.IndexByte(app, '&')] + got[app+"/"+map[bool]string{true: "config", false: "params"}[strings.Contains(l, "config=")]+"/"+p.Name+p.Key+strings.Join(p.Models, ",")] = want{p.Name, p.Chat, p.Responses, p.Anthropic, p.Gemini, p.Key, p.Models} + } + if n != 11 { + t.Fatalf("%d provider links in the examples", n) + } + for _, c := range []struct { + key string + w want + }{ + // endpoint, apiKey: claude's address is Anthropic's + {"claude/params/Example AIsk-test-key123", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123"}}, + // the config's env, with its three tiers + {"claude/config/Example AIsk-test-key123example-chat,example-fast,example-pro", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123", Models: []string{"example-chat", "example-fast", "example-pro"}}}, + // the key in the URL, the address in the config + {"claude/config/Example AIsk-test-key123", want{Name: "Example AI", Anthropic: "https://api.example.com", Key: "sk-test-key123"}}, + // codex: config.toml's provider table, wire_api responses + {"codex/config/Example AIsk-test-key123example-coder", want{Name: "Example AI", Responses: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-coder"}}}, + {"codex/params/Example AIsk-test-key123", want{Name: "Example AI", Responses: "https://api.example.com/v1", Key: "sk-test-key123"}}, + {"gemini/config/Example GeminiAIzaSy-test-key123", want{Name: "Example Gemini", Gemini: "https://api.example.com", Key: "AIzaSy-test-key123"}}, + // apiFormat names the API an app of any kind speaks + {"opencode/params/Example AIsk-test-key123example-chat", want{Name: "Example AI", Anthropic: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-chat"}}}, + {"pi/params/Example AIsk-test-key123example-chat", want{Name: "Example AI", Chat: "https://api.example.com/v1", Key: "sk-test-key123", Models: []string{"example-chat"}}}, + } { + if g, ok := got[c.key]; !ok { + t.Errorf("no example gave %q; have %v", c.key, got) + } else if !reflect.DeepEqual(g, c.w) { + t.Errorf("%s:\n got %+v\nwant %+v", c.key, g, c.w) + } + } +} + +func TestCCSwitchIconAndUsageDropped(t *testing.T) { + for _, l := range ccSwitchLinks(t) { + if !strings.Contains(l, "iconUrl=") { + continue + } + p, err := ParseImport(l) + if err != nil || p.IconURL == "" { + t.Fatalf("iconUrl: %q, %v", p.IconURL, err) + } + } + // a usage script (CC Switch's balance query) is code: never taken + p, err := ParseImport("ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example&usageScript=KHsKfSk%3D&usageEnabled=true&usageBaseUrl=https%3A%2F%2Fevil.example") + if err != nil || p.BalanceURL != "" { + t.Fatalf("%+v %v", p, err) + } +} + +func TestCCSwitchRefused(t *testing.T) { + const base = "ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example" + for name, c := range map[string]struct{ link, why string }{ + "other version": {strings.Replace(base, "//v1/", "//v2/", 1), "v1"}, + "other path": {strings.Replace(base, "/import?", "/export?", 1), "/import"}, + "no resource": {strings.Replace(base, "resource=provider&", "", 1), "resource"}, + "unknown app": {strings.Replace(base, "app=claude", "app=nope", 1), "app"}, + "no name": {strings.Replace(base, "name=x&", "", 1), "name"}, + "plain http": {strings.Replace(base, "https", "http", 1), "https"}, + "javascript": {strings.Replace(base, "https%3A%2F%2Fa.example", "javascript%3Aalert(1)", 1), "base URL"}, + "file": {strings.Replace(base, "https%3A%2F%2Fa.example", "file%3A%2F%2F%2Fetc%2Fpasswd", 1), "base URL"}, + "bad format": {base + "&apiFormat=grpc", "apiFormat"}, + "remote config": {base + "&configUrl=https%3A%2F%2Fa.example%2Fc.json", "configUrl"}, + "config not base64": {base + "&config=%25%25%25", "base64"}, + "config not json": {base + "&config=bm90IGpzb24", "json"}, + "config huge": {base + "&config=" + strings.Repeat("A", 300<<10), "large"}, + "claude no env": {base + "&config=e30", "env"}, + "key with newline": {base + "&apiKey=sk%0Aevil", "key"}, + "no address": {"ccswitch://v1/import?resource=provider&app=claude&name=x", "base URL"}, + "codex env_key": {"ccswitch://v1/import?resource=provider&app=codex&name=x&config=" + + b64(`{"config":"model_provider=\"p\"\n[model_providers.p]\nbase_url=\"https://a.example/v1\"\nenv_key=\"HOME_SECRET\""}`), "HOME_SECRET"}, + "name only a symbol": {"ccswitch://v1/import?resource=provider&app=claude&name=%2A%2A&endpoint=https%3A%2F%2Fa.example", "id"}, + } { + t.Run(name, func(t *testing.T) { + p, err := ParseImport(c.link) + if err == nil { + t.Fatalf("accepted: %+v", p) + } + if !strings.Contains(err.Error(), c.why) { + t.Fatalf("%q does not say %q", err, c.why) + } + }) + } + if _, err := ParseImport("ccswitch://v1/import?resource=provider&app=claude&name=x&endpoint=https%3A%2F%2Fa.example&homepage=javascript%3Aalert(1)"); err != nil { + t.Fatalf("a bad homepage turned the link away: %v", err) + } +} + +// a ccswitch link is as safe as a magpie one: the balance host rule and +// the id rules are the shared ones +func TestCCSwitchNamedAsSubscription(t *testing.T) { + p, err := ParseImport("CCSWITCH://V1/import?resource=provider&app=claude&name=claude&endpoint=https%3A%2F%2Fa.example") + if err != nil || p.ID == "claude" { + t.Fatalf("%+v %v", p, err) + } +} + +func b64(s string) string { + const a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" + var out []byte + for i := 0; i < len(s); i += 3 { + var v uint + n := 0 + for j := 0; j < 3; j++ { + v <<= 8 + if i+j < len(s) { + v |= uint(s[i+j]) + n++ + } + } + for j := 0; j <= n; j++ { + out = append(out, a[(v>>(18-6*uint(j)))&63]) + } + } + return string(out) +} diff --git a/internal/provider/importurl.go b/internal/provider/importurl.go index c306257ec..a92585c9a 100644 --- a/internal/provider/importurl.go +++ b/internal/provider/importurl.go @@ -53,6 +53,13 @@ const Scheme = "magpie" // ParseImport reads an import link into the provider it describes. func ParseImport(link string) (Provider, error) { u, err := url.Parse(strings.TrimSpace(link)) + if err == nil && strings.EqualFold(u.Scheme, CCSwitchScheme) { + q, err := ccSwitchQuery(u) + if err != nil { + return Provider{}, err + } + return importFromQuery(q) + } if err != nil || !strings.EqualFold(u.Scheme, Scheme) { return Provider{}, errors.New("not a magpie:// link") } @@ -63,7 +70,14 @@ func ParseImport(link string) (Provider, error) { if action != "import" { return Provider{}, errorf("magpie://%s is not something magpie knows; links start magpie://import?", action) } - q := u.Query() + return importFromQuery(u.Query()) +} + +// importFromQuery is ParseImport after the link's shape is known: q holds +// the parameters in the list above, from a magpie:// link or translated from +// a ccswitch:// one (ccSwitchQuery). +func importFromQuery(q url.Values) (Provider, error) { + var err error get := func(k string) string { return strings.TrimSpace(q.Get(k)) } var p Provider diff --git a/internal/provider/testdata/ccswitch_links.txt b/internal/provider/testdata/ccswitch_links.txt new file mode 100644 index 000000000..81a88afbc --- /dev/null +++ b/internal/provider/testdata/ccswitch_links.txt @@ -0,0 +1,14 @@ +ccswitch://v1/import?resource=mcp&apps=claude%2Ccodex&config=eyJtY3BTZXJ2ZXJzIjp7ImNvbnRleHQ3Ijp7ImNvbW1hbmQiOiJucHgiLCJhcmdzIjpbIi15IiwiQHVwc3Rhc2gvY29udGV4dDctbWNwIl0sImVudiI6e319LCJzZXF1ZW50aWFsLXRoaW5raW5nIjp7ImNvbW1hbmQiOiJucHgiLCJhcmdzIjpbIi15IiwiQG1vZGVsY29udGV4dHByb3RvY29sL3NlcnZlci1zZXF1ZW50aWFsLXRoaW5raW5nIl0sImVudiI6e319fX0%3D +ccswitch://v1/import?resource=prompt&app=claude&name=%E4%BB%A3%E7%A0%81%E5%AE%A1%E6%9F%A5%E4%B8%93%E5%AE%B6&content=IyDku6PnoIHlrqHmn6XkuJPlrrYKCuS9oOaYr%2BS4gOS9jeaciee7j%2BmqjOeahOS7o%2BeggeWuoeafpeWRmOOAguWuoeafpeS7o%2BeggeaXtu%2B8jOWFiOaMh%2BWHuuS8muWvvOiHtOmUmeivr%2BeahOmXrumimO%2B8jOWGjee7meWHuuS%2FruaUueW7uuiuruOAgg%3D%3D&description=%E4%B8%93%E6%B3%A8%E4%BB%A3%E7%A0%81%E8%B4%A8%E9%87%8F +ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&apiKey=sk-test-key123&configFormat=json&config=eyJlbnYiOnsiQU5USFJPUElDX0JBU0VfVVJMIjoiaHR0cHM6Ly9hcGkuZXhhbXBsZS5jb20iLCJBUElfVElNRU9VVF9NUyI6IjYwMDAwMCJ9fQ%3D%3D +ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&configFormat=json&config=eyJlbnYiOnsiQU5USFJPUElDX0FVVEhfVE9LRU4iOiJzay10ZXN0LWtleTEyMyIsIkFOVEhST1BJQ19CQVNFX1VSTCI6Imh0dHBzOi8vYXBpLmV4YW1wbGUuY29tIiwiQU5USFJPUElDX01PREVMIjoiZXhhbXBsZS1jaGF0IiwiQU5USFJPUElDX0RFRkFVTFRfSEFJS1VfTU9ERUwiOiJleGFtcGxlLWZhc3QiLCJBTlRIUk9QSUNfREVGQVVMVF9TT05ORVRfTU9ERUwiOiJleGFtcGxlLWNoYXQiLCJBTlRIUk9QSUNfREVGQVVMVF9PUFVTX01PREVMIjoiZXhhbXBsZS1wcm8ifX0%3D +ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&iconUrl=https%3A%2F%2Fraw.githubusercontent.com%2Ffarion1231%2Fcc-switch%2Fmain%2Fsrc-tauri%2Ficons%2F128x128.png +ccswitch://v1/import?resource=provider&app=claude&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fS91c2VyL2JhbGFuY2UiLAogICAgbWV0aG9kOiAiR0VUIiwKICAgIGhlYWRlcnM6IHsKICAgICAgIkF1dGhvcml6YXRpb24iOiAiQmVhcmVyIHt7YXBpS2V5fX0iCiAgICB9CiAgfSwKICBleHRyYWN0b3I6IGZ1bmN0aW9uIChyZXNwb25zZSkgewogICAgaWYgKHJlc3BvbnNlLmVycm9yKSB7CiAgICAgIHJldHVybiB7IGlzVmFsaWQ6IGZhbHNlLCBpbnZhbGlkTWVzc2FnZTogU3RyaW5nKHJlc3BvbnNlLmVycm9yLm1lc3NhZ2UgfHwgcmVzcG9uc2UuZXJyb3IpIH07CiAgICB9CiAgICByZXR1cm4gewogICAgICByZW1haW5pbmc6IE51bWJlcihyZXNwb25zZS5iYWxhbmNlKSwKICAgICAgdW5pdDogIlVTRCIKICAgIH07CiAgfQp9KQ +ccswitch://v1/import?resource=provider&app=claude&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fSIucmVwbGFjZSgvXC8rJC8sICIiKS5yZXBsYWNlKC9cL3YxJC8sICIiKSArICIvdjEvdXNhZ2UiLAogICAgbWV0aG9kOiAiR0VUIiwKICAgIGhlYWRlcnM6IHsKICAgICAgIkF1dGhvcml6YXRpb24iOiAiQmVhcmVyIHt7YXBpS2V5fX0iLAogICAgICAiVXNlci1BZ2VudCI6ICJjYy1zd2l0Y2gvMS4wIgogICAgfQogIH0sCiAgZXh0cmFjdG9yOiBmdW5jdGlvbiAocmVzcG9uc2UpIHsKICAgIHZhciBxdW90YSA9IHJlc3BvbnNlLnF1b3RhIHx8IHt9OwogICAgdmFyIHJlc3VsdCA9IHsKICAgICAgaXNWYWxpZDogcmVzcG9uc2UuaXNWYWxpZCAhPT0gZmFsc2UsCiAgICAgIHVuaXQ6IHJlc3BvbnNlLnVuaXQgfHwgcXVvdGEudW5pdCB8fCAiVVNEIgogICAgfTsKICAgIGlmICh0eXBlb2YgcmVzcG9uc2UucGxhbk5hbWUgPT09ICJzdHJpbmciKSByZXN1bHQucGxhbk5hbWUgPSByZXNwb25zZS5wbGFuTmFtZTsKICAgIGlmICh0eXBlb2YgcmVzcG9uc2UucmVtYWluaW5nID09PSAibnVtYmVyIiAmJiByZXNwb25zZS5yZW1haW5pbmcgPj0gMCkgewogICAgICByZXN1bHQucmVtYWluaW5nID0gcmVzcG9uc2UucmVtYWluaW5nOwogICAgfQogICAgaWYgKHF1b3RhLmxpbWl0ID4gMCkgewogICAgICByZXN1bHQudXNlZCA9IHF1b3RhLnVzZWQ7CiAgICAgIHJlc3VsdC50b3RhbCA9IHF1b3RhLmxpbWl0OwogICAgfQogICAgaWYgKCFyZXN1bHQuaXNWYWxpZCkgewogICAgICByZXN1bHQuaW52YWxpZE1lc3NhZ2UgPSByZXNwb25zZS5zdGF0dXMKICAgICAgICA%2FIFN0cmluZyhyZXNwb25zZS5zdGF0dXMpCiAgICAgICAgOiAi5p%2Bl6K%2Bi5aSx6LSlIjsKICAgIH0KICAgIHJldHVybiByZXN1bHQ7CiAgfSwKfSk%3D&usageAutoInterval=30 +ccswitch://v1/import?resource=provider&app=codex&name=Example%20AI&configFormat=json&config=eyJhdXRoIjp7Ik9QRU5BSV9BUElfS0VZIjoic2stdGVzdC1rZXkxMjMifSwiY29uZmlnIjoibW9kZWxfcHJvdmlkZXIgPSBcImV4YW1wbGVcIlxubW9kZWwgPSBcImV4YW1wbGUtY29kZXJcIlxuXG5bbW9kZWxfcHJvdmlkZXJzLmV4YW1wbGVdXG5uYW1lID0gXCJFeGFtcGxlIEFJXCJcbmJhc2VfdXJsID0gXCJodHRwczovL2FwaS5leGFtcGxlLmNvbS92MVwiXG53aXJlX2FwaSA9IFwicmVzcG9uc2VzXCIifQ%3D%3D +ccswitch://v1/import?resource=provider&app=codex&name=Example+AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&usageScript=KHsKICByZXF1ZXN0OiB7CiAgICB1cmw6ICJ7e2Jhc2VVcmx9fS9hcGkvdXNlci9zZWxmIiwKICAgIG1ldGhvZDogIkdFVCIsCiAgICBoZWFkZXJzOiB7CiAgICAgICJBdXRob3JpemF0aW9uIjogIkJlYXJlciB7e2FjY2Vzc1Rva2VufX0iLAogICAgICAiTmV3LUFwaS1Vc2VyIjogInt7dXNlcklkfX0iCiAgICB9CiAgfSwKICBleHRyYWN0b3I6IGZ1bmN0aW9uIChyZXNwb25zZSkgewogICAgaWYgKHJlc3BvbnNlLnN1Y2Nlc3MgJiYgcmVzcG9uc2UuZGF0YSkgewogICAgICByZXR1cm4gewogICAgICAgIHBsYW5OYW1lOiByZXNwb25zZS5kYXRhLmdyb3VwLAogICAgICAgIHJlbWFpbmluZzogcmVzcG9uc2UuZGF0YS5xdW90YSAvIDUwMDAwMCwKICAgICAgICB1c2VkOiByZXNwb25zZS5kYXRhLnVzZWRfcXVvdGEgLyA1MDAwMDAsCiAgICAgICAgdW5pdDogIlVTRCIKICAgICAgfTsKICAgIH0KICAgIHJldHVybiB7IGlzVmFsaWQ6IGZhbHNlLCBpbnZhbGlkTWVzc2FnZTogU3RyaW5nKHJlc3BvbnNlLm1lc3NhZ2UgfHwgIuafpeivouWksei0pSIpIH07CiAgfQp9KQ&usageBaseUrl=https%3A%2F%2Fapi.example.com&usageAccessToken=test-access-token&usageUserId=1&usageAutoInterval=30 +ccswitch://v1/import?resource=provider&app=gemini&name=Example%20Gemini&configFormat=json&config=eyJHRU1JTklfQVBJX0tFWSI6IkFJemFTeS10ZXN0LWtleTEyMyIsIkdPT0dMRV9HRU1JTklfQkFTRV9VUkwiOiJodHRwczovL2FwaS5leGFtcGxlLmNvbSJ9 +ccswitch://v1/import?resource=provider&app=opencode&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&apiFormat=anthropic&model=example-chat +ccswitch://v1/import?resource=provider&app=pi&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com%2Fv1&apiKey=sk-test-key123&apiFormat=openai_chat&model=example-chat +ccswitch://v1/import?resource=skill&repo=example%2Fclaude-skills&branch=main +ccswitch://v1/import?resource=provider&app=claude&name=Example%20AI&endpoint=https%3A%2F%2Fapi.example.com&apiKey=sk-xxxx diff --git a/internal/uninstall/system_linux.go b/internal/uninstall/system_linux.go index 13c45d933..3b5185afa 100644 --- a/internal/uninstall/system_linux.go +++ b/internal/uninstall/system_linux.go @@ -1,6 +1,7 @@ package uninstall import ( + "errors" "os" "path/filepath" "strings" @@ -21,26 +22,33 @@ func dataHome() string { // unregisterScheme takes out the desktop entry the app made for magpie:// // links while it runs exe, or an exe that is gone, and its icon with it. func unregisterScheme(exe string) error { - entry := filepath.Join(dataHome(), "applications", "magpie.desktop") + _, err := removeEntry("magpie-ccswitch.desktop", exe) + gone, err2 := removeEntry("magpie.desktop", exe) + if gone { + _ = os.Remove(filepath.Join(dataHome(), "icons", "hicolor", "256x256", "apps", "magpie.png")) + } + return errors.Join(err, err2) +} + +// removeEntry takes out one of the app's desktop entries while it runs exe, +// or an exe that is gone. +func removeEntry(name, exe string) (bool, error) { + entry := filepath.Join(dataHome(), "applications", name) b, err := os.ReadFile(entry) if err != nil { - return nil + return false, nil } for _, l := range strings.Split(string(b), "\n") { if run, ok := strings.CutPrefix(l, "Exec="); ok { run = strings.TrimSuffix(run, " %u") if run != exe { if _, err := os.Stat(run); err == nil { - return nil // another magpie's + return false, nil // another magpie's } } } } - if err := os.Remove(entry); err != nil { - return err - } - _ = os.Remove(filepath.Join(dataHome(), "icons", "hicolor", "256x256", "apps", "magpie.png")) - return nil + return true, os.Remove(entry) } // webData is WebKitGTK's folder for the app's pages (named after the diff --git a/internal/uninstall/system_windows.go b/internal/uninstall/system_windows.go index b20bea032..795dc3679 100644 --- a/internal/uninstall/system_windows.go +++ b/internal/uninstall/system_windows.go @@ -1,6 +1,7 @@ package uninstall import ( + "errors" "os" "path/filepath" "strings" @@ -12,10 +13,14 @@ import ( const schemeKey = `Software\Classes\magpie` -// unregisterScheme takes out the magpie:// handler the app registered -// while it opens exe, or an exe that is gone. +// unregisterScheme takes out the magpie:// and ccswitch:// handlers the app +// registered while they open exe, or an exe that is gone. func unregisterScheme(exe string) error { - k, err := registry.OpenKey(registry.CURRENT_USER, schemeKey+`\shell\open\command`, registry.QUERY_VALUE) + return errors.Join(removeSchemeKey(schemeKey, exe), removeSchemeKey(`Software\Classes\ccswitch`, exe)) +} + +func removeSchemeKey(key, exe string) error { + k, err := registry.OpenKey(registry.CURRENT_USER, key+`\shell\open\command`, registry.QUERY_VALUE) if err != nil { return nil } @@ -27,7 +32,7 @@ func unregisterScheme(exe string) error { } } for _, sub := range []string{`\shell\open\command`, `\shell\open`, `\shell`, `\DefaultIcon`, ``} { - if err := registry.DeleteKey(registry.CURRENT_USER, schemeKey+sub); err != nil && err != registry.ErrNotExist { + if err := registry.DeleteKey(registry.CURRENT_USER, key+sub); err != nil && err != registry.ErrNotExist { return err } } diff --git a/site/public/docs/import.html b/site/public/docs/import.html index b65399754..2f330d0e0 100644 --- a/site/public/docs/import.html +++ b/site/public/docs/import.html @@ -318,6 +318,7 @@ href = "https://usemagpie.ai/import#" + urlencode({ LinuxBy a desktop entry (x-scheme-handler/magpie), written by the installer and again on first run. Terminalmagpie import <link> shows the same summary and asks before adding. +

CC Switch links. magpie also opens the ccswitch://v1/import?resource=provider&… links relays make for CC Switch (app, name, endpoint, apiKey, apiFormat, model, or a base64 config), with the same confirmation. Only providers are taken, not prompts, MCP servers or skills. magpie claims the scheme only when no other app has it, so CC Switch, if installed, keeps its links (on macOS, where both can claim it, the system picks).

Import links need magpie 0.1.8 or later. When magpie is already running, the link goes to that instance and its window comes forward.

diff --git a/site/public/docs/ja/import.html b/site/public/docs/ja/import.html index 7fc9482a1..7f94cf4ce 100644 --- a/site/public/docs/ja/import.html +++ b/site/public/docs/ja/import.html @@ -318,6 +318,7 @@ href = "https://usemagpie.ai/import#" + urlencode({ Linuxデスクトップエントリ(x-scheme-handler/magpie)で登録します。インストーラが書き込み、初回起動時にも再度書き込みます。 ターミナルmagpie import <リンク> が同じ概要を表示し、追加前に確認します。 +

CC Switch のリンク。magpie は、リレーが CC Switch 向けに作る ccswitch://v1/import?resource=provider&… リンクも開きます(app、name、endpoint、apiKey、apiFormat、model、または base64 の config)。確認は同じです。取り込むのはプロバイダーだけで、プロンプト、MCP、スキルは対象外です。ほかのアプリがスキームを持っていない場合にだけ登録するため、CC Switch があればそちらが開きます(両方が宣言できる macOS ではシステムが選びます)。

インポートリンクには magpie 0.1.8 以降が必要です。magpie がすでに起動している場合、リンクはそのインスタンスに渡され、ウィンドウが前面に表示されます。

diff --git a/site/public/docs/zh/import.html b/site/public/docs/zh/import.html index 12986c9a4..9c3bb661d 100644 --- a/site/public/docs/zh/import.html +++ b/site/public/docs/zh/import.html @@ -318,6 +318,7 @@ href = "https://usemagpie.ai/import#" + urlencode({ Linux通过桌面文件(x-scheme-handler/magpie)注册,安装器写一次,首次运行时再写一次。 终端magpie import <链接> 显示同样的摘要,添加前会询问。 +

CC Switch 链接。magpie 也能打开中转站为 CC Switch 做的 ccswitch://v1/import?resource=provider&… 链接(app、name、endpoint、apiKey、apiFormat、model,或 base64 的 config),同样要用户确认。只收供应商,不收提示词、MCP 和技能。只有没有别的应用占用这个协议时,magpie 才会注册它:装了 CC Switch 就仍由它打开(macOS 上两者都能声明,由系统选择)。

导入链接需要 magpie 0.1.8 或更新版本。magpie 已在运行时,链接会交给那个实例,并把它的窗口调到前台。

diff --git a/site/public/install.sh b/site/public/install.sh index ae5833fb1..6fcf9426a 100644 --- a/site/public/install.sh +++ b/site/public/install.sh @@ -286,6 +286,16 @@ if [ -n "$uninstall" ]; then if [ -f "$apps/magpie.desktop" ] && { [ "$run" = "$exe" ] || [ ! -e "$run" ]; }; then gone "$apps/magpie.desktop" fi + # the entry for ccswitch:// links, on the same terms, and its default + cc=$(runs "$apps/magpie-ccswitch.desktop" Exec) + if [ -f "$apps/magpie-ccswitch.desktop" ] && { [ "$cc" = "$exe" ] || [ ! -e "$cc" ]; }; then + gone "$apps/magpie-ccswitch.desktop" + list="$config/mimeapps.list" + if [ -f "$list" ] && grep -qx 'x-scheme-handler/ccswitch=magpie-ccswitch\.desktop;\{0,1\}' "$list"; then + grep -vx 'x-scheme-handler/ccswitch=magpie-ccswitch\.desktop;\{0,1\}' "$list" > "$list.magpie-new" || true + mv "$list.magpie-new" "$list" + fi + fi # with no menu entry (this one, or the one magpie uninstall took), # what came with it: the icon, the magpie:// default xdg-mime set # (that line only) and the menu's cache when it lists nothing else