@pendral/trajective
v0.1.0
Published
Trajective governance SDK: emit AI traces, spans, audit and policy events from any product to the Trajective control plane, and enforce its policies locally.
Downloads
2,560
Readme
@pendral/trajective
The one dependency a product adds to become governable.
Trajective is the governance control plane for our AI products. This package is how a product talks to it. It does three things, all optional, all fail-open:
- Traces — every model call, tool call, retrieval and agent run, with usage, latency and cost.
- Events — audit actions, policy decisions, PII detections, human reviews, incidents, evals.
- Policy — the tenant's model allow/deny lists, budgets, content-capture mode and rules, pulled from the control plane and enforced locally, in-process, before the provider is called.
Three rules govern this package:
- It never breaks the product. No function throws into your code path. With no API key it is a silent no-op. Every network failure degrades to a log line. A full queue drops rather than grows.
- It never blocks a response. Sends are batched and fire-and-forget.
- Sensitive content is opt-in and separable. Prompts and completions travel in content blocks with a mode, so a tenant can keep hashes only, redacted text, or the full payload — and change their mind without the product being redeployed.
Install
npm install @pendral/trajectiveConfigure by environment; nothing else is required:
TRAJECTIVE_ENDPOINT=https://trajective.evryhealth.com
TRAJECTIVE_API_KEY=trj_prod_... # per product, per environment
TRAJECTIVE_TENANT_ID=org_123 # default tenant when a trace doesn't name one
TRAJECTIVE_CONTENT_MODE=hash # none | hash | redacted | full
TRAJECTIVE_SUBJECT_SALT=... # so subject hashes can't be joined across tenantsWithout TRAJECTIVE_API_KEY and TRAJECTIVE_ENDPOINT the client is disabled and every call below is a
no-op, so a product can ship the instrumentation before the control plane exists.
Quick start
// lib/trajective.ts — one instance per process
import { createTrajective } from "@pendral/trajective";
export const trajective = createTrajective({
product: { id: "inline", version: process.env.APP_VERSION },
environment: process.env.NODE_ENV,
});
// Announce the product on boot. Drives the control plane's inventory and model registry.
await trajective.register({
display_name: "+inline_",
environments: ["dev", "prod"],
capabilities: ["llm", "tools", "cost", "audit_log", "policy_enforcement"],
models: [{ provider: "anthropic", model: "claude-opus-5", purpose: "review" }],
policy_hooks: ["models", "budgets", "content", "rules"],
});register also reports the entity types this process can actually redact,
filled in from its real detector set rather than declared by hand. That is what
lets the control plane refuse to publish a redaction policy naming an entity
nothing can detect, instead of the promise failing silently at runtime.
Tracing
A trace is one unit of work a governance officer would recognise: a PR review, a phone call, a chat turn, a nightly analysis. Spans are what happened inside it.
await trajective.withTrace(
{ kind: "review", name: `PR ${pr.number}`, actor: { type: "user", id: userId }, scope: { repo_id: repo.id } },
async (trace) => {
await runReview(); // model and tool calls below nest automatically
trace.setScope({ job_id: job.id }); // ids discovered late still land on the record
},
);Nesting is ambient — AsyncLocalStorage carries the trace, so no recorder has to be threaded through
function signatures. A withTrace inside another withTrace opens a span instead of a second record.
For work that outlives the function that starts it (a streaming route that returns a Response while
the model is still generating), open the trace by hand:
const trace = trajective.startTrace({ kind: "chat", name: "session" });
stream.onFinish(() => trace.end());
stream.onError((error) => trace.end({ error }));Across processes, pass the header:
// producer
fetch(url, { headers: { [TRACE_HEADER]: trace.toHeader() } });
// consumer
const trace = trajective.continueTrace(req.headers.get(TRACE_HEADER), { kind: "api", name: "handler" });The AI SDK integration
If the product uses the Vercel AI SDK, this is the whole integration:
import { wrapLanguageModel } from "ai";
import { trajectiveMiddleware, trajectiveTools } from "@pendral/trajective/ai-sdk";
import { trajective } from "@/lib/trajective";
export function model(id: string) {
return wrapLanguageModel({ model: anthropic(id), middleware: trajectiveMiddleware(trajective) });
}Middleware sits under generateText, streamText, generateObject and embed alike, so a
classification pass written next year is on the record without anyone remembering to instrument it.
Each call records provider, request and response model, token usage split into uncached / cache-read
/ cache-write / reasoning, cost, latency, time-to-first-token, finish reasons, the call parameters
worth auditing, and — per content mode — the prompt and the completion.
Tool executions get their own spans, with a category the policy can act on:
const tools = trajectiveTools(trajective, { lookup_member, send_email }, {
categories: { lookup_member: "phi", send_email: "external" },
});Per-call context rides in providerOptions:
streamText({
model,
providerOptions: { trajective: { purpose: "member-chat", actor, subject, no_content: false } },
});Policy
The control plane hands back a signed bundle; the SDK caches it (honouring ETag and ttl_s) and
enforces it in-process:
{
"models": { "allow": ["anthropic/*"], "deny": ["openai/*"], "default": "anthropic/claude-haiku-4-5" },
"budgets": { "monthly_usd": 5000, "alert_pct": [80, 100], "hard_stop": false },
"content": { "capture": "redacted", "retention_days": 30, "redact_entities": ["SSN", "MRN", "EMAIL"] },
"review": { "route_to_human": { "tool_categories": ["phi", "write"] } },
"rules": [{ "id": "no-phi-to-fast-tier", "when": { "purpose": "phi-summary", "model": { "prefix": "claude-haiku" } }, "then": "deny" }]
}The bundle is signed with an HMAC keyed by the product's ingest key — the one
secret the control plane and the product both hold — so a product can prove the
policy it is enforcing came from the control plane untampered. A bundle whose
signature does not verify is refused rather than enforced, and refusing it is not
silent: it is logged on every poll, policyStatus() returns "rejected" rather
than "none", and an incident is raised so the governance team can see that a
product is running unpoliced. Check policyStatus() on a health endpoint.
A denied model throws TrajectivePolicyError before the provider is called; pass
{ enforce: "log" } to the middleware to record the decision and let the call through while a new
policy is being rolled out. Either way the decision is emitted as a policy.decision event, so "what
did the policy actually do last month" is answerable.
content.capture can only ever make capture more restrictive than the product's own setting — a
tenant policy can never turn on full prompt capture in a product that asked for hashes.
Events
trajective.audit({ action: "role.grant", target_type: "user", target_id: "u_2", summary: "granted auditor" });
trajective.emit("human.review", { review_id, state: "approved", reviewer_id, time_in_queue_ms });
trajective.emit("incident", { severity: "sev2", category: "data_leak", summary, state: "open" });
trajective.emit("eval.result", { eval_suite: "hallucination", metric: "accuracy", score: 0.91, passed: true });Events inherit the active trace, span, actor and subject, so an audit line written inside a trace is already linked to the model calls that produced it. Every event carries a ULID that the control plane de-duplicates on, so a retried batch is not a double entry in the audit log.
Content and PII
span.addContent(trajective.content(promptText, "input"));| mode | what travels |
|---|---|
| none | nothing |
| hash | sha256 + byte count |
| redacted | text with PII replaced by [EMAIL], [SSN], …, plus a per-type count |
| full | the text verbatim |
The digest is always of the original text, in every mode, so the same prompt is recognisable
across tenants and modes without the text ever being stored. Redaction covers email, SSN, Luhn-valid
card numbers, phone, DOB, MRN / member id, IP and API-key-shaped secrets; supply your own detectors
for anything stronger. Every redaction emits a data.detection event, which is what turns "we redact
PHI" into evidence an auditor can read.
Subject ids are hashed with a per-deployment salt:
subject: trajective.subject("member", memberId, "phi") // { type, id_hash, data_class }Products that already have a trace store
Two adapters map an existing store onto the wire format, so a product with its own traces is not instrumented twice:
import { exportInlineTrace } from "@pendral/trajective/adapters/inline"; // AgentTrace / AgentSpan
import { exportVocalisTrace } from "@pendral/trajective/adapters/vocalis"; // AiTraces / AiSpansCall either one when a trace is finalised. Both honour the content mode and hash subjects on the way out.
Local development
npx trajective-sink --port 4319 --policy ./examples/policy.example.json --verbose
TRAJECTIVE_ENDPOINT=http://localhost:4319 TRAJECTIVE_API_KEY=trj_dev npm run devThe sink implements the real ingest routes, prints a readable summary of every trace and event, and serves a policy bundle from a file — so model allow/deny lists and content modes can be exercised without the control plane running.
In tests, swap the transport instead:
import { MemorySink } from "@pendral/trajective/testing";
const sink = new MemorySink();
const trajective = createTrajective({ product: { id: "x" }, transport: sink, tenantId: "t" });
// ...
await trajective.flush();
expect(sink.spans()).toHaveLength(2);
expect(sink.events("policy.decision")[0].attributes.outcome).toBe("deny");Shutdown
process.on("SIGTERM", () => void trajective.shutdown());Wire contract
src/types.ts holds the plain shapes; @pendral/trajective/schema exports Zod validators for the same
contract, and a compile-time assertion keeps the two from drifting. The control plane validates every
ingest with them.
POST /api/ingest/v1/traces—{ traces: [{ trace, spans[] }] }. Both upsert by id; a trace is sent when it opens, after every span, and when it closes, so a long-running trace is visible while it runs.POST /api/ingest/v1/events—{ events: [] }, de-duplicated on the event ULID.POST /api/ingest/v1/register— the product describes itself and its models.GET /api/ingest/v1/policy— the signed bundle, withETag/304. The request carriesx-trajective-policy-statusandx-trajective-policy-version, so the control plane can tell a product that pulls and enforces from one that pulls and rejects. Both look like a pull otherwise.
Span kinds follow the OpenTelemetry GenAI conventions (invoke_agent, turn, chat,
execute_tool, embeddings, retrieval, stt, tts, plus guardrail and operation), so a
trace can also be exported to any OTel backend later.
Development
npm run verify # typecheck, build, then the full suite (sources and built artifacts)The suite includes tests that run against the built bundles, not only the sources: each entry point is bundled separately, and a duplicated module-level singleton there would silently break trace nesting in a way source-only tests cannot see.
