agent-nowledge-mem 0.1.0: pick Nowledge Mem's Default, AI Now and Background models in magpie (#821)

Adds packages/nowledge-mem-agent (@magpie-community/agent-nowledge-mem
0.1.0), a kind: agent registry entry and a row in the README's Agents table.
Picking a magpie model for the "Nowledge Mem / AI Now" agent points
Nowledge's Default, AI Now and Background purposes at one native
`magpie:nowledge-agent` provider instance; disconnecting restores what the
user had. Distinct from packages/nowledge-mem (gateway recall/capture).

The descriptor (nowledge-mem.agent.js) records the selection; a
dependency-free Bun main syncs it through Nowledge's /remote-llm/* routes
with a journal, manual-edit detection, a restore phase, a pid lock and 0600
atomic writes. Remote backends need HTTPS with a key, redirects are
refused, and unchanged remote polls back off to 30s.

Reviewed head d3b6e3937b371dea24839fe602818c4e6aa4d03d, merged onto
origin/main 049295f5 (clean). Run on mote (macOS) and WSL2 Ubuntu 24.04,
Bun 1.4.2, HOME=$(mktemp -d) each run:
- bun test packages/nowledge-mem-agent: 28 pass, 0 fail (both machines)
- bun scripts/check.mjs nowledge-mem-agent: ok (it skips agent hooks)
- bun scripts/check.mjs: exit 0
- repo-root bun test: 6608 pass, 20 skip, 0 fail (479 files)

Broken by hand, one at a time, each red on the named test:
redirect: 'error'; the quiet-period return; the remote backoff skip;
!referenced before provider removal; defaultRestored before turning
Remote off; the native provider_type check; the per-purpose shape check;
the sandbox's XDG containment; the sandbox's agent-home deletes; the
sandbox's HOME check (its two halves together; each alone is covered by
the other).

Not tried by the reviewer: a real Nowledge Mem app or nmem (the author
reports a contract run on Nowledge 0.10.115), the opt-in smoke and
contract scripts, the runtime inside magpie's plugin host, Windows.
This commit is contained in:
Alexhang1314520
2026-11-07 12:45:50 +08:00
committed by GitHub
parent b475f33187
commit 090b46ba4f
23 changed files with 1227 additions and 0 deletions
+1
View File
@@ -269,6 +269,7 @@ it off puts the config back.
| [pig](packages/pig) | [PiG](https://github.com/MichaelKinsy/PiG): Magpie's endpoint and model catalog in `~/.pig/agent/models.json`, and the model PiG starts on (`defaultProvider`/`defaultModel` in `settings.json`) picked on the Agents page |
| [type4me](packages/type4me) | [Type4Me](https://github.com/joewongjc/type4me), macOS voice input: `~/Library/Application Support/Type4Me/magpie-agent.json`, for its LLM post-processing |
| [opencodereview](packages/opencodereview) | [Open Code Review](https://github.com/alibaba/open-code-review) (`ocr`): `~/.opencodereview/config.json` as a custom Anthropic provider, so `ocr review` / `ocr scan` run on magpie's models |
| [nowledge-mem-agent](packages/nowledge-mem-agent) | [Nowledge Mem / AI Now](https://mem.nowledge.co/): choose Default, AI Now and Background models through Magpie, with recovery journaling; separate from the Nowledge memory recall/capture gateway plugin |
```sh
magpie plugin add @magpie-community/agent-<name>
+11
View File
@@ -0,0 +1,11 @@
# Changelog
## 0.1.0 — 2026-11-07
- Add a Magpie Agent row for Nowledge Mem / AI Now.
- Synchronize Default, AI Now and Background through a dedicated native Magpie provider instance.
- Preserve original assignments in a recovery journal; protect manual changes and recover interrupted operations.
- Include private state files, separate backend authentication, CLI diagnostics and emergency restore.
- Provide credential-free unit/HTTP tests, an opt-in actual-Magpie smoke test and a restricted Nowledge API contract check.
Compatibility verified with Magpie 0.1.3212 and Nowledge Mem 0.10.115. Real paid inference, other operating systems and subsequent Nowledge versions are outside the first release's validation.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+104
View File
@@ -0,0 +1,104 @@
# Nowledge Mem / AI Now Agent
Select a model in **Magpie → Agents → Nowledge Mem / AI Now** for Nowledge's **Default, AI Now and Background** assignments. Magpie owns upstream accounts and routing; Nowledge connects to one dedicated native Magpie provider instance.
[中文说明](README.zh-CN.md)
This differs from [`@magpie-community/gateway-nowledge-mem`](../nowledge-mem): that package recalls memories/Context Bundles for other harnesses and optionally imports conversations. This Agent controls the models **Nowledge itself uses**, performs no recall/capture, and needs no gateway memory plugin. Its directory is `nowledge-mem-agent` because `packages/nowledge-mem` already contains that separate package.
## Connect
```sh
magpie plugin add @magpie-community/agent-nowledge-mem
magpie nowledge-mem <provider/model>
```
Or add this complete folder through Plugins → Add plugin. Install the whole package: `nowledge-mem.agent.js` runs in moejs and `main: index.mjs` runs the bridge in Magpie's Bun host. No runtime dependencies or installation scripts.
Keep both applications running. Local changes settle within two polls, normally 2–4 seconds. Start a new AI Now conversation; existing conversations or AI Identities with explicit overrides can keep their own models. Choose a tool-capable chat model.
The provider instance is `magpie:nowledge-agent`, displayed as **Magpie · Nowledge Agent**. Existing providers and credentials are preserved. The gateway URL and Agent key come from `connect`; full `provider/model` or `group/name` identifiers are sent unchanged, without a LiteLLM prefix.
Default, AI Now and Background share the selected model. Connection enables Remote mode; disconnection restores the original mode when still owned. Explicit embedding, OCR/vision and decision assignments are untouched; inherited vision follows Default.
The icon is Nowledge's official [favicon](https://mem.nowledge.co/favicon.png), used for identification. This is a third-party adapter.
## Backend and credentials
Default backend: `http://127.0.0.1:14242`. Save custom connection settings in `~/.config/magpie-nowledge-mem/adapter.json`:
```json
{
"apiUrl": "https://your-mem.example.com",
"apiKeyFile": "~/.config/magpie-nowledge-mem/nowledge.key",
"pollMs": 2000
}
```
The key file contains the **Nowledge backend access key**, separate from Magpie's gateway key; restrict it to your user. `NMEM_API_URL` and `NMEM_API_KEY` also work. Explicit connection fields override environment values; Magpie plugin options override the file. GUI applications may not inherit shell environment variables. The standalone CLI does not read Magpie's saved plugin options, so use the shared adapter file for recovery.
Authenticated non-loopback backends require HTTPS. Redirects are rejected, and diagnostics omit server response bodies. Use the actual backend address shown by Nowledge. Across machines, Magpie's gateway address must be reachable from the Nowledge server; loopback always refers to that server's own machine. Hosted Nowledge Cloud workspaces manage their models and are outside scope.
Local configuration is checked every two seconds. For remote backends, unchanged successful checks back off to at most one every 30 seconds. The local selection file is still polled at the configured interval, so a new selection promptly restarts the quiet-period check.
## Disconnect, uninstall and recover
Disconnect the **Agent row** before disabling/removing the plugin or quitting Magpie. Keep the plugin and Nowledge running until restoration finishes:
```sh
magpie nowledge-mem default
```
If the package or host is removed first, asynchronous restoration is not guaranteed. When the selection file disappears while the host is alive, the loop treats it as a disconnect. If already removed, obtain a checkout/extracted copy of this package and run:
```sh
node cli.mjs status
node cli.mjs restore
node cli.mjs sync
```
Bun can run these commands too. `restore` restores still-owned settings and pauses the current selection; another model selection or explicit `sync` resumes management. Use the original backend URL and authentication.
**Keep `~/.config/magpie-nowledge-mem/state.json` until recovery completes.** It records original assignments and intended/applied writes, not existing provider secrets. Writes are atomic and `0600`, with a pid lock; the adapter directory and selection file permissions are tightened.
Manual purpose edits are retained and reported as conflicts. Changed providers and providers referenced by a manually selected purpose are retained. If the original default was empty, Nowledge can clear it only by removing this provider; new references can prevent that. An actionable error retains the journal until the conflict is resolved. Do not delete it to hide an incomplete restore.
The API exposes only `has_api_key`, so replacement of an existing instance's key is not detectable. Disconnect before editing that credential. There is no conditional-write API; a small external read/write race remains possible.
## Compatibility and the REST contract
Last actual create/remove contract check: **Nowledge Mem 0.10.115**, official desktop Rust service, **2026-11-07**. A temporary instance was removed, Remote mode was preserved, and original assignments were restored. The installed `nmem` CLI also reports `0.10.115`.
`magpie` is a native type shipped by that Nowledge version. This package does not register it. Its bundled Providers UI contains `providerType: magpie`; its bundled client declares:
| Endpoint | Purpose |
| --- | --- |
| `GET /remote-llm/config` | Masked providers and explicit/effective purposes |
| `POST /remote-llm/config` | Save the independent instance with `provider_type: magpie` |
| `POST /remote-llm/purpose` | Assign `default`, `ai_now`, `background` |
| `POST /remote-llm/enabled` | Change Remote mode |
| `POST /remote-llm/provider/remove` | Remove an unchanged, unreferenced owned instance |
The evidence is the official installed assets `remote-routes-DB7HdQZR.js`, `client-yS6RTdNt.js`, `settings-view-D0HsZ7_I.js`, plus live API tests. These routes are **absent from the served OpenAPI document**. The public [embedding provider guide](https://mem.nowledge.co/docs/embedding-providers) also lists Magpie; the general [provider](https://mem.nowledge.co/docs/llm-providers) and [CLI](https://mem.nowledge.co/docs/cli) guides do not describe this full private routing contract.
A missing route, incompatible config schema, or failure to retain the native `magpie` type stops the adapter visibly before purpose assignments, preserving recovery data. It does not silently substitute another provider type. Later Nowledge versions remain unverified.
Actual host smoke: **Magpie 0.1.3212 on macOS**. Desktop-only install detection on the tested Mac uses `~/Library/Application Support/co.nowledge.mem.desktop`, the installed bundle's data directory; `nmem` on PATH is another signal. Other OS-specific desktop paths are not asserted. Linux/server installs can expose `nmem` on PATH; Windows desktop-only detection remains unverified.
## Development
```sh
bun test ./*.test.mjs
MAGPIE_BIN=/path/to/magpie node tests/magpie-smoke.mjs
node tests/nowledge-contract.mjs --read-only
```
Tests use `bun:test` next to source. The optional smoke test gives **child processes their own HOME/USERPROFILE, XDG config/cache/data and AppData directories**, disables account discovery, clears known agent path overrides, and refuses the caller's real home or escaped directories. It uses fake Nowledge/vendor endpoints, sends no paid inference, and leaves the caller's environment unchanged.
The contract script's default mode temporarily creates/removes a provider and refuses an enabled backend or configured providers. Read-only mode checks version, schema and an existing native Magpie instance with no writes. Do not use mutating mode on a live configured workspace.
The repository-root command `bun scripts/check.mjs nowledge-mem-agent` checks registry syntax/classification; its upstream checker skips Agent hook loading. Package tests and the optional host smoke cover behavior. See [VALIDATION.md](VALIDATION.md) for limits and mutation checks.
References: [Magpie plugins](https://usemagpie.ai/docs/zh/plugins), [gateway integration](https://usemagpie.ai/docs/integrate), [community publishing](https://github.com/magpie-community/plugins#publishing).
MIT license.
+132
View File
@@ -0,0 +1,132 @@
# Nowledge Mem / AI Now — Magpie Agent 插件
在 **Magpie → Agent → Nowledge Mem / AI Now** 选择一个模型,同步到 Nowledge 的 **Default、AI Now、Background** 三项用途。上游账号、订阅、密钥、模型路由和故障切换由 Magpie 管理;Nowledge 只连接 Magpie 网关。
这是使用官方 Agent 扩展协议的第三方插件,不是 Nowledge 的 MCP 记忆插件。它不会把 Nowledge 变成 Magpie 的模型供应商。
与社区现有的 `@magpie-community/gateway-nowledge-mem` 不同:本插件管理 **Nowledge 自己使用哪个模型**;现有 gateway 插件为其他 Agent 召回记忆、注入 Context Bundle,并按需导入对话。本插件不依赖该 gateway 插件,也不执行记忆召回或对话导入。
## 安装
要求:已运行的 Magpie、Nowledge Mem 桌面版或自托管服务;Nowledge 需要支持 `magpie` 类型和独立 provider 实例。开发与验证版本见 [VALIDATION.md](VALIDATION.md)。Bun 由 Magpie 的插件宿主管理,没有 npm 依赖和安装脚本。独立诊断命令需要 Node.js 22+,或使用 `bun cli.mjs`。
1. 在 Magpie 的 **插件 → 添加插件** 中填写 `@magpie-community/agent-nowledge-mem`,或选择下载解压后包含本文件和 `package.json` 的完整文件夹。
2. 确认 Magpie 的上游 provider 已经登录并有可用模型。
3. 打开 **Agent → Nowledge Mem / AI Now**,选择支持工具调用的模型或路由组。
4. 保持 Magpie 和 Nowledge 运行,通常等待 2–4 秒。Nowledge 的 Providers 页面会出现独立的 **Magpie · Nowledge Agent**,三项用途会使用你刚选的模型。开始一个新对话验证实际回答。
有 `magpie` 命令时可以安装社区包。使用版本号固定已测试版本:
```sh
magpie plugin add @magpie-community/agent-nowledge-mem@0.1.0
```
也可在解压后的插件目录执行:
```sh
magpie plugin add "$PWD"
magpie nowledge-mem <供应商/模型>
```
macOS 未把 Magpie 加入 PATH 时,可用应用中的命令:
```sh
/Applications/magpie.app/Contents/MacOS/magpie plugin add "$PWD"
```
不要只导入 `nowledge-mem.agent.js`:这个插件同时需要 `main` 指定的 Bun 同步模块。不要导入 `.tgz` 文件作为本地目录;使用解压后的完整文件夹。
## 实际管理范围
| 项目 | 行为 |
| --- | --- |
| Default、AI Now、Background | 同步为 Magpie 当前选中的同一个模型 |
| Remote / Local 模式 | 首次接入启用 Remote;正常断开恢复接入前的值 |
| 其他 provider 及其密钥 | 不覆盖,使用独立实例 `magpie:nowledge-agent` |
| Embedding、Vision / OCR、Fast decisions | 不写它们的用途配置;**原本跟随 Default 的 Vision 也会随 Default 改变** |
| 已打开的对话、单次会话或 AI Identity 的显式模型覆盖 | 可能继续使用自己的模型;请开始新对话并检查其模型选择 |
| 模型能力 | 同步已知 context window、输出上限和图片能力;不臆造未知能力 |
网关 URL 和 Agent 专属 key 来自 Magpie 的 `connect` 入参,未固定网关端口,也不需要复制上游 key。使用完整 `provider/model` 或 `group/name`,不增加 `openai/` 前缀。请求采用 Chat Completions,Magpie 负责向上游协议转换。
## Nowledge 地址与认证
默认连接本机 `http://127.0.0.1:14242`。如果你的 Nowledge 使用其他端口、远程地址或访问 key,请创建:
`~/.config/magpie-nowledge-mem/adapter.json`
```json
{
"apiUrl": "https://your-mem.example.com",
"apiKeyFile": "~/.config/magpie-nowledge-mem/nowledge.key",
"pollMs": 2000
}
```
`nowledge.key` 中只放 **Nowledge 服务的访问 key**,并设置文件权限为仅自己可读写。它与 Magpie 的网关 key 是两套凭据。不要把任何 key 提交到插件项目。
也支持宿主环境变量 `NMEM_API_URL`、`NMEM_API_KEY`;显式 `apiUrl` / `apiKeyFile` 优先。GUI 启动的应用未必继承终端的环境变量,优先使用上述文件。Magpie 的插件选项也支持相同字段,选项优先于文件。
独立 CLI 不会自动读取 Magpie 中保存的插件选项;使用诊断/恢复命令时,请把相同连接参数放入上述 `adapter.json` 或 CLI 的环境变量。
远程 Nowledge 必须使用 HTTPS 才能发送访问 key;HTTP 仅允许本机回环地址。接口重定向被拒绝。请使用 Nowledge 实际展示的连接地址,不推测远程 `/remote-api` 或其他部署路径。
Nowledge Mem **Cloud 托管工作区** 的模型由服务管理,不属于本插件适用范围。自托管 Nowledge 与 Magpie 分处两台机器时,还必须保证写入 Nowledge 的 Magpie 网关地址能从 Nowledge 服务所在机器访问;`127.0.0.1` 始终指服务自身。单独改 `apiUrl` 不能解决网关可达性。
## 状态与恢复
在插件目录执行:
```sh
node cli.mjs status
node cli.mjs sync
node cli.mjs restore
```
- `status`:显示后端地址、三项用途、是否有恢复日志和上次同步结果,不输出 key。
- `sync`:立即应用当前选择,并解除紧急恢复留下的暂停。
- `restore`:恢复仍由插件管理的设置;暂停当前选择,防止仍在运行的宿主马上重新接管。以后在 Magpie 改选模型,或执行 `sync`,可再次接管。
正常断开请在 **Magpie 的 Agent 行**关掉连接,或执行:
```sh
magpie nowledge-mem default
```
等待同步后,用 `node cli.mjs status` 确认 `recoveryPending` 为 `false`,再停用或卸载插件。**直接停用插件、退出 Magpie 或删除插件目录,会同时停止 Bun 同步模块,无法保证当时自动回滚。** 如果已经这么做,保留插件文件,启动 Nowledge 后执行 `node cli.mjs restore`。
恢复数据保存在 `~/.config/magpie-nowledge-mem/state.json`,状态在同目录 `status.json`。**恢复前不要删除 `state.json`。** 它记录原用途及插件自己的写入,不保存旧 provider 的 API key。写入采用权限 `0600` 的临时文件及原子替换;同步加进程锁,崩溃后保留日志供重试。同步宿主会将插件自己的标准目录收紧为 `0700`,并在读取选择文件前将其权限收紧为 `0600`。
如果你在 Nowledge 中手动修改了已接管的用途,插件会保留修改,并在日志/状态里报告 `conflicts`,以后不再覆盖该用途。如果手动改过插件 provider 的连接字段,或其他用途正在引用它,恢复时会保留该 provider。恢复完成后需要你自行核对再删除;不会直接覆盖或删除。
提供商列表只返回 `has_api_key`,无法判断用户是否手动替换了同一实例里的 key。因此请在 Magpie 管理期间通过 Magpie 切换连接,或先断开 Agent 后再编辑该 provider 的凭据。后端 API 没有条件写入机制;外部同时写设置时存在读取与写入之间的短暂竞争窗口。
## 排障
- Agent 未出现:确认安装的是完整文件夹,包中有 `package.json` 的 `magpie.agent` 和 `main`;检查 `nmem` 是否在 PATH;在 Magpie 里关开插件加载新版本。
- 选模型后未生效:打开 Nowledge,执行 `node cli.mjs status`,查看 Magpie 插件宿主日志;修改设置后需要让选择文件稳定一个轮询周期。
- `HTTP 401/403`:配置 Nowledge 访问 key 或核对服务权限;不能用上游模型 key 代替。
- `already exists`:同名独立实例已存在。先检查恢复日志并执行 `restore`;对于用户保留的实例,手动更名或删除后再连接,插件不会覆盖它。
- 没有默认 provider 但已有其他 provider:请先在 Nowledge 选一个默认 provider,保证断开时有可恢复目标。
- 后端离线:保持文件和恢复日志,恢复服务后自动重试。无法解析的 JSON 不会被当成断开。
- 命令行单次执行不会持久运行同步模块;持续同步需要 Magpie 应用或 `magpie serve` 保持运行。
## 开发与官方依据
```sh
bun test ./*.test.mjs
bun run check
MAGPIE_BIN=/Applications/magpie.app/Contents/MacOS/magpie node tests/magpie-smoke.mjs
npm pack
```
烟雾测试使用独立 Magpie 配置、临时插件副本及模拟 HTTP 服务,不调用真实模型。
- [Magpie 插件开发:Agent 插件](https://usemagpie.ai/docs/zh/plugins):moejs Agent 模块、`connect`、Bun `main` 同步方案、键级恢复。
- [Magpie 应用接入指南](https://usemagpie.ai/docs/integrate):动态模型目录、完整模型 id、网关协议及身份识别。
- [Nowledge LLM Providers](https://mem.nowledge.co/docs/llm-providers):用途、OpenAI 兼容接口、上下文窗口。
- [Nowledge CLI](https://mem.nowledge.co/docs/cli):provider 与用途配置。
Nowledge 的 provider 管理路由当前未包含在其公开 OpenAPI 中。本实现按 **0.10.115 官方应用附带的客户端代码**核对 REST 路由与请求体,并对实际运行服务检查 provider 的创建/删除行为。后续 Nowledge 版本改变这些接口时可能需要更新适配器。
许可证:MIT。
+48
View File
@@ -0,0 +1,48 @@
# Validation
Date: 2026-11-07 (Asia/Hong_Kong).
## Package checks
`bun test packages/nowledge-mem-agent`: **28 passed, 0 failed** on Bun 1.3.5/macOS. Tests use `bun:test` next to the source.
Full repository validation with the reviewer's **Bun 1.4.2**, under an isolated child home: **6614 passed, 9 skipped, 0 failed**, 479 files, 212.01 seconds. The older local Bun does not honor the repository's test exclusions and was not used as the full-suite result.
Coverage includes connection/switch/disconnection, original purposes and Remote mode, manual edits, partial failures, first-provider activation, legacy empty placeholders, journal/backend binding, locks, private atomic writes, malformed selections, emergency-restore pause, remote polling backoff, and incompatible REST responses.
The redirect case uses two HTTP servers on different hosts (`127.0.0.1` and `localhost`); it checks rejection, zero visits to the target and no received credential. The provider-reference test leaves its connection fingerprint unchanged so only the external reference protects it. The default-mode test changes Default during Background's restoration and checks Remote remains enabled. Poll-clock/file-read injection tests the quiet period without sleeping.
## Mutation checks
Each guard was removed alone, the package suite run in a fresh process, then the original source restored:
| Removed guard | Result |
| --- | --- |
| `redirect: 'error'` | 1 failing test |
| Quiet-period early return | 2 failing tests |
| `!referenced` before provider removal | 1 failing test |
| `defaultRestored` before disabling Remote | 1 failing test |
Restored source: 28 passed. `bun scripts/check.mjs nowledge-mem-agent` validates registry syntax/classification; it skips loading Agent hooks.
## Actual Magpie host smoke
`MAGPIE_BIN=/Applications/magpie.app/Contents/MacOS/magpie node packages/nowledge-mem-agent/tests/magpie-smoke.mjs` passed with Magpie **0.1.3212**.
Every child process receives its own HOME/USERPROFILE, XDG config/cache/data and AppData roots in a private temporary directory. Guards reject the real caller/account home and escaped directories; known agent-home overrides are removed. The caller's environment is not mutated. Account discovery is disabled. The descriptor is loaded unchanged; tilde paths resolve in the sandbox home.
Confirmed: Agent registration, sandboxed `connect`, dynamic gateway address/key, Bun-host synchronization of three purposes, model change, full disconnect recovery and `0600` selection file. Fake Nowledge and vendor endpoints received **zero model calls**. No live agent configuration is used.
## Nowledge contract evidence
Actual provider create/remove contract last run: **Nowledge Mem 0.10.115 on 2026-11-07**. The independent native `magpie:<id>` instance, context/output metadata, key masking, first-provider auto-activation and preserved Remote mode were checked. The temporary provider was removed and original assignments restored.
For this revision, `node tests/nowledge-contract.mjs --read-only` also passed against the running **0.10.115** service: version from OpenAPI metadata, required purpose fields and an existing `provider_type: magpie` confirmed with **no writes**. The opt-in mutating mode refuses enabled/configured backends.
The provider management routes are not present in that version's public OpenAPI. They were checked against its official installed client assets and live service; the exact routes and evidence are in README. An incompatible config or a backend that coerces the native type stops before purpose writes, with a visible error and retained journal.
## Limits
No actual paid inference, multi-turn tool use, long-context compaction, Windows desktop detection or subsequent Nowledge release is claimed as verified. macOS desktop data-directory detection was checked; other platforms retain PATH-based CLI detection. Uninstall before disconnecting can stop the bridge before restore: keep its journal and use the documented recovery CLI. External references can prevent clearing an originally empty default. These limits are explicit in README.
No user credentials, provider keys or Nowledge data are part of this package. No runtime dependencies or install scripts.
@@ -0,0 +1,14 @@
import {test,afterEach} from 'bun:test';
import assert from 'node:assert/strict';
test('Agent writes the gateway supplied by Magpie and keeps model ids intact', async () => {
const { agent, connect } = await import('./nowledge-mem.agent.js');
assert.equal(agent.model, 'model');
const values = connect({gateway: {v1:'http://127.0.0.1:3999/v1', key:'agent-secret'}, model: {id:'group/daily', context:100000, output:16000, images:true}});
assert.equal(values['gateway.baseURL'], 'http://127.0.0.1:3999/v1');
assert.equal(values['gateway.key'], 'agent-secret');
assert.equal(values['metadata.context'], 100000);
assert.equal(values['metadata.output'], 16000);
assert.equal(values['metadata.images'], true);
assert.equal(agent.prefix, undefined);
});
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env node
import { settings, runOnce, status } from './lib/runtime.mjs';
const command=process.argv[2] || 'status';
if(!['status','sync','restore'].includes(command)) {
console.error('Usage: node cli.mjs [status|sync|restore]');process.exitCode=2;
} else {
try {
const config=await settings();
const result=command==='status'?await status(config):await runOnce(config,{restore:command==='restore',resume:command==='sync'});
console.log(JSON.stringify(result,null,2));
} catch(error) {
console.error(error instanceof SyntaxError?'Invalid JSON configuration or selection.':error.message);process.exitCode=1;
}
}
+9
View File
@@ -0,0 +1,9 @@
import { startAdapter } from './lib/runtime.mjs';
const STARTED=Symbol.for('magpie.nowledge-mem.adapter.v1');
// Only export the plugin: Magpie treats every exported function as a plugin.
export default async function NowledgeMemAgent(input,options) {
if(!globalThis[STARTED]){await startAdapter(input,options);globalThis[STARTED]=true;}
return {};
}
+25
View File
@@ -0,0 +1,25 @@
export function normalizeURL(value) {
const url = new URL(value);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error('Use an HTTP(S) URL without embedded credentials, query or fragment.');
return url.toString().replace(/\/+$/, '');
}
export function createAPI({apiUrl, apiKey, timeoutMs = 10000}) {
const base = normalizeURL(apiUrl);
const hostname = new URL(base).hostname;
if (apiKey && new URL(base).protocol !== 'https:' && !['127.0.0.1','localhost','[::1]'].includes(hostname)) throw new Error('A remote Nowledge backend with an API key requires HTTPS.');
return async (route, body) => {
const response = await fetch(`${base}${route}`, {
method: body === undefined ? 'GET' : 'POST',
headers: { 'content-type': 'application/json', ...(apiKey ? {authorization: `Bearer ${apiKey}`} : {}) },
...(body === undefined ? {} : {body:JSON.stringify(body)}),
signal: AbortSignal.timeout(timeoutMs),
redirect: 'error',
});
// Do not include server bodies in errors: some gateways echo credentials.
if (!response.ok) throw new Error(`Nowledge ${route}: HTTP ${response.status}`);
const result = await response.json();
if (result?.success === false) throw new Error(`Nowledge ${route}: operation rejected`);
return result?.config && typeof result.config === 'object' ? result.config : result;
};
}
+49
View File
@@ -0,0 +1,49 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
export async function readJSON(file) {
try { return JSON.parse(await fs.readFile(file, 'utf8')); }
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
}
export async function writeJSON(file, value) {
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
const temp = `${file}.${randomUUID()}.tmp`;
try {
const handle = await fs.open(temp, 'wx', 0o600);
try { await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`); await handle.sync(); }
finally { await handle.close(); }
await fs.rename(temp, file);
} finally { await fs.rm(temp, { force: true }); }
}
export async function withLock(stateFile, run) {
const lock = `${stateFile}.lock`;
await fs.mkdir(path.dirname(lock), { recursive: true, mode: 0o700 });
let handle;
for (let attempt = 0; attempt < 2; attempt++) {
try { handle = await fs.open(lock, 'wx', 0o600); break; }
catch (error) {
if (error.code !== 'EEXIST') throw error;
let stale = false;
try {
const owner = await readJSON(lock);
if (Number.isSafeInteger(owner?.pid) && owner.pid > 0) {
try { process.kill(owner.pid, 0); }
catch (e) { if (e.code === 'ESRCH') stale = true; }
}
} catch (e) {
if (e.code === 'ENOENT') continue;
// A process can die between creating and filling the lock.
if (e instanceof SyntaxError) stale = Date.now() - (await fs.stat(lock)).mtimeMs > 30000;
else throw e;
}
if (!stale) throw new Error('Another Nowledge sync is running; retry shortly.');
await fs.rm(lock, { force: true });
}
}
if (!handle) throw new Error('Could not acquire Nowledge sync lock.');
try { await handle.writeFile(JSON.stringify({ pid: process.pid })); return await run(); }
finally { await handle.close(); await fs.rm(lock, { force: true }); }
}
+105
View File
@@ -0,0 +1,105 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { homedir } from 'node:os';
import { createHash } from 'node:crypto';
import { readJSON, writeJSON } from './files.mjs';
import { synchronize } from './sync.mjs';
import { createAPI, normalizeURL } from './api.mjs';
export const defaultDirectory = path.join(homedir(),'.config','magpie-nowledge-mem');
const expand = p => path.resolve(p.startsWith('~/') ? path.join(homedir(),p.slice(2)) : p);
const hash = text => createHash('sha256').update(text).digest('hex');
export async function settings(options = {}) {
const file = process.env.MAGPIE_NOWLEDGE_CONFIG || path.join(defaultDirectory,'adapter.json');
const local = await readJSON(expand(file)) || {};
const config = {...local,...options};
const selectionFile = expand(config.selectionFile || path.join(defaultDirectory,'selection.json'));
const directory = path.dirname(selectionFile);
const apiUrl = normalizeURL(config.apiUrl || process.env.NMEM_API_URL || 'http://127.0.0.1:14242');
let apiKey = process.env.NMEM_API_KEY || '';
if (config.apiKeyFile) apiKey = (await fs.readFile(expand(config.apiKeyFile),'utf8')).trim();
if (typeof config.pollMs !== 'undefined' && (!Number.isSafeInteger(config.pollMs) || config.pollMs<500 || config.pollMs>60000)) throw new Error('pollMs must be an integer from 500 to 60000.');
return {apiUrl,apiKey,selectionFile,stateFile:path.join(directory,'state.json'),statusFile:path.join(directory,'status.json'),pauseFile:path.join(directory,'paused.json'),pollMs:config.pollMs || 2000,timeoutMs:10000};
}
export async function selectionText(file) {
try { await fs.chmod(file,0o600);return await fs.readFile(file,'utf8'); }
catch(error) { if(error.code==='ENOENT')return '';throw error; }
}
export async function runOnce(config, {restore=false,resume=false}={}) {
const text = await selectionText(config.selectionFile);
if(restore) await writeJSON(config.pauseFile,{selectionHash:hash(text)});
if(resume) await fs.rm(config.pauseFile,{force:true});
const pause=await readJSON(config.pauseFile);
if(!restore && pause?.selectionHash===hash(text)) return {status:'paused',conflicts:[]};
if(pause&&!restore) await fs.rm(config.pauseFile,{force:true});
const selection=restore||!text.trim()?null:JSON.parse(text);
const result=await synchronize(selection,config);
const last=await readJSON(config.statusFile);
const {updatedAt,...previous}=last || {};
if(JSON.stringify(previous)!==JSON.stringify(result)) await writeJSON(config.statusFile,{...result,updatedAt:new Date().toISOString()});
return result;
}
export async function status(config) {
const journal=await readJSON(config.stateFile);
const last=await readJSON(config.statusFile);
const paused=!!await readJSON(config.pauseFile);
const api=createAPI(config);
const c=await api('/remote-llm/config');
return {apiUrl:config.apiUrl,selectionFile:config.selectionFile,recoveryPending:!!journal,paused,last,enabled:c.enabled,purposes:Object.fromEntries(['default','ai_now','background'].map(p=>[p,{provider:c.purposes?.[p]?.provider??null,model:c.purposes?.[p]?.model??null}]))};
}
export async function startAdapter(input, options, dependencies={}) {
const resolveSettings=dependencies.settings||settings;
const readSelection=dependencies.selectionText||selectionText;
const synchronizeOnce=dependencies.runOnce||runOnce;
const schedule=dependencies.setTimeout||setTimeout;
const cancel=dependencies.clearTimeout||clearTimeout;
const now=dependencies.now||Date.now;
const initial=await resolveSettings(options);
const directory=path.dirname(initial.selectionFile);
await fs.mkdir(directory,{recursive:true,mode:0o700});
// Only tighten our own standard directory; do not chmod arbitrary parents
// supplied by an integrator through selectionFile.
if(directory===defaultDirectory)await fs.chmod(directory,0o700);
let stopped=false, timer, previousText, previousMessage='',lastResult,nextRemoteSync=0,remoteDelay=initial.pollMs;
const log=(level,message)=>{
if(message===previousMessage)return;
previousMessage=message;
try { input?.client?.app?.log?.({body:{service:'nowledge-agent',level,message}})?.catch?.(()=>{}); } catch {}
};
const tick=async()=>{
if(stopped)return;
let delay=2000;
let remote=false;
try {
const config=await resolveSettings(options);delay=config.pollMs;
remote=!['127.0.0.1','localhost','[::1]'].includes(new URL(config.apiUrl).hostname);
const text=await readSelection(config.selectionFile);
// Magpie patches individual keys. Wait for a full quiet polling period
// before interpreting a newly changed selection.
if(text!==previousText){previousText=text;nextRemoteSync=0;remoteDelay=config.pollMs;lastResult=undefined;return;}
if(remote&&now()<nextRemoteSync)return;
const result=await synchronizeOnce(config);
if(remote){
const signature=JSON.stringify(result);
remoteDelay=signature===lastResult?Math.min(Math.max(config.pollMs,30000),remoteDelay*2):config.pollMs;
nextRemoteSync=now()+remoteDelay;lastResult=signature;
}
log(result.conflicts.length?'warn':'info',`nowledge-agent: ${result.status}${result.model?` · ${result.model}`:''}${result.conflicts.length?` · conflicts: ${result.conflicts.join(', ')}`:''}`);
} catch(error) {
if(remote){remoteDelay=Math.min(Math.max(delay,30000),Math.max(delay,remoteDelay*2));nextRemoteSync=now()+remoteDelay;}
// Errors from our API wrapper contain no server body or credentials.
const message=error instanceof SyntaxError?'Selection/config JSON is incomplete; waiting for a valid file.':error.code==='ENOENT'?'A configured credential file is missing.':error.message;
log('warn',`nowledge-agent: ${message}`);
} finally {
if(!stopped){timer=schedule(tick,delay);timer.unref?.();}
}
};
// Init must finish before a backend is available; no network in this call.
timer=schedule(tick,0);timer.unref?.();
return ()=>{stopped=true;cancel(timer);};
}
@@ -0,0 +1,25 @@
import { normalizeURL } from './api.mjs';
export function selectionFrom(value) {
if (value === null) return null;
// Magpie restores keys individually; a completely empty object is disconnect.
if (value && typeof value === 'object' && !Array.isArray(value) && !value.model && !value.gateway?.key && !value.gateway?.baseURL) return null;
if (!value || typeof value !== 'object' || typeof value.model !== 'string' || !value.model.trim() || typeof value.gateway?.key !== 'string' || !value.gateway.key.trim() || typeof value.gateway.baseURL !== 'string') throw new Error('Incomplete Magpie selection; refusing to change Nowledge.');
const baseURL = normalizeURL(value.gateway.baseURL);
if (!baseURL.endsWith('/v1')) throw new Error('Magpie gateway baseURL must end in /v1.');
return {model:value.model, gateway:{baseURL,key:value.gateway.key}, metadata:value.metadata ?? {}};
}
export function providerConfig(selection, provider) {
const n = selection.metadata;
const body = {
enabled:true, provider, provider_type:'magpie', display_name:'Magpie · Nowledge Agent',
model:selection.model, api_key:selection.gateway.key, api_base:selection.gateway.baseURL,
api_format:'chat_completions', temperature:0.7, max_tokens:8192, timeout:600,
extra_params:{no_activate:true, preserve_enabled:true},
};
if (Number.isSafeInteger(n.context) && n.context > 0) body.context_window = n.context;
if (Number.isSafeInteger(n.output) && n.output > 0) body.max_tokens = Math.min(8192,n.output);
if (typeof n.images === 'boolean') body.extra_params._nmem_provider_capabilities = {vision:n.images,vision_model:{model:selection.model,supports_image_input:n.images}};
return body;
}
+137
View File
@@ -0,0 +1,137 @@
import fs from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { createAPI, normalizeURL } from './api.mjs';
import { readJSON, writeJSON, withLock } from './files.mjs';
import { selectionFrom, providerConfig } from './selection.mjs';
const PURPOSES = ['default','ai_now','background'];
const equal = (a,b) => JSON.stringify(a) === JSON.stringify(b);
const pair = (p) => ({provider:p?.provider || null,model:p?.model || null});
function currentPair(config,purpose) {
return pair(config.purposes?.[purpose] ?? (purpose === 'default' ? {provider:config.active_provider || config.provider,model:config.model} : {}));
}
function fingerprint(p) {
if (!p) return null;
return {provider_type:p.provider_type || 'magpie',model:p.model,api_base:p.api_base?.replace(/\/+$/,''),api_format:p.api_format || 'chat_completions',context_window:p.context_window ?? null};
}
function owns(entry,current) {
return !entry.released && [entry.applied,entry.pending, ...(!entry.applied ? [entry.before] : [])].filter(Boolean).some(x=>equal(x,current));
}
function validConfig(config) {
const assignment=p=>p&&typeof p==='object'&&!Array.isArray(p)&&Object.hasOwn(p,'provider')&&Object.hasOwn(p,'model');
if (!config || typeof config.enabled !== 'boolean' || !Object.hasOwn(config,'providers') || Array.isArray(config.providers) || !PURPOSES.every(p=>assignment(config.purposes?.[p]))) throw new Error('Unsupported Nowledge config response; no changes made.');
}
export async function synchronize(rawSelection,options) {
const selection = selectionFrom(rawSelection);
const apiUrl = normalizeURL(options.apiUrl);
if (!options.stateFile) throw new Error('stateFile is required');
return withLock(options.stateFile,async()=>{
let state = await readJSON(options.stateFile);
if (state && (state.version !== 1 || state.apiUrl !== apiUrl)) throw new Error('Recovery journal belongs to a different backend or version; use its original backend.');
if(state && (state.providerId!=='magpie:nowledge-agent' || typeof state.original?.enabled!=='boolean' || !state.provider || !state.enabled || !PURPOSES.every(p=>state.purposes?.[p]?.before))) throw new Error('Invalid recovery journal; preserve it and recover with the original adapter.');
if(state?.phase==='restoring'&&selection) throw new Error('An interrupted restore is pending. Run cli.mjs restore before reconnecting.');
if (!selection && !state) return {status:'disconnected',conflicts:[]};
const api = createAPI({...options,apiUrl});
let config = await api('/remote-llm/config');
validConfig(config);
const save = () => writeJSON(options.stateFile,state);
if (!state) {
const providerId = 'magpie:nowledge-agent';
if (config.providers?.[providerId]) throw new Error(`Provider ${providerId} already exists; refusing to overwrite it.`);
const hasConfiguredProvider=Object.values(config.providers || {}).some(p=>p?.model||p?.has_api_key||p?.api_base);
if (!currentPair(config,'default').provider && hasConfiguredProvider) throw new Error('No default provider is selected, but other configured providers exist. Select an original default in Nowledge first so it can be restored reliably.');
state = {version:1,apiUrl,providerId,original:{enabled:config.enabled,activeProvider:config.active_provider || config.provider || null},purposes:{},provider:{applied:null,pending:null,digest:null},enabled:{before:config.enabled,applied:null,pending:null}};
for (const p of PURPOSES) state.purposes[p] = {before:currentPair(config,p),applied:null,pending:null,released:false};
await save();
}
const conflicts=[];
const markConflict = async(p) => {state.purposes[p].released=true;conflicts.push(p);await save();};
if (selection) {
// Discover manual changes before a provider POST: updating its default
// model may itself affect Nowledge's active default assignment.
for(const p of PURPOSES) {
const e=state.purposes[p];
if(!e.released&&!owns(e,currentPair(config,p)))await markConflict(p);
}
const body=providerConfig(selection,state.providerId);
const wanted=fingerprint(body);
const stored=config.providers?.[state.providerId];
const record=state.provider;
if (stored && ![record.applied,record.pending].filter(Boolean).some(x=>equal(x,fingerprint(stored)))) throw new Error('Managed provider was changed manually; disconnect the Agent and recover before reconnecting.');
const digest=createHash('sha256').update(JSON.stringify(body)).digest('hex');
if(state.purposes.default.released && currentPair(config,'default').provider===state.providerId && digest!==record.digest) throw new Error('Default was changed manually on the managed provider. Disconnect the Agent before changing its model.');
if (!stored || digest !== record.digest || !equal(fingerprint(stored),wanted)) {
// Nowledge may auto-select its first provider, and may update a default
// model along with the provider. Journal that side effect before POST.
for(const p of PURPOSES) {
const e=state.purposes[p];
if(owns(e,currentPair(config,p))) e.pending={provider:state.providerId,model:selection.model};
}
record.pending=wanted;await save();
config=await api('/remote-llm/config',body);
// Read back to use the server's canonical field values.
config=await api('/remote-llm/config');validConfig(config);
const confirmed=config.providers?.[state.providerId];
if (!confirmed || confirmed.provider_type!=='magpie' || confirmed.model !== body.model || confirmed.api_base?.replace(/\/+$/,'') !== body.api_base) throw new Error('Nowledge did not retain the requested native Magpie provider configuration.');
record.applied=fingerprint(confirmed);record.pending=null;record.digest=digest;await save();
}
for (const p of PURPOSES) {
const e=state.purposes[p];
if (e.released) {conflicts.push(p);continue;}
const current=currentPair(config,p);
if (!owns(e,current)) {await markConflict(p);continue;}
const desired={provider:state.providerId,model:selection.model};
if (!equal(current,desired)) {
e.pending=desired;await save();
await api('/remote-llm/purpose',{purpose:p,...desired});
config=await api('/remote-llm/config');
if (!equal(currentPair(config,p),desired)) throw new Error(`Nowledge did not retain the ${p} assignment.`);
}
if(!equal(e.applied,desired)||e.pending) {e.applied=desired;e.pending=null;await save();}
}
const e=state.enabled;
if (!config.enabled && e.applied !== true) {
e.pending=true;await save();await api('/remote-llm/enabled',{enabled:true});e.applied=true;e.pending=null;await save();
} else if (!config.enabled && e.applied === true) conflicts.push('enabled');
return {status:conflicts.length?'conflict':'connected',model:selection.model,conflicts};
}
// Recover per purpose. A journal survives every intermediate step.
state.phase='restoring';await save();
for (const p of PURPOSES) {
const e=state.purposes[p];
const current=currentPair(config,p);
if (e.restored) continue;
if (equal(current,e.before)) {e.restored=true;await save();continue;}
if (!owns(e,current)) {if(!e.released)await markConflict(p);else conflicts.push(p);e.restored=true;await save();continue;}
// The API rejects default=null. Removing our originally-first provider
// clears that default; defer it until the other purposes are restored.
if (p==='default' && !e.before.provider) {e.clearByRemoval=true;await save();continue;}
e.pending=e.before;await save();
await api('/remote-llm/purpose',{purpose:p,...e.before});
config=await api('/remote-llm/config');
if (!equal(currentPair(config,p),e.before)) throw new Error(`Nowledge did not restore ${p}.`);
e.restored=true;e.pending=null;await save();
}
config=await api('/remote-llm/config');
const enabled=state.enabled;
const active=config.active_provider || config.provider || null;
const clearDefault=state.purposes.default.clearByRemoval && owns(state.purposes.default,currentPair(config,'default'));
const defaultRestored=equal(currentPair(config,'default'),state.purposes.default.before) || clearDefault;
// Never switch off remote mode underneath a user's new default provider.
if (defaultRestored && (enabled.applied !== null || enabled.pending !== null) && [enabled.applied,enabled.pending].includes(config.enabled) && config.enabled !== enabled.before) {
await api('/remote-llm/enabled',{enabled:enabled.before});
}
const stored=config.providers?.[state.providerId];
const referenced=Object.entries(config.purposes || {}).some(([name,p])=>p?.provider === state.providerId && !(name==='default'&&clearDefault)) || (active === state.providerId && !clearDefault);
if (stored && !referenced && [state.provider.applied,state.provider.pending].filter(Boolean).some(x=>equal(x,fingerprint(stored)))) await api('/remote-llm/provider/remove',{provider:state.providerId});
else if (stored) conflicts.push('provider-retained');
if(clearDefault) {
const checked=await api('/remote-llm/config');
if(!equal(currentPair(checked,'default'),state.purposes.default.before)) throw new Error('Cannot clear the original empty default while the provider is retained. Remove its new references or restore its original connection fields, then retry restore.');
}
await fs.rm(options.stateFile,{force:true});
return {status:'disconnected',conflicts};
});
}
@@ -0,0 +1,23 @@
// Runs in Magpie's moejs sandbox: no Node/Bun APIs or external imports here.
export const agent = {
id: 'nowledge-mem',
name: 'Nowledge Mem / AI Now',
icon: 'https://mem.nowledge.co/favicon.png',
bin: 'nmem',
dir: '~/Library/Application Support/co.nowledge.mem.desktop',
config: '~/.config/magpie-nowledge-mem/selection.json',
format: 'json',
model: 'model',
ua: ['nowledge', 'nmem'],
notice: 'Syncs Default, AI Now and Background. Keep Nowledge open; start a new chat after a few seconds. Disconnect before uninstalling. 同步 Default、AI Now 和后台任务;保持 Nowledge 运行,等待数秒后开始新对话。卸载前先断开此 Agent。',
};
export function connect({ gateway, model }) {
return {
'gateway.baseURL': gateway.v1,
'gateway.key': gateway.key,
'metadata.context': model.context || null,
'metadata.output': model.output || null,
'metadata.images': typeof model.images === 'boolean' ? model.images : null,
};
}
+51
View File
@@ -0,0 +1,51 @@
{
"name": "@magpie-community/agent-nowledge-mem",
"version": "0.1.0",
"description": "Manage Nowledge Mem Default, AI Now and Background models from Magpie",
"type": "module",
"main": "./index.mjs",
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/nowledge-mem-agent"
},
"homepage": "https://github.com/magpie-community/plugins/tree/main/packages/nowledge-mem-agent",
"bugs": {
"url": "https://github.com/magpie-community/plugins/issues"
},
"files": [
"nowledge-mem.agent.js",
"index.mjs",
"cli.mjs",
"lib/",
"README.md",
"VALIDATION.md",
"LICENSE",
"README.zh-CN.md"
],
"scripts": {
"test": "bun test ./*.test.mjs",
"check": "node --check index.mjs && node --check cli.mjs && node --check nowledge-mem.agent.js"
},
"engines": {
"node": ">=22"
},
"keywords": [
"opencode",
"opencode-plugin",
"magpie-plugin",
"magpie-agent",
"nowledge-mem",
"agent"
],
"license": "MIT",
"magpie": {
"agent": "./nowledge-mem.agent.js",
"name": "Nowledge Mem / AI Now",
"summary": {
"zh": "从 Magpie 管理 Nowledge Mem 的 Default、AI Now 和后台任务模型",
"en": "Manage Nowledge Mem Default, AI Now and Background models"
},
"icon": "https://mem.nowledge.co/favicon.png"
}
}
@@ -0,0 +1,93 @@
import {test,afterEach} from 'bun:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import { tmpdir } from 'node:os';
import { selectionFrom } from './lib/selection.mjs';
import { runOnce, selectionText } from './lib/runtime.mjs';
import { withLock, writeJSON, readJSON } from './lib/files.mjs';
import { createAPI } from './lib/api.mjs';
import {createServer} from 'node:http';
import {startAdapter} from './lib/runtime.mjs';
const cleanups=[];
afterEach(async()=>{for(const close of cleanups.splice(0).reverse())await close();});
test('Magpie empty parent objects after disconnect are understood',()=>{
assert.equal(selectionFrom({gateway:{},metadata:{context:null,output:null}}),null);
assert.throws(()=>selectionFrom({gateway:{key:'secret'}}),/Incomplete/);
});
test('restore pauses stale selection and sync explicitly resumes it',async()=>{
const dir=await fs.mkdtemp(path.join(tmpdir(),'nowledge-runtime-'));
cleanups.push(()=>fs.rm(dir,{recursive:true,force:true}));
const config={selectionFile:path.join(dir,'selection.json'),stateFile:path.join(dir,'state.json'),pauseFile:path.join(dir,'paused.json'),statusFile:path.join(dir,'status.json'),apiUrl:'http://127.0.0.1:9'};
await writeJSON(config.selectionFile,{model:'x',gateway:{baseURL:'http://127.0.0.1:3425/v1',key:'secret'}});
assert.equal((await runOnce(config,{restore:true})).status,'disconnected');
assert.equal((await runOnce(config)).status,'paused');
await assert.rejects(runOnce(config,{resume:true}));
assert.equal(await readJSON(config.pauseFile),null);
});
test('lock prevents concurrent processes from owning one journal',async()=>{
const dir=await fs.mkdtemp(path.join(tmpdir(),'nowledge-lock-'));cleanups.push(()=>fs.rm(dir,{recursive:true,force:true}));
const file=path.join(dir,'state.json');
await withLock(file,async()=>{await assert.rejects(withLock(file,async()=>{}),/Another/);});
await withLock(file,async()=>{});
});
test('private atomic writes and malformed JSON are not mistaken for missing files',async()=>{
const dir=await fs.mkdtemp(path.join(tmpdir(),'nowledge-files-'));cleanups.push(()=>fs.rm(dir,{recursive:true,force:true}));
const file=path.join(dir,'x.json');assert.equal(await selectionText(file),'');
await writeJSON(file,{a:1});assert.equal((await fs.stat(file)).mode&0o777,0o600);
await fs.chmod(file,0o644);await selectionText(file);assert.equal((await fs.stat(file)).mode&0o777,0o600);
await fs.writeFile(file,'{"apiKey":"secret",');await assert.rejects(readJSON(file),SyntaxError);
});
test('backend credentials cannot be redirected or sent over remote HTTP',()=>{
assert.throws(()=>createAPI({apiUrl:'http://example.com',apiKey:'secret'}),/HTTPS/);
assert.throws(()=>createAPI({apiUrl:'https://user:secret@example.com'}),/credentials/);
});
test('redirected backend requests fail before contacting the second host',async()=>{
let leaked,visits=0;
const destination=createServer((req,res)=>{visits++;leaked=req.headers.authorization;res.setHeader('content-type','application/json');res.end('{}');});
await new Promise(r=>destination.listen(0,r));
cleanups.push(()=>new Promise(r=>destination.close(r)));
const target=`http://localhost:${destination.address().port}/target`;
const redirector=createServer((req,res)=>{res.writeHead(302,{location:target});res.end();});
await new Promise(r=>redirector.listen(0,'127.0.0.1',r));
cleanups.push(()=>new Promise(r=>redirector.close(r)));
const api=createAPI({apiUrl:`http://127.0.0.1:${redirector.address().port}`,apiKey:'redirect-test-key'});
await assert.rejects(api('/remote-llm/config'));
assert.equal(visits,0);assert.equal(leaked,undefined);
});
test('polling waits for one unchanged selection before syncing',async()=>{
const dir=await fs.mkdtemp(path.join(tmpdir(),'nowledge-clock-'));cleanups.push(()=>fs.rm(dir,{recursive:true,force:true}));
const tasks=[],synced=[];let text='first selection';
const config={selectionFile:path.join(dir,'selection.json'),apiUrl:'http://127.0.0.1:9',pollMs:500};
const dependencies={settings:async()=>config,selectionText:async()=>text,runOnce:async()=>{synced.push(text);return {status:'connected',conflicts:[]};},setTimeout:(fn,ms)=>{const task={fn,ms,unref(){}};tasks.push(task);return task;},clearTimeout:task=>{task.cancelled=true;},now:()=>0};
const stop=await startAdapter({},config,dependencies);
try{
assert.equal(tasks.length,1);
await tasks.shift().fn();assert.deepEqual(synced,[]);
text='new selection';await tasks.shift().fn();assert.deepEqual(synced,[]);
await tasks.shift().fn();assert.deepEqual(synced,['new selection']);
}finally{stop();}
assert.equal(tasks.at(-1).cancelled,true);
});
test('remote API polling backs off while local selection changes still synchronize promptly',async()=>{
const dir=await fs.mkdtemp(path.join(tmpdir(),'nowledge-backoff-'));cleanups.push(()=>fs.rm(dir,{recursive:true,force:true}));
const tasks=[],synced=[];let clock=0,text='first';
const config={selectionFile:path.join(dir,'selection.json'),apiUrl:'https://mem.example.test',pollMs:500};
const deps={settings:async()=>config,selectionText:async()=>text,runOnce:async()=>{synced.push(text);return {status:'connected',conflicts:[]};},setTimeout:fn=>{const timer={fn,unref(){}};tasks.push(timer);return timer;},clearTimeout:()=>{},now:()=>clock};
const stop=await startAdapter({},config,deps);
try{
await tasks.shift().fn();clock=500;await tasks.shift().fn();clock=1000;await tasks.shift().fn();
clock=1500;await tasks.shift().fn();assert.equal(synced.length,2);
text='changed';clock=1600;await tasks.shift().fn();clock=1700;await tasks.shift().fn();
assert.deepEqual(synced,['first','first','changed']);
}finally{stop();}
});
@@ -0,0 +1,22 @@
import {test} from 'bun:test';
import assert from 'node:assert/strict';
import path from 'node:path';
import {tmpdir,homedir} from 'node:os';
import {sandboxEnvironment,assertSandboxEnvironment} from './tests/sandbox.mjs';
test('smoke environment isolates all homes and leaves the caller unchanged',()=>{
const original=process.env.HOME;const root=path.join(tmpdir(),'nowledge-sandbox-check');
const env=sandboxEnvironment(root,{...process.env,CODEX_HOME:'/real/codex',CLAUDE_CONFIG_DIR:'/real/claude'});
assert.equal(env.HOME,path.join(root,'home'));assert.equal(process.env.HOME,original);
assert.equal(env.CODEX_HOME,undefined);assert.equal(env.CLAUDE_CONFIG_DIR,undefined);
assert.equal(env.MAGPIE_NO_ACCOUNTS,'1');
assertSandboxEnvironment(env,root);
});
test('smoke refuses a real home or escaped config/cache directory',()=>{
const root=path.join(tmpdir(),'nowledge-sandbox-check');const env=sandboxEnvironment(root);
assert.throws(()=>assertSandboxEnvironment({...env,HOME:homedir()},root),/Refusing real HOME/);
assert.throws(()=>assertSandboxEnvironment({...env,XDG_CONFIG_HOME:path.join(homedir(),'.config')},root),/XDG_CONFIG_HOME/);
assert.throws(()=>assertSandboxEnvironment({...env,XDG_CACHE_HOME:root},root),/XDG_CACHE_HOME/);
assert.throws(()=>assertSandboxEnvironment({...env,XDG_CACHE_HOME:path.dirname(root)},root),/XDG_CACHE_HOME/);
});
+185
View File
@@ -0,0 +1,185 @@
import {test,afterEach} from 'bun:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { mkdtemp, readFile, writeFile, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
const cleanups=[];
afterEach(async()=>{for(const close of cleanups.splice(0).reverse())await close();});
const ID = 'magpie:nowledge-agent';
const pick = (model='vendor/model-1') => ({model, gateway:{baseURL:'http://127.0.0.1:3425/v1',key:'gateway-secret'}, metadata:{context:65536,output:8192,images:true}});
const initial = () => ({enabled:false, active_provider:'old', provider:'old', model:'old-model', providers:{old:{provider_type:'openai_compatible',model:'old-model',has_api_key:true}}, purposes:{default:{provider:'old',model:'old-model'},ai_now:{provider:null,model:null,uses_default:true},background:{provider:'old',model:'background-model'},ocr:{provider:null,model:null,uses_default:true},embedding:{provider:null,model:null},decision:{provider:null,model:null}}});
async function fixture() {
const { synchronize } = await import('./lib/sync.mjs');
const dir = await mkdtemp(path.join(tmpdir(),'nowledge-agent-test-'));
let config=initial();
let autoActivate=false;
const calls=[];
let failPurpose=null;
let switchDefaultDuringRestore=false;
let coerceType;
const server=createServer(async(req,res)=>{
let body='';for await (const c of req) body+=c;
const data=body?JSON.parse(body):null;
calls.push({method:req.method,url:req.url,body:data,auth:req.headers.authorization});
res.setHeader('content-type','application/json');
if(req.method==='GET'&&req.url==='/remote-llm/config') return res.end(JSON.stringify(config));
if(req.url==='/remote-llm/config'&&req.method==='POST') {
assert.equal(data.extra_params.no_activate,true);
assert.equal(data.extra_params.preserve_enabled,true);
config.providers[data.provider]={...data,has_api_key:!!data.api_key};delete config.providers[data.provider].api_key;
if(coerceType)config.providers[data.provider].provider_type=coerceType;
if((autoActivate&&!config.active_provider)||config.active_provider===data.provider){config.active_provider=data.provider;config.provider=data.provider;config.model=data.model;config.purposes.default={provider:data.provider,model:data.model};}
} else if(req.url==='/remote-llm/purpose') {
if(data.purpose==='default'&&!data.provider){res.statusCode=400;return res.end('{"detail":"default purpose requires provider"}');}
if(failPurpose===data.purpose){failPurpose=null;res.statusCode=503;return res.end('{"error":"retry"}');}
config.purposes[data.purpose]={provider:data.provider??null,model:data.model??null};
if(data.purpose==='default'){config.active_provider=data.provider??'';config.provider=data.provider??'';config.model=data.model??'';}
if(switchDefaultDuringRestore&&data.purpose==='background'&&data.provider==='old'){
config.purposes.default={provider:'old',model:'manual-new-default'};config.active_provider='old';config.provider='old';config.model='manual-new-default';
}
} else if(req.url==='/remote-llm/enabled') config.enabled=data.enabled;
else if(req.url==='/remote-llm/activate') {config.active_provider=data.provider??'';config.provider=data.provider??'';}
else if(req.url==='/remote-llm/provider/remove') {
delete config.providers[data.provider];
if(config.active_provider===data.provider){config.active_provider='';config.provider='';config.model='';config.purposes.default={provider:null,model:null};}
}
else {res.statusCode=404;return res.end('{}');}
res.end(JSON.stringify(config));
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
cleanups.push(async()=>{await new Promise(resolve=>server.close(resolve));await rm(dir,{recursive:true,force:true});});
const options={apiUrl:`http://127.0.0.1:${server.address().port}`, apiKey:'backend-secret', stateFile:path.join(dir,'state.json')};
return {dir,calls,options,sync:(selection)=>synchronize(selection,options),get config(){return config;},fail:(p)=>failPurpose=p,coerceProviderType:type=>coerceType=type,switchDefaultDuringRestore:()=>switchDefaultDuringRestore=true,empty(){config=initial();config.providers={};config.active_provider='';config.provider='';config.model='';config.purposes.default={provider:null,model:null};config.purposes.background={provider:null,model:null};autoActivate=true;}};
}
test('connect manages three purposes with separate backend and gateway keys',async()=>{
const f=await fixture();await f.sync(pick());
for(const purpose of ['default','ai_now','background']) assert.deepEqual(f.config.purposes[purpose],{provider:ID,model:'vendor/model-1'});
assert.deepEqual(f.config.purposes.ocr,initial().purposes.ocr);
assert.equal(f.config.enabled,true);
const created=f.calls.find(c=>c.method==='POST'&&c.url==='/remote-llm/config');
assert.equal(created.body.api_key,'gateway-secret');assert.equal(created.auth,'Bearer backend-secret');
assert.equal(created.body.provider_type,'magpie');assert.equal(created.body.context_window,65536);
assert.equal((await stat(f.options.stateFile)).mode&0o777,0o600);
});
test('switch is idempotent and disconnect restores original assignments and mode',async()=>{
const f=await fixture();await f.sync(pick());await f.sync(pick('group/fallback'));
const before=f.calls.filter(c=>c.method==='POST').length;await f.sync(pick('group/fallback'));
assert.equal(f.calls.filter(c=>c.method==='POST').length,before);
await f.sync(null);
for(const p of ['default','ai_now','background']) assert.deepEqual(f.config.purposes[p],{provider:initial().purposes[p].provider,model:initial().purposes[p].model});
assert.equal(f.config.enabled,false);assert.equal(f.config.providers[ID],undefined);
assert.equal(f.config.providers.old.has_api_key,true);
await assert.rejects(readFile(f.options.stateFile),{code:'ENOENT'});
});
test('manual purpose edits are preserved during updates and disconnection',async()=>{
const f=await fixture();await f.sync(pick());
f.config.purposes.ai_now={provider:'old',model:'hand-picked'};
const result=await f.sync(pick('vendor/model-2'));
assert.ok(result.conflicts.includes('ai_now'));
assert.deepEqual(f.config.purposes.ai_now,{provider:'old',model:'hand-picked'});
await f.sync(null);assert.equal(f.config.purposes.ai_now.model,'hand-picked');
});
test('failed partial connect retains original snapshot and can resume then restore',async()=>{
const f=await fixture();f.fail('ai_now');
await assert.rejects(f.sync(pick()));
assert.ok(JSON.parse(await readFile(f.options.stateFile,'utf8')).original);
await f.sync(pick());await f.sync(null);
assert.equal(f.config.purposes.default.provider,'old');assert.equal(f.config.purposes.background.model,'background-model');
});
test('existing provider instance is never overwritten',async()=>{
const f=await fixture();f.config.providers[ID]={model:'user-provider',has_api_key:true};
await assert.rejects(f.sync(pick()),/already exists|已存在/);
assert.equal(f.calls.filter(c=>c.method==='POST').length,0);
});
test('changed provider and external references survive disconnect',async()=>{
const f=await fixture();await f.sync(pick());
f.config.providers[ID].api_base='http://127.0.0.1:5555/v1';
f.config.purposes.ocr={provider:ID,model:'vision-model'};
await f.sync(null);
assert.ok(f.config.providers[ID]);assert.equal(f.config.purposes.ocr.model,'vision-model');
});
test('invalid selection cannot be treated as a disconnect',async()=>{
const f=await fixture();await f.sync(pick());
await assert.rejects(f.sync({model:'x',gateway:{}}));
assert.equal(f.config.purposes.default.provider,ID);
});
test('a journal cannot be replayed against a different backend',async()=>{
const f=await fixture();await f.sync(pick());
const {synchronize}=await import('./lib/sync.mjs');
await assert.rejects(synchronize(null,{...f.options,apiUrl:'http://127.0.0.1:9'}),/backend|后端/);
});
test('first provider auto-activation is owned and an empty default restores by removal',async()=>{
const f=await fixture();f.empty();await f.sync(pick());
assert.equal(f.config.purposes.default.provider,ID);
await f.sync(null);assert.equal(f.config.active_provider,'');assert.equal(f.config.enabled,false);
assert.equal(f.config.providers[ID],undefined);
assert.ok(!f.calls.some(c=>c.url==='/remote-llm/purpose'&&c.body?.purpose==='default'&&!c.body.provider));
});
test('an interrupted restore must finish before a new connection',async()=>{
const f=await fixture();await f.sync(pick());f.fail('background');
await assert.rejects(f.sync(null));
await assert.rejects(f.sync(pick('vendor/next')),/restor|recover/i);
await f.sync(null);assert.equal(f.config.purposes.background.model,'background-model');
});
test('remote mode write is recovered even if its success was not journaled',async()=>{
const f=await fixture();await f.sync(pick());
const state=JSON.parse(await readFile(f.options.stateFile,'utf8'));
state.enabled.applied=null;state.enabled.pending=true;await writeFile(f.options.stateFile,JSON.stringify(state));
await f.sync(null);assert.equal(f.config.enabled,false);
});
test('provider update cannot undo a manual default model on the managed instance',async()=>{
const f=await fixture();await f.sync(pick());
f.config.purposes.default={provider:ID,model:'user-model'};
await assert.rejects(f.sync(pick('vendor/next')),/manual|disconnect/i);
assert.equal(f.config.purposes.default.model,'user-model');
});
test('an empty legacy placeholder is preserved when no default is configured',async()=>{
const f=await fixture();f.empty();f.config.providers.openai={model:'',has_api_key:false,api_base:null};
const placeholder=structuredClone(f.config.providers.openai);
await f.sync(pick());await f.sync(null);
assert.deepEqual(f.config.providers,{openai:placeholder});assert.equal(f.config.active_provider,'');
});
test('unchanged managed provider stays when an independently selected purpose references it',async()=>{
const f=await fixture();await f.sync(pick());
f.config.purposes.ocr={provider:ID,model:'vision-model'};
await f.sync(null);
assert.ok(f.config.providers[ID]);assert.equal(f.config.purposes.ocr.provider,ID);
assert.ok(!f.calls.some(c=>c.method==='POST'&&c.url==='/remote-llm/provider/remove'));
});
test('a new default selected during restore keeps Remote mode enabled',async()=>{
const f=await fixture();await f.sync(pick());f.switchDefaultDuringRestore();
await f.sync(null);
assert.equal(f.config.purposes.default.model,'manual-new-default');assert.equal(f.config.enabled,true);
assert.ok(!f.calls.some(c=>c.url==='/remote-llm/enabled'&&c.body?.enabled===false));
});
test('unsupported config response fails before any mutation',async()=>{
const f=await fixture();delete f.config.purposes;
await assert.rejects(f.sync(pick()),/Unsupported/);
assert.equal(f.calls.filter(c=>c.method==='POST').length,0);
});
test('an unsupported native provider type stops before purpose assignments',async()=>{
const f=await fixture();f.coerceProviderType('openai_compatible');
await assert.rejects(f.sync(pick()),/native Magpie/);
assert.ok(!f.calls.some(c=>c.url==='/remote-llm/purpose'));
});
@@ -0,0 +1,87 @@
// Opt-in: MAGPIE_BIN=/path/to/magpie node tests/magpie-smoke.mjs
// Separate Magpie registry, copied plugin with a temporary selection path,
// fake Nowledge API, fake vendor. Never invokes a paid model.
import fs from 'node:fs/promises';
import path from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { createServer } from 'node:http';
import { spawn } from 'node:child_process';
import assert from 'node:assert/strict';
import { setTimeout as delay } from 'node:timers/promises';
import {sandboxEnvironment,assertSandboxEnvironment} from './sandbox.mjs';
const bin=process.env.MAGPIE_BIN;
if(!bin)throw Error('Set MAGPIE_BIN to the installed Magpie executable.');
const dir=await fs.mkdtemp(path.join(tmpdir(),'nowledge-magpie-smoke-'));
const root=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const plugin=path.join(dir,'plugin');
const selectionFile=path.join(dir,'home','.config','magpie-nowledge-mem','selection.json');
const config={enabled:false,provider:'',active_provider:'',model:'',providers:{},purposes:Object.fromEntries(['default','ai_now','background','ocr','embedding','decision'].map(p=>[p,{provider:null,model:null}]))};
const original=structuredClone(config);
let modelCalls=0,service,logs='';
const backend=createServer(async(req,res)=>{
res.setHeader('content-type','application/json');
let raw='';for await(const c of req)raw+=c;const body=raw?JSON.parse(raw):null;
if(req.url==='/v1/models')return res.end(JSON.stringify({object:'list',data:['one','two'].map(id=>({id,object:'model',context_window:65536,max_output_tokens:8192}))}));
if(req.url==='/v1/chat/completions'){modelCalls++;res.statusCode=500;return res.end('{}');}
if(req.url==='/remote-llm/config'&&body){
config.providers[body.provider]={...body,has_api_key:true};delete config.providers[body.provider].api_key;
if(!config.active_provider){config.active_provider=body.provider;config.provider=body.provider;config.model=body.model;config.purposes.default={provider:body.provider,model:body.model};}
} else if(req.url==='/remote-llm/purpose') {
if(body.purpose==='default'&&!body.provider){res.statusCode=400;return res.end('{}');}
config.purposes[body.purpose]={provider:body.provider??null,model:body.model??null};
if(body.purpose==='default'){config.active_provider=body.provider;config.provider=body.provider;config.model=body.model;}
} else if(req.url==='/remote-llm/enabled')config.enabled=body.enabled;
else if(req.url==='/remote-llm/provider/remove'){
delete config.providers[body.provider];
if(config.active_provider===body.provider){config.active_provider='';config.provider='';config.model='';config.purposes.default={provider:null,model:null};}
} else if(req.url!=='/remote-llm/config'){res.statusCode=404;return res.end('{}');}
res.end(JSON.stringify(config));
});
await new Promise(resolve=>backend.listen(0,'127.0.0.1',resolve));
const url=`http://127.0.0.1:${backend.address().port}`;
const portServer=createServer();await new Promise(r=>portServer.listen(0,'127.0.0.1',r));const port=portServer.address().port;await new Promise(r=>portServer.close(r));
const env={...sandboxEnvironment(dir),MAGPIE_NOWLEDGE_CONFIG:path.join(dir,'adapter.json'),MAGPIE_ADDR:`127.0.0.1:${port}`};
const command=(...args)=>new Promise((resolve,reject)=>{
assertSandboxEnvironment(env,dir);
const child=spawn(bin,args,{env,stdio:['ignore','pipe','pipe']});let text='';
child.stdout.on('data',b=>text+=b);child.stderr.on('data',b=>text+=b);
const timer=setTimeout(()=>child.kill('SIGTERM'),30000);
child.once('error',reject);child.once('close',code=>{clearTimeout(timer);if(code===0)resolve(text);else reject(Error(`magpie ${args.slice(0,2).join(' ')} exited ${code}: ${text.slice(-2000)}`));});
});
async function until(predicate,label){const end=Date.now()+20000;while(Date.now()<end){if(predicate())return;await delay(200);}throw Error(`Timed out: ${label}\n${logs.slice(-3000)}`);}
try {
await fs.mkdir(plugin,{recursive:true});
await fs.mkdir(env.HOME,{recursive:true,mode:0o700});
for(const name of ['package.json','nowledge-mem.agent.js','index.mjs','lib'])await fs.cp(path.join(root,name),path.join(plugin,name),{recursive:true});
await fs.writeFile(env.MAGPIE_NOWLEDGE_CONFIG,JSON.stringify({selectionFile,apiUrl:url,pollMs:500}));
await command('plugin','add',plugin);
await command('plugin','options',plugin,JSON.stringify({selectionFile,apiUrl:url,pollMs:500}));
await command('provider','add','smoke',`url=${url}/v1`,'key=smoke-only','models=one,two','context=65536');
// Gateway's persisted port is documented in settings.json, but is not a
// writable key in the CLI's `settings set` subset on 0.1.3212.
const settingsFile=path.join(env.XDG_CONFIG_HOME,'magpie','settings.json');
let settings={};try{settings=JSON.parse(await fs.readFile(settingsFile,'utf8'));}catch(e){if(e.code!=='ENOENT')throw e;}
await fs.mkdir(path.dirname(settingsFile),{recursive:true});
await fs.writeFile(settingsFile,JSON.stringify({...settings,port}));
const agents=await command('agents');assert.ok(agents.includes('Nowledge Mem / AI Now'),'Agent row missing');
assertSandboxEnvironment(env,dir);
service=spawn(bin,['serve'],{env,stdio:['ignore','pipe','pipe']});
service.stdout.on('data',b=>logs+=b);service.stderr.on('data',b=>logs+=b);
await command('nowledge-mem','smoke/one');
await until(()=>['default','ai_now','background'].every(p=>config.purposes[p].model==='smoke/one'),'first model synchronization');
const picked=JSON.parse(await fs.readFile(selectionFile,'utf8'));assert.ok(picked.gateway.key);assert.equal(picked.gateway.baseURL,`http://127.0.0.1:${port}/v1`);
assert.equal((await fs.stat(selectionFile)).mode&0o077,0,'Agent gateway key file must be private');
await command('nowledge-mem','smoke/two');
await until(()=>['default','ai_now','background'].every(p=>config.purposes[p].model==='smoke/two'),'model change');
await command('nowledge-mem','default');
await until(()=>!config.providers['magpie:nowledge-agent']&&!config.enabled,'disconnect restoration');
assert.deepEqual(config,original);assert.equal(modelCalls,0);
console.log('PASS: actual Magpie Agent load, dynamic gateway/key, Bun host sync, model change, disconnect restoration; zero model calls.');
} finally {
if(service){service.kill('SIGTERM');await new Promise(resolve=>{service.once('close',resolve);setTimeout(()=>{service.kill('SIGKILL');resolve();},2000).unref();});}
await new Promise(resolve=>backend.close(resolve));
await fs.rm(dir,{recursive:true,force:true});
}
@@ -0,0 +1,42 @@
// Opt-in local contract check. Refuses to run against an enabled/configured
// instance; creates and removes one temporary provider, without model calls.
import assert from 'node:assert/strict';
import { createAPI } from '../lib/api.mjs';
import { providerConfig } from '../lib/selection.mjs';
const api=createAPI({apiUrl:process.env.NMEM_API_URL || 'http://127.0.0.1:14242',apiKey:process.env.NMEM_API_KEY});
const before=await api('/remote-llm/config');
const spec=await api('/openapi.json');
console.log('Nowledge service version:',spec.info?.version||'unknown');
if(process.argv.includes('--read-only')){
assert.equal(typeof before.enabled,'boolean');
for(const purpose of ['default','ai_now','background'])assert.ok(before.purposes?.[purpose]&&Object.hasOwn(before.purposes[purpose],'provider')&&Object.hasOwn(before.purposes[purpose],'model'));
assert.ok(Object.values(before.providers||{}).some(p=>p.provider_type==='magpie'),'Read-only check requires an existing native Magpie provider');
console.log('PASS: read-only config shape and native Magpie provider confirmed; no writes.');
process.exit(0);
}
assert.equal(before.enabled,false,'Contract check requires disabled Remote mode');
assert.ok(!Object.values(before.providers || {}).some(p=>p.model||p.has_api_key||p.api_base),'Contract check requires no configured providers (empty legacy placeholders are allowed)');
assert.ok(!before.active_provider&&!before.provider,'Contract check requires no active provider');
const provider=`magpie:agent-contract-${Date.now()}`;
try {
const body=providerConfig({model:'contract/model',gateway:{baseURL:'http://127.0.0.1:3425/v1',key:'magpie-nowledge-mem-contract-only'},metadata:{context:65536,output:4096,images:true}},provider);
await api('/remote-llm/config',body);
const after=await api('/remote-llm/config');
assert.equal(after.enabled,false);
assert.equal(after.active_provider,provider,'First provider auto-activation contract');
assert.equal(after.providers[provider].provider_type,'magpie');
assert.equal(after.providers[provider].model,'contract/model');
assert.equal(after.providers[provider].context_window,65536);
assert.equal(after.providers[provider].max_tokens,4096);
assert.equal(after.providers[provider].has_api_key,true);
assert.equal(after.providers[provider].api_key,undefined,'List API must mask keys');
console.log('PASS: native Magpie provider instance, scoped metadata, masked key, first-provider auto-activation, Remote mode preserved.');
} finally {
const current=await api('/remote-llm/config');
if(current.providers?.[provider])await api('/remote-llm/provider/remove',{provider});
const after=await api('/remote-llm/config');
assert.equal(after.enabled,before.enabled);assert.equal(after.active_provider,before.active_provider);
assert.deepEqual(after.purposes,before.purposes);assert.deepEqual(after.providers,before.providers);
console.log('PASS: temporary provider removed; original active provider, mode and purpose assignments restored.');
}
@@ -0,0 +1,26 @@
import path from 'node:path';
import {homedir,userInfo} from 'node:os';
const callerHome=homedir();
let accountHome=callerHome;
try{accountHome=userInfo().homedir;}catch{}
export function assertSandboxEnvironment(env,root){
const contains=p=>{
if(typeof p!=='string')return false;
const relative=path.relative(path.resolve(root),path.resolve(p));
return relative!==''&&relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);
};
if(!contains(env.HOME)||[callerHome,accountHome].some(p=>path.resolve(p)===path.resolve(env.HOME)))throw Error('Refusing real HOME: the smoke test requires its own sandbox home.');
for(const key of ['XDG_CONFIG_HOME','XDG_CACHE_HOME','XDG_DATA_HOME'])if(!contains(env[key]))throw Error(`${key} must stay inside the smoke sandbox.`);
}
export function sandboxEnvironment(root,base=process.env){
const smokeHome=path.join(root,'home');
// Configure only a child process's actual home; never mutate the caller's
// process.env or use its HOME as a scratch directory.
const env={...base,HOME:smokeHome,USERPROFILE:smokeHome,APPDATA:path.join(smokeHome,'AppData','Roaming'),LOCALAPPDATA:path.join(smokeHome,'AppData','Local'),XDG_CONFIG_HOME:path.join(smokeHome,'.config'),XDG_CACHE_HOME:path.join(smokeHome,'.cache'),XDG_DATA_HOME:path.join(smokeHome,'.local','share'),MAGPIE_NO_ACCOUNTS:'1',DO_NOT_TRACK:'1',NMEM_API_KEY:''};
for(const key of ['CODEX_HOME','CLAUDE_CONFIG_DIR','GEMINI_CLI_HOME','OPENCODE_CONFIG','OPENCODE_CONFIG_DIR','PI_CODING_AGENT_DIR'])delete env[key];
assertSandboxEnvironment(env,root);
return env;
}
+2
View File
@@ -90,6 +90,8 @@
"summary": { "en": "New API's sensitive-word filter: turn away or mask words and patterns in what you send, and in replies.", "zh": "New API 的敏感词过滤:拒绝或替换你发出的内容和回复里的词与正则。" } },
{ "package": "@magpie-community/middleware-think-tags", "name": "Think Tags", "kind": "middleware", "community": true,
"summary": { "en": "Take a model's leading <think>, <thinking> or <thought> block out of its reply's text, or put a Chat reply's reasoning into it.", "zh": "去掉回复正文开头的 <think>、<thinking> 或 <thought> 思考块,或把 Chat 回复的思考内容放进正文。" } },
{ "package": "@magpie-community/agent-nowledge-mem", "name": "Nowledge Mem / AI Now models", "kind": "agent", "community": true, "icon": "https://mem.nowledge.co/favicon.png",
"summary": {"en": "Choose Nowledge Mem Default, AI Now and Background models through Magpie. Distinct from gateway-nowledge-mem recall/capture. Disconnect before uninstalling.", "zh": "在 Magpie 管理 Nowledge 的 Default、AI Now 和后台模型;与 gateway-nowledge-mem 的记忆召回、对话导入用途不同。卸载前先断开。"} },
{ "package": "@magpie-community/agent-kilo", "name": "Kilo Code", "kind": "agent", "community": true, "icon": "https://github.com/Kilo-Org.png",
"summary": { "en": "Kilo Code (kilo.ai) on magpie's Agents page: pick one of magpie's models for it, and switch it off to put its config back.", "zh": "把 Kilo Code(kilo.ai)加到 magpie 的 Agent 页:选择 magpie 的模型,关掉即恢复原来的配置。" } },
{ "package": "@magpie-community/middleware-antigravity-cloak", "name": "Antigravity Cloak", "kind": "middleware", "community": true,