@askexenow/exe-os 0.8.0 → 0.8.2

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 (107) hide show
  1. package/README.md +178 -79
  2. package/package.json +1 -1
  3. package/dist/bin/backfill-responses.js +0 -1912
  4. package/dist/bin/backfill-vectors.js +0 -1642
  5. package/dist/bin/cleanup-stale-review-tasks.js +0 -1339
  6. package/dist/bin/cli.js +0 -18800
  7. package/dist/bin/exe-agent.js +0 -1858
  8. package/dist/bin/exe-assign.js +0 -1957
  9. package/dist/bin/exe-boot.js +0 -6460
  10. package/dist/bin/exe-call.js +0 -197
  11. package/dist/bin/exe-cloud.js +0 -850
  12. package/dist/bin/exe-dispatch.js +0 -1146
  13. package/dist/bin/exe-doctor.js +0 -1657
  14. package/dist/bin/exe-export-behaviors.js +0 -1494
  15. package/dist/bin/exe-forget.js +0 -1627
  16. package/dist/bin/exe-gateway.js +0 -7732
  17. package/dist/bin/exe-healthcheck.js +0 -207
  18. package/dist/bin/exe-heartbeat.js +0 -1647
  19. package/dist/bin/exe-kill.js +0 -1479
  20. package/dist/bin/exe-launch-agent.js +0 -1704
  21. package/dist/bin/exe-link.js +0 -192
  22. package/dist/bin/exe-new-employee.js +0 -852
  23. package/dist/bin/exe-pending-messages.js +0 -1446
  24. package/dist/bin/exe-pending-notifications.js +0 -1321
  25. package/dist/bin/exe-pending-reviews.js +0 -1468
  26. package/dist/bin/exe-repo-drift.js +0 -95
  27. package/dist/bin/exe-review.js +0 -1590
  28. package/dist/bin/exe-search.js +0 -2651
  29. package/dist/bin/exe-session-cleanup.js +0 -3173
  30. package/dist/bin/exe-settings.js +0 -354
  31. package/dist/bin/exe-status.js +0 -1532
  32. package/dist/bin/exe-team.js +0 -1324
  33. package/dist/bin/git-sweep.js +0 -2185
  34. package/dist/bin/graph-backfill.js +0 -1968
  35. package/dist/bin/graph-export.js +0 -1604
  36. package/dist/bin/install.js +0 -656
  37. package/dist/bin/list-providers.js +0 -140
  38. package/dist/bin/scan-tasks.js +0 -1820
  39. package/dist/bin/setup.js +0 -951
  40. package/dist/bin/shard-migrate.js +0 -1494
  41. package/dist/bin/update.js +0 -95
  42. package/dist/bin/wiki-sync.js +0 -1514
  43. package/dist/gateway/index.js +0 -8848
  44. package/dist/hooks/bug-report-worker.js +0 -2743
  45. package/dist/hooks/commit-complete.js +0 -2108
  46. package/dist/hooks/error-recall.js +0 -2861
  47. package/dist/hooks/exe-heartbeat-hook.js +0 -232
  48. package/dist/hooks/ingest-worker.js +0 -4793
  49. package/dist/hooks/ingest.js +0 -684
  50. package/dist/hooks/instructions-loaded.js +0 -1880
  51. package/dist/hooks/notification.js +0 -1726
  52. package/dist/hooks/post-compact.js +0 -1751
  53. package/dist/hooks/pre-compact.js +0 -1746
  54. package/dist/hooks/pre-tool-use.js +0 -2191
  55. package/dist/hooks/prompt-ingest-worker.js +0 -2126
  56. package/dist/hooks/prompt-submit.js +0 -4693
  57. package/dist/hooks/response-ingest-worker.js +0 -1936
  58. package/dist/hooks/session-end.js +0 -1752
  59. package/dist/hooks/session-start.js +0 -2795
  60. package/dist/hooks/stop.js +0 -1835
  61. package/dist/hooks/subagent-stop.js +0 -1726
  62. package/dist/hooks/summary-worker.js +0 -2661
  63. package/dist/index.js +0 -11834
  64. package/dist/lib/cloud-sync.js +0 -495
  65. package/dist/lib/config.js +0 -222
  66. package/dist/lib/consolidation.js +0 -476
  67. package/dist/lib/crypto.js +0 -51
  68. package/dist/lib/database.js +0 -730
  69. package/dist/lib/device-registry.js +0 -900
  70. package/dist/lib/embedder.js +0 -632
  71. package/dist/lib/employee-templates.js +0 -543
  72. package/dist/lib/employees.js +0 -177
  73. package/dist/lib/error-detector.js +0 -156
  74. package/dist/lib/exe-daemon-client.js +0 -451
  75. package/dist/lib/exe-daemon.js +0 -8285
  76. package/dist/lib/file-grep.js +0 -199
  77. package/dist/lib/hybrid-search.js +0 -1819
  78. package/dist/lib/identity-templates.js +0 -320
  79. package/dist/lib/identity.js +0 -223
  80. package/dist/lib/keychain.js +0 -145
  81. package/dist/lib/license.js +0 -377
  82. package/dist/lib/messaging.js +0 -1376
  83. package/dist/lib/reminders.js +0 -63
  84. package/dist/lib/schedules.js +0 -1396
  85. package/dist/lib/session-registry.js +0 -52
  86. package/dist/lib/skill-learning.js +0 -477
  87. package/dist/lib/status-brief.js +0 -235
  88. package/dist/lib/store.js +0 -1551
  89. package/dist/lib/task-router.js +0 -62
  90. package/dist/lib/tasks.js +0 -2456
  91. package/dist/lib/tmux-routing.js +0 -2836
  92. package/dist/lib/tmux-status.js +0 -261
  93. package/dist/lib/tmux-transport.js +0 -83
  94. package/dist/lib/transport.js +0 -128
  95. package/dist/lib/ws-auth.js +0 -19
  96. package/dist/lib/ws-client.js +0 -160
  97. package/dist/mcp/server.js +0 -10538
  98. package/dist/mcp/tools/complete-reminder.js +0 -67
  99. package/dist/mcp/tools/create-reminder.js +0 -52
  100. package/dist/mcp/tools/create-task.js +0 -1853
  101. package/dist/mcp/tools/deactivate-behavior.js +0 -263
  102. package/dist/mcp/tools/list-reminders.js +0 -62
  103. package/dist/mcp/tools/list-tasks.js +0 -463
  104. package/dist/mcp/tools/send-message.js +0 -1382
  105. package/dist/mcp/tools/update-task.js +0 -1692
  106. package/dist/runtime/index.js +0 -6809
  107. package/dist/tui/App.js +0 -17479
@@ -1,850 +0,0 @@
1
- #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error('Dynamic require of "' + x + '" is not supported');
9
- });
10
- var __esm = (fn, res) => function __init() {
11
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
- };
13
- var __export = (target, all) => {
14
- for (var name in all)
15
- __defProp(target, name, { get: all[name], enumerable: true });
16
- };
17
-
18
- // src/lib/config.ts
19
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
20
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
21
- import path2 from "path";
22
- import os from "os";
23
- function resolveDataDir() {
24
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
25
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
26
- const newDir = path2.join(os.homedir(), ".exe-os");
27
- const legacyDir = path2.join(os.homedir(), ".exe-mem");
28
- if (!existsSync2(newDir) && existsSync2(legacyDir)) {
29
- try {
30
- renameSync(legacyDir, newDir);
31
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
32
- `);
33
- } catch {
34
- return legacyDir;
35
- }
36
- }
37
- return newDir;
38
- }
39
- function migrateLegacyConfig(raw) {
40
- if ("r2" in raw) {
41
- process.stderr.write(
42
- "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
43
- );
44
- delete raw.r2;
45
- }
46
- if ("syncIntervalMs" in raw) {
47
- delete raw.syncIntervalMs;
48
- }
49
- return raw;
50
- }
51
- function migrateConfig(raw) {
52
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
53
- let currentVersion = fromVersion;
54
- let migrated = false;
55
- if (currentVersion > CURRENT_CONFIG_VERSION) {
56
- return { config: raw, migrated: false, fromVersion };
57
- }
58
- for (const migration of CONFIG_MIGRATIONS) {
59
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
60
- raw = migration.migrate(raw);
61
- currentVersion = migration.to;
62
- migrated = true;
63
- }
64
- }
65
- return { config: raw, migrated, fromVersion };
66
- }
67
- function normalizeScalingRoadmap(raw) {
68
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
69
- const userRoadmap = raw.scalingRoadmap ?? {};
70
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
71
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
72
- userAuto.enabled = raw.rerankerEnabled;
73
- }
74
- raw.scalingRoadmap = {
75
- ...userRoadmap,
76
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
77
- };
78
- }
79
- function normalizeSessionLifecycle(raw) {
80
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
81
- const userSL = raw.sessionLifecycle ?? {};
82
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
83
- }
84
- async function loadConfig() {
85
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
86
- await mkdir2(dir, { recursive: true });
87
- const configPath = path2.join(dir, "config.json");
88
- if (!existsSync2(configPath)) {
89
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
90
- }
91
- const raw = await readFile2(configPath, "utf-8");
92
- try {
93
- let parsed = JSON.parse(raw);
94
- parsed = migrateLegacyConfig(parsed);
95
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
96
- if (migrated) {
97
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
98
- `);
99
- try {
100
- await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
101
- } catch {
102
- }
103
- }
104
- normalizeScalingRoadmap(migratedCfg);
105
- normalizeSessionLifecycle(migratedCfg);
106
- const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
107
- if (config.dbPath.startsWith("~")) {
108
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
109
- }
110
- return config;
111
- } catch {
112
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
113
- }
114
- }
115
- async function saveConfig(config) {
116
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
117
- await mkdir2(dir, { recursive: true });
118
- const configPath = path2.join(dir, "config.json");
119
- await writeFile2(configPath, JSON.stringify(config, null, 2) + "\n");
120
- }
121
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
122
- var init_config = __esm({
123
- "src/lib/config.ts"() {
124
- "use strict";
125
- EXE_AI_DIR = resolveDataDir();
126
- DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
127
- MODELS_DIR = path2.join(EXE_AI_DIR, "models");
128
- CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
129
- LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
130
- CURRENT_CONFIG_VERSION = 1;
131
- DEFAULT_CONFIG = {
132
- config_version: CURRENT_CONFIG_VERSION,
133
- dbPath: DB_PATH,
134
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
135
- embeddingDim: 1024,
136
- batchSize: 20,
137
- flushIntervalMs: 1e4,
138
- autoIngestion: true,
139
- autoRetrieval: true,
140
- searchMode: "hybrid",
141
- hookSearchMode: "hybrid",
142
- fileGrepEnabled: true,
143
- splashEffect: true,
144
- consolidationEnabled: true,
145
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
146
- consolidationModel: "claude-haiku-4-5-20251001",
147
- consolidationMaxCallsPerRun: 20,
148
- selfQueryRouter: true,
149
- selfQueryModel: "claude-haiku-4-5-20251001",
150
- rerankerEnabled: true,
151
- scalingRoadmap: {
152
- rerankerAutoTrigger: {
153
- enabled: true,
154
- broadQueryMinCardinality: 5e4,
155
- fetchTopK: 150,
156
- returnTopK: 5
157
- }
158
- },
159
- graphRagEnabled: true,
160
- wikiEnabled: false,
161
- wikiUrl: "",
162
- wikiApiKey: "",
163
- wikiSyncIntervalMs: 30 * 60 * 1e3,
164
- wikiWorkspaceMapping: {
165
- exe: "Executive",
166
- yoshi: "Engineering",
167
- mari: "Marketing",
168
- tom: "Engineering",
169
- sasha: "Production"
170
- },
171
- wikiAutoUpdate: true,
172
- wikiAutoUpdateThreshold: 0.5,
173
- wikiAutoUpdateCreateNew: true,
174
- skillLearning: true,
175
- skillThreshold: 3,
176
- skillModel: "claude-haiku-4-5-20251001",
177
- exeHeartbeat: {
178
- enabled: true,
179
- intervalSeconds: 60,
180
- staleInProgressThresholdHours: 2
181
- },
182
- sessionLifecycle: {
183
- idleKillEnabled: true,
184
- idleKillTicksRequired: 3,
185
- idleKillIntercomAckWindowMs: 1e4,
186
- maxAutoInstances: 10
187
- }
188
- };
189
- CONFIG_MIGRATIONS = [
190
- {
191
- from: 0,
192
- to: 1,
193
- migrate: (cfg) => {
194
- cfg.config_version = 1;
195
- return cfg;
196
- }
197
- }
198
- ];
199
- }
200
- });
201
-
202
- // src/lib/license.ts
203
- var license_exports = {};
204
- __export(license_exports, {
205
- LICENSE_PUBLIC_KEY_PEM: () => LICENSE_PUBLIC_KEY_PEM,
206
- PLAN_LIMITS: () => PLAN_LIMITS,
207
- assertVpsLicense: () => assertVpsLicense,
208
- checkLicense: () => checkLicense,
209
- getCachedLicense: () => getCachedLicense,
210
- isFeatureAllowed: () => isFeatureAllowed,
211
- loadDeviceId: () => loadDeviceId,
212
- loadLicense: () => loadLicense,
213
- mirrorLicenseKey: () => mirrorLicenseKey,
214
- saveLicense: () => saveLicense,
215
- validateLicense: () => validateLicense
216
- });
217
- import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync3, mkdirSync } from "fs";
218
- import { randomUUID } from "crypto";
219
- import path3 from "path";
220
- import { jwtVerify, importSPKI } from "jose";
221
- function loadDeviceId() {
222
- const deviceJsonPath = path3.join(EXE_AI_DIR, "device.json");
223
- try {
224
- if (existsSync3(deviceJsonPath)) {
225
- const data = JSON.parse(readFileSync2(deviceJsonPath, "utf8"));
226
- if (data.deviceId) return data.deviceId;
227
- }
228
- } catch {
229
- }
230
- try {
231
- if (existsSync3(DEVICE_ID_PATH)) {
232
- const id2 = readFileSync2(DEVICE_ID_PATH, "utf8").trim();
233
- if (id2) return id2;
234
- }
235
- } catch {
236
- }
237
- const id = randomUUID();
238
- mkdirSync(EXE_AI_DIR, { recursive: true });
239
- writeFileSync(DEVICE_ID_PATH, id, "utf8");
240
- return id;
241
- }
242
- function loadLicense() {
243
- try {
244
- if (!existsSync3(LICENSE_PATH)) return null;
245
- return readFileSync2(LICENSE_PATH, "utf8").trim();
246
- } catch {
247
- return null;
248
- }
249
- }
250
- function saveLicense(apiKey) {
251
- mkdirSync(EXE_AI_DIR, { recursive: true });
252
- writeFileSync(LICENSE_PATH, apiKey.trim(), "utf8");
253
- }
254
- async function verifyLicenseJwt(token) {
255
- try {
256
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
257
- const { payload } = await jwtVerify(token, key, {
258
- algorithms: [LICENSE_JWT_ALG]
259
- });
260
- const plan = payload.plan ?? "free";
261
- const email = payload.sub ?? "";
262
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
263
- return {
264
- valid: true,
265
- plan,
266
- email,
267
- expiresAt: payload.exp ? new Date(payload.exp * 1e3).toISOString() : null,
268
- deviceLimit: limits.devices,
269
- employeeLimit: limits.employees,
270
- memoryLimit: limits.memories
271
- };
272
- } catch {
273
- return null;
274
- }
275
- }
276
- async function getCachedLicense() {
277
- try {
278
- if (!existsSync3(CACHE_PATH)) return null;
279
- const raw = JSON.parse(readFileSync2(CACHE_PATH, "utf8"));
280
- if (!raw.token || typeof raw.token !== "string") return null;
281
- return await verifyLicenseJwt(raw.token);
282
- } catch {
283
- return null;
284
- }
285
- }
286
- function readCachedToken() {
287
- try {
288
- if (!existsSync3(CACHE_PATH)) return null;
289
- const raw = JSON.parse(readFileSync2(CACHE_PATH, "utf8"));
290
- return typeof raw.token === "string" ? raw.token : null;
291
- } catch {
292
- return null;
293
- }
294
- }
295
- function cacheResponse(token) {
296
- try {
297
- writeFileSync(CACHE_PATH, JSON.stringify({ token }), "utf8");
298
- } catch {
299
- }
300
- }
301
- async function validateLicense(apiKey, deviceId) {
302
- const did = deviceId ?? loadDeviceId();
303
- try {
304
- const res = await fetch(`${API_BASE}/auth/activate`, {
305
- method: "POST",
306
- headers: { "Content-Type": "application/json" },
307
- body: JSON.stringify({ apiKey, deviceId: did }),
308
- signal: AbortSignal.timeout(1e4)
309
- });
310
- if (res.ok) {
311
- const data = await res.json();
312
- if (data.error === "device_limit_exceeded") {
313
- const cached2 = await getCachedLicense();
314
- if (cached2) return cached2;
315
- return { ...FREE_LICENSE, valid: false, plan: "free" };
316
- }
317
- if (data.token) {
318
- cacheResponse(data.token);
319
- const verified = await verifyLicenseJwt(data.token);
320
- if (verified) return verified;
321
- }
322
- const limits = PLAN_LIMITS[data.plan] ?? PLAN_LIMITS.free;
323
- return {
324
- valid: data.valid,
325
- plan: data.plan,
326
- email: data.email,
327
- expiresAt: data.expiresAt,
328
- deviceLimit: limits.devices,
329
- employeeLimit: limits.employees,
330
- memoryLimit: limits.memories
331
- };
332
- }
333
- const cached = await getCachedLicense();
334
- if (cached) return cached;
335
- return { ...FREE_LICENSE, valid: false, plan: "free" };
336
- } catch {
337
- const cached = await getCachedLicense();
338
- if (cached) return cached;
339
- return FREE_LICENSE;
340
- }
341
- }
342
- async function checkLicense() {
343
- const key = loadLicense();
344
- if (!key) return FREE_LICENSE;
345
- const cached = await getCachedLicense();
346
- if (cached) return cached;
347
- const deviceId = loadDeviceId();
348
- return validateLicense(key, deviceId);
349
- }
350
- function isFeatureAllowed(license, feature) {
351
- switch (feature) {
352
- case "cloud_sync":
353
- case "external_agents":
354
- case "wiki":
355
- return license.plan !== "free";
356
- case "unlimited_employees":
357
- return license.plan === "team" || license.plan === "agency" || license.plan === "enterprise";
358
- }
359
- }
360
- function mirrorLicenseKey(apiKey) {
361
- const trimmed = apiKey.trim();
362
- if (!trimmed) return;
363
- saveLicense(trimmed);
364
- }
365
- async function assertVpsLicense(opts) {
366
- const env = opts?.env ?? process.env;
367
- const inProduction = env.NODE_ENV === "production";
368
- if (!opts?.force && !inProduction) {
369
- return { ...FREE_LICENSE, plan: "free" };
370
- }
371
- const envKey = env.EXE_LICENSE_KEY?.trim();
372
- if (envKey) {
373
- saveLicense(envKey);
374
- }
375
- const apiKey = envKey ?? loadLicense();
376
- if (!apiKey) {
377
- throw new Error(
378
- "License required: set EXE_LICENSE_KEY env var with your exe_sk_* key. Purchase at https://askexe.com. This VPS image refuses to boot without a valid license."
379
- );
380
- }
381
- const deviceId = loadDeviceId();
382
- let backendResponse = null;
383
- let explicitRejection = false;
384
- let transientFailure = false;
385
- try {
386
- const res = await fetch(`${API_BASE}/auth/activate`, {
387
- method: "POST",
388
- headers: { "Content-Type": "application/json" },
389
- body: JSON.stringify({ apiKey, deviceId }),
390
- signal: AbortSignal.timeout(1e4)
391
- });
392
- if (res.ok) {
393
- backendResponse = await res.json();
394
- if (!backendResponse.valid) explicitRejection = true;
395
- } else if (res.status === 401 || res.status === 403) {
396
- explicitRejection = true;
397
- } else {
398
- transientFailure = true;
399
- }
400
- } catch {
401
- transientFailure = true;
402
- }
403
- if (backendResponse?.valid) {
404
- if (backendResponse.token) {
405
- cacheResponse(backendResponse.token);
406
- const verified = await verifyLicenseJwt(backendResponse.token);
407
- if (verified) return verified;
408
- }
409
- const limits = PLAN_LIMITS[backendResponse.plan] ?? PLAN_LIMITS.free;
410
- return {
411
- valid: true,
412
- plan: backendResponse.plan,
413
- email: backendResponse.email,
414
- expiresAt: backendResponse.expiresAt,
415
- deviceLimit: limits.devices,
416
- employeeLimit: limits.employees,
417
- memoryLimit: limits.memories
418
- };
419
- }
420
- if (explicitRejection) {
421
- throw new Error(
422
- `License invalid or expired. Renew at https://askexe.com, then restart. Backend rejected key ending in ...${apiKey.slice(-4)}.`
423
- );
424
- }
425
- if (!transientFailure) {
426
- throw new Error(
427
- "License validation failed: unknown backend state. Restore network connectivity to https://askexe.com/cloud and retry."
428
- );
429
- }
430
- const fresh = await getCachedLicense();
431
- if (fresh && fresh.valid) return fresh;
432
- const graceDays = opts?.offlineGraceDays ?? 7;
433
- const graceMs = graceDays * 24 * 60 * 60 * 1e3;
434
- try {
435
- const token = readCachedToken();
436
- if (token) {
437
- const payloadB64 = token.split(".")[1];
438
- if (payloadB64) {
439
- const payload = JSON.parse(Buffer.from(payloadB64, "base64url").toString());
440
- const expMs = (payload.exp ?? 0) * 1e3;
441
- if (Date.now() < expMs + graceMs) {
442
- const key = await importSPKI(LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG);
443
- const { payload: verified } = await jwtVerify(token, key, {
444
- algorithms: [LICENSE_JWT_ALG],
445
- clockTolerance: graceDays * 24 * 60 * 60
446
- });
447
- const plan = verified.plan ?? "free";
448
- const limits = PLAN_LIMITS[plan] ?? PLAN_LIMITS.free;
449
- return {
450
- valid: true,
451
- plan,
452
- email: verified.sub ?? "",
453
- expiresAt: verified.exp ? new Date(verified.exp * 1e3).toISOString() : null,
454
- deviceLimit: limits.devices,
455
- employeeLimit: limits.employees,
456
- memoryLimit: limits.memories
457
- };
458
- }
459
- }
460
- }
461
- } catch {
462
- }
463
- throw new Error(
464
- `License validation unreachable for more than ${graceDays} days. Restore network connectivity to https://askexe.com/cloud and retry. This VPS image refuses to boot after the offline grace window.`
465
- );
466
- }
467
- var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH, API_BASE, LICENSE_PUBLIC_KEY_PEM, LICENSE_JWT_ALG, PLAN_LIMITS, FREE_LICENSE;
468
- var init_license = __esm({
469
- "src/lib/license.ts"() {
470
- "use strict";
471
- init_config();
472
- LICENSE_PATH = path3.join(EXE_AI_DIR, "license.key");
473
- CACHE_PATH = path3.join(EXE_AI_DIR, "license-cache.json");
474
- DEVICE_ID_PATH = path3.join(EXE_AI_DIR, "device-id");
475
- API_BASE = "https://askexe.com/cloud";
476
- LICENSE_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
477
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEeHztAMOpR/ZMh+rWuOASjEZ54CGY
478
- 4uj+UqeKCcvtgNHKmOK278HJaJcANe9xAeji8AFYu27q3WtzCi04pHudow==
479
- -----END PUBLIC KEY-----`;
480
- LICENSE_JWT_ALG = "ES256";
481
- PLAN_LIMITS = {
482
- free: { devices: 1, employees: 1, memories: 5e3 },
483
- pro: { devices: 2, employees: 5, memories: 1e5 },
484
- team: { devices: 10, employees: 20, memories: 1e6 },
485
- agency: { devices: 50, employees: 100, memories: 1e7 },
486
- enterprise: { devices: -1, employees: -1, memories: -1 }
487
- };
488
- FREE_LICENSE = {
489
- valid: true,
490
- plan: "free",
491
- email: "",
492
- expiresAt: null,
493
- deviceLimit: 1,
494
- employeeLimit: 1,
495
- memoryLimit: 5e3
496
- };
497
- }
498
- });
499
-
500
- // src/bin/exe-cloud.ts
501
- import { createInterface } from "readline";
502
-
503
- // src/lib/keychain.ts
504
- import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
505
- import { existsSync } from "fs";
506
- import path from "path";
507
- import crypto from "crypto";
508
- var SERVICE = "exe-mem";
509
- var ACCOUNT = "master-key";
510
- function getKeyDir() {
511
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path.join(process.env.HOME ?? "/tmp", ".exe-os");
512
- }
513
- function getKeyPath() {
514
- return path.join(getKeyDir(), "master.key");
515
- }
516
- async function tryKeytar() {
517
- try {
518
- return await import("keytar");
519
- } catch {
520
- return null;
521
- }
522
- }
523
- async function getMasterKey() {
524
- const keytar = await tryKeytar();
525
- if (keytar) {
526
- try {
527
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
528
- if (stored) {
529
- return Buffer.from(stored, "base64");
530
- }
531
- } catch {
532
- }
533
- }
534
- const keyPath = getKeyPath();
535
- if (!existsSync(keyPath)) {
536
- return null;
537
- }
538
- try {
539
- const content = await readFile(keyPath, "utf-8");
540
- return Buffer.from(content.trim(), "base64");
541
- } catch {
542
- return null;
543
- }
544
- }
545
- async function setMasterKey(key) {
546
- const b64 = key.toString("base64");
547
- const keytar = await tryKeytar();
548
- if (keytar) {
549
- try {
550
- await keytar.setPassword(SERVICE, ACCOUNT, b64);
551
- return;
552
- } catch {
553
- }
554
- }
555
- const dir = getKeyDir();
556
- await mkdir(dir, { recursive: true });
557
- const keyPath = getKeyPath();
558
- await writeFile(keyPath, b64 + "\n", "utf-8");
559
- await chmod(keyPath, 384);
560
- }
561
- function exportMnemonic(key) {
562
- if (key.length !== 32) {
563
- throw new Error(`Key must be 32 bytes, got ${key.length}`);
564
- }
565
- const hash = crypto.createHash("sha256").update(key).digest();
566
- const checksumByte = hash[0];
567
- let bits = "";
568
- for (const byte of key) {
569
- bits += byte.toString(2).padStart(8, "0");
570
- }
571
- bits += checksumByte.toString(2).padStart(8, "0");
572
- const words = [];
573
- let wordlist;
574
- try {
575
- const bip39 = __require("bip39");
576
- wordlist = bip39.wordlists?.english ?? bip39.default?.wordlists?.english;
577
- if (!wordlist) throw new Error("no wordlist");
578
- } catch {
579
- throw new Error("bip39 package required. Install with: npm install bip39");
580
- }
581
- for (let i = 0; i < 264; i += 11) {
582
- const index = parseInt(bits.slice(i, i + 11), 2);
583
- words.push(wordlist[index]);
584
- }
585
- return words.join(" ");
586
- }
587
- function importMnemonic(mnemonic) {
588
- const words = mnemonic.trim().split(/\s+/);
589
- if (words.length !== 24) {
590
- throw new Error(`Expected 24 words, got ${words.length}`);
591
- }
592
- let wordlist;
593
- try {
594
- const bip39 = __require("bip39");
595
- wordlist = bip39.wordlists?.english ?? bip39.default?.wordlists?.english;
596
- if (!wordlist) throw new Error("no wordlist");
597
- } catch {
598
- throw new Error("bip39 package required. Install with: npm install bip39");
599
- }
600
- let bits = "";
601
- for (const word of words) {
602
- const index = wordlist.indexOf(word.toLowerCase());
603
- if (index === -1) {
604
- throw new Error(`Invalid BIP39 word: "${word}"`);
605
- }
606
- bits += index.toString(2).padStart(11, "0");
607
- }
608
- const entropyBits = bits.slice(0, 256);
609
- const checksumBits = bits.slice(256, 264);
610
- const key = Buffer.alloc(32);
611
- for (let i = 0; i < 32; i++) {
612
- key[i] = parseInt(entropyBits.slice(i * 8, (i + 1) * 8), 2);
613
- }
614
- const hash = crypto.createHash("sha256").update(key).digest();
615
- const expectedChecksum = hash[0].toString(2).padStart(8, "0");
616
- if (checksumBits !== expectedChecksum) {
617
- throw new Error("Invalid mnemonic checksum");
618
- }
619
- return key;
620
- }
621
-
622
- // src/bin/exe-cloud.ts
623
- init_config();
624
-
625
- // src/lib/ws-auth.ts
626
- import crypto2 from "crypto";
627
- var WS_AUTH_HKDF_INFO = "exe-os-ws-auth-v1";
628
- var ORG_ID_HKDF_INFO = "exe-os-org-id-v1";
629
- function deriveWsAuthToken(masterKey) {
630
- return Buffer.from(crypto2.hkdfSync("sha256", masterKey, "", WS_AUTH_HKDF_INFO, 32));
631
- }
632
- function deriveOrgId(masterKey) {
633
- const raw = Buffer.from(crypto2.hkdfSync("sha256", masterKey, "", ORG_ID_HKDF_INFO, 32));
634
- return crypto2.createHash("sha256").update(raw).digest("hex").slice(0, 32);
635
- }
636
- function hashAuthToken(token) {
637
- return crypto2.createHash("sha256").update(token).digest("hex");
638
- }
639
-
640
- // src/lib/is-main.ts
641
- import { realpathSync } from "fs";
642
- import { fileURLToPath } from "url";
643
- function isMainModule(importMetaUrl) {
644
- if (process.argv[1] == null) return false;
645
- try {
646
- const scriptPath = realpathSync(process.argv[1]);
647
- const modulePath = realpathSync(fileURLToPath(importMetaUrl));
648
- return scriptPath === modulePath;
649
- } catch {
650
- return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
651
- }
652
- }
653
-
654
- // src/bin/exe-cloud.ts
655
- var BAR = "\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550";
656
- function ask(rl, question) {
657
- return new Promise((resolve) => {
658
- rl.question(question, (answer) => resolve(answer.trim()));
659
- });
660
- }
661
- async function setupMode() {
662
- const rl = createInterface({ input: process.stdin, output: process.stdout });
663
- console.log(BAR);
664
- console.log(" EXE CLOUD SETUP");
665
- console.log(BAR);
666
- console.log("");
667
- console.log("Step 1: Encryption Key");
668
- const existingKey = await getMasterKey();
669
- if (existingKey) {
670
- console.log(" \u2713 Master key already present. Skipping.\n");
671
- } else {
672
- const hasPhrase = await ask(rl, " Do you have a 24-word recovery phrase from another device? (y/n) ");
673
- if (hasPhrase.toLowerCase().startsWith("y")) {
674
- const mnemonic = await ask(rl, " Paste your 24 words: ");
675
- try {
676
- const key = importMnemonic(mnemonic);
677
- await setMasterKey(key);
678
- console.log(" \u2713 Key imported.\n");
679
- } catch (err) {
680
- console.error(` \u2717 Invalid mnemonic: ${err instanceof Error ? err.message : String(err)}`);
681
- rl.close();
682
- process.exit(1);
683
- }
684
- } else {
685
- console.log(" No recovery phrase \u2014 run /exe-setup on your first device to generate one.");
686
- console.log(" Then use /exe-cloud sync on that device to get the phrase.\n");
687
- rl.close();
688
- return;
689
- }
690
- }
691
- console.log("Step 2: Cloud Sync");
692
- const config = await loadConfig();
693
- if (config.cloud?.apiKey) {
694
- console.log(` \u2713 Cloud already configured (${config.cloud.endpoint}).
695
- `);
696
- const masterKey = await getMasterKey();
697
- if (masterKey) {
698
- const orgId = deriveOrgId(masterKey);
699
- const authTokenHash = hashAuthToken(deriveWsAuthToken(masterKey));
700
- try {
701
- const regResp = await fetch(`${config.cloud.endpoint}/api/register-org`, {
702
- method: "POST",
703
- headers: { Authorization: `Bearer ${config.cloud.apiKey}`, "Content-Type": "application/json" },
704
- body: JSON.stringify({ orgId, authTokenHash })
705
- });
706
- if (regResp.ok) {
707
- console.log(" \u2713 Org registered for cross-machine messaging.\n");
708
- }
709
- } catch {
710
- }
711
- }
712
- } else {
713
- const apiKey = await ask(rl, " Paste your API key (exe_sk_...): ");
714
- if (!apiKey) {
715
- console.log(" Skipped. Use /exe-settings to configure later.");
716
- rl.close();
717
- return;
718
- }
719
- const endpoint = await ask(rl, " Endpoint [https://askexe.com/cloud]: ") || "https://askexe.com/cloud";
720
- console.log(" Validating...");
721
- try {
722
- const resp = await fetch(`${endpoint}/auth/verify`, {
723
- method: "POST",
724
- headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }
725
- });
726
- if (resp.ok) {
727
- config.cloud = { apiKey, endpoint };
728
- await saveConfig(config);
729
- try {
730
- const { mirrorLicenseKey: mirrorLicenseKey2 } = await Promise.resolve().then(() => (init_license(), license_exports));
731
- mirrorLicenseKey2(apiKey);
732
- } catch {
733
- }
734
- console.log(" \u2713 Cloud sync configured.\n");
735
- const masterKey = await getMasterKey();
736
- if (masterKey) {
737
- console.log("Step 3: Cross-Machine Messaging");
738
- const orgId = deriveOrgId(masterKey);
739
- const authTokenHash = hashAuthToken(deriveWsAuthToken(masterKey));
740
- try {
741
- const regResp = await fetch(`${endpoint}/api/register-org`, {
742
- method: "POST",
743
- headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
744
- body: JSON.stringify({ orgId, authTokenHash })
745
- });
746
- if (regResp.ok) {
747
- console.log(" \u2713 Org registered for cross-machine messaging.\n");
748
- } else {
749
- console.log(` \u26A0 Org registration failed (${regResp.status}). WS relay may not work.
750
- `);
751
- }
752
- } catch {
753
- console.log(" \u26A0 Org registration failed (network). WS relay may not work.\n");
754
- }
755
- }
756
- } else {
757
- console.log(` \u2717 Validation failed (${resp.status}). Key not saved.`);
758
- rl.close();
759
- process.exit(1);
760
- }
761
- } catch (err) {
762
- console.log(` \u2717 Could not reach endpoint: ${err instanceof Error ? err.message : String(err)}`);
763
- rl.close();
764
- process.exit(1);
765
- }
766
- }
767
- console.log(BAR);
768
- console.log(" Setup complete. Memories will sync now.");
769
- console.log(BAR);
770
- rl.close();
771
- }
772
- async function syncMode() {
773
- const key = await getMasterKey();
774
- if (!key) {
775
- console.error("No master key found. Run /exe-setup first.");
776
- process.exit(1);
777
- }
778
- const config = await loadConfig();
779
- const mnemonic = exportMnemonic(key);
780
- console.log(BAR);
781
- console.log(" EXE CLOUD \u2014 DEVICE SYNC INFO");
782
- console.log(BAR);
783
- console.log("");
784
- console.log("Run /exe-cloud on the new device and paste these when prompted:\n");
785
- console.log(" 24-word recovery phrase:");
786
- console.log(` ${mnemonic}
787
- `);
788
- if (config.cloud?.apiKey) {
789
- console.log(" Cloud API key:");
790
- console.log(` ${config.cloud.apiKey}
791
- `);
792
- console.log(" Endpoint:");
793
- console.log(` ${config.cloud.endpoint}
794
- `);
795
- } else {
796
- console.log(" Cloud sync: not configured (local-only)\n");
797
- }
798
- console.log("\u26A0 Anyone with the recovery phrase can decrypt your memories.");
799
- console.log(BAR);
800
- }
801
- async function statusMode() {
802
- const key = await getMasterKey();
803
- const config = await loadConfig();
804
- console.log(BAR);
805
- console.log(" EXE CLOUD STATUS");
806
- console.log(BAR);
807
- console.log("");
808
- if (key) {
809
- const fingerprint = key.toString("hex").slice(0, 8);
810
- console.log(` Encryption key: \u2713 present (${fingerprint}...)`);
811
- } else {
812
- console.log(" Encryption key: \u2717 not found \u2014 run /exe-setup");
813
- }
814
- if (config.cloud?.apiKey) {
815
- const masked = config.cloud.apiKey.slice(0, 10) + "..." + config.cloud.apiKey.slice(-4);
816
- console.log(` Cloud sync: \u2713 Exe Cloud (${masked})`);
817
- console.log(` Endpoint: ${config.cloud.endpoint}`);
818
- } else if (config.turso?.url) {
819
- console.log(` Cloud sync: \u2713 libSQL (legacy) (${config.turso.url})`);
820
- } else {
821
- console.log(" Cloud sync: local-only");
822
- }
823
- console.log("");
824
- console.log(BAR);
825
- }
826
- async function main() {
827
- const mode = process.argv[2]?.toLowerCase();
828
- if (mode === "sync") {
829
- await syncMode();
830
- } else if (mode === "status") {
831
- await statusMode();
832
- } else if (!mode || mode === "setup") {
833
- await setupMode();
834
- } else {
835
- console.error("Usage:");
836
- console.error(" exe-cloud \u2014 full device setup (key + cloud)");
837
- console.error(" exe-cloud sync \u2014 export info for new device");
838
- console.error(" exe-cloud status \u2014 show current sync status");
839
- process.exit(1);
840
- }
841
- }
842
- if (isMainModule(import.meta.url)) {
843
- main().catch((err) => {
844
- console.error(err instanceof Error ? err.message : String(err));
845
- process.exit(1);
846
- });
847
- }
848
- export {
849
- main
850
- };