@exulu/backend 5.7.2 → 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-RELZZYVA.js → chunk-NUEM3HMI.js} +460 -1471
- package/dist/chunk-RNZ4IDCT.js +946 -0
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-L6SESYPH.js → convert-exulu-tools-to-ai-sdk-tools-3UCQOIY6.js} +4 -2
- package/dist/doc_processor-E5GCE2ZT.js +10 -0
- package/dist/index.cjs +29584 -29401
- package/dist/index.d.cts +118 -105
- package/dist/index.d.ts +118 -105
- package/dist/index.js +144 -1049
- package/ee/invoke-skills/binary-file-guard.test.ts +0 -0
- package/ee/invoke-skills/binary-file-guard.ts +0 -0
- package/ee/python/documents/processing/doc_processor.ts +3 -3
- package/package.json +1 -1
|
@@ -0,0 +1,1166 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
import {
|
|
3
|
+
LiteLLMAdminError,
|
|
4
|
+
isLiteLLMClientMode,
|
|
5
|
+
litellmBase,
|
|
6
|
+
resolveLiteLLMTarget,
|
|
7
|
+
setLiteLLMClientMode
|
|
8
|
+
} from "./chunk-6URU62NI.js";
|
|
9
|
+
|
|
10
|
+
// src/postgres/client.ts
|
|
11
|
+
import Knex from "knex";
|
|
12
|
+
import "pgvector/knex";
|
|
13
|
+
var db = {};
|
|
14
|
+
var databaseExistsChecked = false;
|
|
15
|
+
var getDbName = () => process.env.POSTGRES_DB_NAME || "exulu";
|
|
16
|
+
async function ensureDatabaseExists() {
|
|
17
|
+
const dbName = getDbName();
|
|
18
|
+
const defaultKnex = Knex({
|
|
19
|
+
client: "pg",
|
|
20
|
+
connection: {
|
|
21
|
+
host: process.env.POSTGRES_DB_HOST,
|
|
22
|
+
port: parseInt(process.env.POSTGRES_DB_PORT || "5432"),
|
|
23
|
+
user: process.env.POSTGRES_DB_USER,
|
|
24
|
+
database: "postgres",
|
|
25
|
+
// Connect to default database
|
|
26
|
+
password: process.env.POSTGRES_DB_PASSWORD,
|
|
27
|
+
ssl: process.env.POSTGRES_DB_SSL === "true" ? { rejectUnauthorized: false } : false,
|
|
28
|
+
connectionTimeoutMillis: 1e4
|
|
29
|
+
},
|
|
30
|
+
pool: {
|
|
31
|
+
min: 2,
|
|
32
|
+
max: 4,
|
|
33
|
+
acquireTimeoutMillis: 3e4,
|
|
34
|
+
createTimeoutMillis: 3e4,
|
|
35
|
+
idleTimeoutMillis: 3e4,
|
|
36
|
+
reapIntervalMillis: 1e3,
|
|
37
|
+
createRetryIntervalMillis: 200
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
try {
|
|
41
|
+
const result = await defaultKnex.raw(`
|
|
42
|
+
SELECT 1 FROM pg_database WHERE datname = '${dbName}'
|
|
43
|
+
`);
|
|
44
|
+
if (result.rows.length === 0) {
|
|
45
|
+
console.log(`[EXULU] Database '${dbName}' does not exist. Creating it...`);
|
|
46
|
+
await defaultKnex.raw(`CREATE DATABASE ${dbName}`);
|
|
47
|
+
console.log(`[EXULU] Database '${dbName}' created successfully.`);
|
|
48
|
+
} else {
|
|
49
|
+
console.log(`[EXULU] Database '${dbName}' already exists.`);
|
|
50
|
+
}
|
|
51
|
+
} catch (error) {
|
|
52
|
+
console.error(
|
|
53
|
+
"[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.",
|
|
54
|
+
error
|
|
55
|
+
);
|
|
56
|
+
return;
|
|
57
|
+
} finally {
|
|
58
|
+
await defaultKnex.destroy();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function postgresClient() {
|
|
62
|
+
if (!db["exulu"]) {
|
|
63
|
+
try {
|
|
64
|
+
if (!databaseExistsChecked) {
|
|
65
|
+
await ensureDatabaseExists();
|
|
66
|
+
databaseExistsChecked = true;
|
|
67
|
+
}
|
|
68
|
+
const knex = Knex({
|
|
69
|
+
client: "pg",
|
|
70
|
+
connection: {
|
|
71
|
+
host: process.env.POSTGRES_DB_HOST,
|
|
72
|
+
port: parseInt(process.env.POSTGRES_DB_PORT || "5432"),
|
|
73
|
+
user: process.env.POSTGRES_DB_USER,
|
|
74
|
+
database: getDbName(),
|
|
75
|
+
password: process.env.POSTGRES_DB_PASSWORD,
|
|
76
|
+
ssl: process.env.POSTGRES_DB_SSL === "true" ? { rejectUnauthorized: false } : false,
|
|
77
|
+
// TCP keepalive prevents idle sockets from being silently dropped by
|
|
78
|
+
// intermediate network devices (NAT, firewalls) between us and Hetzner.
|
|
79
|
+
keepAlive: true,
|
|
80
|
+
keepAliveInitialDelayMillis: 1e4,
|
|
81
|
+
connectionTimeoutMillis: 3e4,
|
|
82
|
+
statement_timeout: 18e5,
|
|
83
|
+
query_timeout: 18e5
|
|
84
|
+
},
|
|
85
|
+
pool: {
|
|
86
|
+
min: 10,
|
|
87
|
+
max: 300,
|
|
88
|
+
acquireTimeoutMillis: 12e4,
|
|
89
|
+
createTimeoutMillis: 3e4,
|
|
90
|
+
idleTimeoutMillis: 3e4,
|
|
91
|
+
reapIntervalMillis: 1e3,
|
|
92
|
+
createRetryIntervalMillis: 200,
|
|
93
|
+
// Enable propagateCreateError to properly handle connection creation failures
|
|
94
|
+
propagateCreateError: false,
|
|
95
|
+
// Log pool events to help debug connection issues
|
|
96
|
+
afterCreate: (conn, done) => {
|
|
97
|
+
console.log("[EXULU] New database connection created");
|
|
98
|
+
conn.query("SET statement_timeout = 1800000; SET hnsw.ef_search = 20", (err) => {
|
|
99
|
+
if (err) {
|
|
100
|
+
console.error("[EXULU] Error setting connection parameters:", err);
|
|
101
|
+
}
|
|
102
|
+
done(err, conn);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
try {
|
|
108
|
+
await knex.schema.createExtensionIfNotExists("vector");
|
|
109
|
+
} catch (error) {
|
|
110
|
+
console.error(
|
|
111
|
+
"[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.",
|
|
112
|
+
error
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
db["exulu"] = knex;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
console.error("[EXULU] Error initializing exulu database.", error);
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
db: db["exulu"]
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/exulu/litellm/supervisor.ts
|
|
127
|
+
import { spawn } from "child_process";
|
|
128
|
+
import { existsSync } from "fs";
|
|
129
|
+
import { resolve } from "path";
|
|
130
|
+
var LITELLM_UI_PATH = "/litellm-admin";
|
|
131
|
+
var MAX_CRASHES = 5;
|
|
132
|
+
var INITIAL_BACKOFF_MS = 1e3;
|
|
133
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
134
|
+
var READY_TIMEOUT_MS = 9e4;
|
|
135
|
+
var WAIT_TIMEOUT_MS = 6e4;
|
|
136
|
+
var READY_POLL_INTERVAL_MS = 200;
|
|
137
|
+
var SHUTDOWN_GRACE_MS = 5e3;
|
|
138
|
+
var internal = {
|
|
139
|
+
child: void 0,
|
|
140
|
+
state: "idle",
|
|
141
|
+
crashCount: 0,
|
|
142
|
+
backoffMs: INITIAL_BACKOFF_MS,
|
|
143
|
+
readyPromise: void 0,
|
|
144
|
+
shutdownRequested: false
|
|
145
|
+
};
|
|
146
|
+
var isLiteLLMEnabled = () => process.env.EXULU_USE_LITELLM === "true";
|
|
147
|
+
var resolveConfig = (packageRoot) => {
|
|
148
|
+
const host = process.env.LITELLM_HOST ?? "127.0.0.1";
|
|
149
|
+
const port = process.env.LITELLM_PORT ?? "4000";
|
|
150
|
+
const masterKey = process.env.LITELLM_MASTER_KEY;
|
|
151
|
+
const configPath = process.env.LITELLM_CONFIG_PATH ?? resolve(process.cwd(), "./config.litellm.yaml");
|
|
152
|
+
const venvBin = resolve(packageRoot, "ee/python/.venv/bin");
|
|
153
|
+
const venvPython = resolve(venvBin, "python");
|
|
154
|
+
const litellmBin = resolve(venvBin, "litellm");
|
|
155
|
+
return { host, port, masterKey, configPath, venvBin, venvPython, litellmBin };
|
|
156
|
+
};
|
|
157
|
+
var log = (line) => console.log(`[EXULU-LITELLM] ${line}`);
|
|
158
|
+
var pollHealth = async (host, port) => {
|
|
159
|
+
const url = `http://${host}:${port}/health/liveliness`;
|
|
160
|
+
const deadline = Date.now() + READY_TIMEOUT_MS;
|
|
161
|
+
while (Date.now() < deadline) {
|
|
162
|
+
try {
|
|
163
|
+
const res = await fetch(url, { method: "GET" });
|
|
164
|
+
if (res.ok) return;
|
|
165
|
+
} catch {
|
|
166
|
+
}
|
|
167
|
+
await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
|
|
168
|
+
}
|
|
169
|
+
throw new Error(
|
|
170
|
+
`LiteLLM did not become ready at ${url} within ${READY_TIMEOUT_MS}ms`
|
|
171
|
+
);
|
|
172
|
+
};
|
|
173
|
+
var spawnLiteLLM = (cfg) => {
|
|
174
|
+
log(
|
|
175
|
+
`Spawning LiteLLM: ${cfg.litellmBin} --config ${cfg.configPath} --port ${cfg.port} --host ${cfg.host}`
|
|
176
|
+
);
|
|
177
|
+
const { DEBUG: _debug, ...rest } = process.env;
|
|
178
|
+
const childEnv = {
|
|
179
|
+
...rest,
|
|
180
|
+
DEBUG: "false"
|
|
181
|
+
};
|
|
182
|
+
if (!process.env.DISABLE_SCHEMA_UPDATE) {
|
|
183
|
+
childEnv.DISABLE_SCHEMA_UPDATE = "true";
|
|
184
|
+
}
|
|
185
|
+
if (LITELLM_UI_PATH && !process.env.SERVER_ROOT_PATH) {
|
|
186
|
+
childEnv.SERVER_ROOT_PATH = LITELLM_UI_PATH;
|
|
187
|
+
}
|
|
188
|
+
const child = spawn(
|
|
189
|
+
cfg.litellmBin,
|
|
190
|
+
[
|
|
191
|
+
"--config",
|
|
192
|
+
cfg.configPath,
|
|
193
|
+
"--port",
|
|
194
|
+
cfg.port,
|
|
195
|
+
"--host",
|
|
196
|
+
cfg.host
|
|
197
|
+
],
|
|
198
|
+
{
|
|
199
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
200
|
+
env: childEnv
|
|
201
|
+
}
|
|
202
|
+
);
|
|
203
|
+
child.stdout?.on("data", (chunk) => {
|
|
204
|
+
chunk.toString().split("\n").filter((l) => l.length > 0).forEach((l) => log(l));
|
|
205
|
+
});
|
|
206
|
+
child.stderr?.on("data", (chunk) => {
|
|
207
|
+
chunk.toString().split("\n").filter((l) => l.length > 0).forEach((l) => log(`stderr: ${l}`));
|
|
208
|
+
});
|
|
209
|
+
return child;
|
|
210
|
+
};
|
|
211
|
+
var supervise = async (cfg) => {
|
|
212
|
+
while (!internal.shutdownRequested && internal.crashCount < MAX_CRASHES) {
|
|
213
|
+
internal.state = internal.crashCount === 0 ? "starting" : "respawning";
|
|
214
|
+
internal.child = spawnLiteLLM(cfg);
|
|
215
|
+
const exitPromise = new Promise((resolveFn) => {
|
|
216
|
+
internal.child.on("exit", (code2) => resolveFn(code2));
|
|
217
|
+
});
|
|
218
|
+
try {
|
|
219
|
+
await Promise.race([
|
|
220
|
+
pollHealth(cfg.host, cfg.port).then(() => "ready"),
|
|
221
|
+
exitPromise.then((code2) => ({ exited: code2 }))
|
|
222
|
+
]);
|
|
223
|
+
} catch (err) {
|
|
224
|
+
log(`Readiness probe failed: ${err.message}`);
|
|
225
|
+
try {
|
|
226
|
+
internal.child?.kill("SIGTERM");
|
|
227
|
+
} catch {
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (!internal.child?.killed && internal.child?.exitCode === null) {
|
|
231
|
+
internal.state = "ready";
|
|
232
|
+
internal.crashCount = 0;
|
|
233
|
+
internal.backoffMs = INITIAL_BACKOFF_MS;
|
|
234
|
+
log("LiteLLM is ready.");
|
|
235
|
+
}
|
|
236
|
+
const code = await exitPromise;
|
|
237
|
+
internal.state = "respawning";
|
|
238
|
+
internal.child = void 0;
|
|
239
|
+
if (internal.shutdownRequested) {
|
|
240
|
+
log("Child exited during shutdown; supervisor stopping.");
|
|
241
|
+
internal.state = "stopped";
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
internal.crashCount += 1;
|
|
245
|
+
log(
|
|
246
|
+
`LiteLLM exited (code=${code}). Crash ${internal.crashCount}/${MAX_CRASHES}. Respawning in ${internal.backoffMs}ms.`
|
|
247
|
+
);
|
|
248
|
+
if (internal.crashCount >= MAX_CRASHES) {
|
|
249
|
+
log(
|
|
250
|
+
"LiteLLM keeps crashing \u2014 fix the config and restart Exulu. Giving up on respawn."
|
|
251
|
+
);
|
|
252
|
+
internal.state = "given_up";
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
await new Promise((r) => setTimeout(r, internal.backoffMs));
|
|
256
|
+
internal.backoffMs = Math.min(internal.backoffMs * 2, MAX_BACKOFF_MS);
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
var _packageRoot;
|
|
260
|
+
var setLiteLLMPackageRoot = (root) => {
|
|
261
|
+
_packageRoot = root;
|
|
262
|
+
};
|
|
263
|
+
var enableLiteLLMClientMode = () => {
|
|
264
|
+
if (internal.readyPromise) return;
|
|
265
|
+
setLiteLLMClientMode(true);
|
|
266
|
+
};
|
|
267
|
+
var startLiteLLMSupervisor = async (options = {}) => {
|
|
268
|
+
if (!isLiteLLMEnabled()) return;
|
|
269
|
+
if (internal.readyPromise) {
|
|
270
|
+
return internal.readyPromise;
|
|
271
|
+
}
|
|
272
|
+
if (!process.env.LITELLM_MASTER_KEY) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
"EXULU_USE_LITELLM is true but LITELLM_MASTER_KEY is not set. Set LITELLM_MASTER_KEY to a strong secret and restart Exulu."
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
const packageRoot = options.packageRoot ?? _packageRoot;
|
|
278
|
+
if (!packageRoot) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
"LiteLLM supervisor: package root not set. Call setLiteLLMPackageRoot() from the boot path before starting the supervisor."
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
const cfg = resolveConfig(packageRoot);
|
|
284
|
+
if (!existsSync(cfg.configPath)) {
|
|
285
|
+
log(
|
|
286
|
+
`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.`
|
|
287
|
+
);
|
|
288
|
+
internal.state = "given_up";
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (!existsSync(cfg.litellmBin)) {
|
|
292
|
+
log(
|
|
293
|
+
`LiteLLM binary not found at ${cfg.litellmBin}. The Python venv may not be set up. Run setupPythonEnvironment() from @exulu/backend, then restart.`
|
|
294
|
+
);
|
|
295
|
+
internal.state = "given_up";
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
internal.readyPromise = (async () => {
|
|
299
|
+
supervise(cfg);
|
|
300
|
+
const deadline = Date.now() + READY_TIMEOUT_MS + 5e3;
|
|
301
|
+
while (Date.now() < deadline) {
|
|
302
|
+
if (internal.state === "ready") return;
|
|
303
|
+
if (internal.state === "given_up") {
|
|
304
|
+
throw new Error("LiteLLM supervisor gave up before becoming ready.");
|
|
305
|
+
}
|
|
306
|
+
await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
|
|
307
|
+
}
|
|
308
|
+
throw new Error("Timed out waiting for LiteLLM supervisor readiness.");
|
|
309
|
+
})();
|
|
310
|
+
registerShutdownHandlers();
|
|
311
|
+
return internal.readyPromise;
|
|
312
|
+
};
|
|
313
|
+
var waitForLiteLLMReady = async () => {
|
|
314
|
+
if (!isLiteLLMEnabled()) return;
|
|
315
|
+
if (isLiteLLMClientMode()) {
|
|
316
|
+
if (internal.state === "ready") return;
|
|
317
|
+
const { baseUrl, authHeaders, remote } = resolveLiteLLMTarget();
|
|
318
|
+
const url = remote ? `${baseUrl}/v1/models` : `${baseUrl}/health/liveliness`;
|
|
319
|
+
let res;
|
|
320
|
+
try {
|
|
321
|
+
res = await fetch(url, { method: "GET", headers: remote ? authHeaders : {} });
|
|
322
|
+
} catch (err) {
|
|
323
|
+
throw new Error(
|
|
324
|
+
`LiteLLM proxy not reachable at ${url} (is the Exulu server process running?): ${err.message}`
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
if (!res.ok) {
|
|
328
|
+
throw new Error(
|
|
329
|
+
`LiteLLM proxy health probe at ${url} returned ${res.status}.`
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
internal.state = "ready";
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (!internal.readyPromise) {
|
|
336
|
+
return startLiteLLMSupervisor();
|
|
337
|
+
}
|
|
338
|
+
const deadline = Date.now() + WAIT_TIMEOUT_MS;
|
|
339
|
+
while (Date.now() < deadline) {
|
|
340
|
+
const s = getSupervisorState();
|
|
341
|
+
if (s === "ready") return;
|
|
342
|
+
if (s === "given_up") {
|
|
343
|
+
throw new Error("LiteLLM supervisor has given up.");
|
|
344
|
+
}
|
|
345
|
+
await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
|
|
346
|
+
}
|
|
347
|
+
throw new Error("Timed out waiting for LiteLLM to become ready.");
|
|
348
|
+
};
|
|
349
|
+
var stopLiteLLM = (signal = "SIGTERM") => {
|
|
350
|
+
internal.shutdownRequested = true;
|
|
351
|
+
const child = internal.child;
|
|
352
|
+
if (!child) return;
|
|
353
|
+
try {
|
|
354
|
+
child.kill(signal);
|
|
355
|
+
} catch {
|
|
356
|
+
}
|
|
357
|
+
setTimeout(() => {
|
|
358
|
+
try {
|
|
359
|
+
if (!child.killed && child.exitCode === null) {
|
|
360
|
+
child.kill("SIGKILL");
|
|
361
|
+
}
|
|
362
|
+
} catch {
|
|
363
|
+
}
|
|
364
|
+
}, SHUTDOWN_GRACE_MS).unref();
|
|
365
|
+
};
|
|
366
|
+
var shutdownHandlersRegistered = false;
|
|
367
|
+
var registerShutdownHandlers = () => {
|
|
368
|
+
if (shutdownHandlersRegistered) return;
|
|
369
|
+
shutdownHandlersRegistered = true;
|
|
370
|
+
process.on("SIGINT", () => stopLiteLLM("SIGTERM"));
|
|
371
|
+
process.on("SIGTERM", () => stopLiteLLM("SIGTERM"));
|
|
372
|
+
process.on("exit", () => stopLiteLLM("SIGTERM"));
|
|
373
|
+
};
|
|
374
|
+
var getSupervisorState = () => internal.state;
|
|
375
|
+
|
|
376
|
+
// ee/entitlements.ts
|
|
377
|
+
var ENTITLEMENTS = {
|
|
378
|
+
"rbac": false,
|
|
379
|
+
"advanced-markdown-chunker": false,
|
|
380
|
+
"agentic-retrieval": false,
|
|
381
|
+
"queues": false,
|
|
382
|
+
"custom-branding": false,
|
|
383
|
+
"evals": false,
|
|
384
|
+
"template-conversations": false,
|
|
385
|
+
"agent-feedback": false,
|
|
386
|
+
"multi-agent-tooling": false,
|
|
387
|
+
"advanced-document-processing": false,
|
|
388
|
+
"rate-limits": false,
|
|
389
|
+
"claim-check": false
|
|
390
|
+
};
|
|
391
|
+
var checkLicense = () => {
|
|
392
|
+
if (!process.env.EXULU_ENTERPRISE_LICENSE || process.env.EXULU_ENTERPRISE_LICENSE === "" || !process.env.EXULU_ENTERPRISE_LICENSE.startsWith("EXULU_EE_")) {
|
|
393
|
+
return ENTITLEMENTS;
|
|
394
|
+
} else {
|
|
395
|
+
return {
|
|
396
|
+
"rbac": true,
|
|
397
|
+
"advanced-markdown-chunker": true,
|
|
398
|
+
"agentic-retrieval": true,
|
|
399
|
+
"mcp": true,
|
|
400
|
+
"queues": true,
|
|
401
|
+
"prompt-library": true,
|
|
402
|
+
"custom-branding": true,
|
|
403
|
+
"evals": true,
|
|
404
|
+
"template-conversations": true,
|
|
405
|
+
"agent-feedback": true,
|
|
406
|
+
"multi-agent-tooling": true,
|
|
407
|
+
"advanced-document-processing": true,
|
|
408
|
+
"rate-limits": true,
|
|
409
|
+
"claim-check": true
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
// src/exulu/resolve-model.ts
|
|
415
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
416
|
+
|
|
417
|
+
// src/exulu/tags.ts
|
|
418
|
+
var MAX_LEN = 63;
|
|
419
|
+
function sanitizeTagValue(raw) {
|
|
420
|
+
if (raw === void 0 || raw === null) return void 0;
|
|
421
|
+
const s = String(raw).normalize("NFKC").toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
422
|
+
return s.slice(0, MAX_LEN);
|
|
423
|
+
}
|
|
424
|
+
function buildTags(input) {
|
|
425
|
+
const candidates = [];
|
|
426
|
+
if (input.user_id) {
|
|
427
|
+
candidates.push("user_id_" + input.user_id);
|
|
428
|
+
}
|
|
429
|
+
if (input.user_name) {
|
|
430
|
+
candidates.push("user_name_" + input.user_name);
|
|
431
|
+
}
|
|
432
|
+
if (input.role_id) {
|
|
433
|
+
candidates.push("role_id_" + input.role_id);
|
|
434
|
+
}
|
|
435
|
+
if (input.role_name) {
|
|
436
|
+
candidates.push("role_name_" + input.role_name);
|
|
437
|
+
}
|
|
438
|
+
if (input.project_id) {
|
|
439
|
+
candidates.push("project_id_" + input.project_id);
|
|
440
|
+
}
|
|
441
|
+
if (input.project_name) {
|
|
442
|
+
candidates.push("project_name_" + input.project_name);
|
|
443
|
+
}
|
|
444
|
+
if (input.agent_id) {
|
|
445
|
+
candidates.push("agent_id_" + input.agent_id);
|
|
446
|
+
}
|
|
447
|
+
if (input.agent_name) {
|
|
448
|
+
candidates.push("agent_name_" + input.agent_name);
|
|
449
|
+
}
|
|
450
|
+
if (input.team_id) {
|
|
451
|
+
candidates.push("team_id_" + input.team_id);
|
|
452
|
+
}
|
|
453
|
+
if (input.team_name) {
|
|
454
|
+
candidates.push("team_name_" + input.team_name);
|
|
455
|
+
}
|
|
456
|
+
if (input.routine_id) {
|
|
457
|
+
candidates.push("routine_id_" + input.routine_id);
|
|
458
|
+
}
|
|
459
|
+
if (input.routine_name) {
|
|
460
|
+
candidates.push("routine_name_" + input.routine_name);
|
|
461
|
+
}
|
|
462
|
+
if (input.context_id) {
|
|
463
|
+
candidates.push("context_id_" + input.context_id);
|
|
464
|
+
}
|
|
465
|
+
if (input.context_name) {
|
|
466
|
+
candidates.push("context_name_" + input.context_name);
|
|
467
|
+
}
|
|
468
|
+
console.log("[EXULU] Candidates", candidates);
|
|
469
|
+
const out = [];
|
|
470
|
+
for (const candidate of candidates) {
|
|
471
|
+
if (candidate === void 0 || candidate === null) continue;
|
|
472
|
+
const value = sanitizeTagValue(candidate);
|
|
473
|
+
console.log("[EXULU] Sanitized tag value", value);
|
|
474
|
+
if (value === void 0 || value === "") continue;
|
|
475
|
+
out.push(value);
|
|
476
|
+
}
|
|
477
|
+
return out;
|
|
478
|
+
}
|
|
479
|
+
function budgetTagFor(entityType, id) {
|
|
480
|
+
const value = sanitizeTagValue(`${entityType}_id_${id}`);
|
|
481
|
+
return value ?? "";
|
|
482
|
+
}
|
|
483
|
+
function decodeBody(body) {
|
|
484
|
+
if (typeof body === "string") return body;
|
|
485
|
+
if (body instanceof Uint8Array) return new TextDecoder().decode(body);
|
|
486
|
+
return void 0;
|
|
487
|
+
}
|
|
488
|
+
function stripContentLengthHeader(headers) {
|
|
489
|
+
if (!headers) return headers;
|
|
490
|
+
if (typeof headers.delete === "function") {
|
|
491
|
+
const clone = new globalThis.Headers(headers);
|
|
492
|
+
clone.delete("content-length");
|
|
493
|
+
return clone;
|
|
494
|
+
}
|
|
495
|
+
if (Array.isArray(headers)) {
|
|
496
|
+
return headers.filter(
|
|
497
|
+
([k]) => k.toLowerCase() !== "content-length"
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
const out = {};
|
|
501
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
502
|
+
if (k.toLowerCase() === "content-length") continue;
|
|
503
|
+
out[k] = v;
|
|
504
|
+
}
|
|
505
|
+
return out;
|
|
506
|
+
}
|
|
507
|
+
function createTaggedFetch(tags) {
|
|
508
|
+
const labeled = async (input, init) => {
|
|
509
|
+
try {
|
|
510
|
+
if (!init || !init.body) return globalThis.fetch(input, init);
|
|
511
|
+
const method = (init.method ?? "POST").toUpperCase();
|
|
512
|
+
if (method !== "POST" && method !== "PUT" && method !== "PATCH") {
|
|
513
|
+
return globalThis.fetch(input, init);
|
|
514
|
+
}
|
|
515
|
+
const decoded = decodeBody(init.body);
|
|
516
|
+
if (decoded === void 0) {
|
|
517
|
+
console.warn("[vertex-labels] unsupported body type, forwarding unchanged");
|
|
518
|
+
return globalThis.fetch(input, init);
|
|
519
|
+
}
|
|
520
|
+
let parsed;
|
|
521
|
+
try {
|
|
522
|
+
parsed = JSON.parse(decoded);
|
|
523
|
+
} catch {
|
|
524
|
+
console.warn("[vertex-labels] body is not JSON, forwarding unchanged");
|
|
525
|
+
return globalThis.fetch(input, init);
|
|
526
|
+
}
|
|
527
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
528
|
+
return globalThis.fetch(input, init);
|
|
529
|
+
}
|
|
530
|
+
const existing = parsed.metadata ?? {};
|
|
531
|
+
parsed.metadata = { ...existing, tags };
|
|
532
|
+
console.log("[EXULU] tags", parsed.metadata);
|
|
533
|
+
const nextInit = {
|
|
534
|
+
...init,
|
|
535
|
+
body: JSON.stringify(parsed),
|
|
536
|
+
headers: stripContentLengthHeader(init.headers)
|
|
537
|
+
};
|
|
538
|
+
return globalThis.fetch(input, nextInit);
|
|
539
|
+
} catch (err) {
|
|
540
|
+
console.warn("[vertex-labels] label injection failed, forwarding unchanged", err);
|
|
541
|
+
return globalThis.fetch(input, init);
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
return labeled;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// src/exulu/litellm/admin-client.ts
|
|
548
|
+
async function call(path, body) {
|
|
549
|
+
const { url, masterKey } = litellmBase();
|
|
550
|
+
const res = await fetch(`${url}${path}`, {
|
|
551
|
+
method: "POST",
|
|
552
|
+
headers: {
|
|
553
|
+
Authorization: `Bearer ${masterKey}`,
|
|
554
|
+
"Content-Type": "application/json"
|
|
555
|
+
},
|
|
556
|
+
body: JSON.stringify(body)
|
|
557
|
+
});
|
|
558
|
+
if (!res.ok) {
|
|
559
|
+
const text = await res.text().catch(() => "");
|
|
560
|
+
throw new LiteLLMAdminError(
|
|
561
|
+
`LiteLLM ${path} returned ${res.status}: ${text}`,
|
|
562
|
+
res.status
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
return await res.json().catch(() => ({}));
|
|
566
|
+
}
|
|
567
|
+
async function tagNew(input) {
|
|
568
|
+
await call("/tag/new", {
|
|
569
|
+
name: input.name,
|
|
570
|
+
max_budget: input.max_budget,
|
|
571
|
+
budget_duration: input.budget_duration
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
async function tagUpdate(input) {
|
|
575
|
+
await call("/tag/update", {
|
|
576
|
+
name: input.name,
|
|
577
|
+
max_budget: input.max_budget,
|
|
578
|
+
budget_duration: input.budget_duration
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
async function budgetUpdate(budget_id, patch) {
|
|
582
|
+
await call("/budget/update", { budget_id, ...patch });
|
|
583
|
+
}
|
|
584
|
+
async function tagDelete(name) {
|
|
585
|
+
await call("/tag/delete", { name });
|
|
586
|
+
}
|
|
587
|
+
function extractBudget(raw) {
|
|
588
|
+
const bt = raw?.litellm_budget_table ?? {};
|
|
589
|
+
const max_budget = bt.max_budget ?? raw?.max_budget ?? null;
|
|
590
|
+
const budget_duration = bt.budget_duration ?? raw?.budget_duration ?? null;
|
|
591
|
+
const budget_reset_at = bt.budget_reset_at ?? raw?.budget_reset_at ?? null;
|
|
592
|
+
const budget_id = bt.budget_id ?? raw?.budget_id ?? null;
|
|
593
|
+
const spend = typeof raw?.spend === "number" ? raw.spend : typeof bt.spend === "number" ? bt.spend : 0;
|
|
594
|
+
return { max_budget, budget_duration, budget_reset_at, budget_id, spend };
|
|
595
|
+
}
|
|
596
|
+
async function listTags() {
|
|
597
|
+
const { url, masterKey } = litellmBase();
|
|
598
|
+
const res = await fetch(`${url}/tag/list`, {
|
|
599
|
+
method: "GET",
|
|
600
|
+
headers: { Authorization: `Bearer ${masterKey}` }
|
|
601
|
+
});
|
|
602
|
+
if (!res.ok) {
|
|
603
|
+
const text = await res.text().catch(() => "");
|
|
604
|
+
throw new LiteLLMAdminError(
|
|
605
|
+
`LiteLLM /tag/list returned ${res.status}: ${text}`,
|
|
606
|
+
res.status
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
const json = await res.json().catch(() => []);
|
|
610
|
+
if (Array.isArray(json)) return json;
|
|
611
|
+
if (json && typeof json === "object") return Object.values(json);
|
|
612
|
+
return [];
|
|
613
|
+
}
|
|
614
|
+
async function listTagBudgets() {
|
|
615
|
+
const entries = await listTags();
|
|
616
|
+
const map = {};
|
|
617
|
+
for (const e of entries) {
|
|
618
|
+
const name = e?.name ?? e?.tag_name;
|
|
619
|
+
if (typeof name !== "string") continue;
|
|
620
|
+
const b = extractBudget(e);
|
|
621
|
+
if (b.max_budget == null) continue;
|
|
622
|
+
map[name] = {
|
|
623
|
+
name,
|
|
624
|
+
spend: b.spend,
|
|
625
|
+
max_budget: b.max_budget,
|
|
626
|
+
budget_duration: b.budget_duration,
|
|
627
|
+
budget_reset_at: b.budget_reset_at,
|
|
628
|
+
budget_id: b.budget_id
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
const names = Object.keys(map);
|
|
632
|
+
if (names.length > 0) {
|
|
633
|
+
try {
|
|
634
|
+
const info = await tagInfo(names);
|
|
635
|
+
for (const name of names) {
|
|
636
|
+
const ti = info[name];
|
|
637
|
+
const entry = map[name];
|
|
638
|
+
if (ti && entry) entry.spend = ti.spend;
|
|
639
|
+
}
|
|
640
|
+
} catch {
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return map;
|
|
644
|
+
}
|
|
645
|
+
async function tagInfo(names) {
|
|
646
|
+
const out = {};
|
|
647
|
+
for (const n of names) out[n] = null;
|
|
648
|
+
if (names.length === 0) return out;
|
|
649
|
+
let json;
|
|
650
|
+
try {
|
|
651
|
+
json = await call("/tag/info", { names });
|
|
652
|
+
} catch (err) {
|
|
653
|
+
if (err instanceof LiteLLMAdminError && /not found/i.test(err.message)) {
|
|
654
|
+
return out;
|
|
655
|
+
}
|
|
656
|
+
throw err;
|
|
657
|
+
}
|
|
658
|
+
for (const name of names) {
|
|
659
|
+
const raw = json?.[name];
|
|
660
|
+
if (!raw) {
|
|
661
|
+
out[name] = null;
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
const b = extractBudget(raw);
|
|
665
|
+
if (b.max_budget == null) {
|
|
666
|
+
out[name] = null;
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
out[name] = {
|
|
670
|
+
name,
|
|
671
|
+
spend: b.spend,
|
|
672
|
+
max_budget: b.max_budget,
|
|
673
|
+
budget_duration: b.budget_duration,
|
|
674
|
+
budget_reset_at: b.budget_reset_at,
|
|
675
|
+
budget_id: b.budget_id
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
return out;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// src/exulu/litellm/activity-client.ts
|
|
682
|
+
var SANITIZE_MAX_LEN = 63;
|
|
683
|
+
function sanitizeTagPrefix(raw) {
|
|
684
|
+
return String(raw).normalize("NFKC").toLowerCase().replace(/[^a-z0-9_-]/g, "-").slice(0, SANITIZE_MAX_LEN);
|
|
685
|
+
}
|
|
686
|
+
var TAG_LIST_TTL_MS = 3e4;
|
|
687
|
+
var tagListCache = null;
|
|
688
|
+
async function getCachedTagList() {
|
|
689
|
+
const now = Date.now();
|
|
690
|
+
if (tagListCache && now - tagListCache.fetchedAt < TAG_LIST_TTL_MS) {
|
|
691
|
+
return tagListCache.tags;
|
|
692
|
+
}
|
|
693
|
+
const tags = await listTags();
|
|
694
|
+
tagListCache = { fetchedAt: now, tags };
|
|
695
|
+
return tags;
|
|
696
|
+
}
|
|
697
|
+
async function getTagDailyActivity(params) {
|
|
698
|
+
const { url, masterKey } = litellmBase();
|
|
699
|
+
const qs = new URLSearchParams();
|
|
700
|
+
qs.set("start_date", params.startDate);
|
|
701
|
+
qs.set("end_date", params.endDate);
|
|
702
|
+
if (params.tags && params.tags.length > 0) {
|
|
703
|
+
qs.set("tags", params.tags.join(","));
|
|
704
|
+
}
|
|
705
|
+
if (params.model) qs.set("model", params.model);
|
|
706
|
+
if (params.page != null) qs.set("page", String(params.page));
|
|
707
|
+
if (params.pageSize != null) qs.set("page_size", String(params.pageSize));
|
|
708
|
+
if (params.excludeTeamTags != null) {
|
|
709
|
+
qs.set("exclude_team_tags", params.excludeTeamTags ? "true" : "false");
|
|
710
|
+
}
|
|
711
|
+
const res = await fetch(`${url}/tag/daily/activity?${qs.toString()}`, {
|
|
712
|
+
method: "GET",
|
|
713
|
+
headers: { Authorization: `Bearer ${masterKey}` }
|
|
714
|
+
});
|
|
715
|
+
if (!res.ok) {
|
|
716
|
+
const text = await res.text().catch(() => "");
|
|
717
|
+
throw new LiteLLMAdminError(
|
|
718
|
+
`LiteLLM /tag/daily/activity returned ${res.status}: ${text}`,
|
|
719
|
+
res.status
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
return await res.json().catch(() => ({}));
|
|
723
|
+
}
|
|
724
|
+
async function getTagSpendByWindow(windows, endDate) {
|
|
725
|
+
const windowEntries = Object.entries(windows);
|
|
726
|
+
const out = {};
|
|
727
|
+
for (const [tag] of windowEntries) out[tag] = 0;
|
|
728
|
+
if (windowEntries.length === 0) return out;
|
|
729
|
+
let startDate = windowEntries[0][1];
|
|
730
|
+
for (const [, start] of windowEntries) {
|
|
731
|
+
if (start < startDate) startDate = start;
|
|
732
|
+
}
|
|
733
|
+
const tags = windowEntries.map(([tag]) => tag);
|
|
734
|
+
const MAX_PAGES = 50;
|
|
735
|
+
const PAGE_SIZE = 1e3;
|
|
736
|
+
for (let page = 1; page <= MAX_PAGES; page++) {
|
|
737
|
+
const json = await getTagDailyActivity({
|
|
738
|
+
startDate,
|
|
739
|
+
endDate,
|
|
740
|
+
tags,
|
|
741
|
+
page,
|
|
742
|
+
pageSize: PAGE_SIZE
|
|
743
|
+
});
|
|
744
|
+
const results = Array.isArray(json?.results) ? json.results : [];
|
|
745
|
+
for (const row of results) {
|
|
746
|
+
const date = typeof row?.date === "string" ? row.date : null;
|
|
747
|
+
if (!date) continue;
|
|
748
|
+
const entities = row?.breakdown?.entities;
|
|
749
|
+
if (!entities || typeof entities !== "object") continue;
|
|
750
|
+
for (const [tag, windowStart] of windowEntries) {
|
|
751
|
+
if (date < windowStart) continue;
|
|
752
|
+
const ed = entities[tag];
|
|
753
|
+
if (!ed) continue;
|
|
754
|
+
const m = ed?.metrics ?? ed;
|
|
755
|
+
const raw = m?.spend;
|
|
756
|
+
const spend = typeof raw === "number" ? raw : Number(raw);
|
|
757
|
+
if (Number.isFinite(spend)) out[tag] = (out[tag] ?? 0) + spend;
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const meta = json?.metadata ?? {};
|
|
761
|
+
const totalPages = Number(meta?.total_pages ?? json?.total_pages ?? 0);
|
|
762
|
+
const hasMore = Boolean(meta?.has_more ?? json?.has_more ?? false);
|
|
763
|
+
if (results.length === 0) break;
|
|
764
|
+
if (totalPages ? page >= totalPages : !hasMore) break;
|
|
765
|
+
}
|
|
766
|
+
return out;
|
|
767
|
+
}
|
|
768
|
+
async function listTagsByPrefix(prefix) {
|
|
769
|
+
const sanitised = sanitizeTagPrefix(prefix);
|
|
770
|
+
if (!sanitised) return { sanitisedPrefix: "", names: [] };
|
|
771
|
+
const all = await getCachedTagList();
|
|
772
|
+
const names = [];
|
|
773
|
+
for (const e of all) {
|
|
774
|
+
const name = e?.name ?? e?.tag_name;
|
|
775
|
+
if (typeof name !== "string") continue;
|
|
776
|
+
if (name.startsWith(sanitised)) names.push(name);
|
|
777
|
+
}
|
|
778
|
+
return { sanitisedPrefix: sanitised, names };
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// src/exulu/litellm/budget-service.ts
|
|
782
|
+
var SETTINGS_KEY = "budget_settings";
|
|
783
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
784
|
+
function ymd(d) {
|
|
785
|
+
return d.toISOString().slice(0, 10);
|
|
786
|
+
}
|
|
787
|
+
function durationToDays(duration) {
|
|
788
|
+
if (!duration) return 30;
|
|
789
|
+
const m = /^\s*(\d+(?:\.\d+)?)\s*(mo|[a-z]+)?\s*$/i.exec(String(duration));
|
|
790
|
+
if (!m) return 30;
|
|
791
|
+
const n = parseFloat(m[1]);
|
|
792
|
+
if (!Number.isFinite(n) || n <= 0) return 30;
|
|
793
|
+
switch ((m[2] ?? "d").toLowerCase()) {
|
|
794
|
+
case "h":
|
|
795
|
+
return n / 24;
|
|
796
|
+
case "w":
|
|
797
|
+
return n * 7;
|
|
798
|
+
case "mo":
|
|
799
|
+
return n * 30;
|
|
800
|
+
case "y":
|
|
801
|
+
return n * 365;
|
|
802
|
+
default:
|
|
803
|
+
return n;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
function subtractDuration(date, duration) {
|
|
807
|
+
const m = /^\s*(\d+(?:\.\d+)?)\s*(mo|[a-z]+)?\s*$/i.exec(String(duration ?? ""));
|
|
808
|
+
const unit = m ? (m[2] ?? "d").toLowerCase() : "d";
|
|
809
|
+
const n = m ? parseFloat(m[1]) : NaN;
|
|
810
|
+
if (unit === "mo" && Number.isFinite(n) && n > 0) {
|
|
811
|
+
const result = new Date(date);
|
|
812
|
+
result.setUTCMonth(result.getUTCMonth() - Math.round(n));
|
|
813
|
+
return result;
|
|
814
|
+
}
|
|
815
|
+
return new Date(date.getTime() - durationToDays(duration) * DAY_MS);
|
|
816
|
+
}
|
|
817
|
+
function subtractOneCalendarMonth(date) {
|
|
818
|
+
const result = new Date(date);
|
|
819
|
+
result.setUTCMonth(result.getUTCMonth() - 1);
|
|
820
|
+
return result;
|
|
821
|
+
}
|
|
822
|
+
function windowStartYmd(reset_at, duration) {
|
|
823
|
+
const now = Date.now();
|
|
824
|
+
const reset = reset_at ? new Date(reset_at) : null;
|
|
825
|
+
const resetMs = reset && !Number.isNaN(reset.getTime()) ? reset.getTime() : null;
|
|
826
|
+
const trailingStart = subtractDuration(new Date(now), duration);
|
|
827
|
+
if (resetMs !== null) {
|
|
828
|
+
if (resetMs > now) {
|
|
829
|
+
const periodStart = reset.getUTCDate() === 1 ? subtractOneCalendarMonth(reset) : subtractDuration(reset, duration);
|
|
830
|
+
return ymd(periodStart > trailingStart ? periodStart : trailingStart);
|
|
831
|
+
} else {
|
|
832
|
+
return ymd(reset > trailingStart ? reset : trailingStart);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
return ymd(trailingStart);
|
|
836
|
+
}
|
|
837
|
+
async function enrichSpendFromActivity(map) {
|
|
838
|
+
const names = Object.keys(map);
|
|
839
|
+
if (names.length === 0) return;
|
|
840
|
+
const windows = {};
|
|
841
|
+
for (const name of names) {
|
|
842
|
+
const ti = map[name];
|
|
843
|
+
windows[name] = windowStartYmd(ti.budget_reset_at, ti.budget_duration);
|
|
844
|
+
}
|
|
845
|
+
try {
|
|
846
|
+
const spendByTag = await getTagSpendByWindow(
|
|
847
|
+
windows,
|
|
848
|
+
ymd(new Date(Date.now() + DAY_MS))
|
|
849
|
+
);
|
|
850
|
+
for (const name of names) {
|
|
851
|
+
const spend = spendByTag[name];
|
|
852
|
+
if (typeof spend === "number" && Number.isFinite(spend)) {
|
|
853
|
+
map[name].spend = spend;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
} catch (err) {
|
|
857
|
+
console.warn("[EXULU] enrichSpendFromActivity failed", err);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
var DEFAULT_SETTINGS = {
|
|
861
|
+
global_user_budget: { enabled: false, max_budget: 0, budget_duration: "30d" },
|
|
862
|
+
show_user_budget_in_chat: false,
|
|
863
|
+
user_budget_display: "amount"
|
|
864
|
+
};
|
|
865
|
+
function isEnabled() {
|
|
866
|
+
return process.env.EXULU_USE_LITELLM === "true" && !!process.env.LITELLM_MASTER_KEY;
|
|
867
|
+
}
|
|
868
|
+
async function getBudgetSettings() {
|
|
869
|
+
const { db: db2 } = await postgresClient();
|
|
870
|
+
const row = await db2.from("platform_configurations").where({ config_key: SETTINGS_KEY }).first();
|
|
871
|
+
if (!row?.config_value) return { ...DEFAULT_SETTINGS };
|
|
872
|
+
const parsed = typeof row.config_value === "string" ? (() => {
|
|
873
|
+
try {
|
|
874
|
+
return JSON.parse(row.config_value);
|
|
875
|
+
} catch {
|
|
876
|
+
return {};
|
|
877
|
+
}
|
|
878
|
+
})() : row.config_value;
|
|
879
|
+
return {
|
|
880
|
+
global_user_budget: {
|
|
881
|
+
...DEFAULT_SETTINGS.global_user_budget,
|
|
882
|
+
...parsed?.global_user_budget ?? {}
|
|
883
|
+
},
|
|
884
|
+
show_user_budget_in_chat: parsed?.show_user_budget_in_chat ?? DEFAULT_SETTINGS.show_user_budget_in_chat,
|
|
885
|
+
user_budget_display: parsed?.user_budget_display === "percent" ? "percent" : "amount"
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
async function setBudgetSettings(settings) {
|
|
889
|
+
const { db: db2 } = await postgresClient();
|
|
890
|
+
await db2.from("platform_configurations").insert({
|
|
891
|
+
config_key: SETTINGS_KEY,
|
|
892
|
+
config_value: JSON.stringify(settings),
|
|
893
|
+
description: "Tag-based budget settings (global per-user default + show-in-chat)"
|
|
894
|
+
}).onConflict("config_key").merge({ config_value: JSON.stringify(settings) });
|
|
895
|
+
return settings;
|
|
896
|
+
}
|
|
897
|
+
function parseResetAt(raw) {
|
|
898
|
+
if (raw === void 0 || raw === null || raw === "") {
|
|
899
|
+
return { valid: true, value: void 0 };
|
|
900
|
+
}
|
|
901
|
+
if (typeof raw !== "string") return { valid: false };
|
|
902
|
+
const t = Date.parse(raw);
|
|
903
|
+
if (Number.isNaN(t)) return { valid: false };
|
|
904
|
+
return { valid: true, value: new Date(t).toISOString() };
|
|
905
|
+
}
|
|
906
|
+
async function upsertBudget(tag, max_budget, budget_duration, budget_reset_at) {
|
|
907
|
+
const info = await tagInfo([tag]);
|
|
908
|
+
try {
|
|
909
|
+
if (info[tag]) {
|
|
910
|
+
await tagUpdate({ name: tag, max_budget, budget_duration });
|
|
911
|
+
} else {
|
|
912
|
+
await tagNew({ name: tag, max_budget, budget_duration });
|
|
913
|
+
}
|
|
914
|
+
} catch {
|
|
915
|
+
if (info[tag]) {
|
|
916
|
+
await tagNew({ name: tag, max_budget, budget_duration });
|
|
917
|
+
} else {
|
|
918
|
+
await tagUpdate({ name: tag, max_budget, budget_duration });
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (budget_reset_at) {
|
|
922
|
+
const after = await tagInfo([tag]);
|
|
923
|
+
const budgetId = after[tag]?.budget_id ?? null;
|
|
924
|
+
if (budgetId) {
|
|
925
|
+
await budgetUpdate(budgetId, { budget_reset_at });
|
|
926
|
+
} else {
|
|
927
|
+
console.warn(`[EXULU] upsertBudget: no budget_id for ${tag}; reset date not applied`);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
invalidateBudgetCaches(tag);
|
|
931
|
+
}
|
|
932
|
+
function invalidateBudgetCaches(tag) {
|
|
933
|
+
provisionCache.delete(tag);
|
|
934
|
+
readCache.delete(tag);
|
|
935
|
+
tagMapCache = void 0;
|
|
936
|
+
tagMapInflight = void 0;
|
|
937
|
+
}
|
|
938
|
+
var TAG_MAP_TTL_MS = 30 * 1e3;
|
|
939
|
+
var tagMapCache;
|
|
940
|
+
var tagMapInflight;
|
|
941
|
+
async function getTagBudgetMap() {
|
|
942
|
+
if (!process.env.LITELLM_MASTER_KEY) return {};
|
|
943
|
+
if (tagMapCache && tagMapCache.expiry > Date.now()) return tagMapCache.map;
|
|
944
|
+
if (tagMapInflight) return tagMapInflight;
|
|
945
|
+
tagMapInflight = (async () => {
|
|
946
|
+
try {
|
|
947
|
+
const map = await listTagBudgets();
|
|
948
|
+
await enrichSpendFromActivity(map);
|
|
949
|
+
tagMapCache = { expiry: Date.now() + TAG_MAP_TTL_MS, map };
|
|
950
|
+
return map;
|
|
951
|
+
} catch (err) {
|
|
952
|
+
console.warn("[EXULU] getTagBudgetMap failed", err);
|
|
953
|
+
return {};
|
|
954
|
+
} finally {
|
|
955
|
+
tagMapInflight = void 0;
|
|
956
|
+
}
|
|
957
|
+
})();
|
|
958
|
+
return tagMapInflight;
|
|
959
|
+
}
|
|
960
|
+
var PROVISION_TTL_MS = 60 * 60 * 1e3;
|
|
961
|
+
var provisionCache = /* @__PURE__ */ new Map();
|
|
962
|
+
async function provisionDefaultUserBudget(userId) {
|
|
963
|
+
try {
|
|
964
|
+
if (!isEnabled()) return;
|
|
965
|
+
const tag = budgetTagFor("user", userId);
|
|
966
|
+
if (!tag) return;
|
|
967
|
+
const cached = provisionCache.get(tag);
|
|
968
|
+
if (cached && cached > Date.now()) return;
|
|
969
|
+
const { global_user_budget: g } = await getBudgetSettings();
|
|
970
|
+
if (!g.enabled || !(g.max_budget > 0)) {
|
|
971
|
+
provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
const info = await tagInfo([tag]);
|
|
975
|
+
if (info[tag]?.max_budget != null) {
|
|
976
|
+
provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
await tagNew({
|
|
980
|
+
name: tag,
|
|
981
|
+
max_budget: g.max_budget,
|
|
982
|
+
budget_duration: g.budget_duration
|
|
983
|
+
});
|
|
984
|
+
provisionCache.set(tag, Date.now() + PROVISION_TTL_MS);
|
|
985
|
+
} catch (err) {
|
|
986
|
+
console.warn("[EXULU] ensureUserBudget failed", err);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
var READ_TTL_MS = 30 * 1e3;
|
|
990
|
+
var readCache = /* @__PURE__ */ new Map();
|
|
991
|
+
async function getUserBudgetView(userId) {
|
|
992
|
+
try {
|
|
993
|
+
if (!isEnabled()) return null;
|
|
994
|
+
const tag = budgetTagFor("user", userId);
|
|
995
|
+
if (!tag) return null;
|
|
996
|
+
const cached = readCache.get(tag);
|
|
997
|
+
if (cached && cached.expiry > Date.now()) return cached.view;
|
|
998
|
+
const settings = await getBudgetSettings();
|
|
999
|
+
if (!settings.show_user_budget_in_chat) {
|
|
1000
|
+
readCache.set(tag, { expiry: Date.now() + READ_TTL_MS, view: null });
|
|
1001
|
+
return null;
|
|
1002
|
+
}
|
|
1003
|
+
await provisionDefaultUserBudget(userId);
|
|
1004
|
+
const info = await tagInfo([tag]);
|
|
1005
|
+
const ti = info[tag];
|
|
1006
|
+
if (ti?.max_budget != null) {
|
|
1007
|
+
await enrichSpendFromActivity({ [tag]: ti });
|
|
1008
|
+
}
|
|
1009
|
+
const view = ti?.max_budget != null ? {
|
|
1010
|
+
spend: ti.spend,
|
|
1011
|
+
max_budget: ti.max_budget,
|
|
1012
|
+
budget_duration: ti.budget_duration,
|
|
1013
|
+
budget_reset_at: ti.budget_reset_at,
|
|
1014
|
+
display: settings.user_budget_display
|
|
1015
|
+
} : null;
|
|
1016
|
+
readCache.set(tag, { expiry: Date.now() + READ_TTL_MS, view });
|
|
1017
|
+
return view;
|
|
1018
|
+
} catch (err) {
|
|
1019
|
+
console.warn("[EXULU] getUserBudgetView failed", err);
|
|
1020
|
+
return null;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// src/exulu/resolve-model.ts
|
|
1025
|
+
var ResolveModelError = class extends Error {
|
|
1026
|
+
constructor(code, message) {
|
|
1027
|
+
super(message);
|
|
1028
|
+
this.code = code;
|
|
1029
|
+
this.name = "ResolveModelError";
|
|
1030
|
+
}
|
|
1031
|
+
};
|
|
1032
|
+
var getLiteLLMProvider = ({
|
|
1033
|
+
user,
|
|
1034
|
+
role,
|
|
1035
|
+
project,
|
|
1036
|
+
agent,
|
|
1037
|
+
team,
|
|
1038
|
+
routine
|
|
1039
|
+
}) => {
|
|
1040
|
+
const { baseUrl, authHeaders } = resolveLiteLLMTarget();
|
|
1041
|
+
const tags = buildTags({
|
|
1042
|
+
user_id: user?.id,
|
|
1043
|
+
role_id: role?.id,
|
|
1044
|
+
project_id: project?.id,
|
|
1045
|
+
agent_id: agent?.id,
|
|
1046
|
+
user_name: !user ? void 0 : user.type === "api" ? user.firstname ?? user.email : user.email,
|
|
1047
|
+
role_name: role?.name,
|
|
1048
|
+
project_name: project?.name,
|
|
1049
|
+
agent_name: agent?.name,
|
|
1050
|
+
team_id: team?.id,
|
|
1051
|
+
team_name: team?.name,
|
|
1052
|
+
routine_id: routine?.id,
|
|
1053
|
+
routine_name: routine?.name
|
|
1054
|
+
});
|
|
1055
|
+
return createOpenAICompatible({
|
|
1056
|
+
name: "litellm",
|
|
1057
|
+
baseURL: `${baseUrl}/v1`,
|
|
1058
|
+
// createOpenAICompatible requires a non-empty apiKey; real auth for remote mode is the
|
|
1059
|
+
// exulu-api-key header (added via `headers`). The passthrough strips/ignores Authorization.
|
|
1060
|
+
apiKey: process.env.LITELLM_MASTER_KEY ?? process.env.EXULU_API_KEY ?? "x",
|
|
1061
|
+
headers: authHeaders,
|
|
1062
|
+
fetch: createTaggedFetch(tags),
|
|
1063
|
+
// Without this flag the openai-compatible provider strips any
|
|
1064
|
+
// responseFormat.schema before sending and warns
|
|
1065
|
+
// "JSON response format schema is only supported with structuredOutputs".
|
|
1066
|
+
// Models then return free-form JSON that fails Zod parsing in callers
|
|
1067
|
+
// using `Output.object({ schema })`. LiteLLM forwards
|
|
1068
|
+
// `response_format: { type: "json_schema", ... }` to every upstream it
|
|
1069
|
+
// supports — including Vertex Gemini, which translates it into
|
|
1070
|
+
// responseSchema/responseMimeType — so enabling this matches the actual
|
|
1071
|
+
// proxy contract.
|
|
1072
|
+
supportsStructuredOutputs: true,
|
|
1073
|
+
// Request token usage on STREAMED responses. Without this the openai-compatible
|
|
1074
|
+
// provider omits `stream_options: { include_usage: true }`, so LiteLLM returns no
|
|
1075
|
+
// usage for streaming calls — which zeroes out the per-request token metrics and
|
|
1076
|
+
// the message-footer token count (both read the AI SDK `totalUsage`/finish-part usage).
|
|
1077
|
+
includeUsage: true
|
|
1078
|
+
});
|
|
1079
|
+
};
|
|
1080
|
+
async function resolveModel(input) {
|
|
1081
|
+
const { modelId, user, agent, project, routine } = input;
|
|
1082
|
+
if (!isLiteLLMEnabled()) {
|
|
1083
|
+
throw new Error("Litellm not configured or available.");
|
|
1084
|
+
}
|
|
1085
|
+
try {
|
|
1086
|
+
await waitForLiteLLMReady();
|
|
1087
|
+
} catch (err) {
|
|
1088
|
+
throw new ResolveModelError(
|
|
1089
|
+
"LITELLM_NOT_READY",
|
|
1090
|
+
`LiteLLM is not ready: ${err.message}`
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
if (user?.id) await provisionDefaultUserBudget(user.id);
|
|
1094
|
+
const litellm = getLiteLLMProvider({
|
|
1095
|
+
user,
|
|
1096
|
+
role: user?.role,
|
|
1097
|
+
// Fall back to the caller's own project (set on API keys) when no
|
|
1098
|
+
// explicit request project is supplied, so API-triggered requests are
|
|
1099
|
+
// attributed to the key's project.
|
|
1100
|
+
project: project ?? user?.project,
|
|
1101
|
+
agent,
|
|
1102
|
+
team: user?.team,
|
|
1103
|
+
routine
|
|
1104
|
+
});
|
|
1105
|
+
const languageModel = litellm(modelId);
|
|
1106
|
+
const syntheticModel = {
|
|
1107
|
+
id: modelId,
|
|
1108
|
+
name: modelId,
|
|
1109
|
+
provider: modelId,
|
|
1110
|
+
active: true,
|
|
1111
|
+
rights_mode: "public",
|
|
1112
|
+
created_by: "litellm"
|
|
1113
|
+
};
|
|
1114
|
+
return {
|
|
1115
|
+
languageModel,
|
|
1116
|
+
model: syntheticModel
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// src/utils/with-retry.ts
|
|
1121
|
+
async function withRetry(generateFn, maxRetries = 3, opts = {}) {
|
|
1122
|
+
const { shouldRetry, baseDelayMs = 1e3 } = opts;
|
|
1123
|
+
let lastError;
|
|
1124
|
+
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
1125
|
+
try {
|
|
1126
|
+
return await generateFn();
|
|
1127
|
+
} catch (error) {
|
|
1128
|
+
lastError = error;
|
|
1129
|
+
console.error(`[EXULU] generateText attempt ${attempt} failed:`, error);
|
|
1130
|
+
if (attempt === maxRetries || shouldRetry && !shouldRetry(error)) {
|
|
1131
|
+
throw error;
|
|
1132
|
+
}
|
|
1133
|
+
await new Promise((resolve2) => setTimeout(resolve2, Math.pow(2, attempt) * baseDelayMs));
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
throw lastError;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
export {
|
|
1140
|
+
postgresClient,
|
|
1141
|
+
LITELLM_UI_PATH,
|
|
1142
|
+
isLiteLLMEnabled,
|
|
1143
|
+
setLiteLLMPackageRoot,
|
|
1144
|
+
enableLiteLLMClientMode,
|
|
1145
|
+
startLiteLLMSupervisor,
|
|
1146
|
+
waitForLiteLLMReady,
|
|
1147
|
+
buildTags,
|
|
1148
|
+
budgetTagFor,
|
|
1149
|
+
createTaggedFetch,
|
|
1150
|
+
tagDelete,
|
|
1151
|
+
tagInfo,
|
|
1152
|
+
getTagDailyActivity,
|
|
1153
|
+
listTagsByPrefix,
|
|
1154
|
+
getBudgetSettings,
|
|
1155
|
+
setBudgetSettings,
|
|
1156
|
+
parseResetAt,
|
|
1157
|
+
upsertBudget,
|
|
1158
|
+
invalidateBudgetCaches,
|
|
1159
|
+
getTagBudgetMap,
|
|
1160
|
+
provisionDefaultUserBudget,
|
|
1161
|
+
getUserBudgetView,
|
|
1162
|
+
checkLicense,
|
|
1163
|
+
ResolveModelError,
|
|
1164
|
+
resolveModel,
|
|
1165
|
+
withRetry
|
|
1166
|
+
};
|