@exulu/backend 5.5.0 → 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/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-ZWFL6YUH.js";
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", (err) => {
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(err)}${count > 1 ? ` (x${count})` : ""}`);
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 = (err) => {
263
- lastError = err;
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 (err) {
663
+ } catch (err2) {
662
664
  void newQueue.close().catch(() => {
663
665
  });
664
- throw err;
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 (err) {
2494
+ } catch (err2) {
2004
2495
  console.warn(
2005
2496
  `[EXULU] Could not read the chunk vector dimensionality for "${contextId}":`,
2006
- err.message
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 (err) {
2608
+ } catch (err2) {
2118
2609
  console.warn(
2119
2610
  "[EXULU] Could not read the Transcripts settings:",
2120
- err.message
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 VALID_RIGHTS_MODES2 = ["private", "users", "roles", "teams", "public"];
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 (err) {
2867
+ } catch (err2) {
2377
2868
  console.warn(
2378
2869
  "[EXULU] Could not read prompt_library for the Transcripts settings page:",
2379
- err.message
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 (err) {
2878
+ } catch (err2) {
2388
2879
  console.warn(
2389
2880
  "[EXULU] Could not read agents for the Transcripts settings page:",
2390
- err.message
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 && !VALID_RIGHTS_MODES2.includes(input.rights_mode)) {
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: ${VALID_RIGHTS_MODES2.join(", ")}`
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 (err) {
3789
+ } catch (err2) {
3216
3790
  ctx.embedder = previous;
3217
- throw err;
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 (!VALID_RIGHTS_MODES2.includes(rights_mode)) {
3827
+ if (!VALID_RIGHTS_MODES3.includes(rights_mode)) {
3254
3828
  throw new Error(
3255
- `Invalid rights_mode "${rights_mode}" \u2014 expected one of: ${VALID_RIGHTS_MODES2.join(", ")}`
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 "email_intake".`
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 (err) {
3488
- console.warn(`[EXULU] could not re-sign stored file URL for key "${location.key}":`, err);
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 (err) {
3536
- console.warn(`[EXULU] could not list session files for prompt (session ${opts.sessionID}):`, err);
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 ?? randomUUID(),
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 ?? randomUUID(),
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 (err) {
5312
+ } catch (err2) {
4771
5313
  console.warn(
4772
5314
  "[EXULU] Failed to parse the agentic_context_search vocabulary config while building agent instructions.",
4773
- err
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 randomUUID3 } from "crypto";
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 randomUUID2 } from "crypto";
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(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/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", (err) => reject(err instanceof Error ? err : new Error(String(err))));
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 : `<${randomUUID2()}@webhook.local>`;
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 (err) {
5696
+ } catch (err2) {
5155
5697
  console.error(
5156
5698
  "[EXULU] email-inbound rate limit: redis unavailable, allowing (best-effort)",
5157
- err instanceof Error ? err.message : String(err)
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: randomUUID3(),
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 (err) {
6586
- console.warn(`[EXULU] Could not resolve the context window for routine model "${resolved.model.id}"; using the default.`, err);
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"
@@ -6655,6 +7699,12 @@ var processUiMessagesFlow = async ({
6655
7699
  const stream = result.stream.toUIMessageStream({
6656
7700
  messageMetadata: ({ part }) => {
6657
7701
  console.log("[EXULU] part", part.type);
7702
+ if (part.type === "finish-step") {
7703
+ return {
7704
+ lastStepInputTokens: part.usage.inputTokens,
7705
+ lastStepOutputTokens: part.usage.outputTokens
7706
+ };
7707
+ }
6658
7708
  if (part.type === "finish") {
6659
7709
  return finishTurnMetadata({ totalUsage: part.totalUsage, startedAt: startTime });
6660
7710
  }
@@ -6915,10 +7965,10 @@ async function fetch_with_retry(args) {
6915
7965
  url,
6916
7966
  timeout_ms ? { ...options, signal: AbortSignal.timeout(timeout_ms) } : options
6917
7967
  );
6918
- } catch (err) {
6919
- if (!retry_on_reject || attempt === max_attempts) throw err;
7968
+ } catch (err2) {
7969
+ if (!retry_on_reject || attempt === max_attempts) throw err2;
6920
7970
  console.log(
6921
- `[EXULU-RECALL] fetch error from ${url} (${err.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
7971
+ `[EXULU-RECALL] fetch error from ${url} (${err2.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
6922
7972
  );
6923
7973
  await new Promise((resolve4) => setTimeout(resolve4, 5e3 + jitterMs()));
6924
7974
  continue;
@@ -7251,13 +8301,13 @@ var recallService = {
7251
8301
  });
7252
8302
  const [updated] = await db(TABLE).where({ id: inserted.id }).update({ recall_bot_id: bot.id, updatedAt: /* @__PURE__ */ new Date() }).returning("*");
7253
8303
  return this._row(updated);
7254
- } catch (err) {
8304
+ } catch (err2) {
7255
8305
  const [failed] = await db(TABLE).where({ id: inserted.id }).update({
7256
8306
  status: "failed",
7257
- error: err.message,
8307
+ error: err2.message,
7258
8308
  updatedAt: /* @__PURE__ */ new Date()
7259
8309
  }).returning("*");
7260
- log2(`createBot failed for job ${inserted.id}: ${err.message}`);
8310
+ log2(`createBot failed for job ${inserted.id}: ${err2.message}`);
7261
8311
  return this._row(failed);
7262
8312
  }
7263
8313
  },
@@ -7328,8 +8378,8 @@ var recallService = {
7328
8378
  row?.language || "auto"
7329
8379
  );
7330
8380
  await this._update(jobId, { recall_transcript_id: transcript.id ?? null });
7331
- } catch (err) {
7332
- await this._fail(jobId, `create transcript failed: ${err.message}`);
8381
+ } catch (err2) {
8382
+ await this._fail(jobId, `create transcript failed: ${err2.message}`);
7333
8383
  }
7334
8384
  },
7335
8385
  async _onTranscriptDone(jobId, transcriptId, recordingId) {
@@ -7365,12 +8415,12 @@ var recallService = {
7365
8415
  jobId,
7366
8416
  exuluApp.get().config
7367
8417
  );
7368
- } catch (err) {
7369
- log2(`could not store video locally for job ${jobId}: ${err.message}`);
8418
+ } catch (err2) {
8419
+ log2(`could not store video locally for job ${jobId}: ${err2.message}`);
7370
8420
  }
7371
8421
  }
7372
- } catch (err) {
7373
- log2(`could not fetch recording duration for job ${jobId}: ${err.message}`);
8422
+ } catch (err2) {
8423
+ log2(`could not fetch recording duration for job ${jobId}: ${err2.message}`);
7374
8424
  }
7375
8425
  }
7376
8426
  await this._update(jobId, {
@@ -7380,8 +8430,8 @@ var recallService = {
7380
8430
  ...videoS3Key ? { video_s3key: videoS3Key } : {},
7381
8431
  status: "awaiting_review"
7382
8432
  });
7383
- } catch (err) {
7384
- await this._fail(jobId, `transcript download failed: ${err.message}`);
8433
+ } catch (err2) {
8434
+ await this._fail(jobId, `transcript download failed: ${err2.message}`);
7385
8435
  return;
7386
8436
  }
7387
8437
  await this.runPostProcessing(jobId);
@@ -7413,9 +8463,9 @@ var recallService = {
7413
8463
  if (!video) return null;
7414
8464
  if (video.status?.code && video.status.code !== "done") return null;
7415
8465
  return video.data?.download_url ?? null;
7416
- } catch (err) {
8466
+ } catch (err2) {
7417
8467
  log2(
7418
- `could not resolve video url for recording ${recordingId}: ${err.message}`
8468
+ `could not resolve video url for recording ${recordingId}: ${err2.message}`
7419
8469
  );
7420
8470
  return null;
7421
8471
  }
@@ -7552,15 +8602,15 @@ ${transcriptText}`,
7552
8602
  error: null,
7553
8603
  ran_at: ranAt
7554
8604
  };
7555
- } catch (err) {
7556
- log2(`post-processing prompt ${promptId} failed for job ${job.id}: ${err.message}`);
8605
+ } catch (err2) {
8606
+ log2(`post-processing prompt ${promptId} failed for job ${job.id}: ${err2.message}`);
7557
8607
  return {
7558
8608
  prompt_id: promptId,
7559
8609
  agent_id: agentId,
7560
8610
  prompt_name: promptName,
7561
8611
  status: "failed",
7562
8612
  output: null,
7563
- error: err.message,
8613
+ error: err2.message,
7564
8614
  ran_at: ranAt
7565
8615
  };
7566
8616
  }
@@ -7590,8 +8640,8 @@ ${transcriptText}`,
7590
8640
  const job = this._row(dbRow);
7591
8641
  try {
7592
8642
  if (await this._reconcileStuckJob(job)) acted++;
7593
- } catch (err) {
7594
- if (await this._reconcileError(job, err)) acted++;
8643
+ } catch (err2) {
8644
+ if (await this._reconcileError(job, err2)) acted++;
7595
8645
  }
7596
8646
  }
7597
8647
  for (const dbRow of redo) {
@@ -7599,9 +8649,9 @@ ${transcriptText}`,
7599
8649
  log2(`reconcile: re-running lost post-processing for job ${dbRow.id}`);
7600
8650
  const outputs = await this.runPostProcessing(dbRow.id);
7601
8651
  if (outputs.length > 0) acted++;
7602
- } catch (err) {
8652
+ } catch (err2) {
7603
8653
  log2(
7604
- `post-processing redo failed for job ${dbRow.id}: ${err.message}`
8654
+ `post-processing redo failed for job ${dbRow.id}: ${err2.message}`
7605
8655
  );
7606
8656
  }
7607
8657
  }
@@ -7621,9 +8671,9 @@ ${transcriptText}`,
7621
8671
  * Otherwise apply the 24h give-up (API errors must not defer it forever),
7622
8672
  * and touch the row so it rotates to the back of the sweep window.
7623
8673
  */
7624
- async _reconcileError(job, err) {
7625
- const message = err.message ?? String(err);
7626
- if (err.status === 404) {
8674
+ async _reconcileError(job, err2) {
8675
+ const message = err2.message ?? String(err2);
8676
+ if (err2.status === 404) {
7627
8677
  await this._fail(
7628
8678
  job.id,
7629
8679
  `Recall no longer knows this recording: ${message}`
@@ -7818,15 +8868,15 @@ var request2 = async (path2, init = {}) => {
7818
8868
  let res;
7819
8869
  try {
7820
8870
  res = await fetch(url, init);
7821
- } catch (err) {
8871
+ } catch (err2) {
7822
8872
  throw new TranscriptionServerUnavailable(
7823
- `Unable to reach whisper server at ${url}: ${err.message}`
8873
+ `Unable to reach whisper server at ${url}: ${err2.message}`
7824
8874
  );
7825
8875
  }
7826
8876
  if (res.status === 404) {
7827
- const err = new Error(`whisper server returned 404 for ${path2}`);
7828
- err.code = "JOB_NOT_FOUND";
7829
- throw err;
8877
+ const err2 = new Error(`whisper server returned 404 for ${path2}`);
8878
+ err2.code = "JOB_NOT_FOUND";
8879
+ throw err2;
7830
8880
  }
7831
8881
  if (!res.ok) {
7832
8882
  throw new Error(
@@ -7975,13 +9025,13 @@ var transcriptionService = {
7975
9025
  updatedAt: /* @__PURE__ */ new Date()
7976
9026
  }).returning("*");
7977
9027
  return this._rowFromDb(updated);
7978
- } catch (err) {
9028
+ } catch (err2) {
7979
9029
  const [failed] = await db(TABLE2).where({ id: row.id }).update({
7980
9030
  status: "failed",
7981
- error: err.message,
9031
+ error: err2.message,
7982
9032
  updatedAt: /* @__PURE__ */ new Date()
7983
9033
  }).returning("*");
7984
- log3(`Failed to dispatch job ${row.id}: ${err.message}`);
9034
+ log3(`Failed to dispatch job ${row.id}: ${err2.message}`);
7985
9035
  return this._rowFromDb(failed);
7986
9036
  }
7987
9037
  },
@@ -8000,18 +9050,18 @@ var transcriptionService = {
8000
9050
  try {
8001
9051
  const job = await transcriptionClient.getJob(row.whisper_job_id);
8002
9052
  await this._applyJobUpdate(row, job);
8003
- } catch (err) {
8004
- const code = err.code;
9053
+ } catch (err2) {
9054
+ const code = err2.code;
8005
9055
  if (code === "JOB_NOT_FOUND") {
8006
9056
  await db(TABLE2).where({ id: row.id }).update({
8007
9057
  status: "failed",
8008
9058
  error: "lost on server restart",
8009
9059
  updatedAt: /* @__PURE__ */ new Date()
8010
9060
  });
8011
- } else if (err instanceof TranscriptionServerUnavailable) {
9061
+ } else if (err2 instanceof TranscriptionServerUnavailable) {
8012
9062
  log3(`Whisper server unreachable while polling ${row.id}; will retry`);
8013
9063
  } else {
8014
- log3(`Error polling job ${row.id}: ${err.message}`);
9064
+ log3(`Error polling job ${row.id}: ${err2.message}`);
8015
9065
  }
8016
9066
  }
8017
9067
  }
@@ -8038,8 +9088,8 @@ var transcriptionService = {
8038
9088
  row.post_processing_prompts,
8039
9089
  row.post_processing_outputs
8040
9090
  )) {
8041
- void recallService.runPostProcessing(row.id).catch((err) => {
8042
- log3(`post-processing for upload ${row.id} failed: ${err.message}`);
9091
+ void recallService.runPostProcessing(row.id).catch((err2) => {
9092
+ log3(`post-processing for upload ${row.id} failed: ${err2.message}`);
8043
9093
  });
8044
9094
  }
8045
9095
  return;
@@ -8067,10 +9117,10 @@ var transcriptionService = {
8067
9117
  if (row.whisper_job_id && transcriptionClient.isConfigured()) {
8068
9118
  try {
8069
9119
  await transcriptionClient.cancelJob(row.whisper_job_id);
8070
- } catch (err) {
8071
- const code = err.code;
9120
+ } catch (err2) {
9121
+ const code = err2.code;
8072
9122
  if (code !== "JOB_NOT_FOUND") {
8073
- log3(`Best-effort cancel of whisper job failed: ${err.message}`);
9123
+ log3(`Best-effort cancel of whisper job failed: ${err2.message}`);
8074
9124
  }
8075
9125
  }
8076
9126
  }
@@ -8180,13 +9230,13 @@ var transcriptionService = {
8180
9230
  // upsert when re-saving
8181
9231
  );
8182
9232
  item = result.item;
8183
- } catch (err) {
9233
+ } catch (err2) {
8184
9234
  await db(TABLE2).where({ id }).update({
8185
9235
  speakers: JSON.stringify(input.speakers),
8186
- error: `Failed to save: ${err.message}`,
9236
+ error: `Failed to save: ${err2.message}`,
8187
9237
  updatedAt: /* @__PURE__ */ new Date()
8188
9238
  });
8189
- throw err;
9239
+ throw err2;
8190
9240
  }
8191
9241
  const itemId = item.id ?? row.saved_item_id ?? "";
8192
9242
  const users = input.target_rbac_users ?? row.target_rbac_users ?? [];
@@ -8200,8 +9250,8 @@ var transcriptionService = {
8200
9250
  { users, roles },
8201
9251
  []
8202
9252
  );
8203
- } catch (err) {
8204
- log3(`RBAC update failed for item ${itemId}: ${err.message}`);
9253
+ } catch (err2) {
9254
+ log3(`RBAC update failed for item ${itemId}: ${err2.message}`);
8205
9255
  }
8206
9256
  }
8207
9257
  const projectId = input.project_id ?? row.project_id ?? null;
@@ -8222,8 +9272,8 @@ var transcriptionService = {
8222
9272
  });
8223
9273
  }
8224
9274
  }
8225
- } catch (err) {
8226
- projectWarning = err.message;
9275
+ } catch (err2) {
9276
+ projectWarning = err2.message;
8227
9277
  }
8228
9278
  }
8229
9279
  const nextCorrectedSegments = input.corrected_segments !== void 0 ? input.corrected_segments : row.corrected_segments;
@@ -8264,9 +9314,9 @@ var transcriptionService = {
8264
9314
  const { db } = await postgresClient();
8265
9315
  try {
8266
9316
  await assertOwnsTranscriptionJob(db, user, jobId);
8267
- } catch (err) {
8268
- if (err instanceof TranscriptionJobAccessError) return void 0;
8269
- throw err;
9317
+ } catch (err2) {
9318
+ if (err2 instanceof TranscriptionJobAccessError) return void 0;
9319
+ throw err2;
8270
9320
  }
8271
9321
  const dbRow = await db(TABLE2).where({ id: jobId }).first();
8272
9322
  if (!dbRow) return void 0;
@@ -8397,8 +9447,8 @@ var liveRecordingService = {
8397
9447
  );
8398
9448
  }
8399
9449
  log4(`live recording ${id} stopped \u2192 awaiting_review`);
8400
- void recallService.runPostProcessing(id).catch((err) => {
8401
- log4(`post-processing for job ${id} failed: ${err.message}`);
9450
+ void recallService.runPostProcessing(id).catch((err2) => {
9451
+ log4(`post-processing for job ${id} failed: ${err2.message}`);
8402
9452
  });
8403
9453
  return rowFromDb(updated);
8404
9454
  }
@@ -8528,16 +9578,16 @@ async function insertTriggerWithSecretRetry(insertFn, baseRow) {
8528
9578
  for (let attempt = 0; attempt < 5; attempt++) {
8529
9579
  try {
8530
9580
  return await insertFn({ ...baseRow, secret: generateTriggerSecret() });
8531
- } catch (err) {
8532
- if (err?.code === "23505") continue;
8533
- throw err;
9581
+ } catch (err2) {
9582
+ if (err2?.code === "23505") continue;
9583
+ throw err2;
8534
9584
  }
8535
9585
  }
8536
9586
  throw new Error("Could not generate a unique trigger secret.");
8537
9587
  }
8538
9588
 
8539
9589
  // src/exulu/email-inbound/webhook.ts
8540
- import { randomUUID as randomUUID4 } from "crypto";
9590
+ import { randomUUID as randomUUID5 } from "crypto";
8541
9591
 
8542
9592
  // src/exulu/email-inbound/verify-signature.ts
8543
9593
  import { createHmac, timingSafeEqual } from "crypto";
@@ -8566,10 +9616,10 @@ async function isReplay(redis, signature, timestamp) {
8566
9616
  EX: REPLAY_TTL_SECONDS
8567
9617
  });
8568
9618
  return result === null;
8569
- } catch (err) {
9619
+ } catch (err2) {
8570
9620
  console.error(
8571
9621
  "[EXULU] routine-webhook replay guard: redis unavailable, degrading to window-only",
8572
- err instanceof Error ? err.message : String(err)
9622
+ err2 instanceof Error ? err2.message : String(err2)
8573
9623
  );
8574
9624
  return false;
8575
9625
  }
@@ -8642,8 +9692,8 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
8642
9692
  payloadBytes = rawBody;
8643
9693
  format = "eml";
8644
9694
  }
8645
- } catch (err) {
8646
- res.status(400).json({ detail: err instanceof Error ? err.message : "bad payload" });
9695
+ } catch (err2) {
9696
+ res.status(400).json({ detail: err2 instanceof Error ? err2.message : "bad payload" });
8647
9697
  return;
8648
9698
  }
8649
9699
  void deps.stampLastFiredAt(db, trigger.id).catch(
@@ -8651,7 +9701,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
8651
9701
  );
8652
9702
  try {
8653
9703
  const ext = format === "json" ? "json" : "eml";
8654
- const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${randomUUID4()}.${ext}`, payloadBytes);
9704
+ const s3Key = await deps.putRawPayload(`${EMAIL_INBOUND_S3_PREFIX}${randomUUID5()}.${ext}`, payloadBytes);
8655
9705
  await deps.enqueueIntake({ s3Key, triggerId: trigger.id, format });
8656
9706
  } catch (error) {
8657
9707
  console.error("[EXULU-WEBHOOK] persist/enqueue failed", error);
@@ -8662,7 +9712,7 @@ var createRoutineWebhookHandler = (deps) => async (req, res) => {
8662
9712
  };
8663
9713
 
8664
9714
  // src/graphql/schemas/index.ts
8665
- import { randomUUID as randomUUID5 } from "crypto";
9715
+ import { randomUUID as randomUUID6 } from "crypto";
8666
9716
 
8667
9717
  // src/graphql/resolvers/memory-base-stats.ts
8668
9718
  var num = (v) => typeof v === "number" ? v : Number(v) || 0;
@@ -10156,6 +11206,8 @@ function createSDL(tables, contexts, tools, config, evals) {
10156
11206
  mutationDefs += `
10157
11207
  ${tableNameSingular}GenerateChunks(where: [Filter${tableNameSingularUpperCaseFirst}], limit: Int): ${tableNameSingular}GenerateChunksReturnPayload
10158
11208
  ${tableNameSingular}ExecuteSource(source: ID!, inputs: JSON!): ${tableNameSingular}ExecuteSourceReturnPayload
11209
+ ${tableNameSingular}StartImport(input: StartImportInput!): StartImportPayload
11210
+ ${tableNameSingular}CancelImport(jobResultId: ID!): CancelImportPayload
10159
11211
  ${tableNameSingular}DeleteChunks(where: [Filter${tableNameSingularUpperCaseFirst}], limit: Int): ${tableNameSingular}DeleteChunksReturnPayload
10160
11212
  ${tableNameSingular}BackfillEntities(onlyStale: Boolean, limit: Int): ${tableNameSingular}EntityBackfillPayload
10161
11213
  ${tableNameSingular}PurgeEntityType(type: String!): ${tableNameSingular}EntityPurgePayload
@@ -10194,6 +11246,40 @@ function createSDL(tables, contexts, tools, config, evals) {
10194
11246
  items: [String!]
10195
11247
  }
10196
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
+
10197
11283
  type ${tableNameSingular}ProcessItemFieldReturnPayload {
10198
11284
  message: String!
10199
11285
  results: [String]
@@ -10728,8 +11814,8 @@ type EmbeddingModelOption {
10728
11814
  maxChunkSize: m.maxChunkSize,
10729
11815
  maxBatchSize: m.maxBatchSize
10730
11816
  }));
10731
- } catch (err) {
10732
- console.warn("[EXULU] Could not read embedding models:", err.message);
11817
+ } catch (err2) {
11818
+ console.warn("[EXULU] Could not read embedding models:", err2.message);
10733
11819
  return [];
10734
11820
  }
10735
11821
  };
@@ -10922,9 +12008,9 @@ type EmbeddingModelOption {
10922
12008
  throw new Error("You don't have access to this workflow template.");
10923
12009
  }
10924
12010
  const hasWorkflowsWriteRole = user?.super_admin || user?.role?.workflows === "write";
10925
- const canWrite = hasWorkflowsWriteRole && await checkRecordAccess(workflowTemplate, "write", user);
12011
+ const canWrite2 = hasWorkflowsWriteRole && await checkRecordAccess(workflowTemplate, "write", user);
10926
12012
  const rows = await db.from("workflow_triggers").where({ workflow: args.workflow }).orderBy("createdAt", "asc");
10927
- return rows.map((r) => toWorkflowTriggerPayload(r, { canWrite }));
12013
+ return rows.map((r) => toWorkflowTriggerPayload(r, { canWrite: canWrite2 }));
10928
12014
  };
10929
12015
  resolvers.Mutation["upsertWorkflowEmailTrigger"] = async (_, args, context) => {
10930
12016
  if (!args.workflow) {
@@ -11005,9 +12091,9 @@ type EmbeddingModelOption {
11005
12091
  const rows = await db.from("workflow_triggers").where({ id: args.id }).update({ secret: generateTriggerSecret(), updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).returning("*");
11006
12092
  updated = rows[0];
11007
12093
  break;
11008
- } catch (err) {
11009
- if (err?.code === "23505") continue;
11010
- throw err;
12094
+ } catch (err2) {
12095
+ if (err2?.code === "23505") continue;
12096
+ throw err2;
11011
12097
  }
11012
12098
  }
11013
12099
  if (!updated) throw new Error("Could not generate a unique trigger secret.");
@@ -11053,13 +12139,13 @@ type EmbeddingModelOption {
11053
12139
  bytes = Buffer.from(args.payload, "latin1");
11054
12140
  format = "eml";
11055
12141
  }
11056
- } catch (err) {
11057
- return { outcome: "error", error: err instanceof Error ? err.message : "bad payload" };
12142
+ } catch (err2) {
12143
+ return { outcome: "error", error: err2 instanceof Error ? err2.message : "bad payload" };
11058
12144
  }
11059
12145
  const ext = format === "json" ? "json" : "eml";
11060
12146
  const fullKey = await uploadFile(
11061
12147
  bytes,
11062
- `${EMAIL_INBOUND_S3_PREFIX}${randomUUID5()}.${ext}`,
12148
+ `${EMAIL_INBOUND_S3_PREFIX}${randomUUID6()}.${ext}`,
11063
12149
  config,
11064
12150
  { contentType: "application/octet-stream" },
11065
12151
  void 0,
@@ -11244,11 +12330,11 @@ type EmbeddingModelOption {
11244
12330
  user
11245
12331
  );
11246
12332
  return new Map(rows.map((row) => [row.id, row]));
11247
- } catch (err) {
11248
- if (err instanceof Error && err.message.startsWith("Access control error")) {
12333
+ } catch (err2) {
12334
+ if (err2 instanceof Error && err2.message.startsWith("Access control error")) {
11249
12335
  return /* @__PURE__ */ new Map();
11250
12336
  }
11251
- throw err;
12337
+ throw err2;
11252
12338
  }
11253
12339
  };
11254
12340
  const loadRoutineRunForWrite = async (db, user, id) => {
@@ -11762,8 +12848,8 @@ type EmbeddingModelOption {
11762
12848
  stuck_count: num7(stuckRow?.c),
11763
12849
  stale_count: num7(staleRow?.c)
11764
12850
  };
11765
- } catch (err) {
11766
- console.error("[EXULU] computeContextAggregates failed for", contextId, err);
12851
+ } catch (err2) {
12852
+ console.error("[EXULU] computeContextAggregates failed for", contextId, err2);
11767
12853
  return empty;
11768
12854
  }
11769
12855
  };
@@ -12303,9 +13389,9 @@ async function extractZipToPrefix(bytes, prefix, config) {
12303
13389
  let zip;
12304
13390
  try {
12305
13391
  zip = await JSZip.loadAsync(bytes);
12306
- } catch (err) {
13392
+ } catch (err2) {
12307
13393
  throw new BundleValidationError(
12308
- `Could not parse zip file: ${err?.message ?? "unknown error"}`
13394
+ `Could not parse zip file: ${err2?.message ?? "unknown error"}`
12309
13395
  );
12310
13396
  }
12311
13397
  const entries = [];
@@ -12406,13 +13492,13 @@ import bodyParser from "body-parser";
12406
13492
  import "crypto-js";
12407
13493
  import "openai";
12408
13494
  import fs2 from "fs";
12409
- import { randomUUID as randomUUID8 } from "crypto";
13495
+ import { randomUUID as randomUUID9 } from "crypto";
12410
13496
  import "@opentelemetry/api";
12411
13497
  import JSZip3 from "jszip";
12412
13498
 
12413
13499
  // src/skills/bundled.ts
12414
13500
  import JSZip2 from "jszip";
12415
- import { createHash as createHash2, randomUUID as randomUUID6 } from "crypto";
13501
+ import { createHash as createHash2, randomUUID as randomUUID7 } from "crypto";
12416
13502
 
12417
13503
  // src/skills/bundled.generated.ts
12418
13504
  var BUNDLED_SKILLS = [
@@ -12495,7 +13581,7 @@ async function seedBundledSkills({
12495
13581
  log6(`"${skill.name}" updated to v${nextVersion}`);
12496
13582
  continue;
12497
13583
  }
12498
- const skillId = randomUUID6();
13584
+ const skillId = randomUUID7();
12499
13585
  await extractBundleToVersion({ bytes: await bundledSkillZip(skill), skillId, version: 1, config });
12500
13586
  await db("skills").insert({
12501
13587
  id: skillId,
@@ -12593,7 +13679,7 @@ ${SUGGESTIONS_SYSTEM_PROMPT}` : SUGGESTIONS_SYSTEM_PROMPT;
12593
13679
  };
12594
13680
 
12595
13681
  // src/exulu/compact-session.ts
12596
- import { randomUUID as randomUUID7 } from "crypto";
13682
+ import { randomUUID as randomUUID8 } from "crypto";
12597
13683
  import { generateText as generateText6, validateUIMessages as validateUIMessages2 } from "ai";
12598
13684
  var CompactionInsufficientError = class extends Error {
12599
13685
  constructor(reason) {
@@ -12696,7 +13782,7 @@ Focus especially on: ${steer.trim()}` : SUMMARY_SYSTEM;
12696
13782
  ...steer?.trim() ? { steer: steer.trim() } : {}
12697
13783
  };
12698
13784
  const checkpoint = {
12699
- id: `compaction_${randomUUID7()}`,
13785
+ id: `compaction_${randomUUID8()}`,
12700
13786
  role: "user",
12701
13787
  parts: [{ type: "text", text: `[Conversation summary \u2014 earlier messages were compacted]
12702
13788
 
@@ -12709,19 +13795,19 @@ ${summary}` }],
12709
13795
 
12710
13796
  // src/exulu/request-error.ts
12711
13797
  import { TypeValidationError } from "ai";
12712
- function describeRequestError(err) {
12713
- if (err instanceof ContextCompactionRequiredError) {
12714
- return { status: 413, body: err.message };
13798
+ function describeRequestError(err2) {
13799
+ if (err2 instanceof ContextCompactionRequiredError) {
13800
+ return { status: 413, body: err2.message };
12715
13801
  }
12716
- if (TypeValidationError.isInstance(err)) {
12717
- const cause = err.cause;
13802
+ if (TypeValidationError.isInstance(err2)) {
13803
+ const cause = err2.cause;
12718
13804
  const detail = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
12719
13805
  return {
12720
13806
  status: 422,
12721
13807
  body: `The stored conversation could not be loaded: ${detail.slice(0, 400) || "type validation failed"}`
12722
13808
  };
12723
13809
  }
12724
- return { status: 500, body: err instanceof Error ? err.message : String(err) };
13810
+ return { status: 500, body: err2 instanceof Error ? err2.message : String(err2) };
12725
13811
  }
12726
13812
 
12727
13813
  // src/exulu/memory/recalled-metadata.ts
@@ -13159,12 +14245,12 @@ function registerLiveRecordingChunkRoute(app, deps) {
13159
14245
  const db = await deps.getDb();
13160
14246
  try {
13161
14247
  await deps.assertOwns(db, user, jobId);
13162
- } catch (err) {
13163
- if (err instanceof TranscriptionJobAccessError) {
13164
- res.status(err.code).json({ detail: err.message });
14248
+ } catch (err2) {
14249
+ if (err2 instanceof TranscriptionJobAccessError) {
14250
+ res.status(err2.code).json({ detail: err2.message });
13165
14251
  return;
13166
14252
  }
13167
- throw err;
14253
+ throw err2;
13168
14254
  }
13169
14255
  const row = await db.from("transcription_jobs").select(["status", "raw_segments", "project_id"]).where({ id: jobId }).first();
13170
14256
  if (!row) {
@@ -13219,14 +14305,14 @@ function registerLiveRecordingChunkRoute(app, deps) {
13219
14305
  priorText: LIVE_PRIOR_TEXT_ENABLED ? priorTextFrom(row.raw_segments) : void 0,
13220
14306
  tags
13221
14307
  }));
13222
- } catch (err) {
13223
- if (err instanceof TranscriptionError) {
13224
- const code = err.upstreamStatus >= 500 ? 502 : err.upstreamStatus;
13225
- res.status(code).json({ detail: err.message });
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 });
13226
14312
  return;
13227
14313
  }
13228
- console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`, err);
13229
- res.status(500).json({ detail: err instanceof Error ? err.message : "Transcription failed." });
14314
+ console.error(`[EXULU] ${CHUNK_ROUTE_PATH} transcription failed`, err2);
14315
+ res.status(500).json({ detail: err2 instanceof Error ? err2.message : "Transcription failed." });
13230
14316
  return;
13231
14317
  }
13232
14318
  }
@@ -13316,7 +14402,7 @@ var formatSrtTime = (seconds) => {
13316
14402
  const ms = String(totalMs % 1e3).padStart(3, "0");
13317
14403
  return `${formatCsvTime(wholeSeconds)},${ms}`;
13318
14404
  };
13319
- var csvField = (value, isTextField = false) => {
14405
+ var csvField2 = (value, isTextField = false) => {
13320
14406
  const needsQuote = /["\n\r,]/.test(value) || isTextField;
13321
14407
  return needsQuote ? `"${value.replace(/"/g, '""')}"` : value;
13322
14408
  };
@@ -13330,7 +14416,7 @@ function buildTranscriptCsv(item, options) {
13330
14416
  const label = resolveLabel(item, segment.speaker, options.speakers);
13331
14417
  const text = (segment.text ?? "").trim();
13332
14418
  const cells = options.timestamps ? [formatCsvTime(segment.start), formatCsvTime(segment.end), label, text] : [label, text];
13333
- return cells.map((value, i) => csvField(value, i === cells.length - 1)).join(",");
14419
+ return cells.map((value, i) => csvField2(value, i === cells.length - 1)).join(",");
13334
14420
  });
13335
14421
  return [header2, ...rows].join("\n") + "\n";
13336
14422
  }
@@ -13390,8 +14476,8 @@ function registerTranscriptExportRoute(app, deps) {
13390
14476
  `attachment; filename="${encodeURIComponent(filename)}"`
13391
14477
  );
13392
14478
  res.send(body);
13393
- } catch (err) {
13394
- console.error("[EXULU] transcript export failed", err);
14479
+ } catch (err2) {
14480
+ console.error("[EXULU] transcript export failed", err2);
13395
14481
  res.status(500).json({ detail: "Export failed." });
13396
14482
  }
13397
14483
  });
@@ -13441,8 +14527,8 @@ function registerTranscriptExportRoute(app, deps) {
13441
14527
  `attachment; filename="${encodeURIComponent(filename)}"`
13442
14528
  );
13443
14529
  res.send(body);
13444
- } catch (err) {
13445
- console.error("[EXULU] transcript job export failed", err);
14530
+ } catch (err2) {
14531
+ console.error("[EXULU] transcript job export failed", err2);
13446
14532
  res.status(500).json({ detail: "Export failed." });
13447
14533
  }
13448
14534
  });
@@ -13509,7 +14595,7 @@ function pipelineConfigFor(agent) {
13509
14595
  // ee/claim-check/routes.ts
13510
14596
  var CLAIM_CHECK_PATH = "/claims/check";
13511
14597
  var CLAIM_CHECK_SESSION_PATH = "/claims/check/:session";
13512
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
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;
13513
14599
  function hasNumericUserId(user) {
13514
14600
  return Boolean(user?.id) && Number.isFinite(Number(user?.id));
13515
14601
  }
@@ -13670,9 +14756,9 @@ function registerClaimCheckRoutes(app, deps) {
13670
14756
  }
13671
14757
  try {
13672
14758
  agent = await deps.getAgent(body.agent);
13673
- } catch (err) {
14759
+ } catch (err2) {
13674
14760
  console.warn(
13675
- `[EXULU] claim check: agent lookup for "${body.agent}" failed: ${err instanceof Error ? err.message : String(err)}`
14761
+ `[EXULU] claim check: agent lookup for "${body.agent}" failed: ${err2 instanceof Error ? err2.message : String(err2)}`
13676
14762
  );
13677
14763
  }
13678
14764
  if (!agent) {
@@ -13697,7 +14783,7 @@ function registerClaimCheckRoutes(app, deps) {
13697
14783
  });
13698
14784
  return;
13699
14785
  }
13700
- if (deps.findClaimCheck && body.session && body.messageId && UUID_RE.test(body.session)) {
14786
+ if (deps.findClaimCheck && body.session && body.messageId && UUID_RE2.test(body.session)) {
13701
14787
  try {
13702
14788
  const stored = await deps.findClaimCheck({
13703
14789
  session: body.session,
@@ -13708,10 +14794,10 @@ function registerClaimCheckRoutes(app, deps) {
13708
14794
  res.status(200).json(stored);
13709
14795
  return;
13710
14796
  }
13711
- } catch (err) {
14797
+ } catch (err2) {
13712
14798
  console.warn(
13713
14799
  "[EXULU claim-check] could not read the stored check for this message; running the check.",
13714
- err
14800
+ err2
13715
14801
  );
13716
14802
  }
13717
14803
  }
@@ -13737,10 +14823,10 @@ function registerClaimCheckRoutes(app, deps) {
13737
14823
  model = resolved.languageModel;
13738
14824
  break;
13739
14825
  }
13740
- } catch (err) {
13741
- lastError = err;
14826
+ } catch (err2) {
14827
+ lastError = err2;
13742
14828
  console.warn(
13743
- `[EXULU] claim check: model "${modelId}" failed to resolve: ${err instanceof Error ? err.message : String(err)}`
14829
+ `[EXULU] claim check: model "${modelId}" failed to resolve: ${err2 instanceof Error ? err2.message : String(err2)}`
13744
14830
  );
13745
14831
  }
13746
14832
  }
@@ -13804,21 +14890,21 @@ function registerClaimCheckRoutes(app, deps) {
13804
14890
  ]);
13805
14891
  completedResult = result;
13806
14892
  res.status(200).json(result);
13807
- } catch (err) {
13808
- if (err instanceof ClaimCheckTimeoutError) {
14893
+ } catch (err2) {
14894
+ if (err2 instanceof ClaimCheckTimeoutError) {
13809
14895
  console.warn(`[EXULU] claim check exceeded the ${timeoutMs} ms deadline.`);
13810
14896
  res.status(504).json({
13811
14897
  detail: `The claim check did not finish within ${timeoutMs / 1e3} seconds and was cancelled.`
13812
14898
  });
13813
14899
  } else {
13814
- console.error("[EXULU] claim check failed.", err);
14900
+ console.error("[EXULU] claim check failed.", err2);
13815
14901
  res.status(500).json({ detail: "The claim check failed." });
13816
14902
  }
13817
14903
  } finally {
13818
14904
  if (deadline) clearTimeout(deadline);
13819
14905
  deps.limiter.release();
13820
14906
  }
13821
- if (completedResult && body.session && body.messageId && UUID_RE.test(body.session)) {
14907
+ if (completedResult && body.session && body.messageId && UUID_RE2.test(body.session)) {
13822
14908
  if (!deps.saveClaimCheck) {
13823
14909
  console.error(
13824
14910
  "[EXULU claim-check] saveClaimCheck is not wired; this check cannot survive a reload."
@@ -13831,8 +14917,8 @@ function registerClaimCheckRoutes(app, deps) {
13831
14917
  userId: Number(user.id),
13832
14918
  result: completedResult
13833
14919
  });
13834
- } catch (err) {
13835
- console.warn("[EXULU claim-check] could not store the check for this message.", err);
14920
+ } catch (err2) {
14921
+ console.warn("[EXULU claim-check] could not store the check for this message.", err2);
13836
14922
  }
13837
14923
  }
13838
14924
  }
@@ -13843,7 +14929,7 @@ function registerClaimCheckRoutes(app, deps) {
13843
14929
  return;
13844
14930
  }
13845
14931
  const session = req.params.session ?? "";
13846
- if (!UUID_RE.test(session)) {
14932
+ if (!UUID_RE2.test(session)) {
13847
14933
  res.status(400).json({ detail: "session must be a uuid." });
13848
14934
  return;
13849
14935
  }
@@ -13860,8 +14946,8 @@ function registerClaimCheckRoutes(app, deps) {
13860
14946
  try {
13861
14947
  const checks = await deps.listClaimChecks({ session, userId: Number(auth.user.id) });
13862
14948
  res.status(200).json({ checks });
13863
- } catch (err) {
13864
- console.error("[EXULU claim-check] could not read stored checks.", err);
14949
+ } catch (err2) {
14950
+ console.error("[EXULU claim-check] could not read stored checks.", err2);
13865
14951
  res.status(500).json({ detail: "Could not read stored checks." });
13866
14952
  }
13867
14953
  });
@@ -15170,9 +16256,9 @@ async function runClaimCheck(args) {
15170
16256
  limits: { truncated: skipped.length > 0 || truncation.sources > 0, sentencesSkipped: skipped.length },
15171
16257
  notes: state.notes
15172
16258
  };
15173
- } catch (err) {
16259
+ } catch (err2) {
15174
16260
  timings.totalMs = Date.now() - startedAt;
15175
- const message = err instanceof Error ? err.message : String(err);
16261
+ const message = err2 instanceof Error ? err2.message : String(err2);
15176
16262
  return {
15177
16263
  status: "partial",
15178
16264
  score: scoreClaims([], options.thresholds),
@@ -15231,8 +16317,8 @@ function makeSecondChance(args) {
15231
16317
  }))
15232
16318
  );
15233
16319
  return selectEvidence([claimText], index, MAX_SNIPPETS_PER_CLAIM);
15234
- } catch (err) {
15235
- console.warn("[EXULU claim-check] second-chance retrieval failed:", err);
16320
+ } catch (err2) {
16321
+ console.warn("[EXULU claim-check] second-chance retrieval failed:", err2);
15236
16322
  return [];
15237
16323
  }
15238
16324
  };
@@ -15278,8 +16364,8 @@ async function testSource(source, deps) {
15278
16364
  try {
15279
16365
  await entry.ping();
15280
16366
  return { ok: true };
15281
- } catch (err) {
15282
- return { ok: false, reason: "unreachable", message: err.message };
16367
+ } catch (err2) {
16368
+ return { ok: false, reason: "unreachable", message: err2.message };
15283
16369
  }
15284
16370
  }
15285
16371
 
@@ -16323,6 +17409,7 @@ var {
16323
17409
  rbacSchema,
16324
17410
  promptLibrarySchema,
16325
17411
  contextPresetsSchema,
17412
+ contextFoldersSchema,
16326
17413
  teamsSchema,
16327
17414
  entityTypeSettingsSchema,
16328
17415
  promptFavoritesSchema,
@@ -16385,6 +17472,12 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
16385
17472
  jobResultsSchema(),
16386
17473
  promptLibrarySchema(),
16387
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(),
16388
17481
  teamsSchema(),
16389
17482
  entityTypeSettingsSchema(),
16390
17483
  promptFavoritesSchema(),
@@ -16537,8 +17630,8 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
16537
17630
  }
16538
17631
  const event = req.body;
16539
17632
  res.status(200).json({ ok: true });
16540
- void recallService.handleWebhookEvent(event).catch((err) => {
16541
- console.error("[EXULU-RECALL] webhook processing failed", err);
17633
+ void recallService.handleWebhookEvent(event).catch((err2) => {
17634
+ console.error("[EXULU-RECALL] webhook processing failed", err2);
16542
17635
  });
16543
17636
  });
16544
17637
  const routineWebhookHandler = createRoutineWebhookHandler({
@@ -16569,7 +17662,7 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
16569
17662
  inputs: payload
16570
17663
  };
16571
17664
  await queue.queue.add("email-intake", jobData, {
16572
- jobId: randomUUID8(),
17665
+ jobId: randomUUID9(),
16573
17666
  attempts: 3,
16574
17667
  removeOnComplete: 5e3,
16575
17668
  removeOnFail: 1e4,
@@ -16765,13 +17858,13 @@ var createExpressRoutes = async (app, tools, contexts, config, evals, tracer) =>
16765
17858
  user,
16766
17859
  agent
16767
17860
  });
16768
- } catch (err) {
16769
- if (err instanceof ResolveModelError) {
16770
- const status = err.code === "MODEL_FORBIDDEN" ? 403 : 400;
16771
- res.status(status).json({ message: err.message, code: err.code });
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 });
16772
17865
  return;
16773
17866
  }
16774
- throw err;
17867
+ throw err2;
16775
17868
  }
16776
17869
  const resolvedLanguageModel = resolved.languageModel;
16777
17870
  const resolvedModelId = resolved.model.id;
@@ -16822,13 +17915,13 @@ ${customInstructions}` : agent.instructions,
16822
17915
  contextWindow,
16823
17916
  disabledTools
16824
17917
  });
16825
- } catch (err) {
17918
+ } catch (err2) {
16826
17919
  if (headers.session) clearStreamActive(headers.session);
16827
17920
  console.error(
16828
17921
  "[EXULU] chat request failed before streaming.",
16829
- err instanceof Error ? err.message.slice(0, 500) : err
17922
+ err2 instanceof Error ? err2.message.slice(0, 500) : err2
16830
17923
  );
16831
- const { status, body } = describeRequestError(err);
17924
+ const { status, body } = describeRequestError(err2);
16832
17925
  res.status(status).send(body);
16833
17926
  return;
16834
17927
  }
@@ -16940,7 +18033,7 @@ ${customInstructions}` : agent.instructions,
16940
18033
  contextId: agent.memory,
16941
18034
  agentId: agent.id,
16942
18035
  session: headers.session ?? null,
16943
- messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID8(),
18036
+ messageId: responseMessage?.id ?? messages[messages.length - 1]?.id ?? randomUUID9(),
16944
18037
  userId: user?.id ?? null
16945
18038
  });
16946
18039
  }
@@ -17019,12 +18112,12 @@ ${customInstructions}` : agent.instructions,
17019
18112
  onTokenUsage: async ({ inputTokens, outputTokens }) => {
17020
18113
  }
17021
18114
  });
17022
- } catch (err) {
18115
+ } catch (err2) {
17023
18116
  console.error(
17024
18117
  "[EXULU] run request failed.",
17025
- err instanceof Error ? err.message.slice(0, 500) : err
18118
+ err2 instanceof Error ? err2.message.slice(0, 500) : err2
17026
18119
  );
17027
- const { status, body } = describeRequestError(err);
18120
+ const { status, body } = describeRequestError(err2);
17028
18121
  res.status(status).send(body);
17029
18122
  return;
17030
18123
  }
@@ -17091,13 +18184,13 @@ ${customInstructions}` : agent.instructions,
17091
18184
  let resolved;
17092
18185
  try {
17093
18186
  resolved = await resolveModel({ modelId, user, agent });
17094
- } catch (err) {
17095
- if (err instanceof ResolveModelError) {
17096
- const status = err.code === "MODEL_FORBIDDEN" ? 403 : 400;
17097
- res.status(status).json({ message: err.message, code: err.code });
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 });
17098
18191
  return;
17099
18192
  }
17100
- throw err;
18193
+ throw err2;
17101
18194
  }
17102
18195
  const contextWindow = await resolveContextWindow({
17103
18196
  modelId: resolved.model.id
@@ -17113,13 +18206,13 @@ ${customInstructions}` : agent.instructions,
17113
18206
  modelId: resolved.model.id
17114
18207
  });
17115
18208
  res.json(result);
17116
- } catch (err) {
17117
- if (err instanceof CompactionInsufficientError) {
17118
- res.status(422).send(err.message);
18209
+ } catch (err2) {
18210
+ if (err2 instanceof CompactionInsufficientError) {
18211
+ res.status(422).send(err2.message);
17119
18212
  return;
17120
18213
  }
17121
- console.error("[EXULU] compactSession failed.", err);
17122
- res.status(500).json({ message: err instanceof Error ? err.message : "Compaction failed." });
18214
+ console.error("[EXULU] compactSession failed.", err2);
18215
+ res.status(500).json({ message: err2 instanceof Error ? err2.message : "Compaction failed." });
17123
18216
  }
17124
18217
  });
17125
18218
  };
@@ -17184,13 +18277,13 @@ ${customInstructions}` : agent.instructions,
17184
18277
  user,
17185
18278
  agent
17186
18279
  });
17187
- } catch (err) {
17188
- if (err instanceof ResolveModelError) {
17189
- const status = err.code === "MODEL_FORBIDDEN" ? 403 : 400;
17190
- res.status(status).json({ detail: err.message, code: err.code });
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 });
17191
18284
  return;
17192
18285
  }
17193
- throw err;
18286
+ throw err2;
17194
18287
  }
17195
18288
  try {
17196
18289
  const { suggestions, usage } = await generateSuggestions({
@@ -17230,10 +18323,10 @@ ${customInstructions}` : agent.instructions,
17230
18323
  ] : []
17231
18324
  ]);
17232
18325
  res.status(200).json({ suggestions });
17233
- } catch (err) {
17234
- console.error("[EXULU] suggestions generation failed", err);
18326
+ } catch (err2) {
18327
+ console.error("[EXULU] suggestions generation failed", err2);
17235
18328
  res.status(500).json({
17236
- detail: err instanceof Error ? err.message : "Failed to generate suggestions."
18329
+ detail: err2 instanceof Error ? err2.message : "Failed to generate suggestions."
17237
18330
  });
17238
18331
  }
17239
18332
  });
@@ -17243,14 +18336,14 @@ ${customInstructions}` : agent.instructions,
17243
18336
  limits: { fileSize: MAX_TRANSCRIBE_BYTES }
17244
18337
  });
17245
18338
  const transcribeUploadMiddleware = (req, res, next) => {
17246
- transcribeUpload.single("file")(req, res, (err) => {
17247
- if (!err) return next();
17248
- const code = err?.code;
18339
+ transcribeUpload.single("file")(req, res, (err2) => {
18340
+ if (!err2) return next();
18341
+ const code = err2?.code;
17249
18342
  if (code === "LIMIT_FILE_SIZE") {
17250
18343
  res.status(413).json({ detail: "Recording too large. Please record a shorter clip." });
17251
18344
  return;
17252
18345
  }
17253
- res.status(400).json({ detail: err instanceof Error ? err.message : "Upload failed." });
18346
+ res.status(400).json({ detail: err2 instanceof Error ? err2.message : "Upload failed." });
17254
18347
  });
17255
18348
  };
17256
18349
  app.post(
@@ -17294,15 +18387,15 @@ ${customInstructions}` : agent.instructions,
17294
18387
  try {
17295
18388
  const { text } = await transcribeAudio({ file, language });
17296
18389
  res.status(200).json({ text });
17297
- } catch (err) {
17298
- if (err instanceof TranscriptionError) {
17299
- const code = err.upstreamStatus >= 500 ? 502 : err.upstreamStatus;
17300
- res.status(code).json({ detail: err.message });
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 });
17301
18394
  return;
17302
18395
  }
17303
- console.error("[EXULU] /transcribe failed", err);
18396
+ console.error("[EXULU] /transcribe failed", err2);
17304
18397
  res.status(500).json({
17305
- detail: err instanceof Error ? err.message : "Transcription failed."
18398
+ detail: err2 instanceof Error ? err2.message : "Transcription failed."
17306
18399
  });
17307
18400
  }
17308
18401
  }
@@ -17381,8 +18474,8 @@ ${customInstructions}` : agent.instructions,
17381
18474
  const response = await fetch(url, {
17382
18475
  headers: { Authorization: recallApiKey(), accept: "application/json" },
17383
18476
  signal: AbortSignal.timeout(1e4)
17384
- }).catch((err) => {
17385
- throw new Error(`Unable to reach the Recall API: ${err.message}`);
18477
+ }).catch((err2) => {
18478
+ throw new Error(`Unable to reach the Recall API: ${err2.message}`);
17386
18479
  });
17387
18480
  if (!response.ok) {
17388
18481
  const body = await response.text();
@@ -17406,8 +18499,8 @@ ${customInstructions}` : agent.instructions,
17406
18499
  }
17407
18500
  });
17408
18501
  res.status(200).json(result);
17409
- } catch (err) {
17410
- res.status(400).json({ detail: err.message });
18502
+ } catch (err2) {
18503
+ res.status(400).json({ detail: err2.message });
17411
18504
  }
17412
18505
  });
17413
18506
  const MAX_TTS_INPUT_CHARS = 4e3;
@@ -17455,15 +18548,15 @@ ${customInstructions}` : agent.instructions,
17455
18548
  res.setHeader("Content-Length", String(audio.length));
17456
18549
  res.setHeader("Cache-Control", "no-store");
17457
18550
  res.send(audio);
17458
- } catch (err) {
17459
- if (err instanceof SpeechError) {
17460
- const code = err.upstreamStatus >= 500 ? 502 : err.upstreamStatus;
17461
- res.status(code).json({ detail: err.message });
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 });
17462
18555
  return;
17463
18556
  }
17464
- console.error("[EXULU] /speech failed", err);
18557
+ console.error("[EXULU] /speech failed", err2);
17465
18558
  res.status(500).json({
17466
- detail: err instanceof Error ? err.message : "Speech generation failed."
18559
+ detail: err2 instanceof Error ? err2.message : "Speech generation failed."
17467
18560
  });
17468
18561
  }
17469
18562
  }
@@ -17474,10 +18567,10 @@ ${customInstructions}` : agent.instructions,
17474
18567
  const configPath = process.env.LITELLM_CONFIG_PATH ?? resolvePath(process.cwd(), "./config.litellm.yaml");
17475
18568
  const models = parseImageGenerationModels(configPath);
17476
18569
  return new Map(models.map((m) => [m.model_name, m]));
17477
- } catch (err) {
18570
+ } catch (err2) {
17478
18571
  console.error(
17479
18572
  "[EXULU] Skipping /images/* routes due to config.litellm.yaml error:",
17480
- err.message
18573
+ err2.message
17481
18574
  );
17482
18575
  return /* @__PURE__ */ new Map();
17483
18576
  }
@@ -17589,7 +18682,7 @@ ${customInstructions}` : agent.instructions,
17589
18682
  const keys = [];
17590
18683
  const revisedPrompts = [];
17591
18684
  for (const img of images) {
17592
- const filename = `${randomUUID8()}.${img.extension}`;
18685
+ const filename = `${randomUUID9()}.${img.extension}`;
17593
18686
  const key = `sessions/${sessionId}/images/${toolCallId}/${filename}`;
17594
18687
  const fullKey = await uploadFile(
17595
18688
  img.buffer,
@@ -17679,16 +18772,16 @@ ${style.markdown}` : params.prompt;
17679
18772
  revisedPrompt: revisedPrompts[i]
17680
18773
  }))
17681
18774
  });
17682
- } catch (err) {
18775
+ } catch (err2) {
17683
18776
  if (abortController.signal.aborted) return;
17684
- if (err instanceof ImageGenerationError) {
17685
- const code = err.upstreamStatus >= 500 ? 502 : err.upstreamStatus;
17686
- res.status(code).json({ detail: err.message });
18777
+ if (err2 instanceof ImageGenerationError) {
18778
+ const code = err2.upstreamStatus >= 500 ? 502 : err2.upstreamStatus;
18779
+ res.status(code).json({ detail: err2.message });
17687
18780
  return;
17688
18781
  }
17689
- console.error("[EXULU] /images/generate failed", err);
18782
+ console.error("[EXULU] /images/generate failed", err2);
17690
18783
  res.status(500).json({
17691
- detail: err instanceof Error ? err.message : "Image generation failed."
18784
+ detail: err2 instanceof Error ? err2.message : "Image generation failed."
17692
18785
  });
17693
18786
  }
17694
18787
  });
@@ -17796,16 +18889,16 @@ ${style.markdown}` : params.prompt;
17796
18889
  revisedPrompt: revisedPrompts[i]
17797
18890
  }))
17798
18891
  });
17799
- } catch (err) {
18892
+ } catch (err2) {
17800
18893
  if (abortController.signal.aborted) return;
17801
- if (err instanceof ImageGenerationError) {
17802
- const code = err.upstreamStatus >= 500 ? 502 : err.upstreamStatus;
17803
- res.status(code).json({ detail: err.message });
18894
+ if (err2 instanceof ImageGenerationError) {
18895
+ const code = err2.upstreamStatus >= 500 ? 502 : err2.upstreamStatus;
18896
+ res.status(code).json({ detail: err2.message });
17804
18897
  return;
17805
18898
  }
17806
- console.error("[EXULU] /images/edit failed", err);
18899
+ console.error("[EXULU] /images/edit failed", err2);
17807
18900
  res.status(500).json({
17808
- detail: err instanceof Error ? err.message : "Image edit failed."
18901
+ detail: err2 instanceof Error ? err2.message : "Image edit failed."
17809
18902
  });
17810
18903
  }
17811
18904
  });
@@ -17877,7 +18970,7 @@ ${style.markdown}` : params.prompt;
17877
18970
  (d) => `- ${d.presignedUrl} (prompt: "${d.prompt}", model: ${d.model}${d.styleName ? `, style: ${d.styleName}` : ""})`
17878
18971
  );
17879
18972
  const messageText = "The user generated and selected the following image(s) in this chat:\n" + lines.join("\n");
17880
- const messageId = randomUUID8();
18973
+ const messageId = randomUUID9();
17881
18974
  const uiMessage = {
17882
18975
  id: messageId,
17883
18976
  role: "system",
@@ -18010,11 +19103,11 @@ ${style.markdown}` : params.prompt;
18010
19103
  reader.releaseLock();
18011
19104
  }
18012
19105
  res.end();
18013
- } catch (err) {
18014
- console.error("[EXULU] LiteLLM UI proxy failed", err);
19106
+ } catch (err2) {
19107
+ console.error("[EXULU] LiteLLM UI proxy failed", err2);
18015
19108
  if (!res.headersSent) {
18016
19109
  res.status(502).json({
18017
- detail: err instanceof Error ? err.message : "LiteLLM UI proxy failed."
19110
+ detail: err2 instanceof Error ? err2.message : "LiteLLM UI proxy failed."
18018
19111
  });
18019
19112
  } else {
18020
19113
  res.end();
@@ -18139,11 +19232,11 @@ ${style.markdown}` : params.prompt;
18139
19232
  reader.releaseLock();
18140
19233
  }
18141
19234
  res.end();
18142
- } catch (err) {
18143
- console.error("[EXULU] /litellm proxy failed", err);
19235
+ } catch (err2) {
19236
+ console.error("[EXULU] /litellm proxy failed", err2);
18144
19237
  if (!res.headersSent) {
18145
19238
  res.status(502).json({
18146
- detail: err instanceof Error ? err.message : "LiteLLM proxy failed."
19239
+ detail: err2 instanceof Error ? err2.message : "LiteLLM proxy failed."
18147
19240
  });
18148
19241
  } else {
18149
19242
  res.end();
@@ -18200,8 +19293,8 @@ ${style.markdown}` : params.prompt;
18200
19293
  `attachment; filename="${encodeURIComponent(filename)}"`
18201
19294
  );
18202
19295
  res.send(bytes);
18203
- } catch (err) {
18204
- console.error("[EXULU] markdown export failed", err);
19296
+ } catch (err2) {
19297
+ console.error("[EXULU] markdown export failed", err2);
18205
19298
  res.status(500).json({ detail: "Export failed." });
18206
19299
  }
18207
19300
  });
@@ -18299,14 +19392,14 @@ ${style.markdown}` : params.prompt;
18299
19392
  }
18300
19393
  try {
18301
19394
  res.status(200).json({ usage: await getMyUsageView(authResult.user.id, window) });
18302
- } catch (err) {
18303
- if (err instanceof LiteLLMAdminError) {
18304
- res.status(502).json({ detail: err.message });
19395
+ } catch (err2) {
19396
+ if (err2 instanceof LiteLLMAdminError) {
19397
+ res.status(502).json({ detail: err2.message });
18305
19398
  return;
18306
19399
  }
18307
- console.error("[EXULU] /me/usage failed", err);
19400
+ console.error("[EXULU] /me/usage failed", err2);
18308
19401
  res.status(500).json({
18309
- detail: err instanceof Error ? err.message : "Usage query failed."
19402
+ detail: err2 instanceof Error ? err2.message : "Usage query failed."
18310
19403
  });
18311
19404
  }
18312
19405
  });
@@ -18336,11 +19429,11 @@ ${style.markdown}` : params.prompt;
18336
19429
  try {
18337
19430
  await upsertBudget(tag, body.max_budget, body.budget_duration, body.budget_reset_at);
18338
19431
  results.push({ entityId: String(id), ok: true });
18339
- } catch (err) {
19432
+ } catch (err2) {
18340
19433
  results.push({
18341
19434
  entityId: String(id),
18342
19435
  ok: false,
18343
- error: err instanceof Error ? err.message : "Failed."
19436
+ error: err2 instanceof Error ? err2.message : "Failed."
18344
19437
  });
18345
19438
  }
18346
19439
  }
@@ -18367,9 +19460,9 @@ ${style.markdown}` : params.prompt;
18367
19460
  await upsertBudget(tag, body.max_budget, body.budget_duration, body.budget_reset_at);
18368
19461
  const info = await tagInfo([tag]);
18369
19462
  res.status(200).json({ budget: info[tag] ?? null });
18370
- } catch (err) {
19463
+ } catch (err2) {
18371
19464
  res.status(502).json({
18372
- detail: err instanceof Error ? err.message : "Failed to save budget."
19465
+ detail: err2 instanceof Error ? err2.message : "Failed to save budget."
18373
19466
  });
18374
19467
  }
18375
19468
  }
@@ -18389,9 +19482,9 @@ ${style.markdown}` : params.prompt;
18389
19482
  await tagDelete(tag);
18390
19483
  invalidateBudgetCaches(tag);
18391
19484
  res.status(204).end();
18392
- } catch (err) {
19485
+ } catch (err2) {
18393
19486
  res.status(502).json({
18394
- detail: err instanceof Error ? err.message : "Failed to delete budget."
19487
+ detail: err2 instanceof Error ? err2.message : "Failed to delete budget."
18395
19488
  });
18396
19489
  }
18397
19490
  }
@@ -18762,14 +19855,14 @@ ${style.markdown}` : params.prompt;
18762
19855
  echoedPrefix
18763
19856
  );
18764
19857
  res.status(200).json(projected);
18765
- } catch (err) {
18766
- if (err instanceof LiteLLMAdminError) {
18767
- res.status(502).json({ detail: err.message });
19858
+ } catch (err2) {
19859
+ if (err2 instanceof LiteLLMAdminError) {
19860
+ res.status(502).json({ detail: err2.message });
18768
19861
  return;
18769
19862
  }
18770
- console.error("[EXULU] /admin/litellm/tag-activity failed", err);
19863
+ console.error("[EXULU] /admin/litellm/tag-activity failed", err2);
18771
19864
  res.status(500).json({
18772
- detail: err instanceof Error ? err.message : "Analytics query failed."
19865
+ detail: err2 instanceof Error ? err2.message : "Analytics query failed."
18773
19866
  });
18774
19867
  }
18775
19868
  }
@@ -18830,7 +19923,7 @@ ${style.markdown}` : params.prompt;
18830
19923
  void (async () => {
18831
19924
  const { db } = await postgresClient();
18832
19925
  await seedBundledSkills({ db, config });
18833
- })().catch((err) => console.error("[SKILLS] seeding the bundled skills failed", err));
19926
+ })().catch((err2) => console.error("[SKILLS] seeding the bundled skills failed", err2));
18834
19927
  app.get("/skills/agent/bootstrap", async (_req, res) => {
18835
19928
  try {
18836
19929
  const zip = new JSZip3();
@@ -18846,8 +19939,8 @@ ${style.markdown}` : params.prompt;
18846
19939
  res.setHeader("Content-Type", "application/zip");
18847
19940
  res.setHeader("Content-Disposition", 'attachment; filename="imp-skills.zip"');
18848
19941
  res.send(buffer);
18849
- } catch (err) {
18850
- console.error("[SKILLS] Failed to build bootstrap zip", err);
19942
+ } catch (err2) {
19943
+ console.error("[SKILLS] Failed to build bootstrap zip", err2);
18851
19944
  res.status(500).json({ detail: "Failed to build bootstrap skill." });
18852
19945
  }
18853
19946
  });
@@ -18931,17 +20024,17 @@ ${style.markdown}` : params.prompt;
18931
20024
  const { db } = await postgresClient();
18932
20025
  const existing = await resolveSkillByName(db, name);
18933
20026
  if (existing) {
18934
- const canWrite = await canAccessSkill(db, existing, "write", authResult.user);
18935
- if (canWrite) {
20027
+ const canWrite2 = await canAccessSkill(db, existing, "write", authResult.user);
20028
+ if (canWrite2) {
18936
20029
  const nextVersion = (existing.current_version ?? 1) + 1;
18937
20030
  try {
18938
20031
  await extractBundleToVersion({ bytes, skillId: existing.id, version: nextVersion, config });
18939
- } catch (err) {
18940
- if (err instanceof BundleValidationError) {
18941
- res.status(400).json({ detail: err.message });
20032
+ } catch (err2) {
20033
+ if (err2 instanceof BundleValidationError) {
20034
+ res.status(400).json({ detail: err2.message });
18942
20035
  return;
18943
20036
  }
18944
- console.error("[SKILLS] publish (new version) failed", err);
20037
+ console.error("[SKILLS] publish (new version) failed", err2);
18945
20038
  res.status(500).json({ detail: "Failed to publish new version." });
18946
20039
  return;
18947
20040
  }
@@ -18974,15 +20067,15 @@ ${style.markdown}` : params.prompt;
18974
20067
  return;
18975
20068
  }
18976
20069
  const meta = await parseSkillFrontmatter(bytes);
18977
- const skillId = randomUUID8();
20070
+ const skillId = randomUUID9();
18978
20071
  try {
18979
20072
  await extractBundleToVersion({ bytes, skillId, version: 1, config });
18980
- } catch (err) {
18981
- if (err instanceof BundleValidationError) {
18982
- res.status(400).json({ detail: err.message });
20073
+ } catch (err2) {
20074
+ if (err2 instanceof BundleValidationError) {
20075
+ res.status(400).json({ detail: err2.message });
18983
20076
  return;
18984
20077
  }
18985
- console.error("[SKILLS] publish (create) failed", err);
20078
+ console.error("[SKILLS] publish (create) failed", err2);
18986
20079
  res.status(500).json({ detail: "Failed to publish skill." });
18987
20080
  return;
18988
20081
  }
@@ -19002,7 +20095,7 @@ ${style.markdown}` : params.prompt;
19002
20095
  rights_mode: visibility,
19003
20096
  created_by: authResult.user.id
19004
20097
  });
19005
- } catch (err) {
20098
+ } catch (err2) {
19006
20099
  res.status(409).json({ detail: "That name is unavailable." });
19007
20100
  return;
19008
20101
  }
@@ -19056,8 +20149,8 @@ ${style.markdown}` : params.prompt;
19056
20149
  const s3Key = `skills/${skillId}/v1/SKILL.md`;
19057
20150
  try {
19058
20151
  await uploadFile(Buffer.from(skillMdContent, "utf-8"), s3Key, config, { contentType: "text/markdown" }, void 0, void 0, true);
19059
- } catch (err) {
19060
- console.error("[SKILLS] Failed to create SKILL.md in S3", err);
20152
+ } catch (err2) {
20153
+ console.error("[SKILLS] Failed to create SKILL.md in S3", err2);
19061
20154
  res.status(500).json({ detail: "Failed to initialise skill folder in S3." });
19062
20155
  return;
19063
20156
  }
@@ -19094,7 +20187,7 @@ ${style.markdown}` : params.prompt;
19094
20187
  res.status(404).json({ detail: "Skill not found." });
19095
20188
  return;
19096
20189
  }
19097
- const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID8()}${extension}`;
20190
+ const stagingKey = `user_${authResult.user.id}/skills/_staging/${randomUUID9()}${extension}`;
19098
20191
  const fullKey = config.fileUploads?.s3prefix ? `${config.fileUploads.s3prefix.replace(/\/$/, "")}/${stagingKey}` : stagingKey;
19099
20192
  const uploadUrl = await getS3SignedUploadUrl(fullKey, contentType, config);
19100
20193
  res.json({ uploadUrl, stagingKey });
@@ -19134,15 +20227,15 @@ ${style.markdown}` : params.prompt;
19134
20227
  let bytes;
19135
20228
  try {
19136
20229
  bytes = await getS3ObjectBytes(fullStagingKey, config);
19137
- } catch (err) {
19138
- console.error("[SKILLS] Failed to fetch staged bundle", err);
20230
+ } catch (err2) {
20231
+ console.error("[SKILLS] Failed to fetch staged bundle", err2);
19139
20232
  res.status(500).json({ detail: "Failed to fetch staged bundle from S3." });
19140
20233
  return;
19141
20234
  }
19142
20235
  let result;
19143
20236
  try {
19144
20237
  result = await extractBundleToS3({ bytes, skillId, isZip, config });
19145
- } catch (err) {
20238
+ } catch (err2) {
19146
20239
  try {
19147
20240
  await db("skills").where({ id: skillId }).delete();
19148
20241
  } catch (cleanupErr) {
@@ -19159,11 +20252,11 @@ ${style.markdown}` : params.prompt;
19159
20252
  cleanupErr
19160
20253
  );
19161
20254
  }
19162
- if (err instanceof BundleValidationError) {
19163
- res.status(400).json({ detail: err.message });
20255
+ if (err2 instanceof BundleValidationError) {
20256
+ res.status(400).json({ detail: err2.message });
19164
20257
  return;
19165
20258
  }
19166
- console.error("[SKILLS] Failed to extract bundle", err);
20259
+ console.error("[SKILLS] Failed to extract bundle", err2);
19167
20260
  res.status(500).json({ detail: "Failed to extract bundle." });
19168
20261
  return;
19169
20262
  }
@@ -19177,8 +20270,8 @@ ${style.markdown}` : params.prompt;
19177
20270
  });
19178
20271
  try {
19179
20272
  await deleteS3Object(fullStagingKey, config);
19180
- } catch (err) {
19181
- console.warn(`[SKILLS] Failed to delete staging key ${fullStagingKey}; continuing.`, err);
20273
+ } catch (err2) {
20274
+ console.warn(`[SKILLS] Failed to delete staging key ${fullStagingKey}; continuing.`, err2);
19182
20275
  }
19183
20276
  res.json({ version: 1, filesCount: result.filesCount });
19184
20277
  });
@@ -19586,8 +20679,8 @@ ${style.markdown}` : params.prompt;
19586
20679
  const skills = await getEnabledSkills(agent, []);
19587
20680
  const outcome = await refreshSessionSkills(sessionId, skills, config);
19588
20681
  res.json({ ...outcome, skills: skills.map((s) => ({ id: s.id, name: s.name, version: s.current_version })) });
19589
- } catch (err) {
19590
- console.error("[SKILLS] reload failed", err);
20682
+ } catch (err2) {
20683
+ console.error("[SKILLS] reload failed", err2);
19591
20684
  res.status(500).json({ detail: "Could not reload the skills." });
19592
20685
  }
19593
20686
  });
@@ -19607,8 +20700,8 @@ ${style.markdown}` : params.prompt;
19607
20700
  let objects;
19608
20701
  try {
19609
20702
  objects = await listS3ObjectsByPrefix(userSessionPrefix, config);
19610
- } catch (err) {
19611
- console.error("[SESSION-FILES] Failed to list S3 objects", err);
20703
+ } catch (err2) {
20704
+ console.error("[SESSION-FILES] Failed to list S3 objects", err2);
19612
20705
  res.status(500).json({ detail: "Failed to list session files." });
19613
20706
  return;
19614
20707
  }
@@ -19690,8 +20783,8 @@ ${style.markdown}` : params.prompt;
19690
20783
  config
19691
20784
  });
19692
20785
  res.json(result);
19693
- } catch (err) {
19694
- console.error("[SESSION-FILES] sync-to-sandbox failed", err);
20786
+ } catch (err2) {
20787
+ console.error("[SESSION-FILES] sync-to-sandbox failed", err2);
19695
20788
  res.status(500).json({ detail: "Failed to sync file into sandbox." });
19696
20789
  }
19697
20790
  }
@@ -19718,8 +20811,8 @@ ${style.markdown}` : params.prompt;
19718
20811
  try {
19719
20812
  await deleteS3Object(key, config);
19720
20813
  res.json({ deleted: true });
19721
- } catch (err) {
19722
- console.error("[SESSION-FILES] delete failed", err);
20814
+ } catch (err2) {
20815
+ console.error("[SESSION-FILES] delete failed", err2);
19723
20816
  res.status(500).json({ detail: "Failed to delete session file." });
19724
20817
  }
19725
20818
  }
@@ -19760,13 +20853,13 @@ ${style.markdown}` : params.prompt;
19760
20853
  res.setHeader("Content-Type", "application/pdf");
19761
20854
  res.setHeader("Cache-Control", "private, max-age=300");
19762
20855
  res.send(pdfBytes);
19763
- } catch (err) {
19764
- if (err instanceof PreviewRenderError) {
19765
- console.error("[SESSION-FILES] preview render failed", err);
19766
- res.status(500).json({ detail: err.message });
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 });
19767
20860
  return;
19768
20861
  }
19769
- console.error("[SESSION-FILES] preview unexpected error", err);
20862
+ console.error("[SESSION-FILES] preview unexpected error", err2);
19770
20863
  res.status(500).json({ detail: "Failed to render preview." });
19771
20864
  }
19772
20865
  }
@@ -19871,8 +20964,8 @@ ${style.markdown}` : params.prompt;
19871
20964
  `attachment; filename="${filename}"`
19872
20965
  );
19873
20966
  res.send(buffer);
19874
- } catch (err) {
19875
- console.error("[GDPR] Failed to build data export", err);
20967
+ } catch (err2) {
20968
+ console.error("[GDPR] Failed to build data export", err2);
19876
20969
  res.status(500).json({ detail: "Failed to build data export." });
19877
20970
  }
19878
20971
  });
@@ -19893,8 +20986,8 @@ ${style.markdown}` : params.prompt;
19893
20986
  await trx("rbac").where({ user_id: targetUser.id }).delete();
19894
20987
  await trx("users").where({ id: targetUser.id }).delete();
19895
20988
  });
19896
- } catch (err) {
19897
- console.error("[GDPR] Failed to delete user", err);
20989
+ } catch (err2) {
20990
+ console.error("[GDPR] Failed to delete user", err2);
19898
20991
  res.status(500).json({ detail: "Failed to delete user." });
19899
20992
  return;
19900
20993
  }
@@ -19902,8 +20995,8 @@ ${style.markdown}` : params.prompt;
19902
20995
  const prefix = `user_${targetUser.id}/`;
19903
20996
  const files = await listS3ObjectsByPrefix(prefix, config);
19904
20997
  await Promise.all(files.map((f) => deleteS3Object(f.key, config)));
19905
- } catch (err) {
19906
- console.error("[GDPR] DB delete succeeded but S3 cleanup failed", err);
20998
+ } catch (err2) {
20999
+ console.error("[GDPR] DB delete succeeded but S3 cleanup failed", err2);
19907
21000
  }
19908
21001
  res.status(204).send();
19909
21002
  });
@@ -20197,9 +21290,9 @@ ${style.markdown}` : params.prompt;
20197
21290
  if (!agentModel) return "";
20198
21291
  return "";
20199
21292
  };
20200
- const UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
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;
20201
21294
  const getGuestAgentById = async (id) => {
20202
- if (!UUID_RE2.test(id)) return void 0;
21295
+ if (!UUID_RE3.test(id)) return void 0;
20203
21296
  const { db } = await postgresClient();
20204
21297
  return db.from("agents").where({ id, guest_access: true, active: true }).first();
20205
21298
  };
@@ -20342,7 +21435,7 @@ function buildUnifiedDiff(fromLines, toLines, fromLabel, toLabel) {
20342
21435
 
20343
21436
  // src/mcp/index.ts
20344
21437
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
20345
- import { randomUUID as randomUUID9 } from "crypto";
21438
+ import { randomUUID as randomUUID10 } from "crypto";
20346
21439
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
20347
21440
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
20348
21441
  import "express";
@@ -20436,7 +21529,7 @@ var ExuluMCP = class {
20436
21529
  throw new Error("Tool not found in converted tools array.");
20437
21530
  }
20438
21531
  const iterator = await convertedTool.execute(inputs, {
20439
- toolCallId: tool2.id + "_" + randomUUID9(),
21532
+ toolCallId: tool2.id + "_" + randomUUID10(),
20440
21533
  messages: []
20441
21534
  });
20442
21535
  let result;
@@ -20626,7 +21719,7 @@ var ExuluMCP = class {
20626
21719
  transport = this.transports[sessionId];
20627
21720
  } else if (!sessionId && isInitializeRequest(req.body)) {
20628
21721
  transport = new StreamableHTTPServerTransport({
20629
- sessionIdGenerator: () => randomUUID9(),
21722
+ sessionIdGenerator: () => randomUUID10(),
20630
21723
  onsessioninitialized: (sessionId2) => {
20631
21724
  this.transports[sessionId2] = transport;
20632
21725
  }
@@ -21207,7 +22300,7 @@ After asking a question, use the Question Read tool to check if the user has ans
21207
22300
 
21208
22301
  // src/templates/tools/question/question-ask.ts
21209
22302
  import z15 from "zod";
21210
- import { randomUUID as randomUUID10 } from "crypto";
22303
+ import { randomUUID as randomUUID11 } from "crypto";
21211
22304
  var AnswerOptionSchema = z15.object({
21212
22305
  id: z15.string().describe("Unique identifier for the answer option"),
21213
22306
  text: z15.string().describe("The text of the answer option")
@@ -21261,15 +22354,15 @@ var QuestionAskTool = new ExuluTool({
21261
22354
  throw new Error("You don't have access to this session " + session.id + ".");
21262
22355
  }
21263
22356
  const answerOptionsWithIds = answerOptions.map((text) => ({
21264
- id: randomUUID10(),
22357
+ id: randomUUID11(),
21265
22358
  text
21266
22359
  }));
21267
22360
  answerOptionsWithIds.push({
21268
- id: randomUUID10(),
22361
+ id: randomUUID11(),
21269
22362
  text: "None of the above..."
21270
22363
  });
21271
22364
  const newQuestion = {
21272
- id: randomUUID10(),
22365
+ id: randomUUID11(),
21273
22366
  question,
21274
22367
  answerOptions: answerOptionsWithIds,
21275
22368
  status: "pending"
@@ -21606,8 +22699,8 @@ var tick = async () => {
21606
22699
  if (stopped) return;
21607
22700
  try {
21608
22701
  await transcriptionService.pollOnce(MAX_PER_TICK);
21609
- } catch (err) {
21610
- console.error(`[EXULU-TRANSCRIPTION] polling tick failed: ${err.message}`);
22702
+ } catch (err2) {
22703
+ console.error(`[EXULU-TRANSCRIPTION] polling tick failed: ${err2.message}`);
21611
22704
  } finally {
21612
22705
  if (!stopped) {
21613
22706
  timer = setTimeout(tick, POLL_INTERVAL_MS);
@@ -21640,9 +22733,9 @@ var tick2 = async () => {
21640
22733
  if (acted > 0) {
21641
22734
  console.log(`[EXULU-RECALL] reconcile tick recovered ${acted} job(s)`);
21642
22735
  }
21643
- } catch (err) {
22736
+ } catch (err2) {
21644
22737
  console.error(
21645
- `[EXULU-RECALL] reconcile tick failed: ${err.message}`
22738
+ `[EXULU-RECALL] reconcile tick failed: ${err2.message}`
21646
22739
  );
21647
22740
  } finally {
21648
22741
  if (!stopped2) {
@@ -21836,6 +22929,7 @@ var ExuluApp = class {
21836
22929
  5,
21837
22930
  300
21838
22931
  );
22932
+ registerImportQueue();
21839
22933
  if (queues2?.length) {
21840
22934
  for (const queue of queues2) {
21841
22935
  queueSet.add(await queue);
@@ -21884,10 +22978,10 @@ var ExuluApp = class {
21884
22978
  setLiteLLMPackageRoot(packageRoot);
21885
22979
  try {
21886
22980
  await startLiteLLMSupervisor();
21887
- } catch (err) {
22981
+ } catch (err2) {
21888
22982
  console.error(
21889
22983
  "[EXULU] LiteLLM supervisor failed to start:",
21890
- err.message
22984
+ err2.message
21891
22985
  );
21892
22986
  }
21893
22987
  }
@@ -21898,9 +22992,9 @@ var ExuluApp = class {
21898
22992
  console.log(
21899
22993
  `[EXULU] Transcription: enabled (server=${process.env.TRANSCRIPTION_SERVER}, device=${health.device}, GPU=${health.gpu.available ? "enabled" : "disabled"}, diarization=${health.diarization ? "enabled" : "disabled"})`
21900
22994
  );
21901
- } catch (err) {
22995
+ } catch (err2) {
21902
22996
  console.warn(
21903
- `[EXULU] TRANSCRIPTION_SERVER set but not reachable yet: ${err.message}. Polling loop is running; jobs will reconcile once the server is up.`
22997
+ `[EXULU] TRANSCRIPTION_SERVER set but not reachable yet: ${err2.message}. Polling loop is running; jobs will reconcile once the server is up.`
21904
22998
  );
21905
22999
  }
21906
23000
  } else {
@@ -22959,6 +24053,7 @@ var {
22959
24053
  jobResultsSchema: jobResultsSchema2,
22960
24054
  promptLibrarySchema: promptLibrarySchema2,
22961
24055
  contextPresetsSchema: contextPresetsSchema2,
24056
+ contextFoldersSchema: contextFoldersSchema2,
22962
24057
  contextProjectionsSchema,
22963
24058
  contextMapTopicsSchema,
22964
24059
  entityTypeSettingsSchema: entityTypeSettingsSchema2,
@@ -23022,6 +24117,7 @@ var up = async function(knex) {
23022
24117
  jobResultsSchema2(),
23023
24118
  promptLibrarySchema2(),
23024
24119
  contextPresetsSchema2(),
24120
+ contextFoldersSchema2(),
23025
24121
  contextProjectionsSchema(),
23026
24122
  contextMapTopicsSchema(),
23027
24123
  entityTypeSettingsSchema2(),
@@ -23423,12 +24519,12 @@ var initLiteLLMDatabase = async (packageRoot) => {
23423
24519
  await probe.connect();
23424
24520
  await probe.end();
23425
24521
  return true;
23426
- } catch (err) {
23427
- const code = err?.code;
24522
+ } catch (err2) {
24523
+ const code = err2?.code;
23428
24524
  if (code !== "3D000") {
23429
24525
  warn2([
23430
24526
  `Could not connect to LiteLLM's target database:`,
23431
- ` ${err instanceof Error ? err.message : String(err)}`,
24527
+ ` ${err2 instanceof Error ? err2.message : String(err2)}`,
23432
24528
  ``,
23433
24529
  `Skipping LiteLLM database setup. LiteLLM features that depend on`,
23434
24530
  `the database will fail at runtime until this is resolved.`
@@ -23492,11 +24588,11 @@ var initLiteLLMDatabase = async (packageRoot) => {
23492
24588
  ORDER BY table_name;`
23493
24589
  );
23494
24590
  foreignTables = res.rows.map((r) => r.table_name);
23495
- } catch (err) {
24591
+ } catch (err2) {
23496
24592
  warn2([
23497
24593
  `Could not query LiteLLM's target database to verify it is safe`,
23498
24594
  `to push into:`,
23499
- ` ${err instanceof Error ? err.message : String(err)}`,
24595
+ ` ${err2 instanceof Error ? err2.message : String(err2)}`,
23500
24596
  ``,
23501
24597
  `Skipping LiteLLM database setup. LiteLLM features that depend on the`,
23502
24598
  `database will fail at runtime until this is resolved.`
@@ -24122,7 +25218,7 @@ import * as path from "path";
24122
25218
  import { generateText as generateText8, Output as Output3 } from "ai";
24123
25219
  import { z as z19 } from "zod";
24124
25220
  import pLimit from "p-limit";
24125
- import { randomUUID as randomUUID11 } from "crypto";
25221
+ import { randomUUID as randomUUID12 } from "crypto";
24126
25222
  import * as mammoth from "mammoth";
24127
25223
  import TurndownService from "turndown";
24128
25224
  import WordExtractor from "word-extractor";
@@ -24289,10 +25385,10 @@ async function resolveOcr(input) {
24289
25385
  }
24290
25386
  try {
24291
25387
  await waitForLiteLLMReady();
24292
- } catch (err) {
25388
+ } catch (err2) {
24293
25389
  throw new ResolveOcrError(
24294
25390
  "LITELLM_NOT_READY",
24295
- `LiteLLM is not ready: ${err.message}`
25391
+ `LiteLLM is not ready: ${err2.message}`
24296
25392
  );
24297
25393
  }
24298
25394
  const { baseUrl, authHeaders } = resolveLiteLLMTarget();
@@ -24809,9 +25905,9 @@ async function processPdf(buffer, paths, config, verbose = false) {
24809
25905
  let pdfChunks;
24810
25906
  try {
24811
25907
  pdfChunks = JSON.parse(splitResult.stdout);
24812
- } catch (err) {
25908
+ } catch (err2) {
24813
25909
  throw new Error(
24814
- `[EXULU] split_pdf.py returned invalid JSON on stdout: ${err.message}
25910
+ `[EXULU] split_pdf.py returned invalid JSON on stdout: ${err2.message}
24815
25911
  stdout: ${splitResult.stdout.slice(0, 500)}
24816
25912
  stderr: ${splitResult.stderr.slice(-1e3)}`
24817
25913
  );
@@ -24957,7 +26053,7 @@ var loadFile = async (file, name, tempDir) => {
24957
26053
  if (!fileType) {
24958
26054
  throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
24959
26055
  }
24960
- const UUID2 = randomUUID11();
26056
+ const UUID2 = randomUUID12();
24961
26057
  let buffer;
24962
26058
  if (Buffer.isBuffer(file)) {
24963
26059
  filePath = path.join(tempDir, `${UUID2}.${fileType}`);
@@ -24987,7 +26083,7 @@ async function documentProcessor({
24987
26083
  if (!license["advanced-document-processing"]) {
24988
26084
  throw new Error("Advanced document processing is an enterprise feature, please add a valid Exulu enterprise license key to use it.");
24989
26085
  }
24990
- const uuid = randomUUID11();
26086
+ const uuid = randomUUID12();
24991
26087
  const tempDir = path.join(process.cwd(), "temp", uuid);
24992
26088
  const localFilesAndFoldersToDelete = [tempDir];
24993
26089
  console.log(`[EXULU] Temporary directory for processing document ${name}: ${tempDir}`);