@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-review.js
CHANGED
|
@@ -9,9 +9,34 @@ 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
|
+
async function enforcePrivateFile(filePath) {
|
|
23
|
+
try {
|
|
24
|
+
await chmod(filePath, PRIVATE_FILE_MODE);
|
|
25
|
+
} catch {
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
|
|
29
|
+
var init_secure_files = __esm({
|
|
30
|
+
"src/lib/secure-files.ts"() {
|
|
31
|
+
"use strict";
|
|
32
|
+
PRIVATE_DIR_MODE = 448;
|
|
33
|
+
PRIVATE_FILE_MODE = 384;
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
|
|
12
37
|
// src/lib/config.ts
|
|
13
|
-
import { readFile, writeFile
|
|
14
|
-
import { readFileSync, existsSync, renameSync } from "fs";
|
|
38
|
+
import { readFile, writeFile } from "fs/promises";
|
|
39
|
+
import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
|
|
15
40
|
import path from "path";
|
|
16
41
|
import os from "os";
|
|
17
42
|
function resolveDataDir() {
|
|
@@ -19,7 +44,7 @@ function resolveDataDir() {
|
|
|
19
44
|
if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
|
|
20
45
|
const newDir = path.join(os.homedir(), ".exe-os");
|
|
21
46
|
const legacyDir = path.join(os.homedir(), ".exe-mem");
|
|
22
|
-
if (!
|
|
47
|
+
if (!existsSync2(newDir) && existsSync2(legacyDir)) {
|
|
23
48
|
try {
|
|
24
49
|
renameSync(legacyDir, newDir);
|
|
25
50
|
process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
|
|
@@ -82,9 +107,9 @@ function normalizeAutoUpdate(raw) {
|
|
|
82
107
|
}
|
|
83
108
|
async function loadConfig() {
|
|
84
109
|
const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
|
|
85
|
-
await
|
|
110
|
+
await ensurePrivateDir(dir);
|
|
86
111
|
const configPath = path.join(dir, "config.json");
|
|
87
|
-
if (!
|
|
112
|
+
if (!existsSync2(configPath)) {
|
|
88
113
|
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
|
|
89
114
|
}
|
|
90
115
|
const raw = await readFile(configPath, "utf-8");
|
|
@@ -97,6 +122,7 @@ async function loadConfig() {
|
|
|
97
122
|
`);
|
|
98
123
|
try {
|
|
99
124
|
await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
|
|
125
|
+
await enforcePrivateFile(configPath);
|
|
100
126
|
} catch {
|
|
101
127
|
}
|
|
102
128
|
}
|
|
@@ -116,6 +142,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
|
|
|
116
142
|
var init_config = __esm({
|
|
117
143
|
"src/lib/config.ts"() {
|
|
118
144
|
"use strict";
|
|
145
|
+
init_secure_files();
|
|
119
146
|
EXE_AI_DIR = resolveDataDir();
|
|
120
147
|
DB_PATH = path.join(EXE_AI_DIR, "memories.db");
|
|
121
148
|
MODELS_DIR = path.join(EXE_AI_DIR, "models");
|
|
@@ -194,7 +221,7 @@ var init_config = __esm({
|
|
|
194
221
|
|
|
195
222
|
// src/lib/employees.ts
|
|
196
223
|
import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
|
|
197
|
-
import { existsSync as
|
|
224
|
+
import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
|
|
198
225
|
import { execSync } from "child_process";
|
|
199
226
|
import path2 from "path";
|
|
200
227
|
import os2 from "os";
|
|
@@ -211,7 +238,7 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
|
|
|
211
238
|
return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
|
|
212
239
|
}
|
|
213
240
|
async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
|
|
214
|
-
if (!
|
|
241
|
+
if (!existsSync3(employeesPath)) {
|
|
215
242
|
return [];
|
|
216
243
|
}
|
|
217
244
|
const raw = await readFile2(employeesPath, "utf-8");
|
|
@@ -222,7 +249,7 @@ async function loadEmployees(employeesPath = EMPLOYEES_PATH) {
|
|
|
222
249
|
}
|
|
223
250
|
}
|
|
224
251
|
function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
225
|
-
if (!
|
|
252
|
+
if (!existsSync3(employeesPath)) return [];
|
|
226
253
|
try {
|
|
227
254
|
return JSON.parse(readFileSync2(employeesPath, "utf-8"));
|
|
228
255
|
} catch {
|
|
@@ -232,7 +259,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
|
232
259
|
function getEmployee(employees, name) {
|
|
233
260
|
return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
234
261
|
}
|
|
235
|
-
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
|
|
262
|
+
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
|
|
236
263
|
var init_employees = __esm({
|
|
237
264
|
"src/lib/employees.ts"() {
|
|
238
265
|
"use strict";
|
|
@@ -240,6 +267,7 @@ var init_employees = __esm({
|
|
|
240
267
|
EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
|
|
241
268
|
DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
|
|
242
269
|
COORDINATOR_ROLE = "COO";
|
|
270
|
+
IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
|
|
243
271
|
}
|
|
244
272
|
});
|
|
245
273
|
|
|
@@ -298,9 +326,605 @@ var init_db_retry = __esm({
|
|
|
298
326
|
}
|
|
299
327
|
});
|
|
300
328
|
|
|
329
|
+
// src/lib/database-adapter.ts
|
|
330
|
+
import os3 from "os";
|
|
331
|
+
import path3 from "path";
|
|
332
|
+
import { createRequire } from "module";
|
|
333
|
+
import { pathToFileURL } from "url";
|
|
334
|
+
function quotedIdentifier(identifier) {
|
|
335
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
336
|
+
}
|
|
337
|
+
function unqualifiedTableName(name) {
|
|
338
|
+
const raw = name.trim().replace(/^"|"$/g, "");
|
|
339
|
+
const parts = raw.split(".");
|
|
340
|
+
return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
|
|
341
|
+
}
|
|
342
|
+
function stripTrailingSemicolon(sql) {
|
|
343
|
+
return sql.trim().replace(/;+\s*$/u, "");
|
|
344
|
+
}
|
|
345
|
+
function appendClause(sql, clause) {
|
|
346
|
+
const trimmed = stripTrailingSemicolon(sql);
|
|
347
|
+
const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
|
|
348
|
+
if (!returningMatch) {
|
|
349
|
+
return `${trimmed}${clause}`;
|
|
350
|
+
}
|
|
351
|
+
const idx = returningMatch.index;
|
|
352
|
+
return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
|
|
353
|
+
}
|
|
354
|
+
function normalizeStatement(stmt) {
|
|
355
|
+
if (typeof stmt === "string") {
|
|
356
|
+
return { kind: "positional", sql: stmt, args: [] };
|
|
357
|
+
}
|
|
358
|
+
const sql = stmt.sql;
|
|
359
|
+
if (Array.isArray(stmt.args) || stmt.args === void 0) {
|
|
360
|
+
return { kind: "positional", sql, args: stmt.args ?? [] };
|
|
361
|
+
}
|
|
362
|
+
return { kind: "named", sql, args: stmt.args };
|
|
363
|
+
}
|
|
364
|
+
function rewriteBooleanLiterals(sql) {
|
|
365
|
+
let out = sql;
|
|
366
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
367
|
+
const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
|
|
368
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
|
|
369
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
|
|
370
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
|
|
371
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
|
|
372
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
|
|
373
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
|
|
374
|
+
}
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
377
|
+
function rewriteInsertOrIgnore(sql) {
|
|
378
|
+
if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
|
|
379
|
+
return sql;
|
|
380
|
+
}
|
|
381
|
+
const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
|
|
382
|
+
return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
|
|
383
|
+
}
|
|
384
|
+
function rewriteInsertOrReplace(sql) {
|
|
385
|
+
const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
|
|
386
|
+
if (!match) {
|
|
387
|
+
return sql;
|
|
388
|
+
}
|
|
389
|
+
const rawTable = match[1];
|
|
390
|
+
const rawColumns = match[2];
|
|
391
|
+
const remainder = match[3];
|
|
392
|
+
const tableName = unqualifiedTableName(rawTable);
|
|
393
|
+
const conflictKeys = UPSERT_KEYS[tableName];
|
|
394
|
+
if (!conflictKeys?.length) {
|
|
395
|
+
return sql;
|
|
396
|
+
}
|
|
397
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
398
|
+
const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
|
|
399
|
+
const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
|
|
400
|
+
const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
|
|
401
|
+
return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
|
|
402
|
+
}
|
|
403
|
+
function rewriteSql(sql) {
|
|
404
|
+
let out = sql;
|
|
405
|
+
out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
|
|
406
|
+
out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
|
|
407
|
+
out = rewriteBooleanLiterals(out);
|
|
408
|
+
out = rewriteInsertOrReplace(out);
|
|
409
|
+
out = rewriteInsertOrIgnore(out);
|
|
410
|
+
return stripTrailingSemicolon(out);
|
|
411
|
+
}
|
|
412
|
+
function toBoolean(value) {
|
|
413
|
+
if (value === null || value === void 0) return value;
|
|
414
|
+
if (typeof value === "boolean") return value;
|
|
415
|
+
if (typeof value === "number") return value !== 0;
|
|
416
|
+
if (typeof value === "bigint") return value !== 0n;
|
|
417
|
+
if (typeof value === "string") {
|
|
418
|
+
const normalized = value.trim().toLowerCase();
|
|
419
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
420
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
421
|
+
}
|
|
422
|
+
return Boolean(value);
|
|
423
|
+
}
|
|
424
|
+
function countQuestionMarks(sql, end) {
|
|
425
|
+
let count = 0;
|
|
426
|
+
let inSingle = false;
|
|
427
|
+
let inDouble = false;
|
|
428
|
+
let inLineComment = false;
|
|
429
|
+
let inBlockComment = false;
|
|
430
|
+
for (let i = 0; i < end; i++) {
|
|
431
|
+
const ch = sql[i];
|
|
432
|
+
const next = sql[i + 1];
|
|
433
|
+
if (inLineComment) {
|
|
434
|
+
if (ch === "\n") inLineComment = false;
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
if (inBlockComment) {
|
|
438
|
+
if (ch === "*" && next === "/") {
|
|
439
|
+
inBlockComment = false;
|
|
440
|
+
i += 1;
|
|
441
|
+
}
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
445
|
+
inLineComment = true;
|
|
446
|
+
i += 1;
|
|
447
|
+
continue;
|
|
448
|
+
}
|
|
449
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
450
|
+
inBlockComment = true;
|
|
451
|
+
i += 1;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
455
|
+
inSingle = !inSingle;
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
459
|
+
inDouble = !inDouble;
|
|
460
|
+
continue;
|
|
461
|
+
}
|
|
462
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
463
|
+
count += 1;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return count;
|
|
467
|
+
}
|
|
468
|
+
function findBooleanPlaceholderIndexes(sql) {
|
|
469
|
+
const indexes = /* @__PURE__ */ new Set();
|
|
470
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
471
|
+
const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
|
|
472
|
+
for (const match of sql.matchAll(pattern)) {
|
|
473
|
+
const matchText = match[0];
|
|
474
|
+
const qIndex = match.index + matchText.lastIndexOf("?");
|
|
475
|
+
indexes.add(countQuestionMarks(sql, qIndex + 1));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
return indexes;
|
|
479
|
+
}
|
|
480
|
+
function coerceInsertBooleanArgs(sql, args) {
|
|
481
|
+
const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
|
|
482
|
+
if (!match) return;
|
|
483
|
+
const rawTable = match[1];
|
|
484
|
+
const rawColumns = match[2];
|
|
485
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
486
|
+
if (!boolColumns?.size) return;
|
|
487
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
488
|
+
for (const [index, column] of columns.entries()) {
|
|
489
|
+
if (boolColumns.has(column) && index < args.length) {
|
|
490
|
+
args[index] = toBoolean(args[index]);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
function coerceUpdateBooleanArgs(sql, args) {
|
|
495
|
+
const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
|
|
496
|
+
if (!match) return;
|
|
497
|
+
const rawTable = match[1];
|
|
498
|
+
const setClause = match[2];
|
|
499
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
500
|
+
if (!boolColumns?.size) return;
|
|
501
|
+
const assignments = setClause.split(",");
|
|
502
|
+
let placeholderIndex = 0;
|
|
503
|
+
for (const assignment of assignments) {
|
|
504
|
+
if (!assignment.includes("?")) continue;
|
|
505
|
+
placeholderIndex += 1;
|
|
506
|
+
const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
|
|
507
|
+
if (colMatch && boolColumns.has(colMatch[1])) {
|
|
508
|
+
args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function coerceBooleanArgs(sql, args) {
|
|
513
|
+
const nextArgs = [...args];
|
|
514
|
+
coerceInsertBooleanArgs(sql, nextArgs);
|
|
515
|
+
coerceUpdateBooleanArgs(sql, nextArgs);
|
|
516
|
+
const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
|
|
517
|
+
for (const index of placeholderIndexes) {
|
|
518
|
+
if (index > 0 && index <= nextArgs.length) {
|
|
519
|
+
nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return nextArgs;
|
|
523
|
+
}
|
|
524
|
+
function convertQuestionMarksToDollarParams(sql) {
|
|
525
|
+
let out = "";
|
|
526
|
+
let placeholder = 0;
|
|
527
|
+
let inSingle = false;
|
|
528
|
+
let inDouble = false;
|
|
529
|
+
let inLineComment = false;
|
|
530
|
+
let inBlockComment = false;
|
|
531
|
+
for (let i = 0; i < sql.length; i++) {
|
|
532
|
+
const ch = sql[i];
|
|
533
|
+
const next = sql[i + 1];
|
|
534
|
+
if (inLineComment) {
|
|
535
|
+
out += ch;
|
|
536
|
+
if (ch === "\n") inLineComment = false;
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (inBlockComment) {
|
|
540
|
+
out += ch;
|
|
541
|
+
if (ch === "*" && next === "/") {
|
|
542
|
+
out += next;
|
|
543
|
+
inBlockComment = false;
|
|
544
|
+
i += 1;
|
|
545
|
+
}
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
549
|
+
out += ch + next;
|
|
550
|
+
inLineComment = true;
|
|
551
|
+
i += 1;
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
555
|
+
out += ch + next;
|
|
556
|
+
inBlockComment = true;
|
|
557
|
+
i += 1;
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
561
|
+
inSingle = !inSingle;
|
|
562
|
+
out += ch;
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
566
|
+
inDouble = !inDouble;
|
|
567
|
+
out += ch;
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
571
|
+
placeholder += 1;
|
|
572
|
+
out += `$${placeholder}`;
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
out += ch;
|
|
576
|
+
}
|
|
577
|
+
return out;
|
|
578
|
+
}
|
|
579
|
+
function translateStatementForPostgres(stmt) {
|
|
580
|
+
const normalized = normalizeStatement(stmt);
|
|
581
|
+
if (normalized.kind === "named") {
|
|
582
|
+
throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
|
|
583
|
+
}
|
|
584
|
+
const rewrittenSql = rewriteSql(normalized.sql);
|
|
585
|
+
const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
|
|
586
|
+
return {
|
|
587
|
+
sql: convertQuestionMarksToDollarParams(rewrittenSql),
|
|
588
|
+
args: coercedArgs
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
function shouldBypassPostgres(stmt) {
|
|
592
|
+
const normalized = normalizeStatement(stmt);
|
|
593
|
+
if (normalized.kind === "named") {
|
|
594
|
+
return true;
|
|
595
|
+
}
|
|
596
|
+
return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
|
|
597
|
+
}
|
|
598
|
+
function shouldFallbackOnError(error) {
|
|
599
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
600
|
+
return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
|
|
601
|
+
}
|
|
602
|
+
function isReadQuery(sql) {
|
|
603
|
+
const trimmed = sql.trimStart();
|
|
604
|
+
return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
|
|
605
|
+
}
|
|
606
|
+
function buildRow(row, columns) {
|
|
607
|
+
const values = columns.map((column) => row[column]);
|
|
608
|
+
return Object.assign(values, row);
|
|
609
|
+
}
|
|
610
|
+
function buildResultSet(rows, rowsAffected = 0) {
|
|
611
|
+
const columns = rows[0] ? Object.keys(rows[0]) : [];
|
|
612
|
+
const resultRows = rows.map((row) => buildRow(row, columns));
|
|
613
|
+
return {
|
|
614
|
+
columns,
|
|
615
|
+
columnTypes: columns.map(() => ""),
|
|
616
|
+
rows: resultRows,
|
|
617
|
+
rowsAffected,
|
|
618
|
+
lastInsertRowid: void 0,
|
|
619
|
+
toJSON() {
|
|
620
|
+
return {
|
|
621
|
+
columns,
|
|
622
|
+
columnTypes: columns.map(() => ""),
|
|
623
|
+
rows,
|
|
624
|
+
rowsAffected,
|
|
625
|
+
lastInsertRowid: void 0
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
async function loadPrismaClient() {
|
|
631
|
+
if (!prismaClientPromise) {
|
|
632
|
+
prismaClientPromise = (async () => {
|
|
633
|
+
const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
|
|
634
|
+
if (explicitPath) {
|
|
635
|
+
const module2 = await import(pathToFileURL(explicitPath).href);
|
|
636
|
+
const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
|
|
637
|
+
if (!PrismaClient2) {
|
|
638
|
+
throw new Error(`No PrismaClient export found at ${explicitPath}`);
|
|
639
|
+
}
|
|
640
|
+
return new PrismaClient2();
|
|
641
|
+
}
|
|
642
|
+
const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
|
|
643
|
+
const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
|
|
644
|
+
const prismaEntry = requireFromExeDb.resolve("@prisma/client");
|
|
645
|
+
const module = await import(pathToFileURL(prismaEntry).href);
|
|
646
|
+
const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
|
|
647
|
+
if (!PrismaClient) {
|
|
648
|
+
throw new Error(`No PrismaClient export found in ${prismaEntry}`);
|
|
649
|
+
}
|
|
650
|
+
return new PrismaClient();
|
|
651
|
+
})();
|
|
652
|
+
}
|
|
653
|
+
return prismaClientPromise;
|
|
654
|
+
}
|
|
655
|
+
async function ensureCompatibilityViews(prisma) {
|
|
656
|
+
if (!compatibilityBootstrapPromise) {
|
|
657
|
+
compatibilityBootstrapPromise = (async () => {
|
|
658
|
+
for (const mapping of VIEW_MAPPINGS) {
|
|
659
|
+
const relation = mapping.source.replace(/"/g, "");
|
|
660
|
+
const rows = await prisma.$queryRawUnsafe(
|
|
661
|
+
"SELECT to_regclass($1) AS regclass",
|
|
662
|
+
relation
|
|
663
|
+
);
|
|
664
|
+
if (!rows[0]?.regclass) {
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
667
|
+
await prisma.$executeRawUnsafe(
|
|
668
|
+
`CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
})();
|
|
672
|
+
}
|
|
673
|
+
return compatibilityBootstrapPromise;
|
|
674
|
+
}
|
|
675
|
+
async function executeOnPrisma(executor, stmt) {
|
|
676
|
+
const translated = translateStatementForPostgres(stmt);
|
|
677
|
+
if (isReadQuery(translated.sql)) {
|
|
678
|
+
const rows = await executor.$queryRawUnsafe(
|
|
679
|
+
translated.sql,
|
|
680
|
+
...translated.args
|
|
681
|
+
);
|
|
682
|
+
return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
|
|
683
|
+
}
|
|
684
|
+
const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
|
|
685
|
+
return buildResultSet([], rowsAffected);
|
|
686
|
+
}
|
|
687
|
+
function splitSqlStatements(sql) {
|
|
688
|
+
const parts = [];
|
|
689
|
+
let current = "";
|
|
690
|
+
let inSingle = false;
|
|
691
|
+
let inDouble = false;
|
|
692
|
+
let inLineComment = false;
|
|
693
|
+
let inBlockComment = false;
|
|
694
|
+
for (let i = 0; i < sql.length; i++) {
|
|
695
|
+
const ch = sql[i];
|
|
696
|
+
const next = sql[i + 1];
|
|
697
|
+
if (inLineComment) {
|
|
698
|
+
current += ch;
|
|
699
|
+
if (ch === "\n") inLineComment = false;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
if (inBlockComment) {
|
|
703
|
+
current += ch;
|
|
704
|
+
if (ch === "*" && next === "/") {
|
|
705
|
+
current += next;
|
|
706
|
+
inBlockComment = false;
|
|
707
|
+
i += 1;
|
|
708
|
+
}
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
712
|
+
current += ch + next;
|
|
713
|
+
inLineComment = true;
|
|
714
|
+
i += 1;
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
718
|
+
current += ch + next;
|
|
719
|
+
inBlockComment = true;
|
|
720
|
+
i += 1;
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
724
|
+
inSingle = !inSingle;
|
|
725
|
+
current += ch;
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
729
|
+
inDouble = !inDouble;
|
|
730
|
+
current += ch;
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
if (!inSingle && !inDouble && ch === ";") {
|
|
734
|
+
if (current.trim()) {
|
|
735
|
+
parts.push(current.trim());
|
|
736
|
+
}
|
|
737
|
+
current = "";
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
current += ch;
|
|
741
|
+
}
|
|
742
|
+
if (current.trim()) {
|
|
743
|
+
parts.push(current.trim());
|
|
744
|
+
}
|
|
745
|
+
return parts;
|
|
746
|
+
}
|
|
747
|
+
async function createPrismaDbAdapter(fallbackClient) {
|
|
748
|
+
const prisma = await loadPrismaClient();
|
|
749
|
+
await ensureCompatibilityViews(prisma);
|
|
750
|
+
let closed = false;
|
|
751
|
+
let adapter;
|
|
752
|
+
const fallbackExecute = async (stmt, error) => {
|
|
753
|
+
if (!fallbackClient) {
|
|
754
|
+
if (error) throw error;
|
|
755
|
+
throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
|
|
756
|
+
}
|
|
757
|
+
if (error) {
|
|
758
|
+
process.stderr.write(
|
|
759
|
+
`[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
760
|
+
`
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
return fallbackClient.execute(stmt);
|
|
764
|
+
};
|
|
765
|
+
adapter = {
|
|
766
|
+
async execute(stmt) {
|
|
767
|
+
if (shouldBypassPostgres(stmt)) {
|
|
768
|
+
return fallbackExecute(stmt);
|
|
769
|
+
}
|
|
770
|
+
try {
|
|
771
|
+
return await executeOnPrisma(prisma, stmt);
|
|
772
|
+
} catch (error) {
|
|
773
|
+
if (shouldFallbackOnError(error)) {
|
|
774
|
+
return fallbackExecute(stmt, error);
|
|
775
|
+
}
|
|
776
|
+
throw error;
|
|
777
|
+
}
|
|
778
|
+
},
|
|
779
|
+
async batch(stmts, mode) {
|
|
780
|
+
if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
|
|
781
|
+
if (!fallbackClient) {
|
|
782
|
+
throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
|
|
783
|
+
}
|
|
784
|
+
return fallbackClient.batch(stmts, mode);
|
|
785
|
+
}
|
|
786
|
+
try {
|
|
787
|
+
if (prisma.$transaction) {
|
|
788
|
+
return await prisma.$transaction(async (tx) => {
|
|
789
|
+
const results2 = [];
|
|
790
|
+
for (const stmt of stmts) {
|
|
791
|
+
results2.push(await executeOnPrisma(tx, stmt));
|
|
792
|
+
}
|
|
793
|
+
return results2;
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
const results = [];
|
|
797
|
+
for (const stmt of stmts) {
|
|
798
|
+
results.push(await executeOnPrisma(prisma, stmt));
|
|
799
|
+
}
|
|
800
|
+
return results;
|
|
801
|
+
} catch (error) {
|
|
802
|
+
if (fallbackClient && shouldFallbackOnError(error)) {
|
|
803
|
+
process.stderr.write(
|
|
804
|
+
`[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
805
|
+
`
|
|
806
|
+
);
|
|
807
|
+
return fallbackClient.batch(stmts, mode);
|
|
808
|
+
}
|
|
809
|
+
throw error;
|
|
810
|
+
}
|
|
811
|
+
},
|
|
812
|
+
async migrate(stmts) {
|
|
813
|
+
if (fallbackClient) {
|
|
814
|
+
return fallbackClient.migrate(stmts);
|
|
815
|
+
}
|
|
816
|
+
return adapter.batch(stmts, "deferred");
|
|
817
|
+
},
|
|
818
|
+
async transaction(mode) {
|
|
819
|
+
if (!fallbackClient) {
|
|
820
|
+
throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
|
|
821
|
+
}
|
|
822
|
+
return fallbackClient.transaction(mode);
|
|
823
|
+
},
|
|
824
|
+
async executeMultiple(sql) {
|
|
825
|
+
if (fallbackClient && shouldBypassPostgres(sql)) {
|
|
826
|
+
return fallbackClient.executeMultiple(sql);
|
|
827
|
+
}
|
|
828
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
829
|
+
await adapter.execute(statement);
|
|
830
|
+
}
|
|
831
|
+
},
|
|
832
|
+
async sync() {
|
|
833
|
+
if (fallbackClient) {
|
|
834
|
+
return fallbackClient.sync();
|
|
835
|
+
}
|
|
836
|
+
return { frame_no: 0, frames_synced: 0 };
|
|
837
|
+
},
|
|
838
|
+
close() {
|
|
839
|
+
closed = true;
|
|
840
|
+
prismaClientPromise = null;
|
|
841
|
+
compatibilityBootstrapPromise = null;
|
|
842
|
+
void prisma.$disconnect?.();
|
|
843
|
+
},
|
|
844
|
+
get closed() {
|
|
845
|
+
return closed;
|
|
846
|
+
},
|
|
847
|
+
get protocol() {
|
|
848
|
+
return "prisma-postgres";
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
return adapter;
|
|
852
|
+
}
|
|
853
|
+
var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
|
|
854
|
+
var init_database_adapter = __esm({
|
|
855
|
+
"src/lib/database-adapter.ts"() {
|
|
856
|
+
"use strict";
|
|
857
|
+
VIEW_MAPPINGS = [
|
|
858
|
+
{ view: "memories", source: "memory.memory_records" },
|
|
859
|
+
{ view: "tasks", source: "memory.tasks" },
|
|
860
|
+
{ view: "behaviors", source: "memory.behaviors" },
|
|
861
|
+
{ view: "entities", source: "memory.entities" },
|
|
862
|
+
{ view: "relationships", source: "memory.relationships" },
|
|
863
|
+
{ view: "entity_memories", source: "memory.entity_memories" },
|
|
864
|
+
{ view: "entity_aliases", source: "memory.entity_aliases" },
|
|
865
|
+
{ view: "notifications", source: "memory.notifications" },
|
|
866
|
+
{ view: "messages", source: "memory.messages" },
|
|
867
|
+
{ view: "users", source: "wiki.users" },
|
|
868
|
+
{ view: "workspaces", source: "wiki.workspaces" },
|
|
869
|
+
{ view: "workspace_users", source: "wiki.workspace_users" },
|
|
870
|
+
{ view: "documents", source: "wiki.workspace_documents" },
|
|
871
|
+
{ view: "chats", source: "wiki.workspace_chats" }
|
|
872
|
+
];
|
|
873
|
+
UPSERT_KEYS = {
|
|
874
|
+
memories: ["id"],
|
|
875
|
+
tasks: ["id"],
|
|
876
|
+
behaviors: ["id"],
|
|
877
|
+
entities: ["id"],
|
|
878
|
+
relationships: ["id"],
|
|
879
|
+
entity_aliases: ["alias"],
|
|
880
|
+
notifications: ["id"],
|
|
881
|
+
messages: ["id"],
|
|
882
|
+
users: ["id"],
|
|
883
|
+
workspaces: ["id"],
|
|
884
|
+
workspace_users: ["id"],
|
|
885
|
+
documents: ["id"],
|
|
886
|
+
chats: ["id"]
|
|
887
|
+
};
|
|
888
|
+
BOOLEAN_COLUMNS_BY_TABLE = {
|
|
889
|
+
memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
|
|
890
|
+
behaviors: /* @__PURE__ */ new Set(["active"]),
|
|
891
|
+
notifications: /* @__PURE__ */ new Set(["read"]),
|
|
892
|
+
users: /* @__PURE__ */ new Set(["has_personal_memory"])
|
|
893
|
+
};
|
|
894
|
+
BOOLEAN_COLUMN_NAMES = new Set(
|
|
895
|
+
Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
|
|
896
|
+
);
|
|
897
|
+
IMMEDIATE_FALLBACK_PATTERNS = [
|
|
898
|
+
/\bPRAGMA\b/i,
|
|
899
|
+
/\bsqlite_master\b/i,
|
|
900
|
+
/(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
|
|
901
|
+
/\bMATCH\b/i,
|
|
902
|
+
/\bvector_distance_cos\s*\(/i,
|
|
903
|
+
/\bjson_extract\s*\(/i,
|
|
904
|
+
/\bjulianday\s*\(/i,
|
|
905
|
+
/\bstrftime\s*\(/i,
|
|
906
|
+
/\blast_insert_rowid\s*\(/i
|
|
907
|
+
];
|
|
908
|
+
prismaClientPromise = null;
|
|
909
|
+
compatibilityBootstrapPromise = null;
|
|
910
|
+
}
|
|
911
|
+
});
|
|
912
|
+
|
|
301
913
|
// src/lib/database.ts
|
|
302
914
|
import { createClient } from "@libsql/client";
|
|
303
915
|
async function initDatabase(config) {
|
|
916
|
+
if (_walCheckpointTimer) {
|
|
917
|
+
clearInterval(_walCheckpointTimer);
|
|
918
|
+
_walCheckpointTimer = null;
|
|
919
|
+
}
|
|
920
|
+
if (_daemonClient) {
|
|
921
|
+
_daemonClient.close();
|
|
922
|
+
_daemonClient = null;
|
|
923
|
+
}
|
|
924
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
925
|
+
_adapterClient.close();
|
|
926
|
+
}
|
|
927
|
+
_adapterClient = null;
|
|
304
928
|
if (_client) {
|
|
305
929
|
_client.close();
|
|
306
930
|
_client = null;
|
|
@@ -314,6 +938,7 @@ async function initDatabase(config) {
|
|
|
314
938
|
}
|
|
315
939
|
_client = createClient(opts);
|
|
316
940
|
_resilientClient = wrapWithRetry(_client);
|
|
941
|
+
_adapterClient = _resilientClient;
|
|
317
942
|
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
318
943
|
});
|
|
319
944
|
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
@@ -324,11 +949,17 @@ async function initDatabase(config) {
|
|
|
324
949
|
});
|
|
325
950
|
}, 3e4);
|
|
326
951
|
_walCheckpointTimer.unref();
|
|
952
|
+
if (process.env.DATABASE_URL) {
|
|
953
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
954
|
+
}
|
|
327
955
|
}
|
|
328
956
|
function getClient() {
|
|
329
|
-
if (!
|
|
957
|
+
if (!_adapterClient) {
|
|
330
958
|
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
331
959
|
}
|
|
960
|
+
if (process.env.DATABASE_URL) {
|
|
961
|
+
return _adapterClient;
|
|
962
|
+
}
|
|
332
963
|
if (process.env.EXE_IS_DAEMON === "1") {
|
|
333
964
|
return _resilientClient;
|
|
334
965
|
}
|
|
@@ -621,6 +1252,7 @@ async function ensureSchema() {
|
|
|
621
1252
|
project TEXT NOT NULL,
|
|
622
1253
|
summary TEXT NOT NULL,
|
|
623
1254
|
task_file TEXT,
|
|
1255
|
+
session_scope TEXT,
|
|
624
1256
|
read INTEGER NOT NULL DEFAULT 0,
|
|
625
1257
|
created_at TEXT NOT NULL
|
|
626
1258
|
);
|
|
@@ -629,7 +1261,7 @@ async function ensureSchema() {
|
|
|
629
1261
|
ON notifications(read);
|
|
630
1262
|
|
|
631
1263
|
CREATE INDEX IF NOT EXISTS idx_notifications_agent
|
|
632
|
-
ON notifications(agent_id);
|
|
1264
|
+
ON notifications(agent_id, session_scope);
|
|
633
1265
|
|
|
634
1266
|
CREATE INDEX IF NOT EXISTS idx_notifications_task_file
|
|
635
1267
|
ON notifications(task_file);
|
|
@@ -667,6 +1299,7 @@ async function ensureSchema() {
|
|
|
667
1299
|
target_agent TEXT NOT NULL,
|
|
668
1300
|
target_project TEXT,
|
|
669
1301
|
target_device TEXT NOT NULL DEFAULT 'local',
|
|
1302
|
+
session_scope TEXT,
|
|
670
1303
|
content TEXT NOT NULL,
|
|
671
1304
|
priority TEXT DEFAULT 'normal',
|
|
672
1305
|
status TEXT DEFAULT 'pending',
|
|
@@ -680,10 +1313,31 @@ async function ensureSchema() {
|
|
|
680
1313
|
);
|
|
681
1314
|
|
|
682
1315
|
CREATE INDEX IF NOT EXISTS idx_messages_target
|
|
683
|
-
ON messages(target_agent, status);
|
|
1316
|
+
ON messages(target_agent, session_scope, status);
|
|
684
1317
|
|
|
685
1318
|
CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
|
|
686
|
-
ON messages(target_agent, from_agent, server_seq);
|
|
1319
|
+
ON messages(target_agent, session_scope, from_agent, server_seq);
|
|
1320
|
+
`);
|
|
1321
|
+
try {
|
|
1322
|
+
await client.execute({
|
|
1323
|
+
sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
|
|
1324
|
+
args: []
|
|
1325
|
+
});
|
|
1326
|
+
} catch {
|
|
1327
|
+
}
|
|
1328
|
+
try {
|
|
1329
|
+
await client.execute({
|
|
1330
|
+
sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
|
|
1331
|
+
args: []
|
|
1332
|
+
});
|
|
1333
|
+
} catch {
|
|
1334
|
+
}
|
|
1335
|
+
await client.executeMultiple(`
|
|
1336
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
|
|
1337
|
+
ON notifications(agent_id, session_scope, read, created_at);
|
|
1338
|
+
|
|
1339
|
+
CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
|
|
1340
|
+
ON messages(target_agent, session_scope, status, created_at);
|
|
687
1341
|
`);
|
|
688
1342
|
try {
|
|
689
1343
|
await client.execute({
|
|
@@ -1267,17 +1921,26 @@ async function ensureSchema() {
|
|
|
1267
1921
|
} catch {
|
|
1268
1922
|
}
|
|
1269
1923
|
}
|
|
1924
|
+
try {
|
|
1925
|
+
await client.execute({
|
|
1926
|
+
sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
|
|
1927
|
+
args: []
|
|
1928
|
+
});
|
|
1929
|
+
} catch {
|
|
1930
|
+
}
|
|
1270
1931
|
}
|
|
1271
|
-
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
|
|
1932
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
|
|
1272
1933
|
var init_database = __esm({
|
|
1273
1934
|
"src/lib/database.ts"() {
|
|
1274
1935
|
"use strict";
|
|
1275
1936
|
init_db_retry();
|
|
1276
1937
|
init_employees();
|
|
1938
|
+
init_database_adapter();
|
|
1277
1939
|
_client = null;
|
|
1278
1940
|
_resilientClient = null;
|
|
1279
1941
|
_walCheckpointTimer = null;
|
|
1280
1942
|
_daemonClient = null;
|
|
1943
|
+
_adapterClient = null;
|
|
1281
1944
|
initTurso = initDatabase;
|
|
1282
1945
|
}
|
|
1283
1946
|
});
|
|
@@ -1287,6 +1950,7 @@ var shard_manager_exports = {};
|
|
|
1287
1950
|
__export(shard_manager_exports, {
|
|
1288
1951
|
disposeShards: () => disposeShards,
|
|
1289
1952
|
ensureShardSchema: () => ensureShardSchema,
|
|
1953
|
+
getOpenShardCount: () => getOpenShardCount,
|
|
1290
1954
|
getReadyShardClient: () => getReadyShardClient,
|
|
1291
1955
|
getShardClient: () => getShardClient,
|
|
1292
1956
|
getShardsDir: () => getShardsDir,
|
|
@@ -1295,15 +1959,18 @@ __export(shard_manager_exports, {
|
|
|
1295
1959
|
listShards: () => listShards,
|
|
1296
1960
|
shardExists: () => shardExists
|
|
1297
1961
|
});
|
|
1298
|
-
import
|
|
1299
|
-
import { existsSync as
|
|
1962
|
+
import path5 from "path";
|
|
1963
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
|
|
1300
1964
|
import { createClient as createClient2 } from "@libsql/client";
|
|
1301
1965
|
function initShardManager(encryptionKey) {
|
|
1302
1966
|
_encryptionKey = encryptionKey;
|
|
1303
|
-
if (!
|
|
1304
|
-
|
|
1967
|
+
if (!existsSync5(SHARDS_DIR)) {
|
|
1968
|
+
mkdirSync2(SHARDS_DIR, { recursive: true });
|
|
1305
1969
|
}
|
|
1306
1970
|
_shardingEnabled = true;
|
|
1971
|
+
if (_evictionTimer) clearInterval(_evictionTimer);
|
|
1972
|
+
_evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
|
|
1973
|
+
_evictionTimer.unref();
|
|
1307
1974
|
}
|
|
1308
1975
|
function isShardingEnabled() {
|
|
1309
1976
|
return _shardingEnabled;
|
|
@@ -1320,21 +1987,28 @@ function getShardClient(projectName) {
|
|
|
1320
1987
|
throw new Error(`Invalid project name for shard: "${projectName}"`);
|
|
1321
1988
|
}
|
|
1322
1989
|
const cached = _shards.get(safeName);
|
|
1323
|
-
if (cached)
|
|
1324
|
-
|
|
1990
|
+
if (cached) {
|
|
1991
|
+
_shardLastAccess.set(safeName, Date.now());
|
|
1992
|
+
return cached;
|
|
1993
|
+
}
|
|
1994
|
+
while (_shards.size >= MAX_OPEN_SHARDS) {
|
|
1995
|
+
evictLRU();
|
|
1996
|
+
}
|
|
1997
|
+
const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
|
|
1325
1998
|
const client = createClient2({
|
|
1326
1999
|
url: `file:${dbPath}`,
|
|
1327
2000
|
encryptionKey: _encryptionKey
|
|
1328
2001
|
});
|
|
1329
2002
|
_shards.set(safeName, client);
|
|
2003
|
+
_shardLastAccess.set(safeName, Date.now());
|
|
1330
2004
|
return client;
|
|
1331
2005
|
}
|
|
1332
2006
|
function shardExists(projectName) {
|
|
1333
2007
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1334
|
-
return
|
|
2008
|
+
return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
|
|
1335
2009
|
}
|
|
1336
2010
|
function listShards() {
|
|
1337
|
-
if (!
|
|
2011
|
+
if (!existsSync5(SHARDS_DIR)) return [];
|
|
1338
2012
|
return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
1339
2013
|
}
|
|
1340
2014
|
async function ensureShardSchema(client) {
|
|
@@ -1386,6 +2060,8 @@ async function ensureShardSchema(client) {
|
|
|
1386
2060
|
for (const col of [
|
|
1387
2061
|
"ALTER TABLE memories ADD COLUMN task_id TEXT",
|
|
1388
2062
|
"ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
|
|
2063
|
+
"ALTER TABLE memories ADD COLUMN author_device_id TEXT",
|
|
2064
|
+
"ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
|
|
1389
2065
|
"ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
|
|
1390
2066
|
"ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
|
|
1391
2067
|
"ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
|
|
@@ -1408,7 +2084,23 @@ async function ensureShardSchema(client) {
|
|
|
1408
2084
|
// MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
|
|
1409
2085
|
"ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
|
|
1410
2086
|
"ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
|
|
1411
|
-
"ALTER TABLE memories ADD COLUMN trajectory TEXT"
|
|
2087
|
+
"ALTER TABLE memories ADD COLUMN trajectory TEXT",
|
|
2088
|
+
// Metadata enrichment columns (must match database.ts)
|
|
2089
|
+
"ALTER TABLE memories ADD COLUMN intent TEXT",
|
|
2090
|
+
"ALTER TABLE memories ADD COLUMN outcome TEXT",
|
|
2091
|
+
"ALTER TABLE memories ADD COLUMN domain TEXT",
|
|
2092
|
+
"ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
|
|
2093
|
+
"ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
|
|
2094
|
+
"ALTER TABLE memories ADD COLUMN chain_position TEXT",
|
|
2095
|
+
"ALTER TABLE memories ADD COLUMN review_status TEXT",
|
|
2096
|
+
"ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
|
|
2097
|
+
"ALTER TABLE memories ADD COLUMN file_paths TEXT",
|
|
2098
|
+
"ALTER TABLE memories ADD COLUMN commit_hash TEXT",
|
|
2099
|
+
"ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
|
|
2100
|
+
"ALTER TABLE memories ADD COLUMN token_cost REAL",
|
|
2101
|
+
"ALTER TABLE memories ADD COLUMN audience TEXT",
|
|
2102
|
+
"ALTER TABLE memories ADD COLUMN language_type TEXT",
|
|
2103
|
+
"ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
|
|
1412
2104
|
]) {
|
|
1413
2105
|
try {
|
|
1414
2106
|
await client.execute(col);
|
|
@@ -1507,21 +2199,69 @@ async function getReadyShardClient(projectName) {
|
|
|
1507
2199
|
await ensureShardSchema(client);
|
|
1508
2200
|
return client;
|
|
1509
2201
|
}
|
|
2202
|
+
function evictLRU() {
|
|
2203
|
+
let oldest = null;
|
|
2204
|
+
let oldestTime = Infinity;
|
|
2205
|
+
for (const [name, time] of _shardLastAccess) {
|
|
2206
|
+
if (time < oldestTime) {
|
|
2207
|
+
oldestTime = time;
|
|
2208
|
+
oldest = name;
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
if (oldest) {
|
|
2212
|
+
const client = _shards.get(oldest);
|
|
2213
|
+
if (client) {
|
|
2214
|
+
client.close();
|
|
2215
|
+
}
|
|
2216
|
+
_shards.delete(oldest);
|
|
2217
|
+
_shardLastAccess.delete(oldest);
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
function evictIdleShards() {
|
|
2221
|
+
const now = Date.now();
|
|
2222
|
+
const toEvict = [];
|
|
2223
|
+
for (const [name, lastAccess] of _shardLastAccess) {
|
|
2224
|
+
if (now - lastAccess > SHARD_IDLE_MS) {
|
|
2225
|
+
toEvict.push(name);
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
for (const name of toEvict) {
|
|
2229
|
+
const client = _shards.get(name);
|
|
2230
|
+
if (client) {
|
|
2231
|
+
client.close();
|
|
2232
|
+
}
|
|
2233
|
+
_shards.delete(name);
|
|
2234
|
+
_shardLastAccess.delete(name);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
function getOpenShardCount() {
|
|
2238
|
+
return _shards.size;
|
|
2239
|
+
}
|
|
1510
2240
|
function disposeShards() {
|
|
2241
|
+
if (_evictionTimer) {
|
|
2242
|
+
clearInterval(_evictionTimer);
|
|
2243
|
+
_evictionTimer = null;
|
|
2244
|
+
}
|
|
1511
2245
|
for (const [, client] of _shards) {
|
|
1512
2246
|
client.close();
|
|
1513
2247
|
}
|
|
1514
2248
|
_shards.clear();
|
|
2249
|
+
_shardLastAccess.clear();
|
|
1515
2250
|
_shardingEnabled = false;
|
|
1516
2251
|
_encryptionKey = null;
|
|
1517
2252
|
}
|
|
1518
|
-
var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
|
|
2253
|
+
var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
|
|
1519
2254
|
var init_shard_manager = __esm({
|
|
1520
2255
|
"src/lib/shard-manager.ts"() {
|
|
1521
2256
|
"use strict";
|
|
1522
2257
|
init_config();
|
|
1523
|
-
SHARDS_DIR =
|
|
2258
|
+
SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
|
|
2259
|
+
SHARD_IDLE_MS = 5 * 60 * 1e3;
|
|
2260
|
+
MAX_OPEN_SHARDS = 10;
|
|
2261
|
+
EVICTION_INTERVAL_MS = 60 * 1e3;
|
|
1524
2262
|
_shards = /* @__PURE__ */ new Map();
|
|
2263
|
+
_shardLastAccess = /* @__PURE__ */ new Map();
|
|
2264
|
+
_evictionTimer = null;
|
|
1525
2265
|
_encryptionKey = null;
|
|
1526
2266
|
_shardingEnabled = false;
|
|
1527
2267
|
}
|
|
@@ -1729,16 +2469,16 @@ init_database();
|
|
|
1729
2469
|
|
|
1730
2470
|
// src/lib/keychain.ts
|
|
1731
2471
|
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
1732
|
-
import { existsSync as
|
|
1733
|
-
import
|
|
1734
|
-
import
|
|
2472
|
+
import { existsSync as existsSync4 } from "fs";
|
|
2473
|
+
import path4 from "path";
|
|
2474
|
+
import os4 from "os";
|
|
1735
2475
|
var SERVICE = "exe-mem";
|
|
1736
2476
|
var ACCOUNT = "master-key";
|
|
1737
2477
|
function getKeyDir() {
|
|
1738
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ??
|
|
2478
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
|
|
1739
2479
|
}
|
|
1740
2480
|
function getKeyPath() {
|
|
1741
|
-
return
|
|
2481
|
+
return path4.join(getKeyDir(), "master.key");
|
|
1742
2482
|
}
|
|
1743
2483
|
async function tryKeytar() {
|
|
1744
2484
|
try {
|
|
@@ -1759,9 +2499,9 @@ async function getMasterKey() {
|
|
|
1759
2499
|
}
|
|
1760
2500
|
}
|
|
1761
2501
|
const keyPath = getKeyPath();
|
|
1762
|
-
if (!
|
|
2502
|
+
if (!existsSync4(keyPath)) {
|
|
1763
2503
|
process.stderr.write(
|
|
1764
|
-
`[keychain] Key not found at ${keyPath} (HOME=${
|
|
2504
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
1765
2505
|
`
|
|
1766
2506
|
);
|
|
1767
2507
|
return null;
|