Files
plugins/packages/nowledge-mem/mem.mjs
T
SadWood 5b370f3e62 nowledge-mem 0.1.5: one Settings dialog for every option on released hosts (#588, SadWood)
The Nowledge Mem page's dialog now sets every option the hook reads, on Magpie's released bridge (options.get/set only), by SadWood.

- One Settings dialog: connection, key (an empty field keeps the saved key; Remove saved key / Undo), API key variable, recall and remote recall, Context Bundle, apps without memory, capture and remote capture, the human-dialogue filter (a switch, Cindy only with it on, tool results only with it off) and the advanced numbers. Remote HTTP needs the Advanced exception.
- A × beside a field that holds an explicit value returns it to the default. Saving re-reads the options, writes only edited fields, and refuses (keeping the draft) when one of them, or a gate's remote grant or the endpoint behind a newly allowed HTTP exception, changed elsewhere.
- page/validate.js is shared by the page and resolveOptions, so both refuse the same values.
- The footer wraps at narrow widths (German Save was cut off at 380px).
- No native select. Every language has every key; the English fallback loop is gone.

Reviewed at 75a09d19e, run merged onto main 04f3608 (main's later 24cd0b9 touches packages/cursor only). Mac mini, Bun 1.4.2, temp HOME:
- packages/nowledge-mem: 130 pass, 2 skip (live Mem, Linux-only Chrome layout), 0 fail.
- whole repo bun test: 4699 pass, 12 skip, 0 fail. bun scripts/check.mjs: exit 0.
- PR CI at this head ran the Linux Chrome layout test (pass, 30 layouts) and 4587 pass.
- Browser harness: page/ framed with sandbox="allow-scripts", magpie's CSP and magpie's real pagebridge.js; Chromium and WebKit, en/zh/zh-TW/ja/de, 320/380/900px, light/dark (60 runs). No request beyond the page's own files, no console or page errors, the key never in the DOM, no select, no overflow, key field password again after show/close/reopen, recallRemote shown but disabled while recall is off. Flows (en 380, both engines): editing Space gives one options.set keeping custom, apiKey, requestTimeoutMs:900, skipAgents and recallRemote; http://100.64.0.5 refused until the HTTP exception is on, then saved; a Space changed elsewhere conflicts and writes nothing; Bearer key replaces and empties the field; Remove saved key deletes apiKey; turning recall on keeps recallRemote.

Broken by hand:
- Main's footer CSS back: the harness flags 12 runs (en 320, de 320/380, both engines).
- settings.js dependency check off: "enabling a global gate conflicts…" and "enabling HTTP exception conflicts…" go red.
- validateExplicitOptions removed from resolveOptions: two hook option tests go red.

Not tried: a real Mem server.
2026-11-02 05:14:03 +08:00

216 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The Nowledge Mem connection for the gateway hook: how the endpoint and
// credential are resolved, how a request is made and bounded, and the small
// helpers the hook needs. The page, the hook and Mem's own clients read the
// same options and environment, so they never disagree about where Mem is or
// which Space they speak to.
import { createHash } from "node:crypto";
import "./page/validate.js";
const validateExplicitOptions = globalThis.__nowledgeMemValidateOptions;
// Bumped with package.json: Mem's own clients record it on imported Threads.
export const version = "0.1.5";
// The only report codes magpie's Plugins page shows; tools turn these into
// messages, never the service's own text.
export class MemFailure extends Error {
code;
status;
constructor(code, status = 0) {
super(`Nowledge Mem ${code}`);
this.code = code;
this.status = status;
}
}
// Mem search answers carry per-hit debug metadata: 20 hits can reach ~110 KiB.
const maxResponseBytes = 512 << 10;
export function resolveOptions(raw = {}, env = process.env) {
try { validateExplicitOptions(raw); } catch { throw new MemFailure("invalid"); }
const text = (v) => {
if (v === undefined || v === null || v === "")
return undefined;
if (typeof v !== "string" || !v.trim())
throw new MemFailure("invalid");
return v;
};
// A name may be a list or comma/newline-separated text, as in #597.
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;
// The Mem endpoint, as its own clients resolve it: the option, then the
// portable NMEM_API_URL, then the local desktop default. A URL from the
// environment that isn't an HTTP(S) address is ignored rather than fatal.
const configured = text(raw.serverUrl);
let serverUrl = configured;
if (!configured) {
let fromEnv;
try { fromEnv = text(env.NMEM_API_URL); } catch { /* unusable */ }
for (const candidate of [fromEnv, "http://127.0.0.1:14242"]) {
try {
if (candidate && ["https:", "http:"].includes(new URL(candidate).protocol)) {
serverUrl = candidate;
break;
}
}
catch { /* next candidate */ }
}
}
if (!serverUrl)
throw new MemFailure("invalid");
let server;
try {
server = new URL(serverUrl);
}
catch {
throw new MemFailure("invalid");
}
// a credential is never sent in clear text to another machine, kept in a
// URL that logs show, or followed through a redirect
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(server.hostname);
if (server.username || server.password || server.search || server.hash || !["https:", "http:"].includes(server.protocol) ||
(server.protocol === "http:" && !loopback && raw.allowInsecureHttp !== true))
throw new MemFailure("invalid");
server.pathname = server.pathname.replace(/\/$/, "") + "/";
const apiKeyEnv = text(raw.apiKeyEnv) ?? "NMEM_API_KEY";
if (!/^NMEM_[A-Za-z0-9_]+$/u.test(apiKeyEnv))
throw new MemFailure("invalid");
const apiKey = bearer(text(raw.apiKey) ?? text(env[apiKeyEnv]));
if (apiKey && /[\s\u0000-\u001f\u007f]/u.test(apiKey))
throw new MemFailure("invalid");
return {
server, apiKey, apiKeyEnv,
spaceId: text(raw.spaceId),
agentId: text(raw.agentId),
hostAgentId: text(raw.hostAgentId),
skipAgents,
recall: raw.recall ?? true,
contextBundle: raw.contextBundle ?? true,
capture: raw.capture ?? false,
recallRemote: raw.recallRemote ?? false,
captureRemote: raw.captureRemote ?? false,
captureTools: raw.captureTools ?? true,
captureFilter,
captureCindy: raw.captureCindy ?? false,
maxMemories: raw.maxMemories ?? 5,
maxBytes: raw.maxBytes ?? 6000,
requestTimeoutMs: raw.requestTimeoutMs ?? 1500,
recallBackoffMs: raw.recallBackoffMs ?? 30_000,
};
}
// 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
// vocabulary; the caller decides what each means for it.
export async function request(o, { method, route, payload, signal, timeoutMs, expected = [], fetch: fetcher = fetch }) {
const headers = { "User-Agent": `magpie-nowledge-mem/${version}`, Accept: "application/json" };
if (payload !== undefined)
headers["Content-Type"] = "application/json";
if (o.apiKey)
headers.Authorization = `Bearer ${o.apiKey}`;
const deadline = AbortSignal.timeout(timeoutMs);
const combined = signal ? AbortSignal.any([signal, deadline]) : deadline;
try {
combined.throwIfAborted();
let r;
try {
r = await fetcher(new URL(route, o.server), {
method, headers, signal: combined, redirect: "error",
body: payload === undefined ? undefined : JSON.stringify(payload),
});
}
catch {
throw new MemFailure("unavailable");
}
if (r.ok)
return { status: r.status, body: await json(r) };
await r.body?.cancel();
if (expected.includes(r.status))
return { status: r.status, body: undefined };
if (r.status === 401 || r.status === 403)
throw new MemFailure("unauthorized", r.status);
if (r.status === 400)
throw new MemFailure(o.spaceId ? "unbound" : "invalid", r.status);
if (r.status === 404)
throw new MemFailure("notfound", r.status);
if (r.status === 409 || r.status === 422)
throw new MemFailure("invalid", r.status);
throw new MemFailure("unavailable", r.status);
}
catch (error) {
// The client's own cancellation keeps its reason, not ours.
signal?.throwIfAborted();
if (deadline.aborted)
throw new MemFailure("unavailable");
throw error;
}
}
async function json(r) {
const reader = r.body?.getReader();
if (!reader)
throw new MemFailure("invalid", r.status);
const chunks = [];
let size = 0;
try {
for (;;) {
let part;
try { part = await reader.read(); }
catch { throw new MemFailure("unavailable", r.status); }
const { value, done } = part;
if (done)
break;
size += value.byteLength;
if (size > maxResponseBytes) {
await reader.cancel();
throw new MemFailure("invalid", r.status);
}
chunks.push(value);
}
}
finally {
reader.releaseLock();
}
try {
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
}
catch {
throw new MemFailure("invalid", r.status);
}
}
export function bearer(value) {
if (!value)
return undefined;
return value.replace(/^Bearer\s+/iu, "").trim() || undefined;
}
export function serviceKey(o) { return sha256(o.server.href, o.apiKey ?? "", o.spaceId ?? ""); }
export function sha256(...parts) { return createHash("sha256").update(parts.join("\0")).digest("hex"); }
export function utf8(text) { return Buffer.byteLength(text, "utf8"); }
// trimText cuts at a UTF-8 boundary and marks the cut, so a tool's output and
// a recall block stay inside their budgets.
export function trimText(text, max) {
if (utf8(text) <= max)
return text;
let out = "", bytes = 0;
for (const ch of text) {
const size = utf8(ch);
if (bytes + size > max - 3)
break;
out += ch;
bytes += size;
}
return `${out}…`;
}