agent: LiveAgent, magpie's models in its model picker (xiaoxiaofei. on Discord)

xiaoxiaofei. asked for LiveAgent (Stack-Cairn/LiveAgent, v2). LiveAgent 2
is a Tauri app that runs its models through K-brain, a Go backend it
starts as `k-brain backend -data-dir <root>`; every provider lives in
<root>/config.json (JSONC, Pi's provider shape). Root: $LIVEAGENT_HOME,
else $K_BRAIN_HOME, else the folder ~/.liveagent/data-dir.json points to,
else ~/.liveagent, on every OS (LiveAgent's data_home.rs and
kbrain_backend.rs, K-brain's internal/config and internal/storage).

Connect adds providers.magpie: type claude_code + api anthropic-messages
(what LiveAgent's own settings write for an Anthropic-compatible
provider), baseUrl the gateway root (K-brain appends /v1 and posts
/messages with X-Api-Key), the key naming LiveAgent, activeModels null,
modelOrder in magpie's order, models sorted by id with display name,
window, output limit and input [text, image]. K-brain decodes with
unknown fields refused, so only its fields are written. A default or
compact model still K-brain's endpoint-less demo model1 becomes magpie's
first; the user's own pick stays. Through a sync the user's name, the
models they turned off, their order, K-brain's metadata and a model's
own displayName stay; a new model is on and last; nothing to change
writes nothing. A file K-brain wouldn't read as providers (not an
object, providers not an object, top-level models, a bare provider) is
left alone. Disconnect takes the entry out, puts picks back to K-brain's
default, gives a file left with no provider K-brain's demo back (its CLI
restores config.json.bak, which could hold magpie's, from a file with
none), and removes a file holding only what magpie made. LiveAgent's
backend holds the settings and writes them whole on any change, so a
change is refused while liveagent or k-brain runs (macOS/Linux; the
notice says to quit it first, in every language). Logo: the app's own
64px icon (src-tauri/icons/64x64.png, MIT) in an SVG.

Run on mote at this tree:
- gofmt -l clean; go vet ./internal/agent ./internal/agentenv for darwin,
  linux (nogui) and windows
- go test -tags nogui ./internal/agent -run 'LiveAgent|GatewayKey|ListsModels'
  ok; ./internal/agentenv ok; ./internal/gui: only TestCoreScriptBudget
  red, which is red on its base too (app.js untouched here; #5139)
- GUI icon-tile, i18n-keys, agent-notice-lang, gui-zh-tw, gui-ja, gui-de:
  Chromium 27/27, WebKit 27/27
Broken by hand on mote, each red: the user's activeModels not kept
(TestLiveAgentProvider "activeModels after sync [], want [...]"); the
demo provider not put back (TestLiveAgentMakesItsFile "emptied file");
the demo default not replaced (TestLiveAgentProvider, TestLiveAgentMakesItsFile).

Real use on mote (sandbox HOME and LIVEAGENT_HOME, this magpie on
127.0.0.1:3562, a fake Anthropic upstream on 3561, LiveAgent 2.0.5's
bundled k-brain from the release dmg):
- k-brain backend's first start wrote config.json as {}; magpie
  liveagent magpie then wrote providers.magpie and the default pick
- `k-brain run "Reply with exactly: pong"` (K-brain's CLI, same config
  and routing code) answered "pong"; the upstream saw POST /v1/messages
  from magpie
- the backend LiveAgent starts listed magpie's model in /v1/models with
  it as the default, and its /v1/text/generate answered "pong" through
  magpie
- with k-brain running, connect/disconnect were refused with the notice;
  after it quit, disconnect removed the file magpie made
Not tried: LiveAgent's window itself (its model picker was not opened;
the backend's API it reads was); LiveAgent on Linux or Windows; a real
vendor reply (fake upstream).
This commit is contained in:
yetone
2026-11-04 18:41:13 +08:00
parent 1a1ca0351b
commit c03dee7e3e
12 changed files with 996 additions and 3 deletions
+1 -1
View File
@@ -80,7 +80,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 · 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 · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot · QwenPaw · OpenClaw
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 · 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 · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · NewMax · LiveAgent · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot · QwenPaw · OpenClaw
</td></tr>
</table>
+1 -1
View File
@@ -80,7 +80,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 · 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 · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · NewMax · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot · QwenPaw · OpenClaw
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 · 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 · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · Grok App · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy · Pencil · OpenPencil · OpenBot · NewMax · LiveAgent · Raycast · Kiro Crew · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy · Lody · AionUi · Ante · AstrBot · QwenPaw · OpenClaw
</td></tr>
</table>
+1
View File
@@ -149,6 +149,7 @@ line; agents connected to magpie lose it when it quits.
| OpenPencil | `openpencil/settings.json` in the config folder: `~/Library/Application Support` (macOS), `$XDG_CONFIG_HOME` or `~/.config` (Linux), `%APPDATA%` (Windows) | provider (a `magpie` entry in its `builtin_agents`, magpie's models in its chat's model picker; the user's entries and settings kept; refused while OpenPencil runs, as it writes the file back when it quits) |
| OpenBot | `OpenBot/openbot-custom-providers-v1.json` in the app data folder: `~/Library/Application Support` (macOS), `%APPDATA%` (Windows), `$XDG_CONFIG_HOME` or `~/.config` (Linux) | provider (a keyless `magpie` endpoint, magpie's models in its model picker; the user's endpoints kept; OpenBot reads it at start, so restart it) |
| NewMax | `newmax.db` (SQLite, the row `app` of its `settings` table) in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` (every OS) | provider (a `magpie-gateway` entry in its `providers` and `providerOrder`, magpie's models in its model picker; the rest of the row kept byte for byte; refused while NewMax runs, as it writes its settings back whenever one changes) |
| LiveAgent | `config.json` (JSONC, K-brain's) in `$LIVEAGENT_HOME`, else `$K_BRAIN_HOME`, else the folder `~/.liveagent/data-dir.json` points to, else `~/.liveagent` (every OS) | provider (a `magpie` entry in its `providers`, Anthropic Messages at the gateway's root, magpie's models in its model picker; a default still K-brain's own demo model becomes magpie's first; refused while LiveAgent or its `k-brain` backend runs, as it writes its settings back whenever one changes) |
| 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) |
| 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) |
+2
View File
@@ -93,6 +93,7 @@ something else shows up as drift.
- OpenBot (nightly-labs/openbot, openbot.run; jiezhengj on Discord) keeps the OpenAI-compatible endpoints its model picker lists in `openbot-custom-providers-v1.json` in Electron's userData folder, app data joined with `OpenBot`: `~/Library/Application Support/OpenBot` on a Mac, `%APPDATA%\OpenBot` on Windows, `$XDG_CONFIG_HOME/OpenBot` or `~/.config/OpenBot` on Linux (`openBot` in [`openbot.go`](../../internal/agent/openbot.go); its `custom-provider-store.ts` and `opencode-config.ts`, v0.58.0). magpie adds one entry to `providers`, `id: magpie` at the gateway's `/v1` with `secret: null`: an entry's key and headers are one safeStorage ciphertext (the Keychain, DPAPI) that magpie doesn't open, so OpenBot hands the entry to OpenCode keyless, the gateway takes it as a request from this computer, and it counts as OpenCode's. OpenBot's list decoders fail closed (one entry or model it wouldn't take empties the list), so the models are the picked ones whose `magpie/<id>` OpenBot accepts (ASCII letters, digits and `._:/[],=-`, at most 160), at most 64, with a context window only inside 1,024 to 100,000,000. The user's other entries stay, and so do the `name`, `harness` and `secret` they give magpie's entry; a sync with nothing to change doesn't write. A file whose `version` isn't the number 1, or whose `providers` isn't a list, is one OpenBot itself refuses, so magpie leaves it alone. Disconnect takes the entry out, and the file when only the version and an empty list are left. OpenBot reads the file once at start and writes it whole only when an endpoint is saved, edited or removed there, so the notice (while it runs) says to restart it before doing that. The model is picked in OpenBot's picker (`ListsModels`). Detected by its userData folder, `OpenBot.app` (`app.openbot.desktop`), or `OpenBot.exe` under `%LOCALAPPDATA%\Programs` or `%ProgramFiles%`. Its MCP servers live in its SQLite database, which magpie doesn't write: magpie's `/mcp/magpie/…` servers are added there by hand as HTTP servers.
- Antigravity, Google's desktop app (not Antigravity IDE, `com.google.antigravity-ide`), takes a gateway from `~/.antigravity/settings.json` from 2.15 on: Google's Antigravity Enterprise Gateway (docs.cloud.google.com/gemini/enterprise/docs/ai-developer-tools/connect-enterprise-gateway; `antigravity` in [`antigravity.go`](../../internal/agent/antigravity.go), ryougi_hachi on X). magpie writes `gateway` as `{enabled: true, url: <gateway>, apiKey: <key naming Antigravity>, wireProtocol: openai}` and the model it starts on as `models.defaultModelId`, and takes out `models.list`, which would narrow the picker to the user's own. On the openai protocol the app's backend (2.28.2) asks `<url>/v1/models` for its picker, labelled by id (`NoNames`, `ListsModels`), and streams `<url>/v1/chat/completions` with the key as a bearer token and a User-Agent of `antigravity/hub/<version>`. The user's gateway, default model and list are stashed and put back on disconnect, or when a model of their own is picked; `caCertPath` and the rest of the file are never touched, and a `Sync` keeps what the user added to magpie's block (`customHeaders`). On a gateway the app uses no Google sign-in. An organisation's `admin_settings.json` and the `AGY_LLM_GATEWAY_*` variables win over the file, so `Check` says when either sets a gateway. agy reads the same file below its own settings: an agy connected on its own row keeps its route, one that isn't follows the app's gateway, as the notice says. `~/.antigravity` is Antigravity IDE's and agy's too, so the app is found by its bundle at 2.15 or later (`desktopApps`) or `~/.gemini/antigravity/agyhub_summaries_proto.pb`, which only its backend writes. The app reads the file at start, so the notice asks for a restart. The Antigravity accounts magpie signs in (provider `antigravity`) are a separate thing: those send magpie's requests to Google.
- NewMax (newmax.cc, an Electron app on the Claude Agent SDK) keeps its settings as JSON in the row `app` of the `settings` table of `newmax.db`, a SQLite database in WAL mode in `$NEWMAX_USER_DATA_DIR`, else `~/.newmax` on every system (`newMax` in [`newmax.go`](../../internal/agent/newmax.go); its main bundle's `configureAppDataPaths`, `loadPersistedAppSettings` and the renderer's `mergeProviders`, v1.1.22). magpie adds one entry to `providers` in the shape NewMax's own import writes, `id: magpie-gateway` (its own preset is `magpie`, its import's ids hold `%3A`), `apiFormat: anthropic` at the gateway's root (NewMax appends `/v1/messages`) with `ANTHROPIC_AUTH_TOKEN` and a key naming NewMax, at most 20 models (`MAX_MODELS`) as `models` and `enabledModels` with their context windows, and its id at the end of `providerOrder`. The row is edited in place in one immediate transaction, so every other byte stays; the user's `name` and `enabled` for magpie's entry and the fields NewMax adds to it stay through a sync, and a sync with nothing to change doesn't write. A row that isn't a JSON object, or whose `providers` or `providerOrder` isn't a list, is left alone. With no row (NewMax at its defaults), magpie writes one with its entry alone, as NewMax lays its defaults and presets under the row; with no database yet, it asks to open NewMax once. Disconnect takes the entry and the id out, sets a pick of it back to `default`, and takes the row out when only what magpie made is left. NewMax holds its settings in memory and writes the whole row back whenever one changes, so a change is refused while `NewMax` (`newmax` on Linux) runs (Windows can't be asked, so the notice says to quit it first). The model is picked in NewMax's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder or `NewMax.app` (`cc.newmax.desktop`).
- LiveAgent (Stack-Cairn/LiveAgent v2, a Tauri app) runs its models through K-brain, a Go backend it starts with its data folder, which keeps every provider in `config.json` there: `$LIVEAGENT_HOME`, else `$K_BRAIN_HOME`, else the folder `~/.liveagent/data-dir.json` points to (`{"path": …}`, set when the user moves LiveAgent's data), else `~/.liveagent` on every system (`liveAgent` in [`liveagent.go`](../../internal/agent/liveagent.go); LiveAgent's `data_home.rs` and `kbrain_backend.rs`, K-brain v0.107.12's `internal/config`). The file is JSONC in Pi's provider shape, decoded with unknown fields refused, so magpie writes only K-brain's fields: one entry `providers.magpie`, `type: claude_code` and `api: anthropic-messages` as LiveAgent's own settings write an Anthropic-compatible provider, `baseUrl` the gateway's root (K-brain appends `/v1` and posts to `/messages` with `X-Api-Key`), a key naming LiveAgent, `activeModels: null` (every model on), magpie's order as `modelOrder`, and `models` sorted by id as K-brain writes them, with each one's display name, context window, output limit and `input: [text, image]` when it takes images. Comments and every other key stay. Through a sync the user's name for the entry, the models they turned off (`activeModels`), their order and the fields K-brain adds (its `metadata`) stay; a model new to magpie's list is on and goes last, and a sync with nothing to change doesn't write. A default (or compact) model still K-brain's own, `model1` of its endpoint-less `demo` provider, becomes magpie's first; one the user picked stays. A file K-brain wouldn't read as providers (not an object, `providers` not an object, a top-level `models`, one provider written bare) is left alone. Disconnect takes the entry out and a pick of it back to K-brain's default; a file left with no provider gets K-brain's `demo` back, since K-brain takes one with none as written over and restores `config.json.bak`, which can still hold magpie's; a file with nothing but what magpie made goes. LiveAgent's backend makes the file as `{}` when there is none (so a disconnect that takes the file away is undone the next start, harmlessly), reads it when it starts and writes it whole whenever a setting changes, so a change is refused while `liveagent` or `k-brain` runs (Windows can't be asked, so the notice says to quit it first). A model id another provider of the user's lists too has its metadata shared by K-brain, so a sync may write that model's limits back each time. The model is picked in LiveAgent's model picker, so the field is whether magpie is in it (`ListsModels`). Detected by its data folder, `LiveAgent.app` (`com.xiaofei.liveagent`) or its Windows install. Its logo is the app's own 64px icon (`src-tauri/icons/64x64.png`, MIT) in an SVG.
- DevEco Code (Huawei's OpenCode fork, #1885) is wired as OpenCode is (`deveco` in [`agents.go`](../../internal/agent/agents.go)): magpie's provider goes into the first of `deveco.jsonc`, `deveco.json` and `config.json` in `~/.config/deveco` (the one DevEco merges last, so the one that wins), or in `$DEVECO_CONFIG_DIR` when that is absolute, read after them. 0.2.3 sends `deveco/0.2.3 ai-sdk/…` to a provider of its config, but much of the OpenCode code it keeps still sends OpenCode's own User-Agent (`opencode/<version>`), so its provider's key is `magpie-deveco` (`openCodeKeyAt`), not the plain `magpie` OpenCode and MiMo Code send, and Check asks for that key. Its npm package has no Linux binary, so no install command is offered there (`cliSpec.only`).
- Grok Build keeps magpie's models as one `[model."magpie/<provider>/<model>"]` table each in `config.toml` under `$GROK_HOME`, else `~/.grok` (`grok` in [`grok.go`](../../internal/agent/grok.go)), each on the gateway's `/v1` with magpie's key. Grok Build takes `api_backend` per model table, `"chat_completions"` (its default), `"responses"` or `"messages"` (Anthropic Messages), and sends each to `base_url` joined with `/chat/completions`, `/responses` or `/messages` (the "Supported API Backends" page bundled in its binary; grok 1.0.67). magpie writes each model's native API (`grokBackend`, from `catalog.Model.APIs` as Pi, droid and dsh pick theirs; uk.jent on Discord), so the gateway relays the request as it is: Responses for a model served best there, Messages for a Claude on an Anthropic endpoint, Chat for the rest, a group whose members differ, or one not known. Each table's `context_window` "drives auto-compact timing" (Grok Build's config reference), so it is where Long conversations has Codex compact (`grokWindow`, codexcat's rule): a threshold set on the model or its provider, else `settings.Working` of the model's window, the whole window under Full window; Long conversations is in Grok Build's sheet on the Agents page (`AGENT_PREFS`). A `context_window` the user set in one of magpie's tables by hand stays through a sync and a new pick (uk.jent on Discord: dozens of 1M models set to 300K one by one): what magpie last gave each model is stashed (`grok:<path>:windows`), and a value other than it is the user's (`grokOwnWindow`). With no record yet (a config an older magpie wrote, which gave every model its whole window), a value other than the model's whole window and other than magpie's now is taken for the user's. Disconnect drops the record with the tables. `TestGrokKeepsAWindowSetByHand`, `TestGrokKeepsAWindowSetBeforeTheRecord`, `TestGrokWindowFollowsLongConversations`.
- Droid keeps magpie's models as `customModels` entries in `~/.factory/settings.json` (`droidIn` in [`droid.go`](../../internal/agent/droid.go)), each with `provider` `openai` (Responses, `baseUrl` the gateway's `/v1`), `anthropic` (the gateway root) or `generic-chat-completion-api` (Chat, `/v1`). droid reads a custom model's `model` itself and, at every session start, warns about one whose name looks like OpenAI's (`/\bgpt[-_.]?\d/i`, `/codex/i`, `/\bo[1-9](?:[-_.]|$)/i`) on any provider but `openai`, or like a Claude (`/claude|haiku|sonnet|opus/i`) on neither `anthropic` nor `bedrock-converse` (droid 0.231.0's bundle, `xs` and `g2`; ji233 on Discord: `ultrafast/gpt-6.1-sol` on Chat). So `droidWants` puts such a model on the provider droid asks for, whatever its provider speaks, and the gateway translates; any other model goes on its `APIs`, as Pi, omp and dsh pick theirs. A `provider`, `displayName`, `maxContextLimit`, `maxOutputTokens` or `noImageSupport` the user changed in one of magpie's entries stays through a sync and a new pick (`droidMerge`): what magpie last gave each entry is stashed (`droid:<path>:wrote`), and a value other than it is the user's; keys magpie doesn't write stay too, droid's `index` aside. `baseUrl` follows the entry's provider and `apiKey` is the wiring, both put back at every sync. With no record (entries an older magpie wrote, which every sync wrote over anyway), magpie's values are taken. Disconnect drops the record with the entries. `TestDroidWantsItsOwnRule`, `TestDroidProviderByName`, `TestDroidKeepsAnEntryEditedByHand`.
@@ -203,6 +204,7 @@ go test -tags nogui ./internal/agent -run '^TestOpenPencil'
go test -tags nogui ./internal/agent -run '^TestOpenBot'
go test -tags nogui ./internal/agent -run '^TestAntigravity'
go test -tags nogui ./internal/agent -run '^TestNewMax'
go test -tags nogui ./internal/agent -run '^TestLiveAgent'
go test -tags nogui ./internal/agent -run '^TestGrokApp'
go test -tags nogui ./internal/agent -run 'ClaudeScience'
go test -tags nogui ./internal/gateway -run 'TestClaudeScience'
+1
View File
@@ -290,6 +290,7 @@ func onMachine(home, cfg string) []*Agent {
openPencil(home, cfg),
openBot(home, cfg),
newMax(home),
liveAgent(home),
raycast(home),
kiroCrew(home),
t3code(home),
+1
View File
@@ -225,6 +225,7 @@ func TestPinnedGatewayKeyForEveryWriter(t *testing.T) {
"copilotjb": jbKey,
"cursor": cursorLocalEnv(gw)[cursorLocalVars[1]],
"hanako": hanakoProvider().APIKey,
"liveagent": liveAgentEntryFor(gw).APIKey,
"newmax": newMaxEntryFor(gw).APIKey,
"openclaw": openClawProviderAt(gw)["apiKey"],
"openpencil": openPencilEntry(gw).APIKey,
+1 -1
View File
@@ -61,7 +61,7 @@ func TestEveryPickerOfMagpiesModelsCanBeNarrowed(t *testing.T) {
if len(bare) > 0 {
t.Errorf("magpie's models are put in these agents' pickers with no way to pick which: %v", bare)
}
for _, id := range []string{"zcode", "pencil", "openpencil", "openbot", "newmax", "t3code", "workbuddy", "workbuddy-ai", copilotJBID, CursorLocalID} {
for _, id := range []string{"zcode", "pencil", "openpencil", "openbot", "newmax", "liveagent", "t3code", "workbuddy", "workbuddy-ai", copilotJBID, CursorLocalID} {
if !slices.Contains(menus, id) {
t.Errorf("%s's row has no model list to pick in (ListsModels): %v", id, menus)
}
+518
View File
@@ -0,0 +1,518 @@
package agent
// LiveAgent (Stack-Cairn/LiveAgent, a Tauri app; xiaoxiaofei. on Discord)
// is a desktop agent whose v2 runs its model calls through K-brain, a Go
// backend it starts as `k-brain backend -data-dir <root>`. K-brain keeps
// every provider in one config.json in that root (LiveAgent's
// kbrain_backend.rs ensure_started, data_home.rs; K-brain v0.107.12's
// internal/config): $LIVEAGENT_HOME, else $K_BRAIN_HOME, else the folder
// ~/.liveagent/data-dir.json points to ({"path": <absolute folder>}, set
// when the user moves LiveAgent's data in its settings), else ~/.liveagent,
// on every system. The file is JSONC, Pi's provider shape:
//
// // k-brain configuration — JSONC: comments and trailing commas are allowed.
// {"defaultModel":"…", "defaultProvider":"…", …,
// "providers":{…, "magpie":{"name":"magpie","type":"claude_code",
// "baseUrl":"http://127.0.0.1:3425","api":"anthropic-messages",
// "apiKey":"magpie-liveagent","activeModels":null,
// "modelOrder":["<model>",…],
// "models":[{"id":"<model>","displayName":"…","input":["text","image"],
// "contextWindow":200000,"maxTokens":64000},…]}}}
//
// type claude_code with api anthropic-messages is what LiveAgent's own
// settings write for an Anthropic-compatible provider
// (providerSettings.ts); K-brain appends /v1 to a baseUrl that doesn't end
// in a version and posts to /messages with X-Api-Key, so baseUrl is the
// gateway's root. activeModels null is every model active
// (Provider.ModelActive). K-brain decodes the file with unknown fields
// refused, so magpie writes only fields it knows. A file K-brain wouldn't
// read as providers (a top-level models, or one provider written bare at
// the top) is left alone.
//
// The backend makes the file as {} when there is none, reads it once, when
// it starts (storage.OpenLocal), and writes the whole of it back from what
// it holds whenever a setting changes (Config.SaveFile), so a
// change magpie makes while it runs is lost: magpie refuses one then,
// where it can tell (Running can't on Windows, where the notice says so).
// The model is picked in LiveAgent's model picker, so the field is whether
// magpie's models are in it (ListsModels). The user's name for magpie's
// entry, the models they turned off in it, their order of them and the
// fields K-brain adds (metadata) stay through a sync, and a sync with
// nothing to change doesn't write.
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"slices"
"sort"
"strings"
"github.com/tidwall/gjson"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
)
// liveAgentApp is LiveAgent's macOS bundle (tauri.conf.json's identifier).
var liveAgentApp = desktopApp{id: "com.xiaofei.liveagent", names: []string{"LiveAgent.app"}}
// liveAgentProc is LiveAgent's processes: the app (CFBundleExecutable
// liveagent, the Linux and Windows binary's name too) and the k-brain
// backend it starts, which holds the settings. The program itself, the
// first word of its command line, or an executable in the .app wherever
// the bundle is.
var liveAgentProc = []string{`^([^ ]*/)?(liveagent|k-brain)( |$)`, `LiveAgent\.app/Contents/MacOS/(liveagent|k-brain)( |$)`}
var noticeLiveAgent = newNotice("LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.")
// errLiveAgentRunning is a change refused while LiveAgent runs.
var errLiveAgentRunning = errors.New("LiveAgent writes its settings back over what magpie writes now: quit LiveAgent, then try again")
// liveAgentDemo is the provider K-brain's CLI writes in a config it makes
// (config.Default), with no endpoint, and its models.
const liveAgentDemo = "demo"
const liveAgentDemoModel = "model1"
func liveAgent(home string) *Agent {
dir := liveAgentDir(home)
path := filepath.Join(dir, "config.json")
write := func(on bool) error {
if !on {
return liveAgentUnwire(path)
}
return liveAgentWire(path, liveAgentEntryFor(gateway.URL()))
}
return atomic(&Agent{
ID: "liveagent", Name: "LiveAgent", Icon: "liveagent-color", Aliases: []string{"live-agent", "k-brain", "kbrain"},
Dir: dir, Path: path,
detect: func() bool {
return isDir(dir) || isDir(filepath.Join(home, ".liveagent")) || macBundle(liveAgentApp) || liveAgentWindowsApp()
},
Notice: func() string {
if liveAgentWired(path) && Running(liveAgentProc...) {
return noticeLiveAgent.String()
}
return ""
},
// a sync while it runs is written as well: its next save puts back
// what it holds, and the next sync magpie's models
Sync: func() error {
if !liveAgentWired(path) {
return nil
}
return write(true)
},
ListsModels: true,
Fields: []Field{{
Key: "provider", Label: "provider",
Get: func() string {
if liveAgentWired(path) {
return magpieID
}
return ""
},
Set: func(v string) error {
if liveAgentRunning() {
return errLiveAgentRunning
}
return write(v != "")
},
Options: func(map[string]string) []Option {
return []Option{{Value: magpieID, Label: "magpie", Icon: "magpie", Note: "every magpie model in LiveAgent's model picker"}}
},
}},
}, path)
}
// liveAgentRunning says LiveAgent is open where magpie can tell; on
// Windows, where Running can't, no, and the notice asks to quit it first.
var liveAgentRunning = func() bool {
return runtime.GOOS != "windows" && Running(liveAgentProc...)
}
// liveAgentDir is the folder of K-brain's config.json as LiveAgent hands it
// over: $LIVEAGENT_HOME, else $K_BRAIN_HOME (each only an absolute path,
// here), else the folder ~/.liveagent/data-dir.json points to, else
// ~/.liveagent.
func liveAgentDir(home string) string {
for _, v := range []string{"LIVEAGENT_HOME", "K_BRAIN_HOME"} {
if d := strings.TrimSpace(appdir.Getenv(v)); d != "" && filepath.IsAbs(d) {
return d
}
}
def := filepath.Join(home, ".liveagent")
if b, err := os.ReadFile(filepath.Join(def, "data-dir.json")); err == nil {
var p struct {
Path string `json:"path"`
}
if json.Unmarshal(b, &p) == nil && filepath.IsAbs(p.Path) && filepath.Clean(p.Path) != filepath.Clean(def) {
return p.Path
}
}
return def
}
// liveAgentWindowsApp says LiveAgent's installer has put it where it
// installs it: per user under %LOCALAPPDATA%\LiveAgent, or for everyone
// under %ProgramFiles%\LiveAgent.
func liveAgentWindowsApp() bool {
if runtime.GOOS != "windows" {
return false
}
for _, v := range []string{"LOCALAPPDATA", "ProgramW6432", "ProgramFiles"} {
if d := appdir.Getenv(v); d != "" && isFile(filepath.Join(d, "LiveAgent", "liveagent.exe")) {
return true
}
}
return false
}
// liveAgentModel is one of magpie's models as K-brain writes one (PiModel).
type liveAgentModel struct {
ID string `json:"id"`
DisplayName string `json:"displayName,omitempty"`
Input []string `json:"input,omitempty"`
ContextWindow int `json:"contextWindow,omitempty"`
MaxTokens int `json:"maxTokens,omitempty"`
}
// liveAgentEntry is magpie's provider, in the order K-brain writes one.
type liveAgentEntry struct {
Name string `json:"name"`
Type string `json:"type"`
BaseURL string `json:"baseUrl"`
API string `json:"api"`
APIKey string `json:"apiKey"`
ActiveModels []string `json:"activeModels"`
ModelOrder []string `json:"modelOrder,omitempty"`
Models []liveAgentModel `json:"models"`
}
// liveAgentEntryFor is magpie's provider for a gateway at gw: its
// Anthropic Messages at the root, the key that names LiveAgent, and the
// models picked for it, each once, sorted by id as K-brain writes them,
// and in magpie's order as modelOrder.
func liveAgentEntryFor(gw string) liveAgentEntry {
e := liveAgentEntry{Name: "magpie", Type: "claude_code", BaseURL: gw, API: "anthropic-messages",
APIKey: agentKeyAt("liveagent", gw), Models: []liveAgentModel{}}
seen := map[string]bool{}
for _, m := range sharedModels("liveagent") {
if strings.TrimSpace(m.ID) == "" || seen[m.ID] {
continue
}
seen[m.ID] = true
lm := liveAgentModel{ID: m.ID, ContextWindow: max(m.Context, 0), MaxTokens: max(m.Output, 0)}
if m.Name != "" && m.Name != m.ID {
lm.DisplayName = m.Name
}
if m.Images {
lm.Input = []string{"text", "image"}
}
e.Models = append(e.Models, lm)
e.ModelOrder = append(e.ModelOrder, m.ID)
}
sort.SliceStable(e.Models, func(i, j int) bool { return e.Models[i].ID < e.Models[j].ID })
return e
}
// liveAgentRead is config.json without its comments and trailing commas,
// the object it holds, and an error for one K-brain wouldn't read as its
// providers: not an object, providers not an object, a top-level models,
// or one provider written bare. A file that isn't there, or holds nothing,
// is nil.
func liveAgentRead(path string) ([]byte, map[string]json.RawMessage, error) {
b, err := edit.Read(path)
if err != nil {
return nil, nil, err
}
if len(bytes.TrimSpace(b)) == 0 {
return nil, nil, nil
}
b = jsonc.ToJSON(bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")))
var root map[string]json.RawMessage
if !json.Valid(b) || json.Unmarshal(b, &root) != nil || root == nil {
return nil, nil, fmt.Errorf("%s isn't a JSON object K-brain reads, so magpie leaves it alone", path)
}
if _, ok := root["models"]; ok {
return nil, nil, fmt.Errorf("%s has a top-level models, which K-brain refuses, so magpie leaves it alone", path)
}
p, ok := root["providers"]
if !ok {
for _, k := range []string{"name", "api", "baseUrl", "apiKey"} {
if _, bare := root[k]; bare {
return nil, nil, fmt.Errorf("%s is one provider written bare, so magpie leaves it alone", path)
}
}
} else if r := gjson.ParseBytes(p); r.Type != gjson.Null && !r.IsObject() {
return nil, nil, fmt.Errorf("%s: providers is not an object, so magpie leaves it alone", path)
}
return b, root, nil
}
// liveAgentWired says config.json has magpie's provider.
func liveAgentWired(path string) bool {
b, _, err := liveAgentRead(path)
return err == nil && gjson.GetBytes(b, "providers.magpie").IsObject()
}
// liveAgentWire puts magpie's provider into config.json, the file made
// when there is none. One there already keeps its name, the fields K-brain
// adds, each model's other fields, the models the user turned off and
// their order; a model new to magpie's list is turned on and goes last.
// A default model still K-brain's own (model1 of its empty demo provider,
// which has no endpoint to call) becomes magpie's first.
func liveAgentWire(path string, want liveAgentEntry) error {
b, _, err := liveAgentRead(path)
if err != nil {
return err
}
old := gjson.GetBytes(b, "providers.magpie")
var entry []byte
if !old.IsObject() {
entry, err = json.Marshal(want)
if err != nil {
return err
}
} else {
entry, err = liveAgentMerge([]byte(old.Raw), want)
if err != nil {
return err
}
if jsonEqual([]byte(old.Raw), entry) {
entry = nil
}
}
var set []edit.KV
if entry != nil {
set = append(set, edit.KV{Path: "providers.magpie", Value: json.RawMessage(entry)})
}
if len(want.ModelOrder) > 0 && liveAgentDefaultUnset(b, "defaultModel", "defaultProvider") {
set = append(set, edit.KV{Path: "defaultModel", Value: want.ModelOrder[0]}, edit.KV{Path: "defaultProvider", Value: "magpie"})
}
if len(want.ModelOrder) > 0 && b != nil && liveAgentDefaultUnset(b, "compactModel", "compactProvider") &&
gjson.GetBytes(b, "compactModel").Exists() {
set = append(set, edit.KV{Path: "compactModel", Value: want.ModelOrder[0]}, edit.KV{Path: "compactProvider", Value: "magpie"})
}
if len(set) == 0 {
return nil
}
return edit.SetJSON(path, set...)
}
// liveAgentMerge is magpie's entry want laid over the one config.json has.
func liveAgentMerge(old []byte, want liveAgentEntry) ([]byte, error) {
oldModels := map[string][]byte{}
var known []string
for _, m := range gjson.GetBytes(old, "models").Array() {
if id := m.Get("id").String(); id != "" {
oldModels[id] = []byte(m.Raw)
known = append(known, id)
}
}
ids := map[string]bool{}
var models []json.RawMessage
for _, m := range want.Models {
ids[m.ID] = true
w, err := json.Marshal(m)
if err != nil {
return nil, err
}
o, had := oldModels[m.ID]
if !had {
models = append(models, w)
continue
}
var set []jsonKV
gjson.ParseBytes(w).ForEach(func(k, v gjson.Result) bool {
// a name the user gave it in LiveAgent stays
if k.String() == "displayName" && gjson.GetBytes(o, "displayName").Exists() {
return true
}
set = append(set, jsonKV{k.String(), []byte(v.Raw)})
return true
})
models = append(models, jsonSetKeys(o, set))
}
if models == nil {
models = []json.RawMessage{}
}
set := []jsonKV{
{"type", rawJSON(want.Type)}, {"baseUrl", rawJSON(want.BaseURL)}, {"api", rawJSON(want.API)},
{"apiKey", rawJSON(want.APIKey)}, {"models", joinRaw(models)},
}
// the models the user turned off stay off, a new one is on
if a := gjson.GetBytes(old, "activeModels"); a.IsArray() {
var active []string
for _, id := range a.Array() {
if ids[id.String()] {
active = append(active, id.String())
}
}
for _, m := range want.Models {
if !slices.Contains(known, m.ID) && !slices.Contains(active, m.ID) {
active = append(active, m.ID)
}
}
if active == nil {
active = []string{}
}
set = append(set, jsonKV{"activeModels", rawJSON(active)})
} else {
set = append(set, jsonKV{"activeModels", []byte("null")})
}
// the user's order stays, a new model goes last
order := want.ModelOrder
if o := gjson.GetBytes(old, "modelOrder"); o.IsArray() {
var kept []string
for _, id := range o.Array() {
if ids[id.String()] && !slices.Contains(kept, id.String()) {
kept = append(kept, id.String())
}
}
for _, id := range want.ModelOrder {
if !slices.Contains(kept, id) {
kept = append(kept, id)
}
}
order = kept
}
if len(order) > 0 {
set = append(set, jsonKV{"modelOrder", rawJSON(order)})
}
if !gjson.GetBytes(old, "name").Exists() {
set = append(set, jsonKV{"name", rawJSON(want.Name)})
}
return jsonSetKeys(old, set), nil
}
// liveAgentDefaultUnset says the pick at the keys model and prov is none,
// or still K-brain's own: model1 of its demo provider, which has no
// endpoint, with no other provider listing a model1.
func liveAgentDefaultUnset(b []byte, model, prov string) bool {
if b == nil {
return true
}
m, p := gjson.GetBytes(b, model).String(), gjson.GetBytes(b, prov).String()
if p != "" && p != liveAgentDemo {
return false
}
if m == "" {
return p == ""
}
if m != liveAgentDemoModel {
return false
}
ok := true
gjson.GetBytes(b, "providers").ForEach(func(k, v gjson.Result) bool {
if k.String() == liveAgentDemo {
if strings.TrimSpace(v.Get("baseUrl").String()) != "" {
ok = false
}
return true
}
for _, x := range v.Get("models").Array() {
if x.Get("id").String() == liveAgentDemoModel {
ok = false
}
}
return true
})
return ok
}
// liveAgentUnwire takes magpie's provider out of config.json and every
// pick of it back to K-brain's default; the file goes when only what
// magpie made is left. A file left with no provider gets K-brain's own
// demo one back, since K-brain reads one with none as written over and
// restores its config.json.bak, which can still hold magpie's.
func liveAgentUnwire(path string) error {
b, root, err := liveAgentRead(path)
if err != nil || !gjson.GetBytes(b, "providers.magpie").Exists() {
return err
}
var magpieOnly = map[string]bool{}
for _, m := range gjson.GetBytes(b, "providers.magpie.models").Array() {
magpieOnly[m.Get("id").String()] = true
}
left := 0
// K-brain's demo provider still there, with its model1
demo := gjson.GetBytes(b, "providers."+liveAgentDemo+".models.#(id=="+liveAgentDemoModel+")").Exists()
gjson.GetBytes(b, "providers").ForEach(func(k, v gjson.Result) bool {
if k.String() == "magpie" {
return true
}
left++
for _, m := range v.Get("models").Array() {
delete(magpieOnly, m.Get("id").String())
}
return true
})
// the file magpie made: its provider and its picks
rest := 0
for k := range root {
switch k {
case "providers", "defaultModel", "defaultProvider":
default:
rest++
}
}
if left == 0 && rest == 0 {
return os.Remove(path)
}
del := []string{"providers.magpie"}
var set []edit.KV
for _, pick := range [][2]string{{"defaultModel", "defaultProvider"}, {"compactModel", "compactProvider"}, {"taskModel", "taskProvider"}} {
m, p := gjson.GetBytes(b, pick[0]).String(), gjson.GetBytes(b, pick[1]).String()
if p != "magpie" && (p != "" || !magpieOnly[m]) {
continue
}
if p != "" {
del = append(del, pick[1])
}
// K-brain's own default and compact model are its demo's model1
switch {
case pick[0] != "taskModel" && (left == 0 || demo):
set = append(set, edit.KV{Path: pick[0], Value: liveAgentDemoModel})
case pick[0] == "defaultModel":
// K-brain picks the first model of its providers
set = append(set, edit.KV{Path: pick[0], Value: ""})
default:
del = append(del, pick[0])
}
}
if left == 0 {
set = append(set, edit.KV{Path: "providers." + liveAgentDemo, Value: json.RawMessage(liveAgentDemoProvider)})
}
raw, err := os.ReadFile(path)
if err != nil {
return err
}
out, err := edit.PatchJSON(raw, set, del)
if err != nil {
return err
}
return edit.WriteAtomic(path, out)
}
// liveAgentDemoProvider is K-brain's demo provider as its Save writes
// config.Default's.
const liveAgentDemoProvider = `{"name":"demo","baseUrl":"","api":"openai-completions","apiKey":"","activeModels":null,"models":[{"id":"model1","contextWindow":128000,"maxTokens":8192},{"id":"model2","contextWindow":128000,"maxTokens":8192}]}`
func rawJSON(v any) []byte {
b, _ := json.Marshal(v)
return b
}
// jsonEqual says two JSON texts hold the same value.
func jsonEqual(a, b []byte) bool {
var y any
return json.Unmarshal(b, &y) == nil && sameJSON(string(a), y)
}
+461
View File
@@ -0,0 +1,461 @@
package agent
import (
"encoding/json"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/tidwall/jsonc"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
)
// liveAgentDefault is config.json as K-brain's CLI writes config.Default
// (marshalConfig: its header, then MarshalIndent with two spaces).
const liveAgentDefault = `// k-brain configuration — JSONC: comments and trailing commas are allowed.
// providers use Pi's provider shape: name, api, models, baseUrl, and apiKey.
// defaultModel/defaultProvider pick a configured model route.
{
"language": "en",
"defaultModel": "model1",
"compactModel": "model1",
"providers": {
"demo": {
"name": "demo",
"baseUrl": "",
"api": "openai-completions",
"apiKey": "",
"activeModels": null,
"models": [
{
"id": "model1",
"contextWindow": 128000,
"maxTokens": 8192
},
{
"id": "model2",
"contextWindow": 128000,
"maxTokens": 8192
}
]
}
}
}
`
// liveAgentSetup is a sandbox HOME with LiveAgent's root at
// ~/.liveagent, two models from a provider of the user's, and LiveAgent
// not running.
func liveAgentSetup(t *testing.T) (string, *Agent, []string) {
t.Helper()
home := syncHome(t)
t.Setenv("LIVEAGENT_HOME", "")
t.Setenv("K_BRAIN_HOME", "")
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)
}
t.Cleanup(func() { liveAgentRunning = func() bool { return false } })
liveAgentRunning = func() bool { return false }
a := liveAgent(home)
var want []string
for _, m := range magpieModels("liveagent") {
want = append(want, m.ID)
}
if len(want) < 2 {
t.Fatalf("models %v", want)
}
return home, a, want
}
func liveAgentFile(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return string(b)
}
func liveAgentWrite(t *testing.T, path, s string) {
t.Helper()
os.MkdirAll(filepath.Dir(path), 0o755)
if err := os.WriteFile(path, []byte(s), 0o600); err != nil {
t.Fatal(err)
}
}
// liveAgentJSON is the file as K-brain's parseConfigJSONC reads it: its
// comments gone, and an error for anything that isn't an object.
func liveAgentJSON(t *testing.T, s string) gjson.Result {
t.Helper()
b := jsonc.ToJSON([]byte(s))
var root map[string]json.RawMessage
if err := json.Unmarshal(b, &root); err != nil || root == nil {
t.Fatalf("not a JSON object K-brain reads: %v\n%s", err, s)
}
return gjson.ParseBytes(b)
}
func liveAgentIDs(r gjson.Result) []string {
var ids []string
for _, v := range r.Array() {
if v.Type == gjson.String {
ids = append(ids, v.String())
} else {
ids = append(ids, v.Get("id").String())
}
}
return ids
}
// LiveAgent v2 lists the providers of K-brain's config.json in its model
// picker. magpie adds itself as "magpie" on the gateway's Anthropic
// Messages with the key naming LiveAgent, makes magpie's first model the
// pick when the pick is still K-brain's empty demo, keeps the rest of the
// file, writes nothing when nothing changed, keeps the user's name, models
// turned off, order and K-brain's fields through a sync, and off gives
// back the file it found.
func TestLiveAgentProvider(t *testing.T) {
home, a, want := liveAgentSetup(t)
if !slices.ContainsFunc(All(), func(x *Agent) bool { return x.ID == "liveagent" && x.Name == "LiveAgent" }) {
t.Fatal("LiveAgent is not among the agents")
}
if a.Path != filepath.Join(home, ".liveagent", "config.json") {
t.Fatalf("path %s", a.Path)
}
if a.Detected() {
t.Fatal("found with nothing there")
}
liveAgentWrite(t, a.Path, liveAgentDefault)
if !a.Detected() {
t.Fatal("not found with its data folder")
}
f := a.Field("provider")
if f.Get() != "" {
t.Fatalf("get: %q", f.Get())
}
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
if f.Get() != magpieID {
t.Fatalf("get after set: %q", f.Get())
}
gw := gateway.URL()
got := liveAgentFile(t, a.Path)
if !strings.HasPrefix(got, liveAgentDefault[:strings.Index(liveAgentDefault, "{")]) {
t.Errorf("K-brain's header comments lost:\n%s", got)
}
r := liveAgentJSON(t, got)
e := r.Get("providers.magpie")
if e.Get("name").String() != "magpie" || e.Get("type").String() != "claude_code" || e.Get("api").String() != "anthropic-messages" ||
e.Get("baseUrl").String() != gw || strings.HasSuffix(gw, "/v1") || e.Get("apiKey").String() != agentKeyAt("liveagent", gw) ||
e.Get("activeModels").Type != gjson.Null || !e.Get("activeModels").Exists() {
t.Errorf("entry: %s", e.Raw)
}
sorted := slices.Clone(want)
slices.Sort(sorted)
if ids := liveAgentIDs(e.Get("models")); !slices.Equal(ids, sorted) {
t.Errorf("models %v, want %v", ids, sorted)
}
if ids := liveAgentIDs(e.Get("modelOrder")); !slices.Equal(ids, want) {
t.Errorf("modelOrder %v, want %v", ids, want)
}
if r.Get("defaultModel").String() != want[0] || r.Get("defaultProvider").String() != "magpie" ||
r.Get("compactModel").String() != want[0] || r.Get("compactProvider").String() != "magpie" {
t.Errorf("picks still K-brain's empty demo: %s", got)
}
if r.Get("language").String() != "en" || r.Get("providers.demo.api").String() != "openai-completions" {
t.Errorf("the rest of the file changed: %s", got)
}
// nothing changed: nothing written
before, _ := os.Stat(a.Path)
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
if again := liveAgentFile(t, a.Path); again != got {
t.Errorf("rewritten with nothing changed:\n%s\n%s", got, again)
}
if after, _ := os.Stat(a.Path); !after.ModTime().Equal(before.ModTime()) {
t.Error("file touched with nothing changed")
}
// renamed, a model turned off, reordered and renamed in LiveAgent,
// K-brain's metadata added, a model magpie has now missing: a sync
// keeps the user's and K-brain's, and the new model is on and last
last := want[len(want)-1]
var models []json.RawMessage
for _, m := range e.Get("models").Array() {
switch m.Get("id").String() {
case last:
continue
case want[0]:
var mm map[string]any
json.Unmarshal([]byte(m.Raw), &mm)
mm["displayName"] = "Mine"
models = append(models, rawJSON(mm))
default:
models = append(models, json.RawMessage(m.Raw))
}
}
order := slices.Clone(want[:len(want)-1])
slices.Reverse(order)
mine, _ := json.Marshal(map[string]any{
"name": "My magpie", "type": "claude_code", "baseUrl": gw, "api": "anthropic-messages", "apiKey": e.Get("apiKey").String(),
"activeModels": []string{want[1]}, "modelOrder": order, "metadata": map[string]any{"providerOrder": 3}, "models": models,
})
var edited map[string]any
json.Unmarshal(jsonc.ToJSON([]byte(got)), &edited)
var mineV any
json.Unmarshal(mine, &mineV)
edited["providers"].(map[string]any)["magpie"] = mineV
eb, _ := json.MarshalIndent(edited, "", " ")
liveAgentWrite(t, a.Path, string(eb))
if err := a.Sync(); err != nil {
t.Fatal(err)
}
e = liveAgentJSON(t, liveAgentFile(t, a.Path)).Get("providers.magpie")
if e.Get("name").String() != "My magpie" || e.Get("metadata.providerOrder").Int() != 3 {
t.Errorf("the user's name and K-brain's fields not kept: %s", e.Raw)
}
if ids := liveAgentIDs(e.Get("models")); !slices.Equal(ids, sorted) {
t.Errorf("models after sync %v, want %v", ids, sorted)
}
if ids := liveAgentIDs(e.Get("activeModels")); !slices.Equal(ids, []string{want[1], last}) {
t.Errorf("activeModels after sync %v, want %v", ids, []string{want[1], last})
}
if ids := liveAgentIDs(e.Get("modelOrder")); !slices.Equal(ids, append(order, last)) {
t.Errorf("modelOrder after sync %v, want %v", ids, append(order, last))
}
if n := e.Get(`models.#(id=="` + want[0] + `").displayName`).String(); n != "Mine" {
t.Errorf("the user's name for a model: %q", n)
}
// off: magpie's entry goes, the picks go back to K-brain's model1,
// and the rest is the file it found
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if f.Get() != "" {
t.Fatalf("get after off: %q", f.Get())
}
if !jsonEqual(jsonc.ToJSON([]byte(liveAgentFile(t, a.Path))), jsonc.ToJSON([]byte(liveAgentDefault))) {
t.Errorf("after off:\n%s\nwant\n%s", liveAgentFile(t, a.Path), liveAgentDefault)
}
// and on then off, untouched since, is the file byte for byte
liveAgentWrite(t, a.Path, liveAgentDefault)
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if got := liveAgentFile(t, a.Path); got != liveAgentDefault {
t.Errorf("on then off:\n%s\nwant\n%s", got, liveAgentDefault)
}
// a sync with no entry there writes none
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if got := liveAgentFile(t, a.Path); got != liveAgentDefault {
t.Errorf("a sync wrote magpie back:\n%s", got)
}
}
// With no config.json, or the {} LiveAgent's backend makes on its first
// start, on writes magpie's provider and pick, and off takes away the
// file it made. A user's own provider and pick stay through on and off,
// and a file left with no provider gets K-brain's demo back, which
// K-brain's CLI reads as a config, where none would bring back its .bak.
func TestLiveAgentMakesItsFile(t *testing.T) {
_, a, want := liveAgentSetup(t)
f := a.Field("provider")
for _, start := range []string{"", "{}"} {
os.Remove(a.Path)
if start != "" {
liveAgentWrite(t, a.Path, start)
}
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
r := liveAgentJSON(t, liveAgentFile(t, a.Path))
if r.Get("defaultModel").String() != want[0] || r.Get("defaultProvider").String() != "magpie" ||
!r.Get("providers.magpie.models").IsArray() || r.Get("compactModel").Exists() {
t.Errorf("from %q: %s", start, r.Raw)
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(a.Path); !os.IsNotExist(err) {
t.Errorf("from %q, off left %s", start, liveAgentFile(t, a.Path))
}
}
// the user's provider and pick, and a setting: theirs stay
const theirs = `{"language":"zh","defaultModel":"deepseek-chat","defaultProvider":"ds","providers":{"ds":{"name":"ds","baseUrl":"https://api.deepseek.com","api":"openai-completions","apiKey":"sk-u","activeModels":null,"models":[{"id":"deepseek-chat"}]}}}`
liveAgentWrite(t, a.Path, theirs)
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
if r := liveAgentJSON(t, liveAgentFile(t, a.Path)); r.Get("defaultModel").String() != "deepseek-chat" || r.Get("defaultProvider").String() != "ds" {
t.Errorf("the user's pick changed: %s", r.Raw)
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if got := liveAgentFile(t, a.Path); got != theirs {
t.Errorf("on then off:\n%s\nwant\n%s", got, theirs)
}
// picked in LiveAgent (default, task), then off: the picks go back to
// K-brain's, the first model of the providers left
liveAgentWrite(t, a.Path, theirs)
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
s := strings.Replace(liveAgentFile(t, a.Path), `"defaultModel":"deepseek-chat","defaultProvider":"ds"`, `"defaultModel":"`+want[1]+`","defaultProvider":"magpie","taskModel":"`+want[0]+`","taskProvider":"magpie"`, 1)
liveAgentWrite(t, a.Path, s)
if err := f.Set(""); err != nil {
t.Fatal(err)
}
r := liveAgentJSON(t, liveAgentFile(t, a.Path))
if r.Get("providers.magpie").Exists() || r.Get("defaultModel").String() != "" || !r.Get("defaultModel").Exists() ||
r.Get("defaultProvider").Exists() || r.Get("taskModel").Exists() || r.Get("taskProvider").Exists() ||
r.Get("providers.ds.apiKey").String() != "sk-u" || r.Get("language").String() != "zh" {
t.Errorf("after off: %s", r.Raw)
}
// only magpie's provider left, and a setting: off gives K-brain's
// demo back, and its model1 as the pick
liveAgentWrite(t, a.Path, `{"language":"zh"}`)
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
r = liveAgentJSON(t, liveAgentFile(t, a.Path))
if r.Get("providers.magpie").Exists() || r.Get("defaultModel").String() != "model1" || r.Get("defaultProvider").Exists() ||
r.Get("providers.demo.api").String() != "openai-completions" || r.Get("language").String() != "zh" {
t.Errorf("emptied file: %s", r.Raw)
}
}
// A config.json K-brain wouldn't read as its providers, or one LiveAgent
// holds while it runs, is left as it is, on and off.
func TestLiveAgentLeavesAlone(t *testing.T) {
_, a, _ := liveAgentSetup(t)
f := a.Field("provider")
for _, s := range []string{
`{"providers":`,
`{"models":{"x":{}},"providers":{}}`,
`{"name":"mine","api":"openai-completions","baseUrl":"https://x","apiKey":"k","models":[]}`,
`{"providers":[{"name":"mine"}]}`,
`[]`,
} {
liveAgentWrite(t, a.Path, s)
if err := f.Set(magpieID); err == nil {
t.Errorf("set on %s: no error", s)
}
if err := a.Sync(); err != nil {
t.Errorf("sync on %s: %v", s, err)
}
if got := liveAgentFile(t, a.Path); got != s {
t.Errorf("%s changed to %s", s, got)
}
}
liveAgentWrite(t, a.Path, liveAgentDefault)
liveAgentRunning = func() bool { return true }
if err := f.Set(magpieID); err != errLiveAgentRunning {
t.Errorf("on while running: %v", err)
}
if got := liveAgentFile(t, a.Path); got != liveAgentDefault {
t.Errorf("written while running: %s", got)
}
liveAgentRunning = func() bool { return false }
if err := f.Set(magpieID); err != nil {
t.Fatal(err)
}
on := liveAgentFile(t, a.Path)
liveAgentRunning = func() bool { return true }
if err := f.Set(""); err != errLiveAgentRunning {
t.Errorf("off while running: %v", err)
}
if got := liveAgentFile(t, a.Path); got != on {
t.Errorf("written while running: %s", got)
}
}
// LiveAgent's root: $LIVEAGENT_HOME, then $K_BRAIN_HOME, then the folder
// ~/.liveagent/data-dir.json points to, then ~/.liveagent; a relative
// path is not a root.
func TestLiveAgentDir(t *testing.T) {
home := syncHome(t)
def := filepath.Join(home, ".liveagent")
moved := filepath.Join(home, "Data", "LiveAgent")
for _, c := range []struct {
live, kbrain, pointer, want string
}{
{"", "", "", def},
{moved, "", "", moved},
{"", moved, "", moved},
{moved, filepath.Join(home, "other"), "", moved},
{"rel", "", "", def},
{"", "", `{"path":` + strings.TrimSpace(string(rawJSON(moved))) + `}`, moved},
{"", "", `{"path":` + strings.TrimSpace(string(rawJSON(def))) + `}`, def},
{"", "", `{"path":"rel"}`, def},
{"", "", `not json`, def},
} {
t.Setenv("LIVEAGENT_HOME", c.live)
t.Setenv("K_BRAIN_HOME", c.kbrain)
os.Remove(filepath.Join(def, "data-dir.json"))
if c.pointer != "" {
liveAgentWrite(t, filepath.Join(def, "data-dir.json"), c.pointer)
}
if got := liveAgentDir(home); got != c.want {
t.Errorf("%+v: %s", c, got)
}
if got := liveAgent(home).Path; got != filepath.Join(c.want, "config.json") {
t.Errorf("%+v: path %s", c, got)
}
}
}
// LiveAgent's processes: the app and the k-brain backend it starts,
// wherever the bundle is.
func TestLiveAgentProcess(t *testing.T) {
match := func(cmd string) bool {
for _, p := range liveAgentProc {
if regexp.MustCompile(p).MatchString(cmd) {
return true
}
}
return false
}
for _, cmd := range []string{
"/Applications/LiveAgent.app/Contents/MacOS/liveagent",
"/Users/u/Apps/My Apps/LiveAgent.app/Contents/MacOS/k-brain backend -listen 127.0.0.1:0 -data-dir /Users/u/.liveagent -parent-stdio",
"/usr/bin/liveagent",
"k-brain backend -listen 127.0.0.1:0",
} {
if !match(cmd) {
t.Errorf("not LiveAgent: %s", cmd)
}
}
for _, cmd := range []string{"vim /Users/u/.liveagent/config.json", "/usr/bin/liveagentd", "/opt/k-brain-tools/x", "grep liveagent"} {
if match(cmd) {
t.Errorf("taken for LiveAgent: %s", cmd)
}
}
}
+3
View File
@@ -71,6 +71,9 @@ var Vars = []string{
"ANTE_HOME",
// NewMax's data folder (its newmax.db), ~/.newmax without it
"NEWMAX_USER_DATA_DIR",
// LiveAgent's data folder (K-brain's config.json), else the one
// ~/.liveagent/data-dir.json points to, else ~/.liveagent
"LIVEAGENT_HOME", "K_BRAIN_HOME",
// AstrBot's root, the folder holding its data/ (else ~/.astrbot, the desktop app's)
"ASTRBOT_ROOT",
// jcode's folder, ~/.jcode without it
+5
View File
@@ -4379,6 +4379,7 @@ const I18N = {
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "OpenChamber 的项目 {project} 有自己的默认模型({model}),在该项目里会改用它。",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil 启动时读取设置、退出时把设置全部写回 —— 请先退出 OpenPencil 再更改这里,然后打开它,在聊天的模型选择器中选一个 magpie 的模型。",
"NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax 运行时把设置放在内存里,任一设置变化时会全部写回 —— 请先退出 NewMax 再更改这里,然后打开它,在模型选择器中选一个 magpie 的模型。",
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent 运行时把设置放在内存里,任一设置变化时会全部写回 —— 请先退出 LiveAgent 再更改这里,然后打开它,在模型选择器中选一个 magpie 的模型。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil 启动时读取自定义模型,需重启 Pencil 才能在它的模型选择器中看到 magpie 的模型。",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On magpie it doesn't use your Google sign-in; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity 启动时读取网关,需重启 Antigravity 才能使用 magpie 的模型。接入 magpie 时它不使用你的 Google 登录,在这里关闭即可恢复。未在自己那一行接入的 agy 也会跟着它走。",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravity 的 {path} 设置了自己的网关,它优先于 ~/.antigravity/settings.json,所以不会连到 magpie",
@@ -8944,6 +8945,7 @@ const I18N = {
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "OpenChamber 的專案 {project} 有自己的預設模型({model}),在該專案裡會改用它。",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil 啟動時讀取設定、結束時把設定全部寫回 —— 請先結束 OpenPencil 再變更這裡,然後開啟它,在聊天的模型選擇器中選一個 magpie 的模型。",
"NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax 執行時把設定放在記憶體中,任一設定變更時會全部寫回 —— 請先結束 NewMax 再變更這裡,然後開啟它,在模型選擇器中選一個 magpie 的模型。",
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent 執行時把設定放在記憶體中,任一設定變更時會全部寫回 —— 請先結束 LiveAgent 再變更這裡,然後開啟它,在模型選擇器中選一個 magpie 的模型。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil 啟動時讀取自訂模型,需重啟 Pencil 才能在它的模型選擇器中看到 magpie 的模型。",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On magpie it doesn't use your Google sign-in; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity 啟動時讀取閘道,需重啟 Antigravity 才能使用 magpie 的模型。接入 magpie 時它不使用你的 Google 登入,在這裡關閉即可恢復。未在自己那一列接入的 agy 也會跟著它走。",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravity 的 {path} 設定了自己的閘道,它優先於 ~/.antigravity/settings.json,所以不會連到 magpie",
@@ -13511,6 +13513,7 @@ const I18N = {
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "OpenChamber のプロジェクト {project} には独自のデフォルトモデル({model})があり、そこではそちらが使われます。",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil は起動時に設定を読み込み、終了時に設定をすべて書き戻します。ここを変更する前に OpenPencil を終了し、その後開いてチャットのモデル選択で magpie のモデルを選んでください。",
"NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax は実行中に設定をメモリに保持し、設定が変わるたびにすべて書き戻します。ここを変更する前に NewMax を終了し、その後開いてモデル選択で magpie のモデルを選んでください。",
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent は実行中に設定をメモリに保持し、設定が変わるたびにすべて書き戻します。ここを変更する前に LiveAgent を終了し、その後開いてモデル選択で magpie のモデルを選んでください。",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil は起動時にカスタムモデルを読み込みます。モデル選択に magpie のモデルを表示するには Pencil を再起動してください。",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On magpie it doesn't use your Google sign-in; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity は起動時にゲートウェイを読み込みます。magpie のモデルを使うには Antigravity を再起動してください。magpie 経由では Google のサインインは使われず、ここでオフにすると元に戻ります。自分の行で接続していない agy もこれに従います。",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravity の {path} が独自のゲートウェイを設定しており、~/.antigravity/settings.json より優先されるため、magpie に届きません",
@@ -18078,6 +18081,7 @@ const I18N = {
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.": "Das OpenChamber-Projekt {project} hat ein eigenes Standardmodell ({model}), das dort stattdessen genutzt wird.",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.": "OpenPencil liest seine Einstellungen beim Start und schreibt sie beim Beenden alle zurück – OpenPencil vor dieser Änderung beenden, dann öffnen und in der Modellauswahl seines Chats ein magpie-Modell wählen.",
"NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.": "NewMax hält seine Einstellungen während der Ausführung im Speicher und schreibt sie bei jeder Änderung alle zurück – NewMax vor dieser Änderung beenden, dann öffnen und in seiner Modellauswahl ein magpie-Modell wählen.",
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.": "LiveAgent hält seine Einstellungen während der Ausführung im Speicher und schreibt sie bei jeder Änderung alle zurück – LiveAgent vor dieser Änderung beenden, dann öffnen und in seiner Modellauswahl ein magpie-Modell wählen.",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.": "Pencil liest seine eigenen Modelle beim Start – Pencil neu starten, um magpies Modelle in seiner Modellauswahl zu sehen.",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On magpie it doesn't use your Google sign-in; turning it off here gives that back. An agy not connected on its own row follows it too.": "Antigravity liest sein Gateway beim Start – Antigravity neu starten, um magpies Modelle zu nutzen. Über magpie nutzt es deine Google-Anmeldung nicht; hier ausschalten gibt sie zurück. Ein agy, das nicht in seiner eigenen Zeile verbunden ist, folgt ihm auch.",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie": "Antigravitys {path} setzt ein eigenes Gateway, das Vorrang vor ~/.antigravity/settings.json hat, daher erreicht es magpie nicht",
@@ -18339,6 +18343,7 @@ const NOTICES = [
"OpenChamber's project {project} has a default model of its own ({model}), which it uses there instead.",
"OpenPencil reads its settings when it starts and writes them all back when it quits — quit OpenPencil before changing this, then open it and pick a magpie model in its chat's model picker.",
"NewMax keeps its settings in memory while it runs and writes them all back when one changes — quit NewMax before changing this, then open it and pick a magpie model in its model picker.",
"LiveAgent keeps its settings in memory while it runs and writes them all back when one changes — quit LiveAgent before changing this, then open it and pick a magpie model in its model picker.",
"Pencil reads its custom models at start-up — restart Pencil to see magpie's models in its model picker.",
"Antigravity reads its gateway at start-up — restart Antigravity to use magpie's models. On magpie it doesn't use your Google sign-in; turning it off here gives that back. An agy not connected on its own row follows it too.",
"Antigravity's {path} sets a gateway of its own, which wins over ~/.antigravity/settings.json, so it doesn't reach magpie",
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.8 KiB