diff --git a/.changeset/39008-core-document-text.md b/.changeset/39008-core-document-text.md new file mode 100644 index 00000000000..9ca69183510 --- /dev/null +++ b/.changeset/39008-core-document-text.md @@ -0,0 +1,28 @@ +--- +'@objectstack/core': patch +'@objectstack/mcp': patch +--- + +feat(core): the bounded document text extractor is exported as `@objectstack/core/document-text` + +Clause-②: yes (widening) +Metadata-protocol: none + +The extractor MCP `read_file` reads PDF, Word, text and image files with now lives in `@objectstack/core` and is exported from a Node-only subpath, so a service that depends on the kernel package (an AI service handing a model a document's text instead of the document) uses it without depending on `@objectstack/mcp`: + +```ts +import { extractFileContent, ReadFileExtractionBusyError } from '@objectstack/core/document-text'; + +const content = await extractFileContent(bytes, mimeType, fileName); +// { kind: 'text', text, truncated, format, note? } | { kind: 'image', data, mimeType } | { kind: 'none', reason } +``` + +It keeps every bound `read_file`'s extraction had (how many bytes to read at all stays the caller's cap: `read_file` keeps its 10 MiB `READ_FILE_MAX_BYTES`, and a text or image file is decoded on the calling thread at whatever size it is handed): + +- at most 100,000 characters of text (`READ_FILE_TEXT_MAX_CHARS`), 200 PDF pages, a 32 MiB inflated Word body and a 5 MiB image; +- a CPU-time budget per PDF or Word extraction (`OS_MCP_READ_FILE_CPU_BUDGET_MS`, default 2000 ms), checked between pages and paragraphs, with a wall-clock ceiling of five budgets on a worker; +- a `worker_threads` pool and a process-wide cap on extractions in flight (`OS_MCP_READ_FILE_MAX_CONCURRENT`, default 4); one more is refused at once with `ReadFileExtractionBusyError` (`SERVICE_UNAVAILABLE`, 503, `retryAfterSeconds`), never queued. + +Every caller in one process shares the bounds, the pool and the count, so the cap holds whoever asks, and through whichever copy of the package: an ESM `import` and a CJS `require` of the subpath (or two installed versions) share one state under a registered symbol, and `instanceof ReadFileExtractionBusyError` recognises a refusal from any copy. A host that bundles `@objectstack/core` into one file ships `dist/document-text-worker.js` (or `.cjs`) beside its bundle, or points the pool at wherever it put that file with `configureExtractionWorkerEntry` (the file is addressed by path; no `exports` entry names it). Without a worker, that copy extracts on the request thread under the same two bounds, said once at `warn`; another copy in the same process that finds its worker keeps reading on workers, and an idle worker serves any copy. + +The subpath is kept off the main entry, so a host that never reads a document never loads `unpdf`, which is now a dependency of `@objectstack/core` instead of `@objectstack/mcp`. `read_file` reads through the shared extractor and answers as before; the two host variables keep their names and defaults. One fix on the way: the pool now copies the bytes it hands a worker into a fresh `Uint8Array` instead of slicing them, so a Node `Buffer` (whose `slice` is a view over shared memory) reads on a worker instead of failing to transfer, which `read_file` answered with its could-not-read sentence, and the caller's `Buffer` is left intact. One operator-visible change: the one-time `warn` when no worker can start now reads `[document-text] PDF and Word text (read_file and every other caller) is extracted on the request thread, not on a worker: …` (was `[MCP] read_file extracts PDF and Word text on the request thread, not on a worker: …`), since it now speaks for every caller; a log alert matching the old text needs the new one. diff --git a/content/docs/ai/connect-mcp.mdx b/content/docs/ai/connect-mcp.mdx index 100a5fe8e92..0900ebfa151 100644 --- a/content/docs/ai/connect-mcp.mdx +++ b/content/docs/ai/connect-mcp.mdx @@ -486,6 +486,14 @@ The defaults keep a self-hosted deployment reading files as before: a 9 MiB, inside the budget. Both are read once when the server starts; a value that is not a positive whole number stops the start with a message naming the variable. +The extractor behind `read_file` is the platform's shared one, +`@objectstack/core/document-text`, so an AI service in the same process reads +documents under the same two bounds: the cap counts every extraction in flight, +whoever asked for it. If no worker can start (a host that bundled the server +into one file), files are read on the request thread under the same two bounds, +said once in the log as `[document-text] PDF and Word text … is extracted on the +request thread, not on a worker`. + The tools are a fixed ~10-tool **spine** with the object name as a *parameter* (`query_records(objectName, …)`), not one tool per object — so the list stays usable on an app with hundreds of objects. Which objects and actions that spine diff --git a/docs/qa/platform-checklist/areas/ai.json b/docs/qa/platform-checklist/areas/ai.json index c02ddbbb18d..7b78a32c0bb 100644 --- a/docs/qa/platform-checklist/areas/ai.json +++ b/docs/qa/platform-checklist/areas/ai.json @@ -1263,7 +1263,7 @@ "title": "read_file answers the text of a PDF and a Word document with its facts, stops a long extraction at the CPU-time budget with a note, refuses past the concurrent-reading cap with a retryable 503, and a malformed budget variable fails the boot naming it", "since": "v18.4", "status": "active", - "revision": 3, + "revision": 4, "priority": "P1", "surface": "api", "personas": [ @@ -1295,7 +1295,7 @@ { "clause": "a Word document answers its paragraphs as text", "oracle": "network", - "verify": "facts carry content 'text' and the .docx mime type as format; the text block holds the document's paragraphs (packages/mcp/src/file-content.ts#extractFileContent)", + "verify": "facts carry content 'text' and the .docx mime type as format; the text block holds the document's paragraphs (packages/core/src/document-text-extract.ts#extractFileContent)", "evidence": "both content blocks" }, { @@ -1307,13 +1307,13 @@ { "clause": "an extraction over the CPU-time budget answers the text read so far, truncated, with the budget note", "oracle": "network", - "verify": "facts carry content 'text', truncated true and a note opening 'Reading stopped at the CPU-time budget for one file (60 ms) after page', the budget the boot carries (packages/mcp/src/file-content.ts#pdfAnswer, #stoppedExtractionAnswer, #READ_FILE_CPU_BUDGET_MS_ENV). A budget spent before the first page's text answers the zero-page shape instead: content 'none', no truncated, and the budget sentence as the note (pdfAnswer's empty arm hands the budget note over as its reason). That shape is a fixture budget too low for the host, not this clause's verdict: record it and read again at a higher budget. Whether a stopped read must always carry truncated true is open for the maintainer (#32945); until it is ruled, the zero-page shape is no FAIL", + "verify": "facts carry content 'text', truncated true and a note opening 'Reading stopped at the CPU-time budget for one file (60 ms) after page', the budget the boot carries (packages/core/src/document-text-extract.ts#pdfAnswer, #stoppedExtractionAnswer, #READ_FILE_CPU_BUDGET_MS_ENV). A budget spent before the first page's text answers the zero-page shape instead: content 'none', no truncated, and the budget sentence as the note (pdfAnswer's empty arm hands the budget note over as its reason). That shape is a fixture budget too low for the host, not this clause's verdict: record it and read again at a higher budget. Whether a stopped read must always carry truncated true is open for the maintainer (#32945); until it is ruled, the zero-page shape is no FAIL", "evidence": "the facts block" }, { "clause": "a malformed budget variable fails the boot naming the variable", "oracle": "log", - "verify": "the boot fails with 'OS_MCP_READ_FILE_CPU_BUDGET_MS must be a positive integer; got \"abc\"' (packages/mcp/src/file-content.ts#configureReadFileExtraction, called from the MCP plugin's init)", + "verify": "the boot fails with 'OS_MCP_READ_FILE_CPU_BUDGET_MS must be a positive integer; got \"abc\"' (packages/core/src/document-text-extract.ts#configureReadFileExtraction, called from the MCP plugin's init)", "evidence": "the exit code and the log line" }, { @@ -1336,10 +1336,10 @@ }, "source": [ "packages/mcp/src/file-content.ts#renderReadFile", - "packages/mcp/src/file-content.ts#extractFileContent", - "packages/mcp/src/file-content.ts#stoppedExtractionAnswer", - "packages/mcp/src/file-content.ts#configureReadFileExtraction", - "packages/mcp/src/file-content.ts#ReadFileExtractionBusyError", + "packages/core/src/document-text-extract.ts#extractFileContent", + "packages/core/src/document-text-extract.ts#stoppedExtractionAnswer", + "packages/core/src/document-text-extract.ts#configureReadFileExtraction", + "packages/core/src/document-text-extract.ts#ReadFileExtractionBusyError", "packages/mcp/src/mcp-http-tools.ts#registerFileTools" ], "history": [ @@ -1352,7 +1352,7 @@ { "revision": 2, "date": "2026-11-13", - "change": "assertion-defect correction of acceptance[3] (with fixtures.requires[2] and [3], steps[0] and steps[2]). At OS_MCP_READ_FILE_CPU_BUDGET_MS=1 the budget is spent before the first page, so pdfAnswer's empty arm answers content 'none' with the budget note and no truncated (packages/mcp/src/file-content.ts#pdfAnswer); at 60 the clause's shape appears. The fixture budget is raised to 60, the clause names the zero-page shape as a fixture signal to re-read at a higher budget, and leaves open whether a stopped read must always carry truncated true (if ruled so, that is a product defect in pdfAnswer's empty arm, not this item's). The receipt field is on showcase_invoice_line, not showcase_invoice (examples/app-showcase/src/data/objects/invoice.object.ts), so the fixture and steps name the invoice line. Found by the 18.4.0 acceptance run #32940 (F-4 to F-8 and its R4/R5 comments; wave anchor #32908). Re-read at main cf1b55c0. Card #32945", + "change": "assertion-defect correction of acceptance[3] (with fixtures.requires[2] and [3], steps[0] and steps[2]). At OS_MCP_READ_FILE_CPU_BUDGET_MS=1 the budget is spent before the first page, so pdfAnswer's empty arm answers content 'none' with the budget note and no truncated (packages/core/src/document-text-extract.ts#pdfAnswer, where the extractor moved in revision 4); at 60 the clause's shape appears. The fixture budget is raised to 60, the clause names the zero-page shape as a fixture signal to re-read at a higher budget, and leaves open whether a stopped read must always carry truncated true (if ruled so, that is a product defect in pdfAnswer's empty arm, not this item's). The receipt field is on showcase_invoice_line, not showcase_invoice (examples/app-showcase/src/data/objects/invoice.object.ts), so the fixture and steps name the invoice line. Found by the 18.4.0 acceptance run #32940 (F-4 to F-8 and its R4/R5 comments; wave anchor #32908). Re-read at main cf1b55c0. Card #32945", "ref": "#32945" }, { @@ -1360,6 +1360,12 @@ "date": "2026-11-15", "change": "acceptance[5].verify names `--reporter=tree`, the reporter that prints the one line per pin file this is scored on: in a runner's non-TTY shell vitest's default reporter prints the run's totals only (RUNNER.md's environment facts; QA run #33784's note 10, comment 6893243542). No clause or threshold changed. Card #33969", "ref": "#34068" + }, + { + "revision": 4, + "date": "2026-12-02", + "change": "anchor repoint, no clause, step, fixture or threshold changed: the extractor read_file reads through (its caps, the CPU budget, the worker pool, the cap on reads in flight and the busy refusal) moved from packages/mcp/src/file-content.ts to the shared packages/core/src/document-text-extract.ts (published through the curated entry packages/core/src/document-text.ts, export @objectstack/core/document-text), so acceptance[1], [3] and [4], source and revision 2's citation name it there; renderReadFile and READ_FILE_MAX_BYTES stay in the MCP file. The worker-pool pins moved beside the pool (packages/core/src/document-text.worker-pool.test.ts); the pins acceptance[5] scores stay in automated.ref. Card #39008", + "ref": "#39008" } ] }, diff --git a/packages/core/package.json b/packages/core/package.json index 7208c1dcf2a..58ddfa5bec6 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -37,6 +37,16 @@ "types": "./dist/logger.d.cts", "default": "./dist/logger.cjs" } + }, + "./document-text": { + "import": { + "types": "./dist/document-text.d.ts", + "default": "./dist/document-text.js" + }, + "require": { + "types": "./dist/document-text.d.cts", + "default": "./dist/document-text.cjs" + } } }, "scripts": { @@ -60,6 +70,7 @@ "@objectstack/spec": "workspace:*", "@objectstack/types": "workspace:*", "undici": "^7.30.1", + "unpdf": "1.9.1", "zod": "^4.6.6" }, "keywords": [ diff --git a/packages/core/src/document-text-extract.ts b/packages/core/src/document-text-extract.ts new file mode 100644 index 00000000000..50b9303116a --- /dev/null +++ b/packages/core/src/document-text-extract.ts @@ -0,0 +1,732 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { inflateRawSync } from 'node:zlib'; + +import { runExtractionInWorker } from './document-text-pool.js'; +import { BUSY_ERROR_BRAND, documentTextState } from './document-text-state.js'; + +/** + * The implementation behind `@objectstack/core/document-text` (`document-text.ts`, + * which re-exports the public part and documents it). Internal: the worker + * entry and the pool import from here; nothing outside this package does. + */ + +/** The most characters of extracted text one answer carries. */ +export const READ_FILE_TEXT_MAX_CHARS = 100_000; + +/** The most PDF pages read. */ +export const READ_FILE_PDF_MAX_PAGES = 200; + +/** The most bytes a `.docx` body (`word/document.xml`) may inflate to: 32 MiB. */ +export const READ_FILE_DOCX_XML_MAX_BYTES = 32 * 1024 * 1024; + +/** + * The largest image returned as an image block: 5 MiB, the most an MCP client + * passes to a model as one image. A larger image answers its link. + */ +export const READ_FILE_IMAGE_MAX_BYTES = 5 * 1024 * 1024; + +/** The host variable naming the CPU-time budget of one PDF or Word extraction, in milliseconds. */ +export const READ_FILE_CPU_BUDGET_MS_ENV = 'OS_MCP_READ_FILE_CPU_BUDGET_MS'; + +/** The host variable naming how many PDF or Word extractions may run at once in the process. */ +export const READ_FILE_MAX_CONCURRENT_ENV = 'OS_MCP_READ_FILE_MAX_CONCURRENT'; + +/** + * 2000 ms of CPU per extraction. Well above what any file within the other + * caps was measured to take (a 9 MiB, 200-page PDF dense in drawing operators: + * about 300–650 ms), so a self-hosted deployment reads every such file in full + * as before; it stops only a file built to take seconds. + */ +export const READ_FILE_CPU_BUDGET_MS_DEFAULT = 2000; + +/** + * 4 extractions in flight. More than one person's assistant reads at once on a + * self-hosted deployment, and few enough that a burst holds the process for at + * most four budgets. + */ +export const READ_FILE_MAX_CONCURRENT_DEFAULT = 4; + +/** + * A worker's wall-clock ceiling per extraction, as a multiple of the CPU + * budget: 5, so 10 s under the default budget. A worker checks its CPU budget + * between pages, so the ceiling only catches one that does not reach a + * checkpoint (a single page that runs long). Five is the share of one core a + * worker still gets when every slot of the default pool (4) and the request + * thread run on a single core: under that load a worker that is still + * reaching its checkpoints has used its budget before the ceiling, so the + * ceiling never cuts a read the budget would have let finish. + */ +export const READ_FILE_WALL_CEILING_MULTIPLE = 5; + +/** The two host bounds on PDF and Word extraction. */ +export interface ReadFileExtractionLimits { + /** CPU time one extraction may use, in milliseconds, checked between pages or paragraphs. */ + cpuBudgetMs: number; + /** Extractions that may run at once in the process, and the size of the worker pool; one more is refused. */ + maxConcurrent: number; +} + +function readPositiveIntegerVar(env: Record, name: string, fallback: number): number { + const raw = env[name]; + if (raw == null || raw.trim() === '') return fallback; + const text = raw.trim(); + const n = Number(text); + // A typo here must not be the thing that switches the bound off: an + // unreadable value fails loudly instead of reading as unset. + if (!/^\d+$/.test(text) || !Number.isSafeInteger(n) || n <= 0) { + throw new Error( + `${name} must be a positive integer; got ${JSON.stringify(raw)}. ` + + `Unset it for the default (${fallback}), or set a whole number.`, + ); + } + return n; +} + +/** + * The host's bounds on PDF and Word extraction, from `env` (default + * `process.env`). An unset variable takes its default; a value that is not a + * positive integer throws, naming the variable. + */ +export function resolveReadFileExtractionLimits( + env: Record = typeof process !== 'undefined' ? process.env : {}, +): ReadFileExtractionLimits { + return { + cpuBudgetMs: readPositiveIntegerVar(env, READ_FILE_CPU_BUDGET_MS_ENV, READ_FILE_CPU_BUDGET_MS_DEFAULT), + maxConcurrent: readPositiveIntegerVar(env, READ_FILE_MAX_CONCURRENT_ENV, READ_FILE_MAX_CONCURRENT_DEFAULT), + }; +} + +/** + * Fix the bounds every extraction in this process runs under: `limits`, or + * the host's ({@link resolveReadFileExtractionLimits}). The plugin's `init` + * calls it once, so a malformed variable fails the boot; a process that never + * calls it reads the host's on its first extraction. + */ +export function configureReadFileExtraction(limits?: ReadFileExtractionLimits): ReadFileExtractionLimits { + documentTextState.limits = limits ?? resolveReadFileExtractionLimits(); + return documentTextState.limits; +} + +/** + * The bounds extractions run under now: the ones {@link configureReadFileExtraction} + * fixed, else the host's, read and fixed on this first call. Throws, naming + * the variable, when a host variable is malformed: a caller that must fail on + * that before it starts a read (as `read_file` does) calls this first. + */ +export function activeReadFileExtractionLimits(): ReadFileExtractionLimits { + documentTextState.limits ??= resolveReadFileExtractionLimits(); + return documentTextState.limits; +} + +/** + * The refusal of an extraction over the process-wide cap: ADR-0112 + * `SERVICE_UNAVAILABLE` (503), retryable. The process is busy reading other + * files, which says nothing about this caller or this file, so the answer is + * "try again shortly", with the seconds to wait. + */ +export class ReadFileExtractionBusyError extends Error { + /** + * Any copy of this class answers `instanceof` for a refusal from any other + * copy (an ESM and a CJS load of this package in one process, or two + * installed versions): they share one cap ({@link documentTextState}), so a + * caller must recognise the refusal whichever copy raised it. + */ + static [Symbol.hasInstance](value: unknown): value is ReadFileExtractionBusyError { + return typeof value === 'object' && value !== null && (value as Record)[BUSY_ERROR_BRAND] === true; + } + + readonly code = 'SERVICE_UNAVAILABLE' as const; + readonly status = 503; + constructor( + readonly maxConcurrent: number, + /** Seconds to wait before retrying: about one extraction's budget. */ + readonly retryAfterSeconds: number, + ) { + super( + `The server is already reading ${maxConcurrent} files, the most it reads at once, so this file was not read. ` + + `Try again in about ${retryAfterSeconds} second${retryAfterSeconds === 1 ? '' : 's'}.`, + ); + this.name = 'ReadFileExtractionBusyError'; + Object.defineProperty(this, BUSY_ERROR_BRAND, { value: true }); + } +} + +/** CPU time spent since a start reading, against one extraction's budget. */ +export interface CpuBudget { + readonly budgetMs: number; + /** True once the extraction has used its budget. */ + spent(): boolean; +} + +/** The in-process budget: process CPU time, which stops early, never late. */ +function startCpuBudget(budgetMs: number): CpuBudget { + const start = process.cpuUsage(); + return { + budgetMs, + spent() { + const used = process.cpuUsage(start); + return (used.user + used.system) / 1000 >= budgetMs; + }, + }; +} + +/** + * Where reading stopped at the CPU budget: `after` the pages or paragraphs + * read ("page 3 of 120", "64 paragraphs"), or `before` the first one ("page 1 + * of 120", "the first paragraph") when the stop came before any was read. + */ +type BudgetStop = { budgetMs: number; after: string } | { budgetMs: number; before: string }; + +/** + * The sentence an answer cut by the CPU budget carries. It calls the text + * partial only when some text came back (`gotText`): a stop before the first + * page or paragraph says it stopped before any was read, and a stop after + * parts that held no text says none was found, so an answer with no text + * never claims to hold part of it. + */ +function cpuBudgetNote(stop: BudgetStop, gotText: boolean): string { + const stopped = `Reading stopped at the CPU-time budget for one file (${stop.budgetMs} ms)`; + if ('before' in stop) { + return `${stopped} before ${stop.before} was read, so no text came back. Download the file with the link instead.`; + } + return gotText + ? `${stopped} after ${stop.after}, so the text is partial. Download the file with the link for the rest.` + : `${stopped} after ${stop.after}, and no text was found in what was read. Download the file with the link instead.`; +} + +/** The images an MCP image block carries; any other image answers its link. */ +const INLINE_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']); + +const DOCX_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; + +/** The media types read as text, beside every `text/*`. */ +const TEXT_TYPES = new Set([ + 'application/json', + 'application/ld+json', + 'application/xml', + 'application/x-yaml', + 'application/yaml', + 'application/csv', + 'application/javascript', + 'application/sql', + 'image/svg+xml', +]); + +/** The media type a name's extension stands for, for a file stored with none (or as bytes). */ +const TYPE_BY_EXTENSION: Record = { + pdf: 'application/pdf', + docx: DOCX_TYPE, + txt: 'text/plain', + md: 'text/markdown', + csv: 'text/csv', + tsv: 'text/tab-separated-values', + json: 'application/json', + xml: 'application/xml', + yaml: 'application/yaml', + yml: 'application/yaml', + html: 'text/html', + htm: 'text/html', + svg: 'image/svg+xml', + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + webp: 'image/webp', +}; + + +/** The content a file yields: its text, its image, or a sentence on why there is neither. */ +export type ExtractedContent = + | { + kind: 'text'; + text: string; + truncated: boolean; + format: string; + /** Why the text is cut, when it was cut by something other than the length and page caps. */ + note?: string; + } + | { kind: 'image'; data: string; mimeType: string } + | { kind: 'none'; reason: string }; + +/** The media type to read the file as: the stored one, else the name's extension, lower-cased and without parameters. */ +export function effectiveMimeType(mimeType: string | null, name: string): string { + const stored = (mimeType ?? '').split(';')[0].trim().toLowerCase(); + if (stored && stored !== 'application/octet-stream') return stored; + const ext = name.includes('.') ? name.split('.').pop()!.toLowerCase() : ''; + return TYPE_BY_EXTENSION[ext] ?? (stored || 'application/octet-stream'); +} + +function isTextType(type: string): boolean { + return type.startsWith('text/') || TEXT_TYPES.has(type) || type.endsWith('+json') || type.endsWith('+xml'); +} + +function bounded(text: string): { text: string; truncated: boolean } { + return text.length > READ_FILE_TEXT_MAX_CHARS + ? { text: text.slice(0, READ_FILE_TEXT_MAX_CHARS), truncated: true } + : { text, truncated: false }; +} + +/** + * The content of a file's bytes, by its media type. A file an extractor cannot + * read answers `{ kind: 'none' }` with the sentence. Throws one thing: a PDF or + * Word file met while the process already runs as many extractions as the host + * allows is refused with {@link ReadFileExtractionBusyError}. + */ +export async function extractFileContent(bytes: Uint8Array, mimeType: string | null, name: string): Promise { + const type = effectiveMimeType(mimeType, name); + if (INLINE_IMAGE_TYPES.has(type)) { + if (bytes.byteLength > READ_FILE_IMAGE_MAX_BYTES) { + return { + kind: 'none', + reason: `The image is ${bytes.byteLength} bytes, over the ${READ_FILE_IMAGE_MAX_BYTES}-byte cap for showing an image. Download it with the link instead.`, + }; + } + return { kind: 'image', data: Buffer.from(bytes).toString('base64'), mimeType: type }; + } + if (isTextType(type)) { + return { kind: 'text', format: type, ...bounded(new TextDecoder('utf-8').decode(bytes)) }; + } + if (type === 'application/pdf') return withExtractionSlot('pdf', bytes); + if (type === DOCX_TYPE) return withExtractionSlot('docx', bytes); + return { + kind: 'none', + reason: `A ${type} file has no text read_file can read. Download it with the link instead.`, + }; +} + +/** The two documents read by extraction rather than decoding. */ +export type DocumentKind = 'pdf' | 'docx'; + +/** + * Run one document extraction inside the process-wide cap. Over the cap it is + * refused at once, on this thread, before any worker is touched, never + * queued. Within it, the extraction runs on a pool worker under the CPU + * budget and the wall-clock ceiling; where no worker can start, in-process + * under the CPU budget. The slot is released in `finally`, so an extraction + * that throws (or whose worker crashed) frees it too. + */ +async function withExtractionSlot(kind: DocumentKind, bytes: Uint8Array): Promise { + const limits = activeReadFileExtractionLimits(); + if (documentTextState.inFlight >= limits.maxConcurrent) { + throw new ReadFileExtractionBusyError(limits.maxConcurrent, Math.max(1, Math.ceil(limits.cpuBudgetMs / 1000))); + } + documentTextState.inFlight++; + try { + const outcome = await runExtractionInWorker( + { kind, bytes, cpuBudgetMs: limits.cpuBudgetMs }, + { poolSize: limits.maxConcurrent, ceilingMs: limits.cpuBudgetMs * READ_FILE_WALL_CEILING_MULTIPLE }, + ); + if (outcome.status === 'done') return outcome.result; + if (outcome.status === 'overrun') return stoppedExtractionAnswer(kind, outcome.progress, limits.cpuBudgetMs); + return await extractDocument(kind, bytes, startCpuBudget(limits.cpuBudgetMs)); + } finally { + documentTextState.inFlight--; + } +} + +/** + * What an extraction has read so far, sent as it reads, so a worker stopped + * part-way still answers the text it had already sent back. + */ +export type ExtractionProgress = + /** The PDF opened, with this many pages. */ + | { kind: 'pdf-open'; numPages: number } + /** The next PDF page's text, trimmed, in page order. */ + | { kind: 'pdf-page'; text: string } + /** The Word body's text since the last report, as read, and the paragraphs read in all. */ + | { kind: 'docx-paragraphs'; text: string; paragraphs: number }; + +/** A sink an extractor reports its progress to; in-process there is none. */ +export type ProgressSink = (progress: ExtractionProgress) => void; + +/** One document's text, read under `budget`, reporting progress to `onProgress` as it goes. */ +export async function extractDocument( + kind: DocumentKind, + bytes: Uint8Array, + budget: CpuBudget, + onProgress?: ProgressSink, +): Promise { + return kind === 'pdf' ? extractPdfText(bytes, budget, onProgress) : extractDocxText(bytes, budget, onProgress); +} + +/** + * The answer of an extraction stopped part-way at the wall-clock ceiling: the + * text its progress carried, `truncated: true`, and the CPU-budget note, the + * same shape an extraction stopped at its budget answers. A stop before the + * first page or paragraph came back answers no text, with a note saying the + * read stopped before any was read. + */ +export function stoppedExtractionAnswer(kind: DocumentKind, progress: readonly ExtractionProgress[], budgetMs: number): ExtractedContent { + if (kind === 'pdf') { + let numPages: number | undefined; + const pages: string[] = []; + for (const p of progress) { + if (p.kind === 'pdf-open') numPages = p.numPages; + else if (p.kind === 'pdf-page') pages.push(p.text); + } + const of = numPages === undefined ? '' : ` of ${numPages}`; + const stop: BudgetStop = pages.length === 0 + ? { budgetMs, before: `page 1${of}` } + : { budgetMs, after: `page ${pages.length}${of}` }; + return pdfAnswer(pages, numPages ?? pages.length, stop); + } + let text = ''; + let paragraphs = 0; + for (const p of progress) { + if (p.kind !== 'docx-paragraphs') continue; + text += p.text; + paragraphs = p.paragraphs; + } + const stop: BudgetStop = paragraphs === 0 + ? { budgetMs, before: 'the first paragraph' } + : { budgetMs, after: `${paragraphs} paragraphs` }; + return docxAnswer(text, false, stop); +} + +// ── PDF ────────────────────────────────────────────────────────────────── + +/** The slice of pdf.js's text item a page's text is read from. */ +interface PdfTextItem { + str?: unknown; + hasEOL?: unknown; +} + +/** The slice of pdf.js's document proxy read here. */ +interface PdfDocument { + numPages: number; + getPage(n: number): Promise<{ getTextContent(): Promise<{ items: PdfTextItem[] }>; cleanup?(): unknown }>; + destroy(): Promise; +} + +/** The slice of `unpdf` used, typed here so pdf.js's own types stay out of this package's surface. */ +interface UnpdfModule { + getDocumentProxy(data: Uint8Array, options?: Record): Promise; +} + +let unpdfModule: Promise | undefined; + +/** `unpdf`, imported on the first PDF read, never at load. */ +function loadUnpdf(): Promise { + unpdfModule ??= import('unpdf').then((m) => m as unknown as UnpdfModule); + return unpdfModule; +} + +/** A one-page PDF reading "warm", for {@link preloadPdfReader}. */ +function warmUpPdf(): Uint8Array { + const stream = 'BT /F1 12 Tf 72 720 Td (warm) Tj ET'; + const objects = [ + '<< /Type /Catalog /Pages 2 0 R >>', + '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', + '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>', + `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`, + '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', + ]; + let out = '%PDF-1.4\n'; + const offsets: number[] = []; + objects.forEach((body, i) => { + offsets.push(out.length); + out += `${i + 1} 0 obj\n${body}\nendobj\n`; + }); + const xref = out.length; + out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`; + for (const o of offsets) out += `${String(o).padStart(10, '0')} 00000 n \n`; + out += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; + return new Uint8Array(Buffer.from(out, 'latin1')); +} + +/** + * Make the PDF reader ready now rather than on the first PDF: load `unpdf` + * and read one page of a built-in one-page PDF, which is when pdf.js sets up + * its in-thread worker and loads the rest of itself. A pool worker does this + * before it says it is ready, so that one-time cost (hundreds of milliseconds + * on a busy host) belongs to the worker's start and is never charged to a + * job's wall-clock ceiling. Charged to a job, a small ceiling could stop a + * cold worker's first read every time, and its replacement would start cold + * again. A failure here is left to the first PDF read, which answers its + * could-not-read sentence as before. + */ +export async function preloadPdfReader(): Promise { + try { + const unpdf = await loadUnpdf(); + const doc = await unpdf.getDocumentProxy(warmUpPdf(), pdfOpenOptions()); + try { + const page = await doc.getPage(1); + await page.getTextContent(); + page.cleanup?.(); + } finally { + await doc.destroy(); + } + } catch { + // Left to the first PDF read. + } +} + +/** How every PDF is opened: pdf.js's `eval` path off, its console output off, no font loading. */ +function pdfOpenOptions(): Record { + return { + isEvalSupported: false, + // Errors only: pdf.js warns through `console.log`, which on a stdio + // transport is the protocol stream. + verbosity: 0, + disableFontFace: true, + useSystemFonts: false, + }; +} + +/** + * A PDF's answer from the pages read, in order: their text joined, cut at the + * length cap, `truncated` when fewer than `numPages` were read, and the budget + * note when reading stopped at the budget (which always truncates). + */ +function pdfAnswer(parts: readonly string[], numPages: number, stop: BudgetStop | undefined): ExtractedContent { + const joined = parts.join('\n\n').trim(); + if (!joined) { + return { + kind: 'none', + reason: stop + ? cpuBudgetNote(stop, false) + : 'This PDF has no text layer (it may be a scan), so there is no text to read. Download it with the link instead.', + }; + } + const { text, truncated } = bounded(joined); + return { + kind: 'text', + format: 'application/pdf', + text, + truncated: truncated || parts.length < numPages || stop !== undefined, + ...(stop !== undefined ? { note: cpuBudgetNote(stop, true) } : {}), + }; +} + +async function extractPdfText(bytes: Uint8Array, budget: CpuBudget, onProgress?: ProgressSink): Promise { + let doc: PdfDocument; + try { + const unpdf = await loadUnpdf(); + // pdf.js keeps the buffer it is handed; it gets a copy. + doc = await unpdf.getDocumentProxy(new Uint8Array(bytes), pdfOpenOptions()); + } catch (err) { + const passworded = (err as { name?: unknown })?.name === 'PasswordException'; + return { + kind: 'none', + reason: passworded + ? 'This PDF is password-protected, so its text cannot be read. Download it with the link instead.' + : 'This file could not be read as a PDF: it is damaged or not a PDF. Download it with the link instead.', + }; + } + try { + onProgress?.({ kind: 'pdf-open', numPages: doc.numPages }); + const pages = Math.min(doc.numPages, READ_FILE_PDF_MAX_PAGES); + const parts: string[] = []; + let length = 0; + let read = 0; + let outOfBudget = false; + for (let n = 1; n <= pages && length <= READ_FILE_TEXT_MAX_CHARS; n++) { + // Between pages, never mid-page: the first page is always read. + if (n > 1 && budget.spent()) { + outOfBudget = true; + break; + } + const page = await doc.getPage(n); + const content = await page.getTextContent(); + let pageText = ''; + for (const item of content.items) { + if (typeof item.str !== 'string') continue; + pageText += item.str + (item.hasEOL === true ? '\n' : ''); + } + page.cleanup?.(); + parts.push(pageText.trim()); + onProgress?.({ kind: 'pdf-page', text: parts[parts.length - 1] }); + length += pageText.length + 2; + read = n; + } + const stop = outOfBudget ? { budgetMs: budget.budgetMs, after: `page ${read} of ${doc.numPages}` } : undefined; + return pdfAnswer(parts, doc.numPages, stop); + } catch { + return { + kind: 'none', + reason: 'This PDF could not be read to the end: it is damaged. Download it with the link instead.', + }; + } finally { + try { + await doc.destroy(); + } catch { + // Releasing the document is best-effort; the answer is already decided. + } + } +} + +// ── Word (.docx) ───────────────────────────────────────────────────────── + +const ZIP_END_OF_CENTRAL_DIRECTORY = 0x06054b50; +const ZIP_CENTRAL_DIRECTORY_HEADER = 0x02014b50; +const ZIP_LOCAL_FILE_HEADER = 0x04034b50; +/** The end record is 22 bytes plus a comment of at most 65535. */ +const ZIP_END_SEARCH_SPAN = 22 + 0xffff; +const DOCX_BODY_ENTRY = 'word/document.xml'; + +const NOT_A_DOCX = + 'This file could not be read as a Word document: it is damaged or not a .docx. Download it with the link instead.'; + +/** The stored bytes of one ZIP entry and how they are compressed, or `null` when the archive has no such entry. */ +function zipEntry(buf: Buffer, wanted: string): { method: number; data: Buffer } | null { + const searchFrom = Math.max(0, buf.length - ZIP_END_SEARCH_SPAN); + let end = -1; + for (let i = buf.length - 22; i >= searchFrom; i--) { + if (buf.readUInt32LE(i) === ZIP_END_OF_CENTRAL_DIRECTORY) { + end = i; + break; + } + } + if (end < 0) throw new Error('no end of central directory'); + const entries = buf.readUInt16LE(end + 10); + let at = buf.readUInt32LE(end + 16); + for (let k = 0; k < entries; k++) { + if (at + 46 > buf.length || buf.readUInt32LE(at) !== ZIP_CENTRAL_DIRECTORY_HEADER) throw new Error('bad central directory'); + const method = buf.readUInt16LE(at + 10); + const compressedSize = buf.readUInt32LE(at + 20); + const nameLength = buf.readUInt16LE(at + 28); + const extraLength = buf.readUInt16LE(at + 30); + const commentLength = buf.readUInt16LE(at + 32); + const localOffset = buf.readUInt32LE(at + 42); + const name = buf.toString('utf8', at + 46, at + 46 + nameLength); + if (name === wanted) { + if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== ZIP_LOCAL_FILE_HEADER) { + throw new Error('bad local header'); + } + const start = localOffset + 30 + buf.readUInt16LE(localOffset + 26) + buf.readUInt16LE(localOffset + 28); + if (start + compressedSize > buf.length) throw new Error('truncated entry'); + return { method, data: buf.subarray(start, start + compressedSize) }; + } + at += 46 + nameLength + extraLength + commentLength; + } + return null; +} + +const XML_ENTITIES: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }; + +function decodeXmlEntities(text: string): string { + return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);/g, (whole, body: string) => { + if (body.startsWith('#x')) return safeCodePoint(parseInt(body.slice(2), 16), whole); + if (body.startsWith('#')) return safeCodePoint(parseInt(body.slice(1), 10), whole); + return XML_ENTITIES[body] ?? whole; + }); +} + +function safeCodePoint(code: number, fallback: string): string { + return Number.isInteger(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : fallback; +} + +const DOCX_PARAGRAPH_END = ''; + +/** How many `.docx` paragraphs are read between two reads of the CPU clock. */ +const DOCX_BUDGET_CHECK_EVERY = 64; + +/** One stretch of a `.docx` body as text: tabs and breaks kept, a paragraph end as a line end, every other tag dropped. */ +function docxChunkText(xml: string): string { + const text = xml + .replace(/]*\/>/g, '\t') + .replace(/]*\/>/g, '\n') + .replace(/<\/w:p>/g, '\n') + .replace(/<[^>]+>/g, ''); + return decodeXmlEntities(text); +} + +/** + * A `.docx` body's text: paragraphs as lines, tabs and breaks kept, every + * other tag dropped. Read paragraph by paragraph, stopping at a paragraph end + * once the CPU budget is spent; `paragraphs` counts those read and `complete` + * says whether the body was read to its end. + */ +function docxXmlText( + xml: string, + budget: CpuBudget, + onProgress?: ProgressSink, +): { text: string; complete: boolean; outOfBudget: boolean; paragraphs: number } { + const parts: string[] = []; + let reported = 0; + let at = 0; + let paragraphs = 0; + let outOfBudget = false; + while (at < xml.length) { + const end = xml.indexOf(DOCX_PARAGRAPH_END, at); + const next = end < 0 ? xml.length : end + DOCX_PARAGRAPH_END.length; + parts.push(docxChunkText(xml.slice(at, next))); + at = next; + if (end >= 0) paragraphs++; + if (at >= xml.length) break; + // Between paragraphs, never mid-paragraph; every DOCX_BUDGET_CHECK_EVERY + // paragraphs, so the clock read stays a rounding error on a long body. + if (paragraphs % DOCX_BUDGET_CHECK_EVERY === 0) { + if (onProgress) { + onProgress({ kind: 'docx-paragraphs', text: parts.slice(reported).join(''), paragraphs }); + reported = parts.length; + } + if (budget.spent()) { + outOfBudget = true; + break; + } + } + } + return { + text: parts.join(''), + complete: at >= xml.length, + outOfBudget, + paragraphs, + }; +} + +/** + * A Word document's answer from its body's text as read: blank runs folded, + * cut at the length cap, `truncated` when the body was not read to its end, + * and the budget note when reading stopped at the budget. + */ +function docxAnswer(read: string, complete: boolean, stop: BudgetStop | undefined): ExtractedContent { + const whole = read.replace(/\n{3,}/g, '\n\n').trim(); + if (!whole) return { kind: 'none', reason: stop ? cpuBudgetNote(stop, false) : 'This Word document has no text.' }; + const { text, truncated } = bounded(whole); + return { + kind: 'text', + format: DOCX_TYPE, + text, + truncated: truncated || !complete, + ...(stop !== undefined ? { note: cpuBudgetNote(stop, true) } : {}), + }; +} + +function extractDocxText(bytes: Uint8Array, budget: CpuBudget, onProgress?: ProgressSink): ExtractedContent { + const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let entry: { method: number; data: Buffer } | null; + try { + entry = zipEntry(buf, DOCX_BODY_ENTRY); + } catch { + return { kind: 'none', reason: NOT_A_DOCX }; + } + if (!entry) return { kind: 'none', reason: NOT_A_DOCX }; + let xml: Buffer; + try { + if (entry.method === 0) xml = entry.data; + else if (entry.method === 8) xml = inflateRawSync(entry.data, { maxOutputLength: READ_FILE_DOCX_XML_MAX_BYTES }); + else return { kind: 'none', reason: NOT_A_DOCX }; + } catch (err) { + const tooLarge = (err as { code?: unknown })?.code === 'ERR_BUFFER_TOO_LARGE' || err instanceof RangeError; + return { + kind: 'none', + reason: tooLarge + ? `This Word document's text expands past ${READ_FILE_DOCX_XML_MAX_BYTES} bytes, more than read_file reads. Download it with the link instead.` + : NOT_A_DOCX, + }; + } + if (xml.length > READ_FILE_DOCX_XML_MAX_BYTES) { + return { + kind: 'none', + reason: `This Word document's text is more than ${READ_FILE_DOCX_XML_MAX_BYTES} bytes, more than read_file reads. Download it with the link instead.`, + }; + } + // The inflate above is one call and cannot stop part-way; its output is + // bounded by READ_FILE_DOCX_XML_MAX_BYTES. The budget is checked between + // the body's paragraphs. + const read = docxXmlText(xml.toString('utf8'), budget, onProgress); + const stop = read.outOfBudget ? { budgetMs: budget.budgetMs, after: `${read.paragraphs} paragraphs` } : undefined; + return docxAnswer(read.text, read.complete, stop); +} diff --git a/packages/mcp/src/file-extraction-pool.ts b/packages/core/src/document-text-pool.ts similarity index 77% rename from packages/mcp/src/file-extraction-pool.ts rename to packages/core/src/document-text-pool.ts index 4b0c78ef2d8..d218f0127d1 100644 --- a/packages/mcp/src/file-extraction-pool.ts +++ b/packages/core/src/document-text-pool.ts @@ -4,12 +4,14 @@ import { existsSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { Worker } from 'node:worker_threads'; -import type { DocumentKind, ExtractedContent, ExtractionProgress } from './file-content.js'; +import type { DocumentKind, ExtractedContent, ExtractionProgress } from './document-text-extract.js'; +import { documentTextState as pool } from './document-text-state.js'; /** - * [#31828] The bounded `worker_threads` pool `read_file` extracts PDF and Word - * text on, so the request thread keeps serving while a file is read (the - * #31100 ruling, phase 2; ADR-0102 D1). + * [#31828] The bounded `worker_threads` pool PDF and Word text is extracted on + * (`@objectstack/core/document-text`, the extractor `read_file` and every + * other caller share), so the request thread keeps serving while a file is + * read (the #31100 ruling, phase 2; ADR-0102 D1). * * - **Size.** At most `poolSize` workers, which is the host's cap on * extractions in flight (`OS_MCP_READ_FILE_MAX_CONCURRENT`): one knob. The @@ -25,7 +27,7 @@ import type { DocumentKind, ExtractedContent, ExtractionProgress } from './file- * - **Replacement.** A worker that overran, crashed or exited is never handed * another job; the next job starts a fresh one. A crash fails only its own * job (the promise rejects; `read_file` answers its could-not-read - * sentence). + * sentence, another caller decides its own answer). * - **Unavailable.** When the worker entry cannot start (it is not beside * this module, as in a host that bundled the package into one file, or it * fails before it says it is ready), every job answers `unavailable` and @@ -70,8 +72,8 @@ export type ExtractionWorkerMessage = export type ExtractionWorkerRequest = ExtractionJob; /** - * The built worker entry beside this module: `file-extraction-worker.js` - * beside `index.js`, `.cjs` beside `index.cjs` (the CJS build's + * The built worker entry beside this module: `document-text-worker.js` + * beside `document-text.js`, `.cjs` beside `document-text.cjs` (the CJS build's * `import.meta.url` is tsup's `shims` rewrite). Anything else (the TypeScript * source under a test runner, a bundle with no `import.meta`) names why * there is none. @@ -86,9 +88,9 @@ function builtWorkerEntry(): ExtractionWorkerEntry | string { if (typeof here !== 'string' || here === '') return 'this module has no import.meta.url to find the worker entry from'; const ext = /\.(c?js|mjs)$/.exec(new URL(here).pathname)?.[0]; if (!ext) return `this module runs from ${new URL(here).pathname}, not a built .js or .cjs file, so there is no built worker entry beside it`; - const url = new URL(`./file-extraction-worker${ext}`, here); + const url = new URL(`./document-text-worker${ext}`, here); if (url.protocol === 'file:' && !existsSync(fileURLToPath(url))) { - return `the worker entry ${fileURLToPath(url)} is not there (was @objectstack/mcp bundled into one file?)`; + return `the worker entry ${fileURLToPath(url)} is not there (was @objectstack/core bundled into one file? Point the pool at the entry with configureExtractionWorkerEntry)`; } return { url }; } @@ -100,38 +102,45 @@ function builtWorkerEntry(): ExtractionWorkerEntry | string { */ const WORKER_START_TIMEOUT_MS = 10_000; -let entryOverride: ExtractionWorkerEntry | undefined; +/** + * Why no worker can start from THIS copy of the module, once recorded (and + * warned) the first time. Per copy, never in the shared state: the built + * entry is found beside this copy's own `import.meta.url`, so one copy that + * cannot find it (a host that bundled core into one file) says nothing about + * another copy in the same process that can (core loaded from + * `node_modules`), whose extractions stay off the request thread. + */ let unavailableReason: string | undefined; -const idle: Worker[] = []; -let started = 0; /** * Point the pool at another worker entry (or back at the built one), and * start it over: idle workers are terminated and a recorded "cannot start" is - * forgotten. For tests, which run the TypeScript source through a loader. + * forgotten. For a host that ships the worker entry somewhere other than + * beside this module (a bundled deployment), and for tests, which run the + * TypeScript source through a loader. */ export function configureExtractionWorkerEntry(entry: ExtractionWorkerEntry | undefined): void { - entryOverride = entry; + pool.entryOverride = entry; resetExtractionWorkerPool(); } /** Terminate the idle workers, forget a recorded "cannot start", and count started workers from zero. */ export function resetExtractionWorkerPool(): void { - for (const worker of idle.splice(0)) void worker.terminate(); + for (const worker of pool.idle.splice(0)) void worker.terminate(); unavailableReason = undefined; - started = 0; + pool.started = 0; } /** How many workers the pool has started, and how many sit idle. */ export function extractionWorkerPoolStats(): { started: number; idle: number } { - return { started, idle: idle.length }; + return { started: pool.started, idle: pool.idle.length }; } function markUnavailable(reason: string): ExtractionOutcome { if (unavailableReason === undefined) { unavailableReason = reason; console.warn( - `[MCP] read_file extracts PDF and Word text on the request thread, not on a worker: ${reason}. ` + `[document-text] PDF and Word text (read_file and every other caller) is extracted on the request thread, not on a worker: ${reason}. ` + 'The CPU budget and the cap on extractions in flight still apply.', ); } @@ -140,7 +149,7 @@ function markUnavailable(reason: string): ExtractionOutcome { /** A worker started and ready for a job, or the reason it could not start. */ function startWorker(): Promise { - const entry = entryOverride ?? builtWorkerEntry(); + const entry = pool.entryOverride ?? builtWorkerEntry(); if (typeof entry === 'string') return Promise.resolve(entry); let worker: Worker; try { @@ -150,14 +159,14 @@ function startWorker(): Promise { } catch (err) { return Promise.resolve(`the worker entry could not start: ${(err as Error)?.message ?? String(err)}`); } - started++; + pool.started++; worker.stdout.pipe(process.stderr, { end: false }); // Between jobs nobody else listens: an idle worker's failure must not be an // unhandled 'error' event, and a worker that ended leaves the idle list. worker.on('error', () => {}); worker.on('exit', () => { - const at = idle.indexOf(worker); - if (at >= 0) idle.splice(at, 1); + const at = pool.idle.indexOf(worker); + if (at >= 0) pool.idle.splice(at, 1); }); return new Promise((resolve) => { const timer = setTimeout( @@ -185,9 +194,9 @@ function startWorker(): Promise { /** Hand a worker back to the pool, or end it when the pool is already full. */ function release(worker: Worker, poolSize: number): void { - if (idle.length < poolSize) { + if (pool.idle.length < poolSize) { worker.unref(); - idle.push(worker); + pool.idle.push(worker); } else { void worker.terminate(); } @@ -205,9 +214,12 @@ function discard(worker: Worker): void { * worker crashed or its extractor threw. */ export async function runExtractionInWorker(job: ExtractionJob, bounds: ExtractionPoolBounds): Promise { - if (unavailableReason !== undefined) return { status: 'unavailable', reason: unavailableReason }; - let worker = idle.pop(); + // An idle worker first, whichever copy started it: it runs the same protocol + // (the state key's suffix guards that), so a copy that cannot start one of + // its own still reads on a worker while one is idle. + let worker = pool.idle.pop(); if (!worker) { + if (unavailableReason !== undefined) return { status: 'unavailable', reason: unavailableReason }; const startedWorker = await startWorker(); if (typeof startedWorker === 'string') return markUnavailable(startedWorker); worker = startedWorker; @@ -234,16 +246,20 @@ function runOn(worker: Worker, job: ExtractionJob, bounds: ExtractionPoolBounds) const onMessage = (message: ExtractionWorkerMessage) => { if (message?.type === 'progress') progress.push(message.progress); else if (message?.type === 'done') settle(true, () => resolve({ status: 'done', result: message.result })); - else if (message?.type === 'failed') settle(true, () => reject(new Error(`read_file extraction failed: ${message.message}`))); + else if (message?.type === 'failed') settle(true, () => reject(new Error(`document extraction failed: ${message.message}`))); }; const onError = (err: Error) => settle(false, () => reject(err)); - const onExit = (code: number) => settle(false, () => reject(new Error(`read_file extraction worker exited (code ${code})`))); + const onExit = (code: number) => settle(false, () => reject(new Error(`document extraction worker exited (code ${code})`))); worker.on('message', onMessage); worker.once('error', onError); worker.once('exit', onExit); // The worker gets its own copy: the caller's bytes stay usable, and the - // copy's buffer moves to the worker instead of being cloned again. - const bytes = job.bytes.slice(); + // copy's buffer moves to the worker instead of being cloned again. A + // fresh `Uint8Array`, never `job.bytes.slice()`: a Node `Buffer` is a + // `Uint8Array` whose `slice` is a view over the same memory (often Node's + // shared, untransferable pool), so moving its buffer would fail to clone + // or detach the caller's bytes. + const bytes = new Uint8Array(job.bytes); const request: ExtractionWorkerRequest = { kind: job.kind, bytes, cpuBudgetMs: job.cpuBudgetMs }; worker.postMessage(request, [bytes.buffer]); }); diff --git a/packages/core/src/document-text-state.ts b/packages/core/src/document-text-state.ts new file mode 100644 index 00000000000..4213fb024a2 --- /dev/null +++ b/packages/core/src/document-text-state.ts @@ -0,0 +1,58 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { Worker } from 'node:worker_threads'; + +import type { ReadFileExtractionLimits } from './document-text-extract.js'; +import type { ExtractionWorkerEntry } from './document-text-pool.js'; + +/** + * The document extractor's process-wide state, held once per process however + * many copies of this package the process loaded. + * + * The cap on extractions in flight is one number for the whole process, + * whoever asks: the MCP `read_file` tool and an AI service may reach the + * extractor through different copies of `@objectstack/core` (an ESM `import` + * and a CJS `require` of `@objectstack/core/document-text` each load their own + * module, and a host can install two versions). Module-level variables would + * give each copy its own count, bounds and pool, so N copies would admit N + * times the cap. The state lives instead under a registered symbol on + * `globalThis` (`Symbol.for` returns the same symbol in every copy), the way + * `security/credential-use-client.ts` shares its scope storage. + * + * Bump the key's suffix whenever this shape or the pool's worker protocol + * (`ExtractionWorkerRequest` / `ExtractionWorkerMessage`) changes, so a copy + * never reads state or hands a job to a worker of a shape it does not know; + * copies on different suffixes then keep separate state, as before this + * module. + * + * What is true of one copy only stays in that copy: whether a worker entry + * can be found beside it (`document-text-pool.ts`'s `unavailableReason`). + * + * A worker thread has its own `globalThis`, so a pool worker never shares + * (or counts against) the request threads' state. + */ +export interface DocumentTextState { + /** The bounds fixed by `configureReadFileExtraction`, or read on the first extraction. */ + limits: ReadFileExtractionLimits | undefined; + /** PDF and Word extractions running now, process-wide. */ + inFlight: number; + /** The worker entry a host pointed the pool at, if any. */ + entryOverride: ExtractionWorkerEntry | undefined; + /** Started workers waiting for the next job. */ + idle: Worker[]; + /** Workers started since the pool was last reset. */ + started: number; +} + +const STATE_KEY: unique symbol = Symbol.for('objectstack.core.documentText.state.v1'); + +/** Marks a `ReadFileExtractionBusyError` from any copy, for its `instanceof`. */ +export const BUSY_ERROR_BRAND: unique symbol = Symbol.for('objectstack.core.documentText.busyError'); + +export const documentTextState: DocumentTextState = ((globalThis as Record)[STATE_KEY] ??= { + limits: undefined, + inFlight: 0, + entryOverride: undefined, + idle: [], + started: 0, +} satisfies DocumentTextState) as DocumentTextState; diff --git a/packages/mcp/src/file-extraction-worker.ts b/packages/core/src/document-text-worker.ts similarity index 87% rename from packages/mcp/src/file-extraction-worker.ts rename to packages/core/src/document-text-worker.ts index 04953165d76..fcbe3aae462 100644 --- a/packages/mcp/src/file-extraction-worker.ts +++ b/packages/core/src/document-text-worker.ts @@ -3,12 +3,12 @@ import { performance } from 'node:perf_hooks'; import { parentPort } from 'node:worker_threads'; -import { extractDocument, preloadPdfReader, type CpuBudget } from './file-content.js'; -import type { ExtractionWorkerMessage, ExtractionWorkerRequest } from './file-extraction-pool.js'; +import { extractDocument, preloadPdfReader, type CpuBudget } from './document-text-extract.js'; +import type { ExtractionWorkerMessage, ExtractionWorkerRequest } from './document-text-pool.js'; /** - * [#31828] The `read_file` extraction worker: one job at a time, a PDF's or a - * Word document's text, read by the same extractors the in-process path runs + * [#31828] The document extraction worker (`@objectstack/core/document-text`): + * one job at a time, a PDF's or a Word document's text, read by the same extractors the in-process path runs * (`extractDocument`), so a worker's answer is the in-process answer. * * - Each page (PDF) or each 64 paragraphs (Word) is sent back as it is read, @@ -22,7 +22,8 @@ import type { ExtractionWorkerMessage, ExtractionWorkerRequest } from './file-ex * (`performance.eventLoopUtilization()`), which a worker that does nothing * else spends only on this job. * - An extractor that throws answers `failed` and the worker stays usable; - * `read_file` answers its could-not-read sentence, as in-process. + * the caller's promise rejects, as in-process (`read_file` answers its + * could-not-read sentence). * - `unpdf` stays a dynamic import (never loaded with the package), and the * worker loads and sets it up before it says it is ready (`preloadPdfReader`), so the * load is part of the worker's start and never of a job's ceiling. diff --git a/packages/core/src/document-text.shared-state.test.ts b/packages/core/src/document-text.shared-state.test.ts new file mode 100644 index 00000000000..09633f9a749 --- /dev/null +++ b/packages/core/src/document-text.shared-state.test.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; + +import { extractionWorkerPoolStats } from './document-text-pool.js'; + +type DocumentText = typeof import('./document-text.js'); + +const DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; + +/** Two separate module copies of the public entry, as an ESM and a CJS load of the package would be. */ +async function twoCopies(): Promise<[DocumentText, DocumentText]> { + vi.resetModules(); + const first = await import('./document-text.js'); + vi.resetModules(); + const second = await import('./document-text.js'); + return [first, second]; +} + +/** + * [#39008] The extractor's process-wide state (the bounds, the count of + * extractions in flight, the worker pool) is one per process, not one per + * module copy: an ESM `import` and a CJS `require` of + * `@objectstack/core/document-text` (or two installed versions) are two + * copies, and per-copy state would admit the cap once per copy. + */ +describe('every copy of @objectstack/core/document-text in one process shares one state', () => { + afterEach(async () => { + const [copy] = await twoCopies(); + copy.configureReadFileExtraction({ + cpuBudgetMs: copy.READ_FILE_CPU_BUDGET_MS_DEFAULT, + maxConcurrent: copy.READ_FILE_MAX_CONCURRENT_DEFAULT, + }); + copy.configureExtractionWorkerEntry(undefined); + vi.restoreAllMocks(); + }); + + it('the copies are distinct modules (the premise of the rest)', async () => { + const [first, second] = await twoCopies(); + expect(first.extractFileContent).not.toBe(second.extractFileContent); + expect(first.ReadFileExtractionBusyError).not.toBe(second.ReadFileExtractionBusyError); + }); + + it('bounds fixed through one copy are the bounds every copy runs under', async () => { + const [first, second] = await twoCopies(); + first.configureReadFileExtraction({ cpuBudgetMs: 750, maxConcurrent: 3 }); + expect(second.activeReadFileExtractionLimits()).toEqual({ cpuBudgetMs: 750, maxConcurrent: 3 }); + }); + + it('an extraction in flight through one copy counts against the cap of every copy', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const [first, second] = await twoCopies(); + first.configureReadFileExtraction({ cpuBudgetMs: 2000, maxConcurrent: 1 }); + + // The slot is taken synchronously, before the extraction's first await. + const holding = first.extractFileContent(new Uint8Array([1, 2, 3]), DOCX, 'a.docx'); + const refused = second.extractFileContent(new Uint8Array([1, 2, 3]), DOCX, 'b.docx'); + + const error = await refused.then(() => undefined, (err: unknown) => err); + expect(error).toBeInstanceOf(second.ReadFileExtractionBusyError); + expect(error).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, maxConcurrent: 1 }); + await expect(holding).resolves.toMatchObject({ kind: 'none' }); + + // Released through the first copy, the slot is free for the second. + await expect(second.extractFileContent(new Uint8Array([1, 2, 3]), DOCX, 'c.docx')).resolves.toMatchObject({ kind: 'none' }); + }); + + it("a busy refusal raised by one copy is an instance of every copy's class, and nothing else is", async () => { + const [first, second] = await twoCopies(); + const refusal = new first.ReadFileExtractionBusyError(4, 2); + expect(refusal).toBeInstanceOf(second.ReadFileExtractionBusyError); + expect(refusal).toBeInstanceOf(first.ReadFileExtractionBusyError); + expect(refusal).toBeInstanceOf(Error); + expect(new Error('busy')).not.toBeInstanceOf(second.ReadFileExtractionBusyError); + expect(Object.assign(new Error('x'), { code: 'SERVICE_UNAVAILABLE' })).not.toBeInstanceOf(second.ReadFileExtractionBusyError); + expect(null).not.toBeInstanceOf(second.ReadFileExtractionBusyError); + }); + + it('a copy that cannot find its worker decides that for itself only, and still reads on an idle worker', { timeout: 60_000 }, async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const [first, second] = await twoCopies(); + first.configureExtractionWorkerEntry(undefined); + + // Under vitest neither copy has a built worker beside it. The first copy + // finds none and says so; that is its own verdict, so the second copy + // looks for its own entry and says so too, instead of inheriting it. + await expect(first.extractFileContent(new Uint8Array([1, 2, 3]), DOCX, 'a.docx')).resolves.toMatchObject({ kind: 'none' }); + await expect(second.extractFileContent(new Uint8Array([1, 2, 3]), DOCX, 'b.docx')).resolves.toMatchObject({ kind: 'none' }); + expect(warn).toHaveBeenCalledTimes(2); + expect(extractionWorkerPoolStats().started).toBe(0); + + // The second copy gets an entry (the worker's source through tsx) and + // reads on a worker, which goes back to the shared idle list. + second.configureExtractionWorkerEntry({ + url: new URL('./document-text-worker.ts', import.meta.url), + execArgv: ['--import', pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href], + }); + await expect(second.extractFileContent(new Uint8Array([1, 2, 3]), DOCX, 'c.docx')).resolves.toMatchObject({ kind: 'none' }); + expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 1 }); + + // The first copy still holds its own "cannot start", yet takes the idle + // worker rather than reading on the request thread, and says nothing more. + await expect(first.extractFileContent(new Uint8Array([1, 2, 3]), DOCX, 'd.docx')).resolves.toMatchObject({ kind: 'none' }); + expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 1 }); + expect(warn).toHaveBeenCalledTimes(2); + }); +}); diff --git a/packages/core/src/document-text.ts b/packages/core/src/document-text.ts new file mode 100644 index 00000000000..ab9e80704d9 --- /dev/null +++ b/packages/core/src/document-text.ts @@ -0,0 +1,104 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `@objectstack/core/document-text`: the words of a file's bytes, read under + * fixed caps and two host bounds. One extractor for every caller in the + * process: the MCP `read_file` tool (`@objectstack/mcp`, which renders this + * answer beside the file's facts and a download link) and any AI service that + * hands a model a document's text instead of the document itself. Node-only, + * like `@objectstack/core/egress`, and kept off the main entry, so a host that + * never reads a document never loads `unpdf`. + * + * Every caller in one process shares the same bounds, the same worker pool and + * the same count of extractions in flight: the cap is one process-wide number, + * whoever asks, and through whichever copy of this package (an ESM and a CJS + * load, or two installed versions, share one state: `document-text-state.ts`). The names keep the `READ_FILE_` prefix of the two host + * variables that set the bounds (`OS_MCP_READ_FILE_*`), which `read_file` + * shipped first. + * + * ## The caps, each a named constant + * + * - {@link READ_FILE_TEXT_MAX_CHARS}: the most characters of text one answer + * carries; past it the text is cut and the answer says so. + * - {@link READ_FILE_PDF_MAX_PAGES}: the most PDF pages read. + * - {@link READ_FILE_DOCX_XML_MAX_BYTES}: the most bytes a `.docx` body may + * inflate to (a compressed body can expand far past its stored size). + * - {@link READ_FILE_IMAGE_MAX_BYTES}: the largest image answered as an image. + * + * How many bytes a caller reads at all is the caller's cap (`read_file`'s is + * its own `READ_FILE_MAX_BYTES`, 10 MiB); every extractor here runs on the + * bytes it is handed. + * + * ## The extractors + * + * - Text (`text/*`, JSON, XML, CSV, Markdown, YAML, SVG): decoded as UTF-8. + * - Images (PNG, JPEG, GIF, WebP): answered as the image itself, base64, up to + * {@link READ_FILE_IMAGE_MAX_BYTES}. + * - PDF: `unpdf` 1.9.1 (pdf.js), loaded by dynamic import on the first PDF + * read, with pdf.js's `eval` path off (`isEvalSupported: false`) and its + * console output off. A file pdf.js cannot open answers a sentence, never a + * throw. + * - Word (`.docx`): the ZIP's `word/document.xml`, inflated with `node:zlib` + * under {@link READ_FILE_DOCX_XML_MAX_BYTES}, its paragraphs as lines. + * + * Anything else answers `{ kind: 'none' }` with a sentence saying it has no + * text to read. The sentences were written for `read_file`: they name that + * tool and the download link it answers beside them. + * + * ## Off the request thread, under two host bounds (ADR-0102 D1) + * + * PDF and Word extraction runs on a bounded `worker_threads` pool + * (`document-text-pool.ts`, entry `document-text-worker.ts`), so the request + * thread keeps serving every other request while a file is read. Two + * host-configured bounds keep one caller's files from holding the process: + * + * - a CPU-time budget per extraction ({@link READ_FILE_CPU_BUDGET_MS_ENV}, + * default {@link READ_FILE_CPU_BUDGET_MS_DEFAULT}), checked between PDF + * pages and between Word paragraphs, never mid-page. In a worker it is the + * worker thread's own CPU time; in-process it is process CPU time + * (`process.cpuUsage()` deltas), which charges an extraction for work + * interleaved with it, so the error is to stop early, never late. Out of + * budget, the answer is the text read so far, `truncated: true`, and a note + * naming the budget. A worker that does not reach a checkpoint within + * {@link READ_FILE_WALL_CEILING_MULTIPLE} budgets of wall time is + * terminated and replaced, and the answer is the same shape over the pages + * it had already sent back. + * - a process-wide cap on extractions in flight + * ({@link READ_FILE_MAX_CONCURRENT_ENV}, default + * {@link READ_FILE_MAX_CONCURRENT_DEFAULT}), which is also the pool's size. + * Over it, the call is refused on the request thread at once, before any + * worker is touched, never queued: {@link ReadFileExtractionBusyError}, a + * retryable `SERVICE_UNAVAILABLE`. + * + * A host where the worker cannot start (one that bundled this package into a + * single file, so the worker entry is not beside it) extracts in-process under + * the same two bounds, said once at `warn` with the reason; such a host can + * point the pool at the worker entry it ships with + * {@link configureExtractionWorkerEntry}. + * + * Both bounds are read once ({@link configureReadFileExtraction}, which the + * MCP plugin's `init` calls at boot; a process that never calls it reads them + * on its first extraction), and a malformed value throws naming the variable, + * never a bound that is silently off. + */ + +export { + READ_FILE_TEXT_MAX_CHARS, + READ_FILE_PDF_MAX_PAGES, + READ_FILE_DOCX_XML_MAX_BYTES, + READ_FILE_IMAGE_MAX_BYTES, + READ_FILE_CPU_BUDGET_MS_ENV, + READ_FILE_MAX_CONCURRENT_ENV, + READ_FILE_CPU_BUDGET_MS_DEFAULT, + READ_FILE_MAX_CONCURRENT_DEFAULT, + READ_FILE_WALL_CEILING_MULTIPLE, + resolveReadFileExtractionLimits, + configureReadFileExtraction, + activeReadFileExtractionLimits, + ReadFileExtractionBusyError, + extractFileContent, + type ReadFileExtractionLimits, + type ExtractedContent, +} from './document-text-extract.js'; + +export { configureExtractionWorkerEntry, type ExtractionWorkerEntry } from './document-text-pool.js'; diff --git a/packages/core/src/document-text.worker-pool.test.ts b/packages/core/src/document-text.worker-pool.test.ts new file mode 100644 index 00000000000..df67f1bf687 --- /dev/null +++ b/packages/core/src/document-text.worker-pool.test.ts @@ -0,0 +1,453 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; +import { crc32, deflateRawSync } from 'node:zlib'; + +import { + READ_FILE_CPU_BUDGET_MS_DEFAULT, + READ_FILE_MAX_CONCURRENT_DEFAULT, + ReadFileExtractionBusyError, + configureExtractionWorkerEntry, + configureReadFileExtraction, + extractFileContent, + type ExtractedContent, + type ExtractionWorkerEntry, +} from './document-text.js'; +import { extractionWorkerPoolStats } from './document-text-pool.js'; + +/** + * [#31828] The shared document extractor (`@objectstack/core/document-text`) + * read on its worker pool: the request thread keeps running while a heavy PDF + * is read; a worker past its wall-clock ceiling is terminated, the pages it + * sent back are the answer, and the next call gets a fresh worker; a crashed + * worker fails only its own call; the over-cap refusal is decided on the + * request thread; and where no worker can start, the in-process answer is the + * same. + * + * These pins moved here from `@objectstack/mcp`'s `read_file` suite with the + * pool itself. That suite keeps the in-process pins and how `read_file` + * renders each answer (the facts block, the note, the coded busy refusal, the + * could-not-read sentence for a rejected read); here the answer is the + * extractor's own (`ExtractedContent`, or the rejection). + * + * Under vitest this module is the TypeScript source, which has no built worker + * beside it, so the pool is pointed at the worker's source, started through + * the repo's `tsx` loader. + */ + +/** A one-page PDF whose page draws `text` in Helvetica, with a correct cross-reference table. */ +function minimalPdf(text: string): Uint8Array { + return pdfOf([`BT /F1 24 Tf 72 720 Td (${text}) Tj ET`]); +} + +/** A PDF with one page per entry of `texts`, each page drawing its text in Helvetica. */ +function multiPagePdf(texts: string[]): Uint8Array { + return pdfOf(texts.map((text) => `BT /F1 24 Tf 72 720 Td (${text}) Tj ET`)); +} + +/** A PDF whose pages each say `Page N text`, plus `drawOps(N)` path operators (what makes a page slow to read). */ +function heavyPdf(pages: number, drawOps: (page: number) => number): Uint8Array { + const streams: string[] = []; + for (let i = 0; i < pages; i++) { + const draw: string[] = []; + for (let k = 0; k < drawOps(i + 1); k++) draw.push(`${(k * 7) % 600} ${(k * 13) % 780} m ${(k * 11) % 600} ${(k * 17) % 780} l S`); + streams.push(`BT /F1 12 Tf 72 720 Td (Page ${i + 1} text) Tj ET\n${draw.join('\n')}`); + } + return pdfOf(streams); +} + +/** A PDF with one page per content stream, Helvetica as the font, and a correct cross-reference table. */ +function pdfOf(streams: string[]): Uint8Array { + const objects: string[] = []; + objects[1] = '<< /Type /Catalog /Pages 2 0 R >>'; + objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>'; + const kids: string[] = []; + streams.forEach((stream, i) => { + const pageId = 4 + i * 2; + kids.push(`${pageId} 0 R`); + objects[pageId] = `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${pageId + 1} 0 R /Resources << /Font << /F1 3 0 R >> >> >>`; + objects[pageId + 1] = `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`; + }); + objects[2] = `<< /Type /Pages /Kids [${kids.join(' ')}] /Count ${streams.length} >>`; + let out = '%PDF-1.4\n'; + const offsets: number[] = []; + for (let i = 1; i < objects.length; i++) { + offsets[i] = out.length; + out += `${i} 0 obj\n${objects[i]}\nendobj\n`; + } + const xref = out.length; + out += `xref\n0 ${objects.length}\n0000000000 65535 f \n`; + for (let i = 1; i < objects.length; i++) out += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`; + out += `trailer\n<< /Size ${objects.length} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; + return new Uint8Array(Buffer.from(out, 'latin1')); +} + +/** A ZIP holding `entries`, each deflated, as a `.docx` is laid out. */ +function zip(entries: Record): Uint8Array { + const locals: Buffer[] = []; + const centrals: Buffer[] = []; + let offset = 0; + for (const [name, data] of Object.entries(entries)) { + const nameBuf = Buffer.from(name, 'utf8'); + const compressed = deflateRawSync(data); + const crc = crc32(data); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(8, 8); + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(compressed.length, 18); + local.writeUInt32LE(data.length, 22); + local.writeUInt16LE(nameBuf.length, 26); + locals.push(local, nameBuf, compressed); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(20, 4); + central.writeUInt16LE(20, 6); + central.writeUInt16LE(8, 10); + central.writeUInt32LE(crc, 16); + central.writeUInt32LE(compressed.length, 20); + central.writeUInt32LE(data.length, 24); + central.writeUInt16LE(nameBuf.length, 28); + central.writeUInt32LE(offset, 42); + centrals.push(central, nameBuf); + offset += local.length + nameBuf.length + compressed.length; + } + const cd = Buffer.concat(centrals); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(Object.keys(entries).length, 8); + end.writeUInt16LE(Object.keys(entries).length, 10); + end.writeUInt32LE(cd.length, 12); + end.writeUInt32LE(offset, 16); + return new Uint8Array(Buffer.concat([...locals, cd, end])); +} + +const DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; +const docxBody = (paragraphs: string[]) => + Buffer.from( + '' + + paragraphs.map((p) => `${p}`).join('') + + '', + ); + +const pageTexts = (n: number) => Array.from({ length: n }, (_, i) => `Page ${i + 1} text`); + +const DEFAULTS = { cpuBudgetMs: READ_FILE_CPU_BUDGET_MS_DEFAULT, maxConcurrent: READ_FILE_MAX_CONCURRENT_DEFAULT }; + +const pdfRead = (bytes: Uint8Array, name = 'file.pdf') => extractFileContent(bytes, 'application/pdf', name); + +describe('the document extractor reads PDF and Word text on a worker pool, off the request thread', { timeout: 60_000 }, () => { + const SOURCE_WORKER: ExtractionWorkerEntry = { + url: new URL('./document-text-worker.ts', import.meta.url), + execArgv: ['--import', pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href], + }; + beforeEach(() => { + configureReadFileExtraction(DEFAULTS); + configureExtractionWorkerEntry(SOURCE_WORKER); + }); + afterEach(() => { + vi.restoreAllMocks(); + configureExtractionWorkerEntry(undefined); + configureReadFileExtraction(DEFAULTS); + }); + + it('CONTROL: a small PDF and a small Word document read in full on a worker, the same answer the in-process path gives', async () => { + const pdf = multiPagePdf(['Page one opens', 'Page two follows', 'Page three closes']); + const docx = zip({ 'word/document.xml': docxBody(['Claim summary', 'Water & mould']) }); + const read = () => Promise.all([pdfRead(pdf, 'three.pdf'), extractFileContent(docx, DOCX, 'summary.docx')]); + + const onWorker = await read(); + expect(extractionWorkerPoolStats().started).toBeGreaterThanOrEqual(1); + expect(onWorker[0]).toEqual({ + kind: 'text', + format: 'application/pdf', + text: 'Page one opens\n\nPage two follows\n\nPage three closes', + truncated: false, + }); + expect(onWorker[1]).toEqual({ kind: 'text', format: DOCX, text: 'Claim summary\nWater & mould', truncated: false }); + + // The in-process path: under vitest the built entry is not beside the + // pool's source, so no worker starts, said once at warn with the reason. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + configureExtractionWorkerEntry(undefined); + const inProcess = await read(); + expect(inProcess).toEqual(onWorker); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toContain('not a built .js or .cjs file'); + expect(String(warn.mock.calls[0][0])).toContain('The CPU budget and the cap on extractions in flight still apply.'); + }); + + it('an entry that fails before it is ready falls back to in-process, said once, and answers the same', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + configureExtractionWorkerEntry({ url: new URL('data:text/javascript,throw new Error("no extraction here")') }); + const pdf = minimalPdf('Read in-process'); + const first = await pdfRead(pdf, 'a.pdf'); + const second = await pdfRead(pdf, 'a.pdf'); + expect(first).toMatchObject({ kind: 'text', text: 'Read in-process' }); + expect(second).toEqual(first); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toContain('no extraction here'); + }); + + it('the request thread keeps ticking while a heavy PDF is read', async () => { + const pdf = heavyPdf(120, () => 2250); + await pdfRead(pdf, 'heavy.pdf'); // warm: the worker starts and loads unpdf + let ticks = 0; + const interval = setInterval(() => { + ticks++; + }, 1); + const started = performance.now(); + const result = await pdfRead(pdf, 'heavy.pdf'); + const wallMs = performance.now() - started; + clearInterval(interval); + expect(result).toEqual({ kind: 'text', format: 'application/pdf', text: pageTexts(120).join('\n\n'), truncated: false }); + // In-process this count is 0 (pdf.js never yields a macrotask while it + // reads). On the pool a 1 ms timer fires through the read: at least one + // tick per 4 ms of wall time, and at least 20. + expect({ ticks, enough: ticks >= 20 && ticks >= wallMs / 4 }).toMatchObject({ enough: true }); + }); + + /** + * The worker started with a preload that replaces `process.threadCpuUsage` + * IN THE WORKER THREAD with a clock advancing `stepMs` on every read: the + * worker's twin of the in-process stepping clock `read_file`'s suite spies on + * the request thread's `process.cpuUsage`, which cannot reach a worker. "The + * budget is spent" is then decided by how many checkpoints the extractor + * reached, never by how fast, or how loaded, this machine is. The worker's + * own code is unchanged: it reads the clock it always reads. + */ + function steppingThreadCpuWorker(stepMs: number): ExtractionWorkerEntry { + const clock = `let now = 0; process.threadCpuUsage = () => { now += ${stepMs * 1000}; return { user: now, system: 0 }; };`; + return { + ...SOURCE_WORKER, + execArgv: [...(SOURCE_WORKER.execArgv ?? []), '--import', `data:text/javascript,${encodeURIComponent(clock)}`], + }; + } + + it('out of CPU budget on the worker: the pages read so far, truncated, with the budget note, as in-process', async () => { + // The budget is spent at the third checkpoint (3 x 1000 ms of the stepping + // clock), so the read stops after page 3, whatever the runner's load. The + // budget is 3000 ms, not a few tens, because the pool's wall-clock ceiling + // is 5 budgets of REAL time: at 30 ms that ceiling (150 ms) cut a loaded + // runner's read before page 1, answering "after page 0" with no text. + configureReadFileExtraction({ cpuBudgetMs: 3000, maxConcurrent: 4 }); + configureExtractionWorkerEntry(steppingThreadCpuWorker(1000)); + const result = await pdfRead(heavyPdf(120, () => 2250), 'heavy.pdf'); + expect(result).toEqual({ + kind: 'text', + format: 'application/pdf', + text: pageTexts(3).join('\n\n'), + truncated: true, + note: 'Reading stopped at the CPU-time budget for one file (3000 ms) after page 3 of 120, so the text is partial. ' + + 'Download the file with the link for the rest.', + }); + + // Word: the budget is checked every 64 paragraphs. A 15 ms step spends the + // same 3000 ms budget at the 200th checkpoint, 12,800 paragraphs in, which + // is past the length cap, so the cap is what cuts the text that was read. + configureExtractionWorkerEntry(steppingThreadCpuWorker(15)); + const paragraphs = Array.from({ length: 60_000 }, (_, i) => `Paragraph ${i + 1}`); + const docx = zip({ 'word/document.xml': docxBody(paragraphs) }); + const word = await extractFileContent(docx, DOCX, 'long.docx'); + // The length cap still applies to what was read. + expect(paragraphs.slice(0, 12_800).join('\n').length).toBeGreaterThan(100_000); + expect(word).toEqual({ + kind: 'text', + format: DOCX, + text: paragraphs.slice(0, 12_800).join('\n').slice(0, 100_000), + truncated: true, + note: 'Reading stopped at the CPU-time budget for one file (3000 ms) after 12800 paragraphs, so the text is partial. ' + + 'Download the file with the link for the rest.', + }); + }); + + it('a worker past its wall-clock ceiling is terminated: the pages it sent back are the answer, and the next call gets a fresh worker', async () => { + // Ceiling = 5 x 40 ms. Page 2 alone takes far longer, and a page is never + // cut by the budget (it is checked between pages), so only the ceiling + // can stop this read. + configureReadFileExtraction({ cpuBudgetMs: 40, maxConcurrent: 1 }); + await pdfRead(minimalPdf('Small'), 'small.pdf'); // warm the one worker + expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 1 }); + const stopped = await pdfRead(heavyPdf(3, (page) => (page === 2 ? 600_000 : 0)), 'stuck.pdf'); + expect(stopped).toEqual({ + kind: 'text', + format: 'application/pdf', + text: 'Page 1 text', + truncated: true, + note: 'Reading stopped at the CPU-time budget for one file (40 ms) after page 1 of 3, so the text is partial. ' + + 'Download the file with the link for the rest.', + }); + // The overrun worker is gone, not back in the pool. + expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 0 }); + + await expect(pdfRead(minimalPdf('Served next'), 'small.pdf')).resolves.toMatchObject({ text: 'Served next' }); + expect(extractionWorkerPoolStats()).toEqual({ started: 2, idle: 1 }); + }); + + it("a Node Buffer reads on a worker like any Uint8Array, and the caller's Buffer is left as it was", async () => { + // A small Buffer lives in Node's shared allocation pool, whose memory + // cannot be moved to a worker; a large one owns memory the move would + // take from the caller. Each must be copied, never sliced, before it goes. + const pooled = Buffer.from(minimalPdf('Pooled buffer')); + const own = Buffer.alloc(pooled.byteLength + 8192); + pooled.copy(own); + const ownPdf = own.subarray(0, pooled.byteLength); + const before = [Buffer.from(pooled), Buffer.from(ownPdf)]; + + await expect(extractFileContent(pooled, 'application/pdf', 'pooled.pdf')).resolves.toMatchObject({ kind: 'text', text: 'Pooled buffer' }); + await expect(extractFileContent(ownPdf, 'application/pdf', 'own.pdf')).resolves.toMatchObject({ kind: 'text', text: 'Pooled buffer' }); + expect(extractionWorkerPoolStats().started).toBeGreaterThanOrEqual(1); + expect(pooled.equals(before[0])).toBe(true); + expect(ownPdf.equals(before[1])).toBe(true); + expect(own.buffer.byteLength).toBeGreaterThan(0); + }); + + it('a worker that crashes fails only its own call, whose promise rejects, and is replaced', async () => { + // A stand-in worker: it crashes on a file whose first byte is "X", and + // otherwise answers the bytes as text, so the pool's own handling is what + // is pinned. + const standIn = [ + "import { parentPort } from 'node:worker_threads';", + "parentPort.on('message', (job) => {", + ' if (job.bytes[0] === 88) process.exit(7);', + " parentPort.postMessage({ type: 'done', result: { kind: 'text', format: 'application/pdf', text: new TextDecoder().decode(job.bytes), truncated: false } });", + '});', + "parentPort.postMessage({ type: 'ready' });", + ].join('\n'); + configureExtractionWorkerEntry({ url: new URL(`data:text/javascript,${encodeURIComponent(standIn)}`) }); + configureReadFileExtraction({ cpuBudgetMs: 1000, maxConcurrent: 1 }); + await expect(pdfRead(new Uint8Array(Buffer.from('X marks the crash')), 'boom.pdf')).rejects.toThrow( + 'document extraction worker exited (code 7)', + ); + expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 0 }); + await expect(pdfRead(new Uint8Array(Buffer.from('fine')), 'fine.pdf')).resolves.toMatchObject({ text: 'fine' }); + expect(extractionWorkerPoolStats()).toEqual({ started: 2, idle: 1 }); + }); + + it('over the cap is refused on the request thread, at once, with a retryable SERVICE_UNAVAILABLE, while workers read', async () => { + configureReadFileExtraction({ cpuBudgetMs: 3000, maxConcurrent: 2 }); + const pdf = heavyPdf(40, () => 2250); + const inFlight = [pdfRead(pdf, 'a.pdf'), pdfRead(pdf, 'b.pdf')]; + try { + const refused = await pdfRead(pdf, 'c.pdf').then( + () => undefined, + (error: unknown) => error, + ); + expect(refused).toBeInstanceOf(ReadFileExtractionBusyError); + expect(refused).toMatchObject({ + code: 'SERVICE_UNAVAILABLE', + status: 503, + maxConcurrent: 2, + retryAfterSeconds: 3, + message: 'The server is already reading 2 files, the most it reads at once, so this file was not read. Try again in about 3 seconds.', + }); + } finally { + await Promise.allSettled(inFlight); + } + for (const done of await Promise.all(inFlight)) expect(done).toMatchObject({ kind: 'text', text: pageTexts(40).join('\n\n') }); + // Both slots are free again, and the two workers wait in the pool. + expect(extractionWorkerPoolStats()).toEqual({ started: 2, idle: 2 }); + await expect(pdfRead(minimalPdf('Free'), 'd.pdf')).resolves.toMatchObject({ text: 'Free' }); + }); +}); + +/** + * [#34855] A worker stopped at its wall-clock ceiling before it sent back the + * first page or paragraph answers no text, with a reason saying the read + * stopped before any was read, never one calling the text partial. + * + * The worker is a stand-in that sends back exactly the progress a test + * scripts and then never answers, so the ceiling is what ends every read + * here and how far the read got is fixed by the script, never by how fast, or + * how loaded, this machine is: the clock decides when the read stops, never + * where. The progress messages are the real extractor's + * (`ExtractionProgress`), and the answer is built by the pool's own overrun + * path, as for a real worker. + */ +describe('a worker stopped at its wall-clock ceiling before the first page answers no text, never partial text', { timeout: 30_000 }, () => { + beforeEach(() => { + // Ceiling = 5 x 100 ms of real time: room for the scripted progress to + // arrive on a loaded runner, and every read here waits it out once. + configureReadFileExtraction({ cpuBudgetMs: 100, maxConcurrent: 1 }); + }); + afterEach(() => { + vi.restoreAllMocks(); + configureExtractionWorkerEntry(undefined); + configureReadFileExtraction(DEFAULTS); + }); + + /** A stand-in worker that sends `progress` back for every job, then never answers it. */ + function stalledWorker(progress: unknown[]): ExtractionWorkerEntry { + const source = [ + "import { parentPort } from 'node:worker_threads';", + `const progress = ${JSON.stringify(progress)};`, + "parentPort.on('message', () => {", + " for (const p of progress) parentPort.postMessage({ type: 'progress', progress: p });", + '});', + "parentPort.postMessage({ type: 'ready' });", + ].join('\n'); + return { url: new URL(`data:text/javascript,${encodeURIComponent(source)}`) }; + } + + async function readStopped(progress: unknown[], name: string, mimeType: string): Promise { + configureExtractionWorkerEntry(stalledWorker(progress)); + const result = await extractFileContent(new Uint8Array(Buffer.from('never read')), mimeType, name); + // The stalled worker is gone, not back in the pool: the ceiling ended it. + expect(extractionWorkerPoolStats().idle).toBe(0); + return result; + } + + it('a PDF opened but stopped before page 1, and one stopped before it opened, answer no text and say so', async () => { + const opened = await readStopped([{ kind: 'pdf-open', numPages: 120 }], 'heavy.pdf', 'application/pdf'); + expect(opened).toEqual({ + kind: 'none', + reason: 'Reading stopped at the CPU-time budget for one file (100 ms) before page 1 of 120 was read, so no text came back. ' + + 'Download the file with the link instead.', + }); + + const unopened = await readStopped([], 'heavy.pdf', 'application/pdf'); + expect(unopened).toEqual({ + kind: 'none', + reason: 'Reading stopped at the CPU-time budget for one file (100 ms) before page 1 was read, so no text came back. ' + + 'Download the file with the link instead.', + }); + }); + + it('a Word document stopped before its first paragraphs came back answers no text and says so', async () => { + const result = await readStopped([], 'long.docx', DOCX); + expect(result).toEqual({ + kind: 'none', + reason: 'Reading stopped at the CPU-time budget for one file (100 ms) before the first paragraph was read, so no text came back. ' + + 'Download the file with the link instead.', + }); + }); + + it('CONTROL: a stop after page 1, or after the first paragraphs, still answers that text as partial', async () => { + const pdf = await readStopped( + [{ kind: 'pdf-open', numPages: 120 }, { kind: 'pdf-page', text: 'Page 1 text' }], + 'heavy.pdf', + 'application/pdf', + ); + expect(pdf).toEqual({ + kind: 'text', + format: 'application/pdf', + text: 'Page 1 text', + truncated: true, + note: 'Reading stopped at the CPU-time budget for one file (100 ms) after page 1 of 120, so the text is partial. ' + + 'Download the file with the link for the rest.', + }); + + const word = await readStopped([{ kind: 'docx-paragraphs', text: 'P1\nP2\n', paragraphs: 64 }], 'long.docx', DOCX); + expect(word).toEqual({ + kind: 'text', + format: DOCX, + text: 'P1\nP2', + truncated: true, + note: 'Reading stopped at the CPU-time budget for one file (100 ms) after 64 paragraphs, so the text is partial. ' + + 'Download the file with the link for the rest.', + }); + }); +}); diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.ts index 7969d0abf45..201407726ed 100644 --- a/packages/core/tsup.config.ts +++ b/packages/core/tsup.config.ts @@ -5,7 +5,7 @@ import { defineConfig, type Options } from 'tsup'; import { dropSourcesContent } from '../../scripts/tsup-drop-sources-content.mjs'; /** - * `@objectstack/core` ships three entry points: + * `@objectstack/core` ships four entry points: * - `index.ts` — full microkernel (Node-only; pulls in plugin sandbox, * filesystem helpers, etc). * - `logger.ts` — tiny browser-safe logger reused by `@objectstack/client` @@ -14,8 +14,18 @@ import { dropSourcesContent } from '../../scripts/tsup-drop-sources-content.mjs' * - `egress.ts` — the outbound-request guard (Node-only; loads `undici`), kept * off the main entry so a kernel that makes no tenant-aimed requests never * loads the HTTP client. + * - `document-text.ts` — the bounded document text extractor (Node-only; + * loads `unpdf` on the first PDF), shared by MCP `read_file` and any AI + * service, kept off the main entry for the same reason. + * + * Plus one entry that is no export: `document-text-worker.ts`, the + * extractor's `worker_threads` entry. The pool starts it from + * `new URL('./document-text-worker.js' | '.cjs', import.meta.url)`, so it must + * sit beside `document-text` in both formats, carries its own copy of the + * extractor (`splitting: false`), and needs no declaration. */ -const ENTRY_NAMES = ['index', 'logger', 'egress'] as const; +const ENTRY_NAMES = ['index', 'logger', 'egress', 'document-text'] as const; +const WORKER_ENTRY = 'src/document-text-worker.ts'; const emitDts = !process.env.OS_SKIP_DTS; const shared: Options = { @@ -64,9 +74,18 @@ const shared: Options = { export default defineConfig([ { ...shared, + entry: [...shared.entry as string[], WORKER_ENTRY], clean: true, dts: false, format: ['esm', 'cjs'], + // LOAD-BEARING for the worker pool: without it esbuild EMPTIES + // `import.meta` in the CJS build, the pool cannot find the worker entry + // beside `document-text.cjs`, and every CJS caller extracts in-process. + // `shims` rewrites `import.meta.url` there to a `__filename`-derived URL + // (the same reason `packages/mcp/tsup.config.ts` carries it). Need-based: + // nothing else in this package reads `import.meta`, `__dirname` or + // `__filename`, so the other entries are untouched. + shims: true, onSuccess: emitDts ? async () => { await Promise.all( diff --git a/packages/drivers/driver-memory/vitest.config.ts b/packages/drivers/driver-memory/vitest.config.ts index 17acfb243ec..47910563541 100644 --- a/packages/drivers/driver-memory/vitest.config.ts +++ b/packages/drivers/driver-memory/vitest.config.ts @@ -24,6 +24,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, // Subpath BEFORE the bare package, same prefix-match reason: `./node` is a // published subpath served by a FILE (`types/src/node.ts` — the node-only slice diff --git a/packages/drivers/driver-sql/vitest.config.ts b/packages/drivers/driver-sql/vitest.config.ts index 52f797f8695..c94a9664103 100644 --- a/packages/drivers/driver-sql/vitest.config.ts +++ b/packages/drivers/driver-sql/vitest.config.ts @@ -84,6 +84,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, ], }, diff --git a/packages/mcp/package.json b/packages/mcp/package.json index cd66058d1a6..e0c2d34aec1 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -35,7 +35,6 @@ "@objectstack/rest": "workspace:*", "@objectstack/spec": "workspace:*", "@objectstack/types": "workspace:*", - "unpdf": "1.9.1", "zod": "^4.6.6" }, "devDependencies": { @@ -47,6 +46,7 @@ "@objectstack/service-record-context": "workspace:*", "@types/node": "^26.6.5", "typescript": "^6.0.3", + "unpdf": "1.9.1", "vitest": "^4.1.11" }, "keywords": [ diff --git a/packages/mcp/src/file-content.ts b/packages/mcp/src/file-content.ts index 74a4fbf25dd..7dc38338298 100644 --- a/packages/mcp/src/file-content.ts +++ b/packages/mcp/src/file-content.ts @@ -1,290 +1,39 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -import { inflateRawSync } from 'node:zlib'; - -import { runExtractionInWorker } from './file-extraction-pool.js'; +import { + READ_FILE_PDF_MAX_PAGES, + READ_FILE_TEXT_MAX_CHARS, + ReadFileExtractionBusyError, + activeReadFileExtractionLimits, + extractFileContent, + type ExtractedContent, +} from '@objectstack/core/document-text'; /** * [#30892] What `read_file` hands an agent from a file a record carries: the * file's words, or the image itself, beside its size, the cap that applied * and a short-lived download link. * - * ## The caps, each a named constant + * The words come from the shared document extractor, + * `@objectstack/core/document-text`: its caps (100,000 characters, 200 PDF + * pages, the inflated `.docx` body, the image size), its two host bounds + * (`OS_MCP_READ_FILE_CPU_BUDGET_MS`, `OS_MCP_READ_FILE_MAX_CONCURRENT`; the + * plugin's `init` reads them at boot) and its worker pool live there, shared + * with every other caller in the process. This module owns what is + * `read_file`'s alone: * * - {@link READ_FILE_MAX_BYTES}: the largest file whose bytes are read at * all. A larger file answers its size, the cap and the link, and nothing - * is extracted. Every extractor below runs only on bytes already within it. - * - {@link READ_FILE_TEXT_MAX_CHARS}: the most characters of text one answer - * carries; past it the text is cut and the answer says so. - * - {@link READ_FILE_PDF_MAX_PAGES}: the most PDF pages read. - * - {@link READ_FILE_DOCX_XML_MAX_BYTES}: the most bytes a `.docx` body may - * inflate to (a compressed body can expand far past its stored size). - * - * ## The extractors - * - * - Text (`text/*`, JSON, XML, CSV, Markdown, YAML, SVG): decoded as UTF-8. - * - Images (PNG, JPEG, GIF, WebP): returned as an MCP image block, up to - * {@link READ_FILE_IMAGE_MAX_BYTES}. - * - PDF: `unpdf` 1.9.1 (pdf.js), loaded by dynamic import on the first PDF - * read, with pdf.js's `eval` path off (`isEvalSupported: false`) and its - * console output off. A file pdf.js cannot open answers a sentence, never a - * throw out of the tool. - * - Word (`.docx`): the ZIP's `word/document.xml`, inflated with `node:zlib` - * under {@link READ_FILE_DOCX_XML_MAX_BYTES}, its paragraphs as lines. - * - * Anything else answers its size and the link, and says it has no text this - * tool reads. - * - * ## Off the request thread, under two host bounds (ADR-0102 D1) - * - * PDF and Word extraction runs on a bounded `worker_threads` pool - * (`file-extraction-pool.ts`, entry `file-extraction-worker.ts`), so the - * request thread keeps serving every other request while a file is read (the - * #31100 ruling, phase 2). Two host-configured bounds keep one caller's files - * from holding the process (phase 1): - * - * - a CPU-time budget per extraction ({@link READ_FILE_CPU_BUDGET_MS_ENV}, - * default {@link READ_FILE_CPU_BUDGET_MS_DEFAULT}), checked between PDF - * pages and between Word paragraphs, never mid-page. In a worker it is the - * worker thread's own CPU time; in-process it is process CPU time - * (`process.cpuUsage()` deltas), which charges an extraction for work - * interleaved with it, so the error is to stop early, never late. Out of - * budget, the answer is the text read so far, `truncated: true`, and a note - * naming the budget and the download link. A worker that does not reach a - * checkpoint within {@link READ_FILE_WALL_CEILING_MULTIPLE} budgets of wall - * time is terminated and replaced, and the answer is the same shape over the - * pages it had already sent back. - * - a process-wide cap on extractions in flight - * ({@link READ_FILE_MAX_CONCURRENT_ENV}, default - * {@link READ_FILE_MAX_CONCURRENT_DEFAULT}), which is also the pool's size. - * Over it, the call is refused on the request thread at once, before any - * worker is touched, never queued: {@link ReadFileExtractionBusyError}, a - * retryable `SERVICE_UNAVAILABLE`. - * - * A host where the worker cannot start (one that bundled this package into a - * single file, so the worker entry is not beside it) extracts in-process under - * the same two bounds, said once at `warn` with the reason. - * - * Both are read once at boot ({@link configureReadFileExtraction}, called by - * the plugin's `init`) and a malformed value is a boot fault naming the - * variable, never a bound that is silently off. + * is extracted. + * - the file bridge ({@link McpFileBridge}) the runtime implements over the + * storage plugin, and + * - the answer ({@link renderReadFile}): the file's facts as JSON, then its + * text or its image. */ /** The largest file `read_file` reads the bytes of: 10 MiB. */ export const READ_FILE_MAX_BYTES = 10 * 1024 * 1024; -/** The most characters of extracted text one `read_file` answer carries. */ -export const READ_FILE_TEXT_MAX_CHARS = 100_000; - -/** The most PDF pages `read_file` reads. */ -export const READ_FILE_PDF_MAX_PAGES = 200; - -/** The most bytes a `.docx` body (`word/document.xml`) may inflate to: 32 MiB. */ -export const READ_FILE_DOCX_XML_MAX_BYTES = 32 * 1024 * 1024; - -/** - * The largest image returned as an image block: 5 MiB, the most an MCP client - * passes to a model as one image. A larger image answers its link. - */ -export const READ_FILE_IMAGE_MAX_BYTES = 5 * 1024 * 1024; - -/** The host variable naming the CPU-time budget of one PDF or Word extraction, in milliseconds. */ -export const READ_FILE_CPU_BUDGET_MS_ENV = 'OS_MCP_READ_FILE_CPU_BUDGET_MS'; - -/** The host variable naming how many PDF or Word extractions may run at once in the process. */ -export const READ_FILE_MAX_CONCURRENT_ENV = 'OS_MCP_READ_FILE_MAX_CONCURRENT'; - -/** - * 2000 ms of CPU per extraction. Well above what any file within the other - * caps was measured to take (a 9 MiB, 200-page PDF dense in drawing operators: - * about 300–650 ms), so a self-hosted deployment reads every such file in full - * as before; it stops only a file built to take seconds. - */ -export const READ_FILE_CPU_BUDGET_MS_DEFAULT = 2000; - -/** - * 4 extractions in flight. More than one person's assistant reads at once on a - * self-hosted deployment, and few enough that a burst holds the process for at - * most four budgets. - */ -export const READ_FILE_MAX_CONCURRENT_DEFAULT = 4; - -/** - * A worker's wall-clock ceiling per extraction, as a multiple of the CPU - * budget: 5, so 10 s under the default budget. A worker checks its CPU budget - * between pages, so the ceiling only catches one that does not reach a - * checkpoint (a single page that runs long). Five is the share of one core a - * worker still gets when every slot of the default pool (4) and the request - * thread run on a single core: under that load a worker that is still - * reaching its checkpoints has used its budget before the ceiling, so the - * ceiling never cuts a read the budget would have let finish. - */ -export const READ_FILE_WALL_CEILING_MULTIPLE = 5; - -/** The two host bounds on PDF and Word extraction. */ -export interface ReadFileExtractionLimits { - /** CPU time one extraction may use, in milliseconds, checked between pages or paragraphs. */ - cpuBudgetMs: number; - /** Extractions that may run at once in the process, and the size of the worker pool; one more is refused. */ - maxConcurrent: number; -} - -function readPositiveIntegerVar(env: Record, name: string, fallback: number): number { - const raw = env[name]; - if (raw == null || raw.trim() === '') return fallback; - const text = raw.trim(); - const n = Number(text); - // A typo here must not be the thing that switches the bound off: an - // unreadable value fails loudly instead of reading as unset. - if (!/^\d+$/.test(text) || !Number.isSafeInteger(n) || n <= 0) { - throw new Error( - `${name} must be a positive integer; got ${JSON.stringify(raw)}. ` - + `Unset it for the default (${fallback}), or set a whole number.`, - ); - } - return n; -} - -/** - * The host's bounds on PDF and Word extraction, from `env` (default - * `process.env`). An unset variable takes its default; a value that is not a - * positive integer throws, naming the variable. - */ -export function resolveReadFileExtractionLimits( - env: Record = typeof process !== 'undefined' ? process.env : {}, -): ReadFileExtractionLimits { - return { - cpuBudgetMs: readPositiveIntegerVar(env, READ_FILE_CPU_BUDGET_MS_ENV, READ_FILE_CPU_BUDGET_MS_DEFAULT), - maxConcurrent: readPositiveIntegerVar(env, READ_FILE_MAX_CONCURRENT_ENV, READ_FILE_MAX_CONCURRENT_DEFAULT), - }; -} - -let extractionLimits: ReadFileExtractionLimits | undefined; - -/** - * Fix the bounds every extraction in this process runs under: `limits`, or - * the host's ({@link resolveReadFileExtractionLimits}). The plugin's `init` - * calls it once, so a malformed variable fails the boot; a process that never - * calls it reads the host's on its first extraction. - */ -export function configureReadFileExtraction(limits?: ReadFileExtractionLimits): ReadFileExtractionLimits { - extractionLimits = limits ?? resolveReadFileExtractionLimits(); - return extractionLimits; -} - -function activeExtractionLimits(): ReadFileExtractionLimits { - extractionLimits ??= resolveReadFileExtractionLimits(); - return extractionLimits; -} - -/** PDF and Word extractions running now, process-wide. */ -let extractionsInFlight = 0; - -/** - * The refusal of an extraction over the process-wide cap: ADR-0112 - * `SERVICE_UNAVAILABLE` (503), retryable. The process is busy reading other - * files, which says nothing about this caller or this file, so the answer is - * "try again shortly", with the seconds to wait. - */ -export class ReadFileExtractionBusyError extends Error { - readonly code = 'SERVICE_UNAVAILABLE' as const; - readonly status = 503; - constructor( - readonly maxConcurrent: number, - /** Seconds to wait before retrying: about one extraction's budget. */ - readonly retryAfterSeconds: number, - ) { - super( - `The server is already reading ${maxConcurrent} files, the most it reads at once, so this file was not read. ` - + `Try again in about ${retryAfterSeconds} second${retryAfterSeconds === 1 ? '' : 's'}.`, - ); - this.name = 'ReadFileExtractionBusyError'; - } -} - -/** CPU time spent since a start reading, against one extraction's budget. */ -export interface CpuBudget { - readonly budgetMs: number; - /** True once the extraction has used its budget. */ - spent(): boolean; -} - -/** The in-process budget: process CPU time, which stops early, never late. */ -function startCpuBudget(budgetMs: number): CpuBudget { - const start = process.cpuUsage(); - return { - budgetMs, - spent() { - const used = process.cpuUsage(start); - return (used.user + used.system) / 1000 >= budgetMs; - }, - }; -} - -/** - * Where reading stopped at the CPU budget: `after` the pages or paragraphs - * read ("page 3 of 120", "64 paragraphs"), or `before` the first one ("page 1 - * of 120", "the first paragraph") when the stop came before any was read. - */ -type BudgetStop = { budgetMs: number; after: string } | { budgetMs: number; before: string }; - -/** - * The sentence an answer cut by the CPU budget carries. It calls the text - * partial only when some text came back (`gotText`): a stop before the first - * page or paragraph says it stopped before any was read, and a stop after - * parts that held no text says none was found, so an answer with no text - * never claims to hold part of it. - */ -function cpuBudgetNote(stop: BudgetStop, gotText: boolean): string { - const stopped = `Reading stopped at the CPU-time budget for one file (${stop.budgetMs} ms)`; - if ('before' in stop) { - return `${stopped} before ${stop.before} was read, so no text came back. Download the file with the link instead.`; - } - return gotText - ? `${stopped} after ${stop.after}, so the text is partial. Download the file with the link for the rest.` - : `${stopped} after ${stop.after}, and no text was found in what was read. Download the file with the link instead.`; -} - -/** The images an MCP image block carries; any other image answers its link. */ -const INLINE_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']); - -const DOCX_TYPE = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; - -/** The media types read as text, beside every `text/*`. */ -const TEXT_TYPES = new Set([ - 'application/json', - 'application/ld+json', - 'application/xml', - 'application/x-yaml', - 'application/yaml', - 'application/csv', - 'application/javascript', - 'application/sql', - 'image/svg+xml', -]); - -/** The media type a name's extension stands for, for a file stored with none (or as bytes). */ -const TYPE_BY_EXTENSION: Record = { - pdf: 'application/pdf', - docx: DOCX_TYPE, - txt: 'text/plain', - md: 'text/markdown', - csv: 'text/csv', - tsv: 'text/tab-separated-values', - json: 'application/json', - xml: 'application/xml', - yaml: 'application/yaml', - yml: 'application/yaml', - html: 'text/html', - htm: 'text/html', - svg: 'image/svg+xml', - png: 'image/png', - jpg: 'image/jpeg', - jpeg: 'image/jpeg', - gif: 'image/gif', - webp: 'image/webp', -}; - /** The file the bridge read, as `read_file` renders it. */ export interface McpReadFile { fileId: string; @@ -370,501 +119,6 @@ export interface McpFileBridge { /** One MCP tool-result content block `read_file` answers with. */ export type FileContentBlock = { type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }; -/** The content a file yields: its text, its image, or a sentence on why there is neither. */ -export type ExtractedContent = - | { - kind: 'text'; - text: string; - truncated: boolean; - format: string; - /** Why the text is cut, when it was cut by something other than the length and page caps. */ - note?: string; - } - | { kind: 'image'; data: string; mimeType: string } - | { kind: 'none'; reason: string }; - -/** The media type to read the file as: the stored one, else the name's extension, lower-cased and without parameters. */ -export function effectiveMimeType(mimeType: string | null, name: string): string { - const stored = (mimeType ?? '').split(';')[0].trim().toLowerCase(); - if (stored && stored !== 'application/octet-stream') return stored; - const ext = name.includes('.') ? name.split('.').pop()!.toLowerCase() : ''; - return TYPE_BY_EXTENSION[ext] ?? (stored || 'application/octet-stream'); -} - -function isTextType(type: string): boolean { - return type.startsWith('text/') || TEXT_TYPES.has(type) || type.endsWith('+json') || type.endsWith('+xml'); -} - -function bounded(text: string): { text: string; truncated: boolean } { - return text.length > READ_FILE_TEXT_MAX_CHARS - ? { text: text.slice(0, READ_FILE_TEXT_MAX_CHARS), truncated: true } - : { text, truncated: false }; -} - -/** - * The content of a file's bytes, by its media type. A file an extractor cannot - * read answers `{ kind: 'none' }` with the sentence. Throws one thing: a PDF or - * Word file met while the process already runs as many extractions as the host - * allows is refused with {@link ReadFileExtractionBusyError}. - */ -export async function extractFileContent(bytes: Uint8Array, mimeType: string | null, name: string): Promise { - const type = effectiveMimeType(mimeType, name); - if (INLINE_IMAGE_TYPES.has(type)) { - if (bytes.byteLength > READ_FILE_IMAGE_MAX_BYTES) { - return { - kind: 'none', - reason: `The image is ${bytes.byteLength} bytes, over the ${READ_FILE_IMAGE_MAX_BYTES}-byte cap for showing an image. Download it with the link instead.`, - }; - } - return { kind: 'image', data: Buffer.from(bytes).toString('base64'), mimeType: type }; - } - if (isTextType(type)) { - return { kind: 'text', format: type, ...bounded(new TextDecoder('utf-8').decode(bytes)) }; - } - if (type === 'application/pdf') return withExtractionSlot('pdf', bytes); - if (type === DOCX_TYPE) return withExtractionSlot('docx', bytes); - return { - kind: 'none', - reason: `A ${type} file has no text read_file can read. Download it with the link instead.`, - }; -} - -/** The two documents read by extraction rather than decoding. */ -export type DocumentKind = 'pdf' | 'docx'; - -/** - * Run one document extraction inside the process-wide cap. Over the cap it is - * refused at once, on this thread, before any worker is touched, never - * queued. Within it, the extraction runs on a pool worker under the CPU - * budget and the wall-clock ceiling; where no worker can start, in-process - * under the CPU budget. The slot is released in `finally`, so an extraction - * that throws (or whose worker crashed) frees it too. - */ -async function withExtractionSlot(kind: DocumentKind, bytes: Uint8Array): Promise { - const limits = activeExtractionLimits(); - if (extractionsInFlight >= limits.maxConcurrent) { - throw new ReadFileExtractionBusyError(limits.maxConcurrent, Math.max(1, Math.ceil(limits.cpuBudgetMs / 1000))); - } - extractionsInFlight++; - try { - const outcome = await runExtractionInWorker( - { kind, bytes, cpuBudgetMs: limits.cpuBudgetMs }, - { poolSize: limits.maxConcurrent, ceilingMs: limits.cpuBudgetMs * READ_FILE_WALL_CEILING_MULTIPLE }, - ); - if (outcome.status === 'done') return outcome.result; - if (outcome.status === 'overrun') return stoppedExtractionAnswer(kind, outcome.progress, limits.cpuBudgetMs); - return await extractDocument(kind, bytes, startCpuBudget(limits.cpuBudgetMs)); - } finally { - extractionsInFlight--; - } -} - -/** - * What an extraction has read so far, sent as it reads, so a worker stopped - * part-way still answers the text it had already sent back. - */ -export type ExtractionProgress = - /** The PDF opened, with this many pages. */ - | { kind: 'pdf-open'; numPages: number } - /** The next PDF page's text, trimmed, in page order. */ - | { kind: 'pdf-page'; text: string } - /** The Word body's text since the last report, as read, and the paragraphs read in all. */ - | { kind: 'docx-paragraphs'; text: string; paragraphs: number }; - -/** A sink an extractor reports its progress to; in-process there is none. */ -export type ProgressSink = (progress: ExtractionProgress) => void; - -/** One document's text, read under `budget`, reporting progress to `onProgress` as it goes. */ -export async function extractDocument( - kind: DocumentKind, - bytes: Uint8Array, - budget: CpuBudget, - onProgress?: ProgressSink, -): Promise { - return kind === 'pdf' ? extractPdfText(bytes, budget, onProgress) : extractDocxText(bytes, budget, onProgress); -} - -/** - * The answer of an extraction stopped part-way at the wall-clock ceiling: the - * text its progress carried, `truncated: true`, and the CPU-budget note, the - * same shape an extraction stopped at its budget answers. A stop before the - * first page or paragraph came back answers no text, with a note saying the - * read stopped before any was read. - */ -export function stoppedExtractionAnswer(kind: DocumentKind, progress: readonly ExtractionProgress[], budgetMs: number): ExtractedContent { - if (kind === 'pdf') { - let numPages: number | undefined; - const pages: string[] = []; - for (const p of progress) { - if (p.kind === 'pdf-open') numPages = p.numPages; - else if (p.kind === 'pdf-page') pages.push(p.text); - } - const of = numPages === undefined ? '' : ` of ${numPages}`; - const stop: BudgetStop = pages.length === 0 - ? { budgetMs, before: `page 1${of}` } - : { budgetMs, after: `page ${pages.length}${of}` }; - return pdfAnswer(pages, numPages ?? pages.length, stop); - } - let text = ''; - let paragraphs = 0; - for (const p of progress) { - if (p.kind !== 'docx-paragraphs') continue; - text += p.text; - paragraphs = p.paragraphs; - } - const stop: BudgetStop = paragraphs === 0 - ? { budgetMs, before: 'the first paragraph' } - : { budgetMs, after: `${paragraphs} paragraphs` }; - return docxAnswer(text, false, stop); -} - -// ── PDF ────────────────────────────────────────────────────────────────── - -/** The slice of pdf.js's text item a page's text is read from. */ -interface PdfTextItem { - str?: unknown; - hasEOL?: unknown; -} - -/** The slice of pdf.js's document proxy read here. */ -interface PdfDocument { - numPages: number; - getPage(n: number): Promise<{ getTextContent(): Promise<{ items: PdfTextItem[] }>; cleanup?(): unknown }>; - destroy(): Promise; -} - -/** The slice of `unpdf` used, typed here so pdf.js's own types stay out of this package's surface. */ -interface UnpdfModule { - getDocumentProxy(data: Uint8Array, options?: Record): Promise; -} - -let unpdfModule: Promise | undefined; - -/** `unpdf`, imported on the first PDF read, never at load. */ -function loadUnpdf(): Promise { - unpdfModule ??= import('unpdf').then((m) => m as unknown as UnpdfModule); - return unpdfModule; -} - -/** A one-page PDF reading "warm", for {@link preloadPdfReader}. */ -function warmUpPdf(): Uint8Array { - const stream = 'BT /F1 12 Tf 72 720 Td (warm) Tj ET'; - const objects = [ - '<< /Type /Catalog /Pages 2 0 R >>', - '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', - '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>', - `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`, - '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', - ]; - let out = '%PDF-1.4\n'; - const offsets: number[] = []; - objects.forEach((body, i) => { - offsets.push(out.length); - out += `${i + 1} 0 obj\n${body}\nendobj\n`; - }); - const xref = out.length; - out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`; - for (const o of offsets) out += `${String(o).padStart(10, '0')} 00000 n \n`; - out += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; - return new Uint8Array(Buffer.from(out, 'latin1')); -} - -/** - * Make the PDF reader ready now rather than on the first PDF: load `unpdf` - * and read one page of a built-in one-page PDF, which is when pdf.js sets up - * its in-thread worker and loads the rest of itself. A pool worker does this - * before it says it is ready, so that one-time cost (hundreds of milliseconds - * on a busy host) belongs to the worker's start and is never charged to a - * job's wall-clock ceiling. Charged to a job, a small ceiling could stop a - * cold worker's first read every time, and its replacement would start cold - * again. A failure here is left to the first PDF read, which answers its - * could-not-read sentence as before. - */ -export async function preloadPdfReader(): Promise { - try { - const unpdf = await loadUnpdf(); - const doc = await unpdf.getDocumentProxy(warmUpPdf(), pdfOpenOptions()); - try { - const page = await doc.getPage(1); - await page.getTextContent(); - page.cleanup?.(); - } finally { - await doc.destroy(); - } - } catch { - // Left to the first PDF read. - } -} - -/** How every PDF is opened: pdf.js's `eval` path off, its console output off, no font loading. */ -function pdfOpenOptions(): Record { - return { - isEvalSupported: false, - // Errors only: pdf.js warns through `console.log`, which on a stdio - // transport is the protocol stream. - verbosity: 0, - disableFontFace: true, - useSystemFonts: false, - }; -} - -/** - * A PDF's answer from the pages read, in order: their text joined, cut at the - * length cap, `truncated` when fewer than `numPages` were read, and the budget - * note when reading stopped at the budget (which always truncates). - */ -function pdfAnswer(parts: readonly string[], numPages: number, stop: BudgetStop | undefined): ExtractedContent { - const joined = parts.join('\n\n').trim(); - if (!joined) { - return { - kind: 'none', - reason: stop - ? cpuBudgetNote(stop, false) - : 'This PDF has no text layer (it may be a scan), so there is no text to read. Download it with the link instead.', - }; - } - const { text, truncated } = bounded(joined); - return { - kind: 'text', - format: 'application/pdf', - text, - truncated: truncated || parts.length < numPages || stop !== undefined, - ...(stop !== undefined ? { note: cpuBudgetNote(stop, true) } : {}), - }; -} - -async function extractPdfText(bytes: Uint8Array, budget: CpuBudget, onProgress?: ProgressSink): Promise { - let doc: PdfDocument; - try { - const unpdf = await loadUnpdf(); - // pdf.js keeps the buffer it is handed; it gets a copy. - doc = await unpdf.getDocumentProxy(new Uint8Array(bytes), pdfOpenOptions()); - } catch (err) { - const passworded = (err as { name?: unknown })?.name === 'PasswordException'; - return { - kind: 'none', - reason: passworded - ? 'This PDF is password-protected, so its text cannot be read. Download it with the link instead.' - : 'This file could not be read as a PDF: it is damaged or not a PDF. Download it with the link instead.', - }; - } - try { - onProgress?.({ kind: 'pdf-open', numPages: doc.numPages }); - const pages = Math.min(doc.numPages, READ_FILE_PDF_MAX_PAGES); - const parts: string[] = []; - let length = 0; - let read = 0; - let outOfBudget = false; - for (let n = 1; n <= pages && length <= READ_FILE_TEXT_MAX_CHARS; n++) { - // Between pages, never mid-page: the first page is always read. - if (n > 1 && budget.spent()) { - outOfBudget = true; - break; - } - const page = await doc.getPage(n); - const content = await page.getTextContent(); - let pageText = ''; - for (const item of content.items) { - if (typeof item.str !== 'string') continue; - pageText += item.str + (item.hasEOL === true ? '\n' : ''); - } - page.cleanup?.(); - parts.push(pageText.trim()); - onProgress?.({ kind: 'pdf-page', text: parts[parts.length - 1] }); - length += pageText.length + 2; - read = n; - } - const stop = outOfBudget ? { budgetMs: budget.budgetMs, after: `page ${read} of ${doc.numPages}` } : undefined; - return pdfAnswer(parts, doc.numPages, stop); - } catch { - return { - kind: 'none', - reason: 'This PDF could not be read to the end: it is damaged. Download it with the link instead.', - }; - } finally { - try { - await doc.destroy(); - } catch { - // Releasing the document is best-effort; the answer is already decided. - } - } -} - -// ── Word (.docx) ───────────────────────────────────────────────────────── - -const ZIP_END_OF_CENTRAL_DIRECTORY = 0x06054b50; -const ZIP_CENTRAL_DIRECTORY_HEADER = 0x02014b50; -const ZIP_LOCAL_FILE_HEADER = 0x04034b50; -/** The end record is 22 bytes plus a comment of at most 65535. */ -const ZIP_END_SEARCH_SPAN = 22 + 0xffff; -const DOCX_BODY_ENTRY = 'word/document.xml'; - -const NOT_A_DOCX = - 'This file could not be read as a Word document: it is damaged or not a .docx. Download it with the link instead.'; - -/** The stored bytes of one ZIP entry and how they are compressed, or `null` when the archive has no such entry. */ -function zipEntry(buf: Buffer, wanted: string): { method: number; data: Buffer } | null { - const searchFrom = Math.max(0, buf.length - ZIP_END_SEARCH_SPAN); - let end = -1; - for (let i = buf.length - 22; i >= searchFrom; i--) { - if (buf.readUInt32LE(i) === ZIP_END_OF_CENTRAL_DIRECTORY) { - end = i; - break; - } - } - if (end < 0) throw new Error('no end of central directory'); - const entries = buf.readUInt16LE(end + 10); - let at = buf.readUInt32LE(end + 16); - for (let k = 0; k < entries; k++) { - if (at + 46 > buf.length || buf.readUInt32LE(at) !== ZIP_CENTRAL_DIRECTORY_HEADER) throw new Error('bad central directory'); - const method = buf.readUInt16LE(at + 10); - const compressedSize = buf.readUInt32LE(at + 20); - const nameLength = buf.readUInt16LE(at + 28); - const extraLength = buf.readUInt16LE(at + 30); - const commentLength = buf.readUInt16LE(at + 32); - const localOffset = buf.readUInt32LE(at + 42); - const name = buf.toString('utf8', at + 46, at + 46 + nameLength); - if (name === wanted) { - if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== ZIP_LOCAL_FILE_HEADER) { - throw new Error('bad local header'); - } - const start = localOffset + 30 + buf.readUInt16LE(localOffset + 26) + buf.readUInt16LE(localOffset + 28); - if (start + compressedSize > buf.length) throw new Error('truncated entry'); - return { method, data: buf.subarray(start, start + compressedSize) }; - } - at += 46 + nameLength + extraLength + commentLength; - } - return null; -} - -const XML_ENTITIES: Record = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }; - -function decodeXmlEntities(text: string): string { - return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);/g, (whole, body: string) => { - if (body.startsWith('#x')) return safeCodePoint(parseInt(body.slice(2), 16), whole); - if (body.startsWith('#')) return safeCodePoint(parseInt(body.slice(1), 10), whole); - return XML_ENTITIES[body] ?? whole; - }); -} - -function safeCodePoint(code: number, fallback: string): string { - return Number.isInteger(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : fallback; -} - -const DOCX_PARAGRAPH_END = ''; - -/** How many `.docx` paragraphs are read between two reads of the CPU clock. */ -const DOCX_BUDGET_CHECK_EVERY = 64; - -/** One stretch of a `.docx` body as text: tabs and breaks kept, a paragraph end as a line end, every other tag dropped. */ -function docxChunkText(xml: string): string { - const text = xml - .replace(/]*\/>/g, '\t') - .replace(/]*\/>/g, '\n') - .replace(/<\/w:p>/g, '\n') - .replace(/<[^>]+>/g, ''); - return decodeXmlEntities(text); -} - -/** - * A `.docx` body's text: paragraphs as lines, tabs and breaks kept, every - * other tag dropped. Read paragraph by paragraph, stopping at a paragraph end - * once the CPU budget is spent; `paragraphs` counts those read and `complete` - * says whether the body was read to its end. - */ -function docxXmlText( - xml: string, - budget: CpuBudget, - onProgress?: ProgressSink, -): { text: string; complete: boolean; outOfBudget: boolean; paragraphs: number } { - const parts: string[] = []; - let reported = 0; - let at = 0; - let paragraphs = 0; - let outOfBudget = false; - while (at < xml.length) { - const end = xml.indexOf(DOCX_PARAGRAPH_END, at); - const next = end < 0 ? xml.length : end + DOCX_PARAGRAPH_END.length; - parts.push(docxChunkText(xml.slice(at, next))); - at = next; - if (end >= 0) paragraphs++; - if (at >= xml.length) break; - // Between paragraphs, never mid-paragraph; every DOCX_BUDGET_CHECK_EVERY - // paragraphs, so the clock read stays a rounding error on a long body. - if (paragraphs % DOCX_BUDGET_CHECK_EVERY === 0) { - if (onProgress) { - onProgress({ kind: 'docx-paragraphs', text: parts.slice(reported).join(''), paragraphs }); - reported = parts.length; - } - if (budget.spent()) { - outOfBudget = true; - break; - } - } - } - return { - text: parts.join(''), - complete: at >= xml.length, - outOfBudget, - paragraphs, - }; -} - -/** - * A Word document's answer from its body's text as read: blank runs folded, - * cut at the length cap, `truncated` when the body was not read to its end, - * and the budget note when reading stopped at the budget. - */ -function docxAnswer(read: string, complete: boolean, stop: BudgetStop | undefined): ExtractedContent { - const whole = read.replace(/\n{3,}/g, '\n\n').trim(); - if (!whole) return { kind: 'none', reason: stop ? cpuBudgetNote(stop, false) : 'This Word document has no text.' }; - const { text, truncated } = bounded(whole); - return { - kind: 'text', - format: DOCX_TYPE, - text, - truncated: truncated || !complete, - ...(stop !== undefined ? { note: cpuBudgetNote(stop, true) } : {}), - }; -} - -function extractDocxText(bytes: Uint8Array, budget: CpuBudget, onProgress?: ProgressSink): ExtractedContent { - const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); - let entry: { method: number; data: Buffer } | null; - try { - entry = zipEntry(buf, DOCX_BODY_ENTRY); - } catch { - return { kind: 'none', reason: NOT_A_DOCX }; - } - if (!entry) return { kind: 'none', reason: NOT_A_DOCX }; - let xml: Buffer; - try { - if (entry.method === 0) xml = entry.data; - else if (entry.method === 8) xml = inflateRawSync(entry.data, { maxOutputLength: READ_FILE_DOCX_XML_MAX_BYTES }); - else return { kind: 'none', reason: NOT_A_DOCX }; - } catch (err) { - const tooLarge = (err as { code?: unknown })?.code === 'ERR_BUFFER_TOO_LARGE' || err instanceof RangeError; - return { - kind: 'none', - reason: tooLarge - ? `This Word document's text expands past ${READ_FILE_DOCX_XML_MAX_BYTES} bytes, more than read_file reads. Download it with the link instead.` - : NOT_A_DOCX, - }; - } - if (xml.length > READ_FILE_DOCX_XML_MAX_BYTES) { - return { - kind: 'none', - reason: `This Word document's text is more than ${READ_FILE_DOCX_XML_MAX_BYTES} bytes, more than read_file reads. Download it with the link instead.`, - }; - } - // The inflate above is one call and cannot stop part-way; its output is - // bounded by READ_FILE_DOCX_XML_MAX_BYTES. The budget is checked between - // the body's paragraphs. - const read = docxXmlText(xml.toString('utf8'), budget, onProgress); - const stop = read.outOfBudget ? { budgetMs: budget.budgetMs, after: `${read.paragraphs} paragraphs` } : undefined; - return docxAnswer(read.text, read.complete, stop); -} - // ── The answer ─────────────────────────────────────────────────────────── /** @@ -876,7 +130,7 @@ function extractDocxText(bytes: Uint8Array, budget: CpuBudget, onProgress?: Prog export async function renderReadFile(file: McpReadFile): Promise { // Outside the extractors' net: a host variable that is malformed fails the // call naming the variable, never reads as "could not be read". - activeExtractionLimits(); + activeReadFileExtractionLimits(); const facts: Record = { fileId: file.fileId, name: file.name, diff --git a/packages/mcp/src/mcp-file-tools.test.ts b/packages/mcp/src/mcp-file-tools.test.ts index 2ed2290c688..ca98007f2e8 100644 --- a/packages/mcp/src/mcp-file-tools.test.ts +++ b/packages/mcp/src/mcp-file-tools.test.ts @@ -16,8 +16,6 @@ */ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; -import { createRequire } from 'node:module'; -import { pathToFileURL } from 'node:url'; import { crc32, deflateRawSync } from 'node:zlib'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { @@ -36,26 +34,22 @@ import { type McpDataBridge, type McpFederationBridge, } from './mcp-http-tools.js'; +import { READ_FILE_MAX_BYTES, type McpFileBridge, type McpReadFile } from './file-content.js'; +// The shared extractor `read_file` reads through (aliased to its source in +// this package's vitest config). Its worker-pool pins live beside the pool, +// in `packages/core/src/document-text.worker-pool.test.ts`. import { READ_FILE_CPU_BUDGET_MS_DEFAULT, READ_FILE_CPU_BUDGET_MS_ENV, READ_FILE_DOCX_XML_MAX_BYTES, READ_FILE_IMAGE_MAX_BYTES, - READ_FILE_MAX_BYTES, READ_FILE_MAX_CONCURRENT_DEFAULT, READ_FILE_MAX_CONCURRENT_ENV, ReadFileExtractionBusyError, configureReadFileExtraction, extractFileContent, resolveReadFileExtractionLimits, - type McpFileBridge, - type McpReadFile, -} from './file-content.js'; -import { - configureExtractionWorkerEntry, - extractionWorkerPoolStats, - type ExtractionWorkerEntry, -} from './file-extraction-pool.js'; +} from '@objectstack/core/document-text'; import { renderSkillMarkdown } from './skill-md.js'; /** @@ -947,382 +941,3 @@ describe('read_file bounds PDF and Word extraction by the host\'s CPU budget and expect(textOf(next.content[1])).toBe('After the throw'); }); }); - -/** - * [#31828] The same `read_file` answers, read on the extraction worker pool: - * the request thread keeps running while a heavy PDF is read; a worker past - * its wall-clock ceiling is terminated, the pages it sent back are the - * answer, and the next call gets a fresh worker; a crashed worker fails only - * its own call; the over-cap refusal is decided on the request thread as - * before; and where no worker can start, the in-process answer is the same. - * - * Under vitest the pool's own module is the TypeScript source, which has no - * built worker beside it, so every describe above this one runs the - * in-process path (the phase-1 pins, unedited). Here the pool is pointed at - * the worker's source, started through the repo's `tsx` loader. - */ -describe('read_file extracts PDF and Word text on a worker pool, off the request thread', { timeout: 60_000 }, () => { - const SOURCE_WORKER: ExtractionWorkerEntry = { - url: new URL('./file-extraction-worker.ts', import.meta.url), - execArgv: ['--import', pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href], - }; - const DEFAULTS = { cpuBudgetMs: READ_FILE_CPU_BUDGET_MS_DEFAULT, maxConcurrent: READ_FILE_MAX_CONCURRENT_DEFAULT }; - let runtime: MCPServerRuntime; - beforeEach(() => { - runtime = new MCPServerRuntime({ name: 'file-tools', version: '0.0.0' }); - configureReadFileExtraction(DEFAULTS); - configureExtractionWorkerEntry(SOURCE_WORKER); - }); - afterEach(() => { - vi.restoreAllMocks(); - configureExtractionWorkerEntry(undefined); - configureReadFileExtraction(DEFAULTS); - }); - - /** A PDF whose pages each say `Page N text`, plus `drawOps(N)` path operators (what makes a page slow to read). */ - function heavyPdf(pages: number, drawOps: (page: number) => number): Uint8Array { - const objects: string[] = []; - objects[1] = '<< /Type /Catalog /Pages 2 0 R >>'; - objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>'; - const kids: string[] = []; - for (let i = 0; i < pages; i++) { - const pageId = 4 + i * 2; - const draw: string[] = []; - for (let k = 0; k < drawOps(i + 1); k++) draw.push(`${(k * 7) % 600} ${(k * 13) % 780} m ${(k * 11) % 600} ${(k * 17) % 780} l S`); - const stream = `BT /F1 12 Tf 72 720 Td (Page ${i + 1} text) Tj ET\n${draw.join('\n')}`; - kids.push(`${pageId} 0 R`); - objects[pageId] = `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents ${pageId + 1} 0 R /Resources << /Font << /F1 3 0 R >> >> >>`; - objects[pageId + 1] = `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`; - } - objects[2] = `<< /Type /Pages /Kids [${kids.join(' ')}] /Count ${pages} >>`; - let out = '%PDF-1.4\n'; - const offsets: number[] = []; - for (let i = 1; i < objects.length; i++) { - offsets[i] = out.length; - out += `${i} 0 obj\n${objects[i]}\nendobj\n`; - } - const xref = out.length; - out += `xref\n0 ${objects.length}\n0000000000 65535 f \n`; - for (let i = 1; i < objects.length; i++) out += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`; - out += `trailer\n<< /Size ${objects.length} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; - return new Uint8Array(Buffer.from(out, 'latin1')); - } - const pageTexts = (n: number) => Array.from({ length: n }, (_, i) => `Page ${i + 1} text`); - - async function readFile(bridge: ReturnType, file: Partial) { - bridge.next = file; - return callTool(runtime, bridge, 'read_file', { objectName: 'claim', recordId: 'c1', field: 'policy' }); - } - - it('CONTROL: a small PDF and a small Word document read in full on a worker, the same answer the in-process path gives', async () => { - const bridge = fullBridge(); - const pdf = multiPagePdf(['Page one opens', 'Page two follows', 'Page three closes']); - const docx = zip({ 'word/document.xml': docxBody(['Claim summary', 'Water & mould']) }); - const pdfFile = { name: 'three.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }; - const docxFile = { name: 'summary.docx', mimeType: DOCX, size: docx.length, bytes: docx }; - - const onWorker = [await readFile(bridge, pdfFile), await readFile(bridge, docxFile)]; - expect(extractionWorkerPoolStats().started).toBeGreaterThanOrEqual(1); - expect(textOf(onWorker[0].content[1])).toBe('Page one opens\n\nPage two follows\n\nPage three closes'); - expect(factsOf(onWorker[0]).truncated).toBeUndefined(); - expect(textOf(onWorker[1].content[1])).toBe('Claim summary\nWater & mould'); - - // The in-process path: under vitest the built entry is not beside the - // pool's source, so no worker starts, said once at warn with the reason. - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - configureExtractionWorkerEntry(undefined); - const inProcess = [await readFile(bridge, pdfFile), await readFile(bridge, docxFile)]; - expect(inProcess).toEqual(onWorker); - expect(warn).toHaveBeenCalledTimes(1); - expect(String(warn.mock.calls[0][0])).toContain('not a built .js or .cjs file'); - expect(String(warn.mock.calls[0][0])).toContain('The CPU budget and the cap on extractions in flight still apply.'); - }); - - it('an entry that fails before it is ready falls back to in-process, said once, and answers the same', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - configureExtractionWorkerEntry({ url: new URL('data:text/javascript,throw new Error("no extraction here")') }); - const bridge = fullBridge(); - const pdf = minimalPdf('Read in-process'); - const first = await readFile(bridge, { name: 'a.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }); - const second = await readFile(bridge, { name: 'a.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }); - expect(textOf(first.content[1])).toBe('Read in-process'); - expect(second).toEqual(first); - expect(warn).toHaveBeenCalledTimes(1); - expect(String(warn.mock.calls[0][0])).toContain('no extraction here'); - }); - - it('the request thread keeps ticking while a heavy PDF is read', async () => { - const pdf = heavyPdf(120, () => 2250); - const bridge = fullBridge(); - const file = { name: 'heavy.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }; - await readFile(bridge, file); // warm: the worker starts and loads unpdf - let ticks = 0; - const interval = setInterval(() => { - ticks++; - }, 1); - const started = performance.now(); - const result = await readFile(bridge, file); - const wallMs = performance.now() - started; - clearInterval(interval); - expect(textOf(result.content[1])).toBe(pageTexts(120).join('\n\n')); - expect(factsOf(result).truncated).toBeUndefined(); - // In-process this count is 0 (pdf.js never yields a macrotask while it - // reads). On the pool a 1 ms timer fires through the read: at least one - // tick per 4 ms of wall time, and at least 20. - expect({ ticks, enough: ticks >= 20 && ticks >= wallMs / 4 }).toMatchObject({ enough: true }); - }); - - /** - * The worker started with a preload that replaces `process.threadCpuUsage` - * IN THE WORKER THREAD with a clock advancing `stepMs` on every read: the - * worker's twin of the in-process `steppingCpuClock`, which spies the - * request thread's `process.cpuUsage` and cannot reach a worker. "The budget - * is spent" is then decided by how many checkpoints the extractor reached, - * never by how fast, or how loaded, this machine is. The worker's own code - * is unchanged: it reads the clock it always reads. - */ - function steppingThreadCpuWorker(stepMs: number): ExtractionWorkerEntry { - const clock = `let now = 0; process.threadCpuUsage = () => { now += ${stepMs * 1000}; return { user: now, system: 0 }; };`; - return { - ...SOURCE_WORKER, - execArgv: [...(SOURCE_WORKER.execArgv ?? []), '--import', `data:text/javascript,${encodeURIComponent(clock)}`], - }; - } - - it('out of CPU budget on the worker: the pages read so far, truncated, with the budget note, as in-process', async () => { - // The budget is spent at the third checkpoint (3 x 1000 ms of the stepping - // clock), so the read stops after page 3, whatever the runner's load. The - // budget is 3000 ms, not a few tens, because the pool's wall-clock ceiling - // is 5 budgets of REAL time: at 30 ms that ceiling (150 ms) cut a loaded - // runner's read before page 1, answering "after page 0" with no text. - configureReadFileExtraction({ cpuBudgetMs: 3000, maxConcurrent: 4 }); - configureExtractionWorkerEntry(steppingThreadCpuWorker(1000)); - const pdf = heavyPdf(120, () => 2250); - const bridge = fullBridge(); - const result = await readFile(bridge, { name: 'heavy.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }); - const facts = factsOf(result); - expect(facts).toMatchObject({ - content: 'text', - format: 'application/pdf', - truncated: true, - note: 'Reading stopped at the CPU-time budget for one file (3000 ms) after page 3 of 120, so the text is partial. ' - + 'Download the file with the link for the rest.', - }); - expect(textOf(result.content[1])).toBe(pageTexts(3).join('\n\n')); - expect(facts.download).toBeTruthy(); - - // Word: the budget is checked every 64 paragraphs. A 15 ms step spends the - // same 3000 ms budget at the 200th checkpoint, 12,800 paragraphs in, which - // is past the length cap, so the cap is what cuts the text that was read. - configureExtractionWorkerEntry(steppingThreadCpuWorker(15)); - const paragraphs = Array.from({ length: 60_000 }, (_, i) => `Paragraph ${i + 1}`); - const docx = zip({ 'word/document.xml': docxBody(paragraphs) }); - const word = await readFile(bridge, { name: 'long.docx', mimeType: DOCX, size: docx.length, bytes: docx }); - expect(factsOf(word)).toMatchObject({ - content: 'text', - format: DOCX, - truncated: true, - note: 'Reading stopped at the CPU-time budget for one file (3000 ms) after 12800 paragraphs, so the text is partial. ' - + 'Download the file with the link for the rest.', - }); - // The length cap still applies to what was read. - expect(paragraphs.slice(0, 12_800).join('\n').length).toBeGreaterThan(100_000); - expect(textOf(word.content[1])).toBe(paragraphs.slice(0, 12_800).join('\n').slice(0, 100_000)); - }); - - function minimalPdfFile(text = 'Small') { - const pdf = minimalPdf(text); - return { name: 'small.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }; - } - - it('a worker past its wall-clock ceiling is terminated: the pages it sent back are the answer, and the next call gets a fresh worker', async () => { - // Ceiling = 5 x 40 ms. Page 2 alone takes far longer, and a page is never - // cut by the budget (it is checked between pages), so only the ceiling - // can stop this read. - configureReadFileExtraction({ cpuBudgetMs: 40, maxConcurrent: 1 }); - const bridge = fullBridge(); - await readFile(bridge, minimalPdfFile()); // warm the one worker - expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 1 }); - const pdf = heavyPdf(3, (page) => (page === 2 ? 600_000 : 0)); - const stopped = await readFile(bridge, { name: 'stuck.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }); - expect(stopped.isError).toBeUndefined(); - expect(factsOf(stopped)).toMatchObject({ - content: 'text', - format: 'application/pdf', - truncated: true, - note: 'Reading stopped at the CPU-time budget for one file (40 ms) after page 1 of 3, so the text is partial. ' - + 'Download the file with the link for the rest.', - }); - expect(textOf(stopped.content[1])).toBe('Page 1 text'); - // The overrun worker is gone, not back in the pool. - expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 0 }); - - const next = await readFile(bridge, minimalPdfFile('Served next')); - expect(textOf(next.content[1])).toBe('Served next'); - expect(extractionWorkerPoolStats()).toEqual({ started: 2, idle: 1 }); - }); - - it('a worker that crashes fails only its own call, with the could-not-read answer, and is replaced', async () => { - // A stand-in worker: it crashes on a file whose first byte is "X", and - // otherwise answers the bytes as text, so the pool's own handling is what - // is pinned. - const standIn = [ - "import { parentPort } from 'node:worker_threads';", - "parentPort.on('message', (job) => {", - ' if (job.bytes[0] === 88) process.exit(7);', - " parentPort.postMessage({ type: 'done', result: { kind: 'text', format: 'application/pdf', text: new TextDecoder().decode(job.bytes), truncated: false } });", - '});', - "parentPort.postMessage({ type: 'ready' });", - ].join('\n'); - configureExtractionWorkerEntry({ url: new URL(`data:text/javascript,${encodeURIComponent(standIn)}`) }); - configureReadFileExtraction({ cpuBudgetMs: 1000, maxConcurrent: 1 }); - const bridge = fullBridge(); - const crash = new Uint8Array(Buffer.from('X marks the crash')); - const crashed = await readFile(bridge, { name: 'boom.pdf', mimeType: 'application/pdf', size: crash.length, bytes: crash }); - expect(factsOf(crashed)).toMatchObject({ - content: 'none', - note: 'The file\'s content could not be read. Download it with the link instead.', - }); - expect(extractionWorkerPoolStats()).toEqual({ started: 1, idle: 0 }); - const fine = new Uint8Array(Buffer.from('fine')); - const next = await readFile(bridge, { name: 'fine.pdf', mimeType: 'application/pdf', size: fine.length, bytes: fine }); - expect(textOf(next.content[1])).toBe('fine'); - expect(extractionWorkerPoolStats()).toEqual({ started: 2, idle: 1 }); - }); - - it('over the cap is refused on the request thread, at once, with the same retryable answer, while workers read', async () => { - configureReadFileExtraction({ cpuBudgetMs: 3000, maxConcurrent: 2 }); - const pdf = heavyPdf(40, () => 2250); - const inFlight = [ - extractFileContent(pdf, 'application/pdf', 'a.pdf'), - extractFileContent(pdf, 'application/pdf', 'b.pdf'), - ]; - try { - const bridge = fullBridge(); - const refused = await readFile(bridge, { name: 'c.pdf', mimeType: 'application/pdf', size: pdf.length, bytes: pdf }); - expect(refused.isError).toBe(true); - expect(JSON.parse(textOf(refused.content[0])).error).toEqual({ - code: 'SERVICE_UNAVAILABLE', - status: 503, - message: 'The server is already reading 2 files, the most it reads at once, so this file was not read. Try again in about 3 seconds.', - details: { retryAfterSeconds: 3 }, - }); - } finally { - await Promise.allSettled(inFlight); - } - for (const done of await Promise.all(inFlight)) expect(done).toMatchObject({ kind: 'text', text: pageTexts(40).join('\n\n') }); - // Both slots are free again, and the two workers wait in the pool. - expect(extractionWorkerPoolStats()).toEqual({ started: 2, idle: 2 }); - await expect(extractFileContent(minimalPdf('Free'), 'application/pdf', 'd.pdf')).resolves.toMatchObject({ text: 'Free' }); - }); -}); - -/** - * [#34855] A worker stopped at its wall-clock ceiling before it sent back the - * first page or paragraph answers no text, with a note saying the read - * stopped before any was read, never one calling the text partial. - * - * The worker is a stand-in that sends back exactly the progress a test - * scripts and then never answers, so the ceiling is what ends every read - * here and how far the read got is fixed by the script, never by how fast, or - * how loaded, this machine is: the clock decides when the read stops, never - * where. The progress messages are the real extractor's - * (`ExtractionProgress`), and the answer is built by the pool's own overrun - * path, as for a real worker. - */ -describe('read_file: a worker stopped at its wall-clock ceiling before the first page answers no text, never partial text', { timeout: 30_000 }, () => { - const DEFAULTS = { cpuBudgetMs: READ_FILE_CPU_BUDGET_MS_DEFAULT, maxConcurrent: READ_FILE_MAX_CONCURRENT_DEFAULT }; - let runtime: MCPServerRuntime; - beforeEach(() => { - runtime = new MCPServerRuntime({ name: 'file-tools', version: '0.0.0' }); - // Ceiling = 5 x 100 ms of real time: room for the scripted progress to - // arrive on a loaded runner, and every read here waits it out once. - configureReadFileExtraction({ cpuBudgetMs: 100, maxConcurrent: 1 }); - }); - afterEach(() => { - vi.restoreAllMocks(); - configureExtractionWorkerEntry(undefined); - configureReadFileExtraction(DEFAULTS); - }); - - /** A stand-in worker that sends `progress` back for every job, then never answers it. */ - function stalledWorker(progress: unknown[]): ExtractionWorkerEntry { - const source = [ - "import { parentPort } from 'node:worker_threads';", - `const progress = ${JSON.stringify(progress)};`, - "parentPort.on('message', () => {", - " for (const p of progress) parentPort.postMessage({ type: 'progress', progress: p });", - '});', - "parentPort.postMessage({ type: 'ready' });", - ].join('\n'); - return { url: new URL(`data:text/javascript,${encodeURIComponent(source)}`) }; - } - - async function readStopped(progress: unknown[], name: string, mimeType: string) { - configureExtractionWorkerEntry(stalledWorker(progress)); - const bytes = new Uint8Array(Buffer.from('never read')); - const bridge = fullBridge(); - bridge.next = { name, mimeType, size: bytes.length, bytes }; - const result = await callTool(runtime, bridge, 'read_file', { objectName: 'claim', recordId: 'c1', field: 'policy' }); - // The stalled worker is gone, not back in the pool: the ceiling ended it. - expect(extractionWorkerPoolStats().idle).toBe(0); - return result; - } - - it('a PDF opened but stopped before page 1, and one stopped before it opened, answer no text and say so', async () => { - const opened = await readStopped([{ kind: 'pdf-open', numPages: 120 }], 'heavy.pdf', 'application/pdf'); - expect(opened.isError).toBeUndefined(); - expect(factsOf(opened)).toMatchObject({ - content: 'none', - note: 'Reading stopped at the CPU-time budget for one file (100 ms) before page 1 of 120 was read, so no text came back. ' - + 'Download the file with the link instead.', - }); - expect(factsOf(opened).note).not.toContain('partial'); - expect(opened.content).toHaveLength(1); - - const unopened = await readStopped([], 'heavy.pdf', 'application/pdf'); - expect(factsOf(unopened)).toMatchObject({ - content: 'none', - note: 'Reading stopped at the CPU-time budget for one file (100 ms) before page 1 was read, so no text came back. ' - + 'Download the file with the link instead.', - }); - }); - - it('a Word document stopped before its first paragraphs came back answers no text and says so', async () => { - const result = await readStopped([], 'long.docx', DOCX); - expect(result.isError).toBeUndefined(); - expect(factsOf(result)).toMatchObject({ - content: 'none', - note: 'Reading stopped at the CPU-time budget for one file (100 ms) before the first paragraph was read, so no text came back. ' - + 'Download the file with the link instead.', - }); - expect(factsOf(result).note).not.toContain('partial'); - expect(result.content).toHaveLength(1); - }); - - it('CONTROL: a stop after page 1, or after the first paragraphs, still answers that text as partial', async () => { - const pdf = await readStopped( - [{ kind: 'pdf-open', numPages: 120 }, { kind: 'pdf-page', text: 'Page 1 text' }], - 'heavy.pdf', - 'application/pdf', - ); - expect(factsOf(pdf)).toMatchObject({ - content: 'text', - format: 'application/pdf', - truncated: true, - note: 'Reading stopped at the CPU-time budget for one file (100 ms) after page 1 of 120, so the text is partial. ' - + 'Download the file with the link for the rest.', - }); - expect(textOf(pdf.content[1])).toBe('Page 1 text'); - - const word = await readStopped([{ kind: 'docx-paragraphs', text: 'P1\nP2\n', paragraphs: 64 }], 'long.docx', DOCX); - expect(factsOf(word)).toMatchObject({ - content: 'text', - format: DOCX, - truncated: true, - note: 'Reading stopped at the CPU-time budget for one file (100 ms) after 64 paragraphs, so the text is partial. ' - + 'Download the file with the link for the rest.', - }); - expect(textOf(word.content[1])).toBe('P1\nP2'); - }); -}); diff --git a/packages/mcp/src/mcp-http-tools.ts b/packages/mcp/src/mcp-http-tools.ts index 09ef8699a31..13c3ef6fc09 100644 --- a/packages/mcp/src/mcp-http-tools.ts +++ b/packages/mcp/src/mcp-http-tools.ts @@ -138,7 +138,8 @@ import { type DiagnosedObjectListing, } from './metadata-completeness.js'; // [#30892] The file seam and what `read_file` renders from it. -import { READ_FILE_MAX_BYTES, ReadFileExtractionBusyError, renderReadFile, type McpFileBridge } from './file-content.js'; +import { READ_FILE_MAX_BYTES, renderReadFile, type McpFileBridge } from './file-content.js'; +import { ReadFileExtractionBusyError } from '@objectstack/core/document-text'; import { actionCallDoorFor, type McpActionCallDoor, type McpActionCallDoorFacts } from './action-confirmation-elicitation.js'; import type { McpLatestPer } from './types.js'; // [#35145] `expand` and `related`: the relation reads, judged before any read. diff --git a/packages/mcp/src/plugin.ts b/packages/mcp/src/plugin.ts index 32d956fe095..6a26370d39a 100644 --- a/packages/mcp/src/plugin.ts +++ b/packages/mcp/src/plugin.ts @@ -61,7 +61,8 @@ import { } from './stdio-data-bridge.js'; import { SEARCH_KNOWLEDGE_TOOL_NAME, knowledgeToolDefinition, registerKnowledgeTools, type McpDataBridge } from './mcp-http-tools.js'; import { CONNECT_AGENT_UI_BUNDLE } from './connect-ui.js'; -import { configureReadFileExtraction } from './file-content.js'; +// The shared document extractor's two host bounds, read at boot (`read_file` reads through it). +import { configureReadFileExtraction } from '@objectstack/core/document-text'; /** * [#15348] Resolve the deployment's EFFECTIVE tenancy posture for the stdio diff --git a/packages/mcp/tsup.config.ts b/packages/mcp/tsup.config.ts index 27a00b83245..a659efd94d8 100644 --- a/packages/mcp/tsup.config.ts +++ b/packages/mcp/tsup.config.ts @@ -5,12 +5,9 @@ import { defineConfig } from 'tsup'; import { dropSourcesContent } from '../../scripts/tsup-drop-sources-content.mjs'; export default defineConfig({ - // `file-extraction-worker` is `read_file`'s PDF/Word extraction worker - // (#31828): no export points at it; the pool starts it from - // `new URL('./file-extraction-worker.js' | '.cjs', import.meta.url)`, so it - // must sit beside `index` in both formats. `splitting: false` makes each - // entry self-contained (the worker carries its own copy of the extractors). - entry: ['src/index.ts', 'src/file-extraction-worker.ts'], + // `read_file`'s PDF/Word extraction worker moved with the extractor to + // `@objectstack/core/document-text`, which builds it beside its own entry. + entry: ['src/index.ts'], splitting: false, sourcemap: true, clean: true, diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts index ac58f8b5360..0f63b22b0b6 100644 --- a/packages/mcp/vitest.config.ts +++ b/packages/mcp/vitest.config.ts @@ -79,6 +79,12 @@ export default defineConfig({ { find: /^@objectstack\/objectql\/core$/, replacement: path.resolve(__dirname, '../objectql/src/core.ts') }, { find: /^@objectstack\/rest$/, replacement: path.resolve(__dirname, '../rest/src/index.ts') }, { find: /^@objectstack\/service-analytics$/, replacement: path.resolve(__dirname, '../services/service-analytics/src/index.ts') }, + // The shared document extractor `read_file` reads through: its pins here + // (the caps, the budget, the cap on reads in flight) judge the extractor + // in the checkout, never a build of it. Under the source the pool finds + // no built worker beside it, so every read here runs in-process; the + // worker pins live beside the pool in `packages/core`. + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../core/src/document-text.ts') }, // [ADR-0160 D4] The protocol, so `get_record_context`'s pack // listing is read off the real `ObjectStackProtocolImplementation` in the // checkout, decorations included, never a build of it. diff --git a/packages/metadata/vitest.config.ts b/packages/metadata/vitest.config.ts index 6fb04cbc9d8..c5288d3ba2c 100644 --- a/packages/metadata/vitest.config.ts +++ b/packages/metadata/vitest.config.ts @@ -13,6 +13,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../core/src/index.ts') }, // #9457: ONE anchored rule for every `@objectstack/spec` namespace, in place // of the hand-maintained list of the subpaths this package's tests happened diff --git a/packages/plugins/knowledge-memory/vitest.config.ts b/packages/plugins/knowledge-memory/vitest.config.ts index 4bf9c2f3d65..8330a252743 100644 --- a/packages/plugins/knowledge-memory/vitest.config.ts +++ b/packages/plugins/knowledge-memory/vitest.config.ts @@ -24,6 +24,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, // `./testing` (the adapter contract suite) BEFORE the bare package, and both // anchored: a string `find` matches by PREFIX, so the bare entry would diff --git a/packages/plugins/knowledge-pgvector/vitest.config.ts b/packages/plugins/knowledge-pgvector/vitest.config.ts index e25cb0d3084..0b5c2ea0add 100644 --- a/packages/plugins/knowledge-pgvector/vitest.config.ts +++ b/packages/plugins/knowledge-pgvector/vitest.config.ts @@ -24,6 +24,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, // `./testing` (the adapter contract suite) BEFORE the bare package, and both // anchored: a string `find` matches by PREFIX, so the bare entry would diff --git a/packages/plugins/knowledge-turso/vitest.config.ts b/packages/plugins/knowledge-turso/vitest.config.ts index c28064e4c27..a50dead4079 100644 --- a/packages/plugins/knowledge-turso/vitest.config.ts +++ b/packages/plugins/knowledge-turso/vitest.config.ts @@ -24,6 +24,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, // `./testing` (the adapter contract suite) BEFORE the bare package, and both // anchored: a string `find` matches by PREFIX, so the bare entry would diff --git a/packages/plugins/plugin-dev/vitest.config.ts b/packages/plugins/plugin-dev/vitest.config.ts index 56b33210c77..756155ccf14 100644 --- a/packages/plugins/plugin-dev/vitest.config.ts +++ b/packages/plugins/plugin-dev/vitest.config.ts @@ -79,6 +79,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, // Subpath BEFORE the bare package, same prefix-match reason: `./node` is a // published subpath served by a FILE (`types/src/node.ts` — the node-only slice diff --git a/packages/plugins/plugin-hono-server/vitest.config.ts b/packages/plugins/plugin-hono-server/vitest.config.ts index 1f87c04e6b7..9db8e8b3f1d 100644 --- a/packages/plugins/plugin-hono-server/vitest.config.ts +++ b/packages/plugins/plugin-hono-server/vitest.config.ts @@ -24,6 +24,7 @@ export default defineConfig({ // which derives the population from `@objectstack/core`'s own `exports` map. { find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') }, { find: '@objectstack/observability', replacement: path.resolve(__dirname, '../../observability/src/index.ts') }, // #9457: ONE anchored rule for every `@objectstack/spec` namespace, in place diff --git a/packages/runtime/vitest.config.ts b/packages/runtime/vitest.config.ts index d268cd2009d..1fa19de0427 100644 --- a/packages/runtime/vitest.config.ts +++ b/packages/runtime/vitest.config.ts @@ -113,6 +113,7 @@ export default defineConfig({ // path `…/core/src/index.ts/logger`. { find: '@objectstack/core/logger', replacement: path.resolve(__dirname, '../core/src/logger.ts') }, { find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../core/src/egress.ts') }, + { find: /^@objectstack\/core\/document-text$/, replacement: path.resolve(__dirname, '../core/src/document-text.ts') }, { find: '@objectstack/core', replacement: path.resolve(__dirname, '../core/src/index.ts') }, // #7828 / PR #8128: action-execution-destructive.test.ts reads the REAL // `sys_*` identity declarations to prove that today's platform objects diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9cc8c7643c4..c64f62026ea 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1119,6 +1119,9 @@ importers: undici: specifier: ^7.30.1 version: 7.30.1 + unpdf: + specifier: 1.9.1 + version: 1.9.1 zod: specifier: ^4.6.6 version: 4.6.7 @@ -1499,9 +1502,6 @@ importers: '@objectstack/types': specifier: workspace:* version: link:../types - unpdf: - specifier: 1.9.1 - version: 1.9.1 zod: specifier: ^4.6.6 version: 4.6.7 @@ -1530,6 +1530,9 @@ importers: typescript: specifier: ^6.0.3 version: 6.0.3 + unpdf: + specifier: 1.9.1 + version: 1.9.1 vitest: specifier: ^4.1.11 version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.5)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.10)(happy-dom@21.0.4)(jsdom@30.1.1(@noble/hashes@2.4.0))(msw@2.15.0(@types/node@26.6.5)(typescript@6.0.3))(vite@8.3.5(@types/node@26.6.5)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.15(patch_hash=4d1d35da1809be2a945519cb26890e48107810b9b66c6913a6a89abb5ad6a1e6))(yaml@2.9.1))