From 0cc91af3dbeb06e7b90bc338e4bbba4854baa5eb Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 11 Nov 2026 10:24:49 +0800 Subject: [PATCH] agy: magpie's models go in a settings file of its own, so agy's remote control works (baysonfox on X) magpie wrote modelProvider gemini, the model and its custom models into agy's settings.json. That made every agy an API-key session: no Google account, so no remote control (needs the sign-in plus Google's server-side flag), and a plain agy asked for GEMINI_API_KEY too. Now they go in ~/.gemini/antigravity-cli/magpie-settings.json, handed to agy as --settings for the one session (the launch command, magpie agy run, and the function in a shell or a WSL distro). settings.json stays the user's. An older wiring is given back (stashed model and provider) at the next Sync or pick. agy remote-control and --remote-control run plain, on the sign-in. Run (mote): go vet, GOOS=windows and linux nogui vet, agent/cli/sessions/update packages (see push note). Real agy 1.5.3 in a sandbox HOME: plain agy with the user's untouched settings.json now asks for sign-in (no GEMINI_API_KEY error); the new launch reached a stub gateway at /v1beta/models/:streamGenerateContent. Broken by hand: remote-control bypass removed, TestAgyRun red; TestAgy red on the old code (settings.json written). Not tried: real remote control (needs a Google sign-in, none in the sandbox); signed-in BYOM custom models; Windows PowerShell function run. --- docs/subsystems/agent-wiring.md | 4 +- internal/agent/agy.go | 208 ++++++++++++++++--------- internal/agent/agy_posix_test.go | 4 +- internal/agent/agy_test.go | 73 +++++++-- internal/agent/wsl_agy_test.go | 25 ++- internal/cli/agy_cli.go | 16 +- internal/cli/agy_cli_test.go | 25 ++- internal/gui/tests/agy-launch.test.cjs | 2 +- 8 files changed, 250 insertions(+), 107 deletions(-) diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index ef4cfb5de..d3532898d 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -34,7 +34,7 @@ something else shows up as drift. | WSL folders that are links | Through `\\wsl.localhost` Windows can't follow a link the distro has: with `~/.codex` a link to `/mnt/c/Users//.codex`, a mkdir of it says it exists and nothing below it can be made, written, read or listed (#4502, linusxiong). The probe asks `readlink -f` there where each agent folder, its `skills` and the folders beside them lead (`wslLinkPaths`, `distro.Links`; a `$HOME` that is itself through a link is left as it was) and which drive each Windows mount is (`distro.Drives`). `distro.open` opens a path at or below a link where it leads: on a Windows drive the drive's own path (`C:\Users\\.codex`), elsewhere in the distro through its root again; `native` spells such a path back through the link for the agent. A link `readlink -f` couldn't resolve is never guessed at: its agent is unreached (`Agent.Unreached`), says why in its notice and refuses each change and sync. Every writer goes through it: the agents' own files (`place.join`, `place.open`), the library's targets (`wslOpen`, a `wsl` problem per agent), RTK (`rtkAt`, `agent.WSLOpen`), the Sessions page's reads (`sessions.WSLHome.Open`) and the Copilot CLI's sign-in (`provider.CopilotWSLDirs`). Links deeper than the probed paths aren't resolved (`TestWSLOpenThroughLinks`, `TestWSLAgentFolderIsALink`, `TestWSLAgentFolderLinkUnresolved`, `TestWSLProbeLinks`, `TestWSLFolderIsALinkToC`, `TestRTKWSLFolderIsALink`). | [`wsl.go`](../../internal/agent/wsl.go), [`targets.go`](../../internal/library/targets.go), [`rtk_wsl.go`](../../internal/library/rtk_wsl.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`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `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..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). 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 tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, 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. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin::` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `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`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; 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. 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 (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`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`, `--settings <~/.gemini/antigravity-cli/magpie-settings.json>` and `--model` (no `--model` when the user gives one) while that file's model is magpie's, and unchanged otherwise. magpie writes `modelProvider`, `model` and the custom models (the user's own too, as agy takes the key whole) only into that file of its own, never into agy's `settings.json`: `modelProvider: gemini` there made every agy an API-key session with no Google account, so no remote control, which needs the sign-in (baysonfox on X). A `settings.json` an older magpie wired is given back (the stashed model and provider) at the next `Sync` or pick. `agy remote-control …` and `--remote-control` go through the function and `magpie agy run` as plain agy, on the user's sign-in (`AgyRemote`); remote control inside a session on magpie's models is not possible. 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 (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`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). The app (0.1.72, Electron) attaches its window to a daemon running; with none it starts its own (`serve --stdio --adopt-install`, `launch_context` `app-child`) in its own environment, without the variable, and its "let the app run it instead" (and its offer once the app updated past the daemon) stops magpie's to do the same (shuitunlulu_ on Discord: Claude Science went back off magpie). So the keeper also puts magpie's daemon back, on the port the other was on, in place of one with another pid, one started for the gateway's old address, or its own older than the program installed (`--version`, asked again only when the file changed) (`scienceStale`), but only when `status` says no session runs in it (`active_frames` and `active_conversations` 0; a status without them is busy), never one launchd or systemd keeps (`launch_context`), and at most three times an hour (`scienceRetakes`). It reads `operon.lock` every 10 s and asks `status` when the lock's pid changed or a minute went by. A window on the daemon stopped shows the app's "stopped from the command line" screen, whose "start it again in the app" attaches it to magpie's. `Check` reads the daemon's `operon.lock`, not `status` (most of a second for a 130 MB Bun program), and calls a daemon with another pid drift until the keeper replaces it. 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). In a WSL distro (shuitunlulu_ on Discord) it is a WSL twin (`wslKinds`, found by `claude-science` on the probe's PATH, keeping its own notice) whose daemon magpie runs there through `wsl.exe` (`scienceInWSL`, `scienceWSLScript`; the same `scienceHost` steps as this machine's, its note `claude-science-wsl-.json`). The daemon takes http only to a loopback address, so in mirrored networking it gets the gateway's address, and under NAT a relay magpie starts in the distro: `socat` on `127.0.0.1:` to Windows' address on the WSL network (`scienceRelayScript`, its pid and target in `~/.claude-science/magpie-relay`, stopped with its forks as a process group on Disconnect or when the target moved). It is given `http://127.0.0.1:/`, the key in the path, as it sends its own sign-in as the key (gateway-routing's WSL under NAT). Connect says so when the distro has no socat. The keeper runs nothing in WSL until a distro's note exists, then starts both again in each running distro (`wslScienceHosts`). Its `Check` adds the firewall drift any agent pointed at Windows' WSL address gets (`unreachable`), as its one value isn't a model of magpie's, which is what `Drift` asks that of. | [`claudescience.go`](../../internal/agent/claudescience.go), [`claudescience_wsl.go`](../../internal/agent/claudescience_wsl.go), [`science.go`](../../internal/gateway/science.go) | | Claude Code beside its own account | `claude-magpie` (baranwang on X) starts Claude Code through magpie while a plain `claude` stays on the user's own account, nothing switched back and forth. `magpie claude run [args…]` writes `/claude-launch/settings.json` as `claude#launch`, an agent `claudeIn` makes at that folder (`place.dir`) and lists nowhere, so the Agents page, Check and Notice see only the user's settings.json: connected the first time as Connect would (`ConnectHow`), set again when the gateway's address or key moved (`claudeLaunchStale`, the LAN key included), synced after that, with `ANTHROPIC_API_KEY` and the cloud switches (`agentenv.ClaudeProviders`) blanked. It then runs `claude --settings args…` as a child (not exec, so it can tidy after): Claude Code puts a --settings file's env and model over the user's settings.json, a claude.ai sign-in and the shell (tried on 2.1.318). `/model` saves to the user's settings.json, never the --settings file, so `ClaudeLaunchAfter` moves a magpie model picked there into the launch file and gives the user's file its model back while magpie isn't wired into it; it also undoes Claude Code's own one-time `opus` → `opus[1m]` rewrite (`migration_opus_to_opus1m`), which the launch file's 1M opus tier sets off. A Claude alias picked (`sonnet`) stays. On Unix a stopped child stops magpie too (^Z, fg), and its exit code is magpie's; on Windows magpie ignores Ctrl+C while claude runs. The command `claude-magpie` is a launcher beside the `magpie` command (`update.Launchers`): a `#!/bin/sh` `exec` of `Program()`, or on Windows a `.cmd` running `"%~dp0magpie"`. `AddCLI` writes it, and `magpie claude launcher add` puts it there for a command added before; a file by that name without `written by magpie` is never written over. StandIn falls back to the launch file's tiers. | [`claude_launch.go`](../../internal/agent/claude_launch.go), [`claude_launch_cli.go`](../../internal/cli/claude_launch_cli.go), [`claude_run_unix.go`](../../internal/cli/claude_run_unix.go), [`launcher.go`](../../internal/update/launcher.go) | @@ -49,7 +49,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 a WSL distro gets the function in the distro's own profiles (`agyDistroProfiles` in [`agy.go`](../../internal/agent/agy.go), through `update.ShellFunctionAt`): `~/.bashrc`, `~/.zshrc` and `~/.config/fish/config.fish` where each is, and the profile of the login shell the distro's `/etc/passwd` names (bash when it names none) made where it isn't. The distro's `ZDOTDIR` and `XDG_CONFIG_HOME` aren't read. No magpie runs there, so the function (`agyDistroFunction`) reads `settings.json`'s model with `sed` and carries the gateway's address as the distro reaches it (`place.gw`, Windows' under NAT) and the key it takes from there (`agentKeyAt`, the WSL key under NAT). `Sync` writes it again, so an address WSL changed on a restart follows, and until then `Check` reports a function naming another address. A user's own `alias agy` still wins over it. A terminal opened before the change still needs the `Launch` command. +- 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 a WSL distro gets the function in the distro's own profiles (`agyDistroProfiles` in [`agy.go`](../../internal/agent/agy.go), through `update.ShellFunctionAt`): `~/.bashrc`, `~/.zshrc` and `~/.config/fish/config.fish` where each is, and the profile of the login shell the distro's `/etc/passwd` names (bash when it names none) made where it isn't. The distro's `ZDOTDIR` and `XDG_CONFIG_HOME` aren't read. No magpie runs there, so the function (`agyDistroFunction`) reads `magpie-settings.json`'s model with `sed` and carries the gateway's address as the distro reaches it (`place.gw`, Windows' under NAT) and the key it takes from there (`agentKeyAt`, the WSL key under NAT). `Sync` writes it again, so an address WSL changed on a restart follows, and until then `Check` reports a function naming another address. 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`). - An agent whose `Sync` does nothing but bring a block of magpie's name up to the catalog is `ListOnly` (OpenCode, MiMo Code and the other OpenCode forms, Pi and its forks, Goose, Crush, Air, AtomCode, Command Code, Droid, Fx, jcode, Kimi, MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenMausBot, Avibe, Kun, OpenPencil, Penguin, Qwen Code, T3 Code). `SyncCatalog` runs it only while the agent is connected (`Wired`), as its switch on the Agents page says: a custom provider the user named magpie in the agent, with a few models picked by hand, was written over with the whole catalog at every start (yyddbds on Discord, Xiaomi MiMo; `TestCatalogSyncLeavesAHandWrittenMagpieBlock`). A list magpie wrote while connected waits, while the agent runs a model of its own, until a model of magpie's is picked again; a model of magpie's picked by hand on a provider the user wrote doesn't connect it (`handWired`, above). Every `ListOnly` agent magpie connects reads as `Wired` (`TestListOnlyAgentsReadConnected`). Agents whose `Sync` also repairs while not connected (Codex, Claude, Grok, Hermes' bots) are not `ListOnly`. magpie keeps no copy of a list it wrote over before this, so such a list stays full until the user trims it. - `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`). diff --git a/internal/agent/agy.go b/internal/agent/agy.go index a1d2f5bdf..f0b6ff135 100644 --- a/internal/agent/agy.go +++ b/internal/agent/agy.go @@ -15,6 +15,16 @@ package agent // in settings.json or its /model picker with no model name ("model is // empty"); only one given on the command line resolves. // +// None of that is written to settings.json any more (baysonfox on X: with +// "modelProvider": "gemini" in it every agy runs on an API key, with no +// Google account, and remote control, which needs the sign-in, was gone; +// a plain agy asked for GEMINI_API_KEY too). The model, the provider and +// the custom models (the user's own and magpie's, since agy takes the key +// whole) are in a file of magpie's beside it, magpie-settings.json, which +// the launch hands agy as --settings for that one session. settings.json +// stays the user's, and a plain agy, and `agy remote-control` or +// --remote-control through the function, run on their Google sign-in. +// // 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 @@ -53,30 +63,48 @@ const agyModels = "customModelsConfig.customModels" // (x-goog-api-key) alone. A command copied before, with the plain token, // still reaches magpie. func AgyLaunch(model string) string { - return agyLaunchAt(gateway.URL(), agentKey("agy"), model, runtime.GOOS == "windows") + return agyLaunchAt(gateway.URL(), agentKey("agy"), agySettingsFile(), model, runtime.GOOS == "windows") } -// agyLaunchAt is AgyLaunch for agy reaching the gateway at gw with key, in -// PowerShell or a POSIX shell. -func agyLaunchAt(gw, key, model string, powershell bool) string { +// agyOverride is the name of magpie's settings file in agy's folder. +const agyOverride = "magpie-settings.json" + +// agySettingsFile is magpie's settings file for agy on this machine. +func agySettingsFile() string { + home, _ := homes() + return filepath.Join(home, ".gemini", "antigravity-cli", agyOverride) +} + +// AgyRemote says a is what asks agy for its remote control, which only a +// Google sign-in has, never an API key's session: run plain. +func AgyRemote(a string) bool { + a, _, _ = strings.Cut(a, "=") + return a == "remote-control" || a == "--remote-control" || a == "-remote-control" +} + +// agyLaunchAt is AgyLaunch for agy reaching the gateway at gw with key and +// magpie's settings file, in PowerShell or a POSIX shell. +func agyLaunchAt(gw, key, settings, model string, powershell bool) string { if powershell { - return `$env:GEMINI_API_KEY="` + key + `"; $env:GOOGLE_GEMINI_BASE_URL="` + gw + `"; agy --model '` + strings.ReplaceAll(model, "'", "''") + `'` + return `$env:GEMINI_API_KEY="` + key + `"; $env:GOOGLE_GEMINI_BASE_URL="` + gw + `"; agy --settings '` + strings.ReplaceAll(settings, "'", "''") + `' --model '` + strings.ReplaceAll(model, "'", "''") + `'` } - return "GEMINI_API_KEY=" + key + " GOOGLE_GEMINI_BASE_URL=" + gw + " agy --model '" + strings.ReplaceAll(model, "'", `'\''`) + "'" + return "GEMINI_API_KEY=" + key + " GOOGLE_GEMINI_BASE_URL=" + gw + " agy --settings '" + strings.ReplaceAll(settings, "'", `'\''`) + "' --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. +// while magpie's settings file names one of magpie's models; nil and "" +// otherwise, when agy starts as it is. The file is AgySettings. func AgyStart() (env []string, model string) { - home, _ := homes() - m := jsonGet(filepath.Join(home, ".gemini", "antigravity-cli", "settings.json"), "model")() + m := jsonGet(agySettingsFile(), "model")() if !usesMagpie(m) { return nil, "" } return []string{"GEMINI_API_KEY=" + agentKey("agy"), "GOOGLE_GEMINI_BASE_URL=" + gateway.URL()}, m } +// AgySettings is the --settings file agy starts with on magpie. +func AgySettings() string { return agySettingsFile() } + // 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. @@ -107,11 +135,11 @@ func agyFunction(kind, prog string) string { 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 } + if (-not $start.model -or @($args | Where-Object { "$_" -match '^--?(remote-control)(=|$)|^remote-control$' }).Count) { & $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 } + if (@($args | Where-Object { "$_" -match '^--?model(=|$)' }).Count) { & $real --settings $start.settings @args } else { & $real --settings $start.settings --model $start.model @args } } finally { $env:GEMINI_API_KEY = $was[0]; $env:GOOGLE_GEMINI_BASE_URL = $was[1] } }` } @@ -164,11 +192,11 @@ func distroLoginShell(at place) string { return "bash" } -// agyDistroModel is the sed script that prints settings.json's model while -// it is one of magpie's, for the function in a distro, where no magpie -// runs to read it. Its model is a line of its own as magpie writes the -// file; one written on a single line is found too, so long as nothing -// after it is named "model". +// agyDistroModel is the sed script that prints magpie's settings file's +// model, for the function in a distro, where no magpie runs to read it. +// Its model is a line of its own as magpie writes the file; one written on +// a single line is found too, so long as nothing after it is named +// "model". const agyDistroModel = `s|^.*"model"[[:space:]]*:[[:space:]]*"\(` + magpieID + `/[^"]*\)".*$|\1|p` // agyDistroFunction is the function agy in a distro's shell of kind: @@ -177,22 +205,26 @@ const agyDistroModel = `s|^.*"model"[[:space:]]*:[[:space:]]*"\(` + magpieID + ` // `magpie agy run` does on this machine; as it is otherwise. func agyDistroFunction(kind, key, gw string) string { q := func(v string) string { return "'" + strings.ReplaceAll(v, "'", `'\''`) + "'" } - settings := `"$HOME/.gemini/antigravity-cli/settings.json"` + settings := `"$HOME/.gemini/antigravity-cli/` + agyOverride + `"` if kind == "fish" { fq := func(v string) string { return "'" + strings.NewReplacer(`\`, `\\`, "'", `\'`).Replace(v) + "'" } return "function agy\n" + " set -l m (sed -n " + fq(agyDistroModel) + " " + settings + " 2>/dev/null | head -n 1)\n" + " if test -z \"$m\"\n command agy $argv\n return\n end\n" + + " for a in $argv\n switch $a\n case 'remote-control' '--remote-control' '-remote-control' '--remote-control=*'\n command agy $argv\n return\n end\n end\n" + " for a in $argv\n switch $a\n case '--model' '--model=*' '-model' '-model=*'\n set m ''\n end\n end\n" + " if test -n \"$m\"\n set argv --model $m $argv\n end\n" + + " set argv --settings " + settings + " $argv\n" + " env GEMINI_API_KEY=" + fq(key) + " GOOGLE_GEMINI_BASE_URL=" + fq(gw) + " agy $argv\nend" } return agyPosixHead + " local m a\n" + " m=$(sed -n " + q(agyDistroModel) + " " + settings + " 2>/dev/null | head -n 1)\n" + ` if [ -z "$m" ]; then command agy "$@"; return; fi` + "\n" + + ` for a in "$@"; do case "$a" in remote-control|--remote-control|--remote-control=*|-remote-control) command agy "$@"; return;; esac; done` + "\n" + ` for a in "$@"; do case "$a" in --model|--model=*|-model|-model=*) m=;; esac; done` + "\n" + ` if [ -n "$m" ]; then set -- --model "$m" "$@"; fi` + "\n" + + " set -- --settings " + settings + ` "$@"` + "\n" + " GEMINI_API_KEY=" + q(key) + " GOOGLE_GEMINI_BASE_URL=" + q(gw) + ` command agy "$@"` + "\n}" } @@ -218,34 +250,18 @@ func agyIn(at place) *Agent { home := at.home dir := at.open(filepath.Join(home, ".gemini", "antigravity-cli")) path := filepath.Join(dir, "settings.json") - get := jsonGet(path, "model") - provider := jsonGet(path, "modelProvider") - stashModel, stashProvider := "agy:"+path+":model", "agy:"+path+":modelProvider" - // setModels writes customModels with the user's own and, when with, - // magpie's; none left takes the key out - setModels := func(with bool) error { - ms := map[string]any{} - for k, v := range agyCustom(path) { - if !strings.HasPrefix(k, magpieID+"/") { - ms[k] = v - } + over := filepath.Join(dir, agyOverride) + settingsModel, overModel := jsonGet(path, "model"), jsonGet(over, "model") + provider := jsonGet(over, "modelProvider") + // the model is magpie's while its own file names one; a settings.json + // still wired by an older magpie says so too, until migrate moves it + get := func() string { + if m := overModel(); usesMagpie(m) { + return m } - if with { - for _, m := range sharedModels("agy") { - ms[magpieID+"/"+m.ID] = map[string]string{"apiProvider": "API_PROVIDER_GOOGLE_GEMINI", "modelName": m.ID} - } - } - if len(ms) > 0 { - return edit.SetJSON(path, edit.KV{Path: agyModels, Value: ms}) - } - if err := edit.DelJSON(path, agyModels); err != nil { - return err - } - if v, ok := edit.GetJSON(path, "customModelsConfig"); ok && strings.TrimSpace(v) == "{}" { - return edit.DelJSON(path, "customModelsConfig") - } - return nil + return settingsModel() } + stashModel, stashProvider := "agy:"+path+":model", "agy:"+path+":modelProvider" // put sets key to v, or takes it out for "" put := func(key, v string) error { if v == "" { @@ -253,6 +269,59 @@ func agyIn(at place) *Agent { } return edit.SetJSON(path, edit.KV{Path: key, Value: v}) } + // ownModels is the user's own custom models, as settings.json has them + ownModels := func() map[string]any { + ms := map[string]any{} + for k, v := range agyCustom(path) { + if !strings.HasPrefix(k, magpieID+"/") { + ms[k] = v + } + } + return ms + } + // writeOver writes magpie's settings file: the provider, the model and + // every custom model, the user's own too, as agy takes the key whole + writeOver := func(model string) error { + ms := ownModels() + for _, m := range sharedModels("agy") { + ms[magpieID+"/"+m.ID] = map[string]string{"apiProvider": "API_PROVIDER_GOOGLE_GEMINI", "modelName": m.ID} + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + return edit.SetJSON(over, edit.KV{Path: "modelProvider", Value: "gemini"}, edit.KV{Path: "model", Value: model}, edit.KV{Path: agyModels, Value: ms}) + } + dropOver := func() error { + if err := os.Remove(over); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + // migrate takes what an older magpie wrote into settings.json out of + // it, the user's model and provider back; it returns the model that + // was magpie's there, "" when settings.json was never wired + migrate := func() (string, error) { + m := settingsModel() + if !usesMagpie(m) { + return "", nil + } + if err := put("modelProvider", unstash(stashProvider)); err != nil { + return m, err + } + if err := put("model", unstash(stashModel)); err != nil { + return m, err + } + if ms := ownModels(); len(ms) > 0 { + return m, edit.SetJSON(path, edit.KV{Path: agyModels, Value: ms}) + } + if err := edit.DelJSON(path, agyModels); err != nil { + return m, err + } + if v, ok := edit.GetJSON(path, "customModelsConfig"); ok && strings.TrimSpace(v) == "{}" { + return m, edit.DelJSON(path, "customModelsConfig") + } + return m, nil + } // the function agy, in this machine's shells or the distro's distro := at.sys != nil gw, key := at.gw, func() string { return agentKeyAt("agy", at.gw()) } @@ -278,7 +347,7 @@ func agyIn(at place) *Agent { if !distro { return AgyLaunch(model) } - return agyLaunchAt(gw(), key(), model, false) + return agyLaunchAt(gw(), key(), strings.TrimRight(filepath.ToSlash(home), "/")+"/.gemini/antigravity-cli/"+agyOverride, model, false) } return &Agent{ ID: "agy", Name: "Antigravity CLI", Icon: "antigravity-color", Aliases: []string{"antigravity-cli"}, Spelled: prefixed, NoNames: true, @@ -296,12 +365,19 @@ func agyIn(at place) *Agent { return "agy" }, Sync: func() error { - on := usesMagpie(get()) + m, err := migrate() + if err != nil { + return err + } + if m == "" { + m = overModel() + } + on := usesMagpie(m) shell(on) if !on { return nil } - return setModels(true) + return writeOver(m) }, Notice: func() string { v := get() @@ -325,11 +401,11 @@ func agyIn(at place) *Agent { if !usesMagpie(v) { return "" } - if _, ok := agyCustom(path)[v]; !ok { - return "Antigravity CLI's custom model " + v + " (settings.json) is gone, so it no longer reaches magpie" + if _, ok := agyCustom(over)[v]; !ok { + return "Antigravity CLI's custom model " + v + " (" + agyOverride + ") is gone, so it no longer reaches magpie" } if p := provider(); p != "gemini" { - return "Antigravity CLI's modelProvider (settings.json) is " + orDefault(p) + ", not gemini, so it asks Google directly" + return "Antigravity CLI's modelProvider (" + agyOverride + ") is " + orDefault(p) + ", not gemini, so it asks Google directly" } // a distro's function names the gateway's address: one WSL // changed on a restart (NAT) no longer reaches it @@ -346,38 +422,28 @@ func agyIn(at place) *Agent { Key: "model", Label: "model", Get: get, Set: func(v string) error { - cur := get() + if _, err := migrate(); err != nil { + return err + } + cur := overModel() if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { - if !usesMagpie(cur) { - stash(map[string]string{stashModel: cur, stashProvider: provider()}) - } - if err := setModels(true); err != nil { - return err - } - if err := edit.SetJSON(path, edit.KV{Path: "modelProvider", Value: "gemini"}, edit.KV{Path: "model", Value: v}); err != nil { + if err := writeOver(v); err != nil { return err } shell(true) return nil } + // back to the user's own: settings.json was never touched if usesMagpie(cur) { - // back to what the user had - if v == "" { - v = unstash(stashModel) - } else { - forget(stashModel) - } - if err := put("modelProvider", unstash(stashProvider)); err != nil { + if err := dropOver(); err != nil { return err } - } - if err := put("model", v); err != nil { - return err - } - if usesMagpie(cur) { shell(false) } - return setModels(false) + if v == "" { + return nil + } + return put("model", v) }, Options: func(cur map[string]string) []Option { custom := agyCustom(path) diff --git a/internal/agent/agy_posix_test.go b/internal/agent/agy_posix_test.go index f5d6a91a0..6f28fc612 100644 --- a/internal/agent/agy_posix_test.go +++ b/internal/agent/agy_posix_test.go @@ -28,7 +28,7 @@ func TestAgyFunctionInEveryPOSIXShell(t *testing.T) { dir := t.TempDir() bin := filepath.Join(dir, "bin") home := filepath.Join(dir, "home") - settings := filepath.Join(home, ".gemini", "antigravity-cli", "settings.json") + settings := filepath.Join(home, ".gemini", "antigravity-cli", "magpie-settings.json") if err := os.MkdirAll(bin, 0o755); err != nil { t.Fatal(err) } @@ -45,7 +45,7 @@ func TestAgyFunctionInEveryPOSIXShell(t *testing.T) { gone := filepath.Join(dir, "no such magpie") for _, c := range []struct{ name, fn, want string }{ {"here", agyFunction("posix", gone), "agy key= gw= args=a b"}, - {"distro", agyDistroFunction("posix", "k'1", "http://172.20.0.1:3425"), "agy key=k'1 gw=http://172.20.0.1:3425 args=--model magpie/relay/glm-4.6 a b"}, + {"distro", agyDistroFunction("posix", "k'1", "http://172.20.0.1:3425"), "agy key=k'1 gw=http://172.20.0.1:3425 args=--settings " + settings + " --model magpie/relay/glm-4.6 a b"}, } { profile := filepath.Join(dir, c.name+".profile") body := "alias agy='echo ALIAS' 2>/dev/null\n# >>> magpie agy >>>\n" + c.fn + "\n# <<< magpie agy <<<\n" diff --git a/internal/agent/agy_test.go b/internal/agent/agy_test.go index 40180330e..12464d9e3 100644 --- a/internal/agent/agy_test.go +++ b/internal/agent/agy_test.go @@ -59,7 +59,19 @@ func TestAgy(t *testing.T) { if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { t.Fatal(err) } - m := read() + // agy's own settings.json is the user's, untouched: with modelProvider + // gemini in it every agy runs on an API key and has no Google account, + // so no remote control (baysonfox on X) + var was map[string]any + json.Unmarshal([]byte(orig), &was) + if agyJSON(read()) != agyJSON(was) { + t.Fatalf("settings.json written:\n%s", agyRead(t, path)) + } + over := filepath.Join(filepath.Dir(path), "magpie-settings.json") + var m map[string]any + if err := json.Unmarshal([]byte(agyRead(t, over)), &m); err != nil { + t.Fatal(err) + } if m["model"] != "magpie/deepseek/pro" || m["modelProvider"] != "gemini" { t.Fatalf("not wired: %v", m) } @@ -71,25 +83,26 @@ func TestAgy(t *testing.T) { if cm["magpie/deepseek/flash"] == nil || cm["mine"] == nil { t.Fatalf("custom models: %v", cm) } - if ws, _ := m["trustedWorkspaces"].([]any); len(ws) != 1 { - t.Fatalf("other keys lost: %v", m) - } if d := a.Drift(); d != nil { t.Fatalf("drift: %+v", d) } l := a.Launch() - if want := "GEMINI_API_KEY=" + gateway.TokenFor("agy") + " GOOGLE_GEMINI_BASE_URL=" + gateway.URL() + " agy --model 'magpie/deepseek/pro'"; runtime.GOOS != "windows" && l != want { + if want := "GEMINI_API_KEY=" + gateway.TokenFor("agy") + " GOOGLE_GEMINI_BASE_URL=" + gateway.URL() + " agy --settings '" + over + "' --model 'magpie/deepseek/pro'"; runtime.GOOS != "windows" && l != want { t.Fatalf("launch: %q", l) } if n := a.Notice(); !strings.Contains(n, l) { t.Fatalf("notice: %q", n) } - // another of magpie's keeps the user's stashed + if got := a.Field("model").Get(); got != "magpie/deepseek/pro" { + t.Fatalf("model: %q", got) + } + // another of magpie's if err := a.Apply("model", "magpie/deepseek/flash"); err != nil { t.Fatal(err) } - // something else sets modelProvider back: agy asks Google directly - os.WriteFile(path, []byte(strings.Replace(agyRead(t, path), `"gemini"`, `"vertex"`, 1)), 0o644) + // something else sets modelProvider back in magpie's file: agy asks + // Google directly + os.WriteFile(over, []byte(strings.Replace(agyRead(t, over), `"gemini"`, `"vertex"`, 1)), 0o644) if d := a.Drift(); d == nil || d.Kind != "unwired" { t.Fatalf("drift: %+v", d) } @@ -98,21 +111,53 @@ func TestAgy(t *testing.T) { if len(opts) == 0 || opts[0].Value != "mine" || opts[0].Group != "Antigravity CLI" { t.Fatalf("options: %+v", opts) } - // as installed: the user's model and provider back, magpie's models out + // as installed: magpie's file gone, settings.json as it was if err := a.Apply("model", ""); err != nil { t.Fatal(err) } - var back, was map[string]any - json.Unmarshal([]byte(agyRead(t, path)), &back) - json.Unmarshal([]byte(orig), &was) - if agyJSON(back) != agyJSON(was) { + if _, err := os.Stat(over); err == nil { + t.Fatal("magpie's settings file left") + } + if agyJSON(read()) != agyJSON(was) { t.Fatalf("not restored:\n%s", agyRead(t, path)) } if a.Launch() != "" { t.Fatal("launch after reset") } - // with nothing of the user's, reset leaves nothing of magpie's + // the user picks one of their own while on magpie's: it is theirs in + // settings.json, and magpie's file is gone + a.Apply("model", "magpie/deepseek/pro") + if err := a.Apply("model", "mine"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(over); err == nil || a.Launch() != "" { + t.Fatal("still on magpie after picking their own") + } + + // wired by an older magpie (modelProvider and model in settings.json, + // the user's stashed): the next start moves it out of there + os.WriteFile(path, []byte(orig), 0o644) + stash(map[string]string{"agy:" + path + ":model": "mine", "agy:" + path + ":modelProvider": "vertex"}) + old := map[string]any{} + json.Unmarshal([]byte(orig), &old) + old["model"], old["modelProvider"] = "magpie/deepseek/pro", "gemini" + oc := old["customModelsConfig"].(map[string]any)["customModels"].(map[string]any) + oc["magpie/deepseek/pro"] = map[string]any{"apiProvider": "API_PROVIDER_GOOGLE_GEMINI", "modelName": "deepseek/pro"} + b, _ := json.Marshal(old) + os.WriteFile(path, b, 0o644) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if agyJSON(read()) != agyJSON(was) { + t.Fatalf("settings.json not given back:\n%s", agyRead(t, path)) + } + if !strings.Contains(a.Launch(), "--model 'magpie/deepseek/pro'") || a.Drift() != nil { + t.Fatalf("after the move: %q %+v", a.Launch(), a.Drift()) + } + a.Apply("model", "") + + // with nothing of the user's, magpie leaves nothing in settings.json os.WriteFile(path, []byte("{\n \"trustedWorkspaces\": []\n}\n"), 0o644) a.Apply("model", "magpie/deepseek/pro") a.Apply("model", "") diff --git a/internal/agent/wsl_agy_test.go b/internal/agent/wsl_agy_test.go index 7ec1ba5ba..d044db56e 100644 --- a/internal/agent/wsl_agy_test.go +++ b/internal/agent/wsl_agy_test.go @@ -89,9 +89,14 @@ func TestWSLAgyPick(t *testing.T) { if !strings.HasPrefix(key, "wsl-") || !strings.HasSuffix(key, "-agy") { t.Fatalf("key %q", key) } - settings := filepath.Join(dhome, ".gemini", "antigravity-cli", "settings.json") - if m, _ := edit.GetJSON(settings, "model"); m != "magpie/relay/glm-4.6" { - t.Fatalf("settings.json:\n%s", readFile(settings)) + over := filepath.Join(dhome, ".gemini", "antigravity-cli", "magpie-settings.json") + if m, _ := edit.GetJSON(over, "model"); m != "magpie/relay/glm-4.6" { + t.Fatalf("magpie-settings.json:\n%s", readFile(over)) + } + // agy's own settings.json is left as it is (remote control needs agy + // off an API key) + if m, _ := edit.GetJSON(filepath.Join(dhome, ".gemini", "antigravity-cli", "settings.json"), "modelProvider"); m != "" { + t.Fatalf("settings.json has modelProvider %q", m) } for _, p := range []string{bashrc, zshrc} { body := readFile(p) @@ -169,6 +174,7 @@ func TestWSLAgyFunctionRuns(t *testing.T) { t.Fatal(err) } gw := "http://172.20.0.1:" + gateway.Port() + over := filepath.Join(dhome, ".gemini", "antigravity-cli", "magpie-settings.json") bin := t.TempDir() writeFile(t, filepath.Join(bin, "agy"), "#!/bin/sh\necho \"key=$GEMINI_API_KEY url=$GOOGLE_GEMINI_BASE_URL args=$*\"\n") os.Chmod(filepath.Join(bin, "agy"), 0o755) @@ -188,16 +194,21 @@ func TestWSLAgyFunctionRuns(t *testing.T) { } return strings.TrimSpace(string(out)) } - if got := run("-p 'hi there'"); got != on+" args=--model magpie/relay/glm-4.6 -p hi there" { + if got := run("-p 'hi there'"); got != on+" args=--settings "+over+" --model magpie/relay/glm-4.6 -p hi there" { t.Errorf("%s: %s", c.sh, got) } - if got := run("--model=own -p hi"); got != on+" args=--model=own -p hi" { + if got := run("--model=own -p hi"); got != on+" args=--settings "+over+" --model=own -p hi" { t.Errorf("%s, a model given: %s", c.sh, got) } } + // remote control needs the Google sign-in: plain, whatever the model + rc := exec.Command("bash", "-c", `. "$HOME/.bashrc"; agy remote-control start; agy --remote-control`) + rc.Env = []string{"HOME=" + dhome, "PATH=" + bin + ":/usr/bin:/bin"} + if out, err := rc.CombinedOutput(); err != nil || strings.TrimSpace(string(out)) != "key= url= args=remote-control start\nkey= url= args=--remote-control" { + t.Fatalf("remote control: %v %s", err, out) + } // the user picked their own model in agy: it starts as it is - settings := filepath.Join(dhome, ".gemini", "antigravity-cli", "settings.json") - if err := edit.SetJSON(settings, edit.KV{Path: "model", Value: "gemini-3-pro"}); err != nil { + if err := a.Field("model").Set("gemini-3-pro"); err != nil { t.Fatal(err) } cmd := exec.Command("bash", "-c", `. "$HOME/.bashrc"; agy -p hi`) diff --git a/internal/cli/agy_cli.go b/internal/cli/agy_cli.go index abea2cd34..27222ee5d 100644 --- a/internal/cli/agy_cli.go +++ b/internal/cli/agy_cli.go @@ -14,15 +14,18 @@ import ( // `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 +// gateway, key, model and settings file (--settings, magpie-settings.json +// beside agy's own settings.json) while that file names one of magpie's +// models, and as it is otherwise, remote control's too (it needs agy's +// Google sign-in). 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 (not when you give --model yourself); every argument is +--settings and --model (not when you give +--model yourself, nor for remote-control, which needs your Google sign-in); 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. @@ -53,6 +56,7 @@ func agyCmd(args []string) (ok bool, err error) { for _, kv := range env { fmt.Println(kv) } + fmt.Println("settings=" + agent.AgySettings()) fmt.Println("model=" + model) return true, nil } @@ -76,6 +80,11 @@ func agyRun(args []string) error { } env := os.Environ() start, model := agent.AgyStart() + // remote control needs the Google sign-in, which a session on an API + // key (magpie's models) doesn't have: it runs as agy is on its own + if slices.ContainsFunc(args, agent.AgyRemote) { + model = "" + } if model != "" { env = slices.DeleteFunc(env, func(kv string) bool { k, _, _ := strings.Cut(kv, "=") @@ -85,6 +94,7 @@ func agyRun(args []string) error { if !slices.ContainsFunc(args, modelFlag) { args = append([]string{"--model", model}, args...) } + args = append([]string{"--settings", agent.AgySettings()}, args...) } return agyExec(bin, args, env) } diff --git a/internal/cli/agy_cli_test.go b/internal/cli/agy_cli_test.go index eb8051a06..c7f5fb358 100644 --- a/internal/cli/agy_cli_test.go +++ b/internal/cli/agy_cli_test.go @@ -17,7 +17,7 @@ import ( // as it is off magpie. func TestAgyRun(t *testing.T) { home := helpHome(t) - settings := filepath.Join(home, ".gemini", "antigravity-cli", "settings.json") + settings := filepath.Join(home, ".gemini", "antigravity-cli", "magpie-settings.json") os.MkdirAll(filepath.Dir(settings), 0o755) t.Setenv("GEMINI_API_KEY", "users-own") t.Setenv("GOOGLE_GEMINI_BASE_URL", "") @@ -43,11 +43,11 @@ func TestAgyRun(t *testing.T) { 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"}}, + {nil, []string{"--settings", settings, "--model", "magpie/deepseek/pro"}}, + {[]string{"--help"}, []string{"--settings", settings, "--model", "magpie/deepseek/pro", "--help"}}, + {[]string{"-p", "hi", "--model", "mine"}, []string{"--settings", settings, "-p", "hi", "--model", "mine"}}, + {[]string{"--model=mine"}, []string{"--settings", settings, "--model=mine"}}, + {[]string{"-model", "mine"}, []string{"--settings", settings, "-model", "mine"}}, } { if _, err := runOut(t, append([]string{"agy", "run"}, c.in...)...); err != nil { t.Fatal(err) @@ -60,10 +60,21 @@ func TestAgyRun(t *testing.T) { } } 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 { + if want := "GEMINI_API_KEY=" + gateway.TokenFor("agy") + "\nGOOGLE_GEMINI_BASE_URL=" + gateway.URL() + "\nsettings=" + settings + "\nmodel=magpie/deepseek/pro\n"; err != nil || out != want { t.Fatalf("agy env: %q %v", out, err) } + // remote control needs agy's Google sign-in: plain, with the user's own + // environment, however magpie has agy wired (baysonfox on X) + for _, in := range [][]string{{"remote-control", "start"}, {"--remote-control"}, {"-p", "hi", "--remote-control"}} { + if _, err := runOut(t, append([]string{"agy", "run"}, in...)...); err != nil { + t.Fatal(err) + } + if !slices.Equal(args, in) || !slices.Equal(envOf("GEMINI_API_KEY"), []string{"users-own"}) { + t.Fatalf("agy run %v: %v, key %v", in, args, envOf("GEMINI_API_KEY")) + } + } + // off magpie: as it is os.WriteFile(settings, []byte(`{"model": "mine"}`), 0o644) if _, err := runOut(t, "agy", "run", "-p", "hi"); err != nil { diff --git a/internal/gui/tests/agy-launch.test.cjs b/internal/gui/tests/agy-launch.test.cjs index 4b60a44aa..69ba97877 100644 --- a/internal/gui/tests/agy-launch.test.cjs +++ b/internal/gui/tests/agy-launch.test.cjs @@ -15,7 +15,7 @@ const { test } = require("node:test"); const { chromium, webkit } = require("playwright"); const assets = path.resolve(__dirname, "../assets"); -const LAUNCH = "GEMINI_API_KEY=magpie-agy GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:3425 agy --model 'magpie/deepseek/pro'"; +const LAUNCH = "GEMINI_API_KEY=magpie-agy GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:3425 agy --settings '/home/u/.gemini/antigravity-cli/magpie-settings.json' --model 'magpie/deepseek/pro'"; const models = [{ value: "magpie/deepseek/pro", label: "magpie/deepseek/pro", ref: "deepseek/pro" }, { value: "model-b", label: "model-b" }]; const agent = (id, name, launch) => ({ id, name, path: "/test/" + id, launch, wired: true, // on a magpie model (#726: a connected one is in view)