@echomem/mcp 1.4.71 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +34 -6
  2. package/dist/agent-messages-fallback.js +45 -0
  3. package/dist/backend-network-guard.js +48 -0
  4. package/dist/backend-policy.js +46 -0
  5. package/dist/claude-evidence.js +91 -0
  6. package/dist/codex-sync.js +2 -1
  7. package/dist/cowork-source.js +140 -0
  8. package/dist/desktop-presence.js +40 -0
  9. package/dist/desktop-save-activity.js +128 -0
  10. package/dist/durable-entry.js +20 -5
  11. package/dist/headless-runtime.js +4 -0
  12. package/dist/hud/cli.js +16 -17
  13. package/dist/hud/diagnostics.js +2 -1
  14. package/dist/hud/hooks.js +97 -62
  15. package/dist/hud/server.js +2 -1
  16. package/dist/index.js +727 -170
  17. package/dist/lifecycle-entry.js +29 -0
  18. package/dist/local-data-paths.js +15 -1
  19. package/dist/local-usage.js +72 -0
  20. package/dist/memory-intent.js +150 -0
  21. package/dist/memory-links.js +6 -0
  22. package/dist/migrate.js +2 -1
  23. package/dist/package-metadata.js +7 -7
  24. package/dist/pending-save.js +49 -0
  25. package/dist/save-local-trace.js +26 -0
  26. package/dist/save-note-store.js +50 -0
  27. package/dist/save-receipt-store.js +58 -0
  28. package/dist/save-receipt.js +42 -0
  29. package/dist/save-retry.js +43 -0
  30. package/dist/setup-page/client-extraction.js +2 -1
  31. package/dist/setup.js +13 -13
  32. package/dist/source-session-hook.js +16 -2
  33. package/dist/source-session-local.js +241 -0
  34. package/dist/source-session-pretool-hook.js +54 -0
  35. package/dist/source-session.js +4 -0
  36. package/dist/source-snapshot-export.js +68 -0
  37. package/dist/source-snapshot.js +99 -0
  38. package/dist/strict-ingest-contract.js +31 -0
  39. package/dist/strict-raw-session.js +473 -0
  40. package/dist/tool-map-cache.js +62 -0
  41. package/dist/turn-end-saves.js +104 -0
  42. package/dist/v1-contract.js +92 -45
  43. package/package.json +5 -3
  44. package/templates/codex-skills/echomem-save/SKILL.md +26 -27
  45. package/templates/echomem-recall.md +27 -21
  46. package/dist/save-checkpoint-hook.js +0 -122
@@ -0,0 +1,473 @@
1
+ import { resolveCoworkSource } from "./cowork-source.js";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { resolveClaudeProjectsDir, resolveCodexSessionRoots } from "./local-data-paths.js";
5
+ import { isExplicitSaveRequest, isMemorySaveDeclined, latestUserRequestsSave, stripHostNoise, userRequestText } from "./memory-intent.js";
6
+ import { readSaveNotes } from "./save-note-store.js";
7
+ import { projectClaudeMessage, saveNoteText, submittedClaudeAnswers } from "./claude-evidence.js";
8
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
9
+ const MAX_FILES = 5_000;
10
+ // Tool/screenshots can dwarf the actual dialogue. Scan a bounded file one line
11
+ // at a time; enforce the model budget on selected text, not total trace bytes.
12
+ const MAX_FILE_BYTES = 512 * 1024 * 1024;
13
+ const MAX_LINE_BYTES = 64 * 1024 * 1024;
14
+ const MAX_RAW_BYTES = 3 * 1024 * 1024;
15
+ // The backend checks every save against what the session already saved, so a turn must read
16
+ // the same way each time. Turns from this moment on are read in full: the text shown between
17
+ // tool calls as commentary, messages typed mid-turn, no host envelopes, and without a turn the user declined.
18
+ // Earlier turns keep the reading they were saved under.
19
+ const FULL_TURN_SINCE = Date.parse("2026-11-12T00:00:00Z");
20
+ const readInFull = (time) => Date.parse(String(time ?? "")) >= FULL_TURN_SINCE;
21
+ const record = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
22
+ function textBlocks(value) {
23
+ if (typeof value === "string")
24
+ return value;
25
+ if (!Array.isArray(value))
26
+ return "";
27
+ return value.filter(record).filter((x) => x.type === "text" || x.type === "input_text" || x.type === "output_text")
28
+ .map((x) => typeof x.text === "string" ? x.text : "").filter(Boolean).join("\n");
29
+ }
30
+ function locate(root, matches) {
31
+ const pending = [root];
32
+ let inspected = 0;
33
+ let found = null;
34
+ while (pending.length) {
35
+ const dir = pending.pop();
36
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
37
+ const file = path.join(dir, entry.name);
38
+ if (entry.isDirectory())
39
+ pending.push(file);
40
+ else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
41
+ if (++inspected > MAX_FILES)
42
+ throw new Error("SOURCE_INDEX_TOO_LARGE");
43
+ if (!matches(entry.name))
44
+ continue;
45
+ if (found)
46
+ throw new Error("SOURCE_SESSION_AMBIGUOUS");
47
+ found = file;
48
+ }
49
+ }
50
+ }
51
+ if (!found)
52
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
53
+ return found;
54
+ }
55
+ function* parseLines(file) {
56
+ const fd = fs.openSync(file, "r");
57
+ try {
58
+ const st = fs.fstatSync(fd);
59
+ if (!st.isFile() || st.size > MAX_FILE_BYTES)
60
+ throw new Error("SOURCE_SESSION_SCAN_LIMIT");
61
+ const chunk = Buffer.alloc(64 * 1024);
62
+ let position = 0, lineBytes = 0;
63
+ let pieces = [];
64
+ // Freeze the file size for this read; ignore a still-growing final record.
65
+ while (position < st.size) {
66
+ const count = fs.readSync(fd, chunk, 0, Math.min(chunk.length, st.size - position), position);
67
+ if (!count)
68
+ throw new Error("SOURCE_SESSION_CHANGED_DURING_READ");
69
+ position += count;
70
+ let start = 0;
71
+ for (let end = 0; end < count; end++) {
72
+ if (chunk[end] !== 10)
73
+ continue;
74
+ lineBytes += end - start;
75
+ if (lineBytes > MAX_LINE_BYTES)
76
+ throw new Error("SOURCE_SESSION_RECORD_TOO_LARGE");
77
+ pieces.push(Buffer.from(chunk.subarray(start, end)));
78
+ const line = Buffer.concat(pieces).toString("utf8");
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(line);
82
+ }
83
+ catch {
84
+ throw new Error("SOURCE_SESSION_INVALID_JSONL");
85
+ }
86
+ if (!record(parsed))
87
+ throw new Error("SOURCE_SESSION_INVALID_JSONL");
88
+ yield parsed;
89
+ pieces = [];
90
+ lineBytes = 0;
91
+ start = end + 1;
92
+ }
93
+ if (start < count) {
94
+ lineBytes += count - start;
95
+ if (lineBytes > MAX_LINE_BYTES)
96
+ throw new Error("SOURCE_SESSION_RECORD_TOO_LARGE");
97
+ pieces.push(Buffer.from(chunk.subarray(start, count)));
98
+ }
99
+ }
100
+ if (fs.fstatSync(fd).size < st.size)
101
+ throw new Error("SOURCE_SESSION_CHANGED_DURING_READ");
102
+ }
103
+ finally {
104
+ fs.closeSync(fd);
105
+ }
106
+ }
107
+ export function claudeMessages(rows, sourceIds) {
108
+ return claudeTurn(rows, sourceIds).messages;
109
+ }
110
+ /** Claude Code ends every finished turn with an assistant record whose API message stopped
111
+ * with end_turn. Until that record is the newest one, the turn is still being written. */
112
+ function claudeTurn(rows, sourceIds) {
113
+ const nodes = new Map();
114
+ // File order is append order: the fallback when a boundary's lineage link is broken.
115
+ const written = [];
116
+ let leaf = null;
117
+ for (const row of rows) {
118
+ const uuid = typeof row.uuid === "string" ? row.uuid : "";
119
+ if (!uuid)
120
+ continue;
121
+ if (nodes.has(uuid)) {
122
+ // Before a second or later compaction, Claude Code writes the summarised history again,
123
+ // earlier compaction records included, and a kept message may point at a different parent.
124
+ // The newest parent wins; a repeat never moves the leaf, and cycles or gaps still fail below.
125
+ nodes.get(uuid).parentUuid = row.parentUuid;
126
+ continue;
127
+ }
128
+ const message = record(row.message) ? row.message : null;
129
+ // Keep lineage metadata, not tool-result blobs or images, in the node map.
130
+ nodes.set(uuid, { uuid, parentUuid: row.parentUuid, sessionId: row.sessionId,
131
+ type: row.type, subtype: row.subtype, logicalParentUuid: row.logicalParentUuid,
132
+ isCompactSummary: row.isCompactSummary, timestamp: row.timestamp, isSidechain: row.isSidechain,
133
+ messageId: message?.id, message: message ? projectClaudeMessage(message) : null,
134
+ // A message the user typed while the turn was running, at the point it was delivered.
135
+ queuedPrompt: row.type === "attachment" && record(row.attachment) && row.attachment.type === "queued_command"
136
+ && row.attachment.commandMode === "prompt" && typeof row.attachment.prompt === "string" ? row.attachment.prompt : undefined });
137
+ written.push(uuid);
138
+ if (row.isSidechain !== true && (row.type === "user" || row.type === "assistant"))
139
+ leaf = uuid;
140
+ }
141
+ if (!leaf)
142
+ throw new Error("SOURCE_SESSION_EMPTY");
143
+ const newest = nodes.get(leaf);
144
+ const turnOpen = !(newest.type === "assistant" && newest.message?.endsTurn === true);
145
+ const chain = [];
146
+ const seen = new Set();
147
+ while (leaf) {
148
+ if (seen.has(leaf))
149
+ throw new Error("SOURCE_SESSION_INVALID_LINEAGE");
150
+ seen.add(leaf);
151
+ const row = nodes.get(leaf);
152
+ if (!row)
153
+ throw new Error("SOURCE_SESSION_INVALID_LINEAGE");
154
+ chain.push(row);
155
+ leaf = typeof row.parentUuid === "string" ? row.parentUuid : null;
156
+ // A compaction starts a new root but keeps the full history in the file. The backend
157
+ // verifies coverage against the already-saved source, so the walk continues to the
158
+ // record before the boundary. A missing or already-walked predecessor ends the walk there.
159
+ const boundary = !leaf && row.type === "system" && row.subtype === "compact_boundary";
160
+ if (boundary && typeof row.logicalParentUuid === "string" && nodes.has(row.logicalParentUuid) && !seen.has(row.logicalParentUuid)) {
161
+ leaf = row.logicalParentUuid;
162
+ }
163
+ else if (boundary || (leaf && !nodes.has(leaf))) {
164
+ // Claude Code has written a boundary whose logical parent never reached the file (seen
165
+ // once in 28 compactions: the reply in flight when compaction began), and a record whose
166
+ // parent never did (tool results dropped while the disk was full). The history is
167
+ // still in the file, so continue from the last conversation record written before this
168
+ // one. Without one the walk ends here.
169
+ leaf = null;
170
+ for (let index = written.indexOf(row.uuid) - 1; index >= 0; index--) {
171
+ const earlier = nodes.get(written[index]);
172
+ if (seen.has(earlier.uuid) || earlier.isSidechain === true || earlier.isCompactSummary === true
173
+ || (earlier.type !== "user" && earlier.type !== "assistant"))
174
+ continue;
175
+ leaf = earlier.uuid;
176
+ break;
177
+ }
178
+ }
179
+ }
180
+ const messages = [];
181
+ const ordered = chain.reverse();
182
+ const successfulResults = new Set(ordered.flatMap(row => row.message?.successfulResults ?? []));
183
+ // Claude Code writes one record per content block. The text in the same API message as a
184
+ // save_conversation call is the answer that save was made for, in this read and every later one.
185
+ const savedAnswers = new Set(ordered.filter(row => row.message?.savesConversation).map(row => row.messageId));
186
+ const questions = new Map();
187
+ for (const row of ordered) {
188
+ if (typeof row.queuedPrompt === "string" && readInFull(row.timestamp) && userRequestText(row.queuedPrompt)
189
+ && typeof row.uuid === "string" && typeof row.timestamp === "string") {
190
+ messages.push({ role: "User", content: row.queuedPrompt, time: row.timestamp, id: row.uuid });
191
+ }
192
+ if (row.type !== "user" && row.type !== "assistant")
193
+ continue;
194
+ // Claude Code writes the compaction summary as a user record; it is not the user's words.
195
+ if (row.isCompactSummary === true)
196
+ continue;
197
+ const message = row.message;
198
+ if (!message)
199
+ continue;
200
+ const role = row.type === "user" ? "User" : "Assistant";
201
+ // Claude writes tool results as user records. They are evidence, not the
202
+ // user's words, so this initial adapter does not turn them into a user turn.
203
+ if (role === "Assistant")
204
+ for (const question of message.questions)
205
+ questions.set(question.id, question);
206
+ const clarification = message.replies.flatMap(reply => {
207
+ const question = questions.get(reply.id);
208
+ return question ? [submittedClaudeAnswers(reply, question)] : [];
209
+ });
210
+ const completed = message.wrapUpId ? successfulResults.has(message.wrapUpId)
211
+ : message.finalText !== null || (typeof row.messageId === "string" && savedAnswers.has(row.messageId));
212
+ let content = role === "Assistant" ? completed ? message.finalText ?? message.text : ""
213
+ : [message.text, ...clarification].filter(Boolean).join("\n\n");
214
+ // Text shown before the turn's last record sits in records that end with a tool call. It is
215
+ // kept as commentary, as Codex labels it: part of the source, never mistaken for the answer.
216
+ const commentary = role === "Assistant" && !completed && readInFull(row.timestamp);
217
+ if (commentary)
218
+ content = message.text;
219
+ if (!content.trim() && !(role === "Assistant" && message.saveNote))
220
+ continue;
221
+ const time = typeof row.timestamp === "string" ? row.timestamp : "";
222
+ const id = typeof row.uuid === "string" ? row.uuid : "";
223
+ if (!time || !id)
224
+ throw new Error("SOURCE_SESSION_MISSING_METADATA");
225
+ if (content.trim())
226
+ messages.push({ role, content, time, id, ...(role === "Assistant" ? { phase: commentary ? "commentary" : "final_answer" } : {}) });
227
+ if (role === "Assistant" && message.saveNote)
228
+ messages.push({ role, content: message.saveNote, time, id: `${id}${SAVE_NOTE_SUFFIX}`, phase: "final_answer" });
229
+ }
230
+ if (!messages.length || ![...nodes.values()].some((row) => sourceIds.has(String(row.sessionId ?? "")))) {
231
+ throw new Error("SOURCE_SESSION_MISMATCH");
232
+ }
233
+ return { messages, turnOpen };
234
+ }
235
+ /** A save note is a message of its own, named after the record that holds the call. */
236
+ export const SAVE_NOTE_SUFFIX = ":save-note";
237
+ const SAVE_CONVERSATION_CALL = /(?:^|__)save_conversation$/;
238
+ /** The same call written as script source: `tools.mcp__echomem__save_conversation({ ... })`. */
239
+ const SCRIPTED_SAVE_CALL = /(?:^|[^A-Za-z0-9])(?:[A-Za-z0-9]+__)*save_conversation\s*\(/;
240
+ // Saves are made after the answer from this moment on. Earlier save calls came before the
241
+ // answer, and the commentary in front of them is already saved under that phase.
242
+ const ANSWER_FIRST_SINCE = Date.parse("2026-11-11T08:00:00Z");
243
+ /** Codex brackets every turn with task_started and task_complete (or turn_aborted) events. */
244
+ function codexTurn(rows, sessionId, pendingNote, keptNotes = new Map()) {
245
+ let verified = false;
246
+ let turnOpen = false;
247
+ const messages = [];
248
+ let lastWritten = null;
249
+ // A save_conversation call the host has recorded and not yet answered, whose note the record
250
+ // does not hold as plain arguments: Codex also runs tools from a script (an `exec` call).
251
+ let unanswered = null;
252
+ for (const row of rows) {
253
+ if (row.type === "session_meta") {
254
+ if (verified || !record(row.payload) || row.payload.id !== sessionId || row.payload.parent_thread_id)
255
+ throw new Error("SOURCE_SESSION_MISMATCH");
256
+ verified = true;
257
+ }
258
+ if (row.type === "event_msg" && record(row.payload) && /roll.*back/i.test(String(row.payload.type ?? ""))) {
259
+ throw new Error("SOURCE_SESSION_ROLLBACK_UNSUPPORTED");
260
+ }
261
+ if (row.type === "event_msg" && record(row.payload)) {
262
+ if (row.payload.type === "task_started")
263
+ turnOpen = true;
264
+ else if (row.payload.type === "task_complete" || row.payload.type === "turn_aborted") {
265
+ turnOpen = false;
266
+ unanswered = null;
267
+ }
268
+ }
269
+ if (row.type !== "response_item" || !record(row.payload))
270
+ continue;
271
+ if (unanswered && /_call_output$/.test(String(row.payload.type ?? "")) && row.payload.call_id === unanswered.callId)
272
+ unanswered = null;
273
+ // Codex labels the text before any tool call commentary. The assistant message written
274
+ // just before a save_conversation call is the answer that save was made for.
275
+ if (/_call$/.test(String(row.payload.type ?? ""))) {
276
+ if (lastWritten?.role === "Assistant" && Date.parse(String(row.timestamp ?? "")) >= ANSWER_FIRST_SINCE
277
+ && [row.payload.name, row.payload.input, row.payload.arguments].some(part => typeof part === "string" && part.includes("save_conversation"))) {
278
+ lastWritten.phase = "final_answer";
279
+ }
280
+ lastWritten = null;
281
+ const callId = typeof row.payload.call_id === "string" ? row.payload.call_id : typeof row.payload.id === "string" ? row.payload.id : "";
282
+ const scripted = [row.payload.input, row.payload.arguments].some(part => typeof part === "string" && SCRIPTED_SAVE_CALL.test(part));
283
+ // A note already saved from a scripted call is repeated from where it was kept.
284
+ const note = SAVE_CONVERSATION_CALL.test(String(row.payload.name ?? "")) ? saveNoteText(row.payload.arguments ?? row.payload.input)
285
+ : scripted ? keptNotes.get(callId) ?? null : null;
286
+ if (note && callId && typeof row.timestamp === "string") {
287
+ messages.push({ role: "Assistant", content: note, time: row.timestamp, id: `${callId}${SAVE_NOTE_SUFFIX}`, phase: "final_answer" });
288
+ }
289
+ else if (!note && scripted && callId && typeof row.timestamp === "string") {
290
+ unanswered = { callId, time: row.timestamp, after: messages.length };
291
+ }
292
+ }
293
+ if (row.payload.type !== "message")
294
+ continue;
295
+ const role = row.payload.role === "user" ? "User" : row.payload.role === "assistant" ? "Assistant" : null;
296
+ if (!role)
297
+ continue;
298
+ const written = textBlocks(row.payload.content);
299
+ // Codex writes its instructions and environment as user messages; they are not the user's words.
300
+ const content = role === "User" && readInFull(row.timestamp) ? stripHostNoise(written) : written;
301
+ if (!content.trim())
302
+ continue;
303
+ const time = typeof row.timestamp === "string" ? row.timestamp : "";
304
+ const id = typeof row.payload.id === "string" ? row.payload.id : "";
305
+ if (!time || !id)
306
+ throw new Error("SOURCE_SESSION_MISSING_METADATA");
307
+ const phase = row.payload.phase === "commentary" || row.payload.phase === "final_answer" ? row.payload.phase : undefined;
308
+ lastWritten = { role, content, time, id, ...(role === "Assistant" && phase ? { phase } : {}) };
309
+ messages.push(lastWritten);
310
+ }
311
+ if (!verified)
312
+ throw new Error("SOURCE_SESSION_MISMATCH");
313
+ // The call being answered right now is the turn's newest record. Its note is the one this
314
+ // very call carries, so it is taken from the call and placed where the host recorded it.
315
+ if (turnOpen && unanswered && unanswered.after === messages.length && pendingNote?.trim()) {
316
+ messages.push({ role: "Assistant", content: pendingNote.trim(), time: unanswered.time, id: `${unanswered.callId}${SAVE_NOTE_SUFFIX}`, phase: "final_answer" });
317
+ }
318
+ if (!messages.length)
319
+ throw new Error("SOURCE_SESSION_EMPTY");
320
+ return { messages, turnOpen };
321
+ }
322
+ /** Derive current evidence from one verified host transcript, never tool arguments. */
323
+ export function readStrictRawSession(identity, assistantMessageId) {
324
+ return readStrictRawSessionState(identity, assistantMessageId).rawData;
325
+ }
326
+ /** The same evidence, with whether the host is still writing the newest turn and which file
327
+ * holds it. A save reads only finished turns; one requested mid-turn waits for the turn to end.
328
+ * `pendingNote` is the note of the save call being answered, for a host record that names the
329
+ * call without holding its arguments as data. */
330
+ export function readStrictRawSessionState(identity, assistantMessageId, pendingNote) {
331
+ if (identity.evidence === "cloud_cowork_tool_argument")
332
+ throw new Error("SOURCE_SESSION_NOT_LOCALLY_VERIFIED");
333
+ let messages;
334
+ let turnOpen;
335
+ let file;
336
+ if (identity.provider === "claude-code") {
337
+ const ids = [identity.providerSessionId, ...(identity.providerSessionAliases ?? [])].filter((id) => UUID_RE.test(id));
338
+ const root = resolveClaudeProjectsDir();
339
+ if (!root || ids.length === 0)
340
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
341
+ file = locate(root, (name) => ids.some((id) => name === `${id}.jsonl`));
342
+ ({ messages, turnOpen } = claudeTurn(parseLines(file), new Set(ids)));
343
+ }
344
+ else if (identity.provider === "cowork") {
345
+ const source = resolveCoworkSource(identity.providerSessionId);
346
+ file = source.transcriptPath;
347
+ ({ messages, turnOpen } = claudeTurn(parseLines(file), new Set([source.cliSessionId])));
348
+ }
349
+ else if (identity.provider === "codex") {
350
+ const id = identity.providerSessionId;
351
+ if (!UUID_RE.test(id))
352
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
353
+ const roots = resolveCodexSessionRoots({ failOnUnreadable: true });
354
+ if (!roots.length)
355
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
356
+ const matches = roots.map((root) => {
357
+ try {
358
+ return locate(root.path, (name) => name.endsWith(`-${id}.jsonl`));
359
+ }
360
+ catch (error) {
361
+ if (error instanceof Error && error.message === "SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE")
362
+ return null;
363
+ throw error;
364
+ }
365
+ }).filter((match) => match !== null);
366
+ // Readable session folders hold no file for this thread: a cloud chat. Only this case lets a
367
+ // bound Codex save fall back to agent messages; unreadable folders or a bad ID fail closed above.
368
+ if (matches.length === 0)
369
+ throw new Error("SOURCE_SESSION_NO_LOCAL_TRANSCRIPT");
370
+ if (matches.length > 1)
371
+ throw new Error("SOURCE_SESSION_AMBIGUOUS");
372
+ file = matches[0];
373
+ ({ messages, turnOpen } = codexTurn(parseLines(file), id, pendingNote, readSaveNotes(id)));
374
+ }
375
+ else {
376
+ throw new Error("SOURCE_SESSION_TRANSCRIPT_UNAVAILABLE");
377
+ }
378
+ if (assistantMessageId !== undefined) {
379
+ const end = messages.findIndex(message => message.id === assistantMessageId && message.role === "Assistant");
380
+ if (end < 0)
381
+ throw new Error("ASSISTANT_BOUNDARY_UNAVAILABLE");
382
+ messages = messages.slice(0, end + 1);
383
+ }
384
+ // JSON-encode each original text so a user-authored line beginning with
385
+ // "## " cannot forge a new turn or switch its role in the backend parser.
386
+ const blocks = messages.map((m) => `## ${m.role} ${m.time} [${m.id}]${m.phase ? ` phase=${m.phase}` : ""}\n\n${JSON.stringify(m.content)}`);
387
+ return { rawData: fitRawBudget(blocks, messages.map((m) => m.role)), turnOpen, file };
388
+ }
389
+ /** A window over budget keeps its newest whole exchanges: drop from the front, cutting only
390
+ * where a user message begins, so the backend sees complete turns. The ledger treats what
391
+ * fell off as history before the window, not as a gap. One turn over budget cannot be sent. */
392
+ function fitRawBudget(blocks, roles) {
393
+ const size = (block) => Buffer.byteLength(block, "utf8") + 2;
394
+ let start = 0;
395
+ let bytes = blocks.reduce((sum, block) => sum + size(block), -2);
396
+ while (bytes > MAX_RAW_BYTES) {
397
+ let next = start + 1;
398
+ while (next < blocks.length && roles[next] !== "User")
399
+ next++;
400
+ if (next >= blocks.length)
401
+ throw new Error("SOURCE_SESSION_TOO_LARGE");
402
+ for (let index = start; index < next; index++)
403
+ bytes -= size(blocks[index]);
404
+ start = next;
405
+ }
406
+ return blocks.slice(start).join("\n\n");
407
+ }
408
+ /** A save made before the current answer has completed must not commit an older
409
+ * answer and consume the current request. The Stop checkpoint retries after completion. */
410
+ export function completedSaveBoundary(rawData) {
411
+ const headers = [...rawData.matchAll(/^## (User|Assistant) \S+ \[([^\]\n]+)\](?: phase=(commentary|final_answer))?$/gm)];
412
+ const last = headers.at(-1);
413
+ return last?.[1] === "Assistant" && last[3] === "final_answer" ? last[2] : null;
414
+ }
415
+ /** Freeze only a verified native boundary: the answer the save was made for, or the
416
+ * user's explicit retention command. A turn with neither saves nothing; it never
417
+ * reaches back to an earlier turn's answer. */
418
+ export function selectSaveEvidence(rawData, requested = {}, turnOpen = false) {
419
+ if (requested.assistantMessageId && requested.userMessageId)
420
+ throw new Error("SAVE_BOUNDARY_CONFLICT");
421
+ const allBlocks = rawData.split(/\n\n(?=## (?:User|Assistant) )/);
422
+ const allMessages = allBlocks.map(block => {
423
+ const match = /^## (User|Assistant) (\S+) \[([^\]\n]+)\](?: phase=(commentary|final_answer))?\n\n/.exec(block);
424
+ if (!match)
425
+ throw new Error("SOURCE_SESSION_INVALID_INPUT");
426
+ return { role: match[1], time: match[2], id: match[3], phase: match[4], text: JSON.parse(block.slice(match[0].length)) };
427
+ });
428
+ const latest = allMessages.map(message => message.role === "User" && Boolean(userRequestText(message.text))).lastIndexOf(true);
429
+ if (latest >= 0 && isMemorySaveDeclined(allMessages[latest].text))
430
+ throw new Error("MEMORY_SAVE_DECLINED: the latest user request asks not to save; no source was submitted.");
431
+ // A turn the user asked not to save is left out of every later save too, not only its own.
432
+ let declined = false;
433
+ const kept = allMessages.map(message => {
434
+ if (message.role === "User" && userRequestText(message.text))
435
+ declined = readInFull(message.time) && isMemorySaveDeclined(message.text);
436
+ return !declined;
437
+ });
438
+ const blocks = allBlocks.filter((_, index) => kept[index]);
439
+ const messages = allMessages.filter((_, index) => kept[index]);
440
+ const lastUser = messages.map(message => message.role === "User" && Boolean(userRequestText(message.text))).lastIndexOf(true);
441
+ let index = -1;
442
+ if (requested.userMessageId) {
443
+ index = messages.findIndex(message => message.id === requested.userMessageId && message.role === "User");
444
+ if (index < 0 || !isExplicitSaveRequest(messages[index].text))
445
+ throw new Error("EXPLICIT_USER_BOUNDARY_UNAVAILABLE");
446
+ }
447
+ else if (requested.assistantMessageId) {
448
+ index = messages.findIndex(message => message.id === requested.assistantMessageId && message.role === "Assistant" && message.phase === "final_answer");
449
+ if (index < 0)
450
+ throw new Error("ASSISTANT_BOUNDARY_UNAVAILABLE");
451
+ }
452
+ else if (!turnOpen && messages.at(-1)?.phase === "final_answer") {
453
+ // Only a finished turn has a final answer; text written so far in an open turn is not one.
454
+ index = messages.length - 1;
455
+ }
456
+ else if (lastUser >= 0 && isExplicitSaveRequest(messages[lastUser].text)) {
457
+ index = lastUser;
458
+ }
459
+ else if (turnOpen && requested.note?.trim() && messages.at(-1)?.id.endsWith(SAVE_NOTE_SUFFIX)
460
+ && messages.at(-1)?.phase === "final_answer" && messages.at(-1)?.text === requested.note.trim()) {
461
+ // The turn is still open, and the host has recorded this very call: its note is the
462
+ // answer this save is made for. A note from an earlier call never stands in for it.
463
+ index = messages.length - 1;
464
+ }
465
+ if (index < 0)
466
+ return null;
467
+ const selected = messages[index];
468
+ return {
469
+ rawData: blocks.slice(0, index + 1).join("\n\n"),
470
+ boundary: selected.role === "User" ? { userMessageId: selected.id } : { assistantMessageId: selected.id },
471
+ explicitRequest: latestUserRequestsSave(messages.slice(0, index + 1).map(message => ({ role: message.role.toLowerCase(), text: message.text }))),
472
+ };
473
+ }
@@ -0,0 +1,62 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
4
+ import { echoConfigDir } from "./keystore.js";
5
+ const CACHE_TTL_MS = 30 * 60 * 1000;
6
+ const MAX_CACHE_BYTES = 64 * 1024;
7
+ function cacheFile(kind, token) {
8
+ const account = createHash("sha256").update(token).digest("hex").slice(0, 24);
9
+ return path.join(echoConfigDir(), "tool-map-cache", `${account}-${kind}.json`);
10
+ }
11
+ function cipherKey(token, vaultKey) {
12
+ return createHash("sha256").update("echomem-tool-map-v1\0").update(token).update("\0").update(vaultKey).digest();
13
+ }
14
+ /** Tool maps contain private topics, so cache only when the local vault is unlocked. */
15
+ export function readToolMapCache(kind, token, vaultKey) {
16
+ if (!token || !vaultKey)
17
+ return undefined;
18
+ try {
19
+ const file = cacheFile(kind, token);
20
+ const stat = fs.statSync(file);
21
+ if (!stat.isFile() || stat.size > MAX_CACHE_BYTES)
22
+ return undefined;
23
+ const envelope = JSON.parse(fs.readFileSync(file, "utf8"));
24
+ if (envelope.version !== 1 || envelope.expiresAt <= Date.now())
25
+ return undefined;
26
+ const decipher = createDecipheriv("aes-256-gcm", cipherKey(token, vaultKey), Buffer.from(envelope.iv, "base64"));
27
+ decipher.setAuthTag(Buffer.from(envelope.tag, "base64"));
28
+ const plaintext = Buffer.concat([
29
+ decipher.update(Buffer.from(envelope.ciphertext, "base64")),
30
+ decipher.final(),
31
+ ]).toString("utf8");
32
+ return plaintext || undefined;
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ export function writeToolMapCache(kind, value, token, vaultKey) {
39
+ if (!token || !vaultKey || !value || Buffer.byteLength(value) > MAX_CACHE_BYTES / 2)
40
+ return;
41
+ try {
42
+ const file = cacheFile(kind, token);
43
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
44
+ const iv = randomBytes(12);
45
+ const cipher = createCipheriv("aes-256-gcm", cipherKey(token, vaultKey), iv);
46
+ const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
47
+ const envelope = {
48
+ version: 1,
49
+ expiresAt: Date.now() + CACHE_TTL_MS,
50
+ iv: iv.toString("base64"),
51
+ tag: cipher.getAuthTag().toString("base64"),
52
+ ciphertext: ciphertext.toString("base64"),
53
+ };
54
+ const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
55
+ fs.writeFileSync(temporary, JSON.stringify(envelope), { mode: 0o600, flag: "wx" });
56
+ fs.renameSync(temporary, file);
57
+ fs.chmodSync(file, 0o600);
58
+ }
59
+ catch {
60
+ // A cache failure never blocks tool listing or changes memory access.
61
+ }
62
+ }
@@ -0,0 +1,104 @@
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 MAX_AGE_MS = 24 * 60 * 60 * 1000;
6
+ const ENTRY = /^([0-9a-f]{32})\.(\d+)\.json$/;
7
+ const directory = () => path.join(echoConfigDir(), "turn-end-saves");
8
+ const entryName = (contextId, pid) => `${createHash("sha256").update(contextId).digest("hex").slice(0, 32)}.${pid}.json`;
9
+ export const credentialHash = (token) => createHash("sha256").update(token).digest("hex");
10
+ function alive(pid) {
11
+ try {
12
+ process.kill(pid, 0);
13
+ return true;
14
+ }
15
+ catch (error) {
16
+ return error.code === "EPERM";
17
+ }
18
+ }
19
+ /** Record the request on disk so a bridge that exits before the turn ends does not lose it. */
20
+ export function registerTurnEndSave(entry) {
21
+ try {
22
+ const dir = directory();
23
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
24
+ const temporary = path.join(dir, `.${randomUUID()}.tmp`);
25
+ fs.writeFileSync(temporary, JSON.stringify(entry), { mode: 0o600 });
26
+ fs.renameSync(temporary, path.join(dir, entryName(entry.contextId, process.pid)));
27
+ }
28
+ catch {
29
+ // The running bridge still completes the save; only recovery after an exit is lost.
30
+ }
31
+ }
32
+ export function finishTurnEndSave(contextId) {
33
+ try {
34
+ fs.unlinkSync(path.join(directory(), entryName(contextId, process.pid)));
35
+ }
36
+ catch { /* already gone */ }
37
+ }
38
+ /** Take over the requests of bridge processes that no longer run, for this account and
39
+ * backend. Renaming to this process's name is the claim, so two bridges never both take one. */
40
+ export function claimAbandonedTurnEndSaves(account, backend, now = Date.now()) {
41
+ const claimed = [];
42
+ let names;
43
+ try {
44
+ names = fs.readdirSync(directory());
45
+ }
46
+ catch {
47
+ return claimed;
48
+ }
49
+ for (const name of names) {
50
+ const match = ENTRY.exec(name);
51
+ if (!match || alive(Number(match[2])))
52
+ continue;
53
+ const file = path.join(directory(), name);
54
+ try {
55
+ const entry = JSON.parse(fs.readFileSync(file, "utf8"));
56
+ if (entry?.v !== 1 || typeof entry.contextId !== "string" || now - entry.registeredAt > MAX_AGE_MS) {
57
+ fs.unlinkSync(file);
58
+ continue;
59
+ }
60
+ if (entry.credentialHash !== account || entry.backend !== backend)
61
+ continue;
62
+ fs.renameSync(file, path.join(directory(), entryName(entry.contextId, process.pid)));
63
+ claimed.push(entry);
64
+ }
65
+ catch {
66
+ // Unreadable, or another bridge claimed it first.
67
+ }
68
+ }
69
+ return claimed;
70
+ }
71
+ /** Call `closed` once the host has finished the turn. The transcript is read again only after
72
+ * it changed and then stayed unchanged for one interval, so a record still being written is
73
+ * never read. The timer never keeps the bridge process alive. */
74
+ export function whenTurnEnds(file, turnOpen, closed, intervalMs = 1000) {
75
+ let seen = -1;
76
+ let read = -1;
77
+ let done = false;
78
+ const finish = () => { if (!done) {
79
+ done = true;
80
+ closed();
81
+ } };
82
+ const check = () => {
83
+ if (done)
84
+ return;
85
+ let size = -1;
86
+ try {
87
+ size = fs.statSync(file).size;
88
+ }
89
+ catch { /* briefly missing: keep waiting */ }
90
+ if (size === seen && size !== read) {
91
+ read = size;
92
+ let open = true;
93
+ try {
94
+ open = turnOpen();
95
+ }
96
+ catch { /* unreadable right now: wait for the next change */ }
97
+ if (!open)
98
+ return finish();
99
+ }
100
+ seen = size;
101
+ setTimeout(check, intervalMs).unref();
102
+ };
103
+ setTimeout(check, intervalMs).unref();
104
+ }