@exulu/backend 5.7.1 → 5.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/dist/{catalog-3QLU2G7R.js → catalog-4P3TKOV7.js} +2 -1
- package/dist/chunk-4W3V7IHR.js +1166 -0
- package/dist/chunk-6URU62NI.js +54 -0
- package/dist/{chunk-4PDWNVNT.js → chunk-F534XOQR.js} +3 -50
- package/dist/{chunk-XNTGIQLC.js → chunk-NUEM3HMI.js} +501 -1471
- package/dist/chunk-RNZ4IDCT.js +946 -0
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-XOL5J5ET.js → convert-exulu-tools-to-ai-sdk-tools-3UCQOIY6.js} +4 -2
- package/dist/doc_processor-E5GCE2ZT.js +10 -0
- package/dist/index.cjs +29509 -29270
- package/dist/index.d.cts +118 -105
- package/dist/index.d.ts +118 -105
- package/dist/index.js +154 -1053
- package/ee/invoke-skills/binary-file-guard.test.ts +22 -0
- package/ee/invoke-skills/binary-file-guard.ts +33 -0
- package/ee/invoke-skills/create-sandbox.ts +10 -0
- package/ee/python/documents/processing/doc_processor.ts +3 -3
- package/ee/workers.ts +6 -4
- package/package.json +1 -1
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
import "dotenv/config";
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
buildTags,
|
|
4
|
+
checkLicense,
|
|
5
|
+
isLiteLLMEnabled,
|
|
6
|
+
postgresClient,
|
|
7
|
+
provisionDefaultUserBudget,
|
|
8
|
+
resolveModel,
|
|
9
|
+
waitForLiteLLMReady,
|
|
10
|
+
withRetry
|
|
11
|
+
} from "./chunk-4W3V7IHR.js";
|
|
12
|
+
import {
|
|
13
|
+
findLiteLLMModel
|
|
14
|
+
} from "./chunk-F534XOQR.js";
|
|
15
|
+
import {
|
|
16
|
+
resolveLiteLLMTarget
|
|
17
|
+
} from "./chunk-6URU62NI.js";
|
|
10
18
|
|
|
11
19
|
// src/templates/tools/convert-exulu-tools-to-ai-sdk-tools.ts
|
|
12
20
|
import { S3Client as S3Client3, PutObjectCommand as PutObjectCommand3, S3ServiceException } from "@aws-sdk/client-s3";
|
|
@@ -37,1078 +45,6 @@ var exuluApp = {
|
|
|
37
45
|
}
|
|
38
46
|
};
|
|
39
47
|
|
|
40
|
-
// src/exulu/resolve-model.ts
|
|
41
|
-
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
42
|
-
|
|
43
|
-
// src/exulu/litellm/supervisor.ts
|
|
44
|
-
import { spawn } from "child_process";
|
|
45
|
-
import { existsSync } from "fs";
|
|
46
|
-
import { resolve } from "path";
|
|
47
|
-
var LITELLM_UI_PATH = "/litellm-admin";
|
|
48
|
-
var MAX_CRASHES = 5;
|
|
49
|
-
var INITIAL_BACKOFF_MS = 1e3;
|
|
50
|
-
var MAX_BACKOFF_MS = 3e4;
|
|
51
|
-
var READY_TIMEOUT_MS = 9e4;
|
|
52
|
-
var WAIT_TIMEOUT_MS = 6e4;
|
|
53
|
-
var READY_POLL_INTERVAL_MS = 200;
|
|
54
|
-
var SHUTDOWN_GRACE_MS = 5e3;
|
|
55
|
-
var internal = {
|
|
56
|
-
child: void 0,
|
|
57
|
-
state: "idle",
|
|
58
|
-
crashCount: 0,
|
|
59
|
-
backoffMs: INITIAL_BACKOFF_MS,
|
|
60
|
-
readyPromise: void 0,
|
|
61
|
-
shutdownRequested: false
|
|
62
|
-
};
|
|
63
|
-
var isLiteLLMEnabled = () => process.env.EXULU_USE_LITELLM === "true";
|
|
64
|
-
var resolveConfig = (packageRoot) => {
|
|
65
|
-
const host = process.env.LITELLM_HOST ?? "127.0.0.1";
|
|
66
|
-
const port = process.env.LITELLM_PORT ?? "4000";
|
|
67
|
-
const masterKey = process.env.LITELLM_MASTER_KEY;
|
|
68
|
-
const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve(process.cwd(), "./config.litellm.yaml");
|
|
69
|
-
const venvBin = resolve(packageRoot, "ee/python/.venv/bin");
|
|
70
|
-
const venvPython = resolve(venvBin, "python");
|
|
71
|
-
const litellmBin = resolve(venvBin, "litellm");
|
|
72
|
-
return { host, port, masterKey, configPath, venvBin, venvPython, litellmBin };
|
|
73
|
-
};
|
|
74
|
-
var log = (line) => console.log(`[EXULU-LITELLM] ${line}`);
|
|
75
|
-
var pollHealth = async (host, port) => {
|
|
76
|
-
const url = `http://${host}:${port}/health/liveliness`;
|
|
77
|
-
const deadline = Date.now() + READY_TIMEOUT_MS;
|
|
78
|
-
while (Date.now() < deadline) {
|
|
79
|
-
try {
|
|
80
|
-
const res = await fetch(url, { method: "GET" });
|
|
81
|
-
if (res.ok) return;
|
|
82
|
-
} catch {
|
|
83
|
-
}
|
|
84
|
-
await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
|
|
85
|
-
}
|
|
86
|
-
throw new Error(
|
|
87
|
-
`LiteLLM did not become ready at ${url} within ${READY_TIMEOUT_MS}ms`
|
|
88
|
-
);
|
|
89
|
-
};
|
|
90
|
-
var spawnLiteLLM = (cfg) => {
|
|
91
|
-
log(
|
|
92
|
-
`Spawning LiteLLM: ${cfg.litellmBin} --config ${cfg.configPath} --port ${cfg.port} --host ${cfg.host}`
|
|
93
|
-
);
|
|
94
|
-
const { DEBUG: _debug, ...rest } = process.env;
|
|
95
|
-
const childEnv = {
|
|
96
|
-
...rest,
|
|
97
|
-
DEBUG: "false"
|
|
98
|
-
};
|
|
99
|
-
if (!process.env.DISABLE_SCHEMA_UPDATE) {
|
|
100
|
-
childEnv.DISABLE_SCHEMA_UPDATE = "true";
|
|
101
|
-
}
|
|
102
|
-
if (LITELLM_UI_PATH && !process.env.SERVER_ROOT_PATH) {
|
|
103
|
-
childEnv.SERVER_ROOT_PATH = LITELLM_UI_PATH;
|
|
104
|
-
}
|
|
105
|
-
const child = spawn(
|
|
106
|
-
cfg.litellmBin,
|
|
107
|
-
[
|
|
108
|
-
"--config",
|
|
109
|
-
cfg.configPath,
|
|
110
|
-
"--port",
|
|
111
|
-
cfg.port,
|
|
112
|
-
"--host",
|
|
113
|
-
cfg.host
|
|
114
|
-
],
|
|
115
|
-
{
|
|
116
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
117
|
-
env: childEnv
|
|
118
|
-
}
|
|
119
|
-
);
|
|
120
|
-
child.stdout?.on("data", (chunk) => {
|
|
121
|
-
chunk.toString().split("\n").filter((l) => l.length > 0).forEach((l) => log(l));
|
|
122
|
-
});
|
|
123
|
-
child.stderr?.on("data", (chunk) => {
|
|
124
|
-
chunk.toString().split("\n").filter((l) => l.length > 0).forEach((l) => log(`stderr: ${l}`));
|
|
125
|
-
});
|
|
126
|
-
return child;
|
|
127
|
-
};
|
|
128
|
-
var supervise = async (cfg) => {
|
|
129
|
-
while (!internal.shutdownRequested && internal.crashCount < MAX_CRASHES) {
|
|
130
|
-
internal.state = internal.crashCount === 0 ? "starting" : "respawning";
|
|
131
|
-
internal.child = spawnLiteLLM(cfg);
|
|
132
|
-
const exitPromise = new Promise((resolveFn) => {
|
|
133
|
-
internal.child.on("exit", (code2) => resolveFn(code2));
|
|
134
|
-
});
|
|
135
|
-
try {
|
|
136
|
-
await Promise.race([
|
|
137
|
-
pollHealth(cfg.host, cfg.port).then(() => "ready"),
|
|
138
|
-
exitPromise.then((code2) => ({ exited: code2 }))
|
|
139
|
-
]);
|
|
140
|
-
} catch (err3) {
|
|
141
|
-
log(`Readiness probe failed: ${err3.message}`);
|
|
142
|
-
try {
|
|
143
|
-
internal.child?.kill("SIGTERM");
|
|
144
|
-
} catch {
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
if (!internal.child?.killed && internal.child?.exitCode === null) {
|
|
148
|
-
internal.state = "ready";
|
|
149
|
-
internal.crashCount = 0;
|
|
150
|
-
internal.backoffMs = INITIAL_BACKOFF_MS;
|
|
151
|
-
log("LiteLLM is ready.");
|
|
152
|
-
}
|
|
153
|
-
const code = await exitPromise;
|
|
154
|
-
internal.state = "respawning";
|
|
155
|
-
internal.child = void 0;
|
|
156
|
-
if (internal.shutdownRequested) {
|
|
157
|
-
log("Child exited during shutdown; supervisor stopping.");
|
|
158
|
-
internal.state = "stopped";
|
|
159
|
-
return;
|
|
160
|
-
}
|
|
161
|
-
internal.crashCount += 1;
|
|
162
|
-
log(
|
|
163
|
-
`LiteLLM exited (code=${code}). Crash ${internal.crashCount}/${MAX_CRASHES}. Respawning in ${internal.backoffMs}ms.`
|
|
164
|
-
);
|
|
165
|
-
if (internal.crashCount >= MAX_CRASHES) {
|
|
166
|
-
log(
|
|
167
|
-
"LiteLLM keeps crashing \u2014 fix the config and restart Exulu. Giving up on respawn."
|
|
168
|
-
);
|
|
169
|
-
internal.state = "given_up";
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
await new Promise((r) => setTimeout(r, internal.backoffMs));
|
|
173
|
-
internal.backoffMs = Math.min(internal.backoffMs * 2, MAX_BACKOFF_MS);
|
|
174
|
-
}
|
|
175
|
-
};
|
|
176
|
-
var _packageRoot;
|
|
177
|
-
var setLiteLLMPackageRoot = (root) => {
|
|
178
|
-
_packageRoot = root;
|
|
179
|
-
};
|
|
180
|
-
var enableLiteLLMClientMode = () => {
|
|
181
|
-
if (internal.readyPromise) return;
|
|
182
|
-
setLiteLLMClientMode(true);
|
|
183
|
-
};
|
|
184
|
-
var startLiteLLMSupervisor = async (options = {}) => {
|
|
185
|
-
if (!isLiteLLMEnabled()) return;
|
|
186
|
-
if (internal.readyPromise) {
|
|
187
|
-
return internal.readyPromise;
|
|
188
|
-
}
|
|
189
|
-
if (!process.env.LITELLM_MASTER_KEY) {
|
|
190
|
-
throw new Error(
|
|
191
|
-
"EXULU_USE_LITELLM is true but LITELLM_MASTER_KEY is not set. Set LITELLM_MASTER_KEY to a strong secret and restart Exulu."
|
|
192
|
-
);
|
|
193
|
-
}
|
|
194
|
-
const packageRoot = options.packageRoot ?? _packageRoot;
|
|
195
|
-
if (!packageRoot) {
|
|
196
|
-
throw new Error(
|
|
197
|
-
"LiteLLM supervisor: package root not set. Call setLiteLLMPackageRoot() from the boot path before starting the supervisor."
|
|
198
|
-
);
|
|
199
|
-
}
|
|
200
|
-
const cfg = resolveConfig(packageRoot);
|
|
201
|
-
if (!existsSync(cfg.configPath)) {
|
|
202
|
-
log(
|
|
203
|
-
`LiteLLM config not found at ${cfg.configPath}. Copy ee/python/.litellm/config.yaml.example to that path, edit it, and restart Exulu. LiteLLM will NOT be started until then.`
|
|
204
|
-
);
|
|
205
|
-
internal.state = "given_up";
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
if (!existsSync(cfg.litellmBin)) {
|
|
209
|
-
log(
|
|
210
|
-
`LiteLLM binary not found at ${cfg.litellmBin}. The Python venv may not be set up. Run setupPythonEnvironment() from @exulu/backend, then restart.`
|
|
211
|
-
);
|
|
212
|
-
internal.state = "given_up";
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
internal.readyPromise = (async () => {
|
|
216
|
-
supervise(cfg);
|
|
217
|
-
const deadline = Date.now() + READY_TIMEOUT_MS + 5e3;
|
|
218
|
-
while (Date.now() < deadline) {
|
|
219
|
-
if (internal.state === "ready") return;
|
|
220
|
-
if (internal.state === "given_up") {
|
|
221
|
-
throw new Error("LiteLLM supervisor gave up before becoming ready.");
|
|
222
|
-
}
|
|
223
|
-
await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
|
|
224
|
-
}
|
|
225
|
-
throw new Error("Timed out waiting for LiteLLM supervisor readiness.");
|
|
226
|
-
})();
|
|
227
|
-
registerShutdownHandlers();
|
|
228
|
-
return internal.readyPromise;
|
|
229
|
-
};
|
|
230
|
-
var waitForLiteLLMReady = async () => {
|
|
231
|
-
if (!isLiteLLMEnabled()) return;
|
|
232
|
-
if (isLiteLLMClientMode()) {
|
|
233
|
-
if (internal.state === "ready") return;
|
|
234
|
-
const { baseUrl, authHeaders, remote } = resolveLiteLLMTarget();
|
|
235
|
-
const url = remote ? `${baseUrl}/v1/models` : `${baseUrl}/health/liveliness`;
|
|
236
|
-
let res;
|
|
237
|
-
try {
|
|
238
|
-
res = await fetch(url, { method: "GET", headers: remote ? authHeaders : {} });
|
|
239
|
-
} catch (err3) {
|
|
240
|
-
throw new Error(
|
|
241
|
-
`LiteLLM proxy not reachable at ${url} (is the Exulu server process running?): ${err3.message}`
|
|
242
|
-
);
|
|
243
|
-
}
|
|
244
|
-
if (!res.ok) {
|
|
245
|
-
throw new Error(
|
|
246
|
-
`LiteLLM proxy health probe at ${url} returned ${res.status}.`
|
|
247
|
-
);
|
|
248
|
-
}
|
|
249
|
-
internal.state = "ready";
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
if (!internal.readyPromise) {
|
|
253
|
-
return startLiteLLMSupervisor();
|
|
254
|
-
}
|
|
255
|
-
const deadline = Date.now() + WAIT_TIMEOUT_MS;
|
|
256
|
-
while (Date.now() < deadline) {
|
|
257
|
-
const s = getSupervisorState();
|
|
258
|
-
if (s === "ready") return;
|
|
259
|
-
if (s === "given_up") {
|
|
260
|
-
throw new Error("LiteLLM supervisor has given up.");
|
|
261
|
-
}
|
|
262
|
-
await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
|
|
263
|
-
}
|
|
264
|
-
throw new Error("Timed out waiting for LiteLLM to become ready.");
|
|
265
|
-
};
|
|
266
|
-
var stopLiteLLM = (signal = "SIGTERM") => {
|
|
267
|
-
internal.shutdownRequested = true;
|
|
268
|
-
const child = internal.child;
|
|
269
|
-
if (!child) return;
|
|
270
|
-
try {
|
|
271
|
-
child.kill(signal);
|
|
272
|
-
} catch {
|
|
273
|
-
}
|
|
274
|
-
setTimeout(() => {
|
|
275
|
-
try {
|
|
276
|
-
if (!child.killed && child.exitCode === null) {
|
|
277
|
-
child.kill("SIGKILL");
|
|
278
|
-
}
|
|
279
|
-
} catch {
|
|
280
|
-
}
|
|
281
|
-
}, SHUTDOWN_GRACE_MS).unref();
|
|
282
|
-
};
|
|
283
|
-
var shutdownHandlersRegistered = false;
|
|
284
|
-
var registerShutdownHandlers = () => {
|
|
285
|
-
if (shutdownHandlersRegistered) return;
|
|
286
|
-
shutdownHandlersRegistered = true;
|
|
287
|
-
process.on("SIGINT", () => stopLiteLLM("SIGTERM"));
|
|
288
|
-
process.on("SIGTERM", () => stopLiteLLM("SIGTERM"));
|
|
289
|
-
process.on("exit", () => stopLiteLLM("SIGTERM"));
|
|
290
|
-
};
|
|
291
|
-
var getSupervisorState = () => internal.state;
|
|
292
|
-
|
|
293
|
-
// src/exulu/tags.ts
|
|
294
|
-
var MAX_LEN = 63;
|
|
295
|
-
function sanitizeTagValue(raw) {
|
|
296
|
-
if (raw === void 0 || raw === null) return void 0;
|
|
297
|
-
const s = String(raw).normalize("NFKC").toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
298
|
-
return s.slice(0, MAX_LEN);
|
|
299
|
-
}
|
|
300
|
-
function buildTags(input) {
|
|
301
|
-
const candidates = [];
|
|
302
|
-
if (input.user_id) {
|
|
303
|
-
candidates.push("user_id_" + input.user_id);
|
|
304
|
-
}
|
|
305
|
-
if (input.user_name) {
|
|
306
|
-
candidates.push("user_name_" + input.user_name);
|
|
307
|
-
}
|
|
308
|
-
if (input.role_id) {
|
|
309
|
-
candidates.push("role_id_" + input.role_id);
|
|
310
|
-
}
|
|
311
|
-
if (input.role_name) {
|
|
312
|
-
candidates.push("role_name_" + input.role_name);
|
|
313
|
-
}
|
|
314
|
-
if (input.project_id) {
|
|
315
|
-
candidates.push("project_id_" + input.project_id);
|
|
316
|
-
}
|
|
317
|
-
if (input.project_name) {
|
|
318
|
-
candidates.push("project_name_" + input.project_name);
|
|
319
|
-
}
|
|
320
|
-
if (input.agent_id) {
|
|
321
|
-
candidates.push("agent_id_" + input.agent_id);
|
|
322
|
-
}
|
|
323
|
-
if (input.agent_name) {
|
|
324
|
-
candidates.push("agent_name_" + input.agent_name);
|
|
325
|
-
}
|
|
326
|
-
if (input.team_id) {
|
|
327
|
-
candidates.push("team_id_" + input.team_id);
|
|
328
|
-
}
|
|
329
|
-
if (input.team_name) {
|
|
330
|
-
candidates.push("team_name_" + input.team_name);
|
|
331
|
-
}
|
|
332
|
-
if (input.routine_id) {
|
|
333
|
-
candidates.push("routine_id_" + input.routine_id);
|
|
334
|
-
}
|
|
335
|
-
if (input.routine_name) {
|
|
336
|
-
candidates.push("routine_name_" + input.routine_name);
|
|
337
|
-
}
|
|
338
|
-
if (input.context_id) {
|
|
339
|
-
candidates.push("context_id_" + input.context_id);
|
|
340
|
-
}
|
|
341
|
-
if (input.context_name) {
|
|
342
|
-
candidates.push("context_name_" + input.context_name);
|
|
343
|
-
}
|
|
344
|
-
console.log("[EXULU] Candidates", candidates);
|
|
345
|
-
const out = [];
|
|
346
|
-
for (const candidate of candidates) {
|
|
347
|
-
if (candidate === void 0 || candidate === null) continue;
|
|
348
|
-
const value = sanitizeTagValue(candidate);
|
|
349
|
-
console.log("[EXULU] Sanitized tag value", value);
|
|
350
|
-
if (value === void 0 || value === "") continue;
|
|
351
|
-
out.push(value);
|
|
352
|
-
}
|
|
353
|
-
return out;
|
|
354
|
-
}
|
|
355
|
-
function budgetTagFor(entityType, id) {
|
|
356
|
-
const value = sanitizeTagValue(`${entityType}_id_${id}`);
|
|
357
|
-
return value ?? "";
|
|
358
|
-
}
|
|
359
|
-
function decodeBody(body) {
|
|
360
|
-
if (typeof body === "string") return body;
|
|
361
|
-
if (body instanceof Uint8Array) return new TextDecoder().decode(body);
|
|
362
|
-
return void 0;
|
|
363
|
-
}
|
|
364
|
-
function stripContentLengthHeader(headers) {
|
|
365
|
-
if (!headers) return headers;
|
|
366
|
-
if (typeof headers.delete === "function") {
|
|
367
|
-
const clone = new globalThis.Headers(headers);
|
|
368
|
-
clone.delete("content-length");
|
|
369
|
-
return clone;
|
|
370
|
-
}
|
|
371
|
-
if (Array.isArray(headers)) {
|
|
372
|
-
return headers.filter(
|
|
373
|
-
([k]) => k.toLowerCase() !== "content-length"
|
|
374
|
-
);
|
|
375
|
-
}
|
|
376
|
-
const out = {};
|
|
377
|
-
for (const [k, v] of Object.entries(headers)) {
|
|
378
|
-
if (k.toLowerCase() === "content-length") continue;
|
|
379
|
-
out[k] = v;
|
|
380
|
-
}
|
|
381
|
-
return out;
|
|
382
|
-
}
|
|
383
|
-
function createTaggedFetch(tags) {
|
|
384
|
-
const labeled = async (input, init) => {
|
|
385
|
-
try {
|
|
386
|
-
if (!init || !init.body) return globalThis.fetch(input, init);
|
|
387
|
-
const method = (init.method ?? "POST").toUpperCase();
|
|
388
|
-
if (method !== "POST" && method !== "PUT" && method !== "PATCH") {
|
|
389
|
-
return globalThis.fetch(input, init);
|
|
390
|
-
}
|
|
391
|
-
const decoded = decodeBody(init.body);
|
|
392
|
-
if (decoded === void 0) {
|
|
393
|
-
console.warn("[vertex-labels] unsupported body type, forwarding unchanged");
|
|
394
|
-
return globalThis.fetch(input, init);
|
|
395
|
-
}
|
|
396
|
-
let parsed;
|
|
397
|
-
try {
|
|
398
|
-
parsed = JSON.parse(decoded);
|
|
399
|
-
} catch {
|
|
400
|
-
console.warn("[vertex-labels] body is not JSON, forwarding unchanged");
|
|
401
|
-
return globalThis.fetch(input, init);
|
|
402
|
-
}
|
|
403
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
404
|
-
return globalThis.fetch(input, init);
|
|
405
|
-
}
|
|
406
|
-
const existing = parsed.metadata ?? {};
|
|
407
|
-
parsed.metadata = { ...existing, tags };
|
|
408
|
-
console.log("[EXULU] tags", parsed.metadata);
|
|
409
|
-
const nextInit = {
|
|
410
|
-
...init,
|
|
411
|
-
body: JSON.stringify(parsed),
|
|
412
|
-
headers: stripContentLengthHeader(init.headers)
|
|
413
|
-
};
|
|
414
|
-
return globalThis.fetch(input, nextInit);
|
|
415
|
-
} catch (err3) {
|
|
416
|
-
console.warn("[vertex-labels] label injection failed, forwarding unchanged", err3);
|
|
417
|
-
return globalThis.fetch(input, init);
|
|
418
|
-
}
|
|
419
|
-
};
|
|
420
|
-
return labeled;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
// src/postgres/client.ts
|
|
424
|
-
import Knex from "knex";
|
|
425
|
-
import "pgvector/knex";
|
|
426
|
-
var db = {};
|
|
427
|
-
var databaseExistsChecked = false;
|
|
428
|
-
var getDbName = () => process.env.POSTGRES_DB_NAME || "exulu";
|
|
429
|
-
async function ensureDatabaseExists() {
|
|
430
|
-
const dbName = getDbName();
|
|
431
|
-
const defaultKnex = Knex({
|
|
432
|
-
client: "pg",
|
|
433
|
-
connection: {
|
|
434
|
-
host: process.env.POSTGRES_DB_HOST,
|
|
435
|
-
port: parseInt(process.env.POSTGRES_DB_PORT || "5432"),
|
|
436
|
-
user: process.env.POSTGRES_DB_USER,
|
|
437
|
-
database: "postgres",
|
|
438
|
-
// Connect to default database
|
|
439
|
-
password: process.env.POSTGRES_DB_PASSWORD,
|
|
440
|
-
ssl: process.env.POSTGRES_DB_SSL === "true" ? { rejectUnauthorized: false } : false,
|
|
441
|
-
connectionTimeoutMillis: 1e4
|
|
442
|
-
},
|
|
443
|
-
pool: {
|
|
444
|
-
min: 2,
|
|
445
|
-
max: 4,
|
|
446
|
-
acquireTimeoutMillis: 3e4,
|
|
447
|
-
createTimeoutMillis: 3e4,
|
|
448
|
-
idleTimeoutMillis: 3e4,
|
|
449
|
-
reapIntervalMillis: 1e3,
|
|
450
|
-
createRetryIntervalMillis: 200
|
|
451
|
-
}
|
|
452
|
-
});
|
|
453
|
-
try {
|
|
454
|
-
const result = await defaultKnex.raw(`
|
|
455
|
-
SELECT 1 FROM pg_database WHERE datname = '${dbName}'
|
|
456
|
-
`);
|
|
457
|
-
if (result.rows.length === 0) {
|
|
458
|
-
console.log(`[EXULU] Database '${dbName}' does not exist. Creating it...`);
|
|
459
|
-
await defaultKnex.raw(`CREATE DATABASE ${dbName}`);
|
|
460
|
-
console.log(`[EXULU] Database '${dbName}' created successfully.`);
|
|
461
|
-
} else {
|
|
462
|
-
console.log(`[EXULU] Database '${dbName}' already exists.`);
|
|
463
|
-
}
|
|
464
|
-
} catch (error) {
|
|
465
|
-
console.error(
|
|
466
|
-
"[EXULU] Error while checking to ensure the database exists, this could be if the user running the server does not have database admin rights, it is fine to ignore this if you are sure the database exists.",
|
|
467
|
-
error
|
|
468
|
-
);
|
|
469
|
-
return;
|
|
470
|
-
} finally {
|
|
471
|
-
await defaultKnex.destroy();
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
async function postgresClient() {
|
|
475
|
-
if (!db["exulu"]) {
|
|
476
|
-
try {
|
|
477
|
-
if (!databaseExistsChecked) {
|
|
478
|
-
await ensureDatabaseExists();
|
|
479
|
-
databaseExistsChecked = true;
|
|
480
|
-
}
|
|
481
|
-
const knex = Knex({
|
|
482
|
-
client: "pg",
|
|
483
|
-
connection: {
|
|
484
|
-
host: process.env.POSTGRES_DB_HOST,
|
|
485
|
-
port: parseInt(process.env.POSTGRES_DB_PORT || "5432"),
|
|
486
|
-
user: process.env.POSTGRES_DB_USER,
|
|
487
|
-
database: getDbName(),
|
|
488
|
-
password: process.env.POSTGRES_DB_PASSWORD,
|
|
489
|
-
ssl: process.env.POSTGRES_DB_SSL === "true" ? { rejectUnauthorized: false } : false,
|
|
490
|
-
// TCP keepalive prevents idle sockets from being silently dropped by
|
|
491
|
-
// intermediate network devices (NAT, firewalls) between us and Hetzner.
|
|
492
|
-
keepAlive: true,
|
|
493
|
-
keepAliveInitialDelayMillis: 1e4,
|
|
494
|
-
connectionTimeoutMillis: 3e4,
|
|
495
|
-
statement_timeout: 18e5,
|
|
496
|
-
query_timeout: 18e5
|
|
497
|
-
},
|
|
498
|
-
pool: {
|
|
499
|
-
min: 10,
|
|
500
|
-
max: 300,
|
|
501
|
-
acquireTimeoutMillis: 12e4,
|
|
502
|
-
createTimeoutMillis: 3e4,
|
|
503
|
-
idleTimeoutMillis: 3e4,
|
|
504
|
-
reapIntervalMillis: 1e3,
|
|
505
|
-
createRetryIntervalMillis: 200,
|
|
506
|
-
// Enable propagateCreateError to properly handle connection creation failures
|
|
507
|
-
propagateCreateError: false,
|
|
508
|
-
// Log pool events to help debug connection issues
|
|
509
|
-
afterCreate: (conn, done) => {
|
|
510
|
-
console.log("[EXULU] New database connection created");
|
|
511
|
-
conn.query("SET statement_timeout = 1800000; SET hnsw.ef_search = 20", (err3) => {
|
|
512
|
-
if (err3) {
|
|
513
|
-
console.error("[EXULU] Error setting connection parameters:", err3);
|
|
514
|
-
}
|
|
515
|
-
done(err3, conn);
|
|
516
|
-
});
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
});
|
|
520
|
-
try {
|
|
521
|
-
await knex.schema.createExtensionIfNotExists("vector");
|
|
522
|
-
} catch (error) {
|
|
523
|
-
console.error(
|
|
524
|
-
"[EXULU] Error creating vector extension, this might be fine if you already activated the extension and the 'user' running this script does not have higher level database permissions.",
|
|
525
|
-
error
|
|
526
|
-
);
|
|
527
|
-
}
|
|
528
|
-
db["exulu"] = knex;
|
|
529
|
-
} catch (error) {
|
|
530
|
-
console.error("[EXULU] Error initializing exulu database.", error);
|
|
531
|
-
throw error;
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
return {
|
|
535
|
-
db: db["exulu"]
|
|
536
|
-
};
|
|
537
|
-
}
|
|
538
|
-
|
|
539
|
-
// src/exulu/litellm/admin-client.ts
|
|
540
|
-
async function call(path3, body) {
|
|
541
|
-
const { url, masterKey } = litellmBase();
|
|
542
|
-
const res = await fetch(`${url}${path3}`, {
|
|
543
|
-
method: "POST",
|
|
544
|
-
headers: {
|
|
545
|
-
Authorization: `Bearer ${masterKey}`,
|
|
546
|
-
"Content-Type": "application/json"
|
|
547
|
-
},
|
|
548
|
-
body: JSON.stringify(body)
|
|
549
|
-
});
|
|
550
|
-
if (!res.ok) {
|
|
551
|
-
const text = await res.text().catch(() => "");
|
|
552
|
-
throw new LiteLLMAdminError(
|
|
553
|
-
`LiteLLM ${path3} returned ${res.status}: ${text}`,
|
|
554
|
-
res.status
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
return await res.json().catch(() => ({}));
|
|
558
|
-
}
|
|
559
|
-
async function tagNew(input) {
|
|
560
|
-
await call("/tag/new", {
|
|
561
|
-
name: input.name,
|
|
562
|
-
max_budget: input.max_budget,
|
|
563
|
-
budget_duration: input.budget_duration
|
|
564
|
-
});
|
|
565
|
-
}
|
|
566
|
-
async function tagUpdate(input) {
|
|
567
|
-
await call("/tag/update", {
|
|
568
|
-
name: input.name,
|
|
569
|
-
max_budget: input.max_budget,
|
|
570
|
-
budget_duration: input.budget_duration
|
|
571
|
-
});
|
|
572
|
-
}
|
|
573
|
-
async function budgetUpdate(budget_id, patch) {
|
|
574
|
-
await call("/budget/update", { budget_id, ...patch });
|
|
575
|
-
}
|
|
576
|
-
async function tagDelete(name) {
|
|
577
|
-
await call("/tag/delete", { name });
|
|
578
|
-
}
|
|
579
|
-
function extractBudget(raw) {
|
|
580
|
-
const bt = raw?.litellm_budget_table ?? {};
|
|
581
|
-
const max_budget = bt.max_budget ?? raw?.max_budget ?? null;
|
|
582
|
-
const budget_duration = bt.budget_duration ?? raw?.budget_duration ?? null;
|
|
583
|
-
const budget_reset_at = bt.budget_reset_at ?? raw?.budget_reset_at ?? null;
|
|
584
|
-
const budget_id = bt.budget_id ?? raw?.budget_id ?? null;
|
|
585
|
-
const spend = typeof raw?.spend === "number" ? raw.spend : typeof bt.spend === "number" ? bt.spend : 0;
|
|
586
|
-
return { max_budget, budget_duration, budget_reset_at, budget_id, spend };
|
|
587
|
-
}
|
|
588
|
-
async function listTags() {
|
|
589
|
-
const { url, masterKey } = litellmBase();
|
|
590
|
-
const res = await fetch(`${url}/tag/list`, {
|
|
591
|
-
method: "GET",
|
|
592
|
-
headers: { Authorization: `Bearer ${masterKey}` }
|
|
593
|
-
});
|
|
594
|
-
if (!res.ok) {
|
|
595
|
-
const text = await res.text().catch(() => "");
|
|
596
|
-
throw new LiteLLMAdminError(
|
|
597
|
-
`LiteLLM /tag/list returned ${res.status}: ${text}`,
|
|
598
|
-
res.status
|
|
599
|
-
);
|
|
600
|
-
}
|
|
601
|
-
const json = await res.json().catch(() => []);
|
|
602
|
-
if (Array.isArray(json)) return json;
|
|
603
|
-
if (json && typeof json === "object") return Object.values(json);
|
|
604
|
-
return [];
|
|
605
|
-
}
|
|
606
|
-
async function listTagBudgets() {
|
|
607
|
-
const entries = await listTags();
|
|
608
|
-
const map = {};
|
|
609
|
-
for (const e of entries) {
|
|
610
|
-
const name = e?.name ?? e?.tag_name;
|
|
611
|
-
if (typeof name !== "string") continue;
|
|
612
|
-
const b = extractBudget(e);
|
|
613
|
-
if (b.max_budget == null) continue;
|
|
614
|
-
map[name] = {
|
|
615
|
-
name,
|
|
616
|
-
spend: b.spend,
|
|
617
|
-
max_budget: b.max_budget,
|
|
618
|
-
budget_duration: b.budget_duration,
|
|
619
|
-
budget_reset_at: b.budget_reset_at,
|
|
620
|
-
budget_id: b.budget_id
|
|
621
|
-
};
|
|
622
|
-
}
|
|
623
|
-
const names = Object.keys(map);
|
|
624
|
-
if (names.length > 0) {
|
|
625
|
-
try {
|
|
626
|
-
const info = await tagInfo(names);
|
|
627
|
-
for (const name of names) {
|
|
628
|
-
const ti = info[name];
|
|
629
|
-
const entry = map[name];
|
|
630
|
-
if (ti && entry) entry.spend = ti.spend;
|
|
631
|
-
}
|
|
632
|
-
} catch {
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
return map;
|
|
636
|
-
}
|
|
637
|
-
async function tagInfo(names) {
|
|
638
|
-
const out = {};
|
|
639
|
-
for (const n of names) out[n] = null;
|
|
640
|
-
if (names.length === 0) return out;
|
|
641
|
-
let json;
|
|
642
|
-
try {
|
|
643
|
-
json = await call("/tag/info", { names });
|
|
644
|
-
} catch (err3) {
|
|
645
|
-
if (err3 instanceof LiteLLMAdminError && /not found/i.test(err3.message)) {
|
|
646
|
-
return out;
|
|
647
|
-
}
|
|
648
|
-
throw err3;
|
|
649
|
-
}
|
|
650
|
-
for (const name of names) {
|
|
651
|
-
const raw = json?.[name];
|
|
652
|
-
if (!raw) {
|
|
653
|
-
out[name] = null;
|
|
654
|
-
continue;
|
|
655
|
-
}
|
|
656
|
-
const b = extractBudget(raw);
|
|
657
|
-
if (b.max_budget == null) {
|
|
658
|
-
out[name] = null;
|
|
659
|
-
continue;
|
|
660
|
-
}
|
|
661
|
-
out[name] = {
|
|
662
|
-
name,
|
|
663
|
-
spend: b.spend,
|
|
664
|
-
max_budget: b.max_budget,
|
|
665
|
-
budget_duration: b.budget_duration,
|
|
666
|
-
budget_reset_at: b.budget_reset_at,
|
|
667
|
-
budget_id: b.budget_id
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
return out;
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
// src/exulu/litellm/activity-client.ts
|
|
674
|
-
var SANITIZE_MAX_LEN = 63;
|
|
675
|
-
function sanitizeTagPrefix(raw) {
|
|
676
|
-
return String(raw).normalize("NFKC").toLowerCase().replace(/[^a-z0-9_-]/g, "-").slice(0, SANITIZE_MAX_LEN);
|
|
677
|
-
}
|
|
678
|
-
var TAG_LIST_TTL_MS = 3e4;
|
|
679
|
-
var tagListCache = null;
|
|
680
|
-
async function getCachedTagList() {
|
|
681
|
-
const now = Date.now();
|
|
682
|
-
if (tagListCache && now - tagListCache.fetchedAt < TAG_LIST_TTL_MS) {
|
|
683
|
-
return tagListCache.tags;
|
|
684
|
-
}
|
|
685
|
-
const tags = await listTags();
|
|
686
|
-
tagListCache = { fetchedAt: now, tags };
|
|
687
|
-
return tags;
|
|
688
|
-
}
|
|
689
|
-
async function getTagDailyActivity(params) {
|
|
690
|
-
const { url, masterKey } = litellmBase();
|
|
691
|
-
const qs = new URLSearchParams();
|
|
692
|
-
qs.set("start_date", params.startDate);
|
|
693
|
-
qs.set("end_date", params.endDate);
|
|
694
|
-
if (params.tags && params.tags.length > 0) {
|
|
695
|
-
qs.set("tags", params.tags.join(","));
|
|
696
|
-
}
|
|
697
|
-
if (params.model) qs.set("model", params.model);
|
|
698
|
-
if (params.page != null) qs.set("page", String(params.page));
|
|
699
|
-
if (params.pageSize != null) qs.set("page_size", String(params.pageSize));
|
|
700
|
-
if (params.excludeTeamTags != null) {
|
|
701
|
-
qs.set("exclude_team_tags", params.excludeTeamTags ? "true" : "false");
|
|
702
|
-
}
|
|
703
|
-
const res = await fetch(`${url}/tag/daily/activity?${qs.toString()}`, {
|
|
704
|
-
method: "GET",
|
|
705
|
-
headers: { Authorization: `Bearer ${masterKey}` }
|
|
706
|
-
});
|
|
707
|
-
if (!res.ok) {
|
|
708
|
-
const text = await res.text().catch(() => "");
|
|
709
|
-
throw new LiteLLMAdminError(
|
|
710
|
-
`LiteLLM /tag/daily/activity returned ${res.status}: ${text}`,
|
|
711
|
-
res.status
|
|
712
|
-
);
|
|
713
|
-
}
|
|
714
|
-
return await res.json().catch(() => ({}));
|
|
715
|
-
}
|
|
716
|
-
async function getTagSpendByWindow(windows, endDate) {
|
|
717
|
-
const windowEntries = Object.entries(windows);
|
|
718
|
-
const out = {};
|
|
719
|
-
for (const [tag] of windowEntries) out[tag] = 0;
|
|
720
|
-
if (windowEntries.length === 0) return out;
|
|
721
|
-
let startDate = windowEntries[0][1];
|
|
722
|
-
for (const [, start] of windowEntries) {
|
|
723
|
-
if (start < startDate) startDate = start;
|
|
724
|
-
}
|
|
725
|
-
const tags = windowEntries.map(([tag]) => tag);
|
|
726
|
-
const MAX_PAGES = 50;
|
|
727
|
-
const PAGE_SIZE = 1e3;
|
|
728
|
-
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
729
|
-
const json = await getTagDailyActivity({
|
|
730
|
-
startDate,
|
|
731
|
-
endDate,
|
|
732
|
-
tags,
|
|
733
|
-
page,
|
|
734
|
-
pageSize: PAGE_SIZE
|
|
735
|
-
});
|
|
736
|
-
const results = Array.isArray(json?.results) ? json.results : [];
|
|
737
|
-
for (const row of results) {
|
|
738
|
-
const date = typeof row?.date === "string" ? row.date : null;
|
|
739
|
-
if (!date) continue;
|
|
740
|
-
const entities = row?.breakdown?.entities;
|
|
741
|
-
if (!entities || typeof entities !== "object") continue;
|
|
742
|
-
for (const [tag, windowStart] of windowEntries) {
|
|
743
|
-
if (date < windowStart) continue;
|
|
744
|
-
const ed = entities[tag];
|
|
745
|
-
if (!ed) continue;
|
|
746
|
-
const m = ed?.metrics ?? ed;
|
|
747
|
-
const raw = m?.spend;
|
|
748
|
-
const spend = typeof raw === "number" ? raw : Number(raw);
|
|
749
|
-
if (Number.isFinite(spend)) out[tag] = (out[tag] ?? 0) + spend;
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
const meta = json?.metadata ?? {};
|
|
753
|
-
const totalPages = Number(meta?.total_pages ?? json?.total_pages ?? 0);
|
|
754
|
-
const hasMore = Boolean(meta?.has_more ?? json?.has_more ?? false);
|
|
755
|
-
if (results.length === 0) break;
|
|
756
|
-
if (totalPages ? page >= totalPages : !hasMore) break;
|
|
757
|
-
}
|
|
758
|
-
return out;
|
|
759
|
-
}
|
|
760
|
-
async function listTagsByPrefix(prefix) {
|
|
761
|
-
const sanitised = sanitizeTagPrefix(prefix);
|
|
762
|
-
if (!sanitised) return { sanitisedPrefix: "", names: [] };
|
|
763
|
-
const all = await getCachedTagList();
|
|
764
|
-
const names = [];
|
|
765
|
-
for (const e of all) {
|
|
766
|
-
const name = e?.name ?? e?.tag_name;
|
|
767
|
-
if (typeof name !== "string") continue;
|
|
768
|
-
if (name.startsWith(sanitised)) names.push(name);
|
|
769
|
-
}
|
|
770
|
-
return { sanitisedPrefix: sanitised, names };
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
// src/exulu/litellm/budget-service.ts
|
|
774
|
-
var SETTINGS_KEY = "budget_settings";
|
|
775
|
-
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
776
|
-
function ymd(d) {
|
|
777
|
-
return d.toISOString().slice(0, 10);
|
|
778
|
-
}
|
|
779
|
-
function durationToDays(duration) {
|
|
780
|
-
if (!duration) return 30;
|
|
781
|
-
const m = /^\s*(\d+(?:\.\d+)?)\s*(mo|[a-z]+)?\s*$/i.exec(String(duration));
|
|
782
|
-
if (!m) return 30;
|
|
783
|
-
const n = parseFloat(m[1]);
|
|
784
|
-
if (!Number.isFinite(n) || n <= 0) return 30;
|
|
785
|
-
switch ((m[2] ?? "d").toLowerCase()) {
|
|
786
|
-
case "h":
|
|
787
|
-
return n / 24;
|
|
788
|
-
case "w":
|
|
789
|
-
return n * 7;
|
|
790
|
-
case "mo":
|
|
791
|
-
return n * 30;
|
|
792
|
-
case "y":
|
|
793
|
-
return n * 365;
|
|
794
|
-
default:
|
|
795
|
-
return n;
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
function subtractDuration(date, duration) {
|
|
799
|
-
const m = /^\s*(\d+(?:\.\d+)?)\s*(mo|[a-z]+)?\s*$/i.exec(String(duration ?? ""));
|
|
800
|
-
const unit = m ? (m[2] ?? "d").toLowerCase() : "d";
|
|
801
|
-
const n = m ? parseFloat(m[1]) : NaN;
|
|
802
|
-
if (unit === "mo" && Number.isFinite(n) && n > 0) {
|
|
803
|
-
const result = new Date(date);
|
|
804
|
-
result.setUTCMonth(result.getUTCMonth() - Math.round(n));
|
|
805
|
-
return result;
|
|
806
|
-
}
|
|
807
|
-
return new Date(date.getTime() - durationToDays(duration) * DAY_MS);
|
|
808
|
-
}
|
|
809
|
-
function subtractOneCalendarMonth(date) {
|
|
810
|
-
const result = new Date(date);
|
|
811
|
-
result.setUTCMonth(result.getUTCMonth() - 1);
|
|
812
|
-
return result;
|
|
813
|
-
}
|
|
814
|
-
function windowStartYmd(reset_at, duration) {
|
|
815
|
-
const now = Date.now();
|
|
816
|
-
const reset = reset_at ? new Date(reset_at) : null;
|
|
817
|
-
const resetMs = reset && !Number.isNaN(reset.getTime()) ? reset.getTime() : null;
|
|
818
|
-
const trailingStart = subtractDuration(new Date(now), duration);
|
|
819
|
-
if (resetMs !== null) {
|
|
820
|
-
if (resetMs > now) {
|
|
821
|
-
const periodStart = reset.getUTCDate() === 1 ? subtractOneCalendarMonth(reset) : subtractDuration(reset, duration);
|
|
822
|
-
return ymd(periodStart > trailingStart ? periodStart : trailingStart);
|
|
823
|
-
} else {
|
|
824
|
-
return ymd(reset > trailingStart ? reset : trailingStart);
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
return ymd(trailingStart);
|
|
828
|
-
}
|
|
829
|
-
async function enrichSpendFromActivity(map) {
|
|
830
|
-
const names = Object.keys(map);
|
|
831
|
-
if (names.length === 0) return;
|
|
832
|
-
const windows = {};
|
|
833
|
-
for (const name of names) {
|
|
834
|
-
const ti = map[name];
|
|
835
|
-
windows[name] = windowStartYmd(ti.budget_reset_at, ti.budget_duration);
|
|
836
|
-
}
|
|
837
|
-
try {
|
|
838
|
-
const spendByTag = await getTagSpendByWindow(
|
|
839
|
-
windows,
|
|
840
|
-
ymd(new Date(Date.now() + DAY_MS))
|
|
841
|
-
);
|
|
842
|
-
for (const name of names) {
|
|
843
|
-
const spend = spendByTag[name];
|
|
844
|
-
if (typeof spend === "number" && Number.isFinite(spend)) {
|
|
845
|
-
map[name].spend = spend;
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
} catch (err3) {
|
|
849
|
-
console.warn("[EXULU] enrichSpendFromActivity failed", err3);
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
var DEFAULT_SETTINGS = {
|
|
853
|
-
global_user_budget: { enabled: false, max_budget: 0, budget_duration: "30d" },
|
|
854
|
-
show_user_budget_in_chat: false,
|
|
855
|
-
user_budget_display: "amount"
|
|
856
|
-
};
|
|
857
|
-
function isEnabled() {
|
|
858
|
-
return process.env.EXULU_USE_LITELLM === "true" && !!process.env.LITELLM_MASTER_KEY;
|
|
859
|
-
}
|
|
860
|
-
async function getBudgetSettings() {
|
|
861
|
-
const { db: db2 } = await postgresClient();
|
|
862
|
-
const row = await db2.from("platform_configurations").where({ config_key: SETTINGS_KEY }).first();
|
|
863
|
-
if (!row?.config_value) return { ...DEFAULT_SETTINGS };
|
|
864
|
-
const parsed = typeof row.config_value === "string" ? (() => {
|
|
865
|
-
try {
|
|
866
|
-
return JSON.parse(row.config_value);
|
|
867
|
-
} catch {
|
|
868
|
-
return {};
|
|
869
|
-
}
|
|
870
|
-
})() : row.config_value;
|
|
871
|
-
return {
|
|
872
|
-
global_user_budget: {
|
|
873
|
-
...DEFAULT_SETTINGS.global_user_budget,
|
|
874
|
-
...parsed?.global_user_budget ?? {}
|
|
875
|
-
},
|
|
876
|
-
show_user_budget_in_chat: parsed?.show_user_budget_in_chat ?? DEFAULT_SETTINGS.show_user_budget_in_chat,
|
|
877
|
-
user_budget_display: parsed?.user_budget_display === "percent" ? "percent" : "amount"
|
|
878
|
-
};
|
|
879
|
-
}
|
|
880
|
-
async function setBudgetSettings(settings) {
|
|
881
|
-
const { db: db2 } = await postgresClient();
|
|
882
|
-
await db2.from("platform_configurations").insert({
|
|
883
|
-
config_key: SETTINGS_KEY,
|
|
884
|
-
config_value: JSON.stringify(settings),
|
|
885
|
-
description: "Tag-based budget settings (global per-user default + show-in-chat)"
|
|
886
|
-
}).onConflict("config_key").merge({ config_value: JSON.stringify(settings) });
|
|
887
|
-
return settings;
|
|
888
|
-
}
|
|
889
|
-
function parseResetAt(raw) {
|
|
890
|
-
if (raw === void 0 || raw === null || raw === "") {
|
|
891
|
-
return { valid: true, value: void 0 };
|
|
892
|
-
}
|
|
893
|
-
if (typeof raw !== "string") return { valid: false };
|
|
894
|
-
const t = Date.parse(raw);
|
|
895
|
-
if (Number.isNaN(t)) return { valid: false };
|
|
896
|
-
return { valid: true, value: new Date(t).toISOString() };
|
|
897
|
-
}
|
|
898
|
-
async function upsertBudget(tag, max_budget, budget_duration, budget_reset_at) {
|
|
899
|
-
const info = await tagInfo([tag]);
|
|
900
|
-
try {
|
|
901
|
-
if (info[tag]) {
|
|
902
|
-
await tagUpdate({ name: tag, max_budget, budget_duration });
|
|
903
|
-
} else {
|
|
904
|
-
await tagNew({ name: tag, max_budget, budget_duration });
|
|
905
|
-
}
|
|
906
|
-
} catch {
|
|
907
|
-
if (info[tag]) {
|
|
908
|
-
await tagNew({ name: tag, max_budget, budget_duration });
|
|
909
|
-
} else {
|
|
910
|
-
await tagUpdate({ name: tag, max_budget, budget_duration });
|
|
911
|
-
}
|
|
912
|
-
}
|
|
913
|
-
if (budget_reset_at) {
|
|
914
|
-
const after = await tagInfo([tag]);
|
|
915
|
-
const budgetId = after[tag]?.budget_id ?? null;
|
|
916
|
-
if (budgetId) {
|
|
917
|
-
await budgetUpdate(budgetId, { budget_reset_at });
|
|
918
|
-
} else {
|
|
919
|
-
console.warn(`[EXULU] upsertBudget: no budget_id for ${tag}; reset date not applied`);
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
invalidateBudgetCaches(tag);
|
|
923
|
-
}
|
|
924
|
-
function invalidateBudgetCaches(tag) {
|
|
925
|
-
provisionCache.delete(tag);
|
|
926
|
-
readCache.delete(tag);
|
|
927
|
-
tagMapCache = void 0;
|
|
928
|
-
tagMapInflight = void 0;
|
|
929
|
-
}
|
|
930
|
-
var TAG_MAP_TTL_MS = 30 * 1e3;
|
|
931
|
-
var tagMapCache;
|
|
932
|
-
var tagMapInflight;
|
|
933
|
-
async function getTagBudgetMap() {
|
|
934
|
-
if (!process.env.LITELLM_MASTER_KEY) return {};
|
|
935
|
-
if (tagMapCache && tagMapCache.expiry > Date.now()) return tagMapCache.map;
|
|
936
|
-
if (tagMapInflight) return tagMapInflight;
|
|
937
|
-
tagMapInflight = (async () => {
|
|
938
|
-
try {
|
|
939
|
-
const map = await listTagBudgets();
|
|
940
|
-
await enrichSpendFromActivity(map);
|
|
941
|
-
tagMapCache = { expiry: Date.now() + TAG_MAP_TTL_MS, map };
|
|
942
|
-
return map;
|
|
943
|
-
} catch (err3) {
|
|
944
|
-
console.warn("[EXULU] getTagBudgetMap failed", err3);
|
|
945
|
-
return {};
|
|
946
|
-
} finally {
|
|
947
|
-
tagMapInflight = void 0;
|
|
948
|
-
}
|
|
949
|
-
})();
|
|
950
|
-
return tagMapInflight;
|
|
951
|
-
}
|
|
952
|
-
var PROVISION_TTL_MS = 60 * 60 * 1e3;
|
|
953
|
-
var provisionCache = /* @__PURE__ */ new Map();
|
|
954
|
-
async function provisionDefaultUserBudget(userId) {
|
|
955
|
-
try {
|
|
956
|
-
if (!isEnabled()) return;
|
|
957
|
-
const tag = budgetTagFor("user", userId);
|
|
958
|
-
if (!tag) return;
|
|
959
|
-
const cached = provisionCache.get(tag);
|
|
960
|
-
if (cached && cached > Date.now()) return;
|
|
961
|
-
const { global_user_budget: g } = await getBudgetSettings();
|
|
962
|
-
if (!g.enabled || !(g.max_budget > 0)) {
|
|
963
|
-
provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
|
|
964
|
-
return;
|
|
965
|
-
}
|
|
966
|
-
const info = await tagInfo([tag]);
|
|
967
|
-
if (info[tag]?.max_budget != null) {
|
|
968
|
-
provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
|
|
969
|
-
return;
|
|
970
|
-
}
|
|
971
|
-
await tagNew({
|
|
972
|
-
name: tag,
|
|
973
|
-
max_budget: g.max_budget,
|
|
974
|
-
budget_duration: g.budget_duration
|
|
975
|
-
});
|
|
976
|
-
provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
|
|
977
|
-
} catch (err3) {
|
|
978
|
-
console.warn("[EXULU] ensureUserBudget failed", err3);
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
var READ_TTL_MS = 30 * 1e3;
|
|
982
|
-
var readCache = /* @__PURE__ */ new Map();
|
|
983
|
-
async function getUserBudgetView(userId) {
|
|
984
|
-
try {
|
|
985
|
-
if (!isEnabled()) return null;
|
|
986
|
-
const tag = budgetTagFor("user", userId);
|
|
987
|
-
if (!tag) return null;
|
|
988
|
-
const cached = readCache.get(tag);
|
|
989
|
-
if (cached && cached.expiry > Date.now()) return cached.view;
|
|
990
|
-
const settings = await getBudgetSettings();
|
|
991
|
-
if (!settings.show_user_budget_in_chat) {
|
|
992
|
-
readCache.set(tag, { expiry: Date.now() + READ_TTL_MS, view: null });
|
|
993
|
-
return null;
|
|
994
|
-
}
|
|
995
|
-
await provisionDefaultUserBudget(userId);
|
|
996
|
-
const info = await tagInfo([tag]);
|
|
997
|
-
const ti = info[tag];
|
|
998
|
-
if (ti?.max_budget != null) {
|
|
999
|
-
await enrichSpendFromActivity({ [tag]: ti });
|
|
1000
|
-
}
|
|
1001
|
-
const view = ti?.max_budget != null ? {
|
|
1002
|
-
spend: ti.spend,
|
|
1003
|
-
max_budget: ti.max_budget,
|
|
1004
|
-
budget_duration: ti.budget_duration,
|
|
1005
|
-
budget_reset_at: ti.budget_reset_at,
|
|
1006
|
-
display: settings.user_budget_display
|
|
1007
|
-
} : null;
|
|
1008
|
-
readCache.set(tag, { expiry: Date.now() + READ_TTL_MS, view });
|
|
1009
|
-
return view;
|
|
1010
|
-
} catch (err3) {
|
|
1011
|
-
console.warn("[EXULU] getUserBudgetView failed", err3);
|
|
1012
|
-
return null;
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
|
|
1016
|
-
// src/exulu/resolve-model.ts
|
|
1017
|
-
var ResolveModelError = class extends Error {
|
|
1018
|
-
constructor(code, message) {
|
|
1019
|
-
super(message);
|
|
1020
|
-
this.code = code;
|
|
1021
|
-
this.name = "ResolveModelError";
|
|
1022
|
-
}
|
|
1023
|
-
};
|
|
1024
|
-
var getLiteLLMProvider = ({
|
|
1025
|
-
user,
|
|
1026
|
-
role,
|
|
1027
|
-
project,
|
|
1028
|
-
agent,
|
|
1029
|
-
team,
|
|
1030
|
-
routine
|
|
1031
|
-
}) => {
|
|
1032
|
-
const { baseUrl, authHeaders } = resolveLiteLLMTarget();
|
|
1033
|
-
const tags = buildTags({
|
|
1034
|
-
user_id: user?.id,
|
|
1035
|
-
role_id: role?.id,
|
|
1036
|
-
project_id: project?.id,
|
|
1037
|
-
agent_id: agent?.id,
|
|
1038
|
-
user_name: !user ? void 0 : user.type === "api" ? user.firstname ?? user.email : user.email,
|
|
1039
|
-
role_name: role?.name,
|
|
1040
|
-
project_name: project?.name,
|
|
1041
|
-
agent_name: agent?.name,
|
|
1042
|
-
team_id: team?.id,
|
|
1043
|
-
team_name: team?.name,
|
|
1044
|
-
routine_id: routine?.id,
|
|
1045
|
-
routine_name: routine?.name
|
|
1046
|
-
});
|
|
1047
|
-
return createOpenAICompatible({
|
|
1048
|
-
name: "litellm",
|
|
1049
|
-
baseURL: `${baseUrl}/v1`,
|
|
1050
|
-
// createOpenAICompatible requires a non-empty apiKey; real auth for remote mode is the
|
|
1051
|
-
// exulu-api-key header (added via `headers`). The passthrough strips/ignores Authorization.
|
|
1052
|
-
apiKey: process.env.LITELLM_MASTER_KEY ?? process.env.EXULU_API_KEY ?? "x",
|
|
1053
|
-
headers: authHeaders,
|
|
1054
|
-
fetch: createTaggedFetch(tags),
|
|
1055
|
-
// Without this flag the openai-compatible provider strips any
|
|
1056
|
-
// responseFormat.schema before sending and warns
|
|
1057
|
-
// "JSON response format schema is only supported with structuredOutputs".
|
|
1058
|
-
// Models then return free-form JSON that fails Zod parsing in callers
|
|
1059
|
-
// using `Output.object({ schema })`. LiteLLM forwards
|
|
1060
|
-
// `response_format: { type: "json_schema", ... }` to every upstream it
|
|
1061
|
-
// supports — including Vertex Gemini, which translates it into
|
|
1062
|
-
// responseSchema/responseMimeType — so enabling this matches the actual
|
|
1063
|
-
// proxy contract.
|
|
1064
|
-
supportsStructuredOutputs: true,
|
|
1065
|
-
// Request token usage on STREAMED responses. Without this the openai-compatible
|
|
1066
|
-
// provider omits `stream_options: { include_usage: true }`, so LiteLLM returns no
|
|
1067
|
-
// usage for streaming calls — which zeroes out the per-request token metrics and
|
|
1068
|
-
// the message-footer token count (both read the AI SDK `totalUsage`/finish-part usage).
|
|
1069
|
-
includeUsage: true
|
|
1070
|
-
});
|
|
1071
|
-
};
|
|
1072
|
-
async function resolveModel(input) {
|
|
1073
|
-
const { modelId, user, agent, project, routine } = input;
|
|
1074
|
-
if (!isLiteLLMEnabled()) {
|
|
1075
|
-
throw new Error("Litellm not configured or available.");
|
|
1076
|
-
}
|
|
1077
|
-
try {
|
|
1078
|
-
await waitForLiteLLMReady();
|
|
1079
|
-
} catch (err3) {
|
|
1080
|
-
throw new ResolveModelError(
|
|
1081
|
-
"LITELLM_NOT_READY",
|
|
1082
|
-
`LiteLLM is not ready: ${err3.message}`
|
|
1083
|
-
);
|
|
1084
|
-
}
|
|
1085
|
-
if (user?.id) await provisionDefaultUserBudget(user.id);
|
|
1086
|
-
const litellm = getLiteLLMProvider({
|
|
1087
|
-
user,
|
|
1088
|
-
role: user?.role,
|
|
1089
|
-
// Fall back to the caller's own project (set on API keys) when no
|
|
1090
|
-
// explicit request project is supplied, so API-triggered requests are
|
|
1091
|
-
// attributed to the key's project.
|
|
1092
|
-
project: project ?? user?.project,
|
|
1093
|
-
agent,
|
|
1094
|
-
team: user?.team,
|
|
1095
|
-
routine
|
|
1096
|
-
});
|
|
1097
|
-
const languageModel = litellm(modelId);
|
|
1098
|
-
const syntheticModel = {
|
|
1099
|
-
id: modelId,
|
|
1100
|
-
name: modelId,
|
|
1101
|
-
provider: modelId,
|
|
1102
|
-
active: true,
|
|
1103
|
-
rights_mode: "public",
|
|
1104
|
-
created_by: "litellm"
|
|
1105
|
-
};
|
|
1106
|
-
return {
|
|
1107
|
-
languageModel,
|
|
1108
|
-
model: syntheticModel
|
|
1109
|
-
};
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
48
|
// src/exulu/auth/validate.ts
|
|
1113
49
|
var OAUTH_REQUIRED_STRING_FIELDS = [
|
|
1114
50
|
"authorizationUrl",
|
|
@@ -1264,8 +200,8 @@ var TABLE = "user_credentials";
|
|
|
1264
200
|
var encrypt = (value) => CryptoJS.AES.encrypt(value, process.env.NEXTAUTH_SECRET).toString();
|
|
1265
201
|
var decrypt = (value) => CryptoJS.AES.decrypt(value, process.env.NEXTAUTH_SECRET).toString(CryptoJS.enc.Utf8);
|
|
1266
202
|
async function get(provider, userId) {
|
|
1267
|
-
const { db
|
|
1268
|
-
const row = await
|
|
203
|
+
const { db } = await postgresClient();
|
|
204
|
+
const row = await db.from(TABLE).where({ provider, user_id: String(userId) }).first();
|
|
1269
205
|
if (!row) {
|
|
1270
206
|
return null;
|
|
1271
207
|
}
|
|
@@ -1277,9 +213,9 @@ async function get(provider, userId) {
|
|
|
1277
213
|
};
|
|
1278
214
|
}
|
|
1279
215
|
async function upsert(record) {
|
|
1280
|
-
const { db
|
|
216
|
+
const { db } = await postgresClient();
|
|
1281
217
|
const encrypted = encrypt(JSON.stringify(record.data));
|
|
1282
|
-
await
|
|
218
|
+
await db.from(TABLE).insert({
|
|
1283
219
|
provider: record.provider,
|
|
1284
220
|
user_id: String(record.userId),
|
|
1285
221
|
auth_type: record.authType,
|
|
@@ -1288,8 +224,8 @@ async function upsert(record) {
|
|
|
1288
224
|
}).onConflict(["provider", "user_id"]).merge({ auth_type: record.authType, data: encrypted, updated_at: /* @__PURE__ */ new Date() });
|
|
1289
225
|
}
|
|
1290
226
|
async function listByUser(userId) {
|
|
1291
|
-
const { db
|
|
1292
|
-
const list = await
|
|
227
|
+
const { db } = await postgresClient();
|
|
228
|
+
const list = await db.from(TABLE).where({ user_id: String(userId) }).orderBy("provider");
|
|
1293
229
|
return list.map((row) => ({
|
|
1294
230
|
provider: row.provider,
|
|
1295
231
|
authType: row.auth_type,
|
|
@@ -1298,8 +234,8 @@ async function listByUser(userId) {
|
|
|
1298
234
|
}));
|
|
1299
235
|
}
|
|
1300
236
|
async function del(provider, userId) {
|
|
1301
|
-
const { db
|
|
1302
|
-
await
|
|
237
|
+
const { db } = await postgresClient();
|
|
238
|
+
await db.from(TABLE).where({ provider, user_id: String(userId) }).del();
|
|
1303
239
|
}
|
|
1304
240
|
var credentialStore = { get, upsert, listByUser, delete: del };
|
|
1305
241
|
|
|
@@ -1723,7 +659,7 @@ var ExuluTool = class _ExuluTool {
|
|
|
1723
659
|
if (!agent) {
|
|
1724
660
|
throw new Error("Agent not found.");
|
|
1725
661
|
}
|
|
1726
|
-
const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-
|
|
662
|
+
const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-3UCQOIY6.js");
|
|
1727
663
|
const tools = await convertExuluToolsToAiSdkTools2(
|
|
1728
664
|
[this],
|
|
1729
665
|
[],
|
|
@@ -1772,8 +708,8 @@ var ExuluTool = class _ExuluTool {
|
|
|
1772
708
|
// src/exulu/statistics.ts
|
|
1773
709
|
var updateStatistic = async (statistic) => {
|
|
1774
710
|
const currentDate = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1775
|
-
const { db
|
|
1776
|
-
const existing = await
|
|
711
|
+
const { db } = await postgresClient();
|
|
712
|
+
const existing = await db.from("tracking").where({
|
|
1777
713
|
...statistic.user ? { user: statistic.user } : {},
|
|
1778
714
|
...statistic.role ? { role: statistic.role } : {},
|
|
1779
715
|
...statistic.project ? { project: statistic.project } : {},
|
|
@@ -1783,7 +719,7 @@ var updateStatistic = async (statistic) => {
|
|
|
1783
719
|
createdAt: currentDate
|
|
1784
720
|
}).first();
|
|
1785
721
|
if (!existing) {
|
|
1786
|
-
await
|
|
722
|
+
await db.from("tracking").insert({
|
|
1787
723
|
name: statistic.name,
|
|
1788
724
|
label: statistic.label,
|
|
1789
725
|
type: statistic.type,
|
|
@@ -1794,8 +730,8 @@ var updateStatistic = async (statistic) => {
|
|
|
1794
730
|
...statistic.project ? { project: statistic.project } : {}
|
|
1795
731
|
});
|
|
1796
732
|
} else {
|
|
1797
|
-
await
|
|
1798
|
-
total:
|
|
733
|
+
await db.from("tracking").update({
|
|
734
|
+
total: db.raw("total + ?", [statistic.count ?? 1])
|
|
1799
735
|
}).where({
|
|
1800
736
|
id: existing.id
|
|
1801
737
|
});
|
|
@@ -1912,44 +848,6 @@ var createSessionItemsRetrievalTool = async ({
|
|
|
1912
848
|
// ee/agentic-retrieval/pipeline/index.ts
|
|
1913
849
|
import { z as z7 } from "zod";
|
|
1914
850
|
|
|
1915
|
-
// ee/entitlements.ts
|
|
1916
|
-
var ENTITLEMENTS = {
|
|
1917
|
-
"rbac": false,
|
|
1918
|
-
"advanced-markdown-chunker": false,
|
|
1919
|
-
"agentic-retrieval": false,
|
|
1920
|
-
"queues": false,
|
|
1921
|
-
"custom-branding": false,
|
|
1922
|
-
"evals": false,
|
|
1923
|
-
"template-conversations": false,
|
|
1924
|
-
"agent-feedback": false,
|
|
1925
|
-
"multi-agent-tooling": false,
|
|
1926
|
-
"advanced-document-processing": false,
|
|
1927
|
-
"rate-limits": false,
|
|
1928
|
-
"claim-check": false
|
|
1929
|
-
};
|
|
1930
|
-
var checkLicense = () => {
|
|
1931
|
-
if (!process.env.EXULU_ENTERPRISE_LICENSE || process.env.EXULU_ENTERPRISE_LICENSE === "" || !process.env.EXULU_ENTERPRISE_LICENSE.startsWith("EXULU_EE_")) {
|
|
1932
|
-
return ENTITLEMENTS;
|
|
1933
|
-
} else {
|
|
1934
|
-
return {
|
|
1935
|
-
"rbac": true,
|
|
1936
|
-
"advanced-markdown-chunker": true,
|
|
1937
|
-
"agentic-retrieval": true,
|
|
1938
|
-
"mcp": true,
|
|
1939
|
-
"queues": true,
|
|
1940
|
-
"prompt-library": true,
|
|
1941
|
-
"custom-branding": true,
|
|
1942
|
-
"evals": true,
|
|
1943
|
-
"template-conversations": true,
|
|
1944
|
-
"agent-feedback": true,
|
|
1945
|
-
"multi-agent-tooling": true,
|
|
1946
|
-
"advanced-document-processing": true,
|
|
1947
|
-
"rate-limits": true,
|
|
1948
|
-
"claim-check": true
|
|
1949
|
-
};
|
|
1950
|
-
}
|
|
1951
|
-
};
|
|
1952
|
-
|
|
1953
851
|
// src/exulu/resolve-reranker.ts
|
|
1954
852
|
var ResolveRerankerError = class extends Error {
|
|
1955
853
|
constructor(code, message) {
|
|
@@ -2298,27 +1196,6 @@ import { z as z5 } from "zod";
|
|
|
2298
1196
|
|
|
2299
1197
|
// ee/agentic-retrieval/pipeline/micro-call.ts
|
|
2300
1198
|
import { generateText, NoOutputGeneratedError, Output } from "ai";
|
|
2301
|
-
|
|
2302
|
-
// src/utils/with-retry.ts
|
|
2303
|
-
async function withRetry(generateFn, maxRetries = 3, opts = {}) {
|
|
2304
|
-
const { shouldRetry, baseDelayMs = 1e3 } = opts;
|
|
2305
|
-
let lastError;
|
|
2306
|
-
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
2307
|
-
try {
|
|
2308
|
-
return await generateFn();
|
|
2309
|
-
} catch (error) {
|
|
2310
|
-
lastError = error;
|
|
2311
|
-
console.error(`[EXULU] generateText attempt ${attempt} failed:`, error);
|
|
2312
|
-
if (attempt === maxRetries || shouldRetry && !shouldRetry(error)) {
|
|
2313
|
-
throw error;
|
|
2314
|
-
}
|
|
2315
|
-
await new Promise((resolve4) => setTimeout(resolve4, Math.pow(2, attempt) * baseDelayMs));
|
|
2316
|
-
}
|
|
2317
|
-
}
|
|
2318
|
-
throw lastError;
|
|
2319
|
-
}
|
|
2320
|
-
|
|
2321
|
-
// ee/agentic-retrieval/pipeline/micro-call.ts
|
|
2322
1199
|
var MICRO_CALL_MAX_OUTPUT_TOKENS = 2e3;
|
|
2323
1200
|
function microCallProviderOptions(model) {
|
|
2324
1201
|
const modelId = typeof model === "string" ? model : model?.modelId;
|
|
@@ -3924,12 +2801,12 @@ function makeNearDuplicateFinder(opts) {
|
|
|
3924
2801
|
const work = [...byContext.entries()].filter(([, ids]) => ids.length > 1);
|
|
3925
2802
|
if (work.length === 0) return [];
|
|
3926
2803
|
try {
|
|
3927
|
-
const
|
|
2804
|
+
const db = opts.db ?? (await postgresClient()).db;
|
|
3928
2805
|
const results = await Promise.all(
|
|
3929
2806
|
work.map(async ([ctxId, ids]) => {
|
|
3930
2807
|
const table = getChunksTableName(ctxId);
|
|
3931
2808
|
try {
|
|
3932
|
-
const res = await
|
|
2809
|
+
const res = await db.raw(
|
|
3933
2810
|
`select a.id as a, b.id as b
|
|
3934
2811
|
from "${table}" a
|
|
3935
2812
|
join "${table}" b on a.id < b.id
|
|
@@ -4718,7 +3595,7 @@ var authentication = async ({
|
|
|
4718
3595
|
apikey,
|
|
4719
3596
|
authtoken,
|
|
4720
3597
|
internalkey,
|
|
4721
|
-
db
|
|
3598
|
+
db
|
|
4722
3599
|
}) => {
|
|
4723
3600
|
if (internalkey) {
|
|
4724
3601
|
if (!process.env.INTERNAL_SECRET) {
|
|
@@ -4765,21 +3642,21 @@ var authentication = async ({
|
|
|
4765
3642
|
code: 401
|
|
4766
3643
|
};
|
|
4767
3644
|
}
|
|
4768
|
-
const user = await
|
|
3645
|
+
const user = await db.from("users").select("*").whereRaw("LOWER(email) = LOWER(?)", [authtoken?.email]).first();
|
|
4769
3646
|
if (user?.role) {
|
|
4770
|
-
const role = await
|
|
3647
|
+
const role = await db.from("roles").select("*").where("id", user?.role).first();
|
|
4771
3648
|
if (role) {
|
|
4772
3649
|
user.role = role;
|
|
4773
3650
|
}
|
|
4774
3651
|
}
|
|
4775
3652
|
if (user?.team) {
|
|
4776
|
-
const team = await
|
|
3653
|
+
const team = await db.from("teams").select("*").where("id", user?.team).first();
|
|
4777
3654
|
if (team) {
|
|
4778
3655
|
user.team = team;
|
|
4779
3656
|
}
|
|
4780
3657
|
}
|
|
4781
3658
|
if (user?.project) {
|
|
4782
|
-
const project = await
|
|
3659
|
+
const project = await db.from("projects").select("*").where("id", user?.project).first();
|
|
4783
3660
|
if (project) {
|
|
4784
3661
|
user.project = project;
|
|
4785
3662
|
}
|
|
@@ -4806,7 +3683,7 @@ var authentication = async ({
|
|
|
4806
3683
|
}
|
|
4807
3684
|
}
|
|
4808
3685
|
if (apikey) {
|
|
4809
|
-
const users = await
|
|
3686
|
+
const users = await db.from("users").select("*").where("type", "api");
|
|
4810
3687
|
if (!users || users.length === 0) {
|
|
4811
3688
|
return {
|
|
4812
3689
|
error: true,
|
|
@@ -4840,23 +3717,23 @@ var authentication = async ({
|
|
|
4840
3717
|
const user_key_compare_value = user.apikey.substring(0, user_key_last_slash_index);
|
|
4841
3718
|
const isMatch = await bcrypt.compare(request_key_compare_value, user_key_compare_value);
|
|
4842
3719
|
if (isMatch) {
|
|
4843
|
-
await
|
|
3720
|
+
await db.from("users").where({ id: user.id }).update({
|
|
4844
3721
|
last_used: /* @__PURE__ */ new Date()
|
|
4845
3722
|
}).returning("id");
|
|
4846
3723
|
if (user?.role) {
|
|
4847
|
-
const role = await
|
|
3724
|
+
const role = await db.from("roles").select("*").where("id", user?.role).first();
|
|
4848
3725
|
if (role) {
|
|
4849
3726
|
user.role = role;
|
|
4850
3727
|
}
|
|
4851
3728
|
}
|
|
4852
3729
|
if (user?.team) {
|
|
4853
|
-
const team = await
|
|
3730
|
+
const team = await db.from("teams").select("*").where("id", user?.team).first();
|
|
4854
3731
|
if (team) {
|
|
4855
3732
|
user.team = team;
|
|
4856
3733
|
}
|
|
4857
3734
|
}
|
|
4858
3735
|
if (user?.project) {
|
|
4859
|
-
const project = await
|
|
3736
|
+
const project = await db.from("projects").select("*").where("id", user?.project).first();
|
|
4860
3737
|
if (project) {
|
|
4861
3738
|
user.project = project;
|
|
4862
3739
|
}
|
|
@@ -5034,7 +3911,7 @@ var uploadFile = async (file, fileName, config, options = {}, user, customBucket
|
|
|
5034
3911
|
if (error.name === "SignatureDoesNotMatch" || error.name === "InvalidAccessKeyId" || error.name === "AccessDenied") {
|
|
5035
3912
|
if (attempt < maxRetries) {
|
|
5036
3913
|
const backoffMs = Math.pow(2, attempt) * 1e3;
|
|
5037
|
-
await new Promise((
|
|
3914
|
+
await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
|
|
5038
3915
|
s3Client = void 0;
|
|
5039
3916
|
getS3Client(config);
|
|
5040
3917
|
continue;
|
|
@@ -5210,7 +4087,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5210
4087
|
}
|
|
5211
4088
|
const apikey = req.headers["exulu-api-key"] || null;
|
|
5212
4089
|
const internalkey = req.headers["internal-key"] || null;
|
|
5213
|
-
const { db
|
|
4090
|
+
const { db } = await postgresClient();
|
|
5214
4091
|
let authtoken = null;
|
|
5215
4092
|
if (typeof apikey !== "string" && typeof internalkey !== "string") {
|
|
5216
4093
|
authtoken = await getToken(req.headers.authorization ?? "");
|
|
@@ -5219,7 +4096,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5219
4096
|
authtoken,
|
|
5220
4097
|
apikey,
|
|
5221
4098
|
internalkey,
|
|
5222
|
-
db
|
|
4099
|
+
db
|
|
5223
4100
|
});
|
|
5224
4101
|
if (!authenticationResult.user?.id) {
|
|
5225
4102
|
res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
|
|
@@ -5251,7 +4128,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5251
4128
|
app.get("/s3/download", async (req, res, next) => {
|
|
5252
4129
|
const apikey = req.headers["exulu-api-key"] || null;
|
|
5253
4130
|
const internalkey = req.headers["internal-key"] || null;
|
|
5254
|
-
const { db
|
|
4131
|
+
const { db } = await postgresClient();
|
|
5255
4132
|
let authtoken = null;
|
|
5256
4133
|
if (typeof apikey !== "string" && typeof internalkey !== "string") {
|
|
5257
4134
|
authtoken = await getToken(req.headers.authorization ?? "");
|
|
@@ -5260,7 +4137,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5260
4137
|
authtoken,
|
|
5261
4138
|
apikey,
|
|
5262
4139
|
internalkey,
|
|
5263
|
-
db
|
|
4140
|
+
db
|
|
5264
4141
|
});
|
|
5265
4142
|
if (!authenticationResult.user?.id) {
|
|
5266
4143
|
res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
|
|
@@ -5309,7 +4186,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5309
4186
|
}
|
|
5310
4187
|
const apikey = req.headers["exulu-api-key"] || null;
|
|
5311
4188
|
const internalkey = req.headers["internal-key"] || null;
|
|
5312
|
-
const { db
|
|
4189
|
+
const { db } = await postgresClient();
|
|
5313
4190
|
let authtoken = null;
|
|
5314
4191
|
if (typeof apikey !== "string" && typeof internalkey !== "string") {
|
|
5315
4192
|
authtoken = await getToken(req.headers.authorization ?? "");
|
|
@@ -5318,7 +4195,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5318
4195
|
authtoken,
|
|
5319
4196
|
apikey,
|
|
5320
4197
|
internalkey,
|
|
5321
|
-
db
|
|
4198
|
+
db
|
|
5322
4199
|
});
|
|
5323
4200
|
if (!authenticationResult.user?.id) {
|
|
5324
4201
|
res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
|
|
@@ -5352,7 +4229,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5352
4229
|
}
|
|
5353
4230
|
const apikey = req.headers["exulu-api-key"] || null;
|
|
5354
4231
|
const internalkey = req.headers["internal-key"] || null;
|
|
5355
|
-
const { db
|
|
4232
|
+
const { db } = await postgresClient();
|
|
5356
4233
|
let authtoken = null;
|
|
5357
4234
|
if (typeof apikey !== "string" && typeof internalkey !== "string") {
|
|
5358
4235
|
authtoken = await getToken(req.headers.authorization ?? "");
|
|
@@ -5361,7 +4238,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5361
4238
|
authtoken,
|
|
5362
4239
|
apikey,
|
|
5363
4240
|
internalkey,
|
|
5364
|
-
db
|
|
4241
|
+
db
|
|
5365
4242
|
});
|
|
5366
4243
|
if (!authenticationResult.user?.id) {
|
|
5367
4244
|
res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
|
|
@@ -5469,7 +4346,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5469
4346
|
throw new Error("File uploads are not configured");
|
|
5470
4347
|
}
|
|
5471
4348
|
const apikey = req.headers["exulu-api-key"] || null;
|
|
5472
|
-
const { db
|
|
4349
|
+
const { db } = await postgresClient();
|
|
5473
4350
|
let authtoken = null;
|
|
5474
4351
|
if (typeof apikey !== "string") {
|
|
5475
4352
|
authtoken = await getToken(req.headers.authorization ?? "");
|
|
@@ -5477,7 +4354,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5477
4354
|
const authenticationResult = await authentication({
|
|
5478
4355
|
authtoken,
|
|
5479
4356
|
apikey,
|
|
5480
|
-
db
|
|
4357
|
+
db
|
|
5481
4358
|
});
|
|
5482
4359
|
if (!authenticationResult.user?.id) {
|
|
5483
4360
|
res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
|
|
@@ -5525,7 +4402,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5525
4402
|
throw new Error("File uploads are not configured");
|
|
5526
4403
|
}
|
|
5527
4404
|
const apikey = req.headers["exulu-api-key"] || null;
|
|
5528
|
-
const { db
|
|
4405
|
+
const { db } = await postgresClient();
|
|
5529
4406
|
let authtoken = null;
|
|
5530
4407
|
if (typeof apikey !== "string") {
|
|
5531
4408
|
authtoken = await getToken(req.headers.authorization ?? "");
|
|
@@ -5533,7 +4410,7 @@ var createUppyRoutes = async (app, config) => {
|
|
|
5533
4410
|
const authenticationResult = await authentication({
|
|
5534
4411
|
authtoken,
|
|
5535
4412
|
apikey,
|
|
5536
|
-
db
|
|
4413
|
+
db
|
|
5537
4414
|
});
|
|
5538
4415
|
if (!authenticationResult.user?.id) {
|
|
5539
4416
|
res.status(authenticationResult.code || 500).json({ detail: `${authenticationResult.message}` });
|
|
@@ -5769,7 +4646,7 @@ var ExuluStorage = class {
|
|
|
5769
4646
|
};
|
|
5770
4647
|
|
|
5771
4648
|
// src/exulu/context.ts
|
|
5772
|
-
import
|
|
4649
|
+
import pgvector from "pgvector/knex";
|
|
5773
4650
|
|
|
5774
4651
|
// ee/tokenizer.ts
|
|
5775
4652
|
import { Tiktoken } from "tiktoken/lite";
|
|
@@ -6459,8 +5336,8 @@ var defaultChunker = async (item, maxChunkSize) => {
|
|
|
6459
5336
|
};
|
|
6460
5337
|
|
|
6461
5338
|
// src/exulu/litellm/parse-embedding-models.ts
|
|
6462
|
-
import { existsSync
|
|
6463
|
-
import { resolve
|
|
5339
|
+
import { existsSync, readFileSync } from "fs";
|
|
5340
|
+
import { resolve } from "path";
|
|
6464
5341
|
var DEFAULT_MAX_CHUNK_SIZE = 1024;
|
|
6465
5342
|
var DEFAULT_MAX_BATCH_SIZE = 100;
|
|
6466
5343
|
var stripComment = (line) => {
|
|
@@ -6471,9 +5348,9 @@ var parseInt10 = (raw) => {
|
|
|
6471
5348
|
const n = Number(raw.trim());
|
|
6472
5349
|
return Number.isInteger(n) ? n : void 0;
|
|
6473
5350
|
};
|
|
6474
|
-
var resolveLiteLLMConfigPath = () => process.env.LITELLM_CONFIG_PATH ??
|
|
5351
|
+
var resolveLiteLLMConfigPath = () => process.env.LITELLM_CONFIG_PATH ?? resolve(process.cwd(), "./config.litellm.yaml");
|
|
6475
5352
|
var parseEmbeddingModels = (configPath) => {
|
|
6476
|
-
if (!
|
|
5353
|
+
if (!existsSync(configPath)) return [];
|
|
6477
5354
|
const text = readFileSync(configPath, "utf8");
|
|
6478
5355
|
const lines = text.split("\n");
|
|
6479
5356
|
const entries = [];
|
|
@@ -6961,24 +5838,24 @@ function readProjectionRow(row) {
|
|
|
6961
5838
|
if (width(candidate.intercept) !== 3) problems.push(`intercept ${width(candidate.intercept)} of 3`);
|
|
6962
5839
|
return problems.length > 0 ? { problem: problems.join(", ") } : { projection: candidate };
|
|
6963
5840
|
}
|
|
6964
|
-
async function dropProjection(
|
|
5841
|
+
async function dropProjection(db, contextId) {
|
|
6965
5842
|
try {
|
|
6966
5843
|
const context = sanitizeName(contextId);
|
|
6967
|
-
await
|
|
6968
|
-
await
|
|
5844
|
+
await db("context_projections").where({ context }).delete();
|
|
5845
|
+
await db("context_map_topics").where({ context }).delete();
|
|
6969
5846
|
} catch (e) {
|
|
6970
5847
|
console.error("[EXULU] could not delete the context projection or its topic rows", e instanceof Error ? e.message : String(e));
|
|
6971
5848
|
}
|
|
6972
5849
|
clearProjectionCache();
|
|
6973
5850
|
}
|
|
6974
|
-
async function loadProjection(
|
|
5851
|
+
async function loadProjection(db, contextId, now = Date.now()) {
|
|
6975
5852
|
let key;
|
|
6976
5853
|
let projection = null;
|
|
6977
5854
|
try {
|
|
6978
5855
|
key = sanitizeName(contextId);
|
|
6979
5856
|
const hit = cache.get(key);
|
|
6980
5857
|
if (hit && now - hit.loadedAt < PROJECTION_CACHE_TTL_MS) return hit.projection;
|
|
6981
|
-
const row = await
|
|
5858
|
+
const row = await db("context_projections").where({ context: key }).first();
|
|
6982
5859
|
if (!row) announceUnfitted(key, contextId, "never fitted");
|
|
6983
5860
|
else if (Number(row.version) !== PROJECTION_VERSION) {
|
|
6984
5861
|
announceUnfitted(key, contextId, `stored version ${String(row.version)}, this build reads ${PROJECTION_VERSION}`);
|
|
@@ -6994,13 +5871,13 @@ async function loadProjection(db2, contextId, now = Date.now()) {
|
|
|
6994
5871
|
return projection;
|
|
6995
5872
|
}
|
|
6996
5873
|
async function chunkCoordinates({
|
|
6997
|
-
db
|
|
5874
|
+
db,
|
|
6998
5875
|
contextId,
|
|
6999
5876
|
vectors
|
|
7000
5877
|
}) {
|
|
7001
5878
|
if (vectors.length === 0) return [];
|
|
7002
5879
|
try {
|
|
7003
|
-
const projection = await loadProjection(
|
|
5880
|
+
const projection = await loadProjection(db, contextId);
|
|
7004
5881
|
if (!projection) return vectors.map(() => null);
|
|
7005
5882
|
const mean = Float32Array.from(projection.mean);
|
|
7006
5883
|
const basis = projection.basis.map((b) => Float32Array.from(b));
|
|
@@ -7027,8 +5904,8 @@ async function chunkCoordinates({
|
|
|
7027
5904
|
var embedderKey = (contextId) => `context_embedder:${contextId}`;
|
|
7028
5905
|
var getEmbedderSetting = async (contextId) => {
|
|
7029
5906
|
try {
|
|
7030
|
-
const { db
|
|
7031
|
-
const row = await
|
|
5907
|
+
const { db } = await postgresClient();
|
|
5908
|
+
const row = await db.from("platform_configurations").where({ config_key: embedderKey(contextId) }).first();
|
|
7032
5909
|
if (!row?.config_value) return null;
|
|
7033
5910
|
const raw = row.config_value;
|
|
7034
5911
|
let value = raw;
|
|
@@ -7055,17 +5932,17 @@ var getEmbedderSetting = async (contextId) => {
|
|
|
7055
5932
|
}
|
|
7056
5933
|
};
|
|
7057
5934
|
var setEmbedderSetting = async (contextId, model, queue) => {
|
|
7058
|
-
const { db
|
|
5935
|
+
const { db } = await postgresClient();
|
|
7059
5936
|
const value = JSON.stringify({ model: model.trim(), queue: queue?.trim() || null });
|
|
7060
|
-
await
|
|
5937
|
+
await db.from("platform_configurations").insert({
|
|
7061
5938
|
config_key: embedderKey(contextId),
|
|
7062
5939
|
config_value: value,
|
|
7063
5940
|
description: `Embedding model for context ${contextId}`
|
|
7064
5941
|
}).onConflict("config_key").merge({ config_value: value });
|
|
7065
5942
|
};
|
|
7066
5943
|
var clearEmbedderSetting = async (contextId) => {
|
|
7067
|
-
const { db
|
|
7068
|
-
await
|
|
5944
|
+
const { db } = await postgresClient();
|
|
5945
|
+
await db.from("platform_configurations").where({ config_key: embedderKey(contextId) }).del();
|
|
7069
5946
|
};
|
|
7070
5947
|
var resolveContextEmbedder = async (context) => {
|
|
7071
5948
|
const stored = await getEmbedderSetting(context.id);
|
|
@@ -7101,8 +5978,8 @@ var captureCodeEmbedder = (context) => {
|
|
|
7101
5978
|
};
|
|
7102
5979
|
var codeEmbedderFor = (context) => codeEmbedders.has(context) ? codeEmbedders.get(context) : context.embedder;
|
|
7103
5980
|
var contextEmbedderInfoFor = async (context, deps = {}) => {
|
|
7104
|
-
const
|
|
7105
|
-
return
|
|
5981
|
+
const resolve3 = deps.resolve ?? resolveContextEmbedder;
|
|
5982
|
+
return resolve3({ id: context.id, embedder: codeEmbedderFor(context) });
|
|
7106
5983
|
};
|
|
7107
5984
|
var willEmbedOnQueue = async (context, overrideQueue) => {
|
|
7108
5985
|
if (overrideQueue) {
|
|
@@ -7111,11 +5988,11 @@ var willEmbedOnQueue = async (context, overrideQueue) => {
|
|
|
7111
5988
|
return Boolean(await codeEmbedderFor(context)?.queue);
|
|
7112
5989
|
};
|
|
7113
5990
|
var hydrateContextEmbedders = async (contexts, deps = {}) => {
|
|
7114
|
-
const { resolve:
|
|
5991
|
+
const { resolve: resolve3, modelInfo, queues } = { ...defaultDeps(), ...deps };
|
|
7115
5992
|
for (const context of contexts) {
|
|
7116
5993
|
try {
|
|
7117
5994
|
const codeEmbedder = captureCodeEmbedder(context);
|
|
7118
|
-
const info = await
|
|
5995
|
+
const info = await resolve3({ id: context.id, embedder: codeEmbedder });
|
|
7119
5996
|
if (info.source !== "database" || !info.databaseModel) {
|
|
7120
5997
|
context.embedder = codeEmbedder;
|
|
7121
5998
|
continue;
|
|
@@ -7575,8 +6452,8 @@ var hydrateEntityTypes = async (context) => {
|
|
|
7575
6452
|
byName.set(t.name.toLowerCase().trim(), { name: t.name, description: t.description || "" });
|
|
7576
6453
|
}
|
|
7577
6454
|
try {
|
|
7578
|
-
const { db
|
|
7579
|
-
const adminRows = await
|
|
6455
|
+
const { db } = await postgresClient();
|
|
6456
|
+
const adminRows = await db.from("entity_type_settings").where({ context: context.id, active: true });
|
|
7580
6457
|
for (const row of adminRows) {
|
|
7581
6458
|
if (!row?.name) continue;
|
|
7582
6459
|
byName.set(row.name.toLowerCase().trim(), {
|
|
@@ -7597,8 +6474,8 @@ var entitiesEnabled = async (context) => {
|
|
|
7597
6474
|
var upsertEntitySuggestions = async (context, suggestions) => {
|
|
7598
6475
|
if (!suggestions.length) return;
|
|
7599
6476
|
try {
|
|
7600
|
-
const { db
|
|
7601
|
-
const existing = await
|
|
6477
|
+
const { db } = await postgresClient();
|
|
6478
|
+
const existing = await db.from("entity_type_settings").where({ context: context.id }).select("name");
|
|
7602
6479
|
const existingNames = new Set(
|
|
7603
6480
|
existing.map(
|
|
7604
6481
|
(r) => String(r.name || "").toLowerCase().trim()
|
|
@@ -7612,7 +6489,7 @@ var upsertEntitySuggestions = async (context, suggestions) => {
|
|
|
7612
6489
|
status: "suggested"
|
|
7613
6490
|
}));
|
|
7614
6491
|
if (rows.length) {
|
|
7615
|
-
await
|
|
6492
|
+
await db.from("entity_type_settings").insert(rows);
|
|
7616
6493
|
}
|
|
7617
6494
|
} catch (err3) {
|
|
7618
6495
|
console.warn(
|
|
@@ -7624,8 +6501,8 @@ var upsertEntitySuggestions = async (context, suggestions) => {
|
|
|
7624
6501
|
var entityModelKey = (contextId) => `entity_extraction_model:${contextId}`;
|
|
7625
6502
|
var getEntityModelSetting = async (contextId) => {
|
|
7626
6503
|
try {
|
|
7627
|
-
const { db
|
|
7628
|
-
const row = await
|
|
6504
|
+
const { db } = await postgresClient();
|
|
6505
|
+
const row = await db.from("platform_configurations").where({ config_key: entityModelKey(contextId) }).first();
|
|
7629
6506
|
if (!row?.config_value) return null;
|
|
7630
6507
|
const raw = row.config_value;
|
|
7631
6508
|
let value = raw;
|
|
@@ -7643,14 +6520,14 @@ var getEntityModelSetting = async (contextId) => {
|
|
|
7643
6520
|
}
|
|
7644
6521
|
};
|
|
7645
6522
|
var setEntityModelSetting = async (contextId, modelId) => {
|
|
7646
|
-
const { db
|
|
6523
|
+
const { db } = await postgresClient();
|
|
7647
6524
|
const key = entityModelKey(contextId);
|
|
7648
6525
|
if (!modelId || !modelId.trim()) {
|
|
7649
|
-
await
|
|
6526
|
+
await db.from("platform_configurations").where({ config_key: key }).del();
|
|
7650
6527
|
return;
|
|
7651
6528
|
}
|
|
7652
6529
|
const value = JSON.stringify(modelId.trim());
|
|
7653
|
-
await
|
|
6530
|
+
await db.from("platform_configurations").insert({
|
|
7654
6531
|
config_key: key,
|
|
7655
6532
|
config_value: value,
|
|
7656
6533
|
description: `Entity extraction model for context ${contextId}`
|
|
@@ -7861,37 +6738,37 @@ var getChunkEntitiesTableName = (id) => sanitizeName(id) + "_chunk_entities";
|
|
|
7861
6738
|
|
|
7862
6739
|
// src/exulu/entities/store.ts
|
|
7863
6740
|
var entitiesTableExists = async (context) => {
|
|
7864
|
-
const { db
|
|
7865
|
-
return
|
|
6741
|
+
const { db } = await postgresClient();
|
|
6742
|
+
return db.schema.hasTable(getEntitiesTableName(context.id));
|
|
7866
6743
|
};
|
|
7867
6744
|
var chunkEntitiesTableExists = async (context) => {
|
|
7868
|
-
const { db
|
|
7869
|
-
return
|
|
6745
|
+
const { db } = await postgresClient();
|
|
6746
|
+
return db.schema.hasTable(getChunkEntitiesTableName(context.id));
|
|
7870
6747
|
};
|
|
7871
6748
|
var createEntitiesTable = async (context) => {
|
|
7872
|
-
const { db
|
|
6749
|
+
const { db } = await postgresClient();
|
|
7873
6750
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
7874
6751
|
console.log("[EXULU] Creating table: " + entitiesTable);
|
|
7875
|
-
await
|
|
7876
|
-
table.uuid("id").primary().defaultTo(
|
|
6752
|
+
await db.schema.createTable(entitiesTable, (table) => {
|
|
6753
|
+
table.uuid("id").primary().defaultTo(db.fn.uuid());
|
|
7877
6754
|
table.text("type").notNullable();
|
|
7878
6755
|
table.text("canonical_key").notNullable();
|
|
7879
6756
|
table.text("display_name");
|
|
7880
6757
|
table.integer("mention_count").defaultTo(0);
|
|
7881
6758
|
table.integer("doc_count").defaultTo(0);
|
|
7882
6759
|
table.jsonb("metadata");
|
|
7883
|
-
table.timestamp("createdAt").defaultTo(
|
|
7884
|
-
table.timestamp("updatedAt").defaultTo(
|
|
6760
|
+
table.timestamp("createdAt").defaultTo(db.fn.now());
|
|
6761
|
+
table.timestamp("updatedAt").defaultTo(db.fn.now());
|
|
7885
6762
|
table.unique(["type", "canonical_key"], { indexName: `${entitiesTable}_type_key_uq` });
|
|
7886
6763
|
});
|
|
7887
6764
|
};
|
|
7888
6765
|
var createChunkEntitiesTable = async (context) => {
|
|
7889
|
-
const { db
|
|
6766
|
+
const { db } = await postgresClient();
|
|
7890
6767
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
7891
6768
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
7892
6769
|
const chunksTable = getChunksTableName(context.id);
|
|
7893
6770
|
console.log("[EXULU] Creating table: " + junctionTable);
|
|
7894
|
-
await
|
|
6771
|
+
await db.schema.createTable(junctionTable, (table) => {
|
|
7895
6772
|
table.uuid("chunk_id").notNullable().references("id").inTable(chunksTable).onDelete("CASCADE");
|
|
7896
6773
|
table.uuid("entity_id").notNullable().references("id").inTable(entitiesTable).onDelete("CASCADE");
|
|
7897
6774
|
table.uuid("item_id").notNullable();
|
|
@@ -7904,36 +6781,36 @@ var createChunkEntitiesTable = async (context) => {
|
|
|
7904
6781
|
});
|
|
7905
6782
|
};
|
|
7906
6783
|
var ensureItemEntityColumns = async (context) => {
|
|
7907
|
-
const { db
|
|
6784
|
+
const { db } = await postgresClient();
|
|
7908
6785
|
const itemsTable = getTableName(context.id);
|
|
7909
|
-
if (!await
|
|
7910
|
-
await
|
|
6786
|
+
if (!await db.schema.hasColumn(itemsTable, "entities_updated_at")) {
|
|
6787
|
+
await db.schema.alterTable(itemsTable, (t) => {
|
|
7911
6788
|
t.timestamp("entities_updated_at").defaultTo(null);
|
|
7912
6789
|
});
|
|
7913
6790
|
}
|
|
7914
|
-
if (!await
|
|
7915
|
-
await
|
|
6791
|
+
if (!await db.schema.hasColumn(itemsTable, "entity_types_signature")) {
|
|
6792
|
+
await db.schema.alterTable(itemsTable, (t) => {
|
|
7916
6793
|
t.text("entity_types_signature").defaultTo(null);
|
|
7917
6794
|
});
|
|
7918
6795
|
}
|
|
7919
6796
|
};
|
|
7920
6797
|
var uniq = (arr) => Array.from(new Set(arr));
|
|
7921
6798
|
var getEntityIdsForItem = async (context, itemId) => {
|
|
7922
|
-
const { db
|
|
6799
|
+
const { db } = await postgresClient();
|
|
7923
6800
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
7924
|
-
const rows = await
|
|
6801
|
+
const rows = await db(junctionTable).where({ item_id: itemId }).distinct("entity_id");
|
|
7925
6802
|
return rows.map((r) => r.entity_id);
|
|
7926
6803
|
};
|
|
7927
6804
|
var getEntitiesForItem = async (context, itemId) => {
|
|
7928
6805
|
if (!await chunkEntitiesTableExists(context)) return [];
|
|
7929
|
-
const { db
|
|
6806
|
+
const { db } = await postgresClient();
|
|
7930
6807
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
7931
6808
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
7932
|
-
const rows = await
|
|
6809
|
+
const rows = await db(`${junctionTable} as j`).join(`${entitiesTable} as e`, "e.id", "j.entity_id").where("j.item_id", itemId).groupBy("e.id", "e.type", "e.display_name").select(
|
|
7933
6810
|
"e.id as id",
|
|
7934
6811
|
"e.type as type",
|
|
7935
6812
|
"e.display_name as name",
|
|
7936
|
-
|
|
6813
|
+
db.raw("COUNT(*)::int as mentions")
|
|
7937
6814
|
).orderBy([
|
|
7938
6815
|
{ column: "e.type", order: "asc" },
|
|
7939
6816
|
{ column: "e.display_name", order: "asc" }
|
|
@@ -7952,12 +6829,12 @@ var ingestEntitiesForItem = async ({
|
|
|
7952
6829
|
signature,
|
|
7953
6830
|
previousEntityIds
|
|
7954
6831
|
}) => {
|
|
7955
|
-
const { db
|
|
6832
|
+
const { db } = await postgresClient();
|
|
7956
6833
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
7957
6834
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
7958
6835
|
const chunksTable = getChunksTableName(context.id);
|
|
7959
6836
|
const itemsTable = getTableName(context.id);
|
|
7960
|
-
await
|
|
6837
|
+
await db.transaction(async (trx) => {
|
|
7961
6838
|
const oldEntityIds = previousEntityIds ?? (await trx(junctionTable).where({ item_id: itemId }).distinct("entity_id")).map(
|
|
7962
6839
|
(r) => r.entity_id
|
|
7963
6840
|
);
|
|
@@ -8031,12 +6908,12 @@ var ingestEntitiesForItem = async ({
|
|
|
8031
6908
|
};
|
|
8032
6909
|
var detachEntitiesForItem = async (context, itemId) => {
|
|
8033
6910
|
if (!await chunkEntitiesTableExists(context)) return 0;
|
|
8034
|
-
const { db
|
|
6911
|
+
const { db } = await postgresClient();
|
|
8035
6912
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
8036
6913
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
8037
6914
|
const itemsTable = getTableName(context.id);
|
|
8038
6915
|
let detached = 0;
|
|
8039
|
-
await
|
|
6916
|
+
await db.transaction(async (trx) => {
|
|
8040
6917
|
const affected = (await trx(junctionTable).where({ item_id: itemId }).distinct("entity_id")).map((r) => r.entity_id);
|
|
8041
6918
|
detached = affected.length;
|
|
8042
6919
|
if (!affected.length) return;
|
|
@@ -8062,31 +6939,31 @@ var detachEntitiesForItem = async (context, itemId) => {
|
|
|
8062
6939
|
};
|
|
8063
6940
|
var resolveQueryEntities = async (context, mentions) => {
|
|
8064
6941
|
if (!mentions.length) return [];
|
|
8065
|
-
const { db
|
|
6942
|
+
const { db } = await postgresClient();
|
|
8066
6943
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
8067
6944
|
const pairs = uniq(
|
|
8068
6945
|
mentions.map((m) => `${m.type}|${normalizeCanonicalKey(m.canonical)}`)
|
|
8069
6946
|
).map((k) => k.split("|"));
|
|
8070
6947
|
if (!pairs.length) return [];
|
|
8071
|
-
const rows = await
|
|
6948
|
+
const rows = await db(entitiesTable).whereIn(["type", "canonical_key"], pairs);
|
|
8072
6949
|
return rows;
|
|
8073
6950
|
};
|
|
8074
6951
|
var getSharedEntityCounts = async (context, chunkIds, entityIds) => {
|
|
8075
6952
|
const result = /* @__PURE__ */ new Map();
|
|
8076
6953
|
if (!chunkIds.length || !entityIds.length) return result;
|
|
8077
|
-
const { db
|
|
6954
|
+
const { db } = await postgresClient();
|
|
8078
6955
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
8079
|
-
const rows = await
|
|
6956
|
+
const rows = await db(junctionTable).whereIn("chunk_id", chunkIds).whereIn("entity_id", entityIds).groupBy("chunk_id").select("chunk_id").count("* as cnt");
|
|
8080
6957
|
for (const r of rows) result.set(r.chunk_id, Number(r.cnt));
|
|
8081
6958
|
return result;
|
|
8082
6959
|
};
|
|
8083
6960
|
var getEntitiesForChunks = async (context, chunkIds) => {
|
|
8084
6961
|
const result = /* @__PURE__ */ new Map();
|
|
8085
6962
|
if (!chunkIds.length) return result;
|
|
8086
|
-
const { db
|
|
6963
|
+
const { db } = await postgresClient();
|
|
8087
6964
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
8088
6965
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
8089
|
-
const rows = await
|
|
6966
|
+
const rows = await db(junctionTable + " as j").whereIn("j.chunk_id", chunkIds).join(entitiesTable + " as e", "e.id", "j.entity_id").select("j.chunk_id as chunk_id", "e.id as id", "e.display_name as name", "e.type as type");
|
|
8090
6967
|
for (const r of rows) {
|
|
8091
6968
|
const list = result.get(r.chunk_id) || [];
|
|
8092
6969
|
list.push({ id: r.id, name: r.name, type: r.type });
|
|
@@ -8095,10 +6972,10 @@ var getEntitiesForChunks = async (context, chunkIds) => {
|
|
|
8095
6972
|
return result;
|
|
8096
6973
|
};
|
|
8097
6974
|
var getRelatedEntities = async (context, entity, k = 5) => {
|
|
8098
|
-
const { db
|
|
6975
|
+
const { db } = await postgresClient();
|
|
8099
6976
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
8100
6977
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
8101
|
-
const rows = await
|
|
6978
|
+
const rows = await db(junctionTable + " as j1").join(junctionTable + " as j2", function() {
|
|
8102
6979
|
this.on("j1.item_id", "=", "j2.item_id").andOn("j2.entity_id", "!=", "j1.entity_id");
|
|
8103
6980
|
}).join(entitiesTable + " as e2", "e2.id", "j2.entity_id").where("j1.entity_id", entity.id).groupBy("e2.id", "e2.display_name", "e2.type", "e2.doc_count").select("e2.id as id", "e2.display_name as name", "e2.type as type", "e2.doc_count as doc_count").countDistinct("j2.item_id as shared").orderBy("shared", "desc").limit(k);
|
|
8104
6981
|
return rows.map((r) => {
|
|
@@ -8112,11 +6989,11 @@ var getRelatedEntities = async (context, entity, k = 5) => {
|
|
|
8112
6989
|
};
|
|
8113
6990
|
var buildEntityInsights = async (context, queryEntities, resultChunkIds, relatedLimit = 5) => {
|
|
8114
6991
|
if (!queryEntities.length) return { queryEntities: [] };
|
|
8115
|
-
const { db
|
|
6992
|
+
const { db } = await postgresClient();
|
|
8116
6993
|
const junctionTable = getChunkEntitiesTableName(context.id);
|
|
8117
6994
|
const matched = /* @__PURE__ */ new Map();
|
|
8118
6995
|
if (resultChunkIds.length) {
|
|
8119
|
-
const rows = await
|
|
6996
|
+
const rows = await db(junctionTable).whereIn("chunk_id", resultChunkIds).whereIn(
|
|
8120
6997
|
"entity_id",
|
|
8121
6998
|
queryEntities.map((e) => e.id)
|
|
8122
6999
|
).groupBy("entity_id").select("entity_id").countDistinct("chunk_id as cnt");
|
|
@@ -8141,12 +7018,12 @@ var buildEntityInsights = async (context, queryEntities, resultChunkIds, related
|
|
|
8141
7018
|
return { queryEntities: insights };
|
|
8142
7019
|
};
|
|
8143
7020
|
var resolveEntityFilter = async (context, filter) => {
|
|
8144
|
-
const { db
|
|
7021
|
+
const { db } = await postgresClient();
|
|
8145
7022
|
const entitiesTable = getEntitiesTableName(context.id);
|
|
8146
7023
|
let ids = [...filter.entityIds || []];
|
|
8147
7024
|
if (filter.entities?.length) {
|
|
8148
7025
|
const pairs = filter.entities.map((e) => [e.type, normalizeCanonicalKey(e.name)]);
|
|
8149
|
-
const rows = await
|
|
7026
|
+
const rows = await db(entitiesTable).whereIn(["type", "canonical_key"], pairs).select("id");
|
|
8150
7027
|
ids = [...ids, ...rows.map((r) => r.id)];
|
|
8151
7028
|
}
|
|
8152
7029
|
return uniq(ids);
|
|
@@ -8193,8 +7070,8 @@ var extractAndIngestEntities = async ({
|
|
|
8193
7070
|
const types = await hydrateEntityTypes(context);
|
|
8194
7071
|
if (!types.length || !context.embedder) return 0;
|
|
8195
7072
|
await ensureEntityTables(context);
|
|
8196
|
-
const { db
|
|
8197
|
-
const chunkRows = await
|
|
7073
|
+
const { db } = await postgresClient();
|
|
7074
|
+
const chunkRows = await db(getChunksTableName(context.id)).where({ source: itemId }).select("chunk_index", "content").orderBy("chunk_index", "asc");
|
|
8198
7075
|
const chunks = chunkRows.map((c) => ({ index: Number(c.chunk_index), content: c.content })).filter((c) => c.content);
|
|
8199
7076
|
const { mentions, suggestions } = await extractEntitiesForItem({
|
|
8200
7077
|
context,
|
|
@@ -8227,7 +7104,7 @@ var vectorSearch = async ({
|
|
|
8227
7104
|
chunkFilters,
|
|
8228
7105
|
sort,
|
|
8229
7106
|
context,
|
|
8230
|
-
db
|
|
7107
|
+
db,
|
|
8231
7108
|
query,
|
|
8232
7109
|
keywords,
|
|
8233
7110
|
method,
|
|
@@ -8289,19 +7166,19 @@ var vectorSearch = async ({
|
|
|
8289
7166
|
if (entitiesOn && entityFilter) {
|
|
8290
7167
|
filterEntityIds = await resolveEntityFilter(context, entityFilter);
|
|
8291
7168
|
}
|
|
8292
|
-
let chunksQuery =
|
|
7169
|
+
let chunksQuery = db(chunksTable + " as chunks").select([
|
|
8293
7170
|
"chunks.id as chunk_id",
|
|
8294
7171
|
"chunks.source",
|
|
8295
7172
|
"chunks.content",
|
|
8296
7173
|
"chunks.chunk_index",
|
|
8297
|
-
|
|
8298
|
-
|
|
7174
|
+
db.raw('chunks."createdAt" as chunk_created_at'),
|
|
7175
|
+
db.raw('chunks."updatedAt" as chunk_updated_at'),
|
|
8299
7176
|
"chunks.metadata",
|
|
8300
7177
|
"items.id as item_id",
|
|
8301
7178
|
"items.name as item_name",
|
|
8302
7179
|
"items.external_id as item_external_id",
|
|
8303
|
-
|
|
8304
|
-
|
|
7180
|
+
db.raw('items."updatedAt" as item_updated_at'),
|
|
7181
|
+
db.raw('items."createdAt" as item_created_at')
|
|
8305
7182
|
]);
|
|
8306
7183
|
chunksQuery.leftJoin(mainTable + " as items", function() {
|
|
8307
7184
|
this.on("chunks.source", "=", "items.id");
|
|
@@ -8409,7 +7286,7 @@ var vectorSearch = async ({
|
|
|
8409
7286
|
const rankParams = languages.map(() => orQuery);
|
|
8410
7287
|
const matchExpression = languages.map((lang) => `chunks.fts @@ to_tsquery('${lang}', ?)`).join(" OR ");
|
|
8411
7288
|
const matchParams = languages.map(() => orQuery);
|
|
8412
|
-
chunksQuery.select(
|
|
7289
|
+
chunksQuery.select(db.raw(`GREATEST(${rankExpression}) as fts_rank`, rankParams)).whereRaw(
|
|
8413
7290
|
`((${matchExpression})) AND (items.archived IS FALSE OR items.archived IS NULL)`,
|
|
8414
7291
|
matchParams
|
|
8415
7292
|
).orderByRaw(`fts_rank DESC`);
|
|
@@ -8420,7 +7297,7 @@ var vectorSearch = async ({
|
|
|
8420
7297
|
chunksQuery.limit(limit * 2);
|
|
8421
7298
|
chunksQuery.whereNotNull(`chunks.embedding`).whereRaw(`(items.archived IS FALSE OR items.archived IS NULL)`);
|
|
8422
7299
|
console.log("[EXULU] Chunks query:", chunksQuery.toQuery());
|
|
8423
|
-
chunksQuery.select(
|
|
7300
|
+
chunksQuery.select(db.raw(`1 - (chunks.embedding <=> ${vectorExpr}) AS cosine_distance`));
|
|
8424
7301
|
chunksQuery.orderByRaw(`chunks.embedding <=> ${vectorExpr} ASC NULLS LAST`);
|
|
8425
7302
|
chunksQuery.whereRaw(`(1 - (chunks.embedding <=> ${vectorExpr}) >= ?)`, [
|
|
8426
7303
|
cutoffs?.cosineDistance || 0
|
|
@@ -8430,7 +7307,7 @@ var vectorSearch = async ({
|
|
|
8430
7307
|
case "hybridSearch": {
|
|
8431
7308
|
let strictMatches = false;
|
|
8432
7309
|
if (query && hybridOrQuery) {
|
|
8433
|
-
const probe = await
|
|
7310
|
+
const probe = await db(chunksTable + " as chunks").select(db.raw("1")).whereRaw(`(${languages.map((lang) => `chunks.fts @@ plainto_tsquery('${lang}', ?)`).join(" OR ")})`, languages.map(() => query)).first();
|
|
8434
7311
|
strictMatches = Boolean(probe);
|
|
8435
7312
|
}
|
|
8436
7313
|
const fullText = chooseFullTextQuery({ strictMatches, strictText: query ?? "", orText: hybridOrQuery });
|
|
@@ -8444,10 +7321,10 @@ var vectorSearch = async ({
|
|
|
8444
7321
|
const ftRankParams = languages.map(() => hybridOrQuery);
|
|
8445
7322
|
const ftMatchExpression = languages.map((lang) => `chunks.fts @@ ${ftsFn}('${lang}', ?)`).join(" OR ");
|
|
8446
7323
|
const ftMatchParams = languages.map(() => hybridOrQuery);
|
|
8447
|
-
let fullTextQuery =
|
|
7324
|
+
let fullTextQuery = db(chunksTable + " as chunks").select([
|
|
8448
7325
|
"chunks.id",
|
|
8449
7326
|
"chunks.source",
|
|
8450
|
-
|
|
7327
|
+
db.raw(
|
|
8451
7328
|
`row_number() OVER (ORDER BY GREATEST(${ftRankExpression}) DESC) AS rank_ix`,
|
|
8452
7329
|
ftRankParams
|
|
8453
7330
|
)
|
|
@@ -8458,10 +7335,10 @@ var vectorSearch = async ({
|
|
|
8458
7335
|
if (filterEntityIds) {
|
|
8459
7336
|
applyEntityFilter(fullTextQuery, "chunks", context, filterEntityIds, entityFilter?.mode || "any");
|
|
8460
7337
|
}
|
|
8461
|
-
let semanticQuery =
|
|
7338
|
+
let semanticQuery = db(chunksTable + " as chunks").select([
|
|
8462
7339
|
"chunks.id",
|
|
8463
7340
|
"chunks.source",
|
|
8464
|
-
|
|
7341
|
+
db.raw(`row_number() OVER (ORDER BY chunks.embedding <=> ${vectorExpr} ASC) AS rank_ix`)
|
|
8465
7342
|
]).leftJoin(mainTable + " as items", "items.id", "chunks.source").whereNotNull("chunks.embedding").whereRaw(`(1 - (chunks.embedding <=> ${vectorExpr})) >= ?`, [cutoffs?.cosineDistance || 0]).whereRaw(`(items.archived IS FALSE OR items.archived IS NULL)`).limit(Math.min(matchCount * 2, 500));
|
|
8466
7343
|
semanticQuery = applyFilters(semanticQuery, itemFilters, table, "items");
|
|
8467
7344
|
semanticQuery = applyFilters(semanticQuery, chunkFilters, table, "chunks");
|
|
@@ -8469,7 +7346,7 @@ var vectorSearch = async ({
|
|
|
8469
7346
|
if (filterEntityIds) {
|
|
8470
7347
|
applyEntityFilter(semanticQuery, "chunks", context, filterEntityIds, entityFilter?.mode || "any");
|
|
8471
7348
|
}
|
|
8472
|
-
let hybridQuery =
|
|
7349
|
+
let hybridQuery = db.with("full_text", fullTextQuery).with("semantic", semanticQuery).select([
|
|
8473
7350
|
"items.id as item_id",
|
|
8474
7351
|
"items.name as item_name",
|
|
8475
7352
|
"items.external_id as item_external_id",
|
|
@@ -8478,16 +7355,16 @@ var vectorSearch = async ({
|
|
|
8478
7355
|
"chunks.content",
|
|
8479
7356
|
"chunks.chunk_index",
|
|
8480
7357
|
"chunks.metadata",
|
|
8481
|
-
|
|
8482
|
-
|
|
8483
|
-
|
|
8484
|
-
|
|
8485
|
-
|
|
7358
|
+
db.raw('chunks."createdAt" as chunk_created_at'),
|
|
7359
|
+
db.raw('chunks."updatedAt" as chunk_updated_at'),
|
|
7360
|
+
db.raw('items."updatedAt" as item_updated_at'),
|
|
7361
|
+
db.raw('items."createdAt" as item_created_at'),
|
|
7362
|
+
db.raw(
|
|
8486
7363
|
`GREATEST(${languages.map((lang) => `ts_rank(chunks.fts, ${ftsFn}('${lang}', ?))`).join(", ")}) AS fts_rank`,
|
|
8487
7364
|
languages.map(() => hybridOrQuery)
|
|
8488
7365
|
),
|
|
8489
|
-
|
|
8490
|
-
|
|
7366
|
+
db.raw(`(1 - (chunks.embedding <=> ${vectorExpr})) AS cosine_distance`),
|
|
7367
|
+
db.raw(
|
|
8491
7368
|
`
|
|
8492
7369
|
(
|
|
8493
7370
|
COALESCE(1.0 / (? + ft.rank_ix), 0.0) * ?
|
|
@@ -8498,7 +7375,7 @@ var vectorSearch = async ({
|
|
|
8498
7375
|
[rrfK, fullTextWeight, rrfK, semanticWeight]
|
|
8499
7376
|
)
|
|
8500
7377
|
]).from("full_text as ft").fullOuterJoin("semantic as se", "ft.id", "se.id").join(chunksTable + " as chunks", function() {
|
|
8501
|
-
this.on(
|
|
7378
|
+
this.on(db.raw("COALESCE(ft.id, se.id)"), "=", "chunks.id");
|
|
8502
7379
|
}).join(mainTable + " as items", "items.id", "chunks.source").whereRaw(
|
|
8503
7380
|
`
|
|
8504
7381
|
(
|
|
@@ -8604,7 +7481,7 @@ var vectorSearch = async ({
|
|
|
8604
7481
|
if (plan.size > 0) {
|
|
8605
7482
|
const itemIds = Array.from(plan.keys());
|
|
8606
7483
|
const indices = Array.from(new Set(Array.from(plan.values()).flatMap((s) => Array.from(s))));
|
|
8607
|
-
const rows = await
|
|
7484
|
+
const rows = await db(chunksTable).select(["id", "source", "chunk_index", "content", "metadata", "createdAt", "updatedAt"]).whereIn("source", itemIds).whereIn("chunk_index", indices);
|
|
8608
7485
|
results = mergeNeighbours(results, rows, plan, { name: table.name.singular, id: table.id || "" });
|
|
8609
7486
|
}
|
|
8610
7487
|
results = results.sort((a, b) => {
|
|
@@ -8775,14 +7652,14 @@ var PRUNE_EVERY = 100;
|
|
|
8775
7652
|
var MAX_IMPORT_PER_CONTEXT = 200;
|
|
8776
7653
|
var sinceLastPrune = 0;
|
|
8777
7654
|
var pruning = false;
|
|
8778
|
-
async function maybePruneJobResults(
|
|
7655
|
+
async function maybePruneJobResults(db) {
|
|
8779
7656
|
sinceLastPrune += 1;
|
|
8780
7657
|
if (sinceLastPrune < PRUNE_EVERY || pruning) return;
|
|
8781
7658
|
sinceLastPrune = 0;
|
|
8782
7659
|
pruning = true;
|
|
8783
7660
|
try {
|
|
8784
|
-
await pruneGenericJobResults(
|
|
8785
|
-
await pruneImportJobResults(
|
|
7661
|
+
await pruneGenericJobResults(db);
|
|
7662
|
+
await pruneImportJobResults(db);
|
|
8786
7663
|
} finally {
|
|
8787
7664
|
pruning = false;
|
|
8788
7665
|
}
|
|
@@ -8792,14 +7669,14 @@ function excludeImportType(builder) {
|
|
|
8792
7669
|
this.whereNot({ type: "import" }).orWhereNull("type");
|
|
8793
7670
|
});
|
|
8794
7671
|
}
|
|
8795
|
-
async function pruneGenericJobResults(
|
|
7672
|
+
async function pruneGenericJobResults(db) {
|
|
8796
7673
|
try {
|
|
8797
7674
|
const boundary = await excludeImportType(
|
|
8798
|
-
|
|
7675
|
+
db("job_results").whereIn("state", TERMINAL_JOB_STATES)
|
|
8799
7676
|
).orderBy("createdAt", "desc").offset(MAX_TERMINAL).limit(1).first();
|
|
8800
7677
|
if (boundary?.createdAt) {
|
|
8801
7678
|
const deleted = await excludeImportType(
|
|
8802
|
-
|
|
7679
|
+
db("job_results").whereIn("state", TERMINAL_JOB_STATES)
|
|
8803
7680
|
).where("createdAt", "<=", boundary.createdAt).del();
|
|
8804
7681
|
if (deleted) {
|
|
8805
7682
|
console.log(
|
|
@@ -8811,11 +7688,11 @@ async function pruneGenericJobResults(db2) {
|
|
|
8811
7688
|
console.error("[EXULU] job_results prune failed", err3);
|
|
8812
7689
|
}
|
|
8813
7690
|
}
|
|
8814
|
-
async function pruneImportJobResults(
|
|
8815
|
-
if (
|
|
7691
|
+
async function pruneImportJobResults(db) {
|
|
7692
|
+
if (db.client?.config?.client !== "pg") return;
|
|
8816
7693
|
try {
|
|
8817
7694
|
const statePlaceholders = TERMINAL_JOB_STATES.map(() => "?").join(", ");
|
|
8818
|
-
const deleted = await
|
|
7695
|
+
const deleted = await db("job_results").where({ type: "import" }).whereRaw(
|
|
8819
7696
|
`id in (
|
|
8820
7697
|
select id from (
|
|
8821
7698
|
select id, row_number() over (partition by context order by "createdAt" desc) as rn
|
|
@@ -8892,9 +7769,9 @@ var bullmqDecorator = async ({
|
|
|
8892
7769
|
const redisId = uuidv4();
|
|
8893
7770
|
if ((type === "processor" || type === "embedder") && context) {
|
|
8894
7771
|
try {
|
|
8895
|
-
const { db
|
|
7772
|
+
const { db } = await postgresClient();
|
|
8896
7773
|
const itemId = item == null ? null : typeof item === "object" ? item.id ?? null : item;
|
|
8897
|
-
await
|
|
7774
|
+
await db.from("job_results").insert({
|
|
8898
7775
|
job_id: redisId,
|
|
8899
7776
|
label,
|
|
8900
7777
|
state: "waiting",
|
|
@@ -8904,7 +7781,7 @@ var bullmqDecorator = async ({
|
|
|
8904
7781
|
result: null,
|
|
8905
7782
|
metadata: {}
|
|
8906
7783
|
});
|
|
8907
|
-
void maybePruneJobResults(
|
|
7784
|
+
void maybePruneJobResults(db);
|
|
8908
7785
|
} catch (err3) {
|
|
8909
7786
|
console.error("[EXULU] enqueue job_results insert failed", err3);
|
|
8910
7787
|
}
|
|
@@ -9068,17 +7945,17 @@ var ExuluContext2 = class {
|
|
|
9068
7945
|
if (!processorResult) {
|
|
9069
7946
|
throw new Error("Processor result is required for updating the item in the db.");
|
|
9070
7947
|
}
|
|
9071
|
-
const { db
|
|
7948
|
+
const { db } = await postgresClient();
|
|
9072
7949
|
delete processorResult.field;
|
|
9073
7950
|
delete processorResult.fts;
|
|
9074
|
-
await
|
|
7951
|
+
await db.from(getTableName(this.id)).where({
|
|
9075
7952
|
id: processorResult.id
|
|
9076
7953
|
}).update({
|
|
9077
7954
|
...processorResult,
|
|
9078
7955
|
last_processed_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
9079
7956
|
});
|
|
9080
7957
|
if (this.processor?.config?.generateEmbeddings) {
|
|
9081
|
-
const fullItem = await
|
|
7958
|
+
const fullItem = await db.from(getTableName(this.id)).where({
|
|
9082
7959
|
id: processorResult.id
|
|
9083
7960
|
}).first();
|
|
9084
7961
|
if (!fullItem) {
|
|
@@ -9110,7 +7987,7 @@ var ExuluContext2 = class {
|
|
|
9110
7987
|
await refreshContextEmbeddersIfStale(exuluApp.get().contexts);
|
|
9111
7988
|
} catch {
|
|
9112
7989
|
}
|
|
9113
|
-
const { db
|
|
7990
|
+
const { db } = await postgresClient();
|
|
9114
7991
|
const result = await vectorSearch({
|
|
9115
7992
|
...options,
|
|
9116
7993
|
user: options.user,
|
|
@@ -9118,7 +7995,7 @@ var ExuluContext2 = class {
|
|
|
9118
7995
|
itemFilters: options.itemFilters,
|
|
9119
7996
|
chunkFilters: options.chunkFilters,
|
|
9120
7997
|
context: this,
|
|
9121
|
-
db
|
|
7998
|
+
db,
|
|
9122
7999
|
limit: options?.limit || this.configuration.maxRetrievalResults || 10,
|
|
9123
8000
|
cutoffs: options.cutoffs,
|
|
9124
8001
|
expand: options.expand,
|
|
@@ -9127,11 +8004,11 @@ var ExuluContext2 = class {
|
|
|
9127
8004
|
return result;
|
|
9128
8005
|
};
|
|
9129
8006
|
deleteAll = async () => {
|
|
9130
|
-
const { db
|
|
9131
|
-
await
|
|
9132
|
-
await
|
|
8007
|
+
const { db } = await postgresClient();
|
|
8008
|
+
await db.from(getTableName(this.id)).delete();
|
|
8009
|
+
await db.from(getChunksTableName(this.id)).delete();
|
|
9133
8010
|
if (await entitiesTableExists(this)) {
|
|
9134
|
-
await
|
|
8011
|
+
await db.from(getEntitiesTableName(this.id)).delete();
|
|
9135
8012
|
}
|
|
9136
8013
|
return {
|
|
9137
8014
|
count: 0,
|
|
@@ -9145,16 +8022,16 @@ var ExuluContext2 = class {
|
|
|
9145
8022
|
});
|
|
9146
8023
|
};
|
|
9147
8024
|
tableExists = async () => {
|
|
9148
|
-
const { db
|
|
8025
|
+
const { db } = await postgresClient();
|
|
9149
8026
|
const tableName = getTableName(this.id);
|
|
9150
8027
|
console.log("[EXULU] checking if table exists.", tableName);
|
|
9151
|
-
const tableExists = await
|
|
8028
|
+
const tableExists = await db.schema.hasTable(tableName);
|
|
9152
8029
|
return tableExists;
|
|
9153
8030
|
};
|
|
9154
8031
|
chunksTableExists = async () => {
|
|
9155
|
-
const { db
|
|
8032
|
+
const { db } = await postgresClient();
|
|
9156
8033
|
const chunksTableName = getChunksTableName(this.id);
|
|
9157
|
-
const chunksTableExists = await
|
|
8034
|
+
const chunksTableExists = await db.schema.hasTable(chunksTableName);
|
|
9158
8035
|
return chunksTableExists;
|
|
9159
8036
|
};
|
|
9160
8037
|
createAndUpsertEmbeddings = async (item, config, user, statistics, role, job) => {
|
|
@@ -9164,7 +8041,7 @@ var ExuluContext2 = class {
|
|
|
9164
8041
|
if (!item.id) {
|
|
9165
8042
|
throw new Error("Item id is required for generating embeddings.");
|
|
9166
8043
|
}
|
|
9167
|
-
const { db
|
|
8044
|
+
const { db } = await postgresClient();
|
|
9168
8045
|
if (statistics) {
|
|
9169
8046
|
await updateStatistic({
|
|
9170
8047
|
name: "count",
|
|
@@ -9199,9 +8076,9 @@ var ExuluContext2 = class {
|
|
|
9199
8076
|
metadata: c.metadata ?? {},
|
|
9200
8077
|
vector: vectors[i] ?? []
|
|
9201
8078
|
}));
|
|
9202
|
-
const coordinates = await chunkCoordinates({ db
|
|
8079
|
+
const coordinates = await chunkCoordinates({ db, contextId: this.id, vectors: chunks.map((c) => c.vector) });
|
|
9203
8080
|
const previousEntityIds = await captureEntitiesBeforeReembed(this, item.id);
|
|
9204
|
-
await
|
|
8081
|
+
await db.from(getChunksTableName(this.id)).where({ source }).delete();
|
|
9205
8082
|
if (chunks?.length) {
|
|
9206
8083
|
const sanitizeString = (str3) => {
|
|
9207
8084
|
if (!str3) return "";
|
|
@@ -9219,7 +8096,7 @@ var ExuluContext2 = class {
|
|
|
9219
8096
|
}
|
|
9220
8097
|
return sanitized;
|
|
9221
8098
|
};
|
|
9222
|
-
await
|
|
8099
|
+
await db.from(getChunksTableName(this.id)).insert(
|
|
9223
8100
|
chunks.map((chunk, index) => ({
|
|
9224
8101
|
// Sanitize source to remove null bytes
|
|
9225
8102
|
source: sanitizeString(source),
|
|
@@ -9228,14 +8105,14 @@ var ExuluContext2 = class {
|
|
|
9228
8105
|
// Remove null bytes (0x00) which are invalid in PostgreSQL UTF8 encoding
|
|
9229
8106
|
content: sanitizeString(chunk.content),
|
|
9230
8107
|
chunk_index: chunk.index,
|
|
9231
|
-
embedding:
|
|
8108
|
+
embedding: pgvector.toSql(chunk.vector),
|
|
9232
8109
|
// Written only when a projection exists, so the insert stays valid on
|
|
9233
8110
|
// a chunks table that predates the px/py/pz columns.
|
|
9234
8111
|
...coordinates[index] ? { px: coordinates[index].x, py: coordinates[index].y, pz: coordinates[index].z } : {}
|
|
9235
8112
|
}))
|
|
9236
8113
|
);
|
|
9237
8114
|
}
|
|
9238
|
-
await
|
|
8115
|
+
await db.from(getTableName(this.id)).where({ id: item.id }).update({
|
|
9239
8116
|
chunks_count: chunks?.length || 0,
|
|
9240
8117
|
embeddings_updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
9241
8118
|
}).returning("id");
|
|
@@ -9257,7 +8134,7 @@ var ExuluContext2 = class {
|
|
|
9257
8134
|
);
|
|
9258
8135
|
}
|
|
9259
8136
|
item.rights_mode = sanitizeItemRightsMode(item.rights_mode, this.configuration.defaultRightsMode);
|
|
9260
|
-
const { db
|
|
8137
|
+
const { db } = await postgresClient();
|
|
9261
8138
|
Object.keys(item).forEach((key) => {
|
|
9262
8139
|
if (this.fields.find((field) => field.name === key)?.type === "json") {
|
|
9263
8140
|
if (typeof item[key] === "object" || Array.isArray(item[key])) {
|
|
@@ -9266,7 +8143,7 @@ var ExuluContext2 = class {
|
|
|
9266
8143
|
}
|
|
9267
8144
|
});
|
|
9268
8145
|
console.log("[EXULU] Creating item", item);
|
|
9269
|
-
const mutation =
|
|
8146
|
+
const mutation = db.from(getTableName(this.id)).insert({
|
|
9270
8147
|
...item,
|
|
9271
8148
|
tags: item.tags ? Array.isArray(item.tags) ? item.tags.join(",") : item.tags : void 0
|
|
9272
8149
|
}).returning("id");
|
|
@@ -9304,7 +8181,7 @@ var ExuluContext2 = class {
|
|
|
9304
8181
|
jobs.push(processorJob);
|
|
9305
8182
|
}
|
|
9306
8183
|
if (!processorJob && processorResult) {
|
|
9307
|
-
await
|
|
8184
|
+
await db.from(getTableName(this.id)).where({ id: results[0].id }).update({
|
|
9308
8185
|
...processorResult
|
|
9309
8186
|
});
|
|
9310
8187
|
if (processor.config?.generateEmbeddings) {
|
|
@@ -9336,11 +8213,11 @@ var ExuluContext2 = class {
|
|
|
9336
8213
|
};
|
|
9337
8214
|
updateItem = async (item, config, user, role, generateEmbeddingsOverwrite, runProcessorOverwrite) => {
|
|
9338
8215
|
console.log("[EXULU] updating item", item);
|
|
9339
|
-
const { db
|
|
8216
|
+
const { db } = await postgresClient();
|
|
9340
8217
|
if (item.field) {
|
|
9341
8218
|
delete item.field;
|
|
9342
8219
|
}
|
|
9343
|
-
const record = await
|
|
8220
|
+
const record = await db.from(getTableName(this.id)).where({ id: item.id }).first();
|
|
9344
8221
|
if (!record) {
|
|
9345
8222
|
throw new Error("Item not found.");
|
|
9346
8223
|
}
|
|
@@ -9351,7 +8228,7 @@ var ExuluContext2 = class {
|
|
|
9351
8228
|
}
|
|
9352
8229
|
}
|
|
9353
8230
|
});
|
|
9354
|
-
const mutation =
|
|
8231
|
+
const mutation = db.from(getTableName(this.id)).where({ id: record.id }).update({
|
|
9355
8232
|
...item,
|
|
9356
8233
|
tags: item.tags ? Array.isArray(item.tags) ? item.tags.join(",") : item.tags : void 0
|
|
9357
8234
|
}).returning("id");
|
|
@@ -9375,7 +8252,7 @@ var ExuluContext2 = class {
|
|
|
9375
8252
|
jobs.push(processorJob);
|
|
9376
8253
|
}
|
|
9377
8254
|
if (!processorJob && processorResult) {
|
|
9378
|
-
await
|
|
8255
|
+
await db.from(getTableName(this.id)).where({ id: record.id }).update({
|
|
9379
8256
|
...processorResult
|
|
9380
8257
|
});
|
|
9381
8258
|
if (processor.config?.generateEmbeddings) {
|
|
@@ -9403,40 +8280,40 @@ var ExuluContext2 = class {
|
|
|
9403
8280
|
};
|
|
9404
8281
|
};
|
|
9405
8282
|
deleteItem = async (item, user, role) => {
|
|
9406
|
-
const { db
|
|
8283
|
+
const { db } = await postgresClient();
|
|
9407
8284
|
if (!item.id && !item.external_id) {
|
|
9408
8285
|
throw new Error("Item id or external id is required for deleting an item.");
|
|
9409
8286
|
}
|
|
9410
8287
|
if (!item.id?.length && item?.external_id) {
|
|
9411
|
-
item = await
|
|
8288
|
+
item = await db.from(getTableName(this.id)).where({ external_id: item.external_id }).first();
|
|
9412
8289
|
if (!item || !item.id) {
|
|
9413
8290
|
throw new Error(`Item not found for external id ${item?.external_id || "undefined"}.`);
|
|
9414
8291
|
}
|
|
9415
8292
|
}
|
|
9416
8293
|
const chunkTableExists = await this.chunksTableExists();
|
|
9417
8294
|
if (chunkTableExists) {
|
|
9418
|
-
const chunks = await
|
|
8295
|
+
const chunks = await db.from(getChunksTableName(this.id)).where({ source: item.id }).select("id");
|
|
9419
8296
|
if (chunks.length > 0) {
|
|
9420
|
-
await
|
|
8297
|
+
await db.from(getChunksTableName(this.id)).where({ source: item.id }).delete();
|
|
9421
8298
|
}
|
|
9422
8299
|
}
|
|
9423
|
-
await
|
|
8300
|
+
await db.from(getTableName(this.id)).where({ id: item.id }).delete();
|
|
9424
8301
|
return {
|
|
9425
8302
|
id: item.id,
|
|
9426
8303
|
job: void 0
|
|
9427
8304
|
};
|
|
9428
8305
|
};
|
|
9429
8306
|
getItem = async ({ item }) => {
|
|
9430
|
-
const { db
|
|
8307
|
+
const { db } = await postgresClient();
|
|
9431
8308
|
if (!item.id && !item.external_id) {
|
|
9432
8309
|
throw new Error("Item id or external id is required to get an item.");
|
|
9433
8310
|
}
|
|
9434
|
-
const result = await
|
|
8311
|
+
const result = await db.from(getTableName(this.id)).where({
|
|
9435
8312
|
...item.id ? { id: item.id } : {},
|
|
9436
8313
|
...item.external_id ? { external_id: item.external_id } : {}
|
|
9437
8314
|
}).first();
|
|
9438
8315
|
if (result) {
|
|
9439
|
-
const chunksCount = await
|
|
8316
|
+
const chunksCount = await db.from(getChunksTableName(this.id)).where({ source: result.id }).count("id");
|
|
9440
8317
|
result.chunksCount = Number(chunksCount[0].count) || 0;
|
|
9441
8318
|
}
|
|
9442
8319
|
return result;
|
|
@@ -9447,9 +8324,9 @@ var ExuluContext2 = class {
|
|
|
9447
8324
|
user,
|
|
9448
8325
|
role
|
|
9449
8326
|
}) => {
|
|
9450
|
-
const { db
|
|
8327
|
+
const { db } = await postgresClient();
|
|
9451
8328
|
const tableDefinition = convertContextToTableDefinition(this);
|
|
9452
|
-
let query =
|
|
8329
|
+
let query = db.from(getTableName(this.id)).select(fields || "*");
|
|
9453
8330
|
query = applyFilters(query, filters || [], tableDefinition);
|
|
9454
8331
|
if (user) {
|
|
9455
8332
|
const acUser = role && (!user.role || user.role.id !== role) ? { ...user, role: { ...user.role ?? {}, id: role } } : user;
|
|
@@ -9478,8 +8355,8 @@ var ExuluContext2 = class {
|
|
|
9478
8355
|
if (!item.id) {
|
|
9479
8356
|
throw new Error("Item id is required for generating embeddings.");
|
|
9480
8357
|
}
|
|
9481
|
-
const { db
|
|
9482
|
-
const record = await
|
|
8358
|
+
const { db } = await postgresClient();
|
|
8359
|
+
const record = await db.from(getTableName(this.id)).where({ id: item.id }).first();
|
|
9483
8360
|
if (!record) {
|
|
9484
8361
|
throw new Error("Item not found.");
|
|
9485
8362
|
}
|
|
@@ -9523,8 +8400,8 @@ var ExuluContext2 = class {
|
|
|
9523
8400
|
);
|
|
9524
8401
|
},
|
|
9525
8402
|
all: async (config, userId, roleId, limit) => {
|
|
9526
|
-
const { db
|
|
9527
|
-
let query =
|
|
8403
|
+
const { db } = await postgresClient();
|
|
8404
|
+
let query = db.from(getTableName(this.id)).select("*");
|
|
9528
8405
|
if (limit) {
|
|
9529
8406
|
query = query.limit(limit);
|
|
9530
8407
|
}
|
|
@@ -9564,15 +8441,15 @@ var ExuluContext2 = class {
|
|
|
9564
8441
|
/** Count items whose entities were extracted with an out-of-date type set. */
|
|
9565
8442
|
countStale: async () => {
|
|
9566
8443
|
if (!await entitiesEnabled(this)) return 0;
|
|
9567
|
-
const { db
|
|
8444
|
+
const { db } = await postgresClient();
|
|
9568
8445
|
const itemsTable = getTableName(this.id);
|
|
9569
|
-
if (!await
|
|
9570
|
-
const rows2 = await
|
|
8446
|
+
if (!await db.schema.hasColumn(itemsTable, "entity_types_signature")) {
|
|
8447
|
+
const rows2 = await db(itemsTable).count("id as count");
|
|
9571
8448
|
return Number(rows2[0]?.count) || 0;
|
|
9572
8449
|
}
|
|
9573
8450
|
const types = await hydrateEntityTypes(this);
|
|
9574
8451
|
const signature = computeTypesSignature(types);
|
|
9575
|
-
const rows = await
|
|
8452
|
+
const rows = await db(itemsTable).where(function() {
|
|
9576
8453
|
this.whereNull("entity_types_signature").orWhere(
|
|
9577
8454
|
"entity_types_signature",
|
|
9578
8455
|
"!=",
|
|
@@ -9593,13 +8470,13 @@ var ExuluContext2 = class {
|
|
|
9593
8470
|
if (!await entitiesEnabled(this)) {
|
|
9594
8471
|
return { processed: 0, skipped: 0 };
|
|
9595
8472
|
}
|
|
9596
|
-
const { db
|
|
8473
|
+
const { db } = await postgresClient();
|
|
9597
8474
|
const itemsTable = getTableName(this.id);
|
|
9598
8475
|
const SAFEGUARD_CAP = limit ?? 5e3;
|
|
9599
8476
|
const types = await hydrateEntityTypes(this);
|
|
9600
8477
|
const signature = computeTypesSignature(types);
|
|
9601
|
-
let query =
|
|
9602
|
-
if (onlyStale && await
|
|
8478
|
+
let query = db(itemsTable).select("id");
|
|
8479
|
+
if (onlyStale && await db.schema.hasColumn(itemsTable, "entity_types_signature")) {
|
|
9603
8480
|
query = query.where(function() {
|
|
9604
8481
|
this.whereNull("entity_types_signature").orWhere(
|
|
9605
8482
|
"entity_types_signature",
|
|
@@ -9643,18 +8520,18 @@ var ExuluContext2 = class {
|
|
|
9643
8520
|
/** Remove all entities (and their mentions via cascade) of a given type. */
|
|
9644
8521
|
purgeType: async (typeName) => {
|
|
9645
8522
|
if (!await entitiesTableExists(this)) return { removed: 0 };
|
|
9646
|
-
const { db
|
|
9647
|
-
const removed = await
|
|
8523
|
+
const { db } = await postgresClient();
|
|
8524
|
+
const removed = await db(getEntitiesTableName(this.id)).where({ type: typeName }).delete();
|
|
9648
8525
|
return { removed: Number(removed) || 0 };
|
|
9649
8526
|
}
|
|
9650
8527
|
};
|
|
9651
8528
|
createItemsTable = async () => {
|
|
9652
|
-
const { db
|
|
8529
|
+
const { db } = await postgresClient();
|
|
9653
8530
|
const tableName = getTableName(this.id);
|
|
9654
8531
|
console.log("[EXULU] Creating table: " + tableName);
|
|
9655
|
-
await
|
|
8532
|
+
await db.schema.createTable(tableName, (table) => {
|
|
9656
8533
|
console.log("[EXULU] Creating fields for table.", this.fields);
|
|
9657
|
-
table.uuid("id").primary().defaultTo(
|
|
8534
|
+
table.uuid("id").primary().defaultTo(db.fn.uuid());
|
|
9658
8535
|
table.text("name");
|
|
9659
8536
|
table.text("description");
|
|
9660
8537
|
table.text("tags");
|
|
@@ -9678,8 +8555,8 @@ var ExuluContext2 = class {
|
|
|
9678
8555
|
}
|
|
9679
8556
|
mapType(table, type, sanitizeName(name), void 0, unique);
|
|
9680
8557
|
}
|
|
9681
|
-
table.timestamp("createdAt").defaultTo(
|
|
9682
|
-
table.timestamp("updatedAt").defaultTo(
|
|
8558
|
+
table.timestamp("createdAt").defaultTo(db.fn.now());
|
|
8559
|
+
table.timestamp("updatedAt").defaultTo(db.fn.now());
|
|
9683
8560
|
const languages = this.configuration.languages?.length ? this.configuration.languages : ["english"];
|
|
9684
8561
|
const tsvectorExpression = languages.map((lang) => `to_tsvector('${lang}', coalesce(name, '') || ' ' || coalesce(description, '') || ' ' || coalesce(external_id, '') || ' ' || regexp_replace(coalesce(name, ''), '[_\\-\\s]+', '', 'g') || ' ' || regexp_replace(coalesce(external_id, ''), '[_\\-\\s]+', '', 'g'))`).join(" || ");
|
|
9685
8562
|
table.specificType(
|
|
@@ -9691,7 +8568,7 @@ var ExuluContext2 = class {
|
|
|
9691
8568
|
return;
|
|
9692
8569
|
};
|
|
9693
8570
|
createChunksTable = async () => {
|
|
9694
|
-
const { db
|
|
8571
|
+
const { db } = await postgresClient();
|
|
9695
8572
|
const tableName = getChunksTableName(this.id);
|
|
9696
8573
|
console.log("[EXULU] Creating table: " + tableName);
|
|
9697
8574
|
if (!this.embedder) {
|
|
@@ -9700,8 +8577,8 @@ var ExuluContext2 = class {
|
|
|
9700
8577
|
);
|
|
9701
8578
|
}
|
|
9702
8579
|
const { dimensionality } = getEmbeddingModelInfo(this.embedder.model);
|
|
9703
|
-
await
|
|
9704
|
-
table.uuid("id").primary().defaultTo(
|
|
8580
|
+
await db.schema.createTable(tableName, (table) => {
|
|
8581
|
+
table.uuid("id").primary().defaultTo(db.fn.uuid());
|
|
9705
8582
|
table.uuid("source").references("id").inTable(getTableName(this.id));
|
|
9706
8583
|
table.text("content");
|
|
9707
8584
|
table.jsonb("metadata");
|
|
@@ -9718,10 +8595,10 @@ var ExuluContext2 = class {
|
|
|
9718
8595
|
);
|
|
9719
8596
|
table.index(["fts"], `${tableName}_fts_gin_idx`, "gin");
|
|
9720
8597
|
table.index(["source"], `${tableName}_source_idx`);
|
|
9721
|
-
table.timestamp("createdAt").defaultTo(
|
|
9722
|
-
table.timestamp("updatedAt").defaultTo(
|
|
8598
|
+
table.timestamp("createdAt").defaultTo(db.fn.now());
|
|
8599
|
+
table.timestamp("updatedAt").defaultTo(db.fn.now());
|
|
9723
8600
|
});
|
|
9724
|
-
await
|
|
8601
|
+
await db.raw(`
|
|
9725
8602
|
CREATE INDEX IF NOT EXISTS ${tableName}_embedding_hnsw_cosine
|
|
9726
8603
|
ON ${tableName}
|
|
9727
8604
|
USING hnsw (embedding vector_cosine_ops)
|
|
@@ -11474,7 +10351,7 @@ var convertContextToTableDefinition = (context) => {
|
|
|
11474
10351
|
};
|
|
11475
10352
|
|
|
11476
10353
|
// ee/rbac-update.ts
|
|
11477
|
-
var handleRBACUpdate = async (
|
|
10354
|
+
var handleRBACUpdate = async (db, entityName, resourceId, rbacData, existingRbacRecords) => {
|
|
11478
10355
|
const license = checkLicense();
|
|
11479
10356
|
if (!license.rbac) {
|
|
11480
10357
|
console.warn(`[EXULU] You are not licensed to use RBAC.`);
|
|
@@ -11487,7 +10364,7 @@ var handleRBACUpdate = async (db2, entityName, resourceId, rbacData, existingRba
|
|
|
11487
10364
|
/* projects = [] */
|
|
11488
10365
|
} = rbacData;
|
|
11489
10366
|
if (!existingRbacRecords) {
|
|
11490
|
-
existingRbacRecords = await
|
|
10367
|
+
existingRbacRecords = await db.from("rbac").where({
|
|
11491
10368
|
entity: entityName,
|
|
11492
10369
|
target_resource_id: resourceId
|
|
11493
10370
|
}).select("*");
|
|
@@ -11517,19 +10394,19 @@ var handleRBACUpdate = async (db2, entityName, resourceId, rbacData, existingRba
|
|
|
11517
10394
|
(r) => r.access_type === "Team" && !newTeamRecords.has(`${r.team_id}:${r.rights}`)
|
|
11518
10395
|
);
|
|
11519
10396
|
if (usersToRemove.length > 0) {
|
|
11520
|
-
await
|
|
10397
|
+
await db.from("rbac").whereIn(
|
|
11521
10398
|
"id",
|
|
11522
10399
|
usersToRemove.map((r) => r.id)
|
|
11523
10400
|
).del();
|
|
11524
10401
|
}
|
|
11525
10402
|
if (rolesToRemove.length > 0) {
|
|
11526
|
-
await
|
|
10403
|
+
await db.from("rbac").whereIn(
|
|
11527
10404
|
"id",
|
|
11528
10405
|
rolesToRemove.map((r) => r.id)
|
|
11529
10406
|
).del();
|
|
11530
10407
|
}
|
|
11531
10408
|
if (teamsToRemove.length > 0) {
|
|
11532
|
-
await
|
|
10409
|
+
await db.from("rbac").whereIn(
|
|
11533
10410
|
"id",
|
|
11534
10411
|
teamsToRemove.map((r) => r.id)
|
|
11535
10412
|
).del();
|
|
@@ -11569,7 +10446,7 @@ var handleRBACUpdate = async (db2, entityName, resourceId, rbacData, existingRba
|
|
|
11569
10446
|
});
|
|
11570
10447
|
});
|
|
11571
10448
|
if (recordsToInsert.length > 0) {
|
|
11572
|
-
await
|
|
10449
|
+
await db.from("rbac").insert(recordsToInsert);
|
|
11573
10450
|
}
|
|
11574
10451
|
};
|
|
11575
10452
|
|
|
@@ -11596,13 +10473,13 @@ function memoryBaseHasSourceSession(context) {
|
|
|
11596
10473
|
}
|
|
11597
10474
|
|
|
11598
10475
|
// src/exulu/memory/access.ts
|
|
11599
|
-
async function canEditMemory(context, row, user,
|
|
10476
|
+
async function canEditMemory(context, row, user, db) {
|
|
11600
10477
|
if (!user?.id) return false;
|
|
11601
10478
|
if (user.super_admin === true) return true;
|
|
11602
10479
|
const creator = creatorId(row.created_by);
|
|
11603
10480
|
if (creator !== null && creator === user.id) return true;
|
|
11604
10481
|
const entity = convertContextToTableDefinition(context).name.singular;
|
|
11605
|
-
const grants = await
|
|
10482
|
+
const grants = await db("rbac").where({ entity, target_resource_id: row.id, rights: "write" }).select("access_type", "user_id", "role_id", "team_id");
|
|
11606
10483
|
return grants.some(
|
|
11607
10484
|
(g) => g.access_type === "User" && g.user_id === user.id || g.access_type === "Role" && !!user.role?.id && g.role_id === user.role.id || g.access_type === "Team" && !!user.team?.id && g.team_id === user.team.id
|
|
11608
10485
|
);
|
|
@@ -11656,18 +10533,18 @@ var RecallCollector = class {
|
|
|
11656
10533
|
return [...this.items.values()];
|
|
11657
10534
|
}
|
|
11658
10535
|
};
|
|
11659
|
-
async function loadVisibleMemoryRows(context, ids, user,
|
|
10536
|
+
async function loadVisibleMemoryRows(context, ids, user, db) {
|
|
11660
10537
|
if (ids.length === 0) return [];
|
|
11661
10538
|
const table = convertContextToTableDefinition(context);
|
|
11662
|
-
const query =
|
|
10539
|
+
const query = db(getTableName(context.id)).whereIn("id", ids).whereNot("archived", true);
|
|
11663
10540
|
const withAccess = applyAccessControl(table, query, user);
|
|
11664
10541
|
return withAccess.select(MEMORY_ITEM_FIELDS);
|
|
11665
10542
|
}
|
|
11666
|
-
function createRecallCollector(context, user,
|
|
10543
|
+
function createRecallCollector(context, user, db) {
|
|
11667
10544
|
return new RecallCollector({
|
|
11668
10545
|
contextId: context.id,
|
|
11669
|
-
loadItems: (ids) => loadVisibleMemoryRows(context, ids, user,
|
|
11670
|
-
loadUsers: (ids) =>
|
|
10546
|
+
loadItems: (ids) => loadVisibleMemoryRows(context, ids, user, db),
|
|
10547
|
+
loadUsers: (ids) => db("users").whereIn("id", ids).select("id", "firstname", "lastname", "email")
|
|
11671
10548
|
});
|
|
11672
10549
|
}
|
|
11673
10550
|
var cite = (s) => s.replace(/[{}",]/g, " ").replace(/\s+/g, " ").trim();
|
|
@@ -11693,16 +10570,16 @@ var resolveType = (context, raw) => {
|
|
|
11693
10570
|
const wanted = String(raw ?? "").toUpperCase();
|
|
11694
10571
|
return values.find((v) => v.toUpperCase() === wanted);
|
|
11695
10572
|
};
|
|
11696
|
-
async function creatorOf(row,
|
|
10573
|
+
async function creatorOf(row, db) {
|
|
11697
10574
|
const creator = creatorId(row.created_by);
|
|
11698
10575
|
if (creator === null) return null;
|
|
11699
|
-
const [u] = await
|
|
10576
|
+
const [u] = await db("users").whereIn("id", [creator]).select("id", "firstname", "lastname", "email");
|
|
11700
10577
|
return u ? { id: u.id, name: displayName(u) } : null;
|
|
11701
10578
|
}
|
|
11702
10579
|
async function findVisible(context, id, user) {
|
|
11703
|
-
const { db
|
|
11704
|
-
const [row] = await loadVisibleMemoryRows(context, [id], user,
|
|
11705
|
-
return { row, db
|
|
10580
|
+
const { db } = await postgresClient();
|
|
10581
|
+
const [row] = await loadVisibleMemoryRows(context, [id], user, db);
|
|
10582
|
+
return { row, db };
|
|
11706
10583
|
}
|
|
11707
10584
|
function createMemoryTools({ agent, context, user }) {
|
|
11708
10585
|
const types = memoryTypeValues(context);
|
|
@@ -11761,8 +10638,8 @@ function createMemoryTools({ agent, context, user }) {
|
|
|
11761
10638
|
let warning;
|
|
11762
10639
|
if (d?.rbac && (d.rbac.users?.length || d.rbac.roles?.length || d.rbac.teams?.length)) {
|
|
11763
10640
|
try {
|
|
11764
|
-
const { db
|
|
11765
|
-
await handleRBACUpdate(
|
|
10641
|
+
const { db } = await postgresClient();
|
|
10642
|
+
await handleRBACUpdate(db, convertContextToTableDefinition(context).name.singular, created.id, d.rbac, []);
|
|
11766
10643
|
} catch (e) {
|
|
11767
10644
|
warning = `Access grants could not be applied: ${e instanceof Error ? e.message : String(e)}`;
|
|
11768
10645
|
}
|
|
@@ -11784,15 +10661,15 @@ function createMemoryTools({ agent, context, user }) {
|
|
|
11784
10661
|
const id = typeof input?.memoryId === "string" ? input.memoryId : "";
|
|
11785
10662
|
if (!id || !user?.id) return false;
|
|
11786
10663
|
try {
|
|
11787
|
-
const { row, db
|
|
11788
|
-
return !!row && await canEditMemory(context, row, user,
|
|
10664
|
+
const { row, db } = await findVisible(context, id, user);
|
|
10665
|
+
return !!row && await canEditMemory(context, row, user, db);
|
|
11789
10666
|
} catch (e) {
|
|
11790
10667
|
console.warn(`[EXULU] memory: needsApproval check failed for "${id}":`, e instanceof Error ? e.message : e);
|
|
11791
10668
|
return false;
|
|
11792
10669
|
}
|
|
11793
10670
|
};
|
|
11794
|
-
const noAccess = async (id, row,
|
|
11795
|
-
const createdBy = row ? await creatorOf(row,
|
|
10671
|
+
const noAccess = async (id, row, db) => {
|
|
10672
|
+
const createdBy = row ? await creatorOf(row, db) : null;
|
|
11796
10673
|
const title = row?.name ?? null;
|
|
11797
10674
|
const result = createdBy ? `This memory was saved by ${createdBy.name}; only they or an admin can change it. Suggest asking them.` : "No memory with that id is available to this user.";
|
|
11798
10675
|
return { type: "memory_no_access", contextId: context.id, itemId: id, title, createdBy, result };
|
|
@@ -11816,8 +10693,8 @@ function createMemoryTools({ agent, context, user }) {
|
|
|
11816
10693
|
const { user: u, exuluConfig, memoryDecision } = params;
|
|
11817
10694
|
if (!u?.id) return err("Memory requires a signed-in user.");
|
|
11818
10695
|
const id = String(params.memoryId ?? "");
|
|
11819
|
-
const { row, db
|
|
11820
|
-
if (!row || !await canEditMemory(context, row, u,
|
|
10696
|
+
const { row, db } = await findVisible(context, id, u);
|
|
10697
|
+
if (!row || !await canEditMemory(context, row, u, db)) return noAccess(id, row, db);
|
|
11821
10698
|
const d = memoryDecision?.kind === "update" ? memoryDecision : void 0;
|
|
11822
10699
|
const patch = { id };
|
|
11823
10700
|
const information = d?.information ?? params.information;
|
|
@@ -11857,8 +10734,8 @@ function createMemoryTools({ agent, context, user }) {
|
|
|
11857
10734
|
const { user: u } = params;
|
|
11858
10735
|
if (!u?.id) return err("Memory requires a signed-in user.");
|
|
11859
10736
|
const id = String(params.memoryId ?? "");
|
|
11860
|
-
const { row, db
|
|
11861
|
-
if (!row || !await canEditMemory(context, row, u,
|
|
10737
|
+
const { row, db } = await findVisible(context, id, u);
|
|
10738
|
+
if (!row || !await canEditMemory(context, row, u, db)) return noAccess(id, row, db);
|
|
11862
10739
|
try {
|
|
11863
10740
|
await context.deleteItem({ id }, u.id, u.role?.id);
|
|
11864
10741
|
return { type: "memory_forgotten", contextId: context.id, itemId: id, title: row.name ?? "", result: `Forgot memory "${row.name ?? id}".` };
|
|
@@ -11981,9 +10858,9 @@ var checkItemWriteAccess = async (context, record, user) => {
|
|
|
11981
10858
|
return false;
|
|
11982
10859
|
}
|
|
11983
10860
|
const entity = getTableName(context.id);
|
|
11984
|
-
const { db
|
|
10861
|
+
const { db } = await postgresClient();
|
|
11985
10862
|
if (record.rights_mode === "users") {
|
|
11986
|
-
const grant = await
|
|
10863
|
+
const grant = await db.from("rbac").where({
|
|
11987
10864
|
entity,
|
|
11988
10865
|
target_resource_id: record.id,
|
|
11989
10866
|
access_type: "User",
|
|
@@ -11997,7 +10874,7 @@ var checkItemWriteAccess = async (context, record, user) => {
|
|
|
11997
10874
|
if (!roleId) {
|
|
11998
10875
|
return false;
|
|
11999
10876
|
}
|
|
12000
|
-
const grant = await
|
|
10877
|
+
const grant = await db.from("rbac").where({
|
|
12001
10878
|
entity,
|
|
12002
10879
|
target_resource_id: record.id,
|
|
12003
10880
|
access_type: "Role",
|
|
@@ -12011,7 +10888,7 @@ var checkItemWriteAccess = async (context, record, user) => {
|
|
|
12011
10888
|
if (!teamId) {
|
|
12012
10889
|
return false;
|
|
12013
10890
|
}
|
|
12014
|
-
const grant = await
|
|
10891
|
+
const grant = await db.from("rbac").where({
|
|
12015
10892
|
entity,
|
|
12016
10893
|
target_resource_id: record.id,
|
|
12017
10894
|
access_type: "Team",
|
|
@@ -12399,7 +11276,7 @@ import { randomUUID as randomUUID4 } from "crypto";
|
|
|
12399
11276
|
import { z as z12 } from "zod";
|
|
12400
11277
|
|
|
12401
11278
|
// ee/rbac-resolver.ts
|
|
12402
|
-
var RBACResolver = async (
|
|
11279
|
+
var RBACResolver = async (db, entityName, resourceId, rights_mode) => {
|
|
12403
11280
|
const license = checkLicense();
|
|
12404
11281
|
if (!license.rbac) {
|
|
12405
11282
|
return {
|
|
@@ -12409,7 +11286,7 @@ var RBACResolver = async (db2, entityName, resourceId, rights_mode) => {
|
|
|
12409
11286
|
teams: []
|
|
12410
11287
|
};
|
|
12411
11288
|
}
|
|
12412
|
-
const rbacRecords = await
|
|
11289
|
+
const rbacRecords = await db.from("rbac").where({
|
|
12413
11290
|
entity: entityName,
|
|
12414
11291
|
target_resource_id: resourceId
|
|
12415
11292
|
}).select("*");
|
|
@@ -12513,18 +11390,18 @@ var checkRecordAccess = async (record, request, user) => {
|
|
|
12513
11390
|
};
|
|
12514
11391
|
|
|
12515
11392
|
// src/skills/skill-access.ts
|
|
12516
|
-
async function resolveSkillByName(
|
|
12517
|
-
const row = await
|
|
11393
|
+
async function resolveSkillByName(db, name) {
|
|
11394
|
+
const row = await db("skills").where({ name }).first();
|
|
12518
11395
|
return row ?? null;
|
|
12519
11396
|
}
|
|
12520
|
-
async function canAccessSkill(
|
|
12521
|
-
const rbac = await RBACResolver(
|
|
11397
|
+
async function canAccessSkill(db, skill, action, user) {
|
|
11398
|
+
const rbac = await RBACResolver(db, "skill", skill.id, skill.rights_mode || "private");
|
|
12522
11399
|
return checkRecordAccess({ ...skill, RBAC: rbac }, action, user);
|
|
12523
11400
|
}
|
|
12524
|
-
async function filterReadableSkills(
|
|
11401
|
+
async function filterReadableSkills(db, skills, user) {
|
|
12525
11402
|
const out = [];
|
|
12526
11403
|
for (const s of skills) {
|
|
12527
|
-
if (await canAccessSkill(
|
|
11404
|
+
if (await canAccessSkill(db, s, "read", user)) out.push(s);
|
|
12528
11405
|
}
|
|
12529
11406
|
return out;
|
|
12530
11407
|
}
|
|
@@ -12662,11 +11539,11 @@ ${content.replace(/^\s+/, "")}`;
|
|
|
12662
11539
|
};
|
|
12663
11540
|
var generalPrefix = (config) => config?.fileUploads?.s3prefix ? `${String(config.fileUploads.s3prefix).replace(/\/+$/, "")}/` : "";
|
|
12664
11541
|
var relativePaths = (keys, config, prefix) => keys.map((f) => f.key.replace(generalPrefix(config) + prefix, "")).filter((p) => p && !p.endsWith("/"));
|
|
12665
|
-
async function resolveSkill(
|
|
11542
|
+
async function resolveSkill(db, ref) {
|
|
12666
11543
|
const value = String(ref ?? "").trim();
|
|
12667
11544
|
if (!value) return null;
|
|
12668
|
-
const byId = /^[0-9a-f-]{36}$/i.test(value) ? await
|
|
12669
|
-
return byId ?? await resolveSkillByName(
|
|
11545
|
+
const byId = /^[0-9a-f-]{36}$/i.test(value) ? await db("skills").where({ id: value }).first() : null;
|
|
11546
|
+
return byId ?? await resolveSkillByName(db, value);
|
|
12670
11547
|
}
|
|
12671
11548
|
var normalizeFiles = (raw) => {
|
|
12672
11549
|
if (!Array.isArray(raw)) return { files: [] };
|
|
@@ -12704,9 +11581,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
|
|
|
12704
11581
|
execute: async (params) => {
|
|
12705
11582
|
const { user } = params;
|
|
12706
11583
|
if (!user?.id) return err2("Skills require a signed-in user.");
|
|
12707
|
-
const
|
|
12708
|
-
const rows = await
|
|
12709
|
-
const readable = await filterReadableSkills(
|
|
11584
|
+
const db = await getDb();
|
|
11585
|
+
const rows = await db("skills").select("id", "name", "description", "current_version", "rights_mode", "created_by");
|
|
11586
|
+
const readable = await filterReadableSkills(db, rows, user);
|
|
12710
11587
|
const q = String(params.query ?? "").trim().toLowerCase();
|
|
12711
11588
|
const skills = readable.filter((s) => !q || `${s.name} ${s.description ?? ""}`.toLowerCase().includes(q)).map((s) => ({ id: s.id, name: s.name, description: s.description ?? "", version: s.current_version ?? 1 }));
|
|
12712
11589
|
return {
|
|
@@ -12733,9 +11610,9 @@ var createSkillAuthorTools = (agent, deps = {}) => {
|
|
|
12733
11610
|
execute: async (params) => {
|
|
12734
11611
|
const { user, exuluConfig } = params;
|
|
12735
11612
|
if (!user?.id) return err2("Skills require a signed-in user.");
|
|
12736
|
-
const
|
|
12737
|
-
const skill = await resolveSkill(
|
|
12738
|
-
if (!skill || !await canAccessSkill(
|
|
11613
|
+
const db = await getDb();
|
|
11614
|
+
const skill = await resolveSkill(db, params.skill);
|
|
11615
|
+
if (!skill || !await canAccessSkill(db, skill, "read", user)) {
|
|
12739
11616
|
return { type: "skill_no_access", skill: String(params.skill), result: `No skill "${params.skill}" that you can read.` };
|
|
12740
11617
|
}
|
|
12741
11618
|
const version = skill.current_version ?? 1;
|
|
@@ -12792,15 +11669,15 @@ ${content}`
|
|
|
12792
11669
|
const skillMd = files.find((f) => f.path === "SKILL.md");
|
|
12793
11670
|
if (!skillMd) return err2("A skill needs a SKILL.md at its root.");
|
|
12794
11671
|
skillMd.content = ensureFrontmatter(skillMd.content, name, description);
|
|
12795
|
-
const
|
|
12796
|
-
if (await resolveSkillByName(
|
|
11672
|
+
const db = await getDb();
|
|
11673
|
+
if (await resolveSkillByName(db, name)) return err2(`A skill named "${name}" already exists. Use skill_update to change it, or choose another name.`);
|
|
12797
11674
|
const rights_mode = decision?.rights_mode ?? "private";
|
|
12798
11675
|
const skillId = randomUUID4();
|
|
12799
11676
|
const stamp = now().toISOString();
|
|
12800
11677
|
for (const f of files) {
|
|
12801
11678
|
await io.upload(Buffer.from(f.content, "utf8"), `skills/${skillId}/v1/${f.path}`, exuluConfig, contentTypeFor(f.path));
|
|
12802
11679
|
}
|
|
12803
|
-
await
|
|
11680
|
+
await db("skills").insert({
|
|
12804
11681
|
id: skillId,
|
|
12805
11682
|
name,
|
|
12806
11683
|
description: description || parseFrontmatter(skillMd.content).description || "",
|
|
@@ -12814,7 +11691,7 @@ ${content}`
|
|
|
12814
11691
|
created_by: user.id
|
|
12815
11692
|
});
|
|
12816
11693
|
if (decision?.rbac && rights_mode !== "private" && rights_mode !== "public") {
|
|
12817
|
-
await handleRBACUpdate(
|
|
11694
|
+
await handleRBACUpdate(db, "skill", skillId, decision.rbac, []);
|
|
12818
11695
|
}
|
|
12819
11696
|
const paths = files.map((f) => f.path);
|
|
12820
11697
|
return {
|
|
@@ -12854,9 +11731,9 @@ ${content}`
|
|
|
12854
11731
|
if (!user?.id) return err2("Skills require a signed-in user.");
|
|
12855
11732
|
if (!exuluConfig?.fileUploads) return err2("File uploads are not configured on this instance, so skills cannot be stored.");
|
|
12856
11733
|
const decision = params.skillDecision?.kind === "update" ? params.skillDecision : void 0;
|
|
12857
|
-
const
|
|
12858
|
-
const skill = await resolveSkill(
|
|
12859
|
-
if (!skill || !await canAccessSkill(
|
|
11734
|
+
const db = await getDb();
|
|
11735
|
+
const skill = await resolveSkill(db, params.skill);
|
|
11736
|
+
if (!skill || !await canAccessSkill(db, skill, "write", user)) {
|
|
12860
11737
|
return { type: "skill_no_access", skill: String(params.skill), result: `No skill "${params.skill}" that you may change.` };
|
|
12861
11738
|
}
|
|
12862
11739
|
const parsed = normalizeFiles(params.files);
|
|
@@ -12894,7 +11771,7 @@ ${content}`
|
|
|
12894
11771
|
const stamp = now().toISOString();
|
|
12895
11772
|
const history = Array.isArray(skill.history) ? skill.history : [];
|
|
12896
11773
|
const label = String(decision?.label ?? params.label ?? "").trim() || `Updated in chat with ${agent.name}`;
|
|
12897
|
-
await
|
|
11774
|
+
await db("skills").where({ id: skill.id }).update({
|
|
12898
11775
|
current_version: newVersion,
|
|
12899
11776
|
updatedAt: stamp,
|
|
12900
11777
|
...description ? { description } : {},
|
|
@@ -12942,9 +11819,9 @@ import {
|
|
|
12942
11819
|
SandboxManager
|
|
12943
11820
|
} from "@anthropic-ai/sandbox-runtime";
|
|
12944
11821
|
import { mkdir, rm, writeFile, readFile as fsReadFile, readdir, stat } from "fs/promises";
|
|
12945
|
-
import { existsSync as
|
|
12946
|
-
import { join as join2, dirname, resolve as
|
|
12947
|
-
import { exec as exec2, spawn
|
|
11822
|
+
import { existsSync as existsSync4 } from "fs";
|
|
11823
|
+
import { join as join2, dirname, resolve as resolve2, relative, posix } from "path";
|
|
11824
|
+
import { exec as exec2, spawn } from "child_process";
|
|
12948
11825
|
import { promisify as promisify2 } from "util";
|
|
12949
11826
|
|
|
12950
11827
|
// ee/invoke-skills/artifact-filter.ts
|
|
@@ -12976,7 +11853,7 @@ function needsDownload(localSize, remoteSize) {
|
|
|
12976
11853
|
|
|
12977
11854
|
// src/exulu/system-dependencies.ts
|
|
12978
11855
|
import { exec } from "child_process";
|
|
12979
|
-
import { existsSync as
|
|
11856
|
+
import { existsSync as existsSync2 } from "fs";
|
|
12980
11857
|
import { join } from "path";
|
|
12981
11858
|
import { promisify } from "util";
|
|
12982
11859
|
var execAsync = promisify(exec);
|
|
@@ -13051,7 +11928,7 @@ async function probeDependency(dep) {
|
|
|
13051
11928
|
case "npm-global": {
|
|
13052
11929
|
const root = await getNpmGlobalRoot();
|
|
13053
11930
|
if (!root) return false;
|
|
13054
|
-
return
|
|
11931
|
+
return existsSync2(join(root, dep.check.packageName));
|
|
13055
11932
|
}
|
|
13056
11933
|
}
|
|
13057
11934
|
}
|
|
@@ -13285,6 +12162,41 @@ var buildSkillEnv = ({
|
|
|
13285
12162
|
};
|
|
13286
12163
|
};
|
|
13287
12164
|
|
|
12165
|
+
// ee/invoke-skills/binary-file-guard.ts
|
|
12166
|
+
var BINARY_DOCUMENT_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
12167
|
+
".pdf",
|
|
12168
|
+
".doc",
|
|
12169
|
+
".docx",
|
|
12170
|
+
".xls",
|
|
12171
|
+
".xlsx",
|
|
12172
|
+
".ppt",
|
|
12173
|
+
".pptx",
|
|
12174
|
+
".odt",
|
|
12175
|
+
".ods",
|
|
12176
|
+
".odp",
|
|
12177
|
+
".zip",
|
|
12178
|
+
".gz",
|
|
12179
|
+
".png",
|
|
12180
|
+
".jpg",
|
|
12181
|
+
".jpeg",
|
|
12182
|
+
".gif",
|
|
12183
|
+
".bmp",
|
|
12184
|
+
".tif",
|
|
12185
|
+
".tiff",
|
|
12186
|
+
".webp"
|
|
12187
|
+
]);
|
|
12188
|
+
function isBinaryDocumentPath(path3) {
|
|
12189
|
+
const dot = path3.lastIndexOf(".");
|
|
12190
|
+
if (dot < 0) return false;
|
|
12191
|
+
return BINARY_DOCUMENT_EXTENSIONS.has(path3.slice(dot).toLowerCase());
|
|
12192
|
+
}
|
|
12193
|
+
function looksBinary(content) {
|
|
12194
|
+
return content.slice(0, 8192).includes("\0");
|
|
12195
|
+
}
|
|
12196
|
+
function binaryReadHint(path3) {
|
|
12197
|
+
return `"${path3}" is a binary file \u2014 readFile would return raw bytes that cannot be interpreted and would flood the context. The text of mail attachments is already in the conversation (the <file file name=\u2026> block); for other documents use parse_document to extract the text first, then read within that extracted text.`;
|
|
12198
|
+
}
|
|
12199
|
+
|
|
13288
12200
|
// ee/invoke-skills/variable-grants.ts
|
|
13289
12201
|
var selectRowsToDecrypt = (rows) => rows.filter((row) => Boolean(row?.name) && row.allow_skill_access === true);
|
|
13290
12202
|
var deriveWithheldNames = (rows, granted) => [
|
|
@@ -13306,7 +12218,7 @@ var selectGrantedVariables = (rows) => {
|
|
|
13306
12218
|
};
|
|
13307
12219
|
|
|
13308
12220
|
// src/exulu/litellm/os-environ-names.ts
|
|
13309
|
-
import { existsSync as
|
|
12221
|
+
import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
|
|
13310
12222
|
var OS_ENVIRON_DIRECTIVE = /os\.environ\/([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
13311
12223
|
var parseOsEnvironNames = (yamlText) => {
|
|
13312
12224
|
const found = /* @__PURE__ */ new Set();
|
|
@@ -13320,7 +12232,7 @@ var parseOsEnvironNames = (yamlText) => {
|
|
|
13320
12232
|
};
|
|
13321
12233
|
var readLiteLLMOsEnvironNames = (configPath = resolveLiteLLMConfigPath()) => {
|
|
13322
12234
|
try {
|
|
13323
|
-
if (!
|
|
12235
|
+
if (!existsSync3(configPath)) return [];
|
|
13324
12236
|
return parseOsEnvironNames(readFileSync2(configPath, "utf8"));
|
|
13325
12237
|
} catch (err3) {
|
|
13326
12238
|
console.warn(
|
|
@@ -13861,8 +12773,8 @@ import { tool as tool2 } from "ai";
|
|
|
13861
12773
|
import { z as z13 } from "zod";
|
|
13862
12774
|
import CryptoJS3 from "crypto-js";
|
|
13863
12775
|
var getAllExuluVariables = async () => {
|
|
13864
|
-
const { db
|
|
13865
|
-
const rows = await
|
|
12776
|
+
const { db } = await postgresClient();
|
|
12777
|
+
const rows = await db.from("variables").select("*");
|
|
13866
12778
|
const decrypted = [];
|
|
13867
12779
|
for (const row of selectRowsToDecrypt(rows)) {
|
|
13868
12780
|
let value = row.value;
|
|
@@ -13915,18 +12827,18 @@ function probeSandboxSupport() {
|
|
|
13915
12827
|
if (process.platform !== "linux") {
|
|
13916
12828
|
return { canSandbox: false, reason: `Unsupported platform: ${process.platform}` };
|
|
13917
12829
|
}
|
|
13918
|
-
return await new Promise((
|
|
13919
|
-
const child =
|
|
12830
|
+
return await new Promise((resolve3) => {
|
|
12831
|
+
const child = spawn("bwrap", ["--dev-bind", "/", "/", "--", "/bin/true"], { env: {} });
|
|
13920
12832
|
let stderr = "";
|
|
13921
12833
|
child.stderr.on("data", (chunk) => {
|
|
13922
12834
|
stderr += chunk.toString();
|
|
13923
12835
|
});
|
|
13924
12836
|
child.on("error", (err3) => {
|
|
13925
|
-
|
|
12837
|
+
resolve3({ canSandbox: false, reason: `bwrap not executable: ${err3.message}` });
|
|
13926
12838
|
});
|
|
13927
12839
|
child.on("exit", (code) => {
|
|
13928
|
-
if (code === 0)
|
|
13929
|
-
else
|
|
12840
|
+
if (code === 0) resolve3({ canSandbox: true });
|
|
12841
|
+
else resolve3({ canSandbox: false, reason: stderr.trim() || `bwrap exited ${code}` });
|
|
13930
12842
|
});
|
|
13931
12843
|
});
|
|
13932
12844
|
})();
|
|
@@ -13972,7 +12884,7 @@ async function downloadSkill(skill, skillsDirectory, config) {
|
|
|
13972
12884
|
}
|
|
13973
12885
|
}
|
|
13974
12886
|
function isArtifactPath(absPath, sessionDir) {
|
|
13975
|
-
const resolved =
|
|
12887
|
+
const resolved = resolve2(absPath);
|
|
13976
12888
|
const rel = relative(sessionDir, resolved);
|
|
13977
12889
|
if (!rel || rel.startsWith("..")) return false;
|
|
13978
12890
|
const first = rel.split("/")[0];
|
|
@@ -14041,7 +12953,7 @@ async function restoreArtifactsFromS3(sessionDir, sessionId, userId, config, opt
|
|
|
14041
12953
|
async function downloadKeyIntoSandbox(opts) {
|
|
14042
12954
|
const { sessionId, userId, fullS3Key, config } = opts;
|
|
14043
12955
|
const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
|
|
14044
|
-
if (!
|
|
12956
|
+
if (!existsSync4(sessionDir)) {
|
|
14045
12957
|
return { written: false };
|
|
14046
12958
|
}
|
|
14047
12959
|
const userPrefix = `user_${userId}/sessions/${sessionId}/`;
|
|
@@ -14104,7 +13016,7 @@ async function createSessionSandbox(sessionId, skills, config, userId, agent) {
|
|
|
14104
13016
|
return cached.handle;
|
|
14105
13017
|
}
|
|
14106
13018
|
const sessionDir = join2("/tmp", "exulu-sessions", sessionId);
|
|
14107
|
-
const dirExisted =
|
|
13019
|
+
const dirExisted = existsSync4(sessionDir);
|
|
14108
13020
|
await mkdir(sessionDir, { recursive: true });
|
|
14109
13021
|
const skillsDirectory = join2(sessionDir, "skills");
|
|
14110
13022
|
const installedSkills = /* @__PURE__ */ new Map();
|
|
@@ -14278,7 +13190,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
|
|
|
14278
13190
|
if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir)) {
|
|
14279
13191
|
return {};
|
|
14280
13192
|
}
|
|
14281
|
-
const rel = relative(sessionDir,
|
|
13193
|
+
const rel = relative(sessionDir, resolve2(absPath));
|
|
14282
13194
|
const s3Key = artifactS3Key(sessionId, rel);
|
|
14283
13195
|
const out = {};
|
|
14284
13196
|
try {
|
|
@@ -14321,7 +13233,7 @@ Probe error: ${probe.reason ?? "(no detail)"}`
|
|
|
14321
13233
|
`mkdir -p ${shellQuote(dirname(file.path))} && cat > ${shellQuote(file.path)}`
|
|
14322
13234
|
);
|
|
14323
13235
|
await new Promise((resolveSpawn, rejectSpawn) => {
|
|
14324
|
-
const child =
|
|
13236
|
+
const child = spawn("/bin/bash", ["-c", wrapped], { env: sandboxedExecEnv });
|
|
14325
13237
|
let stderr = "";
|
|
14326
13238
|
child.stderr.on("data", (chunk) => {
|
|
14327
13239
|
stderr += chunk.toString();
|
|
@@ -14408,7 +13320,13 @@ Probe error: ${probe.reason ?? "(no detail)"}`
|
|
|
14408
13320
|
}),
|
|
14409
13321
|
execute: async ({ path: path3 }) => {
|
|
14410
13322
|
const resolvedPath = resolveSessionPath(path3, sessionDir);
|
|
13323
|
+
if (isBinaryDocumentPath(resolvedPath)) {
|
|
13324
|
+
return { content: "", error: binaryReadHint(path3) };
|
|
13325
|
+
}
|
|
14411
13326
|
const content = await customSandbox.readFile(resolvedPath);
|
|
13327
|
+
if (looksBinary(content)) {
|
|
13328
|
+
return { content: "", error: binaryReadHint(path3) };
|
|
13329
|
+
}
|
|
14412
13330
|
return { content };
|
|
14413
13331
|
}
|
|
14414
13332
|
});
|
|
@@ -14759,12 +13677,12 @@ var createSessionFileReadTool = ({
|
|
|
14759
13677
|
// src/templates/tools/parse-document-tool.ts
|
|
14760
13678
|
import { z as z15 } from "zod";
|
|
14761
13679
|
import { extname } from "path";
|
|
14762
|
-
import { parseOfficeAsync } from "officeparser";
|
|
13680
|
+
import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
|
|
14763
13681
|
|
|
14764
13682
|
// src/templates/tools/document-render-helpers.ts
|
|
14765
13683
|
import { execFile } from "child_process";
|
|
14766
13684
|
import { promisify as promisify3 } from "util";
|
|
14767
|
-
import { existsSync as
|
|
13685
|
+
import { existsSync as existsSync5 } from "fs";
|
|
14768
13686
|
import { mkdtemp, readdir as readdir2, readFile, rm as rm2, writeFile as writeFile2 } from "fs/promises";
|
|
14769
13687
|
import { tmpdir } from "os";
|
|
14770
13688
|
import { join as join3 } from "path";
|
|
@@ -14800,7 +13718,7 @@ async function convertLegacyOfficeToModern(bytes, ext) {
|
|
|
14800
13718
|
);
|
|
14801
13719
|
}
|
|
14802
13720
|
const outputPath = join3(dir, `input.${target}`);
|
|
14803
|
-
if (!
|
|
13721
|
+
if (!existsSync5(outputPath)) {
|
|
14804
13722
|
throw new Error(`LibreOffice produced no output converting "${ext}" to ${target}`);
|
|
14805
13723
|
}
|
|
14806
13724
|
return await readFile(outputPath);
|
|
@@ -14822,6 +13740,19 @@ async function pdfToText(pdf) {
|
|
|
14822
13740
|
await rm2(dir, { recursive: true, force: true });
|
|
14823
13741
|
}
|
|
14824
13742
|
}
|
|
13743
|
+
async function pdfPageCount(pdf) {
|
|
13744
|
+
const dir = await mkdtemp(join3(tmpdir(), "exulu-pdfinfo-"));
|
|
13745
|
+
try {
|
|
13746
|
+
const inputPath = join3(dir, "input.pdf");
|
|
13747
|
+
await writeFile2(inputPath, pdf);
|
|
13748
|
+
const { stdout } = await execFileAsync("pdfinfo", [inputPath], { timeout: 3e4, maxBuffer: 1e6 });
|
|
13749
|
+
const match = /^Pages:\s+(\d+)/m.exec(stdout);
|
|
13750
|
+
if (!match) throw new Error("pdfinfo did not report a page count");
|
|
13751
|
+
return Number(match[1]);
|
|
13752
|
+
} finally {
|
|
13753
|
+
await rm2(dir, { recursive: true, force: true });
|
|
13754
|
+
}
|
|
13755
|
+
}
|
|
14825
13756
|
async function renderPdfPageToPng(pdf, page, scaleTo) {
|
|
14826
13757
|
const dir = await mkdtemp(join3(tmpdir(), "exulu-render-"));
|
|
14827
13758
|
try {
|
|
@@ -14845,6 +13776,112 @@ async function renderPdfPageToPng(pdf, page, scaleTo) {
|
|
|
14845
13776
|
}
|
|
14846
13777
|
}
|
|
14847
13778
|
|
|
13779
|
+
// src/exulu/attachment-text.ts
|
|
13780
|
+
import { parseOfficeAsync } from "officeparser";
|
|
13781
|
+
var DEFAULT_ATTACHMENT_MAX_PAGES = 50;
|
|
13782
|
+
function attachmentMaxPages(env = process.env) {
|
|
13783
|
+
const raw = env.EXULU_ATTACHMENT_MAX_PAGES;
|
|
13784
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_ATTACHMENT_MAX_PAGES;
|
|
13785
|
+
const parsed = Number(raw);
|
|
13786
|
+
if (!Number.isInteger(parsed) || parsed <= 0) {
|
|
13787
|
+
console.warn(`[EXULU] EXULU_ATTACHMENT_MAX_PAGES=${JSON.stringify(raw)} is not a positive integer; using ${DEFAULT_ATTACHMENT_MAX_PAGES}.`);
|
|
13788
|
+
return DEFAULT_ATTACHMENT_MAX_PAGES;
|
|
13789
|
+
}
|
|
13790
|
+
return parsed;
|
|
13791
|
+
}
|
|
13792
|
+
function tooLongNotice(filename, pageCount, maxPages) {
|
|
13793
|
+
return `[Document too long: "${filename}" has ${pageCount} pages, the limit for attachments is ${maxPages} pages (EXULU_ATTACHMENT_MAX_PAGES). The document was NOT read. Tell the user plainly that the document is too long and ask for a shorter document or an excerpt with the relevant pages.]`;
|
|
13794
|
+
}
|
|
13795
|
+
var loadDocumentProcessor = async () => {
|
|
13796
|
+
const mod = await import("./doc_processor-E5GCE2ZT.js");
|
|
13797
|
+
return mod.documentProcessor;
|
|
13798
|
+
};
|
|
13799
|
+
function pagesToText(pages) {
|
|
13800
|
+
if (pages.length <= 1) return (pages[0]?.text ?? "").trim();
|
|
13801
|
+
return pages.map(({ page, text }) => `--- page ${page} ---
|
|
13802
|
+
${text.trim()}`).join("\n");
|
|
13803
|
+
}
|
|
13804
|
+
function pagesFromProcessor(result) {
|
|
13805
|
+
return (result ?? []).map((p) => ({
|
|
13806
|
+
page: p.page,
|
|
13807
|
+
// The VLM pass rewrites a page when OCR garbled it; prefer that text.
|
|
13808
|
+
text: (p.vlm_corrected_text ?? p.content ?? "").trim()
|
|
13809
|
+
}));
|
|
13810
|
+
}
|
|
13811
|
+
var defaultOfficeParse = async (bytes) => String(await parseOfficeAsync(bytes, { outputErrorToConsole: false, newlineDelimiter: "\n" }));
|
|
13812
|
+
async function extractDocument(input) {
|
|
13813
|
+
const config = input.exuluConfig?.attachments?.documentProcessor;
|
|
13814
|
+
if (config) {
|
|
13815
|
+
if (input.filename.toLowerCase().endsWith(".pdf")) {
|
|
13816
|
+
const maxPages = attachmentMaxPages();
|
|
13817
|
+
let pageCount;
|
|
13818
|
+
try {
|
|
13819
|
+
pageCount = await (input.countPages ?? pdfPageCount)(input.bytes);
|
|
13820
|
+
} catch (error) {
|
|
13821
|
+
console.warn(`[EXULU] Could not count pages of ${input.filename}:`, error instanceof Error ? error.message : String(error));
|
|
13822
|
+
}
|
|
13823
|
+
if (pageCount !== void 0 && pageCount > maxPages) {
|
|
13824
|
+
console.warn(`[EXULU] ${input.filename} has ${pageCount} pages, over the attachment cap of ${maxPages}; not read.`);
|
|
13825
|
+
return {
|
|
13826
|
+
pages: [],
|
|
13827
|
+
text: tooLongNotice(input.filename, pageCount, maxPages),
|
|
13828
|
+
engine: "document-processor",
|
|
13829
|
+
tooLong: { pageCount, maxPages }
|
|
13830
|
+
};
|
|
13831
|
+
}
|
|
13832
|
+
}
|
|
13833
|
+
try {
|
|
13834
|
+
const process2 = input.process ?? await loadDocumentProcessor();
|
|
13835
|
+
const result = await process2({
|
|
13836
|
+
file: input.bytes,
|
|
13837
|
+
name: input.filename,
|
|
13838
|
+
config: { ...config, attribution: { ...config.attribution, ...input.attribution } }
|
|
13839
|
+
});
|
|
13840
|
+
const pages = pagesFromProcessor(result);
|
|
13841
|
+
if (pages.some((p) => p.text.length > 0)) {
|
|
13842
|
+
return { pages, text: pagesToText(pages), engine: "document-processor" };
|
|
13843
|
+
}
|
|
13844
|
+
console.warn(`[EXULU] Document processor returned no text for ${input.filename}; falling back to officeparser.`);
|
|
13845
|
+
} catch (error) {
|
|
13846
|
+
console.warn(
|
|
13847
|
+
`[EXULU] Document processor failed for ${input.filename}; falling back to officeparser:`,
|
|
13848
|
+
error instanceof Error ? error.message : String(error)
|
|
13849
|
+
);
|
|
13850
|
+
}
|
|
13851
|
+
}
|
|
13852
|
+
const text = (await (input.officeParse ?? defaultOfficeParse)(input.bytes)).trim();
|
|
13853
|
+
return { pages: [{ page: 1, text }], text, engine: "officeparser" };
|
|
13854
|
+
}
|
|
13855
|
+
var PROCESSOR_NAMES = /* @__PURE__ */ new Set(["liteparse", "mistral", "officeparser"]);
|
|
13856
|
+
function validateAttachmentsConfig(config, license) {
|
|
13857
|
+
const processorConfig = config?.attachments?.documentProcessor;
|
|
13858
|
+
if (!processorConfig) return [];
|
|
13859
|
+
const problems = [];
|
|
13860
|
+
const name = processorConfig.processor?.name;
|
|
13861
|
+
if (!name || !PROCESSOR_NAMES.has(name)) {
|
|
13862
|
+
problems.push(`attachments.documentProcessor.processor.name must be one of ${[...PROCESSOR_NAMES].join(", ")} (got ${JSON.stringify(name)})`);
|
|
13863
|
+
}
|
|
13864
|
+
if (name === "mistral" && !processorConfig.processor.model?.trim()) {
|
|
13865
|
+
problems.push('attachments.documentProcessor.processor.model (the OCR model_name from config.litellm.yaml, e.g. "vertex-ocr") is required for the "mistral" engine');
|
|
13866
|
+
}
|
|
13867
|
+
if (processorConfig.vlm !== void 0) {
|
|
13868
|
+
if (!processorConfig.vlm.model?.trim()) {
|
|
13869
|
+
problems.push('attachments.documentProcessor.vlm.model (a LiteLLM model_name, e.g. "vertex-gemini-2.5-flash") is required when vlm is set');
|
|
13870
|
+
}
|
|
13871
|
+
if (!(Number.isInteger(processorConfig.vlm.concurrency) && processorConfig.vlm.concurrency > 0)) {
|
|
13872
|
+
problems.push("attachments.documentProcessor.vlm.concurrency must be a positive integer");
|
|
13873
|
+
}
|
|
13874
|
+
}
|
|
13875
|
+
if (!license["advanced-document-processing"]) {
|
|
13876
|
+
problems.push("attachments.documentProcessor needs the enterprise licence (advanced-document-processing); set EXULU_ENTERPRISE_LICENSE or remove the attachments config");
|
|
13877
|
+
}
|
|
13878
|
+
const rawMax = process.env.EXULU_ATTACHMENT_MAX_PAGES;
|
|
13879
|
+
if (rawMax !== void 0 && rawMax.trim() !== "" && !(Number.isInteger(Number(rawMax)) && Number(rawMax) > 0)) {
|
|
13880
|
+
problems.push(`EXULU_ATTACHMENT_MAX_PAGES must be a positive integer (got ${JSON.stringify(rawMax)}; default ${DEFAULT_ATTACHMENT_MAX_PAGES})`);
|
|
13881
|
+
}
|
|
13882
|
+
return problems;
|
|
13883
|
+
}
|
|
13884
|
+
|
|
14848
13885
|
// src/templates/tools/parse-document-tool.ts
|
|
14849
13886
|
var DEFAULT_LIMIT2 = 250;
|
|
14850
13887
|
var MAX_CONTENT_CHARS2 = 16e3;
|
|
@@ -14875,6 +13912,19 @@ var OFFICE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
14875
13912
|
".rtf"
|
|
14876
13913
|
]);
|
|
14877
13914
|
var pagesPattern = /^(\d+)(?:-(\d+))?$/;
|
|
13915
|
+
function resolvePageRange(pages, totalPages, safeName) {
|
|
13916
|
+
if (!pages) return [1, totalPages];
|
|
13917
|
+
const m = pagesPattern.exec(pages.trim());
|
|
13918
|
+
if (!m) return { error: `Invalid pages "${pages}" \u2014 use "3" or "2-5".` };
|
|
13919
|
+
const range = [Number(m[1]), Number(m[2] ?? m[1])];
|
|
13920
|
+
if (range[0] < 1 || range[0] > range[1]) {
|
|
13921
|
+
return { error: `Invalid pages "${pages}" \u2014 start must be at least 1 and not greater than the end.` };
|
|
13922
|
+
}
|
|
13923
|
+
if (range[0] > totalPages) {
|
|
13924
|
+
return { error: `Page range starts at ${range[0]} but "${safeName}" has only ${totalPages} page${totalPages === 1 ? "" : "s"}.` };
|
|
13925
|
+
}
|
|
13926
|
+
return range;
|
|
13927
|
+
}
|
|
14878
13928
|
var BINARY_DOCUMENT_EXTENSION_PATTERN = new RegExp(
|
|
14879
13929
|
`([^\\s"'\`]+\\.(?:pdf|${[...OFFICE_EXTENSIONS].map((ext) => ext.slice(1)).join("|")}))\\b`,
|
|
14880
13930
|
"i"
|
|
@@ -14926,7 +13976,21 @@ var createParseDocumentTool = ({
|
|
|
14926
13976
|
const bytes = Buffer.from(await res.arrayBuffer());
|
|
14927
13977
|
let fullText;
|
|
14928
13978
|
let totalPages;
|
|
14929
|
-
if (
|
|
13979
|
+
if (exuluConfig.attachments?.documentProcessor) {
|
|
13980
|
+
const extracted = await extractDocument({ bytes, filename: safeName, exuluConfig, attribution: { user } });
|
|
13981
|
+
if (extracted.tooLong) {
|
|
13982
|
+
return { error: extracted.text };
|
|
13983
|
+
}
|
|
13984
|
+
if (extracted.engine === "document-processor") {
|
|
13985
|
+
totalPages = extracted.pages.length;
|
|
13986
|
+
const range = resolvePageRange(pages, totalPages, safeName);
|
|
13987
|
+
if (!Array.isArray(range)) return range;
|
|
13988
|
+
const multiPage = totalPages > 1;
|
|
13989
|
+
fullText = extracted.pages.filter(({ page }) => page >= range[0] && page <= range[1]).map(({ page, text }) => multiPage ? `--- page ${page} ---
|
|
13990
|
+
${text.trim()}` : text.trim()).join("\n");
|
|
13991
|
+
}
|
|
13992
|
+
}
|
|
13993
|
+
if (fullText === void 0 && ext === ".pdf") {
|
|
14930
13994
|
const raw = await pdfToText(bytes);
|
|
14931
13995
|
const pageTexts = raw.replace(/\f$/, "").split("\f");
|
|
14932
13996
|
totalPages = pageTexts.length;
|
|
@@ -14941,29 +14005,19 @@ var createParseDocumentTool = ({
|
|
|
14941
14005
|
error: `"${safeName}" has no extractable text layer (likely a scan or image-based PDF). Use view_document_page to look at pages visually, or suggest the user add the document to a knowledge base with a document processor for full OCR.`
|
|
14942
14006
|
};
|
|
14943
14007
|
}
|
|
14944
|
-
|
|
14945
|
-
if (
|
|
14946
|
-
const m = pagesPattern.exec(pages.trim());
|
|
14947
|
-
if (!m) return { error: `Invalid pages "${pages}" \u2014 use "3" or "2-5".` };
|
|
14948
|
-
range = [Number(m[1]), Number(m[2] ?? m[1])];
|
|
14949
|
-
if (range[0] < 1 || range[0] > range[1]) {
|
|
14950
|
-
return { error: `Invalid pages "${pages}" \u2014 start must be at least 1 and not greater than the end.` };
|
|
14951
|
-
}
|
|
14952
|
-
if (range[0] > totalPages) {
|
|
14953
|
-
return { error: `Page range starts at ${range[0]} but "${safeName}" has only ${totalPages} page${totalPages === 1 ? "" : "s"}.` };
|
|
14954
|
-
}
|
|
14955
|
-
}
|
|
14008
|
+
const range = resolvePageRange(pages, totalPages, safeName);
|
|
14009
|
+
if (!Array.isArray(range)) return range;
|
|
14956
14010
|
fullText = pageTexts.map((text, i) => ({ page: i + 1, text })).filter(({ page }) => page >= range[0] && page <= range[1]).map(({ page, text }) => `--- page ${page} ---
|
|
14957
14011
|
${text.trim()}`).join("\n");
|
|
14958
|
-
} else {
|
|
14012
|
+
} else if (fullText === void 0) {
|
|
14959
14013
|
const officeBytes = isLegacyOfficeFormat(ext) ? await convertLegacyOfficeToModern(bytes, ext) : bytes;
|
|
14960
|
-
const extracted = await
|
|
14014
|
+
const extracted = await parseOfficeAsync2(officeBytes, {
|
|
14961
14015
|
outputErrorToConsole: false,
|
|
14962
14016
|
newlineDelimiter: "\n"
|
|
14963
14017
|
});
|
|
14964
14018
|
fullText = String(extracted);
|
|
14965
14019
|
}
|
|
14966
|
-
const lines = fullText.split("\n");
|
|
14020
|
+
const lines = (fullText ?? "").split("\n");
|
|
14967
14021
|
const start = (offset ?? 1) - 1;
|
|
14968
14022
|
const requested = limit ?? DEFAULT_LIMIT2;
|
|
14969
14023
|
const sliced = lines.slice(start, start + requested);
|
|
@@ -15012,7 +14066,7 @@ import { extname as extname3 } from "path";
|
|
|
15012
14066
|
|
|
15013
14067
|
// src/sessions/pdf-preview-cache.ts
|
|
15014
14068
|
import { exec as exec3 } from "child_process";
|
|
15015
|
-
import { existsSync as
|
|
14069
|
+
import { existsSync as existsSync6 } from "fs";
|
|
15016
14070
|
import { mkdir as mkdir2, readFile as readFile2, rename, rm as rm3, writeFile as writeFile3 } from "fs/promises";
|
|
15017
14071
|
import { extname as extname2, join as join4 } from "path";
|
|
15018
14072
|
import { promisify as promisify4 } from "util";
|
|
@@ -15037,7 +14091,7 @@ async function getPdfPreviewBytes(opts) {
|
|
|
15037
14091
|
throw new PreviewRenderError(`Invalid ETag for ${sourceKey}`);
|
|
15038
14092
|
}
|
|
15039
14093
|
const cachedPath = join4(CACHE_ROOT, `${safeEtag}.pdf`);
|
|
15040
|
-
if (
|
|
14094
|
+
if (existsSync6(cachedPath)) {
|
|
15041
14095
|
return readFile2(cachedPath);
|
|
15042
14096
|
}
|
|
15043
14097
|
const existing = inFlight.get(safeEtag);
|
|
@@ -15062,7 +14116,7 @@ async function getPdfPreviewBytes(opts) {
|
|
|
15062
14116
|
`LibreOffice conversion failed for ${sourceKey} (etag ${etag}): ${err3?.stderr ?? err3?.message ?? "unknown error"}`
|
|
15063
14117
|
);
|
|
15064
14118
|
}
|
|
15065
|
-
if (!
|
|
14119
|
+
if (!existsSync6(outputPath)) {
|
|
15066
14120
|
throw new PreviewRenderError(
|
|
15067
14121
|
`LibreOffice produced no output for ${sourceKey} (etag ${etag})`
|
|
15068
14122
|
);
|
|
@@ -15373,7 +14427,7 @@ var getMimeType = (type) => {
|
|
|
15373
14427
|
}
|
|
15374
14428
|
};
|
|
15375
14429
|
var hydrateVariables = async (tool3) => {
|
|
15376
|
-
const { db
|
|
14430
|
+
const { db } = await postgresClient();
|
|
15377
14431
|
const promises = tool3.config.map(async (toolConfig) => {
|
|
15378
14432
|
if (!toolConfig.variable) {
|
|
15379
14433
|
return toolConfig;
|
|
@@ -15405,7 +14459,7 @@ var hydrateVariables = async (tool3) => {
|
|
|
15405
14459
|
}
|
|
15406
14460
|
return toolConfig;
|
|
15407
14461
|
}
|
|
15408
|
-
const variable = await
|
|
14462
|
+
const variable = await db.from("variables").where({ name: variableName }).first();
|
|
15409
14463
|
if (!variable) {
|
|
15410
14464
|
throw new Error(
|
|
15411
14465
|
"Variable " + variableName + " not found in hydrateVariables method, with type " + type + "."
|
|
@@ -15454,8 +14508,8 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
|
|
|
15454
14508
|
const disabled = new Set(disabledTools ?? []);
|
|
15455
14509
|
let projectScope;
|
|
15456
14510
|
if (project && !disabled.has("agentic_context_search")) {
|
|
15457
|
-
const { db
|
|
15458
|
-
const projectRow = await
|
|
14511
|
+
const { db } = await postgresClient();
|
|
14512
|
+
const projectRow = await db.from("projects").where("id", project).first();
|
|
15459
14513
|
let rawItems = projectRow?.project_items;
|
|
15460
14514
|
if (typeof rawItems === "string") {
|
|
15461
14515
|
try {
|
|
@@ -15846,7 +14900,6 @@ var convertExuluToolsToAiSdkTools = async (currentTools, currentSkills, approved
|
|
|
15846
14900
|
|
|
15847
14901
|
export {
|
|
15848
14902
|
getToken,
|
|
15849
|
-
postgresClient,
|
|
15850
14903
|
authentication,
|
|
15851
14904
|
STATISTICS_TYPE_ENUM,
|
|
15852
14905
|
resolveLiteLLMConfigPath,
|
|
@@ -15872,27 +14925,6 @@ export {
|
|
|
15872
14925
|
BaseChunker,
|
|
15873
14926
|
SentenceChunker,
|
|
15874
14927
|
defaultChunker,
|
|
15875
|
-
LITELLM_UI_PATH,
|
|
15876
|
-
isLiteLLMEnabled,
|
|
15877
|
-
setLiteLLMPackageRoot,
|
|
15878
|
-
enableLiteLLMClientMode,
|
|
15879
|
-
startLiteLLMSupervisor,
|
|
15880
|
-
waitForLiteLLMReady,
|
|
15881
|
-
buildTags,
|
|
15882
|
-
budgetTagFor,
|
|
15883
|
-
createTaggedFetch,
|
|
15884
|
-
tagDelete,
|
|
15885
|
-
tagInfo,
|
|
15886
|
-
getTagDailyActivity,
|
|
15887
|
-
listTagsByPrefix,
|
|
15888
|
-
getBudgetSettings,
|
|
15889
|
-
setBudgetSettings,
|
|
15890
|
-
parseResetAt,
|
|
15891
|
-
upsertBudget,
|
|
15892
|
-
invalidateBudgetCaches,
|
|
15893
|
-
getTagBudgetMap,
|
|
15894
|
-
provisionDefaultUserBudget,
|
|
15895
|
-
getUserBudgetView,
|
|
15896
14928
|
resolveEmbedder,
|
|
15897
14929
|
PROJECTION_VERSION,
|
|
15898
14930
|
PROJECTION_METHOD,
|
|
@@ -15949,14 +14981,11 @@ export {
|
|
|
15949
14981
|
applyAccessControl,
|
|
15950
14982
|
applyFilters,
|
|
15951
14983
|
workflowTemplatesSchema,
|
|
15952
|
-
checkLicense,
|
|
15953
14984
|
userCredentialsSchema,
|
|
15954
14985
|
coreSchemas,
|
|
15955
14986
|
convertContextToTableDefinition,
|
|
15956
14987
|
setEntityModelSetting,
|
|
15957
14988
|
resolveEntityModel,
|
|
15958
|
-
ResolveModelError,
|
|
15959
|
-
resolveModel,
|
|
15960
14989
|
getEntitiesTableName,
|
|
15961
14990
|
getChunkEntitiesTableName,
|
|
15962
14991
|
getEntitiesForItem,
|
|
@@ -16023,6 +15052,8 @@ export {
|
|
|
16023
15052
|
SCRUBBED_CREDENTIAL_TEXT,
|
|
16024
15053
|
SCRUBBED_OAUTH_TEXT,
|
|
16025
15054
|
SESSION_FILE_READ_TOOL_NAME,
|
|
15055
|
+
extractDocument,
|
|
15056
|
+
validateAttachmentsConfig,
|
|
16026
15057
|
PARSE_DOCUMENT_TOOL_NAME,
|
|
16027
15058
|
PreviewRenderError,
|
|
16028
15059
|
getPdfPreviewBytes,
|
|
@@ -16036,7 +15067,6 @@ export {
|
|
|
16036
15067
|
CLAIM_CHECK_MAX_OUTPUT_TOKENS,
|
|
16037
15068
|
CLAIM_CHECK_DEFAULTS,
|
|
16038
15069
|
parsePipelineConfig,
|
|
16039
|
-
withRetry,
|
|
16040
15070
|
microCallProviderOptions,
|
|
16041
15071
|
microCall,
|
|
16042
15072
|
searchContexts,
|