@askexenow/exe-os 0.9.6 → 0.9.8
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 +754 -79
- package/dist/bin/backfill-responses.js +752 -77
- package/dist/bin/backfill-vectors.js +752 -77
- package/dist/bin/cleanup-stale-review-tasks.js +668 -37
- package/dist/bin/cli.js +1399 -607
- package/dist/bin/exe-agent-config.js +123 -95
- package/dist/bin/exe-agent.js +41 -25
- package/dist/bin/exe-assign.js +732 -57
- package/dist/bin/exe-boot.js +795 -155
- package/dist/bin/exe-call.js +209 -138
- package/dist/bin/exe-cloud.js +35 -12
- package/dist/bin/exe-dispatch.js +703 -72
- package/dist/bin/exe-doctor.js +648 -26
- package/dist/bin/exe-export-behaviors.js +650 -20
- package/dist/bin/exe-forget.js +635 -13
- package/dist/bin/exe-gateway.js +1064 -273
- package/dist/bin/exe-heartbeat.js +676 -45
- package/dist/bin/exe-kill.js +646 -16
- package/dist/bin/exe-launch-agent.js +887 -97
- package/dist/bin/exe-link.js +658 -43
- package/dist/bin/exe-new-employee.js +378 -177
- package/dist/bin/exe-pending-messages.js +656 -34
- package/dist/bin/exe-pending-notifications.js +635 -13
- package/dist/bin/exe-pending-reviews.js +659 -37
- package/dist/bin/exe-rename.js +645 -30
- package/dist/bin/exe-review.js +635 -13
- package/dist/bin/exe-search.js +771 -88
- package/dist/bin/exe-session-cleanup.js +845 -152
- package/dist/bin/exe-settings.js +127 -91
- package/dist/bin/exe-start-codex.js +729 -94
- package/dist/bin/exe-start-opencode.js +717 -82
- package/dist/bin/exe-status.js +668 -37
- package/dist/bin/exe-team.js +635 -13
- package/dist/bin/git-sweep.js +731 -91
- package/dist/bin/graph-backfill.js +643 -13
- package/dist/bin/graph-export.js +646 -16
- package/dist/bin/install.js +596 -193
- package/dist/bin/scan-tasks.js +735 -95
- package/dist/bin/setup.js +1038 -210
- package/dist/bin/shard-migrate.js +645 -15
- package/dist/bin/wiki-sync.js +646 -16
- package/dist/gateway/index.js +1038 -247
- package/dist/hooks/bug-report-worker.js +902 -172
- package/dist/hooks/commit-complete.js +729 -89
- package/dist/hooks/error-recall.js +776 -93
- package/dist/hooks/exe-heartbeat-hook.js +85 -71
- package/dist/hooks/ingest-worker.js +851 -158
- package/dist/hooks/ingest.js +90 -73
- package/dist/hooks/instructions-loaded.js +669 -38
- package/dist/hooks/notification.js +661 -30
- package/dist/hooks/post-compact.js +685 -45
- package/dist/hooks/pre-compact.js +729 -89
- package/dist/hooks/pre-tool-use.js +883 -127
- package/dist/hooks/prompt-ingest-worker.js +758 -83
- package/dist/hooks/prompt-submit.js +1071 -321
- package/dist/hooks/response-ingest-worker.js +758 -83
- package/dist/hooks/session-end.js +732 -92
- package/dist/hooks/session-start.js +1042 -209
- package/dist/hooks/stop.js +691 -51
- package/dist/hooks/subagent-stop.js +685 -45
- package/dist/hooks/summary-worker.js +827 -134
- package/dist/index.js +1026 -234
- package/dist/lib/cloud-sync.js +663 -48
- package/dist/lib/consolidation.js +26 -3
- package/dist/lib/database.js +626 -18
- package/dist/lib/db.js +2261 -0
- package/dist/lib/device-registry.js +640 -25
- package/dist/lib/embedder.js +96 -43
- package/dist/lib/employee-templates.js +16 -0
- package/dist/lib/employees.js +259 -83
- package/dist/lib/exe-daemon-client.js +101 -63
- package/dist/lib/exe-daemon.js +905 -164
- package/dist/lib/hybrid-search.js +771 -88
- package/dist/lib/identity.js +27 -7
- package/dist/lib/messaging.js +66 -30
- package/dist/lib/reminders.js +21 -1
- package/dist/lib/schedules.js +636 -14
- package/dist/lib/skill-learning.js +21 -1
- package/dist/lib/store.js +643 -13
- package/dist/lib/task-router.js +82 -71
- package/dist/lib/tasks.js +109 -73
- package/dist/lib/tmux-routing.js +98 -62
- package/dist/lib/token-spend.js +26 -6
- package/dist/mcp/server.js +1807 -472
- package/dist/mcp/tools/complete-reminder.js +21 -1
- package/dist/mcp/tools/create-reminder.js +21 -1
- package/dist/mcp/tools/create-task.js +301 -166
- package/dist/mcp/tools/deactivate-behavior.js +24 -4
- package/dist/mcp/tools/list-reminders.js +21 -1
- package/dist/mcp/tools/list-tasks.js +206 -40
- package/dist/mcp/tools/send-message.js +69 -33
- package/dist/mcp/tools/update-task.js +86 -50
- package/dist/runtime/index.js +731 -91
- package/dist/tui/App.js +864 -125
- package/package.json +3 -2
package/dist/bin/exe-assign.js
CHANGED
|
@@ -232,7 +232,7 @@ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
|
|
|
232
232
|
function getEmployee(employees, name) {
|
|
233
233
|
return employees.find((e) => e.name.toLowerCase() === name.toLowerCase());
|
|
234
234
|
}
|
|
235
|
-
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
|
|
235
|
+
var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE, IDENTITY_DIR;
|
|
236
236
|
var init_employees = __esm({
|
|
237
237
|
"src/lib/employees.ts"() {
|
|
238
238
|
"use strict";
|
|
@@ -240,6 +240,7 @@ var init_employees = __esm({
|
|
|
240
240
|
EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
|
|
241
241
|
DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
|
|
242
242
|
COORDINATOR_ROLE = "COO";
|
|
243
|
+
IDENTITY_DIR = path2.join(EXE_AI_DIR, "identity");
|
|
243
244
|
}
|
|
244
245
|
});
|
|
245
246
|
|
|
@@ -490,76 +491,125 @@ async function pingDaemon() {
|
|
|
490
491
|
return null;
|
|
491
492
|
}
|
|
492
493
|
function killAndRespawnDaemon() {
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
494
|
+
if (!acquireSpawnLock()) {
|
|
495
|
+
process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
|
|
496
|
+
if (_socket) {
|
|
497
|
+
_socket.destroy();
|
|
498
|
+
_socket = null;
|
|
499
|
+
}
|
|
500
|
+
_connected = false;
|
|
501
|
+
_buffer = "";
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
try {
|
|
505
|
+
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
506
|
+
if (existsSync3(PID_PATH)) {
|
|
507
|
+
try {
|
|
508
|
+
const pid = parseInt(readFileSync3(PID_PATH, "utf8").trim(), 10);
|
|
509
|
+
if (pid > 0) {
|
|
510
|
+
try {
|
|
511
|
+
process.kill(pid, "SIGKILL");
|
|
512
|
+
} catch {
|
|
513
|
+
}
|
|
501
514
|
}
|
|
515
|
+
} catch {
|
|
502
516
|
}
|
|
517
|
+
}
|
|
518
|
+
if (_socket) {
|
|
519
|
+
_socket.destroy();
|
|
520
|
+
_socket = null;
|
|
521
|
+
}
|
|
522
|
+
_connected = false;
|
|
523
|
+
_buffer = "";
|
|
524
|
+
try {
|
|
525
|
+
unlinkSync2(PID_PATH);
|
|
503
526
|
} catch {
|
|
504
527
|
}
|
|
528
|
+
try {
|
|
529
|
+
unlinkSync2(SOCKET_PATH);
|
|
530
|
+
} catch {
|
|
531
|
+
}
|
|
532
|
+
spawnDaemon();
|
|
533
|
+
} finally {
|
|
534
|
+
releaseSpawnLock();
|
|
505
535
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
_socket = null;
|
|
509
|
-
}
|
|
510
|
-
_connected = false;
|
|
511
|
-
_buffer = "";
|
|
536
|
+
}
|
|
537
|
+
function isDaemonTooYoung() {
|
|
512
538
|
try {
|
|
513
|
-
|
|
539
|
+
const stat = statSync(PID_PATH);
|
|
540
|
+
return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
|
|
514
541
|
} catch {
|
|
542
|
+
return false;
|
|
515
543
|
}
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
544
|
+
}
|
|
545
|
+
async function retryThenRestart(doRequest, label) {
|
|
546
|
+
const result = await doRequest();
|
|
547
|
+
if (!result.error) {
|
|
548
|
+
_consecutiveFailures = 0;
|
|
549
|
+
return result;
|
|
519
550
|
}
|
|
520
|
-
|
|
551
|
+
_consecutiveFailures++;
|
|
552
|
+
for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
|
|
553
|
+
const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
|
|
554
|
+
process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
|
|
555
|
+
`);
|
|
556
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
557
|
+
if (!_connected) {
|
|
558
|
+
if (!await connectToSocket()) continue;
|
|
559
|
+
}
|
|
560
|
+
const retry = await doRequest();
|
|
561
|
+
if (!retry.error) {
|
|
562
|
+
_consecutiveFailures = 0;
|
|
563
|
+
return retry;
|
|
564
|
+
}
|
|
565
|
+
_consecutiveFailures++;
|
|
566
|
+
}
|
|
567
|
+
if (isDaemonTooYoung()) {
|
|
568
|
+
process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
|
|
569
|
+
`);
|
|
570
|
+
return { error: result.error };
|
|
571
|
+
}
|
|
572
|
+
process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
|
|
573
|
+
`);
|
|
574
|
+
killAndRespawnDaemon();
|
|
575
|
+
const start = Date.now();
|
|
576
|
+
let delay2 = 200;
|
|
577
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
578
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
579
|
+
if (await connectToSocket()) break;
|
|
580
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
581
|
+
}
|
|
582
|
+
if (!_connected) return { error: "Daemon restart failed" };
|
|
583
|
+
const final = await doRequest();
|
|
584
|
+
if (!final.error) _consecutiveFailures = 0;
|
|
585
|
+
return final;
|
|
521
586
|
}
|
|
522
587
|
async function embedViaClient(text, priority = "high") {
|
|
523
588
|
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
524
589
|
_requestCount++;
|
|
525
590
|
if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
|
|
526
591
|
const health = await pingDaemon();
|
|
527
|
-
if (!health) {
|
|
592
|
+
if (!health && !isDaemonTooYoung()) {
|
|
528
593
|
process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
|
|
529
594
|
`);
|
|
530
595
|
killAndRespawnDaemon();
|
|
531
596
|
const start = Date.now();
|
|
532
|
-
let
|
|
597
|
+
let d = 200;
|
|
533
598
|
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
534
|
-
await new Promise((r) => setTimeout(r,
|
|
599
|
+
await new Promise((r) => setTimeout(r, d));
|
|
535
600
|
if (await connectToSocket()) break;
|
|
536
|
-
|
|
601
|
+
d = Math.min(d * 2, 3e3);
|
|
537
602
|
}
|
|
538
603
|
if (!_connected) return null;
|
|
539
604
|
}
|
|
540
605
|
}
|
|
541
|
-
const result = await
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
killAndRespawnDaemon();
|
|
547
|
-
const start = Date.now();
|
|
548
|
-
let delay2 = 200;
|
|
549
|
-
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
550
|
-
await new Promise((r) => setTimeout(r, delay2));
|
|
551
|
-
if (await connectToSocket()) break;
|
|
552
|
-
delay2 = Math.min(delay2 * 2, 3e3);
|
|
553
|
-
}
|
|
554
|
-
if (!_connected) return null;
|
|
555
|
-
const retry = await sendRequest([text], priority);
|
|
556
|
-
if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
|
|
557
|
-
process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
|
|
558
|
-
`);
|
|
559
|
-
}
|
|
560
|
-
return null;
|
|
606
|
+
const result = await retryThenRestart(
|
|
607
|
+
() => sendRequest([text], priority),
|
|
608
|
+
"Embed"
|
|
609
|
+
);
|
|
610
|
+
return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
|
|
561
611
|
}
|
|
562
|
-
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending, MAX_BUFFER;
|
|
612
|
+
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
|
|
563
613
|
var init_exe_daemon_client = __esm({
|
|
564
614
|
"src/lib/exe-daemon-client.ts"() {
|
|
565
615
|
"use strict";
|
|
@@ -574,7 +624,11 @@ var init_exe_daemon_client = __esm({
|
|
|
574
624
|
_connected = false;
|
|
575
625
|
_buffer = "";
|
|
576
626
|
_requestCount = 0;
|
|
627
|
+
_consecutiveFailures = 0;
|
|
577
628
|
HEALTH_CHECK_INTERVAL = 100;
|
|
629
|
+
MAX_RETRIES_BEFORE_RESTART = 3;
|
|
630
|
+
RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
|
|
631
|
+
MIN_DAEMON_AGE_MS = 3e4;
|
|
578
632
|
_pending = /* @__PURE__ */ new Map();
|
|
579
633
|
MAX_BUFFER = 1e7;
|
|
580
634
|
}
|
|
@@ -635,9 +689,605 @@ var init_db_retry = __esm({
|
|
|
635
689
|
}
|
|
636
690
|
});
|
|
637
691
|
|
|
692
|
+
// src/lib/database-adapter.ts
|
|
693
|
+
import os4 from "os";
|
|
694
|
+
import path4 from "path";
|
|
695
|
+
import { createRequire } from "module";
|
|
696
|
+
import { pathToFileURL } from "url";
|
|
697
|
+
function quotedIdentifier(identifier) {
|
|
698
|
+
return `"${identifier.replace(/"/g, '""')}"`;
|
|
699
|
+
}
|
|
700
|
+
function unqualifiedTableName(name) {
|
|
701
|
+
const raw = name.trim().replace(/^"|"$/g, "");
|
|
702
|
+
const parts = raw.split(".");
|
|
703
|
+
return parts[parts.length - 1].replace(/^"|"$/g, "").toLowerCase();
|
|
704
|
+
}
|
|
705
|
+
function stripTrailingSemicolon(sql) {
|
|
706
|
+
return sql.trim().replace(/;+\s*$/u, "");
|
|
707
|
+
}
|
|
708
|
+
function appendClause(sql, clause) {
|
|
709
|
+
const trimmed = stripTrailingSemicolon(sql);
|
|
710
|
+
const returningMatch = /\sRETURNING\b[\s\S]*$/iu.exec(trimmed);
|
|
711
|
+
if (!returningMatch) {
|
|
712
|
+
return `${trimmed}${clause}`;
|
|
713
|
+
}
|
|
714
|
+
const idx = returningMatch.index;
|
|
715
|
+
return `${trimmed.slice(0, idx)}${clause}${trimmed.slice(idx)}`;
|
|
716
|
+
}
|
|
717
|
+
function normalizeStatement(stmt) {
|
|
718
|
+
if (typeof stmt === "string") {
|
|
719
|
+
return { kind: "positional", sql: stmt, args: [] };
|
|
720
|
+
}
|
|
721
|
+
const sql = stmt.sql;
|
|
722
|
+
if (Array.isArray(stmt.args) || stmt.args === void 0) {
|
|
723
|
+
return { kind: "positional", sql, args: stmt.args ?? [] };
|
|
724
|
+
}
|
|
725
|
+
return { kind: "named", sql, args: stmt.args };
|
|
726
|
+
}
|
|
727
|
+
function rewriteBooleanLiterals(sql) {
|
|
728
|
+
let out = sql;
|
|
729
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
730
|
+
const scoped = `((?:\\b[a-z_][a-z0-9_]*\\.)?${column})`;
|
|
731
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*0\\b`, "giu"), "$1 = FALSE");
|
|
732
|
+
out = out.replace(new RegExp(`${scoped}\\s*=\\s*1\\b`, "giu"), "$1 = TRUE");
|
|
733
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*0\\b`, "giu"), "$1 != FALSE");
|
|
734
|
+
out = out.replace(new RegExp(`${scoped}\\s*!=\\s*1\\b`, "giu"), "$1 != TRUE");
|
|
735
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*0\\b`, "giu"), "$1 <> FALSE");
|
|
736
|
+
out = out.replace(new RegExp(`${scoped}\\s*<>\\s*1\\b`, "giu"), "$1 <> TRUE");
|
|
737
|
+
}
|
|
738
|
+
return out;
|
|
739
|
+
}
|
|
740
|
+
function rewriteInsertOrIgnore(sql) {
|
|
741
|
+
if (!/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu.test(sql)) {
|
|
742
|
+
return sql;
|
|
743
|
+
}
|
|
744
|
+
const replaced = sql.replace(/^\s*INSERT\s+OR\s+IGNORE\s+INTO\b/iu, "INSERT INTO");
|
|
745
|
+
return /\bON\s+CONFLICT\b/iu.test(replaced) ? replaced : appendClause(replaced, " ON CONFLICT DO NOTHING");
|
|
746
|
+
}
|
|
747
|
+
function rewriteInsertOrReplace(sql) {
|
|
748
|
+
const match = /^\s*INSERT\s+OR\s+REPLACE\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)([\s\S]*)$/iu.exec(sql);
|
|
749
|
+
if (!match) {
|
|
750
|
+
return sql;
|
|
751
|
+
}
|
|
752
|
+
const rawTable = match[1];
|
|
753
|
+
const rawColumns = match[2];
|
|
754
|
+
const remainder = match[3];
|
|
755
|
+
const tableName = unqualifiedTableName(rawTable);
|
|
756
|
+
const conflictKeys = UPSERT_KEYS[tableName];
|
|
757
|
+
if (!conflictKeys?.length) {
|
|
758
|
+
return sql;
|
|
759
|
+
}
|
|
760
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
761
|
+
const updateColumns = columns.filter((col) => !conflictKeys.includes(col));
|
|
762
|
+
const conflictTarget = conflictKeys.map(quotedIdentifier).join(", ");
|
|
763
|
+
const updateClause = updateColumns.length === 0 ? " DO NOTHING" : ` DO UPDATE SET ${updateColumns.map((col) => `${quotedIdentifier(col)} = EXCLUDED.${quotedIdentifier(col)}`).join(", ")}`;
|
|
764
|
+
return `INSERT INTO ${rawTable} (${rawColumns})${appendClause(remainder, ` ON CONFLICT (${conflictTarget})${updateClause}`)}`;
|
|
765
|
+
}
|
|
766
|
+
function rewriteSql(sql) {
|
|
767
|
+
let out = sql;
|
|
768
|
+
out = out.replace(/\bdatetime\(\s*['"]now['"]\s*\)/giu, "CURRENT_TIMESTAMP");
|
|
769
|
+
out = out.replace(/\bvector32\s*\(\s*\?\s*\)/giu, "?");
|
|
770
|
+
out = rewriteBooleanLiterals(out);
|
|
771
|
+
out = rewriteInsertOrReplace(out);
|
|
772
|
+
out = rewriteInsertOrIgnore(out);
|
|
773
|
+
return stripTrailingSemicolon(out);
|
|
774
|
+
}
|
|
775
|
+
function toBoolean(value) {
|
|
776
|
+
if (value === null || value === void 0) return value;
|
|
777
|
+
if (typeof value === "boolean") return value;
|
|
778
|
+
if (typeof value === "number") return value !== 0;
|
|
779
|
+
if (typeof value === "bigint") return value !== 0n;
|
|
780
|
+
if (typeof value === "string") {
|
|
781
|
+
const normalized = value.trim().toLowerCase();
|
|
782
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
783
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
784
|
+
}
|
|
785
|
+
return Boolean(value);
|
|
786
|
+
}
|
|
787
|
+
function countQuestionMarks(sql, end) {
|
|
788
|
+
let count = 0;
|
|
789
|
+
let inSingle = false;
|
|
790
|
+
let inDouble = false;
|
|
791
|
+
let inLineComment = false;
|
|
792
|
+
let inBlockComment = false;
|
|
793
|
+
for (let i = 0; i < end; i++) {
|
|
794
|
+
const ch = sql[i];
|
|
795
|
+
const next = sql[i + 1];
|
|
796
|
+
if (inLineComment) {
|
|
797
|
+
if (ch === "\n") inLineComment = false;
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
if (inBlockComment) {
|
|
801
|
+
if (ch === "*" && next === "/") {
|
|
802
|
+
inBlockComment = false;
|
|
803
|
+
i += 1;
|
|
804
|
+
}
|
|
805
|
+
continue;
|
|
806
|
+
}
|
|
807
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
808
|
+
inLineComment = true;
|
|
809
|
+
i += 1;
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
813
|
+
inBlockComment = true;
|
|
814
|
+
i += 1;
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
818
|
+
inSingle = !inSingle;
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
822
|
+
inDouble = !inDouble;
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
826
|
+
count += 1;
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
return count;
|
|
830
|
+
}
|
|
831
|
+
function findBooleanPlaceholderIndexes(sql) {
|
|
832
|
+
const indexes = /* @__PURE__ */ new Set();
|
|
833
|
+
for (const column of BOOLEAN_COLUMN_NAMES) {
|
|
834
|
+
const pattern = new RegExp(`(?:\\b[a-z_][a-z0-9_]*\\.)?${column}\\s*=\\s*\\?`, "giu");
|
|
835
|
+
for (const match of sql.matchAll(pattern)) {
|
|
836
|
+
const matchText = match[0];
|
|
837
|
+
const qIndex = match.index + matchText.lastIndexOf("?");
|
|
838
|
+
indexes.add(countQuestionMarks(sql, qIndex + 1));
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
return indexes;
|
|
842
|
+
}
|
|
843
|
+
function coerceInsertBooleanArgs(sql, args) {
|
|
844
|
+
const match = /^\s*INSERT(?:\s+OR\s+(?:IGNORE|REPLACE))?\s+INTO\s+([A-Za-z0-9_."]+)\s*\(([^)]+)\)/iu.exec(sql);
|
|
845
|
+
if (!match) return;
|
|
846
|
+
const rawTable = match[1];
|
|
847
|
+
const rawColumns = match[2];
|
|
848
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
849
|
+
if (!boolColumns?.size) return;
|
|
850
|
+
const columns = rawColumns.split(",").map((col) => col.trim().replace(/^"|"$/g, ""));
|
|
851
|
+
for (const [index, column] of columns.entries()) {
|
|
852
|
+
if (boolColumns.has(column) && index < args.length) {
|
|
853
|
+
args[index] = toBoolean(args[index]);
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
function coerceUpdateBooleanArgs(sql, args) {
|
|
858
|
+
const match = /^\s*UPDATE\s+([A-Za-z0-9_."]+)\s+SET\s+([\s\S]+?)(?:\s+WHERE\b|$)/iu.exec(sql);
|
|
859
|
+
if (!match) return;
|
|
860
|
+
const rawTable = match[1];
|
|
861
|
+
const setClause = match[2];
|
|
862
|
+
const boolColumns = BOOLEAN_COLUMNS_BY_TABLE[unqualifiedTableName(rawTable)];
|
|
863
|
+
if (!boolColumns?.size) return;
|
|
864
|
+
const assignments = setClause.split(",");
|
|
865
|
+
let placeholderIndex = 0;
|
|
866
|
+
for (const assignment of assignments) {
|
|
867
|
+
if (!assignment.includes("?")) continue;
|
|
868
|
+
placeholderIndex += 1;
|
|
869
|
+
const colMatch = /^\s*(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*\?/iu.exec(assignment);
|
|
870
|
+
if (colMatch && boolColumns.has(colMatch[1])) {
|
|
871
|
+
args[placeholderIndex - 1] = toBoolean(args[placeholderIndex - 1]);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
function coerceBooleanArgs(sql, args) {
|
|
876
|
+
const nextArgs = [...args];
|
|
877
|
+
coerceInsertBooleanArgs(sql, nextArgs);
|
|
878
|
+
coerceUpdateBooleanArgs(sql, nextArgs);
|
|
879
|
+
const placeholderIndexes = findBooleanPlaceholderIndexes(sql);
|
|
880
|
+
for (const index of placeholderIndexes) {
|
|
881
|
+
if (index > 0 && index <= nextArgs.length) {
|
|
882
|
+
nextArgs[index - 1] = toBoolean(nextArgs[index - 1]);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
return nextArgs;
|
|
886
|
+
}
|
|
887
|
+
function convertQuestionMarksToDollarParams(sql) {
|
|
888
|
+
let out = "";
|
|
889
|
+
let placeholder = 0;
|
|
890
|
+
let inSingle = false;
|
|
891
|
+
let inDouble = false;
|
|
892
|
+
let inLineComment = false;
|
|
893
|
+
let inBlockComment = false;
|
|
894
|
+
for (let i = 0; i < sql.length; i++) {
|
|
895
|
+
const ch = sql[i];
|
|
896
|
+
const next = sql[i + 1];
|
|
897
|
+
if (inLineComment) {
|
|
898
|
+
out += ch;
|
|
899
|
+
if (ch === "\n") inLineComment = false;
|
|
900
|
+
continue;
|
|
901
|
+
}
|
|
902
|
+
if (inBlockComment) {
|
|
903
|
+
out += ch;
|
|
904
|
+
if (ch === "*" && next === "/") {
|
|
905
|
+
out += next;
|
|
906
|
+
inBlockComment = false;
|
|
907
|
+
i += 1;
|
|
908
|
+
}
|
|
909
|
+
continue;
|
|
910
|
+
}
|
|
911
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
912
|
+
out += ch + next;
|
|
913
|
+
inLineComment = true;
|
|
914
|
+
i += 1;
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
918
|
+
out += ch + next;
|
|
919
|
+
inBlockComment = true;
|
|
920
|
+
i += 1;
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
924
|
+
inSingle = !inSingle;
|
|
925
|
+
out += ch;
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
929
|
+
inDouble = !inDouble;
|
|
930
|
+
out += ch;
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
if (!inSingle && !inDouble && ch === "?") {
|
|
934
|
+
placeholder += 1;
|
|
935
|
+
out += `$${placeholder}`;
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
out += ch;
|
|
939
|
+
}
|
|
940
|
+
return out;
|
|
941
|
+
}
|
|
942
|
+
function translateStatementForPostgres(stmt) {
|
|
943
|
+
const normalized = normalizeStatement(stmt);
|
|
944
|
+
if (normalized.kind === "named") {
|
|
945
|
+
throw new Error("Named SQL parameters are not supported by the Prisma adapter.");
|
|
946
|
+
}
|
|
947
|
+
const rewrittenSql = rewriteSql(normalized.sql);
|
|
948
|
+
const coercedArgs = coerceBooleanArgs(rewrittenSql, normalized.args);
|
|
949
|
+
return {
|
|
950
|
+
sql: convertQuestionMarksToDollarParams(rewrittenSql),
|
|
951
|
+
args: coercedArgs
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
function shouldBypassPostgres(stmt) {
|
|
955
|
+
const normalized = normalizeStatement(stmt);
|
|
956
|
+
if (normalized.kind === "named") {
|
|
957
|
+
return true;
|
|
958
|
+
}
|
|
959
|
+
return IMMEDIATE_FALLBACK_PATTERNS.some((pattern) => pattern.test(normalized.sql));
|
|
960
|
+
}
|
|
961
|
+
function shouldFallbackOnError(error) {
|
|
962
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
963
|
+
return /42P01|42883|42601|does not exist|syntax error|not supported|Named SQL parameters are not supported/iu.test(message);
|
|
964
|
+
}
|
|
965
|
+
function isReadQuery(sql) {
|
|
966
|
+
const trimmed = sql.trimStart();
|
|
967
|
+
return /^(SELECT|WITH|SHOW|EXPLAIN|VALUES)\b/iu.test(trimmed) || /\bRETURNING\b/iu.test(trimmed);
|
|
968
|
+
}
|
|
969
|
+
function buildRow(row, columns) {
|
|
970
|
+
const values = columns.map((column) => row[column]);
|
|
971
|
+
return Object.assign(values, row);
|
|
972
|
+
}
|
|
973
|
+
function buildResultSet(rows, rowsAffected = 0) {
|
|
974
|
+
const columns = rows[0] ? Object.keys(rows[0]) : [];
|
|
975
|
+
const resultRows = rows.map((row) => buildRow(row, columns));
|
|
976
|
+
return {
|
|
977
|
+
columns,
|
|
978
|
+
columnTypes: columns.map(() => ""),
|
|
979
|
+
rows: resultRows,
|
|
980
|
+
rowsAffected,
|
|
981
|
+
lastInsertRowid: void 0,
|
|
982
|
+
toJSON() {
|
|
983
|
+
return {
|
|
984
|
+
columns,
|
|
985
|
+
columnTypes: columns.map(() => ""),
|
|
986
|
+
rows,
|
|
987
|
+
rowsAffected,
|
|
988
|
+
lastInsertRowid: void 0
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
async function loadPrismaClient() {
|
|
994
|
+
if (!prismaClientPromise) {
|
|
995
|
+
prismaClientPromise = (async () => {
|
|
996
|
+
const explicitPath = process.env.EXE_OS_PRISMA_CLIENT_PATH;
|
|
997
|
+
if (explicitPath) {
|
|
998
|
+
const module2 = await import(pathToFileURL(explicitPath).href);
|
|
999
|
+
const PrismaClient2 = module2.PrismaClient ?? module2.default?.PrismaClient;
|
|
1000
|
+
if (!PrismaClient2) {
|
|
1001
|
+
throw new Error(`No PrismaClient export found at ${explicitPath}`);
|
|
1002
|
+
}
|
|
1003
|
+
return new PrismaClient2();
|
|
1004
|
+
}
|
|
1005
|
+
const exeDbRoot = process.env.EXE_DB_ROOT ?? path4.join(os4.homedir(), "exe-db");
|
|
1006
|
+
const requireFromExeDb = createRequire(path4.join(exeDbRoot, "package.json"));
|
|
1007
|
+
const prismaEntry = requireFromExeDb.resolve("@prisma/client");
|
|
1008
|
+
const module = await import(pathToFileURL(prismaEntry).href);
|
|
1009
|
+
const PrismaClient = module.PrismaClient ?? module.default?.PrismaClient;
|
|
1010
|
+
if (!PrismaClient) {
|
|
1011
|
+
throw new Error(`No PrismaClient export found in ${prismaEntry}`);
|
|
1012
|
+
}
|
|
1013
|
+
return new PrismaClient();
|
|
1014
|
+
})();
|
|
1015
|
+
}
|
|
1016
|
+
return prismaClientPromise;
|
|
1017
|
+
}
|
|
1018
|
+
async function ensureCompatibilityViews(prisma) {
|
|
1019
|
+
if (!compatibilityBootstrapPromise) {
|
|
1020
|
+
compatibilityBootstrapPromise = (async () => {
|
|
1021
|
+
for (const mapping of VIEW_MAPPINGS) {
|
|
1022
|
+
const relation = mapping.source.replace(/"/g, "");
|
|
1023
|
+
const rows = await prisma.$queryRawUnsafe(
|
|
1024
|
+
"SELECT to_regclass($1) AS regclass",
|
|
1025
|
+
relation
|
|
1026
|
+
);
|
|
1027
|
+
if (!rows[0]?.regclass) {
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
await prisma.$executeRawUnsafe(
|
|
1031
|
+
`CREATE OR REPLACE VIEW public.${quotedIdentifier(mapping.view)} AS SELECT * FROM ${mapping.source}`
|
|
1032
|
+
);
|
|
1033
|
+
}
|
|
1034
|
+
})();
|
|
1035
|
+
}
|
|
1036
|
+
return compatibilityBootstrapPromise;
|
|
1037
|
+
}
|
|
1038
|
+
async function executeOnPrisma(executor, stmt) {
|
|
1039
|
+
const translated = translateStatementForPostgres(stmt);
|
|
1040
|
+
if (isReadQuery(translated.sql)) {
|
|
1041
|
+
const rows = await executor.$queryRawUnsafe(
|
|
1042
|
+
translated.sql,
|
|
1043
|
+
...translated.args
|
|
1044
|
+
);
|
|
1045
|
+
return buildResultSet(rows, /\bRETURNING\b/iu.test(translated.sql) ? rows.length : 0);
|
|
1046
|
+
}
|
|
1047
|
+
const rowsAffected = await executor.$executeRawUnsafe(translated.sql, ...translated.args);
|
|
1048
|
+
return buildResultSet([], rowsAffected);
|
|
1049
|
+
}
|
|
1050
|
+
function splitSqlStatements(sql) {
|
|
1051
|
+
const parts = [];
|
|
1052
|
+
let current = "";
|
|
1053
|
+
let inSingle = false;
|
|
1054
|
+
let inDouble = false;
|
|
1055
|
+
let inLineComment = false;
|
|
1056
|
+
let inBlockComment = false;
|
|
1057
|
+
for (let i = 0; i < sql.length; i++) {
|
|
1058
|
+
const ch = sql[i];
|
|
1059
|
+
const next = sql[i + 1];
|
|
1060
|
+
if (inLineComment) {
|
|
1061
|
+
current += ch;
|
|
1062
|
+
if (ch === "\n") inLineComment = false;
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
if (inBlockComment) {
|
|
1066
|
+
current += ch;
|
|
1067
|
+
if (ch === "*" && next === "/") {
|
|
1068
|
+
current += next;
|
|
1069
|
+
inBlockComment = false;
|
|
1070
|
+
i += 1;
|
|
1071
|
+
}
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
if (!inSingle && !inDouble && ch === "-" && next === "-") {
|
|
1075
|
+
current += ch + next;
|
|
1076
|
+
inLineComment = true;
|
|
1077
|
+
i += 1;
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
if (!inSingle && !inDouble && ch === "/" && next === "*") {
|
|
1081
|
+
current += ch + next;
|
|
1082
|
+
inBlockComment = true;
|
|
1083
|
+
i += 1;
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
if (!inDouble && ch === "'" && sql[i - 1] !== "\\") {
|
|
1087
|
+
inSingle = !inSingle;
|
|
1088
|
+
current += ch;
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
if (!inSingle && ch === '"' && sql[i - 1] !== "\\") {
|
|
1092
|
+
inDouble = !inDouble;
|
|
1093
|
+
current += ch;
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
if (!inSingle && !inDouble && ch === ";") {
|
|
1097
|
+
if (current.trim()) {
|
|
1098
|
+
parts.push(current.trim());
|
|
1099
|
+
}
|
|
1100
|
+
current = "";
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
current += ch;
|
|
1104
|
+
}
|
|
1105
|
+
if (current.trim()) {
|
|
1106
|
+
parts.push(current.trim());
|
|
1107
|
+
}
|
|
1108
|
+
return parts;
|
|
1109
|
+
}
|
|
1110
|
+
async function createPrismaDbAdapter(fallbackClient) {
|
|
1111
|
+
const prisma = await loadPrismaClient();
|
|
1112
|
+
await ensureCompatibilityViews(prisma);
|
|
1113
|
+
let closed = false;
|
|
1114
|
+
let adapter;
|
|
1115
|
+
const fallbackExecute = async (stmt, error) => {
|
|
1116
|
+
if (!fallbackClient) {
|
|
1117
|
+
if (error) throw error;
|
|
1118
|
+
throw new Error("No fallback SQLite client is available for this Prisma-routed query.");
|
|
1119
|
+
}
|
|
1120
|
+
if (error) {
|
|
1121
|
+
process.stderr.write(
|
|
1122
|
+
`[database-adapter] Falling back to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
1123
|
+
`
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
return fallbackClient.execute(stmt);
|
|
1127
|
+
};
|
|
1128
|
+
adapter = {
|
|
1129
|
+
async execute(stmt) {
|
|
1130
|
+
if (shouldBypassPostgres(stmt)) {
|
|
1131
|
+
return fallbackExecute(stmt);
|
|
1132
|
+
}
|
|
1133
|
+
try {
|
|
1134
|
+
return await executeOnPrisma(prisma, stmt);
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
if (shouldFallbackOnError(error)) {
|
|
1137
|
+
return fallbackExecute(stmt, error);
|
|
1138
|
+
}
|
|
1139
|
+
throw error;
|
|
1140
|
+
}
|
|
1141
|
+
},
|
|
1142
|
+
async batch(stmts, mode) {
|
|
1143
|
+
if (stmts.some((stmt) => shouldBypassPostgres(stmt))) {
|
|
1144
|
+
if (!fallbackClient) {
|
|
1145
|
+
throw new Error("Cannot batch unsupported SQLite-only statements without a fallback client.");
|
|
1146
|
+
}
|
|
1147
|
+
return fallbackClient.batch(stmts, mode);
|
|
1148
|
+
}
|
|
1149
|
+
try {
|
|
1150
|
+
if (prisma.$transaction) {
|
|
1151
|
+
return await prisma.$transaction(async (tx) => {
|
|
1152
|
+
const results2 = [];
|
|
1153
|
+
for (const stmt of stmts) {
|
|
1154
|
+
results2.push(await executeOnPrisma(tx, stmt));
|
|
1155
|
+
}
|
|
1156
|
+
return results2;
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
const results = [];
|
|
1160
|
+
for (const stmt of stmts) {
|
|
1161
|
+
results.push(await executeOnPrisma(prisma, stmt));
|
|
1162
|
+
}
|
|
1163
|
+
return results;
|
|
1164
|
+
} catch (error) {
|
|
1165
|
+
if (fallbackClient && shouldFallbackOnError(error)) {
|
|
1166
|
+
process.stderr.write(
|
|
1167
|
+
`[database-adapter] Falling back batch to SQLite: ${error instanceof Error ? error.message : String(error)}
|
|
1168
|
+
`
|
|
1169
|
+
);
|
|
1170
|
+
return fallbackClient.batch(stmts, mode);
|
|
1171
|
+
}
|
|
1172
|
+
throw error;
|
|
1173
|
+
}
|
|
1174
|
+
},
|
|
1175
|
+
async migrate(stmts) {
|
|
1176
|
+
if (fallbackClient) {
|
|
1177
|
+
return fallbackClient.migrate(stmts);
|
|
1178
|
+
}
|
|
1179
|
+
return adapter.batch(stmts, "deferred");
|
|
1180
|
+
},
|
|
1181
|
+
async transaction(mode) {
|
|
1182
|
+
if (!fallbackClient) {
|
|
1183
|
+
throw new Error("Interactive transactions are only supported on the SQLite fallback client.");
|
|
1184
|
+
}
|
|
1185
|
+
return fallbackClient.transaction(mode);
|
|
1186
|
+
},
|
|
1187
|
+
async executeMultiple(sql) {
|
|
1188
|
+
if (fallbackClient && shouldBypassPostgres(sql)) {
|
|
1189
|
+
return fallbackClient.executeMultiple(sql);
|
|
1190
|
+
}
|
|
1191
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
1192
|
+
await adapter.execute(statement);
|
|
1193
|
+
}
|
|
1194
|
+
},
|
|
1195
|
+
async sync() {
|
|
1196
|
+
if (fallbackClient) {
|
|
1197
|
+
return fallbackClient.sync();
|
|
1198
|
+
}
|
|
1199
|
+
return { frame_no: 0, frames_synced: 0 };
|
|
1200
|
+
},
|
|
1201
|
+
close() {
|
|
1202
|
+
closed = true;
|
|
1203
|
+
prismaClientPromise = null;
|
|
1204
|
+
compatibilityBootstrapPromise = null;
|
|
1205
|
+
void prisma.$disconnect?.();
|
|
1206
|
+
},
|
|
1207
|
+
get closed() {
|
|
1208
|
+
return closed;
|
|
1209
|
+
},
|
|
1210
|
+
get protocol() {
|
|
1211
|
+
return "prisma-postgres";
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
return adapter;
|
|
1215
|
+
}
|
|
1216
|
+
var VIEW_MAPPINGS, UPSERT_KEYS, BOOLEAN_COLUMNS_BY_TABLE, BOOLEAN_COLUMN_NAMES, IMMEDIATE_FALLBACK_PATTERNS, prismaClientPromise, compatibilityBootstrapPromise;
|
|
1217
|
+
var init_database_adapter = __esm({
|
|
1218
|
+
"src/lib/database-adapter.ts"() {
|
|
1219
|
+
"use strict";
|
|
1220
|
+
VIEW_MAPPINGS = [
|
|
1221
|
+
{ view: "memories", source: "memory.memory_records" },
|
|
1222
|
+
{ view: "tasks", source: "memory.tasks" },
|
|
1223
|
+
{ view: "behaviors", source: "memory.behaviors" },
|
|
1224
|
+
{ view: "entities", source: "memory.entities" },
|
|
1225
|
+
{ view: "relationships", source: "memory.relationships" },
|
|
1226
|
+
{ view: "entity_memories", source: "memory.entity_memories" },
|
|
1227
|
+
{ view: "entity_aliases", source: "memory.entity_aliases" },
|
|
1228
|
+
{ view: "notifications", source: "memory.notifications" },
|
|
1229
|
+
{ view: "messages", source: "memory.messages" },
|
|
1230
|
+
{ view: "users", source: "wiki.users" },
|
|
1231
|
+
{ view: "workspaces", source: "wiki.workspaces" },
|
|
1232
|
+
{ view: "workspace_users", source: "wiki.workspace_users" },
|
|
1233
|
+
{ view: "documents", source: "wiki.workspace_documents" },
|
|
1234
|
+
{ view: "chats", source: "wiki.workspace_chats" }
|
|
1235
|
+
];
|
|
1236
|
+
UPSERT_KEYS = {
|
|
1237
|
+
memories: ["id"],
|
|
1238
|
+
tasks: ["id"],
|
|
1239
|
+
behaviors: ["id"],
|
|
1240
|
+
entities: ["id"],
|
|
1241
|
+
relationships: ["id"],
|
|
1242
|
+
entity_aliases: ["alias"],
|
|
1243
|
+
notifications: ["id"],
|
|
1244
|
+
messages: ["id"],
|
|
1245
|
+
users: ["id"],
|
|
1246
|
+
workspaces: ["id"],
|
|
1247
|
+
workspace_users: ["id"],
|
|
1248
|
+
documents: ["id"],
|
|
1249
|
+
chats: ["id"]
|
|
1250
|
+
};
|
|
1251
|
+
BOOLEAN_COLUMNS_BY_TABLE = {
|
|
1252
|
+
memories: /* @__PURE__ */ new Set(["has_error", "draft"]),
|
|
1253
|
+
behaviors: /* @__PURE__ */ new Set(["active"]),
|
|
1254
|
+
notifications: /* @__PURE__ */ new Set(["read"]),
|
|
1255
|
+
users: /* @__PURE__ */ new Set(["has_personal_memory"])
|
|
1256
|
+
};
|
|
1257
|
+
BOOLEAN_COLUMN_NAMES = new Set(
|
|
1258
|
+
Object.values(BOOLEAN_COLUMNS_BY_TABLE).flatMap((cols) => [...cols])
|
|
1259
|
+
);
|
|
1260
|
+
IMMEDIATE_FALLBACK_PATTERNS = [
|
|
1261
|
+
/\bPRAGMA\b/i,
|
|
1262
|
+
/\bsqlite_master\b/i,
|
|
1263
|
+
/(?:^|[.\s])(?:memories|conversations|entities)_fts\b/i,
|
|
1264
|
+
/\bMATCH\b/i,
|
|
1265
|
+
/\bvector_distance_cos\s*\(/i,
|
|
1266
|
+
/\bjson_extract\s*\(/i,
|
|
1267
|
+
/\bjulianday\s*\(/i,
|
|
1268
|
+
/\bstrftime\s*\(/i,
|
|
1269
|
+
/\blast_insert_rowid\s*\(/i
|
|
1270
|
+
];
|
|
1271
|
+
prismaClientPromise = null;
|
|
1272
|
+
compatibilityBootstrapPromise = null;
|
|
1273
|
+
}
|
|
1274
|
+
});
|
|
1275
|
+
|
|
638
1276
|
// src/lib/database.ts
|
|
639
1277
|
import { createClient } from "@libsql/client";
|
|
640
1278
|
async function initDatabase(config) {
|
|
1279
|
+
if (_walCheckpointTimer) {
|
|
1280
|
+
clearInterval(_walCheckpointTimer);
|
|
1281
|
+
_walCheckpointTimer = null;
|
|
1282
|
+
}
|
|
1283
|
+
if (_daemonClient) {
|
|
1284
|
+
_daemonClient.close();
|
|
1285
|
+
_daemonClient = null;
|
|
1286
|
+
}
|
|
1287
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
1288
|
+
_adapterClient.close();
|
|
1289
|
+
}
|
|
1290
|
+
_adapterClient = null;
|
|
641
1291
|
if (_client) {
|
|
642
1292
|
_client.close();
|
|
643
1293
|
_client = null;
|
|
@@ -651,6 +1301,7 @@ async function initDatabase(config) {
|
|
|
651
1301
|
}
|
|
652
1302
|
_client = createClient(opts);
|
|
653
1303
|
_resilientClient = wrapWithRetry(_client);
|
|
1304
|
+
_adapterClient = _resilientClient;
|
|
654
1305
|
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
655
1306
|
});
|
|
656
1307
|
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
@@ -661,11 +1312,17 @@ async function initDatabase(config) {
|
|
|
661
1312
|
});
|
|
662
1313
|
}, 3e4);
|
|
663
1314
|
_walCheckpointTimer.unref();
|
|
1315
|
+
if (process.env.DATABASE_URL) {
|
|
1316
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1317
|
+
}
|
|
664
1318
|
}
|
|
665
1319
|
function getClient() {
|
|
666
|
-
if (!
|
|
1320
|
+
if (!_adapterClient) {
|
|
667
1321
|
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
668
1322
|
}
|
|
1323
|
+
if (process.env.DATABASE_URL) {
|
|
1324
|
+
return _adapterClient;
|
|
1325
|
+
}
|
|
669
1326
|
if (process.env.EXE_IS_DAEMON === "1") {
|
|
670
1327
|
return _resilientClient;
|
|
671
1328
|
}
|
|
@@ -1605,16 +2262,18 @@ async function ensureSchema() {
|
|
|
1605
2262
|
}
|
|
1606
2263
|
}
|
|
1607
2264
|
}
|
|
1608
|
-
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, initTurso;
|
|
2265
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso;
|
|
1609
2266
|
var init_database = __esm({
|
|
1610
2267
|
"src/lib/database.ts"() {
|
|
1611
2268
|
"use strict";
|
|
1612
2269
|
init_db_retry();
|
|
1613
2270
|
init_employees();
|
|
2271
|
+
init_database_adapter();
|
|
1614
2272
|
_client = null;
|
|
1615
2273
|
_resilientClient = null;
|
|
1616
2274
|
_walCheckpointTimer = null;
|
|
1617
2275
|
_daemonClient = null;
|
|
2276
|
+
_adapterClient = null;
|
|
1618
2277
|
initTurso = initDatabase;
|
|
1619
2278
|
}
|
|
1620
2279
|
});
|
|
@@ -1632,7 +2291,7 @@ __export(shard_manager_exports, {
|
|
|
1632
2291
|
listShards: () => listShards,
|
|
1633
2292
|
shardExists: () => shardExists
|
|
1634
2293
|
});
|
|
1635
|
-
import
|
|
2294
|
+
import path6 from "path";
|
|
1636
2295
|
import { existsSync as existsSync5, mkdirSync, readdirSync } from "fs";
|
|
1637
2296
|
import { createClient as createClient2 } from "@libsql/client";
|
|
1638
2297
|
function initShardManager(encryptionKey) {
|
|
@@ -1658,7 +2317,7 @@ function getShardClient(projectName) {
|
|
|
1658
2317
|
}
|
|
1659
2318
|
const cached = _shards.get(safeName);
|
|
1660
2319
|
if (cached) return cached;
|
|
1661
|
-
const dbPath =
|
|
2320
|
+
const dbPath = path6.join(SHARDS_DIR, `${safeName}.db`);
|
|
1662
2321
|
const client = createClient2({
|
|
1663
2322
|
url: `file:${dbPath}`,
|
|
1664
2323
|
encryptionKey: _encryptionKey
|
|
@@ -1668,7 +2327,7 @@ function getShardClient(projectName) {
|
|
|
1668
2327
|
}
|
|
1669
2328
|
function shardExists(projectName) {
|
|
1670
2329
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1671
|
-
return existsSync5(
|
|
2330
|
+
return existsSync5(path6.join(SHARDS_DIR, `${safeName}.db`));
|
|
1672
2331
|
}
|
|
1673
2332
|
function listShards() {
|
|
1674
2333
|
if (!existsSync5(SHARDS_DIR)) return [];
|
|
@@ -1745,7 +2404,23 @@ async function ensureShardSchema(client) {
|
|
|
1745
2404
|
// MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
|
|
1746
2405
|
"ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
|
|
1747
2406
|
"ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
|
|
1748
|
-
"ALTER TABLE memories ADD COLUMN trajectory TEXT"
|
|
2407
|
+
"ALTER TABLE memories ADD COLUMN trajectory TEXT",
|
|
2408
|
+
// Metadata enrichment columns (must match database.ts)
|
|
2409
|
+
"ALTER TABLE memories ADD COLUMN intent TEXT",
|
|
2410
|
+
"ALTER TABLE memories ADD COLUMN outcome TEXT",
|
|
2411
|
+
"ALTER TABLE memories ADD COLUMN domain TEXT",
|
|
2412
|
+
"ALTER TABLE memories ADD COLUMN referenced_entities TEXT",
|
|
2413
|
+
"ALTER TABLE memories ADD COLUMN retrieval_count INTEGER DEFAULT 0",
|
|
2414
|
+
"ALTER TABLE memories ADD COLUMN chain_position TEXT",
|
|
2415
|
+
"ALTER TABLE memories ADD COLUMN review_status TEXT",
|
|
2416
|
+
"ALTER TABLE memories ADD COLUMN context_window_pct INTEGER",
|
|
2417
|
+
"ALTER TABLE memories ADD COLUMN file_paths TEXT",
|
|
2418
|
+
"ALTER TABLE memories ADD COLUMN commit_hash TEXT",
|
|
2419
|
+
"ALTER TABLE memories ADD COLUMN duration_ms INTEGER",
|
|
2420
|
+
"ALTER TABLE memories ADD COLUMN token_cost REAL",
|
|
2421
|
+
"ALTER TABLE memories ADD COLUMN audience TEXT",
|
|
2422
|
+
"ALTER TABLE memories ADD COLUMN language_type TEXT",
|
|
2423
|
+
"ALTER TABLE memories ADD COLUMN parent_memory_id TEXT"
|
|
1749
2424
|
]) {
|
|
1750
2425
|
try {
|
|
1751
2426
|
await client.execute(col);
|
|
@@ -1857,7 +2532,7 @@ var init_shard_manager = __esm({
|
|
|
1857
2532
|
"src/lib/shard-manager.ts"() {
|
|
1858
2533
|
"use strict";
|
|
1859
2534
|
init_config();
|
|
1860
|
-
SHARDS_DIR =
|
|
2535
|
+
SHARDS_DIR = path6.join(EXE_AI_DIR, "shards");
|
|
1861
2536
|
_shards = /* @__PURE__ */ new Map();
|
|
1862
2537
|
_encryptionKey = null;
|
|
1863
2538
|
_shardingEnabled = false;
|
|
@@ -2206,15 +2881,15 @@ init_database();
|
|
|
2206
2881
|
// src/lib/keychain.ts
|
|
2207
2882
|
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2208
2883
|
import { existsSync as existsSync4 } from "fs";
|
|
2209
|
-
import
|
|
2210
|
-
import
|
|
2884
|
+
import path5 from "path";
|
|
2885
|
+
import os5 from "os";
|
|
2211
2886
|
var SERVICE = "exe-mem";
|
|
2212
2887
|
var ACCOUNT = "master-key";
|
|
2213
2888
|
function getKeyDir() {
|
|
2214
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ??
|
|
2889
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path5.join(os5.homedir(), ".exe-os");
|
|
2215
2890
|
}
|
|
2216
2891
|
function getKeyPath() {
|
|
2217
|
-
return
|
|
2892
|
+
return path5.join(getKeyDir(), "master.key");
|
|
2218
2893
|
}
|
|
2219
2894
|
async function tryKeytar() {
|
|
2220
2895
|
try {
|
|
@@ -2237,7 +2912,7 @@ async function getMasterKey() {
|
|
|
2237
2912
|
const keyPath = getKeyPath();
|
|
2238
2913
|
if (!existsSync4(keyPath)) {
|
|
2239
2914
|
process.stderr.write(
|
|
2240
|
-
`[keychain] Key not found at ${keyPath} (HOME=${
|
|
2915
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2241
2916
|
`
|
|
2242
2917
|
);
|
|
2243
2918
|
return null;
|