Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

agent: plain agy starts Antigravity CLI on magpie in a new terminal

yetone9ae7912210fd
diff --git a/docs/reference.md b/docs/reference.md
index 8722a6950..8ba64f81c 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -2327,6 +2327,17 @@ the API key goes to `~/.gemini/.env`. Picking a catalog model points
`auth` to API key with the gateway token, and names the model in
`settings.json`; a native model puts the previous auth back.
+**Antigravity CLI** (`agy`) takes the gateway, its key and the model only
+from how it is started. Picking a catalog model (`magpie agy <model>`)
+puts a function named `agy` in a marked block (`# >>> magpie agy >>>`) of
+your shell profiles: `.zshrc`, the bash profile a terminal reads, and
+`config.fish` (the PowerShell profiles on Windows). In a new terminal,
+plain `agy` then runs `magpie agy run`, which starts the real agy with the
+gateway, the key and `--model` (yours wins when you give one); off magpie
+it starts agy untouched. A terminal open already takes the command the
+Launch row copies. Stepping out (`magpie agy default`) takes the block out
+again. `magpie agy env` prints what `agy run` adds.
+
### Import links
A vendor or relay can hand its users a ready-made provider as a link:
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 72aa12502..dea71ac61 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -26,7 +26,7 @@ something else shows up as drift.
| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-<agent>` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) |
| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`; Codex's top-level `model_auto_compact_token_limit`. The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated extra tokens over the fewest and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`, carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) |
-| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`cursorLocalEfforts`, #1003). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
+| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`cursorLocalEfforts`, #1003). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer), each minute while magpie serves; it never stops one running. `Check` reads the daemon's `operon.lock`, not `status` (seconds for a 130 MB Bun program), and calls a daemon with another pid drift: the app's window, opened while none ran, starts its own without the variable. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) |
## Runtime path
@@ -40,6 +40,7 @@ something else shows up as drift.
## Constraints and failure behavior
- magpie only removes what it wrote. Anything else in an agent's config stays as it was.
+- agy's shell function (`update.ShellFunction`, [`shellfn.go`](../../internal/update/shellfn.go)) sits between `# >>> magpie agy >>>` and `# <<< magpie agy <<<`, the only lines magpie writes or takes out of a profile. The profiles are those `cliProfile` names (zsh's in `ZDOTDIR` when set, bash's, fish's `config.fish`), plus PowerShell 7's and Windows PowerShell's on Windows when their execution policy runs a profile. A missing profile is made only for the shell a terminal opens. Only a file inside the home is written, writes go through temp-and-rename, and a profile that can't be read is left alone. Picking one of magpie's models and every `Sync` on one put it there, which covers users wired before it existed. Stepping out and a `Sync` off magpie take it out. agy in WSL gets none. A user's own `alias agy` still wins over it. A terminal opened before the change still needs the `Launch` command.
- A sync brings magpie's models up to date, not where the agent reaches magpie. Every `Sync` that `SyncCatalog` runs (each start and update of magpie, a provider added, and a plugin signed in to, out of or renewed, or listing other models than the last time: `plugin.OnChange` and `plugin.OnListed` call `catalog.Touched`, #2373) goes through `synced`, which passes each file written through `kept.away` (`edit.Filtered`, [`keptaway.go`](../../internal/agent/keptaway.go)). The filter sees every file written through `edit` while it is on, from any goroutine and under whatever lock the writer holds, so it takes none a writer may hold: the gateway's address and the LAN key are read before it is on (`keeping`), and magpie's own files (`magpieFile`: its folder as named or where its links lead, such as a `~/.config` linked into a dotfiles repo) are left as they are (ylorn on Discord: `settings.Save` under the settings' lock reached a filter that read the settings, and the app hung ~10s after every start; `TestOwnWritesDuringASyncWithALinkedConfig`). In a file without the gateway's own address, whose magpie the user pointed at an address on another machine (a NAS's, or this machine's LAN address), and with no address a WSL distro was seen at, that address stays in place of `gateway.URL()`, with the path before magpie's every URL at it had (`awayPath`: a reverse proxy's `/magpie`; on loopback, a local proxy's route where magpie answered or hasn't been asked), and so does the key that went with it in place of magpie's own (coeo91 on Discord: the base URL went back to 127.0.0.1 after an update or restart). An address on this machine's loopback follows the gateway; with more than one address or key gone, the write is left as it is. Picking a model in magpie still points the agent at this magpie, but for Claude Code at a proxy to it (above). ZCode and WorkBuddy keep such an address in their own writers too (`zcodeAddress`, `buddyWriteAt`).
- `SyncCatalog` holds the catalog it builds (`provider.Hold`), the plugins' providers and sign-ins among it, for up to a second. Those `catalog.Touched` drops are told in the background, so a plugin change also drops what is held at once (`plugin.OnChangeNow`, [`hold.go`](../../internal/provider/hold.go)): the host's "auth" event is read before its reply to the sign-in that saved it, and a look at the accounts once the sign-in returns sees it (#2449: `magpie plugin login` found no account while a sync ran; `TestHeldGoesWithAPluginChange`).
- JetBrains Air's `magpie-opencode.json` keeps user-added fields in `provider.magpie`, including nested options, on sync and model picks (`air` in [`air.go`](../../internal/agent/air.go), using `theirsKept` in [`sync.go`](../../internal/agent/sync.go)). The gateway fields and complete model list are still replaced, so removed models leave the list.
@@ -129,6 +130,8 @@ something else shows up as drift.
```sh
go test -tags nogui ./internal/agent -run '^TestStepCode'
+go test -tags nogui ./internal/agent ./internal/update ./internal/cli -run 'TestAgy|TestShellFunction|TestWithFnBlock|TestShellProfiles'
+node --test internal/gui/tests/agy-launch.test.cjs
go test -tags nogui ./internal/agent -run '^TestMothX'
go test -tags nogui ./internal/agent -run '^TestPenguin'
go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestClaudeReviewedOnlyWhereMessagesReachClaude|TestT3CodeAutoModeReview|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress'
diff --git a/internal/agent/agent.go b/internal/agent/agent.go
index 37f464503..fc3178149 100644
--- a/internal/agent/agent.go
+++ b/internal/agent/agent.go
@@ -249,6 +249,10 @@ type Agent struct {
// environment (agy), is the command that starts it on magpie, while
// it is on one of magpie's models; "" otherwise.
Launch func() string
+ // Typed, for such an agent, is what the user types in a new terminal
+ // to start it on magpie, a function magpie gave their shells (agy);
+ // "" when there is none, and Launch is the way.
+ Typed func() string
// SplitSuffix, for an agent whose model values carry something of its
// own after the model that varies from value to value (omp's thinking
// level, "…:max"), splits a value into the model the picker offers and
diff --git a/internal/agent/agy.go b/internal/agent/agy.go
index 9b127ef79..44c30480a 100644
--- a/internal/agent/agy.go
+++ b/internal/agent/agy.go
@@ -14,6 +14,17 @@ package agent
// names the model with --model too: agy 1.2 asks for a custom model picked
// in settings.json or its /model picker with no model name ("model is
// empty"); only one given on the command line resolves.
+//
+// So that typing agy just works (bestony on Discord: the command was
+// copied at each start), magpie puts a function named agy in the profile
+// of each shell the user has, between "# >>> magpie agy >>>" and
+// "# <<< magpie agy <<<" (update.ShellFunction), while agy is on one of
+// magpie's models. It runs `magpie agy run`, which starts the real agy
+// with the two variables and --model when settings.json's model is still
+// magpie's and as it is otherwise (cli/agy_cli.go); PowerShell's asks
+// `magpie agy env` for them, since the app it would run is a GUI program
+// PowerShell doesn't wait for. A terminal open before takes the command
+// from the row.
import (
"encoding/json"
@@ -27,6 +38,7 @@ import (
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/update"
)
const agyModels = "customModelsConfig.customModels"
@@ -45,6 +57,69 @@ func AgyLaunch(model string) string {
return "GEMINI_API_KEY=" + key + " GOOGLE_GEMINI_BASE_URL=" + gateway.URL() + " agy --model '" + strings.ReplaceAll(model, "'", `'\''`) + "'"
}
+// AgyStart is what starts agy on magpie, the variables and the model,
+// while settings.json's model is one of magpie's; nil and "" otherwise,
+// when agy starts as it is.
+func AgyStart() (env []string, model string) {
+ home, _ := homes()
+ m := jsonGet(filepath.Join(home, ".gemini", "antigravity-cli", "settings.json"), "model")()
+ if !usesMagpie(m) {
+ return nil, ""
+ }
+ return []string{"GEMINI_API_KEY=" + agentKey("agy"), "GOOGLE_GEMINI_BASE_URL=" + gateway.URL()}, m
+}
+
+// agyShell gives the user's shells the function agy, or takes it out of
+// them; only for agy on this machine. What fails leaves the setting as it
+// is: the row's command still starts it.
+func agyShell(home string, on bool) {
+ if here, _ := homes(); here != home {
+ return
+ }
+ if on {
+ update.ShellFunction("agy", agyFunction)
+ } else {
+ update.DropShellFunction("agy")
+ }
+}
+
+// agyTyped is "agy" while a shell's profile has magpie's function for it.
+func agyTyped() string {
+ if len(update.ShellFunctionIn("agy")) > 0 {
+ return "agy"
+ }
+ return ""
+}
+
+// agyFunction is the function agy in a shell of kind, which runs prog
+// (this magpie) to start it; the agy on PATH when prog is gone.
+func agyFunction(kind, prog string) string {
+ switch kind {
+ case "fish":
+ q := "'" + strings.NewReplacer(`\`, `\\`, "'", `\'`).Replace(prog) + "'"
+ return "function agy\n if test -x " + q + "\n " + q + " agy run $argv\n else\n command agy $argv\n end\nend"
+ case "powershell":
+ q := "'" + strings.ReplaceAll(prog, "'", "''") + "'"
+ return `function agy {
+ $real = Get-Command agy -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
+ if (-not $real) { Write-Error 'agy is not installed'; return }
+ $start = @{}
+ if (Test-Path -LiteralPath ` + q + `) {
+ foreach ($l in @(& ` + q + ` agy env)) { $k, $v = "$l" -split '=', 2; if ($v) { $start[$k] = $v } }
+ }
+ if (-not $start.model) { & $real @args; return }
+ $was = $env:GEMINI_API_KEY, $env:GOOGLE_GEMINI_BASE_URL
+ $env:GEMINI_API_KEY = $start.GEMINI_API_KEY; $env:GOOGLE_GEMINI_BASE_URL = $start.GOOGLE_GEMINI_BASE_URL
+ try {
+ if (@($args | Where-Object { "$_" -match '^--?model(=|$)' }).Count) { & $real @args } else { & $real --model $start.model @args }
+ } finally { $env:GEMINI_API_KEY = $was[0]; $env:GOOGLE_GEMINI_BASE_URL = $was[1] }
+}`
+ }
+ q := "'" + strings.ReplaceAll(prog, "'", `'\''`) + "'"
+ // "function": a name the user aliased isn't expanded where it is defined
+ return "function agy {\n if [ -x " + q + " ]; then " + q + ` agy run "$@"; else command agy "$@"; fi` + "\n}"
+}
+
// agyCustom reads customModels as it is, raw JSON by key.
func agyCustom(path string) map[string]json.RawMessage {
out := map[string]json.RawMessage{}
@@ -106,8 +181,16 @@ func agy(home string) *Agent {
}
return ""
},
- Sync: func() error {
+ Typed: func() string {
if !usesMagpie(get()) {
+ return ""
+ }
+ return agyTyped()
+ },
+ Sync: func() error {
+ on := usesMagpie(get())
+ agyShell(home, on)
+ if !on {
return nil
}
return setModels(true)
@@ -117,6 +200,12 @@ func agy(home string) *Agent {
if !usesMagpie(v) {
return ""
}
+ if in := update.ShellFunctionIn("agy"); len(in) > 0 {
+ for i := range in {
+ in[i] = update.TildeHome(in[i])
+ }
+ return noticeAgyTyped.say("profiles", strings.Join(in, ", "), "command", AgyLaunch(v))
+ }
return noticeAgy.say("command", AgyLaunch(v))
},
Check: func() string {
@@ -144,7 +233,11 @@ func agy(home string) *Agent {
if err := setModels(true); err != nil {
return err
}
- return edit.SetJSON(path, edit.KV{Path: "modelProvider", Value: "gemini"}, edit.KV{Path: "model", Value: v})
+ if err := edit.SetJSON(path, edit.KV{Path: "modelProvider", Value: "gemini"}, edit.KV{Path: "model", Value: v}); err != nil {
+ return err
+ }
+ agyShell(home, true)
+ return nil
}
if usesMagpie(cur) {
// back to what the user had
@@ -160,6 +253,9 @@ func agy(home string) *Agent {
if err := put("model", v); err != nil {
return err
}
+ if usesMagpie(cur) {
+ agyShell(home, false)
+ }
return setModels(false)
},
Options: func(cur map[string]string) []Option {
@@ -189,4 +285,7 @@ func agy(home string) *Agent {
}
// what agy says after a change (notice.go)
-var noticeAgy = newNotice("agy takes magpie's gateway and model only from how it is started — start it with {command}")
+var (
+ noticeAgy = newNotice("agy takes magpie's gateway and model only from how it is started — start it with {command}")
+ noticeAgyTyped = newNotice("Type agy in a new terminal: magpie added it to {profiles}, to start agy on magpie's gateway and model (in a terminal open now: {command}).")
+)
diff --git a/internal/agent/agy_shell_test.go b/internal/agent/agy_shell_test.go
new file mode 100644
index 000000000..8d5520bee
--- /dev/null
+++ b/internal/agent/agy_shell_test.go
@@ -0,0 +1,112 @@
+//go:build !windows
+
+package agent
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/update"
+)
+
+// Typing agy just works (bestony on Discord): picking one of magpie's
+// models for agy gives the user's shells a function agy that starts it
+// through magpie, the next start puts it back for a user wired before,
+// and stepping out takes it out, the user's own lines as they were.
+func TestAgyShell(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ t.Setenv("ZDOTDIR", "")
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
+ if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil {
+ t.Fatal(err)
+ }
+ mine := "alias ll='ls -l'\n"
+ rcs := []string{".zshrc", ".bashrc", ".bash_profile"}
+ for _, n := range rcs {
+ os.WriteFile(filepath.Join(home, n), []byte(mine), 0o644)
+ }
+ a, err := Find("agy")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if env, m := AgyStart(); env != nil || m != "" {
+ t.Fatalf("AgyStart before: %v %q", env, m)
+ }
+ if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
+ t.Fatal(err)
+ }
+ in := update.ShellFunctionIn("agy")
+ if len(in) == 0 {
+ t.Fatal("no shell's profile has agy")
+ }
+ for _, p := range in {
+ b, _ := os.ReadFile(p)
+ if s := string(b); !strings.HasPrefix(s, mine+"\n# >>> magpie agy >>>\nfunction agy {\n") || !strings.Contains(s, ` agy run "$@"; else command agy "$@"; fi`) || !strings.HasSuffix(s, "}\n# <<< magpie agy <<<\n") {
+ t.Fatalf("%s:\n%s", p, s)
+ }
+ }
+ if a.Typed() != "agy" {
+ t.Fatalf("typed: %q", a.Typed())
+ }
+ if n := a.Notice(); !strings.HasPrefix(n, "Type agy in a new terminal: magpie added it to ~/") || !strings.HasSuffix(n, "(in a terminal open now: "+a.Launch()+").") {
+ t.Fatalf("notice: %q", n)
+ }
+ env, m := AgyStart()
+ if m != "magpie/deepseek/pro" || strings.Join(env, " ") != "GEMINI_API_KEY="+gateway.TokenFor("agy")+" GOOGLE_GEMINI_BASE_URL="+gateway.URL() {
+ t.Fatalf("AgyStart: %v %q", env, m)
+ }
+
+ // wired before the function was given: the next start gives it
+ for _, p := range in {
+ os.WriteFile(p, []byte(mine), 0o644)
+ }
+ if a.Typed() != "" {
+ t.Fatal("typed with no function")
+ }
+ if err := a.Sync(); err != nil {
+ t.Fatal(err)
+ }
+ if got := update.ShellFunctionIn("agy"); strings.Join(got, ",") != strings.Join(in, ",") {
+ t.Fatalf("after Sync: %v, want %v", got, in)
+ }
+
+ // out: as the user had them
+ if err := a.Apply("model", ""); err != nil {
+ t.Fatal(err)
+ }
+ for _, n := range rcs {
+ if b, _ := os.ReadFile(filepath.Join(home, n)); string(b) != mine {
+ t.Fatalf("%s after stepping out:\n%s", n, b)
+ }
+ }
+ if a.Typed() != "" {
+ t.Fatal("typed after stepping out")
+ }
+ // and a start off magpie doesn't give it again
+ a.Sync()
+ if got := update.ShellFunctionIn("agy"); len(got) != 0 {
+ t.Fatalf("Sync off magpie: %v", got)
+ }
+}
+
+// The function in each shell runs this magpie's `agy run`, the agy on
+// PATH when magpie is gone, its path quoted for that shell.
+func TestAgyFunction(t *testing.T) {
+ prog := "/Users/o'neil/magpie"
+ for kind, want := range map[string]string{
+ "posix": `if [ -x '/Users/o'\''neil/magpie' ]; then '/Users/o'\''neil/magpie' agy run "$@"; else command agy "$@"; fi`,
+ "fish": `'/Users/o\'neil/magpie' agy run $argv`,
+ "powershell": `foreach ($l in @(& '/Users/o''neil/magpie' agy env))`,
+ } {
+ if got := agyFunction(kind, prog); !strings.Contains(got, want) {
+ t.Errorf("%s:\n%s\nwant it to have %s", kind, got, want)
+ }
+ }
+}
diff --git a/internal/cli/agy_cli.go b/internal/cli/agy_cli.go
new file mode 100644
index 000000000..abea2cd34
--- /dev/null
+++ b/internal/cli/agy_cli.go
@@ -0,0 +1,108 @@
+package cli
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+
+ "github.com/yetone/magpie/internal/agent"
+ "github.com/yetone/magpie/internal/proc"
+)
+
+// `magpie agy run [args…]` is what the function agy magpie puts in the
+// user's shells runs (agent/agy.go): the agy on PATH, given magpie's
+// gateway, key and model while settings.json's model is one of magpie's,
+// and as it is otherwise. Every argument is agy's, --help too. `magpie agy
+// env` prints those variables and the model, one NAME=value a line and
+// nothing off magpie, for PowerShell's function.
+
+const agyRunUsage = `magpie agy run [args…] start agy, on magpie while its model is one of magpie's
+
+The agy on your PATH starts with GEMINI_API_KEY, GOOGLE_GEMINI_BASE_URL and
+--model <its model> (not when you give --model yourself); every argument is
+agy's. Off magpie's models it starts as it is. The function agy magpie puts
+in your shell's profile runs this.
+
+magpie agy env the variables and model it starts agy with, a NAME=value
+ a line; nothing while agy isn't on magpie
+`
+
+// agyCmd is `magpie agy run|env …`; ok false for another form.
+func agyCmd(args []string) (ok bool, err error) {
+ if len(args) < 2 || args[0] != "agy" && args[0] != "antigravity-cli" {
+ return false, nil
+ }
+ switch args[1] {
+ case "run":
+ return true, agyRun(args[2:])
+ case "env":
+ if len(args) > 2 {
+ if slices.Contains([]string{"-h", "--help", "help"}, args[2]) {
+ fmt.Print(agyRunUsage)
+ return true, nil
+ }
+ return true, fmt.Errorf("magpie agy env takes nothing after it, not %q", args[2])
+ }
+ env, model := agent.AgyStart()
+ if model == "" {
+ return true, nil
+ }
+ for _, kv := range env {
+ fmt.Println(kv)
+ }
+ fmt.Println("model=" + model)
+ return true, nil
+ }
+ return false, nil
+}
+
+// agyExec starts the program bin as agy with args and env, in place of
+// magpie where the system can (agy_exec_*.go); tests set it.
+var agyExec = agyExecOS
+
+// agyLook is the agy on PATH; tests set it.
+var agyLook = func() (string, error) { return proc.Look("agy") }
+
+func agyRun(args []string) error {
+ bin, err := agyLook()
+ if err != nil {
+ return errors.New("agy isn't installed, or isn't on your PATH")
+ }
+ if self, err := os.Executable(); err == nil && sameProgram(self, bin) {
+ return errors.New("the agy on your PATH is magpie itself; install Antigravity CLI")
+ }
+ env := os.Environ()
+ start, model := agent.AgyStart()
+ if model != "" {
+ env = slices.DeleteFunc(env, func(kv string) bool {
+ k, _, _ := strings.Cut(kv, "=")
+ return strings.EqualFold(k, "GEMINI_API_KEY") || strings.EqualFold(k, "GOOGLE_GEMINI_BASE_URL")
+ })
+ env = append(env, start...)
+ if !slices.ContainsFunc(args, modelFlag) {
+ args = append([]string{"--model", model}, args...)
+ }
+ }
+ return agyExec(bin, args, env)
+}
+
+// modelFlag says a is agy's --model, which it takes as -model too.
+func modelFlag(a string) bool {
+ a, _, _ = strings.Cut(a, "=")
+ return a == "--model" || a == "-model"
+}
+
+func sameProgram(a, b string) bool {
+ if ra, err := filepath.EvalSymlinks(a); err == nil {
+ a = ra
+ }
+ if rb, err := filepath.EvalSymlinks(b); err == nil {
+ b = rb
+ }
+ sa, err1 := os.Stat(a)
+ sb, err2 := os.Stat(b)
+ return err1 == nil && err2 == nil && os.SameFile(sa, sb)
+}
diff --git a/internal/cli/agy_cli_test.go b/internal/cli/agy_cli_test.go
new file mode 100644
index 000000000..eb8051a06
--- /dev/null
+++ b/internal/cli/agy_cli_test.go
@@ -0,0 +1,90 @@
+package cli
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/gateway"
+)
+
+// `magpie agy run`, what the function agy in the user's shells runs
+// (bestony on Discord): the agy on PATH, given magpie's gateway, key and
+// --model while settings.json's model is magpie's, every argument agy's;
+// as it is off magpie.
+func TestAgyRun(t *testing.T) {
+ home := helpHome(t)
+ settings := filepath.Join(home, ".gemini", "antigravity-cli", "settings.json")
+ os.MkdirAll(filepath.Dir(settings), 0o755)
+ t.Setenv("GEMINI_API_KEY", "users-own")
+ t.Setenv("GOOGLE_GEMINI_BASE_URL", "")
+ var bin string
+ var args, env []string
+ oldExec, oldLook := agyExec, agyLook
+ t.Cleanup(func() { agyExec, agyLook = oldExec, oldLook })
+ agyExec = func(b string, a, e []string) error {
+ bin, args, env = b, a, e
+ return nil
+ }
+ real := filepath.Join(home, "bin", "agy")
+ agyLook = func() (string, error) { return real, nil }
+ envOf := func(k string) []string {
+ var out []string
+ for _, kv := range env {
+ if strings.HasPrefix(kv, k+"=") {
+ out = append(out, strings.TrimPrefix(kv, k+"="))
+ }
+ }
+ return out
+ }
+
+ os.WriteFile(settings, []byte(`{"model": "magpie/deepseek/pro", "modelProvider": "gemini"}`), 0o644)
+ for _, c := range []struct{ in, want []string }{
+ {nil, []string{"--model", "magpie/deepseek/pro"}},
+ {[]string{"--help"}, []string{"--model", "magpie/deepseek/pro", "--help"}},
+ {[]string{"-p", "hi", "--model", "mine"}, []string{"-p", "hi", "--model", "mine"}},
+ {[]string{"--model=mine"}, []string{"--model=mine"}},
+ {[]string{"-model", "mine"}, []string{"-model", "mine"}},
+ } {
+ if _, err := runOut(t, append([]string{"agy", "run"}, c.in...)...); err != nil {
+ t.Fatal(err)
+ }
+ if bin != real || !slices.Equal(args, c.want) {
+ t.Fatalf("agy run %v: %s %v, want %v", c.in, bin, args, c.want)
+ }
+ if k, u := envOf("GEMINI_API_KEY"), envOf("GOOGLE_GEMINI_BASE_URL"); !slices.Equal(k, []string{gateway.TokenFor("agy")}) || !slices.Equal(u, []string{gateway.URL()}) {
+ t.Fatalf("env: key %v, url %v", k, u)
+ }
+ }
+ out, err := runOut(t, "agy", "env")
+ if want := "GEMINI_API_KEY=" + gateway.TokenFor("agy") + "\nGOOGLE_GEMINI_BASE_URL=" + gateway.URL() + "\nmodel=magpie/deepseek/pro\n"; err != nil || out != want {
+ t.Fatalf("agy env: %q %v", out, err)
+ }
+
+ // off magpie: as it is
+ os.WriteFile(settings, []byte(`{"model": "mine"}`), 0o644)
+ if _, err := runOut(t, "agy", "run", "-p", "hi"); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(args, []string{"-p", "hi"}) || !slices.Equal(envOf("GEMINI_API_KEY"), []string{"users-own"}) {
+ t.Fatalf("off magpie: %v %v", args, envOf("GEMINI_API_KEY"))
+ }
+ if out, err := runOut(t, "agy", "env"); err != nil || out != "" {
+ t.Fatalf("agy env off magpie: %q %v", out, err)
+ }
+
+ // what --help and a stray value say
+ if out, _ := runOut(t, "agy", "--help"); !strings.Contains(out, "magpie agy run [args…]") {
+ t.Fatalf("agy --help:\n%s", out)
+ }
+ if _, err := runOut(t, "agy", "env", "x"); err == nil {
+ t.Fatal("agy env x: no error")
+ }
+ agyLook = func() (string, error) { return "", errors.New("not found") }
+ if _, err := runOut(t, "agy", "run"); err == nil || !strings.Contains(err.Error(), "isn't installed") {
+ t.Fatalf("no agy: %v", err)
+ }
+}
diff --git a/internal/cli/agy_exec_unix.go b/internal/cli/agy_exec_unix.go
new file mode 100644
index 000000000..1ff4a4775
--- /dev/null
+++ b/internal/cli/agy_exec_unix.go
@@ -0,0 +1,11 @@
+//go:build !windows
+
+package cli
+
+import "syscall"
+
+// agyExecOS runs agy in magpie's place: the terminal's signals and exit
+// code are agy's own.
+func agyExecOS(bin string, args, env []string) error {
+ return syscall.Exec(bin, append([]string{"agy"}, args...), env)
+}
diff --git a/internal/cli/agy_exec_windows.go b/internal/cli/agy_exec_windows.go
new file mode 100644
index 000000000..94757d92c
--- /dev/null
+++ b/internal/cli/agy_exec_windows.go
@@ -0,0 +1,25 @@
+package cli
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+ "os/signal"
+
+ "github.com/yetone/magpie/internal/proc"
+)
+
+// agyExecOS starts agy and waits for it, its exit code magpie's: Windows
+// has no exec. Ctrl+C is agy's to handle, so magpie lets it pass.
+func agyExecOS(bin string, args, env []string) error {
+ cmd := proc.Command(bin, args...)
+ cmd.Env = env
+ cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
+ signal.Ignore(os.Interrupt)
+ err := cmd.Run()
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ return exitError{code: ee.ExitCode()}
+ }
+ return err
+}
diff --git a/internal/cli/help_cli.go b/internal/cli/help_cli.go
index e0e665d73..abad1f447 100644
--- a/internal/cli/help_cli.go
+++ b/internal/cli/help_cli.go
@@ -127,6 +127,10 @@ func agentHelp(a *agent.Agent) string {
fmt.Fprintf(&b, " magpie %s <field> <value> set another field\n", id)
fmt.Fprintf(&b, " magpie %s default take magpie out: back on what it had before\n", id)
fmt.Fprintf(&b, " magpie %s <field> default that field back to its own default\n", id)
+ if a.ID == "agy" {
+ fmt.Fprintf(&b, " magpie %s run [args…] start agy, on magpie while its model is magpie's (what your shell's agy runs)\n", id)
+ fmt.Fprintf(&b, " magpie %s env the variables and model it is started with\n", id)
+ }
var keys []string
for _, f := range a.Fields {
keys = append(keys, f.Key)
diff --git a/internal/cli/main.go b/internal/cli/main.go
index 0df9d0c04..6f969a6d2 100644
--- a/internal/cli/main.go
+++ b/internal/cli/main.go
@@ -265,6 +265,11 @@ func run(args []string) error {
agent.SyncCatalogSettled()
catalog.Changed = was
}()
+ // what a shell's agy runs (agy_cli.go): every argument after run is
+ // agy's, --help too, and nothing is moved or started first
+ if ok, err := agyCmd(args); ok {
+ return err
+ }
// before anything is read, moved or started: --help on any command
// prints its usage and does nothing else
if helpAsked(args) {
diff --git a/internal/gui/api.go b/internal/gui/api.go
index 230cbb1e1..365e9a31a 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -197,6 +197,9 @@ type agentJSON struct {
// Launch: the command that starts an agent taking the gateway only
// from its environment (agy) on magpie, to copy
Launch string `json:"launch,omitempty"`
+ // Typed: what starts it on magpie typed in a new terminal, a function
+ // magpie gave the user's shells (agy); the launch is for one open now
+ Typed string `json:"typed,omitempty"`
// Models: how many of the catalog its lists show, for an agent that
// picks among it (agent_models.go)
Models *modelCountJSON `json:"models,omitempty"`
@@ -2450,6 +2453,9 @@ func state() stateJSON {
if a.Launch != nil {
aj.Launch = a.Launch()
}
+ if a.Typed != nil && aj.Launch != "" {
+ aj.Typed = a.Typed()
+ }
aj.CLIMissing = a.CLIMissing()
if a.Native != nil {
native := a.Native.Read()
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index ef13d1abc..d66b1e84d 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -2082,7 +2082,12 @@ function connectPanel(a, { fields, fieldBtn }) {
const cp = el("button", "ag-quiet", t("Copy"));
cp.type = "button";
cp.onclick = () => copy(a.launch, t("Launch command"), null, t("Copied — run it to start {name} on magpie", { name: a.name }));
- kv(t("Start it with"), line(code(a.launch), cp));
+ // a function magpie gave the user's shells starts it (agy): typed in a
+ // new terminal; the command is for one open before
+ if (a.typed) {
+ kv(t("Start it with"), line(code(a.typed), el("span", "ag-hint", t("in a new terminal"))));
+ kv(t("In a terminal open now"), line(code(a.launch), cp));
+ } else kv(t("Start it with"), line(code(a.launch), cp));
}
// the files magpie changed, and the way back
const foot = el("div", "ag-foot");
@@ -3894,7 +3899,9 @@ function launchButton(a) {
const b = el("button", "field extra launch");
b.type = "button";
b.append(svg(LAUNCH_GLYPH, 13, 1.5));
- b.title = t("{name} takes magpie only from its environment · click to copy the command that starts it:", { name: a.name }) + "\n" + a.launch;
+ b.title = (a.typed
+ ? t("Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:", { command: a.typed, name: a.name })
+ : t("{name} takes magpie only from its environment · click to copy the command that starts it:", { name: a.name })) + "\n" + a.launch;
b.setAttribute("aria-label", b.title);
b.onclick = (ev) => {
ev.stopPropagation();
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index c16e8ee1b..571f79f64 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -2764,6 +2764,9 @@ const I18N = {
"Resume": "继续",
"Resume command": "继续会话的命令",
"{name} takes magpie only from its environment · click to copy the command that starts it:": "{name} 只能从环境变量接入 magpie · 点击复制启动它的命令:",
+ "in a new terminal": "在新打开的终端中",
+ "In a terminal open now": "已打开的终端",
+ "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "在新终端输入 {command} 即可让 {name} 走 magpie · 点击复制在已打开终端中用的命令:",
"Launch command": "启动命令",
"Copy launch command": "复制启动命令",
"Copied — run it to start {name} on magpie": "已复制,运行它即可让 {name} 走 magpie",
@@ -3825,6 +3828,7 @@ const I18N = {
"ZCode reads its providers at start-up — restart ZCode to see magpie's models in its picker.": "ZCode 启动时读取供应商,需重启 ZCode 才能在它的模型选择器中看到 magpie 的模型。",
"AstrBot reads cmd_config.json at start-up and writes it back whole when its WebUI saves settings — restart AstrBot to use this, before saving anything in its WebUI.": "AstrBot 启动时读取 cmd_config.json,并在其 WebUI 保存设置时整份写回——请重启 AstrBot 以使用此设置,且在此之前不要在其 WebUI 中保存任何内容。",
"agy takes magpie's gateway and model only from how it is started — start it with {command}": "agy 只从启动方式中获取 magpie 的网关和模型,请这样启动它:{command}",
+ "Type agy in a new terminal: magpie added it to {profiles}, to start agy on magpie's gateway and model (in a terminal open now: {command}).": "在新终端中直接输入 agy 即可:magpie 已把它加入 {profiles},会用 magpie 的网关和模型启动 agy(已打开的终端中请用:{command})。",
"dsh reads its config at start-up — restart open dsh sessions to use this.": "dsh 启动时读取配置,需重启已打开的 dsh 会话才会生效。",
"dsh's web search goes through magpie, which has nothing to search with yet: set up a provider that searches by itself (DeepSeek, Claude, Codex, …) or a search API under Settings › Web search.": "dsh 的联网搜索经过 magpie,而 magpie 目前还没有可用的搜索方式:请添加一个自带搜索的供应商(DeepSeek、Claude、Codex 等),或在“设置 › 联网搜索”中配置搜索 API。",
"fx reads its settings at start-up — restart open fx sessions to use this.": "fx 启动时读取设置,需重启已打开的 fx 会话才会生效。",
@@ -6746,6 +6750,9 @@ const I18N = {
"Resume": "繼續",
"Resume command": "繼續會話的命令",
"{name} takes magpie only from its environment · click to copy the command that starts it:": "{name} 只能從環境變數接入 magpie · 點選複製啟動它的命令:",
+ "in a new terminal": "在新開的終端機中",
+ "In a terminal open now": "已開啟的終端機",
+ "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "在新終端機輸入 {command} 即可讓 {name} 走 magpie · 點選複製在已開啟終端機中用的命令:",
"Launch command": "啟動命令",
"Copy launch command": "複製啟動命令",
"Copied — run it to start {name} on magpie": "已複製,執行它即可讓 {name} 走 magpie",
@@ -7809,6 +7816,7 @@ const I18N = {
"ZCode reads its providers at start-up — restart ZCode to see magpie's models in its picker.": "ZCode 啟動時讀取供應商,需重啟 ZCode 才能在它的模型選擇器中看到 magpie 的模型。",
"AstrBot reads cmd_config.json at start-up and writes it back whole when its WebUI saves settings — restart AstrBot to use this, before saving anything in its WebUI.": "AstrBot 啟動時讀取 cmd_config.json,並在其 WebUI 儲存設定時整份寫回——請重啟 AstrBot 以使用此設定,且在此之前不要在其 WebUI 中儲存任何內容。",
"agy takes magpie's gateway and model only from how it is started — start it with {command}": "agy 只從啟動方式中取得 magpie 的閘道和模型,請這樣啟動它:{command}",
+ "Type agy in a new terminal: magpie added it to {profiles}, to start agy on magpie's gateway and model (in a terminal open now: {command}).": "在新終端機中直接輸入 agy 即可:magpie 已把它加入 {profiles},會用 magpie 的閘道和模型啟動 agy(已開啟的終端機中請用:{command})。",
"dsh reads its config at start-up — restart open dsh sessions to use this.": "dsh 啟動時讀取設定,需重啟已打開的 dsh 會話才會生效。",
"dsh's web search goes through magpie, which has nothing to search with yet: set up a provider that searches by itself (DeepSeek, Claude, Codex, …) or a search API under Settings › Web search.": "dsh 的聯網搜尋經過 magpie,而 magpie 目前還沒有可用的搜尋方式:請新增一個自帶搜尋的供應商(DeepSeek、Claude、Codex 等),或在“設定 › 聯網搜尋”中設定搜尋 API。",
"fx reads its settings at start-up — restart open fx sessions to use this.": "fx 啟動時讀取設定,需重啟已打開的 fx 會話才會生效。",
@@ -10732,6 +10740,9 @@ const I18N = {
"Resume": "再開",
"Resume command": "再開コマンド",
"{name} takes magpie only from its environment · click to copy the command that starts it:": "{name} は環境変数からのみ magpie を使います · クリックで起動コマンドをコピー:",
+ "in a new terminal": "新しいターミナルで",
+ "In a terminal open now": "開いているターミナルでは",
+ "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "新しいターミナルで {command} と入力すると {name} が magpie 経由で起動します · クリックで開いているターミナル用のコマンドをコピー:",
"Launch command": "起動コマンド",
"Copy launch command": "起動コマンドをコピー",
"Copied — run it to start {name} on magpie": "コピーしました。実行すると {name} が magpie 経由で起動します",
@@ -11795,6 +11806,7 @@ const I18N = {
"ZCode reads its providers at start-up — restart ZCode to see magpie's models in its picker.": "ZCode は起動時にプロバイダを読み込みます。モデル選択に magpie のモデルを表示するには ZCode を再起動してください。",
"AstrBot reads cmd_config.json at start-up and writes it back whole when its WebUI saves settings — restart AstrBot to use this, before saving anything in its WebUI.": "AstrBot は起動時に cmd_config.json を読み込み、WebUI で設定を保存するとファイル全体を書き戻します。これを使うには、WebUI で何かを保存する前に AstrBot を再起動してください。",
"agy takes magpie's gateway and model only from how it is started — start it with {command}": "agy は magpie のゲートウェイとモデルを起動方法からしか受け取りません。次のように起動してください:{command}",
+ "Type agy in a new terminal: magpie added it to {profiles}, to start agy on magpie's gateway and model (in a terminal open now: {command}).": "新しいターミナルで agy と入力するだけです:magpie が {profiles} に追加し、magpie のゲートウェイとモデルで agy を起動します(開いているターミナルでは:{command})。",
"dsh reads its config at start-up — restart open dsh sessions to use this.": "dsh は起動時に設定を読み込みます。反映するには開いている dsh セッションを再起動してください。",
"dsh's web search goes through magpie, which has nothing to search with yet: set up a provider that searches by itself (DeepSeek, Claude, Codex, …) or a search API under Settings › Web search.": "dsh のウェブ検索は magpie を経由しますが、magpie にはまだ検索手段がありません。自前で検索するプロバイダ(DeepSeek、Claude、Codex など)を追加するか、「設定 › ウェブ検索」で検索 API を設定してください。",
"fx reads its settings at start-up — restart open fx sessions to use this.": "fx は起動時に設定を読み込みます。反映するには開いている fx セッションを再起動してください。",
@@ -14728,6 +14740,9 @@ const I18N = {
"Resume": "Fortsetzen",
"Resume command": "Befehl zum Fortsetzen",
"{name} takes magpie only from its environment · click to copy the command that starts it:": "{name} übernimmt magpie nur aus seiner Umgebung · klicken, um den Startbefehl zu kopieren:",
+ "in a new terminal": "in einem neuen Terminal",
+ "In a terminal open now": "In einem schon offenen Terminal",
+ "Type {command} in a new terminal to start {name} on magpie · click to copy the command for a terminal open now:": "In einem neuen Terminal startet {command} {name} über magpie · klicken, um den Befehl für ein schon offenes Terminal zu kopieren:",
"Launch command": "Startbefehl",
"Copy launch command": "Startbefehl kopieren",
"Copied — run it to start {name} on magpie": "Kopiert — ausführen, um {name} über magpie zu starten",
@@ -15781,6 +15796,7 @@ const I18N = {
"ZCode reads its providers at start-up — restart ZCode to see magpie's models in its picker.": "ZCode liest seine Anbieter beim Start – ZCode neu starten, um magpies Modelle in seiner Auswahl zu sehen.",
"AstrBot reads cmd_config.json at start-up and writes it back whole when its WebUI saves settings — restart AstrBot to use this, before saving anything in its WebUI.": "AstrBot liest cmd_config.json beim Start und schreibt sie ganz zurück, wenn seine WebUI Einstellungen speichert – AstrBot neu starten, um dies zu nutzen, bevor in seiner WebUI etwas gespeichert wird.",
"agy takes magpie's gateway and model only from how it is started — start it with {command}": "agy übernimmt magpies Gateway und Modell nur aus seinem Startbefehl – so starten: {command}",
+ "Type agy in a new terminal: magpie added it to {profiles}, to start agy on magpie's gateway and model (in a terminal open now: {command}).": "Tippe agy in einem neuen Terminal: magpie hat es zu {profiles} hinzugefügt und startet agy mit magpies Gateway und Modell (in einem schon offenen Terminal: {command}).",
"dsh reads its config at start-up — restart open dsh sessions to use this.": "dsh liest seine Konfiguration beim Start – offene dsh-Sitzungen neu starten, damit es gilt.",
"dsh's web search goes through magpie, which has nothing to search with yet: set up a provider that searches by itself (DeepSeek, Claude, Codex, …) or a search API under Settings › Web search.": "Die Websuche von dsh läuft über magpie, das noch nichts zum Suchen hat: einen Anbieter einrichten, der selbst sucht (DeepSeek, Claude, Codex, …), oder eine Such-API unter Einstellungen › Websuche.",
"fx reads its settings at start-up — restart open fx sessions to use this.": "fx liest seine Einstellungen beim Start – offene fx-Sitzungen neu starten, damit es gilt.",
@@ -16016,6 +16032,7 @@ const NOTICES = [
"WSL {distro} isn't running: magpie shows what it last saw there, and starts it only to change something.",
"ZCode reads its providers at start-up — restart ZCode to see magpie's models in its picker.",
"agy takes magpie's gateway and model only from how it is started — start it with {command}",
+ "Type agy in a new terminal: magpie added it to {profiles}, to start agy on magpie's gateway and model (in a terminal open now: {command}).",
"an open Claude Code session keeps the effort it started with — restart it to use this.",
"an open Claude Code session keeps the ultracode it started with — restart it to use this.",
"dsh reads its config at start-up — restart open dsh sessions to use this.",
diff --git a/internal/gui/tests/agy-launch.test.cjs b/internal/gui/tests/agy-launch.test.cjs
index 1bea44a12..14843c0de 100644
--- a/internal/gui/tests/agy-launch.test.cjs
+++ b/internal/gui/tests/agy-launch.test.cjs
@@ -4,7 +4,10 @@
// it on magpie, once it is connected (right before the model picker beside
// its switch, agy picking no model once started): the command in its tooltip, one click copying it (posted to /api/copy) and saying so, with the
// page left where it was; none on an agent without one; in the tray panel's
-// opened row too; the words in Chinese. No backend: the API is faked here.
+// opened row too; the words in Chinese. Once magpie has given the user's
+// shells a function agy (typed), the square and the opened row say plain
+// agy starts it in a new terminal, and the command is for one open now.
+// No backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
@@ -18,6 +21,7 @@ const agent = (id, name, launch) => ({
id, name, path: "/test/" + id, launch, wired: true, // on a magpie model (#726: a connected one is in view)
fields: [{ key: "model", label: "model", value: "magpie/deepseek/pro", options: models }],
});
+let typed = false;
const state = {
agents: [agent("claude", "Claude Code"), ...Array.from({ length: 4 }, (_, i) => agent("agent-" + i, "agent-" + i)),
agent("agy", "Antigravity CLI", LAUNCH), ...Array.from({ length: 8 }, (_, i) => agent("more-" + i, "more-" + i))],
@@ -29,7 +33,10 @@ function server(lang, copies) {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
- if (url.pathname === "/api/state") return route.fulfill({ json: { ...state, settings: { lang, theme: "light" } } });
+ if (url.pathname === "/api/state") {
+ const agents = state.agents.map((a) => (typed && a.id === "agy" ? { ...a, typed: "agy" } : a));
+ return route.fulfill({ json: { ...state, agents, settings: { lang, theme: "light" } } });
+ }
if (url.pathname === "/api/copy") { copies.push(req.postDataJSON().text); return route.fulfill({ json: {} }); }
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
@@ -116,6 +123,38 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.match(await page.locator("#status").textContent(), /已复制,运行它即可让 Antigravity CLI 走 magpie/);
});
+ await t.test("typed in a new terminal", async () => {
+ typed = true;
+ try {
+ for (const [lang, square, start, now] of [
+ ["en", /^Type agy in a new terminal to start Antigravity CLI on magpie · click to copy the command for a terminal open now:\n/, "Start it with", "In a terminal open now"],
+ ["zh", /^在新终端输入 agy 即可让 Antigravity CLI 走 magpie · 点击复制在已打开终端中用的命令:\n/, "启动命令", "已打开的终端"],
+ ]) {
+ const copies = [];
+ const page = await open("http://magpie.test/", lang, copies);
+ const b = page.locator(`${row("agy")} .field.launch`);
+ const title = await b.getAttribute("title");
+ assert.match(title, square);
+ assert(title.endsWith(LAUNCH), title);
+ await b.click();
+ await page.waitForTimeout(300);
+ assert.deepEqual(copies, [LAUNCH], "the square still copies the command, for a terminal open now");
+ // the opened row: agy, then the command
+ await page.locator(`${row("agy")} .ag-link`).click();
+ await page.locator(`${row("agy")} .ag-kv`).first().waitFor();
+ const kvs = await page.evaluate((r) => [...document.querySelectorAll(r + " .ag-kv")].map((k) => [k.querySelector(".ag-k").textContent, k.querySelector(".ag-v").textContent]), row("agy"));
+ const i = kvs.findIndex(([k]) => k === start);
+ assert(i >= 0, JSON.stringify(kvs));
+ assert.equal(kvs[i][1], "agy" + (lang === "en" ? "in a new terminal" : "在新打开的终端中"));
+ assert.equal(kvs[i + 1][0], now);
+ assert(kvs[i + 1][1].startsWith(LAUNCH), kvs[i + 1][1]);
+ await page.close();
+ }
+ } finally {
+ typed = false;
+ }
+ });
+
assert.deepEqual(errors, []);
});
}
diff --git a/internal/update/shellfn.go b/internal/update/shellfn.go
new file mode 100644
index 000000000..c65f60120
--- /dev/null
+++ b/internal/update/shellfn.go
@@ -0,0 +1,232 @@
+package update
+
+import (
+ "bytes"
+ "errors"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+
+ "github.com/yetone/magpie/internal/edit"
+)
+
+// A command an agent is typed by, given to it by magpie: agy takes
+// magpie's gateway, its key and the model only from how it is started
+// (agent/agy.go), so magpie puts a function named agy in the profile of
+// each shell the user has, which starts it through this magpie (bestony on
+// Discord: no command to copy at each start). The function sits in a
+// block of its own between two marked lines, which is all magpie ever
+// writes or takes out of the profile; the rest of the file is the user's.
+//
+// The shells are those ReadCLI asks about: zsh (its .zshrc in ZDOTDIR when
+// that is set), bash (the file a terminal's bash reads) and fish
+// (config.fish) on macOS and Linux, PowerShell 7 and Windows PowerShell on
+// Windows, each only where its execution policy runs a profile. A profile
+// that isn't there yet is made only for the shell a terminal opens, and
+// only a profile inside the home is written, so a test's temporary home
+// keeps it from the real one.
+
+// ShellBody is a function's text for one shell: "posix" (zsh, bash),
+// "fish" or "powershell"; prog is this magpie, by a path that stays put.
+type ShellBody func(kind, prog string) string
+
+// fnProfile is one shell's profile a function goes in.
+type fnProfile struct {
+ Kind string // posix, fish, powershell
+ Path string
+ Create bool // made when it isn't there: the shell a terminal opens
+}
+
+// What the shell functions ask the system; tests set them.
+var (
+ fnProfiles = shellProfiles
+ fnHome = func() string {
+ if runtime.GOOS == "windows" {
+ return os.Getenv("USERPROFILE")
+ }
+ return os.Getenv("HOME")
+ }
+)
+
+var fnMu sync.Mutex
+
+func fnOpen(name string) string { return "# >>> magpie " + name + " >>>" }
+func fnClose(name string) string { return "# <<< magpie " + name + " <<<" }
+
+// ShellFunction puts the function name, as body gives it for each shell,
+// in the profile of every shell the user has, or brings one there up to
+// date. It says the profiles that have it now. A profile that can't be
+// read is left as it is: what it holds is unknown.
+func ShellFunction(name string, body ShellBody) ([]string, error) {
+ prog, err := cliExe()
+ if err != nil {
+ return nil, err
+ }
+ fnMu.Lock()
+ defer fnMu.Unlock()
+ var in []string
+ var errs []error
+ for _, p := range fnProfiles() {
+ if !fnInHome(p.Path) {
+ continue
+ }
+ ok, err := setFnBlock(p, name, strings.TrimRight(body(p.Kind, prog), "\n"))
+ if err != nil {
+ errs = append(errs, err)
+ }
+ if ok {
+ in = append(in, p.Path)
+ }
+ }
+ return in, errors.Join(errs...)
+}
+
+// DropShellFunction takes the function name out of every profile magpie
+// put it in.
+func DropShellFunction(name string) error {
+ fnMu.Lock()
+ defer fnMu.Unlock()
+ var errs []error
+ for _, p := range fnProfiles() {
+ if !fnInHome(p.Path) {
+ continue
+ }
+ if _, err := setFnBlock(p, name, ""); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// ShellFunctionIn says the profiles that hold the function name.
+func ShellFunctionIn(name string) []string {
+ var in []string
+ for _, p := range fnProfiles() {
+ if !fnInHome(p.Path) {
+ continue
+ }
+ b, err := os.ReadFile(p.Path)
+ if err == nil && fnFind(lines(string(edit.TrimBOM(b))), name) >= 0 {
+ in = append(in, p.Path)
+ }
+ }
+ return in
+}
+
+// fnInHome says p is a file in the user's home.
+func fnInHome(p string) bool {
+ h := fnHome()
+ if h == "" || !filepath.IsAbs(h) || !filepath.IsAbs(p) {
+ return false
+ }
+ rel, err := filepath.Rel(h, p)
+ return err == nil && rel != "." && !strings.HasPrefix(rel, "..")
+}
+
+// setFnBlock writes the function name's block in the profile p as body,
+// or takes it out for ""; it says whether the block is there after.
+func setFnBlock(p fnProfile, name, body string) (bool, error) {
+ b, err := os.ReadFile(p.Path)
+ if errors.Is(err, fs.ErrNotExist) {
+ if body == "" || !p.Create {
+ return false, nil
+ }
+ b, err = nil, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ text := string(edit.TrimBOM(b))
+ out := withFnBlock(text, name, body, p.Kind == "powershell")
+ if out == text {
+ return body != "", nil
+ }
+ if b == nil {
+ if err := os.MkdirAll(filepath.Dir(p.Path), 0o755); err != nil {
+ return false, err
+ }
+ // Windows PowerShell reads a profile without a byte order mark
+ // in the system's code page, which a path of the user's name
+ // outside ASCII would be garbled in
+ if p.Kind == "powershell" {
+ out = "\xef\xbb\xbf" + out
+ }
+ }
+ if err := edit.WriteAtomic(p.Path, []byte(out)); err != nil {
+ return false, err
+ }
+ return body != "", nil
+}
+
+func lines(text string) []string { return strings.Split(text, "\n") }
+
+// fnFind is the line the function name's block opens on, -1 none.
+func fnFind(ls []string, name string) int {
+ for i, l := range ls {
+ if strings.TrimRight(l, "\r") == fnOpen(name) {
+ return i
+ }
+ }
+ return -1
+}
+
+// withFnBlock is the profile text with the function name's block as body,
+// in place of the one it has or after the rest; body "" takes the block
+// out, and the blank line put before it. The file's own line endings are
+// kept; a new file gets CRLF for PowerShell.
+func withFnBlock(text, name, body string, crlf bool) string {
+ nl := "\n"
+ if strings.Contains(text, "\r\n") || text == "" && crlf {
+ nl = "\r\n"
+ }
+ var block []string
+ if body != "" {
+ block = append(append([]string{fnOpen(name)}, lines(strings.ReplaceAll(body, "\r\n", "\n"))...), fnClose(name))
+ }
+ ls := lines(strings.ReplaceAll(text, "\r\n", "\n"))
+ if i := fnFind(ls, name); i >= 0 {
+ end := -1
+ for j := i + 1; j < len(ls); j++ {
+ if ls[j] == fnClose(name) {
+ end = j
+ break
+ }
+ }
+ if end < 0 {
+ // opened and never closed: someone cut it; the open line alone
+ // is magpie's
+ end = i
+ }
+ if body != "" {
+ out := append(append(clone(ls[:i]), block...), ls[end+1:]...)
+ return strings.Join(out, nl)
+ }
+ // out, with the blank line put before it
+ from := i
+ if i > 0 && ls[i-1] == "" {
+ from = i - 1
+ }
+ return strings.Join(append(clone(ls[:from]), ls[end+1:]...), nl)
+ }
+ if body == "" {
+ return text
+ }
+ var buf bytes.Buffer
+ buf.WriteString(text)
+ if text != "" {
+ if !strings.HasSuffix(text, "\n") {
+ buf.WriteString(nl)
+ }
+ buf.WriteString(nl)
+ }
+ buf.WriteString(strings.Join(block, nl) + nl)
+ return buf.String()
+}
+
+func clone(s []string) []string { return append([]string(nil), s...) }
+
+// TildeHome is p with the home as ~, for a message.
+func TildeHome(p string) string { return tildeHome(p) }
diff --git a/internal/update/shellfn_other.go b/internal/update/shellfn_other.go
new file mode 100644
index 000000000..8e3710127
--- /dev/null
+++ b/internal/update/shellfn_other.go
@@ -0,0 +1,48 @@
+//go:build !windows
+
+package update
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+)
+
+// shellProfiles are the profiles of the shells installed here that a
+// function goes in: zsh's, bash's and fish's (cliProfile), the one a
+// terminal opens made when it isn't there yet. A Mac's login bash reads
+// the first of .bash_profile, .bash_login and .profile there is.
+func shellProfiles() []fnProfile {
+ var out []fnProfile
+ for _, sh := range cliShells() {
+ p := cliProfile(sh.Name)
+ if p == "" {
+ continue
+ }
+ kind := "posix"
+ create := sh.Default
+ switch sh.Name {
+ case "fish":
+ kind = "fish"
+ // fish makes ~/.config/fish on its first start, and reads
+ // config.fish there when there is one
+ if st, err := os.Stat(filepath.Dir(p)); err == nil && st.IsDir() {
+ create = true
+ }
+ case "bash":
+ if runtime.GOOS == "darwin" {
+ if _, err := os.Lstat(p); os.IsNotExist(err) {
+ h := filepath.Dir(p)
+ for _, n := range []string{".bash_login", ".profile"} {
+ if _, err := os.Lstat(filepath.Join(h, n)); err == nil {
+ p = filepath.Join(h, n)
+ break
+ }
+ }
+ }
+ }
+ }
+ out = append(out, fnProfile{Kind: kind, Path: p, Create: create})
+ }
+ return out
+}
diff --git a/internal/update/shellfn_other_test.go b/internal/update/shellfn_other_test.go
new file mode 100644
index 000000000..cb5945714
--- /dev/null
+++ b/internal/update/shellfn_other_test.go
@@ -0,0 +1,65 @@
+//go:build !windows
+
+package update
+
+import (
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+// The profiles agy's function goes in are the ones each shell reads as a
+// terminal opens it: zsh's in ZDOTDIR when that is set, the login shell's
+// made when it isn't there, a shell that isn't the terminal's only when
+// its profile is.
+func TestShellProfiles(t *testing.T) {
+ h := t.TempDir()
+ t.Setenv("HOME", h)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
+ zdot := filepath.Join(h, ".config", "zsh")
+ t.Setenv("ZDOTDIR", zdot)
+ oldExe, oldShells := cliExe, cliShells
+ t.Cleanup(func() { cliExe, cliShells = oldExe, oldShells })
+ cliExe = func() (string, error) { return "/Applications/magpie.app/Contents/MacOS/magpie", nil }
+ cliShells = func() []cliShell {
+ return []cliShell{{Name: "zsh", Default: true}, {Name: "bash"}, {Name: "fish"}, {Name: "nu"}}
+ }
+ bashrc := ".bashrc"
+ if runtime.GOOS == "darwin" {
+ // no .bash_profile: a login bash reads .profile
+ bashrc = ".profile"
+ write(t, filepath.Join(h, ".profile"), "umask 022\n")
+ } else {
+ write(t, filepath.Join(h, ".bashrc"), "umask 022\n")
+ }
+ in, err := ShellFunction("agy", fnBody)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{filepath.Join(zdot, ".zshrc"), filepath.Join(h, bashrc)}
+ if strings.Join(in, ",") != strings.Join(want, ",") {
+ t.Fatalf("in = %v, want %v", in, want)
+ }
+ if _, err := os.Stat(filepath.Join(h, ".zshrc")); !os.IsNotExist(err) {
+ t.Fatal("~/.zshrc was written though ZDOTDIR is set")
+ }
+ if _, err := os.Stat(filepath.Join(h, ".config", "fish")); !os.IsNotExist(err) {
+ t.Fatal("fish's config was made, though fish has never started")
+ }
+
+ // fish has started once: its config folder is there
+ os.MkdirAll(filepath.Join(h, ".config", "fish"), 0o755)
+ in, _ = ShellFunction("agy", fnBody)
+ if len(in) != 3 || in[2] != filepath.Join(h, ".config", "fish", "config.fish") {
+ t.Fatalf("with fish's folder: %v", in)
+ }
+
+ // ZDOTDIR outside the home: not magpie's to write
+ t.Setenv("ZDOTDIR", t.TempDir())
+ in, _ = ShellFunction("agy", fnBody)
+ if len(in) != 2 {
+ t.Fatalf("ZDOTDIR outside the home: %v", in)
+ }
+}
diff --git a/internal/update/shellfn_test.go b/internal/update/shellfn_test.go
new file mode 100644
index 000000000..b11133091
--- /dev/null
+++ b/internal/update/shellfn_test.go
@@ -0,0 +1,154 @@
+package update
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// fnBody is a function body that says the shell and the program.
+func fnBody(kind, prog string) string {
+ return "agy() { # " + kind + "\n '" + prog + "' agy run \"$@\"\n}"
+}
+
+// The block magpie puts in a shell's profile for agy (bestony on Discord):
+// added after the user's own lines, the same file again when nothing
+// changed, rewritten in place, taken out leaving the file as it was, and
+// never written where the file can't be read or outside the home.
+func TestShellFunction(t *testing.T) {
+ h := t.TempDir()
+ t.Setenv("HOME", h)
+ t.Setenv("USERPROFILE", h)
+ exe := filepath.Join(h, "Applications", "magpie")
+ rc := filepath.Join(h, ".zshrc")
+ fish := filepath.Join(h, ".config", "fish", "config.fish")
+ crlf := filepath.Join(h, "Documents", "PowerShell", "Microsoft.PowerShell_profile.ps1")
+ broken := filepath.Join(h, ".bashrc")
+ outside := filepath.Join(t.TempDir(), ".zshrc")
+ profiles := []fnProfile{
+ {Kind: "posix", Path: rc},
+ {Kind: "fish", Path: fish},
+ {Kind: "powershell", Path: crlf},
+ {Kind: "posix", Path: broken},
+ {Kind: "posix", Path: outside, Create: true},
+ }
+ oldExe, oldProfiles := cliExe, fnProfiles
+ t.Cleanup(func() { cliExe, fnProfiles = oldExe, oldProfiles })
+ cliExe = func() (string, error) { return exe, nil }
+ fnProfiles = func() []fnProfile { return profiles }
+
+ mine := "export PATH=$HOME/bin:$PATH\nalias ll='ls -l'" // no newline at the end
+ write(t, rc, mine)
+ ps := "\xef\xbb\xbfSet-Alias ll Get-ChildItem\r\n"
+ write(t, crlf, ps)
+ // a folder where .bashrc is: its read fails, so what it holds is unknown
+ if err := os.MkdirAll(broken, 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ in, err := ShellFunction("agy", fnBody)
+ if err == nil {
+ t.Fatal("the unreadable .bashrc gave no error")
+ }
+ if strings.Join(in, ",") != rc+","+crlf {
+ t.Fatalf("in = %v", in)
+ }
+ want := mine + "\n\n# >>> magpie agy >>>\nagy() { # posix\n '" + exe + "' agy run \"$@\"\n}\n# <<< magpie agy <<<\n"
+ if got := read(t, rc); got != want {
+ t.Fatalf(".zshrc:\n%s\nwant:\n%s", got, want)
+ }
+ if got := read(t, crlf); !strings.HasPrefix(got, ps+"\r\n# >>> magpie agy >>>\r\nagy() { # powershell\r\n") || strings.Contains(strings.ReplaceAll(got, "\r\n", ""), "\n") {
+ t.Fatalf("PowerShell's profile lost its BOM or CRLF: %q", got)
+ }
+ if _, err := os.Stat(fish); !os.IsNotExist(err) {
+ t.Fatal("fish's profile was made, though fish isn't the shell a terminal opens")
+ }
+ if _, err := os.Stat(outside); !os.IsNotExist(err) {
+ t.Fatal("a profile outside the home was written")
+ }
+ if got := ShellFunctionIn("agy"); strings.Join(got, ",") != rc+","+crlf {
+ t.Fatalf("ShellFunctionIn = %v", got)
+ }
+
+ // again: nothing changes, the file isn't written
+ st, _ := os.Stat(rc)
+ old := st.ModTime().Add(-time.Hour)
+ os.Chtimes(rc, old, old)
+ if _, err := ShellFunction("agy", fnBody); err == nil {
+ t.Fatal("no error the second time")
+ }
+ if got := read(t, rc); got != want {
+ t.Fatalf("second time:\n%s", got)
+ }
+ if st, _ := os.Stat(rc); !st.ModTime().Equal(old) {
+ t.Fatal("the same block was written again")
+ }
+
+ // the user adds lines after it; the block is rewritten where it is
+ write(t, rc, want+"export EDITOR=vim\n")
+ exe = filepath.Join(h, "moved", "magpie")
+ ShellFunction("agy", fnBody)
+ if got := read(t, rc); got != strings.ReplaceAll(want, filepath.Join(h, "Applications"), filepath.Join(h, "moved"))+"export EDITOR=vim\n" {
+ t.Fatalf("rewritten:\n%s", got)
+ }
+
+ // out: the user's lines as they were
+ if err := DropShellFunction("agy"); err == nil {
+ t.Fatal("no error dropping with the unreadable .bashrc")
+ }
+ if got := read(t, rc); got != mine+"\nexport EDITOR=vim\n" {
+ t.Fatalf("after Drop:\n%q", got)
+ }
+ if got := read(t, crlf); got != ps {
+ t.Fatalf("PowerShell's after Drop: %q", got)
+ }
+ if got := ShellFunctionIn("agy"); len(got) != 0 {
+ t.Fatalf("ShellFunctionIn after Drop = %v", got)
+ }
+
+ // the shell a terminal opens gets a profile made for it
+ profiles[1].Create = true
+ ShellFunction("agy", fnBody)
+ if got := read(t, fish); got != "# >>> magpie agy >>>\nagy() { # fish\n '"+exe+"' agy run \"$@\"\n}\n# <<< magpie agy <<<\n" {
+ t.Fatalf("made fish profile:\n%s", got)
+ }
+}
+
+// withFnBlock's cases: the file's own ending, a block whose close line was
+// cut, another tool's block left alone.
+func TestWithFnBlock(t *testing.T) {
+ for _, c := range []struct{ name, in, body, want string }{
+ {"empty", "", "x", "# >>> magpie agy >>>\nx\n# <<< magpie agy <<<\n"},
+ {"ends with newline", "a\n", "x", "a\n\n# >>> magpie agy >>>\nx\n# <<< magpie agy <<<\n"},
+ {"out", "a\n\n# >>> magpie agy >>>\nx\n# <<< magpie agy <<<\n", "", "a\n"},
+ {"out, between lines", "a\n\n# >>> magpie agy >>>\nx\n# <<< magpie agy <<<\nb\n", "", "a\nb\n"},
+ {"close cut", "a\n# >>> magpie agy >>>\nb\n", "", "a\nb\n"},
+ {"another's block", "# >>> conda initialize >>>\nc\n# <<< conda initialize <<<\n", "", "# >>> conda initialize >>>\nc\n# <<< conda initialize <<<\n"},
+ {"none to drop", "a", "", "a"},
+ } {
+ if got := withFnBlock(c.in, "agy", c.body, false); got != c.want {
+ t.Errorf("%s: %q, want %q", c.name, got, c.want)
+ }
+ }
+}
+
+func write(t *testing.T, p, s string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func read(t *testing.T, p string) string {
+ t.Helper()
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
diff --git a/internal/update/shellfn_windows.go b/internal/update/shellfn_windows.go
new file mode 100644
index 000000000..86bd76c7d
--- /dev/null
+++ b/internal/update/shellfn_windows.go
@@ -0,0 +1,90 @@
+package update
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+
+ "golang.org/x/sys/windows"
+ "golang.org/x/sys/windows/registry"
+
+ "github.com/yetone/magpie/internal/proc"
+)
+
+// shellProfiles are PowerShell 7's and Windows PowerShell's profiles, each
+// only where its execution policy runs a profile: Windows PowerShell's is
+// Restricted until the user changes it, and a profile it may not run
+// would put an error in each terminal it opens. cmd has no profile.
+func shellProfiles() []fnProfile {
+ docs := documents()
+ if docs == "" {
+ return nil
+ }
+ gpo := policy(registry.LOCAL_MACHINE, `SOFTWARE\Policies\Microsoft\Windows\PowerShell`)
+ var out []fnProfile
+ seven := filepath.Join(docs, "PowerShell")
+ if _, err := os.Stat(seven); err == nil || pwshInstalled() {
+ // RemoteSigned unless a policy says otherwise
+ if gpo == "" || runsProfile(gpo) {
+ out = append(out, fnProfile{Kind: "powershell", Path: filepath.Join(seven, "Microsoft.PowerShell_profile.ps1"), Create: true})
+ }
+ }
+ p := gpo
+ if p == "" {
+ p = policy(registry.CURRENT_USER, `SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell`)
+ }
+ if p == "" {
+ p = policy(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell`)
+ }
+ if runsProfile(p) {
+ out = append(out, fnProfile{Kind: "powershell", Path: filepath.Join(docs, "WindowsPowerShell", "Microsoft.PowerShell_profile.ps1"), Create: true})
+ }
+ return out
+}
+
+func pwshInstalled() bool {
+ _, err := proc.Look("pwsh")
+ return err == nil
+}
+
+// runsProfile says a policy lets a profile written here run.
+func runsProfile(p string) bool {
+ switch strings.ToLower(p) {
+ case "remotesigned", "unrestricted", "bypass":
+ return true
+ }
+ return false
+}
+
+// policy is the ExecutionPolicy a registry key sets, "" none.
+func policy(root registry.Key, path string) string {
+ k, err := registry.OpenKey(root, path, registry.QUERY_VALUE)
+ if err != nil {
+ return ""
+ }
+ defer k.Close()
+ if path == `SOFTWARE\Policies\Microsoft\Windows\PowerShell` {
+ if on, _, err := k.GetIntegerValue("EnableScripts"); err == nil && on == 0 {
+ return "Restricted"
+ }
+ }
+ v, _, _ := k.GetStringValue("ExecutionPolicy")
+ return v
+}
+
+// documents is the user's Documents folder, where PowerShell's profiles
+// are; under a home that isn't the user's own (a test's), Documents in it.
+func documents() string {
+ home := os.Getenv("USERPROFILE")
+ if home == "" {
+ return ""
+ }
+ own, _ := windows.KnownFolderPath(windows.FOLDERID_Profile, 0)
+ if own == "" || !strings.EqualFold(filepath.Clean(own), filepath.Clean(home)) {
+ return filepath.Join(home, "Documents")
+ }
+ if d, err := windows.KnownFolderPath(windows.FOLDERID_Documents, 0); err == nil && d != "" {
+ return d
+ }
+ return filepath.Join(home, "Documents")
+}