@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
|
@@ -15,6 +15,15 @@ var __export = (target, all) => {
|
|
|
15
15
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
16
16
|
};
|
|
17
17
|
|
|
18
|
+
// src/types/memory.ts
|
|
19
|
+
var EMBEDDING_DIM;
|
|
20
|
+
var init_memory = __esm({
|
|
21
|
+
"src/types/memory.ts"() {
|
|
22
|
+
"use strict";
|
|
23
|
+
EMBEDDING_DIM = 1024;
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
|
|
18
27
|
// src/lib/db-retry.ts
|
|
19
28
|
function isBusyError(err) {
|
|
20
29
|
if (err instanceof Error) {
|
|
@@ -64,9 +73,9 @@ var MAX_RETRIES, BASE_DELAY_MS, MAX_JITTER_MS;
|
|
|
64
73
|
var init_db_retry = __esm({
|
|
65
74
|
"src/lib/db-retry.ts"() {
|
|
66
75
|
"use strict";
|
|
67
|
-
MAX_RETRIES =
|
|
68
|
-
BASE_DELAY_MS =
|
|
69
|
-
MAX_JITTER_MS =
|
|
76
|
+
MAX_RETRIES = 5;
|
|
77
|
+
BASE_DELAY_MS = 250;
|
|
78
|
+
MAX_JITTER_MS = 400;
|
|
70
79
|
}
|
|
71
80
|
});
|
|
72
81
|
|
|
@@ -915,455 +924,1148 @@ var init_database_adapter = __esm({
|
|
|
915
924
|
}
|
|
916
925
|
});
|
|
917
926
|
|
|
918
|
-
// src/lib/
|
|
919
|
-
import
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
927
|
+
// src/lib/daemon-auth.ts
|
|
928
|
+
import crypto from "crypto";
|
|
929
|
+
import path4 from "path";
|
|
930
|
+
import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
931
|
+
function normalizeToken(token) {
|
|
932
|
+
if (!token) return null;
|
|
933
|
+
const trimmed = token.trim();
|
|
934
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
935
|
+
}
|
|
936
|
+
function readDaemonToken() {
|
|
937
|
+
try {
|
|
938
|
+
if (!existsSync4(DAEMON_TOKEN_PATH)) return null;
|
|
939
|
+
return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
|
|
940
|
+
} catch {
|
|
941
|
+
return null;
|
|
924
942
|
}
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
943
|
+
}
|
|
944
|
+
function ensureDaemonToken(seed) {
|
|
945
|
+
const existing = readDaemonToken();
|
|
946
|
+
if (existing) return existing;
|
|
947
|
+
const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
|
|
948
|
+
ensurePrivateDirSync(EXE_AI_DIR);
|
|
949
|
+
writeFileSync2(DAEMON_TOKEN_PATH, `${token}
|
|
950
|
+
`, "utf8");
|
|
951
|
+
enforcePrivateFileSync(DAEMON_TOKEN_PATH);
|
|
952
|
+
return token;
|
|
953
|
+
}
|
|
954
|
+
var DAEMON_TOKEN_PATH;
|
|
955
|
+
var init_daemon_auth = __esm({
|
|
956
|
+
"src/lib/daemon-auth.ts"() {
|
|
957
|
+
"use strict";
|
|
958
|
+
init_config();
|
|
959
|
+
init_secure_files();
|
|
960
|
+
DAEMON_TOKEN_PATH = path4.join(EXE_AI_DIR, "exed.token");
|
|
928
961
|
}
|
|
929
|
-
|
|
930
|
-
|
|
962
|
+
});
|
|
963
|
+
|
|
964
|
+
// src/lib/exe-daemon-client.ts
|
|
965
|
+
import net from "net";
|
|
966
|
+
import os4 from "os";
|
|
967
|
+
import { spawn } from "child_process";
|
|
968
|
+
import { randomUUID } from "crypto";
|
|
969
|
+
import { existsSync as existsSync5, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
|
|
970
|
+
import path5 from "path";
|
|
971
|
+
import { fileURLToPath } from "url";
|
|
972
|
+
function handleData(chunk) {
|
|
973
|
+
_buffer += chunk.toString();
|
|
974
|
+
if (_buffer.length > MAX_BUFFER) {
|
|
975
|
+
_buffer = "";
|
|
976
|
+
return;
|
|
931
977
|
}
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
978
|
+
let newlineIdx;
|
|
979
|
+
while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
|
|
980
|
+
const line = _buffer.slice(0, newlineIdx).trim();
|
|
981
|
+
_buffer = _buffer.slice(newlineIdx + 1);
|
|
982
|
+
if (!line) continue;
|
|
983
|
+
try {
|
|
984
|
+
const response = JSON.parse(line);
|
|
985
|
+
const id = response.id;
|
|
986
|
+
if (!id) continue;
|
|
987
|
+
const entry = _pending.get(id);
|
|
988
|
+
if (entry) {
|
|
989
|
+
clearTimeout(entry.timer);
|
|
990
|
+
_pending.delete(id);
|
|
991
|
+
entry.resolve(response);
|
|
992
|
+
}
|
|
993
|
+
} catch {
|
|
994
|
+
}
|
|
937
995
|
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
996
|
+
}
|
|
997
|
+
function cleanupStaleFiles() {
|
|
998
|
+
if (existsSync5(PID_PATH)) {
|
|
999
|
+
try {
|
|
1000
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
1001
|
+
if (pid > 0) {
|
|
1002
|
+
try {
|
|
1003
|
+
process.kill(pid, 0);
|
|
1004
|
+
return;
|
|
1005
|
+
} catch {
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
} catch {
|
|
1009
|
+
}
|
|
1010
|
+
try {
|
|
1011
|
+
unlinkSync2(PID_PATH);
|
|
1012
|
+
} catch {
|
|
1013
|
+
}
|
|
1014
|
+
try {
|
|
1015
|
+
unlinkSync2(SOCKET_PATH);
|
|
1016
|
+
} catch {
|
|
1017
|
+
}
|
|
943
1018
|
}
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
|
|
952
|
-
_walCheckpointTimer = setInterval(() => {
|
|
953
|
-
_client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
|
|
954
|
-
});
|
|
955
|
-
}, 3e4);
|
|
956
|
-
_walCheckpointTimer.unref();
|
|
957
|
-
if (process.env.DATABASE_URL) {
|
|
958
|
-
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1019
|
+
}
|
|
1020
|
+
function findPackageRoot() {
|
|
1021
|
+
let dir = path5.dirname(fileURLToPath(import.meta.url));
|
|
1022
|
+
const { root } = path5.parse(dir);
|
|
1023
|
+
while (dir !== root) {
|
|
1024
|
+
if (existsSync5(path5.join(dir, "package.json"))) return dir;
|
|
1025
|
+
dir = path5.dirname(dir);
|
|
959
1026
|
}
|
|
1027
|
+
return null;
|
|
960
1028
|
}
|
|
961
|
-
function
|
|
962
|
-
if (
|
|
963
|
-
|
|
1029
|
+
function getAvailableMemoryGB() {
|
|
1030
|
+
if (process.platform === "darwin") {
|
|
1031
|
+
try {
|
|
1032
|
+
const { execSync: execSync2 } = __require("child_process");
|
|
1033
|
+
const vmstat = execSync2("vm_stat", { encoding: "utf8" });
|
|
1034
|
+
const pageSize = 16384;
|
|
1035
|
+
const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
|
|
1036
|
+
const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
|
|
1037
|
+
const free = vmstat.match(/Pages free:\s+(\d+)/);
|
|
1038
|
+
const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
|
|
1039
|
+
const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
|
|
1040
|
+
const freePages = free ? parseInt(free[1], 10) : 0;
|
|
1041
|
+
const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
|
|
1042
|
+
const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
|
|
1043
|
+
return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
|
|
1044
|
+
} catch {
|
|
1045
|
+
return os4.freemem() / (1024 * 1024 * 1024);
|
|
1046
|
+
}
|
|
964
1047
|
}
|
|
965
|
-
|
|
966
|
-
|
|
1048
|
+
return os4.freemem() / (1024 * 1024 * 1024);
|
|
1049
|
+
}
|
|
1050
|
+
function spawnDaemon() {
|
|
1051
|
+
const freeGB = getAvailableMemoryGB();
|
|
1052
|
+
const totalGB = os4.totalmem() / (1024 * 1024 * 1024);
|
|
1053
|
+
if (totalGB <= 8) {
|
|
1054
|
+
process.stderr.write(
|
|
1055
|
+
`[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
|
|
1056
|
+
`
|
|
1057
|
+
);
|
|
1058
|
+
return;
|
|
967
1059
|
}
|
|
968
|
-
if (
|
|
969
|
-
|
|
1060
|
+
if (totalGB <= 16 && freeGB < 2) {
|
|
1061
|
+
process.stderr.write(
|
|
1062
|
+
`[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
|
|
1063
|
+
`
|
|
1064
|
+
);
|
|
1065
|
+
return;
|
|
970
1066
|
}
|
|
971
|
-
|
|
972
|
-
|
|
1067
|
+
const pkgRoot = findPackageRoot();
|
|
1068
|
+
if (!pkgRoot) {
|
|
1069
|
+
process.stderr.write("[exed-client] WARN: cannot find package root\n");
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
const daemonPath = path5.join(pkgRoot, "dist", "lib", "exe-daemon.js");
|
|
1073
|
+
if (!existsSync5(daemonPath)) {
|
|
1074
|
+
process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
|
|
1075
|
+
`);
|
|
1076
|
+
return;
|
|
1077
|
+
}
|
|
1078
|
+
const resolvedPath = daemonPath;
|
|
1079
|
+
const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
|
|
1080
|
+
process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
|
|
1081
|
+
`);
|
|
1082
|
+
const logPath = path5.join(path5.dirname(SOCKET_PATH), "exed.log");
|
|
1083
|
+
let stderrFd = "ignore";
|
|
1084
|
+
try {
|
|
1085
|
+
stderrFd = openSync(logPath, "a");
|
|
1086
|
+
} catch {
|
|
1087
|
+
}
|
|
1088
|
+
const heapCapMB = totalGB <= 8 ? 256 : 512;
|
|
1089
|
+
const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
|
|
1090
|
+
const child = spawn(process.execPath, nodeArgs, {
|
|
1091
|
+
detached: true,
|
|
1092
|
+
stdio: ["ignore", "ignore", stderrFd],
|
|
1093
|
+
env: {
|
|
1094
|
+
...process.env,
|
|
1095
|
+
TMUX: void 0,
|
|
1096
|
+
// Daemon is global — must not inherit session scope
|
|
1097
|
+
TMUX_PANE: void 0,
|
|
1098
|
+
// Prevents resolveExeSession() from scoping to one session
|
|
1099
|
+
EXE_DAEMON_SOCK: SOCKET_PATH,
|
|
1100
|
+
EXE_DAEMON_PID: PID_PATH,
|
|
1101
|
+
[DAEMON_TOKEN_ENV]: daemonToken
|
|
1102
|
+
}
|
|
1103
|
+
});
|
|
1104
|
+
child.unref();
|
|
1105
|
+
if (typeof stderrFd === "number") {
|
|
1106
|
+
try {
|
|
1107
|
+
closeSync(stderrFd);
|
|
1108
|
+
} catch {
|
|
1109
|
+
}
|
|
973
1110
|
}
|
|
974
|
-
return _resilientClient;
|
|
975
1111
|
}
|
|
976
|
-
function
|
|
977
|
-
|
|
978
|
-
|
|
1112
|
+
function acquireSpawnLock() {
|
|
1113
|
+
try {
|
|
1114
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
1115
|
+
closeSync(fd);
|
|
1116
|
+
return true;
|
|
1117
|
+
} catch {
|
|
1118
|
+
try {
|
|
1119
|
+
const stat = statSync(SPAWN_LOCK_PATH);
|
|
1120
|
+
if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
|
|
1121
|
+
try {
|
|
1122
|
+
unlinkSync2(SPAWN_LOCK_PATH);
|
|
1123
|
+
} catch {
|
|
1124
|
+
}
|
|
1125
|
+
try {
|
|
1126
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
1127
|
+
closeSync(fd);
|
|
1128
|
+
return true;
|
|
1129
|
+
} catch {
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
} catch {
|
|
1133
|
+
}
|
|
1134
|
+
return false;
|
|
979
1135
|
}
|
|
980
|
-
return _client;
|
|
981
1136
|
}
|
|
982
|
-
|
|
983
|
-
const client = getRawClient();
|
|
984
|
-
await client.execute("PRAGMA journal_mode = WAL");
|
|
985
|
-
await client.execute("PRAGMA busy_timeout = 30000");
|
|
986
|
-
await client.execute("PRAGMA wal_autocheckpoint = 1000");
|
|
1137
|
+
function releaseSpawnLock() {
|
|
987
1138
|
try {
|
|
988
|
-
|
|
1139
|
+
unlinkSync2(SPAWN_LOCK_PATH);
|
|
989
1140
|
} catch {
|
|
990
1141
|
}
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
1025
|
-
ON memories(agent_id, project_name);
|
|
1026
|
-
`);
|
|
1027
|
-
await client.executeMultiple(`
|
|
1028
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
1029
|
-
raw_text,
|
|
1030
|
-
content='memories',
|
|
1031
|
-
content_rowid='rowid'
|
|
1032
|
-
);
|
|
1033
|
-
|
|
1034
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
1035
|
-
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1036
|
-
END;
|
|
1037
|
-
|
|
1038
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
1039
|
-
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1040
|
-
END;
|
|
1041
|
-
|
|
1042
|
-
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
1043
|
-
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1044
|
-
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1045
|
-
END;
|
|
1046
|
-
`);
|
|
1047
|
-
await client.executeMultiple(`
|
|
1048
|
-
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
1049
|
-
key TEXT PRIMARY KEY,
|
|
1050
|
-
value TEXT NOT NULL
|
|
1051
|
-
);
|
|
1052
|
-
`);
|
|
1053
|
-
await client.executeMultiple(`
|
|
1054
|
-
CREATE TABLE IF NOT EXISTS tasks (
|
|
1055
|
-
id TEXT PRIMARY KEY,
|
|
1056
|
-
title TEXT NOT NULL,
|
|
1057
|
-
assigned_to TEXT NOT NULL,
|
|
1058
|
-
assigned_by TEXT NOT NULL,
|
|
1059
|
-
project_name TEXT NOT NULL,
|
|
1060
|
-
priority TEXT NOT NULL DEFAULT 'p1',
|
|
1061
|
-
status TEXT NOT NULL DEFAULT 'open',
|
|
1062
|
-
task_file TEXT,
|
|
1063
|
-
created_at TEXT NOT NULL,
|
|
1064
|
-
updated_at TEXT NOT NULL
|
|
1065
|
-
);
|
|
1066
|
-
|
|
1067
|
-
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
1068
|
-
ON tasks(assigned_to, status);
|
|
1069
|
-
`);
|
|
1070
|
-
await client.executeMultiple(`
|
|
1071
|
-
CREATE TABLE IF NOT EXISTS behaviors (
|
|
1072
|
-
id TEXT PRIMARY KEY,
|
|
1073
|
-
agent_id TEXT NOT NULL,
|
|
1074
|
-
project_name TEXT,
|
|
1075
|
-
domain TEXT,
|
|
1076
|
-
content TEXT NOT NULL,
|
|
1077
|
-
active INTEGER NOT NULL DEFAULT 1,
|
|
1078
|
-
created_at TEXT NOT NULL,
|
|
1079
|
-
updated_at TEXT NOT NULL
|
|
1080
|
-
);
|
|
1081
|
-
|
|
1082
|
-
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
1083
|
-
ON behaviors(agent_id, active);
|
|
1084
|
-
`);
|
|
1085
|
-
try {
|
|
1086
|
-
const coordinatorName = getCoordinatorName();
|
|
1087
|
-
const existing = await client.execute({
|
|
1088
|
-
sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
|
|
1089
|
-
args: [coordinatorName]
|
|
1142
|
+
}
|
|
1143
|
+
function connectToSocket() {
|
|
1144
|
+
return new Promise((resolve) => {
|
|
1145
|
+
if (_socket && _connected) {
|
|
1146
|
+
resolve(true);
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
const socket = net.createConnection({ path: SOCKET_PATH });
|
|
1150
|
+
const connectTimeout = setTimeout(() => {
|
|
1151
|
+
socket.destroy();
|
|
1152
|
+
resolve(false);
|
|
1153
|
+
}, 2e3);
|
|
1154
|
+
socket.on("connect", () => {
|
|
1155
|
+
clearTimeout(connectTimeout);
|
|
1156
|
+
_socket = socket;
|
|
1157
|
+
_connected = true;
|
|
1158
|
+
_buffer = "";
|
|
1159
|
+
socket.on("data", handleData);
|
|
1160
|
+
socket.on("close", () => {
|
|
1161
|
+
_connected = false;
|
|
1162
|
+
_socket = null;
|
|
1163
|
+
for (const [id, entry] of _pending) {
|
|
1164
|
+
clearTimeout(entry.timer);
|
|
1165
|
+
_pending.delete(id);
|
|
1166
|
+
entry.resolve({ error: "Connection closed" });
|
|
1167
|
+
}
|
|
1168
|
+
});
|
|
1169
|
+
socket.on("error", () => {
|
|
1170
|
+
_connected = false;
|
|
1171
|
+
_socket = null;
|
|
1172
|
+
});
|
|
1173
|
+
resolve(true);
|
|
1090
1174
|
});
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1175
|
+
socket.on("error", () => {
|
|
1176
|
+
clearTimeout(connectTimeout);
|
|
1177
|
+
resolve(false);
|
|
1178
|
+
});
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
async function connectEmbedDaemon() {
|
|
1182
|
+
if (_socket && _connected) return true;
|
|
1183
|
+
if (await connectToSocket()) return true;
|
|
1184
|
+
if (acquireSpawnLock()) {
|
|
1185
|
+
try {
|
|
1186
|
+
cleanupStaleFiles();
|
|
1187
|
+
spawnDaemon();
|
|
1188
|
+
} finally {
|
|
1189
|
+
releaseSpawnLock();
|
|
1104
1190
|
}
|
|
1105
|
-
} catch {
|
|
1106
1191
|
}
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1192
|
+
const start = Date.now();
|
|
1193
|
+
let delay2 = 100;
|
|
1194
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1195
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
1196
|
+
if (await connectToSocket()) return true;
|
|
1197
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
1113
1198
|
}
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1199
|
+
return false;
|
|
1200
|
+
}
|
|
1201
|
+
function sendRequest(texts, priority) {
|
|
1202
|
+
return sendDaemonRequest({ texts, priority });
|
|
1203
|
+
}
|
|
1204
|
+
function sendDaemonRequest(payload, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
1205
|
+
return new Promise((resolve) => {
|
|
1206
|
+
if (!_socket || !_connected) {
|
|
1207
|
+
resolve({ error: "Not connected" });
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
const id = randomUUID();
|
|
1211
|
+
const token = process.env[DAEMON_TOKEN_ENV] ?? readDaemonToken();
|
|
1212
|
+
const timer = setTimeout(() => {
|
|
1213
|
+
_pending.delete(id);
|
|
1214
|
+
resolve({ error: "Request timeout" });
|
|
1215
|
+
}, timeoutMs);
|
|
1216
|
+
_pending.set(id, { resolve, timer });
|
|
1217
|
+
try {
|
|
1218
|
+
_socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
|
|
1219
|
+
} catch {
|
|
1220
|
+
clearTimeout(timer);
|
|
1221
|
+
_pending.delete(id);
|
|
1222
|
+
resolve({ error: "Write failed" });
|
|
1223
|
+
}
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
async function pingDaemon() {
|
|
1227
|
+
if (!_socket || !_connected) return null;
|
|
1228
|
+
const response = await sendDaemonRequest({ type: "health" }, 5e3);
|
|
1229
|
+
if (response.health) {
|
|
1230
|
+
return response.health;
|
|
1120
1231
|
}
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1232
|
+
return null;
|
|
1233
|
+
}
|
|
1234
|
+
function killAndRespawnDaemon() {
|
|
1235
|
+
if (!acquireSpawnLock()) {
|
|
1236
|
+
process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
|
|
1237
|
+
if (_socket) {
|
|
1238
|
+
_socket.destroy();
|
|
1239
|
+
_socket = null;
|
|
1240
|
+
}
|
|
1241
|
+
_connected = false;
|
|
1242
|
+
_buffer = "";
|
|
1243
|
+
return;
|
|
1127
1244
|
}
|
|
1128
1245
|
try {
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1246
|
+
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
1247
|
+
if (existsSync5(PID_PATH)) {
|
|
1248
|
+
try {
|
|
1249
|
+
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
1250
|
+
if (pid > 0) {
|
|
1251
|
+
try {
|
|
1252
|
+
process.kill(pid, "SIGKILL");
|
|
1253
|
+
} catch {
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
} catch {
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
if (_socket) {
|
|
1260
|
+
_socket.destroy();
|
|
1261
|
+
_socket = null;
|
|
1262
|
+
}
|
|
1263
|
+
_connected = false;
|
|
1264
|
+
_buffer = "";
|
|
1265
|
+
try {
|
|
1266
|
+
unlinkSync2(PID_PATH);
|
|
1267
|
+
} catch {
|
|
1268
|
+
}
|
|
1269
|
+
try {
|
|
1270
|
+
unlinkSync2(SOCKET_PATH);
|
|
1271
|
+
} catch {
|
|
1272
|
+
}
|
|
1273
|
+
spawnDaemon();
|
|
1274
|
+
} finally {
|
|
1275
|
+
releaseSpawnLock();
|
|
1136
1276
|
}
|
|
1277
|
+
}
|
|
1278
|
+
function isDaemonTooYoung() {
|
|
1137
1279
|
try {
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
args: []
|
|
1141
|
-
});
|
|
1142
|
-
} catch {
|
|
1143
|
-
}
|
|
1144
|
-
try {
|
|
1145
|
-
await client.execute({
|
|
1146
|
-
sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
|
|
1147
|
-
args: []
|
|
1148
|
-
});
|
|
1280
|
+
const stat = statSync(PID_PATH);
|
|
1281
|
+
return Date.now() - stat.mtimeMs < MIN_DAEMON_AGE_MS;
|
|
1149
1282
|
} catch {
|
|
1283
|
+
return false;
|
|
1150
1284
|
}
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1285
|
+
}
|
|
1286
|
+
async function retryThenRestart(doRequest, label) {
|
|
1287
|
+
const result = await doRequest();
|
|
1288
|
+
if (!result.error) {
|
|
1289
|
+
_consecutiveFailures = 0;
|
|
1290
|
+
return result;
|
|
1157
1291
|
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1292
|
+
_consecutiveFailures++;
|
|
1293
|
+
for (let i = 0; i < MAX_RETRIES_BEFORE_RESTART; i++) {
|
|
1294
|
+
const delayMs = RETRY_DELAYS_MS[i] ?? 5e3;
|
|
1295
|
+
process.stderr.write(`[exed-client] ${label} failed (${result.error}), retry ${i + 1}/${MAX_RETRIES_BEFORE_RESTART} in ${delayMs}ms
|
|
1296
|
+
`);
|
|
1297
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
1298
|
+
if (!_connected) {
|
|
1299
|
+
if (!await connectToSocket()) continue;
|
|
1300
|
+
}
|
|
1301
|
+
const retry = await doRequest();
|
|
1302
|
+
if (!retry.error) {
|
|
1303
|
+
_consecutiveFailures = 0;
|
|
1304
|
+
return retry;
|
|
1305
|
+
}
|
|
1306
|
+
_consecutiveFailures++;
|
|
1164
1307
|
}
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
});
|
|
1170
|
-
} catch {
|
|
1308
|
+
if (isDaemonTooYoung()) {
|
|
1309
|
+
process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
|
|
1310
|
+
`);
|
|
1311
|
+
return { error: result.error };
|
|
1171
1312
|
}
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1313
|
+
process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
|
|
1314
|
+
`);
|
|
1315
|
+
killAndRespawnDaemon();
|
|
1316
|
+
const start = Date.now();
|
|
1317
|
+
let delay2 = 200;
|
|
1318
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1319
|
+
await new Promise((r) => setTimeout(r, delay2));
|
|
1320
|
+
if (await connectToSocket()) break;
|
|
1321
|
+
delay2 = Math.min(delay2 * 2, 3e3);
|
|
1178
1322
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1323
|
+
if (!_connected) return { error: "Daemon restart failed" };
|
|
1324
|
+
const final = await doRequest();
|
|
1325
|
+
if (!final.error) _consecutiveFailures = 0;
|
|
1326
|
+
return final;
|
|
1327
|
+
}
|
|
1328
|
+
async function embedViaClient(text, priority = "high") {
|
|
1329
|
+
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
1330
|
+
_requestCount++;
|
|
1331
|
+
if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
|
|
1332
|
+
const health = await pingDaemon();
|
|
1333
|
+
if (!health && !isDaemonTooYoung()) {
|
|
1334
|
+
process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
|
|
1335
|
+
`);
|
|
1336
|
+
killAndRespawnDaemon();
|
|
1337
|
+
const start = Date.now();
|
|
1338
|
+
let d = 200;
|
|
1339
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
1340
|
+
await new Promise((r) => setTimeout(r, d));
|
|
1341
|
+
if (await connectToSocket()) break;
|
|
1342
|
+
d = Math.min(d * 2, 3e3);
|
|
1343
|
+
}
|
|
1344
|
+
if (!_connected) return null;
|
|
1345
|
+
}
|
|
1185
1346
|
}
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1347
|
+
const result = await retryThenRestart(
|
|
1348
|
+
() => sendRequest([text], priority),
|
|
1349
|
+
"Embed"
|
|
1350
|
+
);
|
|
1351
|
+
return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
|
|
1352
|
+
}
|
|
1353
|
+
function isClientConnected() {
|
|
1354
|
+
return _connected;
|
|
1355
|
+
}
|
|
1356
|
+
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;
|
|
1357
|
+
var init_exe_daemon_client = __esm({
|
|
1358
|
+
"src/lib/exe-daemon-client.ts"() {
|
|
1359
|
+
"use strict";
|
|
1360
|
+
init_config();
|
|
1361
|
+
init_daemon_auth();
|
|
1362
|
+
SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path5.join(EXE_AI_DIR, "exed.sock");
|
|
1363
|
+
PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path5.join(EXE_AI_DIR, "exed.pid");
|
|
1364
|
+
SPAWN_LOCK_PATH = path5.join(EXE_AI_DIR, "exed-spawn.lock");
|
|
1365
|
+
SPAWN_LOCK_STALE_MS = 3e4;
|
|
1366
|
+
CONNECT_TIMEOUT_MS = 15e3;
|
|
1367
|
+
REQUEST_TIMEOUT_MS = 3e4;
|
|
1368
|
+
DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
|
|
1369
|
+
_socket = null;
|
|
1370
|
+
_connected = false;
|
|
1371
|
+
_buffer = "";
|
|
1372
|
+
_requestCount = 0;
|
|
1373
|
+
_consecutiveFailures = 0;
|
|
1374
|
+
HEALTH_CHECK_INTERVAL = 100;
|
|
1375
|
+
MAX_RETRIES_BEFORE_RESTART = 3;
|
|
1376
|
+
RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
|
|
1377
|
+
MIN_DAEMON_AGE_MS = 3e4;
|
|
1378
|
+
_pending = /* @__PURE__ */ new Map();
|
|
1379
|
+
MAX_BUFFER = 1e7;
|
|
1192
1380
|
}
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1381
|
+
});
|
|
1382
|
+
|
|
1383
|
+
// src/lib/daemon-protocol.ts
|
|
1384
|
+
function serializeValue(v) {
|
|
1385
|
+
if (v === null || v === void 0) return null;
|
|
1386
|
+
if (typeof v === "bigint") return Number(v);
|
|
1387
|
+
if (typeof v === "boolean") return v ? 1 : 0;
|
|
1388
|
+
if (v instanceof Uint8Array) {
|
|
1389
|
+
return { __blob: Buffer.from(v).toString("base64") };
|
|
1199
1390
|
}
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
|
|
1203
|
-
args: []
|
|
1204
|
-
});
|
|
1205
|
-
} catch {
|
|
1391
|
+
if (ArrayBuffer.isView(v)) {
|
|
1392
|
+
return { __blob: Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("base64") };
|
|
1206
1393
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
|
|
1210
|
-
args: []
|
|
1211
|
-
});
|
|
1212
|
-
} catch {
|
|
1394
|
+
if (v instanceof ArrayBuffer) {
|
|
1395
|
+
return { __blob: Buffer.from(v).toString("base64") };
|
|
1213
1396
|
}
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1397
|
+
if (typeof v === "string" || typeof v === "number") return v;
|
|
1398
|
+
return String(v);
|
|
1399
|
+
}
|
|
1400
|
+
function deserializeValue(v) {
|
|
1401
|
+
if (v === null) return null;
|
|
1402
|
+
if (typeof v === "object" && v !== null && "__blob" in v) {
|
|
1403
|
+
const buf = Buffer.from(v.__blob, "base64");
|
|
1404
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
1220
1405
|
}
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1406
|
+
return v;
|
|
1407
|
+
}
|
|
1408
|
+
function deserializeResultSet(srs) {
|
|
1409
|
+
const rows = srs.rows.map((obj) => {
|
|
1410
|
+
const values = srs.columns.map(
|
|
1411
|
+
(col) => deserializeValue(obj[col] ?? null)
|
|
1412
|
+
);
|
|
1413
|
+
const row = values;
|
|
1414
|
+
for (let i = 0; i < srs.columns.length; i++) {
|
|
1415
|
+
const col = srs.columns[i];
|
|
1416
|
+
if (col !== void 0) {
|
|
1417
|
+
row[col] = values[i] ?? null;
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
Object.defineProperty(row, "length", {
|
|
1421
|
+
value: values.length,
|
|
1422
|
+
enumerable: false
|
|
1225
1423
|
});
|
|
1226
|
-
|
|
1424
|
+
return row;
|
|
1425
|
+
});
|
|
1426
|
+
return {
|
|
1427
|
+
columns: srs.columns,
|
|
1428
|
+
columnTypes: srs.columnTypes ?? [],
|
|
1429
|
+
rows,
|
|
1430
|
+
rowsAffected: srs.rowsAffected,
|
|
1431
|
+
lastInsertRowid: srs.lastInsertRowid != null ? BigInt(srs.lastInsertRowid) : void 0,
|
|
1432
|
+
toJSON: () => ({
|
|
1433
|
+
columns: srs.columns,
|
|
1434
|
+
columnTypes: srs.columnTypes ?? [],
|
|
1435
|
+
rows: srs.rows,
|
|
1436
|
+
rowsAffected: srs.rowsAffected,
|
|
1437
|
+
lastInsertRowid: srs.lastInsertRowid
|
|
1438
|
+
})
|
|
1439
|
+
};
|
|
1440
|
+
}
|
|
1441
|
+
var init_daemon_protocol = __esm({
|
|
1442
|
+
"src/lib/daemon-protocol.ts"() {
|
|
1443
|
+
"use strict";
|
|
1227
1444
|
}
|
|
1228
|
-
|
|
1229
|
-
CREATE TABLE IF NOT EXISTS consolidations (
|
|
1230
|
-
id TEXT PRIMARY KEY,
|
|
1231
|
-
consolidated_memory_id TEXT NOT NULL,
|
|
1232
|
-
source_memory_id TEXT NOT NULL,
|
|
1233
|
-
created_at TEXT NOT NULL
|
|
1234
|
-
);
|
|
1445
|
+
});
|
|
1235
1446
|
|
|
1236
|
-
|
|
1237
|
-
|
|
1447
|
+
// src/lib/db-daemon-client.ts
|
|
1448
|
+
var db_daemon_client_exports = {};
|
|
1449
|
+
__export(db_daemon_client_exports, {
|
|
1450
|
+
createDaemonDbClient: () => createDaemonDbClient,
|
|
1451
|
+
initDaemonDbClient: () => initDaemonDbClient
|
|
1452
|
+
});
|
|
1453
|
+
function normalizeStatement2(stmt) {
|
|
1454
|
+
if (typeof stmt === "string") {
|
|
1455
|
+
return { sql: stmt, args: [] };
|
|
1456
|
+
}
|
|
1457
|
+
const sql = stmt.sql;
|
|
1458
|
+
let args = [];
|
|
1459
|
+
if (Array.isArray(stmt.args)) {
|
|
1460
|
+
args = stmt.args.map((v) => serializeValue(v));
|
|
1461
|
+
} else if (stmt.args && typeof stmt.args === "object") {
|
|
1462
|
+
const named = {};
|
|
1463
|
+
for (const [key, val] of Object.entries(stmt.args)) {
|
|
1464
|
+
named[key] = serializeValue(val);
|
|
1465
|
+
}
|
|
1466
|
+
return { sql, args: named };
|
|
1467
|
+
}
|
|
1468
|
+
return { sql, args };
|
|
1469
|
+
}
|
|
1470
|
+
function createDaemonDbClient(fallbackClient) {
|
|
1471
|
+
let _useDaemon = false;
|
|
1472
|
+
const client = {
|
|
1473
|
+
async execute(stmt) {
|
|
1474
|
+
if (!_useDaemon || !isClientConnected()) {
|
|
1475
|
+
return fallbackClient.execute(stmt);
|
|
1476
|
+
}
|
|
1477
|
+
const { sql, args } = normalizeStatement2(stmt);
|
|
1478
|
+
const response = await sendDaemonRequest({
|
|
1479
|
+
type: "db-execute",
|
|
1480
|
+
sql,
|
|
1481
|
+
args
|
|
1482
|
+
});
|
|
1483
|
+
if (response.error) {
|
|
1484
|
+
const errMsg = String(response.error);
|
|
1485
|
+
if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
|
|
1486
|
+
process.stderr.write(`[db-daemon] Transport error (${errMsg}), falling back to direct
|
|
1487
|
+
`);
|
|
1488
|
+
return fallbackClient.execute(stmt);
|
|
1489
|
+
}
|
|
1490
|
+
throw new Error(errMsg);
|
|
1491
|
+
}
|
|
1492
|
+
if (response.db) {
|
|
1493
|
+
return deserializeResultSet(response.db);
|
|
1494
|
+
}
|
|
1495
|
+
process.stderr.write("[db-daemon] Unexpected response shape, falling back to direct\n");
|
|
1496
|
+
return fallbackClient.execute(stmt);
|
|
1497
|
+
},
|
|
1498
|
+
async batch(stmts, mode) {
|
|
1499
|
+
if (!_useDaemon || !isClientConnected()) {
|
|
1500
|
+
return fallbackClient.batch(stmts, mode);
|
|
1501
|
+
}
|
|
1502
|
+
const statements = stmts.map(normalizeStatement2);
|
|
1503
|
+
const response = await sendDaemonRequest({
|
|
1504
|
+
type: "db-batch",
|
|
1505
|
+
statements,
|
|
1506
|
+
mode: mode ?? "deferred"
|
|
1507
|
+
});
|
|
1508
|
+
if (response.error) {
|
|
1509
|
+
const errMsg = String(response.error);
|
|
1510
|
+
if (errMsg === "Not connected" || errMsg === "Request timeout" || errMsg === "Write failed" || errMsg === "DB not initialized") {
|
|
1511
|
+
process.stderr.write(`[db-daemon] Batch transport error (${errMsg}), falling back to direct
|
|
1512
|
+
`);
|
|
1513
|
+
return fallbackClient.batch(stmts, mode);
|
|
1514
|
+
}
|
|
1515
|
+
throw new Error(errMsg);
|
|
1516
|
+
}
|
|
1517
|
+
const batchResults = response["db-batch"];
|
|
1518
|
+
if (batchResults) {
|
|
1519
|
+
return batchResults.map(deserializeResultSet);
|
|
1520
|
+
}
|
|
1521
|
+
process.stderr.write("[db-daemon] Unexpected batch response shape, falling back to direct\n");
|
|
1522
|
+
return fallbackClient.batch(stmts, mode);
|
|
1523
|
+
},
|
|
1524
|
+
// Transaction support — delegate to fallback (transactions need direct connection)
|
|
1525
|
+
async transaction(mode) {
|
|
1526
|
+
return fallbackClient.transaction(mode);
|
|
1527
|
+
},
|
|
1528
|
+
// executeMultiple — delegate to fallback (used only for schema migrations)
|
|
1529
|
+
async executeMultiple(sql) {
|
|
1530
|
+
return fallbackClient.executeMultiple(sql);
|
|
1531
|
+
},
|
|
1532
|
+
// migrate — delegate to fallback
|
|
1533
|
+
async migrate(stmts) {
|
|
1534
|
+
return fallbackClient.migrate(stmts);
|
|
1535
|
+
},
|
|
1536
|
+
// Sync mode — delegate to fallback
|
|
1537
|
+
sync() {
|
|
1538
|
+
return fallbackClient.sync();
|
|
1539
|
+
},
|
|
1540
|
+
close() {
|
|
1541
|
+
_useDaemon = false;
|
|
1542
|
+
},
|
|
1543
|
+
get closed() {
|
|
1544
|
+
return fallbackClient.closed;
|
|
1545
|
+
},
|
|
1546
|
+
get protocol() {
|
|
1547
|
+
return fallbackClient.protocol;
|
|
1548
|
+
}
|
|
1549
|
+
};
|
|
1550
|
+
return {
|
|
1551
|
+
...client,
|
|
1552
|
+
/** Enable daemon routing (call after confirming daemon is connected) */
|
|
1553
|
+
_enableDaemon() {
|
|
1554
|
+
_useDaemon = true;
|
|
1555
|
+
},
|
|
1556
|
+
/** Check if daemon routing is active */
|
|
1557
|
+
_isDaemonActive() {
|
|
1558
|
+
return _useDaemon && isClientConnected();
|
|
1559
|
+
}
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
async function initDaemonDbClient(fallbackClient) {
|
|
1563
|
+
if (process.env.EXE_IS_DAEMON === "1") return null;
|
|
1564
|
+
const connected = await connectEmbedDaemon();
|
|
1565
|
+
if (!connected) {
|
|
1566
|
+
process.stderr.write("[db-daemon] Daemon unavailable \u2014 using direct SQLite\n");
|
|
1567
|
+
return null;
|
|
1568
|
+
}
|
|
1569
|
+
const client = createDaemonDbClient(fallbackClient);
|
|
1570
|
+
client._enableDaemon();
|
|
1571
|
+
process.stderr.write("[db-daemon] DB routing through daemon (single-writer)\n");
|
|
1572
|
+
return client;
|
|
1573
|
+
}
|
|
1574
|
+
var init_db_daemon_client = __esm({
|
|
1575
|
+
"src/lib/db-daemon-client.ts"() {
|
|
1576
|
+
"use strict";
|
|
1577
|
+
init_exe_daemon_client();
|
|
1578
|
+
init_daemon_protocol();
|
|
1579
|
+
}
|
|
1580
|
+
});
|
|
1238
1581
|
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1582
|
+
// src/lib/database.ts
|
|
1583
|
+
var database_exports = {};
|
|
1584
|
+
__export(database_exports, {
|
|
1585
|
+
disposeDatabase: () => disposeDatabase,
|
|
1586
|
+
disposeTurso: () => disposeTurso,
|
|
1587
|
+
ensureSchema: () => ensureSchema,
|
|
1588
|
+
getClient: () => getClient,
|
|
1589
|
+
getRawClient: () => getRawClient,
|
|
1590
|
+
initDaemonClient: () => initDaemonClient,
|
|
1591
|
+
initDatabase: () => initDatabase,
|
|
1592
|
+
initTurso: () => initTurso,
|
|
1593
|
+
isInitialized: () => isInitialized
|
|
1594
|
+
});
|
|
1595
|
+
import { createClient } from "@libsql/client";
|
|
1596
|
+
async function initDatabase(config) {
|
|
1597
|
+
if (_walCheckpointTimer) {
|
|
1598
|
+
clearInterval(_walCheckpointTimer);
|
|
1599
|
+
_walCheckpointTimer = null;
|
|
1600
|
+
}
|
|
1601
|
+
if (_daemonClient) {
|
|
1602
|
+
_daemonClient.close();
|
|
1603
|
+
_daemonClient = null;
|
|
1604
|
+
}
|
|
1605
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
1606
|
+
_adapterClient.close();
|
|
1607
|
+
}
|
|
1608
|
+
_adapterClient = null;
|
|
1609
|
+
if (_client) {
|
|
1610
|
+
_client.close();
|
|
1611
|
+
_client = null;
|
|
1612
|
+
_resilientClient = null;
|
|
1613
|
+
}
|
|
1614
|
+
const opts = {
|
|
1615
|
+
url: `file:${config.dbPath}`
|
|
1616
|
+
};
|
|
1617
|
+
if (config.encryptionKey) {
|
|
1618
|
+
opts.encryptionKey = config.encryptionKey;
|
|
1619
|
+
}
|
|
1620
|
+
_client = createClient(opts);
|
|
1621
|
+
_resilientClient = wrapWithRetry(_client);
|
|
1622
|
+
_adapterClient = _resilientClient;
|
|
1623
|
+
_client.execute("PRAGMA busy_timeout = 30000").catch(() => {
|
|
1624
|
+
});
|
|
1625
|
+
_client.execute("PRAGMA journal_mode = WAL").catch(() => {
|
|
1626
|
+
});
|
|
1627
|
+
if (_walCheckpointTimer) clearInterval(_walCheckpointTimer);
|
|
1628
|
+
_walCheckpointTimer = setInterval(() => {
|
|
1629
|
+
_client?.execute("PRAGMA wal_checkpoint(PASSIVE)").catch(() => {
|
|
1630
|
+
});
|
|
1631
|
+
}, 3e4);
|
|
1632
|
+
_walCheckpointTimer.unref();
|
|
1633
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
|
|
1634
|
+
_adapterClient = await createPrismaDbAdapter(_resilientClient);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
function isInitialized() {
|
|
1638
|
+
return _adapterClient !== null || _client !== null;
|
|
1639
|
+
}
|
|
1640
|
+
function getClient() {
|
|
1641
|
+
if (!_adapterClient) {
|
|
1642
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
1643
|
+
}
|
|
1644
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") {
|
|
1645
|
+
return _adapterClient;
|
|
1646
|
+
}
|
|
1647
|
+
if (process.env.EXE_IS_DAEMON === "1") {
|
|
1648
|
+
return _resilientClient;
|
|
1649
|
+
}
|
|
1650
|
+
if (_daemonClient && _daemonClient._isDaemonActive()) {
|
|
1651
|
+
return _daemonClient;
|
|
1652
|
+
}
|
|
1653
|
+
return _resilientClient;
|
|
1654
|
+
}
|
|
1655
|
+
async function initDaemonClient() {
|
|
1656
|
+
if (process.env.DATABASE_URL && process.env.EXE_USE_POSTGRES === "1") return;
|
|
1657
|
+
if (process.env.EXE_IS_DAEMON === "1") return;
|
|
1658
|
+
if (process.env.VITEST) return;
|
|
1659
|
+
if (!_resilientClient) return;
|
|
1660
|
+
if (_daemonClient) return;
|
|
1661
|
+
try {
|
|
1662
|
+
const { initDaemonDbClient: initDaemonDbClient2 } = await Promise.resolve().then(() => (init_db_daemon_client(), db_daemon_client_exports));
|
|
1663
|
+
_daemonClient = await initDaemonDbClient2(_resilientClient);
|
|
1664
|
+
} catch (err) {
|
|
1665
|
+
process.stderr.write(
|
|
1666
|
+
`[database] Daemon client init failed (non-fatal): ${err instanceof Error ? err.message : String(err)}
|
|
1667
|
+
`
|
|
1668
|
+
);
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
function getRawClient() {
|
|
1672
|
+
if (!_client) {
|
|
1673
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
1674
|
+
}
|
|
1675
|
+
return _client;
|
|
1676
|
+
}
|
|
1677
|
+
async function ensureSchema() {
|
|
1678
|
+
const client = getRawClient();
|
|
1679
|
+
await client.execute("PRAGMA journal_mode = WAL");
|
|
1680
|
+
await client.execute("PRAGMA busy_timeout = 30000");
|
|
1681
|
+
await client.execute("PRAGMA wal_autocheckpoint = 1000");
|
|
1682
|
+
try {
|
|
1683
|
+
await client.execute("PRAGMA libsql_vector_search_ef = 128");
|
|
1684
|
+
} catch {
|
|
1685
|
+
}
|
|
1686
|
+
await client.executeMultiple(`
|
|
1687
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
1688
|
+
id TEXT PRIMARY KEY,
|
|
1689
|
+
agent_id TEXT NOT NULL,
|
|
1690
|
+
agent_role TEXT NOT NULL,
|
|
1691
|
+
session_id TEXT NOT NULL,
|
|
1692
|
+
timestamp TEXT NOT NULL,
|
|
1693
|
+
tool_name TEXT NOT NULL,
|
|
1694
|
+
project_name TEXT NOT NULL,
|
|
1695
|
+
has_error INTEGER NOT NULL DEFAULT 0,
|
|
1696
|
+
raw_text TEXT NOT NULL,
|
|
1697
|
+
vector F32_BLOB(1024),
|
|
1698
|
+
version INTEGER NOT NULL DEFAULT 0
|
|
1263
1699
|
);
|
|
1264
1700
|
|
|
1265
|
-
CREATE INDEX IF NOT EXISTS
|
|
1266
|
-
ON
|
|
1701
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent
|
|
1702
|
+
ON memories(agent_id);
|
|
1267
1703
|
|
|
1268
|
-
CREATE INDEX IF NOT EXISTS
|
|
1269
|
-
ON
|
|
1704
|
+
CREATE INDEX IF NOT EXISTS idx_memories_timestamp
|
|
1705
|
+
ON memories(timestamp);
|
|
1270
1706
|
|
|
1271
|
-
CREATE INDEX IF NOT EXISTS
|
|
1272
|
-
ON
|
|
1707
|
+
CREATE INDEX IF NOT EXISTS idx_memories_session
|
|
1708
|
+
ON memories(session_id);
|
|
1709
|
+
|
|
1710
|
+
CREATE INDEX IF NOT EXISTS idx_memories_project
|
|
1711
|
+
ON memories(project_name);
|
|
1712
|
+
|
|
1713
|
+
CREATE INDEX IF NOT EXISTS idx_memories_tool
|
|
1714
|
+
ON memories(tool_name);
|
|
1715
|
+
|
|
1716
|
+
CREATE INDEX IF NOT EXISTS idx_memories_version
|
|
1717
|
+
ON memories(version);
|
|
1718
|
+
|
|
1719
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
1720
|
+
ON memories(agent_id, project_name);
|
|
1273
1721
|
`);
|
|
1274
1722
|
await client.executeMultiple(`
|
|
1275
|
-
CREATE TABLE IF NOT EXISTS
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
job_type TEXT NOT NULL DEFAULT 'report',
|
|
1280
|
-
prompt TEXT,
|
|
1281
|
-
assigned_to TEXT,
|
|
1282
|
-
project_name TEXT,
|
|
1283
|
-
active INTEGER NOT NULL DEFAULT 1,
|
|
1284
|
-
use_crontab INTEGER NOT NULL DEFAULT 0,
|
|
1285
|
-
created_at TEXT NOT NULL
|
|
1723
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
1724
|
+
raw_text,
|
|
1725
|
+
content='memories',
|
|
1726
|
+
content_rowid='rowid'
|
|
1286
1727
|
);
|
|
1728
|
+
|
|
1729
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
1730
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1731
|
+
END;
|
|
1732
|
+
|
|
1733
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
1734
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1735
|
+
END;
|
|
1736
|
+
|
|
1737
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
1738
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1739
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1740
|
+
END;
|
|
1287
1741
|
`);
|
|
1288
1742
|
await client.executeMultiple(`
|
|
1289
|
-
CREATE TABLE IF NOT EXISTS
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
hostname TEXT NOT NULL,
|
|
1293
|
-
projects TEXT NOT NULL DEFAULT '[]',
|
|
1294
|
-
agents TEXT NOT NULL DEFAULT '[]',
|
|
1295
|
-
connected INTEGER DEFAULT 0,
|
|
1296
|
-
last_seen TEXT NOT NULL
|
|
1743
|
+
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
1744
|
+
key TEXT PRIMARY KEY,
|
|
1745
|
+
value TEXT NOT NULL
|
|
1297
1746
|
);
|
|
1298
1747
|
`);
|
|
1299
1748
|
await client.executeMultiple(`
|
|
1300
|
-
CREATE TABLE IF NOT EXISTS
|
|
1301
|
-
id
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
server_seq INTEGER,
|
|
1312
|
-
retry_count INTEGER DEFAULT 0,
|
|
1313
|
-
created_at TEXT NOT NULL,
|
|
1314
|
-
delivered_at TEXT,
|
|
1315
|
-
processed_at TEXT,
|
|
1316
|
-
failed_at TEXT,
|
|
1317
|
-
failure_reason TEXT
|
|
1749
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
1750
|
+
id TEXT PRIMARY KEY,
|
|
1751
|
+
title TEXT NOT NULL,
|
|
1752
|
+
assigned_to TEXT NOT NULL,
|
|
1753
|
+
assigned_by TEXT NOT NULL,
|
|
1754
|
+
project_name TEXT NOT NULL,
|
|
1755
|
+
priority TEXT NOT NULL DEFAULT 'p1',
|
|
1756
|
+
status TEXT NOT NULL DEFAULT 'open',
|
|
1757
|
+
task_file TEXT,
|
|
1758
|
+
created_at TEXT NOT NULL,
|
|
1759
|
+
updated_at TEXT NOT NULL
|
|
1318
1760
|
);
|
|
1319
1761
|
|
|
1320
|
-
CREATE INDEX IF NOT EXISTS
|
|
1321
|
-
ON
|
|
1762
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
1763
|
+
ON tasks(assigned_to, status);
|
|
1764
|
+
`);
|
|
1765
|
+
await client.executeMultiple(`
|
|
1766
|
+
CREATE TABLE IF NOT EXISTS behaviors (
|
|
1767
|
+
id TEXT PRIMARY KEY,
|
|
1768
|
+
agent_id TEXT NOT NULL,
|
|
1769
|
+
project_name TEXT,
|
|
1770
|
+
domain TEXT,
|
|
1771
|
+
content TEXT NOT NULL,
|
|
1772
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1773
|
+
created_at TEXT NOT NULL,
|
|
1774
|
+
updated_at TEXT NOT NULL
|
|
1775
|
+
);
|
|
1322
1776
|
|
|
1323
|
-
CREATE INDEX IF NOT EXISTS
|
|
1324
|
-
ON
|
|
1777
|
+
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
1778
|
+
ON behaviors(agent_id, active);
|
|
1325
1779
|
`);
|
|
1326
1780
|
try {
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1781
|
+
const coordinatorName = getCoordinatorName();
|
|
1782
|
+
const existing = await client.execute({
|
|
1783
|
+
sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
|
|
1784
|
+
args: [coordinatorName]
|
|
1330
1785
|
});
|
|
1786
|
+
if (Number(existing.rows[0]?.cnt) === 0) {
|
|
1787
|
+
const seededAt = "2026-03-25T00:00:00Z";
|
|
1788
|
+
for (const [domain, content] of [
|
|
1789
|
+
["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
|
|
1790
|
+
["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
|
|
1791
|
+
["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
|
|
1792
|
+
]) {
|
|
1793
|
+
await client.execute({
|
|
1794
|
+
sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
1795
|
+
VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
|
|
1796
|
+
args: [coordinatorName, domain, content, seededAt, seededAt]
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1331
1800
|
} catch {
|
|
1332
1801
|
}
|
|
1333
1802
|
try {
|
|
1334
1803
|
await client.execute({
|
|
1335
|
-
sql: `ALTER TABLE
|
|
1804
|
+
sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
|
|
1336
1805
|
args: []
|
|
1337
1806
|
});
|
|
1338
1807
|
} catch {
|
|
1339
1808
|
}
|
|
1340
|
-
await client.executeMultiple(`
|
|
1341
|
-
CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
|
|
1342
|
-
ON notifications(agent_id, session_scope, read, created_at);
|
|
1343
|
-
|
|
1344
|
-
CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
|
|
1345
|
-
ON messages(target_agent, session_scope, status, created_at);
|
|
1346
|
-
`);
|
|
1347
1809
|
try {
|
|
1348
1810
|
await client.execute({
|
|
1349
|
-
sql: `
|
|
1811
|
+
sql: `ALTER TABLE behaviors ADD COLUMN vector F32_BLOB(${EMBEDDING_DIM})`,
|
|
1350
1812
|
args: []
|
|
1351
1813
|
});
|
|
1814
|
+
} catch {
|
|
1815
|
+
}
|
|
1816
|
+
try {
|
|
1352
1817
|
await client.execute({
|
|
1353
|
-
sql: `
|
|
1818
|
+
sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
|
|
1354
1819
|
args: []
|
|
1355
1820
|
});
|
|
1821
|
+
} catch {
|
|
1822
|
+
}
|
|
1823
|
+
try {
|
|
1356
1824
|
await client.execute({
|
|
1357
|
-
sql: `
|
|
1825
|
+
sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
|
|
1358
1826
|
args: []
|
|
1359
1827
|
});
|
|
1828
|
+
} catch {
|
|
1829
|
+
}
|
|
1830
|
+
try {
|
|
1360
1831
|
await client.execute({
|
|
1361
|
-
sql: `
|
|
1832
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
|
|
1833
|
+
ON tasks(parent_task_id)
|
|
1834
|
+
WHERE parent_task_id IS NOT NULL`,
|
|
1362
1835
|
args: []
|
|
1363
1836
|
});
|
|
1364
1837
|
} catch {
|
|
1365
1838
|
}
|
|
1366
|
-
|
|
1839
|
+
try {
|
|
1840
|
+
await client.execute({
|
|
1841
|
+
sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
|
|
1842
|
+
args: []
|
|
1843
|
+
});
|
|
1844
|
+
} catch {
|
|
1845
|
+
}
|
|
1846
|
+
try {
|
|
1847
|
+
await client.execute({
|
|
1848
|
+
sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
|
|
1849
|
+
args: []
|
|
1850
|
+
});
|
|
1851
|
+
} catch {
|
|
1852
|
+
}
|
|
1853
|
+
try {
|
|
1854
|
+
await client.execute({
|
|
1855
|
+
sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
|
|
1856
|
+
args: []
|
|
1857
|
+
});
|
|
1858
|
+
} catch {
|
|
1859
|
+
}
|
|
1860
|
+
try {
|
|
1861
|
+
await client.execute({
|
|
1862
|
+
sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
|
|
1863
|
+
args: []
|
|
1864
|
+
});
|
|
1865
|
+
} catch {
|
|
1866
|
+
}
|
|
1867
|
+
try {
|
|
1868
|
+
await client.execute({
|
|
1869
|
+
sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
|
|
1870
|
+
args: []
|
|
1871
|
+
});
|
|
1872
|
+
} catch {
|
|
1873
|
+
}
|
|
1874
|
+
try {
|
|
1875
|
+
await client.execute({
|
|
1876
|
+
sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
|
|
1877
|
+
args: []
|
|
1878
|
+
});
|
|
1879
|
+
} catch {
|
|
1880
|
+
}
|
|
1881
|
+
try {
|
|
1882
|
+
await client.execute({
|
|
1883
|
+
sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
|
|
1884
|
+
args: []
|
|
1885
|
+
});
|
|
1886
|
+
} catch {
|
|
1887
|
+
}
|
|
1888
|
+
try {
|
|
1889
|
+
await client.execute({
|
|
1890
|
+
sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
|
|
1891
|
+
args: []
|
|
1892
|
+
});
|
|
1893
|
+
} catch {
|
|
1894
|
+
}
|
|
1895
|
+
try {
|
|
1896
|
+
await client.execute({
|
|
1897
|
+
sql: `ALTER TABLE tasks ADD COLUMN session_scope TEXT`,
|
|
1898
|
+
args: []
|
|
1899
|
+
});
|
|
1900
|
+
} catch {
|
|
1901
|
+
}
|
|
1902
|
+
try {
|
|
1903
|
+
await client.execute({
|
|
1904
|
+
sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
|
|
1905
|
+
args: []
|
|
1906
|
+
});
|
|
1907
|
+
} catch {
|
|
1908
|
+
}
|
|
1909
|
+
try {
|
|
1910
|
+
await client.execute({
|
|
1911
|
+
sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
|
|
1912
|
+
args: []
|
|
1913
|
+
});
|
|
1914
|
+
} catch {
|
|
1915
|
+
}
|
|
1916
|
+
try {
|
|
1917
|
+
await client.execute({
|
|
1918
|
+
sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
|
|
1919
|
+
args: []
|
|
1920
|
+
});
|
|
1921
|
+
} catch {
|
|
1922
|
+
}
|
|
1923
|
+
try {
|
|
1924
|
+
await client.execute({
|
|
1925
|
+
sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
|
|
1926
|
+
args: []
|
|
1927
|
+
});
|
|
1928
|
+
} catch {
|
|
1929
|
+
}
|
|
1930
|
+
await client.executeMultiple(`
|
|
1931
|
+
CREATE TABLE IF NOT EXISTS consolidations (
|
|
1932
|
+
id TEXT PRIMARY KEY,
|
|
1933
|
+
consolidated_memory_id TEXT NOT NULL,
|
|
1934
|
+
source_memory_id TEXT NOT NULL,
|
|
1935
|
+
created_at TEXT NOT NULL
|
|
1936
|
+
);
|
|
1937
|
+
|
|
1938
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_source
|
|
1939
|
+
ON consolidations(source_memory_id);
|
|
1940
|
+
|
|
1941
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
|
|
1942
|
+
ON consolidations(consolidated_memory_id);
|
|
1943
|
+
`);
|
|
1944
|
+
await client.executeMultiple(`
|
|
1945
|
+
CREATE TABLE IF NOT EXISTS reminders (
|
|
1946
|
+
id TEXT PRIMARY KEY,
|
|
1947
|
+
text TEXT NOT NULL,
|
|
1948
|
+
created_at TEXT NOT NULL,
|
|
1949
|
+
due_date TEXT,
|
|
1950
|
+
completed_at TEXT
|
|
1951
|
+
);
|
|
1952
|
+
`);
|
|
1953
|
+
await client.executeMultiple(`
|
|
1954
|
+
CREATE TABLE IF NOT EXISTS notifications (
|
|
1955
|
+
id TEXT PRIMARY KEY,
|
|
1956
|
+
agent_id TEXT NOT NULL,
|
|
1957
|
+
agent_role TEXT NOT NULL,
|
|
1958
|
+
event TEXT NOT NULL,
|
|
1959
|
+
project TEXT NOT NULL,
|
|
1960
|
+
summary TEXT NOT NULL,
|
|
1961
|
+
task_file TEXT,
|
|
1962
|
+
session_scope TEXT,
|
|
1963
|
+
read INTEGER NOT NULL DEFAULT 0,
|
|
1964
|
+
created_at TEXT NOT NULL
|
|
1965
|
+
);
|
|
1966
|
+
|
|
1967
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_read
|
|
1968
|
+
ON notifications(read);
|
|
1969
|
+
|
|
1970
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_agent
|
|
1971
|
+
ON notifications(agent_id, session_scope);
|
|
1972
|
+
|
|
1973
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_task_file
|
|
1974
|
+
ON notifications(task_file);
|
|
1975
|
+
`);
|
|
1976
|
+
await client.executeMultiple(`
|
|
1977
|
+
CREATE TABLE IF NOT EXISTS schedules (
|
|
1978
|
+
id TEXT PRIMARY KEY,
|
|
1979
|
+
cron TEXT NOT NULL,
|
|
1980
|
+
description TEXT NOT NULL,
|
|
1981
|
+
job_type TEXT NOT NULL DEFAULT 'report',
|
|
1982
|
+
prompt TEXT,
|
|
1983
|
+
assigned_to TEXT,
|
|
1984
|
+
project_name TEXT,
|
|
1985
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1986
|
+
use_crontab INTEGER NOT NULL DEFAULT 0,
|
|
1987
|
+
created_at TEXT NOT NULL
|
|
1988
|
+
);
|
|
1989
|
+
`);
|
|
1990
|
+
await client.executeMultiple(`
|
|
1991
|
+
CREATE TABLE IF NOT EXISTS device_registry (
|
|
1992
|
+
device_id TEXT PRIMARY KEY,
|
|
1993
|
+
friendly_name TEXT NOT NULL,
|
|
1994
|
+
hostname TEXT NOT NULL,
|
|
1995
|
+
projects TEXT NOT NULL DEFAULT '[]',
|
|
1996
|
+
agents TEXT NOT NULL DEFAULT '[]',
|
|
1997
|
+
connected INTEGER DEFAULT 0,
|
|
1998
|
+
last_seen TEXT NOT NULL
|
|
1999
|
+
);
|
|
2000
|
+
`);
|
|
2001
|
+
await client.executeMultiple(`
|
|
2002
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
2003
|
+
id TEXT PRIMARY KEY,
|
|
2004
|
+
from_agent TEXT NOT NULL,
|
|
2005
|
+
from_device TEXT NOT NULL DEFAULT 'local',
|
|
2006
|
+
target_agent TEXT NOT NULL,
|
|
2007
|
+
target_project TEXT,
|
|
2008
|
+
target_device TEXT NOT NULL DEFAULT 'local',
|
|
2009
|
+
session_scope TEXT,
|
|
2010
|
+
content TEXT NOT NULL,
|
|
2011
|
+
priority TEXT DEFAULT 'normal',
|
|
2012
|
+
status TEXT DEFAULT 'pending',
|
|
2013
|
+
server_seq INTEGER,
|
|
2014
|
+
retry_count INTEGER DEFAULT 0,
|
|
2015
|
+
created_at TEXT NOT NULL,
|
|
2016
|
+
delivered_at TEXT,
|
|
2017
|
+
processed_at TEXT,
|
|
2018
|
+
failed_at TEXT,
|
|
2019
|
+
failure_reason TEXT
|
|
2020
|
+
);
|
|
2021
|
+
|
|
2022
|
+
CREATE INDEX IF NOT EXISTS idx_messages_target
|
|
2023
|
+
ON messages(target_agent, session_scope, status);
|
|
2024
|
+
|
|
2025
|
+
CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
|
|
2026
|
+
ON messages(target_agent, session_scope, from_agent, server_seq);
|
|
2027
|
+
`);
|
|
2028
|
+
try {
|
|
2029
|
+
await client.execute({
|
|
2030
|
+
sql: `ALTER TABLE notifications ADD COLUMN session_scope TEXT`,
|
|
2031
|
+
args: []
|
|
2032
|
+
});
|
|
2033
|
+
} catch {
|
|
2034
|
+
}
|
|
2035
|
+
try {
|
|
2036
|
+
await client.execute({
|
|
2037
|
+
sql: `ALTER TABLE messages ADD COLUMN session_scope TEXT`,
|
|
2038
|
+
args: []
|
|
2039
|
+
});
|
|
2040
|
+
} catch {
|
|
2041
|
+
}
|
|
2042
|
+
await client.executeMultiple(`
|
|
2043
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_agent_scope_read
|
|
2044
|
+
ON notifications(agent_id, session_scope, read, created_at);
|
|
2045
|
+
|
|
2046
|
+
CREATE INDEX IF NOT EXISTS idx_messages_target_scope_status
|
|
2047
|
+
ON messages(target_agent, session_scope, status, created_at);
|
|
2048
|
+
`);
|
|
2049
|
+
try {
|
|
2050
|
+
await client.execute({
|
|
2051
|
+
sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
|
|
2052
|
+
args: []
|
|
2053
|
+
});
|
|
2054
|
+
await client.execute({
|
|
2055
|
+
sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
|
|
2056
|
+
args: []
|
|
2057
|
+
});
|
|
2058
|
+
await client.execute({
|
|
2059
|
+
sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
|
|
2060
|
+
args: []
|
|
2061
|
+
});
|
|
2062
|
+
await client.execute({
|
|
2063
|
+
sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
|
|
2064
|
+
args: []
|
|
2065
|
+
});
|
|
2066
|
+
} catch {
|
|
2067
|
+
}
|
|
2068
|
+
await client.executeMultiple(`
|
|
1367
2069
|
CREATE TABLE IF NOT EXISTS trajectories (
|
|
1368
2070
|
id TEXT PRIMARY KEY,
|
|
1369
2071
|
task_id TEXT NOT NULL,
|
|
@@ -1955,19 +2657,40 @@ async function ensureSchema() {
|
|
|
1955
2657
|
} catch {
|
|
1956
2658
|
}
|
|
1957
2659
|
}
|
|
1958
|
-
|
|
2660
|
+
async function disposeDatabase() {
|
|
2661
|
+
if (_walCheckpointTimer) {
|
|
2662
|
+
clearInterval(_walCheckpointTimer);
|
|
2663
|
+
_walCheckpointTimer = null;
|
|
2664
|
+
}
|
|
2665
|
+
if (_daemonClient) {
|
|
2666
|
+
_daemonClient.close();
|
|
2667
|
+
_daemonClient = null;
|
|
2668
|
+
}
|
|
2669
|
+
if (_adapterClient && _adapterClient !== _resilientClient) {
|
|
2670
|
+
_adapterClient.close();
|
|
2671
|
+
}
|
|
2672
|
+
_adapterClient = null;
|
|
2673
|
+
if (_client) {
|
|
2674
|
+
_client.close();
|
|
2675
|
+
_client = null;
|
|
2676
|
+
_resilientClient = null;
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
var _client, _resilientClient, _walCheckpointTimer, _daemonClient, _adapterClient, initTurso, disposeTurso;
|
|
1959
2680
|
var init_database = __esm({
|
|
1960
2681
|
"src/lib/database.ts"() {
|
|
1961
2682
|
"use strict";
|
|
1962
2683
|
init_db_retry();
|
|
1963
2684
|
init_employees();
|
|
1964
2685
|
init_database_adapter();
|
|
2686
|
+
init_memory();
|
|
1965
2687
|
_client = null;
|
|
1966
2688
|
_resilientClient = null;
|
|
1967
2689
|
_walCheckpointTimer = null;
|
|
1968
2690
|
_daemonClient = null;
|
|
1969
2691
|
_adapterClient = null;
|
|
1970
2692
|
initTurso = initDatabase;
|
|
2693
|
+
disposeTurso = disposeDatabase;
|
|
1971
2694
|
}
|
|
1972
2695
|
});
|
|
1973
2696
|
|
|
@@ -1985,12 +2708,12 @@ __export(shard_manager_exports, {
|
|
|
1985
2708
|
listShards: () => listShards,
|
|
1986
2709
|
shardExists: () => shardExists
|
|
1987
2710
|
});
|
|
1988
|
-
import
|
|
1989
|
-
import { existsSync as
|
|
2711
|
+
import path7 from "path";
|
|
2712
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync } from "fs";
|
|
1990
2713
|
import { createClient as createClient2 } from "@libsql/client";
|
|
1991
2714
|
function initShardManager(encryptionKey) {
|
|
1992
2715
|
_encryptionKey = encryptionKey;
|
|
1993
|
-
if (!
|
|
2716
|
+
if (!existsSync7(SHARDS_DIR)) {
|
|
1994
2717
|
mkdirSync2(SHARDS_DIR, { recursive: true });
|
|
1995
2718
|
}
|
|
1996
2719
|
_shardingEnabled = true;
|
|
@@ -2020,7 +2743,7 @@ function getShardClient(projectName) {
|
|
|
2020
2743
|
while (_shards.size >= MAX_OPEN_SHARDS) {
|
|
2021
2744
|
evictLRU();
|
|
2022
2745
|
}
|
|
2023
|
-
const dbPath =
|
|
2746
|
+
const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
|
|
2024
2747
|
const client = createClient2({
|
|
2025
2748
|
url: `file:${dbPath}`,
|
|
2026
2749
|
encryptionKey: _encryptionKey
|
|
@@ -2031,10 +2754,10 @@ function getShardClient(projectName) {
|
|
|
2031
2754
|
}
|
|
2032
2755
|
function shardExists(projectName) {
|
|
2033
2756
|
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
2034
|
-
return
|
|
2757
|
+
return existsSync7(path7.join(SHARDS_DIR, `${safeName}.db`));
|
|
2035
2758
|
}
|
|
2036
2759
|
function listShards() {
|
|
2037
|
-
if (!
|
|
2760
|
+
if (!existsSync7(SHARDS_DIR)) return [];
|
|
2038
2761
|
return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
2039
2762
|
}
|
|
2040
2763
|
async function ensureShardSchema(client) {
|
|
@@ -2281,7 +3004,7 @@ var init_shard_manager = __esm({
|
|
|
2281
3004
|
"src/lib/shard-manager.ts"() {
|
|
2282
3005
|
"use strict";
|
|
2283
3006
|
init_config();
|
|
2284
|
-
SHARDS_DIR =
|
|
3007
|
+
SHARDS_DIR = path7.join(EXE_AI_DIR, "shards");
|
|
2285
3008
|
SHARD_IDLE_MS = 5 * 60 * 1e3;
|
|
2286
3009
|
MAX_OPEN_SHARDS = 10;
|
|
2287
3010
|
EVICTION_INTERVAL_MS = 60 * 1e3;
|
|
@@ -2401,554 +3124,164 @@ var init_platform_procedures = __esm({
|
|
|
2401
3124
|
domain: "architecture",
|
|
2402
3125
|
priority: "p0",
|
|
2403
3126
|
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."
|
|
2404
|
-
}
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
//
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
var init_global_procedures = __esm({
|
|
2472
|
-
"src/lib/global-procedures.ts"() {
|
|
2473
|
-
"use strict";
|
|
2474
|
-
init_database();
|
|
2475
|
-
init_platform_procedures();
|
|
2476
|
-
_customerCache = "";
|
|
2477
|
-
_cacheLoaded = false;
|
|
2478
|
-
_platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
|
|
2479
|
-
${p.content}`).join("\n\n");
|
|
2480
|
-
}
|
|
2481
|
-
});
|
|
2482
|
-
|
|
2483
|
-
// src/lib/daemon-auth.ts
|
|
2484
|
-
import crypto from "crypto";
|
|
2485
|
-
import path6 from "path";
|
|
2486
|
-
import { existsSync as existsSync6, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
2487
|
-
function normalizeToken(token) {
|
|
2488
|
-
if (!token) return null;
|
|
2489
|
-
const trimmed = token.trim();
|
|
2490
|
-
return trimmed.length > 0 ? trimmed : null;
|
|
2491
|
-
}
|
|
2492
|
-
function readDaemonToken() {
|
|
2493
|
-
try {
|
|
2494
|
-
if (!existsSync6(DAEMON_TOKEN_PATH)) return null;
|
|
2495
|
-
return normalizeToken(readFileSync3(DAEMON_TOKEN_PATH, "utf8"));
|
|
2496
|
-
} catch {
|
|
2497
|
-
return null;
|
|
2498
|
-
}
|
|
2499
|
-
}
|
|
2500
|
-
function ensureDaemonToken(seed) {
|
|
2501
|
-
const existing = readDaemonToken();
|
|
2502
|
-
if (existing) return existing;
|
|
2503
|
-
const token = normalizeToken(seed) ?? crypto.randomBytes(32).toString("hex");
|
|
2504
|
-
ensurePrivateDirSync(EXE_AI_DIR);
|
|
2505
|
-
writeFileSync2(DAEMON_TOKEN_PATH, `${token}
|
|
2506
|
-
`, "utf8");
|
|
2507
|
-
enforcePrivateFileSync(DAEMON_TOKEN_PATH);
|
|
2508
|
-
return token;
|
|
2509
|
-
}
|
|
2510
|
-
var DAEMON_TOKEN_PATH;
|
|
2511
|
-
var init_daemon_auth = __esm({
|
|
2512
|
-
"src/lib/daemon-auth.ts"() {
|
|
2513
|
-
"use strict";
|
|
2514
|
-
init_config();
|
|
2515
|
-
init_secure_files();
|
|
2516
|
-
DAEMON_TOKEN_PATH = path6.join(EXE_AI_DIR, "exed.token");
|
|
2517
|
-
}
|
|
2518
|
-
});
|
|
2519
|
-
|
|
2520
|
-
// src/lib/exe-daemon-client.ts
|
|
2521
|
-
import net from "net";
|
|
2522
|
-
import os5 from "os";
|
|
2523
|
-
import { spawn } from "child_process";
|
|
2524
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
2525
|
-
import { existsSync as existsSync7, unlinkSync as unlinkSync2, readFileSync as readFileSync4, openSync, closeSync, statSync } from "fs";
|
|
2526
|
-
import path7 from "path";
|
|
2527
|
-
import { fileURLToPath } from "url";
|
|
2528
|
-
function handleData(chunk) {
|
|
2529
|
-
_buffer += chunk.toString();
|
|
2530
|
-
if (_buffer.length > MAX_BUFFER) {
|
|
2531
|
-
_buffer = "";
|
|
2532
|
-
return;
|
|
2533
|
-
}
|
|
2534
|
-
let newlineIdx;
|
|
2535
|
-
while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
|
|
2536
|
-
const line = _buffer.slice(0, newlineIdx).trim();
|
|
2537
|
-
_buffer = _buffer.slice(newlineIdx + 1);
|
|
2538
|
-
if (!line) continue;
|
|
2539
|
-
try {
|
|
2540
|
-
const response = JSON.parse(line);
|
|
2541
|
-
const id = response.id;
|
|
2542
|
-
if (!id) continue;
|
|
2543
|
-
const entry = _pending.get(id);
|
|
2544
|
-
if (entry) {
|
|
2545
|
-
clearTimeout(entry.timer);
|
|
2546
|
-
_pending.delete(id);
|
|
2547
|
-
entry.resolve(response);
|
|
2548
|
-
}
|
|
2549
|
-
} catch {
|
|
2550
|
-
}
|
|
2551
|
-
}
|
|
2552
|
-
}
|
|
2553
|
-
function cleanupStaleFiles() {
|
|
2554
|
-
if (existsSync7(PID_PATH)) {
|
|
2555
|
-
try {
|
|
2556
|
-
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
2557
|
-
if (pid > 0) {
|
|
2558
|
-
try {
|
|
2559
|
-
process.kill(pid, 0);
|
|
2560
|
-
return;
|
|
2561
|
-
} catch {
|
|
2562
|
-
}
|
|
2563
|
-
}
|
|
2564
|
-
} catch {
|
|
2565
|
-
}
|
|
2566
|
-
try {
|
|
2567
|
-
unlinkSync2(PID_PATH);
|
|
2568
|
-
} catch {
|
|
2569
|
-
}
|
|
2570
|
-
try {
|
|
2571
|
-
unlinkSync2(SOCKET_PATH);
|
|
2572
|
-
} catch {
|
|
2573
|
-
}
|
|
2574
|
-
}
|
|
2575
|
-
}
|
|
2576
|
-
function findPackageRoot() {
|
|
2577
|
-
let dir = path7.dirname(fileURLToPath(import.meta.url));
|
|
2578
|
-
const { root } = path7.parse(dir);
|
|
2579
|
-
while (dir !== root) {
|
|
2580
|
-
if (existsSync7(path7.join(dir, "package.json"))) return dir;
|
|
2581
|
-
dir = path7.dirname(dir);
|
|
2582
|
-
}
|
|
2583
|
-
return null;
|
|
2584
|
-
}
|
|
2585
|
-
function getAvailableMemoryGB() {
|
|
2586
|
-
if (process.platform === "darwin") {
|
|
2587
|
-
try {
|
|
2588
|
-
const { execSync: execSync2 } = __require("child_process");
|
|
2589
|
-
const vmstat = execSync2("vm_stat", { encoding: "utf8" });
|
|
2590
|
-
const pageSize = 16384;
|
|
2591
|
-
const pageSizeMatch = vmstat.match(/page size of (\d+) bytes/);
|
|
2592
|
-
const actualPageSize = pageSizeMatch ? parseInt(pageSizeMatch[1], 10) : pageSize;
|
|
2593
|
-
const free = vmstat.match(/Pages free:\s+(\d+)/);
|
|
2594
|
-
const inactive = vmstat.match(/Pages inactive:\s+(\d+)/);
|
|
2595
|
-
const speculative = vmstat.match(/Pages speculative:\s+(\d+)/);
|
|
2596
|
-
const freePages = free ? parseInt(free[1], 10) : 0;
|
|
2597
|
-
const inactivePages = inactive ? parseInt(inactive[1], 10) : 0;
|
|
2598
|
-
const speculativePages = speculative ? parseInt(speculative[1], 10) : 0;
|
|
2599
|
-
return (freePages + inactivePages + speculativePages) * actualPageSize / (1024 * 1024 * 1024);
|
|
2600
|
-
} catch {
|
|
2601
|
-
return os5.freemem() / (1024 * 1024 * 1024);
|
|
2602
|
-
}
|
|
2603
|
-
}
|
|
2604
|
-
return os5.freemem() / (1024 * 1024 * 1024);
|
|
2605
|
-
}
|
|
2606
|
-
function spawnDaemon() {
|
|
2607
|
-
const freeGB = getAvailableMemoryGB();
|
|
2608
|
-
const totalGB = os5.totalmem() / (1024 * 1024 * 1024);
|
|
2609
|
-
if (totalGB <= 8) {
|
|
2610
|
-
process.stderr.write(
|
|
2611
|
-
`[exed-client] SKIP: ${totalGB.toFixed(0)}GB system \u2014 embedding daemon disabled. Using keyword search only. Minimum 16GB recommended for vector search.
|
|
2612
|
-
`
|
|
2613
|
-
);
|
|
2614
|
-
return;
|
|
2615
|
-
}
|
|
2616
|
-
if (totalGB <= 16 && freeGB < 2) {
|
|
2617
|
-
process.stderr.write(
|
|
2618
|
-
`[exed-client] SKIP: low memory (${freeGB.toFixed(1)}GB available / ${totalGB.toFixed(0)}GB total). Embedding daemon not started \u2014 using keyword search only.
|
|
2619
|
-
`
|
|
2620
|
-
);
|
|
2621
|
-
return;
|
|
2622
|
-
}
|
|
2623
|
-
const pkgRoot = findPackageRoot();
|
|
2624
|
-
if (!pkgRoot) {
|
|
2625
|
-
process.stderr.write("[exed-client] WARN: cannot find package root\n");
|
|
2626
|
-
return;
|
|
2627
|
-
}
|
|
2628
|
-
const daemonPath = path7.join(pkgRoot, "dist", "lib", "exe-daemon.js");
|
|
2629
|
-
if (!existsSync7(daemonPath)) {
|
|
2630
|
-
process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
|
|
2631
|
-
`);
|
|
2632
|
-
return;
|
|
2633
|
-
}
|
|
2634
|
-
const resolvedPath = daemonPath;
|
|
2635
|
-
const daemonToken = ensureDaemonToken(process.env[DAEMON_TOKEN_ENV] ?? null);
|
|
2636
|
-
process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
|
|
2637
|
-
`);
|
|
2638
|
-
const logPath = path7.join(path7.dirname(SOCKET_PATH), "exed.log");
|
|
2639
|
-
let stderrFd = "ignore";
|
|
2640
|
-
try {
|
|
2641
|
-
stderrFd = openSync(logPath, "a");
|
|
2642
|
-
} catch {
|
|
2643
|
-
}
|
|
2644
|
-
const heapCapMB = totalGB <= 8 ? 256 : 512;
|
|
2645
|
-
const nodeArgs = [`--max-old-space-size=${heapCapMB}`, resolvedPath];
|
|
2646
|
-
const child = spawn(process.execPath, nodeArgs, {
|
|
2647
|
-
detached: true,
|
|
2648
|
-
stdio: ["ignore", "ignore", stderrFd],
|
|
2649
|
-
env: {
|
|
2650
|
-
...process.env,
|
|
2651
|
-
TMUX: void 0,
|
|
2652
|
-
// Daemon is global — must not inherit session scope
|
|
2653
|
-
TMUX_PANE: void 0,
|
|
2654
|
-
// Prevents resolveExeSession() from scoping to one session
|
|
2655
|
-
EXE_DAEMON_SOCK: SOCKET_PATH,
|
|
2656
|
-
EXE_DAEMON_PID: PID_PATH,
|
|
2657
|
-
[DAEMON_TOKEN_ENV]: daemonToken
|
|
2658
|
-
}
|
|
2659
|
-
});
|
|
2660
|
-
child.unref();
|
|
2661
|
-
if (typeof stderrFd === "number") {
|
|
2662
|
-
try {
|
|
2663
|
-
closeSync(stderrFd);
|
|
2664
|
-
} catch {
|
|
2665
|
-
}
|
|
2666
|
-
}
|
|
2667
|
-
}
|
|
2668
|
-
function acquireSpawnLock() {
|
|
2669
|
-
try {
|
|
2670
|
-
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
2671
|
-
closeSync(fd);
|
|
2672
|
-
return true;
|
|
2673
|
-
} catch {
|
|
2674
|
-
try {
|
|
2675
|
-
const stat = statSync(SPAWN_LOCK_PATH);
|
|
2676
|
-
if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
|
|
2677
|
-
try {
|
|
2678
|
-
unlinkSync2(SPAWN_LOCK_PATH);
|
|
2679
|
-
} catch {
|
|
2680
|
-
}
|
|
2681
|
-
try {
|
|
2682
|
-
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
2683
|
-
closeSync(fd);
|
|
2684
|
-
return true;
|
|
2685
|
-
} catch {
|
|
2686
|
-
}
|
|
2687
|
-
}
|
|
2688
|
-
} catch {
|
|
2689
|
-
}
|
|
2690
|
-
return false;
|
|
2691
|
-
}
|
|
2692
|
-
}
|
|
2693
|
-
function releaseSpawnLock() {
|
|
2694
|
-
try {
|
|
2695
|
-
unlinkSync2(SPAWN_LOCK_PATH);
|
|
2696
|
-
} catch {
|
|
2697
|
-
}
|
|
2698
|
-
}
|
|
2699
|
-
function connectToSocket() {
|
|
2700
|
-
return new Promise((resolve) => {
|
|
2701
|
-
if (_socket && _connected) {
|
|
2702
|
-
resolve(true);
|
|
2703
|
-
return;
|
|
2704
|
-
}
|
|
2705
|
-
const socket = net.createConnection({ path: SOCKET_PATH });
|
|
2706
|
-
const connectTimeout = setTimeout(() => {
|
|
2707
|
-
socket.destroy();
|
|
2708
|
-
resolve(false);
|
|
2709
|
-
}, 2e3);
|
|
2710
|
-
socket.on("connect", () => {
|
|
2711
|
-
clearTimeout(connectTimeout);
|
|
2712
|
-
_socket = socket;
|
|
2713
|
-
_connected = true;
|
|
2714
|
-
_buffer = "";
|
|
2715
|
-
socket.on("data", handleData);
|
|
2716
|
-
socket.on("close", () => {
|
|
2717
|
-
_connected = false;
|
|
2718
|
-
_socket = null;
|
|
2719
|
-
for (const [id, entry] of _pending) {
|
|
2720
|
-
clearTimeout(entry.timer);
|
|
2721
|
-
_pending.delete(id);
|
|
2722
|
-
entry.resolve({ error: "Connection closed" });
|
|
2723
|
-
}
|
|
2724
|
-
});
|
|
2725
|
-
socket.on("error", () => {
|
|
2726
|
-
_connected = false;
|
|
2727
|
-
_socket = null;
|
|
2728
|
-
});
|
|
2729
|
-
resolve(true);
|
|
2730
|
-
});
|
|
2731
|
-
socket.on("error", () => {
|
|
2732
|
-
clearTimeout(connectTimeout);
|
|
2733
|
-
resolve(false);
|
|
2734
|
-
});
|
|
2735
|
-
});
|
|
2736
|
-
}
|
|
2737
|
-
async function connectEmbedDaemon() {
|
|
2738
|
-
if (_socket && _connected) return true;
|
|
2739
|
-
if (await connectToSocket()) return true;
|
|
2740
|
-
if (acquireSpawnLock()) {
|
|
2741
|
-
try {
|
|
2742
|
-
cleanupStaleFiles();
|
|
2743
|
-
spawnDaemon();
|
|
2744
|
-
} finally {
|
|
2745
|
-
releaseSpawnLock();
|
|
2746
|
-
}
|
|
2747
|
-
}
|
|
2748
|
-
const start = Date.now();
|
|
2749
|
-
let delay2 = 100;
|
|
2750
|
-
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
2751
|
-
await new Promise((r) => setTimeout(r, delay2));
|
|
2752
|
-
if (await connectToSocket()) return true;
|
|
2753
|
-
delay2 = Math.min(delay2 * 2, 3e3);
|
|
3127
|
+
},
|
|
3128
|
+
// --- MCP is the ONLY data interface ---
|
|
3129
|
+
{
|
|
3130
|
+
title: "MCP disconnect \u2014 ask the user, never work around it",
|
|
3131
|
+
domain: "workflow",
|
|
3132
|
+
priority: "p0",
|
|
3133
|
+
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."
|
|
3134
|
+
},
|
|
3135
|
+
// --- MCP Tool Catalog (Layer 0 — every agent knows what tools exist) ---
|
|
3136
|
+
{
|
|
3137
|
+
title: "MCP tools \u2014 memory and search",
|
|
3138
|
+
domain: "tool-use",
|
|
3139
|
+
priority: "p1",
|
|
3140
|
+
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)."
|
|
3141
|
+
},
|
|
3142
|
+
{
|
|
3143
|
+
title: "MCP tools \u2014 task orchestration",
|
|
3144
|
+
domain: "tool-use",
|
|
3145
|
+
priority: "p1",
|
|
3146
|
+
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."
|
|
3147
|
+
},
|
|
3148
|
+
{
|
|
3149
|
+
title: "MCP tools \u2014 knowledge graph (GraphRAG)",
|
|
3150
|
+
domain: "tool-use",
|
|
3151
|
+
priority: "p1",
|
|
3152
|
+
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."
|
|
3153
|
+
},
|
|
3154
|
+
{
|
|
3155
|
+
title: "MCP tools \u2014 identity, behavior, and decisions",
|
|
3156
|
+
domain: "tool-use",
|
|
3157
|
+
priority: "p1",
|
|
3158
|
+
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."
|
|
3159
|
+
},
|
|
3160
|
+
{
|
|
3161
|
+
title: "MCP tools \u2014 communication and messaging",
|
|
3162
|
+
domain: "tool-use",
|
|
3163
|
+
priority: "p1",
|
|
3164
|
+
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.)."
|
|
3165
|
+
},
|
|
3166
|
+
{
|
|
3167
|
+
title: "MCP tools \u2014 wiki, documents, and content",
|
|
3168
|
+
domain: "tool-use",
|
|
3169
|
+
priority: "p1",
|
|
3170
|
+
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."
|
|
3171
|
+
},
|
|
3172
|
+
{
|
|
3173
|
+
title: "MCP tools \u2014 system, operations, and admin",
|
|
3174
|
+
domain: "tool-use",
|
|
3175
|
+
priority: "p1",
|
|
3176
|
+
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."
|
|
3177
|
+
},
|
|
3178
|
+
{
|
|
3179
|
+
title: "MCP tools \u2014 config, licensing, and team",
|
|
3180
|
+
domain: "tool-use",
|
|
3181
|
+
priority: "p1",
|
|
3182
|
+
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."
|
|
3183
|
+
},
|
|
3184
|
+
{
|
|
3185
|
+
title: "MCP tools \u2014 advanced (triggers, skills, orchestration)",
|
|
3186
|
+
domain: "tool-use",
|
|
3187
|
+
priority: "p1",
|
|
3188
|
+
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."
|
|
3189
|
+
}
|
|
3190
|
+
];
|
|
3191
|
+
PLATFORM_PROCEDURE_TITLES = new Set(
|
|
3192
|
+
PLATFORM_PROCEDURES.map((p) => p.title)
|
|
3193
|
+
);
|
|
2754
3194
|
}
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
}, timeoutMs);
|
|
2772
|
-
_pending.set(id, { resolve, timer });
|
|
2773
|
-
try {
|
|
2774
|
-
_socket.write(JSON.stringify({ id, token, ...payload }) + "\n");
|
|
2775
|
-
} catch {
|
|
2776
|
-
clearTimeout(timer);
|
|
2777
|
-
_pending.delete(id);
|
|
2778
|
-
resolve({ error: "Write failed" });
|
|
2779
|
-
}
|
|
3195
|
+
});
|
|
3196
|
+
|
|
3197
|
+
// src/lib/global-procedures.ts
|
|
3198
|
+
var global_procedures_exports = {};
|
|
3199
|
+
__export(global_procedures_exports, {
|
|
3200
|
+
deactivateGlobalProcedure: () => deactivateGlobalProcedure,
|
|
3201
|
+
getGlobalProceduresBlock: () => getGlobalProceduresBlock,
|
|
3202
|
+
loadGlobalProcedures: () => loadGlobalProcedures,
|
|
3203
|
+
storeGlobalProcedure: () => storeGlobalProcedure
|
|
3204
|
+
});
|
|
3205
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
3206
|
+
async function loadGlobalProcedures() {
|
|
3207
|
+
const client = getClient();
|
|
3208
|
+
const result = await client.execute({
|
|
3209
|
+
sql: "SELECT * FROM global_procedures WHERE active = 1 ORDER BY priority ASC, created_at ASC",
|
|
3210
|
+
args: []
|
|
2780
3211
|
});
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
if (
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
return null;
|
|
2789
|
-
}
|
|
2790
|
-
function killAndRespawnDaemon() {
|
|
2791
|
-
if (!acquireSpawnLock()) {
|
|
2792
|
-
process.stderr.write("[exed-client] Another process is already restarting daemon \u2014 skipping\n");
|
|
2793
|
-
if (_socket) {
|
|
2794
|
-
_socket.destroy();
|
|
2795
|
-
_socket = null;
|
|
2796
|
-
}
|
|
2797
|
-
_connected = false;
|
|
2798
|
-
_buffer = "";
|
|
2799
|
-
return;
|
|
2800
|
-
}
|
|
2801
|
-
try {
|
|
2802
|
-
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
2803
|
-
if (existsSync7(PID_PATH)) {
|
|
2804
|
-
try {
|
|
2805
|
-
const pid = parseInt(readFileSync4(PID_PATH, "utf8").trim(), 10);
|
|
2806
|
-
if (pid > 0) {
|
|
2807
|
-
try {
|
|
2808
|
-
process.kill(pid, "SIGKILL");
|
|
2809
|
-
} catch {
|
|
2810
|
-
}
|
|
2811
|
-
}
|
|
2812
|
-
} catch {
|
|
2813
|
-
}
|
|
2814
|
-
}
|
|
2815
|
-
if (_socket) {
|
|
2816
|
-
_socket.destroy();
|
|
2817
|
-
_socket = null;
|
|
2818
|
-
}
|
|
2819
|
-
_connected = false;
|
|
2820
|
-
_buffer = "";
|
|
2821
|
-
try {
|
|
2822
|
-
unlinkSync2(PID_PATH);
|
|
2823
|
-
} catch {
|
|
2824
|
-
}
|
|
2825
|
-
try {
|
|
2826
|
-
unlinkSync2(SOCKET_PATH);
|
|
2827
|
-
} catch {
|
|
2828
|
-
}
|
|
2829
|
-
spawnDaemon();
|
|
2830
|
-
} finally {
|
|
2831
|
-
releaseSpawnLock();
|
|
3212
|
+
const allRows = result.rows;
|
|
3213
|
+
const customerOnly = allRows.filter((p) => !PLATFORM_PROCEDURE_TITLES.has(p.title));
|
|
3214
|
+
if (customerOnly.length > 0) {
|
|
3215
|
+
_customerCache = customerOnly.map((p) => `### ${p.title}
|
|
3216
|
+
${p.content}`).join("\n\n");
|
|
3217
|
+
} else {
|
|
3218
|
+
_customerCache = "";
|
|
2832
3219
|
}
|
|
3220
|
+
_cacheLoaded = true;
|
|
3221
|
+
return customerOnly;
|
|
2833
3222
|
}
|
|
2834
|
-
function
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
3223
|
+
function getGlobalProceduresBlock() {
|
|
3224
|
+
const sections = [];
|
|
3225
|
+
if (_platformCache) sections.push(_platformCache);
|
|
3226
|
+
if (_cacheLoaded && _customerCache) sections.push(_customerCache);
|
|
3227
|
+
if (sections.length === 0) return "";
|
|
3228
|
+
return `## Organization-Wide Procedures (MANDATORY \u2014 supersedes all other rules)
|
|
3229
|
+
|
|
3230
|
+
${sections.join("\n\n")}
|
|
3231
|
+
`;
|
|
2841
3232
|
}
|
|
2842
|
-
async function
|
|
2843
|
-
const
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
await new Promise((r) => setTimeout(r, delayMs));
|
|
2854
|
-
if (!_connected) {
|
|
2855
|
-
if (!await connectToSocket()) continue;
|
|
2856
|
-
}
|
|
2857
|
-
const retry = await doRequest();
|
|
2858
|
-
if (!retry.error) {
|
|
2859
|
-
_consecutiveFailures = 0;
|
|
2860
|
-
return retry;
|
|
2861
|
-
}
|
|
2862
|
-
_consecutiveFailures++;
|
|
2863
|
-
}
|
|
2864
|
-
if (isDaemonTooYoung()) {
|
|
2865
|
-
process.stderr.write(`[exed-client] ${label}: daemon too young (< ${MIN_DAEMON_AGE_MS / 1e3}s) \u2014 skipping restart
|
|
2866
|
-
`);
|
|
2867
|
-
return { error: result.error };
|
|
2868
|
-
}
|
|
2869
|
-
process.stderr.write(`[exed-client] ${label}: ${_consecutiveFailures} consecutive failures \u2014 restarting daemon
|
|
2870
|
-
`);
|
|
2871
|
-
killAndRespawnDaemon();
|
|
2872
|
-
const start = Date.now();
|
|
2873
|
-
let delay2 = 200;
|
|
2874
|
-
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
2875
|
-
await new Promise((r) => setTimeout(r, delay2));
|
|
2876
|
-
if (await connectToSocket()) break;
|
|
2877
|
-
delay2 = Math.min(delay2 * 2, 3e3);
|
|
2878
|
-
}
|
|
2879
|
-
if (!_connected) return { error: "Daemon restart failed" };
|
|
2880
|
-
const final = await doRequest();
|
|
2881
|
-
if (!final.error) _consecutiveFailures = 0;
|
|
2882
|
-
return final;
|
|
3233
|
+
async function storeGlobalProcedure(input) {
|
|
3234
|
+
const id = randomUUID2();
|
|
3235
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3236
|
+
const client = getClient();
|
|
3237
|
+
await client.execute({
|
|
3238
|
+
sql: `INSERT INTO global_procedures (id, title, content, priority, domain, active, created_at, updated_at)
|
|
3239
|
+
VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
|
|
3240
|
+
args: [id, input.title, input.content, input.priority ?? "p0", input.domain ?? null, now, now]
|
|
3241
|
+
});
|
|
3242
|
+
await loadGlobalProcedures();
|
|
3243
|
+
return id;
|
|
2883
3244
|
}
|
|
2884
|
-
async function
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
const start = Date.now();
|
|
2894
|
-
let d = 200;
|
|
2895
|
-
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
2896
|
-
await new Promise((r) => setTimeout(r, d));
|
|
2897
|
-
if (await connectToSocket()) break;
|
|
2898
|
-
d = Math.min(d * 2, 3e3);
|
|
2899
|
-
}
|
|
2900
|
-
if (!_connected) return null;
|
|
2901
|
-
}
|
|
2902
|
-
}
|
|
2903
|
-
const result = await retryThenRestart(
|
|
2904
|
-
() => sendRequest([text], priority),
|
|
2905
|
-
"Embed"
|
|
2906
|
-
);
|
|
2907
|
-
return !result.error && result.vectors?.[0] ? result.vectors[0] : null;
|
|
3245
|
+
async function deactivateGlobalProcedure(id) {
|
|
3246
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3247
|
+
const client = getClient();
|
|
3248
|
+
const result = await client.execute({
|
|
3249
|
+
sql: "UPDATE global_procedures SET active = 0, updated_at = ? WHERE id = ?",
|
|
3250
|
+
args: [now, id]
|
|
3251
|
+
});
|
|
3252
|
+
await loadGlobalProcedures();
|
|
3253
|
+
return result.rowsAffected > 0;
|
|
2908
3254
|
}
|
|
2909
|
-
var
|
|
2910
|
-
var
|
|
2911
|
-
"src/lib/
|
|
3255
|
+
var _customerCache, _cacheLoaded, _platformCache;
|
|
3256
|
+
var init_global_procedures = __esm({
|
|
3257
|
+
"src/lib/global-procedures.ts"() {
|
|
2912
3258
|
"use strict";
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
CONNECT_TIMEOUT_MS = 15e3;
|
|
2920
|
-
REQUEST_TIMEOUT_MS = 3e4;
|
|
2921
|
-
DAEMON_TOKEN_ENV = "EXE_DAEMON_TOKEN";
|
|
2922
|
-
_socket = null;
|
|
2923
|
-
_connected = false;
|
|
2924
|
-
_buffer = "";
|
|
2925
|
-
_requestCount = 0;
|
|
2926
|
-
_consecutiveFailures = 0;
|
|
2927
|
-
HEALTH_CHECK_INTERVAL = 100;
|
|
2928
|
-
MAX_RETRIES_BEFORE_RESTART = 3;
|
|
2929
|
-
RETRY_DELAYS_MS = [1e3, 3e3, 5e3];
|
|
2930
|
-
MIN_DAEMON_AGE_MS = 3e4;
|
|
2931
|
-
_pending = /* @__PURE__ */ new Map();
|
|
2932
|
-
MAX_BUFFER = 1e7;
|
|
3259
|
+
init_database();
|
|
3260
|
+
init_platform_procedures();
|
|
3261
|
+
_customerCache = "";
|
|
3262
|
+
_cacheLoaded = false;
|
|
3263
|
+
_platformCache = PLATFORM_PROCEDURES.map((p) => `### ${p.title}
|
|
3264
|
+
${p.content}`).join("\n\n");
|
|
2933
3265
|
}
|
|
2934
3266
|
});
|
|
2935
3267
|
|
|
2936
3268
|
// src/lib/store.ts
|
|
2937
|
-
|
|
3269
|
+
init_memory();
|
|
2938
3270
|
init_database();
|
|
3271
|
+
import { createHash } from "crypto";
|
|
2939
3272
|
|
|
2940
3273
|
// src/lib/keychain.ts
|
|
2941
3274
|
import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
|
|
2942
|
-
import { existsSync as
|
|
2943
|
-
import
|
|
2944
|
-
import
|
|
3275
|
+
import { existsSync as existsSync6 } from "fs";
|
|
3276
|
+
import path6 from "path";
|
|
3277
|
+
import os5 from "os";
|
|
2945
3278
|
var SERVICE = "exe-mem";
|
|
2946
3279
|
var ACCOUNT = "master-key";
|
|
2947
3280
|
function getKeyDir() {
|
|
2948
|
-
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ??
|
|
3281
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
|
|
2949
3282
|
}
|
|
2950
3283
|
function getKeyPath() {
|
|
2951
|
-
return
|
|
3284
|
+
return path6.join(getKeyDir(), "master.key");
|
|
2952
3285
|
}
|
|
2953
3286
|
async function tryKeytar() {
|
|
2954
3287
|
try {
|
|
@@ -2969,9 +3302,9 @@ async function getMasterKey() {
|
|
|
2969
3302
|
}
|
|
2970
3303
|
}
|
|
2971
3304
|
const keyPath = getKeyPath();
|
|
2972
|
-
if (!
|
|
3305
|
+
if (!existsSync6(keyPath)) {
|
|
2973
3306
|
process.stderr.write(
|
|
2974
|
-
`[keychain] Key not found at ${keyPath} (HOME=${
|
|
3307
|
+
`[keychain] Key not found at ${keyPath} (HOME=${os5.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
|
|
2975
3308
|
`
|
|
2976
3309
|
);
|
|
2977
3310
|
return null;
|
|
@@ -3100,6 +3433,11 @@ async function initStore(options) {
|
|
|
3100
3433
|
encryptionKey: hexKey
|
|
3101
3434
|
});
|
|
3102
3435
|
await retryOnBusy2(() => ensureSchema(), "ensureSchema");
|
|
3436
|
+
try {
|
|
3437
|
+
const { initDaemonClient: initDaemonClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
|
|
3438
|
+
await initDaemonClient2();
|
|
3439
|
+
} catch {
|
|
3440
|
+
}
|
|
3103
3441
|
if (!options?.lightweight) {
|
|
3104
3442
|
try {
|
|
3105
3443
|
const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|