@exulu/backend 5.5.1 → 5.6.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/{chunk-ZWFL6YUH.js → chunk-SJNP75II.js} +112 -5
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-C5LYP4UN.js → convert-exulu-tools-to-ai-sdk-tools-7TYZVHEQ.js} +1 -1
- package/dist/index.cjs +1765 -550
- package/dist/index.js +1468 -378
- package/ee/queues/import-queue.ts +27 -0
- package/ee/queues/prune-job-results.test.ts +105 -1
- package/ee/queues/prune-job-results.ts +85 -9
- package/ee/queues/queues.ts +1 -0
- package/ee/workers.ts +173 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -126,6 +126,7 @@ import {
|
|
|
126
126
|
getS3ObjectBytes,
|
|
127
127
|
getS3ObjectContent,
|
|
128
128
|
getS3ObjectEtag,
|
|
129
|
+
getS3ObjectStream,
|
|
129
130
|
getS3SignedUploadUrl,
|
|
130
131
|
getTableName,
|
|
131
132
|
getTagBudgetMap,
|
|
@@ -207,7 +208,7 @@ import {
|
|
|
207
208
|
willEmbedOnQueue,
|
|
208
209
|
withRetry,
|
|
209
210
|
workflowTemplatesSchema
|
|
210
|
-
} from "./chunk-
|
|
211
|
+
} from "./chunk-SJNP75II.js";
|
|
211
212
|
import {
|
|
212
213
|
LiteLLMAdminError,
|
|
213
214
|
findLiteLLMModel,
|
|
@@ -245,11 +246,11 @@ var describeError = (e) => {
|
|
|
245
246
|
function logRedisErrors(source, label) {
|
|
246
247
|
let count = 0;
|
|
247
248
|
let lastLoggedAt = 0;
|
|
248
|
-
source.on("error", (
|
|
249
|
+
source.on("error", (err2) => {
|
|
249
250
|
count += 1;
|
|
250
251
|
const now = Date.now();
|
|
251
252
|
if (count === 1 || now - lastLoggedAt >= ERROR_LOG_THROTTLE_MS) {
|
|
252
|
-
errorLog(`${label} connection error (${redisAddress()}): ${describeError(
|
|
253
|
+
errorLog(`${label} connection error (${redisAddress()}): ${describeError(err2)}${count > 1 ? ` (x${count})` : ""}`);
|
|
253
254
|
lastLoggedAt = now;
|
|
254
255
|
}
|
|
255
256
|
});
|
|
@@ -259,8 +260,8 @@ async function guardRedisStartup(label, run, source) {
|
|
|
259
260
|
log(`Connecting to Redis (${addr}) for ${label}\u2026`);
|
|
260
261
|
const startedAt = Date.now();
|
|
261
262
|
let lastError;
|
|
262
|
-
const onError = (
|
|
263
|
-
lastError =
|
|
263
|
+
const onError = (err2) => {
|
|
264
|
+
lastError = err2;
|
|
264
265
|
};
|
|
265
266
|
source?.on("error", onError);
|
|
266
267
|
const watchdog = setInterval(() => {
|
|
@@ -596,7 +597,8 @@ import { Queue } from "bullmq";
|
|
|
596
597
|
import { BullMQOtel } from "bullmq-otel";
|
|
597
598
|
var global_queues = {
|
|
598
599
|
eval_runs: "eval_runs",
|
|
599
|
-
email_intake: "email_intake"
|
|
600
|
+
email_intake: "email_intake",
|
|
601
|
+
import: "import"
|
|
600
602
|
};
|
|
601
603
|
var ExuluQueues = class {
|
|
602
604
|
queues;
|
|
@@ -658,10 +660,10 @@ var ExuluQueues = class {
|
|
|
658
660
|
logRedisErrors(newQueue, `queue "${name}"`);
|
|
659
661
|
try {
|
|
660
662
|
await guardRedisStartup(`queue "${name}"`, () => newQueue.waitUntilReady(), newQueue);
|
|
661
|
-
} catch (
|
|
663
|
+
} catch (err2) {
|
|
662
664
|
void newQueue.close().catch(() => {
|
|
663
665
|
});
|
|
664
|
-
throw
|
|
666
|
+
throw err2;
|
|
665
667
|
}
|
|
666
668
|
await newQueue.setGlobalConcurrency(queueConcurrency);
|
|
667
669
|
this.queues.push({
|
|
@@ -1805,6 +1807,495 @@ async function deleteRoutineRunRow(db, row, queues2) {
|
|
|
1805
1807
|
await db.from("job_results").where({ id: row.id }).del();
|
|
1806
1808
|
}
|
|
1807
1809
|
|
|
1810
|
+
// ee/queues/import-queue.ts
|
|
1811
|
+
var IMPORT_QUEUE_CONCURRENCY = { worker: 1, queue: 1 };
|
|
1812
|
+
var IMPORT_QUEUE_RATELIMIT = 1;
|
|
1813
|
+
var IMPORT_QUEUE_TIMEOUT_SECONDS = 6 * 3600;
|
|
1814
|
+
function registerImportQueue() {
|
|
1815
|
+
return queues.register(
|
|
1816
|
+
global_queues.import,
|
|
1817
|
+
IMPORT_QUEUE_CONCURRENCY,
|
|
1818
|
+
IMPORT_QUEUE_RATELIMIT,
|
|
1819
|
+
IMPORT_QUEUE_TIMEOUT_SECONDS
|
|
1820
|
+
);
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
// src/exulu/import/start-import.ts
|
|
1824
|
+
import { randomUUID } from "crypto";
|
|
1825
|
+
|
|
1826
|
+
// src/utils/serialize-error.ts
|
|
1827
|
+
var MAX_CAUSE_DEPTH = 3;
|
|
1828
|
+
function serializeError(err2, depth = 0) {
|
|
1829
|
+
if (err2 instanceof Error) {
|
|
1830
|
+
const out = { name: err2.name, message: err2.message };
|
|
1831
|
+
if (err2.stack) out.stack = err2.stack;
|
|
1832
|
+
for (const [key, value] of Object.entries(err2)) {
|
|
1833
|
+
if (key !== "cause") out[key] = value;
|
|
1834
|
+
}
|
|
1835
|
+
const cause = err2.cause;
|
|
1836
|
+
if (cause !== void 0 && depth < MAX_CAUSE_DEPTH) {
|
|
1837
|
+
out.cause = serializeError(cause, depth + 1);
|
|
1838
|
+
}
|
|
1839
|
+
return out;
|
|
1840
|
+
}
|
|
1841
|
+
if (typeof err2 === "string") {
|
|
1842
|
+
return { message: err2 };
|
|
1843
|
+
}
|
|
1844
|
+
if (err2 !== null && typeof err2 === "object") {
|
|
1845
|
+
let message;
|
|
1846
|
+
try {
|
|
1847
|
+
message = JSON.stringify(err2);
|
|
1848
|
+
} catch {
|
|
1849
|
+
message = "[unserializable error object]";
|
|
1850
|
+
}
|
|
1851
|
+
return { ...err2, message };
|
|
1852
|
+
}
|
|
1853
|
+
return { message: String(err2) };
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
// src/exulu/import/coerce.ts
|
|
1857
|
+
var TEXTUAL = /* @__PURE__ */ new Set(["text", "longText", "shortText", "markdown", "code"]);
|
|
1858
|
+
function err(raw, code, params) {
|
|
1859
|
+
return { raw, value: null, error: { code, params } };
|
|
1860
|
+
}
|
|
1861
|
+
function coerceValue(field, raw) {
|
|
1862
|
+
const trimmed = raw.trim();
|
|
1863
|
+
if (trimmed === "") {
|
|
1864
|
+
return { raw, value: TEXTUAL.has(field.type) ? "" : null };
|
|
1865
|
+
}
|
|
1866
|
+
switch (field.type) {
|
|
1867
|
+
case "number": {
|
|
1868
|
+
const hasComma = trimmed.includes(",");
|
|
1869
|
+
const hasDot = trimmed.includes(".");
|
|
1870
|
+
if (hasComma && hasDot) return err(raw, "number");
|
|
1871
|
+
let candidate = trimmed;
|
|
1872
|
+
if (hasComma) {
|
|
1873
|
+
const parts = trimmed.split(",");
|
|
1874
|
+
if (parts.length !== 2 || (parts[1]?.length ?? 0) === 3) return err(raw, "numberAmbiguous");
|
|
1875
|
+
candidate = parts.join(".");
|
|
1876
|
+
}
|
|
1877
|
+
const n = Number(candidate);
|
|
1878
|
+
if (!Number.isFinite(n)) return err(raw, "number");
|
|
1879
|
+
return { raw, value: n };
|
|
1880
|
+
}
|
|
1881
|
+
case "boolean": {
|
|
1882
|
+
const v = trimmed.toLowerCase();
|
|
1883
|
+
if (["true", "yes", "ja", "1"].includes(v)) return { raw, value: true };
|
|
1884
|
+
if (["false", "no", "nein", "0"].includes(v)) return { raw, value: false };
|
|
1885
|
+
return err(raw, "boolean");
|
|
1886
|
+
}
|
|
1887
|
+
case "enum": {
|
|
1888
|
+
const match = (field.enumValues ?? []).find((e) => e.toLowerCase() === trimmed.toLowerCase());
|
|
1889
|
+
if (!match) return err(raw, "enum", { values: (field.enumValues ?? []).join(", ") });
|
|
1890
|
+
return { raw, value: match };
|
|
1891
|
+
}
|
|
1892
|
+
case "date": {
|
|
1893
|
+
if (/^\d{4}-\d{2}-\d{2}(T[\d:.]+(Z|[+-]\d{2}:?\d{2})?)?$/.test(trimmed)) {
|
|
1894
|
+
return Number.isNaN(Date.parse(trimmed)) ? err(raw, "date") : { raw, value: trimmed };
|
|
1895
|
+
}
|
|
1896
|
+
if (trimmed.includes("/")) return err(raw, "date");
|
|
1897
|
+
return Number.isNaN(Date.parse(trimmed)) ? err(raw, "date") : { raw, value: new Date(trimmed).toISOString() };
|
|
1898
|
+
}
|
|
1899
|
+
case "json": {
|
|
1900
|
+
try {
|
|
1901
|
+
JSON.parse(trimmed);
|
|
1902
|
+
return { raw, value: trimmed };
|
|
1903
|
+
} catch {
|
|
1904
|
+
return err(raw, "json");
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
case "uuid": {
|
|
1908
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed) ? { raw, value: trimmed } : err(raw, "uuid");
|
|
1909
|
+
}
|
|
1910
|
+
default:
|
|
1911
|
+
return { raw, value: raw };
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
// src/exulu/import/rows.ts
|
|
1916
|
+
function tentativeAction(cells) {
|
|
1917
|
+
const id = cells.id?.value;
|
|
1918
|
+
if (typeof id === "string" && id !== "") return "update";
|
|
1919
|
+
const externalId = cells.external_id?.value;
|
|
1920
|
+
if (typeof externalId === "string" && externalId !== "") return "update";
|
|
1921
|
+
return "create";
|
|
1922
|
+
}
|
|
1923
|
+
function buildRow(index, cells, byIndex, fields) {
|
|
1924
|
+
const byName = new Map(fields.map((f) => [f.name, f]));
|
|
1925
|
+
const rowCells = {};
|
|
1926
|
+
for (let i = 0; i < byIndex.length; i++) {
|
|
1927
|
+
const fieldName = byIndex[i];
|
|
1928
|
+
if (!fieldName) continue;
|
|
1929
|
+
const field = byName.get(fieldName);
|
|
1930
|
+
if (!field) continue;
|
|
1931
|
+
rowCells[fieldName] = coerceValue(field, cells[i] ?? "");
|
|
1932
|
+
}
|
|
1933
|
+
const action = tentativeAction(rowCells);
|
|
1934
|
+
const errors = [];
|
|
1935
|
+
for (const f of fields) {
|
|
1936
|
+
const cell = rowCells[f.name];
|
|
1937
|
+
const mustHaveValue = action === "create" || cell !== void 0;
|
|
1938
|
+
if (f.required && mustHaveValue && (cell === void 0 || cell.raw.trim() === "")) {
|
|
1939
|
+
errors.push(`required:${f.name}`);
|
|
1940
|
+
continue;
|
|
1941
|
+
}
|
|
1942
|
+
if (cell?.error) {
|
|
1943
|
+
errors.push(`${f.name}:${cell.error.code}`);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
return { index, cells: rowCells, errors };
|
|
1947
|
+
}
|
|
1948
|
+
function rowIsValid(row) {
|
|
1949
|
+
return row.errors.length === 0;
|
|
1950
|
+
}
|
|
1951
|
+
function rowAction(row) {
|
|
1952
|
+
const id = row.cells.id?.value;
|
|
1953
|
+
if (typeof id === "string" && id !== "") {
|
|
1954
|
+
return { action: "update", by: "id", key: id };
|
|
1955
|
+
}
|
|
1956
|
+
const externalId = row.cells.external_id?.value;
|
|
1957
|
+
if (typeof externalId === "string" && externalId !== "") {
|
|
1958
|
+
return { action: "update", by: "external_id", key: externalId };
|
|
1959
|
+
}
|
|
1960
|
+
return { action: "create" };
|
|
1961
|
+
}
|
|
1962
|
+
function cellValues(row) {
|
|
1963
|
+
const input = {};
|
|
1964
|
+
for (const [name, cell] of Object.entries(row.cells)) {
|
|
1965
|
+
if (name === "id") continue;
|
|
1966
|
+
if (name === "external_id" && (cell.value == null || cell.value === "")) continue;
|
|
1967
|
+
input[name] = cell.value;
|
|
1968
|
+
}
|
|
1969
|
+
return input;
|
|
1970
|
+
}
|
|
1971
|
+
function asGrantList(value) {
|
|
1972
|
+
return Array.isArray(value) ? value : [];
|
|
1973
|
+
}
|
|
1974
|
+
function rbacGrantsFor(access) {
|
|
1975
|
+
const hasGrants = access.rights_mode === "users" || access.rights_mode === "roles" || access.rights_mode === "teams";
|
|
1976
|
+
if (!hasGrants) return void 0;
|
|
1977
|
+
return {
|
|
1978
|
+
users: asGrantList(access.users),
|
|
1979
|
+
roles: asGrantList(access.roles),
|
|
1980
|
+
teams: asGrantList(access.teams)
|
|
1981
|
+
};
|
|
1982
|
+
}
|
|
1983
|
+
function buildCreateInput(row, access) {
|
|
1984
|
+
const input = cellValues(row);
|
|
1985
|
+
input.rights_mode = access.rights_mode;
|
|
1986
|
+
return input;
|
|
1987
|
+
}
|
|
1988
|
+
function buildUpdateInput(row) {
|
|
1989
|
+
return cellValues(row);
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
// src/exulu/import/worker-deps.ts
|
|
1993
|
+
function grantsOf(existing) {
|
|
1994
|
+
const raw = existing.RBAC;
|
|
1995
|
+
return Array.isArray(raw) ? raw : [];
|
|
1996
|
+
}
|
|
1997
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1998
|
+
function isUuid(value) {
|
|
1999
|
+
return UUID_RE.test(value);
|
|
2000
|
+
}
|
|
2001
|
+
function idOf(value) {
|
|
2002
|
+
if (typeof value === "string") return value;
|
|
2003
|
+
if (value != null && typeof value === "object" && "id" in value) {
|
|
2004
|
+
const id = value.id;
|
|
2005
|
+
if (typeof id === "string") return id;
|
|
2006
|
+
if (typeof id === "number") return String(id);
|
|
2007
|
+
}
|
|
2008
|
+
return void 0;
|
|
2009
|
+
}
|
|
2010
|
+
function canWrite(existing, user) {
|
|
2011
|
+
if (user.super_admin === true) return true;
|
|
2012
|
+
if (existing.rights_mode === "public") return true;
|
|
2013
|
+
const isCreator = existing.created_by != null && String(existing.created_by) === String(user.id);
|
|
2014
|
+
if (existing.rights_mode === "private") return isCreator;
|
|
2015
|
+
if (isCreator) return true;
|
|
2016
|
+
if (existing.rights_mode === "users") {
|
|
2017
|
+
return grantsOf(existing).some(
|
|
2018
|
+
(g) => g.access_type === "User" && String(g.user_id) === String(user.id) && g.rights === "write"
|
|
2019
|
+
);
|
|
2020
|
+
}
|
|
2021
|
+
if (existing.rights_mode === "roles") {
|
|
2022
|
+
const roleId = idOf(user.role);
|
|
2023
|
+
if (!roleId) return false;
|
|
2024
|
+
return grantsOf(existing).some(
|
|
2025
|
+
(g) => g.access_type === "Role" && String(g.role_id) === roleId && g.rights === "write"
|
|
2026
|
+
);
|
|
2027
|
+
}
|
|
2028
|
+
if (existing.rights_mode === "teams") {
|
|
2029
|
+
const teamId = idOf(user.team);
|
|
2030
|
+
if (!teamId) return false;
|
|
2031
|
+
return grantsOf(existing).some(
|
|
2032
|
+
(g) => g.access_type === "Team" && String(g.team_id) === teamId && g.rights === "write"
|
|
2033
|
+
);
|
|
2034
|
+
}
|
|
2035
|
+
return false;
|
|
2036
|
+
}
|
|
2037
|
+
async function selectItemsBy(db, tableName, column, values) {
|
|
2038
|
+
if (values.length === 0) return [];
|
|
2039
|
+
return db(tableName).select("id", "external_id", "rights_mode", "created_by").whereIn(column, values);
|
|
2040
|
+
}
|
|
2041
|
+
async function lookupExisting(db, tableName, ids, externalIds) {
|
|
2042
|
+
const [byId, byExternalId] = await Promise.all([
|
|
2043
|
+
selectItemsBy(db, tableName, "id", ids.filter(isUuid)),
|
|
2044
|
+
selectItemsBy(db, tableName, "external_id", externalIds)
|
|
2045
|
+
]);
|
|
2046
|
+
const merged = /* @__PURE__ */ new Map();
|
|
2047
|
+
for (const row of [...byId, ...byExternalId]) merged.set(row.id, row);
|
|
2048
|
+
const rows = [...merged.values()];
|
|
2049
|
+
if (rows.length === 0) return [];
|
|
2050
|
+
const needsGrants = rows.some(
|
|
2051
|
+
(r) => r.rights_mode === "users" || r.rights_mode === "roles" || r.rights_mode === "teams"
|
|
2052
|
+
);
|
|
2053
|
+
if (!needsGrants) {
|
|
2054
|
+
return rows.map((r) => ({ ...r, RBAC: [] }));
|
|
2055
|
+
}
|
|
2056
|
+
const grants = await db("rbac").select("target_resource_id", "access_type", "user_id", "role_id", "team_id", "rights").where({ entity: tableName }).whereIn(
|
|
2057
|
+
"target_resource_id",
|
|
2058
|
+
rows.map((r) => r.id)
|
|
2059
|
+
);
|
|
2060
|
+
const grantsByItem = /* @__PURE__ */ new Map();
|
|
2061
|
+
for (const g of grants) {
|
|
2062
|
+
const list = grantsByItem.get(g.target_resource_id) ?? [];
|
|
2063
|
+
list.push(g);
|
|
2064
|
+
grantsByItem.set(g.target_resource_id, list);
|
|
2065
|
+
}
|
|
2066
|
+
return rows.map((r) => ({ ...r, RBAC: grantsByItem.get(r.id) ?? [] }));
|
|
2067
|
+
}
|
|
2068
|
+
function parseMetadata(value) {
|
|
2069
|
+
if (value == null) return {};
|
|
2070
|
+
let parsed = value;
|
|
2071
|
+
if (typeof value === "string") {
|
|
2072
|
+
try {
|
|
2073
|
+
parsed = JSON.parse(value);
|
|
2074
|
+
} catch {
|
|
2075
|
+
return {};
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
return typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
2079
|
+
}
|
|
2080
|
+
function mergeMetadataRaw(db, patch) {
|
|
2081
|
+
return db.raw("coalesce(metadata, '{}'::jsonb) || ?::jsonb", [JSON.stringify(patch)]);
|
|
2082
|
+
}
|
|
2083
|
+
async function writeProgress(db, jobResultId, m) {
|
|
2084
|
+
await db("job_results").where({ id: jobResultId }).update({ metadata: mergeMetadataRaw(db, m) });
|
|
2085
|
+
}
|
|
2086
|
+
async function isCancelRequested(db, jobResultId) {
|
|
2087
|
+
const row = await db("job_results").where({ id: jobResultId }).select("metadata").first();
|
|
2088
|
+
return parseMetadata(row?.metadata).cancelRequested === true;
|
|
2089
|
+
}
|
|
2090
|
+
async function finalizeCancelled(db, jobResultId, result) {
|
|
2091
|
+
await db("job_results").where({ id: jobResultId }).whereIn("state", [JOB_STATUS_ENUM.active]).update({
|
|
2092
|
+
state: JOB_STATUS_ENUM.cancelled,
|
|
2093
|
+
result: JSON.stringify(result),
|
|
2094
|
+
metadata: mergeMetadataRaw(db, result)
|
|
2095
|
+
});
|
|
2096
|
+
}
|
|
2097
|
+
async function uploadErrorReport(csv, contextId, jobResultId, config, user) {
|
|
2098
|
+
const buffer = Buffer.from(csv, "utf-8");
|
|
2099
|
+
const fileName = `imports/${contextId}/${jobResultId}-errors.csv`;
|
|
2100
|
+
return uploadFile(buffer, fileName, config, { contentType: "text/csv" }, user, void 0, true);
|
|
2101
|
+
}
|
|
2102
|
+
function buildWorkerDeps(input) {
|
|
2103
|
+
const { db, config, context, contextId, jobResultId, stream, fields, mapping, access, options, user, log: log6 } = input;
|
|
2104
|
+
const tableName = getTableName(contextId);
|
|
2105
|
+
const roleId = idOf(user.role);
|
|
2106
|
+
const generateEmbeddingsOverwrite = options.skipEmbeddings ? false : void 0;
|
|
2107
|
+
const rbac = rbacGrantsFor(access);
|
|
2108
|
+
const total = typeof input.total === "number" && input.total > 0 ? input.total : void 0;
|
|
2109
|
+
return {
|
|
2110
|
+
stream,
|
|
2111
|
+
fields,
|
|
2112
|
+
mapping,
|
|
2113
|
+
access,
|
|
2114
|
+
options,
|
|
2115
|
+
user,
|
|
2116
|
+
log: log6,
|
|
2117
|
+
total,
|
|
2118
|
+
lookupExisting: (ids, externalIds) => lookupExisting(db, tableName, ids, externalIds),
|
|
2119
|
+
canWrite: (existing) => canWrite(existing, user),
|
|
2120
|
+
createItem: async (itemInput) => {
|
|
2121
|
+
const { RBAC: _droppedRbacColumn, ...columns } = itemInput;
|
|
2122
|
+
const created = await context.createItem(
|
|
2123
|
+
{ ...columns, created_by: user.id },
|
|
2124
|
+
config,
|
|
2125
|
+
user.id,
|
|
2126
|
+
roleId,
|
|
2127
|
+
false,
|
|
2128
|
+
generateEmbeddingsOverwrite
|
|
2129
|
+
);
|
|
2130
|
+
const createdId = created?.item?.id;
|
|
2131
|
+
if (rbac && typeof createdId === "string") {
|
|
2132
|
+
await handleRBACUpdate(db, tableName, createdId, rbac, []);
|
|
2133
|
+
}
|
|
2134
|
+
},
|
|
2135
|
+
// buildUpdateInput (rows.ts) never carries an id/rights_mode/RBAC -- the
|
|
2136
|
+
// target's id is threaded in here, same as the GraphQL updateOne path.
|
|
2137
|
+
// `created_by` is deliberately left untouched on an update.
|
|
2138
|
+
updateItem: async (id, itemInput) => {
|
|
2139
|
+
await context.updateItem({ id, ...itemInput }, config, user.id, roleId, generateEmbeddingsOverwrite);
|
|
2140
|
+
},
|
|
2141
|
+
writeProgress: (m) => writeProgress(db, jobResultId, m),
|
|
2142
|
+
isCancelRequested: () => isCancelRequested(db, jobResultId),
|
|
2143
|
+
uploadErrorReport: (csv) => uploadErrorReport(csv, contextId, jobResultId, config, user.id)
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
// src/exulu/import/start-import.ts
|
|
2148
|
+
function idOrSelf(value) {
|
|
2149
|
+
if (value != null && typeof value === "object" && "id" in value) {
|
|
2150
|
+
return value.id;
|
|
2151
|
+
}
|
|
2152
|
+
return value;
|
|
2153
|
+
}
|
|
2154
|
+
var VALID_RIGHTS_MODES2 = ["private", "users", "roles", "teams", "public"];
|
|
2155
|
+
var StartImportError = class extends Error {
|
|
2156
|
+
constructor(code) {
|
|
2157
|
+
super(code);
|
|
2158
|
+
this.code = code;
|
|
2159
|
+
this.name = "StartImportError";
|
|
2160
|
+
}
|
|
2161
|
+
};
|
|
2162
|
+
async function startImport(deps, args) {
|
|
2163
|
+
const { db, config, queue, user, contextExists, uuid } = deps;
|
|
2164
|
+
if (!contextExists(args.contextId)) {
|
|
2165
|
+
throw new StartImportError("CONTEXT_NOT_FOUND");
|
|
2166
|
+
}
|
|
2167
|
+
if (!VALID_RIGHTS_MODES2.includes(args.access.rights_mode)) {
|
|
2168
|
+
throw new StartImportError("INVALID_RIGHTS_MODE");
|
|
2169
|
+
}
|
|
2170
|
+
const access = {
|
|
2171
|
+
...args.access,
|
|
2172
|
+
users: asGrantList(args.access.users),
|
|
2173
|
+
roles: asGrantList(args.access.roles),
|
|
2174
|
+
teams: asGrantList(args.access.teams)
|
|
2175
|
+
};
|
|
2176
|
+
if (args.options?.delimiter != null && args.options.delimiter.length !== 1) {
|
|
2177
|
+
throw new StartImportError("INVALID_DELIMITER");
|
|
2178
|
+
}
|
|
2179
|
+
const bucket = args.s3Key.split("/")[0];
|
|
2180
|
+
if (bucket !== config.fileUploads?.s3Bucket) {
|
|
2181
|
+
throw new StartImportError("IMPORT_S3_KEY_OUTSIDE_BUCKET");
|
|
2182
|
+
}
|
|
2183
|
+
const keyWithoutBucket = args.s3Key.split("/").slice(1).join("/");
|
|
2184
|
+
const prefixAllowed = user.type === "api" || user.super_admin === true || !keyWithoutBucket.includes("user_") || keyWithoutBucket.includes(`user_${user.id}/`);
|
|
2185
|
+
if (!prefixAllowed) {
|
|
2186
|
+
throw new StartImportError("IMPORT_S3_KEY_NOT_ALLOWED");
|
|
2187
|
+
}
|
|
2188
|
+
const running = await db("job_results").where({ context: args.contextId, type: "import" }).whereIn("state", ["waiting", "active"]).first();
|
|
2189
|
+
if (running) {
|
|
2190
|
+
throw new StartImportError("IMPORT_ALREADY_RUNNING");
|
|
2191
|
+
}
|
|
2192
|
+
const id = (uuid ?? randomUUID)();
|
|
2193
|
+
const label = `Import ${args.fileName}`;
|
|
2194
|
+
const userSnapshot = {
|
|
2195
|
+
id: user.id,
|
|
2196
|
+
super_admin: user.super_admin === true,
|
|
2197
|
+
role: idOrSelf(user.role),
|
|
2198
|
+
team: idOrSelf(user.team)
|
|
2199
|
+
};
|
|
2200
|
+
await db("job_results").insert({
|
|
2201
|
+
id,
|
|
2202
|
+
job_id: id,
|
|
2203
|
+
type: "import",
|
|
2204
|
+
context: args.contextId,
|
|
2205
|
+
label,
|
|
2206
|
+
state: "waiting",
|
|
2207
|
+
trigger: args.trigger,
|
|
2208
|
+
trigger_metadata: JSON.stringify({
|
|
2209
|
+
s3Key: args.s3Key,
|
|
2210
|
+
fileName: args.fileName,
|
|
2211
|
+
mapping: args.mapping,
|
|
2212
|
+
access,
|
|
2213
|
+
options: args.options,
|
|
2214
|
+
user: userSnapshot
|
|
2215
|
+
}),
|
|
2216
|
+
metadata: JSON.stringify({
|
|
2217
|
+
total: args.totalRows ?? 0,
|
|
2218
|
+
processed: 0,
|
|
2219
|
+
created: 0,
|
|
2220
|
+
updated: 0,
|
|
2221
|
+
failed: 0,
|
|
2222
|
+
invalid: 0
|
|
2223
|
+
})
|
|
2224
|
+
});
|
|
2225
|
+
try {
|
|
2226
|
+
await queue.add(
|
|
2227
|
+
"import",
|
|
2228
|
+
{
|
|
2229
|
+
label,
|
|
2230
|
+
type: "import",
|
|
2231
|
+
// BullMqJobData.trigger is a STATISTICS_LABELS value, which has no
|
|
2232
|
+
// "ui" member -- "api" here is just that field's required value for
|
|
2233
|
+
// this queue path, unrelated to the job_results row's own ui|api
|
|
2234
|
+
// `trigger` column above (which records real run provenance).
|
|
2235
|
+
trigger: "api",
|
|
2236
|
+
timeoutInSeconds: 6 * 3600,
|
|
2237
|
+
// Required: bullmq.validate (src/validators/bullmq.ts) throws without
|
|
2238
|
+
// an `inputs` key, even though the import branch ignores it (its
|
|
2239
|
+
// inputs live on the job_results row's trigger_metadata instead).
|
|
2240
|
+
inputs: {},
|
|
2241
|
+
jobResultId: id,
|
|
2242
|
+
context: args.contextId,
|
|
2243
|
+
user: user.id,
|
|
2244
|
+
role: idOrSelf(user.role)
|
|
2245
|
+
},
|
|
2246
|
+
{
|
|
2247
|
+
jobId: id,
|
|
2248
|
+
attempts: 1,
|
|
2249
|
+
removeOnComplete: 5e3,
|
|
2250
|
+
removeOnFail: 5e3
|
|
2251
|
+
}
|
|
2252
|
+
);
|
|
2253
|
+
} catch (error) {
|
|
2254
|
+
await db("job_results").where({ id }).update({ state: "failed", error: JSON.stringify(serializeError(error)) });
|
|
2255
|
+
throw error;
|
|
2256
|
+
}
|
|
2257
|
+
return { jobResultId: id };
|
|
2258
|
+
}
|
|
2259
|
+
async function cancelImport(deps, jobResultId) {
|
|
2260
|
+
const { db, queue, user } = deps;
|
|
2261
|
+
const row = await db("job_results").where({ id: jobResultId }).first();
|
|
2262
|
+
if (!row) {
|
|
2263
|
+
throw new StartImportError("IMPORT_NOT_FOUND");
|
|
2264
|
+
}
|
|
2265
|
+
if (row.type !== "import") {
|
|
2266
|
+
throw new StartImportError("IMPORT_NOT_FOUND");
|
|
2267
|
+
}
|
|
2268
|
+
if (row.state !== "waiting" && row.state !== "active") {
|
|
2269
|
+
return { ok: true };
|
|
2270
|
+
}
|
|
2271
|
+
const meta = parseMetadata(row.trigger_metadata);
|
|
2272
|
+
const starterId = idOrSelf(meta.user);
|
|
2273
|
+
const isStarter = starterId != null && Number(starterId) === user.id;
|
|
2274
|
+
if (!isStarter && user.super_admin !== true) {
|
|
2275
|
+
throw new StartImportError("NOT_AUTHORIZED");
|
|
2276
|
+
}
|
|
2277
|
+
await db("job_results").where({ id: jobResultId }).update({ metadata: mergeMetadataRaw(db, { cancelRequested: true }) });
|
|
2278
|
+
if (row.state === "waiting") {
|
|
2279
|
+
try {
|
|
2280
|
+
const job = await queue.getJob?.(jobResultId);
|
|
2281
|
+
await job?.remove();
|
|
2282
|
+
} catch (error) {
|
|
2283
|
+
console.error("[EXULU] failed to remove queued import job after cancel", error);
|
|
2284
|
+
}
|
|
2285
|
+
await db("job_results").where({ id: jobResultId }).whereIn("state", ["waiting"]).update({ state: "cancelled" });
|
|
2286
|
+
} else {
|
|
2287
|
+
try {
|
|
2288
|
+
const job = await queue.getJob?.(jobResultId);
|
|
2289
|
+
if (!job) {
|
|
2290
|
+
await db("job_results").where({ id: jobResultId }).whereIn("state", ["active"]).update({ state: "cancelled" });
|
|
2291
|
+
}
|
|
2292
|
+
} catch (error) {
|
|
2293
|
+
console.error("[EXULU] failed to inspect the running import job after cancel", error);
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
return { ok: true };
|
|
2297
|
+
}
|
|
2298
|
+
|
|
1808
2299
|
// src/exulu/shared-artifacts.ts
|
|
1809
2300
|
import bcrypt2 from "bcryptjs";
|
|
1810
2301
|
var normalizeS3Key = (key, bucket) => {
|
|
@@ -2000,10 +2491,10 @@ var currentChunksDimensionality = async (contextId) => {
|
|
|
2000
2491
|
[getChunksTableName(contextId)]
|
|
2001
2492
|
);
|
|
2002
2493
|
return parseVectorDimensionality(result?.rows?.[0]?.type ?? null);
|
|
2003
|
-
} catch (
|
|
2494
|
+
} catch (err2) {
|
|
2004
2495
|
console.warn(
|
|
2005
2496
|
`[EXULU] Could not read the chunk vector dimensionality for "${contextId}":`,
|
|
2006
|
-
|
|
2497
|
+
err2.message
|
|
2007
2498
|
);
|
|
2008
2499
|
return null;
|
|
2009
2500
|
}
|
|
@@ -2114,10 +2605,10 @@ var getTranscriptsSettings = async () => {
|
|
|
2114
2605
|
const { db } = await postgresClient();
|
|
2115
2606
|
const row = await db.from("platform_configurations").where({ config_key: TRANSCRIPTS_SETTINGS_KEY }).first();
|
|
2116
2607
|
return { ...EMPTY, ...parseStoredSettings(row) ?? {} };
|
|
2117
|
-
} catch (
|
|
2608
|
+
} catch (err2) {
|
|
2118
2609
|
console.warn(
|
|
2119
2610
|
"[EXULU] Could not read the Transcripts settings:",
|
|
2120
|
-
|
|
2611
|
+
err2.message
|
|
2121
2612
|
);
|
|
2122
2613
|
return { ...EMPTY };
|
|
2123
2614
|
}
|
|
@@ -2231,7 +2722,7 @@ var parseSettingsInput = (input) => {
|
|
|
2231
2722
|
};
|
|
2232
2723
|
|
|
2233
2724
|
// src/graphql/mutations/index.ts
|
|
2234
|
-
var
|
|
2725
|
+
var VALID_RIGHTS_MODES3 = ["private", "users", "roles", "teams", "public"];
|
|
2235
2726
|
var postprocessDeletion = async ({
|
|
2236
2727
|
table,
|
|
2237
2728
|
requestedFields,
|
|
@@ -2373,10 +2864,10 @@ var buildTranscriptsSettingsInfo = async () => {
|
|
|
2373
2864
|
const { db } = await postgresClient();
|
|
2374
2865
|
const promptRows = await db.from("prompt_library").select("id");
|
|
2375
2866
|
livePromptIds = new Set(promptRows.map((row) => String(row.id)));
|
|
2376
|
-
} catch (
|
|
2867
|
+
} catch (err2) {
|
|
2377
2868
|
console.warn(
|
|
2378
2869
|
"[EXULU] Could not read prompt_library for the Transcripts settings page:",
|
|
2379
|
-
|
|
2870
|
+
err2.message
|
|
2380
2871
|
);
|
|
2381
2872
|
}
|
|
2382
2873
|
let liveAgentIds = null;
|
|
@@ -2384,10 +2875,10 @@ var buildTranscriptsSettingsInfo = async () => {
|
|
|
2384
2875
|
const { db } = await postgresClient();
|
|
2385
2876
|
const agentRows = await db.from("agents").select("id");
|
|
2386
2877
|
liveAgentIds = new Set(agentRows.map((row) => String(row.id)));
|
|
2387
|
-
} catch (
|
|
2878
|
+
} catch (err2) {
|
|
2388
2879
|
console.warn(
|
|
2389
2880
|
"[EXULU] Could not read agents for the Transcripts settings page:",
|
|
2390
|
-
|
|
2881
|
+
err2.message
|
|
2391
2882
|
);
|
|
2392
2883
|
}
|
|
2393
2884
|
const { live, stale } = livePromptIds && liveAgentIds ? filterLivePresets(resolved.summaryPresets.value, livePromptIds, liveAgentIds) : { live: resolved.summaryPresets.value, stale: [] };
|
|
@@ -2600,9 +3091,9 @@ function createMutations(table, contexts, tools, config) {
|
|
|
2600
3091
|
input.id = db.fn.uuid();
|
|
2601
3092
|
}
|
|
2602
3093
|
}
|
|
2603
|
-
if (table.RBAC && input.rights_mode != null && !
|
|
3094
|
+
if (table.RBAC && input.rights_mode != null && !VALID_RIGHTS_MODES3.includes(input.rights_mode)) {
|
|
2604
3095
|
throw new Error(
|
|
2605
|
-
`Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${
|
|
3096
|
+
`Invalid rights_mode "${input.rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES3.join(", ")}`
|
|
2606
3097
|
);
|
|
2607
3098
|
}
|
|
2608
3099
|
const columns = await db(tableNamePlural).columnInfo();
|
|
@@ -3010,6 +3501,89 @@ function createMutations(table, contexts, tools, config) {
|
|
|
3010
3501
|
items
|
|
3011
3502
|
};
|
|
3012
3503
|
};
|
|
3504
|
+
const getImportQueue = async () => {
|
|
3505
|
+
let registered;
|
|
3506
|
+
try {
|
|
3507
|
+
registered = registerImportQueue();
|
|
3508
|
+
} catch (error) {
|
|
3509
|
+
throw new Error("QUEUES_NOT_LICENSED");
|
|
3510
|
+
}
|
|
3511
|
+
let importQueue;
|
|
3512
|
+
try {
|
|
3513
|
+
importQueue = await registered.use();
|
|
3514
|
+
} catch (error) {
|
|
3515
|
+
console.error("[EXULU] import queue unavailable", error);
|
|
3516
|
+
throw error;
|
|
3517
|
+
}
|
|
3518
|
+
return {
|
|
3519
|
+
add: (name, data, opts) => importQueue.queue.add(name, data, opts),
|
|
3520
|
+
getJob: (id) => importQueue.queue.getJob(id)
|
|
3521
|
+
};
|
|
3522
|
+
};
|
|
3523
|
+
mutations[`${tableNameSingular}StartImport`] = async (_, args, context, info) => {
|
|
3524
|
+
if (!context.user) {
|
|
3525
|
+
throw new Error("NOT_AUTHORIZED");
|
|
3526
|
+
}
|
|
3527
|
+
if (!table.id) {
|
|
3528
|
+
throw new Error("CONTEXT_NOT_FOUND");
|
|
3529
|
+
}
|
|
3530
|
+
const queue = await getImportQueue();
|
|
3531
|
+
try {
|
|
3532
|
+
return await startImport(
|
|
3533
|
+
{
|
|
3534
|
+
db: context.db,
|
|
3535
|
+
config,
|
|
3536
|
+
queue,
|
|
3537
|
+
user: context.user,
|
|
3538
|
+
// Mirrors ExecuteSource's own `exists` lookup above, as a
|
|
3539
|
+
// predicate rather than a one-shot find (start-import.ts needs
|
|
3540
|
+
// it before it knows the id is even valid).
|
|
3541
|
+
contextExists: (id) => contexts.some((c) => c.id === id)
|
|
3542
|
+
},
|
|
3543
|
+
{
|
|
3544
|
+
contextId: table.id,
|
|
3545
|
+
s3Key: args.input.s3Key,
|
|
3546
|
+
fileName: args.input.fileName,
|
|
3547
|
+
mapping: args.input.mapping,
|
|
3548
|
+
access: args.input.access,
|
|
3549
|
+
options: args.input.options,
|
|
3550
|
+
// Runs-view provenance (same rule as the workflow-run resolver
|
|
3551
|
+
// at src/graphql/schemas/index.ts:1964): API-key callers get
|
|
3552
|
+
// "api", everyone else (UI session) gets "ui".
|
|
3553
|
+
trigger: context.user.type === "api" ? "api" : "ui",
|
|
3554
|
+
totalRows: args.input.totalRows
|
|
3555
|
+
}
|
|
3556
|
+
);
|
|
3557
|
+
} catch (error) {
|
|
3558
|
+
if (error instanceof StartImportError) {
|
|
3559
|
+
throw new Error(error.code);
|
|
3560
|
+
}
|
|
3561
|
+
throw error;
|
|
3562
|
+
}
|
|
3563
|
+
};
|
|
3564
|
+
mutations[`${tableNameSingular}CancelImport`] = async (_, args, context, info) => {
|
|
3565
|
+
if (!context.user) {
|
|
3566
|
+
throw new Error("NOT_AUTHORIZED");
|
|
3567
|
+
}
|
|
3568
|
+
const queue = await getImportQueue();
|
|
3569
|
+
try {
|
|
3570
|
+
return await cancelImport(
|
|
3571
|
+
{
|
|
3572
|
+
db: context.db,
|
|
3573
|
+
config,
|
|
3574
|
+
queue,
|
|
3575
|
+
user: context.user,
|
|
3576
|
+
contextExists: (id) => contexts.some((c) => c.id === id)
|
|
3577
|
+
},
|
|
3578
|
+
args.jobResultId
|
|
3579
|
+
);
|
|
3580
|
+
} catch (error) {
|
|
3581
|
+
if (error instanceof StartImportError) {
|
|
3582
|
+
throw new Error(error.code);
|
|
3583
|
+
}
|
|
3584
|
+
throw error;
|
|
3585
|
+
}
|
|
3586
|
+
};
|
|
3013
3587
|
mutations[`${tableNameSingular}GenerateChunks`] = async (_, args, context, info) => {
|
|
3014
3588
|
const { db } = await postgresClient();
|
|
3015
3589
|
const exists = contexts.find((context2) => context2.id === table.id);
|
|
@@ -3212,9 +3786,9 @@ function createMutations(table, contexts, tools, config) {
|
|
|
3212
3786
|
rebuild: result.case,
|
|
3213
3787
|
itemsQueued: result.items
|
|
3214
3788
|
};
|
|
3215
|
-
} catch (
|
|
3789
|
+
} catch (err2) {
|
|
3216
3790
|
ctx.embedder = previous;
|
|
3217
|
-
throw
|
|
3791
|
+
throw err2;
|
|
3218
3792
|
}
|
|
3219
3793
|
};
|
|
3220
3794
|
mutations[`${tableNameSingular}ExtractEntities`] = async (_, args, context) => {
|
|
@@ -3250,9 +3824,9 @@ function createMutations(table, contexts, tools, config) {
|
|
|
3250
3824
|
if (!Array.isArray(ids) || ids.length === 0) {
|
|
3251
3825
|
throw new Error("ids is required and must be a non-empty array.");
|
|
3252
3826
|
}
|
|
3253
|
-
if (!
|
|
3827
|
+
if (!VALID_RIGHTS_MODES3.includes(rights_mode)) {
|
|
3254
3828
|
throw new Error(
|
|
3255
|
-
`Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${
|
|
3829
|
+
`Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES3.join(", ")}`
|
|
3256
3830
|
);
|
|
3257
3831
|
}
|
|
3258
3832
|
for (const id of ids) {
|
|
@@ -3302,9 +3876,7 @@ function createMutations(table, contexts, tools, config) {
|
|
|
3302
3876
|
if (!inner) continue;
|
|
3303
3877
|
mutations[key] = async (parent, args, context, info) => {
|
|
3304
3878
|
if (context?.user?.super_admin !== true) {
|
|
3305
|
-
throw new Error(
|
|
3306
|
-
`${table.name.plural} rows are changed through their own API; the generic mutation is reserved for super admins.`
|
|
3307
|
-
);
|
|
3879
|
+
throw new Error(`${table.name.plural} rows may only be changed by super admins through this API.`);
|
|
3308
3880
|
}
|
|
3309
3881
|
return inner(parent, args, context, info);
|
|
3310
3882
|
};
|
|
@@ -3329,12 +3901,12 @@ var bullmq = {
|
|
|
3329
3901
|
if (!data.inputs) {
|
|
3330
3902
|
throw new Error(`Missing property "inputs" in data for job ${id}.`);
|
|
3331
3903
|
}
|
|
3332
|
-
if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function" && data.type !== "source" && data.type !== "email_intake") {
|
|
3904
|
+
if (data.type !== "embedder" && data.type !== "workflow" && data.type !== "processor" && data.type !== "eval_run" && data.type !== "eval_function" && data.type !== "source" && data.type !== "email_intake" && data.type !== "import") {
|
|
3333
3905
|
throw new Error(
|
|
3334
|
-
`Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run", "eval_function", "source" or "
|
|
3906
|
+
`Property "type" in data for job ${id} must be of value "embedder", "workflow", "processor", "eval_run", "eval_function", "source", "email_intake" or "import".`
|
|
3335
3907
|
);
|
|
3336
3908
|
}
|
|
3337
|
-
if (data.type !== "email_intake" && !data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length && !data.source) {
|
|
3909
|
+
if (data.type !== "email_intake" && data.type !== "import" && !data.workflow && !data.embedder && !data.processor && !data.eval_run_id && !data.eval_functions?.length && !data.source) {
|
|
3338
3910
|
throw new Error(
|
|
3339
3911
|
`Either a workflow, embedder, processor, eval_run, eval_functions or source must be set for job ${id}.`
|
|
3340
3912
|
);
|
|
@@ -3342,36 +3914,6 @@ var bullmq = {
|
|
|
3342
3914
|
}
|
|
3343
3915
|
};
|
|
3344
3916
|
|
|
3345
|
-
// src/utils/serialize-error.ts
|
|
3346
|
-
var MAX_CAUSE_DEPTH = 3;
|
|
3347
|
-
function serializeError(err, depth = 0) {
|
|
3348
|
-
if (err instanceof Error) {
|
|
3349
|
-
const out = { name: err.name, message: err.message };
|
|
3350
|
-
if (err.stack) out.stack = err.stack;
|
|
3351
|
-
for (const [key, value] of Object.entries(err)) {
|
|
3352
|
-
if (key !== "cause") out[key] = value;
|
|
3353
|
-
}
|
|
3354
|
-
const cause = err.cause;
|
|
3355
|
-
if (cause !== void 0 && depth < MAX_CAUSE_DEPTH) {
|
|
3356
|
-
out.cause = serializeError(cause, depth + 1);
|
|
3357
|
-
}
|
|
3358
|
-
return out;
|
|
3359
|
-
}
|
|
3360
|
-
if (typeof err === "string") {
|
|
3361
|
-
return { message: err };
|
|
3362
|
-
}
|
|
3363
|
-
if (err !== null && typeof err === "object") {
|
|
3364
|
-
let message;
|
|
3365
|
-
try {
|
|
3366
|
-
message = JSON.stringify(err);
|
|
3367
|
-
} catch {
|
|
3368
|
-
message = "[unserializable error object]";
|
|
3369
|
-
}
|
|
3370
|
-
return { ...err, message };
|
|
3371
|
-
}
|
|
3372
|
-
return { message: String(err) };
|
|
3373
|
-
}
|
|
3374
|
-
|
|
3375
3917
|
// src/exulu/turn-metadata.ts
|
|
3376
3918
|
function finishTurnMetadata(opts) {
|
|
3377
3919
|
const now = opts.now ?? Date.now();
|
|
@@ -3484,8 +4026,8 @@ async function resolveFreshFileUrl(url, opts) {
|
|
|
3484
4026
|
if (!location) return url;
|
|
3485
4027
|
try {
|
|
3486
4028
|
return await opts.sign(location.bucket, location.key);
|
|
3487
|
-
} catch (
|
|
3488
|
-
console.warn(`[EXULU] could not re-sign stored file URL for key "${location.key}":`,
|
|
4029
|
+
} catch (err2) {
|
|
4030
|
+
console.warn(`[EXULU] could not re-sign stored file URL for key "${location.key}":`, err2);
|
|
3489
4031
|
return url;
|
|
3490
4032
|
}
|
|
3491
4033
|
}
|
|
@@ -3532,8 +4074,8 @@ async function loadSessionFileListing(opts) {
|
|
|
3532
4074
|
lastModified: new Date(o.lastModified)
|
|
3533
4075
|
}));
|
|
3534
4076
|
return describeSessionFiles(files, { lastTurnAt: opts.lastTurnAt });
|
|
3535
|
-
} catch (
|
|
3536
|
-
console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`,
|
|
4077
|
+
} catch (err2) {
|
|
4078
|
+
console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`, err2);
|
|
3537
4079
|
return "";
|
|
3538
4080
|
}
|
|
3539
4081
|
}
|
|
@@ -3974,7 +4516,7 @@ async function recordMemoryUsage(input) {
|
|
|
3974
4516
|
}
|
|
3975
4517
|
|
|
3976
4518
|
// src/exulu/generate-stream.ts
|
|
3977
|
-
import { randomUUID } from "crypto";
|
|
4519
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
3978
4520
|
var processFilePartsInMessages = async (messages, offloadCtx) => {
|
|
3979
4521
|
const processedMessages = await Promise.all(
|
|
3980
4522
|
messages.map(async (message) => {
|
|
@@ -4377,7 +4919,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
4377
4919
|
contextId: agent.memory,
|
|
4378
4920
|
agentId: agent.id,
|
|
4379
4921
|
session: session ?? null,
|
|
4380
|
-
messageId: output.response?.id ??
|
|
4922
|
+
messageId: output.response?.id ?? randomUUID2(),
|
|
4381
4923
|
userId: user?.id ?? null
|
|
4382
4924
|
});
|
|
4383
4925
|
}
|
|
@@ -4452,7 +4994,7 @@ When a tool execution is not approved by the user, do not retry it unless explic
|
|
|
4452
4994
|
contextId: agent.memory,
|
|
4453
4995
|
agentId: agent.id,
|
|
4454
4996
|
session: session ?? null,
|
|
4455
|
-
messageId: response?.id ??
|
|
4997
|
+
messageId: response?.id ?? randomUUID2(),
|
|
4456
4998
|
userId: user?.id ?? null
|
|
4457
4999
|
});
|
|
4458
5000
|
}
|
|
@@ -4767,10 +5309,10 @@ function extractGlossaryFromAgentTools(tools) {
|
|
|
4767
5309
|
return glossary.filter(
|
|
4768
5310
|
(g) => !!g && typeof g.term === "string" && typeof g.meaning === "string" && g.term.trim().length > 0
|
|
4769
5311
|
);
|
|
4770
|
-
} catch (
|
|
5312
|
+
} catch (err2) {
|
|
4771
5313
|
console.warn(
|
|
4772
5314
|
"[EXULU] Failed to parse the agentic_context_search vocabulary config while building agent instructions.",
|
|
4773
|
-
|
|
5315
|
+
err2
|
|
4774
5316
|
);
|
|
4775
5317
|
return [];
|
|
4776
5318
|
}
|
|
@@ -4951,7 +5493,7 @@ import { createIdGenerator } from "ai";
|
|
|
4951
5493
|
import "crypto-js";
|
|
4952
5494
|
|
|
4953
5495
|
// src/exulu/email-inbound/intake.ts
|
|
4954
|
-
import { randomUUID as
|
|
5496
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
4955
5497
|
|
|
4956
5498
|
// src/exulu/email-inbound/normalize.ts
|
|
4957
5499
|
import { createHash } from "crypto";
|
|
@@ -5014,7 +5556,7 @@ async function parseRawMime(raw) {
|
|
|
5014
5556
|
}
|
|
5015
5557
|
|
|
5016
5558
|
// src/exulu/email-inbound/adapters.ts
|
|
5017
|
-
import { randomUUID as
|
|
5559
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
5018
5560
|
import { Readable } from "stream";
|
|
5019
5561
|
import Busboy from "busboy";
|
|
5020
5562
|
var htmlToText2 = (html) => html.replace(/<\s*(script|style)[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi, "").replace(/<[^>]+>/g, " ").replace(/ /gi, " ").replace(/&/gi, "&").replace(/</gi, "<").replace(/>/gi, ">").replace(/\s+/g, " ").trim();
|
|
@@ -5059,7 +5601,7 @@ function extractMultipartMimePart(rawBody, contentType) {
|
|
|
5059
5601
|
if (found) resolve4(found);
|
|
5060
5602
|
else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
|
|
5061
5603
|
});
|
|
5062
|
-
bb.on("error", (
|
|
5604
|
+
bb.on("error", (err2) => reject(err2 instanceof Error ? err2 : new Error(String(err2))));
|
|
5063
5605
|
Readable.from(rawBody).pipe(bb);
|
|
5064
5606
|
});
|
|
5065
5607
|
}
|
|
@@ -5072,7 +5614,7 @@ function jsonToInboundEmail(raw) {
|
|
|
5072
5614
|
const subject = typeof obj.subject === "string" ? obj.subject : "";
|
|
5073
5615
|
const html = typeof obj.html === "string" ? obj.html : void 0;
|
|
5074
5616
|
const text = typeof obj.text === "string" && obj.text ? obj.text : html ? htmlToText2(html) : "";
|
|
5075
|
-
const messageId = typeof obj.message_id === "string" && obj.message_id ? obj.message_id : `<${
|
|
5617
|
+
const messageId = typeof obj.message_id === "string" && obj.message_id ? obj.message_id : `<${randomUUID3()}@webhook.local>`;
|
|
5076
5618
|
const attachments = Array.isArray(obj.attachments) ? obj.attachments.map(decodeAttachment) : [];
|
|
5077
5619
|
const headers = /* @__PURE__ */ new Map([["message-id", messageId]]);
|
|
5078
5620
|
return {
|
|
@@ -5151,10 +5693,10 @@ var checkRateLimit = async (redis, key, limitPerHour, now = Date.now()) => {
|
|
|
5151
5693
|
const elapsedFraction = now % HOUR_MS / HOUR_MS;
|
|
5152
5694
|
const weighted = count + previous * (1 - elapsedFraction);
|
|
5153
5695
|
return weighted <= limitPerHour;
|
|
5154
|
-
} catch (
|
|
5696
|
+
} catch (err2) {
|
|
5155
5697
|
console.error(
|
|
5156
5698
|
"[EXULU] email-inbound rate limit: redis unavailable, allowing (best-effort)",
|
|
5157
|
-
|
|
5699
|
+
err2 instanceof Error ? err2.message : String(err2)
|
|
5158
5700
|
);
|
|
5159
5701
|
return true;
|
|
5160
5702
|
}
|
|
@@ -5306,7 +5848,7 @@ var fireRun = async (opts) => {
|
|
|
5306
5848
|
}
|
|
5307
5849
|
const fromDisplay = email.from.name ? `"${email.from.name}" <${email.from.address}>` : `<${email.from.address}>`;
|
|
5308
5850
|
const initialMessage = {
|
|
5309
|
-
id:
|
|
5851
|
+
id: randomUUID4(),
|
|
5310
5852
|
role: "user",
|
|
5311
5853
|
parts: [
|
|
5312
5854
|
{
|
|
@@ -5485,6 +6027,417 @@ function computeRunCostUsd(inputTokens, outputTokens, price) {
|
|
|
5485
6027
|
return inTok / 1e6 * inPrice + outTok / 1e6 * outPrice;
|
|
5486
6028
|
}
|
|
5487
6029
|
|
|
6030
|
+
// src/exulu/import/csv-stream.ts
|
|
6031
|
+
import { Transform } from "stream";
|
|
6032
|
+
import { parse } from "csv-parse";
|
|
6033
|
+
var CANDIDATE_DELIMITERS = [",", ";", " ", "|"];
|
|
6034
|
+
var MAX_HEADER_BYTES = 64 * 1024;
|
|
6035
|
+
function sniffDelimiter(headerLine) {
|
|
6036
|
+
const counts = new Map(CANDIDATE_DELIMITERS.map((d) => [d, 0]));
|
|
6037
|
+
let inQuotes = false;
|
|
6038
|
+
for (const char of headerLine) {
|
|
6039
|
+
if (char === '"') {
|
|
6040
|
+
inQuotes = !inQuotes;
|
|
6041
|
+
continue;
|
|
6042
|
+
}
|
|
6043
|
+
if (inQuotes) continue;
|
|
6044
|
+
const seen = counts.get(char);
|
|
6045
|
+
if (seen !== void 0) counts.set(char, seen + 1);
|
|
6046
|
+
}
|
|
6047
|
+
let best = CANDIDATE_DELIMITERS[0];
|
|
6048
|
+
let bestCount = 0;
|
|
6049
|
+
for (const candidate of CANDIDATE_DELIMITERS) {
|
|
6050
|
+
const count = counts.get(candidate) ?? 0;
|
|
6051
|
+
if (count > bestCount) {
|
|
6052
|
+
best = candidate;
|
|
6053
|
+
bestCount = count;
|
|
6054
|
+
}
|
|
6055
|
+
}
|
|
6056
|
+
return best;
|
|
6057
|
+
}
|
|
6058
|
+
function createSniffer(onFirstLine) {
|
|
6059
|
+
const head = [];
|
|
6060
|
+
let headBytes = 0;
|
|
6061
|
+
let resolved = false;
|
|
6062
|
+
const resolve4 = (line) => {
|
|
6063
|
+
if (resolved) return;
|
|
6064
|
+
resolved = true;
|
|
6065
|
+
onFirstLine(line);
|
|
6066
|
+
};
|
|
6067
|
+
return new Transform({
|
|
6068
|
+
readableHighWaterMark: 4 * MAX_HEADER_BYTES,
|
|
6069
|
+
transform(chunk2, _encoding, callback) {
|
|
6070
|
+
if (!resolved) {
|
|
6071
|
+
const buffer = Buffer.isBuffer(chunk2) ? chunk2 : Buffer.from(String(chunk2));
|
|
6072
|
+
head.push(buffer);
|
|
6073
|
+
headBytes += buffer.length;
|
|
6074
|
+
const text = Buffer.concat(head).toString("utf-8");
|
|
6075
|
+
const eol = /\r|\n/.exec(text);
|
|
6076
|
+
if (eol) {
|
|
6077
|
+
resolve4(text.slice(0, eol.index));
|
|
6078
|
+
} else if (headBytes >= MAX_HEADER_BYTES) {
|
|
6079
|
+
resolve4(text);
|
|
6080
|
+
}
|
|
6081
|
+
}
|
|
6082
|
+
callback(null, chunk2);
|
|
6083
|
+
},
|
|
6084
|
+
flush(callback) {
|
|
6085
|
+
resolve4(Buffer.concat(head).toString("utf-8"));
|
|
6086
|
+
callback();
|
|
6087
|
+
}
|
|
6088
|
+
});
|
|
6089
|
+
}
|
|
6090
|
+
async function streamCsvRows(input, handlers, opts) {
|
|
6091
|
+
let resolveFirstLine = () => {
|
|
6092
|
+
};
|
|
6093
|
+
const firstLine = new Promise((resolve4) => {
|
|
6094
|
+
resolveFirstLine = resolve4;
|
|
6095
|
+
});
|
|
6096
|
+
const sniffer = createSniffer((line) => resolveFirstLine(line));
|
|
6097
|
+
let parser;
|
|
6098
|
+
let earlyError;
|
|
6099
|
+
input.on("error", (err2) => sniffer.destroy(err2));
|
|
6100
|
+
sniffer.on("error", (err2) => {
|
|
6101
|
+
if (parser) parser.destroy(err2);
|
|
6102
|
+
else {
|
|
6103
|
+
earlyError = err2;
|
|
6104
|
+
resolveFirstLine("");
|
|
6105
|
+
}
|
|
6106
|
+
});
|
|
6107
|
+
input.pipe(sniffer);
|
|
6108
|
+
const headerLine = await firstLine;
|
|
6109
|
+
if (earlyError) throw earlyError;
|
|
6110
|
+
const delimiter = opts?.delimiter ?? sniffDelimiter(headerLine);
|
|
6111
|
+
parser = parse({
|
|
6112
|
+
bom: true,
|
|
6113
|
+
relax_quotes: true,
|
|
6114
|
+
relax_column_count: true,
|
|
6115
|
+
skip_empty_lines: true,
|
|
6116
|
+
columns: false,
|
|
6117
|
+
delimiter,
|
|
6118
|
+
// csv-parse's auto record-delimiter discovery locks onto the first
|
|
6119
|
+
// line ending it sees (outside quotes) and never reconsiders -- a file
|
|
6120
|
+
// whose header ends in "\n" but has later rows ending in "\r\n" (or
|
|
6121
|
+
// vice versa) would then have the "\r" leak into field content instead
|
|
6122
|
+
// of being recognized as part of the delimiter. Listing all three EOL
|
|
6123
|
+
// styles up front avoids that trap for real-world, possibly
|
|
6124
|
+
// inconsistently-terminated uploads.
|
|
6125
|
+
record_delimiter: ["\r\n", "\n", "\r"]
|
|
6126
|
+
});
|
|
6127
|
+
sniffer.pipe(parser);
|
|
6128
|
+
let sawHeader = false;
|
|
6129
|
+
let index = 0;
|
|
6130
|
+
for await (const record of parser) {
|
|
6131
|
+
if (!sawHeader) {
|
|
6132
|
+
sawHeader = true;
|
|
6133
|
+
await handlers.onHeader(record.map((cell) => cell.trim()));
|
|
6134
|
+
continue;
|
|
6135
|
+
}
|
|
6136
|
+
if (record.every((cell) => cell.trim() === "")) continue;
|
|
6137
|
+
await handlers.onRow(record, index);
|
|
6138
|
+
index++;
|
|
6139
|
+
}
|
|
6140
|
+
return { rows: index };
|
|
6141
|
+
}
|
|
6142
|
+
|
|
6143
|
+
// src/exulu/import/mapping.ts
|
|
6144
|
+
function normalizeHeader(value) {
|
|
6145
|
+
return value.trim().toLowerCase().replace(/[\s-]+/g, "_");
|
|
6146
|
+
}
|
|
6147
|
+
function headerMatchesField(field, normalizedHeader) {
|
|
6148
|
+
if (normalizeHeader(field.name) === normalizedHeader) return true;
|
|
6149
|
+
return field.label != null && normalizeHeader(field.label) === normalizedHeader;
|
|
6150
|
+
}
|
|
6151
|
+
function autoMapColumns(headers, fields) {
|
|
6152
|
+
const used = /* @__PURE__ */ new Set();
|
|
6153
|
+
return headers.map((header2) => {
|
|
6154
|
+
const normalized = normalizeHeader(header2);
|
|
6155
|
+
const match = fields.find((f) => !used.has(f.name) && headerMatchesField(f, normalized));
|
|
6156
|
+
if (!match) return { header: header2, fieldName: null };
|
|
6157
|
+
used.add(match.name);
|
|
6158
|
+
return { header: header2, fieldName: match.name };
|
|
6159
|
+
});
|
|
6160
|
+
}
|
|
6161
|
+
var CORE_FIELDS = [
|
|
6162
|
+
{ name: "id", type: "text", core: true },
|
|
6163
|
+
{ name: "external_id", type: "text", core: true },
|
|
6164
|
+
{ name: "name", type: "shortText", required: true, core: true },
|
|
6165
|
+
{ name: "description", type: "longText", core: true },
|
|
6166
|
+
{ name: "tags", type: "text", core: true }
|
|
6167
|
+
];
|
|
6168
|
+
function importFieldsFor(fields) {
|
|
6169
|
+
const custom = fields.filter((f) => !f.calculated && !f.hidden && f.type !== "file").map((f) => ({
|
|
6170
|
+
name: sanitizeName(f.name),
|
|
6171
|
+
label: f.name,
|
|
6172
|
+
type: f.type,
|
|
6173
|
+
required: f.required === true,
|
|
6174
|
+
core: false,
|
|
6175
|
+
enumValues: f.enumValues
|
|
6176
|
+
}));
|
|
6177
|
+
return [...CORE_FIELDS, ...custom];
|
|
6178
|
+
}
|
|
6179
|
+
function resolveMapping(headers, fields, given) {
|
|
6180
|
+
if (!given) {
|
|
6181
|
+
return { byIndex: autoMapColumns(headers, fields).map((m) => m.fieldName), unknownFields: [] };
|
|
6182
|
+
}
|
|
6183
|
+
const fieldNames = new Set(fields.map((f) => f.name));
|
|
6184
|
+
const byHeader = new Map(given.map((g) => [normalizeHeader(g.header), g.fieldName]));
|
|
6185
|
+
const unknownFields = /* @__PURE__ */ new Set();
|
|
6186
|
+
const byIndex = headers.map((header2) => {
|
|
6187
|
+
const fieldName = byHeader.get(normalizeHeader(header2));
|
|
6188
|
+
if (fieldName == null) return null;
|
|
6189
|
+
if (!fieldNames.has(fieldName)) {
|
|
6190
|
+
unknownFields.add(fieldName);
|
|
6191
|
+
return null;
|
|
6192
|
+
}
|
|
6193
|
+
return fieldName;
|
|
6194
|
+
});
|
|
6195
|
+
return { byIndex, unknownFields: [...unknownFields] };
|
|
6196
|
+
}
|
|
6197
|
+
|
|
6198
|
+
// src/exulu/import/run-import.ts
|
|
6199
|
+
var ABORT_MESSAGES = {
|
|
6200
|
+
NO_MAPPABLE_COLUMNS: "No column in the file maps to a usable field (name, id, or external_id).",
|
|
6201
|
+
EMPTY_FILE: "The file has no header row."
|
|
6202
|
+
};
|
|
6203
|
+
var ImportAbort = class extends Error {
|
|
6204
|
+
constructor(code) {
|
|
6205
|
+
super(ABORT_MESSAGES[code]);
|
|
6206
|
+
this.code = code;
|
|
6207
|
+
this.name = "ImportAbort";
|
|
6208
|
+
}
|
|
6209
|
+
};
|
|
6210
|
+
var DEFAULT_CHUNK_ROWS = 500;
|
|
6211
|
+
var DEFAULT_CONCURRENCY = 8;
|
|
6212
|
+
var DEFAULT_PROGRESS_INTERVAL_MS = 1e4;
|
|
6213
|
+
var IMPORT_MAX_ERROR_LINES = 5e4;
|
|
6214
|
+
var RunCancelled = class extends Error {
|
|
6215
|
+
};
|
|
6216
|
+
function csvField(value) {
|
|
6217
|
+
return /["\n\r,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
|
|
6218
|
+
}
|
|
6219
|
+
function csvLine(cells) {
|
|
6220
|
+
return cells.map(csvField).join(",");
|
|
6221
|
+
}
|
|
6222
|
+
async function runPool(items, concurrency, worker) {
|
|
6223
|
+
let next = 0;
|
|
6224
|
+
const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
|
|
6225
|
+
while (next < items.length) {
|
|
6226
|
+
const index = next;
|
|
6227
|
+
next += 1;
|
|
6228
|
+
await worker(items[index]);
|
|
6229
|
+
}
|
|
6230
|
+
});
|
|
6231
|
+
await Promise.all(runners);
|
|
6232
|
+
}
|
|
6233
|
+
async function runImport(deps) {
|
|
6234
|
+
const now = deps.now ?? Date.now;
|
|
6235
|
+
const log6 = deps.log ?? (() => {
|
|
6236
|
+
});
|
|
6237
|
+
const chunkRows = deps.chunkRows ?? DEFAULT_CHUNK_ROWS;
|
|
6238
|
+
const concurrency = deps.concurrency ?? DEFAULT_CONCURRENCY;
|
|
6239
|
+
const progressIntervalMs = deps.progressIntervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS;
|
|
6240
|
+
const maxErrorLines = deps.maxErrorLines ?? IMPORT_MAX_ERROR_LINES;
|
|
6241
|
+
const startedAt = now();
|
|
6242
|
+
const metadata = {
|
|
6243
|
+
total: deps.total ?? null,
|
|
6244
|
+
processed: 0,
|
|
6245
|
+
created: 0,
|
|
6246
|
+
updated: 0,
|
|
6247
|
+
failed: 0,
|
|
6248
|
+
invalid: 0
|
|
6249
|
+
};
|
|
6250
|
+
let cancelled = false;
|
|
6251
|
+
let headerSeen = false;
|
|
6252
|
+
let headerCells = [];
|
|
6253
|
+
let byIndex = [];
|
|
6254
|
+
const errorLines = [];
|
|
6255
|
+
let truncatedErrorCount = 0;
|
|
6256
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
6257
|
+
const seenExternalIds = /* @__PURE__ */ new Set();
|
|
6258
|
+
let buffer = [];
|
|
6259
|
+
let lastTickAt = startedAt;
|
|
6260
|
+
function pushErrorLine(cells, message) {
|
|
6261
|
+
if (errorLines.length < maxErrorLines) {
|
|
6262
|
+
errorLines.push(csvLine([...cells, message]));
|
|
6263
|
+
} else {
|
|
6264
|
+
truncatedErrorCount++;
|
|
6265
|
+
}
|
|
6266
|
+
}
|
|
6267
|
+
async function runCreate(row, cells) {
|
|
6268
|
+
try {
|
|
6269
|
+
await deps.createItem(buildCreateInput(row, deps.access));
|
|
6270
|
+
metadata.created++;
|
|
6271
|
+
} catch (e) {
|
|
6272
|
+
metadata.failed++;
|
|
6273
|
+
pushErrorLine(cells, e instanceof Error ? e.message : String(e));
|
|
6274
|
+
}
|
|
6275
|
+
}
|
|
6276
|
+
async function runUpdate(existing, row, cells) {
|
|
6277
|
+
let allowed;
|
|
6278
|
+
try {
|
|
6279
|
+
allowed = deps.canWrite(existing);
|
|
6280
|
+
} catch (e) {
|
|
6281
|
+
metadata.failed++;
|
|
6282
|
+
pushErrorLine(cells, e instanceof Error ? e.message : String(e));
|
|
6283
|
+
return;
|
|
6284
|
+
}
|
|
6285
|
+
if (!allowed) {
|
|
6286
|
+
metadata.failed++;
|
|
6287
|
+
pushErrorLine(cells, "no write access");
|
|
6288
|
+
return;
|
|
6289
|
+
}
|
|
6290
|
+
try {
|
|
6291
|
+
await deps.updateItem(existing.id, buildUpdateInput(row));
|
|
6292
|
+
metadata.updated++;
|
|
6293
|
+
} catch (e) {
|
|
6294
|
+
metadata.failed++;
|
|
6295
|
+
pushErrorLine(cells, e instanceof Error ? e.message : String(e));
|
|
6296
|
+
}
|
|
6297
|
+
}
|
|
6298
|
+
async function processChunk(chunk2) {
|
|
6299
|
+
if (chunk2.length === 0) return;
|
|
6300
|
+
const toCreate = [];
|
|
6301
|
+
const toUpdate = [];
|
|
6302
|
+
for (const { index, cells } of chunk2) {
|
|
6303
|
+
metadata.processed++;
|
|
6304
|
+
try {
|
|
6305
|
+
const row = buildRow(index, cells, byIndex, deps.fields);
|
|
6306
|
+
if (!rowIsValid(row)) {
|
|
6307
|
+
metadata.invalid++;
|
|
6308
|
+
pushErrorLine(cells, row.errors.join("; "));
|
|
6309
|
+
continue;
|
|
6310
|
+
}
|
|
6311
|
+
const action = rowAction(row);
|
|
6312
|
+
if (action.action === "create") {
|
|
6313
|
+
toCreate.push({ row, cells });
|
|
6314
|
+
continue;
|
|
6315
|
+
}
|
|
6316
|
+
const seen = action.by === "id" ? seenIds : seenExternalIds;
|
|
6317
|
+
if (seen.has(action.key)) {
|
|
6318
|
+
metadata.invalid++;
|
|
6319
|
+
pushErrorLine(cells, `duplicateKey:${action.by}`);
|
|
6320
|
+
continue;
|
|
6321
|
+
}
|
|
6322
|
+
seen.add(action.key);
|
|
6323
|
+
toUpdate.push({ row, by: action.by, key: action.key, cells });
|
|
6324
|
+
} catch (e) {
|
|
6325
|
+
metadata.failed++;
|
|
6326
|
+
pushErrorLine(cells, e instanceof Error ? e.message : String(e));
|
|
6327
|
+
}
|
|
6328
|
+
}
|
|
6329
|
+
const ids = toUpdate.filter((u) => u.by === "id").map((u) => u.key);
|
|
6330
|
+
const externalIds = toUpdate.filter((u) => u.by === "external_id").map((u) => u.key);
|
|
6331
|
+
let existingRows;
|
|
6332
|
+
try {
|
|
6333
|
+
existingRows = ids.length > 0 || externalIds.length > 0 ? await deps.lookupExisting(ids, externalIds) : [];
|
|
6334
|
+
} catch (e) {
|
|
6335
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
6336
|
+
for (const { cells } of toCreate) {
|
|
6337
|
+
metadata.failed++;
|
|
6338
|
+
pushErrorLine(cells, message);
|
|
6339
|
+
}
|
|
6340
|
+
for (const u of toUpdate) {
|
|
6341
|
+
metadata.failed++;
|
|
6342
|
+
pushErrorLine(u.cells, message);
|
|
6343
|
+
}
|
|
6344
|
+
return;
|
|
6345
|
+
}
|
|
6346
|
+
const byId = new Map(existingRows.map((r) => [r.id, r]));
|
|
6347
|
+
const byExternalId = new Map(
|
|
6348
|
+
existingRows.filter((r) => r.external_id != null).map((r) => [r.external_id, r])
|
|
6349
|
+
);
|
|
6350
|
+
const tasks = [];
|
|
6351
|
+
for (const { row, cells } of toCreate) {
|
|
6352
|
+
tasks.push(() => runCreate(row, cells));
|
|
6353
|
+
}
|
|
6354
|
+
for (const u of toUpdate) {
|
|
6355
|
+
const existing = u.by === "id" ? byId.get(u.key) : byExternalId.get(u.key);
|
|
6356
|
+
if (existing) {
|
|
6357
|
+
tasks.push(() => runUpdate(existing, u.row, u.cells));
|
|
6358
|
+
continue;
|
|
6359
|
+
}
|
|
6360
|
+
if (u.by === "id") {
|
|
6361
|
+
metadata.failed++;
|
|
6362
|
+
pushErrorLine(u.cells, "id not found");
|
|
6363
|
+
continue;
|
|
6364
|
+
}
|
|
6365
|
+
tasks.push(() => runCreate(u.row, u.cells));
|
|
6366
|
+
}
|
|
6367
|
+
await runPool(tasks, concurrency, (task) => task());
|
|
6368
|
+
}
|
|
6369
|
+
async function tick3() {
|
|
6370
|
+
lastTickAt = now();
|
|
6371
|
+
await deps.writeProgress({ ...metadata });
|
|
6372
|
+
}
|
|
6373
|
+
try {
|
|
6374
|
+
await streamCsvRows(
|
|
6375
|
+
deps.stream,
|
|
6376
|
+
{
|
|
6377
|
+
onHeader: (headers) => {
|
|
6378
|
+
headerSeen = true;
|
|
6379
|
+
headerCells = headers;
|
|
6380
|
+
const resolved = resolveMapping(headers, deps.fields, deps.mapping);
|
|
6381
|
+
byIndex = resolved.byIndex;
|
|
6382
|
+
const nameMapped = byIndex.includes("name");
|
|
6383
|
+
const keyMapped = byIndex.includes("id") || byIndex.includes("external_id");
|
|
6384
|
+
const allUnmapped = byIndex.every((f) => f === null);
|
|
6385
|
+
if (allUnmapped || !nameMapped && !keyMapped) {
|
|
6386
|
+
throw new ImportAbort("NO_MAPPABLE_COLUMNS");
|
|
6387
|
+
}
|
|
6388
|
+
},
|
|
6389
|
+
onRow: async (cells, index) => {
|
|
6390
|
+
buffer.push({ index, cells });
|
|
6391
|
+
const intervalElapsed = now() - lastTickAt >= progressIntervalMs;
|
|
6392
|
+
if (buffer.length < chunkRows && !intervalElapsed) return;
|
|
6393
|
+
const chunk2 = buffer;
|
|
6394
|
+
buffer = [];
|
|
6395
|
+
await processChunk(chunk2);
|
|
6396
|
+
await tick3();
|
|
6397
|
+
if (await deps.isCancelRequested()) {
|
|
6398
|
+
cancelled = true;
|
|
6399
|
+
log6(`import: cancelled after ${metadata.processed} rows`);
|
|
6400
|
+
throw new RunCancelled();
|
|
6401
|
+
}
|
|
6402
|
+
}
|
|
6403
|
+
},
|
|
6404
|
+
{ delimiter: deps.options.delimiter }
|
|
6405
|
+
);
|
|
6406
|
+
} catch (e) {
|
|
6407
|
+
if (!(e instanceof RunCancelled)) throw e;
|
|
6408
|
+
}
|
|
6409
|
+
if (!headerSeen) {
|
|
6410
|
+
throw new ImportAbort("EMPTY_FILE");
|
|
6411
|
+
}
|
|
6412
|
+
if (!cancelled && buffer.length > 0) {
|
|
6413
|
+
const chunk2 = buffer;
|
|
6414
|
+
buffer = [];
|
|
6415
|
+
await processChunk(chunk2);
|
|
6416
|
+
await tick3();
|
|
6417
|
+
}
|
|
6418
|
+
const errorReportTruncated = truncatedErrorCount > 0;
|
|
6419
|
+
let errorReportKey = null;
|
|
6420
|
+
if (errorLines.length > 0 || errorReportTruncated) {
|
|
6421
|
+
const lines = [csvLine([...headerCells, "import_error"]), ...errorLines];
|
|
6422
|
+
if (errorReportTruncated) {
|
|
6423
|
+
const markerPadding = Array(Math.max(headerCells.length - 1, 0)).fill("");
|
|
6424
|
+
lines.push(csvLine(["\u2026", ...markerPadding, `truncated: ${truncatedErrorCount} more rows not listed`]));
|
|
6425
|
+
}
|
|
6426
|
+
const csv = "\uFEFF" + lines.join("\n");
|
|
6427
|
+
errorReportKey = await deps.uploadErrorReport(csv);
|
|
6428
|
+
}
|
|
6429
|
+
log6(
|
|
6430
|
+
`import: completed -- processed ${metadata.processed}, created ${metadata.created}, updated ${metadata.updated}, failed ${metadata.failed}, invalid ${metadata.invalid}`
|
|
6431
|
+
);
|
|
6432
|
+
return {
|
|
6433
|
+
...metadata,
|
|
6434
|
+
durationMs: now() - startedAt,
|
|
6435
|
+
errorReportKey,
|
|
6436
|
+
cancelled,
|
|
6437
|
+
errorReportTruncated
|
|
6438
|
+
};
|
|
6439
|
+
}
|
|
6440
|
+
|
|
5488
6441
|
// ee/workers.ts
|
|
5489
6442
|
var FlowStepError = class extends Error {
|
|
5490
6443
|
stepIndex;
|
|
@@ -5595,7 +6548,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
5595
6548
|
type: bullmqJob.data.type
|
|
5596
6549
|
});
|
|
5597
6550
|
let progressInterval;
|
|
5598
|
-
if (bullmqJob.data.type === "processor") {
|
|
6551
|
+
if (bullmqJob.data.type === "processor" || bullmqJob.data.type === "import") {
|
|
5599
6552
|
progressInterval = setInterval(async () => {
|
|
5600
6553
|
try {
|
|
5601
6554
|
await bullmqJob.updateProgress({
|
|
@@ -6249,6 +7202,97 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
6249
7202
|
}
|
|
6250
7203
|
};
|
|
6251
7204
|
}
|
|
7205
|
+
if (data.type === "import") {
|
|
7206
|
+
console.log("[EXULU] running a server-side bulk import job.", bullmqJob.name);
|
|
7207
|
+
if (!data.jobResultId) {
|
|
7208
|
+
throw new Error(`No jobResultId set for import job ${bullmqJob.id}.`);
|
|
7209
|
+
}
|
|
7210
|
+
if (!data.context) {
|
|
7211
|
+
throw new Error(`No context id set for import job ${bullmqJob.id}.`);
|
|
7212
|
+
}
|
|
7213
|
+
const importData = {
|
|
7214
|
+
type: "import",
|
|
7215
|
+
jobResultId: data.jobResultId,
|
|
7216
|
+
context: data.context,
|
|
7217
|
+
user: data.user,
|
|
7218
|
+
role: data.role
|
|
7219
|
+
};
|
|
7220
|
+
const jobResultId = importData.jobResultId;
|
|
7221
|
+
const row = await db.from("job_results").where({ id: jobResultId }).first();
|
|
7222
|
+
if (!row) {
|
|
7223
|
+
throw new Error(
|
|
7224
|
+
`job_results row ${jobResultId} not found for import job ${bullmqJob.id}.`
|
|
7225
|
+
);
|
|
7226
|
+
}
|
|
7227
|
+
const priorMetadata = parseMetadata(row.metadata);
|
|
7228
|
+
const priorProcessed = Number(priorMetadata.processed ?? 0);
|
|
7229
|
+
if (row.state === JOB_STATUS_ENUM.active || priorProcessed > 0) {
|
|
7230
|
+
throw new Error(
|
|
7231
|
+
`IMPORT_RESTARTED_AFTER_STALL: import ${jobResultId} was already running; partial rows are kept, start a new import`
|
|
7232
|
+
);
|
|
7233
|
+
}
|
|
7234
|
+
await upsertJobStart(db, bullmqJob, row.label, "import");
|
|
7235
|
+
const context = contexts.find((c) => c.id === importData.context);
|
|
7236
|
+
if (!context) {
|
|
7237
|
+
throw new Error(`Context ${importData.context} not found in the registry.`);
|
|
7238
|
+
}
|
|
7239
|
+
const triggerMetadata = parseRunMetadata(row.trigger_metadata);
|
|
7240
|
+
if (!triggerMetadata.s3Key) {
|
|
7241
|
+
throw new Error(
|
|
7242
|
+
`No s3Key recorded on job_results row ${jobResultId} for import job.`
|
|
7243
|
+
);
|
|
7244
|
+
}
|
|
7245
|
+
if (!triggerMetadata.access) {
|
|
7246
|
+
throw new Error(
|
|
7247
|
+
`No batch access recorded on job_results row ${jobResultId} for import job.`
|
|
7248
|
+
);
|
|
7249
|
+
}
|
|
7250
|
+
const snap = triggerMetadata.user;
|
|
7251
|
+
const importUser = snap && typeof snap === "object" ? {
|
|
7252
|
+
id: Number(snap.id),
|
|
7253
|
+
super_admin: snap.super_admin === true,
|
|
7254
|
+
role: snap.role,
|
|
7255
|
+
team: snap.team
|
|
7256
|
+
} : { id: Number(snap ?? importData.user), role: importData.role };
|
|
7257
|
+
if (!importUser.id) {
|
|
7258
|
+
throw new Error(`No acting user recorded for import job ${bullmqJob.id}.`);
|
|
7259
|
+
}
|
|
7260
|
+
const bareS3Key = triggerMetadata.s3Key.slice(triggerMetadata.s3Key.indexOf("/") + 1);
|
|
7261
|
+
const stream = await getS3ObjectStream(bareS3Key, config);
|
|
7262
|
+
try {
|
|
7263
|
+
const deps = buildWorkerDeps({
|
|
7264
|
+
db,
|
|
7265
|
+
config,
|
|
7266
|
+
context,
|
|
7267
|
+
contextId: importData.context,
|
|
7268
|
+
jobResultId,
|
|
7269
|
+
stream,
|
|
7270
|
+
fields: importFieldsFor(context.fields),
|
|
7271
|
+
mapping: triggerMetadata.mapping,
|
|
7272
|
+
access: triggerMetadata.access,
|
|
7273
|
+
options: triggerMetadata.options ?? {},
|
|
7274
|
+
user: importUser,
|
|
7275
|
+
log: (m) => console.log(`[EXULU] import ${jobResultId}: ${m}`),
|
|
7276
|
+
// The row count StartImport seeded into metadata.total
|
|
7277
|
+
// (from the caller's `totalRows`); buildWorkerDeps treats a
|
|
7278
|
+
// 0/absent value as "unknown" so the progress patch does
|
|
7279
|
+
// not overwrite it with null on the first tick.
|
|
7280
|
+
total: priorMetadata.total
|
|
7281
|
+
});
|
|
7282
|
+
const result = await runImport(deps);
|
|
7283
|
+
if (result.cancelled) {
|
|
7284
|
+
await finalizeCancelled(db, row.id, result);
|
|
7285
|
+
}
|
|
7286
|
+
return { result, metadata: result };
|
|
7287
|
+
} catch (error) {
|
|
7288
|
+
if (error instanceof ImportAbort) {
|
|
7289
|
+
console.error(`[EXULU] import ${jobResultId} aborted: ${error.code}`);
|
|
7290
|
+
}
|
|
7291
|
+
throw error;
|
|
7292
|
+
} finally {
|
|
7293
|
+
stream.destroy();
|
|
7294
|
+
}
|
|
7295
|
+
}
|
|
6252
7296
|
if (data.type === "email_intake") {
|
|
6253
7297
|
console.log("[EXULU] running a routine webhook intake job.", bullmqJob.name);
|
|
6254
7298
|
if (!data.inputs?.s3Key || !data.inputs?.triggerId) {
|
|
@@ -6582,8 +7626,8 @@ var processUiMessagesFlow = async ({
|
|
|
6582
7626
|
let contextWindow;
|
|
6583
7627
|
try {
|
|
6584
7628
|
contextWindow = await resolveContextWindow({ modelId: resolved.model.id });
|
|
6585
|
-
} catch (
|
|
6586
|
-
console.warn(`[EXULU] Could not resolve the context window for routine model "${resolved.model.id}"; using the default.`,
|
|
7629
|
+
} catch (err2) {
|
|
7630
|
+
console.warn(`[EXULU] Could not resolve the context window for routine model "${resolved.model.id}"; using the default.`, err2);
|
|
6587
7631
|
}
|
|
6588
7632
|
const messagesWithoutPlaceholder = inputMessages.filter(
|
|
6589
7633
|
(message) => message.metadata?.type !== "placeholder"
|
|
@@ -6921,10 +7965,10 @@ async function fetch_with_retry(args) {
|
|
|
6921
7965
|
url,
|
|
6922
7966
|
timeout_ms ? { ...options, signal: AbortSignal.timeout(timeout_ms) } : options
|
|
6923
7967
|
);
|
|
6924
|
-
} catch (
|
|
6925
|
-
if (!retry_on_reject || attempt === max_attempts) throw
|
|
7968
|
+
} catch (err2) {
|
|
7969
|
+
if (!retry_on_reject || attempt === max_attempts) throw err2;
|
|
6926
7970
|
console.log(
|
|
6927
|
-
`[EXULU-RECALL] fetch error from ${url} (${
|
|
7971
|
+
`[EXULU-RECALL] fetch error from ${url} (${err2.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
|
|
6928
7972
|
);
|
|
6929
7973
|
await new Promise((resolve4) => setTimeout(resolve4, 5e3 + jitterMs()));
|
|
6930
7974
|
continue;
|
|
@@ -7257,13 +8301,13 @@ var recallService = {
|
|
|
7257
8301
|
});
|
|
7258
8302
|
const [updated] = await db(TABLE).where({ id: inserted.id }).update({ recall_bot_id: bot.id, updatedAt: /* @__PURE__ */ new Date() }).returning("*");
|
|
7259
8303
|
return this._row(updated);
|
|
7260
|
-
} catch (
|
|
8304
|
+
} catch (err2) {
|
|
7261
8305
|
const [failed] = await db(TABLE).where({ id: inserted.id }).update({
|
|
7262
8306
|
status: "failed",
|
|
7263
|
-
error:
|
|
8307
|
+
error: err2.message,
|
|
7264
8308
|
updatedAt: /* @__PURE__ */ new Date()
|
|
7265
8309
|
}).returning("*");
|
|
7266
|
-
log2(`createBot failed for job ${inserted.id}: ${
|
|
8310
|
+
log2(`createBot failed for job ${inserted.id}: ${err2.message}`);
|
|
7267
8311
|
return this._row(failed);
|
|
7268
8312
|
}
|
|
7269
8313
|
},
|
|
@@ -7334,8 +8378,8 @@ var recallService = {
|
|
|
7334
8378
|
row?.language || "auto"
|
|
7335
8379
|
);
|
|
7336
8380
|
await this._update(jobId, { recall_transcript_id: transcript.id ?? null });
|
|
7337
|
-
} catch (
|
|
7338
|
-
await this._fail(jobId, `create transcript failed: ${
|
|
8381
|
+
} catch (err2) {
|
|
8382
|
+
await this._fail(jobId, `create transcript failed: ${err2.message}`);
|
|
7339
8383
|
}
|
|
7340
8384
|
},
|
|
7341
8385
|
async _onTranscriptDone(jobId, transcriptId, recordingId) {
|
|
@@ -7371,12 +8415,12 @@ var recallService = {
|
|
|
7371
8415
|
jobId,
|
|
7372
8416
|
exuluApp.get().config
|
|
7373
8417
|
);
|
|
7374
|
-
} catch (
|
|
7375
|
-
log2(`could not store video locally for job ${jobId}: ${
|
|
8418
|
+
} catch (err2) {
|
|
8419
|
+
log2(`could not store video locally for job ${jobId}: ${err2.message}`);
|
|
7376
8420
|
}
|
|
7377
8421
|
}
|
|
7378
|
-
} catch (
|
|
7379
|
-
log2(`could not fetch recording duration for job ${jobId}: ${
|
|
8422
|
+
} catch (err2) {
|
|
8423
|
+
log2(`could not fetch recording duration for job ${jobId}: ${err2.message}`);
|
|
7380
8424
|
}
|
|
7381
8425
|
}
|
|
7382
8426
|
await this._update(jobId, {
|
|
@@ -7386,8 +8430,8 @@ var recallService = {
|
|
|
7386
8430
|
...videoS3Key ? { video_s3key: videoS3Key } : {},
|
|
7387
8431
|
status: "awaiting_review"
|
|
7388
8432
|
});
|
|
7389
|
-
} catch (
|
|
7390
|
-
await this._fail(jobId, `transcript download failed: ${
|
|
8433
|
+
} catch (err2) {
|
|
8434
|
+
await this._fail(jobId, `transcript download failed: ${err2.message}`);
|
|
7391
8435
|
return;
|
|
7392
8436
|
}
|
|
7393
8437
|
await this.runPostProcessing(jobId);
|
|
@@ -7419,9 +8463,9 @@ var recallService = {
|
|
|
7419
8463
|
if (!video) return null;
|
|
7420
8464
|
if (video.status?.code && video.status.code !== "done") return null;
|
|
7421
8465
|
return video.data?.download_url ?? null;
|
|
7422
|
-
} catch (
|
|
8466
|
+
} catch (err2) {
|
|
7423
8467
|
log2(
|
|
7424
|
-
`could not resolve video url for recording ${recordingId}: ${
|
|
8468
|
+
`could not resolve video url for recording ${recordingId}: ${err2.message}`
|
|
7425
8469
|
);
|
|
7426
8470
|
return null;
|
|
7427
8471
|
}
|
|
@@ -7558,15 +8602,15 @@ ${transcriptText}`,
|
|
|
7558
8602
|
error: null,
|
|
7559
8603
|
ran_at: ranAt
|
|
7560
8604
|
};
|
|
7561
|
-
} catch (
|
|
7562
|
-
log2(`post-processing prompt ${promptId} failed for job ${job.id}: ${
|
|
8605
|
+
} catch (err2) {
|
|
8606
|
+
log2(`post-processing prompt ${promptId} failed for job ${job.id}: ${err2.message}`);
|
|
7563
8607
|
return {
|
|
7564
8608
|
prompt_id: promptId,
|
|
7565
8609
|
agent_id: agentId,
|
|
7566
8610
|
prompt_name: promptName,
|
|
7567
8611
|
status: "failed",
|
|
7568
8612
|
output: null,
|
|
7569
|
-
error:
|
|
8613
|
+
error: err2.message,
|
|
7570
8614
|
ran_at: ranAt
|
|
7571
8615
|
};
|
|
7572
8616
|
}
|
|
@@ -7596,8 +8640,8 @@ ${transcriptText}`,
|
|
|
7596
8640
|
const job = this._row(dbRow);
|
|
7597
8641
|
try {
|
|
7598
8642
|
if (await this._reconcileStuckJob(job)) acted++;
|
|
7599
|
-
} catch (
|
|
7600
|
-
if (await this._reconcileError(job,
|
|
8643
|
+
} catch (err2) {
|
|
8644
|
+
if (await this._reconcileError(job, err2)) acted++;
|
|
7601
8645
|
}
|
|
7602
8646
|
}
|
|
7603
8647
|
for (const dbRow of redo) {
|
|
@@ -7605,9 +8649,9 @@ ${transcriptText}`,
|
|
|
7605
8649
|
log2(`reconcile: re-running lost post-processing for job ${dbRow.id}`);
|
|
7606
8650
|
const outputs = await this.runPostProcessing(dbRow.id);
|
|
7607
8651
|
if (outputs.length > 0) acted++;
|
|
7608
|
-
} catch (
|
|
8652
|
+
} catch (err2) {
|
|
7609
8653
|
log2(
|
|
7610
|
-
`post-processing redo failed for job ${dbRow.id}: ${
|
|
8654
|
+
`post-processing redo failed for job ${dbRow.id}: ${err2.message}`
|
|
7611
8655
|
);
|
|
7612
8656
|
}
|
|
7613
8657
|
}
|
|
@@ -7627,9 +8671,9 @@ ${transcriptText}`,
|
|
|
7627
8671
|
* Otherwise apply the 24h give-up (API errors must not defer it forever),
|
|
7628
8672
|
* and touch the row so it rotates to the back of the sweep window.
|
|
7629
8673
|
*/
|
|
7630
|
-
async _reconcileError(job,
|
|
7631
|
-
const message =
|
|
7632
|
-
if (
|
|
8674
|
+
async _reconcileError(job, err2) {
|
|
8675
|
+
const message = err2.message ?? String(err2);
|
|
8676
|
+
if (err2.status === 404) {
|
|
7633
8677
|
await this._fail(
|
|
7634
8678
|
job.id,
|
|
7635
8679
|
`Recall no longer knows this recording: ${message}`
|
|
@@ -7824,15 +8868,15 @@ var request2 = async (path2, init = {}) => {
|
|
|
7824
8868
|
let res;
|
|
7825
8869
|
try {
|
|
7826
8870
|
res = await fetch(url, init);
|
|
7827
|
-
} catch (
|
|
8871
|
+
} catch (err2) {
|
|
7828
8872
|
throw new TranscriptionServerUnavailable(
|
|
7829
|
-
`Unable to reach whisper server at ${url}: ${
|
|
8873
|
+
`Unable to reach whisper server at ${url}: ${err2.message}`
|
|
7830
8874
|
);
|
|
7831
8875
|
}
|
|
7832
8876
|
if (res.status === 404) {
|
|
7833
|
-
const
|
|
7834
|
-
|
|
7835
|
-
throw
|
|
8877
|
+
const err2 = new Error(`whisper server returned 404 for ${path2}`);
|
|
8878
|
+
err2.code = "JOB_NOT_FOUND";
|
|
8879
|
+
throw err2;
|
|
7836
8880
|
}
|
|
7837
8881
|
if (!res.ok) {
|
|
7838
8882
|
throw new Error(
|
|
@@ -7981,13 +9025,13 @@ var transcriptionService = {
|
|
|
7981
9025
|
updatedAt: /* @__PURE__ */ new Date()
|
|
7982
9026
|
}).returning("*");
|
|
7983
9027
|
return this._rowFromDb(updated);
|
|
7984
|
-
} catch (
|
|
9028
|
+
} catch (err2) {
|
|
7985
9029
|
const [failed] = await db(TABLE2).where({ id: row.id }).update({
|
|
7986
9030
|
status: "failed",
|
|
7987
|
-
error:
|
|
9031
|
+
error: err2.message,
|
|
7988
9032
|
updatedAt: /* @__PURE__ */ new Date()
|
|
7989
9033
|
}).returning("*");
|
|
7990
|
-
log3(`Failed to dispatch job ${row.id}: ${
|
|
9034
|
+
log3(`Failed to dispatch job ${row.id}: ${err2.message}`);
|
|
7991
9035
|
return this._rowFromDb(failed);
|
|
7992
9036
|
}
|
|
7993
9037
|
},
|
|
@@ -8006,18 +9050,18 @@ var transcriptionService = {
|
|
|
8006
9050
|
try {
|
|
8007
9051
|
const job = await transcriptionClient.getJob(row.whisper_job_id);
|
|
8008
9052
|
await this._applyJobUpdate(row, job);
|
|
8009
|
-
} catch (
|
|
8010
|
-
const code =
|
|
9053
|
+
} catch (err2) {
|
|
9054
|
+
const code = err2.code;
|
|
8011
9055
|
if (code === "JOB_NOT_FOUND") {
|
|
8012
9056
|
await db(TABLE2).where({ id: row.id }).update({
|
|
8013
9057
|
status: "failed",
|
|
8014
9058
|
error: "lost on server restart",
|
|
8015
9059
|
updatedAt: /* @__PURE__ */ new Date()
|
|
8016
9060
|
});
|
|
8017
|
-
} else if (
|
|
9061
|
+
} else if (err2 instanceof TranscriptionServerUnavailable) {
|
|
8018
9062
|
log3(`Whisper server unreachable while polling ${row.id}; will retry`);
|
|
8019
9063
|
} else {
|
|
8020
|
-
log3(`Error polling job ${row.id}: ${
|
|
9064
|
+
log3(`Error polling job ${row.id}: ${err2.message}`);
|
|
8021
9065
|
}
|
|
8022
9066
|
}
|
|
8023
9067
|
}
|
|
@@ -8044,8 +9088,8 @@ var transcriptionService = {
|
|
|
8044
9088
|
row.post_processing_prompts,
|
|
8045
9089
|
row.post_processing_outputs
|
|
8046
9090
|
)) {
|
|
8047
|
-
void recallService.runPostProcessing(row.id).catch((
|
|
8048
|
-
log3(`post-processing for upload ${row.id} failed: ${
|
|
9091
|
+
void recallService.runPostProcessing(row.id).catch((err2) => {
|
|
9092
|
+
log3(`post-processing for upload ${row.id} failed: ${err2.message}`);
|
|
8049
9093
|
});
|
|
8050
9094
|
}
|
|
8051
9095
|
return;
|
|
@@ -8073,10 +9117,10 @@ var transcriptionService = {
|
|
|
8073
9117
|
if (row.whisper_job_id && transcriptionClient.isConfigured()) {
|
|
8074
9118
|
try {
|
|
8075
9119
|
await transcriptionClient.cancelJob(row.whisper_job_id);
|
|
8076
|
-
} catch (
|
|
8077
|
-
const code =
|
|
9120
|
+
} catch (err2) {
|
|
9121
|
+
const code = err2.code;
|
|
8078
9122
|
if (code !== "JOB_NOT_FOUND") {
|
|
8079
|
-
log3(`Best-effort cancel of whisper job failed: ${
|
|
9123
|
+
log3(`Best-effort cancel of whisper job failed: ${err2.message}`);
|
|
8080
9124
|
}
|
|
8081
9125
|
}
|
|
8082
9126
|
}
|
|
@@ -8186,13 +9230,13 @@ var transcriptionService = {
|
|
|
8186
9230
|
// upsert when re-saving
|
|
8187
9231
|
);
|
|
8188
9232
|
item = result.item;
|
|
8189
|
-
} catch (
|
|
9233
|
+
} catch (err2) {
|
|
8190
9234
|
await db(TABLE2).where({ id }).update({
|
|
8191
9235
|
speakers: JSON.stringify(input.speakers),
|
|
8192
|
-
error: `Failed to save: ${
|
|
9236
|
+
error: `Failed to save: ${err2.message}`,
|
|
8193
9237
|
updatedAt: /* @__PURE__ */ new Date()
|
|
8194
9238
|
});
|
|
8195
|
-
throw
|
|
9239
|
+
throw err2;
|
|
8196
9240
|
}
|
|
8197
9241
|
const itemId = item.id ?? row.saved_item_id ?? "";
|
|
8198
9242
|
const users = input.target_rbac_users ?? row.target_rbac_users ?? [];
|
|
@@ -8206,8 +9250,8 @@ var transcriptionService = {
|
|
|
8206
9250
|
{ users, roles },
|
|
8207
9251
|
[]
|
|
8208
9252
|
);
|
|
8209
|
-
} catch (
|
|
8210
|
-
log3(`RBAC update failed for item ${itemId}: ${
|
|
9253
|
+
} catch (err2) {
|
|
9254
|
+
log3(`RBAC update failed for item ${itemId}: ${err2.message}`);
|
|
8211
9255
|
}
|
|
8212
9256
|
}
|
|
8213
9257
|
const projectId = input.project_id ?? row.project_id ?? null;
|
|
@@ -8228,8 +9272,8 @@ var transcriptionService = {
|
|
|
8228
9272
|
});
|
|
8229
9273
|
}
|
|
8230
9274
|
}
|
|
8231
|
-
} catch (
|
|
8232
|
-
projectWarning =
|
|
9275
|
+
} catch (err2) {
|
|
9276
|
+
projectWarning = err2.message;
|
|
8233
9277
|
}
|
|
8234
9278
|
}
|
|
8235
9279
|
const nextCorrectedSegments = input.corrected_segments !== void 0 ? input.corrected_segments : row.corrected_segments;
|
|
@@ -8270,9 +9314,9 @@ var transcriptionService = {
|
|
|
8270
9314
|
const { db } = await postgresClient();
|
|
8271
9315
|
try {
|
|
8272
9316
|
await assertOwnsTranscriptionJob(db, user, jobId);
|
|
8273
|
-
} catch (
|
|
8274
|
-
if (
|
|
8275
|
-
throw
|
|
9317
|
+
} catch (err2) {
|
|
9318
|
+
if (err2 instanceof TranscriptionJobAccessError) return void 0;
|
|
9319
|
+
throw err2;
|
|
8276
9320
|
}
|
|
8277
9321
|
const dbRow = await db(TABLE2).where({ id: jobId }).first();
|
|
8278
9322
|
if (!dbRow) return void 0;
|
|
@@ -8403,8 +9447,8 @@ var liveRecordingService = {
|
|
|
8403
9447
|
);
|
|
8404
9448
|
}
|
|
8405
9449
|
log4(`live recording ${id} stopped \u2192 awaiting_review`);
|
|
8406
|
-
void recallService.runPostProcessing(id).catch((
|
|
8407
|
-
log4(`post-processing for job ${id} failed: ${
|
|
9450
|
+
void recallService.runPostProcessing(id).catch((err2) => {
|
|
9451
|
+
log4(`post-processing for job ${id} failed: ${err2.message}`);
|
|
8408
9452
|
});
|
|
8409
9453
|
return rowFromDb(updated);
|
|
8410
9454
|
}
|
|
@@ -8534,16 +9578,16 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
|
|
|
8534
9578
|
for (let attempt = 0; attempt < 5; attempt++) {
|
|
8535
9579
|
try {
|
|
8536
9580
|
return await insertFn({ ...baseRow, secret: generateTriggerSecret() });
|
|
8537
|
-
} catch (
|
|
8538
|
-
if (
|
|
8539
|
-
throw
|
|
9581
|
+
} catch (err2) {
|
|
9582
|
+
if (err2?.code === "23505") continue;
|
|
9583
|
+
throw err2;
|
|
8540
9584
|
}
|
|
8541
9585
|
}
|
|
8542
9586
|
throw new Error("Could not generate a unique trigger secret.");
|
|
8543
9587
|
}
|
|
8544
9588
|
|
|
8545
9589
|
// src/exulu/email-inbound/webhook.ts
|
|
8546
|
-
import { randomUUID as
|
|
9590
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
8547
9591
|
|
|
8548
9592
|
// src/exulu/email-inbound/verify-signature.ts
|
|
8549
9593
|
import { createHmac, timingSafeEqual } from "crypto";
|
|
@@ -8572,10 +9616,10 @@ async function isReplay(redis, signature, timestamp) {
|
|
|
8572
9616
|
EX: REPLAY_TTL_SECONDS
|
|
8573
9617
|
});
|
|
8574
9618
|
return result === null;
|
|
8575
|
-
} catch (
|
|
9619
|
+
} catch (err2) {
|
|
8576
9620
|
console.error(
|
|
8577
9621
|
"[EXULU] routine-webhook replay guard: redis unavailable, degrading to window-only",
|
|
8578
|
-
|
|
9622
|
+
err2 instanceof Error ? err2.message : String(err2)
|
|
8579
9623
|
);
|
|
8580
9624
|
return false;
|
|
8581
9625
|
}
|
|
@@ -8648,8 +9692,8 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
|
|
|
8648
9692
|
payloadBytes = rawBody;
|
|
8649
9693
|
format = "eml";
|
|
8650
9694
|
}
|
|
8651
|
-
} catch (
|
|
8652
|
-
res.status(400).json({ detail:
|
|
9695
|
+
} catch (err2) {
|
|
9696
|
+
res.status(400).json({ detail: err2 instanceof Error ? err2.message : "bad payload" });
|
|
8653
9697
|
return;
|
|
8654
9698
|
}
|
|
8655
9699
|
void deps.stampLastFiredAt(db, trigger.id).catch(
|
|
@@ -8657,7 +9701,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
|
|
|
8657
9701
|
);
|
|
8658
9702
|
try {
|
|
8659
9703
|
const ext = format === "json" ? "json" : "eml";
|
|
8660
|
-
const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${
|
|
9704
|
+
const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${randomUUID5()}.${ext}`, payloadBytes);
|
|
8661
9705
|
await deps.enqueueIntake({ s3Key, triggerId: trigger.id, format });
|
|
8662
9706
|
} catch (error) {
|
|
8663
9707
|
console.error("[EXULU-WEBHOOK] persist/enqueue failed", error);
|
|
@@ -8668,7 +9712,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
|
|
|
8668
9712
|
};
|
|
8669
9713
|
|
|
8670
9714
|
// src/graphql/schemas/index.ts
|
|
8671
|
-
import { randomUUID as
|
|
9715
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
8672
9716
|
|
|
8673
9717
|
// src/graphql/resolvers/memory-base-stats.ts
|
|
8674
9718
|
var num = (v) => typeof v === "number" ? v : Number(v) || 0;
|
|
@@ -10162,6 +11206,8 @@ function createSDL(tables, contexts, tools, config, evals) {
|
|
|
10162
11206
|
mutationDefs += `
|
|
10163
11207
|
${tableNameSingular}GenerateChunks(where: [Filter${tableNameSingularUpperCaseFirst}], limit: Int): ${tableNameSingular}GenerateChunksReturnPayload
|
|
10164
11208
|
${tableNameSingular}ExecuteSource(source: ID!, inputs: JSON!): ${tableNameSingular}ExecuteSourceReturnPayload
|
|
11209
|
+
${tableNameSingular}StartImport(input: StartImportInput!): StartImportPayload
|
|
11210
|
+
${tableNameSingular}CancelImport(jobResultId: ID!): CancelImportPayload
|
|
10165
11211
|
${tableNameSingular}DeleteChunks(where: [Filter${tableNameSingularUpperCaseFirst}], limit: Int): ${tableNameSingular}DeleteChunksReturnPayload
|
|
10166
11212
|
${tableNameSingular}BackfillEntities(onlyStale: Boolean, limit: Int): ${tableNameSingular}EntityBackfillPayload
|
|
10167
11213
|
${tableNameSingular}PurgeEntityType(type: String!): ${tableNameSingular}EntityPurgePayload
|
|
@@ -10200,6 +11246,40 @@ function createSDL(tables, contexts, tools, config, evals) {
|
|
|
10200
11246
|
items: [String!]
|
|
10201
11247
|
}
|
|
10202
11248
|
|
|
11249
|
+
input StartImportMappingInput {
|
|
11250
|
+
header: String!
|
|
11251
|
+
fieldName: String
|
|
11252
|
+
}
|
|
11253
|
+
|
|
11254
|
+
input StartImportAccessInput {
|
|
11255
|
+
rights_mode: String!
|
|
11256
|
+
users: JSON
|
|
11257
|
+
roles: JSON
|
|
11258
|
+
teams: JSON
|
|
11259
|
+
}
|
|
11260
|
+
|
|
11261
|
+
input StartImportOptionsInput {
|
|
11262
|
+
skipEmbeddings: Boolean
|
|
11263
|
+
delimiter: String
|
|
11264
|
+
}
|
|
11265
|
+
|
|
11266
|
+
input StartImportInput {
|
|
11267
|
+
s3Key: String!
|
|
11268
|
+
fileName: String!
|
|
11269
|
+
mapping: [StartImportMappingInput!]
|
|
11270
|
+
access: StartImportAccessInput!
|
|
11271
|
+
options: StartImportOptionsInput
|
|
11272
|
+
totalRows: Int
|
|
11273
|
+
}
|
|
11274
|
+
|
|
11275
|
+
type StartImportPayload {
|
|
11276
|
+
jobResultId: ID!
|
|
11277
|
+
}
|
|
11278
|
+
|
|
11279
|
+
type CancelImportPayload {
|
|
11280
|
+
ok: Boolean!
|
|
11281
|
+
}
|
|
11282
|
+
|
|
10203
11283
|
type ${tableNameSingular}ProcessItemFieldReturnPayload {
|
|
10204
11284
|
message: String!
|
|
10205
11285
|
results: [String]
|
|
@@ -10734,8 +11814,8 @@ type EmbeddingModelOption {
|
|
|
10734
11814
|
maxChunkSize: m.maxChunkSize,
|
|
10735
11815
|
maxBatchSize: m.maxBatchSize
|
|
10736
11816
|
}));
|
|
10737
|
-
} catch (
|
|
10738
|
-
console.warn("[EXULU] Could not read embedding models:",
|
|
11817
|
+
} catch (err2) {
|
|
11818
|
+
console.warn("[EXULU] Could not read embedding models:", err2.message);
|
|
10739
11819
|
return [];
|
|
10740
11820
|
}
|
|
10741
11821
|
};
|
|
@@ -10928,9 +12008,9 @@ type EmbeddingModelOption {
|
|
|
10928
12008
|
throw new Error("You don't have access to this workflow template.");
|
|
10929
12009
|
}
|
|
10930
12010
|
const hasWorkflowsWriteRole = user?.super_admin || user?.role?.workflows === "write";
|
|
10931
|
-
const
|
|
12011
|
+
const canWrite2 = hasWorkflowsWriteRole && await checkRecordAccess(workflowTemplate, "write", user);
|
|
10932
12012
|
const rows = await db.from("workflow_triggers").where({ workflow: args.workflow }).orderBy("createdAt", "asc");
|
|
10933
|
-
return rows.map((r) => toWorkflowTriggerPayload(r, { canWrite }));
|
|
12013
|
+
return rows.map((r) => toWorkflowTriggerPayload(r, { canWrite: canWrite2 }));
|
|
10934
12014
|
};
|
|
10935
12015
|
resolvers.Mutation["upsertWorkflowEmailTrigger"] = async (_, args, context) => {
|
|
10936
12016
|
if (!args.workflow) {
|
|
@@ -11011,9 +12091,9 @@ type EmbeddingModelOption {
|
|
|
11011
12091
|
const rows = await db.from("workflow_triggers").where({ id: args.id }).update({ secret: generateTriggerSecret(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).returning("*");
|
|
11012
12092
|
updated = rows[0];
|
|
11013
12093
|
break;
|
|
11014
|
-
} catch (
|
|
11015
|
-
if (
|
|
11016
|
-
throw
|
|
12094
|
+
} catch (err2) {
|
|
12095
|
+
if (err2?.code === "23505") continue;
|
|
12096
|
+
throw err2;
|
|
11017
12097
|
}
|
|
11018
12098
|
}
|
|
11019
12099
|
if (!updated) throw new Error("Could not generate a unique trigger secret.");
|
|
@@ -11059,13 +12139,13 @@ type EmbeddingModelOption {
|
|
|
11059
12139
|
bytes = Buffer.from(args.payload, "latin1");
|
|
11060
12140
|
format = "eml";
|
|
11061
12141
|
}
|
|
11062
|
-
} catch (
|
|
11063
|
-
return { outcome: "error", error:
|
|
12142
|
+
} catch (err2) {
|
|
12143
|
+
return { outcome: "error", error: err2 instanceof Error ? err2.message : "bad payload" };
|
|
11064
12144
|
}
|
|
11065
12145
|
const ext = format === "json" ? "json" : "eml";
|
|
11066
12146
|
const fullKey = await uploadFile(
|
|
11067
12147
|
bytes,
|
|
11068
|
-
`${EMAIL_INBOUND_S3_PREFIX}${
|
|
12148
|
+
`${EMAIL_INBOUND_S3_PREFIX}${randomUUID6()}.${ext}`,
|
|
11069
12149
|
config,
|
|
11070
12150
|
{ contentType: "application/octet-stream" },
|
|
11071
12151
|
void 0,
|
|
@@ -11250,11 +12330,11 @@ type EmbeddingModelOption {
|
|
|
11250
12330
|
user
|
|
11251
12331
|
);
|
|
11252
12332
|
return new Map(rows.map((row) => [row.id, row]));
|
|
11253
|
-
} catch (
|
|
11254
|
-
if (
|
|
12333
|
+
} catch (err2) {
|
|
12334
|
+
if (err2 instanceof Error && err2.message.startsWith("Access control error")) {
|
|
11255
12335
|
return /* @__PURE__ */ new Map();
|
|
11256
12336
|
}
|
|
11257
|
-
throw
|
|
12337
|
+
throw err2;
|
|
11258
12338
|
}
|
|
11259
12339
|
};
|
|
11260
12340
|
const loadRoutineRunForWrite = async (db, user, id) => {
|
|
@@ -11768,8 +12848,8 @@ type EmbeddingModelOption {
|
|
|
11768
12848
|
stuck_count: num7(stuckRow?.c),
|
|
11769
12849
|
stale_count: num7(staleRow?.c)
|
|
11770
12850
|
};
|
|
11771
|
-
} catch (
|
|
11772
|
-
console.error("[EXULU] computeContextAggregates failed for", contextId,
|
|
12851
|
+
} catch (err2) {
|
|
12852
|
+
console.error("[EXULU] computeContextAggregates failed for", contextId, err2);
|
|
11773
12853
|
return empty;
|
|
11774
12854
|
}
|
|
11775
12855
|
};
|
|
@@ -12309,9 +13389,9 @@ async function extractZipToPrefix(bytes, prefix, config) {
|
|
|
12309
13389
|
let zip;
|
|
12310
13390
|
try {
|
|
12311
13391
|
zip = await JSZip.loadAsync(bytes);
|
|
12312
|
-
} catch (
|
|
13392
|
+
} catch (err2) {
|
|
12313
13393
|
throw new BundleValidationError(
|
|
12314
|
-
`Could not parse zip file: ${
|
|
13394
|
+
`Could not parse zip file: ${err2?.message ?? "unknown error"}`
|
|
12315
13395
|
);
|
|
12316
13396
|
}
|
|
12317
13397
|
const entries = [];
|
|
@@ -12412,13 +13492,13 @@ import bodyParser from "body-parser";
|
|
|
12412
13492
|
import "crypto-js";
|
|
12413
13493
|
import "openai";
|
|
12414
13494
|
import fs2 from "fs";
|
|
12415
|
-
import { randomUUID as
|
|
13495
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
12416
13496
|
import "@opentelemetry/api";
|
|
12417
13497
|
import JSZip3 from "jszip";
|
|
12418
13498
|
|
|
12419
13499
|
// src/skills/bundled.ts
|
|
12420
13500
|
import JSZip2 from "jszip";
|
|
12421
|
-
import { createHash as createHash2, randomUUID as
|
|
13501
|
+
import { createHash as createHash2, randomUUID as randomUUID7 } from "crypto";
|
|
12422
13502
|
|
|
12423
13503
|
// src/skills/bundled.generated.ts
|
|
12424
13504
|
var BUNDLED_SKILLS = [
|
|
@@ -12501,7 +13581,7 @@ async function seedBundledSkills({
|
|
|
12501
13581
|
log6(`"${skill.name}" updated to v${nextVersion}`);
|
|
12502
13582
|
continue;
|
|
12503
13583
|
}
|
|
12504
|
-
const skillId =
|
|
13584
|
+
const skillId = randomUUID7();
|
|
12505
13585
|
await extractBundleToVersion({ bytes: await bundledSkillZip(skill), skillId, version: 1, config });
|
|
12506
13586
|
await db("skills").insert({
|
|
12507
13587
|
id: skillId,
|
|
@@ -12599,7 +13679,7 @@ ${SUGGESTIONS_SYSTEM_PROMPT}` : SUGGESTIONS_SYSTEM_PROMPT;
|
|
|
12599
13679
|
};
|
|
12600
13680
|
|
|
12601
13681
|
// src/exulu/compact-session.ts
|
|
12602
|
-
import { randomUUID as
|
|
13682
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
12603
13683
|
import { generateText as generateText6, validateUIMessages as validateUIMessages2 } from "ai";
|
|
12604
13684
|
var CompactionInsufficientError = class extends Error {
|
|
12605
13685
|
constructor(reason) {
|
|
@@ -12702,7 +13782,7 @@ Focus especially on: ${steer.trim()}` : SUMMARY_SYSTEM;
|
|
|
12702
13782
|
...steer?.trim() ? { steer: steer.trim() } : {}
|
|
12703
13783
|
};
|
|
12704
13784
|
const checkpoint = {
|
|
12705
|
-
id: `compaction_${
|
|
13785
|
+
id: `compaction_${randomUUID8()}`,
|
|
12706
13786
|
role: "user",
|
|
12707
13787
|
parts: [{ type: "text", text: `[Conversation summary \u2014 earlier messages were compacted]
|
|
12708
13788
|
|
|
@@ -12715,19 +13795,19 @@ ${summary}` }],
|
|
|
12715
13795
|
|
|
12716
13796
|
// src/exulu/request-error.ts
|
|
12717
13797
|
import { TypeValidationError } from "ai";
|
|
12718
|
-
function describeRequestError(
|
|
12719
|
-
if (
|
|
12720
|
-
return { status: 413, body:
|
|
13798
|
+
function describeRequestError(err2) {
|
|
13799
|
+
if (err2 instanceof ContextCompactionRequiredError) {
|
|
13800
|
+
return { status: 413, body: err2.message };
|
|
12721
13801
|
}
|
|
12722
|
-
if (TypeValidationError.isInstance(
|
|
12723
|
-
const cause =
|
|
13802
|
+
if (TypeValidationError.isInstance(err2)) {
|
|
13803
|
+
const cause = err2.cause;
|
|
12724
13804
|
const detail = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
|
|
12725
13805
|
return {
|
|
12726
13806
|
status: 422,
|
|
12727
13807
|
body: `The stored conversation could not be loaded: ${detail.slice(0, 400) || "type validation failed"}`
|
|
12728
13808
|
};
|
|
12729
13809
|
}
|
|
12730
|
-
return { status: 500, body:
|
|
13810
|
+
return { status: 500, body: err2 instanceof Error ? err2.message : String(err2) };
|
|
12731
13811
|
}
|
|
12732
13812
|
|
|
12733
13813
|
// src/exulu/memory/recalled-metadata.ts
|
|
@@ -13165,12 +14245,12 @@ function registerLiveRecordingChunkRoute(app, deps) {
|
|
|
13165
14245
|
const db = await deps.getDb();
|
|
13166
14246
|
try {
|
|
13167
14247
|
await deps.assertOwns(db, user, jobId);
|
|
13168
|
-
} catch (
|
|
13169
|
-
if (
|
|
13170
|
-
res.status(
|
|
14248
|
+
} catch (err2) {
|
|
14249
|
+
if (err2 instanceof TranscriptionJobAccessError) {
|
|
14250
|
+
res.status(err2.code).json({ detail: err2.message });
|
|
13171
14251
|
return;
|
|
13172
14252
|
}
|
|
13173
|
-
throw
|
|
14253
|
+
throw err2;
|
|
13174
14254
|
}
|
|
13175
14255
|
const row = await db.from("transcription_jobs").select(["status", "raw_segments", "project_id"]).where({ id: jobId }).first();
|
|
13176
14256
|
if (!row) {
|
|
@@ -13225,14 +14305,14 @@ function registerLiveRecordingChunkRoute(app, deps) {
|
|
|
13225
14305
|
priorText: LIVE_PRIOR_TEXT_ENABLED ? priorTextFrom(row.raw_segments) : void 0,
|
|
13226
14306
|
tags
|
|
13227
14307
|
}));
|
|
13228
|
-
} catch (
|
|
13229
|
-
if (
|
|
13230
|
-
const code =
|
|
13231
|
-
res.status(code).json({ detail:
|
|
14308
|
+
} catch (err2) {
|
|
14309
|
+
if (err2 instanceof TranscriptionError) {
|
|
14310
|
+
const code = err2.upstreamStatus >= 500 ? 502 : err2.upstreamStatus;
|
|
14311
|
+
res.status(code).json({ detail: err2.message });
|
|
13232
14312
|
return;
|
|
13233
14313
|
}
|
|
13234
|
-
console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`,
|
|
13235
|
-
res.status(500).json({ detail:
|
|
14314
|
+
console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`, err2);
|
|
14315
|
+
res.status(500).json({ detail: err2 instanceof Error ? err2.message : "Transcription failed." });
|
|
13236
14316
|
return;
|
|
13237
14317
|
}
|
|
13238
14318
|
}
|
|
@@ -13322,7 +14402,7 @@ var formatSrtTime = (seconds) => {
|
|
|
13322
14402
|
const ms = String(totalMs % 1e3).padStart(3, "0");
|
|
13323
14403
|
return `${formatCsvTime(wholeSeconds)},${ms}`;
|
|
13324
14404
|
};
|
|
13325
|
-
var
|
|
14405
|
+
var csvField2 = (value, isTextField = false) => {
|
|
13326
14406
|
const needsQuote = /["\n\r,]/.test(value) || isTextField;
|
|
13327
14407
|
return needsQuote ? `"${value.replace(/"/g, '""')}"` : value;
|
|
13328
14408
|
};
|
|
@@ -13336,7 +14416,7 @@ function buildTranscriptCsv(item, options) {
|
|
|
13336
14416
|
const label = resolveLabel(item, segment.speaker, options.speakers);
|
|
13337
14417
|
const text = (segment.text ?? "").trim();
|
|
13338
14418
|
const cells = options.timestamps ? [formatCsvTime(segment.start), formatCsvTime(segment.end), label, text] : [label, text];
|
|
13339
|
-
return cells.map((value, i) =>
|
|
14419
|
+
return cells.map((value, i) => csvField2(value, i === cells.length - 1)).join(",");
|
|
13340
14420
|
});
|
|
13341
14421
|
return [header2, ...rows].join("\n") + "\n";
|
|
13342
14422
|
}
|
|
@@ -13396,8 +14476,8 @@ function registerTranscriptExportRoute(app, deps) {
|
|
|
13396
14476
|
`attachment; filename="${encodeURIComponent(filename)}"`
|
|
13397
14477
|
);
|
|
13398
14478
|
res.send(body);
|
|
13399
|
-
} catch (
|
|
13400
|
-
console.error("[EXULU] transcript export failed",
|
|
14479
|
+
} catch (err2) {
|
|
14480
|
+
console.error("[EXULU] transcript export failed", err2);
|
|
13401
14481
|
res.status(500).json({ detail: "Export failed." });
|
|
13402
14482
|
}
|
|
13403
14483
|
});
|
|
@@ -13447,8 +14527,8 @@ function registerTranscriptExportRoute(app, deps) {
|
|
|
13447
14527
|
`attachment; filename="${encodeURIComponent(filename)}"`
|
|
13448
14528
|
);
|
|
13449
14529
|
res.send(body);
|
|
13450
|
-
} catch (
|
|
13451
|
-
console.error("[EXULU] transcript job export failed",
|
|
14530
|
+
} catch (err2) {
|
|
14531
|
+
console.error("[EXULU] transcript job export failed", err2);
|
|
13452
14532
|
res.status(500).json({ detail: "Export failed." });
|
|
13453
14533
|
}
|
|
13454
14534
|
});
|
|
@@ -13515,7 +14595,7 @@ function pipelineConfigFor(agent) {
|
|
|
13515
14595
|
// ee/claim-check/routes.ts
|
|
13516
14596
|
var CLAIM_CHECK_PATH = "/claims/check";
|
|
13517
14597
|
var CLAIM_CHECK_SESSION_PATH = "/claims/check/:session";
|
|
13518
|
-
var
|
|
14598
|
+
var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13519
14599
|
function hasNumericUserId(user) {
|
|
13520
14600
|
return Boolean(user?.id) && Number.isFinite(Number(user?.id));
|
|
13521
14601
|
}
|
|
@@ -13676,9 +14756,9 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13676
14756
|
}
|
|
13677
14757
|
try {
|
|
13678
14758
|
agent = await deps.getAgent(body.agent);
|
|
13679
|
-
} catch (
|
|
14759
|
+
} catch (err2) {
|
|
13680
14760
|
console.warn(
|
|
13681
|
-
`[EXULU] claim check: agent lookup for "${body.agent}" failed: ${
|
|
14761
|
+
`[EXULU] claim check: agent lookup for "${body.agent}" failed: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
13682
14762
|
);
|
|
13683
14763
|
}
|
|
13684
14764
|
if (!agent) {
|
|
@@ -13703,7 +14783,7 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13703
14783
|
});
|
|
13704
14784
|
return;
|
|
13705
14785
|
}
|
|
13706
|
-
if (deps.findClaimCheck && body.session && body.messageId &&
|
|
14786
|
+
if (deps.findClaimCheck && body.session && body.messageId && UUID_RE2.test(body.session)) {
|
|
13707
14787
|
try {
|
|
13708
14788
|
const stored = await deps.findClaimCheck({
|
|
13709
14789
|
session: body.session,
|
|
@@ -13714,10 +14794,10 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13714
14794
|
res.status(200).json(stored);
|
|
13715
14795
|
return;
|
|
13716
14796
|
}
|
|
13717
|
-
} catch (
|
|
14797
|
+
} catch (err2) {
|
|
13718
14798
|
console.warn(
|
|
13719
14799
|
"[EXULU claim-check] could not read the stored check for this message; running the check.",
|
|
13720
|
-
|
|
14800
|
+
err2
|
|
13721
14801
|
);
|
|
13722
14802
|
}
|
|
13723
14803
|
}
|
|
@@ -13743,10 +14823,10 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13743
14823
|
model = resolved.languageModel;
|
|
13744
14824
|
break;
|
|
13745
14825
|
}
|
|
13746
|
-
} catch (
|
|
13747
|
-
lastError =
|
|
14826
|
+
} catch (err2) {
|
|
14827
|
+
lastError = err2;
|
|
13748
14828
|
console.warn(
|
|
13749
|
-
`[EXULU] claim check: model "${modelId}" failed to resolve: ${
|
|
14829
|
+
`[EXULU] claim check: model "${modelId}" failed to resolve: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
13750
14830
|
);
|
|
13751
14831
|
}
|
|
13752
14832
|
}
|
|
@@ -13810,21 +14890,21 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13810
14890
|
]);
|
|
13811
14891
|
completedResult = result;
|
|
13812
14892
|
res.status(200).json(result);
|
|
13813
|
-
} catch (
|
|
13814
|
-
if (
|
|
14893
|
+
} catch (err2) {
|
|
14894
|
+
if (err2 instanceof ClaimCheckTimeoutError) {
|
|
13815
14895
|
console.warn(`[EXULU] claim check exceeded the ${timeoutMs} ms deadline.`);
|
|
13816
14896
|
res.status(504).json({
|
|
13817
14897
|
detail: `The claim check did not finish within ${timeoutMs / 1e3} seconds and was cancelled.`
|
|
13818
14898
|
});
|
|
13819
14899
|
} else {
|
|
13820
|
-
console.error("[EXULU] claim check failed.",
|
|
14900
|
+
console.error("[EXULU] claim check failed.", err2);
|
|
13821
14901
|
res.status(500).json({ detail: "The claim check failed." });
|
|
13822
14902
|
}
|
|
13823
14903
|
} finally {
|
|
13824
14904
|
if (deadline) clearTimeout(deadline);
|
|
13825
14905
|
deps.limiter.release();
|
|
13826
14906
|
}
|
|
13827
|
-
if (completedResult && body.session && body.messageId &&
|
|
14907
|
+
if (completedResult && body.session && body.messageId && UUID_RE2.test(body.session)) {
|
|
13828
14908
|
if (!deps.saveClaimCheck) {
|
|
13829
14909
|
console.error(
|
|
13830
14910
|
"[EXULU claim-check] saveClaimCheck is not wired; this check cannot survive a reload."
|
|
@@ -13837,8 +14917,8 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13837
14917
|
userId: Number(user.id),
|
|
13838
14918
|
result: completedResult
|
|
13839
14919
|
});
|
|
13840
|
-
} catch (
|
|
13841
|
-
console.warn("[EXULU claim-check] could not store the check for this message.",
|
|
14920
|
+
} catch (err2) {
|
|
14921
|
+
console.warn("[EXULU claim-check] could not store the check for this message.", err2);
|
|
13842
14922
|
}
|
|
13843
14923
|
}
|
|
13844
14924
|
}
|
|
@@ -13849,7 +14929,7 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13849
14929
|
return;
|
|
13850
14930
|
}
|
|
13851
14931
|
const session = req.params.session ?? "";
|
|
13852
|
-
if (!
|
|
14932
|
+
if (!UUID_RE2.test(session)) {
|
|
13853
14933
|
res.status(400).json({ detail: "session must be a uuid." });
|
|
13854
14934
|
return;
|
|
13855
14935
|
}
|
|
@@ -13866,8 +14946,8 @@ function registerClaimCheckRoutes(app, deps) {
|
|
|
13866
14946
|
try {
|
|
13867
14947
|
const checks = await deps.listClaimChecks({ session, userId: Number(auth.user.id) });
|
|
13868
14948
|
res.status(200).json({ checks });
|
|
13869
|
-
} catch (
|
|
13870
|
-
console.error("[EXULU claim-check] could not read stored checks.",
|
|
14949
|
+
} catch (err2) {
|
|
14950
|
+
console.error("[EXULU claim-check] could not read stored checks.", err2);
|
|
13871
14951
|
res.status(500).json({ detail: "Could not read stored checks." });
|
|
13872
14952
|
}
|
|
13873
14953
|
});
|
|
@@ -15176,9 +16256,9 @@ async function runClaimCheck(args) {
|
|
|
15176
16256
|
limits: { truncated: skipped.length > 0 || truncation.sources > 0, sentencesSkipped: skipped.length },
|
|
15177
16257
|
notes: state.notes
|
|
15178
16258
|
};
|
|
15179
|
-
} catch (
|
|
16259
|
+
} catch (err2) {
|
|
15180
16260
|
timings.totalMs = Date.now() - startedAt;
|
|
15181
|
-
const message =
|
|
16261
|
+
const message = err2 instanceof Error ? err2.message : String(err2);
|
|
15182
16262
|
return {
|
|
15183
16263
|
status: "partial",
|
|
15184
16264
|
score: scoreClaims([], options.thresholds),
|
|
@@ -15237,8 +16317,8 @@ function makeSecondChance(args) {
|
|
|
15237
16317
|
}))
|
|
15238
16318
|
);
|
|
15239
16319
|
return selectEvidence([claimText], index, MAX_SNIPPETS_PER_CLAIM);
|
|
15240
|
-
} catch (
|
|
15241
|
-
console.warn("[EXULU claim-check] second-chance retrieval failed:",
|
|
16320
|
+
} catch (err2) {
|
|
16321
|
+
console.warn("[EXULU claim-check] second-chance retrieval failed:", err2);
|
|
15242
16322
|
return [];
|
|
15243
16323
|
}
|
|
15244
16324
|
};
|
|
@@ -15284,8 +16364,8 @@ async function testSource(source, deps) {
|
|
|
15284
16364
|
try {
|
|
15285
16365
|
await entry.ping();
|
|
15286
16366
|
return { ok: true };
|
|
15287
|
-
} catch (
|
|
15288
|
-
return { ok: false, reason: "unreachable", message:
|
|
16367
|
+
} catch (err2) {
|
|
16368
|
+
return { ok: false, reason: "unreachable", message: err2.message };
|
|
15289
16369
|
}
|
|
15290
16370
|
}
|
|
15291
16371
|
|
|
@@ -16329,6 +17409,7 @@ var {
|
|
|
16329
17409
|
rbacSchema,
|
|
16330
17410
|
promptLibrarySchema,
|
|
16331
17411
|
contextPresetsSchema,
|
|
17412
|
+
contextFoldersSchema,
|
|
16332
17413
|
teamsSchema,
|
|
16333
17414
|
entityTypeSettingsSchema,
|
|
16334
17415
|
promptFavoritesSchema,
|
|
@@ -16391,6 +17472,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
16391
17472
|
jobResultsSchema(),
|
|
16392
17473
|
promptLibrarySchema(),
|
|
16393
17474
|
contextPresetsSchema(),
|
|
17475
|
+
// Knowledge folders (2026-10): UI-only grouping of knowledge contexts
|
|
17476
|
+
// for the IMP's folder view. apiWrites: "super_admin" (core-schema.ts)
|
|
17477
|
+
// reserves the generic CreateOne/UpdateOne*/RemoveOne*/CopyOneById
|
|
17478
|
+
// mutations for super admins; reads stay generic for every
|
|
17479
|
+
// authenticated user, same split as sharedArtifactsSchema below.
|
|
17480
|
+
contextFoldersSchema(),
|
|
16394
17481
|
teamsSchema(),
|
|
16395
17482
|
entityTypeSettingsSchema(),
|
|
16396
17483
|
promptFavoritesSchema(),
|
|
@@ -16543,8 +17630,8 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
16543
17630
|
}
|
|
16544
17631
|
const event = req.body;
|
|
16545
17632
|
res.status(200).json({ ok: true });
|
|
16546
|
-
void recallService.handleWebhookEvent(event).catch((
|
|
16547
|
-
console.error("[EXULU-RECALL] webhook processing failed",
|
|
17633
|
+
void recallService.handleWebhookEvent(event).catch((err2) => {
|
|
17634
|
+
console.error("[EXULU-RECALL] webhook processing failed", err2);
|
|
16548
17635
|
});
|
|
16549
17636
|
});
|
|
16550
17637
|
const routineWebhookHandler = createRoutineWebhookHandler({
|
|
@@ -16575,7 +17662,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
16575
17662
|
inputs: payload
|
|
16576
17663
|
};
|
|
16577
17664
|
await queue.queue.add("email-intake", jobData, {
|
|
16578
|
-
jobId:
|
|
17665
|
+
jobId: randomUUID9(),
|
|
16579
17666
|
attempts: 3,
|
|
16580
17667
|
removeOnComplete: 5e3,
|
|
16581
17668
|
removeOnFail: 1e4,
|
|
@@ -16771,13 +17858,13 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
|
|
|
16771
17858
|
user,
|
|
16772
17859
|
agent
|
|
16773
17860
|
});
|
|
16774
|
-
} catch (
|
|
16775
|
-
if (
|
|
16776
|
-
const status =
|
|
16777
|
-
res.status(status).json({ message:
|
|
17861
|
+
} catch (err2) {
|
|
17862
|
+
if (err2 instanceof ResolveModelError) {
|
|
17863
|
+
const status = err2.code === "MODEL_FORBIDDEN" ? 403 : 400;
|
|
17864
|
+
res.status(status).json({ message: err2.message, code: err2.code });
|
|
16778
17865
|
return;
|
|
16779
17866
|
}
|
|
16780
|
-
throw
|
|
17867
|
+
throw err2;
|
|
16781
17868
|
}
|
|
16782
17869
|
const resolvedLanguageModel = resolved.languageModel;
|
|
16783
17870
|
const resolvedModelId = resolved.model.id;
|
|
@@ -16828,13 +17915,13 @@ ${customInstructions}` : agent.instructions,
|
|
|
16828
17915
|
contextWindow,
|
|
16829
17916
|
disabledTools
|
|
16830
17917
|
});
|
|
16831
|
-
} catch (
|
|
17918
|
+
} catch (err2) {
|
|
16832
17919
|
if (headers.session) clearStreamActive(headers.session);
|
|
16833
17920
|
console.error(
|
|
16834
17921
|
"[EXULU] chat request failed before streaming.",
|
|
16835
|
-
|
|
17922
|
+
err2 instanceof Error ? err2.message.slice(0, 500) : err2
|
|
16836
17923
|
);
|
|
16837
|
-
const { status, body } = describeRequestError(
|
|
17924
|
+
const { status, body } = describeRequestError(err2);
|
|
16838
17925
|
res.status(status).send(body);
|
|
16839
17926
|
return;
|
|
16840
17927
|
}
|
|
@@ -16946,7 +18033,7 @@ ${customInstructions}` : agent.instructions,
|
|
|
16946
18033
|
contextId: agent.memory,
|
|
16947
18034
|
agentId: agent.id,
|
|
16948
18035
|
session: headers.session ?? null,
|
|
16949
|
-
messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ??
|
|
18036
|
+
messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID9(),
|
|
16950
18037
|
userId: user?.id ?? null
|
|
16951
18038
|
});
|
|
16952
18039
|
}
|
|
@@ -17025,12 +18112,12 @@ ${customInstructions}` : agent.instructions,
|
|
|
17025
18112
|
onTokenUsage: async ({ inputTokens, outputTokens }) => {
|
|
17026
18113
|
}
|
|
17027
18114
|
});
|
|
17028
|
-
} catch (
|
|
18115
|
+
} catch (err2) {
|
|
17029
18116
|
console.error(
|
|
17030
18117
|
"[EXULU] run request failed.",
|
|
17031
|
-
|
|
18118
|
+
err2 instanceof Error ? err2.message.slice(0, 500) : err2
|
|
17032
18119
|
);
|
|
17033
|
-
const { status, body } = describeRequestError(
|
|
18120
|
+
const { status, body } = describeRequestError(err2);
|
|
17034
18121
|
res.status(status).send(body);
|
|
17035
18122
|
return;
|
|
17036
18123
|
}
|
|
@@ -17097,13 +18184,13 @@ ${customInstructions}` : agent.instructions,
|
|
|
17097
18184
|
let resolved;
|
|
17098
18185
|
try {
|
|
17099
18186
|
resolved = await resolveModel({ modelId, user, agent });
|
|
17100
|
-
} catch (
|
|
17101
|
-
if (
|
|
17102
|
-
const status =
|
|
17103
|
-
res.status(status).json({ message:
|
|
18187
|
+
} catch (err2) {
|
|
18188
|
+
if (err2 instanceof ResolveModelError) {
|
|
18189
|
+
const status = err2.code === "MODEL_FORBIDDEN" ? 403 : 400;
|
|
18190
|
+
res.status(status).json({ message: err2.message, code: err2.code });
|
|
17104
18191
|
return;
|
|
17105
18192
|
}
|
|
17106
|
-
throw
|
|
18193
|
+
throw err2;
|
|
17107
18194
|
}
|
|
17108
18195
|
const contextWindow = await resolveContextWindow({
|
|
17109
18196
|
modelId: resolved.model.id
|
|
@@ -17119,13 +18206,13 @@ ${customInstructions}` : agent.instructions,
|
|
|
17119
18206
|
modelId: resolved.model.id
|
|
17120
18207
|
});
|
|
17121
18208
|
res.json(result);
|
|
17122
|
-
} catch (
|
|
17123
|
-
if (
|
|
17124
|
-
res.status(422).send(
|
|
18209
|
+
} catch (err2) {
|
|
18210
|
+
if (err2 instanceof CompactionInsufficientError) {
|
|
18211
|
+
res.status(422).send(err2.message);
|
|
17125
18212
|
return;
|
|
17126
18213
|
}
|
|
17127
|
-
console.error("[EXULU] compactSession failed.",
|
|
17128
|
-
res.status(500).json({ message:
|
|
18214
|
+
console.error("[EXULU] compactSession failed.", err2);
|
|
18215
|
+
res.status(500).json({ message: err2 instanceof Error ? err2.message : "Compaction failed." });
|
|
17129
18216
|
}
|
|
17130
18217
|
});
|
|
17131
18218
|
};
|
|
@@ -17190,13 +18277,13 @@ ${customInstructions}` : agent.instructions,
|
|
|
17190
18277
|
user,
|
|
17191
18278
|
agent
|
|
17192
18279
|
});
|
|
17193
|
-
} catch (
|
|
17194
|
-
if (
|
|
17195
|
-
const status =
|
|
17196
|
-
res.status(status).json({ detail:
|
|
18280
|
+
} catch (err2) {
|
|
18281
|
+
if (err2 instanceof ResolveModelError) {
|
|
18282
|
+
const status = err2.code === "MODEL_FORBIDDEN" ? 403 : 400;
|
|
18283
|
+
res.status(status).json({ detail: err2.message, code: err2.code });
|
|
17197
18284
|
return;
|
|
17198
18285
|
}
|
|
17199
|
-
throw
|
|
18286
|
+
throw err2;
|
|
17200
18287
|
}
|
|
17201
18288
|
try {
|
|
17202
18289
|
const { suggestions, usage } = await generateSuggestions({
|
|
@@ -17236,10 +18323,10 @@ ${customInstructions}` : agent.instructions,
|
|
|
17236
18323
|
] : []
|
|
17237
18324
|
]);
|
|
17238
18325
|
res.status(200).json({ suggestions });
|
|
17239
|
-
} catch (
|
|
17240
|
-
console.error("[EXULU] suggestions generation failed",
|
|
18326
|
+
} catch (err2) {
|
|
18327
|
+
console.error("[EXULU] suggestions generation failed", err2);
|
|
17241
18328
|
res.status(500).json({
|
|
17242
|
-
detail:
|
|
18329
|
+
detail: err2 instanceof Error ? err2.message : "Failed to generate suggestions."
|
|
17243
18330
|
});
|
|
17244
18331
|
}
|
|
17245
18332
|
});
|
|
@@ -17249,14 +18336,14 @@ ${customInstructions}` : agent.instructions,
|
|
|
17249
18336
|
limits: { fileSize: MAX_TRANSCRIBE_BYTES }
|
|
17250
18337
|
});
|
|
17251
18338
|
const transcribeUploadMiddleware = (req, res, next) => {
|
|
17252
|
-
transcribeUpload.single("file")(req, res, (
|
|
17253
|
-
if (!
|
|
17254
|
-
const code =
|
|
18339
|
+
transcribeUpload.single("file")(req, res, (err2) => {
|
|
18340
|
+
if (!err2) return next();
|
|
18341
|
+
const code = err2?.code;
|
|
17255
18342
|
if (code === "LIMIT_FILE_SIZE") {
|
|
17256
18343
|
res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
|
|
17257
18344
|
return;
|
|
17258
18345
|
}
|
|
17259
|
-
res.status(400).json({ detail:
|
|
18346
|
+
res.status(400).json({ detail: err2 instanceof Error ? err2.message : "Upload failed." });
|
|
17260
18347
|
});
|
|
17261
18348
|
};
|
|
17262
18349
|
app.post(
|
|
@@ -17300,15 +18387,15 @@ ${customInstructions}` : agent.instructions,
|
|
|
17300
18387
|
try {
|
|
17301
18388
|
const { text } = await transcribeAudio({ file, language });
|
|
17302
18389
|
res.status(200).json({ text });
|
|
17303
|
-
} catch (
|
|
17304
|
-
if (
|
|
17305
|
-
const code =
|
|
17306
|
-
res.status(code).json({ detail:
|
|
18390
|
+
} catch (err2) {
|
|
18391
|
+
if (err2 instanceof TranscriptionError) {
|
|
18392
|
+
const code = err2.upstreamStatus >= 500 ? 502 : err2.upstreamStatus;
|
|
18393
|
+
res.status(code).json({ detail: err2.message });
|
|
17307
18394
|
return;
|
|
17308
18395
|
}
|
|
17309
|
-
console.error("[EXULU] /transcribe failed",
|
|
18396
|
+
console.error("[EXULU] /transcribe failed", err2);
|
|
17310
18397
|
res.status(500).json({
|
|
17311
|
-
detail:
|
|
18398
|
+
detail: err2 instanceof Error ? err2.message : "Transcription failed."
|
|
17312
18399
|
});
|
|
17313
18400
|
}
|
|
17314
18401
|
}
|
|
@@ -17387,8 +18474,8 @@ ${customInstructions}` : agent.instructions,
|
|
|
17387
18474
|
const response = await fetch(url, {
|
|
17388
18475
|
headers: { Authorization: recallApiKey(), accept: "application/json" },
|
|
17389
18476
|
signal: AbortSignal.timeout(1e4)
|
|
17390
|
-
}).catch((
|
|
17391
|
-
throw new Error(`Unable to reach the Recall API: ${
|
|
18477
|
+
}).catch((err2) => {
|
|
18478
|
+
throw new Error(`Unable to reach the Recall API: ${err2.message}`);
|
|
17392
18479
|
});
|
|
17393
18480
|
if (!response.ok) {
|
|
17394
18481
|
const body = await response.text();
|
|
@@ -17412,8 +18499,8 @@ ${customInstructions}` : agent.instructions,
|
|
|
17412
18499
|
}
|
|
17413
18500
|
});
|
|
17414
18501
|
res.status(200).json(result);
|
|
17415
|
-
} catch (
|
|
17416
|
-
res.status(400).json({ detail:
|
|
18502
|
+
} catch (err2) {
|
|
18503
|
+
res.status(400).json({ detail: err2.message });
|
|
17417
18504
|
}
|
|
17418
18505
|
});
|
|
17419
18506
|
const MAX_TTS_INPUT_CHARS = 4e3;
|
|
@@ -17461,15 +18548,15 @@ ${customInstructions}` : agent.instructions,
|
|
|
17461
18548
|
res.setHeader("Content-Length", String(audio.length));
|
|
17462
18549
|
res.setHeader("Cache-Control", "no-store");
|
|
17463
18550
|
res.send(audio);
|
|
17464
|
-
} catch (
|
|
17465
|
-
if (
|
|
17466
|
-
const code =
|
|
17467
|
-
res.status(code).json({ detail:
|
|
18551
|
+
} catch (err2) {
|
|
18552
|
+
if (err2 instanceof SpeechError) {
|
|
18553
|
+
const code = err2.upstreamStatus >= 500 ? 502 : err2.upstreamStatus;
|
|
18554
|
+
res.status(code).json({ detail: err2.message });
|
|
17468
18555
|
return;
|
|
17469
18556
|
}
|
|
17470
|
-
console.error("[EXULU] /speech failed",
|
|
18557
|
+
console.error("[EXULU] /speech failed", err2);
|
|
17471
18558
|
res.status(500).json({
|
|
17472
|
-
detail:
|
|
18559
|
+
detail: err2 instanceof Error ? err2.message : "Speech generation failed."
|
|
17473
18560
|
});
|
|
17474
18561
|
}
|
|
17475
18562
|
}
|
|
@@ -17480,10 +18567,10 @@ ${customInstructions}` : agent.instructions,
|
|
|
17480
18567
|
const configPath = process.env.LITELLM_CONFIG_PATH ?? resolvePath(process.cwd(), "./config.litellm.yaml");
|
|
17481
18568
|
const models = parseImageGenerationModels(configPath);
|
|
17482
18569
|
return new Map(models.map((m) => [m.model_name, m]));
|
|
17483
|
-
} catch (
|
|
18570
|
+
} catch (err2) {
|
|
17484
18571
|
console.error(
|
|
17485
18572
|
"[EXULU] Skipping /images/* routes due to config.litellm.yaml error:",
|
|
17486
|
-
|
|
18573
|
+
err2.message
|
|
17487
18574
|
);
|
|
17488
18575
|
return /* @__PURE__ */ new Map();
|
|
17489
18576
|
}
|
|
@@ -17595,7 +18682,7 @@ ${customInstructions}` : agent.instructions,
|
|
|
17595
18682
|
const keys = [];
|
|
17596
18683
|
const revisedPrompts = [];
|
|
17597
18684
|
for (const img of images) {
|
|
17598
|
-
const filename = `${
|
|
18685
|
+
const filename = `${randomUUID9()}.${img.extension}`;
|
|
17599
18686
|
const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
|
|
17600
18687
|
const fullKey = await uploadFile(
|
|
17601
18688
|
img.buffer,
|
|
@@ -17685,16 +18772,16 @@ ${style.markdown}` : params.prompt;
|
|
|
17685
18772
|
revisedPrompt: revisedPrompts[i]
|
|
17686
18773
|
}))
|
|
17687
18774
|
});
|
|
17688
|
-
} catch (
|
|
18775
|
+
} catch (err2) {
|
|
17689
18776
|
if (abortController.signal.aborted) return;
|
|
17690
|
-
if (
|
|
17691
|
-
const code =
|
|
17692
|
-
res.status(code).json({ detail:
|
|
18777
|
+
if (err2 instanceof ImageGenerationError) {
|
|
18778
|
+
const code = err2.upstreamStatus >= 500 ? 502 : err2.upstreamStatus;
|
|
18779
|
+
res.status(code).json({ detail: err2.message });
|
|
17693
18780
|
return;
|
|
17694
18781
|
}
|
|
17695
|
-
console.error("[EXULU] /images/generate failed",
|
|
18782
|
+
console.error("[EXULU] /images/generate failed", err2);
|
|
17696
18783
|
res.status(500).json({
|
|
17697
|
-
detail:
|
|
18784
|
+
detail: err2 instanceof Error ? err2.message : "Image generation failed."
|
|
17698
18785
|
});
|
|
17699
18786
|
}
|
|
17700
18787
|
});
|
|
@@ -17802,16 +18889,16 @@ ${style.markdown}` : params.prompt;
|
|
|
17802
18889
|
revisedPrompt: revisedPrompts[i]
|
|
17803
18890
|
}))
|
|
17804
18891
|
});
|
|
17805
|
-
} catch (
|
|
18892
|
+
} catch (err2) {
|
|
17806
18893
|
if (abortController.signal.aborted) return;
|
|
17807
|
-
if (
|
|
17808
|
-
const code =
|
|
17809
|
-
res.status(code).json({ detail:
|
|
18894
|
+
if (err2 instanceof ImageGenerationError) {
|
|
18895
|
+
const code = err2.upstreamStatus >= 500 ? 502 : err2.upstreamStatus;
|
|
18896
|
+
res.status(code).json({ detail: err2.message });
|
|
17810
18897
|
return;
|
|
17811
18898
|
}
|
|
17812
|
-
console.error("[EXULU] /images/edit failed",
|
|
18899
|
+
console.error("[EXULU] /images/edit failed", err2);
|
|
17813
18900
|
res.status(500).json({
|
|
17814
|
-
detail:
|
|
18901
|
+
detail: err2 instanceof Error ? err2.message : "Image edit failed."
|
|
17815
18902
|
});
|
|
17816
18903
|
}
|
|
17817
18904
|
});
|
|
@@ -17883,7 +18970,7 @@ ${style.markdown}` : params.prompt;
|
|
|
17883
18970
|
(d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
|
|
17884
18971
|
);
|
|
17885
18972
|
const messageText = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
|
|
17886
|
-
const messageId =
|
|
18973
|
+
const messageId = randomUUID9();
|
|
17887
18974
|
const uiMessage = {
|
|
17888
18975
|
id: messageId,
|
|
17889
18976
|
role: "system",
|
|
@@ -18016,11 +19103,11 @@ ${style.markdown}` : params.prompt;
|
|
|
18016
19103
|
reader.releaseLock();
|
|
18017
19104
|
}
|
|
18018
19105
|
res.end();
|
|
18019
|
-
} catch (
|
|
18020
|
-
console.error("[EXULU] LiteLLM UI proxy failed",
|
|
19106
|
+
} catch (err2) {
|
|
19107
|
+
console.error("[EXULU] LiteLLM UI proxy failed", err2);
|
|
18021
19108
|
if (!res.headersSent) {
|
|
18022
19109
|
res.status(502).json({
|
|
18023
|
-
detail:
|
|
19110
|
+
detail: err2 instanceof Error ? err2.message : "LiteLLM UI proxy failed."
|
|
18024
19111
|
});
|
|
18025
19112
|
} else {
|
|
18026
19113
|
res.end();
|
|
@@ -18145,11 +19232,11 @@ ${style.markdown}` : params.prompt;
|
|
|
18145
19232
|
reader.releaseLock();
|
|
18146
19233
|
}
|
|
18147
19234
|
res.end();
|
|
18148
|
-
} catch (
|
|
18149
|
-
console.error("[EXULU] /litellm proxy failed",
|
|
19235
|
+
} catch (err2) {
|
|
19236
|
+
console.error("[EXULU] /litellm proxy failed", err2);
|
|
18150
19237
|
if (!res.headersSent) {
|
|
18151
19238
|
res.status(502).json({
|
|
18152
|
-
detail:
|
|
19239
|
+
detail: err2 instanceof Error ? err2.message : "LiteLLM proxy failed."
|
|
18153
19240
|
});
|
|
18154
19241
|
} else {
|
|
18155
19242
|
res.end();
|
|
@@ -18206,8 +19293,8 @@ ${style.markdown}` : params.prompt;
|
|
|
18206
19293
|
`attachment; filename="${encodeURIComponent(filename)}"`
|
|
18207
19294
|
);
|
|
18208
19295
|
res.send(bytes);
|
|
18209
|
-
} catch (
|
|
18210
|
-
console.error("[EXULU] markdown export failed",
|
|
19296
|
+
} catch (err2) {
|
|
19297
|
+
console.error("[EXULU] markdown export failed", err2);
|
|
18211
19298
|
res.status(500).json({ detail: "Export failed." });
|
|
18212
19299
|
}
|
|
18213
19300
|
});
|
|
@@ -18305,14 +19392,14 @@ ${style.markdown}` : params.prompt;
|
|
|
18305
19392
|
}
|
|
18306
19393
|
try {
|
|
18307
19394
|
res.status(200).json({ usage: await getMyUsageView(authResult.user.id, window) });
|
|
18308
|
-
} catch (
|
|
18309
|
-
if (
|
|
18310
|
-
res.status(502).json({ detail:
|
|
19395
|
+
} catch (err2) {
|
|
19396
|
+
if (err2 instanceof LiteLLMAdminError) {
|
|
19397
|
+
res.status(502).json({ detail: err2.message });
|
|
18311
19398
|
return;
|
|
18312
19399
|
}
|
|
18313
|
-
console.error("[EXULU] /me/usage failed",
|
|
19400
|
+
console.error("[EXULU] /me/usage failed", err2);
|
|
18314
19401
|
res.status(500).json({
|
|
18315
|
-
detail:
|
|
19402
|
+
detail: err2 instanceof Error ? err2.message : "Usage query failed."
|
|
18316
19403
|
});
|
|
18317
19404
|
}
|
|
18318
19405
|
});
|
|
@@ -18342,11 +19429,11 @@ ${style.markdown}` : params.prompt;
|
|
|
18342
19429
|
try {
|
|
18343
19430
|
await upsertBudget(tag, body.max_budget, body.budget_duration, body.budget_reset_at);
|
|
18344
19431
|
results.push({ entityId: String(id), ok: true });
|
|
18345
|
-
} catch (
|
|
19432
|
+
} catch (err2) {
|
|
18346
19433
|
results.push({
|
|
18347
19434
|
entityId: String(id),
|
|
18348
19435
|
ok: false,
|
|
18349
|
-
error:
|
|
19436
|
+
error: err2 instanceof Error ? err2.message : "Failed."
|
|
18350
19437
|
});
|
|
18351
19438
|
}
|
|
18352
19439
|
}
|
|
@@ -18373,9 +19460,9 @@ ${style.markdown}` : params.prompt;
|
|
|
18373
19460
|
await upsertBudget(tag, body.max_budget, body.budget_duration, body.budget_reset_at);
|
|
18374
19461
|
const info = await tagInfo([tag]);
|
|
18375
19462
|
res.status(200).json({ budget: info[tag] ?? null });
|
|
18376
|
-
} catch (
|
|
19463
|
+
} catch (err2) {
|
|
18377
19464
|
res.status(502).json({
|
|
18378
|
-
detail:
|
|
19465
|
+
detail: err2 instanceof Error ? err2.message : "Failed to save budget."
|
|
18379
19466
|
});
|
|
18380
19467
|
}
|
|
18381
19468
|
}
|
|
@@ -18395,9 +19482,9 @@ ${style.markdown}` : params.prompt;
|
|
|
18395
19482
|
await tagDelete(tag);
|
|
18396
19483
|
invalidateBudgetCaches(tag);
|
|
18397
19484
|
res.status(204).end();
|
|
18398
|
-
} catch (
|
|
19485
|
+
} catch (err2) {
|
|
18399
19486
|
res.status(502).json({
|
|
18400
|
-
detail:
|
|
19487
|
+
detail: err2 instanceof Error ? err2.message : "Failed to delete budget."
|
|
18401
19488
|
});
|
|
18402
19489
|
}
|
|
18403
19490
|
}
|
|
@@ -18768,14 +19855,14 @@ ${style.markdown}` : params.prompt;
|
|
|
18768
19855
|
echoedPrefix
|
|
18769
19856
|
);
|
|
18770
19857
|
res.status(200).json(projected);
|
|
18771
|
-
} catch (
|
|
18772
|
-
if (
|
|
18773
|
-
res.status(502).json({ detail:
|
|
19858
|
+
} catch (err2) {
|
|
19859
|
+
if (err2 instanceof LiteLLMAdminError) {
|
|
19860
|
+
res.status(502).json({ detail: err2.message });
|
|
18774
19861
|
return;
|
|
18775
19862
|
}
|
|
18776
|
-
console.error("[EXULU] /admin/litellm/tag-activity failed",
|
|
19863
|
+
console.error("[EXULU] /admin/litellm/tag-activity failed", err2);
|
|
18777
19864
|
res.status(500).json({
|
|
18778
|
-
detail:
|
|
19865
|
+
detail: err2 instanceof Error ? err2.message : "Analytics query failed."
|
|
18779
19866
|
});
|
|
18780
19867
|
}
|
|
18781
19868
|
}
|
|
@@ -18836,7 +19923,7 @@ ${style.markdown}` : params.prompt;
|
|
|
18836
19923
|
void (async () => {
|
|
18837
19924
|
const { db } = await postgresClient();
|
|
18838
19925
|
await seedBundledSkills({ db, config });
|
|
18839
|
-
})().catch((
|
|
19926
|
+
})().catch((err2) => console.error("[SKILLS] seeding the bundled skills failed", err2));
|
|
18840
19927
|
app.get("/skills/agent/bootstrap", async (_req, res) => {
|
|
18841
19928
|
try {
|
|
18842
19929
|
const zip = new JSZip3();
|
|
@@ -18852,8 +19939,8 @@ ${style.markdown}` : params.prompt;
|
|
|
18852
19939
|
res.setHeader("Content-Type", "application/zip");
|
|
18853
19940
|
res.setHeader("Content-Disposition", 'attachment; filename="imp-skills.zip"');
|
|
18854
19941
|
res.send(buffer);
|
|
18855
|
-
} catch (
|
|
18856
|
-
console.error("[SKILLS] Failed to build bootstrap zip",
|
|
19942
|
+
} catch (err2) {
|
|
19943
|
+
console.error("[SKILLS] Failed to build bootstrap zip", err2);
|
|
18857
19944
|
res.status(500).json({ detail: "Failed to build bootstrap skill." });
|
|
18858
19945
|
}
|
|
18859
19946
|
});
|
|
@@ -18937,17 +20024,17 @@ ${style.markdown}` : params.prompt;
|
|
|
18937
20024
|
const { db } = await postgresClient();
|
|
18938
20025
|
const existing = await resolveSkillByName(db, name);
|
|
18939
20026
|
if (existing) {
|
|
18940
|
-
const
|
|
18941
|
-
if (
|
|
20027
|
+
const canWrite2 = await canAccessSkill(db, existing, "write", authResult.user);
|
|
20028
|
+
if (canWrite2) {
|
|
18942
20029
|
const nextVersion = (existing.current_version ?? 1) + 1;
|
|
18943
20030
|
try {
|
|
18944
20031
|
await extractBundleToVersion({ bytes, skillId: existing.id, version: nextVersion, config });
|
|
18945
|
-
} catch (
|
|
18946
|
-
if (
|
|
18947
|
-
res.status(400).json({ detail:
|
|
20032
|
+
} catch (err2) {
|
|
20033
|
+
if (err2 instanceof BundleValidationError) {
|
|
20034
|
+
res.status(400).json({ detail: err2.message });
|
|
18948
20035
|
return;
|
|
18949
20036
|
}
|
|
18950
|
-
console.error("[SKILLS] publish (new version) failed",
|
|
20037
|
+
console.error("[SKILLS] publish (new version) failed", err2);
|
|
18951
20038
|
res.status(500).json({ detail: "Failed to publish new version." });
|
|
18952
20039
|
return;
|
|
18953
20040
|
}
|
|
@@ -18980,15 +20067,15 @@ ${style.markdown}` : params.prompt;
|
|
|
18980
20067
|
return;
|
|
18981
20068
|
}
|
|
18982
20069
|
const meta = await parseSkillFrontmatter(bytes);
|
|
18983
|
-
const skillId =
|
|
20070
|
+
const skillId = randomUUID9();
|
|
18984
20071
|
try {
|
|
18985
20072
|
await extractBundleToVersion({ bytes, skillId, version: 1, config });
|
|
18986
|
-
} catch (
|
|
18987
|
-
if (
|
|
18988
|
-
res.status(400).json({ detail:
|
|
20073
|
+
} catch (err2) {
|
|
20074
|
+
if (err2 instanceof BundleValidationError) {
|
|
20075
|
+
res.status(400).json({ detail: err2.message });
|
|
18989
20076
|
return;
|
|
18990
20077
|
}
|
|
18991
|
-
console.error("[SKILLS] publish (create) failed",
|
|
20078
|
+
console.error("[SKILLS] publish (create) failed", err2);
|
|
18992
20079
|
res.status(500).json({ detail: "Failed to publish skill." });
|
|
18993
20080
|
return;
|
|
18994
20081
|
}
|
|
@@ -19008,7 +20095,7 @@ ${style.markdown}` : params.prompt;
|
|
|
19008
20095
|
rights_mode: visibility,
|
|
19009
20096
|
created_by: authResult.user.id
|
|
19010
20097
|
});
|
|
19011
|
-
} catch (
|
|
20098
|
+
} catch (err2) {
|
|
19012
20099
|
res.status(409).json({ detail: "That name is unavailable." });
|
|
19013
20100
|
return;
|
|
19014
20101
|
}
|
|
@@ -19062,8 +20149,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19062
20149
|
const s3Key = `skills/${skillId}/v1/SKILL.md`;
|
|
19063
20150
|
try {
|
|
19064
20151
|
await uploadFile(Buffer.from(skillMdContent, "utf-8"), s3Key, config, { contentType: "text/markdown" }, void 0, void 0, true);
|
|
19065
|
-
} catch (
|
|
19066
|
-
console.error("[SKILLS] Failed to create SKILL.md in S3",
|
|
20152
|
+
} catch (err2) {
|
|
20153
|
+
console.error("[SKILLS] Failed to create SKILL.md in S3", err2);
|
|
19067
20154
|
res.status(500).json({ detail: "Failed to initialise skill folder in S3." });
|
|
19068
20155
|
return;
|
|
19069
20156
|
}
|
|
@@ -19100,7 +20187,7 @@ ${style.markdown}` : params.prompt;
|
|
|
19100
20187
|
res.status(404).json({ detail: "Skill not found." });
|
|
19101
20188
|
return;
|
|
19102
20189
|
}
|
|
19103
|
-
const stagingKey = `user_${authResult.user.id}/skills/_staging/${
|
|
20190
|
+
const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID9()}${extension}`;
|
|
19104
20191
|
const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
|
|
19105
20192
|
const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
|
|
19106
20193
|
res.json({ uploadUrl, stagingKey });
|
|
@@ -19140,15 +20227,15 @@ ${style.markdown}` : params.prompt;
|
|
|
19140
20227
|
let bytes;
|
|
19141
20228
|
try {
|
|
19142
20229
|
bytes = await getS3ObjectBytes(fullStagingKey, config);
|
|
19143
|
-
} catch (
|
|
19144
|
-
console.error("[SKILLS] Failed to fetch staged bundle",
|
|
20230
|
+
} catch (err2) {
|
|
20231
|
+
console.error("[SKILLS] Failed to fetch staged bundle", err2);
|
|
19145
20232
|
res.status(500).json({ detail: "Failed to fetch staged bundle from S3." });
|
|
19146
20233
|
return;
|
|
19147
20234
|
}
|
|
19148
20235
|
let result;
|
|
19149
20236
|
try {
|
|
19150
20237
|
result = await extractBundleToS3({ bytes, skillId, isZip, config });
|
|
19151
|
-
} catch (
|
|
20238
|
+
} catch (err2) {
|
|
19152
20239
|
try {
|
|
19153
20240
|
await db("skills").where({ id: skillId }).delete();
|
|
19154
20241
|
} catch (cleanupErr) {
|
|
@@ -19165,11 +20252,11 @@ ${style.markdown}` : params.prompt;
|
|
|
19165
20252
|
cleanupErr
|
|
19166
20253
|
);
|
|
19167
20254
|
}
|
|
19168
|
-
if (
|
|
19169
|
-
res.status(400).json({ detail:
|
|
20255
|
+
if (err2 instanceof BundleValidationError) {
|
|
20256
|
+
res.status(400).json({ detail: err2.message });
|
|
19170
20257
|
return;
|
|
19171
20258
|
}
|
|
19172
|
-
console.error("[SKILLS] Failed to extract bundle",
|
|
20259
|
+
console.error("[SKILLS] Failed to extract bundle", err2);
|
|
19173
20260
|
res.status(500).json({ detail: "Failed to extract bundle." });
|
|
19174
20261
|
return;
|
|
19175
20262
|
}
|
|
@@ -19183,8 +20270,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19183
20270
|
});
|
|
19184
20271
|
try {
|
|
19185
20272
|
await deleteS3Object(fullStagingKey, config);
|
|
19186
|
-
} catch (
|
|
19187
|
-
console.warn(`[SKILLS] Failed to delete staging key ${fullStagingKey}; continuing.`,
|
|
20273
|
+
} catch (err2) {
|
|
20274
|
+
console.warn(`[SKILLS] Failed to delete staging key ${fullStagingKey}; continuing.`, err2);
|
|
19188
20275
|
}
|
|
19189
20276
|
res.json({ version: 1, filesCount: result.filesCount });
|
|
19190
20277
|
});
|
|
@@ -19592,8 +20679,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19592
20679
|
const skills = await getEnabledSkills(agent, []);
|
|
19593
20680
|
const outcome = await refreshSessionSkills(sessionId, skills, config);
|
|
19594
20681
|
res.json({ ...outcome, skills: skills.map((s) => ({ id: s.id, name: s.name, version: s.current_version })) });
|
|
19595
|
-
} catch (
|
|
19596
|
-
console.error("[SKILLS] reload failed",
|
|
20682
|
+
} catch (err2) {
|
|
20683
|
+
console.error("[SKILLS] reload failed", err2);
|
|
19597
20684
|
res.status(500).json({ detail: "Could not reload the skills." });
|
|
19598
20685
|
}
|
|
19599
20686
|
});
|
|
@@ -19613,8 +20700,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19613
20700
|
let objects;
|
|
19614
20701
|
try {
|
|
19615
20702
|
objects = await listS3ObjectsByPrefix(userSessionPrefix, config);
|
|
19616
|
-
} catch (
|
|
19617
|
-
console.error("[SESSION-FILES] Failed to list S3 objects",
|
|
20703
|
+
} catch (err2) {
|
|
20704
|
+
console.error("[SESSION-FILES] Failed to list S3 objects", err2);
|
|
19618
20705
|
res.status(500).json({ detail: "Failed to list session files." });
|
|
19619
20706
|
return;
|
|
19620
20707
|
}
|
|
@@ -19696,8 +20783,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19696
20783
|
config
|
|
19697
20784
|
});
|
|
19698
20785
|
res.json(result);
|
|
19699
|
-
} catch (
|
|
19700
|
-
console.error("[SESSION-FILES] sync-to-sandbox failed",
|
|
20786
|
+
} catch (err2) {
|
|
20787
|
+
console.error("[SESSION-FILES] sync-to-sandbox failed", err2);
|
|
19701
20788
|
res.status(500).json({ detail: "Failed to sync file into sandbox." });
|
|
19702
20789
|
}
|
|
19703
20790
|
}
|
|
@@ -19724,8 +20811,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19724
20811
|
try {
|
|
19725
20812
|
await deleteS3Object(key, config);
|
|
19726
20813
|
res.json({ deleted: true });
|
|
19727
|
-
} catch (
|
|
19728
|
-
console.error("[SESSION-FILES] delete failed",
|
|
20814
|
+
} catch (err2) {
|
|
20815
|
+
console.error("[SESSION-FILES] delete failed", err2);
|
|
19729
20816
|
res.status(500).json({ detail: "Failed to delete session file." });
|
|
19730
20817
|
}
|
|
19731
20818
|
}
|
|
@@ -19766,13 +20853,13 @@ ${style.markdown}` : params.prompt;
|
|
|
19766
20853
|
res.setHeader("Content-Type", "application/pdf");
|
|
19767
20854
|
res.setHeader("Cache-Control", "private, max-age=300");
|
|
19768
20855
|
res.send(pdfBytes);
|
|
19769
|
-
} catch (
|
|
19770
|
-
if (
|
|
19771
|
-
console.error("[SESSION-FILES] preview render failed",
|
|
19772
|
-
res.status(500).json({ detail:
|
|
20856
|
+
} catch (err2) {
|
|
20857
|
+
if (err2 instanceof PreviewRenderError) {
|
|
20858
|
+
console.error("[SESSION-FILES] preview render failed", err2);
|
|
20859
|
+
res.status(500).json({ detail: err2.message });
|
|
19773
20860
|
return;
|
|
19774
20861
|
}
|
|
19775
|
-
console.error("[SESSION-FILES] preview unexpected error",
|
|
20862
|
+
console.error("[SESSION-FILES] preview unexpected error", err2);
|
|
19776
20863
|
res.status(500).json({ detail: "Failed to render preview." });
|
|
19777
20864
|
}
|
|
19778
20865
|
}
|
|
@@ -19877,8 +20964,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19877
20964
|
`attachment; filename="${filename}"`
|
|
19878
20965
|
);
|
|
19879
20966
|
res.send(buffer);
|
|
19880
|
-
} catch (
|
|
19881
|
-
console.error("[GDPR] Failed to build data export",
|
|
20967
|
+
} catch (err2) {
|
|
20968
|
+
console.error("[GDPR] Failed to build data export", err2);
|
|
19882
20969
|
res.status(500).json({ detail: "Failed to build data export." });
|
|
19883
20970
|
}
|
|
19884
20971
|
});
|
|
@@ -19899,8 +20986,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19899
20986
|
await trx("rbac").where({ user_id: targetUser.id }).delete();
|
|
19900
20987
|
await trx("users").where({ id: targetUser.id }).delete();
|
|
19901
20988
|
});
|
|
19902
|
-
} catch (
|
|
19903
|
-
console.error("[GDPR] Failed to delete user",
|
|
20989
|
+
} catch (err2) {
|
|
20990
|
+
console.error("[GDPR] Failed to delete user", err2);
|
|
19904
20991
|
res.status(500).json({ detail: "Failed to delete user." });
|
|
19905
20992
|
return;
|
|
19906
20993
|
}
|
|
@@ -19908,8 +20995,8 @@ ${style.markdown}` : params.prompt;
|
|
|
19908
20995
|
const prefix = `user_${targetUser.id}/`;
|
|
19909
20996
|
const files = await listS3ObjectsByPrefix(prefix, config);
|
|
19910
20997
|
await Promise.all(files.map((f) => deleteS3Object(f.key, config)));
|
|
19911
|
-
} catch (
|
|
19912
|
-
console.error("[GDPR] DB delete succeeded but S3 cleanup failed",
|
|
20998
|
+
} catch (err2) {
|
|
20999
|
+
console.error("[GDPR] DB delete succeeded but S3 cleanup failed", err2);
|
|
19913
21000
|
}
|
|
19914
21001
|
res.status(204).send();
|
|
19915
21002
|
});
|
|
@@ -20203,9 +21290,9 @@ ${style.markdown}` : params.prompt;
|
|
|
20203
21290
|
if (!agentModel) return "";
|
|
20204
21291
|
return "";
|
|
20205
21292
|
};
|
|
20206
|
-
const
|
|
21293
|
+
const UUID_RE3 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
20207
21294
|
const getGuestAgentById = async (id) => {
|
|
20208
|
-
if (!
|
|
21295
|
+
if (!UUID_RE3.test(id)) return void 0;
|
|
20209
21296
|
const { db } = await postgresClient();
|
|
20210
21297
|
return db.from("agents").where({ id, guest_access: true, active: true }).first();
|
|
20211
21298
|
};
|
|
@@ -20348,7 +21435,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
|
|
|
20348
21435
|
|
|
20349
21436
|
// src/mcp/index.ts
|
|
20350
21437
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
20351
|
-
import { randomUUID as
|
|
21438
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
20352
21439
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
20353
21440
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
20354
21441
|
import "express";
|
|
@@ -20442,7 +21529,7 @@ var ExuluMCP = class {
|
|
|
20442
21529
|
throw new Error("Tool not found in converted tools array.");
|
|
20443
21530
|
}
|
|
20444
21531
|
const iterator = await convertedTool.execute(inputs, {
|
|
20445
|
-
toolCallId: tool2.id + "_" +
|
|
21532
|
+
toolCallId: tool2.id + "_" + randomUUID10(),
|
|
20446
21533
|
messages: []
|
|
20447
21534
|
});
|
|
20448
21535
|
let result;
|
|
@@ -20632,7 +21719,7 @@ var ExuluMCP = class {
|
|
|
20632
21719
|
transport = this.transports[sessionId];
|
|
20633
21720
|
} else if (!sessionId && isInitializeRequest(req.body)) {
|
|
20634
21721
|
transport = new StreamableHTTPServerTransport({
|
|
20635
|
-
sessionIdGenerator: () =>
|
|
21722
|
+
sessionIdGenerator: () => randomUUID10(),
|
|
20636
21723
|
onsessioninitialized: (sessionId2) => {
|
|
20637
21724
|
this.transports[sessionId2] = transport;
|
|
20638
21725
|
}
|
|
@@ -21213,7 +22300,7 @@ After asking a question, use the Question Read tool to check if the user has ans
|
|
|
21213
22300
|
|
|
21214
22301
|
// src/templates/tools/question/question-ask.ts
|
|
21215
22302
|
import z15 from "zod";
|
|
21216
|
-
import { randomUUID as
|
|
22303
|
+
import { randomUUID as randomUUID11 } from "crypto";
|
|
21217
22304
|
var AnswerOptionSchema = z15.object({
|
|
21218
22305
|
id: z15.string().describe("Unique identifier for the answer option"),
|
|
21219
22306
|
text: z15.string().describe("The text of the answer option")
|
|
@@ -21267,15 +22354,15 @@ var QuestionAskTool = new ExuluTool({
|
|
|
21267
22354
|
throw new Error("You don't have access to this session " + session.id + ".");
|
|
21268
22355
|
}
|
|
21269
22356
|
const answerOptionsWithIds = answerOptions.map((text) => ({
|
|
21270
|
-
id:
|
|
22357
|
+
id: randomUUID11(),
|
|
21271
22358
|
text
|
|
21272
22359
|
}));
|
|
21273
22360
|
answerOptionsWithIds.push({
|
|
21274
|
-
id:
|
|
22361
|
+
id: randomUUID11(),
|
|
21275
22362
|
text: "None of the above..."
|
|
21276
22363
|
});
|
|
21277
22364
|
const newQuestion = {
|
|
21278
|
-
id:
|
|
22365
|
+
id: randomUUID11(),
|
|
21279
22366
|
question,
|
|
21280
22367
|
answerOptions: answerOptionsWithIds,
|
|
21281
22368
|
status: "pending"
|
|
@@ -21612,8 +22699,8 @@ var tick = async () => {
|
|
|
21612
22699
|
if (stopped) return;
|
|
21613
22700
|
try {
|
|
21614
22701
|
await transcriptionService.pollOnce(MAX_PER_TICK);
|
|
21615
|
-
} catch (
|
|
21616
|
-
console.error(`[EXULU-TRANSCRIPTION] polling tick failed: ${
|
|
22702
|
+
} catch (err2) {
|
|
22703
|
+
console.error(`[EXULU-TRANSCRIPTION] polling tick failed: ${err2.message}`);
|
|
21617
22704
|
} finally {
|
|
21618
22705
|
if (!stopped) {
|
|
21619
22706
|
timer = setTimeout(tick, POLL_INTERVAL_MS);
|
|
@@ -21646,9 +22733,9 @@ var tick2 = async () => {
|
|
|
21646
22733
|
if (acted > 0) {
|
|
21647
22734
|
console.log(`[EXULU-RECALL] reconcile tick recovered ${acted} job(s)`);
|
|
21648
22735
|
}
|
|
21649
|
-
} catch (
|
|
22736
|
+
} catch (err2) {
|
|
21650
22737
|
console.error(
|
|
21651
|
-
`[EXULU-RECALL] reconcile tick failed: ${
|
|
22738
|
+
`[EXULU-RECALL] reconcile tick failed: ${err2.message}`
|
|
21652
22739
|
);
|
|
21653
22740
|
} finally {
|
|
21654
22741
|
if (!stopped2) {
|
|
@@ -21842,6 +22929,7 @@ var ExuluApp = class {
|
|
|
21842
22929
|
5,
|
|
21843
22930
|
300
|
|
21844
22931
|
);
|
|
22932
|
+
registerImportQueue();
|
|
21845
22933
|
if (queues2?.length) {
|
|
21846
22934
|
for (const queue of queues2) {
|
|
21847
22935
|
queueSet.add(await queue);
|
|
@@ -21890,10 +22978,10 @@ var ExuluApp = class {
|
|
|
21890
22978
|
setLiteLLMPackageRoot(packageRoot);
|
|
21891
22979
|
try {
|
|
21892
22980
|
await startLiteLLMSupervisor();
|
|
21893
|
-
} catch (
|
|
22981
|
+
} catch (err2) {
|
|
21894
22982
|
console.error(
|
|
21895
22983
|
"[EXULU] LiteLLM supervisor failed to start:",
|
|
21896
|
-
|
|
22984
|
+
err2.message
|
|
21897
22985
|
);
|
|
21898
22986
|
}
|
|
21899
22987
|
}
|
|
@@ -21904,9 +22992,9 @@ var ExuluApp = class {
|
|
|
21904
22992
|
console.log(
|
|
21905
22993
|
`[EXULU] Transcription: enabled (server=${process.env.TRANSCRIPTION_SERVER}, device=${health.device}, GPU=${health.gpu.available ? "enabled" : "disabled"}, diarization=${health.diarization ? "enabled" : "disabled"})`
|
|
21906
22994
|
);
|
|
21907
|
-
} catch (
|
|
22995
|
+
} catch (err2) {
|
|
21908
22996
|
console.warn(
|
|
21909
|
-
`[EXULU] TRANSCRIPTION_SERVER set but not reachable yet: ${
|
|
22997
|
+
`[EXULU] TRANSCRIPTION_SERVER set but not reachable yet: ${err2.message}. Polling loop is running; jobs will reconcile once the server is up.`
|
|
21910
22998
|
);
|
|
21911
22999
|
}
|
|
21912
23000
|
} else {
|
|
@@ -22965,6 +24053,7 @@ var {
|
|
|
22965
24053
|
jobResultsSchema: jobResultsSchema2,
|
|
22966
24054
|
promptLibrarySchema: promptLibrarySchema2,
|
|
22967
24055
|
contextPresetsSchema: contextPresetsSchema2,
|
|
24056
|
+
contextFoldersSchema: contextFoldersSchema2,
|
|
22968
24057
|
contextProjectionsSchema,
|
|
22969
24058
|
contextMapTopicsSchema,
|
|
22970
24059
|
entityTypeSettingsSchema: entityTypeSettingsSchema2,
|
|
@@ -23028,6 +24117,7 @@ var up = async function(knex) {
|
|
|
23028
24117
|
jobResultsSchema2(),
|
|
23029
24118
|
promptLibrarySchema2(),
|
|
23030
24119
|
contextPresetsSchema2(),
|
|
24120
|
+
contextFoldersSchema2(),
|
|
23031
24121
|
contextProjectionsSchema(),
|
|
23032
24122
|
contextMapTopicsSchema(),
|
|
23033
24123
|
entityTypeSettingsSchema2(),
|
|
@@ -23429,12 +24519,12 @@ var initLiteLLMDatabase = async (packageRoot) => {
|
|
|
23429
24519
|
await probe.connect();
|
|
23430
24520
|
await probe.end();
|
|
23431
24521
|
return true;
|
|
23432
|
-
} catch (
|
|
23433
|
-
const code =
|
|
24522
|
+
} catch (err2) {
|
|
24523
|
+
const code = err2?.code;
|
|
23434
24524
|
if (code !== "3D000") {
|
|
23435
24525
|
warn2([
|
|
23436
24526
|
`Could not connect to LiteLLM's target database:`,
|
|
23437
|
-
` ${
|
|
24527
|
+
` ${err2 instanceof Error ? err2.message : String(err2)}`,
|
|
23438
24528
|
``,
|
|
23439
24529
|
`Skipping LiteLLM database setup. LiteLLM features that depend on`,
|
|
23440
24530
|
`the database will fail at runtime until this is resolved.`
|
|
@@ -23498,11 +24588,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
|
|
|
23498
24588
|
ORDER BY table_name;`
|
|
23499
24589
|
);
|
|
23500
24590
|
foreignTables = res.rows.map((r) => r.table_name);
|
|
23501
|
-
} catch (
|
|
24591
|
+
} catch (err2) {
|
|
23502
24592
|
warn2([
|
|
23503
24593
|
`Could not query LiteLLM's target database to verify it is safe`,
|
|
23504
24594
|
`to push into:`,
|
|
23505
|
-
` ${
|
|
24595
|
+
` ${err2 instanceof Error ? err2.message : String(err2)}`,
|
|
23506
24596
|
``,
|
|
23507
24597
|
`Skipping LiteLLM database setup. LiteLLM features that depend on the`,
|
|
23508
24598
|
`database will fail at runtime until this is resolved.`
|
|
@@ -24128,7 +25218,7 @@ import * as path from "path";
|
|
|
24128
25218
|
import { generateText as generateText8, Output as Output3 } from "ai";
|
|
24129
25219
|
import { z as z19 } from "zod";
|
|
24130
25220
|
import pLimit from "p-limit";
|
|
24131
|
-
import { randomUUID as
|
|
25221
|
+
import { randomUUID as randomUUID12 } from "crypto";
|
|
24132
25222
|
import * as mammoth from "mammoth";
|
|
24133
25223
|
import TurndownService from "turndown";
|
|
24134
25224
|
import WordExtractor from "word-extractor";
|
|
@@ -24295,10 +25385,10 @@ async function resolveOcr(input) {
|
|
|
24295
25385
|
}
|
|
24296
25386
|
try {
|
|
24297
25387
|
await waitForLiteLLMReady();
|
|
24298
|
-
} catch (
|
|
25388
|
+
} catch (err2) {
|
|
24299
25389
|
throw new ResolveOcrError(
|
|
24300
25390
|
"LITELLM_NOT_READY",
|
|
24301
|
-
`LiteLLM is not ready: ${
|
|
25391
|
+
`LiteLLM is not ready: ${err2.message}`
|
|
24302
25392
|
);
|
|
24303
25393
|
}
|
|
24304
25394
|
const { baseUrl, authHeaders } = resolveLiteLLMTarget();
|
|
@@ -24815,9 +25905,9 @@ async function processPdf(buffer, paths, config, verbose = false) {
|
|
|
24815
25905
|
let pdfChunks;
|
|
24816
25906
|
try {
|
|
24817
25907
|
pdfChunks = JSON.parse(splitResult.stdout);
|
|
24818
|
-
} catch (
|
|
25908
|
+
} catch (err2) {
|
|
24819
25909
|
throw new Error(
|
|
24820
|
-
`[EXULU] split_pdf.py returned invalid JSON on stdout: ${
|
|
25910
|
+
`[EXULU] split_pdf.py returned invalid JSON on stdout: ${err2.message}
|
|
24821
25911
|
stdout: ${splitResult.stdout.slice(0, 500)}
|
|
24822
25912
|
stderr: ${splitResult.stderr.slice(-1e3)}`
|
|
24823
25913
|
);
|
|
@@ -24963,7 +26053,7 @@ var loadFile = async (file, name, tempDir) => {
|
|
|
24963
26053
|
if (!fileType) {
|
|
24964
26054
|
throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
|
|
24965
26055
|
}
|
|
24966
|
-
const UUID2 =
|
|
26056
|
+
const UUID2 = randomUUID12();
|
|
24967
26057
|
let buffer;
|
|
24968
26058
|
if (Buffer.isBuffer(file)) {
|
|
24969
26059
|
filePath = path.join(tempDir, `${UUID2}.${fileType}`);
|
|
@@ -24993,7 +26083,7 @@ async function documentProcessor({
|
|
|
24993
26083
|
if (!license["advanced-document-processing"]) {
|
|
24994
26084
|
throw new Error("Advanced document processing is an enterprise feature, please add a valid Exulu enterprise license key to use it.");
|
|
24995
26085
|
}
|
|
24996
|
-
const uuid =
|
|
26086
|
+
const uuid = randomUUID12();
|
|
24997
26087
|
const tempDir = path.join(process.cwd(), "temp", uuid);
|
|
24998
26088
|
const localFilesAndFoldersToDelete = [tempDir];
|
|
24999
26089
|
console.log(`[EXULU] Temporary directory for processing document ${name}: ${tempDir}`);
|