@echomem/mcp 1.4.71 → 1.5.1

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/desktop-workspace.js +48 -0
  11. package/dist/durable-entry.js +20 -5
  12. package/dist/headless-runtime.js +4 -0
  13. package/dist/hud/cli.js +16 -17
  14. package/dist/hud/diagnostics.js +2 -1
  15. package/dist/hud/hooks.js +97 -62
  16. package/dist/hud/server.js +2 -1
  17. package/dist/index.js +814 -191
  18. package/dist/lifecycle-entry.js +29 -0
  19. package/dist/local-data-paths.js +15 -1
  20. package/dist/local-usage.js +72 -0
  21. package/dist/memory-intent.js +150 -0
  22. package/dist/memory-links.js +6 -0
  23. package/dist/migrate.js +2 -1
  24. package/dist/package-metadata.js +7 -7
  25. package/dist/pending-save.js +49 -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 +13 -13
  33. package/dist/source-session-hook.js +65 -4
  34. package/dist/source-session-local.js +366 -0
  35. package/dist/source-session-pretool-hook.js +65 -0
  36. package/dist/source-session.js +66 -27
  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 +554 -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 +26 -27
  46. package/templates/echomem-recall.md +27 -21
  47. package/dist/save-checkpoint-hook.js +0 -122
package/dist/index.js CHANGED
@@ -1,11 +1,30 @@
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 { chosenDesktopWorkspace } from "./desktop-workspace.js";
14
+ import { readStrictRawSessionState, SAVE_NOTE_SUFFIX, selectSaveEvidence } from "./strict-raw-session.js";
15
+ import { rememberSaveNote } from "./save-note-store.js";
16
+ import { isMemorySaveDeclined, userRequestText } from "./memory-intent.js";
17
+ import { claimAbandonedTurnEndSaves, credentialHash, finishTurnEndSave, registerTurnEndSave, whenTurnEnds } from "./turn-end-saves.js";
18
+ import { agentMessagesFallbackAllowed, keepRecentMessages } from "./agent-messages-fallback.js";
19
+ import { assertStrictIngestCapabilities, assertStrictIngestReceipt } from "./strict-ingest-contract.js";
20
+ import { PendingSaves } from "./pending-save.js";
21
+ import { withSaveRetry, saveFailureCode } from "./save-retry.js";
22
+ import { beginDesktopSaveActivity, desktopSaveOutcome } from "./desktop-save-activity.js";
23
+ import { completedSaveReceipt, turnSaveResult } from "./save-receipt.js";
24
+ import { enqueueSaveReceipt, takeSaveReceipts } from "./save-receipt-store.js";
25
+ import { startSaveLocalTrace } from "./save-local-trace.js";
26
+ import { readToolMapCache, writeToolMapCache } from "./tool-map-cache.js";
27
+ import { claimSourceSessionProofNonce, registerDirectBridge, registerRelayBridge, takeSourceSessionProof, takeSourceSessionProofForCall, verifySourceSessionProof, } from "./source-session-local.js";
9
28
  import { EventLogger, hashText } from "./events.js";
10
29
  import { requestFailureDetails } from "./request-failure.js";
11
30
  import { contextHealthMarkdown, recomposeCapsuleMarkdown } from "./hud/api.js";
@@ -20,7 +39,7 @@ import { checkLatestUpdateStatus, formatUpdateNotice, formatUpdateStatusText, st
20
39
  import { autoUpdateHeadlessRuntime } from "./headless-runtime.js";
21
40
  import { formatTicketFilingPacket, formatWorkspaceTicketOverview, ticketAddressById, } from "./ticket-review-format.js";
22
41
  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";
42
+ const ECHO_API_BASE_URL = resolveBackendURL();
24
43
  const ECHO_PRICING_URL = process.env.ECHO_PRICING_URL || "https://echoknows.com/dashboard/account";
25
44
  const ECHO_MEMORY_WEB_URL = (process.env.ECHO_MEMORY_WEB_URL || "https://echoknows.com/memory").replace(/\/$/, "");
26
45
  const DESKTOP_MANAGED = process.env.ECHO_DESKTOP_MANAGED === "1";
@@ -42,14 +61,6 @@ function memoryWebUrl(memoryId) {
42
61
  function personalMemoryWebUrl(memoryId) {
43
62
  return memoryWebUrl(memoryId);
44
63
  }
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
64
  function withMemoryCitationInstruction(text) {
54
65
  return `${text}\n\n${MEMORY_CITATION_INSTRUCTION}`;
55
66
  }
@@ -59,6 +70,16 @@ class NoTokenError extends Error {
59
70
  /** Thrown when an encrypted account has no usable key — the model gets an unlock nudge, never ciphertext. */
60
71
  class LockedError extends Error {
61
72
  }
73
+ /** The backend's refusal of a transcript it cannot line up with the session's earlier saves. */
74
+ const SOURCE_RECOVERY_REQUIRED = "PROCESSING_SOURCE_RECOVERY_REQUIRED";
75
+ /** A short code the desktop can name; never server text. */
76
+ function desktopFailureReason(error) {
77
+ if (error instanceof LockedError)
78
+ return "VAULT_LOCKED";
79
+ if (axios.isAxiosError(error) && error.response?.status === 429)
80
+ return "QUOTA_EXCEEDED";
81
+ return saveFailureCode(error);
82
+ }
62
83
  /** Thrown when the bridge cannot prove whether the account is encrypted. */
63
84
  class EncryptionStatusUnavailableError extends Error {
64
85
  }
@@ -273,11 +294,14 @@ function routePersonalRecallInvocation(canonicalName, args) {
273
294
  const hasKeywords = hasKeywordInput(normalizedArgs);
274
295
  const hasDateRangeInput = Boolean(readString(normalizedArgs, "startDate") || readString(normalizedArgs, "endDate"));
275
296
  const intentCount = Number(hasSemanticInput) + Number(hasKeywords) + Number(hasDateRangeInput);
276
- if (intentCount > 1) {
297
+ const semanticWithDateRange = hasSemanticInput && hasDateRangeInput && !hasKeywords
298
+ && Boolean(readString(normalizedArgs, "query"))
299
+ && readNumber(normalizedArgs, "timeFrameDays") === undefined;
300
+ if (intentCount > 1 && !semanticWithDateRange) {
277
301
  return {
278
302
  canonicalName,
279
303
  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.",
304
+ 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
305
  };
282
306
  }
283
307
  if (hasSemanticInput) {
@@ -422,6 +446,30 @@ function conversationAnalyticsFromMessages(value) {
422
446
  ...safeTextAnalytics("last_user_message", userMessages.at(-1)),
423
447
  };
424
448
  }
449
+ function formatMessagesForIngest(messages) {
450
+ return messages
451
+ .map((message) => {
452
+ const content = message.content.trim();
453
+ if (!content)
454
+ return "";
455
+ const label = isUserRole(message.role) ? "User" : message.role.toLowerCase() === "system" ? "System" : "Assistant";
456
+ return `## ${label}\n\n${content}`;
457
+ })
458
+ .filter(Boolean)
459
+ .join("\n\n---\n\n");
460
+ }
461
+ function throwIfProcessingQuotaExceeded(error) {
462
+ if (!axios.isAxiosError(error) || error.response?.status !== 429)
463
+ return;
464
+ const data = error.response.data;
465
+ if (data?.error !== "MEMORY_PROCESSING_QUOTA_EXCEEDED")
466
+ return;
467
+ const message = typeof data.message === "string"
468
+ ? data.message
469
+ : "Weekly memory-processing limit reached. This conversation was not saved.";
470
+ const upgrade = typeof data.upgradeUrl === "string" ? ` Upgrade: ${data.upgradeUrl}` : "";
471
+ throw new McpError(ErrorCode.InvalidRequest, `${message}${upgrade}`);
472
+ }
425
473
  function lastUserMessageFromMessages(value) {
426
474
  if (!Array.isArray(value))
427
475
  return undefined;
@@ -467,23 +515,11 @@ function lastUserMessageFromConversationText(value) {
467
515
  flush();
468
516
  return lastUser || undefined;
469
517
  }
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
- }
518
+ /** The memory columns GET /api/extension/memories/:id returns that a complete candidate also carries. */
519
+ const COMPLETE_MEMORY_ROW_FIELDS = [
520
+ "id", "user_id", "time", "location", "category", "object", "emotion", "description", "details", "created_at",
521
+ "updated_at", "type", "keys", "context_id", "is_public", "is_encrypted", "publication_attention_label",
522
+ ];
487
523
  function normalizeRetrievalCandidate(value, fallbackRank) {
488
524
  if (!isRecord(value))
489
525
  return null;
@@ -502,16 +538,22 @@ function normalizeRetrievalCandidate(value, fallbackRank) {
502
538
  isPublic: typeof value.is_public === "boolean" ? value.is_public : undefined,
503
539
  };
504
540
  }
505
- function withinTimeFrame(memory, candidate, timeFrameDays) {
506
- if (!timeFrameDays)
541
+ function withinTimeFrame(memory, candidate, timeFrameDays, startDate, endDate) {
542
+ if (!timeFrameDays && !startDate && !endDate)
507
543
  return true;
508
544
  const timestamp = readString(memory, "time") ?? readString(memory, "created_at") ?? candidate.time;
509
545
  if (!timestamp)
510
- return true;
546
+ return !startDate && !endDate;
511
547
  const ms = Date.parse(timestamp);
512
548
  if (!Number.isFinite(ms))
513
- return true;
514
- return ms >= Date.now() - timeFrameDays * 24 * 60 * 60 * 1000;
549
+ return !startDate && !endDate;
550
+ if (timeFrameDays && ms < Date.now() - timeFrameDays * 24 * 60 * 60 * 1000)
551
+ return false;
552
+ if (startDate && ms < Date.parse(startDate))
553
+ return false;
554
+ if (endDate && ms > Date.parse(endDate))
555
+ return false;
556
+ return true;
515
557
  }
516
558
  function numberArg(args, key) {
517
559
  return typeof args[key] === "number" && Number.isFinite(args[key]) ? args[key] : undefined;
@@ -741,19 +783,33 @@ class EchoMemApiClient {
741
783
  axios;
742
784
  activeToken;
743
785
  accountGeneration = 0;
786
+ pendingSaves;
787
+ /** Conversations with a save waiting for the host to finish the turn, and how the last one ended. */
788
+ turnEndWaits = new Set();
789
+ /** Turn-end saves made unnecessary because the turn was saved, with its receipt, before it ended. */
790
+ turnEndCancelled = new Set();
791
+ turnEndOutcomes = new Map();
792
+ strictCapability = null;
744
793
  boundSourceSession = null;
794
+ /** The connected app's MCP client name; decides whether an unbound save may fall back. */
795
+ hostClientName;
745
796
  requestContext = new AsyncLocalStorage();
746
797
  sourceSessionsByCanonicalKey = new Map();
747
798
  whoamiCache = null;
748
799
  /** One id per bridge process — groups all saves from this coding session under a single EchoMem context. */
749
800
  sessionId = randomUUID();
801
+ /** Contexts whose transcript the backend could not reconcile with what the session saved
802
+ * before; their saves use the agent's turns for as long as this bridge runs. */
803
+ unreconciledContexts = new Set();
750
804
  encConfigPromise = null;
751
805
  deleteConfirmations = new Map();
752
806
  constructor(store) {
753
807
  this.store = store;
808
+ this.pendingSaves = new PendingSaves();
754
809
  this.activeToken = store.getToken();
755
810
  this.axios = axios.create({
756
811
  baseURL: ECHO_API_BASE_URL.replace(/\/$/, ""),
812
+ ...(readBackendPolicy() ? { maxRedirects: 0 } : {}),
757
813
  timeout: API_REQUEST_TIMEOUT_MS,
758
814
  headers: {
759
815
  "Content-Type": "application/json",
@@ -763,6 +819,7 @@ class EchoMemApiClient {
763
819
  // Read the token fresh on EVERY request (not baked in at construction) so a `login` that runs
764
820
  // after the editor already launched the bridge is picked up on the next call — no restart.
765
821
  this.axios.interceptors.request.use((config) => {
822
+ assertBackendURL(new URL(config.url ?? "", config.baseURL).href);
766
823
  const token = this.synchronizeAccountContext();
767
824
  if (token)
768
825
  config.headers.set("Authorization", `Bearer ${token}`);
@@ -789,6 +846,7 @@ class EchoMemApiClient {
789
846
  this.boundSourceSession = null;
790
847
  this.sourceSessionsByCanonicalKey.clear();
791
848
  this.deleteConfirmations.clear();
849
+ this.turnEndOutcomes.clear();
792
850
  return token;
793
851
  }
794
852
  /** Lets the MCP server invalidate its account-scoped tool-description caches too. */
@@ -800,6 +858,19 @@ class EchoMemApiClient {
800
858
  hasToken() {
801
859
  return !!this.synchronizeAccountContext();
802
860
  }
861
+ /** Called after a successful tool response, never by another session/subagent.
862
+ * Consuming a receipt does not submit a save or move the extraction cursor. */
863
+ takeTurnEndOutcomes(session, generation) {
864
+ if (this.refreshAccountContext() !== generation || !session)
865
+ return null;
866
+ const token = this.store.getToken();
867
+ if (!token)
868
+ return null;
869
+ const receipts = takeSaveReceipts({ account: credentialHash(token), backend: ECHO_API_BASE_URL, session: session.canonicalKey });
870
+ receipts.push(...(this.turnEndOutcomes.get(session.contextId) ?? []));
871
+ this.turnEndOutcomes.delete(session.contextId);
872
+ return [...new Set(receipts)].join("\n\n") || null;
873
+ }
803
874
  /** The per-process session id — the join key telemetry shares with grouped saves. */
804
875
  getSessionId() {
805
876
  return this.sessionId;
@@ -823,14 +894,21 @@ class EchoMemApiClient {
823
894
  }
824
895
  async bindSourceSession(identity, persistForBridge = true) {
825
896
  this.synchronizeAccountContext();
897
+ const generation = this.accountGeneration;
826
898
  if (identity.evidence === SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE && persistForBridge) {
827
899
  throw new Error("A provisional Cloud Cowork identity cannot become shared bridge state");
828
900
  }
829
901
  const cached = this.sourceSessionsByCanonicalKey.get(identity.canonicalKey);
830
- if (cached) {
902
+ if (cached && JSON.stringify(cached.providerSessionAliases) === JSON.stringify(identity.providerSessionAliases)
903
+ && cached.evidence === identity.evidence) {
904
+ // Reuse the server binding, while this call retains its freshly verified source.
905
+ const current = { ...cached, ...identity,
906
+ transcript: identity.evidence === SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE ? undefined : identity.transcript,
907
+ contextId: cached.contextId,
908
+ canonicalKey: cached.canonicalKey, providerSessionId: cached.providerSessionId };
831
909
  if (persistForBridge)
832
- this.boundSourceSession = cached;
833
- return { ...cached, created: false };
910
+ this.boundSourceSession = current;
911
+ return { ...current, created: false };
834
912
  }
835
913
  const response = await this.axios.post("/api/extension/source-sessions/bind", {
836
914
  provider: identity.provider,
@@ -839,6 +917,9 @@ class EchoMemApiClient {
839
917
  evidence: identity.evidence,
840
918
  runtime_version: MCP_PACKAGE_VERSION,
841
919
  }, { headers: { "X-EchoMem-Origin-Channel": "local_mcp" } });
920
+ this.synchronizeAccountContext();
921
+ if (generation !== this.accountGeneration)
922
+ throw new Error("ACCOUNT_CHANGED_DURING_BIND: retry with the current account.");
842
923
  const contextId = readString(response.data, "contextId");
843
924
  const canonicalKey = readString(response.data, "canonicalKey");
844
925
  const provider = readString(response.data, "provider");
@@ -856,8 +937,9 @@ class EchoMemApiClient {
856
937
  canonicalKey,
857
938
  contextId,
858
939
  };
859
- this.sourceSessionsByCanonicalKey.set(identity.canonicalKey, bound);
860
- this.sourceSessionsByCanonicalKey.set(canonicalKey, bound);
940
+ const binding = { ...bound, transcript: undefined };
941
+ this.sourceSessionsByCanonicalKey.set(identity.canonicalKey, binding);
942
+ this.sourceSessionsByCanonicalKey.set(canonicalKey, binding);
861
943
  if (this.sourceSessionsByCanonicalKey.size > 64) {
862
944
  const oldestKey = this.sourceSessionsByCanonicalKey.keys().next().value;
863
945
  if (oldestKey)
@@ -894,6 +976,9 @@ class EchoMemApiClient {
894
976
  if (explicit)
895
977
  return explicit;
896
978
  const response = await this.axios.get("/api/extension/social/groups/current");
979
+ const chosen = chosenDesktopWorkspace(response.data);
980
+ if (chosen)
981
+ return chosen;
897
982
  const group = isRecord(response.data?.group) ? response.data.group : null;
898
983
  const id = group ? readString(group, "id") : undefined;
899
984
  if (!id) {
@@ -932,21 +1017,27 @@ class EchoMemApiClient {
932
1017
  });
933
1018
  return { workspaceId: id, data: response.data };
934
1019
  }
935
- async reviewWorkspaceTicketSession(args) {
1020
+ /** `notchTeam`: for a request the user made (filing, a publication preview),
1021
+ * the team chosen in the Notch answers when no workspace is established. A
1022
+ * routine review leaves it off and is skipped instead. */
1023
+ async reviewWorkspaceTicketSession(args, options = {}) {
936
1024
  const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
937
1025
  const sourceSession = this.getRequestSourceSession();
938
1026
  if (!sourceSession)
939
1027
  return null;
940
- const response = await this.axios.get("/api/extension/workspace-ticket-actions", {
1028
+ const review = (workspaceId) => this.axios.get("/api/extension/workspace-ticket-actions", {
941
1029
  params: {
942
1030
  contextId: sourceSession.contextId,
943
- workspaceId: parsed.workspaceId,
1031
+ workspaceId,
944
1032
  groupId: parsed.groupId,
945
1033
  memoryThreshold: parsed.memoryThreshold,
1034
+ ticketId: parsed.ticketId,
946
1035
  },
947
1036
  timeout: TICKET_REVIEW_TIMEOUT_MS,
948
1037
  });
949
- return response.data;
1038
+ const response = await review(parsed.workspaceId);
1039
+ const chosen = options.notchTeam ? chosenDesktopWorkspace(response.data) : undefined;
1040
+ return chosen ? (await review(chosen)).data : response.data;
950
1041
  }
951
1042
  async acknowledgeWorkspaceTicketReview(args) {
952
1043
  const parsed = acknowledgeWorkspaceTicketReviewSchema.parse(args ?? {});
@@ -1034,12 +1125,22 @@ class EchoMemApiClient {
1034
1125
  * Best-effort: returns undefined on any failure (locked vault, network) rather than blocking tools.
1035
1126
  */
1036
1127
  async fetchMemoryMap() {
1128
+ const cached = readToolMapCache("personal", this.store.getToken(), this.store.getKey());
1129
+ if (cached) {
1130
+ void this.refreshMemoryMapCache();
1131
+ return cached;
1132
+ }
1133
+ return this.refreshMemoryMapCache();
1134
+ }
1135
+ async refreshMemoryMapCache() {
1037
1136
  try {
1137
+ const token = this.store.getToken();
1038
1138
  const enc = await this.encState(); // unencrypted → {enabled:false}; encrypted+locked → throws
1039
1139
  // Tool-list decoration is not a user-initiated search and must not spend
1040
1140
  // one of the account's weekly searches. Build the best-effort map from
1041
1141
  // the ordinary paginated memory listing instead.
1042
- const response = await this.axios.get("/api/extension/memories?limit=200", { timeout: 6000 });
1142
+ // Only the keys are read, so the library-wide totals are not asked for.
1143
+ const response = await this.axios.get("/api/extension/memories?limit=200&summary=0", { timeout: 6000 });
1043
1144
  const data = enc.enabled ? await this.decryptResult(response.data, enc.key) : response.data;
1044
1145
  const memories = Array.isArray(data?.data)
1045
1146
  ? data.data
@@ -1049,7 +1150,11 @@ class EchoMemApiClient {
1049
1150
  const keys = [...new Set(memories.map((m) => String(m?.keys || "").trim()).filter(Boolean))];
1050
1151
  if (!keys.length)
1051
1152
  return undefined;
1052
- return keys.slice(0, 40).map((k) => `- ${k}`).join("\n");
1153
+ const map = keys.slice(0, 40).map((k) => `- ${k}`).join("\n");
1154
+ if (token === this.store.getToken()) {
1155
+ writeToolMapCache("personal", map, token, enc.enabled ? enc.key : this.store.getKey());
1156
+ }
1157
+ return map;
1053
1158
  }
1054
1159
  catch {
1055
1160
  return undefined;
@@ -1061,9 +1166,22 @@ class EchoMemApiClient {
1061
1166
  * local vault is locked — unlike `fetchMemoryMap`, it never needs a decryption key.
1062
1167
  */
1063
1168
  async fetchGroupMemoryMap() {
1169
+ const cached = readToolMapCache("group", this.store.getToken(), this.store.getKey());
1170
+ if (cached) {
1171
+ void this.refreshGroupMemoryMapCache();
1172
+ return cached;
1173
+ }
1174
+ return this.refreshGroupMemoryMapCache();
1175
+ }
1176
+ async refreshGroupMemoryMapCache() {
1064
1177
  try {
1178
+ const token = this.store.getToken();
1179
+ const vaultKey = this.store.getKey();
1065
1180
  const response = await this.axios.get("/api/extension/social/groups/current", { timeout: 6000 });
1066
1181
  const map = typeof response.data?.map === "string" ? response.data.map.trim() : "";
1182
+ if (map && token === this.store.getToken() && vaultKey === this.store.getKey()) {
1183
+ writeToolMapCache("group", map, token, vaultKey);
1184
+ }
1067
1185
  return map || undefined;
1068
1186
  }
1069
1187
  catch {
@@ -1071,6 +1189,41 @@ class EchoMemApiClient {
1071
1189
  }
1072
1190
  }
1073
1191
  /** Encryption config for the current account, cached only for the lifetime of its token. */
1192
+ /** The backend's capability document. Only a document that passes the contract check is
1193
+ * kept for the process and signed-in account; a failed fetch or an incompatible document
1194
+ * is dropped, so a backend restarted or replaced at the same URL is re-checked by the
1195
+ * next save instead of failing every save until this process restarts. A backend that
1196
+ * turns incompatible after a passing check fails the receipt check of the next save. */
1197
+ /** Resolves to how many memories one save may write under the verified contract. */
1198
+ async ensureStrictCapability(explicitBoundary) {
1199
+ const generation = this.refreshAccountContext();
1200
+ if (!this.strictCapability || this.strictCapability.generation !== generation) {
1201
+ const data = this.axios.get("/api/extension/memories/ingest", { maxRedirects: 0, timeout: 10_000 })
1202
+ .then(response => response.data)
1203
+ .catch(error => {
1204
+ if (this.strictCapability?.data === data)
1205
+ this.strictCapability = null; // allow retry next call
1206
+ throw error;
1207
+ });
1208
+ this.strictCapability = { generation, data };
1209
+ }
1210
+ const cached = this.strictCapability;
1211
+ let capability;
1212
+ try {
1213
+ capability = await cached.data;
1214
+ }
1215
+ catch {
1216
+ throw new Error("STRICT_INGEST_BACKEND_UNAVAILABLE: could not verify the backend's strict contract. No transcript was submitted.");
1217
+ }
1218
+ try {
1219
+ return assertStrictIngestCapabilities(capability, explicitBoundary);
1220
+ }
1221
+ catch (error) {
1222
+ if (this.strictCapability === cached)
1223
+ this.strictCapability = null; // re-check the backend next call
1224
+ throw error;
1225
+ }
1226
+ }
1074
1227
  async getEncryptionConfig() {
1075
1228
  const generation = this.refreshAccountContext();
1076
1229
  if (!this.encConfigPromise) {
@@ -1166,8 +1319,18 @@ class EchoMemApiClient {
1166
1319
  logicalRequestId: opts.requestId,
1167
1320
  sessionId: this.sessionId,
1168
1321
  userTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
1322
+ ...(opts.startDate ? { startDate: opts.startDate, endDate: opts.endDate } : {}),
1169
1323
  ...(opts.workspaceId ? { workspaceId: opts.workspaceId } : {}),
1170
1324
  ...(opts.workspaceId ? { recordAccess: opts.recordAccess !== false } : {}),
1325
+ // Personal recall: the host model wrote the query, so the backend retrieves those words
1326
+ // as they are, in score order, with this call's budget and recency filter. The slack
1327
+ // above `limit` covers rows the threshold or the duplicate collapse removes. Older
1328
+ // backends ignore these fields and keep their planned, time-ordered answer.
1329
+ ...(opts.workspaceId ? {} : {
1330
+ mode: "direct",
1331
+ k: Math.min(opts.limit + 10, 60),
1332
+ ...(opts.timeFrameDays ? { timeFrameDays: opts.timeFrameDays } : {}),
1333
+ }),
1171
1334
  });
1172
1335
  trace?.({ requestId: opts.requestId, endpoint, httpStatus: response.status });
1173
1336
  }
@@ -1203,15 +1366,29 @@ class EchoMemApiClient {
1203
1366
  seen.add(candidate.id);
1204
1367
  return true;
1205
1368
  });
1369
+ // The backend answers two angles on the question and returns the primary one
1370
+ // first. Its budget (12) outruns the usual limit (10), so reading the list in
1371
+ // order delivers the primary angle alone and drops the second one unread.
1372
+ // Hold part of the budget for it; whichever bucket runs short, the other fills
1373
+ // the rest, so a question with one good angle still returns `limit` memories.
1374
+ const orderedCandidates = (() => {
1375
+ const primary = dedupedCandidates.filter((candidate) => candidate.bucket === "primary");
1376
+ const inference = dedupedCandidates.filter((candidate) => candidate.bucket !== "primary");
1377
+ if (!inference.length || primary.length < opts.limit)
1378
+ return dedupedCandidates;
1379
+ const reserved = Math.min(inference.length, Math.max(1, Math.floor(opts.limit / 3)));
1380
+ const kept = opts.limit - reserved;
1381
+ return [...primary.slice(0, kept), ...inference.slice(0, reserved), ...primary.slice(kept), ...inference.slice(reserved)];
1382
+ })();
1206
1383
  const memories = [];
1207
- for (const candidate of dedupedCandidates) {
1208
- if (opts.workspaceId) {
1384
+ if (opts.workspaceId) {
1385
+ for (const candidate of orderedCandidates) {
1209
1386
  const raw = rawCandidates.find((value) => {
1210
1387
  if (!isRecord(value))
1211
1388
  return false;
1212
1389
  return (readString(value, "memory_id") ?? readString(value, "id")) === candidate.id;
1213
1390
  });
1214
- if (!isRecord(raw) || !withinTimeFrame(raw, candidate, opts.timeFrameDays))
1391
+ if (!isRecord(raw) || !withinTimeFrame(raw, candidate, opts.timeFrameDays, opts.startDate, opts.endDate))
1215
1392
  continue;
1216
1393
  const key = readString(raw, "key") ?? readString(raw, "keys") ?? candidate.key ?? "";
1217
1394
  memories.push({
@@ -1232,31 +1409,68 @@ class EchoMemApiClient {
1232
1409
  });
1233
1410
  if (memories.length >= opts.limit)
1234
1411
  break;
1235
- continue;
1236
1412
  }
1413
+ }
1414
+ else {
1237
1415
  if (!enc)
1238
1416
  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,
1417
+ // Hydrate a bounded batch in parallel, then consume it in candidate-rank order.
1418
+ // This avoids serial network/decryption latency without changing recall order
1419
+ // or fetching the entire candidate set when the requested limit is small.
1420
+ // A backend that marks a candidate `memory_row_complete` already sent the full
1421
+ // row (ciphertext included), so it is decrypted here instead of re-fetched: one
1422
+ // HTTP round trip per search instead of one per memory. Older backends still GET.
1423
+ const completeRows = new Map();
1424
+ for (const raw of rawCandidates) {
1425
+ if (!isRecord(raw) || raw.memory_row_complete !== true)
1426
+ continue;
1427
+ const id = readString(raw, "memory_id") ?? readString(raw, "id");
1428
+ if (id)
1429
+ completeRows.set(id, raw);
1430
+ }
1431
+ const hydrate = async (id) => {
1432
+ const raw = completeRows.get(id);
1433
+ if (!raw)
1434
+ return this.fetchMemoryById(id, enc);
1435
+ const row = {};
1436
+ for (const field of COMPLETE_MEMORY_ROW_FIELDS)
1437
+ if (field in raw)
1438
+ row[field] = raw[field];
1439
+ return (enc.enabled ? await decryptMemoryFields(row, enc.key) : row);
1251
1440
  };
1252
- if (candidate.score !== undefined) {
1253
- memory.similarity = candidate.score;
1254
- memory.similarity_score = candidate.score;
1255
- memory.retrieval_similarity_score = candidate.score;
1441
+ const hydrationBatchSize = Math.min(8, Math.max(1, opts.limit));
1442
+ // The same note saved twice (identical key and description) takes one slot, not two.
1443
+ const shownRows = new Set();
1444
+ for (let offset = 0; offset < orderedCandidates.length && memories.length < opts.limit; offset += hydrationBatchSize) {
1445
+ const batch = orderedCandidates.slice(offset, offset + hydrationBatchSize);
1446
+ const rows = await Promise.all(batch.map((candidate) => hydrate(candidate.id)));
1447
+ for (let index = 0; index < batch.length && memories.length < opts.limit; index++) {
1448
+ const candidate = batch[index];
1449
+ const row = rows[index];
1450
+ if (!row || !withinTimeFrame(row, candidate, opts.timeFrameDays, opts.startDate, opts.endDate))
1451
+ continue;
1452
+ const key = readString(row, "key") ?? readString(row, "keys") ?? candidate.key ?? "";
1453
+ const rowIdentity = `${key}\u0000${typeof row.description === "string" ? row.description : ""}`;
1454
+ if (shownRows.has(rowIdentity))
1455
+ continue;
1456
+ shownRows.add(rowIdentity);
1457
+ const memory = {
1458
+ ...row,
1459
+ id: readString(row, "id") ?? candidate.id,
1460
+ key,
1461
+ keys: readString(row, "keys") ?? key,
1462
+ retrieval_bucket: candidate.bucket,
1463
+ retrieval_rank: candidate.rank,
1464
+ is_public: typeof row.is_public === "boolean" ? row.is_public : candidate.isPublic,
1465
+ };
1466
+ if (candidate.score !== undefined) {
1467
+ memory.similarity = candidate.score;
1468
+ memory.similarity_score = candidate.score;
1469
+ memory.retrieval_similarity_score = candidate.score;
1470
+ }
1471
+ memories.push(memory);
1472
+ }
1256
1473
  }
1257
- memories.push(memory);
1258
- if (memories.length >= opts.limit)
1259
- break;
1260
1474
  }
1261
1475
  return {
1262
1476
  success: true,
@@ -1306,6 +1520,8 @@ class EchoMemApiClient {
1306
1520
  limit,
1307
1521
  threshold,
1308
1522
  timeFrameDays: parsed.timeFrameDays,
1523
+ startDate: parsed.startDate,
1524
+ endDate: parsed.endDate,
1309
1525
  requestId: randomUUID(),
1310
1526
  workspaceId,
1311
1527
  recordAccess: parsed.recordAccess,
@@ -1324,26 +1540,120 @@ class EchoMemApiClient {
1324
1540
  }
1325
1541
  return data;
1326
1542
  }
1327
- async saveConversation(args) {
1543
+ /** Reports each save that contacts the backend to Echo Desktop's notch: it
1544
+ * starts with the first request and ends with the receipt, a skip, or a failure. */
1545
+ async saveConversation(args, origin = "explicit", waitForCompletion = false) {
1546
+ const report = { origin, joined: true };
1547
+ try {
1548
+ const result = await this.saveConversationOnce(args, report, waitForCompletion);
1549
+ // A call that joined an identical in-flight save leaves the report to it.
1550
+ if (report.joined)
1551
+ report.activity?.discard();
1552
+ return result;
1553
+ }
1554
+ catch (error) {
1555
+ if (report.joined && report.queued)
1556
+ report.activity?.discard();
1557
+ else
1558
+ report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
1559
+ throw error;
1560
+ }
1561
+ }
1562
+ async saveConversationOnce(args, report, waitForCompletion) {
1328
1563
  if (this.isSubagentRequest()) {
1329
1564
  throw new Error(SUBAGENT_DURABLE_WRITE_MESSAGE);
1330
1565
  }
1331
1566
  const parsed = saveConversationSchema.parse(args ?? {});
1332
1567
  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.");
1568
+ const boundSourceSession = this.getBoundSourceSession();
1569
+ const receiptToken = this.store.getToken();
1570
+ // All triggers use verified source evidence and the same Gemini renderer.
1571
+ // Legacy flags are rejected, not used to downgrade after a provider/source error.
1572
+ if (parsed.passthrough === true) {
1573
+ 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.");
1574
+ }
1575
+ if (parsed.conversation !== undefined) {
1576
+ 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.");
1577
+ }
1578
+ if (boundSourceSession?.contextId && this.unreconciledContexts.has(boundSourceSession.contextId)) {
1579
+ return this.saveFromAgentMessages(parsed, { boundSourceSession, groupSharingScopeId, receiptToken, report, reason: SOURCE_RECOVERY_REQUIRED });
1580
+ }
1581
+ // A verified local transcript always wins; agent-supplied turns are used only by hosts
1582
+ // whose transcript this bridge cannot read (Cursor, Claude Desktop chat, Cloud Cowork).
1583
+ let rawSession;
1584
+ let turnOpen;
1585
+ let transcript;
1586
+ try {
1587
+ if (!boundSourceSession?.contextId)
1588
+ throw new Error("SOURCE_SESSION_REQUIRED");
1589
+ ({ rawData: rawSession, turnOpen, file: transcript } = readStrictRawSessionState(boundSourceSession, undefined, parsed.note));
1339
1590
  }
1340
- if (parsed.tags?.length) {
1341
- rawData = `Tags: ${parsed.tags.join(", ")}\n\n${rawData}`;
1591
+ catch (error) {
1592
+ const code = error instanceof Error ? error.message : "";
1593
+ if (agentMessagesFallbackAllowed(boundSourceSession, code, this.hostClientName)) {
1594
+ return this.saveFromAgentMessages(parsed, { boundSourceSession, groupSharingScopeId, receiptToken, report, reason: code });
1595
+ }
1596
+ if (code === "SOURCE_SESSION_REQUIRED") {
1597
+ // Same recovery the ticket tools offer: a request-scoped token found in this host's own
1598
+ // transcript turns this into a verified save in the session's real context.
1599
+ throw new McpError(ErrorCode.InvalidParams, [
1600
+ "SOURCE_SESSION_REQUIRED: EchoMem could not verify this host conversation, so no memory was written.",
1601
+ "Status: source_session_unavailable",
1602
+ "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.",
1603
+ "Never reuse that token, copy one from another conversation, or send a summary instead. If the retry also fails, report that nothing was saved.",
1604
+ ].join("\n"));
1605
+ }
1606
+ throw error;
1342
1607
  }
1608
+ // An open turn is saved now, from the note in this call, so the agent writes the receipt in
1609
+ // its own answer.
1610
+ const requested = !turnOpen ? { ...parsed, note: undefined } : parsed;
1611
+ let evidence = selectSaveEvidence(rawSession, requested, turnOpen);
1612
+ for (let waited = 0; !evidence && waited < 4_000 && turnOpen && requested.note?.trim(); waited += 200) {
1613
+ // The host writes this call a moment after the fact.
1614
+ await new Promise(resolve => setTimeout(resolve, 200));
1615
+ try {
1616
+ rawSession = readStrictRawSessionState(boundSourceSession, undefined, requested.note).rawData;
1617
+ }
1618
+ catch {
1619
+ continue;
1620
+ }
1621
+ evidence = selectSaveEvidence(rawSession, requested, turnOpen);
1622
+ }
1623
+ // A note placed at a scripted call is not in the host's own record. It is kept before the
1624
+ // save is made, so every later reading of this session shows it where it was saved.
1625
+ const noteBoundary = turnOpen ? evidence?.boundary.assistantMessageId : undefined;
1626
+ if (boundSourceSession.provider === "codex" && noteBoundary?.endsWith(SAVE_NOTE_SUFFIX) && requested.note?.trim()
1627
+ && !rememberSaveNote(boundSourceSession.providerSessionId, noteBoundary.slice(0, -SAVE_NOTE_SUFFIX.length), requested.note.trim())) {
1628
+ evidence = null;
1629
+ }
1630
+ const savedInTurn = Boolean(evidence && turnOpen && evidence.boundary.assistantMessageId?.endsWith(SAVE_NOTE_SUFFIX));
1631
+ if (!evidence && turnOpen) {
1632
+ // A save reads only finished turns. This one is still being written, so the call
1633
+ // registers the request and the bridge saves once the host has written the turn's end.
1634
+ this.saveAfterTurnEnds(boundSourceSession, transcript, {
1635
+ groupSharingScopeId, source: parsed.source, title: parsed.title, tags: parsed.tags, url: parsed.url,
1636
+ });
1637
+ return { success: true, memoriesExtracted: 0, extractedMemories: [], savesAfterTurnEnds: true,
1638
+ noteMissing: !parsed.note?.trim(),
1639
+ contextId: boundSourceSession.contextId, groupSharingScopeId };
1640
+ }
1641
+ // This turn is saved now with its receipt: a turn-end save an earlier call registered is not needed.
1642
+ if (savedInTurn && this.turnEndWaits.has(boundSourceSession.contextId))
1643
+ this.turnEndCancelled.add(boundSourceSession.contextId);
1644
+ if (!evidence) {
1645
+ return { success: true, memoriesExtracted: 0, extractedMemories: [], deferredUntilCompletion: true,
1646
+ contextId: boundSourceSession.contextId, groupSharingScopeId };
1647
+ }
1648
+ const { rawData, boundary } = evidence;
1649
+ report.activity = beginDesktopSaveActivity({ token: receiptToken, backend: ECHO_API_BASE_URL, origin: report.origin });
1650
+ // The backend's strict contract is verified before any source is sent, once per process
1651
+ // and signed-in account; every save's receipt re-checks it.
1652
+ const maxNewMemories = await this.ensureStrictCapability(Boolean(boundary.userMessageId));
1653
+ const completionId = boundary.assistantMessageId ?? boundary.userMessageId;
1343
1654
  // For an encrypted account, hand the server the key transiently in the X-Encryption-Key header
1344
1655
  // so it encrypts at rest (mirrors the extension's write path, spec §3.1a). Locked → LockedError.
1345
1656
  const enc = await this.encState();
1346
- const boundSourceSession = this.getBoundSourceSession();
1347
1657
  const config = {
1348
1658
  headers: {
1349
1659
  "X-EchoMem-Request-Id": randomUUID(),
@@ -1351,41 +1661,224 @@ class EchoMemApiClient {
1351
1661
  // session can reach it through remote-devices, but its provisional
1352
1662
  // identity evidence does not change the bridge's transport channel.
1353
1663
  "X-EchoMem-Origin-Channel": "local_mcp",
1664
+ ...(boundSourceSession?.contextId ? { "X-EchoMem-Context-Id": boundSourceSession.contextId } : {}),
1354
1665
  ...(enc.enabled && enc.key ? { "X-Encryption-Key": enc.key } : {}),
1355
1666
  },
1356
1667
  };
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}`);
1668
+ const generation = this.accountGeneration;
1669
+ const operationKey = hashText(JSON.stringify([generation, boundSourceSession.contextId, completionId, rawData]));
1670
+ report.queued = true;
1671
+ const result = await this.pendingSaves.run(operationKey, groupSharingScopeId, completionId, async () => {
1672
+ report.joined = false;
1673
+ const finishLocalTrace = startSaveLocalTrace({ endpoint: `${ECHO_API_BASE_URL}/api/extension/memories/ingest`, contextId: boundSourceSession?.contextId, rawData,
1674
+ ...(parsed.assistantMessageId ? { trigger: { kind: "assistant_message_end", assistantMessageId: parsed.assistantMessageId } } : {}) });
1675
+ const traceStarted = Date.now();
1676
+ try {
1677
+ const send = () => withSaveRetry(async () => {
1678
+ this.synchronizeAccountContext();
1679
+ if (generation !== this.accountGeneration)
1680
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: retry stopped because the signed-in account changed.");
1681
+ return this.axios.post("/api/extension/memories/ingest", {
1682
+ rawData,
1683
+ sourceUrl: parsed.url,
1684
+ source: parsed.source || "mcp_server",
1685
+ title: parsed.title,
1686
+ // A source-session identity owns the memory context. Provisional Cloud Cowork identity
1687
+ // is explicitly marked by its evidence. The independent opaque scope still
1688
+ // governs group-sharing consent and never becomes the source-session identity.
1689
+ conversationKey: boundSourceSession?.canonicalKey ?? groupSharingScopeId,
1690
+ groupSharingScopeId,
1691
+ strictIngest: true,
1692
+ debugTrace: Boolean(process.env.ECHOMEM_SAVE_TRACE_DIR),
1693
+ ...boundary,
1694
+ // A verified save never forwards agent-supplied turns, not even as the trigger preview.
1695
+ triggerMessage: parsed.triggerMessage || undefined,
1696
+ triggerMessageRole: parsed.triggerMessageRole || "user",
1697
+ }, { ...config, timeout: 300_000, maxRedirects: 0 });
1698
+ });
1699
+ const response = await send();
1700
+ try {
1701
+ assertStrictIngestReceipt(response.data, maxNewMemories);
1702
+ }
1703
+ catch (error) {
1704
+ // The backend no longer answers as the contract it showed: check it again before the next save.
1705
+ this.strictCapability = null;
1706
+ throw error;
1385
1707
  }
1708
+ finishLocalTrace({ response: response.data, state: "COMPLETED", elapsedMs: Date.now() - traceStarted });
1709
+ report.activity?.finish(desktopSaveOutcome(response.data));
1710
+ if (response.data?.success === true && response.data?.memoriesExtracted > 0) {
1711
+ // Keep the encrypted startup hint fresh for the next bridge process.
1712
+ // Refreshing is advisory and must not delay the save receipt.
1713
+ void this.refreshMemoryMapCache();
1714
+ if ((Array.isArray(response.data?.groupSyncs) && response.data.groupSyncs.length > 0) || (typeof response.data?.groupSyncsDeferred === "number" && response.data.groupSyncsDeferred > 0)) {
1715
+ void this.refreshGroupMemoryMapCache();
1716
+ }
1717
+ }
1718
+ return { ...response.data, groupSharingScopeId };
1386
1719
  }
1387
- throw error;
1720
+ catch (error) {
1721
+ finishLocalTrace({ state: "FAILED", elapsedMs: Date.now() - traceStarted,
1722
+ response: axios.isAxiosError(error) ? error.response?.data ?? { success: false, error: "TRANSPORT_ERROR" } : { success: false, error: "LOCAL_SAVE_ERROR" },
1723
+ httpStatus: axios.isAxiosError(error) ? error.response?.status : undefined });
1724
+ // The agent's turns are saved next, under their own activity.
1725
+ if (saveFailureCode(error) === SOURCE_RECOVERY_REQUIRED) {
1726
+ report.activity?.discard();
1727
+ throw error;
1728
+ }
1729
+ // A save that outlives the caller's wait still reports how it ended.
1730
+ report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
1731
+ throwIfProcessingQuotaExceeded(error);
1732
+ throw error;
1733
+ }
1734
+ }, waitForCompletion).catch(error => {
1735
+ if (saveFailureCode(error) !== SOURCE_RECOVERY_REQUIRED)
1736
+ throw error;
1737
+ // This session saved before from the agent's turns, on a bridge that could not read its
1738
+ // transcript, and the backend cannot line the transcript up with those memories. That holds
1739
+ // for the rest of the session, so it keeps saving the way it did, in the same context.
1740
+ this.unreconciledContexts.add(boundSourceSession.contextId);
1741
+ return null;
1742
+ });
1743
+ if (!result)
1744
+ return this.saveFromAgentMessages(parsed, { boundSourceSession, groupSharingScopeId, receiptToken, report, reason: SOURCE_RECOVERY_REQUIRED });
1745
+ this.synchronizeAccountContext();
1746
+ if (generation !== this.accountGeneration)
1747
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: the result was withheld because the signed-in account changed.");
1748
+ if ("pendingProcessing" in result && result.pendingProcessing) {
1749
+ return { ...result, assistantMessageId: boundary.assistantMessageId, userMessageId: boundary.userMessageId };
1388
1750
  }
1751
+ return { ...result, savedBoundary: boundary, savedInTurn };
1752
+ }
1753
+ /** One wait per conversation: when the host has written the end of the turn, run the same
1754
+ * save again in the caller's request context. Its result goes to Echo Desktop's notch and
1755
+ * to the next successful MCP tool call of this conversation. */
1756
+ saveAfterTurnEnds(session, transcript, args, context = this.requestContext.getStore() ?? { sourceSession: session, isSubagent: false, lineageStatus: "not_applicable" }) {
1757
+ const id = session.contextId;
1758
+ if (this.turnEndWaits.has(id))
1759
+ return;
1760
+ this.turnEndWaits.add(id);
1761
+ const generation = this.accountGeneration;
1762
+ const token = this.store.getToken();
1763
+ if (token)
1764
+ registerTurnEndSave({ v: 1, contextId: id, session, args, credentialHash: credentialHash(token), backend: ECHO_API_BASE_URL, registeredAt: Date.now() });
1765
+ whenTurnEnds(transcript, () => readStrictRawSessionState(session).turnOpen, () => {
1766
+ if (this.refreshAccountContext() !== generation || this.turnEndCancelled.delete(id)) {
1767
+ this.turnEndWaits.delete(id);
1768
+ finishTurnEndSave(id);
1769
+ return;
1770
+ }
1771
+ const enqueue = (receipt) => {
1772
+ if (this.refreshAccountContext() !== generation)
1773
+ return;
1774
+ if (token && enqueueSaveReceipt({ account: credentialHash(token), backend: ECHO_API_BASE_URL, session: session.canonicalKey }, receipt))
1775
+ return;
1776
+ const receipts = this.turnEndOutcomes.get(id) ?? [];
1777
+ receipts.push(receipt);
1778
+ this.turnEndOutcomes.set(id, receipts);
1779
+ };
1780
+ void this.withRequestContext(context, () => this.saveConversation(args, "auto", true)).then(result => {
1781
+ // The next EchoMem tool call carries the receipt.
1782
+ const receipt = completedSaveReceipt(result, personalMemoryWebUrl);
1783
+ if (receipt)
1784
+ enqueue(receipt);
1785
+ }, error => {
1786
+ enqueue(`The previous turn's save failed (${desktopFailureReason(error)}); no successful save was confirmed. Tell the user briefly; do not claim it was saved.`);
1787
+ }).finally(() => {
1788
+ this.turnEndWaits.delete(id);
1789
+ finishTurnEndSave(id);
1790
+ });
1791
+ });
1792
+ }
1793
+ /** Finish saves that an earlier bridge process registered and did not live to make. */
1794
+ resumeTurnEndSaves() {
1795
+ const token = this.store.getToken();
1796
+ if (!token)
1797
+ return;
1798
+ for (const entry of claimAbandonedTurnEndSaves(credentialHash(token), ECHO_API_BASE_URL)) {
1799
+ const session = entry.session;
1800
+ try {
1801
+ this.saveAfterTurnEnds(session, readStrictRawSessionState(session).file, entry.args, { sourceSession: session, isSubagent: false, lineageStatus: "not_applicable" });
1802
+ }
1803
+ catch {
1804
+ finishTurnEndSave(entry.contextId); // its transcript is gone
1805
+ }
1806
+ }
1807
+ }
1808
+ /** The save path for a host with no transcript this bridge can read: the agent supplies the
1809
+ * relevant turns verbatim, as before the strict bridge, and the backend extracts from them. */
1810
+ async saveFromAgentMessages(parsed, ctx) {
1811
+ // Over the safety cap, the most recent turns are kept rather than the save refused.
1812
+ const { kept: messages, omittedMessages, shortenedNewest } = keepRecentMessages(parsed.messages ?? []);
1813
+ // The same refusal a transcript save honours: the user's latest words decide.
1814
+ const latestRequest = [...messages].reverse().find(message => message.role === "user" && userRequestText(message.content));
1815
+ if (latestRequest && isMemorySaveDeclined(latestRequest.content))
1816
+ throw new Error("MEMORY_SAVE_DECLINED: the latest user request asks not to save; no source was submitted.");
1817
+ let rawData = messages.length ? formatMessagesForIngest(messages) : "";
1818
+ if (!rawData) {
1819
+ // Asking for the turns is a normal step for these hosts, not a failure: nothing was written.
1820
+ return { success: true, memoriesExtracted: 0, extractedMemories: [], messagesRequired: ctx.reason, groupSharingScopeId: ctx.groupSharingScopeId };
1821
+ }
1822
+ if (parsed.tags?.length)
1823
+ rawData = `Tags: ${parsed.tags.join(", ")}\n\n${rawData}`;
1824
+ const generation = this.accountGeneration;
1825
+ const conversationKey = ctx.boundSourceSession?.canonicalKey ?? ctx.groupSharingScopeId;
1826
+ ctx.report.activity = beginDesktopSaveActivity({ token: ctx.receiptToken, backend: ECHO_API_BASE_URL, origin: ctx.report.origin });
1827
+ ctx.report.queued = true;
1828
+ // Identical concurrent calls share one write, as verified saves do. An unbound call's key is a
1829
+ // fresh random scope unless the agent passed one, so it is left out of the identity here.
1830
+ const operationKey = hashText(JSON.stringify([generation, ctx.boundSourceSession?.canonicalKey ?? parsed.groupSharingScopeId ?? "unbound", rawData]));
1831
+ const result = await this.pendingSaves.run(operationKey, ctx.groupSharingScopeId, "agent-messages", async () => {
1832
+ ctx.report.joined = false;
1833
+ try {
1834
+ const enc = await this.encState();
1835
+ const response = await withSaveRetry(async () => {
1836
+ this.synchronizeAccountContext();
1837
+ if (generation !== this.accountGeneration)
1838
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: retry stopped because the signed-in account changed.");
1839
+ return this.axios.post("/api/extension/memories/ingest", {
1840
+ rawData,
1841
+ sourceUrl: parsed.url,
1842
+ source: parsed.source || "mcp_server",
1843
+ title: parsed.title,
1844
+ conversationKey,
1845
+ groupSharingScopeId: ctx.groupSharingScopeId,
1846
+ // Tells the backend this local save had no readable transcript; it then accepts the
1847
+ // agent's turns instead of requiring the strict verified-source contract.
1848
+ sourceEvidence: "agent_messages",
1849
+ triggerMessage: parsed.triggerMessage || lastUserMessageFromMessages(messages),
1850
+ triggerMessageRole: parsed.triggerMessageRole || "user",
1851
+ }, {
1852
+ headers: {
1853
+ "X-EchoMem-Request-Id": randomUUID(),
1854
+ "X-EchoMem-Origin-Channel": "local_mcp",
1855
+ ...(enc.enabled && enc.key ? { "X-Encryption-Key": enc.key } : {}),
1856
+ },
1857
+ timeout: 300_000,
1858
+ maxRedirects: 0,
1859
+ });
1860
+ });
1861
+ ctx.report.activity?.finish(desktopSaveOutcome(response.data));
1862
+ if (response.data?.success === true && response.data?.memoriesExtracted > 0) {
1863
+ void this.refreshMemoryMapCache();
1864
+ if ((Array.isArray(response.data?.groupSyncs) && response.data.groupSyncs.length > 0) || (typeof response.data?.groupSyncsDeferred === "number" && response.data.groupSyncsDeferred > 0)) {
1865
+ void this.refreshGroupMemoryMapCache();
1866
+ }
1867
+ }
1868
+ // With no source session, the scope was this save's conversation key: the receipt hands
1869
+ // it back so the agent's later saves land in the same context.
1870
+ return { ...response.data, groupSharingScopeId: ctx.groupSharingScopeId, scopeKeysConversation: !ctx.boundSourceSession };
1871
+ }
1872
+ catch (error) {
1873
+ ctx.report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
1874
+ throwIfProcessingQuotaExceeded(error);
1875
+ throw error;
1876
+ }
1877
+ });
1878
+ this.synchronizeAccountContext();
1879
+ if (generation !== this.accountGeneration)
1880
+ throw new Error("ACCOUNT_CHANGED_DURING_SAVE: the result was withheld because the signed-in account changed.");
1881
+ return omittedMessages || shortenedNewest ? { ...result, messagesTrimmed: { omittedMessages, shortenedNewest } } : result;
1389
1882
  }
1390
1883
  async deleteMemory(args) {
1391
1884
  const parsed = deleteMemorySchema.parse(args ?? {});
@@ -1500,7 +1993,7 @@ class EchoMemApiClient {
1500
1993
  async searchOthersMemories(args) {
1501
1994
  const parsed = othersSchema.parse(args ?? {});
1502
1995
  try {
1503
- const response = await this.axios.post("/api/extension/social/public-memories/search", {
1996
+ const search = (workspaceId) => this.axios.post("/api/extension/social/public-memories/search", {
1504
1997
  query: parsed.query,
1505
1998
  limit: parsed.limit,
1506
1999
  target: parsed.target,
@@ -1512,12 +2005,14 @@ class EchoMemApiClient {
1512
2005
  kPerUser: parsed.kPerUser,
1513
2006
  similarityThreshold: parsed.similarityThreshold,
1514
2007
  timeFrameDays: parsed.timeFrameDays,
1515
- workspaceId: parsed.workspaceId ?? parsed.groupId,
2008
+ workspaceId,
1516
2009
  scope: parsed.scope,
1517
2010
  requestId: this.sessionId,
1518
2011
  source: "mcp_friend_public_memory_search",
1519
2012
  });
1520
- return response.data;
2013
+ const response = await search(parsed.workspaceId ?? parsed.groupId);
2014
+ const chosen = chosenDesktopWorkspace(response.data);
2015
+ return chosen ? (await search(chosen)).data : response.data;
1521
2016
  }
1522
2017
  catch (error) {
1523
2018
  throw new Error(`search_others_memories failed against ${ECHO_API_BASE_URL}: ${describeError(error)}`);
@@ -1559,11 +2054,13 @@ class EchoMemApiClient {
1559
2054
  const parsed = groupContextSchema.parse(args ?? {});
1560
2055
  try {
1561
2056
  const workspaceId = parsed.workspaceId ?? parsed.groupId;
1562
- const path = workspaceId
1563
- ? `/api/extension/social/groups/current?workspaceId=${encodeURIComponent(workspaceId)}`
2057
+ const path = (id) => id
2058
+ ? `/api/extension/social/groups/current?workspaceId=${encodeURIComponent(id)}`
1564
2059
  : "/api/extension/social/groups/current";
1565
- const response = await this.axios.get(path);
1566
- return response.data;
2060
+ const response = await this.axios.get(path(workspaceId));
2061
+ // Several workspaces and none named: the team chosen in the Notch answers.
2062
+ const chosen = chosenDesktopWorkspace(response.data);
2063
+ return chosen ? (await this.axios.get(path(chosen))).data : response.data;
1567
2064
  }
1568
2065
  catch (error) {
1569
2066
  throw new Error(`get_group_context failed against ${ECHO_API_BASE_URL}: ${describeError(error)}`);
@@ -1601,6 +2098,24 @@ class EchoMemApiClient {
1601
2098
  }
1602
2099
  async prepareGroupPublication(args) {
1603
2100
  const parsed = prepareGroupPublicationSchema.parse(args ?? {});
2101
+ if (parsed.currentSession) {
2102
+ const sourceSession = this.getRequestSourceSession();
2103
+ if (!sourceSession) {
2104
+ throw new Error("source_session_unavailable: retry with a fresh sourceSessionBindingToken to verify this conversation before preparing its publication.");
2105
+ }
2106
+ if (parsed.contextId && parsed.contextId !== sourceSession.contextId) {
2107
+ throw new Error("currentSession cannot be combined with a different contextId.");
2108
+ }
2109
+ // The preview's limit counts memories; the review's own limit counts tickets and is smaller.
2110
+ const result = await this.reviewWorkspaceTicketSession({ ...parsed, limit: undefined }, { notchTeam: true });
2111
+ const review = isRecord(result?.review) ? result.review : {};
2112
+ const workspaceId = readString(review, "workspaceId");
2113
+ if (!workspaceId)
2114
+ throw new Error("workspace_selection_required: specify the destination workspaceId or ticketId for this session's publication preview.");
2115
+ parsed.contextId = sourceSession.contextId;
2116
+ parsed.scope = "context";
2117
+ parsed.workspaceId = workspaceId;
2118
+ }
1604
2119
  const enc = await this.encState();
1605
2120
  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
2121
  return response.data;
@@ -1669,6 +2184,7 @@ function capWait(pending) {
1669
2184
  ]);
1670
2185
  }
1671
2186
  class EchoMemMCPServer {
2187
+ store;
1672
2188
  server;
1673
2189
  client;
1674
2190
  accountGeneration = 0;
@@ -1683,6 +2199,7 @@ class EchoMemMCPServer {
1683
2199
  groupMapInjected = false;
1684
2200
  updateStatus;
1685
2201
  constructor(store) {
2202
+ this.store = store;
1686
2203
  this.server = new Server({
1687
2204
  name: "echomem-mcp",
1688
2205
  version: SERVER_VERSION,
@@ -1787,7 +2304,7 @@ class EchoMemMCPServer {
1787
2304
  this.mapInjected = !!map;
1788
2305
  this.groupMapInjected = !!groupMap;
1789
2306
  const updateNotice = DESKTOP_MANAGED ? undefined : formatUpdateNotice(this.updateStatus);
1790
- return { tools: listToolSpecs({ map, groupMap, updateNotice }) };
2307
+ return { tools: listToolSpecs({ map, groupMap, updateNotice, includeSaveMessages: clientNeedsSaveMessages(this.mcpClientName) }) };
1791
2308
  });
1792
2309
  this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
1793
2310
  this.refreshAccountContext();
@@ -1800,17 +2317,68 @@ class EchoMemMCPServer {
1800
2317
  const clientVersion = this.server.getClientVersion();
1801
2318
  this.mcpClientName = clientVersion?.name ?? this.mcpClientName;
1802
2319
  this.mcpClientVersion = clientVersion?.version ?? this.mcpClientVersion;
2320
+ this.client.hostClientName = this.mcpClientName;
1803
2321
  let sourceResolution = {
1804
2322
  sourceSession: null,
1805
2323
  isSubagent: false,
1806
2324
  lineageStatus: "unbound",
1807
2325
  };
2326
+ let sourceNotReady;
1808
2327
  try {
1809
- sourceResolution = resolveSourceSessionRequestContext(extra._meta, { hostPlatform: this.getMcpClientAnalytics().host_platform });
2328
+ sourceResolution = resolveSourceSessionRequestContext(extra._meta, {
2329
+ hostPlatform: this.getMcpClientAnalytics().host_platform,
2330
+ // Desktop's local-agent-mode MCP process serves multiple conversations.
2331
+ // Its environment belongs to the process, never to this request.
2332
+ env: this.mcpClientName?.startsWith("local-agent-mode-") ? {} : process.env,
2333
+ });
1810
2334
  }
1811
- catch {
2335
+ catch (error) {
2336
+ if (error instanceof Error && error.message.startsWith("SOURCE_SESSION_NOT_READY"))
2337
+ sourceNotReady = error;
1812
2338
  // Malformed host metadata is not model input. Ignore it and retain the explicit fallback.
1813
2339
  }
2340
+ // The hook leaves a call's proof under the host's ID for that call, or, for a call a relay
2341
+ // carries, under its tool name and input; a hook that could do neither put it in the input.
2342
+ const toolUseId = isRecord(extra._meta) ? extra._meta["claudecode/toolUseId"] : undefined;
2343
+ const inInput = isRecord(request.params.arguments) ? request.params.arguments.sourceSessionProof : undefined;
2344
+ const sourceSessionProof = (typeof toolUseId === "string" && toolUseId ? takeSourceSessionProof(toolUseId) : null)
2345
+ ?? (/^(local-agent-mode-|claude)/i.test(this.mcpClientName ?? "")
2346
+ ? takeSourceSessionProofForCall(`mcp__echomem__${request.params.name}`, request.params.arguments, typeof inInput === "string" ? inInput : undefined)
2347
+ : null)
2348
+ ?? inInput;
2349
+ // Signed out, a proof cannot be checked and nothing can be written: the tool itself then
2350
+ // says that EchoMem is not connected.
2351
+ if (sourceSessionProof !== undefined && this.client.hasToken()) {
2352
+ const verified = typeof sourceSessionProof === "string"
2353
+ ? verifySourceSessionProof(sourceSessionProof, `mcp__echomem__${request.params.name}`, this.store.getToken())
2354
+ : null;
2355
+ if (!verified || sourceResolution.isSubagent) {
2356
+ throw new McpError(ErrorCode.InvalidParams, "Invalid or unavailable host source-session proof");
2357
+ }
2358
+ // Only an identity the host sent with this request can contradict the call's own proof.
2359
+ // The process environment is fixed at launch: after /clear Claude Code is in a new
2360
+ // session while this process still holds the old ID.
2361
+ let sentWithRequest = null;
2362
+ try {
2363
+ sentWithRequest = resolveSourceSessionRequestContext(extra._meta, { hostPlatform: this.getMcpClientAnalytics().host_platform, env: {} }).sourceSession;
2364
+ }
2365
+ catch {
2366
+ // Malformed host metadata names no identity.
2367
+ }
2368
+ if (sentWithRequest && sentWithRequest.canonicalKey !== verified.identity.canonicalKey) {
2369
+ throw new McpError(ErrorCode.InvalidParams, "Host metadata and source-session proof disagree");
2370
+ }
2371
+ if (!claimSourceSessionProofNonce(verified.nonce, this.store.getToken())) {
2372
+ throw new McpError(ErrorCode.InvalidParams, "Source-session proof was already used");
2373
+ }
2374
+ sourceResolution = {
2375
+ sourceSession: verified.identity,
2376
+ isSubagent: false,
2377
+ lineageStatus: "top_level",
2378
+ };
2379
+ }
2380
+ if (sourceNotReady && !sourceResolution.sourceSession)
2381
+ throw sourceNotReady;
1814
2382
  let provisionalCloudSession = null;
1815
2383
  try {
1816
2384
  provisionalCloudSession = resolveCloudCoworkSessionFromToolArguments(toolArgs);
@@ -1849,7 +2417,8 @@ class EchoMemMCPServer {
1849
2417
  }
1850
2418
  // A child request starts fail-closed. Resolved children bind to the originating root; unresolved
1851
2419
  // children carry an explicit null so AsyncLocalStorage cannot fall through to a global binding.
1852
- let requestSourceSession = sourceResolution.isSubagent
2420
+ const sharedDesktopBridge = this.mcpClientName?.startsWith("local-agent-mode-") === true;
2421
+ let requestSourceSession = sourceResolution.isSubagent || sharedDesktopBridge
1853
2422
  ? null
1854
2423
  : this.client.getBoundSourceSession();
1855
2424
  // Verified request metadata always wins over a bridge-level compatibility fallback. The
@@ -1858,6 +2427,7 @@ class EchoMemMCPServer {
1858
2427
  if (sourceResolution.sourceSession && this.client.hasToken()) {
1859
2428
  requestSourceSession = await this.client.bindSourceSession(sourceResolution.sourceSession, false);
1860
2429
  }
2430
+ const receiptGeneration = this.client.refreshAccountContext();
1861
2431
  return this.client.withRequestContext({
1862
2432
  ...sourceResolution,
1863
2433
  sourceSession: requestSourceSession,
@@ -1960,26 +2530,8 @@ class EchoMemMCPServer {
1960
2530
  }],
1961
2531
  };
1962
2532
  }
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
- }
2533
+ // Recompose is a local preview/export, never a memory-write shortcut.
2534
+ // Durable retention must use save_conversation's verified Gemini path.
1983
2535
  return { content: [{ type: "text", text: capsuleText }] };
1984
2536
  }
1985
2537
  if (!this.client.hasToken())
@@ -2150,6 +2702,7 @@ class EchoMemMCPServer {
2150
2702
  rec.ok = rec.error_kind === "none";
2151
2703
  rec.latency_ms = Date.now() - t0;
2152
2704
  this.events.record(rec);
2705
+ recordLocalUsage({ action: canonicalName, source: this.getMcpClientAnalytics().host_platform, outcome: rec.ok ? "success" : "failure", duration_ms: rec.latency_ms });
2153
2706
  if (canonicalName !== canonicalToolNames.updateStatus &&
2154
2707
  canonicalName !== canonicalToolNames.contextHealth &&
2155
2708
  canonicalName !== canonicalToolNames.recompose &&
@@ -2178,6 +2731,11 @@ class EchoMemMCPServer {
2178
2731
  void this.client.trackMcpAnalyticsEvent(toolEventName(canonicalName, rec.ok ? "Succeeded" : "Failed"), finalAnalytics, `${analyticsCallId}:completed`);
2179
2732
  }
2180
2733
  }
2734
+ }).then(result => {
2735
+ if (sourceResolution.isSubagent || result.isError || !this.client.hasToken())
2736
+ return result;
2737
+ const receipt = this.client.takeTurnEndOutcomes(requestSourceSession, receiptGeneration);
2738
+ return receipt ? { ...result, content: [...result.content, { type: "text", text: receipt }] } : result;
2181
2739
  });
2182
2740
  });
2183
2741
  }
@@ -2315,26 +2873,53 @@ Details: ${m.details || "N/A"}`)
2315
2873
  rec.conversation_chars = text.length;
2316
2874
  rec.save_source = typeof a?.source === "string" ? a.source : sourceFallback;
2317
2875
  }
2318
- const { success, memoriesExtracted, memoriesDiscarded, extractedMemories, contextId, capsuleId, passthrough: isPassthrough, groupSessionSharing, groupSync, groupSyncs, groupSharingScopeId, error, } = await this.client.saveConversation(enrichedArgs);
2876
+ 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, scopeKeysConversation, } = await this.client.saveConversation(enrichedArgs);
2319
2877
  if (!success)
2320
2878
  throw new Error(`EchoMem API Error: ${error}`);
2879
+ if (isPassthrough)
2880
+ throw new Error("MEMORY_EXTRACTION_REQUIRED: backend returned a legacy direct-write receipt; update the backend.");
2321
2881
  if (rec)
2322
2882
  rec.memories_extracted = typeof memoriesExtracted === "number" ? memoriesExtracted : undefined;
2323
- // Passthrough saves store the capsule verbatim — no extraction, no embeddings.
2324
- if (isPassthrough) {
2883
+ if (typeof messagesRequired === "string") {
2884
+ 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.` }] };
2885
+ }
2886
+ if (savesAfterTurnEnds && noteMissing) {
2887
+ 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." }] };
2888
+ }
2889
+ if (savesAfterTurnEnds) {
2890
+ // The call carried a note, and the host's record of the call could not be read in time.
2891
+ if (rec)
2892
+ rec.save_note_unread = true;
2893
+ 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." }] };
2894
+ }
2895
+ if (deferredUntilCompletion) {
2896
+ return { content: [{ type: "text", text: "No memory was written: the verified source has no finished answer to save. Do not claim anything was saved." }] };
2897
+ }
2898
+ if (pendingProcessing) {
2899
+ // The operation keeps running in this bridge; a repeat call only re-attaches to it.
2900
+ 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." }] };
2901
+ }
2902
+ const checkpointReceipt = savedBoundary ? `EchoMem checkpoint: ${JSON.stringify(savedBoundary)}` : "";
2903
+ // Notice about what this save covers: messages cut to fit the cap.
2904
+ const pendingNotice = [
2905
+ isRecord(messagesTrimmed)
2906
+ ? `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.`
2907
+ : "",
2908
+ ].filter(Boolean).join("\n\n");
2909
+ if (memoriesExtracted === 0 && !isPassthrough) {
2910
+ const existing = Array.isArray(extractedMemories) ? extractedMemories.filter(isRecord) : [];
2325
2911
  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");
2912
+ existing.length
2913
+ ? "Conversation processed successfully. This request was already saved; no duplicate memory was created."
2914
+ : "Conversation processed successfully. No memory was created; there is no new memory ID.",
2915
+ ...existing.map(memory => typeof memory.id === "string"
2916
+ ? `Existing memory: ${memoryMarkdownLink(personalMemoryWebUrl(memory.id), memory.keys, memory.description)}` : ""),
2917
+ typeof decision === "string" ? `Decision: ${decision}.` : "",
2918
+ typeof reason === "string" ? `Reason: ${reason}.` : "",
2919
+ pendingNewEvidence === true ? "Waiting for new evidence; the source window remains pending." : "",
2920
+ checkpointReceipt,
2921
+ pendingNotice,
2922
+ ].filter(Boolean).join("\n\n");
2338
2923
  return { content: [{ type: "text", text }] };
2339
2924
  }
2340
2925
  // Surface WHAT was captured (not just the count) so the agent can verify the key facts survived
@@ -2347,10 +2932,9 @@ Details: ${m.details || "N/A"}`)
2347
2932
  ? [groupSync]
2348
2933
  : [];
2349
2934
  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
- : [];
2935
+ // The backend publishes to approved groups after its response; the receipt says so.
2936
+ const deferredSyncs = typeof groupSyncsDeferred === "number" ? groupSyncsDeferred : 0;
2937
+ const approvedGroupName = isRecord(sharing?.group) ? readString(sharing.group, "name") : null;
2354
2938
  const syncedGroupNames = syncList
2355
2939
  .filter((item) => item.synced === true)
2356
2940
  .map((item) => readString(item, "groupName"))
@@ -2363,10 +2947,9 @@ Details: ${m.details || "N/A"}`)
2363
2947
  ? [
2364
2948
  syncedGroupNames.length
2365
2949
  ? `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
- : "",
2950
+ : deferredSyncs > 0
2951
+ ? "Saved privately first; syncing to approved groups in the background."
2952
+ : "Saved to your private memory.",
2370
2953
  failedSyncs.length
2371
2954
  ? `${failedSyncs.length} approved group sync(s) failed; private memories were preserved.`
2372
2955
  : "",
@@ -2375,9 +2958,7 @@ Details: ${m.details || "N/A"}`)
2375
2958
  : "",
2376
2959
  ].filter(Boolean).join(" ")
2377
2960
  : 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."
2961
+ ? "Saved to your private memory."
2381
2962
  : sharing.decision === "private"
2382
2963
  ? "Saved to your private memory."
2383
2964
  : syncedGroupNames.length
@@ -2387,7 +2968,9 @@ Details: ${m.details || "N/A"}`)
2387
2968
  ? `${protectedIds.length} protected memory item(s) stayed private.`
2388
2969
  : "",
2389
2970
  ].filter(Boolean).join(" ")
2390
- : `Saved to your private memory, but group sync failed${readString(failedSyncs[0] ?? sync ?? {}, "error") ? `: ${readString(failedSyncs[0] ?? sync ?? {}, "error")}` : "."}`;
2971
+ : deferredSyncs > 0
2972
+ ? `Saved to your private memory; syncing to ${approvedGroupName ?? "the approved group"} in the background.`
2973
+ : `Saved to your private memory, but group sync failed${readString(failedSyncs[0] ?? sync ?? {}, "error") ? `: ${readString(failedSyncs[0] ?? sync ?? {}, "error")}` : "."}`;
2391
2974
  const list = saved
2392
2975
  .map((m, idx) => {
2393
2976
  const keys = readString(m, "keys") ?? "(no key)";
@@ -2403,20 +2986,34 @@ Details: ${m.details || "N/A"}`)
2403
2986
  ].filter(Boolean).join("\n");
2404
2987
  })
2405
2988
  .join("\n\n");
2989
+ // Notch visibility is not evidence that this particular receipt was seen.
2990
+ // Always return real memory links for the chat's durable confirmation.
2406
2991
  const text = [
2407
2992
  `Successfully ingested conversation. Extracted ${memoriesExtracted} memory distinct events.`,
2408
2993
  receipt,
2409
- GROUP_SESSION_SHARING_PROMPTS_ENABLED && typeof groupSharingScopeId === "string" && groupSharingScopeId
2410
- ? `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
- : "",
2994
+ checkpointReceipt,
2995
+ pendingNotice,
2996
+ typeof groupSharingScopeId !== "string" || !groupSharingScopeId
2997
+ ? ""
2998
+ : GROUP_SESSION_SHARING_PROMPTS_ENABLED
2999
+ ? `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.`
3000
+ // A host with no readable transcript and no session hook cannot be told apart from the
3001
+ // other conversations on its bridge, so the agent carries the key between its saves.
3002
+ : scopeKeysConversation === true
3003
+ ? `Conversation sharing scope: ${groupSharingScopeId}\nPass this exact groupSharingScopeId on every later save_conversation call in this conversation, so its saves stay in one conversation. Never reuse it in another conversation or save it as memory.`
3004
+ : "",
2412
3005
  typeof memoriesDiscarded === "number" && memoriesDiscarded > 0
2413
3006
  ? `${memoriesDiscarded} additional memories were not stored because your active-memory limit was reached.`
2414
3007
  : "",
2415
- list ? `EchoMem saved:\n\n${list}` : "",
3008
+ // A turn saved in this call ends with its own receipt block below: only that one is titled for the answer.
3009
+ list ? `${savedInTurn ? "Saved memories, for your check only:" : "EchoMem saved:"}\n\n${list}` : "",
2416
3010
  saved.length
2417
3011
  ? `Verify these captured the key facts. Re-fetch this exact batch later by searching the ids above${typeof contextId === "string" && contextId ? ` (context ${contextId})` : ""}.`
2418
3012
  : "",
2419
- saved.length ? SAVED_MEMORY_RECEIPT_INSTRUCTION : "",
3013
+ saved.length && !savedInTurn ? SAVED_MEMORY_RECEIPT_INSTRUCTION : "",
3014
+ saved.length && savedInTurn
3015
+ ? `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}`
3016
+ : "",
2420
3017
  ].filter(Boolean).join("\n\n");
2421
3018
  return { content: [{ type: "text", text }] };
2422
3019
  }
@@ -2433,7 +3030,10 @@ Details: ${m.details || "N/A"}`)
2433
3030
  bound.created ? "Created and bound the source-session context." : "Source-session context is bound.",
2434
3031
  `Context: ${bound.contextId}`,
2435
3032
  `Source session: ${bound.canonicalKey}`,
2436
- "Later EchoMem saves, recalls, citations, sharing decisions, and activity from this bridge will use this context automatically.",
3033
+ // Claude Desktop runs one bridge for every conversation, so a binding there holds for one request.
3034
+ this.mcpClientName?.startsWith("local-agent-mode-")
3035
+ ? "This host shares one EchoMem bridge between conversations, so the binding covers this request only. Each later call must carry its own fresh sourceSessionBindingToken."
3036
+ : "Later EchoMem saves, recalls, citations, sharing decisions, and activity from this bridge will use this context automatically.",
2437
3037
  ].join("\n"),
2438
3038
  }],
2439
3039
  };
@@ -2536,24 +3136,14 @@ Details: ${m.details || "N/A"}`)
2536
3136
  };
2537
3137
  }
2538
3138
  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
3139
  return {
2550
3140
  content: [{
2551
3141
  type: "text",
2552
3142
  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,
3143
+ "Status: review_skipped_no_workspace",
3144
+ "No unique workspace is established for this conversation, so routine ticket stewardship is skipped.",
3145
+ "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.",
3146
+ "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
3147
  ].join("\n"),
2558
3148
  }],
2559
3149
  };
@@ -2655,7 +3245,7 @@ Details: ${m.details || "N/A"}`)
2655
3245
  }
2656
3246
  async handleFindWorkspaceTicketCandidates(args) {
2657
3247
  const parsed = findWorkspaceTicketCandidatesSchema.parse(args ?? {});
2658
- const result = await this.client.reviewWorkspaceTicketSession(parsed);
3248
+ const result = await this.client.reviewWorkspaceTicketSession(parsed, { notchTeam: true });
2659
3249
  if (!result) {
2660
3250
  return {
2661
3251
  content: [{
@@ -2720,6 +3310,9 @@ Details: ${m.details || "N/A"}`)
2720
3310
  type: "text",
2721
3311
  text: [
2722
3312
  workspaceId ? `Workspace: ${workspaceId}` : "",
3313
+ ...(parsed.ticketId ? [
3314
+ `Requested target ticket (workspace data): ${JSON.stringify(candidates.find(ticket => ticket.id === parsed.ticketId) ?? { id: parsed.ticketId, status: "not_in_snapshot" })}`,
3315
+ ] : []),
2723
3316
  ...formatTicketFilingPacket({
2724
3317
  candidates,
2725
3318
  activeAssignments,
@@ -2729,7 +3322,7 @@ Details: ${m.details || "N/A"}`)
2729
3322
  ...pendingLines,
2730
3323
  "",
2731
3324
  `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.",
3325
+ "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
3326
  ].filter(Boolean).join("\n"),
2734
3327
  }],
2735
3328
  };
@@ -2738,7 +3331,7 @@ Details: ${m.details || "N/A"}`)
2738
3331
  const parsed = recordWorkspaceTicketProposalSchema.parse(args ?? {});
2739
3332
  const result = await this.client.recordWorkspaceTicketProposal(parsed);
2740
3333
  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.");
3334
+ 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
3335
  }
2743
3336
  const proposal = isRecord(result.proposal) ? result.proposal : {};
2744
3337
  const proposalId = readString(proposal, "proposalId");
@@ -2769,7 +3362,7 @@ Details: ${m.details || "N/A"}`)
2769
3362
  const parsed = acknowledgeWorkspaceTicketReviewSchema.parse(args ?? {});
2770
3363
  const result = await this.client.acknowledgeWorkspaceTicketReview(parsed);
2771
3364
  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.");
3365
+ 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
3366
  }
2774
3367
  const acknowledgement = isRecord(result.acknowledgement) ? result.acknowledgement : {};
2775
3368
  const outcome = readString(acknowledgement, "outcome") ?? parsed.outcome;
@@ -2899,7 +3492,7 @@ Details: ${m.details || "N/A"}`)
2899
3492
  }
2900
3493
  const result = await this.client.applyWorkspaceTicketAction(parsed);
2901
3494
  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.");
3495
+ 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
3496
  }
2904
3497
  const ticket = isRecord(result.ticket) ? result.ticket : {};
2905
3498
  const ticketId = readString(ticket, "id") ?? parsed.ticketId ?? "unknown";
@@ -2937,7 +3530,8 @@ Details: ${m.details || "N/A"}`)
2937
3530
  : parsed.action === "unassign_current"
2938
3531
  ? "Closed this session's active ticket interval. Past ticket activity remains visible; workspace sharing and published memory snapshots are unchanged."
2939
3532
  : "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.",
3533
+ "Session binding completed. This action does not publish memories or enable future sharing.",
3534
+ "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
3535
  ].filter(Boolean).join("\n"),
2942
3536
  }],
2943
3537
  };
@@ -3635,6 +4229,8 @@ Details: ${m.details || "N/A"}`;
3635
4229
  `Prepared publication scan ${payload?.scanId} for ${payload?.group?.name ?? "your group"}.`,
3636
4230
  `Window: ${payload?.windowStart ?? "context start"} → ${payload?.windowEnd}`,
3637
4231
  `Candidates: ${candidates.length}. Nothing has been published.`,
4232
+ 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.` : "",
4233
+ 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
4234
  `Current title: ${readString(participantProfile, "title") ?? "Not declared"}`,
3639
4235
  `Current declared responsibility: ${readString(participantProfile, "responsibilitySummary") ?? "Not provided"}`,
3640
4236
  "",
@@ -3721,6 +4317,7 @@ Details: ${m.details || "N/A"}`;
3721
4317
  `Newly published: ${published}.`,
3722
4318
  `Exact duplicates skipped: ${duplicates}.`,
3723
4319
  `Selected memory IDs: ${parsed.memoryIds.join(", ") || "(none)"}.`,
4320
+ payload?.futureSharingEnabled === true ? "Future eligible memories from this session will be shared with the same workspace. Flagged memories remain private." : "",
3724
4321
  "The scan cursor advanced; encrypted originals and global public settings were unchanged.",
3725
4322
  ].join("\n"),
3726
4323
  }],
@@ -3803,12 +4400,38 @@ Details: ${m.details || "N/A"}`;
3803
4400
  }
3804
4401
  async run() {
3805
4402
  const transport = new StdioServerTransport();
4403
+ // Claude Desktop's shared bridge is reached through a relay that carries only a call's input.
4404
+ this.server.oninitialized = () => {
4405
+ if (this.server.getClientVersion()?.name?.startsWith("local-agent-mode-"))
4406
+ registerRelayBridge();
4407
+ else
4408
+ registerDirectBridge();
4409
+ };
3806
4410
  await this.server.connect(transport);
4411
+ this.client.resumeTurnEndSaves();
3807
4412
  this.events.record({ type: "session_start" });
3808
4413
  console.error("EchoMem MCP server running on stdio");
3809
4414
  }
3810
4415
  }
3811
4416
  async function main() {
4417
+ if (process.argv[2] === "source-snapshot") {
4418
+ try {
4419
+ const { exportSourceSnapshot } = await import("./source-snapshot-export.js");
4420
+ let input = "";
4421
+ for await (const chunk of process.stdin) {
4422
+ input += String(chunk);
4423
+ if (input.length > 32_000)
4424
+ throw new Error("SOURCE_SNAPSHOT_REQUEST_TOO_LARGE");
4425
+ }
4426
+ process.stdout.write(JSON.stringify(exportSourceSnapshot(JSON.parse(input))));
4427
+ }
4428
+ catch (error) {
4429
+ const message = error instanceof Error && /^[A-Z_]+$/.test(error.message) ? error.message : "SOURCE_SNAPSHOT_UNAVAILABLE";
4430
+ process.stdout.write(JSON.stringify({ success: false, error: message }));
4431
+ process.exitCode = 1;
4432
+ }
4433
+ return;
4434
+ }
3812
4435
  // Subcommands (setup/login/unlock/status/logout/help) run and exit; no subcommand → serve.
3813
4436
  const handled = await runCli(process.argv.slice(2));
3814
4437
  if (handled) {