@nexus-legal/sdk
v0.31.0
Published
SDK oficial TypeScript / JavaScript de la API pública v1 de Nexus Legal — análisis legal multijurisdiccional con candados de certeza, jurisprudencia vectorial y sandbox. Wrapper tipado con retries automáticos, idempotency built-in, manejo de rate limits.
Maintainers
Readme
@nexus-legal/sdk
Official TypeScript / JavaScript SDK for the Nexus Legal API v1 — multi-jurisdictional legal analysis with defensible certainty locks, vector case-law search, sandbox, usage analytics and an EU-soil Zero-Retention pipeline.
npm install @nexus-legal/sdkRequires Node.js 18+ (or any runtime with globalThis.fetch).
Quick start
import { NexusClient } from "@nexus-legal/sdk";
const nexus = new NexusClient({ apiKey: process.env.NEXUS_API_KEY! });
const result = await nexus.analyze({
text: "Por el presente contrato, el arrendador cede el uso…",
jurisdiction: "ES",
legalBranch: "civil",
});
console.log(result.analysis);
console.log("Rate limit remaining:", result.rateLimit.remaining);Get an API key at /developers. Full docs at /developers/docs.
If your account runs on your OWN engine, this first call throws
Accounts provisioned as BYO-only never run legal generation on a Nexus engine —
that is the point of the setting, not a limitation. Until you register an engine,
every generative call (analyze, consulta, chat, drafting, the A/B/C nodes)
answers 409 BYO_PROVIDER_REQUIRED. It is a configuration state, not a transient
failure: retrying returns the same 409, and no credits are charged.
import { NexusClient, ByoProviderRequiredError } from "@nexus-legal/sdk";
try {
await nexus.analyze({ text, jurisdiction: "SG" });
} catch (e) {
if (e instanceof ByoProviderRequiredError) {
// Register the engine once, then re-run. Nothing was executed or charged.
await nexus.llmProviders.create({
label: "Firm Anthropic",
kind: "anthropic", // openai_compatible | anthropic | bedrock
model_default: "claude-opus-4-8",
api_key: process.env.FIRM_LLM_KEY!, // write-only: encrypted, never returned
});
} else throw e;
}Read-only surfaces (case-law search, legislation lookup, citation verification, coverage, billing) work normally without an engine — they run no generation.
Features
- Typed — first-class TypeScript types for every endpoint, request and response.
- Auto idempotency — every
POSTcarries an auto-generatedIdempotency-Key(UUID v4) so retries are safe by default. Opt-out withautoIdempotency: false. - Smart retries — 429 / 5xx with exponential backoff + jitter, honoring
Retry-After. Configurable per request. - Typed errors —
RateLimitError,InsufficientCreditsError,IdempotencyConflictError,ValidationError,AuthenticationError,ServerError,TimeoutError, and for the firm's own engineByoProviderAccountError(424),ProviderUnreachableError(503),ByoProviderRequiredError(409). - Result-integrity signals (v0.24.0+) —
truncated,chunksUsed/chunksTotal,corpusPartial,piiResiduals,citationsOrigenC,killSwitch,audited,counts_measured,noteCode,termination… the fields that say a result is NOT complete are typed and documented. See Result integrity. - Rate-limit telemetry — every response exposes
result.rateLimit.{limit,remaining,reset}. - Zero deps — pure TypeScript, no
node-fetch, nouuid, nojs-yaml. Works in Node, Deno, Bun, and edge runtimes that exposefetch. - Audit-trail parser —
extractAuditTrail()pulls theNEXUS-AUDIT-TRAIL-BEGIN…ENDblock as a structured object. - Multi-agent
mode=deep(v1.6.0+) — Node A + Node B adversarial auditor. Structured findings inresult.audit. The engine behind each node is a deployment decision, not a contract: readresult.modelfor the run you actually got, and on a BYO account no platform model runs at all (see Analysis modes). - Citation verification (v0.12.0+) —
result.citationCheckscarries the deterministic anti-hallucination verdict of every citation in the analysis (verified|mismatch|not_found|derogated|not_verifiable|pending), checked against the official corpus (BOE / CENDOJ). Zero LLM cost.
Analysis modes
| Mode | Credits | Pipeline | Use case |
|------|---------|----------|----------|
| standard (default) | 1 | Node A only | Most analyses |
| deep | 2 | Node A → Node B adversarial audit | Critical reviews, due diligence, hallucination-sensitive contexts |
Aliases for backward-compat: agil ⇄ standard, auditoria ⇄ deep. The server normalizes them.
const result = await nexus.analyze({
text: contractText,
jurisdiction: "ES",
mode: "deep", // 2 credits — Nodo B auditará el output de Nodo A
});
if (result.audit) {
console.log(`Overall severity: ${result.audit.overallSeverity}`);
for (const finding of result.audit.findings) {
console.log(`[${finding.severity}] ${finding.type}: ${finding.description}`);
}
console.log("Recommendations:", result.audit.recommendations);
}The audit object is present only when mode=deep. Its shape:
interface AuditResult {
auditor: string; // "deepseek-v4-pro"
text: string; // free-form audit prose
findings: AuditFinding[]; // structured list
overallSeverity: "low" | "medium" | "high";
recommendations: string;
processingMs: number;
}
interface AuditFinding {
type: "hallucination" | "missing_clause" | "weak_reasoning"
| "citation_error" | "other";
severity: "low" | "medium" | "high";
description: string;
}API surface
const nexus = new NexusClient({
apiKey: "nlk_…",
baseUrl: "https://legal.nexusquantum.legal", // default
timeout: 120_000, // ms, default 2 min
maxRetries: 3, // default
autoIdempotency: true, // default
});
// Top-level
await nexus.analyze({ text, jurisdiction, legalBranch, language, mode });
// Sandbox (no credits consumed)
await nexus.sandbox.analyze({ sample: "providencia_aeat" });
await nexus.sandbox.metadata();
// Case-law search
await nexus.jurisprudencia.search({ query, jurisdiction, topK });
// Vigent legislation — Spain (ES) live: full BOE corpus indexed
// (~356k vigent articles, semantic search). Other jurisdictions may
// still be rails-only; check per-jurisdiction status with coverage().
await nexus.normativa.articulo({ // literal a fecha
norma: "BOE-A-1889-4763",
articulo: "1124",
fecha: "2026-05-21",
jurisdiccion: "ES",
});
await nexus.normativa.search({ // búsqueda semántica
query: "responsabilidad contractual del arrendatario",
jurisdiccion: "ES",
topK: 10,
});
await nexus.normativa.getVersiones("BOE-A-1889-4763");
await nexus.normativa.coverage(); // status + totals, no auth
// Catalogs and usage
await nexus.jurisdictions.list();
await nexus.usage.get({ from, to, granularity });
await nexus.usage.csv({ from, to, granularity });
// Time tracking (v0.13.0+) — útil para Office add-ins y facturación
const { categories } = await nexus.timeCategories.list({ locale: "es" });
await nexus.timeEntries.create({
caseId: "7f3a…",
categoryId: categories[0].id,
minutes: 45,
description: "Revisión de contrato",
});
const { entries } = await nexus.timeEntries.list({ caseId: "7f3a…", unbilledOnly: true });
// SLA status (v0.13.0+) — uptime/latencia del mes en curso + log mensual
const sla = await nexus.sla.status({ limitHistory: 12 });
console.log(sla.current.uptime_pct, sla.lifetime.total_credits);
// IP allowlist (v0.13.0+) — restringe la API key a tus rangos
// (0 entries = allow all; se activa al añadir la primera)
await nexus.security.ipAllowlist.add({ cidr: "203.0.113.0/24", label: "Oficina" });
const { entries: ips, enforced } = await nexus.security.ipAllowlist.list();
await nexus.security.ipAllowlist.delete(ips[0].id);
// Corpus coverage (auto-discovered, includes all indexed tables)
await nexus.corpus.coverage();
// DMS — analiza un fichero de Box por id (sin descargarlo tú) y, por
// defecto, escribe el análisis de vuelta a Box como metadata. Requiere
// que el usuario tras la API key tenga una conexión Box activa (OAuth).
const box = await nexus.dms.box.analyze({
fileId: "1234567890",
jurisdiction: "ES",
legalBranch: "civil",
// writeMetadata: false, // desactiva el write-back a Box
});
console.log(box.analysis, box.source.file_name, box.metadataWritten);
// White-label config (partner/distributor — v1.7.0+)
await nexus.branding.get();
await nexus.branding.update({
branding: "partner",
partner_brand_name: "Acme Legal AI",
partner_legal_name: "Acme Legal S.A.",
partner_logo_url: "https://cdn.example.com/logo.png",
partner_primary_color: "#1A5F8B",
partner_support_email: "[email protected]",
partner_website: "https://example.com",
});
// Si la key es master de una org, los cambios se propagan a todas las
// sub-keys automáticamente. Sub-keys (child) reciben 403.
// Webhooks (Tier 2)
await nexus.webhooks.create({
url: "https://your-server.com/webhook",
events: ["analysis.completed", "analysis.failed", "credits.low"],
});
await nexus.webhooks.list();
await nexus.webhooks.update(id, { active: false });
await nexus.webhooks.delete(id);
// v0.7.0+ — inspect deliveries (debug)
const { deliveries } = await nexus.webhooks.getDeliveries(webhookId, {
limit: 100,
status: "failed", // pending | success | failed | exhausted
});
for (const d of deliveries) {
console.log(d.event, d.status, d.last_status_code, d.attempts);
}
// DSR export (GDPR Art.15 + Art.20 — v0.6.0+)
const bundle = await nexus.account.exportDsr();
// Para masters de organización:
// const subBundle = await nexus.account.exportDsr({ forSubKey: subKeyId });
// Organizations + sub-keys (Tier 2)
await nexus.organizations.create({ name: "Despacho Vázquez" });
await nexus.organizations.list();
const subKey = await nexus.organizations.createKey(orgId, {
childLabel: "Cliente Acme",
scopes: ["analyze", "query"],
});
// subKey.key se muestra UNA SOLA VEZ — guárdalo seguroSanctions screening (v0.30.0+)
Party screening runs against local lists by default: downloaded to our own infrastructure, and no party name leaves it. That is what fits Zero Retention and a sovereign deployment.
If you would rather use your own sanctions data, you bring it under your own contract:
const provider = await nexus.screeningProviders.create({
label: "Our OpenSanctions subscription",
base_url: "https://api.example.com",
api_key: "…", // WRITE-ONLY: encrypted, never returned
lists: ["EU FSF", "UK OFSI", "OFAC SDN"],
});
provider.key_fingerprint; // "sha256:5052032a4bff" — a non-reversible hashWhy it has to be yours and not ours. Screening needs the parties' REAL names,
before anonymisation: a sanctions list does not match [PERSON_1]. Sending those
names to a third party is a transfer of personal data, and whoever contracts the
source has to be whoever answers for it. There is therefore no provider of ours
that calls a third party, and its absence is the design.
Read who is actually screening, not just the list
const { providers, effective_provider, local_lists } = await nexus.screeningProviders.list();effective_provider exists because an empty providers array was ambiguous:
| value | meaning |
|----------|---------|
| byo | runs against your provider, under your contract |
| local | runs against lists downloaded to our infrastructure; no name leaves it |
| none | local lists are not populated here and you have no provider: nothing is screened |
none is not "configure one" — it is "we do not offer this here yet". Check it
before reading an empty list as "no matches".
Two refusals, on purpose
// Rotating a credential in place leaves no trace of when it changed. Delete and recreate.
await nexus.screeningProviders.update(id, { api_key: "new" }); // throws before the round trip
await nexus.screeningProviders.update(id, { enabled: false }); // this is fine
// Withdrawing yours does not switch screening off: it says what you fall back TO.
const { effective_provider } = await nexus.screeningProviders.delete(id); // "local" | "none"A failure of your provider is never substituted. There is nothing of ours to
fall back to: sending your names elsewhere because yours was down would be exactly
the transfer this design avoids. Screening stops at the first failure and the
result says so — see partyScreening below.
Reading the result
analyze() returns partyScreening whenever screening was attempted:
const r = await nexus.analyze({ text, jurisdiction: "GB", professionalRole: "abogado" });
r.partyScreening?.screened; // parties ACTUALLY checked
r.partyScreening?.failed; // attempted and NOT checked
r.partyScreening?.failureReason; // verbatim from your provider, e.g. "HTTP 401"
r.partyScreening?.entries; // hits only🔴 Read screened and failed together. entries: [] with failed > 0 is
not a clean result: it means nobody looked. Until v1.52.0 of the API these were
served identically, and a provider that was down produced the same output as a
genuinely clean screening.
Advanced examples
// Cross-reference: find statutes cited in a judgment (UUID del corpus)
const articulos = await nexus.cruce.articulosDeSentencia(jurisprudenciaId);
// Cross-reference: find judgments that cite a statute article
const sentencias = await nexus.cruce.sentenciasDeArticulo("400", {
normaAlias: "LEC",
top: 10,
});
// Procedural time limits — `jurisdiction` is required and has NO default.
// A period counted under another jurisdiction's rules gives you a date you may act on.
const plazo = await nexus.plazos.calcular({
jurisdiction: "ES", // LEC + LOPJ, CGPJ and regional holidays, August non-working
fechaBase: "2026-05-29",
cantidad: 20,
tipoComputo: "habiles",
ccaa: "ES-MD",
});
// England and Wales — CPR r 2.8 (clear days; no August vacation)
const appellantsNotice = await nexus.plazos.calcular({
jurisdiction: "GB-EAW",
fechaBase: "2026-05-01",
cantidad: 21, // CPR r 52.12(2)(b)
tipoComputo: "naturales", // returned as `clear_days`
});
// → { jurisdiction, fecha_vencimiento, regla_aplicable, ajustes_aplicados, ... }
// Verify a statute citation against the vigent corpus (anti-hallucination)
const cita = await nexus.normativa.verifyCita({
citation: "Art. 1902 CC",
claimText: "El que por acción u omisión causa daño a otro...",
});
// → { status: "verified"|"mismatch"|"not_found"|"derogated"|"pending", similarity, url }
// Verify a case-law citation (ECLI / ROJ)
const citaJuris = await nexus.jurisprudencia.verifyCita({
citation: "ECLI:ES:TS:2023:1234",
claimText: "El Tribunal declara la nulidad parcial...",
});
// Case email inbox (email-to-matter)
const inbox = await nexus.cases.emails.list(caseId, { limit: 20 });
const alias = NexusClient.inboundEmailAlias(caseId); // sin llamada de redResult integrity
A 200 tells you the call worked, not that the result is complete. These fields are
what tell you the second thing — read them before using anything:
const d = await nexus.cases.draft(caseId);
if (d.truncated) throw new Error("The engine stopped mid-output: the draft is incomplete.");
if (d.corpusPartial) {
// chunksTotal === null means the denominator could NOT be counted — not "no more".
console.warn(`Written over ${d.chunksUsed} of ${d.chunksTotal ?? "an unknown number of"} chunks.`);
}
if (d.piiResiduals?.length) console.warn("Personal-data markers left in the text:", d.piiResiduals);
if (d.citationsOrigenC?.length) console.warn("Citations not backed by the case file:", d.citationsOrigenC);
if (d.killSwitch) console.warn(`Watchdog ${d.killSwitch.level}: ${d.killSwitch.reason}`);Three rules that apply to all of them (see the TruthSignals type for the full
catalogue and the per-field reasons):
falseand0are answers.truncated: falseasserts the text is whole.nullmeans "could not be measured", never "there is none".chunksTotal: 0says the case file has no chunks;chunksTotal: nullsays the count failed and you do not know the coverage. Never?? 0one of these.- An absent field means this surface does not emit it — not that all is well.
The same rule runs through the rest of the API surface: audited: false on an audit
means Node B produced no verdict (its findings: [] is filler, not "nothing found");
counts_measured: false on cases.list() means every document_count is null;
crossChecked: false means the cross-check list came back unreadable;
termination: "caller_stopped" on a consensus job means the second review never ran;
noteCode: "COVERAGE_UNKNOWN" on a legislation search means the empty result is not
evidence of absence; a 503 BILLING_SUMMARY_READ_FAILED means the balance could not
be read — it does not mean zero.
Error handling
import {
InsufficientCreditsError,
RateLimitError,
ValidationError,
} from "@nexus-legal/sdk";
try {
await nexus.analyze({ text, jurisdiction: "ES" });
} catch (err) {
if (err instanceof InsufficientCreditsError) {
console.error(`Need ${err.required} credits, have ${err.balance}.`);
} else if (err instanceof RateLimitError) {
console.warn(`Rate limited. Retry in ${err.retryAfter}s.`);
} else if (err instanceof ValidationError) {
console.error(`Bad request: ${err.message}`);
// err.code is a stable identifier (VALIDATION_ERROR, BATCH_TOO_LARGE, ...)
console.error(`Code: ${err.code}, request_id: ${err.requestId}`);
} else {
throw err;
}
}When the engine that failed is yours (BYO) — three different failures with three different fixes, so they are three different classes:
import {
ByoProviderAccountError, // 424 — your provider rejected it: credit, key, quota
ProviderUnreachableError, // 503 — your endpoint could not be reached (transport)
ByoProviderRequiredError, // 409 — this surface needs your own engine; none configured
} from "@nexus-legal/sdk";
catch (err) {
if (err instanceof ByoProviderAccountError) {
// Nothing was charged and Nexus did NOT fall back to another engine: your
// documents only ever go to the provider you configured. Retrying will not
// help — `err.reason` is credit_exhausted | invalid_key | access_denied |
// provider_rejected, and `err.provider` is the engine's label.
} else if (err instanceof ProviderUnreachableError) {
// Transport failure of YOUR endpoint (`err.errorClass`), not a Nexus outage.
} else if (err instanceof ByoProviderRequiredError) {
// Configure a provider for this node, then re-run.
}
}Error format (v1.6.0+) — stable, Stripe-style:
{
"error": {
"type": "invalid_request_error",
"code": "VALIDATION_ERROR",
"message": "Texto demasiado corto (mín. 50 chars).",
"request_id": "req_abc-123",
"details": { "field": "text", "min": 50, "got": 12 }
},
"error_message": "Texto demasiado corto (mín. 50 chars).", // backward-compat alias
"code": "VALIDATION_ERROR" // backward-compat alias
}Every response (success or error) includes header X-Request-Id: req_<uuid>. The SDK surfaces it as err.requestId — reference it in support tickets. You can also pre-set your own via X-Request-Id header (validated regex [A-Za-z0-9_-]{8,100}, ignored otherwise).
Error types: invalid_request_error, authentication_error, permission_error, rate_limit_error, insufficient_credits_error, not_found_error, conflict_error, api_error.
Idempotency
Every POST is sent with a fresh Idempotency-Key. If the network fails between the request and the response, the SDK retries with the same key — Nexus returns the cached result (24-hour TTL) without re-charging credits. The flag result.idempotencyReplayed tells you whether the response came from the cache.
To use your own key (e.g. derived from a domain identifier so multiple processes converge):
await nexus.analyze(
{ text, jurisdiction: "ES" },
{ idempotencyKey: `expediente-${expedienteId}` },
);Reusing the same key with a different body throws IdempotencyConflictError (HTTP 409).
Retries
By default the SDK retries 429 / 5xx up to 3 times with exponential backoff (min(2^attempt, 30s) + jitter). Override per client or per call:
const nexus = new NexusClient({ apiKey, maxRetries: 5 });
// or per request
await nexus.analyze({ text, jurisdiction: "ES" }, { maxRetries: 0 });Network failures and TimeoutErrors are retried with the same policy.
Audit-trail parsing
import { extractAuditTrail } from "@nexus-legal/sdk";
const result = await nexus.analyze({ text, jurisdiction: "ES" });
const trail = extractAuditTrail(result.analysis);
if (trail?.levels_emitted["L5-C"] && trail.levels_emitted["L5-C"] > 0) {
// Critical contractual risk — escalate to human reviewer.
}
for (const flag of trail?.review_flags ?? []) {
await createTask({ title: flag });
}The parser is intentionally narrow (no YAML dependency). For arbitrary YAML, use the raw field with js-yaml.
Cancellation and timeouts
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 5_000);
await nexus.analyze({ text, jurisdiction: "ES" }, { signal: ctrl.signal });Per-call timeouts override the client-level default:
await nexus.analyze({ text, jurisdiction: "ES" }, { timeout: 60_000 });TimeoutError is retried like network errors.
Compatibility
| Runtime | Status |
| -------------------- | ---------------- |
| Node.js ≥ 18 | ✅ first-class |
| Bun | ✅ |
| Deno | ✅ (via npm:) |
| Cloudflare Workers | ✅ |
| Vercel Edge runtime | ✅ |
| Browser | ⚠️ technically works, but never ship an API key to the browser — proxy through your backend |
Versioning
This SDK targets API v1.x and follows SemVer:
- MAJOR — drops support for an API breaking change (we mirror Nexus's 6-month deprecation window).
- MINOR — new endpoints, new fields, new options.
- PATCH — bug fixes, doc improvements.
See the API changelog.
License
MIT — see LICENSE.
Built by Nexus Legal. Questions? Email [email protected].
