@decionis/sdk
v0.3.0
Published
Node SDK and service-boundary middleware for policy-gated Decionis execution.
Maintainers
Readme
@decionis/sdk
Node SDK for the canonical Decionis policy-evaluation route.
Install
npm install @decionis/sdkIt includes:
- a typed client for
POST /v1/protocol/evaluate-decision - a typed execution-authority client for
POST /v1/authority/enforce-and-bind - Express middleware for service-boundary policy gating
- Express verifier middleware for Decionis execution tokens
- Fastify pre-handler hooks for the same pattern
- a runtime adapter so an agent inside any sandbox (e.g. Runta) calls Decionis for the verdict + a single-use grant before a consequential action
- a provider-neutral agent task gateway for pre-prompt reservation, proxy headers, sandbox egress verification, and usage reconciliation
Canonical decision runtime
Decionis is the authoritative served decision runtime. Product repositories own platform signal normalization, credentials, persistence, execution adapters, and customer-facing copy; they do not copy the protocol evaluator.
Use createDecionisDecisionRuntimeClient for that boundary. It fixes the route to
DECIONIS_DECISION_RUNTIME_ROUTE so an adapter cannot quietly switch to a local
or product-owned evaluator:
import { createDecionisDecisionRuntimeClient } from "@decionis/sdk";
const decisions = createDecionisDecisionRuntimeClient({
baseUrl: process.env.DECIONIS_BASE_URL!,
apiKey: process.env.DECIONIS_API_KEY!,
});
const verdict = await decisions.evaluateDecision({
org_id: process.env.DECIONIS_ORG_ID!,
decision_type: "ORDER_SUBMIT",
workflow_key: "order_submit",
context: normalizedIntent,
});Latency-critical edges may enforce a pre-synced, signed snapshot locally, but that is a bounded cache/verifier—not a second policy runtime. Policy resolution, ledgering, and authoritative Decision Dossiers remain with Decionis.
Core pattern
- Build a Decionis decision request from the incoming HTTP request.
- Call Decionis before the route mutates state.
- Continue on
APPROVE, or deny onREJECT,REVIEW, andESCALATEby default. - Forward Decision Dossier identifiers back through response headers.
For a matched policy ESCALATE, the response may include the complete
decionis.authority_requirement/1. Supply a Presence-compatible context.action_context
when evaluating, pass both objects unchanged to Presence Authority, and keep the action held until
a later Decionis re-evaluation authorizes release. An ESCALATE without this object is still a hold;
clients must never invent the missing authority policy.
Package contents
- ESM and CommonJS builds in
dist/ - TypeScript declarations
- middleware helpers that do not require a direct runtime dependency on Express
- an OpenID AuthZEN input adapter (
createAuthZenEntitlementProvider) that carries an enterprise policy decision point's answer into evaluation as a material signal; see AuthZEN interoperability
Release
For repository-backed packaging and publish automation, use the workflow documented in
docs/package-distribution.md. Breaking changes
to this package are recorded in CHANGELOG.md.
Example
import { createDecionisNodeSdk, createExpressPolicyGate } from "@decionis/sdk";
const client = createDecionisNodeSdk({
baseUrl: process.env.DECIONIS_BASE_URL!,
apiKey: process.env.DECIONIS_API_KEY!,
defaultRequest: {
policy_version: "payments-v1",
objective_profile: "risk_conservative",
mode: "ENFORCEMENT",
},
});
app.post(
"/payments/release",
createExpressPolicyGate({
client,
buildDecisionRequest: (req) => ({
org_id: process.env.DECIONIS_ORG_ID!,
decision_type: "PAYMENT_RELEASE",
amount: Number(req.body.amount),
workflow_key: "payment_release",
vertical_pack: "finance",
context: {
route: req.originalUrl,
actor_id: req.user?.id,
},
}),
}),
releasePaymentHandler,
);Execution Authority
SDK code packages action intent and binds execution through Decionis. Policy rules stay in the Authority API, not in the agent process.
import { bindAuthorityIntent, createDecionisExecutionClient } from "@decionis/sdk";
const decionis = createDecionisExecutionClient({
authorityBaseUrl: process.env.DECIONIS_AUTHORITY_URL!,
defaultHeaders: { authorization: `Bearer ${process.env.DECIONIS_API_KEY!}` },
});
const request = bindAuthorityIntent({
protocol_version: "agent-safe.intent/1",
tenant_id: process.env.DECIONIS_ORG_ID!,
intent_id: crypto.randomUUID(),
captured_at: new Date().toISOString(),
expires_at: new Date(Date.now() + 60_000).toISOString(),
actor: { id: "research_agent", type: "AI_AGENT", runtime: "mcp" },
action: {
type: "send_payment",
resource: "wallet.usdc",
parameters: { amount: 0.25, currency: "USD" },
},
context: {},
downstream_target: {
system: "payment_api",
operation: "send_payment",
endpoint: "POST /payments",
},
});
await decionis.enforceAndExecute({
request,
execute: () => paymentApi.sendPayment({ amount: 0.25 }),
});Tenant, actor, target, and credentials must come from trusted server context, not model output. bindAuthorityIntent canonicalizes and hashes the exact short-lived intent. Keep the downstream credential behind this executor callback.
Decionis-managed Presence escalation
Managed mode keeps the executor on the Decionis API. Decionis creates the policy-required Presence ceremony, verifies Presence's independently signed evidence, re-evaluates current policy for the unchanged exact intent, and only then returns its normal execution grant. The executor does not need Presence service credentials.
import { bindManagedAuthorityIntent, createDecionisExecutionClient } from "@decionis/sdk";
const request = bindManagedAuthorityIntent(intentBinding, {
mode: "MANAGED",
approver: { role_id: "APPROVER" },
verification_requirements: { methods: ["WEBAUTHN", "ACTIVE_LIVENESS"] },
});
const pending = await decionis.enforceAndBind(request);
if (!pending.managed_escalation) throw new Error("managed escalation was not created");
const authorization = await decionis.waitForAuthorization(request, pending);
if (authorization.status !== "GRANT_READY" || !authorization.decision?.execution_token) {
return refuse(authorization.reason_codes);
}
const claim = await decionis.redeemGrant(
authorization.decision.execution_token,
request,
authorization.decision,
);
if (!claim.valid || !claim.claim_token) return refuse(claim.reason_codes);
const result = await sideEffectHandler();
await decionis.finalizeGrant({
executionToken: authorization.decision.execution_token,
claimToken: claim.claim_token,
outcome: "COMMITTED",
commitCorrelationId: request.intent_id,
});waitForAuthorization polls Decionis—not Presence—with bounded jittered
exponential backoff and stops at the original intent expiry. A late ceremony
returns INTENT_EXPIRED and RECAPTURE_REQUIRED; it never revives the old
intent. Direct customer-coordinated Presence remains supported by supplying
verified receipt references through the existing evidence.humanApproval
flow.
Ceremony is the human identity and assurance check. Evidence is Presence's signed result for one exact intent. Delivery transports only an opaque invitation locator. Delivery does not confer authority. Human approval is necessary when policy requires it, but Presence evidence is not transferable execution authority. Presence authorization cannot revive an expired execution intent.
enforceAndExecute is grant-required and fail-closed by default: the single-use
grant must be issued and redeemed before execute runs, and every non-executing
path — policy block, no grant, failed redemption, unreachable authority — resolves
to executed: false instead of running the action.
Grant-required (strict) enforcement
enforceAndExecuteStrict makes the single-use grant a hard precondition —
"no valid grant, no execution." It authorizes, then redeems the grant before
execute runs, and fails closed on every other path. Because the grant is redeemed
up front, a downstream failure requires a fresh decision rather than replaying an
ALLOW. The default enforceAndExecute delegates to this path — grant-required,
fail-closed enforcement is the default, not an opt-in. Call the strict method
directly when you need the grant redemption and a precise non-execution reason.
The history of this default is recorded in CHANGELOG.md.
const result = await decionis.enforceAndExecuteStrict({
request,
execute: ({ grant }) => paymentApi.sendPayment({ amount: 0.25, grantId: grant.claims?.jti }),
effectEvidence: {
externalReference: "payment-request-42",
observer: { id: "payments-worker", version: "2026.08.31" },
// Non-JSON results can provide deterministic bytes and a stable profile.
// responseCanonicalizer: { profile: "payment-response/1", canonicalize: encodePayment },
},
});
if (!result.executed) {
// result.reason: BLOCKED_BY_POLICY | NO_EXECUTION_GRANT | GRANT_NOT_REDEEMABLE | AUTHORITY_ERROR
return refuse(result.reason);
}Downstream services should verify and consume the token before mutating state:
import { createExpressExecutionTokenVerifier } from "@decionis/sdk";
app.post(
"/payments",
createExpressExecutionTokenVerifier({
authorityBaseUrl: process.env.DECIONIS_AUTHORITY_URL!,
buildVerificationRequest: (req) => ({
actor_id: req.body.actor_id,
action_type: "SEND_PAYMENT",
resource: "wallet.usdc",
amount: Number(req.body.amount),
currency: "USD",
downstream_target: {
system: "payment_api",
operation: "send_payment",
endpoint: "POST /payments",
},
}),
}),
paymentHandler,
);Agentic checkout (ACP / AP2) authorization primitive
AgenticCheckoutGate is the in-process authorization primitive for agentic
commerce: it runs the deterministic gate against a pre-synced signed policy
snapshot (zero network on the hot path), mints a single-use, cart-bound Execution
Grant on ALLOW, and appends to the ledger off the hot path. authorizeAgenticCheckout
returns a flat ACP/AP2 accept/decline result.
import { authorizeAgenticCheckout } from "@decionis/sdk";
const auth = await authorizeAgenticCheckout(
{ snapshot, issueGrant },
{ request, signal: { cartTotal: 100, discountAmount: 0, estimatedCost: 20 } },
{ requireGrant: true }, // strict: an ALLOW without a bound grant is NOT authorized
);
if (!auth.authorized) return decline(auth.acp_status, auth.reasons);
proceedToPayment(auth.execution_grant); // single-use, action-bound{ requireGrant: true } is the fail-closed posture that pairs with
enforceAndExecuteStrict — no bound grant, no authorization.
The strict path now calls /v1/execution/claim-token immediately before the callback and /v1/execution/finalize-token immediately after it. The callback receives claimToken and commitCorrelationId. For execution-bound grants, a JSON callback result is JCS-canonicalized and its SHA-256 digest is recorded as GATE_OBSERVED effect evidence; effectEvidence can add a downstream reference, observer identity, privacy-safe metadata digest, and deterministic response canonicalizer for non-JSON results. A non-JSON result without a canonicalizer remains finalized but explicitly unconfirmed. Do not retry an error whose external effect is unknown; it is finalized as INDETERMINATE by default. Use classifyFailure only when the adapter can prove the downstream operation did not commit. The complete execution-binding and recovery contract is documented in execution-bound-decision-dossiers.md.
Agent task reservation and provider proxy
Use DecionisAgentTaskGateway before model traffic. It keeps the Decionis runtime key
separate from the provider credential and produces native base URLs and headers for the
OpenAI and Anthropic SDKs.
import OpenAI from "openai";
import { createDecionisAgentTaskGateway } from "@decionis/sdk";
const gateway = createDecionisAgentTaskGateway({
gatewayBaseUrl: process.env.DECIONIS_AGENT_GATEWAY_URL!,
apiKey: process.env.DECIONIS_API_KEY!,
});
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY!,
baseURL: gateway.providerBaseUrl("openai"),
defaultHeaders: gateway.providerHeaders({
orgId: process.env.DECIONIS_ORG_ID!,
userId: "[email protected]",
sessionId: crypto.randomUUID(),
idempotencyKey: crypto.randomUUID(),
host: "codex",
}),
});Direct embeddings can call reserve(), authorizeEgress(), reconcile(), and
release() instead. The complete boundary and rollout contract is documented in
AgentBoundaryGateway.md.
