@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.
Files changed (83) hide show
  1. package/README.md +22 -4
  2. package/dist/{chunk-Q2F7EQCA.js → chunk-22AJZ7UQ.js} +2 -2
  3. package/dist/{chunk-GCMP2YYN.js → chunk-2COJXGP4.js} +2 -2
  4. package/dist/{chunk-SYSSACWJ.js → chunk-CSBXI3ET.js} +39 -20
  5. package/dist/chunk-CSBXI3ET.js.map +1 -0
  6. package/dist/{chunk-QPR77YXP.js → chunk-EY6HIDG2.js} +13 -11
  7. package/dist/chunk-EY6HIDG2.js.map +1 -0
  8. package/dist/{chunk-GDN44ZC7.js → chunk-FNIIUNW6.js} +2 -2
  9. package/dist/{chunk-YELXEWKH.js → chunk-GK7OWVRQ.js} +3 -3
  10. package/dist/{chunk-7UWVXXTU.js → chunk-KLERXJ47.js} +3 -3
  11. package/dist/{chunk-THC7QOAK.js → chunk-KVZN35JF.js} +7 -7
  12. package/dist/{chunk-SEXZABB2.js → chunk-Q22B7YDQ.js} +5 -5
  13. package/dist/{chunk-VRAG5V66.js → chunk-Q7254IPO.js} +908 -43
  14. package/dist/chunk-Q7254IPO.js.map +1 -0
  15. package/dist/{chunk-EKFOHVHS.js → chunk-QQ6YHR7I.js} +11 -11
  16. package/dist/{chunk-MLC3KO2O.js → chunk-RAQT2OBR.js} +7 -7
  17. package/dist/{chunk-DVLQYARZ.js → chunk-UDLRBKC3.js} +3 -3
  18. package/dist/{chunk-DOYTMHDI.js → chunk-VUVFQJWZ.js} +2 -2
  19. package/dist/{chunk-LEOXFQJJ.js → chunk-XRKUJ5B4.js} +2 -2
  20. package/dist/{chunk-ZF23OPYV.js → chunk-YIUBD27J.js} +14 -14
  21. package/dist/chunk-YIUBD27J.js.map +1 -0
  22. package/dist/{chunk-DAW6FUGL.js → chunk-YIVOTIDF.js} +5 -5
  23. package/dist/{chunk-FYMMTODQ.js → chunk-ZT67CYDS.js} +2 -2
  24. package/dist/{chunk-FYMMTODQ.js.map → chunk-ZT67CYDS.js.map} +1 -1
  25. package/dist/{cleanup-WJFE6IVP.js → cleanup-4TXIHTJT.js} +11 -11
  26. package/dist/cli.js +55 -36
  27. package/dist/cli.js.map +1 -1
  28. package/dist/{codex-trust-3BFTJFRD.js → codex-trust-2JIY66CP.js} +4 -4
  29. package/dist/daemon.js +1090 -169
  30. package/dist/daemon.js.map +1 -1
  31. package/dist/dispatcher-O6NGADCQ.js +22 -0
  32. package/dist/{embeddings-H352GFKD.js → embeddings-AAS7NKGB.js} +5 -5
  33. package/dist/ingest-DW3AG4M5.js +20 -0
  34. package/dist/{keychain-A2Z7D7YE.js → keychain-SHRO7W6J.js} +3 -3
  35. package/dist/mcp.js +15 -15
  36. package/dist/{memory-value-M3TA7SEK.js → memory-value-R2C7ZSDF.js} +11 -11
  37. package/dist/{provenance-CXU6LZK7.js → provenance-I5GIAP7N.js} +9 -9
  38. package/dist/quality-32MAXPNJ.js +25 -0
  39. package/dist/retrieval-RKYWWNWC.js +15 -0
  40. package/dist/{store-YCVWABSH.js → store-X2B6MRBH.js} +4 -4
  41. package/dist/sync-server.js +2 -2
  42. package/dist/{tasks-4UL2FIAQ.js → tasks-H4NIS6QO.js} +11 -11
  43. package/dist/{usage-HZ27RG53.js → usage-35HSDMNT.js} +4 -4
  44. package/package.json +2 -1
  45. package/vendor/recall-cloud-sync/PROVENANCE.md +27 -0
  46. package/vendor/recall-cloud-sync/managed-worker.mjs +48 -0
  47. package/vendor/recall-cloud-sync/private-token.mjs +95 -0
  48. package/vendor/recall-cloud-sync/recall-sync-local.mjs +406 -0
  49. package/vendor/recall-cloud-sync/recall-sync.mjs +1266 -0
  50. package/dist/chunk-QPR77YXP.js.map +0 -1
  51. package/dist/chunk-SYSSACWJ.js.map +0 -1
  52. package/dist/chunk-VRAG5V66.js.map +0 -1
  53. package/dist/chunk-ZF23OPYV.js.map +0 -1
  54. package/dist/dispatcher-5JVGZNWT.js +0 -22
  55. package/dist/ingest-NVYEOSVZ.js +0 -20
  56. package/dist/quality-4CG6U273.js +0 -25
  57. package/dist/retrieval-42CPYUDW.js +0 -15
  58. /package/dist/{chunk-Q2F7EQCA.js.map → chunk-22AJZ7UQ.js.map} +0 -0
  59. /package/dist/{chunk-GCMP2YYN.js.map → chunk-2COJXGP4.js.map} +0 -0
  60. /package/dist/{chunk-GDN44ZC7.js.map → chunk-FNIIUNW6.js.map} +0 -0
  61. /package/dist/{chunk-YELXEWKH.js.map → chunk-GK7OWVRQ.js.map} +0 -0
  62. /package/dist/{chunk-7UWVXXTU.js.map → chunk-KLERXJ47.js.map} +0 -0
  63. /package/dist/{chunk-THC7QOAK.js.map → chunk-KVZN35JF.js.map} +0 -0
  64. /package/dist/{chunk-SEXZABB2.js.map → chunk-Q22B7YDQ.js.map} +0 -0
  65. /package/dist/{chunk-EKFOHVHS.js.map → chunk-QQ6YHR7I.js.map} +0 -0
  66. /package/dist/{chunk-MLC3KO2O.js.map → chunk-RAQT2OBR.js.map} +0 -0
  67. /package/dist/{chunk-DVLQYARZ.js.map → chunk-UDLRBKC3.js.map} +0 -0
  68. /package/dist/{chunk-DOYTMHDI.js.map → chunk-VUVFQJWZ.js.map} +0 -0
  69. /package/dist/{chunk-LEOXFQJJ.js.map → chunk-XRKUJ5B4.js.map} +0 -0
  70. /package/dist/{chunk-DAW6FUGL.js.map → chunk-YIVOTIDF.js.map} +0 -0
  71. /package/dist/{cleanup-WJFE6IVP.js.map → cleanup-4TXIHTJT.js.map} +0 -0
  72. /package/dist/{codex-trust-3BFTJFRD.js.map → codex-trust-2JIY66CP.js.map} +0 -0
  73. /package/dist/{dispatcher-5JVGZNWT.js.map → dispatcher-O6NGADCQ.js.map} +0 -0
  74. /package/dist/{embeddings-H352GFKD.js.map → embeddings-AAS7NKGB.js.map} +0 -0
  75. /package/dist/{ingest-NVYEOSVZ.js.map → ingest-DW3AG4M5.js.map} +0 -0
  76. /package/dist/{keychain-A2Z7D7YE.js.map → keychain-SHRO7W6J.js.map} +0 -0
  77. /package/dist/{memory-value-M3TA7SEK.js.map → memory-value-R2C7ZSDF.js.map} +0 -0
  78. /package/dist/{provenance-CXU6LZK7.js.map → provenance-I5GIAP7N.js.map} +0 -0
  79. /package/dist/{quality-4CG6U273.js.map → quality-32MAXPNJ.js.map} +0 -0
  80. /package/dist/{retrieval-42CPYUDW.js.map → retrieval-RKYWWNWC.js.map} +0 -0
  81. /package/dist/{store-YCVWABSH.js.map → store-X2B6MRBH.js.map} +0 -0
  82. /package/dist/{tasks-4UL2FIAQ.js.map → tasks-H4NIS6QO.js.map} +0 -0
  83. /package/dist/{usage-HZ27RG53.js.map → usage-35HSDMNT.js.map} +0 -0
package/dist/daemon.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  computeQualityReport,
3
3
  listQualitySnapshots,
4
4
  recordQualitySnapshot
5
- } from "./chunk-DAW6FUGL.js";
5
+ } from "./chunk-YIVOTIDF.js";
6
6
  import {
7
7
  ensureDailyBackup,
8
8
  extractCodexSessionId,
@@ -23,16 +23,21 @@ import {
23
23
  runReliabilityVerdictCycle,
24
24
  toolOutcomeFromPayload,
25
25
  writeRepoContextArtifact
26
- } from "./chunk-ZF23OPYV.js";
27
- import "./chunk-YELXEWKH.js";
26
+ } from "./chunk-YIUBD27J.js";
27
+ import "./chunk-GK7OWVRQ.js";
28
28
  import {
29
29
  createRecallMcpServer
30
- } from "./chunk-QPR77YXP.js";
30
+ } from "./chunk-EY6HIDG2.js";
31
31
  import {
32
32
  graphQuery
33
- } from "./chunk-SEXZABB2.js";
33
+ } from "./chunk-Q22B7YDQ.js";
34
34
  import {
35
+ CloudError,
36
+ DEFAULT_CLOUD_API,
37
+ LEGACY_LAUNCHD_LABEL,
35
38
  bootstrapHistoryEmbeddings,
39
+ buildChildEnv,
40
+ buildEngineArgs,
36
41
  compileContext,
37
42
  compileContextHybrid,
38
43
  computeMetrics,
@@ -41,6 +46,7 @@ import {
41
46
  createPolicy,
42
47
  endEvalSession,
43
48
  endSessionLifecycle,
49
+ ensurePrivateDir,
44
50
  ensureRepoBootstrapped,
45
51
  evaluatePolicy,
46
52
  findHistorySnippetByRepoKind,
@@ -49,28 +55,40 @@ import {
49
55
  incrementEvalCounter,
50
56
  inferRepoSlugFromPath,
51
57
  initDb,
58
+ isCloudQueryEnabled,
52
59
  listActivityEvents,
53
60
  listActivitySessions,
54
61
  listHistorySnippets,
55
62
  listPendingApprovals,
56
63
  listPolicies,
64
+ loadCloudConfig,
65
+ normalizePassphrase,
66
+ normalizeSecret,
57
67
  pruneMemories,
68
+ readPrivatePassphrase,
69
+ readPrivateSecret,
58
70
  recordSessionLifecycleEvent,
59
71
  recordSignal,
72
+ removeFile,
60
73
  removeHistoryFtsRow,
61
74
  removeHistoryVecRow,
62
75
  requestApproval,
63
76
  resolveApproval,
77
+ resolveCloudPaths,
64
78
  runValueRetrievalEval,
79
+ saveCloudConfig,
65
80
  scanAndStore,
81
+ setCloudQueryEnabled,
66
82
  signalOutcomeFallback,
67
83
  startEvalSession,
68
84
  startSessionLifecycle,
69
85
  summarizeValueRetrievalEval,
70
86
  syncHistoryFtsIndex,
71
87
  updateHistorySnippet,
72
- verifyHistoryEmbeddings
73
- } from "./chunk-VRAG5V66.js";
88
+ validateApi,
89
+ verifyHistoryEmbeddings,
90
+ writePrivateFile
91
+ } from "./chunk-Q7254IPO.js";
74
92
  import {
75
93
  DEFAULT_ENQUEUE_CONFIG,
76
94
  autoResolveContradictions,
@@ -88,12 +106,12 @@ import {
88
106
  processReviewFeedback,
89
107
  resolveContradiction,
90
108
  runDeterministicCleanup
91
- } from "./chunk-EKFOHVHS.js";
92
- import "./chunk-MLC3KO2O.js";
93
- import "./chunk-LEOXFQJJ.js";
109
+ } from "./chunk-QQ6YHR7I.js";
110
+ import "./chunk-RAQT2OBR.js";
111
+ import "./chunk-XRKUJ5B4.js";
94
112
  import {
95
113
  Sentry
96
- } from "./chunk-Q2F7EQCA.js";
114
+ } from "./chunk-22AJZ7UQ.js";
97
115
  import {
98
116
  confirmMemory,
99
117
  createMemory,
@@ -110,9 +128,9 @@ import {
110
128
  rollbackMemory,
111
129
  safeIngestMemoryById,
112
130
  statusFromConfidence
113
- } from "./chunk-THC7QOAK.js";
114
- import "./chunk-DVLQYARZ.js";
115
- import "./chunk-DOYTMHDI.js";
131
+ } from "./chunk-KVZN35JF.js";
132
+ import "./chunk-UDLRBKC3.js";
133
+ import "./chunk-VUVFQJWZ.js";
116
134
  import {
117
135
  bootstrapEmbeddings,
118
136
  getEmbeddingModelInfo,
@@ -121,11 +139,11 @@ import {
121
139
  queueMemoryEmbeddingSync,
122
140
  rebuildEmbeddingIndexResponsive,
123
141
  verifyEmbeddings
124
- } from "./chunk-SYSSACWJ.js";
142
+ } from "./chunk-CSBXI3ET.js";
125
143
  import {
126
144
  hasProviderConfigured,
127
145
  init_keychain
128
- } from "./chunk-GDN44ZC7.js";
146
+ } from "./chunk-FNIIUNW6.js";
129
147
  import {
130
148
  clearGraph,
131
149
  countEntities,
@@ -136,7 +154,7 @@ import {
136
154
  listEntitiesForMemory,
137
155
  listMemoryIdsForEntity,
138
156
  neighborsOf
139
- } from "./chunk-7UWVXXTU.js";
157
+ } from "./chunk-KLERXJ47.js";
140
158
  import {
141
159
  activityEvents,
142
160
  eq,
@@ -146,11 +164,11 @@ import {
146
164
  implicitSignals,
147
165
  lt,
148
166
  memories
149
- } from "./chunk-GCMP2YYN.js";
167
+ } from "./chunk-2COJXGP4.js";
150
168
  import {
151
169
  define_RECALL_BUILD_INFO_default,
152
170
  init_define_RECALL_BUILD_INFO
153
- } from "./chunk-FYMMTODQ.js";
171
+ } from "./chunk-ZT67CYDS.js";
154
172
 
155
173
  // src/daemon.ts
156
174
  init_define_RECALL_BUILD_INFO();
@@ -194,12 +212,941 @@ function emit(name, payload) {
194
212
 
195
213
  // src/daemon.ts
196
214
  import { homedir } from "os";
197
- import { join as join3 } from "path";
198
215
 
199
- // src/graph/reconcile.ts
216
+ // src/cloud/service.ts
217
+ init_define_RECALL_BUILD_INFO();
218
+ import { hostname as hostname2 } from "os";
219
+ import { isAbsolute as isAbsolute2, relative } from "path";
220
+
221
+ // src/cloud/engine.ts
200
222
  init_define_RECALL_BUILD_INFO();
201
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
223
+ import { existsSync } from "fs";
202
224
  import { dirname, join } from "path";
225
+ import { fileURLToPath } from "url";
226
+ var ENGINE_DIR = join("vendor", "recall-cloud-sync");
227
+ function resolveEngineFiles(fromUrl = import.meta.url) {
228
+ const here = dirname(fileURLToPath(fromUrl));
229
+ for (const up of ["..", join("..", "..")]) {
230
+ const dir = join(here, up, ENGINE_DIR);
231
+ const engine = join(dir, "recall-sync.mjs");
232
+ const wrapper = join(dir, "managed-worker.mjs");
233
+ if (existsSync(engine) && existsSync(wrapper)) return { engine, wrapper };
234
+ }
235
+ throw new CloudError("The Recall Cloud sync engine is not bundled with this install", "engine-missing", 500);
236
+ }
237
+
238
+ // src/cloud/legacy.ts
239
+ init_define_RECALL_BUILD_INFO();
240
+ import { spawnSync } from "child_process";
241
+ import { chmodSync, copyFileSync, lstatSync, renameSync, rmSync } from "fs";
242
+ import { hostname } from "os";
243
+ import { basename, isAbsolute, join as join2, resolve } from "path";
244
+ var VALUE_FLAGS = /* @__PURE__ */ new Set([
245
+ "api",
246
+ "token-file",
247
+ "interval",
248
+ "device-id",
249
+ "db",
250
+ "device-alias",
251
+ "state-file",
252
+ "status",
253
+ "full-reconcile-interval",
254
+ "limit",
255
+ "rejected-retention-days"
256
+ ]);
257
+ var KNOWN_ENV = /* @__PURE__ */ new Set([
258
+ "RECALL_CLOUD_API",
259
+ "RECALL_CLOUD_DEVICE_ID",
260
+ "RECALL_CLOUD_E2EE_PASSPHRASE",
261
+ "RECALL_CLOUD_TOKEN",
262
+ "RECALL_DB",
263
+ "RECALL_REJECTED_RETENTION_DAYS"
264
+ ]);
265
+ function unsupported(message) {
266
+ return new CloudError(message, "legacy-unsupported", 409);
267
+ }
268
+ function expandHome(value, home) {
269
+ if (value === "~") return home;
270
+ if (value.startsWith("~/")) return join2(home, value.slice(2));
271
+ return value;
272
+ }
273
+ function parseInt10(value, min, label) {
274
+ if (!/^\d{1,9}$/.test(value) || Number(value) < min) {
275
+ throw unsupported(`The existing sync job has an invalid ${label}, so it was left unchanged`);
276
+ }
277
+ return Number(value);
278
+ }
279
+ function parseAliases(values) {
280
+ const aliases = {};
281
+ for (const entry of values) {
282
+ const at = entry.indexOf("=");
283
+ const from = at > 0 ? entry.slice(0, at).trim() : "";
284
+ const to = at > 0 ? entry.slice(at + 1).trim() : "";
285
+ if (!from || !to || from.includes(":") || to.includes(":")) {
286
+ throw unsupported("The existing sync job has an invalid device alias, so it was left unchanged");
287
+ }
288
+ aliases[from] = to;
289
+ }
290
+ return aliases;
291
+ }
292
+ function parseLegacyPlist(plist, paths, osHostname = hostname) {
293
+ const root = plist && typeof plist === "object" ? plist : {};
294
+ if (root.Label !== LEGACY_LAUNCHD_LABEL) {
295
+ throw unsupported("The existing sync job does not have the standard Recall Cloud Sync label, so it was left unchanged");
296
+ }
297
+ const argv = Array.isArray(root.ProgramArguments) && root.ProgramArguments.every((v) => typeof v === "string") ? root.ProgramArguments : null;
298
+ if (!argv || argv.length < 3 || basename(argv[1]) !== "recall-sync.mjs" || argv[2] !== "watch") {
299
+ throw unsupported("The existing sync job is not a standard Recall Cloud watch job, so it was left unchanged");
300
+ }
301
+ const flags = /* @__PURE__ */ new Map();
302
+ let e2ee = false;
303
+ for (let i = 3; i < argv.length; i++) {
304
+ const arg = argv[i];
305
+ const name = arg.startsWith("--") ? arg.slice(2) : "";
306
+ const label = /^[a-z0-9-]{1,40}$/.test(name) ? `--${name}` : "an unknown argument";
307
+ if (name === "e2ee") {
308
+ e2ee = true;
309
+ continue;
310
+ }
311
+ if (!VALUE_FLAGS.has(name)) {
312
+ throw unsupported(`The existing sync job uses an option Recall cannot migrate safely (${label}), so it was left unchanged`);
313
+ }
314
+ const value = argv[i + 1];
315
+ if (value === void 0 || value.startsWith("--")) {
316
+ throw unsupported(`The existing sync job is missing a value for ${label}, so it was left unchanged`);
317
+ }
318
+ const existing = flags.get(name) ?? [];
319
+ if (existing.length > 0 && name !== "device-alias") {
320
+ throw unsupported(`The existing sync job repeats ${label}, so it was left unchanged`);
321
+ }
322
+ flags.set(name, [...existing, value]);
323
+ i++;
324
+ }
325
+ const env = {};
326
+ if (root.EnvironmentVariables && typeof root.EnvironmentVariables === "object") {
327
+ for (const [key, value] of Object.entries(root.EnvironmentVariables)) {
328
+ if (typeof value !== "string") continue;
329
+ if ((key.startsWith("RECALL_CLOUD_") || key.startsWith("RECALL_")) && !KNOWN_ENV.has(key)) {
330
+ throw unsupported("The existing sync job sets an environment option Recall cannot migrate safely, so it was left unchanged");
331
+ }
332
+ env[key] = value;
333
+ }
334
+ }
335
+ const first = (name) => flags.get(name)?.[0];
336
+ const home = paths.home;
337
+ const legacyHome = env.HOME;
338
+ const homeDiffers = legacyHome !== void 0 && resolve(legacyHome) !== resolve(home);
339
+ const absolutePath = (value, fallback2, label) => {
340
+ const raw = value ?? fallback2;
341
+ const usesHome = value === void 0 || value === "~" || value.startsWith("~/");
342
+ if (usesHome && homeDiffers) {
343
+ throw unsupported(`The existing sync job runs with a different HOME, so its ${label} cannot be moved safely and it was left unchanged`);
344
+ }
345
+ const expanded = expandHome(raw, home);
346
+ if (!isAbsolute(expanded)) {
347
+ throw unsupported(`The existing sync job uses a relative ${label}, so it was left unchanged`);
348
+ }
349
+ return resolve(expanded);
350
+ };
351
+ const apiValue = first("api") ?? env.RECALL_CLOUD_API;
352
+ const tokenFile = first("token-file");
353
+ if (!apiValue) throw unsupported("The existing sync job has no API address, so it was left unchanged");
354
+ if (!tokenFile) {
355
+ throw unsupported("The existing sync job does not use a token file. Use Connect with a fresh token instead.");
356
+ }
357
+ let passphrase = null;
358
+ if (e2ee) {
359
+ passphrase = env.RECALL_CLOUD_E2EE_PASSPHRASE ?? null;
360
+ if (!passphrase) {
361
+ throw new CloudError(
362
+ "The existing sync job uses end-to-end encryption but its passphrase is not recoverable. Nothing was changed; reconnect with your passphrase instead.",
363
+ "encryption-required",
364
+ 409
365
+ );
366
+ }
367
+ }
368
+ const retention = first("rejected-retention-days") ?? env.RECALL_REJECTED_RETENTION_DAYS;
369
+ return {
370
+ api: validateApi(apiValue),
371
+ tokenFile: absolutePath(tokenFile, tokenFile, "token file"),
372
+ intervalSeconds: first("interval") ? parseInt10(first("interval"), 1, "interval") : 300,
373
+ deviceId: first("device-id") ?? env.RECALL_CLOUD_DEVICE_ID ?? env.HOSTNAME ?? osHostname(),
374
+ deviceAliases: parseAliases(flags.get("device-alias") ?? []),
375
+ dbPath: absolutePath(first("db") ?? env.RECALL_DB, join2(home, ".recall", "recall.db"), "database path"),
376
+ stateFile: absolutePath(first("state-file"), join2(home, ".config", "recall-cloud", "sync-state.json"), "sync state file"),
377
+ fullReconcileSeconds: first("full-reconcile-interval") ? parseInt10(first("full-reconcile-interval"), 1, "reconcile interval") : null,
378
+ statuses: first("status") ?? null,
379
+ limit: first("limit") ? parseInt10(first("limit"), 1, "limit") : null,
380
+ rejectedRetentionDays: retention != null ? parseInt10(retention, 0, "retention") : null,
381
+ e2ee,
382
+ passphrase
383
+ };
384
+ }
385
+ function defaultLaunchctl(args) {
386
+ const result = spawnSync("launchctl", args, { encoding: "utf8", timeout: 1e4 });
387
+ return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
388
+ }
389
+ function defaultReadPlist(plistPath) {
390
+ const stat = lstatSync(plistPath);
391
+ if (!stat.isFile() || stat.isSymbolicLink()) throw unsupported("The existing sync job file is not a regular file");
392
+ const result = spawnSync("/usr/bin/plutil", ["-convert", "json", "-o", "-", plistPath], {
393
+ encoding: "utf8",
394
+ timeout: 1e4,
395
+ maxBuffer: 1024 * 1024
396
+ });
397
+ if (result.status !== 0) throw unsupported("The existing sync job file could not be read");
398
+ return JSON.parse(result.stdout);
399
+ }
400
+ var LegacyLaunchd = class {
401
+ constructor(deps) {
402
+ this.deps = deps;
403
+ this.platform = deps.platform ?? process.platform;
404
+ this.launchctl = deps.launchctl ?? defaultLaunchctl;
405
+ this.readPlist = deps.readPlist ?? defaultReadPlist;
406
+ this.uid = deps.uid ?? (() => typeof process.getuid === "function" ? process.getuid() : 0);
407
+ this.sleep = deps.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
408
+ this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
409
+ }
410
+ deps;
411
+ platform;
412
+ launchctl;
413
+ readPlist;
414
+ uid;
415
+ sleep;
416
+ now;
417
+ get target() {
418
+ return `gui/${this.uid()}/${LEGACY_LAUNCHD_LABEL}`;
419
+ }
420
+ plistExists() {
421
+ if (this.platform !== "darwin") return false;
422
+ try {
423
+ lstatSync(this.deps.paths.legacyPlist);
424
+ return true;
425
+ } catch {
426
+ return false;
427
+ }
428
+ }
429
+ loadedState() {
430
+ if (this.platform !== "darwin") return "absent";
431
+ const result = this.launchctl(["print", this.target]);
432
+ if (result.status === 0) return "loaded";
433
+ if (result.status === 113 || /could not find service|not found/i.test(`${result.stderr}${result.stdout}`)) return "absent";
434
+ return "unknown";
435
+ }
436
+ readSettings() {
437
+ return parseLegacyPlist(this.readPlist(this.deps.paths.legacyPlist), this.deps.paths);
438
+ }
439
+ /** Boots the old job out, then requires launchd to prove it is gone. Fails closed otherwise. */
440
+ async bootoutAndProve() {
441
+ this.launchctl(["bootout", this.target]);
442
+ for (let attempt = 0; attempt < 3; attempt++) {
443
+ if (this.loadedState() === "absent") return;
444
+ await this.sleep(300);
445
+ }
446
+ throw new CloudError(
447
+ "macOS did not stop the old Recall Cloud Sync item (it may be blocked in Login Items & Extensions). Nothing was started, so there is no duplicate sync. Allow or remove the old item, then try again.",
448
+ "migration-blocked",
449
+ 409
450
+ );
451
+ }
452
+ /** Moves the old plist out of LaunchAgents (kept for rollback) so it cannot relaunch at login. */
453
+ retirePlist() {
454
+ const { legacyPlist, backupDir } = this.deps.paths;
455
+ const stamp = this.now().toISOString().replace(/[:.]/g, "-");
456
+ const backup = join2(backupDir, `${LEGACY_LAUNCHD_LABEL}.plist.${stamp}`);
457
+ try {
458
+ ensurePrivateDir(backupDir);
459
+ try {
460
+ renameSync(legacyPlist, backup);
461
+ } catch {
462
+ copyFileSync(legacyPlist, backup);
463
+ rmSync(legacyPlist, { force: true });
464
+ }
465
+ chmodSync(backup, 384);
466
+ return backup;
467
+ } catch {
468
+ throw new CloudError(
469
+ "The old sync job was stopped but its LaunchAgent file could not be moved aside, so cloud sync was not started.",
470
+ "migration-blocked",
471
+ 409
472
+ );
473
+ }
474
+ }
475
+ };
476
+
477
+ // src/cloud/state.ts
478
+ init_define_RECALL_BUILD_INFO();
479
+ import { createHash } from "crypto";
480
+ import { existsSync as existsSync2, readFileSync } from "fs";
481
+ import { resolve as resolve2 } from "path";
482
+ function engineStateKey(config) {
483
+ return createHash("sha256").update(`${config.api}\0${config.deviceId}\0${resolve2(config.dbPath)}`).digest("hex");
484
+ }
485
+ function requestFullReconcile(config) {
486
+ let state = null;
487
+ try {
488
+ if (!existsSync2(config.stateFile)) return false;
489
+ state = JSON.parse(readFileSync(config.stateFile, "utf8"));
490
+ } catch {
491
+ return false;
492
+ }
493
+ const entry = state?.entries?.[engineStateKey(config)];
494
+ if (!entry || typeof entry !== "object") return false;
495
+ entry.fullReconciledAt = null;
496
+ try {
497
+ writePrivateFile(config.stateFile, `${JSON.stringify(state, null, 2)}
498
+ `);
499
+ } catch {
500
+ throw new CloudError(
501
+ "Recall could not reset the sync position for the new token, so Connect was not completed. Nothing is syncing.",
502
+ "config-invalid",
503
+ 500
504
+ );
505
+ }
506
+ return true;
507
+ }
508
+
509
+ // src/cloud/worker.ts
510
+ init_define_RECALL_BUILD_INFO();
511
+ import { spawn as nodeSpawn } from "child_process";
512
+ function classifyEngineOutput(line) {
513
+ if (/failed (?:401|403)\b/i.test(line)) return "The cloud rejected this device's token";
514
+ if (/failed (?:408|425|429|5\d\d)\b/i.test(line)) return "The cloud is temporarily unavailable";
515
+ if (/failed \d{3}\b/i.test(line)) return "A cloud request failed";
516
+ if (/fetch failed|network error|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|aborted|timeout/i.test(line)) return "Network error while syncing";
517
+ if (/database is locked|SQLITE_BUSY/i.test(line)) return "The local database was busy";
518
+ if (/Recall DB not found/i.test(line)) return "The local Recall database was not found";
519
+ if (/e2ee|passphrase/i.test(line)) return "Encryption is not configured correctly";
520
+ if (/credential|token/i.test(line)) return "The sync credentials could not be used";
521
+ if (/sync error/i.test(line)) return "A sync cycle failed";
522
+ return null;
523
+ }
524
+ var CloudWorker = class {
525
+ spawnFn;
526
+ startTimeoutMs;
527
+ stopGraceMs;
528
+ stopDeadlineMs;
529
+ backoffMs;
530
+ maxRestarts;
531
+ restartWindowMs;
532
+ log;
533
+ child = null;
534
+ launch = null;
535
+ state = "stopped";
536
+ stopping = false;
537
+ stopFailed = false;
538
+ startedAt = null;
539
+ lastError = null;
540
+ lastSyncAt = null;
541
+ lastExit = null;
542
+ restarts = 0;
543
+ restartTimes = [];
544
+ startTimer = null;
545
+ backoffTimer = null;
546
+ waiters = [];
547
+ buffer = "";
548
+ constructor(options = {}) {
549
+ this.spawnFn = options.spawn ?? ((command, args, opts) => nodeSpawn(command, args, opts));
550
+ this.startTimeoutMs = options.startTimeoutMs ?? 2e4;
551
+ this.stopGraceMs = options.stopGraceMs ?? 3e3;
552
+ this.stopDeadlineMs = options.stopDeadlineMs ?? 2e3;
553
+ this.backoffMs = options.backoffMs ?? [2e3, 1e4, 3e4, 6e4];
554
+ this.maxRestarts = options.maxRestarts ?? 5;
555
+ this.restartWindowMs = options.restartWindowMs ?? 10 * 6e4;
556
+ this.log = options.log ?? (() => {
557
+ });
558
+ }
559
+ start(launch) {
560
+ if (this.child && this.stopFailed) {
561
+ throw new Error("The previous sync engine has not exited yet");
562
+ }
563
+ if (this.child || this.state === "backoff" || this.state === "starting" || this.state === "running") return;
564
+ this.launch = launch;
565
+ this.stopping = false;
566
+ this.restarts = 0;
567
+ this.restartTimes = [];
568
+ this.lastError = null;
569
+ this.lastSyncAt = null;
570
+ this.spawnChild();
571
+ }
572
+ /**
573
+ * Resolves only after the child has been observed to exit. If it does not exit
574
+ * within the bounded deadline, the child stays tracked (state "failed"), no
575
+ * replacement can start, and the promise rejects so callers do not report a
576
+ * disconnect that has not happened.
577
+ */
578
+ async stop() {
579
+ this.stopping = true;
580
+ this.clearTimers();
581
+ const child = this.child;
582
+ if (!child) {
583
+ this.state = "stopped";
584
+ this.stopFailed = false;
585
+ this.stopping = false;
586
+ return;
587
+ }
588
+ let release = () => {
589
+ };
590
+ const exited = new Promise((resolve4) => {
591
+ release = () => resolve4("exited");
592
+ this.waiters.push(release);
593
+ });
594
+ try {
595
+ if (child.connected) child.send?.({ type: "stop" });
596
+ } catch {
597
+ }
598
+ this.signal(child, "SIGTERM");
599
+ const killTimer = setTimeout(() => this.signal(child, "SIGKILL"), this.stopGraceMs);
600
+ let deadlineTimer;
601
+ const deadline = new Promise((resolve4) => {
602
+ deadlineTimer = setTimeout(() => resolve4("timeout"), this.stopGraceMs + this.stopDeadlineMs);
603
+ });
604
+ const outcome = await Promise.race([exited, deadline]);
605
+ clearTimeout(killTimer);
606
+ clearTimeout(deadlineTimer);
607
+ if (outcome === "timeout") {
608
+ this.waiters = this.waiters.filter((waiter) => waiter !== release);
609
+ this.state = "failed";
610
+ this.stopFailed = true;
611
+ this.lastError = "The sync engine did not stop";
612
+ throw new Error("The sync engine did not stop");
613
+ }
614
+ this.stopFailed = false;
615
+ this.stopping = false;
616
+ }
617
+ signal(child, signal) {
618
+ try {
619
+ child.kill(signal);
620
+ } catch {
621
+ }
622
+ }
623
+ /** Synchronous last resort for process 'exit' handlers. */
624
+ killSync() {
625
+ this.stopping = true;
626
+ this.clearTimers();
627
+ try {
628
+ this.child?.kill("SIGKILL");
629
+ } catch {
630
+ }
631
+ this.child = null;
632
+ this.state = "stopped";
633
+ }
634
+ status() {
635
+ return {
636
+ state: this.state,
637
+ pid: this.child?.pid ?? null,
638
+ startedAt: this.startedAt,
639
+ restarts: this.restarts,
640
+ lastError: this.lastError,
641
+ lastSyncAt: this.lastSyncAt,
642
+ lastExit: this.lastExit
643
+ };
644
+ }
645
+ spawnChild() {
646
+ const launch = this.launch;
647
+ if (!launch) return;
648
+ let child;
649
+ try {
650
+ child = this.spawnFn(launch.command, launch.args, {
651
+ env: launch.env,
652
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
653
+ windowsHide: true
654
+ });
655
+ } catch {
656
+ this.lastError = "The sync engine could not be started";
657
+ this.scheduleRestart();
658
+ return;
659
+ }
660
+ this.child = child;
661
+ this.state = "starting";
662
+ this.startedAt = (/* @__PURE__ */ new Date()).toISOString();
663
+ this.buffer = "";
664
+ child.stdout?.on("data", (chunk) => this.onOutput(chunk));
665
+ child.stderr?.on("data", (chunk) => this.onOutput(chunk));
666
+ child.on("error", () => {
667
+ this.lastError = "The sync engine could not be started";
668
+ if (child.pid === void 0) this.handleExit(child, null, null);
669
+ });
670
+ child.on("exit", (code, signal) => this.handleExit(child, code, signal));
671
+ this.startTimer = setTimeout(() => {
672
+ if (this.child === child && this.state === "starting") {
673
+ this.lastError = "The sync engine did not start in time";
674
+ child.kill("SIGKILL");
675
+ }
676
+ }, this.startTimeoutMs);
677
+ }
678
+ onOutput(chunk) {
679
+ this.buffer += chunk.toString("utf8");
680
+ const lines = this.buffer.split("\n");
681
+ this.buffer = (lines.pop() ?? "").slice(-4096);
682
+ for (const line of lines) {
683
+ if (line.includes("watch started")) {
684
+ if (this.state === "starting") this.state = "running";
685
+ if (this.startTimer) clearTimeout(this.startTimer);
686
+ this.startTimer = null;
687
+ continue;
688
+ }
689
+ if (/\bpull ok fetched=/.test(line)) {
690
+ this.lastSyncAt = (/* @__PURE__ */ new Date()).toISOString();
691
+ this.lastError = null;
692
+ continue;
693
+ }
694
+ const reason = classifyEngineOutput(line);
695
+ if (reason) this.lastError = reason;
696
+ }
697
+ }
698
+ handleExit(child, code, signal) {
699
+ if (this.child !== child) return;
700
+ this.child = null;
701
+ this.clearTimers();
702
+ this.lastExit = { code, signal: signal ?? null, at: (/* @__PURE__ */ new Date()).toISOString() };
703
+ if (this.stopping) {
704
+ this.state = "stopped";
705
+ this.stopFailed = false;
706
+ const waiters = this.waiters;
707
+ this.waiters = [];
708
+ for (const resolve4 of waiters) resolve4();
709
+ return;
710
+ }
711
+ this.scheduleRestart();
712
+ }
713
+ scheduleRestart() {
714
+ const now = Date.now();
715
+ this.restartTimes = [...this.restartTimes.filter((t) => now - t < this.restartWindowMs), now];
716
+ if (this.restartTimes.length > this.maxRestarts) {
717
+ this.state = "failed";
718
+ this.lastError = this.lastError ?? "The sync engine keeps stopping";
719
+ this.log("[recall-cloud] sync engine stopped repeatedly; giving up until reconnected");
720
+ return;
721
+ }
722
+ this.restarts += 1;
723
+ this.state = "backoff";
724
+ const delay = this.backoffMs[Math.min(this.restarts - 1, this.backoffMs.length - 1)] ?? 6e4;
725
+ this.backoffTimer = setTimeout(() => {
726
+ this.backoffTimer = null;
727
+ if (!this.stopping && !this.child) this.spawnChild();
728
+ }, delay);
729
+ }
730
+ clearTimers() {
731
+ if (this.startTimer) clearTimeout(this.startTimer);
732
+ if (this.backoffTimer) clearTimeout(this.backoffTimer);
733
+ this.startTimer = null;
734
+ this.backoffTimer = null;
735
+ }
736
+ };
737
+
738
+ // src/cloud/service.ts
739
+ function safeMessage(error) {
740
+ return error instanceof CloudError ? error.message : "Cloud sync could not be started";
741
+ }
742
+ function isInside(directory, file) {
743
+ const rel = relative(directory, file);
744
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
745
+ }
746
+ var CloudService = class {
747
+ paths;
748
+ env;
749
+ worker;
750
+ legacy;
751
+ engineFn;
752
+ nodePath;
753
+ osHostname;
754
+ now;
755
+ log;
756
+ chain = Promise.resolve();
757
+ startError = null;
758
+ constructor(deps = {}) {
759
+ this.env = deps.env ?? process.env;
760
+ this.paths = deps.paths ?? resolveCloudPaths(this.env);
761
+ this.log = deps.log ?? (() => {
762
+ });
763
+ this.worker = deps.worker ?? new CloudWorker({ log: this.log });
764
+ this.legacy = deps.legacy ?? new LegacyLaunchd({ paths: this.paths });
765
+ this.engineFn = deps.engine ?? (() => resolveEngineFiles());
766
+ this.nodePath = deps.nodePath ?? process.execPath;
767
+ this.osHostname = deps.osHostname ?? hostname2;
768
+ this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
769
+ }
770
+ /** The Mac App Store edition never syncs to the cloud. */
771
+ available() {
772
+ return this.env.RECALL_DISTRIBUTION !== "mac-app-store";
773
+ }
774
+ status() {
775
+ const available = this.available();
776
+ let config = null;
777
+ let error = null;
778
+ if (available) {
779
+ try {
780
+ config = loadCloudConfig(this.paths);
781
+ } catch (e) {
782
+ error = safeMessage(e);
783
+ }
784
+ }
785
+ const worker = this.worker.status();
786
+ const detected = available && this.legacy.plistExists();
787
+ const loadedState = detected ? this.legacy.loadedState() : "absent";
788
+ const loaded = loadedState === "loaded";
789
+ const unknown = loadedState === "unknown";
790
+ let state;
791
+ if (!available) state = "unavailable";
792
+ else if (error) state = "failed";
793
+ else if (config?.migrationPending) state = "migration-pending";
794
+ else if (!config || !config.enabled) state = "disconnected";
795
+ else if (worker.state === "failed" || worker.state === "stopped" && this.startError) state = "failed";
796
+ else state = worker.state;
797
+ if (state === "failed" && !error) error = this.startError ?? worker.lastError;
798
+ else if (state === "backoff" || state === "running" || state === "starting") error = worker.lastError;
799
+ return {
800
+ available,
801
+ state,
802
+ enabled: Boolean(config?.enabled),
803
+ worker: { pid: worker.pid, startedAt: worker.startedAt, restarts: worker.restarts, lastExit: worker.lastExit, lastSyncAt: worker.lastSyncAt },
804
+ config: config ? {
805
+ api: config.api,
806
+ deviceId: config.deviceId,
807
+ intervalSeconds: config.intervalSeconds,
808
+ e2ee: config.e2ee,
809
+ migratedFrom: config.migratedFrom,
810
+ optInAt: config.optInAt,
811
+ queryEnrichment: isCloudQueryEnabled(config, this.env)
812
+ } : null,
813
+ legacy: { detected, loaded, unknown, canMigrate: available && detected && !config?.enabled },
814
+ error
815
+ };
816
+ }
817
+ setQueryEnrichment(enabled) {
818
+ return this.exclusive(async () => {
819
+ if (typeof enabled !== "boolean") throw new CloudError("Online retrieval enabled must be a boolean", "invalid");
820
+ setCloudQueryEnabled(enabled, this.env, this.paths);
821
+ return this.status();
822
+ });
823
+ }
824
+ /** Called once when the daemon is listening. No config, or disabled, means a no-op. */
825
+ startIfEnabled() {
826
+ return this.exclusive(async () => {
827
+ if (!this.available()) return;
828
+ let config;
829
+ try {
830
+ config = loadCloudConfig(this.paths);
831
+ } catch (e) {
832
+ this.startError = safeMessage(e);
833
+ return;
834
+ }
835
+ if (!config || !config.enabled) return;
836
+ this.launchSafely(config);
837
+ });
838
+ }
839
+ connect(input) {
840
+ return this.exclusive(async () => {
841
+ this.assertAvailable();
842
+ if (input.optIn !== true) {
843
+ throw new CloudError("Confirm that you want to sync this Mac to Recall Cloud first", "opt-in-required");
844
+ }
845
+ const engine = this.engineFn();
846
+ void engine;
847
+ const token = normalizeSecret(String(input.token ?? "").trim(), "token");
848
+ const typedPassphrase = input.e2eePassphrase == null || input.e2eePassphrase === "" ? null : normalizePassphrase(input.e2eePassphrase);
849
+ const existing = loadCloudConfig(this.paths);
850
+ this.assertNoLegacy();
851
+ let passphrase = typedPassphrase;
852
+ if (!passphrase && existing?.e2ee) {
853
+ try {
854
+ passphrase = existing.passphraseFile ? readPrivatePassphrase(existing.passphraseFile) : null;
855
+ } catch {
856
+ passphrase = null;
857
+ }
858
+ if (!passphrase) {
859
+ throw new CloudError(
860
+ "This Mac previously used end-to-end encryption. Enter the same passphrase to reconnect; Recall will not sync unencrypted.",
861
+ "encryption-required",
862
+ 409
863
+ );
864
+ }
865
+ }
866
+ const api = validateApi(input.api ?? existing?.api ?? DEFAULT_CLOUD_API);
867
+ const deviceId = String(input.deviceId ?? existing?.deviceId ?? this.defaultDeviceId()).trim();
868
+ if (!deviceId || deviceId.includes(":") || deviceId.length > 200) {
869
+ throw new CloudError("Invalid device name", "invalid");
870
+ }
871
+ await this.stopWorker();
872
+ if (existing?.enabled) saveCloudConfig(this.paths, { ...existing, enabled: false });
873
+ ensurePrivateDir(this.paths.cloudDir);
874
+ writePrivateFile(this.paths.tokenFile, token);
875
+ if (passphrase) writePrivateFile(this.paths.passphraseFile, passphrase);
876
+ const config = {
877
+ version: 1,
878
+ enabled: true,
879
+ ...existing?.queryEnrichment === void 0 ? {} : {
880
+ queryEnrichment: existing.queryEnrichment
881
+ },
882
+ optInAt: this.now().toISOString(),
883
+ api,
884
+ deviceId,
885
+ deviceAliases: existing?.deviceAliases ?? {},
886
+ intervalSeconds: existing?.intervalSeconds ?? 300,
887
+ fullReconcileSeconds: existing?.fullReconcileSeconds ?? null,
888
+ statuses: existing?.statuses ?? null,
889
+ limit: existing?.limit ?? null,
890
+ rejectedRetentionDays: existing?.rejectedRetentionDays ?? null,
891
+ dbPath: existing?.dbPath ?? this.paths.dbFile,
892
+ stateFile: existing?.stateFile ?? this.paths.stateFile,
893
+ tokenFile: this.paths.tokenFile,
894
+ e2ee: passphrase !== null,
895
+ passphraseFile: passphrase ? this.paths.passphraseFile : null,
896
+ migratedFrom: existing?.migratedFrom ?? null,
897
+ migrationPending: false
898
+ };
899
+ requestFullReconcile(config);
900
+ saveCloudConfig(this.paths, config);
901
+ this.launchSafely(config);
902
+ return this.status();
903
+ });
904
+ }
905
+ /** Stops the worker first and reports success only once the child has exited. */
906
+ disconnect() {
907
+ return this.exclusive(async () => {
908
+ await this.stopWorker();
909
+ this.startError = null;
910
+ let existing = null;
911
+ try {
912
+ existing = loadCloudConfig(this.paths);
913
+ } catch {
914
+ existing = null;
915
+ }
916
+ if (existing) {
917
+ saveCloudConfig(this.paths, { ...existing, enabled: false, migrationPending: false });
918
+ const { cloudDir } = this.paths;
919
+ if (isInside(cloudDir, existing.tokenFile) && !this.legacy.plistExists()) removeFile(existing.tokenFile);
920
+ if (existing.passphraseFile && isInside(cloudDir, existing.passphraseFile)) removeFile(existing.passphraseFile);
921
+ }
922
+ return this.status();
923
+ });
924
+ }
925
+ /**
926
+ * Explicit user action only. Stages the new config disabled, stops the legacy
927
+ * job and requires launchd to prove it is gone, retires its plist, and only
928
+ * then enables and starts the in-daemon worker. Any failure leaves the worker off.
929
+ */
930
+ migrateLegacy(input) {
931
+ return this.exclusive(async () => {
932
+ this.assertAvailable();
933
+ if (input.optIn !== true) {
934
+ throw new CloudError("Confirm that you want to move sync into Recall first", "opt-in-required");
935
+ }
936
+ this.engineFn();
937
+ if (!this.legacy.plistExists()) {
938
+ throw new CloudError("No existing Recall Cloud Sync job was found on this Mac", "legacy-missing", 404);
939
+ }
940
+ await this.stopWorker();
941
+ const legacy = this.legacy.readSettings();
942
+ readPrivateSecret(legacy.tokenFile, "token");
943
+ let passphraseFile = null;
944
+ if (legacy.e2ee && legacy.passphrase) {
945
+ ensurePrivateDir(this.paths.cloudDir);
946
+ writePrivateFile(this.paths.passphraseFile, normalizePassphrase(legacy.passphrase));
947
+ passphraseFile = this.paths.passphraseFile;
948
+ }
949
+ const staged = {
950
+ version: 1,
951
+ enabled: false,
952
+ optInAt: null,
953
+ api: legacy.api,
954
+ deviceId: legacy.deviceId,
955
+ deviceAliases: legacy.deviceAliases,
956
+ intervalSeconds: legacy.intervalSeconds,
957
+ fullReconcileSeconds: legacy.fullReconcileSeconds,
958
+ statuses: legacy.statuses,
959
+ limit: legacy.limit,
960
+ rejectedRetentionDays: legacy.rejectedRetentionDays,
961
+ dbPath: legacy.dbPath,
962
+ stateFile: legacy.stateFile,
963
+ tokenFile: legacy.tokenFile,
964
+ e2ee: legacy.e2ee,
965
+ passphraseFile,
966
+ migratedFrom: "legacy-launchd",
967
+ migrationPending: true
968
+ };
969
+ saveCloudConfig(this.paths, staged);
970
+ await this.legacy.bootoutAndProve();
971
+ this.legacy.retirePlist();
972
+ const final = { ...staged, enabled: true, optInAt: this.now().toISOString(), migrationPending: false };
973
+ saveCloudConfig(this.paths, final);
974
+ this.launchSafely(final);
975
+ return this.status();
976
+ });
977
+ }
978
+ async shutdown() {
979
+ await this.exclusive(async () => {
980
+ try {
981
+ await this.worker.stop();
982
+ } catch {
983
+ this.worker.killSync();
984
+ }
985
+ });
986
+ }
987
+ /** Synchronous last resort for the process 'exit' event. */
988
+ killSync() {
989
+ this.worker.killSync();
990
+ }
991
+ launchSafely(config) {
992
+ try {
993
+ this.startError = null;
994
+ this.launch(config);
995
+ } catch (e) {
996
+ this.startError = safeMessage(e);
997
+ this.log(`[recall-cloud] not started: ${this.startError}`);
998
+ }
999
+ }
1000
+ launch(config) {
1001
+ const engine = this.engineFn();
1002
+ this.assertNoLegacy();
1003
+ readPrivateSecret(config.tokenFile, "token");
1004
+ let passphrase = null;
1005
+ if (config.e2ee) {
1006
+ try {
1007
+ passphrase = readPrivatePassphrase(config.passphraseFile ?? "");
1008
+ } catch {
1009
+ throw new CloudError(
1010
+ "End-to-end encryption is on but its passphrase is unavailable, so sync was not started",
1011
+ "encryption-required",
1012
+ 409
1013
+ );
1014
+ }
1015
+ }
1016
+ this.worker.start({
1017
+ command: this.nodePath,
1018
+ args: [engine.wrapper, ...buildEngineArgs(config, engine.engine)],
1019
+ env: buildChildEnv(this.env, passphrase)
1020
+ });
1021
+ }
1022
+ /** Refuses to run beside the old separate job, so uploads can never be duplicated. */
1023
+ assertNoLegacy() {
1024
+ if (this.legacy.plistExists()) {
1025
+ throw new CloudError(
1026
+ "The old Recall Cloud Sync job is still installed. Use Move sync into Recall first.",
1027
+ "legacy-active",
1028
+ 409
1029
+ );
1030
+ }
1031
+ const loaded = this.legacy.loadedState();
1032
+ if (loaded === "loaded") {
1033
+ throw new CloudError(
1034
+ "The old Recall Cloud Sync job is still running. Use Move sync into Recall first.",
1035
+ "legacy-active",
1036
+ 409
1037
+ );
1038
+ }
1039
+ if (loaded === "unknown") {
1040
+ throw new CloudError(
1041
+ "Recall could not confirm that the old Recall Cloud Sync job is stopped, so sync was not started. Try again.",
1042
+ "legacy-active",
1043
+ 409
1044
+ );
1045
+ }
1046
+ }
1047
+ assertAvailable() {
1048
+ if (!this.available()) {
1049
+ throw new CloudError("Recall Cloud sync is not available in this edition", "unavailable", 403);
1050
+ }
1051
+ }
1052
+ async stopWorker() {
1053
+ try {
1054
+ await this.worker.stop();
1055
+ } catch {
1056
+ throw new CloudError("The sync process did not stop. Nothing was changed; try again.", "unavailable", 503);
1057
+ }
1058
+ }
1059
+ defaultDeviceId() {
1060
+ return this.env.RECALL_CLOUD_DEVICE_ID ?? this.env.HOSTNAME ?? this.osHostname() ?? "local-device";
1061
+ }
1062
+ exclusive(fn) {
1063
+ const run = this.chain.then(fn, fn);
1064
+ this.chain = run.catch(() => void 0);
1065
+ return run;
1066
+ }
1067
+ };
1068
+
1069
+ // src/cloud/routes.ts
1070
+ init_define_RECALL_BUILD_INFO();
1071
+
1072
+ // src/daemon/body.ts
1073
+ init_define_RECALL_BUILD_INFO();
1074
+ var MAX_DAEMON_BODY_BYTES = 1024 * 1024;
1075
+ var JsonBodyError = class extends Error {
1076
+ constructor(message, status) {
1077
+ super(message);
1078
+ this.status = status;
1079
+ this.name = "JsonBodyError";
1080
+ }
1081
+ status;
1082
+ };
1083
+ async function parseJsonBody(req, maxBytes = MAX_DAEMON_BODY_BYTES) {
1084
+ const chunks = [];
1085
+ let total = 0;
1086
+ let tooLarge = false;
1087
+ for await (const chunk of req) {
1088
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1089
+ total += bytes.byteLength;
1090
+ if (total > maxBytes) {
1091
+ tooLarge = true;
1092
+ chunks.length = 0;
1093
+ continue;
1094
+ }
1095
+ if (!tooLarge) chunks.push(bytes);
1096
+ }
1097
+ if (tooLarge) {
1098
+ throw new JsonBodyError("request body too large", 413);
1099
+ }
1100
+ if (total === 0) return {};
1101
+ try {
1102
+ return JSON.parse(Buffer.concat(chunks).toString("utf-8"));
1103
+ } catch {
1104
+ throw new JsonBodyError("invalid JSON body", 400);
1105
+ }
1106
+ }
1107
+
1108
+ // src/cloud/routes.ts
1109
+ var MAX_CLOUD_BODY_BYTES = 16 * 1024;
1110
+ function send(res, status, data) {
1111
+ res.statusCode = status;
1112
+ res.setHeader("Content-Type", "application/json");
1113
+ res.end(JSON.stringify(data));
1114
+ }
1115
+ async function handleCloudRoute(service, req, res, path, method) {
1116
+ if (!path.startsWith("/cloud/")) return false;
1117
+ try {
1118
+ if (path === "/cloud/status" && method === "GET") {
1119
+ send(res, 200, service.status());
1120
+ return true;
1121
+ }
1122
+ if (method !== "POST" || !["/cloud/connect", "/cloud/disconnect", "/cloud/migrate", "/cloud/query"].includes(path)) {
1123
+ return false;
1124
+ }
1125
+ const body = await parseJsonBody(req, MAX_CLOUD_BODY_BYTES);
1126
+ const input = body && typeof body === "object" && !Array.isArray(body) ? body : {};
1127
+ if (path === "/cloud/connect") send(res, 200, await service.connect(input));
1128
+ else if (path === "/cloud/migrate") send(res, 200, await service.migrateLegacy(input));
1129
+ else if (path === "/cloud/query") send(res, 200, await service.setQueryEnrichment(input.enabled));
1130
+ else send(res, 200, await service.disconnect());
1131
+ return true;
1132
+ } catch (error) {
1133
+ if (error instanceof JsonBodyError) throw error;
1134
+ if (error instanceof CloudError) {
1135
+ send(res, error.status, { error: error.message, code: error.code });
1136
+ return true;
1137
+ }
1138
+ send(res, 500, { error: "Cloud sync request failed", code: "internal" });
1139
+ return true;
1140
+ }
1141
+ }
1142
+
1143
+ // src/daemon.ts
1144
+ import { join as join5 } from "path";
1145
+
1146
+ // src/graph/reconcile.ts
1147
+ init_define_RECALL_BUILD_INFO();
1148
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
1149
+ import { dirname as dirname2, join as join3 } from "path";
203
1150
  var GRAPH_EXTRACTOR_VERSION = 2;
204
1151
  function reconcileGraph(db2) {
205
1152
  clearGraph(db2);
@@ -214,7 +1161,7 @@ function reconcileGraph(db2) {
214
1161
  return { memories: rows.length, entity_touches: entityTouches, relation_touches: relationTouches };
215
1162
  }
216
1163
  function reconcileGraphIfStale(db2, dataDir) {
217
- const markerPath = join(dataDir, ".graph-extractor-version");
1164
+ const markerPath = join3(dataDir, ".graph-extractor-version");
218
1165
  if (readMarker(markerPath) >= GRAPH_EXTRACTOR_VERSION) return null;
219
1166
  const result = reconcileGraph(db2);
220
1167
  writeMarker(markerPath, GRAPH_EXTRACTOR_VERSION);
@@ -222,8 +1169,8 @@ function reconcileGraphIfStale(db2, dataDir) {
222
1169
  }
223
1170
  function readMarker(path) {
224
1171
  try {
225
- if (!existsSync(path)) return 0;
226
- const parsed = parseInt(readFileSync(path, "utf8").trim(), 10);
1172
+ if (!existsSync3(path)) return 0;
1173
+ const parsed = parseInt(readFileSync2(path, "utf8").trim(), 10);
227
1174
  return Number.isFinite(parsed) ? parsed : 0;
228
1175
  } catch {
229
1176
  return 0;
@@ -231,7 +1178,7 @@ function readMarker(path) {
231
1178
  }
232
1179
  function writeMarker(path, version) {
233
1180
  try {
234
- mkdirSync(dirname(path), { recursive: true });
1181
+ mkdirSync(dirname2(path), { recursive: true });
235
1182
  writeFileSync(path, `${version}
236
1183
  `, "utf8");
237
1184
  } catch {
@@ -241,13 +1188,13 @@ function writeMarker(path, version) {
241
1188
  // src/webui/server.ts
242
1189
  init_define_RECALL_BUILD_INFO();
243
1190
  import { createServer } from "http";
244
- import { createReadStream, existsSync as existsSync2, readFileSync as readFileSync2, statSync } from "fs";
245
- import { extname, join as join2, normalize, resolve, sep } from "path";
246
- import { fileURLToPath } from "url";
1191
+ import { createReadStream, existsSync as existsSync4, readFileSync as readFileSync3, statSync } from "fs";
1192
+ import { extname, join as join4, normalize, resolve as resolve3, sep } from "path";
1193
+ import { fileURLToPath as fileURLToPath2 } from "url";
247
1194
 
248
1195
  // src/webui/ws.ts
249
1196
  init_define_RECALL_BUILD_INFO();
250
- import { createHash } from "crypto";
1197
+ import { createHash as createHash2 } from "crypto";
251
1198
  var WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
252
1199
  var clients = /* @__PURE__ */ new Set();
253
1200
  var pingTimer = null;
@@ -266,7 +1213,7 @@ function handleUpgrade(req, socket) {
266
1213
  socket.destroy();
267
1214
  return;
268
1215
  }
269
- const accept = createHash("sha1").update(key + WS_GUID).digest("base64");
1216
+ const accept = createHash2("sha1").update(key + WS_GUID).digest("base64");
270
1217
  socket.write(
271
1218
  [
272
1219
  "HTTP/1.1 101 Switching Protocols",
@@ -405,17 +1352,17 @@ function serializeLifecycle(operation) {
405
1352
  return result;
406
1353
  }
407
1354
  function defaultDistDir() {
408
- const here = fileURLToPath(new URL(".", import.meta.url));
1355
+ const here = fileURLToPath2(new URL(".", import.meta.url));
409
1356
  let dir = here;
410
1357
  for (let i = 0; i < 8; i++) {
411
- if (existsSync2(join2(dir, "package.json"))) {
412
- return join2(dir, "dist", "webui");
1358
+ if (existsSync4(join4(dir, "package.json"))) {
1359
+ return join4(dir, "dist", "webui");
413
1360
  }
414
- const parent = resolve(dir, "..");
1361
+ const parent = resolve3(dir, "..");
415
1362
  if (parent === dir) break;
416
1363
  dir = parent;
417
1364
  }
418
- return join2(here, "..", "..", "dist", "webui");
1365
+ return join4(here, "..", "..", "dist", "webui");
419
1366
  }
420
1367
  function getStatus() {
421
1368
  if (!active) {
@@ -427,7 +1374,7 @@ function getStatus() {
427
1374
  url: null,
428
1375
  client_count: 0,
429
1376
  dist_dir: distDir,
430
- dist_exists: existsSync2(distDir),
1377
+ dist_exists: existsSync4(distDir),
431
1378
  started_at: null
432
1379
  };
433
1380
  }
@@ -438,7 +1385,7 @@ function getStatus() {
438
1385
  url: `http://${active.host}:${active.port}`,
439
1386
  client_count: clientCount(),
440
1387
  dist_dir: active.distDir,
441
- dist_exists: existsSync2(active.distDir),
1388
+ dist_exists: existsSync4(active.distDir),
442
1389
  started_at: active.startedAt
443
1390
  };
444
1391
  }
@@ -458,11 +1405,11 @@ async function startListener(options) {
458
1405
  socket.destroy();
459
1406
  }
460
1407
  });
461
- await new Promise((resolve2, reject) => {
1408
+ await new Promise((resolve4, reject) => {
462
1409
  server2.once("error", reject);
463
1410
  server2.listen(port, host, () => {
464
1411
  server2.off("error", reject);
465
- resolve2();
1412
+ resolve4();
466
1413
  });
467
1414
  });
468
1415
  active = { server: server2, port, host, distDir, startedAt: (/* @__PURE__ */ new Date()).toISOString() };
@@ -476,8 +1423,8 @@ async function stopListener() {
476
1423
  const a = active;
477
1424
  active = null;
478
1425
  shutdown();
479
- await new Promise((resolve2) => {
480
- a.server.close(() => resolve2());
1426
+ await new Promise((resolve4) => {
1427
+ a.server.close(() => resolve4());
481
1428
  a.server.closeAllConnections();
482
1429
  });
483
1430
  return getStatus();
@@ -511,15 +1458,15 @@ function handleHttp(req, res, distDir) {
511
1458
  res.end();
512
1459
  return;
513
1460
  }
514
- const relative = decoded === "/" ? "index.html" : decoded.replace(/^\/+/, "");
515
- const fullPath = normalize(join2(distDir, relative));
1461
+ const relative2 = decoded === "/" ? "index.html" : decoded.replace(/^\/+/, "");
1462
+ const fullPath = normalize(join4(distDir, relative2));
516
1463
  if (!fullPath.startsWith(distDir + sep) && fullPath !== distDir) {
517
1464
  res.statusCode = 403;
518
1465
  res.end();
519
1466
  return;
520
1467
  }
521
1468
  if (!isReadableFileCandidate(fullPath)) {
522
- const indexPath = join2(distDir, "index.html");
1469
+ const indexPath = join4(distDir, "index.html");
523
1470
  if (isReadableFileCandidate(indexPath)) {
524
1471
  serveFile(res, indexPath, req.method === "HEAD");
525
1472
  } else {
@@ -557,7 +1504,7 @@ function serveFile(res, file, head = false) {
557
1504
  const port = Number(process.env.RECALL_PORT);
558
1505
  if (Number.isInteger(port) && port > 0 && port <= 65535) {
559
1506
  try {
560
- const html = readFileSync2(file, "utf8");
1507
+ const html = readFileSync3(file, "utf8");
561
1508
  const meta = `<meta name="recall-daemon-url" content="http://127.0.0.1:${port}">`;
562
1509
  res.end(html.replace(/<head(?:\s[^>]*)?>/i, (head2) => head2 + meta));
563
1510
  } catch {
@@ -603,7 +1550,7 @@ function escapeHtml(s) {
603
1550
 
604
1551
  // src/daemon.ts
605
1552
  import { execFile, spawn } from "child_process";
606
- import { fileURLToPath as fileURLToPath2 } from "url";
1553
+ import { fileURLToPath as fileURLToPath3 } from "url";
607
1554
 
608
1555
  // src/maintenance/lifecycle.ts
609
1556
  init_define_RECALL_BUILD_INFO();
@@ -1229,42 +2176,6 @@ function deny(res) {
1229
2176
  res.end(JSON.stringify({ error: "local request required" }));
1230
2177
  }
1231
2178
 
1232
- // src/daemon/body.ts
1233
- init_define_RECALL_BUILD_INFO();
1234
- var MAX_DAEMON_BODY_BYTES = 1024 * 1024;
1235
- var JsonBodyError = class extends Error {
1236
- constructor(message, status) {
1237
- super(message);
1238
- this.status = status;
1239
- this.name = "JsonBodyError";
1240
- }
1241
- status;
1242
- };
1243
- async function parseJsonBody(req, maxBytes = MAX_DAEMON_BODY_BYTES) {
1244
- const chunks = [];
1245
- let total = 0;
1246
- let tooLarge = false;
1247
- for await (const chunk of req) {
1248
- const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1249
- total += bytes.byteLength;
1250
- if (total > maxBytes) {
1251
- tooLarge = true;
1252
- chunks.length = 0;
1253
- continue;
1254
- }
1255
- if (!tooLarge) chunks.push(bytes);
1256
- }
1257
- if (tooLarge) {
1258
- throw new JsonBodyError("request body too large", 413);
1259
- }
1260
- if (total === 0) return {};
1261
- try {
1262
- return JSON.parse(Buffer.concat(chunks).toString("utf-8"));
1263
- } catch {
1264
- throw new JsonBodyError("invalid JSON body", 400);
1265
- }
1266
- }
1267
-
1268
2179
  // src/runtime/build.ts
1269
2180
  init_define_RECALL_BUILD_INFO();
1270
2181
  var fallback = {
@@ -1732,10 +2643,10 @@ function scheduleReliabilityVerdictLoop() {
1732
2643
  timer.unref?.();
1733
2644
  }
1734
2645
  function runReliabilityProbeSubprocess(realEmbeddings) {
1735
- const cliPath = fileURLToPath2(new URL("./cli.js", import.meta.url));
2646
+ const cliPath = fileURLToPath3(new URL("./cli.js", import.meta.url));
1736
2647
  const args = [cliPath, "reliability", "--probe"];
1737
2648
  if (realEmbeddings) args.push("--real-embeddings");
1738
- return new Promise((resolve2, reject) => {
2649
+ return new Promise((resolve4, reject) => {
1739
2650
  execFile(process.execPath, args, {
1740
2651
  env: process.env,
1741
2652
  timeout: 3e5,
@@ -1750,13 +2661,14 @@ function runReliabilityProbeSubprocess(realEmbeddings) {
1750
2661
  if (typeof parsed.ok !== "boolean" || typeof parsed.database_integrity !== "boolean") {
1751
2662
  throw new Error("missing reliability probe fields");
1752
2663
  }
1753
- resolve2(parsed);
2664
+ resolve4(parsed);
1754
2665
  } catch {
1755
2666
  reject(new Error("Reliability probe process returned invalid JSON"));
1756
2667
  }
1757
2668
  });
1758
2669
  });
1759
2670
  }
2671
+ var cloudService = new CloudService({ log: (message) => console.log(message) });
1760
2672
  var server = createServer2(async (req, res) => {
1761
2673
  const url = new URL(req.url ?? "/", `http://localhost:${PORT}`);
1762
2674
  const path = url.pathname;
@@ -1773,7 +2685,7 @@ var server = createServer2(async (req, res) => {
1773
2685
  }
1774
2686
  res.setHeader("Content-Type", "application/json");
1775
2687
  if (path === "/health" && method === "GET") {
1776
- return send(res, 200, {
2688
+ return send2(res, 200, {
1777
2689
  status: "ok",
1778
2690
  version: pkg.version,
1779
2691
  instance_id: process.env.RECALL_INSTANCE_ID ?? null,
@@ -1786,25 +2698,25 @@ var server = createServer2(async (req, res) => {
1786
2698
  });
1787
2699
  }
1788
2700
  if (path === "/doctor" && method === "GET") {
1789
- return send(res, 200, {
2701
+ return send2(res, 200, {
1790
2702
  version: pkg.version,
1791
2703
  ...getDoctorStatusReport()
1792
2704
  });
1793
2705
  }
1794
2706
  if (path === "/update" && method === "GET") {
1795
2707
  if (process.env.RECALL_DISTRIBUTION === "mac-app-store") {
1796
- return send(res, 200, {
2708
+ return send2(res, 200, {
1797
2709
  current_version: pkg.version,
1798
2710
  update_available: false,
1799
2711
  managed_by: "mac-app-store"
1800
2712
  });
1801
2713
  }
1802
- return send(res, 200, await releaseChecker.check(pkg.version, url.searchParams.get("refresh") === "1"));
2714
+ return send2(res, 200, await releaseChecker.check(pkg.version, url.searchParams.get("refresh") === "1"));
1803
2715
  }
1804
2716
  if (path === "/store/memory" && method === "POST" && process.env.RECALL_DISTRIBUTION === "mac-app-store") {
1805
2717
  const body = await parseBody(req);
1806
2718
  if (typeof body.text !== "string" || !body.text.trim() || body.text.length > 8192) {
1807
- return send(res, 400, { error: "A memory must contain 1 to 8192 characters." });
2719
+ return send2(res, 400, { error: "A memory must contain 1 to 8192 characters." });
1808
2720
  }
1809
2721
  const repo = typeof body.repo === "string" && body.repo.trim() ? body.repo.trim() : null;
1810
2722
  const id = createMemory(db, {
@@ -1817,31 +2729,31 @@ var server = createServer2(async (req, res) => {
1817
2729
  });
1818
2730
  safeIngestMemory(id);
1819
2731
  emit("memory.created", { memory_id: id, repo, source: "manual" });
1820
- return send(res, 201, { id });
2732
+ return send2(res, 201, { id });
1821
2733
  }
1822
2734
  if (path.startsWith("/hook/agent/") && method === "POST") {
1823
2735
  const segments = path.split("/");
1824
2736
  const agent = segments[3];
1825
2737
  const event = segments[4];
1826
2738
  if (segments.length !== 5 || agent !== "codex" && agent !== "claude-code" || !HTTP_HOOK_EVENTS.includes(event)) {
1827
- return send(res, 400, { error: "unsupported agent or hook event" });
2739
+ return send2(res, 400, { error: "unsupported agent or hook event" });
1828
2740
  }
1829
2741
  const body = await parseBody(req);
1830
2742
  try {
1831
- return send(res, 200, await handleAgentHttpHook(
2743
+ return send2(res, 200, await handleAgentHttpHook(
1832
2744
  db,
1833
2745
  agent,
1834
2746
  event,
1835
2747
  body
1836
2748
  ));
1837
2749
  } catch (error) {
1838
- return send(res, 400, { error: error instanceof Error ? error.message : "invalid hook" });
2750
+ return send2(res, 400, { error: error instanceof Error ? error.message : "invalid hook" });
1839
2751
  }
1840
2752
  }
1841
2753
  if (path === "/compile" && method === "POST") {
1842
2754
  const body = await parseBody(req);
1843
2755
  const repo = resolveRepo(body);
1844
- if (!repo) return send(res, 400, { error: "repo or repo_path required" });
2756
+ if (!repo) return send2(res, 400, { error: "repo or repo_path required" });
1845
2757
  const bootstrap = ensureRepoBootstrapped(db, {
1846
2758
  repo,
1847
2759
  repoPathHint: body.repo_path
@@ -1892,10 +2804,11 @@ var server = createServer2(async (req, res) => {
1892
2804
  dropped: result.memories_dropped,
1893
2805
  history_included: result.history_included,
1894
2806
  token_estimate: result.token_estimate,
2807
+ ...result.cloud_enrichment ? { cloud_enrichment: result.cloud_enrichment } : {},
1895
2808
  repo_path: bootstrap.repo_path
1896
2809
  }
1897
2810
  });
1898
- return send(res, 200, {
2811
+ return send2(res, 200, {
1899
2812
  ...result,
1900
2813
  repo,
1901
2814
  repo_path: bootstrap.repo_path ?? body.repo_path ?? null,
@@ -1905,7 +2818,7 @@ var server = createServer2(async (req, res) => {
1905
2818
  if (path === "/session/start" && method === "POST") {
1906
2819
  const body = await parseBody(req);
1907
2820
  if (!body.session_id) {
1908
- return send(res, 400, { error: "session_id required" });
2821
+ return send2(res, 400, { error: "session_id required" });
1909
2822
  }
1910
2823
  const result = startSessionLifecycle(db, {
1911
2824
  session_id: body.session_id,
@@ -1920,12 +2833,12 @@ var server = createServer2(async (req, res) => {
1920
2833
  client: body.client ?? null,
1921
2834
  repo: body.repo ?? null
1922
2835
  });
1923
- return send(res, 200, result);
2836
+ return send2(res, 200, result);
1924
2837
  }
1925
2838
  if (path === "/session/event" && method === "POST") {
1926
2839
  const body = await parseBody(req);
1927
2840
  if (!body.session_id || !body.name) {
1928
- return send(res, 400, { error: "session_id and name required" });
2841
+ return send2(res, 400, { error: "session_id and name required" });
1929
2842
  }
1930
2843
  const result = recordSessionLifecycleEvent(db, {
1931
2844
  session_id: body.session_id,
@@ -1937,12 +2850,12 @@ var server = createServer2(async (req, res) => {
1937
2850
  name: body.name,
1938
2851
  payload: body.payload ?? {}
1939
2852
  });
1940
- return send(res, 200, result);
2853
+ return send2(res, 200, result);
1941
2854
  }
1942
2855
  if (path === "/session/end" && method === "POST") {
1943
2856
  const body = await parseBody(req);
1944
2857
  if (!body.session_id) {
1945
- return send(res, 400, { error: "session_id required" });
2858
+ return send2(res, 400, { error: "session_id required" });
1946
2859
  }
1947
2860
  const result = endSessionLifecycle(db, {
1948
2861
  session_id: body.session_id,
@@ -1957,10 +2870,10 @@ var server = createServer2(async (req, res) => {
1957
2870
  session_id: body.session_id,
1958
2871
  repo: body.repo ?? null
1959
2872
  });
1960
- return send(res, 200, result);
2873
+ return send2(res, 200, result);
1961
2874
  }
1962
2875
  if (path === "/graph/stats" && method === "GET") {
1963
- return send(res, 200, {
2876
+ return send2(res, 200, {
1964
2877
  entities: countEntities(db),
1965
2878
  relations: countRelations(db)
1966
2879
  });
@@ -1969,7 +2882,7 @@ var server = createServer2(async (req, res) => {
1969
2882
  const repo = url.searchParams.get("repo") ?? void 0;
1970
2883
  const limit = parseInt(url.searchParams.get("limit") ?? "2000", 10);
1971
2884
  const rows = listAllRelations(db, { repo, limit });
1972
- return send(res, 200, { count: rows.length, relations: rows });
2885
+ return send2(res, 200, { count: rows.length, relations: rows });
1973
2886
  }
1974
2887
  if (path === "/graph/entities" && method === "GET") {
1975
2888
  const repo = url.searchParams.get("repo") ?? void 0;
@@ -1982,7 +2895,7 @@ var server = createServer2(async (req, res) => {
1982
2895
  search,
1983
2896
  limit
1984
2897
  });
1985
- return send(res, 200, {
2898
+ return send2(res, 200, {
1986
2899
  count: rows.length,
1987
2900
  entities: rows
1988
2901
  });
@@ -1990,7 +2903,7 @@ var server = createServer2(async (req, res) => {
1990
2903
  if (path === "/graph/query" && method === "POST") {
1991
2904
  const body = await parseBody(req);
1992
2905
  if (!body.query || typeof body.query !== "string") {
1993
- return send(res, 400, { error: "query (string) required" });
2906
+ return send2(res, 400, { error: "query (string) required" });
1994
2907
  }
1995
2908
  const embeddingConfig = loadEmbeddingConfigFromEnv();
1996
2909
  const result = await graphQuery(db, body.query, embeddingConfig, {
@@ -1999,7 +2912,7 @@ var server = createServer2(async (req, res) => {
1999
2912
  limit: typeof body.limit === "number" ? body.limit : void 0,
2000
2913
  relationTypes: Array.isArray(body.relation_types) ? body.relation_types : void 0
2001
2914
  });
2002
- return send(res, 200, {
2915
+ return send2(res, 200, {
2003
2916
  seed_count: result.seed_count,
2004
2917
  expanded_entities: result.expanded_entities,
2005
2918
  hits: result.hits.map((h) => ({
@@ -2019,8 +2932,8 @@ var server = createServer2(async (req, res) => {
2019
2932
  if (path.startsWith("/graph/entity/") && method === "GET") {
2020
2933
  const id = path.slice("/graph/entity/".length);
2021
2934
  const ent = getEntity(db, id);
2022
- if (!ent) return send(res, 404, { error: "entity not found" });
2023
- return send(res, 200, {
2935
+ if (!ent) return send2(res, 404, { error: "entity not found" });
2936
+ return send2(res, 200, {
2024
2937
  entity: ent,
2025
2938
  memories: listMemoryIdsForEntity(db, id)
2026
2939
  });
@@ -2028,17 +2941,17 @@ var server = createServer2(async (req, res) => {
2028
2941
  if (path === "/graph/neighbors" && method === "POST") {
2029
2942
  const body = await parseBody(req);
2030
2943
  if (!body.entity_id || typeof body.entity_id !== "string") {
2031
- return send(res, 400, { error: "entity_id (string) required" });
2944
+ return send2(res, 400, { error: "entity_id (string) required" });
2032
2945
  }
2033
2946
  const root = getEntity(db, body.entity_id);
2034
- if (!root) return send(res, 404, { error: "entity not found" });
2947
+ if (!root) return send2(res, 404, { error: "entity not found" });
2035
2948
  const walk = neighborsOf(db, body.entity_id, {
2036
2949
  hops: typeof body.hops === "number" ? body.hops : void 0,
2037
2950
  relationTypes: Array.isArray(body.relation_types) ? body.relation_types : void 0
2038
2951
  });
2039
2952
  const includeMemories = body.include_memories !== false;
2040
2953
  const memoriesByEntity = includeMemories ? Object.fromEntries(walk.entities.map((e) => [e.id, listMemoryIdsForEntity(db, e.id)])) : {};
2041
- return send(res, 200, {
2954
+ return send2(res, 200, {
2042
2955
  root,
2043
2956
  entities: walk.entities,
2044
2957
  relations: walk.relations,
@@ -2048,10 +2961,10 @@ var server = createServer2(async (req, res) => {
2048
2961
  if (path.startsWith("/graph/memory/") && method === "GET") {
2049
2962
  const memId = path.slice("/graph/memory/".length);
2050
2963
  const ents = listEntitiesForMemory(db, memId);
2051
- return send(res, 200, { memory_id: memId, entities: ents });
2964
+ return send2(res, 200, { memory_id: memId, entities: ents });
2052
2965
  }
2053
2966
  if (path === "/webui/status" && method === "GET") {
2054
- return send(res, 200, getStatus());
2967
+ return send2(res, 200, getStatus());
2055
2968
  }
2056
2969
  if (path === "/webui/start" && method === "POST") {
2057
2970
  const body = await parseBody(req).catch(() => ({}));
@@ -2061,70 +2974,70 @@ var server = createServer2(async (req, res) => {
2061
2974
  if (body.open !== false && status.url) {
2062
2975
  openInBrowser(status.url);
2063
2976
  }
2064
- return send(res, 200, status);
2977
+ return send2(res, 200, status);
2065
2978
  }
2066
2979
  if (path === "/webui/stop" && method === "POST") {
2067
2980
  const status = await stop();
2068
- return send(res, 200, status);
2981
+ return send2(res, 200, status);
2069
2982
  }
2070
2983
  if (path === "/dispatch/wake" && method === "POST") {
2071
2984
  wakeDispatcherDebounced();
2072
- return send(res, 202, { status: "queued", debounce_ms: DISPATCH_WAKE_DEBOUNCE_MS });
2985
+ return send2(res, 202, { status: "queued", debounce_ms: DISPATCH_WAKE_DEBOUNCE_MS });
2073
2986
  }
2074
2987
  if (path === "/hook/prompt" && method === "POST") {
2075
2988
  const body = await parseBody(req);
2076
2989
  if (!body.text) {
2077
- return send(res, 400, { error: "text required" });
2990
+ return send2(res, 400, { error: "text required" });
2078
2991
  }
2079
2992
  const result = await handlePromptHook(body, {
2080
2993
  db,
2081
2994
  source: "daemon"
2082
2995
  });
2083
- return send(res, 200, { ...result, transport: "daemon" });
2996
+ return send2(res, 200, { ...result, transport: "daemon" });
2084
2997
  }
2085
2998
  if (path === "/hook/tool" && method === "POST") {
2086
2999
  const body = await parseBody(req);
2087
3000
  if (!body.name || typeof body.exit_code !== "number") {
2088
- return send(res, 400, { error: "name and numeric exit_code required" });
3001
+ return send2(res, 400, { error: "name and numeric exit_code required" });
2089
3002
  }
2090
3003
  const result = await handleToolHook(body, {
2091
3004
  db,
2092
3005
  source: "daemon"
2093
3006
  });
2094
- return send(res, 200, { ...result, transport: "daemon" });
3007
+ return send2(res, 200, { ...result, transport: "daemon" });
2095
3008
  }
2096
3009
  if (path === "/hook/assistant" && method === "POST") {
2097
3010
  const body = await parseBody(req);
2098
3011
  if (!body.text) {
2099
- return send(res, 400, { error: "text required" });
3012
+ return send2(res, 400, { error: "text required" });
2100
3013
  }
2101
3014
  const result = await handleAssistantCompletionHook(body, {
2102
3015
  db,
2103
3016
  source: "daemon"
2104
3017
  });
2105
- return send(res, 200, { ...result, transport: "daemon" });
3018
+ return send2(res, 200, { ...result, transport: "daemon" });
2106
3019
  }
2107
3020
  if (path === "/hook/session-start" && method === "POST") {
2108
3021
  const body = await parseBody(req);
2109
3022
  if (!body.session_id || !body.agent) {
2110
- return send(res, 400, { error: "session_id and agent required" });
3023
+ return send2(res, 400, { error: "session_id and agent required" });
2111
3024
  }
2112
3025
  const result = await handleSessionStartHook(body, {
2113
3026
  db,
2114
3027
  source: "daemon"
2115
3028
  });
2116
- return send(res, 200, { ...result, transport: "daemon" });
3029
+ return send2(res, 200, { ...result, transport: "daemon" });
2117
3030
  }
2118
3031
  if (path === "/hook/session-end" && method === "POST") {
2119
3032
  const body = await parseBody(req);
2120
3033
  if (!body.session_id) {
2121
- return send(res, 400, { error: "session_id required" });
3034
+ return send2(res, 400, { error: "session_id required" });
2122
3035
  }
2123
3036
  const result = await handleSessionEndHook(body, {
2124
3037
  db,
2125
3038
  source: "daemon"
2126
3039
  });
2127
- return send(res, 200, { ...result, transport: "daemon" });
3040
+ return send2(res, 200, { ...result, transport: "daemon" });
2128
3041
  }
2129
3042
  if (path === "/correct" && method === "POST") {
2130
3043
  const body = await parseBody(req);
@@ -2153,7 +3066,7 @@ var server = createServer2(async (req, res) => {
2153
3066
  source: "correction"
2154
3067
  });
2155
3068
  }
2156
- return send(res, 200, { created: ids, pending_task_id: pendingTaskId ?? null });
3069
+ return send2(res, 200, { created: ids, pending_task_id: pendingTaskId ?? null });
2157
3070
  }
2158
3071
  if (path === "/review" && method === "POST") {
2159
3072
  const body = await parseBody(req);
@@ -2182,7 +3095,7 @@ var server = createServer2(async (req, res) => {
2182
3095
  source: "review"
2183
3096
  });
2184
3097
  }
2185
- return send(res, 200, { created: ids });
3098
+ return send2(res, 200, { created: ids });
2186
3099
  }
2187
3100
  if (path === "/confirm" && method === "POST") {
2188
3101
  const body = await parseBody(req);
@@ -2194,7 +3107,7 @@ var server = createServer2(async (req, res) => {
2194
3107
  repo: mem?.repo ?? null
2195
3108
  });
2196
3109
  }
2197
- return send(res, ok ? 200 : 404, { success: ok });
3110
+ return send2(res, ok ? 200 : 404, { success: ok });
2198
3111
  }
2199
3112
  if (path === "/reject" && method === "POST") {
2200
3113
  const body = await parseBody(req);
@@ -2217,7 +3130,7 @@ var server = createServer2(async (req, res) => {
2217
3130
  actor: "daemon:http"
2218
3131
  });
2219
3132
  }
2220
- return send(res, ok ? 200 : 404, { success: ok });
3133
+ return send2(res, ok ? 200 : 404, { success: ok });
2221
3134
  }
2222
3135
  if (path === "/feedback" && method === "POST") {
2223
3136
  const body = await parseBody(req);
@@ -2233,7 +3146,7 @@ var server = createServer2(async (req, res) => {
2233
3146
  outcome: String(body.outcome ?? ""),
2234
3147
  injected: Boolean(body.injected)
2235
3148
  });
2236
- return send(res, 200, { feedback_id: id });
3149
+ return send2(res, 200, { feedback_id: id });
2237
3150
  }
2238
3151
  if (path === "/memories" && method === "GET") {
2239
3152
  const repo = url.searchParams.get("repo") ?? void 0;
@@ -2241,7 +3154,7 @@ var server = createServer2(async (req, res) => {
2241
3154
  const limit = parseInt(url.searchParams.get("limit") ?? "50", 10);
2242
3155
  const offset = parseInt(url.searchParams.get("offset") ?? "0", 10);
2243
3156
  const items = queryMemories(db, { repo, status, limit, offset });
2244
- return send(res, 200, {
3157
+ return send2(res, 200, {
2245
3158
  memories: items,
2246
3159
  offset,
2247
3160
  limit,
@@ -2251,8 +3164,8 @@ var server = createServer2(async (req, res) => {
2251
3164
  if (path.startsWith("/memory/") && method === "GET") {
2252
3165
  const id = path.slice("/memory/".length);
2253
3166
  const mem = getMemory(db, id);
2254
- if (!mem) return send(res, 404, { error: "not found" });
2255
- return send(res, 200, mem);
3167
+ if (!mem) return send2(res, 404, { error: "not found" });
3168
+ return send2(res, 200, mem);
2256
3169
  }
2257
3170
  if (path === "/scan" && method === "POST") {
2258
3171
  const body = await parseBody(req);
@@ -2290,7 +3203,7 @@ var server = createServer2(async (req, res) => {
2290
3203
  type: m?.type
2291
3204
  });
2292
3205
  }
2293
- return send(res, 200, {
3206
+ return send2(res, 200, {
2294
3207
  created: ids,
2295
3208
  count: ids.length,
2296
3209
  artifact_path: artifact.output_path,
@@ -2301,22 +3214,22 @@ var server = createServer2(async (req, res) => {
2301
3214
  const repo = url.searchParams.get("repo") ?? void 0;
2302
3215
  const since = url.searchParams.get("since") ?? void 0;
2303
3216
  const metrics = computeMetrics(db, { repo, since });
2304
- return send(res, 200, metrics);
3217
+ return send2(res, 200, metrics);
2305
3218
  }
2306
3219
  if (path === "/eval/start" && method === "POST") {
2307
3220
  const body = await parseBody(req);
2308
3221
  const id = startEvalSession(db, body.repo);
2309
- return send(res, 200, { session_id: id });
3222
+ return send2(res, 200, { session_id: id });
2310
3223
  }
2311
3224
  if (path === "/eval/end" && method === "POST") {
2312
3225
  const body = await parseBody(req);
2313
3226
  endEvalSession(db, body.session_id);
2314
- return send(res, 200, { success: true });
3227
+ return send2(res, 200, { success: true });
2315
3228
  }
2316
3229
  if (path === "/eval/increment" && method === "POST") {
2317
3230
  const body = await parseBody(req);
2318
3231
  incrementEvalCounter(db, body.session_id, body.field, body.amount ?? 1);
2319
- return send(res, 200, { success: true });
3232
+ return send2(res, 200, { success: true });
2320
3233
  }
2321
3234
  if (path === "/signal" && method === "POST") {
2322
3235
  const body = await parseBody(req);
@@ -2338,16 +3251,16 @@ var server = createServer2(async (req, res) => {
2338
3251
  request: { signal_type: body.signal_type, context: body.context ?? null },
2339
3252
  result: { signal_id: id }
2340
3253
  });
2341
- return send(res, 200, { signal_id: id });
3254
+ return send2(res, 200, { signal_id: id });
2342
3255
  }
2343
3256
  if (path.startsWith("/signal/stats/") && method === "GET") {
2344
3257
  const memId = path.slice("/signal/stats/".length);
2345
3258
  const stats = getSignalStats(db, memId);
2346
- return send(res, 200, stats);
3259
+ return send2(res, 200, stats);
2347
3260
  }
2348
3261
  if (path === "/quality" && method === "GET") {
2349
3262
  const repo = url.searchParams.get("repo") ?? void 0;
2350
- return send(res, 200, getRepoQualityProfile(db, repo));
3263
+ return send2(res, 200, getRepoQualityProfile(db, repo));
2351
3264
  }
2352
3265
  if (path === "/activity" && method === "GET") {
2353
3266
  const repo = url.searchParams.get("repo") ?? void 0;
@@ -2366,7 +3279,7 @@ var server = createServer2(async (req, res) => {
2366
3279
  limit,
2367
3280
  offset
2368
3281
  });
2369
- return send(res, 200, { events, offset, limit, has_more: events.length === limit });
3282
+ return send2(res, 200, { events, offset, limit, has_more: events.length === limit });
2370
3283
  }
2371
3284
  if (path === "/sessions" && method === "GET") {
2372
3285
  const repo = url.searchParams.get("repo") ?? void 0;
@@ -2383,7 +3296,7 @@ var server = createServer2(async (req, res) => {
2383
3296
  limit: Math.max(limit + offset, 200)
2384
3297
  });
2385
3298
  const page = grouped.slice(offset, offset + limit);
2386
- return send(res, 200, {
3299
+ return send2(res, 200, {
2387
3300
  sessions: page,
2388
3301
  offset,
2389
3302
  limit,
@@ -2392,44 +3305,44 @@ var server = createServer2(async (req, res) => {
2392
3305
  }
2393
3306
  if (path === "/policy/list" && method === "GET") {
2394
3307
  const orgId = url.searchParams.get("org_id") ?? "";
2395
- return send(res, 200, { policies: listPolicies(db, orgId) });
3308
+ return send2(res, 200, { policies: listPolicies(db, orgId) });
2396
3309
  }
2397
3310
  if (path === "/policy" && method === "POST") {
2398
3311
  const body = await parseBody(req);
2399
3312
  const id = createPolicy(db, body.org_id, body.rule_type, body.config);
2400
- return send(res, 200, { policy_id: id });
3313
+ return send2(res, 200, { policy_id: id });
2401
3314
  }
2402
3315
  if (path === "/policy/check" && method === "POST") {
2403
3316
  const body = await parseBody(req);
2404
3317
  const mem = getMemory(db, body.memory_id);
2405
- if (!mem) return send(res, 404, { error: "memory not found" });
3318
+ if (!mem) return send2(res, 404, { error: "memory not found" });
2406
3319
  const violations = evaluatePolicy(db, body.org_id, mem);
2407
- return send(res, 200, { violations });
3320
+ return send2(res, 200, { violations });
2408
3321
  }
2409
3322
  if (path === "/approval/request" && method === "POST") {
2410
3323
  const body = await parseBody(req);
2411
3324
  const id = requestApproval(db, body.memory_id, body.org_id, body.requested_by ?? "daemon");
2412
- return send(res, 200, { approval_id: id });
3325
+ return send2(res, 200, { approval_id: id });
2413
3326
  }
2414
3327
  if (path === "/approval/pending" && method === "GET") {
2415
3328
  const orgId = url.searchParams.get("org_id") ?? "";
2416
- return send(res, 200, { approvals: listPendingApprovals(db, orgId) });
3329
+ return send2(res, 200, { approvals: listPendingApprovals(db, orgId) });
2417
3330
  }
2418
3331
  if (path === "/approval/resolve" && method === "POST") {
2419
3332
  const body = await parseBody(req);
2420
3333
  const ok = resolveApproval(db, body.approval_id, body.status, body.reviewed_by ?? "daemon", body.reason);
2421
- return send(res, ok ? 200 : 404, { success: ok });
3334
+ return send2(res, ok ? 200 : 404, { success: ok });
2422
3335
  }
2423
3336
  if (path.startsWith("/health/") && method === "GET") {
2424
3337
  const memId = path.slice("/health/".length);
2425
3338
  const score = computeHealthScore(db, memId);
2426
- if (!score) return send(res, 404, { error: "not found" });
2427
- return send(res, 200, score);
3339
+ if (!score) return send2(res, 404, { error: "not found" });
3340
+ return send2(res, 200, score);
2428
3341
  }
2429
3342
  if (path === "/health" && method === "GET") {
2430
3343
  const repo = url.searchParams.get("repo") ?? void 0;
2431
3344
  const scores = computeAllHealthScores(db, repo);
2432
- return send(res, 200, { scores });
3345
+ return send2(res, 200, { scores });
2433
3346
  }
2434
3347
  if (path === "/contradictions/detect" && method === "POST") {
2435
3348
  const body = await parseBody(req);
@@ -2442,7 +3355,7 @@ var server = createServer2(async (req, res) => {
2442
3355
  severity: c.severity
2443
3356
  });
2444
3357
  }
2445
- return send(res, 200, { contradictions: found });
3358
+ return send2(res, 200, { contradictions: found });
2446
3359
  }
2447
3360
  if (path === "/contradictions" && method === "GET") {
2448
3361
  const resolved = url.searchParams.get("resolved");
@@ -2453,7 +3366,7 @@ var server = createServer2(async (req, res) => {
2453
3366
  limit,
2454
3367
  offset
2455
3368
  });
2456
- return send(res, 200, {
3369
+ return send2(res, 200, {
2457
3370
  contradictions: items,
2458
3371
  offset,
2459
3372
  limit,
@@ -2469,43 +3382,44 @@ var server = createServer2(async (req, res) => {
2469
3382
  keep_memory_id: body.keep_memory_id
2470
3383
  });
2471
3384
  }
2472
- return send(res, ok ? 200 : 404, { success: ok });
3385
+ return send2(res, ok ? 200 : 404, { success: ok });
2473
3386
  }
2474
3387
  if (path === "/contradictions/auto-resolve" && method === "POST") {
2475
3388
  const body = await parseBody(req);
2476
3389
  const count = autoResolveContradictions(db, body.repo);
2477
- return send(res, 200, { resolved: count });
3390
+ return send2(res, 200, { resolved: count });
2478
3391
  }
2479
3392
  if (path === "/prune" && method === "POST") {
2480
3393
  const body = await parseBody(req);
2481
3394
  const result = pruneMemories(db, body.config);
2482
- return send(res, 200, result);
3395
+ return send2(res, 200, result);
2483
3396
  }
2484
3397
  if (path.startsWith("/audit/memory/") && method === "GET") {
2485
3398
  const memId = path.slice("/audit/memory/".length);
2486
3399
  const entries = getAuditTrail(db, memId);
2487
- return send(res, 200, { entries });
3400
+ return send2(res, 200, { entries });
2488
3401
  }
2489
3402
  if (path === "/audit/recent" && method === "GET") {
2490
3403
  const limit = parseInt(url.searchParams.get("limit") ?? "50");
2491
3404
  const entries = getRecentAudit(db, limit);
2492
- return send(res, 200, { entries });
3405
+ return send2(res, 200, { entries });
2493
3406
  }
2494
3407
  if (path === "/audit/rollback" && method === "POST") {
2495
3408
  const body = await parseBody(req);
2496
3409
  const ok = rollbackMemory(db, body.memory_id, body.audit_entry_id, body.actor ?? "daemon");
2497
- return send(res, ok ? 200 : 404, { success: ok });
3410
+ return send2(res, ok ? 200 : 404, { success: ok });
2498
3411
  }
2499
- send(res, 404, { error: "not found" });
3412
+ if (await handleCloudRoute(cloudService, req, res, path, method)) return;
3413
+ send2(res, 404, { error: "not found" });
2500
3414
  } catch (err) {
2501
3415
  if (err instanceof JsonBodyError) {
2502
- return send(res, err.status, { error: err.message });
3416
+ return send2(res, err.status, { error: err.message });
2503
3417
  }
2504
3418
  Sentry.captureException(err);
2505
- send(res, 500, { error: "internal server error" });
3419
+ send2(res, 500, { error: "internal server error" });
2506
3420
  }
2507
3421
  });
2508
- function send(res, status, data) {
3422
+ function send2(res, status, data) {
2509
3423
  res.statusCode = status;
2510
3424
  res.end(JSON.stringify(data));
2511
3425
  }
@@ -2536,7 +3450,7 @@ async function startDaemon() {
2536
3450
  }
2537
3451
  }
2538
3452
  try {
2539
- const dataDir = process.env.RECALL_DATA_DIR ?? join3(homedir(), ".recall");
3453
+ const dataDir = process.env.RECALL_DATA_DIR ?? join5(homedir(), ".recall");
2540
3454
  const reconciled = reconcileGraphIfStale(db, dataDir);
2541
3455
  if (reconciled) {
2542
3456
  console.log(
@@ -2554,7 +3468,14 @@ async function startDaemon() {
2554
3468
  scheduleQualitySnapshotLoop();
2555
3469
  scheduleReliabilityProbeLoop();
2556
3470
  scheduleReliabilityVerdictLoop();
3471
+ void cloudService.startIfEnabled();
2557
3472
  });
3473
+ for (const signal of ["SIGTERM", "SIGINT"]) {
3474
+ process.once(signal, () => {
3475
+ void cloudService.shutdown().finally(() => process.kill(process.pid, signal));
3476
+ });
3477
+ }
3478
+ process.on("exit", () => cloudService.killSync());
2558
3479
  }
2559
3480
  void startDaemon().catch((error) => {
2560
3481
  const message = error instanceof Error ? error.stack ?? error.message : String(error);