agents: Nowledge Mem's own AI runs on magpie (xiaomaomiloulou on X)

Nowledge Mem asks for "选择一个 AI" on its first page and in Settings >
AI, and Mem 0.10 has a provider type of magpie's own. Picking a magpie
model for the new agent nowledge-mem now sets it up from magpie:

- Mem keeps its providers in remote_llm.json with each key encrypted, so
  the file is only read. Changes go through its backend (nmem-server,
  127.0.0.1:14242, $NMEM_API_URL when it names this computer), as its
  Settings and `nmem config provider` do: POST /remote-llm/config saves
  provider "magpie" at the gateway's /v1 with agentKey("nowledge-mem")
  and the model, which makes it active and turns the AI on.
- Mem puts temperature, max_tokens and timeout back to its defaults
  when a save leaves them out, so every save sends the provider's own.
- What Mem had is stashed once: the active provider, whether the AI was
  on, and a "magpie" provider the user made, which keeps its key and
  gets its model, base and parameters back. Stepping out activates the
  provider Mem had (unless one was picked in Mem since), removes
  magpie's provider and turns the AI off again if it was off.
- Mem has to run to change it (errMemDown); a sync moves the base only
  when the gateway's port moved. Detected by its config folder or the
  installed app (co.nowledge.mem.desktop). Icon from its icon.icns.

Run (mote):
- go test -count=1 -run 'NowledgeMem|TestEveryAgent|TestListOnly|TestSync|Desktop'
  ./internal/agent ./internal/library ./internal/agentenv ok; -run Icon
  ./internal/gui ok.
- GUI: icon-one-tone, icon-tile, routing-client-icons, i18n-keys in
  Chromium and WebKit, 58 of 59; the red is icon-tile's dim-color, red
  on origin/main since 2649d5d72 (#6759), not this icon.
- Real Nowledge Mem 0.10.121 (free tier) in a sandbox HOME on mote, its
  nmem-server on its own port behind a logging proxy, and a sandbox
  magpie (go build of this tree) with a fake OpenAI vendor:
  `magpie nowledge-mem fakeoa/fake-model` made magpie Mem's active
  provider at the sandbox gateway; Mem's own `nmem config provider test`
  answered "Connection OK — magpie/fakeoa/fake-model", the vendor got
  the request, and `magpie usage` counted it under Nowledge Mem.
  `magpie nowledge-mem default` put openai_compatible/u2 back as active,
  removed magpie's provider, and Mem's test passed on it again.
- That run found NMEM_API_URL dropped as "not an absolute path";
  NotPaths has it now (the AGY sibling is the commit before).

- On 681f2ee7f, then rebased onto 6af38c0ee (internal/gui providers
  only, none of these packages): gofmt -l clean; go vet, GOOS=linux
  and GOOS=windows go vet of ./internal/agent ./internal/agentenv
  ./internal/library ok; the tests above again ok.
- Not run: the full go test ./... suite. mote had another session's full
  suite running and mica's disk is full (323 MB free); it runs on mote
  once that one ends, and a red gets its own issue and fix.

Broken by hand: without the check that magpie's provider is still the
active one, TestNowledgeMemKeepsALaterPick is red; without re-sending
temperature, or sending a key over the user's own magpie provider,
TestNowledgeMemKeepsTheUsersMagpie is red; with NMEM_API_URL out of
NotPaths, TestNowledgeMemOnlyOnThisComputer is red.

Not tried: Mem's window itself (the run used its API and CLI), magpie's
GUI connect row clicked, Windows and Linux (config folder per OS is
from Mem's source, not a real install), a paid Mem plan.
This commit is contained in:
yetone
2026-11-19 15:44:48 +08:00
parent f63549b5ca
commit 72f7c1f41a
14 changed files with 865 additions and 4 deletions
+1 -1
View File
@@ -83,7 +83,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 · Dim · 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 · Mistral Vibe · 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 · Paseo · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Open Code Review · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · Dim · 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 · Mistral Vibe · 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 · Paseo · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Open Code Review · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun · Nowledge Mem
</td></tr>
</table>
+1 -1
View File
@@ -83,7 +83,7 @@ magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、
<table>
<tr><td>
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · Dim · 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 · Mistral Vibe · 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 · Paseo · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Open Code Review · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun
Claude Code · Claude Desktop · Claude Science · Codex · Gemini CLI · Antigravity CLI · Dim · 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 · Mistral Vibe · 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 · Paseo · OpenPencil · OpenBot · Craft Agents · Tuanjie Cowork · NewMax · LiveAgent · Raycast · Kiro Crew · OpenMausBot · T3 Code · OpenHanako · AtomCode · Open Code Review · Snow CLI · Alma · Shelley · Cindy · Lody · AionUi · Cherry Studio · Ante · AstrBot · QwenPaw · OpenClaw · Avibe · Kun · Nowledge Mem
</td></tr>
</table>
+1
View File
@@ -166,6 +166,7 @@ line; agents connected to magpie lose it when it quits.
| 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) |
| Nowledge Mem | `remote_llm.json` in its config folder (`~/Library/Application Support/co.nowledge.mem.desktop`, `%APPDATA%`, `$XDG_CONFIG_HOME`; `$NMEM_APP_CONFIG_DIR`), read only: changed through its backend's API on `127.0.0.1:14242` (`$NMEM_API_URL`) while it runs | model (Mem's own `magpie` provider at the gateway's `/v1` with Mem's own key, made its active AI and turned on; the provider and on/off Mem had come back on disconnect. Mem 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) |
| Open Code Review | `~/.opencodereview/config.json` | model (a `magpie` custom provider made the one in use; its Claude Code, Codex, Cursor, Kimi Code and OpenCode plugins run the same `ocr`) |
+1
View File
@@ -159,6 +159,7 @@ something else shows up as drift.
- 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`).
- Nowledge Mem (`nowledgemem.go`, a Tauri app, `co.nowledge.mem.desktop`; xiaomaomiloulou on X) runs its own AI (search, distilling, its chat) on the remote LLM provider picked on its first page and in Settings > AI, kept in `remote_llm.json` in its config folder (`$NMEM_APP_CONFIG_DIR`, else `co.nowledge.mem.desktop` in the system's config folder) with each key encrypted, so the file is only read. Mem 0.10 has a provider type of magpie's own (`magpie`, default base `http://127.0.0.1:3425/v1`, `Bearer magpie-nowledge-mem` with no key), and the gateway reads that key as the agent `nowledge-mem`. magpie changes it through Mem's backend, nmem-server, at `127.0.0.1:14242` (`$NMEM_API_URL`, loopback only; `memLive` probes `/remote-llm/status`), as Settings and `nmem config provider` do: `POST /remote-llm/config` saves provider `magpie` with the model, the gateway's `/v1` and `agentKey("nowledge-mem")`, and always makes it active and turns the AI on. Left out, `temperature`, `max_tokens` and `timeout` go back to Mem's defaults, so every change sends the provider's own again (`memBody`). What Mem had is stashed once (`nowledge-mem.prev:<dir>`): the active provider, whether the AI was on, and a `magpie` provider the user made themselves, which keeps its own key and gets its model, base and parameters back. Stepping out activates the provider Mem had (`/remote-llm/activate`), unless one was picked in Mem since, removes magpie's provider (`/remote-llm/provider/remove`) and turns the AI off again (`/remote-llm/enabled`) if it was off. Every change needs Mem running (`errMemDown`); reads go to the API, else the file. A sync moves the base only from the gateway's own address on an older port (`avibeMoved`). Every test of the package but Mem's own finds a Mem running per config folder (`runningMem`).
- 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`.
+1
View File
@@ -401,6 +401,7 @@ func onMachineAll(home, cfg string) []*Agent {
openMausBot(home),
avibe(home),
kun(home),
nowledgeMem(home),
hanako(home),
atomcode(home),
ocr(home),
+3
View File
@@ -157,6 +157,9 @@ var desktopApps = map[string]desktopApp{
// folder is the default's, not read from an install.
"minimax-code": {id: "com.minimax.agent.cn", names: []string{"MiniMax Code.app"}, win: filepath.Join("MiniMax Code", "MiniMax Code.exe"),
more: []desktopApp{{id: "com.minimax.agent", names: []string{"MiniMax Code.app"}}}},
// Nowledge Mem (0.10.121: Nowledge Mem.app, co.nowledge.mem.desktop, a
// Tauri app) keeps its config folder only once it has been opened.
"nowledge-mem": {id: "co.nowledge.mem.desktop", names: []string{"Nowledge Mem.app"}},
"codebuddy": {id: "com.tencent.codebuddy", names: []string{"CodeBuddy.app"},
more: []desktopApp{{id: "com.tencent.codebuddycn", names: []string{"CodeBuddy CN.app"}}}},
}
+3
View File
@@ -63,6 +63,9 @@ func TestMain(m *testing.M) {
// nor a Kun runtime this machine runs: each home's Kun runs in the
// test (runningKun)
kunLive = runningKun
// nor the Nowledge Mem this machine runs: each config folder's Mem
// runs in the test (runningMem)
memLive = runningMem
// 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)
+454
View File
@@ -0,0 +1,454 @@
package agent
// Nowledge Mem (mem.nowledge.co, a Tauri app, co.nowledge.mem.desktop;
// xiaomaomiloulou on X) is a personal memory app whose own AI (search,
// distilling, the chat) runs on a remote LLM picked on its first page,
// "选择一个 AI", and in Settings > AI. Mem 0.10 has a provider of magpie's
// own among its types: "magpie", at the gateway's default address
// http://127.0.0.1:3425/v1, which sends Bearer magpie-nowledge-mem when no
// key is set. So magpie's gateway already reads its requests as the agent
// nowledge-mem; what it lacked was the setting.
//
// Mem keeps its providers in remote_llm.json in its config folder
// (~/Library/Application Support/co.nowledge.mem.desktop on a Mac,
// %APPDATA%\co.nowledge.mem.desktop on Windows, the XDG config folder on
// Linux; $NMEM_APP_CONFIG_DIR), each key encrypted there (api_key_enc and
// api_key_nonce), so the file is never written by magpie. Mem's backend,
// nmem-server, changes it through its HTTP API on 127.0.0.1:14242 (the
// nmem CLI's $NMEM_API_URL), which takes loopback requests without a key,
// as Mem's own Settings and `nmem config provider` do (read at 0.10.121):
//
// GET /remote-llm/config enabled, active_provider, providers{id: provider_type, model, api_base, has_api_key, …}
// POST /remote-llm/config {enabled, provider, provider_type, model, api_base, api_key, temperature, max_tokens, timeout}
// POST /remote-llm/activate {provider}
// POST /remote-llm/provider/remove {provider}
// POST /remote-llm/enabled {enabled}
//
// POST /remote-llm/config saves a provider and always makes it the active
// one; api_base and api_key left out keep what was stored, but
// temperature, max_tokens and timeout left out go back to 0.7, 8192 and
// 60, so the provider's own are sent again with every change.
//
// Picking a magpie model for Mem saves the provider "magpie" (type magpie)
// at the gateway's /v1 with Mem's own agent key and that model, and turns
// Mem's AI on. What Mem had before is stashed: its active provider,
// whether its AI was on, and a "magpie" provider the user had made
// themselves, with its values. Stepping out activates that provider again,
// puts the user's "magpie" back as it was or removes magpie's, and turns
// the AI off again if it was off.
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"path/filepath"
"runtime"
"slices"
"strings"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/edit"
)
// memBundle is Mem's bundle id, the name of its config folder.
const memBundle = "co.nowledge.mem.desktop"
// memAddr is where Mem's backend listens unless $NMEM_API_URL says.
const memAddr = "http://127.0.0.1:14242"
// memDefaultBase is where Mem's magpie type goes with no api_base.
const memDefaultBase = "http://127.0.0.1:3425/v1"
// errMemDown is a change asked of a Mem that isn't running.
var errMemDown = errors.New("Nowledge Mem changes its AI only while it runs: open Nowledge Mem, then try again")
// memConfigDir is Mem's config folder: $NMEM_APP_CONFIG_DIR, else the
// app's folder in the system's config folder.
func memConfigDir(home string) string {
if d := strings.TrimSpace(appdir.Getenv("NMEM_APP_CONFIG_DIR")); d != "" {
return d
}
switch runtime.GOOS {
case "darwin":
return filepath.Join(home, "Library", "Application Support", memBundle)
case "windows":
if d := appdir.Getenv("APPDATA"); d != "" {
return filepath.Join(d, memBundle)
}
return filepath.Join(home, "AppData", "Roaming", memBundle)
}
if d := appdir.Getenv("XDG_CONFIG_HOME"); d != "" {
return filepath.Join(d, memBundle)
}
return filepath.Join(home, ".config", memBundle)
}
// memProvider is one of Mem's providers, as its API (provider_type) and
// its file (type) give it.
type memProvider struct {
Type string `json:"provider_type,omitempty"`
FileType string `json:"type,omitempty"`
Model string `json:"model"`
APIBase string `json:"api_base,omitempty"`
HasKey bool `json:"has_api_key,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
Timeout *float64 `json:"timeout,omitempty"`
}
func (p memProvider) kind() string {
if p.Type != "" {
return p.Type
}
return p.FileType
}
// memState is Mem's remote LLM setting.
type memState struct {
Enabled bool `json:"enabled"`
Active string `json:"active_provider"`
Providers map[string]memProvider `json:"providers"`
}
// memPrev is what Mem had before magpie, as stashed.
type memPrev struct {
Active string `json:"active,omitempty"`
Enabled bool `json:"enabled"`
Had *memProvider `json:"had,omitempty"`
}
// memOn says magpie's provider is the one Mem's AI uses.
func memOn(s memState) (memProvider, bool) {
p, ok := s.Providers[magpieID]
return p, ok && s.Enabled && s.Active == magpieID
}
// memBase is where p sends Mem's requests.
func memBase(p memProvider) string {
if p.APIBase == "" && p.kind() == magpieID {
return memDefaultBase
}
return strings.TrimSuffix(p.APIBase, "/")
}
// memRead is Mem's setting as remote_llm.json has it, for a Mem that
// isn't running.
func memRead(path string) (memState, bool) {
raw, err := edit.Read(path)
if err != nil {
return memState{}, false
}
var s memState
if json.Unmarshal(raw, &s) != nil {
return memState{}, false
}
return s, true
}
func nowledgeMem(home string) *Agent {
dir := memConfigDir(home)
path := filepath.Join(dir, "remote_llm.json")
keyPrev := "nowledge-mem.prev:" + dir
now := func() (memState, *memClient) {
if c := memLive(dir); c != nil {
if s, err := c.config(); err == nil {
return s, c
}
}
s, _ := memRead(path)
return s, nil
}
// wire makes magpie's provider Mem's AI, with model m
wire := func(c *memClient, s memState, m string) error {
had, there := s.Providers[magpieID]
if unstashPeek(keyPrev) == "" {
prev := memPrev{Enabled: s.Enabled}
if s.Active != magpieID {
prev.Active = s.Active
}
if there {
prev.Had = &had
}
b, _ := json.Marshal(prev)
stash(map[string]string{keyPrev: string(b)})
}
body := memBody(had, magpieID, m)
body["api_base"] = gatewayV1()
var prev memPrev
json.Unmarshal([]byte(unstashPeek(keyPrev)), &prev)
if prev.Had == nil {
// a key on the user's own "magpie" provider stays theirs
body["api_key"] = agentKey("nowledge-mem")
}
return c.post("/remote-llm/config", body)
}
// unwire takes magpie's provider out of Mem's AI, putting back what Mem
// had, with model v on it where v isn't ""
unwire := func(c *memClient, s memState, v string) error {
raw := unstashPeek(keyPrev)
var prev memPrev
if raw == "" {
// magpie never stashed: a "magpie" the user made by hand is
// theirs to keep; Mem goes to another provider of its own
prev.Had, prev.Enabled = &memProvider{}, true
for _, id := range slices.Sorted(maps.Keys(s.Providers)) {
if id != magpieID {
prev.Active = id
break
}
}
if prev.Active == "" {
prev.Enabled = false
}
} else {
json.Unmarshal([]byte(raw), &prev)
}
if p, ok := s.Providers[magpieID]; ok && prev.Had != nil && prev.Had.Model != "" {
back := memBody(p, magpieID, prev.Had.Model)
back["api_base"] = prev.Had.APIBase
for k, val := range map[string]any{"temperature": prev.Had.Temperature, "max_tokens": prev.Had.MaxTokens, "timeout": prev.Had.Timeout} {
if val != nil {
back[k] = val
}
}
if err := c.post("/remote-llm/config", back); err != nil {
return err
}
}
// a provider the user picked in Mem since stays picked
ours := s.Active == magpieID
if p, ok := s.Providers[prev.Active]; ok && prev.Active != magpieID && (ours || v != "") {
if v != "" && v != p.Model {
if err := c.post("/remote-llm/config", memBody(p, prev.Active, v)); err != nil {
return err
}
} else if err := c.post("/remote-llm/activate", map[string]any{"provider": prev.Active}); err != nil {
return err
}
} else if v != "" && ours {
return errors.New("Nowledge Mem had no AI of its own to use " + v + " with: pick one in its Settings > AI")
}
if _, ok := s.Providers[magpieID]; ok && prev.Had == nil {
if err := c.post("/remote-llm/provider/remove", map[string]any{"provider": magpieID}); err != nil {
return err
}
}
if !prev.Enabled && ours {
if err := c.post("/remote-llm/enabled", map[string]any{"enabled": false}); err != nil {
return err
}
}
forget(keyPrev)
return nil
}
return &Agent{
ID: "nowledge-mem", Name: "Nowledge Mem", Icon: "nowledge-mem",
Dir: dir, Path: path,
detect: func() bool {
return isDir(dir) || (&Agent{ID: "nowledge-mem"}).HasApp()
},
// a gateway on a new port reaches magpie's provider
Sync: func() error {
c := memLive(dir)
if c == nil {
return nil
}
s, err := c.config()
if err != nil {
return err
}
p, on := memOn(s)
if !on || !avibeMoved(memBase(p)) {
return nil
}
body := memBody(p, magpieID, p.Model)
body["api_base"] = gatewayV1()
return c.post("/remote-llm/config", body)
},
Check: func() string {
s, _ := now()
p, on := memOn(s)
if !on {
return ""
}
return wiringOff("Nowledge Mem", path, func(string) (string, bool) { return memBase(p), true }, "api_base", gatewayV1())
},
Fields: []Field{{
Key: "model", Label: "model",
Get: func() string {
s, _ := now()
if p, on := memOn(s); on {
return magpieID + "/" + p.Model
}
if p, ok := s.Providers[s.Active]; ok && s.Enabled {
return p.Model
}
return ""
},
Set: func(v string) error {
s, c := now()
if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) {
if c == nil {
return errMemDown
}
return wire(c, s, ref)
}
_, on := memOn(s)
_, made := s.Providers[magpieID]
stashed := unstashPeek(keyPrev) != ""
if !on && !(stashed && made) {
if v == "" {
return nil
}
if p, ok := s.Providers[s.Active]; ok && p.Model == v {
return nil
}
}
if c == nil {
if !on && !stashed {
return nil
}
return errMemDown
}
if on || stashed {
return unwire(c, s, v)
}
p, ok := s.Providers[s.Active]
if !ok {
return errors.New("Nowledge Mem has no AI of its own to use " + v + " with: pick one in its Settings > AI")
}
return c.post("/remote-llm/config", memBody(p, s.Active, v))
},
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("Nowledge Mem", own), "nowledge-mem", magpieID+"/")
},
}},
}
}
// memBody is the POST /remote-llm/config that saves provider id as p is,
// with model m, its parameters sent again (left out, Mem resets them).
func memBody(p memProvider, id, m string) map[string]any {
kind := p.kind()
if kind == "" {
kind = id
}
body := map[string]any{"enabled": true, "provider": id, "provider_type": kind, "model": m}
if p.Temperature != nil {
body["temperature"] = *p.Temperature
}
if p.MaxTokens != nil {
body["max_tokens"] = *p.MaxTokens
}
if p.Timeout != nil {
body["timeout"] = *p.Timeout
}
return body
}
// memProbe gives up quickly: a backend that doesn't answer at once isn't
// running.
const memProbe = 1500 * time.Millisecond
// memWait is how long a change may take.
const memWait = 20 * time.Second
// memClient is a running Mem's backend API.
type memClient struct {
http *http.Client
base string
}
// memLive is memConnect, for the tests to stand in for.
var memLive = memConnect
// memConnect is the backend of the Mem whose config folder is dir if it
// answers, nil if none runs: $NMEM_API_URL when it names this computer,
// else 127.0.0.1:14242.
func memConnect(dir string) *memClient {
base := memAddr
if u := strings.TrimSpace(appdir.Getenv("NMEM_API_URL")); u != "" {
p, err := url.Parse(u)
if err != nil || (p.Scheme != "http" && p.Scheme != "https") || !kunLoopback(p.Hostname()) {
return nil
}
base = strings.TrimRight(u, "/")
}
c := &memClient{http: &http.Client{}, base: base}
ctx, cancel := context.WithTimeout(context.Background(), memProbe)
defer cancel()
if _, err := c.do(ctx, "GET", "/remote-llm/status", nil); err != nil {
return nil
}
return c
}
func (c *memClient) 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")
}
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("Nowledge Mem: %w", err)
}
defer resp.Body.Close()
out, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
if err != nil {
return nil, fmt.Errorf("Nowledge Mem: %w", err)
}
if resp.StatusCode/100 != 2 {
var e struct {
Detail any `json:"detail"`
}
json.Unmarshal(out, &e)
if s, ok := e.Detail.(string); ok && s != "" {
return nil, errors.New("Nowledge Mem: " + s)
}
return nil, fmt.Errorf("Nowledge Mem: %s %s: HTTP %d", method, path, resp.StatusCode)
}
return out, nil
}
func (c *memClient) config() (memState, error) {
ctx, cancel := context.WithTimeout(context.Background(), memWait)
defer cancel()
b, err := c.do(ctx, "GET", "/remote-llm/config", nil)
if err != nil {
return memState{}, err
}
var s memState
if err := json.Unmarshal(b, &s); err != nil {
return memState{}, fmt.Errorf("Nowledge Mem: /remote-llm/config: %w", err)
}
return s, nil
}
func (c *memClient) post(path string, body any) error {
ctx, cancel := context.WithTimeout(context.Background(), memWait)
defer cancel()
_, err := c.do(ctx, "POST", path, body)
return err
}
+391
View File
@@ -0,0 +1,391 @@
package agent
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
// fakeMem is Nowledge Mem's backend (nmem-server 0.10.121) as magpie uses
// it, keeping its setting in remote_llm.json as Mem does, with what was
// seen from the real one: POST /remote-llm/config saves a provider and
// makes it the active one, keeps api_base and the key when they are left
// out and puts temperature, max_tokens and timeout back to 0.7, 8192 and
// 60; removing the active provider leaves none active; activating one
// that isn't there is refused; {"enabled": false} alone goes to
// /remote-llm/enabled.
type fakeMem struct {
dir string
mu sync.Mutex
ops []string
keys map[string]string
}
type fakeMemProvider struct {
Type string `json:"type"`
Model string `json:"model"`
APIBase string `json:"api_base,omitempty"`
Temperature float64 `json:"temperature"`
MaxTokens int `json:"max_tokens"`
Timeout float64 `json:"timeout"`
KeyEnc string `json:"api_key_enc,omitempty"`
}
type fakeMemDoc struct {
Enabled bool `json:"enabled"`
Active string `json:"active_provider"`
Providers map[string]*fakeMemProvider `json:"providers"`
}
func (f *fakeMem) read() fakeMemDoc {
d := fakeMemDoc{}
if b, err := os.ReadFile(filepath.Join(f.dir, "remote_llm.json")); err == nil {
json.Unmarshal(b, &d)
}
if d.Providers == nil {
d.Providers = map[string]*fakeMemProvider{}
}
return d
}
func (f *fakeMem) write(d fakeMemDoc) {
os.MkdirAll(f.dir, 0o700)
b, _ := json.MarshalIndent(d, "", " ")
os.WriteFile(filepath.Join(f.dir, "remote_llm.json"), b, 0o600)
}
// add is a provider the user saved in Mem's Settings > AI.
func (f *fakeMem) add(id, kind, model, base string, temp float64) {
d := f.read()
d.Providers[id] = &fakeMemProvider{Type: kind, Model: model, APIBase: base, Temperature: temp, MaxTokens: 4096, Timeout: 120, KeyEnc: "enc"}
d.Enabled, d.Active = true, id
f.write(d)
}
func (f *fakeMem) handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
if f.keys == nil {
f.keys = map[string]string{}
}
fail := func(code int, msg string) {
w.WriteHeader(code)
json.NewEncoder(w).Encode(map[string]any{"detail": msg})
}
var body map[string]any
if r.Body != nil {
json.NewDecoder(r.Body).Decode(&body)
}
d := f.read()
f.ops = append(f.ops, r.Method+" "+r.URL.Path)
switch r.Method + " " + r.URL.Path {
case "GET /remote-llm/status":
json.NewEncoder(w).Encode(map[string]any{"configured": d.Active != ""})
return
case "GET /remote-llm/config":
ps := map[string]any{}
for id, p := range d.Providers {
ps[id] = map[string]any{"provider": id, "provider_type": p.Type, "model": p.Model, "api_base": p.APIBase, "has_api_key": p.KeyEnc != "", "temperature": p.Temperature, "max_tokens": p.MaxTokens, "timeout": p.Timeout}
}
json.NewEncoder(w).Encode(map[string]any{"enabled": d.Enabled, "active_provider": d.Active, "providers": ps})
return
case "POST /remote-llm/config":
id, _ := body["provider"].(string)
if id == "" {
fail(422, "provider is required")
return
}
p := d.Providers[id]
if p == nil {
p = &fakeMemProvider{}
d.Providers[id] = p
}
p.Type, _ = body["provider_type"].(string)
p.Model, _ = body["model"].(string)
if b, ok := body["api_base"].(string); ok {
p.APIBase = b
}
if k, ok := body["api_key"].(string); ok {
p.KeyEnc = "enc"
f.keys[id] = k
}
p.Temperature, p.MaxTokens, p.Timeout = 0.7, 8192, 60
if v, ok := body["temperature"].(float64); ok {
p.Temperature = v
}
if v, ok := body["max_tokens"].(float64); ok {
p.MaxTokens = int(v)
}
if v, ok := body["timeout"].(float64); ok {
p.Timeout = v
}
d.Enabled, _ = body["enabled"].(bool)
d.Active = id
case "POST /remote-llm/activate":
id, _ := body["provider"].(string)
if d.Providers[id] == nil {
fail(400, "Unknown provider: "+id)
return
}
d.Active = id
case "POST /remote-llm/provider/remove":
id, _ := body["provider"].(string)
delete(d.Providers, id)
delete(f.keys, id)
if d.Active == id {
d.Active = ""
}
case "POST /remote-llm/enabled":
d.Enabled, _ = body["enabled"].(bool)
default:
fail(404, "Not Found")
return
}
f.write(d)
json.NewEncoder(w).Encode(map[string]any{"success": true})
})
}
// runningMems are the Mems every test but this file's own finds running
// (main_test.go), one a config folder, served in the process.
var runningMems = struct {
sync.Mutex
at map[string]*fakeMem
}{at: map[string]*fakeMem{}}
func runningMem(dir string) *memClient {
runningMems.Lock()
f := runningMems.at[dir]
if f == nil {
f = &fakeMem{dir: dir}
runningMems.at[dir] = f
}
runningMems.Unlock()
return &memClient{http: &http.Client{Transport: handlerTransport{f.handler()}}, base: "http://localhost"}
}
// serveFakeMem is the Mem at dir running, for this test alone.
func serveFakeMem(t *testing.T, dir string) *fakeMem {
t.Helper()
f := &fakeMem{dir: dir}
was := memLive
memLive = func(d string) *memClient {
if d != dir {
return nil
}
return &memClient{http: &http.Client{Transport: handlerTransport{f.handler()}}, base: "http://localhost"}
}
t.Cleanup(func() { memLive = was })
return f
}
func memTestHome(t *testing.T) (home, dir string) {
t.Helper()
home, _ = museHome(t) // magpie with deepseek/pro and deepseek/flash
dir = filepath.Join(t.TempDir(), "mem")
t.Setenv("NMEM_APP_CONFIG_DIR", dir)
t.Setenv("NMEM_API_URL", "")
os.MkdirAll(dir, 0o700)
return home, dir
}
// Picking a magpie model for Nowledge Mem saves Mem's own magpie provider
// at the gateway's /v1 with Mem's key and that model, as its first page's
// "选择一个 AI" does, and turns its AI on; stepping out picks the
// provider Mem had again and removes magpie's (xiaomaomiloulou on X).
func TestNowledgeMemUsesMagpie(t *testing.T) {
home, dir := memTestHome(t)
f := serveFakeMem(t, dir)
f.add("openai_compatible", "openai_compatible", "qwen3", "https://example.com/v1", 0.2)
a := nowledgeMem(home)
if a.Dir != dir || !a.Detected() {
t.Fatalf("Mem at %s not found (%s)", dir, a.Dir)
}
fm := a.Field("model")
if got := fm.Get(); got != "qwen3" || a.Wired() {
t.Fatalf("own: %q wired %v", got, a.Wired())
}
for range 2 { // twice: what Mem had is stashed once
if err := fm.Set("magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
}
d := f.read()
p := d.Providers["magpie"]
if p == nil || p.Type != "magpie" || p.Model != "deepseek/pro" || p.APIBase != gatewayV1() || d.Active != "magpie" || !d.Enabled {
t.Fatalf("connected: %+v %+v", d, p)
}
if f.keys["magpie"] != agentKey("nowledge-mem") {
t.Errorf("key %q", f.keys["magpie"])
}
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)
}
if err := fm.Set("magpie/deepseek/flash"); err != nil {
t.Fatal(err)
}
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()
own := d.Providers["openai_compatible"]
if d.Providers["magpie"] != nil || d.Active != "openai_compatible" || !d.Enabled || own.Model != "qwen3" || own.Temperature != 0.2 {
t.Errorf("after disconnect: %+v %+v", d, own)
}
if a.Wired() || unstashPeek("nowledge-mem.prev:"+dir) != "" {
t.Error("still wired, or stashed, after disconnect")
}
}
// A "magpie" provider the user made in Mem themselves, with a key of
// their own and their own temperature, is put back as it was: its model,
// address and parameters, and its key never sent over.
func TestNowledgeMemKeepsTheUsersMagpie(t *testing.T) {
home, dir := memTestHome(t)
f := serveFakeMem(t, dir)
f.add("magpie", "magpie", "theirs", "http://192.168.1.9:3425/v1", 0.3)
f.add("openai", "openai", "gpt-5", "", 0.5)
a := nowledgeMem(home)
if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
if _, sent := f.keys["magpie"]; sent {
t.Error("the user's own magpie provider was given magpie's key")
}
if p := f.read().Providers["magpie"]; p.APIBase != gatewayV1() || p.Temperature != 0.3 {
t.Errorf("connected: %+v", p)
}
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
d := f.read()
p := d.Providers["magpie"]
if p == nil || p.Model != "theirs" || p.APIBase != "http://192.168.1.9:3425/v1" || p.Temperature != 0.3 || p.MaxTokens != 4096 || d.Active != "openai" {
t.Errorf("after disconnect: %+v %+v", d, p)
}
}
// A Mem whose AI was off, with no provider at all, is left that way.
func TestNowledgeMemFromNothing(t *testing.T) {
home, dir := memTestHome(t)
f := serveFakeMem(t, dir)
a := nowledgeMem(home)
if _, err := a.ConnectHow(); err != nil {
t.Fatal(err)
}
if d := f.read(); !a.Wired() || d.Active != "magpie" || !d.Enabled {
t.Fatalf("connect from nothing: %+v", d)
}
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
if d := f.read(); len(d.Providers) != 0 || d.Active != "" || d.Enabled {
t.Errorf("left %+v", d)
}
}
// A provider the user picked in Mem while connected stays picked when
// magpie steps out, and Mem's AI stays on.
func TestNowledgeMemKeepsALaterPick(t *testing.T) {
home, dir := memTestHome(t)
f := serveFakeMem(t, dir)
f.add("openai_compatible", "openai_compatible", "qwen3", "https://example.com/v1", 0.2)
f.add("openai", "openai", "gpt-5", "", 0.5)
f.add("openai_compatible", "openai_compatible", "qwen3", "https://example.com/v1", 0.2)
a := nowledgeMem(home)
if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
d := f.read()
d.Active = "openai" // picked in Mem's Settings > AI
f.write(d)
if err := a.Field("model").Set(""); err != nil {
t.Fatal(err)
}
if d := f.read(); d.Active != "openai" || !d.Enabled || d.Providers["magpie"] != nil {
t.Errorf("after: %+v", d)
}
}
// A gateway on a new port reaches magpie's provider on the next sync.
func TestNowledgeMemFollowsTheGateway(t *testing.T) {
home, dir := memTestHome(t)
f := serveFakeMem(t, dir)
a := nowledgeMem(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, "api_base") {
t.Errorf("Check on a moved gateway: %q", msg)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if p := f.read().Providers["magpie"]; p.APIBase != "http://127.0.0.1:3426/v1" || p.Model != "deepseek/pro" {
t.Errorf("after the move: %+v", p)
}
}
// Mem changes its AI only while it runs; magpie never writes the file,
// whose keys Mem encrypts.
func TestNowledgeMemNeedsItRunning(t *testing.T) {
home, dir := memTestHome(t)
was := memLive
memLive = func(string) *memClient { return nil }
t.Cleanup(func() { memLive = was })
a := nowledgeMem(home)
if err := a.Field("model").Set("magpie/deepseek/pro"); !errors.Is(err, errMemDown) {
t.Errorf("connect with Mem 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, "remote_llm.json")); err == nil {
t.Error("remote_llm.json written while Mem is stopped")
}
// connected, then Mem quit: read from its file, and disconnect waits
os.WriteFile(filepath.Join(dir, "remote_llm.json"), []byte(`{"enabled":true,"active_provider":"magpie","providers":{"magpie":{"type":"magpie","model":"deepseek/pro","api_base":"`+gatewayV1()+`"}}}`), 0o600)
if got := a.Field("model").Get(); got != "magpie/deepseek/pro" {
t.Errorf("read from the file: %q", got)
}
if err := a.Field("model").Set(""); !errors.Is(err, errMemDown) {
t.Errorf("disconnect with Mem stopped: %v", err)
}
}
// $NMEM_API_URL naming another machine is never asked.
func TestNowledgeMemOnlyOnThisComputer(t *testing.T) {
_, dir := memTestHome(t)
// the nmem CLI's NMEM_API_URL is followed when it names this computer:
// it is an address, not a folder magpie drops when it isn't absolute
srv := httptest.NewServer((&fakeMem{dir: dir}).handler())
t.Cleanup(srv.Close)
t.Setenv("NMEM_API_URL", srv.URL+"/")
if c := memConnect(dir); c == nil || c.base != srv.URL {
t.Fatalf("NMEM_API_URL=%s/ not followed: %+v", srv.URL, c)
}
for _, u := range []string{"http://192.168.1.2:14242", "http://evil.example", "file:///x"} {
t.Setenv("NMEM_API_URL", u)
if memConnect(dir) != nil {
t.Errorf("%s reached", u)
}
}
}
+2
View File
@@ -43,6 +43,8 @@ func syncHome(t *testing.T) string {
t.Setenv("OMB_DATA_DIR", "")
t.Setenv("AVIBE_HOME", "")
t.Setenv("KUN_DATA_DIR", "")
t.Setenv("NMEM_APP_CONFIG_DIR", "")
t.Setenv("NMEM_API_URL", "")
t.Setenv("OMO_CODING_AGENT_DIR", "")
t.Setenv("SENPI_CODING_AGENT_DIR", "")
t.Setenv("PRIME_AGENT_CODING_AGENT_DIR", "")
+5 -1
View File
@@ -89,6 +89,10 @@ var Vars = []string{
// Kun's data folder (its runtime.json and model-connections.v2.json),
// ~/.kun/data without it
"KUN_DATA_DIR",
// Nowledge Mem's config folder (its remote_llm.json), and where its
// backend listens (the nmem CLI's), 127.0.0.1:14242 without it
"NMEM_APP_CONFIG_DIR",
"NMEM_API_URL",
// AstrBot's root, the folder holding its data/ (else ~/.astrbot, the desktop app's)
"ASTRBOT_ROOT",
// Dim alpha's folder (dima), ~/.dimcode-alpha without it
@@ -170,7 +174,7 @@ var Vars = []string{
var NotPaths = map[string]bool{
"PI_PROFILE": true, "OMP_PROFILE": true,
"WINDSURF_API_SERVER_URL": true, "ZCODE_CREDENTIAL_SECRET": true,
"AGY_LLM_GATEWAY_URL": true,
"AGY_LLM_GATEWAY_URL": true, "NMEM_API_URL": true,
"PI_CONFIG_DIR": true, "OPENCODE_DB": true,
"STEPCODE_CONFIG_DIR": true,
"MAGPIE_ZED_BIN": true, "MAGPIE_ZED_PROCESS_NAMES": true,
+1 -1
View File
@@ -372,7 +372,7 @@ function toneCheck(img) {
swap();
}, { once: true });
}
const pngIcons = new Set(["aigocode", "crush", "zcode", "alma", "hanako", "cindy", "lody", "typesafe", "atomcode", "snow", "mlx-serve", "gpustack", "mothx", "zoo-code", "kimi-code-desktop", "openbot", "avibe", "kun"]);
const pngIcons = new Set(["aigocode", "crush", "zcode", "alma", "hanako", "cindy", "lody", "typesafe", "atomcode", "snow", "mlx-serve", "gpustack", "mothx", "zoo-code", "kimi-code-desktop", "openbot", "avibe", "kun", "nowledge-mem"]);
// 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: 6.3 KiB

+1
View File
@@ -51,6 +51,7 @@ var noLibrary = map[string]string{
"paimon": "not looked at (#5897)",
"shelley": "not looked at (#5897)",
"kun": "not looked at (#5897)",
"nowledge-mem": "a memory app: its own AI only, no skills or MCP servers of an agent's",
"dim": "not looked at (#5897)",
"open-code-review": "a review CLI with its own fixed tools, not a coding agent; whether it reads skills or MCP not looked at",
}