@echomem/mcp 1.4.71 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +34 -6
  2. package/dist/agent-messages-fallback.js +45 -0
  3. package/dist/backend-network-guard.js +48 -0
  4. package/dist/backend-policy.js +46 -0
  5. package/dist/claude-evidence.js +91 -0
  6. package/dist/codex-sync.js +2 -1
  7. package/dist/cowork-source.js +140 -0
  8. package/dist/desktop-presence.js +40 -0
  9. package/dist/desktop-save-activity.js +128 -0
  10. package/dist/durable-entry.js +20 -5
  11. package/dist/headless-runtime.js +4 -0
  12. package/dist/hud/cli.js +16 -17
  13. package/dist/hud/diagnostics.js +2 -1
  14. package/dist/hud/hooks.js +97 -62
  15. package/dist/hud/server.js +2 -1
  16. package/dist/index.js +727 -170
  17. package/dist/lifecycle-entry.js +29 -0
  18. package/dist/local-data-paths.js +15 -1
  19. package/dist/local-usage.js +72 -0
  20. package/dist/memory-intent.js +150 -0
  21. package/dist/memory-links.js +6 -0
  22. package/dist/migrate.js +2 -1
  23. package/dist/package-metadata.js +7 -7
  24. package/dist/pending-save.js +49 -0
  25. package/dist/save-local-trace.js +26 -0
  26. package/dist/save-note-store.js +50 -0
  27. package/dist/save-receipt-store.js +58 -0
  28. package/dist/save-receipt.js +42 -0
  29. package/dist/save-retry.js +43 -0
  30. package/dist/setup-page/client-extraction.js +2 -1
  31. package/dist/setup.js +13 -13
  32. package/dist/source-session-hook.js +16 -2
  33. package/dist/source-session-local.js +241 -0
  34. package/dist/source-session-pretool-hook.js +54 -0
  35. package/dist/source-session.js +4 -0
  36. package/dist/source-snapshot-export.js +68 -0
  37. package/dist/source-snapshot.js +99 -0
  38. package/dist/strict-ingest-contract.js +31 -0
  39. package/dist/strict-raw-session.js +473 -0
  40. package/dist/tool-map-cache.js +62 -0
  41. package/dist/turn-end-saves.js +104 -0
  42. package/dist/v1-contract.js +92 -45
  43. package/package.json +5 -3
  44. package/templates/codex-skills/echomem-save/SKILL.md +26 -27
  45. package/templates/echomem-recall.md +27 -21
  46. package/dist/save-checkpoint-hook.js +0 -122
package/dist/index.js CHANGED
@@ -1,11 +1,29 @@
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";
10
28
  import { requestFailureDetails } from "./request-failure.js";
11
29
  import { contextHealthMarkdown, recomposeCapsuleMarkdown } from "./hud/api.js";
@@ -20,7 +38,7 @@ import { checkLatestUpdateStatus, formatUpdateNotice, formatUpdateStatusText, st
20
38
  import { autoUpdateHeadlessRuntime } from "./headless-runtime.js";
21
39
  import { formatTicketFilingPacket, formatWorkspaceTicketOverview, ticketAddressById, } from "./ticket-review-format.js";
22
40
  import { SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE, resolveCloudCoworkSessionFromToolArguments, resolveSourceSessionRequestContext, resolveSourceSessionFromBindingToken, resolveSourceSessionFromBindingTokenWithRetry, } from "./source-session.js";
23
- const ECHO_API_BASE_URL = process.env.ECHO_API_BASE_URL || "https://echo-mem-chrome.vercel.app";
41
+ const ECHO_API_BASE_URL = resolveBackendURL();
24
42
  const ECHO_PRICING_URL = process.env.ECHO_PRICING_URL || "https://echoknows.com/dashboard/account";
25
43
  const ECHO_MEMORY_WEB_URL = (process.env.ECHO_MEMORY_WEB_URL || "https://echoknows.com/memory").replace(/\/$/, "");
26
44
  const DESKTOP_MANAGED = process.env.ECHO_DESKTOP_MANAGED === "1";
@@ -42,14 +60,6 @@ function memoryWebUrl(memoryId) {
42
60
  function personalMemoryWebUrl(memoryId) {
43
61
  return memoryWebUrl(memoryId);
44
62
  }
45
- function memoryMarkdownLink(url, keys, description) {
46
- const rawLabel = String(keys || description || "Open memory").replace(/\s+/g, " ").trim();
47
- const label = (rawLabel.length > 100 ? `${rawLabel.slice(0, 97).trim()}…` : rawLabel)
48
- .replace(/\\/g, "\\\\")
49
- .replace(/\[/g, "\\[")
50
- .replace(/\]/g, "\\]");
51
- return `[${label}](${url})`;
52
- }
53
63
  function withMemoryCitationInstruction(text) {
54
64
  return `${text}\n\n${MEMORY_CITATION_INSTRUCTION}`;
55
65
  }
@@ -59,6 +69,14 @@ class NoTokenError extends Error {
59
69
  /** Thrown when an encrypted account has no usable key — the model gets an unlock nudge, never ciphertext. */
60
70
  class LockedError extends Error {
61
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
+ }
62
80
  /** Thrown when the bridge cannot prove whether the account is encrypted. */
63
81
  class EncryptionStatusUnavailableError extends Error {
64
82
  }
@@ -273,11 +291,14 @@ function routePersonalRecallInvocation(canonicalName, args) {
273
291
  const hasKeywords = hasKeywordInput(normalizedArgs);
274
292
  const hasDateRangeInput = Boolean(readString(normalizedArgs, "startDate") || readString(normalizedArgs, "endDate"));
275
293
  const intentCount = Number(hasSemanticInput) + Number(hasKeywords) + Number(hasDateRangeInput);
276
- if (intentCount > 1) {
294
+ const semanticWithDateRange = hasSemanticInput && hasDateRangeInput && !hasKeywords
295
+ && Boolean(readString(normalizedArgs, "query"))
296
+ && readNumber(normalizedArgs, "timeFrameDays") === undefined;
297
+ if (intentCount > 1 && !semanticWithDateRange) {
277
298
  return {
278
299
  canonicalName,
279
300
  args: normalizedArgs,
280
- 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.",
281
302
  };
282
303
  }
283
304
  if (hasSemanticInput) {
@@ -422,6 +443,30 @@ function conversationAnalyticsFromMessages(value) {
422
443
  ...safeTextAnalytics("last_user_message", userMessages.at(-1)),
423
444
  };
424
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
+ }
425
470
  function lastUserMessageFromMessages(value) {
426
471
  if (!Array.isArray(value))
427
472
  return undefined;
@@ -467,23 +512,11 @@ function lastUserMessageFromConversationText(value) {
467
512
  flush();
468
513
  return lastUser || undefined;
469
514
  }
470
- function formatMessagesForIngest(messages) {
471
- return messages
472
- .map((message) => {
473
- const content = message.content.trim();
474
- if (!content)
475
- return "";
476
- const role = message.role.toLowerCase();
477
- const label = role === "user" || role === "human"
478
- ? "User"
479
- : role === "system"
480
- ? "System"
481
- : "Assistant";
482
- return `## ${label}\n\n${content}`;
483
- })
484
- .filter(Boolean)
485
- .join("\n\n---\n\n");
486
- }
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
+ ];
487
520
  function normalizeRetrievalCandidate(value, fallbackRank) {
488
521
  if (!isRecord(value))
489
522
  return null;
@@ -502,16 +535,22 @@ function normalizeRetrievalCandidate(value, fallbackRank) {
502
535
  isPublic: typeof value.is_public === "boolean" ? value.is_public : undefined,
503
536
  };
504
537
  }
505
- function withinTimeFrame(memory, candidate, timeFrameDays) {
506
- if (!timeFrameDays)
538
+ function withinTimeFrame(memory, candidate, timeFrameDays, startDate, endDate) {
539
+ if (!timeFrameDays && !startDate && !endDate)
507
540
  return true;
508
541
  const timestamp = readString(memory, "time") ?? readString(memory, "created_at") ?? candidate.time;
509
542
  if (!timestamp)
510
- return true;
543
+ return !startDate && !endDate;
511
544
  const ms = Date.parse(timestamp);
512
545
  if (!Number.isFinite(ms))
513
- return true;
514
- 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;
515
554
  }
516
555
  function numberArg(args, key) {
517
556
  return typeof args[key] === "number" && Number.isFinite(args[key]) ? args[key] : undefined;
@@ -741,7 +780,16 @@ class EchoMemApiClient {
741
780
  axios;
742
781
  activeToken;
743
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;
744
790
  boundSourceSession = null;
791
+ /** The connected app's MCP client name; decides whether an unbound save may fall back. */
792
+ hostClientName;
745
793
  requestContext = new AsyncLocalStorage();
746
794
  sourceSessionsByCanonicalKey = new Map();
747
795
  whoamiCache = null;
@@ -751,9 +799,11 @@ class EchoMemApiClient {
751
799
  deleteConfirmations = new Map();
752
800
  constructor(store) {
753
801
  this.store = store;
802
+ this.pendingSaves = new PendingSaves();
754
803
  this.activeToken = store.getToken();
755
804
  this.axios = axios.create({
756
805
  baseURL: ECHO_API_BASE_URL.replace(/\/$/, ""),
806
+ ...(readBackendPolicy() ? { maxRedirects: 0 } : {}),
757
807
  timeout: API_REQUEST_TIMEOUT_MS,
758
808
  headers: {
759
809
  "Content-Type": "application/json",
@@ -763,6 +813,7 @@ class EchoMemApiClient {
763
813
  // Read the token fresh on EVERY request (not baked in at construction) so a `login` that runs
764
814
  // after the editor already launched the bridge is picked up on the next call — no restart.
765
815
  this.axios.interceptors.request.use((config) => {
816
+ assertBackendURL(new URL(config.url ?? "", config.baseURL).href);
766
817
  const token = this.synchronizeAccountContext();
767
818
  if (token)
768
819
  config.headers.set("Authorization", `Bearer ${token}`);
@@ -789,6 +840,7 @@ class EchoMemApiClient {
789
840
  this.boundSourceSession = null;
790
841
  this.sourceSessionsByCanonicalKey.clear();
791
842
  this.deleteConfirmations.clear();
843
+ this.turnEndOutcomes.clear();
792
844
  return token;
793
845
  }
794
846
  /** Lets the MCP server invalidate its account-scoped tool-description caches too. */
@@ -800,6 +852,19 @@ class EchoMemApiClient {
800
852
  hasToken() {
801
853
  return !!this.synchronizeAccountContext();
802
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
+ }
803
868
  /** The per-process session id — the join key telemetry shares with grouped saves. */
804
869
  getSessionId() {
805
870
  return this.sessionId;
@@ -943,6 +1008,7 @@ class EchoMemApiClient {
943
1008
  workspaceId: parsed.workspaceId,
944
1009
  groupId: parsed.groupId,
945
1010
  memoryThreshold: parsed.memoryThreshold,
1011
+ ticketId: parsed.ticketId,
946
1012
  },
947
1013
  timeout: TICKET_REVIEW_TIMEOUT_MS,
948
1014
  });
@@ -1034,12 +1100,22 @@ class EchoMemApiClient {
1034
1100
  * Best-effort: returns undefined on any failure (locked vault, network) rather than blocking tools.
1035
1101
  */
1036
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() {
1037
1111
  try {
1112
+ const token = this.store.getToken();
1038
1113
  const enc = await this.encState(); // unencrypted → {enabled:false}; encrypted+locked → throws
1039
1114
  // Tool-list decoration is not a user-initiated search and must not spend
1040
1115
  // one of the account's weekly searches. Build the best-effort map from
1041
1116
  // the ordinary paginated memory listing instead.
1042
- 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 });
1043
1119
  const data = enc.enabled ? await this.decryptResult(response.data, enc.key) : response.data;
1044
1120
  const memories = Array.isArray(data?.data)
1045
1121
  ? data.data
@@ -1049,7 +1125,11 @@ class EchoMemApiClient {
1049
1125
  const keys = [...new Set(memories.map((m) => String(m?.keys || "").trim()).filter(Boolean))];
1050
1126
  if (!keys.length)
1051
1127
  return undefined;
1052
- 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;
1053
1133
  }
1054
1134
  catch {
1055
1135
  return undefined;
@@ -1061,9 +1141,22 @@ class EchoMemApiClient {
1061
1141
  * local vault is locked — unlike `fetchMemoryMap`, it never needs a decryption key.
1062
1142
  */
1063
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() {
1064
1152
  try {
1153
+ const token = this.store.getToken();
1154
+ const vaultKey = this.store.getKey();
1065
1155
  const response = await this.axios.get("/api/extension/social/groups/current", { timeout: 6000 });
1066
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
+ }
1067
1160
  return map || undefined;
1068
1161
  }
1069
1162
  catch {
@@ -1071,6 +1164,41 @@ class EchoMemApiClient {
1071
1164
  }
1072
1165
  }
1073
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
+ }
1074
1202
  async getEncryptionConfig() {
1075
1203
  const generation = this.refreshAccountContext();
1076
1204
  if (!this.encConfigPromise) {
@@ -1166,8 +1294,18 @@ class EchoMemApiClient {
1166
1294
  logicalRequestId: opts.requestId,
1167
1295
  sessionId: this.sessionId,
1168
1296
  userTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
1297
+ ...(opts.startDate ? { startDate: opts.startDate, endDate: opts.endDate } : {}),
1169
1298
  ...(opts.workspaceId ? { workspaceId: opts.workspaceId } : {}),
1170
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
+ }),
1171
1309
  });
1172
1310
  trace?.({ requestId: opts.requestId, endpoint, httpStatus: response.status });
1173
1311
  }
@@ -1203,15 +1341,29 @@ class EchoMemApiClient {
1203
1341
  seen.add(candidate.id);
1204
1342
  return true;
1205
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
+ })();
1206
1358
  const memories = [];
1207
- for (const candidate of dedupedCandidates) {
1208
- if (opts.workspaceId) {
1359
+ if (opts.workspaceId) {
1360
+ for (const candidate of orderedCandidates) {
1209
1361
  const raw = rawCandidates.find((value) => {
1210
1362
  if (!isRecord(value))
1211
1363
  return false;
1212
1364
  return (readString(value, "memory_id") ?? readString(value, "id")) === candidate.id;
1213
1365
  });
1214
- if (!isRecord(raw) || !withinTimeFrame(raw, candidate, opts.timeFrameDays))
1366
+ if (!isRecord(raw) || !withinTimeFrame(raw, candidate, opts.timeFrameDays, opts.startDate, opts.endDate))
1215
1367
  continue;
1216
1368
  const key = readString(raw, "key") ?? readString(raw, "keys") ?? candidate.key ?? "";
1217
1369
  memories.push({
@@ -1232,31 +1384,68 @@ class EchoMemApiClient {
1232
1384
  });
1233
1385
  if (memories.length >= opts.limit)
1234
1386
  break;
1235
- continue;
1236
1387
  }
1388
+ }
1389
+ else {
1237
1390
  if (!enc)
1238
1391
  throw new Error("Personal memory search requires encryption state");
1239
- const row = await this.fetchMemoryById(candidate.id, enc);
1240
- if (!row || !withinTimeFrame(row, candidate, opts.timeFrameDays))
1241
- continue;
1242
- const key = readString(row, "key") ?? readString(row, "keys") ?? candidate.key ?? "";
1243
- const memory = {
1244
- ...row,
1245
- id: readString(row, "id") ?? candidate.id,
1246
- key,
1247
- keys: readString(row, "keys") ?? key,
1248
- retrieval_bucket: candidate.bucket,
1249
- retrieval_rank: candidate.rank,
1250
- 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);
1251
1415
  };
1252
- if (candidate.score !== undefined) {
1253
- memory.similarity = candidate.score;
1254
- memory.similarity_score = candidate.score;
1255
- 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
+ }
1256
1448
  }
1257
- memories.push(memory);
1258
- if (memories.length >= opts.limit)
1259
- break;
1260
1449
  }
1261
1450
  return {
1262
1451
  success: true,
@@ -1306,6 +1495,8 @@ class EchoMemApiClient {
1306
1495
  limit,
1307
1496
  threshold,
1308
1497
  timeFrameDays: parsed.timeFrameDays,
1498
+ startDate: parsed.startDate,
1499
+ endDate: parsed.endDate,
1309
1500
  requestId: randomUUID(),
1310
1501
  workspaceId,
1311
1502
  recordAccess: parsed.recordAccess,
@@ -1324,26 +1515,117 @@ class EchoMemApiClient {
1324
1515
  }
1325
1516
  return data;
1326
1517
  }
1327
- 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) {
1328
1538
  if (this.isSubagentRequest()) {
1329
1539
  throw new Error(SUBAGENT_DURABLE_WRITE_MESSAGE);
1330
1540
  }
1331
1541
  const parsed = saveConversationSchema.parse(args ?? {});
1332
1542
  const groupSharingScopeId = parsed.groupSharingScopeId ?? randomUUID();
1333
- let rawData = parsed.conversation?.trim() || "";
1334
- if (!rawData && parsed.messages?.length) {
1335
- rawData = formatMessagesForIngest(parsed.messages);
1336
- }
1337
- if (!rawData) {
1338
- 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));
1339
1562
  }
1340
- if (parsed.tags?.length) {
1341
- 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;
1342
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;
1343
1626
  // For an encrypted account, hand the server the key transiently in the X-Encryption-Key header
1344
1627
  // so it encrypts at rest (mirrors the extension's write path, spec §3.1a). Locked → LockedError.
1345
1628
  const enc = await this.encState();
1346
- const boundSourceSession = this.getBoundSourceSession();
1347
1629
  const config = {
1348
1630
  headers: {
1349
1631
  "X-EchoMem-Request-Id": randomUUID(),
@@ -1351,41 +1633,207 @@ class EchoMemApiClient {
1351
1633
  // session can reach it through remote-devices, but its provisional
1352
1634
  // identity evidence does not change the bridge's transport channel.
1353
1635
  "X-EchoMem-Origin-Channel": "local_mcp",
1636
+ ...(boundSourceSession?.contextId ? { "X-EchoMem-Context-Id": boundSourceSession.contextId } : {}),
1354
1637
  ...(enc.enabled && enc.key ? { "X-Encryption-Key": enc.key } : {}),
1355
1638
  },
1356
1639
  };
1357
- try {
1358
- const response = await this.axios.post("/api/extension/memories/ingest", {
1359
- rawData,
1360
- sourceUrl: parsed.url,
1361
- source: parsed.source || "mcp_server",
1362
- title: parsed.title,
1363
- // A source-session identity owns the memory context. Provisional Cloud Cowork identity
1364
- // is explicitly marked by its evidence. The independent opaque scope still
1365
- // governs group-sharing consent and never becomes the source-session identity.
1366
- conversationKey: boundSourceSession?.canonicalKey ?? groupSharingScopeId,
1367
- groupSharingScopeId,
1368
- passthrough: parsed.passthrough || false,
1369
- triggerMessage: parsed.triggerMessage ||
1370
- lastUserMessageFromMessages(parsed.messages) ||
1371
- lastUserMessageFromConversationText(parsed.conversation),
1372
- triggerMessageRole: parsed.triggerMessageRole || "user",
1373
- }, config);
1374
- return { ...response.data, groupSharingScopeId };
1375
- }
1376
- catch (error) {
1377
- if (axios.isAxiosError(error) && error.response?.status === 429) {
1378
- const data = error.response.data;
1379
- if (data?.error === "MEMORY_PROCESSING_QUOTA_EXCEEDED") {
1380
- const message = typeof data.message === "string"
1381
- ? data.message
1382
- : "Weekly memory-processing limit reached. This conversation was not saved.";
1383
- const upgrade = typeof data.upgradeUrl === "string" ? ` Upgrade: ${data.upgradeUrl}` : "";
1384
- 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;
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
+ }
1385
1689
  }
1690
+ return { ...response.data, groupSharingScopeId };
1386
1691
  }
1387
- 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 };
1388
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 };
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;
1389
1837
  }
1390
1838
  async deleteMemory(args) {
1391
1839
  const parsed = deleteMemorySchema.parse(args ?? {});
@@ -1601,6 +2049,24 @@ class EchoMemApiClient {
1601
2049
  }
1602
2050
  async prepareGroupPublication(args) {
1603
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
+ }
1604
2070
  const enc = await this.encState();
1605
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 });
1606
2072
  return response.data;
@@ -1669,6 +2135,7 @@ function capWait(pending) {
1669
2135
  ]);
1670
2136
  }
1671
2137
  class EchoMemMCPServer {
2138
+ store;
1672
2139
  server;
1673
2140
  client;
1674
2141
  accountGeneration = 0;
@@ -1683,6 +2150,7 @@ class EchoMemMCPServer {
1683
2150
  groupMapInjected = false;
1684
2151
  updateStatus;
1685
2152
  constructor(store) {
2153
+ this.store = store;
1686
2154
  this.server = new Server({
1687
2155
  name: "echomem-mcp",
1688
2156
  version: SERVER_VERSION,
@@ -1787,7 +2255,7 @@ class EchoMemMCPServer {
1787
2255
  this.mapInjected = !!map;
1788
2256
  this.groupMapInjected = !!groupMap;
1789
2257
  const updateNotice = DESKTOP_MANAGED ? undefined : formatUpdateNotice(this.updateStatus);
1790
- return { tools: listToolSpecs({ map, groupMap, updateNotice }) };
2258
+ return { tools: listToolSpecs({ map, groupMap, updateNotice, includeSaveMessages: clientNeedsSaveMessages(this.mcpClientName) }) };
1791
2259
  });
1792
2260
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
1793
2261
  this.refreshAccountContext();
@@ -1800,17 +2268,59 @@ class EchoMemMCPServer {
1800
2268
  const clientVersion = this.server.getClientVersion();
1801
2269
  this.mcpClientName = clientVersion?.name ?? this.mcpClientName;
1802
2270
  this.mcpClientVersion = clientVersion?.version ?? this.mcpClientVersion;
2271
+ this.client.hostClientName = this.mcpClientName;
1803
2272
  let sourceResolution = {
1804
2273
  sourceSession: null,
1805
2274
  isSubagent: false,
1806
2275
  lineageStatus: "unbound",
1807
2276
  };
1808
2277
  try {
1809
- 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
+ });
1810
2284
  }
1811
2285
  catch {
1812
2286
  // Malformed host metadata is not model input. Ignore it and retain the explicit fallback.
1813
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
+ }
1814
2324
  let provisionalCloudSession = null;
1815
2325
  try {
1816
2326
  provisionalCloudSession = resolveCloudCoworkSessionFromToolArguments(toolArgs);
@@ -1849,7 +2359,8 @@ class EchoMemMCPServer {
1849
2359
  }
1850
2360
  // A child request starts fail-closed. Resolved children bind to the originating root; unresolved
1851
2361
  // children carry an explicit null so AsyncLocalStorage cannot fall through to a global binding.
1852
- let requestSourceSession = sourceResolution.isSubagent
2362
+ const sharedDesktopBridge = this.mcpClientName?.startsWith("local-agent-mode-") === true;
2363
+ let requestSourceSession = sourceResolution.isSubagent || sharedDesktopBridge
1853
2364
  ? null
1854
2365
  : this.client.getBoundSourceSession();
1855
2366
  // Verified request metadata always wins over a bridge-level compatibility fallback. The
@@ -1858,6 +2369,7 @@ class EchoMemMCPServer {
1858
2369
  if (sourceResolution.sourceSession && this.client.hasToken()) {
1859
2370
  requestSourceSession = await this.client.bindSourceSession(sourceResolution.sourceSession, false);
1860
2371
  }
2372
+ const receiptGeneration = this.client.refreshAccountContext();
1861
2373
  return this.client.withRequestContext({
1862
2374
  ...sourceResolution,
1863
2375
  sourceSession: requestSourceSession,
@@ -1960,26 +2472,8 @@ class EchoMemMCPServer {
1960
2472
  }],
1961
2473
  };
1962
2474
  }
1963
- // If logged in, persist the capsule via passthrough so it's retrievable by contextId.
1964
- if (this.client.hasToken()) {
1965
- try {
1966
- const saveResult = await this.client.saveConversation({
1967
- conversation: capsuleText,
1968
- title: "Session capsule (recompose)",
1969
- source: "mcp_recompose",
1970
- passthrough: true,
1971
- });
1972
- const ctxId = saveResult?.contextId;
1973
- const capId = saveResult?.capsuleId;
1974
- const persistLine = ctxId
1975
- ? `\n\n---\nCapsule persisted${capId ? ` (${capId})` : ""}. To reload in a fresh session:\nget_memories_by_context({ contextId: "${ctxId}" })`
1976
- : "";
1977
- return { content: [{ type: "text", text: capsuleText + persistLine }] };
1978
- }
1979
- catch {
1980
- // Persistence is best-effort; return the capsule text regardless.
1981
- }
1982
- }
2475
+ // Recompose is a local preview/export, never a memory-write shortcut.
2476
+ // Durable retention must use save_conversation's verified Gemini path.
1983
2477
  return { content: [{ type: "text", text: capsuleText }] };
1984
2478
  }
1985
2479
  if (!this.client.hasToken())
@@ -2150,6 +2644,7 @@ class EchoMemMCPServer {
2150
2644
  rec.ok = rec.error_kind === "none";
2151
2645
  rec.latency_ms = Date.now() - t0;
2152
2646
  this.events.record(rec);
2647
+ recordLocalUsage({ action: canonicalName, source: this.getMcpClientAnalytics().host_platform, outcome: rec.ok ? "success" : "failure", duration_ms: rec.latency_ms });
2153
2648
  if (canonicalName !== canonicalToolNames.updateStatus &&
2154
2649
  canonicalName !== canonicalToolNames.contextHealth &&
2155
2650
  canonicalName !== canonicalToolNames.recompose &&
@@ -2178,6 +2673,11 @@ class EchoMemMCPServer {
2178
2673
  void this.client.trackMcpAnalyticsEvent(toolEventName(canonicalName, rec.ok ? "Succeeded" : "Failed"), finalAnalytics, `${analyticsCallId}:completed`);
2179
2674
  }
2180
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;
2181
2681
  });
2182
2682
  });
2183
2683
  }
@@ -2315,26 +2815,53 @@ Details: ${m.details || "N/A"}`)
2315
2815
  rec.conversation_chars = text.length;
2316
2816
  rec.save_source = typeof a?.source === "string" ? a.source : sourceFallback;
2317
2817
  }
2318
- 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);
2319
2819
  if (!success)
2320
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.");
2321
2823
  if (rec)
2322
2824
  rec.memories_extracted = typeof memoriesExtracted === "number" ? memoriesExtracted : undefined;
2323
- // Passthrough saves store the capsule verbatim — no extraction, no embeddings.
2324
- 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) : [];
2325
2853
  const text = [
2326
- `Session capsule saved (passthrough, no extraction).`,
2327
- typeof capsuleId === "string" && capsuleId ? `Capsule ID: ${capsuleId}` : "",
2328
- typeof capsuleId === "string" && capsuleId
2329
- ? `Open saved capsule: ${memoryMarkdownLink(personalMemoryWebUrl(capsuleId), "Session capsule")}`
2330
- : "",
2331
- typeof contextId === "string" && contextId ? `Context: ${contextId}` : "",
2332
- typeof groupSharingScopeId === "string" && groupSharingScopeId
2333
- ? `Conversation sharing scope: ${groupSharingScopeId}`
2334
- : "",
2335
- "",
2336
- `To reload this capsule in a fresh session: get_memories_by_context({ contextId: "${contextId}" })`,
2337
- ].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");
2338
2865
  return { content: [{ type: "text", text }] };
2339
2866
  }
2340
2867
  // Surface WHAT was captured (not just the count) so the agent can verify the key facts survived
@@ -2347,10 +2874,9 @@ Details: ${m.details || "N/A"}`)
2347
2874
  ? [groupSync]
2348
2875
  : [];
2349
2876
  const sync = syncList.length === 1 ? syncList[0] : null;
2350
- const sharingGroup = isRecord(sharing?.group) ? sharing.group : {};
2351
- const availableGroups = Array.isArray(sharing?.availableGroups)
2352
- ? sharing.availableGroups.filter(isRecord)
2353
- : [];
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;
2354
2880
  const syncedGroupNames = syncList
2355
2881
  .filter((item) => item.synced === true)
2356
2882
  .map((item) => readString(item, "groupName"))
@@ -2363,10 +2889,9 @@ Details: ${m.details || "N/A"}`)
2363
2889
  ? [
2364
2890
  syncedGroupNames.length
2365
2891
  ? `Saved privately first and synced to approved groups: ${syncedGroupNames.join(", ")}.`
2366
- : "Saved to your private memory.",
2367
- GROUP_SESSION_SHARING_PROMPTS_ENABLED
2368
- ? `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.`
2369
- : "",
2892
+ : deferredSyncs > 0
2893
+ ? "Saved privately first; syncing to approved groups in the background."
2894
+ : "Saved to your private memory.",
2370
2895
  failedSyncs.length
2371
2896
  ? `${failedSyncs.length} approved group sync(s) failed; private memories were preserved.`
2372
2897
  : "",
@@ -2375,9 +2900,7 @@ Details: ${m.details || "N/A"}`)
2375
2900
  : "",
2376
2901
  ].filter(Boolean).join(" ")
2377
2902
  : sharing?.decision === null || sharing?.decision === undefined
2378
- ? GROUP_SESSION_SHARING_PROMPTS_ENABLED
2379
- ? `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.`
2380
- : "Saved to your private memory."
2903
+ ? "Saved to your private memory."
2381
2904
  : sharing.decision === "private"
2382
2905
  ? "Saved to your private memory."
2383
2906
  : syncedGroupNames.length
@@ -2387,7 +2910,9 @@ Details: ${m.details || "N/A"}`)
2387
2910
  ? `${protectedIds.length} protected memory item(s) stayed private.`
2388
2911
  : "",
2389
2912
  ].filter(Boolean).join(" ")
2390
- : `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")}` : "."}`;
2391
2916
  const list = saved
2392
2917
  .map((m, idx) => {
2393
2918
  const keys = readString(m, "keys") ?? "(no key)";
@@ -2403,20 +2928,28 @@ Details: ${m.details || "N/A"}`)
2403
2928
  ].filter(Boolean).join("\n");
2404
2929
  })
2405
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.
2406
2933
  const text = [
2407
2934
  `Successfully ingested conversation. Extracted ${memoriesExtracted} memory distinct events.`,
2408
2935
  receipt,
2936
+ checkpointReceipt,
2937
+ pendingNotice,
2409
2938
  GROUP_SESSION_SHARING_PROMPTS_ENABLED && typeof groupSharingScopeId === "string" && groupSharingScopeId
2410
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.`
2411
2940
  : "",
2412
2941
  typeof memoriesDiscarded === "number" && memoriesDiscarded > 0
2413
2942
  ? `${memoriesDiscarded} additional memories were not stored because your active-memory limit was reached.`
2414
2943
  : "",
2415
- 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}` : "",
2416
2946
  saved.length
2417
2947
  ? `Verify these captured the key facts. Re-fetch this exact batch later by searching the ids above${typeof contextId === "string" && contextId ? ` (context ${contextId})` : ""}.`
2418
2948
  : "",
2419
- 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
+ : "",
2420
2953
  ].filter(Boolean).join("\n\n");
2421
2954
  return { content: [{ type: "text", text }] };
2422
2955
  }
@@ -2433,7 +2966,10 @@ Details: ${m.details || "N/A"}`)
2433
2966
  bound.created ? "Created and bound the source-session context." : "Source-session context is bound.",
2434
2967
  `Context: ${bound.contextId}`,
2435
2968
  `Source session: ${bound.canonicalKey}`,
2436
- "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.",
2437
2973
  ].join("\n"),
2438
2974
  }],
2439
2975
  };
@@ -2536,24 +3072,14 @@ Details: ${m.details || "N/A"}`)
2536
3072
  };
2537
3073
  }
2538
3074
  if (result.requiresWorkspaceSelection === true) {
2539
- const workspaces = Array.isArray(result.availableWorkspaces)
2540
- ? result.availableWorkspaces.filter(isRecord)
2541
- : [];
2542
- const choices = workspaces.map((workspace) => {
2543
- const id = readString(workspace, "id") ?? "unknown";
2544
- const name = (readString(workspace, "name") ?? "Unnamed workspace")
2545
- .replace(/\s+/g, " ")
2546
- .trim();
2547
- return `- ${name} · ${id}`;
2548
- });
2549
3075
  return {
2550
3076
  content: [{
2551
3077
  type: "text",
2552
3078
  text: [
2553
- "Status: workspace_selection_required",
2554
- "This conversation is not assigned to exactly one workspace and the user belongs to multiple workspaces.",
2555
- "Ask the user which workspace this conversation belongs to, then repeat the review with that workspaceId.",
2556
- ...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.",
2557
3083
  ].join("\n"),
2558
3084
  }],
2559
3085
  };
@@ -2720,6 +3246,9 @@ Details: ${m.details || "N/A"}`)
2720
3246
  type: "text",
2721
3247
  text: [
2722
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
+ ] : []),
2723
3252
  ...formatTicketFilingPacket({
2724
3253
  candidates,
2725
3254
  activeAssignments,
@@ -2729,7 +3258,7 @@ Details: ${m.details || "N/A"}`)
2729
3258
  ...pendingLines,
2730
3259
  "",
2731
3260
  `Proposal snapshot to copy exactly: reviewedThroughAt=${reviewedThroughAt ?? "unavailable"}; expectedActiveTicketId=${snapshotTicketId ?? "null"}; expectedActiveTicketVersion=${snapshotTicketVersion ?? "null"}.`,
2732
- "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.",
2733
3262
  ].filter(Boolean).join("\n"),
2734
3263
  }],
2735
3264
  };
@@ -2738,7 +3267,7 @@ Details: ${m.details || "N/A"}`)
2738
3267
  const parsed = recordWorkspaceTicketProposalSchema.parse(args ?? {});
2739
3268
  const result = await this.client.recordWorkspaceTicketProposal(parsed);
2740
3269
  if (!result) {
2741
- 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.");
2742
3271
  }
2743
3272
  const proposal = isRecord(result.proposal) ? result.proposal : {};
2744
3273
  const proposalId = readString(proposal, "proposalId");
@@ -2769,7 +3298,7 @@ Details: ${m.details || "N/A"}`)
2769
3298
  const parsed = acknowledgeWorkspaceTicketReviewSchema.parse(args ?? {});
2770
3299
  const result = await this.client.acknowledgeWorkspaceTicketReview(parsed);
2771
3300
  if (!result) {
2772
- 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.");
2773
3302
  }
2774
3303
  const acknowledgement = isRecord(result.acknowledgement) ? result.acknowledgement : {};
2775
3304
  const outcome = readString(acknowledgement, "outcome") ?? parsed.outcome;
@@ -2899,7 +3428,7 @@ Details: ${m.details || "N/A"}`)
2899
3428
  }
2900
3429
  const result = await this.client.applyWorkspaceTicketAction(parsed);
2901
3430
  if (!result) {
2902
- 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.");
2903
3432
  }
2904
3433
  const ticket = isRecord(result.ticket) ? result.ticket : {};
2905
3434
  const ticketId = readString(ticket, "id") ?? parsed.ticketId ?? "unknown";
@@ -2937,7 +3466,8 @@ Details: ${m.details || "N/A"}`)
2937
3466
  : parsed.action === "unassign_current"
2938
3467
  ? "Closed this session's active ticket interval. Past ticket activity remains visible; workspace sharing and published memory snapshots are unchanged."
2939
3468
  : "This action keeps the session bound to the returned ticket.",
2940
- "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.",
2941
3471
  ].filter(Boolean).join("\n"),
2942
3472
  }],
2943
3473
  };
@@ -3635,6 +4165,8 @@ Details: ${m.details || "N/A"}`;
3635
4165
  `Prepared publication scan ${payload?.scanId} for ${payload?.group?.name ?? "your group"}.`,
3636
4166
  `Window: ${payload?.windowStart ?? "context start"} → ${payload?.windowEnd}`,
3637
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." : "",
3638
4170
  `Current title: ${readString(participantProfile, "title") ?? "Not declared"}`,
3639
4171
  `Current declared responsibility: ${readString(participantProfile, "responsibilitySummary") ?? "Not provided"}`,
3640
4172
  "",
@@ -3721,6 +4253,7 @@ Details: ${m.details || "N/A"}`;
3721
4253
  `Newly published: ${published}.`,
3722
4254
  `Exact duplicates skipped: ${duplicates}.`,
3723
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." : "",
3724
4257
  "The scan cursor advanced; encrypted originals and global public settings were unchanged.",
3725
4258
  ].join("\n"),
3726
4259
  }],
@@ -3803,12 +4336,36 @@ Details: ${m.details || "N/A"}`;
3803
4336
  }
3804
4337
  async run() {
3805
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
+ };
3806
4344
  await this.server.connect(transport);
4345
+ this.client.resumeTurnEndSaves();
3807
4346
  this.events.record({ type: "session_start" });
3808
4347
  console.error("EchoMem MCP server running on stdio");
3809
4348
  }
3810
4349
  }
3811
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
+ }
3812
4369
  // Subcommands (setup/login/unlock/status/logout/help) run and exit; no subcommand → serve.
3813
4370
  const handled = await runCli(process.argv.slice(2));
3814
4371
  if (handled) {