@pendral/platform
v0.11.0
Published
Official TypeScript SDK and CLI for the EvryAI Platform: governed AI agents, runs, approvals, journeys, sandboxes and webhooks.
Readme
EvryAI Platform SDK
The official TypeScript SDK for the EvryAI Platform. Build AI agents that act for your members and customers under enterprise governance: every tool call is checked against the member's consent and your policies, sensitive actions wait for approval, and each decision lands in a tamper-evident audit trail.
- Fully typed. Every request and response is typed from the API definition, with no extra dependencies.
- Safe retries. Every write carries an idempotency key, and retries never run twice.
- Live runs. Stream an agent's work as it happens, with automatic resume after a dropped connection.
- Governance built in. Grants, policies, approvals, reviews and a hash-chained audit trail.
- Guardrails and budgets. PII and PHI redaction before the model reads a tool result (20 identifier types, checksum-validated), prompt-injection defense for tool results, AI disclosure notices, checks on every reply, and cost, token, tool call and time limits per run.
- Policy that knows the context. Rules on time of day in your timezone, the channel, your own session attributes and how often a tool already ran for a member (velocity limits).
- A kill switch. Suspend an agent from code or the CLI: new runs are refused, active ones cancelled, schedules skip, all audited.
- Durable agents. Schedules, memory across sessions and crash retries that never repeat a write.
- Journeys and evals. Multi-step flows across agents, and test suites that gate every release, from CI with
evryai evals gate. - Direct tool calls. When your code already knows the tool and its input (a voice turn, a button, a job), call it in one request with no model step, under the same grant, policy, approvals, guardrails and audit.
- Verified tool calls. Check who each tool call acts for with
@pendral/platform/toolsbefore your system does anything. - Independent audit checks. Recompute the audit chain on your side with
verifyAuditChain, and stream it to your SIEM as OCSF or CEF. - A testing kit. Unit test your integration, tool endpoints and webhook handlers with
@pendral/platform/testing, without calling EvryAI. - Runs anywhere. Node.js 18+, Bun, Deno and edge runtimes.
Installation
npm install @pendral/platformGetting started
Create an API key in the developer console and set it as EVRYAI_API_KEY.
Use a evk_test_ key while you build; test and live data never mix.
import { EvryAI } from "@pendral/platform";
const evry = new EvryAI(); // reads EVRYAI_API_KEY
const session = await evry.sessions.create({ agentId: "agt_...", subject: "member-8812" });
const run = await evry.runs.create({
sessionId: session.id,
message: { text: "Can I refill my prescription?" },
});
const result = await evry.runs.wait(run.id);
console.log(result.status, result.output?.text);Streaming
Follow a run live. The stream resumes from the last event if the connection drops, and ends when the run finishes or needs you.
for await (const event of evry.runs.stream(run.id)) {
if (event.event === "text.delta") process.stdout.write(String(event.data.text));
}text.delta is live only. When each model step ends, its full text is stored as message.completed (after the output
guardrails), so a client that reconnects mid-run rebuilds the reply from the replay: replace that step's streamed deltas with it.
import { isRunEvent } from "@pendral/platform";
const steps = new Map<number, string>();
for await (const event of evry.runs.stream(run.id)) {
if (isRunEvent(event, "message.completed")) steps.set(event.data.step, event.data.text);
}
console.log([...steps.values()].join("\n\n"));Start a run and its stream in one request, a round trip sooner than runs.create then runs.stream:
const { runId, events } = await evry.runs.createAndStream(
{ sessionId: session.id, message: { text: "When is my next visit?" } },
{ idempotencyKey: "turn-42" }
);
for await (const event of events) {
if (event.event === "text.delta") process.stdout.write(String(event.data.text));
}
console.log(runId);Context for one run
context gives the agent text from your own system for one run only, such as today's appointments or the screen the member is on
(up to 8,000 characters). The agent reads it as system context after its instructions. It is not a member message: it is not stored in
the session's conversation, later runs never see it, and it is not screened or redacted as member input, so never put member-typed text
in it. The run shows only its size and SHA-256 hash, and the audit trail records the same as run.context.
await evry.runs.create({
sessionId: session.id,
message: { text: "When is my next visit?" },
context: "Upcoming: Dr. Lee, Tuesday 9:15. Member prefers short answers.",
});Every run also tells the agent the current date, time and weekday. Set the session's timezone metadata to an IANA name to use the
member's local time; anything else falls back to UTC.
await evry.sessions.create({ agentId: agent.id, subject: "member-8812", metadata: { timezone: "America/New_York" } });Handing off to another agent
handoff starts a run that continues work another run began, on any agent and in any session for the same subject (or between
sessions with no subject). The agent reads
the source run's conversation (the person's and the agent's turns, tools called, results clipped), keeping the most recent turns within
maxChars (default 8,000, at most 20,000), as data for this run only. The run shows handoff, and the audit trail records
run.handoff pointing at the source run. If the source acted under a grant, the new session needs an active grant for the
same subject that covers its agent (GRANT_REQUIRED otherwise). The link is kept in the run's own fields, not its metadata.
declare const triageRunId: string;
const billingSession = await evry.sessions.create({ agentId: "agt_billing", subject: "user-8812", grantId: "grt_..." });
const next = await evry.runs.create({
sessionId: billingSession.id,
message: { text: "Please reorder it." },
handoff: { fromRunId: triageRunId },
});
console.log(next.handoff); // { fromRunId, fromSessionId, fromAgentId }Reasoning
Models that can reason think before they answer. Pick a model and an effort from models.list(), set it on the agent, and follow the
thinking live with reasoning.delta. Each finished block is also stored as model.reasoning, in order with the tool calls it led to.
import { isRunEvent } from "@pendral/platform";
const models = await evry.models.list();
const model = models.find((m) => m.reasoning.supported)!;
await evry.agents.update({ agentId: agent.id, model: model.id, reasoning: { effort: "high" } });
for await (const event of evry.runs.stream(run.id)) {
if (isRunEvent(event, "reasoning.delta")) process.stderr.write(event.data.text);
if (isRunEvent(event, "text.delta")) process.stdout.write(event.data.text);
}When a run needs you
A run pauses with requires_action when a person must approve an action, or when a tool runs in your own systems.
let current = await evry.runs.wait(run.id);
while (current.status === "requires_action") {
const action = current.requiredAction;
if (action?.type === "submit_tool_outputs") {
const outputs = await Promise.all(
action.toolCalls.map(async (call) => ({ toolCallId: call.id, output: await runTool(call.name, call.input) }))
);
await evry.runs.toolOutputs.submit({ runId: current.id, outputs });
} else if (action?.type === "approval") {
const approval = await evry.approvals.get({ approvalId: action.approvalId });
// Show approval.toolCall to the member exactly as it is, then:
await evry.approvals.approve({ approvalId: approval.id, inputHash: approval.inputHash });
} else {
break; // A reviewer resolves the case in your workflow.
}
current = await evry.runs.wait(current.id);
}A client tool can need an approval too. Once approved, the run pauses again with submit_tool_outputs for that call and its approved
input, so your app performs it exactly once. A denied call goes back to the agent as declined.
Asking first, outside a run
When a schedule, a webhook or your own code finds something to do for a member, propose it and let them decide later. Nothing runs until they approve. Approving runs the call once through the governed gateway, where their grant and the agent's policy decide again, and it is audited like any governed call. Denying runs nothing.
const approval = await evry.approvals.create(
{
sessionId,
subject: "member_8812", // optional: must be the session's member
tool: "renew_subscription",
input: { subscriptionId: "sub_31" },
title: "Renew your annual plan?",
details: "Renews on the card on file for $120.",
expiresAt: new Date(Date.now() + 48 * 3600_000).toISOString(), // at most 30 days; defaults to the agent's wait limit
},
{ idempotencyKey: "renewal:sub_31:2026-11-16" }
);
// Later the member says yes to several at once. Each item is decided on its own.
const pending: Array<{ id: string; inputHash: string }> = [approval];
const { results } = await evry.approvals.decideMany({
items: pending.map((a) => ({ id: a.id, inputHash: a.inputHash })),
decision: "approve",
decidedBy: "member:8812",
});
for (const result of results) {
if (!result.ok) console.warn(result.id, result.error?.code); // CONFLICT (stale inputHash), INVALID_STATE (decided or expired)
}
// The proposed call is a direct tool call: its result arrives on approval.runId.
const done = await evry.toolCalls.wait(approval.runId);A proposal the grant or policy refuses now fails with POLICY_DENIED and creates nothing, as does one the policy would send to a
reviewer. It needs approvals:write and tool_calls:write.
Every approval has an expiresAt. Past it, the approval reads expired, approving it returns INVALID_STATE, nothing runs, and
an approval.expired webhook carries the approval.
Run to completion
runs.execute starts a run and drives it to the end. It streams events, runs your client tools when the agent calls them, and asks
you what to do when a person must decide. It returns the final run and its reply.
const { run, text } = await evry.runs.execute(
{ agentId: "agt_...", subject: "member-8812" },
{
message: "Can I refill RX123?",
clientTools: {
// Runs in your process. Throw to tell the agent the call failed.
read_chart: async (input) => chart.read(input),
},
onEvent: (event) => {
if (event.event === "text.delta") process.stdout.write(String(event.data.text));
},
// "wait" polls until someone approves or denies; "cancel" cancels the run; nothing returns the paused run.
onApproval: async (action) => (action.type === "approval" ? "wait" : undefined),
timeoutMs: 10 * 60_000,
}
);Pass { sessionId } instead to continue a conversation. A client tool with no handler, or one that throws, is reported to the agent
as an error (CLIENT_TOOL_MISSING or CLIENT_TOOL_FAILED). Each submission carries an idempotency key derived from the run and its
tool call ids, so retrying never submits twice.
Guardrails and budgets
Guardrails and limits are part of an agent version, so they are versioned, evaluated and promoted with it.
const agent = await evry.agents.create({
name: "Pharmacy assistant",
model: "auto",
instructions: "Help members refill prescriptions. Never give dosing advice.",
toolIds: [lookupMember.id, checkRefill.id],
guardrails: {
toolOutputPii: "redact", // the model never reads these identifiers in tool results
piiEntities: ["ssn", "mrn", "mbi", "dob", "card"],
outputPii: "redact", // nor writes them in a reply
outputRules: [{ id: "no_dosing", pattern: "\\b[0-9]+ ?mg\\b", action: "block", reason: "Dosage advice needs a pharmacist." }],
},
limits: { maxCostUsd: 0.5, maxToolCalls: 20, maxDurationSeconds: 120 },
});Each trigger adds a guardrail.triggered run event and an audit record naming the entity types, never the values. A blocked reply
fails the run with GUARDRAIL_BLOCKED; a spent budget fails it with BUDGET_EXCEEDED, TOOL_CALL_LIMIT or RUN_TIMEOUT.
Set inputPii: "redact" to redact the same identifiers in the person's own message before it is stored or read by the model.
piiEntities defaults to ssn, email, phone, card, dob, mrn, mbi and ip. Name any of itin, ein, iban, routing,
bank_account, npi, dea, passport, drivers_license, vin, uk_nino and ca_sin to add them; each is validated by its check digit
or needs a label next to it, so ordinary numbers are left alone. In tool results a field name counts as the label, so
{ "routingNumber": "021000021" } is caught. Naming entities replaces the default list, so spread it to add to it:
import { DEFAULT_PII_ENTITIES } from "@pendral/platform";
await evry.agents.update({ agentId: agent.id, guardrails: { piiEntities: [...DEFAULT_PII_ENTITIES, "npi", "dea"] } });Input screening
Every incoming message is screened for jailbreak and prompt-injection attempts before a run starts, by a classifier and a
second-opinion model inside the BAA boundary. inputScreening sets what happens: "block" (the default) refuses a confirmed attack with
INPUT_BLOCKED and runs a suspicious message with extra caution, "flag" never refuses, and "off" skips the screen.
await evry.agents.update({ agentId: agent.id, inputScreening: "flag" });Prompt injection and AI disclosure
Agents that read email, tickets or documents can be handed instructions inside that data. toolOutputInjection checks every tool
result for hidden Unicode, phrases that address the model and chat template markers before the model reads it. disclosure adds a
fixed notice to the start of the reply, so telling people they are talking to an AI never depends on the model.
await evry.agents.update({
agentId: agent.id,
guardrails: {
toolOutputInjection: "block", // "flag" records, "strip" removes hidden characters, "block" withholds the result
disclosure: { text: "You are chatting with an automated assistant.", when: "first_reply" },
},
});Policy context: time, channel, attributes and velocity
Rules can read when a call happens (in the policy's timezone), the session's channel, metadata your server set on the session and
run, and how many times the same tool already ran for this member or across your organization.
await evry.policies.create({
name: "Refunds",
document: {
default: "allow",
timezone: "America/New_York",
rules: [
{ id: "two_a_month", match: { tools: ["issue_refund"] }, when: [{ path: "context.velocity.subject.30d", op: "gte", value: 2 }], effect: "deny", reason: "Two refunds a month per member at most." },
{ id: "after_hours", match: { risk: "write" }, when: [{ path: "context.time.hour", op: "gte", value: 18 }], effect: "escalate", reason: "After 6pm a person approves changes." },
{ id: "voice_unverified", match: { risk: "write" }, when: [{ path: "context.channel", op: "eq", value: "voice" }, { path: "context.session.metadata.verified", op: "not_exists" }], effect: "deny", reason: "Verify the caller first." },
],
},
});The platform fills context.time and context.velocity itself; neither a caller nor a tool can set them. A missing value makes a
comparison false, so use not_exists for rules that must fire when an attribute is absent.
Long reviews, step-up and erasure
// Wait up to 10 days for a person, and make cases due in 3 days.
await evry.agents.update({ agentId: agent.id, limits: { waitHours: 240, reviewDueHours: 72 } });
// After your own identity check, mid-conversation; policies see it from the next step. Audited by key.
await evry.sessions.update({ sessionId, metadata: { verified: "otp" } });
// A deletion request: messages, run timelines, outputs and approval inputs go; ids and the audit trail stay.
const { erased } = await evry.sessions.erase({ sessionId, reason: "DSR-2026-0412" });
console.log(erased);Subscribe to guardrail.triggered to hear about every redaction, block and screen decision as it happens. policies.simulate and
policies.evaluate return warnings when a rule reads context.time or context.velocity and you did not pass it.
Kill switch
const stopped = await evry.agents.suspend({ agentId: agent.id, reason: "INC-4411: wrong refund amounts" });
console.log(stopped.cancelledRunIds); // active runs it cancelled; new runs now fail with AGENT_SUSPENDED
await evry.agents.resume({ agentId: agent.id, reason: "Fixed in v14, verified in test mode" });Schedules skip while an agent is suspended (without counting failures), journeys wait, and both calls are audited and sent as
agent.suspended and agent.resumed webhooks.
To pause what agents do for one member instead, suspend their grant. While it is suspended, runs in its sessions do not start
(GRANT_SUSPENDED), tool calls of runs already going, direct tool calls and approved actions are denied with GRANT_SUSPENDED,
its schedules skip with lastOutcome: "skipped_grant_suspended" (not counted as failures), and journey steps wait. Both calls are
audited and sent as grant.suspended and grant.resumed.
await evry.grants.suspend({ grantId: "grt_...", reason: "Member paused automation in the app" });
await evry.grants.resume({ grantId: "grt_...", reason: "Member turned it back on" });Agents for one person, from a template
An agent template is a base your organization approves: instructions every agent made from it follows first, the policy, guardrails, screening and reasoning it inherits, and a ceiling on the tools, models, limits, memory and memory stores it may enable. An agent owned by a subject belongs to one end user: only sessions, schedules and grants for that subject may use it. The two are independent; together they give each person their own agent that never exceeds what the organization allows.
declare const lookupTool: { id: string };
declare const bookTool: { id: string };
declare const consentPolicy: { id: string };
const template = await evry.agentTemplates.create({
name: "Personal assistant",
instructions: "You are a personal assistant for one person. Never share their data with anyone else.",
model: "auto",
toolIds: [lookupTool.id, bookTool.id], // the ceiling
policyId: consentPolicy.id, // inherited; agents made from the template cannot change it
limits: { maxCostUsd: 2 },
memory: { scopes: ["subject"] },
quotas: { maxAgentsPerSubject: 3 },
});
const mine = await evry.agents.create({
name: "Trip planner",
instructions: "Plan around my kids' school calendar.",
templateId: template.id,
ownerSubject: "user-8812",
toolIds: [lookupTool.id],
limits: { maxCostUsd: 1 },
});- Asking for anything above the ceiling, or setting
policyId,guardrails,inputScreening,reasoning,temperature,evalPassThresholdorsubjectNounon a templated agent, fails withVALIDATION_ERRORnaming the field, at create and at update. - An owned agent serves only its owner: a session, schedule or grant for anyone else fails with
FORBIDDEN, and journeys cannot use it. Its name and instructions pass the identifier and prompt-injection screens (CONTENT_REJECTED,INPUT_BLOCKED). - Quotas fail with
QUOTA_EXCEEDEDanddetails.limit:templateAgentsPerSubject,templateAgents,ownedAgentsPerSubject(20) orownedAgentsPerOrganization(100,000). agentTemplates.updatepublishes a new version and brings every agent made from it to it: choices above the new ceiling are taken away (agent.constrained, with what was removed), and an agent that cannot be brought down is suspended. The result says how many moved; the rest move in the background and always before their next run.agents.deleteends an owned agent: it cancels its runs, archives its schedules, revokes the grants that cover only it, and erases its own memory and the memory store records it wrote (taggedagent:<id>), keeping any that carry one of the template'ssharedTags. The result counts each. It needsmemories:writeandgrants:writeas well asagents:write. Pause one withagents.suspend.
declare const mine: { id: string };
const removed = await evry.agents.delete({ agentId: mine.id });
console.log(removed.runsCancelled, removed.schedulesArchived, removed.grantsRevoked, removed.memoriesErased, removed.memoryRecordsErased);Agents send agent.created, agent.updated, agent.suspended, agent.resumed, agent.deleted (with deletion, the
same counts) and agent.constrained (with constraint: { templateId, templateVersion, removed }). Receiving them needs
agents:read. Type them with AgentEventData; AGENT_EVENT_TYPES lists them.
import { createWebhookHandler, type AgentEventData, type WebhookEvent } from "@pendral/platform";
declare function tellOwner(subject: string | null, text: string): Promise<void>;
export const POST = createWebhookHandler({
secret: process.env.EVRYAI_WEBHOOK_SECRET!,
on: {
"agent.constrained": async (event) => {
const agent = (event as WebhookEvent<AgentEventData["agent.constrained"]>).data.object;
await tellOwner(agent.ownerSubject, `${agent.name} can no longer use: ${agent.constraint.removed.join(", ")}`);
},
},
});Durable agents
Wake an agent on a schedule, let it remember what it did, and restart it if the machine running it stops.
const worker = await evry.agents.create({
name: "Care gap outreach",
model: "auto",
instructions: "Check open care gaps. Skip any you raised in the last 14 days (check memory), then save what you raised.",
toolIds: [findCareGaps.id, draftOutreach.id],
memory: { scope: "subject" }, // memory_list, memory_get, memory_save, memory_delete, each governed and audited
limits: { maxRetries: 2, maxCostUsd: 0.25 },
});
await evry.schedules.create({
agentId: worker.id,
name: "Morning care gaps",
cron: "0 8 * * 1-5",
timezone: "America/New_York",
message: "Run this morning's care gap check.",
subject: "member_8812",
});
// Seed, read, correct or erase what the agent remembers about a member.
await evry.memories.set({ agentId: worker.id, subject: "member_8812", key: "preferences.contact", value: { channel: "sms" } });
await evry.memories.erase({ agentId: worker.id, subject: "member_8812" });An occurrence is skipped while the previous run is still going, and a schedule pauses itself after repeated failures (with a
schedule.paused webhook). A crashed run is retried from its last saved point, but never after a write tool already ran.
One schedule per member is fine: there is no cap per organization or agent. Find a member's with
evry.schedules.list({ subject: "member_8812" }), and spread the minute across members rather than starting thousands at once.
Crons follow the zone's daylight saving: a time skipped by the spring change runs an hour later that day, and a time repeated by
the autumn change runs once.
Memory stores
A memory store is what your organization knows about the people it serves, as its own governed resource: not tied to one
agent, written by your backend, by extraction from conversations, by agents after a run or by their tools, and read by any
of them. Every memory carries who said it and how (stated, inferred, imported), confidence, sensitivity, and a
validity history: a changed fact supersedes the old one instead of overwriting it.
const store = await evry.memoryStores.create({
name: "members",
config: {
extraction: {
instructions: "Capture care preferences, people who help with care, providers and logistics.",
// How extraction labels what it keeps. A choice made once is inferred, never a stated preference.
policy: { stated: "explicit", singleInstance: "inferred", singleInstanceMaxConfidence: 0.6, inferredMaxConfidence: 0.8, temporaryDays: 14 },
},
},
});
// Seed what you already know, with provenance.
await evry.memoryStores.profile.update({ storeId: store.id, subject: "member_8812", fields: { preferred_name: "Sam" }, sourceLabel: "onboarding" });
await evry.memoryStores.memories.create({
storeId: store.id,
subject: "member_8812",
kind: "preference",
content: "Prefers morning appointments",
evidence: "mornings are best for me",
evidenceKind: "quote",
basis: "explicit",
});
// A passing state: forgotten after expiresAt (or the policy's temporaryDays).
await evry.memoryStores.memories.create({ storeId: store.id, subject: "member_8812", content: "Is travelling this week", temporary: true });
// Or hand over a conversation: the platform extracts and reconciles (add, update, supersede, forget, ignore) and says why.
const job = await evry.memoryStores.add({
storeId: store.id,
subject: "member_8812",
messages: [{ role: "user", content: "I retired, so afternoons work now. And please forget my old pharmacy." }],
// Optional: rules for this material only, on top of the store's.
instructions: "A single booking is never a preference.",
policy: { singleInstance: "skip" },
});
for (const change of job.changes) console.log(change.op, change.content, change.source, change.basis, change.expiresAt, change.reason);
// One call for a prompt: the profile plus what is relevant to this message, within a token budget, with the ids it used.
const recalled = await evry.memoryStores.context({ storeId: store.id, subject: "member_8812", query: "Can you book my checkup?", maxTokens: 600 });
await evry.runs.create({ sessionId, message: { text: "Can you book my checkup?" }, context: recalled.text });
// Each memory says how it is known, so an app can label it and keep sensitive ones off a voice channel.
for (const m of recalled.memories) {
const label = m.source === "stated" ? "You told us" : "We noticed";
const quote = m.provenance.evidenceKind === "quote" ? m.provenance.evidence : null;
console.log(label, m.content, m.confidence, m.sensitivity, quote, m.temporary ? `until ${m.expiresAt}` : "");
}
// Search with filters and explanations; correct, supersede, forget; history; erase and export for data requests.
const { hits } = await evry.memoryStores.search({ storeId: store.id, subject: "member_8812", query: "appointment times", maxSensitivity: "phi" });
console.log(hits.map((h) => [h.memory.content, h.score, h.matched, h.memory.provenance.source]));
await evry.memoryStores.memories.supersede({ storeId: store.id, memoryId: hits[0].memory.id, content: "Prefers afternoon appointments" });
await evry.memoryStores.export({ storeId: store.id, subject: "member_8812" });
await evry.memoryStores.eraseSubject({ subject: "member_8812", includeAgentMemories: true });How a memory is known travels with it. provenance.source is stated only for what the person said outright, with their own
words kept verbatim (evidenceKind: "quote"); provenance.basis says how anything else was inferred (single_instance,
repeated, implied), and the store's policy caps inferred confidence, can refuse single choices or inferences
altogether, and marks topics as sensitive. A passing state (temporary) carries its end in expiresAt, drops out of search
and context then, and is swept. The context text shows each memory's statement, how it is known and when, and the person's
words only when they were kept as a quote. Memory text is stored as written: whitespace is normalised and nothing is added.
Agents attach to stores instead of owning them. With recall, the platform gives the model the context block for the
session's subject before its first step; with capture, it extracts from the run's turns when the run completes; tools
adds memory_search, memory_remember and memory_forget under the agent's policy. The run's events show what was
recalled (memory.recalled) and captured (memory.captured) by id.
const [members] = (await evry.memoryStores.list({ name: "members" })).data;
const concierge = await evry.agents.create({
name: "Concierge",
model: "auto",
instructions: "Help members with their plan.",
memoryStores: [{ storeId: members.id, recall: true, capture: true, tools: ["search"], maxSensitivity: "phi" }],
});Several agents can share one store and still keep to their own lane. tags are added to everything an agent writes. readTags
says what it may read: recall, memory_search and memory_forget see only memories carrying at least one of them (recall still
includes the member's profile fields, which carry no tags). Without readTags, reads keep the old rule (every one of tags must
be present).
declare const membersId: string;
await evry.agents.create({
name: "Billing",
model: "auto",
instructions: "Handle billing questions.",
memoryStores: [{ storeId: membersId, recall: true, tools: ["search", "remember"], tags: ["team:billing"], readTags: ["shared", "team:billing"] }],
});Use a memory store for knowledge about people that several agents and your own systems share. Keep using agent key/value
memory for an agent's own working state (a cursor, a follow-up date). Content is encrypted at rest; identifiers and secrets
are refused (CONTENT_REJECTED) unless the store allows that identifier type. Writes need memories:write, reads
memories:read, and creating or configuring stores memory_stores:write. Events (memory.created, memory.updated,
memory.superseded, memory.deleted, memory_subject.erased, memory_job.completed) never carry content.
Sandboxes
Ephemeral, isolated computers your agents and backend start in seconds to run code, drive a real browser or operate a desktop, on behalf of a member. Every action is audited with the key, the member and the run.
const sandbox = await evry.sandboxes.create({
template: "browser", // desktop + Chromium; "code" has no desktop
name: "refill-portal-job",
ttlMinutes: 30, // deleted when it runs out, whatever happens to your process
network: { egress: "allowlist", allowedHosts: ["portal.example.com"] },
subject: "member_8812",
runId: run.id,
labels: { job: "refill-42" },
});
const { exitCode, output } = await evry.sandboxes.commands.run({ sandboxId: sandbox.id, command: "node -v" });
for await (const event of evry.sandboxes.commands.stream({ sandboxId: sandbox.id, command: "npm test" })) {
if (event.type === "output") process.stdout.write(event.text);
else console.log("exit", event.exitCode);
}
await evry.sandboxes.files.write({ sandboxId: sandbox.id, path: "/tmp/input.json", content: JSON.stringify({ memberId: "8812" }) });Drive the browser from your server without holding a WebSocket, or attach Playwright yourself:
const sandbox = await evry.sandboxes.create({ template: "browser", ttlMinutes: 30 });
await evry.sandboxes.browser.start({ sandboxId: sandbox.id });
await evry.sandboxes.browser.navigate({ sandboxId: sandbox.id, url: "https://portal.example.com/login" });
// The platform types the credential; your code and the model never see it.
await evry.sandboxes.browser.fill({ sandboxId: sandbox.id, target: { label: "Password" }, secret: { connectionId: "con_01J9Z8Q4M3T5V7X9B1C3D5F7G9" } });
await evry.sandboxes.browser.click({ sandboxId: sandbox.id, target: { role: "button", name: "Sign in" } });
const { snapshot } = await evry.sandboxes.browser.snapshot({ sandboxId: sandbox.id }); // accessibility tree, secrets masked
const shot = await evry.sandboxes.browser.screenshot({ sandboxId: sandbox.id }); // secret and password fields painted over
// Attach Playwright yourself: chromium.connectOverCDP(cdpUrl), no headers needed until it expires.
const { cdpUrl } = await evry.sandboxes.browser.connect({ sandboxId: sandbox.id, expiresInSeconds: 600 });
const live = await evry.sandboxes.liveView.create({ sandboxId: sandbox.id, mode: "view" }); // a URL a person can watch
await evry.sandboxes.delete({ sandboxId: sandbox.id });- Secrets by reference.
{ connectionId }or{ secret: name }(stored withsandboxes.secrets.set) go into a command'ssecretEnv, abrowser.fillorcomputer.keyboard. Values are scrubbed to[secret:<name>]from every output. A connection only goes to pages on itsallowedHosts, and into commands only when the sandbox's egress is an allowlist within them. Using secrets needs thesandbox_secrets:writescope, as do the raw channels of a sandbox that holds one: commands, file reads, downloads, screenshots, the CDP URL, live view and exported cookies. Injecting a secret revokes CDP and live view URLs issued earlier to keys without that scope. - Lifecycle.
stopkeeps the disk and the browser profile;startbrings it back;extendadds minutes; idle sandboxes stop afteridleTimeoutMinutes. Limits per organization (sandboxes.quota.get) fail withQUOTA_EXCEEDED. - Audit and events. Every action is an audit record (never content or secret values) and a
sandbox.actionevent; lifecycle changes aresandbox.created,started,stopped,expiredanddeletedwebhooks. - Desktop.
computer.screenshot,computer.pointer,computer.keyboardandrecordings.start/stop/downloadUrlfor an MP4 of the session.
Agents and tools
const tool = await evry.tools.create({
name: "check_refill",
description: "Check whether a prescription can be refilled",
kind: "http",
url: "https://api.pharmacy.example/refills/check",
method: "POST",
risk: "read",
inputSchema: {
type: "object",
properties: { rxNumber: { type: "string" } },
required: ["rxNumber"],
},
});
const agent = await evry.agents.create({
name: "Pharmacy assistant",
instructions: "Help members refill prescriptions.",
model: "auto",
toolIds: [tool.id],
});Tool credentials are stored as connections and attached at call time. They are never returned by the API or shown to the model.
An agent's prompts call the person it acts for a "member" unless you set subjectNoun, such as customer, patient or
employee: evry.agents.update({ agentId: agent.id, subjectNoun: "customer" }). It changes the wording the model reads
(who it acts for, memory and handoff instructions), never what the agent may do.
Calling a tool directly
When your code already knows which tool to call with which input (a voice model asked for the member's deductible, a button, a form, a scheduled job), call it directly instead of starting a run. There is no model step, so the answer comes back in about the time your endpoint takes, and the call gets exactly the governance it would get from the agent: the session's member, grant, channel and metadata, the agent version's policy and guardrails, approvals, the on-behalf-of token and the audit trail.
const call = await evry.toolCalls.create(
{ sessionId: session.id, tool: "check_refill", input: { rxNumber: "RX123" } },
{ idempotencyKey: "voice-turn-42" }
);
if (call.status === "completed") {
console.log(call.output); // after redaction and the tool-output guardrails, as the agent would have read it
} else if (call.status === "requires_action" && call.requiredAction?.type === "approval") {
const approval = await evry.approvals.get({ approvalId: call.requiredAction.approvalId });
// Show approval.toolCall to the member exactly as it is, then:
await evry.approvals.approve({ approvalId: approval.id, inputHash: approval.inputHash });
const done = await evry.toolCalls.wait(call.id); // the call runs exactly once
console.log(done.output);
} else {
console.log(call.error?.code, call.decision?.policy?.ruleId); // POLICY_DENIED and the rule, UPSTREAM_ERROR, ...
}- It needs the
tool_calls:writescope. A key with onlyruns:writecannot choose tools and inputs itself. toolis a tool id or name from the agent version the session runs; only HTTP tools. Anything else, or input that does not match the tool's schema, is refused with aValidationErrorbefore anything runs or is recorded.- A
deny(from policy, or a revoked or missing grant) returns afailedcall withPOLICY_DENIED;confirmandescalatereturnrequires_actionwith an approval or a case. Listen fortool_call.completedinstead of waiting if you prefer. - The call and its result are added to the session's conversation so the agent's next run knows what was done; pass
history: falsefor background reads. Audit records match the agent's own calls, withexecutor.initiatornaming your key, and velocity rules count both. - Reads run beside an active agent run in the session. A write is refused with
ConflictErrorwhile an agent run is queued or running, and goes ahead while one is paused for a decision. The other way round,runs.createthrowsConflictErrorwhile a direct write in the session is executing, so the new run always sees its result. - With an
idempotencyKey, a retry returns the same call and never executes it twice.
Webhooks
Verify every delivery before you trust it. Pass the raw request body, not parsed JSON.
import { EvryAI, WebhookSignatureError } from "@pendral/platform";
export async function POST(request: Request) {
try {
const event = await EvryAI.webhooks.constructEvent(
await request.text(),
request.headers.get("evryai-signature"),
process.env.EVRYAI_WEBHOOK_SECRET!
);
// handle event.type, e.g. "run.completed" or "approval.requested"
return new Response(null, { status: 204 });
} catch (error) {
if (error instanceof WebhookSignatureError) return new Response("Invalid signature", { status: 400 });
throw error;
}
}Or let the SDK route events for you. createWebhookHandler returns a Fetch API handler that works in Next.js route handlers, Hono,
Bun, Deno and Workers.
import { createWebhookHandler } from "@pendral/platform";
export const POST = createWebhookHandler({
// Several secrets are accepted while you rotate one.
secret: [process.env.EVRYAI_WEBHOOK_SECRET!, process.env.EVRYAI_WEBHOOK_SECRET_OLD!],
on: {
"run.completed": async (event) => notify(event.data.object),
"approval.requested": async (event) => queueForReview(event.data.object),
},
dedupe: (eventId) => redis.exists(`evt:${eventId}`).then(Boolean),
markHandled: (eventId) => redis.set(`evt:${eventId}`, "1", { EX: 86_400 }).then(() => undefined),
});Bad signatures get 400. Event types with no listener get 200 and are ignored. A listener that throws gets 500, so the event is
delivered again; deliveries are at least once, which is why dedupe exists.
Tool endpoints
Every governed tool call EvryAI makes to your system carries an EvryAI-On-Behalf-Of token: a short-lived ES256 JWT naming the
member, the agent and version, the run, the tool call and the grant. Verify it before you act. @pendral/platform/tools checks the
signature against EvryAI's published keys with Web Crypto, and checks the issuer, audience, expiry and token type.
import { createToolHandler } from "@pendral/platform/tools";
import { z } from "zod";
const input = z.object({ memberId: z.string() });
export const POST = createToolHandler({
audience: "https://api.example.com", // your endpoint's origin; defaults to the request's
livemode: true, // refuse test-mode calls on this endpoint
input: input.parse, // throws answer 400 INVALID_INPUT
idempotency: redisStore, // { get(key), set(key, value) }: one answer per tool call
handler: async ({ memberId }, { claims }) => {
// claims.subject is the member the agent acts for; claims.grantId is their consent.
return members.lookup(memberId, { actingFor: claims.subject });
},
});To check a token yourself, call verifyOnBehalfOf(request, { audience }). It returns the claims or throws an OnBehalfOfError with a
code (MISSING_TOKEN, INVALID_SIGNATURE, EXPIRED, CLAIM_MISMATCH, and so on). Keys are cached for five minutes and refetched
when a token names a key the cache does not have.
Verifying the audit trail yourself
Audit records are hash-chained per organization. audit.verify() asks the API to check the chain. verifyAuditChain recomputes
every hash and link on your side, so an auditor does not have to take the API's word for it.
import { verifyAuditChain } from "@pendral/platform";
const { organizationId } = await evry.me.get();
const records = [];
for await (const record of evry.audit.list({ limit: 100 })) records.push(record);
const result = await verifyAuditChain(records, { organizationId, fromGenesis: true });
if (!result.ok) console.error(`Chain breaks at seq ${result.firstBadSeq}: ${result.reason}`);Without fromGenesis, a range of records is checked from the first one you pass, which suits exports you verify in parts.
Send it to your SIEM
toOcsf maps a record onto an OCSF 1.1 API Activity event, toCef writes one ArcSight CEF line, and formatAuditRecord(record, format)
picks by name. From a scheduled job, evryai audit export does the paging and checkpointing for you (see the command line section).
import { toCef, toOcsf } from "@pendral/platform/audit";
for await (const record of evry.audit.list({ limit: 100 })) {
console.log(JSON.stringify(toOcsf(record)));
console.log(toCef(record));
break;
}Testing your integration
@pendral/platform/testing lets you test code built on the SDK without calling EvryAI.
import { createMockFetch, createTestIssuer, mockError, signedWebhookRequest, testWebhookEvent } from "@pendral/platform/testing";
// A fake API for the client, answering by operation id. Unmocked operations fail with NOT_MOCKED.
const api = createMockFetch({
"sessions.create": ({ body }) => ({ id: "ses_1", subject: body?.subject }),
"runs.create": mockError(409, "AGENT_SUSPENDED", "This agent is suspended."),
});
const client = new EvryAI({ apiKey: "evk_test_unit", fetch: api.fetch, maxRetries: 0 });
console.log(api.callsTo("runs.create"));
// Signed deliveries for your webhook route, and on-behalf-of tokens for your tool endpoints.
const delivery = await signedWebhookRequest(testWebhookEvent("run.completed", { id: "run_1" }), "whsec_test");
const issuer = await createTestIssuer();
const toolCall = await issuer.request("https://api.example.com/tools/lookup", { memberId: "m-1" }, { subject: "m-1" });Pass issuer.verifyOptions to createToolHandler or verifyOnBehalfOf in tests only. mockPage returns list pages with a cursor and
mockEventStream serves the event stream that runs.stream, runs.wait and runs.execute follow.
For code built on sandboxes, createSandboxMock() is an in-memory sandbox service (lifecycle, commands, files, secrets and
the browser's navigate, snapshot, fill and screenshot) to spread into createMockFetch, with mockSandbox() for fixtures and
mockCommandStream() for sandboxes.commands.stream:
import { createMockFetch, createSandboxMock } from "@pendral/platform/testing";
const sandboxes = createSandboxMock({ onCommand: (command) => (command === "node -v" ? "v24.0.0" : "") });
const fake = new EvryAI({ apiKey: "evk_test_unit", fetch: createMockFetch(sandboxes.handlers).fetch, maxRetries: 0 });
const box = await fake.sandboxes.create({ template: "browser" });
console.log((await fake.sandboxes.commands.run({ sandboxId: box.id, command: "node -v" })).output);For code that calls tools directly, createToolCallMock() runs your own tool functions under the decisions you choose, with
approvals that run a confirmed call once, and mockToolCall() makes fixtures:
import { createMockFetch, createToolCallMock } from "@pendral/platform/testing";
const toolCalls = createToolCallMock({
tools: { get_deductible: () => ({ remainingCents: 108000 }) },
decide: ({ tool }) => (tool === "get_deductible" ? "allow" : "confirm"),
});
const voice = new EvryAI({ apiKey: "evk_test_unit", fetch: createMockFetch(toolCalls.handlers).fetch, maxRetries: 0 });
console.log((await voice.toolCalls.create({ sessionId: "ses_1", tool: "get_deductible", input: {} })).output);For code built on memory stores, createMemoryStoreMock() keeps stores and memories in memory, with your own extraction for
add and word-overlap search, and mockMemory() makes fixtures:
import { createMemoryStoreMock, createMockFetch } from "@pendral/platform/testing";
const memory = createMemoryStoreMock({ extract: ({ text }) => [{ op: "add", content: text }] });
const mocked = new EvryAI({ apiKey: "evk_test_unit", fetch: createMockFetch(memory.handlers).fetch, maxRetries: 0 });
const members = await mocked.memoryStores.create({ name: "members" });
await mocked.memoryStores.add({ storeId: members.id, subject: "m-1", text: "Prefers texts" });Pagination
list methods return the first page when awaited, and every item when iterated.
const page = await evry.runs.list({ limit: 50 });
for await (const run of evry.runs.list({ status: "completed" })) {
console.log(run.id);
}Errors
Every API error is an EvryAIError subclass carrying status, code, message, requestId and details.
import { RateLimitError, ValidationError } from "@pendral/platform";
try {
await evry.agents.create({ name: "", instructions: "", model: "auto" });
} catch (error) {
if (error instanceof ValidationError) console.error(error.details);
else if (error instanceof RateLimitError) console.error(`Retry in ${error.retryAfter}s`);
else throw error;
}| Class | When |
| --- | --- |
| AuthenticationError | The key is missing, invalid, expired or revoked. |
| PermissionError | The key lacks the scope this call needs. |
| NotFoundError | The object does not exist, or belongs to another organization or mode. |
| ConflictError | The object is not in a state that allows this, or an idempotency key is busy. |
| ValidationError | The request failed validation. details lists each problem. |
| RateLimitError | The key is over its request or token limit. |
| ServerError | Something failed on our side. Quote requestId to support. |
| ConnectionError | The request never reached the API. |
Retries and idempotency
Rate limits, server errors and network failures are retried up to twice with backoff, honoring Retry-After. Every write sends an
Idempotency-Key, and retries reuse it, so a retried request returns the original result instead of acting twice. Pass your own key
to make an operation idempotent across your own retries:
await evry.runs.create(
{ sessionId, message: { text: "Refill RX123" } },
{ idempotencyKey: `refill-${orderId}` }
);Configuration
const evry = new EvryAI({
apiKey: process.env.EVRYAI_API_KEY,
baseUrl: "https://evryai.app/api/v1", // only for a dedicated deployment
maxRetries: 2,
timeoutMs: 60_000,
});| Option | Default | |
| --- | --- | --- |
| apiKey | EVRYAI_API_KEY | An evk_live_ or evk_test_ key, or an OAuth access token. |
| baseUrl | EVRYAI_BASE_URL, then the hosted API | Set it if your organization runs a dedicated deployment. |
| maxRetries | 2 | Per request. Override per call with { maxRetries }. |
| timeoutMs | 60000 | Per attempt. Override per call with { timeoutMs }. |
| apiVersion | 2026-10-01 | Pins the API version this SDK was built for. |
| fetch | global fetch | Supply your own for proxies or testing. |
| defaultHeaders | none | Sent on every request, e.g. a W3C traceparent. Cannot replace authentication or version headers. |
| onRequest | none | Called before each attempt with { operationId, method, url, attempt }. |
| onResponse | none | Called after each attempt with the above plus status, requestId and durationMs. |
The hooks receive metadata only, never request or response bodies, because those can carry PHI. A hook that throws is ignored.
evry.withOptions({ ... }) returns a new client with some options changed, for example a tracing header for one request flow.
const evry = new EvryAI({
onResponse: ({ operationId, status, durationMs, requestId }) =>
metrics.histogram("evryai.request", durationMs, { operationId, status, requestId }),
});
const traced = evry.withOptions({ defaultHeaders: { traceparent: currentTraceparent() } });Keep API keys on your server. Never ship them to a browser or mobile app.
Command line
The package includes the evryai CLI.
npx -p @pendral/platform evryai whoami # check a key: organization, mode, scopes and limits
npx -p @pendral/platform evryai openapi # print the OpenAPI document
npx -p @pendral/platform evryai listen --forward-to http://localhost:3000/webhookslisten forwards new events to a local URL, signed like real webhook deliveries, so you can build your webhook handler without
exposing your machine.
Two commands are built for CI:
# Run an agent version's eval suite and exit 1 if it scores below the bar (default: the agent's own threshold).
npx -p @pendral/platform evryai evals gate --agent agt_... --version 4 --min-pass-rate 0.95
# Pull every audit record and check the hash chain locally. Without --offline the API checks it.
npx -p @pendral/platform evryai audit verify --offlineTwo are built for operations:
# New audit records oldest first, as JSON Lines, OCSF or CEF. The next checkpoint is printed on stderr.
npx -p @pendral/platform evryai audit export --format ocsf --after-seq 18240 >> audit.ocsf.jsonl
# The incident switch, and its way back. Pass --keep-runs to leave active runs to stop at their next step.
npx -p @pendral/platform evryai agents suspend agt_... --reason "INC-4411: wrong refund amounts"
npx -p @pendral/platform evryai agents resume agt_... --reason "Fixed in v14"evals gate prints each failing scenario and the reason it failed.
Requirements
- Node.js 18 or later, or any runtime with
fetchand Web Crypto - TypeScript 5 or later, if you use TypeScript
Support
See the documentation for guides and the full API reference. For help, contact your
EvryAI account team and include the requestId from the error or the X-Request-Id response header.
License
Proprietary. Copyright © 2026 Pendral, Inc. All rights reserved.
This SDK may only be used to access the EvryAI Platform under an active EvryAI subscription agreement. Platform access is licensed and billed under that agreement. See LICENSE.
