@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/lib/schedules.js
CHANGED
|
@@ -63,9 +63,34 @@ var init_db_retry = __esm({
|
|
|
63
63
|
}
|
|
64
64
|
});
|
|
65
65
|
|
|
66
|
+
// src/lib/secure-files.ts
|
|
67
|
+
import { chmodSync, existsSync, mkdirSync } from "fs";
|
|
68
|
+
import { chmod, mkdir } from "fs/promises";
|
|
69
|
+
async function ensurePrivateDir(dirPath) {
|
|
70
|
+
await mkdir(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
71
|
+
try {
|
|
72
|
+
await chmod(dirPath, PRIVATE_DIR_MODE);
|
|
73
|
+
} catch {
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function enforcePrivateFile(filePath) {
|
|
77
|
+
try {
|
|
78
|
+
await chmod(filePath, PRIVATE_FILE_MODE);
|
|
79
|
+
} catch {
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
|
|
83
|
+
var init_secure_files = __esm({
|
|
84
|
+
"src/lib/secure-files.ts"() {
|
|
85
|
+
"use strict";
|
|
86
|
+
PRIVATE_DIR_MODE = 448;
|
|
87
|
+
PRIVATE_FILE_MODE = 384;
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
66
91
|
// src/lib/config.ts
|
|
67
|
-
import { readFile, writeFile
|
|
68
|
-
import { readFileSync, existsSync, renameSync } from "fs";
|
|
92
|
+
import { readFile, writeFile } from "fs/promises";
|
|
93
|
+
import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
|
|
69
94
|
import path from "path";
|
|
70
95
|
import os from "os";
|
|
71
96
|
function resolveDataDir() {
|
|
@@ -73,7 +98,7 @@ function resolveDataDir() {
|
|
|
73
98
|
if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
|
|
74
99
|
const newDir = path.join(os.homedir(), ".exe-os");
|
|
75
100
|
const legacyDir = path.join(os.homedir(), ".exe-mem");
|
|
76
|
-
if (!
|
|
101
|
+
if (!existsSync2(newDir) && existsSync2(legacyDir)) {
|
|
77
102
|
try {
|
|
78
103
|
renameSync(legacyDir, newDir);
|
|
79
104
|
process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
|
|
@@ -136,9 +161,9 @@ function normalizeAutoUpdate(raw) {
|
|
|
136
161
|
}
|
|
137
162
|
async function loadConfig() {
|
|
138
163
|
const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
|
|
139
|
-
await
|
|
164
|
+
await ensurePrivateDir(dir);
|
|
140
165
|
const configPath = path.join(dir, "config.json");
|
|
141
|
-
if (!
|
|
166
|
+
if (!existsSync2(configPath)) {
|
|
142
167
|
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
|
|
143
168
|
}
|
|
144
169
|
const raw = await readFile(configPath, "utf-8");
|
|
@@ -151,6 +176,7 @@ async function loadConfig() {
|
|
|
151
176
|
`);
|
|
152
177
|
try {
|
|
153
178
|
await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
|
|
179
|
+
await enforcePrivateFile(configPath);
|
|
154
180
|
} catch {
|
|
155
181
|
}
|
|
156
182
|
}
|
|
@@ -170,6 +196,7 @@ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CON
|
|
|
170
196
|
var init_config = __esm({
|
|
171
197
|
"src/lib/config.ts"() {
|
|
172
198
|
"use strict";
|
|
199
|
+
init_secure_files();
|
|
173
200
|
EXE_AI_DIR = resolveDataDir();
|
|
174
201
|
DB_PATH = path.join(EXE_AI_DIR, "memories.db");
|
|
175
202
|
MODELS_DIR = path.join(EXE_AI_DIR, "models");
|
|
@@ -248,7 +275,7 @@ var init_config = __esm({
|
|
|
248
275
|
|
|
249
276
|
// src/lib/employees.ts
|
|
250
277
|
import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
|
|
251
|
-
import { existsSync as
|
|
278
|
+
import { existsSync as existsSync3, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
|
|
252
279
|
import { execSync } from "child_process";
|
|
253
280
|
import path2 from "path";
|
|
254
281
|
import os2 from "os";
|
|
@@ -265,14 +292,14 @@ function getCoordinatorName(employees = loadEmployeesSync()) {
|
|
|
265
292
|
return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
|
|
266
293
|
}
|
|
267
294
|
function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
268
|
-
if (!
|
|
295
|
+
if (!existsSync3(employeesPath)) return [];
|
|
269
296
|
try {
|
|
270
297
|
return JSON.parse(readFileSync2(employeesPath, "utf-8"));
|
|
271
298
|
} catch {
|
|
272
299
|
return [];
|
|
273
300
|
}
|
|
274
301
|
}
|
|
275
|
-
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
|
|
302
|
+
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
|
|
276
303
|
var init_employees = __esm({
|
|
277
304
|
"src/lib/employees.ts"() {
|
|
278
305
|
"use strict";
|
|
@@ -280,12 +307,609 @@ var init_employees = __esm({
|
|
|
280
307
|
EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
|
|
281
308
|
DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
|
|
282
309
|
COORDINATOR_ROLE = "COO";
|
|
310
|
+
IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// src/lib/database-adapter.ts
|
|
315
|
+
import os3 from "os";
|
|
316
|
+
import path3 from "path";
|
|
317
|
+
import { createRequire } from "module";
|
|
318
|
+
import { pathToFileURL } from "url";
|
|
319
|
+
function quotedIdentifier(identifier) {
|
|
320
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
321
|
+
}
|
|
322
|
+
function unqualifiedTableName(name) {
|
|
323
|
+
const raw = name.trim().replace(/^"|"$/g, "");
|
|
324
|
+
const parts = raw.split(".");
|
|
325
|
+
return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
|
|
326
|
+
}
|
|
327
|
+
function stripTrailingSemicolon(sql) {
|
|
328
|
+
return sql.trim().replace(/;+\s*$/u, "");
|
|
329
|
+
}
|
|
330
|
+
function appendClause(sql, clause) {
|
|
331
|
+
const trimmed = stripTrailingSemicolon(sql);
|
|
332
|
+
const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
|
|
333
|
+
if (!returningMatch) {
|
|
334
|
+
return `${trimmed}${clause}`;
|
|
335
|
+
}
|
|
336
|
+
const idx = returningMatch.index;
|
|
337
|
+
return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
|
|
338
|
+
}
|
|
339
|
+
function normalizeStatement(stmt) {
|
|
340
|
+
if (typeof stmt === "string") {
|
|
341
|
+
return { kind: "positional", sql: stmt, args: [] };
|
|
342
|
+
}
|
|
343
|
+
const sql = stmt.sql;
|
|
344
|
+
if (Array.isArray(stmt.args) || stmt.args === void 0) {
|
|
345
|
+
return { kind: "positional", sql, args: stmt.args ?? [] };
|
|
346
|
+
}
|
|
347
|
+
return { kind: "named", sql, args: stmt.args };
|
|
348
|
+
}
|
|
349
|
+
function rewriteBooleanLiterals(sql) {
|
|
350
|
+
let out = sql;
|
|
351
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
352
|
+
const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
|
|
353
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
|
|
354
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
|
|
355
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
|
|
356
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
|
|
357
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
|
|
358
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
|
|
359
|
+
}
|
|
360
|
+
return out;
|
|
361
|
+
}
|
|
362
|
+
function rewriteInsertOrIgnore(sql) {
|
|
363
|
+
if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
|
|
364
|
+
return sql;
|
|
365
|
+
}
|
|
366
|
+
const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
|
|
367
|
+
return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
|
|
368
|
+
}
|
|
369
|
+
function rewriteInsertOrReplace(sql) {
|
|
370
|
+
const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
|
|
371
|
+
if (!match) {
|
|
372
|
+
return sql;
|
|
373
|
+
}
|
|
374
|
+
const rawTable = match[1];
|
|
375
|
+
const rawColumns = match[2];
|
|
376
|
+
const remainder = match[3];
|
|
377
|
+
const tableName = unqualifiedTableName(rawTable);
|
|
378
|
+
const conflictKeys = UPSERT_KEYS[tableName];
|
|
379
|
+
if (!conflictKeys?.length) {
|
|
380
|
+
return sql;
|
|
381
|
+
}
|
|
382
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
383
|
+
const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
|
|
384
|
+
const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
|
|
385
|
+
const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
|
|
386
|
+
return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
|
|
387
|
+
}
|
|
388
|
+
function rewriteSql(sql) {
|
|
389
|
+
let out = sql;
|
|
390
|
+
out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
|
|
391
|
+
out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
|
|
392
|
+
out = rewriteBooleanLiterals(out);
|
|
393
|
+
out = rewriteInsertOrReplace(out);
|
|
394
|
+
out = rewriteInsertOrIgnore(out);
|
|
395
|
+
return stripTrailingSemicolon(out);
|
|
396
|
+
}
|
|
397
|
+
function toBoolean(value) {
|
|
398
|
+
if (value === null || value === void 0) return value;
|
|
399
|
+
if (typeof value === "boolean") return value;
|
|
400
|
+
if (typeof value === "number") return value !== 0;
|
|
401
|
+
if (typeof value === "bigint") return value !== 0n;
|
|
402
|
+
if (typeof value === "string") {
|
|
403
|
+
const normalized = value.trim().toLowerCase();
|
|
404
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
405
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
406
|
+
}
|
|
407
|
+
return Boolean(value);
|
|
408
|
+
}
|
|
409
|
+
function countQuestionMarks(sql, end) {
|
|
410
|
+
let count = 0;
|
|
411
|
+
let inSingle = false;
|
|
412
|
+
let inDouble = false;
|
|
413
|
+
let inLineComment = false;
|
|
414
|
+
let inBlockComment = false;
|
|
415
|
+
for (let i = 0; i < end; i++) {
|
|
416
|
+
const ch = sql[i];
|
|
417
|
+
const next = sql[i + 1];
|
|
418
|
+
if (inLineComment) {
|
|
419
|
+
if (ch === "\n") inLineComment = false;
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (inBlockComment) {
|
|
423
|
+
if (ch === "*" && next === "/") {
|
|
424
|
+
inBlockComment = false;
|
|
425
|
+
i += 1;
|
|
426
|
+
}
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
430
|
+
inLineComment = true;
|
|
431
|
+
i += 1;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
435
|
+
inBlockComment = true;
|
|
436
|
+
i += 1;
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
440
|
+
inSingle = !inSingle;
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
444
|
+
inDouble = !inDouble;
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
448
|
+
count += 1;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return count;
|
|
452
|
+
}
|
|
453
|
+
function findBooleanPlaceholderIndexes(sql) {
|
|
454
|
+
const indexes = /* @__PURE__ */ new Set();
|
|
455
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
456
|
+
const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
|
|
457
|
+
for (const match of sql.matchAll(pattern)) {
|
|
458
|
+
const matchText = match[0];
|
|
459
|
+
const qIndex = match.index + matchText.lastIndexOf("?");
|
|
460
|
+
indexes.add(countQuestionMarks(sql, qIndex + 1));
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return indexes;
|
|
464
|
+
}
|
|
465
|
+
function coerceInsertBooleanArgs(sql, args) {
|
|
466
|
+
const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
|
|
467
|
+
if (!match) return;
|
|
468
|
+
const rawTable = match[1];
|
|
469
|
+
const rawColumns = match[2];
|
|
470
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
471
|
+
if (!boolColumns?.size) return;
|
|
472
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
473
|
+
for (const [index, column] of columns.entries()) {
|
|
474
|
+
if (boolColumns.has(column) && index < args.length) {
|
|
475
|
+
args[index] = toBoolean(args[index]);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
function coerceUpdateBooleanArgs(sql, args) {
|
|
480
|
+
const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
|
|
481
|
+
if (!match) return;
|
|
482
|
+
const rawTable = match[1];
|
|
483
|
+
const setClause = match[2];
|
|
484
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
485
|
+
if (!boolColumns?.size) return;
|
|
486
|
+
const assignments = setClause.split(",");
|
|
487
|
+
let placeholderIndex = 0;
|
|
488
|
+
for (const assignment of assignments) {
|
|
489
|
+
if (!assignment.includes("?")) continue;
|
|
490
|
+
placeholderIndex += 1;
|
|
491
|
+
const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
|
|
492
|
+
if (colMatch && boolColumns.has(colMatch[1])) {
|
|
493
|
+
args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function coerceBooleanArgs(sql, args) {
|
|
498
|
+
const nextArgs = [...args];
|
|
499
|
+
coerceInsertBooleanArgs(sql, nextArgs);
|
|
500
|
+
coerceUpdateBooleanArgs(sql, nextArgs);
|
|
501
|
+
const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
|
|
502
|
+
for (const index of placeholderIndexes) {
|
|
503
|
+
if (index > 0 && index <= nextArgs.length) {
|
|
504
|
+
nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return nextArgs;
|
|
508
|
+
}
|
|
509
|
+
function convertQuestionMarksToDollarParams(sql) {
|
|
510
|
+
let out = "";
|
|
511
|
+
let placeholder = 0;
|
|
512
|
+
let inSingle = false;
|
|
513
|
+
let inDouble = false;
|
|
514
|
+
let inLineComment = false;
|
|
515
|
+
let inBlockComment = false;
|
|
516
|
+
for (let i = 0; i < sql.length; i++) {
|
|
517
|
+
const ch = sql[i];
|
|
518
|
+
const next = sql[i + 1];
|
|
519
|
+
if (inLineComment) {
|
|
520
|
+
out += ch;
|
|
521
|
+
if (ch === "\n") inLineComment = false;
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
if (inBlockComment) {
|
|
525
|
+
out += ch;
|
|
526
|
+
if (ch === "*" && next === "/") {
|
|
527
|
+
out += next;
|
|
528
|
+
inBlockComment = false;
|
|
529
|
+
i += 1;
|
|
530
|
+
}
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
534
|
+
out += ch + next;
|
|
535
|
+
inLineComment = true;
|
|
536
|
+
i += 1;
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
540
|
+
out += ch + next;
|
|
541
|
+
inBlockComment = true;
|
|
542
|
+
i += 1;
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
546
|
+
inSingle = !inSingle;
|
|
547
|
+
out += ch;
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
551
|
+
inDouble = !inDouble;
|
|
552
|
+
out += ch;
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
556
|
+
placeholder += 1;
|
|
557
|
+
out += `$${placeholder}`;
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
out += ch;
|
|
561
|
+
}
|
|
562
|
+
return out;
|
|
563
|
+
}
|
|
564
|
+
function translateStatementForPostgres(stmt) {
|
|
565
|
+
const normalized = normalizeStatement(stmt);
|
|
566
|
+
if (normalized.kind === "named") {
|
|
567
|
+
throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
|
|
568
|
+
}
|
|
569
|
+
const rewrittenSql = rewriteSql(normalized.sql);
|
|
570
|
+
const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
|
|
571
|
+
return {
|
|
572
|
+
sql: convertQuestionMarksToDollarParams(rewrittenSql),
|
|
573
|
+
args: coercedArgs
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
function shouldBypassPostgres(stmt) {
|
|
577
|
+
const normalized = normalizeStatement(stmt);
|
|
578
|
+
if (normalized.kind === "named") {
|
|
579
|
+
return true;
|
|
580
|
+
}
|
|
581
|
+
return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
|
|
582
|
+
}
|
|
583
|
+
function shouldFallbackOnError(error) {
|
|
584
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
585
|
+
return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
|
|
586
|
+
}
|
|
587
|
+
function isReadQuery(sql) {
|
|
588
|
+
const trimmed = sql.trimStart();
|
|
589
|
+
return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
|
|
590
|
+
}
|
|
591
|
+
function buildRow(row, columns) {
|
|
592
|
+
const values = columns.map((column) => row[column]);
|
|
593
|
+
return Object.assign(values, row);
|
|
594
|
+
}
|
|
595
|
+
function buildResultSet(rows, rowsAffected = 0) {
|
|
596
|
+
const columns = rows[0] ? Object.keys(rows[0]) : [];
|
|
597
|
+
const resultRows = rows.map((row) => buildRow(row, columns));
|
|
598
|
+
return {
|
|
599
|
+
columns,
|
|
600
|
+
columnTypes: columns.map(() => ""),
|
|
601
|
+
rows: resultRows,
|
|
602
|
+
rowsAffected,
|
|
603
|
+
lastInsertRowid: void 0,
|
|
604
|
+
toJSON() {
|
|
605
|
+
return {
|
|
606
|
+
columns,
|
|
607
|
+
columnTypes: columns.map(() => ""),
|
|
608
|
+
rows,
|
|
609
|
+
rowsAffected,
|
|
610
|
+
lastInsertRowid: void 0
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
async function loadPrismaClient() {
|
|
616
|
+
if (!prismaClientPromise) {
|
|
617
|
+
prismaClientPromise = (async () => {
|
|
618
|
+
const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
|
|
619
|
+
if (explicitPath) {
|
|
620
|
+
const module2 = await import(pathToFileURL(explicitPath).href);
|
|
621
|
+
const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
|
|
622
|
+
if (!PrismaClient2) {
|
|
623
|
+
throw new Error(`No PrismaClient export found at ${explicitPath}`);
|
|
624
|
+
}
|
|
625
|
+
return new PrismaClient2();
|
|
626
|
+
}
|
|
627
|
+
const exeDbRoot = process.env.EXE_DB_ROOT ?? path3.join(os3.homedir(), "exe-db");
|
|
628
|
+
const requireFromExeDb = createRequire(path3.join(exeDbRoot, "package.json"));
|
|
629
|
+
const prismaEntry = requireFromExeDb.resolve("@prisma/client");
|
|
630
|
+
const module = await import(pathToFileURL(prismaEntry).href);
|
|
631
|
+
const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
|
|
632
|
+
if (!PrismaClient) {
|
|
633
|
+
throw new Error(`No PrismaClient export found in ${prismaEntry}`);
|
|
634
|
+
}
|
|
635
|
+
return new PrismaClient();
|
|
636
|
+
})();
|
|
637
|
+
}
|
|
638
|
+
return prismaClientPromise;
|
|
639
|
+
}
|
|
640
|
+
async function ensureCompatibilityViews(prisma) {
|
|
641
|
+
if (!compatibilityBootstrapPromise) {
|
|
642
|
+
compatibilityBootstrapPromise = (async () => {
|
|
643
|
+
for (const mapping of VIEW_MAPPINGS) {
|
|
644
|
+
const relation = mapping.source.replace(/"/g, "");
|
|
645
|
+
const rows = await prisma.$queryRawUnsafe(
|
|
646
|
+
"SELECT to_regclass($1) AS regclass",
|
|
647
|
+
relation
|
|
648
|
+
);
|
|
649
|
+
if (!rows[0]?.regclass) {
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
await prisma.$executeRawUnsafe(
|
|
653
|
+
`CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
})();
|
|
657
|
+
}
|
|
658
|
+
return compatibilityBootstrapPromise;
|
|
659
|
+
}
|
|
660
|
+
async function executeOnPrisma(executor, stmt) {
|
|
661
|
+
const translated = translateStatementForPostgres(stmt);
|
|
662
|
+
if (isReadQuery(translated.sql)) {
|
|
663
|
+
const rows = await executor.$queryRawUnsafe(
|
|
664
|
+
translated.sql,
|
|
665
|
+
...translated.args
|
|
666
|
+
);
|
|
667
|
+
return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
|
|
668
|
+
}
|
|
669
|
+
const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
|
|
670
|
+
return buildResultSet([], rowsAffected);
|
|
671
|
+
}
|
|
672
|
+
function splitSqlStatements(sql) {
|
|
673
|
+
const parts = [];
|
|
674
|
+
let current = "";
|
|
675
|
+
let inSingle = false;
|
|
676
|
+
let inDouble = false;
|
|
677
|
+
let inLineComment = false;
|
|
678
|
+
let inBlockComment = false;
|
|
679
|
+
for (let i = 0; i < sql.length; i++) {
|
|
680
|
+
const ch = sql[i];
|
|
681
|
+
const next = sql[i + 1];
|
|
682
|
+
if (inLineComment) {
|
|
683
|
+
current += ch;
|
|
684
|
+
if (ch === "\n") inLineComment = false;
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
if (inBlockComment) {
|
|
688
|
+
current += ch;
|
|
689
|
+
if (ch === "*" && next === "/") {
|
|
690
|
+
current += next;
|
|
691
|
+
inBlockComment = false;
|
|
692
|
+
i += 1;
|
|
693
|
+
}
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
697
|
+
current += ch + next;
|
|
698
|
+
inLineComment = true;
|
|
699
|
+
i += 1;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
703
|
+
current += ch + next;
|
|
704
|
+
inBlockComment = true;
|
|
705
|
+
i += 1;
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
709
|
+
inSingle = !inSingle;
|
|
710
|
+
current += ch;
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
714
|
+
inDouble = !inDouble;
|
|
715
|
+
current += ch;
|
|
716
|
+
continue;
|
|
717
|
+
}
|
|
718
|
+
if (!inSingle && !inDouble && ch === ";") {
|
|
719
|
+
if (current.trim()) {
|
|
720
|
+
parts.push(current.trim());
|
|
721
|
+
}
|
|
722
|
+
current = "";
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
current += ch;
|
|
726
|
+
}
|
|
727
|
+
if (current.trim()) {
|
|
728
|
+
parts.push(current.trim());
|
|
729
|
+
}
|
|
730
|
+
return parts;
|
|
731
|
+
}
|
|
732
|
+
async function createPrismaDbAdapter(fallbackClient) {
|
|
733
|
+
const prisma = await loadPrismaClient();
|
|
734
|
+
await ensureCompatibilityViews(prisma);
|
|
735
|
+
let closed = false;
|
|
736
|
+
let adapter;
|
|
737
|
+
const fallbackExecute = async (stmt, error) => {
|
|
738
|
+
if (!fallbackClient) {
|
|
739
|
+
if (error) throw error;
|
|
740
|
+
throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
|
|
741
|
+
}
|
|
742
|
+
if (error) {
|
|
743
|
+
process.stderr.write(
|
|
744
|
+
`[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
745
|
+
`
|
|
746
|
+
);
|
|
747
|
+
}
|
|
748
|
+
return fallbackClient.execute(stmt);
|
|
749
|
+
};
|
|
750
|
+
adapter = {
|
|
751
|
+
async execute(stmt) {
|
|
752
|
+
if (shouldBypassPostgres(stmt)) {
|
|
753
|
+
return fallbackExecute(stmt);
|
|
754
|
+
}
|
|
755
|
+
try {
|
|
756
|
+
return await executeOnPrisma(prisma, stmt);
|
|
757
|
+
} catch (error) {
|
|
758
|
+
if (shouldFallbackOnError(error)) {
|
|
759
|
+
return fallbackExecute(stmt, error);
|
|
760
|
+
}
|
|
761
|
+
throw error;
|
|
762
|
+
}
|
|
763
|
+
},
|
|
764
|
+
async batch(stmts, mode) {
|
|
765
|
+
if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
|
|
766
|
+
if (!fallbackClient) {
|
|
767
|
+
throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
|
|
768
|
+
}
|
|
769
|
+
return fallbackClient.batch(stmts, mode);
|
|
770
|
+
}
|
|
771
|
+
try {
|
|
772
|
+
if (prisma.$transaction) {
|
|
773
|
+
return await prisma.$transaction(async (tx) => {
|
|
774
|
+
const results2 = [];
|
|
775
|
+
for (const stmt of stmts) {
|
|
776
|
+
results2.push(await executeOnPrisma(tx, stmt));
|
|
777
|
+
}
|
|
778
|
+
return results2;
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
const results = [];
|
|
782
|
+
for (const stmt of stmts) {
|
|
783
|
+
results.push(await executeOnPrisma(prisma, stmt));
|
|
784
|
+
}
|
|
785
|
+
return results;
|
|
786
|
+
} catch (error) {
|
|
787
|
+
if (fallbackClient && shouldFallbackOnError(error)) {
|
|
788
|
+
process.stderr.write(
|
|
789
|
+
`[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
790
|
+
`
|
|
791
|
+
);
|
|
792
|
+
return fallbackClient.batch(stmts, mode);
|
|
793
|
+
}
|
|
794
|
+
throw error;
|
|
795
|
+
}
|
|
796
|
+
},
|
|
797
|
+
async migrate(stmts) {
|
|
798
|
+
if (fallbackClient) {
|
|
799
|
+
return fallbackClient.migrate(stmts);
|
|
800
|
+
}
|
|
801
|
+
return adapter.batch(stmts, "deferred");
|
|
802
|
+
},
|
|
803
|
+
async transaction(mode) {
|
|
804
|
+
if (!fallbackClient) {
|
|
805
|
+
throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
|
|
806
|
+
}
|
|
807
|
+
return fallbackClient.transaction(mode);
|
|
808
|
+
},
|
|
809
|
+
async executeMultiple(sql) {
|
|
810
|
+
if (fallbackClient && shouldBypassPostgres(sql)) {
|
|
811
|
+
return fallbackClient.executeMultiple(sql);
|
|
812
|
+
}
|
|
813
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
814
|
+
await adapter.execute(statement);
|
|
815
|
+
}
|
|
816
|
+
},
|
|
817
|
+
async sync() {
|
|
818
|
+
if (fallbackClient) {
|
|
819
|
+
return fallbackClient.sync();
|
|
820
|
+
}
|
|
821
|
+
return { frame_no: 0, frames_synced: 0 };
|
|
822
|
+
},
|
|
823
|
+
close() {
|
|
824
|
+
closed = true;
|
|
825
|
+
prismaClientPromise = null;
|
|
826
|
+
compatibilityBootstrapPromise = null;
|
|
827
|
+
void prisma.$disconnect?.();
|
|
828
|
+
},
|
|
829
|
+
get closed() {
|
|
830
|
+
return closed;
|
|
831
|
+
},
|
|
832
|
+
get protocol() {
|
|
833
|
+
return "prisma-postgres";
|
|
834
|
+
}
|
|
835
|
+
};
|
|
836
|
+
return adapter;
|
|
837
|
+
}
|
|
838
|
+
var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
|
|
839
|
+
var init_database_adapter = __esm({
|
|
840
|
+
"src/lib/database-adapter.ts"() {
|
|
841
|
+
"use strict";
|
|
842
|
+
VIEW_MAPPINGS = [
|
|
843
|
+
{ view: "memories", source: "memory.memory_records" },
|
|
844
|
+
{ view: "tasks", source: "memory.tasks" },
|
|
845
|
+
{ view: "behaviors", source: "memory.behaviors" },
|
|
846
|
+
{ view: "entities", source: "memory.entities" },
|
|
847
|
+
{ view: "relationships", source: "memory.relationships" },
|
|
848
|
+
{ view: "entity_memories", source: "memory.entity_memories" },
|
|
849
|
+
{ view: "entity_aliases", source: "memory.entity_aliases" },
|
|
850
|
+
{ view: "notifications", source: "memory.notifications" },
|
|
851
|
+
{ view: "messages", source: "memory.messages" },
|
|
852
|
+
{ view: "users", source: "wiki.users" },
|
|
853
|
+
{ view: "workspaces", source: "wiki.workspaces" },
|
|
854
|
+
{ view: "workspace_users", source: "wiki.workspace_users" },
|
|
855
|
+
{ view: "documents", source: "wiki.workspace_documents" },
|
|
856
|
+
{ view: "chats", source: "wiki.workspace_chats" }
|
|
857
|
+
];
|
|
858
|
+
UPSERT_KEYS = {
|
|
859
|
+
memories: ["id"],
|
|
860
|
+
tasks: ["id"],
|
|
861
|
+
behaviors: ["id"],
|
|
862
|
+
entities: ["id"],
|
|
863
|
+
relationships: ["id"],
|
|
864
|
+
entity_aliases: ["alias"],
|
|
865
|
+
notifications: ["id"],
|
|
866
|
+
messages: ["id"],
|
|
867
|
+
users: ["id"],
|
|
868
|
+
workspaces: ["id"],
|
|
869
|
+
workspace_users: ["id"],
|
|
870
|
+
documents: ["id"],
|
|
871
|
+
chats: ["id"]
|
|
872
|
+
};
|
|
873
|
+
BOOLEAN_COLUMNS_BY_TABLE = {
|
|
874
|
+
memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
|
|
875
|
+
behaviors: /* @__PURE__ */ new Set(["active"]),
|
|
876
|
+
notifications: /* @__PURE__ */ new Set(["read"]),
|
|
877
|
+
users: /* @__PURE__ */ new Set(["has_personal_memory"])
|
|
878
|
+
};
|
|
879
|
+
BOOLEAN_COLUMN_NAMES = new Set(
|
|
880
|
+
Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
|
|
881
|
+
);
|
|
882
|
+
IMMEDIATE_FALLBACK_PATTERNS = [
|
|
883
|
+
/\bPRAGMA\b/i,
|
|
884
|
+
/\bsqlite_master\b/i,
|
|
885
|
+
/(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
|
|
886
|
+
/\bMATCH\b/i,
|
|
887
|
+
/\bvector_distance_cos\s*\(/i,
|
|
888
|
+
/\bjson_extract\s*\(/i,
|
|
889
|
+
/\bjulianday\s*\(/i,
|
|
890
|
+
/\bstrftime\s*\(/i,
|
|
891
|
+
/\blast_insert_rowid\s*\(/i
|
|
892
|
+
];
|
|
893
|
+
prismaClientPromise = null;
|
|
894
|
+
compatibilityBootstrapPromise = null;
|
|
283
895
|
}
|
|
284
896
|
});
|
|
285
897
|
|
|
286
898
|
// src/lib/database.ts
|
|
287
899
|
import { createClient } from "@libsql/client";
|
|
288
900
|
async function initDatabase(config) {
|
|
901
|
+
if (_walCheckpointTimer) {
|
|
902
|
+
clearInterval(_walCheckpointTimer);
|
|
903
|
+
_walCheckpointTimer = null;
|
|
904
|
+
}
|
|
905
|
+
if (_daemonClient) {
|
|
906
|
+
_daemonClient.close();
|
|
907
|
+
_daemonClient = null;
|
|
908
|
+
}
|
|
909
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
910
|
+
_adapterClient.close();
|
|
911
|
+
}
|
|
912
|
+
_adapterClient = null;
|
|
289
913
|
if (_client) {
|
|
290
914
|
_client.close();
|
|
291
915
|
_client = null;
|
|
@@ -299,6 +923,7 @@ async function initDatabase(config) {
|
|
|
299
923
|
}
|
|
300
924
|
_client = createClient(opts);
|
|
301
925
|
_resilientClient = wrapWithRetry(_client);
|
|
926
|
+
_adapterClient = _resilientClient;
|
|
302
927
|
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
303
928
|
});
|
|
304
929
|
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
@@ -309,14 +934,20 @@ async function initDatabase(config) {
|
|
|
309
934
|
});
|
|
310
935
|
}, 3e4);
|
|
311
936
|
_walCheckpointTimer.unref();
|
|
937
|
+
if (process.env.DATABASE_URL) {
|
|
938
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
939
|
+
}
|
|
312
940
|
}
|
|
313
941
|
function isInitialized() {
|
|
314
|
-
return _client !== null;
|
|
942
|
+
return _adapterClient !== null || _client !== null;
|
|
315
943
|
}
|
|
316
944
|
function getClient() {
|
|
317
|
-
if (!
|
|
945
|
+
if (!_adapterClient) {
|
|
318
946
|
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
319
947
|
}
|
|
948
|
+
if (process.env.DATABASE_URL) {
|
|
949
|
+
return _adapterClient;
|
|
950
|
+
}
|
|
320
951
|
if (process.env.EXE_IS_DAEMON === "1") {
|
|
321
952
|
return _resilientClient;
|
|
322
953
|
}
|
|
@@ -609,6 +1240,7 @@ async function ensureSchema() {
|
|
|
609
1240
|
project TEXT NOT NULL,
|
|
610
1241
|
summary TEXT NOT NULL,
|
|
611
1242
|
task_file TEXT,
|
|
1243
|
+
session_scope TEXT,
|
|
612
1244
|
read INTEGER NOT NULL DEFAULT 0,
|
|
613
1245
|
created_at TEXT NOT NULL
|
|
614
1246
|
);
|
|
@@ -617,7 +1249,7 @@ async function ensureSchema() {
|
|
|
617
1249
|
ON notifications(read);
|
|
618
1250
|
|
|
619
1251
|
CREATE INDEX IF NOT EXISTS idx_notifications_agent
|
|
620
|
-
ON notifications(agent_id);
|
|
1252
|
+
ON notifications(agent_id, session_scope);
|
|
621
1253
|
|
|
622
1254
|
CREATE INDEX IF NOT EXISTS idx_notifications_task_file
|
|
623
1255
|
ON notifications(task_file);
|
|
@@ -655,6 +1287,7 @@ async function ensureSchema() {
|
|
|
655
1287
|
target_agent TEXT NOT NULL,
|
|
656
1288
|
target_project TEXT,
|
|
657
1289
|
target_device TEXT NOT NULL DEFAULT 'local',
|
|
1290
|
+
session_scope TEXT,
|
|
658
1291
|
content TEXT NOT NULL,
|
|
659
1292
|
priority TEXT DEFAULT 'normal',
|
|
660
1293
|
status TEXT DEFAULT 'pending',
|
|
@@ -668,10 +1301,31 @@ async function ensureSchema() {
|
|
|
668
1301
|
);
|
|
669
1302
|
|
|
670
1303
|
CREATE INDEX IF NOT EXISTS idx_messages_target
|
|
671
|
-
ON messages(target_agent, status);
|
|
1304
|
+
ON messages(target_agent, session_scope, status);
|
|
672
1305
|
|
|
673
1306
|
CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
|
|
674
|
-
ON messages(target_agent, from_agent, server_seq);
|
|
1307
|
+
ON messages(target_agent, session_scope, from_agent, server_seq);
|
|
1308
|
+
`);
|
|
1309
|
+
try {
|
|
1310
|
+
await client.execute({
|
|
1311
|
+
sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
|
|
1312
|
+
args: []
|
|
1313
|
+
});
|
|
1314
|
+
} catch {
|
|
1315
|
+
}
|
|
1316
|
+
try {
|
|
1317
|
+
await client.execute({
|
|
1318
|
+
sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
|
|
1319
|
+
args: []
|
|
1320
|
+
});
|
|
1321
|
+
} catch {
|
|
1322
|
+
}
|
|
1323
|
+
await client.executeMultiple(`
|
|
1324
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
|
|
1325
|
+
ON notifications(agent_id, session_scope, read, created_at);
|
|
1326
|
+
|
|
1327
|
+
CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
|
|
1328
|
+
ON messages(target_agent, session_scope, status, created_at);
|
|
675
1329
|
`);
|
|
676
1330
|
try {
|
|
677
1331
|
await client.execute({
|
|
@@ -1255,17 +1909,26 @@ async function ensureSchema() {
|
|
|
1255
1909
|
} catch {
|
|
1256
1910
|
}
|
|
1257
1911
|
}
|
|
1912
|
+
try {
|
|
1913
|
+
await client.execute({
|
|
1914
|
+
sql: `UPDATE tasks SET status = 'closed' WHERE status = 'done' AND result IS NOT NULL`,
|
|
1915
|
+
args: []
|
|
1916
|
+
});
|
|
1917
|
+
} catch {
|
|
1918
|
+
}
|
|
1258
1919
|
}
|
|
1259
|
-
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
|
|
1920
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
|
|
1260
1921
|
var init_database = __esm({
|
|
1261
1922
|
"src/lib/database.ts"() {
|
|
1262
1923
|
"use strict";
|
|
1263
1924
|
init_db_retry();
|
|
1264
1925
|
init_employees();
|
|
1926
|
+
init_database_adapter();
|
|
1265
1927
|
_client = null;
|
|
1266
1928
|
_resilientClient = null;
|
|
1267
1929
|
_walCheckpointTimer = null;
|
|
1268
1930
|
_daemonClient = null;
|
|
1931
|
+
_adapterClient = null;
|
|
1269
1932
|
initTurso = initDatabase;
|
|
1270
1933
|
}
|
|
1271
1934
|
});
|
|
@@ -1275,6 +1938,7 @@ var shard_manager_exports = {};
|
|
|
1275
1938
|
__export(shard_manager_exports, {
|
|
1276
1939
|
disposeShards: () => disposeShards,
|
|
1277
1940
|
ensureShardSchema: () => ensureShardSchema,
|
|
1941
|
+
getOpenShardCount: () => getOpenShardCount,
|
|
1278
1942
|
getReadyShardClient: () => getReadyShardClient,
|
|
1279
1943
|
getShardClient: () => getShardClient,
|
|
1280
1944
|
getShardsDir: () => getShardsDir,
|
|
@@ -1283,15 +1947,18 @@ __export(shard_manager_exports, {
|
|
|
1283
1947
|
listShards: () => listShards,
|
|
1284
1948
|
shardExists: () => shardExists
|
|
1285
1949
|
});
|
|
1286
|
-
import
|
|
1287
|
-
import { existsSync as
|
|
1950
|
+
import path5 from "path";
|
|
1951
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync } from "fs";
|
|
1288
1952
|
import { createClient as createClient2 } from "@libsql/client";
|
|
1289
1953
|
function initShardManager(encryptionKey) {
|
|
1290
1954
|
_encryptionKey = encryptionKey;
|
|
1291
|
-
if (!
|
|
1292
|
-
|
|
1955
|
+
if (!existsSync5(SHARDS_DIR)) {
|
|
1956
|
+
mkdirSync2(SHARDS_DIR, { recursive: true });
|
|
1293
1957
|
}
|
|
1294
1958
|
_shardingEnabled = true;
|
|
1959
|
+
if (_evictionTimer) clearInterval(_evictionTimer);
|
|
1960
|
+
_evictionTimer = setInterval(evictIdleShards, EVICTION_INTERVAL_MS);
|
|
1961
|
+
_evictionTimer.unref();
|
|
1295
1962
|
}
|
|
1296
1963
|
function isShardingEnabled() {
|
|
1297
1964
|
return _shardingEnabled;
|
|
@@ -1308,21 +1975,28 @@ function getShardClient(projectName) {
|
|
|
1308
1975
|
throw new Error(`Invalid project name for shard: "${projectName}"`);
|
|
1309
1976
|
}
|
|
1310
1977
|
const cached = _shards.get(safeName);
|
|
1311
|
-
if (cached)
|
|
1312
|
-
|
|
1978
|
+
if (cached) {
|
|
1979
|
+
_shardLastAccess.set(safeName, Date.now());
|
|
1980
|
+
return cached;
|
|
1981
|
+
}
|
|
1982
|
+
while (_shards.size >= MAX_OPEN_SHARDS) {
|
|
1983
|
+
evictLRU();
|
|
1984
|
+
}
|
|
1985
|
+
const dbPath = path5.join(SHARDS_DIR, `${safeName}.db`);
|
|
1313
1986
|
const client = createClient2({
|
|
1314
1987
|
url: `file:${dbPath}`,
|
|
1315
1988
|
encryptionKey: _encryptionKey
|
|
1316
1989
|
});
|
|
1317
1990
|
_shards.set(safeName, client);
|
|
1991
|
+
_shardLastAccess.set(safeName, Date.now());
|
|
1318
1992
|
return client;
|
|
1319
1993
|
}
|
|
1320
1994
|
function shardExists(projectName) {
|
|
1321
1995
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1322
|
-
return
|
|
1996
|
+
return existsSync5(path5.join(SHARDS_DIR, `${safeName}.db`));
|
|
1323
1997
|
}
|
|
1324
1998
|
function listShards() {
|
|
1325
|
-
if (!
|
|
1999
|
+
if (!existsSync5(SHARDS_DIR)) return [];
|
|
1326
2000
|
return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
1327
2001
|
}
|
|
1328
2002
|
async function ensureShardSchema(client) {
|
|
@@ -1374,6 +2048,8 @@ async function ensureShardSchema(client) {
|
|
|
1374
2048
|
for (const col of [
|
|
1375
2049
|
"ALTER TABLE memories ADD COLUMN task_id TEXT",
|
|
1376
2050
|
"ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
|
|
2051
|
+
"ALTER TABLE memories ADD COLUMN author_device_id TEXT",
|
|
2052
|
+
"ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'",
|
|
1377
2053
|
"ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
|
|
1378
2054
|
"ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
|
|
1379
2055
|
"ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
|
|
@@ -1396,7 +2072,23 @@ async function ensureShardSchema(client) {
|
|
|
1396
2072
|
// MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
|
|
1397
2073
|
"ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
|
|
1398
2074
|
"ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
|
|
1399
|
-
"ALTER TABLE memories ADD COLUMN trajectory TEXT"
|
|
2075
|
+
"ALTER TABLE memories ADD COLUMN trajectory TEXT",
|
|
2076
|
+
// Metadata enrichment columns (must match database.ts)
|
|
2077
|
+
"ALTER TABLE memories ADD COLUMN intent TEXT",
|
|
2078
|
+
"ALTER TABLE memories ADD COLUMN outcome TEXT",
|
|
2079
|
+
"ALTER TABLE memories ADD COLUMN domain TEXT",
|
|
2080
|
+
"ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
|
|
2081
|
+
"ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
|
|
2082
|
+
"ALTER TABLE memories ADD COLUMN chain_position TEXT",
|
|
2083
|
+
"ALTER TABLE memories ADD COLUMN review_status TEXT",
|
|
2084
|
+
"ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
|
|
2085
|
+
"ALTER TABLE memories ADD COLUMN file_paths TEXT",
|
|
2086
|
+
"ALTER TABLE memories ADD COLUMN commit_hash TEXT",
|
|
2087
|
+
"ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
|
|
2088
|
+
"ALTER TABLE memories ADD COLUMN token_cost REAL",
|
|
2089
|
+
"ALTER TABLE memories ADD COLUMN audience TEXT",
|
|
2090
|
+
"ALTER TABLE memories ADD COLUMN language_type TEXT",
|
|
2091
|
+
"ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
|
|
1400
2092
|
]) {
|
|
1401
2093
|
try {
|
|
1402
2094
|
await client.execute(col);
|
|
@@ -1495,21 +2187,69 @@ async function getReadyShardClient(projectName) {
|
|
|
1495
2187
|
await ensureShardSchema(client);
|
|
1496
2188
|
return client;
|
|
1497
2189
|
}
|
|
2190
|
+
function evictLRU() {
|
|
2191
|
+
let oldest = null;
|
|
2192
|
+
let oldestTime = Infinity;
|
|
2193
|
+
for (const [name, time] of _shardLastAccess) {
|
|
2194
|
+
if (time < oldestTime) {
|
|
2195
|
+
oldestTime = time;
|
|
2196
|
+
oldest = name;
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
if (oldest) {
|
|
2200
|
+
const client = _shards.get(oldest);
|
|
2201
|
+
if (client) {
|
|
2202
|
+
client.close();
|
|
2203
|
+
}
|
|
2204
|
+
_shards.delete(oldest);
|
|
2205
|
+
_shardLastAccess.delete(oldest);
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
function evictIdleShards() {
|
|
2209
|
+
const now = Date.now();
|
|
2210
|
+
const toEvict = [];
|
|
2211
|
+
for (const [name, lastAccess] of _shardLastAccess) {
|
|
2212
|
+
if (now - lastAccess > SHARD_IDLE_MS) {
|
|
2213
|
+
toEvict.push(name);
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
for (const name of toEvict) {
|
|
2217
|
+
const client = _shards.get(name);
|
|
2218
|
+
if (client) {
|
|
2219
|
+
client.close();
|
|
2220
|
+
}
|
|
2221
|
+
_shards.delete(name);
|
|
2222
|
+
_shardLastAccess.delete(name);
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
function getOpenShardCount() {
|
|
2226
|
+
return _shards.size;
|
|
2227
|
+
}
|
|
1498
2228
|
function disposeShards() {
|
|
2229
|
+
if (_evictionTimer) {
|
|
2230
|
+
clearInterval(_evictionTimer);
|
|
2231
|
+
_evictionTimer = null;
|
|
2232
|
+
}
|
|
1499
2233
|
for (const [, client] of _shards) {
|
|
1500
2234
|
client.close();
|
|
1501
2235
|
}
|
|
1502
2236
|
_shards.clear();
|
|
2237
|
+
_shardLastAccess.clear();
|
|
1503
2238
|
_shardingEnabled = false;
|
|
1504
2239
|
_encryptionKey = null;
|
|
1505
2240
|
}
|
|
1506
|
-
var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
|
|
2241
|
+
var SHARDS_DIR, SHARD_IDLE_MS, MAX_OPEN_SHARDS, EVICTION_INTERVAL_MS, _shards, _shardLastAccess, _evictionTimer, _encryptionKey, _shardingEnabled;
|
|
1507
2242
|
var init_shard_manager = __esm({
|
|
1508
2243
|
"src/lib/shard-manager.ts"() {
|
|
1509
2244
|
"use strict";
|
|
1510
2245
|
init_config();
|
|
1511
|
-
SHARDS_DIR =
|
|
2246
|
+
SHARDS_DIR = path5.join(EXE_AI_DIR, "shards");
|
|
2247
|
+
SHARD_IDLE_MS = 5 * 60 * 1e3;
|
|
2248
|
+
MAX_OPEN_SHARDS = 10;
|
|
2249
|
+
EVICTION_INTERVAL_MS = 60 * 1e3;
|
|
1512
2250
|
_shards = /* @__PURE__ */ new Map();
|
|
2251
|
+
_shardLastAccess = /* @__PURE__ */ new Map();
|
|
2252
|
+
_evictionTimer = null;
|
|
1513
2253
|
_encryptionKey = null;
|
|
1514
2254
|
_shardingEnabled = false;
|
|
1515
2255
|
}
|
|
@@ -1713,16 +2453,16 @@ init_database();
|
|
|
1713
2453
|
|
|
1714
2454
|
// src/lib/keychain.ts
|
|
1715
2455
|
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
1716
|
-
import { existsSync as
|
|
1717
|
-
import
|
|
1718
|
-
import
|
|
2456
|
+
import { existsSync as existsSync4 } from "fs";
|
|
2457
|
+
import path4 from "path";
|
|
2458
|
+
import os4 from "os";
|
|
1719
2459
|
var SERVICE = "exe-mem";
|
|
1720
2460
|
var ACCOUNT = "master-key";
|
|
1721
2461
|
function getKeyDir() {
|
|
1722
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ??
|
|
2462
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
|
|
1723
2463
|
}
|
|
1724
2464
|
function getKeyPath() {
|
|
1725
|
-
return
|
|
2465
|
+
return path4.join(getKeyDir(), "master.key");
|
|
1726
2466
|
}
|
|
1727
2467
|
async function tryKeytar() {
|
|
1728
2468
|
try {
|
|
@@ -1743,9 +2483,9 @@ async function getMasterKey() {
|
|
|
1743
2483
|
}
|
|
1744
2484
|
}
|
|
1745
2485
|
const keyPath = getKeyPath();
|
|
1746
|
-
if (!
|
|
2486
|
+
if (!existsSync4(keyPath)) {
|
|
1747
2487
|
process.stderr.write(
|
|
1748
|
-
`[keychain] Key not found at ${keyPath} (HOME=${
|
|
2488
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
1749
2489
|
`
|
|
1750
2490
|
);
|
|
1751
2491
|
return null;
|