mr-memory 3.9.0 → 3.10.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.
package/README.md CHANGED
@@ -40,6 +40,19 @@ openclaw mr upload --workspace <dir> # Custom workspace directory
40
40
  openclaw mr upload --brain <dir> # Custom state dir (sessions from another agent)
41
41
  ```
42
42
 
43
+ ## Historical Import (agent-driven)
44
+
45
+ Import existing OpenClaw conversation history with a strict division of labor: the server owns the extraction prompt (versioned, fetched at import time), your agent owns discovery/parsing of the local session files, and the CLI owns transport. The agent never uploads; the CLI never parses history.
46
+
47
+ ```bash
48
+ openclaw mr import --instructions # print the server's extraction prompt for your agent
49
+ openclaw mr import --file extract.jsonl # validate, preview, price quote, approve, upload
50
+ openclaw mr import --file extract.jsonl --yes # non-interactive approval
51
+ openclaw mr import --dismiss # permanently silence the import nudge
52
+ ```
53
+
54
+ Guarantees: the extract is validated locally (four fields per record, `openclaw:` prefixed ids, epoch-ms timestamps); the CLI shows record count, date range, estimated tokens, and the server price quote and requires explicit approval before any write; the import id is content-derived and every batch carries an Idempotency-Key, so re-running after any interruption replays committed batches for free and resumes. Duplicates are never re-billed. The memory key never appears in the prompt or the extract file. When a vault is new, injected context includes a one-line import suggestion until an import completes or you `--dismiss`.
55
+
43
56
  ## How It Works
44
57
 
45
58
  When enabled, relay hooks retrieve memory before agent/model input and capture the direct user-to-assistant conversation at `agent_end`. Inference and provider API keys remain inside OpenClaw; the plugin does not route provider calls through MemoryRouter and is not a provider-key proxy.
@@ -0,0 +1,457 @@
1
+ /**
2
+ * Agent-driven historical import: the transport half (OpenClaw lane).
3
+ *
4
+ * Division of labor (locked): the SERVER owns the extraction prompt
5
+ * (GET /v1/memory/imports/instructions, versioned like reflection_contract);
6
+ * the HOST AGENT executes that prompt locally and writes a JSONL extract; THIS
7
+ * MODULE owns transport only: local validation, deterministic identity math
8
+ * (byte-for-byte with workers/src/services/import-identity.ts), create and
9
+ * approve, idempotent batch upload with resume, and the receipt. The agent
10
+ * never touches HTTP for upload and this module never parses history.
11
+ *
12
+ * The Memory Key never appears in the prompt or the extract file; it rides
13
+ * only in the Authorization header.
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { readFileSync } from "node:fs";
17
+ import readline from "node:readline";
18
+ import { importInstructions, importCreate, importApprove, importBatch, importStatus, importReceipt, importDismiss, } from "./memoryrouter-api.js";
19
+ export const PLATFORM = "openclaw";
20
+ export const PARSER_VERSION = 1;
21
+ export const CHUNK_VERSION = 1;
22
+ const BATCH_SIZE = 2000;
23
+ const MAX_CONTENT_CHARS = 1000000;
24
+ const MAX_UPLOAD_ATTEMPTS = 5;
25
+ const INITIAL_BACKOFF_MS = 2000;
26
+ const MAX_BACKOFF_MS = 30000;
27
+ // ── identity math (mirrors the server byte-for-byte) ─────────────────────────
28
+ function sha256hex(input) {
29
+ return createHash("sha256").update(input, "utf8").digest("hex");
30
+ }
31
+ function sortKeys(value) {
32
+ if (Array.isArray(value))
33
+ return value.map(sortKeys);
34
+ if (value && typeof value === "object") {
35
+ const out = {};
36
+ for (const key of Object.keys(value).sort()) {
37
+ out[key] = sortKeys(value[key]);
38
+ }
39
+ return out;
40
+ }
41
+ return value;
42
+ }
43
+ export function canonicalJson(value) {
44
+ return JSON.stringify(sortKeys(value));
45
+ }
46
+ export function normalizeText(input) {
47
+ return input.normalize("NFC").replace(/\r\n?/g, "\n").trim();
48
+ }
49
+ export function vaultFingerprint(memoryKey) {
50
+ return `mrvault_${sha256hex(memoryKey).slice(0, 16)}`;
51
+ }
52
+ function unescapeIdPart(s) {
53
+ return s.replace(/%3A/g, ":").replace(/%25/g, "%");
54
+ }
55
+ export function parseExternalId(id) {
56
+ const parts = id.split(":");
57
+ if (parts.length !== 4)
58
+ return null;
59
+ const [platform, conv, msg, ver] = parts;
60
+ if (!/^v\d+$/.test(ver))
61
+ return null;
62
+ return {
63
+ platform,
64
+ conversationId: unescapeIdPart(conv),
65
+ messageId: unescapeIdPart(msg),
66
+ parserVersion: parseInt(ver.slice(1), 10),
67
+ };
68
+ }
69
+ export function recordHash(fields) {
70
+ return sha256hex(canonicalJson({
71
+ conversationId: fields.conversationId,
72
+ messageId: fields.messageId,
73
+ role: fields.role,
74
+ text: normalizeText(fields.text),
75
+ timestamp: fields.timestamp,
76
+ v: PARSER_VERSION,
77
+ })).slice(0, 32);
78
+ }
79
+ export function conversationContentHash(fields) {
80
+ return sha256hex(canonicalJson(fields)).slice(0, 32);
81
+ }
82
+ export function archiveContentId(conversationContentHashes) {
83
+ const canonical = [...conversationContentHashes].sort().join("\n");
84
+ return `arc_${sha256hex(`v${PARSER_VERSION}\n${canonical}`).slice(0, 24)}`;
85
+ }
86
+ export function deriveImportId(archiveId, fingerprint) {
87
+ return `imp_${sha256hex(`${archiveId}|${fingerprint}|p${PARSER_VERSION}|c${CHUNK_VERSION}`).slice(0, 24)}`;
88
+ }
89
+ export function previewDigest(preview) {
90
+ return `pvd_${sha256hex(canonicalJson(preview)).slice(0, 32)}`;
91
+ }
92
+ export function readExtract(filePath, platform = PLATFORM) {
93
+ let raw;
94
+ try {
95
+ raw = readFileSync(filePath, "utf8");
96
+ }
97
+ catch (err) {
98
+ return { error: `could not read ${filePath}: ${err instanceof Error ? err.message : String(err)}` };
99
+ }
100
+ const records = [];
101
+ const seen = new Set();
102
+ const lines = raw.split("\n");
103
+ for (let i = 0; i < lines.length; i++) {
104
+ const line = lines[i].trim();
105
+ if (!line)
106
+ continue;
107
+ const lineNo = i + 1;
108
+ let p;
109
+ try {
110
+ p = JSON.parse(line);
111
+ }
112
+ catch {
113
+ return { error: `line ${lineNo}: not valid JSON` };
114
+ }
115
+ if (!p || typeof p !== "object" || Array.isArray(p))
116
+ return { error: `line ${lineNo}: record is not an object` };
117
+ const extras = Object.keys(p).filter((k) => !["external_id", "content", "timestamp", "role"].includes(k));
118
+ if (extras.length)
119
+ return { error: `line ${lineNo}: unexpected fields: ${extras.join(", ")}` };
120
+ if (typeof p.external_id !== "string" || !p.external_id)
121
+ return { error: `line ${lineNo}: external_id must be a string` };
122
+ const parsed = parseExternalId(p.external_id);
123
+ if (!parsed)
124
+ return { error: `line ${lineNo}: malformed external_id (expected ${platform}:<conversation>:<message>:v${PARSER_VERSION})` };
125
+ if (parsed.platform !== platform)
126
+ return { error: `line ${lineNo}: external_id platform must be ${platform}, got ${parsed.platform}` };
127
+ if (parsed.parserVersion !== PARSER_VERSION)
128
+ return { error: `line ${lineNo}: external_id version must be v${PARSER_VERSION}` };
129
+ if (typeof p.content !== "string" || p.content.length === 0)
130
+ return { error: `line ${lineNo}: content must be a non-empty string` };
131
+ if (p.content.length > MAX_CONTENT_CHARS)
132
+ return { error: `line ${lineNo}: content exceeds ${MAX_CONTENT_CHARS} chars` };
133
+ if (typeof p.timestamp !== "number" || !Number.isFinite(p.timestamp) || p.timestamp <= 0) {
134
+ return { error: `line ${lineNo}: timestamp must be a positive epoch-milliseconds number` };
135
+ }
136
+ if (p.timestamp < 1000000000000)
137
+ return { error: `line ${lineNo}: timestamp looks like seconds, not milliseconds (${p.timestamp})` };
138
+ if (p.role !== "user" && p.role !== "assistant")
139
+ return { error: `line ${lineNo}: role must be "user" or "assistant"` };
140
+ if (seen.has(p.external_id))
141
+ return { error: `line ${lineNo}: duplicate external_id ${p.external_id}` };
142
+ seen.add(p.external_id);
143
+ records.push({
144
+ externalId: p.external_id,
145
+ conversationId: parsed.conversationId,
146
+ messageId: parsed.messageId,
147
+ content: p.content,
148
+ role: p.role,
149
+ timestamp: p.timestamp,
150
+ });
151
+ }
152
+ if (records.length === 0)
153
+ return { error: "the extract file contains no records" };
154
+ return { records };
155
+ }
156
+ // ── identity + preview ───────────────────────────────────────────────────────
157
+ export function computeIdentity(records, memoryKey, platform = PLATFORM) {
158
+ const byConversation = new Map();
159
+ for (const r of records) {
160
+ r.recordSha256 = recordHash({
161
+ conversationId: r.conversationId,
162
+ messageId: r.messageId,
163
+ role: r.role,
164
+ text: r.content,
165
+ timestamp: r.timestamp,
166
+ });
167
+ if (!byConversation.has(r.conversationId))
168
+ byConversation.set(r.conversationId, []);
169
+ byConversation.get(r.conversationId).push(r);
170
+ }
171
+ const convHashes = [];
172
+ for (const [conversationId, convRecords] of byConversation) {
173
+ convHashes.push(conversationContentHash({
174
+ conversationId,
175
+ canonicalPolicy: `agent-extract-${platform}`,
176
+ canonicalLeaf: null,
177
+ records: convRecords.map((r) => ({
178
+ externalId: r.externalId,
179
+ recordHash: r.recordSha256,
180
+ role: r.role,
181
+ timestamp: r.timestamp,
182
+ })),
183
+ }));
184
+ }
185
+ const archiveId = archiveContentId(convHashes);
186
+ const fingerprint = vaultFingerprint(memoryKey);
187
+ const importId = deriveImportId(archiveId, fingerprint);
188
+ return { archiveId, fingerprint, importId, conversations: byConversation.size };
189
+ }
190
+ export function estimateTokens(records) {
191
+ let total = 0;
192
+ for (const r of records)
193
+ total += Math.ceil(r.content.length / 4);
194
+ return total;
195
+ }
196
+ export function buildPreviewSummary(records) {
197
+ let earliest = Number.POSITIVE_INFINITY;
198
+ let latest = 0;
199
+ let user = 0;
200
+ for (const r of records) {
201
+ if (r.role === "user")
202
+ user++;
203
+ if (r.timestamp < earliest)
204
+ earliest = r.timestamp;
205
+ if (r.timestamp > latest)
206
+ latest = r.timestamp;
207
+ }
208
+ return {
209
+ records: records.length,
210
+ userRecords: user,
211
+ assistantRecords: records.length - user,
212
+ earliestMs: Number.isFinite(earliest) ? earliest : 0,
213
+ latestMs: latest,
214
+ estimatedTokens: estimateTokens(records),
215
+ };
216
+ }
217
+ export function toWireRecord(r, platform = PLATFORM) {
218
+ return JSON.stringify({
219
+ external_id: r.externalId,
220
+ record_sha256: r.recordSha256,
221
+ content: r.content,
222
+ role: r.role,
223
+ timestamp: r.timestamp,
224
+ source_platform: platform,
225
+ parser_version: PARSER_VERSION,
226
+ chunk_version: CHUNK_VERSION,
227
+ });
228
+ }
229
+ const defaultFetchers = {
230
+ importInstructions,
231
+ importCreate,
232
+ importApprove,
233
+ importBatch,
234
+ importStatus,
235
+ importReceipt,
236
+ importDismiss,
237
+ };
238
+ function fmtDate(ms) {
239
+ if (!Number.isFinite(ms) || ms <= 0)
240
+ return "unknown";
241
+ return new Date(ms).toISOString().slice(0, 10);
242
+ }
243
+ function fmtTokens(n) {
244
+ if (n >= 1000000)
245
+ return `${(n / 1000000).toFixed(1)}M`;
246
+ if (n >= 1000)
247
+ return `${(n / 1000).toFixed(1)}K`;
248
+ return String(n);
249
+ }
250
+ async function jsonOf(res) {
251
+ try {
252
+ return (await res.json());
253
+ }
254
+ catch {
255
+ return {};
256
+ }
257
+ }
258
+ function errorDetail(status, body) {
259
+ const parts = [body.error, body.message].filter(Boolean);
260
+ return parts.length ? parts.join(": ") : `HTTP ${status}`;
261
+ }
262
+ function sleep(ms) {
263
+ return new Promise((resolve) => setTimeout(resolve, ms));
264
+ }
265
+ function ask(question) {
266
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
267
+ return new Promise((resolve) => rl.question(question, (answer) => {
268
+ rl.close();
269
+ resolve(answer.trim().toLowerCase());
270
+ }));
271
+ }
272
+ /** Fetch and print the server-side extraction prompt for the host agent. */
273
+ export async function runInstructions(options) {
274
+ const f = { ...defaultFetchers, ...(options.fetchers || {}) };
275
+ const log = options.log || ((...args) => console.log(...args));
276
+ const res = await f.importInstructions(options.endpoint, options.key, options.platform || PLATFORM);
277
+ const body = await jsonOf(res);
278
+ if (!res.ok)
279
+ throw new Error(`could not fetch import instructions (${errorDetail(res.status, body)})`);
280
+ if (!body.prompt)
281
+ throw new Error("instructions response carried no prompt");
282
+ log(body.prompt);
283
+ return { version: Number(body.import_prompt_version) || 0 };
284
+ }
285
+ /** Call the dismiss endpoint so the server-side nudge stops permanently. */
286
+ export async function runDismiss(options) {
287
+ const f = { ...defaultFetchers, ...(options.fetchers || {}) };
288
+ const log = options.log || ((...args) => console.log(...args));
289
+ const res = await f.importDismiss(options.endpoint, options.key, options.platform || PLATFORM);
290
+ const body = await jsonOf(res);
291
+ if (!res.ok)
292
+ throw new Error(`dismiss failed (${errorDetail(res.status, body)})`);
293
+ log("Import suggestion dismissed permanently for this vault.");
294
+ }
295
+ /** The transport: validate, create, quote, approve, upload, receipt. */
296
+ export async function runImportFile(options) {
297
+ const f = { ...defaultFetchers, ...(options.fetchers || {}) };
298
+ const log = options.log || ((...args) => console.log(...args));
299
+ const platform = options.platform || PLATFORM;
300
+ if (!options.file)
301
+ throw new Error("--file <path> is required");
302
+ const parsed = readExtract(options.file, platform);
303
+ if (parsed.error)
304
+ throw new Error(`invalid extract: ${parsed.error}`);
305
+ const records = parsed.records;
306
+ const identity = computeIdentity(records, options.key, platform);
307
+ const preview = buildPreviewSummary(records);
308
+ const clientPreviewDigest = previewDigest({
309
+ importId: identity.importId,
310
+ archiveId: identity.archiveId,
311
+ fingerprint: identity.fingerprint,
312
+ parserVersion: PARSER_VERSION,
313
+ chunkVersion: CHUNK_VERSION,
314
+ expectedRecords: preview.records,
315
+ expectedChunks: preview.records,
316
+ estimatedTokens: preview.estimatedTokens,
317
+ selection: null,
318
+ categories: [],
319
+ });
320
+ const createRes = await f.importCreate(options.endpoint, options.key, {
321
+ import_id: identity.importId,
322
+ archive_content_id: identity.archiveId,
323
+ archive_sha256: null,
324
+ parser_version: PARSER_VERSION,
325
+ chunk_version: CHUNK_VERSION,
326
+ source_platform: platform,
327
+ vault_fingerprint: identity.fingerprint,
328
+ preview_digest: clientPreviewDigest,
329
+ expected_records: preview.records,
330
+ expected_chunks: preview.records,
331
+ estimated_tokens: preview.estimatedTokens,
332
+ selection: null,
333
+ categories: [],
334
+ });
335
+ const created = await jsonOf(createRes);
336
+ if (!createRes.ok)
337
+ throw new Error(`import preflight failed (${errorDetail(createRes.status, created)})`);
338
+ if (created.preview_digest && created.preview_digest !== clientPreviewDigest) {
339
+ throw new Error("client/server preview digest mismatch (fail closed)");
340
+ }
341
+ const quote = (created.cost_quote || {});
342
+ log("");
343
+ log("Import preview");
344
+ log("----------------------------");
345
+ log(`Platform: ${platform}`);
346
+ log(`Destination vault: ${identity.fingerprint} (opaque fingerprint)`);
347
+ log(`Conversations: ${identity.conversations}`);
348
+ log(`Records: ${preview.records} (user ${preview.userRecords}, assistant ${preview.assistantRecords})`);
349
+ log(`Date range: ${fmtDate(preview.earliestMs)} to ${fmtDate(preview.latestMs)}`);
350
+ log(`Estimated tokens: ${fmtTokens(preview.estimatedTokens)}`);
351
+ if (quote.available) {
352
+ log(`Estimated cost: $${((quote.estimated_cost_cents || 0) / 100).toFixed(2)} (rate $${quote.rate_per_million_usd}/1M paid tokens, free remaining ${fmtTokens(quote.free_tokens_remaining || 0)})`);
353
+ }
354
+ else {
355
+ log(`Estimated cost: unavailable (${quote.reason || "unknown"}); the server will refuse approval (fail closed)`);
356
+ }
357
+ log(`Import id: ${identity.importId}`);
358
+ log("");
359
+ log("Re-running this command is always safe: committed batches replay for free and duplicates are never re-billed.");
360
+ log("");
361
+ if (!options.yes) {
362
+ if (options.nonInteractive || !process.stdin.isTTY) {
363
+ throw new Error("approval required: re-run with --yes to confirm the upload");
364
+ }
365
+ const answer = await ask("Proceed with the upload? [y/N]: ");
366
+ if (answer !== "y" && answer !== "yes") {
367
+ log("Aborted. Nothing was uploaded.");
368
+ return { aborted: true };
369
+ }
370
+ }
371
+ const approveRes = await f.importApprove(options.endpoint, options.key, identity.importId, String(created.approval_digest));
372
+ if (!approveRes.ok) {
373
+ const body = await jsonOf(approveRes);
374
+ // A completed import cannot be re-approved; that is the fully-settled
375
+ // resume case. Print the receipt instead of failing.
376
+ if (body.error === "import_completed") {
377
+ const receiptRes = await f.importReceipt(options.endpoint, options.key, identity.importId);
378
+ let receipt = null;
379
+ if (receiptRes.ok) {
380
+ const receiptBody = await jsonOf(receiptRes);
381
+ receipt = receiptBody.receipt ?? null;
382
+ }
383
+ log("This exact extract was already fully imported into this vault. Nothing to upload.");
384
+ if (receipt) {
385
+ log("Receipt:");
386
+ log(JSON.stringify(receipt, null, 2));
387
+ }
388
+ return { importId: identity.importId, complete: true, receipt };
389
+ }
390
+ throw new Error(`approval refused (${errorDetail(approveRes.status, body)})`);
391
+ }
392
+ const batches = [];
393
+ const size = options.batchSize || BATCH_SIZE;
394
+ for (let i = 0; i < records.length; i += size)
395
+ batches.push(records.slice(i, i + size));
396
+ const totals = { stored: 0, duplicate: 0, skipped: 0, failed: 0, conflict: 0 };
397
+ log(`Uploading ${records.length} record(s) in ${batches.length} batch(es)...`);
398
+ for (let i = 0; i < batches.length; i++) {
399
+ const jsonl = batches[i].map((r) => toWireRecord(r, platform)).join("\n");
400
+ const idempotencyKey = `${identity.importId}:b${i}`;
401
+ let res = null;
402
+ let backoff = INITIAL_BACKOFF_MS;
403
+ for (let attempt = 1; attempt <= MAX_UPLOAD_ATTEMPTS; attempt++) {
404
+ try {
405
+ res = await f.importBatch(options.endpoint, options.key, identity.importId, i, jsonl, idempotencyKey);
406
+ }
407
+ catch (err) {
408
+ res = null;
409
+ if (attempt === MAX_UPLOAD_ATTEMPTS) {
410
+ throw new Error(`batch ${i} failed after ${MAX_UPLOAD_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)}`);
411
+ }
412
+ }
413
+ if (res && (res.ok || (res.status < 500 && res.status !== 429)))
414
+ break;
415
+ if (attempt === MAX_UPLOAD_ATTEMPTS)
416
+ break;
417
+ await sleep(backoff);
418
+ backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
419
+ }
420
+ if (!res)
421
+ throw new Error(`batch ${i} received no response`);
422
+ const body = await jsonOf(res);
423
+ if (res.status === 402) {
424
+ throw new Error("payment required: out of tokens/credits. Add credits at https://app.memoryrouter.ai and re-run to resume.");
425
+ }
426
+ if (!res.ok)
427
+ throw new Error(`batch ${i} failed (${errorDetail(res.status, body)}). Re-run to resume; committed batches replay for free.`);
428
+ const s = (body.summary || {});
429
+ totals.stored += s.stored || 0;
430
+ totals.duplicate += s.duplicate || 0;
431
+ totals.skipped += s.skipped || 0;
432
+ totals.failed += s.failed || 0;
433
+ totals.conflict += s.conflict || 0;
434
+ log(` batch ${i + 1}/${batches.length}${body.replayed ? " (replayed, free)" : ""}: stored ${s.stored || 0}, duplicate ${s.duplicate || 0}, failed ${s.failed || 0}`);
435
+ }
436
+ const statusRes = await f.importStatus(options.endpoint, options.key, identity.importId);
437
+ const statusBody = await jsonOf(statusRes);
438
+ const complete = Boolean(statusRes.ok && statusBody.complete);
439
+ let receipt = null;
440
+ if (complete) {
441
+ const receiptRes = await f.importReceipt(options.endpoint, options.key, identity.importId);
442
+ if (receiptRes.ok) {
443
+ const receiptBody = await jsonOf(receiptRes);
444
+ receipt = receiptBody.receipt ?? null;
445
+ }
446
+ }
447
+ log("");
448
+ log(`Done. stored=${totals.stored} duplicate=${totals.duplicate} skipped=${totals.skipped} failed=${totals.failed} conflict=${totals.conflict}`);
449
+ if (receipt) {
450
+ log("Receipt:");
451
+ log(JSON.stringify(receipt, null, 2));
452
+ }
453
+ else if (!complete) {
454
+ log("The import is not fully settled yet; re-run this command to resume/reconcile.");
455
+ }
456
+ return { importId: identity.importId, totals, complete, receipt };
457
+ }