@echomem/mcp 1.4.71 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +34 -6
  2. package/dist/agent-messages-fallback.js +45 -0
  3. package/dist/backend-network-guard.js +48 -0
  4. package/dist/backend-policy.js +46 -0
  5. package/dist/claude-evidence.js +91 -0
  6. package/dist/codex-sync.js +2 -1
  7. package/dist/cowork-source.js +140 -0
  8. package/dist/desktop-presence.js +40 -0
  9. package/dist/desktop-save-activity.js +128 -0
  10. package/dist/desktop-workspace.js +48 -0
  11. package/dist/durable-entry.js +20 -5
  12. package/dist/headless-runtime.js +4 -0
  13. package/dist/hud/cli.js +16 -17
  14. package/dist/hud/diagnostics.js +2 -1
  15. package/dist/hud/hooks.js +97 -62
  16. package/dist/hud/server.js +2 -1
  17. package/dist/index.js +814 -191
  18. package/dist/lifecycle-entry.js +29 -0
  19. package/dist/local-data-paths.js +15 -1
  20. package/dist/local-usage.js +72 -0
  21. package/dist/memory-intent.js +150 -0
  22. package/dist/memory-links.js +6 -0
  23. package/dist/migrate.js +2 -1
  24. package/dist/package-metadata.js +7 -7
  25. package/dist/pending-save.js +49 -0
  26. package/dist/save-local-trace.js +26 -0
  27. package/dist/save-note-store.js +50 -0
  28. package/dist/save-receipt-store.js +58 -0
  29. package/dist/save-receipt.js +42 -0
  30. package/dist/save-retry.js +43 -0
  31. package/dist/setup-page/client-extraction.js +2 -1
  32. package/dist/setup.js +13 -13
  33. package/dist/source-session-hook.js +65 -4
  34. package/dist/source-session-local.js +366 -0
  35. package/dist/source-session-pretool-hook.js +65 -0
  36. package/dist/source-session.js +66 -27
  37. package/dist/source-snapshot-export.js +68 -0
  38. package/dist/source-snapshot.js +99 -0
  39. package/dist/strict-ingest-contract.js +31 -0
  40. package/dist/strict-raw-session.js +554 -0
  41. package/dist/tool-map-cache.js +62 -0
  42. package/dist/turn-end-saves.js +104 -0
  43. package/dist/v1-contract.js +92 -45
  44. package/package.json +5 -3
  45. package/templates/codex-skills/echomem-save/SKILL.md +26 -27
  46. package/templates/echomem-recall.md +27 -21
  47. package/dist/save-checkpoint-hook.js +0 -122
package/README.md CHANGED
@@ -115,22 +115,29 @@ the local Codex/Claude logs and does not require a separate process or desktop o
115
115
 
116
116
  ## Local conversation lifecycle hooks
117
117
 
118
- For hook-capable Codex and Claude Code clients, MCP setup installs two local lifecycle hooks:
118
+ For hook-capable clients, MCP setup installs `SessionStart` and `Stop` hooks. Claude Code also
119
+ gets a `PreToolUse` hook for EchoMem tools:
119
120
 
120
121
  - **`SessionStart` — source-session binding.** The hook receives the host-owned `session_id` and
121
122
  `transcript_path`, verifies that they identify the same local JSONL, and idempotently binds the
122
123
  canonical `codex:<id>` or `claude-code:<id>` context through
123
- `POST /api/extension/source-sessions/bind`. On each MCP call, the bridge independently confirms
124
- the exact host-owned session metadata and attaches the returned context before saving, recalling,
125
- citing, sharing, or recording activity. No "latest session" lookup is used. `bind_source_session`
126
- remains available only for clients without startup hooks.
124
+ `POST /api/extension/source-sessions/bind`. It also records a signed local session entry for
125
+ the Claude Code tool hook. No "latest session" lookup is used. `bind_source_session` remains a
126
+ compatibility fallback.
127
+ - **`PreToolUse` — per-call identity in Claude Code.** Immediately before an EchoMem MCP call,
128
+ the hook attaches a short-lived signed proof of the host session. The shared Claude Desktop
129
+ bridge verifies that proof and keeps the identity scoped to that one request. A call without
130
+ proof cannot inherit another Desktop conversation's identity. The hook never approves a tool
131
+ or asks the user to share with a team. The proof prevents accidental cross-session mixing;
132
+ code with access to the same local EchoMem credential can also mint one, so backend account and
133
+ workspace authorization remain the security boundary.
127
134
  - **`Stop` — private-save checkpoint.** Before a completed turn exits, the hook reads only that
128
135
  turn's local transcript slice. If the turn appears durable and did not already call
129
136
  `save_conversation`, it blocks completion once and asks the Agent to create a concise private
130
137
  checkpoint. It never authors or uploads a checkpoint itself. Re-entry is guarded by
131
138
  `stop_hook_active`, so the second Stop is allowed after the Agent has checked or saved.
132
139
 
133
- Both hook entries are merged idempotently into `~/.codex/hooks.json` and
140
+ The hook entries are merged idempotently into `~/.codex/hooks.json` and
134
141
  `~/.claude/settings.json`; unrelated user hooks and settings are preserved. Hooks fail open when
135
142
  their local input is missing so they cannot prevent a conversation from starting or finishing.
136
143
 
@@ -252,6 +259,27 @@ ECHO_API_TOKEN="your_token" ECHO_API_BASE_URL="http://localhost:3000" npm run st
252
259
 
253
260
  * **`search_memories`**: Retrieve ranked personal memories for a query. Defaults to memory-only output and skips EchoMem answer generation; set `includeAnswer: true` for the legacy synthesized recall.
254
261
  * **`save_conversation`**: Ingest and structure a conversation directly into your EchoMem timeline.
262
+
263
+ During an open local turn this registers one check for when the reply ends. The agent
264
+ shows a brief queued/checking status; registration is not a saved-memory claim. After
265
+ the backend finishes, the next successful EchoMem tool result in the same conversation
266
+ carries a compact receipt with real memory links, or a no-new-memory/failure status.
267
+ Reading a receipt never submits another save. Pending receipts are persisted under
268
+ `chat-save-receipts` in the Echo config directory, scoped to the credential, backend,
269
+ and verified source session. They survive bridge restart and are consumed at tool
270
+ delivery. Switching accounts cannot expose another account's receipts; switching
271
+ back allows that account to receive its pending receipts. A visible Desktop notch
272
+ does not suppress the chat receipt. A new turn's queued status never cancels a
273
+ confirmed receipt from an earlier turn in the same result.
274
+
275
+ The bridge cannot edit an already-sent assistant reply: immediate post-turn activity
276
+ is shown by Desktop, while the chat receipt requires a subsequent EchoMem tool call.
277
+ Tool delivery is not an acknowledgement that the host rendered the final message:
278
+ a disconnect during delivery or an assistant omitting a returned receipt still
279
+ requires host-level acknowledgement to guarantee display. If disk writes fail,
280
+ the bridge retains an in-memory fallback. Pending turn-end requests retain their
281
+ existing disk recovery path.
282
+
255
283
  * **`get_memories_by_time_range`**: Retrieve memories between explicit start/end timestamps.
256
284
  * **`search_memories_by_keywords`**: Retrieve memories by matching the `keys` field.
257
285
  * **`search_others_memories`**: Search other users' public memories through MemoryFeed public search.
@@ -0,0 +1,45 @@
1
+ /** Source errors meaning this host has no transcript the bridge can read. Only these let a save
2
+ * fall back to agent-supplied turns; a transcript that exists but fails verification never does. */
3
+ export const TRANSCRIPT_UNAVAILABLE_CODES = new Set([
4
+ "SOURCE_SESSION_REQUIRED",
5
+ "SOURCE_SESSION_NOT_LOCALLY_VERIFIED",
6
+ "SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE",
7
+ "SOURCE_SESSION_NO_LOCAL_TRANSCRIPT",
8
+ ]);
9
+ /** A safety cap against pasting a whole session, not the target size: the tool guidance asks for
10
+ * at most six messages and 12,000 characters, and a normal save stays well under this. */
11
+ export const AGENT_MESSAGES_MAX_CHARS = 100_000;
12
+ const OMITTED_MARK = "[earlier text omitted]\n";
13
+ /** Fits agent-supplied turns under the cap by keeping the most recent whole messages. When the
14
+ * newest message alone is over the cap, its end is kept, marked as cut. Blank messages are skipped
15
+ * first, so they never take the place of a real turn. */
16
+ export function keepRecentMessages(input, maxChars = AGENT_MESSAGES_MAX_CHARS) {
17
+ const messages = input.filter((message) => message.content.trim());
18
+ let start = messages.length;
19
+ let total = 0;
20
+ while (start > 0 && total + messages[start - 1].content.length <= maxChars)
21
+ total += messages[--start].content.length;
22
+ if (start === 0)
23
+ return { kept: [...messages], omittedMessages: 0, shortenedNewest: false };
24
+ if (start < messages.length)
25
+ return { kept: messages.slice(start), omittedMessages: start, shortenedNewest: false };
26
+ const newest = messages[messages.length - 1];
27
+ const tail = newest.content.slice(newest.content.length - (maxChars - OMITTED_MARK.length));
28
+ return { kept: [{ ...newest, content: OMITTED_MARK + tail }], omittedMessages: messages.length - 1, shortenedNewest: true };
29
+ }
30
+ /** Whether a save may use agent-supplied turns after source error `code`. An unbound save falls
31
+ * back unless its app always keeps a transcript (Claude Code, Codex): there the binding failed, and
32
+ * the save fails closed as before. A bound session falls back only when it can never have a local
33
+ * transcript (Cloud Cowork, or a Codex thread with no file in readable session folders); otherwise
34
+ * its fallback source would sit in the session's context, where every later verified save must parse
35
+ * it and is refused. Unreadable Codex folders or a bad thread ID fail closed. */
36
+ export function agentMessagesFallbackAllowed(session, code, clientName) {
37
+ if (!TRANSCRIPT_UNAVAILABLE_CODES.has(code))
38
+ return false;
39
+ if (!session) {
40
+ const name = (clientName ?? "").toLowerCase();
41
+ return name !== "claude-code" && !name.startsWith("codex");
42
+ }
43
+ return session.evidence === "cloud_cowork_tool_argument"
44
+ || (session.provider === "codex" && code === "SOURCE_SESSION_NO_LOCAL_TRANSCRIPT");
45
+ }
@@ -0,0 +1,48 @@
1
+ import http from "node:http";
2
+ import https from "node:https";
3
+ import { syncBuiltinESMExports } from "node:module";
4
+ import { assertBackendURL, readBackendPolicy, resolveBackendURL } from "./backend-policy.js";
5
+ /** Defense against old hardcoded API URLs and redirects in a localhost-only installation. */
6
+ export function checkBackendRequest(url) {
7
+ if (!readBackendPolicy())
8
+ return;
9
+ const backendHost = url.hostname === "echoknows.com" || url.hostname.endsWith(".echoknows.com")
10
+ || url.hostname.endsWith(".vercel.app");
11
+ const backendPath = /^\/api\/(?:extension|local|mcp)(?:\/|$)/.test(url.pathname);
12
+ if (backendHost || backendPath)
13
+ assertBackendURL(url.href);
14
+ }
15
+ // Evaluate before importing modules with endpoint constants. No policy means no behavior change.
16
+ if (readBackendPolicy()) {
17
+ resolveBackendURL();
18
+ for (const transport of [http, https]) {
19
+ const original = transport.request;
20
+ transport.request = ((...args) => {
21
+ const input = args[0];
22
+ if (typeof input === "string" || input instanceof URL)
23
+ checkBackendRequest(new URL(input));
24
+ else if (input && typeof input === "object") {
25
+ const opts = input;
26
+ const protocol = opts.protocol ?? (transport === https ? "https:" : "http:");
27
+ const host = opts.hostname ?? opts.host ?? "localhost";
28
+ checkBackendRequest(new URL(`${protocol}//${host}${opts.port ? `:${opts.port}` : ""}${opts.path ?? "/"}`));
29
+ }
30
+ return Reflect.apply(original, transport, args);
31
+ });
32
+ // Node's get closes over its own request, so route it through the checked export.
33
+ transport.get = ((...args) => {
34
+ const request = Reflect.apply(transport.request, transport, args);
35
+ request.end();
36
+ return request;
37
+ });
38
+ }
39
+ syncBuiltinESMExports();
40
+ const originalFetch = globalThis.fetch;
41
+ globalThis.fetch = (input, init) => {
42
+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
43
+ checkBackendRequest(url);
44
+ const policy = readBackendPolicy();
45
+ // Do not permit the local backend to redirect a request to a different host.
46
+ return originalFetch(input, policy && url.origin === policy.apiBaseURL ? { ...init, redirect: "error" } : init);
47
+ };
48
+ }
@@ -0,0 +1,46 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ /** A device policy is independent of a host's per-server environment and runtime version. */
5
+ export function readBackendPolicy(homeDir = os.homedir()) {
6
+ const file = path.join(homeDir, ".echomem", "backend-policy.json");
7
+ let raw;
8
+ try {
9
+ raw = fs.readFileSync(file, "utf8");
10
+ }
11
+ catch (error) {
12
+ if (error.code === "ENOENT")
13
+ return null;
14
+ throw new Error("BACKEND_POLICY_UNREADABLE: refusing to fall back to a remote backend");
15
+ }
16
+ try {
17
+ const policy = JSON.parse(raw);
18
+ const url = new URL(policy.apiBaseURL);
19
+ if (policy.version !== 1 || policy.mode !== "localhost-only"
20
+ || !["http:", "https:"].includes(url.protocol)
21
+ || !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
22
+ || url.username || url.password || url.search || url.hash || url.pathname !== "/")
23
+ throw new Error();
24
+ return { version: 1, mode: "localhost-only", apiBaseURL: url.origin };
25
+ }
26
+ catch {
27
+ throw new Error("BACKEND_POLICY_INVALID: refusing to fall back to a remote backend");
28
+ }
29
+ }
30
+ export function resolveBackendURL(fallback = "https://echo-mem-chrome.vercel.app", env = process.env) {
31
+ const policy = readBackendPolicy();
32
+ if (policy) {
33
+ // Children (including Stop workers) inherit the exact same endpoint.
34
+ process.env.ECHO_API_BASE_URL = policy.apiBaseURL;
35
+ return policy.apiBaseURL;
36
+ }
37
+ return (env.ECHO_API_BASE_URL || fallback).replace(/\/$/, "");
38
+ }
39
+ export function assertBackendURL(value) {
40
+ const policy = readBackendPolicy();
41
+ if (!policy)
42
+ return;
43
+ const url = new URL(value);
44
+ if (url.origin !== policy.apiBaseURL || url.username || url.password)
45
+ throw new Error("BACKEND_POLICY_BLOCKED: this device only allows the configured localhost backend");
46
+ }
@@ -0,0 +1,91 @@
1
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
+ export function visibleText(value) {
3
+ if (typeof value === "string")
4
+ return value;
5
+ if (!Array.isArray(value))
6
+ return "";
7
+ return value.filter(object).filter(block => ["text", "input_text", "output_text"].includes(String(block.type)))
8
+ .map(block => typeof block.text === "string" ? block.text : "").filter(Boolean).join("\n");
9
+ }
10
+ /** The EchoMem save tool under any host prefix; the text written just before its call is the turn's answer. */
11
+ export const SAVE_CONVERSATION_TOOL = /(?:^|__)save_conversation$/;
12
+ /** The agent's own statement of what a turn settled, written into its save_conversation call.
13
+ * The host records the call in its transcript, so the note is the agent's words as much as any
14
+ * text it showed: the answer a save made before the turn's end is made for. */
15
+ export function saveNoteText(input) {
16
+ let value = input;
17
+ if (typeof value === "string") {
18
+ try {
19
+ value = JSON.parse(value);
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ if (!object(value) || typeof value.note !== "string")
26
+ return null;
27
+ return value.note.trim() || null;
28
+ }
29
+ /** Project only native text, submitted answers and the host's completed-answer tool.
30
+ * Arbitrary tool output and unchosen action/option labels are never user facts. */
31
+ export function projectClaudeMessage(message) {
32
+ const blocks = Array.isArray(message.content) ? message.content.filter(object) : [];
33
+ const text = visibleText(message.content);
34
+ const projection = { text, finalText: message.stop_reason === "end_turn" && text.trim() ? text : null,
35
+ wrapUpId: null, savesConversation: false, saveNote: null, endsTurn: message.stop_reason === "end_turn", questions: [], replies: [], successfulResults: [] };
36
+ for (const block of blocks) {
37
+ if (block.type === "tool_use" && typeof block.name === "string" && SAVE_CONVERSATION_TOOL.test(block.name)) {
38
+ projection.savesConversation = true;
39
+ projection.saveNote = saveNoteText(block.input) ?? projection.saveNote;
40
+ }
41
+ if (block.type === "tool_use" && block.name === "AskUserQuestion" && typeof block.id === "string" && object(block.input)) {
42
+ const questions = Array.isArray(block.input.questions) ? block.input.questions.filter(object)
43
+ .map(question => typeof question.question === "string" ? question.question : "").filter(Boolean) : [];
44
+ if (questions.length)
45
+ projection.questions.push({ id: block.id, questions });
46
+ }
47
+ if (block.type === "tool_use" && block.name === "mcp__ccd_turn__wrap_up" && typeof block.id === "string" && object(block.input)
48
+ && typeof block.input.recap === "string" && block.input.recap.trim()) {
49
+ projection.finalText = [block.input.recap, typeof block.input.ask === "string" ? `Follow-up question: ${block.input.ask}` : ""].filter(Boolean).join("\n\n");
50
+ projection.wrapUpId = block.id;
51
+ }
52
+ if (block.type === "tool_result" && typeof block.tool_use_id === "string" && block.is_error !== true) {
53
+ const result = visibleText(block.content);
54
+ // wrap_up can merely update a status box and ask the agent to write the
55
+ // actual closing answer. Only this host acknowledgement ends the turn.
56
+ if (result.startsWith("Shown in the next-step box."))
57
+ projection.successfulResults.push(block.tool_use_id);
58
+ if (result.startsWith("The user answered: "))
59
+ projection.replies.push({ id: block.tool_use_id, text: result });
60
+ }
61
+ }
62
+ return projection;
63
+ }
64
+ /** Decode the host answer envelope using the questions from its matched tool call.
65
+ * Retain answers verbatim; do not infer a selection from an option or a default. */
66
+ export function submittedClaudeAnswers(reply, question) {
67
+ const prefix = "The user answered: ";
68
+ const suffix = '". Read the answers carefully';
69
+ const ending = reply.text.lastIndexOf(suffix);
70
+ if (!reply.text.startsWith(prefix) || ending < prefix.length)
71
+ throw new Error("SOURCE_CLARIFICATION_UNPARSEABLE");
72
+ const body = reply.text.slice(prefix.length, ending + 1);
73
+ const answers = [];
74
+ let offset = 0;
75
+ while (offset < body.length) {
76
+ const matched = question.questions.find(text => body.startsWith(`"${text}"="`, offset));
77
+ if (!matched)
78
+ throw new Error("SOURCE_CLARIFICATION_UNPARSEABLE");
79
+ const begin = offset + matched.length + 4;
80
+ const boundaries = question.questions.map(text => body.indexOf(`", "${text}"="`, begin)).filter(index => index >= 0);
81
+ const end = boundaries.length ? Math.min(...boundaries) : body.length - 1;
82
+ if (body[end] !== '"')
83
+ throw new Error("SOURCE_CLARIFICATION_UNPARSEABLE");
84
+ answers.push({ question: matched, answer: body.slice(begin, end) });
85
+ offset = end === body.length - 1 ? body.length : end + 3;
86
+ }
87
+ if (!answers.length)
88
+ throw new Error("SOURCE_CLARIFICATION_UNPARSEABLE");
89
+ // Reuse the existing explicit-retention parser: only `answer` expresses intent.
90
+ return `<send_user_message_question_reply>\n${JSON.stringify(answers)}\n</send_user_message_question_reply>`;
91
+ }
@@ -1,3 +1,4 @@
1
+ import { resolveBackendURL } from "./backend-policy.js";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
  import { StringDecoder } from "node:string_decoder";
@@ -5,7 +6,7 @@ import { createHash } from "node:crypto";
5
6
  import axios from "axios";
6
7
  import { KeyStore } from "./keystore.js";
7
8
  import { resolveCodexSessionsDir } from "./local-data-paths.js";
8
- const API_BASE_URL = (process.env.ECHO_API_BASE_URL || "https://echo-mem-chrome.vercel.app").replace(/\/$/, "");
9
+ const API_BASE_URL = (resolveBackendURL()).replace(/\/$/, "");
9
10
  const DEFAULT_DAYS = 7;
10
11
  const DEFAULT_LIMIT = 50;
11
12
  const URL_RE = /\bhttps?:\/\/[^\s<>"')\]]+/i;
@@ -0,0 +1,140 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { resolveClaudeCoworkSessionRoots } from "./local-data-paths.js";
4
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
+ const LOCAL = /^local_[0-9a-f-]{36}$/i;
6
+ /** Never use newest-file or title matching as session identity. */
7
+ export function resolveCoworkSource(localSessionId, roots = resolveClaudeCoworkSessionRoots()) {
8
+ if (!LOCAL.test(localSessionId) || !UUID.test(localSessionId.slice(6)))
9
+ throw new Error("SOURCE_SESSION_INVALID_ID");
10
+ const matches = [];
11
+ let inspected = 0;
12
+ const walk = (root, visit, metadataOnly = false) => {
13
+ const pending = [root];
14
+ while (pending.length) {
15
+ const directory = pending.pop();
16
+ const entries = fs.readdirSync(directory, { withFileTypes: true });
17
+ const hasMetadata = metadataOnly &&
18
+ entries.some((item) => item.isFile() && /^local_.*\.json$/.test(item.name));
19
+ for (const item of entries) {
20
+ if (++inspected > 30_000)
21
+ throw new Error("SOURCE_INDEX_TOO_LARGE");
22
+ if (item.isSymbolicLink() ||
23
+ item.name === "subagents" ||
24
+ item.name === "node_modules" ||
25
+ item.name === ".git" ||
26
+ (metadataOnly &&
27
+ ((hasMetadata && item.isDirectory()) || item.name === ".claude")))
28
+ continue;
29
+ const file = path.join(directory, item.name);
30
+ if (item.isDirectory())
31
+ pending.push(file);
32
+ else if (item.isFile())
33
+ visit(file);
34
+ }
35
+ }
36
+ };
37
+ for (const root of new Set(roots.map((value) => fs.realpathSync(value)))) {
38
+ walk(root, (file) => {
39
+ if (path.basename(file).toLowerCase() !==
40
+ `${localSessionId.toLowerCase()}.json`)
41
+ return;
42
+ if (fs.statSync(file).size > 1024 * 1024)
43
+ throw new Error("SOURCE_SESSION_METADATA_TOO_LARGE");
44
+ const metadata = JSON.parse(fs.readFileSync(file, "utf8"));
45
+ if (metadata.sessionId !== localSessionId ||
46
+ typeof metadata.cliSessionId !== "string" ||
47
+ !UUID.test(metadata.cliSessionId)) {
48
+ throw new Error("SOURCE_SESSION_METADATA_UNVERIFIED");
49
+ }
50
+ const parent = path.dirname(file);
51
+ const uuid = localSessionId.slice(6).toLowerCase();
52
+ const directories = fs
53
+ .readdirSync(parent, { withFileTypes: true })
54
+ .filter((entry) => entry.isDirectory() &&
55
+ !entry.isSymbolicLink() &&
56
+ (entry.name.toLowerCase() === localSessionId.toLowerCase() ||
57
+ (entry.name.length >= 8 &&
58
+ uuid.startsWith(entry.name.toLowerCase()))));
59
+ const wanted = `${metadata.cliSessionId.toLowerCase()}.jsonl`;
60
+ const paths = new Set();
61
+ for (const directory of directories) {
62
+ const sandboxRoot = fs.realpathSync(path.join(parent, directory.name));
63
+ const projectRoot = path.join(sandboxRoot, ".claude", "projects");
64
+ if (fs.existsSync(projectRoot) &&
65
+ !fs.realpathSync(projectRoot).startsWith(sandboxRoot + path.sep))
66
+ throw new Error("SOURCE_SESSION_PATH_ESCAPE");
67
+ if (!fs.existsSync(projectRoot) ||
68
+ fs.lstatSync(projectRoot).isSymbolicLink())
69
+ continue;
70
+ walk(projectRoot, (transcript) => {
71
+ if (path.basename(transcript).toLowerCase() === wanted)
72
+ paths.add(fs.realpathSync(transcript));
73
+ });
74
+ }
75
+ if (paths.size !== 1)
76
+ throw new Error(paths.size
77
+ ? "SOURCE_SESSION_AMBIGUOUS"
78
+ : "SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
79
+ const transcriptPath = [...paths][0];
80
+ if (!transcriptPath.startsWith(root + path.sep))
81
+ throw new Error("SOURCE_SESSION_PATH_ESCAPE");
82
+ matches.push({
83
+ transcriptPath,
84
+ cliSessionId: metadata.cliSessionId,
85
+ localSessionId,
86
+ });
87
+ }, true);
88
+ }
89
+ if (matches.length !== 1)
90
+ throw new Error(matches.length
91
+ ? "SOURCE_SESSION_AMBIGUOUS"
92
+ : "SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
93
+ return matches[0];
94
+ }
95
+ /** Metadata-backed reverse lookup used by host hooks; short sandbox names carry no identity. */
96
+ export function coworkSessionForTranscript(file) {
97
+ const parts = path.resolve(file).split(path.sep);
98
+ const index = parts.lastIndexOf(".claude");
99
+ if (index < 1 ||
100
+ parts[index + 1] !== "projects" ||
101
+ parts.includes("subagents"))
102
+ return null;
103
+ const cli = path.basename(file, ".jsonl");
104
+ if (!UUID.test(cli))
105
+ return null;
106
+ const sandbox = parts[index - 1];
107
+ const parent = parts.slice(0, index - 1).join(path.sep) || path.sep;
108
+ try {
109
+ const matches = [];
110
+ for (const entry of fs.readdirSync(parent, { withFileTypes: true })) {
111
+ if (!entry.isFile() || !/^local_.*\.json$/.test(entry.name))
112
+ continue;
113
+ const candidate = path.join(parent, entry.name);
114
+ if (fs.statSync(candidate).size > 1024 * 1024)
115
+ continue;
116
+ let meta;
117
+ try {
118
+ meta = JSON.parse(fs.readFileSync(candidate, "utf8"));
119
+ }
120
+ catch {
121
+ continue;
122
+ }
123
+ if (typeof meta.sessionId !== "string" ||
124
+ !LOCAL.test(meta.sessionId) ||
125
+ meta.cliSessionId !== cli)
126
+ continue;
127
+ if (sandbox === meta.sessionId ||
128
+ (sandbox.length >= 8 && meta.sessionId.slice(6).startsWith(sandbox)))
129
+ matches.push(meta.sessionId);
130
+ }
131
+ if (matches.length > 1)
132
+ throw new Error("SOURCE_SESSION_AMBIGUOUS");
133
+ return matches[0] ?? null;
134
+ }
135
+ catch (error) {
136
+ if (error instanceof Error && error.message === "SOURCE_SESSION_AMBIGUOUS")
137
+ throw error;
138
+ return null;
139
+ }
140
+ }
@@ -0,0 +1,40 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { echoConfigDir } from "./keystore.js";
4
+ /** Echo Desktop announces itself while it runs: `~/.echomem/desktop-presence.json`
5
+ * holding `{ v: 1, pid, notchVisible, updatedAt }`, rewritten at least every 15 s.
6
+ * A fresh file from a live process means the notch shows save activity, so the
7
+ * save receipt stays out of the answer. A missing, stale or orphaned file means
8
+ * no notch: the receipt goes into the answer, as with an older desktop. */
9
+ export const DESKTOP_PRESENCE_FILE = "desktop-presence.json";
10
+ export const DESKTOP_PRESENCE_FRESH_MS = 45_000;
11
+ function processAlive(pid) {
12
+ try {
13
+ process.kill(pid, 0);
14
+ return true;
15
+ }
16
+ catch (error) {
17
+ return error.code === "EPERM";
18
+ }
19
+ }
20
+ export function readDesktopPresence(options = {}) {
21
+ const file = path.join(options.directory ?? echoConfigDir(), DESKTOP_PRESENCE_FILE);
22
+ try {
23
+ const stat = fs.statSync(file);
24
+ if (!stat.isFile() || stat.size > 4096)
25
+ return null;
26
+ const row = JSON.parse(fs.readFileSync(file, "utf8"));
27
+ if (row.v !== 1 || typeof row.pid !== "number" || !Number.isInteger(row.pid) || row.pid <= 0
28
+ || typeof row.updatedAt !== "number" || !Number.isFinite(row.updatedAt))
29
+ return null;
30
+ const now = options.now ?? Date.now();
31
+ if (Math.abs(now - row.updatedAt) > DESKTOP_PRESENCE_FRESH_MS)
32
+ return null;
33
+ if (!(options.alive ?? processAlive)(row.pid))
34
+ return null;
35
+ return { pid: row.pid, notchVisible: row.notchVisible === true, updatedAt: row.updatedAt };
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
@@ -0,0 +1,128 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { echoConfigDir } from "./keystore.js";
5
+ const REASON = /^[A-Z][A-Z0-9_]{1,79}$/;
6
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ const MAX_MEMORIES = 5;
8
+ const MAX_TITLE = 160;
9
+ /** The saved memories' ids and titles, the same local data saved-receipts keeps. */
10
+ function savedMemories(value) {
11
+ if (!Array.isArray(value))
12
+ return [];
13
+ return value.flatMap(item => {
14
+ if (!item || typeof item !== "object")
15
+ return [];
16
+ const { id, keys } = item;
17
+ if (typeof id !== "string" || !UUID.test(id) || typeof keys !== "string")
18
+ return [];
19
+ const title = keys.replace(/\s+/g, " ").trim().slice(0, MAX_TITLE);
20
+ return title ? [{ id, title }] : [];
21
+ }).slice(0, MAX_MEMORIES);
22
+ }
23
+ /** Local desktop IPC, independent of analytics/telemetry opt-in. No transcript,
24
+ * token, key, or server error text is ever written here: reasons are upper-case
25
+ * codes, and only a successful save carries its memories' ids and titles. One
26
+ * atomic file per operation supports concurrent bridge processes without a
27
+ * shared lock. */
28
+ export function beginDesktopSaveActivity(options) {
29
+ if (!options.token)
30
+ return { finish() { }, discard() { } };
31
+ const directory = options.directory ?? path.join(echoConfigDir(), "desktop-save-activity");
32
+ const operationID = randomUUID();
33
+ const file = path.join(directory, `${operationID}.json`);
34
+ const startedAt = Date.now();
35
+ const base = {
36
+ v: 1, operationID,
37
+ credentialHash: createHash("sha256").update(options.token).digest("hex"),
38
+ backend: options.backend.replace(/\/$/, ""),
39
+ startedAt,
40
+ ...(options.origin ? { origin: options.origin } : {}),
41
+ };
42
+ let finished = false;
43
+ const write = (fields) => {
44
+ const temporary = path.join(directory, `.${operationID}-${randomUUID()}.tmp`);
45
+ try {
46
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
47
+ fs.chmodSync(directory, 0o700);
48
+ fs.writeFileSync(temporary, JSON.stringify({ ...base, ...fields, updatedAt: Date.now() }), { mode: 0o600, flag: "wx" });
49
+ fs.renameSync(temporary, file);
50
+ }
51
+ catch {
52
+ // UI feedback must never fail or slow down a save.
53
+ try {
54
+ fs.unlinkSync(temporary);
55
+ }
56
+ catch { /* absent/unwritable */ }
57
+ }
58
+ };
59
+ // Reap crashed bridge processes and terminals left while Echo was closed.
60
+ try {
61
+ for (const name of fs.readdirSync(directory).slice(0, 512)) {
62
+ if (!/^[a-f0-9-]{36}\.json$/.test(name))
63
+ continue;
64
+ const candidate = path.join(directory, name);
65
+ if (Date.now() - fs.statSync(candidate).mtimeMs > 3_600_000)
66
+ fs.unlinkSync(candidate);
67
+ }
68
+ }
69
+ catch { /* optional IPC directory may not exist yet */ }
70
+ write({ phase: "saving" });
71
+ const heartbeat = setInterval(() => write({ phase: "saving" }), options.heartbeatMs ?? 15_000);
72
+ heartbeat.unref();
73
+ const stop = () => {
74
+ if (finished)
75
+ return false;
76
+ finished = true;
77
+ clearInterval(heartbeat);
78
+ return true;
79
+ };
80
+ return {
81
+ finish(outcome) {
82
+ if (!stop())
83
+ return;
84
+ const reason = "reason" in outcome && typeof outcome.reason === "string" && REASON.test(outcome.reason)
85
+ ? { reason: outcome.reason } : {};
86
+ if (outcome.phase === "saved") {
87
+ const memories = savedMemories(outcome.memories);
88
+ const count = typeof outcome.count === "number" && Number.isSafeInteger(outcome.count) && outcome.count >= 0
89
+ ? outcome.count : undefined;
90
+ write({ phase: "saved", ...(count !== undefined ? { count } : {}), ...(memories.length ? { memories } : {}) });
91
+ }
92
+ else if (outcome.phase === "skipped") {
93
+ write({ phase: "saved", count: 0, outcome: "skipped", ...reason });
94
+ }
95
+ else {
96
+ write({ phase: "failed", ...reason });
97
+ }
98
+ const cleanup = setTimeout(() => { try {
99
+ fs.unlinkSync(file);
100
+ }
101
+ catch { /* gone */ } }, 60_000);
102
+ cleanup.unref();
103
+ },
104
+ /** This call joined another caller's identical save, which reports it. */
105
+ discard() {
106
+ if (!stop())
107
+ return;
108
+ try {
109
+ fs.unlinkSync(file);
110
+ }
111
+ catch { /* gone */ }
112
+ },
113
+ };
114
+ }
115
+ /** Classifies an ingest receipt for the desktop. */
116
+ export function desktopSaveOutcome(data) {
117
+ const r = (data && typeof data === "object" ? data : {});
118
+ if (r.success !== true) {
119
+ return { phase: "failed", reason: typeof r.error === "string" && REASON.test(r.error) ? r.error : "SAVE_NOT_COMPLETED" };
120
+ }
121
+ const count = typeof r.memoriesExtracted === "number" ? r.memoriesExtracted : 0;
122
+ if (count > 0)
123
+ return { phase: "saved", count, memories: r.extractedMemories };
124
+ if (r.decision === "NO")
125
+ return { phase: "skipped", reason: r.alreadyProcessed === true ? "ALREADY_PROCESSED" : "NOTHING_TO_SAVE" };
126
+ const skipped = typeof r.skipped === "string" ? r.skipped.toUpperCase() : undefined;
127
+ return { phase: "skipped", reason: skipped && REASON.test(skipped) ? skipped : "NOTHING_NEW" };
128
+ }