Skip to content

TypeScript SDK

The official TypeScript SDK for the InPolicy governance API. Adds type safety, safe automatic retries, and a clean ergonomic surface.

Terminal window
npm install @inpolicy/sdk
import { InPolicyClient } from '@inpolicy/sdk';
const ip = new InPolicyClient({
apiKey: process.env.INPOLICY_API_KEY!,
// all optional:
baseUrl: 'https://api.inpolicy.ai/api/v1/agent',
timeoutMs: 30_000,
maxRetries: 2,
userAgent: 'my-support-agent/1.4.0',
});

One client per API key; safe to reuse across requests.

const result = await ip.recordTurn({
sessionId: 'sess_abc',
turn: { role: 'user', content: "I'm 16 — can I buy this?" },
});
console.log(result.activePolicies); // what's active now
console.log(result.injectionBlock); // paste into your system prompt
console.log(result.diff.newlyApplicable); // what just became active

The full RecordTurnInput shape:

{
sessionId: string; // letters, digits and . _ : @ + = -, 1 to 200
turn: { role: 'user' | 'assistant' | 'tool'; content: string }; // content max 100,000 chars
recentContext?: string[]; // last 2-3 prior turns, for disambiguation
priorHistory?: string[]; // bootstrap on first call only
endUserContext?: {
ephemeralId?: string;
attributes?: Record<string, unknown>; // satisfies subjectBinding; scope with country/teams
};
policyAreaIds?: string[]; // 1-50 policy areas of your workspace; omit for all
country?: string; // ISO 3166-1 alpha-2, e.g. 'GB' (see below)
tokenBudget?: number; // injection_block size, default 600
idempotencyKey?: string; // same characters as sessionId, 1 to 200; the same request
// within 5 min returns the same response, and the same
// key with any field different is a 409
checkOutput?: boolean; // only when role='assistant'; needs governance:check
ttlSeconds?: number; // idle timeout (300 to 604800 s); later turns keep it
}

sessionId (and a stream’s replyId) must match ^[A-Za-z0-9._:@+=-]{1,200}$; any other id gets a 400 on every governance call. Hash or base64url-encode ids with /, #, spaces, other characters or more than 200 characters. Earlier versions of the API accepted any non-empty string.

Country. Pass country (an ISO 3166-1 alpha-2 code such as 'GB', usually where the end user is) on recordTurn, preInference, postInference, checkToolCall and streamCheckOutput so policies scoped to countries apply only where they should. Leave it out and no country filter is applied. With a signed-in user’s token the profile country is used instead. See API reference.

// post_inference_checking is on by default for new keys
const check = await ip.postInference({
output: draft,
sessionId: 'sess_abc',
});
if (!check.checked) {
// Not checked: `decision` follows the key's on_check_error setting.
// Log it; don't treat it as clean.
} else if (check.decision === 'block') {
if (check.suggestedRedaction) {
return check.suggestedRedaction; // every finding rewritten; safe to send
}
// Null: regenerate with the violations as guidance, or route to a person
}

A violation’s enforcementType is fix when enforcementText holds a rewrite of matchedText, and warning when it holds advice only (audit is never returned here; ApplicablePolicy.enforcement can still be audit). suggestedRedaction is not null only when every finding that counts toward decision is a fix whose rewrite applies cleanly and leaves no flagged text behind, so you can send it as is. A single warning finding makes it null; then regenerate. Prefer it to splicing enforcementText over matchedText yourself.

// tool_call_governance is on by default for new keys
const ok = await ip.checkToolCall({
sessionId: 'sess_abc',
toolName: 'send_email',
arguments: { to: 'customer@...', subject: '...', body: '...' },
});
if (!ok.checked) {
// Not checked: `allow` follows the key's on_check_error and
// `violations` is empty.
if (!ok.allow) return "I couldn't check that email against policy, so I didn't send it.";
} else if (!ok.allow) {
return `I can't send that email — ${ok.violations[0]?.explanation ?? 'it breaks a policy'}`;
}
await actuallySendEmail();
const snapshot = await ip.getConversationState('sess_abc');
// { turnCount, activePolicies, injectionBlock, bindingLog, updatedAt }
await ip.endConversation('sess_abc'); // delete conversation state; safe to call twice

endConversation throws an InPolicyApiError with status: 409 if a turn for the same session is still being saved. Call it again.

streamCheckOutput checks a reply while your LLM streams it. It keeps reading your source while a check runs, sends at most one check at a time, and yields events in order:

Event When Fields
violation A check found a new violation (each is reported once per reply) violation, watermark, decision, traceId
progress A check finished processedChars, watermark, decision
unchecked A segment was not checked; finalize still covers it reason, watermark
complete Finalize returned (the default) verdict: the whole-output result, as postInference
final Only with finalize: false: the closing isFinal chunk returned decision, checked, uncheckedReason, riskScore, watermark, traceId
error A call failed message, recoverable, status, code, retryAfterMs, budget (on a 402)

decision is the segment’s decision on an incremental chunk and the whole reply’s on the closing chunk. On final, riskScore is the reply’s highest. When the closing chunk was not checked, final has checked: false and decision: null (or block if an earlier chunk blocked): the stream route does not apply on_check_error, so handle a null decision per your own on_check_error (with block, hold the reply). With finalize: false, a failed closing chunk ends the stream with an error whose recoverable is false, and no final event. If you switch over evt.type exhaustively, include final and unchecked.

An incremental chunk that fails with a network error, a timeout, 408, 429 or 5xx gives error with recoverable: true, and finalize still runs. Any other 4xx on a chunk (400, 401, 402, 403, 404, …) gives one error with recoverable: false; the SDK then sends no more chunks and no closing call, reads your source to its end, and the stream ends with no complete or final. Treat that reply as not checked. An empty or whitespace-only output is not checked and the stream ends with no event at all.

A 200 the SDK cannot read (a null body, no numeric watermark, or a newViolations that is not a list) is an error with status: 200 and a message starting malformed streaming check response: recoverable: true on an incremental chunk, recoverable: false on the closing chunk with finalize: false. A body that is not JSON at all is an error too, without a status.

With finalize: false, final.decision is the worst of every chunk result the SDK received and the server’s closing answer, and final.riskScore is the highest of any chunk, so a chunk that blocked is never lost.

Every chunk and the finalize call carry one replyId: opts.replyId if you pass one (for example your message id), otherwise a random UUID per call. If you pass your own, use a new one for every reply: the API treats a replyId used again as the same reply, counted once and keeping what the earlier reply found. StreamingViolation.offset, watermark and the lastCheckedOffset you pass to streamCheckOutputOnce or finalizeStreamingCheck are JavaScript string indices (UTF-16 code units); the SDK converts to and from the API’s Unicode code points. See Streaming check_output.

Every non-2xx response throws an InPolicyApiError:

Field What it holds
status HTTP status.
message The server’s reason (several validation messages joined with ; ), or InPolicy API <status> <method> <path> when the body had none.
code The API’s error code when it sent one, e.g. TENANT_TOKEN_BUDGET_EXCEEDED, RATE_LIMIT_EXCEEDED.
traceId The failed request’s trace id. Quote it to InPolicy support.
details The parsed JSON error body.
body The raw body (up to 10,000 characters).
retryAfterMs From Retry-After, or the body’s retryAfterSeconds.

A 402 with code TENANT_TOKEN_BUDGET_EXCEEDED throws BudgetExceededError, which is also an InPolicyApiError. It has budget: { capCents, usedCents, periodEnd } (or null if the server sent none). The message was not checked; checks resume at budget.periodEnd. The SDK does not retry a 402.

import { BudgetExceededError, InPolicyApiError } from '@inpolicy/sdk';
try {
await ip.recordTurn({ ... });
} catch (err) {
if (err instanceof BudgetExceededError) {
// Not checked. Hold the message or route it to a person until
// err.budget?.periodEnd.
} else if (err instanceof InPolicyApiError) {
if (err.status === 400) {
// err.message says what to fix in the request.
} else if (err.status === 401 || err.status === 403) {
// 401: key missing, invalid or revoked. 403: the key lacks a scope
// (e.g. governance:check for checkOutput) or a feature gate is disabled.
// Retrying will not help.
} else if (err.status === 409) {
// conversation/turn: idempotencyKey reused for a different request, or
// another turn on the same session is still being saved (retry that one).
// endConversation: a turn is still being saved; retry.
} else if (err.status === 429) {
// Rate limited for longer than the SDK waits on its own (5 s).
// err.retryAfterMs says when to try again.
} else if (err.status >= 500) {
// A check (POST) is not retried on 5xx: it may already have run and
// been billed. Retry it yourself with an idempotencyKey where the call
// takes one, or treat it as unchecked.
}
}
// network / timeout errors also reach here, not wrapped in InPolicyApiError
}

The SDK retries only what is safe to send twice:

  • ✅ Reads (GET, DELETE): on 5xx, network errors and timeouts.
  • ✅ Any call refused with 429 before it ran, waiting out Retry-After when it is 5 seconds or less. A longer wait throws InPolicyApiError with status: 429 and retryAfterMs.
  • ❌ Checks (POST) on 5xx, network errors or timeouts: the check may still be running and may already have been billed, so re-sending it would check and bill the message again.
  • ❌ Other 4xx responses, including 402 (the request itself is wrong or can’t run; retrying won’t help).

Backoff is exponential with jitter (100 ms, 200 ms, 400 ms, … capped at 2 s) unless Retry-After says otherwise. Tune with maxRetries (default 2, giving 3 total attempts).

import { InPolicyClient } from '@inpolicy/sdk';
import OpenAI from 'openai';
const ip = new InPolicyClient({ apiKey: process.env.INPOLICY_API_KEY! });
const openai = new OpenAI();
class Conversation {
constructor(public sessionId = crypto.randomUUID()) {}
async say(userMessage: string): Promise<string> {
const pre = await ip.recordTurn({
sessionId: this.sessionId,
turn: { role: 'user', content: userMessage },
});
const res = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: `You are a support agent.\n\n${pre.injectionBlock}` },
{ role: 'user', content: userMessage },
],
});
const output = res.choices[0].message.content ?? '';
await ip.recordTurn({
sessionId: this.sessionId,
turn: { role: 'assistant', content: output },
});
return output;
}
async end() {
await ip.endConversation(this.sessionId);
}
}
const chat = new Conversation();
console.log(await chat.say("I'm 16 — can I buy this?"));
console.log(await chat.say("Okay, can I at least see the product page?"));
await chat.end();

Python support is on the roadmap. In the meantime, call the REST API directly. The shape is the same as documented in the API reference, and Python requests/httpx work fine.