@echomem/mcp 1.5.0 → 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.
@@ -0,0 +1,48 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { echoConfigDir } from "./keystore.js";
4
+ /** The team chosen in Echo Desktop's Notch: `~/.echomem/desktop-workspace.json`
5
+ * holding `{ v: 1, workspaceId, updatedAt }`. Desktop rewrites it when the
6
+ * choice changes and removes it when no team is chosen or the account signs
7
+ * out. It is a choice, not a heartbeat, so it does not go stale: it stands
8
+ * while Desktop is closed.
9
+ *
10
+ * The file names a workspace and proves nothing. It is only ever used to pick
11
+ * among the workspaces the backend has just listed for this bridge's account
12
+ * (`chosenDesktopWorkspace`), so another account's choice, or a team the user
13
+ * has left, is ignored and the user is asked as before. */
14
+ export const DESKTOP_WORKSPACE_FILE = "desktop-workspace.json";
15
+ const WORKSPACE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16
+ export function readDesktopWorkspace(options = {}) {
17
+ const file = path.join(options.directory ?? echoConfigDir(), DESKTOP_WORKSPACE_FILE);
18
+ try {
19
+ const stat = fs.statSync(file);
20
+ if (!stat.isFile() || stat.size > 4096)
21
+ return null;
22
+ const row = JSON.parse(fs.readFileSync(file, "utf8"));
23
+ if (row.v !== 1 || typeof row.workspaceId !== "string" || !WORKSPACE_ID.test(row.workspaceId))
24
+ return null;
25
+ return row.workspaceId.toLowerCase();
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ /** The Notch's team, when the backend asked which workspace to use and that
32
+ * team is one of the choices it offered. Undefined otherwise. */
33
+ export function chosenDesktopWorkspace(payload, options = {}) {
34
+ if (!payload || typeof payload !== "object")
35
+ return undefined;
36
+ const answer = payload;
37
+ if (answer.requiresWorkspaceSelection !== true || !Array.isArray(answer.availableWorkspaces))
38
+ return undefined;
39
+ const chosen = readDesktopWorkspace(options);
40
+ if (!chosen)
41
+ return undefined;
42
+ for (const workspace of answer.availableWorkspaces) {
43
+ const id = workspace && typeof workspace === "object" ? workspace.id : undefined;
44
+ if (typeof id === "string" && id.toLowerCase() === chosen)
45
+ return id;
46
+ }
47
+ return undefined;
48
+ }
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import axios from "axios";
10
10
  import { ZodError } from "zod";
11
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";
12
12
  import { KeyStore } from "./keystore.js";
13
+ import { chosenDesktopWorkspace } from "./desktop-workspace.js";
13
14
  import { readStrictRawSessionState, SAVE_NOTE_SUFFIX, selectSaveEvidence } from "./strict-raw-session.js";
14
15
  import { rememberSaveNote } from "./save-note-store.js";
15
16
  import { isMemorySaveDeclined, userRequestText } from "./memory-intent.js";
@@ -23,7 +24,7 @@ import { completedSaveReceipt, turnSaveResult } from "./save-receipt.js";
23
24
  import { enqueueSaveReceipt, takeSaveReceipts } from "./save-receipt-store.js";
24
25
  import { startSaveLocalTrace } from "./save-local-trace.js";
25
26
  import { readToolMapCache, writeToolMapCache } from "./tool-map-cache.js";
26
- import { claimSourceSessionProofNonce, registerDirectBridge, takeSourceSessionProof, verifySourceSessionProof } from "./source-session-local.js";
27
+ import { claimSourceSessionProofNonce, registerDirectBridge, registerRelayBridge, takeSourceSessionProof, takeSourceSessionProofForCall, verifySourceSessionProof, } from "./source-session-local.js";
27
28
  import { EventLogger, hashText } from "./events.js";
28
29
  import { requestFailureDetails } from "./request-failure.js";
29
30
  import { contextHealthMarkdown, recomposeCapsuleMarkdown } from "./hud/api.js";
@@ -69,6 +70,8 @@ class NoTokenError extends Error {
69
70
  /** Thrown when an encrypted account has no usable key — the model gets an unlock nudge, never ciphertext. */
70
71
  class LockedError extends Error {
71
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";
72
75
  /** A short code the desktop can name; never server text. */
73
76
  function desktopFailureReason(error) {
74
77
  if (error instanceof LockedError)
@@ -795,6 +798,9 @@ class EchoMemApiClient {
795
798
  whoamiCache = null;
796
799
  /** One id per bridge process — groups all saves from this coding session under a single EchoMem context. */
797
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();
798
804
  encConfigPromise = null;
799
805
  deleteConfirmations = new Map();
800
806
  constructor(store) {
@@ -888,14 +894,21 @@ class EchoMemApiClient {
888
894
  }
889
895
  async bindSourceSession(identity, persistForBridge = true) {
890
896
  this.synchronizeAccountContext();
897
+ const generation = this.accountGeneration;
891
898
  if (identity.evidence === SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE && persistForBridge) {
892
899
  throw new Error("A provisional Cloud Cowork identity cannot become shared bridge state");
893
900
  }
894
901
  const cached = this.sourceSessionsByCanonicalKey.get(identity.canonicalKey);
895
- 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 };
896
909
  if (persistForBridge)
897
- this.boundSourceSession = cached;
898
- return { ...cached, created: false };
910
+ this.boundSourceSession = current;
911
+ return { ...current, created: false };
899
912
  }
900
913
  const response = await this.axios.post("/api/extension/source-sessions/bind", {
901
914
  provider: identity.provider,
@@ -904,6 +917,9 @@ class EchoMemApiClient {
904
917
  evidence: identity.evidence,
905
918
  runtime_version: MCP_PACKAGE_VERSION,
906
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.");
907
923
  const contextId = readString(response.data, "contextId");
908
924
  const canonicalKey = readString(response.data, "canonicalKey");
909
925
  const provider = readString(response.data, "provider");
@@ -921,8 +937,9 @@ class EchoMemApiClient {
921
937
  canonicalKey,
922
938
  contextId,
923
939
  };
924
- this.sourceSessionsByCanonicalKey.set(identity.canonicalKey, bound);
925
- this.sourceSessionsByCanonicalKey.set(canonicalKey, bound);
940
+ const binding = { ...bound, transcript: undefined };
941
+ this.sourceSessionsByCanonicalKey.set(identity.canonicalKey, binding);
942
+ this.sourceSessionsByCanonicalKey.set(canonicalKey, binding);
926
943
  if (this.sourceSessionsByCanonicalKey.size > 64) {
927
944
  const oldestKey = this.sourceSessionsByCanonicalKey.keys().next().value;
928
945
  if (oldestKey)
@@ -959,6 +976,9 @@ class EchoMemApiClient {
959
976
  if (explicit)
960
977
  return explicit;
961
978
  const response = await this.axios.get("/api/extension/social/groups/current");
979
+ const chosen = chosenDesktopWorkspace(response.data);
980
+ if (chosen)
981
+ return chosen;
962
982
  const group = isRecord(response.data?.group) ? response.data.group : null;
963
983
  const id = group ? readString(group, "id") : undefined;
964
984
  if (!id) {
@@ -997,22 +1017,27 @@ class EchoMemApiClient {
997
1017
  });
998
1018
  return { workspaceId: id, data: response.data };
999
1019
  }
1000
- 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 = {}) {
1001
1024
  const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
1002
1025
  const sourceSession = this.getRequestSourceSession();
1003
1026
  if (!sourceSession)
1004
1027
  return null;
1005
- const response = await this.axios.get("/api/extension/workspace-ticket-actions", {
1028
+ const review = (workspaceId) => this.axios.get("/api/extension/workspace-ticket-actions", {
1006
1029
  params: {
1007
1030
  contextId: sourceSession.contextId,
1008
- workspaceId: parsed.workspaceId,
1031
+ workspaceId,
1009
1032
  groupId: parsed.groupId,
1010
1033
  memoryThreshold: parsed.memoryThreshold,
1011
1034
  ticketId: parsed.ticketId,
1012
1035
  },
1013
1036
  timeout: TICKET_REVIEW_TIMEOUT_MS,
1014
1037
  });
1015
- 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;
1016
1041
  }
1017
1042
  async acknowledgeWorkspaceTicketReview(args) {
1018
1043
  const parsed = acknowledgeWorkspaceTicketReviewSchema.parse(args ?? {});
@@ -1550,6 +1575,9 @@ class EchoMemApiClient {
1550
1575
  if (parsed.conversation !== undefined) {
1551
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.");
1552
1577
  }
1578
+ if (boundSourceSession?.contextId && this.unreconciledContexts.has(boundSourceSession.contextId)) {
1579
+ return this.saveFromAgentMessages(parsed, { boundSourceSession, groupSharingScopeId, receiptToken, report, reason: SOURCE_RECOVERY_REQUIRED });
1580
+ }
1553
1581
  // A verified local transcript always wins; agent-supplied turns are used only by hosts
1554
1582
  // whose transcript this bridge cannot read (Cursor, Claude Desktop chat, Cloud Cowork).
1555
1583
  let rawSession;
@@ -1693,12 +1721,27 @@ class EchoMemApiClient {
1693
1721
  finishLocalTrace({ state: "FAILED", elapsedMs: Date.now() - traceStarted,
1694
1722
  response: axios.isAxiosError(error) ? error.response?.data ?? { success: false, error: "TRANSPORT_ERROR" } : { success: false, error: "LOCAL_SAVE_ERROR" },
1695
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
+ }
1696
1729
  // A save that outlives the caller's wait still reports how it ended.
1697
1730
  report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
1698
1731
  throwIfProcessingQuotaExceeded(error);
1699
1732
  throw error;
1700
1733
  }
1701
- }, waitForCompletion);
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 });
1702
1745
  this.synchronizeAccountContext();
1703
1746
  if (generation !== this.accountGeneration)
1704
1747
  throw new Error("ACCOUNT_CHANGED_DURING_SAVE: the result was withheld because the signed-in account changed.");
@@ -1822,7 +1865,9 @@ class EchoMemApiClient {
1822
1865
  void this.refreshGroupMemoryMapCache();
1823
1866
  }
1824
1867
  }
1825
- return { ...response.data, groupSharingScopeId: ctx.groupSharingScopeId };
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 };
1826
1871
  }
1827
1872
  catch (error) {
1828
1873
  ctx.report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
@@ -1948,7 +1993,7 @@ class EchoMemApiClient {
1948
1993
  async searchOthersMemories(args) {
1949
1994
  const parsed = othersSchema.parse(args ?? {});
1950
1995
  try {
1951
- 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", {
1952
1997
  query: parsed.query,
1953
1998
  limit: parsed.limit,
1954
1999
  target: parsed.target,
@@ -1960,12 +2005,14 @@ class EchoMemApiClient {
1960
2005
  kPerUser: parsed.kPerUser,
1961
2006
  similarityThreshold: parsed.similarityThreshold,
1962
2007
  timeFrameDays: parsed.timeFrameDays,
1963
- workspaceId: parsed.workspaceId ?? parsed.groupId,
2008
+ workspaceId,
1964
2009
  scope: parsed.scope,
1965
2010
  requestId: this.sessionId,
1966
2011
  source: "mcp_friend_public_memory_search",
1967
2012
  });
1968
- 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;
1969
2016
  }
1970
2017
  catch (error) {
1971
2018
  throw new Error(`search_others_memories failed against ${ECHO_API_BASE_URL}: ${describeError(error)}`);
@@ -2007,11 +2054,13 @@ class EchoMemApiClient {
2007
2054
  const parsed = groupContextSchema.parse(args ?? {});
2008
2055
  try {
2009
2056
  const workspaceId = parsed.workspaceId ?? parsed.groupId;
2010
- const path = workspaceId
2011
- ? `/api/extension/social/groups/current?workspaceId=${encodeURIComponent(workspaceId)}`
2057
+ const path = (id) => id
2058
+ ? `/api/extension/social/groups/current?workspaceId=${encodeURIComponent(id)}`
2012
2059
  : "/api/extension/social/groups/current";
2013
- const response = await this.axios.get(path);
2014
- 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;
2015
2064
  }
2016
2065
  catch (error) {
2017
2066
  throw new Error(`get_group_context failed against ${ECHO_API_BASE_URL}: ${describeError(error)}`);
@@ -2058,7 +2107,7 @@ class EchoMemApiClient {
2058
2107
  throw new Error("currentSession cannot be combined with a different contextId.");
2059
2108
  }
2060
2109
  // The preview's limit counts memories; the review's own limit counts tickets and is smaller.
2061
- const result = await this.reviewWorkspaceTicketSession({ ...parsed, limit: undefined });
2110
+ const result = await this.reviewWorkspaceTicketSession({ ...parsed, limit: undefined }, { notchTeam: true });
2062
2111
  const review = isRecord(result?.review) ? result.review : {};
2063
2112
  const workspaceId = readString(review, "workspaceId");
2064
2113
  if (!workspaceId)
@@ -2274,6 +2323,7 @@ class EchoMemMCPServer {
2274
2323
  isSubagent: false,
2275
2324
  lineageStatus: "unbound",
2276
2325
  };
2326
+ let sourceNotReady;
2277
2327
  try {
2278
2328
  sourceResolution = resolveSourceSessionRequestContext(extra._meta, {
2279
2329
  hostPlatform: this.getMcpClientAnalytics().host_platform,
@@ -2282,14 +2332,20 @@ class EchoMemMCPServer {
2282
2332
  env: this.mcpClientName?.startsWith("local-agent-mode-") ? {} : process.env,
2283
2333
  });
2284
2334
  }
2285
- catch {
2335
+ catch (error) {
2336
+ if (error instanceof Error && error.message.startsWith("SOURCE_SESSION_NOT_READY"))
2337
+ sourceNotReady = error;
2286
2338
  // Malformed host metadata is not model input. Ignore it and retain the explicit fallback.
2287
2339
  }
2288
- // The hook leaves a call's proof under the host's ID for that call; a hook that could not
2289
- // do that put it in the input instead.
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.
2290
2342
  const toolUseId = isRecord(extra._meta) ? extra._meta["claudecode/toolUseId"] : undefined;
2343
+ const inInput = isRecord(request.params.arguments) ? request.params.arguments.sourceSessionProof : undefined;
2291
2344
  const sourceSessionProof = (typeof toolUseId === "string" && toolUseId ? takeSourceSessionProof(toolUseId) : null)
2292
- ?? (isRecord(request.params.arguments) ? request.params.arguments.sourceSessionProof : undefined);
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;
2293
2349
  // Signed out, a proof cannot be checked and nothing can be written: the tool itself then
2294
2350
  // says that EchoMem is not connected.
2295
2351
  if (sourceSessionProof !== undefined && this.client.hasToken()) {
@@ -2321,6 +2377,8 @@ class EchoMemMCPServer {
2321
2377
  lineageStatus: "top_level",
2322
2378
  };
2323
2379
  }
2380
+ if (sourceNotReady && !sourceResolution.sourceSession)
2381
+ throw sourceNotReady;
2324
2382
  let provisionalCloudSession = null;
2325
2383
  try {
2326
2384
  provisionalCloudSession = resolveCloudCoworkSessionFromToolArguments(toolArgs);
@@ -2815,7 +2873,7 @@ Details: ${m.details || "N/A"}`)
2815
2873
  rec.conversation_chars = text.length;
2816
2874
  rec.save_source = typeof a?.source === "string" ? a.source : sourceFallback;
2817
2875
  }
2818
- const { success, memoriesExtracted, memoriesDiscarded, extractedMemories, contextId, passthrough: isPassthrough, groupSessionSharing, groupSync, groupSyncs, groupSyncsDeferred, groupSharingScopeId, error, decision, reason, pendingNewEvidence, deferredUntilCompletion, savesAfterTurnEnds, noteMissing, savedInTurn, pendingProcessing, savedBoundary, messagesRequired, messagesTrimmed, } = await this.client.saveConversation(enrichedArgs);
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);
2819
2877
  if (!success)
2820
2878
  throw new Error(`EchoMem API Error: ${error}`);
2821
2879
  if (isPassthrough)
@@ -2935,9 +2993,15 @@ Details: ${m.details || "N/A"}`)
2935
2993
  receipt,
2936
2994
  checkpointReceipt,
2937
2995
  pendingNotice,
2938
- GROUP_SESSION_SHARING_PROMPTS_ENABLED && typeof groupSharingScopeId === "string" && groupSharingScopeId
2939
- ? `Conversation sharing scope: ${groupSharingScopeId}\nReuse this exact groupSharingScopeId only for request_group_session_sharing, set_group_session_sharing, and save_conversation calls in this conversation. Never reuse it in another conversation or save it as memory.`
2940
- : "",
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
+ : "",
2941
3005
  typeof memoriesDiscarded === "number" && memoriesDiscarded > 0
2942
3006
  ? `${memoriesDiscarded} additional memories were not stored because your active-memory limit was reached.`
2943
3007
  : "",
@@ -3181,7 +3245,7 @@ Details: ${m.details || "N/A"}`)
3181
3245
  }
3182
3246
  async handleFindWorkspaceTicketCandidates(args) {
3183
3247
  const parsed = findWorkspaceTicketCandidatesSchema.parse(args ?? {});
3184
- const result = await this.client.reviewWorkspaceTicketSession(parsed);
3248
+ const result = await this.client.reviewWorkspaceTicketSession(parsed, { notchTeam: true });
3185
3249
  if (!result) {
3186
3250
  return {
3187
3251
  content: [{
@@ -4338,7 +4402,9 @@ Details: ${m.details || "N/A"}`;
4338
4402
  const transport = new StdioServerTransport();
4339
4403
  // Claude Desktop's shared bridge is reached through a relay that carries only a call's input.
4340
4404
  this.server.oninitialized = () => {
4341
- if (!this.server.getClientVersion()?.name?.startsWith("local-agent-mode-"))
4405
+ if (this.server.getClientVersion()?.name?.startsWith("local-agent-mode-"))
4406
+ registerRelayBridge();
4407
+ else
4342
4408
  registerDirectBridge();
4343
4409
  };
4344
4410
  await this.server.connect(transport);
@@ -135,7 +135,53 @@ function claudeDesktopSessionForCliId(cliSessionId) {
135
135
  }
136
136
  return best ? verifiedClaudeDesktopSession(best.desktopSessionId, best.cliSessionIds) : null;
137
137
  }
138
- export function resolveSourceSessionFromHookPayload(payload) {
138
+ /** The session the Claude desktop app says it hosts here, if that session's own record names
139
+ * this CLI session. The app writes the record a few seconds after the session's first message, so
140
+ * a call made sooner finds none: within `waitMs` it is waited for, because without it the session
141
+ * would be known by its CLI ID alone from then on. A record that names another CLI session is
142
+ * not waited on: a `claude` started inside a hosted session inherits that session's ID. Looking
143
+ * the record up by its name also keeps this independent of how many records there are. */
144
+ function hostedClaudeDesktopSession(cliSessionId, waitMs) {
145
+ const hostSessionId = process.env.CLAUDE_CODE_HOST_SESSION_ID?.trim() ?? "";
146
+ if (!CLAUDE_DESKTOP_ID_RE.test(hostSessionId))
147
+ return null;
148
+ const pause = new Int32Array(new SharedArrayBuffer(4));
149
+ for (const deadline = Date.now() + waitMs;;) {
150
+ const pending = [claudeDesktopSessionsRoot()];
151
+ const claims = [];
152
+ for (let directory = pending.pop(); directory; directory = pending.pop()) {
153
+ let entries;
154
+ try {
155
+ entries = fs.readdirSync(directory, { withFileTypes: true });
156
+ }
157
+ catch {
158
+ continue;
159
+ }
160
+ for (const entry of entries) {
161
+ if (entry.isDirectory())
162
+ pending.push(path.join(directory, entry.name));
163
+ else if (entry.isFile() && entry.name === `${hostSessionId}.json`) {
164
+ const claim = readClaudeDesktopClaim(path.join(directory, entry.name));
165
+ if (claim)
166
+ claims.push(claim);
167
+ }
168
+ }
169
+ }
170
+ const claim = claims.find((candidate) => candidate.cliSessionIds.includes(cliSessionId));
171
+ if (claim)
172
+ return verifiedClaudeDesktopSession(claim.desktopSessionId, claim.cliSessionIds);
173
+ if (claims.length > 0)
174
+ return null;
175
+ if (Date.now() >= deadline) {
176
+ if (process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop") {
177
+ throw new Error("SOURCE_SESSION_NOT_READY: Claude Desktop has not written this Code tab session record yet. Retry this call shortly.");
178
+ }
179
+ return null;
180
+ }
181
+ Atomics.wait(pause, 0, 0, 100);
182
+ }
183
+ }
184
+ export function resolveSourceSessionFromHookPayload(payload, options = {}) {
139
185
  const requestedSessionId = typeof payload.session_id === "string" ? payload.session_id.trim() : "";
140
186
  const transcriptPath = typeof payload.transcript_path === "string" ? payload.transcript_path.trim() : "";
141
187
  if (!requestedSessionId || !transcriptPath || !path.isAbsolute(transcriptPath))
@@ -163,7 +209,8 @@ export function resolveSourceSessionFromHookPayload(payload) {
163
209
  const filenameSession = path.basename(file, path.extname(file));
164
210
  if (filenameSession !== requestedSessionId)
165
211
  return null;
166
- const desktopSession = claudeDesktopSessionForCliId(filenameSession.toLowerCase());
212
+ const desktopSession = hostedClaudeDesktopSession(filenameSession.toLowerCase(), options.awaitDesktopRecordMs ?? 0)
213
+ ?? claudeDesktopSessionForCliId(filenameSession.toLowerCase());
167
214
  if (desktopSession)
168
215
  return desktopSession;
169
216
  return verifiedSourceSession("claude-code", filenameSession, SOURCE_SESSION_HOOK_EVIDENCE);
@@ -50,10 +50,16 @@ function pruneExpiredProofClaims(secret) {
50
50
  }
51
51
  }
52
52
  function identityFromData(data) {
53
+ const transcript = data.transcript;
54
+ if (transcript && (!path.isAbsolute(transcript.path) || !UUID_RE.test(transcript.sessionId)
55
+ || path.basename(transcript.path) !== `${transcript.sessionId}.jsonl`
56
+ || ![data.providerSessionId, ...(data.providerSessionAliases ?? [])].includes(transcript.sessionId))) {
57
+ throw new Error("Invalid signed transcript identity");
58
+ }
53
59
  if (data.provider === "claude-code" && data.providerSessionId.startsWith("local_")) {
54
- return verifiedClaudeDesktopSession(data.providerSessionId, data.providerSessionAliases ?? []);
60
+ return { ...verifiedClaudeDesktopSession(data.providerSessionId, data.providerSessionAliases ?? []), ...(transcript ? { transcript } : {}) };
55
61
  }
56
- return verifiedSourceSession(data.provider, data.providerSessionId, SOURCE_SESSION_HOOK_EVIDENCE);
62
+ return { ...verifiedSourceSession(data.provider, data.providerSessionId, SOURCE_SESSION_HOOK_EVIDENCE), ...(transcript ? { transcript } : {}) };
57
63
  }
58
64
  export function registerLocalSourceSession(sessionId, identity, secret) {
59
65
  if (!secret)
@@ -65,6 +71,7 @@ export function registerLocalSourceSession(sessionId, identity, secret) {
65
71
  provider: identity.provider,
66
72
  providerSessionId: identity.providerSessionId,
67
73
  providerSessionAliases: identity.providerSessionAliases,
74
+ transcript: identity.transcript,
68
75
  },
69
76
  registeredAt: Date.now(),
70
77
  };
@@ -80,7 +87,7 @@ export function registerLocalSourceSession(sessionId, identity, secret) {
80
87
  function readLocalSourceSession(sessionId, secret) {
81
88
  try {
82
89
  const file = registryFile(sessionId);
83
- if (fs.statSync(file).size > 4096)
90
+ if (fs.statSync(file).size > 16_384)
84
91
  return null;
85
92
  const envelope = JSON.parse(fs.readFileSync(file, "utf8"));
86
93
  const expected = signature(secret, envelope.payload);
@@ -117,7 +124,7 @@ export function mintSourceSessionProof(sessionId, toolName, secret) {
117
124
  return `${payload}.${signature(secret, payload).toString("base64url")}`;
118
125
  }
119
126
  export function verifySourceSessionProof(proof, toolName, secret) {
120
- if (!secret || proof.length > 4096)
127
+ if (!secret || proof.length > 24_576)
121
128
  return null;
122
129
  try {
123
130
  const [payload, mac, extra] = proof.split(".");
@@ -190,7 +197,97 @@ export function takeSourceSessionProof(toolUseId) {
190
197
  return null;
191
198
  }
192
199
  }
200
+ // A relay delivers a call's tool name and input and nothing beside them, so those are what the
201
+ // hook and the relay bridge both know the call by. The Claude desktop app's relay also fills in
202
+ // the defaults the tool's schema declares, so the bridge receives every field the hook saw and
203
+ // may receive more: a waiting proof is for a call that carries all of its fields unchanged.
204
+ // Only hashes of the fields are kept, never the input itself.
205
+ const CALL_PROOF_WINDOW_MS = 2 * 60 * 1000;
206
+ const callProofsDir = () => path.join(echoConfigDir(), "source-session-call-proofs");
207
+ const sortedKeys = (value) => Array.isArray(value) ? value.map(sortedKeys)
208
+ : value !== null && typeof value === "object"
209
+ ? Object.fromEntries(Object.keys(value).sort().map(key => [key, sortedKeys(value[key])]))
210
+ : value;
211
+ const fieldHashes = (input) => Object.fromEntries(Object.entries(input !== null && typeof input === "object" && !Array.isArray(input) ? input : {})
212
+ .filter(([, value]) => value !== undefined)
213
+ .map(([key, value]) => [key, createHash("sha256").update(JSON.stringify(sortedKeys(value))).digest("hex")]));
214
+ const proofSessionId = (proof) => {
215
+ try {
216
+ return String(JSON.parse(Buffer.from(proof.split(".")[0], "base64url").toString("utf8")).sessionId);
217
+ }
218
+ catch {
219
+ return "";
220
+ }
221
+ };
222
+ function waitingCallProofs() {
223
+ const directory = callProofsDir();
224
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
225
+ const waiting = [];
226
+ for (const name of fs.readdirSync(directory)) {
227
+ const file = path.join(directory, name);
228
+ try {
229
+ const left = fs.statSync(file).mtimeMs;
230
+ // A call the host never made leaves its proof behind for the length of the window.
231
+ if (Date.now() - left > CALL_PROOF_WINDOW_MS)
232
+ fs.unlinkSync(file);
233
+ else if (!name.startsWith("."))
234
+ waiting.push({ ...JSON.parse(fs.readFileSync(file, "utf8")), file, left });
235
+ }
236
+ catch { /* taken meanwhile */ }
237
+ }
238
+ return waiting;
239
+ }
240
+ /** Leave a relayed call's proof under the call's tool name and input. A call from another session
241
+ * that the relay bridge could take for this one makes the two indistinguishable: this one's
242
+ * proof then goes in its input. */
243
+ export function leaveSourceSessionProofForCall(toolName, input, proof) {
244
+ try {
245
+ const fields = fieldHashes(input);
246
+ const mayBeTakenFor = (other) => other.toolName === toolName && proofSessionId(other.proof) !== proofSessionId(proof)
247
+ && Object.entries(fields).every(([key, hash]) => other.fields[key] === undefined || other.fields[key] === hash);
248
+ if (waitingCallProofs().some(mayBeTakenFor))
249
+ return false;
250
+ const temporary = path.join(callProofsDir(), `.${randomUUID()}.tmp`);
251
+ fs.writeFileSync(temporary, JSON.stringify({ toolName, fields, proof }), { mode: 0o600, flag: "wx" });
252
+ fs.renameSync(temporary, path.join(callProofsDir(), randomUUID()));
253
+ return true;
254
+ }
255
+ catch {
256
+ return false;
257
+ }
258
+ }
259
+ /** Take the proof the hook left for a call with this tool name and input, oldest first. Proofs
260
+ * from two sessions cannot be told apart, so neither is used. A call that carries a proof in its
261
+ * input is only ever given one left by that same session. */
262
+ export function takeSourceSessionProofForCall(toolName, input, carried) {
263
+ try {
264
+ const sent = fieldHashes(input);
265
+ const waiting = waitingCallProofs().filter(entry => entry.toolName === toolName
266
+ && Object.entries(entry.fields).every(([key, hash]) => sent[key] === hash)
267
+ && (carried === undefined || proofSessionId(entry.proof) === proofSessionId(carried)));
268
+ if (new Set(waiting.map(entry => proofSessionId(entry.proof))).size > 1) {
269
+ for (const entry of waiting)
270
+ try {
271
+ fs.unlinkSync(entry.file);
272
+ }
273
+ catch { /* taken meanwhile */ }
274
+ return null;
275
+ }
276
+ for (const entry of waiting.sort((a, b) => a.left - b.left)) {
277
+ try {
278
+ fs.unlinkSync(entry.file);
279
+ return entry.proof;
280
+ }
281
+ catch { /* another bridge took this one */ }
282
+ }
283
+ }
284
+ catch {
285
+ // Nothing was left for this call.
286
+ }
287
+ return null;
288
+ }
193
289
  const directBridgesDir = () => path.join(echoConfigDir(), "direct-bridges");
290
+ const relayBridgesDir = () => path.join(echoConfigDir(), "relay-bridges");
194
291
  const running = (pid) => {
195
292
  try {
196
293
  process.kill(pid, 0);
@@ -200,6 +297,34 @@ const running = (pid) => {
200
297
  return error.code === "EPERM";
201
298
  }
202
299
  };
300
+ /** Record that this bridge is one a relay reaches, and that it collects the proofs left for
301
+ * relayed calls. A relay bridge from before that reads a proof only from the call's input. */
302
+ export function registerRelayBridge() {
303
+ try {
304
+ const directory = relayBridgesDir();
305
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
306
+ for (const name of fs.readdirSync(directory)) {
307
+ if (!running(Number(name)))
308
+ try {
309
+ fs.unlinkSync(path.join(directory, name));
310
+ }
311
+ catch { /* removed meanwhile */ }
312
+ }
313
+ fs.writeFileSync(path.join(directory, String(process.pid)), "", { mode: 0o600 });
314
+ }
315
+ catch {
316
+ // Without the record the hook puts the proof in the call's input, which every bridge reads.
317
+ }
318
+ }
319
+ /** Whether a running relay bridge collects the proofs left for relayed calls. */
320
+ export function relayBridgeCollectsProofs() {
321
+ try {
322
+ return fs.readdirSync(relayBridgesDir()).some(name => Number(name) > 0 && running(Number(name)));
323
+ }
324
+ catch {
325
+ return false;
326
+ }
327
+ }
203
328
  /** Record that this bridge serves the host process that launched it, and no relay in between.
204
329
  * Only such a host delivers its own ID for each call along with the call. */
205
330
  export function registerDirectBridge(hostPid = process.ppid) {
@@ -1,5 +1,5 @@
1
1
  import { KeyStore } from "./keystore.js";
2
- import { hostRunsDirectBridge, leaveSourceSessionProof, mintSourceSessionProof, registerLocalSourceSession } from "./source-session-local.js";
2
+ import { hostRunsDirectBridge, leaveSourceSessionProof, leaveSourceSessionProofForCall, mintSourceSessionProof, registerLocalSourceSession, relayBridgeCollectsProofs, } from "./source-session-local.js";
3
3
  import { resolveSourceSessionFromHookPayload } from "./source-session-hook.js";
4
4
  function isRecord(value) {
5
5
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -19,28 +19,35 @@ export function runSourceSessionPreToolHook(input) {
19
19
  const secret = new KeyStore().getToken();
20
20
  if (!secret)
21
21
  return "";
22
- let proof = mintSourceSessionProof(sessionId, toolName, secret);
23
- if (!proof) {
24
- // SessionStart can run before the JSONL exists. At first tool use it should
25
- // exist; verify once and repair the local registry without a backend call.
26
- const identity = resolveSourceSessionFromHookPayload(payload);
22
+ // Resolve the current host evidence before minting. A cached CLI ID can predate the
23
+ // desktop record, and a resumed chat can have a new CLI transcript under the same key.
24
+ if (typeof payload.transcript_path === "string" && payload.transcript_path) {
25
+ const identity = resolveSourceSessionFromHookPayload(payload, { awaitDesktopRecordMs: 3_500 });
27
26
  if (!identity)
28
- return "";
27
+ throw new Error("SOURCE_SESSION_NOT_READY: the host transcript is not readable yet. Retry this call shortly.");
28
+ if (identity.provider === "claude-code") {
29
+ identity.transcript = { path: payload.transcript_path, sessionId };
30
+ }
29
31
  registerLocalSourceSession(sessionId, identity, secret);
30
- proof = mintSourceSessionProof(sessionId, toolName, secret);
31
32
  }
33
+ const proof = mintSourceSessionProof(sessionId, toolName, secret);
32
34
  if (!proof)
33
35
  return "";
34
- // A host that runs its own bridge sends its ID for each call along with the call, so the
35
- // proof travels beside it. Rewriting the input instead makes auto mode refuse the call,
36
- // because the input no longer matches what it reviewed. A bridge reached through a relay
37
- // receives only the input. The Claude desktop app serves a session's calls through its relay
38
- // even though that session's own `claude` process launches a bridge too; it gives each
39
- // session it hosts a local_ ID.
36
+ // Rewriting the input makes auto mode refuse the call, because the input no longer matches
37
+ // what it reviewed, so there the proof travels beside the call wherever a bridge can find it.
38
+ // A host that runs its own bridge sends its ID for each call along with the call. The Claude
39
+ // desktop app serves a session's calls through its relay even though that session's own
40
+ // `claude` process launches a bridge too, and gives each session it hosts a local_ ID; its
41
+ // relay delivers only the tool name and the input, which then name the call. They name it
42
+ // less exactly than an ID does, so outside auto mode, where a call may also wait on a person
43
+ // for as long as they take, the proof stays in the input.
40
44
  const toolUseId = typeof payload.tool_use_id === "string" ? payload.tool_use_id : "";
41
45
  const desktopHosted = process.env.CLAUDE_CODE_HOST_SESSION_ID?.startsWith("local_") === true;
42
46
  if (toolUseId && !desktopHosted && hostRunsDirectBridge() && leaveSourceSessionProof(toolUseId, proof))
43
47
  return "";
48
+ if (desktopHosted && payload.permission_mode === "auto" && relayBridgeCollectsProofs()
49
+ && leaveSourceSessionProofForCall(toolName, payload.tool_input, proof))
50
+ return "";
44
51
  return JSON.stringify({
45
52
  hookSpecificOutput: {
46
53
  hookEventName: "PreToolUse",
@@ -48,7 +55,11 @@ export function runSourceSessionPreToolHook(input) {
48
55
  },
49
56
  });
50
57
  }
51
- catch {
58
+ catch (error) {
59
+ if (error instanceof Error && error.message.startsWith("SOURCE_SESSION_NOT_READY")) {
60
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse",
61
+ permissionDecision: "deny", permissionDecisionReason: error.message } });
62
+ }
52
63
  return "";
53
64
  }
54
65
  }
@@ -375,6 +375,52 @@ function claudeDesktopClaimFiles(root) {
375
375
  }
376
376
  return files;
377
377
  }
378
+ function readClaudeDesktopClaim(file) {
379
+ try {
380
+ const record = JSON.parse(fs.readFileSync(file, "utf8"));
381
+ if (!isRecord(record) || record.isArchived === true)
382
+ return null;
383
+ const providerSessionId = typeof record.sessionId === "string"
384
+ ? record.sessionId.trim()
385
+ : "";
386
+ if (!/^local_[A-Za-z0-9_-]{1,194}$/.test(providerSessionId))
387
+ return null;
388
+ const rawAliases = [record.cliSessionId, ...(Array.isArray(record.priorCliSessionIds)
389
+ ? record.priorCliSessionIds
390
+ : [])];
391
+ const aliases = [...new Set(rawAliases.map(normalizedUuid).filter((value) => !!value))]
392
+ .slice(0, 32);
393
+ const focusedAt = [record.lastFocusedAt, record.lastActivityAt, record.createdAt]
394
+ .find((value) => typeof value === "number" && Number.isFinite(value));
395
+ return {
396
+ providerSessionId,
397
+ providerSessionAliases: aliases,
398
+ focusedAt: focusedAt ?? 0,
399
+ };
400
+ }
401
+ catch {
402
+ return null;
403
+ }
404
+ }
405
+ /** The Claude desktop app's own record of a session it hosts in its Code tab. Cowork sets the
406
+ * same host session variable but keeps its sessions elsewhere, so only this record tells the two
407
+ * apart; it also names the CLI sessions whose transcripts hold the conversation. */
408
+ function claudeDesktopClaimForHostSession(hostSessionId, options) {
409
+ for (const supportRoot of resolveClaudeDesktopSupportRoots({
410
+ env: options.env,
411
+ homeDir: options.homeDir,
412
+ platform: options.platform,
413
+ })) {
414
+ for (const file of claudeDesktopClaimFiles(path.join(supportRoot, "claude-code-sessions"))) {
415
+ if (path.basename(file) !== `${hostSessionId}.json`)
416
+ continue;
417
+ const claim = readClaudeDesktopClaim(file);
418
+ if (claim?.providerSessionId === hostSessionId && claim.providerSessionAliases.length > 0)
419
+ return claim;
420
+ }
421
+ }
422
+ return null;
423
+ }
378
424
  function claudeDesktopClaimForAlias(cliSessionId, options) {
379
425
  const normalizedAlias = normalizedUuid(cliSessionId);
380
426
  if (!normalizedAlias)
@@ -387,33 +433,9 @@ function claudeDesktopClaimForAlias(cliSessionId, options) {
387
433
  })) {
388
434
  const sessionsRoot = path.join(supportRoot, "claude-code-sessions");
389
435
  for (const file of claudeDesktopClaimFiles(sessionsRoot)) {
390
- try {
391
- const record = JSON.parse(fs.readFileSync(file, "utf8"));
392
- if (!isRecord(record) || record.isArchived === true)
393
- continue;
394
- const providerSessionId = typeof record.sessionId === "string"
395
- ? record.sessionId.trim()
396
- : "";
397
- if (!/^local_[A-Za-z0-9_-]{1,194}$/.test(providerSessionId))
398
- continue;
399
- const rawAliases = [record.cliSessionId, ...(Array.isArray(record.priorCliSessionIds)
400
- ? record.priorCliSessionIds
401
- : [])];
402
- const aliases = [...new Set(rawAliases.map(normalizedUuid).filter((value) => !!value))]
403
- .slice(0, 32);
404
- if (!aliases.includes(normalizedAlias))
405
- continue;
406
- const focusedAt = [record.lastFocusedAt, record.lastActivityAt, record.createdAt]
407
- .find((value) => typeof value === "number" && Number.isFinite(value));
408
- claims.push({
409
- providerSessionId,
410
- providerSessionAliases: aliases,
411
- focusedAt: focusedAt ?? 0,
412
- });
413
- }
414
- catch {
415
- continue;
416
- }
436
+ const claim = readClaudeDesktopClaim(file);
437
+ if (claim?.providerSessionAliases.includes(normalizedAlias))
438
+ claims.push(claim);
417
439
  }
418
440
  }
419
441
  const claimsByConversation = new Map();
@@ -534,6 +556,19 @@ export function resolveSourceSessionRequestContext(metadata, options = {}) {
534
556
  // "Claude Code" and expose both IDs. The outer host session is the durable Cowork conversation;
535
557
  // it must win over the nested CLI session whenever Anthropic supplies both host-owned values.
536
558
  if (isClaudeHost && coworkCandidate) {
559
+ // The desktop app's Code tab supplies the same variable. Its sessions are Claude Code
560
+ // sessions, with their transcripts under ~/.claude/projects rather than in Cowork's folders.
561
+ const codeTab = claudeDesktopClaimForHostSession(coworkCandidate, options);
562
+ if (codeTab) {
563
+ return {
564
+ sourceSession: verifiedClaudeDesktopSession(codeTab.providerSessionId, codeTab.providerSessionAliases),
565
+ isSubagent: false,
566
+ lineageStatus: "not_applicable",
567
+ };
568
+ }
569
+ if (env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop") {
570
+ throw new Error("SOURCE_SESSION_NOT_READY: Claude Desktop has not written this Code tab session record yet. Retry this call shortly.");
571
+ }
537
572
  return {
538
573
  sourceSession: verifiedSourceSession("cowork", coworkCandidate, SOURCE_SESSION_MCP_METADATA_EVIDENCE),
539
574
  isSubagent: false,
@@ -319,6 +319,16 @@ function codexTurn(rows, sessionId, pendingNote, keptNotes = new Map()) {
319
319
  throw new Error("SOURCE_SESSION_EMPTY");
320
320
  return { messages, turnOpen };
321
321
  }
322
+ /** A signed locator still has to resolve inside this host's configured transcript root. */
323
+ function claudeTranscriptPath(file, root, sessionId) {
324
+ const real = fs.realpathSync(file);
325
+ const relative = path.relative(root, real);
326
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)
327
+ || path.basename(real) !== `${sessionId}.jsonl` || !fs.statSync(real).isFile()) {
328
+ throw new Error("SOURCE_SESSION_MISMATCH");
329
+ }
330
+ return real;
331
+ }
322
332
  /** Derive current evidence from one verified host transcript, never tool arguments. */
323
333
  export function readStrictRawSession(identity, assistantMessageId) {
324
334
  return readStrictRawSessionState(identity, assistantMessageId).rawData;
@@ -338,8 +348,79 @@ export function readStrictRawSessionState(identity, assistantMessageId, pendingN
338
348
  const root = resolveClaudeProjectsDir();
339
349
  if (!root || ids.length === 0)
340
350
  throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
341
- file = locate(root, (name) => ids.some((id) => name === `${id}.jsonl`));
342
- ({ messages, turnOpen } = claudeTurn(parseLines(file), new Set(ids)));
351
+ const source = identity.transcript;
352
+ const activeId = source?.sessionId ?? ids[0];
353
+ if (!ids.includes(activeId))
354
+ throw new Error("SOURCE_SESSION_MISMATCH");
355
+ const files = new Map();
356
+ if (source) {
357
+ const real = claudeTranscriptPath(source.path, root, activeId);
358
+ files.set(activeId, real);
359
+ // Resumed CLI files normally share a project folder. Exact host-owned paths avoid
360
+ // re-indexing every unrelated project on each save.
361
+ for (const id of ids) {
362
+ const sibling = path.join(path.dirname(real), `${id}.jsonl`);
363
+ if (!files.has(id) && fs.existsSync(sibling))
364
+ files.set(id, claudeTranscriptPath(sibling, root, id));
365
+ }
366
+ }
367
+ if (ids.some(id => !files.has(id))) {
368
+ const pending = [root];
369
+ let inspected = 0;
370
+ while (pending.length) {
371
+ const directory = pending.pop();
372
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
373
+ const candidate = path.join(directory, entry.name);
374
+ if (entry.isDirectory())
375
+ pending.push(candidate);
376
+ else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
377
+ if (++inspected > MAX_FILES)
378
+ throw new Error("SOURCE_INDEX_TOO_LARGE");
379
+ const id = entry.name.slice(0, -6);
380
+ if (!ids.includes(id))
381
+ continue;
382
+ const previous = files.get(id);
383
+ if (previous && previous !== candidate)
384
+ throw new Error("SOURCE_SESSION_AMBIGUOUS");
385
+ files.set(id, candidate);
386
+ }
387
+ }
388
+ }
389
+ }
390
+ const currentFile = files.get(activeId);
391
+ if (!currentFile)
392
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
393
+ file = currentFile;
394
+ messages = [];
395
+ turnOpen = false;
396
+ const positions = new Map();
397
+ // Desktop declares prior CLI sessions in order. Current is last; repeated native
398
+ // message IDs in resumed files retain their original content and ledger position.
399
+ const chronologicalIds = [...ids.slice(1), ids[0]];
400
+ for (const id of chronologicalIds.slice(0, chronologicalIds.indexOf(activeId) + 1)) {
401
+ const transcript = files.get(id);
402
+ if (!transcript)
403
+ continue;
404
+ const parsed = claudeTurn(parseLines(transcript), new Set(ids));
405
+ let previousPosition = -1;
406
+ for (const message of parsed.messages) {
407
+ const position = positions.get(message.id);
408
+ if (position !== undefined) {
409
+ if (JSON.stringify(messages[position]) !== JSON.stringify(message))
410
+ throw new Error("SOURCE_SESSION_MESSAGE_CHANGED");
411
+ if (position <= previousPosition)
412
+ throw new Error("SOURCE_SESSION_INVALID_LINEAGE");
413
+ previousPosition = position;
414
+ }
415
+ else {
416
+ previousPosition = messages.length;
417
+ positions.set(message.id, previousPosition);
418
+ messages.push(message);
419
+ }
420
+ }
421
+ if (id === activeId)
422
+ turnOpen = parsed.turnOpen;
423
+ }
343
424
  }
344
425
  else if (identity.provider === "cowork") {
345
426
  const source = resolveCoworkSource(identity.providerSessionId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@echomem/mcp",
3
- "version": "1.5.0",
3
+ "version": "1.5.1",
4
4
  "description": "EchoMem MCP bridge for cross-agent memory, local history import, and recall",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -36,7 +36,7 @@
36
36
  "test:config-safety": "npm run build && node test/config-safety.test.mjs",
37
37
  "test:billing-ui": "npm run build && node test/setup-ui.test.mjs billing",
38
38
  "test:mcp-control": "npm run build && node test/mcp-control.test.mjs",
39
- "test": "npm run build && node test/source-session.test.mjs && node test/source-session-stress.test.mjs && node test/source-session-proof.test.mjs && node test/shared-desktop-proof.test.mjs && node test/cowork-source.test.mjs && node test/source-snapshot-export.test.mjs && node test/cowork-ticket-session.test.mjs && node test/strict-raw-session.test.mjs && node test/agent-messages-fallback.test.mjs && node test/pending-save.test.mjs && node test/save-retry.test.mjs && node test/gemini-save-contract.test.mjs && node test/ticket-review-format.test.mjs && node test/schema-parity.test.mjs && node test/ticket-overview.test.mjs && node test/ticket-stewardship-contract.test.mjs && node test/stewardship-integration.test.mjs && node test/source-session-hook.test.mjs && node test/local-data-paths.test.mjs && node test/crypto.test.mjs && node test/tool-map-cache.test.mjs && node test/integration.test.mjs && node test/onboarding-resilience.test.mjs && node test/local-auth.test.mjs && node test/product-analytics.test.mjs && node test/retrieval-only.test.mjs && node test/no-restart.test.mjs && node test/canonical-golden.test.mjs && node test/tools.test.mjs && node test/workspace-selector.test.mjs && node test/group-map.test.mjs && node test/update-check.test.mjs && node test/headless-runtime.test.mjs && node test/claude-code-config.test.mjs && node test/config-safety.test.mjs && node test/mcp-control.test.mjs && node test/delete.test.mjs && node test/low-touch-tools.test.mjs && node test/migrate.test.mjs && node test/restart-recovery.test.mjs && node test/desktop-save-activity.test.mjs && node test/desktop-presence.test.mjs && node test/durable-entry.test.mjs && node test/lifecycle-hook-refresh.test.mjs && node test/durable-reexec.test.mjs && node test/doctor.test.mjs && node test/environment-matrix.test.mjs && node test/request-failure.test.mjs && node test/turn-end-save.test.mjs && node test/in-turn-save.test.mjs && node test/save-receipt.test.mjs && node test/proof-beside-call.test.mjs && node test/code-tab-proof-delivery.test.mjs && node test/full-turn-reading.test.mjs && node test/memory-links.test.mjs && node test/notch-reply-contract.test.mjs",
39
+ "test": "npm run build && node test/source-session.test.mjs && node test/source-session-stress.test.mjs && node test/source-session-proof.test.mjs && node test/shared-desktop-proof.test.mjs && node test/cowork-source.test.mjs && node test/source-snapshot-export.test.mjs && node test/cowork-ticket-session.test.mjs && node test/strict-raw-session.test.mjs && node test/agent-messages-fallback.test.mjs && node test/pending-save.test.mjs && node test/save-retry.test.mjs && node test/gemini-save-contract.test.mjs && node test/ticket-review-format.test.mjs && node test/schema-parity.test.mjs && node test/ticket-overview.test.mjs && node test/ticket-stewardship-contract.test.mjs && node test/stewardship-integration.test.mjs && node test/source-session-hook.test.mjs && node test/local-data-paths.test.mjs && node test/crypto.test.mjs && node test/tool-map-cache.test.mjs && node test/integration.test.mjs && node test/onboarding-resilience.test.mjs && node test/local-auth.test.mjs && node test/product-analytics.test.mjs && node test/retrieval-only.test.mjs && node test/no-restart.test.mjs && node test/canonical-golden.test.mjs && node test/tools.test.mjs && node test/workspace-selector.test.mjs && node test/group-map.test.mjs && node test/update-check.test.mjs && node test/headless-runtime.test.mjs && node test/claude-code-config.test.mjs && node test/config-safety.test.mjs && node test/mcp-control.test.mjs && node test/delete.test.mjs && node test/low-touch-tools.test.mjs && node test/migrate.test.mjs && node test/restart-recovery.test.mjs && node test/desktop-save-activity.test.mjs && node test/desktop-presence.test.mjs && node test/desktop-workspace.test.mjs && node test/durable-entry.test.mjs && node test/lifecycle-hook-refresh.test.mjs && node test/durable-reexec.test.mjs && node test/doctor.test.mjs && node test/environment-matrix.test.mjs && node test/request-failure.test.mjs && node test/turn-end-save.test.mjs && node test/in-turn-save.test.mjs && node test/save-receipt.test.mjs && node test/proof-beside-call.test.mjs && node test/code-tab-proof-delivery.test.mjs && node --import tsx test/session-lifecycle.test.mjs && node test/full-turn-reading.test.mjs && node test/memory-links.test.mjs && node test/notch-reply-contract.test.mjs",
40
40
  "prepack": "npm run build",
41
41
  "test:save-trace": "npm run build && node --test test/save-local-trace.test.mjs",
42
42
  "test:backend-policy": "npm run build && node test/backend-policy.test.mjs"