agent: agy moves onto the community agent-agy plugin
The built-in agy agent (Antigravity CLI) is the first built-in agent a community agent plugin serves, as the retired subscriptions moved onto provider plugins. While @magpie-community/agent-agy is installed and on, magpie's agy is the plugin's: the built-in leaves the list (here and in WSL), its id and aliases are the plugin's, and what the built-in wired is handed over. Turned off or removed, the built-in is back. Nothing is forced yet; the forced install and the built-in's retirement come once the plugin is on npm and a real run with it is on record. The plugin (plugins ebcff866, 0.2.0) follows the built-in since0cc91af3d: its config is magpie's own magpie-settings.json, handed to agy with --settings, agy's settings.json is only read, and remote-control runs as agy is. What an agent plugin can say now (agentplug; docs/reference.md and the site's plugins pages, en/zh/ja, and llms-full.txt): - base: the agent's own settings file, read for the user's own model and passed to connect and own; needs launch.args with {config}, and stepping out removes magpie's config file whole; - launch {env, model, args, plain}: `magpie start <id>` and the shell functions (posix, fish, PowerShell, a WSL distro's) put args before the model flag, and run a plain word or flag as the agent is; - own({config, base, model}), effort, wsl, aliases. Moving over (plugged_moved.go): agentMovers names agy's package; agyHandover gives back a settings.json an older built-in wired (Sync), then makes magpie-settings.json the plugin's stash, so the plugin's agent reads as connected and stepping out removes the file. Run (mote, macOS 27, Go 1.26.8) atfe8c05e0c, the base before the last rebase: - go test internal/agent (507s), agentplug, sessions, edit, update, plugin: ok. - internal/cli and internal/gui: red only on main's own reds, the same at origin/main8fe720453: TestModelUsageAlignsEveryDescription and TestModelUsageLinesUpItsDescriptions (#6104), TestSettingsSaveKeepsWhatItDoesNotSend (#6103), TestCoreScriptBudget (#6116, filed now). - GUI, both engines, and site node --test: agy-effort, agy-launch, library-rtk-agy, gui-de, gui-zh-tw, i18n-en-no-cjk, i18n-keys, plugin-page-foreign-error, site/*.test.mjs: 114 pass. - vet: macOS, GOOS=windows, Linux in WSL (-tags gtk3); gofmt clean. - The shell functions with a config path holding a space: bash and zsh on mote, PowerShell on Windows (win-run), bash in WSL. - Broken by hand: TestAgyPlugin red with Args, Plain or the file's removal taken out. At 20d807d92 (rebased on8fe720453): vet (macOS, windows) ok, agentplug and internal/agent -run 'Agy|Plugged' ok, agy-launch and i18n-keys pass; plugin-page-foreign-error is red there and at plain origin/main8fe720453, from that commit (#6117), not this change. Plugins repo: bun test packages/agent-agy 4 pass. Not tried: fish (on none of the machines); a real agy run with the plugin at 0.2.0 (the 0.1.0 design ran for real in a sandbox HOME, the settings.json one this replaces); Windows and WSL agy with the plugin; an install from npm: @magpie-community/agent-agy isn't on npm yet, so until its first publish no user is moved.
This commit is contained in:
+31
-1
@@ -1584,7 +1584,37 @@ call costs. Each is left out when it isn't known (a routing group has no
|
||||
"pricing": { "prompt": "0.0000003", "completion": "0.0000012", "input_cache_read": "0.00000003" } }
|
||||
```
|
||||
|
||||
An id magpie's own agents use is refused. In the market an agent's entry has
|
||||
An agent that takes the gateway only from how it is started, not from a
|
||||
file, says so in `launch`: `{ env: { GEMINI_API_KEY: "{key}",
|
||||
GOOGLE_GEMINI_BASE_URL: "{url}" }, model: "--model" }`. While its model is
|
||||
one of magpie's, magpie puts a function named after its `bin` in the
|
||||
user's shells (zsh, bash, fish, PowerShell) that runs `magpie <id> run`,
|
||||
which starts the agent with those variables and the model flag; its own
|
||||
model takes the function out. A value is `{key}`, `{url}` or `{v1}`, a
|
||||
path after the address at most, so nothing else a plugin says reaches a
|
||||
shell profile. Beside `launch`:
|
||||
|
||||
- `merge`: key paths of a json config whose object `connect` returns
|
||||
magpie's members of, written beside the user's own and taken out alone
|
||||
(`["customModelsConfig.customModels"]`);
|
||||
- `launch.args`: flags put before the user's arguments, each `{config}`,
|
||||
the config's path (`{ "--settings": "{config}" }`); `launch.plain`:
|
||||
arguments that start the agent as it is, never on the gateway
|
||||
(`["remote-control"]`);
|
||||
- `base`: for a config handed over by `launch.args`, so magpie's own
|
||||
file, the agent's own settings file: `connect` and `own` get it as
|
||||
`base`, the user's own model is written there, and stepping out takes
|
||||
the config away whole;
|
||||
- `own({ config, base, model })`: the user's own models for the picker, each
|
||||
`{ value, model, direct }`, `direct` naming the vendor it goes to;
|
||||
- `effort: true`, the Effort field; `wsl: true`, the agent in WSL
|
||||
distros too; `aliases`, other names `magpie <name>` takes.
|
||||
|
||||
An id magpie's own agents use is refused, except a built-in's that moves
|
||||
onto a community plugin: with `@magpie-community/agent-agy` installed and
|
||||
on, `agy` is the plugin's, and what the built-in had wired is handed over
|
||||
as the plugin's, so nothing changes for the user; with it off or removed,
|
||||
agy is connected no more and the built-in is back. In the market an agent's entry has
|
||||
`"kind": "agent"` (`@magpie-community/agent-<name>`). An agent that needs a
|
||||
runtime (a timer, a file watched) keeps its agent file in moejs and adds a
|
||||
Bun module as the package's `main`; a package that declares `magpie.agent`
|
||||
|
||||
@@ -37,6 +37,7 @@ something else shows up as drift.
|
||||
| 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.<model>.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:<id>:<path>` (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`, `--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) |
|
||||
| Built-ins a plugin serves | `agentMovers` names the community agent plugin a built-in agent moves onto (`agy`: `@magpie-community/agent-agy`). While that plugin is installed and on, `dropMoved` leaves the built-in out (`onMachine`, and `wslKind.served` in a distro), and the plugin's agent takes its id and aliases. Its desc says what the built-in did in code. `config` is magpie's own `magpie-settings.json` and `base` agy's `settings.json` (`Desc.Base`, `bf` in `plugged`): `connect` and `own` get `base` parsed, the user's own model is written there, `get` reads it off magpie, and stepping out removes the config whole, so `settings.json` is never written while on magpie and remote control keeps its Google sign-in (0cc91af3d). `launch` (`{env, model, args, plain}`) gives it the same shell function and `magpie <id> run`/`env` (`launchSpec` in [`plugged_launch.go`](../../internal/agent/plugged_launch.go); `startCmd` in [`start_cli.go`](../../internal/cli/start_cli.go) finds any agent with `Start` by id or alias, `agent.Starter`): `args` `{"--settings": "{config}"}` go before the model flag, filled with the config as the agent's system spells it (`env` prints them as `settings=<file>`, which the PowerShell function reads), and a `plain` argument (`remote-control`) runs the agent as it is, in `startRun` (`Starting.Plained`) and in a distro's or PowerShell's function, which have no magpie to ask (`TestPluggedDistroFunctionArgsAndPlain`, `TestPluggedPowerShellFunctionArgsAndPlain`). `effort`, `wsl` and `aliases` are the rest. A `launch.env` value is `{key}`, `{url}` or `{v1}` with a path at most (`envValueOK`), an `args` value only `{config}`, and a `plain` word a subcommand or flag, so nothing else a plugin says reaches a shell profile (`TestLaunchSaysOnlyWhatAShellTakesAsItIs`, `TestBaseIsForAHandedConfig`). What the built-in wired is handed over the first time the plugin's agent reads its file with nothing stashed (`handedOver`, `agyHandover` in [`plugged_moved.go`](../../internal/agent/plugged_moved.go)): a `settings.json` an older built-in wired is given back first, by the built-in's own `Sync` (its `migrate`, then `magpie-settings.json` written); then, while `magpie-settings.json` names one of magpie's models, its keys become the plugin's `Had` as not there before, so the plugin's own model or Disconnect takes the file away and leaves `settings.json` as the user had it. Turning the plugin off disconnects it as any plugin agent's (below), and the built-in is back (`TestAgyPlugin`, `TestAgyHandedToPlugin`, `TestAgyOldWiringHandedToPlugin`, `TestAgyHandedOverUnwire`). | [`plugged_moved.go`](../../internal/agent/plugged_moved.go), [`plugged_launch.go`](../../internal/agent/plugged_launch.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-<distro>.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:<gateway port>` 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:<port>/<WSL key>`, 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 `<config>/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 <file> 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) |
|
||||
|
||||
|
||||
@@ -291,6 +291,10 @@ type Agent struct {
|
||||
// to start it on magpie, a function magpie gave their shells (agy);
|
||||
// "" when there is none, and Launch is the way.
|
||||
Typed func() string
|
||||
// Start, for such an agent, is what `magpie <id> run` starts it with:
|
||||
// its command, the variables and its model flag, the model "" while
|
||||
// it isn't on magpie's, when it starts as it is.
|
||||
Start func() Starting
|
||||
// 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
|
||||
|
||||
@@ -44,8 +44,10 @@ func init() {
|
||||
// an agy conversation started on magpie's gateway is picked up again
|
||||
// there, with the variables and --model it was started with
|
||||
sessions.AgyStart = func() string {
|
||||
home, _ := homes()
|
||||
return agy(home).Launch()
|
||||
if a, _ := FindIn(local(), "agy"); a != nil && a.Launch != nil {
|
||||
return a.Launch()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
// a Copilot CLI signed in inside a running distro (#723)
|
||||
provider.CopilotWSLDirs = copilotWSLDirs
|
||||
@@ -248,8 +250,27 @@ func local() []*Agent {
|
||||
return append(own, pluggedAgents(home, own, nil)...)
|
||||
}
|
||||
|
||||
// onMachine are builtins but those in WSL.
|
||||
func onMachine(home, cfg string) []*Agent {
|
||||
// Starter is the agent on this machine typed as q, by its id or an alias
|
||||
// (no prefix: every argument after it is the agent's), that magpie starts
|
||||
// from the command line (Agent.Start); nil for none.
|
||||
func Starter(q string) *Agent {
|
||||
for _, a := range local() {
|
||||
if a.Start == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(a.ID, q) || slices.Contains(a.Aliases, strings.ToLower(q)) {
|
||||
return a
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// onMachine are builtins but those in WSL, and but those a plugin serves
|
||||
// now (agentMovers).
|
||||
func onMachine(home, cfg string) []*Agent { return dropMoved(onMachineAll(home, cfg)) }
|
||||
|
||||
// onMachineAll is onMachine with every built-in.
|
||||
func onMachineAll(home, cfg string) []*Agent {
|
||||
return append([]*Agent{
|
||||
claude(home),
|
||||
claudeDesktop(home),
|
||||
|
||||
+22
-26
@@ -75,12 +75,10 @@ func agySettingsFile() string {
|
||||
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"
|
||||
}
|
||||
// agyPlain are what ask agy for its remote control, which only a Google
|
||||
// sign-in has, never an API key's session: agy runs plain with one of
|
||||
// them (alone or with "=value").
|
||||
var agyPlain = []string{"remote-control", "--remote-control", "-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.
|
||||
@@ -91,20 +89,6 @@ func agyLaunchAt(gw, key, settings, model string, powershell bool) string {
|
||||
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 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) {
|
||||
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.
|
||||
@@ -364,6 +348,14 @@ func agyIn(at place) *Agent {
|
||||
}
|
||||
return "agy"
|
||||
},
|
||||
Start: func() Starting {
|
||||
s := Starting{Bin: "agy", Flag: "--model", Plain: agyPlain}
|
||||
if v := overModel(); usesMagpie(v) {
|
||||
s.Env, s.Model = []string{"GEMINI_API_KEY=" + key(), "GOOGLE_GEMINI_BASE_URL=" + gw()}, v
|
||||
s.Args = []string{"--settings", at.native(over)}
|
||||
}
|
||||
return s
|
||||
},
|
||||
Sync: func() error {
|
||||
m, err := migrate()
|
||||
if err != nil {
|
||||
@@ -471,7 +463,10 @@ func agyIn(at place) *Agent {
|
||||
}
|
||||
}
|
||||
|
||||
// agyEffortField is how hard agy's models reason, picked in its row. agy
|
||||
// agyEffortField is effortField for agy.
|
||||
func agyEffortField(on func() bool) Field { return effortField("agy", on) }
|
||||
|
||||
// effortField is how hard agy's models reason, picked in its row. agy
|
||||
// 1.5 has --effort for one session only, which it allows for a model
|
||||
// whose name it knows and turns away for magpie's ("not adjustable" in
|
||||
// /effort, xyenon on Discord), and settings.json has no key for it
|
||||
@@ -480,17 +475,18 @@ func agyIn(at place) *Agent {
|
||||
// requests for the level picked here (provider.AgentEffort), as the
|
||||
// model takes it (withGeminiEffort); with none they go as agy asks.
|
||||
// Shown only while agy is on magpie's models, and never read at a
|
||||
// stopped distro (#3896).
|
||||
func agyEffortField(on func() bool) Field {
|
||||
// stopped distro (#3896). An agent a plugin adds that says effort has
|
||||
// one as well, under its id.
|
||||
func effortField(id string, on func() bool) Field {
|
||||
return Field{
|
||||
Key: "effort", Label: "effort",
|
||||
Get: func() string { return provider.AgentEffort("agy") },
|
||||
Set: func(v string) error { return provider.SetAgentEffort("agy", v) },
|
||||
Get: func() string { return provider.AgentEffort(id) },
|
||||
Set: func(v string) error { return provider.SetAgentEffort(id, v) },
|
||||
Options: func(map[string]string) []Option {
|
||||
if !on() {
|
||||
return nil
|
||||
}
|
||||
return pickedEfforts("agy")
|
||||
return pickedEfforts(id)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,8 +36,8 @@ func TestAgyShell(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if env, m := AgyStart(); env != nil || m != "" {
|
||||
t.Fatalf("AgyStart before: %v %q", env, m)
|
||||
if s := a.Start(); s.Env != nil || s.Model != "" {
|
||||
t.Fatalf("Start before: %+v", s)
|
||||
}
|
||||
if err := a.Apply("model", "magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -58,9 +58,8 @@ func TestAgyShell(t *testing.T) {
|
||||
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)
|
||||
if s := a.Start(); s.Model != "magpie/deepseek/pro" || strings.Join(s.Env, " ") != "GEMINI_API_KEY="+gateway.TokenFor("agy")+" GOOGLE_GEMINI_BASE_URL="+gateway.URL() {
|
||||
t.Fatalf("Start: %+v", s)
|
||||
}
|
||||
|
||||
// wired before the function was given: the next start gives it
|
||||
|
||||
+282
-21
@@ -16,6 +16,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
@@ -27,6 +28,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
@@ -60,6 +62,10 @@ type pluggedStash struct {
|
||||
// before them has neither, and its file's name says its format
|
||||
Spec string `json:"spec,omitempty"`
|
||||
Format string `json:"format,omitempty"`
|
||||
// Made are the objects a merge key sits in (and the key itself) that
|
||||
// the file didn't have before magpie's first write, shallowest
|
||||
// first: each is taken out again when it is left empty
|
||||
Made []string `json:"made,omitempty"`
|
||||
}
|
||||
|
||||
// PluginErrors is why an agent a plugin adds isn't listed, by plugin
|
||||
@@ -109,7 +115,7 @@ func pluggedAgents(home string, builtin []*Agent, errs map[string]string) []*Age
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, plugged(home, p))
|
||||
out = append(out, plugged(here(home), p))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -123,12 +129,16 @@ func PluginPath(p string) string {
|
||||
|
||||
// pluggedPath is the file a plugin names, with ~ and $VAR as a shell
|
||||
// reads them.
|
||||
func pluggedPath(home, p string) string {
|
||||
func pluggedPath(home, p string) string { return pluggedPathEnv(home, p, os.Getenv) }
|
||||
|
||||
// pluggedPathEnv is pluggedPath with the variables getenv gives: none in
|
||||
// a WSL distro, whose variables magpie can't read.
|
||||
func pluggedPathEnv(home, p string, getenv func(string) string) string {
|
||||
p = os.Expand(p, func(k string) string {
|
||||
if k == "HOME" {
|
||||
return home
|
||||
}
|
||||
return os.Getenv(k)
|
||||
return getenv(k)
|
||||
})
|
||||
if p == "~" || strings.HasPrefix(p, "~/") {
|
||||
p = filepath.Join(home, p[1:])
|
||||
@@ -277,21 +287,94 @@ func (f pluggedFile) restore(key string, st pluggedStash) error {
|
||||
if err := f.set(kvs); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := len(st.Made) - 1; i >= 0; i-- {
|
||||
if v, ok := f.raw(st.Made[i]); ok && emptyObject(v) {
|
||||
if err := f.del(st.Made[i : i+1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
forget(key)
|
||||
return nil
|
||||
}
|
||||
|
||||
// plugged is the Agent of a plugin's agent at home.
|
||||
func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
// emptyObject says raw JSON v is {}.
|
||||
func emptyObject(v string) bool {
|
||||
var m map[string]json.RawMessage
|
||||
return json.Unmarshal([]byte(v), &m) == nil && m != nil && len(m) == 0
|
||||
}
|
||||
|
||||
// merged writes each object out has under one of merge's keys member by
|
||||
// member, beside what the user has there; the rest of out as it is.
|
||||
func merged(out map[string]any, merge []string) []edit.KV {
|
||||
var kvs []edit.KV
|
||||
for _, m := range merge {
|
||||
// connect's objects come as their JSON text (agentplug.keys)
|
||||
var obj map[string]json.RawMessage
|
||||
switch v := out[m].(type) {
|
||||
case json.RawMessage:
|
||||
if json.Unmarshal(v, &obj) != nil || obj == nil {
|
||||
continue
|
||||
}
|
||||
case map[string]any:
|
||||
obj = map[string]json.RawMessage{}
|
||||
for k, x := range v {
|
||||
b, _ := json.Marshal(x)
|
||||
obj[k] = b
|
||||
}
|
||||
default:
|
||||
continue
|
||||
}
|
||||
delete(out, m)
|
||||
for _, k := range sortedKeys(obj) {
|
||||
kvs = append(kvs, edit.KV{Path: m + "." + gjson.Escape(k), Value: obj[k]})
|
||||
}
|
||||
}
|
||||
return kvs
|
||||
}
|
||||
|
||||
// made are the objects of merge's keys, and those they sit in, that f
|
||||
// doesn't have, shallowest first.
|
||||
func (f pluggedFile) made(merge []string) []string {
|
||||
var out []string
|
||||
for _, m := range merge {
|
||||
parts := strings.Split(m, ".")
|
||||
for i := range parts {
|
||||
k := strings.Join(parts[:i+1], ".")
|
||||
if _, ok := f.raw(k); !ok && !slices.Contains(out, k) {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// plugged is the Agent of a plugin's agent at a place: this machine's
|
||||
// home, or a WSL distro's for one that says wsl.
|
||||
func plugged(at place, p *agentplug.Agent) *Agent {
|
||||
d := p.Desc
|
||||
id := d.ID
|
||||
f := pluggedFile{pluggedPath(home, d.Config), d.Format}
|
||||
home := at.home
|
||||
distro := at.sys != nil
|
||||
ppath := func(s string) string { return pluggedPath(home, s) }
|
||||
if distro {
|
||||
ppath = func(s string) string { return at.open(pluggedPathEnv(home, s, func(string) string { return "" })) }
|
||||
}
|
||||
f := pluggedFile{ppath(d.Config), d.Format}
|
||||
key := "plugin:" + id + ":" + f.path
|
||||
at := here(home)
|
||||
// bf: the agent's own settings file, where config is magpie's alone
|
||||
// (agentplug.Desc.Base): the user's model is there off magpie
|
||||
var bf *pluggedFile
|
||||
if d.Base != "" {
|
||||
bf = &pluggedFile{ppath(d.Base), d.Format}
|
||||
}
|
||||
saved := func() (pluggedStash, bool) {
|
||||
var st pluggedStash
|
||||
v := stashShared()[key]
|
||||
return st, v != "" && json.Unmarshal([]byte(v), &st) == nil
|
||||
if v == "" {
|
||||
return handedOver(id, at, f, p.Spec, key)
|
||||
}
|
||||
return st, json.Unmarshal([]byte(v), &st) == nil
|
||||
}
|
||||
save := func(st pluggedStash) {
|
||||
b, _ := json.Marshal(st)
|
||||
@@ -303,7 +386,21 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
st, ok := saved()
|
||||
return st, ok && f.wired(id, st)
|
||||
}
|
||||
restore := func(st pluggedStash) error { return f.restore(key, st) }
|
||||
// restore puts back what the user had; magpie's own file (with a
|
||||
// base) goes as a whole
|
||||
restore := func(st pluggedStash) error {
|
||||
if err := f.restore(key, st); err != nil || bf == nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Remove(f.path); err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// l: one that takes the gateway only from how it is started, config
|
||||
// as the agent names it
|
||||
l := newLaunch(d, at.native(f.path))
|
||||
gkey := func() string { return agentKeyAt(id, at.gw()) }
|
||||
// only: the agent picks its model itself among those connect writes
|
||||
// (#2374), so magpie writes no model, and the switch is its one field;
|
||||
// or it keeps its startup model in a file apart (sf), which its model
|
||||
@@ -312,7 +409,7 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
var sf *pluggedFile
|
||||
var skey string
|
||||
if d.Startup != nil {
|
||||
sf = &pluggedFile{pluggedPath(home, d.Startup.Config), d.Startup.Format}
|
||||
sf = &pluggedFile{ppath(d.Startup.Config), d.Startup.Format}
|
||||
skey = "plugin:" + id + ":" + sf.path
|
||||
}
|
||||
// startSaved is what magpie keeps of the startup file
|
||||
@@ -408,12 +505,16 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
if model == nil {
|
||||
model = map[string]any{"id": ref, "name": ref, "context": 0, "output": 0, "images": false, "efforts": []string{}}
|
||||
}
|
||||
gk := agentKeyAt(id, at.gw())
|
||||
gk := gkey()
|
||||
in := map[string]any{
|
||||
"gateway": map[string]any{"url": at.gw(), "v1": at.v1(), "key": gk},
|
||||
"models": models,
|
||||
"agent": map[string]any{"id": id, "config": f.path},
|
||||
}
|
||||
if bf != nil {
|
||||
in["agent"].(map[string]any)["base"] = bf.path
|
||||
in["base"] = bf.parsed()
|
||||
}
|
||||
if !only || ref != "" {
|
||||
in["model"] = model
|
||||
}
|
||||
@@ -421,7 +522,7 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", plugin.Name(p.Spec), err)
|
||||
}
|
||||
var kvs []edit.KV
|
||||
kvs := merged(out, d.Merge)
|
||||
if only {
|
||||
// nothing written would read as connected all the same
|
||||
if len(out) == 0 {
|
||||
@@ -443,7 +544,7 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
}
|
||||
st, was := onMagpie()
|
||||
if !was {
|
||||
st = pluggedStash{Had: map[string]string{}}
|
||||
st = pluggedStash{Had: map[string]string{}, Made: f.made(d.Merge)}
|
||||
}
|
||||
// a key magpie wrote before that connect no longer returns gets
|
||||
// what the user had back
|
||||
@@ -451,6 +552,11 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
return err
|
||||
}
|
||||
st.Ref, st.Mark, st.Value, st.Wrote = ref, mark, gk, strs
|
||||
if mark == "" && l != nil && ref != "" {
|
||||
// nothing written is the key, which goes in the environment:
|
||||
// the model says it is magpie's file still (holds)
|
||||
st.Value = d.Prefix + ref
|
||||
}
|
||||
st.Spec, st.Format = p.Spec, f.format
|
||||
save(st)
|
||||
if sf != nil && ref != "" {
|
||||
@@ -462,19 +568,76 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
if sf != nil {
|
||||
return startModel()
|
||||
}
|
||||
st, ok := onMagpie()
|
||||
if !ok && bf != nil {
|
||||
v, _ := bf.get(d.Model)
|
||||
return v
|
||||
}
|
||||
v, _ := f.get(d.Model)
|
||||
if st, ok := onMagpie(); ok && v == d.Prefix+st.Ref {
|
||||
return magpieID + "/" + st.Ref
|
||||
if ok {
|
||||
// one of magpie's models picked in the agent since is magpie's
|
||||
// still, for one started on it (its picker lists them all)
|
||||
if r, has := strings.CutPrefix(v, d.Prefix); has && (r == st.Ref || l != nil && isMagpie(r)) {
|
||||
return magpieID + "/" + r
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
// magpieModel is the model as the agent names it while it is one of
|
||||
// magpie's, "" otherwise
|
||||
magpieModel := func() string {
|
||||
if r, ok := strings.CutPrefix(get(), magpieID+"/"); ok {
|
||||
return d.Prefix + r
|
||||
}
|
||||
return ""
|
||||
}
|
||||
var lsh launchShell
|
||||
if l != nil {
|
||||
read := modelSed(d.Format, d.Model, d.Prefix)
|
||||
file := at.native(f.path)
|
||||
lsh = launchShell{l: l, at: at, distro: distro, fn: func(kind string) string {
|
||||
held := ""
|
||||
if read == "" {
|
||||
held = magpieModel()
|
||||
}
|
||||
return l.distroFunction(kind, l.vars(at.gw(), gkey()), read, file, held)
|
||||
}}
|
||||
}
|
||||
// shell gives the shells the function while the agent is on magpie's
|
||||
// models, and takes it out after; never at a stopped distro
|
||||
shell := func() {
|
||||
if l != nil && !at.cold {
|
||||
lsh.set(magpieModel() != "")
|
||||
}
|
||||
}
|
||||
icon := pluggedIcon(p)
|
||||
a := &Agent{
|
||||
ID: id, Name: d.Name, Icon: icon, Spelled: prefixed,
|
||||
UA: d.UA,
|
||||
Bin: d.Bin, Path: f.path,
|
||||
Plugin: p.Spec,
|
||||
Notice: func() string { return d.Notice },
|
||||
Plugin: p.Spec,
|
||||
Aliases: slices.Clone(d.Aliases),
|
||||
Notice: func() string {
|
||||
if l == nil {
|
||||
return d.Notice
|
||||
}
|
||||
m := magpieModel()
|
||||
if m == "" {
|
||||
return d.Notice
|
||||
}
|
||||
cmd := l.command(at.gw(), gkey(), m, !distro && runtime.GOOS == "windows")
|
||||
if in := lsh.in(); len(in) > 0 {
|
||||
for i := range in {
|
||||
if distro {
|
||||
in[i] = at.native(in[i])
|
||||
} else {
|
||||
in[i] = update.TildeHome(in[i])
|
||||
}
|
||||
}
|
||||
return noticeLaunchTyped.say("bin", l.bin, "profiles", strings.Join(in, ", "), "agent", d.Name, "command", cmd)
|
||||
}
|
||||
return noticeLaunch.say("agent", d.Name, "command", cmd)
|
||||
},
|
||||
Check: func() string {
|
||||
st, ok := onMagpie()
|
||||
if !ok {
|
||||
@@ -490,7 +653,24 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
for _, k := range sortedKeys(st.Wrote) {
|
||||
kvs = append(kvs, k, st.Wrote[k])
|
||||
}
|
||||
return wiringOff(d.Name, f.path, f.get, kvs...)
|
||||
if w := wiringOff(d.Name, f.path, f.get, kvs...); w != "" || l == nil {
|
||||
return w
|
||||
}
|
||||
// the model's entry under a merge key, which it is picked from
|
||||
m := magpieModel()
|
||||
for _, mk := range d.Merge {
|
||||
k := mk + "." + gjson.Escape(m)
|
||||
if _, wrote := st.Had[k]; !wrote {
|
||||
continue
|
||||
}
|
||||
if _, ok := f.raw(k); !ok {
|
||||
return fmt.Sprintf("%s's %s (%s) is gone, so it no longer reaches magpie", d.Name, m, filepath.Base(f.path))
|
||||
}
|
||||
}
|
||||
if p := lsh.stale(); p != "" {
|
||||
return fmt.Sprintf("%s's function %s in %s names magpie at an address it no longer has", d.Name, l.bin, at.native(p))
|
||||
}
|
||||
return ""
|
||||
},
|
||||
ListsModels: only && sf == nil,
|
||||
Fields: []Field{{
|
||||
@@ -498,7 +678,11 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
Get: get,
|
||||
Set: func(v string) error {
|
||||
if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {
|
||||
return wire(ref)
|
||||
if err := wire(ref); err != nil {
|
||||
return err
|
||||
}
|
||||
shell()
|
||||
return nil
|
||||
}
|
||||
if err := startRestore(); err != nil {
|
||||
return err
|
||||
@@ -508,9 +692,12 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
return err
|
||||
}
|
||||
}
|
||||
defer shell()
|
||||
mf, key := f, d.Model
|
||||
if sf != nil {
|
||||
mf, key = *sf, d.Startup.Model
|
||||
} else if bf != nil {
|
||||
mf = *bf
|
||||
}
|
||||
if v == "" {
|
||||
return mf.del([]string{key})
|
||||
@@ -518,11 +705,15 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
return mf.set([]edit.KV{{Path: key, Value: v}})
|
||||
},
|
||||
Options: func(cur map[string]string) []Option {
|
||||
return withVia(ownOptions("", cur["model"]), id, magpieID+"/")
|
||||
if !p.HasOwn() {
|
||||
return withVia(ownOptions("", cur["model"]), id, magpieID+"/")
|
||||
}
|
||||
return withVia(group(d.Name, pluggedOwn(p, f, bf, cur["model"])), id, magpieID+"/")
|
||||
},
|
||||
}},
|
||||
// the catalog changed: what connect writes for the model may too
|
||||
Sync: func() error {
|
||||
defer shell()
|
||||
if st, ok := onMagpie(); ok && sf != nil {
|
||||
// the startup model too while it is magpie's, as it is
|
||||
// now; else connect's list alone, for the agent's picker
|
||||
@@ -533,11 +724,15 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
} else if ok {
|
||||
if v, _ := f.get(d.Model); only || v == d.Prefix+st.Ref {
|
||||
return wire(st.Ref)
|
||||
} else if r, ok := strings.CutPrefix(get(), magpieID+"/"); ok && l != nil {
|
||||
// another of magpie's, picked in the agent
|
||||
return wire(r)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Unwire: func() error {
|
||||
defer shell()
|
||||
if err := startRestore(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -548,6 +743,9 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
},
|
||||
}
|
||||
paths := []string{f.path}
|
||||
if bf != nil {
|
||||
paths = append(paths, bf.path)
|
||||
}
|
||||
if sf != nil {
|
||||
// a model of the agent's own picked in it, magpie's provider still
|
||||
// in its list: connected, as joined, not drift (#2424's Beside)
|
||||
@@ -583,11 +781,74 @@ func plugged(home string, p *agentplug.Agent) *Agent {
|
||||
}}
|
||||
}
|
||||
if d.Dir != "" {
|
||||
a.Dir = pluggedPath(home, d.Dir)
|
||||
a.Dir = ppath(d.Dir)
|
||||
}
|
||||
if l != nil {
|
||||
a.Launch = func() string {
|
||||
m := magpieModel()
|
||||
if m == "" {
|
||||
return ""
|
||||
}
|
||||
return l.command(at.gw(), gkey(), m, !distro && runtime.GOOS == "windows")
|
||||
}
|
||||
a.Typed = func() string {
|
||||
if magpieModel() == "" || len(lsh.in()) == 0 {
|
||||
return ""
|
||||
}
|
||||
return l.bin
|
||||
}
|
||||
a.Start = func() Starting {
|
||||
s := Starting{Bin: l.bin, Flag: l.flag, Plain: slices.Clone(l.plain)}
|
||||
if m := magpieModel(); m != "" {
|
||||
s.Env, s.Model, s.Args = l.vars(at.gw(), gkey()), m, slices.Clone(l.args)
|
||||
}
|
||||
return s
|
||||
}
|
||||
}
|
||||
if d.Effort {
|
||||
a.Fields = append(a.Fields, effortField(id, func() bool { return !at.cold && strings.HasPrefix(get(), magpieID+"/") }))
|
||||
}
|
||||
return atomic(a, paths...)
|
||||
}
|
||||
|
||||
// parsed is f as a hook is given it: its JSON parsed, {} for none or
|
||||
// another format.
|
||||
func (f pluggedFile) parsed() any {
|
||||
var cfg any = map[string]any{}
|
||||
if f.format == "json" {
|
||||
if b, err := edit.Read(f.path); err == nil && len(b) > 0 {
|
||||
var v map[string]any
|
||||
if json.Unmarshal(jsonc.ToJSON(b), &v) == nil && v != nil {
|
||||
cfg = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// pluggedOwn are the agent's own models its plugin's own lists, read from
|
||||
// its file as it is (and its base, bf, nil for none), cur among them;
|
||||
// each says the vendor it goes to.
|
||||
func pluggedOwn(p *agentplug.Agent, f pluggedFile, bf *pluggedFile, cur string) []Option {
|
||||
var base any
|
||||
if bf != nil {
|
||||
base = bf.parsed()
|
||||
}
|
||||
if strings.HasPrefix(cur, magpieID+"/") {
|
||||
cur = ""
|
||||
}
|
||||
own, _ := p.OwnModels(f.parsed(), base, cur)
|
||||
out := make([]Option, 0, len(own))
|
||||
for _, o := range own {
|
||||
m := o.Model
|
||||
if m == "" {
|
||||
m = o.Value
|
||||
}
|
||||
out = append(out, Option{Value: o.Value, Icon: modelIcon("", m), Direct: o.Direct})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// pluggedIcon is the picture the plugin gives its agent, else the one the
|
||||
// plugin market gives the plugin, else magpie's generic one.
|
||||
func pluggedIcon(p *agentplug.Agent) string {
|
||||
|
||||
@@ -0,0 +1,408 @@
|
||||
//go:build !windows
|
||||
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
|
||||
// agyPluginSrc is @magpie-community/agent-agy's agy.agent.js, as published
|
||||
// (magpie-community/plugins, packages/agent-agy).
|
||||
const agyPluginSrc = `
|
||||
// Antigravity CLI (agy) keeps its settings in
|
||||
// ~/.gemini/antigravity-cli/settings.json, and the models it can pick in
|
||||
// customModelsConfig.customModels, each {apiProvider, modelName}. It takes
|
||||
// the address and key of a Gemini endpoint only from how it is started,
|
||||
// so magpie starts it: the function agy magpie puts in your shells runs
|
||||
// ` + "`" + `magpie agy run` + "`" + `, which gives agy GEMINI_API_KEY, GOOGLE_GEMINI_BASE_URL,
|
||||
// --settings magpie-settings.json and --model while its model is one of
|
||||
// magpie's.
|
||||
//
|
||||
// magpie writes only magpie-settings.json, a file of its own beside
|
||||
// settings.json, which agy reads for the one session started with
|
||||
// --settings: "modelProvider": "gemini" in settings.json would make every
|
||||
// agy an API-key session, with no Google account and so no remote
|
||||
// control. agy takes customModels whole from that file, so the user's own
|
||||
// custom models are carried into it beside magpie's. remote-control runs
|
||||
// as agy is, on the user's sign-in.
|
||||
export const agent = {
|
||||
id: "agy",
|
||||
name: "Antigravity CLI",
|
||||
icon: "antigravity-color",
|
||||
aliases: ["antigravity-cli"],
|
||||
bin: "agy",
|
||||
dir: "~/.gemini/antigravity-cli",
|
||||
config: "~/.gemini/antigravity-cli/magpie-settings.json",
|
||||
base: "~/.gemini/antigravity-cli/settings.json",
|
||||
format: "json",
|
||||
model: "model",
|
||||
prefix: "magpie/",
|
||||
launch: {
|
||||
env: { GEMINI_API_KEY: "{key}", GOOGLE_GEMINI_BASE_URL: "{url}" },
|
||||
model: "--model",
|
||||
args: { "--settings": "{config}" },
|
||||
plain: ["remote-control", "--remote-control", "-remote-control"],
|
||||
},
|
||||
effort: true,
|
||||
wsl: true,
|
||||
}
|
||||
|
||||
const GEMINI = "API_PROVIDER_GOOGLE_GEMINI"
|
||||
|
||||
// the user's own custom models, from settings.json
|
||||
const ownModels = (base) => {
|
||||
const out = {}
|
||||
for (const [k, v] of Object.entries(base?.customModelsConfig?.customModels ?? {})) {
|
||||
if (!k.startsWith("magpie/")) out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function connect({ models, base }) {
|
||||
const custom = ownModels(base)
|
||||
for (const m of models) custom[` + "`" + `magpie/${m.id}` + "`" + `] = { apiProvider: GEMINI, modelName: m.id }
|
||||
return { modelProvider: "gemini", "customModelsConfig.customModels": custom }
|
||||
}
|
||||
|
||||
// the user's own models, which go to their provider rather than through
|
||||
// magpie, and the one agy is on when it isn't listed
|
||||
export function own({ base, model }) {
|
||||
const custom = base?.customModelsConfig?.customModels ?? {}
|
||||
const out = []
|
||||
for (const [k, v] of Object.entries(custom)) {
|
||||
if (k.startsWith("magpie/")) continue
|
||||
const p = String(v?.apiProvider ?? "")
|
||||
const direct = p.includes("ANTHROPIC") ? "Anthropic" : p.includes("OPENAI") ? "OpenAI" : "Google"
|
||||
out.push({ value: k, model: String(v?.modelName ?? k), direct })
|
||||
}
|
||||
out.sort((a, b) => (a.value < b.value ? -1 : a.value > b.value ? 1 : 0))
|
||||
if (model && !(model in custom)) out.unshift({ value: model, model, direct: "Google" })
|
||||
return out
|
||||
}
|
||||
`
|
||||
|
||||
// agyPluginHome is a home with the agent-agy plugin installed, agentMovers
|
||||
// naming it for agy, shells' profiles with a line of the user's own, and
|
||||
// agy's settings.json as settings.
|
||||
func agyPluginHome(t *testing.T, settings string) (home, path, mine string, rcs []string) {
|
||||
t.Helper()
|
||||
home = pluggedHome(t, agyPluginSrc)
|
||||
t.Setenv("ZDOTDIR", "")
|
||||
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)
|
||||
}
|
||||
path = filepath.Join(home, ".gemini", "antigravity-cli", "settings.json")
|
||||
os.MkdirAll(filepath.Dir(path), 0o755)
|
||||
if settings != "" {
|
||||
os.WriteFile(path, []byte(settings), 0o644)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// overOf is magpie's own settings file beside settings.json at path.
|
||||
func overOf(path string) string { return filepath.Join(filepath.Dir(path), agyOverride) }
|
||||
|
||||
func fileGone(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatalf("%s is still there: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// moveAgy names the plugin installed in home as the one agy moves onto.
|
||||
func moveAgy(t *testing.T, home string) {
|
||||
was := agentMovers
|
||||
agentMovers = map[string]string{"agy": filepath.Join(home, "plugins", "pa")}
|
||||
t.Cleanup(func() { agentMovers = was })
|
||||
}
|
||||
|
||||
func settingsOf(t *testing.T, path string) map[string]any {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var v map[string]any
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
t.Fatalf("%v: %s", err, b)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func profilesAre(t *testing.T, home, mine string, rcs []string) {
|
||||
t.Helper()
|
||||
for _, n := range rcs {
|
||||
if b, _ := os.ReadFile(filepath.Join(home, n)); string(b) != mine {
|
||||
t.Fatalf("%s:\n%s", n, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// agy as the agent-agy plugin does what the built-in did: one agy in the
|
||||
// list, found by its alias too; the user's own custom models offered as
|
||||
// going to their provider; magpie's model written with modelProvider and
|
||||
// magpie's custom models beside the user's; the function agy in every
|
||||
// shell, which starts it with the variables and --model; and its own model
|
||||
// again, or Disconnect, puts settings.json and the profiles back as they
|
||||
// were.
|
||||
func TestAgyPlugin(t *testing.T) {
|
||||
const before = `{"model": "gemini-3-pro", "customModelsConfig": {"customModels": {"my-claude": {"apiProvider": "API_PROVIDER_ANTHROPIC", "modelName": "claude-sonnet-4-5"}}}}`
|
||||
home, path, mine, rcs := agyPluginHome(t, before)
|
||||
moveAgy(t, home)
|
||||
var want map[string]any
|
||||
json.Unmarshal([]byte(before), &want)
|
||||
|
||||
n := 0
|
||||
for _, a := range All() {
|
||||
if a.ID == "agy" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
a, err := Find("agy")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1 || a.Plugin == "" || a.Name != "Antigravity CLI" {
|
||||
t.Fatalf("%d agy, %+v", n, a)
|
||||
}
|
||||
if b, _ := Find("antigravity-cli"); b == nil || b.Plugin != a.Plugin {
|
||||
t.Fatal("not found by its alias")
|
||||
}
|
||||
f := a.Field("model")
|
||||
opts := f.Options(map[string]string{"model": f.Get()})
|
||||
direct := map[string]string{}
|
||||
for _, o := range opts {
|
||||
direct[o.Value] = o.Direct
|
||||
}
|
||||
if direct["my-claude"] != "Anthropic" || direct["gemini-3-pro"] != "Google" || !containsOption(opts, "magpie/deepseek/pro") {
|
||||
t.Fatalf("options: %+v", opts)
|
||||
}
|
||||
if a.Field("effort") == nil {
|
||||
t.Fatal("no effort field")
|
||||
}
|
||||
|
||||
if err := f.Set("magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// settings.json is left as it was; magpie's file has the model, the
|
||||
// provider and every custom model, the user's own carried in
|
||||
if c := settingsOf(t, path); !reflect.DeepEqual(c, want) {
|
||||
t.Fatalf("settings.json: %v", c)
|
||||
}
|
||||
over := overOf(path)
|
||||
c := settingsOf(t, over)
|
||||
custom, _ := c["customModelsConfig"].(map[string]any)["customModels"].(map[string]any)
|
||||
if c["model"] != "magpie/deepseek/pro" || c["modelProvider"] != "gemini" || custom["my-claude"] == nil ||
|
||||
!reflect.DeepEqual(custom["magpie/deepseek/pro"], map[string]any{"apiProvider": "API_PROVIDER_GOOGLE_GEMINI", "modelName": "deepseek/pro"}) ||
|
||||
custom["magpie/deepseek/flash"] == nil {
|
||||
t.Fatalf("wired: %v", c)
|
||||
}
|
||||
if f.Get() != "magpie/deepseek/pro" || a.Check() != "" {
|
||||
t.Fatalf("get %q, check %q", f.Get(), a.Check())
|
||||
}
|
||||
s := a.Start()
|
||||
if s.Bin != "agy" || s.Flag != "--model" || s.Model != "magpie/deepseek/pro" ||
|
||||
!slices.Equal(s.Env, []string{"GEMINI_API_KEY=" + gateway.TokenFor("agy"), "GOOGLE_GEMINI_BASE_URL=" + gateway.URL()}) ||
|
||||
!slices.Equal(s.Args, []string{"--settings", over}) {
|
||||
t.Fatalf("start: %+v", s)
|
||||
}
|
||||
if !s.Given("-model=x") || s.Given("--modelx") {
|
||||
t.Fatal("Given")
|
||||
}
|
||||
// remote-control runs as agy is, on the user's Google sign-in
|
||||
for _, arg := range []string{"remote-control", "--remote-control", "-remote-control=x"} {
|
||||
if !s.Plained(arg) {
|
||||
t.Fatalf("%s is not plain", arg)
|
||||
}
|
||||
}
|
||||
if s.Plained("--model") || s.Plained("remote") {
|
||||
t.Fatal("Plained took another")
|
||||
}
|
||||
if st := Starter("antigravity-cli"); st == nil || st.Plugin != a.Plugin {
|
||||
t.Fatal("Starter by alias")
|
||||
}
|
||||
if Starter("ag") != nil {
|
||||
t.Fatal("Starter took a prefix")
|
||||
}
|
||||
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 >>>\n"+agyPosixHead) || !strings.Contains(s, ` agy run "$@"; else command agy "$@"; fi`) {
|
||||
t.Fatalf("%s:\n%s", p, s)
|
||||
}
|
||||
}
|
||||
if a.Typed() != "agy" || !strings.HasPrefix(a.Notice(), "Type agy in a new terminal: magpie added it to ~/") {
|
||||
t.Fatalf("typed %q, notice %q", a.Typed(), a.Notice())
|
||||
}
|
||||
if want := "GEMINI_API_KEY=" + gateway.TokenFor("agy") + " GOOGLE_GEMINI_BASE_URL=" + gateway.URL() + " agy --settings " + posixQuote(over) + " --model 'magpie/deepseek/pro'"; a.Launch() != want {
|
||||
t.Fatalf("launch %q, want %q", a.Launch(), want)
|
||||
}
|
||||
// another of magpie's models
|
||||
if err := f.Set("magpie/deepseek/flash"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Start().Model != "magpie/deepseek/flash" {
|
||||
t.Fatal("flash")
|
||||
}
|
||||
|
||||
// its own again: magpie's file gone, settings.json as it was
|
||||
if err := f.Set("gemini-3-pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileGone(t, over)
|
||||
if c := settingsOf(t, path); !reflect.DeepEqual(c, want) {
|
||||
t.Fatalf("own: %v", c)
|
||||
}
|
||||
if f.Get() != "gemini-3-pro" {
|
||||
t.Fatalf("get off magpie %q", f.Get())
|
||||
}
|
||||
profilesAre(t, home, mine, rcs)
|
||||
if s := a.Start(); s.Model != "" || s.Env != nil || s.Args != nil {
|
||||
t.Fatalf("start off magpie: %+v", s)
|
||||
}
|
||||
// another of the user's own, written into settings.json
|
||||
if err := f.Set("my-claude"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c := settingsOf(t, path); c["model"] != "my-claude" {
|
||||
t.Fatalf("own model: %v", c)
|
||||
}
|
||||
fileGone(t, over)
|
||||
os.WriteFile(path, []byte(before), 0o644)
|
||||
|
||||
// Disconnect: magpie's file gone, settings.json untouched
|
||||
if err := f.Set("magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.Unwire(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileGone(t, over)
|
||||
if c := settingsOf(t, path); !reflect.DeepEqual(c, want) {
|
||||
t.Fatalf("unwired: %v", c)
|
||||
}
|
||||
profilesAre(t, home, mine, rcs)
|
||||
}
|
||||
|
||||
// A user the built-in agy wired keeps their setup when agy moves onto the
|
||||
// plugin: the plugin's agy reads as connected on magpie's model, started
|
||||
// with magpie's file, and its own model again takes magpie's file and the
|
||||
// function away, settings.json as the user had it. With the plugin gone,
|
||||
// the built-in is agy again.
|
||||
func TestAgyHandedToPlugin(t *testing.T) {
|
||||
const before = `{"model": "gemini-3-pro", "modelProvider": "vertex", "customModelsConfig": {"customModels": {"mine": {"apiProvider": "API_PROVIDER_GOOGLE_GEMINI", "modelName": "gemini-3-pro"}}}}`
|
||||
home, path, mine, rcs := agyPluginHome(t, before)
|
||||
var want map[string]any
|
||||
json.Unmarshal([]byte(before), &want)
|
||||
|
||||
b, err := Find("agy")
|
||||
if err != nil || b.Plugin != "" {
|
||||
t.Fatalf("built-in: %+v %v", b, err)
|
||||
}
|
||||
if err := b.Apply("model", "magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(update.ShellFunctionIn("agy")) == 0 {
|
||||
t.Fatal("the built-in gave no function")
|
||||
}
|
||||
|
||||
moveAgy(t, home)
|
||||
a, err := Find("agy")
|
||||
if err != nil || a.Plugin == "" {
|
||||
t.Fatalf("moved: %+v %v", a, err)
|
||||
}
|
||||
f := a.Field("model")
|
||||
if f.Get() != "magpie/deepseek/pro" || a.Check() != "" || a.Start().Model != "magpie/deepseek/pro" {
|
||||
t.Fatalf("handed over: get %q, check %q", f.Get(), a.Check())
|
||||
}
|
||||
if err := a.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c := settingsOf(t, path); !reflect.DeepEqual(c, want) {
|
||||
t.Fatalf("settings.json after sync: %v", c)
|
||||
}
|
||||
if err := f.Set("gemini-3-pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileGone(t, overOf(path))
|
||||
if c := settingsOf(t, path); !reflect.DeepEqual(c, want) {
|
||||
t.Fatalf("own: %v", c)
|
||||
}
|
||||
profilesAre(t, home, mine, rcs)
|
||||
|
||||
// the plugin gone: the built-in again
|
||||
agentMovers = map[string]string{}
|
||||
if b, _ := Find("agy"); b == nil || b.Plugin != "" {
|
||||
t.Fatalf("after: %+v", b)
|
||||
}
|
||||
}
|
||||
|
||||
// A settings.json an older built-in wired (model, modelProvider and
|
||||
// magpie's custom models in it, the user's own stashed) is given back when
|
||||
// the plugin takes agy over, and magpie's model moves into magpie's file.
|
||||
func TestAgyOldWiringHandedToPlugin(t *testing.T) {
|
||||
const old = `{"model": "magpie/deepseek/pro", "modelProvider": "gemini", "theme": "dark", "customModelsConfig": {"customModels": {"mine": {"apiProvider": "API_PROVIDER_ANTHROPIC", "modelName": "claude-sonnet-4-5"}, "magpie/deepseek/pro": {"apiProvider": "API_PROVIDER_GOOGLE_GEMINI", "modelName": "deepseek/pro"}}}}`
|
||||
home, path, mine, rcs := agyPluginHome(t, old)
|
||||
stash(map[string]string{"agy:" + path + ":model": "gemini-3-pro", "agy:" + path + ":modelProvider": "vertex"})
|
||||
moveAgy(t, home)
|
||||
a, _ := Find("agy")
|
||||
if a == nil || a.Plugin == "" {
|
||||
t.Fatal("not moved")
|
||||
}
|
||||
f := a.Field("model")
|
||||
if f.Get() != "magpie/deepseek/pro" || a.Check() != "" {
|
||||
t.Fatalf("handed over: get %q, check %q", f.Get(), a.Check())
|
||||
}
|
||||
want := map[string]any{"model": "gemini-3-pro", "modelProvider": "vertex", "theme": "dark", "customModelsConfig": map[string]any{"customModels": map[string]any{"mine": map[string]any{"apiProvider": "API_PROVIDER_ANTHROPIC", "modelName": "claude-sonnet-4-5"}}}}
|
||||
if c := settingsOf(t, path); !reflect.DeepEqual(c, want) {
|
||||
t.Fatalf("settings.json given back: %v", c)
|
||||
}
|
||||
c := settingsOf(t, overOf(path))
|
||||
custom, _ := c["customModelsConfig"].(map[string]any)["customModels"].(map[string]any)
|
||||
if c["model"] != "magpie/deepseek/pro" || c["modelProvider"] != "gemini" || custom["mine"] == nil {
|
||||
t.Fatalf("magpie's file: %v", c)
|
||||
}
|
||||
if err := a.Unwire(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileGone(t, overOf(path))
|
||||
if c := settingsOf(t, path); !reflect.DeepEqual(c, want) {
|
||||
t.Fatalf("unwired: %v", c)
|
||||
}
|
||||
profilesAre(t, home, mine, rcs)
|
||||
}
|
||||
|
||||
// A user the built-in wired with no settings.json of their own: Disconnect
|
||||
// on the plugin takes magpie's file away and makes no settings.json.
|
||||
func TestAgyHandedOverUnwire(t *testing.T) {
|
||||
home, path, mine, rcs := agyPluginHome(t, "")
|
||||
b, _ := Find("agy")
|
||||
if err := b.Apply("model", "magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
moveAgy(t, home)
|
||||
a, _ := Find("agy")
|
||||
if a.Plugin == "" {
|
||||
t.Fatal("not moved")
|
||||
}
|
||||
if err := a.Unwire(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fileGone(t, overOf(path))
|
||||
fileGone(t, path)
|
||||
profilesAre(t, home, mine, rcs)
|
||||
}
|
||||
@@ -72,11 +72,11 @@ func pluggedOff(spec string) *Agent {
|
||||
}
|
||||
home, cfg := homes()
|
||||
for _, b := range append(builtins(home, cfg), others...) {
|
||||
if b.ID == p.Desc.ID || slices.Contains(b.Aliases, p.Desc.ID) {
|
||||
if (b.ID == p.Desc.ID || slices.Contains(b.Aliases, p.Desc.ID)) && !movesTo(b.ID, p) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return plugged(home, p)
|
||||
return plugged(here(home), p)
|
||||
}
|
||||
|
||||
// Gone is what RestoreGone did: the files it put back as the user had
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
package agent
|
||||
|
||||
// An agent a plugin adds that takes the gateway only from how it is
|
||||
// started (agentplug.Launch: agy reads GEMINI_API_KEY and
|
||||
// GOOGLE_GEMINI_BASE_URL from its environment and resolves a model only
|
||||
// given with --model) is started on magpie as the built-in agy was: its
|
||||
// row gives the command, and magpie puts a function named its command in
|
||||
// each shell the user has while it is on one of magpie's models. On this
|
||||
// machine the function runs `magpie <id> run` (cli/agy_cli.go), which
|
||||
// starts the real one with the variables and the model while its file's
|
||||
// model is magpie's, and as it is otherwise; PowerShell's asks `magpie
|
||||
// <id> env` for them. A WSL distro has no magpie to ask, so its function
|
||||
// reads the model from the file itself (or holds it, where the file can't
|
||||
// be read so), with the variables written in.
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentplug"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
|
||||
// launchSpec is how a plugin's agent is started: its id, which `magpie
|
||||
// <id> run` names, its command, the flag that names the model ("" none),
|
||||
// its variables, by name, the flags put before the user's arguments with
|
||||
// their values (flag then value, sorted by flag: agy's --settings and
|
||||
// magpie's settings file), and the arguments that start it as it is.
|
||||
type launchSpec struct {
|
||||
id, bin, flag string
|
||||
env map[string]string // templates (agentplug.Fill)
|
||||
args, plain []string
|
||||
}
|
||||
|
||||
// newLaunch is d's launch, its config's path, as the agent names it,
|
||||
// in place of {config}.
|
||||
func newLaunch(d agentplug.Desc, config string) *launchSpec {
|
||||
if d.Launch == nil {
|
||||
return nil
|
||||
}
|
||||
l := &launchSpec{id: d.ID, bin: d.Bin, flag: d.Launch.Model, env: d.Launch.Env, plain: slices.Clone(d.Launch.Plain)}
|
||||
for _, f := range sortedKeys(d.Launch.Args) {
|
||||
l.args = append(l.args, f, strings.ReplaceAll(d.Launch.Args[f], "{config}", config))
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// plainCases are the plain arguments as a shell's case matches them:
|
||||
// each alone, and a flag with "=value".
|
||||
func (l *launchSpec) plainCases() []string {
|
||||
var out []string
|
||||
for _, a := range l.plain {
|
||||
out = append(out, a)
|
||||
if strings.HasPrefix(a, "-") {
|
||||
out = append(out, a+"=*")
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// vars are the variables filled for the gateway at gw and key, sorted by
|
||||
// name, NAME=value.
|
||||
func (l *launchSpec) vars(gw, key string) []string {
|
||||
out := make([]string, 0, len(l.env))
|
||||
for _, k := range sortedKeys(l.env) {
|
||||
out = append(out, k+"="+agentplug.Fill(l.env[k], gw, gw+"/v1", key))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// names are the variables' names, sorted.
|
||||
func (l *launchSpec) names() []string { return sortedKeys(l.env) }
|
||||
|
||||
// flags are the forms of the model's flag the agent takes: --model and
|
||||
// -model for "--model", as agy does.
|
||||
func (l *launchSpec) flags() []string {
|
||||
if l.flag == "" {
|
||||
return nil
|
||||
}
|
||||
out := []string{l.flag}
|
||||
if strings.HasPrefix(l.flag, "--") {
|
||||
out = append(out, l.flag[1:])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Given says a is the model's flag, in one of its forms, alone or with
|
||||
// "=value".
|
||||
func (l *launchSpec) given(a string) bool {
|
||||
a, _, _ = strings.Cut(a, "=")
|
||||
return slices.Contains(l.flags(), a)
|
||||
}
|
||||
|
||||
func posixQuote(v string) string { return "'" + strings.ReplaceAll(v, "'", `'\''`) + "'" }
|
||||
func fishQuote(v string) string {
|
||||
return "'" + strings.NewReplacer(`\`, `\\`, "'", `\'`).Replace(v) + "'"
|
||||
}
|
||||
func psQuote(v string) string { return "'" + strings.ReplaceAll(v, "'", "''") + "'" }
|
||||
|
||||
// command is what starts the agent on the gateway at gw with key and
|
||||
// model, in PowerShell or a POSIX shell.
|
||||
func (l *launchSpec) command(gw, key, model string, powershell bool) string {
|
||||
var b strings.Builder
|
||||
for _, kv := range l.vars(gw, key) {
|
||||
k, v, _ := strings.Cut(kv, "=")
|
||||
if powershell {
|
||||
b.WriteString(`$env:` + k + `="` + v + `"; `)
|
||||
} else {
|
||||
b.WriteString(k + "=" + v + " ")
|
||||
}
|
||||
}
|
||||
b.WriteString(l.bin)
|
||||
quote := posixQuote
|
||||
if powershell {
|
||||
quote = psQuote
|
||||
}
|
||||
for i := 0; i+1 < len(l.args); i += 2 {
|
||||
b.WriteString(" " + l.args[i] + " " + quote(l.args[i+1]))
|
||||
}
|
||||
if l.flag != "" {
|
||||
b.WriteString(" " + l.flag + " " + quote(model))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// posixHead opens the function in a POSIX shell's profile: "bin() {",
|
||||
// which dash takes too, an alias of its name taken out first on a line of
|
||||
// its own (agyPosixHead).
|
||||
func (l *launchSpec) posixHead() string {
|
||||
return "unalias " + l.bin + " 2>/dev/null || true\n" + l.bin + "() {\n"
|
||||
}
|
||||
|
||||
// function is the function in this machine's shell of kind, which runs
|
||||
// prog (this magpie) to start the agent; the command on PATH when prog is
|
||||
// gone.
|
||||
func (l *launchSpec) function(kind, prog string) string {
|
||||
switch kind {
|
||||
case "fish":
|
||||
q := fishQuote(prog)
|
||||
return "function " + l.bin + "\n if test -x " + q + "\n " + q + " " + l.id + " run $argv\n else\n command " + l.bin + " $argv\n end\nend"
|
||||
case "powershell":
|
||||
q := psQuote(prog)
|
||||
names := make([]string, 0, len(l.env))
|
||||
for _, n := range l.names() {
|
||||
names = append(names, psQuote(n))
|
||||
}
|
||||
set := " $names = @(" + strings.Join(names, ", ") + ")\n" +
|
||||
" $was = @{}\n" +
|
||||
" foreach ($n in $names) { $was[$n] = [Environment]::GetEnvironmentVariable($n, 'Process'); [Environment]::SetEnvironmentVariable($n, $start[$n], 'Process') }\n"
|
||||
pre := ""
|
||||
for i := 0; i+1 < len(l.args); i += 2 {
|
||||
pre += " " + l.args[i] + " $start['" + strings.TrimLeft(l.args[i], "-") + "']"
|
||||
}
|
||||
run := " & $real" + pre + " @args\n"
|
||||
if l.flag != "" {
|
||||
name := regexp.QuoteMeta(strings.TrimLeft(l.flag, "-"))
|
||||
run = " if (@($args | Where-Object { \"$_\" -match '^--?" + name + "(=|$)' }).Count) { & $real" + pre + " @args } else { & $real" + pre + " " + l.flag + " $start.model @args }\n"
|
||||
}
|
||||
plain := ""
|
||||
if len(l.plain) > 0 {
|
||||
alts := make([]string, len(l.plain))
|
||||
for i, a := range l.plain {
|
||||
alts[i] = regexp.QuoteMeta(a)
|
||||
}
|
||||
plain = " -or @($args | Where-Object { \"$_\" -match '^(" + strings.Join(alts, "|") + ")(=|$)' }).Count"
|
||||
}
|
||||
return "function " + l.bin + " {\n" +
|
||||
" $real = Get-Command " + l.bin + " -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1\n" +
|
||||
" if (-not $real) { Write-Error '" + l.bin + " is not installed'; return }\n" +
|
||||
" $start = @{}\n" +
|
||||
" if (Test-Path -LiteralPath " + q + ") {\n" +
|
||||
" foreach ($l in @(& " + q + " " + l.id + " env)) { $k, $v = \"$l\" -split '=', 2; if ($v) { $start[$k] = $v } }\n" +
|
||||
" }\n" +
|
||||
" if (-not $start.model" + plain + ") { & $real @args; return }\n" +
|
||||
set +
|
||||
" try {\n" + run +
|
||||
" } finally { foreach ($n in $names) { [Environment]::SetEnvironmentVariable($n, $was[$n], 'Process') } }\n" +
|
||||
"}"
|
||||
}
|
||||
q := posixQuote(prog)
|
||||
return l.posixHead() + " if [ -x " + q + " ]; then " + q + " " + l.id + ` run "$@"; else command ` + l.bin + ` "$@"; fi` + "\n}"
|
||||
}
|
||||
|
||||
// distroFunction is the function in a WSL distro's shell of kind: while
|
||||
// read (a sed script over file, the config as the distro names it) prints
|
||||
// a model, or model is held ("" for read), the command started with vars
|
||||
// and the model after its flag (none when the user gives the flag); as it
|
||||
// is otherwise.
|
||||
func (l *launchSpec) distroFunction(kind string, vars []string, read, file, model string) string {
|
||||
var cases []string
|
||||
for _, f := range l.flags() {
|
||||
cases = append(cases, f, f+"=*")
|
||||
}
|
||||
if kind == "fish" {
|
||||
var b strings.Builder
|
||||
b.WriteString("function " + l.bin + "\n")
|
||||
if read != "" {
|
||||
b.WriteString(" set -l m (sed -n " + fishQuote(read) + " " + fishQuote(file) + " 2>/dev/null | head -n 1)\n")
|
||||
} else {
|
||||
b.WriteString(" set -l m " + fishQuote(model) + "\n")
|
||||
}
|
||||
b.WriteString(" if test -z \"$m\"\n command " + l.bin + " $argv\n return\n end\n")
|
||||
if pc := l.plainCases(); len(pc) > 0 {
|
||||
qs := make([]string, len(pc))
|
||||
for i, c := range pc {
|
||||
qs[i] = fishQuote(c)
|
||||
}
|
||||
b.WriteString(" for a in $argv\n switch $a\n case " + strings.Join(qs, " ") + "\n command " + l.bin + " $argv\n return\n end\n end\n")
|
||||
}
|
||||
if len(cases) > 0 {
|
||||
qs := make([]string, len(cases))
|
||||
for i, c := range cases {
|
||||
qs[i] = fishQuote(c)
|
||||
}
|
||||
b.WriteString(" for a in $argv\n switch $a\n case " + strings.Join(qs, " ") + "\n set m ''\n end\n end\n")
|
||||
b.WriteString(" if test -n \"$m\"\n set argv " + l.flag + " $m $argv\n end\n")
|
||||
}
|
||||
if len(l.args) > 0 {
|
||||
qs := make([]string, len(l.args))
|
||||
for i, a := range l.args {
|
||||
qs[i] = fishQuote(a)
|
||||
}
|
||||
b.WriteString(" set argv " + strings.Join(qs, " ") + " $argv\n")
|
||||
}
|
||||
b.WriteString(" env")
|
||||
for _, kv := range vars {
|
||||
k, v, _ := strings.Cut(kv, "=")
|
||||
b.WriteString(" " + k + "=" + fishQuote(v))
|
||||
}
|
||||
b.WriteString(" " + l.bin + " $argv\nend")
|
||||
return b.String()
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString(l.posixHead())
|
||||
b.WriteString(" local m a\n")
|
||||
if read != "" {
|
||||
b.WriteString(" m=$(sed -n " + posixQuote(read) + " " + posixQuote(file) + " 2>/dev/null | head -n 1)\n")
|
||||
} else {
|
||||
b.WriteString(" m=" + posixQuote(model) + "\n")
|
||||
}
|
||||
b.WriteString(` if [ -z "$m" ]; then command ` + l.bin + ` "$@"; return; fi` + "\n")
|
||||
if pc := l.plainCases(); len(pc) > 0 {
|
||||
b.WriteString(` for a in "$@"; do case "$a" in ` + strings.Join(pc, "|") + `) command ` + l.bin + ` "$@"; return;; esac; done` + "\n")
|
||||
}
|
||||
if len(cases) > 0 {
|
||||
b.WriteString(` for a in "$@"; do case "$a" in ` + strings.Join(cases, "|") + `) m=;; esac; done` + "\n")
|
||||
b.WriteString(` if [ -n "$m" ]; then set -- ` + l.flag + ` "$m" "$@"; fi` + "\n")
|
||||
}
|
||||
if len(l.args) > 0 {
|
||||
qs := make([]string, len(l.args))
|
||||
for i, a := range l.args {
|
||||
qs[i] = posixQuote(a)
|
||||
}
|
||||
b.WriteString(" set -- " + strings.Join(qs, " ") + ` "$@"` + "\n")
|
||||
}
|
||||
b.WriteString(" ")
|
||||
for _, kv := range vars {
|
||||
k, v, _ := strings.Cut(kv, "=")
|
||||
b.WriteString(" " + k + "=" + posixQuote(v))
|
||||
}
|
||||
b.WriteString(" command " + l.bin + ` "$@"` + "\n}")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// sedBRE is s as a literal in a sed basic regular expression delimited
|
||||
// by '|'.
|
||||
func sedBRE(s string) string {
|
||||
return strings.NewReplacer(`\`, `\\`, `.`, `\.`, `*`, `\*`, `[`, `\[`, `]`, `\]`, `^`, `\^`, `$`, `\$`, `|`, `\|`).Replace(s)
|
||||
}
|
||||
|
||||
// modelSed is the sed script that prints the model of a file of format
|
||||
// at the top-level key while it starts with prefix (magpie's), for a
|
||||
// distro's function; "" where a script can't say (a key below another,
|
||||
// no prefix to tell magpie's by), and the function holds the model.
|
||||
// magpie writes the key on a line of its own; one on a single line is
|
||||
// found too, so long as nothing after it has the key's name.
|
||||
func modelSed(format, key, prefix string) string {
|
||||
if prefix == "" || key == "" || strings.ContainsAny(key, `.\`) {
|
||||
return ""
|
||||
}
|
||||
k, p := sedBRE(key), sedBRE(prefix)
|
||||
switch format {
|
||||
case "json":
|
||||
return `s|^.*"` + k + `"[[:space:]]*:[[:space:]]*"\(` + p + `[^"]*\)".*$|\1|p`
|
||||
case "yaml":
|
||||
return `s|^` + k + `:[[:space:]]*["']\{0,1\}\(` + p + `[^"' #]*\).*$|\1|p`
|
||||
case "env":
|
||||
return `s|^[[:space:]]*\(export[[:space:]]\{1,\}\)\{0,1\}` + k + `=["']\{0,1\}\(` + p + `[^"' #]*\).*$|\2|p`
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// launchShell gives the shells at the place the function of l, or takes
|
||||
// it out of them: this machine's (as `magpie <id> run`), a distro's (vars
|
||||
// and the model written in, distroProfiles). What fails leaves the setting
|
||||
// as it is: the row's command still starts it.
|
||||
type launchShell struct {
|
||||
l *launchSpec
|
||||
at place
|
||||
distro bool
|
||||
// fn is the function in a distro's shell of kind, as it is now
|
||||
fn func(kind string) string
|
||||
}
|
||||
|
||||
func (s launchShell) set(on bool) {
|
||||
switch {
|
||||
case !s.distro:
|
||||
if here, _ := homes(); here != s.at.home {
|
||||
return
|
||||
}
|
||||
if on {
|
||||
update.ShellFunction(s.l.bin, s.l.function)
|
||||
} else {
|
||||
update.DropShellFunction(s.l.bin)
|
||||
}
|
||||
case on:
|
||||
update.ShellFunctionAt(agyDistroProfiles(s.at), s.l.bin, s.fn)
|
||||
default:
|
||||
update.DropShellFunctionAt(agyDistroProfiles(s.at), s.l.bin)
|
||||
}
|
||||
}
|
||||
|
||||
// in are the profiles that have the function.
|
||||
func (s launchShell) in() []string {
|
||||
if !s.distro {
|
||||
if here, _ := homes(); here != s.at.home {
|
||||
return nil
|
||||
}
|
||||
return update.ShellFunctionIn(s.l.bin)
|
||||
}
|
||||
return update.ShellFunctionInAt(agyDistroProfiles(s.at), s.l.bin)
|
||||
}
|
||||
|
||||
// stale says a distro's function names what is no longer so (the
|
||||
// gateway's address, which WSL's NAT changes on a restart): the profile
|
||||
// it is in, "" for none.
|
||||
func (s launchShell) stale() string {
|
||||
if !s.distro {
|
||||
return ""
|
||||
}
|
||||
for _, p := range s.in() {
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, k := range []string{"posix", "fish"} {
|
||||
if strings.Contains(string(b), s.fn(k)) {
|
||||
goto next
|
||||
}
|
||||
}
|
||||
return p
|
||||
next:
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// what an agent a plugin adds that is started on magpie says after a
|
||||
// change (notice.go)
|
||||
var (
|
||||
noticeLaunch = newNotice("{agent} takes magpie's gateway and model only from how it is started — start it with {command}")
|
||||
noticeLaunchTyped = newNotice("Type {bin} in a new terminal: magpie added it to {profiles}, to start {agent} on magpie's gateway and model (in a terminal open now: {command}).")
|
||||
)
|
||||
|
||||
// Starting is what starts an agent on magpie (Agent.Start): the command
|
||||
// on PATH, the variables, the flags with their values put before the
|
||||
// user's arguments (Args, flag then value: agy's --settings <file>), and
|
||||
// the model after Flag (none when Flag is ""); Model "" while it isn't on
|
||||
// magpie's, and it starts as it is. With one of Plain among the user's
|
||||
// arguments (alone or with "=value") it starts as it is too.
|
||||
type Starting struct {
|
||||
Bin string
|
||||
Env []string
|
||||
Args []string
|
||||
Model string
|
||||
Flag string
|
||||
Plain []string
|
||||
}
|
||||
|
||||
// Plained says a is one of Plain, alone or with "=value".
|
||||
func (s Starting) Plained(a string) bool {
|
||||
a, _, _ = strings.Cut(a, "=")
|
||||
return slices.Contains(s.Plain, a)
|
||||
}
|
||||
|
||||
// Given says a is the model's flag in one of its forms (--model, -model),
|
||||
// alone or with "=value".
|
||||
func (s Starting) Given(a string) bool {
|
||||
if s.Flag == "" {
|
||||
return false
|
||||
}
|
||||
return (&launchSpec{flag: s.Flag}).given(a)
|
||||
}
|
||||
|
||||
// Names are the variables' names.
|
||||
func (s Starting) Names() []string {
|
||||
out := make([]string, 0, len(s.Env))
|
||||
for _, kv := range s.Env {
|
||||
k, _, _ := strings.Cut(kv, "=")
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentplug"
|
||||
)
|
||||
|
||||
// agyLaunchDesc is agent-agy's launch: the gateway in env, magpie's own
|
||||
// settings file through --settings, and remote-control as agy is.
|
||||
func agyLaunchDesc() agentplug.Desc {
|
||||
return agentplug.Desc{ID: "agy", Bin: "agy", Format: "json", Model: "model", Prefix: "magpie/",
|
||||
Launch: &agentplug.Launch{Env: map[string]string{"GEMINI_API_KEY": "{key}"}, Model: "--model",
|
||||
Args: map[string]string{"--settings": "{config}"}, Plain: []string{"remote-control", "--remote-control", "-remote-control"}}}
|
||||
}
|
||||
|
||||
// The function a distro's shell gets starts the agent with launch.args
|
||||
// before the model, the user's arguments after, and runs a plain argument
|
||||
// as the agent is: in bash, zsh and fish, whichever are here.
|
||||
func TestPluggedDistroFunctionArgsAndPlain(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the distro's shells")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
cfg := filepath.Join(dir, "magpie settings.json")
|
||||
writeFile(t, cfg, `{"model": "magpie/relay/glm"}`)
|
||||
bin := t.TempDir()
|
||||
writeFile(t, filepath.Join(bin, "agy"), "#!/bin/sh\necho \"key=$GEMINI_API_KEY args=$*\"\n")
|
||||
os.Chmod(filepath.Join(bin, "agy"), 0o755)
|
||||
l := newLaunch(agyLaunchDesc(), cfg)
|
||||
read := modelSed("json", "model", "magpie/")
|
||||
vars := l.vars("http://gw", "k1")
|
||||
for _, sh := range []string{"bash", "zsh", "fish"} {
|
||||
path, err := exec.LookPath(sh)
|
||||
if err != nil {
|
||||
t.Logf("no %s", sh)
|
||||
continue
|
||||
}
|
||||
kind := "posix"
|
||||
if sh == "fish" {
|
||||
kind = "fish"
|
||||
}
|
||||
fn := filepath.Join(t.TempDir(), "fn")
|
||||
writeFile(t, fn, l.distroFunction(kind, vars, read, cfg, ""))
|
||||
run := func(args string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command(path, "-c", "source "+posixQuote(fn)+"; agy "+args)
|
||||
cmd.Env = []string{"HOME=" + dir, "PATH=" + bin + ":/usr/bin:/bin"}
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%s %s: %v\n%s", sh, args, err, out)
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
on := "key=k1 args=--settings " + cfg + " "
|
||||
for args, want := range map[string]string{
|
||||
"-p hi": on + "--model magpie/relay/glm -p hi",
|
||||
"--model=own -p hi": on + "--model=own -p hi",
|
||||
"remote-control start": "key= args=remote-control start",
|
||||
"--remote-control": "key= args=--remote-control",
|
||||
"-p x -remote-control=y": "key= args=-p x -remote-control=y",
|
||||
} {
|
||||
if got := run(args); got != want {
|
||||
t.Errorf("%s agy %s:\n got %s\nwant %s", sh, args, got, want)
|
||||
}
|
||||
}
|
||||
// off magpie: as it is
|
||||
writeFile(t, cfg, `{"model": "gemini-3-pro"}`)
|
||||
if got := run("-p hi"); got != "key= args=-p hi" {
|
||||
t.Errorf("%s off magpie: %s", sh, got)
|
||||
}
|
||||
writeFile(t, cfg, `{"model": "magpie/relay/glm"}`)
|
||||
}
|
||||
}
|
||||
|
||||
// The PowerShell function starts the agent with launch.args from what
|
||||
// `magpie <id> env` prints (settings=…), and runs a plain argument as the
|
||||
// agent is.
|
||||
func TestPluggedPowerShellFunctionArgsAndPlain(t *testing.T) {
|
||||
ps, err := exec.LookPath("pwsh")
|
||||
if err != nil {
|
||||
if ps, err = exec.LookPath("powershell"); err != nil {
|
||||
t.Skip("no PowerShell")
|
||||
}
|
||||
}
|
||||
dir := t.TempDir()
|
||||
cfg := filepath.Join(dir, "magpie settings.json")
|
||||
var prog string
|
||||
if runtime.GOOS == "windows" {
|
||||
prog = filepath.Join(dir, "magpie.cmd")
|
||||
writeFile(t, prog, "@echo GEMINI_API_KEY=k1\r\n@echo settings="+cfg+"\r\n@echo model=magpie/relay/glm\r\n")
|
||||
writeFile(t, filepath.Join(dir, "agy.cmd"), "@echo key=%GEMINI_API_KEY% args=%*\r\n")
|
||||
} else {
|
||||
prog = filepath.Join(dir, "magpie")
|
||||
writeFile(t, prog, "#!/bin/sh\necho GEMINI_API_KEY=k1\necho 'settings="+cfg+"'\necho model=magpie/relay/glm\n")
|
||||
writeFile(t, filepath.Join(dir, "agy"), "#!/bin/sh\necho \"key=$GEMINI_API_KEY args=$*\"\n")
|
||||
os.Chmod(prog, 0o755)
|
||||
os.Chmod(filepath.Join(dir, "agy"), 0o755)
|
||||
}
|
||||
l := newLaunch(agyLaunchDesc(), cfg)
|
||||
fn := filepath.Join(dir, "fn.ps1")
|
||||
writeFile(t, fn, l.function("powershell", prog))
|
||||
run := func(args string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command(ps, "-NoProfile", "-NonInteractive", "-Command", ". '"+fn+"'; agy "+args)
|
||||
cmd.Env = append(os.Environ(), "PATH="+dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("agy %s: %v\n%s", args, err, out)
|
||||
}
|
||||
return strings.Join(strings.Fields(strings.ReplaceAll(string(out), `"`, "")), " ")
|
||||
}
|
||||
for args, want := range map[string]string{
|
||||
"-p hi": "key=k1 args=--settings " + cfg + " --model magpie/relay/glm -p hi",
|
||||
"--model=own -p hi": "key=k1 args=--settings " + cfg + " --model=own -p hi",
|
||||
"remote-control start": "key= args=remote-control start",
|
||||
"--remote-control": "key= args=--remote-control",
|
||||
} {
|
||||
if got := run(args); got != strings.Join(strings.Fields(want), " ") {
|
||||
t.Errorf("agy %s:\n got %s\nwant %s", args, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package agent
|
||||
|
||||
// A built-in agent can move onto a community agent plugin, as the retired
|
||||
// built-in subscriptions moved onto provider plugins (AGENTS.md). While
|
||||
// the plugin agentMovers names for it is installed and on, the agent is
|
||||
// the plugin's: the built-in is left out of the list (on this machine and
|
||||
// in WSL distros, wslKind.served), its id and aliases are the plugin's,
|
||||
// and what the built-in had wired is handed over (handovers), so the
|
||||
// plugin's agent reads as connected and puts back what the user had when
|
||||
// magpie steps out. With the plugin off or removed the built-in is back.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentplug"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
)
|
||||
|
||||
// agentMovers are the built-in agents a community plugin serves, by id:
|
||||
// the plugin's npm package. A var so tests can name their own.
|
||||
var agentMovers = map[string]string{"agy": "@magpie-community/agent-agy"}
|
||||
|
||||
// movedAgent is the plugin listed that serves the built-in agent id, nil
|
||||
// for none.
|
||||
func movedAgent(id string) *agentplug.Agent {
|
||||
pkg, ok := agentMovers[id]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
list, _ := agentplug.List()
|
||||
for _, p := range list {
|
||||
if movesTo(id, p) && plugin.Name(p.Spec) == pkg {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// movesTo says p's agent is the one the built-in id moves onto: its id is
|
||||
// the built-in's, and agentMovers names its package.
|
||||
func movesTo(id string, p *agentplug.Agent) bool {
|
||||
pkg, ok := agentMovers[id]
|
||||
return ok && p.Desc.ID == id && plugin.Name(p.Spec) == pkg
|
||||
}
|
||||
|
||||
// dropMoved is list without the built-ins a plugin listed serves.
|
||||
func dropMoved(list []*Agent) []*Agent {
|
||||
moved := map[string]bool{}
|
||||
for id := range agentMovers {
|
||||
if movedAgent(id) != nil {
|
||||
moved[id] = true
|
||||
}
|
||||
}
|
||||
if len(moved) == 0 {
|
||||
return list
|
||||
}
|
||||
out := list[:0:0]
|
||||
for _, a := range list {
|
||||
if !moved[a.ID] {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// handovers turn what a built-in agent wired at a place into the plugin's
|
||||
// stash of its file f, by id; false when the built-in hadn't wired it.
|
||||
var handovers = map[string]func(at place, f pluggedFile) (pluggedStash, bool){"agy": agyHandover}
|
||||
|
||||
// handedOver is the stash of the plugin spec's agent id at f, under key,
|
||||
// made from what the built-in had wired there, and saved; false when
|
||||
// there is nothing to hand over.
|
||||
func handedOver(id string, at place, f pluggedFile, spec, key string) (pluggedStash, bool) {
|
||||
h := handovers[id]
|
||||
if h == nil || agentMovers[id] != plugin.Name(spec) {
|
||||
return pluggedStash{}, false
|
||||
}
|
||||
st, ok := h(at, f)
|
||||
if !ok {
|
||||
return st, false
|
||||
}
|
||||
st.Spec, st.Format = spec, f.format
|
||||
b, _ := json.Marshal(st)
|
||||
stash(map[string]string{key: string(b)})
|
||||
return st, true
|
||||
}
|
||||
|
||||
// agyHandover is the built-in agy's wiring as the agent-agy plugin's,
|
||||
// whose config is magpie's own settings file too (agyOverride). A
|
||||
// settings.json an older built-in wired is given back first, as the
|
||||
// built-in's Sync does (migrate), its model moved into magpie's file;
|
||||
// then, while that file's model is magpie's, the file is the plugin's:
|
||||
// every key it has was magpie's, so stepping out takes the file away.
|
||||
func agyHandover(at place, f pluggedFile) (pluggedStash, bool) {
|
||||
if filepath.Base(f.path) != agyOverride {
|
||||
return pluggedStash{}, false
|
||||
}
|
||||
b := agyIn(at)
|
||||
if usesMagpie(jsonGet(b.Path, "model")()) {
|
||||
if err := b.Sync(); err != nil {
|
||||
return pluggedStash{}, false
|
||||
}
|
||||
}
|
||||
model, _ := f.get("model")
|
||||
if !usesMagpie(model) {
|
||||
return pluggedStash{}, false
|
||||
}
|
||||
had := map[string]string{}
|
||||
for _, k := range []string{"model", "modelProvider", agyModels} {
|
||||
had[k] = "\x00"
|
||||
}
|
||||
return pluggedStash{
|
||||
Had: had,
|
||||
Ref: strings.TrimPrefix(model, magpieID+"/"),
|
||||
Value: model,
|
||||
Wrote: map[string]string{"modelProvider": "gemini"},
|
||||
}, true
|
||||
}
|
||||
+10
-1
@@ -448,6 +448,15 @@ type wslKind struct {
|
||||
ownNotice bool
|
||||
}
|
||||
|
||||
// served is k with its agent the plugin's, where a plugin that says wsl
|
||||
// serves the built-in now (agentMovers).
|
||||
func (k wslKind) served() wslKind {
|
||||
if p := movedAgent(k.id); p != nil && p.Desc.WSL {
|
||||
k.in = func(at place) *Agent { return plugged(at, p) }
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
var wslKinds = []wslKind{
|
||||
// its daemon, which magpie starts there itself (claudescience_wsl.go):
|
||||
// the probe looks in ~/.local/bin, where its installer puts it
|
||||
@@ -1153,7 +1162,7 @@ func wslAgentsOf(ds []distro) []*Agent {
|
||||
// distro's files opened start it again (#3896)
|
||||
for _, k := range wslKinds {
|
||||
if k.found(d) {
|
||||
out = append(out, wslAgent(k, d))
|
||||
out = append(out, wslAgent(k.served(), d))
|
||||
}
|
||||
}
|
||||
// the named omp profiles the probe remembered: the row is made
|
||||
|
||||
+221
-11
@@ -46,6 +46,49 @@
|
||||
// mcp: "~/.aider/mcp.json", mcpFormat: "claude",
|
||||
// skills: "~/.aider/skills",
|
||||
// }
|
||||
//
|
||||
// An agent that takes the gateway only from how it is started (agy reads
|
||||
// GEMINI_API_KEY and GOOGLE_GEMINI_BASE_URL from its environment, and
|
||||
// resolves a model only given on its command line) says so with launch,
|
||||
// beside model and bin. While it is on one of magpie's models its row
|
||||
// gives the command, and magpie puts a function named bin in the user's
|
||||
// shells that runs `magpie <id> run`: the agent started with env, each
|
||||
// {url}, {v1} and {key} the gateway's, and the model after launch.model's
|
||||
// flag (none when the user gives that flag).
|
||||
//
|
||||
// launch: {
|
||||
// env: { GEMINI_API_KEY: "{key}", GOOGLE_GEMINI_BASE_URL: "{url}" },
|
||||
// model: "--model",
|
||||
// }
|
||||
//
|
||||
// merge names keys whose object connect returns only magpie's members of:
|
||||
// each member is written on its own beside the user's, and taken out
|
||||
// again when magpie steps out (agy's customModelsConfig.customModels).
|
||||
// effort: true gives its row a field for how hard magpie's models reason,
|
||||
// which the gateway asks its requests for (an agent with no setting of
|
||||
// its own for it). wsl: true, for an agent that takes a built-in's place
|
||||
// (magpie's agentMovers), has it wired in WSL distros too where the
|
||||
// built-in was; aliases are other names it is typed as.
|
||||
//
|
||||
// An agent that reads a settings file of magpie's own only when it is so
|
||||
// started (agy's --settings) names it as config, the flag that hands it
|
||||
// over in launch.args, and its own settings file as base: magpie writes
|
||||
// only config, which it removes when magpie steps out, and the user's
|
||||
// own model goes in base. connect's input and own's have base, parsed,
|
||||
// so connect can carry the user's own entries over (agy takes
|
||||
// customModels whole from the --settings file). launch.plain are the
|
||||
// arguments that start it as it is (agy's remote-control, which needs
|
||||
// its Google sign-in).
|
||||
//
|
||||
// config: "~/.gemini/antigravity-cli/magpie-settings.json",
|
||||
// base: "~/.gemini/antigravity-cli/settings.json",
|
||||
// launch: { env: {…}, model: "--model", args: { "--settings": "{config}" }, plain: ["remote-control", "--remote-control"] },
|
||||
//
|
||||
// A module may also export own({ config, base, model }), given its config
|
||||
// file (and base) as parsed JSON ({} for none) and the model it is on
|
||||
// now, returning the agent's own models for its picker, each { value,
|
||||
// model, direct }: the value written, the model's name for its picture,
|
||||
// and the vendor it goes to without magpie.
|
||||
package agentplug
|
||||
|
||||
import (
|
||||
@@ -54,6 +97,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -107,6 +151,53 @@ type Desc struct {
|
||||
// for an agent that keeps it apart from config; nil for one that
|
||||
// keeps it in config (Model) or picks it itself
|
||||
Startup *Startup `json:"startup"`
|
||||
// Base is the agent's own settings file, for one whose config is a
|
||||
// file of magpie's alone (launch.args names it): the user's model is
|
||||
// there off magpie, and connect and own are given it as base; magpie
|
||||
// never writes it but for the user's own model picked in its row
|
||||
Base string `json:"base"`
|
||||
// Launch is how the agent is started on magpie, for one that takes the
|
||||
// gateway only from its environment and command line; nil for one its
|
||||
// config file connects
|
||||
Launch *Launch `json:"launch"`
|
||||
// Merge are key paths whose object connect returns magpie's members
|
||||
// of, each written beside the user's own (json only)
|
||||
Merge []string `json:"merge"`
|
||||
// Effort gives the agent's row magpie's effort field
|
||||
Effort bool `json:"effort"`
|
||||
// WSL has the agent in WSL distros too
|
||||
WSL bool `json:"wsl"`
|
||||
// Aliases are other names the agent is typed as
|
||||
Aliases []string `json:"aliases"`
|
||||
}
|
||||
|
||||
// Launch is the environment an agent is started with, by variable, each
|
||||
// value {key}, {url} or {v1} (the gateway's), or a path under the address,
|
||||
// and Model the flag that names its model on the command line ("" for
|
||||
// none).
|
||||
type Launch struct {
|
||||
Env map[string]string `json:"env"`
|
||||
Model string `json:"model"`
|
||||
// Args are flags put before the user's arguments, each with its value
|
||||
// "{config}", the path of agent.config: agy's --settings, for a config
|
||||
// that is magpie's own file the agent reads only when so started
|
||||
Args map[string]string `json:"args"`
|
||||
// Plain are arguments (a subcommand or a flag, alone or with
|
||||
// "=value") with which the agent starts as it is, off magpie: agy's
|
||||
// remote-control, which needs its own sign-in
|
||||
Plain []string `json:"plain"`
|
||||
}
|
||||
|
||||
// Fill is v with {url}, {v1} and {key} as given.
|
||||
func Fill(v, url, v1, key string) string {
|
||||
return strings.NewReplacer("{url}", url, "{v1}", v1, "{key}", key).Replace(v)
|
||||
}
|
||||
|
||||
// Own is one of an agent's own models, as own() gives it.
|
||||
type Own struct {
|
||||
Value string `json:"value"`
|
||||
Model string `json:"model"`
|
||||
Direct string `json:"direct"`
|
||||
}
|
||||
|
||||
// Startup is where an agent keeps the model it starts on, apart from the
|
||||
@@ -150,6 +241,8 @@ type Agent struct {
|
||||
rt *moejs.Runtime
|
||||
connect moejs.Hook
|
||||
has bool
|
||||
own moejs.Hook
|
||||
hasOwn bool
|
||||
}
|
||||
|
||||
// How long the module may take to load, and connect to answer.
|
||||
@@ -160,7 +253,19 @@ var (
|
||||
|
||||
var errTimeout = errors.New("took too long")
|
||||
|
||||
var idOK = lazyre.New(`^[a-z0-9][a-z0-9._-]{0,63}$`)
|
||||
var (
|
||||
idOK = lazyre.New(`^[a-z0-9][a-z0-9._-]{0,63}$`)
|
||||
binOK = lazyre.New(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
|
||||
envOK = lazyre.New(`^[A-Za-z_][A-Za-z0-9_]{0,127}$`)
|
||||
flagOK = lazyre.New(`^--?[A-Za-z0-9][A-Za-z0-9-]{0,63}$`)
|
||||
// a plain argument: a subcommand or a flag
|
||||
plainOK = lazyre.New(`^-{0,2}[A-Za-z0-9][A-Za-z0-9-]{0,63}$`)
|
||||
// a launch variable's value is magpie's address or key, a path under
|
||||
// the address at most: it goes into the user's shell profiles, and a
|
||||
// variable such as LD_PRELOAD or NODE_OPTIONS gets nothing a plugin
|
||||
// chose
|
||||
envValueOK = lazyre.New(`^(\{key\}|\{(url|v1)\}(/[A-Za-z0-9._~-]+)*/?)$`)
|
||||
)
|
||||
|
||||
type set struct {
|
||||
stamp string
|
||||
@@ -301,6 +406,14 @@ func Compile(spec, file string) (*Agent, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, h := range [][]string{{"own"}, {"default", "own"}} {
|
||||
if hk, err := mod.Hook(h[0], h[1:]...); err == nil {
|
||||
if ok, _ := a.rt.Has(hk); ok {
|
||||
a.own, a.hasOwn = hk, true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
// connect only: with no model key, connect's keys are all magpie
|
||||
// writes, so a module with neither would write nothing
|
||||
if a.Desc.Startup != nil && !a.has {
|
||||
@@ -374,15 +487,116 @@ func (d *Desc) check() error {
|
||||
for i, u := range d.UA {
|
||||
d.UA[i] = strings.ToLower(u)
|
||||
}
|
||||
if l := d.Launch; l != nil {
|
||||
l.Model = strings.TrimSpace(l.Model)
|
||||
switch {
|
||||
case d.Model == "":
|
||||
return errors.New("agent.launch starts the agent on a model: name its key with agent.model")
|
||||
case !binOK.MatchString(d.Bin):
|
||||
return fmt.Errorf("agent.launch needs agent.bin, the command it starts, as a shell names a function (letters, digits, '_' and '-'), not %q", d.Bin)
|
||||
case len(l.Env) == 0 && l.Model == "":
|
||||
return errors.New("agent.launch gives neither env nor a model flag")
|
||||
case l.Model != "" && !flagOK.MatchString(l.Model):
|
||||
return fmt.Errorf("agent.launch.model %q: a flag, as --model", l.Model)
|
||||
}
|
||||
for f, v := range l.Args {
|
||||
if !flagOK.MatchString(f) || f == l.Model {
|
||||
return fmt.Errorf("agent.launch.args %q: a flag, as --settings, not the model's", f)
|
||||
}
|
||||
if v != "{config}" {
|
||||
return fmt.Errorf("agent.launch.args %s %q: {config}, agent.config's path", f, v)
|
||||
}
|
||||
}
|
||||
for i, a := range l.Plain {
|
||||
a = strings.TrimSpace(a)
|
||||
if !plainOK.MatchString(a) {
|
||||
return fmt.Errorf("agent.launch.plain %q: a subcommand or a flag", a)
|
||||
}
|
||||
l.Plain[i] = a
|
||||
}
|
||||
for k := range l.Env {
|
||||
if !envOK.MatchString(k) {
|
||||
return fmt.Errorf("agent.launch.env %q: a variable's name", k)
|
||||
}
|
||||
if !envValueOK.MatchString(l.Env[k]) {
|
||||
return fmt.Errorf("agent.launch.env %s %q: {key}, {url} or {v1}, a path after the address at most", k, l.Env[k])
|
||||
}
|
||||
}
|
||||
}
|
||||
if d.Base = strings.TrimSpace(d.Base); d.Base != "" {
|
||||
switch {
|
||||
case d.Launch == nil || !slices.Contains(slices.Collect(maps.Values(d.Launch.Args)), "{config}"):
|
||||
return errors.New("agent.base is for an agent.config that agent.launch.args hands the agent, as magpie's own file")
|
||||
case d.Base == strings.TrimSpace(d.Config):
|
||||
return errors.New("agent.base is agent.config")
|
||||
case FormatOf(d.Base) != "" && FormatOf(d.Base) != d.Format:
|
||||
return fmt.Errorf("agent.base %q: a file of agent.format, %s", d.Base, d.Format)
|
||||
}
|
||||
}
|
||||
for i, m := range d.Merge {
|
||||
m = strings.TrimSpace(m)
|
||||
switch {
|
||||
case d.Format != "json":
|
||||
return errors.New("agent.merge is for a json agent.config")
|
||||
case m == "":
|
||||
return errors.New("agent.merge names an empty key")
|
||||
case m == d.Model:
|
||||
return fmt.Errorf("agent.merge %q is the model's own key", m)
|
||||
}
|
||||
d.Merge[i] = m
|
||||
}
|
||||
for i, al := range d.Aliases {
|
||||
al = strings.TrimSpace(al)
|
||||
if !idOK.MatchString(al) || al == d.ID {
|
||||
return fmt.Errorf("agent.aliases %q: lower-case letters, digits, '.', '_' and '-', not its id", al)
|
||||
}
|
||||
d.Aliases[i] = al
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HasOwn says the module exports own.
|
||||
func (a *Agent) HasOwn() bool { return a.hasOwn }
|
||||
|
||||
// OwnModels is what the module's own gives for config, the agent's file
|
||||
// as parsed JSON, base, its own settings file so (agent.base; nil for
|
||||
// none), and model, the one it is on now; none for a module without it.
|
||||
func (a *Agent) OwnModels(config, base any, model string) ([]Own, error) {
|
||||
if !a.hasOwn {
|
||||
return nil, nil
|
||||
}
|
||||
in := map[string]any{"config": config, "model": model}
|
||||
if base != nil {
|
||||
in["base"] = base
|
||||
}
|
||||
b, err := a.call(a.own, "own", in)
|
||||
if err != nil || b == nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []Own
|
||||
if err := json.Unmarshal(b, &out); err != nil {
|
||||
return nil, errors.New("own returned no list of models")
|
||||
}
|
||||
return slices.DeleteFunc(out, func(o Own) bool { return o.Value == "" }), nil
|
||||
}
|
||||
|
||||
// Connect is what the module's connect returns for in: the keys to write
|
||||
// beside the model, by key path. A module without connect writes none.
|
||||
func (a *Agent) Connect(in map[string]any) (map[string]any, error) {
|
||||
if !a.has {
|
||||
return nil, nil
|
||||
}
|
||||
b, err := a.call(a.connect, "connect", in)
|
||||
if err != nil || b == nil {
|
||||
return nil, err
|
||||
}
|
||||
return keys(b)
|
||||
}
|
||||
|
||||
// call calls the module's hook named name with in, and gives what it
|
||||
// returns as JSON text: nil for nothing, an error for what isn't an
|
||||
// object or a list.
|
||||
func (a *Agent) call(hook moejs.Hook, name string, in map[string]any) ([]byte, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
defer a.rt.ReleaseCallData()
|
||||
@@ -393,33 +607,29 @@ func (a *Agent) Connect(in map[string]any) (map[string]any, error) {
|
||||
var res moejs.Value
|
||||
err = a.limit(connectLimit, func() error {
|
||||
var err error
|
||||
res, err = a.rt.Call(a.connect, arg)
|
||||
res, err = a.rt.Call(hook, arg)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect: %s", errText(err))
|
||||
return nil, fmt.Errorf("%s: %s", name, errText(err))
|
||||
}
|
||||
if st, v, ok := moejs.PromiseResult(res); ok {
|
||||
switch st {
|
||||
case moejs.PromiseFulfilled:
|
||||
res = v
|
||||
case moejs.PromiseRejected:
|
||||
return nil, fmt.Errorf("connect rejected: %s", text(a.rt, v))
|
||||
return nil, fmt.Errorf("%s rejected: %s", name, text(a.rt, v))
|
||||
default:
|
||||
return nil, errors.New("connect returned a promise that never settled")
|
||||
return nil, fmt.Errorf("%s returned a promise that never settled", name)
|
||||
}
|
||||
}
|
||||
if res.IsUndefined() || res.IsNull() {
|
||||
return nil, nil
|
||||
}
|
||||
if !res.IsObject() {
|
||||
return nil, errors.New("connect returned neither an object nor nothing")
|
||||
return nil, fmt.Errorf("%s returned neither an object nor nothing", name)
|
||||
}
|
||||
b, err := a.rt.AppendJSON(nil, res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return keys(b)
|
||||
return a.rt.AppendJSON(nil, res)
|
||||
}
|
||||
|
||||
// keys is connect's result, as JSON text, by key path. An object or array
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package agentplug
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func compileSrc(t *testing.T, src string) (*Agent, error) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "agent.js")
|
||||
if err := os.WriteFile(file, []byte(src), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return Compile(dir, file)
|
||||
}
|
||||
|
||||
// What agent.launch says goes into the user's shell profiles: the command,
|
||||
// the variables' names and their values. A module can say only names a
|
||||
// shell takes as they are, and values that are magpie's address or key,
|
||||
// so no plugin puts a command of its own, or a value of its choosing
|
||||
// (LD_PRELOAD, NODE_OPTIONS), into the user's shells.
|
||||
func TestLaunchSaysOnlyWhatAShellTakesAsItIs(t *testing.T) {
|
||||
desc := func(launch, bin string) string {
|
||||
return `export const agent = { id: "lx", bin: "` + bin + `", config: "~/.lx.json", model: "model", prefix: "magpie/", launch: ` + launch + ` };`
|
||||
}
|
||||
ok := []string{
|
||||
`{ env: { GEMINI_API_KEY: "{key}", GOOGLE_GEMINI_BASE_URL: "{url}" }, model: "--model" }`,
|
||||
`{ env: { BASE: "{v1}" } }`,
|
||||
`{ env: { BASE: "{url}/api/v2/" } }`,
|
||||
`{ model: "-m" }`,
|
||||
`{ model: "--model", args: { "--settings": "{config}" }, plain: ["remote-control", "--remote-control"] }`,
|
||||
}
|
||||
for _, l := range ok {
|
||||
a, err := compileSrc(t, desc(l, "lx"))
|
||||
if err != nil || a.Desc.Launch == nil {
|
||||
t.Errorf("%s: %v", l, err)
|
||||
}
|
||||
}
|
||||
bad := map[string]string{
|
||||
desc(`{ env: { K: "{key}; rm -rf ~" } }`, "lx"): "agent.launch.env K",
|
||||
desc(`{ env: { LD_PRELOAD: "/tmp/x.so" } }`, "lx"): "agent.launch.env LD_PRELOAD",
|
||||
desc(`{ env: { NODE_OPTIONS: "--require=/x {key}" } }`, "lx"): "agent.launch.env NODE_OPTIONS",
|
||||
desc(`{ env: { BASE: "{url}/$(id)" } }`, "lx"): "agent.launch.env BASE",
|
||||
desc(`{ env: { BASE: "{url}/../x" } }`, "lx"): "",
|
||||
desc(`{ env: { "A B": "{key}" } }`, "lx"): "a variable's name",
|
||||
desc(`{ model: "--model; id" }`, "lx"): "a flag",
|
||||
desc(`{ model: "--model" }`, "lx; id"): "agent.bin",
|
||||
desc(`{}`, "lx"): "neither env nor a model flag",
|
||||
desc(`{ model: "-m", args: { "--settings": "/tmp/x" } }`, "lx"): "agent.launch.args --settings",
|
||||
desc(`{ model: "-m", args: { "--x; id": "{config}" } }`, "lx"): "agent.launch.args",
|
||||
desc(`{ model: "-m", args: { "-m": "{config}" } }`, "lx"): "not the model's",
|
||||
desc(`{ model: "-m", plain: ["a b"] }`, "lx"): "agent.launch.plain",
|
||||
desc(`{ model: "-m", plain: ["x;id"] }`, "lx"): "agent.launch.plain",
|
||||
}
|
||||
for src, want := range bad {
|
||||
_, err := compileSrc(t, src)
|
||||
if want == "" {
|
||||
// a dot path is still a path under the address: a shell takes it as it is
|
||||
if err != nil {
|
||||
t.Errorf("%s: %v", src, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%s: %v, want %q", src, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// own is given the agent's file as parsed and the model it is on, and
|
||||
// what it lists without a value is left out.
|
||||
func TestOwnModels(t *testing.T) {
|
||||
a, err := compileSrc(t, `export const agent = { id: "lx", config: "~/.lx.json", model: "model" };
|
||||
export function own({ config, base, model }) {
|
||||
return [...Object.keys((base ?? config).models ?? {}).map((k) => ({ value: k, direct: "Google" })), { value: model, model: "m-" + model }, { value: "" }];
|
||||
}`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !a.HasOwn() {
|
||||
t.Fatal("own not found")
|
||||
}
|
||||
got, err := a.OwnModels(map[string]any{"models": map[string]any{"mine": true}}, nil, "cur")
|
||||
if err != nil || len(got) != 2 || got[0] != (Own{Value: "mine", Direct: "Google"}) || got[1] != (Own{Value: "cur", Model: "m-cur"}) {
|
||||
t.Fatalf("own: %+v %v", got, err)
|
||||
}
|
||||
// the agent's own file, when it has one, is given as base
|
||||
got, err = a.OwnModels(map[string]any{}, map[string]any{"models": map[string]any{"theirs": true}}, "cur")
|
||||
if err != nil || len(got) != 2 || got[0].Value != "theirs" {
|
||||
t.Fatalf("own with base: %+v %v", got, err)
|
||||
}
|
||||
b, err := compileSrc(t, `export const agent = { id: "lx", config: "~/.lx.json", model: "model" };`)
|
||||
if err != nil || b.HasOwn() {
|
||||
t.Fatalf("no own: %v", err)
|
||||
}
|
||||
if got, err := b.OwnModels(nil, nil, ""); got != nil || err != nil {
|
||||
t.Fatalf("no own: %v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// agent.base, the agent's own file beside magpie's, is only for a config
|
||||
// the agent is handed by agent.launch.args, and is never the config.
|
||||
func TestBaseIsForAHandedConfig(t *testing.T) {
|
||||
src := func(base, launch string) string {
|
||||
return `export const agent = { id: "lx", bin: "lx", config: "~/.lx/magpie.json", base: "` + base + `", model: "model", launch: ` + launch + ` };`
|
||||
}
|
||||
if a, err := compileSrc(t, src("~/.lx/settings.json", `{ model: "-m", args: { "--settings": "{config}" } }`)); err != nil || a.Desc.Base != "~/.lx/settings.json" {
|
||||
t.Fatalf("base: %v", err)
|
||||
}
|
||||
bad := map[string]string{
|
||||
src("~/.lx/settings.json", `{ model: "-m" }`): "agent.launch.args hands the agent",
|
||||
src("~/.lx/magpie.json", `{ model: "-m", args: { "--settings": "{config}" } }`): "agent.base is agent.config",
|
||||
src("~/.lx/settings.yaml", `{ model: "-m", args: { "--settings": "{config}" } }`): "a file of agent.format",
|
||||
}
|
||||
for s, want := range bad {
|
||||
if _, err := compileSrc(t, s); err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("%s: %v, want %q", s, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
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, 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
|
||||
--settings <magpie's file> and --model <its 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.
|
||||
|
||||
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("settings=" + agent.AgySettings())
|
||||
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()
|
||||
// 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, "=")
|
||||
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...)
|
||||
}
|
||||
args = append([]string{"--settings", agent.AgySettings()}, 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)
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
//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)
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
// claudeRunOS starts claude and waits for it, its exit code magpie's, as
|
||||
// agyExecOS does. Ctrl+C is claude's to handle, so magpie lets it pass.
|
||||
// startExecOS does. Ctrl+C is claude's to handle, so magpie lets it pass.
|
||||
func claudeRunOS(bin string, args, env []string) error {
|
||||
cmd := proc.Command(bin, args...)
|
||||
cmd.Env = env
|
||||
|
||||
@@ -140,8 +140,9 @@ 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)
|
||||
if a.Start != nil {
|
||||
bin := a.Start().Bin
|
||||
fmt.Fprintf(&b, " magpie %s run [args…] start %s, on magpie while its model is magpie's (what your shell's %s runs)\n", id, bin, bin)
|
||||
fmt.Fprintf(&b, " magpie %s env the variables and model it is started with\n", id)
|
||||
}
|
||||
if a.ID == "claude" {
|
||||
|
||||
@@ -336,16 +336,17 @@ 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
|
||||
}
|
||||
// claude-magpie (claude_launch_cli.go): every argument after run is
|
||||
// claude's, --help too
|
||||
if ok, err := claudeLaunchCmd(args); ok {
|
||||
return err
|
||||
}
|
||||
// what a shell's agy, or another agent's function, runs
|
||||
// (start_cli.go): every argument after run is the agent's, --help
|
||||
// too, and nothing is moved or started first
|
||||
if ok, err := startCmd(args); ok {
|
||||
return err
|
||||
}
|
||||
// Claude Magpie.app (claude_desktop_launch_cli.go), --help too
|
||||
if ok, err := claudeDesktopLaunchCmd(args); ok {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
)
|
||||
|
||||
// `magpie <agent> run [args…]` is what the function magpie puts in the
|
||||
// user's shells for an agent that takes magpie's gateway and model only
|
||||
// from how it is started (Agent.Start: the built-in agy, an agent plugin
|
||||
// with launch) runs: the agent's command on PATH, given magpie's
|
||||
// variables and model while the agent is on one of magpie's models, and
|
||||
// as it is otherwise (and with an argument that runs it plain, agy's
|
||||
// remote-control, which needs agy's Google sign-in). Every argument is the
|
||||
// agent's, --help too. `magpie <agent> env` prints those variables, the
|
||||
// value of each flag it is started with (settings=<file> for --settings)
|
||||
// and the model, one NAME=value a line and nothing off magpie, for
|
||||
// PowerShell's function.
|
||||
|
||||
func startUsage(id string, s agent.Starting) string {
|
||||
vars := strings.Join(s.Names(), ", ")
|
||||
if vars == "" {
|
||||
vars = "magpie's gateway"
|
||||
}
|
||||
model := ""
|
||||
for i := 0; i+1 < len(s.Args); i += 2 {
|
||||
vars += ", " + s.Args[i] + " " + s.Args[i+1]
|
||||
}
|
||||
if s.Flag != "" {
|
||||
model = " and\n" + s.Flag + " <its model> (not when you give " + s.Flag + " yourself)"
|
||||
}
|
||||
return fmt.Sprintf(`magpie %[1]s run [args…] start %[2]s, on magpie while its model is one of magpie's
|
||||
|
||||
The %[2]s on your PATH starts with %[3]s%[4]s; every argument is
|
||||
%[2]s's. Off magpie's models it starts as it is. The function %[2]s magpie
|
||||
puts in your shell's profile runs this.
|
||||
|
||||
magpie %[1]s env the variables and model it starts %[2]s with, a
|
||||
NAME=value a line; nothing while it isn't on magpie
|
||||
`, id, s.Bin, vars, model)
|
||||
}
|
||||
|
||||
// startCmd is `magpie <agent> run|env …` for an agent magpie starts
|
||||
// (agent.Starter); ok false for another form.
|
||||
func startCmd(args []string) (ok bool, err error) {
|
||||
if len(args) < 2 || args[1] != "run" && args[1] != "env" {
|
||||
return false, nil
|
||||
}
|
||||
a := agent.Starter(args[0])
|
||||
if a == nil {
|
||||
return false, nil
|
||||
}
|
||||
s := a.Start()
|
||||
if args[1] == "run" {
|
||||
return true, startRun(s, args[2:])
|
||||
}
|
||||
if len(args) > 2 {
|
||||
if slices.Contains([]string{"-h", "--help", "help"}, args[2]) {
|
||||
fmt.Print(startUsage(args[0], s))
|
||||
return true, nil
|
||||
}
|
||||
return true, fmt.Errorf("magpie %s env takes nothing after it, not %q", args[0], args[2])
|
||||
}
|
||||
if s.Model == "" {
|
||||
return true, nil
|
||||
}
|
||||
for _, kv := range s.Env {
|
||||
fmt.Println(kv)
|
||||
}
|
||||
for i := 0; i+1 < len(s.Args); i += 2 {
|
||||
fmt.Println(strings.TrimLeft(s.Args[i], "-") + "=" + s.Args[i+1])
|
||||
}
|
||||
fmt.Println("model=" + s.Model)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// startExec starts the program at path as name with args and env, in
|
||||
// place of magpie where the system can (start_exec_*.go); tests set it.
|
||||
var startExec = startExecOS
|
||||
|
||||
// startLook is the command on PATH; tests set it.
|
||||
var startLook = proc.Look
|
||||
|
||||
func startRun(s agent.Starting, args []string) error {
|
||||
path, err := startLook(s.Bin)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s isn't installed, or isn't on your PATH", s.Bin)
|
||||
}
|
||||
if self, err := os.Executable(); err == nil && sameProgram(self, path) {
|
||||
return errors.New("the " + s.Bin + " on your PATH is magpie itself; install the agent")
|
||||
}
|
||||
env := os.Environ()
|
||||
if slices.ContainsFunc(args, s.Plained) {
|
||||
s.Model = ""
|
||||
}
|
||||
if s.Model != "" {
|
||||
names := s.Names()
|
||||
env = slices.DeleteFunc(env, func(kv string) bool {
|
||||
k, _, _ := strings.Cut(kv, "=")
|
||||
return slices.ContainsFunc(names, func(n string) bool { return strings.EqualFold(k, n) })
|
||||
})
|
||||
env = append(env, s.Env...)
|
||||
if s.Flag != "" && !slices.ContainsFunc(args, s.Given) {
|
||||
args = append([]string{s.Flag, s.Model}, args...)
|
||||
}
|
||||
args = append(slices.Clone(s.Args), args...)
|
||||
}
|
||||
return startExec(path, s.Bin, args, env)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -21,16 +21,21 @@ func TestAgyRun(t *testing.T) {
|
||||
os.MkdirAll(filepath.Dir(settings), 0o755)
|
||||
t.Setenv("GEMINI_API_KEY", "users-own")
|
||||
t.Setenv("GOOGLE_GEMINI_BASE_URL", "")
|
||||
var bin string
|
||||
var bin, name 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
|
||||
oldExec, oldLook := startExec, startLook
|
||||
t.Cleanup(func() { startExec, startLook = oldExec, oldLook })
|
||||
startExec = func(b, n string, a, e []string) error {
|
||||
bin, name, args, env = b, n, a, e
|
||||
return nil
|
||||
}
|
||||
real := filepath.Join(home, "bin", "agy")
|
||||
agyLook = func() (string, error) { return real, nil }
|
||||
startLook = func(b string) (string, error) {
|
||||
if b != "agy" {
|
||||
return "", errors.New("looked for " + b)
|
||||
}
|
||||
return real, nil
|
||||
}
|
||||
envOf := func(k string) []string {
|
||||
var out []string
|
||||
for _, kv := range env {
|
||||
@@ -52,7 +57,7 @@ func TestAgyRun(t *testing.T) {
|
||||
if _, err := runOut(t, append([]string{"agy", "run"}, c.in...)...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bin != real || !slices.Equal(args, c.want) {
|
||||
if bin != real || name != "agy" || !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()}) {
|
||||
@@ -94,7 +99,7 @@ func TestAgyRun(t *testing.T) {
|
||||
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") }
|
||||
startLook = func(string) (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)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//go:build !windows
|
||||
|
||||
package cli
|
||||
|
||||
import "syscall"
|
||||
|
||||
// startExecOS runs the agent at path as name in magpie's place: the
|
||||
// terminal's signals and exit code are the agent's own.
|
||||
func startExecOS(path, name string, args, env []string) error {
|
||||
return syscall.Exec(path, append([]string{name}, args...), env)
|
||||
}
|
||||
@@ -9,10 +9,11 @@ import (
|
||||
"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...)
|
||||
// startExecOS starts the agent at path and waits for it, its exit code
|
||||
// magpie's: Windows has no exec. Ctrl+C is the agent's to handle, so
|
||||
// magpie lets it pass.
|
||||
func startExecOS(path, _ string, args, env []string) error {
|
||||
cmd := proc.Command(path, args...)
|
||||
cmd.Env = env
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
signal.Ignore(os.Interrupt)
|
||||
+16
-2
@@ -165,8 +165,22 @@ func splitPath(keyPath string) []string {
|
||||
return append(parts, keyPath[start:])
|
||||
}
|
||||
|
||||
// unescapeKey is a key path's part as the key it names.
|
||||
func unescapeKey(part string) string { return strings.ReplaceAll(part, `\.`, ".") }
|
||||
// unescapeKey is a key path's part as the key it names: each character
|
||||
// after a backslash as it is, as gjson.Escape writes them (a model id's
|
||||
// '.', a '*' or '?' gjson would match on).
|
||||
func unescapeKey(part string) string {
|
||||
if !strings.Contains(part, `\`) {
|
||||
return part
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(part); i++ {
|
||||
if part[i] == '\\' && i+1 < len(part) {
|
||||
i++
|
||||
}
|
||||
b.WriteByte(part[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func splice(raw []byte, at, n int, with []byte) ([]byte, error) {
|
||||
out := make([]byte, 0, len(raw)-n+len(with))
|
||||
|
||||
@@ -4859,6 +4859,8 @@ 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 中保存任何内容。",
|
||||
"QwenPaw reads its providers at start-up — restart QwenPaw once after connecting it, and after magpie's models change; a model picked for an agent after that is used from its next message.": "QwenPaw 启动时读取其提供商——连接后以及 magpie 的模型变化后,请重启一次 QwenPaw;此后为某个智能体选择的模型从其下一条消息起生效。",
|
||||
"{agent} takes magpie's gateway and model only from how it is started — start it with {command}": "{agent} 只从启动方式中获取 magpie 的网关和模型,请这样启动它:{command}",
|
||||
"Type {bin} in a new terminal: magpie added it to {profiles}, to start {agent} on magpie's gateway and model (in a terminal open now: {command}).": "在新终端中直接输入 {bin} 即可:magpie 已把它加入 {profiles},会用 magpie 的网关和模型启动 {agent}(已打开的终端中请用:{command})。",
|
||||
"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 会话才会生效。",
|
||||
@@ -9905,6 +9907,8 @@ 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 中儲存任何內容。",
|
||||
"QwenPaw reads its providers at start-up — restart QwenPaw once after connecting it, and after magpie's models change; a model picked for an agent after that is used from its next message.": "QwenPaw 啟動時讀取其提供者——連接後以及 magpie 的模型變更後,請重啟一次 QwenPaw;此後為某個智慧體選擇的模型從其下一則訊息起生效。",
|
||||
"{agent} takes magpie's gateway and model only from how it is started — start it with {command}": "{agent} 只從啟動方式中取得 magpie 的閘道和模型,請這樣啟動它:{command}",
|
||||
"Type {bin} in a new terminal: magpie added it to {profiles}, to start {agent} on magpie's gateway and model (in a terminal open now: {command}).": "在新終端機中直接輸入 {bin} 即可:magpie 已把它加入 {profiles},會用 magpie 的閘道和模型啟動 {agent}(已開啟的終端機中請用:{command})。",
|
||||
"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 會話才會生效。",
|
||||
@@ -14953,6 +14957,8 @@ 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 を再起動してください。",
|
||||
"QwenPaw reads its providers at start-up — restart QwenPaw once after connecting it, and after magpie's models change; a model picked for an agent after that is used from its next message.": "QwenPaw は起動時にプロバイダーを読み込みます。接続した後と magpie のモデルが変わった後に一度 QwenPaw を再起動してください。その後エージェントに選んだモデルは次のメッセージから使われます。",
|
||||
"{agent} takes magpie's gateway and model only from how it is started — start it with {command}": "{agent} は magpie のゲートウェイとモデルを起動方法からしか受け取りません。次のように起動してください:{command}",
|
||||
"Type {bin} in a new terminal: magpie added it to {profiles}, to start {agent} on magpie's gateway and model (in a terminal open now: {command}).": "新しいターミナルで {bin} と入力するだけです:magpie が {profiles} に追加し、magpie のゲートウェイとモデルで {agent} を起動します(開いているターミナルでは:{command})。",
|
||||
"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 セッションを再起動してください。",
|
||||
@@ -20001,6 +20007,8 @@ 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.",
|
||||
"QwenPaw reads its providers at start-up — restart QwenPaw once after connecting it, and after magpie's models change; a model picked for an agent after that is used from its next message.": "QwenPaw liest seine Anbieter beim Start – QwenPaw nach dem Verbinden und nach Änderungen an magpies Modellen einmal neu starten; ein danach für einen Agenten gewähltes Modell gilt ab seiner nächsten Nachricht.",
|
||||
"{agent} takes magpie's gateway and model only from how it is started — start it with {command}": "{agent} übernimmt magpies Gateway und Modell nur aus seinem Startbefehl – so starten: {command}",
|
||||
"Type {bin} in a new terminal: magpie added it to {profiles}, to start {agent} on magpie's gateway and model (in a terminal open now: {command}).": "Tippe {bin} in einem neuen Terminal: magpie hat es zu {profiles} hinzugefügt und startet {agent} mit magpies Gateway und Modell (in einem schon offenen Terminal: {command}).",
|
||||
"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.",
|
||||
@@ -20286,6 +20294,8 @@ const NOTICES = [
|
||||
"WSL {distro} is in {net} networking, not mirrored, so its {agent} was pointed at Windows ({url}) rather than 127.0.0.1; magpie listens there for WSL, and it answers once Windows' firewall lets WSL in. For 127.0.0.1, set networkingMode=mirrored under [wsl2] in %UserProfile%\\.wslconfig and run wsl --shutdown, then pick the model again.",
|
||||
"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.",
|
||||
"{agent} takes magpie's gateway and model only from how it is started — start it with {command}",
|
||||
"Type {bin} in a new terminal: magpie added it to {profiles}, to start {agent} on magpie's gateway and model (in a terminal open now: {command}).",
|
||||
"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.",
|
||||
|
||||
@@ -916,9 +916,14 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
|
||||
<tr><td><code>icon</code></td><td>行のアイコン。アイコン名、<code>https://</code> または <code>data:</code> URL。省略するとプラグインのアイコン、それもなければ汎用のもの。</td></tr>
|
||||
<tr><td><code>notice</code></td><td>モデルを変えた後に表示する案内。組み込みのエージェントと同じです。</td></tr>
|
||||
<tr><td><code>library</code></td><td><span class="ui">ライブラリ</span>が渡すものをエージェントがどこで読むか:<code>instructions</code>(毎回の会話の前に読む Markdown ファイル)、<code>mcp</code>(MCP サーバーのファイル)とその書き方を表す <code>mcpFormat</code>(どのエージェントのファイルと同じ形か:<code>alma</code>, <code>antigravity</code>, <code>claude</code>, <code>cline</code>, <code>codex</code>, <code>commandcode</code>, <code>copilot</code>, <code>crush</code>, <code>cursor</code>, <code>devin</code>, <code>gemini</code>, <code>goose</code>, <code>grok</code>, <code>hermes</code>, <code>kimi</code>, <code>omp</code>, <code>opencode</code>, <code>zed</code>。<code>claude</code> は <code>{"mcpServers": {…}}</code>)、<code>skills</code>(<code>SKILL.md</code> のフォルダを置くフォルダ)。どれも省略でき、<code>~</code> と <code>$VAR</code> は展開されます:<code>library: { instructions: "~/.toy/AGENTS.md", mcp: "~/.toy/mcp.json", mcpFormat: "claude", skills: "~/.toy/skills" }</code>。書かなければライブラリからは何も渡されず、渡そうとするとプラグインが書くべきキーを示して断られます。</td></tr>
|
||||
<tr><td><code>launch</code></td><td>起動のされ方からしかゲートウェイを読まないエージェント向け:<code>env</code> は起動時に渡す環境変数で、値はそれぞれ <code>{key}</code>、<code>{url}</code>、<code>{v1}</code> のいずれか(アドレスの後にパスを一つまで)、<code>model</code> はモデルを指定するフラグです。magpie のモデルを使っている間、magpie はユーザーのシェル(zsh、bash、fish、PowerShell)に <code>bin</code> の名前の関数を置き、<code>magpie <id> run</code> でゲートウェイ経由で起動します:<code>launch: { env: { GEMINI_API_KEY: "{key}", GOOGLE_GEMINI_BASE_URL: "{url}" }, model: "--model" }</code>。自分のモデルに戻すと関数は取り除かれます。<code>args</code> はユーザーの引数の前に置くフラグで、値はどれも <code>{config}</code>(設定ファイルのパス)です:<code>args: { "--settings": "{config}" }</code>。<code>plain</code> はエージェントをゲートウェイを通さずそのまま起動する引数(サブコマンドかフラグ)です:<code>plain: ["remote-control"]</code>。</td></tr>
|
||||
<tr><td><code>base</code></td><td><code>launch.args</code> で <code>config</code> を渡す、つまり設定ファイルが magpie 専用のファイルであるエージェント向け:エージェント自身の設定ファイルです。<code>connect</code> と <code>own</code> はそれをパース済みの <code>base</code> として受け取り、ユーザー自身のモデルはそこに書き込まれ、外すときは設定ファイルごと取り除かれます:<code>base: "~/.gemini/antigravity-cli/settings.json"</code>。</td></tr>
|
||||
<tr><td><code>merge</code></td><td>json の <code>config</code> 用:<code>connect</code> が magpie のメンバーを返すオブジェクトのキーパス。ユーザー自身のメンバーの横に書き込まれ、取り除くときは magpie のものだけです:<code>merge: ["customModelsConfig.customModels"]</code>。</td></tr>
|
||||
<tr><td><code>effort</code>, <code>wsl</code>, <code>aliases</code></td><td><code>effort: true</code> でエージェントに推論の強さの欄が付きます。<code>wsl: true</code> で WSL ディストリビューションにも表示されます。<code>aliases</code> は <code>magpie <名前></code> が受け付ける別名です。</td></tr>
|
||||
</table></div>
|
||||
<h3>connect</h3>
|
||||
<p><code>connect(input)</code> はモデルの横に書き込む他のキーを、キーのパスと値で返します。<code>async</code> でも構いません。受け取るのは <code>gateway</code>(<code>url</code>、<code>/v1</code> で終わる URL の <code>v1</code>、エージェント専用のキー <code>key</code>。リクエストはその id で数えられます)、<code>model</code>(<code>id</code>、<code>name</code>、<code>context</code>、<code>output</code>、<code>images</code>、<code>efforts</code>、そして <code>/v1/models</code> と同じ名前の <code>native_endpoints</code>(リクエストが変換されずにそのまま通るゲートウェイのパス、例えば <code>["/v1/chat/completions"]</code>)と <code>pricing</code>(1 トークンあたりの USD、10 進の文字列:<code>prompt</code>、<code>completion</code>、<code>input_cache_read</code>、<code>input_cache_write</code>。分からないものは含まれず、空や 0 にはなりません))、<code>models</code>(magpie がエージェントに出すすべてのモデル、同じ形)、<code>agent</code>(<code>id</code>、<code>config</code>)です。<code>connect</code> がないプラグインはモデルだけを書きます。magpie のモデルが変わると <code>connect</code> がもう一度呼ばれるので、書いたモデル一覧は最新のまま保たれます。</p>
|
||||
<p><code>own({ config, base, model })</code> をエクスポートすると、行のピッカーに出すエージェント自身のモデルを返せます。パース済みの設定ファイル(ないときは <code>{}</code>。<code>base</code> があればそれも)と今のモデルを受け取り、<code>{ value, model, direct }</code> のリストを返します。<code>value</code> はモデルとして書き込む値、<code>model</code> はベンダーでの名前、<code>direct</code> は直接つながるベンダー(<code>Google</code>、<code>OpenAI</code>、<code>Anthropic</code>)です。ない場合、ピッカーには今のモデルだけが出ます。</p>
|
||||
<h3>magpie がすること</h3>
|
||||
<ul>
|
||||
<li><b>書き込み。</b>各キーをその場で書き換え、ユーザーのコメントや他のキーは残します。最初に書く前に、各キーの元の値を型ごと(数値は数値のまま)取っておきます。</li>
|
||||
|
||||
@@ -916,9 +916,14 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
|
||||
<tr><td><code>icon</code></td><td>A picture for its row: an icon name, an <code>https://</code> or <code>data:</code> URL. The plugin’s own icon, else a generic one, when left out.</td></tr>
|
||||
<tr><td><code>notice</code></td><td>Said after its model is changed, as for magpie’s own agents.</td></tr>
|
||||
<tr><td><code>library</code></td><td>Where the agent reads what the <span class="ui">Library</span> gives: <code>instructions</code> (a Markdown file it reads before every conversation), <code>mcp</code> (its MCP servers file) with <code>mcpFormat</code>, the agent whose file it is shaped like (<code>alma</code>, <code>antigravity</code>, <code>claude</code>, <code>cline</code>, <code>codex</code>, <code>commandcode</code>, <code>copilot</code>, <code>crush</code>, <code>cursor</code>, <code>devin</code>, <code>gemini</code>, <code>goose</code>, <code>grok</code>, <code>hermes</code>, <code>kimi</code>, <code>omp</code>, <code>opencode</code>, <code>zed</code>; <code>claude</code> is <code>{"mcpServers": {…}}</code>), and <code>skills</code> (a folder of <code>SKILL.md</code> folders). Each is optional, with <code>~</code> and <code>$VAR</code> expanded: <code>library: { instructions: "~/.toy/AGENTS.md", mcp: "~/.toy/mcp.json", mcpFormat: "claude", skills: "~/.toy/skills" }</code>. Without it the agent is given nothing from the Library, and giving it an item is refused, naming the key its plugin would set.</td></tr>
|
||||
<tr><td><code>launch</code></td><td>For an agent that takes the gateway only from how it is started: <code>env</code>, the variables it is started with, each <code>{key}</code>, <code>{url}</code> or <code>{v1}</code> with a path after the address at most, and <code>model</code>, the flag that names the model. While it is on one of magpie’s models, magpie puts a function named after its <code>bin</code> in the user’s shells (zsh, bash, fish, PowerShell), which runs <code>magpie <id> run</code> to start it on the gateway: <code>launch: { env: { GEMINI_API_KEY: "{key}", GOOGLE_GEMINI_BASE_URL: "{url}" }, model: "--model" }</code>. Its own model takes the function out. <code>args</code> are flags put before the user’s arguments, each <code>{config}</code>, the config’s path: <code>args: { "--settings": "{config}" }</code>. <code>plain</code> are arguments, a subcommand or a flag, that start the agent as it is, never on the gateway: <code>plain: ["remote-control"]</code>.</td></tr>
|
||||
<tr><td><code>base</code></td><td>For an agent handed its <code>config</code> by <code>launch.args</code>, so that the config is magpie’s own file: the agent’s own settings file. <code>connect</code> and <code>own</code> get it parsed as <code>base</code>, the user’s own model is written there, and stepping out takes the config away whole: <code>base: "~/.gemini/antigravity-cli/settings.json"</code>.</td></tr>
|
||||
<tr><td><code>merge</code></td><td>For a json <code>config</code>: key paths whose object <code>connect</code> returns magpie’s members of, written beside the user’s own and taken out alone: <code>merge: ["customModelsConfig.customModels"]</code>.</td></tr>
|
||||
<tr><td><code>effort</code>, <code>wsl</code>, <code>aliases</code></td><td><code>effort: true</code> gives the agent the Effort field; <code>wsl: true</code> lists it in WSL distros too; <code>aliases</code> are other names <code>magpie <name></code> takes.</td></tr>
|
||||
</table></div>
|
||||
<h3>connect</h3>
|
||||
<p><code>connect(input)</code> returns the other keys to write beside the model, by key path, each with its value; it may be <code>async</code>. It is given <code>gateway</code> (<code>url</code>, <code>v1</code> — the URL ending in <code>/v1</code> — and <code>key</code>, the agent’s own key, which counts its requests under its id), <code>model</code> (<code>id</code>, <code>name</code>, <code>context</code>, <code>output</code>, <code>images</code>, <code>efforts</code>, and as <code>/v1/models</code> names them <code>native_endpoints</code>, the gateway paths a request for it goes on untranslated such as <code>["/v1/chat/completions"]</code>, and <code>pricing</code>, USD a token as decimal strings: <code>prompt</code>, <code>completion</code>, <code>input_cache_read</code>, <code>input_cache_write</code>; each left out when not known, never empty or 0), <code>models</code> (every model magpie offers the agent, the same way) and <code>agent</code> (<code>id</code>, <code>config</code>). A plugin without <code>connect</code> writes only the model. It is called again when magpie’s models change, so a list it writes stays current.</p>
|
||||
<p><code>own({ config, base, model })</code>, when exported, gives the agent’s own models for the row’s picker: it gets the config file parsed (<code>{}</code> for none), <code>base</code> too when the agent has one, and the model the agent is on, and returns a list of <code>{ value, model, direct }</code>, <code>value</code> what is written as the model, <code>model</code> its name at the vendor and <code>direct</code> the vendor it goes to (<code>Google</code>, <code>OpenAI</code>, <code>Anthropic</code>). Without it the picker lists the model the agent is on.</p>
|
||||
<h3>What magpie does with it</h3>
|
||||
<ul>
|
||||
<li><b>Writing.</b> Each key is set in place, the user’s comments and other keys kept. Before the first write, what each key held is kept aside, typed (a number stays a number).</li>
|
||||
|
||||
@@ -916,9 +916,14 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to
|
||||
<tr><td><code>icon</code></td><td>这一行的图标:图标名、<code>https://</code> 或 <code>data:</code> URL。不写就用插件自己的图标,再没有就用通用图标。</td></tr>
|
||||
<tr><td><code>notice</code></td><td>换模型之后显示的提示,和内置 Agent 一样。</td></tr>
|
||||
<tr><td><code>library</code></td><td>Agent 从哪里读<span class="ui">资源库</span>给它的东西:<code>instructions</code>(每次对话前读的 Markdown 文件)、<code>mcp</code>(它的 MCP 服务器文件)和 <code>mcpFormat</code>(这个文件的写法跟哪个 Agent 的一样:<code>alma</code>, <code>antigravity</code>, <code>claude</code>, <code>cline</code>, <code>codex</code>, <code>commandcode</code>, <code>copilot</code>, <code>crush</code>, <code>cursor</code>, <code>devin</code>, <code>gemini</code>, <code>goose</code>, <code>grok</code>, <code>hermes</code>, <code>kimi</code>, <code>omp</code>, <code>opencode</code>, <code>zed</code>;<code>claude</code> 即 <code>{"mcpServers": {…}}</code>),以及 <code>skills</code>(放 <code>SKILL.md</code> 文件夹的目录)。每项都可省略,<code>~</code> 和 <code>$VAR</code> 会展开:<code>library: { instructions: "~/.toy/AGENTS.md", mcp: "~/.toy/mcp.json", mcpFormat: "claude", skills: "~/.toy/skills" }</code>。不写的话,资源库不会给它任何东西,给它某一项时会被拒绝,并说明插件该写哪个键。</td></tr>
|
||||
<tr><td><code>launch</code></td><td>给只从启动方式读取网关的 Agent:<code>env</code> 是启动时带上的环境变量,每个值是 <code>{key}</code>、<code>{url}</code> 或 <code>{v1}</code>,地址后最多再接一段路径;<code>model</code> 是指定模型的参数。它用着 magpie 的模型时,magpie 会在用户的 shell(zsh、bash、fish、PowerShell)里放一个以 <code>bin</code> 命名的函数,运行 <code>magpie <id> run</code>,让它从网关启动:<code>launch: { env: { GEMINI_API_KEY: "{key}", GOOGLE_GEMINI_BASE_URL: "{url}" }, model: "--model" }</code>。换回它自己的模型时,函数随之移除。<code>args</code> 是放在用户参数前面的参数,值都是 <code>{config}</code>,即配置文件的路径:<code>args: { "--settings": "{config}" }</code>。<code>plain</code> 是让 Agent 按原样启动、不走网关的参数(子命令或参数):<code>plain: ["remote-control"]</code>。</td></tr>
|
||||
<tr><td><code>base</code></td><td>给由 <code>launch.args</code> 交给 Agent 的 <code>config</code>,即配置文件是 magpie 自己的文件时:Agent 自己的设置文件。<code>connect</code> 和 <code>own</code> 会拿到解析好的 <code>base</code>,用户自己的模型写在这里,退出时整个配置文件被移除:<code>base: "~/.gemini/antigravity-cli/settings.json"</code>。</td></tr>
|
||||
<tr><td><code>merge</code></td><td>用于 json 的 <code>config</code>:这些键路径的对象由 <code>connect</code> 返回 magpie 的成员,写在用户自己的成员旁边,移除时只移除 magpie 的:<code>merge: ["customModelsConfig.customModels"]</code>。</td></tr>
|
||||
<tr><td><code>effort</code>, <code>wsl</code>, <code>aliases</code></td><td><code>effort: true</code> 给 Agent 加上推理强度一栏;<code>wsl: true</code> 让它在 WSL 发行版里也列出;<code>aliases</code> 是 <code>magpie <名字></code> 也认的其他名字。</td></tr>
|
||||
</table></div>
|
||||
<h3>connect</h3>
|
||||
<p><code>connect(input)</code> 返回要在模型旁边一起写入的其他键,按键路径给出各自的值;可以是 <code>async</code>。它拿到 <code>gateway</code>(<code>url</code>、<code>v1</code>——以 <code>/v1</code> 结尾的地址——和 <code>key</code>,即这个 Agent 自己的 key,请求会按它的 id 计入用量)、<code>model</code>(<code>id</code>、<code>name</code>、<code>context</code>、<code>output</code>、<code>images</code>、<code>efforts</code>,以及与 <code>/v1/models</code> 同名的 <code>native_endpoints</code>——请求不经转换直接走的网关路径,如 <code>["/v1/chat/completions"]</code>——和 <code>pricing</code>——每 token 的美元价格,十进制字符串:<code>prompt</code>、<code>completion</code>、<code>input_cache_read</code>、<code>input_cache_write</code>;不知道的就不给,绝不是空或 0)、<code>models</code>(magpie 给这个 Agent 的所有模型,格式相同)和 <code>agent</code>(<code>id</code>、<code>config</code>)。没有 <code>connect</code> 的插件只写模型。magpie 的模型有变化时会再调用一次 <code>connect</code>,它写的模型列表因此保持最新。</p>
|
||||
<p>导出 <code>own({ config, base, model })</code> 时,它给出这一行选择器里 Agent 自己的模型:拿到解析好的配置文件(没有时为 <code>{}</code>,有 <code>base</code> 时也一并给出)和 Agent 当前的模型,返回 <code>{ value, model, direct }</code> 的列表:<code>value</code> 是写入的模型值,<code>model</code> 是它在厂商那里的名字,<code>direct</code> 是它直连的厂商(<code>Google</code>、<code>OpenAI</code>、<code>Anthropic</code>)。不导出时,选择器只列出 Agent 当前的模型。</p>
|
||||
<h3>magpie 怎么用它</h3>
|
||||
<ul>
|
||||
<li><b>写入。</b>每个键原地修改,用户的注释和其他键都保留。第一次写之前,每个键原来的值会按原类型存起来(数字仍是数字)。</li>
|
||||
|
||||
@@ -5617,11 +5617,17 @@ magpie plugin add ./agent-aider # or a single *.agent.js file
|
||||
| `icon` | A picture for its row: an icon name, an `https://` or `data:` URL. The plugin’s own icon, else a generic one, when left out. |
|
||||
| `notice` | Said after its model is changed, as for magpie’s own agents. |
|
||||
| `library` | Where the agent reads what the Library gives: `instructions` (a Markdown file it reads before every conversation), `mcp` (its MCP servers file) with `mcpFormat`, the agent whose file it is shaped like (`alma`, `antigravity`, `claude`, `cline`, `codex`, `commandcode`, `copilot`, `crush`, `cursor`, `devin`, `gemini`, `goose`, `grok`, `hermes`, `kimi`, `omp`, `opencode`, `zed`; `claude` is `{"mcpServers": {…}}`), and `skills` (a folder of `SKILL.md` folders). Each is optional, with `~` and `$VAR` expanded: `library: { instructions: "~/.toy/AGENTS.md", mcp: "~/.toy/mcp.json", mcpFormat: "claude", skills: "~/.toy/skills" }`. Without it the agent is given nothing from the Library, and giving it an item is refused, naming the key its plugin would set. |
|
||||
| `launch` | For an agent that takes the gateway only from how it is started: `env`, the variables it is started with, each `{key}`, `{url}` or `{v1}` with a path after the address at most, and `model`, the flag that names the model. While it is on one of magpie’s models, magpie puts a function named after its `bin` in the user’s shells (zsh, bash, fish, PowerShell), which runs `magpie <id> run` to start it on the gateway: `launch: { env: { GEMINI_API_KEY: "{key}", GOOGLE_GEMINI_BASE_URL: "{url}" }, model: "--model" }`. Its own model takes the function out. `args` are flags put before the user’s arguments, each `{config}`, the config’s path: `args: { "--settings": "{config}" }`. `plain` are arguments, a subcommand or a flag, that start the agent as it is, never on the gateway: `plain: ["remote-control"]`. |
|
||||
| `base` | For an agent handed its `config` by `launch.args`, so that the config is magpie’s own file: the agent’s own settings file. `connect` and `own` get it parsed as `base`, the user’s own model is written there, and stepping out takes the config away whole: `base: "~/.gemini/antigravity-cli/settings.json"`. |
|
||||
| `merge` | For a json `config`: key paths whose object `connect` returns magpie’s members of, written beside the user’s own and taken out alone: `merge: ["customModelsConfig.customModels"]`. |
|
||||
| `effort`, `wsl`, `aliases` | `effort: true` gives the agent the Effort field; `wsl: true` lists it in WSL distros too; `aliases` are other names `magpie <name>` takes. |
|
||||
|
||||
### connect
|
||||
|
||||
`connect(input)` returns the other keys to write beside the model, by key path, each with its value; it may be `async`. It is given `gateway` (`url`, `v1` — the URL ending in `/v1` — and `key`, the agent’s own key, which counts its requests under its id), `model` (`id`, `name`, `context`, `output`, `images`, `efforts`, and as `/v1/models` names them `native_endpoints`, the gateway paths a request for it goes on untranslated such as `["/v1/chat/completions"]`, and `pricing`, USD a token as decimal strings: `prompt`, `completion`, `input_cache_read`, `input_cache_write`; each left out when not known, never empty or 0), `models` (every model magpie offers the agent, the same way) and `agent` (`id`, `config`). A plugin without `connect` writes only the model. It is called again when magpie’s models change, so a list it writes stays current.
|
||||
|
||||
`own({ config, base, model })`, when exported, gives the agent’s own models for the row’s picker: it gets the config file parsed (`{}` for none), `base` too when the agent has one, and the model the agent is on, and returns a list of `{ value, model, direct }`, `value` what is written as the model, `model` its name at the vendor and `direct` the vendor it goes to (`Google`, `OpenAI`, `Anthropic`). Without it the picker lists the model the agent is on.
|
||||
|
||||
### What magpie does with it
|
||||
|
||||
- **Writing..** Each key is set in place, the user’s comments and other keys kept. Before the first write, what each key held is kept aside, typed (a number stays a number).
|
||||
|
||||
Reference in New Issue
Block a user