@echomem/mcp 1.4.71 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +34 -6
  2. package/dist/agent-messages-fallback.js +45 -0
  3. package/dist/backend-network-guard.js +48 -0
  4. package/dist/backend-policy.js +46 -0
  5. package/dist/claude-evidence.js +91 -0
  6. package/dist/codex-sync.js +2 -1
  7. package/dist/cowork-source.js +140 -0
  8. package/dist/desktop-presence.js +40 -0
  9. package/dist/desktop-save-activity.js +128 -0
  10. package/dist/durable-entry.js +20 -5
  11. package/dist/headless-runtime.js +4 -0
  12. package/dist/hud/cli.js +16 -17
  13. package/dist/hud/diagnostics.js +2 -1
  14. package/dist/hud/hooks.js +97 -62
  15. package/dist/hud/server.js +2 -1
  16. package/dist/index.js +727 -170
  17. package/dist/lifecycle-entry.js +29 -0
  18. package/dist/local-data-paths.js +15 -1
  19. package/dist/local-usage.js +72 -0
  20. package/dist/memory-intent.js +150 -0
  21. package/dist/memory-links.js +6 -0
  22. package/dist/migrate.js +2 -1
  23. package/dist/package-metadata.js +7 -7
  24. package/dist/pending-save.js +49 -0
  25. package/dist/save-local-trace.js +26 -0
  26. package/dist/save-note-store.js +50 -0
  27. package/dist/save-receipt-store.js +58 -0
  28. package/dist/save-receipt.js +42 -0
  29. package/dist/save-retry.js +43 -0
  30. package/dist/setup-page/client-extraction.js +2 -1
  31. package/dist/setup.js +13 -13
  32. package/dist/source-session-hook.js +16 -2
  33. package/dist/source-session-local.js +241 -0
  34. package/dist/source-session-pretool-hook.js +54 -0
  35. package/dist/source-session.js +4 -0
  36. package/dist/source-snapshot-export.js +68 -0
  37. package/dist/source-snapshot.js +99 -0
  38. package/dist/strict-ingest-contract.js +31 -0
  39. package/dist/strict-raw-session.js +473 -0
  40. package/dist/tool-map-cache.js +62 -0
  41. package/dist/turn-end-saves.js +104 -0
  42. package/dist/v1-contract.js +92 -45
  43. package/package.json +5 -3
  44. package/templates/codex-skills/echomem-save/SKILL.md +26 -27
  45. package/templates/echomem-recall.md +27 -21
  46. package/dist/save-checkpoint-hook.js +0 -122
@@ -0,0 +1,29 @@
1
+ import "./backend-network-guard.js";
2
+ import { resolveBackendURL } from "./backend-policy.js";
3
+ // Persist the same non-secret endpoint/ownership as the installed MCP. Hook
4
+ // processes do not inherit a host's per-server environment. Set these before
5
+ // loading lifecycle modules, whose endpoint constants initialize on import.
6
+ const args = process.argv.slice(2);
7
+ const take = (flag) => {
8
+ const index = args.indexOf(flag);
9
+ if (index < 0)
10
+ return undefined;
11
+ if (!args[index + 1])
12
+ throw new Error(`Missing ${flag}`);
13
+ return args.splice(index, 2)[1];
14
+ };
15
+ const apiBase = take("--api-base-url");
16
+ if (apiBase) {
17
+ const url = new URL(apiBase);
18
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)
19
+ throw new Error("Invalid lifecycle API endpoint");
20
+ process.env.ECHO_API_BASE_URL = apiBase;
21
+ }
22
+ const managed = args.indexOf("--desktop-managed");
23
+ if (managed >= 0) {
24
+ args.splice(managed, 1);
25
+ process.env.ECHO_DESKTOP_MANAGED = "1";
26
+ }
27
+ resolveBackendURL();
28
+ process.argv = [process.argv[0], process.argv[1], ...args];
29
+ await import("./hud/cli.js");
@@ -65,7 +65,21 @@ export function resolveCodexSessionRoots(opts = {}) {
65
65
  const roots = [];
66
66
  const seenRealpaths = new Set();
67
67
  for (const candidate of candidates) {
68
- const resolved = resolveReadableDirectory(path.join(root, candidate.child));
68
+ const candidatePath = path.join(root, candidate.child);
69
+ const resolved = resolveReadableDirectory(candidatePath);
70
+ if (!resolved && opts.failOnUnreadable) {
71
+ // A missing optional root is fine; an inaccessible root cannot prove that
72
+ // a local transcript is absent. lstat also keeps broken symlinks fail-closed.
73
+ try {
74
+ fs.lstatSync(candidatePath);
75
+ }
76
+ catch (error) {
77
+ if (error.code === "ENOENT")
78
+ continue;
79
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
80
+ }
81
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
82
+ }
69
83
  if (!resolved || seenRealpaths.has(resolved))
70
84
  continue;
71
85
  seenRealpaths.add(resolved);
@@ -0,0 +1,72 @@
1
+ import { resolveBackendURL } from "./backend-policy.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { echoConfigDir } from "./keystore.js";
6
+ import { MCP_PACKAGE_VERSION } from "./package-metadata.js";
7
+ let flushing = false;
8
+ /** Local development only; a durable journal/outbox, with no prompt or result content. */
9
+ export function recordLocalUsage(usage, options = {}) {
10
+ const env = options.env ?? process.env;
11
+ if (env.ECHO_DESKTOP_MANAGED !== "1" || env.NODE_ENV === "test" || env.NODE_TEST_CONTEXT
12
+ || env.DO_NOT_TRACK || env.ECHO_DISABLE_TELEMETRY || /^(0|false|off|no)$/i.test(env.ECHO_TELEMETRY ?? ""))
13
+ return;
14
+ try {
15
+ const backend = new URL(resolveBackendURL("https://echoknows.com", env));
16
+ if (!['localhost', '127.0.0.1', '[::1]'].includes(backend.hostname))
17
+ return;
18
+ const root = options.root ?? path.join(echoConfigDir(), "local-usage");
19
+ const config = JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8"));
20
+ if (config.enabled !== true)
21
+ return;
22
+ const identity = fs.readFileSync(path.join(root, "installation-id"), "utf8").trim();
23
+ if (!/^[0-9a-f-]{36}$/i.test(identity))
24
+ return;
25
+ const uuid = randomUUID();
26
+ const now = new Date();
27
+ const safe = (value) => value.slice(0, 80).replace(/[^a-zA-Z0-9_. -]/g, '_');
28
+ const row = { uuid, event: "Echo Local Feature Used", distinct_id: `echo-local:${identity}`, timestamp: now.toISOString(), properties: {
29
+ analytics_scope: 'echo_local_usage_v1', environment: 'local_development', component: 'mcp',
30
+ action: safe(usage.action), source: safe(usage.source), outcome: safe(usage.outcome), duration_ms: usage.duration_ms,
31
+ display_kind: 'not_applicable', is_main_display: false, page: 'none', local_timezone: 'America/Los_Angeles',
32
+ local_day: new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Los_Angeles' }).format(now),
33
+ local_installation_id: identity, app_version: MCP_PACKAGE_VERSION, '$insert_id': uuid, '$process_person_profile': false,
34
+ } };
35
+ fs.mkdirSync(path.join(root, 'pending'), { recursive: true, mode: 0o700 });
36
+ const data = JSON.stringify(row);
37
+ fs.appendFileSync(path.join(root, 'events.jsonl'), data + '\n', { mode: 0o600 });
38
+ const pending = path.join(root, 'pending', uuid + '.json');
39
+ fs.writeFileSync(pending + '.tmp', data, { mode: 0o600 });
40
+ fs.renameSync(pending + '.tmp', pending);
41
+ if (options.send !== false)
42
+ void flushLocalUsage(root);
43
+ }
44
+ catch { /* Usage collection must never affect a tool call. */ }
45
+ }
46
+ export async function flushLocalUsage(root = path.join(echoConfigDir(), 'local-usage')) {
47
+ if (flushing)
48
+ return;
49
+ flushing = true;
50
+ try {
51
+ const config = JSON.parse(fs.readFileSync(path.join(root, 'config.json'), 'utf8'));
52
+ if (config.enabled !== true || !config.posthog_token || !config.posthog_host?.startsWith('https://'))
53
+ return;
54
+ const files = fs.readdirSync(path.join(root, 'pending')).filter(f => /^[0-9a-f-]{36}\.json$/i.test(f)).slice(0, 50);
55
+ if (!files.length)
56
+ return;
57
+ const batch = files.map(file => JSON.parse(fs.readFileSync(path.join(root, 'pending', file), 'utf8')));
58
+ const response = await fetch(config.posthog_host + '/batch/', { method: 'POST', headers: { 'Content-Type': 'application/json' },
59
+ body: JSON.stringify({ api_key: config.posthog_token, batch }), signal: AbortSignal.timeout(5000) });
60
+ if (response.ok)
61
+ for (const file of files) {
62
+ try {
63
+ fs.unlinkSync(path.join(root, 'pending', file));
64
+ }
65
+ catch { }
66
+ }
67
+ }
68
+ catch { /* Retry pending events on the next call or from Echo Local. */ }
69
+ finally {
70
+ flushing = false;
71
+ }
72
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Host envelopes that arrive inside user messages. They carry no user-stated
3
+ * fact and, at ~10k characters per Codex session, they are the largest
4
+ * distractor the extractor sees. Only these
5
+ * exact host tags are stripped; a user pasting their own markup is untouched.
6
+ */
7
+ const HOST_TAGS = [
8
+ "INSTRUCTIONS", "environment_context", "external_codex_apps_open_page", "in-app-browser-context",
9
+ "local-command-caveat", "command-name", "command-message", "command-args", "local-command-stdout", "system-reminder",
10
+ ];
11
+ const HOST_BLOCK = new RegExp(`<(${HOST_TAGS.join("|")})(?:\\s[^>]*)?>[\\s\\S]*?</\\1>`, "g");
12
+ const AGENTS_HEADER = /^\s*# AGENTS\.md instructions\s*/;
13
+ const REQUEST_LABEL = /^\s*## My request:\s*/;
14
+ /** The user's own words with host envelopes removed; the same string when there are none. */
15
+ export function stripHostNoise(text) {
16
+ HOST_BLOCK.lastIndex = 0;
17
+ if (!HOST_BLOCK.test(text) && !AGENTS_HEADER.test(text))
18
+ return text;
19
+ return text.replace(AGENTS_HEADER, "").replace(HOST_BLOCK, "").replace(REQUEST_LABEL, "").trim();
20
+ }
21
+ /** The user's own request text, with the host's ambient envelope removed. */
22
+ export function userRequestText(text) {
23
+ const original = text.trim();
24
+ const opener = '<in-app-browser-context source="ambient-ui-state">';
25
+ const closing = "</in-app-browser-context>";
26
+ let request = original;
27
+ if (original.startsWith("<send_user_message_question_reply>")) {
28
+ // Question labels/IDs are host metadata. Only the submitted answer can
29
+ // express intent ("input" contains "put", but is not a save command).
30
+ const reply = /^<send_user_message_question_reply>\s*([\s\S]*?)\s*<\/send_user_message_question_reply>$/.exec(original);
31
+ if (!reply)
32
+ return "";
33
+ try {
34
+ const items = JSON.parse(reply[1]);
35
+ if (!Array.isArray(items) || !items.every(item => item && typeof item.answer === "string"))
36
+ return "";
37
+ request = items.map(item => item.answer).join("\n");
38
+ }
39
+ catch {
40
+ return "";
41
+ }
42
+ }
43
+ if (original.startsWith(opener)) {
44
+ // This exact host envelope carries ambient data, not user intent. Only the
45
+ // request after its single closed block counts; a malformed envelope is no request.
46
+ const end = original.indexOf(closing);
47
+ if (end < 0 || original.indexOf(closing, end + closing.length) >= 0)
48
+ return "";
49
+ const tail = original.slice(end + closing.length).trim();
50
+ if (!/^## My request:\s*/.test(tail))
51
+ return "";
52
+ request = tail.replace(/^## My request:\s*/, "");
53
+ }
54
+ request = stripHostNoise(request).trim();
55
+ if (request.startsWith("<") || request.startsWith("# AGENTS.md"))
56
+ return "";
57
+ return request.replace(/^(?:(?:okay|ok)\b|可以(?=[,,。!!\s])|好的?|对的?|嗯|行)[,,。!!\s]*/i, "").trim();
58
+ }
59
+ const CHINESE_SAVE_VERB = "(?:保存|存(?!储|在|量)|记住|记下|记一下|记录|记到|记进|记入)";
60
+ const SAVE_VERB = `(?:${CHINESE_SAVE_VERB}|\\b(?:save|remember|store|keep|add|put)\\b)`;
61
+ const MEMORY_TARGET = "(?:记忆|长期记忆|\\b(?:memory|memories|echo(?:\\s*mem(?:ory)?)?)\\b)";
62
+ const DECLINE = "(?:先|暂时)?(?:不要|别|不用|不需要|不必|不想|don't\\s+|do not\\s+|never\\s+|no need to\\s+)(?:再|去)?\\s*(?:保存|存|记住|记下|记录|save\\b|remember\\b|store\\b)";
63
+ const DECLINE_FIRST = new RegExp(`^${DECLINE}`, "i");
64
+ // Later in the message the refusal must be about the conversation itself, so "don't save the
65
+ // file yet" inside a longer request is not one.
66
+ const DECLINE_LATER = new RegExp(`^${DECLINE}\\s*(?:一下)?(?:$|这|它|以上|上面|刚才|到|进|入|(?:any of )?(?:this|that|it|these|those|any(?:thing)?)\\b|(?:to|in(?:to)?)\\s+(?:memory|echo)|(?:the|this|our)\\s+(?:conversation|chat|session|turn|message))`, "i");
67
+ /** The user asks that this message not be saved: as its first words, or as a sentence of its
68
+ * own anywhere in it. Typographic apostrophes read as plain ones. */
69
+ export function isMemorySaveDeclined(text) {
70
+ const request = userRequestText(text).replace(/[\u2018\u2019\u02BC]/g, "'");
71
+ const sentences = request.split(/[.!?。!?;;::\n]+/).map(sentence => sentence.trim().replace(/^(?:请|please\s+)/i, ""));
72
+ return sentences.some((sentence, index) => (index === 0 ? DECLINE_FIRST : DECLINE_LATER).test(sentence));
73
+ }
74
+ /** A status question is not retention consent, even in punctuation-free speech input. */
75
+ export function isMemorySaveStatusQuestion(text) {
76
+ const request = userRequestText(text);
77
+ if (!request)
78
+ return false;
79
+ if (/^(?:did|have|has|had|was|were|is|are)\b[^.!?\n]{0,160}\b(?:saved?|stored?|remembered|memorized)\b/i.test(request))
80
+ return true;
81
+ const mentionsSaving = /(?:保存|存(?:到|进|入|过|好|了|记忆|\s)|记住|记下|记录|写入)/.test(request);
82
+ return mentionsSaving && /(?:了[吗么嘛没]|了没有|过[吗么嘛]|好没|成功[吗么嘛])[??。.!!\s]*$/.test(request);
83
+ }
84
+ /**
85
+ * A direct request to save: a save verb together with a memory target
86
+ * ("存到我的记忆里", "save this to echo", "记一下到 EchoMem"), or a bare
87
+ * imperative ("存一下", "remember this"). Negations, hypotheticals, quoted
88
+ * examples, questions about the rules and questions about past state are not
89
+ * requests. When the user asks to save, the answer must be yes.
90
+ */
91
+ export function isExplicitSaveRequest(text) {
92
+ const request = userRequestText(text);
93
+ if (!request)
94
+ return false;
95
+ if (isMemorySaveStatusQuestion(request))
96
+ return false;
97
+ // Quoted phrase, rule discussion, hypothetical, or a question about meaning or past state.
98
+ if (/^["'“‘`]/.test(request))
99
+ return false;
100
+ if (/^(?:如果|假如|当用户|当我|例如|比如|规则|判断标准|if\b|when\b|for example\b|e\.g\.)/i.test(request))
101
+ return false;
102
+ if (/^(?:what|how|why|which|does|is|are|什么|怎么|为什么|为啥)\b/i.test(request) || /^(?:什么|怎么|为什么|为啥)/.test(request))
103
+ return false;
104
+ if (/(?:了吗|是否|有没有|存过|已经存|did you|have you|was it|is it)/i.test(request) && /[??]\s*$/.test(request))
105
+ return false;
106
+ // A negation right before the verb: "不要存", "先不保存", "don't save", "no need to remember".
107
+ if (new RegExp(`(?:不要|别|不用|不需要|不必|先不|暂不|不想|don't|do not|never|no need to|not)\\s*(?:再|去)?\\s*${SAVE_VERB}`, "i").test(request))
108
+ return false;
109
+ if (/^(?:不要|别|不用|不需要|don't\b|do not\b)/i.test(request))
110
+ return false;
111
+ // Require an actual retention request, not a coding/research instruction
112
+ // mentioning memory storage. Lexical co-occurrence alone is insufficient.
113
+ const imperative = request.replace(/^(?:请帮我|请你|请|你帮我|帮我|你)\s*/, "")
114
+ .replace(/^(?:一定要|务必)\s*/, "");
115
+ // Compound artifact requests can ask for retention in a later clause:
116
+ // "分析这个事故,然后封装成一个记忆". Match a whole imperative clause,
117
+ // not a quoted example, a save-handler implementation request, or a noun mention.
118
+ const packagesMemory = imperative.split(/[,,。;;!!??\n]/).some(clause => /^(?:然后|并且|同时|再)?\s*(?:请|帮我)?\s*封装成(?:一条|一个)?\s*(?:记忆|长期记忆|Echo\s*Memory)\s*$/i.test(clause.trim()));
119
+ if (packagesMemory)
120
+ return true;
121
+ // A direct "remember <fact/preference>" does not need the word "memory".
122
+ // Keep file-saving and implementation requests outside this exception.
123
+ if (/^(?:记住|记下|记一下|记下来)\s*\S/.test(imperative)
124
+ || /^(?:please\s+)?(?:(?:can|could|would)\s+you\s+)?remember(?:\s|:)/i.test(imperative)
125
+ || /^(?:保存|存)(?:一下|下来|下)(?:这个|这条|这段|这些|它|结果|刚才|上面|以上)(?!文件)/.test(imperative)
126
+ || /^(?:可以|能不能|能否)(?:帮我)?(?:保存|存|记住)(?:一下)?(?:这个|这条|这段|这些|它|结果)(?:吗)?[??。!!\s]*$/.test(imperative))
127
+ return true;
128
+ const asksRetention = new RegExp(`^${CHINESE_SAVE_VERB}`).test(imperative)
129
+ || new RegExp(`^(?:把|将)[^。!?!?\\n]{1,120}?${CHINESE_SAVE_VERB}(?:到|进|入|成|为|在|一下|下来|住|下)`).test(imperative)
130
+ || /^(?:把|将)[^。!?!?\n]{1,120}?(?:记到|记进|记入)/.test(imperative)
131
+ || /^(?:please\s+)?(?:(?:can|could|would)\s+you\s+)?(?:save|remember|store|keep|add|put)(?=\s|$)/i.test(imperative)
132
+ || /^(?:看一下)?[^。!?!?\n]{0,60}(?:能不能|可以|能否)(?:帮我)?(?:保存|存|记住|记录)/.test(imperative);
133
+ const verb = new RegExp(SAVE_VERB, "i");
134
+ const target = new RegExp(MEMORY_TARGET, "i");
135
+ if (asksRetention && verb.test(request) && target.test(request))
136
+ return true;
137
+ // Bare imperatives with no target named.
138
+ return /^(?:请|帮我|请帮我|你)?(?:保存|存|记)(?:一下|下来|下|住)?(?:这个|这条|这段|这些|它|结果)?(?:一下)?[。!!\s]*$/.test(request)
139
+ || /^(?:please\s+)?(?:(?:can|could|would)\s+you\s+)?(?:save|remember|store)\s+(?:this|that|it|these)[.!?\s]*$/i.test(request)
140
+ // The whole message is a request to save the conversation: "save", "save convo", "save this conversation now".
141
+ || /^(?:please\s+)?(?:(?:can|could|would)\s+you\s+)?save(?:\s+(?:this|that|the|our))?(?:\s+(?:conversation|convo|chat|session|thread|discussion))?(?:\s+(?:now|again|please))*[.!\s]*$/i.test(request)
142
+ || /^(?:请|帮我|请帮我|你)?(?:保存|存)(?:一下|下)?(?:这次|这个|本次|当前)?(?:对话|会话|聊天|讨论)[。!!\s]*$/.test(request);
143
+ }
144
+ export function latestUserRequestsSave(messages) {
145
+ for (let index = messages.length - 1; index >= 0; index--) {
146
+ if (messages[index].role === "user" && userRequestText(messages[index].text))
147
+ return isExplicitSaveRequest(messages[index].text);
148
+ }
149
+ return false;
150
+ }
@@ -0,0 +1,6 @@
1
+ export function memoryMarkdownLink(url, keys, description) {
2
+ const rawLabel = String(keys || description || "Open memory").replace(/\s+/g, " ").trim();
3
+ const label = (rawLabel.length > 100 ? `${rawLabel.slice(0, 97).trim()}…` : rawLabel)
4
+ .replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
5
+ return `[${label}](${url})`;
6
+ }
package/dist/migrate.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { resolveBackendURL } from "./backend-policy.js";
1
2
  /**
2
3
  * `echomem-mcp migrate` — one-shot bulk back-fill of the user's EXISTING local coding-agent history
3
4
  * (Codex + Claude Code + local Claude Desktop Cowork) into their Echo cloud. The onboarding
@@ -31,7 +32,7 @@ import { fetchEncryptionConfig } from "./encryption.js";
31
32
  import { discoverCodexSessionFiles } from "./codex-session-files.js";
32
33
  import { resolveClaudeCoworkSessionRoots, resolveClaudeProjectsDir } from "./local-data-paths.js";
33
34
  import { eachJsonLine, walkLocalFiles } from "./local-jsonl.js";
34
- const API_BASE = (process.env.ECHO_API_BASE_URL || "https://echo-mem-chrome.vercel.app").replace(/\/$/, "");
35
+ const API_BASE = (resolveBackendURL()).replace(/\/$/, "");
35
36
  const RATE_MAX = 28; // stay under the import-jobs /run limit of 30 / 60s
36
37
  const RATE_WINDOW_MS = 60_000;
37
38
  export const MIGRATE_CONCURRENCY = 6; // import jobs run concurrently; request STARTS are still throttled <RATE_MAX/min
@@ -36,8 +36,8 @@ export const MCP_VAULT_UNLOCK_INSTRUCTION = MCP_DESKTOP_MANAGED
36
36
  const MCP_UPDATE_INSTRUCTION = MCP_DESKTOP_MANAGED
37
37
  ? "install the MCP update from Echo Desktop (Settings, MCP)"
38
38
  : `updates auto-install in the background; on failure run \`${MCP_UPDATE_ALL_COMMAND}\``;
39
- export const MEMORY_CITATION_INSTRUCTION = 'If the user-facing answer materially relies on one or more EchoMem memories, end it with a compact "EchoMem sources:" list containing only the memories actually used. For memories owned by teammates or accepted friends, call record_memory_citations immediately before the final answer with those exact Memory IDs. Do not cite memories that were merely retrieved. Use each memory key as the Markdown label and its canonical https://echoknows.com/memory/<memory-id> URL. Omit the sources section and citation receipt when no memory informed the answer.';
40
- export const SAVED_MEMORY_RECEIPT_INSTRUCTION = 'After save_conversation succeeds and returns one or more saved memory IDs, follow the already-written answer with a short closing "EchoMem saved:" list containing every memory created by that call; do not repeat the answer. Use each memory key as the Markdown label and its canonical https://echoknows.com/memory/<memory-id> URL. This save receipt is separate from "EchoMem sources:" and does not imply that the newly saved memories informed the answer.';
39
+ export const MEMORY_CITATION_INSTRUCTION = 'If the user-facing answer materially relies on one or more EchoMem memories, end it with a compact "EchoMem sources:" list containing only the memories actually used. For memories owned by teammates or accepted friends, call record_memory_citations immediately before the final answer with those exact Memory IDs. Do not cite memories that were merely retrieved. Use each memory key as the Markdown label. When a returned title link uses the local backend /api/local/memories/<memory-id>/open entry, preserve that exact URL as the primary clickable title so it opens Echo Local; retain the canonical https://echoknows.com/memory/<memory-id> URL as a secondary web link. Otherwise use the canonical URL. Omit the sources section and citation receipt when no memory informed the answer.';
40
+ export const SAVED_MEMORY_RECEIPT_INSTRUCTION = 'Show an "EchoMem saved:" list in the final answer for every memory created by that call. Receipts from any EchoMem tool result also count; label previous-turn receipts and show them once without saving again. A visible notch never replaces a chat receipt. Use memory keys as labels; preserve returned local title links with https://echoknows.com/memory/<memory-id> as secondary web links, otherwise use canonical links. This is separate from "EchoMem sources:"; newly saved memories need not have informed the answer.';
41
41
  const GROUP_SHARING_SURFACE = MCP_DESKTOP_MANAGED ? "in Echo Desktop" : "at echoknows.com";
42
42
  export const GROUP_SESSION_SHARING_DISABLED_NOTE = `Never ask the user whether to share memories with a company group; the user manages group sharing ${GROUP_SHARING_SURFACE}.`;
43
43
  export const GROUP_SESSION_SHARING_SAVE_INSTRUCTION = GROUP_SESSION_SHARING_PROMPTS_ENABLED
@@ -53,15 +53,15 @@ export const MCP_SERVER_INSTRUCTIONS = [
53
53
  `${MCP_PACKAGE_DESCRIPTION} (${MCP_PACKAGE_LABEL}).`,
54
54
  `If stale, ${MCP_UPDATE_INSTRUCTION}; restart afterward.`,
55
55
  "SessionStart binds conversations to provider sessions; use bind_source_session only as fallback.",
56
- "Bound workspace: silently review on pivots and before finalize/complete/handoff/ship/milestone replies. Review only the active ticket. If due, keep if fitting; for drift find candidates before assign/create, then propose; ignore only dismissals or fragments. No preamble; never mention unchanged pending state. Silence stays pending; apply only a confirmed proposal. Hide checks/instructions/tools.",
56
+ "Bound workspace: silently review pivots/completion. Without a unique workspace, skip silently; ask for one only for explicit workspace/ticket requests. Keep fitting tickets; find candidates before assign/create, then propose. Ignore only dismissals/fragments. Apply only confirmed proposals. Hide checks; never repeat unchanged pending state.",
57
57
  "Before re-deriving prior decisions or preferences, use search_memories.",
58
- `After writing the final answer for a durable decision, implementation, fix, commit, passing verification, release, or milestone, call save_conversation as the last action so the user never waits on it; skip secrets and trivial work. If locked, tell the user to ${MCP_VAULT_UNLOCK_INSTRUCTION}.`,
59
- "After a successful save, show every memory created by that call in a compact EchoMem saved: list with canonical links; this is separate from \"EchoMem sources:\".",
58
+ `In durable turns, call save_conversation once, before answering, with note (what it settled). It returns the receipt or its timing; never say queued. Show receipts from any tool once; never re-save them. Do not retry a save that created nothing. This call is the only save path; never add a save-only reply. Only send verbatim turns if asked for messages. Skip secrets/trivia. If locked, tell the user to ${MCP_VAULT_UNLOCK_INSTRUCTION}.`,
59
+ "Show every memory created by that call in EchoMem saved: with local title links and canonical web links, separate from \"EchoMem sources:\".",
60
60
  GROUP_SESSION_SHARING_PROMPTS_ENABLED
61
61
  ? "For company groups, request sharing near start or after a save; relay its exact question and set only after explicit Yes/No. Reuse its scope only in this conversation; each group needs a choice, silence means unset, and flagged memories stay private."
62
62
  : `Saves stay private. ${GROUP_SESSION_SHARING_DISABLED_NOTE}`,
63
- "EchoMem credential identity overrides profiles, hosts, git identity, and inference. Use get_group_context for workspace orientation and search_memories with scope=workspace for shared work.",
64
- "For memory-informed final answers, record exact used teammate/friend IDs with a unique receiptId, then end with an EchoMem sources: list using memory keys and canonical https://echoknows.com/memory/<memory-id> links.",
63
+ "EchoMem credentials determine identity. Use get_group_context for workspace context and search_memories scope=workspace for shared work.",
64
+ "When using teammate/friend memories, record their exact IDs with a unique receiptId. End memory-informed answers with EchoMem sources: using keys, returned title links and canonical web links.",
65
65
  "Group profiles, sharing, publication, sensitive flags, and deletion require explicit confirmation. Never store or log an echo_grp_ invite code.",
66
66
  ].filter(Boolean).join(" ");
67
67
  export function withMcpVersion(description) {
@@ -0,0 +1,49 @@
1
+ /** Keep one in-flight write per frozen source. Each MCP call returns before the
2
+ * host's 60-second timeout; polling consumes the same promise, not another POST. */
3
+ export class PendingSaves {
4
+ waitMs;
5
+ now;
6
+ entries = new Map();
7
+ constructor(waitMs = 45_000, now = Date.now) {
8
+ this.waitMs = waitMs;
9
+ this.now = now;
10
+ }
11
+ async run(key, scope, boundary, start, waitForCompletion = false) {
12
+ const now = this.now();
13
+ // Never evict a live operation: a slow provider/retry would otherwise let
14
+ // the next poll issue a second write for the identical frozen source.
15
+ for (const [id, entry] of this.entries)
16
+ if (entry.settledAt !== undefined && now - entry.settledAt > 10 * 60_000)
17
+ this.entries.delete(id);
18
+ let entry = this.entries.get(key);
19
+ if (!entry) {
20
+ if (this.entries.size >= 128)
21
+ throw new Error("SAVE_QUEUE_BUSY: too many unfinished saves; retry later.");
22
+ const created = { promise: Promise.resolve({ ok: true, value: undefined }), scope, boundary, delivered: false };
23
+ created.promise = Promise.resolve().then(start).then(value => ({ ok: true, value }), error => ({ ok: false, error }))
24
+ .then(result => { created.settledAt = this.now(); return result; });
25
+ entry = created;
26
+ this.entries.set(key, created);
27
+ }
28
+ let timer;
29
+ try {
30
+ const result = waitForCompletion ? await entry.promise : await Promise.race([entry.promise, new Promise(resolve => { timer = setTimeout(() => resolve(null), this.waitMs); })]);
31
+ if (result === null)
32
+ return { success: true, memoriesExtracted: 0, extractedMemories: [], pendingProcessing: true,
33
+ assistantMessageId: entry.boundary, groupSharingScopeId: entry.scope };
34
+ if (this.entries.get(key) === entry)
35
+ this.entries.delete(key);
36
+ if (!result.ok)
37
+ throw result.error;
38
+ if (entry.delivered && result.value && typeof result.value === "object" && "memoriesExtracted" in result.value) {
39
+ return { ...result.value, memoriesExtracted: 0, reused: true };
40
+ }
41
+ entry.delivered = true;
42
+ return result.value;
43
+ }
44
+ finally {
45
+ if (timer)
46
+ clearTimeout(timer);
47
+ }
48
+ }
49
+ }
@@ -0,0 +1,26 @@
1
+ import { mkdirSync, writeFileSync, renameSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ /** Opt-in private local diagnostics. Never serialize HTTP headers or credentials. */
5
+ export function startSaveLocalTrace(record) {
6
+ const directory = process.env.ECHOMEM_SAVE_TRACE_DIR;
7
+ if (!directory)
8
+ return () => { };
9
+ const id = randomUUID();
10
+ const started = Date.now();
11
+ const target = join(directory, `${started}-${id}.json`);
12
+ const snapshot = { ...record, id, timestamp: new Date(started).toISOString(), origin: "local_mcp", state: "IN_FLIGHT" };
13
+ const updateRecord = (update) => {
14
+ try {
15
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
16
+ Object.assign(snapshot, update);
17
+ writeFileSync(`${target}.tmp`, JSON.stringify(snapshot), { mode: 0o600 });
18
+ renameSync(`${target}.tmp`, target);
19
+ }
20
+ catch {
21
+ // Diagnostics must never change the outcome of a memory write.
22
+ }
23
+ };
24
+ updateRecord({});
25
+ return updateRecord;
26
+ }
@@ -0,0 +1,50 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { echoConfigDir } from "./keystore.js";
5
+ /** Notes of saves made from a call the host recorded as script source, one file per host
6
+ * session. The host's record names such a call without holding its note, and a saved note is
7
+ * part of the session's history from then on: every later reading must show it again, in the
8
+ * same place, or the next save finds a gap. Kept beside the receipts, readable by the user only. */
9
+ const directory = () => path.join(echoConfigDir(), "save-notes");
10
+ const file = (sessionId) => path.join(directory(), `${createHash("sha256").update(sessionId.toLowerCase()).digest("hex").slice(0, 32)}.json`);
11
+ export function readSaveNotes(sessionId) {
12
+ try {
13
+ const stored = JSON.parse(fs.readFileSync(file(sessionId), "utf8"));
14
+ if (!stored || typeof stored !== "object" || Array.isArray(stored))
15
+ return new Map();
16
+ return new Map(Object.entries(stored).filter((entry) => typeof entry[1] === "string"));
17
+ }
18
+ catch {
19
+ return new Map();
20
+ }
21
+ }
22
+ /** False when the note could not be kept: the save must then not be made from it. */
23
+ export function rememberSaveNote(sessionId, callId, note) {
24
+ const notes = readSaveNotes(sessionId);
25
+ if (notes.get(callId) === note)
26
+ return true;
27
+ // A call's note never changes once kept: a later reading must repeat what was saved.
28
+ if (notes.has(callId))
29
+ return false;
30
+ notes.set(callId, note);
31
+ let temporary;
32
+ try {
33
+ fs.mkdirSync(directory(), { recursive: true, mode: 0o700 });
34
+ temporary = path.join(directory(), `.${randomUUID()}.tmp`);
35
+ fs.writeFileSync(temporary, JSON.stringify(Object.fromEntries(notes)), { mode: 0o600 });
36
+ fs.renameSync(temporary, file(sessionId));
37
+ return true;
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ finally {
43
+ if (temporary) {
44
+ try {
45
+ fs.unlinkSync(temporary);
46
+ }
47
+ catch { /* renamed or unwritten */ }
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,58 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { echoConfigDir } from "./keystore.js";
5
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
6
+ const directory = (scope) => path.join(echoConfigDir(), "chat-save-receipts", digest(JSON.stringify(scope)));
7
+ /** Returns false on a disk failure so the caller can retain an in-memory fallback. */
8
+ export function enqueueSaveReceipt(scope, text) {
9
+ const dir = directory(scope);
10
+ let temporary;
11
+ try {
12
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
13
+ temporary = path.join(dir, `.${randomUUID()}.tmp`);
14
+ fs.writeFileSync(temporary, JSON.stringify({ v: 1, text }), { mode: 0o600 });
15
+ fs.renameSync(temporary, path.join(dir, `${digest(text)}.json`));
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ finally {
22
+ if (temporary) {
23
+ try {
24
+ fs.unlinkSync(temporary);
25
+ }
26
+ catch { /* renamed or unwritten */ }
27
+ }
28
+ }
29
+ }
30
+ /** Consume at tool delivery, not proof of rendering in the host's final message.
31
+ * Unlink is the claim: concurrent bridges cannot both deliver the same file.
32
+ * Merely reading notifications never submits another memory save. */
33
+ export function takeSaveReceipts(scope) {
34
+ const dir = directory(scope);
35
+ let names;
36
+ try {
37
+ names = fs.readdirSync(dir);
38
+ }
39
+ catch {
40
+ return [];
41
+ }
42
+ const receipts = [];
43
+ for (const name of names.sort()) {
44
+ if (!/^[a-f0-9]{64}\.json$/.test(name))
45
+ continue;
46
+ const file = path.join(dir, name);
47
+ try {
48
+ const entry = JSON.parse(fs.readFileSync(file, "utf8"));
49
+ if (!entry || typeof entry !== "object" || !("v" in entry) || entry.v !== 1 ||
50
+ !("text" in entry) || typeof entry.text !== "string")
51
+ continue;
52
+ fs.unlinkSync(file);
53
+ receipts.push(entry.text);
54
+ }
55
+ catch { /* unreadable or claimed by another bridge */ }
56
+ }
57
+ return receipts;
58
+ }
@@ -0,0 +1,42 @@
1
+ import { memoryMarkdownLink } from "./memory-links.js";
2
+ /** Only a completed backend result can become a saved receipt. No transcript or
3
+ * extraction details are needed in the chat notification. */
4
+ export function completedSaveReceipt(result, memoryUrl) {
5
+ if (!result || typeof result !== "object")
6
+ return null;
7
+ const row = result;
8
+ if (row.success !== true || row.pendingProcessing || row.savesAfterTurnEnds || row.deferredUntilCompletion)
9
+ return null;
10
+ const memories = Array.isArray(row.extractedMemories) ? row.extractedMemories : [];
11
+ const links = memories.flatMap((memory) => {
12
+ if (!memory || typeof memory !== "object")
13
+ return [];
14
+ const item = memory;
15
+ return typeof item.id === "string" && item.id
16
+ ? [memoryMarkdownLink(memoryUrl(item.id), typeof item.keys === "string" ? item.keys : "Saved memory", "")]
17
+ : [];
18
+ });
19
+ if (links.length)
20
+ return [
21
+ row.memoriesExtracted === 0
22
+ ? "The previous turn was already saved; no duplicate memory was created."
23
+ : "The previous turn's save finished.",
24
+ `EchoMem saved:\n${links.map(link => `- ${link}`).join("\n")}`,
25
+ "Show this compact receipt in your user-facing answer, identifying it as the previous completed turn. Do not call save_conversation to save it again.",
26
+ ].join("\n\n");
27
+ return "The previous turn was checked; no new memory was created. Tell the user briefly that the check completed without a new memory. Do not retry merely to create a memory.";
28
+ }
29
+ /** The receipt for the turn being saved, as the block the agent copies into its answer. A check
30
+ * that created nothing shows nothing. */
31
+ export function turnSaveResult(result, memoryUrl) {
32
+ const row = result && typeof result === "object" ? result : {};
33
+ const memories = row.success === true && !row.pendingProcessing && !row.savesAfterTurnEnds && !row.deferredUntilCompletion
34
+ && Array.isArray(row.extractedMemories) ? row.extractedMemories : [];
35
+ const links = memories.flatMap((memory) => {
36
+ const item = memory && typeof memory === "object" ? memory : {};
37
+ return typeof item.id === "string" && item.id
38
+ ? [memoryMarkdownLink(memoryUrl(item.id), typeof item.keys === "string" ? item.keys : "Saved memory", "")] : [];
39
+ });
40
+ return links.length ? { kind: "saved", text: `EchoMem saved:\n${links.map(link => `- ${link}`).join("\n")}` }
41
+ : { kind: "none", text: "" };
42
+ }
@@ -0,0 +1,43 @@
1
+ import axios from "axios";
2
+ /** Retry only transient transport failures or a backend's explicit retryable
3
+ * verdict. Quota, auth, invalid evidence, malformed receipts and an empty save never
4
+ * enter this path. The caller must keep the source/request identity unchanged. */
5
+ export function isTransientSaveError(error) {
6
+ if (!axios.isAxiosError(error))
7
+ return false;
8
+ if (!error.response)
9
+ return ["ECONNRESET", "EPIPE", "ETIMEDOUT", "ECONNABORTED", "ECONNREFUSED"].includes(error.code ?? "");
10
+ const data = error.response.data;
11
+ return [502, 503, 504].includes(error.response.status) && data?.retryable === true;
12
+ }
13
+ export async function withSaveRetry(attempt, pause = ms => new Promise(resolve => setTimeout(resolve, ms))) {
14
+ for (let index = 0;; index++) {
15
+ try {
16
+ return await attempt(index);
17
+ }
18
+ catch (error) {
19
+ if (index >= 2 || !isTransientSaveError(error))
20
+ throw error;
21
+ await pause(index === 0 ? 750 : 1_500);
22
+ }
23
+ }
24
+ }
25
+ /** Preserve diagnostic codes, never provider response text or credentials. */
26
+ export function saveFailureCode(error) {
27
+ const valid = (value) => typeof value === "string" && /^[A-Z][A-Z0-9_]{1,79}$/.test(value);
28
+ if (axios.isAxiosError(error)) {
29
+ const body = error.response?.data;
30
+ const code = typeof body === "object" && body !== null && "error" in body ? body.error : undefined;
31
+ if (valid(code))
32
+ return code;
33
+ if (error.response)
34
+ return `HTTP_${error.response.status}`;
35
+ if (valid(error.code))
36
+ return error.code;
37
+ }
38
+ const message = error instanceof Error ? error.message : "";
39
+ if (valid(message))
40
+ return message;
41
+ const prefix = /^([A-Z][A-Z0-9_]{1,79}):/.exec(message)?.[1];
42
+ return prefix ?? "SAVE_FAILED";
43
+ }
@@ -1,3 +1,4 @@
1
+ import { resolveBackendURL } from "../backend-policy.js";
1
2
  // Generated by splitting the previous inline setup page. Keep this source readable: it is emitted into one browser IIFE.
2
3
  export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dashboard (post-auth extraction) ---------- */
3
4
  function renderDiscoveryCheck(slow) {
@@ -1039,7 +1040,7 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1039
1040
  async function refreshPlanQuotaCatalog() {
1040
1041
  if (Date.now() - planQuotaCatalogLastFetchedAt < 60000) return;
1041
1042
  try {
1042
- var response = await fetch("https://echo-mem-chrome.vercel.app/api/public/plan-quotas", { cache: "no-store" });
1043
+ var response = await fetch(${JSON.stringify(resolveBackendURL() + "/api/public/plan-quotas")}, { cache: "no-store" });
1043
1044
  var payload = response.ok ? await response.json() : null;
1044
1045
  if (!payload || !payload.plans || typeof payload.plans !== "object") return;
1045
1046
  planQuotaCatalog = payload.plans;