@askexenow/exe-os 0.9.16 → 0.9.18
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 +1242 -909
- package/dist/bin/backfill-responses.js +1245 -912
- package/dist/bin/backfill-vectors.js +1244 -906
- package/dist/bin/cleanup-stale-review-tasks.js +1870 -417
- package/dist/bin/cli.js +217 -107
- package/dist/bin/exe-agent-config.js +2 -2
- package/dist/bin/exe-agent.js +62 -0
- package/dist/bin/exe-assign.js +346 -10
- package/dist/bin/exe-boot.js +387 -32
- package/dist/bin/exe-call.js +72 -2
- package/dist/bin/exe-cloud.js +8 -0
- package/dist/bin/exe-dispatch.js +1821 -225
- package/dist/bin/exe-doctor.js +720 -52
- package/dist/bin/exe-export-behaviors.js +1429 -148
- package/dist/bin/exe-forget.js +1408 -34
- package/dist/bin/exe-gateway.js +1629 -1295
- package/dist/bin/exe-heartbeat.js +1899 -448
- package/dist/bin/exe-kill.js +1624 -346
- package/dist/bin/exe-launch-agent.js +726 -90
- package/dist/bin/exe-link.js +27 -8
- package/dist/bin/exe-new-employee.js +75 -9
- package/dist/bin/exe-pending-messages.js +2769 -1316
- package/dist/bin/exe-pending-notifications.js +2829 -1376
- package/dist/bin/exe-pending-reviews.js +2847 -1392
- package/dist/bin/exe-rename.js +89 -8
- package/dist/bin/exe-review.js +1494 -312
- package/dist/bin/exe-search.js +1608 -1300
- package/dist/bin/exe-session-cleanup.js +194 -91
- package/dist/bin/exe-settings.js +10 -2
- package/dist/bin/exe-start-codex.js +769 -120
- package/dist/bin/exe-start-opencode.js +763 -108
- package/dist/bin/exe-status.js +1887 -434
- package/dist/bin/exe-team.js +1782 -324
- package/dist/bin/git-sweep.js +408 -33
- package/dist/bin/graph-backfill.js +681 -27
- package/dist/bin/graph-export.js +1419 -141
- package/dist/bin/install.js +4 -8
- package/dist/bin/intercom-check.js +8641 -0
- package/dist/bin/scan-tasks.js +553 -38
- package/dist/bin/setup.js +82 -10
- package/dist/bin/shard-migrate.js +682 -28
- package/dist/gateway/index.js +1629 -1295
- package/dist/hooks/bug-report-worker.js +1136 -183
- package/dist/hooks/codex-stop-task-finalizer.js +1060 -107
- package/dist/hooks/commit-complete.js +408 -33
- package/dist/hooks/error-recall.js +1608 -1300
- package/dist/hooks/ingest-worker.js +250 -7966
- package/dist/hooks/ingest.js +707 -119
- package/dist/hooks/instructions-loaded.js +383 -20
- package/dist/hooks/notification.js +383 -20
- package/dist/hooks/post-compact.js +384 -21
- package/dist/hooks/{response-ingest-worker.js → post-tool-combined.js} +4157 -1716
- package/dist/hooks/pre-compact.js +486 -45
- package/dist/hooks/pre-tool-use.js +385 -22
- package/dist/hooks/prompt-submit.js +291 -96
- package/dist/hooks/session-end.js +490 -48
- package/dist/hooks/session-start.js +236 -22
- package/dist/hooks/stop.js +192 -50
- package/dist/hooks/subagent-stop.js +95 -18
- package/dist/hooks/summary-worker.js +205 -361
- package/dist/index.js +221 -105
- package/dist/lib/agent-config.js +2 -2
- package/dist/lib/cloud-sync.js +27 -8
- package/dist/lib/consolidation.js +437 -41
- package/dist/lib/database.js +20 -8
- package/dist/lib/db-daemon-client.js +2 -2
- package/dist/lib/db.js +20 -8
- package/dist/lib/device-registry.js +27 -8
- package/dist/lib/employee-templates.js +62 -0
- package/dist/lib/employees.js +2 -2
- package/dist/lib/exe-daemon.js +6703 -6259
- package/dist/lib/hybrid-search.js +1608 -1300
- package/dist/lib/identity.js +1 -1
- package/dist/lib/messaging.js +11 -3
- package/dist/lib/reminders.js +1 -1
- package/dist/lib/schedules.js +718 -26
- package/dist/lib/session-registry.js +11 -0
- package/dist/lib/skill-learning.js +639 -9
- package/dist/lib/store.js +676 -27
- package/dist/lib/tasks.js +665 -27
- package/dist/lib/tmux-routing.js +732 -94
- package/dist/lib/token-spend.js +1 -1
- package/dist/mcp/server.js +856 -383
- package/dist/mcp/tools/complete-reminder.js +1 -1
- package/dist/mcp/tools/create-reminder.js +1 -1
- package/dist/mcp/tools/create-task.js +616 -46
- package/dist/mcp/tools/deactivate-behavior.js +9 -1
- package/dist/mcp/tools/list-reminders.js +1 -1
- package/dist/mcp/tools/list-tasks.js +10 -2
- package/dist/mcp/tools/send-message.js +11 -3
- package/dist/mcp/tools/update-task.js +677 -39
- package/dist/runtime/index.js +425 -37
- package/dist/tui/App.js +365 -34
- package/package.json +5 -2
- package/src/commands/exe/intercom.md +6 -17
- package/dist/bin/wiki-sync.js +0 -2991
- package/dist/hooks/prompt-ingest-worker.js +0 -3979
|
@@ -3,6 +3,12 @@ var __defProp = Object.defineProperty;
|
|
|
3
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
7
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
8
|
+
}) : x)(function(x) {
|
|
9
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
10
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
11
|
+
});
|
|
6
12
|
var __esm = (fn, res) => function __init() {
|
|
7
13
|
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
8
14
|
};
|
|
@@ -69,9 +75,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
|
|
|
69
75
|
var init_db_retry = __esm({
|
|
70
76
|
"src/lib/db-retry.ts"() {
|
|
71
77
|
"use strict";
|
|
72
|
-
MAX_RETRIES =
|
|
73
|
-
BASE_DELAY_MS =
|
|
74
|
-
MAX_JITTER_MS =
|
|
78
|
+
MAX_RETRIES = 5;
|
|
79
|
+
BASE_DELAY_MS = 250;
|
|
80
|
+
MAX_JITTER_MS = 400;
|
|
75
81
|
}
|
|
76
82
|
});
|
|
77
83
|
|
|
@@ -85,12 +91,25 @@ async function ensurePrivateDir(dirPath) {
|
|
|
85
91
|
} catch {
|
|
86
92
|
}
|
|
87
93
|
}
|
|
94
|
+
function ensurePrivateDirSync(dirPath) {
|
|
95
|
+
mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
96
|
+
try {
|
|
97
|
+
chmodSync(dirPath, PRIVATE_DIR_MODE);
|
|
98
|
+
} catch {
|
|
99
|
+
}
|
|
100
|
+
}
|
|
88
101
|
async function enforcePrivateFile(filePath) {
|
|
89
102
|
try {
|
|
90
103
|
await chmod(filePath, PRIVATE_FILE_MODE);
|
|
91
104
|
} catch {
|
|
92
105
|
}
|
|
93
106
|
}
|
|
107
|
+
function enforcePrivateFileSync(filePath) {
|
|
108
|
+
try {
|
|
109
|
+
if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
|
|
110
|
+
} catch {
|
|
111
|
+
}
|
|
112
|
+
}
|
|
94
113
|
var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
|
|
95
114
|
var init_secure_files = __esm({
|
|
96
115
|
"src/lib/secure-files.ts"() {
|
|
@@ -907,207 +926,988 @@ var init_database_adapter = __esm({
|
|
|
907
926
|
}
|
|
908
927
|
});
|
|
909
928
|
|
|
910
|
-
// src/
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
929
|
+
// src/types/memory.ts
|
|
930
|
+
var EMBEDDING_DIM;
|
|
931
|
+
var init_memory = __esm({
|
|
932
|
+
"src/types/memory.ts"() {
|
|
933
|
+
"use strict";
|
|
934
|
+
EMBEDDING_DIM = 1024;
|
|
916
935
|
}
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
936
|
+
});
|
|
937
|
+
|
|
938
|
+
// src/lib/daemon-auth.ts
|
|
939
|
+
import crypto from "crypto";
|
|
940
|
+
import path4 from "path";
|
|
941
|
+
import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
942
|
+
function normalizeToken(token) {
|
|
943
|
+
if (!token) return null;
|
|
944
|
+
const trimmed = token.trim();
|
|
945
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
946
|
+
}
|
|
947
|
+
function readDaemonToken() {
|
|
948
|
+
try {
|
|
949
|
+
if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
|
|
950
|
+
return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
|
|
951
|
+
} catch {
|
|
952
|
+
return null;
|
|
920
953
|
}
|
|
921
|
-
|
|
922
|
-
|
|
954
|
+
}
|
|
955
|
+
function ensureDaemonToken(seed) {
|
|
956
|
+
const existing = readDaemonToken();
|
|
957
|
+
if (existing) return existing;
|
|
958
|
+
const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
|
|
959
|
+
ensurePrivateDirSync(EXE_AI_DIR);
|
|
960
|
+
writeFileSync2(DAEMON_TOKEN_PATH, `${token}
|
|
961
|
+
`, "utf8");
|
|
962
|
+
enforcePrivateFileSync(DAEMON_TOKEN_PATH);
|
|
963
|
+
return token;
|
|
964
|
+
}
|
|
965
|
+
var DAEMON_TOKEN_PATH;
|
|
966
|
+
var init_daemon_auth = __esm({
|
|
967
|
+
"src/lib/daemon-auth.ts"() {
|
|
968
|
+
"use strict";
|
|
969
|
+
init_config();
|
|
970
|
+
init_secure_files();
|
|
971
|
+
DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
|
|
923
972
|
}
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
973
|
+
});
|
|
974
|
+
|
|
975
|
+
// src/lib/exe-daemon-client.ts
|
|
976
|
+
var exe_daemon_client_exports = {};
|
|
977
|
+
__export(exe_daemon_client_exports, {
|
|
978
|
+
connectEmbedDaemon: () => connectEmbedDaemon,
|
|
979
|
+
disconnectClient: () => disconnectClient,
|
|
980
|
+
embedBatchViaClient: () => embedBatchViaClient,
|
|
981
|
+
embedViaClient: () => embedViaClient,
|
|
982
|
+
isClientConnected: () => isClientConnected,
|
|
983
|
+
pingDaemon: () => pingDaemon,
|
|
984
|
+
sendDaemonRequest: () => sendDaemonRequest,
|
|
985
|
+
sendIngestRequest: () => sendIngestRequest
|
|
986
|
+
});
|
|
987
|
+
import net from "net";
|
|
988
|
+
import os4 from "os";
|
|
989
|
+
import { spawn } from "child_process";
|
|
990
|
+
import { randomUUID } from "crypto";
|
|
991
|
+
import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
|
|
992
|
+
import path5 from "path";
|
|
993
|
+
import { fileURLToPath } from "url";
|
|
994
|
+
function handleData(chunk) {
|
|
995
|
+
_buffer += chunk.toString();
|
|
996
|
+
if (_buffer.length > MAX_BUFFER) {
|
|
997
|
+
_buffer = "";
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
let newlineIdx;
|
|
1001
|
+
while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
|
|
1002
|
+
const line = _buffer.slice(0, newlineIdx).trim();
|
|
1003
|
+
_buffer = _buffer.slice(newlineIdx + 1);
|
|
1004
|
+
if (!line) continue;
|
|
1005
|
+
try {
|
|
1006
|
+
const response = JSON.parse(line);
|
|
1007
|
+
const id = response.id;
|
|
1008
|
+
if (!id) continue;
|
|
1009
|
+
const entry = _pending.get(id);
|
|
1010
|
+
if (entry) {
|
|
1011
|
+
clearTimeout(entry.timer);
|
|
1012
|
+
_pending.delete(id);
|
|
1013
|
+
entry.resolve(response);
|
|
1014
|
+
}
|
|
1015
|
+
} catch {
|
|
1016
|
+
}
|
|
929
1017
|
}
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
1018
|
+
}
|
|
1019
|
+
function cleanupStaleFiles() {
|
|
1020
|
+
if (existsSync5(PID_PATH)) {
|
|
1021
|
+
try {
|
|
1022
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
1023
|
+
if (pid > 0) {
|
|
1024
|
+
try {
|
|
1025
|
+
process.kill(pid, 0);
|
|
1026
|
+
return;
|
|
1027
|
+
} catch {
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
} catch {
|
|
1031
|
+
}
|
|
1032
|
+
try {
|
|
1033
|
+
unlinkSync2(PID_PATH);
|
|
1034
|
+
} catch {
|
|
1035
|
+
}
|
|
1036
|
+
try {
|
|
1037
|
+
unlinkSync2(SOCKET_PATH);
|
|
1038
|
+
} catch {
|
|
1039
|
+
}
|
|
935
1040
|
}
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
|
|
944
|
-
_walCheckpointTimer = setInterval(() => {
|
|
945
|
-
_client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
|
|
946
|
-
});
|
|
947
|
-
}, 3e4);
|
|
948
|
-
_walCheckpointTimer.unref();
|
|
949
|
-
if (process.env.DATABASE_URL) {
|
|
950
|
-
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1041
|
+
}
|
|
1042
|
+
function findPackageRoot() {
|
|
1043
|
+
let dir = path5.dirname(fileURLToPath(import.meta.url));
|
|
1044
|
+
const { root } = path5.parse(dir);
|
|
1045
|
+
while (dir !== root) {
|
|
1046
|
+
if (existsSync5(path5.join(dir, "package.json"))) return dir;
|
|
1047
|
+
dir = path5.dirname(dir);
|
|
951
1048
|
}
|
|
1049
|
+
return null;
|
|
952
1050
|
}
|
|
953
|
-
function
|
|
954
|
-
if (
|
|
955
|
-
|
|
1051
|
+
function getAvailableMemoryGB() {
|
|
1052
|
+
if (process.platform === "darwin") {
|
|
1053
|
+
try {
|
|
1054
|
+
const { execSync: execSync4 } = __require("child_process");
|
|
1055
|
+
const vmstat = execSync4("vm_stat", { encoding: "utf8" });
|
|
1056
|
+
const pageSize = 16384;
|
|
1057
|
+
const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
|
|
1058
|
+
const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
|
|
1059
|
+
const free = vmstat.match(/Pages free:\s+(\d+)/);
|
|
1060
|
+
const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
|
|
1061
|
+
const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
|
|
1062
|
+
const freePages = free ? parseInt(free[1], 10) : 0;
|
|
1063
|
+
const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
|
|
1064
|
+
const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
|
|
1065
|
+
return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
|
|
1066
|
+
} catch {
|
|
1067
|
+
return os4.freemem() / (1024 * 1024 * 1024);
|
|
1068
|
+
}
|
|
956
1069
|
}
|
|
957
|
-
|
|
958
|
-
|
|
1070
|
+
return os4.freemem() / (1024 * 1024 * 1024);
|
|
1071
|
+
}
|
|
1072
|
+
function spawnDaemon() {
|
|
1073
|
+
const freeGB = getAvailableMemoryGB();
|
|
1074
|
+
const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
|
|
1075
|
+
if (totalGB <= 8) {
|
|
1076
|
+
process.stderr.write(
|
|
1077
|
+
`[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
|
|
1078
|
+
`
|
|
1079
|
+
);
|
|
1080
|
+
return;
|
|
959
1081
|
}
|
|
960
|
-
if (
|
|
961
|
-
|
|
1082
|
+
if (totalGB <= 16 && freeGB < 2) {
|
|
1083
|
+
process.stderr.write(
|
|
1084
|
+
`[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
|
|
1085
|
+
`
|
|
1086
|
+
);
|
|
1087
|
+
return;
|
|
962
1088
|
}
|
|
963
|
-
|
|
964
|
-
|
|
1089
|
+
const pkgRoot = findPackageRoot();
|
|
1090
|
+
if (!pkgRoot) {
|
|
1091
|
+
process.stderr.write("[exed-client] WARN: cannot find package root\n");
|
|
1092
|
+
return;
|
|
965
1093
|
}
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
1094
|
+
const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
|
|
1095
|
+
if (!existsSync5(daemonPath)) {
|
|
1096
|
+
process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
|
|
1097
|
+
`);
|
|
1098
|
+
return;
|
|
971
1099
|
}
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
await client.execute("PRAGMA wal_autocheckpoint = 1000");
|
|
1100
|
+
const resolvedPath = daemonPath;
|
|
1101
|
+
const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
|
|
1102
|
+
process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
|
|
1103
|
+
`);
|
|
1104
|
+
const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
|
|
1105
|
+
let stderrFd = "ignore";
|
|
979
1106
|
try {
|
|
980
|
-
|
|
1107
|
+
stderrFd = openSync(logPath, "a");
|
|
981
1108
|
} catch {
|
|
982
1109
|
}
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
CREATE INDEX IF NOT EXISTS idx_memories_session
|
|
1005
|
-
ON memories(session_id);
|
|
1006
|
-
|
|
1007
|
-
CREATE INDEX IF NOT EXISTS idx_memories_project
|
|
1008
|
-
ON memories(project_name);
|
|
1009
|
-
|
|
1010
|
-
CREATE INDEX IF NOT EXISTS idx_memories_tool
|
|
1011
|
-
ON memories(tool_name);
|
|
1012
|
-
|
|
1013
|
-
CREATE INDEX IF NOT EXISTS idx_memories_version
|
|
1014
|
-
ON memories(version);
|
|
1015
|
-
|
|
1016
|
-
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
1017
|
-
ON memories(agent_id, project_name);
|
|
1018
|
-
`);
|
|
1019
|
-
await client.executeMultiple(`
|
|
1020
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
1021
|
-
raw_text,
|
|
1022
|
-
content='memories',
|
|
1023
|
-
content_rowid='rowid'
|
|
1024
|
-
);
|
|
1025
|
-
|
|
1026
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
1027
|
-
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1028
|
-
END;
|
|
1029
|
-
|
|
1030
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
1031
|
-
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1032
|
-
END;
|
|
1033
|
-
|
|
1034
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
1035
|
-
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1036
|
-
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1037
|
-
END;
|
|
1038
|
-
`);
|
|
1039
|
-
await client.executeMultiple(`
|
|
1040
|
-
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
1041
|
-
key TEXT PRIMARY KEY,
|
|
1042
|
-
value TEXT NOT NULL
|
|
1043
|
-
);
|
|
1044
|
-
`);
|
|
1045
|
-
await client.executeMultiple(`
|
|
1046
|
-
CREATE TABLE IF NOT EXISTS tasks (
|
|
1047
|
-
id TEXT PRIMARY KEY,
|
|
1048
|
-
title TEXT NOT NULL,
|
|
1049
|
-
assigned_to TEXT NOT NULL,
|
|
1050
|
-
assigned_by TEXT NOT NULL,
|
|
1051
|
-
project_name TEXT NOT NULL,
|
|
1052
|
-
priority TEXT NOT NULL DEFAULT 'p1',
|
|
1053
|
-
status TEXT NOT NULL DEFAULT 'open',
|
|
1054
|
-
task_file TEXT,
|
|
1055
|
-
created_at TEXT NOT NULL,
|
|
1056
|
-
updated_at TEXT NOT NULL
|
|
1057
|
-
);
|
|
1058
|
-
|
|
1059
|
-
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
1060
|
-
ON tasks(assigned_to, status);
|
|
1061
|
-
`);
|
|
1062
|
-
await client.executeMultiple(`
|
|
1063
|
-
CREATE TABLE IF NOT EXISTS behaviors (
|
|
1064
|
-
id TEXT PRIMARY KEY,
|
|
1065
|
-
agent_id TEXT NOT NULL,
|
|
1066
|
-
project_name TEXT,
|
|
1067
|
-
domain TEXT,
|
|
1068
|
-
content TEXT NOT NULL,
|
|
1069
|
-
active INTEGER NOT NULL DEFAULT 1,
|
|
1070
|
-
created_at TEXT NOT NULL,
|
|
1071
|
-
updated_at TEXT NOT NULL
|
|
1072
|
-
);
|
|
1073
|
-
|
|
1074
|
-
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
1075
|
-
ON behaviors(agent_id, active);
|
|
1076
|
-
`);
|
|
1077
|
-
try {
|
|
1078
|
-
const coordinatorName = getCoordinatorName();
|
|
1079
|
-
const existing = await client.execute({
|
|
1080
|
-
sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
|
|
1081
|
-
args: [coordinatorName]
|
|
1082
|
-
});
|
|
1083
|
-
if (Number(existing.rows[0]?.cnt) === 0) {
|
|
1084
|
-
const seededAt = "2026-03-25T00:00:00Z";
|
|
1085
|
-
for (const [domain, content] of [
|
|
1086
|
-
["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
|
|
1087
|
-
["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
|
|
1088
|
-
["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
|
|
1089
|
-
]) {
|
|
1090
|
-
await client.execute({
|
|
1091
|
-
sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
1092
|
-
VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
|
|
1093
|
-
args: [coordinatorName, domain, content, seededAt, seededAt]
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1110
|
+
const heapCapMB = totalGB <= 8 ? 256 : 512;
|
|
1111
|
+
const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
|
|
1112
|
+
const child = spawn(process.execPath, nodeArgs, {
|
|
1113
|
+
detached: true,
|
|
1114
|
+
stdio: ["ignore", "ignore", stderrFd],
|
|
1115
|
+
env: {
|
|
1116
|
+
...process.env,
|
|
1117
|
+
TMUX: void 0,
|
|
1118
|
+
// Daemon is global — must not inherit session scope
|
|
1119
|
+
TMUX_PANE: void 0,
|
|
1120
|
+
// Prevents resolveExeSession() from scoping to one session
|
|
1121
|
+
EXE_DAEMON_SOCK: SOCKET_PATH,
|
|
1122
|
+
EXE_DAEMON_PID: PID_PATH,
|
|
1123
|
+
[DAEMON_TOKEN_ENV]: daemonToken
|
|
1124
|
+
}
|
|
1125
|
+
});
|
|
1126
|
+
child.unref();
|
|
1127
|
+
if (typeof stderrFd === "number") {
|
|
1128
|
+
try {
|
|
1129
|
+
closeSync(stderrFd);
|
|
1130
|
+
} catch {
|
|
1096
1131
|
}
|
|
1097
|
-
} catch {
|
|
1098
1132
|
}
|
|
1133
|
+
}
|
|
1134
|
+
function acquireSpawnLock() {
|
|
1099
1135
|
try {
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
});
|
|
1136
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
1137
|
+
closeSync(fd);
|
|
1138
|
+
return true;
|
|
1104
1139
|
} catch {
|
|
1140
|
+
try {
|
|
1141
|
+
const stat = statSync(SPAWN_LOCK_PATH);
|
|
1142
|
+
if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
|
|
1143
|
+
try {
|
|
1144
|
+
unlinkSync2(SPAWN_LOCK_PATH);
|
|
1145
|
+
} catch {
|
|
1146
|
+
}
|
|
1147
|
+
try {
|
|
1148
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
1149
|
+
closeSync(fd);
|
|
1150
|
+
return true;
|
|
1151
|
+
} catch {
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
} catch {
|
|
1155
|
+
}
|
|
1156
|
+
return false;
|
|
1105
1157
|
}
|
|
1158
|
+
}
|
|
1159
|
+
function releaseSpawnLock() {
|
|
1106
1160
|
try {
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1161
|
+
unlinkSync2(SPAWN_LOCK_PATH);
|
|
1162
|
+
} catch {
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
function connectToSocket() {
|
|
1166
|
+
return new Promise((resolve) => {
|
|
1167
|
+
if (_socket && _connected) {
|
|
1168
|
+
resolve(true);
|
|
1169
|
+
return;
|
|
1170
|
+
}
|
|
1171
|
+
const socket = net.createConnection({ path: SOCKET_PATH });
|
|
1172
|
+
const connectTimeout = setTimeout(() => {
|
|
1173
|
+
socket.destroy();
|
|
1174
|
+
resolve(false);
|
|
1175
|
+
}, 2e3);
|
|
1176
|
+
socket.on("connect", () => {
|
|
1177
|
+
clearTimeout(connectTimeout);
|
|
1178
|
+
_socket = socket;
|
|
1179
|
+
_connected = true;
|
|
1180
|
+
_buffer = "";
|
|
1181
|
+
socket.on("data", handleData);
|
|
1182
|
+
socket.on("close", () => {
|
|
1183
|
+
_connected = false;
|
|
1184
|
+
_socket = null;
|
|
1185
|
+
for (const [id, entry] of _pending) {
|
|
1186
|
+
clearTimeout(entry.timer);
|
|
1187
|
+
_pending.delete(id);
|
|
1188
|
+
entry.resolve({ error: "Connection closed" });
|
|
1189
|
+
}
|
|
1190
|
+
});
|
|
1191
|
+
socket.on("error", () => {
|
|
1192
|
+
_connected = false;
|
|
1193
|
+
_socket = null;
|
|
1194
|
+
});
|
|
1195
|
+
resolve(true);
|
|
1196
|
+
});
|
|
1197
|
+
socket.on("error", () => {
|
|
1198
|
+
clearTimeout(connectTimeout);
|
|
1199
|
+
resolve(false);
|
|
1200
|
+
});
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
async function connectEmbedDaemon() {
|
|
1204
|
+
if (_socket && _connected) return true;
|
|
1205
|
+
if (await connectToSocket()) return true;
|
|
1206
|
+
if (acquireSpawnLock()) {
|
|
1207
|
+
try {
|
|
1208
|
+
cleanupStaleFiles();
|
|
1209
|
+
spawnDaemon();
|
|
1210
|
+
} finally {
|
|
1211
|
+
releaseSpawnLock();
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
const start = Date.now();
|
|
1215
|
+
let delay2 = 100;
|
|
1216
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1217
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
1218
|
+
if (await connectToSocket()) return true;
|
|
1219
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
1220
|
+
}
|
|
1221
|
+
return false;
|
|
1222
|
+
}
|
|
1223
|
+
function sendRequest(texts, priority) {
|
|
1224
|
+
return sendDaemonRequest({ texts, priority });
|
|
1225
|
+
}
|
|
1226
|
+
function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
1227
|
+
return new Promise((resolve) => {
|
|
1228
|
+
if (!_socket || !_connected) {
|
|
1229
|
+
resolve({ error: "Not connected" });
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
const id = randomUUID();
|
|
1233
|
+
const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
|
|
1234
|
+
const timer = setTimeout(() => {
|
|
1235
|
+
_pending.delete(id);
|
|
1236
|
+
resolve({ error: "Request timeout" });
|
|
1237
|
+
}, timeoutMs);
|
|
1238
|
+
_pending.set(id, { resolve, timer });
|
|
1239
|
+
try {
|
|
1240
|
+
_socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
|
|
1241
|
+
} catch {
|
|
1242
|
+
clearTimeout(timer);
|
|
1243
|
+
_pending.delete(id);
|
|
1244
|
+
resolve({ error: "Write failed" });
|
|
1245
|
+
}
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
async function pingDaemon() {
|
|
1249
|
+
if (!_socket || !_connected) return null;
|
|
1250
|
+
const response = await sendDaemonRequest({ type: "health" }, 5e3);
|
|
1251
|
+
if (response.health) {
|
|
1252
|
+
return response.health;
|
|
1253
|
+
}
|
|
1254
|
+
return null;
|
|
1255
|
+
}
|
|
1256
|
+
function killAndRespawnDaemon() {
|
|
1257
|
+
if (!acquireSpawnLock()) {
|
|
1258
|
+
process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
|
|
1259
|
+
if (_socket) {
|
|
1260
|
+
_socket.destroy();
|
|
1261
|
+
_socket = null;
|
|
1262
|
+
}
|
|
1263
|
+
_connected = false;
|
|
1264
|
+
_buffer = "";
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
try {
|
|
1268
|
+
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
1269
|
+
if (existsSync5(PID_PATH)) {
|
|
1270
|
+
try {
|
|
1271
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
1272
|
+
if (pid > 0) {
|
|
1273
|
+
try {
|
|
1274
|
+
process.kill(pid, "SIGKILL");
|
|
1275
|
+
} catch {
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
} catch {
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
if (_socket) {
|
|
1282
|
+
_socket.destroy();
|
|
1283
|
+
_socket = null;
|
|
1284
|
+
}
|
|
1285
|
+
_connected = false;
|
|
1286
|
+
_buffer = "";
|
|
1287
|
+
try {
|
|
1288
|
+
unlinkSync2(PID_PATH);
|
|
1289
|
+
} catch {
|
|
1290
|
+
}
|
|
1291
|
+
try {
|
|
1292
|
+
unlinkSync2(SOCKET_PATH);
|
|
1293
|
+
} catch {
|
|
1294
|
+
}
|
|
1295
|
+
spawnDaemon();
|
|
1296
|
+
} finally {
|
|
1297
|
+
releaseSpawnLock();
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
function isDaemonTooYoung() {
|
|
1301
|
+
try {
|
|
1302
|
+
const stat = statSync(PID_PATH);
|
|
1303
|
+
return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
|
|
1304
|
+
} catch {
|
|
1305
|
+
return false;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
async function retryThenRestart(doRequest, label) {
|
|
1309
|
+
const result = await doRequest();
|
|
1310
|
+
if (!result.error) {
|
|
1311
|
+
_consecutiveFailures = 0;
|
|
1312
|
+
return result;
|
|
1313
|
+
}
|
|
1314
|
+
_consecutiveFailures++;
|
|
1315
|
+
for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
|
|
1316
|
+
const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
|
|
1317
|
+
process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
|
|
1318
|
+
`);
|
|
1319
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
1320
|
+
if (!_connected) {
|
|
1321
|
+
if (!await connectToSocket()) continue;
|
|
1322
|
+
}
|
|
1323
|
+
const retry = await doRequest();
|
|
1324
|
+
if (!retry.error) {
|
|
1325
|
+
_consecutiveFailures = 0;
|
|
1326
|
+
return retry;
|
|
1327
|
+
}
|
|
1328
|
+
_consecutiveFailures++;
|
|
1329
|
+
}
|
|
1330
|
+
if (isDaemonTooYoung()) {
|
|
1331
|
+
process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
|
|
1332
|
+
`);
|
|
1333
|
+
return { error: result.error };
|
|
1334
|
+
}
|
|
1335
|
+
process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
|
|
1336
|
+
`);
|
|
1337
|
+
killAndRespawnDaemon();
|
|
1338
|
+
const start = Date.now();
|
|
1339
|
+
let delay2 = 200;
|
|
1340
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1341
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
1342
|
+
if (await connectToSocket()) break;
|
|
1343
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
1344
|
+
}
|
|
1345
|
+
if (!_connected) return { error: "Daemon restart failed" };
|
|
1346
|
+
const final = await doRequest();
|
|
1347
|
+
if (!final.error) _consecutiveFailures = 0;
|
|
1348
|
+
return final;
|
|
1349
|
+
}
|
|
1350
|
+
async function embedViaClient(text, priority = "high") {
|
|
1351
|
+
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
1352
|
+
_requestCount++;
|
|
1353
|
+
if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
|
|
1354
|
+
const health = await pingDaemon();
|
|
1355
|
+
if (!health && !isDaemonTooYoung()) {
|
|
1356
|
+
process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
|
|
1357
|
+
`);
|
|
1358
|
+
killAndRespawnDaemon();
|
|
1359
|
+
const start = Date.now();
|
|
1360
|
+
let d = 200;
|
|
1361
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1362
|
+
await new Promise((r) => setTimeout(r, d));
|
|
1363
|
+
if (await connectToSocket()) break;
|
|
1364
|
+
d = Math.min(d * 2, 3e3);
|
|
1365
|
+
}
|
|
1366
|
+
if (!_connected) return null;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
const result = await retryThenRestart(
|
|
1370
|
+
() => sendRequest([text], priority),
|
|
1371
|
+
"Embed"
|
|
1372
|
+
);
|
|
1373
|
+
return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
|
|
1374
|
+
}
|
|
1375
|
+
async function embedBatchViaClient(texts, priority = "high") {
|
|
1376
|
+
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
1377
|
+
_requestCount++;
|
|
1378
|
+
const result = await retryThenRestart(
|
|
1379
|
+
() => sendRequest(texts, priority),
|
|
1380
|
+
"Batch embed"
|
|
1381
|
+
);
|
|
1382
|
+
return !result.error && result.vectors ? result.vectors : null;
|
|
1383
|
+
}
|
|
1384
|
+
function disconnectClient() {
|
|
1385
|
+
if (_socket) {
|
|
1386
|
+
_socket.destroy();
|
|
1387
|
+
_socket = null;
|
|
1388
|
+
}
|
|
1389
|
+
_connected = false;
|
|
1390
|
+
_buffer = "";
|
|
1391
|
+
for (const [id, entry] of _pending) {
|
|
1392
|
+
clearTimeout(entry.timer);
|
|
1393
|
+
_pending.delete(id);
|
|
1394
|
+
entry.resolve({ error: "Client disconnected" });
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
function isClientConnected() {
|
|
1398
|
+
return _connected;
|
|
1399
|
+
}
|
|
1400
|
+
function sendIngestRequest(payload) {
|
|
1401
|
+
if (!_socket || !_connected) return false;
|
|
1402
|
+
try {
|
|
1403
|
+
const id = randomUUID();
|
|
1404
|
+
const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
|
|
1405
|
+
_socket.write(JSON.stringify({ id, token, type: "ingest", ...payload }) + "\n");
|
|
1406
|
+
return true;
|
|
1407
|
+
} catch {
|
|
1408
|
+
return false;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, DAEMON_TOKEN_ENV, _socket, _connected, _buffer, _requestCount, _consecutiveFailures, HEALTH_CHECK_INTERVAL, MAX_RETRIES_BEFORE_RESTART, RETRY_DELAYS_MS, MIN_DAEMON_AGE_MS, _pending, MAX_BUFFER;
|
|
1412
|
+
var init_exe_daemon_client = __esm({
|
|
1413
|
+
"src/lib/exe-daemon-client.ts"() {
|
|
1414
|
+
"use strict";
|
|
1415
|
+
init_config();
|
|
1416
|
+
init_daemon_auth();
|
|
1417
|
+
SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
|
|
1418
|
+
PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
|
|
1419
|
+
SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
|
|
1420
|
+
SPAWN_LOCK_STALE_MS = 3e4;
|
|
1421
|
+
CONNECT_TIMEOUT_MS = 15e3;
|
|
1422
|
+
REQUEST_TIMEOUT_MS = 3e4;
|
|
1423
|
+
DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
|
|
1424
|
+
_socket = null;
|
|
1425
|
+
_connected = false;
|
|
1426
|
+
_buffer = "";
|
|
1427
|
+
_requestCount = 0;
|
|
1428
|
+
_consecutiveFailures = 0;
|
|
1429
|
+
HEALTH_CHECK_INTERVAL = 100;
|
|
1430
|
+
MAX_RETRIES_BEFORE_RESTART = 3;
|
|
1431
|
+
RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
|
|
1432
|
+
MIN_DAEMON_AGE_MS = 3e4;
|
|
1433
|
+
_pending = /* @__PURE__ */ new Map();
|
|
1434
|
+
MAX_BUFFER = 1e7;
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
|
|
1438
|
+
// src/lib/daemon-protocol.ts
|
|
1439
|
+
var daemon_protocol_exports = {};
|
|
1440
|
+
__export(daemon_protocol_exports, {
|
|
1441
|
+
deserializeArgs: () => deserializeArgs,
|
|
1442
|
+
deserializeResultSet: () => deserializeResultSet,
|
|
1443
|
+
deserializeValue: () => deserializeValue,
|
|
1444
|
+
serializeArgs: () => serializeArgs,
|
|
1445
|
+
serializeResultSet: () => serializeResultSet,
|
|
1446
|
+
serializeValue: () => serializeValue
|
|
1447
|
+
});
|
|
1448
|
+
function serializeValue(v) {
|
|
1449
|
+
if (v === null || v === void 0) return null;
|
|
1450
|
+
if (typeof v === "bigint") return Number(v);
|
|
1451
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
1452
|
+
if (v instanceof Uint8Array) {
|
|
1453
|
+
return { __blob: Buffer.from(v).toString("base64") };
|
|
1454
|
+
}
|
|
1455
|
+
if (ArrayBuffer.isView(v)) {
|
|
1456
|
+
return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
|
|
1457
|
+
}
|
|
1458
|
+
if (v instanceof ArrayBuffer) {
|
|
1459
|
+
return { __blob: Buffer.from(v).toString("base64") };
|
|
1460
|
+
}
|
|
1461
|
+
if (typeof v === "string" || typeof v === "number") return v;
|
|
1462
|
+
return String(v);
|
|
1463
|
+
}
|
|
1464
|
+
function deserializeValue(v) {
|
|
1465
|
+
if (v === null) return null;
|
|
1466
|
+
if (typeof v === "object" && v !== null && "__blob" in v) {
|
|
1467
|
+
const buf = Buffer.from(v.__blob, "base64");
|
|
1468
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
1469
|
+
}
|
|
1470
|
+
return v;
|
|
1471
|
+
}
|
|
1472
|
+
function serializeArgs(args) {
|
|
1473
|
+
return args.map(serializeValue);
|
|
1474
|
+
}
|
|
1475
|
+
function deserializeArgs(args) {
|
|
1476
|
+
return args.map(deserializeValue);
|
|
1477
|
+
}
|
|
1478
|
+
function serializeResultSet(rs) {
|
|
1479
|
+
const rows = [];
|
|
1480
|
+
for (const row of rs.rows) {
|
|
1481
|
+
const obj = {};
|
|
1482
|
+
for (let i = 0; i < rs.columns.length; i++) {
|
|
1483
|
+
const col = rs.columns[i];
|
|
1484
|
+
if (col !== void 0) {
|
|
1485
|
+
obj[col] = serializeValue(row[i]);
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
rows.push(obj);
|
|
1489
|
+
}
|
|
1490
|
+
return {
|
|
1491
|
+
columns: [...rs.columns],
|
|
1492
|
+
columnTypes: [...rs.columnTypes ?? []],
|
|
1493
|
+
rows,
|
|
1494
|
+
rowsAffected: typeof rs.rowsAffected === "bigint" ? Number(rs.rowsAffected) : rs.rowsAffected ?? 0,
|
|
1495
|
+
lastInsertRowid: rs.lastInsertRowid != null ? typeof rs.lastInsertRowid === "bigint" ? Number(rs.lastInsertRowid) : rs.lastInsertRowid : null
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
function deserializeResultSet(srs) {
|
|
1499
|
+
const rows = srs.rows.map((obj) => {
|
|
1500
|
+
const values = srs.columns.map(
|
|
1501
|
+
(col) => deserializeValue(obj[col] ?? null)
|
|
1502
|
+
);
|
|
1503
|
+
const row = values;
|
|
1504
|
+
for (let i = 0; i < srs.columns.length; i++) {
|
|
1505
|
+
const col = srs.columns[i];
|
|
1506
|
+
if (col !== void 0) {
|
|
1507
|
+
row[col] = values[i] ?? null;
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
Object.defineProperty(row, "length", {
|
|
1511
|
+
value: values.length,
|
|
1512
|
+
enumerable: false
|
|
1513
|
+
});
|
|
1514
|
+
return row;
|
|
1515
|
+
});
|
|
1516
|
+
return {
|
|
1517
|
+
columns: srs.columns,
|
|
1518
|
+
columnTypes: srs.columnTypes ?? [],
|
|
1519
|
+
rows,
|
|
1520
|
+
rowsAffected: srs.rowsAffected,
|
|
1521
|
+
lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
|
|
1522
|
+
toJSON: () => ({
|
|
1523
|
+
columns: srs.columns,
|
|
1524
|
+
columnTypes: srs.columnTypes ?? [],
|
|
1525
|
+
rows: srs.rows,
|
|
1526
|
+
rowsAffected: srs.rowsAffected,
|
|
1527
|
+
lastInsertRowid: srs.lastInsertRowid
|
|
1528
|
+
})
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
var init_daemon_protocol = __esm({
|
|
1532
|
+
"src/lib/daemon-protocol.ts"() {
|
|
1533
|
+
"use strict";
|
|
1534
|
+
}
|
|
1535
|
+
});
|
|
1536
|
+
|
|
1537
|
+
// src/lib/db-daemon-client.ts
|
|
1538
|
+
var db_daemon_client_exports = {};
|
|
1539
|
+
__export(db_daemon_client_exports, {
|
|
1540
|
+
createDaemonDbClient: () => createDaemonDbClient,
|
|
1541
|
+
initDaemonDbClient: () => initDaemonDbClient
|
|
1542
|
+
});
|
|
1543
|
+
function normalizeStatement2(stmt) {
|
|
1544
|
+
if (typeof stmt === "string") {
|
|
1545
|
+
return { sql: stmt, args: [] };
|
|
1546
|
+
}
|
|
1547
|
+
const sql = stmt.sql;
|
|
1548
|
+
let args = [];
|
|
1549
|
+
if (Array.isArray(stmt.args)) {
|
|
1550
|
+
args = stmt.args.map((v) => serializeValue(v));
|
|
1551
|
+
} else if (stmt.args && typeof stmt.args === "object") {
|
|
1552
|
+
const named = {};
|
|
1553
|
+
for (const [key, val] of Object.entries(stmt.args)) {
|
|
1554
|
+
named[key] = serializeValue(val);
|
|
1555
|
+
}
|
|
1556
|
+
return { sql, args: named };
|
|
1557
|
+
}
|
|
1558
|
+
return { sql, args };
|
|
1559
|
+
}
|
|
1560
|
+
function createDaemonDbClient(fallbackClient) {
|
|
1561
|
+
let _useDaemon = false;
|
|
1562
|
+
const client = {
|
|
1563
|
+
async execute(stmt) {
|
|
1564
|
+
if (!_useDaemon || !isClientConnected()) {
|
|
1565
|
+
return fallbackClient.execute(stmt);
|
|
1566
|
+
}
|
|
1567
|
+
const { sql, args } = normalizeStatement2(stmt);
|
|
1568
|
+
const response = await sendDaemonRequest({
|
|
1569
|
+
type: "db-execute",
|
|
1570
|
+
sql,
|
|
1571
|
+
args
|
|
1572
|
+
});
|
|
1573
|
+
if (response.error) {
|
|
1574
|
+
const errMsg = String(response.error);
|
|
1575
|
+
if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
|
|
1576
|
+
process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
|
|
1577
|
+
`);
|
|
1578
|
+
return fallbackClient.execute(stmt);
|
|
1579
|
+
}
|
|
1580
|
+
throw new Error(errMsg);
|
|
1581
|
+
}
|
|
1582
|
+
if (response.db) {
|
|
1583
|
+
return deserializeResultSet(response.db);
|
|
1584
|
+
}
|
|
1585
|
+
process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
|
|
1586
|
+
return fallbackClient.execute(stmt);
|
|
1587
|
+
},
|
|
1588
|
+
async batch(stmts, mode) {
|
|
1589
|
+
if (!_useDaemon || !isClientConnected()) {
|
|
1590
|
+
return fallbackClient.batch(stmts, mode);
|
|
1591
|
+
}
|
|
1592
|
+
const statements = stmts.map(normalizeStatement2);
|
|
1593
|
+
const response = await sendDaemonRequest({
|
|
1594
|
+
type: "db-batch",
|
|
1595
|
+
statements,
|
|
1596
|
+
mode: mode ?? "deferred"
|
|
1597
|
+
});
|
|
1598
|
+
if (response.error) {
|
|
1599
|
+
const errMsg = String(response.error);
|
|
1600
|
+
if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
|
|
1601
|
+
process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
|
|
1602
|
+
`);
|
|
1603
|
+
return fallbackClient.batch(stmts, mode);
|
|
1604
|
+
}
|
|
1605
|
+
throw new Error(errMsg);
|
|
1606
|
+
}
|
|
1607
|
+
const batchResults = response["db-batch"];
|
|
1608
|
+
if (batchResults) {
|
|
1609
|
+
return batchResults.map(deserializeResultSet);
|
|
1610
|
+
}
|
|
1611
|
+
process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
|
|
1612
|
+
return fallbackClient.batch(stmts, mode);
|
|
1613
|
+
},
|
|
1614
|
+
// Transaction support — delegate to fallback (transactions need direct connection)
|
|
1615
|
+
async transaction(mode) {
|
|
1616
|
+
return fallbackClient.transaction(mode);
|
|
1617
|
+
},
|
|
1618
|
+
// executeMultiple — delegate to fallback (used only for schema migrations)
|
|
1619
|
+
async executeMultiple(sql) {
|
|
1620
|
+
return fallbackClient.executeMultiple(sql);
|
|
1621
|
+
},
|
|
1622
|
+
// migrate — delegate to fallback
|
|
1623
|
+
async migrate(stmts) {
|
|
1624
|
+
return fallbackClient.migrate(stmts);
|
|
1625
|
+
},
|
|
1626
|
+
// Sync mode — delegate to fallback
|
|
1627
|
+
sync() {
|
|
1628
|
+
return fallbackClient.sync();
|
|
1629
|
+
},
|
|
1630
|
+
close() {
|
|
1631
|
+
_useDaemon = false;
|
|
1632
|
+
},
|
|
1633
|
+
get closed() {
|
|
1634
|
+
return fallbackClient.closed;
|
|
1635
|
+
},
|
|
1636
|
+
get protocol() {
|
|
1637
|
+
return fallbackClient.protocol;
|
|
1638
|
+
}
|
|
1639
|
+
};
|
|
1640
|
+
return {
|
|
1641
|
+
...client,
|
|
1642
|
+
/** Enable daemon routing (call after confirming daemon is connected) */
|
|
1643
|
+
_enableDaemon() {
|
|
1644
|
+
_useDaemon = true;
|
|
1645
|
+
},
|
|
1646
|
+
/** Check if daemon routing is active */
|
|
1647
|
+
_isDaemonActive() {
|
|
1648
|
+
return _useDaemon && isClientConnected();
|
|
1649
|
+
}
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
async function initDaemonDbClient(fallbackClient) {
|
|
1653
|
+
if (process.env.EXE_IS_DAEMON === "1") return null;
|
|
1654
|
+
const connected = await connectEmbedDaemon();
|
|
1655
|
+
if (!connected) {
|
|
1656
|
+
process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
|
|
1657
|
+
return null;
|
|
1658
|
+
}
|
|
1659
|
+
const client = createDaemonDbClient(fallbackClient);
|
|
1660
|
+
client._enableDaemon();
|
|
1661
|
+
process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
|
|
1662
|
+
return client;
|
|
1663
|
+
}
|
|
1664
|
+
var init_db_daemon_client = __esm({
|
|
1665
|
+
"src/lib/db-daemon-client.ts"() {
|
|
1666
|
+
"use strict";
|
|
1667
|
+
init_exe_daemon_client();
|
|
1668
|
+
init_daemon_protocol();
|
|
1669
|
+
}
|
|
1670
|
+
});
|
|
1671
|
+
|
|
1672
|
+
// src/lib/database.ts
|
|
1673
|
+
var database_exports = {};
|
|
1674
|
+
__export(database_exports, {
|
|
1675
|
+
disposeDatabase: () => disposeDatabase,
|
|
1676
|
+
disposeTurso: () => disposeTurso,
|
|
1677
|
+
ensureSchema: () => ensureSchema,
|
|
1678
|
+
getClient: () => getClient,
|
|
1679
|
+
getRawClient: () => getRawClient,
|
|
1680
|
+
initDaemonClient: () => initDaemonClient,
|
|
1681
|
+
initDatabase: () => initDatabase,
|
|
1682
|
+
initTurso: () => initTurso,
|
|
1683
|
+
isInitialized: () => isInitialized
|
|
1684
|
+
});
|
|
1685
|
+
import { createClient } from "@libsql/client";
|
|
1686
|
+
async function initDatabase(config) {
|
|
1687
|
+
if (_walCheckpointTimer) {
|
|
1688
|
+
clearInterval(_walCheckpointTimer);
|
|
1689
|
+
_walCheckpointTimer = null;
|
|
1690
|
+
}
|
|
1691
|
+
if (_daemonClient) {
|
|
1692
|
+
_daemonClient.close();
|
|
1693
|
+
_daemonClient = null;
|
|
1694
|
+
}
|
|
1695
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
1696
|
+
_adapterClient.close();
|
|
1697
|
+
}
|
|
1698
|
+
_adapterClient = null;
|
|
1699
|
+
if (_client) {
|
|
1700
|
+
_client.close();
|
|
1701
|
+
_client = null;
|
|
1702
|
+
_resilientClient = null;
|
|
1703
|
+
}
|
|
1704
|
+
const opts = {
|
|
1705
|
+
url: `file:${config.dbPath}`
|
|
1706
|
+
};
|
|
1707
|
+
if (config.encryptionKey) {
|
|
1708
|
+
opts.encryptionKey = config.encryptionKey;
|
|
1709
|
+
}
|
|
1710
|
+
_client = createClient(opts);
|
|
1711
|
+
_resilientClient = wrapWithRetry(_client);
|
|
1712
|
+
_adapterClient = _resilientClient;
|
|
1713
|
+
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
1714
|
+
});
|
|
1715
|
+
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
1716
|
+
});
|
|
1717
|
+
if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
|
|
1718
|
+
_walCheckpointTimer = setInterval(() => {
|
|
1719
|
+
_client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
|
|
1720
|
+
});
|
|
1721
|
+
}, 3e4);
|
|
1722
|
+
_walCheckpointTimer.unref();
|
|
1723
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
|
|
1724
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
function isInitialized() {
|
|
1728
|
+
return _adapterClient !== null || _client !== null;
|
|
1729
|
+
}
|
|
1730
|
+
function getClient() {
|
|
1731
|
+
if (!_adapterClient) {
|
|
1732
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
1733
|
+
}
|
|
1734
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
|
|
1735
|
+
return _adapterClient;
|
|
1736
|
+
}
|
|
1737
|
+
if (process.env.EXE_IS_DAEMON === "1") {
|
|
1738
|
+
return _resilientClient;
|
|
1739
|
+
}
|
|
1740
|
+
if (_daemonClient && _daemonClient._isDaemonActive()) {
|
|
1741
|
+
return _daemonClient;
|
|
1742
|
+
}
|
|
1743
|
+
return _resilientClient;
|
|
1744
|
+
}
|
|
1745
|
+
async function initDaemonClient() {
|
|
1746
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
|
|
1747
|
+
if (process.env.EXE_IS_DAEMON === "1") return;
|
|
1748
|
+
if (process.env.VITEST) return;
|
|
1749
|
+
if (!_resilientClient) return;
|
|
1750
|
+
if (_daemonClient) return;
|
|
1751
|
+
try {
|
|
1752
|
+
const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
|
|
1753
|
+
_daemonClient = await initDaemonDbClient2(_resilientClient);
|
|
1754
|
+
} catch (err) {
|
|
1755
|
+
process.stderr.write(
|
|
1756
|
+
`[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
|
|
1757
|
+
`
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
function getRawClient() {
|
|
1762
|
+
if (!_client) {
|
|
1763
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
1764
|
+
}
|
|
1765
|
+
return _client;
|
|
1766
|
+
}
|
|
1767
|
+
async function ensureSchema() {
|
|
1768
|
+
const client = getRawClient();
|
|
1769
|
+
await client.execute("PRAGMA journal_mode = WAL");
|
|
1770
|
+
await client.execute("PRAGMA busy_timeout = 30000");
|
|
1771
|
+
await client.execute("PRAGMA wal_autocheckpoint = 1000");
|
|
1772
|
+
try {
|
|
1773
|
+
await client.execute("PRAGMA libsql_vector_search_ef = 128");
|
|
1774
|
+
} catch {
|
|
1775
|
+
}
|
|
1776
|
+
await client.executeMultiple(`
|
|
1777
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
1778
|
+
id TEXT PRIMARY KEY,
|
|
1779
|
+
agent_id TEXT NOT NULL,
|
|
1780
|
+
agent_role TEXT NOT NULL,
|
|
1781
|
+
session_id TEXT NOT NULL,
|
|
1782
|
+
timestamp TEXT NOT NULL,
|
|
1783
|
+
tool_name TEXT NOT NULL,
|
|
1784
|
+
project_name TEXT NOT NULL,
|
|
1785
|
+
has_error INTEGER NOT NULL DEFAULT 0,
|
|
1786
|
+
raw_text TEXT NOT NULL,
|
|
1787
|
+
vector F32_BLOB(1024),
|
|
1788
|
+
version INTEGER NOT NULL DEFAULT 0
|
|
1789
|
+
);
|
|
1790
|
+
|
|
1791
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent
|
|
1792
|
+
ON memories(agent_id);
|
|
1793
|
+
|
|
1794
|
+
CREATE INDEX IF NOT EXISTS idx_memories_timestamp
|
|
1795
|
+
ON memories(timestamp);
|
|
1796
|
+
|
|
1797
|
+
CREATE INDEX IF NOT EXISTS idx_memories_session
|
|
1798
|
+
ON memories(session_id);
|
|
1799
|
+
|
|
1800
|
+
CREATE INDEX IF NOT EXISTS idx_memories_project
|
|
1801
|
+
ON memories(project_name);
|
|
1802
|
+
|
|
1803
|
+
CREATE INDEX IF NOT EXISTS idx_memories_tool
|
|
1804
|
+
ON memories(tool_name);
|
|
1805
|
+
|
|
1806
|
+
CREATE INDEX IF NOT EXISTS idx_memories_version
|
|
1807
|
+
ON memories(version);
|
|
1808
|
+
|
|
1809
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
1810
|
+
ON memories(agent_id, project_name);
|
|
1811
|
+
`);
|
|
1812
|
+
await client.executeMultiple(`
|
|
1813
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
1814
|
+
raw_text,
|
|
1815
|
+
content='memories',
|
|
1816
|
+
content_rowid='rowid'
|
|
1817
|
+
);
|
|
1818
|
+
|
|
1819
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
1820
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1821
|
+
END;
|
|
1822
|
+
|
|
1823
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
1824
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1825
|
+
END;
|
|
1826
|
+
|
|
1827
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
1828
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1829
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1830
|
+
END;
|
|
1831
|
+
`);
|
|
1832
|
+
await client.executeMultiple(`
|
|
1833
|
+
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
1834
|
+
key TEXT PRIMARY KEY,
|
|
1835
|
+
value TEXT NOT NULL
|
|
1836
|
+
);
|
|
1837
|
+
`);
|
|
1838
|
+
await client.executeMultiple(`
|
|
1839
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
1840
|
+
id TEXT PRIMARY KEY,
|
|
1841
|
+
title TEXT NOT NULL,
|
|
1842
|
+
assigned_to TEXT NOT NULL,
|
|
1843
|
+
assigned_by TEXT NOT NULL,
|
|
1844
|
+
project_name TEXT NOT NULL,
|
|
1845
|
+
priority TEXT NOT NULL DEFAULT 'p1',
|
|
1846
|
+
status TEXT NOT NULL DEFAULT 'open',
|
|
1847
|
+
task_file TEXT,
|
|
1848
|
+
created_at TEXT NOT NULL,
|
|
1849
|
+
updated_at TEXT NOT NULL
|
|
1850
|
+
);
|
|
1851
|
+
|
|
1852
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
1853
|
+
ON tasks(assigned_to, status);
|
|
1854
|
+
`);
|
|
1855
|
+
await client.executeMultiple(`
|
|
1856
|
+
CREATE TABLE IF NOT EXISTS behaviors (
|
|
1857
|
+
id TEXT PRIMARY KEY,
|
|
1858
|
+
agent_id TEXT NOT NULL,
|
|
1859
|
+
project_name TEXT,
|
|
1860
|
+
domain TEXT,
|
|
1861
|
+
content TEXT NOT NULL,
|
|
1862
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1863
|
+
created_at TEXT NOT NULL,
|
|
1864
|
+
updated_at TEXT NOT NULL
|
|
1865
|
+
);
|
|
1866
|
+
|
|
1867
|
+
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
1868
|
+
ON behaviors(agent_id, active);
|
|
1869
|
+
`);
|
|
1870
|
+
try {
|
|
1871
|
+
const coordinatorName = getCoordinatorName();
|
|
1872
|
+
const existing = await client.execute({
|
|
1873
|
+
sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
|
|
1874
|
+
args: [coordinatorName]
|
|
1875
|
+
});
|
|
1876
|
+
if (Number(existing.rows[0]?.cnt) === 0) {
|
|
1877
|
+
const seededAt = "2026-03-25T00:00:00Z";
|
|
1878
|
+
for (const [domain, content] of [
|
|
1879
|
+
["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
|
|
1880
|
+
["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
|
|
1881
|
+
["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
|
|
1882
|
+
]) {
|
|
1883
|
+
await client.execute({
|
|
1884
|
+
sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
1885
|
+
VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
|
|
1886
|
+
args: [coordinatorName, domain, content, seededAt, seededAt]
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
} catch {
|
|
1891
|
+
}
|
|
1892
|
+
try {
|
|
1893
|
+
await client.execute({
|
|
1894
|
+
sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
|
|
1895
|
+
args: []
|
|
1896
|
+
});
|
|
1897
|
+
} catch {
|
|
1898
|
+
}
|
|
1899
|
+
try {
|
|
1900
|
+
await client.execute({
|
|
1901
|
+
sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
|
|
1902
|
+
args: []
|
|
1903
|
+
});
|
|
1904
|
+
} catch {
|
|
1905
|
+
}
|
|
1906
|
+
try {
|
|
1907
|
+
await client.execute({
|
|
1908
|
+
sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
|
|
1909
|
+
args: []
|
|
1910
|
+
});
|
|
1111
1911
|
} catch {
|
|
1112
1912
|
}
|
|
1113
1913
|
try {
|
|
@@ -1947,19 +2747,97 @@ async function ensureSchema() {
|
|
|
1947
2747
|
} catch {
|
|
1948
2748
|
}
|
|
1949
2749
|
}
|
|
1950
|
-
|
|
2750
|
+
async function disposeDatabase() {
|
|
2751
|
+
if (_walCheckpointTimer) {
|
|
2752
|
+
clearInterval(_walCheckpointTimer);
|
|
2753
|
+
_walCheckpointTimer = null;
|
|
2754
|
+
}
|
|
2755
|
+
if (_daemonClient) {
|
|
2756
|
+
_daemonClient.close();
|
|
2757
|
+
_daemonClient = null;
|
|
2758
|
+
}
|
|
2759
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
2760
|
+
_adapterClient.close();
|
|
2761
|
+
}
|
|
2762
|
+
_adapterClient = null;
|
|
2763
|
+
if (_client) {
|
|
2764
|
+
_client.close();
|
|
2765
|
+
_client = null;
|
|
2766
|
+
_resilientClient = null;
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
|
|
1951
2770
|
var init_database = __esm({
|
|
1952
2771
|
"src/lib/database.ts"() {
|
|
1953
2772
|
"use strict";
|
|
1954
2773
|
init_db_retry();
|
|
1955
2774
|
init_employees();
|
|
1956
2775
|
init_database_adapter();
|
|
2776
|
+
init_memory();
|
|
1957
2777
|
_client = null;
|
|
1958
2778
|
_resilientClient = null;
|
|
1959
2779
|
_walCheckpointTimer = null;
|
|
1960
2780
|
_daemonClient = null;
|
|
1961
2781
|
_adapterClient = null;
|
|
1962
2782
|
initTurso = initDatabase;
|
|
2783
|
+
disposeTurso = disposeDatabase;
|
|
2784
|
+
}
|
|
2785
|
+
});
|
|
2786
|
+
|
|
2787
|
+
// src/lib/keychain.ts
|
|
2788
|
+
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2789
|
+
import { existsSync as existsSync6 } from "fs";
|
|
2790
|
+
import path6 from "path";
|
|
2791
|
+
import os5 from "os";
|
|
2792
|
+
function getKeyDir() {
|
|
2793
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
|
|
2794
|
+
}
|
|
2795
|
+
function getKeyPath() {
|
|
2796
|
+
return path6.join(getKeyDir(), "master.key");
|
|
2797
|
+
}
|
|
2798
|
+
async function tryKeytar() {
|
|
2799
|
+
try {
|
|
2800
|
+
return await import("keytar");
|
|
2801
|
+
} catch {
|
|
2802
|
+
return null;
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
async function getMasterKey() {
|
|
2806
|
+
const keytar = await tryKeytar();
|
|
2807
|
+
if (keytar) {
|
|
2808
|
+
try {
|
|
2809
|
+
const stored = await keytar.getPassword(SERVICE, ACCOUNT);
|
|
2810
|
+
if (stored) {
|
|
2811
|
+
return Buffer.from(stored, "base64");
|
|
2812
|
+
}
|
|
2813
|
+
} catch {
|
|
2814
|
+
}
|
|
2815
|
+
}
|
|
2816
|
+
const keyPath = getKeyPath();
|
|
2817
|
+
if (!existsSync6(keyPath)) {
|
|
2818
|
+
process.stderr.write(
|
|
2819
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2820
|
+
`
|
|
2821
|
+
);
|
|
2822
|
+
return null;
|
|
2823
|
+
}
|
|
2824
|
+
try {
|
|
2825
|
+
const content = await readFile3(keyPath, "utf-8");
|
|
2826
|
+
return Buffer.from(content.trim(), "base64");
|
|
2827
|
+
} catch (err) {
|
|
2828
|
+
process.stderr.write(
|
|
2829
|
+
`[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
|
|
2830
|
+
`
|
|
2831
|
+
);
|
|
2832
|
+
return null;
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
var SERVICE, ACCOUNT;
|
|
2836
|
+
var init_keychain = __esm({
|
|
2837
|
+
"src/lib/keychain.ts"() {
|
|
2838
|
+
"use strict";
|
|
2839
|
+
SERVICE = "exe-mem";
|
|
2840
|
+
ACCOUNT = "master-key";
|
|
1963
2841
|
}
|
|
1964
2842
|
});
|
|
1965
2843
|
|
|
@@ -2032,12 +2910,12 @@ __export(shard_manager_exports, {
|
|
|
2032
2910
|
listShards: () => listShards,
|
|
2033
2911
|
shardExists: () => shardExists
|
|
2034
2912
|
});
|
|
2035
|
-
import
|
|
2036
|
-
import { existsSync as
|
|
2913
|
+
import path7 from "path";
|
|
2914
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
|
|
2037
2915
|
import { createClient as createClient2 } from "@libsql/client";
|
|
2038
2916
|
function initShardManager(encryptionKey) {
|
|
2039
2917
|
_encryptionKey = encryptionKey;
|
|
2040
|
-
if (!
|
|
2918
|
+
if (!existsSync7(SHARDS_DIR)) {
|
|
2041
2919
|
mkdirSync2(SHARDS_DIR, { recursive: true });
|
|
2042
2920
|
}
|
|
2043
2921
|
_shardingEnabled = true;
|
|
@@ -2067,7 +2945,7 @@ function getShardClient(projectName) {
|
|
|
2067
2945
|
while (_shards.size >= MAX_OPEN_SHARDS) {
|
|
2068
2946
|
evictLRU();
|
|
2069
2947
|
}
|
|
2070
|
-
const dbPath =
|
|
2948
|
+
const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
|
|
2071
2949
|
const client = createClient2({
|
|
2072
2950
|
url: `file:${dbPath}`,
|
|
2073
2951
|
encryptionKey: _encryptionKey
|
|
@@ -2078,10 +2956,10 @@ function getShardClient(projectName) {
|
|
|
2078
2956
|
}
|
|
2079
2957
|
function shardExists(projectName) {
|
|
2080
2958
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
2081
|
-
return
|
|
2959
|
+
return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
|
|
2082
2960
|
}
|
|
2083
2961
|
function listShards() {
|
|
2084
|
-
if (!
|
|
2962
|
+
if (!existsSync7(SHARDS_DIR)) return [];
|
|
2085
2963
|
return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
2086
2964
|
}
|
|
2087
2965
|
async function ensureShardSchema(client) {
|
|
@@ -2328,7 +3206,7 @@ var init_shard_manager = __esm({
|
|
|
2328
3206
|
"src/lib/shard-manager.ts"() {
|
|
2329
3207
|
"use strict";
|
|
2330
3208
|
init_config();
|
|
2331
|
-
SHARDS_DIR =
|
|
3209
|
+
SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
|
|
2332
3210
|
SHARD_IDLE_MS = 5 * 60 * 1e3;
|
|
2333
3211
|
MAX_OPEN_SHARDS = 10;
|
|
2334
3212
|
EVICTION_INTERVAL_MS = 60 * 1e3;
|
|
@@ -2448,93 +3326,743 @@ var init_platform_procedures = __esm({
|
|
|
2448
3326
|
domain: "architecture",
|
|
2449
3327
|
priority: "p0",
|
|
2450
3328
|
content: "Tasks live in the DB. Intercom (tmux send-keys) is fire-and-forget \u2014 it may fail, get garbled, or arrive mid-work. Never rely on intercom for task delivery. The UserPromptSubmit hook checks the DB for new tasks on every prompt. Your operating procedures step 7 says check for next work. The daemon nudges idle agents as a speedup. If you have no tasks, you found them all."
|
|
3329
|
+
},
|
|
3330
|
+
// --- MCP is the ONLY data interface ---
|
|
3331
|
+
{
|
|
3332
|
+
title: "MCP disconnect \u2014 ask the user, never work around it",
|
|
3333
|
+
domain: "workflow",
|
|
3334
|
+
priority: "p0",
|
|
3335
|
+
content: "If MCP tools are unavailable, disconnected, or returning connection errors: STOP. Tell the user clearly: 'MCP server is disconnected. Please run /mcp to reconnect.' Do NOT attempt workarounds \u2014 no raw Node imports, no direct DB access, no CLI hacks, no daemon socket calls. MCP is the ONLY data interface. Working around it wastes time, hits bundling issues, and bypasses the contract boundary. Ask once, wait, proceed when reconnected."
|
|
3336
|
+
},
|
|
3337
|
+
// --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
|
|
3338
|
+
{
|
|
3339
|
+
title: "MCP tools \u2014 memory and search",
|
|
3340
|
+
domain: "tool-use",
|
|
3341
|
+
priority: "p1",
|
|
3342
|
+
content: "recall_my_memory: search your own memories (semantic + FTS). ask_team_memory: search a colleague's memories by agent name. store_memory: persist a memory (decisions, summaries, context). commit_memory: high-importance memory that survives consolidation. search_everything: unified search across memories, tasks, entities, conversations. get_session_context: temporal window of memories around a timestamp. consolidate_memories: merge duplicate/related memories into insights. get_memory_cardinality: count memories per agent (health check)."
|
|
3343
|
+
},
|
|
3344
|
+
{
|
|
3345
|
+
title: "MCP tools \u2014 task orchestration",
|
|
3346
|
+
domain: "tool-use",
|
|
3347
|
+
priority: "p1",
|
|
3348
|
+
content: "create_task: dispatch work to an employee (auto-spawns session). The ONLY dispatch path. list_tasks: query tasks by status, assignee, project. get_task: fetch full task details by ID. update_task: change status (in_progress, done, blocked, cancelled) + add result summary. close_task: finalize a reviewed task (COO only). checkpoint_task: save progress state for crash recovery. resume_employee: re-spawn an employee session for an existing task."
|
|
3349
|
+
},
|
|
3350
|
+
{
|
|
3351
|
+
title: "MCP tools \u2014 knowledge graph (GraphRAG)",
|
|
3352
|
+
domain: "tool-use",
|
|
3353
|
+
priority: "p1",
|
|
3354
|
+
content: "query_relationships: find connections between entities in the knowledge graph. get_entity_neighbors: explore an entity's direct connections. get_hot_entities: find most-referenced entities (trending topics). get_graph_stats: graph health \u2014 entity/relationship counts, density. export_graph: export graph data for visualization. merge_entities: deduplicate entities (alias resolution). find_similar_trajectories: match tool-call patterns to past task solutions."
|
|
3355
|
+
},
|
|
3356
|
+
{
|
|
3357
|
+
title: "MCP tools \u2014 identity, behavior, and decisions",
|
|
3358
|
+
domain: "tool-use",
|
|
3359
|
+
priority: "p1",
|
|
3360
|
+
content: "get_identity: read an agent's exe.md (Layer 1 identity). update_identity: write an agent's exe.md. Identity > behavior \u2014 use for permanent rules. store_behavior: record a correction or pattern for an agent (Layer 2 expertise). list_behaviors: view an agent's active behaviors. deactivate_behavior: soft-delete a stale or conflicting behavior. store_decision: record an ADR (architectural decision record). get_decision: retrieve a past decision by query."
|
|
3361
|
+
},
|
|
3362
|
+
{
|
|
3363
|
+
title: "MCP tools \u2014 communication and messaging",
|
|
3364
|
+
domain: "tool-use",
|
|
3365
|
+
priority: "p1",
|
|
3366
|
+
content: "send_message: send supplementary context to another agent (NOT for actionable work \u2014 use create_task). acknowledge_messages: mark messages as read. send_whatsapp: send WhatsApp message via gateway (customer-facing alerts). query_conversations: search ingested conversations across all channels (WhatsApp, email, etc.)."
|
|
3367
|
+
},
|
|
3368
|
+
{
|
|
3369
|
+
title: "MCP tools \u2014 wiki, documents, and content",
|
|
3370
|
+
domain: "tool-use",
|
|
3371
|
+
priority: "p1",
|
|
3372
|
+
content: "create_wiki_page: create a wiki page in exe-wiki. list_wiki_pages: browse wiki pages. get_wiki_page: read a wiki page. update_wiki_page: edit a wiki page. ingest_document: import a file (PDF, MD, etc.) into memory as chunks. list_documents: browse ingested documents by workspace. purge_document: remove a document and its memory chunks. set_document_importance: adjust chunk importance scores. rerank_documents: re-score document relevance for a query."
|
|
3373
|
+
},
|
|
3374
|
+
{
|
|
3375
|
+
title: "MCP tools \u2014 system, operations, and admin",
|
|
3376
|
+
domain: "tool-use",
|
|
3377
|
+
priority: "p1",
|
|
3378
|
+
content: "get_agent_spend: token usage per agent/session (cost tracking). list_agent_sessions: view agent session history. get_session_kills: audit log of killed sessions. get_daemon_health: check exed daemon status. get_auto_wake_status: daemon auto-wake configuration. get_worker_gate: check worker deployment gates. run_memory_audit: health check \u2014 duplicates, null vectors, orphaned rows. run_consolidation: trigger sleep-time memory consolidation. cloud_sync: force a cloud sync cycle. backup_vps: trigger VPS backup."
|
|
3379
|
+
},
|
|
3380
|
+
{
|
|
3381
|
+
title: "MCP tools \u2014 config, licensing, and team",
|
|
3382
|
+
domain: "tool-use",
|
|
3383
|
+
priority: "p1",
|
|
3384
|
+
content: "set_agent_config: view/change per-agent runtime and model settings. list_employees: view the employee roster. add_person: add a person to the CRM contacts roster. list_people: browse CRM contacts. get_person: fetch contact details. get_license_status: check license validity. create_license: generate a new license key (admin). list_licenses: view all issued licenses. activate_license: activate a license on a device."
|
|
3385
|
+
},
|
|
3386
|
+
{
|
|
3387
|
+
title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
|
|
3388
|
+
domain: "tool-use",
|
|
3389
|
+
priority: "p1",
|
|
3390
|
+
content: "create_trigger: set up a scheduled recurring agent job (cron). list_triggers: view active triggers. load_skill: load a slash-command skill dynamically. apply_starter_pack: import a pre-built behavior + identity pack for a role. export_orchestration: export full org state (tasks, behaviors, identities) as portable JSON. import_orchestration: import org state into a new instance. deploy_client: deploy a customer client instance. query_company_brain: unified RAG query across all company knowledge. create_reminder: set a text reminder (shown in boot brief). list_reminders: view pending reminders. complete_reminder: mark a reminder done. global_procedure: manage Layer 0 procedures (actions: store, list, deactivate). Legacy aliases: store_global_procedure, list_global_procedures, deactivate_global_procedure."
|
|
3391
|
+
}
|
|
3392
|
+
];
|
|
3393
|
+
PLATFORM_PROCEDURE_TITLES = new Set(
|
|
3394
|
+
PLATFORM_PROCEDURES.map((p) => p.title)
|
|
3395
|
+
);
|
|
3396
|
+
}
|
|
3397
|
+
});
|
|
3398
|
+
|
|
3399
|
+
// src/lib/global-procedures.ts
|
|
3400
|
+
var global_procedures_exports = {};
|
|
3401
|
+
__export(global_procedures_exports, {
|
|
3402
|
+
deactivateGlobalProcedure: () => deactivateGlobalProcedure,
|
|
3403
|
+
getGlobalProceduresBlock: () => getGlobalProceduresBlock,
|
|
3404
|
+
loadGlobalProcedures: () => loadGlobalProcedures,
|
|
3405
|
+
storeGlobalProcedure: () => storeGlobalProcedure
|
|
3406
|
+
});
|
|
3407
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
3408
|
+
async function loadGlobalProcedures() {
|
|
3409
|
+
const client = getClient();
|
|
3410
|
+
const result = await client.execute({
|
|
3411
|
+
sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
|
|
3412
|
+
args: []
|
|
3413
|
+
});
|
|
3414
|
+
const allRows = result.rows;
|
|
3415
|
+
const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
|
|
3416
|
+
if (customerOnly.length > 0) {
|
|
3417
|
+
_customerCache = customerOnly.map((p) => `### ${p.title}
|
|
3418
|
+
${p.content}`).join("\n\n");
|
|
3419
|
+
} else {
|
|
3420
|
+
_customerCache = "";
|
|
3421
|
+
}
|
|
3422
|
+
_cacheLoaded = true;
|
|
3423
|
+
return customerOnly;
|
|
3424
|
+
}
|
|
3425
|
+
function getGlobalProceduresBlock() {
|
|
3426
|
+
const sections = [];
|
|
3427
|
+
if (_platformCache) sections.push(_platformCache);
|
|
3428
|
+
if (_cacheLoaded && _customerCache) sections.push(_customerCache);
|
|
3429
|
+
if (sections.length === 0) return "";
|
|
3430
|
+
return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
|
|
3431
|
+
|
|
3432
|
+
${sections.join("\n\n")}
|
|
3433
|
+
`;
|
|
3434
|
+
}
|
|
3435
|
+
async function storeGlobalProcedure(input) {
|
|
3436
|
+
const id = randomUUID2();
|
|
3437
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3438
|
+
const client = getClient();
|
|
3439
|
+
await client.execute({
|
|
3440
|
+
sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
|
|
3441
|
+
VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
|
|
3442
|
+
args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
|
|
3443
|
+
});
|
|
3444
|
+
await loadGlobalProcedures();
|
|
3445
|
+
return id;
|
|
3446
|
+
}
|
|
3447
|
+
async function deactivateGlobalProcedure(id) {
|
|
3448
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3449
|
+
const client = getClient();
|
|
3450
|
+
const result = await client.execute({
|
|
3451
|
+
sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
|
|
3452
|
+
args: [now, id]
|
|
3453
|
+
});
|
|
3454
|
+
await loadGlobalProcedures();
|
|
3455
|
+
return result.rowsAffected > 0;
|
|
3456
|
+
}
|
|
3457
|
+
var _customerCache, _cacheLoaded, _platformCache;
|
|
3458
|
+
var init_global_procedures = __esm({
|
|
3459
|
+
"src/lib/global-procedures.ts"() {
|
|
3460
|
+
"use strict";
|
|
3461
|
+
init_database();
|
|
3462
|
+
init_platform_procedures();
|
|
3463
|
+
_customerCache = "";
|
|
3464
|
+
_cacheLoaded = false;
|
|
3465
|
+
_platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
|
|
3466
|
+
${p.content}`).join("\n\n");
|
|
3467
|
+
}
|
|
3468
|
+
});
|
|
3469
|
+
|
|
3470
|
+
// src/lib/store.ts
|
|
3471
|
+
var store_exports = {};
|
|
3472
|
+
__export(store_exports, {
|
|
3473
|
+
attachDocumentMetadata: () => attachDocumentMetadata,
|
|
3474
|
+
buildRawVisibilityFilter: () => buildRawVisibilityFilter,
|
|
3475
|
+
buildWikiScopeFilter: () => buildWikiScopeFilter,
|
|
3476
|
+
classifyTier: () => classifyTier,
|
|
3477
|
+
disposeStore: () => disposeStore,
|
|
3478
|
+
flushBatch: () => flushBatch,
|
|
3479
|
+
flushTier3: () => flushTier3,
|
|
3480
|
+
getMemoryCardinality: () => getMemoryCardinality,
|
|
3481
|
+
initStore: () => initStore,
|
|
3482
|
+
reserveVersions: () => reserveVersions,
|
|
3483
|
+
searchMemories: () => searchMemories,
|
|
3484
|
+
updateMemoryStatus: () => updateMemoryStatus,
|
|
3485
|
+
vectorToBlob: () => vectorToBlob,
|
|
3486
|
+
writeMemory: () => writeMemory
|
|
3487
|
+
});
|
|
3488
|
+
import { createHash } from "crypto";
|
|
3489
|
+
function isBusyError2(err) {
|
|
3490
|
+
if (err instanceof Error) {
|
|
3491
|
+
const msg = err.message.toLowerCase();
|
|
3492
|
+
return msg.includes("sqlite_busy") || msg.includes("database is locked");
|
|
3493
|
+
}
|
|
3494
|
+
return false;
|
|
3495
|
+
}
|
|
3496
|
+
async function retryOnBusy2(fn, label) {
|
|
3497
|
+
for (let attempt = 0; attempt <= INIT_MAX_RETRIES; attempt++) {
|
|
3498
|
+
try {
|
|
3499
|
+
return await fn();
|
|
3500
|
+
} catch (err) {
|
|
3501
|
+
if (!isBusyError2(err) || attempt === INIT_MAX_RETRIES) throw err;
|
|
3502
|
+
process.stderr.write(
|
|
3503
|
+
`[store] SQLITE_BUSY during ${label}, retry ${attempt + 1}/${INIT_MAX_RETRIES}
|
|
3504
|
+
`
|
|
3505
|
+
);
|
|
3506
|
+
await new Promise((r) => setTimeout(r, INIT_RETRY_DELAY_MS * (attempt + 1)));
|
|
3507
|
+
}
|
|
3508
|
+
}
|
|
3509
|
+
throw new Error("unreachable");
|
|
3510
|
+
}
|
|
3511
|
+
async function initStore(options) {
|
|
3512
|
+
if (_flushTimer !== null) {
|
|
3513
|
+
clearInterval(_flushTimer);
|
|
3514
|
+
_flushTimer = null;
|
|
3515
|
+
}
|
|
3516
|
+
_pendingRecords = [];
|
|
3517
|
+
_flushing = false;
|
|
3518
|
+
_batchSize = options?.batchSize ?? 20;
|
|
3519
|
+
_flushIntervalMs = options?.flushIntervalMs ?? 1e4;
|
|
3520
|
+
let dbPath = options?.dbPath;
|
|
3521
|
+
if (!dbPath) {
|
|
3522
|
+
const config = await loadConfig();
|
|
3523
|
+
dbPath = config.dbPath;
|
|
3524
|
+
}
|
|
3525
|
+
let masterKey = options?.masterKey ?? null;
|
|
3526
|
+
if (!masterKey) {
|
|
3527
|
+
masterKey = await getMasterKey();
|
|
3528
|
+
if (!masterKey) {
|
|
3529
|
+
throw new Error(
|
|
3530
|
+
"No encryption key found. Run /exe-setup to generate one."
|
|
3531
|
+
);
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
const hexKey = masterKey.toString("hex");
|
|
3535
|
+
await initTurso({
|
|
3536
|
+
dbPath,
|
|
3537
|
+
encryptionKey: hexKey
|
|
3538
|
+
});
|
|
3539
|
+
await retryOnBusy2(() => ensureSchema(), "ensureSchema");
|
|
3540
|
+
try {
|
|
3541
|
+
const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
|
|
3542
|
+
await initDaemonClient2();
|
|
3543
|
+
} catch {
|
|
3544
|
+
}
|
|
3545
|
+
if (!options?.lightweight) {
|
|
3546
|
+
try {
|
|
3547
|
+
const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
3548
|
+
initShardManager2(hexKey);
|
|
3549
|
+
} catch {
|
|
3550
|
+
}
|
|
3551
|
+
const client = getClient();
|
|
3552
|
+
const vResult = await retryOnBusy2(
|
|
3553
|
+
() => client.execute("SELECT MAX(version) as max_v FROM memories"),
|
|
3554
|
+
"version-query"
|
|
3555
|
+
);
|
|
3556
|
+
_nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
|
|
3557
|
+
try {
|
|
3558
|
+
const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
|
|
3559
|
+
await loadGlobalProcedures2();
|
|
3560
|
+
} catch {
|
|
3561
|
+
}
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
3564
|
+
function classifyTier(record) {
|
|
3565
|
+
if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
|
|
3566
|
+
if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
|
|
3567
|
+
return 3;
|
|
3568
|
+
}
|
|
3569
|
+
function inferFilePaths(record) {
|
|
3570
|
+
if (!["Read", "Write", "Edit"].includes(record.tool_name)) return null;
|
|
3571
|
+
const firstLine = record.raw_text.split("\n")[0] ?? "";
|
|
3572
|
+
const match = firstLine.match(/(\/[\w./-]+\.\w+)/);
|
|
3573
|
+
return match ? JSON.stringify([match[1]]) : null;
|
|
3574
|
+
}
|
|
3575
|
+
function inferCommitHash(record) {
|
|
3576
|
+
if (record.tool_name !== "Bash") return null;
|
|
3577
|
+
const match = record.raw_text.match(/\b([a-f0-9]{7,40})\b/);
|
|
3578
|
+
return match ? match[1] : null;
|
|
3579
|
+
}
|
|
3580
|
+
function inferLanguageType(record) {
|
|
3581
|
+
const text = record.raw_text;
|
|
3582
|
+
if (!text || text.length < 10) return null;
|
|
3583
|
+
const trimmed = text.trimStart();
|
|
3584
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) return "json";
|
|
3585
|
+
if (/\b(SELECT|INSERT|UPDATE|DELETE|CREATE TABLE|ALTER TABLE)\b/i.test(text)) return "sql";
|
|
3586
|
+
if (/\b(function |const |import |export |class |def |async |=>)\b/.test(text)) return "code";
|
|
3587
|
+
if (trimmed.startsWith("#") || trimmed.startsWith("*")) return "prose";
|
|
3588
|
+
return "mixed";
|
|
3589
|
+
}
|
|
3590
|
+
function inferDomain(record) {
|
|
3591
|
+
const proj = (record.project_name ?? "").toLowerCase();
|
|
3592
|
+
if (proj.includes("marketing") || proj.includes("content")) return "marketing";
|
|
3593
|
+
if (proj.includes("crm") || proj.includes("customer")) return "customer";
|
|
3594
|
+
return null;
|
|
3595
|
+
}
|
|
3596
|
+
async function writeMemory(record) {
|
|
3597
|
+
if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
|
|
3598
|
+
throw new Error(
|
|
3599
|
+
`Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
|
|
3600
|
+
);
|
|
3601
|
+
}
|
|
3602
|
+
const contentHash = createHash("md5").update(record.raw_text).digest("hex");
|
|
3603
|
+
if (_pendingRecords.some((r) => r.content_hash === contentHash && r.agent_id === record.agent_id)) {
|
|
3604
|
+
return;
|
|
3605
|
+
}
|
|
3606
|
+
try {
|
|
3607
|
+
const client = getClient();
|
|
3608
|
+
const existing = await client.execute({
|
|
3609
|
+
sql: "SELECT id FROM memories WHERE content_hash = ? AND agent_id = ? LIMIT 1",
|
|
3610
|
+
args: [contentHash, record.agent_id]
|
|
3611
|
+
});
|
|
3612
|
+
if (existing.rows.length > 0) return;
|
|
3613
|
+
} catch {
|
|
3614
|
+
}
|
|
3615
|
+
const dbRow = {
|
|
3616
|
+
id: record.id,
|
|
3617
|
+
agent_id: record.agent_id,
|
|
3618
|
+
agent_role: record.agent_role,
|
|
3619
|
+
session_id: record.session_id,
|
|
3620
|
+
timestamp: record.timestamp,
|
|
3621
|
+
tool_name: record.tool_name,
|
|
3622
|
+
project_name: record.project_name,
|
|
3623
|
+
has_error: record.has_error ? 1 : 0,
|
|
3624
|
+
raw_text: record.raw_text,
|
|
3625
|
+
vector: record.vector,
|
|
3626
|
+
version: 0,
|
|
3627
|
+
// Placeholder — assigned atomically at flush time
|
|
3628
|
+
task_id: record.task_id ?? null,
|
|
3629
|
+
importance: record.importance ?? 5,
|
|
3630
|
+
status: record.status ?? "active",
|
|
3631
|
+
confidence: record.confidence ?? 0.7,
|
|
3632
|
+
last_accessed: record.last_accessed ?? record.timestamp,
|
|
3633
|
+
workspace_id: record.workspace_id ?? null,
|
|
3634
|
+
document_id: record.document_id ?? null,
|
|
3635
|
+
user_id: record.user_id ?? null,
|
|
3636
|
+
char_offset: record.char_offset ?? null,
|
|
3637
|
+
page_number: record.page_number ?? null,
|
|
3638
|
+
source_path: record.source_path ?? null,
|
|
3639
|
+
source_type: record.source_type ?? null,
|
|
3640
|
+
tier: record.tier ?? classifyTier(record),
|
|
3641
|
+
supersedes_id: record.supersedes_id ?? null,
|
|
3642
|
+
draft: record.draft ? 1 : 0,
|
|
3643
|
+
memory_type: record.memory_type ?? "raw",
|
|
3644
|
+
trajectory: record.trajectory ? JSON.stringify(record.trajectory) : null,
|
|
3645
|
+
content_hash: contentHash,
|
|
3646
|
+
intent: record.intent ?? null,
|
|
3647
|
+
outcome: record.outcome ?? null,
|
|
3648
|
+
domain: record.domain ?? inferDomain(record),
|
|
3649
|
+
referenced_entities: record.referenced_entities ?? null,
|
|
3650
|
+
retrieval_count: record.retrieval_count ?? 0,
|
|
3651
|
+
chain_position: record.chain_position ?? null,
|
|
3652
|
+
review_status: record.review_status ?? null,
|
|
3653
|
+
context_window_pct: record.context_window_pct ?? null,
|
|
3654
|
+
file_paths: record.file_paths ?? inferFilePaths(record),
|
|
3655
|
+
commit_hash: record.commit_hash ?? inferCommitHash(record),
|
|
3656
|
+
duration_ms: record.duration_ms ?? null,
|
|
3657
|
+
token_cost: record.token_cost ?? null,
|
|
3658
|
+
audience: record.audience ?? null,
|
|
3659
|
+
language_type: record.language_type ?? inferLanguageType(record),
|
|
3660
|
+
parent_memory_id: record.parent_memory_id ?? null
|
|
3661
|
+
};
|
|
3662
|
+
_pendingRecords.push(dbRow);
|
|
3663
|
+
orgBus.emit({
|
|
3664
|
+
type: "memory_stored",
|
|
3665
|
+
agentId: record.agent_id,
|
|
3666
|
+
project: record.project_name,
|
|
3667
|
+
timestamp: record.timestamp
|
|
3668
|
+
});
|
|
3669
|
+
const MAX_PENDING = 1e3;
|
|
3670
|
+
if (_pendingRecords.length > MAX_PENDING) {
|
|
3671
|
+
const dropped = _pendingRecords.length - MAX_PENDING;
|
|
3672
|
+
_pendingRecords = _pendingRecords.slice(-MAX_PENDING);
|
|
3673
|
+
console.warn(`[store] Dropped ${dropped} oldest pending records (overflow)`);
|
|
3674
|
+
}
|
|
3675
|
+
if (_flushTimer === null) {
|
|
3676
|
+
_flushTimer = setInterval(() => {
|
|
3677
|
+
void flushBatch();
|
|
3678
|
+
}, _flushIntervalMs);
|
|
3679
|
+
if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
|
|
3680
|
+
_flushTimer.unref();
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
if (_pendingRecords.length >= _batchSize) {
|
|
3684
|
+
await flushBatch();
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
async function flushBatch() {
|
|
3688
|
+
if (_flushing || _pendingRecords.length === 0) return 0;
|
|
3689
|
+
_flushing = true;
|
|
3690
|
+
try {
|
|
3691
|
+
const batch = _pendingRecords.slice(0);
|
|
3692
|
+
const client = getClient();
|
|
3693
|
+
const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
|
|
3694
|
+
let baseVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
|
|
3695
|
+
for (const row of batch) {
|
|
3696
|
+
row.version = baseVersion++;
|
|
3697
|
+
}
|
|
3698
|
+
_nextVersion = baseVersion;
|
|
3699
|
+
const buildStmt = (row) => {
|
|
3700
|
+
const hasVector = row.vector !== null;
|
|
3701
|
+
const taskId = row.task_id ?? null;
|
|
3702
|
+
const importance = row.importance ?? 5;
|
|
3703
|
+
const status = row.status ?? "active";
|
|
3704
|
+
const confidence = row.confidence ?? 0.7;
|
|
3705
|
+
const lastAccessed = row.last_accessed ?? row.timestamp;
|
|
3706
|
+
const workspaceId = row.workspace_id ?? null;
|
|
3707
|
+
const documentId = row.document_id ?? null;
|
|
3708
|
+
const userId = row.user_id ?? null;
|
|
3709
|
+
const charOffset = row.char_offset ?? null;
|
|
3710
|
+
const pageNumber = row.page_number ?? null;
|
|
3711
|
+
const sourcePath = row.source_path ?? null;
|
|
3712
|
+
const sourceType = row.source_type ?? null;
|
|
3713
|
+
const tier = row.tier ?? 3;
|
|
3714
|
+
const supersedesId = row.supersedes_id ?? null;
|
|
3715
|
+
const draft = row.draft ? 1 : 0;
|
|
3716
|
+
const memoryType = row.memory_type ?? "raw";
|
|
3717
|
+
const trajectory = row.trajectory ?? null;
|
|
3718
|
+
const contentHash = row.content_hash ?? null;
|
|
3719
|
+
const intent = row.intent ?? null;
|
|
3720
|
+
const outcome = row.outcome ?? null;
|
|
3721
|
+
const domain = row.domain ?? null;
|
|
3722
|
+
const referencedEntities = row.referenced_entities ?? null;
|
|
3723
|
+
const retrievalCount = row.retrieval_count ?? 0;
|
|
3724
|
+
const chainPosition = row.chain_position ?? null;
|
|
3725
|
+
const reviewStatus = row.review_status ?? null;
|
|
3726
|
+
const contextWindowPct = row.context_window_pct ?? null;
|
|
3727
|
+
const filePaths = row.file_paths ?? null;
|
|
3728
|
+
const commitHash = row.commit_hash ?? null;
|
|
3729
|
+
const durationMs = row.duration_ms ?? null;
|
|
3730
|
+
const tokenCost = row.token_cost ?? null;
|
|
3731
|
+
const audience = row.audience ?? null;
|
|
3732
|
+
const languageType = row.language_type ?? null;
|
|
3733
|
+
const parentMemoryId = row.parent_memory_id ?? null;
|
|
3734
|
+
const cols = `id, agent_id, agent_role, session_id, timestamp,
|
|
3735
|
+
tool_name, project_name,
|
|
3736
|
+
has_error, raw_text, vector, version, task_id, importance, status,
|
|
3737
|
+
confidence, last_accessed,
|
|
3738
|
+
workspace_id, document_id, user_id, char_offset, page_number,
|
|
3739
|
+
source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory, content_hash,
|
|
3740
|
+
intent, outcome, domain, referenced_entities, retrieval_count,
|
|
3741
|
+
chain_position, review_status, context_window_pct, file_paths, commit_hash,
|
|
3742
|
+
duration_ms, token_cost, audience, language_type, parent_memory_id`;
|
|
3743
|
+
const metaArgs = [
|
|
3744
|
+
intent,
|
|
3745
|
+
outcome,
|
|
3746
|
+
domain,
|
|
3747
|
+
referencedEntities,
|
|
3748
|
+
retrievalCount,
|
|
3749
|
+
chainPosition,
|
|
3750
|
+
reviewStatus,
|
|
3751
|
+
contextWindowPct,
|
|
3752
|
+
filePaths,
|
|
3753
|
+
commitHash,
|
|
3754
|
+
durationMs,
|
|
3755
|
+
tokenCost,
|
|
3756
|
+
audience,
|
|
3757
|
+
languageType,
|
|
3758
|
+
parentMemoryId
|
|
3759
|
+
];
|
|
3760
|
+
const baseArgs = [
|
|
3761
|
+
row.id,
|
|
3762
|
+
row.agent_id,
|
|
3763
|
+
row.agent_role,
|
|
3764
|
+
row.session_id,
|
|
3765
|
+
row.timestamp,
|
|
3766
|
+
row.tool_name,
|
|
3767
|
+
row.project_name,
|
|
3768
|
+
row.has_error,
|
|
3769
|
+
row.raw_text
|
|
3770
|
+
];
|
|
3771
|
+
const sharedArgs = [
|
|
3772
|
+
row.version,
|
|
3773
|
+
taskId,
|
|
3774
|
+
importance,
|
|
3775
|
+
status,
|
|
3776
|
+
confidence,
|
|
3777
|
+
lastAccessed,
|
|
3778
|
+
workspaceId,
|
|
3779
|
+
documentId,
|
|
3780
|
+
userId,
|
|
3781
|
+
charOffset,
|
|
3782
|
+
pageNumber,
|
|
3783
|
+
sourcePath,
|
|
3784
|
+
sourceType,
|
|
3785
|
+
tier,
|
|
3786
|
+
supersedesId,
|
|
3787
|
+
draft,
|
|
3788
|
+
memoryType,
|
|
3789
|
+
trajectory,
|
|
3790
|
+
contentHash
|
|
3791
|
+
];
|
|
3792
|
+
return {
|
|
3793
|
+
sql: hasVector ? `INSERT OR IGNORE INTO memories (${cols})
|
|
3794
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories (${cols})
|
|
3795
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
3796
|
+
args: hasVector ? [...baseArgs, vectorToBlob(row.vector), ...sharedArgs, ...metaArgs] : [...baseArgs, ...sharedArgs, ...metaArgs]
|
|
3797
|
+
};
|
|
3798
|
+
};
|
|
3799
|
+
const globalClient = getClient();
|
|
3800
|
+
const globalStmts = batch.map(buildStmt);
|
|
3801
|
+
await globalClient.batch(globalStmts, "write");
|
|
3802
|
+
_pendingRecords.splice(0, batch.length);
|
|
3803
|
+
try {
|
|
3804
|
+
const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
3805
|
+
if (isShardingEnabled2()) {
|
|
3806
|
+
const byProject = /* @__PURE__ */ new Map();
|
|
3807
|
+
for (const row of batch) {
|
|
3808
|
+
const proj = row.project_name || "unknown";
|
|
3809
|
+
if (!byProject.has(proj)) byProject.set(proj, []);
|
|
3810
|
+
byProject.get(proj).push(row);
|
|
3811
|
+
}
|
|
3812
|
+
for (const [project, rows] of byProject) {
|
|
3813
|
+
try {
|
|
3814
|
+
const shardClient = await getReadyShardClient2(project);
|
|
3815
|
+
const shardStmts = rows.map(buildStmt);
|
|
3816
|
+
await shardClient.batch(shardStmts, "write");
|
|
3817
|
+
} catch (err) {
|
|
3818
|
+
process.stderr.write(
|
|
3819
|
+
`[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
|
|
3820
|
+
`
|
|
3821
|
+
);
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
2451
3824
|
}
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
3825
|
+
} catch {
|
|
3826
|
+
}
|
|
3827
|
+
return batch.length;
|
|
3828
|
+
} finally {
|
|
3829
|
+
_flushing = false;
|
|
2456
3830
|
}
|
|
2457
|
-
}
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
}
|
|
2467
|
-
|
|
2468
|
-
|
|
3831
|
+
}
|
|
3832
|
+
function buildWikiScopeFilter(options, columnPrefix) {
|
|
3833
|
+
const args = [];
|
|
3834
|
+
let clause = "";
|
|
3835
|
+
if (options?.workspaceId !== void 0) {
|
|
3836
|
+
clause += ` AND ${columnPrefix}workspace_id = ?`;
|
|
3837
|
+
args.push(options.workspaceId);
|
|
3838
|
+
}
|
|
3839
|
+
if (options?.userId === void 0) {
|
|
3840
|
+
clause += ` AND ${columnPrefix}user_id IS NULL`;
|
|
3841
|
+
} else if (options.userId === null) {
|
|
3842
|
+
clause += ` AND ${columnPrefix}user_id IS NULL`;
|
|
3843
|
+
} else {
|
|
3844
|
+
clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
|
|
3845
|
+
args.push(options.userId);
|
|
3846
|
+
}
|
|
3847
|
+
return { clause, args };
|
|
3848
|
+
}
|
|
3849
|
+
function buildRawVisibilityFilter(options, columnPrefix) {
|
|
3850
|
+
if (options?.includeRaw === false) {
|
|
3851
|
+
return {
|
|
3852
|
+
clause: ` AND COALESCE(${columnPrefix}memory_type, 'raw') != 'raw'`,
|
|
3853
|
+
args: []
|
|
3854
|
+
};
|
|
3855
|
+
}
|
|
3856
|
+
return { clause: "", args: [] };
|
|
3857
|
+
}
|
|
3858
|
+
async function searchMemories(queryVector, agentId, options) {
|
|
3859
|
+
let client;
|
|
3860
|
+
try {
|
|
3861
|
+
const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
3862
|
+
if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
|
|
3863
|
+
client = await getReadyShardClient2(options.projectName);
|
|
3864
|
+
} else {
|
|
3865
|
+
client = getClient();
|
|
3866
|
+
}
|
|
3867
|
+
} catch {
|
|
3868
|
+
client = getClient();
|
|
3869
|
+
}
|
|
3870
|
+
const limit = options?.limit ?? 10;
|
|
3871
|
+
const statusFilter = options?.includeArchived ? "" : `
|
|
3872
|
+
AND COALESCE(status, 'active') = 'active'`;
|
|
3873
|
+
const draftFilter = options?.includeDrafts ? "" : `
|
|
3874
|
+
AND (draft = 0 OR draft IS NULL)`;
|
|
3875
|
+
let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
|
|
3876
|
+
tool_name, project_name,
|
|
3877
|
+
has_error, raw_text, vector, importance, status,
|
|
3878
|
+
confidence, last_accessed,
|
|
3879
|
+
workspace_id, document_id, user_id,
|
|
3880
|
+
char_offset, page_number,
|
|
3881
|
+
source_path, source_type
|
|
3882
|
+
FROM memories
|
|
3883
|
+
WHERE agent_id = ?
|
|
3884
|
+
AND vector IS NOT NULL${statusFilter}${draftFilter}
|
|
3885
|
+
AND COALESCE(confidence, 0.7) >= 0.3`;
|
|
3886
|
+
const args = [agentId];
|
|
3887
|
+
const scope = buildWikiScopeFilter(options, "");
|
|
3888
|
+
sql += scope.clause;
|
|
3889
|
+
args.push(...scope.args);
|
|
3890
|
+
const rawVisibility = buildRawVisibilityFilter(options, "");
|
|
3891
|
+
sql += rawVisibility.clause;
|
|
3892
|
+
args.push(...rawVisibility.args);
|
|
3893
|
+
if (options?.projectName) {
|
|
3894
|
+
sql += ` AND project_name = ?`;
|
|
3895
|
+
args.push(options.projectName);
|
|
3896
|
+
}
|
|
3897
|
+
if (options?.toolName) {
|
|
3898
|
+
sql += ` AND tool_name = ?`;
|
|
3899
|
+
args.push(options.toolName);
|
|
3900
|
+
}
|
|
3901
|
+
if (options?.hasError !== void 0) {
|
|
3902
|
+
sql += ` AND has_error = ?`;
|
|
3903
|
+
args.push(options.hasError ? 1 : 0);
|
|
3904
|
+
}
|
|
3905
|
+
if (options?.since) {
|
|
3906
|
+
sql += ` AND timestamp >= ?`;
|
|
3907
|
+
args.push(options.since);
|
|
3908
|
+
}
|
|
3909
|
+
if (options?.memoryType) {
|
|
3910
|
+
sql += ` AND memory_type = ?`;
|
|
3911
|
+
args.push(options.memoryType);
|
|
3912
|
+
}
|
|
3913
|
+
sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
|
|
3914
|
+
args.push(vectorToBlob(queryVector));
|
|
3915
|
+
sql += ` LIMIT ?`;
|
|
3916
|
+
args.push(limit);
|
|
3917
|
+
const result = await client.execute({ sql, args });
|
|
3918
|
+
return result.rows.map((row) => ({
|
|
3919
|
+
id: row.id,
|
|
3920
|
+
agent_id: row.agent_id,
|
|
3921
|
+
agent_role: row.agent_role,
|
|
3922
|
+
session_id: row.session_id,
|
|
3923
|
+
timestamp: row.timestamp,
|
|
3924
|
+
tool_name: row.tool_name,
|
|
3925
|
+
project_name: row.project_name,
|
|
3926
|
+
has_error: row.has_error === 1,
|
|
3927
|
+
raw_text: row.raw_text,
|
|
3928
|
+
vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
|
|
3929
|
+
importance: row.importance ?? 5,
|
|
3930
|
+
status: row.status ?? "active",
|
|
3931
|
+
confidence: row.confidence ?? 0.7,
|
|
3932
|
+
last_accessed: row.last_accessed ?? row.timestamp,
|
|
3933
|
+
workspace_id: row.workspace_id ?? null,
|
|
3934
|
+
document_id: row.document_id ?? null,
|
|
3935
|
+
user_id: row.user_id ?? null,
|
|
3936
|
+
char_offset: row.char_offset ?? null,
|
|
3937
|
+
page_number: row.page_number ?? null,
|
|
3938
|
+
source_path: row.source_path ?? null,
|
|
3939
|
+
source_type: row.source_type ?? null
|
|
3940
|
+
}));
|
|
3941
|
+
}
|
|
3942
|
+
async function attachDocumentMetadata(records) {
|
|
3943
|
+
const docIds = [
|
|
3944
|
+
...new Set(
|
|
3945
|
+
records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
|
|
3946
|
+
)
|
|
3947
|
+
];
|
|
3948
|
+
if (docIds.length === 0) return records;
|
|
3949
|
+
try {
|
|
3950
|
+
const client = getClient();
|
|
3951
|
+
const placeholders = docIds.map(() => "?").join(",");
|
|
3952
|
+
const result = await client.execute({
|
|
3953
|
+
sql: `SELECT id, filename, mime, source_type, uploaded_at
|
|
3954
|
+
FROM documents
|
|
3955
|
+
WHERE id IN (${placeholders})`,
|
|
3956
|
+
args: docIds
|
|
3957
|
+
});
|
|
3958
|
+
const byId = /* @__PURE__ */ new Map();
|
|
3959
|
+
for (const row of result.rows) {
|
|
3960
|
+
const id = row.id;
|
|
3961
|
+
byId.set(id, {
|
|
3962
|
+
document_id: id,
|
|
3963
|
+
filename: row.filename,
|
|
3964
|
+
mime: row.mime ?? null,
|
|
3965
|
+
source_type: row.source_type ?? null,
|
|
3966
|
+
uploaded_at: row.uploaded_at
|
|
3967
|
+
});
|
|
3968
|
+
}
|
|
3969
|
+
for (const record of records) {
|
|
3970
|
+
if (!record.document_id) continue;
|
|
3971
|
+
record.document_metadata = byId.get(record.document_id) ?? null;
|
|
3972
|
+
}
|
|
3973
|
+
} catch {
|
|
3974
|
+
}
|
|
3975
|
+
return records;
|
|
3976
|
+
}
|
|
3977
|
+
async function flushTier3(agentId, options) {
|
|
2469
3978
|
const client = getClient();
|
|
3979
|
+
const maxAge = options?.maxAgeHours ?? 72;
|
|
3980
|
+
const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
|
|
3981
|
+
if (options?.dryRun) {
|
|
3982
|
+
const result2 = await client.execute({
|
|
3983
|
+
sql: `SELECT COUNT(*) as cnt FROM memories
|
|
3984
|
+
WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
|
|
3985
|
+
args: [agentId, cutoff]
|
|
3986
|
+
});
|
|
3987
|
+
return { archived: Number(result2.rows[0]?.cnt ?? 0) };
|
|
3988
|
+
}
|
|
2470
3989
|
const result = await client.execute({
|
|
2471
|
-
sql:
|
|
2472
|
-
|
|
3990
|
+
sql: `UPDATE memories SET status = 'archived'
|
|
3991
|
+
WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
|
|
3992
|
+
args: [agentId, cutoff]
|
|
2473
3993
|
});
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
_customerCache = "";
|
|
3994
|
+
return { archived: result.rowsAffected };
|
|
3995
|
+
}
|
|
3996
|
+
async function disposeStore() {
|
|
3997
|
+
if (_flushTimer !== null) {
|
|
3998
|
+
clearInterval(_flushTimer);
|
|
3999
|
+
_flushTimer = null;
|
|
2481
4000
|
}
|
|
2482
|
-
|
|
2483
|
-
|
|
4001
|
+
if (_pendingRecords.length > 0) {
|
|
4002
|
+
await flushBatch();
|
|
4003
|
+
}
|
|
4004
|
+
await disposeTurso();
|
|
4005
|
+
_pendingRecords = [];
|
|
4006
|
+
_nextVersion = 1;
|
|
2484
4007
|
}
|
|
2485
|
-
function
|
|
2486
|
-
const
|
|
2487
|
-
|
|
2488
|
-
if (_cacheLoaded && _customerCache) sections.push(_customerCache);
|
|
2489
|
-
if (sections.length === 0) return "";
|
|
2490
|
-
return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
|
|
2491
|
-
|
|
2492
|
-
${sections.join("\n\n")}
|
|
2493
|
-
`;
|
|
4008
|
+
function vectorToBlob(vector) {
|
|
4009
|
+
const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
|
|
4010
|
+
return JSON.stringify(Array.from(f32));
|
|
2494
4011
|
}
|
|
2495
|
-
async function
|
|
2496
|
-
const id = randomUUID();
|
|
2497
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4012
|
+
async function updateMemoryStatus(id, status) {
|
|
2498
4013
|
const client = getClient();
|
|
2499
4014
|
await client.execute({
|
|
2500
|
-
sql: `
|
|
2501
|
-
|
|
2502
|
-
args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
|
|
4015
|
+
sql: `UPDATE memories SET status = ? WHERE id = ?`,
|
|
4016
|
+
args: [status, id]
|
|
2503
4017
|
});
|
|
2504
|
-
await loadGlobalProcedures();
|
|
2505
|
-
return id;
|
|
2506
4018
|
}
|
|
2507
|
-
|
|
2508
|
-
const
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
});
|
|
2514
|
-
await loadGlobalProcedures();
|
|
2515
|
-
return result.rowsAffected > 0;
|
|
4019
|
+
function reserveVersions(count) {
|
|
4020
|
+
const reserved = [];
|
|
4021
|
+
for (let i = 0; i < count; i++) {
|
|
4022
|
+
reserved.push(_nextVersion++);
|
|
4023
|
+
}
|
|
4024
|
+
return reserved;
|
|
2516
4025
|
}
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
4026
|
+
async function getMemoryCardinality(agentId) {
|
|
4027
|
+
try {
|
|
4028
|
+
const client = getClient();
|
|
4029
|
+
const result = await client.execute({
|
|
4030
|
+
sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
|
|
4031
|
+
args: [agentId]
|
|
4032
|
+
});
|
|
4033
|
+
return Number(result.rows[0]?.cnt) || 0;
|
|
4034
|
+
} catch {
|
|
4035
|
+
return 0;
|
|
4036
|
+
}
|
|
4037
|
+
}
|
|
4038
|
+
var INIT_MAX_RETRIES, INIT_RETRY_DELAY_MS, _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
|
|
4039
|
+
var init_store = __esm({
|
|
4040
|
+
"src/lib/store.ts"() {
|
|
2520
4041
|
"use strict";
|
|
4042
|
+
init_memory();
|
|
2521
4043
|
init_database();
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
4044
|
+
init_keychain();
|
|
4045
|
+
init_config();
|
|
4046
|
+
init_state_bus();
|
|
4047
|
+
INIT_MAX_RETRIES = 3;
|
|
4048
|
+
INIT_RETRY_DELAY_MS = 1e3;
|
|
4049
|
+
_pendingRecords = [];
|
|
4050
|
+
_batchSize = 20;
|
|
4051
|
+
_flushIntervalMs = 1e4;
|
|
4052
|
+
_flushTimer = null;
|
|
4053
|
+
_flushing = false;
|
|
4054
|
+
_nextVersion = 1;
|
|
2527
4055
|
}
|
|
2528
4056
|
});
|
|
2529
4057
|
|
|
2530
4058
|
// src/lib/session-registry.ts
|
|
2531
|
-
import
|
|
2532
|
-
import
|
|
4059
|
+
import path8 from "path";
|
|
4060
|
+
import os6 from "os";
|
|
2533
4061
|
var REGISTRY_PATH;
|
|
2534
4062
|
var init_session_registry = __esm({
|
|
2535
4063
|
"src/lib/session-registry.ts"() {
|
|
2536
4064
|
"use strict";
|
|
2537
|
-
REGISTRY_PATH =
|
|
4065
|
+
REGISTRY_PATH = path8.join(os6.homedir(), ".exe-os", "session-registry.json");
|
|
2538
4066
|
}
|
|
2539
4067
|
});
|
|
2540
4068
|
|
|
@@ -2779,8 +4307,8 @@ var init_runtime_table = __esm({
|
|
|
2779
4307
|
});
|
|
2780
4308
|
|
|
2781
4309
|
// src/lib/agent-config.ts
|
|
2782
|
-
import { readFileSync as
|
|
2783
|
-
import
|
|
4310
|
+
import { readFileSync as readFileSync5, writeFileSync as writeFileSync3, existsSync as existsSync8 } from "fs";
|
|
4311
|
+
import path9 from "path";
|
|
2784
4312
|
var AGENT_CONFIG_PATH, DEFAULT_MODELS;
|
|
2785
4313
|
var init_agent_config = __esm({
|
|
2786
4314
|
"src/lib/agent-config.ts"() {
|
|
@@ -2788,9 +4316,9 @@ var init_agent_config = __esm({
|
|
|
2788
4316
|
init_config();
|
|
2789
4317
|
init_runtime_table();
|
|
2790
4318
|
init_secure_files();
|
|
2791
|
-
AGENT_CONFIG_PATH =
|
|
4319
|
+
AGENT_CONFIG_PATH = path9.join(EXE_AI_DIR, "agent-config.json");
|
|
2792
4320
|
DEFAULT_MODELS = {
|
|
2793
|
-
claude: "claude-opus-4",
|
|
4321
|
+
claude: "claude-opus-4.6",
|
|
2794
4322
|
codex: RUNTIME_TABLE.codex?.defaultModel ?? "gpt-5.4",
|
|
2795
4323
|
opencode: RUNTIME_TABLE.opencode?.defaultModel ?? "anthropic/claude-sonnet-4-6"
|
|
2796
4324
|
};
|
|
@@ -2798,41 +4326,41 @@ var init_agent_config = __esm({
|
|
|
2798
4326
|
});
|
|
2799
4327
|
|
|
2800
4328
|
// src/lib/intercom-queue.ts
|
|
2801
|
-
import { readFileSync as
|
|
2802
|
-
import
|
|
2803
|
-
import
|
|
4329
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync4, renameSync as renameSync3, existsSync as existsSync9, mkdirSync as mkdirSync3 } from "fs";
|
|
4330
|
+
import path10 from "path";
|
|
4331
|
+
import os7 from "os";
|
|
2804
4332
|
var QUEUE_PATH, TTL_MS, INTERCOM_LOG;
|
|
2805
4333
|
var init_intercom_queue = __esm({
|
|
2806
4334
|
"src/lib/intercom-queue.ts"() {
|
|
2807
4335
|
"use strict";
|
|
2808
|
-
QUEUE_PATH =
|
|
4336
|
+
QUEUE_PATH = path10.join(os7.homedir(), ".exe-os", "intercom-queue.json");
|
|
2809
4337
|
TTL_MS = 60 * 60 * 1e3;
|
|
2810
|
-
INTERCOM_LOG =
|
|
4338
|
+
INTERCOM_LOG = path10.join(os7.homedir(), ".exe-os", "intercom.log");
|
|
2811
4339
|
}
|
|
2812
4340
|
});
|
|
2813
4341
|
|
|
2814
4342
|
// src/lib/license.ts
|
|
2815
|
-
import { readFileSync as
|
|
2816
|
-
import { randomUUID as
|
|
4343
|
+
import { readFileSync as readFileSync7, writeFileSync as writeFileSync5, existsSync as existsSync10, mkdirSync as mkdirSync4 } from "fs";
|
|
4344
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
2817
4345
|
import { createRequire as createRequire2 } from "module";
|
|
2818
4346
|
import { pathToFileURL as pathToFileURL2 } from "url";
|
|
2819
|
-
import
|
|
2820
|
-
import
|
|
4347
|
+
import os8 from "os";
|
|
4348
|
+
import path11 from "path";
|
|
2821
4349
|
import { jwtVerify, importSPKI } from "jose";
|
|
2822
4350
|
var LICENSE_PATH, CACHE_PATH, DEVICE_ID_PATH;
|
|
2823
4351
|
var init_license = __esm({
|
|
2824
4352
|
"src/lib/license.ts"() {
|
|
2825
4353
|
"use strict";
|
|
2826
4354
|
init_config();
|
|
2827
|
-
LICENSE_PATH =
|
|
2828
|
-
CACHE_PATH =
|
|
2829
|
-
DEVICE_ID_PATH =
|
|
4355
|
+
LICENSE_PATH = path11.join(EXE_AI_DIR, "license.key");
|
|
4356
|
+
CACHE_PATH = path11.join(EXE_AI_DIR, "license-cache.json");
|
|
4357
|
+
DEVICE_ID_PATH = path11.join(EXE_AI_DIR, "device-id");
|
|
2830
4358
|
}
|
|
2831
4359
|
});
|
|
2832
4360
|
|
|
2833
4361
|
// src/lib/plan-limits.ts
|
|
2834
|
-
import { readFileSync as
|
|
2835
|
-
import
|
|
4362
|
+
import { readFileSync as readFileSync8, existsSync as existsSync11 } from "fs";
|
|
4363
|
+
import path12 from "path";
|
|
2836
4364
|
var CACHE_PATH2;
|
|
2837
4365
|
var init_plan_limits = __esm({
|
|
2838
4366
|
"src/lib/plan-limits.ts"() {
|
|
@@ -2841,15 +4369,15 @@ var init_plan_limits = __esm({
|
|
|
2841
4369
|
init_employees();
|
|
2842
4370
|
init_license();
|
|
2843
4371
|
init_config();
|
|
2844
|
-
CACHE_PATH2 =
|
|
4372
|
+
CACHE_PATH2 = path12.join(EXE_AI_DIR, "license-cache.json");
|
|
2845
4373
|
}
|
|
2846
4374
|
});
|
|
2847
4375
|
|
|
2848
4376
|
// src/lib/tmux-routing.ts
|
|
2849
|
-
import { readFileSync as
|
|
2850
|
-
import
|
|
2851
|
-
import
|
|
2852
|
-
import { fileURLToPath } from "url";
|
|
4377
|
+
import { readFileSync as readFileSync9, writeFileSync as writeFileSync6, mkdirSync as mkdirSync5, existsSync as existsSync12, appendFileSync, readdirSync as readdirSync2 } from "fs";
|
|
4378
|
+
import path13 from "path";
|
|
4379
|
+
import os9 from "os";
|
|
4380
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2853
4381
|
function getMySession() {
|
|
2854
4382
|
return getTransport().getMySession();
|
|
2855
4383
|
}
|
|
@@ -2861,7 +4389,7 @@ function extractRootExe(name) {
|
|
|
2861
4389
|
}
|
|
2862
4390
|
function getParentExe(sessionKey) {
|
|
2863
4391
|
try {
|
|
2864
|
-
const data = JSON.parse(
|
|
4392
|
+
const data = JSON.parse(readFileSync9(path13.join(SESSION_CACHE, `parent-exe-${sessionKey}.json`), "utf8"));
|
|
2865
4393
|
return data.parentExe || null;
|
|
2866
4394
|
} catch {
|
|
2867
4395
|
return null;
|
|
@@ -2904,10 +4432,10 @@ var init_tmux_routing = __esm({
|
|
|
2904
4432
|
init_intercom_queue();
|
|
2905
4433
|
init_plan_limits();
|
|
2906
4434
|
init_employees();
|
|
2907
|
-
SPAWN_LOCK_DIR =
|
|
2908
|
-
SESSION_CACHE =
|
|
2909
|
-
INTERCOM_LOG2 =
|
|
2910
|
-
DEBOUNCE_FILE =
|
|
4435
|
+
SPAWN_LOCK_DIR = path13.join(os9.homedir(), ".exe-os", "spawn-locks");
|
|
4436
|
+
SESSION_CACHE = path13.join(os9.homedir(), ".exe-os", "session-cache");
|
|
4437
|
+
INTERCOM_LOG2 = path13.join(os9.homedir(), ".exe-os", "intercom.log");
|
|
4438
|
+
DEBOUNCE_FILE = path13.join(SESSION_CACHE, "intercom-debounce.json");
|
|
2911
4439
|
DEBOUNCE_CLEANUP_AGE_MS = 5 * 60 * 1e3;
|
|
2912
4440
|
}
|
|
2913
4441
|
});
|
|
@@ -2936,141 +4464,66 @@ var init_task_scope = __esm({
|
|
|
2936
4464
|
}
|
|
2937
4465
|
});
|
|
2938
4466
|
|
|
2939
|
-
// src/
|
|
2940
|
-
|
|
2941
|
-
init_database();
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2945
|
-
import { existsSync as existsSync4 } from "fs";
|
|
2946
|
-
import path4 from "path";
|
|
2947
|
-
import os4 from "os";
|
|
2948
|
-
var SERVICE = "exe-mem";
|
|
2949
|
-
var ACCOUNT = "master-key";
|
|
2950
|
-
function getKeyDir() {
|
|
2951
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
|
|
2952
|
-
}
|
|
2953
|
-
function getKeyPath() {
|
|
2954
|
-
return path4.join(getKeyDir(), "master.key");
|
|
2955
|
-
}
|
|
2956
|
-
async function tryKeytar() {
|
|
2957
|
-
try {
|
|
2958
|
-
return await import("keytar");
|
|
2959
|
-
} catch {
|
|
2960
|
-
return null;
|
|
2961
|
-
}
|
|
2962
|
-
}
|
|
2963
|
-
async function getMasterKey() {
|
|
2964
|
-
const keytar = await tryKeytar();
|
|
2965
|
-
if (keytar) {
|
|
2966
|
-
try {
|
|
2967
|
-
const stored = await keytar.getPassword(SERVICE, ACCOUNT);
|
|
2968
|
-
if (stored) {
|
|
2969
|
-
return Buffer.from(stored, "base64");
|
|
2970
|
-
}
|
|
2971
|
-
} catch {
|
|
2972
|
-
}
|
|
2973
|
-
}
|
|
2974
|
-
const keyPath = getKeyPath();
|
|
2975
|
-
if (!existsSync4(keyPath)) {
|
|
2976
|
-
process.stderr.write(
|
|
2977
|
-
`[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2978
|
-
`
|
|
2979
|
-
);
|
|
2980
|
-
return null;
|
|
4467
|
+
// src/bin/fast-db-init.ts
|
|
4468
|
+
async function fastDbInit() {
|
|
4469
|
+
const { isInitialized: isInitialized2, getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
|
|
4470
|
+
if (isInitialized2()) {
|
|
4471
|
+
return getClient2();
|
|
2981
4472
|
}
|
|
2982
4473
|
try {
|
|
2983
|
-
const
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
_flushTimer = null;
|
|
3031
|
-
}
|
|
3032
|
-
_pendingRecords = [];
|
|
3033
|
-
_flushing = false;
|
|
3034
|
-
_batchSize = options?.batchSize ?? 20;
|
|
3035
|
-
_flushIntervalMs = options?.flushIntervalMs ?? 1e4;
|
|
3036
|
-
let dbPath = options?.dbPath;
|
|
3037
|
-
if (!dbPath) {
|
|
3038
|
-
const config = await loadConfig();
|
|
3039
|
-
dbPath = config.dbPath;
|
|
3040
|
-
}
|
|
3041
|
-
let masterKey = options?.masterKey ?? null;
|
|
3042
|
-
if (!masterKey) {
|
|
3043
|
-
masterKey = await getMasterKey();
|
|
3044
|
-
if (!masterKey) {
|
|
3045
|
-
throw new Error(
|
|
3046
|
-
"No encryption key found. Run /exe-setup to generate one."
|
|
3047
|
-
);
|
|
3048
|
-
}
|
|
3049
|
-
}
|
|
3050
|
-
const hexKey = masterKey.toString("hex");
|
|
3051
|
-
await initTurso({
|
|
3052
|
-
dbPath,
|
|
3053
|
-
encryptionKey: hexKey
|
|
3054
|
-
});
|
|
3055
|
-
await retryOnBusy2(() => ensureSchema(), "ensureSchema");
|
|
3056
|
-
if (!options?.lightweight) {
|
|
3057
|
-
try {
|
|
3058
|
-
const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
3059
|
-
initShardManager2(hexKey);
|
|
3060
|
-
} catch {
|
|
3061
|
-
}
|
|
3062
|
-
const client = getClient();
|
|
3063
|
-
const vResult = await retryOnBusy2(
|
|
3064
|
-
() => client.execute("SELECT MAX(version) as max_v FROM memories"),
|
|
3065
|
-
"version-query"
|
|
3066
|
-
);
|
|
3067
|
-
_nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
|
|
3068
|
-
try {
|
|
3069
|
-
const { loadGlobalProcedures: loadGlobalProcedures2 } = await Promise.resolve().then(() => (init_global_procedures(), global_procedures_exports));
|
|
3070
|
-
await loadGlobalProcedures2();
|
|
3071
|
-
} catch {
|
|
4474
|
+
const { connectEmbedDaemon: connectEmbedDaemon2, sendDaemonRequest: sendDaemonRequest2, isClientConnected: isClientConnected2 } = await Promise.resolve().then(() => (init_exe_daemon_client(), exe_daemon_client_exports));
|
|
4475
|
+
const { deserializeResultSet: deserializeResultSet2 } = await Promise.resolve().then(() => (init_daemon_protocol(), daemon_protocol_exports));
|
|
4476
|
+
await connectEmbedDaemon2();
|
|
4477
|
+
if (isClientConnected2()) {
|
|
4478
|
+
const daemonClient = {
|
|
4479
|
+
async execute(stmt) {
|
|
4480
|
+
const sql = typeof stmt === "string" ? stmt : stmt.sql;
|
|
4481
|
+
const args = typeof stmt === "string" ? [] : Array.isArray(stmt.args) ? stmt.args : [];
|
|
4482
|
+
const resp = await sendDaemonRequest2({ type: "db-execute", sql, args });
|
|
4483
|
+
if (resp.error) throw new Error(String(resp.error));
|
|
4484
|
+
if (resp.db) return deserializeResultSet2(resp.db);
|
|
4485
|
+
throw new Error("Unexpected daemon response");
|
|
4486
|
+
},
|
|
4487
|
+
async batch(stmts, mode) {
|
|
4488
|
+
const statements = stmts.map((s) => {
|
|
4489
|
+
const sql = typeof s === "string" ? s : s.sql;
|
|
4490
|
+
const args = typeof s === "string" ? [] : Array.isArray(s.args) ? s.args : [];
|
|
4491
|
+
return { sql, args };
|
|
4492
|
+
});
|
|
4493
|
+
const resp = await sendDaemonRequest2({ type: "db-batch", statements, mode: mode ?? "deferred" });
|
|
4494
|
+
if (resp.error) throw new Error(String(resp.error));
|
|
4495
|
+
const batchResults = resp["db-batch"];
|
|
4496
|
+
if (batchResults) return batchResults.map(deserializeResultSet2);
|
|
4497
|
+
throw new Error("Unexpected daemon batch response");
|
|
4498
|
+
},
|
|
4499
|
+
async transaction(_mode) {
|
|
4500
|
+
throw new Error("Transactions not supported via daemon socket");
|
|
4501
|
+
},
|
|
4502
|
+
async executeMultiple(_sql) {
|
|
4503
|
+
throw new Error("executeMultiple not supported via daemon socket");
|
|
4504
|
+
},
|
|
4505
|
+
async migrate(_stmts) {
|
|
4506
|
+
throw new Error("migrate not supported via daemon socket");
|
|
4507
|
+
},
|
|
4508
|
+
sync() {
|
|
4509
|
+
return Promise.resolve(void 0);
|
|
4510
|
+
},
|
|
4511
|
+
close() {
|
|
4512
|
+
},
|
|
4513
|
+
get closed() {
|
|
4514
|
+
return false;
|
|
4515
|
+
},
|
|
4516
|
+
get protocol() {
|
|
4517
|
+
return "file";
|
|
4518
|
+
}
|
|
4519
|
+
};
|
|
4520
|
+
return daemonClient;
|
|
3072
4521
|
}
|
|
4522
|
+
} catch {
|
|
3073
4523
|
}
|
|
4524
|
+
const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
|
|
4525
|
+
await initStore2({ lightweight: true });
|
|
4526
|
+
return getClient2();
|
|
3074
4527
|
}
|
|
3075
4528
|
|
|
3076
4529
|
// src/bin/cleanup-stale-review-tasks.ts
|
|
@@ -3079,13 +4532,13 @@ init_task_scope();
|
|
|
3079
4532
|
|
|
3080
4533
|
// src/lib/is-main.ts
|
|
3081
4534
|
import { realpathSync } from "fs";
|
|
3082
|
-
import { fileURLToPath as
|
|
4535
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
3083
4536
|
function isMainModule(importMetaUrl) {
|
|
3084
4537
|
if (process.argv[1] == null) return false;
|
|
3085
4538
|
if (process.argv[1].includes("mcp/server")) return false;
|
|
3086
4539
|
try {
|
|
3087
4540
|
const scriptPath = realpathSync(process.argv[1]);
|
|
3088
|
-
const modulePath = realpathSync(
|
|
4541
|
+
const modulePath = realpathSync(fileURLToPath3(importMetaUrl));
|
|
3089
4542
|
return scriptPath === modulePath;
|
|
3090
4543
|
} catch {
|
|
3091
4544
|
return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
|
|
@@ -3161,7 +4614,7 @@ async function main() {
|
|
|
3161
4614
|
const beforeIso = beforeIdx >= 0 ? args[beforeIdx + 1] : void 0;
|
|
3162
4615
|
const assigneeIdx = args.indexOf("--assignee");
|
|
3163
4616
|
const assignee = assigneeIdx >= 0 ? args[assigneeIdx + 1] : void 0;
|
|
3164
|
-
await
|
|
4617
|
+
await fastDbInit();
|
|
3165
4618
|
if (stats) {
|
|
3166
4619
|
await statsByAssignee();
|
|
3167
4620
|
process.exit(0);
|