@echomem/mcp 1.5.0 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/desktop-workspace.js +48 -0
- package/dist/index.js +109 -32
- package/dist/local-data-paths.js +5 -0
- package/dist/request-failure.js +9 -0
- package/dist/source-session-hook.js +90 -6
- package/dist/source-session-local.js +160 -11
- package/dist/source-session-pretool-hook.js +33 -17
- package/dist/source-session.js +62 -27
- package/dist/source-snapshot-export.js +4 -1
- package/dist/strict-raw-session.js +83 -2
- package/package.json +2 -2
|
@@ -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,9 +24,9 @@ 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
|
-
import { requestFailureDetails } from "./request-failure.js";
|
|
29
|
+
import { BACKEND_UNREACHABLE, backendUnreachable, requestFailureDetails } from "./request-failure.js";
|
|
29
30
|
import { contextHealthMarkdown, recomposeCapsuleMarkdown } from "./hud/api.js";
|
|
30
31
|
import { refreshInstalledLifecycleHooks } from "./hud/hooks.js";
|
|
31
32
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -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)
|
|
@@ -118,6 +121,9 @@ function stringifyErrorValue(value) {
|
|
|
118
121
|
return String(value);
|
|
119
122
|
}
|
|
120
123
|
function describeError(error) {
|
|
124
|
+
// The socket error ("connect ECONNREFUSED 127.0.0.1:3000") tells a user nothing.
|
|
125
|
+
if (backendUnreachable(error))
|
|
126
|
+
return BACKEND_UNREACHABLE;
|
|
121
127
|
if (axios.isAxiosError(error)) {
|
|
122
128
|
const status = error.response?.status;
|
|
123
129
|
const body = stringifyErrorValue(error.response?.data);
|
|
@@ -795,6 +801,9 @@ class EchoMemApiClient {
|
|
|
795
801
|
whoamiCache = null;
|
|
796
802
|
/** One id per bridge process — groups all saves from this coding session under a single EchoMem context. */
|
|
797
803
|
sessionId = randomUUID();
|
|
804
|
+
/** Contexts whose transcript the backend could not reconcile with what the session saved
|
|
805
|
+
* before; their saves use the agent's turns for as long as this bridge runs. */
|
|
806
|
+
unreconciledContexts = new Set();
|
|
798
807
|
encConfigPromise = null;
|
|
799
808
|
deleteConfirmations = new Map();
|
|
800
809
|
constructor(store) {
|
|
@@ -888,14 +897,21 @@ class EchoMemApiClient {
|
|
|
888
897
|
}
|
|
889
898
|
async bindSourceSession(identity, persistForBridge = true) {
|
|
890
899
|
this.synchronizeAccountContext();
|
|
900
|
+
const generation = this.accountGeneration;
|
|
891
901
|
if (identity.evidence === SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE && persistForBridge) {
|
|
892
902
|
throw new Error("A provisional Cloud Cowork identity cannot become shared bridge state");
|
|
893
903
|
}
|
|
894
904
|
const cached = this.sourceSessionsByCanonicalKey.get(identity.canonicalKey);
|
|
895
|
-
if (cached)
|
|
905
|
+
if (cached && JSON.stringify(cached.providerSessionAliases) === JSON.stringify(identity.providerSessionAliases)
|
|
906
|
+
&& cached.evidence === identity.evidence) {
|
|
907
|
+
// Reuse the server binding, while this call retains its freshly verified source.
|
|
908
|
+
const current = { ...cached, ...identity,
|
|
909
|
+
transcript: identity.evidence === SOURCE_SESSION_CLOUD_TOOL_ARGUMENT_EVIDENCE ? undefined : identity.transcript,
|
|
910
|
+
contextId: cached.contextId,
|
|
911
|
+
canonicalKey: cached.canonicalKey, providerSessionId: cached.providerSessionId };
|
|
896
912
|
if (persistForBridge)
|
|
897
|
-
this.boundSourceSession =
|
|
898
|
-
return { ...
|
|
913
|
+
this.boundSourceSession = current;
|
|
914
|
+
return { ...current, created: false };
|
|
899
915
|
}
|
|
900
916
|
const response = await this.axios.post("/api/extension/source-sessions/bind", {
|
|
901
917
|
provider: identity.provider,
|
|
@@ -904,6 +920,9 @@ class EchoMemApiClient {
|
|
|
904
920
|
evidence: identity.evidence,
|
|
905
921
|
runtime_version: MCP_PACKAGE_VERSION,
|
|
906
922
|
}, { headers: { "X-EchoMem-Origin-Channel": "local_mcp" } });
|
|
923
|
+
this.synchronizeAccountContext();
|
|
924
|
+
if (generation !== this.accountGeneration)
|
|
925
|
+
throw new Error("ACCOUNT_CHANGED_DURING_BIND: retry with the current account.");
|
|
907
926
|
const contextId = readString(response.data, "contextId");
|
|
908
927
|
const canonicalKey = readString(response.data, "canonicalKey");
|
|
909
928
|
const provider = readString(response.data, "provider");
|
|
@@ -921,8 +940,9 @@ class EchoMemApiClient {
|
|
|
921
940
|
canonicalKey,
|
|
922
941
|
contextId,
|
|
923
942
|
};
|
|
924
|
-
|
|
925
|
-
this.sourceSessionsByCanonicalKey.set(canonicalKey,
|
|
943
|
+
const binding = { ...bound, transcript: undefined };
|
|
944
|
+
this.sourceSessionsByCanonicalKey.set(identity.canonicalKey, binding);
|
|
945
|
+
this.sourceSessionsByCanonicalKey.set(canonicalKey, binding);
|
|
926
946
|
if (this.sourceSessionsByCanonicalKey.size > 64) {
|
|
927
947
|
const oldestKey = this.sourceSessionsByCanonicalKey.keys().next().value;
|
|
928
948
|
if (oldestKey)
|
|
@@ -959,6 +979,9 @@ class EchoMemApiClient {
|
|
|
959
979
|
if (explicit)
|
|
960
980
|
return explicit;
|
|
961
981
|
const response = await this.axios.get("/api/extension/social/groups/current");
|
|
982
|
+
const chosen = chosenDesktopWorkspace(response.data);
|
|
983
|
+
if (chosen)
|
|
984
|
+
return chosen;
|
|
962
985
|
const group = isRecord(response.data?.group) ? response.data.group : null;
|
|
963
986
|
const id = group ? readString(group, "id") : undefined;
|
|
964
987
|
if (!id) {
|
|
@@ -997,22 +1020,27 @@ class EchoMemApiClient {
|
|
|
997
1020
|
});
|
|
998
1021
|
return { workspaceId: id, data: response.data };
|
|
999
1022
|
}
|
|
1000
|
-
|
|
1023
|
+
/** `notchTeam`: for a request the user made (filing, a publication preview),
|
|
1024
|
+
* the team chosen in the Notch answers when no workspace is established. A
|
|
1025
|
+
* routine review leaves it off and is skipped instead. */
|
|
1026
|
+
async reviewWorkspaceTicketSession(args, options = {}) {
|
|
1001
1027
|
const parsed = reviewWorkspaceTicketSessionSchema.parse(args ?? {});
|
|
1002
1028
|
const sourceSession = this.getRequestSourceSession();
|
|
1003
1029
|
if (!sourceSession)
|
|
1004
1030
|
return null;
|
|
1005
|
-
const
|
|
1031
|
+
const review = (workspaceId) => this.axios.get("/api/extension/workspace-ticket-actions", {
|
|
1006
1032
|
params: {
|
|
1007
1033
|
contextId: sourceSession.contextId,
|
|
1008
|
-
workspaceId
|
|
1034
|
+
workspaceId,
|
|
1009
1035
|
groupId: parsed.groupId,
|
|
1010
1036
|
memoryThreshold: parsed.memoryThreshold,
|
|
1011
1037
|
ticketId: parsed.ticketId,
|
|
1012
1038
|
},
|
|
1013
1039
|
timeout: TICKET_REVIEW_TIMEOUT_MS,
|
|
1014
1040
|
});
|
|
1015
|
-
|
|
1041
|
+
const response = await review(parsed.workspaceId);
|
|
1042
|
+
const chosen = options.notchTeam ? chosenDesktopWorkspace(response.data) : undefined;
|
|
1043
|
+
return chosen ? (await review(chosen)).data : response.data;
|
|
1016
1044
|
}
|
|
1017
1045
|
async acknowledgeWorkspaceTicketReview(args) {
|
|
1018
1046
|
const parsed = acknowledgeWorkspaceTicketReviewSchema.parse(args ?? {});
|
|
@@ -1206,7 +1234,7 @@ class EchoMemApiClient {
|
|
|
1206
1234
|
if (this.encConfigPromise === request)
|
|
1207
1235
|
this.encConfigPromise = null; // allow retry next call
|
|
1208
1236
|
console.error(`[encryption] config fetch failed: ${describeError(error)} — refusing memory access`);
|
|
1209
|
-
throw new EncryptionStatusUnavailableError("EchoMem could not verify the account encryption state");
|
|
1237
|
+
throw new EncryptionStatusUnavailableError("EchoMem could not verify the account encryption state", { cause: error });
|
|
1210
1238
|
});
|
|
1211
1239
|
this.encConfigPromise = request;
|
|
1212
1240
|
}
|
|
@@ -1550,6 +1578,9 @@ class EchoMemApiClient {
|
|
|
1550
1578
|
if (parsed.conversation !== undefined) {
|
|
1551
1579
|
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
1580
|
}
|
|
1581
|
+
if (boundSourceSession?.contextId && this.unreconciledContexts.has(boundSourceSession.contextId)) {
|
|
1582
|
+
return this.saveFromAgentMessages(parsed, { boundSourceSession, groupSharingScopeId, receiptToken, report, reason: SOURCE_RECOVERY_REQUIRED });
|
|
1583
|
+
}
|
|
1553
1584
|
// A verified local transcript always wins; agent-supplied turns are used only by hosts
|
|
1554
1585
|
// whose transcript this bridge cannot read (Cursor, Claude Desktop chat, Cloud Cowork).
|
|
1555
1586
|
let rawSession;
|
|
@@ -1693,12 +1724,27 @@ class EchoMemApiClient {
|
|
|
1693
1724
|
finishLocalTrace({ state: "FAILED", elapsedMs: Date.now() - traceStarted,
|
|
1694
1725
|
response: axios.isAxiosError(error) ? error.response?.data ?? { success: false, error: "TRANSPORT_ERROR" } : { success: false, error: "LOCAL_SAVE_ERROR" },
|
|
1695
1726
|
httpStatus: axios.isAxiosError(error) ? error.response?.status : undefined });
|
|
1727
|
+
// The agent's turns are saved next, under their own activity.
|
|
1728
|
+
if (saveFailureCode(error) === SOURCE_RECOVERY_REQUIRED) {
|
|
1729
|
+
report.activity?.discard();
|
|
1730
|
+
throw error;
|
|
1731
|
+
}
|
|
1696
1732
|
// A save that outlives the caller's wait still reports how it ended.
|
|
1697
1733
|
report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
|
|
1698
1734
|
throwIfProcessingQuotaExceeded(error);
|
|
1699
1735
|
throw error;
|
|
1700
1736
|
}
|
|
1701
|
-
}, waitForCompletion)
|
|
1737
|
+
}, waitForCompletion).catch(error => {
|
|
1738
|
+
if (saveFailureCode(error) !== SOURCE_RECOVERY_REQUIRED)
|
|
1739
|
+
throw error;
|
|
1740
|
+
// This session saved before from the agent's turns, on a bridge that could not read its
|
|
1741
|
+
// transcript, and the backend cannot line the transcript up with those memories. That holds
|
|
1742
|
+
// for the rest of the session, so it keeps saving the way it did, in the same context.
|
|
1743
|
+
this.unreconciledContexts.add(boundSourceSession.contextId);
|
|
1744
|
+
return null;
|
|
1745
|
+
});
|
|
1746
|
+
if (!result)
|
|
1747
|
+
return this.saveFromAgentMessages(parsed, { boundSourceSession, groupSharingScopeId, receiptToken, report, reason: SOURCE_RECOVERY_REQUIRED });
|
|
1702
1748
|
this.synchronizeAccountContext();
|
|
1703
1749
|
if (generation !== this.accountGeneration)
|
|
1704
1750
|
throw new Error("ACCOUNT_CHANGED_DURING_SAVE: the result was withheld because the signed-in account changed.");
|
|
@@ -1822,7 +1868,9 @@ class EchoMemApiClient {
|
|
|
1822
1868
|
void this.refreshGroupMemoryMapCache();
|
|
1823
1869
|
}
|
|
1824
1870
|
}
|
|
1825
|
-
|
|
1871
|
+
// With no source session, the scope was this save's conversation key: the receipt hands
|
|
1872
|
+
// it back so the agent's later saves land in the same context.
|
|
1873
|
+
return { ...response.data, groupSharingScopeId: ctx.groupSharingScopeId, scopeKeysConversation: !ctx.boundSourceSession };
|
|
1826
1874
|
}
|
|
1827
1875
|
catch (error) {
|
|
1828
1876
|
ctx.report.activity?.finish({ phase: "failed", reason: desktopFailureReason(error) });
|
|
@@ -1948,7 +1996,7 @@ class EchoMemApiClient {
|
|
|
1948
1996
|
async searchOthersMemories(args) {
|
|
1949
1997
|
const parsed = othersSchema.parse(args ?? {});
|
|
1950
1998
|
try {
|
|
1951
|
-
const
|
|
1999
|
+
const search = (workspaceId) => this.axios.post("/api/extension/social/public-memories/search", {
|
|
1952
2000
|
query: parsed.query,
|
|
1953
2001
|
limit: parsed.limit,
|
|
1954
2002
|
target: parsed.target,
|
|
@@ -1960,12 +2008,14 @@ class EchoMemApiClient {
|
|
|
1960
2008
|
kPerUser: parsed.kPerUser,
|
|
1961
2009
|
similarityThreshold: parsed.similarityThreshold,
|
|
1962
2010
|
timeFrameDays: parsed.timeFrameDays,
|
|
1963
|
-
workspaceId
|
|
2011
|
+
workspaceId,
|
|
1964
2012
|
scope: parsed.scope,
|
|
1965
2013
|
requestId: this.sessionId,
|
|
1966
2014
|
source: "mcp_friend_public_memory_search",
|
|
1967
2015
|
});
|
|
1968
|
-
|
|
2016
|
+
const response = await search(parsed.workspaceId ?? parsed.groupId);
|
|
2017
|
+
const chosen = chosenDesktopWorkspace(response.data);
|
|
2018
|
+
return chosen ? (await search(chosen)).data : response.data;
|
|
1969
2019
|
}
|
|
1970
2020
|
catch (error) {
|
|
1971
2021
|
throw new Error(`search_others_memories failed against ${ECHO_API_BASE_URL}: ${describeError(error)}`);
|
|
@@ -2007,11 +2057,13 @@ class EchoMemApiClient {
|
|
|
2007
2057
|
const parsed = groupContextSchema.parse(args ?? {});
|
|
2008
2058
|
try {
|
|
2009
2059
|
const workspaceId = parsed.workspaceId ?? parsed.groupId;
|
|
2010
|
-
const path =
|
|
2011
|
-
? `/api/extension/social/groups/current?workspaceId=${encodeURIComponent(
|
|
2060
|
+
const path = (id) => id
|
|
2061
|
+
? `/api/extension/social/groups/current?workspaceId=${encodeURIComponent(id)}`
|
|
2012
2062
|
: "/api/extension/social/groups/current";
|
|
2013
|
-
const response = await this.axios.get(path);
|
|
2014
|
-
|
|
2063
|
+
const response = await this.axios.get(path(workspaceId));
|
|
2064
|
+
// Several workspaces and none named: the team chosen in the Notch answers.
|
|
2065
|
+
const chosen = chosenDesktopWorkspace(response.data);
|
|
2066
|
+
return chosen ? (await this.axios.get(path(chosen))).data : response.data;
|
|
2015
2067
|
}
|
|
2016
2068
|
catch (error) {
|
|
2017
2069
|
throw new Error(`get_group_context failed against ${ECHO_API_BASE_URL}: ${describeError(error)}`);
|
|
@@ -2058,7 +2110,7 @@ class EchoMemApiClient {
|
|
|
2058
2110
|
throw new Error("currentSession cannot be combined with a different contextId.");
|
|
2059
2111
|
}
|
|
2060
2112
|
// 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 });
|
|
2113
|
+
const result = await this.reviewWorkspaceTicketSession({ ...parsed, limit: undefined }, { notchTeam: true });
|
|
2062
2114
|
const review = isRecord(result?.review) ? result.review : {};
|
|
2063
2115
|
const workspaceId = readString(review, "workspaceId");
|
|
2064
2116
|
if (!workspaceId)
|
|
@@ -2274,6 +2326,7 @@ class EchoMemMCPServer {
|
|
|
2274
2326
|
isSubagent: false,
|
|
2275
2327
|
lineageStatus: "unbound",
|
|
2276
2328
|
};
|
|
2329
|
+
let sourceNotReady;
|
|
2277
2330
|
try {
|
|
2278
2331
|
sourceResolution = resolveSourceSessionRequestContext(extra._meta, {
|
|
2279
2332
|
hostPlatform: this.getMcpClientAnalytics().host_platform,
|
|
@@ -2282,14 +2335,20 @@ class EchoMemMCPServer {
|
|
|
2282
2335
|
env: this.mcpClientName?.startsWith("local-agent-mode-") ? {} : process.env,
|
|
2283
2336
|
});
|
|
2284
2337
|
}
|
|
2285
|
-
catch {
|
|
2338
|
+
catch (error) {
|
|
2339
|
+
if (error instanceof Error && error.message.startsWith("SOURCE_SESSION_NOT_READY"))
|
|
2340
|
+
sourceNotReady = error;
|
|
2286
2341
|
// Malformed host metadata is not model input. Ignore it and retain the explicit fallback.
|
|
2287
2342
|
}
|
|
2288
|
-
// The hook leaves a call's proof under the host's ID for that call
|
|
2289
|
-
//
|
|
2343
|
+
// The hook leaves a call's proof under the host's ID for that call, or, for a call a relay
|
|
2344
|
+
// carries, under its tool name and input; a hook that could do neither put it in the input.
|
|
2290
2345
|
const toolUseId = isRecord(extra._meta) ? extra._meta["claudecode/toolUseId"] : undefined;
|
|
2346
|
+
const inInput = isRecord(request.params.arguments) ? request.params.arguments.sourceSessionProof : undefined;
|
|
2291
2347
|
const sourceSessionProof = (typeof toolUseId === "string" && toolUseId ? takeSourceSessionProof(toolUseId) : null)
|
|
2292
|
-
?? (
|
|
2348
|
+
?? (/^(local-agent-mode-|claude)/i.test(this.mcpClientName ?? "")
|
|
2349
|
+
? takeSourceSessionProofForCall(`mcp__echomem__${request.params.name}`, request.params.arguments, typeof inInput === "string" ? inInput : undefined)
|
|
2350
|
+
: null)
|
|
2351
|
+
?? inInput;
|
|
2293
2352
|
// Signed out, a proof cannot be checked and nothing can be written: the tool itself then
|
|
2294
2353
|
// says that EchoMem is not connected.
|
|
2295
2354
|
if (sourceSessionProof !== undefined && this.client.hasToken()) {
|
|
@@ -2321,6 +2380,8 @@ class EchoMemMCPServer {
|
|
|
2321
2380
|
lineageStatus: "top_level",
|
|
2322
2381
|
};
|
|
2323
2382
|
}
|
|
2383
|
+
if (sourceNotReady && !sourceResolution.sourceSession)
|
|
2384
|
+
throw sourceNotReady;
|
|
2324
2385
|
let provisionalCloudSession = null;
|
|
2325
2386
|
try {
|
|
2326
2387
|
provisionalCloudSession = resolveCloudCoworkSessionFromToolArguments(toolArgs);
|
|
@@ -2595,6 +2656,14 @@ class EchoMemMCPServer {
|
|
|
2595
2656
|
],
|
|
2596
2657
|
};
|
|
2597
2658
|
}
|
|
2659
|
+
// Whichever request met the dead address first, say the one thing that is wrong.
|
|
2660
|
+
if (backendUnreachable(error instanceof EncryptionStatusUnavailableError ? error.cause : error)) {
|
|
2661
|
+
const outcome = canonicalName === canonicalToolNames.save ? "nothing was saved" : "nothing was returned or changed";
|
|
2662
|
+
return {
|
|
2663
|
+
content: [{ type: "text", text: `${BACKEND_UNREACHABLE}; ${outcome}.` }],
|
|
2664
|
+
isError: true,
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2598
2667
|
if (error instanceof EncryptionStatusUnavailableError) {
|
|
2599
2668
|
return {
|
|
2600
2669
|
content: [{
|
|
@@ -2815,7 +2884,7 @@ Details: ${m.details || "N/A"}`)
|
|
|
2815
2884
|
rec.conversation_chars = text.length;
|
|
2816
2885
|
rec.save_source = typeof a?.source === "string" ? a.source : sourceFallback;
|
|
2817
2886
|
}
|
|
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);
|
|
2887
|
+
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
2888
|
if (!success)
|
|
2820
2889
|
throw new Error(`EchoMem API Error: ${error}`);
|
|
2821
2890
|
if (isPassthrough)
|
|
@@ -2935,9 +3004,15 @@ Details: ${m.details || "N/A"}`)
|
|
|
2935
3004
|
receipt,
|
|
2936
3005
|
checkpointReceipt,
|
|
2937
3006
|
pendingNotice,
|
|
2938
|
-
|
|
2939
|
-
?
|
|
2940
|
-
:
|
|
3007
|
+
typeof groupSharingScopeId !== "string" || !groupSharingScopeId
|
|
3008
|
+
? ""
|
|
3009
|
+
: GROUP_SESSION_SHARING_PROMPTS_ENABLED
|
|
3010
|
+
? `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.`
|
|
3011
|
+
// A host with no readable transcript and no session hook cannot be told apart from the
|
|
3012
|
+
// other conversations on its bridge, so the agent carries the key between its saves.
|
|
3013
|
+
: scopeKeysConversation === true
|
|
3014
|
+
? `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.`
|
|
3015
|
+
: "",
|
|
2941
3016
|
typeof memoriesDiscarded === "number" && memoriesDiscarded > 0
|
|
2942
3017
|
? `${memoriesDiscarded} additional memories were not stored because your active-memory limit was reached.`
|
|
2943
3018
|
: "",
|
|
@@ -3181,7 +3256,7 @@ Details: ${m.details || "N/A"}`)
|
|
|
3181
3256
|
}
|
|
3182
3257
|
async handleFindWorkspaceTicketCandidates(args) {
|
|
3183
3258
|
const parsed = findWorkspaceTicketCandidatesSchema.parse(args ?? {});
|
|
3184
|
-
const result = await this.client.reviewWorkspaceTicketSession(parsed);
|
|
3259
|
+
const result = await this.client.reviewWorkspaceTicketSession(parsed, { notchTeam: true });
|
|
3185
3260
|
if (!result) {
|
|
3186
3261
|
return {
|
|
3187
3262
|
content: [{
|
|
@@ -4338,7 +4413,9 @@ Details: ${m.details || "N/A"}`;
|
|
|
4338
4413
|
const transport = new StdioServerTransport();
|
|
4339
4414
|
// Claude Desktop's shared bridge is reached through a relay that carries only a call's input.
|
|
4340
4415
|
this.server.oninitialized = () => {
|
|
4341
|
-
if (
|
|
4416
|
+
if (this.server.getClientVersion()?.name?.startsWith("local-agent-mode-"))
|
|
4417
|
+
registerRelayBridge();
|
|
4418
|
+
else
|
|
4342
4419
|
registerDirectBridge();
|
|
4343
4420
|
};
|
|
4344
4421
|
await this.server.connect(transport);
|
package/dist/local-data-paths.js
CHANGED
|
@@ -99,6 +99,11 @@ export function resolveClaudeProjectsDir(opts = {}) {
|
|
|
99
99
|
const root = configuredRoot("CLAUDE_CONFIG_DIR", ".claude", opts);
|
|
100
100
|
return resolveReadableDirectory(root ? path.join(root, "projects") : null);
|
|
101
101
|
}
|
|
102
|
+
/** Claude Code publishes one live process record per PID in the active profile. */
|
|
103
|
+
export function resolveClaudeProcessSessionsDir() {
|
|
104
|
+
const root = configuredRoot("CLAUDE_CONFIG_DIR", ".claude");
|
|
105
|
+
return resolveReadableDirectory(root ? path.join(root, "sessions") : null);
|
|
106
|
+
}
|
|
102
107
|
/**
|
|
103
108
|
* Cursor's per-project data root. Its Agent writes one transcript per conversation at
|
|
104
109
|
* `projects/<slug>/agent-transcripts/<uuid>/<uuid>.jsonl`. Cursor itself honours no profile
|
package/dist/request-failure.js
CHANGED
|
@@ -30,3 +30,12 @@ export function requestFailureDetails(error) {
|
|
|
30
30
|
}
|
|
31
31
|
return { errorCode: analyticsErrorCode(error) === "timeout" ? "timeout" : "network" };
|
|
32
32
|
}
|
|
33
|
+
// Node reports these when no connection to the backend was made, so the
|
|
34
|
+
// request never arrived. A reset or a timeout is not among them: the backend
|
|
35
|
+
// may have received that request.
|
|
36
|
+
const UNREACHABLE_CODES = new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH"]);
|
|
37
|
+
export const BACKEND_UNREACHABLE = "EchoMem's server can't be reached";
|
|
38
|
+
/** True when a backend request failed because nothing answered at its address. */
|
|
39
|
+
export function backendUnreachable(error) {
|
|
40
|
+
return axios.isAxiosError(error) && !error.response && UNREACHABLE_CODES.has(error.code ?? "");
|
|
41
|
+
}
|
|
@@ -5,8 +5,10 @@ import path from "node:path";
|
|
|
5
5
|
import axios from "axios";
|
|
6
6
|
import { KeyStore } from "./keystore.js";
|
|
7
7
|
import { MCP_PACKAGE_VERSION } from "./package-metadata.js";
|
|
8
|
-
import {
|
|
8
|
+
import { resolveClaudeProcessSessionsDir } from "./local-data-paths.js";
|
|
9
|
+
import { hookParentPids, registeredDesktopSession, registerLocalSourceSession } from "./source-session-local.js";
|
|
9
10
|
import { SOURCE_SESSION_HOOK_EVIDENCE, verifiedClaudeDesktopSession, verifiedSourceSession, } from "./source-session.js";
|
|
11
|
+
export const DESKTOP_RECORD_WAIT_MS = 3_500;
|
|
10
12
|
const API_BASE = (resolveBackendURL()).replace(/\/$/, "");
|
|
11
13
|
const MAX_HEAD_BYTES = 256 * 1024;
|
|
12
14
|
const MAX_CLAUDE_DESKTOP_INDEX_FILES = 2_000;
|
|
@@ -58,10 +60,10 @@ function claudeDesktopSessionsRoot() {
|
|
|
58
60
|
|| path.join(process.env.HOME || "", "Library", "Application Support", "Claude");
|
|
59
61
|
return path.join(support, "claude-code-sessions");
|
|
60
62
|
}
|
|
61
|
-
function readClaudeDesktopClaim(file) {
|
|
63
|
+
function readClaudeDesktopClaim(file, exactHost = false) {
|
|
62
64
|
try {
|
|
63
65
|
const stat = fs.statSync(file);
|
|
64
|
-
if (!stat.isFile() || stat.size > MAX_HEAD_BYTES)
|
|
66
|
+
if (!stat.isFile() || (!exactHost && stat.size > MAX_HEAD_BYTES))
|
|
65
67
|
return null;
|
|
66
68
|
const row = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
67
69
|
if (!isRecord(row) || row.isArchived === true)
|
|
@@ -135,7 +137,88 @@ function claudeDesktopSessionForCliId(cliSessionId) {
|
|
|
135
137
|
}
|
|
136
138
|
return best ? verifiedClaudeDesktopSession(best.desktopSessionId, best.cliSessionIds) : null;
|
|
137
139
|
}
|
|
138
|
-
|
|
140
|
+
// Use only the nearest Claude process record. An inner CLI can inherit the outer tab's
|
|
141
|
+
// environment, so both host-owned IDs must match the current hook.
|
|
142
|
+
function isActiveCodeTab(hostId, cliId) {
|
|
143
|
+
if (process.env.CLAUDE_CODE_ENTRYPOINT !== "claude-desktop" || !UUID_RE.test(cliId))
|
|
144
|
+
return false;
|
|
145
|
+
const directory = resolveClaudeProcessSessionsDir();
|
|
146
|
+
if (!directory)
|
|
147
|
+
return false;
|
|
148
|
+
for (const pid of hookParentPids()) {
|
|
149
|
+
let row;
|
|
150
|
+
try {
|
|
151
|
+
row = JSON.parse(fs.readFileSync(path.join(directory, `${pid}.json`), "utf8"));
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (error.code === "ENOENT")
|
|
155
|
+
continue;
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
if (isRecord(row) && row.pid === pid && row.entrypoint === "claude-desktop"
|
|
159
|
+
&& row.hostSessionId === hostId && row.sessionId === cliId) {
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
/** The session the Claude desktop app says it hosts here, if that session's own record names
|
|
167
|
+
* this CLI session. The app writes the record a few seconds after the session's first message, so
|
|
168
|
+
* a call made sooner finds none: within `waitMs` it is waited for, because without it the session
|
|
169
|
+
* would be known by its CLI ID alone from then on. A nested CLI inherits the outer tab's ID;
|
|
170
|
+
* only a verified active tab can wait for a desktop record that still names a different CLI. Looking
|
|
171
|
+
* the record up by its name also keeps this independent of how many records there are. */
|
|
172
|
+
function hostedClaudeDesktopSession(cliSessionId, waitMs, includePriorCliIds) {
|
|
173
|
+
const hostSessionId = process.env.CLAUDE_CODE_HOST_SESSION_ID?.trim() ?? "";
|
|
174
|
+
if (!CLAUDE_DESKTOP_ID_RE.test(hostSessionId))
|
|
175
|
+
return null;
|
|
176
|
+
const pause = new Int32Array(new SharedArrayBuffer(4));
|
|
177
|
+
for (const deadline = Date.now() + waitMs;;) {
|
|
178
|
+
const active = isActiveCodeTab(hostSessionId, cliSessionId);
|
|
179
|
+
// Binding a resumed tab may promote a context stored under a previous CLI ID.
|
|
180
|
+
// Read the full mapping on a cold lookup. Warm searches can reuse the signed mapping.
|
|
181
|
+
if (active && !includePriorCliIds) {
|
|
182
|
+
const cached = registeredDesktopSession(cliSessionId, hostSessionId, new KeyStore().getToken());
|
|
183
|
+
if (cached)
|
|
184
|
+
return cached;
|
|
185
|
+
}
|
|
186
|
+
const pending = [claudeDesktopSessionsRoot()];
|
|
187
|
+
const claims = [];
|
|
188
|
+
for (let directory = pending.pop(); directory; directory = pending.pop()) {
|
|
189
|
+
let entries;
|
|
190
|
+
try {
|
|
191
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
for (const entry of entries) {
|
|
197
|
+
if (entry.isDirectory())
|
|
198
|
+
pending.push(path.join(directory, entry.name));
|
|
199
|
+
else if (entry.isFile() && entry.name === `${hostSessionId}.json`) {
|
|
200
|
+
const claim = readClaudeDesktopClaim(path.join(directory, entry.name), true);
|
|
201
|
+
if (claim?.desktopSessionId === hostSessionId)
|
|
202
|
+
claims.push(claim);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const claim = claims.find((candidate) => candidate.cliSessionIds.includes(cliSessionId));
|
|
207
|
+
if (claim)
|
|
208
|
+
return verifiedClaudeDesktopSession(claim.desktopSessionId, claim.cliSessionIds);
|
|
209
|
+
// A verified, resumed tab may still have a desktop record naming its previous CLI session.
|
|
210
|
+
if (claims.length > 0 && !active)
|
|
211
|
+
return null;
|
|
212
|
+
if (Date.now() >= deadline) {
|
|
213
|
+
if (process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop") {
|
|
214
|
+
throw new Error("SOURCE_SESSION_NOT_READY: Claude Desktop has not written this Code tab session record yet. Retry this call shortly.");
|
|
215
|
+
}
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
Atomics.wait(pause, 0, 0, 100);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
export function resolveSourceSessionFromHookPayload(payload, options = {}) {
|
|
139
222
|
const requestedSessionId = typeof payload.session_id === "string" ? payload.session_id.trim() : "";
|
|
140
223
|
const transcriptPath = typeof payload.transcript_path === "string" ? payload.transcript_path.trim() : "";
|
|
141
224
|
if (!requestedSessionId || !transcriptPath || !path.isAbsolute(transcriptPath))
|
|
@@ -163,7 +246,8 @@ export function resolveSourceSessionFromHookPayload(payload) {
|
|
|
163
246
|
const filenameSession = path.basename(file, path.extname(file));
|
|
164
247
|
if (filenameSession !== requestedSessionId)
|
|
165
248
|
return null;
|
|
166
|
-
const
|
|
249
|
+
const cliSessionId = filenameSession.toLowerCase();
|
|
250
|
+
const desktopSession = hostedClaudeDesktopSession(cliSessionId, options.awaitDesktopRecordMs ?? 0, options.includePriorCliIds === true) ?? claudeDesktopSessionForCliId(cliSessionId);
|
|
167
251
|
if (desktopSession)
|
|
168
252
|
return desktopSession;
|
|
169
253
|
return verifiedSourceSession("claude-code", filenameSession, SOURCE_SESSION_HOOK_EVIDENCE);
|
|
@@ -193,7 +277,7 @@ export async function runSourceSessionStartHook(input) {
|
|
|
193
277
|
const parsed = JSON.parse(input);
|
|
194
278
|
if (!isRecord(parsed))
|
|
195
279
|
return JSON.stringify({ continue: true });
|
|
196
|
-
const identity = resolveSourceSessionFromHookPayload(parsed);
|
|
280
|
+
const identity = resolveSourceSessionFromHookPayload(parsed, { includePriorCliIds: true });
|
|
197
281
|
if (identity) {
|
|
198
282
|
const sessionId = typeof parsed.session_id === "string" ? parsed.session_id : "";
|
|
199
283
|
try {
|
|
@@ -3,7 +3,7 @@ import fs from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
5
5
|
import { echoConfigDir } from "./keystore.js";
|
|
6
|
-
import { SOURCE_SESSION_HOOK_EVIDENCE, verifiedClaudeDesktopSession, verifiedSourceSession, } from "./source-session.js";
|
|
6
|
+
import { SOURCE_SESSION_DESKTOP_INDEX_EVIDENCE, SOURCE_SESSION_HOOK_EVIDENCE, verifiedClaudeDesktopSession, verifiedSourceSession, } from "./source-session.js";
|
|
7
7
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
8
8
|
const PROOF_TTL_MS = 60 * 60 * 1000;
|
|
9
9
|
const REGISTRY_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
@@ -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,8 +71,10 @@ 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(),
|
|
77
|
+
...(identity.evidence === SOURCE_SESSION_DESKTOP_INDEX_EVIDENCE ? { desktopAliasesVerified: true } : {}),
|
|
70
78
|
};
|
|
71
79
|
const payload = JSON.stringify(entry);
|
|
72
80
|
const dir = path.dirname(file);
|
|
@@ -76,11 +84,12 @@ export function registerLocalSourceSession(sessionId, identity, secret) {
|
|
|
76
84
|
fs.renameSync(temporary, file);
|
|
77
85
|
fs.chmodSync(file, 0o600);
|
|
78
86
|
pruneExpiredProofClaims(secret);
|
|
87
|
+
return entry;
|
|
79
88
|
}
|
|
80
89
|
function readLocalSourceSession(sessionId, secret) {
|
|
81
90
|
try {
|
|
82
91
|
const file = registryFile(sessionId);
|
|
83
|
-
if (fs.statSync(file).size >
|
|
92
|
+
if (fs.statSync(file).size > 16_384)
|
|
84
93
|
return null;
|
|
85
94
|
const envelope = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
86
95
|
const expected = signature(secret, envelope.payload);
|
|
@@ -99,11 +108,19 @@ function readLocalSourceSession(sessionId, secret) {
|
|
|
99
108
|
return null;
|
|
100
109
|
}
|
|
101
110
|
}
|
|
102
|
-
|
|
111
|
+
/** Reuse aliases only for the same live tab, current CLI process and signing account. */
|
|
112
|
+
export function registeredDesktopSession(cliId, hostId, secret) {
|
|
113
|
+
const entry = secret ? readLocalSourceSession(cliId, secret) : null;
|
|
114
|
+
if (!entry?.desktopAliasesVerified || entry.identity.provider !== "claude-code"
|
|
115
|
+
|| entry.identity.providerSessionId !== hostId || entry.identity.providerSessionAliases?.[0] !== cliId)
|
|
116
|
+
return null;
|
|
117
|
+
return verifiedClaudeDesktopSession(hostId, entry.identity.providerSessionAliases);
|
|
118
|
+
}
|
|
119
|
+
export function mintSourceSessionProof(sessionId, toolName, secret, fresh) {
|
|
103
120
|
if (!secret || !/^mcp__echomem__/.test(toolName))
|
|
104
121
|
return null;
|
|
105
|
-
const registered = readLocalSourceSession(sessionId, secret);
|
|
106
|
-
if (!registered)
|
|
122
|
+
const registered = fresh ?? readLocalSourceSession(sessionId, secret);
|
|
123
|
+
if (!registered || registered.sessionId !== sessionId.toLowerCase())
|
|
107
124
|
return null;
|
|
108
125
|
const issuedAt = Date.now();
|
|
109
126
|
const proof = {
|
|
@@ -117,7 +134,7 @@ export function mintSourceSessionProof(sessionId, toolName, secret) {
|
|
|
117
134
|
return `${payload}.${signature(secret, payload).toString("base64url")}`;
|
|
118
135
|
}
|
|
119
136
|
export function verifySourceSessionProof(proof, toolName, secret) {
|
|
120
|
-
if (!secret || proof.length >
|
|
137
|
+
if (!secret || proof.length > 24_576)
|
|
121
138
|
return null;
|
|
122
139
|
try {
|
|
123
140
|
const [payload, mac, extra] = proof.split(".");
|
|
@@ -190,7 +207,97 @@ export function takeSourceSessionProof(toolUseId) {
|
|
|
190
207
|
return null;
|
|
191
208
|
}
|
|
192
209
|
}
|
|
210
|
+
// A relay delivers a call's tool name and input and nothing beside them, so those are what the
|
|
211
|
+
// hook and the relay bridge both know the call by. The Claude desktop app's relay also fills in
|
|
212
|
+
// the defaults the tool's schema declares, so the bridge receives every field the hook saw and
|
|
213
|
+
// may receive more: a waiting proof is for a call that carries all of its fields unchanged.
|
|
214
|
+
// Only hashes of the fields are kept, never the input itself.
|
|
215
|
+
const CALL_PROOF_WINDOW_MS = 2 * 60 * 1000;
|
|
216
|
+
const callProofsDir = () => path.join(echoConfigDir(), "source-session-call-proofs");
|
|
217
|
+
const sortedKeys = (value) => Array.isArray(value) ? value.map(sortedKeys)
|
|
218
|
+
: value !== null && typeof value === "object"
|
|
219
|
+
? Object.fromEntries(Object.keys(value).sort().map(key => [key, sortedKeys(value[key])]))
|
|
220
|
+
: value;
|
|
221
|
+
const fieldHashes = (input) => Object.fromEntries(Object.entries(input !== null && typeof input === "object" && !Array.isArray(input) ? input : {})
|
|
222
|
+
.filter(([, value]) => value !== undefined)
|
|
223
|
+
.map(([key, value]) => [key, createHash("sha256").update(JSON.stringify(sortedKeys(value))).digest("hex")]));
|
|
224
|
+
const proofSessionId = (proof) => {
|
|
225
|
+
try {
|
|
226
|
+
return String(JSON.parse(Buffer.from(proof.split(".")[0], "base64url").toString("utf8")).sessionId);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return "";
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
function waitingCallProofs() {
|
|
233
|
+
const directory = callProofsDir();
|
|
234
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
235
|
+
const waiting = [];
|
|
236
|
+
for (const name of fs.readdirSync(directory)) {
|
|
237
|
+
const file = path.join(directory, name);
|
|
238
|
+
try {
|
|
239
|
+
const left = fs.statSync(file).mtimeMs;
|
|
240
|
+
// A call the host never made leaves its proof behind for the length of the window.
|
|
241
|
+
if (Date.now() - left > CALL_PROOF_WINDOW_MS)
|
|
242
|
+
fs.unlinkSync(file);
|
|
243
|
+
else if (!name.startsWith("."))
|
|
244
|
+
waiting.push({ ...JSON.parse(fs.readFileSync(file, "utf8")), file, left });
|
|
245
|
+
}
|
|
246
|
+
catch { /* taken meanwhile */ }
|
|
247
|
+
}
|
|
248
|
+
return waiting;
|
|
249
|
+
}
|
|
250
|
+
/** Leave a relayed call's proof under the call's tool name and input. A call from another session
|
|
251
|
+
* that the relay bridge could take for this one makes the two indistinguishable: this one's
|
|
252
|
+
* proof then goes in its input. */
|
|
253
|
+
export function leaveSourceSessionProofForCall(toolName, input, proof) {
|
|
254
|
+
try {
|
|
255
|
+
const fields = fieldHashes(input);
|
|
256
|
+
const mayBeTakenFor = (other) => other.toolName === toolName && proofSessionId(other.proof) !== proofSessionId(proof)
|
|
257
|
+
&& Object.entries(fields).every(([key, hash]) => other.fields[key] === undefined || other.fields[key] === hash);
|
|
258
|
+
if (waitingCallProofs().some(mayBeTakenFor))
|
|
259
|
+
return false;
|
|
260
|
+
const temporary = path.join(callProofsDir(), `.${randomUUID()}.tmp`);
|
|
261
|
+
fs.writeFileSync(temporary, JSON.stringify({ toolName, fields, proof }), { mode: 0o600, flag: "wx" });
|
|
262
|
+
fs.renameSync(temporary, path.join(callProofsDir(), randomUUID()));
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** Take the proof the hook left for a call with this tool name and input, oldest first. Proofs
|
|
270
|
+
* from two sessions cannot be told apart, so neither is used. A call that carries a proof in its
|
|
271
|
+
* input is only ever given one left by that same session. */
|
|
272
|
+
export function takeSourceSessionProofForCall(toolName, input, carried) {
|
|
273
|
+
try {
|
|
274
|
+
const sent = fieldHashes(input);
|
|
275
|
+
const waiting = waitingCallProofs().filter(entry => entry.toolName === toolName
|
|
276
|
+
&& Object.entries(entry.fields).every(([key, hash]) => sent[key] === hash)
|
|
277
|
+
&& (carried === undefined || proofSessionId(entry.proof) === proofSessionId(carried)));
|
|
278
|
+
if (new Set(waiting.map(entry => proofSessionId(entry.proof))).size > 1) {
|
|
279
|
+
for (const entry of waiting)
|
|
280
|
+
try {
|
|
281
|
+
fs.unlinkSync(entry.file);
|
|
282
|
+
}
|
|
283
|
+
catch { /* taken meanwhile */ }
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
for (const entry of waiting.sort((a, b) => a.left - b.left)) {
|
|
287
|
+
try {
|
|
288
|
+
fs.unlinkSync(entry.file);
|
|
289
|
+
return entry.proof;
|
|
290
|
+
}
|
|
291
|
+
catch { /* another bridge took this one */ }
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
// Nothing was left for this call.
|
|
296
|
+
}
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
193
299
|
const directBridgesDir = () => path.join(echoConfigDir(), "direct-bridges");
|
|
300
|
+
const relayBridgesDir = () => path.join(echoConfigDir(), "relay-bridges");
|
|
194
301
|
const running = (pid) => {
|
|
195
302
|
try {
|
|
196
303
|
process.kill(pid, 0);
|
|
@@ -200,6 +307,34 @@ const running = (pid) => {
|
|
|
200
307
|
return error.code === "EPERM";
|
|
201
308
|
}
|
|
202
309
|
};
|
|
310
|
+
/** Record that this bridge is one a relay reaches, and that it collects the proofs left for
|
|
311
|
+
* relayed calls. A relay bridge from before that reads a proof only from the call's input. */
|
|
312
|
+
export function registerRelayBridge() {
|
|
313
|
+
try {
|
|
314
|
+
const directory = relayBridgesDir();
|
|
315
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
316
|
+
for (const name of fs.readdirSync(directory)) {
|
|
317
|
+
if (!running(Number(name)))
|
|
318
|
+
try {
|
|
319
|
+
fs.unlinkSync(path.join(directory, name));
|
|
320
|
+
}
|
|
321
|
+
catch { /* removed meanwhile */ }
|
|
322
|
+
}
|
|
323
|
+
fs.writeFileSync(path.join(directory, String(process.pid)), "", { mode: 0o600 });
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
// Without the record the hook puts the proof in the call's input, which every bridge reads.
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/** Whether a running relay bridge collects the proofs left for relayed calls. */
|
|
330
|
+
export function relayBridgeCollectsProofs() {
|
|
331
|
+
try {
|
|
332
|
+
return fs.readdirSync(relayBridgesDir()).some(name => Number(name) > 0 && running(Number(name)));
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
203
338
|
/** Record that this bridge serves the host process that launched it, and no relay in between.
|
|
204
339
|
* Only such a host delivers its own ID for each call along with the call. */
|
|
205
340
|
export function registerDirectBridge(hostPid = process.ppid) {
|
|
@@ -219,6 +354,22 @@ export function registerDirectBridge(hostPid = process.ppid) {
|
|
|
219
354
|
// Without the record the hook puts the proof in the call's input, which every bridge reads.
|
|
220
355
|
}
|
|
221
356
|
}
|
|
357
|
+
/** A command hook can run directly under its host or through a shell wrapper. */
|
|
358
|
+
export function* hookParentPids() {
|
|
359
|
+
if (process.ppid <= 1)
|
|
360
|
+
return;
|
|
361
|
+
yield process.ppid;
|
|
362
|
+
try {
|
|
363
|
+
const parents = new Map(execFileSync("ps", ["-ax", "-o", "pid=,ppid="], { encoding: "utf8", timeout: 2000 })
|
|
364
|
+
.split("\n").map(line => line.trim().split(/\s+/).map(Number)));
|
|
365
|
+
for (let pid = parents.get(process.ppid) ?? 0, depth = 1; pid > 1 && depth < 8; pid = parents.get(pid) ?? 0, depth++) {
|
|
366
|
+
yield pid;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
// On hosts without a process table, only the direct parent is known.
|
|
371
|
+
}
|
|
372
|
+
}
|
|
222
373
|
/** Whether the host running this hook has a bridge of its own: one of this process's ancestors
|
|
223
374
|
* launched a bridge that is still running. */
|
|
224
375
|
export function hostRunsDirectBridge() {
|
|
@@ -227,9 +378,7 @@ export function hostRunsDirectBridge() {
|
|
|
227
378
|
.filter(([host, bridge]) => host > 0 && bridge > 0 && running(bridge));
|
|
228
379
|
if (!bridges.length)
|
|
229
380
|
return false;
|
|
230
|
-
const
|
|
231
|
-
.split("\n").map(line => line.trim().split(/\s+/).map(Number)));
|
|
232
|
-
for (let pid = process.ppid, depth = 0; pid > 1 && depth < 8; pid = parents.get(pid) ?? 0, depth++) {
|
|
381
|
+
for (const pid of hookParentPids()) {
|
|
233
382
|
if (bridges.some(([host]) => host === pid))
|
|
234
383
|
return true;
|
|
235
384
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { KeyStore } from "./keystore.js";
|
|
2
|
-
import { hostRunsDirectBridge, leaveSourceSessionProof, mintSourceSessionProof, registerLocalSourceSession } from "./source-session-local.js";
|
|
3
|
-
import { resolveSourceSessionFromHookPayload } from "./source-session-hook.js";
|
|
2
|
+
import { hostRunsDirectBridge, leaveSourceSessionProof, leaveSourceSessionProofForCall, mintSourceSessionProof, registerLocalSourceSession, relayBridgeCollectsProofs, } from "./source-session-local.js";
|
|
3
|
+
import { DESKTOP_RECORD_WAIT_MS, resolveSourceSessionFromHookPayload } from "./source-session-hook.js";
|
|
4
4
|
function isRecord(value) {
|
|
5
5
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6
6
|
}
|
|
@@ -19,28 +19,40 @@ export function runSourceSessionPreToolHook(input) {
|
|
|
19
19
|
const secret = new KeyStore().getToken();
|
|
20
20
|
if (!secret)
|
|
21
21
|
return "";
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
+
let registered;
|
|
25
|
+
if (typeof payload.transcript_path === "string" && payload.transcript_path) {
|
|
26
|
+
const identity = resolveSourceSessionFromHookPayload(payload, {
|
|
27
|
+
awaitDesktopRecordMs: DESKTOP_RECORD_WAIT_MS,
|
|
28
|
+
includePriorCliIds: toolName === "mcp__echomem__save_conversation",
|
|
29
|
+
});
|
|
27
30
|
if (!identity)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
+
throw new Error("SOURCE_SESSION_NOT_READY: the host transcript is not readable yet. Retry this call shortly.");
|
|
32
|
+
if (identity.provider === "claude-code") {
|
|
33
|
+
identity.transcript = { path: payload.transcript_path, sessionId };
|
|
34
|
+
}
|
|
35
|
+
registered = registerLocalSourceSession(sessionId, identity, secret);
|
|
31
36
|
}
|
|
37
|
+
// A parallel hook can replace the shared registry entry after registration.
|
|
38
|
+
const proof = mintSourceSessionProof(sessionId, toolName, secret, registered);
|
|
32
39
|
if (!proof)
|
|
33
40
|
return "";
|
|
34
|
-
//
|
|
35
|
-
// proof travels beside
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
//
|
|
41
|
+
// Rewriting the input makes auto mode refuse the call, because the input no longer matches
|
|
42
|
+
// what it reviewed, so there the proof travels beside the call wherever a bridge can find it.
|
|
43
|
+
// A host that runs its own bridge sends its ID for each call along with the call. The Claude
|
|
44
|
+
// desktop app serves a session's calls through its relay even though that session's own
|
|
45
|
+
// `claude` process launches a bridge too, and gives each session it hosts a local_ ID; its
|
|
46
|
+
// relay delivers only the tool name and the input, which then name the call. They name it
|
|
47
|
+
// less exactly than an ID does, so outside auto mode, where a call may also wait on a person
|
|
48
|
+
// for as long as they take, the proof stays in the input.
|
|
40
49
|
const toolUseId = typeof payload.tool_use_id === "string" ? payload.tool_use_id : "";
|
|
41
50
|
const desktopHosted = process.env.CLAUDE_CODE_HOST_SESSION_ID?.startsWith("local_") === true;
|
|
42
51
|
if (toolUseId && !desktopHosted && hostRunsDirectBridge() && leaveSourceSessionProof(toolUseId, proof))
|
|
43
52
|
return "";
|
|
53
|
+
if (desktopHosted && payload.permission_mode === "auto" && relayBridgeCollectsProofs()
|
|
54
|
+
&& leaveSourceSessionProofForCall(toolName, payload.tool_input, proof))
|
|
55
|
+
return "";
|
|
44
56
|
return JSON.stringify({
|
|
45
57
|
hookSpecificOutput: {
|
|
46
58
|
hookEventName: "PreToolUse",
|
|
@@ -48,7 +60,11 @@ export function runSourceSessionPreToolHook(input) {
|
|
|
48
60
|
},
|
|
49
61
|
});
|
|
50
62
|
}
|
|
51
|
-
catch {
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error instanceof Error && error.message.startsWith("SOURCE_SESSION_NOT_READY")) {
|
|
65
|
+
return JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse",
|
|
66
|
+
permissionDecision: "deny", permissionDecisionReason: error.message } });
|
|
67
|
+
}
|
|
52
68
|
return "";
|
|
53
69
|
}
|
|
54
70
|
}
|
package/dist/source-session.js
CHANGED
|
@@ -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
|
-
|
|
391
|
-
|
|
392
|
-
|
|
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,
|
|
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import os from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { readStrictRawSession, selectSaveEvidence, } from "./strict-raw-session.js";
|
|
5
|
-
import { resolveSourceSessionFromHookPayload } from "./source-session-hook.js";
|
|
5
|
+
import { DESKTOP_RECORD_WAIT_MS, resolveSourceSessionFromHookPayload } from "./source-session-hook.js";
|
|
6
6
|
import { validateSourceSnapshot } from "./source-snapshot.js";
|
|
7
7
|
/** Private-file IPC for Echo Desktop. Stdout never carries conversation contents. */
|
|
8
8
|
export function exportSourceSnapshot(input) {
|
|
@@ -25,6 +25,9 @@ export function exportSourceSnapshot(input) {
|
|
|
25
25
|
const identity = resolveSourceSessionFromHookPayload({
|
|
26
26
|
session_id: nativeId,
|
|
27
27
|
transcript_path: value.transcriptPath,
|
|
28
|
+
}, {
|
|
29
|
+
includePriorCliIds: true,
|
|
30
|
+
awaitDesktopRecordMs: process.env.CLAUDE_CODE_ENTRYPOINT === "claude-desktop" ? DESKTOP_RECORD_WAIT_MS : 0,
|
|
28
31
|
});
|
|
29
32
|
if (!identity ||
|
|
30
33
|
identity.provider !== value.provider ||
|
|
@@ -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
|
-
|
|
342
|
-
|
|
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.
|
|
3
|
+
"version": "1.5.2",
|
|
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/backend-unreachable.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"
|