nowledge-mem 0.1.3: skipAgents leaves the apps you name without memory (#597)

QingZ11 relayed a user whose Doubao translator, behind magpie, had Mem
recall added to every translation. The plugin had one global recall
switch, so the only way out was turning memory off for every agent.

skipAgents (option, and "Apps without memory" on the plugin page) lists
apps by the agent name magpie gives a request (ctx.agent, the Agent
column on magpie's Usage page). A listed app's request is treated like
another machine's: no search, no Context Bundle, no capture, nothing
sent to Mem, request unchanged, reported "skipped". Names compare
without case, spaces or punctuation, so "Claude Code" matches
claude-code. A list or a comma-separated string (ASCII or full-width
comma). Default empty: nothing changes for anyone who doesn't set it.

Run (mote, at this tree on origin/main 1a3a138):
- HOME=$(mktemp -d) bun test: 4529 pass, 0 fail, 9 skip (live checks).
- bun scripts/check.mjs: ok.
- Broken by hand: without the skipAgents check in run(), the new test
  goes red (1 fail), green with it.
Not tried: a real magpie with a real translator app; the hook's ctx is
driven as magpie's host calls it, and the page script through its test.
This commit is contained in:
yetone
2026-11-01 18:39:03 +08:00
parent 1a3a138491
commit df98bf6fb2
8 changed files with 100 additions and 7 deletions
+8 -1
View File
@@ -107,6 +107,12 @@ derived value for all of them.
- `recall`: default **true**. Whether a turn gets Mem context. Recall only
happens when a Mem endpoint is reachable; failures leave the request as it
came.
- `skipAgents`: default empty. Apps this plugin leaves alone: their requests
get no recall, Context Bundle or capture, and nothing about them reaches Mem.
A list of names (`["Mozilla", "Claude Code"]`) or one comma-separated
string. A name is the app's agent as Magpie's Usage page shows it; case,
spaces and punctuation don't matter, so `Claude Code` and `claude-code` are
one app. A translator or other one-shot tool behind Magpie goes here (#597).
- `contextBundle`: default **true**. On a session's first turn, ask Mem for its
Context Bundle (owner profile, rules and Working Memory) and add its rendered
markdown. When the bundle is empty, missing or failing, the hook falls back
@@ -261,7 +267,8 @@ own: the offline tests replace `globalThis.fetch` to keep Cursor's token local
The page uses only Magpie's released `magpie.options` and theme bridge. It
declares no reads and saving stores configuration without probing the
connection or writing Memory. It shows the Server, API key, Space, Agent, the
recall, Context Bundle and capture switches. Its **What is sent** section says
apps without memory (`skipAgents`), and the recall, Context Bundle and capture
switches. Its **What is sent** section says
the scope: direct local requests and `magpie-key` from this computer; other
gateway keys and remote requests are never included. It follows Magpie's language (English, Simplified and
Traditional Chinese, Japanese, German) and theme, and preserves options it does
+16 -1
View File
@@ -6,7 +6,7 @@
import { createHash } from "node:crypto";
// Bumped with package.json: Mem's own clients record it on imported Threads.
export const version = "0.1.2";
export const version = "0.1.3";
// The only report codes magpie's Plugins page shows; tools turn these into
// messages, never the service's own text.
@@ -42,6 +42,14 @@ export function resolveOptions(raw = {}, env = process.env) {
throw new MemFailure("invalid");
return value;
};
// skipAgents names the apps whose requests this plugin leaves alone: a
// list, or one string of names split by commas or new lines.
let skip = raw.skipAgents ?? [];
if (typeof skip === "string")
skip = skip.split(/[,,\n]/u);
if (!Array.isArray(skip) || skip.some((name) => typeof name !== "string"))
throw new MemFailure("invalid");
const skipAgents = new Set(skip.map(agentKey).filter(Boolean));
const captureFilter = raw.captureFilter === undefined ? "off" : raw.captureFilter;
if (captureFilter !== "off" && captureFilter !== "human")
throw new MemFailure("invalid");
@@ -90,6 +98,7 @@ export function resolveOptions(raw = {}, env = process.env) {
spaceId: text(raw.spaceId),
agentId: text(raw.agentId),
hostAgentId: text(raw.hostAgentId),
skipAgents,
recall: bool("recall", true),
contextBundle: bool("contextBundle", true),
capture: bool("capture", false),
@@ -103,6 +112,12 @@ export function resolveOptions(raw = {}, env = process.env) {
};
}
// agentKey is an app's name as skipAgents compares it: magpie's id
// ("claude-code") and the name its pages show ("Claude Code") are one app.
export function agentKey(name) {
return String(name ?? "").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "");
}
// request sends to the configured Mem only, reads a bounded reply and decodes
// it strictly. A status in `expected` comes back without its body, so
// "nothing there" is told from a failure. Failures use Mem's small outcome
+5 -3
View File
@@ -14,7 +14,7 @@
// "contextBundle": true, "maxMemories": 5, "maxBytes": 6000,
// "requestTimeoutMs": 900, "recallBackoffMs": 30000, "capture": false,
// "captureTools": true, "captureFilter": "off", "captureCindy": false,
// "allowInsecureHttp": false}
// "allowInsecureHttp": false, "skipAgents": []}
//
// A turn keeps the block it was given for the rest of the conversation, so what
// the agent sends stays the same from one request to the next and the
@@ -23,7 +23,7 @@
import { resolve } from "node:path";
import { captureMessage } from "./capture-filter.mjs";
import { conversation as transcript, history, notice, open, close } from "./conversation.mjs";
import { MemFailure as Failure, resolveOptions, request, serviceKey, sha256, trimText, utf8, version } from "./mem.mjs";
import { MemFailure as Failure, agentKey, resolveOptions, request, serviceKey, sha256, trimText, utf8, version } from "./mem.mjs";
const maxQuery = 2000;
const maxMemory = 1000;
const maxImport = 512 << 10;
@@ -65,7 +65,9 @@ export async function onRequest(body, ctx) {
}
async function run(body, ctx) {
const o = resolveOptions(ctx.options);
const own = ctx.origin === "local" || ctx.origin === "magpie-key";
// An app the user listed in skipAgents (a translator, say) gets neither
// recall nor capture: its requests go as they came, and Mem hears nothing.
const own = (ctx.origin === "local" || ctx.origin === "magpie-key") && !o.skipAgents.has(agentKey(ctx.agent));
const recall = o.recall && own;
const capture = o.capture && own;
if (!recall && !capture) {
@@ -314,6 +314,8 @@ test("options it can't use are invalid, before anything is sent", async () => {
{ serverUrl: "http://127.0.0.1:14242", requestTimeoutMs: 10_000 },
{ serverUrl: "http://127.0.0.1:14242", recallBackoffMs: 10 },
{ serverUrl: "http://127.0.0.1:14242", capture: "yes" },
{ serverUrl: "http://127.0.0.1:14242", skipAgents: 5 },
{ serverUrl: "http://127.0.0.1:14242", skipAgents: ["Mozilla", 1] },
{ serverUrl: "http://127.0.0.1:14242", apiKey: "bad key" },
{ serverUrl: "http://127.0.0.1:14242", apiKey: "bad\nkey" },
]) {
@@ -463,6 +465,39 @@ test("the Magpie sharing key from this computer is included; other gateway keys
expect(of("threads/import")).toHaveLength(0)
})
test("an app named in skipAgents gets no recall and no capture; other apps still do (#597)", async () => {
for (const skipAgents of [["Mozilla", "Claude Code"], "mozilla,claude-code", " MOZILLA ,\nclaude_code "]) {
for (const agent of ["Mozilla", "claude-code"]) {
mock()
calls.length = 0
const [reports, context] = capturing("chat", { agent, options: { skipAgents } })
const body = structuredClone(chat)
expect(await onRequest(body, context)).toBeUndefined()
expect(body).toEqual(chat)
expect(context.state.nowledgeMem).toBeUndefined()
await onResponse(reply, { ...context, success: true })
expect(calls).toHaveLength(0)
expect(reports).toEqual([["skipped"]])
reset()
}
mock()
calls.length = 0
const [, other] = capturing("chat", { agent: "codex", options: { skipAgents } })
const body = structuredClone(chat)
await onRequest(body, other)
expect(body.messages[1].content).toContain("QUARTZ-8413")
await onResponse(reply, { ...other, success: true })
expect(of("memories/search")).toHaveLength(1)
expect(of("threads/import")).toHaveLength(1)
reset()
}
// a request with no agent is not taken for a listed one
mock()
calls.length = 0
await onRequest(structuredClone(chat), ctx("chat", { options: { serverUrl: "http://127.0.0.1:14242", skipAgents: ["", " "] } }))
expect(of("memories/search")).toHaveLength(1)
})
test("remote and unknown origins stay out", async () => {
for (const origin of ["remote", undefined]) {
mock()
@@ -709,6 +744,7 @@ test("configuration page saves the Mem connection for the shipped hook", async (
elements.agent.value = "agent-3"
elements.key.value = "Bearer nmem_page_key"
elements.capture.checked = true
elements["skip-agents"].value = " Mozilla,, Claude Code ,"
await save()
expect(options).toEqual({
...original,
@@ -717,7 +753,9 @@ test("configuration page saves the Mem connection for the shipped hook", async (
agentId: "agent-3",
apiKey: "nmem_page_key",
capture: true,
skipAgents: ["Mozilla", "Claude Code"],
})
expect(elements["summary-skip"].textContent).toBe("Mozilla, Claude Code")
// Run the shipped hook with exactly what the page saved.
mock({ "threads/import": (body) => Response.json({ success: true, failed_count: 0, results: [{ success: true, thread_id: body.thread_id, message_count: body.messages.length, messages_added: body.messages.length }] }) })
const hookContext = ctx("chat", { options })
@@ -752,12 +790,17 @@ test("configuration page saves the Mem connection for the shipped hook", async (
expect(elements.result.dataset.message).toBe("invalidUrl")
}
elements.configure.onclick()
expect(elements["skip-agents"].value).toBe("Mozilla, Claude Code")
elements.url.value = "https://mem.example.com"
elements.key.value = ""
elements.space.value = " "
elements.agent.value = ""
elements.capture.checked = false
elements["skip-agents"].value = " , "
await save()
expect(options.skipAgents).toBeUndefined()
expect(elements["summary-skip"].textContent).toBe("None")
expect(options.serverUrl).toBe("https://mem.example.com/")
// The main page's Test button tests the saved connection; the test page
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/gateway-nowledge-mem",
"version": "0.1.2",
"version": "0.1.3",
"description": "Nowledge Mem recall, Context Bundle and optional conversation capture at the Magpie gateway, for every connected harness",
"type": "module",
"files": [
+15
View File
@@ -23,6 +23,9 @@ const messages = {
"keyFallback": "With this field empty, Magpie reads the variable named in apiKeyEnv (NMEM_API_KEY by default); only NMEM_* names are accepted.",
"behaviorSection": "What Magpie sends",
"recallHelp": "Search Mem with the latest user turn and add what it recalls to the request.",
"skipAgents": "Apps without memory",
"skipAgentsHelp": "Optional. App names as Magpie’s Usage page shows them, separated by commas. Their requests get no recall and are never saved.",
"none": "None",
"contextLabel": "Context Bundle",
"contextHelp": "On a session’s first turn, also send your profile, rules and Working Memory.",
"toolsTitle": "Memory tools",
@@ -79,6 +82,9 @@ const messages = {
"keyFallback": "此字段留空时,Magpie 读取 apiKeyEnv 指定的变量(默认 NMEM_API_KEY);只接受 NMEM_* 名称。",
"behaviorSection": "Magpie 会发送什么",
"recallHelp": "用最新一条用户消息搜索 Mem,并把召回内容加入请求。",
"skipAgents": "不用记忆的应用",
"skipAgentsHelp": "可选。按 Magpie 用量页显示的应用名填写,用逗号分隔。这些应用的请求不召回记忆,也不保存对话。",
"none": "无",
"contextLabel": "Context Bundle",
"contextHelp": "会话第一轮还会附带你的档案、规则和 Working Memory。",
"toolsTitle": "记忆工具",
@@ -135,6 +141,9 @@ const messages = {
"keyFallback": "此欄位留空時,Magpie 讀取 apiKeyEnv 指定的變數(預設為 NMEM_API_KEY);只接受 NMEM_* 名稱。",
"behaviorSection": "Magpie 會傳送什麼",
"recallHelp": "用最新一則使用者訊息搜尋 Mem,並把召回內容加入請求。",
"skipAgents": "不用記憶的應用程式",
"skipAgentsHelp": "選填。依 Magpie 用量頁顯示的應用程式名稱填寫,以逗號分隔。這些應用程式的請求不召回記憶,也不儲存對話。",
"none": "無",
"contextLabel": "Context Bundle",
"contextHelp": "工作階段第一輪還會附上你的設定檔、規則與 Working Memory。",
"toolsTitle": "記憶工具",
@@ -191,6 +200,9 @@ const messages = {
"keyFallback": "空欄の場合、Magpie は apiKeyEnv の変数(既定は NMEM_API_KEY)を読みます。NMEM_* の名前だけを受け付けます。",
"behaviorSection": "Magpie が送るもの",
"recallHelp": "最新のユーザーの発話で Mem を検索し、呼び出した内容をリクエストに加えます。",
"skipAgents": "メモリを使わないアプリ",
"skipAgentsHelp": "任意。Magpie の使用量ページに表示されるアプリ名をカンマ区切りで入力します。これらのアプリのリクエストには呼び出しを行わず、会話も保存しません。",
"none": "なし",
"contextLabel": "Context Bundle",
"contextHelp": "セッションの最初のターンでは、プロフィール・ルール・Working Memory も送ります。",
"toolsTitle": "メモリツール",
@@ -247,6 +259,9 @@ const messages = {
"keyFallback": "Bei leerem Feld liest Magpie die in apiKeyEnv genannte Variable (standardmäßig NMEM_API_KEY); nur NMEM_*-Namen werden akzeptiert.",
"behaviorSection": "Was Magpie sendet",
"recallHelp": "Mem mit dem letzten Benutzerbeitrag durchsuchen und das Gefundene an die Anfrage anhängen.",
"skipAgents": "Apps ohne Gedächtnis",
"skipAgentsHelp": "Optional. App-Namen wie auf Magpies Nutzungsseite, durch Kommas getrennt. Ihre Anfragen bekommen keinen Abruf und werden nie gespeichert.",
"none": "Keine",
"contextLabel": "Context Bundle",
"contextHelp": "Beim ersten Zug einer Sitzung werden auch Profil, Regeln und Working Memory gesendet.",
"toolsTitle": "Speicher-Tools",
+2 -1
View File
@@ -6,7 +6,7 @@
<body><main>
<header class="page-head"><img class="brand" src="icon.svg" width="30" height="30" alt=""><div><h1>Nowledge Mem</h1><p data-t="intro">Recall your Mem memory in every agent behind Magpie.</p></div><div class="header-actions"><button id="configure" type="button" disabled data-t="configure">Configure connection</button><button id="test-saved" class="secondary" type="button" disabled data-t="testConnection">Test connection</button></div></header>
<section class="panel"><div class="section-heading"><h2 data-t="connection">Connection</h2><span id="configured" role="status"></span></div>
<dl class="connection-summary"><div><dt data-t="url">Server URL</dt><dd id="summary-url">—</dd></div><div><dt data-t="space">Space ID</dt><dd id="summary-space">—</dd></div><div><dt data-t="recall">Memory recall</dt><dd id="summary-recall">—</dd></div><div><dt id="summary-capture-label" data-t="capture">Save conversations</dt><dd class="capture-status"><input id="summary-capture" class="slide-switch" type="checkbox" role="switch" disabled aria-labelledby="summary-capture-label" aria-describedby="capture-feedback"><span id="capture-state"></span></dd></div></dl>
<dl class="connection-summary"><div><dt data-t="url">Server URL</dt><dd id="summary-url">—</dd></div><div><dt data-t="space">Space ID</dt><dd id="summary-space">—</dd></div><div><dt data-t="recall">Memory recall</dt><dd id="summary-recall">—</dd></div><div><dt data-t="skipAgents">Apps without memory</dt><dd id="summary-skip">—</dd></div><div><dt id="summary-capture-label" data-t="capture">Save conversations</dt><dd class="capture-status"><input id="summary-capture" class="slide-switch" type="checkbox" role="switch" disabled aria-labelledby="summary-capture-label" aria-describedby="capture-feedback"><span id="capture-state"></span></dd></div></dl>
<p id="capture-feedback" role="status" aria-live="polite" hidden></p></section>
<dialog id="settings" aria-labelledby="dialog-title" aria-describedby="dialog-description">
<div class="dialog-head">
@@ -27,6 +27,7 @@
<fieldset class="settings-section"><legend><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v4M12 17v4M4.9 4.9l2.8 2.8M16.3 16.3l2.8 2.8M3 12h4M17 12h4M4.9 19.1l2.8-2.8M16.3 7.7l2.8-2.8"/></svg><span data-t="behaviorSection">What Magpie sends</span></legend>
<label class="switch-field" for="recall"><input id="recall" type="checkbox" role="switch"><span><strong data-t="recall">Memory recall</strong><small data-t="recallHelp">Search Mem with the latest user turn and add what it recalls to the request.</small></span></label>
<label class="switch-field" for="context"><input id="context" type="checkbox" role="switch"><span><strong data-t="contextLabel">Context Bundle</strong><small data-t="contextHelp">On a session’s first turn, also send your profile, rules and Working Memory.</small></span></label>
<label for="skip-agents"><span data-t="skipAgents">Apps without memory</span><input id="skip-agents" placeholder="Mozilla" autocomplete="off" spellcheck="false" aria-describedby="skip-agents-help"><small id="skip-agents-help" data-t="skipAgentsHelp">Optional. App names as Magpie’s Usage page shows them, separated by commas. Their requests get no recall and are never saved.</small></label>
<label class="switch-field" for="capture"><input id="capture" type="checkbox" role="switch"><span><strong data-t="capture">Save conversations</strong><small data-t="captureHelp">Off by default. Import completed conversations as Mem Threads, which Mem distills into Memory.</small></span></label>
</fieldset>
<p id="result" role="status" aria-live="polite" hidden></p>
+10
View File
@@ -19,11 +19,17 @@ function summary() {
$("summary-url").textContent = savedOptions.serverUrl || t("localDefault");
$("summary-space").textContent = savedOptions.spaceId || t("defaultSpace");
$("summary-recall").textContent = savedOptions.recall === false ? t("off") : t("on");
$("summary-skip").textContent = skipList(savedOptions.skipAgents).join(", ") || t("none");
const capture = $("summary-capture");
capture.checked = pendingCapture ?? savedOptions.capture === true;
$("capture-state").textContent = savedOptions.capture === true ? t("on") : t("off");
capture.title = t("captureHelp");
}
// skipAgents is kept as a list; one typed by hand may be a single string.
function skipList(value) {
const names = Array.isArray(value) ? value : typeof value === "string" ? value.split(/[,,\n]/) : [];
return names.filter((name) => typeof name === "string").map((name) => name.trim()).filter(Boolean);
}
function validUrl(raw) {
let url;
try { url = new URL(raw); } catch { return null }
@@ -44,6 +50,7 @@ function fill(options) {
$("url").value = options.serverUrl || "";
$("space").value = options.spaceId || "";
$("agent").value = options.agentId || "";
$("skip-agents").value = skipList(options.skipAgents).join(", ");
$("key").value = (options.apiKey || "").replace(/^Bearer\s+/i, "");
$("key").type = "password";
$("recall").checked = options.recall !== false;
@@ -91,6 +98,7 @@ const save = async (event) => {
if (!url) { result("invalidUrl", true); $("url").focus(); return }
const space = $("space").value.trim();
const agent = $("agent").value.trim();
const skip = skipList($("skip-agents").value);
const key = $("key").value.trim().replace(/^Bearer\s+/i, "");
if (key && /[\s\u0000-\u001f\u007f]/.test(key)) {
result("invalidKey", true); $("key").focus(); return;
@@ -104,6 +112,8 @@ const save = async (event) => {
else delete next.spaceId;
if (agent) next.agentId = agent;
else delete next.agentId;
if (skip.length) next.skipAgents = skip;
else delete next.skipAgents;
if (key) next.apiKey = key;
else delete next.apiKey;
await magpie.options.set(next);