@askexenow/exe-os 0.9.7 → 0.9.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/backfill-conversations.js +953 -105
- package/dist/bin/backfill-responses.js +952 -104
- package/dist/bin/backfill-vectors.js +956 -108
- package/dist/bin/cleanup-stale-review-tasks.js +802 -58
- package/dist/bin/cli.js +2292 -1070
- package/dist/bin/exe-agent-config.js +157 -101
- package/dist/bin/exe-agent.js +55 -29
- package/dist/bin/exe-assign.js +940 -92
- package/dist/bin/exe-boot.js +1424 -442
- package/dist/bin/exe-call.js +240 -141
- package/dist/bin/exe-cloud.js +198 -70
- package/dist/bin/exe-dispatch.js +951 -192
- package/dist/bin/exe-doctor.js +791 -51
- package/dist/bin/exe-export-behaviors.js +790 -42
- package/dist/bin/exe-forget.js +771 -31
- package/dist/bin/exe-gateway.js +1592 -521
- package/dist/bin/exe-heartbeat.js +850 -109
- package/dist/bin/exe-kill.js +783 -35
- package/dist/bin/exe-launch-agent.js +1030 -107
- package/dist/bin/exe-link.js +916 -110
- package/dist/bin/exe-new-employee.js +526 -217
- package/dist/bin/exe-pending-messages.js +1046 -62
- package/dist/bin/exe-pending-notifications.js +1318 -111
- package/dist/bin/exe-pending-reviews.js +1040 -72
- package/dist/bin/exe-rename.js +772 -59
- package/dist/bin/exe-review.js +772 -32
- package/dist/bin/exe-search.js +982 -128
- package/dist/bin/exe-session-cleanup.js +1180 -306
- package/dist/bin/exe-settings.js +185 -105
- package/dist/bin/exe-start-codex.js +886 -132
- package/dist/bin/exe-start-opencode.js +873 -119
- package/dist/bin/exe-status.js +803 -59
- package/dist/bin/exe-team.js +772 -32
- package/dist/bin/git-sweep.js +1046 -223
- package/dist/bin/graph-backfill.js +779 -31
- package/dist/bin/graph-export.js +785 -37
- package/dist/bin/install.js +632 -200
- package/dist/bin/scan-tasks.js +1055 -232
- package/dist/bin/setup.js +1419 -320
- package/dist/bin/shard-migrate.js +783 -35
- package/dist/bin/update.js +138 -49
- package/dist/bin/wiki-sync.js +782 -34
- package/dist/gateway/index.js +1444 -449
- package/dist/hooks/bug-report-worker.js +1141 -269
- package/dist/hooks/codex-stop-task-finalizer.js +4678 -0
- package/dist/hooks/commit-complete.js +1044 -221
- package/dist/hooks/error-recall.js +989 -135
- package/dist/hooks/exe-heartbeat-hook.js +99 -75
- package/dist/hooks/ingest-worker.js +4176 -3226
- package/dist/hooks/ingest.js +920 -168
- package/dist/hooks/instructions-loaded.js +874 -70
- package/dist/hooks/notification.js +860 -56
- package/dist/hooks/post-compact.js +881 -73
- package/dist/hooks/pre-compact.js +1050 -227
- package/dist/hooks/pre-tool-use.js +1084 -159
- package/dist/hooks/prompt-ingest-worker.js +1089 -164
- package/dist/hooks/prompt-submit.js +1469 -515
- package/dist/hooks/response-ingest-worker.js +1104 -179
- package/dist/hooks/session-end.js +1085 -251
- package/dist/hooks/session-start.js +1241 -231
- package/dist/hooks/stop.js +935 -109
- package/dist/hooks/subagent-stop.js +881 -73
- package/dist/hooks/summary-worker.js +1323 -307
- package/dist/index.js +1449 -452
- package/dist/lib/agent-config.js +28 -6
- package/dist/lib/cloud-sync.js +909 -115
- package/dist/lib/config.js +30 -10
- package/dist/lib/consolidation.js +42 -9
- package/dist/lib/database.js +739 -33
- package/dist/lib/db-daemon-client.js +73 -19
- package/dist/lib/db.js +2359 -0
- package/dist/lib/device-registry.js +760 -47
- package/dist/lib/embedder.js +201 -73
- package/dist/lib/employee-templates.js +30 -4
- package/dist/lib/employees.js +290 -86
- package/dist/lib/exe-daemon-client.js +187 -83
- package/dist/lib/exe-daemon.js +1696 -616
- package/dist/lib/hybrid-search.js +982 -128
- package/dist/lib/identity.js +43 -13
- package/dist/lib/license.js +133 -48
- package/dist/lib/messaging.js +167 -80
- package/dist/lib/reminders.js +35 -5
- package/dist/lib/schedules.js +772 -32
- package/dist/lib/skill-learning.js +54 -7
- package/dist/lib/store.js +779 -31
- package/dist/lib/task-router.js +94 -73
- package/dist/lib/tasks.js +298 -225
- package/dist/lib/tmux-routing.js +246 -172
- package/dist/lib/token-spend.js +52 -14
- package/dist/mcp/server.js +2893 -850
- package/dist/mcp/tools/complete-reminder.js +35 -5
- package/dist/mcp/tools/create-reminder.js +35 -5
- package/dist/mcp/tools/create-task.js +507 -323
- package/dist/mcp/tools/deactivate-behavior.js +40 -10
- package/dist/mcp/tools/list-reminders.js +35 -5
- package/dist/mcp/tools/list-tasks.js +277 -104
- package/dist/mcp/tools/send-message.js +129 -56
- package/dist/mcp/tools/update-task.js +1864 -188
- package/dist/runtime/index.js +1083 -259
- package/dist/tui/App.js +1501 -434
- package/package.json +3 -2
package/dist/bin/exe-assign.js
CHANGED
|
@@ -9,9 +9,47 @@ var __export = (target, all) => {
|
|
|
9
9
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
10
|
};
|
|
11
11
|
|
|
12
|
+
// src/lib/secure-files.ts
|
|
13
|
+
import { chmodSync, existsSync, mkdirSync } from "fs";
|
|
14
|
+
import { chmod, mkdir } from "fs/promises";
|
|
15
|
+
async function ensurePrivateDir(dirPath) {
|
|
16
|
+
await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
17
|
+
try {
|
|
18
|
+
await chmod(dirPath, PRIVATE_DIR_MODE);
|
|
19
|
+
} catch {
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function ensurePrivateDirSync(dirPath) {
|
|
23
|
+
mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
24
|
+
try {
|
|
25
|
+
chmodSync(dirPath, PRIVATE_DIR_MODE);
|
|
26
|
+
} catch {
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function enforcePrivateFile(filePath) {
|
|
30
|
+
try {
|
|
31
|
+
await chmod(filePath, PRIVATE_FILE_MODE);
|
|
32
|
+
} catch {
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function enforcePrivateFileSync(filePath) {
|
|
36
|
+
try {
|
|
37
|
+
if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
|
|
38
|
+
} catch {
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
|
|
42
|
+
var init_secure_files = __esm({
|
|
43
|
+
"src/lib/secure-files.ts"() {
|
|
44
|
+
"use strict";
|
|
45
|
+
PRIVATE_DIR_MODE = 448;
|
|
46
|
+
PRIVATE_FILE_MODE = 384;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
12
50
|
// src/lib/config.ts
|
|
13
|
-
import { readFile, writeFile
|
|
14
|
-
import { readFileSync, existsSync, renameSync } from "fs";
|
|
51
|
+
import { readFile, writeFile } from "fs/promises";
|
|
52
|
+
import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
|
|
15
53
|
import path from "path";
|
|
16
54
|
import os from "os";
|
|
17
55
|
function resolveDataDir() {
|
|
@@ -19,7 +57,7 @@ function resolveDataDir() {
|
|
|
19
57
|
if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
|
|
20
58
|
const newDir = path.join(os.homedir(), ".exe-os");
|
|
21
59
|
const legacyDir = path.join(os.homedir(), ".exe-mem");
|
|
22
|
-
if (!
|
|
60
|
+
if (!existsSync2(newDir) && existsSync2(legacyDir)) {
|
|
23
61
|
try {
|
|
24
62
|
renameSync(legacyDir, newDir);
|
|
25
63
|
process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
|
|
@@ -82,9 +120,9 @@ function normalizeAutoUpdate(raw) {
|
|
|
82
120
|
}
|
|
83
121
|
async function loadConfig() {
|
|
84
122
|
const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
|
|
85
|
-
await
|
|
123
|
+
await ensurePrivateDir(dir);
|
|
86
124
|
const configPath = path.join(dir, "config.json");
|
|
87
|
-
if (!
|
|
125
|
+
if (!existsSync2(configPath)) {
|
|
88
126
|
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
|
|
89
127
|
}
|
|
90
128
|
const raw = await readFile(configPath, "utf-8");
|
|
@@ -97,6 +135,7 @@ async function loadConfig() {
|
|
|
97
135
|
`);
|
|
98
136
|
try {
|
|
99
137
|
await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
|
|
138
|
+
await enforcePrivateFile(configPath);
|
|
100
139
|
} catch {
|
|
101
140
|
}
|
|
102
141
|
}
|
|
@@ -116,6 +155,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
|
|
|
116
155
|
var init_config = __esm({
|
|
117
156
|
"src/lib/config.ts"() {
|
|
118
157
|
"use strict";
|
|
158
|
+
init_secure_files();
|
|
119
159
|
EXE_AI_DIR = resolveDataDir();
|
|
120
160
|
DB_PATH = path.join(EXE_AI_DIR, "memories.db");
|
|
121
161
|
MODELS_DIR = path.join(EXE_AI_DIR, "models");
|
|
@@ -194,7 +234,7 @@ var init_config = __esm({
|
|
|
194
234
|
|
|
195
235
|
// src/lib/employees.ts
|
|
196
236
|
import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
|
|
197
|
-
import { existsSync as
|
|
237
|
+
import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
|
|
198
238
|
import { execSync } from "child_process";
|
|
199
239
|
import path2 from "path";
|
|
200
240
|
import os2 from "os";
|
|
@@ -211,7 +251,7 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
|
|
|
211
251
|
return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
|
|
212
252
|
}
|
|
213
253
|
async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
|
|
214
|
-
if (!
|
|
254
|
+
if (!existsSync3(employeesPath)) {
|
|
215
255
|
return [];
|
|
216
256
|
}
|
|
217
257
|
const raw = await readFile2(employeesPath, "utf-8");
|
|
@@ -222,7 +262,7 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
|
|
|
222
262
|
}
|
|
223
263
|
}
|
|
224
264
|
function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
225
|
-
if (!
|
|
265
|
+
if (!existsSync3(employeesPath)) return [];
|
|
226
266
|
try {
|
|
227
267
|
return JSON.parse(readFileSync2(employeesPath, "utf-8"));
|
|
228
268
|
} catch {
|
|
@@ -232,7 +272,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
|
232
272
|
function getEmployee(employees, name) {
|
|
233
273
|
return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
234
274
|
}
|
|
235
|
-
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
|
|
275
|
+
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
|
|
236
276
|
var init_employees = __esm({
|
|
237
277
|
"src/lib/employees.ts"() {
|
|
238
278
|
"use strict";
|
|
@@ -240,6 +280,44 @@ var init_employees = __esm({
|
|
|
240
280
|
EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
|
|
241
281
|
DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
|
|
242
282
|
COORDINATOR_ROLE = "COO";
|
|
283
|
+
IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
// src/lib/daemon-auth.ts
|
|
288
|
+
import crypto from "crypto";
|
|
289
|
+
import path3 from "path";
|
|
290
|
+
import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
291
|
+
function normalizeToken(token) {
|
|
292
|
+
if (!token) return null;
|
|
293
|
+
const trimmed = token.trim();
|
|
294
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
295
|
+
}
|
|
296
|
+
function readDaemonToken() {
|
|
297
|
+
try {
|
|
298
|
+
if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
|
|
299
|
+
return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
|
|
300
|
+
} catch {
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
function ensureDaemonToken(seed) {
|
|
305
|
+
const existing = readDaemonToken();
|
|
306
|
+
if (existing) return existing;
|
|
307
|
+
const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
|
|
308
|
+
ensurePrivateDirSync(EXE_AI_DIR);
|
|
309
|
+
writeFileSync2(DAEMON_TOKEN_PATH, `${token}
|
|
310
|
+
`, "utf8");
|
|
311
|
+
enforcePrivateFileSync(DAEMON_TOKEN_PATH);
|
|
312
|
+
return token;
|
|
313
|
+
}
|
|
314
|
+
var DAEMON_TOKEN_PATH;
|
|
315
|
+
var init_daemon_auth = __esm({
|
|
316
|
+
"src/lib/daemon-auth.ts"() {
|
|
317
|
+
"use strict";
|
|
318
|
+
init_config();
|
|
319
|
+
init_secure_files();
|
|
320
|
+
DAEMON_TOKEN_PATH = path3.join(EXE_AI_DIR, "exed.token");
|
|
243
321
|
}
|
|
244
322
|
});
|
|
245
323
|
|
|
@@ -248,8 +326,8 @@ import net from "net";
|
|
|
248
326
|
import os3 from "os";
|
|
249
327
|
import { spawn } from "child_process";
|
|
250
328
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
251
|
-
import { existsSync as
|
|
252
|
-
import
|
|
329
|
+
import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
|
|
330
|
+
import path4 from "path";
|
|
253
331
|
import { fileURLToPath } from "url";
|
|
254
332
|
function handleData(chunk) {
|
|
255
333
|
_buffer += chunk.toString();
|
|
@@ -277,9 +355,9 @@ function handleData(chunk) {
|
|
|
277
355
|
}
|
|
278
356
|
}
|
|
279
357
|
function cleanupStaleFiles() {
|
|
280
|
-
if (
|
|
358
|
+
if (existsSync5(PID_PATH)) {
|
|
281
359
|
try {
|
|
282
|
-
const pid = parseInt(
|
|
360
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
283
361
|
if (pid > 0) {
|
|
284
362
|
try {
|
|
285
363
|
process.kill(pid, 0);
|
|
@@ -300,11 +378,11 @@ function cleanupStaleFiles() {
|
|
|
300
378
|
}
|
|
301
379
|
}
|
|
302
380
|
function findPackageRoot() {
|
|
303
|
-
let dir =
|
|
304
|
-
const { root } =
|
|
381
|
+
let dir = path4.dirname(fileURLToPath(import.meta.url));
|
|
382
|
+
const { root } = path4.parse(dir);
|
|
305
383
|
while (dir !== root) {
|
|
306
|
-
if (
|
|
307
|
-
dir =
|
|
384
|
+
if (existsSync5(path4.join(dir, "package.json"))) return dir;
|
|
385
|
+
dir = path4.dirname(dir);
|
|
308
386
|
}
|
|
309
387
|
return null;
|
|
310
388
|
}
|
|
@@ -330,16 +408,17 @@ function spawnDaemon() {
|
|
|
330
408
|
process.stderr.write("[exed-client] WARN: cannot find package root\n");
|
|
331
409
|
return;
|
|
332
410
|
}
|
|
333
|
-
const daemonPath =
|
|
334
|
-
if (!
|
|
411
|
+
const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
|
|
412
|
+
if (!existsSync5(daemonPath)) {
|
|
335
413
|
process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
|
|
336
414
|
`);
|
|
337
415
|
return;
|
|
338
416
|
}
|
|
339
417
|
const resolvedPath = daemonPath;
|
|
418
|
+
const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
|
|
340
419
|
process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
|
|
341
420
|
`);
|
|
342
|
-
const logPath =
|
|
421
|
+
const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
|
|
343
422
|
let stderrFd = "ignore";
|
|
344
423
|
try {
|
|
345
424
|
stderrFd = openSync(logPath, "a");
|
|
@@ -357,7 +436,8 @@ function spawnDaemon() {
|
|
|
357
436
|
TMUX_PANE: void 0,
|
|
358
437
|
// Prevents resolveExeSession() from scoping to one session
|
|
359
438
|
EXE_DAEMON_SOCK: SOCKET_PATH,
|
|
360
|
-
EXE_DAEMON_PID: PID_PATH
|
|
439
|
+
EXE_DAEMON_PID: PID_PATH,
|
|
440
|
+
[DAEMON_TOKEN_ENV]: daemonToken
|
|
361
441
|
}
|
|
362
442
|
});
|
|
363
443
|
child.unref();
|
|
@@ -467,13 +547,14 @@ function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
|
467
547
|
return;
|
|
468
548
|
}
|
|
469
549
|
const id = randomUUID2();
|
|
550
|
+
const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
|
|
470
551
|
const timer = setTimeout(() => {
|
|
471
552
|
_pending.delete(id);
|
|
472
553
|
resolve({ error: "Request timeout" });
|
|
473
554
|
}, timeoutMs);
|
|
474
555
|
_pending.set(id, { resolve, timer });
|
|
475
556
|
try {
|
|
476
|
-
_socket.write(JSON.stringify({ id, ...payload }) + "\n");
|
|
557
|
+
_socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
|
|
477
558
|
} catch {
|
|
478
559
|
clearTimeout(timer);
|
|
479
560
|
_pending.delete(id);
|
|
@@ -490,91 +571,146 @@ async function pingDaemon() {
|
|
|
490
571
|
return null;
|
|
491
572
|
}
|
|
492
573
|
function killAndRespawnDaemon() {
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
574
|
+
if (!acquireSpawnLock()) {
|
|
575
|
+
process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
|
|
576
|
+
if (_socket) {
|
|
577
|
+
_socket.destroy();
|
|
578
|
+
_socket = null;
|
|
579
|
+
}
|
|
580
|
+
_connected = false;
|
|
581
|
+
_buffer = "";
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
try {
|
|
585
|
+
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
586
|
+
if (existsSync5(PID_PATH)) {
|
|
587
|
+
try {
|
|
588
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
589
|
+
if (pid > 0) {
|
|
590
|
+
try {
|
|
591
|
+
process.kill(pid, "SIGKILL");
|
|
592
|
+
} catch {
|
|
593
|
+
}
|
|
501
594
|
}
|
|
595
|
+
} catch {
|
|
502
596
|
}
|
|
597
|
+
}
|
|
598
|
+
if (_socket) {
|
|
599
|
+
_socket.destroy();
|
|
600
|
+
_socket = null;
|
|
601
|
+
}
|
|
602
|
+
_connected = false;
|
|
603
|
+
_buffer = "";
|
|
604
|
+
try {
|
|
605
|
+
unlinkSync2(PID_PATH);
|
|
503
606
|
} catch {
|
|
504
607
|
}
|
|
608
|
+
try {
|
|
609
|
+
unlinkSync2(SOCKET_PATH);
|
|
610
|
+
} catch {
|
|
611
|
+
}
|
|
612
|
+
spawnDaemon();
|
|
613
|
+
} finally {
|
|
614
|
+
releaseSpawnLock();
|
|
505
615
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
_socket = null;
|
|
509
|
-
}
|
|
510
|
-
_connected = false;
|
|
511
|
-
_buffer = "";
|
|
616
|
+
}
|
|
617
|
+
function isDaemonTooYoung() {
|
|
512
618
|
try {
|
|
513
|
-
|
|
619
|
+
const stat = statSync(PID_PATH);
|
|
620
|
+
return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
|
|
514
621
|
} catch {
|
|
622
|
+
return false;
|
|
515
623
|
}
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
624
|
+
}
|
|
625
|
+
async function retryThenRestart(doRequest, label) {
|
|
626
|
+
const result = await doRequest();
|
|
627
|
+
if (!result.error) {
|
|
628
|
+
_consecutiveFailures = 0;
|
|
629
|
+
return result;
|
|
630
|
+
}
|
|
631
|
+
_consecutiveFailures++;
|
|
632
|
+
for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
|
|
633
|
+
const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
|
|
634
|
+
process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
|
|
635
|
+
`);
|
|
636
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
637
|
+
if (!_connected) {
|
|
638
|
+
if (!await connectToSocket()) continue;
|
|
639
|
+
}
|
|
640
|
+
const retry = await doRequest();
|
|
641
|
+
if (!retry.error) {
|
|
642
|
+
_consecutiveFailures = 0;
|
|
643
|
+
return retry;
|
|
644
|
+
}
|
|
645
|
+
_consecutiveFailures++;
|
|
646
|
+
}
|
|
647
|
+
if (isDaemonTooYoung()) {
|
|
648
|
+
process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
|
|
649
|
+
`);
|
|
650
|
+
return { error: result.error };
|
|
651
|
+
}
|
|
652
|
+
process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
|
|
653
|
+
`);
|
|
654
|
+
killAndRespawnDaemon();
|
|
655
|
+
const start = Date.now();
|
|
656
|
+
let delay2 = 200;
|
|
657
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
658
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
659
|
+
if (await connectToSocket()) break;
|
|
660
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
519
661
|
}
|
|
520
|
-
|
|
662
|
+
if (!_connected) return { error: "Daemon restart failed" };
|
|
663
|
+
const final = await doRequest();
|
|
664
|
+
if (!final.error) _consecutiveFailures = 0;
|
|
665
|
+
return final;
|
|
521
666
|
}
|
|
522
667
|
async function embedViaClient(text, priority = "high") {
|
|
523
668
|
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
524
669
|
_requestCount++;
|
|
525
670
|
if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
|
|
526
671
|
const health = await pingDaemon();
|
|
527
|
-
if (!health) {
|
|
672
|
+
if (!health && !isDaemonTooYoung()) {
|
|
528
673
|
process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
|
|
529
674
|
`);
|
|
530
675
|
killAndRespawnDaemon();
|
|
531
676
|
const start = Date.now();
|
|
532
|
-
let
|
|
677
|
+
let d = 200;
|
|
533
678
|
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
534
|
-
await new Promise((r) => setTimeout(r,
|
|
679
|
+
await new Promise((r) => setTimeout(r, d));
|
|
535
680
|
if (await connectToSocket()) break;
|
|
536
|
-
|
|
681
|
+
d = Math.min(d * 2, 3e3);
|
|
537
682
|
}
|
|
538
683
|
if (!_connected) return null;
|
|
539
684
|
}
|
|
540
685
|
}
|
|
541
|
-
const result = await
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
killAndRespawnDaemon();
|
|
547
|
-
const start = Date.now();
|
|
548
|
-
let delay2 = 200;
|
|
549
|
-
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
550
|
-
await new Promise((r) => setTimeout(r, delay2));
|
|
551
|
-
if (await connectToSocket()) break;
|
|
552
|
-
delay2 = Math.min(delay2 * 2, 3e3);
|
|
553
|
-
}
|
|
554
|
-
if (!_connected) return null;
|
|
555
|
-
const retry = await sendRequest([text], priority);
|
|
556
|
-
if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
|
|
557
|
-
process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
|
|
558
|
-
`);
|
|
559
|
-
}
|
|
560
|
-
return null;
|
|
686
|
+
const result = await retryThenRestart(
|
|
687
|
+
() => sendRequest([text], priority),
|
|
688
|
+
"Embed"
|
|
689
|
+
);
|
|
690
|
+
return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
|
|
561
691
|
}
|
|
562
|
-
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending, MAX_BUFFER;
|
|
692
|
+
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
|
|
563
693
|
var init_exe_daemon_client = __esm({
|
|
564
694
|
"src/lib/exe-daemon-client.ts"() {
|
|
565
695
|
"use strict";
|
|
566
696
|
init_config();
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
697
|
+
init_daemon_auth();
|
|
698
|
+
SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
|
|
699
|
+
PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
|
|
700
|
+
SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
|
|
570
701
|
SPAWN_LOCK_STALE_MS = 3e4;
|
|
571
702
|
CONNECT_TIMEOUT_MS = 15e3;
|
|
572
703
|
REQUEST_TIMEOUT_MS = 3e4;
|
|
704
|
+
DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
|
|
573
705
|
_socket = null;
|
|
574
706
|
_connected = false;
|
|
575
707
|
_buffer = "";
|
|
576
708
|
_requestCount = 0;
|
|
709
|
+
_consecutiveFailures = 0;
|
|
577
710
|
HEALTH_CHECK_INTERVAL = 100;
|
|
711
|
+
MAX_RETRIES_BEFORE_RESTART = 3;
|
|
712
|
+
RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
|
|
713
|
+
MIN_DAEMON_AGE_MS = 3e4;
|
|
578
714
|
_pending = /* @__PURE__ */ new Map();
|
|
579
715
|
MAX_BUFFER = 1e7;
|
|
580
716
|
}
|
|
@@ -635,9 +771,605 @@ var init_db_retry = __esm({
|
|
|
635
771
|
}
|
|
636
772
|
});
|
|
637
773
|
|
|
774
|
+
// src/lib/database-adapter.ts
|
|
775
|
+
import os4 from "os";
|
|
776
|
+
import path5 from "path";
|
|
777
|
+
import { createRequire } from "module";
|
|
778
|
+
import { pathToFileURL } from "url";
|
|
779
|
+
function quotedIdentifier(identifier) {
|
|
780
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
781
|
+
}
|
|
782
|
+
function unqualifiedTableName(name) {
|
|
783
|
+
const raw = name.trim().replace(/^"|"$/g, "");
|
|
784
|
+
const parts = raw.split(".");
|
|
785
|
+
return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
|
|
786
|
+
}
|
|
787
|
+
function stripTrailingSemicolon(sql) {
|
|
788
|
+
return sql.trim().replace(/;+\s*$/u, "");
|
|
789
|
+
}
|
|
790
|
+
function appendClause(sql, clause) {
|
|
791
|
+
const trimmed = stripTrailingSemicolon(sql);
|
|
792
|
+
const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
|
|
793
|
+
if (!returningMatch) {
|
|
794
|
+
return `${trimmed}${clause}`;
|
|
795
|
+
}
|
|
796
|
+
const idx = returningMatch.index;
|
|
797
|
+
return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
|
|
798
|
+
}
|
|
799
|
+
function normalizeStatement(stmt) {
|
|
800
|
+
if (typeof stmt === "string") {
|
|
801
|
+
return { kind: "positional", sql: stmt, args: [] };
|
|
802
|
+
}
|
|
803
|
+
const sql = stmt.sql;
|
|
804
|
+
if (Array.isArray(stmt.args) || stmt.args === void 0) {
|
|
805
|
+
return { kind: "positional", sql, args: stmt.args ?? [] };
|
|
806
|
+
}
|
|
807
|
+
return { kind: "named", sql, args: stmt.args };
|
|
808
|
+
}
|
|
809
|
+
function rewriteBooleanLiterals(sql) {
|
|
810
|
+
let out = sql;
|
|
811
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
812
|
+
const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
|
|
813
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
|
|
814
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
|
|
815
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
|
|
816
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
|
|
817
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
|
|
818
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
|
|
819
|
+
}
|
|
820
|
+
return out;
|
|
821
|
+
}
|
|
822
|
+
function rewriteInsertOrIgnore(sql) {
|
|
823
|
+
if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
|
|
824
|
+
return sql;
|
|
825
|
+
}
|
|
826
|
+
const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
|
|
827
|
+
return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
|
|
828
|
+
}
|
|
829
|
+
function rewriteInsertOrReplace(sql) {
|
|
830
|
+
const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
|
|
831
|
+
if (!match) {
|
|
832
|
+
return sql;
|
|
833
|
+
}
|
|
834
|
+
const rawTable = match[1];
|
|
835
|
+
const rawColumns = match[2];
|
|
836
|
+
const remainder = match[3];
|
|
837
|
+
const tableName = unqualifiedTableName(rawTable);
|
|
838
|
+
const conflictKeys = UPSERT_KEYS[tableName];
|
|
839
|
+
if (!conflictKeys?.length) {
|
|
840
|
+
return sql;
|
|
841
|
+
}
|
|
842
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
843
|
+
const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
|
|
844
|
+
const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
|
|
845
|
+
const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
|
|
846
|
+
return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
|
|
847
|
+
}
|
|
848
|
+
function rewriteSql(sql) {
|
|
849
|
+
let out = sql;
|
|
850
|
+
out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
|
|
851
|
+
out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
|
|
852
|
+
out = rewriteBooleanLiterals(out);
|
|
853
|
+
out = rewriteInsertOrReplace(out);
|
|
854
|
+
out = rewriteInsertOrIgnore(out);
|
|
855
|
+
return stripTrailingSemicolon(out);
|
|
856
|
+
}
|
|
857
|
+
function toBoolean(value) {
|
|
858
|
+
if (value === null || value === void 0) return value;
|
|
859
|
+
if (typeof value === "boolean") return value;
|
|
860
|
+
if (typeof value === "number") return value !== 0;
|
|
861
|
+
if (typeof value === "bigint") return value !== 0n;
|
|
862
|
+
if (typeof value === "string") {
|
|
863
|
+
const normalized = value.trim().toLowerCase();
|
|
864
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
865
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
866
|
+
}
|
|
867
|
+
return Boolean(value);
|
|
868
|
+
}
|
|
869
|
+
function countQuestionMarks(sql, end) {
|
|
870
|
+
let count = 0;
|
|
871
|
+
let inSingle = false;
|
|
872
|
+
let inDouble = false;
|
|
873
|
+
let inLineComment = false;
|
|
874
|
+
let inBlockComment = false;
|
|
875
|
+
for (let i = 0; i < end; i++) {
|
|
876
|
+
const ch = sql[i];
|
|
877
|
+
const next = sql[i + 1];
|
|
878
|
+
if (inLineComment) {
|
|
879
|
+
if (ch === "\n") inLineComment = false;
|
|
880
|
+
continue;
|
|
881
|
+
}
|
|
882
|
+
if (inBlockComment) {
|
|
883
|
+
if (ch === "*" && next === "/") {
|
|
884
|
+
inBlockComment = false;
|
|
885
|
+
i += 1;
|
|
886
|
+
}
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
890
|
+
inLineComment = true;
|
|
891
|
+
i += 1;
|
|
892
|
+
continue;
|
|
893
|
+
}
|
|
894
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
895
|
+
inBlockComment = true;
|
|
896
|
+
i += 1;
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
900
|
+
inSingle = !inSingle;
|
|
901
|
+
continue;
|
|
902
|
+
}
|
|
903
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
904
|
+
inDouble = !inDouble;
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
908
|
+
count += 1;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
return count;
|
|
912
|
+
}
|
|
913
|
+
function findBooleanPlaceholderIndexes(sql) {
|
|
914
|
+
const indexes = /* @__PURE__ */ new Set();
|
|
915
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
916
|
+
const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
|
|
917
|
+
for (const match of sql.matchAll(pattern)) {
|
|
918
|
+
const matchText = match[0];
|
|
919
|
+
const qIndex = match.index + matchText.lastIndexOf("?");
|
|
920
|
+
indexes.add(countQuestionMarks(sql, qIndex + 1));
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
return indexes;
|
|
924
|
+
}
|
|
925
|
+
function coerceInsertBooleanArgs(sql, args) {
|
|
926
|
+
const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
|
|
927
|
+
if (!match) return;
|
|
928
|
+
const rawTable = match[1];
|
|
929
|
+
const rawColumns = match[2];
|
|
930
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
931
|
+
if (!boolColumns?.size) return;
|
|
932
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
933
|
+
for (const [index, column] of columns.entries()) {
|
|
934
|
+
if (boolColumns.has(column) && index < args.length) {
|
|
935
|
+
args[index] = toBoolean(args[index]);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
function coerceUpdateBooleanArgs(sql, args) {
|
|
940
|
+
const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
|
|
941
|
+
if (!match) return;
|
|
942
|
+
const rawTable = match[1];
|
|
943
|
+
const setClause = match[2];
|
|
944
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
945
|
+
if (!boolColumns?.size) return;
|
|
946
|
+
const assignments = setClause.split(",");
|
|
947
|
+
let placeholderIndex = 0;
|
|
948
|
+
for (const assignment of assignments) {
|
|
949
|
+
if (!assignment.includes("?")) continue;
|
|
950
|
+
placeholderIndex += 1;
|
|
951
|
+
const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
|
|
952
|
+
if (colMatch && boolColumns.has(colMatch[1])) {
|
|
953
|
+
args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
function coerceBooleanArgs(sql, args) {
|
|
958
|
+
const nextArgs = [...args];
|
|
959
|
+
coerceInsertBooleanArgs(sql, nextArgs);
|
|
960
|
+
coerceUpdateBooleanArgs(sql, nextArgs);
|
|
961
|
+
const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
|
|
962
|
+
for (const index of placeholderIndexes) {
|
|
963
|
+
if (index > 0 && index <= nextArgs.length) {
|
|
964
|
+
nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
return nextArgs;
|
|
968
|
+
}
|
|
969
|
+
function convertQuestionMarksToDollarParams(sql) {
|
|
970
|
+
let out = "";
|
|
971
|
+
let placeholder = 0;
|
|
972
|
+
let inSingle = false;
|
|
973
|
+
let inDouble = false;
|
|
974
|
+
let inLineComment = false;
|
|
975
|
+
let inBlockComment = false;
|
|
976
|
+
for (let i = 0; i < sql.length; i++) {
|
|
977
|
+
const ch = sql[i];
|
|
978
|
+
const next = sql[i + 1];
|
|
979
|
+
if (inLineComment) {
|
|
980
|
+
out += ch;
|
|
981
|
+
if (ch === "\n") inLineComment = false;
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
if (inBlockComment) {
|
|
985
|
+
out += ch;
|
|
986
|
+
if (ch === "*" && next === "/") {
|
|
987
|
+
out += next;
|
|
988
|
+
inBlockComment = false;
|
|
989
|
+
i += 1;
|
|
990
|
+
}
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
994
|
+
out += ch + next;
|
|
995
|
+
inLineComment = true;
|
|
996
|
+
i += 1;
|
|
997
|
+
continue;
|
|
998
|
+
}
|
|
999
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
1000
|
+
out += ch + next;
|
|
1001
|
+
inBlockComment = true;
|
|
1002
|
+
i += 1;
|
|
1003
|
+
continue;
|
|
1004
|
+
}
|
|
1005
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
1006
|
+
inSingle = !inSingle;
|
|
1007
|
+
out += ch;
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
1011
|
+
inDouble = !inDouble;
|
|
1012
|
+
out += ch;
|
|
1013
|
+
continue;
|
|
1014
|
+
}
|
|
1015
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
1016
|
+
placeholder += 1;
|
|
1017
|
+
out += `$${placeholder}`;
|
|
1018
|
+
continue;
|
|
1019
|
+
}
|
|
1020
|
+
out += ch;
|
|
1021
|
+
}
|
|
1022
|
+
return out;
|
|
1023
|
+
}
|
|
1024
|
+
function translateStatementForPostgres(stmt) {
|
|
1025
|
+
const normalized = normalizeStatement(stmt);
|
|
1026
|
+
if (normalized.kind === "named") {
|
|
1027
|
+
throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
|
|
1028
|
+
}
|
|
1029
|
+
const rewrittenSql = rewriteSql(normalized.sql);
|
|
1030
|
+
const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
|
|
1031
|
+
return {
|
|
1032
|
+
sql: convertQuestionMarksToDollarParams(rewrittenSql),
|
|
1033
|
+
args: coercedArgs
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
function shouldBypassPostgres(stmt) {
|
|
1037
|
+
const normalized = normalizeStatement(stmt);
|
|
1038
|
+
if (normalized.kind === "named") {
|
|
1039
|
+
return true;
|
|
1040
|
+
}
|
|
1041
|
+
return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
|
|
1042
|
+
}
|
|
1043
|
+
function shouldFallbackOnError(error) {
|
|
1044
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1045
|
+
return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
|
|
1046
|
+
}
|
|
1047
|
+
function isReadQuery(sql) {
|
|
1048
|
+
const trimmed = sql.trimStart();
|
|
1049
|
+
return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
|
|
1050
|
+
}
|
|
1051
|
+
function buildRow(row, columns) {
|
|
1052
|
+
const values = columns.map((column) => row[column]);
|
|
1053
|
+
return Object.assign(values, row);
|
|
1054
|
+
}
|
|
1055
|
+
function buildResultSet(rows, rowsAffected = 0) {
|
|
1056
|
+
const columns = rows[0] ? Object.keys(rows[0]) : [];
|
|
1057
|
+
const resultRows = rows.map((row) => buildRow(row, columns));
|
|
1058
|
+
return {
|
|
1059
|
+
columns,
|
|
1060
|
+
columnTypes: columns.map(() => ""),
|
|
1061
|
+
rows: resultRows,
|
|
1062
|
+
rowsAffected,
|
|
1063
|
+
lastInsertRowid: void 0,
|
|
1064
|
+
toJSON() {
|
|
1065
|
+
return {
|
|
1066
|
+
columns,
|
|
1067
|
+
columnTypes: columns.map(() => ""),
|
|
1068
|
+
rows,
|
|
1069
|
+
rowsAffected,
|
|
1070
|
+
lastInsertRowid: void 0
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
};
|
|
1074
|
+
}
|
|
1075
|
+
async function loadPrismaClient() {
|
|
1076
|
+
if (!prismaClientPromise) {
|
|
1077
|
+
prismaClientPromise = (async () => {
|
|
1078
|
+
const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
|
|
1079
|
+
if (explicitPath) {
|
|
1080
|
+
const module2 = await import(pathToFileURL(explicitPath).href);
|
|
1081
|
+
const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
|
|
1082
|
+
if (!PrismaClient2) {
|
|
1083
|
+
throw new Error(`No PrismaClient export found at ${explicitPath}`);
|
|
1084
|
+
}
|
|
1085
|
+
return new PrismaClient2();
|
|
1086
|
+
}
|
|
1087
|
+
const exeDbRoot = process.env.EXE_DB_ROOT ?? path5.join(os4.homedir(), "exe-db");
|
|
1088
|
+
const requireFromExeDb = createRequire(path5.join(exeDbRoot, "package.json"));
|
|
1089
|
+
const prismaEntry = requireFromExeDb.resolve("@prisma/client");
|
|
1090
|
+
const module = await import(pathToFileURL(prismaEntry).href);
|
|
1091
|
+
const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
|
|
1092
|
+
if (!PrismaClient) {
|
|
1093
|
+
throw new Error(`No PrismaClient export found in ${prismaEntry}`);
|
|
1094
|
+
}
|
|
1095
|
+
return new PrismaClient();
|
|
1096
|
+
})();
|
|
1097
|
+
}
|
|
1098
|
+
return prismaClientPromise;
|
|
1099
|
+
}
|
|
1100
|
+
async function ensureCompatibilityViews(prisma) {
|
|
1101
|
+
if (!compatibilityBootstrapPromise) {
|
|
1102
|
+
compatibilityBootstrapPromise = (async () => {
|
|
1103
|
+
for (const mapping of VIEW_MAPPINGS) {
|
|
1104
|
+
const relation = mapping.source.replace(/"/g, "");
|
|
1105
|
+
const rows = await prisma.$queryRawUnsafe(
|
|
1106
|
+
"SELECT to_regclass($1) AS regclass",
|
|
1107
|
+
relation
|
|
1108
|
+
);
|
|
1109
|
+
if (!rows[0]?.regclass) {
|
|
1110
|
+
continue;
|
|
1111
|
+
}
|
|
1112
|
+
await prisma.$executeRawUnsafe(
|
|
1113
|
+
`CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
})();
|
|
1117
|
+
}
|
|
1118
|
+
return compatibilityBootstrapPromise;
|
|
1119
|
+
}
|
|
1120
|
+
async function executeOnPrisma(executor, stmt) {
|
|
1121
|
+
const translated = translateStatementForPostgres(stmt);
|
|
1122
|
+
if (isReadQuery(translated.sql)) {
|
|
1123
|
+
const rows = await executor.$queryRawUnsafe(
|
|
1124
|
+
translated.sql,
|
|
1125
|
+
...translated.args
|
|
1126
|
+
);
|
|
1127
|
+
return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
|
|
1128
|
+
}
|
|
1129
|
+
const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
|
|
1130
|
+
return buildResultSet([], rowsAffected);
|
|
1131
|
+
}
|
|
1132
|
+
function splitSqlStatements(sql) {
|
|
1133
|
+
const parts = [];
|
|
1134
|
+
let current = "";
|
|
1135
|
+
let inSingle = false;
|
|
1136
|
+
let inDouble = false;
|
|
1137
|
+
let inLineComment = false;
|
|
1138
|
+
let inBlockComment = false;
|
|
1139
|
+
for (let i = 0; i < sql.length; i++) {
|
|
1140
|
+
const ch = sql[i];
|
|
1141
|
+
const next = sql[i + 1];
|
|
1142
|
+
if (inLineComment) {
|
|
1143
|
+
current += ch;
|
|
1144
|
+
if (ch === "\n") inLineComment = false;
|
|
1145
|
+
continue;
|
|
1146
|
+
}
|
|
1147
|
+
if (inBlockComment) {
|
|
1148
|
+
current += ch;
|
|
1149
|
+
if (ch === "*" && next === "/") {
|
|
1150
|
+
current += next;
|
|
1151
|
+
inBlockComment = false;
|
|
1152
|
+
i += 1;
|
|
1153
|
+
}
|
|
1154
|
+
continue;
|
|
1155
|
+
}
|
|
1156
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
1157
|
+
current += ch + next;
|
|
1158
|
+
inLineComment = true;
|
|
1159
|
+
i += 1;
|
|
1160
|
+
continue;
|
|
1161
|
+
}
|
|
1162
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
1163
|
+
current += ch + next;
|
|
1164
|
+
inBlockComment = true;
|
|
1165
|
+
i += 1;
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
1169
|
+
inSingle = !inSingle;
|
|
1170
|
+
current += ch;
|
|
1171
|
+
continue;
|
|
1172
|
+
}
|
|
1173
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
1174
|
+
inDouble = !inDouble;
|
|
1175
|
+
current += ch;
|
|
1176
|
+
continue;
|
|
1177
|
+
}
|
|
1178
|
+
if (!inSingle && !inDouble && ch === ";") {
|
|
1179
|
+
if (current.trim()) {
|
|
1180
|
+
parts.push(current.trim());
|
|
1181
|
+
}
|
|
1182
|
+
current = "";
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
current += ch;
|
|
1186
|
+
}
|
|
1187
|
+
if (current.trim()) {
|
|
1188
|
+
parts.push(current.trim());
|
|
1189
|
+
}
|
|
1190
|
+
return parts;
|
|
1191
|
+
}
|
|
1192
|
+
async function createPrismaDbAdapter(fallbackClient) {
|
|
1193
|
+
const prisma = await loadPrismaClient();
|
|
1194
|
+
await ensureCompatibilityViews(prisma);
|
|
1195
|
+
let closed = false;
|
|
1196
|
+
let adapter;
|
|
1197
|
+
const fallbackExecute = async (stmt, error) => {
|
|
1198
|
+
if (!fallbackClient) {
|
|
1199
|
+
if (error) throw error;
|
|
1200
|
+
throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
|
|
1201
|
+
}
|
|
1202
|
+
if (error) {
|
|
1203
|
+
process.stderr.write(
|
|
1204
|
+
`[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
1205
|
+
`
|
|
1206
|
+
);
|
|
1207
|
+
}
|
|
1208
|
+
return fallbackClient.execute(stmt);
|
|
1209
|
+
};
|
|
1210
|
+
adapter = {
|
|
1211
|
+
async execute(stmt) {
|
|
1212
|
+
if (shouldBypassPostgres(stmt)) {
|
|
1213
|
+
return fallbackExecute(stmt);
|
|
1214
|
+
}
|
|
1215
|
+
try {
|
|
1216
|
+
return await executeOnPrisma(prisma, stmt);
|
|
1217
|
+
} catch (error) {
|
|
1218
|
+
if (shouldFallbackOnError(error)) {
|
|
1219
|
+
return fallbackExecute(stmt, error);
|
|
1220
|
+
}
|
|
1221
|
+
throw error;
|
|
1222
|
+
}
|
|
1223
|
+
},
|
|
1224
|
+
async batch(stmts, mode) {
|
|
1225
|
+
if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
|
|
1226
|
+
if (!fallbackClient) {
|
|
1227
|
+
throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
|
|
1228
|
+
}
|
|
1229
|
+
return fallbackClient.batch(stmts, mode);
|
|
1230
|
+
}
|
|
1231
|
+
try {
|
|
1232
|
+
if (prisma.$transaction) {
|
|
1233
|
+
return await prisma.$transaction(async (tx) => {
|
|
1234
|
+
const results2 = [];
|
|
1235
|
+
for (const stmt of stmts) {
|
|
1236
|
+
results2.push(await executeOnPrisma(tx, stmt));
|
|
1237
|
+
}
|
|
1238
|
+
return results2;
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
const results = [];
|
|
1242
|
+
for (const stmt of stmts) {
|
|
1243
|
+
results.push(await executeOnPrisma(prisma, stmt));
|
|
1244
|
+
}
|
|
1245
|
+
return results;
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
if (fallbackClient && shouldFallbackOnError(error)) {
|
|
1248
|
+
process.stderr.write(
|
|
1249
|
+
`[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
1250
|
+
`
|
|
1251
|
+
);
|
|
1252
|
+
return fallbackClient.batch(stmts, mode);
|
|
1253
|
+
}
|
|
1254
|
+
throw error;
|
|
1255
|
+
}
|
|
1256
|
+
},
|
|
1257
|
+
async migrate(stmts) {
|
|
1258
|
+
if (fallbackClient) {
|
|
1259
|
+
return fallbackClient.migrate(stmts);
|
|
1260
|
+
}
|
|
1261
|
+
return adapter.batch(stmts, "deferred");
|
|
1262
|
+
},
|
|
1263
|
+
async transaction(mode) {
|
|
1264
|
+
if (!fallbackClient) {
|
|
1265
|
+
throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
|
|
1266
|
+
}
|
|
1267
|
+
return fallbackClient.transaction(mode);
|
|
1268
|
+
},
|
|
1269
|
+
async executeMultiple(sql) {
|
|
1270
|
+
if (fallbackClient && shouldBypassPostgres(sql)) {
|
|
1271
|
+
return fallbackClient.executeMultiple(sql);
|
|
1272
|
+
}
|
|
1273
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
1274
|
+
await adapter.execute(statement);
|
|
1275
|
+
}
|
|
1276
|
+
},
|
|
1277
|
+
async sync() {
|
|
1278
|
+
if (fallbackClient) {
|
|
1279
|
+
return fallbackClient.sync();
|
|
1280
|
+
}
|
|
1281
|
+
return { frame_no: 0, frames_synced: 0 };
|
|
1282
|
+
},
|
|
1283
|
+
close() {
|
|
1284
|
+
closed = true;
|
|
1285
|
+
prismaClientPromise = null;
|
|
1286
|
+
compatibilityBootstrapPromise = null;
|
|
1287
|
+
void prisma.$disconnect?.();
|
|
1288
|
+
},
|
|
1289
|
+
get closed() {
|
|
1290
|
+
return closed;
|
|
1291
|
+
},
|
|
1292
|
+
get protocol() {
|
|
1293
|
+
return "prisma-postgres";
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
return adapter;
|
|
1297
|
+
}
|
|
1298
|
+
var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
|
|
1299
|
+
var init_database_adapter = __esm({
|
|
1300
|
+
"src/lib/database-adapter.ts"() {
|
|
1301
|
+
"use strict";
|
|
1302
|
+
VIEW_MAPPINGS = [
|
|
1303
|
+
{ view: "memories", source: "memory.memory_records" },
|
|
1304
|
+
{ view: "tasks", source: "memory.tasks" },
|
|
1305
|
+
{ view: "behaviors", source: "memory.behaviors" },
|
|
1306
|
+
{ view: "entities", source: "memory.entities" },
|
|
1307
|
+
{ view: "relationships", source: "memory.relationships" },
|
|
1308
|
+
{ view: "entity_memories", source: "memory.entity_memories" },
|
|
1309
|
+
{ view: "entity_aliases", source: "memory.entity_aliases" },
|
|
1310
|
+
{ view: "notifications", source: "memory.notifications" },
|
|
1311
|
+
{ view: "messages", source: "memory.messages" },
|
|
1312
|
+
{ view: "users", source: "wiki.users" },
|
|
1313
|
+
{ view: "workspaces", source: "wiki.workspaces" },
|
|
1314
|
+
{ view: "workspace_users", source: "wiki.workspace_users" },
|
|
1315
|
+
{ view: "documents", source: "wiki.workspace_documents" },
|
|
1316
|
+
{ view: "chats", source: "wiki.workspace_chats" }
|
|
1317
|
+
];
|
|
1318
|
+
UPSERT_KEYS = {
|
|
1319
|
+
memories: ["id"],
|
|
1320
|
+
tasks: ["id"],
|
|
1321
|
+
behaviors: ["id"],
|
|
1322
|
+
entities: ["id"],
|
|
1323
|
+
relationships: ["id"],
|
|
1324
|
+
entity_aliases: ["alias"],
|
|
1325
|
+
notifications: ["id"],
|
|
1326
|
+
messages: ["id"],
|
|
1327
|
+
users: ["id"],
|
|
1328
|
+
workspaces: ["id"],
|
|
1329
|
+
workspace_users: ["id"],
|
|
1330
|
+
documents: ["id"],
|
|
1331
|
+
chats: ["id"]
|
|
1332
|
+
};
|
|
1333
|
+
BOOLEAN_COLUMNS_BY_TABLE = {
|
|
1334
|
+
memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
|
|
1335
|
+
behaviors: /* @__PURE__ */ new Set(["active"]),
|
|
1336
|
+
notifications: /* @__PURE__ */ new Set(["read"]),
|
|
1337
|
+
users: /* @__PURE__ */ new Set(["has_personal_memory"])
|
|
1338
|
+
};
|
|
1339
|
+
BOOLEAN_COLUMN_NAMES = new Set(
|
|
1340
|
+
Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
|
|
1341
|
+
);
|
|
1342
|
+
IMMEDIATE_FALLBACK_PATTERNS = [
|
|
1343
|
+
/\bPRAGMA\b/i,
|
|
1344
|
+
/\bsqlite_master\b/i,
|
|
1345
|
+
/(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
|
|
1346
|
+
/\bMATCH\b/i,
|
|
1347
|
+
/\bvector_distance_cos\s*\(/i,
|
|
1348
|
+
/\bjson_extract\s*\(/i,
|
|
1349
|
+
/\bjulianday\s*\(/i,
|
|
1350
|
+
/\bstrftime\s*\(/i,
|
|
1351
|
+
/\blast_insert_rowid\s*\(/i
|
|
1352
|
+
];
|
|
1353
|
+
prismaClientPromise = null;
|
|
1354
|
+
compatibilityBootstrapPromise = null;
|
|
1355
|
+
}
|
|
1356
|
+
});
|
|
1357
|
+
|
|
638
1358
|
// src/lib/database.ts
|
|
639
1359
|
import { createClient } from "@libsql/client";
|
|
640
1360
|
async function initDatabase(config) {
|
|
1361
|
+
if (_walCheckpointTimer) {
|
|
1362
|
+
clearInterval(_walCheckpointTimer);
|
|
1363
|
+
_walCheckpointTimer = null;
|
|
1364
|
+
}
|
|
1365
|
+
if (_daemonClient) {
|
|
1366
|
+
_daemonClient.close();
|
|
1367
|
+
_daemonClient = null;
|
|
1368
|
+
}
|
|
1369
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
1370
|
+
_adapterClient.close();
|
|
1371
|
+
}
|
|
1372
|
+
_adapterClient = null;
|
|
641
1373
|
if (_client) {
|
|
642
1374
|
_client.close();
|
|
643
1375
|
_client = null;
|
|
@@ -651,6 +1383,7 @@ async function initDatabase(config) {
|
|
|
651
1383
|
}
|
|
652
1384
|
_client = createClient(opts);
|
|
653
1385
|
_resilientClient = wrapWithRetry(_client);
|
|
1386
|
+
_adapterClient = _resilientClient;
|
|
654
1387
|
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
655
1388
|
});
|
|
656
1389
|
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
@@ -661,11 +1394,17 @@ async function initDatabase(config) {
|
|
|
661
1394
|
});
|
|
662
1395
|
}, 3e4);
|
|
663
1396
|
_walCheckpointTimer.unref();
|
|
1397
|
+
if (process.env.DATABASE_URL) {
|
|
1398
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1399
|
+
}
|
|
664
1400
|
}
|
|
665
1401
|
function getClient() {
|
|
666
|
-
if (!
|
|
1402
|
+
if (!_adapterClient) {
|
|
667
1403
|
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
668
1404
|
}
|
|
1405
|
+
if (process.env.DATABASE_URL) {
|
|
1406
|
+
return _adapterClient;
|
|
1407
|
+
}
|
|
669
1408
|
if (process.env.EXE_IS_DAEMON === "1") {
|
|
670
1409
|
return _resilientClient;
|
|
671
1410
|
}
|
|
@@ -958,6 +1697,7 @@ async function ensureSchema() {
|
|
|
958
1697
|
project TEXT NOT NULL,
|
|
959
1698
|
summary TEXT NOT NULL,
|
|
960
1699
|
task_file TEXT,
|
|
1700
|
+
session_scope TEXT,
|
|
961
1701
|
read INTEGER NOT NULL DEFAULT 0,
|
|
962
1702
|
created_at TEXT NOT NULL
|
|
963
1703
|
);
|
|
@@ -966,7 +1706,7 @@ async function ensureSchema() {
|
|
|
966
1706
|
ON notifications(read);
|
|
967
1707
|
|
|
968
1708
|
CREATE INDEX IF NOT EXISTS idx_notifications_agent
|
|
969
|
-
ON notifications(agent_id);
|
|
1709
|
+
ON notifications(agent_id, session_scope);
|
|
970
1710
|
|
|
971
1711
|
CREATE INDEX IF NOT EXISTS idx_notifications_task_file
|
|
972
1712
|
ON notifications(task_file);
|
|
@@ -1004,6 +1744,7 @@ async function ensureSchema() {
|
|
|
1004
1744
|
target_agent TEXT NOT NULL,
|
|
1005
1745
|
target_project TEXT,
|
|
1006
1746
|
target_device TEXT NOT NULL DEFAULT 'local',
|
|
1747
|
+
session_scope TEXT,
|
|
1007
1748
|
content TEXT NOT NULL,
|
|
1008
1749
|
priority TEXT DEFAULT 'normal',
|
|
1009
1750
|
status TEXT DEFAULT 'pending',
|
|
@@ -1017,10 +1758,31 @@ async function ensureSchema() {
|
|
|
1017
1758
|
);
|
|
1018
1759
|
|
|
1019
1760
|
CREATE INDEX IF NOT EXISTS idx_messages_target
|
|
1020
|
-
ON messages(target_agent, status);
|
|
1761
|
+
ON messages(target_agent, session_scope, status);
|
|
1021
1762
|
|
|
1022
1763
|
CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
|
|
1023
|
-
ON messages(target_agent, from_agent, server_seq);
|
|
1764
|
+
ON messages(target_agent, session_scope, from_agent, server_seq);
|
|
1765
|
+
`);
|
|
1766
|
+
try {
|
|
1767
|
+
await client.execute({
|
|
1768
|
+
sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
|
|
1769
|
+
args: []
|
|
1770
|
+
});
|
|
1771
|
+
} catch {
|
|
1772
|
+
}
|
|
1773
|
+
try {
|
|
1774
|
+
await client.execute({
|
|
1775
|
+
sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
|
|
1776
|
+
args: []
|
|
1777
|
+
});
|
|
1778
|
+
} catch {
|
|
1779
|
+
}
|
|
1780
|
+
await client.executeMultiple(`
|
|
1781
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
|
|
1782
|
+
ON notifications(agent_id, session_scope, read, created_at);
|
|
1783
|
+
|
|
1784
|
+
CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
|
|
1785
|
+
ON messages(target_agent, session_scope, status, created_at);
|
|
1024
1786
|
`);
|
|
1025
1787
|
try {
|
|
1026
1788
|
await client.execute({
|
|
@@ -1604,17 +2366,26 @@ async function ensureSchema() {
|
|
|
1604
2366
|
} catch {
|
|
1605
2367
|
}
|
|
1606
2368
|
}
|
|
2369
|
+
try {
|
|
2370
|
+
await client.execute({
|
|
2371
|
+
sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
|
|
2372
|
+
args: []
|
|
2373
|
+
});
|
|
2374
|
+
} catch {
|
|
2375
|
+
}
|
|
1607
2376
|
}
|
|
1608
|
-
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
|
|
2377
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
|
|
1609
2378
|
var init_database = __esm({
|
|
1610
2379
|
"src/lib/database.ts"() {
|
|
1611
2380
|
"use strict";
|
|
1612
2381
|
init_db_retry();
|
|
1613
2382
|
init_employees();
|
|
2383
|
+
init_database_adapter();
|
|
1614
2384
|
_client = null;
|
|
1615
2385
|
_resilientClient = null;
|
|
1616
2386
|
_walCheckpointTimer = null;
|
|
1617
2387
|
_daemonClient = null;
|
|
2388
|
+
_adapterClient = null;
|
|
1618
2389
|
initTurso = initDatabase;
|
|
1619
2390
|
}
|
|
1620
2391
|
});
|
|
@@ -1624,6 +2395,7 @@ var shard_manager_exports = {};
|
|
|
1624
2395
|
__export(shard_manager_exports, {
|
|
1625
2396
|
disposeShards: () => disposeShards,
|
|
1626
2397
|
ensureShardSchema: () => ensureShardSchema,
|
|
2398
|
+
getOpenShardCount: () => getOpenShardCount,
|
|
1627
2399
|
getReadyShardClient: () => getReadyShardClient,
|
|
1628
2400
|
getShardClient: () => getShardClient,
|
|
1629
2401
|
getShardsDir: () => getShardsDir,
|
|
@@ -1632,15 +2404,18 @@ __export(shard_manager_exports, {
|
|
|
1632
2404
|
listShards: () => listShards,
|
|
1633
2405
|
shardExists: () => shardExists
|
|
1634
2406
|
});
|
|
1635
|
-
import
|
|
1636
|
-
import { existsSync as
|
|
2407
|
+
import path7 from "path";
|
|
2408
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
|
|
1637
2409
|
import { createClient as createClient2 } from "@libsql/client";
|
|
1638
2410
|
function initShardManager(encryptionKey) {
|
|
1639
2411
|
_encryptionKey = encryptionKey;
|
|
1640
|
-
if (!
|
|
1641
|
-
|
|
2412
|
+
if (!existsSync7(SHARDS_DIR)) {
|
|
2413
|
+
mkdirSync2(SHARDS_DIR, { recursive: true });
|
|
1642
2414
|
}
|
|
1643
2415
|
_shardingEnabled = true;
|
|
2416
|
+
if (_evictionTimer) clearInterval(_evictionTimer);
|
|
2417
|
+
_evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
|
|
2418
|
+
_evictionTimer.unref();
|
|
1644
2419
|
}
|
|
1645
2420
|
function isShardingEnabled() {
|
|
1646
2421
|
return _shardingEnabled;
|
|
@@ -1657,21 +2432,28 @@ function getShardClient(projectName) {
|
|
|
1657
2432
|
throw new Error(`Invalid project name for shard: "${projectName}"`);
|
|
1658
2433
|
}
|
|
1659
2434
|
const cached = _shards.get(safeName);
|
|
1660
|
-
if (cached)
|
|
1661
|
-
|
|
2435
|
+
if (cached) {
|
|
2436
|
+
_shardLastAccess.set(safeName, Date.now());
|
|
2437
|
+
return cached;
|
|
2438
|
+
}
|
|
2439
|
+
while (_shards.size >= MAX_OPEN_SHARDS) {
|
|
2440
|
+
evictLRU();
|
|
2441
|
+
}
|
|
2442
|
+
const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
|
|
1662
2443
|
const client = createClient2({
|
|
1663
2444
|
url: `file:${dbPath}`,
|
|
1664
2445
|
encryptionKey: _encryptionKey
|
|
1665
2446
|
});
|
|
1666
2447
|
_shards.set(safeName, client);
|
|
2448
|
+
_shardLastAccess.set(safeName, Date.now());
|
|
1667
2449
|
return client;
|
|
1668
2450
|
}
|
|
1669
2451
|
function shardExists(projectName) {
|
|
1670
2452
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1671
|
-
return
|
|
2453
|
+
return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
|
|
1672
2454
|
}
|
|
1673
2455
|
function listShards() {
|
|
1674
|
-
if (!
|
|
2456
|
+
if (!existsSync7(SHARDS_DIR)) return [];
|
|
1675
2457
|
return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
1676
2458
|
}
|
|
1677
2459
|
async function ensureShardSchema(client) {
|
|
@@ -1723,6 +2505,8 @@ async function ensureShardSchema(client) {
|
|
|
1723
2505
|
for (const col of [
|
|
1724
2506
|
"ALTER TABLE memories ADD COLUMN task_id TEXT",
|
|
1725
2507
|
"ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
|
|
2508
|
+
"ALTER TABLE memories ADD COLUMN author_device_id TEXT",
|
|
2509
|
+
"ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
|
|
1726
2510
|
"ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
|
|
1727
2511
|
"ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
|
|
1728
2512
|
"ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
|
|
@@ -1745,7 +2529,23 @@ async function ensureShardSchema(client) {
|
|
|
1745
2529
|
// MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
|
|
1746
2530
|
"ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
|
|
1747
2531
|
"ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
|
|
1748
|
-
"ALTER TABLE memories ADD COLUMN trajectory TEXT"
|
|
2532
|
+
"ALTER TABLE memories ADD COLUMN trajectory TEXT",
|
|
2533
|
+
// Metadata enrichment columns (must match database.ts)
|
|
2534
|
+
"ALTER TABLE memories ADD COLUMN intent TEXT",
|
|
2535
|
+
"ALTER TABLE memories ADD COLUMN outcome TEXT",
|
|
2536
|
+
"ALTER TABLE memories ADD COLUMN domain TEXT",
|
|
2537
|
+
"ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
|
|
2538
|
+
"ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
|
|
2539
|
+
"ALTER TABLE memories ADD COLUMN chain_position TEXT",
|
|
2540
|
+
"ALTER TABLE memories ADD COLUMN review_status TEXT",
|
|
2541
|
+
"ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
|
|
2542
|
+
"ALTER TABLE memories ADD COLUMN file_paths TEXT",
|
|
2543
|
+
"ALTER TABLE memories ADD COLUMN commit_hash TEXT",
|
|
2544
|
+
"ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
|
|
2545
|
+
"ALTER TABLE memories ADD COLUMN token_cost REAL",
|
|
2546
|
+
"ALTER TABLE memories ADD COLUMN audience TEXT",
|
|
2547
|
+
"ALTER TABLE memories ADD COLUMN language_type TEXT",
|
|
2548
|
+
"ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
|
|
1749
2549
|
]) {
|
|
1750
2550
|
try {
|
|
1751
2551
|
await client.execute(col);
|
|
@@ -1844,21 +2644,69 @@ async function getReadyShardClient(projectName) {
|
|
|
1844
2644
|
await ensureShardSchema(client);
|
|
1845
2645
|
return client;
|
|
1846
2646
|
}
|
|
2647
|
+
function evictLRU() {
|
|
2648
|
+
let oldest = null;
|
|
2649
|
+
let oldestTime = Infinity;
|
|
2650
|
+
for (const [name, time] of _shardLastAccess) {
|
|
2651
|
+
if (time < oldestTime) {
|
|
2652
|
+
oldestTime = time;
|
|
2653
|
+
oldest = name;
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
if (oldest) {
|
|
2657
|
+
const client = _shards.get(oldest);
|
|
2658
|
+
if (client) {
|
|
2659
|
+
client.close();
|
|
2660
|
+
}
|
|
2661
|
+
_shards.delete(oldest);
|
|
2662
|
+
_shardLastAccess.delete(oldest);
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
function evictIdleShards() {
|
|
2666
|
+
const now = Date.now();
|
|
2667
|
+
const toEvict = [];
|
|
2668
|
+
for (const [name, lastAccess] of _shardLastAccess) {
|
|
2669
|
+
if (now - lastAccess > SHARD_IDLE_MS) {
|
|
2670
|
+
toEvict.push(name);
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
for (const name of toEvict) {
|
|
2674
|
+
const client = _shards.get(name);
|
|
2675
|
+
if (client) {
|
|
2676
|
+
client.close();
|
|
2677
|
+
}
|
|
2678
|
+
_shards.delete(name);
|
|
2679
|
+
_shardLastAccess.delete(name);
|
|
2680
|
+
}
|
|
2681
|
+
}
|
|
2682
|
+
function getOpenShardCount() {
|
|
2683
|
+
return _shards.size;
|
|
2684
|
+
}
|
|
1847
2685
|
function disposeShards() {
|
|
2686
|
+
if (_evictionTimer) {
|
|
2687
|
+
clearInterval(_evictionTimer);
|
|
2688
|
+
_evictionTimer = null;
|
|
2689
|
+
}
|
|
1848
2690
|
for (const [, client] of _shards) {
|
|
1849
2691
|
client.close();
|
|
1850
2692
|
}
|
|
1851
2693
|
_shards.clear();
|
|
2694
|
+
_shardLastAccess.clear();
|
|
1852
2695
|
_shardingEnabled = false;
|
|
1853
2696
|
_encryptionKey = null;
|
|
1854
2697
|
}
|
|
1855
|
-
var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
|
|
2698
|
+
var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
|
|
1856
2699
|
var init_shard_manager = __esm({
|
|
1857
2700
|
"src/lib/shard-manager.ts"() {
|
|
1858
2701
|
"use strict";
|
|
1859
2702
|
init_config();
|
|
1860
|
-
SHARDS_DIR =
|
|
2703
|
+
SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
|
|
2704
|
+
SHARD_IDLE_MS = 5 * 60 * 1e3;
|
|
2705
|
+
MAX_OPEN_SHARDS = 10;
|
|
2706
|
+
EVICTION_INTERVAL_MS = 60 * 1e3;
|
|
1861
2707
|
_shards = /* @__PURE__ */ new Map();
|
|
2708
|
+
_shardLastAccess = /* @__PURE__ */ new Map();
|
|
2709
|
+
_evictionTimer = null;
|
|
1862
2710
|
_encryptionKey = null;
|
|
1863
2711
|
_shardingEnabled = false;
|
|
1864
2712
|
}
|
|
@@ -2205,16 +3053,16 @@ init_database();
|
|
|
2205
3053
|
|
|
2206
3054
|
// src/lib/keychain.ts
|
|
2207
3055
|
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2208
|
-
import { existsSync as
|
|
2209
|
-
import
|
|
2210
|
-
import
|
|
3056
|
+
import { existsSync as existsSync6 } from "fs";
|
|
3057
|
+
import path6 from "path";
|
|
3058
|
+
import os5 from "os";
|
|
2211
3059
|
var SERVICE = "exe-mem";
|
|
2212
3060
|
var ACCOUNT = "master-key";
|
|
2213
3061
|
function getKeyDir() {
|
|
2214
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ??
|
|
3062
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
|
|
2215
3063
|
}
|
|
2216
3064
|
function getKeyPath() {
|
|
2217
|
-
return
|
|
3065
|
+
return path6.join(getKeyDir(), "master.key");
|
|
2218
3066
|
}
|
|
2219
3067
|
async function tryKeytar() {
|
|
2220
3068
|
try {
|
|
@@ -2235,9 +3083,9 @@ async function getMasterKey() {
|
|
|
2235
3083
|
}
|
|
2236
3084
|
}
|
|
2237
3085
|
const keyPath = getKeyPath();
|
|
2238
|
-
if (!
|
|
3086
|
+
if (!existsSync6(keyPath)) {
|
|
2239
3087
|
process.stderr.write(
|
|
2240
|
-
`[keychain] Key not found at ${keyPath} (HOME=${
|
|
3088
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2241
3089
|
`
|
|
2242
3090
|
);
|
|
2243
3091
|
return null;
|