@exulu/backend 5.7.2 → 5.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{catalog-3QLU2G7R.js → catalog-4P3TKOV7.js} +2 -1
- package/dist/chunk-4W3V7IHR.js +1166 -0
- package/dist/chunk-6URU62NI.js +54 -0
- package/dist/{chunk-4PDWNVNT.js → chunk-F534XOQR.js} +3 -50
- package/dist/{chunk-RELZZYVA.js → chunk-NUEM3HMI.js} +460 -1471
- package/dist/chunk-RNZ4IDCT.js +946 -0
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-L6SESYPH.js → convert-exulu-tools-to-ai-sdk-tools-3UCQOIY6.js} +4 -2
- package/dist/doc_processor-E5GCE2ZT.js +10 -0
- package/dist/index.cjs +29618 -29397
- package/dist/index.d.cts +118 -105
- package/dist/index.d.ts +118 -105
- package/dist/index.js +184 -1051
- package/ee/invoke-skills/binary-file-guard.test.ts +0 -0
- package/ee/invoke-skills/binary-file-guard.ts +0 -0
- package/ee/python/documents/processing/doc_processor.ts +3 -3
- package/package.json +1 -1
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-
|
|
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-
|
|
224
|
+
} from "./chunk-6URU62NI.js";
|
|
217
225
|
|
|
218
226
|
// src/index.ts
|
|
219
227
|
import "dotenv/config";
|
|
@@ -4004,13 +4012,13 @@ var MEDIA_TYPE_ALIASES = {
|
|
|
4004
4012
|
};
|
|
4005
4013
|
function fileNameFromUrl(url) {
|
|
4006
4014
|
if (!url) return void 0;
|
|
4007
|
-
let
|
|
4015
|
+
let path;
|
|
4008
4016
|
try {
|
|
4009
|
-
|
|
4017
|
+
path = new URL(url).pathname;
|
|
4010
4018
|
} catch {
|
|
4011
|
-
|
|
4019
|
+
path = url.split("?")[0] ?? "";
|
|
4012
4020
|
}
|
|
4013
|
-
const last =
|
|
4021
|
+
const last = path.split("/").pop() ?? "";
|
|
4014
4022
|
try {
|
|
4015
4023
|
return decodeURIComponent(last) || void 0;
|
|
4016
4024
|
} catch {
|
|
@@ -4319,9 +4327,6 @@ var autoDeclineStaleApprovals = (messages) => {
|
|
|
4319
4327
|
return { messages: reconciled, declined };
|
|
4320
4328
|
};
|
|
4321
4329
|
|
|
4322
|
-
// src/exulu/generate-stream.ts
|
|
4323
|
-
import { parseOfficeAsync } from "officeparser";
|
|
4324
|
-
|
|
4325
4330
|
// src/exulu/auth/guardrail.ts
|
|
4326
4331
|
var CREDENTIAL_GUARDRAIL = `Credential safety:
|
|
4327
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.
|
|
@@ -4601,7 +4606,7 @@ var processFilePartsInMessages = async (messages, offloadCtx) => {
|
|
|
4601
4606
|
};
|
|
4602
4607
|
}
|
|
4603
4608
|
const filename = classified.filename;
|
|
4604
|
-
console.log(`[EXULU] Converting file part to text
|
|
4609
|
+
console.log(`[EXULU] Converting file part to text: ${filename}`);
|
|
4605
4610
|
try {
|
|
4606
4611
|
const response = await fetch(url);
|
|
4607
4612
|
if (!response.ok) {
|
|
@@ -4613,12 +4618,17 @@ var processFilePartsInMessages = async (messages, offloadCtx) => {
|
|
|
4613
4618
|
text: `[Error: Could not load file ${filename}]`
|
|
4614
4619
|
};
|
|
4615
4620
|
}
|
|
4616
|
-
const
|
|
4617
|
-
const
|
|
4618
|
-
|
|
4619
|
-
|
|
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 }
|
|
4620
4627
|
});
|
|
4621
|
-
|
|
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);
|
|
4622
4632
|
return {
|
|
4623
4633
|
type: "text",
|
|
4624
4634
|
text: `<file file name = "${filename}" >
|
|
@@ -5650,7 +5660,7 @@ function detectPayloadFormat(contentType) {
|
|
|
5650
5660
|
}
|
|
5651
5661
|
var MIME_FIELD_NAMES = /* @__PURE__ */ new Set(["body-mime", "email", "message"]);
|
|
5652
5662
|
function extractMultipartMimePart(rawBody, contentType) {
|
|
5653
|
-
return new Promise((
|
|
5663
|
+
return new Promise((resolve3, reject) => {
|
|
5654
5664
|
let found = null;
|
|
5655
5665
|
const bb = Busboy({ headers: { "content-type": contentType }, defCharset: "latin1" });
|
|
5656
5666
|
bb.on("field", (name, value) => {
|
|
@@ -5659,7 +5669,7 @@ function extractMultipartMimePart(rawBody, contentType) {
|
|
|
5659
5669
|
}
|
|
5660
5670
|
});
|
|
5661
5671
|
bb.on("close", () => {
|
|
5662
|
-
if (found)
|
|
5672
|
+
if (found) resolve3(found);
|
|
5663
5673
|
else reject(new Error("No raw MIME part found (expected a body-mime, email, or message field)."));
|
|
5664
5674
|
});
|
|
5665
5675
|
bb.on("error", (err2) => reject(err2 instanceof Error ? err2 : new Error(String(err2))));
|
|
@@ -6151,7 +6161,7 @@ function createSniffer(onFirstLine) {
|
|
|
6151
6161
|
const head = [];
|
|
6152
6162
|
let headBytes = 0;
|
|
6153
6163
|
let resolved = false;
|
|
6154
|
-
const
|
|
6164
|
+
const resolve3 = (line) => {
|
|
6155
6165
|
if (resolved) return;
|
|
6156
6166
|
resolved = true;
|
|
6157
6167
|
onFirstLine(line);
|
|
@@ -6166,15 +6176,15 @@ function createSniffer(onFirstLine) {
|
|
|
6166
6176
|
const text = Buffer.concat(head).toString("utf-8");
|
|
6167
6177
|
const eol = /\r|\n/.exec(text);
|
|
6168
6178
|
if (eol) {
|
|
6169
|
-
|
|
6179
|
+
resolve3(text.slice(0, eol.index));
|
|
6170
6180
|
} else if (headBytes >= MAX_HEADER_BYTES) {
|
|
6171
|
-
|
|
6181
|
+
resolve3(text);
|
|
6172
6182
|
}
|
|
6173
6183
|
}
|
|
6174
6184
|
callback(null, chunk2);
|
|
6175
6185
|
},
|
|
6176
6186
|
flush(callback) {
|
|
6177
|
-
|
|
6187
|
+
resolve3(Buffer.concat(head).toString("utf-8"));
|
|
6178
6188
|
callback();
|
|
6179
6189
|
}
|
|
6180
6190
|
});
|
|
@@ -6182,8 +6192,8 @@ function createSniffer(onFirstLine) {
|
|
|
6182
6192
|
async function streamCsvRows(input, handlers, opts) {
|
|
6183
6193
|
let resolveFirstLine = () => {
|
|
6184
6194
|
};
|
|
6185
|
-
const firstLine = new Promise((
|
|
6186
|
-
resolveFirstLine =
|
|
6195
|
+
const firstLine = new Promise((resolve3) => {
|
|
6196
|
+
resolveFirstLine = resolve3;
|
|
6187
6197
|
});
|
|
6188
6198
|
const sniffer = createSniffer((line) => resolveFirstLine(line));
|
|
6189
6199
|
let parser;
|
|
@@ -6677,7 +6687,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
6677
6687
|
);
|
|
6678
6688
|
if (attempt < retries) {
|
|
6679
6689
|
const backoffMs = 500 * Math.pow(2, attempt - 1);
|
|
6680
|
-
await new Promise((
|
|
6690
|
+
await new Promise((resolve3) => setTimeout(resolve3, backoffMs));
|
|
6681
6691
|
}
|
|
6682
6692
|
}
|
|
6683
6693
|
}
|
|
@@ -6897,7 +6907,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
6897
6907
|
}
|
|
6898
6908
|
const retries2 = 3;
|
|
6899
6909
|
let attempts = 0;
|
|
6900
|
-
const promise = new Promise(async (
|
|
6910
|
+
const promise = new Promise(async (resolve3, reject) => {
|
|
6901
6911
|
while (attempts < retries2) {
|
|
6902
6912
|
try {
|
|
6903
6913
|
const messages2 = await processUiMessagesFlow({
|
|
@@ -6916,7 +6926,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
6916
6926
|
// back into blanket pre-approval (spec §5.2).
|
|
6917
6927
|
respectToolApprovals: workflow.auto_approve_tools !== true
|
|
6918
6928
|
});
|
|
6919
|
-
|
|
6929
|
+
resolve3(messages2);
|
|
6920
6930
|
break;
|
|
6921
6931
|
} catch (error) {
|
|
6922
6932
|
console.error(
|
|
@@ -6943,7 +6953,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
6943
6953
|
}
|
|
6944
6954
|
reject(new Error(error instanceof Error ? error.message : String(error)));
|
|
6945
6955
|
}
|
|
6946
|
-
await new Promise((
|
|
6956
|
+
await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
|
|
6947
6957
|
}
|
|
6948
6958
|
}
|
|
6949
6959
|
});
|
|
@@ -7041,7 +7051,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
7041
7051
|
} = await validateEvalPayload(data);
|
|
7042
7052
|
const retries2 = 3;
|
|
7043
7053
|
let attempts = 0;
|
|
7044
|
-
const promise = new Promise(async (
|
|
7054
|
+
const promise = new Promise(async (resolve3, reject) => {
|
|
7045
7055
|
while (attempts < retries2) {
|
|
7046
7056
|
try {
|
|
7047
7057
|
const messages2 = await processUiMessagesFlow({
|
|
@@ -7052,7 +7062,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
7052
7062
|
tools,
|
|
7053
7063
|
config
|
|
7054
7064
|
});
|
|
7055
|
-
|
|
7065
|
+
resolve3(messages2);
|
|
7056
7066
|
break;
|
|
7057
7067
|
} catch (error) {
|
|
7058
7068
|
console.error(
|
|
@@ -7063,7 +7073,7 @@ var createWorkers = async (queues2, config, contexts, evals, tools, tracer) => {
|
|
|
7063
7073
|
if (attempts >= retries2) {
|
|
7064
7074
|
reject(new Error(error instanceof Error ? error.message : String(error)));
|
|
7065
7075
|
}
|
|
7066
|
-
await new Promise((
|
|
7076
|
+
await new Promise((resolve4) => setTimeout((resolve5) => resolve5(true), 2e3));
|
|
7067
7077
|
}
|
|
7068
7078
|
}
|
|
7069
7079
|
});
|
|
@@ -7639,7 +7649,7 @@ var pollJobResult = async ({
|
|
|
7639
7649
|
attempts++;
|
|
7640
7650
|
const job = await Job.fromId(queue.queue, jobId);
|
|
7641
7651
|
if (!job) {
|
|
7642
|
-
await new Promise((
|
|
7652
|
+
await new Promise((resolve3) => setTimeout((resolve4) => resolve4(true), 2e3));
|
|
7643
7653
|
continue;
|
|
7644
7654
|
}
|
|
7645
7655
|
const elapsedTime = Date.now() - startTime;
|
|
@@ -7669,7 +7679,7 @@ var pollJobResult = async ({
|
|
|
7669
7679
|
console.log(`[EXULU] eval function ${job.id} result: ${result}`);
|
|
7670
7680
|
break;
|
|
7671
7681
|
}
|
|
7672
|
-
await new Promise((
|
|
7682
|
+
await new Promise((resolve3) => setTimeout(() => resolve3(true), 2e3));
|
|
7673
7683
|
}
|
|
7674
7684
|
return result;
|
|
7675
7685
|
};
|
|
@@ -7767,7 +7777,7 @@ var processUiMessagesFlow = async ({
|
|
|
7767
7777
|
trigger: "agent"
|
|
7768
7778
|
};
|
|
7769
7779
|
try {
|
|
7770
|
-
messageHistory = await new Promise(async (
|
|
7780
|
+
messageHistory = await new Promise(async (resolve3, reject) => {
|
|
7771
7781
|
const startTime = Date.now();
|
|
7772
7782
|
try {
|
|
7773
7783
|
const result = await generateStream({
|
|
@@ -7856,7 +7866,7 @@ var processUiMessagesFlow = async ({
|
|
|
7856
7866
|
})
|
|
7857
7867
|
] : []
|
|
7858
7868
|
]);
|
|
7859
|
-
|
|
7869
|
+
resolve3({
|
|
7860
7870
|
messages,
|
|
7861
7871
|
metadata: {
|
|
7862
7872
|
tokens: {
|
|
@@ -8065,7 +8075,7 @@ async function fetch_with_retry(args) {
|
|
|
8065
8075
|
console.log(
|
|
8066
8076
|
`[EXULU-RECALL] fetch error from ${url} (${err2.message}); retrying in ~5s (attempt ${attempt}/${max_attempts})`
|
|
8067
8077
|
);
|
|
8068
|
-
await new Promise((
|
|
8078
|
+
await new Promise((resolve3) => setTimeout(resolve3, 5e3 + jitterMs()));
|
|
8069
8079
|
continue;
|
|
8070
8080
|
}
|
|
8071
8081
|
let wait_for = null;
|
|
@@ -8085,7 +8095,7 @@ async function fetch_with_retry(args) {
|
|
|
8085
8095
|
`[EXULU-RECALL] retryable ${response.status} from ${url}; retrying in ~${wait_for}s (attempt ${attempt}/${max_attempts})`
|
|
8086
8096
|
);
|
|
8087
8097
|
await new Promise(
|
|
8088
|
-
(
|
|
8098
|
+
(resolve3) => setTimeout(resolve3, 1e3 * wait_for + jitterMs())
|
|
8089
8099
|
);
|
|
8090
8100
|
continue;
|
|
8091
8101
|
}
|
|
@@ -8095,9 +8105,9 @@ async function fetch_with_retry(args) {
|
|
|
8095
8105
|
`[EXULU-RECALL] Max attempts (${max_attempts}) reached while fetching ${url}.`
|
|
8096
8106
|
);
|
|
8097
8107
|
}
|
|
8098
|
-
var request = async (
|
|
8108
|
+
var request = async (path, init = {}) => {
|
|
8099
8109
|
assertRecallConfigured();
|
|
8100
|
-
const url = `${recallApiBaseUrl()}${
|
|
8110
|
+
const url = `${recallApiBaseUrl()}${path}`;
|
|
8101
8111
|
const response = await fetch_with_retry({
|
|
8102
8112
|
url,
|
|
8103
8113
|
options: {
|
|
@@ -8115,7 +8125,7 @@ var request = async (path2, init = {}) => {
|
|
|
8115
8125
|
if (!response.ok) {
|
|
8116
8126
|
const body = await response.text();
|
|
8117
8127
|
throw new RecallApiError(
|
|
8118
|
-
`Recall API ${response.status} for ${
|
|
8128
|
+
`Recall API ${response.status} for ${path}: ${body}`,
|
|
8119
8129
|
response.status,
|
|
8120
8130
|
body
|
|
8121
8131
|
);
|
|
@@ -8958,8 +8968,8 @@ var getBaseUrl = () => {
|
|
|
8958
8968
|
}
|
|
8959
8969
|
return url.replace(/\/$/, "");
|
|
8960
8970
|
};
|
|
8961
|
-
var request2 = async (
|
|
8962
|
-
const url = `${getBaseUrl()}${
|
|
8971
|
+
var request2 = async (path, init = {}) => {
|
|
8972
|
+
const url = `${getBaseUrl()}${path}`;
|
|
8963
8973
|
let res;
|
|
8964
8974
|
try {
|
|
8965
8975
|
res = await fetch(url, init);
|
|
@@ -8969,13 +8979,13 @@ var request2 = async (path2, init = {}) => {
|
|
|
8969
8979
|
);
|
|
8970
8980
|
}
|
|
8971
8981
|
if (res.status === 404) {
|
|
8972
|
-
const err2 = new Error(`whisper server returned 404 for ${
|
|
8982
|
+
const err2 = new Error(`whisper server returned 404 for ${path}`);
|
|
8973
8983
|
err2.code = "JOB_NOT_FOUND";
|
|
8974
8984
|
throw err2;
|
|
8975
8985
|
}
|
|
8976
8986
|
if (!res.ok) {
|
|
8977
8987
|
throw new Error(
|
|
8978
|
-
`whisper server returned ${res.status} for ${
|
|
8988
|
+
`whisper server returned ${res.status} for ${path}: ${await res.text()}`
|
|
8979
8989
|
);
|
|
8980
8990
|
}
|
|
8981
8991
|
return await res.json();
|
|
@@ -11908,7 +11918,7 @@ type EmbeddingModelOption {
|
|
|
11908
11918
|
}
|
|
11909
11919
|
`;
|
|
11910
11920
|
resolvers.Query["litellmCatalog"] = async () => {
|
|
11911
|
-
const { fetchLiteLLMCatalog } = await import("./catalog-
|
|
11921
|
+
const { fetchLiteLLMCatalog } = await import("./catalog-4P3TKOV7.js");
|
|
11912
11922
|
return fetchLiteLLMCatalog();
|
|
11913
11923
|
};
|
|
11914
11924
|
resolvers.Query["availableEmbeddingModels"] = async () => {
|
|
@@ -12365,7 +12375,7 @@ type EmbeddingModelOption {
|
|
|
12365
12375
|
await db.from("job_results").where({ id: jobResultId }).update({ session: sessionId });
|
|
12366
12376
|
const retries = 3;
|
|
12367
12377
|
let attempts = 0;
|
|
12368
|
-
const promise = new Promise(async (
|
|
12378
|
+
const promise = new Promise(async (resolve3, reject) => {
|
|
12369
12379
|
while (attempts < retries) {
|
|
12370
12380
|
try {
|
|
12371
12381
|
const messages2 = await processUiMessagesFlow({
|
|
@@ -12380,7 +12390,7 @@ type EmbeddingModelOption {
|
|
|
12380
12390
|
routine: { id: workflow.id, name: workflow.name },
|
|
12381
12391
|
sessionId
|
|
12382
12392
|
});
|
|
12383
|
-
|
|
12393
|
+
resolve3(messages2);
|
|
12384
12394
|
break;
|
|
12385
12395
|
} catch (error) {
|
|
12386
12396
|
console.error(
|
|
@@ -12394,7 +12404,7 @@ type EmbeddingModelOption {
|
|
|
12394
12404
|
if (attempts >= retries) {
|
|
12395
12405
|
reject(error instanceof Error ? error : new Error(String(error)));
|
|
12396
12406
|
}
|
|
12397
|
-
await new Promise((
|
|
12407
|
+
await new Promise((resolve4) => setTimeout(() => resolve4(true), 2e3));
|
|
12398
12408
|
}
|
|
12399
12409
|
}
|
|
12400
12410
|
});
|
|
@@ -12965,10 +12975,10 @@ type EmbeddingModelOption {
|
|
|
12965
12975
|
contexts.map(async (context2) => {
|
|
12966
12976
|
let processor = null;
|
|
12967
12977
|
if (context2.processor) {
|
|
12968
|
-
processor = await new Promise(async (
|
|
12978
|
+
processor = await new Promise(async (resolve3, reject) => {
|
|
12969
12979
|
const config2 = context2.processor?.config;
|
|
12970
12980
|
const queue = await config2?.queue;
|
|
12971
|
-
|
|
12981
|
+
resolve3({
|
|
12972
12982
|
name: context2.processor.name,
|
|
12973
12983
|
description: context2.processor.description,
|
|
12974
12984
|
queue: queue?.queue?.name || void 0,
|
|
@@ -13050,10 +13060,10 @@ type EmbeddingModelOption {
|
|
|
13050
13060
|
}
|
|
13051
13061
|
let processor = null;
|
|
13052
13062
|
if (data.processor) {
|
|
13053
|
-
processor = await new Promise(async (
|
|
13063
|
+
processor = await new Promise(async (resolve3, reject) => {
|
|
13054
13064
|
const config2 = data.processor?.config;
|
|
13055
13065
|
const queue = await config2?.queue;
|
|
13056
|
-
|
|
13066
|
+
resolve3({
|
|
13057
13067
|
name: data.processor.name,
|
|
13058
13068
|
description: data.processor.description,
|
|
13059
13069
|
queue: queue?.queue?.name || void 0,
|
|
@@ -13480,14 +13490,14 @@ var BundleValidationError = class extends Error {
|
|
|
13480
13490
|
this.name = "BundleValidationError";
|
|
13481
13491
|
}
|
|
13482
13492
|
};
|
|
13483
|
-
function isUnsafePath(
|
|
13484
|
-
if (!
|
|
13485
|
-
if (
|
|
13486
|
-
return
|
|
13487
|
-
}
|
|
13488
|
-
function isOsJunkPath(
|
|
13489
|
-
if (
|
|
13490
|
-
const basename =
|
|
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() ?? "";
|
|
13491
13501
|
return basename === ".DS_Store" || basename === "Thumbs.db" || basename === "desktop.ini";
|
|
13492
13502
|
}
|
|
13493
13503
|
async function extractZipToPrefix(bytes, prefix, config) {
|
|
@@ -13513,17 +13523,17 @@ async function extractZipToPrefix(bytes, prefix, config) {
|
|
|
13513
13523
|
`Bundle has ${entries.length} entries, exceeding the limit of ${MAX_ENTRY_COUNT}.`
|
|
13514
13524
|
);
|
|
13515
13525
|
}
|
|
13516
|
-
for (const { path
|
|
13517
|
-
if (isUnsafePath(
|
|
13526
|
+
for (const { path } of entries) {
|
|
13527
|
+
if (isUnsafePath(path)) {
|
|
13518
13528
|
throw new BundleValidationError(
|
|
13519
|
-
`Bundle contains an unsafe path: ${
|
|
13529
|
+
`Bundle contains an unsafe path: ${path}`
|
|
13520
13530
|
);
|
|
13521
13531
|
}
|
|
13522
13532
|
}
|
|
13523
13533
|
let prefixToStrip = "";
|
|
13524
13534
|
const firstSegments = /* @__PURE__ */ new Set();
|
|
13525
|
-
for (const { path
|
|
13526
|
-
const head =
|
|
13535
|
+
for (const { path } of entries) {
|
|
13536
|
+
const head = path.split("/")[0];
|
|
13527
13537
|
if (head) firstSegments.add(head);
|
|
13528
13538
|
}
|
|
13529
13539
|
if (firstSegments.size === 1) {
|
|
@@ -13531,7 +13541,7 @@ async function extractZipToPrefix(bytes, prefix, config) {
|
|
|
13531
13541
|
const allWrapped = entries.every((e) => e.path.startsWith(single + "/"));
|
|
13532
13542
|
if (allWrapped) prefixToStrip = single + "/";
|
|
13533
13543
|
}
|
|
13534
|
-
const stripped = (
|
|
13544
|
+
const stripped = (path) => prefixToStrip && path.startsWith(prefixToStrip) ? path.slice(prefixToStrip.length) : path;
|
|
13535
13545
|
const hasSkillMd = entries.some((e) => stripped(e.path) === "SKILL.md");
|
|
13536
13546
|
if (!hasSkillMd) {
|
|
13537
13547
|
throw new BundleValidationError(
|
|
@@ -13540,15 +13550,15 @@ async function extractZipToPrefix(bytes, prefix, config) {
|
|
|
13540
13550
|
}
|
|
13541
13551
|
const prepared = [];
|
|
13542
13552
|
let totalBytes = 0;
|
|
13543
|
-
for (const { path
|
|
13553
|
+
for (const { path, entry } of entries) {
|
|
13544
13554
|
const content = await entry.async("nodebuffer");
|
|
13545
13555
|
totalBytes += content.byteLength;
|
|
13546
13556
|
if (totalBytes > MAX_TOTAL_UNCOMPRESSED_BYTES) {
|
|
13547
13557
|
throw new BundleValidationError(
|
|
13548
|
-
`Bundle uncompressed size exceeds ${MAX_TOTAL_UNCOMPRESSED_BYTES} bytes (50 MB). Reached ${totalBytes} bytes at "${
|
|
13558
|
+
`Bundle uncompressed size exceeds ${MAX_TOTAL_UNCOMPRESSED_BYTES} bytes (50 MB). Reached ${totalBytes} bytes at "${path}".`
|
|
13549
13559
|
);
|
|
13550
13560
|
}
|
|
13551
|
-
const relPath = stripped(
|
|
13561
|
+
const relPath = stripped(path);
|
|
13552
13562
|
if (!relPath) continue;
|
|
13553
13563
|
prepared.push({ relPath, content });
|
|
13554
13564
|
}
|
|
@@ -13626,8 +13636,8 @@ var BUNDLED_SKILLS = [
|
|
|
13626
13636
|
var BUNDLED_LABEL = "Bundled with the IMP";
|
|
13627
13637
|
function bundledSkillHash(skill) {
|
|
13628
13638
|
const h = createHash2("sha256");
|
|
13629
|
-
for (const
|
|
13630
|
-
h.update(
|
|
13639
|
+
for (const path of Object.keys(skill.files).sort()) {
|
|
13640
|
+
h.update(path).update("\0").update(skill.files[path]).update("\0");
|
|
13631
13641
|
}
|
|
13632
13642
|
return h.digest("hex");
|
|
13633
13643
|
}
|
|
@@ -13638,8 +13648,8 @@ function bundledSkillDescription(skill) {
|
|
|
13638
13648
|
}
|
|
13639
13649
|
async function bundledSkillZip(skill) {
|
|
13640
13650
|
const zip = new JSZip2();
|
|
13641
|
-
for (const [
|
|
13642
|
-
zip.file(
|
|
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);
|
|
13643
13653
|
}
|
|
13644
13654
|
return zip.generateAsync({ type: "nodebuffer", platform: "UNIX" });
|
|
13645
13655
|
}
|
|
@@ -14019,7 +14029,7 @@ var internetSearchTool = new ExuluTool({
|
|
|
14019
14029
|
} catch (error) {
|
|
14020
14030
|
if (error instanceof Perplexity.RateLimitError && attempt < maxRetries - 1) {
|
|
14021
14031
|
const delay = Math.pow(2, attempt) * 1e3 + Math.random() * 1e3;
|
|
14022
|
-
await new Promise((
|
|
14032
|
+
await new Promise((resolve3) => setTimeout(resolve3, delay));
|
|
14023
14033
|
continue;
|
|
14024
14034
|
}
|
|
14025
14035
|
throw error;
|
|
@@ -15513,11 +15523,11 @@ function excerptFor(windows3, sentenceTexts) {
|
|
|
15513
15523
|
const body = [...byIndex.entries()].sort((a, b) => a[0] - b[0]).map(([, text]) => text).join(" ");
|
|
15514
15524
|
const sections = [];
|
|
15515
15525
|
for (const w of windows3) {
|
|
15516
|
-
const
|
|
15517
|
-
if (
|
|
15526
|
+
const path = w.sentence.headingPath.filter(Boolean).join(" > ");
|
|
15527
|
+
if (path && !sections.includes(path)) sections.push(path);
|
|
15518
15528
|
}
|
|
15519
15529
|
if (sections.length === 0) return body;
|
|
15520
|
-
return `${sections.map((
|
|
15530
|
+
return `${sections.map((path) => `Section: ${path}`).join("\n")}
|
|
15521
15531
|
|
|
15522
15532
|
${body}`;
|
|
15523
15533
|
}
|
|
@@ -16776,7 +16786,7 @@ See docs/superpowers/specs/2026-05-31-in-chat-image-generation-design.md for the
|
|
|
16776
16786
|
import { resolve as resolvePath } from "path";
|
|
16777
16787
|
|
|
16778
16788
|
// src/exulu/litellm/passthrough-allowlist.ts
|
|
16779
|
-
var isLiteLLMPassthroughPathAllowed = (
|
|
16789
|
+
var isLiteLLMPassthroughPathAllowed = (path) => path.startsWith("/v1/") || path === "/model/info";
|
|
16780
16790
|
|
|
16781
16791
|
// src/exulu/litellm/usage-view.ts
|
|
16782
16792
|
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
@@ -17188,7 +17198,9 @@ var publicAgentView = (row, slug) => ({
|
|
|
17188
17198
|
welcomemessage: row.welcomemessage ?? "",
|
|
17189
17199
|
slug,
|
|
17190
17200
|
guest_auth_mode: row.guest_auth_mode || "regular",
|
|
17191
|
-
guest_has_cover: !!row.guest_cover_image
|
|
17201
|
+
guest_has_cover: !!row.guest_cover_image,
|
|
17202
|
+
guest_has_idle_animation: !!row.animation_idle,
|
|
17203
|
+
guest_has_responding_animation: !!row.animation_responding
|
|
17192
17204
|
});
|
|
17193
17205
|
var evaluateGuestChatAccess = async (agent, userId, guestPassword) => {
|
|
17194
17206
|
if (agent.guest_access) {
|
|
@@ -17491,8 +17503,8 @@ can create an API key at \`<base_url>/token\`.
|
|
|
17491
17503
|
var REQUEST_SIZE_LIMIT = "50mb";
|
|
17492
17504
|
var getExuluVersionNumber = async () => {
|
|
17493
17505
|
try {
|
|
17494
|
-
const
|
|
17495
|
-
const packageJson = fs2.readFileSync(
|
|
17506
|
+
const path = process.cwd();
|
|
17507
|
+
const packageJson = fs2.readFileSync(path + "/package.json", "utf8");
|
|
17496
17508
|
const packageData = JSON.parse(packageJson);
|
|
17497
17509
|
const exuluVersion = packageData.dependencies["@exulu/backend"];
|
|
17498
17510
|
console.log(`[EXULU] Installed exulu-backend version: ${exuluVersion}`);
|
|
@@ -20693,35 +20705,35 @@ ${style.markdown}` : params.prompt;
|
|
|
20693
20705
|
const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".txt", ".py", ".js", ".ts", ".json", ".yaml", ".yml", ".sh", ".toml"]);
|
|
20694
20706
|
const MAX_DIFF_BYTES = 500 * 1024;
|
|
20695
20707
|
const fileDiffs = await Promise.all(
|
|
20696
|
-
[...allPaths].map(async (
|
|
20697
|
-
const inFrom = fromMap.has(
|
|
20698
|
-
const inTo = toMap.has(
|
|
20708
|
+
[...allPaths].map(async (path) => {
|
|
20709
|
+
const inFrom = fromMap.has(path);
|
|
20710
|
+
const inTo = toMap.has(path);
|
|
20699
20711
|
const status = !inFrom ? "added" : !inTo ? "removed" : "modified";
|
|
20700
20712
|
if (status === "modified") {
|
|
20701
|
-
const ext =
|
|
20713
|
+
const ext = path.slice(path.lastIndexOf(".")).toLowerCase();
|
|
20702
20714
|
if (!TEXT_EXTENSIONS.has(ext)) {
|
|
20703
|
-
return { path
|
|
20715
|
+
return { path, status };
|
|
20704
20716
|
}
|
|
20705
20717
|
try {
|
|
20706
20718
|
const [fromContent, toContent] = await Promise.all([
|
|
20707
|
-
getS3ObjectContent(s3Prefix + fromPrefix +
|
|
20708
|
-
getS3ObjectContent(s3Prefix + toPrefix +
|
|
20719
|
+
getS3ObjectContent(s3Prefix + fromPrefix + path, config),
|
|
20720
|
+
getS3ObjectContent(s3Prefix + toPrefix + path, config)
|
|
20709
20721
|
]);
|
|
20710
20722
|
if (fromContent === toContent) {
|
|
20711
|
-
return { path
|
|
20723
|
+
return { path, status: "unchanged" };
|
|
20712
20724
|
}
|
|
20713
20725
|
if (fromContent.length + toContent.length > MAX_DIFF_BYTES) {
|
|
20714
|
-
return { path
|
|
20726
|
+
return { path, status };
|
|
20715
20727
|
}
|
|
20716
20728
|
const fromLines = fromContent.split("\n");
|
|
20717
20729
|
const toLines = toContent.split("\n");
|
|
20718
|
-
const diff = buildUnifiedDiff(fromLines, toLines, `v${fromVersion}/${
|
|
20719
|
-
return { path
|
|
20730
|
+
const diff = buildUnifiedDiff(fromLines, toLines, `v${fromVersion}/${path}`, `v${toVersion}/${path}`);
|
|
20731
|
+
return { path, status, diff };
|
|
20720
20732
|
} catch {
|
|
20721
|
-
return { path
|
|
20733
|
+
return { path, status };
|
|
20722
20734
|
}
|
|
20723
20735
|
}
|
|
20724
|
-
return { path
|
|
20736
|
+
return { path, status };
|
|
20725
20737
|
})
|
|
20726
20738
|
);
|
|
20727
20739
|
res.json({
|
|
@@ -21435,7 +21447,11 @@ ${style.markdown}` : params.prompt;
|
|
|
21435
21447
|
"welcomemessage",
|
|
21436
21448
|
"model",
|
|
21437
21449
|
"guest_auth_mode",
|
|
21438
|
-
"guest_cover_image"
|
|
21450
|
+
"guest_cover_image",
|
|
21451
|
+
// Presence only — publicAgentView turns these into booleans and the
|
|
21452
|
+
// bytes are served by /public-agents/:id/animation/:kind.
|
|
21453
|
+
"animation_idle",
|
|
21454
|
+
"animation_responding"
|
|
21439
21455
|
);
|
|
21440
21456
|
const views = await Promise.all(
|
|
21441
21457
|
rows.map(
|
|
@@ -21477,6 +21493,38 @@ ${style.markdown}` : params.prompt;
|
|
|
21477
21493
|
res.setHeader("Cache-Control", "public, max-age=300");
|
|
21478
21494
|
res.send(bytes);
|
|
21479
21495
|
});
|
|
21496
|
+
app.get(
|
|
21497
|
+
"/public-agents/:id/animation/:kind",
|
|
21498
|
+
async (req, res) => {
|
|
21499
|
+
const kind = req.params.kind;
|
|
21500
|
+
if (kind !== "idle" && kind !== "responding") {
|
|
21501
|
+
res.status(404).json({ detail: "Not found." });
|
|
21502
|
+
return;
|
|
21503
|
+
}
|
|
21504
|
+
const row = await getGuestAgentById(req.params.id ?? "");
|
|
21505
|
+
const key = kind === "idle" ? row?.animation_idle : row?.animation_responding;
|
|
21506
|
+
if (!key) {
|
|
21507
|
+
res.status(404).json({ detail: "Not found." });
|
|
21508
|
+
return;
|
|
21509
|
+
}
|
|
21510
|
+
let bytes;
|
|
21511
|
+
try {
|
|
21512
|
+
bytes = await getS3ObjectBytes(key, config);
|
|
21513
|
+
} catch (e) {
|
|
21514
|
+
if (e?.name === "NoSuchKey" || e?.name === "NotFound" || e?.$metadata?.httpStatusCode === 404) {
|
|
21515
|
+
res.status(404).json({ detail: "Animation not found." });
|
|
21516
|
+
return;
|
|
21517
|
+
}
|
|
21518
|
+
console.error("[EXULU] public-agent animation read failed", e);
|
|
21519
|
+
res.status(500).json({ detail: "Failed to read animation." });
|
|
21520
|
+
return;
|
|
21521
|
+
}
|
|
21522
|
+
res.setHeader("Content-Type", "application/json");
|
|
21523
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
21524
|
+
res.setHeader("Cache-Control", "public, max-age=300");
|
|
21525
|
+
res.send(bytes);
|
|
21526
|
+
}
|
|
21527
|
+
);
|
|
21480
21528
|
app.post(
|
|
21481
21529
|
"/public-agents/:id/verify-password",
|
|
21482
21530
|
async (req, res) => {
|
|
@@ -23115,6 +23163,17 @@ var ExuluApp = class {
|
|
|
23115
23163
|
if (!license["queues"] && queues.list.size > 0) {
|
|
23116
23164
|
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.`);
|
|
23117
23165
|
}
|
|
23166
|
+
const attachmentProblems = validateAttachmentsConfig(config, license);
|
|
23167
|
+
if (attachmentProblems.length > 0) {
|
|
23168
|
+
throw new Error(`[EXULU] Invalid attachments.documentProcessor config:
|
|
23169
|
+
- ${attachmentProblems.join("\n- ")}`);
|
|
23170
|
+
}
|
|
23171
|
+
if (config?.attachments?.documentProcessor) {
|
|
23172
|
+
const { processor, vlm } = config.attachments.documentProcessor;
|
|
23173
|
+
console.log(`[EXULU] Attachments: OCR via ${processor.name}${processor.model ? ` (${processor.model})` : ""}${vlm ? `, VLM ${vlm.model} (concurrency ${vlm.concurrency})` : ", no VLM pass"}.`);
|
|
23174
|
+
} else {
|
|
23175
|
+
console.log("[EXULU] Attachments: text layer only (officeparser); set attachments.documentProcessor for OCR + VLM.");
|
|
23176
|
+
}
|
|
23118
23177
|
if (redisServer.host?.length && redisServer.port?.length) {
|
|
23119
23178
|
queues.register(
|
|
23120
23179
|
global_queues.eval_runs,
|
|
@@ -25417,932 +25476,6 @@ var MarkdownChunker = class {
|
|
|
25417
25476
|
}
|
|
25418
25477
|
};
|
|
25419
25478
|
|
|
25420
|
-
// ee/python/documents/processing/doc_processor.ts
|
|
25421
|
-
import * as fs3 from "fs";
|
|
25422
|
-
import * as path from "path";
|
|
25423
|
-
import { generateText as generateText8, Output as Output3 } from "ai";
|
|
25424
|
-
import { z as z19 } from "zod";
|
|
25425
|
-
import pLimit from "p-limit";
|
|
25426
|
-
import { randomUUID as randomUUID12 } from "crypto";
|
|
25427
|
-
import * as mammoth from "mammoth";
|
|
25428
|
-
import TurndownService from "turndown";
|
|
25429
|
-
import WordExtractor from "word-extractor";
|
|
25430
|
-
import { parseOfficeAsync as parseOfficeAsync2 } from "officeparser";
|
|
25431
|
-
|
|
25432
|
-
// src/utils/python-executor.ts
|
|
25433
|
-
import { exec } from "child_process";
|
|
25434
|
-
import { promisify as promisify2 } from "util";
|
|
25435
|
-
import { resolve as resolve3, join as join2, dirname } from "path";
|
|
25436
|
-
import { existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
|
|
25437
|
-
import { fileURLToPath } from "url";
|
|
25438
|
-
var execAsync = promisify2(exec);
|
|
25439
|
-
function getPackageRoot2() {
|
|
25440
|
-
const currentFile = fileURLToPath(import.meta.url);
|
|
25441
|
-
let currentDir = dirname(currentFile);
|
|
25442
|
-
let attempts = 0;
|
|
25443
|
-
const maxAttempts = 10;
|
|
25444
|
-
while (attempts < maxAttempts) {
|
|
25445
|
-
const packageJsonPath = join2(currentDir, "package.json");
|
|
25446
|
-
if (existsSync5(packageJsonPath)) {
|
|
25447
|
-
try {
|
|
25448
|
-
const packageJson = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
|
|
25449
|
-
if (packageJson.name === "@exulu/backend") {
|
|
25450
|
-
return currentDir;
|
|
25451
|
-
}
|
|
25452
|
-
} catch {
|
|
25453
|
-
}
|
|
25454
|
-
}
|
|
25455
|
-
const parentDir = resolve3(currentDir, "..");
|
|
25456
|
-
if (parentDir === currentDir) {
|
|
25457
|
-
break;
|
|
25458
|
-
}
|
|
25459
|
-
currentDir = parentDir;
|
|
25460
|
-
attempts++;
|
|
25461
|
-
}
|
|
25462
|
-
return resolve3(dirname(fileURLToPath(import.meta.url)), "../..");
|
|
25463
|
-
}
|
|
25464
|
-
var PythonEnvironmentError = class extends Error {
|
|
25465
|
-
constructor(message) {
|
|
25466
|
-
super(message);
|
|
25467
|
-
this.name = "PythonEnvironmentError";
|
|
25468
|
-
}
|
|
25469
|
-
};
|
|
25470
|
-
var PythonExecutionError = class extends Error {
|
|
25471
|
-
stdout;
|
|
25472
|
-
stderr;
|
|
25473
|
-
exitCode;
|
|
25474
|
-
constructor(message, stdout, stderr, exitCode) {
|
|
25475
|
-
super(message);
|
|
25476
|
-
this.name = "PythonExecutionError";
|
|
25477
|
-
this.stdout = stdout;
|
|
25478
|
-
this.stderr = stderr;
|
|
25479
|
-
this.exitCode = exitCode;
|
|
25480
|
-
}
|
|
25481
|
-
};
|
|
25482
|
-
function getVenvPath(packageRoot) {
|
|
25483
|
-
return resolve3(packageRoot, "ee/python/.venv");
|
|
25484
|
-
}
|
|
25485
|
-
function getPythonExecutable(packageRoot) {
|
|
25486
|
-
const venvPath = getVenvPath(packageRoot);
|
|
25487
|
-
return join2(venvPath, "bin", "python");
|
|
25488
|
-
}
|
|
25489
|
-
async function validatePythonEnvironmentForExecution(packageRoot) {
|
|
25490
|
-
const validation = await validatePythonEnvironment(packageRoot);
|
|
25491
|
-
if (!validation.valid) {
|
|
25492
|
-
throw new PythonEnvironmentError(validation.message);
|
|
25493
|
-
}
|
|
25494
|
-
}
|
|
25495
|
-
async function executePythonScript(config) {
|
|
25496
|
-
const {
|
|
25497
|
-
scriptPath,
|
|
25498
|
-
args = [],
|
|
25499
|
-
packageRoot = getPackageRoot2(),
|
|
25500
|
-
cwd = process.cwd(),
|
|
25501
|
-
timeout = 3e5,
|
|
25502
|
-
// 5 minutes default
|
|
25503
|
-
env = {},
|
|
25504
|
-
validateEnvironment = true
|
|
25505
|
-
} = config;
|
|
25506
|
-
if (validateEnvironment) {
|
|
25507
|
-
await validatePythonEnvironmentForExecution(packageRoot);
|
|
25508
|
-
}
|
|
25509
|
-
const resolvedScriptPath = resolve3(packageRoot, scriptPath);
|
|
25510
|
-
if (!existsSync5(resolvedScriptPath)) {
|
|
25511
|
-
throw new PythonExecutionError(
|
|
25512
|
-
`Python script not found: ${resolvedScriptPath}`,
|
|
25513
|
-
"",
|
|
25514
|
-
"",
|
|
25515
|
-
1
|
|
25516
|
-
);
|
|
25517
|
-
}
|
|
25518
|
-
const pythonExecutable = getPythonExecutable(packageRoot);
|
|
25519
|
-
const quotedArgs = args.map((arg) => {
|
|
25520
|
-
return arg.includes(" ") ? `"${arg}"` : arg;
|
|
25521
|
-
});
|
|
25522
|
-
const command = `${pythonExecutable} "${resolvedScriptPath}" ${quotedArgs.join(" ")}`;
|
|
25523
|
-
try {
|
|
25524
|
-
const { stdout, stderr } = await execAsync(command, {
|
|
25525
|
-
cwd,
|
|
25526
|
-
timeout,
|
|
25527
|
-
env: {
|
|
25528
|
-
...process.env,
|
|
25529
|
-
...env,
|
|
25530
|
-
// Ensure Python doesn't write bytecode files
|
|
25531
|
-
PYTHONDONTWRITEBYTECODE: "1"
|
|
25532
|
-
},
|
|
25533
|
-
maxBuffer: 50 * 1024 * 1024
|
|
25534
|
-
// 50MB buffer for output (increased from 10MB)
|
|
25535
|
-
});
|
|
25536
|
-
return {
|
|
25537
|
-
stdout: stdout.trim(),
|
|
25538
|
-
stderr: stderr.trim(),
|
|
25539
|
-
exitCode: 0,
|
|
25540
|
-
success: true
|
|
25541
|
-
};
|
|
25542
|
-
} catch (error) {
|
|
25543
|
-
const stdout = error.stdout?.toString() ?? "";
|
|
25544
|
-
const stderr = error.stderr?.toString() ?? "";
|
|
25545
|
-
const exitCode = error.code ?? 1;
|
|
25546
|
-
let errorMessage = `Python script execution failed: ${error.message}`;
|
|
25547
|
-
if (stderr) {
|
|
25548
|
-
errorMessage += `
|
|
25549
|
-
|
|
25550
|
-
Stderr:
|
|
25551
|
-
${stderr}`;
|
|
25552
|
-
}
|
|
25553
|
-
if (stdout) {
|
|
25554
|
-
errorMessage += `
|
|
25555
|
-
|
|
25556
|
-
Stdout:
|
|
25557
|
-
${stdout}`;
|
|
25558
|
-
}
|
|
25559
|
-
errorMessage += `
|
|
25560
|
-
|
|
25561
|
-
Command executed:
|
|
25562
|
-
${command}`;
|
|
25563
|
-
throw new PythonExecutionError(
|
|
25564
|
-
errorMessage,
|
|
25565
|
-
stdout,
|
|
25566
|
-
stderr,
|
|
25567
|
-
exitCode
|
|
25568
|
-
);
|
|
25569
|
-
}
|
|
25570
|
-
}
|
|
25571
|
-
|
|
25572
|
-
// ee/python/documents/processing/doc_processor.ts
|
|
25573
|
-
import { LiteParse } from "@llamaindex/liteparse";
|
|
25574
|
-
|
|
25575
|
-
// src/exulu/resolve-ocr.ts
|
|
25576
|
-
var ResolveOcrError = class extends Error {
|
|
25577
|
-
constructor(code, message) {
|
|
25578
|
-
super(message);
|
|
25579
|
-
this.code = code;
|
|
25580
|
-
this.name = "ResolveOcrError";
|
|
25581
|
-
}
|
|
25582
|
-
};
|
|
25583
|
-
async function resolveOcr(input) {
|
|
25584
|
-
const { model, contextId, contextName, user, userId, roleId, project, agent, routine } = input;
|
|
25585
|
-
if (!isLiteLLMEnabled()) {
|
|
25586
|
-
throw new ResolveOcrError(
|
|
25587
|
-
"LITELLM_NOT_CONFIGURED",
|
|
25588
|
-
"resolveOcr requires EXULU_USE_LITELLM=true \u2014 OCR is served exclusively through the LiteLLM proxy."
|
|
25589
|
-
);
|
|
25590
|
-
}
|
|
25591
|
-
try {
|
|
25592
|
-
await waitForLiteLLMReady();
|
|
25593
|
-
} catch (err2) {
|
|
25594
|
-
throw new ResolveOcrError(
|
|
25595
|
-
"LITELLM_NOT_READY",
|
|
25596
|
-
`LiteLLM is not ready: ${err2.message}`
|
|
25597
|
-
);
|
|
25598
|
-
}
|
|
25599
|
-
const { baseUrl, authHeaders } = resolveLiteLLMTarget();
|
|
25600
|
-
const resolvedUserId = user?.id ?? userId;
|
|
25601
|
-
if (resolvedUserId) await provisionDefaultUserBudget(resolvedUserId);
|
|
25602
|
-
const role = user?.role;
|
|
25603
|
-
const tags = buildTags({
|
|
25604
|
-
user_id: resolvedUserId,
|
|
25605
|
-
role_id: role?.id ?? roleId,
|
|
25606
|
-
project_id: (project ?? user?.project)?.id,
|
|
25607
|
-
agent_id: agent?.id,
|
|
25608
|
-
team_id: user?.team?.id,
|
|
25609
|
-
routine_id: routine?.id,
|
|
25610
|
-
context_id: contextId,
|
|
25611
|
-
user_name: !user ? void 0 : user.type === "api" ? user.firstname ?? user.email : user.email,
|
|
25612
|
-
role_name: role?.name,
|
|
25613
|
-
project_name: (project ?? user?.project)?.name,
|
|
25614
|
-
agent_name: agent?.name,
|
|
25615
|
-
team_name: user?.team?.name,
|
|
25616
|
-
routine_name: routine?.name,
|
|
25617
|
-
context_name: contextName
|
|
25618
|
-
});
|
|
25619
|
-
const endpoint = `${baseUrl}/v1/ocr`;
|
|
25620
|
-
const ocr = async (document, opts) => {
|
|
25621
|
-
const res = await fetch(endpoint, {
|
|
25622
|
-
method: "POST",
|
|
25623
|
-
headers: {
|
|
25624
|
-
...authHeaders,
|
|
25625
|
-
"Content-Type": "application/json"
|
|
25626
|
-
},
|
|
25627
|
-
body: JSON.stringify({
|
|
25628
|
-
model,
|
|
25629
|
-
document,
|
|
25630
|
-
// Mistral OCR optional params — only sent when provided.
|
|
25631
|
-
...opts?.pages ? { pages: opts.pages } : {},
|
|
25632
|
-
...opts?.includeImageBase64 !== void 0 ? { include_image_base64: opts.includeImageBase64 } : {},
|
|
25633
|
-
...opts?.imageLimit !== void 0 ? { image_limit: opts.imageLimit } : {},
|
|
25634
|
-
...opts?.imageMinSize !== void 0 ? { image_min_size: opts.imageMinSize } : {},
|
|
25635
|
-
// LiteLLM reads metadata.tags for tag-based spend tracking — same
|
|
25636
|
-
// mechanism createTaggedFetch / resolveEmbedder use.
|
|
25637
|
-
metadata: { tags }
|
|
25638
|
-
})
|
|
25639
|
-
});
|
|
25640
|
-
if (!res.ok) {
|
|
25641
|
-
const text = await res.text().catch(() => "");
|
|
25642
|
-
throw new Error(
|
|
25643
|
-
`[EXULU] LiteLLM /v1/ocr returned ${res.status} for model "${model}": ${text}`
|
|
25644
|
-
);
|
|
25645
|
-
}
|
|
25646
|
-
const json = await res.json();
|
|
25647
|
-
if (!Array.isArray(json.pages)) {
|
|
25648
|
-
throw new Error(
|
|
25649
|
-
`[EXULU] LiteLLM /v1/ocr returned no pages for model "${model}".`
|
|
25650
|
-
);
|
|
25651
|
-
}
|
|
25652
|
-
return json;
|
|
25653
|
-
};
|
|
25654
|
-
return { model, ocr };
|
|
25655
|
-
}
|
|
25656
|
-
|
|
25657
|
-
// ee/python/documents/processing/doc_processor.ts
|
|
25658
|
-
async function processDocx(file) {
|
|
25659
|
-
const html = await mammoth.convertToHtml({ buffer: file });
|
|
25660
|
-
const turndownService = new TurndownService();
|
|
25661
|
-
let markdown = turndownService.turndown(html.value);
|
|
25662
|
-
markdown = markdown.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
|
|
25663
|
-
return {
|
|
25664
|
-
json: [{
|
|
25665
|
-
page: 1,
|
|
25666
|
-
content: markdown,
|
|
25667
|
-
headings: []
|
|
25668
|
-
}],
|
|
25669
|
-
markdown
|
|
25670
|
-
};
|
|
25671
|
-
}
|
|
25672
|
-
async function processWord(file) {
|
|
25673
|
-
const extractor = new WordExtractor();
|
|
25674
|
-
const extracted = await extractor.extract(file);
|
|
25675
|
-
let content = extracted.getBody();
|
|
25676
|
-
content = content.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
|
|
25677
|
-
return {
|
|
25678
|
-
json: [{
|
|
25679
|
-
page: 1,
|
|
25680
|
-
content,
|
|
25681
|
-
headings: []
|
|
25682
|
-
}],
|
|
25683
|
-
markdown: content
|
|
25684
|
-
};
|
|
25685
|
-
}
|
|
25686
|
-
async function resolveVlmModel(config) {
|
|
25687
|
-
const modelId = config?.vlm?.model;
|
|
25688
|
-
if (!modelId) return void 0;
|
|
25689
|
-
const { languageModel } = await resolveModel({
|
|
25690
|
-
modelId,
|
|
25691
|
-
user: config?.attribution?.user,
|
|
25692
|
-
project: config?.attribution?.project,
|
|
25693
|
-
agent: config?.attribution?.agent,
|
|
25694
|
-
routine: config?.attribution?.routine,
|
|
25695
|
-
rbacBypass: true
|
|
25696
|
-
});
|
|
25697
|
-
return languageModel;
|
|
25698
|
-
}
|
|
25699
|
-
async function processImage(buffer, paths, config, verbose = false) {
|
|
25700
|
-
try {
|
|
25701
|
-
await fs3.promises.mkdir(paths.images, { recursive: true });
|
|
25702
|
-
const imagePath = path.join(paths.images, "1.png");
|
|
25703
|
-
await fs3.promises.writeFile(imagePath, buffer);
|
|
25704
|
-
console.log(`[EXULU] Image saved to: ${imagePath}`);
|
|
25705
|
-
let json = [{
|
|
25706
|
-
page: 1,
|
|
25707
|
-
content: "",
|
|
25708
|
-
// Empty initially, will be populated by VLM if enabled
|
|
25709
|
-
image: imagePath,
|
|
25710
|
-
headings: []
|
|
25711
|
-
}];
|
|
25712
|
-
const vlmModel = await resolveVlmModel(config);
|
|
25713
|
-
if (vlmModel) {
|
|
25714
|
-
console.log("[EXULU] Extracting content from image using VLM...");
|
|
25715
|
-
json = await validateWithVLM(
|
|
25716
|
-
json,
|
|
25717
|
-
vlmModel,
|
|
25718
|
-
verbose,
|
|
25719
|
-
config.vlm.concurrency
|
|
25720
|
-
);
|
|
25721
|
-
await fs3.promises.writeFile(
|
|
25722
|
-
paths.json,
|
|
25723
|
-
JSON.stringify(json, null, 2),
|
|
25724
|
-
"utf-8"
|
|
25725
|
-
);
|
|
25726
|
-
console.log("[EXULU] VLM content extraction complete");
|
|
25727
|
-
const correctedCount = json.filter((p) => p.vlm_corrected_text).length;
|
|
25728
|
-
console.log(`[EXULU] Content extracted: ${correctedCount > 0 ? "Yes" : "No"}`);
|
|
25729
|
-
} else {
|
|
25730
|
-
console.log("[EXULU] No VLM configured, image saved without content extraction");
|
|
25731
|
-
console.log("[EXULU] Note: Enable VLM in config to extract text/content from images");
|
|
25732
|
-
await fs3.promises.writeFile(
|
|
25733
|
-
paths.json,
|
|
25734
|
-
JSON.stringify(json, null, 2),
|
|
25735
|
-
"utf-8"
|
|
25736
|
-
);
|
|
25737
|
-
}
|
|
25738
|
-
const markdown = json.map((p) => p.vlm_corrected_text ?? p.content).join("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
|
|
25739
|
-
await fs3.promises.writeFile(paths.markdown, markdown, "utf-8");
|
|
25740
|
-
return {
|
|
25741
|
-
markdown,
|
|
25742
|
-
json
|
|
25743
|
-
};
|
|
25744
|
-
} catch (error) {
|
|
25745
|
-
console.error("[EXULU] Error processing image:", error);
|
|
25746
|
-
throw error;
|
|
25747
|
-
}
|
|
25748
|
-
}
|
|
25749
|
-
function normalizeMarkdownContent(content) {
|
|
25750
|
-
const lines = content.split("\n");
|
|
25751
|
-
const normalizedLines = [];
|
|
25752
|
-
for (const line of lines) {
|
|
25753
|
-
if (line.includes("|")) {
|
|
25754
|
-
const parts = line.split("|");
|
|
25755
|
-
const cleanedParts = parts.map((part) => part.trim());
|
|
25756
|
-
const normalizedLine = cleanedParts.join(" | ");
|
|
25757
|
-
normalizedLines.push(normalizedLine);
|
|
25758
|
-
} else {
|
|
25759
|
-
normalizedLines.push(line.trimEnd());
|
|
25760
|
-
}
|
|
25761
|
-
}
|
|
25762
|
-
return normalizedLines.join("\n");
|
|
25763
|
-
}
|
|
25764
|
-
function reconstructHeadings(correctedText, headingsHierarchy) {
|
|
25765
|
-
if (!headingsHierarchy || typeof headingsHierarchy !== "object") {
|
|
25766
|
-
return correctedText;
|
|
25767
|
-
}
|
|
25768
|
-
let result = correctedText;
|
|
25769
|
-
function extractHeadingsWithLevels(hierarchy, level = 2) {
|
|
25770
|
-
const headings2 = [];
|
|
25771
|
-
for (const [key, value] of Object.entries(hierarchy)) {
|
|
25772
|
-
headings2.push({ text: key, level });
|
|
25773
|
-
if (value && typeof value === "object") {
|
|
25774
|
-
headings2.push(...extractHeadingsWithLevels(value, level + 1));
|
|
25775
|
-
}
|
|
25776
|
-
}
|
|
25777
|
-
return headings2;
|
|
25778
|
-
}
|
|
25779
|
-
const headings = extractHeadingsWithLevels(headingsHierarchy);
|
|
25780
|
-
for (const { text, level } of headings) {
|
|
25781
|
-
const markdownPrefix = "#".repeat(level);
|
|
25782
|
-
const escapedText = text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
25783
|
-
const regex = new RegExp(
|
|
25784
|
-
`^(${escapedText})$`,
|
|
25785
|
-
"gm"
|
|
25786
|
-
);
|
|
25787
|
-
result = result.replace(regex, `${markdownPrefix} $1`);
|
|
25788
|
-
}
|
|
25789
|
-
return result;
|
|
25790
|
-
}
|
|
25791
|
-
async function validatePageWithVLM(page, imagePath, model) {
|
|
25792
|
-
const imageBuffer = await fs3.promises.readFile(imagePath);
|
|
25793
|
-
const imageBase64 = imageBuffer.toString("base64");
|
|
25794
|
-
const mimeType = "image/png";
|
|
25795
|
-
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.
|
|
25796
|
-
|
|
25797
|
-
---
|
|
25798
|
-
## CURRENT OCR OUTPUT
|
|
25799
|
-
|
|
25800
|
-
${page.content}
|
|
25801
|
-
---
|
|
25802
|
-
|
|
25803
|
-
## YOUR TASK
|
|
25804
|
-
|
|
25805
|
-
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).
|
|
25806
|
-
|
|
25807
|
-
---
|
|
25808
|
-
## VALIDATION CHECKLIST
|
|
25809
|
-
|
|
25810
|
-
Work through these checks in order:
|
|
25811
|
-
|
|
25812
|
-
### 1. Text Accuracy
|
|
25813
|
-
- Verify all text is correctly transcribed.
|
|
25814
|
-
- 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.
|
|
25815
|
-
|
|
25816
|
-
### 2. Heading Levels
|
|
25817
|
-
- Verify that headings use correct Markdown levels (#, ##, ###, ####, #####, ######).
|
|
25818
|
-
- Determine heading level using the following priority:
|
|
25819
|
-
1. **Hierarchical numbering** (strongest signal): e.g. "1" \u2192 #, "2.1" \u2192 ##, "2.1.1" \u2192 ###, "2.1.2.5" \u2192 ####
|
|
25820
|
-
2. Font size (larger = higher level)
|
|
25821
|
-
3. Indentation
|
|
25822
|
-
4. Bold/emphasis styling
|
|
25823
|
-
|
|
25824
|
-
### 3. Tables
|
|
25825
|
-
|
|
25826
|
-
**First, decide whether the table should be Markdown or plain text:**
|
|
25827
|
-
- Use **Markdown table format** if the table has a consistent, clear header structure and uniform column layout throughout.
|
|
25828
|
-
- Use **plain text structured description** if the table:
|
|
25829
|
-
- Lacks a clear header row
|
|
25830
|
-
- Uses mixed or irregular column structures across rows
|
|
25831
|
-
- Functions more like a certificate, form, or label layout
|
|
25832
|
-
|
|
25833
|
-
**If using Markdown format**, follow these rules strictly:
|
|
25834
|
-
- Every table must have: header row \u2192 separator row \u2192 data rows
|
|
25835
|
-
- Use simple separators only: \`| --- | --- |\` (NOT \`|---|---|\` or long dashes)
|
|
25836
|
-
- Example:
|
|
25837
|
-
\`\`\`
|
|
25838
|
-
| Column 1 | Column 2 |
|
|
25839
|
-
| --- | --- |
|
|
25840
|
-
| Data 1 | Data 2 |
|
|
25841
|
-
\`\`\`
|
|
25842
|
-
- 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.
|
|
25843
|
-
|
|
25844
|
-
**Symbol translation rules for table cells:**
|
|
25845
|
-
- Black/filled dot \u2192 \`+\` (active); White/empty dot \u2192 \`-\` (inactive)
|
|
25846
|
-
*(e.g. Rufe-LED columns)*
|
|
25847
|
-
- Green or black checkmark \u2192 \`+\` (active); Red or black cross \u2192 \`-\` (inactive)
|
|
25848
|
-
|
|
25849
|
-
### 4. Multi-Page Table Continuity
|
|
25850
|
-
- 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.
|
|
25851
|
-
- 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\`.
|
|
25852
|
-
|
|
25853
|
-
### 5. Technical Diagrams & Schematics
|
|
25854
|
-
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:
|
|
25855
|
-
- Open a <diagram> tag with the following content:
|
|
25856
|
-
<diagram>
|
|
25857
|
-
<description>
|
|
25858
|
-
Add a detailed description of the diagram here.
|
|
25859
|
-
</description>
|
|
25860
|
-
<mermaid>
|
|
25861
|
-
Add a mermaid diagram schema here that in detail describes the diagram.
|
|
25862
|
-
</mermaid>
|
|
25863
|
-
</diagram>
|
|
25864
|
-
|
|
25865
|
-
### 6. Captions, Icons & Symbols
|
|
25866
|
-
- Verify that image captions, labels, icons, and checkmarks are present and correctly transcribed.
|
|
25867
|
-
|
|
25868
|
-
### 7. Only populate \`corrected_text\` when \`needs_correction\` is true. If the OCR output is accurate, return \`needs_correction: false\` and \`corrected_content: null\`.
|
|
25869
|
-
`;
|
|
25870
|
-
const result = await generateText8({
|
|
25871
|
-
model,
|
|
25872
|
-
output: Output3.object({
|
|
25873
|
-
schema: z19.object({
|
|
25874
|
-
needs_correction: z19.boolean(),
|
|
25875
|
-
corrected_text: z19.string().nullable(),
|
|
25876
|
-
current_page_table: z19.object({
|
|
25877
|
-
headers: z19.array(z19.string()),
|
|
25878
|
-
is_continuation: z19.boolean()
|
|
25879
|
-
}).nullable(),
|
|
25880
|
-
confidence: z19.enum(["high", "medium", "low"]),
|
|
25881
|
-
reasoning: z19.string()
|
|
25882
|
-
})
|
|
25883
|
-
}),
|
|
25884
|
-
messages: [
|
|
25885
|
-
{
|
|
25886
|
-
role: "user",
|
|
25887
|
-
content: [
|
|
25888
|
-
{ type: "text", text: prompt },
|
|
25889
|
-
{
|
|
25890
|
-
type: "image",
|
|
25891
|
-
image: `data:${mimeType};base64,${imageBase64}`
|
|
25892
|
-
}
|
|
25893
|
-
]
|
|
25894
|
-
}
|
|
25895
|
-
]
|
|
25896
|
-
});
|
|
25897
|
-
const parsedOutput = result.output;
|
|
25898
|
-
const validation = {
|
|
25899
|
-
needs_correction: parsedOutput.needs_correction,
|
|
25900
|
-
corrected_text: parsedOutput.corrected_text || void 0,
|
|
25901
|
-
confidence: parsedOutput.confidence,
|
|
25902
|
-
current_page_table: parsedOutput.current_page_table || void 0,
|
|
25903
|
-
reasoning: parsedOutput.reasoning
|
|
25904
|
-
};
|
|
25905
|
-
console.log(`[EXULU] VLM validation result: ${JSON.stringify(validation)}`);
|
|
25906
|
-
return validation;
|
|
25907
|
-
}
|
|
25908
|
-
function reconstructTableHeaders(document, validationResults, verbose = false) {
|
|
25909
|
-
let lastTableHeaders = void 0;
|
|
25910
|
-
for (const page of document) {
|
|
25911
|
-
const validation = validationResults.get(page.page);
|
|
25912
|
-
if (!validation) continue;
|
|
25913
|
-
const tableInfo = validation.current_page_table;
|
|
25914
|
-
if (tableInfo && tableInfo.headers.length > 0) {
|
|
25915
|
-
if (tableInfo.is_continuation && lastTableHeaders) {
|
|
25916
|
-
if (verbose) {
|
|
25917
|
-
console.log(`[EXULU] Page ${page.page}: Reconstructing table headers from previous page`);
|
|
25918
|
-
console.log(`[EXULU] Previous headers: ${lastTableHeaders.join(" | ")}`);
|
|
25919
|
-
}
|
|
25920
|
-
const contentToModify = page.vlm_corrected_text || page.content;
|
|
25921
|
-
const lines = contentToModify.split("\n");
|
|
25922
|
-
const firstTableLineIndex = lines.findIndex((line) => line.trim().startsWith("|"));
|
|
25923
|
-
if (firstTableLineIndex !== -1) {
|
|
25924
|
-
const headerRow = `| ${lastTableHeaders.join(" | ")} |`;
|
|
25925
|
-
const separatorRow = `| ${lastTableHeaders.map(() => "---").join(" | ")} |`;
|
|
25926
|
-
lines.splice(firstTableLineIndex, 0, headerRow, separatorRow);
|
|
25927
|
-
const reconstructedContent = lines.join("\n");
|
|
25928
|
-
if (page.vlm_corrected_text) {
|
|
25929
|
-
page.vlm_corrected_text = reconstructedContent;
|
|
25930
|
-
} else {
|
|
25931
|
-
page.content = reconstructedContent;
|
|
25932
|
-
}
|
|
25933
|
-
if (verbose) {
|
|
25934
|
-
console.log(`[EXULU] Page ${page.page}: Added table headers successfully`);
|
|
25935
|
-
}
|
|
25936
|
-
}
|
|
25937
|
-
if (!tableInfo.is_continuation) {
|
|
25938
|
-
lastTableHeaders = tableInfo.headers;
|
|
25939
|
-
}
|
|
25940
|
-
} else {
|
|
25941
|
-
lastTableHeaders = tableInfo.headers;
|
|
25942
|
-
if (verbose) {
|
|
25943
|
-
console.log(`[EXULU] Page ${page.page}: Storing table headers for potential continuation`);
|
|
25944
|
-
console.log(`[EXULU] Headers: ${lastTableHeaders.join(" | ")}`);
|
|
25945
|
-
}
|
|
25946
|
-
}
|
|
25947
|
-
} else {
|
|
25948
|
-
lastTableHeaders = void 0;
|
|
25949
|
-
}
|
|
25950
|
-
}
|
|
25951
|
-
}
|
|
25952
|
-
async function validateWithVLM(document, model, verbose = false, concurrency = 10) {
|
|
25953
|
-
console.log(`[EXULU] Starting VLM validation for processor output, ${document.length} pages...`);
|
|
25954
|
-
console.log(`[EXULU] Concurrency limit: ${concurrency}`);
|
|
25955
|
-
const limit = pLimit(concurrency);
|
|
25956
|
-
const validationResults = /* @__PURE__ */ new Map();
|
|
25957
|
-
let validatedCount = 0;
|
|
25958
|
-
let correctedCount = 0;
|
|
25959
|
-
const validationTasks = document.map(
|
|
25960
|
-
(page) => limit(async () => {
|
|
25961
|
-
await new Promise((resolve4) => setImmediate(resolve4));
|
|
25962
|
-
const imagePath = page.image;
|
|
25963
|
-
if (!imagePath) {
|
|
25964
|
-
console.warn(`[EXULU] Page ${page.page}: No image found, skipping validation`);
|
|
25965
|
-
return;
|
|
25966
|
-
}
|
|
25967
|
-
if (page.content) {
|
|
25968
|
-
const hasImage = page.content.match(/\.(jpeg|jpg|png|gif|webp)/i);
|
|
25969
|
-
const hasTable = (page.content.match(/\|/g)?.length || 0) > 1;
|
|
25970
|
-
if (!hasImage && !hasTable) {
|
|
25971
|
-
if (verbose) {
|
|
25972
|
-
console.log(`[EXULU] Page ${page.page}: No image or table found, SKIPPING VLM validation`);
|
|
25973
|
-
}
|
|
25974
|
-
return;
|
|
25975
|
-
}
|
|
25976
|
-
} else {
|
|
25977
|
-
if (verbose) {
|
|
25978
|
-
console.log(`[EXULU] Page ${page.page}: Standalone image, proceeding with VLM content extraction`);
|
|
25979
|
-
}
|
|
25980
|
-
}
|
|
25981
|
-
let validation;
|
|
25982
|
-
try {
|
|
25983
|
-
console.log(`[EXULU] Validating page ${page.page} with VLM`);
|
|
25984
|
-
validation = await withRetry(async () => {
|
|
25985
|
-
return await validatePageWithVLM(page, imagePath, model);
|
|
25986
|
-
}, 3);
|
|
25987
|
-
validationResults.set(page.page, validation);
|
|
25988
|
-
if (verbose && validation.current_page_table) {
|
|
25989
|
-
console.log(`[EXULU] Page ${page.page} table info:`, {
|
|
25990
|
-
headers: validation.current_page_table.headers,
|
|
25991
|
-
is_continuation: validation.current_page_table.is_continuation
|
|
25992
|
-
});
|
|
25993
|
-
}
|
|
25994
|
-
} catch (error) {
|
|
25995
|
-
console.error(`[EXULU] Error validating page ${page.page} with VLM more than 3 times, skipping:`, error);
|
|
25996
|
-
throw error;
|
|
25997
|
-
}
|
|
25998
|
-
if (validation.needs_correction && validation.corrected_text) {
|
|
25999
|
-
page.vlm_validated = true;
|
|
26000
|
-
const normalizedText = normalizeMarkdownContent(validation.corrected_text);
|
|
26001
|
-
const correctedWithHeadings = reconstructHeadings(
|
|
26002
|
-
normalizedText,
|
|
26003
|
-
page.headings
|
|
26004
|
-
);
|
|
26005
|
-
page.vlm_corrected_text = correctedWithHeadings;
|
|
26006
|
-
correctedCount++;
|
|
26007
|
-
if (verbose) {
|
|
26008
|
-
console.log(
|
|
26009
|
-
`[EXULU] Page ${page.page}: Corrected (${validation.confidence} confidence)`
|
|
26010
|
-
);
|
|
26011
|
-
console.log(`[EXULU] Reason: ${validation.reasoning}`);
|
|
26012
|
-
}
|
|
26013
|
-
} else {
|
|
26014
|
-
if (verbose) {
|
|
26015
|
-
console.log(
|
|
26016
|
-
`[EXULU] Page ${page.page}: No correction needed (${validation.confidence} confidence)`
|
|
26017
|
-
);
|
|
26018
|
-
}
|
|
26019
|
-
}
|
|
26020
|
-
validatedCount++;
|
|
26021
|
-
})
|
|
26022
|
-
);
|
|
26023
|
-
await Promise.all(validationTasks);
|
|
26024
|
-
console.log(`[EXULU] VLM validation complete (parallel processing):`);
|
|
26025
|
-
console.log(`[EXULU] Validated: ${validatedCount} pages`);
|
|
26026
|
-
console.log(`[EXULU] Corrected: ${correctedCount} pages`);
|
|
26027
|
-
console.log(`[EXULU] Starting sequential table header reconstruction...`);
|
|
26028
|
-
reconstructTableHeaders(document, validationResults, verbose);
|
|
26029
|
-
console.log(`[EXULU] Table header reconstruction complete`);
|
|
26030
|
-
return document;
|
|
26031
|
-
}
|
|
26032
|
-
async function processDocument(filePath, fileType, buffer, tempDir, config, verbose = false) {
|
|
26033
|
-
console.log("Starting document processing...");
|
|
26034
|
-
console.log(`${fileType}: ${filePath}`);
|
|
26035
|
-
const paths = {
|
|
26036
|
-
json: path.join(tempDir, `processed.json`),
|
|
26037
|
-
markdown: path.join(tempDir, `markdown.md`),
|
|
26038
|
-
images: path.join(tempDir, "images"),
|
|
26039
|
-
source: filePath
|
|
26040
|
-
};
|
|
26041
|
-
const stripped = filePath.split(".").pop()?.trim().toLowerCase();
|
|
26042
|
-
let result;
|
|
26043
|
-
switch (stripped) {
|
|
26044
|
-
case "txt":
|
|
26045
|
-
case "md":
|
|
26046
|
-
let content = buffer.toString();
|
|
26047
|
-
content = content.replace(/!\[.*?\]\(data:image\/[^)]+\)/g, "");
|
|
26048
|
-
result = {
|
|
26049
|
-
markdown: content,
|
|
26050
|
-
json: [{
|
|
26051
|
-
page: 1,
|
|
26052
|
-
content,
|
|
26053
|
-
headings: []
|
|
26054
|
-
}]
|
|
26055
|
-
};
|
|
26056
|
-
break;
|
|
26057
|
-
case "pdf":
|
|
26058
|
-
result = await processPdf(buffer, paths, config, verbose);
|
|
26059
|
-
break;
|
|
26060
|
-
case "docx":
|
|
26061
|
-
result = await processDocx(buffer);
|
|
26062
|
-
break;
|
|
26063
|
-
case "doc":
|
|
26064
|
-
result = await processWord(buffer);
|
|
26065
|
-
break;
|
|
26066
|
-
case "jpg":
|
|
26067
|
-
case "jpeg":
|
|
26068
|
-
case "png":
|
|
26069
|
-
case "gif":
|
|
26070
|
-
case "webp":
|
|
26071
|
-
result = await processImage(buffer, paths, config, verbose);
|
|
26072
|
-
break;
|
|
26073
|
-
// Todo other file types with docx and officeparser
|
|
26074
|
-
default:
|
|
26075
|
-
throw new Error(`[EXULU] Unsupported file type: ${fileType}`);
|
|
26076
|
-
}
|
|
26077
|
-
return {
|
|
26078
|
-
content: result,
|
|
26079
|
-
files: {
|
|
26080
|
-
markdown: paths.markdown,
|
|
26081
|
-
json: paths.json
|
|
26082
|
-
}
|
|
26083
|
-
};
|
|
26084
|
-
}
|
|
26085
|
-
async function processPdf(buffer, paths, config, verbose = false) {
|
|
26086
|
-
try {
|
|
26087
|
-
let json = [];
|
|
26088
|
-
if (config?.processor.name === "officeparser") {
|
|
26089
|
-
const text = await parseOfficeAsync2(buffer, {
|
|
26090
|
-
outputErrorToConsole: false,
|
|
26091
|
-
newlineDelimiter: "\n"
|
|
26092
|
-
});
|
|
26093
|
-
json = [{
|
|
26094
|
-
page: 1,
|
|
26095
|
-
content: text,
|
|
26096
|
-
headings: []
|
|
26097
|
-
}];
|
|
26098
|
-
} else if (config?.processor.name === "mistral") {
|
|
26099
|
-
const resolved = await resolveOcr({
|
|
26100
|
-
model: config.processor.model ?? "mistral-ocr",
|
|
26101
|
-
...config.attribution
|
|
26102
|
-
});
|
|
26103
|
-
const maxPagesPerChunk = config.processor.maxPagesPerChunk ?? 25;
|
|
26104
|
-
const chunksDir = path.join(path.dirname(paths.json), "ocr_chunks");
|
|
26105
|
-
const splitResult = await executePythonScript({
|
|
26106
|
-
scriptPath: "ee/python/documents/processing/split_pdf.py",
|
|
26107
|
-
args: [paths.source, chunksDir, "--chunk-size", String(maxPagesPerChunk), "--max-size-mb", "25"],
|
|
26108
|
-
timeout: 5 * 60 * 1e3
|
|
26109
|
-
});
|
|
26110
|
-
let pdfChunks;
|
|
26111
|
-
try {
|
|
26112
|
-
pdfChunks = JSON.parse(splitResult.stdout);
|
|
26113
|
-
} catch (err2) {
|
|
26114
|
-
throw new Error(
|
|
26115
|
-
`[EXULU] split_pdf.py returned invalid JSON on stdout: ${err2.message}
|
|
26116
|
-
stdout: ${splitResult.stdout.slice(0, 500)}
|
|
26117
|
-
stderr: ${splitResult.stderr.slice(-1e3)}`
|
|
26118
|
-
);
|
|
26119
|
-
}
|
|
26120
|
-
console.log(`[EXULU] PDF split into ${pdfChunks.length} chunk(s) for OCR (max ${maxPagesPerChunk} pages each)`);
|
|
26121
|
-
const chunkLimit = pLimit(3);
|
|
26122
|
-
const chunkResults = await Promise.all(
|
|
26123
|
-
pdfChunks.map(
|
|
26124
|
-
(chunk2, i) => chunkLimit(async () => {
|
|
26125
|
-
await new Promise((resolve4) => setImmediate(resolve4));
|
|
26126
|
-
await new Promise((resolve4) => setTimeout(resolve4, Math.floor(Math.random() * 1e3) + 200));
|
|
26127
|
-
console.log(`[EXULU] OCR chunk ${i + 1}/${pdfChunks.length}: pages ${chunk2.start_page}\u2013${chunk2.end_page - 1}`);
|
|
26128
|
-
const chunkBuffer = await fs3.promises.readFile(chunk2.path);
|
|
26129
|
-
const chunkBase64 = chunkBuffer.toString("base64");
|
|
26130
|
-
const chunkResponse = await withRetry(async () => {
|
|
26131
|
-
return await resolved.ocr({
|
|
26132
|
-
type: "document_url",
|
|
26133
|
-
document_url: "data:application/pdf;base64," + chunkBase64
|
|
26134
|
-
}, { includeImageBase64: false });
|
|
26135
|
-
}, 10);
|
|
26136
|
-
return { pages: chunkResponse.pages, offset: chunk2.start_page };
|
|
26137
|
-
})
|
|
26138
|
-
)
|
|
26139
|
-
);
|
|
26140
|
-
const mergedPages = chunkResults.sort((a, b) => a.offset - b.offset).flatMap(
|
|
26141
|
-
({ pages, offset }) => pages.map((p) => ({ ...p, index: p.index + offset }))
|
|
26142
|
-
);
|
|
26143
|
-
const parser = new LiteParse();
|
|
26144
|
-
const screenshots = await parser.screenshot(paths.source, void 0);
|
|
26145
|
-
await fs3.promises.mkdir(paths.images, { recursive: true });
|
|
26146
|
-
for (const screenshot of screenshots) {
|
|
26147
|
-
await fs3.promises.writeFile(
|
|
26148
|
-
path.join(
|
|
26149
|
-
paths.images,
|
|
26150
|
-
`${screenshot.pageNum}.png`
|
|
26151
|
-
),
|
|
26152
|
-
screenshot.imageBuffer
|
|
26153
|
-
);
|
|
26154
|
-
screenshot.imagePath = path.join(paths.images, `${screenshot.pageNum}.png`);
|
|
26155
|
-
}
|
|
26156
|
-
json = mergedPages.map((page) => ({
|
|
26157
|
-
page: page.index + 1,
|
|
26158
|
-
content: page.markdown,
|
|
26159
|
-
image: screenshots.find((s) => s.pageNum === page.index + 1)?.imagePath,
|
|
26160
|
-
headings: []
|
|
26161
|
-
}));
|
|
26162
|
-
fs3.writeFileSync(paths.json, JSON.stringify(json, null, 2));
|
|
26163
|
-
} else if (config?.processor.name === "liteparse") {
|
|
26164
|
-
const parser = new LiteParse();
|
|
26165
|
-
const result = await parser.parse(paths.source);
|
|
26166
|
-
const screenshots = await parser.screenshot(paths.source, void 0);
|
|
26167
|
-
console.log(`[EXULU] Liteparse screenshots: ${JSON.stringify(screenshots)}`);
|
|
26168
|
-
await fs3.promises.mkdir(paths.images, { recursive: true });
|
|
26169
|
-
for (const screenshot of screenshots) {
|
|
26170
|
-
await fs3.promises.writeFile(path.join(paths.images, `${screenshot.pageNum}.png`), screenshot.imageBuffer);
|
|
26171
|
-
screenshot.imagePath = path.join(paths.images, `${screenshot.pageNum}.png`);
|
|
26172
|
-
}
|
|
26173
|
-
json = result.pages.map((page) => ({
|
|
26174
|
-
page: page.pageNum,
|
|
26175
|
-
content: page.text,
|
|
26176
|
-
image: screenshots.find((s) => s.pageNum === page.pageNum)?.imagePath
|
|
26177
|
-
}));
|
|
26178
|
-
fs3.writeFileSync(paths.json, JSON.stringify(json, null, 2));
|
|
26179
|
-
} else {
|
|
26180
|
-
const configured = String(config?.processor?.name ?? "");
|
|
26181
|
-
throw new Error(
|
|
26182
|
-
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.' : "")
|
|
26183
|
-
);
|
|
26184
|
-
}
|
|
26185
|
-
console.log(`[EXULU]
|
|
26186
|
-
\u2713 Document processing completed successfully`);
|
|
26187
|
-
console.log(`[EXULU] Total pages: ${json.length}`);
|
|
26188
|
-
console.log(`[EXULU] Output file: ${paths.json}`);
|
|
26189
|
-
const vlmModel = config?.vlm?.model ? await resolveVlmModel(config) : void 0;
|
|
26190
|
-
if (vlmModel && json.length > 0) {
|
|
26191
|
-
json = await validateWithVLM(
|
|
26192
|
-
json,
|
|
26193
|
-
vlmModel,
|
|
26194
|
-
verbose,
|
|
26195
|
-
config.vlm.concurrency
|
|
26196
|
-
);
|
|
26197
|
-
console.log("[EXULU] \n\u{1F4CA} Processing Summary:");
|
|
26198
|
-
console.log(`[EXULU] Total pages: ${json.length}`);
|
|
26199
|
-
const validatedPages = json.filter((p) => p.vlm_validated);
|
|
26200
|
-
const correctedPages = json.filter((p) => p.vlm_corrected_text);
|
|
26201
|
-
console.log(`[EXULU] VLM validated pages: ${validatedPages.length}`);
|
|
26202
|
-
console.log(`[EXULU] VLM corrected pages: ${correctedPages.length}`);
|
|
26203
|
-
if (correctedPages.length > 0) {
|
|
26204
|
-
console.log("\n\u{1F527} Example Corrections:");
|
|
26205
|
-
correctedPages.slice(0, 2).forEach((page) => {
|
|
26206
|
-
console.log(`[EXULU]
|
|
26207
|
-
Page ${page.page} (Page ${page.page}):`);
|
|
26208
|
-
console.log(`[EXULU] Original: ${page.content.substring(0, 150)}...`);
|
|
26209
|
-
console.log(`[EXULU] Corrected: ${page.vlm_corrected_text.substring(0, 150)}...`);
|
|
26210
|
-
});
|
|
26211
|
-
}
|
|
26212
|
-
await fs3.promises.writeFile(
|
|
26213
|
-
paths.json,
|
|
26214
|
-
JSON.stringify(json, null, 2),
|
|
26215
|
-
"utf-8"
|
|
26216
|
-
);
|
|
26217
|
-
}
|
|
26218
|
-
const markdownStream = fs3.createWriteStream(paths.markdown, { encoding: "utf-8" });
|
|
26219
|
-
for (let i = 0; i < json.length; i++) {
|
|
26220
|
-
const p = json[i];
|
|
26221
|
-
if (!p) continue;
|
|
26222
|
-
const content = p.vlm_corrected_text ?? p.content;
|
|
26223
|
-
markdownStream.write(content);
|
|
26224
|
-
if (i < json.length - 1) {
|
|
26225
|
-
markdownStream.write("\n\n\n<!-- END_OF_PAGE -->\n\n\n");
|
|
26226
|
-
}
|
|
26227
|
-
}
|
|
26228
|
-
await new Promise((resolve4, reject) => {
|
|
26229
|
-
markdownStream.end(() => resolve4());
|
|
26230
|
-
markdownStream.on("error", reject);
|
|
26231
|
-
});
|
|
26232
|
-
console.log(`[EXULU] Validated output saved to: ${paths.json}`);
|
|
26233
|
-
console.log(`[EXULU] Validated markdown saved to: ${paths.markdown}`);
|
|
26234
|
-
const markdown = await fs3.promises.readFile(paths.markdown, "utf-8");
|
|
26235
|
-
const processedJson = json.map((e) => {
|
|
26236
|
-
const finalContent = e.vlm_corrected_text ?? e.content;
|
|
26237
|
-
return {
|
|
26238
|
-
page: e.page,
|
|
26239
|
-
content: finalContent
|
|
26240
|
-
};
|
|
26241
|
-
});
|
|
26242
|
-
json.length = 0;
|
|
26243
|
-
json = [];
|
|
26244
|
-
const memUsage = process.memoryUsage();
|
|
26245
|
-
console.log(`[EXULU] Memory after document processing: ${Math.round(memUsage.heapUsed / 1024 / 1024)}MB / ${Math.round(memUsage.heapTotal / 1024 / 1024)}MB`);
|
|
26246
|
-
return {
|
|
26247
|
-
markdown,
|
|
26248
|
-
json: processedJson
|
|
26249
|
-
};
|
|
26250
|
-
} catch (error) {
|
|
26251
|
-
console.error("[EXULU] Error processing document:", error);
|
|
26252
|
-
throw error;
|
|
26253
|
-
}
|
|
26254
|
-
}
|
|
26255
|
-
var loadFile = async (file, name, tempDir) => {
|
|
26256
|
-
let filePath = file;
|
|
26257
|
-
let fileType = name?.split(".").pop();
|
|
26258
|
-
if (!fileType) {
|
|
26259
|
-
throw new Error("[EXULU] File name does not include extension, extension is required for document processing.");
|
|
26260
|
-
}
|
|
26261
|
-
const UUID2 = randomUUID12();
|
|
26262
|
-
let buffer;
|
|
26263
|
-
if (Buffer.isBuffer(file)) {
|
|
26264
|
-
filePath = path.join(tempDir, `${UUID2}.${fileType}`);
|
|
26265
|
-
await fs3.promises.writeFile(filePath, file);
|
|
26266
|
-
buffer = file;
|
|
26267
|
-
} else {
|
|
26268
|
-
filePath = filePath.trim();
|
|
26269
|
-
if (filePath.startsWith("http")) {
|
|
26270
|
-
const response = await fetch(filePath);
|
|
26271
|
-
const array = await response.arrayBuffer();
|
|
26272
|
-
const tempFilePath = path.join(tempDir, `${UUID2}.${fileType}`);
|
|
26273
|
-
await fs3.promises.writeFile(tempFilePath, Buffer.from(array));
|
|
26274
|
-
buffer = Buffer.from(array);
|
|
26275
|
-
filePath = tempFilePath;
|
|
26276
|
-
} else {
|
|
26277
|
-
buffer = await fs3.promises.readFile(file);
|
|
26278
|
-
}
|
|
26279
|
-
}
|
|
26280
|
-
return { filePath, fileType, buffer };
|
|
26281
|
-
};
|
|
26282
|
-
async function documentProcessor({
|
|
26283
|
-
file,
|
|
26284
|
-
name,
|
|
26285
|
-
config
|
|
26286
|
-
}) {
|
|
26287
|
-
const license = checkLicense();
|
|
26288
|
-
if (!license["advanced-document-processing"]) {
|
|
26289
|
-
throw new Error("Advanced document processing is an enterprise feature, please add a valid Exulu enterprise license key to use it.");
|
|
26290
|
-
}
|
|
26291
|
-
const uuid = randomUUID12();
|
|
26292
|
-
const tempDir = path.join(process.cwd(), "temp", uuid);
|
|
26293
|
-
const localFilesAndFoldersToDelete = [tempDir];
|
|
26294
|
-
console.log(`[EXULU] Temporary directory for processing document ${name}: ${tempDir}`);
|
|
26295
|
-
await fs3.promises.mkdir(tempDir, { recursive: true });
|
|
26296
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
26297
|
-
await fs3.promises.writeFile(path.join(tempDir, "created_at.txt"), timestamp);
|
|
26298
|
-
try {
|
|
26299
|
-
const {
|
|
26300
|
-
filePath,
|
|
26301
|
-
fileType,
|
|
26302
|
-
buffer
|
|
26303
|
-
} = await loadFile(file, name, tempDir);
|
|
26304
|
-
let supportedTypes = [];
|
|
26305
|
-
switch (config?.processor.name) {
|
|
26306
|
-
case "officeparser":
|
|
26307
|
-
supportedTypes = ["docx", "pptx", "xlsx", "odt", "odp", "ods", "pdf", "rtf", "csv", "md", "html"];
|
|
26308
|
-
break;
|
|
26309
|
-
case "liteparse":
|
|
26310
|
-
supportedTypes = ["pdf", "doc", "docx", "docm", "odt", "rtf", "ppt", "pptx", "pptm", "odp", "xls", "xlsx", "xlsm", "ods", "csv", "tsv"];
|
|
26311
|
-
break;
|
|
26312
|
-
case "mistral":
|
|
26313
|
-
supportedTypes = ["pdf", "docx", "doc", "txt", "md", "jpg", "jpeg", "png", "gif", "webp"];
|
|
26314
|
-
break;
|
|
26315
|
-
}
|
|
26316
|
-
if (!supportedTypes.includes(fileType.toLowerCase())) {
|
|
26317
|
-
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(", ")}.`);
|
|
26318
|
-
}
|
|
26319
|
-
const { content } = await processDocument(
|
|
26320
|
-
filePath,
|
|
26321
|
-
fileType,
|
|
26322
|
-
buffer,
|
|
26323
|
-
tempDir,
|
|
26324
|
-
config,
|
|
26325
|
-
true
|
|
26326
|
-
);
|
|
26327
|
-
return content.json;
|
|
26328
|
-
} catch (error) {
|
|
26329
|
-
console.error("Error during chunking:", error);
|
|
26330
|
-
throw error;
|
|
26331
|
-
} finally {
|
|
26332
|
-
if (config?.debugging?.deleteTempFiles !== false) {
|
|
26333
|
-
for (const file2 of localFilesAndFoldersToDelete) {
|
|
26334
|
-
try {
|
|
26335
|
-
await fs3.promises.rm(file2, { recursive: true });
|
|
26336
|
-
console.log(`[EXULU] Deleted file or folder: ${file2}`);
|
|
26337
|
-
} catch (error) {
|
|
26338
|
-
console.error(`[EXULU] Error deleting file or folder: ${file2}`, error);
|
|
26339
|
-
console.log(`[EXULU] File or folder still exists: ${file2}`);
|
|
26340
|
-
}
|
|
26341
|
-
}
|
|
26342
|
-
}
|
|
26343
|
-
}
|
|
26344
|
-
}
|
|
26345
|
-
|
|
26346
25479
|
// src/exulu/reranker.ts
|
|
26347
25480
|
async function rerank(input) {
|
|
26348
25481
|
const { query, items, topN, ...resolveInput } = input;
|
|
@@ -26700,12 +25833,12 @@ async function fitContextProjection({
|
|
|
26700
25833
|
const basis = randomizedPCA(vectors, dims, Math.min(budget, dims, vectors.length - 1), seed, POWER_ITERATIONS);
|
|
26701
25834
|
if (basis.length === 0) return empty(`${contextId} has no variance in its embeddings`);
|
|
26702
25835
|
const reduced = vectors.map((v) => projectComponents(v, mean, basis));
|
|
26703
|
-
const spread = reduced.reduce((s,
|
|
25836
|
+
const spread = reduced.reduce((s, z19) => s + Math.hypot(...Array.from(z19)), 0) / reduced.length;
|
|
26704
25837
|
if (!Number.isFinite(spread) || spread < 1e-8) return empty(`${contextId} has no variance in its embeddings`);
|
|
26705
25838
|
log6(`fitting ${contextId}: ${vectors.length} vectors, ${dims} dims \u2192 ${basis.length} components`);
|
|
26706
25839
|
log6(`${contextId}: laying out ${reduced.length} points in 3d (the slow phase)`);
|
|
26707
25840
|
const umap = (umapFactory ?? defaultUmap)(seed, reduced.length);
|
|
26708
|
-
const raw = umap.fit(reduced.map((
|
|
25841
|
+
const raw = umap.fit(reduced.map((z19) => Array.from(z19)));
|
|
26709
25842
|
const oriented = rotateLayout(raw, principalRotation(raw, seed));
|
|
26710
25843
|
const { points: layout, scale } = normalizeLayout(oriented);
|
|
26711
25844
|
if (!Number.isFinite(scale) || scale <= 0) return empty(`${contextId} produced a degenerate layout (every point in one place)`);
|
|
@@ -26790,13 +25923,13 @@ async function backfillCoordinates({
|
|
|
26790
25923
|
const raw = parseVector(row.embedding);
|
|
26791
25924
|
if (raw.length !== projection.dims) continue;
|
|
26792
25925
|
const known = layout?.get(String(row.id));
|
|
26793
|
-
const [x, y,
|
|
25926
|
+
const [x, y, z19] = known ?? applyMap(
|
|
26794
25927
|
projectComponents(l2normalize(raw), mean, basis),
|
|
26795
25928
|
projection.map,
|
|
26796
25929
|
projection.intercept
|
|
26797
25930
|
);
|
|
26798
25931
|
values.push("(?::uuid, ?::real, ?::real, ?::real)");
|
|
26799
|
-
bindings.push(row.id, x, y,
|
|
25932
|
+
bindings.push(row.id, x, y, z19);
|
|
26800
25933
|
}
|
|
26801
25934
|
if (values.length) {
|
|
26802
25935
|
await db.raw(
|