@exulu/backend 5.12.0 → 5.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-RNZ4IDCT.js → chunk-KLPCQWM3.js} +74 -18
- package/dist/{chunk-4W3V7IHR.js → chunk-NBDSN45T.js} +22 -0
- package/dist/{chunk-U4UIVZST.js → chunk-QU67ANL5.js} +2909 -451
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-WEC42QHZ.js → convert-exulu-tools-to-ai-sdk-tools-UT7TOLLD.js} +2 -2
- package/dist/doc_processor-SVOSOVOY.js +12 -0
- package/dist/index.cjs +4530 -1589
- package/dist/index.d.cts +100 -4
- package/dist/index.d.ts +100 -4
- package/dist/index.js +842 -604
- package/ee/invoke-skills/create-sandbox.project-session.test.ts +184 -0
- package/ee/invoke-skills/create-sandbox.project.test.ts +47 -0
- package/ee/invoke-skills/create-sandbox.symlink.test.ts +296 -0
- package/ee/invoke-skills/create-sandbox.ts +146 -37
- package/ee/invoke-skills/project-sync.test.ts +389 -0
- package/ee/invoke-skills/project-sync.ts +306 -0
- package/ee/invoke-skills/safe-fs.test.ts +69 -0
- package/ee/invoke-skills/safe-fs.ts +216 -0
- package/ee/python/documents/processing/doc_processor.limits.test.ts +257 -0
- package/ee/python/documents/processing/doc_processor.progress.test.ts +151 -0
- package/ee/python/documents/processing/doc_processor.ts +115 -13
- package/ee/python/documents/processing/limits.test.ts +35 -0
- package/ee/python/documents/processing/limits.ts +54 -0
- package/ee/workers.ts +87 -86
- package/package.json +1 -1
- package/dist/doc_processor-E5GCE2ZT.js +0 -10
|
@@ -16,6 +16,8 @@ import { LiteParse } from '@llamaindex/liteparse';
|
|
|
16
16
|
import { resolveOcr } from '@SRC/exulu/resolve-ocr';
|
|
17
17
|
import type { ResolveOcrInput } from '@SRC/exulu/resolve-ocr';
|
|
18
18
|
import { resolveModel } from '@SRC/exulu/resolve-model';
|
|
19
|
+
import type { ProgressFn } from '@SRC/exulu/document-cache/progress';
|
|
20
|
+
import { ocrConcurrency, type ProviderLimiters } from './limits';
|
|
19
21
|
|
|
20
22
|
export type DocumentProcessorConfig = {
|
|
21
23
|
vlm?: {
|
|
@@ -29,6 +31,14 @@ export type DocumentProcessorConfig = {
|
|
|
29
31
|
model: string;
|
|
30
32
|
concurrency: number;
|
|
31
33
|
},
|
|
34
|
+
/**
|
|
35
|
+
* OCR settings. `concurrency` is how many OCR chunk calls ONE document runs
|
|
36
|
+
* at once (default 3, 1..8). Reads in chat additionally share a process-wide
|
|
37
|
+
* ceiling of 8 (see limits.ts); knowledge-base processing does not.
|
|
38
|
+
*/
|
|
39
|
+
ocr?: {
|
|
40
|
+
concurrency?: number;
|
|
41
|
+
}
|
|
32
42
|
processor: {
|
|
33
43
|
name: "liteparse" | "mistral" | "officeparser"
|
|
34
44
|
/**
|
|
@@ -67,6 +77,8 @@ export type ProcessedPage = {
|
|
|
67
77
|
image?: string;
|
|
68
78
|
vlm_corrected_text?: string;
|
|
69
79
|
vlm_validated?: boolean;
|
|
80
|
+
/** Set only under tolerateVisionFailures: the vision pass failed for this page, the text is OCR only. */
|
|
81
|
+
vlm_failed?: boolean;
|
|
70
82
|
}
|
|
71
83
|
export type ProcessedDocument = ProcessedPage[];
|
|
72
84
|
|
|
@@ -163,6 +175,9 @@ async function processImage(
|
|
|
163
175
|
paths: ProcessingPaths,
|
|
164
176
|
config?: DocumentProcessorConfig,
|
|
165
177
|
verbose: boolean = false,
|
|
178
|
+
tolerateVisionFailures: boolean = false,
|
|
179
|
+
onProgress?: ProgressFn,
|
|
180
|
+
limiters?: ProviderLimiters,
|
|
166
181
|
): Promise<ProcessorOutput> {
|
|
167
182
|
try {
|
|
168
183
|
// Create images directory
|
|
@@ -191,7 +206,10 @@ async function processImage(
|
|
|
191
206
|
json,
|
|
192
207
|
vlmModel,
|
|
193
208
|
verbose,
|
|
194
|
-
config!.vlm!.concurrency
|
|
209
|
+
config!.vlm!.concurrency,
|
|
210
|
+
tolerateVisionFailures,
|
|
211
|
+
onProgress,
|
|
212
|
+
limiters,
|
|
195
213
|
);
|
|
196
214
|
|
|
197
215
|
// Save the processed result
|
|
@@ -311,12 +329,14 @@ function reconstructHeadings(
|
|
|
311
329
|
}
|
|
312
330
|
|
|
313
331
|
/**
|
|
314
|
-
* Validates and potentially corrects all chunks from a page using VLM
|
|
332
|
+
* Validates and potentially corrects all chunks from a page using VLM.
|
|
333
|
+
* `timeoutMs` is set on the chat path only (see ProviderLimiters.visionTimeoutMs).
|
|
315
334
|
*/
|
|
316
335
|
async function validatePageWithVLM(
|
|
317
336
|
page: ProcessedPage,
|
|
318
337
|
imagePath: string,
|
|
319
|
-
model: LanguageModel
|
|
338
|
+
model: LanguageModel,
|
|
339
|
+
timeoutMs?: number,
|
|
320
340
|
): Promise<VLMValidationResult> {
|
|
321
341
|
// Read the image as base64
|
|
322
342
|
const imageBuffer = await fs.promises.readFile(imagePath);
|
|
@@ -401,6 +421,8 @@ If the page contains a flow-chart, schematic, technical drawing or control board
|
|
|
401
421
|
|
|
402
422
|
const result = await generateText({
|
|
403
423
|
model: model,
|
|
424
|
+
// Chat path only: a stalled provider must not pin a slot. Without it the SDK default applies, as before.
|
|
425
|
+
...(timeoutMs ? { abortSignal: AbortSignal.timeout(timeoutMs) } : {}),
|
|
404
426
|
output: Output.object({
|
|
405
427
|
schema: z.object({
|
|
406
428
|
needs_correction: z.boolean(),
|
|
@@ -455,7 +477,7 @@ If the page contains a flow-chart, schematic, technical drawing or control board
|
|
|
455
477
|
/**
|
|
456
478
|
* Reconstructs table headers across pages sequentially after parallel VLM processing
|
|
457
479
|
*/
|
|
458
|
-
function reconstructTableHeaders(
|
|
480
|
+
export function reconstructTableHeaders(
|
|
459
481
|
document: ProcessedDocument,
|
|
460
482
|
validationResults: Map<number, VLMValidationResult>,
|
|
461
483
|
verbose: boolean = false
|
|
@@ -464,6 +486,11 @@ function reconstructTableHeaders(
|
|
|
464
486
|
|
|
465
487
|
for (const page of document) {
|
|
466
488
|
const validation = validationResults.get(page.page);
|
|
489
|
+
if (page.vlm_failed) {
|
|
490
|
+
// Nothing is known about this page's table, so headers carried from before it must not reach later pages.
|
|
491
|
+
lastTableHeaders = undefined;
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
467
494
|
if (!validation) continue;
|
|
468
495
|
|
|
469
496
|
const tableInfo = validation.current_page_table;
|
|
@@ -524,6 +551,24 @@ function reconstructTableHeaders(
|
|
|
524
551
|
}
|
|
525
552
|
}
|
|
526
553
|
|
|
554
|
+
/** Progress is advisory: a throwing callback must never touch processing. */
|
|
555
|
+
function safeProgress(onProgress: ProgressFn | undefined, p: Parameters<ProgressFn>[0]): void {
|
|
556
|
+
try {
|
|
557
|
+
onProgress?.(p);
|
|
558
|
+
} catch (error) {
|
|
559
|
+
console.warn('[EXULU] onProgress callback threw; ignored:', error instanceof Error ? error.message : String(error));
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** Whether a page gets a vision pass: it has an image and either no text yet or an image/table in its text. */
|
|
564
|
+
function needsVisionPass(page: ProcessedPage): boolean {
|
|
565
|
+
if (!page.image) return false;
|
|
566
|
+
if (!page.content) return true;
|
|
567
|
+
const hasImage = page.content.match(/\.(jpeg|jpg|png|gif|webp)/i);
|
|
568
|
+
const hasTable = (page.content.match(/\|/g)?.length || 0) > 1;
|
|
569
|
+
return Boolean(hasImage || hasTable);
|
|
570
|
+
}
|
|
571
|
+
|
|
527
572
|
/**
|
|
528
573
|
* Identifies pages that need VLM validation and validates them in parallel
|
|
529
574
|
*/
|
|
@@ -531,7 +576,10 @@ async function validateWithVLM(
|
|
|
531
576
|
document: ProcessedDocument,
|
|
532
577
|
model: LanguageModel,
|
|
533
578
|
verbose: boolean = false,
|
|
534
|
-
concurrency: number = 10
|
|
579
|
+
concurrency: number = 10,
|
|
580
|
+
tolerateVisionFailures: boolean = false,
|
|
581
|
+
onProgress?: ProgressFn,
|
|
582
|
+
limiters?: ProviderLimiters,
|
|
535
583
|
): Promise<ProcessedDocument> {
|
|
536
584
|
console.log(`[EXULU] Starting VLM validation for processor output, ${document.length} pages...`);
|
|
537
585
|
console.log(`[EXULU] Concurrency limit: ${concurrency}`);
|
|
@@ -542,6 +590,14 @@ async function validateWithVLM(
|
|
|
542
590
|
// Store validation results for post-processing
|
|
543
591
|
const validationResults = new Map<number, VLMValidationResult>();
|
|
544
592
|
|
|
593
|
+
// Progress counts the pages that actually get a vision pass.
|
|
594
|
+
const visionTotal = document.filter(needsVisionPass).length;
|
|
595
|
+
let visionDone = 0;
|
|
596
|
+
const reportVisionPage = () => {
|
|
597
|
+
visionDone++;
|
|
598
|
+
safeProgress(onProgress, { phase: "vision", pagesDone: visionDone, pagesTotal: visionTotal });
|
|
599
|
+
};
|
|
600
|
+
|
|
545
601
|
// Track metrics
|
|
546
602
|
let validatedCount = 0;
|
|
547
603
|
let correctedCount = 0;
|
|
@@ -586,11 +642,14 @@ async function validateWithVLM(
|
|
|
586
642
|
try {
|
|
587
643
|
console.log(`[EXULU] Validating page ${page.page} with VLM`);
|
|
588
644
|
validation = await withRetry(async () => {
|
|
589
|
-
|
|
645
|
+
// Process-wide ceiling (chat paths only), taken per attempt so a retry queues again.
|
|
646
|
+
const attempt = () => validatePageWithVLM(page, imagePath, model, limiters?.visionTimeoutMs);
|
|
647
|
+
return await (limiters ? limiters.vision(attempt) : attempt());
|
|
590
648
|
}, 3);
|
|
591
649
|
|
|
592
650
|
// Store validation result for post-processing
|
|
593
651
|
validationResults.set(page.page, validation);
|
|
652
|
+
reportVisionPage();
|
|
594
653
|
|
|
595
654
|
if (verbose && validation.current_page_table) {
|
|
596
655
|
console.log(`[EXULU] Page ${page.page} table info:`, {
|
|
@@ -600,6 +659,12 @@ async function validateWithVLM(
|
|
|
600
659
|
}
|
|
601
660
|
} catch (error) {
|
|
602
661
|
console.error(`[EXULU] Error validating page ${page.page} with VLM more than 3 times, skipping:`, error);
|
|
662
|
+
if (tolerateVisionFailures) {
|
|
663
|
+
// The page keeps its OCR text; the caller reports it as unverified.
|
|
664
|
+
page.vlm_failed = true;
|
|
665
|
+
reportVisionPage();
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
603
668
|
// Throw so the job fails
|
|
604
669
|
throw error;
|
|
605
670
|
}
|
|
@@ -667,6 +732,9 @@ async function processDocument(
|
|
|
667
732
|
tempDir: string,
|
|
668
733
|
config?: DocumentProcessorConfig,
|
|
669
734
|
verbose: boolean = false,
|
|
735
|
+
tolerateVisionFailures: boolean = false,
|
|
736
|
+
onProgress?: ProgressFn,
|
|
737
|
+
limiters?: ProviderLimiters,
|
|
670
738
|
): Promise<{
|
|
671
739
|
content: {
|
|
672
740
|
markdown: string,
|
|
@@ -712,7 +780,7 @@ async function processDocument(
|
|
|
712
780
|
};
|
|
713
781
|
break;
|
|
714
782
|
case 'pdf':
|
|
715
|
-
result = await processPdf(buffer, paths, config, verbose);
|
|
783
|
+
result = await processPdf(buffer, paths, config, verbose, tolerateVisionFailures, onProgress, limiters);
|
|
716
784
|
break;
|
|
717
785
|
case 'docx':
|
|
718
786
|
result = await processDocx(buffer);
|
|
@@ -725,7 +793,7 @@ async function processDocument(
|
|
|
725
793
|
case 'png':
|
|
726
794
|
case 'gif':
|
|
727
795
|
case 'webp':
|
|
728
|
-
result = await processImage(buffer, paths, config, verbose);
|
|
796
|
+
result = await processImage(buffer, paths, config, verbose, tolerateVisionFailures, onProgress, limiters);
|
|
729
797
|
break;
|
|
730
798
|
|
|
731
799
|
// Todo other file types with docx and officeparser
|
|
@@ -746,6 +814,9 @@ async function processPdf(
|
|
|
746
814
|
paths: ProcessingPaths,
|
|
747
815
|
config?: DocumentProcessorConfig,
|
|
748
816
|
verbose: boolean = false,
|
|
817
|
+
tolerateVisionFailures: boolean = false,
|
|
818
|
+
onProgress?: ProgressFn,
|
|
819
|
+
limiters?: ProviderLimiters,
|
|
749
820
|
): Promise<ProcessorOutput> {
|
|
750
821
|
try {
|
|
751
822
|
let json: ProcessedDocument = [];
|
|
@@ -770,6 +841,8 @@ async function processPdf(
|
|
|
770
841
|
const resolved = await resolveOcr({
|
|
771
842
|
model: config.processor.model ?? "mistral-ocr",
|
|
772
843
|
...config.attribution,
|
|
844
|
+
// Chat path only; knowledge-base processing passes no limiters and gets no explicit timeout.
|
|
845
|
+
...(limiters?.ocrTimeoutMs ? { timeoutMs: limiters.ocrTimeoutMs } : {}),
|
|
773
846
|
});
|
|
774
847
|
|
|
775
848
|
// Split the PDF into ≤ N-page chunks before sending to OCR.
|
|
@@ -806,7 +879,9 @@ async function processPdf(
|
|
|
806
879
|
|
|
807
880
|
// Process chunks in parallel with a concurrency cap to respect rate limits.
|
|
808
881
|
// Each chunk gets a small random jitter to spread out requests.
|
|
809
|
-
const chunkLimit = pLimit(
|
|
882
|
+
const chunkLimit = pLimit(ocrConcurrency(config));
|
|
883
|
+
const ocrTotal = pdfChunks.reduce((sum, c) => sum + (c.end_page - c.start_page), 0);
|
|
884
|
+
let ocrDone = 0;
|
|
810
885
|
|
|
811
886
|
const chunkResults = await Promise.all(
|
|
812
887
|
pdfChunks.map((chunk, i) =>
|
|
@@ -821,12 +896,20 @@ async function processPdf(
|
|
|
821
896
|
const chunkBase64 = chunkBuffer.toString('base64');
|
|
822
897
|
|
|
823
898
|
const chunkResponse = await withRetry(async () => {
|
|
824
|
-
|
|
899
|
+
// With limiters (chat paths) the per-document slot (chunkLimit) is held while
|
|
900
|
+
// this waits for the process-wide slot; the process-wide queue never waits on
|
|
901
|
+
// a per-document one, so the nesting cannot deadlock.
|
|
902
|
+
const attempt = () => resolved.ocr({
|
|
825
903
|
type: "document_url",
|
|
826
904
|
document_url: "data:application/pdf;base64," + chunkBase64,
|
|
827
905
|
}, { includeImageBase64: false });
|
|
906
|
+
return await (limiters ? limiters.ocr(attempt) : attempt());
|
|
828
907
|
}, 10);
|
|
829
908
|
|
|
909
|
+
// Chunks finish out of order; the shared counter keeps the reported count monotonic.
|
|
910
|
+
ocrDone += chunk.end_page - chunk.start_page;
|
|
911
|
+
safeProgress(onProgress, { phase: "ocr", pagesDone: ocrDone, pagesTotal: ocrTotal });
|
|
912
|
+
|
|
830
913
|
return { pages: chunkResponse.pages, offset: chunk.start_page };
|
|
831
914
|
})
|
|
832
915
|
)
|
|
@@ -915,7 +998,10 @@ async function processPdf(
|
|
|
915
998
|
json,
|
|
916
999
|
vlmModel,
|
|
917
1000
|
verbose,
|
|
918
|
-
config!.vlm!.concurrency
|
|
1001
|
+
config!.vlm!.concurrency,
|
|
1002
|
+
tolerateVisionFailures,
|
|
1003
|
+
onProgress,
|
|
1004
|
+
limiters,
|
|
919
1005
|
);
|
|
920
1006
|
|
|
921
1007
|
console.log('[EXULU] \n📊 Processing Summary:');
|
|
@@ -980,6 +1066,7 @@ async function processPdf(
|
|
|
980
1066
|
return {
|
|
981
1067
|
page: e.page,
|
|
982
1068
|
content: finalContent,
|
|
1069
|
+
...(e.vlm_failed ? { vlm_failed: true } : {}),
|
|
983
1070
|
};
|
|
984
1071
|
});
|
|
985
1072
|
|
|
@@ -1046,11 +1133,23 @@ const loadFile = async (
|
|
|
1046
1133
|
export async function documentProcessor({
|
|
1047
1134
|
file,
|
|
1048
1135
|
name,
|
|
1049
|
-
config
|
|
1136
|
+
config,
|
|
1137
|
+
tolerateVisionFailures,
|
|
1138
|
+
onProgress,
|
|
1139
|
+
limiters,
|
|
1050
1140
|
}: {
|
|
1051
1141
|
file: string | Buffer;
|
|
1052
1142
|
name: string;
|
|
1053
1143
|
config?: DocumentProcessorConfig;
|
|
1144
|
+
/** A page whose vision pass failed keeps its OCR text and is flagged `vlm_failed` instead of failing the document. */
|
|
1145
|
+
tolerateVisionFailures?: boolean;
|
|
1146
|
+
/** Reports OCR progress per finished chunk and vision progress per finished page. */
|
|
1147
|
+
onProgress?: ProgressFn;
|
|
1148
|
+
/**
|
|
1149
|
+
* Process-wide ceilings on OCR and vision calls. Passed by the chat paths only (extractDocument);
|
|
1150
|
+
* absent for knowledge-base processing, which keeps its per-document limits unchanged.
|
|
1151
|
+
*/
|
|
1152
|
+
limiters?: ProviderLimiters;
|
|
1054
1153
|
}): Promise<ProcessedDocument | undefined> {
|
|
1055
1154
|
|
|
1056
1155
|
const license = checkLicense()
|
|
@@ -1106,7 +1205,10 @@ export async function documentProcessor({
|
|
|
1106
1205
|
buffer,
|
|
1107
1206
|
tempDir,
|
|
1108
1207
|
config,
|
|
1109
|
-
true
|
|
1208
|
+
true,
|
|
1209
|
+
tolerateVisionFailures,
|
|
1210
|
+
onProgress,
|
|
1211
|
+
limiters,
|
|
1110
1212
|
);
|
|
1111
1213
|
|
|
1112
1214
|
return content.json;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ocrConcurrency, ocrLimiter, visionLimiter, PROCESS_WIDE_LIMIT } from "./limits";
|
|
2
|
+
|
|
3
|
+
describe("ocrConcurrency", () => {
|
|
4
|
+
it("defaults to 3", () => {
|
|
5
|
+
expect(ocrConcurrency(undefined)).toBe(3);
|
|
6
|
+
expect(ocrConcurrency({})).toBe(3);
|
|
7
|
+
expect(ocrConcurrency({ ocr: {} })).toBe(3);
|
|
8
|
+
});
|
|
9
|
+
it("reads documentProcessor.ocr.concurrency and clamps to 1..8", () => {
|
|
10
|
+
expect(ocrConcurrency({ ocr: { concurrency: 5 } })).toBe(5);
|
|
11
|
+
expect(ocrConcurrency({ ocr: { concurrency: 0 } })).toBe(1);
|
|
12
|
+
expect(ocrConcurrency({ ocr: { concurrency: 99 } })).toBe(8);
|
|
13
|
+
expect(ocrConcurrency({ ocr: { concurrency: 2.7 } })).toBe(3);
|
|
14
|
+
expect(ocrConcurrency({ ocr: { concurrency: Number.NaN } })).toBe(3);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe("process-wide limiters", () => {
|
|
19
|
+
it.each([["ocr", ocrLimiter], ["vision", visionLimiter]] as const)("%s limiter queues beyond 8 slots instead of refusing", async (_n, limiter) => {
|
|
20
|
+
expect(PROCESS_WIDE_LIMIT).toBe(8);
|
|
21
|
+
let running = 0;
|
|
22
|
+
let max = 0;
|
|
23
|
+
await Promise.all(
|
|
24
|
+
Array.from({ length: 30 }, () =>
|
|
25
|
+
limiter(async () => {
|
|
26
|
+
running++;
|
|
27
|
+
max = Math.max(max, running);
|
|
28
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
29
|
+
running--;
|
|
30
|
+
}),
|
|
31
|
+
),
|
|
32
|
+
);
|
|
33
|
+
expect(max).toBe(8);
|
|
34
|
+
});
|
|
35
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import pLimit from "p-limit";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Process-wide ceilings on provider calls made by the document processor.
|
|
5
|
+
* They apply ONLY to extractions that opt in by passing `processWideLimiters`
|
|
6
|
+
* to `documentProcessor` (the chat paths via extractDocument: parse_document and
|
|
7
|
+
* inline attachments), so two long documents read in chat at once cannot
|
|
8
|
+
* multiply the load on the OCR / vision endpoints. Knowledge-base processing
|
|
9
|
+
* calls the processor directly without them and keeps its own per-document
|
|
10
|
+
* limits (ocr.concurrency, vlm.concurrency) unchanged. Calls beyond the
|
|
11
|
+
* ceiling queue; they are never refused. Per-document limiters (ocrConcurrency, the
|
|
12
|
+
* VLM concurrency setting) sit OUTSIDE these and wrap a function that awaits
|
|
13
|
+
* them, which cannot deadlock: a queued call holds only its per-document slot.
|
|
14
|
+
*
|
|
15
|
+
* Kept free of imports beyond p-limit so it loads on an unlicensed boot.
|
|
16
|
+
*/
|
|
17
|
+
export const PROCESS_WIDE_LIMIT = 8;
|
|
18
|
+
export const DEFAULT_OCR_CONCURRENCY = 3;
|
|
19
|
+
|
|
20
|
+
export const ocrLimiter = pLimit(PROCESS_WIDE_LIMIT);
|
|
21
|
+
export const visionLimiter = pLimit(PROCESS_WIDE_LIMIT);
|
|
22
|
+
|
|
23
|
+
/** Runs `fn` under a ceiling. */
|
|
24
|
+
export type ProviderLimiter = <T>(fn: () => Promise<T>) => Promise<T>;
|
|
25
|
+
/**
|
|
26
|
+
* What the chat paths pass to documentProcessor. The call time limits travel with the limiters:
|
|
27
|
+
* a stalled provider must not pin chat slots, while knowledge-base processing (which passes
|
|
28
|
+
* none) keeps the transport's own, longer limit exactly as before.
|
|
29
|
+
*/
|
|
30
|
+
export type ProviderLimiters = {
|
|
31
|
+
ocr: ProviderLimiter;
|
|
32
|
+
vision: ProviderLimiter;
|
|
33
|
+
/** Longest one OCR request may take; a timeout counts as a failed attempt for the retry logic. */
|
|
34
|
+
ocrTimeoutMs?: number;
|
|
35
|
+
/** Longest one vision (page validation) call may take; same retry treatment. */
|
|
36
|
+
visionTimeoutMs?: number;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export const OCR_CALL_TIMEOUT_MS = 180_000;
|
|
40
|
+
export const VISION_CALL_TIMEOUT_MS = 120_000;
|
|
41
|
+
|
|
42
|
+
export const processWideLimiters: ProviderLimiters = {
|
|
43
|
+
ocr: ocrLimiter,
|
|
44
|
+
vision: visionLimiter,
|
|
45
|
+
ocrTimeoutMs: OCR_CALL_TIMEOUT_MS,
|
|
46
|
+
visionTimeoutMs: VISION_CALL_TIMEOUT_MS,
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** Per-document OCR concurrency from `documentProcessor.ocr.concurrency`: default 3, clamped to 1..8. */
|
|
50
|
+
export function ocrConcurrency(config?: { ocr?: { concurrency?: number } }): number {
|
|
51
|
+
const raw = config?.ocr?.concurrency;
|
|
52
|
+
if (typeof raw !== "number" || !Number.isFinite(raw)) return DEFAULT_OCR_CONCURRENCY;
|
|
53
|
+
return Math.min(PROCESS_WIDE_LIMIT, Math.max(1, Math.round(raw)));
|
|
54
|
+
}
|
package/ee/workers.ts
CHANGED
|
@@ -41,7 +41,7 @@ import { exuluApp } from "@SRC/exulu/app/singleton";
|
|
|
41
41
|
import { handleEmailIntake } from "@SRC/exulu/email-inbound/intake";
|
|
42
42
|
import { markStreamActive, clearStreamActive } from "@SRC/exulu/active-streams.ts";
|
|
43
43
|
import { messageHasPendingApproval, substituteVariablesInMessage } from "@SRC/exulu/routines/flow-steps.ts";
|
|
44
|
-
import {
|
|
44
|
+
import { withRunSession } from "@SRC/exulu/routines/run-session.ts";
|
|
45
45
|
import { casJobResultState, parseRunMetadata, upsertWorkflowRunStart } from "@SRC/exulu/routines/run-state.ts";
|
|
46
46
|
import { findLiteLLMModel } from "@SRC/exulu/litellm/catalog.ts";
|
|
47
47
|
import { computeRunCostUsd } from "@SRC/exulu/routines/run-cost.ts";
|
|
@@ -559,105 +559,106 @@ export const createWorkers = async (
|
|
|
559
559
|
|
|
560
560
|
// Session-backed runs (spec §3.4): reuse the session provided by
|
|
561
561
|
// the enqueuer (email intake / continuation / retry / previous
|
|
562
|
-
// BullMQ attempt)
|
|
563
|
-
//
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
562
|
+
// BullMQ attempt) once it is verified to be this routine's run
|
|
563
|
+
// session, otherwise create one with the routine's rbac snapshot
|
|
564
|
+
// under the run identity. A foreign session fails the run before
|
|
565
|
+
// the flow below is ever invoked (withRunSession).
|
|
566
|
+
const result = await withRunSession(
|
|
567
|
+
db,
|
|
568
|
+
{
|
|
569
|
+
existingSession: started.session,
|
|
570
|
+
jobResultId,
|
|
568
571
|
workflow: {
|
|
569
572
|
id: workflow.id,
|
|
570
573
|
name: workflow.name,
|
|
571
574
|
agent: workflow.agent,
|
|
572
575
|
rights_mode: workflow.rights_mode,
|
|
573
576
|
},
|
|
574
|
-
|
|
575
|
-
title: `${workflow.name} — ${new Date().toISOString()}`,
|
|
577
|
+
runUser: user,
|
|
576
578
|
trigger: data.triggerSource ?? "api",
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
const retries = 3;
|
|
583
|
-
let attempts = 0;
|
|
579
|
+
},
|
|
580
|
+
async (sessionId) => {
|
|
581
|
+
const retries = 3;
|
|
582
|
+
let attempts = 0;
|
|
584
583
|
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
try {
|
|
601
|
-
// processUiMessagesFlow mutates inputMessages in place (ids
|
|
602
|
-
// + substituted text) — pass a fresh deep copy each attempt
|
|
603
|
-
// so a retry/resume never reuses the mutated array.
|
|
604
|
-
const messages = await processUiMessagesFlow({
|
|
605
|
-
agent,
|
|
606
|
-
inputMessages: structuredClone(inputMessages),
|
|
607
|
-
contexts,
|
|
608
|
-
user,
|
|
609
|
-
tools,
|
|
610
|
-
config,
|
|
611
|
-
variables: data.inputs,
|
|
612
|
-
// Tag LLM spend to this routine (cron + ad-hoc share this path).
|
|
613
|
-
routine: { id: workflow.id, name: workflow.name },
|
|
614
|
-
jobResultId,
|
|
615
|
-
sessionId,
|
|
616
|
-
resumeFromIndex,
|
|
617
|
-
// Approval-gated tools pause unless the routine opted
|
|
618
|
-
// back into blanket pre-approval (spec §5.2).
|
|
619
|
-
respectToolApprovals: workflow.auto_approve_tools !== true,
|
|
620
|
-
});
|
|
621
|
-
resolve(messages);
|
|
622
|
-
break;
|
|
623
|
-
} catch (error: unknown) {
|
|
624
|
-
console.error(
|
|
625
|
-
`[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
|
|
626
|
-
error instanceof Error ? error.message : String(error),
|
|
627
|
-
);
|
|
628
|
-
if (error instanceof FlowStepError) {
|
|
629
|
-
// Completed steps already persisted their messages —
|
|
630
|
-
// resume at the failed step (spec §5.4).
|
|
631
|
-
resumeFromIndex = error.stepIndex;
|
|
632
|
-
}
|
|
633
|
-
attempts++;
|
|
634
|
-
if (attempts >= retries) {
|
|
635
|
-
// Persist progress so BullMQ attempt-level retries and
|
|
636
|
-
// retryRoutineRun resume from the failed step.
|
|
584
|
+
const promise = new Promise<{
|
|
585
|
+
messages: UIMessage[];
|
|
586
|
+
metadata: {
|
|
587
|
+
tokens: {
|
|
588
|
+
totalTokens: number;
|
|
589
|
+
reasoningTokens: number;
|
|
590
|
+
inputTokens: number;
|
|
591
|
+
outputTokens: number;
|
|
592
|
+
cachedInputTokens: number;
|
|
593
|
+
};
|
|
594
|
+
duration: number;
|
|
595
|
+
};
|
|
596
|
+
pausedAtStepIndex?: number;
|
|
597
|
+
}>(async (resolve, reject) => {
|
|
598
|
+
while (attempts < retries) {
|
|
637
599
|
try {
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
600
|
+
// processUiMessagesFlow mutates inputMessages in place (ids
|
|
601
|
+
// + substituted text) — pass a fresh deep copy each attempt
|
|
602
|
+
// so a retry/resume never reuses the mutated array.
|
|
603
|
+
const messages = await processUiMessagesFlow({
|
|
604
|
+
agent,
|
|
605
|
+
inputMessages: structuredClone(inputMessages),
|
|
606
|
+
contexts,
|
|
607
|
+
user,
|
|
608
|
+
tools,
|
|
609
|
+
config,
|
|
610
|
+
variables: data.inputs,
|
|
611
|
+
// Tag LLM spend to this routine (cron + ad-hoc share this path).
|
|
612
|
+
routine: { id: workflow.id, name: workflow.name },
|
|
613
|
+
jobResultId,
|
|
614
|
+
sessionId,
|
|
615
|
+
resumeFromIndex,
|
|
616
|
+
// Approval-gated tools pause unless the routine opted
|
|
617
|
+
// back into blanket pre-approval (spec §5.2).
|
|
618
|
+
respectToolApprovals: workflow.auto_approve_tools !== true,
|
|
619
|
+
});
|
|
620
|
+
resolve(messages);
|
|
621
|
+
break;
|
|
622
|
+
} catch (error: unknown) {
|
|
648
623
|
console.error(
|
|
649
|
-
`[EXULU]
|
|
650
|
-
|
|
624
|
+
`[EXULU] error processing UI messages flow for agent ${agent.name} (${agent.id}).`,
|
|
625
|
+
error instanceof Error ? error.message : String(error),
|
|
651
626
|
);
|
|
627
|
+
if (error instanceof FlowStepError) {
|
|
628
|
+
// Completed steps already persisted their messages —
|
|
629
|
+
// resume at the failed step (spec §5.4).
|
|
630
|
+
resumeFromIndex = error.stepIndex;
|
|
631
|
+
}
|
|
632
|
+
attempts++;
|
|
633
|
+
if (attempts >= retries) {
|
|
634
|
+
// Persist progress so BullMQ attempt-level retries and
|
|
635
|
+
// retryRoutineRun resume from the failed step.
|
|
636
|
+
try {
|
|
637
|
+
await db
|
|
638
|
+
.from("job_results")
|
|
639
|
+
.where({ id: jobResultId })
|
|
640
|
+
.update({
|
|
641
|
+
metadata: JSON.stringify({
|
|
642
|
+
...runBookkeeping,
|
|
643
|
+
current_step_index: resumeFromIndex,
|
|
644
|
+
}),
|
|
645
|
+
});
|
|
646
|
+
} catch (persistError) {
|
|
647
|
+
console.error(
|
|
648
|
+
`[EXULU] failed to persist run progress for job ${bullmqJob.id}.`,
|
|
649
|
+
persistError,
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
reject(new Error(error instanceof Error ? error.message : String(error)));
|
|
653
|
+
}
|
|
654
|
+
await new Promise((resolve) => setTimeout(() => resolve(true), 2000));
|
|
652
655
|
}
|
|
653
|
-
reject(new Error(error instanceof Error ? error.message : String(error)));
|
|
654
656
|
}
|
|
655
|
-
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
});
|
|
657
|
+
});
|
|
659
658
|
|
|
660
|
-
|
|
659
|
+
return await promise;
|
|
660
|
+
},
|
|
661
|
+
);
|
|
661
662
|
const messages = result.messages;
|
|
662
663
|
const metadata = result.metadata;
|
|
663
664
|
|
package/package.json
CHANGED