@echomem/mcp 1.4.69 → 1.4.71

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.
package/README.md CHANGED
@@ -134,6 +134,13 @@ Both hook entries are merged idempotently into `~/.codex/hooks.json` and
134
134
  `~/.claude/settings.json`; unrelated user hooks and settings are preserved. Hooks fail open when
135
135
  their local input is missing so they cannot prevent a conversation from starting or finishing.
136
136
 
137
+ When setup runs from Echo Desktop or the standalone runtime, hook commands point at a path that
138
+ follows runtime updates: Desktop's `current` folder, or `~/.echomem/mcp-runtime/hud-launcher.mjs`,
139
+ which runs whichever standalone version is active. Each MCP server those runtimes start also
140
+ repoints EchoMem hooks that older installers pinned to a version folder or the npx cache, and any
141
+ that name a missing file. A working Codex hook is left for the next setup run, since Codex asks
142
+ users to re-trust changed hooks. A checkout, global install, or npx copy never repoints hooks.
143
+
137
144
  ### Cloud Cowork through `remote-devices`
138
145
 
139
146
  Cloud Cowork inference cannot use the local hook or transcript-verification path. The shared local
@@ -2,7 +2,7 @@ import { spawnSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { installHeadlessRuntimeSync, readHeadlessRuntimeInstallation } from "./headless-runtime.js";
5
+ import { ensureHudLauncher, installHeadlessRuntimeSync, readHeadlessRuntimeInstallation } from "./headless-runtime.js";
6
6
  import { MCP_PACKAGE_NAME, MCP_PACKAGE_VERSION } from "./package-metadata.js";
7
7
  /**
8
8
  * Resolving a DURABLE path to this package's own files.
@@ -70,6 +70,60 @@ export function resolveDurableDistPath(relative) {
70
70
  }
71
71
  return { path: local, ephemeral: localIsEphemeral };
72
72
  }
73
+ /**
74
+ * Echo Desktop runs this package from `<root>/versions/<v>/dist` and moves the `<root>/current` link
75
+ * to each new version. When `current` points at this copy, return the running node and dist
76
+ * directory as seen through that link, so a persisted path follows Desktop updates. Node resolves
77
+ * links when it loads a module, so the running paths alone always name the version folder. Null for
78
+ * any other layout, and for a superseded copy that `current` no longer points at.
79
+ */
80
+ export function desktopCurrentPaths(distDir = runningDistDir(), execPath = process.execPath) {
81
+ try {
82
+ const dist = fs.realpathSync(distDir);
83
+ const versionDir = path.dirname(dist);
84
+ if (path.basename(path.dirname(versionDir)) !== "versions")
85
+ return null;
86
+ const current = path.join(path.dirname(path.dirname(versionDir)), "current");
87
+ if (fs.realpathSync(current) !== versionDir)
88
+ return null;
89
+ const bundledNode = path.relative(versionDir, fs.realpathSync(execPath));
90
+ const node = bundledNode && !bundledNode.startsWith("..") && !path.isAbsolute(bundledNode)
91
+ ? path.join(current, bundledNode)
92
+ : execPath;
93
+ return { node, dist: path.join(current, path.basename(dist)) };
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ /**
100
+ * Where a lifecycle hook should point so it keeps following runtime updates: Echo Desktop's
101
+ * `current` link, else the standalone runtime's hud launcher. Only the copy a runtime currently runs
102
+ * gets one. A checkout, global install, npx copy, or superseded version gets null, so it never
103
+ * points hooks at a runtime other than itself.
104
+ */
105
+ export function stableHudCommandTarget() {
106
+ const desktop = desktopCurrentPaths();
107
+ if (desktop)
108
+ return { node: desktop.node, cli: path.join(desktop.dist, "hud", "cli.js") };
109
+ const standalone = readHeadlessRuntimeInstallation();
110
+ if (!standalone || !isSamePath(runningDistDir(), path.dirname(standalone.entry)))
111
+ return null;
112
+ try {
113
+ return { node: process.execPath, cli: ensureHudLauncher() };
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ }
119
+ function isSamePath(a, b) {
120
+ try {
121
+ return fs.realpathSync(a) === fs.realpathSync(b);
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ }
73
127
  /** Set on the child so a re-exec can never recurse. */
74
128
  const REEXEC_GUARD = "ECHO_DURABLE_REEXEC";
75
129
  /**
@@ -19,6 +19,9 @@ function activeRuntimePath() {
19
19
  export function headlessLauncherPath() {
20
20
  return path.join(headlessRuntimeRoot(), "launcher.mjs");
21
21
  }
22
+ export function headlessHudLauncherPath() {
23
+ return path.join(headlessRuntimeRoot(), "hud-launcher.mjs");
24
+ }
22
25
  function packageEntryForPrefix(prefix) {
23
26
  return path.join(prefix, "node_modules", ...MCP_PACKAGE_NAME.split("/"), "dist", "index.js");
24
27
  }
@@ -48,8 +51,14 @@ function atomicWriteJson(file, value) {
48
51
  }
49
52
  }
50
53
  function ensureLauncher() {
54
+ return ensureLauncherFile(headlessLauncherPath(), "path.resolve(root, active.entry)");
55
+ }
56
+ /** Like launcher.mjs, but runs the active runtime's hud CLI, so lifecycle hooks follow updates too. */
57
+ export function ensureHudLauncher() {
58
+ return ensureLauncherFile(headlessHudLauncherPath(), 'path.join(path.dirname(path.resolve(root, active.entry)), "hud", "cli.js")');
59
+ }
60
+ function ensureLauncherFile(launcher, entryExpression) {
51
61
  const root = headlessRuntimeRoot();
52
- const launcher = headlessLauncherPath();
53
62
  fs.mkdirSync(root, { recursive: true, mode: 0o700 });
54
63
  const source = [
55
64
  "#!/usr/bin/env node",
@@ -61,7 +70,7 @@ function ensureLauncher() {
61
70
  'if (active.layout !== 1 || typeof active.entry !== "string" || path.isAbsolute(active.entry) || active.entry.split(/[\\\\/]/).includes("..")) {',
62
71
  ' throw new Error("EchoMem MCP runtime pointer is invalid; run `npx -y @echomem/mcp@latest update --all`.");',
63
72
  "}",
64
- "const entry = path.resolve(root, active.entry);",
73
+ `const entry = ${entryExpression};`,
65
74
  'if (!fs.existsSync(entry)) throw new Error("EchoMem MCP runtime is missing; run `npx -y @echomem/mcp@latest update --all`.");',
66
75
  "await import(pathToFileURL(entry).href);",
67
76
  "",
package/dist/hud/hooks.js CHANGED
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { atomicWriteJsonObject, readJsonObjectFile } from "../config-files.js";
5
- import { resolveDurableDistPath } from "../durable-entry.js";
5
+ import { isEphemeralNpxPath, resolveDurableDistPath, stableHudCommandTarget } from "../durable-entry.js";
6
6
  /**
7
7
  * Hook commands are persisted into another program's settings and must keep working long after this
8
8
  * process exits. Resolving them from `import.meta.url` pins them to whatever copy happens to be
@@ -88,6 +88,86 @@ export function removeLifecycleHooks(mode) {
88
88
  }
89
89
  return { files, removedGroups };
90
90
  }
91
+ const LIFECYCLE_COMMAND = /^"((?:[^"\\]|\\.)*)" "((?:[^"\\]|\\.)*)" (save-checkpoint|bind-source-session)$/;
92
+ /**
93
+ * Repoint installed EchoMem lifecycle hooks that are pinned to a runtime version folder or the npx
94
+ * cache, or that name a file that no longer exists. Runtime updates never rerun setup, so such a
95
+ * hook keeps running whichever version wrote it. Only the copy Echo Desktop or the standalone
96
+ * runtime currently runs does this; see stableHudCommandTarget. Only EchoMem's own commands change
97
+ * and no hook is ever added. Working Codex hooks are kept, because Codex makes the user re-trust
98
+ * every changed hook. Returns the files written; any failure leaves that file untouched.
99
+ */
100
+ export function refreshInstalledLifecycleHooks() {
101
+ const target = stableHudCommandTarget();
102
+ if (!target)
103
+ return [];
104
+ const files = [];
105
+ for (const [envKey, fallbackName, fileName, repairPinned] of [
106
+ ["CLAUDE_CONFIG_DIR", ".claude", "settings.json", true],
107
+ ["CODEX_HOME", ".codex", "hooks.json", false],
108
+ ]) {
109
+ try {
110
+ const file = path.join(profileDirectory(envKey, fallbackName), fileName);
111
+ if (fs.lstatSync(file).isSymbolicLink())
112
+ continue;
113
+ const content = readHooksFile(file);
114
+ if (!refreshLifecycleCommands(content.hooks, target, repairPinned))
115
+ continue;
116
+ atomicWriteJsonObject(file, content);
117
+ files.push(file);
118
+ }
119
+ catch {
120
+ /* Missing, unreadable, or invalid settings stay exactly as they are. */
121
+ }
122
+ }
123
+ return files;
124
+ }
125
+ function refreshLifecycleCommands(hooks, target, repairPinned) {
126
+ if (!hooks || typeof hooks !== "object" || Array.isArray(hooks))
127
+ return false;
128
+ let changed = false;
129
+ for (const groups of Object.values(hooks)) {
130
+ if (!Array.isArray(groups))
131
+ continue;
132
+ for (const group of groups.filter(isEchoLifecycleGroup)) {
133
+ const entries = group.hooks;
134
+ if (!Array.isArray(entries))
135
+ continue;
136
+ for (const entry of entries) {
137
+ if (typeof entry !== "object" || entry === null)
138
+ continue;
139
+ const hook = entry;
140
+ // Codex runs commandWindows on Windows, and the two can drift apart, so judge each on its own.
141
+ for (const field of ["command", "commandWindows"]) {
142
+ const replacement = refreshedLifecycleCommand(hook[field], target, repairPinned);
143
+ if (!replacement)
144
+ continue;
145
+ hook[field] = replacement;
146
+ changed = true;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ return changed;
152
+ }
153
+ function refreshedLifecycleCommand(command, target, repairPinned) {
154
+ const match = typeof command === "string" ? LIFECYCLE_COMMAND.exec(command) : null;
155
+ if (!match)
156
+ return null;
157
+ const replacement = `${JSON.stringify(target.node)} ${JSON.stringify(target.cli)} ${match[3]}`;
158
+ if (replacement === command)
159
+ return null;
160
+ const [node, script] = [match[1], match[2]].map((quoted) => JSON.parse(`"${quoted}"`));
161
+ if (!fs.existsSync(node) || !fs.existsSync(script))
162
+ return replacement;
163
+ return repairPinned && isPinnedRuntimePath(script) ? replacement : null;
164
+ }
165
+ /** Inside a `versions/<semver>` folder or the npx cache: correct only until the next update. */
166
+ function isPinnedRuntimePath(file) {
167
+ const parts = file.split(/[\\/]/);
168
+ return isEphemeralNpxPath(file)
169
+ || parts.some((part, index) => part === "versions" && /^\d+\.\d+\.\d+/.test(parts[index + 1] ?? ""));
170
+ }
91
171
  function installCodexHooks() {
92
172
  const dir = profileDirectory("CODEX_HOME", ".codex");
93
173
  const file = path.join(dir, "hooks.json");
@@ -102,10 +182,17 @@ function installCodexHooks() {
102
182
  return file;
103
183
  }
104
184
  function saveCheckpointCommand() {
105
- return hookCommandFor(path.join("hud", "cli.js"), "save-checkpoint");
185
+ return lifecycleHookCommand("save-checkpoint");
106
186
  }
107
187
  function sourceSessionCommand() {
108
- return hookCommandFor(path.join("hud", "cli.js"), "bind-source-session");
188
+ return lifecycleHookCommand("bind-source-session");
189
+ }
190
+ /** Prefer a target that follows runtime updates: a hook pinned to one version keeps running it. */
191
+ function lifecycleHookCommand(subcommand) {
192
+ const target = stableHudCommandTarget();
193
+ if (!target)
194
+ return hookCommandFor(path.join("hud", "cli.js"), subcommand);
195
+ return `${JSON.stringify(target.node)} ${JSON.stringify(target.cli)} ${subcommand}`;
109
196
  }
110
197
  function installCodexSourceSessionHook() {
111
198
  const dir = profileDirectory("CODEX_HOME", ".codex");
package/dist/index.js CHANGED
@@ -7,11 +7,13 @@ import { ZodError } from "zod";
7
7
  import { acknowledgeWorkspaceTicketReviewSchema, applyWorkspaceTicketActionSchema, bindSourceSessionSchema, canonicalToolNames, completeGroupPublicationSchema, createGroupInviteSchema, createGroupSchema, deleteMemorySchema, flagPublicationAttentionSchema, findWorkspaceTicketCandidatesSchema, getGroupSessionSharingSchema, getByContextSchema, groupContextSchema, joinGroupSchema, keywordsSchema, listFriendsSchema, listToolSpecs, linkWorkspaceTicketSessionSchema, othersSchema, publishBatchToGroupSchema, publishToGroupSchema, prepareGroupPublicationSchema, publicMemorySchema, recordMemoryCitationsSchema, recordWorkspaceTicketProposalSchema, requestGroupSessionSharingSchema, reviewWorkspaceTicketSessionSchema, resolveCanonicalToolName, saveConversationSchema, searchMemoriesSchema, searchUsersSchema, sendFriendRequestSchema, timeRangeSchema, updateGroupProfileSchema, setGroupSessionSharingSchema, } from "./v1-contract.js";
8
8
  import { KeyStore } from "./keystore.js";
9
9
  import { EventLogger, hashText } from "./events.js";
10
+ import { requestFailureDetails } from "./request-failure.js";
10
11
  import { contextHealthMarkdown, recomposeCapsuleMarkdown } from "./hud/api.js";
12
+ import { refreshInstalledLifecycleHooks } from "./hud/hooks.js";
11
13
  import { createHash, randomUUID } from "node:crypto";
12
14
  import { AsyncLocalStorage } from "node:async_hooks";
13
15
  import { fetchEncryptionConfig, decryptMemoryFields, verifyKeyB64, } from "./encryption.js";
14
- import { refreshInstalledMemoryGuidance, runCli } from "./setup.js";
16
+ import { refreshInstalledCodexSkills, refreshInstalledMemoryGuidance, runCli } from "./setup.js";
15
17
  import { MCP_PACKAGE_VERSION, MCP_SERVER_INSTRUCTIONS, MEMORY_CITATION_INSTRUCTION, SAVED_MEMORY_RECEIPT_INSTRUCTION, GROUP_SESSION_SHARING_DISABLED_NOTE, GROUP_SESSION_SHARING_PROMPTS_ENABLED, } from "./package-metadata.js";
16
18
  import { clearBillingAlert, writeBillingAlert } from "./billing-alert.js";
17
19
  import { checkLatestUpdateStatus, formatUpdateNotice, formatUpdateStatusText, startBackgroundUpdateCheck, } from "./update-check.js";
@@ -22,6 +24,12 @@ const ECHO_API_BASE_URL = process.env.ECHO_API_BASE_URL || "https://echo-mem-chr
22
24
  const ECHO_PRICING_URL = process.env.ECHO_PRICING_URL || "https://echoknows.com/dashboard/account";
23
25
  const ECHO_MEMORY_WEB_URL = (process.env.ECHO_MEMORY_WEB_URL || "https://echoknows.com/memory").replace(/\/$/, "");
24
26
  const DESKTOP_MANAGED = process.env.ECHO_DESKTOP_MANAGED === "1";
27
+ // No Echo API route may run past Vercel's 300s function limit, so a request
28
+ // still unanswered after this is a dead connection (sleep, network change).
29
+ // Without a limit, such a request waited until the OS gave up (~30 minutes).
30
+ const API_REQUEST_TIMEOUT_MS = 310_000;
31
+ // The routine ticket-fit review is a single database read (p95 under 2s).
32
+ const TICKET_REVIEW_TIMEOUT_MS = 30_000;
25
33
  const CONNECT_DEVICE_INSTRUCTION = DESKTOP_MANAGED
26
34
  ? "Open Echo Desktop, sign in, and choose Connect MCP, then retry this action."
27
35
  : "Run `echomem-mcp login` in a terminal to reconnect this device, then retry this action.";
@@ -153,21 +161,24 @@ function formatUpgradeRequiredResult(error) {
153
161
  const data = error.response?.data;
154
162
  if (!isRecord(data))
155
163
  return null;
164
+ const code = readString(data, "error") ?? readString(data, "code");
165
+ const normalizedCode = String(code || "").toUpperCase();
166
+ // Billing answers are a 402 *_REQUIRES_PLAN or a *_QUOTA_EXCEEDED code. Any
167
+ // other 403 (session not owned, no workspace access) and the per-minute
168
+ // rate limit are ordinary errors and must not ask the user to upgrade.
169
+ const quotaExceeded = normalizedCode.includes("QUOTA");
170
+ const planRequired = status === 402 || normalizedCode.includes("REQUIRES_PLAN");
171
+ if (!quotaExceeded && !planRequired)
172
+ return null;
156
173
  const upgradeUrl = readString(data, "upgradeUrl")
157
174
  ?? readString(data, "pricingUrl")
158
175
  ?? readString(data, "url")
159
176
  ?? ECHO_PRICING_URL;
160
177
  const message = readString(data, "message")
161
178
  ?? "Memory search and recall require an Echo Pro or Power plan.";
162
- const code = readString(data, "error") ?? readString(data, "code");
163
179
  const plan = readString(data, "plan");
164
180
  const pricingUrl = appendDesktopClientHint(appendPricingSource(upgradeUrl, "mcp_search"));
165
- const normalizedCode = String(code || "").toUpperCase();
166
- const kind = status === 429 || normalizedCode.includes("QUOTA") || normalizedCode.includes("LIMIT")
167
- ? "quota_exceeded"
168
- : status === 402 || normalizedCode.includes("REQUIRES_PLAN")
169
- ? "plan_required"
170
- : "billing_attention";
181
+ const kind = quotaExceeded ? "quota_exceeded" : "plan_required";
171
182
  writeBillingAlert({
172
183
  kind,
173
184
  code,
@@ -176,7 +187,7 @@ function formatUpgradeRequiredResult(error) {
176
187
  pricingUrl,
177
188
  });
178
189
  return [
179
- "ACTION REQUIRED: tell the user to start a 14-day Pro trial or choose a subscription at this exact URL:",
190
+ "ACTION REQUIRED: tell the user to choose a subscription at this exact URL:",
180
191
  pricingUrl,
181
192
  "When replying, include the exact URL above. Do not reply only with \"connect\" or \"upgrade\".",
182
193
  "",
@@ -743,6 +754,7 @@ class EchoMemApiClient {
743
754
  this.activeToken = store.getToken();
744
755
  this.axios = axios.create({
745
756
  baseURL: ECHO_API_BASE_URL.replace(/\/$/, ""),
757
+ timeout: API_REQUEST_TIMEOUT_MS,
746
758
  headers: {
747
759
  "Content-Type": "application/json",
748
760
  "X-Echo-Client": "mcp",
@@ -825,6 +837,7 @@ class EchoMemApiClient {
825
837
  providerSessionId: identity.providerSessionId,
826
838
  providerSessionAliases: identity.providerSessionAliases,
827
839
  evidence: identity.evidence,
840
+ runtime_version: MCP_PACKAGE_VERSION,
828
841
  }, { headers: { "X-EchoMem-Origin-Channel": "local_mcp" } });
829
842
  const contextId = readString(response.data, "contextId");
830
843
  const canonicalKey = readString(response.data, "canonicalKey");
@@ -931,6 +944,7 @@ class EchoMemApiClient {
931
944
  groupId: parsed.groupId,
932
945
  memoryThreshold: parsed.memoryThreshold,
933
946
  },
947
+ timeout: TICKET_REVIEW_TIMEOUT_MS,
934
948
  });
935
949
  return response.data;
936
950
  }
@@ -1002,7 +1016,13 @@ class EchoMemApiClient {
1002
1016
  if (!this.hasToken())
1003
1017
  return;
1004
1018
  try {
1005
- await this.axios.post("/api/extension/mcp/events", { eventType, eventProperties, insertId }, { timeout: 1500 });
1019
+ await this.axios.post("/api/extension/mcp/events", {
1020
+ eventType,
1021
+ // Stamp at the transport boundary so every emitted lifecycle event
1022
+ // uses this installed package, never caller-supplied metadata.
1023
+ eventProperties: { ...eventProperties, runtime_version: MCP_PACKAGE_VERSION },
1024
+ insertId,
1025
+ }, { timeout: 1500 });
1006
1026
  }
1007
1027
  catch {
1008
1028
  // Remote analytics is best-effort and must never change MCP behavior.
@@ -1419,6 +1439,7 @@ class EchoMemApiClient {
1419
1439
  endDate: parsed.endDate,
1420
1440
  limit: parsed.limit,
1421
1441
  requestId: randomUUID(),
1442
+ sessionId: this.sessionId,
1422
1443
  });
1423
1444
  return enc.enabled ? await this.decryptResult(response.data, enc.key) : response.data;
1424
1445
  }
@@ -2043,6 +2064,13 @@ class EchoMemMCPServer {
2043
2064
  }
2044
2065
  catch (error) {
2045
2066
  rec.error_kind = classifyError(error);
2067
+ // Memory search reports its own request trace; every other tool gets
2068
+ // its failure detail (HTTP status, upstream code, timeout or network) here.
2069
+ if (rec.http_status === undefined && rec.error_code === undefined) {
2070
+ const failure = requestFailureDetails(error);
2071
+ rec.http_status = failure.httpStatus;
2072
+ rec.error_code = failure.errorCode;
2073
+ }
2046
2074
  if (error instanceof NoTokenError) {
2047
2075
  // Not isError: a normal "not connected yet" state. Once `login` runs, the next call works.
2048
2076
  return {
@@ -3792,6 +3820,11 @@ async function main() {
3792
3820
  // Existing standalone users may receive a new runtime without re-running setup. Refresh only
3793
3821
  // EchoMem's marker-owned block so stale Desktop-era instructions disappear automatically.
3794
3822
  refreshInstalledMemoryGuidance();
3823
+ // Codex skills carry the same instructions, so refresh the ones setup already installed.
3824
+ refreshInstalledCodexSkills();
3825
+ // Lifecycle hooks go stale the same way, Desktop installs included: each keeps running the
3826
+ // runtime version that wrote it until something repoints it.
3827
+ refreshInstalledLifecycleHooks();
3795
3828
  const store = new KeyStore();
3796
3829
  // Serve mode is meant to be SPAWNED by the MCP client (editor), which drives us over a piped stdin.
3797
3830
  // A human who runs the bare server in a terminal instead gets a process that blocks forever on stdio
@@ -37,7 +37,7 @@ 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
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, make the save visible in the final user-facing answer with a compact "EchoMem saved:" list containing every memory created by that call. 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.';
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.';
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
@@ -55,7 +55,7 @@ export const MCP_SERVER_INSTRUCTIONS = [
55
55
  "SessionStart binds conversations to provider sessions; use bind_source_session only as fallback.",
56
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.",
57
57
  "Before re-deriving prior decisions or preferences, use search_memories.",
58
- `Before a final response for a durable decision, implementation, fix, commit, passing verification, release, or milestone, call save_conversation; skip secrets and trivial work. If locked, tell the user to ${MCP_VAULT_UNLOCK_INSTRUCTION}.`,
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
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:\".",
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."
@@ -0,0 +1,32 @@
1
+ import axios from "axios";
2
+ import { analyticsErrorCode } from "./product-analytics.js";
3
+ // Upstream routes report failures as SCREAMING_SNAKE codes (for example
4
+ // WORKSPACE_TICKET_NOT_FOUND). Any other `error` value may be free text from a
5
+ // response body, which must never leave the bridge.
6
+ const UPSTREAM_ERROR_CODE = /^[A-Z][A-Z0-9_]{1,79}$/;
7
+ function upstreamErrorCode(data) {
8
+ if (typeof data !== "object" || data === null || Array.isArray(data))
9
+ return undefined;
10
+ const record = data;
11
+ for (const key of ["error", "code", "errorCode"]) {
12
+ const value = record[key];
13
+ if (typeof value === "string" && UPSTREAM_ERROR_CODE.test(value))
14
+ return value;
15
+ }
16
+ return undefined;
17
+ }
18
+ /**
19
+ * Telemetry-safe description of a failed backend request: the HTTP status and
20
+ * a token-like code. The code is the upstream error code when the response
21
+ * carries one, `http_<status>` otherwise, and `timeout` or `network` when no
22
+ * response arrived. Errors that are not HTTP requests yield nothing.
23
+ */
24
+ export function requestFailureDetails(error) {
25
+ if (!axios.isAxiosError(error))
26
+ return {};
27
+ const status = error.response?.status;
28
+ if (typeof status === "number") {
29
+ return { httpStatus: status, errorCode: upstreamErrorCode(error.response?.data) ?? `http_${status}` };
30
+ }
31
+ return { errorCode: analyticsErrorCode(error) === "timeout" ? "timeout" : "network" };
32
+ }
@@ -658,13 +658,11 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
658
658
  function historicalSelectionLimit() {
659
659
  if (!setupPlanConfirmed()) return 0;
660
660
  var quota = billingStatus && billingStatus.historicalConversationQuota;
661
+ if (quota && (quota.limit === -1 || quota.remaining === -1)) return candidateSessions().length;
661
662
  if (quota && typeof quota.remaining === "number" && isFinite(quota.remaining)) {
662
663
  return Math.max(0, Math.floor(quota.remaining));
663
664
  }
664
- var plan = String(billingStatus && billingStatus.plan || "").toLowerCase();
665
- if (plan === "power" || plan === "enterprise") return 2000;
666
- if (paidRecallPlan(plan)) return 500;
667
- return 100;
665
+ return candidateSessions().length;
668
666
  }
669
667
  function selectedSessionKeyList() {
670
668
  var valid = Object.create(null);
@@ -785,7 +783,7 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
785
783
  setSessionPickerStatus("Opening secure Stripe checkout…");
786
784
  var checkout = await openHostedBilling(
787
785
  "/billing-checkout",
788
- { plan: targetPlan, trial: !billingStatus || billingStatus.trialAvailable !== false },
786
+ { plan: targetPlan, trial: false },
789
787
  "Creating your secure checkout…",
790
788
  "Checkout opened in Stripe. Keep this local page open; Echo will confirm here automatically."
791
789
  );
@@ -1067,18 +1065,6 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1067
1065
  return parsed.toISOString().slice(0, 10);
1068
1066
  }
1069
1067
  }
1070
- function trialChargeDateText() {
1071
- var chargeAt = new Date(Date.now() + 14 * 24 * 60 * 60 * 1000);
1072
- try {
1073
- return new Intl.DateTimeFormat(undefined, {
1074
- year: "numeric",
1075
- month: "long",
1076
- day: "numeric"
1077
- }).format(chargeAt);
1078
- } catch (_) {
1079
- return chargeAt.toISOString().slice(0, 10);
1080
- }
1081
- }
1082
1068
  function paidPlanLifecycleText(plan) {
1083
1069
  var state = String(billingStatus && billingStatus.subscriptionStatus || "").toLowerCase();
1084
1070
  var trialEnd = formatBillingDate(billingStatus && billingStatus.trialEndedAt);
@@ -1114,13 +1100,13 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1114
1100
  var limit = quota && typeof quota.limit === "number" ? quota.limit : null;
1115
1101
  var moneyFact = canceled
1116
1102
  ? "No future charge"
1117
- : (state === "trialing" ? setupPlanPrice(plan) + "/month after trial" : setupPlanPrice(plan) + "/month");
1103
+ : (state === "trialing" ? setupPlanPrice(plan) + "/month after trial" : "Billed monthly");
1118
1104
  slot.classList.add("is-visible");
1119
1105
  slot.innerHTML =
1120
1106
  '<section class="billingCommitment' + (canceled ? ' is-canceled' : '') + '" aria-label="Current plan commitment">' +
1121
1107
  '<div class="billingCommitmentIdentity"><span>' + esc(statusLabel) + '</span><strong>' + esc(planLabel) + '</strong></div>' +
1122
1108
  '<div class="billingCommitmentFacts">' +
1123
- '<span><b>' + esc(limit === null ? "Plan import allowance" : quotaNumber(limit)) + '</b>' + (limit === null ? "" : " coding-session imports") + '</span>' +
1109
+ '<span><b>' + esc(limit === -1 ? "Unlimited" : limit === null ? "Plan import allowance" : quotaNumber(limit)) + '</b>' + (limit === null ? "" : " coding-session imports") + '</span>' +
1124
1110
  '<span><b>' + esc(moneyFact) + '</b></span>' +
1125
1111
  '</div>' +
1126
1112
  '<p>' + esc(lifecycle || "Your paid plan is active.") + '</p>' +
@@ -1140,16 +1126,15 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1140
1126
  return true;
1141
1127
  }
1142
1128
  function setupPlanDefinition(plan) {
1143
- var trialAvailable = !billingStatus || billingStatus.trialAvailable !== false;
1144
1129
  var limits = quotaLimitsForPlan(plan);
1145
1130
  var fallbackFeatures = plan === "power"
1146
- ? ["2,000 past chats", "agent-heavy memory", "2,000 memory recalls / week"]
1131
+ ? ["Unlimited past chats", "agent-heavy memory", "2,000 memory recalls / week"]
1147
1132
  : plan === "pro"
1148
- ? ["500 past chats", "daily memory updates", "500 memory recalls / week"]
1149
- : ["100 coding sessions", "a few new sessions / week", "100 memory recalls / week"];
1133
+ ? ["Unlimited past chats", "daily memory updates", "500 memory recalls / week"]
1134
+ : ["Unlimited past chats", "a few new sessions / week", "100 memory recalls / week"];
1150
1135
  var features = limits
1151
1136
  ? [
1152
- quotaNumber(limits.historicalConversationLimit) + " past chats",
1137
+ "Unlimited past chats",
1153
1138
  quotaTokens(limits.memoryProcessingInputTokensWeeklyLimit) + " new-chat tokens / week",
1154
1139
  quotaNumber(limits.memorySearchWeeklyLimit) + " memory recalls / week"
1155
1140
  ]
@@ -1158,16 +1143,16 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1158
1143
  id: "power",
1159
1144
  name: "Power",
1160
1145
  homeName: "Power",
1161
- price: "$100",
1162
- cadence: trialAvailable ? "per month · 14-day trial" : "per month · billed immediately",
1146
+ price: "$20",
1147
+ cadence: "per month for 12 months, then $100",
1163
1148
  features: features
1164
1149
  };
1165
1150
  if (plan === "pro") return {
1166
1151
  id: "pro",
1167
1152
  name: "Pro",
1168
1153
  homeName: "Pro",
1169
- price: "$20",
1170
- cadence: trialAvailable ? "per month · 14-day trial" : "per month · billed immediately",
1154
+ price: "$4",
1155
+ cadence: "per month for 12 months, then $20",
1171
1156
  features: features
1172
1157
  };
1173
1158
  return {
@@ -1182,12 +1167,11 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1182
1167
  function renderPlanHabitat() {
1183
1168
  setupPlanPreview = setupPlanPreview === "pro" || setupPlanPreview === "power" ? setupPlanPreview : "free";
1184
1169
  var plan = setupPlanDefinition(setupPlanPreview);
1185
- var trialOn = !billingStatus || billingStatus.trialAvailable !== false;
1186
1170
  // The desktop app's plan grid: three ruled columns, the chosen one inverted, one action below.
1187
1171
  var columns = ["free", "pro", "power"].map(function (id) {
1188
1172
  var column = setupPlanDefinition(id);
1189
1173
  var selected = id === plan.id;
1190
- var billingNote = id === "free" ? "" : (trialOn ? "14 days free" : "Billed immediately");
1174
+ var billingNote = id === "free" ? "" : "80% off for 12 months";
1191
1175
  var accessibleName = column.homeName + " " + column.price + " " + (id === "free" ? "forever" : "/ month") + (billingNote ? " · " + billingNote : "");
1192
1176
  var facts = column.features.map(function (feature) {
1193
1177
  return '<li>' + setupIcon("check") + '<span>' + esc(feature) + '</span></li>';
@@ -1196,18 +1180,16 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1196
1180
  '<span class="planColumnHead"><span class="planColumnState">' + (selected ? "Selected" : "") + '</span><span class="planColumnMark" aria-hidden="true">' + (selected ? setupIcon("check") : "") + '</span></span>' +
1197
1181
  '<span class="planColumnName">' + esc(column.homeName) + '</span>' +
1198
1182
  '<span class="planColumnPrice"><strong>' + esc(column.price) + '</strong><span>' + (id === "free" ? "forever" : "/ month") + '</span></span>' +
1199
- '<span class="planColumnTrial' + (billingNote ? "" : " is-hidden") + '"' + (billingNote ? "" : ' aria-hidden="true"') + '>' + (billingNote || "14 days free") + '</span>' +
1183
+ '<span class="planColumnTrial' + (billingNote ? "" : " is-hidden") + '"' + (billingNote ? "" : ' aria-hidden="true"') + '>' + (billingNote || " ") + '</span>' +
1200
1184
  '<ul class="planColumnFacts">' + facts + '</ul>' +
1201
1185
  '</div>';
1202
1186
  }).join("");
1203
1187
  var chooseId = plan.id === "free" ? "chooseFreePlan" : (plan.id === "power" ? "choosePowerPlan" : "chooseProPlan");
1204
1188
  var chooseLabel = plan.id === "free"
1205
1189
  ? "Continue with " + plan.homeName
1206
- : (trialOn
1207
- ? "Start " + plan.homeName + " trial — $0 today"
1208
- : "Subscribe to " + plan.homeName);
1190
+ : "Subscribe to " + plan.homeName;
1209
1191
  return '<section class="mvpPricing" aria-labelledby="setupPlanHeading">' +
1210
- '<header class="mvpPricingIntro"><h2 id="setupPlanHeading">Choose your <strong>Echo.</strong></h2><p>Choose how much past work Echo can bring with you.</p></header>' +
1192
+ '<header class="mvpPricingIntro"><h2 id="setupPlanHeading">Choose your <strong>Echo.</strong></h2><p>Past-chat imports are unlimited on every plan. Choose your weekly recall capacity.</p></header>' +
1211
1193
  '<div class="planGrid" role="radiogroup" aria-label="Choose an Echo plan">' + columns + '</div>' +
1212
1194
  '<div class="planGridAction"><button type="button" class="primary mvpPlanCta" id="' + chooseId + '">' + esc(chooseLabel) + ' <span aria-hidden="true">→</span></button></div>' +
1213
1195
  '<p class="mvpPlanStatus" id="setupPlanStatus" role="status"></p>' +
@@ -1288,8 +1270,8 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1288
1270
  rememberCheckoutSessionId("");
1289
1271
  billingSyncAttempts = 0;
1290
1272
  var paidHistory = billingStatus && billingStatus.historicalConversationQuota;
1291
- var paidUsage = paidHistory && typeof paidHistory.used === "number" && typeof paidHistory.limit === "number"
1292
- ? paidHistory.used + " / " + paidHistory.limit + " coding sessions imported."
1273
+ var paidUsage = paidHistory && typeof paidHistory.used === "number"
1274
+ ? paidHistory.used + " coding sessions imported, with no limit."
1293
1275
  : "Your coding-session import and weekly memory allowance are ready.";
1294
1276
  var lifecycleText = paidPlanLifecycleText(plan);
1295
1277
  var paidDetail = lifecycleText
@@ -1309,7 +1291,7 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1309
1291
  if (planGateDecision) planGateDecision.classList.remove("is-checkout-pending");
1310
1292
  var freeLimits = quotaLimitsForPlan("free");
1311
1293
  var freePlanCopy = freeLimits
1312
- ? quotaNumber(freeLimits.historicalConversationLimit) + " coding sessions and " + quotaNumber(freeLimits.memorySearchWeeklyLimit) + " memory recalls each week."
1294
+ ? "Unlimited coding sessions and " + quotaNumber(freeLimits.memorySearchWeeklyLimit) + " memory recalls each week."
1313
1295
  : "Your managed import and weekly memory allowances are ready.";
1314
1296
  slot.innerHTML = '<div class="setupPlanConfirmed"><span class="setupPlanConfirmedIcon" aria-hidden="true">' + setupIcon("check") + '</span><span class="setupPlanConfirmedCopy"><strong>Free Echo</strong><span>' + esc(freePlanCopy) + '</span></span><button type="button" class="textButton" id="changeSetupPlan">Change</button></div>';
1315
1297
  renderBillingCommitment("");
@@ -1336,19 +1318,18 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1336
1318
  }
1337
1319
  if (planGateDecision) planGateDecision.classList.add("is-checkout-pending");
1338
1320
  var selectedPaidPlan = pendingPaidPlan === "power" ? "Power" : "Pro";
1339
- var pendingHasTrial = !billingStatus || billingStatus.trialAvailable !== false;
1340
- var pendingPrice = pendingPaidPlan === "power" ? "$100" : "$20";
1341
- var pendingLimit = pendingPaidPlan === "power" ? "2,000" : "500";
1321
+ var pendingPrice = pendingPaidPlan === "power" ? "$20" : "$4";
1322
+ var standardPrice = pendingPaidPlan === "power" ? "$100" : "$20";
1342
1323
  var pendingStatus = billingCheckMessage || (billingLastCheckedAt
1343
1324
  ? "Checking automatically every few seconds · Last checked just now"
1344
1325
  : "Checking automatically every few seconds");
1345
1326
  slot.innerHTML =
1346
1327
  '<section class="setupPlanChoice setupPlanCheckout" aria-labelledby="setupPlanHeading">' +
1347
- '<div class="setupPlanIntro"><h3 id="setupPlanHeading">' + esc(pendingHasTrial ? selectedPaidPlan + " trial — $0 today" : selectedPaidPlan + " subscription") + '</h3><p>Complete checkout in Stripe, then return here. This page updates automatically.</p></div>' +
1328
+ '<div class="setupPlanIntro"><h3 id="setupPlanHeading">' + esc(selectedPaidPlan + " subscription") + '</h3><p>Complete checkout in Stripe, then return here. This page updates automatically.</p></div>' +
1348
1329
  '<dl class="checkoutCommitment">' +
1349
- '<div><dt>Today</dt><dd>' + esc(pendingHasTrial ? "$0" : pendingPrice) + '</dd></div>' +
1350
- '<div><dt>History import</dt><dd>' + esc(pendingLimit) + ' sessions</dd></div>' +
1351
- '<div><dt>' + esc(pendingHasTrial ? "First charge" : "Billing") + '</dt><dd>' + esc(pendingHasTrial ? pendingPrice + " on " + trialChargeDateText() : pendingPrice + "/month now") + '</dd></div>' +
1330
+ '<div><dt>Today</dt><dd>' + esc(pendingPrice) + '</dd></div>' +
1331
+ '<div><dt>History import</dt><dd>Unlimited sessions</dd></div>' +
1332
+ '<div><dt>Billing</dt><dd>' + esc(pendingPrice + "/month for 12 months, then " + standardPrice + "/month") + '</dd></div>' +
1352
1333
  '</dl>' +
1353
1334
  '<div class="checkoutActions"><button type="button" class="primary" id="continueSelectedPaidPlan">Reopen Stripe checkout</button></div>' +
1354
1335
  '<p class="checkoutPollStatus" id="setupPlanStatus" role="status" aria-live="polite">' + esc(pendingStatus) + '</p>' +
@@ -1482,7 +1463,7 @@ export const SETUP_PAGE_CLIENT_EXTRACTION = String.raw ` /* ---------- dash
1482
1463
  setSetupPlanStatus("Opening secure checkout…");
1483
1464
  var checkout = await openHostedBilling(
1484
1465
  "/billing-checkout",
1485
- { plan: plan, trial: !billingStatus || billingStatus.trialAvailable !== false },
1466
+ { plan: plan, trial: false },
1486
1467
  "Creating your secure checkout…",
1487
1468
  "Checkout opened in a secure tab. Keep this local page open; Echo will confirm here automatically."
1488
1469
  );
@@ -51,7 +51,7 @@ function extractionPreviewBootstrap(options) {
51
51
  const historicalConversationQuota = quotaLimit == null || quotaRemaining == null
52
52
  ? null
53
53
  : {
54
- used: Math.max(0, quotaLimit - quotaRemaining),
54
+ used: quotaLimit === -1 ? 0 : Math.max(0, quotaLimit - quotaRemaining),
55
55
  limit: quotaLimit,
56
56
  remaining: quotaRemaining,
57
57
  };
@@ -121,35 +121,35 @@ export function renderSetupPreviewBootstrap(state) {
121
121
  }
122
122
  if (state === "extract-degraded")
123
123
  return `${watermark}${extractionPreviewBootstrap({
124
- plan: "free", paid: false, trialAvailable: true, trialUsed: false,
125
- quotaLimit: 100, quotaRemaining: 100, candidateCount: 7, selectFree: true,
124
+ plan: "free", paid: false, trialAvailable: false, trialUsed: false,
125
+ quotaLimit: -1, quotaRemaining: -1, candidateCount: 7, selectFree: true,
126
126
  })}
127
127
  stats.discovery = { phase: "quick", exact: false };
128
128
  stats.optionalDiagnostics = { degraded: true, reason: "EXACT_DISCOVERY_FAILED", countsTrusted: false };
129
129
  renderDashboard();`;
130
130
  if (state === "extract-degraded-exact")
131
131
  return `${watermark}${extractionPreviewBootstrap({
132
- plan: "free", paid: false, trialAvailable: true, trialUsed: false,
133
- quotaLimit: 100, quotaRemaining: 100, candidateCount: 7, selectFree: true,
132
+ plan: "free", paid: false, trialAvailable: false, trialUsed: false,
133
+ quotaLimit: -1, quotaRemaining: -1, candidateCount: 7, selectFree: true,
134
134
  })}
135
135
  stats.discovery = { phase: "exact", exact: true };
136
136
  stats.optionalDiagnostics = { degraded: true, reason: "ACCOUNT_RECONCILIATION_FAILED", countsTrusted: true };
137
137
  renderDashboard();`;
138
138
  if (state === "extract-ready")
139
139
  return `${watermark}${extractionPreviewBootstrap({
140
- plan: "free", paid: false, trialAvailable: true, trialUsed: false,
141
- quotaLimit: 100, quotaRemaining: 28, candidateCount: 28,
140
+ plan: "free", paid: false, trialAvailable: false, trialUsed: false,
141
+ quotaLimit: -1, quotaRemaining: -1, candidateCount: 28,
142
142
  })}`;
143
143
  if (state === "extract-free-selected")
144
144
  return `${watermark}${extractionPreviewBootstrap({
145
- plan: "free", paid: false, trialAvailable: true, trialUsed: false,
146
- quotaLimit: 100, quotaRemaining: 100, selectFree: true,
145
+ plan: "free", paid: false, trialAvailable: false, trialUsed: false,
146
+ quotaLimit: -1, quotaRemaining: -1, selectFree: true,
147
147
  })}`;
148
148
  if (state === "extract-free-trial-used")
149
149
  return `${watermark}${extractionPreviewBootstrap({
150
150
  plan: "free", paid: false, trialAvailable: false, trialUsed: true,
151
151
  subscriptionStatus: "expired", trialEndedAt: "2026-07-20T00:00:00.000Z",
152
- quotaLimit: 100, quotaRemaining: 100,
152
+ quotaLimit: -1, quotaRemaining: -1,
153
153
  })}`;
154
154
  if (state === "extract-limit")
155
155
  return `${watermark}${extractionPreviewBootstrap({
@@ -160,7 +160,7 @@ export function renderSetupPreviewBootstrap(state) {
160
160
  return `${watermark}${extractionPreviewBootstrap({
161
161
  plan: "pro", paid: true, trialAvailable: false, trialUsed: true,
162
162
  subscriptionStatus: "trialing", trialEndedAt: "2026-08-04T12:00:00.000Z",
163
- quotaLimit: 500, quotaRemaining: 500,
163
+ quotaLimit: -1, quotaRemaining: -1,
164
164
  })}`;
165
165
  if (state === "extract-pro-trial-canceling")
166
166
  return `${watermark}${extractionPreviewBootstrap({
@@ -168,45 +168,45 @@ export function renderSetupPreviewBootstrap(state) {
168
168
  subscriptionStatus: "trialing", cancelAtPeriodEnd: true,
169
169
  trialEndedAt: "2026-08-04T12:00:00.000Z",
170
170
  currentPeriodEnd: "2026-08-04T12:00:00.000Z",
171
- quotaLimit: 500, quotaRemaining: 500,
171
+ quotaLimit: -1, quotaRemaining: -1,
172
172
  })}`;
173
173
  if (state === "extract-pro-active")
174
174
  return `${watermark}${extractionPreviewBootstrap({
175
175
  plan: "pro", paid: true, trialAvailable: false, trialUsed: true,
176
- subscriptionStatus: "active", quotaLimit: 500, quotaRemaining: 500,
176
+ subscriptionStatus: "active", quotaLimit: -1, quotaRemaining: -1,
177
177
  })}`;
178
178
  if (state === "extract-pro-canceling")
179
179
  return `${watermark}${extractionPreviewBootstrap({
180
180
  plan: "pro", paid: true, trialAvailable: false, trialUsed: true,
181
181
  subscriptionStatus: "active", cancelAtPeriodEnd: true,
182
182
  currentPeriodEnd: "2026-08-28T12:00:00.000Z",
183
- quotaLimit: 500, quotaRemaining: 500,
183
+ quotaLimit: -1, quotaRemaining: -1,
184
184
  })}`;
185
185
  if (state === "extract-power-trial")
186
186
  return `${watermark}${extractionPreviewBootstrap({
187
187
  plan: "power", paid: true, trialAvailable: false, trialUsed: true,
188
188
  subscriptionStatus: "trialing", trialEndedAt: "2026-08-04T12:00:00.000Z",
189
189
  currentPeriodEnd: "2026-08-04T12:00:00.000Z",
190
- quotaLimit: 2_000, quotaRemaining: 2_000,
190
+ quotaLimit: -1, quotaRemaining: -1,
191
191
  })}`;
192
192
  if (state === "extract-power-active")
193
193
  return `${watermark}${extractionPreviewBootstrap({
194
194
  plan: "power", paid: true, trialAvailable: false, trialUsed: true,
195
- subscriptionStatus: "active", quotaLimit: 2_000, quotaRemaining: 2_000,
195
+ subscriptionStatus: "active", quotaLimit: -1, quotaRemaining: -1,
196
196
  })}`;
197
197
  if (state === "extract-team-active")
198
198
  return `${watermark}${extractionPreviewBootstrap({
199
199
  plan: "team", paid: true, trialAvailable: false, trialUsed: true,
200
- subscriptionStatus: "active", quotaLimit: 500, quotaRemaining: 500,
200
+ subscriptionStatus: "active", quotaLimit: -1, quotaRemaining: -1,
201
201
  })}`;
202
202
  if (state === "extract-enterprise-active")
203
203
  return `${watermark}${extractionPreviewBootstrap({
204
204
  plan: "enterprise", paid: true, trialAvailable: false, trialUsed: true,
205
- subscriptionStatus: "active", quotaLimit: 2_000, quotaRemaining: 2_000,
205
+ subscriptionStatus: "active", quotaLimit: -1, quotaRemaining: -1,
206
206
  })}`;
207
207
  if (state === "extract-unknown")
208
208
  return `${watermark}${extractionPreviewBootstrap({
209
- plan: "unknown", paid: false, trialAvailable: true, trialUsed: false,
209
+ plan: "unknown", paid: false, trialAvailable: false, trialUsed: false,
210
210
  showUnknownStatus: true,
211
211
  })}`;
212
212
  if (state === "auth-login")
@@ -223,13 +223,13 @@ export function renderSetupPreviewBootstrap(state) {
223
223
  renderLocalLoginComplete();`;
224
224
  if (state === "checkout-pro-selected")
225
225
  return `${watermark}${extractionPreviewBootstrap({
226
- plan: "free", paid: false, trialAvailable: true, trialUsed: false,
227
- quotaLimit: 100, quotaRemaining: 100, selectedPlanChoice: "pro", checkoutPending: true,
226
+ plan: "free", paid: false, trialAvailable: false, trialUsed: false,
227
+ quotaLimit: -1, quotaRemaining: -1, selectedPlanChoice: "pro", checkoutPending: true,
228
228
  })}`;
229
229
  if (state === "checkout-pro-stale")
230
230
  return `${watermark}${extractionPreviewBootstrap({
231
- plan: "free", paid: false, trialAvailable: true, trialUsed: false,
232
- quotaLimit: 100, quotaRemaining: 100, selectedPlanChoice: "pro",
231
+ plan: "free", paid: false, trialAvailable: false, trialUsed: false,
232
+ quotaLimit: -1, quotaRemaining: -1, selectedPlanChoice: "pro",
233
233
  })}`;
234
234
  if (state === "auth-unlock")
235
235
  return `${watermark}\n renderLocalPassphrase("unlock", "preview@example.com");`;
package/dist/setup.js CHANGED
@@ -462,9 +462,9 @@ function echomemGuidanceBlock() {
462
462
  "- EchoMem's local SessionStart hook automatically binds each new Codex or Claude Code conversation to its real source-session ID. Use `bind_source_session` with a fresh UUID only as a compatibility fallback when the hook is unavailable or reports that the session is unbound.",
463
463
  "- Before re-deriving past decisions, project context, or anything the user likely settled before: call `search_memories` first.",
464
464
  '- If the final 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. Link each memory key to its canonical `https://echoknows.com/memory/<memory-id>` URL. Do not cite memories that were merely retrieved, and omit the section when no memory informed the answer.',
465
- "- Before the final response for a task that produced a durable decision, confirmed preference, implementation, resolved bug, commit, passing verification, release, or project milestone: call `save_conversation`. This private checkpoint does not require a separate user request. Do not save secrets, credentials, incidental chatter, or trivial read-only work. If a qualifying save fails because the encrypted vault is locked, relay the bridge's unlock instruction; for this standalone runtime, use `echomem-mcp unlock`. Never silently skip it.",
465
+ "- After writing the final answer for a task that produced a durable decision, confirmed preference, implementation, resolved bug, commit, passing verification, release, or project milestone: call `save_conversation` as the last action, so the user reads the answer without waiting on the save. This private checkpoint does not require a separate user request. Do not save secrets, credentials, incidental chatter, or trivial read-only work. If a qualifying save fails because the encrypted vault is locked, relay the bridge's unlock instruction; for this standalone runtime, use `echomem-mcp unlock`. Never silently skip it.",
466
466
  "- For `save_conversation`, prefer `messages` and omit `conversation`: copy the smallest relevant contiguous set of user and assistant turns verbatim, preserving role and order. Exclude system instructions, tool calls, and hidden content. Use at most six messages and 12,000 total characters; drop whole older turns instead of truncating or rewriting them. If exact source text is unavailable, use `conversation` with a concise structured summary prefixed `Summary (source excerpt unavailable):`.",
467
- '- After `save_conversation` succeeds and returns one or more saved memory IDs, make the save visible in the final user-facing answer with a compact `EchoMem saved:` list containing every memory created by that call. Link each memory key to its canonical `https://echoknows.com/memory/<memory-id>` URL. This save receipt is separate from `EchoMem sources:` and does not imply the newly saved memories informed the answer.',
467
+ '- 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. Link each memory key to its canonical `https://echoknows.com/memory/<memory-id>` URL. This save receipt is separate from `EchoMem sources:` and does not imply the newly saved memories informed the answer.',
468
468
  GROUP_SESSION_SHARING_PROMPTS_ENABLED
469
469
  ? "- For a user with a company group, call `request_group_session_sharing` near conversation start or after a qualifying private save. On the first call in a conversation, omit `groupSharingScopeId` so EchoMem mints a fresh opaque scope. Reuse that exact scope only in this conversation for later get/request/set/save calls, and never persist it as memory. If multiple groups are returned, reuse the same scope and call once per `groupId`. Relay the tool's exact text question and call `set_group_session_sharing` only after an explicit Yes/No. Silence leaves that group's state unset; never infer an answer. Saves sync eligible memories to every approved group; a No keeps them private for that group."
470
470
  : `- Saves are always private. ${GROUP_SESSION_SHARING_DISABLED_NOTE}`,
@@ -567,6 +567,29 @@ export function refreshInstalledMemoryGuidance() {
567
567
  }
568
568
  }
569
569
  }
570
+ /** Refresh EchoMem-owned Codex skills that are already installed; never installs missing ones. */
571
+ export function refreshInstalledCodexSkills() {
572
+ let skillsRoot;
573
+ try {
574
+ skillsRoot = path.join(codexHome(), "skills");
575
+ }
576
+ catch {
577
+ return;
578
+ }
579
+ const templateRoot = fileURLToPath(new URL("../templates/codex-skills/", import.meta.url));
580
+ for (const skillName of CODEX_SKILL_NAMES) {
581
+ const source = path.join(templateRoot, skillName);
582
+ const destination = path.join(skillsRoot, skillName);
583
+ try {
584
+ if (!fs.existsSync(destination) || packagedSkillMatches(source, destination))
585
+ continue;
586
+ fs.cpSync(source, destination, { recursive: true, force: true });
587
+ }
588
+ catch {
589
+ // Unreadable or externally managed skill folders are left untouched.
590
+ }
591
+ }
592
+ }
570
593
  /** Merge the EchoMem entry into a JSON client's `mcpServers` map without clobbering siblings. */
571
594
  export function writeJsonClientConfig(configPath, entry, options = {}) {
572
595
  const config = readJsonObjectFile(configPath, "MCP client configuration");
@@ -2362,7 +2385,7 @@ export function startCallbackServer(opts = {}) {
2362
2385
  json(res, 200, {
2363
2386
  plan: "free",
2364
2387
  paid: false,
2365
- trialAvailable: true,
2388
+ trialAvailable: false,
2366
2389
  trialUsed: false,
2367
2390
  subscriptionStatus: null,
2368
2391
  trialStartedAt: null,
@@ -2381,7 +2404,7 @@ export function startCallbackServer(opts = {}) {
2381
2404
  ]);
2382
2405
  const plan = (asString(response.data?.plan) || "free").toLowerCase();
2383
2406
  const trialUsed = response.data?.billing?.trialUsed === true;
2384
- const trialAvailable = response.data?.billing?.trialAvailable !== false;
2407
+ const trialAvailable = response.data?.billing?.trialAvailable === true;
2385
2408
  const accountEmail = asString(profileResponse?.data?.email) || activeAccountEmail;
2386
2409
  if (accountEmail)
2387
2410
  activeAccountEmail = accountEmail;
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import axios from "axios";
4
4
  import { KeyStore } from "./keystore.js";
5
+ import { MCP_PACKAGE_VERSION } from "./package-metadata.js";
5
6
  import { SOURCE_SESSION_HOOK_EVIDENCE, verifiedClaudeDesktopSession, verifiedSourceSession, } from "./source-session.js";
6
7
  const API_BASE = (process.env.ECHO_API_BASE_URL || "https://echo-mem-chrome.vercel.app").replace(/\/$/, "");
7
8
  const MAX_HEAD_BYTES = 256 * 1024;
@@ -170,6 +171,7 @@ async function bindSourceSession(identity) {
170
171
  providerSessionId: identity.providerSessionId,
171
172
  providerSessionAliases: identity.providerSessionAliases,
172
173
  evidence: identity.evidence,
174
+ runtime_version: MCP_PACKAGE_VERSION,
173
175
  }, {
174
176
  headers: {
175
177
  Authorization: `Bearer ${token}`,
@@ -813,7 +813,7 @@ export function listToolSpecs(opts = {}) {
813
813
  const groupMap = opts.groupMap?.trim();
814
814
  const updateNotice = opts.updateNotice?.trim();
815
815
  const recallPlanNote = "Available on every plan: Free includes 100 searches each week, Pro includes 500, and Power includes 2,000.";
816
- const searchBillingReplyInstruction = "If search returns an ACTION REQUIRED subscription message, tell the user to start their trial or subscription and include the exact URL from that result verbatim. Do not respond only with \"connect\" or \"upgrade\".";
816
+ const searchBillingReplyInstruction = "If search returns an ACTION REQUIRED subscription message, tell the user to start their subscription and include the exact URL from that result verbatim. Do not respond only with \"connect\" or \"upgrade\".";
817
817
  const memoryCitationInstruction = MEMORY_CITATION_INSTRUCTION;
818
818
  const updateSection = updateNotice ? `\n\nUPDATE NOTICE: ${updateNotice}` : "";
819
819
  const mapSection = map
@@ -1264,7 +1264,7 @@ export function listToolSpecs(opts = {}) {
1264
1264
  },
1265
1265
  {
1266
1266
  name: canonicalToolNames.save,
1267
- description: `Save durable knowledge from this conversation into the user's private EchoMem (durable memories are extracted automatically). Call before the final response when work produced a durable decision, confirmed preference, implementation, resolved bug, commit, passing verification, release, or project milestone; this private checkpoint does not require a separate user request. Omit secrets, incidental chatter, and trivial read-only work. If the encrypted vault is locked, tell the user to ${MCP_VAULT_UNLOCK_INSTRUCTION} and never silently skip a qualifying checkpoint. Private persistence happens first.${GROUP_SESSION_SHARING_SAVE_INSTRUCTION} New extraction input uses the plan's weekly processing allowance; if the limit is reached, nothing is saved. passthrough=true stores the text verbatim as a session capsule. ${SAVED_MEMORY_RECEIPT_INSTRUCTION}`,
1267
+ description: `Save durable knowledge from this conversation into the user's private EchoMem (durable memories are extracted automatically). Call after writing the final answer, as the turn's last action, when work produced a durable decision, confirmed preference, implementation, resolved bug, commit, passing verification, release, or project milestone; this private checkpoint does not require a separate user request. Omit secrets, incidental chatter, and trivial read-only work. If the encrypted vault is locked, tell the user to ${MCP_VAULT_UNLOCK_INSTRUCTION} and never silently skip a qualifying checkpoint. Private persistence happens first.${GROUP_SESSION_SHARING_SAVE_INSTRUCTION} New extraction input uses the plan's weekly processing allowance; if the limit is reached, nothing is saved. passthrough=true stores the text verbatim as a session capsule. ${SAVED_MEMORY_RECEIPT_INSTRUCTION}`,
1268
1268
  inputSchema: {
1269
1269
  type: "object",
1270
1270
  properties: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@echomem/mcp",
3
- "version": "1.4.69",
3
+ "version": "1.4.71",
4
4
  "description": "EchoMem MCP bridge for cross-agent memory, local history import, and recall",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -36,7 +36,7 @@
36
36
  "test:config-safety": "npm run build && node test/config-safety.test.mjs",
37
37
  "test:billing-ui": "npm run build && node test/setup-ui.test.mjs billing",
38
38
  "test:mcp-control": "npm run build && node test/mcp-control.test.mjs",
39
- "test": "npm run build && node test/source-session.test.mjs && node test/source-session-stress.test.mjs && node test/cowork-ticket-session.test.mjs && node test/ticket-review-format.test.mjs && node test/schema-parity.test.mjs && node test/ticket-overview.test.mjs && node test/ticket-stewardship-contract.test.mjs && node test/stewardship-integration.test.mjs && node test/source-session-hook.test.mjs && node test/local-data-paths.test.mjs && node test/crypto.test.mjs && node test/integration.test.mjs && node test/onboarding-resilience.test.mjs && node test/local-auth.test.mjs && node test/product-analytics.test.mjs && node test/retrieval-only.test.mjs && node test/no-restart.test.mjs && node test/canonical-golden.test.mjs && node test/tools.test.mjs && node test/workspace-selector.test.mjs && node test/group-map.test.mjs && node test/update-check.test.mjs && node test/headless-runtime.test.mjs && node test/claude-code-config.test.mjs && node test/config-safety.test.mjs && node test/mcp-control.test.mjs && node test/delete.test.mjs && node test/low-touch-tools.test.mjs && node test/migrate.test.mjs && node test/restart-recovery.test.mjs && node test/save-checkpoint-hook.test.mjs && node test/durable-entry.test.mjs && node test/durable-reexec.test.mjs && node test/doctor.test.mjs && node test/environment-matrix.test.mjs",
39
+ "test": "npm run build && node test/source-session.test.mjs && node test/source-session-stress.test.mjs && node test/cowork-ticket-session.test.mjs && node test/ticket-review-format.test.mjs && node test/schema-parity.test.mjs && node test/ticket-overview.test.mjs && node test/ticket-stewardship-contract.test.mjs && node test/stewardship-integration.test.mjs && node test/source-session-hook.test.mjs && node test/local-data-paths.test.mjs && node test/crypto.test.mjs && node test/integration.test.mjs && node test/onboarding-resilience.test.mjs && node test/local-auth.test.mjs && node test/product-analytics.test.mjs && node test/request-failure.test.mjs && node test/retrieval-only.test.mjs && node test/no-restart.test.mjs && node test/canonical-golden.test.mjs && node test/tools.test.mjs && node test/workspace-selector.test.mjs && node test/group-map.test.mjs && node test/update-check.test.mjs && node test/headless-runtime.test.mjs && node test/claude-code-config.test.mjs && node test/config-safety.test.mjs && node test/mcp-control.test.mjs && node test/delete.test.mjs && node test/low-touch-tools.test.mjs && node test/migrate.test.mjs && node test/restart-recovery.test.mjs && node test/save-checkpoint-hook.test.mjs && node test/durable-entry.test.mjs && node test/lifecycle-hook-refresh.test.mjs && node test/durable-reexec.test.mjs && node test/doctor.test.mjs && node test/environment-matrix.test.mjs",
40
40
  "prepack": "npm run build"
41
41
  },
42
42
  "dependencies": {
@@ -16,16 +16,16 @@ Use the `save_conversation` tool from the `echomem` MCP server.
16
16
  `Summary (source excerpt unavailable):`. Add a concise title, source, and useful tags.
17
17
  4. Use `passthrough: true` only when the user explicitly needs a verbatim session capsule.
18
18
  5. Never include secrets, credentials, or unnecessary sensitive content.
19
- 6. Confirm what EchoMem saved. When the tool returns one or more saved memory IDs, end the final
20
- user-facing answer with a compact `EchoMem saved:` list containing every memory created by that
21
- call. Use each memory key as the Markdown label and its canonical
22
- `https://echoknows.com/memory/<memory-id>` URL. Keep this separate from `EchoMem sources:`; a save
19
+ 6. Confirm what EchoMem saved. When the tool returns one or more saved memory IDs, follow the
20
+ already-written answer with a short closing `EchoMem saved:` list containing
21
+ every memory created by that call; do not repeat the answer. Use each memory key as the
22
+ Markdown label and its canonical `https://echoknows.com/memory/<memory-id>` URL. Keep this separate from `EchoMem sources:`; a save
23
23
  receipt does not imply the newly saved memories informed the answer. If saving fails, report the
24
24
  failure without switching providers silently.
25
- 7. Before a final response, use this workflow proactively when the task produced a durable decision,
26
- confirmed preference, implementation, resolved bug, commit, passing verification, release, or
27
- project milestone. A private checkpoint does not require a separate user request. Skip trivial
28
- read-only work and incidental chatter.
25
+ 7. After writing the final answer, use this workflow proactively as the last action when the task
26
+ produced a durable decision, confirmed preference, implementation, resolved bug, commit, passing
27
+ verification, release, or project milestone. A private checkpoint does not require a separate
28
+ user request. Skip trivial read-only work and incidental chatter.
29
29
  8. If the encrypted vault is locked, tell the user to run `echomem-mcp unlock`; never silently skip a
30
30
  qualifying checkpoint.
31
31
  9. For a user with a company group, call `request_group_session_sharing` near conversation start or
@@ -16,9 +16,9 @@ This project has EchoMem connected — the user's long-term memory across all th
16
16
  "the usual", "our convention").
17
17
  - Treat recalled memories as authoritative context, but **cite them** (they carry provenance —
18
18
  date + source) so the user can verify.
19
- - Before the final response for work that produced a durable decision, confirmed preference,
19
+ - After writing the final answer for work that produced a durable decision, confirmed preference,
20
20
  implementation, resolved bug, commit, passing verification, release, or project milestone, call
21
- `save_conversation`. This private checkpoint does not require a separate user request. Prefer
21
+ `save_conversation` as the last action, so the user reads the answer without waiting on the save. This private checkpoint does not require a separate user request. Prefer
22
22
  `messages` and omit `conversation`: copy the smallest relevant contiguous set of user and assistant
23
23
  turns verbatim, preserving role and order. Exclude system instructions, tool calls, and hidden
24
24
  content. Use at most six messages and 12,000 total characters; drop whole older turns instead of
@@ -26,9 +26,9 @@ This project has EchoMem connected — the user's long-term memory across all th
26
26
  structured summary prefixed `Summary (source excerpt unavailable):`. Never save secrets,
27
27
  credentials, incidental chatter, or trivial read-only work. This does not authorize company-group
28
28
  publication.
29
- - After `save_conversation` succeeds and returns one or more saved memory IDs, make the save visible
30
- in the final user-facing answer with a compact `EchoMem saved:` list containing every memory
31
- created by that call. Link each memory key to its canonical
29
+ - After `save_conversation` succeeds and returns one or more saved memory IDs, follow the
30
+ already-written answer with a short closing `EchoMem saved:` list containing every memory
31
+ created by that call; do not repeat the answer. Link each memory key to its canonical
32
32
  `https://echoknows.com/memory/<memory-id>` URL. This save receipt is separate from
33
33
  `EchoMem sources:` and does not imply that the newly saved memories informed the answer.
34
34
  - For a user with a company group, call `request_group_session_sharing` near conversation start or