diff --git a/packages/nowledge-mem/README.md b/packages/nowledge-mem/README.md index 78241b6..2e74084 100644 --- a/packages/nowledge-mem/README.md +++ b/packages/nowledge-mem/README.md @@ -70,17 +70,12 @@ environment Magpie starts with, as Mem's own clients do: A key saved in the page is kept in Magpie's local plugin configuration, not the system keychain, and takes precedence over the environment. Enter it directly; -the form also accepts an existing `Bearer …` value. The page's **Configure -connection** form also sets the Space, Agent and the recall, Context Bundle, -capture switches; Magpie's plugin **Options** editor remains available for -advanced settings. Saving conversations remains a separate opt-in. +the form also accepts an existing `Bearer …` value. The page's **Settings** form also sets the Space, Agent, recall, Context Bundle, +capture and advanced options; Magpie's plugin **Options** editor remains available. Saving conversations remains a separate opt-in. `serverUrl` must be HTTPS, or HTTP only for `localhost`, `127.0.0.1` and `[::1]`. Credentials, a query or a fragment in the URL are refused. Set -`allowInsecureHttp` (the page's **Allow HTTP to another machine** switch) only -on a network you trust, such as a Tailscale tailnet, whose link is already -encrypted: then `http://mac-studio.tailnet.ts.net:14242` or -`http://100.x.y.z:14242` is accepted by the page and the hook alike. +`allowInsecureHttp` only for a trusted network, such as a Tailscale tailnet; prefer HTTPS elsewhere. ## One gateway, several harnesses @@ -153,8 +148,7 @@ derived value for all of them. the protocol role does not establish authorship. It does not infer native Side Chat boundaries. Configure both options in Plugins → Options. - `allowInsecureHttp`: default **false**. Permits plain HTTP to a server that - is not a loopback address, for a network you trust such as Tailscale. Prefer - HTTPS elsewhere. The page has a switch for it. + is not a loopback address. Prefer HTTPS. - `recallRemote`: default **false**. Recall and the Context Bundle go only to direct local requests and `magpie-key` from this computer. Set it to give recall also to `remote` requests (another machine) and `gateway-key` @@ -163,7 +157,7 @@ derived value for all of them. - `captureRemote`: default **false**. With `capture` on, also save conversations from `remote` and `gateway-key` requests. It does not grant recall: without `recallRemote` those requests are saved but get nothing from - Mem. Set these two in Plugins → Options; the page does not show them. + Mem. The Settings page has separate switches for these options. - `port`: the loopback port of the page's connection test, default 3479. Change it only when another program holds that port; the page reads the same value. @@ -277,14 +271,14 @@ own: the offline tests replace `globalThis.fetch` to keep Cursor's token local ## Page -The page uses only Magpie's released `magpie.options` and theme bridge. It +The page uses Magpie's released `magpie.options` and theme bridge. Before +saving it re-reads and merges edited fields, but another write between the read +and write can still be lost. The released bridge can also round integers outside +JavaScript's exact range, including in unlisted options. Use one editor at a time. It declares no reads and saving stores configuration without probing the -connection or writing Memory. It shows the Server, API key, Space, Agent, the -apps without memory (`skipAgents`), the recall, Context Bundle and capture -switches, and **Allow HTTP to another machine** (`allowInsecureHttp`). Its **What is sent** section says +connection or writing Memory. It shows connection, local and remote recall, apps excluded with `skipAgents`, local and remote capture, filtering and advanced options. Its **What is sent** section says the scope: direct local requests and `magpie-key` from this computer; other -gateway keys and remote requests are included only through `recallRemote` and -`captureRemote`. It follows Magpie's language (English, Simplified and +gateway keys and remote requests require separate `recallRemote` or `captureRemote` opt-ins. It follows Magpie's language (English, Simplified and Traditional Chinese, Japanese, German) and theme, and preserves options it does not show. diff --git a/packages/nowledge-mem/mem.mjs b/packages/nowledge-mem/mem.mjs index d6937a3..010e18b 100644 --- a/packages/nowledge-mem/mem.mjs +++ b/packages/nowledge-mem/mem.mjs @@ -4,9 +4,11 @@ // 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.4"; +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. @@ -24,6 +26,7 @@ export class MemFailure extends Error { 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; @@ -31,28 +34,12 @@ export function resolveOptions(raw = {}, env = process.env) { throw new MemFailure("invalid"); return v; }; - const bool = (name, fallback) => { - if (raw[name] !== undefined && typeof raw[name] !== "boolean") - throw new MemFailure("invalid"); - return raw[name] ?? fallback; - }; - const integer = (name, fallback, min, max) => { - const value = raw[name] ?? fallback; - if (!Number.isInteger(value) || value < min || value > max) - 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. + // 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"); + 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"); // 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. @@ -99,18 +86,18 @@ export function resolveOptions(raw = {}, env = process.env) { agentId: text(raw.agentId), hostAgentId: text(raw.hostAgentId), skipAgents, - recall: bool("recall", true), - contextBundle: bool("contextBundle", true), - capture: bool("capture", false), - recallRemote: bool("recallRemote", false), - captureRemote: bool("captureRemote", false), - captureTools: bool("captureTools", true), + 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: bool("captureCindy", false), - maxMemories: integer("maxMemories", 5, 1, 20), - maxBytes: integer("maxBytes", 6000, 512, 32768), - requestTimeoutMs: integer("requestTimeoutMs", 1500, 50, 5000), - recallBackoffMs: integer("recallBackoffMs", 30_000, 100, 300_000), + captureCindy: raw.captureCindy ?? false, + maxMemories: raw.maxMemories ?? 5, + maxBytes: raw.maxBytes ?? 6000, + requestTimeoutMs: raw.requestTimeoutMs ?? 1500, + recallBackoffMs: raw.recallBackoffMs ?? 30_000, }; } diff --git a/packages/nowledge-mem/nowledge-mem.test.mjs b/packages/nowledge-mem/nowledge-mem.test.mjs index 231de96..4d25570 100644 --- a/packages/nowledge-mem/nowledge-mem.test.mjs +++ b/packages/nowledge-mem/nowledge-mem.test.mjs @@ -709,7 +709,6 @@ test("a canceled request keeps its reason and does not back off the service", as expect(body.messages[1].content).toContain("QUARTZ-8413") }) -// The official sandbox page may configure options, but has no network or custom host API. test("remote and gateway-key requests get recall and capture only by their own opt-in (#608)", async () => { for (const origin of ["remote", "gateway-key"]) { for (const [recallRemote, captureRemote] of [[false, false], [true, false], [false, true], [true, true]]) { @@ -750,222 +749,19 @@ test("remote and gateway-key requests get recall and capture only by their own o } }) -test("configuration page uses only the released options and theme bridge", async () => { - const source = await Bun.file(new URL("./page/settings.js", import.meta.url)).text() - const calls = [...source.matchAll(/magpie\.([\w.]+)/g)].map((match) => match[1]) - expect([...new Set(calls)].sort()).toEqual(["onTheme", "options.get", "options.set", "ready.then", "theme"]) - expect(source).not.toMatch(/\b(fetch|XMLHttpRequest|WebSocket|EventSource)\b/) - const html = await Bun.file(new URL("./page/settings.html", import.meta.url)).text() - expect([...html.matchAll(/]*\bsrc="([^"]+)"/g)].map(([, src]) => src).sort()).toEqual(["_magpie/bridge.js", "i18n.js", "settings.js"]) - expect(html).not.toMatch(/]*\bsrc=)[^>]*>/) - expect([...html.matchAll(/\b(?:src|href)="((?:https?:)?\/\/[^"]+)"/g)]).toEqual([]) -}) - -test("configuration page saves the Mem connection for the shipped hook", async () => { - const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text() - const [dictionary, source, html] = await Promise.all([read("i18n.js"), read("settings.js"), read("settings.html")]) - const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, { - dataset: {}, value: "", type: id === "key" ? "password" : "text", checked: false, - setAttribute(name, value) { this[name] = value }, focus() {}, showModal() {}, close() {}, - }])) - const document = { documentElement: {}, getElementById: (id) => elements[id], querySelectorAll: () => [] } - const location = { href: "http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html", assign(url) { this.assigned = url } } - const window = { name: "" } - let options = { apiKeyEnv: "NMEM_API_KEY", recall: true, contextBundle: true, capture: false, maxMemories: 5, maxBytes: 6000 } - let writes = 0 - const magpie = { - theme: { lang: "en" }, ready: Promise.resolve(), onTheme() {}, - options: { get: async () => ({ ...options }), set: async (next) => { options = { ...next }; writes++ } }, - } - runInNewContext(`${dictionary}\n${source}`, { document, magpie, window, location, navigator: { language: "en" }, URL }) - await new Promise(setImmediate) - const save = () => elements.save.onclick({ preventDefault() {} }) - const original = { ...options } - elements.url.value = "http://127.0.0.1:14242" - elements.space.value = " space-7 " - 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, - serverUrl: "http://127.0.0.1:14242/", - spaceId: "space-7", - 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 }) - hookContext.state = {} - await onRequest(structuredClone(chat), hookContext) - expect(of("memories/search")[0].init.headers.Authorization).toBe("Bearer nmem_page_key") - expect(of("memories/search")[0].url.origin).toBe("http://127.0.0.1:14242") - await onResponse(reply, { ...hookContext, success: true }) - expect(of("threads/import")[0].body.space_id).toBe("space-7") - expect(of("threads/import")[0].body.metadata.agent_id).toBe("agent-3") - - elements.configure.onclick() - expect(elements.key.type).toBe("password") - expect(elements.key.value).toBe("nmem_page_key") - elements["show-key"].onclick() - expect(elements.key.type).toBe("text") - expect(elements["show-key"]["aria-pressed"]).toBe("true") - elements.settings.onclose() - expect(elements.key.type).toBe("password") - expect(elements.key.value).toBe("") - - for (const invalid of ["bad key", "bad\nkey"]) { - elements.key.value = invalid - await save() - expect(writes).toBe(1) - expect(elements.result.dataset.message).toBe("invalidKey") - } - for (const invalid of ["ftp://mem.example.com", "http://mem.example.com", "https://mem.example.com?token=x"]) { - elements.url.value = invalid - await save() - expect(writes).toBe(1) - 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 - // reads only the way back and the language. - elements["test-saved"].onclick() - expect(location.assigned).toBe("http://127.0.0.1:3479/test?lang=en") - expect(options.apiKey).toBeUndefined() - expect(options.spaceId).toBeUndefined() - expect(options.agentId).toBeUndefined() - expect(options.apiKeyEnv).toBe("NMEM_API_KEY") - expect(options.maxBytes).toBe(6000) - expect(elements["summary-space"].textContent).toBe("Default Space") -}) - -test("configuration page takes a tailnet HTTP server only with Allow HTTP to another machine (#608)", async () => { - const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text() - const [dictionary, source, html] = await Promise.all([read("i18n.js"), read("settings.js"), read("settings.html")]) - const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, { - dataset: {}, value: "", type: id === "key" ? "password" : "text", checked: false, - setAttribute(name, value) { this[name] = value }, focus() {}, showModal() {}, close() {}, - }])) - expect(elements["insecure-http"]).toBeDefined() - const document = { documentElement: {}, getElementById: (id) => elements[id], querySelectorAll: () => [] } - const location = { href: "http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html", assign(url) { this.assigned = url } } - let options = { serverUrl: "http://mac-studio.tailnet.ts.net:14242", recall: true, maxBytes: 6000 } - let writes = 0 - const magpie = { - theme: { lang: "en" }, ready: Promise.resolve(), onTheme() {}, - options: { get: async () => ({ ...options }), set: async (next) => { options = { ...next }; writes++ } }, - } - runInNewContext(`${dictionary}\n${source}`, { document, magpie, window: { name: "" }, location, navigator: { language: "en" }, URL }) - await new Promise(setImmediate) - const save = () => elements.save.onclick({ preventDefault() {} }) - - // without the option, a saved tailnet HTTP URL can't be tested or saved - expect(elements["insecure-http"].checked).toBe(false) - elements["test-saved"].onclick() - expect(location.assigned).toBeUndefined() - expect(elements.configured.dataset.message).toBe("invalidUrl") - for (const url of ["http://mac-studio.tailnet.ts.net:14242", "http://100.101.102.103:14242"]) { - elements.url.value = url - await save() - expect(writes).toBe(0) - expect(elements.result.dataset.message).toBe("invalidUrl") - } - - // with it, the page saves what the hook then uses - elements["insecure-http"].checked = true - for (const url of ["http://100.101.102.103:14242", "http://mac-studio.tailnet.ts.net:14242"]) { - elements.url.value = url - await save() - expect(elements.result.dataset.message).toBe("saveSucceeded") - expect(options).toMatchObject({ serverUrl: `${url}/`, allowInsecureHttp: true, maxBytes: 6000 }) - expect(resolveOptions(options).server.href).toBe(`${url}/`) - } - expect(writes).toBe(2) - elements["test-saved"].onclick() - expect(location.assigned).toBe("http://127.0.0.1:3479/test?lang=en") - mock() - calls.length = 0 - await onRequest(structuredClone(chat), ctx("chat", { options })) - expect(of("memories/search")[0].url.href).toBe("http://mac-studio.tailnet.ts.net:14242/memories/search") - - // the dialog shows the saved option; the rest of the URL rules still hold - elements["insecure-http"].checked = false - elements.configure.onclick() - expect(elements["insecure-http"].checked).toBe(true) - for (const invalid of ["ftp://mem.example.com", "http://user:pw@mac-studio.tailnet.ts.net:14242", "http://mac-studio.tailnet.ts.net:14242?token=x"]) { - elements.url.value = invalid - await save() - expect(writes).toBe(2) - expect(elements.result.dataset.message).toBe("invalidUrl") - } - - // turning it off drops the option, so the tailnet URL is refused again - elements["insecure-http"].checked = false - elements.url.value = "https://mem.example.com" - await save() - expect(writes).toBe(3) - expect(options.allowInsecureHttp).toBeUndefined() - elements.url.value = "http://mac-studio.tailnet.ts.net:14242" - await save() - expect(writes).toBe(3) - expect(elements.result.dataset.message).toBe("invalidUrl") -}) - -test("configuration page follows the host language without losing edits or messages", async () => { - const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text() - const [dictionary, source, html] = await Promise.all([read("i18n.js"), read("settings.js"), read("settings.html")]) - const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, { - dataset: {}, value: "", hidden: false, checked: false, setAttribute(name, value) { this[name] = value }, focus() {}, - }])) - const translated = [...html.matchAll(/data-t="([^"]+)"/g)].map(([, key]) => ({ dataset: { t: key } })) - const document = { - documentElement: {}, getElementById: (id) => elements[id], - querySelectorAll: (selector) => selector === "[data-t]" ? translated : Object.values(elements).filter((el) => el.dataset.message), - } - let repaint - const magpie = { - theme: { lang: "zh" }, ready: Promise.resolve(), onTheme: (fn) => { repaint = fn }, - options: { get: async () => ({ serverUrl: "http://127.0.0.1:14242", capture: true }) }, - } - const window = { name: "" } - const location = { href: "http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html", assign() {} } - const { messages, languageFor, languageTags } = runInNewContext(`${dictionary}\n${source}\nnowledgeMemI18n`, { document, magpie, window, location, navigator: { language: "en" }, URL }) - await new Promise(setImmediate) - for (const language of ["en", "zh", "zh-TW", "ja", "de"]) { - expect(Object.keys(messages[language]).sort()).toEqual(Object.keys(messages.en).sort()) - expect(Object.values(messages[language]).every((text) => typeof text === "string" && text.length > 0)).toBe(true) - } - for (const [input, expected] of [["zh-CN", "zh"], ["zh-Hant-TW", "zh-TW"], ["zh_HK", "zh-TW"], ["ja-JP", "ja"], ["de-AT", "de"], ["fr-FR", "en"]]) { - expect(languageFor(input)).toBe(expected) - } - elements.url.value = "unsaved address" - await elements.save.onclick({ preventDefault() {} }) - for (const language of ["en", "zh-TW", "ja", "de", "zh"]) { - magpie.theme.lang = language - repaint() - expect(document.documentElement.lang).toBe(languageTags[language]) - expect(elements.url.value).toBe("unsaved address") - expect(elements.configured.textContent).toBe(messages[language].loaded) - expect(elements.result.textContent).toBe(messages[language].invalidUrl) - expect(elements.result.dataset.error).toBe("true") - for (const el of translated) expect(el.textContent).toBe(messages[language][el.dataset.t]) +test("remote opt-ins apply consistently across all gateway protocols", async () => { + const fixtures = [ + ["chat",chat,reply], + ["responses",{input:[{role:"user",content:[{type:"input_text",text:"Quartz codename?"}]}]},{status:"completed",output:[{type:"message",role:"assistant",content:[{type:"output_text",text:"answer"}]}]}], + ["anthropic",{messages:[{role:"user",content:[{type:"text",text:"Quartz codename?"}]}]},{type:"message",role:"assistant",content:[{type:"text",text:"answer"}],stop_reason:"end_turn"}], + ["gemini",{contents:[{role:"user",parts:[{text:"Quartz codename?"}]}]},{candidates:[{content:{role:"model",parts:[{text:"answer"}]},finishReason:"STOP"}]}], + ] + for (const origin of ["remote","gateway-key"]) for (const [protocol,input,response] of fixtures) { + reset();calls.length=0;mock() + const [,c]=capturing(protocol,{origin,options:{recallRemote:true,captureRemote:true}}) + await onRequest(structuredClone(input),c) + await onResponse(response,{...c,success:true}) + expect(of("memories/search")).toHaveLength(1) + expect(of("threads/import")).toHaveLength(1) } }) diff --git a/packages/nowledge-mem/package.json b/packages/nowledge-mem/package.json index 366d186..2976f92 100644 --- a/packages/nowledge-mem/package.json +++ b/packages/nowledge-mem/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/gateway-nowledge-mem", - "version": "0.1.4", + "version": "0.1.5", "description": "Nowledge Mem recall, Context Bundle and optional conversation capture at the Magpie gateway, for every connected harness", "type": "module", "files": [ diff --git a/packages/nowledge-mem/page-layout.test.mjs b/packages/nowledge-mem/page-layout.test.mjs new file mode 100644 index 0000000..ad1b7fe --- /dev/null +++ b/packages/nowledge-mem/page-layout.test.mjs @@ -0,0 +1,64 @@ +// This small layout regression runs only with Linux Chrome. It uses a data +// URL, a temporary profile and no network or user browser state. +import { expect, test } from "bun:test" +import { mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { runInNewContext } from "node:vm" + +const chrome = process.platform === "linux" && + (Bun.which("google-chrome") || Bun.which("google-chrome-stable") || Bun.which("chromium") || Bun.which("chromium-browser")) + +test.skipIf(!chrome)("narrow settings footer keeps translated actions inside the dialog", async () => { + const read = (name) => Bun.file(new URL(`./page/${name}`, import.meta.url)).text() + const [html, css, dictionary] = await Promise.all([read("settings.html"), read("style.css"), read("i18n.js")]) + const footer = html.match(/