@sanning/anchor
v0.24.0
Published
Write path for the Sanning evidence plane. Hash your data locally, sign a sanning.events/v2 commitment envelope, and send it to Sanning, which witnesses it on an interval to a permanent public record. Raw bytes never leave your system; you retain them in
Downloads
4,787
Readme
@sanning/anchor
Anchor your agent's work as it happens: hash the bytes locally, sign a commitment envelope, and hand an auditor a pack they verify offline. Your content is hashed in your process and never sent, and nothing here needs a wallet or a chain identity.
The path from signup to a verified pack is at docs.sanning.io. This file covers calling the package.
npm install @sanning/anchorimport { createAnchorer, FsLogStore, LocalEd25519Signer } from "@sanning/anchor";
// Ed25519, the ONLY key involved. Keep the seed: a different seed is a different agent.
const signer = LocalEd25519Signer.fromSeedHex(process.env.SANNING_SIGNING_SEED!);
const fileBytes = new TextEncoder().encode("hello world"); // or a real file / AsyncIterable
const anchorer = createAnchorer({
environment: "production",
signer,
subject: { type: "agent", agent_id: "checkout-agent" },
apiKey: process.env.SANNING_API_KEY!,
// Your store, on your disk. The SDK writes here BEFORE it anchors, and a
// store failure means no anchor. You need it to hand anything over later,
// so configure it now rather than discovering it when you build the evidence pack.
// One disk is one copy: lose it and you lose the evidence. On Live, use an S3-compatible store or back this up.
logStore: new FsLogStore("./logstore"),
});
const result = await anchorer.anchor({
content: fileBytes, // or a string / AsyncIterable: hashed locally
ref: "s3://bucket/key", // optional locator
metadata: { approver: "alice" },
});
result.eventBytes; // RETAIN THESE, the committed event record
result.envelopeBytes; // the exact canonical bytes that went on the wire
result.eventId; // the id THIS process mintedStart in the sandbox
Start with a Sandbox API key, which begins sanning_test_, and set no
environment. The SDK signs "dev", stamps are simulated, and nothing reaches
the public record. A pack built from those records reads verified with the
sandbox label: @sanning/proof verify prints the Sandbox: line and exits 3. When you are ready for
evidence, switch SANNING_API_KEY to a Live API key, which begins
sanning_prod_, and use a new signing seed. See
Sandbox and live and Go live.
The environment and your API key
With an apiKey, environment is optional: the SDK reads it from the key's
prefix. sanning_test_ signs "dev" and sanning_prod_ signs
"production", at the same host. A sanning_test_ key with
environment: "production" throws at construction, and so does a
sanning_prod_ key with environment: "dev" (the Live plane refuses a dev
record): dev records need a Sandbox key, or drop environment to sign
"production". Any other explicit value is used as given. With no key (your own submitter), or a key with neither
prefix, environment is required. A non-string apiKey throws at
construction.
A Live plane refuses a Sandbox API key, and a Sandbox refuses a Live API key.
Only the prefix is read, and the value is sealed into every record. baseUrl
still points the SDK at another origin, such as staging.
From CI, persist one seed. Calling LocalEd25519Signer.generate() in
every run enrolls a new key under the same agent_id, which the plane refuses
as an unauthorized rotation. Generate a seed once (openssl rand -hex 32),
store it as a CI secret beside a Sandbox API key, and pass it as the signer:
const anchorer = createAnchorer({
signer: LocalEd25519Signer.fromSeedHex(process.env.SANNING_SIGNING_SEED!),
subject: { type: "agent", agent_id: "checkout-agent" },
apiKey: process.env.SANNING_API_KEY!,
logStore: new FsLogStore("./logstore"),
});Why there is no wallet
This model inverts where evidence lives. You sign a commitment envelope; we decide where it is placed and how it is witnessed. The consequence is what it removes from you:
An agent needs no chain identity, no data item and no wallet.
Nothing comes back to keep, and that is the design
The plane answers 202 {accepted, event_id} and nothing on it is yours to
keep, no locator, no placement, no signature of ours. The SDK checks that
acknowledgement and discards it. Every field on AnchorResult is something
your own process computed, which is why there is no txId and no gatewayUrl
here: at the moment you write, placement has happened but witnessing has
not, so returning a locator would overstate what is true. The inclusion and
chain proofs travel in the evidence pack instead.
eventBytes is therefore load-bearing rather than convenient. Sanning never
holds them; losing them leaves you holding a commitment to something you can no
longer produce.
Chaining: the link is burnt locally
Pass chain and this anchorer resolves the head from its Store, and
advances it before the POST, not after the plane says yes:
const anchorer = createAnchorer({
signer, subject,
apiKey,
store: myDurableStore, // optional; MemoryStore by default
onGap: (gap) => save(gap), // optional; see below
});
await anchorer.anchor({ content: data, chain: "orders" }); // we resolve + burn the headUse a durable store with one writer for any chain key that outlives one
process. The default MemoryStore loses its heads on a restart, so the next
record on the same chain key starts again at GENESIS: one chain with two
roots, a fork whose links all verify. @sanning/proof reports it as the
chain-second-root finding, which does not change the verdict. A durable store
does not make two writers safe, because the store has no compare-and-set: two
instances on one chain key fork the same way. In production, anchor({ chain })
on the default store warns once per anchorer. If every chain key lives only as
long as the process (the LangChain adapter's per-run key, for example), pass
store: new MemoryStore() to say so and the warning stays quiet.
An ingest POST that times out is an unknown outcome: the plane may have accepted and stored the envelope. So the two options are not symmetric:
| | On an unknown outcome | |---|---| | advance-on-success | the head does not move, the next event reuses the same predecessor, and if the plane did accept the first, two stored records claim one predecessor. Both chains verify. Nothing flags it. | | burn-the-link (what this does) | the head moves regardless, so the next record points at one that may not have landed. The pointer dangles, visible offline, with no cooperation from Sanning. |
A gap is honest and trivially detectable; a fork is ambiguous and looks fine. Same rule in both SDKs, and the same rule the LangChain adapters already used.
A burnt slot you could not see would be worse than no burn at all, so every one is retained:
anchorer.gaps; // [{ chainKey, previousHash, payloadHash, eventId,
// status: "undelivered", eventBytes, error }]
await anchorer.close(); // throws IncompleteTrailError if any remainA gap is reported undelivered, never as a bad record: a timeout says nothing
about whether the plane accepted it. eventBytes is retained on the gap, and
after a failure it is the only copy of something that may already be committed.
chainKey + previousHash still works and is unchanged: there the caller owns
the head, so this anchorer writes no head of its own.
Identical bytes to the Python SDK
sanning-anchor (Python) writes through this same contract, and the two are
gated byte-for-byte against the shared conformance corpus in both CI jobs: the envelope (conformance.test.ts / test_conformance.py), the bytes each
client actually puts on the wire (envelope-parity.test.ts /
test_wire_parity.py), and the chain sequence a failed delivery produces
(chain-burn-parity.test.ts / test_chain_burn_parity.py).
Record an agent run
RunRecorder writes one agent invocation as agent.* records of sanning.agent/1. Use it to record from your own code, or to build an adapter for a framework: @sanning/anchor-langchain is built on it. It gives every record its place in the invocation (run.seq and run.prev_event_id, so a deleted or reordered record shows), pairs each end with its start, lists on the first record what you cannot capture, keeps an approval request across a resume, and writes the closing record.
It does not read your framework. You decide which event is which call, what content each record commits to, and what to name it.
createAnchorer gives you the anchorer. One RunRecorder serves many invocations: it holds the anchorer, the case and your agent version. caseId is 1 to 128 characters of A-Z a-z 0-9 _ . : -, and anything else throws at construction. openRun opens one invocation and writes its first record, agent.run_opened, at run.seq 0.
Three ways in
Start and end. start writes an operation's start and returns a handle. end writes its end, named by the handle's runId. The four operation kinds are agent.step, agent.model_call, agent.tool_call and agent.retrieval. record writes a record that is not an operation: agent.step.occurred, agent.decision, agent.file, agent.error or agent.custom.
import { decisionContent, RunRecorder } from "@sanning/anchor";
const recorder = new RunRecorder(anchorer, { caseId: "claim-4821", agentVersion: "2026.11.0" });
const run = recorder.openRun({ input: { claim_id: "c-1" } });
// The root step has the root run id. How the run ended, as the closing record observes it, is its end.
run.start("agent.step", { runId: run.rootRunId });
const call = run.start("agent.tool_call", { run: { name: "lookup_policy" }, content: { claim_id: "c-1" } });
run.end("agent.tool_call", { runId: call.runId, outcome: "completed", content: { policy: "p-9" } });
run.record("agent.decision", {
content: decisionContent({ name: "claim_verdict", value: "approved" }),
extra: { decision: { name: "claim_verdict" } },
});
run.end("agent.step", { runId: run.rootRunId, outcome: "completed", content: { answer: "approved" } });
const { steps, gaps, unbuilt, observed } = await run.close({ outcome: "completed" });wrap. wrap runs a function as one operation: its start, then its end, completed with what it returned or failed with what it threw, which it throws on. An operation started inside the function, with no parent given, is its child.
const run = recorder.openRun({ input: { claim_id: "c-1" } });
const answer = await run.wrap("agent.step", { runId: run.rootRunId }, async () => {
// Runs inside the root step, so its parent is the root step.
const policy = await run.wrap("agent.tool_call", { run: { name: "lookup_policy" } }, () =>
lookupPolicy("c-1"),
);
return decide(policy);
});
const { observed } = await run.close();End only. When your framework tells you that an operation ended and never that it started, endOnly writes the end with no start. Declare the start's type in notCaptured when you open the run, or a verifier reads the end as undeclared and endOnly refuses it.
const run = recorder.openRun({ notCaptured: ["agent.tool_call.started"] });
// The framework reported the end only, so the start is declared not captured on the first record.
run.endOnly("agent.tool_call", {
outcome: "completed",
run: { name: "lookup_policy" },
content: { policy: "p-9" },
});
const { steps, unbuilt } = await run.close();Each call hands its record to the anchorer and returns. run.steps holds one promise per record, and close() waits for all of them. A record that cannot be written never throws into your code: a call after close(), an id outside the grammar and a failed build are in run.unbuilt, and a delivery failure is in run.gaps. A record that is not written keeps its position, so the next record shows a gap where it would be. run.isComplete is false while either list has an entry, and run.assertComplete() throws IncompleteTrailError for them.
With a failClosed anchorer, wrap does not run its function when the start record is lost.
Close the run
close() writes agent.run_closed once every earlier call has settled, then resolves to { steps, gaps, unbuilt, open, observed }. Call it in a finally, so a throw from your agent still writes it: a run that never closes shows closing.promised on its first record and no agent.run_closed.
The closing record lists the records the run anchored and says how it ended in two places. closing.outcome.observed is what the helper saw, read from the end of the root step, the operation whose run id is run.rootRunId: completed, failed (reason error) or interrupted (reason interrupted), or interrupted with no reason when an operation is still open (below). A run with no root step, or whose root end is not among the records the closing record lists, is unknown. closing.outcome.stated is what you said:
await run.close({ outcome: "failed", reason: "error" });outcome is completed, failed, interrupted or unknown, and reason is a code: error, timeout, cancelled, interrupted or policy. Anything else is refused before a record is written. Your statement never replaces observed.
An operation with no end when close() runs gets no end written for it. It is in open, and a warning names it. When the root step ended completed and its end is among the records the closing record lists, observed is { status: "interrupted" } with no reason. An approval request still waiting for its answer is one of them. interrupt() is the call for a run that stops on purpose: it ends every open operation interrupted, innermost first, and the closing record observes { status: "interrupted", reason: "interrupted" }, also when the root step had already ended completed. A root step that ended failed still observes failed.
close() reports gaps and does not throw for them. close({ strict: true }) throws IncompleteTrailError after the closing record is written. A second close() writes nothing and resolves to the first one's result; one that states an outcome warns that the statement is not in the trail. Every call after close() is refused. A close() made from inside onEvent, which runs while the helper places a record, throws and leaves the run open: call it once the call that wrote the record has returned. A second close() waits at most RUN_CLOSE_WAIT_MS (120 s) for the first, then throws ClosingNotDeliveredError.
One record outside a run
Some events happen outside any run: a session that starts, or a context compacted between two turns. recorder.recordOne(type, options) writes such an event as a one-record invocation (sanning.agent/1 section 4.4). The record has its own root run id, which is also its run id, no parent, run.seq 0 and no previous record. No agent.run_opened and no agent.run_closed are written.
Use openRun when the event is part of a run, so the run's record positions cover it. Use recordOne only when no run is open, or when the event does not belong to the run that is open.
const { step, gaps, unbuilt } = await recorder.recordOne("agent.custom", {
content: { name: "session.compacted", value: { trigger: "manual" } },
extra: { custom: { name: "session.compacted" } },
});recordOne writes the types record writes: agent.step.occurred, agent.decision, agent.file, agent.error and agent.custom. It takes the same fields as record, and writes the content, case, agent version and scope as a run writes them. Any other type throws before a record is written. The record is the first record of its invocation, so a notCaptured you pass is the capture.not_captured list a verifier reads. A conversationId you pass is written as gen_ai.conversation.id, which sanning.agent/1 allows on every type; the SDK never generates one. It groups the record with that conversation's runs and never pairs it with an approval: section 9.1 pairs an approval request with its answer across invocations, and recordOne writes neither. It uses a fresh chain key by default and hands the key back to the anchorer once the record settles, so it never takes a position in a run's chain. A record that is not written is in unbuilt, and a delivery failure is in gaps, as in a run. Neither throws.
Approvals and the store
An approval is two records in two invocations. requestApproval writes agent.approval.requested about an operation of this run, named by its start's eventId, with the actor that decides: human, policy or model. When you open the run with a conversationId, the helper keeps the request in an ApprovalStore, keyed by the conversation and by the request's own event id. The invocation that answers opens with the same conversationId and resume: true, which reads the store before the first record, then calls resolveApproval. The answer's approval.policy_hash is the request's, or the policyHash you pass to resolveApproval when the request names none. An answer whose policyHash differs from the request's is refused, and the request still leaves the store.
const recorder = new RunRecorder(anchorer, { approvals: store });
// The first invocation stops for a person.
const first = recorder.openRun({ conversationId: "thread-7" });
const step = first.start("agent.step", { runId: first.rootRunId });
first.requestApproval({ subjectEventId: step.eventId, actor: "human" });
first.interrupt();
await first.close();
// The answer arrives later, in this process or another that shares the store.
const second = recorder.openRun({ conversationId: "thread-7", resume: true });
second.resolveApproval({ verdict: "approved", actor: "human", reviewer: "alice" });
const { steps, unbuilt } = await second.close();resolveApproval finds the request by its subject and its decider. With no subjectEventId, it answers the one request that is pending. It never guesses: an answer that matches two or more requests, or that matches none, is not written and is in unbuilt. Once exactly one request matches, it is taken out of the store whatever becomes of the answer's record. A resume that finds nothing pending writes the first record with agent.approval.requested in capture.not_captured. A request with the run id of an earlier unanswered request of the same run replaces it. For a resume whose answer you do not write, recorder.takeResumed(conversationId, actor) takes out the one request that answer would have resolved. New input on a conversation, which a framework can treat as dropping what it waited on, is openRun({ conversationId, supersedesPending: true }): the waiting requests are removed from the store with a warning naming each, and stay unanswered in the trail.
A store that outlives the process
Without approvals, the helper keeps requests in a MemoryApprovalStore, one per process. Pass your own store when the resume can arrive in another process: after a restart, on another host, or behind a queue. A memory store in another process holds nothing, so the answer is not written, and a run that closes with a request still held in memory warns.
This is the store's contract, from the ApprovalStore interface:
Where pending approvals wait between two invocations of one conversation, keyed by the conversation id, one entry per request, by its
requestedEventId(agent-events.md section 5.6). Two requests can be about one subject, as when a policy asks and then a human does. Each method can return its value or a promise of it. Pass a store that outlives the process when a resume can arrive in another one.Concurrency. Each method must be atomic on its own. The helper holds no lock across calls, so a
listand thetakeafter it are separate steps. The helper callsputonce a request is handed to the anchorer. A resume callslistonce, before its first record, and answers from what it read; it callstakeonce its answer is handed to the anchorer or found unbuildable, and it ignores whattakereturns.takereturns nothing when the entry is already gone: another resume took it,clearremoved it, or a later request with the same run id replaced it.Two processes that resume one conversation at once can both read the request before either takes it. Each then writes an
agent.approval.resolvednaming it, so the trail holds two answers to one request; onetakegets the entry and the other gets nothing, and the helper warns for the one that got nothing. A store cannot prevent this through this interface: run one resume per conversation at a time.
The methods are put(conversationId, pending), list(conversationId), take(conversationId, requestedEventId) and clear(conversationId). A store that lacks one of them is refused when the RunRecorder is built: the TypeError names each missing method.
This store is an example, not part of the package. It follows the contract on Redis, with ioredis: one hash per conversation, one field per request, and take and clear as one script each, so two resumes cannot both receive an entry.
import type { ApprovalStore, PendingApproval } from "@sanning/anchor";
import type { Redis } from "ioredis";
const TAKE = `local v = redis.call('HGET', KEYS[1], ARGV[1])
if v then redis.call('HDEL', KEYS[1], ARGV[1]) end
return v`;
const CLEAR = `local all = redis.call('HVALS', KEYS[1])
redis.call('DEL', KEYS[1])
return all`;
export class RedisApprovalStore implements ApprovalStore {
constructor(private readonly redis: Redis) {}
private key(conversationId: string): string {
return `sanning:approvals:${conversationId}`;
}
async put(conversationId: string, pending: PendingApproval): Promise<void> {
await this.redis.hset(this.key(conversationId), pending.requestedEventId, JSON.stringify(pending));
}
async list(conversationId: string): Promise<PendingApproval[]> {
const all = await this.redis.hvals(this.key(conversationId));
return all.map((s) => JSON.parse(s) as PendingApproval);
}
async take(conversationId: string, requestedEventId: string): Promise<PendingApproval | undefined> {
const s = (await this.redis.eval(TAKE, 1, this.key(conversationId), requestedEventId)) as string | null;
return s === null ? undefined : (JSON.parse(s) as PendingApproval);
}
async clear(conversationId: string): Promise<PendingApproval[]> {
const all = (await this.redis.eval(CLEAR, 1, this.key(conversationId))) as string[];
return all.map((s) => JSON.parse(s) as PendingApproval);
}
}Pass it as new RunRecorder(anchorer, { approvals: new RedisApprovalStore(redis) }). A Redis entry has no expiry, so a request that nobody answers stays until a take or a clear removes it.
How long a store call can take
Each store call waits at most approvalTimeoutMs (default APPROVAL_STORE_TIMEOUT_MS, 30 seconds). A resume reads the store before its first record, so a slow list, and a slow clear for supersedesPending, delays that record and every call queued behind it, up to the limit. A read past the limit holds nothing: the run opens as if no request were pending, with a warning. A put, take or clear past the limit is a warning, and the call keeps running and can still land. The helper does not wait for a put or a take before it writes the next record, and close() waits for the store calls still running. A slow store therefore slows a resume and the close of the run, and a store that never answers costs 30 seconds at each.
One invocation, one process
An AgentRun keeps the invocation's position, the next run.seq and the last event id, in the memory of the process that opened it. Every record of one invocation must come from that one AgentRun. Running one invocation across several workers is not supported: do not share a rootRunId between processes, and do not hand an AgentRun's work to another process. A resume is a new invocation, so it can run anywhere that reaches the store.
Assemble the evidence pack (npx @sanning/anchor bundle)
Someone asks for evidence for this agent, over this period, usually long
after the run finished. That is the bundle verb: a CLI, because the person
fulfilling an evidence request is usually not the person who wrote the code.
Its input is not a local trace, and cannot be. Placement is Sanning's act, and the inclusion proof comes into being server-side, later, when the interval stamper builds a tree. So the verb reads the proofs from the Sanning index and the bytes from your own log store, and writes one zip: the pack:
export SANNING_API_KEY=… # needs the `anchor:read` scope
npx @sanning/anchor bundle \
--agent claims-triage \
--from 2026-06-01 --to 2026-06-30 \
--logs ./logstore \
--out claims-triage-2026-06.zipThe pack is bundle.json beside logs/<event id>.json: the bundle is the machine-verified JSON, the pack is the zip that carries it. The bundle's body is sanning.stamp.evidence/v2 (section 5.3): your signed envelopes and their inclusion proofs, bound to the Sanning interval stamp whose Merkle root commits to them, with the stamp's witnessed bytes carried verbatim.
It takes no signing key, and there is no flag to give it one. Every event inside was signed at anchor time and stays signed; the pack is a container, so assembling one is not a key-custody event. The wrapper is sealed with a one-time assembly key minted for that run and thrown away, and issuer.kind is assembler: the seal proves the container was not edited on its way to you, and claims nothing about identity. Identity is where it always was: on each event's own envelope, checked per-event by npx @sanning/proof verify.
| Flag | |
|---|---|
| --agent | the agent's subject.agent_id, as committed inside each event |
| --from | period start, inclusive: a whole UTC day written YYYY-MM-DD. A time is refused with a usage error. Required unless --case is given, and refused with it: a case pack takes no dates |
| --to | period end: a whole UTC day written YYYY-MM-DD, and that day is included. A time is refused with a usage error. When it is today (the UTC date), the period ends at the end of the last sealed stamp interval instead, and a day after today is refused. Required unless --case is given |
| --logs | your sanning.logstore/v1 store root: the local directory holding content/ and records/, or s3://bucket or s3://bucket/prefix. Reading a bucket needs @aws-sdk/client-s3 and the same settings as recording: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_ENDPOINT_URL_S3, or the AWS credential chain; any other scheme is refused by name rather than half-read |
| --out | where to write the pack. A .zip suffix is appended if absent, because the public verifier recognises an archive by that extension |
| --base-url | the control plane (default https://api.sanning.io, or $SANNING_BASE_URL) |
| --allow-unstamped | assemble even when records in the period are anchored but not yet stamped. Without it the verb refuses. Takes no value |
| --case | select a case's records and declare the pack about it. The records are those the plane returns for the case id (case_id, in clear), each kept only when its own signed context.case_id is the case; no window is derived, and --from and --to are refused with it; see One case, no window |
| --handoffs-only | with --case, pack only the case's hand-off records: the minimum-disclosure selection for handing another organization your side of a case |
| --report-file | case file only: a file to put under report/. Takes a path, and may be given more than once |
FsLogStore keeps your records on local disk, and it works on Live as it does in the Sandbox. The folder holds the only copy of your records. If you lose the disk, you lose the evidence for the records on it. Sanning keeps only a hash and a time for each one, and no pack can be built from them: bundle refuses those records (exit 4) and names the missing records/<hash> object. Content missing while the record bytes are present is the case that reads Incomplete. For Live, use an S3-compatible bucket you own (versioning or Object Lock recommended), or back the folder up.
A storage backend other than the S3 protocol is added through ObjectStore (the write side) and LogStoreReader (the read side, and the resolver bundle uses for a --logs scheme). There is no built-in Azure Blob or native Google Cloud Storage adapter. A log store you bundle from more than once must be durable and must keep what bundle writes into it: a declaration's record and content go to the --logs store of the run that anchored it, and a later bundle of the same case from a store without them refuses (exit 4).
The API key comes from SANNING_API_KEY and there is deliberately no flag for it, a credential in argv lands in shell history and process listings, and this is a command people paste into tickets. A key without anchor:read is reported as a scope to widen, never as an absence of evidence.
SANNING_GATEWAY_URL (no flag) writes a witnessed-time cache beside the pack. Set it, and bundle asks that gateway's GraphQL endpoint for the block height and time of each stamp's witness transaction and writes them, unsigned, to witness-cache.json next to bundle.json (evidence-bundle.md section 5.6.6). It is a convenience for a human reading the pack years later, not evidence: nobody signs the file, it is outside bundle.json and its signature, and no verdict, exit code or grading input reads it. A reader older than sanning-proof 0.13.0 lists it as a file beside the pack and never opens it. A stamp not yet in a block, or a gateway that does not answer, gets no entry; with no entry at all, this verb writes no file, and a lookup failure never fails the pack.
A period that runs to today ends at the last sealed stamp interval. With --to set to today's UTC date, the pack ends at the end of the last sealed stamp interval before the build, not at midnight: every record in it has a stamp, and two builds in the same interval hold the same records and state the same period. The pack states that end as a time, and the signed text keeps ISO 8601 (2026-10-14 → 2026-10-20T15:00:00.000Z). "Today" is the UTC date the control plane reports, which at 00:30 in London in summer is still the day before: a --to after it is refused. This needs a control plane that answers GET /api/v1/user/records/sealed-through.
Selection runs on a value that is inside the signed material, the record's subject.agent_id, read from your own store. A Minimal-disclosure envelope does not carry it, which is why --logs is required to scope a pack to an agent at all.
It would rather refuse than hand you something that looks complete and is not:
- a record in the window whose record object is absent from your store fails the run: its
subject.agent_idis unknowable, one of them may be this agent's, and assembling over the rest would silently under-report the period; - a store object whose bytes do not hash to the key they were read from fails the run (
log-store.mdsection 3.1: the name is the integrity check); - a window that mixes
devandproductionevidence fails the run: a dev proof is permanently marked dev inside its signed bytes and belongs in no production deliverable; - records that are anchored but not yet stamped are reported as young, never as missing: the stamper seals on an interval, and the proof exists only once it has. They also fail the run rather than being quietly dropped, because a pack that omits them is short for the period it names and says so nowhere inside itself.
--allow-unstampedassembles anyway, and the summary then tells you the pack is short so you can say so in the cover note. Under--caseit refuses, exit2, when a record it would leave out was signed at or before the last record the pack holds (a delivery retry stamped later), because the pack would claim the case's records inside a period it does not cover; run again once the stamper has sealed it. A record signed after the last held one can still be left out; - and before writing anything, the verb verifies the whole pack (the bundle and the bytes travelling beside it) with
@sanning/proof, the same read-only kernel the recipient runs. A pack that does not verify is never written.
One case, no window
--case selects a case's records, and takes no --from or --to:
npx @sanning/anchor bundle --case case-4b19de \
--agent assessor \
--logs ./logstore --out case-4b19de.zip- The pack's records are the ones the plane returns for the case id, kept on their own signed
context.case_id. The SDK sends the case id, in clear, in the projection beside every record of a type the plane indexes (index).--caseasks the plane for the records filed under the case id (case_id, in clear, 1 to 256 characters: no SDK writes a case id longer than 128, and 256 is the plane's query bound only), pages to the end, and keeps each one whose own signedcontext.case_idis the case. It reads nothing else and derives no window. A case pack takes no dates: it holds every record of the case, however long the case runs. - The case id only finds candidates. It is the producer's own word and is not signed, so it selects nothing on its own: a row filed under it whose signed record names another case is left out and counted on the summary.
- Records sent without a projection are not found. A custom one-argument submitter would send none. A custom
submittermust accept the index argument that carries the projection (submit(envelope, index)):createAnchorerthrows at construction for one that declares exactly one parameter (a rest parameter or a mock is not judged by arity), rather than drop the projection in silence.submit(e, index = undefined)has length 1 and is refused too. - A record in the window that names no case refuses a declared pack (the signing seed is set), and an undeclared pack leaves it out and says how many. Pass the case id when you anchor.
- The pack's period is the span of the records it holds: the earliest to the latest
signed_atamong them, read from each signed envelope. The pack's records run oldest first by that signed time compared exactly at full precision (a fraction of any length), ties broken by event id, never by a time the plane's list sends. It is not a window, so there is nothing to pad. The declaration'speriod.endis the exclusive bound, one millisecond after the latest record. - A case pack holds every record of the case, however long the case runs.
--fromor--towith--caseis a usage error: a case pack takes no dates. The control plane reads the whole case, and a plane that does not say how much of the case fell outside what it read, or says some did (a record dated after its clock, or a plane that predates the whole-case read), is refused: the verb exits4rather than build a short pack. An empty selection exits4and writes nothing. - A case file (several
--agent) selects the same way: each pack states its own records' span, and the case file'speriodline is the span of all of them.
Several agents, one case: the case file
Give --agent more than once, with --case, and the verb writes a case file (evidence-bundle.md section 5.6): one pack per agent, each built, declared and verified exactly as a single pack is and sealed by that agent's own key (or the organization's evidence key, below), unpacked under packs/<agent>/ in one zip beside contents.json (an unsigned index of every file and its SHA-256) and HOW-TO-VERIFY.txt. Nobody signs the case file itself.
export SANNING_API_KEY=…
export SANNING_SIGNING_SEEDS=assessor=SEED_A,checker=SEED_B
npx @sanning/anchor bundle --case case-4b19de \
--agent assessor --agent checker \
--logs ./logstore --out case-4b19de.zipReplace SEED_A and SEED_B with each agent's 64-hex signing seed. SANNING_SIGNING_SEEDS holds one <agent>=<seed> entry per --agent, and SANNING_SIGNING_SEED is refused beside it (unless the organization kind is set). To seal every pack with your organization's evidence key instead, set SANNING_SIGNING_KEY_KIND=organization and put that one key in SANNING_SIGNING_SEED: it seals the wrapper of every pack and authors every declaration, each pack's issuer is { kind: organization }, and each record inside stays signed by its own agent. SANNING_SIGNING_SEEDS is refused beside the organization kind. --logs is given once for every agent, or once per --agent in the same order. A case file exits with the code the kernel's case gives the file it wrote, and writes nothing when that case would read failed; a case reads its worst pack. Every agent named gets a pack in the file, or nothing is written:
The organization's evidence key is registered on first use. With SANNING_SIGNING_KEY_KIND=organization, the first bundle that declares, a single pack or a case file, registers the key before it sends any declaration: it asks Sanning for the organization's evidence key and, when there is none, signs a challenge with the seed and registers its public key. It prints one line saying so, and Sanning emails every owner of the organization. A later run finds its own key and goes on. Make the seed with openssl rand -hex 32 on the machine that builds the packs; it never leaves that machine. SANNING_API_KEY is then a key with exactly handover:enroll (the Build evidence permission), anchor:read and anchor:write; an agent's API key never carries handover:enroll. A run that sends no declaration (no seed, the agent kind, or a pack or case file that is not complete yet) never asks. bundle exits 4, sending no declaration and writing nothing, when the organization already has a different evidence key (registering never replaces one: an owner or admin revokes it in the console, on the Signing keys page, and the message prints the first 16 hex characters of both keys), when the key can never be the evidence key (Sanning holds it for another identity, or it was revoked: make a new seed), when the API key lacks handover:enroll, and when Sanning refuses the registration for any other reason, named by the plane's code. When Sanning cannot be reached, after retries on a timeout, a 429 or a 5xx, it exits 2 and sends nothing.
| Agents' packs | Exit | Written? |
| -- | -- | -- |
| All verified | 0 | Yes. Each agent's declaration is anchored. |
| All verified, sandbox | 3 | Yes. Each agent's declaration is anchored. |
| Any incomplete (a stamp not confirmed yet included), none failed | 2 | Yes, with the incomplete packs inside and no declaration anchored. Running it again later writes a new case file in its place. |
| Any pack failed | 1 | No. The output names the agent and prints the kernel's lines. |
| No pack fails alone, and the case fails (through a hand-off) | 1 | No. The output says the case file would read failed and prints the kernel's lines. |
| Records not stamped yet, or the record index could not be reached | 2 | No. |
| Any agent's run could not run, or the file cannot be assembled or written | 4 | No. |
contents.json's absent[] is written empty. --report-file <path>, given any number of times, adds files under report/ beside a report/README.txt saying no record commits to them.
Every declared pack (SANNING_SIGNING_SEED set), single or in a case file, declares sanning.declaration/v2: each record is signed handoff (a record envelope-spec.md section 4.1 governs, claimed in handoffs[]) or step. Each hand-off record's message travels as logs/<event id>.json, exactly JCS(message), the bytes its message_hash commits to. So a full pack reads cleanly as a case, and --handoffs-only is the minimum-disclosure selection for handing another organization your hand-off records alone.
Exit codes: the kernel's one table. bundle exits with the code the kernel's verify gives the pack it wrote, and writes nothing when that pack would read failed. 0 written, verified · 1 nothing written, the pack would read failed · 2 written, incomplete (a stamp not on the public record yet, a record the pack lists and does not hold), or nothing written because the index could not be reached or records are not stamped yet · 3 written, verified with sandbox evidence · 4 could not run, nothing written: a bad flag, unreadable input, or a refusal that is not about the pack's verdict (nothing matched, a case the plane did not read whole, records that cannot be attributed, an output it cannot write).
Hand-offs between agents
createHandoff({ anchorer, caseId }) records a message that passes between two agents, over any transport: the sender's send writes agent.handoff.sent, the receiver's receive verifies what arrived and writes agent.handoff.received. Both are sanning.agent/1 records, built by buildAgentRecord and refused before signing unless they read verified: each carries the message's part counts, and the receiver's carries the sender's event_id. A receiver that holds the bytes of a file part names its position in heldParts, which the record lists as held and not checked. Two additions, both offline:
receive({ expectedSender })refuses a message whose signed sender key is not the one you name, withHandoffUnexpectedSenderError, before anything is recorded. Either case of a key is the same key.handoff.verify({ attachment, wireBytes, expectedSender? })reads a message before you decide: it runs the checksreceiveruns and returns{ message, messageHash, messageBytesHash, sequence, contentType, senderPublicKey, senderRecord, senderRunRecords }, and records nothing. A message that is not the one the sender committed to throwsHandoffAlteredError; callreceivewith the same input to record the tamper. Thenreceiverecords your decision.handoff.confirm({ sent, receivedRecord })lets the sender check the receiver's own signed record (received.receivedRecord, sent back over your transport) with the kernel'sverifyEnvelopeandreadHandoffs. It returns{ confirmed, reasons, outcome, receiverPublicKey, readings }, andreasonsnames every check that failed. A receipt is untrusted, so nothing about it throws.
outcome is a required argument of receive: the agent decides, accepted, rejected or failed, then receive records that decision, before your agent acts on the message. There is no default: this SDK never signs a decision on your behalf, and a missing or invalid value raises HandoffOutcomeRequiredError before anything verifies or is written. The spec has no word for "received, not yet decided", which is a real limitation Hand off between agents states in full, along with the refusal table.
Verifying
The auditor verifies the pack offline with the read-only
@sanning/proof, with no write
SDK in the trust path. Unzip first and verify from inside: handing the verifier
a .zip fails with a JSON parse error, and handing it a directory fails with
EISDIR.
unzip pack.zip -d pack
npx @sanning/proof case packThe case reader reads one pack or a whole case file the same way, and reads each pack's logs/ as part of it. bundle prints this command as its next step. npx @sanning/proof verify bundle.json --logs logs/, from inside the unzipped pack, grades one bundle on its own.
It prints one verdict, verified, failed or incomplete, read from what the pack holds, and exits on the kernel's one table: 0 verified, 1 failed, 2 incomplete, 3 verified with sandbox records, 4 could not run. A pack states no verdict of its own.
A single envelope also verifies by hand, against the AnchorResult your own process holds:
import { ed25519Verify, jcs, sha256Hex, utf8 } from "@sanning/proof";
const { signature, ...preSignature } = result.envelope;
await ed25519Verify(utf8(jcs(preSignature)), signature, result.envelope.public_key); // true
(await sha256Hex(result.eventBytes)) === result.envelope.payload_hash; // trueSee the runnable examples.
Production
Production structurally refuses auto-generated secrets: createAnchorer throws ProductionConfigError unless you pass a signer and a subject, and it throws the same error for a production record that names no log store (no payloadRef and no store locatorFor answer), before the record is signed.
import { createAnchorer, FsLogStore, LocalEd25519Signer } from "@sanning/anchor";
const anchorer = createAnchorer({
environment: "production",
// Identity key (signs envelopes). Any { publicKey(), sign() } works: a file
// seed is shown; Vault/KMS adapters implement the same interface.
signer: LocalEd25519Signer.fromSeedHex(process.env.SANNING_SIGNING_SEED!),
subject: { type: "agent", agent_id: "acme-app" },
apiKey: process.env.SANNING_API_KEY!,
logStore: new FsLogStore("./logstore"),
});The signing key is the only key. Reuse one per agent_id: a second key under one identity is a rotation, and it needs the outgoing key as previousSigner. Anchoring is metered against your API key (scope anchor:write).
When Sanning answers 429
Sanning limits how fast an organization can anchor. Over the limit, it answers HTTP 429 with a Retry-After header. The SDK then waits that long, plus up to 20% more, and sends the same bytes again: the envelope is not rebuilt or signed again, so the record Sanning accepts is the one that used the chain link. A wait never holds the chain: the next record on the same chain is built and signed meanwhile.
rateLimitWaitMsis a deadline, 10,000 ms by default (DEFAULT_RATE_LIMIT_WAIT_MS), measured on the clock from the start of the delivery, so slow answers count against it. No resend goes when its wait would end past the deadline: the delivery fails at once instead. In direct mode,anchor()therefore takes at mostrateLimitWaitMslonger than the first refusal, plus one round trip.- Every wait is at least 1 second, and one delivery resends at most 10 times. A wait Sanning states as shorter than 1 second waits 1 second. A wait longer than 60 seconds counts as 60 seconds.
- After a 429, no delivery from the anchorer starts before the time Sanning named, whichever record heard it.
- Past the budget, the record fails as it would without the wait. In direct mode,
anchor()throwsAnchorDeliveryErrorand the record is onanchorer.gaps. With a buffer, the record stays in the buffer and the next drain attempt goes no sooner than the time Sanning named, even when the backoff is shorter. Adrain()call does not send before that time either. - Inside the budget, a drain pass waits within the pass. Each record Sanning refuses can hold the pass for up to
rateLimitWaitMsplus one round trip (about 10 seconds by default) before it is delivered, and the first record that runs out of budget ends the pass. So a pass, and adrain()orclose()called during a block, can take up to that long for each refused record. rateLimitWaitMs: 0turns the wait off: a 429 fails the delivery at once.- No other refusal is waited on. A 429 without
Retry-After(a spent quota,QUOTA_EXCEEDED), every 403 (a full sandbox,SANDBOX_LIMIT_REACHED, included) and every other status fail at once.
rateLimitWaitMs applies to the client the anchorer builds from apiKey. A submitter of your own does its own waiting.
When Sanning refuses for a limit
Two refusals hold until a person acts: a 403 SANDBOX_LIMIT_REACHED (a Sandbox ceiling, such as records or bytes) and a 429 QUOTA_EXCEEDED with no Retry-After (the Live monthly quota). With a buffer, the drain then:
- Keeps every record in the buffer. Nothing is quarantined, dropped or recorded as a gap.
- Retries at
drainRetryMaxMs(60 s by default) from the first refusal, instead of climbing fromdrainRetryBaseMs. - Sets
recordingStatus().blockedByto{ status, code, limit }.limitis the ceiling Sanning named (records,bytes, ...) or the quota spent (requests).lastErrorcarries the code too. - Resumes on its own once Sanning accepts again, with no restart, and the first delivery clears
blockedBy.
To lift the limit, a person acts: in the Sandbox, reset the Sandbox (Settings, Sandbox, Reset the sandbox in the console), which deletes the organization's Sandbox records; on Live, raise the plan, or wait for the next month's quota. The Sandbox rate refusal, SANDBOX_LIMIT_REACHED as a 429 with Retry-After, is a wait (above) and does not set blockedBy. In direct mode, anchor() throws AnchorDeliveryError for either limit, as before.
Parallel workers on one key
Enrollment is limited per API key, to 12 calls a minute by default, and each enrollment takes at least two of them (the challenge and the enroll). Workers that share one key and one signing key, such as a serverless fleet or several agent processes, all enroll on their first anchor() and draw from that one limit. When they start together, some of them get EnrollmentThrottledError.
The key needs enrolling once, not once per worker:
- Enroll the key once, at deploy time or in a first job, with
enroll(). Enrolling a key that is already enrolled changes nothing, so a deploy can run it every time. - Start every worker with
autoEnroll: false. A worker then makes no enrollment call, and its firstanchor()sends the envelope straight away.
import { enroll, LocalEd25519Signer } from "@sanning/anchor";
// Once, at deploy time or in a first job.
await enroll({
baseUrl: "https://api.sanning.io",
apiKey: process.env.SANNING_API_KEY!,
agentId: "acme-app",
signer: LocalEd25519Signer.fromSeedHex(process.env.SANNING_SIGNING_SEED!),
});import { createAnchorer, FsLogStore, LocalEd25519Signer } from "@sanning/anchor";
// In every worker: the same seed, the same agent_id, no enrollment.
const anchorer = createAnchorer({
environment: "production",
signer: LocalEd25519Signer.fromSeedHex(process.env.SANNING_SIGNING_SEED!),
subject: { type: "agent", agent_id: "acme-app" },
apiKey: process.env.SANNING_API_KEY!,
logStore: new FsLogStore("./logstore"),
autoEnroll: false,
});If a worker starts before the key is enrolled, Sanning refuses its envelopes with HTTP 403, and the SDK raises SigningKeyNotEnrolledError (in direct mode, on the .cause of the AnchorDeliveryError that anchor() throws). Run enroll() for that key, or leave autoEnroll on.
When enroll() itself meets a 429 on the enroll call, it waits the Retry-After and sends the same signed challenge again, without asking for a new one, so a throttled enrollment costs no extra call against the limit. It asks for a new challenge only when Sanning says the one it holds has expired or been used.
Errors
Every error below is a subclass of AnchorError and carries a machine-checkable code:
| Class (code) | When | Do |
|---|---|---|
| IngestError (INGEST_REFUSED) | The plane refused the envelope. .retryable is true for 429, 5xx and transport faults. .retryAfterMs is the wait the plane asked for, at most 60,000 | Retry only when .retryable. The SDK resends only a 429 that carries a wait, within rateLimitWaitMs (When Sanning answers 429); it retries nothing else for you. |
| SigningKeyNotEnrolledError (INGEST_REFUSED) | An IngestError: the plane refused the envelope with 403 SIGNING_KEY_NOT_ENROLLED, because the key that signed it is not enrolled for the organization. Usual with autoEnroll: false | Enroll the key once with enroll(), or leave autoEnroll on (Parallel workers on one key). |
| AnchorDeliveryError (ANCHOR_UNDELIVERED) | A signed envelope did not reach the plane, so the outcome is unknown | Retain .result.eventBytes first. It might already be committed. |
| HttpTimeoutError (HTTP_TIMEOUT) | An ingest or enrollment call went silent past its bound (default 30s, covering the response body) | The outcome is unknown, so this is not evidence that it was rejected. Look the event up before re-sending, because re-running anchor() builds a new envelope and would anchor the same event twice. Re-running enrollment is safe as-is: same-key registration is a server-side no-op. Raise timeoutMs if your plane is legitimately slower; never leave the call unbounded. |
| RetentionError (CONTENT_RETENTION) | The log store refused the bytes, so nothing was sent | Refetch and re-anchor. The chain slot was already burnt, so it is also on gaps. |
| IncompleteTrailError (INCOMPLETE_TRAIL) | close() or assertComplete() found an undelivered or unbuilt event | Drain both .gaps and .unbuilt. Only .gaps carry eventBytes. |
| InvalidRefError (INVALID_REF) | A ref / payload_ref is not a URI, or is longer than 2048 chars | Percent-encode spaces and non-ASCII, or shorten the locator. Checked before anything is signed, because payload_ref becomes permanent public bytes. |
| ProductionConfigError (PRODUCTION_CONFIG) | Production mode without an explicit signer or subject, or a production record with no locator (no payloadRef, and no log store locatorFor answer) | Supply the missing credentials (dev secrets cannot reach production), or use ObjectLogStore or FsLogStore, give your store a locatorFor, or pass payloadRef on the call. |
| RotationUnauthorizedError (ROTATION_UNAUTHORIZED) | The agent_id is already enrolled under a different key | Point at the key already enrolled, or pass the retiring key as previousSigner. |
| EnrollmentFailedError (ENROLLMENT_FAILED), EnrollmentThrottledError (ENROLLMENT_THROTTLED) | Enrollment was refused, or a fleet cold-started together | Check the agent:enroll scope; stagger startup. |
Guarantees
- Local hashing only.
contentis hashed in-process (streams supported); only the signed envelope (a few hundred bytes) is sent to Sanning. - Minimal disclosure. The envelope carries no event type, no subject, no chain pointer: those live in the hash-committed record you retain.
- A salt on every record. Each record carries a fresh random 128-bit
context.salt, so Sanning, which holdspayload_hashand not the record, cannot confirm a guess at its content. Belowfull, Sanning does not receive the salt. No builder option sets it; a record you build yourself and pass toanchor({ buildRecord })orbuildEnvelopecarries whatever well-formed salt you gave it, and the spec makes no finding on a weak one. The module that draws the salt (dist/salt.js) is internal and not public API: it ships only because the builders import it. - Dev proofs are cryptographically dev.
environmentsits inside the signed scope; a dev proof can never be presented as production evidence, and asanning_test_key can never sign a production one. - Verification is a separate, read-only package,
@sanning/proof. This package contains the write path only.
Conformance
Byte-for-byte against the family corpus (sanning-io/proof test-vectors-v5.0). The ANS-104 data-item primitives this package still exports are byte-pinned against arbundles and re-verified by an independent Python parser in CI. See the profile spec.
