@echomem/mcp 1.4.70 → 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 (47) 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 +757 -178
  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/request-failure.js +32 -0
  26. package/dist/save-local-trace.js +26 -0
  27. package/dist/save-note-store.js +50 -0
  28. package/dist/save-receipt-store.js +58 -0
  29. package/dist/save-receipt.js +42 -0
  30. package/dist/save-retry.js +43 -0
  31. package/dist/setup-page/client-extraction.js +2 -1
  32. package/dist/setup.js +36 -13
  33. package/dist/source-session-hook.js +16 -2
  34. package/dist/source-session-local.js +241 -0
  35. package/dist/source-session-pretool-hook.js +54 -0
  36. package/dist/source-session.js +4 -0
  37. package/dist/source-snapshot-export.js +68 -0
  38. package/dist/source-snapshot.js +99 -0
  39. package/dist/strict-ingest-contract.js +31 -0
  40. package/dist/strict-raw-session.js +473 -0
  41. package/dist/tool-map-cache.js +62 -0
  42. package/dist/turn-end-saves.js +104 -0
  43. package/dist/v1-contract.js +92 -45
  44. package/package.json +5 -3
  45. package/templates/codex-skills/echomem-save/SKILL.md +23 -24
  46. package/templates/echomem-recall.md +25 -19
  47. package/dist/save-checkpoint-hook.js +0 -122
package/dist/index.js CHANGED
@@ -1,28 +1,53 @@
1
1
  #!/usr/bin/env node
2
+ import "./backend-network-guard.js";
3
+ import { resolveBackendURL, assertBackendURL, readBackendPolicy } from "./backend-policy.js";
4
+ import { recordLocalUsage } from "./local-usage.js";
5
+ import { memoryMarkdownLink } from "./memory-links.js";
2
6
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
7
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
8
  import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError, } from "@modelcontextprotocol/sdk/types.js";
5
9
  import axios from "axios";
6
10
  import { ZodError } from "zod";
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";
11
+ import { acknowledgeWorkspaceTicketReviewSchema, applyWorkspaceTicketActionSchema, bindSourceSessionSchema, canonicalToolNames, completeGroupPublicationSchema, createGroupInviteSchema, createGroupSchema, deleteMemorySchema, flagPublicationAttentionSchema, findWorkspaceTicketCandidatesSchema, getGroupSessionSharingSchema, getByContextSchema, groupContextSchema, joinGroupSchema, keywordsSchema, listFriendsSchema, listToolSpecs, clientNeedsSaveMessages, SAVE_MESSAGES_GUIDE, linkWorkspaceTicketSessionSchema, othersSchema, publishBatchToGroupSchema, publishToGroupSchema, prepareGroupPublicationSchema, publicMemorySchema, recordMemoryCitationsSchema, recordWorkspaceTicketProposalSchema, requestGroupSessionSharingSchema, reviewWorkspaceTicketSessionSchema, resolveCanonicalToolName, saveConversationSchema, searchMemoriesSchema, searchUsersSchema, sendFriendRequestSchema, timeRangeSchema, updateGroupProfileSchema, setGroupSessionSharingSchema, } from "./v1-contract.js";
8
12
  import { KeyStore } from "./keystore.js";
13
+ import { readStrictRawSessionState, SAVE_NOTE_SUFFIX, selectSaveEvidence } from "./strict-raw-session.js";
14
+ import { rememberSaveNote } from "./save-note-store.js";
15
+ import { isMemorySaveDeclined, userRequestText } from "./memory-intent.js";
16
+ import { claimAbandonedTurnEndSaves, credentialHash, finishTurnEndSave, registerTurnEndSave, whenTurnEnds } from "./turn-end-saves.js";
17
+ import { agentMessagesFallbackAllowed, keepRecentMessages } from "./agent-messages-fallback.js";
18
+ import { assertStrictIngestCapabilities, assertStrictIngestReceipt } from "./strict-ingest-contract.js";
19
+ import { PendingSaves } from "./pending-save.js";
20
+ import { withSaveRetry, saveFailureCode } from "./save-retry.js";
21
+ import { beginDesktopSaveActivity, desktopSaveOutcome } from "./desktop-save-activity.js";
22
+ import { completedSaveReceipt, turnSaveResult } from "./save-receipt.js";
23
+ import { enqueueSaveReceipt, takeSaveReceipts } from "./save-receipt-store.js";
24
+ import { startSaveLocalTrace } from "./save-local-trace.js";
25
+ import { readToolMapCache, writeToolMapCache } from "./tool-map-cache.js";
26
+ import { claimSourceSessionProofNonce, registerDirectBridge, takeSourceSessionProof, verifySourceSessionProof } from "./source-session-local.js";
9
27
  import { EventLogger, hashText } from "./events.js";
28
+ import { requestFailureDetails } from "./request-failure.js";
10
29
  import { contextHealthMarkdown, recomposeCapsuleMarkdown } from "./hud/api.js";
11
30
  import { refreshInstalledLifecycleHooks } from "./hud/hooks.js";
12
31
  import { createHash, randomUUID } from "node:crypto";
13
32
  import { AsyncLocalStorage } from "node:async_hooks";
14
33
  import { fetchEncryptionConfig, decryptMemoryFields, verifyKeyB64, } from "./encryption.js";
15
- import { refreshInstalledMemoryGuidance, runCli } from "./setup.js";
34
+ import { refreshInstalledCodexSkills, refreshInstalledMemoryGuidance, runCli } from "./setup.js";
16
35
  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";
17
36
  import { clearBillingAlert, writeBillingAlert } from "./billing-alert.js";
18
37
  import { checkLatestUpdateStatus, formatUpdateNotice, formatUpdateStatusText, startBackgroundUpdateCheck, } from "./update-check.js";
19
38
  import { autoUpdateHeadlessRuntime } from "./headless-runtime.js";
20
39
  import { formatTicketFilingPacket, formatWorkspaceTicketOverview, ticketAddressById, } from "./ticket-review-format.js";
21
40
  import { SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE, resolveCloudCoworkSessionFromToolArguments, resolveSourceSessionRequestContext, resolveSourceSessionFromBindingToken, resolveSourceSessionFromBindingTokenWithRetry, } from "./source-session.js";
22
- const ECHO_API_BASE_URL = process.env.ECHO_API_BASE_URL || "https://echo-mem-chrome.vercel.app";
41
+ const ECHO_API_BASE_URL = resolveBackendURL();
23
42
  const ECHO_PRICING_URL = process.env.ECHO_PRICING_URL || "https://echoknows.com/dashboard/account";
24
43
  const ECHO_MEMORY_WEB_URL = (process.env.ECHO_MEMORY_WEB_URL || "https://echoknows.com/memory").replace(/\/$/, "");
25
44
  const DESKTOP_MANAGED = process.env.ECHO_DESKTOP_MANAGED === "1";
45
+ // No Echo API route may run past Vercel's 300s function limit, so a request
46
+ // still unanswered after this is a dead connection (sleep, network change).
47
+ // Without a limit, such a request waited until the OS gave up (~30 minutes).
48
+ const API_REQUEST_TIMEOUT_MS = 310_000;
49
+ // The routine ticket-fit review is a single database read (p95 under 2s).
50
+ const TICKET_REVIEW_TIMEOUT_MS = 30_000;
26
51
  const CONNECT_DEVICE_INSTRUCTION = DESKTOP_MANAGED
27
52
  ? "Open Echo Desktop, sign in, and choose Connect MCP, then retry this action."
28
53
  : "Run `echomem-mcp login` in a terminal to reconnect this device, then retry this action.";
@@ -35,14 +60,6 @@ function memoryWebUrl(memoryId) {
35
60
  function personalMemoryWebUrl(memoryId) {
36
61
  return memoryWebUrl(memoryId);
37
62
  }
38
- function memoryMarkdownLink(url, keys, description) {
39
- const rawLabel = String(keys || description || "Open memory").replace(/\s+/g, " ").trim();
40
- const label = (rawLabel.length > 100 ? `${rawLabel.slice(0, 97).trim()}…` : rawLabel)
41
- .replace(/\\/g, "\\\\")
42
- .replace(/\[/g, "\\[")
43
- .replace(/\]/g, "\\]");
44
- return `[${label}](${url})`;
45
- }
46
63
  function withMemoryCitationInstruction(text) {
47
64
  return `${text}\n\n${MEMORY_CITATION_INSTRUCTION}`;
48
65
  }
@@ -52,6 +69,14 @@ class NoTokenError extends Error {
52
69
  /** Thrown when an encrypted account has no usable key — the model gets an unlock nudge, never ciphertext. */
53
70
  class LockedError extends Error {
54
71
  }
72
+ /** A short code the desktop can name; never server text. */
73
+ function desktopFailureReason(error) {
74
+ if (error instanceof LockedError)
75
+ return "VAULT_LOCKED";
76
+ if (axios.isAxiosError(error) && error.response?.status === 429)
77
+ return "QUOTA_EXCEEDED";
78
+ return saveFailureCode(error);
79
+ }
55
80
  /** Thrown when the bridge cannot prove whether the account is encrypted. */
56
81
  class EncryptionStatusUnavailableError extends Error {
57
82
  }
@@ -154,21 +179,24 @@ function formatUpgradeRequiredResult(error) {
154
179
  const data = error.response?.data;
155
180
  if (!isRecord(data))
156
181
  return null;
182
+ const code = readString(data, "error") ?? readString(data, "code");
183
+ const normalizedCode = String(code || "").toUpperCase();
184
+ // Billing answers are a 402 *_REQUIRES_PLAN or a *_QUOTA_EXCEEDED code. Any
185
+ // other 403 (session not owned, no workspace access) and the per-minute
186
+ // rate limit are ordinary errors and must not ask the user to upgrade.
187
+ const quotaExceeded = normalizedCode.includes("QUOTA");
188
+ const planRequired = status === 402 || normalizedCode.includes("REQUIRES_PLAN");
189
+ if (!quotaExceeded && !planRequired)
190
+ return null;
157
191
  const upgradeUrl = readString(data, "upgradeUrl")
158
192
  ?? readString(data, "pricingUrl")
159
193
  ?? readString(data, "url")
160
194
  ?? ECHO_PRICING_URL;
161
195
  const message = readString(data, "message")
162
196
  ?? "Memory search and recall require an Echo Pro or Power plan.";
163
- const code = readString(data, "error") ?? readString(data, "code");
164
197
  const plan = readString(data, "plan");
165
198
  const pricingUrl = appendDesktopClientHint(appendPricingSource(upgradeUrl, "mcp_search"));
166
- const normalizedCode = String(code || "").toUpperCase();
167
- const kind = status === 429 || normalizedCode.includes("QUOTA") || normalizedCode.includes("LIMIT")
168
- ? "quota_exceeded"
169
- : status === 402 || normalizedCode.includes("REQUIRES_PLAN")
170
- ? "plan_required"
171
- : "billing_attention";
199
+ const kind = quotaExceeded ? "quota_exceeded" : "plan_required";
172
200
  writeBillingAlert({
173
201
  kind,
174
202
  code,
@@ -263,11 +291,14 @@ function routePersonalRecallInvocation(canonicalName, args) {
263
291
  const hasKeywords = hasKeywordInput(normalizedArgs);
264
292
  const hasDateRangeInput = Boolean(readString(normalizedArgs, "startDate") || readString(normalizedArgs, "endDate"));
265
293
  const intentCount = Number(hasSemanticInput) + Number(hasKeywords) + Number(hasDateRangeInput);
266
- if (intentCount > 1) {
294
+ const semanticWithDateRange = hasSemanticInput && hasDateRangeInput && !hasKeywords
295
+ && Boolean(readString(normalizedArgs, "query"))
296
+ && readNumber(normalizedArgs, "timeFrameDays") === undefined;
297
+ if (intentCount > 1 && !semanticWithDateRange) {
267
298
  return {
268
299
  canonicalName,
269
300
  args: normalizedArgs,
270
- error: "Ambiguous memory search arguments. Use exactly one input shape: {query, optional timeFrameDays} for topic search, {keywords} for exact-key search, or {startDate, endDate} for a date range.",
301
+ error: "Ambiguous memory search arguments. Use exactly one input shape: {query, optional timeFrameDays} for topic search, {keywords} for exact-key search, or {startDate, endDate} for a date range. A personal topic query may also include both startDate and endDate, without timeFrameDays.",
271
302
  };
272
303
  }
273
304
  if (hasSemanticInput) {
@@ -412,6 +443,30 @@ function conversationAnalyticsFromMessages(value) {
412
443
  ...safeTextAnalytics("last_user_message", userMessages.at(-1)),
413
444
  };
414
445
  }
446
+ function formatMessagesForIngest(messages) {
447
+ return messages
448
+ .map((message) => {
449
+ const content = message.content.trim();
450
+ if (!content)
451
+ return "";
452
+ const label = isUserRole(message.role) ? "User" : message.role.toLowerCase() === "system" ? "System" : "Assistant";
453
+ return `## ${label}\n\n${content}`;
454
+ })
455
+ .filter(Boolean)
456
+ .join("\n\n---\n\n");
457
+ }
458
+ function throwIfProcessingQuotaExceeded(error) {
459
+ if (!axios.isAxiosError(error) || error.response?.status !== 429)
460
+ return;
461
+ const data = error.response.data;
462
+ if (data?.error !== "MEMORY_PROCESSING_QUOTA_EXCEEDED")
463
+ return;
464
+ const message = typeof data.message === "string"
465
+ ? data.message
466
+ : "Weekly memory-processing limit reached. This conversation was not saved.";
467
+ const upgrade = typeof data.upgradeUrl === "string" ? ` Upgrade: ${data.upgradeUrl}` : "";
468
+ throw new McpError(ErrorCode.InvalidRequest, `${message}${upgrade}`);
469
+ }
415
470
  function lastUserMessageFromMessages(value) {
416
471
  if (!Array.isArray(value))
417
472
  return undefined;
@@ -457,23 +512,11 @@ function lastUserMessageFromConversationText(value) {
457
512
  flush();
458
513
  return lastUser || undefined;
459
514
  }
460
- function formatMessagesForIngest(messages) {
461
- return messages
462
- .map((message) => {
463
- const content = message.content.trim();
464
- if (!content)
465
- return "";
466
- const role = message.role.toLowerCase();
467
- const label = role === "user" || role === "human"
468
- ? "User"
469
- : role === "system"
470
- ? "System"
471
- : "Assistant";
472
- return `## ${label}\n\n${content}`;
473
- })
474
- .filter(Boolean)
475
- .join("\n\n---\n\n");
476
- }
515
+ /** The memory columns GET /api/extension/memories/:id returns that a complete candidate also carries. */
516
+ const COMPLETE_MEMORY_ROW_FIELDS = [
517
+ "id", "user_id", "time", "location", "category", "object", "emotion", "description", "details", "created_at",
518
+ "updated_at", "type", "keys", "context_id", "is_public", "is_encrypted", "publication_attention_label",
519
+ ];
477
520
  function normalizeRetrievalCandidate(value, fallbackRank) {
478
521
  if (!isRecord(value))
479
522
  return null;
@@ -492,16 +535,22 @@ function normalizeRetrievalCandidate(value, fallbackRank) {
492
535
  isPublic: typeof value.is_public === "boolean" ? value.is_public : undefined,
493
536
  };
494
537
  }
495
- function withinTimeFrame(memory, candidate, timeFrameDays) {
496
- if (!timeFrameDays)
538
+ function withinTimeFrame(memory, candidate, timeFrameDays, startDate, endDate) {
539
+ if (!timeFrameDays && !startDate && !endDate)
497
540
  return true;
498
541
  const timestamp = readString(memory, "time") ?? readString(memory, "created_at") ?? candidate.time;
499
542
  if (!timestamp)
500
- return true;
543
+ return !startDate && !endDate;
501
544
  const ms = Date.parse(timestamp);
502
545
  if (!Number.isFinite(ms))
503
- return true;
504
- return ms >= Date.now() - timeFrameDays * 24 * 60 * 60 * 1000;
546
+ return !startDate && !endDate;
547
+ if (timeFrameDays && ms < Date.now() - timeFrameDays * 24 * 60 * 60 * 1000)
548
+ return false;
549
+ if (startDate && ms < Date.parse(startDate))
550
+ return false;
551
+ if (endDate && ms > Date.parse(endDate))
552
+ return false;
553
+ return true;
505
554
  }
506
555
  function numberArg(args, key) {
507
556
  return typeof args[key] === "number" && Number.isFinite(args[key]) ? args[key] : undefined;
@@ -731,7 +780,16 @@ class EchoMemApiClient {
731
780
  axios;
732
781
  activeToken;
733
782
  accountGeneration = 0;
783
+ pendingSaves;
784
+ /** Conversations with a save waiting for the host to finish the turn, and how the last one ended. */
785
+ turnEndWaits = new Set();
786
+ /** Turn-end saves made unnecessary because the turn was saved, with its receipt, before it ended. */
787
+ turnEndCancelled = new Set();
788
+ turnEndOutcomes = new Map();
789
+ strictCapability = null;
734
790
  boundSourceSession = null;
791
+ /** The connected app's MCP client name; decides whether an unbound save may fall back. */
792
+ hostClientName;
735
793
  requestContext = new AsyncLocalStorage();
736
794
  sourceSessionsByCanonicalKey = new Map();
737
795
  whoamiCache = null;
@@ -741,9 +799,12 @@ class EchoMemApiClient {
741
799
  deleteConfirmations = new Map();
742
800
  constructor(store) {
743
801
  this.store = store;
802
+ this.pendingSaves = new PendingSaves();
744
803
  this.activeToken = store.getToken();
745
804
  this.axios = axios.create({
746
805
  baseURL: ECHO_API_BASE_URL.replace(/\/$/, ""),
806
+ ...(readBackendPolicy() ? { maxRedirects: 0 } : {}),
807
+ timeout: API_REQUEST_TIMEOUT_MS,
747
808
  headers: {
748
809
  "Content-Type": "application/json",
749
810
  "X-Echo-Client": "mcp",
@@ -752,6 +813,7 @@ class EchoMemApiClient {
752
813
  // Read the token fresh on EVERY request (not baked in at construction) so a `login` that runs
753
814
  // after the editor already launched the bridge is picked up on the next call — no restart.
754
815
  this.axios.interceptors.request.use((config) => {
816
+ assertBackendURL(new URL(config.url ?? "", config.baseURL).href);
755
817
  const token = this.synchronizeAccountContext();
756
818
  if (token)
757
819
  config.headers.set("Authorization", `Bearer ${token}`);
@@ -778,6 +840,7 @@ class EchoMemApiClient {
778
840
  this.boundSourceSession = null;
779
841
  this.sourceSessionsByCanonicalKey.clear();
780
842
  this.deleteConfirmations.clear();
843
+ this.turnEndOutcomes.clear();
781
844
  return token;
782
845
  }
783
846
  /** Lets the MCP server invalidate its account-scoped tool-description caches too. */
@@ -789,6 +852,19 @@ class EchoMemApiClient {
789
852
  hasToken() {
790
853
  return !!this.synchronizeAccountContext();
791
854
  }
855
+ /** Called after a successful tool response, never by another session/subagent.
856
+ * Consuming a receipt does not submit a save or move the extraction cursor. */
857
+ takeTurnEndOutcomes(session, generation) {
858
+ if (this.refreshAccountContext() !== generation || !session)
859
+ return null;
860
+ const token = this.store.getToken();
861
+ if (!token)
862
+ return null;
863
+ const receipts = takeSaveReceipts({ account: credentialHash(token), backend: ECHO_API_BASE_URL, session: session.canonicalKey });
864
+ receipts.push(...(this.turnEndOutcomes.get(session.contextId) ?? []));
865
+ this.turnEndOutcomes.delete(session.contextId);
866
+ return [...new Set(receipts)].join("\n\n") || null;
867
+ }
792
868
  /** The per-process session id — the join key telemetry shares with grouped saves. */
793
869
  getSessionId() {
794
870
  return this.sessionId;
@@ -932,7 +1008,9 @@ class EchoMemApiClient {
932
1008
  workspaceId: parsed.workspaceId,
933
1009
  groupId: parsed.groupId,
934
1010
  memoryThreshold: parsed.memoryThreshold,
1011
+ ticketId: parsed.ticketId,
935
1012
  },
1013
+ timeout: TICKET_REVIEW_TIMEOUT_MS,
936
1014
  });
937
1015
  return response.data;
938
1016
  }
@@ -1022,12 +1100,22 @@ class EchoMemApiClient {
1022
1100
  * Best-effort: returns undefined on any failure (locked vault, network) rather than blocking tools.
1023
1101
  */
1024
1102
  async fetchMemoryMap() {
1103
+ const cached = readToolMapCache("personal", this.store.getToken(), this.store.getKey());
1104
+ if (cached) {
1105
+ void this.refreshMemoryMapCache();
1106
+ return cached;
1107
+ }
1108
+ return this.refreshMemoryMapCache();
1109
+ }
1110
+ async refreshMemoryMapCache() {
1025
1111
  try {
1112
+ const token = this.store.getToken();
1026
1113
  const enc = await this.encState(); // unencrypted → {enabled:false}; encrypted+locked → throws
1027
1114
  // Tool-list decoration is not a user-initiated search and must not spend
1028
1115
  // one of the account's weekly searches. Build the best-effort map from
1029
1116
  // the ordinary paginated memory listing instead.
1030
- const response = await this.axios.get("/api/extension/memories?limit=200", { timeout: 6000 });
1117
+ // Only the keys are read, so the library-wide totals are not asked for.
1118
+ const response = await this.axios.get("/api/extension/memories?limit=200&summary=0", { timeout: 6000 });
1031
1119
  const data = enc.enabled ? await this.decryptResult(response.data, enc.key) : response.data;
1032
1120
  const memories = Array.isArray(data?.data)
1033
1121
  ? data.data
@@ -1037,7 +1125,11 @@ class EchoMemApiClient {
1037
1125
  const keys = [...new Set(memories.map((m) => String(m?.keys || "").trim()).filter(Boolean))];
1038
1126
  if (!keys.length)
1039
1127
  return undefined;
1040
- return keys.slice(0, 40).map((k) => `- ${k}`).join("\n");
1128
+ const map = keys.slice(0, 40).map((k) => `- ${k}`).join("\n");
1129
+ if (token === this.store.getToken()) {
1130
+ writeToolMapCache("personal", map, token, enc.enabled ? enc.key : this.store.getKey());
1131
+ }
1132
+ return map;
1041
1133
  }
1042
1134
  catch {
1043
1135
  return undefined;
@@ -1049,9 +1141,22 @@ class EchoMemApiClient {
1049
1141
  * local vault is locked — unlike `fetchMemoryMap`, it never needs a decryption key.
1050
1142
  */
1051
1143
  async fetchGroupMemoryMap() {
1144
+ const cached = readToolMapCache("group", this.store.getToken(), this.store.getKey());
1145
+ if (cached) {
1146
+ void this.refreshGroupMemoryMapCache();
1147
+ return cached;
1148
+ }
1149
+ return this.refreshGroupMemoryMapCache();
1150
+ }
1151
+ async refreshGroupMemoryMapCache() {
1052
1152
  try {
1153
+ const token = this.store.getToken();
1154
+ const vaultKey = this.store.getKey();
1053
1155
  const response = await this.axios.get("/api/extension/social/groups/current", { timeout: 6000 });
1054
1156
  const map = typeof response.data?.map === "string" ? response.data.map.trim() : "";
1157
+ if (map && token === this.store.getToken() && vaultKey === this.store.getKey()) {
1158
+ writeToolMapCache("group", map, token, vaultKey);
1159
+ }
1055
1160
  return map || undefined;
1056
1161
  }
1057
1162
  catch {
@@ -1059,6 +1164,41 @@ class EchoMemApiClient {
1059
1164
  }
1060
1165
  }
1061
1166
  /** Encryption config for the current account, cached only for the lifetime of its token. */
1167
+ /** The backend's capability document. Only a document that passes the contract check is
1168
+ * kept for the process and signed-in account; a failed fetch or an incompatible document
1169
+ * is dropped, so a backend restarted or replaced at the same URL is re-checked by the
1170
+ * next save instead of failing every save until this process restarts. A backend that
1171
+ * turns incompatible after a passing check fails the receipt check of the next save. */
1172
+ /** Resolves to how many memories one save may write under the verified contract. */
1173
+ async ensureStrictCapability(explicitBoundary) {
1174
+ const generation = this.refreshAccountContext();
1175
+ if (!this.strictCapability || this.strictCapability.generation !== generation) {
1176
+ const data = this.axios.get("/api/extension/memories/ingest", { maxRedirects: 0, timeout: 10_000 })
1177
+ .then(response => response.data)
1178
+ .catch(error => {
1179
+ if (this.strictCapability?.data === data)
1180
+ this.strictCapability = null; // allow retry next call
1181
+ throw error;
1182
+ });
1183
+ this.strictCapability = { generation, data };
1184
+ }
1185
+ const cached = this.strictCapability;
1186
+ let capability;
1187
+ try {
1188
+ capability = await cached.data;
1189
+ }
1190
+ catch {
1191
+ throw new Error("STRICT_INGEST_BACKEND_UNAVAILABLE: could not verify the backend's strict contract. No transcript was submitted.");
1192
+ }
1193
+ try {
1194
+ return assertStrictIngestCapabilities(capability, explicitBoundary);
1195
+ }
1196
+ catch (error) {
1197
+ if (this.strictCapability === cached)
1198
+ this.strictCapability = null; // re-check the backend next call
1199
+ throw error;
1200
+ }
1201
+ }
1062
1202
  async getEncryptionConfig() {
1063
1203
  const generation = this.refreshAccountContext();
1064
1204
  if (!this.encConfigPromise) {
@@ -1154,8 +1294,18 @@ class EchoMemApiClient {
1154
1294
  logicalRequestId: opts.requestId,
1155
1295
  sessionId: this.sessionId,
1156
1296
  userTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
1297
+ ...(opts.startDate ? { startDate: opts.startDate, endDate: opts.endDate } : {}),
1157
1298
  ...(opts.workspaceId ? { workspaceId: opts.workspaceId } : {}),
1158
1299
  ...(opts.workspaceId ? { recordAccess: opts.recordAccess !== false } : {}),
1300
+ // Personal recall: the host model wrote the query, so the backend retrieves those words
1301
+ // as they are, in score order, with this call's budget and recency filter. The slack
1302
+ // above `limit` covers rows the threshold or the duplicate collapse removes. Older
1303
+ // backends ignore these fields and keep their planned, time-ordered answer.
1304
+ ...(opts.workspaceId ? {} : {
1305
+ mode: "direct",
1306
+ k: Math.min(opts.limit + 10, 60),
1307
+ ...(opts.timeFrameDays ? { timeFrameDays: opts.timeFrameDays } : {}),
1308
+ }),
1159
1309
  });
1160
1310
  trace?.({ requestId: opts.requestId, endpoint, httpStatus: response.status });
1161
1311
  }
@@ -1191,15 +1341,29 @@ class EchoMemApiClient {
1191
1341
  seen.add(candidate.id);
1192
1342
  return true;
1193
1343
  });
1344
+ // The backend answers two angles on the question and returns the primary one
1345
+ // first. Its budget (12) outruns the usual limit (10), so reading the list in
1346
+ // order delivers the primary angle alone and drops the second one unread.
1347
+ // Hold part of the budget for it; whichever bucket runs short, the other fills
1348
+ // the rest, so a question with one good angle still returns `limit` memories.
1349
+ const orderedCandidates = (() => {
1350
+ const primary = dedupedCandidates.filter((candidate) => candidate.bucket === "primary");
1351
+ const inference = dedupedCandidates.filter((candidate) => candidate.bucket !== "primary");
1352
+ if (!inference.length || primary.length < opts.limit)
1353
+ return dedupedCandidates;
1354
+ const reserved = Math.min(inference.length, Math.max(1, Math.floor(opts.limit / 3)));
1355
+ const kept = opts.limit - reserved;
1356
+ return [...primary.slice(0, kept), ...inference.slice(0, reserved), ...primary.slice(kept), ...inference.slice(reserved)];
1357
+ })();
1194
1358
  const memories = [];
1195
- for (const candidate of dedupedCandidates) {
1196
- if (opts.workspaceId) {
1359
+ if (opts.workspaceId) {
1360
+ for (const candidate of orderedCandidates) {
1197
1361
  const raw = rawCandidates.find((value) => {
1198
1362
  if (!isRecord(value))
1199
1363
  return false;
1200
1364
  return (readString(value, "memory_id") ?? readString(value, "id")) === candidate.id;
1201
1365
  });
1202
- if (!isRecord(raw) || !withinTimeFrame(raw, candidate, opts.timeFrameDays))
1366
+ if (!isRecord(raw) || !withinTimeFrame(raw, candidate, opts.timeFrameDays, opts.startDate, opts.endDate))
1203
1367
  continue;
1204
1368
  const key = readString(raw, "key") ?? readString(raw, "keys") ?? candidate.key ?? "";
1205
1369
  memories.push({
@@ -1220,31 +1384,68 @@ class EchoMemApiClient {
1220
1384
  });
1221
1385
  if (memories.length >= opts.limit)
1222
1386
  break;
1223
- continue;
1224
1387
  }
1388
+ }
1389
+ else {
1225
1390
  if (!enc)
1226
1391
  throw new Error("Personal memory search requires encryption state");
1227
- const row = await this.fetchMemoryById(candidate.id, enc);
1228
- if (!row || !withinTimeFrame(row, candidate, opts.timeFrameDays))
1229
- continue;
1230
- const key = readString(row, "key") ?? readString(row, "keys") ?? candidate.key ?? "";
1231
- const memory = {
1232
- ...row,
1233
- id: readString(row, "id") ?? candidate.id,
1234
- key,
1235
- keys: readString(row, "keys") ?? key,
1236
- retrieval_bucket: candidate.bucket,
1237
- retrieval_rank: candidate.rank,
1238
- is_public: typeof row.is_public === "boolean" ? row.is_public : candidate.isPublic,
1392
+ // Hydrate a bounded batch in parallel, then consume it in candidate-rank order.
1393
+ // This avoids serial network/decryption latency without changing recall order
1394
+ // or fetching the entire candidate set when the requested limit is small.
1395
+ // A backend that marks a candidate `memory_row_complete` already sent the full
1396
+ // row (ciphertext included), so it is decrypted here instead of re-fetched: one
1397
+ // HTTP round trip per search instead of one per memory. Older backends still GET.
1398
+ const completeRows = new Map();
1399
+ for (const raw of rawCandidates) {
1400
+ if (!isRecord(raw) || raw.memory_row_complete !== true)
1401
+ continue;
1402
+ const id = readString(raw, "memory_id") ?? readString(raw, "id");
1403
+ if (id)
1404
+ completeRows.set(id, raw);
1405
+ }
1406
+ const hydrate = async (id) => {
1407
+ const raw = completeRows.get(id);
1408
+ if (!raw)
1409
+ return this.fetchMemoryById(id, enc);
1410
+ const row = {};
1411
+ for (const field of COMPLETE_MEMORY_ROW_FIELDS)
1412
+ if (field in raw)
1413
+ row[field] = raw[field];
1414
+ return (enc.enabled ? await decryptMemoryFields(row, enc.key) : row);
1239
1415
  };
1240
- if (candidate.score !== undefined) {
1241
- memory.similarity = candidate.score;
1242
- memory.similarity_score = candidate.score;
1243
- memory.retrieval_similarity_score = candidate.score;
1416
+ const hydrationBatchSize = Math.min(8, Math.max(1, opts.limit));
1417
+ // The same note saved twice (identical key and description) takes one slot, not two.
1418
+ const shownRows = new Set();
1419
+ for (let offset = 0; offset < orderedCandidates.length && memories.length < opts.limit; offset += hydrationBatchSize) {
1420
+ const batch = orderedCandidates.slice(offset, offset + hydrationBatchSize);
1421
+ const rows = await Promise.all(batch.map((candidate) => hydrate(candidate.id)));
1422
+ for (let index = 0; index < batch.length && memories.length < opts.limit; index++) {
1423
+ const candidate = batch[index];
1424
+ const row = rows[index];
1425
+ if (!row || !withinTimeFrame(row, candidate, opts.timeFrameDays, opts.startDate, opts.endDate))
1426
+ continue;
1427
+ const key = readString(row, "key") ?? readString(row, "keys") ?? candidate.key ?? "";
1428
+ const rowIdentity = `${key}\u0000${typeof row.description === "string" ? row.description : ""}`;
1429
+ if (shownRows.has(rowIdentity))
1430
+ continue;
1431
+ shownRows.add(rowIdentity);
1432
+ const memory = {
1433
+ ...row,
1434
+ id: readString(row, "id") ?? candidate.id,
1435
+ key,
1436
+ keys: readString(row, "keys") ?? key,
1437
+ retrieval_bucket: candidate.bucket,
1438
+ retrieval_rank: candidate.rank,
1439
+ is_public: typeof row.is_public === "boolean" ? row.is_public : candidate.isPublic,
1440
+ };
1441
+ if (candidate.score !== undefined) {
1442
+ memory.similarity = candidate.score;
1443
+ memory.similarity_score = candidate.score;
1444
+ memory.retrieval_similarity_score = candidate.score;
1445
+ }
1446
+ memories.push(memory);
1447
+ }
1244
1448
  }
1245
- memories.push(memory);
1246
- if (memories.length >= opts.limit)
1247
- break;
1248
1449
  }
1249
1450
  return {
1250
1451
  success: true,
@@ -1294,6 +1495,8 @@ class EchoMemApiClient {
1294
1495
  limit,
1295
1496
  threshold,
1296
1497
  timeFrameDays: parsed.timeFrameDays,
1498
+ startDate: parsed.startDate,
1499
+ endDate: parsed.endDate,
1297
1500
  requestId: randomUUID(),
1298
1501
  workspaceId,
1299
1502
  recordAccess: parsed.recordAccess,
@@ -1312,26 +1515,117 @@ class EchoMemApiClient {
1312
1515
  }
1313
1516
  return data;
1314
1517
  }
1315
- async saveConversation(args) {
1518
+ /** Reports each save that contacts the backend to Echo Desktop's notch: it
1519
+ * starts with the first request and ends with the receipt, a skip, or a failure. */
1520
+ async saveConversation(args, origin = "explicit", waitForCompletion = false) {
1521
+ const report = { origin, joined: true };
1522
+ try {
1523
+ const result = await this.saveConversationOnce(args, report, waitForCompletion);
1524
+ // A call that joined an identical in-flight save leaves the report to it.
1525
+ if (report.joined)
1526
+ report.activity?.discard();
1527
+ return result;
1528
+ }
1529
+ catch (error) {
1530
+ if (report.joined && report.queued)
1531
+ report.activity?.discard();
1532
+ else
1533
+ report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
1534
+ throw error;
1535
+ }
1536
+ }
1537
+ async saveConversationOnce(args, report, waitForCompletion) {
1316
1538
  if (this.isSubagentRequest()) {
1317
1539
  throw new Error(SUBAGENT_DURABLE_WRITE_MESSAGE);
1318
1540
  }
1319
1541
  const parsed = saveConversationSchema.parse(args ?? {});
1320
1542
  const groupSharingScopeId = parsed.groupSharingScopeId ?? randomUUID();
1321
- let rawData = parsed.conversation?.trim() || "";
1322
- if (!rawData && parsed.messages?.length) {
1323
- rawData = formatMessagesForIngest(parsed.messages);
1324
- }
1325
- if (!rawData) {
1326
- throw new McpError(ErrorCode.InvalidParams, "Either conversation or messages is required.");
1543
+ const boundSourceSession = this.getBoundSourceSession();
1544
+ const receiptToken = this.store.getToken();
1545
+ // All triggers use verified source evidence and the same Gemini renderer.
1546
+ // Legacy flags are rejected, not used to downgrade after a provider/source error.
1547
+ if (parsed.passthrough === true) {
1548
+ throw new McpError(ErrorCode.InvalidParams, "MEMORY_EXTRACTION_REQUIRED: passthrough is disabled. Call save_conversation without conversation, messages or passthrough; never retry errors as direct writes.");
1549
+ }
1550
+ if (parsed.conversation !== undefined) {
1551
+ throw new McpError(ErrorCode.InvalidParams, "VERIFIED_SOURCE_REQUIRED: omit conversation; a host-written summary is never a source. EchoMem reads the original session, and asks for verbatim messages only when it cannot.");
1552
+ }
1553
+ // A verified local transcript always wins; agent-supplied turns are used only by hosts
1554
+ // whose transcript this bridge cannot read (Cursor, Claude Desktop chat, Cloud Cowork).
1555
+ let rawSession;
1556
+ let turnOpen;
1557
+ let transcript;
1558
+ try {
1559
+ if (!boundSourceSession?.contextId)
1560
+ throw new Error("SOURCE_SESSION_REQUIRED");
1561
+ ({ rawData: rawSession, turnOpen, file: transcript } = readStrictRawSessionState(boundSourceSession, undefined, parsed.note));
1327
1562
  }
1328
- if (parsed.tags?.length) {
1329
- rawData = `Tags: ${parsed.tags.join(", ")}\n\n${rawData}`;
1563
+ catch (error) {
1564
+ const code = error instanceof Error ? error.message : "";
1565
+ if (agentMessagesFallbackAllowed(boundSourceSession, code, this.hostClientName)) {
1566
+ return this.saveFromAgentMessages(parsed, { boundSourceSession, groupSharingScopeId, receiptToken, report, reason: code });
1567
+ }
1568
+ if (code === "SOURCE_SESSION_REQUIRED") {
1569
+ // Same recovery the ticket tools offer: a request-scoped token found in this host's own
1570
+ // transcript turns this into a verified save in the session's real context.
1571
+ throw new McpError(ErrorCode.InvalidParams, [
1572
+ "SOURCE_SESSION_REQUIRED: EchoMem could not verify this host conversation, so no memory was written.",
1573
+ "Status: source_session_unavailable",
1574
+ "Retry this exact save_conversation call once with a fresh random UUID in sourceSessionBindingToken. The bridge verifies it from this tool call in the local host transcript and saves from that transcript.",
1575
+ "Never reuse that token, copy one from another conversation, or send a summary instead. If the retry also fails, report that nothing was saved.",
1576
+ ].join("\n"));
1577
+ }
1578
+ throw error;
1330
1579
  }
1580
+ // An open turn is saved now, from the note in this call, so the agent writes the receipt in
1581
+ // its own answer.
1582
+ const requested = !turnOpen ? { ...parsed, note: undefined } : parsed;
1583
+ let evidence = selectSaveEvidence(rawSession, requested, turnOpen);
1584
+ for (let waited = 0; !evidence && waited < 4_000 && turnOpen && requested.note?.trim(); waited += 200) {
1585
+ // The host writes this call a moment after the fact.
1586
+ await new Promise(resolve => setTimeout(resolve, 200));
1587
+ try {
1588
+ rawSession = readStrictRawSessionState(boundSourceSession, undefined, requested.note).rawData;
1589
+ }
1590
+ catch {
1591
+ continue;
1592
+ }
1593
+ evidence = selectSaveEvidence(rawSession, requested, turnOpen);
1594
+ }
1595
+ // A note placed at a scripted call is not in the host's own record. It is kept before the
1596
+ // save is made, so every later reading of this session shows it where it was saved.
1597
+ const noteBoundary = turnOpen ? evidence?.boundary.assistantMessageId : undefined;
1598
+ if (boundSourceSession.provider === "codex" && noteBoundary?.endsWith(SAVE_NOTE_SUFFIX) && requested.note?.trim()
1599
+ && !rememberSaveNote(boundSourceSession.providerSessionId, noteBoundary.slice(0, -SAVE_NOTE_SUFFIX.length), requested.note.trim())) {
1600
+ evidence = null;
1601
+ }
1602
+ const savedInTurn = Boolean(evidence && turnOpen && evidence.boundary.assistantMessageId?.endsWith(SAVE_NOTE_SUFFIX));
1603
+ if (!evidence && turnOpen) {
1604
+ // A save reads only finished turns. This one is still being written, so the call
1605
+ // registers the request and the bridge saves once the host has written the turn's end.
1606
+ this.saveAfterTurnEnds(boundSourceSession, transcript, {
1607
+ groupSharingScopeId, source: parsed.source, title: parsed.title, tags: parsed.tags, url: parsed.url,
1608
+ });
1609
+ return { success: true, memoriesExtracted: 0, extractedMemories: [], savesAfterTurnEnds: true,
1610
+ noteMissing: !parsed.note?.trim(),
1611
+ contextId: boundSourceSession.contextId, groupSharingScopeId };
1612
+ }
1613
+ // This turn is saved now with its receipt: a turn-end save an earlier call registered is not needed.
1614
+ if (savedInTurn && this.turnEndWaits.has(boundSourceSession.contextId))
1615
+ this.turnEndCancelled.add(boundSourceSession.contextId);
1616
+ if (!evidence) {
1617
+ return { success: true, memoriesExtracted: 0, extractedMemories: [], deferredUntilCompletion: true,
1618
+ contextId: boundSourceSession.contextId, groupSharingScopeId };
1619
+ }
1620
+ const { rawData, boundary } = evidence;
1621
+ report.activity = beginDesktopSaveActivity({ token: receiptToken, backend: ECHO_API_BASE_URL, origin: report.origin });
1622
+ // The backend's strict contract is verified before any source is sent, once per process
1623
+ // and signed-in account; every save's receipt re-checks it.
1624
+ const maxNewMemories = await this.ensureStrictCapability(Boolean(boundary.userMessageId));
1625
+ const completionId = boundary.assistantMessageId ?? boundary.userMessageId;
1331
1626
  // For an encrypted account, hand the server the key transiently in the X-Encryption-Key header
1332
1627
  // so it encrypts at rest (mirrors the extension's write path, spec §3.1a). Locked → LockedError.
1333
1628
  const enc = await this.encState();
1334
- const boundSourceSession = this.getBoundSourceSession();
1335
1629
  const config = {
1336
1630
  headers: {
1337
1631
  "X-EchoMem-Request-Id": randomUUID(),
@@ -1339,41 +1633,207 @@ class EchoMemApiClient {
1339
1633
  // session can reach it through remote-devices, but its provisional
1340
1634
  // identity evidence does not change the bridge's transport channel.
1341
1635
  "X-EchoMem-Origin-Channel": "local_mcp",
1636
+ ...(boundSourceSession?.contextId ? { "X-EchoMem-Context-Id": boundSourceSession.contextId } : {}),
1342
1637
  ...(enc.enabled && enc.key ? { "X-Encryption-Key": enc.key } : {}),
1343
1638
  },
1344
1639
  };
1345
- try {
1346
- const response = await this.axios.post("/api/extension/memories/ingest", {
1347
- rawData,
1348
- sourceUrl: parsed.url,
1349
- source: parsed.source || "mcp_server",
1350
- title: parsed.title,
1351
- // A source-session identity owns the memory context. Provisional Cloud Cowork identity
1352
- // is explicitly marked by its evidence. The independent opaque scope still
1353
- // governs group-sharing consent and never becomes the source-session identity.
1354
- conversationKey: boundSourceSession?.canonicalKey ?? groupSharingScopeId,
1355
- groupSharingScopeId,
1356
- passthrough: parsed.passthrough || false,
1357
- triggerMessage: parsed.triggerMessage ||
1358
- lastUserMessageFromMessages(parsed.messages) ||
1359
- lastUserMessageFromConversationText(parsed.conversation),
1360
- triggerMessageRole: parsed.triggerMessageRole || "user",
1361
- }, config);
1362
- return { ...response.data, groupSharingScopeId };
1363
- }
1364
- catch (error) {
1365
- if (axios.isAxiosError(error) && error.response?.status === 429) {
1366
- const data = error.response.data;
1367
- if (data?.error === "MEMORY_PROCESSING_QUOTA_EXCEEDED") {
1368
- const message = typeof data.message === "string"
1369
- ? data.message
1370
- : "Weekly memory-processing limit reached. This conversation was not saved.";
1371
- const upgrade = typeof data.upgradeUrl === "string" ? ` Upgrade: ${data.upgradeUrl}` : "";
1372
- throw new McpError(ErrorCode.InvalidRequest, `${message}${upgrade}`);
1640
+ const generation = this.accountGeneration;
1641
+ const operationKey = hashText(JSON.stringify([generation, boundSourceSession.contextId, completionId, rawData]));
1642
+ report.queued = true;
1643
+ const result = await this.pendingSaves.run(operationKey, groupSharingScopeId, completionId, async () => {
1644
+ report.joined = false;
1645
+ const finishLocalTrace = startSaveLocalTrace({ endpoint: `${ECHO_API_BASE_URL}/api/extension/memories/ingest`, contextId: boundSourceSession?.contextId, rawData,
1646
+ ...(parsed.assistantMessageId ? { trigger: { kind: "assistant_message_end", assistantMessageId: parsed.assistantMessageId } } : {}) });
1647
+ const traceStarted = Date.now();
1648
+ try {
1649
+ const send = () => withSaveRetry(async () => {
1650
+ this.synchronizeAccountContext();
1651
+ if (generation !== this.accountGeneration)
1652
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: retry stopped because the signed-in account changed.");
1653
+ return this.axios.post("/api/extension/memories/ingest", {
1654
+ rawData,
1655
+ sourceUrl: parsed.url,
1656
+ source: parsed.source || "mcp_server",
1657
+ title: parsed.title,
1658
+ // A source-session identity owns the memory context. Provisional Cloud Cowork identity
1659
+ // is explicitly marked by its evidence. The independent opaque scope still
1660
+ // governs group-sharing consent and never becomes the source-session identity.
1661
+ conversationKey: boundSourceSession?.canonicalKey ?? groupSharingScopeId,
1662
+ groupSharingScopeId,
1663
+ strictIngest: true,
1664
+ debugTrace: Boolean(process.env.ECHOMEM_SAVE_TRACE_DIR),
1665
+ ...boundary,
1666
+ // A verified save never forwards agent-supplied turns, not even as the trigger preview.
1667
+ triggerMessage: parsed.triggerMessage || undefined,
1668
+ triggerMessageRole: parsed.triggerMessageRole || "user",
1669
+ }, { ...config, timeout: 300_000, maxRedirects: 0 });
1670
+ });
1671
+ const response = await send();
1672
+ try {
1673
+ assertStrictIngestReceipt(response.data, maxNewMemories);
1674
+ }
1675
+ catch (error) {
1676
+ // The backend no longer answers as the contract it showed: check it again before the next save.
1677
+ this.strictCapability = null;
1678
+ throw error;
1373
1679
  }
1680
+ finishLocalTrace({ response: response.data, state: "COMPLETED", elapsedMs: Date.now() - traceStarted });
1681
+ report.activity?.finish(desktopSaveOutcome(response.data));
1682
+ if (response.data?.success === true && response.data?.memoriesExtracted > 0) {
1683
+ // Keep the encrypted startup hint fresh for the next bridge process.
1684
+ // Refreshing is advisory and must not delay the save receipt.
1685
+ void this.refreshMemoryMapCache();
1686
+ if ((Array.isArray(response.data?.groupSyncs) && response.data.groupSyncs.length > 0) || (typeof response.data?.groupSyncsDeferred === "number" && response.data.groupSyncsDeferred > 0)) {
1687
+ void this.refreshGroupMemoryMapCache();
1688
+ }
1689
+ }
1690
+ return { ...response.data, groupSharingScopeId };
1374
1691
  }
1375
- throw error;
1692
+ catch (error) {
1693
+ finishLocalTrace({ state: "FAILED", elapsedMs: Date.now() - traceStarted,
1694
+ response: axios.isAxiosError(error) ? error.response?.data ?? { success: false, error: "TRANSPORT_ERROR" } : { success: false, error: "LOCAL_SAVE_ERROR" },
1695
+ httpStatus: axios.isAxiosError(error) ? error.response?.status : undefined });
1696
+ // A save that outlives the caller's wait still reports how it ended.
1697
+ report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
1698
+ throwIfProcessingQuotaExceeded(error);
1699
+ throw error;
1700
+ }
1701
+ }, waitForCompletion);
1702
+ this.synchronizeAccountContext();
1703
+ if (generation !== this.accountGeneration)
1704
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: the result was withheld because the signed-in account changed.");
1705
+ if ("pendingProcessing" in result && result.pendingProcessing) {
1706
+ return { ...result, assistantMessageId: boundary.assistantMessageId, userMessageId: boundary.userMessageId };
1707
+ }
1708
+ return { ...result, savedBoundary: boundary, savedInTurn };
1709
+ }
1710
+ /** One wait per conversation: when the host has written the end of the turn, run the same
1711
+ * save again in the caller's request context. Its result goes to Echo Desktop's notch and
1712
+ * to the next successful MCP tool call of this conversation. */
1713
+ saveAfterTurnEnds(session, transcript, args, context = this.requestContext.getStore() ?? { sourceSession: session, isSubagent: false, lineageStatus: "not_applicable" }) {
1714
+ const id = session.contextId;
1715
+ if (this.turnEndWaits.has(id))
1716
+ return;
1717
+ this.turnEndWaits.add(id);
1718
+ const generation = this.accountGeneration;
1719
+ const token = this.store.getToken();
1720
+ if (token)
1721
+ registerTurnEndSave({ v: 1, contextId: id, session, args, credentialHash: credentialHash(token), backend: ECHO_API_BASE_URL, registeredAt: Date.now() });
1722
+ whenTurnEnds(transcript, () => readStrictRawSessionState(session).turnOpen, () => {
1723
+ if (this.refreshAccountContext() !== generation || this.turnEndCancelled.delete(id)) {
1724
+ this.turnEndWaits.delete(id);
1725
+ finishTurnEndSave(id);
1726
+ return;
1727
+ }
1728
+ const enqueue = (receipt) => {
1729
+ if (this.refreshAccountContext() !== generation)
1730
+ return;
1731
+ if (token && enqueueSaveReceipt({ account: credentialHash(token), backend: ECHO_API_BASE_URL, session: session.canonicalKey }, receipt))
1732
+ return;
1733
+ const receipts = this.turnEndOutcomes.get(id) ?? [];
1734
+ receipts.push(receipt);
1735
+ this.turnEndOutcomes.set(id, receipts);
1736
+ };
1737
+ void this.withRequestContext(context, () => this.saveConversation(args, "auto", true)).then(result => {
1738
+ // The next EchoMem tool call carries the receipt.
1739
+ const receipt = completedSaveReceipt(result, personalMemoryWebUrl);
1740
+ if (receipt)
1741
+ enqueue(receipt);
1742
+ }, error => {
1743
+ enqueue(`The previous turn's save failed (${desktopFailureReason(error)}); no successful save was confirmed. Tell the user briefly; do not claim it was saved.`);
1744
+ }).finally(() => {
1745
+ this.turnEndWaits.delete(id);
1746
+ finishTurnEndSave(id);
1747
+ });
1748
+ });
1749
+ }
1750
+ /** Finish saves that an earlier bridge process registered and did not live to make. */
1751
+ resumeTurnEndSaves() {
1752
+ const token = this.store.getToken();
1753
+ if (!token)
1754
+ return;
1755
+ for (const entry of claimAbandonedTurnEndSaves(credentialHash(token), ECHO_API_BASE_URL)) {
1756
+ const session = entry.session;
1757
+ try {
1758
+ this.saveAfterTurnEnds(session, readStrictRawSessionState(session).file, entry.args, { sourceSession: session, isSubagent: false, lineageStatus: "not_applicable" });
1759
+ }
1760
+ catch {
1761
+ finishTurnEndSave(entry.contextId); // its transcript is gone
1762
+ }
1763
+ }
1764
+ }
1765
+ /** The save path for a host with no transcript this bridge can read: the agent supplies the
1766
+ * relevant turns verbatim, as before the strict bridge, and the backend extracts from them. */
1767
+ async saveFromAgentMessages(parsed, ctx) {
1768
+ // Over the safety cap, the most recent turns are kept rather than the save refused.
1769
+ const { kept: messages, omittedMessages, shortenedNewest } = keepRecentMessages(parsed.messages ?? []);
1770
+ // The same refusal a transcript save honours: the user's latest words decide.
1771
+ const latestRequest = [...messages].reverse().find(message => message.role === "user" && userRequestText(message.content));
1772
+ if (latestRequest && isMemorySaveDeclined(latestRequest.content))
1773
+ throw new Error("MEMORY_SAVE_DECLINED: the latest user request asks not to save; no source was submitted.");
1774
+ let rawData = messages.length ? formatMessagesForIngest(messages) : "";
1775
+ if (!rawData) {
1776
+ // Asking for the turns is a normal step for these hosts, not a failure: nothing was written.
1777
+ return { success: true, memoriesExtracted: 0, extractedMemories: [], messagesRequired: ctx.reason, groupSharingScopeId: ctx.groupSharingScopeId };
1376
1778
  }
1779
+ if (parsed.tags?.length)
1780
+ rawData = `Tags: ${parsed.tags.join(", ")}\n\n${rawData}`;
1781
+ const generation = this.accountGeneration;
1782
+ const conversationKey = ctx.boundSourceSession?.canonicalKey ?? ctx.groupSharingScopeId;
1783
+ ctx.report.activity = beginDesktopSaveActivity({ token: ctx.receiptToken, backend: ECHO_API_BASE_URL, origin: ctx.report.origin });
1784
+ ctx.report.queued = true;
1785
+ // Identical concurrent calls share one write, as verified saves do. An unbound call's key is a
1786
+ // fresh random scope unless the agent passed one, so it is left out of the identity here.
1787
+ const operationKey = hashText(JSON.stringify([generation, ctx.boundSourceSession?.canonicalKey ?? parsed.groupSharingScopeId ?? "unbound", rawData]));
1788
+ const result = await this.pendingSaves.run(operationKey, ctx.groupSharingScopeId, "agent-messages", async () => {
1789
+ ctx.report.joined = false;
1790
+ try {
1791
+ const enc = await this.encState();
1792
+ const response = await withSaveRetry(async () => {
1793
+ this.synchronizeAccountContext();
1794
+ if (generation !== this.accountGeneration)
1795
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: retry stopped because the signed-in account changed.");
1796
+ return this.axios.post("/api/extension/memories/ingest", {
1797
+ rawData,
1798
+ sourceUrl: parsed.url,
1799
+ source: parsed.source || "mcp_server",
1800
+ title: parsed.title,
1801
+ conversationKey,
1802
+ groupSharingScopeId: ctx.groupSharingScopeId,
1803
+ // Tells the backend this local save had no readable transcript; it then accepts the
1804
+ // agent's turns instead of requiring the strict verified-source contract.
1805
+ sourceEvidence: "agent_messages",
1806
+ triggerMessage: parsed.triggerMessage || lastUserMessageFromMessages(messages),
1807
+ triggerMessageRole: parsed.triggerMessageRole || "user",
1808
+ }, {
1809
+ headers: {
1810
+ "X-EchoMem-Request-Id": randomUUID(),
1811
+ "X-EchoMem-Origin-Channel": "local_mcp",
1812
+ ...(enc.enabled && enc.key ? { "X-Encryption-Key": enc.key } : {}),
1813
+ },
1814
+ timeout: 300_000,
1815
+ maxRedirects: 0,
1816
+ });
1817
+ });
1818
+ ctx.report.activity?.finish(desktopSaveOutcome(response.data));
1819
+ if (response.data?.success === true && response.data?.memoriesExtracted > 0) {
1820
+ void this.refreshMemoryMapCache();
1821
+ if ((Array.isArray(response.data?.groupSyncs) && response.data.groupSyncs.length > 0) || (typeof response.data?.groupSyncsDeferred === "number" && response.data.groupSyncsDeferred > 0)) {
1822
+ void this.refreshGroupMemoryMapCache();
1823
+ }
1824
+ }
1825
+ return { ...response.data, groupSharingScopeId: ctx.groupSharingScopeId };
1826
+ }
1827
+ catch (error) {
1828
+ ctx.report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
1829
+ throwIfProcessingQuotaExceeded(error);
1830
+ throw error;
1831
+ }
1832
+ });
1833
+ this.synchronizeAccountContext();
1834
+ if (generation !== this.accountGeneration)
1835
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: the result was withheld because the signed-in account changed.");
1836
+ return omittedMessages || shortenedNewest ? { ...result, messagesTrimmed: { omittedMessages, shortenedNewest } } : result;
1377
1837
  }
1378
1838
  async deleteMemory(args) {
1379
1839
  const parsed = deleteMemorySchema.parse(args ?? {});
@@ -1427,6 +1887,7 @@ class EchoMemApiClient {
1427
1887
  endDate: parsed.endDate,
1428
1888
  limit: parsed.limit,
1429
1889
  requestId: randomUUID(),
1890
+ sessionId: this.sessionId,
1430
1891
  });
1431
1892
  return enc.enabled ? await this.decryptResult(response.data, enc.key) : response.data;
1432
1893
  }
@@ -1588,6 +2049,24 @@ class EchoMemApiClient {
1588
2049
  }
1589
2050
  async prepareGroupPublication(args) {
1590
2051
  const parsed = prepareGroupPublicationSchema.parse(args ?? {});
2052
+ if (parsed.currentSession) {
2053
+ const sourceSession = this.getRequestSourceSession();
2054
+ if (!sourceSession) {
2055
+ throw new Error("source_session_unavailable: retry with a fresh sourceSessionBindingToken to verify this conversation before preparing its publication.");
2056
+ }
2057
+ if (parsed.contextId && parsed.contextId !== sourceSession.contextId) {
2058
+ throw new Error("currentSession cannot be combined with a different contextId.");
2059
+ }
2060
+ // The preview's limit counts memories; the review's own limit counts tickets and is smaller.
2061
+ const result = await this.reviewWorkspaceTicketSession({ ...parsed, limit: undefined });
2062
+ const review = isRecord(result?.review) ? result.review : {};
2063
+ const workspaceId = readString(review, "workspaceId");
2064
+ if (!workspaceId)
2065
+ throw new Error("workspace_selection_required: specify the destination workspaceId or ticketId for this session's publication preview.");
2066
+ parsed.contextId = sourceSession.contextId;
2067
+ parsed.scope = "context";
2068
+ parsed.workspaceId = workspaceId;
2069
+ }
1591
2070
  const enc = await this.encState();
1592
2071
  const response = await this.axios.post("/api/extension/social/groups/current/publications/prepare", parsed, { headers: enc.enabled && enc.key ? { "X-Encryption-Key": enc.key } : undefined });
1593
2072
  return response.data;
@@ -1656,6 +2135,7 @@ function capWait(pending) {
1656
2135
  ]);
1657
2136
  }
1658
2137
  class EchoMemMCPServer {
2138
+ store;
1659
2139
  server;
1660
2140
  client;
1661
2141
  accountGeneration = 0;
@@ -1670,6 +2150,7 @@ class EchoMemMCPServer {
1670
2150
  groupMapInjected = false;
1671
2151
  updateStatus;
1672
2152
  constructor(store) {
2153
+ this.store = store;
1673
2154
  this.server = new Server({
1674
2155
  name: "echomem-mcp",
1675
2156
  version: SERVER_VERSION,
@@ -1774,7 +2255,7 @@ class EchoMemMCPServer {
1774
2255
  this.mapInjected = !!map;
1775
2256
  this.groupMapInjected = !!groupMap;
1776
2257
  const updateNotice = DESKTOP_MANAGED ? undefined : formatUpdateNotice(this.updateStatus);
1777
- return { tools: listToolSpecs({ map, groupMap, updateNotice }) };
2258
+ return { tools: listToolSpecs({ map, groupMap, updateNotice, includeSaveMessages: clientNeedsSaveMessages(this.mcpClientName) }) };
1778
2259
  });
1779
2260
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
1780
2261
  this.refreshAccountContext();
@@ -1787,17 +2268,59 @@ class EchoMemMCPServer {
1787
2268
  const clientVersion = this.server.getClientVersion();
1788
2269
  this.mcpClientName = clientVersion?.name ?? this.mcpClientName;
1789
2270
  this.mcpClientVersion = clientVersion?.version ?? this.mcpClientVersion;
2271
+ this.client.hostClientName = this.mcpClientName;
1790
2272
  let sourceResolution = {
1791
2273
  sourceSession: null,
1792
2274
  isSubagent: false,
1793
2275
  lineageStatus: "unbound",
1794
2276
  };
1795
2277
  try {
1796
- sourceResolution = resolveSourceSessionRequestContext(extra._meta, { hostPlatform: this.getMcpClientAnalytics().host_platform });
2278
+ sourceResolution = resolveSourceSessionRequestContext(extra._meta, {
2279
+ hostPlatform: this.getMcpClientAnalytics().host_platform,
2280
+ // Desktop's local-agent-mode MCP process serves multiple conversations.
2281
+ // Its environment belongs to the process, never to this request.
2282
+ env: this.mcpClientName?.startsWith("local-agent-mode-") ? {} : process.env,
2283
+ });
1797
2284
  }
1798
2285
  catch {
1799
2286
  // Malformed host metadata is not model input. Ignore it and retain the explicit fallback.
1800
2287
  }
2288
+ // The hook leaves a call's proof under the host's ID for that call; a hook that could not
2289
+ // do that put it in the input instead.
2290
+ const toolUseId = isRecord(extra._meta) ? extra._meta["claudecode/toolUseId"] : undefined;
2291
+ const sourceSessionProof = (typeof toolUseId === "string" && toolUseId ? takeSourceSessionProof(toolUseId) : null)
2292
+ ?? (isRecord(request.params.arguments) ? request.params.arguments.sourceSessionProof : undefined);
2293
+ // Signed out, a proof cannot be checked and nothing can be written: the tool itself then
2294
+ // says that EchoMem is not connected.
2295
+ if (sourceSessionProof !== undefined && this.client.hasToken()) {
2296
+ const verified = typeof sourceSessionProof === "string"
2297
+ ? verifySourceSessionProof(sourceSessionProof, `mcp__echomem__${request.params.name}`, this.store.getToken())
2298
+ : null;
2299
+ if (!verified || sourceResolution.isSubagent) {
2300
+ throw new McpError(ErrorCode.InvalidParams, "Invalid or unavailable host source-session proof");
2301
+ }
2302
+ // Only an identity the host sent with this request can contradict the call's own proof.
2303
+ // The process environment is fixed at launch: after /clear Claude Code is in a new
2304
+ // session while this process still holds the old ID.
2305
+ let sentWithRequest = null;
2306
+ try {
2307
+ sentWithRequest = resolveSourceSessionRequestContext(extra._meta, { hostPlatform: this.getMcpClientAnalytics().host_platform, env: {} }).sourceSession;
2308
+ }
2309
+ catch {
2310
+ // Malformed host metadata names no identity.
2311
+ }
2312
+ if (sentWithRequest && sentWithRequest.canonicalKey !== verified.identity.canonicalKey) {
2313
+ throw new McpError(ErrorCode.InvalidParams, "Host metadata and source-session proof disagree");
2314
+ }
2315
+ if (!claimSourceSessionProofNonce(verified.nonce, this.store.getToken())) {
2316
+ throw new McpError(ErrorCode.InvalidParams, "Source-session proof was already used");
2317
+ }
2318
+ sourceResolution = {
2319
+ sourceSession: verified.identity,
2320
+ isSubagent: false,
2321
+ lineageStatus: "top_level",
2322
+ };
2323
+ }
1801
2324
  let provisionalCloudSession = null;
1802
2325
  try {
1803
2326
  provisionalCloudSession = resolveCloudCoworkSessionFromToolArguments(toolArgs);
@@ -1836,7 +2359,8 @@ class EchoMemMCPServer {
1836
2359
  }
1837
2360
  // A child request starts fail-closed. Resolved children bind to the originating root; unresolved
1838
2361
  // children carry an explicit null so AsyncLocalStorage cannot fall through to a global binding.
1839
- let requestSourceSession = sourceResolution.isSubagent
2362
+ const sharedDesktopBridge = this.mcpClientName?.startsWith("local-agent-mode-") === true;
2363
+ let requestSourceSession = sourceResolution.isSubagent || sharedDesktopBridge
1840
2364
  ? null
1841
2365
  : this.client.getBoundSourceSession();
1842
2366
  // Verified request metadata always wins over a bridge-level compatibility fallback. The
@@ -1845,6 +2369,7 @@ class EchoMemMCPServer {
1845
2369
  if (sourceResolution.sourceSession && this.client.hasToken()) {
1846
2370
  requestSourceSession = await this.client.bindSourceSession(sourceResolution.sourceSession, false);
1847
2371
  }
2372
+ const receiptGeneration = this.client.refreshAccountContext();
1848
2373
  return this.client.withRequestContext({
1849
2374
  ...sourceResolution,
1850
2375
  sourceSession: requestSourceSession,
@@ -1947,26 +2472,8 @@ class EchoMemMCPServer {
1947
2472
  }],
1948
2473
  };
1949
2474
  }
1950
- // If logged in, persist the capsule via passthrough so it's retrievable by contextId.
1951
- if (this.client.hasToken()) {
1952
- try {
1953
- const saveResult = await this.client.saveConversation({
1954
- conversation: capsuleText,
1955
- title: "Session capsule (recompose)",
1956
- source: "mcp_recompose",
1957
- passthrough: true,
1958
- });
1959
- const ctxId = saveResult?.contextId;
1960
- const capId = saveResult?.capsuleId;
1961
- const persistLine = ctxId
1962
- ? `\n\n---\nCapsule persisted${capId ? ` (${capId})` : ""}. To reload in a fresh session:\nget_memories_by_context({ contextId: "${ctxId}" })`
1963
- : "";
1964
- return { content: [{ type: "text", text: capsuleText + persistLine }] };
1965
- }
1966
- catch {
1967
- // Persistence is best-effort; return the capsule text regardless.
1968
- }
1969
- }
2475
+ // Recompose is a local preview/export, never a memory-write shortcut.
2476
+ // Durable retention must use save_conversation's verified Gemini path.
1970
2477
  return { content: [{ type: "text", text: capsuleText }] };
1971
2478
  }
1972
2479
  if (!this.client.hasToken())
@@ -2051,6 +2558,13 @@ class EchoMemMCPServer {
2051
2558
  }
2052
2559
  catch (error) {
2053
2560
  rec.error_kind = classifyError(error);
2561
+ // Memory search reports its own request trace; every other tool gets
2562
+ // its failure detail (HTTP status, upstream code, timeout or network) here.
2563
+ if (rec.http_status === undefined && rec.error_code === undefined) {
2564
+ const failure = requestFailureDetails(error);
2565
+ rec.http_status = failure.httpStatus;
2566
+ rec.error_code = failure.errorCode;
2567
+ }
2054
2568
  if (error instanceof NoTokenError) {
2055
2569
  // Not isError: a normal "not connected yet" state. Once `login` runs, the next call works.
2056
2570
  return {
@@ -2130,6 +2644,7 @@ class EchoMemMCPServer {
2130
2644
  rec.ok = rec.error_kind === "none";
2131
2645
  rec.latency_ms = Date.now() - t0;
2132
2646
  this.events.record(rec);
2647
+ recordLocalUsage({ action: canonicalName, source: this.getMcpClientAnalytics().host_platform, outcome: rec.ok ? "success" : "failure", duration_ms: rec.latency_ms });
2133
2648
  if (canonicalName !== canonicalToolNames.updateStatus &&
2134
2649
  canonicalName !== canonicalToolNames.contextHealth &&
2135
2650
  canonicalName !== canonicalToolNames.recompose &&
@@ -2158,6 +2673,11 @@ class EchoMemMCPServer {
2158
2673
  void this.client.trackMcpAnalyticsEvent(toolEventName(canonicalName, rec.ok ? "Succeeded" : "Failed"), finalAnalytics, `${analyticsCallId}:completed`);
2159
2674
  }
2160
2675
  }
2676
+ }).then(result => {
2677
+ if (sourceResolution.isSubagent || result.isError || !this.client.hasToken())
2678
+ return result;
2679
+ const receipt = this.client.takeTurnEndOutcomes(requestSourceSession, receiptGeneration);
2680
+ return receipt ? { ...result, content: [...result.content, { type: "text", text: receipt }] } : result;
2161
2681
  });
2162
2682
  });
2163
2683
  }
@@ -2295,26 +2815,53 @@ Details: ${m.details || "N/A"}`)
2295
2815
  rec.conversation_chars = text.length;
2296
2816
  rec.save_source = typeof a?.source === "string" ? a.source : sourceFallback;
2297
2817
  }
2298
- const { success, memoriesExtracted, memoriesDiscarded, extractedMemories, contextId, capsuleId, passthrough: isPassthrough, groupSessionSharing, groupSync, groupSyncs, groupSharingScopeId, error, } = await this.client.saveConversation(enrichedArgs);
2818
+ const { success, memoriesExtracted, memoriesDiscarded, extractedMemories, contextId, passthrough: isPassthrough, groupSessionSharing, groupSync, groupSyncs, groupSyncsDeferred, groupSharingScopeId, error, decision, reason, pendingNewEvidence, deferredUntilCompletion, savesAfterTurnEnds, noteMissing, savedInTurn, pendingProcessing, savedBoundary, messagesRequired, messagesTrimmed, } = await this.client.saveConversation(enrichedArgs);
2299
2819
  if (!success)
2300
2820
  throw new Error(`EchoMem API Error: ${error}`);
2821
+ if (isPassthrough)
2822
+ throw new Error("MEMORY_EXTRACTION_REQUIRED: backend returned a legacy direct-write receipt; update the backend.");
2301
2823
  if (rec)
2302
2824
  rec.memories_extracted = typeof memoriesExtracted === "number" ? memoriesExtracted : undefined;
2303
- // Passthrough saves store the capsule verbatim — no extraction, no embeddings.
2304
- if (isPassthrough) {
2825
+ if (typeof messagesRequired === "string") {
2826
+ return { content: [{ type: "text", text: `Nothing was saved yet. EchoMem cannot read this app's transcript (SOURCE_TRANSCRIPT_UNAVAILABLE: ${messagesRequired}). Call save_conversation again with messages: ${SAVE_MESSAGES_GUIDE}. Do not tell the user anything was saved until that call returns saved memories.` }] };
2827
+ }
2828
+ if (savesAfterTurnEnds && noteMissing) {
2829
+ return { content: [{ type: "text", text: "Registered. EchoMem saves this turn once it has ended, because this call had no note. To save it now and show its receipt in this answer, call save_conversation once more with note: two to six self-contained sentences, in the user's language, stating what this turn decided, found or changed, with the concrete names, numbers and reasons. EchoMem then saves this turn before you answer and returns the receipt to show. Say nothing about EchoMem to the user until that call returns." }] };
2830
+ }
2831
+ if (savesAfterTurnEnds) {
2832
+ // The call carried a note, and the host's record of the call could not be read in time.
2833
+ if (rec)
2834
+ rec.save_note_unread = true;
2835
+ return { content: [{ type: "text", text: "Registered. EchoMem saves this turn from the verified transcript once the turn has ended; it could not read this call in the host's transcript yet, so there is no receipt to show in this answer. Write your answer as usual and say nothing about EchoMem or this save in it. Do not claim the turn was saved, poll, or call save_conversation again for it. The next EchoMem tool result carries this turn's receipt; show it once when it arrives." }] };
2836
+ }
2837
+ if (deferredUntilCompletion) {
2838
+ return { content: [{ type: "text", text: "No memory was written: the verified source has no finished answer to save. Do not claim anything was saved." }] };
2839
+ }
2840
+ if (pendingProcessing) {
2841
+ // The operation keeps running in this bridge; a repeat call only re-attaches to it.
2842
+ return { content: [{ type: "text", text: "The save is still processing in the background and will finish without another call. Tell the user briefly that EchoMem is still saving. Do not call save_conversation again for it, and do not report it as saved or as zero memories." }] };
2843
+ }
2844
+ const checkpointReceipt = savedBoundary ? `EchoMem checkpoint: ${JSON.stringify(savedBoundary)}` : "";
2845
+ // Notice about what this save covers: messages cut to fit the cap.
2846
+ const pendingNotice = [
2847
+ isRecord(messagesTrimmed)
2848
+ ? `The messages exceeded EchoMem's size cap, so only the most recent were saved${messagesTrimmed.omittedMessages ? ` (${messagesTrimmed.omittedMessages} earlier message${messagesTrimmed.omittedMessages === 1 ? "" : "s"} left out)` : ""}${messagesTrimmed.shortenedNewest ? "; the newest message was cut to its end" : ""}. Next time send only the turns worth remembering.`
2849
+ : "",
2850
+ ].filter(Boolean).join("\n\n");
2851
+ if (memoriesExtracted === 0 && !isPassthrough) {
2852
+ const existing = Array.isArray(extractedMemories) ? extractedMemories.filter(isRecord) : [];
2305
2853
  const text = [
2306
- `Session capsule saved (passthrough, no extraction).`,
2307
- typeof capsuleId === "string" && capsuleId ? `Capsule ID: ${capsuleId}` : "",
2308
- typeof capsuleId === "string" && capsuleId
2309
- ? `Open saved capsule: ${memoryMarkdownLink(personalMemoryWebUrl(capsuleId), "Session capsule")}`
2310
- : "",
2311
- typeof contextId === "string" && contextId ? `Context: ${contextId}` : "",
2312
- typeof groupSharingScopeId === "string" && groupSharingScopeId
2313
- ? `Conversation sharing scope: ${groupSharingScopeId}`
2314
- : "",
2315
- "",
2316
- `To reload this capsule in a fresh session: get_memories_by_context({ contextId: "${contextId}" })`,
2317
- ].filter(Boolean).join("\n");
2854
+ existing.length
2855
+ ? "Conversation processed successfully. This request was already saved; no duplicate memory was created."
2856
+ : "Conversation processed successfully. No memory was created; there is no new memory ID.",
2857
+ ...existing.map(memory => typeof memory.id === "string"
2858
+ ? `Existing memory: ${memoryMarkdownLink(personalMemoryWebUrl(memory.id), memory.keys, memory.description)}` : ""),
2859
+ typeof decision === "string" ? `Decision: ${decision}.` : "",
2860
+ typeof reason === "string" ? `Reason: ${reason}.` : "",
2861
+ pendingNewEvidence === true ? "Waiting for new evidence; the source window remains pending." : "",
2862
+ checkpointReceipt,
2863
+ pendingNotice,
2864
+ ].filter(Boolean).join("\n\n");
2318
2865
  return { content: [{ type: "text", text }] };
2319
2866
  }
2320
2867
  // Surface WHAT was captured (not just the count) so the agent can verify the key facts survived
@@ -2327,10 +2874,9 @@ Details: ${m.details || "N/A"}`)
2327
2874
  ? [groupSync]
2328
2875
  : [];
2329
2876
  const sync = syncList.length === 1 ? syncList[0] : null;
2330
- const sharingGroup = isRecord(sharing?.group) ? sharing.group : {};
2331
- const availableGroups = Array.isArray(sharing?.availableGroups)
2332
- ? sharing.availableGroups.filter(isRecord)
2333
- : [];
2877
+ // The backend publishes to approved groups after its response; the receipt says so.
2878
+ const deferredSyncs = typeof groupSyncsDeferred === "number" ? groupSyncsDeferred : 0;
2879
+ const approvedGroupName = isRecord(sharing?.group) ? readString(sharing.group, "name") : null;
2334
2880
  const syncedGroupNames = syncList
2335
2881
  .filter((item) => item.synced === true)
2336
2882
  .map((item) => readString(item, "groupName"))
@@ -2343,10 +2889,9 @@ Details: ${m.details || "N/A"}`)
2343
2889
  ? [
2344
2890
  syncedGroupNames.length
2345
2891
  ? `Saved privately first and synced to approved groups: ${syncedGroupNames.join(", ")}.`
2346
- : "Saved to your private memory.",
2347
- GROUP_SESSION_SHARING_PROMPTS_ENABLED
2348
- ? `This user has multiple groups: ${availableGroups.map((group) => `${readString(group, "name") ?? "Unnamed group"} (${readString(group, "id") ?? "unknown id"})`).join(", ")}. Call request_group_session_sharing with this conversation scope and one groupId at a time to obtain a separate text confirmation question for each group.`
2349
- : "",
2892
+ : deferredSyncs > 0
2893
+ ? "Saved privately first; syncing to approved groups in the background."
2894
+ : "Saved to your private memory.",
2350
2895
  failedSyncs.length
2351
2896
  ? `${failedSyncs.length} approved group sync(s) failed; private memories were preserved.`
2352
2897
  : "",
@@ -2355,9 +2900,7 @@ Details: ${m.details || "N/A"}`)
2355
2900
  : "",
2356
2901
  ].filter(Boolean).join(" ")
2357
2902
  : sharing?.decision === null || sharing?.decision === undefined
2358
- ? GROUP_SESSION_SHARING_PROMPTS_ENABLED
2359
- ? `Saved to your private memory. Call request_group_session_sharing with this conversation scope${readString(sharingGroup, "id") ? ` and groupId ${readString(sharingGroup, "id")}` : ""}, relay its exact text question for ${readString(sharingGroup, "name") ?? "your current group"}, and call set_group_session_sharing only after an explicit Yes or No. Silence leaves the state unset.`
2360
- : "Saved to your private memory."
2903
+ ? "Saved to your private memory."
2361
2904
  : sharing.decision === "private"
2362
2905
  ? "Saved to your private memory."
2363
2906
  : syncedGroupNames.length
@@ -2367,7 +2910,9 @@ Details: ${m.details || "N/A"}`)
2367
2910
  ? `${protectedIds.length} protected memory item(s) stayed private.`
2368
2911
  : "",
2369
2912
  ].filter(Boolean).join(" ")
2370
- : `Saved to your private memory, but group sync failed${readString(failedSyncs[0] ?? sync ?? {}, "error") ? `: ${readString(failedSyncs[0] ?? sync ?? {}, "error")}` : "."}`;
2913
+ : deferredSyncs > 0
2914
+ ? `Saved to your private memory; syncing to ${approvedGroupName ?? "the approved group"} in the background.`
2915
+ : `Saved to your private memory, but group sync failed${readString(failedSyncs[0] ?? sync ?? {}, "error") ? `: ${readString(failedSyncs[0] ?? sync ?? {}, "error")}` : "."}`;
2371
2916
  const list = saved
2372
2917
  .map((m, idx) => {
2373
2918
  const keys = readString(m, "keys") ?? "(no key)";
@@ -2383,20 +2928,28 @@ Details: ${m.details || "N/A"}`)
2383
2928
  ].filter(Boolean).join("\n");
2384
2929
  })
2385
2930
  .join("\n\n");
2931
+ // Notch visibility is not evidence that this particular receipt was seen.
2932
+ // Always return real memory links for the chat's durable confirmation.
2386
2933
  const text = [
2387
2934
  `Successfully ingested conversation. Extracted ${memoriesExtracted} memory distinct events.`,
2388
2935
  receipt,
2936
+ checkpointReceipt,
2937
+ pendingNotice,
2389
2938
  GROUP_SESSION_SHARING_PROMPTS_ENABLED && typeof groupSharingScopeId === "string" && groupSharingScopeId
2390
2939
  ? `Conversation sharing scope: ${groupSharingScopeId}\nReuse this exact groupSharingScopeId only for request_group_session_sharing, set_group_session_sharing, and save_conversation calls in this conversation. Never reuse it in another conversation or save it as memory.`
2391
2940
  : "",
2392
2941
  typeof memoriesDiscarded === "number" && memoriesDiscarded > 0
2393
2942
  ? `${memoriesDiscarded} additional memories were not stored because your active-memory limit was reached.`
2394
2943
  : "",
2395
- list ? `EchoMem saved:\n\n${list}` : "",
2944
+ // A turn saved in this call ends with its own receipt block below: only that one is titled for the answer.
2945
+ list ? `${savedInTurn ? "Saved memories, for your check only:" : "EchoMem saved:"}\n\n${list}` : "",
2396
2946
  saved.length
2397
2947
  ? `Verify these captured the key facts. Re-fetch this exact batch later by searching the ids above${typeof contextId === "string" && contextId ? ` (context ${contextId})` : ""}.`
2398
2948
  : "",
2399
- saved.length ? SAVED_MEMORY_RECEIPT_INSTRUCTION : "",
2949
+ saved.length && !savedInTurn ? SAVED_MEMORY_RECEIPT_INSTRUCTION : "",
2950
+ saved.length && savedInTurn
2951
+ ? `This turn is saved; do not describe the save as queued or pending. End your answer with exactly this block, copied character for character. Do not shorten, translate, reword or reformat a title:\n\n${turnSaveResult({ success: true, extractedMemories: saved }, personalMemoryWebUrl).text}`
2952
+ : "",
2400
2953
  ].filter(Boolean).join("\n\n");
2401
2954
  return { content: [{ type: "text", text }] };
2402
2955
  }
@@ -2413,7 +2966,10 @@ Details: ${m.details || "N/A"}`)
2413
2966
  bound.created ? "Created and bound the source-session context." : "Source-session context is bound.",
2414
2967
  `Context: ${bound.contextId}`,
2415
2968
  `Source session: ${bound.canonicalKey}`,
2416
- "Later EchoMem saves, recalls, citations, sharing decisions, and activity from this bridge will use this context automatically.",
2969
+ // Claude Desktop runs one bridge for every conversation, so a binding there holds for one request.
2970
+ this.mcpClientName?.startsWith("local-agent-mode-")
2971
+ ? "This host shares one EchoMem bridge between conversations, so the binding covers this request only. Each later call must carry its own fresh sourceSessionBindingToken."
2972
+ : "Later EchoMem saves, recalls, citations, sharing decisions, and activity from this bridge will use this context automatically.",
2417
2973
  ].join("\n"),
2418
2974
  }],
2419
2975
  };
@@ -2516,24 +3072,14 @@ Details: ${m.details || "N/A"}`)
2516
3072
  };
2517
3073
  }
2518
3074
  if (result.requiresWorkspaceSelection === true) {
2519
- const workspaces = Array.isArray(result.availableWorkspaces)
2520
- ? result.availableWorkspaces.filter(isRecord)
2521
- : [];
2522
- const choices = workspaces.map((workspace) => {
2523
- const id = readString(workspace, "id") ?? "unknown";
2524
- const name = (readString(workspace, "name") ?? "Unnamed workspace")
2525
- .replace(/\s+/g, " ")
2526
- .trim();
2527
- return `- ${name} · ${id}`;
2528
- });
2529
3075
  return {
2530
3076
  content: [{
2531
3077
  type: "text",
2532
3078
  text: [
2533
- "Status: workspace_selection_required",
2534
- "This conversation is not assigned to exactly one workspace and the user belongs to multiple workspaces.",
2535
- "Ask the user which workspace this conversation belongs to, then repeat the review with that workspaceId.",
2536
- ...choices,
3079
+ "Status: review_skipped_no_workspace",
3080
+ "No unique workspace is established for this conversation, so routine ticket stewardship is skipped.",
3081
+ "Continue the user's primary task silently. Do not ask the user to choose a workspace, infer one, or retry this review just because a new message arrived.",
3082
+ "Only an explicit user request for workspace or ticket work should start workspace selection; for create/assign requests use operation=find_candidates and pass a known ticketId when available.",
2537
3083
  ].join("\n"),
2538
3084
  }],
2539
3085
  };
@@ -2700,6 +3246,9 @@ Details: ${m.details || "N/A"}`)
2700
3246
  type: "text",
2701
3247
  text: [
2702
3248
  workspaceId ? `Workspace: ${workspaceId}` : "",
3249
+ ...(parsed.ticketId ? [
3250
+ `Requested target ticket (workspace data): ${JSON.stringify(candidates.find(ticket => ticket.id === parsed.ticketId) ?? { id: parsed.ticketId, status: "not_in_snapshot" })}`,
3251
+ ] : []),
2703
3252
  ...formatTicketFilingPacket({
2704
3253
  candidates,
2705
3254
  activeAssignments,
@@ -2709,7 +3258,7 @@ Details: ${m.details || "N/A"}`)
2709
3258
  ...pendingLines,
2710
3259
  "",
2711
3260
  `Proposal snapshot to copy exactly: reviewedThroughAt=${reviewedThroughAt ?? "unavailable"}; expectedActiveTicketId=${snapshotTicketId ?? "null"}; expectedActiveTicketVersion=${snapshotTicketVersion ?? "null"}.`,
2712
- "This filing packet is discovery context, not a new review snapshot. No ticket or assignment changed.",
3261
+ "This packet includes the current review snapshot. Proceed directly to operation=propose using it; no separate operation=review is needed. No ticket or assignment changed.",
2713
3262
  ].filter(Boolean).join("\n"),
2714
3263
  }],
2715
3264
  };
@@ -2718,7 +3267,7 @@ Details: ${m.details || "N/A"}`)
2718
3267
  const parsed = recordWorkspaceTicketProposalSchema.parse(args ?? {});
2719
3268
  const result = await this.client.recordWorkspaceTicketProposal(parsed);
2720
3269
  if (!result) {
2721
- throw new Error("A verified source-session identity is required to record a ticket proposal. Do not guess or ask the user for a context ID.");
3270
+ throw new Error("Status: source_session_unavailable. A verified source-session identity is required to record a ticket proposal. Retry this exact operation once with a fresh random UUID in sourceSessionBindingToken so the bridge verifies this call in its local transcript. Never reuse a token or guess a context ID.");
2722
3271
  }
2723
3272
  const proposal = isRecord(result.proposal) ? result.proposal : {};
2724
3273
  const proposalId = readString(proposal, "proposalId");
@@ -2749,7 +3298,7 @@ Details: ${m.details || "N/A"}`)
2749
3298
  const parsed = acknowledgeWorkspaceTicketReviewSchema.parse(args ?? {});
2750
3299
  const result = await this.client.acknowledgeWorkspaceTicketReview(parsed);
2751
3300
  if (!result) {
2752
- throw new Error("A verified source-session identity is required to acknowledge a ticket review. Do not guess or ask the user for a context ID.");
3301
+ throw new Error("Status: source_session_unavailable. A verified source-session identity is required to acknowledge a ticket review. Retry this exact operation once with a fresh random UUID in sourceSessionBindingToken so the bridge verifies this call in its local transcript. Never reuse a token or guess a context ID.");
2753
3302
  }
2754
3303
  const acknowledgement = isRecord(result.acknowledgement) ? result.acknowledgement : {};
2755
3304
  const outcome = readString(acknowledgement, "outcome") ?? parsed.outcome;
@@ -2879,7 +3428,7 @@ Details: ${m.details || "N/A"}`)
2879
3428
  }
2880
3429
  const result = await this.client.applyWorkspaceTicketAction(parsed);
2881
3430
  if (!result) {
2882
- throw new Error("A verified source-session identity is required to apply a ticket action. Do not guess or ask the user for a context ID.");
3431
+ throw new Error("Status: source_session_unavailable. A verified source-session identity is required to apply a ticket action. Retry this exact operation once with a fresh random UUID in sourceSessionBindingToken so the bridge verifies this call in its local transcript. Never reuse a token or guess a context ID.");
2883
3432
  }
2884
3433
  const ticket = isRecord(result.ticket) ? result.ticket : {};
2885
3434
  const ticketId = readString(ticket, "id") ?? parsed.ticketId ?? "unknown";
@@ -2917,7 +3466,8 @@ Details: ${m.details || "N/A"}`)
2917
3466
  : parsed.action === "unassign_current"
2918
3467
  ? "Closed this session's active ticket interval. Past ticket activity remains visible; workspace sharing and published memory snapshots are unchanged."
2919
3468
  : "This action keeps the session bound to the returned ticket.",
2920
- "The session's memories remain owned by the canonical source session; ticket views use timestamped assignment history.",
3469
+ "Session binding completed. This action does not publish memories or enable future sharing.",
3470
+ "If the user also explicitly requested sharing, continue with prepare_group_publication(currentSession=true, ticketId) and show the publication preview before complete_group_publication. Otherwise stop here.",
2921
3471
  ].filter(Boolean).join("\n"),
2922
3472
  }],
2923
3473
  };
@@ -3615,6 +4165,8 @@ Details: ${m.details || "N/A"}`;
3615
4165
  `Prepared publication scan ${payload?.scanId} for ${payload?.group?.name ?? "your group"}.`,
3616
4166
  `Window: ${payload?.windowStart ?? "context start"} → ${payload?.windowEnd}`,
3617
4167
  `Candidates: ${candidates.length}. Nothing has been published.`,
4168
+ payload?.nextPage ? `More session memories remain. Continue prepare_group_publication with the same scope and ${JSON.stringify(payload.nextPage)} before claiming this covers the whole session. Keep each scanId with its own candidate IDs.` : "",
4169
+ parsed.currentSession ? "Scope: the verified current session. For a session bind-and-share request, preview existing eligible memories plus future sharing together unless the user narrowed the scope. One confirmation covers the stated binding and sharing choices. Omitting shareFuture preserves existing authorization." : "",
3618
4170
  `Current title: ${readString(participantProfile, "title") ?? "Not declared"}`,
3619
4171
  `Current declared responsibility: ${readString(participantProfile, "responsibilitySummary") ?? "Not provided"}`,
3620
4172
  "",
@@ -3701,6 +4253,7 @@ Details: ${m.details || "N/A"}`;
3701
4253
  `Newly published: ${published}.`,
3702
4254
  `Exact duplicates skipped: ${duplicates}.`,
3703
4255
  `Selected memory IDs: ${parsed.memoryIds.join(", ") || "(none)"}.`,
4256
+ payload?.futureSharingEnabled === true ? "Future eligible memories from this session will be shared with the same workspace. Flagged memories remain private." : "",
3704
4257
  "The scan cursor advanced; encrypted originals and global public settings were unchanged.",
3705
4258
  ].join("\n"),
3706
4259
  }],
@@ -3783,12 +4336,36 @@ Details: ${m.details || "N/A"}`;
3783
4336
  }
3784
4337
  async run() {
3785
4338
  const transport = new StdioServerTransport();
4339
+ // Claude Desktop's shared bridge is reached through a relay that carries only a call's input.
4340
+ this.server.oninitialized = () => {
4341
+ if (!this.server.getClientVersion()?.name?.startsWith("local-agent-mode-"))
4342
+ registerDirectBridge();
4343
+ };
3786
4344
  await this.server.connect(transport);
4345
+ this.client.resumeTurnEndSaves();
3787
4346
  this.events.record({ type: "session_start" });
3788
4347
  console.error("EchoMem MCP server running on stdio");
3789
4348
  }
3790
4349
  }
3791
4350
  async function main() {
4351
+ if (process.argv[2] === "source-snapshot") {
4352
+ try {
4353
+ const { exportSourceSnapshot } = await import("./source-snapshot-export.js");
4354
+ let input = "";
4355
+ for await (const chunk of process.stdin) {
4356
+ input += String(chunk);
4357
+ if (input.length > 32_000)
4358
+ throw new Error("SOURCE_SNAPSHOT_REQUEST_TOO_LARGE");
4359
+ }
4360
+ process.stdout.write(JSON.stringify(exportSourceSnapshot(JSON.parse(input))));
4361
+ }
4362
+ catch (error) {
4363
+ const message = error instanceof Error && /^[A-Z_]+$/.test(error.message) ? error.message : "SOURCE_SNAPSHOT_UNAVAILABLE";
4364
+ process.stdout.write(JSON.stringify({ success: false, error: message }));
4365
+ process.exitCode = 1;
4366
+ }
4367
+ return;
4368
+ }
3792
4369
  // Subcommands (setup/login/unlock/status/logout/help) run and exit; no subcommand → serve.
3793
4370
  const handled = await runCli(process.argv.slice(2));
3794
4371
  if (handled) {
@@ -3800,6 +4377,8 @@ async function main() {
3800
4377
  // Existing standalone users may receive a new runtime without re-running setup. Refresh only
3801
4378
  // EchoMem's marker-owned block so stale Desktop-era instructions disappear automatically.
3802
4379
  refreshInstalledMemoryGuidance();
4380
+ // Codex skills carry the same instructions, so refresh the ones setup already installed.
4381
+ refreshInstalledCodexSkills();
3803
4382
  // Lifecycle hooks go stale the same way, Desktop installs included: each keeps running the
3804
4383
  // runtime version that wrote it until something repoints it.
3805
4384
  refreshInstalledLifecycleHooks();