@edihasaj/recall 2.0.16 → 2.0.17
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 +22 -4
- package/dist/{chunk-Q2F7EQCA.js → chunk-22AJZ7UQ.js} +2 -2
- package/dist/{chunk-GCMP2YYN.js → chunk-2COJXGP4.js} +2 -2
- package/dist/{chunk-SYSSACWJ.js → chunk-CSBXI3ET.js} +39 -20
- package/dist/chunk-CSBXI3ET.js.map +1 -0
- package/dist/{chunk-QPR77YXP.js → chunk-EY6HIDG2.js} +13 -11
- package/dist/chunk-EY6HIDG2.js.map +1 -0
- package/dist/{chunk-GDN44ZC7.js → chunk-FNIIUNW6.js} +2 -2
- package/dist/{chunk-YELXEWKH.js → chunk-GK7OWVRQ.js} +3 -3
- package/dist/{chunk-7UWVXXTU.js → chunk-KLERXJ47.js} +3 -3
- package/dist/{chunk-THC7QOAK.js → chunk-KVZN35JF.js} +7 -7
- package/dist/{chunk-SEXZABB2.js → chunk-Q22B7YDQ.js} +5 -5
- package/dist/{chunk-VRAG5V66.js → chunk-Q7254IPO.js} +908 -43
- package/dist/chunk-Q7254IPO.js.map +1 -0
- package/dist/{chunk-EKFOHVHS.js → chunk-QQ6YHR7I.js} +11 -11
- package/dist/{chunk-MLC3KO2O.js → chunk-RAQT2OBR.js} +7 -7
- package/dist/{chunk-DVLQYARZ.js → chunk-UDLRBKC3.js} +3 -3
- package/dist/{chunk-DOYTMHDI.js → chunk-VUVFQJWZ.js} +2 -2
- package/dist/{chunk-LEOXFQJJ.js → chunk-XRKUJ5B4.js} +2 -2
- package/dist/{chunk-ZF23OPYV.js → chunk-YIUBD27J.js} +14 -14
- package/dist/chunk-YIUBD27J.js.map +1 -0
- package/dist/{chunk-DAW6FUGL.js → chunk-YIVOTIDF.js} +5 -5
- package/dist/{chunk-FYMMTODQ.js → chunk-ZT67CYDS.js} +2 -2
- package/dist/{chunk-FYMMTODQ.js.map → chunk-ZT67CYDS.js.map} +1 -1
- package/dist/{cleanup-WJFE6IVP.js → cleanup-4TXIHTJT.js} +11 -11
- package/dist/cli.js +55 -36
- package/dist/cli.js.map +1 -1
- package/dist/{codex-trust-3BFTJFRD.js → codex-trust-2JIY66CP.js} +4 -4
- package/dist/daemon.js +1090 -169
- package/dist/daemon.js.map +1 -1
- package/dist/dispatcher-O6NGADCQ.js +22 -0
- package/dist/{embeddings-H352GFKD.js → embeddings-AAS7NKGB.js} +5 -5
- package/dist/ingest-DW3AG4M5.js +20 -0
- package/dist/{keychain-A2Z7D7YE.js → keychain-SHRO7W6J.js} +3 -3
- package/dist/mcp.js +15 -15
- package/dist/{memory-value-M3TA7SEK.js → memory-value-R2C7ZSDF.js} +11 -11
- package/dist/{provenance-CXU6LZK7.js → provenance-I5GIAP7N.js} +9 -9
- package/dist/quality-32MAXPNJ.js +25 -0
- package/dist/retrieval-RKYWWNWC.js +15 -0
- package/dist/{store-YCVWABSH.js → store-X2B6MRBH.js} +4 -4
- package/dist/sync-server.js +2 -2
- package/dist/{tasks-4UL2FIAQ.js → tasks-H4NIS6QO.js} +11 -11
- package/dist/{usage-HZ27RG53.js → usage-35HSDMNT.js} +4 -4
- package/package.json +2 -1
- package/vendor/recall-cloud-sync/PROVENANCE.md +27 -0
- package/vendor/recall-cloud-sync/managed-worker.mjs +48 -0
- package/vendor/recall-cloud-sync/private-token.mjs +95 -0
- package/vendor/recall-cloud-sync/recall-sync-local.mjs +406 -0
- package/vendor/recall-cloud-sync/recall-sync.mjs +1266 -0
- package/dist/chunk-QPR77YXP.js.map +0 -1
- package/dist/chunk-SYSSACWJ.js.map +0 -1
- package/dist/chunk-VRAG5V66.js.map +0 -1
- package/dist/chunk-ZF23OPYV.js.map +0 -1
- package/dist/dispatcher-5JVGZNWT.js +0 -22
- package/dist/ingest-NVYEOSVZ.js +0 -20
- package/dist/quality-4CG6U273.js +0 -25
- package/dist/retrieval-42CPYUDW.js +0 -15
- /package/dist/{chunk-Q2F7EQCA.js.map → chunk-22AJZ7UQ.js.map} +0 -0
- /package/dist/{chunk-GCMP2YYN.js.map → chunk-2COJXGP4.js.map} +0 -0
- /package/dist/{chunk-GDN44ZC7.js.map → chunk-FNIIUNW6.js.map} +0 -0
- /package/dist/{chunk-YELXEWKH.js.map → chunk-GK7OWVRQ.js.map} +0 -0
- /package/dist/{chunk-7UWVXXTU.js.map → chunk-KLERXJ47.js.map} +0 -0
- /package/dist/{chunk-THC7QOAK.js.map → chunk-KVZN35JF.js.map} +0 -0
- /package/dist/{chunk-SEXZABB2.js.map → chunk-Q22B7YDQ.js.map} +0 -0
- /package/dist/{chunk-EKFOHVHS.js.map → chunk-QQ6YHR7I.js.map} +0 -0
- /package/dist/{chunk-MLC3KO2O.js.map → chunk-RAQT2OBR.js.map} +0 -0
- /package/dist/{chunk-DVLQYARZ.js.map → chunk-UDLRBKC3.js.map} +0 -0
- /package/dist/{chunk-DOYTMHDI.js.map → chunk-VUVFQJWZ.js.map} +0 -0
- /package/dist/{chunk-LEOXFQJJ.js.map → chunk-XRKUJ5B4.js.map} +0 -0
- /package/dist/{chunk-DAW6FUGL.js.map → chunk-YIVOTIDF.js.map} +0 -0
- /package/dist/{cleanup-WJFE6IVP.js.map → cleanup-4TXIHTJT.js.map} +0 -0
- /package/dist/{codex-trust-3BFTJFRD.js.map → codex-trust-2JIY66CP.js.map} +0 -0
- /package/dist/{dispatcher-5JVGZNWT.js.map → dispatcher-O6NGADCQ.js.map} +0 -0
- /package/dist/{embeddings-H352GFKD.js.map → embeddings-AAS7NKGB.js.map} +0 -0
- /package/dist/{ingest-NVYEOSVZ.js.map → ingest-DW3AG4M5.js.map} +0 -0
- /package/dist/{keychain-A2Z7D7YE.js.map → keychain-SHRO7W6J.js.map} +0 -0
- /package/dist/{memory-value-M3TA7SEK.js.map → memory-value-R2C7ZSDF.js.map} +0 -0
- /package/dist/{provenance-CXU6LZK7.js.map → provenance-I5GIAP7N.js.map} +0 -0
- /package/dist/{quality-4CG6U273.js.map → quality-32MAXPNJ.js.map} +0 -0
- /package/dist/{retrieval-42CPYUDW.js.map → retrieval-RKYWWNWC.js.map} +0 -0
- /package/dist/{store-YCVWABSH.js.map → store-X2B6MRBH.js.map} +0 -0
- /package/dist/{tasks-4UL2FIAQ.js.map → tasks-H4NIS6QO.js.map} +0 -0
- /package/dist/{usage-HZ27RG53.js.map → usage-35HSDMNT.js.map} +0 -0
|
@@ -0,0 +1,1266 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import Database from "better-sqlite3";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from "node:crypto";
|
|
5
|
+
import {
|
|
6
|
+
existsSync,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
readFileSync,
|
|
9
|
+
realpathSync,
|
|
10
|
+
rmSync
|
|
11
|
+
} from "node:fs";
|
|
12
|
+
import { homedir, hostname } from "node:os";
|
|
13
|
+
import { dirname, join, resolve } from "node:path";
|
|
14
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
15
|
+
import {
|
|
16
|
+
applyPulledRecords,
|
|
17
|
+
canonicalExternalId,
|
|
18
|
+
cloudExternalIdForRow
|
|
19
|
+
} from "./recall-sync-local.mjs";
|
|
20
|
+
import {
|
|
21
|
+
normalizeToken,
|
|
22
|
+
readPrivateTokenFile,
|
|
23
|
+
validateApiUrl,
|
|
24
|
+
validatePrivateFile,
|
|
25
|
+
writePrivateFileAtomic,
|
|
26
|
+
writePrivateTokenFile
|
|
27
|
+
} from "./private-token.mjs";
|
|
28
|
+
|
|
29
|
+
const DEFAULT_DB = join(homedir(), ".recall", "recall.db");
|
|
30
|
+
const SELF = fileURLToPath(import.meta.url);
|
|
31
|
+
const LAUNCHD_LABEL = "dev.recallmemory.cloud-sync";
|
|
32
|
+
const SYSTEMD_UNIT = "recall-cloud-sync.service";
|
|
33
|
+
const WINDOWS_TASK = "Recall Cloud Sync";
|
|
34
|
+
const TOKEN_FILE = join(homedir(), ".config", "recall-cloud", "token");
|
|
35
|
+
const SYNC_STATE_FILE = join(homedir(), ".config", "recall-cloud", "sync-state.json");
|
|
36
|
+
// transient is deliberately excluded: it is by definition not durable, and the
|
|
37
|
+
// pull side has no inverse for the push-time transient→candidate coercion, so
|
|
38
|
+
// syncing it silently promoted local transient rows to candidate on the next
|
|
39
|
+
// pull. rejected IS synced — cross-device rejection propagation depends on it;
|
|
40
|
+
// the billing count excludes rejected server-side instead.
|
|
41
|
+
const DEFAULT_PUSH_STATUSES = "active,candidate,rejected";
|
|
42
|
+
const DEFAULT_WATCH_STATUSES = "active,candidate,rejected";
|
|
43
|
+
const DEFAULT_FULL_RECONCILE_SECONDS = 86_400;
|
|
44
|
+
|
|
45
|
+
// --- E2EE (zero-knowledge) client-side encryption -------------------------
|
|
46
|
+
// A deterministic content key is derived from the user's passphrase so every
|
|
47
|
+
// device that knows the passphrase derives the SAME key — no server key
|
|
48
|
+
// exchange needed. The server only ever sees ciphertext + nonce; it never sees
|
|
49
|
+
// the passphrase, the derived key, or plaintext. AES-256-GCM (via Node crypto);
|
|
50
|
+
// the server treats the blobs as opaque, so the exact AEAD is a client choice.
|
|
51
|
+
const E2EE_KDF_SALT = "recall-cloud-e2ee-v1";
|
|
52
|
+
const E2EE_KEY_ID = "pp-v1";
|
|
53
|
+
const GCM_TAG_BYTES = 16;
|
|
54
|
+
|
|
55
|
+
function e2eeKey(passphrase) {
|
|
56
|
+
return scryptSync(Buffer.from(String(passphrase), "utf8"), E2EE_KDF_SALT, 32);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function e2eeEncrypt(key, plaintext) {
|
|
60
|
+
const iv = randomBytes(12);
|
|
61
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
62
|
+
const body = Buffer.concat([cipher.update(Buffer.from(plaintext, "utf8")), cipher.final()]);
|
|
63
|
+
// store ciphertext||authTag as one opaque blob; nonce travels alongside.
|
|
64
|
+
const blob = Buffer.concat([body, cipher.getAuthTag()]);
|
|
65
|
+
return { ciphertext: blob.toString("base64"), nonce: iv.toString("base64") };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function e2eeDecrypt(key, ciphertextB64, nonceB64) {
|
|
69
|
+
const blob = Buffer.from(String(ciphertextB64), "base64");
|
|
70
|
+
const iv = Buffer.from(String(nonceB64), "base64");
|
|
71
|
+
const body = blob.subarray(0, blob.length - GCM_TAG_BYTES);
|
|
72
|
+
const tag = blob.subarray(blob.length - GCM_TAG_BYTES);
|
|
73
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
74
|
+
decipher.setAuthTag(tag);
|
|
75
|
+
return Buffer.concat([decipher.update(body), decipher.final()]).toString("utf8");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Resolve E2EE config from flags/env. Returns null when off; throws if enabled
|
|
79
|
+
// without a passphrase (fail closed rather than silently sync plaintext).
|
|
80
|
+
function resolveE2ee(options) {
|
|
81
|
+
if (!options.e2ee) return null;
|
|
82
|
+
const passphrase = options.e2eePassphrase ?? process.env.RECALL_CLOUD_E2EE_PASSPHRASE;
|
|
83
|
+
if (!passphrase) {
|
|
84
|
+
throw new Error("--e2ee requires a passphrase (--e2ee-passphrase or RECALL_CLOUD_E2EE_PASSPHRASE)");
|
|
85
|
+
}
|
|
86
|
+
return { key: e2eeKey(passphrase) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Run main() only when executed directly, so the module can be imported by
|
|
90
|
+
// tests. Compare realpath-resolved paths so a symlinked location (e.g. macOS
|
|
91
|
+
// /var -> /private/var) still counts as "invoked directly".
|
|
92
|
+
let INVOKED_DIRECTLY = false;
|
|
93
|
+
try {
|
|
94
|
+
INVOKED_DIRECTLY = Boolean(process.argv[1]) && realpathSync(SELF) === realpathSync(process.argv[1]);
|
|
95
|
+
} catch {
|
|
96
|
+
INVOKED_DIRECTLY = process.argv[1] ? import.meta.url === pathToFileURL(process.argv[1]).href : false;
|
|
97
|
+
}
|
|
98
|
+
if (INVOKED_DIRECTLY) {
|
|
99
|
+
main().catch((error) => {
|
|
100
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
101
|
+
process.exit(1);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export {
|
|
106
|
+
DEFAULT_PUSH_STATUSES,
|
|
107
|
+
DEFAULT_WATCH_STATUSES,
|
|
108
|
+
applyPulledRecords,
|
|
109
|
+
canonicalExternalId,
|
|
110
|
+
cloudExternalIdForRow,
|
|
111
|
+
e2eeKey,
|
|
112
|
+
e2eeEncrypt,
|
|
113
|
+
e2eeDecrypt,
|
|
114
|
+
resolveE2ee,
|
|
115
|
+
buildPlist,
|
|
116
|
+
buildSystemdUnit,
|
|
117
|
+
buildWindowsLauncher,
|
|
118
|
+
launchAgentArgs,
|
|
119
|
+
parseDeviceAliases,
|
|
120
|
+
deviceAliasesFromArgs,
|
|
121
|
+
resolveDeviceAliases,
|
|
122
|
+
deviceIdFromArgs,
|
|
123
|
+
legacyTokenFromArgs,
|
|
124
|
+
loadSyncState,
|
|
125
|
+
readPrivateTokenFile,
|
|
126
|
+
readRecallMemories,
|
|
127
|
+
toCloudRecord
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
async function main() {
|
|
131
|
+
const [command, ...args] = process.argv.slice(2);
|
|
132
|
+
const options = parseOptions(args);
|
|
133
|
+
|
|
134
|
+
switch (command) {
|
|
135
|
+
case "push":
|
|
136
|
+
await push(options);
|
|
137
|
+
break;
|
|
138
|
+
case "pull":
|
|
139
|
+
await pull(options);
|
|
140
|
+
break;
|
|
141
|
+
case "verify":
|
|
142
|
+
await verify(options);
|
|
143
|
+
break;
|
|
144
|
+
case "memories":
|
|
145
|
+
case "list-all":
|
|
146
|
+
await memories(options);
|
|
147
|
+
break;
|
|
148
|
+
case "watch":
|
|
149
|
+
await watch(options);
|
|
150
|
+
break;
|
|
151
|
+
case "install":
|
|
152
|
+
await installAgent(options);
|
|
153
|
+
break;
|
|
154
|
+
case "uninstall":
|
|
155
|
+
await uninstallAgent(options);
|
|
156
|
+
break;
|
|
157
|
+
default:
|
|
158
|
+
usage();
|
|
159
|
+
process.exit(command ? 1 : 0);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function push(options) {
|
|
164
|
+
const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
|
|
165
|
+
const token = resolveToken(options);
|
|
166
|
+
const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
|
|
167
|
+
const statusSet = new Set((options.status ?? DEFAULT_PUSH_STATUSES).split(",").map((value) => value.trim()).filter(Boolean));
|
|
168
|
+
const deviceId = options.deviceId ?? hostnameLabel();
|
|
169
|
+
const deviceAliases = resolveDeviceAliases(options);
|
|
170
|
+
const limit = parseInteger(options.limit, 5000);
|
|
171
|
+
const dryRun = Boolean(options.dryRun);
|
|
172
|
+
const e2ee = resolveE2ee(options);
|
|
173
|
+
|
|
174
|
+
const rows = readRecallMemories(dbPath, statusSet, limit, {
|
|
175
|
+
after: options.after,
|
|
176
|
+
afterId: options.afterId
|
|
177
|
+
});
|
|
178
|
+
const records = rows.map((row) => toCloudRecord(row, deviceId, e2ee, deviceAliases));
|
|
179
|
+
|
|
180
|
+
if (dryRun) {
|
|
181
|
+
console.log(JSON.stringify(dryRunPushPayload(records, {
|
|
182
|
+
dbPath,
|
|
183
|
+
api,
|
|
184
|
+
deviceId,
|
|
185
|
+
e2ee: Boolean(e2ee),
|
|
186
|
+
statuses: [...statusSet],
|
|
187
|
+
includeSample: Boolean(options.sample)
|
|
188
|
+
}), null, 2));
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
let accepted = 0;
|
|
193
|
+
// Rows the server actually wrote. `accepted` only counts records that
|
|
194
|
+
// survived the ACL filter; the updated_at guard can still drop stale ones,
|
|
195
|
+
// so "pushed=500" could mean zero writes.
|
|
196
|
+
let applied = 0;
|
|
197
|
+
let aliasesReconciled = 0;
|
|
198
|
+
const batches = chunks(records, 500);
|
|
199
|
+
if (batches.length === 0 && Object.keys(deviceAliases).length > 0) batches.push([]);
|
|
200
|
+
for (const [index, batch] of batches.entries()) {
|
|
201
|
+
const result = await fetchJson(`${api}/v1/sync/push`, {
|
|
202
|
+
method: "POST",
|
|
203
|
+
token,
|
|
204
|
+
body: syncPushRequest(batch, index === 0 ? deviceAliases : {})
|
|
205
|
+
});
|
|
206
|
+
accepted += Number(result.accepted ?? 0);
|
|
207
|
+
// Older servers don't report `applied`; fall back to accepted so the
|
|
208
|
+
// number never reads as a spurious zero.
|
|
209
|
+
applied += Number(result.applied ?? result.accepted ?? 0);
|
|
210
|
+
aliasesReconciled += Number(result.aliasesReconciled ?? 0);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (options.quiet) {
|
|
214
|
+
console.log(`[${new Date().toISOString()}] push ok applied=${applied} accepted=${accepted} selected=${records.length} aliases=${aliasesReconciled} device=${deviceId}`);
|
|
215
|
+
} else {
|
|
216
|
+
console.log(JSON.stringify({
|
|
217
|
+
pushed: accepted,
|
|
218
|
+
applied,
|
|
219
|
+
selected: records.length,
|
|
220
|
+
dbPath,
|
|
221
|
+
api,
|
|
222
|
+
deviceId,
|
|
223
|
+
aliasesReconciled,
|
|
224
|
+
statuses: [...statusSet]
|
|
225
|
+
}, null, 2));
|
|
226
|
+
}
|
|
227
|
+
const last = rows.at(-1);
|
|
228
|
+
return {
|
|
229
|
+
pushed: accepted,
|
|
230
|
+
applied,
|
|
231
|
+
selected: records.length,
|
|
232
|
+
aliasesReconciled,
|
|
233
|
+
cursor: last ? { updatedAt: last.updated_at, id: last.id } : null
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function syncPushRequest(records, deviceAliases = {}) {
|
|
238
|
+
const body = { records };
|
|
239
|
+
if (Object.keys(deviceAliases).length > 0) body.deviceAliases = deviceAliases;
|
|
240
|
+
return body;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function dryRunPushPayload(records, { dbPath, api, deviceId, e2ee, statuses, includeSample = false }) {
|
|
244
|
+
const payload = {
|
|
245
|
+
dryRun: true,
|
|
246
|
+
dbPath,
|
|
247
|
+
api,
|
|
248
|
+
deviceId,
|
|
249
|
+
e2ee,
|
|
250
|
+
selected: records.length,
|
|
251
|
+
statuses
|
|
252
|
+
};
|
|
253
|
+
if (includeSample) payload.sample = records.slice(0, 3);
|
|
254
|
+
return payload;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async function pull(options) {
|
|
258
|
+
const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
|
|
259
|
+
const token = resolveToken(options);
|
|
260
|
+
const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
|
|
261
|
+
const deviceId = options.deviceId ?? hostnameLabel();
|
|
262
|
+
const deviceAliases = resolveDeviceAliases(options);
|
|
263
|
+
const max = parseInteger(options.limit, 100000);
|
|
264
|
+
const records = await fetchAllSyncRecords({
|
|
265
|
+
api,
|
|
266
|
+
token,
|
|
267
|
+
since: options.since,
|
|
268
|
+
sinceId: options.sinceId,
|
|
269
|
+
max
|
|
270
|
+
});
|
|
271
|
+
const applied = options.dryRun
|
|
272
|
+
? {
|
|
273
|
+
imported: 0,
|
|
274
|
+
updated: 0,
|
|
275
|
+
unchanged: 0,
|
|
276
|
+
skippedEncrypted: records.filter((record) => record.encryptionMode === "e2ee").length,
|
|
277
|
+
skippedDuplicate: 0,
|
|
278
|
+
skippedExpiredTombstone: 0
|
|
279
|
+
}
|
|
280
|
+
: applyPulledRecords(dbPath, records, {
|
|
281
|
+
deviceId,
|
|
282
|
+
deviceAliases,
|
|
283
|
+
e2ee: resolveE2ee(options),
|
|
284
|
+
decrypt: e2eeDecrypt,
|
|
285
|
+
rejectedRetentionDays: parseNonNegativeInteger(
|
|
286
|
+
options.rejectedRetentionDays ?? process.env.RECALL_REJECTED_RETENTION_DAYS,
|
|
287
|
+
90
|
|
288
|
+
)
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
if (options.quiet) {
|
|
292
|
+
console.log(
|
|
293
|
+
`[${new Date().toISOString()}] pull ok fetched=${records.length} imported=${applied.imported} updated=${applied.updated} unchanged=${applied.unchanged} skipped=${applied.skippedEncrypted + applied.skippedDuplicate + applied.skippedExpiredTombstone}`
|
|
294
|
+
);
|
|
295
|
+
} else {
|
|
296
|
+
console.log(JSON.stringify({
|
|
297
|
+
fetched: records.length,
|
|
298
|
+
dbPath,
|
|
299
|
+
dryRun: Boolean(options.dryRun),
|
|
300
|
+
...applied
|
|
301
|
+
}, null, 2));
|
|
302
|
+
}
|
|
303
|
+
const last = records.at(-1);
|
|
304
|
+
return {
|
|
305
|
+
fetched: records.length,
|
|
306
|
+
...applied,
|
|
307
|
+
cursor: last?.updatedAt && last?.externalId
|
|
308
|
+
? { updatedAt: last.updatedAt, id: last.externalId }
|
|
309
|
+
: null
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function verify(options) {
|
|
314
|
+
const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
|
|
315
|
+
const token = resolveToken(options);
|
|
316
|
+
const query = options.query ?? "recall";
|
|
317
|
+
const limit = parseInteger(options.limit, 10);
|
|
318
|
+
|
|
319
|
+
const result = await fetchJson(`${api}/v1/compile`, {
|
|
320
|
+
method: "POST",
|
|
321
|
+
token,
|
|
322
|
+
body: { query, limit }
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const memories = Array.isArray(result.memories) ? result.memories : [];
|
|
326
|
+
console.log(JSON.stringify({
|
|
327
|
+
query,
|
|
328
|
+
matched: memories.length,
|
|
329
|
+
mode: result.mode,
|
|
330
|
+
sample: memories.slice(0, 5)
|
|
331
|
+
}, null, 2));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function memories(options) {
|
|
335
|
+
const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
|
|
336
|
+
const token = resolveToken(options);
|
|
337
|
+
const queryFilter = (options.query ?? "").toLowerCase();
|
|
338
|
+
const deviceFilter = options.device ?? null;
|
|
339
|
+
const max = parseInteger(options.limit, 100000);
|
|
340
|
+
|
|
341
|
+
const all = await fetchAllSyncRecords({
|
|
342
|
+
api,
|
|
343
|
+
token,
|
|
344
|
+
since: options.since,
|
|
345
|
+
max
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
// With a passphrase, decrypt e2ee rows client-side so they are readable/
|
|
349
|
+
// searchable locally (the server never could). Rows that don't decrypt with
|
|
350
|
+
// this passphrase are left as-is (shown as [encrypted]).
|
|
351
|
+
const e2ee = resolveE2ee(options);
|
|
352
|
+
let rows = all;
|
|
353
|
+
if (e2ee) {
|
|
354
|
+
rows = rows.map((r) => {
|
|
355
|
+
if (r.encryptionMode !== "e2ee" || !r.contentCiphertext) return r;
|
|
356
|
+
try {
|
|
357
|
+
const payload = JSON.parse(e2eeDecrypt(e2ee.key, r.contentCiphertext, r.contentNonce));
|
|
358
|
+
return { ...r, contentPlaintext: payload.text, metadata: { ...(r.metadata ?? {}), recall: payload.recall } };
|
|
359
|
+
} catch {
|
|
360
|
+
return { ...r, contentPlaintext: "[encrypted: wrong passphrase]" };
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
if (deviceFilter) rows = rows.filter((r) => String(r.externalId ?? "").split(":")[0] === deviceFilter);
|
|
365
|
+
if (queryFilter) rows = rows.filter((r) => String(r.contentPlaintext ?? "").toLowerCase().includes(queryFilter));
|
|
366
|
+
|
|
367
|
+
const show = parseNonNegativeInteger(options.show, 40);
|
|
368
|
+
if (options.json) {
|
|
369
|
+
console.log(JSON.stringify(memoryRowsForOutput(rows, options.show == null ? null : show), null, 2));
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const byDevice = {};
|
|
374
|
+
for (const r of rows) {
|
|
375
|
+
const device = String(r.externalId ?? "?").split(":")[0];
|
|
376
|
+
byDevice[device] = (byDevice[device] ?? 0) + 1;
|
|
377
|
+
}
|
|
378
|
+
console.log(`Memories: ${rows.length}${queryFilter ? ` matching "${queryFilter}"` : ""}${deviceFilter ? ` on ${deviceFilter}` : ""} across ${Object.keys(byDevice).length} device(s)`);
|
|
379
|
+
console.log(Object.entries(byDevice).sort((a, b) => b[1] - a[1]).map(([d, n]) => ` ${d}: ${n}`).join("\n"));
|
|
380
|
+
console.log("");
|
|
381
|
+
if (show === 0) return;
|
|
382
|
+
for (const r of rows.slice(0, show)) {
|
|
383
|
+
const device = String(r.externalId ?? "?").split(":")[0];
|
|
384
|
+
const conf = Number(r.confidence ?? 0).toFixed(2);
|
|
385
|
+
const text = String(r.contentPlaintext ?? "").replace(/\s+/g, " ").slice(0, 96);
|
|
386
|
+
console.log(` [${device}] (${r.kind}/${conf}) ${text}`);
|
|
387
|
+
}
|
|
388
|
+
if (rows.length > show) console.log(` … and ${rows.length - show} more (use --show N or --json)`);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export function memoryRowsForOutput(rows, show) {
|
|
392
|
+
if (show == null) return rows;
|
|
393
|
+
return rows.slice(0, show);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function watch(options) {
|
|
397
|
+
const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
|
|
398
|
+
const token = resolveToken(options);
|
|
399
|
+
const intervalSeconds = parseInteger(options.interval, 300);
|
|
400
|
+
const fullReconcileSeconds = parseInteger(
|
|
401
|
+
options.fullReconcileInterval,
|
|
402
|
+
DEFAULT_FULL_RECONCILE_SECONDS
|
|
403
|
+
);
|
|
404
|
+
const loopOptions = { ...options, token, tokenFile: undefined, tokenStdin: undefined, quiet: true };
|
|
405
|
+
// Rejected rows are tombstones: uploading their status transition removes
|
|
406
|
+
// formerly-active memories from hosted search instead of leaving stale cloud
|
|
407
|
+
// copies behind forever.
|
|
408
|
+
if (!loopOptions.status) loopOptions.status = DEFAULT_WATCH_STATUSES;
|
|
409
|
+
const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
|
|
410
|
+
const deviceId = options.deviceId ?? hostnameLabel();
|
|
411
|
+
const deviceAliases = resolveDeviceAliases(options);
|
|
412
|
+
loopOptions.deviceAlias = Object.entries(deviceAliases).map(([from, to]) => `${from}=${to}`);
|
|
413
|
+
const statePath = resolve(expandHome(options.stateFile ?? SYNC_STATE_FILE));
|
|
414
|
+
const stateKey = createHash("sha256")
|
|
415
|
+
.update(`${api}\0${deviceId}\0${dbPath}`)
|
|
416
|
+
.digest("hex");
|
|
417
|
+
const state = loadSyncState(statePath);
|
|
418
|
+
const cursor = state.entries[stateKey] ?? {
|
|
419
|
+
api,
|
|
420
|
+
deviceId,
|
|
421
|
+
dbPath,
|
|
422
|
+
push: null,
|
|
423
|
+
pull: null,
|
|
424
|
+
fullReconciledAt: null
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
console.log(
|
|
428
|
+
`[recall-cloud] watch started api=${api} db=${dbPath} interval=${intervalSeconds}s device=${deviceId}`
|
|
429
|
+
);
|
|
430
|
+
|
|
431
|
+
let running = true;
|
|
432
|
+
const stop = (signal) => {
|
|
433
|
+
console.log(`[recall-cloud] received ${signal}, stopping watch`);
|
|
434
|
+
running = false;
|
|
435
|
+
};
|
|
436
|
+
process.on("SIGINT", () => stop("SIGINT"));
|
|
437
|
+
process.on("SIGTERM", () => stop("SIGTERM"));
|
|
438
|
+
|
|
439
|
+
while (running) {
|
|
440
|
+
try {
|
|
441
|
+
const lastFullMs = Date.parse(String(cursor.fullReconciledAt ?? ""));
|
|
442
|
+
const fullReconcile = !Number.isFinite(lastFullMs)
|
|
443
|
+
|| Date.now() - lastFullMs >= fullReconcileSeconds * 1000;
|
|
444
|
+
const pushResult = await retryTransientSync(() => push({
|
|
445
|
+
...loopOptions,
|
|
446
|
+
after: fullReconcile ? undefined : cursor.push?.updatedAt,
|
|
447
|
+
afterId: fullReconcile ? undefined : cursor.push?.id
|
|
448
|
+
}));
|
|
449
|
+
if (pushResult?.cursor) cursor.push = pushResult.cursor;
|
|
450
|
+
state.entries[stateKey] = cursor;
|
|
451
|
+
saveSyncState(statePath, state);
|
|
452
|
+
|
|
453
|
+
const pullResult = await retryTransientSync(
|
|
454
|
+
() => retrySqliteBusy(() => pull({
|
|
455
|
+
...loopOptions,
|
|
456
|
+
since: fullReconcile ? undefined : cursor.pull?.updatedAt,
|
|
457
|
+
sinceId: fullReconcile ? undefined : cursor.pull?.id
|
|
458
|
+
}))
|
|
459
|
+
);
|
|
460
|
+
if (pullResult?.cursor) cursor.pull = pullResult.cursor;
|
|
461
|
+
if (fullReconcile) cursor.fullReconciledAt = new Date().toISOString();
|
|
462
|
+
state.entries[stateKey] = cursor;
|
|
463
|
+
saveSyncState(statePath, state);
|
|
464
|
+
} catch (error) {
|
|
465
|
+
console.error(`[${new Date().toISOString()}] sync error: ${error instanceof Error ? error.message : error}`);
|
|
466
|
+
}
|
|
467
|
+
if (!running) break;
|
|
468
|
+
await sleep(intervalSeconds * 1000, () => running);
|
|
469
|
+
}
|
|
470
|
+
console.log("[recall-cloud] watch stopped");
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
export async function retrySqliteBusy(operation, { attempts = 3, delayMs = 1000 } = {}) {
|
|
474
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
475
|
+
try {
|
|
476
|
+
return await operation();
|
|
477
|
+
} catch (error) {
|
|
478
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
479
|
+
const retryable = /(?:database is locked|SQLITE_BUSY)/i.test(message);
|
|
480
|
+
if (!retryable || attempt === attempts) throw error;
|
|
481
|
+
console.warn(
|
|
482
|
+
`[${new Date().toISOString()}] local database busy; retrying pull (${attempt}/${attempts})`
|
|
483
|
+
);
|
|
484
|
+
await new Promise((resolvePromise) => setTimeout(resolvePromise, delayMs));
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
throw new Error("unreachable SQLite retry state");
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
export async function retryTransientSync(operation, { attempts = 3, delayMs = 1000 } = {}) {
|
|
491
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
492
|
+
try {
|
|
493
|
+
return await operation();
|
|
494
|
+
} catch (error) {
|
|
495
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
496
|
+
const retryable =
|
|
497
|
+
/failed (?:408|425|429|5\d\d)\b/i.test(message) ||
|
|
498
|
+
/(?:fetch failed|network error|invalid JSON response)/i.test(message);
|
|
499
|
+
if (!retryable || attempt === attempts) throw error;
|
|
500
|
+
console.warn(
|
|
501
|
+
`[${new Date().toISOString()}] cloud temporarily unavailable; retrying sync (${attempt}/${attempts})`
|
|
502
|
+
);
|
|
503
|
+
await new Promise((resolvePromise) => setTimeout(resolvePromise, delayMs));
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
throw new Error("unreachable transient sync retry state");
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// process.execPath is the versioned Homebrew Cellar path (…/Cellar/node@24/24.x/bin/node),
|
|
510
|
+
// which disappears when Homebrew upgrades that formula — breaking the launchd
|
|
511
|
+
// agent (exit 78). Map it to the same formula's stable opt symlink instead:
|
|
512
|
+
// it survives patch upgrades and keeps the Node major that built
|
|
513
|
+
// better-sqlite3, so the native module ABI still matches. (The unversioned
|
|
514
|
+
// /opt/homebrew/bin/node is avoided: it can jump majors under the agent.)
|
|
515
|
+
export function stableNodeBin(execPath = process.execPath, exists = existsSync) {
|
|
516
|
+
const match = execPath.match(/^(.*)\/Cellar\/([^/]+)\/[^/]+\/bin\/node$/);
|
|
517
|
+
if (match) {
|
|
518
|
+
const optNode = `${match[1]}/opt/${match[2]}/bin/node`;
|
|
519
|
+
if (exists(optNode)) return optNode;
|
|
520
|
+
}
|
|
521
|
+
return execPath;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
async function installAgent(options) {
|
|
525
|
+
const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
|
|
526
|
+
const plistPath = process.platform === "darwin" ? launchAgentPath() : undefined;
|
|
527
|
+
const token = resolveToken(options, { legacyPlistPath: plistPath });
|
|
528
|
+
const intervalSeconds = String(parseInteger(options.interval, 300));
|
|
529
|
+
const deviceId = options.deviceId ?? hostnameLabel();
|
|
530
|
+
const deviceAliases = resolveDeviceAliases(options, { plistPath });
|
|
531
|
+
const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
|
|
532
|
+
const nodeBin = process.platform === "darwin" ? stableNodeBin() : process.execPath;
|
|
533
|
+
|
|
534
|
+
if (plistPath && existsSync(plistPath) && !options.forceDeviceId) {
|
|
535
|
+
const installedDeviceId = installedDeviceIdFromPlist(plistPath);
|
|
536
|
+
if (installedDeviceId && installedDeviceId !== deviceId) {
|
|
537
|
+
throw new Error(
|
|
538
|
+
`installed sync agent uses device id ${installedDeviceId}; refusing to change to ${deviceId} without --force-device-id`
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
writePrivateTokenFile(TOKEN_FILE, token);
|
|
544
|
+
if (process.platform === "linux") {
|
|
545
|
+
installSystemdAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases });
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (process.platform === "win32") {
|
|
549
|
+
installWindowsAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases });
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
if (process.platform !== "darwin") {
|
|
553
|
+
throw new Error(`install is not supported on ${process.platform}`);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const logDir = join(homedir(), "Library", "Logs");
|
|
557
|
+
mkdirSync(logDir, { recursive: true });
|
|
558
|
+
const logFile = join(logDir, "recall-cloud-sync.log");
|
|
559
|
+
mkdirSync(dirname(plistPath), { recursive: true });
|
|
560
|
+
|
|
561
|
+
const args = launchAgentArgs({
|
|
562
|
+
self: SELF,
|
|
563
|
+
api,
|
|
564
|
+
tokenFile: TOKEN_FILE,
|
|
565
|
+
intervalSeconds,
|
|
566
|
+
deviceId,
|
|
567
|
+
dbPath,
|
|
568
|
+
deviceAliases
|
|
569
|
+
});
|
|
570
|
+
const plist = buildPlist({ nodeBin, args, logFile });
|
|
571
|
+
writePrivateFileAtomic(plistPath, plist);
|
|
572
|
+
|
|
573
|
+
try {
|
|
574
|
+
execFileSync("launchctl", ["unload", plistPath], { stdio: "ignore" });
|
|
575
|
+
} catch {
|
|
576
|
+
// not loaded yet
|
|
577
|
+
}
|
|
578
|
+
execFileSync("launchctl", ["load", plistPath], { stdio: "inherit" });
|
|
579
|
+
|
|
580
|
+
console.log(
|
|
581
|
+
JSON.stringify(
|
|
582
|
+
{ installed: true, label: LAUNCHD_LABEL, plist: plistPath, log: logFile, intervalSeconds: Number(intervalSeconds), deviceId, dbPath },
|
|
583
|
+
null,
|
|
584
|
+
2
|
|
585
|
+
)
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
async function uninstallAgent() {
|
|
590
|
+
if (process.platform === "linux") {
|
|
591
|
+
uninstallSystemdAgent();
|
|
592
|
+
} else if (process.platform === "win32") {
|
|
593
|
+
uninstallWindowsAgent();
|
|
594
|
+
} else if (process.platform === "darwin") {
|
|
595
|
+
const plistPath = launchAgentPath();
|
|
596
|
+
try {
|
|
597
|
+
execFileSync("launchctl", ["unload", plistPath], { stdio: "ignore" });
|
|
598
|
+
} catch {
|
|
599
|
+
// already unloaded
|
|
600
|
+
}
|
|
601
|
+
if (existsSync(plistPath)) {
|
|
602
|
+
rmSync(plistPath);
|
|
603
|
+
}
|
|
604
|
+
} else {
|
|
605
|
+
throw new Error(`uninstall is not supported on ${process.platform}`);
|
|
606
|
+
}
|
|
607
|
+
if (existsSync(TOKEN_FILE)) {
|
|
608
|
+
validatePrivateFile(TOKEN_FILE);
|
|
609
|
+
rmSync(TOKEN_FILE);
|
|
610
|
+
}
|
|
611
|
+
console.log(JSON.stringify({ uninstalled: true, platform: process.platform }, null, 2));
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function launchAgentPath() {
|
|
615
|
+
return join(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function buildPlist({ nodeBin, args, logFile }) {
|
|
619
|
+
const programArgs = [nodeBin, ...args]
|
|
620
|
+
.map((value) => ` <string>${escapeXml(String(value))}</string>`)
|
|
621
|
+
.join("\n");
|
|
622
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
623
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
624
|
+
<plist version="1.0">
|
|
625
|
+
<dict>
|
|
626
|
+
<key>Label</key>
|
|
627
|
+
<string>${LAUNCHD_LABEL}</string>
|
|
628
|
+
<key>ProgramArguments</key>
|
|
629
|
+
<array>
|
|
630
|
+
${programArgs}
|
|
631
|
+
</array>
|
|
632
|
+
<key>RunAtLoad</key>
|
|
633
|
+
<true/>
|
|
634
|
+
<key>KeepAlive</key>
|
|
635
|
+
<true/>
|
|
636
|
+
<key>StandardOutPath</key>
|
|
637
|
+
<string>${escapeXml(logFile)}</string>
|
|
638
|
+
<key>StandardErrorPath</key>
|
|
639
|
+
<string>${escapeXml(logFile)}</string>
|
|
640
|
+
</dict>
|
|
641
|
+
</plist>
|
|
642
|
+
`;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function installSystemdAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases }) {
|
|
646
|
+
const unitDir = join(homedir(), ".config", "systemd", "user");
|
|
647
|
+
const unitPath = join(unitDir, SYSTEMD_UNIT);
|
|
648
|
+
mkdirSync(unitDir, { recursive: true, mode: 0o700 });
|
|
649
|
+
const args = launchAgentArgs({
|
|
650
|
+
self: SELF,
|
|
651
|
+
api,
|
|
652
|
+
tokenFile: TOKEN_FILE,
|
|
653
|
+
intervalSeconds,
|
|
654
|
+
deviceId,
|
|
655
|
+
dbPath,
|
|
656
|
+
deviceAliases
|
|
657
|
+
});
|
|
658
|
+
writePrivateFileAtomic(unitPath, buildSystemdUnit({ nodeBin, args }));
|
|
659
|
+
execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "inherit" });
|
|
660
|
+
execFileSync("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT], { stdio: "inherit" });
|
|
661
|
+
console.log(JSON.stringify({
|
|
662
|
+
installed: true,
|
|
663
|
+
platform: "linux",
|
|
664
|
+
service: SYSTEMD_UNIT,
|
|
665
|
+
unit: unitPath,
|
|
666
|
+
logs: `journalctl --user -u ${SYSTEMD_UNIT} -f`,
|
|
667
|
+
intervalSeconds: Number(intervalSeconds),
|
|
668
|
+
deviceId,
|
|
669
|
+
dbPath
|
|
670
|
+
}, null, 2));
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function uninstallSystemdAgent() {
|
|
674
|
+
const unitPath = join(homedir(), ".config", "systemd", "user", SYSTEMD_UNIT);
|
|
675
|
+
try {
|
|
676
|
+
execFileSync("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT], { stdio: "ignore" });
|
|
677
|
+
} catch {
|
|
678
|
+
// already stopped or user systemd unavailable
|
|
679
|
+
}
|
|
680
|
+
if (existsSync(unitPath)) rmSync(unitPath);
|
|
681
|
+
try {
|
|
682
|
+
execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
|
|
683
|
+
} catch {
|
|
684
|
+
// nothing left to reload
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function buildSystemdUnit({ nodeBin, args }) {
|
|
689
|
+
const command = [nodeBin, ...args].map(systemdQuote).join(" ");
|
|
690
|
+
return `[Unit]
|
|
691
|
+
Description=Recall Cloud memory sync
|
|
692
|
+
After=network-online.target
|
|
693
|
+
Wants=network-online.target
|
|
694
|
+
|
|
695
|
+
[Service]
|
|
696
|
+
Type=simple
|
|
697
|
+
ExecStart=${command}
|
|
698
|
+
Restart=always
|
|
699
|
+
RestartSec=10
|
|
700
|
+
|
|
701
|
+
[Install]
|
|
702
|
+
WantedBy=default.target
|
|
703
|
+
`;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function systemdQuote(value) {
|
|
707
|
+
return `"${String(value).replace(/([\\"])/g, "\\$1")}"`;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function installWindowsAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases }) {
|
|
711
|
+
const configDir = dirname(TOKEN_FILE);
|
|
712
|
+
secureWindowsConfigDirectory(configDir);
|
|
713
|
+
const launcherPath = join(configDir, "watch.ps1");
|
|
714
|
+
const logFile = join(configDir, "sync.log");
|
|
715
|
+
const args = launchAgentArgs({
|
|
716
|
+
self: SELF,
|
|
717
|
+
api,
|
|
718
|
+
tokenFile: TOKEN_FILE,
|
|
719
|
+
intervalSeconds,
|
|
720
|
+
deviceId,
|
|
721
|
+
dbPath,
|
|
722
|
+
deviceAliases
|
|
723
|
+
});
|
|
724
|
+
writePrivateFileAtomic(
|
|
725
|
+
launcherPath,
|
|
726
|
+
buildWindowsLauncher({ nodeBin, args, logFile })
|
|
727
|
+
);
|
|
728
|
+
const escapedLauncherPath = launcherPath.replace(/"/g, '\\"');
|
|
729
|
+
const taskArgs = `-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "${escapedLauncherPath}"`;
|
|
730
|
+
const command = [
|
|
731
|
+
"$identity=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",
|
|
732
|
+
`$action=New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ${powerShellQuote(taskArgs)}`,
|
|
733
|
+
"if ($identity -eq 'NT AUTHORITY\\SYSTEM') { $trigger=New-ScheduledTaskTrigger -AtStartup; $principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest } else { $trigger=New-ScheduledTaskTrigger -AtLogOn -User $identity; $principal=New-ScheduledTaskPrincipal -UserId $identity -LogonType Interactive -RunLevel Limited }",
|
|
734
|
+
"$settings=New-ScheduledTaskSettingsSet -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
|
|
735
|
+
`Register-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null`,
|
|
736
|
+
`Start-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)}`
|
|
737
|
+
].join("; ");
|
|
738
|
+
execFileSync(
|
|
739
|
+
"powershell.exe",
|
|
740
|
+
["-NoProfile", "-NonInteractive", "-Command", command],
|
|
741
|
+
{ stdio: "inherit" }
|
|
742
|
+
);
|
|
743
|
+
console.log(JSON.stringify({
|
|
744
|
+
installed: true,
|
|
745
|
+
platform: "win32",
|
|
746
|
+
task: WINDOWS_TASK,
|
|
747
|
+
launcher: launcherPath,
|
|
748
|
+
log: logFile,
|
|
749
|
+
intervalSeconds: Number(intervalSeconds),
|
|
750
|
+
deviceId,
|
|
751
|
+
dbPath
|
|
752
|
+
}, null, 2));
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function secureWindowsConfigDirectory(configDir) {
|
|
756
|
+
const command = [
|
|
757
|
+
"$identity=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",
|
|
758
|
+
"$acl=New-Object System.Security.AccessControl.DirectorySecurity",
|
|
759
|
+
"$acl.SetAccessRuleProtection($true,$false)",
|
|
760
|
+
"$rule=New-Object System.Security.AccessControl.FileSystemAccessRule($identity,'FullControl','ContainerInherit,ObjectInherit','None','Allow')",
|
|
761
|
+
"$acl.SetOwner([System.Security.Principal.NTAccount]$identity)",
|
|
762
|
+
"$acl.SetAccessRule($rule)",
|
|
763
|
+
`Set-Acl -LiteralPath ${powerShellQuote(configDir)} -AclObject $acl`
|
|
764
|
+
].join("; ");
|
|
765
|
+
execFileSync(
|
|
766
|
+
"powershell.exe",
|
|
767
|
+
["-NoProfile", "-NonInteractive", "-Command", command],
|
|
768
|
+
{ stdio: "inherit" }
|
|
769
|
+
);
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
function uninstallWindowsAgent() {
|
|
773
|
+
const command = [
|
|
774
|
+
`$task=Get-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -ErrorAction SilentlyContinue`,
|
|
775
|
+
`if ($task) { Stop-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -Confirm:$false }`
|
|
776
|
+
].join("; ");
|
|
777
|
+
execFileSync(
|
|
778
|
+
"powershell.exe",
|
|
779
|
+
["-NoProfile", "-NonInteractive", "-Command", command],
|
|
780
|
+
{ stdio: "ignore" }
|
|
781
|
+
);
|
|
782
|
+
const launcherPath = join(dirname(TOKEN_FILE), "watch.ps1");
|
|
783
|
+
if (existsSync(launcherPath)) rmSync(launcherPath);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
function buildWindowsLauncher({ nodeBin, args, logFile }) {
|
|
787
|
+
const invoke = [nodeBin, ...args].map(powerShellQuote).join(" ");
|
|
788
|
+
return `$ErrorActionPreference = 'Continue'
|
|
789
|
+
while ($true) {
|
|
790
|
+
& ${invoke} *>> ${powerShellQuote(logFile)}
|
|
791
|
+
Start-Sleep -Seconds 10
|
|
792
|
+
}
|
|
793
|
+
`;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function powerShellQuote(value) {
|
|
797
|
+
return `'${String(value).replace(/'/g, "''")}'`;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function launchAgentArgs({ self, api, tokenFile, intervalSeconds, deviceId, dbPath, deviceAliases = {} }) {
|
|
801
|
+
const args = [
|
|
802
|
+
self,
|
|
803
|
+
"watch",
|
|
804
|
+
"--api",
|
|
805
|
+
api,
|
|
806
|
+
"--token-file",
|
|
807
|
+
tokenFile,
|
|
808
|
+
"--interval",
|
|
809
|
+
intervalSeconds,
|
|
810
|
+
"--device-id",
|
|
811
|
+
deviceId,
|
|
812
|
+
"--db",
|
|
813
|
+
dbPath
|
|
814
|
+
];
|
|
815
|
+
for (const [from, to] of Object.entries(deviceAliases).sort(([a], [b]) => a.localeCompare(b))) {
|
|
816
|
+
args.push("--device-alias", `${from}=${to}`);
|
|
817
|
+
}
|
|
818
|
+
return args;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function resolveToken(options, { legacyPlistPath } = {}) {
|
|
822
|
+
const explicitSources = [
|
|
823
|
+
options.token ? "token" : null,
|
|
824
|
+
options.tokenFile ? "token-file" : null,
|
|
825
|
+
options.tokenStdin ? "token-stdin" : null
|
|
826
|
+
].filter(Boolean);
|
|
827
|
+
if (explicitSources.length > 1) {
|
|
828
|
+
throw new Error(`Use only one token source, received: ${explicitSources.join(", ")}`);
|
|
829
|
+
}
|
|
830
|
+
if (options.token) return normalizeToken(options.token);
|
|
831
|
+
if (options.tokenFile) return readPrivateTokenFile(options.tokenFile);
|
|
832
|
+
if (options.tokenStdin) return normalizeToken(readFileSync(0, "utf8"));
|
|
833
|
+
if (process.env.RECALL_CLOUD_TOKEN) return normalizeToken(process.env.RECALL_CLOUD_TOKEN);
|
|
834
|
+
if (legacyPlistPath && existsSync(legacyPlistPath)) {
|
|
835
|
+
const token = legacyTokenFromPlist(legacyPlistPath);
|
|
836
|
+
if (token) return token;
|
|
837
|
+
}
|
|
838
|
+
throw new Error("--token-file, --token-stdin, or RECALL_CLOUD_TOKEN is required");
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function legacyTokenFromPlist(plistPath) {
|
|
842
|
+
validatePrivateFile(plistPath);
|
|
843
|
+
const output = execFileSync(
|
|
844
|
+
"/usr/bin/plutil",
|
|
845
|
+
["-extract", "ProgramArguments", "json", "-o", "-", plistPath],
|
|
846
|
+
{ encoding: "utf8", maxBuffer: 1024 * 1024 }
|
|
847
|
+
);
|
|
848
|
+
return legacyTokenFromArgs(JSON.parse(output));
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
function resolveDeviceAliases(options, { plistPath } = {}) {
|
|
852
|
+
const explicit = parseDeviceAliases(options.deviceAlias);
|
|
853
|
+
if (Object.keys(explicit).length > 0) return explicit;
|
|
854
|
+
if (!plistPath && process.platform === "darwin") {
|
|
855
|
+
plistPath = launchAgentPath();
|
|
856
|
+
}
|
|
857
|
+
if (!plistPath || !existsSync(plistPath)) return {};
|
|
858
|
+
return installedDeviceAliasesFromPlist(plistPath);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
function installedDeviceAliasesFromPlist(plistPath) {
|
|
862
|
+
validatePrivateFile(plistPath);
|
|
863
|
+
const output = execFileSync(
|
|
864
|
+
"/usr/bin/plutil",
|
|
865
|
+
["-extract", "ProgramArguments", "json", "-o", "-", plistPath],
|
|
866
|
+
{ encoding: "utf8", maxBuffer: 1024 * 1024 }
|
|
867
|
+
);
|
|
868
|
+
return deviceAliasesFromArgs(JSON.parse(output));
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function installedDeviceIdFromPlist(plistPath) {
|
|
872
|
+
validatePrivateFile(plistPath);
|
|
873
|
+
const output = execFileSync(
|
|
874
|
+
"/usr/bin/plutil",
|
|
875
|
+
["-extract", "ProgramArguments", "json", "-o", "-", plistPath],
|
|
876
|
+
{ encoding: "utf8", maxBuffer: 1024 * 1024 }
|
|
877
|
+
);
|
|
878
|
+
return deviceIdFromArgs(JSON.parse(output));
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
function deviceAliasesFromArgs(args) {
|
|
882
|
+
if (!Array.isArray(args)) return {};
|
|
883
|
+
const values = [];
|
|
884
|
+
for (let index = 0; index < args.length; index++) {
|
|
885
|
+
if (args[index] === "--device-alias" && typeof args[index + 1] === "string") {
|
|
886
|
+
values.push(args[index + 1]);
|
|
887
|
+
index++;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
return parseDeviceAliases(values);
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
function deviceIdFromArgs(args) {
|
|
894
|
+
if (!Array.isArray(args)) return null;
|
|
895
|
+
const index = args.indexOf("--device-id");
|
|
896
|
+
if (index === -1 || typeof args[index + 1] !== "string") return null;
|
|
897
|
+
return args[index + 1];
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
function legacyTokenFromArgs(args) {
|
|
901
|
+
if (!Array.isArray(args)) return null;
|
|
902
|
+
const index = args.indexOf("--token");
|
|
903
|
+
if (index === -1 || typeof args[index + 1] !== "string") return null;
|
|
904
|
+
return normalizeToken(args[index + 1]);
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function escapeXml(value) {
|
|
908
|
+
return value
|
|
909
|
+
.replace(/&/g, "&")
|
|
910
|
+
.replace(/</g, "<")
|
|
911
|
+
.replace(/>/g, ">");
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
function sleep(ms, keepGoing) {
|
|
915
|
+
return new Promise((resolveSleep) => {
|
|
916
|
+
const step = 1000;
|
|
917
|
+
let elapsed = 0;
|
|
918
|
+
const timer = setInterval(() => {
|
|
919
|
+
elapsed += step;
|
|
920
|
+
if (elapsed >= ms || (keepGoing && !keepGoing())) {
|
|
921
|
+
clearInterval(timer);
|
|
922
|
+
resolveSleep();
|
|
923
|
+
}
|
|
924
|
+
}, step);
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function readRecallMemories(dbPath, statusSet, limit, cursor = {}) {
|
|
929
|
+
if (!existsSync(dbPath)) {
|
|
930
|
+
throw new Error(`Recall DB not found: ${dbPath}`);
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
const db = new Database(dbPath, { readonly: true, fileMustExist: true });
|
|
934
|
+
try {
|
|
935
|
+
db.pragma("query_only = ON");
|
|
936
|
+
const placeholders = [...statusSet].map(() => "?").join(",");
|
|
937
|
+
const cursorClause = cursor.after
|
|
938
|
+
? "AND (updated_at > ? OR (updated_at = ? AND id > ?))"
|
|
939
|
+
: "";
|
|
940
|
+
const params = [...statusSet];
|
|
941
|
+
if (cursor.after) {
|
|
942
|
+
params.push(cursor.after, cursor.after, cursor.afterId ?? "");
|
|
943
|
+
}
|
|
944
|
+
params.push(limit);
|
|
945
|
+
return db.prepare(`
|
|
946
|
+
SELECT
|
|
947
|
+
id, type, text, scope, path_scope, repo, status, confidence, source,
|
|
948
|
+
evidence, capture_context, supersedes, created_at, updated_at,
|
|
949
|
+
last_validated_at, last_injected_at, injection_count, override_count,
|
|
950
|
+
repetition_count, team_id, sync_version, auto_inject, dedupe_key
|
|
951
|
+
FROM memories
|
|
952
|
+
WHERE status IN (${placeholders})
|
|
953
|
+
${cursorClause}
|
|
954
|
+
ORDER BY updated_at ASC
|
|
955
|
+
, id ASC
|
|
956
|
+
LIMIT ?
|
|
957
|
+
`).all(...params);
|
|
958
|
+
} finally {
|
|
959
|
+
db.close();
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
function loadSyncState(statePath) {
|
|
964
|
+
if (!existsSync(statePath)) return { version: 1, entries: {} };
|
|
965
|
+
validatePrivateFile(statePath);
|
|
966
|
+
try {
|
|
967
|
+
const value = JSON.parse(readFileSync(statePath, "utf8"));
|
|
968
|
+
if (
|
|
969
|
+
value?.version === 1
|
|
970
|
+
&& value.entries
|
|
971
|
+
&& typeof value.entries === "object"
|
|
972
|
+
&& !Array.isArray(value.entries)
|
|
973
|
+
) {
|
|
974
|
+
return value;
|
|
975
|
+
}
|
|
976
|
+
} catch {
|
|
977
|
+
// Fail safe: a corrupt cursor causes one full reconciliation, not data loss.
|
|
978
|
+
}
|
|
979
|
+
return { version: 1, entries: {} };
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
function saveSyncState(statePath, state) {
|
|
983
|
+
mkdirSync(dirname(statePath), { recursive: true, mode: 0o700 });
|
|
984
|
+
writePrivateFileAtomic(statePath, `${JSON.stringify(state, null, 2)}\n`);
|
|
985
|
+
validatePrivateFile(statePath);
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// The record's "source" for the cloud Sources page (privacy-toggle unit). Group
|
|
989
|
+
// by repo/project when known (e.g. "edihasaj/recall"); fall back to the local
|
|
990
|
+
// capture channel (e.g. "capture:user_correction"), else a generic "local"
|
|
991
|
+
// bucket. The cloud registers one source per distinct ref and attributes each
|
|
992
|
+
// memory to it (memory_records.source_id), which is what the Sources page lists.
|
|
993
|
+
function sourceRefFor(row) {
|
|
994
|
+
const repo = row.repo ? String(row.repo).trim() : "";
|
|
995
|
+
if (repo) return repo;
|
|
996
|
+
const src = row.source ? String(row.source).trim() : "";
|
|
997
|
+
if (src) return `capture:${src}`;
|
|
998
|
+
return "local";
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function toCloudRecord(row, deviceId, e2ee = null, deviceAliases = {}) {
|
|
1002
|
+
const recall = {
|
|
1003
|
+
type: row.type,
|
|
1004
|
+
...(Object.hasOwn(row, "note") ? { note: typeof row.note === "string" ? row.note.replace(/\s+/g, " ").trim() || null : null } : {}),
|
|
1005
|
+
scope: row.scope,
|
|
1006
|
+
pathScope: row.path_scope,
|
|
1007
|
+
repo: row.repo,
|
|
1008
|
+
source: row.source,
|
|
1009
|
+
evidence: parseJson(row.evidence, []),
|
|
1010
|
+
captureContext: parseJson(row.capture_context, null),
|
|
1011
|
+
supersedes: row.supersedes,
|
|
1012
|
+
lastValidatedAt: row.last_validated_at,
|
|
1013
|
+
lastInjectedAt: row.last_injected_at,
|
|
1014
|
+
injectionCount: row.injection_count,
|
|
1015
|
+
overrideCount: row.override_count,
|
|
1016
|
+
repetitionCount: row.repetition_count,
|
|
1017
|
+
teamId: row.team_id,
|
|
1018
|
+
syncVersion: row.sync_version,
|
|
1019
|
+
autoInject: Boolean(row.auto_inject),
|
|
1020
|
+
dedupeKey: row.dedupe_key
|
|
1021
|
+
};
|
|
1022
|
+
|
|
1023
|
+
const base = {
|
|
1024
|
+
externalId: cloudExternalIdForRow(row, deviceId, deviceAliases),
|
|
1025
|
+
status: normalizeStatus(row.status),
|
|
1026
|
+
kind: row.type,
|
|
1027
|
+
confidence: clampConfidence(row.confidence),
|
|
1028
|
+
createdAt: row.created_at,
|
|
1029
|
+
updatedAt: row.updated_at
|
|
1030
|
+
};
|
|
1031
|
+
|
|
1032
|
+
if (e2ee) {
|
|
1033
|
+
// Zero-knowledge: encrypt BOTH the text and the rich metadata (evidence /
|
|
1034
|
+
// capture context carry plaintext), and omit the repo-based sourceId so the
|
|
1035
|
+
// server never learns which projects the memories came from. Only opaque
|
|
1036
|
+
// ciphertext + structural fields (kind/confidence/timestamps) are sent.
|
|
1037
|
+
const { ciphertext, nonce } = e2eeEncrypt(e2ee.key, JSON.stringify({ text: row.text, recall }));
|
|
1038
|
+
return {
|
|
1039
|
+
...base,
|
|
1040
|
+
encryptionMode: "e2ee",
|
|
1041
|
+
contentCiphertext: ciphertext,
|
|
1042
|
+
contentNonce: nonce,
|
|
1043
|
+
contentKeyId: E2EE_KEY_ID,
|
|
1044
|
+
metadata: { e2ee: true, source: "recall-local-sqlite", localMemoryId: row.id, deviceId }
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
return {
|
|
1049
|
+
...base,
|
|
1050
|
+
sourceId: sourceRefFor(row),
|
|
1051
|
+
encryptionMode: "synced",
|
|
1052
|
+
contentPlaintext: row.text,
|
|
1053
|
+
metadata: { source: "recall-local-sqlite", localMemoryId: row.id, deviceId, recall }
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
async function fetchAllSyncRecords({ api, token, since = null, sinceId = null, max = 100000 }) {
|
|
1058
|
+
const all = [];
|
|
1059
|
+
let cursorTime = since ?? null;
|
|
1060
|
+
let cursorId = sinceId ?? null;
|
|
1061
|
+
|
|
1062
|
+
while (all.length < max) {
|
|
1063
|
+
const pageSize = Math.min(500, max - all.length);
|
|
1064
|
+
const result = await fetchJson(`${api}/v1/sync/pull`, {
|
|
1065
|
+
method: "POST",
|
|
1066
|
+
token,
|
|
1067
|
+
body: { since: cursorTime, sinceId: cursorId, limit: pageSize }
|
|
1068
|
+
});
|
|
1069
|
+
const batch = Array.isArray(result.records) ? result.records : [];
|
|
1070
|
+
if (batch.length === 0) break;
|
|
1071
|
+
all.push(...batch);
|
|
1072
|
+
const last = batch[batch.length - 1];
|
|
1073
|
+
if (!last?.updatedAt || !last?.externalId || batch.length < pageSize) break;
|
|
1074
|
+
cursorTime = last.updatedAt;
|
|
1075
|
+
cursorId = last.externalId;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
return all;
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
async function fetchJson(url, { method, token, body }) {
|
|
1082
|
+
const headers = { "content-type": "application/json" };
|
|
1083
|
+
if (token) headers.authorization = `Bearer ${token}`;
|
|
1084
|
+
|
|
1085
|
+
const response = await fetch(url, {
|
|
1086
|
+
method,
|
|
1087
|
+
headers,
|
|
1088
|
+
body: JSON.stringify(body ?? {})
|
|
1089
|
+
});
|
|
1090
|
+
const text = await response.text();
|
|
1091
|
+
if (!response.ok) {
|
|
1092
|
+
let detail = response.statusText;
|
|
1093
|
+
try {
|
|
1094
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
1095
|
+
if (typeof parsed.error === "string") detail = parsed.error;
|
|
1096
|
+
} catch {
|
|
1097
|
+
// HTML proxy errors are intentionally not echoed into long-lived logs.
|
|
1098
|
+
}
|
|
1099
|
+
throw new Error(`${method} ${url} failed ${response.status}: ${detail}`);
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
try {
|
|
1103
|
+
return text ? JSON.parse(text) : {};
|
|
1104
|
+
} catch {
|
|
1105
|
+
throw new Error(`${method} ${url} returned invalid JSON response (${response.status})`);
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
function normalizeStatus(status) {
|
|
1110
|
+
if (status === "active" || status === "candidate" || status === "rejected") return status;
|
|
1111
|
+
if (status === "transient") return "candidate";
|
|
1112
|
+
throw new Error(`Unsupported Recall status: ${status}`);
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
function clampConfidence(value) {
|
|
1116
|
+
const number = Number(value ?? 0);
|
|
1117
|
+
if (!Number.isFinite(number)) return 0;
|
|
1118
|
+
return Math.max(0, Math.min(1, number));
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
function parseJson(value, fallback) {
|
|
1122
|
+
if (value == null || value === "") return fallback;
|
|
1123
|
+
if (typeof value !== "string") return value;
|
|
1124
|
+
try {
|
|
1125
|
+
return JSON.parse(value);
|
|
1126
|
+
} catch {
|
|
1127
|
+
return fallback;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
function chunks(values, size) {
|
|
1132
|
+
const result = [];
|
|
1133
|
+
for (let index = 0; index < values.length; index += size) {
|
|
1134
|
+
result.push(values.slice(index, index + size));
|
|
1135
|
+
}
|
|
1136
|
+
return result;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
function parseOptions(args) {
|
|
1140
|
+
const options = {};
|
|
1141
|
+
for (let index = 0; index < args.length; index++) {
|
|
1142
|
+
const arg = args[index];
|
|
1143
|
+
if (!arg.startsWith("--")) {
|
|
1144
|
+
throw new Error(`Unexpected argument: ${arg}`);
|
|
1145
|
+
}
|
|
1146
|
+
const key = camelCase(arg.slice(2));
|
|
1147
|
+
if (
|
|
1148
|
+
key === "dryRun"
|
|
1149
|
+
|| key === "json"
|
|
1150
|
+
|| key === "quiet"
|
|
1151
|
+
|| key === "e2ee"
|
|
1152
|
+
|| key === "sample"
|
|
1153
|
+
|| key === "tokenStdin"
|
|
1154
|
+
|| key === "forceDeviceId"
|
|
1155
|
+
) {
|
|
1156
|
+
options[key] = true;
|
|
1157
|
+
continue;
|
|
1158
|
+
}
|
|
1159
|
+
const value = args[index + 1];
|
|
1160
|
+
if (!value || value.startsWith("--")) {
|
|
1161
|
+
throw new Error(`Missing value for ${arg}`);
|
|
1162
|
+
}
|
|
1163
|
+
if (options[key] == null) {
|
|
1164
|
+
options[key] = value;
|
|
1165
|
+
} else if (Array.isArray(options[key])) {
|
|
1166
|
+
options[key].push(value);
|
|
1167
|
+
} else {
|
|
1168
|
+
options[key] = [options[key], value];
|
|
1169
|
+
}
|
|
1170
|
+
index++;
|
|
1171
|
+
}
|
|
1172
|
+
return options;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
function parseDeviceAliases(value) {
|
|
1176
|
+
const aliases = {};
|
|
1177
|
+
const values = Array.isArray(value) ? value : value == null ? [] : [value];
|
|
1178
|
+
for (const entry of values) {
|
|
1179
|
+
const text = String(entry);
|
|
1180
|
+
const separator = text.indexOf("=");
|
|
1181
|
+
if (separator <= 0 || separator === text.length - 1) {
|
|
1182
|
+
throw new Error(`Invalid --device-alias value: ${text}`);
|
|
1183
|
+
}
|
|
1184
|
+
const from = text.slice(0, separator).trim();
|
|
1185
|
+
const to = text.slice(separator + 1).trim();
|
|
1186
|
+
if (!from || !to || from.includes(":") || to.includes(":")) {
|
|
1187
|
+
throw new Error(`Invalid --device-alias value: ${text}`);
|
|
1188
|
+
}
|
|
1189
|
+
aliases[from] = to;
|
|
1190
|
+
}
|
|
1191
|
+
return aliases;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
function camelCase(value) {
|
|
1195
|
+
return value.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
function required(value, flag) {
|
|
1199
|
+
if (!value) {
|
|
1200
|
+
throw new Error(`${flag} is required`);
|
|
1201
|
+
}
|
|
1202
|
+
return value;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
function requiredApi(value) {
|
|
1206
|
+
return validateApiUrl(required(value, "--api"));
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
function parseInteger(value, fallback) {
|
|
1210
|
+
if (value == null) return fallback;
|
|
1211
|
+
const parsed = Number.parseInt(String(value), 10);
|
|
1212
|
+
if (!Number.isInteger(parsed) || parsed < 1) {
|
|
1213
|
+
throw new Error(`Invalid integer: ${value}`);
|
|
1214
|
+
}
|
|
1215
|
+
return parsed;
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
export function parseNonNegativeInteger(value, fallback) {
|
|
1219
|
+
if (value == null) return fallback;
|
|
1220
|
+
const parsed = Number.parseInt(String(value), 10);
|
|
1221
|
+
if (!Number.isInteger(parsed) || parsed < 0) {
|
|
1222
|
+
throw new Error(`Invalid integer: ${value}`);
|
|
1223
|
+
}
|
|
1224
|
+
return parsed;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
function expandHome(value) {
|
|
1228
|
+
if (value === "~") return homedir();
|
|
1229
|
+
if (value.startsWith("~/")) return join(homedir(), value.slice(2));
|
|
1230
|
+
return value;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
function hostnameLabel() {
|
|
1234
|
+
return process.env.RECALL_CLOUD_DEVICE_ID
|
|
1235
|
+
?? process.env.HOSTNAME
|
|
1236
|
+
?? hostname()
|
|
1237
|
+
?? "local-device";
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
function usage() {
|
|
1241
|
+
console.log(`Usage:
|
|
1242
|
+
node scripts/recall-sync.mjs push --api <url> --token-file <0600-file> [--db ~/.recall/recall.db] [--status active,candidate] [--dry-run] [--sample]
|
|
1243
|
+
node scripts/recall-sync.mjs pull --api <url> --token-file <0600-file> [--db ~/.recall/recall.db] [--since <iso>] [--limit 100000] [--rejected-retention-days 90] [--dry-run]
|
|
1244
|
+
node scripts/recall-sync.mjs verify --api <url> --token-file <0600-file> [--query recall]
|
|
1245
|
+
node scripts/recall-sync.mjs memories --api <url> --token-file <0600-file> [--query <text>] [--device <id>] [--show 40] [--json]
|
|
1246
|
+
node scripts/recall-sync.mjs watch --api <url> --token-file <0600-file> [--interval 300] [--full-reconcile-interval 86400] [--status active,candidate] [--device-id <id>] [--device-alias old=new]
|
|
1247
|
+
printf '%s' "$RECALL_CLOUD_TOKEN" | node scripts/recall-sync.mjs install --api <url> --token-stdin [--interval 300] [--device-id <id>] [--device-alias old=new] [--force-device-id]
|
|
1248
|
+
node scripts/recall-sync.mjs uninstall # remove launchd auto-sync
|
|
1249
|
+
|
|
1250
|
+
E2EE (zero-knowledge): add --e2ee (with --e2ee-passphrase <secret> or RECALL_CLOUD_E2EE_PASSPHRASE)
|
|
1251
|
+
to push/pull/watch to encrypt or decrypt content + metadata client-side; the server stores only
|
|
1252
|
+
ciphertext and cannot search/compile/profile those memories. Add --e2ee to 'memories' to decrypt
|
|
1253
|
+
and read them back locally. Use the SAME passphrase on every device. Tradeoff: e2ee memories are
|
|
1254
|
+
invisible to the web portal, hosted MCP, and server-side search.
|
|
1255
|
+
|
|
1256
|
+
Token sources: --token-file (preferred), --token-stdin (install/one-off), or RECALL_CLOUD_TOKEN.
|
|
1257
|
+
The legacy --token flag remains compatible for one-off commands but exposes its value in process listings.
|
|
1258
|
+
Env fallbacks: RECALL_CLOUD_API, RECALL_CLOUD_TOKEN, RECALL_DB, RECALL_CLOUD_DEVICE_ID, RECALL_CLOUD_E2EE_PASSPHRASE
|
|
1259
|
+
Install refuses accidental device-id changes because local-origin records use it
|
|
1260
|
+
in cloud external IDs; use --force-device-id only for an intentional migration.
|
|
1261
|
+
Use --device-alias old=new during a migration so imported rows that still remember
|
|
1262
|
+
old cloud origins are pushed under the canonical device id.
|
|
1263
|
+
Dry-run push output is count-only by default; add --sample only when plaintext
|
|
1264
|
+
record samples are intentionally needed for debugging.
|
|
1265
|
+
`);
|
|
1266
|
+
}
|