diff --git a/docs/reference.md b/docs/reference.md index bf7b6fef9..23bb3537a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -140,7 +140,7 @@ line; agents connected to magpie lose it when it quits. | QwenPaw | each agent's `agent.json` in its workspace (`~/.qwenpaw/workspaces/`, the agents listed in `config.json`), under `$QWENPAW_WORKING_DIR`, else a legacy `~/.copaw`, else `~/.qwenpaw` | model (a `magpie` custom provider in `providers/custom/magpie.json` under QwenPaw's secret folder, `$QWENPAW_SECRET_DIR` or `~/.qwenpaw.secret`, OpenAI Chat at the gateway with magpie's models; the agent's `active_model` set to it, what was there put back on Disconnect; one row per agent, `qwenpaw` the default and `qwenpaw#` the others; an agent on an ACP backend isn't listed; restart QwenPaw after the first connect), effort (the agent's `thinking_level`; magpie's models with reasoning levels are declared `thinking_param_style: "effort"` so QwenPaw applies it) | | OpenClaw | `openclaw.json` in `~/.openclaw` (`$OPENCLAW_CONFIG_PATH`, `$OPENCLAW_STATE_DIR`, `~/.openclaw-` for `$OPENCLAW_PROFILE`, `~` as `$OPENCLAW_HOME`) | model (a `magpie` provider in `models.providers`, `openai-completions`, with magpie's models in it; `agents.defaults.model`'s primary set to it, what was there put back on Disconnect; `magpie/*` added to a `modelPolicy.allow` that would refuse it; the user's own keys in the provider and its models kept; a chat already on a model keeps it until `/model default`) | | jcode | `config.toml` in `$JCODE_HOME`, else `~/.jcode` | model (a `[providers.magpie]` profile, `openai-compatible`, with magpie's models in it; `[provider] default_provider`/`default_model` set to it, what was there put back on Disconnect; the user's own keys in the profile, such as `headers` and a model's `reasoning_effort`, kept; restart open jcode sessions after connecting) | -| Dim (alpha, `dima`) | none of Dim's: magpie's own `dim.json` beside its settings, and a `dima` function in your shell profiles | model (Dim's documented start-up variables, set only for that run: `DIM_BASE_URL` the gateway's `/v1`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY`, `DIM_MODEL` and both token limits; Dim's home (`$DIMCODE_HOME`, else `~/.dimcode-alpha`), saved Providers and account are never read or written. Type `dima` in a new terminal; picking Dim's own again takes the function out) | +| Dim (alpha, `dima`) | Dim's built-in **Magpie** provider, through Dim's own daemon (`$DIMCODE_HOME`, else `~/.dimcode-alpha`), and magpie's own `dim.json` beside its settings | model (Dim's Magpie provider gets the gateway's `/v1` and magpie's key, is turned on and made Dim's model, so a plain `dima` runs on magpie; no other provider is touched, and a key or address you set on the Magpie entry yourself is kept. Picking Dim's own again turns the entry off and puts back the model Dim was on. When Dim's daemon can't be reached, a `dima` function in your shell profiles starts it with `DIM_BASE_URL`, `DIM_API_KEY`, `DIM_MODEL` and the token limits for that run instead) | | Mistral Vibe | `config.toml` in `$VIBE_HOME`, else `~/.vibe` | model (a `[[providers]]` entry named magpie with the gateway's `/v1` and the key as an `Authorization` header in `extra_headers`, since Vibe reads keys only from the environment; one `[[models]]` entry per model, aliased `magpie//`; `active_model` set to the alias, what was there put back on Disconnect; a `thinking` level the user set on a model kept; restart open vibe sessions after connecting) | | MiniMax Code (mcode) | `~/.minimax/config.yaml` (`$MINIMAX_DATA_DIR`, or the folder the desktop app moved it to) | model (a `magpie` custom provider; magpie's models in its /model) | | Droid (Factory) | `~/.factory/settings.json` (`$FACTORY_HOME_OVERRIDE`) | model (magpie's models as BYOK `customModels`, in Droid's /model) | @@ -3351,15 +3351,21 @@ it starts agy untouched. A terminal open already takes the command the Launch row copies. Stepping out (`magpie agy default`) takes the block out again. `magpie agy env` prints what `agy run` adds. -**Dim** alpha (`dima`, npm's `dimcode-alpha`) is started on magpie the -way Dim documents for any OpenAI-compatible endpoint: `DIM_BASE_URL`, -`DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY`, `DIM_MODEL`, -`DIM_MAX_CONTEXT_TOKENS` and `DIM_MAX_OUTPUT_TOKENS`, for that run only. -Picking a catalog model (`magpie dim `) keeps it in magpie's own -`dim.json` and puts a marked `dima` function in your shell profiles, which -runs `magpie dim run`; Dim's own folder, saved Providers and account are -not touched. `magpie dim default` takes the file and the function out -again, and `magpie dim env` prints what `dim run` adds. No WSL twin. +**Dim** alpha (`dima`, npm's `dimcode-alpha`) has a built-in provider +named Magpie. Picking a catalog model (`magpie dim `) fills it in +through Dim's daemon, the way Dim's own app does: the gateway's `/v1` +(`http://127.0.0.1:3425/v1`, or the port magpie is on), magpie's key, the +provider turned on, and the model made Dim's pick, with its token limits +when the gateway doesn't know them. A plain `dima`, or Dim's app, then runs +on magpie. Dim's other providers are never touched. A key or address you +set on the Magpie entry yourself is kept; magpie only picks the model. +`magpie dim default` turns the entry off, clears the key magpie put there +and puts back the model Dim was on before. The pick is kept in magpie's own +`dim.json`. Only when Dim's daemon can't be reached does magpie fall back to +a marked `dima` function in your shell profiles, which runs `magpie dim run` +with `DIM_BASE_URL`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY`, +`DIM_MODEL`, `DIM_MAX_CONTEXT_TOKENS` and `DIM_MAX_OUTPUT_TOKENS` for that +run; `magpie dim env` prints them. No WSL twin. agy installed in a WSL distro is listed as Antigravity CLI · WSL , found by `~/.gemini/antigravity-cli` or the `agy` command there. diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 5954fa586..4ba92adec 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -43,7 +43,7 @@ something else shows up as drift. | WSL CLI versions and updates | A twin's CLI is read and updated in its distro, as the host's is (`cliupdate_wsl.go`; mewcoder on X): the Agents row shows the version, the newest and an Update button for every `cliSpecs` kind a distro has a command for, and Update all takes them in. Where the binary is comes from the probe (`distro.Paths`, else the command asked of the distro's PATH); one `wsl.exe -d -e sh` script says where its links lead, its `--version` and exit code (`wslCLIScript`, kept ten minutes in `wslProbes`, asked again by Rescan and after an update), with the CLI's own folder, its npm prefix, `~/.local/bin` and `~/.bun/bin` first on PATH, since `wsl.exe -e` has no login PATH and a node CLI would not find node. How it was installed is read from that Linux path by the same rules (`wslHowInstalled`: its own updater via `cliSpec.self`, Homebrew's Cellar, npm, bun or pnpm; volta, yarn and an npm prefix the user can't write, `/usr/lib`, are left alone), and the update runs in the distro through wsl.exe (`wslRunUpdate`) with a Linux brew asked for its newest in the distro too. A distro that isn't running is never started to be asked: its rows show no version and an update says to start it. Not carried over: the host's proxy settings (the distro has its own network), and Grok Build's newest is read from this computer's channel setting. Kinds with no command of their own (Goose, mu) show nothing, as on the host. | [`cliupdate_wsl.go`](../../internal/agent/cliupdate_wsl.go), [`cliupdate.go`](../../internal/agent/cliupdate.go) | | Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) | | Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin::` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). Decision models are never in `models`; `connect` gets them as `decisionModels` (`pluggedDecisionModels`: `provider.OfferedDeciders`, what `/v1/models` lists under `X-Magpie-Deciders`, then the decision routing groups, each with `id`, `name`, `provider` or `group: true`, and `endpoints` `/v1/systemone` and `/v1/decisions`; `TestPluggedConnectSeesDecisionModels`). | [`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. A model of magpie's in `settings.json` while `magpie-settings.json` is already on magpie's is agy's own `/model` pick, which agy writes there even under `--settings`: it moves into magpie's file, and `settings.json`'s model goes back to the one `connect.was` kept (the user's own) or out; the old stash isn't read for it, which put a stale model and `modelProvider: gemini` back or took the user's out (LolingVerse on X, `TestAgyOwnPickKeepsSettings`). agy's `/effort` is turned away for every custom model, so a model with two or more of low, medium and high gets a custom model per level too, `magpie/:` with `thinkingLevel` (the only levels agy 1.5.9 takes there), which agy sends as `thinkingConfig.thinkingLevel` and the gateway asks over the row's (`agyLevelAsked`); the row's model field shows such a pick as its model (`agyLevelOf`). `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. Dim alpha (`dima`, [`dim.go`](../../internal/agent/dim.go)) gets the same kind of function from `launchSpec`, with no model flag: `magpie dim run` starts it with the variables Dim documents for an OpenAI-compatible endpoint (`DIM_BASE_URL` = the gateway's `/v1`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY` = `agentKey("dim")`, `DIM_MODEL`, and `DIM_MAX_CONTEXT_TOKENS`/`DIM_MAX_OUTPUT_TOKENS`, which Dim needs for a model it doesn't know), read for that run only and beside a running daemon. The pick is in magpie's own `dim.json`; nothing in Dim's home or database is written, and Dim's own account (DimAgent, dropped at its vendor's request in v0.1.471) is never read or used. DimCode (dimcode.dev), the vendor's own app, is a client apart from Dim alpha (`dimcode` in `agents.go`, `TestDimCodeByUserAgent`): its User-Agent, `DimCode/` or `DimAgent/`, names it, drawn with the same mark as Dim (its site's favicon); unknown, a DimCode calling a Docker magpie by a gateway key read as a client named DimAgent, drawn as the cube (Yayoi_no_yume on X). Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) | +| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL`, `--settings <~/.gemini/antigravity-cli/magpie-settings.json>` and `--model` (no `--model` when the user gives one) while that file's model is magpie's, and unchanged otherwise. magpie writes `modelProvider`, `model` and the custom models (the user's own too, as agy takes the key whole) only into that file of its own, never into agy's `settings.json`: `modelProvider: gemini` there made every agy an API-key session with no Google account, so no remote control, which needs the sign-in (baysonfox on X). A `settings.json` an older magpie wired is given back (the stashed model and provider) at the next `Sync` or pick. A model of magpie's in `settings.json` while `magpie-settings.json` is already on magpie's is agy's own `/model` pick, which agy writes there even under `--settings`: it moves into magpie's file, and `settings.json`'s model goes back to the one `connect.was` kept (the user's own) or out; the old stash isn't read for it, which put a stale model and `modelProvider: gemini` back or took the user's out (LolingVerse on X, `TestAgyOwnPickKeepsSettings`). agy's `/effort` is turned away for every custom model, so a model with two or more of low, medium and high gets a custom model per level too, `magpie/:` with `thinkingLevel` (the only levels agy 1.5.9 takes there), which agy sends as `thinkingConfig.thinkingLevel` and the gateway asks over the row's (`agyLevelAsked`); the row's model field shows such a pick as its model (`agyLevelOf`). `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. Dim alpha (`dima`, [`dim.go`](../../internal/agent/dim.go), [`dim_daemon.go`](../../internal/agent/dim_daemon.go)) keeps its providers in a database only its daemon writes, so magpie fills in Dim's built-in `magpie` provider through the daemon's JSON-RPC API, as Dim's own clients do (`provider.update` with the record's version, `provider.refresh`, `provider.models.edit` for the token limits the gateway doesn't know, `provider.select` against the pick's version): the gateway's `/v1`, `agentKey("dim")`, turned on, and the model picked. `dimWire` records first what it found (the address, and the pick to give back) in magpie's own `dim.json`, writes the provider only when its key and address are still Dim's defaults or what magpie last wrote (a key or address the user set is kept, and only the model is picked), and `Sync` writes the port and key again when they change. `dimUnwire` turns the entry off with its key cleared (Dim clears a key only on a provider turned off) and puts back the pick. Without a reachable daemon (and with none `dima models` can start), the pick falls back to a `dima` function from `launchSpec` that runs `magpie dim run` with Dim's documented start-up variables (`DIM_BASE_URL`, `DIM_API_FORMAT=openai-compatible`, `DIM_API_KEY`, `DIM_MODEL`, `DIM_MAX_CONTEXT_TOKENS`/`DIM_MAX_OUTPUT_TOKENS`). Dim's other providers and its own account (DimAgent, dropped at its vendor's request in v0.1.471) are never read or used. On Windows the daemon is reached through Dim's own pipe bridge (`dimcode-server app-server --connect-pipe`). DimCode (dimcode.dev), the vendor's own app, is a client apart from Dim alpha (`dimcode` in `agents.go`, `TestDimCodeByUserAgent`): its User-Agent, `DimCode/` or `DimAgent/`, names it, drawn with the same mark as Dim (its site's favicon); unknown, a DimCode calling a Docker magpie by a gateway key read as a client named DimAgent, drawn as the cube (Yayoi_no_yume on X). 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 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=`, 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-.json`). The daemon takes http only to a loopback address, so in mirrored networking it gets the gateway's address, and under NAT a relay magpie starts in the distro: `socat` on `127.0.0.1:` to Windows' address on the WSL network (`scienceRelayScript`, its pid and target in `~/.claude-science/magpie-relay`, stopped with its forks as a process group on Disconnect or when the target moved). It is given `http://127.0.0.1:/`, the key in the path, as it sends its own sign-in as the key (gateway-routing's WSL under NAT). Connect says so when the distro has no socat. The keeper runs nothing in WSL until a distro's note exists, then starts both again in each running distro (`wslScienceHosts`). Its `Check` adds the firewall drift any agent pointed at Windows' WSL address gets (`unreachable`), as its one value isn't a model of magpie's, which is what `Drift` asks that of. | [`claudescience.go`](../../internal/agent/claudescience.go), [`claudescience_wsl.go`](../../internal/agent/claudescience_wsl.go), [`science.go`](../../internal/gateway/science.go) | | Claude Code beside its own account | `claude-magpie` (baranwang on X) starts Claude Code through magpie while a plain `claude` stays on the user's own account, nothing switched back and forth. `magpie claude run [args…]` writes `/claude-launch/settings.json` as `claude#launch`, an agent `claudeIn` makes at that folder (`place.dir`) and lists nowhere, so the Agents page, Check and Notice see only the user's settings.json: connected the first time as Connect would (`ConnectHow`), set again when the gateway's address or key moved (`claudeLaunchStale`, the LAN key included), synced after that, with `ANTHROPIC_API_KEY` and the cloud switches (`agentenv.ClaudeProviders`) blanked. It then runs `claude --settings args…` as a child (not exec, so it can tidy after): Claude Code puts a --settings file's env and model over the user's settings.json, a claude.ai sign-in and the shell (tried on 2.1.318). `/model` saves to the user's settings.json, never the --settings file, so `ClaudeLaunchAfter` moves a magpie model picked there into the launch file and gives the user's file its model back while magpie isn't wired into it; it also undoes Claude Code's own one-time `opus` → `opus[1m]` rewrite (`migration_opus_to_opus1m`), which the launch file's 1M opus tier sets off. A Claude alias picked (`sonnet`) stays. On Unix a stopped child stops magpie too (^Z, fg), and its exit code is magpie's; on Windows magpie ignores Ctrl+C while claude runs. The command `claude-magpie` is a launcher beside the `magpie` command (`update.Launchers`): a `#!/bin/sh` `exec` of `Program()`, or on Windows a `.cmd` running `"%~dp0magpie"`. `AddCLI` writes it, and `magpie claude launcher add` puts it there for a command added before; a file by that name without `written by magpie` is never written over. StandIn falls back to the launch file's tiers. | [`claude_launch.go`](../../internal/agent/claude_launch.go), [`claude_launch_cli.go`](../../internal/cli/claude_launch_cli.go), [`claude_run_unix.go`](../../internal/cli/claude_run_unix.go), [`launcher.go`](../../internal/update/launcher.go) | diff --git a/internal/agent/dim.go b/internal/agent/dim.go index 7ad71aa6c..d82e51dbf 100644 --- a/internal/agent/dim.go +++ b/internal/agent/dim.go @@ -1,37 +1,53 @@ package agent -// Dim alpha (arcships/dim, the `dima` command of npm's dimcode-alpha) is -// started on magpie the way Dim documents for any OpenAI-compatible -// endpoint (docs/design/model-startup.md): DIM_BASE_URL with -// DIM_API_FORMAT, DIM_API_KEY, DIM_MODEL, and DIM_MAX_CONTEXT_TOKENS with -// DIM_MAX_OUTPUT_TOKENS for a model Dim doesn't know. Dim reads them for -// that one run only, beside a running daemon, and leaves its saved -// Providers alone; help, version and management commands ignore them. -// The format is openai-compatible, Dim's generic provider, not -// openai-chat, which Dim takes for OpenAI's own. +// Dim alpha (arcships/dim, the `dima` command of npm's dimcode-alpha) has +// a built-in provider named Magpie (default-catalog.json: Responses at +// http://127.0.0.1:3425/v1, an API key, no models until listed). Picking +// one of magpie's models in Dim's row fills that provider in, through the +// API of Dim's daemon (dim_daemon.go), the way Dim's own Providers +// settings do: magpie's key for Dim, the gateway's address when its port +// isn't 3425, on; its models listed from magpie's /v1/models (the limits +// Dim needs given where magpie's list has none); and the model picked +// made Dim's model. So dima, and anything else on Dim's daemon, runs on +// magpie however it is started. No other provider of Dim's is touched, +// and a key, or an address of neither Dim's nor magpie's, the user gave +// the Magpie provider is left as it is: magpie only picks the model on +// it. What was there before is kept in magpie's dim.json, beside the +// model, and Disconnect (or picking Dim's own) puts it back where it is +// still as magpie left it. Nothing reads or uses Dim's own account +// (magpie dropped the DimAgent subscription at its vendor's request, +// v0.1.471). // -// Nothing of Dim's is written: not its home ($DIMCODE_HOME, else -// ~/.dimcode-alpha), its settings or its database, and nothing reads or -// uses Dim's own account (magpie dropped the DimAgent subscription at its -// vendor's request, v0.1.471). The model picked in Dim's row is in a file -// of magpie's, dim.json in magpie's folder. While it names one of -// magpie's models, magpie puts a function named dima in each shell the -// user has, between "# >>> magpie dima >>>" and "# <<< magpie dima <<<" -// (update.ShellFunction), which runs `magpie dim run` (cli/start_cli.go) -// to start the real dima with the variables; the row gives the command -// for a terminal open before. Picking Dim's own again (or Disconnect) -// removes the file and the function, and dima runs as it did. +// When Dim's daemon can't be reached or doesn't take magpie's model, dima +// is started on magpie the way Dim documents for any OpenAI-compatible +// endpoint (docs/design/model-startup.md) instead: DIM_BASE_URL with +// DIM_API_FORMAT, DIM_API_KEY, DIM_MODEL, and DIM_MAX_CONTEXT_TOKENS with +// DIM_MAX_OUTPUT_TOKENS, read for that one run only. magpie puts a +// function named dima in each shell the user has, between "# >>> magpie +// dima >>>" and "# <<< magpie dima <<<" (update.ShellFunction), which +// runs `magpie dim run` (cli/start_cli.go) to start the real dima with +// them. The format is openai-compatible, Dim's generic provider, not +// openai-chat, which Dim takes for OpenAI's own. Once the daemon is +// reached (a Sync while it runs), the provider is filled in and the +// function goes. import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" "os" "path/filepath" "runtime" + "slices" "strconv" "strings" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/update" ) @@ -109,12 +125,20 @@ func dim(home string) *Agent { return dimIn(here(home)) } func dimIn(at place) *Agent { file := dimFile() + dir := dimDir(at) model := jsonGet(file, "model") gw, key := gateway.URL, func() string { return agentKey("dim") } on := func() bool { return usesMagpie(model()) } spec := func() *launchSpec { return dimLaunch(gw(), key(), model()) } + local := func() bool { h, _ := homes(); return h == at.home } + // wired: Dim's own Magpie provider is on magpie's model, so dima runs + // on it as it is + wired := func() bool { + st := readDimState(file) + return usesMagpie(st.Model) && st.Dim != nil && st.Dim.Picked != "" && st.Dim.Picked == strings.TrimPrefix(st.Model, magpieID+"/") + } shell := func(set bool) { - if h, _ := homes(); h != at.home { + if !local() { return } if set { @@ -124,7 +148,7 @@ func dimIn(at place) *Agent { } } shellIn := func() []string { - if h, _ := homes(); h != at.home { + if !local() { return nil } return update.ShellFunctionIn("dima") @@ -132,15 +156,15 @@ func dimIn(at place) *Agent { launch := func() string { return dimCommand(gw(), key(), model(), runtime.GOOS == "windows") } return &Agent{ ID: "dim", Name: "Dim", Icon: "dim-color", Aliases: []string{"dima", "dimcode-alpha"}, Spelled: prefixed, NoNames: true, - Bin: "dima", Dir: dimDir(at), Path: file, + Bin: "dima", Dir: dir, Path: file, Launch: func() string { - if !on() { + if !on() || wired() { return "" } return launch() }, Typed: func() string { - if !on() || len(shellIn()) == 0 { + if !on() || wired() || len(shellIn()) == 0 { return "" } return "dima" @@ -148,16 +172,29 @@ func dimIn(at place) *Agent { Start: func() Starting { s := Starting{Bin: "dima"} if v := model(); on() { - s.Env, s.Model = spec().vars(gw(), key()), v + s.Model = v + if !wired() { + s.Env = spec().vars(gw(), key()) + } } return s }, Sync: func() error { - shell(on()) + if !on() { + shell(false) + return nil + } + // a running daemon gets magpie's address and key again (a new + // port, a new key), and one a Dim connected before this + // version never had is given them now; none is started here + if local() { + dimWire(dir, file, model(), false, !wired()) + } + shell(!wired()) return nil }, Notice: func() string { - if !on() { + if !on() || wired() { return "" } if in := shellIn(); len(in) > 0 { @@ -178,16 +215,24 @@ func dimIn(at place) *Agent { }, Set: func(v string) error { if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { - if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + st := readDimState(file) + st.Model = v + if err := writeDimState(file, st); err != nil { return err } - if err := edit.SetJSON(file, edit.KV{Path: "model", Value: v}); err != nil { - return err - } - shell(true) + // Dim's Magpie provider, else (no Dim daemon to + // reach, the gateway not answering it) the variables + // of a dima function as before + shell(!local() || dimWire(dir, file, v, true, true) != nil) return nil } // Dim's own model is its own to pick: magpie steps out + // and puts back what it changed + if local() { + if err := dimUnwire(dir, file); err != nil { + return err + } + } if err := os.Remove(file); err != nil && !os.IsNotExist(err) { return err } @@ -200,3 +245,201 @@ func dimIn(at place) *Agent { }}, } } + +// dimDefault is the base URL of Dim's built-in Magpie provider +// (crates/dim-app-server/resources/default-catalog.json). +const dimDefault = "http://127.0.0.1:3425/v1" + +// dimRecord is what magpie changed in Dim, kept in dim.json beside the +// model so Disconnect can put it back. +type dimRecord struct { + // Wrote: magpie gave Dim's Magpie provider its address and key. Not + // when the user had given it a key, or an address of neither Dim's + // nor magpie's, of their own: those are left as they are. + Wrote bool `json:"wrote"` + URL string `json:"url,omitempty"` // the base URL magpie gave it + Key string `json:"key,omitempty"` // a hash of the key magpie gave it + // the provider's base URL before magpie, and Dim's model (on + // Disconnect the provider is turned off: Dim clears a key only so) + BaseURL string `json:"baseUrl,omitempty"` + Selection *dimSelection `json:"selection"` + Picked string `json:"picked,omitempty"` // the model magpie picked in Dim +} + +type dimState struct { + Model string `json:"model,omitempty"` + Dim *dimRecord `json:"dim,omitempty"` +} + +func readDimState(file string) dimState { + var st dimState + if b, err := os.ReadFile(file); err == nil { + json.Unmarshal(b, &st) + } + return st +} + +func writeDimState(file string, st dimState) error { + b, err := json.MarshalIndent(st, "", " ") + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + return err + } + return edit.WriteAtomic(file, append(b, '\n')) +} + +func dimKeyHash(k string) string { + s := sha256.Sum256([]byte(k)) + return hex.EncodeToString(s[:8]) +} + +// dimWire puts Dim's built-in Magpie provider on magpie's gateway: its +// base URL (when the port isn't Dim's 3425), magpie's key for Dim, and on; +// and, with pick, lists its models and makes model Dim's model, giving +// it the limits Dim needs when magpie's /v1/models has none. Nothing else +// of Dim's is changed, and a key or address the user gave that provider +// is theirs: magpie only picks the model on it. What was there before is +// kept in dim.json the first time, for dimUnwire. +func dimWire(dir, file, model string, start, pick bool) error { + dimMu.Lock() + defer dimMu.Unlock() + c, err := dimConnect(dir, start) + if err != nil { + return err + } + defer c.close() + st := readDimState(file) + st.Model = model + p, err := c.provider(magpieID) + if err != nil { + return err + } + url, key := gateway.URL()+"/v1", agentKey("dim") + rec := st.Dim + if rec == nil { + was, err := c.selection() + if err != nil { + return err + } + if was != nil { + was = &dimSelection{Provider: was.Provider, Model: was.Model} + } + base := dimURL(p.Connection.BaseURL) + own := p.Connection.CredentialConfigured || (base != dimDefault && base != dimURL(url)) + rec = &dimRecord{Wrote: !own, BaseURL: p.Connection.BaseURL, Selection: was} + st.Dim = rec + // kept before Dim is written, so a change cut short is put back + if err := writeDimState(file, st); err != nil { + return err + } + } + if rec.Wrote && (rec.URL == "" || dimURL(p.Connection.BaseURL) == dimURL(rec.URL)) { + patch := map[string]any{} + if dimURL(p.Connection.BaseURL) != dimURL(url) { + patch["baseUrl"] = url + } + if !p.Enabled { + patch["enabled"] = true + } + if !p.Connection.CredentialConfigured || rec.Key != dimKeyHash(key) { + patch["credential"] = map[string]any{"action": "set", "value": key} + } + if len(patch) > 0 { + if err := c.update(p, patch); err != nil { + return err + } + } + rec.URL, rec.Key = url, dimKeyHash(key) + if err := writeDimState(file, st); err != nil { + return err + } + } + if !pick { + return nil + } + ref := strings.TrimPrefix(model, magpieID+"/") + var cat dimCatalog + if err := c.call("provider.refresh", map[string]any{"providerId": magpieID}, &cat); err != nil { + return err + } + i := slices.IndexFunc(cat.Models, func(m dimModel) bool { return m.ID == ref }) + if i < 0 { + return fmt.Errorf("Dim's Magpie provider doesn't list %s", ref) + } + if miss := cat.Models[i].MissingLimits; len(miss) > 0 { + // Dim picks no model without both limits (provider.select's + // provider_invalid_config); magpie gives the ones it lacks + ctx, out := dimLimits(model) + e := map[string]any{} + for _, m := range miss { + switch m { + case "contextWindow": + e[m] = ctx + case "maxOutputTokens": + e[m] = out + } + } + if err := c.call("provider.models.edit", map[string]any{"providerId": magpieID, "expectedVersion": cat.Version, "modelId": ref, "edit": e}, nil); err != nil { + return err + } + } + cur, err := c.selection() + if err != nil { + return err + } + if cur == nil || cur.Provider != magpieID || cur.Model != ref { + if err := c.pick(magpieID, ref, cur); err != nil { + return err + } + } + rec.Picked = ref + return writeDimState(file, st) +} + +// dimUnwire puts back what dimWire changed, where it is still as magpie +// left it: Dim's model before (Dim can't go back to none: a Dim that had +// none keeps magpie's, which says no model is available once the +// provider is off), and the Magpie provider's address, key (cleared) and +// off. A value the user changed since is theirs and stays. +func dimUnwire(dir, file string) error { + rec := readDimState(file).Dim + if rec == nil { + return nil + } + dimMu.Lock() + defer dimMu.Unlock() + c, err := dimConnect(dir, true) + if errors.Is(err, errDimAway) && proc.FindTool("dima") == "" { + return nil // Dim is gone, its settings with it + } + if err != nil { + return err + } + defer c.close() + if was := rec.Selection; rec.Picked != "" && was != nil && (was.Provider != magpieID || was.Model != rec.Picked) { + if cur, err := c.selection(); err == nil && cur != nil && cur.Provider == magpieID && cur.Model == rec.Picked { + c.pick(was.Provider, was.Model, cur) // a model since gone stays unpicked + } + } + if !rec.Wrote { + return nil + } + p, err := c.provider(magpieID) + if err != nil { + return err + } + if rec.URL == "" || dimURL(p.Connection.BaseURL) != dimURL(rec.URL) { + return nil + } + // Dim clears a key only with the provider turned off in the same patch + patch := map[string]any{"enabled": false} + if p.Connection.CredentialConfigured { + patch["credential"] = map[string]any{"action": "clear"} + } + if b := rec.BaseURL; b != "" && dimURL(b) != dimURL(p.Connection.BaseURL) { + patch["baseUrl"] = b + } + return c.update(p, patch) +} diff --git a/internal/agent/dim_daemon.go b/internal/agent/dim_daemon.go new file mode 100644 index 000000000..68115de44 --- /dev/null +++ b/internal/agent/dim_daemon.go @@ -0,0 +1,228 @@ +package agent + +// Dim alpha keeps its Providers in a database its daemon owns +// (/rust/dimcode.sqlite, with a version per record that every write +// is checked against), and changes them only through the daemon's +// JSON-RPC API, the one Dim's own CLI and desktop app use +// (crates/dim-app-server/src/provider/management.rs, +// docs/design/appserver/provider-management.md). magpie talks to the +// daemon the same way: newline-delimited JSON-RPC 2.0 after a hello of +// protocol 4, on /rust/daemon.sock on macOS and Linux, and on +// Windows through the authenticated pipe bridge Dim's client starts +// (`dimcode-server app-server --connect-pipe `, dim-client's +// Client::open). Without a daemon, `dima models magpie` starts one, as +// any dima command does, and lists nothing. + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strings" + "sync" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// errDimAway is Dim's daemon not reachable, and none started. +var errDimAway = errors.New("Dim's daemon isn't running") + +// dimOpen connects to the daemon of Dim's home dir, starting it when +// start and it isn't running; tests swap it for a fake daemon. +var dimOpen = openDimDaemon + +func openDimDaemon(dir string, start bool) (io.ReadWriteCloser, error) { + c, err := dimDial(dir) + if err == nil || !start || proc.Isolated() { + if err != nil { + return nil, fmt.Errorf("%w: %v", errDimAway, err) + } + return c, nil + } + bin := proc.FindTool("dima") + if bin == "" { + return nil, fmt.Errorf("%w: dima isn't installed", errDimAway) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + // any dima command starts the daemon; this one lists the Magpie + // provider's models and changes nothing + cmd := proc.CommandContext(ctx, bin, "models", "magpie") + cmd.Env = append(os.Environ(), "DIMCODE_HOME="+dir) + if err := cmd.Run(); err != nil { + return nil, fmt.Errorf("%w: dima models: %v", errDimAway, err) + } + for end := time.Now().Add(10 * time.Second); ; time.Sleep(200 * time.Millisecond) { + if c, err = dimDial(dir); err == nil || time.Now().After(end) { + break + } + } + if err != nil { + return nil, fmt.Errorf("%w: %v", errDimAway, err) + } + return c, nil +} + +// dimConn is one connection to Dim's daemon, greeted. +type dimConn struct { + rw io.ReadWriteCloser + r *bufio.Reader + id int + stop *time.Timer +} + +// dimError is an error the daemon answered, with Dim's own code +// (provider_conflict, provider_not_found, provider_invalid_config…). +type dimError struct { + Message string `json:"message"` + Data struct { + AppError string `json:"appError"` + } `json:"data"` +} + +func (e *dimError) Error() string { return "Dim: " + e.Message } + +func dimCode(err error) string { + var e *dimError + if errors.As(err, &e) { + return e.Data.AppError + } + return "" +} + +// dimConnect is a greeted connection, closed after a minute at most +// whatever it waits on. +func dimConnect(dir string, start bool) (*dimConn, error) { + rw, err := dimOpen(dir, start) + if err != nil { + return nil, err + } + c := &dimConn{rw: rw, r: bufio.NewReaderSize(rw, 64<<10)} + c.stop = time.AfterFunc(time.Minute, func() { rw.Close() }) + var hello struct { + ProtocolVersion int `json:"protocolVersion"` + } + if err := c.call("hello", map[string]any{"protocolVersion": 4, "clientKind": "other", "clientName": "magpie"}, &hello); err != nil { + c.close() + return nil, err + } + return c, nil +} + +func (c *dimConn) close() { + c.stop.Stop() + c.rw.Close() +} + +// call sends method and reads its answer into out (nil to drop it); +// notifications and other answers on the way are skipped. +func (c *dimConn) call(method string, params, out any) error { + c.id++ + b, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": c.id, "method": method, "params": params}) + if err != nil { + return err + } + if _, err := c.rw.Write(append(b, '\n')); err != nil { + return fmt.Errorf("Dim %s: %w", method, err) + } + for { + line, err := c.r.ReadBytes('\n') + if err != nil { + return fmt.Errorf("Dim %s: %w", method, err) + } + var m struct { + ID *int `json:"id"` + Result json.RawMessage `json:"result"` + Error *dimError `json:"error"` + } + if json.Unmarshal(line, &m) != nil || m.ID == nil || *m.ID != c.id { + continue + } + if m.Error != nil { + return m.Error + } + if out == nil { + return nil + } + return json.Unmarshal(m.Result, out) + } +} + +// dimProvider is the part of a Provider record (provider.management) +// magpie reads. +type dimProvider struct { + ID string `json:"providerId"` + Version int `json:"version"` + Enabled bool `json:"enabled"` + Connection struct { + BaseURL string `json:"baseUrl"` + CredentialConfigured bool `json:"credentialConfigured"` + } `json:"connection"` +} + +// dimModel is a model of a provider's catalog (provider.refresh). +type dimModel struct { + ID string `json:"id"` + MissingLimits []string `json:"missingLimits"` +} + +type dimCatalog struct { + Models []dimModel `json:"models"` + Version int `json:"version"` +} + +// dimSelection is Dim's picked model (provider.selection). +type dimSelection struct { + Provider string `json:"provider_id"` + Model string `json:"model_id"` + Version int `json:"version,omitempty"` +} + +func (c *dimConn) provider(id string) (*dimProvider, error) { + var r struct { + Providers []dimProvider `json:"providers"` + } + if err := c.call("provider.management", map[string]any{"providerId": id}, &r); err != nil { + return nil, err + } + for i := range r.Providers { + if r.Providers[i].ID == id { + return &r.Providers[i], nil + } + } + return nil, fmt.Errorf("Dim has no %s provider", id) +} + +func (c *dimConn) update(p *dimProvider, patch map[string]any) error { + return c.call("provider.update", map[string]any{"providerId": p.ID, "expectedVersion": p.Version, "patch": patch}, nil) +} + +func (c *dimConn) selection() (*dimSelection, error) { + var r struct { + Selection *dimSelection `json:"selection"` + } + if err := c.call("provider.selection", map[string]any{}, &r); err != nil { + return nil, err + } + return r.Selection, nil +} + +// pick makes provider/model Dim's model, over the pick of version was +// (nil: none yet). +func (c *dimConn) pick(provider, model string, was *dimSelection) error { + p := map[string]any{"providerId": provider, "modelId": model} + if was != nil { + p["expectedVersion"] = was.Version + } + return c.call("provider.select", p, nil) +} + +// dimMu keeps one change of Dim's providers at a time. +var dimMu sync.Mutex + +// dimURL is a base URL as Dim compares it. +func dimURL(u string) string { return strings.TrimRight(strings.TrimSpace(u), "/") } diff --git a/internal/agent/dim_daemon_other.go b/internal/agent/dim_daemon_other.go new file mode 100644 index 000000000..6affec7c1 --- /dev/null +++ b/internal/agent/dim_daemon_other.go @@ -0,0 +1,16 @@ +//go:build !windows + +package agent + +import ( + "io" + "net" + "path/filepath" + "time" +) + +// dimDial connects to the socket of Dim's daemon, /rust/daemon.sock +// (dim-cli's connect_inner). +func dimDial(dir string) (io.ReadWriteCloser, error) { + return net.DialTimeout("unix", filepath.Join(dir, "rust", "daemon.sock"), 5*time.Second) +} diff --git a/internal/agent/dim_daemon_test.go b/internal/agent/dim_daemon_test.go new file mode 100644 index 000000000..c5f5f1eb7 --- /dev/null +++ b/internal/agent/dim_daemon_test.go @@ -0,0 +1,428 @@ +package agent + +import ( + "bufio" + "encoding/json" + "errors" + "io" + "net" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/update" +) + +// fakeDim is Dim alpha's daemon as magpie talks to it: Provider records +// with versions every write is checked against, a key that is stored and +// never read back, provider.refresh listing the models the gateway would, +// and one global model pick with a version of its own, as +// crates/dim-app-server/src/provider.rs has them. +type fakeDim struct { + mu sync.Mutex + providers map[string]*fakeDimProvider + sel *dimSelection + listed []dimModel // what refresh lists for magpie + calls []string + starts int +} + +type fakeDimProvider struct { + version int + enabled bool + base string + key string // "" none + models []dimModel +} + +func newFakeDim() *fakeDim { + return &fakeDim{providers: map[string]*fakeDimProvider{ + "magpie": {version: 1, base: dimDefault}, + // one of the user's own, on the user's own key and model + "deepseek": {version: 7, enabled: true, base: "https://api.deepseek.com/v1", key: "sk-users", models: []dimModel{{ID: "deepseek-chat"}}}, + }, sel: &dimSelection{Provider: "deepseek", Model: "deepseek-chat", Version: 3}} +} + +// use makes f the daemon of every connection magpie opens; away is none. +func (f *fakeDim) use(t *testing.T) { + old := dimOpen + t.Cleanup(func() { dimOpen = old }) + dimOpen = func(dir string, start bool) (io.ReadWriteCloser, error) { + a, b := net.Pipe() + go f.serve(b) + return a, nil + } +} + +func away(t *testing.T) { + old := dimOpen + t.Cleanup(func() { dimOpen = old }) + dimOpen = func(string, bool) (io.ReadWriteCloser, error) { return nil, errDimAway } +} + +func (f *fakeDim) serve(c net.Conn) { + defer c.Close() + r := bufio.NewReader(c) + for { + line, err := r.ReadBytes('\n') + if err != nil { + return + } + var m struct { + ID int `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` + } + json.Unmarshal(line, &m) + res, code := f.answer(m.Method, m.Params) + out := map[string]any{"jsonrpc": "2.0", "id": m.ID} + if code != "" { + out["error"] = map[string]any{"code": -32000, "message": code, "data": map[string]any{"appError": code}} + } else { + out["result"] = res + } + b, _ := json.Marshal(out) + if _, err := c.Write(append(b, '\n')); err != nil { + return + } + } +} + +func (f *fakeDim) record(id string, p *fakeDimProvider) map[string]any { + return map[string]any{"providerId": id, "version": p.version, "enabled": p.enabled, + "connection": map[string]any{"baseUrl": p.base, "credentialConfigured": p.key != ""}} +} + +func (f *fakeDim) answer(method string, raw json.RawMessage) (any, string) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, method) + var p struct { + ProviderID string `json:"providerId"` + ModelID string `json:"modelId"` + ExpectedVersion *int `json:"expectedVersion"` + Patch map[string]any `json:"patch"` + Edit map[string]int `json:"edit"` + } + json.Unmarshal(raw, &p) + pr := f.providers[p.ProviderID] + switch method { + case "hello": + return map[string]any{"serverVersion": "0.1.0-alpha.24", "protocolVersion": 4}, "" + case "provider.management": + if pr == nil { + return nil, "provider_not_found" + } + return map[string]any{"providers": []any{f.record(p.ProviderID, pr)}}, "" + case "provider.update": + if pr == nil { + return nil, "provider_not_found" + } + if p.ExpectedVersion == nil || *p.ExpectedVersion != pr.version { + return nil, "provider_conflict" + } + if v, ok := p.Patch["baseUrl"].(string); ok { + pr.base = v + } + if v, ok := p.Patch["enabled"].(bool); ok { + pr.enabled = v + } + if c, ok := p.Patch["credential"].(map[string]any); ok { + switch c["action"] { + case "set": + pr.key, _ = c["value"].(string) + case "clear": + if pr.enabled { + return nil, "provider_invalid_config" // clear goes with enabled:false + } + pr.key = "" + } + } + pr.version++ + return f.record(p.ProviderID, pr), "" + case "provider.refresh": + if pr == nil || pr.key == "" || !pr.enabled { + return nil, "provider_invalid_config" + } + pr.models = slices.Clone(f.listed) + pr.version++ + return map[string]any{"models": pr.models, "version": pr.version}, "" + case "provider.models.edit": + if p.ExpectedVersion == nil || *p.ExpectedVersion != pr.version { + return nil, "provider_conflict" + } + for i, m := range pr.models { + if m.ID == p.ModelID { + pr.models[i].MissingLimits = slices.DeleteFunc(slices.Clone(m.MissingLimits), func(k string) bool { return p.Edit[k] > 0 }) + } + } + pr.version++ + return map[string]any{"models": pr.models, "version": pr.version}, "" + case "provider.selection": + return map[string]any{"selection": f.sel}, "" + case "provider.select": + have := (*int)(nil) + if f.sel != nil { + have = &f.sel.Version + } + if (have == nil) != (p.ExpectedVersion == nil) || have != nil && *have != *p.ExpectedVersion { + return nil, "provider_conflict" + } + if pr == nil { + return nil, "provider_not_found" + } + i := slices.IndexFunc(pr.models, func(m dimModel) bool { return m.ID == p.ModelID }) + if i < 0 { + return nil, "provider_not_found" + } + if len(pr.models[i].MissingLimits) > 0 { + return nil, "provider_invalid_config" + } + v := 1 + if f.sel != nil { + v = f.sel.Version + 1 + } + f.sel = &dimSelection{Provider: p.ProviderID, Model: p.ModelID, Version: v} + return f.sel, "" + } + return nil, "method_not_found" +} + +func (f *fakeDim) magpie() fakeDimProvider { + f.mu.Lock() + defer f.mu.Unlock() + return *f.providers["magpie"] +} + +func dimSandbox(t *testing.T) (home string) { + home = t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("DIMCODE_HOME", "") + t.Setenv("SHELL", "/bin/zsh") + t.Setenv("ZDOTDIR", "") + if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(home, ".zshrc"), []byte("export A=1\n"), 0o644) + return home +} + +// Connecting Dim fills in Dim's own built-in Magpie provider through its +// daemon: magpie's key for Dim, on, the model listed (its missing limits +// given) and picked as Dim's model, so a plain dima runs on magpie. The +// user's own provider and its key are untouched, no dima function is +// added, and Disconnect puts Dim's pick and the provider back. +func TestDimFillsItsMagpieProvider(t *testing.T) { + home := dimSandbox(t) + f := newFakeDim() + f.listed = []dimModel{{ID: "deepseek/pro", MissingLimits: []string{"contextWindow", "maxOutputTokens"}}, {ID: "deepseek/flash"}} + f.use(t) + a, err := Find("dim") + if err != nil { + t.Fatal(err) + } + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + m := f.magpie() + if m.key != gateway.TokenFor("dim") || !m.enabled || m.base != dimDefault { + t.Fatalf("Dim's Magpie provider: %+v (want key %q)", m, gateway.TokenFor("dim")) + } + if f.sel == nil || f.sel.Provider != "magpie" || f.sel.Model != "deepseek/pro" { + t.Fatalf("Dim's model %+v", f.sel) + } + if !slices.Contains(f.calls, "provider.models.edit") { + t.Fatalf("no limits given: %v", f.calls) + } + if d := f.providers["deepseek"]; d.version != 7 || d.key != "sk-users" || !d.enabled || d.base != "https://api.deepseek.com/v1" { + t.Fatalf("the user's own provider changed: %+v", d) + } + if update.ShellFunctionIn("dima") != nil { + t.Fatalf("dima function added in %v", update.ShellFunctionIn("dima")) + } + if s := a.Start(); s.Bin != "dima" || s.Model != "magpie/deepseek/pro" || len(s.Env) != 0 { + t.Fatalf("start %+v", s) + } + if a.Launch() != "" || a.Typed() != "" || a.Notice() != "" { + t.Fatalf("launch %q typed %q notice %q", a.Launch(), a.Typed(), a.Notice()) + } + if got := a.Field("model").Get(); got != "magpie/deepseek/pro" { + t.Fatalf("model %q", got) + } + // another model: picked, the provider's key not set again + updates := strings.Count(strings.Join(f.calls, " "), "provider.update") + if err := a.Apply("model", "magpie/deepseek/flash"); err != nil { + t.Fatal(err) + } + if f.sel.Model != "deepseek/flash" || strings.Count(strings.Join(f.calls, " "), "provider.update") != updates { + t.Fatalf("second pick: %+v %v", f.sel, f.calls) + } + + if err := a.Apply("model", ""); err != nil { + t.Fatal(err) + } + if f.sel.Provider != "deepseek" || f.sel.Model != "deepseek-chat" { + t.Fatalf("Dim's model not put back: %+v", f.sel) + } + if m := f.magpie(); m.key != "" || m.enabled || m.base != dimDefault { + t.Fatalf("Dim's Magpie provider not put back: %+v", m) + } + if _, err := os.Stat(dimFile()); !os.IsNotExist(err) { + t.Fatalf("dim.json kept: %v", err) + } + if b, _ := os.ReadFile(filepath.Join(home, ".zshrc")); string(b) != "export A=1\n" { + t.Fatalf(".zshrc:\n%s", b) + } +} + +// A gateway on another port than Dim's 3425 is given to the provider, and +// a later port is given to it again while it is as magpie left it. +func TestDimMagpieProviderPort(t *testing.T) { + dimSandbox(t) + t.Setenv("MAGPIE_ADDR", "127.0.0.1:4567") + f := newFakeDim() + f.sel = nil // a Dim with no model picked yet + f.listed = []dimModel{{ID: "deepseek/pro"}} + f.use(t) + a, _ := Find("dim") + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if m := f.magpie(); m.base != "http://127.0.0.1:4567/v1" || m.key == "" { + t.Fatalf("provider %+v", m) + } + t.Setenv("MAGPIE_ADDR", "127.0.0.1:4568") + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if m := f.magpie(); m.base != "http://127.0.0.1:4568/v1" { + t.Fatalf("new port not given: %+v", m) + } + if err := a.Apply("model", ""); err != nil { + t.Fatal(err) + } + if m := f.magpie(); m.base != dimDefault || m.key != "" || m.enabled { + t.Fatalf("not put back: %+v", m) + } +} + +// A key, or an address of the user's own, on Dim's Magpie provider is +// theirs: magpie picks the model on it and leaves it as it was, on +// Disconnect too. +func TestDimMagpieProviderUsersOwn(t *testing.T) { + for _, tc := range []struct { + name, base, key string + }{ + {"key", dimDefault, "users-own-key"}, + {"address", "http://192.168.1.9:3425/v1", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + dimSandbox(t) + f := newFakeDim() + mp := f.providers["magpie"] + mp.base, mp.key, mp.enabled = tc.base, tc.key, true + f.listed = []dimModel{{ID: "deepseek/pro"}} + f.use(t) + a, _ := Find("dim") + before := f.magpie() + if tc.key == "" { + // Dim lists nothing without a key: the pick fails and dima + // is started on magpie's variables instead + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + if m := f.magpie(); m.base != before.base || m.key != "" || m.version != before.version { + t.Fatalf("the user's address changed: %+v", m) + } + if a.Start().Env == nil { + t.Fatalf("no variables with no pick: %+v", a.Start()) + } + } else { + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + m := f.magpie() + if m.key != tc.key || m.base != tc.base || slices.Contains(f.calls, "provider.update") { + t.Fatalf("the user's own value changed: %+v %v", m, f.calls) + } + if f.sel.Provider != "magpie" || f.sel.Model != "deepseek/pro" { + t.Fatalf("not picked: %+v", f.sel) + } + } + if err := a.Apply("model", ""); err != nil { + t.Fatal(err) + } + if m := f.magpie(); m.key != before.key || m.base != before.base || !m.enabled || slices.Contains(f.calls, "provider.update") { + t.Fatalf("Disconnect changed the user's own: %+v %v", m, f.calls) + } + if f.sel.Provider != "deepseek" { + t.Fatalf("Dim's model not put back: %+v", f.sel) + } + }) + } +} + +// A Dim connected before magpie filled its provider in (its dima function +// in the user's shells) is moved onto the provider by a Sync while its +// daemon runs, and the function goes; with no daemon running, the +// function stays and nothing is started. +func TestDimSyncMovesToProvider(t *testing.T) { + home := dimSandbox(t) + away(t) + a, _ := Find("dim") + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + zshrc := filepath.Join(home, ".zshrc") + if b, _ := os.ReadFile(zshrc); !strings.Contains(string(b), "dima() {") { + t.Skipf("no dima function on this system: %s", b) + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(zshrc); !strings.Contains(string(b), "dima() {") { + t.Fatalf("function gone with no daemon: %s", b) + } + f := newFakeDim() + f.listed = []dimModel{{ID: "deepseek/pro"}} + f.use(t) + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if f.sel.Provider != "magpie" || f.magpie().key == "" { + t.Fatalf("not moved: %+v %+v", f.sel, f.magpie()) + } + if b, _ := os.ReadFile(zshrc); string(b) != "export A=1\n" { + t.Fatalf("function kept:\n%s", b) + } +} + +// Dim gone (no daemon, no dima) doesn't keep Disconnect from finishing. +func TestDimDisconnectWithDimGone(t *testing.T) { + dimSandbox(t) + t.Setenv("PATH", t.TempDir()) + f := newFakeDim() + f.listed = []dimModel{{ID: "deepseek/pro"}} + f.use(t) + a, _ := Find("dim") + if err := a.Apply("model", "magpie/deepseek/pro"); err != nil { + t.Fatal(err) + } + old := dimOpen + dimOpen = func(string, bool) (io.ReadWriteCloser, error) { return nil, errors.Join(errDimAway, os.ErrNotExist) } + defer func() { dimOpen = old }() + if err := a.Apply("model", ""); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(dimFile()); !os.IsNotExist(err) { + t.Fatalf("dim.json kept: %v", err) + } +} diff --git a/internal/agent/dim_daemon_windows.go b/internal/agent/dim_daemon_windows.go new file mode 100644 index 000000000..e9f24b747 --- /dev/null +++ b/internal/agent/dim_daemon_windows.go @@ -0,0 +1,107 @@ +package agent + +import ( + "bufio" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "time" + + "github.com/yetone/magpie/internal/proc" +) + +// dimPipe is the pipe of the daemon of Dim's native home, as dim-cli's +// connect_inner names it: dim-rust- and the first 32 hex digits of +// sha256("dimcode:" + the home as Rust's canonicalize gives it, \\?\C:\…). +func dimPipe(native string) (string, error) { + p, err := filepath.Abs(native) + if err != nil { + return "", err + } + if p, err = filepath.EvalSymlinks(p); err != nil { + return "", err + } + if rest, ok := strings.CutPrefix(p, `\\`); ok { + p = `\\?\UNC\` + rest + } else { + p = `\\?\` + p + } + sum := sha256.Sum256([]byte("dimcode:" + p)) + return `\\.\pipe\dim-rust-` + hex.EncodeToString(sum[:])[:32], nil +} + +// dimBridge is the pipe bridge process, its stdout and stdin the +// connection. +type dimBridge struct { + io.Reader + in io.WriteCloser + cmd *exec.Cmd +} + +func (b *dimBridge) Write(p []byte) (int, error) { return b.in.Write(p) } + +func (b *dimBridge) Close() error { + b.in.Close() + b.cmd.Process.Kill() + b.cmd.Wait() + return nil +} + +// dimDial starts Dim's own bridge to its daemon's pipe (dim-client's +// Client::open): the server binary Dim links into its native home, run +// as `app-server --connect-pipe `, which says {"status":"ready"} +// on its stderr once the pipe is authenticated. +func dimDial(dir string) (io.ReadWriteCloser, error) { + native := filepath.Join(dir, "rust") + pipe, err := dimPipe(native) + if err != nil { + return nil, err + } + server := filepath.Join(native, "dimcode-server.exe") + if _, err := os.Stat(server); err != nil { + return nil, err + } + cmd := proc.Command(server, "app-server", "--connect-pipe", pipe) + in, err := cmd.StdinPipe() + if err != nil { + return nil, err + } + out, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + errs, err := cmd.StderrPipe() + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + return nil, err + } + b := &dimBridge{Reader: out, in: in, cmd: cmd} + ready := make(chan string, 1) + go func() { + line, _ := bufio.NewReader(errs).ReadString('\n') + ready <- line + io.Copy(io.Discard, errs) + }() + var line string + select { + case line = <-ready: + case <-time.After(5 * time.Second): + } + var r struct { + Status string `json:"status"` + Code string `json:"code"` + } + if json.Unmarshal([]byte(line), &r) != nil || r.Status != "ready" { + b.Close() + return nil, errors.New("Dim's pipe bridge isn't ready: " + strings.TrimSpace(line)) + } + return b, nil +} diff --git a/internal/agent/dim_test.go b/internal/agent/dim_test.go index fc5b2a9de..63e10df27 100644 --- a/internal/agent/dim_test.go +++ b/internal/agent/dim_test.go @@ -13,10 +13,12 @@ import ( "github.com/yetone/magpie/internal/update" ) -// Dim alpha is started on magpie through the variables Dim documents for -// an OpenAI-compatible endpoint; the model is in magpie's own file, and -// nothing of Dim's (its home, settings, database or account) is written. +// With no Dim daemon to reach, Dim alpha is started on magpie through the +// variables Dim documents for an OpenAI-compatible endpoint; the model is +// in magpie's own file, and nothing of Dim's (its home, settings, +// database or account) is written. func TestDim(t *testing.T) { + away(t) home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home)