@exulu/backend 5.7.1 → 5.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import "dotenv/config";
2
+ import {
3
+ documentProcessor
4
+ } from "./chunk-RNZ4IDCT.js";
2
5
  import {
3
6
  getPackageRoot,
4
7
  getPythonSetupInstructions,
@@ -28,7 +31,6 @@ import {
28
31
  FIT_SAMPLE,
29
32
  JOB_STATUS_ENUM,
30
33
  KB_EDITOR_TOOL_ID,
31
- LITELLM_UI_PATH,
32
34
  MEMORY_REQUIRED_FIELDS,
33
35
  OAUTH_CALLBACK_PATH,
34
36
  PARSE_DOCUMENT_TOOL_NAME,
@@ -40,7 +42,6 @@ import {
40
42
  PreviewRenderError,
41
43
  RBACResolver,
42
44
  RIDGE_LAMBDA,
43
- ResolveModelError,
44
45
  SCRUBBED_CREDENTIAL_TEXT,
45
46
  SCRUBBED_OAUTH_TEXT,
46
47
  SESSION_FILE_READ_TOOL_NAME,
@@ -67,13 +68,10 @@ import {
67
68
  assertAllowedField,
68
69
  authRegistry,
69
70
  authentication,
70
- budgetTagFor,
71
71
  buildMemoryPromptBlock,
72
- buildTags,
73
72
  canAccessSkill,
74
73
  canEditMemory,
75
74
  captureCodeEmbedder,
76
- checkLicense,
77
75
  checkMemoryBase,
78
76
  checkRecordAccess,
79
77
  chooseFullTextQuery,
@@ -90,7 +88,6 @@ import {
90
88
  createKbEditorPickerTool,
91
89
  createRecallCollector,
92
90
  createSkillAuthorPickerTool,
93
- createTaggedFetch,
94
91
  createUppyRoutes,
95
92
  creatorId,
96
93
  credentialStore,
@@ -102,12 +99,12 @@ import {
102
99
  displayName,
103
100
  downloadKeyIntoSandbox,
104
101
  dropProjection,
105
- enableLiteLLMClientMode,
106
102
  encrypt,
107
103
  ensureEntityTables,
108
104
  estimateMessageTokens,
109
105
  estimateTokens,
110
106
  exchangeCodeForTokens,
107
+ extractDocument,
111
108
  exuluApp,
112
109
  filterReadableSkills,
113
110
  finalAnswerGuard,
@@ -115,7 +112,6 @@ import {
115
112
  finite,
116
113
  fitResidual,
117
114
  getAuditLogger,
118
- getBudgetSettings,
119
115
  getChunkEntitiesTableName,
120
116
  getChunksTableName,
121
117
  getEmbeddingModelInfo,
@@ -129,10 +125,7 @@ import {
129
125
  getS3ObjectStream,
130
126
  getS3SignedUploadUrl,
131
127
  getTableName,
132
- getTagBudgetMap,
133
- getTagDailyActivity,
134
128
  getToken,
135
- getUserBudgetView,
136
129
  guardExtractedFileText,
137
130
  handleRBACUpdate,
138
131
  hasAgentsReadAccess,
@@ -140,13 +133,10 @@ import {
140
133
  hydrateContextEmbedders,
141
134
  imageAttachmentGuard,
142
135
  initAudit,
143
- invalidateBudgetCaches,
144
136
  isExternalOrAnonymousUser,
145
137
  isIgnoredArtifactPath,
146
- isLiteLLMEnabled,
147
138
  l2normalize,
148
139
  listS3ObjectsByPrefix,
149
- listTagsByPrefix,
150
140
  mapStreamErrorMessage,
151
141
  mapType,
152
142
  maybePruneJobResults,
@@ -158,14 +148,11 @@ import {
158
148
  parseEmbeddingModels,
159
149
  parseFrontmatter,
160
150
  parsePipelineConfig,
161
- parseResetAt,
162
151
  parseSkillAuthorConfig,
163
152
  parseSkillFrontmatter,
164
- postgresClient,
165
153
  preprocessQuery,
166
154
  principalRotation,
167
155
  projectComponents,
168
- provisionDefaultUserBudget,
169
156
  randomizedPCA,
170
157
  readProjectionRow,
171
158
  refreshContextEmbeddersIfStale,
@@ -174,7 +161,6 @@ import {
174
161
  resolveEmbedder,
175
162
  resolveEntityModel,
176
163
  resolveLiteLLMConfigPath,
177
- resolveModel,
178
164
  resolveReranker,
179
165
  resolveRetrievalCallBudget,
180
166
  resolveSearchQueryTexts,
@@ -188,32 +174,54 @@ import {
188
174
  sanitizeToolName,
189
175
  searchContexts,
190
176
  sessionFilePrefix,
191
- setBudgetSettings,
192
177
  setEmbedderSetting,
193
178
  setEntityModelSetting,
194
- setLiteLLMPackageRoot,
195
179
  shouldShowSourcesToUser,
196
180
  sliceHistoryAtCheckpoint,
197
- startLiteLLMSupervisor,
198
- tagDelete,
199
- tagInfo,
200
181
  truncateToolOutput,
201
182
  updateStatistic,
202
183
  uploadFile,
203
- upsertBudget,
204
184
  userCredentialsSchema,
185
+ validateAttachmentsConfig,
205
186
  vectorSearch,
206
187
  verifyCredentialNonce,
207
- waitForLiteLLMReady,
208
188
  willEmbedOnQueue,
209
- withRetry,
210
189
  workflowTemplatesSchema
211
- } from "./chunk-XNTGIQLC.js";
190
+ } from "./chunk-NUEM3HMI.js";
191
+ import {
192
+ LITELLM_UI_PATH,
193
+ ResolveModelError,
194
+ budgetTagFor,
195
+ buildTags,
196
+ checkLicense,
197
+ createTaggedFetch,
198
+ enableLiteLLMClientMode,
199
+ getBudgetSettings,
200
+ getTagBudgetMap,
201
+ getTagDailyActivity,
202
+ getUserBudgetView,
203
+ invalidateBudgetCaches,
204
+ isLiteLLMEnabled,
205
+ listTagsByPrefix,
206
+ parseResetAt,
207
+ postgresClient,
208
+ provisionDefaultUserBudget,
209
+ resolveModel,
210
+ setBudgetSettings,
211
+ setLiteLLMPackageRoot,
212
+ startLiteLLMSupervisor,
213
+ tagDelete,
214
+ tagInfo,
215
+ upsertBudget,
216
+ waitForLiteLLMReady
217
+ } from "./chunk-4W3V7IHR.js";
218
+ import {
219
+ findLiteLLMModel
220
+ } from "./chunk-F534XOQR.js";
212
221
  import {
213
222
  LiteLLMAdminError,
214
- findLiteLLMModel,
215
223
  resolveLiteLLMTarget
216
- } from "./chunk-4PDWNVNT.js";
224
+ } from "./chunk-6URU62NI.js";
217
225
 
218
226
  // src/index.ts
219
227
  import "dotenv/config";
@@ -3963,6 +3971,11 @@ var bullmq = {
3963
3971
  }
3964
3972
  };
3965
3973
 
3974
+ // src/utils/jsonb-safe.ts
3975
+ function jsonbSafeStringify(value) {
3976
+ return JSON.stringify(value).replace(/\\u0000/g, "");
3977
+ }
3978
+
3966
3979
  // src/exulu/turn-metadata.ts
3967
3980
  function finishTurnMetadata(opts) {
3968
3981
  const now = opts.now ?? Date.now();
@@ -3999,13 +4012,13 @@ var MEDIA_TYPE_ALIASES = {
3999
4012
  };
4000
4013
  function fileNameFromUrl(url) {
4001
4014
  if (!url) return void 0;
4002
- let path2;
4015
+ let path;
4003
4016
  try {
4004
- path2 = new URL(url).pathname;
4017
+ path = new URL(url).pathname;
4005
4018
  } catch {
4006
- path2 = url.split("?")[0] ?? "";
4019
+ path = url.split("?")[0] ?? "";
4007
4020
  }
4008
- const last = path2.split("/").pop() ?? "";
4021
+ const last = path.split("/").pop() ?? "";
4009
4022
  try {
4010
4023
  return decodeURIComponent(last) || void 0;
4011
4024
  } catch {
@@ -4314,9 +4327,6 @@ var autoDeclineStaleApprovals = (messages) => {
4314
4327
  return { messages: reconciled, declined };
4315
4328
  };
4316
4329
 
4317
- // src/exulu/generate-stream.ts
4318
- import { parseOfficeAsync } from "officeparser";
4319
-
4320
4330
  // src/exulu/auth/guardrail.ts
4321
4331
  var CREDENTIAL_GUARDRAIL = `Credential safety:
4322
4332
  Some tools collect credentials (API keys, passwords, tokens) through a secure form shown directly to the user in the chat UI. Credentials are never entered in the conversation itself.
@@ -4596,7 +4606,7 @@ var processFilePartsInMessages = async (messages, offloadCtx) => {
4596
4606
  };
4597
4607
  }
4598
4608
  const filename = classified.filename;
4599
- console.log(`[EXULU] Converting file part to text using officeparser: ${filename}`);
4609
+ console.log(`[EXULU] Converting file part to text: ${filename}`);
4600
4610
  try {
4601
4611
  const response = await fetch(url);
4602
4612
  if (!response.ok) {
@@ -4608,12 +4618,17 @@ var processFilePartsInMessages = async (messages, offloadCtx) => {
4608
4618
  text: `[Error: Could not load file ${filename}]`
4609
4619
  };
4610
4620
  }
4611
- const arrayBuffer = await response.arrayBuffer();
4612
- const extractedText = await parseOfficeAsync(arrayBuffer, {
4613
- outputErrorToConsole: false,
4614
- newlineDelimiter: "\n"
4621
+ const bytes = Buffer.from(await response.arrayBuffer());
4622
+ const extracted = await extractDocument({
4623
+ bytes,
4624
+ filename,
4625
+ exuluConfig: offloadCtx.exuluConfig,
4626
+ attribution: { user: offloadCtx.user }
4615
4627
  });
4616
- const guardedText = await guardExtractedFileText(filename, String(extractedText), offloadCtx);
4628
+ console.log(
4629
+ extracted.tooLong ? `[EXULU] ${filename} refused: ${extracted.tooLong.pageCount} pages > cap ${extracted.tooLong.maxPages}` : `[EXULU] Extracted ${filename} via ${extracted.engine} (${extracted.pages.length} page(s), ${extracted.text.length} chars)`
4630
+ );
4631
+ const guardedText = await guardExtractedFileText(filename, extracted.text, offloadCtx);
4617
4632
  return {
4618
4633
  type: "text",
4619
4634
  text: `<file file name = "${filename}" >
@@ -5645,7 +5660,7 @@ function detectPayloadFormat(contentType) {
5645
5660
  }
5646
5661
  var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
5647
5662
  function extractMultipartMimePart(rawBody, contentType) {
5648
- return new Promise((resolve4, reject) => {
5663
+ return new Promise((resolve3, reject) => {
5649
5664
  let found = null;
5650
5665
  const bb = Busboy({ headers: { "content-type": contentType }, defCharset: "latin1" });
5651
5666
  bb.on("field", (name, value) => {
@@ -5654,7 +5669,7 @@ function extractMultipartMimePart(rawBody, contentType) {
5654
5669
  }
5655
5670
  });
5656
5671
  bb.on("close", () => {
5657
- if (found) resolve4(found);
5672
+ if (found) resolve3(found);
5658
5673
  else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
5659
5674
  });
5660
5675
  bb.on("error", (err2) => reject(err2 instanceof Error ? err2 : new Error(String(err2))));
@@ -6146,7 +6161,7 @@ function createSniffer(onFirstLine) {
6146
6161
  const head = [];
6147
6162
  let headBytes = 0;
6148
6163
  let resolved = false;
6149
- const resolve4 = (line) => {
6164
+ const resolve3 = (line) => {
6150
6165
  if (resolved) return;
6151
6166
  resolved = true;
6152
6167
  onFirstLine(line);
@@ -6161,15 +6176,15 @@ function createSniffer(onFirstLine) {
6161
6176
  const text = Buffer.concat(head).toString("utf-8");
6162
6177
  const eol = /\r|\n/.exec(text);
6163
6178
  if (eol) {
6164
- resolve4(text.slice(0, eol.index));
6179
+ resolve3(text.slice(0, eol.index));
6165
6180
  } else if (headBytes >= MAX_HEADER_BYTES) {
6166
- resolve4(text);
6181
+ resolve3(text);
6167
6182
  }
6168
6183
  }
6169
6184
  callback(null, chunk2);
6170
6185
  },
6171
6186
  flush(callback) {
6172
- resolve4(Buffer.concat(head).toString("utf-8"));
6187
+ resolve3(Buffer.concat(head).toString("utf-8"));
6173
6188
  callback();
6174
6189
  }
6175
6190
  });
@@ -6177,8 +6192,8 @@ function createSniffer(onFirstLine) {
6177
6192
  async function streamCsvRows(input, handlers, opts) {
6178
6193
  let resolveFirstLine = () => {
6179
6194
  };
6180
- const firstLine = new Promise((resolve4) => {
6181
- resolveFirstLine = resolve4;
6195
+ const firstLine = new Promise((resolve3) => {
6196
+ resolveFirstLine = resolve3;
6182
6197
  });
6183
6198
  const sniffer = createSniffer((line) => resolveFirstLine(line));
6184
6199
  let parser;
@@ -6672,7 +6687,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
6672
6687
  );
6673
6688
  if (attempt < retries) {
6674
6689
  const backoffMs = 500 * Math.pow(2, attempt - 1);
6675
- await new Promise((resolve4) => setTimeout(resolve4, backoffMs));
6690
+ await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
6676
6691
  }
6677
6692
  }
6678
6693
  }
@@ -6892,7 +6907,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
6892
6907
  }
6893
6908
  const retries2 = 3;
6894
6909
  let attempts = 0;
6895
- const promise = new Promise(async (resolve4, reject) => {
6910
+ const promise = new Promise(async (resolve3, reject) => {
6896
6911
  while (attempts < retries2) {
6897
6912
  try {
6898
6913
  const messages2 = await processUiMessagesFlow({
@@ -6911,7 +6926,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
6911
6926
  // back into blanket pre-approval (spec §5.2).
6912
6927
  respectToolApprovals: workflow.auto_approve_tools !== true
6913
6928
  });
6914
- resolve4(messages2);
6929
+ resolve3(messages2);
6915
6930
  break;
6916
6931
  } catch (error) {
6917
6932
  console.error(
@@ -6938,7 +6953,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
6938
6953
  }
6939
6954
  reject(new Error(error instanceof Error ? error.message : String(error)));
6940
6955
  }
6941
- await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
6956
+ await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
6942
6957
  }
6943
6958
  }
6944
6959
  });
@@ -6965,8 +6980,8 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
6965
6980
  );
6966
6981
  if (result.pausedAtStepIndex !== void 0) {
6967
6982
  await db.from("job_results").where({ id: jobResultId }).update({
6968
- result: messages.length > 0 ? JSON.stringify(messages[messages.length - 1]) : null,
6969
- metadata: JSON.stringify({
6983
+ result: messages.length > 0 ? jsonbSafeStringify(messages[messages.length - 1]) : null,
6984
+ metadata: jsonbSafeStringify({
6970
6985
  messages,
6971
6986
  ...metadata,
6972
6987
  tokens,
@@ -7036,7 +7051,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
7036
7051
  } = await validateEvalPayload(data);
7037
7052
  const retries2 = 3;
7038
7053
  let attempts = 0;
7039
- const promise = new Promise(async (resolve4, reject) => {
7054
+ const promise = new Promise(async (resolve3, reject) => {
7040
7055
  while (attempts < retries2) {
7041
7056
  try {
7042
7057
  const messages2 = await processUiMessagesFlow({
@@ -7047,7 +7062,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
7047
7062
  tools,
7048
7063
  config
7049
7064
  });
7050
- resolve4(messages2);
7065
+ resolve3(messages2);
7051
7066
  break;
7052
7067
  } catch (error) {
7053
7068
  console.error(
@@ -7058,7 +7073,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
7058
7073
  if (attempts >= retries2) {
7059
7074
  reject(new Error(error instanceof Error ? error.message : String(error)));
7060
7075
  }
7061
- await new Promise((resolve5) => setTimeout((resolve6) => resolve6(true), 2e3));
7076
+ await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
7062
7077
  }
7063
7078
  }
7064
7079
  });
@@ -7454,8 +7469,9 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
7454
7469
  const { db } = await postgresClient();
7455
7470
  await db.from("job_results").where({ job_id: job.id, state: JOB_STATUS_ENUM.active }).update({
7456
7471
  state: JOB_STATUS_ENUM.completed,
7457
- result: returnvalue.result != null ? JSON.stringify(returnvalue.result) : null,
7458
- metadata: returnvalue.metadata != null ? JSON.stringify(returnvalue.metadata) : null
7472
+ // jsonb rejects the NUL escape; a raw attachment read can carry it (2026-10-29).
7473
+ result: returnvalue.result != null ? jsonbSafeStringify(returnvalue.result) : null,
7474
+ metadata: returnvalue.metadata != null ? jsonbSafeStringify(returnvalue.metadata) : null
7459
7475
  });
7460
7476
  void maybePruneJobResults(db);
7461
7477
  }
@@ -7633,7 +7649,7 @@ var pollJobResult = async ({
7633
7649
  attempts++;
7634
7650
  const job = await Job.fromId(queue.queue, jobId);
7635
7651
  if (!job) {
7636
- await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
7652
+ await new Promise((resolve3) => setTimeout((resolve4) => resolve4(true), 2e3));
7637
7653
  continue;
7638
7654
  }
7639
7655
  const elapsedTime = Date.now() - startTime;
@@ -7663,7 +7679,7 @@ var pollJobResult = async ({
7663
7679
  console.log(`[EXULU] eval function ${job.id} result: ${result}`);
7664
7680
  break;
7665
7681
  }
7666
- await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
7682
+ await new Promise((resolve3) => setTimeout(() => resolve3(true), 2e3));
7667
7683
  }
7668
7684
  return result;
7669
7685
  };
@@ -7761,7 +7777,7 @@ var processUiMessagesFlow = async ({
7761
7777
  trigger: "agent"
7762
7778
  };
7763
7779
  try {
7764
- messageHistory = await new Promise(async (resolve4, reject) => {
7780
+ messageHistory = await new Promise(async (resolve3, reject) => {
7765
7781
  const startTime = Date.now();
7766
7782
  try {
7767
7783
  const result = await generateStream({
@@ -7850,7 +7866,7 @@ var processUiMessagesFlow = async ({
7850
7866
  })
7851
7867
  ] : []
7852
7868
  ]);
7853
- resolve4({
7869
+ resolve3({
7854
7870
  messages,
7855
7871
  metadata: {
7856
7872
  tokens: {
@@ -8059,7 +8075,7 @@ async function fetch_with_retry(args) {
8059
8075
  console.log(
8060
8076
  `[EXULU-RECALL] fetch error from ${url} (${err2.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
8061
8077
  );
8062
- await new Promise((resolve4) => setTimeout(resolve4, 5e3 + jitterMs()));
8078
+ await new Promise((resolve3) => setTimeout(resolve3, 5e3 + jitterMs()));
8063
8079
  continue;
8064
8080
  }
8065
8081
  let wait_for = null;
@@ -8079,7 +8095,7 @@ async function fetch_with_retry(args) {
8079
8095
  `[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
8080
8096
  );
8081
8097
  await new Promise(
8082
- (resolve4) => setTimeout(resolve4, 1e3 * wait_for + jitterMs())
8098
+ (resolve3) => setTimeout(resolve3, 1e3 * wait_for + jitterMs())
8083
8099
  );
8084
8100
  continue;
8085
8101
  }
@@ -8089,9 +8105,9 @@ async function fetch_with_retry(args) {
8089
8105
  `[EXULU-RECALL] Max attempts (${max_attempts}) reached while fetching ${url}.`
8090
8106
  );
8091
8107
  }
8092
- var request = async (path2, init = {}) => {
8108
+ var request = async (path, init = {}) => {
8093
8109
  assertRecallConfigured();
8094
- const url = `${recallApiBaseUrl()}${path2}`;
8110
+ const url = `${recallApiBaseUrl()}${path}`;
8095
8111
  const response = await fetch_with_retry({
8096
8112
  url,
8097
8113
  options: {
@@ -8109,7 +8125,7 @@ var request = async (path2, init = {}) => {
8109
8125
  if (!response.ok) {
8110
8126
  const body = await response.text();
8111
8127
  throw new RecallApiError(
8112
- `Recall API ${response.status} for ${path2}: ${body}`,
8128
+ `Recall API ${response.status} for ${path}: ${body}`,
8113
8129
  response.status,
8114
8130
  body
8115
8131
  );
@@ -8952,8 +8968,8 @@ var getBaseUrl = () => {
8952
8968
  }
8953
8969
  return url.replace(/\/$/, "");
8954
8970
  };
8955
- var request2 = async (path2, init = {}) => {
8956
- const url = `${getBaseUrl()}${path2}`;
8971
+ var request2 = async (path, init = {}) => {
8972
+ const url = `${getBaseUrl()}${path}`;
8957
8973
  let res;
8958
8974
  try {
8959
8975
  res = await fetch(url, init);
@@ -8963,13 +8979,13 @@ var request2 = async (path2, init = {}) => {
8963
8979
  );
8964
8980
  }
8965
8981
  if (res.status === 404) {
8966
- const err2 = new Error(`whisper server returned 404 for ${path2}`);
8982
+ const err2 = new Error(`whisper server returned 404 for ${path}`);
8967
8983
  err2.code = "JOB_NOT_FOUND";
8968
8984
  throw err2;
8969
8985
  }
8970
8986
  if (!res.ok) {
8971
8987
  throw new Error(
8972
- `whisper server returned ${res.status} for ${path2}: ${await res.text()}`
8988
+ `whisper server returned ${res.status} for ${path}: ${await res.text()}`
8973
8989
  );
8974
8990
  }
8975
8991
  return await res.json();
@@ -11902,7 +11918,7 @@ type EmbeddingModelOption {
11902
11918
  }
11903
11919
  `;
11904
11920
  resolvers.Query["litellmCatalog"] = async () => {
11905
- const { fetchLiteLLMCatalog } = await import("./catalog-3QLU2G7R.js");
11921
+ const { fetchLiteLLMCatalog } = await import("./catalog-4P3TKOV7.js");
11906
11922
  return fetchLiteLLMCatalog();
11907
11923
  };
11908
11924
  resolvers.Query["availableEmbeddingModels"] = async () => {
@@ -12359,7 +12375,7 @@ type EmbeddingModelOption {
12359
12375
  await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
12360
12376
  const retries = 3;
12361
12377
  let attempts = 0;
12362
- const promise = new Promise(async (resolve4, reject) => {
12378
+ const promise = new Promise(async (resolve3, reject) => {
12363
12379
  while (attempts < retries) {
12364
12380
  try {
12365
12381
  const messages2 = await processUiMessagesFlow({
@@ -12374,7 +12390,7 @@ type EmbeddingModelOption {
12374
12390
  routine: { id: workflow.id, name: workflow.name },
12375
12391
  sessionId
12376
12392
  });
12377
- resolve4(messages2);
12393
+ resolve3(messages2);
12378
12394
  break;
12379
12395
  } catch (error) {
12380
12396
  console.error(
@@ -12388,7 +12404,7 @@ type EmbeddingModelOption {
12388
12404
  if (attempts >= retries) {
12389
12405
  reject(error instanceof Error ? error : new Error(String(error)));
12390
12406
  }
12391
- await new Promise((resolve5) => setTimeout(() => resolve5(true), 2e3));
12407
+ await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
12392
12408
  }
12393
12409
  }
12394
12410
  });
@@ -12959,10 +12975,10 @@ type EmbeddingModelOption {
12959
12975
  contexts.map(async (context2) => {
12960
12976
  let processor = null;
12961
12977
  if (context2.processor) {
12962
- processor = await new Promise(async (resolve4, reject) => {
12978
+ processor = await new Promise(async (resolve3, reject) => {
12963
12979
  const config2 = context2.processor?.config;
12964
12980
  const queue = await config2?.queue;
12965
- resolve4({
12981
+ resolve3({
12966
12982
  name: context2.processor.name,
12967
12983
  description: context2.processor.description,
12968
12984
  queue: queue?.queue?.name || void 0,
@@ -13044,10 +13060,10 @@ type EmbeddingModelOption {
13044
13060
  }
13045
13061
  let processor = null;
13046
13062
  if (data.processor) {
13047
- processor = await new Promise(async (resolve4, reject) => {
13063
+ processor = await new Promise(async (resolve3, reject) => {
13048
13064
  const config2 = data.processor?.config;
13049
13065
  const queue = await config2?.queue;
13050
- resolve4({
13066
+ resolve3({
13051
13067
  name: data.processor.name,
13052
13068
  description: data.processor.description,
13053
13069
  queue: queue?.queue?.name || void 0,
@@ -13474,14 +13490,14 @@ var BundleValidationError = class extends Error {
13474
13490
  this.name = "BundleValidationError";
13475
13491
  }
13476
13492
  };
13477
- function isUnsafePath(path2) {
13478
- if (!path2) return true;
13479
- if (path2.startsWith("/")) return true;
13480
- return path2.split("/").some((segment) => segment === "..");
13481
- }
13482
- function isOsJunkPath(path2) {
13483
- if (path2.startsWith("__MACOSX/")) return true;
13484
- const basename = path2.split("/").pop() ?? "";
13493
+ function isUnsafePath(path) {
13494
+ if (!path) return true;
13495
+ if (path.startsWith("/")) return true;
13496
+ return path.split("/").some((segment) => segment === "..");
13497
+ }
13498
+ function isOsJunkPath(path) {
13499
+ if (path.startsWith("__MACOSX/")) return true;
13500
+ const basename = path.split("/").pop() ?? "";
13485
13501
  return basename === ".DS_Store" || basename === "Thumbs.db" || basename === "desktop.ini";
13486
13502
  }
13487
13503
  async function extractZipToPrefix(bytes, prefix, config) {
@@ -13507,17 +13523,17 @@ async function extractZipToPrefix(bytes, prefix, config) {
13507
13523
  `Bundle has ${entries.length} entries, exceeding the limit of ${MAX_ENTRY_COUNT}.`
13508
13524
  );
13509
13525
  }
13510
- for (const { path: path2 } of entries) {
13511
- if (isUnsafePath(path2)) {
13526
+ for (const { path } of entries) {
13527
+ if (isUnsafePath(path)) {
13512
13528
  throw new BundleValidationError(
13513
- `Bundle contains an unsafe path: ${path2}`
13529
+ `Bundle contains an unsafe path: ${path}`
13514
13530
  );
13515
13531
  }
13516
13532
  }
13517
13533
  let prefixToStrip = "";
13518
13534
  const firstSegments = /* @__PURE__ */ new Set();
13519
- for (const { path: path2 } of entries) {
13520
- const head = path2.split("/")[0];
13535
+ for (const { path } of entries) {
13536
+ const head = path.split("/")[0];
13521
13537
  if (head) firstSegments.add(head);
13522
13538
  }
13523
13539
  if (firstSegments.size === 1) {
@@ -13525,7 +13541,7 @@ async function extractZipToPrefix(bytes, prefix, config) {
13525
13541
  const allWrapped = entries.every((e) => e.path.startsWith(single + "/"));
13526
13542
  if (allWrapped) prefixToStrip = single + "/";
13527
13543
  }
13528
- const stripped = (path2) => prefixToStrip && path2.startsWith(prefixToStrip) ? path2.slice(prefixToStrip.length) : path2;
13544
+ const stripped = (path) => prefixToStrip && path.startsWith(prefixToStrip) ? path.slice(prefixToStrip.length) : path;
13529
13545
  const hasSkillMd = entries.some((e) => stripped(e.path) === "SKILL.md");
13530
13546
  if (!hasSkillMd) {
13531
13547
  throw new BundleValidationError(
@@ -13534,15 +13550,15 @@ async function extractZipToPrefix(bytes, prefix, config) {
13534
13550
  }
13535
13551
  const prepared = [];
13536
13552
  let totalBytes = 0;
13537
- for (const { path: path2, entry } of entries) {
13553
+ for (const { path, entry } of entries) {
13538
13554
  const content = await entry.async("nodebuffer");
13539
13555
  totalBytes += content.byteLength;
13540
13556
  if (totalBytes > MAX_TOTAL_UNCOMPRESSED_BYTES) {
13541
13557
  throw new BundleValidationError(
13542
- `Bundle uncompressed size exceeds ${MAX_TOTAL_UNCOMPRESSED_BYTES} bytes (50 MB). Reached ${totalBytes} bytes at "${path2}".`
13558
+ `Bundle uncompressed size exceeds ${MAX_TOTAL_UNCOMPRESSED_BYTES} bytes (50 MB). Reached ${totalBytes} bytes at "${path}".`
13543
13559
  );
13544
13560
  }
13545
- const relPath = stripped(path2);
13561
+ const relPath = stripped(path);
13546
13562
  if (!relPath) continue;
13547
13563
  prepared.push({ relPath, content });
13548
13564
  }
@@ -13620,8 +13636,8 @@ var BUNDLED_SKILLS = [
13620
13636
  var BUNDLED_LABEL = "Bundled with the IMP";
13621
13637
  function bundledSkillHash(skill) {
13622
13638
  const h = createHash2("sha256");
13623
- for (const path2 of Object.keys(skill.files).sort()) {
13624
- h.update(path2).update("\0").update(skill.files[path2]).update("\0");
13639
+ for (const path of Object.keys(skill.files).sort()) {
13640
+ h.update(path).update("\0").update(skill.files[path]).update("\0");
13625
13641
  }
13626
13642
  return h.digest("hex");
13627
13643
  }
@@ -13632,8 +13648,8 @@ function bundledSkillDescription(skill) {
13632
13648
  }
13633
13649
  async function bundledSkillZip(skill) {
13634
13650
  const zip = new JSZip2();
13635
- for (const [path2, b64] of Object.entries(skill.files)) {
13636
- zip.file(path2, Buffer.from(b64, "base64"), path2.startsWith("scripts/") ? { unixPermissions: 493 } : void 0);
13651
+ for (const [path, b64] of Object.entries(skill.files)) {
13652
+ zip.file(path, Buffer.from(b64, "base64"), path.startsWith("scripts/") ? { unixPermissions: 493 } : void 0);
13637
13653
  }
13638
13654
  return zip.generateAsync({ type: "nodebuffer", platform: "UNIX" });
13639
13655
  }
@@ -14013,7 +14029,7 @@ var internetSearchTool = new ExuluTool({
14013
14029
  } catch (error) {
14014
14030
  if (error instanceof Perplexity.RateLimitError && attempt < maxRetries - 1) {
14015
14031
  const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
14016
- await new Promise((resolve4) => setTimeout(resolve4, delay));
14032
+ await new Promise((resolve3) => setTimeout(resolve3, delay));
14017
14033
  continue;
14018
14034
  }
14019
14035
  throw error;
@@ -15507,11 +15523,11 @@ function excerptFor(windows3, sentenceTexts) {
15507
15523
  const body = [...byIndex.entries()].sort((a, b) => a[0] - b[0]).map(([, text]) => text).join(" ");
15508
15524
  const sections = [];
15509
15525
  for (const w of windows3) {
15510
- const path2 = w.sentence.headingPath.filter(Boolean).join(" > ");
15511
- if (path2 && !sections.includes(path2)) sections.push(path2);
15526
+ const path = w.sentence.headingPath.filter(Boolean).join(" > ");
15527
+ if (path && !sections.includes(path)) sections.push(path);
15512
15528
  }
15513
15529
  if (sections.length === 0) return body;
15514
- return `${sections.map((path2) => `Section: ${path2}`).join("\n")}
15530
+ return `${sections.map((path) => `Section: ${path}`).join("\n")}
15515
15531
 
15516
15532
  ${body}`;
15517
15533
  }
@@ -16770,7 +16786,7 @@ See docs/superpowers/specs/2026-05-31-in-chat-image-generation-design.md for the
16770
16786
  import { resolve as resolvePath } from "path";
16771
16787
 
16772
16788
  // src/exulu/litellm/passthrough-allowlist.ts
16773
- var isLiteLLMPassthroughPathAllowed = (path2) => path2.startsWith("/v1/") || path2 === "/model/info";
16789
+ var isLiteLLMPassthroughPathAllowed = (path) => path.startsWith("/v1/") || path === "/model/info";
16774
16790
 
16775
16791
  // src/exulu/litellm/usage-view.ts
16776
16792
  var DAY_MS = 24 * 60 * 60 * 1e3;
@@ -17485,8 +17501,8 @@ can create an API key at \`<base_url>/token\`.
17485
17501
  var REQUEST_SIZE_LIMIT = "50mb";
17486
17502
  var getExuluVersionNumber = async () => {
17487
17503
  try {
17488
- const path2 = process.cwd();
17489
- const packageJson = fs2.readFileSync(path2 + "/package.json", "utf8");
17504
+ const path = process.cwd();
17505
+ const packageJson = fs2.readFileSync(path + "/package.json", "utf8");
17490
17506
  const packageData = JSON.parse(packageJson);
17491
17507
  const exuluVersion = packageData.dependencies["@exulu/backend"];
17492
17508
  console.log(`[EXULU] Installed exulu-backend version: ${exuluVersion}`);
@@ -20687,35 +20703,35 @@ ${style.markdown}` : params.prompt;
20687
20703
  const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".txt", ".py", ".js", ".ts", ".json", ".yaml", ".yml", ".sh", ".toml"]);
20688
20704
  const MAX_DIFF_BYTES = 500 * 1024;
20689
20705
  const fileDiffs = await Promise.all(
20690
- [...allPaths].map(async (path2) => {
20691
- const inFrom = fromMap.has(path2);
20692
- const inTo = toMap.has(path2);
20706
+ [...allPaths].map(async (path) => {
20707
+ const inFrom = fromMap.has(path);
20708
+ const inTo = toMap.has(path);
20693
20709
  const status = !inFrom ? "added" : !inTo ? "removed" : "modified";
20694
20710
  if (status === "modified") {
20695
- const ext = path2.slice(path2.lastIndexOf(".")).toLowerCase();
20711
+ const ext = path.slice(path.lastIndexOf(".")).toLowerCase();
20696
20712
  if (!TEXT_EXTENSIONS.has(ext)) {
20697
- return { path: path2, status };
20713
+ return { path, status };
20698
20714
  }
20699
20715
  try {
20700
20716
  const [fromContent, toContent] = await Promise.all([
20701
- getS3ObjectContent(s3Prefix + fromPrefix + path2, config),
20702
- getS3ObjectContent(s3Prefix + toPrefix + path2, config)
20717
+ getS3ObjectContent(s3Prefix + fromPrefix + path, config),
20718
+ getS3ObjectContent(s3Prefix + toPrefix + path, config)
20703
20719
  ]);
20704
20720
  if (fromContent === toContent) {
20705
- return { path: path2, status: "unchanged" };
20721
+ return { path, status: "unchanged" };
20706
20722
  }
20707
20723
  if (fromContent.length + toContent.length > MAX_DIFF_BYTES) {
20708
- return { path: path2, status };
20724
+ return { path, status };
20709
20725
  }
20710
20726
  const fromLines = fromContent.split("\n");
20711
20727
  const toLines = toContent.split("\n");
20712
- const diff = buildUnifiedDiff(fromLines, toLines, `v${fromVersion}/${path2}`, `v${toVersion}/${path2}`);
20713
- return { path: path2, status, diff };
20728
+ const diff = buildUnifiedDiff(fromLines, toLines, `v${fromVersion}/${path}`, `v${toVersion}/${path}`);
20729
+ return { path, status, diff };
20714
20730
  } catch {
20715
- return { path: path2, status };
20731
+ return { path, status };
20716
20732
  }
20717
20733
  }
20718
- return { path: path2, status };
20734
+ return { path, status };
20719
20735
  })
20720
20736
  );
20721
20737
  res.json({
@@ -23109,6 +23125,17 @@ var ExuluApp = class {
23109
23125
  if (!license["queues"] && queues.list.size > 0) {
23110
23126
  throw new Error(`[EXULU] You are not licensed to use queues but have registered the following queues: ${Array.from(queues.list.keys()).join(", ")}. Please set your EXULU_ENTERPRISE_LICENSE env variable.`);
23111
23127
  }
23128
+ const attachmentProblems = validateAttachmentsConfig(config, license);
23129
+ if (attachmentProblems.length > 0) {
23130
+ throw new Error(`[EXULU] Invalid attachments.documentProcessor config:
23131
+ - ${attachmentProblems.join("\n- ")}`);
23132
+ }
23133
+ if (config?.attachments?.documentProcessor) {
23134
+ const { processor, vlm } = config.attachments.documentProcessor;
23135
+ console.log(`[EXULU] Attachments: OCR via ${processor.name}${processor.model ? ` (${processor.model})` : ""}${vlm ? `, VLM ${vlm.model} (concurrency ${vlm.concurrency})` : ", no VLM pass"}.`);
23136
+ } else {
23137
+ console.log("[EXULU] Attachments: text layer only (officeparser); set attachments.documentProcessor for OCR + VLM.");
23138
+ }
23112
23139
  if (redisServer.host?.length && redisServer.port?.length) {
23113
23140
  queues.register(
23114
23141
  global_queues.eval_runs,
@@ -25411,932 +25438,6 @@ var MarkdownChunker = class {
25411
25438
  }
25412
25439
  };
25413
25440
 
25414
- // ee/python/documents/processing/doc_processor.ts
25415
- import * as fs3 from "fs";
25416
- import * as path from "path";
25417
- import { generateText as generateText8, Output as Output3 } from "ai";
25418
- import { z as z19 } from "zod";
25419
- import pLimit from "p-limit";
25420
- import { randomUUID as randomUUID12 } from "crypto";
25421
- import * as mammoth from "mammoth";
25422
- import TurndownService from "turndown";
25423
- import WordExtractor from "word-extractor";
25424
- import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
25425
-
25426
- // src/utils/python-executor.ts
25427
- import { exec } from "child_process";
25428
- import { promisify as promisify2 } from "util";
25429
- import { resolve as resolve3, join as join2, dirname } from "path";
25430
- import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
25431
- import { fileURLToPath } from "url";
25432
- var execAsync = promisify2(exec);
25433
- function getPackageRoot2() {
25434
- const currentFile = fileURLToPath(import.meta.url);
25435
- let currentDir = dirname(currentFile);
25436
- let attempts = 0;
25437
- const maxAttempts = 10;
25438
- while (attempts < maxAttempts) {
25439
- const packageJsonPath = join2(currentDir, "package.json");
25440
- if (existsSync5(packageJsonPath)) {
25441
- try {
25442
- const packageJson = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
25443
- if (packageJson.name === "@exulu/backend") {
25444
- return currentDir;
25445
- }
25446
- } catch {
25447
- }
25448
- }
25449
- const parentDir = resolve3(currentDir, "..");
25450
- if (parentDir === currentDir) {
25451
- break;
25452
- }
25453
- currentDir = parentDir;
25454
- attempts++;
25455
- }
25456
- return resolve3(dirname(fileURLToPath(import.meta.url)), "../..");
25457
- }
25458
- var PythonEnvironmentError = class extends Error {
25459
- constructor(message) {
25460
- super(message);
25461
- this.name = "PythonEnvironmentError";
25462
- }
25463
- };
25464
- var PythonExecutionError = class extends Error {
25465
- stdout;
25466
- stderr;
25467
- exitCode;
25468
- constructor(message, stdout, stderr, exitCode) {
25469
- super(message);
25470
- this.name = "PythonExecutionError";
25471
- this.stdout = stdout;
25472
- this.stderr = stderr;
25473
- this.exitCode = exitCode;
25474
- }
25475
- };
25476
- function getVenvPath(packageRoot) {
25477
- return resolve3(packageRoot, "ee/python/.venv");
25478
- }
25479
- function getPythonExecutable(packageRoot) {
25480
- const venvPath = getVenvPath(packageRoot);
25481
- return join2(venvPath, "bin", "python");
25482
- }
25483
- async function validatePythonEnvironmentForExecution(packageRoot) {
25484
- const validation = await validatePythonEnvironment(packageRoot);
25485
- if (!validation.valid) {
25486
- throw new PythonEnvironmentError(validation.message);
25487
- }
25488
- }
25489
- async function executePythonScript(config) {
25490
- const {
25491
- scriptPath,
25492
- args = [],
25493
- packageRoot = getPackageRoot2(),
25494
- cwd = process.cwd(),
25495
- timeout = 3e5,
25496
- // 5 minutes default
25497
- env = {},
25498
- validateEnvironment = true
25499
- } = config;
25500
- if (validateEnvironment) {
25501
- await validatePythonEnvironmentForExecution(packageRoot);
25502
- }
25503
- const resolvedScriptPath = resolve3(packageRoot, scriptPath);
25504
- if (!existsSync5(resolvedScriptPath)) {
25505
- throw new PythonExecutionError(
25506
- `Python script not found: ${resolvedScriptPath}`,
25507
- "",
25508
- "",
25509
- 1
25510
- );
25511
- }
25512
- const pythonExecutable = getPythonExecutable(packageRoot);
25513
- const quotedArgs = args.map((arg) => {
25514
- return arg.includes(" ") ? `"${arg}"` : arg;
25515
- });
25516
- const command = `${pythonExecutable} "${resolvedScriptPath}" ${quotedArgs.join(" ")}`;
25517
- try {
25518
- const { stdout, stderr } = await execAsync(command, {
25519
- cwd,
25520
- timeout,
25521
- env: {
25522
- ...process.env,
25523
- ...env,
25524
- // Ensure Python doesn't write bytecode files
25525
- PYTHONDONTWRITEBYTECODE: "1"
25526
- },
25527
- maxBuffer: 50 * 1024 * 1024
25528
- // 50MB buffer for output (increased from 10MB)
25529
- });
25530
- return {
25531
- stdout: stdout.trim(),
25532
- stderr: stderr.trim(),
25533
- exitCode: 0,
25534
- success: true
25535
- };
25536
- } catch (error) {
25537
- const stdout = error.stdout?.toString() ?? "";
25538
- const stderr = error.stderr?.toString() ?? "";
25539
- const exitCode = error.code ?? 1;
25540
- let errorMessage = `Python script execution failed: ${error.message}`;
25541
- if (stderr) {
25542
- errorMessage += `
25543
-
25544
- Stderr:
25545
- ${stderr}`;
25546
- }
25547
- if (stdout) {
25548
- errorMessage += `
25549
-
25550
- Stdout:
25551
- ${stdout}`;
25552
- }
25553
- errorMessage += `
25554
-
25555
- Command executed:
25556
- ${command}`;
25557
- throw new PythonExecutionError(
25558
- errorMessage,
25559
- stdout,
25560
- stderr,
25561
- exitCode
25562
- );
25563
- }
25564
- }
25565
-
25566
- // ee/python/documents/processing/doc_processor.ts
25567
- import { LiteParse } from "@llamaindex/liteparse";
25568
-
25569
- // src/exulu/resolve-ocr.ts
25570
- var ResolveOcrError = class extends Error {
25571
- constructor(code, message) {
25572
- super(message);
25573
- this.code = code;
25574
- this.name = "ResolveOcrError";
25575
- }
25576
- };
25577
- async function resolveOcr(input) {
25578
- const { model, contextId, contextName, user, userId, roleId, project, agent, routine } = input;
25579
- if (!isLiteLLMEnabled()) {
25580
- throw new ResolveOcrError(
25581
- "LITELLM_NOT_CONFIGURED",
25582
- "resolveOcr requires EXULU_USE_LITELLM=true \u2014 OCR is served exclusively through the LiteLLM proxy."
25583
- );
25584
- }
25585
- try {
25586
- await waitForLiteLLMReady();
25587
- } catch (err2) {
25588
- throw new ResolveOcrError(
25589
- "LITELLM_NOT_READY",
25590
- `LiteLLM is not ready: ${err2.message}`
25591
- );
25592
- }
25593
- const { baseUrl, authHeaders } = resolveLiteLLMTarget();
25594
- const resolvedUserId = user?.id ?? userId;
25595
- if (resolvedUserId) await provisionDefaultUserBudget(resolvedUserId);
25596
- const role = user?.role;
25597
- const tags = buildTags({
25598
- user_id: resolvedUserId,
25599
- role_id: role?.id ?? roleId,
25600
- project_id: (project ?? user?.project)?.id,
25601
- agent_id: agent?.id,
25602
- team_id: user?.team?.id,
25603
- routine_id: routine?.id,
25604
- context_id: contextId,
25605
- user_name: !user ? void 0 : user.type === "api" ? user.firstname ?? user.email : user.email,
25606
- role_name: role?.name,
25607
- project_name: (project ?? user?.project)?.name,
25608
- agent_name: agent?.name,
25609
- team_name: user?.team?.name,
25610
- routine_name: routine?.name,
25611
- context_name: contextName
25612
- });
25613
- const endpoint = `${baseUrl}/v1/ocr`;
25614
- const ocr = async (document, opts) => {
25615
- const res = await fetch(endpoint, {
25616
- method: "POST",
25617
- headers: {
25618
- ...authHeaders,
25619
- "Content-Type": "application/json"
25620
- },
25621
- body: JSON.stringify({
25622
- model,
25623
- document,
25624
- // Mistral OCR optional params — only sent when provided.
25625
- ...opts?.pages ? { pages: opts.pages } : {},
25626
- ...opts?.includeImageBase64 !== void 0 ? { include_image_base64: opts.includeImageBase64 } : {},
25627
- ...opts?.imageLimit !== void 0 ? { image_limit: opts.imageLimit } : {},
25628
- ...opts?.imageMinSize !== void 0 ? { image_min_size: opts.imageMinSize } : {},
25629
- // LiteLLM reads metadata.tags for tag-based spend tracking — same
25630
- // mechanism createTaggedFetch / resolveEmbedder use.
25631
- metadata: { tags }
25632
- })
25633
- });
25634
- if (!res.ok) {
25635
- const text = await res.text().catch(() => "");
25636
- throw new Error(
25637
- `[EXULU] LiteLLM /v1/ocr returned ${res.status} for model "${model}": ${text}`
25638
- );
25639
- }
25640
- const json = await res.json();
25641
- if (!Array.isArray(json.pages)) {
25642
- throw new Error(
25643
- `[EXULU] LiteLLM /v1/ocr returned no pages for model "${model}".`
25644
- );
25645
- }
25646
- return json;
25647
- };
25648
- return { model, ocr };
25649
- }
25650
-
25651
- // ee/python/documents/processing/doc_processor.ts
25652
- async function processDocx(file) {
25653
- const html = await mammoth.convertToHtml({ buffer: file });
25654
- const turndownService = new TurndownService();
25655
- let markdown = turndownService.turndown(html.value);
25656
- markdown = markdown.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
25657
- return {
25658
- json: [{
25659
- page: 1,
25660
- content: markdown,
25661
- headings: []
25662
- }],
25663
- markdown
25664
- };
25665
- }
25666
- async function processWord(file) {
25667
- const extractor = new WordExtractor();
25668
- const extracted = await extractor.extract(file);
25669
- let content = extracted.getBody();
25670
- content = content.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
25671
- return {
25672
- json: [{
25673
- page: 1,
25674
- content,
25675
- headings: []
25676
- }],
25677
- markdown: content
25678
- };
25679
- }
25680
- async function resolveVlmModel(config) {
25681
- const modelId = config?.vlm?.model;
25682
- if (!modelId) return void 0;
25683
- const { languageModel } = await resolveModel({
25684
- modelId,
25685
- user: config?.attribution?.user,
25686
- project: config?.attribution?.project,
25687
- agent: config?.attribution?.agent,
25688
- routine: config?.attribution?.routine,
25689
- rbacBypass: true
25690
- });
25691
- return languageModel;
25692
- }
25693
- async function processImage(buffer, paths, config, verbose = false) {
25694
- try {
25695
- await fs3.promises.mkdir(paths.images, { recursive: true });
25696
- const imagePath = path.join(paths.images, "1.png");
25697
- await fs3.promises.writeFile(imagePath, buffer);
25698
- console.log(`[EXULU] Image saved to: ${imagePath}`);
25699
- let json = [{
25700
- page: 1,
25701
- content: "",
25702
- // Empty initially, will be populated by VLM if enabled
25703
- image: imagePath,
25704
- headings: []
25705
- }];
25706
- const vlmModel = await resolveVlmModel(config);
25707
- if (vlmModel) {
25708
- console.log("[EXULU] Extracting content from image using VLM...");
25709
- json = await validateWithVLM(
25710
- json,
25711
- vlmModel,
25712
- verbose,
25713
- config.vlm.concurrency
25714
- );
25715
- await fs3.promises.writeFile(
25716
- paths.json,
25717
- JSON.stringify(json, null, 2),
25718
- "utf-8"
25719
- );
25720
- console.log("[EXULU] VLM content extraction complete");
25721
- const correctedCount = json.filter((p) => p.vlm_corrected_text).length;
25722
- console.log(`[EXULU] Content extracted: ${correctedCount > 0 ? "Yes" : "No"}`);
25723
- } else {
25724
- console.log("[EXULU] No VLM configured, image saved without content extraction");
25725
- console.log("[EXULU] Note: Enable VLM in config to extract text/content from images");
25726
- await fs3.promises.writeFile(
25727
- paths.json,
25728
- JSON.stringify(json, null, 2),
25729
- "utf-8"
25730
- );
25731
- }
25732
- const markdown = json.map((p) => p.vlm_corrected_text ?? p.content).join("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
25733
- await fs3.promises.writeFile(paths.markdown, markdown, "utf-8");
25734
- return {
25735
- markdown,
25736
- json
25737
- };
25738
- } catch (error) {
25739
- console.error("[EXULU] Error processing image:", error);
25740
- throw error;
25741
- }
25742
- }
25743
- function normalizeMarkdownContent(content) {
25744
- const lines = content.split("\n");
25745
- const normalizedLines = [];
25746
- for (const line of lines) {
25747
- if (line.includes("|")) {
25748
- const parts = line.split("|");
25749
- const cleanedParts = parts.map((part) => part.trim());
25750
- const normalizedLine = cleanedParts.join(" | ");
25751
- normalizedLines.push(normalizedLine);
25752
- } else {
25753
- normalizedLines.push(line.trimEnd());
25754
- }
25755
- }
25756
- return normalizedLines.join("\n");
25757
- }
25758
- function reconstructHeadings(correctedText, headingsHierarchy) {
25759
- if (!headingsHierarchy || typeof headingsHierarchy !== "object") {
25760
- return correctedText;
25761
- }
25762
- let result = correctedText;
25763
- function extractHeadingsWithLevels(hierarchy, level = 2) {
25764
- const headings2 = [];
25765
- for (const [key, value] of Object.entries(hierarchy)) {
25766
- headings2.push({ text: key, level });
25767
- if (value && typeof value === "object") {
25768
- headings2.push(...extractHeadingsWithLevels(value, level + 1));
25769
- }
25770
- }
25771
- return headings2;
25772
- }
25773
- const headings = extractHeadingsWithLevels(headingsHierarchy);
25774
- for (const { text, level } of headings) {
25775
- const markdownPrefix = "#".repeat(level);
25776
- const escapedText = text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
25777
- const regex = new RegExp(
25778
- `^(${escapedText})$`,
25779
- "gm"
25780
- );
25781
- result = result.replace(regex, `${markdownPrefix} $1`);
25782
- }
25783
- return result;
25784
- }
25785
- async function validatePageWithVLM(page, imagePath, model) {
25786
- const imageBuffer = await fs3.promises.readFile(imagePath);
25787
- const imageBase64 = imageBuffer.toString("base64");
25788
- const mimeType = "image/png";
25789
- const prompt = `You are a document validation assistant. Your task is to analyze a page image and correct the output of an OCR/parsing pipeline. The content may include tables, technical diagrams, schematics, and structured text.
25790
-
25791
- ---
25792
- ## CURRENT OCR OUTPUT
25793
-
25794
- ${page.content}
25795
- ---
25796
-
25797
- ## YOUR TASK
25798
-
25799
- Compare the page image to the OCR output above. Identify errors, omissions, and formatting issues, then return a structured validation result (see OUTPUT FORMAT below).
25800
-
25801
- ---
25802
- ## VALIDATION CHECKLIST
25803
-
25804
- Work through these checks in order:
25805
-
25806
- ### 1. Text Accuracy
25807
- - Verify all text is correctly transcribed.
25808
- - For minor character-level OCR errors (e.g. "\xF6" vs "\xFC", "rn" vs "m"), **prefer the original OCR output** unless you are certain of an error. Do not silently "fix" characters based on guesswork.
25809
-
25810
- ### 2. Heading Levels
25811
- - Verify that headings use correct Markdown levels (#, ##, ###, ####, #####, ######).
25812
- - Determine heading level using the following priority:
25813
- 1. **Hierarchical numbering** (strongest signal): e.g. "1" \u2192 #, "2.1" \u2192 ##, "2.1.1" \u2192 ###, "2.1.2.5" \u2192 ####
25814
- 2. Font size (larger = higher level)
25815
- 3. Indentation
25816
- 4. Bold/emphasis styling
25817
-
25818
- ### 3. Tables
25819
-
25820
- **First, decide whether the table should be Markdown or plain text:**
25821
- - Use **Markdown table format** if the table has a consistent, clear header structure and uniform column layout throughout.
25822
- - Use **plain text structured description** if the table:
25823
- - Lacks a clear header row
25824
- - Uses mixed or irregular column structures across rows
25825
- - Functions more like a certificate, form, or label layout
25826
-
25827
- **If using Markdown format**, follow these rules strictly:
25828
- - Every table must have: header row \u2192 separator row \u2192 data rows
25829
- - Use simple separators only: \`| --- | --- |\` (NOT \`|---|---|\` or long dashes)
25830
- - Example:
25831
- \`\`\`
25832
- | Column 1 | Column 2 |
25833
- | --- | --- |
25834
- | Data 1 | Data 2 |
25835
- \`\`\`
25836
- - Important: do not use the | character as part of the data inside a cell, this would break the table, if a cell contains a | character, use a capital I.
25837
-
25838
- **Symbol translation rules for table cells:**
25839
- - Black/filled dot \u2192 \`+\` (active); White/empty dot \u2192 \`-\` (inactive)
25840
- *(e.g. Rufe-LED columns)*
25841
- - Green or black checkmark \u2192 \`+\` (active); Red or black cross \u2192 \`-\` (inactive)
25842
-
25843
- ### 4. Multi-Page Table Continuity
25844
- - If this page contains a table with a header row that runs to the bottom of the page (suggesting it may continue on the next page), extract the header row and include it in the \`current_page_table.headers\` field.
25845
- - If this page contains a table WITHOUT a header row (suggesting it's a continuation from a previous page), set \`current_page_table.is_continuation\` to true and try to identify what the headers might be based on the data structure. Include your best guess for headers in \`current_page_table.headers\`.
25846
-
25847
- ### 5. Technical Diagrams & Schematics
25848
- If the page contains a flow-chart, schematic, technical drawing or control board layout that is **absent or poorly described** in the OCR output do the following:
25849
- - Open a <diagram> tag with the following content:
25850
- <diagram>
25851
- <description>
25852
- Add a detailed description of the diagram here.
25853
- </description>
25854
- <mermaid>
25855
- Add a mermaid diagram schema here that in detail describes the diagram.
25856
- </mermaid>
25857
- </diagram>
25858
-
25859
- ### 6. Captions, Icons & Symbols
25860
- - Verify that image captions, labels, icons, and checkmarks are present and correctly transcribed.
25861
-
25862
- ### 7. Only populate \`corrected_text\` when \`needs_correction\` is true. If the OCR output is accurate, return \`needs_correction: false\` and \`corrected_content: null\`.
25863
- `;
25864
- const result = await generateText8({
25865
- model,
25866
- output: Output3.object({
25867
- schema: z19.object({
25868
- needs_correction: z19.boolean(),
25869
- corrected_text: z19.string().nullable(),
25870
- current_page_table: z19.object({
25871
- headers: z19.array(z19.string()),
25872
- is_continuation: z19.boolean()
25873
- }).nullable(),
25874
- confidence: z19.enum(["high", "medium", "low"]),
25875
- reasoning: z19.string()
25876
- })
25877
- }),
25878
- messages: [
25879
- {
25880
- role: "user",
25881
- content: [
25882
- { type: "text", text: prompt },
25883
- {
25884
- type: "image",
25885
- image: `data:${mimeType};base64,${imageBase64}`
25886
- }
25887
- ]
25888
- }
25889
- ]
25890
- });
25891
- const parsedOutput = result.output;
25892
- const validation = {
25893
- needs_correction: parsedOutput.needs_correction,
25894
- corrected_text: parsedOutput.corrected_text || void 0,
25895
- confidence: parsedOutput.confidence,
25896
- current_page_table: parsedOutput.current_page_table || void 0,
25897
- reasoning: parsedOutput.reasoning
25898
- };
25899
- console.log(`[EXULU] VLM validation result: ${JSON.stringify(validation)}`);
25900
- return validation;
25901
- }
25902
- function reconstructTableHeaders(document, validationResults, verbose = false) {
25903
- let lastTableHeaders = void 0;
25904
- for (const page of document) {
25905
- const validation = validationResults.get(page.page);
25906
- if (!validation) continue;
25907
- const tableInfo = validation.current_page_table;
25908
- if (tableInfo && tableInfo.headers.length > 0) {
25909
- if (tableInfo.is_continuation && lastTableHeaders) {
25910
- if (verbose) {
25911
- console.log(`[EXULU] Page ${page.page}: Reconstructing table headers from previous page`);
25912
- console.log(`[EXULU] Previous headers: ${lastTableHeaders.join(" | ")}`);
25913
- }
25914
- const contentToModify = page.vlm_corrected_text || page.content;
25915
- const lines = contentToModify.split("\n");
25916
- const firstTableLineIndex = lines.findIndex((line) => line.trim().startsWith("|"));
25917
- if (firstTableLineIndex !== -1) {
25918
- const headerRow = `| ${lastTableHeaders.join(" | ")} |`;
25919
- const separatorRow = `| ${lastTableHeaders.map(() => "---").join(" | ")} |`;
25920
- lines.splice(firstTableLineIndex, 0, headerRow, separatorRow);
25921
- const reconstructedContent = lines.join("\n");
25922
- if (page.vlm_corrected_text) {
25923
- page.vlm_corrected_text = reconstructedContent;
25924
- } else {
25925
- page.content = reconstructedContent;
25926
- }
25927
- if (verbose) {
25928
- console.log(`[EXULU] Page ${page.page}: Added table headers successfully`);
25929
- }
25930
- }
25931
- if (!tableInfo.is_continuation) {
25932
- lastTableHeaders = tableInfo.headers;
25933
- }
25934
- } else {
25935
- lastTableHeaders = tableInfo.headers;
25936
- if (verbose) {
25937
- console.log(`[EXULU] Page ${page.page}: Storing table headers for potential continuation`);
25938
- console.log(`[EXULU] Headers: ${lastTableHeaders.join(" | ")}`);
25939
- }
25940
- }
25941
- } else {
25942
- lastTableHeaders = void 0;
25943
- }
25944
- }
25945
- }
25946
- async function validateWithVLM(document, model, verbose = false, concurrency = 10) {
25947
- console.log(`[EXULU] Starting VLM validation for processor output, ${document.length} pages...`);
25948
- console.log(`[EXULU] Concurrency limit: ${concurrency}`);
25949
- const limit = pLimit(concurrency);
25950
- const validationResults = /* @__PURE__ */ new Map();
25951
- let validatedCount = 0;
25952
- let correctedCount = 0;
25953
- const validationTasks = document.map(
25954
- (page) => limit(async () => {
25955
- await new Promise((resolve4) => setImmediate(resolve4));
25956
- const imagePath = page.image;
25957
- if (!imagePath) {
25958
- console.warn(`[EXULU] Page ${page.page}: No image found, skipping validation`);
25959
- return;
25960
- }
25961
- if (page.content) {
25962
- const hasImage = page.content.match(/\.(jpeg|jpg|png|gif|webp)/i);
25963
- const hasTable = (page.content.match(/\|/g)?.length || 0) > 1;
25964
- if (!hasImage && !hasTable) {
25965
- if (verbose) {
25966
- console.log(`[EXULU] Page ${page.page}: No image or table found, SKIPPING VLM validation`);
25967
- }
25968
- return;
25969
- }
25970
- } else {
25971
- if (verbose) {
25972
- console.log(`[EXULU] Page ${page.page}: Standalone image, proceeding with VLM content extraction`);
25973
- }
25974
- }
25975
- let validation;
25976
- try {
25977
- console.log(`[EXULU] Validating page ${page.page} with VLM`);
25978
- validation = await withRetry(async () => {
25979
- return await validatePageWithVLM(page, imagePath, model);
25980
- }, 3);
25981
- validationResults.set(page.page, validation);
25982
- if (verbose && validation.current_page_table) {
25983
- console.log(`[EXULU] Page ${page.page} table info:`, {
25984
- headers: validation.current_page_table.headers,
25985
- is_continuation: validation.current_page_table.is_continuation
25986
- });
25987
- }
25988
- } catch (error) {
25989
- console.error(`[EXULU] Error validating page ${page.page} with VLM more than 3 times, skipping:`, error);
25990
- throw error;
25991
- }
25992
- if (validation.needs_correction && validation.corrected_text) {
25993
- page.vlm_validated = true;
25994
- const normalizedText = normalizeMarkdownContent(validation.corrected_text);
25995
- const correctedWithHeadings = reconstructHeadings(
25996
- normalizedText,
25997
- page.headings
25998
- );
25999
- page.vlm_corrected_text = correctedWithHeadings;
26000
- correctedCount++;
26001
- if (verbose) {
26002
- console.log(
26003
- `[EXULU] Page ${page.page}: Corrected (${validation.confidence} confidence)`
26004
- );
26005
- console.log(`[EXULU] Reason: ${validation.reasoning}`);
26006
- }
26007
- } else {
26008
- if (verbose) {
26009
- console.log(
26010
- `[EXULU] Page ${page.page}: No correction needed (${validation.confidence} confidence)`
26011
- );
26012
- }
26013
- }
26014
- validatedCount++;
26015
- })
26016
- );
26017
- await Promise.all(validationTasks);
26018
- console.log(`[EXULU] VLM validation complete (parallel processing):`);
26019
- console.log(`[EXULU] Validated: ${validatedCount} pages`);
26020
- console.log(`[EXULU] Corrected: ${correctedCount} pages`);
26021
- console.log(`[EXULU] Starting sequential table header reconstruction...`);
26022
- reconstructTableHeaders(document, validationResults, verbose);
26023
- console.log(`[EXULU] Table header reconstruction complete`);
26024
- return document;
26025
- }
26026
- async function processDocument(filePath, fileType, buffer, tempDir, config, verbose = false) {
26027
- console.log("Starting document processing...");
26028
- console.log(`${fileType}: ${filePath}`);
26029
- const paths = {
26030
- json: path.join(tempDir, `processed.json`),
26031
- markdown: path.join(tempDir, `markdown.md`),
26032
- images: path.join(tempDir, "images"),
26033
- source: filePath
26034
- };
26035
- const stripped = filePath.split(".").pop()?.trim().toLowerCase();
26036
- let result;
26037
- switch (stripped) {
26038
- case "txt":
26039
- case "md":
26040
- let content = buffer.toString();
26041
- content = content.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
26042
- result = {
26043
- markdown: content,
26044
- json: [{
26045
- page: 1,
26046
- content,
26047
- headings: []
26048
- }]
26049
- };
26050
- break;
26051
- case "pdf":
26052
- result = await processPdf(buffer, paths, config, verbose);
26053
- break;
26054
- case "docx":
26055
- result = await processDocx(buffer);
26056
- break;
26057
- case "doc":
26058
- result = await processWord(buffer);
26059
- break;
26060
- case "jpg":
26061
- case "jpeg":
26062
- case "png":
26063
- case "gif":
26064
- case "webp":
26065
- result = await processImage(buffer, paths, config, verbose);
26066
- break;
26067
- // Todo other file types with docx and officeparser
26068
- default:
26069
- throw new Error(`[EXULU] Unsupported file type: ${fileType}`);
26070
- }
26071
- return {
26072
- content: result,
26073
- files: {
26074
- markdown: paths.markdown,
26075
- json: paths.json
26076
- }
26077
- };
26078
- }
26079
- async function processPdf(buffer, paths, config, verbose = false) {
26080
- try {
26081
- let json = [];
26082
- if (config?.processor.name === "officeparser") {
26083
- const text = await parseOfficeAsync2(buffer, {
26084
- outputErrorToConsole: false,
26085
- newlineDelimiter: "\n"
26086
- });
26087
- json = [{
26088
- page: 1,
26089
- content: text,
26090
- headings: []
26091
- }];
26092
- } else if (config?.processor.name === "mistral") {
26093
- const resolved = await resolveOcr({
26094
- model: config.processor.model ?? "mistral-ocr",
26095
- ...config.attribution
26096
- });
26097
- const maxPagesPerChunk = config.processor.maxPagesPerChunk ?? 25;
26098
- const chunksDir = path.join(path.dirname(paths.json), "ocr_chunks");
26099
- const splitResult = await executePythonScript({
26100
- scriptPath: "ee/python/documents/processing/split_pdf.py",
26101
- args: [paths.source, chunksDir, "--chunk-size", String(maxPagesPerChunk), "--max-size-mb", "25"],
26102
- timeout: 5 * 60 * 1e3
26103
- });
26104
- let pdfChunks;
26105
- try {
26106
- pdfChunks = JSON.parse(splitResult.stdout);
26107
- } catch (err2) {
26108
- throw new Error(
26109
- `[EXULU] split_pdf.py returned invalid JSON on stdout: ${err2.message}
26110
- stdout: ${splitResult.stdout.slice(0, 500)}
26111
- stderr: ${splitResult.stderr.slice(-1e3)}`
26112
- );
26113
- }
26114
- console.log(`[EXULU] PDF split into ${pdfChunks.length} chunk(s) for OCR (max ${maxPagesPerChunk} pages each)`);
26115
- const chunkLimit = pLimit(3);
26116
- const chunkResults = await Promise.all(
26117
- pdfChunks.map(
26118
- (chunk2, i) => chunkLimit(async () => {
26119
- await new Promise((resolve4) => setImmediate(resolve4));
26120
- await new Promise((resolve4) => setTimeout(resolve4, Math.floor(Math.random() * 1e3) + 200));
26121
- console.log(`[EXULU] OCR chunk ${i + 1}/${pdfChunks.length}: pages ${chunk2.start_page}\u2013${chunk2.end_page - 1}`);
26122
- const chunkBuffer = await fs3.promises.readFile(chunk2.path);
26123
- const chunkBase64 = chunkBuffer.toString("base64");
26124
- const chunkResponse = await withRetry(async () => {
26125
- return await resolved.ocr({
26126
- type: "document_url",
26127
- document_url: "data:application/pdf;base64," + chunkBase64
26128
- }, { includeImageBase64: false });
26129
- }, 10);
26130
- return { pages: chunkResponse.pages, offset: chunk2.start_page };
26131
- })
26132
- )
26133
- );
26134
- const mergedPages = chunkResults.sort((a, b) => a.offset - b.offset).flatMap(
26135
- ({ pages, offset }) => pages.map((p) => ({ ...p, index: p.index + offset }))
26136
- );
26137
- const parser = new LiteParse();
26138
- const screenshots = await parser.screenshot(paths.source, void 0);
26139
- await fs3.promises.mkdir(paths.images, { recursive: true });
26140
- for (const screenshot of screenshots) {
26141
- await fs3.promises.writeFile(
26142
- path.join(
26143
- paths.images,
26144
- `${screenshot.pageNum}.png`
26145
- ),
26146
- screenshot.imageBuffer
26147
- );
26148
- screenshot.imagePath = path.join(paths.images, `${screenshot.pageNum}.png`);
26149
- }
26150
- json = mergedPages.map((page) => ({
26151
- page: page.index + 1,
26152
- content: page.markdown,
26153
- image: screenshots.find((s) => s.pageNum === page.index + 1)?.imagePath,
26154
- headings: []
26155
- }));
26156
- fs3.writeFileSync(paths.json, JSON.stringify(json, null, 2));
26157
- } else if (config?.processor.name === "liteparse") {
26158
- const parser = new LiteParse();
26159
- const result = await parser.parse(paths.source);
26160
- const screenshots = await parser.screenshot(paths.source, void 0);
26161
- console.log(`[EXULU] Liteparse screenshots: ${JSON.stringify(screenshots)}`);
26162
- await fs3.promises.mkdir(paths.images, { recursive: true });
26163
- for (const screenshot of screenshots) {
26164
- await fs3.promises.writeFile(path.join(paths.images, `${screenshot.pageNum}.png`), screenshot.imageBuffer);
26165
- screenshot.imagePath = path.join(paths.images, `${screenshot.pageNum}.png`);
26166
- }
26167
- json = result.pages.map((page) => ({
26168
- page: page.pageNum,
26169
- content: page.text,
26170
- image: screenshots.find((s) => s.pageNum === page.pageNum)?.imagePath
26171
- }));
26172
- fs3.writeFileSync(paths.json, JSON.stringify(json, null, 2));
26173
- } else {
26174
- const configured = String(config?.processor?.name ?? "");
26175
- throw new Error(
26176
- configured === "" ? "[EXULU] No document processor configured. Set processor.name to one of: mistral, liteparse, officeparser." : `[EXULU] Unknown document processor "${configured}". Supported processors are: mistral, liteparse, officeparser.` + (configured === "docling" ? ' The "docling" processor was removed: it depended on PyMuPDF, which is AGPL-licensed. Use "mistral" for PDF OCR.' : "")
26177
- );
26178
- }
26179
- console.log(`[EXULU]
26180
- \u2713 Document processing completed successfully`);
26181
- console.log(`[EXULU] Total pages: ${json.length}`);
26182
- console.log(`[EXULU] Output file: ${paths.json}`);
26183
- const vlmModel = config?.vlm?.model ? await resolveVlmModel(config) : void 0;
26184
- if (vlmModel && json.length > 0) {
26185
- json = await validateWithVLM(
26186
- json,
26187
- vlmModel,
26188
- verbose,
26189
- config.vlm.concurrency
26190
- );
26191
- console.log("[EXULU] \n\u{1F4CA} Processing Summary:");
26192
- console.log(`[EXULU] Total pages: ${json.length}`);
26193
- const validatedPages = json.filter((p) => p.vlm_validated);
26194
- const correctedPages = json.filter((p) => p.vlm_corrected_text);
26195
- console.log(`[EXULU] VLM validated pages: ${validatedPages.length}`);
26196
- console.log(`[EXULU] VLM corrected pages: ${correctedPages.length}`);
26197
- if (correctedPages.length > 0) {
26198
- console.log("\n\u{1F527} Example Corrections:");
26199
- correctedPages.slice(0, 2).forEach((page) => {
26200
- console.log(`[EXULU]
26201
- Page ${page.page} (Page ${page.page}):`);
26202
- console.log(`[EXULU] Original: ${page.content.substring(0, 150)}...`);
26203
- console.log(`[EXULU] Corrected: ${page.vlm_corrected_text.substring(0, 150)}...`);
26204
- });
26205
- }
26206
- await fs3.promises.writeFile(
26207
- paths.json,
26208
- JSON.stringify(json, null, 2),
26209
- "utf-8"
26210
- );
26211
- }
26212
- const markdownStream = fs3.createWriteStream(paths.markdown, { encoding: "utf-8" });
26213
- for (let i = 0; i < json.length; i++) {
26214
- const p = json[i];
26215
- if (!p) continue;
26216
- const content = p.vlm_corrected_text ?? p.content;
26217
- markdownStream.write(content);
26218
- if (i < json.length - 1) {
26219
- markdownStream.write("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
26220
- }
26221
- }
26222
- await new Promise((resolve4, reject) => {
26223
- markdownStream.end(() => resolve4());
26224
- markdownStream.on("error", reject);
26225
- });
26226
- console.log(`[EXULU] Validated output saved to: ${paths.json}`);
26227
- console.log(`[EXULU] Validated markdown saved to: ${paths.markdown}`);
26228
- const markdown = await fs3.promises.readFile(paths.markdown, "utf-8");
26229
- const processedJson = json.map((e) => {
26230
- const finalContent = e.vlm_corrected_text ?? e.content;
26231
- return {
26232
- page: e.page,
26233
- content: finalContent
26234
- };
26235
- });
26236
- json.length = 0;
26237
- json = [];
26238
- const memUsage = process.memoryUsage();
26239
- console.log(`[EXULU] Memory after document processing: ${Math.round(memUsage.heapUsed / 1024 / 1024)}MB / ${Math.round(memUsage.heapTotal / 1024 / 1024)}MB`);
26240
- return {
26241
- markdown,
26242
- json: processedJson
26243
- };
26244
- } catch (error) {
26245
- console.error("[EXULU] Error processing document:", error);
26246
- throw error;
26247
- }
26248
- }
26249
- var loadFile = async (file, name, tempDir) => {
26250
- let filePath = file;
26251
- let fileType = name?.split(".").pop();
26252
- if (!fileType) {
26253
- throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
26254
- }
26255
- const UUID2 = randomUUID12();
26256
- let buffer;
26257
- if (Buffer.isBuffer(file)) {
26258
- filePath = path.join(tempDir, `${UUID2}.${fileType}`);
26259
- await fs3.promises.writeFile(filePath, file);
26260
- buffer = file;
26261
- } else {
26262
- filePath = filePath.trim();
26263
- if (filePath.startsWith("http")) {
26264
- const response = await fetch(filePath);
26265
- const array = await response.arrayBuffer();
26266
- const tempFilePath = path.join(tempDir, `${UUID2}.${fileType}`);
26267
- await fs3.promises.writeFile(tempFilePath, Buffer.from(array));
26268
- buffer = Buffer.from(array);
26269
- filePath = tempFilePath;
26270
- } else {
26271
- buffer = await fs3.promises.readFile(file);
26272
- }
26273
- }
26274
- return { filePath, fileType, buffer };
26275
- };
26276
- async function documentProcessor({
26277
- file,
26278
- name,
26279
- config
26280
- }) {
26281
- const license = checkLicense();
26282
- if (!license["advanced-document-processing"]) {
26283
- throw new Error("Advanced document processing is an enterprise feature, please add a valid Exulu enterprise license key to use it.");
26284
- }
26285
- const uuid = randomUUID12();
26286
- const tempDir = path.join(process.cwd(), "temp", uuid);
26287
- const localFilesAndFoldersToDelete = [tempDir];
26288
- console.log(`[EXULU] Temporary directory for processing document ${name}: ${tempDir}`);
26289
- await fs3.promises.mkdir(tempDir, { recursive: true });
26290
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
26291
- await fs3.promises.writeFile(path.join(tempDir, "created_at.txt"), timestamp);
26292
- try {
26293
- const {
26294
- filePath,
26295
- fileType,
26296
- buffer
26297
- } = await loadFile(file, name, tempDir);
26298
- let supportedTypes = [];
26299
- switch (config?.processor.name) {
26300
- case "officeparser":
26301
- supportedTypes = ["docx", "pptx", "xlsx", "odt", "odp", "ods", "pdf", "rtf", "csv", "md", "html"];
26302
- break;
26303
- case "liteparse":
26304
- supportedTypes = ["pdf", "doc", "docx", "docm", "odt", "rtf", "ppt", "pptx", "pptm", "odp", "xls", "xlsx", "xlsm", "ods", "csv", "tsv"];
26305
- break;
26306
- case "mistral":
26307
- supportedTypes = ["pdf", "docx", "doc", "txt", "md", "jpg", "jpeg", "png", "gif", "webp"];
26308
- break;
26309
- }
26310
- if (!supportedTypes.includes(fileType.toLowerCase())) {
26311
- throw new Error(`[EXULU] Unsupported file type: ${fileType.toLowerCase()} for Exulu document processor, the ${config?.processor.name} processor only supports the following file types: ${supportedTypes.join(", ")}.`);
26312
- }
26313
- const { content } = await processDocument(
26314
- filePath,
26315
- fileType,
26316
- buffer,
26317
- tempDir,
26318
- config,
26319
- true
26320
- );
26321
- return content.json;
26322
- } catch (error) {
26323
- console.error("Error during chunking:", error);
26324
- throw error;
26325
- } finally {
26326
- if (config?.debugging?.deleteTempFiles !== false) {
26327
- for (const file2 of localFilesAndFoldersToDelete) {
26328
- try {
26329
- await fs3.promises.rm(file2, { recursive: true });
26330
- console.log(`[EXULU] Deleted file or folder: ${file2}`);
26331
- } catch (error) {
26332
- console.error(`[EXULU] Error deleting file or folder: ${file2}`, error);
26333
- console.log(`[EXULU] File or folder still exists: ${file2}`);
26334
- }
26335
- }
26336
- }
26337
- }
26338
- }
26339
-
26340
25441
  // src/exulu/reranker.ts
26341
25442
  async function rerank(input) {
26342
25443
  const { query, items, topN, ...resolveInput } = input;
@@ -26694,12 +25795,12 @@ async function fitContextProjection({
26694
25795
  const basis = randomizedPCA(vectors, dims, Math.min(budget, dims, vectors.length - 1), seed, POWER_ITERATIONS);
26695
25796
  if (basis.length === 0) return empty(`${contextId} has no variance in its embeddings`);
26696
25797
  const reduced = vectors.map((v) => projectComponents(v, mean, basis));
26697
- const spread = reduced.reduce((s, z20) => s + Math.hypot(...Array.from(z20)), 0) / reduced.length;
25798
+ const spread = reduced.reduce((s, z19) => s + Math.hypot(...Array.from(z19)), 0) / reduced.length;
26698
25799
  if (!Number.isFinite(spread) || spread < 1e-8) return empty(`${contextId} has no variance in its embeddings`);
26699
25800
  log6(`fitting ${contextId}: ${vectors.length} vectors, ${dims} dims \u2192 ${basis.length} components`);
26700
25801
  log6(`${contextId}: laying out ${reduced.length} points in 3d (the slow phase)`);
26701
25802
  const umap = (umapFactory ?? defaultUmap)(seed, reduced.length);
26702
- const raw = umap.fit(reduced.map((z20) => Array.from(z20)));
25803
+ const raw = umap.fit(reduced.map((z19) => Array.from(z19)));
26703
25804
  const oriented = rotateLayout(raw, principalRotation(raw, seed));
26704
25805
  const { points: layout, scale } = normalizeLayout(oriented);
26705
25806
  if (!Number.isFinite(scale) || scale <= 0) return empty(`${contextId} produced a degenerate layout (every point in one place)`);
@@ -26784,13 +25885,13 @@ async function backfillCoordinates({
26784
25885
  const raw = parseVector(row.embedding);
26785
25886
  if (raw.length !== projection.dims) continue;
26786
25887
  const known = layout?.get(String(row.id));
26787
- const [x, y, z20] = known ?? applyMap(
25888
+ const [x, y, z19] = known ?? applyMap(
26788
25889
  projectComponents(l2normalize(raw), mean, basis),
26789
25890
  projection.map,
26790
25891
  projection.intercept
26791
25892
  );
26792
25893
  values.push("(?::uuid, ?::real, ?::real, ?::real)");
26793
- bindings.push(row.id, x, y, z20);
25894
+ bindings.push(row.id, x, y, z19);
26794
25895
  }
26795
25896
  if (values.length) {
26796
25897
  await db.raw(