@happyvertical/smrt-ingestion 0.57.31 → 0.57.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/EXTRACTION.md CHANGED
@@ -91,6 +91,21 @@ boundaries for mixed/scanned PDF, Unlimited-OCR, camera observations, message
91
91
  attachments, audio timestamps and malformed/partial output. These fixtures are
92
92
  not real remote-provider integrations and are not the ADR evaluation corpus.
93
93
 
94
+ ### Host OCR data
95
+
96
+ `@happyvertical/pdf` probes its Kreuzberg provider on import and logs
97
+ `Kreuzberg could not initialize Tesseract language 'eng'` when no `eng`
98
+ traineddata is found. Ingestion's suites do not route through Kreuzberg (PDF
99
+ extraction uses `unpdf` or injected fixtures), so on its own this warning does
100
+ not explain a test failure. Hosts that run Kreuzberg OCR need Tesseract
101
+ language data: install `tesseract-ocr-eng` (Debian/Ubuntu) or `tesseract`
102
+ (Homebrew), or place `eng.traineddata` from
103
+ [tessdata_fast](https://github.com/tesseract-ocr/tessdata_fast) in a directory
104
+ and export `TESSDATA_PREFIX` pointing at it. The SDK checks
105
+ `TESSDATA_PREFIX`, then `tesseract --list-langs`, then the common
106
+ `/usr/share`, `/usr/local/share` and Homebrew `tessdata` directories; on
107
+ hosts without those paths (for example NixOS), set `TESSDATA_PREFIX`.
108
+
94
109
  No live Unlimited-OCR, speech recognition or vision quality run is claimed.
95
110
  No recorded-human-audio recognition accuracy, real camera-scene quality,
96
111
  calibrated confidence, table extraction, or automatic-action acceptance is
package/PROPOSALS.md CHANGED
@@ -145,6 +145,45 @@ new text, but their digests do not record it; a host that needs provenance to
145
145
  tell the two apart bumps its own `promptVersion`, which, like any configuration
146
146
  change, makes earlier attempts read as stale (`GenerationSnapshotStaleError`).
147
147
 
148
+ Each suggestion's `explanation` is one or two plain sentences stating what the
149
+ document is and why the handler fits, with no deliberation, self-correction or
150
+ restating of the rules, and is bounded at 300 code points (#4331,
151
+ `PROPOSAL_EXPLANATION_LIMIT`). Two such sentences run about 150-250
152
+ characters; the bound keeps a verbose model from spending its output budget
153
+ (and hitting the `length` finish reason) on prose instead of arguments. A
154
+ reply cut at the token limit is still refused (`finish_reason`) and partial
155
+ JSON is never salvaged; the grammar bound and the instruction are what keep
156
+ replies under the limit. The provider schema and the validator carry the same `maxLength`, so the provider
157
+ copy still accepts a superset of the validator (#4261), and a grammar backend
158
+ enforces the bound while decoding. In the provider schema `explanation` is the
159
+ last suggestion property, after `handlerId`, `handlerVersion`, `args`,
160
+ `evidence`, `alternatives` and `missingFields`, and the top-level keys are
161
+ `outcome`, `suggestions`, `splits` in that order; `required` lists the same
162
+ order. That order predates #4331 and is now pinned by a test, so explanation
163
+ prose cannot precede the arguments. xgrammar emits object properties in schema `properties` order unless
164
+ `any_order` is set (its default is `false`, and vLLM does not set it), and
165
+ llguidance fixes property order to the `properties` map, then `required`. A provider
166
+ that ignores the schema can still return a longer explanation: fresh output is
167
+ normalized after the list deduplication above and before validation, cutting
168
+ it to 299 code points plus `…` on a code-point boundary, so a long explanation
169
+ never fails validation (the raw output-size and SDK `output_limit` checks
170
+ still run first). The value-free count is recorded as
171
+ `provenance.explanationsTruncated`, absent when zero and removed with
172
+ `duplicatesRemoved` whenever the suggestions are discarded. It counts only
173
+ replies from providers that ignore the schema: on a grammar backend such as
174
+ vLLM the string closes at 300 code points with no marker, and nothing is
175
+ counted. The cut happens
176
+ before the invented-target echo check, so an echo beyond the bound is no
177
+ longer seen; explanation text is never a target or authority.
178
+
179
+ Replay: the bound, the property order and the instruction text feed no digest.
180
+ The response schema is built per request and never persisted; the frozen
181
+ interpretation configuration holds versions, identities, the catalog digest and
182
+ `limits`, none of which include the explanation bound. Stored attempts are read
183
+ as persisted, never re-validated or re-cut, so an earlier attempt with an
184
+ explanation of up to 2000 characters still reads, previews and replays with
185
+ its original `output_digest`. New attempts' digests cover the bounded form.
186
+
148
187
  A trusted custom `ProposalGenerator` must likewise honor cancellation, bound its
149
188
  response, and explicitly declare validated `complete` or `unknown` completion.
150
189
  The SDK currently normalizes missing/unknown finish reasons to `stop`
@@ -386,6 +425,44 @@ phrase. Transport failures through the OpenAI SDK already carried
386
425
  problem, and other non-SDK errors contribute the transport facts above. The
387
426
  category is unchanged (`unavailable`).
388
427
 
428
+ ### Host suggestion review (`reviewSuggestion`)
429
+
430
+ A host's own checks on a generated suggestion (a label that is not the invoice
431
+ date, an amount that is not in the document) can hold it and leave a record a
432
+ reviewer sees:
433
+
434
+ ```ts
435
+ proposals: {
436
+ // ...
437
+ reviewSuggestion: ({ suggestion, handler, evidence }) => ({
438
+ hold: true, // optional; forces needs_review
439
+ reasons: ['total_not_in_text'], // optional; <= 8 codes, /^[a-z][a-z0-9_.-]{0,47}$/
440
+ prefilled: ['billDate'], // optional; names declared in handler.argsSchema.properties
441
+ }),
442
+ },
443
+ ```
444
+
445
+ The hook is trusted, server-only and optional. It runs once per validated
446
+ suggestion, after validation and before the decision gate, with deep copies of
447
+ the suggestion, its offered handler and the retained evidence text. It cannot
448
+ change `args`, `missingFields`, evidence or the outcome except through `hold`,
449
+ and it can never upgrade: `hold` sets the suggestion (and a `proposals` outcome)
450
+ to `needs_review`; absent or `hold: false` leaves the validator's disposition.
451
+
452
+ The result is stored as `suggestion.hostReview` (`{held, reasons, prefilled}`)
453
+ and counted in `provenance.hostReview` (`{annotated, held}`); both are absent
454
+ when the hook records nothing. Values cannot be stored: unknown keys, free-text
455
+ or over-long reasons, `prefilled` names that are not argument names, and any
456
+ reason code containing one of the suggestion's own argument values (3+
457
+ characters) make the result invalid. An invalid result, a throw, a rejection or
458
+ a hook slower than `limits.timeoutMs` holds the suggestion with the fixed code
459
+ `host_review_invalid` or `host_review_failed`; the error text is discarded.
460
+ `ReviewView` shows "Checked by the shop: ..." under the arguments.
461
+
462
+ Like `failureCapture`, the hook is not public read configuration and never enters
463
+ frozen configuration or digests. Hosts keep it synchronous-cheap: it runs inside
464
+ the generation lease.
465
+
389
466
  ### Failed-attempt capture (opt-in, #4285)
390
467
 
391
468
  The value-free reason cannot show what the model actually sent. A host that
@@ -1 +1 @@
1
- {"version":3,"file":"proposal-contracts-CqVVPvqq.js","names":[],"sources":["../../src/extraction.ts","../../src/proposal-limits.ts","../../src/proposal-contracts.ts"],"sourcesContent":["import { fork } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { GetAIOptions } from '@happyvertical/ai';\nimport type { PDFReaderOptions } from '@happyvertical/pdf';\nimport type { GetTranscriberOptions } from '@happyvertical/speech';\nimport type { AnalysisOutput } from './dto.js';\nimport {\n ExtractionFailure,\n emptyExtraction,\n validateExtractionRequest,\n} from './extraction-providers.js';\nimport type {\n ExtractionAdapter,\n ExtractionRequest,\n ExtractionResult,\n ProviderIdentity,\n} from './extraction-types.js';\nimport { providerIdentity } from './extraction-types.js';\nimport type { AnalysisLease, IngestionService } from './server.js';\n\nexport type * from './extraction-types.js';\n\n/** Trusted server configuration. Credentials never enter analysis provenance. */\nexport interface ExtractionSDKConfiguration {\n pdf?: {\n provider: NonNullable<PDFReaderOptions['provider']>;\n identity: ProviderIdentity;\n };\n ocr?: { identity: ProviderIdentity; options?: Record<string, unknown> };\n speech?: { identity: ProviderIdentity; options: GetTranscriberOptions };\n vision?: { identity: ProviderIdentity; options: GetAIOptions };\n imageMode?: 'ocr' | 'vision';\n /** Maximum concurrent child processes for this adapter instance (default 1). */\n maxConcurrentProcesses?: number;\n /** The deployment enforces a native-memory ceiling outside Node (e.g. container).\n * Required for native decoders: Node's heap cap does not bound native allocation. */\n nativeMemoryIsolation: 'host-enforced';\n}\n\n/** Production adapter: bounded per-evidence child, terminated on deadline/abort. */\nexport function createSDKExtractionAdapter(\n configuration: ExtractionSDKConfiguration,\n): ExtractionAdapter {\n try {\n configuration = structuredClone(configuration);\n } catch {\n throw new Error('Serializable SDK configuration required');\n }\n const maximum = configuration.maxConcurrentProcesses ?? 1;\n if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 32)\n throw new Error('Invalid extraction concurrency');\n let running = 0;\n if (configuration.nativeMemoryIsolation !== 'host-enforced')\n throw new Error('Native memory isolation is required');\n for (const provider of [\n configuration.pdf,\n configuration.ocr,\n configuration.speech,\n configuration.vision,\n ]) {\n if (provider) provider.identity = providerIdentity(provider.identity);\n }\n if (\n configuration.pdf?.provider === 'auto' ||\n configuration.ocr?.identity.provider === 'auto'\n )\n throw new Error('Pin extraction providers');\n return {\n async extract(request) {\n let latest = emptyExtraction(request);\n try {\n validateExtractionRequest(request);\n } catch (caught) {\n if (!(caught instanceof ExtractionFailure)) throw caught;\n latest.errors.push({\n category: caught.category,\n location: { kind: 'source' },\n });\n return latest;\n }\n if (request.evidence.mediaType.toLowerCase().startsWith('video/')) {\n latest.status = 'unsupported';\n latest.errors.push({\n category: 'unsupported_type',\n location: { kind: 'source' },\n });\n return latest;\n }\n if (request.signal?.aborted) {\n latest.errors.push({\n category: 'cancelled',\n location: { kind: 'source' },\n });\n return latest;\n }\n if (running >= maximum) {\n latest.errors.push({ category: 'limit', location: { kind: 'source' } });\n return latest;\n }\n running++;\n return new Promise<ExtractionResult>((resolve) => {\n // A public entry can move shared code into chunks; resolve without loading it.\n const child = fork(\n join(\n dirname(\n fileURLToPath(\n import.meta.resolve('@happyvertical/smrt-ingestion/server'),\n ),\n ),\n 'extraction-worker.js',\n ),\n [],\n {\n serialization: 'advanced',\n stdio: ['ignore', 'ignore', 'ignore', 'ipc'],\n execArgv: [`--max-old-space-size=${request.limits.workerHeapMb}`],\n detached: process.platform !== 'win32',\n },\n );\n let done = false;\n const stop = () => {\n try {\n if (process.platform !== 'win32' && child.pid)\n process.kill(-child.pid, 'SIGKILL');\n else child.kill('SIGKILL');\n } catch {\n child.kill('SIGKILL');\n }\n };\n const finish = (\n category?: 'timeout' | 'cancelled' | 'unavailable' | 'limit',\n ) => {\n if (done) return;\n done = true;\n running--;\n clearTimeout(timer);\n request.signal?.removeEventListener('abort', abort);\n stop();\n if (category) {\n latest.errors.push({ category, location: { kind: 'source' } });\n latest.status = latest.segments.length ? 'partial' : 'failed';\n latest.truncated = true;\n latest.omitted.push({ kind: 'source' });\n }\n resolve(latest);\n };\n const abort = () => finish('cancelled');\n const timer = setTimeout(\n () => finish('timeout'),\n request.limits.timeoutMs,\n );\n request.signal?.addEventListener('abort', abort, { once: true });\n child.on('error', () => finish('unavailable'));\n child.on('exit', () => {\n if (!done) finish('unavailable');\n });\n child.on(\n 'message',\n async (message: {\n kind: string;\n id?: number;\n result?: ExtractionResult;\n }) => {\n if (done) return;\n if (\n message.kind === 'authorize' &&\n Number.isSafeInteger(message.id)\n ) {\n try {\n await request.beforeProviderCall?.();\n if (!done) child.send({ kind: 'authorized', id: message.id });\n } catch {\n finish('cancelled');\n }\n return;\n }\n if (\n (message.kind === 'progress' || message.kind === 'result') &&\n message.result\n ) {\n // The child is our trusted normalizer; bound serialized IPC output as well.\n if (\n Buffer.byteLength(JSON.stringify(message.result)) >\n request.limits.maxOutputBytes + 65536\n )\n return finish('limit');\n latest = message.result;\n if (message.kind === 'result') finish();\n } else finish('unavailable');\n },\n );\n const {\n signal: _signal,\n beforeProviderCall: _authorize,\n ...wireRequest\n } = request;\n child.send({ request: wireRequest, configuration }, (error) => {\n if (error) finish('unavailable');\n });\n if (request.signal?.aborted) abort();\n });\n },\n };\n}\n\nfunction validateAndNormalizeExtractionOutput(\n result: ExtractionResult,\n request: ExtractionRequest,\n): void {\n const numeric = (value: number) => Number.isFinite(value) && value >= 0;\n const location = (\n value: ExtractionResult['segments'][number]['location'],\n ) => {\n if (!value || typeof value !== 'object') return false;\n if (value.kind === 'source') return true;\n if (value.kind === 'page')\n return Number.isSafeInteger(value.page) && value.page > 0;\n if (value.kind === 'pages')\n return (\n Number.isSafeInteger(value.startPage) &&\n value.startPage > 0 &&\n Number.isSafeInteger(value.endPage) &&\n value.endPage >= value.startPage\n );\n return (\n value.kind === 'time' &&\n numeric(value.startMs) &&\n numeric(value.endMs) &&\n value.endMs >= value.startMs\n );\n };\n if (\n !result ||\n !['complete', 'partial', 'failed', 'unsupported'].includes(result.status) ||\n result.automaticActionEligible !== false ||\n result.configurationRevision !== request.configurationRevision ||\n !result.evidence ||\n Object.entries(request.evidence).some(\n ([key, value]) =>\n result.evidence[key as keyof typeof result.evidence] !== value,\n ) ||\n typeof result.truncated !== 'boolean' ||\n !Array.isArray(result.capabilities) ||\n result.capabilities.some(\n (capability) =>\n !capability ||\n typeof capability.confidence !== 'boolean' ||\n typeof capability.boxes !== 'boolean' ||\n !['source', 'page', 'time'].includes(capability.location) ||\n !['unknown', 'reported'].includes(capability.truncation) ||\n !['unknown', 'reported'].includes(capability.usage),\n ) ||\n !result.limits ||\n Object.entries(request.limits).some(\n ([key, value]) =>\n result.limits[key as keyof typeof result.limits] !== value,\n ) ||\n !Array.isArray(result.segments) ||\n !Array.isArray(result.errors) ||\n !Array.isArray(result.omitted) ||\n (result.status === 'complete' &&\n (result.truncated ||\n result.errors.length > 0 ||\n result.omitted.length > 0)) ||\n result.omitted.some((value) => !location(value)) ||\n result.segments.some(\n (segment) =>\n typeof segment.text !== 'string' ||\n !location(segment.location) ||\n segment.location.kind === 'pages' ||\n (segment.provenance?.provider === 'unlimited-ocr' &&\n (segment.confidence !== null || segment.boxes !== null)) ||\n !segment.provenance ||\n [\n segment.provenance.provider,\n segment.provenance.model,\n segment.provenance.version,\n ].some((value) => typeof value !== 'string' || !value) ||\n (segment.confidence !== null &&\n (!segment.confidence ||\n !numeric(segment.confidence.value) ||\n segment.confidence.value > 1 ||\n segment.confidence.scale !== '0-1' ||\n segment.confidence.calibration !== 'unknown')) ||\n (segment.boxes !== null &&\n (!Array.isArray(segment.boxes) ||\n segment.boxes.some(\n (box) =>\n typeof box.text !== 'string' ||\n ![box.x, box.y, box.width, box.height].every(numeric),\n ))),\n ) ||\n result.errors.some(\n (error) =>\n ![\n 'unsupported_type',\n 'malformed_output',\n 'limit',\n 'timeout',\n 'unavailable',\n 'authentication',\n 'cancelled',\n 'integrity',\n ].includes(error.category) || !location(error.location),\n ) ||\n !result.usage ||\n Object.values(result.usage).some((value) => !numeric(value))\n )\n throw new Error('Invalid extraction output');\n // Structural typing permits extra host fields. Never persist them as identity.\n for (const segment of result.segments)\n segment.provenance = providerIdentity(segment.provenance);\n result.capabilities = result.capabilities.map((capability) => ({\n ...providerIdentity(capability),\n confidence: capability.confidence,\n boxes: capability.boxes,\n location: capability.location,\n truncation: capability.truncation,\n usage: capability.usage,\n }));\n}\n\n/** Current access is rechecked on read and fenced publication by the foundation.\n * The host already allocated the immutable input/config revision and lease. */\nexport async function extractAnalysis(\n service: IngestionService,\n lease: AnalysisLease,\n adapter: ExtractionAdapter,\n options: Pick<\n ExtractionRequest,\n 'limits' | 'configurationRevision' | 'signal'\n >,\n): Promise<boolean> {\n const snapshot = await service.getAnalysisInput(lease);\n const persisted = snapshot.configuration.extraction as\n | { configurationRevision?: unknown; limits?: Record<string, unknown> }\n | undefined;\n if (\n !persisted ||\n persisted.configurationRevision !== options.configurationRevision ||\n !persisted.limits ||\n Object.keys(options.limits).some(\n (key) =>\n persisted.limits?.[key] !==\n options.limits[key as keyof typeof options.limits],\n ) ||\n Object.keys(persisted.limits).length !== Object.keys(options.limits).length\n )\n throw new Error('Extraction configuration mismatch');\n const evidence = snapshot.evidence;\n const boundOptions = { ...options, limits: structuredClone(options.limits) };\n const results: ExtractionResult[] = [];\n let limited = false;\n const publication = (reserve = false): AnalysisOutput => {\n const allComplete =\n !limited &&\n results.length === evidence.length &&\n results.every((result) => result.status === 'complete');\n const firstError =\n limited || reserve\n ? 'limit'\n : results.flatMap((result) => result.errors)[0]?.category;\n return {\n status: reserve\n ? 'needs_attention'\n : allComplete\n ? 'completed'\n : results.some((result) => result.segments.length)\n ? 'partial'\n : 'needs_attention',\n provider: 'smrt-ingestion-extraction',\n model: 'none',\n version: '1',\n output: {\n configurationRevision: options.configurationRevision,\n results,\n ...(limited || reserve\n ? {\n truncated: true,\n omittedEvidenceCount: evidence.length - results.length,\n }\n : {}),\n },\n usage: {},\n ...(firstError ? { error: firstError } : {}),\n };\n };\n // Canonical persistence sorts keys but uses identical JSON value encoding/size.\n const fits = (output: AnalysisOutput) =>\n Buffer.byteLength(JSON.stringify(output)) <= snapshot.maxOutputBytes;\n const minimum: AnalysisOutput = {\n status: 'needs_attention',\n provider: 'smrt-ingestion-extraction',\n model: 'none',\n version: '1',\n output: {},\n usage: {},\n error: 'limit',\n };\n if (!fits(minimum)) return service.failAnalysis(lease, 'limit');\n if (!fits(publication(true))) return service.completeAnalysis(lease, minimum);\n for (const part of evidence) {\n await service.getAnalysisInput(lease);\n const bytes = await service.readEvidence(lease.itemId, part.id);\n await service.getAnalysisInput(lease);\n const request = { ...boundOptions, evidence: part, bytes };\n const result = await adapter.extract({\n ...request,\n evidence: { ...part },\n limits: { ...request.limits },\n bytes: bytes.slice(),\n beforeProviderCall: async () => {\n await service.getAnalysisInput(lease);\n },\n });\n validateAndNormalizeExtractionOutput(result, request);\n results.push(result);\n if (!fits(publication(true))) {\n limited = true;\n // Preserve earlier parts and the largest prefix of complete segments that fits.\n result.status = 'partial';\n result.truncated = true;\n result.errors.push({ category: 'limit', location: { kind: 'source' } });\n while (result.segments.length && !fits(publication(true))) {\n const removed = result.segments.pop();\n if (removed) result.omitted.push(removed.location);\n }\n // Diagnostics are indivisible: omit this result rather than erase known gaps.\n if (!fits(publication(true))) results.pop();\n }\n // Revalidation after an external call prevents returning/publishing revoked evidence.\n await service.getAnalysisInput(lease);\n if (limited || options.signal?.aborted) break;\n }\n return service.completeAnalysis(lease, publication());\n}\n\n/**\n * A split's page groups failed the group check (empty, unknown or repeated\n * page, unordered). Generated splits that fail it are dropped (#4288); the\n * message is a fixed phrase, never page numbers.\n */\nexport class SplitGroupError extends Error {}\n/** Side-effect-free, versioned split proposal. Original evidence is not replaced. */\nexport function proposeDocumentSplits(\n result: ExtractionResult,\n revision: number,\n groups: number[][],\n) {\n if (!Number.isSafeInteger(revision) || revision < 1 || !groups.length)\n throw new Error('Invalid split revision');\n const available = new Set(\n result.segments.flatMap((segment) =>\n segment.location.kind === 'page' ? [segment.location.page] : [],\n ),\n );\n const seen = new Set<number>();\n for (const group of groups) {\n if (!group.length) throw new SplitGroupError('Empty split');\n for (const page of group) {\n if (!Number.isSafeInteger(page) || !available.has(page) || seen.has(page))\n throw new SplitGroupError('Invalid split page');\n seen.add(page);\n }\n if (group.some((page, index) => index > 0 && page <= group[index - 1]))\n throw new SplitGroupError('Unordered split');\n }\n const proposal = {\n revision,\n evidenceId: result.evidence.id,\n inputHash: result.evidence.contentHash,\n configurationRevision: result.configurationRevision,\n groups: groups.map((pages) => ({ pages: [...pages] })),\n status: 'proposed' as const,\n };\n return {\n ...proposal,\n digest: createHash('sha256').update(JSON.stringify(proposal)).digest('hex'),\n };\n}\n","import type { ProposalConfiguration } from './proposal-contracts.js';\n\n/** Validate deployment limits before any item is interpreted. */\nexport function assertProposalLimits(\n limits: ProposalConfiguration['limits'],\n): void {\n if (\n !limits ||\n [\n 'maxHandlers',\n 'maxCandidates',\n 'maxSuggestions',\n 'maxInputBytes',\n 'maxOutputBytes',\n 'maxQueryLength',\n 'timeoutMs',\n ].some(\n (key) =>\n !Number.isSafeInteger(limits[key as keyof typeof limits]) ||\n limits[key as keyof typeof limits] <= 0,\n ) ||\n limits.maxHandlers > 20 ||\n limits.maxCandidates > 20 ||\n limits.maxSuggestions > 20 ||\n limits.timeoutMs > 2_147_483_647\n )\n throw new Error('Invalid proposal limits');\n}\n","import type { DecisionClient } from '@happyvertical/smrt-core';\nimport type { HandlerContext } from './execution-contracts.js';\nimport type { IntakeValues } from './execution-dto.js';\nimport {\n type EvidenceLocation,\n type ProviderIdentity,\n providerIdentity,\n} from './extraction-types.js';\nimport type {\n ProposalCandidate,\n ProposalCatalogEntry,\n ProposalReferenceField,\n} from './proposal-dto.js';\n\n/** Optional discovery capability on the existing application execution handler. */\nexport interface HandlerDiscovery {\n mediaTypes: readonly string[];\n /** Every existing-record argument exposed to generation must be declared here. */\n references: Readonly<Record<string, ProposalReferenceField>>;\n /** Database reads only; filter in the query before ranking/summarizing. */\n candidates?(\n query: string,\n context: HandlerContext,\n page: { limit: number },\n ): Promise<{\n items: Array<Omit<ProposalCandidate, 'key'>>;\n hasMore: boolean;\n }>;\n}\nexport interface GenerationLimits {\n maxHandlers: number;\n maxCandidates: number;\n maxSuggestions: number;\n maxInputBytes: number;\n maxOutputBytes: number;\n maxQueryLength: number;\n timeoutMs: number;\n}\nexport interface GenerativeProposalInput {\n evidence: Array<{\n evidenceId: string;\n partId: string;\n parentEvidenceId: string | null;\n mediaType: string;\n contentHash: string;\n segments: Array<{ text: string; location: EvidenceLocation }>;\n }>;\n offered: Array<{\n handler: ProposalCatalogEntry;\n candidates: ProposalCandidate[];\n }>;\n instructions: string;\n /** Bounded, currently eligible examples; neither evidence nor authority. */\n examples?: import('./feedback-dto.js').FeedbackSelection;\n /** Authenticated human correction carried through fresh extraction; never model authority. */\n humanCorrection?: IntakeValues;\n /** Authenticated reviewer guidance; trusted steering only, never catalog or approval authority. */\n reviewerInstruction?: { id: string; text: string };\n}\n/** Inject only trusted SDK-bound adapters. Generative output is always untrusted. */\nexport interface ProposalGenerator {\n identity: ProviderIdentity;\n generate(\n input: GenerativeProposalInput,\n options: { signal: AbortSignal; maxOutputBytes: number },\n ): Promise<{\n output: unknown;\n completion: 'complete' | 'unknown';\n usage?: Record<string, number>;\n /** Provider-reported immutable model revision, when it safely resolves a configured alias. */\n responseModel?: string;\n }>;\n}\n/**\n * How validated decision answers affect readiness. `gate` (default) sends a\n * suggestion to `needs_review` when the thresholds are not met; `record` still\n * runs and persists the same answers but leaves outcome/disposition to the\n * validator. Neither mode makes any action automation-eligible.\n */\nexport type DecisionReadiness = 'gate' | 'record';\n/** Public decision settings shared by generation and read configuration. */\nexport interface DecisionSettings {\n minimumDecisionProbability?: number;\n tieMargin?: number;\n /**\n * Per-request token window forwarded to the decision client as `maxLen`\n * (the SDK Laya provider option). Absent keeps the client/checkpoint default.\n */\n decisionMaxLen?: number;\n decisionReadiness?: DecisionReadiness;\n}\nexport interface ProposalConfiguration extends DecisionSettings {\n version: string;\n promptVersion: string;\n generator: ProposalGenerator;\n /** Absent means the normal unconfigured decision path, never fake probability. */\n decision?: { client: DecisionClient; identity: ProviderIdentity };\n limits: GenerationLimits;\n /**\n * Opt-in, bounded, redacted capture of the model output on a failed\n * interpretation attempt (#4285). Text requires a host redactor; absent or\n * failed redaction retains no text. Off when absent. Not public read\n * configuration: it never enters frozen configuration, digests or\n * `proposalReadConfiguration`. See PROPOSALS.md.\n */\n failureCapture?: import('./failure-capture.js').FailureCaptureConfiguration;\n}\n/** Credential-free configuration for validating persisted proposal snapshots. */\nexport interface ProposalReadConfiguration extends DecisionSettings {\n version: string;\n promptVersion: string;\n generator: ProviderIdentity;\n decision?: ProviderIdentity;\n limits: GenerationLimits;\n}\n/** Remove generation capability while preserving the public persisted configuration. */\nexport function proposalReadConfiguration(\n config: ProposalConfiguration | ProposalReadConfiguration,\n): ProposalReadConfiguration {\n const generator = providerIdentity(\n 'identity' in config.generator\n ? config.generator.identity\n : config.generator,\n );\n return {\n version: config.version,\n promptVersion: config.promptVersion,\n generator,\n ...(config.decision\n ? {\n decision: providerIdentity(\n 'identity' in config.decision\n ? config.decision.identity\n : config.decision,\n ),\n }\n : {}),\n ...(config.minimumDecisionProbability === undefined\n ? {}\n : { minimumDecisionProbability: config.minimumDecisionProbability }),\n ...(config.tieMargin === undefined ? {} : { tieMargin: config.tieMargin }),\n ...(config.decisionMaxLen === undefined\n ? {}\n : { decisionMaxLen: config.decisionMaxLen }),\n ...(config.decisionReadiness === undefined\n ? {}\n : { decisionReadiness: config.decisionReadiness }),\n limits: {\n maxHandlers: config.limits.maxHandlers,\n maxCandidates: config.limits.maxCandidates,\n maxSuggestions: config.limits.maxSuggestions,\n maxInputBytes: config.limits.maxInputBytes,\n maxOutputBytes: config.limits.maxOutputBytes,\n maxQueryLength: config.limits.maxQueryLength,\n timeoutMs: config.limits.timeoutMs,\n },\n };\n}\nexport interface GenerationStageConfiguration extends IntakeValues {\n stage: 'interpret';\n /** Copied from the pinned extraction source; verified against it before provider disclosure. */\n reviewerInstruction?: IntakeValues;\n proposals: {\n source: import('./proposal-dto.js').GenerationSourcePin;\n configurationVersion: string;\n promptVersion: string;\n catalogDigest: string;\n generator: ProviderIdentity;\n decision: ProviderIdentity | null;\n limits: GenerationLimits;\n minimumDecisionProbability: number;\n tieMargin: number;\n /** Present only when configured, so default digests stay stable. */\n decisionMaxLen?: number;\n /** Present only for `record`; `gate` is the default. */\n decisionReadiness?: 'record';\n };\n}\n"],"mappings":";;;;;;AA0CO,SAAS,2BACd,eACmB;CACnB,IAAI;EACF,gBAAgB,gBAAgB,aAAa;CAC/C,QAAQ;EACN,MAAM,IAAI,MAAM,yCAAyC;CAC3D;CACA,MAAM,UAAU,cAAc,0BAA0B;CACxD,IAAI,CAAC,OAAO,cAAc,OAAO,KAAK,UAAU,KAAK,UAAU,IAC7D,MAAM,IAAI,MAAM,gCAAgC;CAClD,IAAI,UAAU;CACd,IAAI,cAAc,0BAA0B,iBAC1C,MAAM,IAAI,MAAM,qCAAqC;CACvD,KAAA,MAAW,YAAY;EACrB,cAAc;EACd,cAAc;EACd,cAAc;EACd,cAAc;CAChB,GACE,IAAI,UAAU,SAAS,WAAW,iBAAiB,SAAS,QAAQ;CAEtE,IACE,cAAc,KAAK,aAAa,UAChC,cAAc,KAAK,SAAS,aAAa,QAEzC,MAAM,IAAI,MAAM,0BAA0B;CAC5C,OAAO,EACL,MAAM,QAAQ,SAAS;EACrB,IAAI,SAAS,gBAAgB,OAAO;EACpC,IAAI;GACF,0BAA0B,OAAO;EACnC,SAAS,QAAQ;GACf,IAAI,EAAE,kBAAkB,oBAAoB,MAAM;GAClD,OAAO,OAAO,KAAK;IACjB,UAAU,OAAO;IACjB,UAAU,EAAE,MAAM,SAAS;GAC7B,CAAC;GACD,OAAO;EACT;EACA,IAAI,QAAQ,SAAS,UAAU,YAAY,CAAA,CAAE,WA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AyB;AAC7C;;;ACyFO,SAAS,0BACd,QAC2B;CAC3B,MAAM,YAAY,iBAChB,cAAc,OAAO,YACjB,OAAO,UAAU,WACjB,OAAO,SACb;CACA,OAAO;EACL,SAAS,OAAO;EAChB,eAAe,OAAO;EACtB;EACA,GAAI,OAAO,WACP,EACE,UAAU,iBACR,cAAc,OAAO,WACjB,OAAO,SAAS,WAChB,OAAO,QACb,EACF,IACA,CAAC;EACL,GAAI,OAAO,+BAA+B,KAAA,IACtC,CAAC,IACD,EAAE,4BAA4B,OAAO,2BAA2B;EACpE,GAAI,OAAO,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,OAAO,UAAU;EACxE,GAAI,OAAO,mBAAmB,KAAA,IAC1B,CAAC,IACD,EAAE,gBAAgB,OAAO,eAAe;EAC5C,GAAI,OAAO,sBAAsB,KAAA,IAC7B,CAAC,IACD,EAAE,mBAAmB,OAAO,kBAAkB;EAClD,QAAQ;GACN,aAAa,OAAO,OAAO;GAC3B,eAAe,OAAO,OAAO;GAC7B,gBAAgB,OAAO,OAAO;GAC9B,eAAe,OAAO,OAAO;GAC7B,gBAAgB,OAAO,OAAO;GAC9B,gBAAgB,OAAO,OAAO;GAC9B,WAAW,OAAO,OAAO;EAC3B;CACF;AACF"}
1
+ {"version":3,"file":"proposal-contracts-CqVVPvqq.js","names":[],"sources":["../../src/extraction.ts","../../src/proposal-limits.ts","../../src/proposal-contracts.ts"],"sourcesContent":["import { fork } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { GetAIOptions } from '@happyvertical/ai';\nimport type { PDFReaderOptions } from '@happyvertical/pdf';\nimport type { GetTranscriberOptions } from '@happyvertical/speech';\nimport type { AnalysisOutput } from './dto.js';\nimport {\n ExtractionFailure,\n emptyExtraction,\n validateExtractionRequest,\n} from './extraction-providers.js';\nimport type {\n ExtractionAdapter,\n ExtractionRequest,\n ExtractionResult,\n ProviderIdentity,\n} from './extraction-types.js';\nimport { providerIdentity } from './extraction-types.js';\nimport type { AnalysisLease, IngestionService } from './server.js';\n\nexport type * from './extraction-types.js';\n\n/** Trusted server configuration. Credentials never enter analysis provenance. */\nexport interface ExtractionSDKConfiguration {\n pdf?: {\n provider: NonNullable<PDFReaderOptions['provider']>;\n identity: ProviderIdentity;\n };\n ocr?: { identity: ProviderIdentity; options?: Record<string, unknown> };\n speech?: { identity: ProviderIdentity; options: GetTranscriberOptions };\n vision?: { identity: ProviderIdentity; options: GetAIOptions };\n imageMode?: 'ocr' | 'vision';\n /** Maximum concurrent child processes for this adapter instance (default 1). */\n maxConcurrentProcesses?: number;\n /** The deployment enforces a native-memory ceiling outside Node (e.g. container).\n * Required for native decoders: Node's heap cap does not bound native allocation. */\n nativeMemoryIsolation: 'host-enforced';\n}\n\n/** Production adapter: bounded per-evidence child, terminated on deadline/abort. */\nexport function createSDKExtractionAdapter(\n configuration: ExtractionSDKConfiguration,\n): ExtractionAdapter {\n try {\n configuration = structuredClone(configuration);\n } catch {\n throw new Error('Serializable SDK configuration required');\n }\n const maximum = configuration.maxConcurrentProcesses ?? 1;\n if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 32)\n throw new Error('Invalid extraction concurrency');\n let running = 0;\n if (configuration.nativeMemoryIsolation !== 'host-enforced')\n throw new Error('Native memory isolation is required');\n for (const provider of [\n configuration.pdf,\n configuration.ocr,\n configuration.speech,\n configuration.vision,\n ]) {\n if (provider) provider.identity = providerIdentity(provider.identity);\n }\n if (\n configuration.pdf?.provider === 'auto' ||\n configuration.ocr?.identity.provider === 'auto'\n )\n throw new Error('Pin extraction providers');\n return {\n async extract(request) {\n let latest = emptyExtraction(request);\n try {\n validateExtractionRequest(request);\n } catch (caught) {\n if (!(caught instanceof ExtractionFailure)) throw caught;\n latest.errors.push({\n category: caught.category,\n location: { kind: 'source' },\n });\n return latest;\n }\n if (request.evidence.mediaType.toLowerCase().startsWith('video/')) {\n latest.status = 'unsupported';\n latest.errors.push({\n category: 'unsupported_type',\n location: { kind: 'source' },\n });\n return latest;\n }\n if (request.signal?.aborted) {\n latest.errors.push({\n category: 'cancelled',\n location: { kind: 'source' },\n });\n return latest;\n }\n if (running >= maximum) {\n latest.errors.push({ category: 'limit', location: { kind: 'source' } });\n return latest;\n }\n running++;\n return new Promise<ExtractionResult>((resolve) => {\n // A public entry can move shared code into chunks; resolve without loading it.\n const child = fork(\n join(\n dirname(\n fileURLToPath(\n import.meta.resolve('@happyvertical/smrt-ingestion/server'),\n ),\n ),\n 'extraction-worker.js',\n ),\n [],\n {\n serialization: 'advanced',\n stdio: ['ignore', 'ignore', 'ignore', 'ipc'],\n execArgv: [`--max-old-space-size=${request.limits.workerHeapMb}`],\n detached: process.platform !== 'win32',\n },\n );\n let done = false;\n const stop = () => {\n try {\n if (process.platform !== 'win32' && child.pid)\n process.kill(-child.pid, 'SIGKILL');\n else child.kill('SIGKILL');\n } catch {\n child.kill('SIGKILL');\n }\n };\n const finish = (\n category?: 'timeout' | 'cancelled' | 'unavailable' | 'limit',\n ) => {\n if (done) return;\n done = true;\n running--;\n clearTimeout(timer);\n request.signal?.removeEventListener('abort', abort);\n stop();\n if (category) {\n latest.errors.push({ category, location: { kind: 'source' } });\n latest.status = latest.segments.length ? 'partial' : 'failed';\n latest.truncated = true;\n latest.omitted.push({ kind: 'source' });\n }\n resolve(latest);\n };\n const abort = () => finish('cancelled');\n const timer = setTimeout(\n () => finish('timeout'),\n request.limits.timeoutMs,\n );\n request.signal?.addEventListener('abort', abort, { once: true });\n child.on('error', () => finish('unavailable'));\n child.on('exit', () => {\n if (!done) finish('unavailable');\n });\n child.on(\n 'message',\n async (message: {\n kind: string;\n id?: number;\n result?: ExtractionResult;\n }) => {\n if (done) return;\n if (\n message.kind === 'authorize' &&\n Number.isSafeInteger(message.id)\n ) {\n try {\n await request.beforeProviderCall?.();\n if (!done) child.send({ kind: 'authorized', id: message.id });\n } catch {\n finish('cancelled');\n }\n return;\n }\n if (\n (message.kind === 'progress' || message.kind === 'result') &&\n message.result\n ) {\n // The child is our trusted normalizer; bound serialized IPC output as well.\n if (\n Buffer.byteLength(JSON.stringify(message.result)) >\n request.limits.maxOutputBytes + 65536\n )\n return finish('limit');\n latest = message.result;\n if (message.kind === 'result') finish();\n } else finish('unavailable');\n },\n );\n const {\n signal: _signal,\n beforeProviderCall: _authorize,\n ...wireRequest\n } = request;\n child.send({ request: wireRequest, configuration }, (error) => {\n if (error) finish('unavailable');\n });\n if (request.signal?.aborted) abort();\n });\n },\n };\n}\n\nfunction validateAndNormalizeExtractionOutput(\n result: ExtractionResult,\n request: ExtractionRequest,\n): void {\n const numeric = (value: number) => Number.isFinite(value) && value >= 0;\n const location = (\n value: ExtractionResult['segments'][number]['location'],\n ) => {\n if (!value || typeof value !== 'object') return false;\n if (value.kind === 'source') return true;\n if (value.kind === 'page')\n return Number.isSafeInteger(value.page) && value.page > 0;\n if (value.kind === 'pages')\n return (\n Number.isSafeInteger(value.startPage) &&\n value.startPage > 0 &&\n Number.isSafeInteger(value.endPage) &&\n value.endPage >= value.startPage\n );\n return (\n value.kind === 'time' &&\n numeric(value.startMs) &&\n numeric(value.endMs) &&\n value.endMs >= value.startMs\n );\n };\n if (\n !result ||\n !['complete', 'partial', 'failed', 'unsupported'].includes(result.status) ||\n result.automaticActionEligible !== false ||\n result.configurationRevision !== request.configurationRevision ||\n !result.evidence ||\n Object.entries(request.evidence).some(\n ([key, value]) =>\n result.evidence[key as keyof typeof result.evidence] !== value,\n ) ||\n typeof result.truncated !== 'boolean' ||\n !Array.isArray(result.capabilities) ||\n result.capabilities.some(\n (capability) =>\n !capability ||\n typeof capability.confidence !== 'boolean' ||\n typeof capability.boxes !== 'boolean' ||\n !['source', 'page', 'time'].includes(capability.location) ||\n !['unknown', 'reported'].includes(capability.truncation) ||\n !['unknown', 'reported'].includes(capability.usage),\n ) ||\n !result.limits ||\n Object.entries(request.limits).some(\n ([key, value]) =>\n result.limits[key as keyof typeof result.limits] !== value,\n ) ||\n !Array.isArray(result.segments) ||\n !Array.isArray(result.errors) ||\n !Array.isArray(result.omitted) ||\n (result.status === 'complete' &&\n (result.truncated ||\n result.errors.length > 0 ||\n result.omitted.length > 0)) ||\n result.omitted.some((value) => !location(value)) ||\n result.segments.some(\n (segment) =>\n typeof segment.text !== 'string' ||\n !location(segment.location) ||\n segment.location.kind === 'pages' ||\n (segment.provenance?.provider === 'unlimited-ocr' &&\n (segment.confidence !== null || segment.boxes !== null)) ||\n !segment.provenance ||\n [\n segment.provenance.provider,\n segment.provenance.model,\n segment.provenance.version,\n ].some((value) => typeof value !== 'string' || !value) ||\n (segment.confidence !== null &&\n (!segment.confidence ||\n !numeric(segment.confidence.value) ||\n segment.confidence.value > 1 ||\n segment.confidence.scale !== '0-1' ||\n segment.confidence.calibration !== 'unknown')) ||\n (segment.boxes !== null &&\n (!Array.isArray(segment.boxes) ||\n segment.boxes.some(\n (box) =>\n typeof box.text !== 'string' ||\n ![box.x, box.y, box.width, box.height].every(numeric),\n ))),\n ) ||\n result.errors.some(\n (error) =>\n ![\n 'unsupported_type',\n 'malformed_output',\n 'limit',\n 'timeout',\n 'unavailable',\n 'authentication',\n 'cancelled',\n 'integrity',\n ].includes(error.category) || !location(error.location),\n ) ||\n !result.usage ||\n Object.values(result.usage).some((value) => !numeric(value))\n )\n throw new Error('Invalid extraction output');\n // Structural typing permits extra host fields. Never persist them as identity.\n for (const segment of result.segments)\n segment.provenance = providerIdentity(segment.provenance);\n result.capabilities = result.capabilities.map((capability) => ({\n ...providerIdentity(capability),\n confidence: capability.confidence,\n boxes: capability.boxes,\n location: capability.location,\n truncation: capability.truncation,\n usage: capability.usage,\n }));\n}\n\n/** Current access is rechecked on read and fenced publication by the foundation.\n * The host already allocated the immutable input/config revision and lease. */\nexport async function extractAnalysis(\n service: IngestionService,\n lease: AnalysisLease,\n adapter: ExtractionAdapter,\n options: Pick<\n ExtractionRequest,\n 'limits' | 'configurationRevision' | 'signal'\n >,\n): Promise<boolean> {\n const snapshot = await service.getAnalysisInput(lease);\n const persisted = snapshot.configuration.extraction as\n | { configurationRevision?: unknown; limits?: Record<string, unknown> }\n | undefined;\n if (\n !persisted ||\n persisted.configurationRevision !== options.configurationRevision ||\n !persisted.limits ||\n Object.keys(options.limits).some(\n (key) =>\n persisted.limits?.[key] !==\n options.limits[key as keyof typeof options.limits],\n ) ||\n Object.keys(persisted.limits).length !== Object.keys(options.limits).length\n )\n throw new Error('Extraction configuration mismatch');\n const evidence = snapshot.evidence;\n const boundOptions = { ...options, limits: structuredClone(options.limits) };\n const results: ExtractionResult[] = [];\n let limited = false;\n const publication = (reserve = false): AnalysisOutput => {\n const allComplete =\n !limited &&\n results.length === evidence.length &&\n results.every((result) => result.status === 'complete');\n const firstError =\n limited || reserve\n ? 'limit'\n : results.flatMap((result) => result.errors)[0]?.category;\n return {\n status: reserve\n ? 'needs_attention'\n : allComplete\n ? 'completed'\n : results.some((result) => result.segments.length)\n ? 'partial'\n : 'needs_attention',\n provider: 'smrt-ingestion-extraction',\n model: 'none',\n version: '1',\n output: {\n configurationRevision: options.configurationRevision,\n results,\n ...(limited || reserve\n ? {\n truncated: true,\n omittedEvidenceCount: evidence.length - results.length,\n }\n : {}),\n },\n usage: {},\n ...(firstError ? { error: firstError } : {}),\n };\n };\n // Canonical persistence sorts keys but uses identical JSON value encoding/size.\n const fits = (output: AnalysisOutput) =>\n Buffer.byteLength(JSON.stringify(output)) <= snapshot.maxOutputBytes;\n const minimum: AnalysisOutput = {\n status: 'needs_attention',\n provider: 'smrt-ingestion-extraction',\n model: 'none',\n version: '1',\n output: {},\n usage: {},\n error: 'limit',\n };\n if (!fits(minimum)) return service.failAnalysis(lease, 'limit');\n if (!fits(publication(true))) return service.completeAnalysis(lease, minimum);\n for (const part of evidence) {\n await service.getAnalysisInput(lease);\n const bytes = await service.readEvidence(lease.itemId, part.id);\n await service.getAnalysisInput(lease);\n const request = { ...boundOptions, evidence: part, bytes };\n const result = await adapter.extract({\n ...request,\n evidence: { ...part },\n limits: { ...request.limits },\n bytes: bytes.slice(),\n beforeProviderCall: async () => {\n await service.getAnalysisInput(lease);\n },\n });\n validateAndNormalizeExtractionOutput(result, request);\n results.push(result);\n if (!fits(publication(true))) {\n limited = true;\n // Preserve earlier parts and the largest prefix of complete segments that fits.\n result.status = 'partial';\n result.truncated = true;\n result.errors.push({ category: 'limit', location: { kind: 'source' } });\n while (result.segments.length && !fits(publication(true))) {\n const removed = result.segments.pop();\n if (removed) result.omitted.push(removed.location);\n }\n // Diagnostics are indivisible: omit this result rather than erase known gaps.\n if (!fits(publication(true))) results.pop();\n }\n // Revalidation after an external call prevents returning/publishing revoked evidence.\n await service.getAnalysisInput(lease);\n if (limited || options.signal?.aborted) break;\n }\n return service.completeAnalysis(lease, publication());\n}\n\n/**\n * A split's page groups failed the group check (empty, unknown or repeated\n * page, unordered). Generated splits that fail it are dropped (#4288); the\n * message is a fixed phrase, never page numbers.\n */\nexport class SplitGroupError extends Error {}\n/** Side-effect-free, versioned split proposal. Original evidence is not replaced. */\nexport function proposeDocumentSplits(\n result: ExtractionResult,\n revision: number,\n groups: number[][],\n) {\n if (!Number.isSafeInteger(revision) || revision < 1 || !groups.length)\n throw new Error('Invalid split revision');\n const available = new Set(\n result.segments.flatMap((segment) =>\n segment.location.kind === 'page' ? [segment.location.page] : [],\n ),\n );\n const seen = new Set<number>();\n for (const group of groups) {\n if (!group.length) throw new SplitGroupError('Empty split');\n for (const page of group) {\n if (!Number.isSafeInteger(page) || !available.has(page) || seen.has(page))\n throw new SplitGroupError('Invalid split page');\n seen.add(page);\n }\n if (group.some((page, index) => index > 0 && page <= group[index - 1]))\n throw new SplitGroupError('Unordered split');\n }\n const proposal = {\n revision,\n evidenceId: result.evidence.id,\n inputHash: result.evidence.contentHash,\n configurationRevision: result.configurationRevision,\n groups: groups.map((pages) => ({ pages: [...pages] })),\n status: 'proposed' as const,\n };\n return {\n ...proposal,\n digest: createHash('sha256').update(JSON.stringify(proposal)).digest('hex'),\n };\n}\n","import type { ProposalConfiguration } from './proposal-contracts.js';\n\n/** Validate deployment limits before any item is interpreted. */\nexport function assertProposalLimits(\n limits: ProposalConfiguration['limits'],\n): void {\n if (\n !limits ||\n [\n 'maxHandlers',\n 'maxCandidates',\n 'maxSuggestions',\n 'maxInputBytes',\n 'maxOutputBytes',\n 'maxQueryLength',\n 'timeoutMs',\n ].some(\n (key) =>\n !Number.isSafeInteger(limits[key as keyof typeof limits]) ||\n limits[key as keyof typeof limits] <= 0,\n ) ||\n limits.maxHandlers > 20 ||\n limits.maxCandidates > 20 ||\n limits.maxSuggestions > 20 ||\n limits.timeoutMs > 2_147_483_647\n )\n throw new Error('Invalid proposal limits');\n}\n","import type { DecisionClient } from '@happyvertical/smrt-core';\nimport type { HandlerContext } from './execution-contracts.js';\nimport type { IntakeValues } from './execution-dto.js';\nimport {\n type EvidenceLocation,\n type ProviderIdentity,\n providerIdentity,\n} from './extraction-types.js';\nimport type {\n ProposalCandidate,\n ProposalCatalogEntry,\n ProposalReferenceField,\n} from './proposal-dto.js';\n\n/** Optional discovery capability on the existing application execution handler. */\nexport interface HandlerDiscovery {\n mediaTypes: readonly string[];\n /** Every existing-record argument exposed to generation must be declared here. */\n references: Readonly<Record<string, ProposalReferenceField>>;\n /** Database reads only; filter in the query before ranking/summarizing. */\n candidates?(\n query: string,\n context: HandlerContext,\n page: { limit: number },\n ): Promise<{\n items: Array<Omit<ProposalCandidate, 'key'>>;\n hasMore: boolean;\n }>;\n}\nexport interface GenerationLimits {\n maxHandlers: number;\n maxCandidates: number;\n maxSuggestions: number;\n maxInputBytes: number;\n maxOutputBytes: number;\n maxQueryLength: number;\n timeoutMs: number;\n}\nexport interface GenerativeProposalInput {\n evidence: Array<{\n evidenceId: string;\n partId: string;\n parentEvidenceId: string | null;\n mediaType: string;\n contentHash: string;\n segments: Array<{ text: string; location: EvidenceLocation }>;\n }>;\n offered: Array<{\n handler: ProposalCatalogEntry;\n candidates: ProposalCandidate[];\n }>;\n instructions: string;\n /** Bounded, currently eligible examples; neither evidence nor authority. */\n examples?: import('./feedback-dto.js').FeedbackSelection;\n /** Authenticated human correction carried through fresh extraction; never model authority. */\n humanCorrection?: IntakeValues;\n /** Authenticated reviewer guidance; trusted steering only, never catalog or approval authority. */\n reviewerInstruction?: { id: string; text: string };\n}\n/** Inject only trusted SDK-bound adapters. Generative output is always untrusted. */\nexport interface ProposalGenerator {\n identity: ProviderIdentity;\n generate(\n input: GenerativeProposalInput,\n options: { signal: AbortSignal; maxOutputBytes: number },\n ): Promise<{\n output: unknown;\n completion: 'complete' | 'unknown';\n usage?: Record<string, number>;\n /** Provider-reported immutable model revision, when it safely resolves a configured alias. */\n responseModel?: string;\n }>;\n}\n/**\n * How validated decision answers affect readiness. `gate` (default) sends a\n * suggestion to `needs_review` when the thresholds are not met; `record` still\n * runs and persists the same answers but leaves outcome/disposition to the\n * validator. Neither mode makes any action automation-eligible.\n */\nexport type DecisionReadiness = 'gate' | 'record';\n/** Public decision settings shared by generation and read configuration. */\nexport interface DecisionSettings {\n minimumDecisionProbability?: number;\n tieMargin?: number;\n /**\n * Per-request token window forwarded to the decision client as `maxLen`\n * (the SDK Laya provider option). Absent keeps the client/checkpoint default.\n */\n decisionMaxLen?: number;\n decisionReadiness?: DecisionReadiness;\n}\nexport interface ProposalConfiguration extends DecisionSettings {\n version: string;\n promptVersion: string;\n generator: ProposalGenerator;\n /** Absent means the normal unconfigured decision path, never fake probability. */\n decision?: { client: DecisionClient; identity: ProviderIdentity };\n limits: GenerationLimits;\n /**\n * Opt-in, bounded, redacted capture of the model output on a failed\n * interpretation attempt (#4285). Text requires a host redactor; absent or\n * failed redaction retains no text. Off when absent. Not public read\n * configuration: it never enters frozen configuration, digests or\n * `proposalReadConfiguration`. See PROPOSALS.md.\n */\n failureCapture?: import('./failure-capture.js').FailureCaptureConfiguration;\n /**\n * Optional host checks on each validated suggestion (trusted, server-only).\n * Runs after validation and before the decision gate, with a copy of the\n * suggestion, its handler and the retained evidence text. The result can\n * only hold the suggestion at `needs_review` and record bounded, value-free\n * annotations; it can never upgrade a disposition or change args. A throw,\n * timeout or malformed result holds the suggestion with a fixed reason code.\n * Not public read configuration: it never enters frozen configuration or\n * digests. See PROPOSALS.md.\n */\n reviewSuggestion?: (\n input: SuggestionReviewInput,\n ) =>\n | HostSuggestionReviewResult\n | undefined\n | Promise<HostSuggestionReviewResult | undefined>;\n}\n/** A copy of what the host may inspect; mutating it changes nothing. */\nexport interface SuggestionReviewInput {\n suggestion: import('./proposal-dto.js').GeneratedSuggestion;\n handler: ProposalCatalogEntry;\n evidence: GenerativeProposalInput['evidence'];\n}\n/** Host result: bounded codes and argument field names only. */\nexport interface HostSuggestionReviewResult {\n /** Hold the suggestion at `needs_review`. */\n hold?: boolean;\n /** Up to 8 codes matching `^[a-z][a-z0-9_.-]{0,47}$`; never document values. */\n reasons?: string[];\n /** Argument names declared in the handler's `argsSchema` that the host filled itself. */\n prefilled?: string[];\n}\n/** Credential-free configuration for validating persisted proposal snapshots. */\nexport interface ProposalReadConfiguration extends DecisionSettings {\n version: string;\n promptVersion: string;\n generator: ProviderIdentity;\n decision?: ProviderIdentity;\n limits: GenerationLimits;\n}\n/** Remove generation capability while preserving the public persisted configuration. */\nexport function proposalReadConfiguration(\n config: ProposalConfiguration | ProposalReadConfiguration,\n): ProposalReadConfiguration {\n const generator = providerIdentity(\n 'identity' in config.generator\n ? config.generator.identity\n : config.generator,\n );\n return {\n version: config.version,\n promptVersion: config.promptVersion,\n generator,\n ...(config.decision\n ? {\n decision: providerIdentity(\n 'identity' in config.decision\n ? config.decision.identity\n : config.decision,\n ),\n }\n : {}),\n ...(config.minimumDecisionProbability === undefined\n ? {}\n : { minimumDecisionProbability: config.minimumDecisionProbability }),\n ...(config.tieMargin === undefined ? {} : { tieMargin: config.tieMargin }),\n ...(config.decisionMaxLen === undefined\n ? {}\n : { decisionMaxLen: config.decisionMaxLen }),\n ...(config.decisionReadiness === undefined\n ? {}\n : { decisionReadiness: config.decisionReadiness }),\n limits: {\n maxHandlers: config.limits.maxHandlers,\n maxCandidates: config.limits.maxCandidates,\n maxSuggestions: config.limits.maxSuggestions,\n maxInputBytes: config.limits.maxInputBytes,\n maxOutputBytes: config.limits.maxOutputBytes,\n maxQueryLength: config.limits.maxQueryLength,\n timeoutMs: config.limits.timeoutMs,\n },\n };\n}\nexport interface GenerationStageConfiguration extends IntakeValues {\n stage: 'interpret';\n /** Copied from the pinned extraction source; verified against it before provider disclosure. */\n reviewerInstruction?: IntakeValues;\n proposals: {\n source: import('./proposal-dto.js').GenerationSourcePin;\n configurationVersion: string;\n promptVersion: string;\n catalogDigest: string;\n generator: ProviderIdentity;\n decision: ProviderIdentity | null;\n limits: GenerationLimits;\n minimumDecisionProbability: number;\n tieMargin: number;\n /** Present only when configured, so default digests stay stable. */\n decisionMaxLen?: number;\n /** Present only for `record`; `gate` is the default. */\n decisionReadiness?: 'record';\n };\n}\n"],"mappings":";;;;;;AA0CO,SAAS,2BACd,eACmB;CACnB,IAAI;EACF,gBAAgB,gBAAgB,aAAa;CAC/C,QAAQ;EACN,MAAM,IAAI,MAAM,yCAAyC;CAC3D;CACA,MAAM,UAAU,cAAc,0BAA0B;CACxD,IAAI,CAAC,OAAO,cAAc,OAAO,KAAK,UAAU,KAAK,UAAU,IAC7D,MAAM,IAAI,MAAM,gCAAgC;CAClD,IAAI,UAAU;CACd,IAAI,cAAc,0BAA0B,iBAC1C,MAAM,IAAI,MAAM,qCAAqC;CACvD,KAAA,MAAW,YAAY;EACrB,cAAc;EACd,cAAc;EACd,cAAc;EACd,cAAc;CAChB,GACE,IAAI,UAAU,SAAS,WAAW,iBAAiB,SAAS,QAAQ;CAEtE,IACE,cAAc,KAAK,aAAa,UAChC,cAAc,KAAK,SAAS,aAAa,QAEzC,MAAM,IAAI,MAAM,0BAA0B;CAC5C,OAAO,EACL,MAAM,QAAQ,SAAS;EACrB,IAAI,SAAS,gBAAgB,OAAO;EACpC,IAAI;GACF,0BAA0B,OAAO;EACnC,S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EACA;EACA;EACA;CACF,CAAA,CAAE,MACC,QACC,CAAC,OAAO,cAAc,OAAO,IAA2B,KACxD,OAAO,QAA+B,CAC1C,KACA,OAAO,cAAc,MACrB,OAAO,gBAAgB,MACvB,OAAO,iBAAiB,MACxB,OAAO,YAAY,YAEnB,MAAM,IAAI,MAAM,yBAAyB;AAC7C;;;ACwHO,SAAS,0BACd,QAC2B;CAC3B,MAAM,YAAY,iBAChB,cAAc,OAAO,YACjB,OAAO,UAAU,WACjB,OAAO,SACb;CACA,OAAO;EACL,SAAS,OAAO;EAChB,eAAe,OAAO;EACtB;EACA,GAAI,OAAO,WACP,EACE,UAAU,iBACR,cAAc,OAAO,WACjB,OAAO,SAAS,WAChB,OAAO,QACb,EACF,IACA,CAAC;EACL,GAAI,OAAO,+BAA+B,KAAA,IACtC,CAAC,IACD,EAAE,4BAA4B,OAAO,2BAA2B;EACpE,GAAI,OAAO,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,OAAO,UAAU;EACxE,GAAI,OAAO,mBAAmB,KAAA,IAC1B,CAAC,IACD,EAAE,gBAAgB,OAAO,eAAe;EAC5C,GAAI,OAAO,sBAAsB,KAAA,IAC7B,CAAC,IACD,EAAE,mBAAmB,OAAO,kBAAkB;EAClD,QAAQ;GACN,aAAa,OAAO,OAAO;GAC3B,eAAe,OAAO,OAAO;GAC7B,gBAAgB,OAAO,OAAO;GAC9B,eAAe,OAAO,OAAO;GAC7B,gBAAgB,OAAO,OAAO;GAC9B,gBAAgB,OAAO,OAAO;GAC9B,WAAW,OAAO,OAAO;EAC3B;CACF;AACF"}
@@ -0,0 +1,19 @@
1
+ import type { IntakeValues } from './execution-dto.js';
2
+ import type { HostSuggestionReview } from './proposal-dto.js';
3
+ /** At most this many reason codes per suggestion. */
4
+ export declare const HOST_REVIEW_MAX_REASONS = 8;
5
+ /** A reason code: lowercase, starts with a letter, bounded; no spaces or punctuation beyond `_ . -`. */
6
+ export declare const HOST_REVIEW_REASON_PATTERN: RegExp;
7
+ /** Codes the service itself records when the hook fails; hosts may not need to emit them. */
8
+ export declare const HOST_REVIEW_FAILED = "host_review_failed";
9
+ export declare const HOST_REVIEW_INVALID = "host_review_invalid";
10
+ /**
11
+ * Normalize a host `reviewSuggestion` result into the stored, value-free shape.
12
+ * Throws on anything unexpected so the caller can hold the suggestion: only
13
+ * `{hold?, reasons?, prefilled?}` is accepted, `prefilled` entries must be the
14
+ * handler's declared argument names, reasons are bounded codes, and a reason
15
+ * that contains one of the suggestion's own argument values is refused.
16
+ * Returns undefined when the host recorded nothing.
17
+ */
18
+ export declare function normalizeHostReview(result: unknown, argsSchema: IntakeValues, args: IntakeValues): HostSuggestionReview | undefined;
19
+ //# sourceMappingURL=host-review.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-review.d.ts","sourceRoot":"","sources":["../src/host-review.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,qDAAqD;AACrD,eAAO,MAAM,uBAAuB,IAAI,CAAC;AACzC,wGAAwG;AACxG,eAAO,MAAM,0BAA0B,QAA6B,CAAC;AACrE,6FAA6F;AAC7F,eAAO,MAAM,kBAAkB,uBAAuB,CAAC;AACvD,eAAO,MAAM,mBAAmB,wBAAwB,CAAC;AAEzD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,OAAO,EACf,UAAU,EAAE,YAAY,EACxB,IAAI,EAAE,YAAY,GACjB,oBAAoB,GAAG,SAAS,CAmDlC"}
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-ingestion",
5
- "packageVersion": "0.57.31",
5
+ "packageVersion": "0.57.33",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-ingestion:IntakeItem": {
8
8
  "name": "intakeitem",