@docmana/sdk
DOC-2786 adds review items of kind verdict, field __decision__, on executed Receivability nodes. Submit the returned opaque itemId through reviews.decide() with value accepted or rejected; an optional reason is allowed for rejected-to-accepted overrides. This native verdict is independent of formula-defined boolean properties, which an application may correct separately in the same decision. Node status and downstream routing follow the human verdict without rejudging the corrected node. Requires compatible Document API and Consumer Edge; downstream items and status items stay read-only.
The HITL pilot uses the explicit prerelease 0.36.0-hitl.2 and the npm hitl
distribution tag. Install the exact version for reproducible pilot builds:
npm install --save-exact @docmana/sdk@0.36.0-hitl.2
The stable default remains on latest; the prerelease does not select a native
API. Configure the SDK's Consumer base URL on the application server.
Real formula node progress (local HITL pilot)
sdk.executionEvents.list(executionId, { organization, after: 0, limit: 100, signal })
reads a non-consuming metadata journal, including formulas without human review.
Follow nextAfter while non-null; order by sequence, deduplicate eventId, and
honor truncated when the cursor predates retained history. The native journal
keeps at most 2,000 events with the execution. No PDF or final-result retention
is added. Older APIs can return 404; show confirmed status without inventing
progress. Never turn a journal failure into a call to another backend.
The four new names are execution.node.started, execution.node.completed,
execution.node.failed, and execution.node.reused. Events identify a node,
document keys, revision and attempt. A reused output does not imply a new LLM
call. Completion of a node is technical completion, not a positive business
verdict or final execution completion. occurredAt is the real action time;
publishedAt is optional broker time, present on signed callbacks.
verifyExecutionEventCallback and parseExecutionEventCallback accept both the
new node metadata and the four existing review events. Existing review-only
verification helpers remain strict and unchanged. Final execution callbacks and
result ownership keep their existing contract; there are no pipeline events.
Review event callbacks
SDK 0.33.0 adds server-side verifyReviewEventCallback, parseReviewEventCallback
and the ReviewEventCallback type for Consumer's opt-in review event relay.
This is independent from runFlowAsync({ callbackUrl }), which still receives only
the final result. No Service Bus connection is required in your application.
import { verifyReviewEventCallback } from "@docmana/sdk";
const event = verifyReviewEventCallback({
body: rawUtf8Body,
signature: request.headers.get("x-docmana-event-signature"),
timestamp: request.headers.get("x-docmana-event-timestamp"),
secret: serverConfiguredSecret, // at least 32 characters; never sent to a browser
organization: expectedOrganization,
});
await persistOnce(event.organization, event.eventId, event);
// Only now return 2xx. Never finalize an execution from a review notification.
Supported types are execution.awaiting_review, execution.review_done,
execution.review_closed and execution.review_expired. review_done means the
decision is recorded, not that the execution is finished. review_closed also
describes the review rather than the execution. publishedAt is the broker's
publication time. The metadata excludes document names, values, notes and results.
Signatures use HMAC-SHA256 over timestamp + "." + rawBody with header v1=<hex>;
verification accepts a five-minute clock difference. Broker retries are re-signed
but retain the event ID; store it durably for deduplication. An event notification
never consumes the final result. Source publication is best-effort: reconcile
current review state separately after a missed notification.
Official Docmana SDK for calling docmana-consumer-edge-api.
SDK 0.32.0 adds native formula authoring, assisted conversations and revision-pinned
document-trial preparation. Deploy Consumer authoring support before publishing
and adopting this version. DocMana API main supports the ordinary Mongo path;
assisted document trials run in DocMana Flows. A local development tarball is not
an npm release. Optional Git/projection types remain POC contracts, not proof of
support by API main.
The SDK sends documents to Consumer, starts an async flow, polls Consumer for
status, and returns the mapped Consumer execution DTO.
Installation
npm install @docmana/sdk
GitHub release recovery
The Release workflow publishes an existing v<version> tag. GitHub Actions are
pinned to full commit SHAs to satisfy the enterprise policy. If a tag-triggered
run fails before starting, merge the workflow correction first, then manually
run Release from main with that existing tag. The workflow checks out the
tag and verifies its package version before publishing; do not move a release
tag to repair a pipeline. Publication requires the existing npm publisher
credential or trusted-publishing configuration. Verify the version is available
in npm before updating a consumer's lockfile.
Requires Node.js 20+.
Quickstart
import { Docmana } from "@docmana/sdk";
const docmana = new Docmana({
apiBaseUrl: process.env.DOCMANA_API_URL!,
accessToken: process.env.DOCMANA_ACCESS_TOKEN!,
});
const result = await docmana.runFlow("<flow-id>", {
files: ["./contract.pdf"],
context: { contract: { destination: "Canada" } },
useDraftVersion: true,
});
console.log(result.status, result.executionId);
Fraud detection follows the same asynchronous Consumer Edge pattern. The
high-level call starts the job, polls Consumer, and returns the normalized
result:
const fraud = await docmana.detectFraud({
file: "./claim.pdf",
analystContext: "Travel claim; verify the invoice total.",
});
console.log(fraud.verdict, fraud.summary.highestSeverity);
console.log(fraud.summary, fraud.findings);
Authentication
The public SDK is Bearer-only. It does not acquire OAuth tokens and it never
calls docmana-api directly. Provide either a static accessToken or a
getAccessToken provider:
const docmana = new Docmana({
apiBaseUrl: "https://consumer.example.com/v1",
getAccessToken: async ({ forceRefresh } = {}) => {
return forceRefresh ? refreshTokenSomehow() : currentToken();
},
});
If Consumer returns 401 and getAccessToken is configured, the SDK calls
getAccessToken({ forceRefresh: true }) once and retries the request. With a
static accessToken, 401 is returned as an auth error without retry.
Configuration
| Field |
Type |
Required |
Description |
apiBaseUrl |
string |
Yes |
Base URL of Consumer API, including version when applicable. |
accessToken |
string |
One of |
Static Bearer token sent to Consumer. |
getAccessToken |
(options?: { forceRefresh?: boolean }) => string \| Promise<string> |
One of |
Token provider for renewable Bearer tokens. |
timeoutMs |
number |
No |
Maximum polling time for runFlow and detectFraud. Default: 5 minutes. |
pollIntervalMs |
number |
No |
Fallback minimum delay between status polls. Default: 2s. |
pollMaxIntervalMs |
number |
No |
Fallback maximum polling delay. Default: 10s. |
fetch |
typeof fetch |
No |
Custom fetch implementation. |
headers |
Record<string, string> |
No |
Extra headers sent on every Consumer request. |
apiBaseUrl is required so a migrated SDK cannot accidentally call
https://api.docmana.ai.
Run flow params
runFlow(flowId, params, options) and runFlowAsync(flowId, params, options)
use RunFlowParams for request data:
| Field |
Type |
Description |
files |
(string \| { path: string } \| { data, filename, contentType? })[] |
Documents to upload. A string or { path } is treated as a file path. |
documentData |
readonly string[] |
Inline document text, one string per document. |
context |
Record<string, unknown> |
Business context serialized as multipart jsonContext. |
language |
string |
Optional result language passed to Consumer. |
useDraftVersion |
boolean |
Runs the current draft flow version. |
callbackUrl |
string |
Async-only callback URL, serialized as callbackUrl. |
Supply files, documentData, or both. Use one string per document, such as
JSON.stringify(transcript) for a JSON transcript. DocMana classifies each inline
document separately without OCR. Consumer Edge versions that support
documentData also accept UTF-8 .json files in files, subject to the inline
execution payload limit. These inputs are also available for partial executions.
runFlow uses RunFlowOptions for local execution controls:
| Field |
Type |
Description |
signal |
AbortSignal |
Cancels the in-flight request/polling. |
timeoutMs |
number |
Overrides configured polling timeout for this call. |
pollIntervalMs |
number |
Overrides configured fallback minimum polling interval. |
pollMaxIntervalMs |
number |
Overrides configured fallback maximum polling interval. |
onPoll |
(event) => void |
Called after each status poll. |
onRateLimit |
(event) => void |
Called when polling receives 429; includes retryAfterMs. |
runFlowAsync accepts RunFlowAsyncOptions with signal.
once was removed. Use useDraftVersion.
Methods
listFlows() calls GET /v1/flows and returns { id, name, state }[] for
the flows available to the Bearer token. Missing flow states are returned as
"unknown".
listOrganizations() calls GET /v1/organizations and returns
{ id, name }[] for the organizations available to the Bearer token.
getFlowMetadata(flowId) calls GET /v1/flows/:flowId/metadata and returns
{ flowId, name?, version?, jsonContextSchema, languages, minScore?, documents }.
version is the exact published or draft flow version that a new execution
would use.
getFlowDefinition(flowId) calls GET /v1/flows/:flowId/definition and
returns the normalized flow definition { flowId, name?, languages, minScore?, nodes }.
listOrganizationDocuments({ prefix? }) calls
GET /v1/organization-documents and returns { configured, documents }.
downloadOrganizationDocument(path) calls
GET /v1/organization-documents/download?path=... and returns
{ bytes, filename, contentType? }.
downloadOrganizationDocuments(paths) downloads each requested path.
runFlowAsync(flowId, params, options?) posts multipart files to
POST /v1/flows/:flowId/execute-async and returns
{ executionResultId, fileIds }.
runPartialFlow(flowId, params, options?) executes classification, extraction,
or extraction with validation synchronously through Consumer Edge. It returns
the standard DocmanaExecutionResult with partialExecution metadata.
runPartialFlowAsync(flowId, params, options?) starts the same partial execution
asynchronously and returns { executionResultId, fileIds } for standard polling.
getStatus(executionResultId) calls
GET /v1/executions/:executionResultId/status.
getResult(executionResultId, signal?, language?) calls
GET /v1/executions/:executionResultId/result; its result includes the optional
flowVersion identifying the exact flow version used by the execution. Processing
steps can also include model and promptId provenance when Docmana reports them.
When a flow produces receivability results, each document can include
receivabilities, keyed by step name, with status, score, feedback, and any
configured threshold or rejection details returned by Docmana.
runFlow(flowId, params, options?) starts async execution, polls status, fetches the
result, respects X-Poll-After and 429 Retry-After while polling, and throws
DocmanaExecutionError if the result status is FAILED.
detectFraud(params, options?) starts fraud detection from either documentUrl
plus filename, or a local file using the standard FileInput contract. It polls
Consumer until COMPLETED or FAILED and returns the normalized verdict, aggregate
summary and findings with job-local references. Each finding keeps its analysis
category in layer. When the detector supplies it, processor identifies the exact
Fraud API version, source revision, and build time that produced the result. Internal preprocessing, layer telemetry, token counts, LLM calls,
model usage, costs, persistence diagnostics, and the sensitive Fraud document
payload are intentionally never exposed by Consumer or SDK.
detectFraudAsync(params, options?) starts fraud detection and immediately returns
{ jobId, status } without polling.
getFraudDetectionStatus(jobId, signal?) and
getFraudDetectionResult(jobId, signal?) provide the lower-level polling workflow.
Consumer is the polling authority. When GET /status returns X-Poll-After,
the SDK waits that many milliseconds before the next status call. If the header
is absent, the SDK falls back to capped exponential full jitter between
pollIntervalMs and pollMaxIntervalMs. Retry-After on 429 always wins.
Path inputs are streamed from disk instead of being loaded completely into memory.
For multipart submissions only, the SDK retries one 503 Service Unavailable
response carrying Retry-After with a fresh request body, respecting that delay
up to 30 seconds. A downstream 503 without Retry-After is not retried.
Payloads rejected with 413 Payload Too Large are never retried.
The SDK does not log or return documentUrl or uploaded file contents. Signed
query parameters are sent only in the JSON request body to Consumer Edge. Fraud
jobs are not organization-scoped; the legacy organization inputs are accepted
but ignored for compatibility with SDK 0.20 callers.
URL and local-file inputs use the same methods: