@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
package/dist/bin/exe-review.js
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
var __defProp = Object.defineProperty;
|
|
3
3
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
5
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
6
|
+
}) : x)(function(x) {
|
|
7
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
8
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
9
|
+
});
|
|
4
10
|
var __esm = (fn, res) => function __init() {
|
|
5
11
|
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
6
12
|
};
|
|
@@ -19,12 +25,25 @@ async function ensurePrivateDir(dirPath) {
|
|
|
19
25
|
} catch {
|
|
20
26
|
}
|
|
21
27
|
}
|
|
28
|
+
function ensurePrivateDirSync(dirPath) {
|
|
29
|
+
mkdirSync(dirPath, { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
30
|
+
try {
|
|
31
|
+
chmodSync(dirPath, PRIVATE_DIR_MODE);
|
|
32
|
+
} catch {
|
|
33
|
+
}
|
|
34
|
+
}
|
|
22
35
|
async function enforcePrivateFile(filePath) {
|
|
23
36
|
try {
|
|
24
37
|
await chmod(filePath, PRIVATE_FILE_MODE);
|
|
25
38
|
} catch {
|
|
26
39
|
}
|
|
27
40
|
}
|
|
41
|
+
function enforcePrivateFileSync(filePath) {
|
|
42
|
+
try {
|
|
43
|
+
if (existsSync(filePath)) chmodSync(filePath, PRIVATE_FILE_MODE);
|
|
44
|
+
} catch {
|
|
45
|
+
}
|
|
46
|
+
}
|
|
28
47
|
var PRIVATE_DIR_MODE, PRIVATE_FILE_MODE;
|
|
29
48
|
var init_secure_files = __esm({
|
|
30
49
|
"src/lib/secure-files.ts"() {
|
|
@@ -271,6 +290,15 @@ var init_employees = __esm({
|
|
|
271
290
|
}
|
|
272
291
|
});
|
|
273
292
|
|
|
293
|
+
// src/types/memory.ts
|
|
294
|
+
var EMBEDDING_DIM;
|
|
295
|
+
var init_memory = __esm({
|
|
296
|
+
"src/types/memory.ts"() {
|
|
297
|
+
"use strict";
|
|
298
|
+
EMBEDDING_DIM = 1024;
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
|
|
274
302
|
// src/lib/db-retry.ts
|
|
275
303
|
function isBusyError(err) {
|
|
276
304
|
if (err instanceof Error) {
|
|
@@ -320,9 +348,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
|
|
|
320
348
|
var init_db_retry = __esm({
|
|
321
349
|
"src/lib/db-retry.ts"() {
|
|
322
350
|
"use strict";
|
|
323
|
-
MAX_RETRIES =
|
|
324
|
-
BASE_DELAY_MS =
|
|
325
|
-
MAX_JITTER_MS =
|
|
351
|
+
MAX_RETRIES = 5;
|
|
352
|
+
BASE_DELAY_MS = 250;
|
|
353
|
+
MAX_JITTER_MS = 400;
|
|
326
354
|
}
|
|
327
355
|
});
|
|
328
356
|
|
|
@@ -910,198 +938,970 @@ var init_database_adapter = __esm({
|
|
|
910
938
|
}
|
|
911
939
|
});
|
|
912
940
|
|
|
913
|
-
// src/lib/
|
|
914
|
-
import
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
941
|
+
// src/lib/daemon-auth.ts
|
|
942
|
+
import crypto from "crypto";
|
|
943
|
+
import path4 from "path";
|
|
944
|
+
import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
945
|
+
function normalizeToken(token) {
|
|
946
|
+
if (!token) return null;
|
|
947
|
+
const trimmed = token.trim();
|
|
948
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
949
|
+
}
|
|
950
|
+
function readDaemonToken() {
|
|
951
|
+
try {
|
|
952
|
+
if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
|
|
953
|
+
return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
|
|
954
|
+
} catch {
|
|
955
|
+
return null;
|
|
919
956
|
}
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
957
|
+
}
|
|
958
|
+
function ensureDaemonToken(seed) {
|
|
959
|
+
const existing = readDaemonToken();
|
|
960
|
+
if (existing) return existing;
|
|
961
|
+
const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
|
|
962
|
+
ensurePrivateDirSync(EXE_AI_DIR);
|
|
963
|
+
writeFileSync2(DAEMON_TOKEN_PATH, `${token}
|
|
964
|
+
`, "utf8");
|
|
965
|
+
enforcePrivateFileSync(DAEMON_TOKEN_PATH);
|
|
966
|
+
return token;
|
|
967
|
+
}
|
|
968
|
+
var DAEMON_TOKEN_PATH;
|
|
969
|
+
var init_daemon_auth = __esm({
|
|
970
|
+
"src/lib/daemon-auth.ts"() {
|
|
971
|
+
"use strict";
|
|
972
|
+
init_config();
|
|
973
|
+
init_secure_files();
|
|
974
|
+
DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
|
|
923
975
|
}
|
|
924
|
-
|
|
925
|
-
|
|
976
|
+
});
|
|
977
|
+
|
|
978
|
+
// src/lib/exe-daemon-client.ts
|
|
979
|
+
var exe_daemon_client_exports = {};
|
|
980
|
+
__export(exe_daemon_client_exports, {
|
|
981
|
+
connectEmbedDaemon: () => connectEmbedDaemon,
|
|
982
|
+
disconnectClient: () => disconnectClient,
|
|
983
|
+
embedBatchViaClient: () => embedBatchViaClient,
|
|
984
|
+
embedViaClient: () => embedViaClient,
|
|
985
|
+
isClientConnected: () => isClientConnected,
|
|
986
|
+
pingDaemon: () => pingDaemon,
|
|
987
|
+
sendDaemonRequest: () => sendDaemonRequest,
|
|
988
|
+
sendIngestRequest: () => sendIngestRequest
|
|
989
|
+
});
|
|
990
|
+
import net from "net";
|
|
991
|
+
import os4 from "os";
|
|
992
|
+
import { spawn } from "child_process";
|
|
993
|
+
import { randomUUID } from "crypto";
|
|
994
|
+
import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
|
|
995
|
+
import path5 from "path";
|
|
996
|
+
import { fileURLToPath } from "url";
|
|
997
|
+
function handleData(chunk) {
|
|
998
|
+
_buffer += chunk.toString();
|
|
999
|
+
if (_buffer.length > MAX_BUFFER) {
|
|
1000
|
+
_buffer = "";
|
|
1001
|
+
return;
|
|
926
1002
|
}
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
1003
|
+
let newlineIdx;
|
|
1004
|
+
while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
|
|
1005
|
+
const line = _buffer.slice(0, newlineIdx).trim();
|
|
1006
|
+
_buffer = _buffer.slice(newlineIdx + 1);
|
|
1007
|
+
if (!line) continue;
|
|
1008
|
+
try {
|
|
1009
|
+
const response = JSON.parse(line);
|
|
1010
|
+
const id = response.id;
|
|
1011
|
+
if (!id) continue;
|
|
1012
|
+
const entry = _pending.get(id);
|
|
1013
|
+
if (entry) {
|
|
1014
|
+
clearTimeout(entry.timer);
|
|
1015
|
+
_pending.delete(id);
|
|
1016
|
+
entry.resolve(response);
|
|
1017
|
+
}
|
|
1018
|
+
} catch {
|
|
1019
|
+
}
|
|
932
1020
|
}
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
1021
|
+
}
|
|
1022
|
+
function cleanupStaleFiles() {
|
|
1023
|
+
if (existsSync5(PID_PATH)) {
|
|
1024
|
+
try {
|
|
1025
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
1026
|
+
if (pid > 0) {
|
|
1027
|
+
try {
|
|
1028
|
+
process.kill(pid, 0);
|
|
1029
|
+
return;
|
|
1030
|
+
} catch {
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
} catch {
|
|
1034
|
+
}
|
|
1035
|
+
try {
|
|
1036
|
+
unlinkSync2(PID_PATH);
|
|
1037
|
+
} catch {
|
|
1038
|
+
}
|
|
1039
|
+
try {
|
|
1040
|
+
unlinkSync2(SOCKET_PATH);
|
|
1041
|
+
} catch {
|
|
1042
|
+
}
|
|
938
1043
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
|
|
947
|
-
_walCheckpointTimer = setInterval(() => {
|
|
948
|
-
_client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
|
|
949
|
-
});
|
|
950
|
-
}, 3e4);
|
|
951
|
-
_walCheckpointTimer.unref();
|
|
952
|
-
if (process.env.DATABASE_URL) {
|
|
953
|
-
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1044
|
+
}
|
|
1045
|
+
function findPackageRoot() {
|
|
1046
|
+
let dir = path5.dirname(fileURLToPath(import.meta.url));
|
|
1047
|
+
const { root } = path5.parse(dir);
|
|
1048
|
+
while (dir !== root) {
|
|
1049
|
+
if (existsSync5(path5.join(dir, "package.json"))) return dir;
|
|
1050
|
+
dir = path5.dirname(dir);
|
|
954
1051
|
}
|
|
1052
|
+
return null;
|
|
955
1053
|
}
|
|
956
|
-
function
|
|
957
|
-
if (
|
|
958
|
-
|
|
1054
|
+
function getAvailableMemoryGB() {
|
|
1055
|
+
if (process.platform === "darwin") {
|
|
1056
|
+
try {
|
|
1057
|
+
const { execSync: execSync2 } = __require("child_process");
|
|
1058
|
+
const vmstat = execSync2("vm_stat", { encoding: "utf8" });
|
|
1059
|
+
const pageSize = 16384;
|
|
1060
|
+
const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
|
|
1061
|
+
const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
|
|
1062
|
+
const free = vmstat.match(/Pages free:\s+(\d+)/);
|
|
1063
|
+
const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
|
|
1064
|
+
const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
|
|
1065
|
+
const freePages = free ? parseInt(free[1], 10) : 0;
|
|
1066
|
+
const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
|
|
1067
|
+
const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
|
|
1068
|
+
return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
|
|
1069
|
+
} catch {
|
|
1070
|
+
return os4.freemem() / (1024 * 1024 * 1024);
|
|
1071
|
+
}
|
|
959
1072
|
}
|
|
960
|
-
|
|
961
|
-
|
|
1073
|
+
return os4.freemem() / (1024 * 1024 * 1024);
|
|
1074
|
+
}
|
|
1075
|
+
function spawnDaemon() {
|
|
1076
|
+
const freeGB = getAvailableMemoryGB();
|
|
1077
|
+
const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
|
|
1078
|
+
if (totalGB <= 8) {
|
|
1079
|
+
process.stderr.write(
|
|
1080
|
+
`[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
|
|
1081
|
+
`
|
|
1082
|
+
);
|
|
1083
|
+
return;
|
|
962
1084
|
}
|
|
963
|
-
if (
|
|
964
|
-
|
|
1085
|
+
if (totalGB <= 16 && freeGB < 2) {
|
|
1086
|
+
process.stderr.write(
|
|
1087
|
+
`[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
|
|
1088
|
+
`
|
|
1089
|
+
);
|
|
1090
|
+
return;
|
|
965
1091
|
}
|
|
966
|
-
|
|
967
|
-
|
|
1092
|
+
const pkgRoot = findPackageRoot();
|
|
1093
|
+
if (!pkgRoot) {
|
|
1094
|
+
process.stderr.write("[exed-client] WARN: cannot find package root\n");
|
|
1095
|
+
return;
|
|
968
1096
|
}
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
1097
|
+
const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
|
|
1098
|
+
if (!existsSync5(daemonPath)) {
|
|
1099
|
+
process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
|
|
1100
|
+
`);
|
|
1101
|
+
return;
|
|
974
1102
|
}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
await client.execute("PRAGMA wal_autocheckpoint = 1000");
|
|
1103
|
+
const resolvedPath = daemonPath;
|
|
1104
|
+
const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
|
|
1105
|
+
process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
|
|
1106
|
+
`);
|
|
1107
|
+
const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
|
|
1108
|
+
let stderrFd = "ignore";
|
|
982
1109
|
try {
|
|
983
|
-
|
|
1110
|
+
stderrFd = openSync(logPath, "a");
|
|
984
1111
|
} catch {
|
|
985
1112
|
}
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
ON memories(project_name);
|
|
1012
|
-
|
|
1013
|
-
CREATE INDEX IF NOT EXISTS idx_memories_tool
|
|
1014
|
-
ON memories(tool_name);
|
|
1015
|
-
|
|
1016
|
-
CREATE INDEX IF NOT EXISTS idx_memories_version
|
|
1017
|
-
ON memories(version);
|
|
1018
|
-
|
|
1019
|
-
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
1020
|
-
ON memories(agent_id, project_name);
|
|
1021
|
-
`);
|
|
1022
|
-
await client.executeMultiple(`
|
|
1023
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
1024
|
-
raw_text,
|
|
1025
|
-
content='memories',
|
|
1026
|
-
content_rowid='rowid'
|
|
1027
|
-
);
|
|
1028
|
-
|
|
1029
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
1030
|
-
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1031
|
-
END;
|
|
1032
|
-
|
|
1033
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
1034
|
-
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1035
|
-
END;
|
|
1036
|
-
|
|
1037
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
1038
|
-
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1039
|
-
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1040
|
-
END;
|
|
1041
|
-
`);
|
|
1042
|
-
await client.executeMultiple(`
|
|
1043
|
-
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
1044
|
-
key TEXT PRIMARY KEY,
|
|
1045
|
-
value TEXT NOT NULL
|
|
1046
|
-
);
|
|
1047
|
-
`);
|
|
1048
|
-
await client.executeMultiple(`
|
|
1049
|
-
CREATE TABLE IF NOT EXISTS tasks (
|
|
1050
|
-
id TEXT PRIMARY KEY,
|
|
1051
|
-
title TEXT NOT NULL,
|
|
1052
|
-
assigned_to TEXT NOT NULL,
|
|
1053
|
-
assigned_by TEXT NOT NULL,
|
|
1054
|
-
project_name TEXT NOT NULL,
|
|
1055
|
-
priority TEXT NOT NULL DEFAULT 'p1',
|
|
1056
|
-
status TEXT NOT NULL DEFAULT 'open',
|
|
1057
|
-
task_file TEXT,
|
|
1058
|
-
created_at TEXT NOT NULL,
|
|
1059
|
-
updated_at TEXT NOT NULL
|
|
1060
|
-
);
|
|
1061
|
-
|
|
1062
|
-
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
1063
|
-
ON tasks(assigned_to, status);
|
|
1064
|
-
`);
|
|
1065
|
-
await client.executeMultiple(`
|
|
1066
|
-
CREATE TABLE IF NOT EXISTS behaviors (
|
|
1067
|
-
id TEXT PRIMARY KEY,
|
|
1068
|
-
agent_id TEXT NOT NULL,
|
|
1069
|
-
project_name TEXT,
|
|
1070
|
-
domain TEXT,
|
|
1071
|
-
content TEXT NOT NULL,
|
|
1072
|
-
active INTEGER NOT NULL DEFAULT 1,
|
|
1073
|
-
created_at TEXT NOT NULL,
|
|
1074
|
-
updated_at TEXT NOT NULL
|
|
1075
|
-
);
|
|
1076
|
-
|
|
1077
|
-
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
1078
|
-
ON behaviors(agent_id, active);
|
|
1079
|
-
`);
|
|
1113
|
+
const heapCapMB = totalGB <= 8 ? 256 : 512;
|
|
1114
|
+
const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
|
|
1115
|
+
const child = spawn(process.execPath, nodeArgs, {
|
|
1116
|
+
detached: true,
|
|
1117
|
+
stdio: ["ignore", "ignore", stderrFd],
|
|
1118
|
+
env: {
|
|
1119
|
+
...process.env,
|
|
1120
|
+
TMUX: void 0,
|
|
1121
|
+
// Daemon is global — must not inherit session scope
|
|
1122
|
+
TMUX_PANE: void 0,
|
|
1123
|
+
// Prevents resolveExeSession() from scoping to one session
|
|
1124
|
+
EXE_DAEMON_SOCK: SOCKET_PATH,
|
|
1125
|
+
EXE_DAEMON_PID: PID_PATH,
|
|
1126
|
+
[DAEMON_TOKEN_ENV]: daemonToken
|
|
1127
|
+
}
|
|
1128
|
+
});
|
|
1129
|
+
child.unref();
|
|
1130
|
+
if (typeof stderrFd === "number") {
|
|
1131
|
+
try {
|
|
1132
|
+
closeSync(stderrFd);
|
|
1133
|
+
} catch {
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
function acquireSpawnLock() {
|
|
1080
1138
|
try {
|
|
1081
|
-
const
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
}
|
|
1139
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
1140
|
+
closeSync(fd);
|
|
1141
|
+
return true;
|
|
1142
|
+
} catch {
|
|
1143
|
+
try {
|
|
1144
|
+
const stat = statSync(SPAWN_LOCK_PATH);
|
|
1145
|
+
if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
|
|
1146
|
+
try {
|
|
1147
|
+
unlinkSync2(SPAWN_LOCK_PATH);
|
|
1148
|
+
} catch {
|
|
1149
|
+
}
|
|
1150
|
+
try {
|
|
1151
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
1152
|
+
closeSync(fd);
|
|
1153
|
+
return true;
|
|
1154
|
+
} catch {
|
|
1155
|
+
}
|
|
1098
1156
|
}
|
|
1157
|
+
} catch {
|
|
1099
1158
|
}
|
|
1100
|
-
|
|
1159
|
+
return false;
|
|
1101
1160
|
}
|
|
1161
|
+
}
|
|
1162
|
+
function releaseSpawnLock() {
|
|
1102
1163
|
try {
|
|
1103
|
-
|
|
1104
|
-
|
|
1164
|
+
unlinkSync2(SPAWN_LOCK_PATH);
|
|
1165
|
+
} catch {
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
function connectToSocket() {
|
|
1169
|
+
return new Promise((resolve) => {
|
|
1170
|
+
if (_socket && _connected) {
|
|
1171
|
+
resolve(true);
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
const socket = net.createConnection({ path: SOCKET_PATH });
|
|
1175
|
+
const connectTimeout = setTimeout(() => {
|
|
1176
|
+
socket.destroy();
|
|
1177
|
+
resolve(false);
|
|
1178
|
+
}, 2e3);
|
|
1179
|
+
socket.on("connect", () => {
|
|
1180
|
+
clearTimeout(connectTimeout);
|
|
1181
|
+
_socket = socket;
|
|
1182
|
+
_connected = true;
|
|
1183
|
+
_buffer = "";
|
|
1184
|
+
socket.on("data", handleData);
|
|
1185
|
+
socket.on("close", () => {
|
|
1186
|
+
_connected = false;
|
|
1187
|
+
_socket = null;
|
|
1188
|
+
for (const [id, entry] of _pending) {
|
|
1189
|
+
clearTimeout(entry.timer);
|
|
1190
|
+
_pending.delete(id);
|
|
1191
|
+
entry.resolve({ error: "Connection closed" });
|
|
1192
|
+
}
|
|
1193
|
+
});
|
|
1194
|
+
socket.on("error", () => {
|
|
1195
|
+
_connected = false;
|
|
1196
|
+
_socket = null;
|
|
1197
|
+
});
|
|
1198
|
+
resolve(true);
|
|
1199
|
+
});
|
|
1200
|
+
socket.on("error", () => {
|
|
1201
|
+
clearTimeout(connectTimeout);
|
|
1202
|
+
resolve(false);
|
|
1203
|
+
});
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
async function connectEmbedDaemon() {
|
|
1207
|
+
if (_socket && _connected) return true;
|
|
1208
|
+
if (await connectToSocket()) return true;
|
|
1209
|
+
if (acquireSpawnLock()) {
|
|
1210
|
+
try {
|
|
1211
|
+
cleanupStaleFiles();
|
|
1212
|
+
spawnDaemon();
|
|
1213
|
+
} finally {
|
|
1214
|
+
releaseSpawnLock();
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
const start = Date.now();
|
|
1218
|
+
let delay2 = 100;
|
|
1219
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1220
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
1221
|
+
if (await connectToSocket()) return true;
|
|
1222
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
1223
|
+
}
|
|
1224
|
+
return false;
|
|
1225
|
+
}
|
|
1226
|
+
function sendRequest(texts, priority) {
|
|
1227
|
+
return sendDaemonRequest({ texts, priority });
|
|
1228
|
+
}
|
|
1229
|
+
function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
1230
|
+
return new Promise((resolve) => {
|
|
1231
|
+
if (!_socket || !_connected) {
|
|
1232
|
+
resolve({ error: "Not connected" });
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
const id = randomUUID();
|
|
1236
|
+
const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
|
|
1237
|
+
const timer = setTimeout(() => {
|
|
1238
|
+
_pending.delete(id);
|
|
1239
|
+
resolve({ error: "Request timeout" });
|
|
1240
|
+
}, timeoutMs);
|
|
1241
|
+
_pending.set(id, { resolve, timer });
|
|
1242
|
+
try {
|
|
1243
|
+
_socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
|
|
1244
|
+
} catch {
|
|
1245
|
+
clearTimeout(timer);
|
|
1246
|
+
_pending.delete(id);
|
|
1247
|
+
resolve({ error: "Write failed" });
|
|
1248
|
+
}
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
async function pingDaemon() {
|
|
1252
|
+
if (!_socket || !_connected) return null;
|
|
1253
|
+
const response = await sendDaemonRequest({ type: "health" }, 5e3);
|
|
1254
|
+
if (response.health) {
|
|
1255
|
+
return response.health;
|
|
1256
|
+
}
|
|
1257
|
+
return null;
|
|
1258
|
+
}
|
|
1259
|
+
function killAndRespawnDaemon() {
|
|
1260
|
+
if (!acquireSpawnLock()) {
|
|
1261
|
+
process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
|
|
1262
|
+
if (_socket) {
|
|
1263
|
+
_socket.destroy();
|
|
1264
|
+
_socket = null;
|
|
1265
|
+
}
|
|
1266
|
+
_connected = false;
|
|
1267
|
+
_buffer = "";
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
try {
|
|
1271
|
+
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
1272
|
+
if (existsSync5(PID_PATH)) {
|
|
1273
|
+
try {
|
|
1274
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
1275
|
+
if (pid > 0) {
|
|
1276
|
+
try {
|
|
1277
|
+
process.kill(pid, "SIGKILL");
|
|
1278
|
+
} catch {
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
} catch {
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
if (_socket) {
|
|
1285
|
+
_socket.destroy();
|
|
1286
|
+
_socket = null;
|
|
1287
|
+
}
|
|
1288
|
+
_connected = false;
|
|
1289
|
+
_buffer = "";
|
|
1290
|
+
try {
|
|
1291
|
+
unlinkSync2(PID_PATH);
|
|
1292
|
+
} catch {
|
|
1293
|
+
}
|
|
1294
|
+
try {
|
|
1295
|
+
unlinkSync2(SOCKET_PATH);
|
|
1296
|
+
} catch {
|
|
1297
|
+
}
|
|
1298
|
+
spawnDaemon();
|
|
1299
|
+
} finally {
|
|
1300
|
+
releaseSpawnLock();
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
function isDaemonTooYoung() {
|
|
1304
|
+
try {
|
|
1305
|
+
const stat = statSync(PID_PATH);
|
|
1306
|
+
return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
|
|
1307
|
+
} catch {
|
|
1308
|
+
return false;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
async function retryThenRestart(doRequest, label) {
|
|
1312
|
+
const result = await doRequest();
|
|
1313
|
+
if (!result.error) {
|
|
1314
|
+
_consecutiveFailures = 0;
|
|
1315
|
+
return result;
|
|
1316
|
+
}
|
|
1317
|
+
_consecutiveFailures++;
|
|
1318
|
+
for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
|
|
1319
|
+
const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
|
|
1320
|
+
process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
|
|
1321
|
+
`);
|
|
1322
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
1323
|
+
if (!_connected) {
|
|
1324
|
+
if (!await connectToSocket()) continue;
|
|
1325
|
+
}
|
|
1326
|
+
const retry = await doRequest();
|
|
1327
|
+
if (!retry.error) {
|
|
1328
|
+
_consecutiveFailures = 0;
|
|
1329
|
+
return retry;
|
|
1330
|
+
}
|
|
1331
|
+
_consecutiveFailures++;
|
|
1332
|
+
}
|
|
1333
|
+
if (isDaemonTooYoung()) {
|
|
1334
|
+
process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
|
|
1335
|
+
`);
|
|
1336
|
+
return { error: result.error };
|
|
1337
|
+
}
|
|
1338
|
+
process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
|
|
1339
|
+
`);
|
|
1340
|
+
killAndRespawnDaemon();
|
|
1341
|
+
const start = Date.now();
|
|
1342
|
+
let delay2 = 200;
|
|
1343
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1344
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
1345
|
+
if (await connectToSocket()) break;
|
|
1346
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
1347
|
+
}
|
|
1348
|
+
if (!_connected) return { error: "Daemon restart failed" };
|
|
1349
|
+
const final = await doRequest();
|
|
1350
|
+
if (!final.error) _consecutiveFailures = 0;
|
|
1351
|
+
return final;
|
|
1352
|
+
}
|
|
1353
|
+
async function embedViaClient(text, priority = "high") {
|
|
1354
|
+
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
1355
|
+
_requestCount++;
|
|
1356
|
+
if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
|
|
1357
|
+
const health = await pingDaemon();
|
|
1358
|
+
if (!health && !isDaemonTooYoung()) {
|
|
1359
|
+
process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
|
|
1360
|
+
`);
|
|
1361
|
+
killAndRespawnDaemon();
|
|
1362
|
+
const start = Date.now();
|
|
1363
|
+
let d = 200;
|
|
1364
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1365
|
+
await new Promise((r) => setTimeout(r, d));
|
|
1366
|
+
if (await connectToSocket()) break;
|
|
1367
|
+
d = Math.min(d * 2, 3e3);
|
|
1368
|
+
}
|
|
1369
|
+
if (!_connected) return null;
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
const result = await retryThenRestart(
|
|
1373
|
+
() => sendRequest([text], priority),
|
|
1374
|
+
"Embed"
|
|
1375
|
+
);
|
|
1376
|
+
return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
|
|
1377
|
+
}
|
|
1378
|
+
async function embedBatchViaClient(texts, priority = "high") {
|
|
1379
|
+
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
1380
|
+
_requestCount++;
|
|
1381
|
+
const result = await retryThenRestart(
|
|
1382
|
+
() => sendRequest(texts, priority),
|
|
1383
|
+
"Batch embed"
|
|
1384
|
+
);
|
|
1385
|
+
return !result.error && result.vectors ? result.vectors : null;
|
|
1386
|
+
}
|
|
1387
|
+
function disconnectClient() {
|
|
1388
|
+
if (_socket) {
|
|
1389
|
+
_socket.destroy();
|
|
1390
|
+
_socket = null;
|
|
1391
|
+
}
|
|
1392
|
+
_connected = false;
|
|
1393
|
+
_buffer = "";
|
|
1394
|
+
for (const [id, entry] of _pending) {
|
|
1395
|
+
clearTimeout(entry.timer);
|
|
1396
|
+
_pending.delete(id);
|
|
1397
|
+
entry.resolve({ error: "Client disconnected" });
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
function isClientConnected() {
|
|
1401
|
+
return _connected;
|
|
1402
|
+
}
|
|
1403
|
+
function sendIngestRequest(payload) {
|
|
1404
|
+
if (!_socket || !_connected) return false;
|
|
1405
|
+
try {
|
|
1406
|
+
const id = randomUUID();
|
|
1407
|
+
const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
|
|
1408
|
+
_socket.write(JSON.stringify({ id, token, type: "ingest", ...payload }) + "\n");
|
|
1409
|
+
return true;
|
|
1410
|
+
} catch {
|
|
1411
|
+
return false;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
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;
|
|
1415
|
+
var init_exe_daemon_client = __esm({
|
|
1416
|
+
"src/lib/exe-daemon-client.ts"() {
|
|
1417
|
+
"use strict";
|
|
1418
|
+
init_config();
|
|
1419
|
+
init_daemon_auth();
|
|
1420
|
+
SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
|
|
1421
|
+
PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
|
|
1422
|
+
SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
|
|
1423
|
+
SPAWN_LOCK_STALE_MS = 3e4;
|
|
1424
|
+
CONNECT_TIMEOUT_MS = 15e3;
|
|
1425
|
+
REQUEST_TIMEOUT_MS = 3e4;
|
|
1426
|
+
DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
|
|
1427
|
+
_socket = null;
|
|
1428
|
+
_connected = false;
|
|
1429
|
+
_buffer = "";
|
|
1430
|
+
_requestCount = 0;
|
|
1431
|
+
_consecutiveFailures = 0;
|
|
1432
|
+
HEALTH_CHECK_INTERVAL = 100;
|
|
1433
|
+
MAX_RETRIES_BEFORE_RESTART = 3;
|
|
1434
|
+
RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
|
|
1435
|
+
MIN_DAEMON_AGE_MS = 3e4;
|
|
1436
|
+
_pending = /* @__PURE__ */ new Map();
|
|
1437
|
+
MAX_BUFFER = 1e7;
|
|
1438
|
+
}
|
|
1439
|
+
});
|
|
1440
|
+
|
|
1441
|
+
// src/lib/daemon-protocol.ts
|
|
1442
|
+
var daemon_protocol_exports = {};
|
|
1443
|
+
__export(daemon_protocol_exports, {
|
|
1444
|
+
deserializeArgs: () => deserializeArgs,
|
|
1445
|
+
deserializeResultSet: () => deserializeResultSet,
|
|
1446
|
+
deserializeValue: () => deserializeValue,
|
|
1447
|
+
serializeArgs: () => serializeArgs,
|
|
1448
|
+
serializeResultSet: () => serializeResultSet,
|
|
1449
|
+
serializeValue: () => serializeValue
|
|
1450
|
+
});
|
|
1451
|
+
function serializeValue(v) {
|
|
1452
|
+
if (v === null || v === void 0) return null;
|
|
1453
|
+
if (typeof v === "bigint") return Number(v);
|
|
1454
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
1455
|
+
if (v instanceof Uint8Array) {
|
|
1456
|
+
return { __blob: Buffer.from(v).toString("base64") };
|
|
1457
|
+
}
|
|
1458
|
+
if (ArrayBuffer.isView(v)) {
|
|
1459
|
+
return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
|
|
1460
|
+
}
|
|
1461
|
+
if (v instanceof ArrayBuffer) {
|
|
1462
|
+
return { __blob: Buffer.from(v).toString("base64") };
|
|
1463
|
+
}
|
|
1464
|
+
if (typeof v === "string" || typeof v === "number") return v;
|
|
1465
|
+
return String(v);
|
|
1466
|
+
}
|
|
1467
|
+
function deserializeValue(v) {
|
|
1468
|
+
if (v === null) return null;
|
|
1469
|
+
if (typeof v === "object" && v !== null && "__blob" in v) {
|
|
1470
|
+
const buf = Buffer.from(v.__blob, "base64");
|
|
1471
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
1472
|
+
}
|
|
1473
|
+
return v;
|
|
1474
|
+
}
|
|
1475
|
+
function serializeArgs(args) {
|
|
1476
|
+
return args.map(serializeValue);
|
|
1477
|
+
}
|
|
1478
|
+
function deserializeArgs(args) {
|
|
1479
|
+
return args.map(deserializeValue);
|
|
1480
|
+
}
|
|
1481
|
+
function serializeResultSet(rs) {
|
|
1482
|
+
const rows = [];
|
|
1483
|
+
for (const row of rs.rows) {
|
|
1484
|
+
const obj = {};
|
|
1485
|
+
for (let i = 0; i < rs.columns.length; i++) {
|
|
1486
|
+
const col = rs.columns[i];
|
|
1487
|
+
if (col !== void 0) {
|
|
1488
|
+
obj[col] = serializeValue(row[i]);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
rows.push(obj);
|
|
1492
|
+
}
|
|
1493
|
+
return {
|
|
1494
|
+
columns: [...rs.columns],
|
|
1495
|
+
columnTypes: [...rs.columnTypes ?? []],
|
|
1496
|
+
rows,
|
|
1497
|
+
rowsAffected: typeof rs.rowsAffected === "bigint" ? Number(rs.rowsAffected) : rs.rowsAffected ?? 0,
|
|
1498
|
+
lastInsertRowid: rs.lastInsertRowid != null ? typeof rs.lastInsertRowid === "bigint" ? Number(rs.lastInsertRowid) : rs.lastInsertRowid : null
|
|
1499
|
+
};
|
|
1500
|
+
}
|
|
1501
|
+
function deserializeResultSet(srs) {
|
|
1502
|
+
const rows = srs.rows.map((obj) => {
|
|
1503
|
+
const values = srs.columns.map(
|
|
1504
|
+
(col) => deserializeValue(obj[col] ?? null)
|
|
1505
|
+
);
|
|
1506
|
+
const row = values;
|
|
1507
|
+
for (let i = 0; i < srs.columns.length; i++) {
|
|
1508
|
+
const col = srs.columns[i];
|
|
1509
|
+
if (col !== void 0) {
|
|
1510
|
+
row[col] = values[i] ?? null;
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
Object.defineProperty(row, "length", {
|
|
1514
|
+
value: values.length,
|
|
1515
|
+
enumerable: false
|
|
1516
|
+
});
|
|
1517
|
+
return row;
|
|
1518
|
+
});
|
|
1519
|
+
return {
|
|
1520
|
+
columns: srs.columns,
|
|
1521
|
+
columnTypes: srs.columnTypes ?? [],
|
|
1522
|
+
rows,
|
|
1523
|
+
rowsAffected: srs.rowsAffected,
|
|
1524
|
+
lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
|
|
1525
|
+
toJSON: () => ({
|
|
1526
|
+
columns: srs.columns,
|
|
1527
|
+
columnTypes: srs.columnTypes ?? [],
|
|
1528
|
+
rows: srs.rows,
|
|
1529
|
+
rowsAffected: srs.rowsAffected,
|
|
1530
|
+
lastInsertRowid: srs.lastInsertRowid
|
|
1531
|
+
})
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
var init_daemon_protocol = __esm({
|
|
1535
|
+
"src/lib/daemon-protocol.ts"() {
|
|
1536
|
+
"use strict";
|
|
1537
|
+
}
|
|
1538
|
+
});
|
|
1539
|
+
|
|
1540
|
+
// src/lib/db-daemon-client.ts
|
|
1541
|
+
var db_daemon_client_exports = {};
|
|
1542
|
+
__export(db_daemon_client_exports, {
|
|
1543
|
+
createDaemonDbClient: () => createDaemonDbClient,
|
|
1544
|
+
initDaemonDbClient: () => initDaemonDbClient
|
|
1545
|
+
});
|
|
1546
|
+
function normalizeStatement2(stmt) {
|
|
1547
|
+
if (typeof stmt === "string") {
|
|
1548
|
+
return { sql: stmt, args: [] };
|
|
1549
|
+
}
|
|
1550
|
+
const sql = stmt.sql;
|
|
1551
|
+
let args = [];
|
|
1552
|
+
if (Array.isArray(stmt.args)) {
|
|
1553
|
+
args = stmt.args.map((v) => serializeValue(v));
|
|
1554
|
+
} else if (stmt.args && typeof stmt.args === "object") {
|
|
1555
|
+
const named = {};
|
|
1556
|
+
for (const [key, val] of Object.entries(stmt.args)) {
|
|
1557
|
+
named[key] = serializeValue(val);
|
|
1558
|
+
}
|
|
1559
|
+
return { sql, args: named };
|
|
1560
|
+
}
|
|
1561
|
+
return { sql, args };
|
|
1562
|
+
}
|
|
1563
|
+
function createDaemonDbClient(fallbackClient) {
|
|
1564
|
+
let _useDaemon = false;
|
|
1565
|
+
const client = {
|
|
1566
|
+
async execute(stmt) {
|
|
1567
|
+
if (!_useDaemon || !isClientConnected()) {
|
|
1568
|
+
return fallbackClient.execute(stmt);
|
|
1569
|
+
}
|
|
1570
|
+
const { sql, args } = normalizeStatement2(stmt);
|
|
1571
|
+
const response = await sendDaemonRequest({
|
|
1572
|
+
type: "db-execute",
|
|
1573
|
+
sql,
|
|
1574
|
+
args
|
|
1575
|
+
});
|
|
1576
|
+
if (response.error) {
|
|
1577
|
+
const errMsg = String(response.error);
|
|
1578
|
+
if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
|
|
1579
|
+
process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
|
|
1580
|
+
`);
|
|
1581
|
+
return fallbackClient.execute(stmt);
|
|
1582
|
+
}
|
|
1583
|
+
throw new Error(errMsg);
|
|
1584
|
+
}
|
|
1585
|
+
if (response.db) {
|
|
1586
|
+
return deserializeResultSet(response.db);
|
|
1587
|
+
}
|
|
1588
|
+
process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
|
|
1589
|
+
return fallbackClient.execute(stmt);
|
|
1590
|
+
},
|
|
1591
|
+
async batch(stmts, mode) {
|
|
1592
|
+
if (!_useDaemon || !isClientConnected()) {
|
|
1593
|
+
return fallbackClient.batch(stmts, mode);
|
|
1594
|
+
}
|
|
1595
|
+
const statements = stmts.map(normalizeStatement2);
|
|
1596
|
+
const response = await sendDaemonRequest({
|
|
1597
|
+
type: "db-batch",
|
|
1598
|
+
statements,
|
|
1599
|
+
mode: mode ?? "deferred"
|
|
1600
|
+
});
|
|
1601
|
+
if (response.error) {
|
|
1602
|
+
const errMsg = String(response.error);
|
|
1603
|
+
if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
|
|
1604
|
+
process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
|
|
1605
|
+
`);
|
|
1606
|
+
return fallbackClient.batch(stmts, mode);
|
|
1607
|
+
}
|
|
1608
|
+
throw new Error(errMsg);
|
|
1609
|
+
}
|
|
1610
|
+
const batchResults = response["db-batch"];
|
|
1611
|
+
if (batchResults) {
|
|
1612
|
+
return batchResults.map(deserializeResultSet);
|
|
1613
|
+
}
|
|
1614
|
+
process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
|
|
1615
|
+
return fallbackClient.batch(stmts, mode);
|
|
1616
|
+
},
|
|
1617
|
+
// Transaction support — delegate to fallback (transactions need direct connection)
|
|
1618
|
+
async transaction(mode) {
|
|
1619
|
+
return fallbackClient.transaction(mode);
|
|
1620
|
+
},
|
|
1621
|
+
// executeMultiple — delegate to fallback (used only for schema migrations)
|
|
1622
|
+
async executeMultiple(sql) {
|
|
1623
|
+
return fallbackClient.executeMultiple(sql);
|
|
1624
|
+
},
|
|
1625
|
+
// migrate — delegate to fallback
|
|
1626
|
+
async migrate(stmts) {
|
|
1627
|
+
return fallbackClient.migrate(stmts);
|
|
1628
|
+
},
|
|
1629
|
+
// Sync mode — delegate to fallback
|
|
1630
|
+
sync() {
|
|
1631
|
+
return fallbackClient.sync();
|
|
1632
|
+
},
|
|
1633
|
+
close() {
|
|
1634
|
+
_useDaemon = false;
|
|
1635
|
+
},
|
|
1636
|
+
get closed() {
|
|
1637
|
+
return fallbackClient.closed;
|
|
1638
|
+
},
|
|
1639
|
+
get protocol() {
|
|
1640
|
+
return fallbackClient.protocol;
|
|
1641
|
+
}
|
|
1642
|
+
};
|
|
1643
|
+
return {
|
|
1644
|
+
...client,
|
|
1645
|
+
/** Enable daemon routing (call after confirming daemon is connected) */
|
|
1646
|
+
_enableDaemon() {
|
|
1647
|
+
_useDaemon = true;
|
|
1648
|
+
},
|
|
1649
|
+
/** Check if daemon routing is active */
|
|
1650
|
+
_isDaemonActive() {
|
|
1651
|
+
return _useDaemon && isClientConnected();
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
async function initDaemonDbClient(fallbackClient) {
|
|
1656
|
+
if (process.env.EXE_IS_DAEMON === "1") return null;
|
|
1657
|
+
const connected = await connectEmbedDaemon();
|
|
1658
|
+
if (!connected) {
|
|
1659
|
+
process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
|
|
1660
|
+
return null;
|
|
1661
|
+
}
|
|
1662
|
+
const client = createDaemonDbClient(fallbackClient);
|
|
1663
|
+
client._enableDaemon();
|
|
1664
|
+
process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
|
|
1665
|
+
return client;
|
|
1666
|
+
}
|
|
1667
|
+
var init_db_daemon_client = __esm({
|
|
1668
|
+
"src/lib/db-daemon-client.ts"() {
|
|
1669
|
+
"use strict";
|
|
1670
|
+
init_exe_daemon_client();
|
|
1671
|
+
init_daemon_protocol();
|
|
1672
|
+
}
|
|
1673
|
+
});
|
|
1674
|
+
|
|
1675
|
+
// src/lib/database.ts
|
|
1676
|
+
var database_exports = {};
|
|
1677
|
+
__export(database_exports, {
|
|
1678
|
+
disposeDatabase: () => disposeDatabase,
|
|
1679
|
+
disposeTurso: () => disposeTurso,
|
|
1680
|
+
ensureSchema: () => ensureSchema,
|
|
1681
|
+
getClient: () => getClient,
|
|
1682
|
+
getRawClient: () => getRawClient,
|
|
1683
|
+
initDaemonClient: () => initDaemonClient,
|
|
1684
|
+
initDatabase: () => initDatabase,
|
|
1685
|
+
initTurso: () => initTurso,
|
|
1686
|
+
isInitialized: () => isInitialized
|
|
1687
|
+
});
|
|
1688
|
+
import { createClient } from "@libsql/client";
|
|
1689
|
+
async function initDatabase(config) {
|
|
1690
|
+
if (_walCheckpointTimer) {
|
|
1691
|
+
clearInterval(_walCheckpointTimer);
|
|
1692
|
+
_walCheckpointTimer = null;
|
|
1693
|
+
}
|
|
1694
|
+
if (_daemonClient) {
|
|
1695
|
+
_daemonClient.close();
|
|
1696
|
+
_daemonClient = null;
|
|
1697
|
+
}
|
|
1698
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
1699
|
+
_adapterClient.close();
|
|
1700
|
+
}
|
|
1701
|
+
_adapterClient = null;
|
|
1702
|
+
if (_client) {
|
|
1703
|
+
_client.close();
|
|
1704
|
+
_client = null;
|
|
1705
|
+
_resilientClient = null;
|
|
1706
|
+
}
|
|
1707
|
+
const opts = {
|
|
1708
|
+
url: `file:${config.dbPath}`
|
|
1709
|
+
};
|
|
1710
|
+
if (config.encryptionKey) {
|
|
1711
|
+
opts.encryptionKey = config.encryptionKey;
|
|
1712
|
+
}
|
|
1713
|
+
_client = createClient(opts);
|
|
1714
|
+
_resilientClient = wrapWithRetry(_client);
|
|
1715
|
+
_adapterClient = _resilientClient;
|
|
1716
|
+
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
1717
|
+
});
|
|
1718
|
+
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
1719
|
+
});
|
|
1720
|
+
if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
|
|
1721
|
+
_walCheckpointTimer = setInterval(() => {
|
|
1722
|
+
_client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
|
|
1723
|
+
});
|
|
1724
|
+
}, 3e4);
|
|
1725
|
+
_walCheckpointTimer.unref();
|
|
1726
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
|
|
1727
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
function isInitialized() {
|
|
1731
|
+
return _adapterClient !== null || _client !== null;
|
|
1732
|
+
}
|
|
1733
|
+
function getClient() {
|
|
1734
|
+
if (!_adapterClient) {
|
|
1735
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
1736
|
+
}
|
|
1737
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
|
|
1738
|
+
return _adapterClient;
|
|
1739
|
+
}
|
|
1740
|
+
if (process.env.EXE_IS_DAEMON === "1") {
|
|
1741
|
+
return _resilientClient;
|
|
1742
|
+
}
|
|
1743
|
+
if (_daemonClient && _daemonClient._isDaemonActive()) {
|
|
1744
|
+
return _daemonClient;
|
|
1745
|
+
}
|
|
1746
|
+
return _resilientClient;
|
|
1747
|
+
}
|
|
1748
|
+
async function initDaemonClient() {
|
|
1749
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
|
|
1750
|
+
if (process.env.EXE_IS_DAEMON === "1") return;
|
|
1751
|
+
if (process.env.VITEST) return;
|
|
1752
|
+
if (!_resilientClient) return;
|
|
1753
|
+
if (_daemonClient) return;
|
|
1754
|
+
try {
|
|
1755
|
+
const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
|
|
1756
|
+
_daemonClient = await initDaemonDbClient2(_resilientClient);
|
|
1757
|
+
} catch (err) {
|
|
1758
|
+
process.stderr.write(
|
|
1759
|
+
`[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
|
|
1760
|
+
`
|
|
1761
|
+
);
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
function getRawClient() {
|
|
1765
|
+
if (!_client) {
|
|
1766
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
1767
|
+
}
|
|
1768
|
+
return _client;
|
|
1769
|
+
}
|
|
1770
|
+
async function ensureSchema() {
|
|
1771
|
+
const client = getRawClient();
|
|
1772
|
+
await client.execute("PRAGMA journal_mode = WAL");
|
|
1773
|
+
await client.execute("PRAGMA busy_timeout = 30000");
|
|
1774
|
+
await client.execute("PRAGMA wal_autocheckpoint = 1000");
|
|
1775
|
+
try {
|
|
1776
|
+
await client.execute("PRAGMA libsql_vector_search_ef = 128");
|
|
1777
|
+
} catch {
|
|
1778
|
+
}
|
|
1779
|
+
await client.executeMultiple(`
|
|
1780
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
1781
|
+
id TEXT PRIMARY KEY,
|
|
1782
|
+
agent_id TEXT NOT NULL,
|
|
1783
|
+
agent_role TEXT NOT NULL,
|
|
1784
|
+
session_id TEXT NOT NULL,
|
|
1785
|
+
timestamp TEXT NOT NULL,
|
|
1786
|
+
tool_name TEXT NOT NULL,
|
|
1787
|
+
project_name TEXT NOT NULL,
|
|
1788
|
+
has_error INTEGER NOT NULL DEFAULT 0,
|
|
1789
|
+
raw_text TEXT NOT NULL,
|
|
1790
|
+
vector F32_BLOB(1024),
|
|
1791
|
+
version INTEGER NOT NULL DEFAULT 0
|
|
1792
|
+
);
|
|
1793
|
+
|
|
1794
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent
|
|
1795
|
+
ON memories(agent_id);
|
|
1796
|
+
|
|
1797
|
+
CREATE INDEX IF NOT EXISTS idx_memories_timestamp
|
|
1798
|
+
ON memories(timestamp);
|
|
1799
|
+
|
|
1800
|
+
CREATE INDEX IF NOT EXISTS idx_memories_session
|
|
1801
|
+
ON memories(session_id);
|
|
1802
|
+
|
|
1803
|
+
CREATE INDEX IF NOT EXISTS idx_memories_project
|
|
1804
|
+
ON memories(project_name);
|
|
1805
|
+
|
|
1806
|
+
CREATE INDEX IF NOT EXISTS idx_memories_tool
|
|
1807
|
+
ON memories(tool_name);
|
|
1808
|
+
|
|
1809
|
+
CREATE INDEX IF NOT EXISTS idx_memories_version
|
|
1810
|
+
ON memories(version);
|
|
1811
|
+
|
|
1812
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
1813
|
+
ON memories(agent_id, project_name);
|
|
1814
|
+
`);
|
|
1815
|
+
await client.executeMultiple(`
|
|
1816
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
1817
|
+
raw_text,
|
|
1818
|
+
content='memories',
|
|
1819
|
+
content_rowid='rowid'
|
|
1820
|
+
);
|
|
1821
|
+
|
|
1822
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
1823
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1824
|
+
END;
|
|
1825
|
+
|
|
1826
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
1827
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1828
|
+
END;
|
|
1829
|
+
|
|
1830
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
1831
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1832
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1833
|
+
END;
|
|
1834
|
+
`);
|
|
1835
|
+
await client.executeMultiple(`
|
|
1836
|
+
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
1837
|
+
key TEXT PRIMARY KEY,
|
|
1838
|
+
value TEXT NOT NULL
|
|
1839
|
+
);
|
|
1840
|
+
`);
|
|
1841
|
+
await client.executeMultiple(`
|
|
1842
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
1843
|
+
id TEXT PRIMARY KEY,
|
|
1844
|
+
title TEXT NOT NULL,
|
|
1845
|
+
assigned_to TEXT NOT NULL,
|
|
1846
|
+
assigned_by TEXT NOT NULL,
|
|
1847
|
+
project_name TEXT NOT NULL,
|
|
1848
|
+
priority TEXT NOT NULL DEFAULT 'p1',
|
|
1849
|
+
status TEXT NOT NULL DEFAULT 'open',
|
|
1850
|
+
task_file TEXT,
|
|
1851
|
+
created_at TEXT NOT NULL,
|
|
1852
|
+
updated_at TEXT NOT NULL
|
|
1853
|
+
);
|
|
1854
|
+
|
|
1855
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
1856
|
+
ON tasks(assigned_to, status);
|
|
1857
|
+
`);
|
|
1858
|
+
await client.executeMultiple(`
|
|
1859
|
+
CREATE TABLE IF NOT EXISTS behaviors (
|
|
1860
|
+
id TEXT PRIMARY KEY,
|
|
1861
|
+
agent_id TEXT NOT NULL,
|
|
1862
|
+
project_name TEXT,
|
|
1863
|
+
domain TEXT,
|
|
1864
|
+
content TEXT NOT NULL,
|
|
1865
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1866
|
+
created_at TEXT NOT NULL,
|
|
1867
|
+
updated_at TEXT NOT NULL
|
|
1868
|
+
);
|
|
1869
|
+
|
|
1870
|
+
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
1871
|
+
ON behaviors(agent_id, active);
|
|
1872
|
+
`);
|
|
1873
|
+
try {
|
|
1874
|
+
const coordinatorName = getCoordinatorName();
|
|
1875
|
+
const existing = await client.execute({
|
|
1876
|
+
sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
|
|
1877
|
+
args: [coordinatorName]
|
|
1878
|
+
});
|
|
1879
|
+
if (Number(existing.rows[0]?.cnt) === 0) {
|
|
1880
|
+
const seededAt = "2026-03-25T00:00:00Z";
|
|
1881
|
+
for (const [domain, content] of [
|
|
1882
|
+
["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
|
|
1883
|
+
["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
|
|
1884
|
+
["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
|
|
1885
|
+
]) {
|
|
1886
|
+
await client.execute({
|
|
1887
|
+
sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
1888
|
+
VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
|
|
1889
|
+
args: [coordinatorName, domain, content, seededAt, seededAt]
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
1893
|
+
} catch {
|
|
1894
|
+
}
|
|
1895
|
+
try {
|
|
1896
|
+
await client.execute({
|
|
1897
|
+
sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
|
|
1898
|
+
args: []
|
|
1899
|
+
});
|
|
1900
|
+
} catch {
|
|
1901
|
+
}
|
|
1902
|
+
try {
|
|
1903
|
+
await client.execute({
|
|
1904
|
+
sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
|
|
1105
1905
|
args: []
|
|
1106
1906
|
});
|
|
1107
1907
|
} catch {
|
|
@@ -1950,19 +2750,152 @@ async function ensureSchema() {
|
|
|
1950
2750
|
} catch {
|
|
1951
2751
|
}
|
|
1952
2752
|
}
|
|
1953
|
-
|
|
2753
|
+
async function disposeDatabase() {
|
|
2754
|
+
if (_walCheckpointTimer) {
|
|
2755
|
+
clearInterval(_walCheckpointTimer);
|
|
2756
|
+
_walCheckpointTimer = null;
|
|
2757
|
+
}
|
|
2758
|
+
if (_daemonClient) {
|
|
2759
|
+
_daemonClient.close();
|
|
2760
|
+
_daemonClient = null;
|
|
2761
|
+
}
|
|
2762
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
2763
|
+
_adapterClient.close();
|
|
2764
|
+
}
|
|
2765
|
+
_adapterClient = null;
|
|
2766
|
+
if (_client) {
|
|
2767
|
+
_client.close();
|
|
2768
|
+
_client = null;
|
|
2769
|
+
_resilientClient = null;
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
|
|
1954
2773
|
var init_database = __esm({
|
|
1955
2774
|
"src/lib/database.ts"() {
|
|
1956
2775
|
"use strict";
|
|
1957
2776
|
init_db_retry();
|
|
1958
2777
|
init_employees();
|
|
1959
2778
|
init_database_adapter();
|
|
2779
|
+
init_memory();
|
|
1960
2780
|
_client = null;
|
|
1961
2781
|
_resilientClient = null;
|
|
1962
2782
|
_walCheckpointTimer = null;
|
|
1963
2783
|
_daemonClient = null;
|
|
1964
2784
|
_adapterClient = null;
|
|
1965
2785
|
initTurso = initDatabase;
|
|
2786
|
+
disposeTurso = disposeDatabase;
|
|
2787
|
+
}
|
|
2788
|
+
});
|
|
2789
|
+
|
|
2790
|
+
// src/lib/keychain.ts
|
|
2791
|
+
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2792
|
+
import { existsSync as existsSync6 } from "fs";
|
|
2793
|
+
import path6 from "path";
|
|
2794
|
+
import os5 from "os";
|
|
2795
|
+
function getKeyDir() {
|
|
2796
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
|
|
2797
|
+
}
|
|
2798
|
+
function getKeyPath() {
|
|
2799
|
+
return path6.join(getKeyDir(), "master.key");
|
|
2800
|
+
}
|
|
2801
|
+
async function tryKeytar() {
|
|
2802
|
+
try {
|
|
2803
|
+
return await import("keytar");
|
|
2804
|
+
} catch {
|
|
2805
|
+
return null;
|
|
2806
|
+
}
|
|
2807
|
+
}
|
|
2808
|
+
async function getMasterKey() {
|
|
2809
|
+
const keytar = await tryKeytar();
|
|
2810
|
+
if (keytar) {
|
|
2811
|
+
try {
|
|
2812
|
+
const stored = await keytar.getPassword(SERVICE, ACCOUNT);
|
|
2813
|
+
if (stored) {
|
|
2814
|
+
return Buffer.from(stored, "base64");
|
|
2815
|
+
}
|
|
2816
|
+
} catch {
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2819
|
+
const keyPath = getKeyPath();
|
|
2820
|
+
if (!existsSync6(keyPath)) {
|
|
2821
|
+
process.stderr.write(
|
|
2822
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2823
|
+
`
|
|
2824
|
+
);
|
|
2825
|
+
return null;
|
|
2826
|
+
}
|
|
2827
|
+
try {
|
|
2828
|
+
const content = await readFile3(keyPath, "utf-8");
|
|
2829
|
+
return Buffer.from(content.trim(), "base64");
|
|
2830
|
+
} catch (err) {
|
|
2831
|
+
process.stderr.write(
|
|
2832
|
+
`[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
|
|
2833
|
+
`
|
|
2834
|
+
);
|
|
2835
|
+
return null;
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
var SERVICE, ACCOUNT;
|
|
2839
|
+
var init_keychain = __esm({
|
|
2840
|
+
"src/lib/keychain.ts"() {
|
|
2841
|
+
"use strict";
|
|
2842
|
+
SERVICE = "exe-mem";
|
|
2843
|
+
ACCOUNT = "master-key";
|
|
2844
|
+
}
|
|
2845
|
+
});
|
|
2846
|
+
|
|
2847
|
+
// src/lib/state-bus.ts
|
|
2848
|
+
var StateBus, orgBus;
|
|
2849
|
+
var init_state_bus = __esm({
|
|
2850
|
+
"src/lib/state-bus.ts"() {
|
|
2851
|
+
"use strict";
|
|
2852
|
+
StateBus = class {
|
|
2853
|
+
handlers = /* @__PURE__ */ new Map();
|
|
2854
|
+
globalHandlers = /* @__PURE__ */ new Set();
|
|
2855
|
+
/** Emit an event to all subscribers */
|
|
2856
|
+
emit(event) {
|
|
2857
|
+
const typeHandlers = this.handlers.get(event.type);
|
|
2858
|
+
if (typeHandlers) {
|
|
2859
|
+
for (const handler of typeHandlers) {
|
|
2860
|
+
try {
|
|
2861
|
+
handler(event);
|
|
2862
|
+
} catch {
|
|
2863
|
+
}
|
|
2864
|
+
}
|
|
2865
|
+
}
|
|
2866
|
+
for (const handler of this.globalHandlers) {
|
|
2867
|
+
try {
|
|
2868
|
+
handler(event);
|
|
2869
|
+
} catch {
|
|
2870
|
+
}
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
/** Subscribe to a specific event type */
|
|
2874
|
+
on(type, handler) {
|
|
2875
|
+
if (!this.handlers.has(type)) {
|
|
2876
|
+
this.handlers.set(type, /* @__PURE__ */ new Set());
|
|
2877
|
+
}
|
|
2878
|
+
this.handlers.get(type).add(handler);
|
|
2879
|
+
}
|
|
2880
|
+
/** Subscribe to ALL events */
|
|
2881
|
+
onAny(handler) {
|
|
2882
|
+
this.globalHandlers.add(handler);
|
|
2883
|
+
}
|
|
2884
|
+
/** Unsubscribe from a specific event type */
|
|
2885
|
+
off(type, handler) {
|
|
2886
|
+
this.handlers.get(type)?.delete(handler);
|
|
2887
|
+
}
|
|
2888
|
+
/** Unsubscribe from ALL events */
|
|
2889
|
+
offAny(handler) {
|
|
2890
|
+
this.globalHandlers.delete(handler);
|
|
2891
|
+
}
|
|
2892
|
+
/** Remove all listeners */
|
|
2893
|
+
clear() {
|
|
2894
|
+
this.handlers.clear();
|
|
2895
|
+
this.globalHandlers.clear();
|
|
2896
|
+
}
|
|
2897
|
+
};
|
|
2898
|
+
orgBus = new StateBus();
|
|
1966
2899
|
}
|
|
1967
2900
|
});
|
|
1968
2901
|
|
|
@@ -1980,12 +2913,12 @@ __export(shard_manager_exports, {
|
|
|
1980
2913
|
listShards: () => listShards,
|
|
1981
2914
|
shardExists: () => shardExists
|
|
1982
2915
|
});
|
|
1983
|
-
import
|
|
1984
|
-
import { existsSync as
|
|
2916
|
+
import path7 from "path";
|
|
2917
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
|
|
1985
2918
|
import { createClient as createClient2 } from "@libsql/client";
|
|
1986
2919
|
function initShardManager(encryptionKey) {
|
|
1987
2920
|
_encryptionKey = encryptionKey;
|
|
1988
|
-
if (!
|
|
2921
|
+
if (!existsSync7(SHARDS_DIR)) {
|
|
1989
2922
|
mkdirSync2(SHARDS_DIR, { recursive: true });
|
|
1990
2923
|
}
|
|
1991
2924
|
_shardingEnabled = true;
|
|
@@ -2015,7 +2948,7 @@ function getShardClient(projectName) {
|
|
|
2015
2948
|
while (_shards.size >= MAX_OPEN_SHARDS) {
|
|
2016
2949
|
evictLRU();
|
|
2017
2950
|
}
|
|
2018
|
-
const dbPath =
|
|
2951
|
+
const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
|
|
2019
2952
|
const client = createClient2({
|
|
2020
2953
|
url: `file:${dbPath}`,
|
|
2021
2954
|
encryptionKey: _encryptionKey
|
|
@@ -2026,10 +2959,10 @@ function getShardClient(projectName) {
|
|
|
2026
2959
|
}
|
|
2027
2960
|
function shardExists(projectName) {
|
|
2028
2961
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
2029
|
-
return
|
|
2962
|
+
return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
|
|
2030
2963
|
}
|
|
2031
2964
|
function listShards() {
|
|
2032
|
-
if (!
|
|
2965
|
+
if (!existsSync7(SHARDS_DIR)) return [];
|
|
2033
2966
|
return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
2034
2967
|
}
|
|
2035
2968
|
async function ensureShardSchema(client) {
|
|
@@ -2276,7 +3209,7 @@ var init_shard_manager = __esm({
|
|
|
2276
3209
|
"src/lib/shard-manager.ts"() {
|
|
2277
3210
|
"use strict";
|
|
2278
3211
|
init_config();
|
|
2279
|
-
SHARDS_DIR =
|
|
3212
|
+
SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
|
|
2280
3213
|
SHARD_IDLE_MS = 5 * 60 * 1e3;
|
|
2281
3214
|
MAX_OPEN_SHARDS = 10;
|
|
2282
3215
|
EVICTION_INTERVAL_MS = 60 * 1e3;
|
|
@@ -2396,6 +3329,68 @@ var init_platform_procedures = __esm({
|
|
|
2396
3329
|
domain: "architecture",
|
|
2397
3330
|
priority: "p0",
|
|
2398
3331
|
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."
|
|
3332
|
+
},
|
|
3333
|
+
// --- MCP is the ONLY data interface ---
|
|
3334
|
+
{
|
|
3335
|
+
title: "MCP disconnect \u2014 ask the user, never work around it",
|
|
3336
|
+
domain: "workflow",
|
|
3337
|
+
priority: "p0",
|
|
3338
|
+
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."
|
|
3339
|
+
},
|
|
3340
|
+
// --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
|
|
3341
|
+
{
|
|
3342
|
+
title: "MCP tools \u2014 memory and search",
|
|
3343
|
+
domain: "tool-use",
|
|
3344
|
+
priority: "p1",
|
|
3345
|
+
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)."
|
|
3346
|
+
},
|
|
3347
|
+
{
|
|
3348
|
+
title: "MCP tools \u2014 task orchestration",
|
|
3349
|
+
domain: "tool-use",
|
|
3350
|
+
priority: "p1",
|
|
3351
|
+
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."
|
|
3352
|
+
},
|
|
3353
|
+
{
|
|
3354
|
+
title: "MCP tools \u2014 knowledge graph (GraphRAG)",
|
|
3355
|
+
domain: "tool-use",
|
|
3356
|
+
priority: "p1",
|
|
3357
|
+
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."
|
|
3358
|
+
},
|
|
3359
|
+
{
|
|
3360
|
+
title: "MCP tools \u2014 identity, behavior, and decisions",
|
|
3361
|
+
domain: "tool-use",
|
|
3362
|
+
priority: "p1",
|
|
3363
|
+
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."
|
|
3364
|
+
},
|
|
3365
|
+
{
|
|
3366
|
+
title: "MCP tools \u2014 communication and messaging",
|
|
3367
|
+
domain: "tool-use",
|
|
3368
|
+
priority: "p1",
|
|
3369
|
+
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.)."
|
|
3370
|
+
},
|
|
3371
|
+
{
|
|
3372
|
+
title: "MCP tools \u2014 wiki, documents, and content",
|
|
3373
|
+
domain: "tool-use",
|
|
3374
|
+
priority: "p1",
|
|
3375
|
+
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."
|
|
3376
|
+
},
|
|
3377
|
+
{
|
|
3378
|
+
title: "MCP tools \u2014 system, operations, and admin",
|
|
3379
|
+
domain: "tool-use",
|
|
3380
|
+
priority: "p1",
|
|
3381
|
+
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."
|
|
3382
|
+
},
|
|
3383
|
+
{
|
|
3384
|
+
title: "MCP tools \u2014 config, licensing, and team",
|
|
3385
|
+
domain: "tool-use",
|
|
3386
|
+
priority: "p1",
|
|
3387
|
+
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."
|
|
3388
|
+
},
|
|
3389
|
+
{
|
|
3390
|
+
title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
|
|
3391
|
+
domain: "tool-use",
|
|
3392
|
+
priority: "p1",
|
|
3393
|
+
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."
|
|
2399
3394
|
}
|
|
2400
3395
|
];
|
|
2401
3396
|
PLATFORM_PROCEDURE_TITLES = new Set(
|
|
@@ -2412,7 +3407,7 @@ __export(global_procedures_exports, {
|
|
|
2412
3407
|
loadGlobalProcedures: () => loadGlobalProcedures,
|
|
2413
3408
|
storeGlobalProcedure: () => storeGlobalProcedure
|
|
2414
3409
|
});
|
|
2415
|
-
import { randomUUID } from "crypto";
|
|
3410
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2416
3411
|
async function loadGlobalProcedures() {
|
|
2417
3412
|
const client = getClient();
|
|
2418
3413
|
const result = await client.execute({
|
|
@@ -2441,7 +3436,7 @@ ${sections.join("\n\n")}
|
|
|
2441
3436
|
`;
|
|
2442
3437
|
}
|
|
2443
3438
|
async function storeGlobalProcedure(input) {
|
|
2444
|
-
const id =
|
|
3439
|
+
const id = randomUUID2();
|
|
2445
3440
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2446
3441
|
const client = getClient();
|
|
2447
3442
|
await client.execute({
|
|
@@ -2475,125 +3470,25 @@ ${p.content}`).join("\n\n");
|
|
|
2475
3470
|
}
|
|
2476
3471
|
});
|
|
2477
3472
|
|
|
2478
|
-
// src/bin/exe-review.ts
|
|
2479
|
-
init_employees();
|
|
2480
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
2481
|
-
|
|
2482
3473
|
// src/lib/store.ts
|
|
3474
|
+
var store_exports = {};
|
|
3475
|
+
__export(store_exports, {
|
|
3476
|
+
attachDocumentMetadata: () => attachDocumentMetadata,
|
|
3477
|
+
buildRawVisibilityFilter: () => buildRawVisibilityFilter,
|
|
3478
|
+
buildWikiScopeFilter: () => buildWikiScopeFilter,
|
|
3479
|
+
classifyTier: () => classifyTier,
|
|
3480
|
+
disposeStore: () => disposeStore,
|
|
3481
|
+
flushBatch: () => flushBatch,
|
|
3482
|
+
flushTier3: () => flushTier3,
|
|
3483
|
+
getMemoryCardinality: () => getMemoryCardinality,
|
|
3484
|
+
initStore: () => initStore,
|
|
3485
|
+
reserveVersions: () => reserveVersions,
|
|
3486
|
+
searchMemories: () => searchMemories,
|
|
3487
|
+
updateMemoryStatus: () => updateMemoryStatus,
|
|
3488
|
+
vectorToBlob: () => vectorToBlob,
|
|
3489
|
+
writeMemory: () => writeMemory
|
|
3490
|
+
});
|
|
2483
3491
|
import { createHash } from "crypto";
|
|
2484
|
-
|
|
2485
|
-
// src/types/memory.ts
|
|
2486
|
-
var EMBEDDING_DIM = 1024;
|
|
2487
|
-
|
|
2488
|
-
// src/lib/store.ts
|
|
2489
|
-
init_database();
|
|
2490
|
-
|
|
2491
|
-
// src/lib/keychain.ts
|
|
2492
|
-
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2493
|
-
import { existsSync as existsSync4 } from "fs";
|
|
2494
|
-
import path4 from "path";
|
|
2495
|
-
import os4 from "os";
|
|
2496
|
-
var SERVICE = "exe-mem";
|
|
2497
|
-
var ACCOUNT = "master-key";
|
|
2498
|
-
function getKeyDir() {
|
|
2499
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path4.join(os4.homedir(), ".exe-os");
|
|
2500
|
-
}
|
|
2501
|
-
function getKeyPath() {
|
|
2502
|
-
return path4.join(getKeyDir(), "master.key");
|
|
2503
|
-
}
|
|
2504
|
-
async function tryKeytar() {
|
|
2505
|
-
try {
|
|
2506
|
-
return await import("keytar");
|
|
2507
|
-
} catch {
|
|
2508
|
-
return null;
|
|
2509
|
-
}
|
|
2510
|
-
}
|
|
2511
|
-
async function getMasterKey() {
|
|
2512
|
-
const keytar = await tryKeytar();
|
|
2513
|
-
if (keytar) {
|
|
2514
|
-
try {
|
|
2515
|
-
const stored = await keytar.getPassword(SERVICE, ACCOUNT);
|
|
2516
|
-
if (stored) {
|
|
2517
|
-
return Buffer.from(stored, "base64");
|
|
2518
|
-
}
|
|
2519
|
-
} catch {
|
|
2520
|
-
}
|
|
2521
|
-
}
|
|
2522
|
-
const keyPath = getKeyPath();
|
|
2523
|
-
if (!existsSync4(keyPath)) {
|
|
2524
|
-
process.stderr.write(
|
|
2525
|
-
`[keychain] Key not found at ${keyPath} (HOME=${os4.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2526
|
-
`
|
|
2527
|
-
);
|
|
2528
|
-
return null;
|
|
2529
|
-
}
|
|
2530
|
-
try {
|
|
2531
|
-
const content = await readFile3(keyPath, "utf-8");
|
|
2532
|
-
return Buffer.from(content.trim(), "base64");
|
|
2533
|
-
} catch (err) {
|
|
2534
|
-
process.stderr.write(
|
|
2535
|
-
`[keychain] Key read failed at ${keyPath}: ${err instanceof Error ? err.message : String(err)}
|
|
2536
|
-
`
|
|
2537
|
-
);
|
|
2538
|
-
return null;
|
|
2539
|
-
}
|
|
2540
|
-
}
|
|
2541
|
-
|
|
2542
|
-
// src/lib/store.ts
|
|
2543
|
-
init_config();
|
|
2544
|
-
|
|
2545
|
-
// src/lib/state-bus.ts
|
|
2546
|
-
var StateBus = class {
|
|
2547
|
-
handlers = /* @__PURE__ */ new Map();
|
|
2548
|
-
globalHandlers = /* @__PURE__ */ new Set();
|
|
2549
|
-
/** Emit an event to all subscribers */
|
|
2550
|
-
emit(event) {
|
|
2551
|
-
const typeHandlers = this.handlers.get(event.type);
|
|
2552
|
-
if (typeHandlers) {
|
|
2553
|
-
for (const handler of typeHandlers) {
|
|
2554
|
-
try {
|
|
2555
|
-
handler(event);
|
|
2556
|
-
} catch {
|
|
2557
|
-
}
|
|
2558
|
-
}
|
|
2559
|
-
}
|
|
2560
|
-
for (const handler of this.globalHandlers) {
|
|
2561
|
-
try {
|
|
2562
|
-
handler(event);
|
|
2563
|
-
} catch {
|
|
2564
|
-
}
|
|
2565
|
-
}
|
|
2566
|
-
}
|
|
2567
|
-
/** Subscribe to a specific event type */
|
|
2568
|
-
on(type, handler) {
|
|
2569
|
-
if (!this.handlers.has(type)) {
|
|
2570
|
-
this.handlers.set(type, /* @__PURE__ */ new Set());
|
|
2571
|
-
}
|
|
2572
|
-
this.handlers.get(type).add(handler);
|
|
2573
|
-
}
|
|
2574
|
-
/** Subscribe to ALL events */
|
|
2575
|
-
onAny(handler) {
|
|
2576
|
-
this.globalHandlers.add(handler);
|
|
2577
|
-
}
|
|
2578
|
-
/** Unsubscribe from a specific event type */
|
|
2579
|
-
off(type, handler) {
|
|
2580
|
-
this.handlers.get(type)?.delete(handler);
|
|
2581
|
-
}
|
|
2582
|
-
/** Unsubscribe from ALL events */
|
|
2583
|
-
offAny(handler) {
|
|
2584
|
-
this.globalHandlers.delete(handler);
|
|
2585
|
-
}
|
|
2586
|
-
/** Remove all listeners */
|
|
2587
|
-
clear() {
|
|
2588
|
-
this.handlers.clear();
|
|
2589
|
-
this.globalHandlers.clear();
|
|
2590
|
-
}
|
|
2591
|
-
};
|
|
2592
|
-
var orgBus = new StateBus();
|
|
2593
|
-
|
|
2594
|
-
// src/lib/store.ts
|
|
2595
|
-
var INIT_MAX_RETRIES = 3;
|
|
2596
|
-
var INIT_RETRY_DELAY_MS = 1e3;
|
|
2597
3492
|
function isBusyError2(err) {
|
|
2598
3493
|
if (err instanceof Error) {
|
|
2599
3494
|
const msg = err.message.toLowerCase();
|
|
@@ -2616,12 +3511,6 @@ async function retryOnBusy2(fn, label) {
|
|
|
2616
3511
|
}
|
|
2617
3512
|
throw new Error("unreachable");
|
|
2618
3513
|
}
|
|
2619
|
-
var _pendingRecords = [];
|
|
2620
|
-
var _batchSize = 20;
|
|
2621
|
-
var _flushIntervalMs = 1e4;
|
|
2622
|
-
var _flushTimer = null;
|
|
2623
|
-
var _flushing = false;
|
|
2624
|
-
var _nextVersion = 1;
|
|
2625
3514
|
async function initStore(options) {
|
|
2626
3515
|
if (_flushTimer !== null) {
|
|
2627
3516
|
clearInterval(_flushTimer);
|
|
@@ -2651,6 +3540,11 @@ async function initStore(options) {
|
|
|
2651
3540
|
encryptionKey: hexKey
|
|
2652
3541
|
});
|
|
2653
3542
|
await retryOnBusy2(() => ensureSchema(), "ensureSchema");
|
|
3543
|
+
try {
|
|
3544
|
+
const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
|
|
3545
|
+
await initDaemonClient2();
|
|
3546
|
+
} catch {
|
|
3547
|
+
}
|
|
2654
3548
|
if (!options?.lightweight) {
|
|
2655
3549
|
try {
|
|
2656
3550
|
const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
@@ -2938,23 +3832,311 @@ async function flushBatch() {
|
|
|
2938
3832
|
_flushing = false;
|
|
2939
3833
|
}
|
|
2940
3834
|
}
|
|
3835
|
+
function buildWikiScopeFilter(options, columnPrefix) {
|
|
3836
|
+
const args = [];
|
|
3837
|
+
let clause = "";
|
|
3838
|
+
if (options?.workspaceId !== void 0) {
|
|
3839
|
+
clause += ` AND ${columnPrefix}workspace_id = ?`;
|
|
3840
|
+
args.push(options.workspaceId);
|
|
3841
|
+
}
|
|
3842
|
+
if (options?.userId === void 0) {
|
|
3843
|
+
clause += ` AND ${columnPrefix}user_id IS NULL`;
|
|
3844
|
+
} else if (options.userId === null) {
|
|
3845
|
+
clause += ` AND ${columnPrefix}user_id IS NULL`;
|
|
3846
|
+
} else {
|
|
3847
|
+
clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
|
|
3848
|
+
args.push(options.userId);
|
|
3849
|
+
}
|
|
3850
|
+
return { clause, args };
|
|
3851
|
+
}
|
|
3852
|
+
function buildRawVisibilityFilter(options, columnPrefix) {
|
|
3853
|
+
if (options?.includeRaw === false) {
|
|
3854
|
+
return {
|
|
3855
|
+
clause: ` AND COALESCE(${columnPrefix}memory_type, 'raw') != 'raw'`,
|
|
3856
|
+
args: []
|
|
3857
|
+
};
|
|
3858
|
+
}
|
|
3859
|
+
return { clause: "", args: [] };
|
|
3860
|
+
}
|
|
3861
|
+
async function searchMemories(queryVector, agentId, options) {
|
|
3862
|
+
let client;
|
|
3863
|
+
try {
|
|
3864
|
+
const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
3865
|
+
if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
|
|
3866
|
+
client = await getReadyShardClient2(options.projectName);
|
|
3867
|
+
} else {
|
|
3868
|
+
client = getClient();
|
|
3869
|
+
}
|
|
3870
|
+
} catch {
|
|
3871
|
+
client = getClient();
|
|
3872
|
+
}
|
|
3873
|
+
const limit = options?.limit ?? 10;
|
|
3874
|
+
const statusFilter = options?.includeArchived ? "" : `
|
|
3875
|
+
AND COALESCE(status, 'active') = 'active'`;
|
|
3876
|
+
const draftFilter = options?.includeDrafts ? "" : `
|
|
3877
|
+
AND (draft = 0 OR draft IS NULL)`;
|
|
3878
|
+
let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
|
|
3879
|
+
tool_name, project_name,
|
|
3880
|
+
has_error, raw_text, vector, importance, status,
|
|
3881
|
+
confidence, last_accessed,
|
|
3882
|
+
workspace_id, document_id, user_id,
|
|
3883
|
+
char_offset, page_number,
|
|
3884
|
+
source_path, source_type
|
|
3885
|
+
FROM memories
|
|
3886
|
+
WHERE agent_id = ?
|
|
3887
|
+
AND vector IS NOT NULL${statusFilter}${draftFilter}
|
|
3888
|
+
AND COALESCE(confidence, 0.7) >= 0.3`;
|
|
3889
|
+
const args = [agentId];
|
|
3890
|
+
const scope = buildWikiScopeFilter(options, "");
|
|
3891
|
+
sql += scope.clause;
|
|
3892
|
+
args.push(...scope.args);
|
|
3893
|
+
const rawVisibility = buildRawVisibilityFilter(options, "");
|
|
3894
|
+
sql += rawVisibility.clause;
|
|
3895
|
+
args.push(...rawVisibility.args);
|
|
3896
|
+
if (options?.projectName) {
|
|
3897
|
+
sql += ` AND project_name = ?`;
|
|
3898
|
+
args.push(options.projectName);
|
|
3899
|
+
}
|
|
3900
|
+
if (options?.toolName) {
|
|
3901
|
+
sql += ` AND tool_name = ?`;
|
|
3902
|
+
args.push(options.toolName);
|
|
3903
|
+
}
|
|
3904
|
+
if (options?.hasError !== void 0) {
|
|
3905
|
+
sql += ` AND has_error = ?`;
|
|
3906
|
+
args.push(options.hasError ? 1 : 0);
|
|
3907
|
+
}
|
|
3908
|
+
if (options?.since) {
|
|
3909
|
+
sql += ` AND timestamp >= ?`;
|
|
3910
|
+
args.push(options.since);
|
|
3911
|
+
}
|
|
3912
|
+
if (options?.memoryType) {
|
|
3913
|
+
sql += ` AND memory_type = ?`;
|
|
3914
|
+
args.push(options.memoryType);
|
|
3915
|
+
}
|
|
3916
|
+
sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
|
|
3917
|
+
args.push(vectorToBlob(queryVector));
|
|
3918
|
+
sql += ` LIMIT ?`;
|
|
3919
|
+
args.push(limit);
|
|
3920
|
+
const result = await client.execute({ sql, args });
|
|
3921
|
+
return result.rows.map((row) => ({
|
|
3922
|
+
id: row.id,
|
|
3923
|
+
agent_id: row.agent_id,
|
|
3924
|
+
agent_role: row.agent_role,
|
|
3925
|
+
session_id: row.session_id,
|
|
3926
|
+
timestamp: row.timestamp,
|
|
3927
|
+
tool_name: row.tool_name,
|
|
3928
|
+
project_name: row.project_name,
|
|
3929
|
+
has_error: row.has_error === 1,
|
|
3930
|
+
raw_text: row.raw_text,
|
|
3931
|
+
vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
|
|
3932
|
+
importance: row.importance ?? 5,
|
|
3933
|
+
status: row.status ?? "active",
|
|
3934
|
+
confidence: row.confidence ?? 0.7,
|
|
3935
|
+
last_accessed: row.last_accessed ?? row.timestamp,
|
|
3936
|
+
workspace_id: row.workspace_id ?? null,
|
|
3937
|
+
document_id: row.document_id ?? null,
|
|
3938
|
+
user_id: row.user_id ?? null,
|
|
3939
|
+
char_offset: row.char_offset ?? null,
|
|
3940
|
+
page_number: row.page_number ?? null,
|
|
3941
|
+
source_path: row.source_path ?? null,
|
|
3942
|
+
source_type: row.source_type ?? null
|
|
3943
|
+
}));
|
|
3944
|
+
}
|
|
3945
|
+
async function attachDocumentMetadata(records) {
|
|
3946
|
+
const docIds = [
|
|
3947
|
+
...new Set(
|
|
3948
|
+
records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
|
|
3949
|
+
)
|
|
3950
|
+
];
|
|
3951
|
+
if (docIds.length === 0) return records;
|
|
3952
|
+
try {
|
|
3953
|
+
const client = getClient();
|
|
3954
|
+
const placeholders = docIds.map(() => "?").join(",");
|
|
3955
|
+
const result = await client.execute({
|
|
3956
|
+
sql: `SELECT id, filename, mime, source_type, uploaded_at
|
|
3957
|
+
FROM documents
|
|
3958
|
+
WHERE id IN (${placeholders})`,
|
|
3959
|
+
args: docIds
|
|
3960
|
+
});
|
|
3961
|
+
const byId = /* @__PURE__ */ new Map();
|
|
3962
|
+
for (const row of result.rows) {
|
|
3963
|
+
const id = row.id;
|
|
3964
|
+
byId.set(id, {
|
|
3965
|
+
document_id: id,
|
|
3966
|
+
filename: row.filename,
|
|
3967
|
+
mime: row.mime ?? null,
|
|
3968
|
+
source_type: row.source_type ?? null,
|
|
3969
|
+
uploaded_at: row.uploaded_at
|
|
3970
|
+
});
|
|
3971
|
+
}
|
|
3972
|
+
for (const record of records) {
|
|
3973
|
+
if (!record.document_id) continue;
|
|
3974
|
+
record.document_metadata = byId.get(record.document_id) ?? null;
|
|
3975
|
+
}
|
|
3976
|
+
} catch {
|
|
3977
|
+
}
|
|
3978
|
+
return records;
|
|
3979
|
+
}
|
|
3980
|
+
async function flushTier3(agentId, options) {
|
|
3981
|
+
const client = getClient();
|
|
3982
|
+
const maxAge = options?.maxAgeHours ?? 72;
|
|
3983
|
+
const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
|
|
3984
|
+
if (options?.dryRun) {
|
|
3985
|
+
const result2 = await client.execute({
|
|
3986
|
+
sql: `SELECT COUNT(*) as cnt FROM memories
|
|
3987
|
+
WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
|
|
3988
|
+
args: [agentId, cutoff]
|
|
3989
|
+
});
|
|
3990
|
+
return { archived: Number(result2.rows[0]?.cnt ?? 0) };
|
|
3991
|
+
}
|
|
3992
|
+
const result = await client.execute({
|
|
3993
|
+
sql: `UPDATE memories SET status = 'archived'
|
|
3994
|
+
WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
|
|
3995
|
+
args: [agentId, cutoff]
|
|
3996
|
+
});
|
|
3997
|
+
return { archived: result.rowsAffected };
|
|
3998
|
+
}
|
|
3999
|
+
async function disposeStore() {
|
|
4000
|
+
if (_flushTimer !== null) {
|
|
4001
|
+
clearInterval(_flushTimer);
|
|
4002
|
+
_flushTimer = null;
|
|
4003
|
+
}
|
|
4004
|
+
if (_pendingRecords.length > 0) {
|
|
4005
|
+
await flushBatch();
|
|
4006
|
+
}
|
|
4007
|
+
await disposeTurso();
|
|
4008
|
+
_pendingRecords = [];
|
|
4009
|
+
_nextVersion = 1;
|
|
4010
|
+
}
|
|
2941
4011
|
function vectorToBlob(vector) {
|
|
2942
4012
|
const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
|
|
2943
4013
|
return JSON.stringify(Array.from(f32));
|
|
2944
4014
|
}
|
|
4015
|
+
async function updateMemoryStatus(id, status) {
|
|
4016
|
+
const client = getClient();
|
|
4017
|
+
await client.execute({
|
|
4018
|
+
sql: `UPDATE memories SET status = ? WHERE id = ?`,
|
|
4019
|
+
args: [status, id]
|
|
4020
|
+
});
|
|
4021
|
+
}
|
|
4022
|
+
function reserveVersions(count) {
|
|
4023
|
+
const reserved = [];
|
|
4024
|
+
for (let i = 0; i < count; i++) {
|
|
4025
|
+
reserved.push(_nextVersion++);
|
|
4026
|
+
}
|
|
4027
|
+
return reserved;
|
|
4028
|
+
}
|
|
4029
|
+
async function getMemoryCardinality(agentId) {
|
|
4030
|
+
try {
|
|
4031
|
+
const client = getClient();
|
|
4032
|
+
const result = await client.execute({
|
|
4033
|
+
sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
|
|
4034
|
+
args: [agentId]
|
|
4035
|
+
});
|
|
4036
|
+
return Number(result.rows[0]?.cnt) || 0;
|
|
4037
|
+
} catch {
|
|
4038
|
+
return 0;
|
|
4039
|
+
}
|
|
4040
|
+
}
|
|
4041
|
+
var INIT_MAX_RETRIES, INIT_RETRY_DELAY_MS, _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
|
|
4042
|
+
var init_store = __esm({
|
|
4043
|
+
"src/lib/store.ts"() {
|
|
4044
|
+
"use strict";
|
|
4045
|
+
init_memory();
|
|
4046
|
+
init_database();
|
|
4047
|
+
init_keychain();
|
|
4048
|
+
init_config();
|
|
4049
|
+
init_state_bus();
|
|
4050
|
+
INIT_MAX_RETRIES = 3;
|
|
4051
|
+
INIT_RETRY_DELAY_MS = 1e3;
|
|
4052
|
+
_pendingRecords = [];
|
|
4053
|
+
_batchSize = 20;
|
|
4054
|
+
_flushIntervalMs = 1e4;
|
|
4055
|
+
_flushTimer = null;
|
|
4056
|
+
_flushing = false;
|
|
4057
|
+
_nextVersion = 1;
|
|
4058
|
+
}
|
|
4059
|
+
});
|
|
4060
|
+
|
|
4061
|
+
// src/bin/exe-review.ts
|
|
4062
|
+
init_employees();
|
|
4063
|
+
init_store();
|
|
4064
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
4065
|
+
|
|
4066
|
+
// src/bin/fast-db-init.ts
|
|
4067
|
+
async function fastDbInit() {
|
|
4068
|
+
const { isInitialized: isInitialized2, getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
|
|
4069
|
+
if (isInitialized2()) {
|
|
4070
|
+
return getClient2();
|
|
4071
|
+
}
|
|
4072
|
+
try {
|
|
4073
|
+
const { connectEmbedDaemon: connectEmbedDaemon2, sendDaemonRequest: sendDaemonRequest2, isClientConnected: isClientConnected2 } = await Promise.resolve().then(() => (init_exe_daemon_client(), exe_daemon_client_exports));
|
|
4074
|
+
const { deserializeResultSet: deserializeResultSet2 } = await Promise.resolve().then(() => (init_daemon_protocol(), daemon_protocol_exports));
|
|
4075
|
+
await connectEmbedDaemon2();
|
|
4076
|
+
if (isClientConnected2()) {
|
|
4077
|
+
const daemonClient = {
|
|
4078
|
+
async execute(stmt) {
|
|
4079
|
+
const sql = typeof stmt === "string" ? stmt : stmt.sql;
|
|
4080
|
+
const args = typeof stmt === "string" ? [] : Array.isArray(stmt.args) ? stmt.args : [];
|
|
4081
|
+
const resp = await sendDaemonRequest2({ type: "db-execute", sql, args });
|
|
4082
|
+
if (resp.error) throw new Error(String(resp.error));
|
|
4083
|
+
if (resp.db) return deserializeResultSet2(resp.db);
|
|
4084
|
+
throw new Error("Unexpected daemon response");
|
|
4085
|
+
},
|
|
4086
|
+
async batch(stmts, mode) {
|
|
4087
|
+
const statements = stmts.map((s) => {
|
|
4088
|
+
const sql = typeof s === "string" ? s : s.sql;
|
|
4089
|
+
const args = typeof s === "string" ? [] : Array.isArray(s.args) ? s.args : [];
|
|
4090
|
+
return { sql, args };
|
|
4091
|
+
});
|
|
4092
|
+
const resp = await sendDaemonRequest2({ type: "db-batch", statements, mode: mode ?? "deferred" });
|
|
4093
|
+
if (resp.error) throw new Error(String(resp.error));
|
|
4094
|
+
const batchResults = resp["db-batch"];
|
|
4095
|
+
if (batchResults) return batchResults.map(deserializeResultSet2);
|
|
4096
|
+
throw new Error("Unexpected daemon batch response");
|
|
4097
|
+
},
|
|
4098
|
+
async transaction(_mode) {
|
|
4099
|
+
throw new Error("Transactions not supported via daemon socket");
|
|
4100
|
+
},
|
|
4101
|
+
async executeMultiple(_sql) {
|
|
4102
|
+
throw new Error("executeMultiple not supported via daemon socket");
|
|
4103
|
+
},
|
|
4104
|
+
async migrate(_stmts) {
|
|
4105
|
+
throw new Error("migrate not supported via daemon socket");
|
|
4106
|
+
},
|
|
4107
|
+
sync() {
|
|
4108
|
+
return Promise.resolve(void 0);
|
|
4109
|
+
},
|
|
4110
|
+
close() {
|
|
4111
|
+
},
|
|
4112
|
+
get closed() {
|
|
4113
|
+
return false;
|
|
4114
|
+
},
|
|
4115
|
+
get protocol() {
|
|
4116
|
+
return "file";
|
|
4117
|
+
}
|
|
4118
|
+
};
|
|
4119
|
+
return daemonClient;
|
|
4120
|
+
}
|
|
4121
|
+
} catch {
|
|
4122
|
+
}
|
|
4123
|
+
const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
|
|
4124
|
+
await initStore2({ lightweight: true });
|
|
4125
|
+
return getClient2();
|
|
4126
|
+
}
|
|
2945
4127
|
|
|
2946
4128
|
// src/bin/exe-review.ts
|
|
2947
4129
|
init_database();
|
|
2948
4130
|
|
|
2949
4131
|
// src/lib/is-main.ts
|
|
2950
4132
|
import { realpathSync } from "fs";
|
|
2951
|
-
import { fileURLToPath } from "url";
|
|
4133
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2952
4134
|
function isMainModule(importMetaUrl) {
|
|
2953
4135
|
if (process.argv[1] == null) return false;
|
|
2954
4136
|
if (process.argv[1].includes("mcp/server")) return false;
|
|
2955
4137
|
try {
|
|
2956
4138
|
const scriptPath = realpathSync(process.argv[1]);
|
|
2957
|
-
const modulePath = realpathSync(
|
|
4139
|
+
const modulePath = realpathSync(fileURLToPath2(importMetaUrl));
|
|
2958
4140
|
return scriptPath === modulePath;
|
|
2959
4141
|
} catch {
|
|
2960
4142
|
return importMetaUrl === `file://${process.argv[1]}` || importMetaUrl === new URL(process.argv[1], "file://").href;
|
|
@@ -3040,7 +4222,7 @@ function generateReviewReport(employeeName, analysis, memories) {
|
|
|
3040
4222
|
function createReviewMemory(employeeName, report) {
|
|
3041
4223
|
const coordinatorName = getCoordinatorName();
|
|
3042
4224
|
return {
|
|
3043
|
-
id:
|
|
4225
|
+
id: randomUUID3(),
|
|
3044
4226
|
agent_id: coordinatorName,
|
|
3045
4227
|
agent_role: "COO",
|
|
3046
4228
|
session_id: `review-${employeeName}-${Date.now()}`,
|
|
@@ -3068,7 +4250,7 @@ async function main() {
|
|
|
3068
4250
|
);
|
|
3069
4251
|
process.exit(1);
|
|
3070
4252
|
}
|
|
3071
|
-
await
|
|
4253
|
+
await fastDbInit();
|
|
3072
4254
|
const client = getClient();
|
|
3073
4255
|
let memories;
|
|
3074
4256
|
try {
|