@memrosetta/cli 0.4.6 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,539 @@
1
+ import {
2
+ buildMemoryCreatedOp,
3
+ buildRelationCreatedOp,
4
+ openCliSyncContext
5
+ } from "./chunk-KPASMEV7.js";
6
+ import {
7
+ hasFlag,
8
+ optionalOption,
9
+ requireOption
10
+ } from "./chunk-NU5ZJJXP.js";
11
+ import {
12
+ output,
13
+ outputError
14
+ } from "./chunk-ET6TNQOJ.js";
15
+ import {
16
+ getConfig,
17
+ getDefaultDbPath,
18
+ writeConfig
19
+ } from "./chunk-SEPYQK3J.js";
20
+
21
+ // src/commands/sync.ts
22
+ import { randomUUID } from "crypto";
23
+ import { readFileSync } from "fs";
24
+ import { userInfo, platform } from "os";
25
+ import { createInterface } from "readline";
26
+ var ENV_API_KEY = "MEMROSETTA_SYNC_API_KEY";
27
+ var KEY_SOURCE_HINT = [
28
+ "API key required. Use exactly one of:",
29
+ " --key <value> (direct, visible in history)",
30
+ " --key-stdin (pipe from stdin)",
31
+ " --key-file <path> (read from file)",
32
+ ` ${ENV_API_KEY}=<value> (environment variable)`,
33
+ "",
34
+ "On POSIX TTYs an interactive hidden prompt is also available.",
35
+ "See: memrosetta sync enable --help"
36
+ ].join("\n");
37
+ function parseSubcommand(args) {
38
+ const first = args[0];
39
+ if (!first || first.startsWith("--")) return null;
40
+ if (first === "enable" || first === "disable" || first === "status" || first === "now" || first === "device-id" || first === "backfill") {
41
+ return first;
42
+ }
43
+ return null;
44
+ }
45
+ var CONTROL_CHAR_REGEX = /[\x00-\x1F\x7F]/;
46
+ function validateApiKey(key, sourceLabel) {
47
+ const trimmed = key.trim();
48
+ if (trimmed.length === 0) {
49
+ throw new Error(`API key from ${sourceLabel} is empty.`);
50
+ }
51
+ if (CONTROL_CHAR_REGEX.test(trimmed)) {
52
+ throw new Error(
53
+ `API key from ${sourceLabel} contains control characters. Try --key-file or MEMROSETTA_SYNC_API_KEY instead.`
54
+ );
55
+ }
56
+ return trimmed;
57
+ }
58
+ function readKeyFile(path) {
59
+ try {
60
+ return readFileSync(path, "utf-8");
61
+ } catch (err) {
62
+ const msg = err instanceof Error ? err.message : String(err);
63
+ throw new Error(`Could not read --key-file '${path}': ${msg}`);
64
+ }
65
+ }
66
+ async function resolveApiKey(args) {
67
+ const directKey = optionalOption(args, "--key");
68
+ const keyFile = optionalOption(args, "--key-file");
69
+ const useStdin = hasFlag(args, "--key-stdin");
70
+ const explicitCount = [directKey !== void 0, keyFile !== void 0, useStdin].filter(Boolean).length;
71
+ if (explicitCount > 1) {
72
+ throw new Error(
73
+ "Specify only one of --key, --key-stdin, --key-file."
74
+ );
75
+ }
76
+ if (directKey !== void 0) {
77
+ return validateApiKey(directKey, "--key");
78
+ }
79
+ if (useStdin) {
80
+ const raw = await readStdinKey();
81
+ if (!raw) {
82
+ throw new Error(
83
+ "--key-stdin produced no input. On Windows PowerShell, prefer --key-file or MEMROSETTA_SYNC_API_KEY."
84
+ );
85
+ }
86
+ return validateApiKey(raw, "--key-stdin");
87
+ }
88
+ if (keyFile !== void 0) {
89
+ return validateApiKey(readKeyFile(keyFile), `--key-file ${keyFile}`);
90
+ }
91
+ const envKey = process.env[ENV_API_KEY];
92
+ if (envKey !== void 0 && envKey.length > 0) {
93
+ return validateApiKey(envKey, ENV_API_KEY);
94
+ }
95
+ if (platform() !== "win32" && process.stdin.isTTY) {
96
+ const raw = await readHiddenInput("API key: ");
97
+ return validateApiKey(raw, "hidden prompt");
98
+ }
99
+ throw new Error(KEY_SOURCE_HINT);
100
+ }
101
+ async function readHiddenInput(prompt) {
102
+ const stdin = process.stdin;
103
+ const stdout = process.stdout;
104
+ if (!stdin.isTTY) {
105
+ throw new Error("Interactive input requires a TTY. Use --key-stdin to pipe the key instead.");
106
+ }
107
+ stdout.write(prompt);
108
+ const originalWrite = stdout.write.bind(stdout);
109
+ let muted = true;
110
+ stdout.write = (chunk, ...rest) => {
111
+ if (!muted) {
112
+ return originalWrite(chunk, ...rest);
113
+ }
114
+ const str = typeof chunk === "string" ? chunk : chunk?.toString?.("utf-8") ?? "";
115
+ if (str === "\n" || str === "\r\n" || str === "\r") {
116
+ return originalWrite(chunk, ...rest);
117
+ }
118
+ return true;
119
+ };
120
+ const rl = createInterface({
121
+ input: stdin,
122
+ output: stdout,
123
+ terminal: true
124
+ });
125
+ try {
126
+ const answer = await new Promise((resolve, reject) => {
127
+ rl.once("close", () => {
128
+ reject(new Error("Aborted"));
129
+ });
130
+ rl.question("", (value) => {
131
+ resolve(value);
132
+ });
133
+ });
134
+ return answer;
135
+ } finally {
136
+ muted = false;
137
+ stdout.write = originalWrite;
138
+ rl.close();
139
+ }
140
+ }
141
+ async function readStdinKey() {
142
+ const chunks = [];
143
+ for await (const chunk of process.stdin) {
144
+ chunks.push(chunk);
145
+ }
146
+ return Buffer.concat(chunks).toString("utf-8").trim();
147
+ }
148
+ async function testConnection(serverUrl, apiKey) {
149
+ const url = `${serverUrl.replace(/\/$/, "")}/sync/health`;
150
+ try {
151
+ const res = await fetch(url, {
152
+ headers: { Authorization: `Bearer ${apiKey}` }
153
+ });
154
+ if (!res.ok) {
155
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
156
+ }
157
+ } catch (err) {
158
+ const msg = err instanceof Error ? err.message : String(err);
159
+ throw new Error(`Sync server health check failed: ${msg}`);
160
+ }
161
+ }
162
+ async function withSyncClient(dbPath, config, fn) {
163
+ const Database = (await import("better-sqlite3")).default;
164
+ const { SyncClient, ensureSyncSchema } = await import("@memrosetta/sync-client");
165
+ if (!config.syncServerUrl || !config.syncApiKey || !config.syncDeviceId) {
166
+ throw new Error("Sync is not configured. Run: memrosetta sync enable --server <url>");
167
+ }
168
+ if (CONTROL_CHAR_REGEX.test(config.syncApiKey)) {
169
+ throw new Error(
170
+ `Stored API key is invalid (contains control characters from a previous terminal input). Re-run with one of:
171
+ memrosetta sync enable --server ${config.syncServerUrl} --key <api-key>
172
+ memrosetta sync enable --server ${config.syncServerUrl} --key-file path/to/key
173
+ $env:${ENV_API_KEY}='<api-key>'; memrosetta sync enable --server ${config.syncServerUrl}`
174
+ );
175
+ }
176
+ const db = new Database(dbPath);
177
+ try {
178
+ ensureSyncSchema(db);
179
+ const client = new SyncClient(db, {
180
+ serverUrl: config.syncServerUrl,
181
+ apiKey: config.syncApiKey,
182
+ deviceId: config.syncDeviceId,
183
+ userId: config.syncUserId ?? userInfo().username
184
+ });
185
+ return await fn(client, db);
186
+ } finally {
187
+ db.close();
188
+ }
189
+ }
190
+ async function runEnable(options) {
191
+ const { args, format } = options;
192
+ let serverUrl;
193
+ try {
194
+ serverUrl = requireOption(args, "--server", "server URL");
195
+ } catch (err) {
196
+ outputError(err instanceof Error ? err.message : String(err), format);
197
+ process.exitCode = 1;
198
+ return;
199
+ }
200
+ let apiKey;
201
+ try {
202
+ apiKey = await resolveApiKey(args);
203
+ } catch (err) {
204
+ outputError(err instanceof Error ? err.message : String(err), format);
205
+ process.exitCode = 1;
206
+ return;
207
+ }
208
+ const skipTest = hasFlag(args, "--no-test");
209
+ if (!skipTest) {
210
+ try {
211
+ await testConnection(serverUrl, apiKey);
212
+ } catch (err) {
213
+ outputError(
214
+ `${err instanceof Error ? err.message : String(err)}
215
+ Use --no-test to skip the health check.`,
216
+ format
217
+ );
218
+ process.exitCode = 1;
219
+ return;
220
+ }
221
+ }
222
+ const existing = getConfig();
223
+ const deviceId = existing.syncDeviceId ?? `device-${randomUUID().slice(0, 8)}`;
224
+ const userOverride = optionalOption(args, "--user");
225
+ const syncUserId = userOverride ?? existing.syncUserId ?? userInfo().username;
226
+ writeConfig({
227
+ ...existing,
228
+ syncEnabled: true,
229
+ syncServerUrl: serverUrl,
230
+ syncApiKey: apiKey,
231
+ syncDeviceId: deviceId,
232
+ syncUserId
233
+ });
234
+ if (format === "text") {
235
+ process.stdout.write("Sync enabled.\n");
236
+ process.stdout.write(` Server: ${serverUrl}
237
+ `);
238
+ process.stdout.write(` UserId: ${syncUserId}
239
+ `);
240
+ process.stdout.write(` DeviceId: ${deviceId}
241
+ `);
242
+ if (skipTest) {
243
+ process.stdout.write(" (health check skipped)\n");
244
+ }
245
+ return;
246
+ }
247
+ output(
248
+ { enabled: true, serverUrl, userId: syncUserId, deviceId, healthCheckSkipped: skipTest },
249
+ format
250
+ );
251
+ }
252
+ function runDisable(options) {
253
+ const { format } = options;
254
+ const existing = getConfig();
255
+ writeConfig({
256
+ ...existing,
257
+ syncEnabled: false
258
+ });
259
+ if (format === "text") {
260
+ process.stdout.write("Sync disabled. (server URL and API key preserved for re-enable)\n");
261
+ return;
262
+ }
263
+ output({ enabled: false }, format);
264
+ }
265
+ async function runStatus(options) {
266
+ const { format, db } = options;
267
+ const config = getConfig();
268
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
269
+ if (!config.syncEnabled) {
270
+ if (format === "text") {
271
+ process.stdout.write("Sync: disabled\n");
272
+ if (config.syncServerUrl) {
273
+ process.stdout.write(` Server: ${config.syncServerUrl}
274
+ `);
275
+ }
276
+ if (config.syncUserId) {
277
+ process.stdout.write(` UserId: ${config.syncUserId}
278
+ `);
279
+ }
280
+ if (config.syncDeviceId) {
281
+ process.stdout.write(` DeviceId: ${config.syncDeviceId}
282
+ `);
283
+ }
284
+ return;
285
+ }
286
+ output(
287
+ {
288
+ enabled: false,
289
+ serverUrl: config.syncServerUrl ?? null,
290
+ userId: config.syncUserId ?? null,
291
+ deviceId: config.syncDeviceId ?? null
292
+ },
293
+ format
294
+ );
295
+ return;
296
+ }
297
+ try {
298
+ const status = await withSyncClient(dbPath, config, async (client) => client.getStatus());
299
+ if (format === "text") {
300
+ process.stdout.write("Sync: enabled\n");
301
+ process.stdout.write(` Server: ${status.serverUrl}
302
+ `);
303
+ process.stdout.write(` UserId: ${status.userId}
304
+ `);
305
+ process.stdout.write(` DeviceId: ${status.deviceId}
306
+ `);
307
+ process.stdout.write(` Pending ops: ${status.pendingOps}
308
+ `);
309
+ process.stdout.write(` Current cursor: ${status.cursor}
310
+ `);
311
+ process.stdout.write(
312
+ ` Last push: ${status.lastPush.successAt ?? "never"}` + (status.lastPush.attemptAt && status.lastPush.attemptAt !== status.lastPush.successAt ? ` (last attempt: ${status.lastPush.attemptAt})` : "") + "\n"
313
+ );
314
+ process.stdout.write(
315
+ ` Last pull: ${status.lastPull.successAt ?? "never"}` + (status.lastPull.attemptAt && status.lastPull.attemptAt !== status.lastPull.successAt ? ` (last attempt: ${status.lastPull.attemptAt})` : "") + "\n"
316
+ );
317
+ return;
318
+ }
319
+ output(status, format);
320
+ } catch (err) {
321
+ outputError(err instanceof Error ? err.message : String(err), format);
322
+ process.exitCode = 1;
323
+ }
324
+ }
325
+ async function runNow(options) {
326
+ const { args, format, db } = options;
327
+ const config = getConfig();
328
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
329
+ if (!config.syncEnabled) {
330
+ outputError("Sync is disabled. Run: memrosetta sync enable --server <url>", format);
331
+ process.exitCode = 1;
332
+ return;
333
+ }
334
+ const pushOnly = hasFlag(args, "--push-only");
335
+ const pullOnly = hasFlag(args, "--pull-only");
336
+ try {
337
+ const result = await withSyncClient(dbPath, config, async (client) => {
338
+ let pushed = 0;
339
+ let pulled = 0;
340
+ if (!pullOnly) {
341
+ const pushResult = await client.push();
342
+ pushed = pushResult.pushed;
343
+ }
344
+ if (!pushOnly) {
345
+ pulled = await client.pull();
346
+ }
347
+ return { pushed, pulled };
348
+ });
349
+ if (format === "text") {
350
+ process.stdout.write(`Sync complete. pushed=${result.pushed} pulled=${result.pulled}
351
+ `);
352
+ return;
353
+ }
354
+ output(result, format);
355
+ } catch (err) {
356
+ outputError(err instanceof Error ? err.message : String(err), format);
357
+ process.exitCode = 1;
358
+ }
359
+ }
360
+ function runDeviceId(options) {
361
+ const { format } = options;
362
+ const config = getConfig();
363
+ if (!config.syncDeviceId) {
364
+ outputError("No deviceId set. Run: memrosetta sync enable --server <url>", format);
365
+ process.exitCode = 1;
366
+ return;
367
+ }
368
+ if (format === "text") {
369
+ process.stdout.write(`${config.syncDeviceId}
370
+ `);
371
+ return;
372
+ }
373
+ output({ deviceId: config.syncDeviceId }, format);
374
+ }
375
+ async function runBackfill(options) {
376
+ const { args, format, db } = options;
377
+ const config = getConfig();
378
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
379
+ if (!config.syncEnabled) {
380
+ outputError("Sync is disabled. Run: memrosetta sync enable --server <url>", format);
381
+ process.exitCode = 1;
382
+ return;
383
+ }
384
+ const dryRun = hasFlag(args, "--dry-run");
385
+ const userFilter = optionalOption(args, "--user");
386
+ const namespaceFilter = optionalOption(args, "--namespace");
387
+ const includeRelations = !hasFlag(args, "--memories-only");
388
+ const sync = await openCliSyncContext(dbPath);
389
+ if (!sync.enabled) {
390
+ outputError("Sync is not fully configured. Run: memrosetta sync enable", format);
391
+ process.exitCode = 1;
392
+ return;
393
+ }
394
+ try {
395
+ const { default: Database } = await import("better-sqlite3");
396
+ const readDb = new Database(dbPath, { readonly: true });
397
+ try {
398
+ const params = [];
399
+ let where = "1=1";
400
+ if (userFilter) {
401
+ where += " AND user_id = ?";
402
+ params.push(userFilter);
403
+ }
404
+ if (namespaceFilter) {
405
+ where += " AND namespace = ?";
406
+ params.push(namespaceFilter);
407
+ }
408
+ const memRows = readDb.prepare(
409
+ `SELECT memory_id, user_id, namespace, memory_type, content, raw_text,
410
+ document_date, source_id, confidence, salience, keywords,
411
+ event_date_start, event_date_end, invalidated_at, learned_at
412
+ FROM memories
413
+ WHERE ${where}`
414
+ ).all(...params);
415
+ let memoriesQueued = 0;
416
+ let relationsQueued = 0;
417
+ const memoryIdSet = /* @__PURE__ */ new Set();
418
+ if (!dryRun) {
419
+ for (const row of memRows) {
420
+ memoryIdSet.add(row.memory_id);
421
+ sync.enqueue(
422
+ buildMemoryCreatedOp(sync, {
423
+ memoryId: row.memory_id,
424
+ userId: row.user_id,
425
+ namespace: row.namespace ?? void 0,
426
+ memoryType: row.memory_type,
427
+ content: row.content,
428
+ rawText: row.raw_text ?? void 0,
429
+ documentDate: row.document_date ?? void 0,
430
+ sourceId: row.source_id ?? void 0,
431
+ confidence: row.confidence,
432
+ salience: row.salience,
433
+ keywords: row.keywords ? JSON.parse(row.keywords) : void 0,
434
+ eventDateStart: row.event_date_start ?? void 0,
435
+ eventDateEnd: row.event_date_end ?? void 0,
436
+ invalidatedAt: row.invalidated_at ?? void 0,
437
+ learnedAt: row.learned_at,
438
+ // Fields unused by the payload but present on Memory type:
439
+ isLatest: true,
440
+ tier: "warm",
441
+ activationScore: 1,
442
+ accessCount: 0,
443
+ useCount: 0,
444
+ successCount: 0
445
+ })
446
+ );
447
+ memoriesQueued++;
448
+ }
449
+ } else {
450
+ memoriesQueued = memRows.length;
451
+ for (const row of memRows) memoryIdSet.add(row.memory_id);
452
+ }
453
+ if (includeRelations) {
454
+ const relRows = readDb.prepare(
455
+ "SELECT src_memory_id, dst_memory_id, relation_type, created_at, reason FROM memory_relations"
456
+ ).all();
457
+ for (const row of relRows) {
458
+ if (!memoryIdSet.has(row.src_memory_id) || !memoryIdSet.has(row.dst_memory_id)) {
459
+ continue;
460
+ }
461
+ if (!dryRun) {
462
+ sync.enqueue(
463
+ buildRelationCreatedOp(sync, {
464
+ srcMemoryId: row.src_memory_id,
465
+ dstMemoryId: row.dst_memory_id,
466
+ relationType: row.relation_type,
467
+ createdAt: row.created_at,
468
+ reason: row.reason ?? void 0
469
+ })
470
+ );
471
+ }
472
+ relationsQueued++;
473
+ }
474
+ }
475
+ const result = {
476
+ memoriesQueued,
477
+ relationsQueued,
478
+ dryRun,
479
+ userFilter: userFilter ?? null,
480
+ namespaceFilter: namespaceFilter ?? null
481
+ };
482
+ if (format === "text") {
483
+ process.stdout.write(
484
+ `${dryRun ? "Dry run: would enqueue" : "Enqueued"} ${memoriesQueued} memories` + (includeRelations ? ` and ${relationsQueued} relations` : "") + ".\n"
485
+ );
486
+ if (userFilter || namespaceFilter) {
487
+ process.stdout.write(
488
+ ` Filters: user=${userFilter ?? "*"} namespace=${namespaceFilter ?? "*"}
489
+ `
490
+ );
491
+ }
492
+ if (!dryRun) {
493
+ process.stdout.write("Run `memrosetta sync now` to push to the server.\n");
494
+ }
495
+ return;
496
+ }
497
+ output(result, format);
498
+ } finally {
499
+ readDb.close();
500
+ }
501
+ } finally {
502
+ sync.close();
503
+ }
504
+ }
505
+ async function run(options) {
506
+ const sub = parseSubcommand(options.args);
507
+ if (!sub) {
508
+ outputError(
509
+ "Usage: memrosetta sync <enable|disable|status|now|device-id|backfill>\n\n enable --server <url> [--key <key> | --key-stdin | --key-file <p>]\n disable\n status\n now [--push-only | --pull-only]\n device-id\n backfill [--user <id>] [--namespace <ns>] [--memories-only] [--dry-run]\n",
510
+ options.format
511
+ );
512
+ process.exitCode = 1;
513
+ return;
514
+ }
515
+ const rest = { ...options, args: options.args.slice(1) };
516
+ switch (sub) {
517
+ case "enable":
518
+ await runEnable(rest);
519
+ return;
520
+ case "disable":
521
+ runDisable(rest);
522
+ return;
523
+ case "status":
524
+ await runStatus(rest);
525
+ return;
526
+ case "now":
527
+ await runNow(rest);
528
+ return;
529
+ case "device-id":
530
+ runDeviceId(rest);
531
+ return;
532
+ case "backfill":
533
+ await runBackfill(rest);
534
+ return;
535
+ }
536
+ }
537
+ export {
538
+ run
539
+ };