@askexenow/exe-os 0.8.1 → 0.8.3

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 (106) hide show
  1. package/package.json +1 -1
  2. package/dist/bin/backfill-responses.js +0 -2064
  3. package/dist/bin/backfill-vectors.js +0 -1771
  4. package/dist/bin/cleanup-stale-review-tasks.js +0 -1468
  5. package/dist/bin/cli.js +0 -21371
  6. package/dist/bin/exe-agent.js +0 -2016
  7. package/dist/bin/exe-assign.js +0 -2176
  8. package/dist/bin/exe-boot.js +0 -6332
  9. package/dist/bin/exe-call.js +0 -341
  10. package/dist/bin/exe-cloud.js +0 -861
  11. package/dist/bin/exe-dispatch.js +0 -1159
  12. package/dist/bin/exe-doctor.js +0 -1786
  13. package/dist/bin/exe-export-behaviors.js +0 -1637
  14. package/dist/bin/exe-forget.js +0 -1784
  15. package/dist/bin/exe-gateway.js +0 -8140
  16. package/dist/bin/exe-healthcheck.js +0 -207
  17. package/dist/bin/exe-heartbeat.js +0 -1778
  18. package/dist/bin/exe-kill.js +0 -1622
  19. package/dist/bin/exe-launch-agent.js +0 -1847
  20. package/dist/bin/exe-link.js +0 -192
  21. package/dist/bin/exe-new-employee.js +0 -1384
  22. package/dist/bin/exe-pending-messages.js +0 -1576
  23. package/dist/bin/exe-pending-notifications.js +0 -1450
  24. package/dist/bin/exe-pending-reviews.js +0 -1598
  25. package/dist/bin/exe-repo-drift.js +0 -95
  26. package/dist/bin/exe-review.js +0 -1742
  27. package/dist/bin/exe-search.js +0 -3116
  28. package/dist/bin/exe-session-cleanup.js +0 -3360
  29. package/dist/bin/exe-settings.js +0 -365
  30. package/dist/bin/exe-status.js +0 -1661
  31. package/dist/bin/exe-team.js +0 -1453
  32. package/dist/bin/git-sweep.js +0 -2441
  33. package/dist/bin/graph-backfill.js +0 -2111
  34. package/dist/bin/graph-export.js +0 -1747
  35. package/dist/bin/install.js +0 -661
  36. package/dist/bin/list-providers.js +0 -140
  37. package/dist/bin/scan-tasks.js +0 -2039
  38. package/dist/bin/setup.js +0 -2717
  39. package/dist/bin/shard-migrate.js +0 -1637
  40. package/dist/bin/update.js +0 -98
  41. package/dist/bin/wiki-sync.js +0 -1657
  42. package/dist/gateway/index.js +0 -9256
  43. package/dist/hooks/bug-report-worker.js +0 -2903
  44. package/dist/hooks/commit-complete.js +0 -2364
  45. package/dist/hooks/error-recall.js +0 -3327
  46. package/dist/hooks/exe-heartbeat-hook.js +0 -237
  47. package/dist/hooks/ingest-worker.js +0 -5065
  48. package/dist/hooks/ingest.js +0 -695
  49. package/dist/hooks/instructions-loaded.js +0 -2069
  50. package/dist/hooks/notification.js +0 -1915
  51. package/dist/hooks/post-compact.js +0 -1940
  52. package/dist/hooks/pre-compact.js +0 -1935
  53. package/dist/hooks/pre-tool-use.js +0 -2380
  54. package/dist/hooks/prompt-ingest-worker.js +0 -2291
  55. package/dist/hooks/prompt-submit.js +0 -5189
  56. package/dist/hooks/response-ingest-worker.js +0 -2431
  57. package/dist/hooks/session-end.js +0 -2196
  58. package/dist/hooks/session-start.js +0 -3259
  59. package/dist/hooks/stop.js +0 -2025
  60. package/dist/hooks/subagent-stop.js +0 -1915
  61. package/dist/hooks/summary-worker.js +0 -2931
  62. package/dist/index.js +0 -12327
  63. package/dist/lib/cloud-sync.js +0 -500
  64. package/dist/lib/config.js +0 -235
  65. package/dist/lib/consolidation.js +0 -481
  66. package/dist/lib/crypto.js +0 -51
  67. package/dist/lib/database.js +0 -834
  68. package/dist/lib/device-registry.js +0 -1009
  69. package/dist/lib/embedder.js +0 -645
  70. package/dist/lib/employee-templates.js +0 -570
  71. package/dist/lib/employees.js +0 -182
  72. package/dist/lib/error-detector.js +0 -156
  73. package/dist/lib/exe-daemon-client.js +0 -456
  74. package/dist/lib/exe-daemon.js +0 -8699
  75. package/dist/lib/file-grep.js +0 -215
  76. package/dist/lib/hybrid-search.js +0 -3064
  77. package/dist/lib/identity-templates.js +0 -441
  78. package/dist/lib/identity.js +0 -228
  79. package/dist/lib/keychain.js +0 -145
  80. package/dist/lib/license.js +0 -382
  81. package/dist/lib/messaging.js +0 -1389
  82. package/dist/lib/reminders.js +0 -63
  83. package/dist/lib/schedules.js +0 -1525
  84. package/dist/lib/session-registry.js +0 -52
  85. package/dist/lib/skill-learning.js +0 -488
  86. package/dist/lib/status-brief.js +0 -240
  87. package/dist/lib/store.js +0 -1740
  88. package/dist/lib/task-router.js +0 -128
  89. package/dist/lib/tasks.js +0 -2585
  90. package/dist/lib/tmux-routing.js +0 -2969
  91. package/dist/lib/tmux-status.js +0 -261
  92. package/dist/lib/tmux-transport.js +0 -83
  93. package/dist/lib/transport.js +0 -128
  94. package/dist/lib/ws-auth.js +0 -19
  95. package/dist/lib/ws-client.js +0 -160
  96. package/dist/mcp/server.js +0 -10812
  97. package/dist/mcp/tools/complete-reminder.js +0 -67
  98. package/dist/mcp/tools/create-reminder.js +0 -52
  99. package/dist/mcp/tools/create-task.js +0 -1903
  100. package/dist/mcp/tools/deactivate-behavior.js +0 -268
  101. package/dist/mcp/tools/list-reminders.js +0 -62
  102. package/dist/mcp/tools/list-tasks.js +0 -491
  103. package/dist/mcp/tools/send-message.js +0 -1395
  104. package/dist/mcp/tools/update-task.js +0 -1807
  105. package/dist/runtime/index.js +0 -7201
  106. package/dist/tui/App.js +0 -17874
@@ -1,500 +0,0 @@
1
- // src/lib/database.ts
2
- import { createClient } from "@libsql/client";
3
- var _client = null;
4
- function getClient() {
5
- if (!_client) {
6
- throw new Error("Database client not initialized. Call initDatabase() first.");
7
- }
8
- return _client;
9
- }
10
-
11
- // src/lib/crypto.ts
12
- import crypto from "crypto";
13
- var ALGORITHM = "aes-256-gcm";
14
- var IV_LENGTH = 12;
15
- var TAG_LENGTH = 16;
16
- var _syncKey = null;
17
- function requireSyncKey() {
18
- if (!_syncKey) {
19
- throw new Error("Sync crypto not initialized. Call initSyncCrypto(masterKey) first.");
20
- }
21
- return _syncKey;
22
- }
23
- function encryptSyncBlob(data) {
24
- const key = requireSyncKey();
25
- const iv = crypto.randomBytes(IV_LENGTH);
26
- const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
27
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
28
- const tag = cipher.getAuthTag();
29
- return Buffer.concat([iv, encrypted, tag]).toString("base64");
30
- }
31
- function decryptSyncBlob(ciphertext) {
32
- const key = requireSyncKey();
33
- const combined = Buffer.from(ciphertext, "base64");
34
- if (combined.length < IV_LENGTH + TAG_LENGTH) {
35
- throw new Error("Sync blob too short to contain IV + tag");
36
- }
37
- const iv = combined.subarray(0, IV_LENGTH);
38
- const tag = combined.subarray(combined.length - TAG_LENGTH);
39
- const encrypted = combined.subarray(IV_LENGTH, combined.length - TAG_LENGTH);
40
- const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
41
- decipher.setAuthTag(tag);
42
- return Buffer.concat([decipher.update(encrypted), decipher.final()]);
43
- }
44
-
45
- // src/lib/compress.ts
46
- import { brotliCompressSync, brotliDecompressSync, constants } from "zlib";
47
- function compress(input) {
48
- if (input.length === 0) return Buffer.alloc(0);
49
- return brotliCompressSync(input, {
50
- params: {
51
- [constants.BROTLI_PARAM_QUALITY]: 4
52
- }
53
- });
54
- }
55
- function decompress(input) {
56
- if (input.length === 0) return Buffer.alloc(0);
57
- return brotliDecompressSync(input);
58
- }
59
-
60
- // src/lib/plan-limits.ts
61
- import { readFileSync as readFileSync3, existsSync as existsSync4 } from "fs";
62
- import path4 from "path";
63
-
64
- // src/lib/employees.ts
65
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
66
- import { existsSync as existsSync2, symlinkSync, readlinkSync } from "fs";
67
- import { execSync } from "child_process";
68
- import path2 from "path";
69
-
70
- // src/lib/config.ts
71
- import { readFile, writeFile, mkdir } from "fs/promises";
72
- import { readFileSync, existsSync, renameSync } from "fs";
73
- import path from "path";
74
- import os from "os";
75
- function resolveDataDir() {
76
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
77
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
78
- const newDir = path.join(os.homedir(), ".exe-os");
79
- const legacyDir = path.join(os.homedir(), ".exe-mem");
80
- if (!existsSync(newDir) && existsSync(legacyDir)) {
81
- try {
82
- renameSync(legacyDir, newDir);
83
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
84
- `);
85
- } catch {
86
- return legacyDir;
87
- }
88
- }
89
- return newDir;
90
- }
91
- var EXE_AI_DIR = resolveDataDir();
92
- var DB_PATH = path.join(EXE_AI_DIR, "memories.db");
93
- var MODELS_DIR = path.join(EXE_AI_DIR, "models");
94
- var CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
95
- var LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
96
- var CURRENT_CONFIG_VERSION = 1;
97
- var DEFAULT_CONFIG = {
98
- config_version: CURRENT_CONFIG_VERSION,
99
- dbPath: DB_PATH,
100
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
101
- embeddingDim: 1024,
102
- batchSize: 20,
103
- flushIntervalMs: 1e4,
104
- autoIngestion: true,
105
- autoRetrieval: true,
106
- searchMode: "hybrid",
107
- hookSearchMode: "hybrid",
108
- fileGrepEnabled: true,
109
- splashEffect: true,
110
- consolidationEnabled: true,
111
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
112
- consolidationModel: "claude-haiku-4-5-20251001",
113
- consolidationMaxCallsPerRun: 20,
114
- selfQueryRouter: true,
115
- selfQueryModel: "claude-haiku-4-5-20251001",
116
- rerankerEnabled: true,
117
- scalingRoadmap: {
118
- rerankerAutoTrigger: {
119
- enabled: true,
120
- broadQueryMinCardinality: 5e4,
121
- fetchTopK: 150,
122
- returnTopK: 5
123
- }
124
- },
125
- graphRagEnabled: true,
126
- wikiEnabled: false,
127
- wikiUrl: "",
128
- wikiApiKey: "",
129
- wikiSyncIntervalMs: 30 * 60 * 1e3,
130
- wikiWorkspaceMapping: {
131
- exe: "Executive",
132
- yoshi: "Engineering",
133
- mari: "Marketing",
134
- tom: "Engineering",
135
- sasha: "Production"
136
- },
137
- wikiAutoUpdate: true,
138
- wikiAutoUpdateThreshold: 0.5,
139
- wikiAutoUpdateCreateNew: true,
140
- skillLearning: true,
141
- skillThreshold: 3,
142
- skillModel: "claude-haiku-4-5-20251001",
143
- exeHeartbeat: {
144
- enabled: true,
145
- intervalSeconds: 60,
146
- staleInProgressThresholdHours: 2
147
- },
148
- sessionLifecycle: {
149
- idleKillEnabled: true,
150
- idleKillTicksRequired: 3,
151
- idleKillIntercomAckWindowMs: 1e4,
152
- maxAutoInstances: 10
153
- },
154
- autoUpdate: {
155
- checkOnBoot: true,
156
- autoInstall: false,
157
- checkIntervalMs: 24 * 60 * 60 * 1e3
158
- }
159
- };
160
-
161
- // src/lib/employees.ts
162
- var EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
163
-
164
- // src/lib/license.ts
165
- import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync3, mkdirSync } from "fs";
166
- import { randomUUID } from "crypto";
167
- import path3 from "path";
168
- import { jwtVerify, importSPKI } from "jose";
169
- var LICENSE_PATH = path3.join(EXE_AI_DIR, "license.key");
170
- var CACHE_PATH = path3.join(EXE_AI_DIR, "license-cache.json");
171
- var DEVICE_ID_PATH = path3.join(EXE_AI_DIR, "device-id");
172
- var API_BASE = "https://askexe.com/cloud";
173
- var LICENSE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
174
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEeHztAMOpR/ZMh+rWuOASjEZ54CGY
175
- 4uj+UqeKCcvtgNHKmOK278HJaJcANe9xAeji8AFYu27q3WtzCi04pHudow==
176
- -----END PUBLIC KEY-----`;
177
- var LICENSE_JWT_ALG = "ES256";
178
- var PLAN_LIMITS = {
179
- free: { devices: 1, employees: 1, memories: 5e3 },
180
- pro: { devices: 2, employees: 5, memories: 1e5 },
181
- team: { devices: 10, employees: 20, memories: 1e6 },
182
- agency: { devices: 50, employees: 100, memories: 1e7 },
183
- enterprise: { devices: -1, employees: -1, memories: -1 }
184
- };
185
- var FREE_LICENSE = {
186
- valid: true,
187
- plan: "free",
188
- email: "",
189
- expiresAt: null,
190
- deviceLimit: 1,
191
- employeeLimit: 1,
192
- memoryLimit: 5e3
193
- };
194
- function loadDeviceId() {
195
- const deviceJsonPath = path3.join(EXE_AI_DIR, "device.json");
196
- try {
197
- if (existsSync3(deviceJsonPath)) {
198
- const data = JSON.parse(readFileSync2(deviceJsonPath, "utf8"));
199
- if (data.deviceId) return data.deviceId;
200
- }
201
- } catch {
202
- }
203
- try {
204
- if (existsSync3(DEVICE_ID_PATH)) {
205
- const id2 = readFileSync2(DEVICE_ID_PATH, "utf8").trim();
206
- if (id2) return id2;
207
- }
208
- } catch {
209
- }
210
- const id = randomUUID();
211
- mkdirSync(EXE_AI_DIR, { recursive: true });
212
- writeFileSync(DEVICE_ID_PATH, id, "utf8");
213
- return id;
214
- }
215
- function loadLicense() {
216
- try {
217
- if (!existsSync3(LICENSE_PATH)) return null;
218
- return readFileSync2(LICENSE_PATH, "utf8").trim();
219
- } catch {
220
- return null;
221
- }
222
- }
223
- async function verifyLicenseJwt(token) {
224
- try {
225
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
226
- const { payload } = await jwtVerify(token, key, {
227
- algorithms: [LICENSE_JWT_ALG]
228
- });
229
- const plan = payload.plan ?? "free";
230
- const email = payload.sub ?? "";
231
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
232
- return {
233
- valid: true,
234
- plan,
235
- email,
236
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
237
- deviceLimit: limits.devices,
238
- employeeLimit: limits.employees,
239
- memoryLimit: limits.memories
240
- };
241
- } catch {
242
- return null;
243
- }
244
- }
245
- async function getCachedLicense() {
246
- try {
247
- if (!existsSync3(CACHE_PATH)) return null;
248
- const raw = JSON.parse(readFileSync2(CACHE_PATH, "utf8"));
249
- if (!raw.token || typeof raw.token !== "string") return null;
250
- return await verifyLicenseJwt(raw.token);
251
- } catch {
252
- return null;
253
- }
254
- }
255
- function cacheResponse(token) {
256
- try {
257
- writeFileSync(CACHE_PATH, JSON.stringify({ token }), "utf8");
258
- } catch {
259
- }
260
- }
261
- async function validateLicense(apiKey, deviceId) {
262
- const did = deviceId ?? loadDeviceId();
263
- try {
264
- const res = await fetch(`${API_BASE}/auth/activate`, {
265
- method: "POST",
266
- headers: { "Content-Type": "application/json" },
267
- body: JSON.stringify({ apiKey, deviceId: did }),
268
- signal: AbortSignal.timeout(1e4)
269
- });
270
- if (res.ok) {
271
- const data = await res.json();
272
- if (data.error === "device_limit_exceeded") {
273
- const cached2 = await getCachedLicense();
274
- if (cached2) return cached2;
275
- return { ...FREE_LICENSE, valid: false, plan: "free" };
276
- }
277
- if (data.token) {
278
- cacheResponse(data.token);
279
- const verified = await verifyLicenseJwt(data.token);
280
- if (verified) return verified;
281
- }
282
- const limits = PLAN_LIMITS[data.plan] ?? PLAN_LIMITS.free;
283
- return {
284
- valid: data.valid,
285
- plan: data.plan,
286
- email: data.email,
287
- expiresAt: data.expiresAt,
288
- deviceLimit: limits.devices,
289
- employeeLimit: limits.employees,
290
- memoryLimit: limits.memories
291
- };
292
- }
293
- const cached = await getCachedLicense();
294
- if (cached) return cached;
295
- return { ...FREE_LICENSE, valid: false, plan: "free" };
296
- } catch {
297
- const cached = await getCachedLicense();
298
- if (cached) return cached;
299
- return FREE_LICENSE;
300
- }
301
- }
302
- async function checkLicense() {
303
- const key = loadLicense();
304
- if (!key) return FREE_LICENSE;
305
- const cached = await getCachedLicense();
306
- if (cached) return cached;
307
- const deviceId = loadDeviceId();
308
- return validateLicense(key, deviceId);
309
- }
310
- function isFeatureAllowed(license, feature) {
311
- switch (feature) {
312
- case "cloud_sync":
313
- case "external_agents":
314
- case "wiki":
315
- return license.plan !== "free";
316
- case "unlimited_employees":
317
- return license.plan === "team" || license.plan === "agency" || license.plan === "enterprise";
318
- }
319
- }
320
-
321
- // src/lib/plan-limits.ts
322
- var PlanLimitError = class extends Error {
323
- constructor(message) {
324
- super(message);
325
- this.name = "PlanLimitError";
326
- }
327
- };
328
- var CACHE_PATH2 = path4.join(EXE_AI_DIR, "license-cache.json");
329
- async function assertFeature(feature) {
330
- const license = await checkLicense();
331
- if (!isFeatureAllowed(license, feature)) {
332
- throw new PlanLimitError(
333
- `Feature "${feature}" requires a paid plan. Current plan: ${license.plan}. Upgrade at https://askexe.com.`
334
- );
335
- }
336
- }
337
-
338
- // src/lib/cloud-sync.ts
339
- var LOCALHOST_PATTERNS = /^(localhost|127\.0\.0\.1|\[::1\])$/i;
340
- function assertSecureEndpoint(endpoint) {
341
- if (endpoint.startsWith("https://")) return;
342
- if (endpoint.startsWith("http://")) {
343
- try {
344
- const parsed = new URL(endpoint);
345
- if (LOCALHOST_PATTERNS.test(parsed.hostname)) return;
346
- } catch {
347
- return;
348
- }
349
- throw new Error(
350
- `Insecure cloud endpoint rejected: "${endpoint}". Use https:// for remote hosts. Plain http:// is only allowed for localhost.`
351
- );
352
- }
353
- }
354
- async function cloudPush(records, maxVersion, config) {
355
- if (records.length === 0) return true;
356
- assertSecureEndpoint(config.endpoint);
357
- try {
358
- const json = JSON.stringify(records);
359
- const compressed = compress(Buffer.from(json, "utf8"));
360
- const blob = encryptSyncBlob(compressed);
361
- const resp = await fetch(`${config.endpoint}/sync/push`, {
362
- method: "POST",
363
- headers: {
364
- Authorization: `Bearer ${config.apiKey}`,
365
- "Content-Type": "application/json",
366
- "X-Device-Id": loadDeviceId()
367
- },
368
- body: JSON.stringify({ version: maxVersion, blob })
369
- });
370
- return resp.ok;
371
- } catch (err) {
372
- process.stderr.write(`[cloud-sync] PUSH FAILED: ${err instanceof Error ? err.message : String(err)}
373
- `);
374
- return false;
375
- }
376
- }
377
- async function cloudPull(sinceVersion, config) {
378
- assertSecureEndpoint(config.endpoint);
379
- try {
380
- const response = await fetch(`${config.endpoint}/sync/pull`, {
381
- method: "POST",
382
- headers: {
383
- Authorization: `Bearer ${config.apiKey}`,
384
- "Content-Type": "application/json",
385
- "X-Device-Id": loadDeviceId()
386
- },
387
- body: JSON.stringify({ since_version: sinceVersion })
388
- });
389
- if (!response.ok) return { records: [], maxVersion: sinceVersion };
390
- const data = await response.json();
391
- const allRecords = [];
392
- for (const { blob } of data.blobs ?? []) {
393
- try {
394
- const compressed = decryptSyncBlob(blob);
395
- const json = decompress(compressed).toString("utf8");
396
- const records = JSON.parse(json);
397
- allRecords.push(...records);
398
- } catch {
399
- continue;
400
- }
401
- }
402
- return { records: allRecords, maxVersion: data.max_version ?? sinceVersion };
403
- } catch (err) {
404
- process.stderr.write(`[cloud-sync] PULL FAILED: ${err instanceof Error ? err.message : String(err)}
405
- `);
406
- return { records: [], maxVersion: sinceVersion };
407
- }
408
- }
409
- async function cloudSync(config) {
410
- await assertFeature("cloud_sync");
411
- let client;
412
- try {
413
- client = getClient();
414
- } catch {
415
- throw new Error("[cloud-sync] Database not initialized. Call initStore() before cloudSync().");
416
- }
417
- const pullMeta = await client.execute(
418
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_pull_version'"
419
- );
420
- const lastPullVersion = pullMeta.rows.length > 0 ? Number(pullMeta.rows[0].value) : 0;
421
- const pullResult = await cloudPull(lastPullVersion, config);
422
- let pulled = 0;
423
- if (pullResult.records.length > 0) {
424
- const stmts = pullResult.records.map((rec) => ({
425
- sql: `INSERT OR REPLACE INTO memories
426
- (id, agent_id, agent_role, session_id, timestamp,
427
- tool_name, project_name, has_error, raw_text, version,
428
- author_device_id, scope)
429
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
430
- args: [
431
- rec.id,
432
- rec.agent_id,
433
- rec.agent_role,
434
- rec.session_id,
435
- rec.timestamp,
436
- rec.tool_name,
437
- rec.project_name,
438
- rec.has_error,
439
- rec.raw_text,
440
- rec.version,
441
- rec.author_device_id ?? null,
442
- rec.scope ?? "business"
443
- ]
444
- }));
445
- await client.batch(stmts, "write");
446
- pulled = pullResult.records.length;
447
- }
448
- if (pullResult.maxVersion > lastPullVersion) {
449
- await client.execute({
450
- sql: "INSERT OR REPLACE INTO sync_meta (key, value) VALUES ('last_cloud_pull_version', ?)",
451
- args: [String(pullResult.maxVersion)]
452
- });
453
- }
454
- const pushMeta = await client.execute(
455
- "SELECT value FROM sync_meta WHERE key = 'last_cloud_push_version'"
456
- );
457
- const lastPushVersion = pushMeta.rows.length > 0 ? Number(pushMeta.rows[0].value) : 0;
458
- const recordsResult = await client.execute({
459
- sql: `SELECT id, agent_id, agent_role, session_id, timestamp,
460
- tool_name, project_name, has_error, raw_text, version,
461
- author_device_id, scope
462
- FROM memories
463
- WHERE version > ?
464
- AND (scope IS NULL OR scope != 'personal')
465
- ORDER BY version ASC`,
466
- args: [lastPushVersion]
467
- });
468
- let pushed = 0;
469
- if (recordsResult.rows.length > 0) {
470
- const records = recordsResult.rows.map((row) => ({
471
- id: row.id,
472
- agent_id: row.agent_id,
473
- agent_role: row.agent_role,
474
- session_id: row.session_id,
475
- timestamp: row.timestamp,
476
- tool_name: row.tool_name,
477
- project_name: row.project_name,
478
- has_error: row.has_error,
479
- raw_text: row.raw_text,
480
- version: row.version,
481
- author_device_id: row.author_device_id,
482
- scope: row.scope
483
- }));
484
- const maxVersion = Number(records[records.length - 1].version);
485
- const pushOk = await cloudPush(records, maxVersion, config);
486
- if (pushOk) {
487
- await client.execute({
488
- sql: "INSERT OR REPLACE INTO sync_meta (key, value) VALUES ('last_cloud_push_version', ?)",
489
- args: [String(maxVersion)]
490
- });
491
- pushed = records.length;
492
- }
493
- }
494
- return { pushed, pulled };
495
- }
496
- export {
497
- cloudPull,
498
- cloudPush,
499
- cloudSync
500
- };