@happyvertical/smrt-ingestion 0.57.24 → 0.57.26
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/PROPOSALS.md +22 -1
- package/dist/chunks/{proposal-contracts-77Uo1B1j.js → proposal-contracts-CqVVPvqq.js} +6 -5
- package/dist/chunks/proposal-contracts-CqVVPvqq.js.map +1 -0
- package/dist/extraction.d.ts +7 -0
- package/dist/extraction.d.ts.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/models.js +1 -1
- package/dist/models.js.map +1 -1
- package/dist/proposal-dto.d.ts +13 -0
- package/dist/proposal-dto.d.ts.map +1 -1
- package/dist/proposal-validation.d.ts +15 -1
- package/dist/proposal-validation.d.ts.map +1 -1
- package/dist/proposals.d.ts.map +1 -1
- package/dist/proposals.js +59 -8
- package/dist/proposals.js.map +1 -1
- package/dist/server.js +2 -2
- package/dist/smrt-knowledge.json +8 -8
- package/package.json +13 -13
- package/dist/chunks/proposal-contracts-77Uo1B1j.js.map +0 -1
package/dist/server.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { _ as listReadGate, d as GenerationSnapshotStaleError, f as GenerationSourceStaleError, g as generationSnapshotRead, l as UNFINISHED_ACTION_STATES, m as ProposalsNotConfiguredError, p as HandlerArgumentsInvalidError, u as redactedCeiling } from "./chunks/execution-BzVQax0n.js";
|
|
2
2
|
import "./models.js";
|
|
3
3
|
import { r as extractWithProviders } from "./chunks/extraction-providers-C66ADDVe.js";
|
|
4
|
-
import { a as
|
|
4
|
+
import { a as extractAnalysis, i as createSDKExtractionAdapter, n as assertProposalLimits, o as proposeDocumentSplits, r as SplitGroupError, t as proposalReadConfiguration } from "./chunks/proposal-contracts-CqVVPvqq.js";
|
|
5
5
|
import { i as reviewerInstructionView, n as ReviewerInstructionInvalidError, r as ReviewerInstructionStaleError, t as REVIEWER_INSTRUCTION_MAX_LENGTH } from "./chunks/reviewer-instruction-CEc3AOuU.js";
|
|
6
6
|
import { detectEngine, isEmbeddedDatabase, isTransientDatabaseError, withEmbeddedWriteTransaction } from "@happyvertical/smrt-core";
|
|
7
7
|
import { withTenant } from "@happyvertical/smrt-tenancy";
|
|
@@ -3126,6 +3126,6 @@ var IngestionService = class {
|
|
|
3126
3126
|
}
|
|
3127
3127
|
};
|
|
3128
3128
|
//#endregion
|
|
3129
|
-
export { EmailSourceAdapter, GenerationSnapshotStaleError, GenerationSourceStaleError, HandlerArgumentsInvalidError, ITEM_ID_FILTER_CEILING, ITEM_PAGE_CEILING, ITEM_SCAN_CEILING, IngestionService, IntakeScanLimitError, ProposalsNotConfiguredError, REVIEWER_INSTRUCTION_MAX_LENGTH, ReviewerInstructionInvalidError, ReviewerInstructionStaleError, WatchFolderSourceAdapter, createIntakeReviewHost, createSDKExtractionAdapter, createSourceDeliveryHandler, createVendorWebhookHandler, extractAnalysis, isIntakeId, proposeDocumentSplits, reviewerInstructionView };
|
|
3129
|
+
export { EmailSourceAdapter, GenerationSnapshotStaleError, GenerationSourceStaleError, HandlerArgumentsInvalidError, ITEM_ID_FILTER_CEILING, ITEM_PAGE_CEILING, ITEM_SCAN_CEILING, IngestionService, IntakeScanLimitError, ProposalsNotConfiguredError, REVIEWER_INSTRUCTION_MAX_LENGTH, ReviewerInstructionInvalidError, ReviewerInstructionStaleError, SplitGroupError, WatchFolderSourceAdapter, createIntakeReviewHost, createSDKExtractionAdapter, createSourceDeliveryHandler, createVendorWebhookHandler, extractAnalysis, isIntakeId, proposeDocumentSplits, reviewerInstructionView };
|
|
3130
3130
|
|
|
3131
3131
|
//# sourceMappingURL=server.js.map
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,21 +3,21 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-ingestion",
|
|
6
|
-
"packageVersion": "0.57.
|
|
6
|
+
"packageVersion": "0.57.26",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
10
|
+
"manifest": "91d53afb18145e7b066e41f96b0348275556ee03772200ed45bad94d03104412",
|
|
11
|
+
"packageJson": "bfba9f207df65188331d72fa3baccdb6908d59b44453affefd64ca85860e3992",
|
|
12
12
|
"agents": "dea14442054ec1de798cba9be1fbdd955f44b0e4672639cbf3db8101d290c1fb",
|
|
13
13
|
"moduleDoc:agents/execution.md": "fff49dd30d7b1dc8437c8963e5aa2158d1c6d37151de64699f0fa109749cb64b",
|
|
14
14
|
"moduleDoc:README.md": "fc8530af1861c894ec89423e1863ff5bbddf94f1fd7fdea8ea68dc6c48c3de79",
|
|
15
15
|
"moduleDoc:EXTRACTION.md": "b735a25a7be75f3a13f3f9e92b0c25834c1394835c16ccd73a076d5720c14243",
|
|
16
|
-
"moduleDoc:PROPOSALS.md": "
|
|
16
|
+
"moduleDoc:PROPOSALS.md": "3bf9feb10797393d07be27d8e4ac46bb8b442bc4cffaa715d30ef7b828ffd578",
|
|
17
17
|
"moduleDoc:FEEDBACK.md": "275bc853f46611d552cef067985117db5aebd7929ce7292e3f1ec5c0628fc14a",
|
|
18
18
|
"moduleDoc:REVIEW.md": "71868ff0dc39fda61d9df6b9ddfff6fe09385bed420c9d6718d8ec36dfc97db0",
|
|
19
19
|
"agentSurface:src/test-support/execution.ts": "4aeaf95fb12faa2c7fb5a3c9aa8b210ce2636e62c766cb520a97f095bba99a36",
|
|
20
|
-
"agentSurface:src/test-support/proposals.ts": "
|
|
20
|
+
"agentSurface:src/test-support/proposals.ts": "746c63ca16e65c3641fbdc18eea8d9c6d79bb1ac128d3d70fed8696e66d33082"
|
|
21
21
|
},
|
|
22
22
|
"exports": [
|
|
23
23
|
".",
|
|
@@ -1720,7 +1720,7 @@
|
|
|
1720
1720
|
{
|
|
1721
1721
|
"path": "PROPOSALS.md",
|
|
1722
1722
|
"module": "PROPOSALS",
|
|
1723
|
-
"content": "# Application-aware proposal generation\n\n`@happyvertical/smrt-ingestion/proposals` is server-only. Configure\n`IngestionOptions.proposals` and the existing `execution.handlers` catalog.\nHandlers opt into discovery with `discovery.mediaTypes`, `references`, and an\noptional `candidates` callback. There is one catalog: the same operation or\nordered playbook adapter is discovered, validated, previewed, and later applied\nby the execution service. Generation never approves or applies.\n\nCredential-free review hosts may configure `IngestionOptions.proposalRead` with\n`ProposalReadConfiguration`: public generator/decision identities, version,\nprompt version, limits and thresholds only. It reads completed proposals,\npreserves current authority and snapshot validation, and permits human preview;\nit never accepts a generator or provider client. If a process supplies both\nsettings, their public configuration must match exactly. Preparing or generating\nproposals still requires `proposals` with a real generator.\n\n## Discovery and authority\n\n`listHandlers(itemId)` returns a bounded detached catalog. The owning execution\nservice checks the current principal, captured permissions/handler/operation\nceiling, policy, confidential scope, public registered operation facts, and\nordered playbook definition. Every configured provider must occur in the current\npolicy's `providers` allowlist. Missing grants remove handlers before model input.\nAn authorized catalog larger than the configured bound is rejected; the host must\nnarrow it explicitly instead of relying on silent truncation.\n\n`findCandidates({itemId,handlerId,handlerVersion,query,limit})` returns\n`{items,truncated}`. Its trusted handler callback receives `HandlerContext` with\nthe authorized transaction executor. Query by tenant and confidential scope\n**before** selecting, ranking, or building labels. Use a bounded query (often\n`limit + 1`) and report `hasMore`. The service projects candidate identity, model,\nrevision and label, then checks every target with the owning execution callback.\nThere are no hidden counts or pagination tokens. Truncated discovery forces\n`needs_review`; a person may still preview it explicitly, and automation never\nbecomes eligible.\n\nCompleted generation reload checks process authority, the current attempt, and\nowner/candidate visibility in the same final transaction. Database-backed grant\ncallbacks must use the supplied executor. The owning retention lifecycle encloses\nthat transaction so a denied read cannot roll back an authorized shorter privacy\nceiling; restoration starts only after the outer transaction has rolled back.\n\nCandidate callbacks perform bounded database reads only: no provider I/O, network,\nor domain mutations. Target locks and existing retention enforcement remain\nowned by execution. Hosts configure their database's statement deadlines; an\narbitrary trusted callback is not a sandbox. Each existing-record argument must\nbe a declared top-level `references` field of kind `candidate` with its qualified\nmodel, or `evidence`. Closed JSON argument schemas are required. The host owns\nthat declaration and its target authorization semantics.\n\n## Durable stages\n\n1. Complete extraction through the existing analysis ledger.\n2. Call `prepareGeneration(itemId, extractionAttemptId)`. It reads the current\n completed/partial immutable extraction and returns configuration with\n `stage: 'interpret'`, pinned source attempt/revision/input/output/evidence\n digests, prompt/configuration/catalog/provider versions, limits and thresholds.\n3. Pass that configuration to `analyze(itemId, configuration, requestKey)` and\n claim its new revision with `claimAnalysis`.\n4. The host's existing job callback routes on the frozen `configuration.stage`:\n extraction invokes `extractAnalysis`; interpretation invokes\n `generateProposals(lease)`.\n5. Reload the current completed generation using `getCompletedAnalysis(itemId)`,\n or pass an explicit attempt ID to additionally reject stale client state.\n Queued/running revisions never return an older completed attempt.\n\n`analyze` refuses an interpretation configuration whose pinned source is not\nthe item's latest extraction, checked under the item lock before anything is\nsuperseded (`GenerationSourceStaleError`, nothing appended). A preparation\nsuperseded by a later extraction therefore fails at append time rather than\nafter a revision was created.\n\nA generation revision does not rewrite terminal extraction. Reprocessing starts\nwith a new extraction revision, followed by interpretation, while the host keeps\nthe same business intention keys. An interrupted still-current generation lease\ncan be retried; terminal generation output remains immutable. `getGenerationInput`\nreads historical extraction only through the current generation lease and its\nfrozen source pin. It verifies same-item scope, immutable hashes, durable evidence,\nand current process permission before returning detached data. The source must be\nthe immediately preceding revision, so an intervening reprocess invalidates a\nprepared generation. Completed generation reads additionally recheck current\ncatalog and target visibility before disclosing persisted candidate labels.\nExpired, cancelled, revoked, retried or superseded workers cannot read or publish late output. The\ncurrent lease and each offered handler/candidate are rechecked immediately before\neach outbound generative/decision boundary and before publication.\n\n### Inline interpretation\n\nReceipts created with `dispatch: 'inline'` (text/structured parts only) run the\nsame stages in-process through `interpretInline(itemId, { requestId, extraction\n})`: an immutable extraction revision claimed under a fenced lease and extracted\nwith the built-in UTF-8 extractor, then `prepareGeneration` and a fenced\ninterpretation revision generated by `generateProposals`. The analysis lease,\ncatalog digest and live catalog/candidate checks, source pin, provenance and\n`StageFailure` categories are identical to the job path; no dispatch intent is\never deliverable and nothing is enqueued. A retry with the same `requestId`\nreplays the recorded revisions rather than re-preparing against a superseded\nsource, also under concurrency. The interpretation append rechecks, under the\nitem lock, that its pinned extraction is still the latest revision and refuses\na superseded pin: first through the general latest-extraction check that\nevery interpretation append runs (`GenerationSourceStaleError`), then by the\ninline check that the pinned attempt is still current (`Generation source changed`). Generated suggestions still require explicit preview and a human\ndecision, either through the reviewer surface or the submitter-scoped surface\ndescribed in [REVIEW.md](REVIEW.md).\n\n## Providers and validation\n\n`createSDKProposalGenerator(client, identity, {maxTokens,timeoutMs})` uses an\nexisting AI SDK `chat` client. It sends a fixed system instruction and separate\nJSON evidence/catalog data, requests JSON, supplies cancellation and bounds, uses\nno tools or continuation, and rejects known truncation or tool calls,\nunexpected models, malformed JSON and oversized output. Configure SDK clients\nwithout automatic retry that would bypass application boundary checks. The\nadapter's public identity is exactly provider/model/version; credentials and raw\nprovider errors are never provenance.\n\nA trusted custom `ProposalGenerator` must likewise honor cancellation, bound its\nresponse, and explicitly declare validated `complete` or `unknown` completion.\nThe SDK currently normalizes missing/unknown finish reasons to `stop`\n([owning SDK follow-up](https://github.com/happyvertical/sdk/issues/1381)), so its\nadapter conservatively declares `unknown`, persisted as\n`generation_completion_unknown`. Otherwise valid suggestions remain available\nfor human preview; automatic eligibility always remains false. The service\ndeadline aborts requests and prevents late publication; it does not claim to terminate computation at a remote\nprovider or isolate native allocations. Extractor process limits remain separate.\n\nWhen the pinned extraction carries an authenticated reviewer instruction\n(REVIEW.md), `prepareGeneration` copies it into the interpretation configuration\nand `generateProposals` verifies that copy against the extraction record and its\nown digest before provider disclosure (`integrity` otherwise). The prompt then\ncarries it in its own **trusted reviewer guidance** section after the fixed\nsystem instruction and handler contract: the guidance is named as authenticated\nhuman input, limited to the offered catalog, and the evidence remains untrusted\ndata. `GenerativeProposalInput.reviewerInstruction` exposes `{id, text}` to custom\ngenerators; `provenance.reviewerInstruction` records `{id, digest}`. The\ninstruction never changes `offered`, `catalogDigest`, argument schemas,\npermissions or `automaticActionEligible`; a reply that follows guidance outside\nthe catalog fails validation like any other hostile output. **Budget cost:** the instruction counts once against the input budget\n(`maxInputBytes`, each offered handler's `maxBytes` and the live policy\nceiling), as its JSON-escaped text inside the prompt's guidance section — up\nto 4,000 characters plus escaping and the fixed guidance sentence. The\n`reviewerInstruction` field duplicated for custom generators is not counted\nagain. The decision stage also carries it once: its request state holds the\nevidence-side input with the un-guided base instructions under `evidence`, and\nthe guidance only under a separate `reviewerGuidance` key, never under\n`evidence`; the decision budget measures that serialized request as sent. Size `maxInputBytes` with that headroom. Learned examples are\nstill retrieved for an instructed generation; only a logical split correction\nsuppresses them. Every instruction costs a fresh extraction revision before the\nnew interpretation: the predecessor-pin contract above (source = immediately\npreceding revision, current-revision reads) is deliberately left intact rather\nthan reused for a same-source second interpretation, so OCR/speech hosts budget\none extraction per instruction, as for split corrections.\n\nModel output can contain only offered handler versions, schema-valid arguments,\nretained evidence locations and offered alternative handler/candidate keys.\nCandidate IDs must occur in the offered set, and evidence IDs in retained source\nresults. Unknown enums, invented IDs, extra authority/tool/approval fields and\nmalformed structures fail closed. Missing required top-level fields are retained\nas `missingFields`, with `needs_review`; values are never invented to satisfy a\nschema. Observed page/time/source granularity is preserved. Logical scan splits\nuse `proposeDocumentSplits`; originals and hashes remain intact.\n\nA rejected reply ends the attempt as `provider_error` with the `malformed_output`\nwarning and a bounded, value-free `provenance.failure` `{category, reason}` (#4207).\nThe reason lists schema-owned paths, keywords and schema constants, for example\n`/outcome enum (allowedValues=proposals|unknown|...)` and\n`/suggestions/0 required (missingProperty=evidence)`, or the fixed internal check\nand its path, such as `Unoffered handler: /suggestions/0`. Path segments are\nkept only when they are keys declared under the schema's `properties` or\nindexes into a value that actually is an array in the rejected reply; any other\nsegment, numeric or not (for example a key under an open\n`additionalProperties` argument sub-schema, or a numeric key of an object),\nbecomes `?`, and an extra property's name is never echoed.\nIt never contains document text, argument values, evidence content or\nmodel-chosen keys, is cut at 1000 characters,\nand is dropped before the output-limit fallback. Hosts read it from the\ncompleted/partial analysis at `analysis.result.output.proposals.provenance.failure`.\nThe SDK adapter constrains replies with a `json_schema` response format built\nfrom the validator's schema and the fixed instructions describe the shape; a\ncustom `ProposalGenerator` receives no schema, so its raw reply meets the\nvalidator directly and the same reason is recorded.\nThe provider-facing schema is made portable (`portableResponseSchema`, #4260):\nkeywords that common OpenAI-compatible structured-output backends reject are\nremoved at schema positions, including inside handler argument schemas\n(`uniqueItems`, `contains`, `multipleOf`, `format`, `patternProperties`,\n`propertyNames`, `min`/`maxProperties`, `not`, `if`/`then`/`else`,\n`dependent*`, `unevaluated*`, and the `default`/`examples` annotations; the\nfull list and reasons are in `src/proposal-sdk.ts`). With `uniqueItems`, for\nexample, vLLM's xgrammar feature check flags the schema, its auto mode routes\nit to llguidance, and llguidance answers\n`400 Grammar error: Unimplemented keys: [\"uniqueItems\"]`. This only loosens the\ngrammar: the validator still enforces the constraints, including unique\n`alternatives` and `missingFields`, and the fixed instructions ask for distinct\nentries. The exception is `format`, which is advisory: the validator runs Ajv\nwith `validateFormats: false`, so `format` is enforced nowhere. When\n`patternProperties` is removed, the same object's `additionalProperties` is\nremoved too, so the grammar does not shrink to `{}`. The `contentSchema` annotation is omitted as well, so nested unsupported\nconstraints cannot leak through an unvisited schema position. A backend may\nrecursively inspect typed schema-like objects even inside `enum` or `const`\ndata. When such data contains an unsupported keyword, the whole containing\n`enum`/`const` constraint is omitted conservatively; literal data is never\nrewritten. Harmless property names and ordinary enum/const data stay intact.\nThe original validator remains authoritative for omitted literal constraints.\nThere is no automatic `json_object` fallback.\n\nInvariant: the provider copy only ever accepts a superset of what the original\naccepts. Each removed keyword is a conjunct, so removing it only widens. The two\nplaces where removal would narrow are rewritten:\n- every `oneOf` becomes `anyOf` (or joins an existing `anyOf` through `allOf`),\n because loosened `oneOf` branches could both match and reject a value the\n original accepted;\n- an object that loses `patternProperties` also loses `additionalProperties`.\n\nProvider-only `$ref`, `$dynamicRef`, and `$recursiveRef` constraints are also\nremoved. Rewriting or deleting a subschema can invalidate pointer or anchor\ntargets, including targets inside nested `$id` resources. Dropping references\nconservatively widens the grammar without resolving untrusted schema resources;\nproperty names and enum/const data named `$ref` remain unchanged. Referenced\nconstraints, recursion, and dynamic scope remain enforced by the original\nvalidator, so provider guidance for reference-based arguments is less precise.\n\nThe validator still checks the original, including `oneOf` exclusivity. A\nproperty-style regression checks original-valid ⇒ portable-valid across the\nremoved keywords. Handler argument schemas may still carry `allOf` through\nunchanged; its support across backends is unverified, so check such a handler\nagainst the deployed backend.\n\nA generator call that throws ends the attempt as `provider_error` with the\n`unavailable` warning and `provenance.failure` `{category: 'unavailable',\nreason}`. The reason is value-free by construction: a provider's own text can\nquote the prompt or document, so it is never copied. The reason is built only\nfrom a fixed phrase and, for an SDK `AIError` only, the HTTP status (from a\nstructured field, or from the exact `<status> ...` / `TypeSafe request failed\n(<status>): ...` shapes the SDK produces), the SDK error code (from the closed\nlist of codes the SDK raises) and, for a schema rejection, quoted tokens that\nare JSON Schema keywords. Any other error contributes at most a structured\nnumeric status. For example: `provider rejected the response schema (HTTP 400,\ncode API_ERROR); unsupported response-schema keywords: uniqueItems`, or just\n`provider call failed`. It is cut at 500 characters.\n\n`createSDKProposalDecisionClient(client)` adapts an existing SDK client’s optional\ncapability without changing its errors or protocol. Optional `decision` uses public core `executeDecision` and the existing SDK\npredicate, choice, score and batch contracts. Supported-effect predicates,\nhandler classification, candidate entity matching, and action ambiguity/risk\nare distinct questions. Their validated probabilities and provenance are stored\nseparately from generative provenance and unknown OCR certainty. The complete\nserialized decision request, including suggestions and questions, must fit the\nminimum configured/current policy byte ceiling before capability probing and\nagain before deciding. A policy change between these boundaries fails closed.\nActually incomplete extraction always requires review. Unknown provider\ncompletion metadata is preserved as `source_completion_unknown`; it does not\nblock otherwise schema-valid **human** preview or imply completeness. Automatic\naction eligibility remains false. An unconfigured decision path\nis recorded explicitly. Configured errors produce a durable safe failure outcome;\nthey never silently switch to a generative decision fallback.\n\n### Decision readiness gate (#4209)\n\nFor every suggestion `i` the request asks `supported_i` (predicate),\n`route_i` (choice over the offered `handlerId@version` keys plus `none`),\n`risk_i` (ordered score over `clear`, `uncertain`, `ambiguous`) and one\n`entity_i_<field>` choice per candidate-reference argument. The validated\nanswers are always persisted under `provenance.decision.answers`. With the\ndefault `decisionReadiness: 'gate'` they are read as follows, and any failing\ncheck sets the suggestion to `needs_review` (a tie also sets the outcome to\n`ambiguous`):\n\n- `supported.probability >= minimumDecisionProbability` (default `0.8`).\n- `route.choice` equals the suggestion's own `handlerId@handlerVersion`,\n `route.confidence >= minimumDecisionProbability`, and the gap between the two\n largest route probabilities is greater than `tieMargin` (default `0.1`).\n- `risk.score < 1`: only the `clear` level passes; `uncertain` and `ambiguous`\n require review.\n- Each entity match chooses the suggested candidate's key with confidence at or\n above the threshold and a gap above `tieMargin`.\n\nThese values are provider outputs read as if they were calibrated\nprobabilities; nothing in this package calibrates them for this use. The\nteamworks-os measurement in #4209 (self-hosted Laya `typed-decisions`) found no\nseparation between right and wrong suggestions: a correctly read vendor invoice\nscored `supported` 0.37, garbage input 0.45–0.50, a wrongly proposed purchase\norder 0.51, route confidence 0.003–0.15 and `risk` ≥ 0.94, so the gate sent\nevery suggestion to review. Until a labelled sample shows separation, treat the\nanswers as diagnostics and configure:\n\n- `decisionMaxLen`: positive integer forwarded unchanged as the per-request\n `maxLen` of the decision client (the SDK Laya provider's token window; the\n checkpoint default is 1024 and the serialized evidence plus suggestions is\n otherwise truncated). Other clients ignore it.\n- `decisionReadiness: 'record'`: the decision still runs, is bounded and\n authorized exactly as before and its answers, usage, `readiness` and `maxLen`\n are recorded, but the gate never changes `outcome` or `disposition`; readiness\n comes from the validator alone (`missingFields`, outcome, source completeness).\n A client error or timeout is recorded as the `decision_unavailable`\n warning. A reply that comes back and then fails the core `executeDecision`\n identity or answer-shape check is recorded as `decision_malformed` with the\n reply's usage; this is the path for injected `DecisionClient`s. SDK clients,\n including the Laya provider behind `createSDKProposalDecisionClient`,\n validate the reply's shape inside `client.decide` and throw, so a malformed\n SDK reply is recorded as `decision_unavailable` with no usage. Every case\n records the `provenance.decision` identity. The generated suggestions stay\n as they were. The serialized request exceeding the byte budget is a\n configuration failure, not a provider answer: it ends the attempt as `limit`\n in both modes, and in `gate` mode every failure above still ends the attempt\n as `provider_error`. Lease, catalog, policy and provider-allowlist revocation\n fail closed in both modes.\n\nSuccessful output also records `provenance.decision.readiness` (`'gate'` or\n`'record'`) and `maxLen` when set; configuration digests are unchanged, but\npersisted output is therefore not byte-identical to earlier releases.\n\nBoth settings are public configuration: they are part of\n`ProposalReadConfiguration`, the frozen `GenerationStageConfiguration.proposals`\n(present only when set, so existing digests are unchanged) and the completed\nsnapshot authority check. Invalid values fail at proposal service construction.\nNeither mode affects automation: `automaticActionEligible` stays `false`, and\n`authorizeAutomatic` reads only the host's `evaluateAutomatic` callback and\npolicy, never these answers.\n\nOutput records zero, one or multiple suggestions, alternatives, missing fields,\nsource links, proposed splits, versions, allowlisted usage, warnings and explicit\n`unknown`, `ambiguous`, `no_action`, `needs_review` or `provider_error` outcomes.\n`automaticActionEligible` is always false. Provider input/output and the complete\nserialized persisted envelope are bounded by configuration, live policy and the\nreceipt ceiling. Oversized output becomes a bounded review/limit result; when\nno safe envelope fits, the owning service records fixed `failAnalysis` metadata\noutside the provider payload budget without retaining provider output.\n\n## Explicit preview and stable intentions\n\nThe host chooses persisted suggestion indexes and calls:\n\n```ts\nawait service.previewGeneratedProposals({\n itemId,\n attemptId: generationAttemptId,\n selections: [{\n index: 0,\n intentionKey: 'document:meeting-2026-10-09',\n expectedRevision: 0,\n requestId: 'review-request-1',\n }],\n});\n```\n\n`intentionKey` is the host's stable business-intention identity across generation\nrevisions. Never derive a fresh key from model output, suggestion order or a retry.\nSelections must reference current persisted validated `ready_for_review` or\n`needs_review` output (#4208); a `provider_error` attempt, an unoffered handler or\na non-interpretation stage is rejected. A `needs_review` suggestion whose\n`missingFields` are still absent fails the handler schema inside the ordinary\npreview (`Invalid handler payload`) and publishes nothing; the reviewer supplies\nthe missing values through the explicit human path (`previewProposal` /\n`previewPlan`, as the published review host does for `preview({args})`), and the\nhandler's `validate` and `preview` run again on the completed arguments.\nEach batch requires distinct suggestion indexes and intention keys; duplicate\nindexes are rejected before any operation or plan preview is written.\nThe service rechecks current catalog/schema/target/source provenance, then calls\nthe existing operation or plan preview. Each result still requires the ordinary\nhuman review and execution APIs. Reprocessing creates no new business identity;\nsuccessful-action replay protection stays with execution.\n\n## Evidence and limits\n\nThe test matrix is `docs/test-matrix/3673-ingestion-proposals.md`. SQLite and real\nPostgreSQL suites exercise authority, revisions, abstention, hostile output,\ncompound proposals, split provenance and reviewed domain effects. The upload\nreference composes authenticated multipart delivery of a generated embedded-text\nPDF through the actual packaged PDF child, durable interpretation, and the existing\nordered ContentDocument draft/retained-asset plan. It checks duplicate delivery,\nunauthenticated and foreign-tenant denial, explicit approval of both steps,\nidempotent execution replay, page provenance, and unchanged original bytes.\nThe compound-email case uses a declared messages-owner snapshot fixture.\n\nLocal HTTP fixtures execute the actual AI SDK transport and cancellation contract.\nGenerative responses and the separate injected PDF split boundaries establish\ndeterministic orchestration, not model accuracy or OCR quality. No held-out routing\nevaluation or automatic approval is claimed. Missing/unknown AI completion remains\nexplicit under [SDK #1381](https://github.com/happyvertical/sdk/issues/1381).\n\nProposal limits are checked at `IngestionService` construction: positive safe\nintegers, at most 20 handlers/candidates/suggestions and 2147483647 ms timeout.\nInterpretation output uses the exported `GenerationAnalysisOutput` wrapper at\n`analysis.result.output.proposals`; the published review host unwraps it.\nAn explicit feedback `retrieve` denial omits optional examples and feedback\nprovenance and continues generation. Item/execution denials, unexpected failures,\nand revocation after examples were selected still fail closed before disclosure.\n"
|
|
1723
|
+
"content": "# Application-aware proposal generation\n\n`@happyvertical/smrt-ingestion/proposals` is server-only. Configure\n`IngestionOptions.proposals` and the existing `execution.handlers` catalog.\nHandlers opt into discovery with `discovery.mediaTypes`, `references`, and an\noptional `candidates` callback. There is one catalog: the same operation or\nordered playbook adapter is discovered, validated, previewed, and later applied\nby the execution service. Generation never approves or applies.\n\nCredential-free review hosts may configure `IngestionOptions.proposalRead` with\n`ProposalReadConfiguration`: public generator/decision identities, version,\nprompt version, limits and thresholds only. It reads completed proposals,\npreserves current authority and snapshot validation, and permits human preview;\nit never accepts a generator or provider client. If a process supplies both\nsettings, their public configuration must match exactly. Preparing or generating\nproposals still requires `proposals` with a real generator.\n\n## Discovery and authority\n\n`listHandlers(itemId)` returns a bounded detached catalog. The owning execution\nservice checks the current principal, captured permissions/handler/operation\nceiling, policy, confidential scope, public registered operation facts, and\nordered playbook definition. Every configured provider must occur in the current\npolicy's `providers` allowlist. Missing grants remove handlers before model input.\nAn authorized catalog larger than the configured bound is rejected; the host must\nnarrow it explicitly instead of relying on silent truncation.\n\n`findCandidates({itemId,handlerId,handlerVersion,query,limit})` returns\n`{items,truncated}`. Its trusted handler callback receives `HandlerContext` with\nthe authorized transaction executor. Query by tenant and confidential scope\n**before** selecting, ranking, or building labels. Use a bounded query (often\n`limit + 1`) and report `hasMore`. The service projects candidate identity, model,\nrevision and label, then checks every target with the owning execution callback.\nThere are no hidden counts or pagination tokens. Truncated discovery forces\n`needs_review`; a person may still preview it explicitly, and automation never\nbecomes eligible.\n\nCompleted generation reload checks process authority, the current attempt, and\nowner/candidate visibility in the same final transaction. Database-backed grant\ncallbacks must use the supplied executor. The owning retention lifecycle encloses\nthat transaction so a denied read cannot roll back an authorized shorter privacy\nceiling; restoration starts only after the outer transaction has rolled back.\n\nCandidate callbacks perform bounded database reads only: no provider I/O, network,\nor domain mutations. Target locks and existing retention enforcement remain\nowned by execution. Hosts configure their database's statement deadlines; an\narbitrary trusted callback is not a sandbox. Each existing-record argument must\nbe a declared top-level `references` field of kind `candidate` with its qualified\nmodel, or `evidence`. Closed JSON argument schemas are required. The host owns\nthat declaration and its target authorization semantics.\n\n## Durable stages\n\n1. Complete extraction through the existing analysis ledger.\n2. Call `prepareGeneration(itemId, extractionAttemptId)`. It reads the current\n completed/partial immutable extraction and returns configuration with\n `stage: 'interpret'`, pinned source attempt/revision/input/output/evidence\n digests, prompt/configuration/catalog/provider versions, limits and thresholds.\n3. Pass that configuration to `analyze(itemId, configuration, requestKey)` and\n claim its new revision with `claimAnalysis`.\n4. The host's existing job callback routes on the frozen `configuration.stage`:\n extraction invokes `extractAnalysis`; interpretation invokes\n `generateProposals(lease)`.\n5. Reload the current completed generation using `getCompletedAnalysis(itemId)`,\n or pass an explicit attempt ID to additionally reject stale client state.\n Queued/running revisions never return an older completed attempt.\n\n`analyze` refuses an interpretation configuration whose pinned source is not\nthe item's latest extraction, checked under the item lock before anything is\nsuperseded (`GenerationSourceStaleError`, nothing appended). A preparation\nsuperseded by a later extraction therefore fails at append time rather than\nafter a revision was created.\n\nA generation revision does not rewrite terminal extraction. Reprocessing starts\nwith a new extraction revision, followed by interpretation, while the host keeps\nthe same business intention keys. An interrupted still-current generation lease\ncan be retried; terminal generation output remains immutable. `getGenerationInput`\nreads historical extraction only through the current generation lease and its\nfrozen source pin. It verifies same-item scope, immutable hashes, durable evidence,\nand current process permission before returning detached data. The source must be\nthe immediately preceding revision, so an intervening reprocess invalidates a\nprepared generation. Completed generation reads additionally recheck current\ncatalog and target visibility before disclosing persisted candidate labels.\nExpired, cancelled, revoked, retried or superseded workers cannot read or publish late output. The\ncurrent lease and each offered handler/candidate are rechecked immediately before\neach outbound generative/decision boundary and before publication.\n\n### Inline interpretation\n\nReceipts created with `dispatch: 'inline'` (text/structured parts only) run the\nsame stages in-process through `interpretInline(itemId, { requestId, extraction\n})`: an immutable extraction revision claimed under a fenced lease and extracted\nwith the built-in UTF-8 extractor, then `prepareGeneration` and a fenced\ninterpretation revision generated by `generateProposals`. The analysis lease,\ncatalog digest and live catalog/candidate checks, source pin, provenance and\n`StageFailure` categories are identical to the job path; no dispatch intent is\never deliverable and nothing is enqueued. A retry with the same `requestId`\nreplays the recorded revisions rather than re-preparing against a superseded\nsource, also under concurrency. The interpretation append rechecks, under the\nitem lock, that its pinned extraction is still the latest revision and refuses\na superseded pin: first through the general latest-extraction check that\nevery interpretation append runs (`GenerationSourceStaleError`), then by the\ninline check that the pinned attempt is still current (`Generation source changed`). Generated suggestions still require explicit preview and a human\ndecision, either through the reviewer surface or the submitter-scoped surface\ndescribed in [REVIEW.md](REVIEW.md).\n\n## Providers and validation\n\n`createSDKProposalGenerator(client, identity, {maxTokens,timeoutMs})` uses an\nexisting AI SDK `chat` client. It sends a fixed system instruction and separate\nJSON evidence/catalog data, requests JSON, supplies cancellation and bounds, uses\nno tools or continuation, and rejects known truncation or tool calls,\nunexpected models, malformed JSON and oversized output. Configure SDK clients\nwithout automatic retry that would bypass application boundary checks. The\nadapter's public identity is exactly provider/model/version; credentials and raw\nprovider errors are never provenance.\n\nA trusted custom `ProposalGenerator` must likewise honor cancellation, bound its\nresponse, and explicitly declare validated `complete` or `unknown` completion.\nThe SDK currently normalizes missing/unknown finish reasons to `stop`\n([owning SDK follow-up](https://github.com/happyvertical/sdk/issues/1381)), so its\nadapter conservatively declares `unknown`, persisted as\n`generation_completion_unknown`. Otherwise valid suggestions remain available\nfor human preview; automatic eligibility always remains false. The service\ndeadline aborts requests and prevents late publication; it does not claim to terminate computation at a remote\nprovider or isolate native allocations. Extractor process limits remain separate.\n\nWhen the pinned extraction carries an authenticated reviewer instruction\n(REVIEW.md), `prepareGeneration` copies it into the interpretation configuration\nand `generateProposals` verifies that copy against the extraction record and its\nown digest before provider disclosure (`integrity` otherwise). The prompt then\ncarries it in its own **trusted reviewer guidance** section after the fixed\nsystem instruction and handler contract: the guidance is named as authenticated\nhuman input, limited to the offered catalog, and the evidence remains untrusted\ndata. `GenerativeProposalInput.reviewerInstruction` exposes `{id, text}` to custom\ngenerators; `provenance.reviewerInstruction` records `{id, digest}`. The\ninstruction never changes `offered`, `catalogDigest`, argument schemas,\npermissions or `automaticActionEligible`; a reply that follows guidance outside\nthe catalog fails validation like any other hostile output. **Budget cost:** the instruction counts once against the input budget\n(`maxInputBytes`, each offered handler's `maxBytes` and the live policy\nceiling), as its JSON-escaped text inside the prompt's guidance section — up\nto 4,000 characters plus escaping and the fixed guidance sentence. The\n`reviewerInstruction` field duplicated for custom generators is not counted\nagain. The decision stage also carries it once: its request state holds the\nevidence-side input with the un-guided base instructions under `evidence`, and\nthe guidance only under a separate `reviewerGuidance` key, never under\n`evidence`; the decision budget measures that serialized request as sent. Size `maxInputBytes` with that headroom. Learned examples are\nstill retrieved for an instructed generation; only a logical split correction\nsuppresses them. Every instruction costs a fresh extraction revision before the\nnew interpretation: the predecessor-pin contract above (source = immediately\npreceding revision, current-revision reads) is deliberately left intact rather\nthan reused for a same-source second interpretation, so OCR/speech hosts budget\none extraction per instruction, as for split corrections.\n\nModel output can contain only offered handler versions, schema-valid arguments,\nretained evidence locations and offered alternative handler/candidate keys.\nCandidate IDs must occur in the offered set, and evidence IDs in retained source\nresults. Unknown enums, invented IDs, extra authority/tool/approval fields and\nmalformed structures fail closed. Missing required top-level fields are retained\nas `missingFields`, with `needs_review`; values are never invented to satisfy a\nschema. Observed page/time/source granularity is preserved. Logical scan splits\nuse `proposeDocumentSplits`; originals and hashes remain intact.\n\nA generated split whose groups fail that check is dropped, not the whole reply\n(#4288): the suggestions and any other splits are validated as before, the\ndropped split is never published or applied, and `provenance.splitsDropped`\nrecords `{count, checks: ['split_groups']}`, never pages or evidence ids. Any\nother split error still fails the attempt. If every split is dropped, the reply\nhas no split; a reviewer can still split through `reviseLogicalSplit`, and a\nrecorded split correction the reply no longer matches ends as\n`human_split_not_respected`. A split for unknown or repeated evidence is still\nrejected, even when the earlier split on that evidence was dropped. Like\n`duplicatesRemoved`, `splitsDropped` is kept only on a published, validated\nreply. Stored output is never re-validated, so earlier attempts and their\ndigests replay unchanged.\n\nA rejected reply ends the attempt as `provider_error` with the `malformed_output`\nwarning and a bounded, value-free `provenance.failure` `{category, reason}` (#4207).\nThe reason lists schema-owned paths, keywords and schema constants, for example\n`/outcome enum (allowedValues=proposals|unknown|...)` and\n`/suggestions/0 required (missingProperty=evidence)`, or the fixed internal check\nand its path, such as `Unoffered handler: /suggestions/0`. Path segments are\nkept only when they are keys declared under the schema's `properties` or\nindexes into a value that actually is an array in the rejected reply; any other\nsegment, numeric or not (for example a key under an open\n`additionalProperties` argument sub-schema, or a numeric key of an object),\nbecomes `?`, and an extra property's name is never echoed.\nIt never contains document text, argument values, evidence content or\nmodel-chosen keys, is cut at 1000 characters,\nand is dropped before the output-limit fallback. Hosts read it from the\ncompleted/partial analysis at `analysis.result.output.proposals.provenance.failure`.\nThe SDK adapter constrains replies with a `json_schema` response format built\nfrom the validator's schema and the fixed instructions describe the shape; a\ncustom `ProposalGenerator` receives no schema, so its raw reply meets the\nvalidator directly and the same reason is recorded.\nThe provider-facing schema is made portable (`portableResponseSchema`, #4260):\nkeywords that common OpenAI-compatible structured-output backends reject are\nremoved at schema positions, including inside handler argument schemas\n(`uniqueItems`, `contains`, `multipleOf`, `format`, `patternProperties`,\n`propertyNames`, `min`/`maxProperties`, `not`, `if`/`then`/`else`,\n`dependent*`, `unevaluated*`, and the `default`/`examples` annotations; the\nfull list and reasons are in `src/proposal-sdk.ts`). With `uniqueItems`, for\nexample, vLLM's xgrammar feature check flags the schema, its auto mode routes\nit to llguidance, and llguidance answers\n`400 Grammar error: Unimplemented keys: [\"uniqueItems\"]`. This only loosens the\ngrammar: the validator still enforces the constraints, including unique\n`alternatives` and `missingFields`, and the fixed instructions ask for distinct\nentries. The exception is `format`, which is advisory: the validator runs Ajv\nwith `validateFormats: false`, so `format` is enforced nowhere. Because a model\ncan still repeat an entry, fresh generator output is normalized first (#4286):\nwithin each suggestion, repeated `alternatives` and `missingFields` entries\n(equal by canonical JSON) are dropped, keeping the first. Nothing else is\nrewritten, and `uniqueItems` still applies to the result. The count, never the\nvalues, is recorded as `provenance.duplicatesRemoved`, present only when\nnon-zero and only on a published, validated reply. The published output, and so\nits digest, is the normalized form. Stored attempts are read and replayed as\npersisted; they are never renormalized. When\n`patternProperties` is removed, the same object's `additionalProperties` is\nremoved too, so the grammar does not shrink to `{}`. The `contentSchema` annotation is omitted as well, so nested unsupported\nconstraints cannot leak through an unvisited schema position. A backend may\nrecursively inspect typed schema-like objects even inside `enum` or `const`\ndata. When such data contains an unsupported keyword, the whole containing\n`enum`/`const` constraint is omitted conservatively; literal data is never\nrewritten. Harmless property names and ordinary enum/const data stay intact.\nThe original validator remains authoritative for omitted literal constraints.\nThere is no automatic `json_object` fallback.\n\nInvariant: the provider copy only ever accepts a superset of what the original\naccepts. Each removed keyword is a conjunct, so removing it only widens. The two\nplaces where removal would narrow are rewritten:\n- every `oneOf` becomes `anyOf` (or joins an existing `anyOf` through `allOf`),\n because loosened `oneOf` branches could both match and reject a value the\n original accepted;\n- an object that loses `patternProperties` also loses `additionalProperties`.\n\nProvider-only `$ref`, `$dynamicRef`, and `$recursiveRef` constraints are also\nremoved. Rewriting or deleting a subschema can invalidate pointer or anchor\ntargets, including targets inside nested `$id` resources. Dropping references\nconservatively widens the grammar without resolving untrusted schema resources;\nproperty names and enum/const data named `$ref` remain unchanged. Referenced\nconstraints, recursion, and dynamic scope remain enforced by the original\nvalidator, so provider guidance for reference-based arguments is less precise.\n\nThe validator still checks the original, including `oneOf` exclusivity. A\nproperty-style regression checks original-valid ⇒ portable-valid across the\nremoved keywords. Handler argument schemas may still carry `allOf` through\nunchanged; its support across backends is unverified, so check such a handler\nagainst the deployed backend.\n\nA generator call that throws ends the attempt as `provider_error` with the\n`unavailable` warning and `provenance.failure` `{category: 'unavailable',\nreason}`. The reason is value-free by construction: a provider's own text can\nquote the prompt or document, so it is never copied. The reason is built only\nfrom a fixed phrase and, for an SDK `AIError` only, the HTTP status (from a\nstructured field, or from the exact `<status> ...` / `TypeSafe request failed\n(<status>): ...` shapes the SDK produces), the SDK error code (from the closed\nlist of codes the SDK raises) and, for a schema rejection, quoted tokens that\nare JSON Schema keywords. Any other error contributes at most a structured\nnumeric status. For example: `provider rejected the response schema (HTTP 400,\ncode API_ERROR); unsupported response-schema keywords: uniqueItems`, or just\n`provider call failed`. It is cut at 500 characters.\n\n`createSDKProposalDecisionClient(client)` adapts an existing SDK client’s optional\ncapability without changing its errors or protocol. Optional `decision` uses public core `executeDecision` and the existing SDK\npredicate, choice, score and batch contracts. Supported-effect predicates,\nhandler classification, candidate entity matching, and action ambiguity/risk\nare distinct questions. Their validated probabilities and provenance are stored\nseparately from generative provenance and unknown OCR certainty. The complete\nserialized decision request, including suggestions and questions, must fit the\nminimum configured/current policy byte ceiling before capability probing and\nagain before deciding. A policy change between these boundaries fails closed.\nActually incomplete extraction always requires review. Unknown provider\ncompletion metadata is preserved as `source_completion_unknown`; it does not\nblock otherwise schema-valid **human** preview or imply completeness. Automatic\naction eligibility remains false. An unconfigured decision path\nis recorded explicitly. Configured errors produce a durable safe failure outcome;\nthey never silently switch to a generative decision fallback.\n\n### Decision readiness gate (#4209)\n\nFor every suggestion `i` the request asks `supported_i` (predicate),\n`route_i` (choice over the offered `handlerId@version` keys plus `none`),\n`risk_i` (ordered score over `clear`, `uncertain`, `ambiguous`) and one\n`entity_i_<field>` choice per candidate-reference argument. The validated\nanswers are always persisted under `provenance.decision.answers`. With the\ndefault `decisionReadiness: 'gate'` they are read as follows, and any failing\ncheck sets the suggestion to `needs_review` (a tie also sets the outcome to\n`ambiguous`):\n\n- `supported.probability >= minimumDecisionProbability` (default `0.8`).\n- `route.choice` equals the suggestion's own `handlerId@handlerVersion`,\n `route.confidence >= minimumDecisionProbability`, and the gap between the two\n largest route probabilities is greater than `tieMargin` (default `0.1`).\n- `risk.score < 1`: only the `clear` level passes; `uncertain` and `ambiguous`\n require review.\n- Each entity match chooses the suggested candidate's key with confidence at or\n above the threshold and a gap above `tieMargin`.\n\nThese values are provider outputs read as if they were calibrated\nprobabilities; nothing in this package calibrates them for this use. The\nteamworks-os measurement in #4209 (self-hosted Laya `typed-decisions`) found no\nseparation between right and wrong suggestions: a correctly read vendor invoice\nscored `supported` 0.37, garbage input 0.45–0.50, a wrongly proposed purchase\norder 0.51, route confidence 0.003–0.15 and `risk` ≥ 0.94, so the gate sent\nevery suggestion to review. Until a labelled sample shows separation, treat the\nanswers as diagnostics and configure:\n\n- `decisionMaxLen`: positive integer forwarded unchanged as the per-request\n `maxLen` of the decision client (the SDK Laya provider's token window; the\n checkpoint default is 1024 and the serialized evidence plus suggestions is\n otherwise truncated). Other clients ignore it.\n- `decisionReadiness: 'record'`: the decision still runs, is bounded and\n authorized exactly as before and its answers, usage, `readiness` and `maxLen`\n are recorded, but the gate never changes `outcome` or `disposition`; readiness\n comes from the validator alone (`missingFields`, outcome, source completeness).\n A client error or timeout is recorded as the `decision_unavailable`\n warning. A reply that comes back and then fails the core `executeDecision`\n identity or answer-shape check is recorded as `decision_malformed` with the\n reply's usage; this is the path for injected `DecisionClient`s. SDK clients,\n including the Laya provider behind `createSDKProposalDecisionClient`,\n validate the reply's shape inside `client.decide` and throw, so a malformed\n SDK reply is recorded as `decision_unavailable` with no usage. Every case\n records the `provenance.decision` identity. The generated suggestions stay\n as they were. The serialized request exceeding the byte budget is a\n configuration failure, not a provider answer: it ends the attempt as `limit`\n in both modes, and in `gate` mode every failure above still ends the attempt\n as `provider_error`. Lease, catalog, policy and provider-allowlist revocation\n fail closed in both modes.\n\nSuccessful output also records `provenance.decision.readiness` (`'gate'` or\n`'record'`) and `maxLen` when set; configuration digests are unchanged, but\npersisted output is therefore not byte-identical to earlier releases.\n\nBoth settings are public configuration: they are part of\n`ProposalReadConfiguration`, the frozen `GenerationStageConfiguration.proposals`\n(present only when set, so existing digests are unchanged) and the completed\nsnapshot authority check. Invalid values fail at proposal service construction.\nNeither mode affects automation: `automaticActionEligible` stays `false`, and\n`authorizeAutomatic` reads only the host's `evaluateAutomatic` callback and\npolicy, never these answers.\n\nOutput records zero, one or multiple suggestions, alternatives, missing fields,\nsource links, proposed splits, versions, allowlisted usage, warnings and explicit\n`unknown`, `ambiguous`, `no_action`, `needs_review` or `provider_error` outcomes.\n`automaticActionEligible` is always false. Provider input/output and the complete\nserialized persisted envelope are bounded by configuration, live policy and the\nreceipt ceiling. Oversized output becomes a bounded review/limit result; when\nno safe envelope fits, the owning service records fixed `failAnalysis` metadata\noutside the provider payload budget without retaining provider output.\n\n## Explicit preview and stable intentions\n\nThe host chooses persisted suggestion indexes and calls:\n\n```ts\nawait service.previewGeneratedProposals({\n itemId,\n attemptId: generationAttemptId,\n selections: [{\n index: 0,\n intentionKey: 'document:meeting-2026-10-09',\n expectedRevision: 0,\n requestId: 'review-request-1',\n }],\n});\n```\n\n`intentionKey` is the host's stable business-intention identity across generation\nrevisions. Never derive a fresh key from model output, suggestion order or a retry.\nSelections must reference current persisted validated `ready_for_review` or\n`needs_review` output (#4208); a `provider_error` attempt, an unoffered handler or\na non-interpretation stage is rejected. A `needs_review` suggestion whose\n`missingFields` are still absent fails the handler schema inside the ordinary\npreview (`Invalid handler payload`) and publishes nothing; the reviewer supplies\nthe missing values through the explicit human path (`previewProposal` /\n`previewPlan`, as the published review host does for `preview({args})`), and the\nhandler's `validate` and `preview` run again on the completed arguments.\nEach batch requires distinct suggestion indexes and intention keys; duplicate\nindexes are rejected before any operation or plan preview is written.\nThe service rechecks current catalog/schema/target/source provenance, then calls\nthe existing operation or plan preview. Each result still requires the ordinary\nhuman review and execution APIs. Reprocessing creates no new business identity;\nsuccessful-action replay protection stays with execution.\n\n## Evidence and limits\n\nThe test matrix is `docs/test-matrix/3673-ingestion-proposals.md`. SQLite and real\nPostgreSQL suites exercise authority, revisions, abstention, hostile output,\ncompound proposals, split provenance and reviewed domain effects. The upload\nreference composes authenticated multipart delivery of a generated embedded-text\nPDF through the actual packaged PDF child, durable interpretation, and the existing\nordered ContentDocument draft/retained-asset plan. It checks duplicate delivery,\nunauthenticated and foreign-tenant denial, explicit approval of both steps,\nidempotent execution replay, page provenance, and unchanged original bytes.\nThe compound-email case uses a declared messages-owner snapshot fixture.\n\nLocal HTTP fixtures execute the actual AI SDK transport and cancellation contract.\nGenerative responses and the separate injected PDF split boundaries establish\ndeterministic orchestration, not model accuracy or OCR quality. No held-out routing\nevaluation or automatic approval is claimed. Missing/unknown AI completion remains\nexplicit under [SDK #1381](https://github.com/happyvertical/sdk/issues/1381).\n\nProposal limits are checked at `IngestionService` construction: positive safe\nintegers, at most 20 handlers/candidates/suggestions and 2147483647 ms timeout.\nInterpretation output uses the exported `GenerationAnalysisOutput` wrapper at\n`analysis.result.output.proposals`; the published review host unwraps it.\nAn explicit feedback `retrieve` denial omits optional examples and feedback\nprovenance and continues generation. Item/execution denials, unexpected failures,\nand revocation after examples were selected still fail closed before disclosure.\n"
|
|
1724
1724
|
},
|
|
1725
1725
|
{
|
|
1726
1726
|
"path": "FEEDBACK.md",
|
|
@@ -1781,7 +1781,7 @@
|
|
|
1781
1781
|
"code": "not-module-scope",
|
|
1782
1782
|
"helper": "definePlaybook",
|
|
1783
1783
|
"message": "`definePlaybook()` must be called at module scope to be emitted into the manifest and knowledge graph. A declaration the scanner cannot read without evaluating it is not emittable — use `useWebMcpTool` for a tool set derived from computed or fetched data.",
|
|
1784
|
-
"line":
|
|
1784
|
+
"line": 6989,
|
|
1785
1785
|
"column": 9,
|
|
1786
1786
|
"sourceFile": "src/test-support/proposals.ts"
|
|
1787
1787
|
},
|
|
@@ -1789,7 +1789,7 @@
|
|
|
1789
1789
|
"code": "not-module-scope",
|
|
1790
1790
|
"helper": "definePlaybook",
|
|
1791
1791
|
"message": "`definePlaybook()` must be called at module scope to be emitted into the manifest and knowledge graph. A declaration the scanner cannot read without evaluating it is not emittable — use `useWebMcpTool` for a tool set derived from computed or fetched data.",
|
|
1792
|
-
"line":
|
|
1792
|
+
"line": 7618,
|
|
1793
1793
|
"column": 7,
|
|
1794
1794
|
"sourceFile": "src/test-support/proposals.ts"
|
|
1795
1795
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-ingestion",
|
|
3
|
-
"version": "0.57.
|
|
3
|
+
"version": "0.57.26",
|
|
4
4
|
"description": "Durable tenant-scoped intake and evidence foundations",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -50,32 +50,32 @@
|
|
|
50
50
|
}
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@happyvertical/smrt-core": "0.57.
|
|
54
|
-
"@happyvertical/smrt-types": "0.57.
|
|
55
|
-
"@happyvertical/smrt-tenancy": "0.57.
|
|
56
|
-
"@happyvertical/smrt-assets": "0.57.
|
|
57
|
-
"@happyvertical/smrt-jobs": "0.57.
|
|
53
|
+
"@happyvertical/smrt-core": "0.57.26",
|
|
54
|
+
"@happyvertical/smrt-types": "0.57.26",
|
|
55
|
+
"@happyvertical/smrt-tenancy": "0.57.26",
|
|
56
|
+
"@happyvertical/smrt-assets": "0.57.26",
|
|
57
|
+
"@happyvertical/smrt-jobs": "0.57.26",
|
|
58
58
|
"@happyvertical/sql": "^0.106.0",
|
|
59
59
|
"@happyvertical/pdf": "^0.65.9",
|
|
60
60
|
"@happyvertical/ocr": "^0.62.1",
|
|
61
61
|
"@happyvertical/speech": "^0.106.0",
|
|
62
62
|
"@happyvertical/ai": "^0.106.0",
|
|
63
63
|
"sharp": "^0.35.5",
|
|
64
|
-
"@happyvertical/smrt-agents": "0.57.
|
|
65
|
-
"@happyvertical/smrt-playbooks": "0.57.
|
|
64
|
+
"@happyvertical/smrt-agents": "0.57.26",
|
|
65
|
+
"@happyvertical/smrt-playbooks": "0.57.26",
|
|
66
66
|
"ajv": "8.20.0",
|
|
67
|
-
"@happyvertical/smrt-ui": "0.57.
|
|
67
|
+
"@happyvertical/smrt-ui": "0.57.26"
|
|
68
68
|
},
|
|
69
69
|
"devDependencies": {
|
|
70
|
-
"@happyvertical/smrt-vitest": "0.57.
|
|
70
|
+
"@happyvertical/smrt-vitest": "0.57.26",
|
|
71
71
|
"@types/node": "24.13.6",
|
|
72
72
|
"typescript": "6.0.3",
|
|
73
73
|
"vite": "8.1.6",
|
|
74
74
|
"vitest": "4.1.10",
|
|
75
|
-
"@happyvertical/smrt-content": "0.57.
|
|
76
|
-
"@happyvertical/smrt-messages": "0.57.
|
|
75
|
+
"@happyvertical/smrt-content": "0.57.26",
|
|
76
|
+
"@happyvertical/smrt-messages": "0.57.26",
|
|
77
77
|
"@happyvertical/email": "^0.106.0",
|
|
78
|
-
"@happyvertical/smrt-users": "0.57.
|
|
78
|
+
"@happyvertical/smrt-users": "0.57.26",
|
|
79
79
|
"@sveltejs/package": "^2.5.8",
|
|
80
80
|
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
|
81
81
|
"svelte": "^5.57.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"proposal-contracts-77Uo1B1j.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/** 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 Error('Empty split');\n for (const page of group) {\n if (!Number.isSafeInteger(page) || !available.has(page) || seen.has(page))\n throw new Error('Invalid split page');\n seen.add(page);\n }\n if (group.some((page, index) => index > 0 && page <= group[index - 1]))\n throw new Error('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/** 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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