diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 985a5a9e8..4f63f5905 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -409,3 +409,25 @@ file…" shows for every importable plugin subscription, moved built-ins included (`pluginSubs`, `subOf`, `importSay` in app.js). The vendor check (refresh, account lookup) is the plugin's, as its sign-in is. Tests: `TestPluginImportFiles`, `tests/plugin-import.test.cjs`. + +### The vendor CLI a plugin installs + +A plugin that runs its vendor's CLI may declare magpie-only `auth.cli`: +`name` (shown as "Installing {name}…"), `installed()` (whether it is on +this machine), `install({ signal })` (installs it, resolving once it is +there) and `manual` (how a person installs it, told when the install +fails). Before, such a plugin's sign-in failed with "install it first", +which a magpie in a container can't do (niuniu_8964 on X: agy-cli in +Docker); only a moved built-in's or a `pluginRunsCLI` plugin's CLI was +installed by magpie. The host lists the CLI on the provider (`cliOf` in +`host.js`, `plugin.Provider.CLI`) and answers `cliInstalled` and +`installCli` (`plugin.CLIInstalled`, `plugin.InstallCLI`), the install +through the sign-in's proxy and given up with it. `pluginCLI` in +[`pluginsignin.go`](../../internal/provider/pluginsignin.go) asks the +plugin (`ownCLI`), so the sign-in installs it first as a moved +built-in's does (`installCLI`, at most 10 minutes), and so does +`magpie plugin login` (`PluginCLIMissing`, `InstallPluginCLI`). A plugin +that can't be asked counts the CLI as there, and its authorize says what +is missing, as before. Where the CLI goes and how it is kept current is +the plugin's. Tests: `TestPluginInstallsItsCLI`, +`TestPluginSignInInstallsItsCLI`. diff --git a/internal/cli/plugins_cli.go b/internal/cli/plugins_cli.go index 6f29aaf10..1594af18a 100644 --- a/internal/cli/plugins_cli.go +++ b/internal/cli/plugins_cli.go @@ -604,7 +604,8 @@ func pluginLogin(ctx context.Context, name, method string) error { // window's sign-in installs it (#2223: Grok Build in Docker) if name := pluginSignInCLI.missing(pp.ID); name != "" { fmt.Println(amber.Render("!"), name, "isn't installed here: "+pp.Name+" signs in through it. Installing it, as its vendor's installer does…") - if err := pluginSignInCLI.install(ctx, pp.ID); err != nil { + // through the proxy the sign-in and the provider's requests take + if err := pluginSignInCLI.install(provider.Via(ctx, provider.PluginID(pp.ID)), pp.ID); err != nil { return err } fmt.Println(green.Render("✓"), name, "installed") diff --git a/internal/plugin/cli_install_test.go b/internal/plugin/cli_install_test.go new file mode 100644 index 000000000..cfc168d25 --- /dev/null +++ b/internal/plugin/cli_install_test.go @@ -0,0 +1,97 @@ +package plugin + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// A plugin that runs its vendor's CLI says how to install it (auth.cli): +// it is listed with the CLI's name and manual, magpie asks whether it is +// there and has the plugin install it, and gives up an install it no +// longer waits for (niuniu_8964 on X: agy in magpie's container). +func TestPluginInstallsItsCLI(t *testing.T) { + sandbox(t) + home := os.Getenv("HOME") + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + for _, name := range []string{"cliinstall", "importer"} { + abs, _ := filepath.Abs("testdata/" + name) + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + } + ps, err := Providers(ctx) + if err != nil { + t.Fatal(err) + } + var cli, other *Provider + for i := range ps { + switch ps[i].ID { + case "cliinstall": + cli = &ps[i] + case "importer": + other = &ps[i] + } + } + if cli == nil || other == nil { + t.Fatalf("providers = %+v", ps) + } + if cli.CLI == nil || cli.CLI.Name != "Fake CLI" || cli.CLI.Manual != "curl -fsSL https://fake.invalid/install.sh | bash" { + t.Fatalf("cliinstall's CLI = %+v", cli.CLI) + } + if other.CLI != nil { + t.Errorf("a plugin with no auth.cli names one: %+v", other.CLI) + } + if _, err := CLIInstalled(ctx, "importer"); err == nil { + t.Error("a plugin with no auth.cli answered whether its CLI is installed") + } + + if in, err := CLIInstalled(ctx, "cliinstall"); err != nil || in { + t.Fatalf("before the install: %v, %v", in, err) + } + os.WriteFile(filepath.Join(home, "cli-mode"), []byte("fail"), 0o600) + if err := InstallCLI(ctx, "cliinstall"); err == nil || !strings.Contains(err.Error(), "the download was refused") { + t.Fatalf("a failing install = %v", err) + } + + // given up, the plugin's install hears of it and the call returns + os.WriteFile(filepath.Join(home, "cli-mode"), []byte("hang"), 0o600) + hctx, hcancel := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { done <- InstallCLI(hctx, "cliinstall") }() + time.Sleep(200 * time.Millisecond) + hcancel() + select { + case err := <-done: + if err == nil { + t.Fatal("a cancelled install returned no error") + } + case <-ctx.Done(): + t.Fatal("a cancelled install never returned") + } + for range 200 { + if _, err := os.Stat(filepath.Join(home, "cli-aborted")); err == nil { + break + } + time.Sleep(20 * time.Millisecond) + } + if _, err := os.Stat(filepath.Join(home, "cli-aborted")); err != nil { + t.Error("the plugin's install never heard it was given up") + } + + os.Remove(filepath.Join(home, "cli-mode")) + if err := InstallCLI(ctx, "cliinstall"); err != nil { + t.Fatal(err) + } + if in, err := CLIInstalled(ctx, "cliinstall"); err != nil || !in { + t.Fatalf("after the install: %v, %v", in, err) + } + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + t.Fatal("ran out of time") + } +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index adb8bc6ee..d4549b8be 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2623,6 +2623,9 @@ function rowOf(id, a, keys, stored, p, own) { // its accounts can be brought in from a file (auth.import), and which // file that is, as the plugin says it ...importOf(a.auth), + // the vendor CLI its sign-in and requests run through, which magpie + // installs with the plugin's own installer when it isn't there + ...cliOf(a.auth), icon: iconOf(a), usage: typeof a.auth.usage === "function", checkin: typeof a.auth.checkin === "function", @@ -2891,6 +2894,46 @@ function importOf(auth) { return { importable: true, ...(from ? { importFrom: from } : {}), ...(froms ? { importFroms: froms } : {}) } } +// ---- the vendor CLI a plugin runs through ------------------------------------ + +// A plugin that runs its vendor's CLI may say how to install it (magpie's +// own hook, which OpenCode ignores), so a machine without it, magpie in a +// container above all, gets it from magpie's sign-in rather than a shell: +// auth.cli.name: the CLI, as the sign-in names it ("Installing {name}…"). +// auth.cli.installed(): whether it is on this machine now. +// auth.cli.install({ signal }): installs it, resolving once it is there; +// magpie's sign-in starts this when installed() is false, then asks +// the method's authorize. +// auth.cli.manual: how a person installs it, told when install fails. +function cliOf(auth) { + const c = auth?.cli + if (!c || typeof c !== "object" || typeof c.installed !== "function" || typeof c.install !== "function") return {} + const name = shown(c.name, 80) + if (!name) return {} + const manual = shown(c.manual, 300) + return { cli: { name, ...(manual ? { manual } : {}) } } +} + +function cliHook(provider) { + const c = authOf(provider).cli + if (!cliOf({ cli: c }).cli) throw new Error(`${provider} names no CLI to install`) + return c +} + +async function cliInstalled({ provider }) { + return { installed: (await cliHook(provider).installed()) === true } +} + +// installCli runs the plugin's installer through the proxy the +// subscription's requests take (#1663), ended when magpie gives it up +async function installCli({ provider, proxy }, signal) { + const c = cliHook(provider) + const step = via.run(proxy ?? "", () => c.install({ signal })) + await (signal ? bounded(Promise.resolve(step), signal) : step) + if (signal?.aborted) throw new DOMException("the install was cancelled", "AbortError") + return null +} + async function importFiles({ provider, texts, proxy }, signal) { const a = authOf(provider) if (typeof a.import !== "function") throw new Error(`${provider} takes no accounts from a file`) @@ -3610,6 +3653,8 @@ const handlers = { search: runSearch, apiKey, importFiles, + cliInstalled, + installCli, load, usage, checkin, diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index dd75c00ef..8c0123009 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -211,6 +211,11 @@ type Provider struct { Importable bool `json:"importable,omitempty"` ImportFrom string `json:"importFrom,omitempty"` ImportFroms map[string]string `json:"importFroms,omitempty"` + // CLI is the vendor CLI the plugin runs through and can install itself + // (auth.cli, magpie's own hook): a sign-in on a machine without it, + // magpie in a container above all, installs it first (CLIInstalled, + // InstallCLI). nil for a plugin that names none. + CLI *CLI `json:"cli,omitempty"` // MaxConcurrency is how many requests the plugin says each of its // accounts takes at once (magpie's own field, which OpenCode ignores: // the auth hook's maxConcurrency, else package.json's @@ -1104,6 +1109,32 @@ func ImportFiles(ctx context.Context, provider string, texts []string) ([]Import return r.Results, nil } +// CLI is a vendor CLI a plugin can install: its name, and how a person +// installs it, told when the plugin's install fails ("" for none said). +type CLI struct { + Name string `json:"name"` + Manual string `json:"manual,omitempty"` +} + +// CLIInstalled asks the plugin whether the CLI its Provider.CLI names is +// on this machine. +func CLIInstalled(ctx context.Context, provider string) (bool, error) { + var r struct { + Installed bool `json:"installed"` + } + if err := Call(ctx, "cliInstalled", map[string]any{"provider": provider}, &r); err != nil { + return false, err + } + return r.Installed, nil +} + +// InstallCLI has the plugin install the CLI its Provider.CLI names, +// through the proxy ctx carries; it returns once the plugin says it is +// there, or why not. +func InstallCLI(ctx context.Context, provider string) error { + return Call(ctx, "installCli", map[string]any{"provider": provider, "proxy": proxyOf(ctx)}, nil) +} + // SignOut forgets one account of the provider's, every one when account // is "". func SignOut(ctx context.Context, provider, account string) error { diff --git a/internal/plugin/testdata/cliinstall/index.js b/internal/plugin/testdata/cliinstall/index.js new file mode 100644 index 000000000..03b8d8cc5 --- /dev/null +++ b/internal/plugin/testdata/cliinstall/index.js @@ -0,0 +1,40 @@ +// A plugin that runs its vendor's CLI and installs it itself (magpie's +// auth.cli): the "CLI" is a file in HOME. HOME/cli-mode says how the +// install goes: "fail" throws, "hang" waits until magpie gives it up +// (and writes HOME/cli-aborted then), anything else installs it. +import { existsSync, readFileSync, writeFileSync } from "node:fs" +import { homedir } from "node:os" +import { join } from "node:path" + +const home = () => process.env.HOME || process.env.USERPROFILE || homedir() +const bin = () => join(home(), "fake-cli") +const mode = () => { try { return readFileSync(join(home(), "cli-mode"), "utf8").trim() } catch { return "" } } + +export const CLIInstallPlugin = async () => ({ + auth: { + provider: "cliinstall", + cli: { + name: "Fake CLI", + manual: "curl -fsSL https://fake.invalid/install.sh | bash", + installed: async () => existsSync(bin()), + install: async ({ signal } = {}) => { + const m = mode() + if (m === "fail") throw new Error("the download was refused") + if (m === "hang") { + await new Promise((resolve) => signal?.addEventListener("abort", () => { + writeFileSync(join(home(), "cli-aborted"), "1") + resolve() + })) + throw new Error("aborted") + } + writeFileSync(bin(), "#!/bin/sh\n") + }, + }, + methods: [{ + type: "oauth", label: "Browser", + authorize: async () => existsSync(bin()) + ? { url: "https://cliinstall.invalid/login", method: "code", instructions: "Paste the code", callback: async () => ({ type: "failed" }) } + : { url: "", method: "code", callback: async () => ({ type: "failed", error: "Fake CLI not found" }) }, + }], + }, +}) diff --git a/internal/provider/install.go b/internal/provider/install.go index 4a0860654..1b099c24a 100644 --- a/internal/provider/install.go +++ b/internal/provider/install.go @@ -220,8 +220,14 @@ func installCLI(ctx context.Context, c agentCLI) error { if msg == "" { msg = err.Error() } + if manual == "" { + return errorf("installing %s failed (%s); install it yourself, then sign in again", c.Name, msg) + } return errorf("installing %s failed (%s); install it yourself with `%s`, then sign in again", c.Name, msg, manual) } + if manual == "" { + return errorf("the %s installer finished, but magpie can't find it; install it yourself, then sign in again", c.Name) + } return errorf("the %s installer finished, but magpie can't find it; install it yourself with `%s`, then sign in again", c.Name, manual) } diff --git a/internal/provider/pluginsignin.go b/internal/provider/pluginsignin.go index d50128dfb..ccf162c98 100644 --- a/internal/provider/pluginsignin.go +++ b/internal/provider/pluginsignin.go @@ -39,7 +39,9 @@ func StartPluginSignInWith(id string, method int, inputs map[string]string, o Si var installing context.Context if install { s.st.State, s.st.Installing = "installing", cli.Name - installing, s.stop = context.WithCancel(context.Background()) + // through the proxy the sign-in takes: a plugin's own installer + // downloads with the plugin's fetch (plugin.InstallCLI) + installing, s.stop = context.WithCancel(s.via(context.Background())) } else if err := s.pluginBegin(id, method, inputs); err != nil { return SignInState{}, err } @@ -75,8 +77,10 @@ func StartPluginSignInWith(id string, method int, inputs map[string]string, o Si var pluginRunsCLI = map[string]bool{"grok": true} // pluginCLI is the vendor CLI a plugin's sign-in (OpenCode's id) runs -// through and this machine lacks: a moved built-in's, or one in -// pluginRunsCLI. +// through and this machine lacks: a moved built-in's, one in +// pluginRunsCLI, or one the plugin says it installs itself (auth.cli, +// plugin.CLI). The last is how agy-cli has agy installed in a container, +// as Claude's sign-in downloads Claude Code there (niuniu_8964 on X). func pluginCLI(id string) (agentCLI, bool) { if PluginServes(PluginID(id)) { return missingCLI(PluginID(id)) @@ -84,9 +88,35 @@ func pluginCLI(id string) (agentCLI, bool) { if pluginRunsCLI[id] { return missingCLI(id) } + if pp, ok := PluginOf(PluginID(id)); ok && pp.CLI != nil { + c := ownCLI(id, *pp.CLI) + if c.find() == "" { + return c, true + } + } return agentCLI{}, false } +// ownCLI is the CLI a plugin installs itself, as an agentCLI: found when +// the plugin says it is installed, installed by the plugin. A plugin that +// can't be asked counts it as there: its authorize says what is missing, +// as it did before it could install anything. +func ownCLI(id string, c plugin.CLI) agentCLI { + return agentCLI{ + Name: c.Name, + find: func() string { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if in, err := plugin.CLIInstalled(ctx, id); err == nil && !in { + return "" + } + return c.Name + }, + native: func(ctx context.Context) error { return plugin.InstallCLI(ctx, id) }, + manual: c.Manual, + } +} + // PluginCLIMissing is the name of the vendor CLI a plugin's sign-in runs // through and this machine lacks (Grok Build for Grok's), "" when there is // none to install. The command line's sign-in installs it first, as diff --git a/internal/provider/pluginsignin_cli_test.go b/internal/provider/pluginsignin_cli_test.go new file mode 100644 index 000000000..5c4060dcb --- /dev/null +++ b/internal/provider/pluginsignin_cli_test.go @@ -0,0 +1,79 @@ +package provider + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/testenv" +) + +// A plugin whose vendor CLI isn't on this machine had its sign-in fail +// with "install it first", which a magpie in a container can't do +// (niuniu_8964 on X: agy-cli in Docker). A plugin that says how to install +// it (auth.cli) has its sign-in install it first, "Installing {name}…" as +// a moved built-in's, then open the page; one whose install fails says +// why and how to do it by hand; with the CLI there, nothing is installed. +func TestPluginSignInInstallsItsCLI(t *testing.T) { + bun := testenv.Bun(t) + home := claudeHome(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/cliinstall/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + settled := func(id string) SignInState { + t.Helper() + for range 500 { + if st, _ := SignInStatus(id); st.State != "installing" { + return st + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("the sign-in is still installing") + return SignInState{} + } + + if got := PluginCLIMissing("cliinstall"); got != "Fake CLI" { + t.Fatalf("PluginCLIMissing = %q", got) + } + os.WriteFile(filepath.Join(home, "cli-mode"), []byte("fail"), 0o600) + st, err := StartPluginSignIn("cliinstall", 0, nil) + if err != nil || st.State != "installing" || st.Installing != "Fake CLI" { + t.Fatalf("StartPluginSignIn = %+v, %v", st, err) + } + if got := settled(st.ID); got.State != "failed" || !strings.Contains(got.Error, "the download was refused") || !strings.Contains(got.Error, "fake.invalid/install.sh") { + t.Fatalf("a failed install: %+v", got) + } + + os.Remove(filepath.Join(home, "cli-mode")) + st, err = StartPluginSignIn("cliinstall", 0, nil) + if err != nil || st.State != "installing" { + t.Fatalf("StartPluginSignIn = %+v, %v", st, err) + } + if got := settled(st.ID); got.State != "waiting" || got.URL != "https://cliinstall.invalid/login" { + t.Fatalf("after the install: %+v", got) + } + if _, err := os.Stat(filepath.Join(home, "fake-cli")); err != nil { + t.Fatal("the plugin's CLI wasn't installed") + } + + if got := PluginCLIMissing("cliinstall"); got != "" { + t.Fatalf("installed, PluginCLIMissing = %q", got) + } + st, err = StartPluginSignIn("cliinstall", 0, nil) + if err != nil || st.State != "waiting" || st.URL != "https://cliinstall.invalid/login" { + t.Fatalf("with the CLI there: %+v, %v", st, err) + } + CancelSignIn(st.ID) +}