agent: Kun, magpie as a provider connection through its runtime API (zhongxingyuyes on X)
Kun (KunAgent 0.4.5, Electron, com.xingyuzhong.deepseekgui) keeps its
model providers in ~/.kun/data/model-connections.v2.json (or
$KUN_DATA_DIR) and changes them only through its runtime's admin API,
whose address and token are in runtime.json. magpie wires Kun by
calling that API while Kun runs:
POST /v1/model-connections/connect the magpie connection
PATCH /v1/model-connections/:id models, gateway address
POST /v1/model-connections/select the default model
DELETE /v1/model-connections/:id off
POST /v1/provider-config/transactions/preview, then commit
off when magpie's connection is the default: Kun refuses a
plain DELETE of the connection its default names, so the
transaction clears the default and removes it in one step,
and the default the user had before is put back.
When Kun isn't running, wiring says "open Kun, then try again"; the
file is never written behind Kun's back. Kun joins the agent list,
desktop-app detection, the env guard, the icon set (kun.png), the
READMEs and docs/reference.md and docs/subsystems/agent-wiring.md.
Run:
- WSL (Ubuntu 24.04), at the rebased head: go test -tags nogui
-run 'Kun|ListsModels|Picker|Spelled|HandWired|Sync|Drift|ListOnly|
Moved|LAN|Proxy' ./internal/agent ./internal/agentenv ok;
./internal/library ok; ./internal/gui -run 'Icon|Budget|CSS|I18n|
Picker' ok (agentenv: no tests match the filter).
- Windows (win-run): go test -run 'Kun|ListsModels|Picker|Spelled|
HandWired|Drift|ListOnly' ./internal/agent ok. CGO_ENABLED=0 go vet
for windows (agent, gui, agentenv), darwin nogui (agent, agentenv)
and linux nogui (agent, agentenv, gui): clean. gofmt -l clean.
- GUI (WSL, chromium + webkit): i18n-keys, i18n-en-no-cjk,
icon-one-tone, routing-client-icons, icon-tile together 63/63 at
this head. An earlier run at the pre-rebase head was 60/63, the 3
reds icon-one-tone's "Open Design one-tone ... Plugins page"
(chromium), which passed 48/48 alone there and at origin/main: a
load red (#5425).
- Real Kun 0.4.5 (Linux build, sandbox HOME, `kun serve`): connect,
a second model, Sync, restart, off. `kun run`
finished a turn through the gateway (POST /v1/chat/completions,
Bearer magpie-kun, reply "hello from magpie"). Off restored the
previous default, and with no previous default Kun was left with
none and no magpie connection.
Broken by hand: off through the plain DELETE again. The fake Kun now
refuses it as the real one does, and TestKunFromNothing and
TestKunFollowsTheGateway went red with "Deleted connection still has
references: default.providerId"; green with the transaction.
Not tried: Kun's desktop window itself (the runtime was driven
headless); macOS (mote refused SSH all session); `kun run --model`
(run uses its own default model, not the registry's default, so a
CLI run picks magpie's model only with --model).
This commit is contained in:
@@ -82,7 +82,7 @@ magpie finds the subscriptions your agents are signed in to by reading their sig
|
||||
<table>
|
||||
<tr><td>
|
||||
|
||||
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe
|
||||
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
|
||||
|
||||
</td></tr>
|
||||
</table>
|
||||
|
||||
+1
-1
@@ -82,7 +82,7 @@ magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、
|
||||
<table>
|
||||
<tr><td>
|
||||
|
||||
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe
|
||||
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · DevEco Code · Pi · oh-my-pi · StepCode · MothX · PenguinHarness · Aside · OmO · Prime Agent · mu · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · Zoo Code · JetBrains Air · Air (JetBrains IDEs) · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · jcode · Qwen Code · Muse Code · Empryo · nanobot · miniQ · Paimon · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
|
||||
|
||||
</td></tr>
|
||||
</table>
|
||||
|
||||
@@ -163,6 +163,7 @@ line; agents connected to magpie lose it when it quits.
|
||||
| T3 Code | `~/.t3/userdata/settings.json` (`$T3CODE_HOME/userdata`) | provider (a `magpie` provider instance on Claude Code, magpie's models as its custom models; a `magpie-codex` instance on Codex, whose `launchArgs` are Codex's own `-c` overrides to magpie and a `magpie-codex-models.json` catalog beside the settings. The harness is picked in T3's model picker) |
|
||||
| OpenMausBot | `~/.openmausbot/config.json` (`$OMB_DATA_DIR`) | provider (a `magpie` engine in `instances`: OpenMausBot's own Claude endpoint shape, Claude Code with `ANTHROPIC_BASE_URL` at the gateway and magpie's models as its `endpointModels`, in its own `CLAUDE_CONFIG_DIR` under `providers/magpie`. With no `instances` saved, OpenMausBot's default engines are written beside it. OpenMausBot reads it when it starts) |
|
||||
| Avibe | `~/.avibe/config/config.json` (`$AVIBE_HOME`; `~/.vibe_remote` from before 3.0), changed through its control socket `state/dispatch.sock` (Windows: `runtime/control-ipc/endpoint.json`) while it runs | provider (a `magpie` model source on its Models page: custom vendor, OpenAI chat completions at the gateway's `/v1`, with Avibe's own key; Avibe lists magpie's models from the gateway and adds the source to Vibey's, Claude Code's, Codex's and OpenCode's routes. Avibe has to be running to connect or disconnect it) |
|
||||
| Kun | `~/.kun/data/model-connections.v2.json` (`$KUN_DATA_DIR`), changed through its runtime's admin API (`baseUrl` and `runtimeToken` of `runtime.json` in the same folder) while it runs | model (a `magpie` connection in Settings > Providers: HTTP, OpenAI chat completions at the gateway's `/v1`, with Kun's own key and the models picked for Kun; the model picked is Kun's default. Kun has to be running to connect or disconnect it) |
|
||||
| OpenHanako | `~/.hanako/provider-catalog.json` + `agents/<id>/config.yaml` (`$HANA_HOME`; its local API while it runs) | model (the primary agent's; magpie's models as a provider) |
|
||||
| AtomCode | `~/.atomcode/config.toml` (`$ATOMCODE_HOME`) | model, effort (a `magpie` provider account, one model table per catalog model as its own sign-in writes) |
|
||||
| Snow CLI | `~/.snow/profiles/magpie.json` (`$SNOW_CONFIG_DIR`), made the active profile and copied to `config.json` | model (the user's other profiles' models too; Snow App takes the profile in with "Sync Snow CLI API config") |
|
||||
|
||||
@@ -51,7 +51,7 @@ something else shows up as drift.
|
||||
- magpie only removes what it wrote. Anything else in an agent's config stays as it was.
|
||||
- agy's shell function (`update.ShellFunction`, [`shellfn.go`](../../internal/update/shellfn.go)) sits between `# >>> magpie agy >>>` and `# <<< magpie agy <<<`, the only lines magpie writes or takes out of a profile. The profiles are those `cliProfile` names (zsh's in `ZDOTDIR` when set, bash's, fish's `config.fish`), plus PowerShell 7's and Windows PowerShell's on Windows when their execution policy runs a profile. A missing profile is made only for the shell a terminal opens. Only a file inside the home is written, writes go through temp-and-rename, and a profile that can't be read is left alone. Picking one of magpie's models and every `Sync` on one put it there, which covers users wired before it existed. Stepping out and a `Sync` off magpie take it out. agy in a WSL distro gets the function in the distro's own profiles (`agyDistroProfiles` in [`agy.go`](../../internal/agent/agy.go), through `update.ShellFunctionAt`): `~/.bashrc`, `~/.zshrc` and `~/.config/fish/config.fish` where each is, and the profile of the login shell the distro's `/etc/passwd` names (bash when it names none) made where it isn't. The distro's `ZDOTDIR` and `XDG_CONFIG_HOME` aren't read. No magpie runs there, so the function (`agyDistroFunction`) reads `settings.json`'s model with `sed` and carries the gateway's address as the distro reaches it (`place.gw`, Windows' under NAT) and the key it takes from there (`agentKeyAt`, the WSL key under NAT). `Sync` writes it again, so an address WSL changed on a restart follows, and until then `Check` reports a function naming another address. A user's own `alias agy` still wins over it. A terminal opened before the change still needs the `Launch` command.
|
||||
- A sync brings magpie's models up to date, not where the agent reaches magpie. Every `Sync` that `SyncCatalog` runs (each start and update of magpie, a provider added, and a plugin signed in to, out of or renewed, or listing other models than the last time: `plugin.OnChange` and `plugin.OnListed` call `catalog.Touched`, #2373) goes through `synced`, which passes each file written through `kept.away` (`edit.Filtered`, [`keptaway.go`](../../internal/agent/keptaway.go)). The filter sees every file written through `edit` while it is on, from any goroutine and under whatever lock the writer holds, so it takes none a writer may hold: the gateway's address and the LAN key are read before it is on (`keeping`), and magpie's own files (`magpieFile`: its folder as named or where its links lead, such as a `~/.config` linked into a dotfiles repo) are left as they are (ylorn on Discord: `settings.Save` under the settings' lock reached a filter that read the settings, and the app hung ~10s after every start; `TestOwnWritesDuringASyncWithALinkedConfig`). In a file without the gateway's own address, whose magpie the user pointed at an address on another machine (a NAS's, or this machine's LAN address), and with no address a WSL distro was seen at, that address stays in place of `gateway.URL()`, with the path before magpie's every URL at it had (`awayPath`: a reverse proxy's `/magpie`; on loopback, a local proxy's route where magpie answered or hasn't been asked), and so does the key that went with it in place of magpie's own (coeo91 on Discord: the base URL went back to 127.0.0.1 after an update or restart). An address on this machine's loopback follows the gateway; with more than one address or key gone, the write is left as it is. Picking a model in magpie still points the agent at this magpie, but for Claude Code at a proxy to it (above). ZCode and WorkBuddy keep such an address in their own writers too (`zcodeAddress`, `buddyWriteAt`).
|
||||
- An agent whose `Sync` does nothing but bring a block of magpie's name up to the catalog is `ListOnly` (OpenCode, MiMo Code and the other OpenCode forms, Pi and its forks, Goose, Crush, Air, AtomCode, Command Code, Droid, Fx, jcode, Kimi, MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenMausBot, Avibe, OpenPencil, Penguin, Qwen Code, T3 Code). `SyncCatalog` runs it only while the agent is connected (`Wired`), as its switch on the Agents page says: a custom provider the user named magpie in the agent, with a few models picked by hand, was written over with the whole catalog at every start (yyddbds on Discord, Xiaomi MiMo; `TestCatalogSyncLeavesAHandWrittenMagpieBlock`). A list magpie wrote while connected waits, while the agent runs a model of its own, until a model of magpie's is picked again; a model of magpie's picked by hand on a provider the user wrote doesn't connect it (`handWired`, above). Every `ListOnly` agent magpie connects reads as `Wired` (`TestListOnlyAgentsReadConnected`). Agents whose `Sync` also repairs while not connected (Codex, Claude, Grok, Hermes' bots) are not `ListOnly`. magpie keeps no copy of a list it wrote over before this, so such a list stays full until the user trims it.
|
||||
- An agent whose `Sync` does nothing but bring a block of magpie's name up to the catalog is `ListOnly` (OpenCode, MiMo Code and the other OpenCode forms, Pi and its forks, Goose, Crush, Air, AtomCode, Command Code, Droid, Fx, jcode, Kimi, MiniMax, Mothx, omp, OpenChamber, OpenClaw, OpenMausBot, Avibe, Kun, OpenPencil, Penguin, Qwen Code, T3 Code). `SyncCatalog` runs it only while the agent is connected (`Wired`), as its switch on the Agents page says: a custom provider the user named magpie in the agent, with a few models picked by hand, was written over with the whole catalog at every start (yyddbds on Discord, Xiaomi MiMo; `TestCatalogSyncLeavesAHandWrittenMagpieBlock`). A list magpie wrote while connected waits, while the agent runs a model of its own, until a model of magpie's is picked again; a model of magpie's picked by hand on a provider the user wrote doesn't connect it (`handWired`, above). Every `ListOnly` agent magpie connects reads as `Wired` (`TestListOnlyAgentsReadConnected`). Agents whose `Sync` also repairs while not connected (Codex, Claude, Grok, Hermes' bots) are not `ListOnly`. magpie keeps no copy of a list it wrote over before this, so such a list stays full until the user trims it.
|
||||
- `SyncCatalog` holds the catalog it builds (`provider.Hold`), the plugins' providers and sign-ins among it, for up to a second. Those `catalog.Touched` drops are told in the background, so a plugin change also drops what is held at once (`plugin.OnChangeNow`, [`hold.go`](../../internal/provider/hold.go)): the host's "auth" event is read before its reply to the sign-in that saved it, and a look at the accounts once the sign-in returns sees it (#2449: `magpie plugin login` found no account while a sync ran; `TestHeldGoesWithAPluginChange`).
|
||||
- JetBrains Air's `magpie-opencode.json` keeps user-added fields in `provider.magpie`, including nested options, on sync and model picks (`air` in [`air.go`](../../internal/agent/air.go), using `theirsKept` in [`sync.go`](../../internal/agent/sync.go)). The gateway fields and complete model list are still replaced, so removed models leave the list.
|
||||
- Air comes in two forms that read different files, both wired by `airAt` in [`air.go`](../../internal/agent/air.go). The Air app (`air`) reads `acp.json` in its own config folder. The Air plugin in JetBrains IDEs (`air-ide`; bundled from 2026.3, from Marketplace in 2026.2) reads `~/.jetbrains/acp.json` on every system, the file AI Assistant's custom agents are in too (`AcpConfigurationLoader` in the plugin's `intellij.air.backend.acp.runtime`, checked in air-plugin 262.8665.521). Each gets its own Magpie entry and `magpie-opencode.json` beside its `acp.json`. `air-ide` shows for an IDE config folder of 2026.2 or later, or with its entry already there (`TestAirIDEDetectedByIDEVersion`). Neither has a base URL for its own agents (JetBrains AI, the agent's login, or an Anthropic, OpenAI, Gemini or OpenRouter key); The plugin's Codex on its own login runs this computer's `codex` (the terminal's `PATH`, else the `@openai/codex` it installs) as `codex app-server` with the user's `CODEX_HOME` or `~/.codex`, and sets no `model_provider` (`CodexAppServerProcessKt`); its menu is Codex's `model/list` and its default `config/read`'s model. Its Claude Agent runs `claude` with only Air's hooks in `--settings`. So both go through magpie while Codex and Claude Code are connected here. The Air app's Codex runs with a `CODEX_HOME` of its own and JetBrains' gateway (`codexRuntimeEnvironment`, `[model_providers.air-gateway]`), and never does. The model on either Air row is the Magpie agent's alone, and the opened row says which of Air's own agents go through magpie (`airSaid` in `app.js`, `agent-air-own.test.cjs`; jumy_18634 on Discord).
|
||||
@@ -132,6 +132,7 @@ something else shows up as drift.
|
||||
- Claude Desktop's Code tab gets tool search only with Desktop's own `toolSearchEnabled` policy on (3p only, off by default). Off, Desktop 2.7032 (`Ztr` "off") starts Claude Code with `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`, and Claude Code (2.1.312, 2.1.316: `oae` returns "standard") then keeps tool search off whatever `ENABLE_TOOL_SEARCH` says, so every MCP tool went whole on each request (bigcat1800 on Discord: 13 MCP servers, ~162K tokens; a sandbox CLI with 60 MCP tools sent 83 tools, 205KB). On, with the gateway provider and a bundled Claude Code of 2.1.247 or later, Desktop hands the CLI `ENABLE_TOOL_SEARCH=force` as a managed setting and the same CLI sent 13 tools, MCP ones behind `ToolSearch`, 56KB, asking only `tool-search-tool-2025-10-19` of the betas. magpie's profile gets `toolSearchEnabled: true` once, on a switch on and from Sync, as `claudeAiImport` is (`desktopSeedToolSearch`, `desktopSeedOnce`, mark `claude-desktop.tool-search`): a value the user set, false too, or took away since, stays theirs (`TestClaudeDesktopTurnsOnToolSearch`). A profile the user applied for magpie's gateway (`desktopAppliedGateway`) is not written.
|
||||
- OpenMausBot (`openmausbot.go`) runs each bot on an engine from `instances` in `~/.openmausbot/config.json` (`$OMB_DATA_DIR`, `server/config.ts` in its source). magpie writes the `magpie` engine as OpenMausBot's own Claude endpoint (`newClaudeEndpoint`, `claude-endpoints.ts`): driver `claudeAgent`, access `custom`, `config.configDir` under `providers/magpie` so OpenMausBot starts Claude Code with its own `CLAUDE_CONFIG_DIR` and strips account keys the engine doesn't set (`claudeEnvironment`, `claude.ts`), `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the gateway, and magpie's models as `config.endpointModels`, kept to the ids OpenMausBot's `CLAUDE_MODEL_ID` accepts (one bad id makes it refuse the whole engine). A non-empty `instances` is the whole fleet, so with none saved magpie writes OpenMausBot's `DEFAULT_FLEET` beside it (`ombFleet`, stashed as `openmausbot.fleet`) and takes it out again on off if the user hasn't changed it (`TestOpenMausBotFleetChanged`). The name, a model picked from the list, other env and a `cli` are the user's. OpenMausBot reads the file once at start and writes back the fleet it holds whenever an engine is edited in it, so the switch is refused while it runs (`errOMBRunning`; not checked on Windows) and the notice asks to quit it first. That write-back, and an edit of magpie's engine there (`updateClaudeEndpoint` keeps only the model picked and its tiers), leave `endpointModels` without models picked in magpie, and no catalog change follows to sync it again: while magpie serves, `KeepOpenMausBotListed` runs the sync every 30 seconds when the saved list differs from magpie's (`ombListStale`; maxleebeta on Discord, 11-08: Antigravity's models missing from its search). A copy started before magpie's last change to the engine (`ombPart`: the gateway, the first model and the list) offers the row's Restart (`restartApps`, `OpenMausBot.app` and `OpenMausBot.exe`). Codex bots use `~/.codex`, which magpie's Codex wiring already covers.
|
||||
- Avibe (`avibe.go`, `avibe-os` on PyPI, the `vibe` CLI) keeps its model sources in `model_hub.sources` of `config/config.json` in its home (`$AVIBE_HOME`, else `~/.avibe`, else a legacy `~/.vibe_remote`: `config/paths.py`). A source can't be written there by hand: its key is sealed in the Model Hub's store and Avibe adds it to its agents' route chains as it is made. So magpie adds the `magpie` source through the same internal API Avibe's Models page uses (`POST /internal/model-hub`, `core/handlers/model_hub/rpc.py`) on the control socket `state/dispatch.sock` in its home, or on Windows the loopback port and bearer token in `runtime/control-ipc/endpoint.json` (`core/control_ipc.py`). `create_source` makes an `api_key` source of vendor `custom` at the gateway's `/v1` with `agentKey("avibe")`, protocol `openai_chat` and `save_unverified` (Avibe's probe can't tell which protocol a gateway serving all of them speaks); Avibe then lists the models from `/v1/models` itself. Chat completions, not Responses: for a Responses source its CLIProxyAPI runs Codex's executor, which sends `codex-tui` headers the gateway would take for Codex. Its id is stashed (`avibe.source:<home>`); a source of the custom vendor at the gateway's `/v1` counts as magpie's too. `delete_source` and `refresh_source` are sent with `force` and then again with the `would_remove_hops` and `would_interrupt` Avibe answers with, as its page confirms them. A gateway address change makes the source again (the key goes with the address and `patch_source` can't change it). Every change needs Avibe running (`avibeLive` probes `list_sources`; `errAvibeDown`); `Sync` refreshes the source's models while it runs.
|
||||
- Kun (`kun.go`, KunAgent/Kun, an Electron app, `com.xingyuzhong.deepseekgui`; zhongxingyuyes on X) keeps its model connections in `model-connections.v2.json` in its data folder (`$KUN_DATA_DIR`, not ~-expanded, else `~/.kun/data`). A connection's key goes to Kun's credential store as it is made, so the file isn't written by hand: magpie adds the `magpie` connection the way Settings > Providers does, through the runtime's admin API at the `baseUrl` of `runtime.json` in that folder, with its `runtimeToken` as a bearer (loopback only). `POST /v1/model-connections/connect` makes an `http` connection with `api-key` auth at the gateway's `/v1`, `endpointFormat` `chat_completions`, `agentKey("kun")`, the models picked for Kun (500 at most) and the pick selected; another of magpie's models is `PATCH` of the list and `POST /v1/model-connections/select`. Every change names the registry's revision (409 `revision_conflict` otherwise). Kun's default before magpie's is stashed (`kun.prev:<dir>`) and selected again when magpie steps out, then the connection is `DELETE`d. Kun refuses to delete the connection its default names ("still has references: default.providerId"), so with no default of Kun's own to go back to, magpie's goes as Kun's Settings retires one: a provider-config transaction (`POST /v1/provider-config/transactions/preview`, then `commit`) that clears the default and removes the connection (`kunClient.remove`, `TestKunFromNothing`). Its id is stashed (`kun.id:<dir>`); an HTTP connection at the gateway's `/v1` counts as magpie's too. Every change needs Kun running (`kunLive` probes the snapshot; `errKunDown`); reads go to the registry file first. A sync brings the list up to the picked models, and makes the connection again only from the gateway's own address on an older port (`kunMoved`, as `avibeMoved`). Every test of the package but Kun's own finds a Kun running per data folder (`runningKun`).
|
||||
- nanobot (`nanobot.go`, HKUDS/nanobot) answers with `agents.defaults.model`, asked of `agents.defaults.provider`, in `~/.nanobot/config.json` (`config/loader.py`), unless `agents.defaults.modelPreset` names a preset, which goes over both (`Config.resolve_preset`). Any key under `providers` that isn't one of nanobot's own is an OpenAI-compatible endpoint, and a model `<key>/<id>` is sent to it as `<id>` (`create_dynamic_spec`). magpie writes `providers.magpie` (`apiBase` at the gateway's `/v1`, its key, and `extraHeaders` with `User-Agent: nanobot`, by which the gateway tells its requests) and sets provider `magpie`, model `magpie/<id>` and `contextWindowTokens` to the window magpie knows. What the user had in those keys and a `modelPreset` (either spelling: nanobot reads camelCase and snake_case alike) are stashed and put back on off, and `providers.magpie` goes then. nanobot's gateway watches the file and takes a change at its next turn (`config/watcher.py`); `nanobot agent` reads it once.
|
||||
- miniQ (`miniq.go`, LeadingThink/miniQ) has one provider, `provider` in its daemon's `settings.json` (`{baseUrl, apiKey, model, apiProtocol}`, miniq-models `ProviderConfig`), in the data folder `$MINIQ_DATA_DIR`, else the one `miniq-data-dir.json` beside the default names, else `%LOCALAPPDATA%\miniq` or `~/.local/share/miniq` (macOS too). magpie writes the gateway's `/v1`, miniQ's own key (it sends no User-Agent of its own), the catalog id and `apiProtocol` `chat_completions`, since `auto` guesses Responses or Anthropic Messages from a model's name. The user's provider is stashed whole (key and `reasoningEffort` too) and put back on off; with none, the file magpie made goes. The daemon loads settings.json once and writes its whole copy back on every settings change, so magpie also sends a running daemon `settings.update` over the WebSocket `daemon.json` names (`miniqRPC`), which moves open chats to the new model. It can't take a provider out, so Notice asks the daemon (`settings.get`) and says to restart miniQ when its provider isn't the file's. A project's own model settings in miniQ go over the global one.
|
||||
- Paimon (`paimon.go`, aisk/paimon) keeps one JSON file, `$PAIMON_CONFIG_HOME/config.json` or `~/.config/paimon/config.json` (`config.py`). `model` is `provider:name`, and `providers.<provider>` holds that provider's `api_base` and `api_key` alone (`Config.provider_auth`). magpie uses pydantic-ai's `litellm` provider, an OpenAI-compatible proxy that profiles a `vendor/model` name by its vendor and that Paimon's login doesn't offer: `model` `litellm:<catalog id>`, `providers.litellm` at the gateway's `/v1` with magpie's key for Paimon, and `compaction.context_window` the model's window, which Paimon uses only for names genai-prices doesn't know and without which it never compacts. "On magpie" is told by the key. The user's `model`, `providers.litellm` and window are stashed and put back on Disconnect; a file magpie made goes again. Requests carry `paimon/<version>` (`llm.user_agent`). WSL: the distro's `~/.config/paimon`.
|
||||
|
||||
@@ -326,6 +326,7 @@ func onMachine(home, cfg string) []*Agent {
|
||||
t3code(home),
|
||||
openMausBot(home),
|
||||
avibe(home),
|
||||
kun(home),
|
||||
hanako(home),
|
||||
atomcode(home),
|
||||
snow(home),
|
||||
|
||||
@@ -120,7 +120,15 @@ var desktopApps = map[string]desktopApp{
|
||||
// per-user folder isn't under %LOCALAPPDATA%\Programs, so on Windows
|
||||
// it is found by its ~/.codely folder alone.
|
||||
"tuanjie-cowork": {id: "dev.codelycowork.desktop", names: []string{"Tuanjie Cowork.app"}},
|
||||
"penguin": {id: "com.prismshadow.penguinharness", names: []string{"PenguinHarness.app"}, win: filepath.Join("PenguinHarness", "PenguinHarness.exe"), guid: "8bb9acb7-2bdc-596b-9669-7b014ab1c47f"},
|
||||
// Kun (electron-builder.config.cjs, 0.4.5: appId
|
||||
// com.xingyuzhong.deepseekgui from its DeepSeek GUI days, productName
|
||||
// Kun, package kun-gui). Its Windows installer is a per-user assisted
|
||||
// NSIS one, so it goes to %LOCALAPPDATA%\Programs\Kun unless the user
|
||||
// picks another folder; guid is the UUID v5 of the appId, as dsh's
|
||||
// above. Its deb installs /opt/Kun, with the kun:// scheme.
|
||||
"kun": {id: "com.xingyuzhong.deepseekgui", names: []string{"Kun.app"}, win: filepath.Join("Kun", "Kun.exe"), guid: "af3c880c-15f8-5a1f-a7e8-6e299ab90803",
|
||||
onLinux: &linuxApp{dirs: []string{"/opt/Kun"}, exe: "kun-gui", name: "Kun", scheme: "kun"}},
|
||||
"penguin": {id: "com.prismshadow.penguinharness", names: []string{"PenguinHarness.app"}, win: filepath.Join("PenguinHarness", "PenguinHarness.exe"), guid: "8bb9acb7-2bdc-596b-9669-7b014ab1c47f"},
|
||||
// The CodeBuddy IDE (Tencent's VS Code fork, 4.12.2: CodeBuddy.app,
|
||||
// com.tencent.codebuddy, from codebuddy.ai; CodeBuddy CN.app,
|
||||
// com.tencent.codebuddycn, from codebuddy.cn) reads the CodeBuddy Code
|
||||
|
||||
@@ -0,0 +1,597 @@
|
||||
package agent
|
||||
|
||||
// Kun (KunAgent/Kun, kun-agent.com; zhongxingyuyes on X) is a local-first
|
||||
// AI workbench: a desktop app (Code, Work, chats, agents) and a `kun` TUI,
|
||||
// both clients of one runtime, `kun serve`. Its models come from the
|
||||
// provider connections in the runtime's registry,
|
||||
// model-connections.v2.json in its data folder: $KUN_DATA_DIR, else
|
||||
// ~/.kun/data (kun/src/cli/kun-data-dir.ts; read at v0.4.5). The registry
|
||||
// is the authority; the desktop's kun-settings.json and the runtime's
|
||||
// snapshots are projections of it, and a connection's key lives in Kun's
|
||||
// protected credential store under a reference, so a connection can't be
|
||||
// written into a file by hand.
|
||||
//
|
||||
// So magpie adds and removes its connection as Kun's own Settings >
|
||||
// Providers and its `kun provider` CLI do, through the runtime's admin API,
|
||||
// while Kun runs:
|
||||
//
|
||||
// GET /v1/model-connections the snapshot, with its revision
|
||||
// POST /v1/model-connections/connect {expectedRevision, id, name, baseUrl, credential, models, selectedModel, …}
|
||||
// PATCH /v1/model-connections/:id {expectedRevision, models}
|
||||
// POST /v1/model-connections/select {expectedRevision, providerId, model}
|
||||
// DELETE /v1/model-connections/:id?expected_revision=N
|
||||
// POST /v1/provider-config/transactions/preview, then commit the default's own connection
|
||||
//
|
||||
// at the baseUrl of runtime.json in the data folder, with its runtimeToken
|
||||
// as a bearer (server/runtime-discovery.ts, cli/gateway-cli.ts). magpie's
|
||||
// connection, "magpie", is an HTTP one at the gateway's /v1 spoken to as
|
||||
// chat completions with Kun's own agent key, its models the ones picked
|
||||
// for Kun on the Agents page (at most 500, contracts/model-connections.ts).
|
||||
// Picking a magpie model makes it Kun's default; the default Kun had is
|
||||
// stashed and picked again when magpie steps out, before its connection
|
||||
// is removed. The connection's id is stashed too, so one Kun renamed to
|
||||
// magpie-2 is still magpie's.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
)
|
||||
|
||||
// kunRegistry is the file of Kun's provider connections in its data folder.
|
||||
const kunRegistry = "model-connections.v2.json"
|
||||
|
||||
// kunMaxModels is how many models a Kun connection takes.
|
||||
const kunMaxModels = 500
|
||||
|
||||
// errKunDown is a change asked of a Kun that isn't running.
|
||||
var errKunDown = errors.New("Kun adds and changes model providers only while it runs: open Kun, then try again")
|
||||
|
||||
// kunStash is the stash key of what magpie keeps for the Kun at dir: the
|
||||
// id of its connection, and the default Kun had before.
|
||||
func kunStash(dir, what string) string { return "kun." + what + ":" + dir }
|
||||
|
||||
// kunDataDir is Kun's data folder: $KUN_DATA_DIR, else ~/.kun/data.
|
||||
func kunDataDir(home string) string {
|
||||
if d := strings.TrimSpace(appdir.Getenv("KUN_DATA_DIR")); d != "" {
|
||||
if abs, err := filepath.Abs(d); err == nil {
|
||||
return abs
|
||||
}
|
||||
return d
|
||||
}
|
||||
return filepath.Join(home, ".kun", "data")
|
||||
}
|
||||
|
||||
// kunProvider is a connection as the snapshot and the registry give it.
|
||||
type kunProvider struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
Models []string `json:"models"`
|
||||
SelectedModel string `json:"selectedModel"`
|
||||
}
|
||||
|
||||
// kunState is the runtime's snapshot: its connections and its default.
|
||||
type kunState struct {
|
||||
Revision int `json:"revision"`
|
||||
Providers []kunProvider `json:"providers"`
|
||||
DefaultProviderID string `json:"defaultProviderId"`
|
||||
DefaultAccountID string `json:"defaultAccountId"`
|
||||
DefaultModel string `json:"defaultModel"`
|
||||
}
|
||||
|
||||
func (s kunState) provider(id string) (kunProvider, bool) {
|
||||
for _, p := range s.Providers {
|
||||
if p.ID == id {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return kunProvider{}, false
|
||||
}
|
||||
|
||||
// kunOurs is magpie's connection in s: the one whose id magpie stashed,
|
||||
// else an HTTP one at the gateway (added by hand in Kun's Settings).
|
||||
func kunOurs(dir string, s kunState) (kunProvider, bool) {
|
||||
if id := unstashPeek(kunStash(dir, "id")); id != "" {
|
||||
if p, ok := s.provider(id); ok {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
for _, p := range s.Providers {
|
||||
if (p.Kind == "" || p.Kind == "http") && sameGateway(p.BaseURL, gatewayV1()) {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return kunProvider{}, false
|
||||
}
|
||||
|
||||
// kunRead is the Kun at dir's connections as its registry file has them,
|
||||
// for a Kun that isn't running: the registry keeps its connections as a
|
||||
// map of profiles.
|
||||
func kunRead(dir string) (kunState, bool) {
|
||||
raw, err := edit.Read(filepath.Join(dir, kunRegistry))
|
||||
if err != nil {
|
||||
return kunState{}, false
|
||||
}
|
||||
var doc struct {
|
||||
Revision int `json:"revision"`
|
||||
Profiles map[string]kunProvider `json:"profiles"`
|
||||
DefaultProviderID string `json:"defaultProviderId"`
|
||||
DefaultAccountID string `json:"defaultAccountId"`
|
||||
DefaultModel string `json:"defaultModel"`
|
||||
}
|
||||
if json.Unmarshal(raw, &doc) != nil {
|
||||
return kunState{}, false
|
||||
}
|
||||
s := kunState{Revision: doc.Revision, DefaultProviderID: doc.DefaultProviderID, DefaultAccountID: doc.DefaultAccountID, DefaultModel: doc.DefaultModel}
|
||||
for id, p := range doc.Profiles {
|
||||
if p.ID == "" {
|
||||
p.ID = id
|
||||
}
|
||||
s.Providers = append(s.Providers, p)
|
||||
}
|
||||
slices.SortFunc(s.Providers, func(a, b kunProvider) int { return strings.Compare(a.ID, b.ID) })
|
||||
return s, true
|
||||
}
|
||||
|
||||
// kunNow is the Kun at dir's state: its registry file's, which Kun
|
||||
// writes with every change, else the running one's snapshot. Reading the
|
||||
// file asks nothing of a Kun that isn't running.
|
||||
func kunNow(dir string) (kunState, bool) {
|
||||
if s, ok := kunRead(dir); ok {
|
||||
return s, true
|
||||
}
|
||||
if c := kunLive(dir); c != nil {
|
||||
if s, err := c.snapshot(); err == nil {
|
||||
return s, true
|
||||
}
|
||||
}
|
||||
return kunState{}, false
|
||||
}
|
||||
|
||||
// kunModels is the models picked for Kun, as many as a connection takes,
|
||||
// with want among them.
|
||||
func kunModels(want string) []string {
|
||||
var out []string
|
||||
for _, m := range sharedModels("kun") {
|
||||
if m.ID == "" || len(m.ID) > 512 || slices.Contains(out, m.ID) {
|
||||
continue
|
||||
}
|
||||
out = append(out, m.ID)
|
||||
}
|
||||
if want != "" && !slices.Contains(out, want) {
|
||||
out = append([]string{want}, out...)
|
||||
}
|
||||
if len(out) > kunMaxModels {
|
||||
if i := slices.Index(out, want); i >= kunMaxModels {
|
||||
out[kunMaxModels-1] = want
|
||||
}
|
||||
out = out[:kunMaxModels]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// kunPrev is the default Kun had before magpie's, as stashed.
|
||||
type kunPrev struct {
|
||||
Provider string `json:"provider"`
|
||||
Account string `json:"account,omitempty"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
func kun(home string) *Agent {
|
||||
dir := kunDataDir(home)
|
||||
path := filepath.Join(dir, kunRegistry)
|
||||
keyID, keyPrev := kunStash(dir, "id"), kunStash(dir, "prev")
|
||||
// wire makes magpie's connection Kun's default with model m, made
|
||||
// where there is none or it was made for a gateway elsewhere
|
||||
wire := func(c *kunClient, s kunState, m string) error {
|
||||
ours, there := kunOurs(dir, s)
|
||||
if there && kunMoved(ours.BaseURL) {
|
||||
next, err := c.remove(s, ours.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s, there = next, false
|
||||
}
|
||||
if !there {
|
||||
if s.DefaultProviderID != "" {
|
||||
b, _ := json.Marshal(kunPrev{Provider: s.DefaultProviderID, Account: s.DefaultAccountID, Model: s.DefaultModel})
|
||||
if _, had := kunOurs(dir, s); !had && unstashPeek(keyPrev) == "" {
|
||||
stash(map[string]string{keyPrev: string(b)})
|
||||
}
|
||||
}
|
||||
next, err := c.connect(s, m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, p := range next.Providers {
|
||||
if _, was := s.provider(p.ID); !was {
|
||||
stash(map[string]string{keyID: p.ID})
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if unstashPeek(keyID) != ours.ID {
|
||||
stash(map[string]string{keyID: ours.ID})
|
||||
}
|
||||
if models := kunModels(m); !slices.Equal(models, ours.Models) {
|
||||
next, err := c.patchModels(s, ours.ID, models)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s = next
|
||||
}
|
||||
if s.DefaultProviderID == ours.ID && s.DefaultModel == m {
|
||||
return nil
|
||||
}
|
||||
return c.selectModel(s, ours.ID, m)
|
||||
}
|
||||
// unwire takes magpie's connection out of Kun, its default going back
|
||||
// to what it was, with model v where v isn't ""
|
||||
unwire := func(c *kunClient, s kunState, ours kunProvider, v string) error {
|
||||
var prev kunPrev
|
||||
json.Unmarshal([]byte(unstashPeek(keyPrev)), &prev)
|
||||
if _, ok := s.provider(prev.Provider); !ok || prev.Provider == ours.ID {
|
||||
prev = kunPrev{}
|
||||
}
|
||||
if v != "" && prev.Provider == "" {
|
||||
return errors.New("Kun had no provider of its own to use " + v + " with: add one in Kun's Settings > Providers")
|
||||
}
|
||||
if prev.Provider != "" {
|
||||
if v == "" {
|
||||
v = prev.Model
|
||||
}
|
||||
if v != "" {
|
||||
if err := c.selectModel(s, prev.Provider, v); err != nil {
|
||||
return err
|
||||
}
|
||||
next, err := c.snapshot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s = next
|
||||
}
|
||||
}
|
||||
if _, err := c.remove(s, ours.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
forget(keyID, keyPrev)
|
||||
return nil
|
||||
}
|
||||
return &Agent{
|
||||
ID: "kun", Name: "Kun", Icon: "kun",
|
||||
Dir: dir, Path: path,
|
||||
detect: func() bool {
|
||||
return isDir(dir) || (&Agent{ID: "kun"}).HasApp()
|
||||
},
|
||||
ListsModels: true,
|
||||
ListOnly: true,
|
||||
// a model picked or dropped for Kun reaches its connection's list,
|
||||
// and a gateway on a new port its address
|
||||
Sync: func() error {
|
||||
c := kunLive(dir)
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
s, err := c.snapshot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ours, ok := kunOurs(dir, s)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
m := ours.SelectedModel
|
||||
if s.DefaultProviderID == ours.ID && s.DefaultModel != "" {
|
||||
m = s.DefaultModel
|
||||
}
|
||||
if kunMoved(ours.BaseURL) {
|
||||
return wire(c, s, m)
|
||||
}
|
||||
models := kunModels(m)
|
||||
if slices.Equal(models, ours.Models) {
|
||||
return nil
|
||||
}
|
||||
_, err = c.patchModels(s, ours.ID, models)
|
||||
return err
|
||||
},
|
||||
Check: func() string {
|
||||
s, ok := kunRead(dir)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
ours, ok := kunOurs(dir, s)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return wiringOff("Kun", path, func(string) (string, bool) { return strings.TrimSuffix(ours.BaseURL, "/"), true }, "baseUrl", gatewayV1())
|
||||
},
|
||||
Fields: []Field{{
|
||||
Key: "model", Label: "model",
|
||||
Get: func() string {
|
||||
s, ok := kunNow(dir)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if ours, on := kunOurs(dir, s); on && s.DefaultProviderID == ours.ID && s.DefaultModel != "" {
|
||||
return magpieID + "/" + s.DefaultModel
|
||||
}
|
||||
return s.DefaultModel
|
||||
},
|
||||
Set: func(v string) error {
|
||||
if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {
|
||||
c := kunLive(dir)
|
||||
if c == nil {
|
||||
return errKunDown
|
||||
}
|
||||
s, err := c.snapshot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return wire(c, s, ref)
|
||||
}
|
||||
s, known := kunRead(dir)
|
||||
ours, on := kunOurs(dir, s)
|
||||
if known && !on && (v == "" || v == s.DefaultModel) {
|
||||
return nil
|
||||
}
|
||||
c := kunLive(dir)
|
||||
if c == nil {
|
||||
if !known {
|
||||
return nil
|
||||
}
|
||||
return errKunDown
|
||||
}
|
||||
if s, err := c.snapshot(); err == nil {
|
||||
ours, on = kunOurs(dir, s)
|
||||
if on {
|
||||
return unwire(c, s, ours, v)
|
||||
}
|
||||
if v == "" || v == s.DefaultModel {
|
||||
return nil
|
||||
}
|
||||
if s.DefaultProviderID == "" {
|
||||
return errors.New("Kun has no provider of its own to use " + v + " with: add one in Kun's Settings > Providers")
|
||||
}
|
||||
return c.selectModel(s, s.DefaultProviderID, v)
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
},
|
||||
Options: func(cur map[string]string) []Option {
|
||||
var own []Option
|
||||
if c := cur["model"]; c != "" && !usesMagpie(c) {
|
||||
own = append(own, Option{Value: c, Icon: modelIcon("", c)})
|
||||
}
|
||||
return withVia(group("Kun", own), "kun", magpieID+"/")
|
||||
},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
// kunMoved says base, magpie's connection's address, is the gateway's own
|
||||
// on an older port, which a sync moves to where the gateway is now; one
|
||||
// the user pointed elsewhere (another machine, a proxy's route, the way a
|
||||
// WSL distro reaches Windows) stays, as avibeMoved keeps it.
|
||||
func kunMoved(base string) bool { return avibeMoved(base) }
|
||||
|
||||
// kunProbe gives up quickly: a runtime that doesn't answer at once isn't
|
||||
// running.
|
||||
const kunProbe = 1500 * time.Millisecond
|
||||
|
||||
// kunWait is how long a change may take: a connection's credential is
|
||||
// written to Kun's protected store as it is made.
|
||||
const kunWait = 30 * time.Second
|
||||
|
||||
// kunClient is a running Kun runtime's admin API.
|
||||
type kunClient struct {
|
||||
http *http.Client
|
||||
base string
|
||||
token string
|
||||
}
|
||||
|
||||
// kunLive is kunConnect, for the tests to stand in for.
|
||||
var kunLive = kunConnect
|
||||
|
||||
// kunConnect is the admin API of the Kun runtime serving dir if it
|
||||
// answers, nil if none runs: runtime.json outlives a crash.
|
||||
func kunConnect(dir string) *kunClient {
|
||||
c := kunAt(dir)
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), kunProbe)
|
||||
defer cancel()
|
||||
if _, err := c.do(ctx, "GET", "/v1/model-connections", nil); err != nil {
|
||||
return nil
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// kunAt is where the runtime serving dir listens, as runtime.json there
|
||||
// says, or nil with none: Kun's own CLI finds it the same way.
|
||||
func kunAt(dir string) *kunClient {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "runtime.json"))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var d struct {
|
||||
BaseURL string `json:"baseUrl"`
|
||||
Token string `json:"runtimeToken"`
|
||||
}
|
||||
if json.Unmarshal(b, &d) != nil || d.BaseURL == "" {
|
||||
return nil
|
||||
}
|
||||
u, err := url.Parse(d.BaseURL)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || !kunLoopback(u.Hostname()) {
|
||||
return nil
|
||||
}
|
||||
return &kunClient{http: &http.Client{}, base: strings.TrimRight(d.BaseURL, "/"), token: d.Token}
|
||||
}
|
||||
|
||||
// kunLoopback says h names this computer: the runtime's token goes
|
||||
// nowhere else.
|
||||
func kunLoopback(h string) bool {
|
||||
if h == "localhost" {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(h)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
// kunError is a refusal from Kun's runtime.
|
||||
type kunError struct {
|
||||
Status int
|
||||
Code, Message string
|
||||
}
|
||||
|
||||
func (e *kunError) Error() string {
|
||||
if e.Message != "" {
|
||||
return "Kun: " + e.Message
|
||||
}
|
||||
return fmt.Sprintf("Kun: %s (HTTP %d)", e.Code, e.Status)
|
||||
}
|
||||
|
||||
func (c *kunClient) do(ctx context.Context, method, path string, body any) ([]byte, error) {
|
||||
var r io.Reader
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.base+path, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Kun: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
out, err := io.ReadAll(io.LimitReader(resp.Body, 32<<20))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Kun: %w", err)
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
var e struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
json.Unmarshal(out, &e)
|
||||
if e.Code == "" {
|
||||
e.Code = resp.Status
|
||||
}
|
||||
return nil, &kunError{Status: resp.StatusCode, Code: e.Code, Message: e.Message}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// call is a change, answered with the snapshot it leaves.
|
||||
func (c *kunClient) call(method, path string, body any) (kunState, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), kunWait)
|
||||
defer cancel()
|
||||
b, err := c.do(ctx, method, path, body)
|
||||
if err != nil {
|
||||
return kunState{}, err
|
||||
}
|
||||
var s kunState
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return kunState{}, fmt.Errorf("Kun: %s %s: %w", method, path, err)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (c *kunClient) snapshot() (kunState, error) {
|
||||
return c.call("GET", "/v1/model-connections", nil)
|
||||
}
|
||||
|
||||
// connect adds magpie's connection with model m picked, as Kun's default.
|
||||
// Kun's own probe is off: it can't tell the gateway's protocols apart (it
|
||||
// serves them all), and the models are the ones picked for Kun.
|
||||
func (c *kunClient) connect(s kunState, m string) (kunState, error) {
|
||||
return c.call("POST", "/v1/model-connections/connect", map[string]any{
|
||||
"expectedRevision": s.Revision,
|
||||
"id": magpieID, "name": "magpie",
|
||||
"kind": "http", "authType": "api-key",
|
||||
"baseUrl": gatewayV1(), "endpointFormat": "chat_completions",
|
||||
"credential": agentKey("kun"),
|
||||
"models": kunModels(m), "selectedModel": m,
|
||||
"probe": false, "select": true,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *kunClient) patchModels(s kunState, id string, models []string) (kunState, error) {
|
||||
return c.call("PATCH", "/v1/model-connections/"+url.PathEscape(id), map[string]any{
|
||||
"expectedRevision": s.Revision, "models": models,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *kunClient) selectModel(s kunState, id, m string) error {
|
||||
_, err := c.call("POST", "/v1/model-connections/select", map[string]any{
|
||||
"expectedRevision": s.Revision, "providerId": id, "model": m,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// remove takes connection id out of Kun. Kun refuses to delete the
|
||||
// connection its default names ("Deleted connection still has references:
|
||||
// default.providerId"), so that one goes as Kun's own Settings retires it:
|
||||
// one provider-config transaction that clears the default and removes the
|
||||
// connection, previewed and then committed
|
||||
// (server/routes/provider-configuration.ts,
|
||||
// services/provider-configuration-operations.ts).
|
||||
func (c *kunClient) remove(s kunState, id string) (kunState, error) {
|
||||
if s.DefaultProviderID != id {
|
||||
return c.call("DELETE", "/v1/model-connections/"+url.PathEscape(id)+"?expected_revision="+fmt.Sprint(s.Revision), nil)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), kunWait)
|
||||
defer cancel()
|
||||
b, err := c.do(ctx, "POST", "/v1/provider-config/transactions/preview", map[string]any{
|
||||
"expectedRevision": s.Revision,
|
||||
"operations": []any{
|
||||
map[string]any{"kind": "set-default-selection"},
|
||||
map[string]any{"kind": "remove-connection", "connectionId": id},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return kunState{}, err
|
||||
}
|
||||
var p struct {
|
||||
PreviewID string `json:"previewId"`
|
||||
ExpectedRevision int `json:"expectedRevision"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &p); err != nil || p.PreviewID == "" {
|
||||
return kunState{}, fmt.Errorf("Kun: no preview of removing %s", id)
|
||||
}
|
||||
if _, err := c.do(ctx, "POST", "/v1/provider-config/transactions/commit", map[string]any{
|
||||
"expectedRevision": p.ExpectedRevision, "previewId": p.PreviewID,
|
||||
"idempotencyKey": "magpie:remove:" + id + ":" + p.PreviewID,
|
||||
}); err != nil {
|
||||
return kunState{}, err
|
||||
}
|
||||
return c.snapshot()
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeKun is a Kun runtime's model-connections admin API
|
||||
// (kun/src/server/routes/model-connections.ts, 0.4.5) as magpie uses it,
|
||||
// keeping its connections in model-connections.v2.json as Kun's registry
|
||||
// does: a change names the revision it was made against and is refused
|
||||
// with 409 revision_conflict on another, a connection's id is its name's
|
||||
// (magpie-2 when magpie is taken), and a model is selected only from its
|
||||
// connection's list. The connection Kun's default names is never deleted
|
||||
// on its own; it goes in a provider-config transaction that clears the
|
||||
// default too (services/provider-configuration-operations.ts).
|
||||
type fakeKun struct {
|
||||
dir string
|
||||
|
||||
mu sync.Mutex
|
||||
ops []string
|
||||
made []map[string]any
|
||||
creds map[string]string
|
||||
// previews are provider-config transactions previewed, by id
|
||||
previews map[string][]any
|
||||
}
|
||||
|
||||
type fakeKunDoc struct {
|
||||
SchemaVersion int `json:"schemaVersion"`
|
||||
Revision int `json:"revision"`
|
||||
Profiles map[string]map[string]any `json:"profiles"`
|
||||
DefaultProviderID string `json:"defaultProviderId,omitempty"`
|
||||
DefaultAccountID string `json:"defaultAccountId,omitempty"`
|
||||
DefaultModel string `json:"defaultModel,omitempty"`
|
||||
}
|
||||
|
||||
func (f *fakeKun) read() fakeKunDoc {
|
||||
d := fakeKunDoc{SchemaVersion: 2, Profiles: map[string]map[string]any{}}
|
||||
b, err := os.ReadFile(filepath.Join(f.dir, kunRegistry))
|
||||
if err == nil {
|
||||
json.Unmarshal(b, &d)
|
||||
}
|
||||
if d.Profiles == nil {
|
||||
d.Profiles = map[string]map[string]any{}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func (f *fakeKun) write(d fakeKunDoc) {
|
||||
os.MkdirAll(f.dir, 0o700)
|
||||
b, _ := json.MarshalIndent(d, "", " ")
|
||||
os.WriteFile(filepath.Join(f.dir, kunRegistry), b, 0o600)
|
||||
}
|
||||
|
||||
// add puts a connection of the user's own in, as Kun's Settings does.
|
||||
func (f *fakeKun) add(id, base string, models []string, def bool) {
|
||||
d := f.read()
|
||||
d.Profiles[id] = map[string]any{"id": id, "accountId": "default", "name": id, "kind": "http", "baseUrl": base, "models": models, "selectedModel": models[0]}
|
||||
if def {
|
||||
d.DefaultProviderID, d.DefaultAccountID, d.DefaultModel = id, "default", models[0]
|
||||
}
|
||||
d.Revision++
|
||||
f.write(d)
|
||||
}
|
||||
|
||||
func (f *fakeKun) snapshot(d fakeKunDoc) map[string]any {
|
||||
var ps []map[string]any
|
||||
ids := make([]string, 0, len(d.Profiles))
|
||||
for id := range d.Profiles {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
for _, id := range ids {
|
||||
p := map[string]any{"configured": true, "enabled": true, "credentialStatus": "configured"}
|
||||
for k, v := range d.Profiles[id] {
|
||||
p[k] = v
|
||||
}
|
||||
ps = append(ps, p)
|
||||
}
|
||||
return map[string]any{"schemaVersion": 1, "revision": d.Revision, "providers": ps,
|
||||
"defaultProviderId": d.DefaultProviderID, "defaultAccountId": d.DefaultAccountID, "defaultModel": d.DefaultModel}
|
||||
}
|
||||
|
||||
func (f *fakeKun) handler(token string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
fail := func(code int, c, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(map[string]any{"code": c, "message": msg})
|
||||
}
|
||||
if token != "" && r.Header.Get("Authorization") != "Bearer "+token {
|
||||
fail(401, "unauthorized", "missing or invalid runtime token")
|
||||
return
|
||||
}
|
||||
d := f.read()
|
||||
var body map[string]any
|
||||
if r.Body != nil { // a client's GET through handlerTransport has none
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
}
|
||||
rev := func() bool {
|
||||
want := fmt.Sprint(body["expectedRevision"])
|
||||
if q := r.URL.Query().Get("expected_revision"); q != "" {
|
||||
want = q
|
||||
}
|
||||
if want != strconv.Itoa(d.Revision) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(409)
|
||||
json.NewEncoder(w).Encode(map[string]any{"code": "revision_conflict", "message": "stale", "snapshot": f.snapshot(d)})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
strs := func(v any) []string {
|
||||
var out []string
|
||||
for _, x := range v.([]any) {
|
||||
out = append(out, x.(string))
|
||||
}
|
||||
return out
|
||||
}
|
||||
path := r.URL.Path
|
||||
f.ops = append(f.ops, r.Method+" "+path)
|
||||
switch {
|
||||
case r.Method == "GET" && path == "/v1/model-connections":
|
||||
case r.Method == "POST" && path == "/v1/model-connections/connect":
|
||||
if !rev() {
|
||||
return
|
||||
}
|
||||
models := strs(body["models"])
|
||||
sel, _ := body["selectedModel"].(string)
|
||||
if len(models) > 500 || sel != "" && !slices.Contains(models, sel) {
|
||||
fail(400, "invalid_request", "selected model is not present in the provider model list")
|
||||
return
|
||||
}
|
||||
id, _ := body["id"].(string)
|
||||
if id == "" {
|
||||
id, _ = body["name"].(string)
|
||||
}
|
||||
for base, n := id, 2; d.Profiles[id] != nil; n++ {
|
||||
id = fmt.Sprintf("%s-%d", base, n)
|
||||
}
|
||||
f.made = append(f.made, body)
|
||||
if f.creds == nil {
|
||||
f.creds = map[string]string{}
|
||||
}
|
||||
f.creds[id], _ = body["credential"].(string)
|
||||
d.Profiles[id] = map[string]any{"id": id, "accountId": "default", "name": body["name"], "kind": body["kind"], "authType": body["authType"],
|
||||
"baseUrl": body["baseUrl"], "endpointFormat": body["endpointFormat"], "models": models, "selectedModel": sel}
|
||||
if body["select"] == true {
|
||||
d.DefaultProviderID, d.DefaultAccountID, d.DefaultModel = id, "default", sel
|
||||
}
|
||||
d.Revision += 2 // the credential's transaction, then the commit
|
||||
f.write(d)
|
||||
w.WriteHeader(201)
|
||||
case r.Method == "POST" && path == "/v1/model-connections/select":
|
||||
if !rev() {
|
||||
return
|
||||
}
|
||||
id, _ := body["providerId"].(string)
|
||||
m, _ := body["model"].(string)
|
||||
p := d.Profiles[id]
|
||||
if p == nil {
|
||||
fail(404, "not_found", "provider not found")
|
||||
return
|
||||
}
|
||||
if ms := p["models"].([]any); len(ms) > 0 && !slices.Contains(ms, any(m)) {
|
||||
fail(400, "invalid_request", "model is not available for this provider")
|
||||
return
|
||||
}
|
||||
p["selectedModel"] = m
|
||||
d.DefaultProviderID, d.DefaultAccountID, d.DefaultModel = id, "default", m
|
||||
d.Revision++
|
||||
f.write(d)
|
||||
case r.Method == "POST" && path == "/v1/provider-config/transactions/preview":
|
||||
if !rev() {
|
||||
return
|
||||
}
|
||||
if f.previews == nil {
|
||||
f.previews = map[string][]any{}
|
||||
}
|
||||
id := fmt.Sprintf("00000000-0000-4000-8000-%012d", len(f.previews)+1)
|
||||
f.previews[id], _ = body["operations"].([]any)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"previewId": id, "expectedRevision": d.Revision, "operations": body["operations"]})
|
||||
return
|
||||
case r.Method == "POST" && path == "/v1/provider-config/transactions/commit":
|
||||
if !rev() {
|
||||
return
|
||||
}
|
||||
ops, ok := f.previews[fmt.Sprint(body["previewId"])]
|
||||
if !ok || body["idempotencyKey"] == "" {
|
||||
fail(400, "invalid_request", "Configuration preview expired; review the changes again")
|
||||
return
|
||||
}
|
||||
delete(f.previews, fmt.Sprint(body["previewId"]))
|
||||
for _, o := range ops {
|
||||
op := o.(map[string]any)
|
||||
switch op["kind"] {
|
||||
case "set-default-selection":
|
||||
if op["selection"] != nil {
|
||||
fail(400, "invalid_request", "not faked")
|
||||
return
|
||||
}
|
||||
d.DefaultProviderID, d.DefaultAccountID, d.DefaultModel = "", "", ""
|
||||
case "remove-connection":
|
||||
id := fmt.Sprint(op["connectionId"])
|
||||
if d.Profiles[id] == nil {
|
||||
fail(400, "invalid_request", "connection not found")
|
||||
return
|
||||
}
|
||||
delete(d.Profiles, id)
|
||||
default:
|
||||
fail(400, "invalid_request", "not faked")
|
||||
return
|
||||
}
|
||||
}
|
||||
if d.DefaultProviderID != "" && d.Profiles[d.DefaultProviderID] == nil {
|
||||
fail(400, "invalid_request", "Deleted connection still has references: default.providerId")
|
||||
return
|
||||
}
|
||||
d.Revision++
|
||||
f.write(d)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"committedRevision": d.Revision, "applied": true})
|
||||
return
|
||||
case strings.HasPrefix(path, "/v1/model-connections/"):
|
||||
id := strings.TrimPrefix(path, "/v1/model-connections/")
|
||||
p := d.Profiles[id]
|
||||
if p == nil {
|
||||
fail(404, "not_found", "provider not found")
|
||||
return
|
||||
}
|
||||
if !rev() {
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case "PATCH":
|
||||
if ms, ok := body["models"]; ok {
|
||||
p["models"] = ms
|
||||
}
|
||||
case "DELETE":
|
||||
if d.DefaultProviderID == id {
|
||||
fail(400, "invalid_request", "Deleted connection still has references: default.providerId")
|
||||
return
|
||||
}
|
||||
delete(d.Profiles, id)
|
||||
default:
|
||||
fail(405, "method_not_allowed", "")
|
||||
return
|
||||
}
|
||||
d.Revision++
|
||||
f.write(d)
|
||||
default:
|
||||
fail(404, "not_found", "")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(f.snapshot(f.read()))
|
||||
})
|
||||
}
|
||||
|
||||
// serveFakeKun runs a Kun runtime for the data folder dir on a loopback
|
||||
// port, found as Kun's CLI finds it: runtime.json's baseUrl and token.
|
||||
func serveFakeKun(t *testing.T, dir string) *fakeKun {
|
||||
t.Helper()
|
||||
f := &fakeKun{dir: dir}
|
||||
f.write(f.read())
|
||||
token := "rt-" + t.Name()
|
||||
srv := httptest.NewServer(f.handler(token))
|
||||
t.Cleanup(srv.Close)
|
||||
b, _ := json.Marshal(map[string]any{"version": 2, "pid": os.Getpid(), "host": "127.0.0.1", "baseUrl": srv.URL, "runtimeToken": token, "insecure": false})
|
||||
os.WriteFile(filepath.Join(dir, "runtime.json"), b, 0o600)
|
||||
t.Setenv("KUN_DATA_DIR", dir)
|
||||
was := kunLive
|
||||
kunLive = kunConnect
|
||||
t.Cleanup(func() { kunLive = was })
|
||||
return f
|
||||
}
|
||||
|
||||
// runningKuns are the Kun runtimes every test but kun_test.go's own finds
|
||||
// running (main_test.go), one a data folder, served in the process: Kun
|
||||
// takes magpie only while it runs.
|
||||
var runningKuns = struct {
|
||||
sync.Mutex
|
||||
at map[string]*fakeKun
|
||||
}{at: map[string]*fakeKun{}}
|
||||
|
||||
func runningKun(dir string) *kunClient {
|
||||
runningKuns.Lock()
|
||||
f := runningKuns.at[dir]
|
||||
if f == nil {
|
||||
f = &fakeKun{dir: dir}
|
||||
runningKuns.at[dir] = f
|
||||
}
|
||||
runningKuns.Unlock()
|
||||
return &kunClient{http: &http.Client{Transport: handlerTransport{f.handler("")}}, base: "http://localhost"}
|
||||
}
|
||||
|
||||
func kunTestHome(t *testing.T) (home, dir string) {
|
||||
t.Helper()
|
||||
home, _ = museHome(t) // magpie with deepseek/pro and deepseek/flash
|
||||
t.Setenv("KUN_DATA_DIR", "")
|
||||
dir = filepath.Join(home, ".kun", "data")
|
||||
os.MkdirAll(dir, 0o700)
|
||||
return home, dir
|
||||
}
|
||||
|
||||
// Picking a magpie model for Kun adds magpie as a provider connection
|
||||
// through the running Kun's own admin API, as its Settings > Providers
|
||||
// does: an HTTP one at the gateway's /v1, spoken to as chat completions,
|
||||
// with Kun's own key, the models picked for Kun, and the pick as Kun's
|
||||
// default. Kun's default before is picked again when magpie steps out,
|
||||
// and the connection removed (zhongxingyuyes on X).
|
||||
func TestKunAddsMagpieAsAProvider(t *testing.T) {
|
||||
home, dir := kunTestHome(t)
|
||||
f := serveFakeKun(t, dir)
|
||||
f.add("deepseek", "https://api.deepseek.com", []string{"deepseek-chat", "deepseek-reasoner"}, true)
|
||||
a := kun(home)
|
||||
if a.Dir != dir || !a.Detected() {
|
||||
t.Fatalf("Kun at %s not found (%s)", dir, a.Dir)
|
||||
}
|
||||
fm := a.Field("model")
|
||||
if got := fm.Get(); got != "deepseek-chat" || a.Wired() {
|
||||
t.Fatalf("own: %q wired %v", got, a.Wired())
|
||||
}
|
||||
for range 2 { // twice: one connection, Kun's own default stashed once
|
||||
if err := fm.Set("magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if len(f.made) != 1 {
|
||||
t.Fatalf("made %d connections: %v", len(f.made), f.made)
|
||||
}
|
||||
c := f.made[0]
|
||||
for k, v := range map[string]any{"id": "magpie", "name": "magpie", "kind": "http", "authType": "api-key", "baseUrl": gatewayV1(), "endpointFormat": "chat_completions", "credential": agentKey("kun"), "selectedModel": "deepseek/pro", "probe": false, "select": true} {
|
||||
if c[k] != v {
|
||||
t.Errorf("connect %s = %v, want %v", k, c[k], v)
|
||||
}
|
||||
}
|
||||
if ms, _ := c["models"].([]any); !slices.Contains(ms, any("deepseek/pro")) {
|
||||
t.Errorf("models %v", c["models"])
|
||||
}
|
||||
if got := fm.Get(); got != "magpie/deepseek/pro" || !a.Wired() {
|
||||
t.Errorf("connected not read back: %q", got)
|
||||
}
|
||||
if msg := a.Check(); msg != "" {
|
||||
t.Errorf("Check: %s", msg)
|
||||
}
|
||||
// another of magpie's models is a select on the same connection
|
||||
if err := fm.Set("magpie/deepseek/flash"); err != nil || len(f.made) != 1 {
|
||||
t.Fatalf("second model: %v, %d made", err, len(f.made))
|
||||
}
|
||||
if got := fm.Get(); got != "magpie/deepseek/flash" {
|
||||
t.Errorf("second model read back as %q", got)
|
||||
}
|
||||
if err := a.Disconnect(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := f.read()
|
||||
if d.Profiles["magpie"] != nil || d.DefaultProviderID != "deepseek" || d.DefaultModel != "deepseek-chat" {
|
||||
t.Errorf("after disconnect: %+v", d)
|
||||
}
|
||||
if a.Wired() || unstashPeek(kunStash(dir, "id")) != "" || unstashPeek(kunStash(dir, "prev")) != "" {
|
||||
t.Error("still wired, or stashed, after disconnect")
|
||||
}
|
||||
}
|
||||
|
||||
// A Kun with no provider of its own: magpie's connection goes in and
|
||||
// comes out, and Kun is left as it was.
|
||||
func TestKunFromNothing(t *testing.T) {
|
||||
home, dir := kunTestHome(t)
|
||||
f := serveFakeKun(t, dir)
|
||||
a := kun(home)
|
||||
if _, err := a.ConnectHow(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !a.Wired() || len(f.made) != 1 {
|
||||
t.Fatalf("connect from nothing: wired %v, %d made", a.Wired(), len(f.made))
|
||||
}
|
||||
if err := a.Disconnect(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d := f.read(); len(d.Profiles) != 0 || d.DefaultProviderID != "" {
|
||||
t.Errorf("left %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A connection named magpie of the user's own takes magpie-2 for
|
||||
// magpie's, which is still magpie's (its id was stashed); one the user
|
||||
// made at the gateway by hand is magpie's too; the user's own elsewhere is
|
||||
// never touched.
|
||||
func TestKunKnowsItsConnection(t *testing.T) {
|
||||
home, dir := kunTestHome(t)
|
||||
f := serveFakeKun(t, dir)
|
||||
f.add("magpie", "https://example.com/v1", []string{"mine"}, true)
|
||||
a := kun(home)
|
||||
fm := a.Field("model")
|
||||
if err := fm.Set("magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := f.read()
|
||||
if d.Profiles["magpie-2"] == nil || d.DefaultProviderID != "magpie-2" || unstashPeek(kunStash(dir, "id")) != "magpie-2" {
|
||||
t.Fatalf("magpie's connection: %+v, stash %q", d, unstashPeek(kunStash(dir, "id")))
|
||||
}
|
||||
if !a.Wired() {
|
||||
t.Error("magpie-2 not read as magpie's")
|
||||
}
|
||||
if err := fm.Set(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d = f.read()
|
||||
if d.Profiles["magpie"] == nil || d.Profiles["magpie-2"] != nil || d.DefaultProviderID != "magpie" || d.DefaultModel != "mine" {
|
||||
t.Fatalf("after: %+v", d)
|
||||
}
|
||||
// one added by hand at the gateway
|
||||
f.add("gw", gatewayV1()+"/", []string{"deepseek/pro"}, true)
|
||||
if !a.Wired() {
|
||||
t.Fatal("a connection at the gateway added by hand isn't read as magpie's")
|
||||
}
|
||||
if err := fm.Set("magpie/deepseek/pro"); err != nil || len(f.made) != 1 {
|
||||
t.Errorf("connect over one added by hand: %v, %d made", err, len(f.made))
|
||||
}
|
||||
}
|
||||
|
||||
// The gateway on another port: the key goes with the address, so the
|
||||
// connection is made again there; one pointed at another machine stays.
|
||||
func TestKunFollowsTheGateway(t *testing.T) {
|
||||
home, dir := kunTestHome(t)
|
||||
f := serveFakeKun(t, dir)
|
||||
a := kun(home)
|
||||
if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:3426")
|
||||
if msg := a.Check(); !strings.Contains(msg, "baseUrl") {
|
||||
t.Errorf("Check on a moved gateway: %q", msg)
|
||||
}
|
||||
if err := a.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := f.read()
|
||||
p := d.Profiles[unstashPeek(kunStash(dir, "id"))]
|
||||
if len(d.Profiles) != 1 || p == nil || p["baseUrl"] != "http://127.0.0.1:3426/v1" || len(f.made) != 2 || d.DefaultModel != "deepseek/pro" {
|
||||
t.Fatalf("after the move: %+v (%d made)", d, len(f.made))
|
||||
}
|
||||
if f.creds[p["id"].(string)] != agentKey("kun") {
|
||||
t.Error("the key isn't the moved gateway's")
|
||||
}
|
||||
}
|
||||
|
||||
// Kun changes its connections only while it runs; the switch says to
|
||||
// start it rather than writing a registry Kun keeps its own way.
|
||||
func TestKunNeedsItRunning(t *testing.T) {
|
||||
home, dir := kunTestHome(t)
|
||||
t.Setenv("KUN_DATA_DIR", dir)
|
||||
was := kunLive
|
||||
kunLive = kunConnect
|
||||
t.Cleanup(func() { kunLive = was })
|
||||
// runtime.json left by a Kun that quit
|
||||
os.WriteFile(filepath.Join(dir, "runtime.json"), []byte(`{"version":2,"baseUrl":"http://127.0.0.1:1","runtimeToken":"x"}`), 0o600)
|
||||
a := kun(home)
|
||||
if err := a.Field("model").Set("magpie/deepseek/pro"); !errors.Is(err, errKunDown) {
|
||||
t.Errorf("connect with Kun stopped: %v", err)
|
||||
}
|
||||
if err := a.Field("model").Set(""); err != nil {
|
||||
t.Errorf("disconnect with nothing connected: %v", err)
|
||||
}
|
||||
if err := a.Sync(); err != nil {
|
||||
t.Errorf("Sync: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, kunRegistry)); err == nil {
|
||||
t.Error("registry written while Kun is stopped")
|
||||
}
|
||||
}
|
||||
|
||||
// A runtime.json naming another machine is never sent the token.
|
||||
func TestKunOnlyOnThisComputer(t *testing.T) {
|
||||
_, dir := kunTestHome(t)
|
||||
for base, ok := range map[string]bool{"http://127.0.0.1:18899": true, "http://localhost:1": true, "http://[::1]:2": true, "http://192.168.1.2:18899": false, "http://evil.example:80": false, "file:///x": false} {
|
||||
os.WriteFile(filepath.Join(dir, "runtime.json"), []byte(`{"baseUrl":"`+base+`","runtimeToken":"t"}`), 0o600)
|
||||
if got := kunAt(dir) != nil; got != ok {
|
||||
t.Errorf("%s: %v, want %v", base, got, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Kun's data folder is $KUN_DATA_DIR, else ~/.kun/data.
|
||||
func TestKunDataDir(t *testing.T) {
|
||||
home := syncHome(t)
|
||||
if d := kunDataDir(home); d != filepath.Join(home, ".kun", "data") {
|
||||
t.Errorf("default: %s", d)
|
||||
}
|
||||
other := filepath.Join(home, "elsewhere")
|
||||
t.Setenv("KUN_DATA_DIR", other)
|
||||
if d := kunDataDir(home); d != other {
|
||||
t.Errorf("KUN_DATA_DIR: %s", d)
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,9 @@ func TestMain(m *testing.M) {
|
||||
// in the test (runningAvibe), and the tests about Avibe serve their own
|
||||
// (avibe_test.go)
|
||||
avibeLive = runningAvibe
|
||||
// nor a Kun runtime this machine runs: each home's Kun runs in the
|
||||
// test (runningKun)
|
||||
kunLive = runningKun
|
||||
// nor which OpenCode this machine has: an OpenCode 2 on PATH turned
|
||||
// every OpenCode test's file into OpenCode 2's words; the tests about
|
||||
// it say their own (opencode_v2_test.go)
|
||||
|
||||
@@ -42,6 +42,7 @@ func syncHome(t *testing.T) string {
|
||||
t.Setenv("DS_BOT_SHELL_DATA", "")
|
||||
t.Setenv("OMB_DATA_DIR", "")
|
||||
t.Setenv("AVIBE_HOME", "")
|
||||
t.Setenv("KUN_DATA_DIR", "")
|
||||
t.Setenv("OMO_CODING_AGENT_DIR", "")
|
||||
t.Setenv("SENPI_CODING_AGENT_DIR", "")
|
||||
t.Setenv("PRIME_AGENT_CODING_AGENT_DIR", "")
|
||||
|
||||
@@ -82,6 +82,9 @@ var Vars = []string{
|
||||
"OMB_DATA_DIR",
|
||||
// Avibe's home (its config/config.json and its control socket), ~/.avibe without it
|
||||
"AVIBE_HOME",
|
||||
// Kun's data folder (its runtime.json and model-connections.v2.json),
|
||||
// ~/.kun/data without it
|
||||
"KUN_DATA_DIR",
|
||||
// AstrBot's root, the folder holding its data/ (else ~/.astrbot, the desktop app's)
|
||||
"ASTRBOT_ROOT",
|
||||
// jcode's folder, ~/.jcode without it
|
||||
|
||||
@@ -360,7 +360,7 @@ function toneCheck(img) {
|
||||
swap();
|
||||
}, { once: true });
|
||||
}
|
||||
const pngIcons = new Set(["crush", "zcode", "alma", "hanako", "cindy", "lody", "typesafe", "atomcode", "snow", "mlx-serve", "mothx", "zoo-code", "kimi-code-desktop", "openbot", "avibe"]);
|
||||
const pngIcons = new Set(["crush", "zcode", "alma", "hanako", "cindy", "lody", "typesafe", "atomcode", "snow", "mlx-serve", "mothx", "zoo-code", "kimi-code-desktop", "openbot", "avibe", "kun"]);
|
||||
|
||||
// lazy: a picture in a long list (Plugins' rows) is asked for near the
|
||||
// screen: each SVG an <img> draws is a ~0.6 MB webview document, kept (#909)
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.3 KiB |
@@ -51,6 +51,7 @@ var noLibrary = map[string]string{
|
||||
"obsidian": "not looked at (#5897)",
|
||||
"paimon": "not looked at (#5897)",
|
||||
"shelley": "not looked at (#5897)",
|
||||
"kun": "not looked at (#5897)",
|
||||
}
|
||||
|
||||
func TestEveryAgentInLibrary(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user