@askexenow/exe-os 0.8.0
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/LICENSE +21 -0
- package/README.md +139 -0
- package/dist/bin/backfill-responses.js +1912 -0
- package/dist/bin/backfill-vectors.js +1642 -0
- package/dist/bin/cleanup-stale-review-tasks.js +1339 -0
- package/dist/bin/cli.js +18800 -0
- package/dist/bin/exe-agent.js +1858 -0
- package/dist/bin/exe-assign.js +1957 -0
- package/dist/bin/exe-boot.js +6460 -0
- package/dist/bin/exe-call.js +197 -0
- package/dist/bin/exe-cloud.js +850 -0
- package/dist/bin/exe-dispatch.js +1146 -0
- package/dist/bin/exe-doctor.js +1657 -0
- package/dist/bin/exe-export-behaviors.js +1494 -0
- package/dist/bin/exe-forget.js +1627 -0
- package/dist/bin/exe-gateway.js +7732 -0
- package/dist/bin/exe-healthcheck.js +207 -0
- package/dist/bin/exe-heartbeat.js +1647 -0
- package/dist/bin/exe-kill.js +1479 -0
- package/dist/bin/exe-launch-agent.js +1704 -0
- package/dist/bin/exe-link.js +192 -0
- package/dist/bin/exe-new-employee.js +852 -0
- package/dist/bin/exe-pending-messages.js +1446 -0
- package/dist/bin/exe-pending-notifications.js +1321 -0
- package/dist/bin/exe-pending-reviews.js +1468 -0
- package/dist/bin/exe-repo-drift.js +95 -0
- package/dist/bin/exe-review.js +1590 -0
- package/dist/bin/exe-search.js +2651 -0
- package/dist/bin/exe-session-cleanup.js +3173 -0
- package/dist/bin/exe-settings.js +354 -0
- package/dist/bin/exe-status.js +1532 -0
- package/dist/bin/exe-team.js +1324 -0
- package/dist/bin/git-sweep.js +2185 -0
- package/dist/bin/graph-backfill.js +1968 -0
- package/dist/bin/graph-export.js +1604 -0
- package/dist/bin/install.js +656 -0
- package/dist/bin/list-providers.js +140 -0
- package/dist/bin/scan-tasks.js +1820 -0
- package/dist/bin/setup.js +951 -0
- package/dist/bin/shard-migrate.js +1494 -0
- package/dist/bin/update.js +95 -0
- package/dist/bin/wiki-sync.js +1514 -0
- package/dist/gateway/index.js +8848 -0
- package/dist/hooks/bug-report-worker.js +2743 -0
- package/dist/hooks/commit-complete.js +2108 -0
- package/dist/hooks/error-recall.js +2861 -0
- package/dist/hooks/exe-heartbeat-hook.js +232 -0
- package/dist/hooks/ingest-worker.js +4793 -0
- package/dist/hooks/ingest.js +684 -0
- package/dist/hooks/instructions-loaded.js +1880 -0
- package/dist/hooks/notification.js +1726 -0
- package/dist/hooks/post-compact.js +1751 -0
- package/dist/hooks/pre-compact.js +1746 -0
- package/dist/hooks/pre-tool-use.js +2191 -0
- package/dist/hooks/prompt-ingest-worker.js +2126 -0
- package/dist/hooks/prompt-submit.js +4693 -0
- package/dist/hooks/response-ingest-worker.js +1936 -0
- package/dist/hooks/session-end.js +1752 -0
- package/dist/hooks/session-start.js +2795 -0
- package/dist/hooks/stop.js +1835 -0
- package/dist/hooks/subagent-stop.js +1726 -0
- package/dist/hooks/summary-worker.js +2661 -0
- package/dist/index.js +11834 -0
- package/dist/lib/cloud-sync.js +495 -0
- package/dist/lib/config.js +222 -0
- package/dist/lib/consolidation.js +476 -0
- package/dist/lib/crypto.js +51 -0
- package/dist/lib/database.js +730 -0
- package/dist/lib/device-registry.js +900 -0
- package/dist/lib/embedder.js +632 -0
- package/dist/lib/employee-templates.js +543 -0
- package/dist/lib/employees.js +177 -0
- package/dist/lib/error-detector.js +156 -0
- package/dist/lib/exe-daemon-client.js +451 -0
- package/dist/lib/exe-daemon.js +8285 -0
- package/dist/lib/file-grep.js +199 -0
- package/dist/lib/hybrid-search.js +1819 -0
- package/dist/lib/identity-templates.js +320 -0
- package/dist/lib/identity.js +223 -0
- package/dist/lib/keychain.js +145 -0
- package/dist/lib/license.js +377 -0
- package/dist/lib/messaging.js +1376 -0
- package/dist/lib/reminders.js +63 -0
- package/dist/lib/schedules.js +1396 -0
- package/dist/lib/session-registry.js +52 -0
- package/dist/lib/skill-learning.js +477 -0
- package/dist/lib/status-brief.js +235 -0
- package/dist/lib/store.js +1551 -0
- package/dist/lib/task-router.js +62 -0
- package/dist/lib/tasks.js +2456 -0
- package/dist/lib/tmux-routing.js +2836 -0
- package/dist/lib/tmux-status.js +261 -0
- package/dist/lib/tmux-transport.js +83 -0
- package/dist/lib/transport.js +128 -0
- package/dist/lib/ws-auth.js +19 -0
- package/dist/lib/ws-client.js +160 -0
- package/dist/mcp/server.js +10538 -0
- package/dist/mcp/tools/complete-reminder.js +67 -0
- package/dist/mcp/tools/create-reminder.js +52 -0
- package/dist/mcp/tools/create-task.js +1853 -0
- package/dist/mcp/tools/deactivate-behavior.js +263 -0
- package/dist/mcp/tools/list-reminders.js +62 -0
- package/dist/mcp/tools/list-tasks.js +463 -0
- package/dist/mcp/tools/send-message.js +1382 -0
- package/dist/mcp/tools/update-task.js +1692 -0
- package/dist/runtime/index.js +6809 -0
- package/dist/tui/App.js +17479 -0
- package/package.json +104 -0
- package/src/commands/exe/assign.md +17 -0
- package/src/commands/exe/build-adv.md +381 -0
- package/src/commands/exe/call.md +133 -0
- package/src/commands/exe/cloud.md +17 -0
- package/src/commands/exe/employee-heartbeat.md +44 -0
- package/src/commands/exe/forget.md +15 -0
- package/src/commands/exe/heartbeat.md +92 -0
- package/src/commands/exe/intercom.md +81 -0
- package/src/commands/exe/kill.md +34 -0
- package/src/commands/exe/launch.md +52 -0
- package/src/commands/exe/link.md +17 -0
- package/src/commands/exe/logs.md +22 -0
- package/src/commands/exe/new-employee.md +12 -0
- package/src/commands/exe/review.md +14 -0
- package/src/commands/exe/schedule.md +108 -0
- package/src/commands/exe/search.md +13 -0
- package/src/commands/exe/sessions.md +25 -0
- package/src/commands/exe/settings.md +13 -0
- package/src/commands/exe/setup.md +171 -0
- package/src/commands/exe/status.md +15 -0
- package/src/commands/exe/team.md +11 -0
- package/src/commands/exe/update.md +11 -0
- package/src/commands/exe.md +181 -0
|
@@ -0,0 +1,2861 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
+
}) : x)(function(x) {
|
|
6
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
+
});
|
|
9
|
+
var __esm = (fn, res) => function __init() {
|
|
10
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// src/lib/config.ts
|
|
18
|
+
var config_exports = {};
|
|
19
|
+
__export(config_exports, {
|
|
20
|
+
CONFIG_MIGRATIONS: () => CONFIG_MIGRATIONS,
|
|
21
|
+
CONFIG_PATH: () => CONFIG_PATH,
|
|
22
|
+
CURRENT_CONFIG_VERSION: () => CURRENT_CONFIG_VERSION,
|
|
23
|
+
DB_PATH: () => DB_PATH,
|
|
24
|
+
EXE_AI_DIR: () => EXE_AI_DIR,
|
|
25
|
+
LEGACY_LANCE_PATH: () => LEGACY_LANCE_PATH,
|
|
26
|
+
MODELS_DIR: () => MODELS_DIR,
|
|
27
|
+
loadConfig: () => loadConfig,
|
|
28
|
+
loadConfigFrom: () => loadConfigFrom,
|
|
29
|
+
loadConfigSync: () => loadConfigSync,
|
|
30
|
+
migrateConfig: () => migrateConfig,
|
|
31
|
+
saveConfig: () => saveConfig
|
|
32
|
+
});
|
|
33
|
+
import { readFile, writeFile, mkdir } from "fs/promises";
|
|
34
|
+
import { readFileSync, existsSync, renameSync } from "fs";
|
|
35
|
+
import path from "path";
|
|
36
|
+
import os from "os";
|
|
37
|
+
function resolveDataDir() {
|
|
38
|
+
if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
|
|
39
|
+
if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
|
|
40
|
+
const newDir = path.join(os.homedir(), ".exe-os");
|
|
41
|
+
const legacyDir = path.join(os.homedir(), ".exe-mem");
|
|
42
|
+
if (!existsSync(newDir) && existsSync(legacyDir)) {
|
|
43
|
+
try {
|
|
44
|
+
renameSync(legacyDir, newDir);
|
|
45
|
+
process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
|
|
46
|
+
`);
|
|
47
|
+
} catch {
|
|
48
|
+
return legacyDir;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return newDir;
|
|
52
|
+
}
|
|
53
|
+
function migrateLegacyConfig(raw) {
|
|
54
|
+
if ("r2" in raw) {
|
|
55
|
+
process.stderr.write(
|
|
56
|
+
"[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
|
|
57
|
+
);
|
|
58
|
+
delete raw.r2;
|
|
59
|
+
}
|
|
60
|
+
if ("syncIntervalMs" in raw) {
|
|
61
|
+
delete raw.syncIntervalMs;
|
|
62
|
+
}
|
|
63
|
+
return raw;
|
|
64
|
+
}
|
|
65
|
+
function migrateConfig(raw) {
|
|
66
|
+
const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
|
|
67
|
+
let currentVersion = fromVersion;
|
|
68
|
+
let migrated = false;
|
|
69
|
+
if (currentVersion > CURRENT_CONFIG_VERSION) {
|
|
70
|
+
return { config: raw, migrated: false, fromVersion };
|
|
71
|
+
}
|
|
72
|
+
for (const migration of CONFIG_MIGRATIONS) {
|
|
73
|
+
if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
|
|
74
|
+
raw = migration.migrate(raw);
|
|
75
|
+
currentVersion = migration.to;
|
|
76
|
+
migrated = true;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return { config: raw, migrated, fromVersion };
|
|
80
|
+
}
|
|
81
|
+
function normalizeScalingRoadmap(raw) {
|
|
82
|
+
const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
|
|
83
|
+
const userRoadmap = raw.scalingRoadmap ?? {};
|
|
84
|
+
const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
|
|
85
|
+
if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
|
|
86
|
+
userAuto.enabled = raw.rerankerEnabled;
|
|
87
|
+
}
|
|
88
|
+
raw.scalingRoadmap = {
|
|
89
|
+
...userRoadmap,
|
|
90
|
+
rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function normalizeSessionLifecycle(raw) {
|
|
94
|
+
const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
|
|
95
|
+
const userSL = raw.sessionLifecycle ?? {};
|
|
96
|
+
raw.sessionLifecycle = { ...defaultSL, ...userSL };
|
|
97
|
+
}
|
|
98
|
+
async function loadConfig() {
|
|
99
|
+
const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
|
|
100
|
+
await mkdir(dir, { recursive: true });
|
|
101
|
+
const configPath = path.join(dir, "config.json");
|
|
102
|
+
if (!existsSync(configPath)) {
|
|
103
|
+
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
|
|
104
|
+
}
|
|
105
|
+
const raw = await readFile(configPath, "utf-8");
|
|
106
|
+
try {
|
|
107
|
+
let parsed = JSON.parse(raw);
|
|
108
|
+
parsed = migrateLegacyConfig(parsed);
|
|
109
|
+
const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
|
|
110
|
+
if (migrated) {
|
|
111
|
+
process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
|
|
112
|
+
`);
|
|
113
|
+
try {
|
|
114
|
+
await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
|
|
115
|
+
} catch {
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
normalizeScalingRoadmap(migratedCfg);
|
|
119
|
+
normalizeSessionLifecycle(migratedCfg);
|
|
120
|
+
const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
|
|
121
|
+
if (config.dbPath.startsWith("~")) {
|
|
122
|
+
config.dbPath = config.dbPath.replace(/^~/, os.homedir());
|
|
123
|
+
}
|
|
124
|
+
return config;
|
|
125
|
+
} catch {
|
|
126
|
+
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function loadConfigSync() {
|
|
130
|
+
const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
|
|
131
|
+
const configPath = path.join(dir, "config.json");
|
|
132
|
+
if (!existsSync(configPath)) {
|
|
133
|
+
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const raw = readFileSync(configPath, "utf-8");
|
|
137
|
+
let parsed = JSON.parse(raw);
|
|
138
|
+
parsed = migrateLegacyConfig(parsed);
|
|
139
|
+
const { config: migratedCfg } = migrateConfig(parsed);
|
|
140
|
+
normalizeScalingRoadmap(migratedCfg);
|
|
141
|
+
normalizeSessionLifecycle(migratedCfg);
|
|
142
|
+
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
|
|
143
|
+
} catch {
|
|
144
|
+
return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async function saveConfig(config) {
|
|
148
|
+
const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
|
|
149
|
+
await mkdir(dir, { recursive: true });
|
|
150
|
+
const configPath = path.join(dir, "config.json");
|
|
151
|
+
await writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
|
|
152
|
+
}
|
|
153
|
+
async function loadConfigFrom(configPath) {
|
|
154
|
+
const raw = await readFile(configPath, "utf-8");
|
|
155
|
+
try {
|
|
156
|
+
let parsed = JSON.parse(raw);
|
|
157
|
+
parsed = migrateLegacyConfig(parsed);
|
|
158
|
+
const { config: migratedCfg } = migrateConfig(parsed);
|
|
159
|
+
normalizeScalingRoadmap(migratedCfg);
|
|
160
|
+
normalizeSessionLifecycle(migratedCfg);
|
|
161
|
+
return { ...DEFAULT_CONFIG, ...migratedCfg };
|
|
162
|
+
} catch {
|
|
163
|
+
return { ...DEFAULT_CONFIG };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
|
|
167
|
+
var init_config = __esm({
|
|
168
|
+
"src/lib/config.ts"() {
|
|
169
|
+
"use strict";
|
|
170
|
+
EXE_AI_DIR = resolveDataDir();
|
|
171
|
+
DB_PATH = path.join(EXE_AI_DIR, "memories.db");
|
|
172
|
+
MODELS_DIR = path.join(EXE_AI_DIR, "models");
|
|
173
|
+
CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
|
|
174
|
+
LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
|
|
175
|
+
CURRENT_CONFIG_VERSION = 1;
|
|
176
|
+
DEFAULT_CONFIG = {
|
|
177
|
+
config_version: CURRENT_CONFIG_VERSION,
|
|
178
|
+
dbPath: DB_PATH,
|
|
179
|
+
modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
|
|
180
|
+
embeddingDim: 1024,
|
|
181
|
+
batchSize: 20,
|
|
182
|
+
flushIntervalMs: 1e4,
|
|
183
|
+
autoIngestion: true,
|
|
184
|
+
autoRetrieval: true,
|
|
185
|
+
searchMode: "hybrid",
|
|
186
|
+
hookSearchMode: "hybrid",
|
|
187
|
+
fileGrepEnabled: true,
|
|
188
|
+
splashEffect: true,
|
|
189
|
+
consolidationEnabled: true,
|
|
190
|
+
consolidationIntervalMs: 6 * 60 * 60 * 1e3,
|
|
191
|
+
consolidationModel: "claude-haiku-4-5-20251001",
|
|
192
|
+
consolidationMaxCallsPerRun: 20,
|
|
193
|
+
selfQueryRouter: true,
|
|
194
|
+
selfQueryModel: "claude-haiku-4-5-20251001",
|
|
195
|
+
rerankerEnabled: true,
|
|
196
|
+
scalingRoadmap: {
|
|
197
|
+
rerankerAutoTrigger: {
|
|
198
|
+
enabled: true,
|
|
199
|
+
broadQueryMinCardinality: 5e4,
|
|
200
|
+
fetchTopK: 150,
|
|
201
|
+
returnTopK: 5
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
graphRagEnabled: true,
|
|
205
|
+
wikiEnabled: false,
|
|
206
|
+
wikiUrl: "",
|
|
207
|
+
wikiApiKey: "",
|
|
208
|
+
wikiSyncIntervalMs: 30 * 60 * 1e3,
|
|
209
|
+
wikiWorkspaceMapping: {
|
|
210
|
+
exe: "Executive",
|
|
211
|
+
yoshi: "Engineering",
|
|
212
|
+
mari: "Marketing",
|
|
213
|
+
tom: "Engineering",
|
|
214
|
+
sasha: "Production"
|
|
215
|
+
},
|
|
216
|
+
wikiAutoUpdate: true,
|
|
217
|
+
wikiAutoUpdateThreshold: 0.5,
|
|
218
|
+
wikiAutoUpdateCreateNew: true,
|
|
219
|
+
skillLearning: true,
|
|
220
|
+
skillThreshold: 3,
|
|
221
|
+
skillModel: "claude-haiku-4-5-20251001",
|
|
222
|
+
exeHeartbeat: {
|
|
223
|
+
enabled: true,
|
|
224
|
+
intervalSeconds: 60,
|
|
225
|
+
staleInProgressThresholdHours: 2
|
|
226
|
+
},
|
|
227
|
+
sessionLifecycle: {
|
|
228
|
+
idleKillEnabled: true,
|
|
229
|
+
idleKillTicksRequired: 3,
|
|
230
|
+
idleKillIntercomAckWindowMs: 1e4,
|
|
231
|
+
maxAutoInstances: 10
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
CONFIG_MIGRATIONS = [
|
|
235
|
+
{
|
|
236
|
+
from: 0,
|
|
237
|
+
to: 1,
|
|
238
|
+
migrate: (cfg) => {
|
|
239
|
+
cfg.config_version = 1;
|
|
240
|
+
return cfg;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
];
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
// src/types/memory.ts
|
|
248
|
+
var EMBEDDING_DIM;
|
|
249
|
+
var init_memory = __esm({
|
|
250
|
+
"src/types/memory.ts"() {
|
|
251
|
+
"use strict";
|
|
252
|
+
EMBEDDING_DIM = 1024;
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
// src/lib/shard-manager.ts
|
|
257
|
+
var shard_manager_exports = {};
|
|
258
|
+
__export(shard_manager_exports, {
|
|
259
|
+
disposeShards: () => disposeShards,
|
|
260
|
+
ensureShardSchema: () => ensureShardSchema,
|
|
261
|
+
getReadyShardClient: () => getReadyShardClient,
|
|
262
|
+
getShardClient: () => getShardClient,
|
|
263
|
+
getShardsDir: () => getShardsDir,
|
|
264
|
+
initShardManager: () => initShardManager,
|
|
265
|
+
isShardingEnabled: () => isShardingEnabled,
|
|
266
|
+
listShards: () => listShards,
|
|
267
|
+
shardExists: () => shardExists
|
|
268
|
+
});
|
|
269
|
+
import path3 from "path";
|
|
270
|
+
import { existsSync as existsSync3, mkdirSync } from "fs";
|
|
271
|
+
import { createClient as createClient2 } from "@libsql/client";
|
|
272
|
+
function initShardManager(encryptionKey) {
|
|
273
|
+
_encryptionKey = encryptionKey;
|
|
274
|
+
if (!existsSync3(SHARDS_DIR)) {
|
|
275
|
+
mkdirSync(SHARDS_DIR, { recursive: true });
|
|
276
|
+
}
|
|
277
|
+
_shardingEnabled = true;
|
|
278
|
+
}
|
|
279
|
+
function isShardingEnabled() {
|
|
280
|
+
return _shardingEnabled;
|
|
281
|
+
}
|
|
282
|
+
function getShardsDir() {
|
|
283
|
+
return SHARDS_DIR;
|
|
284
|
+
}
|
|
285
|
+
function getShardClient(projectName) {
|
|
286
|
+
if (!_encryptionKey) {
|
|
287
|
+
throw new Error("Shard manager not initialized. Call initShardManager() first.");
|
|
288
|
+
}
|
|
289
|
+
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
290
|
+
if (!safeName) {
|
|
291
|
+
throw new Error(`Invalid project name for shard: "${projectName}"`);
|
|
292
|
+
}
|
|
293
|
+
const cached = _shards.get(safeName);
|
|
294
|
+
if (cached) return cached;
|
|
295
|
+
const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
|
|
296
|
+
const client = createClient2({
|
|
297
|
+
url: `file:${dbPath}`,
|
|
298
|
+
encryptionKey: _encryptionKey
|
|
299
|
+
});
|
|
300
|
+
_shards.set(safeName, client);
|
|
301
|
+
return client;
|
|
302
|
+
}
|
|
303
|
+
function shardExists(projectName) {
|
|
304
|
+
const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
305
|
+
return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
|
|
306
|
+
}
|
|
307
|
+
function listShards() {
|
|
308
|
+
if (!existsSync3(SHARDS_DIR)) return [];
|
|
309
|
+
const { readdirSync: readdirSync3 } = __require("fs");
|
|
310
|
+
return readdirSync3(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
|
|
311
|
+
}
|
|
312
|
+
async function ensureShardSchema(client) {
|
|
313
|
+
await client.execute("PRAGMA journal_mode = WAL");
|
|
314
|
+
await client.execute("PRAGMA busy_timeout = 5000");
|
|
315
|
+
try {
|
|
316
|
+
await client.execute("PRAGMA libsql_vector_search_ef = 128");
|
|
317
|
+
} catch {
|
|
318
|
+
}
|
|
319
|
+
await client.executeMultiple(`
|
|
320
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
321
|
+
id TEXT PRIMARY KEY,
|
|
322
|
+
agent_id TEXT NOT NULL,
|
|
323
|
+
agent_role TEXT NOT NULL,
|
|
324
|
+
session_id TEXT NOT NULL,
|
|
325
|
+
timestamp TEXT NOT NULL,
|
|
326
|
+
tool_name TEXT NOT NULL,
|
|
327
|
+
project_name TEXT NOT NULL,
|
|
328
|
+
has_error INTEGER NOT NULL DEFAULT 0,
|
|
329
|
+
raw_text TEXT NOT NULL,
|
|
330
|
+
vector F32_BLOB(1024),
|
|
331
|
+
version INTEGER NOT NULL DEFAULT 0
|
|
332
|
+
);
|
|
333
|
+
|
|
334
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
|
|
335
|
+
CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
|
|
336
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
|
|
337
|
+
`);
|
|
338
|
+
await client.executeMultiple(`
|
|
339
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
340
|
+
raw_text,
|
|
341
|
+
content='memories',
|
|
342
|
+
content_rowid='rowid'
|
|
343
|
+
);
|
|
344
|
+
|
|
345
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
346
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
347
|
+
END;
|
|
348
|
+
|
|
349
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
350
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
351
|
+
END;
|
|
352
|
+
|
|
353
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
354
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
355
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
356
|
+
END;
|
|
357
|
+
`);
|
|
358
|
+
for (const col of [
|
|
359
|
+
"ALTER TABLE memories ADD COLUMN task_id TEXT",
|
|
360
|
+
"ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
|
|
361
|
+
"ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
|
|
362
|
+
"ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
|
|
363
|
+
"ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
|
|
364
|
+
"ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
|
|
365
|
+
"ALTER TABLE memories ADD COLUMN content_hash TEXT",
|
|
366
|
+
"ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
|
|
367
|
+
"ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
|
|
368
|
+
"ALTER TABLE memories ADD COLUMN last_accessed TEXT",
|
|
369
|
+
// Wiki linkage columns (must match database.ts)
|
|
370
|
+
"ALTER TABLE memories ADD COLUMN workspace_id TEXT",
|
|
371
|
+
"ALTER TABLE memories ADD COLUMN document_id TEXT",
|
|
372
|
+
"ALTER TABLE memories ADD COLUMN user_id TEXT",
|
|
373
|
+
"ALTER TABLE memories ADD COLUMN char_offset INTEGER",
|
|
374
|
+
"ALTER TABLE memories ADD COLUMN page_number INTEGER"
|
|
375
|
+
]) {
|
|
376
|
+
try {
|
|
377
|
+
await client.execute(col);
|
|
378
|
+
} catch {
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
|
|
383
|
+
} catch {
|
|
384
|
+
}
|
|
385
|
+
for (const idx of [
|
|
386
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
|
|
387
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
|
|
388
|
+
"CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
|
|
389
|
+
]) {
|
|
390
|
+
try {
|
|
391
|
+
await client.execute(idx);
|
|
392
|
+
} catch {
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
await client.executeMultiple(`
|
|
396
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
397
|
+
id TEXT PRIMARY KEY,
|
|
398
|
+
name TEXT NOT NULL,
|
|
399
|
+
type TEXT NOT NULL,
|
|
400
|
+
first_seen TEXT NOT NULL,
|
|
401
|
+
last_seen TEXT NOT NULL,
|
|
402
|
+
properties TEXT DEFAULT '{}',
|
|
403
|
+
UNIQUE(name, type)
|
|
404
|
+
);
|
|
405
|
+
|
|
406
|
+
CREATE TABLE IF NOT EXISTS relationships (
|
|
407
|
+
id TEXT PRIMARY KEY,
|
|
408
|
+
source_entity_id TEXT NOT NULL,
|
|
409
|
+
target_entity_id TEXT NOT NULL,
|
|
410
|
+
type TEXT NOT NULL,
|
|
411
|
+
weight REAL DEFAULT 1.0,
|
|
412
|
+
timestamp TEXT NOT NULL,
|
|
413
|
+
properties TEXT DEFAULT '{}',
|
|
414
|
+
UNIQUE(source_entity_id, target_entity_id, type)
|
|
415
|
+
);
|
|
416
|
+
|
|
417
|
+
CREATE TABLE IF NOT EXISTS entity_memories (
|
|
418
|
+
entity_id TEXT NOT NULL,
|
|
419
|
+
memory_id TEXT NOT NULL,
|
|
420
|
+
PRIMARY KEY (entity_id, memory_id)
|
|
421
|
+
);
|
|
422
|
+
|
|
423
|
+
CREATE TABLE IF NOT EXISTS relationship_memories (
|
|
424
|
+
relationship_id TEXT NOT NULL,
|
|
425
|
+
memory_id TEXT NOT NULL,
|
|
426
|
+
PRIMARY KEY (relationship_id, memory_id)
|
|
427
|
+
);
|
|
428
|
+
|
|
429
|
+
CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
|
|
430
|
+
CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
|
|
431
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
|
|
432
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
|
|
433
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
|
|
434
|
+
|
|
435
|
+
CREATE TABLE IF NOT EXISTS hyperedges (
|
|
436
|
+
id TEXT PRIMARY KEY,
|
|
437
|
+
label TEXT NOT NULL,
|
|
438
|
+
relation TEXT NOT NULL,
|
|
439
|
+
confidence REAL DEFAULT 1.0,
|
|
440
|
+
timestamp TEXT NOT NULL
|
|
441
|
+
);
|
|
442
|
+
|
|
443
|
+
CREATE TABLE IF NOT EXISTS hyperedge_nodes (
|
|
444
|
+
hyperedge_id TEXT NOT NULL,
|
|
445
|
+
entity_id TEXT NOT NULL,
|
|
446
|
+
PRIMARY KEY (hyperedge_id, entity_id)
|
|
447
|
+
);
|
|
448
|
+
`);
|
|
449
|
+
for (const col of [
|
|
450
|
+
"ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
|
|
451
|
+
"ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
|
|
452
|
+
]) {
|
|
453
|
+
try {
|
|
454
|
+
await client.execute(col);
|
|
455
|
+
} catch {
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
async function getReadyShardClient(projectName) {
|
|
460
|
+
const client = getShardClient(projectName);
|
|
461
|
+
await ensureShardSchema(client);
|
|
462
|
+
return client;
|
|
463
|
+
}
|
|
464
|
+
function disposeShards() {
|
|
465
|
+
for (const [, client] of _shards) {
|
|
466
|
+
client.close();
|
|
467
|
+
}
|
|
468
|
+
_shards.clear();
|
|
469
|
+
_shardingEnabled = false;
|
|
470
|
+
_encryptionKey = null;
|
|
471
|
+
}
|
|
472
|
+
var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
|
|
473
|
+
var init_shard_manager = __esm({
|
|
474
|
+
"src/lib/shard-manager.ts"() {
|
|
475
|
+
"use strict";
|
|
476
|
+
init_config();
|
|
477
|
+
SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
|
|
478
|
+
_shards = /* @__PURE__ */ new Map();
|
|
479
|
+
_encryptionKey = null;
|
|
480
|
+
_shardingEnabled = false;
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
// src/lib/self-query-router.ts
|
|
485
|
+
var self_query_router_exports = {};
|
|
486
|
+
__export(self_query_router_exports, {
|
|
487
|
+
routeQuery: () => routeQuery
|
|
488
|
+
});
|
|
489
|
+
async function routeQuery(query, model = "claude-haiku-4-5-20251001") {
|
|
490
|
+
if (query.length < 10) {
|
|
491
|
+
return {
|
|
492
|
+
semanticQuery: query,
|
|
493
|
+
projectFilter: null,
|
|
494
|
+
roleFilter: null,
|
|
495
|
+
timeFilter: null,
|
|
496
|
+
isBroadQuery: false
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
try {
|
|
500
|
+
const Anthropic = (await import("@anthropic-ai/sdk")).default;
|
|
501
|
+
const client = new Anthropic();
|
|
502
|
+
const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
503
|
+
const response = await client.messages.create({
|
|
504
|
+
model,
|
|
505
|
+
max_tokens: 256,
|
|
506
|
+
system: `You are a search query router. Extract metadata filters from the user's memory search query. Today is ${now}. Convert relative time references (yesterday, last week) to ISO timestamps.`,
|
|
507
|
+
messages: [{ role: "user", content: query }],
|
|
508
|
+
tools: [EXTRACT_TOOL],
|
|
509
|
+
tool_choice: { type: "tool", name: "extract_search_filters" }
|
|
510
|
+
});
|
|
511
|
+
const toolBlock = response.content.find((b) => b.type === "tool_use");
|
|
512
|
+
if (toolBlock && toolBlock.type === "tool_use") {
|
|
513
|
+
const input2 = toolBlock.input;
|
|
514
|
+
return {
|
|
515
|
+
semanticQuery: input2.semantic_query || query,
|
|
516
|
+
projectFilter: input2.project_filter || null,
|
|
517
|
+
roleFilter: input2.role_filter || null,
|
|
518
|
+
timeFilter: input2.time_filter || null,
|
|
519
|
+
isBroadQuery: Boolean(input2.is_broad_query)
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
} catch (err) {
|
|
523
|
+
process.stderr.write(
|
|
524
|
+
`[self-query-router] LLM extraction failed, using passthrough: ${err instanceof Error ? err.message : String(err)}
|
|
525
|
+
`
|
|
526
|
+
);
|
|
527
|
+
}
|
|
528
|
+
return {
|
|
529
|
+
semanticQuery: query,
|
|
530
|
+
projectFilter: null,
|
|
531
|
+
roleFilter: null,
|
|
532
|
+
timeFilter: null,
|
|
533
|
+
isBroadQuery: false
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
var EXTRACT_TOOL;
|
|
537
|
+
var init_self_query_router = __esm({
|
|
538
|
+
"src/lib/self-query-router.ts"() {
|
|
539
|
+
"use strict";
|
|
540
|
+
EXTRACT_TOOL = {
|
|
541
|
+
name: "extract_search_filters",
|
|
542
|
+
description: "Extract metadata filters from a memory search query to improve retrieval precision.",
|
|
543
|
+
input_schema: {
|
|
544
|
+
type: "object",
|
|
545
|
+
properties: {
|
|
546
|
+
semantic_query: {
|
|
547
|
+
type: "string",
|
|
548
|
+
description: "The core semantic meaning of the query, stripped of metadata references. This is used for embedding search."
|
|
549
|
+
},
|
|
550
|
+
project_filter: {
|
|
551
|
+
type: ["string", "null"],
|
|
552
|
+
description: "Project name if the query references a specific project (e.g., 'exe-os', 'exe-create'). Null if no project specified."
|
|
553
|
+
},
|
|
554
|
+
role_filter: {
|
|
555
|
+
type: ["string", "null"],
|
|
556
|
+
description: "Agent role if the query targets a specific role (e.g., 'CTO', 'CMO'). Null if no role specified."
|
|
557
|
+
},
|
|
558
|
+
time_filter: {
|
|
559
|
+
type: ["string", "null"],
|
|
560
|
+
description: "ISO 8601 timestamp lower bound if the query references a time period (e.g., 'last week', 'yesterday'). Null if no time reference."
|
|
561
|
+
},
|
|
562
|
+
is_broad_query: {
|
|
563
|
+
type: "boolean",
|
|
564
|
+
description: "True if the query is exploratory/broad (e.g., 'what has yoshi been working on', 'summarize recent activity'). False if targeted (e.g., 'how did we fix the auth bug')."
|
|
565
|
+
}
|
|
566
|
+
},
|
|
567
|
+
required: ["semantic_query", "project_filter", "role_filter", "time_filter", "is_broad_query"]
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
// src/lib/exe-daemon-client.ts
|
|
574
|
+
import net from "net";
|
|
575
|
+
import { spawn } from "child_process";
|
|
576
|
+
import { randomUUID } from "crypto";
|
|
577
|
+
import { existsSync as existsSync4, unlinkSync, readFileSync as readFileSync2, openSync, closeSync, statSync } from "fs";
|
|
578
|
+
import path4 from "path";
|
|
579
|
+
import { fileURLToPath } from "url";
|
|
580
|
+
function handleData(chunk) {
|
|
581
|
+
_buffer += chunk.toString();
|
|
582
|
+
let newlineIdx;
|
|
583
|
+
while ((newlineIdx = _buffer.indexOf("\n")) !== -1) {
|
|
584
|
+
const line = _buffer.slice(0, newlineIdx).trim();
|
|
585
|
+
_buffer = _buffer.slice(newlineIdx + 1);
|
|
586
|
+
if (!line) continue;
|
|
587
|
+
try {
|
|
588
|
+
const response = JSON.parse(line);
|
|
589
|
+
const entry = _pending.get(response.id);
|
|
590
|
+
if (entry) {
|
|
591
|
+
clearTimeout(entry.timer);
|
|
592
|
+
_pending.delete(response.id);
|
|
593
|
+
entry.resolve(response);
|
|
594
|
+
}
|
|
595
|
+
} catch {
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function cleanupStaleFiles() {
|
|
600
|
+
if (existsSync4(PID_PATH)) {
|
|
601
|
+
try {
|
|
602
|
+
const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
|
|
603
|
+
if (pid > 0) {
|
|
604
|
+
try {
|
|
605
|
+
process.kill(pid, 0);
|
|
606
|
+
return;
|
|
607
|
+
} catch {
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
} catch {
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
unlinkSync(PID_PATH);
|
|
614
|
+
} catch {
|
|
615
|
+
}
|
|
616
|
+
try {
|
|
617
|
+
unlinkSync(SOCKET_PATH);
|
|
618
|
+
} catch {
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
function findPackageRoot() {
|
|
623
|
+
let dir = path4.dirname(fileURLToPath(import.meta.url));
|
|
624
|
+
const { root } = path4.parse(dir);
|
|
625
|
+
while (dir !== root) {
|
|
626
|
+
if (existsSync4(path4.join(dir, "package.json"))) return dir;
|
|
627
|
+
dir = path4.dirname(dir);
|
|
628
|
+
}
|
|
629
|
+
return null;
|
|
630
|
+
}
|
|
631
|
+
function spawnDaemon() {
|
|
632
|
+
const pkgRoot = findPackageRoot();
|
|
633
|
+
if (!pkgRoot) {
|
|
634
|
+
process.stderr.write("[exed-client] WARN: cannot find package root\n");
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
const daemonPath = path4.join(pkgRoot, "dist", "lib", "exe-daemon.js");
|
|
638
|
+
if (!existsSync4(daemonPath)) {
|
|
639
|
+
process.stderr.write(`[exed-client] WARN: daemon script not found at ${daemonPath}
|
|
640
|
+
`);
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const resolvedPath = daemonPath;
|
|
644
|
+
process.stderr.write(`[exed-client] Spawning daemon: ${resolvedPath}
|
|
645
|
+
`);
|
|
646
|
+
const logPath = path4.join(path4.dirname(SOCKET_PATH), "exed.log");
|
|
647
|
+
let stderrFd = "ignore";
|
|
648
|
+
try {
|
|
649
|
+
stderrFd = openSync(logPath, "a");
|
|
650
|
+
} catch {
|
|
651
|
+
}
|
|
652
|
+
const child = spawn(process.execPath, [resolvedPath], {
|
|
653
|
+
detached: true,
|
|
654
|
+
stdio: ["ignore", "ignore", stderrFd],
|
|
655
|
+
env: {
|
|
656
|
+
...process.env,
|
|
657
|
+
EXE_DAEMON_SOCK: SOCKET_PATH,
|
|
658
|
+
EXE_DAEMON_PID: PID_PATH
|
|
659
|
+
}
|
|
660
|
+
});
|
|
661
|
+
child.unref();
|
|
662
|
+
if (typeof stderrFd === "number") {
|
|
663
|
+
try {
|
|
664
|
+
closeSync(stderrFd);
|
|
665
|
+
} catch {
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
function acquireSpawnLock() {
|
|
670
|
+
try {
|
|
671
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
672
|
+
closeSync(fd);
|
|
673
|
+
return true;
|
|
674
|
+
} catch {
|
|
675
|
+
try {
|
|
676
|
+
const stat = statSync(SPAWN_LOCK_PATH);
|
|
677
|
+
if (Date.now() - stat.mtimeMs > SPAWN_LOCK_STALE_MS) {
|
|
678
|
+
try {
|
|
679
|
+
unlinkSync(SPAWN_LOCK_PATH);
|
|
680
|
+
} catch {
|
|
681
|
+
}
|
|
682
|
+
try {
|
|
683
|
+
const fd = openSync(SPAWN_LOCK_PATH, "wx");
|
|
684
|
+
closeSync(fd);
|
|
685
|
+
return true;
|
|
686
|
+
} catch {
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
} catch {
|
|
690
|
+
}
|
|
691
|
+
return false;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
function releaseSpawnLock() {
|
|
695
|
+
try {
|
|
696
|
+
unlinkSync(SPAWN_LOCK_PATH);
|
|
697
|
+
} catch {
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
function connectToSocket() {
|
|
701
|
+
return new Promise((resolve) => {
|
|
702
|
+
if (_socket && _connected) {
|
|
703
|
+
resolve(true);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
const socket = net.createConnection({ path: SOCKET_PATH });
|
|
707
|
+
const connectTimeout = setTimeout(() => {
|
|
708
|
+
socket.destroy();
|
|
709
|
+
resolve(false);
|
|
710
|
+
}, 2e3);
|
|
711
|
+
socket.on("connect", () => {
|
|
712
|
+
clearTimeout(connectTimeout);
|
|
713
|
+
_socket = socket;
|
|
714
|
+
_connected = true;
|
|
715
|
+
_buffer = "";
|
|
716
|
+
socket.on("data", handleData);
|
|
717
|
+
socket.on("close", () => {
|
|
718
|
+
_connected = false;
|
|
719
|
+
_socket = null;
|
|
720
|
+
for (const [id, entry] of _pending) {
|
|
721
|
+
clearTimeout(entry.timer);
|
|
722
|
+
_pending.delete(id);
|
|
723
|
+
entry.resolve({ error: "Connection closed" });
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
socket.on("error", () => {
|
|
727
|
+
_connected = false;
|
|
728
|
+
_socket = null;
|
|
729
|
+
});
|
|
730
|
+
resolve(true);
|
|
731
|
+
});
|
|
732
|
+
socket.on("error", () => {
|
|
733
|
+
clearTimeout(connectTimeout);
|
|
734
|
+
resolve(false);
|
|
735
|
+
});
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
async function connectEmbedDaemon() {
|
|
739
|
+
if (_socket && _connected) return true;
|
|
740
|
+
if (await connectToSocket()) return true;
|
|
741
|
+
if (acquireSpawnLock()) {
|
|
742
|
+
try {
|
|
743
|
+
cleanupStaleFiles();
|
|
744
|
+
spawnDaemon();
|
|
745
|
+
} finally {
|
|
746
|
+
releaseSpawnLock();
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
const start = Date.now();
|
|
750
|
+
let delay = 100;
|
|
751
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
752
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
753
|
+
if (await connectToSocket()) return true;
|
|
754
|
+
delay = Math.min(delay * 2, 3e3);
|
|
755
|
+
}
|
|
756
|
+
return false;
|
|
757
|
+
}
|
|
758
|
+
function sendRequest(texts, priority) {
|
|
759
|
+
return new Promise((resolve) => {
|
|
760
|
+
if (!_socket || !_connected) {
|
|
761
|
+
resolve({ error: "Not connected" });
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
const id = randomUUID();
|
|
765
|
+
const timer = setTimeout(() => {
|
|
766
|
+
_pending.delete(id);
|
|
767
|
+
resolve({ error: "Request timeout" });
|
|
768
|
+
}, REQUEST_TIMEOUT_MS);
|
|
769
|
+
_pending.set(id, { resolve, timer });
|
|
770
|
+
try {
|
|
771
|
+
_socket.write(JSON.stringify({ id, texts, priority }) + "\n");
|
|
772
|
+
} catch {
|
|
773
|
+
clearTimeout(timer);
|
|
774
|
+
_pending.delete(id);
|
|
775
|
+
resolve({ error: "Write failed" });
|
|
776
|
+
}
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
async function pingDaemon() {
|
|
780
|
+
if (!_socket || !_connected) return null;
|
|
781
|
+
return new Promise((resolve) => {
|
|
782
|
+
const id = randomUUID();
|
|
783
|
+
const timer = setTimeout(() => {
|
|
784
|
+
_pending.delete(id);
|
|
785
|
+
resolve(null);
|
|
786
|
+
}, 5e3);
|
|
787
|
+
_pending.set(id, {
|
|
788
|
+
resolve: (data) => {
|
|
789
|
+
if (data.health) {
|
|
790
|
+
resolve(data.health);
|
|
791
|
+
} else {
|
|
792
|
+
resolve(null);
|
|
793
|
+
}
|
|
794
|
+
},
|
|
795
|
+
timer
|
|
796
|
+
});
|
|
797
|
+
try {
|
|
798
|
+
_socket.write(JSON.stringify({ id, type: "health" }) + "\n");
|
|
799
|
+
} catch {
|
|
800
|
+
clearTimeout(timer);
|
|
801
|
+
_pending.delete(id);
|
|
802
|
+
resolve(null);
|
|
803
|
+
}
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
function killAndRespawnDaemon() {
|
|
807
|
+
process.stderr.write("[exed-client] Killing daemon for restart...\n");
|
|
808
|
+
if (existsSync4(PID_PATH)) {
|
|
809
|
+
try {
|
|
810
|
+
const pid = parseInt(readFileSync2(PID_PATH, "utf8").trim(), 10);
|
|
811
|
+
if (pid > 0) {
|
|
812
|
+
try {
|
|
813
|
+
process.kill(pid, "SIGKILL");
|
|
814
|
+
} catch {
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
} catch {
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
if (_socket) {
|
|
821
|
+
_socket.destroy();
|
|
822
|
+
_socket = null;
|
|
823
|
+
}
|
|
824
|
+
_connected = false;
|
|
825
|
+
_buffer = "";
|
|
826
|
+
try {
|
|
827
|
+
unlinkSync(PID_PATH);
|
|
828
|
+
} catch {
|
|
829
|
+
}
|
|
830
|
+
try {
|
|
831
|
+
unlinkSync(SOCKET_PATH);
|
|
832
|
+
} catch {
|
|
833
|
+
}
|
|
834
|
+
spawnDaemon();
|
|
835
|
+
}
|
|
836
|
+
async function embedViaClient(text, priority = "high") {
|
|
837
|
+
if (!_connected && !await connectEmbedDaemon()) return null;
|
|
838
|
+
_requestCount++;
|
|
839
|
+
if (_requestCount % HEALTH_CHECK_INTERVAL === 0) {
|
|
840
|
+
const health = await pingDaemon();
|
|
841
|
+
if (!health) {
|
|
842
|
+
process.stderr.write(`[exed-client] Periodic health check failed at request ${_requestCount} \u2014 restarting daemon
|
|
843
|
+
`);
|
|
844
|
+
killAndRespawnDaemon();
|
|
845
|
+
const start = Date.now();
|
|
846
|
+
let delay = 200;
|
|
847
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
848
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
849
|
+
if (await connectToSocket()) break;
|
|
850
|
+
delay = Math.min(delay * 2, 3e3);
|
|
851
|
+
}
|
|
852
|
+
if (!_connected) return null;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
const result = await sendRequest([text], priority);
|
|
856
|
+
if (!result.error && result.vectors?.[0]) return result.vectors[0];
|
|
857
|
+
if (result.error) {
|
|
858
|
+
process.stderr.write(`[exed-client] Embed failed (${result.error}) \u2014 attempting restart
|
|
859
|
+
`);
|
|
860
|
+
killAndRespawnDaemon();
|
|
861
|
+
const start = Date.now();
|
|
862
|
+
let delay = 200;
|
|
863
|
+
while (Date.now() - start < CONNECT_TIMEOUT_MS) {
|
|
864
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
865
|
+
if (await connectToSocket()) break;
|
|
866
|
+
delay = Math.min(delay * 2, 3e3);
|
|
867
|
+
}
|
|
868
|
+
if (!_connected) return null;
|
|
869
|
+
const retry = await sendRequest([text], priority);
|
|
870
|
+
if (!retry.error && retry.vectors?.[0]) return retry.vectors[0];
|
|
871
|
+
process.stderr.write(`[exed-client] Embed retry also failed: ${retry.error ?? "no vector"}
|
|
872
|
+
`);
|
|
873
|
+
}
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
function disconnectClient() {
|
|
877
|
+
if (_socket) {
|
|
878
|
+
_socket.destroy();
|
|
879
|
+
_socket = null;
|
|
880
|
+
}
|
|
881
|
+
_connected = false;
|
|
882
|
+
_buffer = "";
|
|
883
|
+
for (const [id, entry] of _pending) {
|
|
884
|
+
clearTimeout(entry.timer);
|
|
885
|
+
_pending.delete(id);
|
|
886
|
+
entry.resolve({ error: "Client disconnected" });
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
var SOCKET_PATH, PID_PATH, SPAWN_LOCK_PATH, SPAWN_LOCK_STALE_MS, CONNECT_TIMEOUT_MS, REQUEST_TIMEOUT_MS, _socket, _connected, _buffer, _requestCount, HEALTH_CHECK_INTERVAL, _pending;
|
|
890
|
+
var init_exe_daemon_client = __esm({
|
|
891
|
+
"src/lib/exe-daemon-client.ts"() {
|
|
892
|
+
"use strict";
|
|
893
|
+
init_config();
|
|
894
|
+
SOCKET_PATH = process.env.EXE_DAEMON_SOCK ?? process.env.EXE_EMBED_SOCK ?? path4.join(EXE_AI_DIR, "exed.sock");
|
|
895
|
+
PID_PATH = process.env.EXE_DAEMON_PID ?? process.env.EXE_EMBED_PID ?? path4.join(EXE_AI_DIR, "exed.pid");
|
|
896
|
+
SPAWN_LOCK_PATH = path4.join(EXE_AI_DIR, "exed-spawn.lock");
|
|
897
|
+
SPAWN_LOCK_STALE_MS = 3e4;
|
|
898
|
+
CONNECT_TIMEOUT_MS = 15e3;
|
|
899
|
+
REQUEST_TIMEOUT_MS = 3e4;
|
|
900
|
+
_socket = null;
|
|
901
|
+
_connected = false;
|
|
902
|
+
_buffer = "";
|
|
903
|
+
_requestCount = 0;
|
|
904
|
+
HEALTH_CHECK_INTERVAL = 100;
|
|
905
|
+
_pending = /* @__PURE__ */ new Map();
|
|
906
|
+
}
|
|
907
|
+
});
|
|
908
|
+
|
|
909
|
+
// src/lib/embedder.ts
|
|
910
|
+
var embedder_exports = {};
|
|
911
|
+
__export(embedder_exports, {
|
|
912
|
+
disposeEmbedder: () => disposeEmbedder,
|
|
913
|
+
embed: () => embed,
|
|
914
|
+
embedDirect: () => embedDirect,
|
|
915
|
+
getEmbedder: () => getEmbedder
|
|
916
|
+
});
|
|
917
|
+
async function getEmbedder() {
|
|
918
|
+
const ok = await connectEmbedDaemon();
|
|
919
|
+
if (!ok) {
|
|
920
|
+
throw new Error(
|
|
921
|
+
"Could not connect to embedding daemon. Ensure the model is installed (run /exe-setup)."
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
async function embed(text) {
|
|
926
|
+
const priority = process.env.EXE_EMBED_PRIORITY === "low" ? "low" : "high";
|
|
927
|
+
const vector = await embedViaClient(text, priority);
|
|
928
|
+
if (!vector) {
|
|
929
|
+
throw new Error(
|
|
930
|
+
"Embedding failed: daemon unavailable. Run /exe-setup to verify model installation."
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
if (vector.length !== EMBEDDING_DIM) {
|
|
934
|
+
throw new Error(
|
|
935
|
+
`Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}. Ensure the correct Jina v5-small Q4_K_M GGUF model is installed.`
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
return vector;
|
|
939
|
+
}
|
|
940
|
+
async function disposeEmbedder() {
|
|
941
|
+
disconnectClient();
|
|
942
|
+
}
|
|
943
|
+
async function embedDirect(text) {
|
|
944
|
+
const llamaCpp = await import("node-llama-cpp");
|
|
945
|
+
const { MODELS_DIR: MODELS_DIR2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
946
|
+
const { existsSync: existsSync7 } = await import("fs");
|
|
947
|
+
const path9 = await import("path");
|
|
948
|
+
const modelPath = path9.join(MODELS_DIR2, "jina-embeddings-v5-small-q4_k_m.gguf");
|
|
949
|
+
if (!existsSync7(modelPath)) {
|
|
950
|
+
throw new Error(`Embedding model not found at ${modelPath}. Run '/exe-setup' to download it.`);
|
|
951
|
+
}
|
|
952
|
+
const llama = await llamaCpp.getLlama();
|
|
953
|
+
const model = await llama.loadModel({ modelPath });
|
|
954
|
+
const context = await model.createEmbeddingContext();
|
|
955
|
+
try {
|
|
956
|
+
const embedding = await context.getEmbeddingFor(text);
|
|
957
|
+
const vector = Array.from(embedding.vector);
|
|
958
|
+
if (vector.length !== EMBEDDING_DIM) {
|
|
959
|
+
throw new Error(
|
|
960
|
+
`Embedding dimension mismatch: expected ${EMBEDDING_DIM}, got ${vector.length}.`
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
return vector;
|
|
964
|
+
} finally {
|
|
965
|
+
await context.dispose();
|
|
966
|
+
await model.dispose();
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
var init_embedder = __esm({
|
|
970
|
+
"src/lib/embedder.ts"() {
|
|
971
|
+
"use strict";
|
|
972
|
+
init_memory();
|
|
973
|
+
init_exe_daemon_client();
|
|
974
|
+
}
|
|
975
|
+
});
|
|
976
|
+
|
|
977
|
+
// src/lib/project-name.ts
|
|
978
|
+
var project_name_exports = {};
|
|
979
|
+
__export(project_name_exports, {
|
|
980
|
+
_resetCache: () => _resetCache,
|
|
981
|
+
getProjectName: () => getProjectName
|
|
982
|
+
});
|
|
983
|
+
import { execSync } from "child_process";
|
|
984
|
+
import path5 from "path";
|
|
985
|
+
function getProjectName(cwd) {
|
|
986
|
+
const dir = cwd ?? process.cwd();
|
|
987
|
+
if (_cached && _cachedCwd === dir) return _cached;
|
|
988
|
+
try {
|
|
989
|
+
const repoRoot = execSync("git rev-parse --show-toplevel", {
|
|
990
|
+
cwd: dir,
|
|
991
|
+
encoding: "utf8",
|
|
992
|
+
timeout: 2e3,
|
|
993
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
994
|
+
}).trim();
|
|
995
|
+
_cached = path5.basename(repoRoot);
|
|
996
|
+
_cachedCwd = dir;
|
|
997
|
+
return _cached;
|
|
998
|
+
} catch {
|
|
999
|
+
_cached = path5.basename(dir);
|
|
1000
|
+
_cachedCwd = dir;
|
|
1001
|
+
return _cached;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
function _resetCache() {
|
|
1005
|
+
_cached = null;
|
|
1006
|
+
_cachedCwd = null;
|
|
1007
|
+
}
|
|
1008
|
+
var _cached, _cachedCwd;
|
|
1009
|
+
var init_project_name = __esm({
|
|
1010
|
+
"src/lib/project-name.ts"() {
|
|
1011
|
+
"use strict";
|
|
1012
|
+
_cached = null;
|
|
1013
|
+
_cachedCwd = null;
|
|
1014
|
+
}
|
|
1015
|
+
});
|
|
1016
|
+
|
|
1017
|
+
// src/lib/file-grep.ts
|
|
1018
|
+
var file_grep_exports = {};
|
|
1019
|
+
__export(file_grep_exports, {
|
|
1020
|
+
grepProjectFiles: () => grepProjectFiles
|
|
1021
|
+
});
|
|
1022
|
+
import { execSync as execSync2 } from "child_process";
|
|
1023
|
+
import { readFileSync as readFileSync3, readdirSync, statSync as statSync2, existsSync as existsSync5 } from "fs";
|
|
1024
|
+
import path6 from "path";
|
|
1025
|
+
import crypto3 from "crypto";
|
|
1026
|
+
async function grepProjectFiles(query, projectRoot, options) {
|
|
1027
|
+
const maxResults = options?.maxResults ?? 10;
|
|
1028
|
+
const terms = query.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_-]/g, "")).filter((t) => t.length >= 3);
|
|
1029
|
+
if (terms.length === 0) return [];
|
|
1030
|
+
const pattern = terms.join("|");
|
|
1031
|
+
let hits;
|
|
1032
|
+
try {
|
|
1033
|
+
hits = grepWithRipgrep(pattern, projectRoot, options?.patterns);
|
|
1034
|
+
} catch {
|
|
1035
|
+
hits = grepWithNodeFs(pattern, projectRoot, options?.patterns);
|
|
1036
|
+
}
|
|
1037
|
+
hits.sort((a, b) => b.density - a.density);
|
|
1038
|
+
const topHits = hits.slice(0, maxResults);
|
|
1039
|
+
return topHits.map((hit) => {
|
|
1040
|
+
const chunkCtx = getChunkContext(hit.filePath, hit.lineNumber);
|
|
1041
|
+
const prefix = chunkCtx ? `[file: ${hit.filePath}:${hit.lineNumber} in ${chunkCtx}]` : `[file: ${hit.filePath}:${hit.lineNumber}]`;
|
|
1042
|
+
return {
|
|
1043
|
+
id: crypto3.createHash("sha256").update(`${hit.filePath}:${hit.lineNumber}`).digest("hex").slice(0, 36),
|
|
1044
|
+
agent_id: "project",
|
|
1045
|
+
agent_role: "file",
|
|
1046
|
+
session_id: "file-grep",
|
|
1047
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1048
|
+
tool_name: "file_grep",
|
|
1049
|
+
project_name: path6.basename(projectRoot),
|
|
1050
|
+
has_error: false,
|
|
1051
|
+
raw_text: `${prefix} ${buildSnippet(hit, projectRoot)}`,
|
|
1052
|
+
vector: null,
|
|
1053
|
+
task_id: null
|
|
1054
|
+
};
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
function getChunkContext(filePath, lineNumber) {
|
|
1058
|
+
try {
|
|
1059
|
+
const ext = filePath.split(".").pop()?.toLowerCase();
|
|
1060
|
+
if (ext !== "ts" && ext !== "tsx" && ext !== "js" && ext !== "jsx") return "";
|
|
1061
|
+
const source = readFileSync3(filePath, "utf8");
|
|
1062
|
+
const lines = source.split("\n");
|
|
1063
|
+
for (let i = Math.min(lineNumber - 1, lines.length - 1); i >= 0; i--) {
|
|
1064
|
+
const line = lines[i];
|
|
1065
|
+
const fnMatch = line.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);
|
|
1066
|
+
if (fnMatch) return `function ${fnMatch[1]}`;
|
|
1067
|
+
const classMatch = line.match(/(?:export\s+)?class\s+(\w+)/);
|
|
1068
|
+
if (classMatch) return `class ${classMatch[1]}`;
|
|
1069
|
+
const arrowMatch = line.match(/(?:export\s+)?(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\(/);
|
|
1070
|
+
if (arrowMatch) return `function ${arrowMatch[1]}`;
|
|
1071
|
+
}
|
|
1072
|
+
} catch {
|
|
1073
|
+
}
|
|
1074
|
+
return "";
|
|
1075
|
+
}
|
|
1076
|
+
function grepWithRipgrep(pattern, projectRoot, patterns) {
|
|
1077
|
+
const globs = (patterns ?? DEFAULT_PATTERNS).map((p) => `--glob '${p}'`).join(" ");
|
|
1078
|
+
const excludes = EXCLUDE_DIRS.map((d) => `--glob '!${d}'`).join(" ");
|
|
1079
|
+
const cmd = `rg -i -c --hidden '${pattern.replace(/'/g, "\\'")}' . ${globs} ${excludes} --max-filesize ${MAX_FILE_SIZE} 2>/dev/null || true`;
|
|
1080
|
+
const output = execSync2(cmd, {
|
|
1081
|
+
cwd: projectRoot,
|
|
1082
|
+
encoding: "utf8",
|
|
1083
|
+
timeout: 3e3,
|
|
1084
|
+
maxBuffer: 1024 * 1024
|
|
1085
|
+
});
|
|
1086
|
+
if (!output.trim()) return [];
|
|
1087
|
+
const hits = [];
|
|
1088
|
+
for (const line of output.trim().split("\n")) {
|
|
1089
|
+
const colonIdx = line.lastIndexOf(":");
|
|
1090
|
+
if (colonIdx === -1) continue;
|
|
1091
|
+
const filePath = line.slice(0, colonIdx);
|
|
1092
|
+
const matchCount = parseInt(line.slice(colonIdx + 1));
|
|
1093
|
+
if (isNaN(matchCount) || matchCount === 0) continue;
|
|
1094
|
+
try {
|
|
1095
|
+
const firstMatch = execSync2(
|
|
1096
|
+
`rg -i -n --hidden '${pattern.replace(/'/g, "\\'")}' '${filePath}' --max-count 1 2>/dev/null | head -1`,
|
|
1097
|
+
{ cwd: projectRoot, encoding: "utf8", timeout: 1e3 }
|
|
1098
|
+
).trim();
|
|
1099
|
+
const lineNum = parseInt(firstMatch.split(":")[0] ?? "1");
|
|
1100
|
+
const totalLines = execSync2(`wc -l < '${filePath}'`, {
|
|
1101
|
+
cwd: projectRoot,
|
|
1102
|
+
encoding: "utf8",
|
|
1103
|
+
timeout: 1e3
|
|
1104
|
+
}).trim();
|
|
1105
|
+
hits.push({
|
|
1106
|
+
filePath,
|
|
1107
|
+
lineNumber: isNaN(lineNum) ? 1 : lineNum,
|
|
1108
|
+
matchLine: firstMatch.slice(firstMatch.indexOf(":") + 1).slice(0, 200),
|
|
1109
|
+
matchCount,
|
|
1110
|
+
totalLines: parseInt(totalLines) || 1,
|
|
1111
|
+
density: matchCount / (parseInt(totalLines) || 1)
|
|
1112
|
+
});
|
|
1113
|
+
} catch {
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
return hits;
|
|
1117
|
+
}
|
|
1118
|
+
function grepWithNodeFs(pattern, projectRoot, patterns) {
|
|
1119
|
+
const regex = new RegExp(pattern, "gi");
|
|
1120
|
+
const files = collectFiles(projectRoot, patterns ?? DEFAULT_PATTERNS);
|
|
1121
|
+
const hits = [];
|
|
1122
|
+
for (const filePath of files.slice(0, MAX_FILES)) {
|
|
1123
|
+
const absPath = path6.join(projectRoot, filePath);
|
|
1124
|
+
try {
|
|
1125
|
+
const stat = statSync2(absPath);
|
|
1126
|
+
if (stat.size > MAX_FILE_SIZE) continue;
|
|
1127
|
+
const content = readFileSync3(absPath, "utf8");
|
|
1128
|
+
const lines = content.split("\n");
|
|
1129
|
+
const matches = content.match(regex);
|
|
1130
|
+
if (!matches || matches.length === 0) continue;
|
|
1131
|
+
const firstMatchIdx = lines.findIndex((l) => regex.test(l));
|
|
1132
|
+
regex.lastIndex = 0;
|
|
1133
|
+
hits.push({
|
|
1134
|
+
filePath,
|
|
1135
|
+
lineNumber: firstMatchIdx >= 0 ? firstMatchIdx + 1 : 1,
|
|
1136
|
+
matchLine: firstMatchIdx >= 0 ? lines[firstMatchIdx].slice(0, 200) : "",
|
|
1137
|
+
matchCount: matches.length,
|
|
1138
|
+
totalLines: lines.length,
|
|
1139
|
+
density: matches.length / lines.length
|
|
1140
|
+
});
|
|
1141
|
+
} catch {
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
return hits;
|
|
1145
|
+
}
|
|
1146
|
+
function collectFiles(root, patterns) {
|
|
1147
|
+
const files = [];
|
|
1148
|
+
function walk(dir, relative) {
|
|
1149
|
+
if (files.length >= MAX_FILES) return;
|
|
1150
|
+
const basename = path6.basename(dir);
|
|
1151
|
+
if (EXCLUDE_DIRS.includes(basename)) return;
|
|
1152
|
+
try {
|
|
1153
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
1154
|
+
for (const entry of entries) {
|
|
1155
|
+
if (files.length >= MAX_FILES) return;
|
|
1156
|
+
const rel = path6.join(relative, entry.name);
|
|
1157
|
+
if (entry.isDirectory()) {
|
|
1158
|
+
walk(path6.join(dir, entry.name), rel);
|
|
1159
|
+
} else if (entry.isFile()) {
|
|
1160
|
+
for (const pat of patterns) {
|
|
1161
|
+
if (matchGlob(rel, pat)) {
|
|
1162
|
+
files.push(rel);
|
|
1163
|
+
break;
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
} catch {
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
walk(root, "");
|
|
1172
|
+
return files;
|
|
1173
|
+
}
|
|
1174
|
+
function matchGlob(filePath, pattern) {
|
|
1175
|
+
if (!pattern.includes("*")) return filePath === pattern;
|
|
1176
|
+
const doubleStarMatch = pattern.match(/^(.+?)\/\*\*\/\*(\.\w+)$/);
|
|
1177
|
+
if (doubleStarMatch) {
|
|
1178
|
+
const dir = doubleStarMatch[1];
|
|
1179
|
+
const ext2 = doubleStarMatch[2];
|
|
1180
|
+
return filePath.startsWith(dir + "/") && filePath.endsWith(ext2);
|
|
1181
|
+
}
|
|
1182
|
+
if (pattern.startsWith("**/")) {
|
|
1183
|
+
const ext2 = pattern.slice(3).replace("*", "");
|
|
1184
|
+
return filePath.endsWith(ext2);
|
|
1185
|
+
}
|
|
1186
|
+
const slashIdx = pattern.lastIndexOf("/");
|
|
1187
|
+
if (slashIdx !== -1) {
|
|
1188
|
+
const dir = pattern.slice(0, slashIdx);
|
|
1189
|
+
const ext2 = pattern.slice(slashIdx + 1).replace("*", "");
|
|
1190
|
+
const fileDir = path6.dirname(filePath);
|
|
1191
|
+
return fileDir === dir && filePath.endsWith(ext2);
|
|
1192
|
+
}
|
|
1193
|
+
const ext = pattern.replace("*", "");
|
|
1194
|
+
return filePath.endsWith(ext) && !filePath.includes("/");
|
|
1195
|
+
}
|
|
1196
|
+
function buildSnippet(hit, projectRoot) {
|
|
1197
|
+
try {
|
|
1198
|
+
const absPath = path6.join(projectRoot, hit.filePath);
|
|
1199
|
+
if (!existsSync5(absPath)) return hit.matchLine;
|
|
1200
|
+
const lines = readFileSync3(absPath, "utf8").split("\n");
|
|
1201
|
+
const start = Math.max(0, hit.lineNumber - 3);
|
|
1202
|
+
const end = Math.min(lines.length, hit.lineNumber + 2);
|
|
1203
|
+
return lines.slice(start, end).join("\n").slice(0, 500);
|
|
1204
|
+
} catch {
|
|
1205
|
+
return hit.matchLine;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
var DEFAULT_PATTERNS, EXCLUDE_DIRS, MAX_FILE_SIZE, MAX_FILES;
|
|
1209
|
+
var init_file_grep = __esm({
|
|
1210
|
+
"src/lib/file-grep.ts"() {
|
|
1211
|
+
"use strict";
|
|
1212
|
+
DEFAULT_PATTERNS = [
|
|
1213
|
+
".planning/*.md",
|
|
1214
|
+
"exe/output/*.md",
|
|
1215
|
+
"README.md",
|
|
1216
|
+
"src/**/*.ts"
|
|
1217
|
+
];
|
|
1218
|
+
EXCLUDE_DIRS = ["node_modules", "dist", ".git", "coverage", ".worktrees"];
|
|
1219
|
+
MAX_FILE_SIZE = 100 * 1024;
|
|
1220
|
+
MAX_FILES = 500;
|
|
1221
|
+
}
|
|
1222
|
+
});
|
|
1223
|
+
|
|
1224
|
+
// src/lib/reranker.ts
|
|
1225
|
+
var reranker_exports = {};
|
|
1226
|
+
__export(reranker_exports, {
|
|
1227
|
+
disposeReranker: () => disposeReranker,
|
|
1228
|
+
getRerankerModelPath: () => getRerankerModelPath,
|
|
1229
|
+
isRerankerAvailable: () => isRerankerAvailable,
|
|
1230
|
+
rerank: () => rerank,
|
|
1231
|
+
rerankWithScores: () => rerankWithScores
|
|
1232
|
+
});
|
|
1233
|
+
import path7 from "path";
|
|
1234
|
+
import { existsSync as existsSync6 } from "fs";
|
|
1235
|
+
function resetIdleTimer() {
|
|
1236
|
+
if (_idleTimer) clearTimeout(_idleTimer);
|
|
1237
|
+
_idleTimer = setTimeout(() => {
|
|
1238
|
+
void disposeReranker();
|
|
1239
|
+
}, IDLE_TIMEOUT_MS);
|
|
1240
|
+
if (_idleTimer && typeof _idleTimer === "object" && "unref" in _idleTimer) {
|
|
1241
|
+
_idleTimer.unref();
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
function isRerankerAvailable() {
|
|
1245
|
+
return existsSync6(path7.join(MODELS_DIR, RERANKER_MODEL_FILE));
|
|
1246
|
+
}
|
|
1247
|
+
function getRerankerModelPath() {
|
|
1248
|
+
return path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
|
|
1249
|
+
}
|
|
1250
|
+
async function ensureLoaded() {
|
|
1251
|
+
if (_rerankerContext) {
|
|
1252
|
+
resetIdleTimer();
|
|
1253
|
+
return;
|
|
1254
|
+
}
|
|
1255
|
+
const modelPath = path7.join(MODELS_DIR, RERANKER_MODEL_FILE);
|
|
1256
|
+
if (!existsSync6(modelPath)) {
|
|
1257
|
+
throw new Error(
|
|
1258
|
+
`Reranker model not found at ${modelPath}. Run /exe-setup to download it.`
|
|
1259
|
+
);
|
|
1260
|
+
}
|
|
1261
|
+
process.stderr.write("[reranker] Loading Jina Reranker v3...\n");
|
|
1262
|
+
const { getLlama } = await import("node-llama-cpp");
|
|
1263
|
+
const llama = await getLlama();
|
|
1264
|
+
_rerankerModel = await llama.loadModel({ modelPath });
|
|
1265
|
+
_rerankerContext = await _rerankerModel.createEmbeddingContext();
|
|
1266
|
+
process.stderr.write("[reranker] Jina Reranker v3 loaded.\n");
|
|
1267
|
+
resetIdleTimer();
|
|
1268
|
+
}
|
|
1269
|
+
async function disposeReranker() {
|
|
1270
|
+
if (_idleTimer) {
|
|
1271
|
+
clearTimeout(_idleTimer);
|
|
1272
|
+
_idleTimer = null;
|
|
1273
|
+
}
|
|
1274
|
+
if (_rerankerContext) {
|
|
1275
|
+
try {
|
|
1276
|
+
await _rerankerContext.dispose();
|
|
1277
|
+
} catch {
|
|
1278
|
+
}
|
|
1279
|
+
_rerankerContext = null;
|
|
1280
|
+
}
|
|
1281
|
+
if (_rerankerModel) {
|
|
1282
|
+
try {
|
|
1283
|
+
await _rerankerModel.dispose();
|
|
1284
|
+
} catch {
|
|
1285
|
+
}
|
|
1286
|
+
_rerankerModel = null;
|
|
1287
|
+
}
|
|
1288
|
+
process.stderr.write("[reranker] Unloaded (idle timeout).\n");
|
|
1289
|
+
}
|
|
1290
|
+
async function rerankWithScores(query, texts, topK) {
|
|
1291
|
+
if (texts.length === 0) return [];
|
|
1292
|
+
await ensureLoaded();
|
|
1293
|
+
const ctx = _rerankerContext;
|
|
1294
|
+
const scored = [];
|
|
1295
|
+
for (let i = 0; i < texts.length; i++) {
|
|
1296
|
+
const text = texts[i] ?? "";
|
|
1297
|
+
try {
|
|
1298
|
+
const input2 = `query: ${query} document: ${text.slice(0, 512)}`;
|
|
1299
|
+
const embedding = await ctx.getEmbeddingFor(input2);
|
|
1300
|
+
const score = embedding.vector[0] ?? 0;
|
|
1301
|
+
scored.push({ text, score, index: i });
|
|
1302
|
+
} catch {
|
|
1303
|
+
scored.push({ text, score: -1, index: i });
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
scored.sort((a, b) => b.score - a.score);
|
|
1307
|
+
return typeof topK === "number" ? scored.slice(0, topK) : scored;
|
|
1308
|
+
}
|
|
1309
|
+
async function rerank(query, candidates, topK = 5) {
|
|
1310
|
+
if (candidates.length === 0) return [];
|
|
1311
|
+
if (candidates.length <= topK) return candidates;
|
|
1312
|
+
const scored = await rerankWithScores(
|
|
1313
|
+
query,
|
|
1314
|
+
candidates.map((c) => c.raw_text),
|
|
1315
|
+
topK
|
|
1316
|
+
);
|
|
1317
|
+
return scored.map((s) => candidates[s.index]);
|
|
1318
|
+
}
|
|
1319
|
+
var RERANKER_MODEL_FILE, IDLE_TIMEOUT_MS, _rerankerContext, _rerankerModel, _idleTimer;
|
|
1320
|
+
var init_reranker = __esm({
|
|
1321
|
+
"src/lib/reranker.ts"() {
|
|
1322
|
+
"use strict";
|
|
1323
|
+
init_config();
|
|
1324
|
+
RERANKER_MODEL_FILE = "jina-reranker-v3-q4_k_m.gguf";
|
|
1325
|
+
IDLE_TIMEOUT_MS = 6e4;
|
|
1326
|
+
_rerankerContext = null;
|
|
1327
|
+
_rerankerModel = null;
|
|
1328
|
+
_idleTimer = null;
|
|
1329
|
+
}
|
|
1330
|
+
});
|
|
1331
|
+
|
|
1332
|
+
// src/adapters/claude/hooks/error-recall.ts
|
|
1333
|
+
init_config();
|
|
1334
|
+
|
|
1335
|
+
// src/lib/error-detector.ts
|
|
1336
|
+
import crypto from "crypto";
|
|
1337
|
+
|
|
1338
|
+
// src/lib/mcp-prefix.ts
|
|
1339
|
+
var MCP_PRIMARY_KEY = "exe-os";
|
|
1340
|
+
var MCP_LEGACY_KEY = "exe-mem";
|
|
1341
|
+
var MCP_TOOL_PREFIXES = [
|
|
1342
|
+
`mcp__${MCP_PRIMARY_KEY}__`,
|
|
1343
|
+
`mcp__${MCP_LEGACY_KEY}__`
|
|
1344
|
+
];
|
|
1345
|
+
|
|
1346
|
+
// src/lib/error-detector.ts
|
|
1347
|
+
var ERROR_PATTERNS = [
|
|
1348
|
+
/\bError\b/i,
|
|
1349
|
+
/\bERR!\b/,
|
|
1350
|
+
/\bFAIL(ED|URE)?\b/i,
|
|
1351
|
+
/\bException\b/i,
|
|
1352
|
+
/\bTraceback\b/,
|
|
1353
|
+
/\bpanic\b/,
|
|
1354
|
+
/\bSIGSEGV\b/,
|
|
1355
|
+
/\bSIGABRT\b/,
|
|
1356
|
+
/exit code [1-9]/i,
|
|
1357
|
+
/non-zero (exit|status)/i,
|
|
1358
|
+
/command not found/i,
|
|
1359
|
+
/permission denied/i,
|
|
1360
|
+
/ENOENT/,
|
|
1361
|
+
/EACCES/,
|
|
1362
|
+
/ENOMEM/
|
|
1363
|
+
];
|
|
1364
|
+
var FILE_CONTENT_TOOLS = /* @__PURE__ */ new Set([
|
|
1365
|
+
"Read",
|
|
1366
|
+
"Write",
|
|
1367
|
+
"Edit",
|
|
1368
|
+
"Glob",
|
|
1369
|
+
"Grep",
|
|
1370
|
+
"NotebookEdit"
|
|
1371
|
+
]);
|
|
1372
|
+
var STDERR_IGNORE_PATTERNS = [
|
|
1373
|
+
/^warning\b/i,
|
|
1374
|
+
/\bDeprecationWarning\b/,
|
|
1375
|
+
/^hint:/i,
|
|
1376
|
+
/^npm warn\b/i,
|
|
1377
|
+
/^npm notice\b/i,
|
|
1378
|
+
/^\(node:\d+\) \w*Warning:/,
|
|
1379
|
+
/^Cloning into/,
|
|
1380
|
+
/^Already on/,
|
|
1381
|
+
/^Switched to/,
|
|
1382
|
+
/^Your branch is/,
|
|
1383
|
+
/^Auto-merging/,
|
|
1384
|
+
/^\s*$/
|
|
1385
|
+
];
|
|
1386
|
+
function isRealStderr(stderr) {
|
|
1387
|
+
const lines = stderr.trim().split("\n");
|
|
1388
|
+
const meaningful = lines.filter(
|
|
1389
|
+
(line) => line.trim().length > 0 && !STDERR_IGNORE_PATTERNS.some((p) => p.test(line))
|
|
1390
|
+
);
|
|
1391
|
+
return meaningful.length > 0;
|
|
1392
|
+
}
|
|
1393
|
+
function logSuppression(exitCode, stderr, stdout) {
|
|
1394
|
+
process.stderr.write(
|
|
1395
|
+
`[error-detector] suppressed bash non-zero exit: code=${exitCode} stderr_len=${stderr.length} stdout_len=${stdout.length}
|
|
1396
|
+
`
|
|
1397
|
+
);
|
|
1398
|
+
}
|
|
1399
|
+
function detectError(data) {
|
|
1400
|
+
const response = data.tool_response;
|
|
1401
|
+
if (!response) return false;
|
|
1402
|
+
const toolName = data.tool_name ?? "";
|
|
1403
|
+
if (FILE_CONTENT_TOOLS.has(toolName)) {
|
|
1404
|
+
return response.type === "error" || response.error != null;
|
|
1405
|
+
}
|
|
1406
|
+
if (toolName === "Bash") {
|
|
1407
|
+
const exitCode = typeof response.exitCode === "number" ? response.exitCode : 0;
|
|
1408
|
+
const stderr = typeof response.stderr === "string" ? response.stderr : "";
|
|
1409
|
+
const stdout = typeof response.stdout === "string" ? response.stdout : "";
|
|
1410
|
+
if (exitCode === 141) {
|
|
1411
|
+
logSuppression(exitCode, stderr, stdout);
|
|
1412
|
+
return false;
|
|
1413
|
+
}
|
|
1414
|
+
if (stderr.trim().length > 0 && isRealStderr(stderr)) return true;
|
|
1415
|
+
if (exitCode !== 0 && !isRealStderr(stderr) && stdout.trim().length > 0) {
|
|
1416
|
+
logSuppression(exitCode, stderr, stdout);
|
|
1417
|
+
return false;
|
|
1418
|
+
}
|
|
1419
|
+
if (exitCode !== 0) return true;
|
|
1420
|
+
return false;
|
|
1421
|
+
}
|
|
1422
|
+
if (response.type === "error" || response.error != null || response.isError === true) {
|
|
1423
|
+
return true;
|
|
1424
|
+
}
|
|
1425
|
+
if (typeof response.stderr === "string" && response.stderr.trim().length > 0) {
|
|
1426
|
+
if (isRealStderr(response.stderr)) return true;
|
|
1427
|
+
}
|
|
1428
|
+
const textParts = [];
|
|
1429
|
+
if (typeof response.stdout === "string") textParts.push(response.stdout);
|
|
1430
|
+
if (typeof response.output === "string") textParts.push(response.output);
|
|
1431
|
+
if (typeof response.text === "string") textParts.push(response.text);
|
|
1432
|
+
if (typeof response.message === "string") textParts.push(response.message);
|
|
1433
|
+
if (textParts.length === 0) return false;
|
|
1434
|
+
const text = textParts.join("\n");
|
|
1435
|
+
return ERROR_PATTERNS.some((pattern) => pattern.test(text));
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// src/adapters/claude/hooks/error-recall.ts
|
|
1439
|
+
init_config();
|
|
1440
|
+
|
|
1441
|
+
// src/lib/store.ts
|
|
1442
|
+
init_memory();
|
|
1443
|
+
|
|
1444
|
+
// src/lib/database.ts
|
|
1445
|
+
import { createClient } from "@libsql/client";
|
|
1446
|
+
var _client = null;
|
|
1447
|
+
var initTurso = initDatabase;
|
|
1448
|
+
async function initDatabase(config) {
|
|
1449
|
+
if (_client) {
|
|
1450
|
+
_client.close();
|
|
1451
|
+
_client = null;
|
|
1452
|
+
}
|
|
1453
|
+
const opts = {
|
|
1454
|
+
url: `file:${config.dbPath}`
|
|
1455
|
+
};
|
|
1456
|
+
if (config.encryptionKey) {
|
|
1457
|
+
opts.encryptionKey = config.encryptionKey;
|
|
1458
|
+
}
|
|
1459
|
+
_client = createClient(opts);
|
|
1460
|
+
}
|
|
1461
|
+
function getClient() {
|
|
1462
|
+
if (!_client) {
|
|
1463
|
+
throw new Error("Database client not initialized. Call initDatabase() first.");
|
|
1464
|
+
}
|
|
1465
|
+
return _client;
|
|
1466
|
+
}
|
|
1467
|
+
async function ensureSchema() {
|
|
1468
|
+
const client = getClient();
|
|
1469
|
+
await client.execute("PRAGMA journal_mode = WAL");
|
|
1470
|
+
await client.execute("PRAGMA busy_timeout = 5000");
|
|
1471
|
+
try {
|
|
1472
|
+
await client.execute("PRAGMA libsql_vector_search_ef = 128");
|
|
1473
|
+
} catch {
|
|
1474
|
+
}
|
|
1475
|
+
await client.executeMultiple(`
|
|
1476
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
1477
|
+
id TEXT PRIMARY KEY,
|
|
1478
|
+
agent_id TEXT NOT NULL,
|
|
1479
|
+
agent_role TEXT NOT NULL,
|
|
1480
|
+
session_id TEXT NOT NULL,
|
|
1481
|
+
timestamp TEXT NOT NULL,
|
|
1482
|
+
tool_name TEXT NOT NULL,
|
|
1483
|
+
project_name TEXT NOT NULL,
|
|
1484
|
+
has_error INTEGER NOT NULL DEFAULT 0,
|
|
1485
|
+
raw_text TEXT NOT NULL,
|
|
1486
|
+
vector F32_BLOB(1024),
|
|
1487
|
+
version INTEGER NOT NULL DEFAULT 0
|
|
1488
|
+
);
|
|
1489
|
+
|
|
1490
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent
|
|
1491
|
+
ON memories(agent_id);
|
|
1492
|
+
|
|
1493
|
+
CREATE INDEX IF NOT EXISTS idx_memories_timestamp
|
|
1494
|
+
ON memories(timestamp);
|
|
1495
|
+
|
|
1496
|
+
CREATE INDEX IF NOT EXISTS idx_memories_session
|
|
1497
|
+
ON memories(session_id);
|
|
1498
|
+
|
|
1499
|
+
CREATE INDEX IF NOT EXISTS idx_memories_project
|
|
1500
|
+
ON memories(project_name);
|
|
1501
|
+
|
|
1502
|
+
CREATE INDEX IF NOT EXISTS idx_memories_tool
|
|
1503
|
+
ON memories(tool_name);
|
|
1504
|
+
|
|
1505
|
+
CREATE INDEX IF NOT EXISTS idx_memories_version
|
|
1506
|
+
ON memories(version);
|
|
1507
|
+
|
|
1508
|
+
CREATE INDEX IF NOT EXISTS idx_memories_agent_project
|
|
1509
|
+
ON memories(agent_id, project_name);
|
|
1510
|
+
`);
|
|
1511
|
+
await client.executeMultiple(`
|
|
1512
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
1513
|
+
raw_text,
|
|
1514
|
+
content='memories',
|
|
1515
|
+
content_rowid='rowid'
|
|
1516
|
+
);
|
|
1517
|
+
|
|
1518
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
|
|
1519
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1520
|
+
END;
|
|
1521
|
+
|
|
1522
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
|
|
1523
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1524
|
+
END;
|
|
1525
|
+
|
|
1526
|
+
CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
|
|
1527
|
+
INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
|
|
1528
|
+
INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
|
|
1529
|
+
END;
|
|
1530
|
+
`);
|
|
1531
|
+
await client.executeMultiple(`
|
|
1532
|
+
CREATE TABLE IF NOT EXISTS sync_meta (
|
|
1533
|
+
key TEXT PRIMARY KEY,
|
|
1534
|
+
value TEXT NOT NULL
|
|
1535
|
+
);
|
|
1536
|
+
`);
|
|
1537
|
+
await client.executeMultiple(`
|
|
1538
|
+
CREATE TABLE IF NOT EXISTS tasks (
|
|
1539
|
+
id TEXT PRIMARY KEY,
|
|
1540
|
+
title TEXT NOT NULL,
|
|
1541
|
+
assigned_to TEXT NOT NULL,
|
|
1542
|
+
assigned_by TEXT NOT NULL,
|
|
1543
|
+
project_name TEXT NOT NULL,
|
|
1544
|
+
priority TEXT NOT NULL DEFAULT 'p1',
|
|
1545
|
+
status TEXT NOT NULL DEFAULT 'open',
|
|
1546
|
+
task_file TEXT,
|
|
1547
|
+
created_at TEXT NOT NULL,
|
|
1548
|
+
updated_at TEXT NOT NULL
|
|
1549
|
+
);
|
|
1550
|
+
|
|
1551
|
+
CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
|
|
1552
|
+
ON tasks(assigned_to, status);
|
|
1553
|
+
`);
|
|
1554
|
+
await client.executeMultiple(`
|
|
1555
|
+
CREATE TABLE IF NOT EXISTS behaviors (
|
|
1556
|
+
id TEXT PRIMARY KEY,
|
|
1557
|
+
agent_id TEXT NOT NULL,
|
|
1558
|
+
project_name TEXT,
|
|
1559
|
+
domain TEXT,
|
|
1560
|
+
content TEXT NOT NULL,
|
|
1561
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1562
|
+
created_at TEXT NOT NULL,
|
|
1563
|
+
updated_at TEXT NOT NULL
|
|
1564
|
+
);
|
|
1565
|
+
|
|
1566
|
+
CREATE INDEX IF NOT EXISTS idx_behaviors_agent
|
|
1567
|
+
ON behaviors(agent_id, active);
|
|
1568
|
+
`);
|
|
1569
|
+
try {
|
|
1570
|
+
const existing = await client.execute({
|
|
1571
|
+
sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
|
|
1572
|
+
args: []
|
|
1573
|
+
});
|
|
1574
|
+
if (Number(existing.rows[0]?.cnt) === 0) {
|
|
1575
|
+
await client.executeMultiple(`
|
|
1576
|
+
INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
1577
|
+
VALUES
|
|
1578
|
+
(hex(randomblob(16)), 'exe', NULL, 'workflow', 'Don''t ask "keep going?" \u2014 just keep executing phases/plans autonomously', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
|
|
1579
|
+
INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
1580
|
+
VALUES
|
|
1581
|
+
(hex(randomblob(16)), 'exe', NULL, 'tool-use', 'Always use create_task MCP tool, never write .md files directly for task creation', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
|
|
1582
|
+
INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
|
|
1583
|
+
VALUES
|
|
1584
|
+
(hex(randomblob(16)), 'exe', NULL, 'workflow', 'Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
|
|
1585
|
+
`);
|
|
1586
|
+
}
|
|
1587
|
+
} catch {
|
|
1588
|
+
}
|
|
1589
|
+
try {
|
|
1590
|
+
await client.execute({
|
|
1591
|
+
sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
|
|
1592
|
+
args: []
|
|
1593
|
+
});
|
|
1594
|
+
} catch {
|
|
1595
|
+
}
|
|
1596
|
+
try {
|
|
1597
|
+
await client.execute({
|
|
1598
|
+
sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
|
|
1599
|
+
args: []
|
|
1600
|
+
});
|
|
1601
|
+
} catch {
|
|
1602
|
+
}
|
|
1603
|
+
try {
|
|
1604
|
+
await client.execute({
|
|
1605
|
+
sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
|
|
1606
|
+
args: []
|
|
1607
|
+
});
|
|
1608
|
+
} catch {
|
|
1609
|
+
}
|
|
1610
|
+
try {
|
|
1611
|
+
await client.execute({
|
|
1612
|
+
sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
|
|
1613
|
+
ON tasks(parent_task_id)
|
|
1614
|
+
WHERE parent_task_id IS NOT NULL`,
|
|
1615
|
+
args: []
|
|
1616
|
+
});
|
|
1617
|
+
} catch {
|
|
1618
|
+
}
|
|
1619
|
+
try {
|
|
1620
|
+
await client.execute({
|
|
1621
|
+
sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
|
|
1622
|
+
args: []
|
|
1623
|
+
});
|
|
1624
|
+
} catch {
|
|
1625
|
+
}
|
|
1626
|
+
try {
|
|
1627
|
+
await client.execute({
|
|
1628
|
+
sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
|
|
1629
|
+
args: []
|
|
1630
|
+
});
|
|
1631
|
+
} catch {
|
|
1632
|
+
}
|
|
1633
|
+
try {
|
|
1634
|
+
await client.execute({
|
|
1635
|
+
sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
|
|
1636
|
+
args: []
|
|
1637
|
+
});
|
|
1638
|
+
} catch {
|
|
1639
|
+
}
|
|
1640
|
+
try {
|
|
1641
|
+
await client.execute({
|
|
1642
|
+
sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
|
|
1643
|
+
args: []
|
|
1644
|
+
});
|
|
1645
|
+
} catch {
|
|
1646
|
+
}
|
|
1647
|
+
try {
|
|
1648
|
+
await client.execute({
|
|
1649
|
+
sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
|
|
1650
|
+
args: []
|
|
1651
|
+
});
|
|
1652
|
+
} catch {
|
|
1653
|
+
}
|
|
1654
|
+
try {
|
|
1655
|
+
await client.execute({
|
|
1656
|
+
sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
|
|
1657
|
+
args: []
|
|
1658
|
+
});
|
|
1659
|
+
} catch {
|
|
1660
|
+
}
|
|
1661
|
+
try {
|
|
1662
|
+
await client.execute({
|
|
1663
|
+
sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
|
|
1664
|
+
args: []
|
|
1665
|
+
});
|
|
1666
|
+
} catch {
|
|
1667
|
+
}
|
|
1668
|
+
try {
|
|
1669
|
+
await client.execute({
|
|
1670
|
+
sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
|
|
1671
|
+
args: []
|
|
1672
|
+
});
|
|
1673
|
+
} catch {
|
|
1674
|
+
}
|
|
1675
|
+
try {
|
|
1676
|
+
await client.execute({
|
|
1677
|
+
sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
|
|
1678
|
+
args: []
|
|
1679
|
+
});
|
|
1680
|
+
} catch {
|
|
1681
|
+
}
|
|
1682
|
+
await client.executeMultiple(`
|
|
1683
|
+
CREATE TABLE IF NOT EXISTS consolidations (
|
|
1684
|
+
id TEXT PRIMARY KEY,
|
|
1685
|
+
consolidated_memory_id TEXT NOT NULL,
|
|
1686
|
+
source_memory_id TEXT NOT NULL,
|
|
1687
|
+
created_at TEXT NOT NULL
|
|
1688
|
+
);
|
|
1689
|
+
|
|
1690
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_source
|
|
1691
|
+
ON consolidations(source_memory_id);
|
|
1692
|
+
|
|
1693
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
|
|
1694
|
+
ON consolidations(consolidated_memory_id);
|
|
1695
|
+
`);
|
|
1696
|
+
await client.executeMultiple(`
|
|
1697
|
+
CREATE TABLE IF NOT EXISTS reminders (
|
|
1698
|
+
id TEXT PRIMARY KEY,
|
|
1699
|
+
text TEXT NOT NULL,
|
|
1700
|
+
created_at TEXT NOT NULL,
|
|
1701
|
+
due_date TEXT,
|
|
1702
|
+
completed_at TEXT
|
|
1703
|
+
);
|
|
1704
|
+
`);
|
|
1705
|
+
await client.executeMultiple(`
|
|
1706
|
+
CREATE TABLE IF NOT EXISTS notifications (
|
|
1707
|
+
id TEXT PRIMARY KEY,
|
|
1708
|
+
agent_id TEXT NOT NULL,
|
|
1709
|
+
agent_role TEXT NOT NULL,
|
|
1710
|
+
event TEXT NOT NULL,
|
|
1711
|
+
project TEXT NOT NULL,
|
|
1712
|
+
summary TEXT NOT NULL,
|
|
1713
|
+
task_file TEXT,
|
|
1714
|
+
read INTEGER NOT NULL DEFAULT 0,
|
|
1715
|
+
created_at TEXT NOT NULL
|
|
1716
|
+
);
|
|
1717
|
+
|
|
1718
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_read
|
|
1719
|
+
ON notifications(read);
|
|
1720
|
+
|
|
1721
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_agent
|
|
1722
|
+
ON notifications(agent_id);
|
|
1723
|
+
|
|
1724
|
+
CREATE INDEX IF NOT EXISTS idx_notifications_task_file
|
|
1725
|
+
ON notifications(task_file);
|
|
1726
|
+
`);
|
|
1727
|
+
await client.executeMultiple(`
|
|
1728
|
+
CREATE TABLE IF NOT EXISTS schedules (
|
|
1729
|
+
id TEXT PRIMARY KEY,
|
|
1730
|
+
cron TEXT NOT NULL,
|
|
1731
|
+
description TEXT NOT NULL,
|
|
1732
|
+
job_type TEXT NOT NULL DEFAULT 'report',
|
|
1733
|
+
prompt TEXT,
|
|
1734
|
+
assigned_to TEXT,
|
|
1735
|
+
project_name TEXT,
|
|
1736
|
+
active INTEGER NOT NULL DEFAULT 1,
|
|
1737
|
+
use_crontab INTEGER NOT NULL DEFAULT 0,
|
|
1738
|
+
created_at TEXT NOT NULL
|
|
1739
|
+
);
|
|
1740
|
+
`);
|
|
1741
|
+
await client.executeMultiple(`
|
|
1742
|
+
CREATE TABLE IF NOT EXISTS device_registry (
|
|
1743
|
+
device_id TEXT PRIMARY KEY,
|
|
1744
|
+
friendly_name TEXT NOT NULL,
|
|
1745
|
+
hostname TEXT NOT NULL,
|
|
1746
|
+
projects TEXT NOT NULL DEFAULT '[]',
|
|
1747
|
+
agents TEXT NOT NULL DEFAULT '[]',
|
|
1748
|
+
connected INTEGER DEFAULT 0,
|
|
1749
|
+
last_seen TEXT NOT NULL
|
|
1750
|
+
);
|
|
1751
|
+
`);
|
|
1752
|
+
await client.executeMultiple(`
|
|
1753
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
1754
|
+
id TEXT PRIMARY KEY,
|
|
1755
|
+
from_agent TEXT NOT NULL,
|
|
1756
|
+
from_device TEXT NOT NULL DEFAULT 'local',
|
|
1757
|
+
target_agent TEXT NOT NULL,
|
|
1758
|
+
target_project TEXT,
|
|
1759
|
+
target_device TEXT NOT NULL DEFAULT 'local',
|
|
1760
|
+
content TEXT NOT NULL,
|
|
1761
|
+
priority TEXT DEFAULT 'normal',
|
|
1762
|
+
status TEXT DEFAULT 'pending',
|
|
1763
|
+
server_seq INTEGER,
|
|
1764
|
+
retry_count INTEGER DEFAULT 0,
|
|
1765
|
+
created_at TEXT NOT NULL,
|
|
1766
|
+
delivered_at TEXT,
|
|
1767
|
+
processed_at TEXT,
|
|
1768
|
+
failed_at TEXT,
|
|
1769
|
+
failure_reason TEXT
|
|
1770
|
+
);
|
|
1771
|
+
|
|
1772
|
+
CREATE INDEX IF NOT EXISTS idx_messages_target
|
|
1773
|
+
ON messages(target_agent, status);
|
|
1774
|
+
|
|
1775
|
+
CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
|
|
1776
|
+
ON messages(target_agent, from_agent, server_seq);
|
|
1777
|
+
`);
|
|
1778
|
+
try {
|
|
1779
|
+
await client.execute({
|
|
1780
|
+
sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
|
|
1781
|
+
args: []
|
|
1782
|
+
});
|
|
1783
|
+
await client.execute({
|
|
1784
|
+
sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
|
|
1785
|
+
args: []
|
|
1786
|
+
});
|
|
1787
|
+
await client.execute({
|
|
1788
|
+
sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
|
|
1789
|
+
args: []
|
|
1790
|
+
});
|
|
1791
|
+
await client.execute({
|
|
1792
|
+
sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
|
|
1793
|
+
args: []
|
|
1794
|
+
});
|
|
1795
|
+
} catch {
|
|
1796
|
+
}
|
|
1797
|
+
await client.executeMultiple(`
|
|
1798
|
+
CREATE TABLE IF NOT EXISTS trajectories (
|
|
1799
|
+
id TEXT PRIMARY KEY,
|
|
1800
|
+
task_id TEXT NOT NULL,
|
|
1801
|
+
agent_id TEXT NOT NULL,
|
|
1802
|
+
project_name TEXT NOT NULL,
|
|
1803
|
+
task_title TEXT NOT NULL,
|
|
1804
|
+
signature TEXT NOT NULL,
|
|
1805
|
+
signature_hash TEXT NOT NULL,
|
|
1806
|
+
tool_count INTEGER NOT NULL,
|
|
1807
|
+
skill_id TEXT,
|
|
1808
|
+
created_at TEXT NOT NULL
|
|
1809
|
+
);
|
|
1810
|
+
|
|
1811
|
+
CREATE INDEX IF NOT EXISTS idx_trajectories_hash
|
|
1812
|
+
ON trajectories(signature_hash);
|
|
1813
|
+
|
|
1814
|
+
CREATE INDEX IF NOT EXISTS idx_trajectories_agent
|
|
1815
|
+
ON trajectories(agent_id);
|
|
1816
|
+
`);
|
|
1817
|
+
try {
|
|
1818
|
+
await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
|
|
1819
|
+
} catch {
|
|
1820
|
+
}
|
|
1821
|
+
await client.executeMultiple(`
|
|
1822
|
+
CREATE TABLE IF NOT EXISTS consolidations (
|
|
1823
|
+
id TEXT PRIMARY KEY,
|
|
1824
|
+
consolidated_memory_id TEXT NOT NULL,
|
|
1825
|
+
source_memory_id TEXT NOT NULL,
|
|
1826
|
+
created_at TEXT NOT NULL
|
|
1827
|
+
);
|
|
1828
|
+
|
|
1829
|
+
CREATE INDEX IF NOT EXISTS idx_consolidations_source
|
|
1830
|
+
ON consolidations(source_memory_id);
|
|
1831
|
+
`);
|
|
1832
|
+
await client.executeMultiple(`
|
|
1833
|
+
CREATE TABLE IF NOT EXISTS audit_trail (
|
|
1834
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1835
|
+
timestamp TEXT NOT NULL,
|
|
1836
|
+
session_id TEXT NOT NULL,
|
|
1837
|
+
agent_id TEXT NOT NULL,
|
|
1838
|
+
tool TEXT NOT NULL,
|
|
1839
|
+
input TEXT,
|
|
1840
|
+
decision TEXT NOT NULL,
|
|
1841
|
+
reason TEXT,
|
|
1842
|
+
is_customer_facing INTEGER NOT NULL DEFAULT 0
|
|
1843
|
+
);
|
|
1844
|
+
|
|
1845
|
+
CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
|
|
1846
|
+
ON audit_trail(agent_id, timestamp);
|
|
1847
|
+
|
|
1848
|
+
CREATE INDEX IF NOT EXISTS idx_audit_trail_session
|
|
1849
|
+
ON audit_trail(session_id);
|
|
1850
|
+
`);
|
|
1851
|
+
try {
|
|
1852
|
+
await client.execute({
|
|
1853
|
+
sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
|
|
1854
|
+
args: []
|
|
1855
|
+
});
|
|
1856
|
+
} catch {
|
|
1857
|
+
}
|
|
1858
|
+
try {
|
|
1859
|
+
await client.execute({
|
|
1860
|
+
sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
|
|
1861
|
+
args: []
|
|
1862
|
+
});
|
|
1863
|
+
} catch {
|
|
1864
|
+
}
|
|
1865
|
+
try {
|
|
1866
|
+
await client.execute({
|
|
1867
|
+
sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
|
|
1868
|
+
args: []
|
|
1869
|
+
});
|
|
1870
|
+
} catch {
|
|
1871
|
+
}
|
|
1872
|
+
try {
|
|
1873
|
+
await client.execute({
|
|
1874
|
+
sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
|
|
1875
|
+
args: []
|
|
1876
|
+
});
|
|
1877
|
+
} catch {
|
|
1878
|
+
}
|
|
1879
|
+
try {
|
|
1880
|
+
await client.execute({
|
|
1881
|
+
sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
|
|
1882
|
+
args: []
|
|
1883
|
+
});
|
|
1884
|
+
} catch {
|
|
1885
|
+
}
|
|
1886
|
+
try {
|
|
1887
|
+
await client.execute({
|
|
1888
|
+
sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
|
|
1889
|
+
args: []
|
|
1890
|
+
});
|
|
1891
|
+
} catch {
|
|
1892
|
+
}
|
|
1893
|
+
try {
|
|
1894
|
+
await client.execute({
|
|
1895
|
+
sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
|
|
1896
|
+
args: []
|
|
1897
|
+
});
|
|
1898
|
+
} catch {
|
|
1899
|
+
}
|
|
1900
|
+
try {
|
|
1901
|
+
await client.execute({
|
|
1902
|
+
sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
|
|
1903
|
+
args: []
|
|
1904
|
+
});
|
|
1905
|
+
} catch {
|
|
1906
|
+
}
|
|
1907
|
+
for (const col of [
|
|
1908
|
+
"ALTER TABLE memories ADD COLUMN content_hash TEXT",
|
|
1909
|
+
"ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
|
|
1910
|
+
]) {
|
|
1911
|
+
try {
|
|
1912
|
+
await client.execute(col);
|
|
1913
|
+
} catch {
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
1916
|
+
await client.executeMultiple(`
|
|
1917
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
1918
|
+
id TEXT PRIMARY KEY,
|
|
1919
|
+
name TEXT NOT NULL,
|
|
1920
|
+
type TEXT NOT NULL,
|
|
1921
|
+
first_seen TEXT NOT NULL,
|
|
1922
|
+
last_seen TEXT NOT NULL,
|
|
1923
|
+
properties TEXT DEFAULT '{}',
|
|
1924
|
+
UNIQUE(name, type)
|
|
1925
|
+
);
|
|
1926
|
+
|
|
1927
|
+
CREATE TABLE IF NOT EXISTS relationships (
|
|
1928
|
+
id TEXT PRIMARY KEY,
|
|
1929
|
+
source_entity_id TEXT NOT NULL,
|
|
1930
|
+
target_entity_id TEXT NOT NULL,
|
|
1931
|
+
type TEXT NOT NULL,
|
|
1932
|
+
weight REAL DEFAULT 1.0,
|
|
1933
|
+
timestamp TEXT NOT NULL,
|
|
1934
|
+
properties TEXT DEFAULT '{}',
|
|
1935
|
+
UNIQUE(source_entity_id, target_entity_id, type)
|
|
1936
|
+
);
|
|
1937
|
+
|
|
1938
|
+
CREATE TABLE IF NOT EXISTS entity_memories (
|
|
1939
|
+
entity_id TEXT NOT NULL,
|
|
1940
|
+
memory_id TEXT NOT NULL,
|
|
1941
|
+
PRIMARY KEY (entity_id, memory_id)
|
|
1942
|
+
);
|
|
1943
|
+
|
|
1944
|
+
CREATE TABLE IF NOT EXISTS relationship_memories (
|
|
1945
|
+
relationship_id TEXT NOT NULL,
|
|
1946
|
+
memory_id TEXT NOT NULL,
|
|
1947
|
+
PRIMARY KEY (relationship_id, memory_id)
|
|
1948
|
+
);
|
|
1949
|
+
|
|
1950
|
+
CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
|
|
1951
|
+
CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
|
|
1952
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
|
|
1953
|
+
CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
|
|
1954
|
+
|
|
1955
|
+
CREATE TABLE IF NOT EXISTS hyperedges (
|
|
1956
|
+
id TEXT PRIMARY KEY,
|
|
1957
|
+
label TEXT NOT NULL,
|
|
1958
|
+
relation TEXT NOT NULL,
|
|
1959
|
+
confidence REAL DEFAULT 1.0,
|
|
1960
|
+
timestamp TEXT NOT NULL
|
|
1961
|
+
);
|
|
1962
|
+
|
|
1963
|
+
CREATE TABLE IF NOT EXISTS hyperedge_nodes (
|
|
1964
|
+
hyperedge_id TEXT NOT NULL,
|
|
1965
|
+
entity_id TEXT NOT NULL,
|
|
1966
|
+
PRIMARY KEY (hyperedge_id, entity_id)
|
|
1967
|
+
);
|
|
1968
|
+
`);
|
|
1969
|
+
await client.executeMultiple(`
|
|
1970
|
+
CREATE TABLE IF NOT EXISTS entity_aliases (
|
|
1971
|
+
alias TEXT NOT NULL PRIMARY KEY,
|
|
1972
|
+
canonical_entity_id TEXT NOT NULL
|
|
1973
|
+
);
|
|
1974
|
+
CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
|
|
1975
|
+
`);
|
|
1976
|
+
for (const col of [
|
|
1977
|
+
"ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
|
|
1978
|
+
"ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
|
|
1979
|
+
]) {
|
|
1980
|
+
try {
|
|
1981
|
+
await client.execute(col);
|
|
1982
|
+
} catch {
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
try {
|
|
1986
|
+
await client.execute(
|
|
1987
|
+
`CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
|
|
1988
|
+
);
|
|
1989
|
+
} catch {
|
|
1990
|
+
}
|
|
1991
|
+
await client.executeMultiple(`
|
|
1992
|
+
CREATE TABLE IF NOT EXISTS identity (
|
|
1993
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1994
|
+
agent_id TEXT NOT NULL UNIQUE,
|
|
1995
|
+
content_hash TEXT NOT NULL,
|
|
1996
|
+
updated_at TEXT NOT NULL,
|
|
1997
|
+
updated_by TEXT NOT NULL
|
|
1998
|
+
);
|
|
1999
|
+
|
|
2000
|
+
CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
|
|
2001
|
+
`);
|
|
2002
|
+
await client.executeMultiple(`
|
|
2003
|
+
CREATE TABLE IF NOT EXISTS chat_history (
|
|
2004
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2005
|
+
session_id TEXT NOT NULL,
|
|
2006
|
+
role TEXT NOT NULL,
|
|
2007
|
+
content TEXT NOT NULL,
|
|
2008
|
+
tool_name TEXT,
|
|
2009
|
+
tool_id TEXT,
|
|
2010
|
+
is_error INTEGER NOT NULL DEFAULT 0,
|
|
2011
|
+
timestamp INTEGER NOT NULL
|
|
2012
|
+
);
|
|
2013
|
+
|
|
2014
|
+
CREATE INDEX IF NOT EXISTS idx_chat_history_session
|
|
2015
|
+
ON chat_history(session_id, id);
|
|
2016
|
+
`);
|
|
2017
|
+
await client.executeMultiple(`
|
|
2018
|
+
CREATE TABLE IF NOT EXISTS workspaces (
|
|
2019
|
+
id TEXT PRIMARY KEY,
|
|
2020
|
+
slug TEXT NOT NULL UNIQUE,
|
|
2021
|
+
name TEXT NOT NULL,
|
|
2022
|
+
owner_agent_id TEXT,
|
|
2023
|
+
created_at TEXT NOT NULL,
|
|
2024
|
+
metadata TEXT
|
|
2025
|
+
);
|
|
2026
|
+
|
|
2027
|
+
CREATE INDEX IF NOT EXISTS idx_workspaces_slug
|
|
2028
|
+
ON workspaces(slug);
|
|
2029
|
+
`);
|
|
2030
|
+
await client.executeMultiple(`
|
|
2031
|
+
CREATE TABLE IF NOT EXISTS documents (
|
|
2032
|
+
id TEXT PRIMARY KEY,
|
|
2033
|
+
workspace_id TEXT NOT NULL,
|
|
2034
|
+
filename TEXT NOT NULL,
|
|
2035
|
+
mime TEXT,
|
|
2036
|
+
source_type TEXT,
|
|
2037
|
+
user_id TEXT,
|
|
2038
|
+
uploaded_at TEXT NOT NULL,
|
|
2039
|
+
metadata TEXT,
|
|
2040
|
+
FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
|
|
2041
|
+
);
|
|
2042
|
+
|
|
2043
|
+
CREATE INDEX IF NOT EXISTS idx_documents_workspace
|
|
2044
|
+
ON documents(workspace_id);
|
|
2045
|
+
|
|
2046
|
+
CREATE INDEX IF NOT EXISTS idx_documents_user
|
|
2047
|
+
ON documents(user_id);
|
|
2048
|
+
`);
|
|
2049
|
+
for (const column of [
|
|
2050
|
+
"workspace_id TEXT",
|
|
2051
|
+
"document_id TEXT",
|
|
2052
|
+
"user_id TEXT",
|
|
2053
|
+
"char_offset INTEGER",
|
|
2054
|
+
"page_number INTEGER"
|
|
2055
|
+
]) {
|
|
2056
|
+
try {
|
|
2057
|
+
await client.execute({
|
|
2058
|
+
sql: `ALTER TABLE memories ADD COLUMN ${column}`,
|
|
2059
|
+
args: []
|
|
2060
|
+
});
|
|
2061
|
+
} catch {
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
await client.executeMultiple(`
|
|
2065
|
+
CREATE INDEX IF NOT EXISTS idx_memories_workspace
|
|
2066
|
+
ON memories(workspace_id);
|
|
2067
|
+
|
|
2068
|
+
CREATE INDEX IF NOT EXISTS idx_memories_document
|
|
2069
|
+
ON memories(document_id);
|
|
2070
|
+
|
|
2071
|
+
CREATE INDEX IF NOT EXISTS idx_memories_user
|
|
2072
|
+
ON memories(user_id);
|
|
2073
|
+
`);
|
|
2074
|
+
await client.executeMultiple(`
|
|
2075
|
+
CREATE TABLE IF NOT EXISTS session_kills (
|
|
2076
|
+
id TEXT PRIMARY KEY,
|
|
2077
|
+
session_name TEXT NOT NULL,
|
|
2078
|
+
agent_id TEXT NOT NULL,
|
|
2079
|
+
killed_at TIMESTAMP NOT NULL,
|
|
2080
|
+
reason TEXT NOT NULL,
|
|
2081
|
+
ticks_idle INTEGER,
|
|
2082
|
+
estimated_tokens_saved INTEGER
|
|
2083
|
+
);
|
|
2084
|
+
|
|
2085
|
+
CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
|
|
2086
|
+
ON session_kills(killed_at);
|
|
2087
|
+
|
|
2088
|
+
CREATE INDEX IF NOT EXISTS idx_session_kills_agent
|
|
2089
|
+
ON session_kills(agent_id);
|
|
2090
|
+
`);
|
|
2091
|
+
await client.executeMultiple(`
|
|
2092
|
+
CREATE TABLE IF NOT EXISTS conversations (
|
|
2093
|
+
id TEXT PRIMARY KEY,
|
|
2094
|
+
platform TEXT NOT NULL,
|
|
2095
|
+
external_id TEXT,
|
|
2096
|
+
sender_id TEXT NOT NULL,
|
|
2097
|
+
sender_name TEXT,
|
|
2098
|
+
sender_phone TEXT,
|
|
2099
|
+
sender_email TEXT,
|
|
2100
|
+
recipient_id TEXT,
|
|
2101
|
+
channel_id TEXT NOT NULL,
|
|
2102
|
+
thread_id TEXT,
|
|
2103
|
+
reply_to_id TEXT,
|
|
2104
|
+
content_text TEXT,
|
|
2105
|
+
content_media TEXT,
|
|
2106
|
+
content_metadata TEXT,
|
|
2107
|
+
agent_response TEXT,
|
|
2108
|
+
agent_name TEXT,
|
|
2109
|
+
timestamp TEXT NOT NULL,
|
|
2110
|
+
ingested_at TEXT NOT NULL
|
|
2111
|
+
);
|
|
2112
|
+
|
|
2113
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_platform
|
|
2114
|
+
ON conversations(platform);
|
|
2115
|
+
|
|
2116
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_sender
|
|
2117
|
+
ON conversations(sender_id);
|
|
2118
|
+
|
|
2119
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
|
|
2120
|
+
ON conversations(timestamp);
|
|
2121
|
+
|
|
2122
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_thread
|
|
2123
|
+
ON conversations(thread_id);
|
|
2124
|
+
|
|
2125
|
+
CREATE INDEX IF NOT EXISTS idx_conversations_channel
|
|
2126
|
+
ON conversations(channel_id);
|
|
2127
|
+
`);
|
|
2128
|
+
await client.executeMultiple(`
|
|
2129
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
|
|
2130
|
+
content_text,
|
|
2131
|
+
sender_name,
|
|
2132
|
+
agent_response,
|
|
2133
|
+
content='conversations',
|
|
2134
|
+
content_rowid='rowid'
|
|
2135
|
+
);
|
|
2136
|
+
|
|
2137
|
+
CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
|
|
2138
|
+
INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
|
|
2139
|
+
VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
|
|
2140
|
+
END;
|
|
2141
|
+
|
|
2142
|
+
CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
|
|
2143
|
+
INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
|
|
2144
|
+
VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
|
|
2145
|
+
END;
|
|
2146
|
+
|
|
2147
|
+
CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
|
|
2148
|
+
INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
|
|
2149
|
+
VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
|
|
2150
|
+
INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
|
|
2151
|
+
VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
|
|
2152
|
+
END;
|
|
2153
|
+
`);
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
// src/lib/keychain.ts
|
|
2157
|
+
import { readFile as readFile2, writeFile as writeFile2, unlink, mkdir as mkdir2, chmod } from "fs/promises";
|
|
2158
|
+
import { existsSync as existsSync2 } from "fs";
|
|
2159
|
+
import path2 from "path";
|
|
2160
|
+
import crypto2 from "crypto";
|
|
2161
|
+
var SERVICE = "exe-mem";
|
|
2162
|
+
var ACCOUNT = "master-key";
|
|
2163
|
+
function getKeyDir() {
|
|
2164
|
+
return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path2.join(process.env.HOME ?? "/tmp", ".exe-os");
|
|
2165
|
+
}
|
|
2166
|
+
function getKeyPath() {
|
|
2167
|
+
return path2.join(getKeyDir(), "master.key");
|
|
2168
|
+
}
|
|
2169
|
+
async function tryKeytar() {
|
|
2170
|
+
try {
|
|
2171
|
+
return await import("keytar");
|
|
2172
|
+
} catch {
|
|
2173
|
+
return null;
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
async function getMasterKey() {
|
|
2177
|
+
const keytar = await tryKeytar();
|
|
2178
|
+
if (keytar) {
|
|
2179
|
+
try {
|
|
2180
|
+
const stored = await keytar.getPassword(SERVICE, ACCOUNT);
|
|
2181
|
+
if (stored) {
|
|
2182
|
+
return Buffer.from(stored, "base64");
|
|
2183
|
+
}
|
|
2184
|
+
} catch {
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
const keyPath = getKeyPath();
|
|
2188
|
+
if (!existsSync2(keyPath)) {
|
|
2189
|
+
return null;
|
|
2190
|
+
}
|
|
2191
|
+
try {
|
|
2192
|
+
const content = await readFile2(keyPath, "utf-8");
|
|
2193
|
+
return Buffer.from(content.trim(), "base64");
|
|
2194
|
+
} catch {
|
|
2195
|
+
return null;
|
|
2196
|
+
}
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
// src/lib/store.ts
|
|
2200
|
+
init_config();
|
|
2201
|
+
var _pendingRecords = [];
|
|
2202
|
+
var _batchSize = 20;
|
|
2203
|
+
var _flushIntervalMs = 1e4;
|
|
2204
|
+
var _flushTimer = null;
|
|
2205
|
+
var _flushing = false;
|
|
2206
|
+
var _nextVersion = 1;
|
|
2207
|
+
async function initStore(options) {
|
|
2208
|
+
if (_flushTimer !== null) {
|
|
2209
|
+
clearInterval(_flushTimer);
|
|
2210
|
+
_flushTimer = null;
|
|
2211
|
+
}
|
|
2212
|
+
_pendingRecords = [];
|
|
2213
|
+
_flushing = false;
|
|
2214
|
+
_batchSize = options?.batchSize ?? 20;
|
|
2215
|
+
_flushIntervalMs = options?.flushIntervalMs ?? 1e4;
|
|
2216
|
+
let dbPath = options?.dbPath;
|
|
2217
|
+
if (!dbPath) {
|
|
2218
|
+
const config = await loadConfig();
|
|
2219
|
+
dbPath = config.dbPath;
|
|
2220
|
+
}
|
|
2221
|
+
let masterKey = options?.masterKey ?? null;
|
|
2222
|
+
if (!masterKey) {
|
|
2223
|
+
masterKey = await getMasterKey();
|
|
2224
|
+
if (!masterKey) {
|
|
2225
|
+
throw new Error(
|
|
2226
|
+
"No encryption key found. Run /exe-setup to generate one."
|
|
2227
|
+
);
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
const hexKey = masterKey.toString("hex");
|
|
2231
|
+
await initTurso({
|
|
2232
|
+
dbPath,
|
|
2233
|
+
encryptionKey: hexKey
|
|
2234
|
+
});
|
|
2235
|
+
await ensureSchema();
|
|
2236
|
+
try {
|
|
2237
|
+
const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
2238
|
+
initShardManager2(hexKey);
|
|
2239
|
+
} catch {
|
|
2240
|
+
}
|
|
2241
|
+
const client = getClient();
|
|
2242
|
+
const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
|
|
2243
|
+
_nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
|
|
2244
|
+
}
|
|
2245
|
+
function buildWikiScopeFilter(options, columnPrefix) {
|
|
2246
|
+
const args = [];
|
|
2247
|
+
let clause = "";
|
|
2248
|
+
if (options?.workspaceId !== void 0) {
|
|
2249
|
+
clause += ` AND ${columnPrefix}workspace_id = ?`;
|
|
2250
|
+
args.push(options.workspaceId);
|
|
2251
|
+
}
|
|
2252
|
+
if (options?.userId === void 0) {
|
|
2253
|
+
clause += ` AND ${columnPrefix}user_id IS NULL`;
|
|
2254
|
+
} else if (options.userId === null) {
|
|
2255
|
+
clause += ` AND ${columnPrefix}user_id IS NULL`;
|
|
2256
|
+
} else {
|
|
2257
|
+
clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
|
|
2258
|
+
args.push(options.userId);
|
|
2259
|
+
}
|
|
2260
|
+
return { clause, args };
|
|
2261
|
+
}
|
|
2262
|
+
async function searchMemories(queryVector, agentId, options) {
|
|
2263
|
+
let client;
|
|
2264
|
+
try {
|
|
2265
|
+
const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
|
|
2266
|
+
if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
|
|
2267
|
+
client = await getReadyShardClient2(options.projectName);
|
|
2268
|
+
} else {
|
|
2269
|
+
client = getClient();
|
|
2270
|
+
}
|
|
2271
|
+
} catch {
|
|
2272
|
+
client = getClient();
|
|
2273
|
+
}
|
|
2274
|
+
const limit = options?.limit ?? 10;
|
|
2275
|
+
const statusFilter = options?.includeArchived ? "" : `
|
|
2276
|
+
AND COALESCE(status, 'active') = 'active'`;
|
|
2277
|
+
let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
|
|
2278
|
+
tool_name, project_name,
|
|
2279
|
+
has_error, raw_text, vector, importance, status,
|
|
2280
|
+
confidence, last_accessed,
|
|
2281
|
+
workspace_id, document_id, user_id,
|
|
2282
|
+
char_offset, page_number
|
|
2283
|
+
FROM memories
|
|
2284
|
+
WHERE agent_id = ?
|
|
2285
|
+
AND vector IS NOT NULL${statusFilter}
|
|
2286
|
+
AND COALESCE(confidence, 0.7) >= 0.3`;
|
|
2287
|
+
const args = [agentId];
|
|
2288
|
+
const scope = buildWikiScopeFilter(options, "");
|
|
2289
|
+
sql += scope.clause;
|
|
2290
|
+
args.push(...scope.args);
|
|
2291
|
+
if (options?.projectName) {
|
|
2292
|
+
sql += ` AND project_name = ?`;
|
|
2293
|
+
args.push(options.projectName);
|
|
2294
|
+
}
|
|
2295
|
+
if (options?.toolName) {
|
|
2296
|
+
sql += ` AND tool_name = ?`;
|
|
2297
|
+
args.push(options.toolName);
|
|
2298
|
+
}
|
|
2299
|
+
if (options?.hasError !== void 0) {
|
|
2300
|
+
sql += ` AND has_error = ?`;
|
|
2301
|
+
args.push(options.hasError ? 1 : 0);
|
|
2302
|
+
}
|
|
2303
|
+
if (options?.since) {
|
|
2304
|
+
sql += ` AND timestamp >= ?`;
|
|
2305
|
+
args.push(options.since);
|
|
2306
|
+
}
|
|
2307
|
+
sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
|
|
2308
|
+
args.push(vectorToBlob(queryVector));
|
|
2309
|
+
sql += ` LIMIT ?`;
|
|
2310
|
+
args.push(limit);
|
|
2311
|
+
const result = await client.execute({ sql, args });
|
|
2312
|
+
return result.rows.map((row) => ({
|
|
2313
|
+
id: row.id,
|
|
2314
|
+
agent_id: row.agent_id,
|
|
2315
|
+
agent_role: row.agent_role,
|
|
2316
|
+
session_id: row.session_id,
|
|
2317
|
+
timestamp: row.timestamp,
|
|
2318
|
+
tool_name: row.tool_name,
|
|
2319
|
+
project_name: row.project_name,
|
|
2320
|
+
has_error: row.has_error === 1,
|
|
2321
|
+
raw_text: row.raw_text,
|
|
2322
|
+
vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
|
|
2323
|
+
importance: row.importance ?? 5,
|
|
2324
|
+
status: row.status ?? "active",
|
|
2325
|
+
confidence: row.confidence ?? 0.7,
|
|
2326
|
+
last_accessed: row.last_accessed ?? row.timestamp,
|
|
2327
|
+
workspace_id: row.workspace_id ?? null,
|
|
2328
|
+
document_id: row.document_id ?? null,
|
|
2329
|
+
user_id: row.user_id ?? null,
|
|
2330
|
+
char_offset: row.char_offset ?? null,
|
|
2331
|
+
page_number: row.page_number ?? null
|
|
2332
|
+
}));
|
|
2333
|
+
}
|
|
2334
|
+
async function attachDocumentMetadata(records) {
|
|
2335
|
+
const docIds = [
|
|
2336
|
+
...new Set(
|
|
2337
|
+
records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
|
|
2338
|
+
)
|
|
2339
|
+
];
|
|
2340
|
+
if (docIds.length === 0) return records;
|
|
2341
|
+
try {
|
|
2342
|
+
const client = getClient();
|
|
2343
|
+
const placeholders = docIds.map(() => "?").join(",");
|
|
2344
|
+
const result = await client.execute({
|
|
2345
|
+
sql: `SELECT id, filename, mime, source_type, uploaded_at
|
|
2346
|
+
FROM documents
|
|
2347
|
+
WHERE id IN (${placeholders})`,
|
|
2348
|
+
args: docIds
|
|
2349
|
+
});
|
|
2350
|
+
const byId = /* @__PURE__ */ new Map();
|
|
2351
|
+
for (const row of result.rows) {
|
|
2352
|
+
const id = row.id;
|
|
2353
|
+
byId.set(id, {
|
|
2354
|
+
document_id: id,
|
|
2355
|
+
filename: row.filename,
|
|
2356
|
+
mime: row.mime ?? null,
|
|
2357
|
+
source_type: row.source_type ?? null,
|
|
2358
|
+
uploaded_at: row.uploaded_at
|
|
2359
|
+
});
|
|
2360
|
+
}
|
|
2361
|
+
for (const record of records) {
|
|
2362
|
+
if (!record.document_id) continue;
|
|
2363
|
+
record.document_metadata = byId.get(record.document_id) ?? null;
|
|
2364
|
+
}
|
|
2365
|
+
} catch {
|
|
2366
|
+
}
|
|
2367
|
+
return records;
|
|
2368
|
+
}
|
|
2369
|
+
function vectorToBlob(vector) {
|
|
2370
|
+
const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
|
|
2371
|
+
return JSON.stringify(Array.from(f32));
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
// src/lib/hybrid-search.ts
|
|
2375
|
+
var RRF_K = 60;
|
|
2376
|
+
async function hybridSearch(queryText, agentId, options) {
|
|
2377
|
+
const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
2378
|
+
const config = await loadConfig2();
|
|
2379
|
+
if (config.searchMode === "fts") {
|
|
2380
|
+
return lightweightSearch(queryText, agentId, options);
|
|
2381
|
+
}
|
|
2382
|
+
const limit = options?.limit ?? 10;
|
|
2383
|
+
let effectiveQuery = queryText;
|
|
2384
|
+
let effectiveOptions = { ...options };
|
|
2385
|
+
let _isBroadQuery = false;
|
|
2386
|
+
if (config.selfQueryRouter && process.env.ANTHROPIC_API_KEY) {
|
|
2387
|
+
try {
|
|
2388
|
+
const { routeQuery: routeQuery2 } = await Promise.resolve().then(() => (init_self_query_router(), self_query_router_exports));
|
|
2389
|
+
const routed = await routeQuery2(queryText, config.selfQueryModel);
|
|
2390
|
+
effectiveQuery = routed.semanticQuery;
|
|
2391
|
+
_isBroadQuery = routed.isBroadQuery;
|
|
2392
|
+
if (routed.projectFilter && !effectiveOptions.projectName) {
|
|
2393
|
+
effectiveOptions.projectName = routed.projectFilter;
|
|
2394
|
+
}
|
|
2395
|
+
if (routed.timeFilter && !effectiveOptions.since) {
|
|
2396
|
+
effectiveOptions.since = routed.timeFilter;
|
|
2397
|
+
}
|
|
2398
|
+
} catch {
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
const broadFetchTopK = config.scalingRoadmap?.rerankerAutoTrigger?.fetchTopK ?? 150;
|
|
2402
|
+
const fetchLimit = _isBroadQuery ? Math.max(limit * 5, broadFetchTopK) : Math.max(limit * 3, 30);
|
|
2403
|
+
const fetchOptions = { ...effectiveOptions, limit: fetchLimit, includeSource: false };
|
|
2404
|
+
let queryVector = null;
|
|
2405
|
+
try {
|
|
2406
|
+
const { embed: embed2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
|
|
2407
|
+
queryVector = await embed2(effectiveQuery);
|
|
2408
|
+
} catch {
|
|
2409
|
+
process.stderr.write("[hybrid-search] Embed daemon unavailable \u2014 FTS-only mode\n");
|
|
2410
|
+
}
|
|
2411
|
+
let grepPromise = Promise.resolve([]);
|
|
2412
|
+
if (config.fileGrepEnabled !== false) {
|
|
2413
|
+
try {
|
|
2414
|
+
const { getProjectName: getProjectName2 } = await Promise.resolve().then(() => (init_project_name(), project_name_exports));
|
|
2415
|
+
const projectRoot = process.cwd();
|
|
2416
|
+
const projectName = getProjectName2(projectRoot);
|
|
2417
|
+
if (projectName && projectName !== "tmp") {
|
|
2418
|
+
const { grepProjectFiles: grepProjectFiles2 } = await Promise.resolve().then(() => (init_file_grep(), file_grep_exports));
|
|
2419
|
+
grepPromise = grepProjectFiles2(effectiveQuery, projectRoot, {
|
|
2420
|
+
maxResults: 10
|
|
2421
|
+
}).catch(() => []);
|
|
2422
|
+
}
|
|
2423
|
+
} catch {
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
const [ftsResults, vectorResults, grepResults] = await Promise.all([
|
|
2427
|
+
lightweightSearch(effectiveQuery, agentId, fetchOptions),
|
|
2428
|
+
queryVector ? searchMemories(queryVector, agentId, fetchOptions) : Promise.resolve([]),
|
|
2429
|
+
grepPromise
|
|
2430
|
+
]);
|
|
2431
|
+
const lists = [];
|
|
2432
|
+
const weights = [];
|
|
2433
|
+
if (ftsResults.length > 0) {
|
|
2434
|
+
lists.push(ftsResults);
|
|
2435
|
+
weights.push(1);
|
|
2436
|
+
}
|
|
2437
|
+
if (vectorResults.length > 0) {
|
|
2438
|
+
lists.push(vectorResults);
|
|
2439
|
+
weights.push(1);
|
|
2440
|
+
}
|
|
2441
|
+
if (grepResults.length > 0) {
|
|
2442
|
+
lists.push(grepResults);
|
|
2443
|
+
weights.push(0.5);
|
|
2444
|
+
}
|
|
2445
|
+
if (lists.length === 0) return [];
|
|
2446
|
+
if (lists.length === 1 && !_isBroadQuery) return lists[0].slice(0, limit);
|
|
2447
|
+
const rrfLimit = _isBroadQuery ? Math.max(limit * 5, 150) : limit;
|
|
2448
|
+
const merged = lists.length === 1 ? lists[0].slice(0, rrfLimit) : rrfMergeMulti(lists, rrfLimit, RRF_K, weights);
|
|
2449
|
+
const auto = config.scalingRoadmap?.rerankerAutoTrigger ?? {
|
|
2450
|
+
enabled: config.rerankerEnabled ?? true,
|
|
2451
|
+
broadQueryMinCardinality: 5e4,
|
|
2452
|
+
fetchTopK: 150,
|
|
2453
|
+
returnTopK: 5
|
|
2454
|
+
};
|
|
2455
|
+
let rerankedAndBlended = null;
|
|
2456
|
+
if (_isBroadQuery && auto.enabled) {
|
|
2457
|
+
const cardinality = await estimateCardinality(agentId, effectiveOptions);
|
|
2458
|
+
if (cardinality > auto.broadQueryMinCardinality) {
|
|
2459
|
+
try {
|
|
2460
|
+
const { isRerankerAvailable: isRerankerAvailable2, rerank: rerank2 } = await Promise.resolve().then(() => (init_reranker(), reranker_exports));
|
|
2461
|
+
if (isRerankerAvailable2()) {
|
|
2462
|
+
const reranked = await rerank2(effectiveQuery, merged, auto.returnTopK);
|
|
2463
|
+
if (reranked.length > 0) {
|
|
2464
|
+
rerankedAndBlended = rrfMergeMulti(
|
|
2465
|
+
[reranked],
|
|
2466
|
+
auto.returnTopK,
|
|
2467
|
+
RRF_K
|
|
2468
|
+
);
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
2471
|
+
} catch {
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
const finalResults = (rerankedAndBlended ?? merged).slice(
|
|
2476
|
+
0,
|
|
2477
|
+
rerankedAndBlended ? auto.returnTopK : limit
|
|
2478
|
+
);
|
|
2479
|
+
if (options?.includeSource && finalResults.length > 0) {
|
|
2480
|
+
await attachDocumentMetadata(finalResults);
|
|
2481
|
+
}
|
|
2482
|
+
if (finalResults.length > 0) {
|
|
2483
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2484
|
+
const ids = finalResults.map((r) => r.id);
|
|
2485
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
2486
|
+
try {
|
|
2487
|
+
const client = getClient();
|
|
2488
|
+
void client.execute({
|
|
2489
|
+
sql: `UPDATE memories SET last_accessed = ? WHERE id IN (${placeholders})`,
|
|
2490
|
+
args: [now, ...ids]
|
|
2491
|
+
}).catch(() => {
|
|
2492
|
+
});
|
|
2493
|
+
} catch {
|
|
2494
|
+
}
|
|
2495
|
+
}
|
|
2496
|
+
return finalResults;
|
|
2497
|
+
}
|
|
2498
|
+
async function estimateCardinality(agentId, options) {
|
|
2499
|
+
const client = getClient();
|
|
2500
|
+
let sql = `SELECT COUNT(*) as cnt FROM memories
|
|
2501
|
+
WHERE agent_id = ?
|
|
2502
|
+
AND COALESCE(status, 'active') = 'active'
|
|
2503
|
+
AND COALESCE(confidence, 0.7) >= 0.3`;
|
|
2504
|
+
const args = [agentId];
|
|
2505
|
+
if (options?.projectName) {
|
|
2506
|
+
sql += ` AND project_name = ?`;
|
|
2507
|
+
args.push(options.projectName);
|
|
2508
|
+
}
|
|
2509
|
+
if (options?.toolName) {
|
|
2510
|
+
sql += ` AND tool_name = ?`;
|
|
2511
|
+
args.push(options.toolName);
|
|
2512
|
+
}
|
|
2513
|
+
if (options?.hasError !== void 0) {
|
|
2514
|
+
sql += ` AND has_error = ?`;
|
|
2515
|
+
args.push(options.hasError ? 1 : 0);
|
|
2516
|
+
}
|
|
2517
|
+
if (options?.since) {
|
|
2518
|
+
sql += ` AND timestamp >= ?`;
|
|
2519
|
+
args.push(options.since);
|
|
2520
|
+
}
|
|
2521
|
+
try {
|
|
2522
|
+
const result = await client.execute({ sql, args });
|
|
2523
|
+
return Number(result.rows[0]?.cnt) || 0;
|
|
2524
|
+
} catch {
|
|
2525
|
+
return 0;
|
|
2526
|
+
}
|
|
2527
|
+
}
|
|
2528
|
+
function recencyScore(timestamp) {
|
|
2529
|
+
const daysSince = (Date.now() - new Date(timestamp).getTime()) / (1e3 * 60 * 60 * 24);
|
|
2530
|
+
return 1 / (1 + daysSince * 0.01);
|
|
2531
|
+
}
|
|
2532
|
+
function normalizedImportance(importance) {
|
|
2533
|
+
return ((importance ?? 5) - 1) / 9;
|
|
2534
|
+
}
|
|
2535
|
+
function rrfMergeMulti(lists, limit, k = RRF_K, weights) {
|
|
2536
|
+
const scores = /* @__PURE__ */ new Map();
|
|
2537
|
+
for (let listIdx = 0; listIdx < lists.length; listIdx++) {
|
|
2538
|
+
const list = lists[listIdx];
|
|
2539
|
+
const weight = weights?.[listIdx] ?? 1;
|
|
2540
|
+
for (let i = 0; i < list.length; i++) {
|
|
2541
|
+
const rec = list[i];
|
|
2542
|
+
const entry = scores.get(rec.id) ?? { rrfScore: 0, record: rec };
|
|
2543
|
+
entry.rrfScore += weight * (1 / (k + i + 1));
|
|
2544
|
+
scores.set(rec.id, entry);
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
const entries = Array.from(scores.values()).map((e) => {
|
|
2548
|
+
const recency = recencyScore(e.record.timestamp);
|
|
2549
|
+
const importance = normalizedImportance(e.record.importance);
|
|
2550
|
+
const confidence = e.record.confidence ?? 0.7;
|
|
2551
|
+
const finalScore = e.rrfScore * 0.35 + recency * 0.14 + importance * 0.21 + confidence * 0.3;
|
|
2552
|
+
return { score: finalScore, record: e.record };
|
|
2553
|
+
});
|
|
2554
|
+
return entries.sort((a, b) => b.score - a.score).slice(0, limit).map((e) => e.record);
|
|
2555
|
+
}
|
|
2556
|
+
async function lightweightSearch(queryText, agentId, options) {
|
|
2557
|
+
const client = getClient();
|
|
2558
|
+
const limit = options?.limit ?? 5;
|
|
2559
|
+
const terms = queryText.toLowerCase().split(/\s+/).filter((t) => t.length >= 3).map((t) => t.replace(/[^a-z0-9_]/g, "")).filter((t) => t.length >= 3);
|
|
2560
|
+
if (terms.length === 0) {
|
|
2561
|
+
return recentRecords(agentId, options, limit);
|
|
2562
|
+
}
|
|
2563
|
+
const prefixTerms = terms.map((t) => `${t}*`);
|
|
2564
|
+
const useAnd = terms.length >= 3;
|
|
2565
|
+
const matchExpr = useAnd ? prefixTerms.join(" AND ") : prefixTerms.join(" OR ");
|
|
2566
|
+
const results = await ftsQuery(client, matchExpr, agentId, options, limit);
|
|
2567
|
+
if (useAnd && results.length < limit) {
|
|
2568
|
+
const orExpr = prefixTerms.join(" OR ");
|
|
2569
|
+
const orResults = await ftsQuery(client, orExpr, agentId, options, limit);
|
|
2570
|
+
const seen = new Set(results.map((r) => r.id));
|
|
2571
|
+
for (const r of orResults) {
|
|
2572
|
+
if (!seen.has(r.id) && results.length < limit) {
|
|
2573
|
+
results.push(r);
|
|
2574
|
+
seen.add(r.id);
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
if (options?.includeSource && results.length > 0) {
|
|
2579
|
+
await attachDocumentMetadata(results);
|
|
2580
|
+
}
|
|
2581
|
+
return results;
|
|
2582
|
+
}
|
|
2583
|
+
async function ftsQuery(client, matchExpr, agentId, options, limit) {
|
|
2584
|
+
const statusFilter = options?.includeArchived ? "" : `
|
|
2585
|
+
AND COALESCE(m.status, 'active') = 'active'`;
|
|
2586
|
+
let sql = `SELECT m.id, m.agent_id, m.agent_role, m.session_id, m.timestamp,
|
|
2587
|
+
m.tool_name, m.project_name,
|
|
2588
|
+
m.has_error, m.raw_text, m.vector, m.task_id,
|
|
2589
|
+
m.importance, m.status, m.confidence, m.last_accessed,
|
|
2590
|
+
m.workspace_id, m.document_id, m.user_id,
|
|
2591
|
+
m.char_offset, m.page_number
|
|
2592
|
+
FROM memories m
|
|
2593
|
+
JOIN memories_fts fts ON m.rowid = fts.rowid
|
|
2594
|
+
WHERE memories_fts MATCH ?
|
|
2595
|
+
AND m.agent_id = ?${statusFilter}
|
|
2596
|
+
AND COALESCE(m.confidence, 0.7) >= 0.3`;
|
|
2597
|
+
const args = [matchExpr, agentId];
|
|
2598
|
+
const scope = buildWikiScopeFilter(options, "m.");
|
|
2599
|
+
sql += scope.clause;
|
|
2600
|
+
args.push(...scope.args);
|
|
2601
|
+
if (options?.projectName) {
|
|
2602
|
+
sql += ` AND m.project_name = ?`;
|
|
2603
|
+
args.push(options.projectName);
|
|
2604
|
+
}
|
|
2605
|
+
if (options?.toolName) {
|
|
2606
|
+
sql += ` AND m.tool_name = ?`;
|
|
2607
|
+
args.push(options.toolName);
|
|
2608
|
+
}
|
|
2609
|
+
if (options?.hasError !== void 0) {
|
|
2610
|
+
sql += ` AND m.has_error = ?`;
|
|
2611
|
+
args.push(options.hasError ? 1 : 0);
|
|
2612
|
+
}
|
|
2613
|
+
if (options?.since) {
|
|
2614
|
+
sql += ` AND m.timestamp >= ?`;
|
|
2615
|
+
args.push(options.since);
|
|
2616
|
+
}
|
|
2617
|
+
sql += ` ORDER BY rank LIMIT ?`;
|
|
2618
|
+
args.push(limit);
|
|
2619
|
+
const result = await client.execute({ sql, args });
|
|
2620
|
+
return result.rows.map((row) => ({
|
|
2621
|
+
id: row.id,
|
|
2622
|
+
agent_id: row.agent_id,
|
|
2623
|
+
agent_role: row.agent_role,
|
|
2624
|
+
session_id: row.session_id,
|
|
2625
|
+
timestamp: row.timestamp,
|
|
2626
|
+
tool_name: row.tool_name,
|
|
2627
|
+
project_name: row.project_name,
|
|
2628
|
+
has_error: row.has_error === 1,
|
|
2629
|
+
raw_text: row.raw_text,
|
|
2630
|
+
vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
|
|
2631
|
+
task_id: row.task_id ?? null,
|
|
2632
|
+
importance: row.importance ?? 5,
|
|
2633
|
+
status: row.status ?? "active",
|
|
2634
|
+
confidence: row.confidence ?? 0.7,
|
|
2635
|
+
last_accessed: row.last_accessed ?? row.timestamp,
|
|
2636
|
+
workspace_id: row.workspace_id ?? null,
|
|
2637
|
+
document_id: row.document_id ?? null,
|
|
2638
|
+
user_id: row.user_id ?? null,
|
|
2639
|
+
char_offset: row.char_offset ?? null,
|
|
2640
|
+
page_number: row.page_number ?? null
|
|
2641
|
+
}));
|
|
2642
|
+
}
|
|
2643
|
+
async function recentRecords(agentId, options, limit) {
|
|
2644
|
+
const client = getClient();
|
|
2645
|
+
const statusFilter = options?.includeArchived ? "" : `
|
|
2646
|
+
AND COALESCE(status, 'active') = 'active'`;
|
|
2647
|
+
let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
|
|
2648
|
+
tool_name, project_name,
|
|
2649
|
+
has_error, raw_text, vector, task_id,
|
|
2650
|
+
importance, status, confidence, last_accessed,
|
|
2651
|
+
workspace_id, document_id, user_id,
|
|
2652
|
+
char_offset, page_number
|
|
2653
|
+
FROM memories
|
|
2654
|
+
WHERE agent_id = ?${statusFilter}
|
|
2655
|
+
AND COALESCE(confidence, 0.7) >= 0.3`;
|
|
2656
|
+
const args = [agentId];
|
|
2657
|
+
const scope = buildWikiScopeFilter(options, "");
|
|
2658
|
+
sql += scope.clause;
|
|
2659
|
+
args.push(...scope.args);
|
|
2660
|
+
if (options?.projectName) {
|
|
2661
|
+
sql += ` AND project_name = ?`;
|
|
2662
|
+
args.push(options.projectName);
|
|
2663
|
+
}
|
|
2664
|
+
if (options?.toolName) {
|
|
2665
|
+
sql += ` AND tool_name = ?`;
|
|
2666
|
+
args.push(options.toolName);
|
|
2667
|
+
}
|
|
2668
|
+
if (options?.hasError !== void 0) {
|
|
2669
|
+
sql += ` AND has_error = ?`;
|
|
2670
|
+
args.push(options.hasError ? 1 : 0);
|
|
2671
|
+
}
|
|
2672
|
+
if (options?.since) {
|
|
2673
|
+
sql += ` AND timestamp >= ?`;
|
|
2674
|
+
args.push(options.since);
|
|
2675
|
+
}
|
|
2676
|
+
sql += ` ORDER BY timestamp DESC LIMIT ?`;
|
|
2677
|
+
args.push(limit);
|
|
2678
|
+
const result = await client.execute({ sql, args });
|
|
2679
|
+
return result.rows.map((row) => ({
|
|
2680
|
+
id: row.id,
|
|
2681
|
+
agent_id: row.agent_id,
|
|
2682
|
+
agent_role: row.agent_role,
|
|
2683
|
+
session_id: row.session_id,
|
|
2684
|
+
timestamp: row.timestamp,
|
|
2685
|
+
tool_name: row.tool_name,
|
|
2686
|
+
project_name: row.project_name,
|
|
2687
|
+
has_error: row.has_error === 1,
|
|
2688
|
+
raw_text: row.raw_text,
|
|
2689
|
+
vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
|
|
2690
|
+
task_id: row.task_id ?? null,
|
|
2691
|
+
importance: row.importance ?? 5,
|
|
2692
|
+
status: row.status ?? "active",
|
|
2693
|
+
confidence: row.confidence ?? 0.7,
|
|
2694
|
+
last_accessed: row.last_accessed ?? row.timestamp,
|
|
2695
|
+
workspace_id: row.workspace_id ?? null,
|
|
2696
|
+
document_id: row.document_id ?? null,
|
|
2697
|
+
user_id: row.user_id ?? null,
|
|
2698
|
+
char_offset: row.char_offset ?? null,
|
|
2699
|
+
page_number: row.page_number ?? null
|
|
2700
|
+
}));
|
|
2701
|
+
}
|
|
2702
|
+
|
|
2703
|
+
// src/adapters/claude/active-agent.ts
|
|
2704
|
+
init_config();
|
|
2705
|
+
import { readFileSync as readFileSync4, writeFileSync, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2, readdirSync as readdirSync2 } from "fs";
|
|
2706
|
+
import { execSync as execSync4 } from "child_process";
|
|
2707
|
+
import path8 from "path";
|
|
2708
|
+
|
|
2709
|
+
// src/lib/session-key.ts
|
|
2710
|
+
import { execSync as execSync3 } from "child_process";
|
|
2711
|
+
var _cached2 = null;
|
|
2712
|
+
function getSessionKey() {
|
|
2713
|
+
if (_cached2) return _cached2;
|
|
2714
|
+
let pid = process.ppid;
|
|
2715
|
+
for (let i = 0; i < 10; i++) {
|
|
2716
|
+
try {
|
|
2717
|
+
const info = execSync3(`ps -p ${pid} -o ppid=,comm=`, {
|
|
2718
|
+
encoding: "utf8",
|
|
2719
|
+
timeout: 2e3
|
|
2720
|
+
}).trim();
|
|
2721
|
+
const match = info.match(/^\s*(\d+)\s+(.+)$/);
|
|
2722
|
+
if (!match) break;
|
|
2723
|
+
const [, ppid, cmd] = match;
|
|
2724
|
+
if (cmd === "claude" || cmd.endsWith("/claude")) {
|
|
2725
|
+
_cached2 = String(pid);
|
|
2726
|
+
return _cached2;
|
|
2727
|
+
}
|
|
2728
|
+
pid = parseInt(ppid, 10);
|
|
2729
|
+
if (pid <= 1) break;
|
|
2730
|
+
} catch {
|
|
2731
|
+
break;
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
_cached2 = process.env.CLAUDE_CODE_SSE_PORT ?? String(process.ppid);
|
|
2735
|
+
return _cached2;
|
|
2736
|
+
}
|
|
2737
|
+
|
|
2738
|
+
// src/adapters/claude/active-agent.ts
|
|
2739
|
+
var CACHE_DIR = path8.join(EXE_AI_DIR, "session-cache");
|
|
2740
|
+
var STALE_MS = 24 * 60 * 60 * 1e3;
|
|
2741
|
+
function getMarkerPath() {
|
|
2742
|
+
return path8.join(CACHE_DIR, `active-agent-${getSessionKey()}.json`);
|
|
2743
|
+
}
|
|
2744
|
+
function getActiveAgent() {
|
|
2745
|
+
try {
|
|
2746
|
+
const markerPath = getMarkerPath();
|
|
2747
|
+
const raw = readFileSync4(markerPath, "utf8");
|
|
2748
|
+
const data = JSON.parse(raw);
|
|
2749
|
+
if (data.agentId) {
|
|
2750
|
+
if (data.startedAt) {
|
|
2751
|
+
const age = Date.now() - new Date(data.startedAt).getTime();
|
|
2752
|
+
if (age > STALE_MS) {
|
|
2753
|
+
try {
|
|
2754
|
+
unlinkSync2(markerPath);
|
|
2755
|
+
} catch {
|
|
2756
|
+
}
|
|
2757
|
+
} else {
|
|
2758
|
+
return {
|
|
2759
|
+
agentId: data.agentId,
|
|
2760
|
+
agentRole: data.agentRole || "employee"
|
|
2761
|
+
};
|
|
2762
|
+
}
|
|
2763
|
+
} else {
|
|
2764
|
+
return {
|
|
2765
|
+
agentId: data.agentId,
|
|
2766
|
+
agentRole: data.agentRole || "employee"
|
|
2767
|
+
};
|
|
2768
|
+
}
|
|
2769
|
+
}
|
|
2770
|
+
} catch {
|
|
2771
|
+
}
|
|
2772
|
+
try {
|
|
2773
|
+
const sessionName = execSync4(
|
|
2774
|
+
"tmux display-message -p '#{session_name}' 2>/dev/null",
|
|
2775
|
+
{ encoding: "utf8", timeout: 2e3 }
|
|
2776
|
+
).trim();
|
|
2777
|
+
const empMatch = sessionName.match(/^(\w+)-exe\d+$/);
|
|
2778
|
+
if (empMatch && empMatch[1] !== "exe") {
|
|
2779
|
+
return { agentId: empMatch[1], agentRole: "employee" };
|
|
2780
|
+
}
|
|
2781
|
+
if (/^exe\d+$/.test(sessionName)) {
|
|
2782
|
+
return { agentId: "exe", agentRole: "COO" };
|
|
2783
|
+
}
|
|
2784
|
+
} catch {
|
|
2785
|
+
}
|
|
2786
|
+
return {
|
|
2787
|
+
agentId: process.env.AGENT_ID || "default",
|
|
2788
|
+
agentRole: process.env.AGENT_ROLE || "employee"
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2792
|
+
// src/adapters/claude/hooks/error-recall.ts
|
|
2793
|
+
if (!process.env.AGENT_ID) {
|
|
2794
|
+
process.env.AGENT_ID = "default";
|
|
2795
|
+
process.env.AGENT_ROLE = "employee";
|
|
2796
|
+
}
|
|
2797
|
+
if (!loadConfigSync().autoRetrieval) {
|
|
2798
|
+
process.exit(0);
|
|
2799
|
+
}
|
|
2800
|
+
var timeout = setTimeout(() => {
|
|
2801
|
+
process.exit(0);
|
|
2802
|
+
}, 5e3);
|
|
2803
|
+
timeout.unref();
|
|
2804
|
+
var input = "";
|
|
2805
|
+
process.stdin.setEncoding("utf8");
|
|
2806
|
+
process.stdin.on("data", (chunk) => {
|
|
2807
|
+
input += chunk;
|
|
2808
|
+
});
|
|
2809
|
+
process.stdin.on("end", async () => {
|
|
2810
|
+
try {
|
|
2811
|
+
const data = JSON.parse(input);
|
|
2812
|
+
if (!detectError(data)) {
|
|
2813
|
+
process.exit(0);
|
|
2814
|
+
}
|
|
2815
|
+
await initStore();
|
|
2816
|
+
const config = await loadConfig();
|
|
2817
|
+
const search = config.hookSearchMode === "hybrid" ? hybridSearch : lightweightSearch;
|
|
2818
|
+
const agent = getActiveAgent();
|
|
2819
|
+
const errorText = JSON.stringify(data.tool_response).slice(0, 300);
|
|
2820
|
+
const memories = await search(
|
|
2821
|
+
errorText,
|
|
2822
|
+
agent.agentId,
|
|
2823
|
+
{ hasError: true, limit: 3 }
|
|
2824
|
+
);
|
|
2825
|
+
if (memories.length > 0) {
|
|
2826
|
+
const client = getClient();
|
|
2827
|
+
const parts = [];
|
|
2828
|
+
for (const m of memories) {
|
|
2829
|
+
parts.push(
|
|
2830
|
+
`**Error:** [${m.timestamp}] ${m.tool_name} (${m.project_name}): ${m.raw_text.slice(0, 400)}`
|
|
2831
|
+
);
|
|
2832
|
+
try {
|
|
2833
|
+
const fixResult = await client.execute({
|
|
2834
|
+
sql: `SELECT tool_name, project_name, raw_text, timestamp
|
|
2835
|
+
FROM memories
|
|
2836
|
+
WHERE agent_id = ? AND timestamp > ? AND has_error = 0
|
|
2837
|
+
ORDER BY timestamp ASC LIMIT 2`,
|
|
2838
|
+
args: [agent.agentId, m.timestamp]
|
|
2839
|
+
});
|
|
2840
|
+
if (fixResult.rows.length > 0) {
|
|
2841
|
+
const fixes = fixResult.rows.map(
|
|
2842
|
+
(r) => ` Fix: [${r.timestamp}] ${r.tool_name}: ${r.raw_text.slice(0, 300)}`
|
|
2843
|
+
).join("\n");
|
|
2844
|
+
parts.push(fixes);
|
|
2845
|
+
}
|
|
2846
|
+
} catch {
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
const output = JSON.stringify({
|
|
2850
|
+
hookSpecificOutput: {
|
|
2851
|
+
hookEventName: "PostToolUse",
|
|
2852
|
+
additionalContext: `## Past Solutions for Similar Errors
|
|
2853
|
+
${parts.join("\n\n")}`
|
|
2854
|
+
}
|
|
2855
|
+
});
|
|
2856
|
+
process.stdout.write(output);
|
|
2857
|
+
}
|
|
2858
|
+
} catch {
|
|
2859
|
+
}
|
|
2860
|
+
process.exit(0);
|
|
2861
|
+
});
|