Reference · Command line
annon CLI
Build with pnpm build. The @defdone/annon package ships the annon bin;
in this checkout run node packages/annon/dist/node/main.js in its place.
Run annon --help for all flags and annon --version (or -v) for the installed version; with
--json the version is { "ok": true, "result": { "version": ... } }. It loads no config, wallet
or secret and also works in agent mode. With --json every command prints one compact JSON line
and asks nothing. Success is { "ok": true, "result": ... };
errors are { "ok": false, "error": { "code": ..., "message": ... } }. Without --json the same
envelope is printed indented whenever standard output is not a terminal, and always in agent mode,
so scripts and pipes read JSON either way. In a terminal a person gets short text instead: one or
two lines per command, catalog as a numbered table, errors as Error: message (code). Exit codes
are the same in every mode. Text from shops and hosts is shown with control characters removed.
In a terminal, share asks for approval with its terms as lines (seller, host, contract, price in
USDC, split, fee, NEAR listing and purchase storage with the number of sales the purchase storage
covers, and a register deposit only when it is not zero); sell with a sponsored split does the same
for the split and fee. Each browser approval is announced with one line before its waiting line,
such as Approval 2: register the file on NEAR. The share result shows expiresAt as a local
date and time with the Unix value in parentheses, or no expiry. When a seller check fails
with wrong_identity (stop, fund, share --resume), the error says who you are signed in as,
who the file's seller is, and how to sign in as the seller. Piped
output, --json and agent mode keep the JSON prompt and envelope unchanged.
Interactive session
annon with no arguments in a terminal, or annon shell, starts a session. It prints the version,
network, signed-in account and whether the configured contract is trusted, then reads commands at
annon> until exit, quit or Ctrl-D. Commands are the ones on this page without the annon
prefix; Tab completes names and flags, help lists them. Each line runs the same code as the
one-shot command, with the same trust prompt, price cap, purchase guard and confirmation, and the
session keeps no wallet, config or secret between commands.
catalognumbers its rows;buy 2buys row 2 of the last listing shown.- After a NEAR or Base payment
buywaits for acceptance, then asks where to save the file. statusandopen --output <file>without an ID use the latest purchasebuysaved for the contract and network of that line, as the one-shot commands do. The session remembers no purchase itself, so a line with another--contract-id,--network,--configor--state-dirnever picks up a purchase made under a different one.- Ctrl-C cancels a prompt (the answer is no), stops a wait for acceptance, or drops a read-only
command. During
buy,fund,sell,share,stoporrecoverit asksA payment may be in progress. Exit anyway? (y/N). Leaving removes nothing: the purchase saved before payment is still there, so check it withannon statusbefore paying again.
Without a terminal, with any argument such as --json, or in agent mode no session starts:
annon prints the help and annon shell fails with invalid_arguments.
The CLI reads a public configuration file named with --config /path/config.json or
ANNON_CONFIG. The default is ~/.config/annon/config.json. annon init --deployment defdone
writes one for the deployment run by defdone when none exists (init).
For any other deployment, write it yourself:
{
"contractId": "your-reviewed-contract.near",
"network": "near:mainnet",
"nearRpc": "https://rpc.mainnet.fastnear.com",
"baseRpc": "https://base.example/rpc-with-key",
"stateDir": "/absolute/private/annon-state",
"relayer": "https://your-reviewed-relayer.example",
"maxPrice": "0.2"
}
Contract ID and NEAR RPC must be supplied by human configuration or CLI flags for contract operations. Browser login alone uses a public RPC default for ownership verification. Base RPC is required only for Base purchases, Base listing creation and resuming Base unlock. NEAR-only verify/status and purchases need no Base RPC. No deployment is implicitly trusted. The first interactive command asks whether you trust
the configured contract to release file keys. --trust-contract records explicit trust
without a prompt. Trust is keyed by network, NEAR RPC and contract; changing any requires
new trust. An offer cannot select a different contract. MCP shares the trust store. For a server, human configuration may set trustContract: true or ANNON_TRUST_CONTRACT=true; tool calls cannot grant trust.
Flags override environment variables, which override config. Config fields have matching
ANNON_CONTRACT_ID, ANNON_NETWORK, ANNON_NEAR_RPC, ANNON_BASE_RPC,
ANNON_STATE_DIR, and ANNON_RELAYER variables. Endpoints use HTTPS; HTTP is allowed
only on localhost. Endpoint URLs cannot contain credentials or query parameters.
The relayer is optional when a NEAR wallet submits transactions. Direct register/reopen
calls use the caller's prepaid contract storage balance; fund it using the deployment's
storage interface before selling or recovering. The SDK exports storageDeposit(wallet, contractId, amountYocto); choose the amount explicitly. Insufficient storage is reported as storage_required.
Keys and saved purchases
Use annon login for per-action browser wallet approval, or annon init --agent for key references, remote signing and a persisted daily budget. See README.md for login, --no-open, --signer, keychain creation and the HTTP signer contract. The legacy explicit local-key sources below remain available. No key discovery occurs.
Select --wallet evm|solana|near or ANNON_WALLET. Local key values are accepted from environment variables or explicitly named files:
| Wallet | Environment | Named file flag / environment |
|---|---|---|
| EVM | ANNON_EVM_PRIVATE_KEY: 0x and 64 hex digits |
--evm-key-file / ANNON_EVM_KEY_FILE, containing that text |
| Solana | ANNON_SOLANA_KEYPAIR: JSON array of 64 bytes |
--solana-key-file / ANNON_SOLANA_KEY_FILE, standard Solana keypair JSON |
| NEAR | ANNON_NEAR_CREDENTIALS: credential JSON |
--near-key-file / ANNON_NEAR_KEY_FILE, near-cli-rs credential JSON with account_id, public_key, private_key (ed25519) |
NEAR files may omit account_id when --near-account / ANNON_NEAR_ACCOUNT supplies it.
On macOS, with no NEAR file or credential env value, explicitly select both
--near-account alice.near --near-public-key ed25519:PUBLIC_KEY (or ANNON_NEAR_ACCOUNT,
ANNON_NEAR_PUBLIC_KEY) to read the near-cli-rs native keychain entry:
service near-mainnet-alice.near, account alice.near:ed25519:PUBLIC_KEY.
Other platforms use the credential JSON file or environment. No keychain enumeration occurs.
Sell, buy, open, recover and stop also require a random 32-byte backup secret. It encrypts the
local purchase, recovery and sell records and the portable backups. It is never derived from a
wallet signature or key. See Backup secret.
verify and accepted/read-only status need neither a wallet nor this secret. A pending Base status with saved state and a backup secret may send unlock through the configured relayer or NEAR wallet. Status can update encrypted local state and backups: expired/canceled Base payments are marked with paymentState, preserving the purchase, attempts and recovery key. It never deletes the purchase record.
State directories are created with mode 0700 and records/outputs with 0600. Keep existing
state directories private. Purchases and recovery grants are encrypted by the SDK; portable
encrypted backups are under stateDir/backups. Public headers and resource URLs are saved
separately for later downloading. Preserve state after timeouts. Losing local state does not
lose recovery rights: the same recovery wallet can create a fresh grant on a new device with
a new backup secret (Loss explains when init creates one). Keys, signed payment
payloads and decrypted file contents are never returned in CLI/MCP results. Plaintext is written only to the explicitly named output.
Init and the configuration
Bare annon init sets up the configuration first, then the backup secret below. It writes the
configuration only when nothing exists at the configuration path (--config, then ANNON_CONFIG,
then ~/.config/annon/config.json); it never changes, replaces or writes through anything already
there, such as a file or a symlink, and reports it as kept without asking. With nothing there:
--deployment defdonewrites the preset for the deployment run by defdone without asking: the configuration in docs/quickstart.md, withstateDirset to the absolute path of~/.local/share/annon.defdoneis the only accepted value; anything else fails withinvalid_arguments(exit 2) before anything is written.- In a terminal without the flag (and without
--json), init asks once:Use the Annon deployment run by defdone (contract v1.annon.defdone.near, relayer relayer.mainnet.annon.dev, demo shop)? [Y/n]. Enter or yes writes the preset; any other answer writes nothing. - Otherwise no configuration is written. The result says how to add one.
The file is written with mode 0600 to an exclusive temporary file, synced, and published with a
hard link, so it never appears half-written and never replaces anything. A missing directory is
created with mode 0700. If something appears at the path while init writes, it is kept. The agent
policy check that runs before init reads an existing config as before, through a symlink too; a
path it cannot read as JSON, such as a directory, stops init with backup_secret_required (exit 2)
before anything is written.
The result adds config beside backupSecret: {"path": ..., "state": "created", "deployment": "defdone"},
{"path": ..., "state": "kept"}, or {"path": ..., "state": "none", "howTo": ...}. In a terminal
init prints one line for the configuration, one for the backup secret, and
Next: annon login --wallet near.
init --agent is unchanged: it saves signer settings only and refuses --deployment. Agent mode
refuses bare init as before.
Backup secret
Run annon init once, before buying, selling or enabling agent mode. It creates
~/.config/annon/backup-secret: 32 random bytes as 64 lowercase hex characters and a newline,
mode 0600, in a directory created with mode 0700. The file is written to an exclusive temporary
file and published with a hard link, so it never appears half-written and an existing file is
never replaced. Running init again only validates the file and reports "created": false. An
unsafe default is refused and never repaired: a symlink, FIFO or other non-regular file, a file not
owned by you or with group or other permission bits, malformed content, or an ~/.config/annon
that is a symlink, is not owned by you, or is writable by group or others. An existing 0755
directory is fine. Every command that reads the default applies the same checks.
The location is fixed. XDG_CONFIG_HOME, XDG_DATA_HOME, XDG_STATE_HOME, --config,
ANNON_CONFIG and --state-dir do not move it. For another private location, name an existing file with the explicit inputs below.
Sources, in order, as before this file existed:
--backup-secret-file(or, when the flag is absent,ANNON_BACKUP_SECRET_FILE), a file with the 64 hex characters.ANNON_BACKUP_SECRET, the hex value itself. Prefer a file: environment values are inherited by child processes.- The default file, only when neither is set.
An empty value counts as unset, as before: an empty --backup-secret-file selects no file even when
ANNON_BACKUP_SECRET_FILE is set, and moves on to ANNON_BACKUP_SECRET. Hex must be lowercase in
every source; an optional 0x prefix and surrounding whitespace are accepted. A selected source that is missing,
unreadable or malformed fails with backup_secret_required (exit 2); there is no fallback to a
later source, the default file or a new secret. annon init with an explicit source only validates
it and never writes, creates or changes that file. Commands other than init read the secret but
never create it, and agent mode and MCP never create it. Bare init accepts only --json,
--config, --state-dir, --backup-secret-file and --deployment; signer options need --agent.
Output: stdout carries the usual single JSON result, for example
{"ok":true,"result":{"configured":true,"backupSecret":{"source":"default-file","path":"/home/me/.config/annon/backup-secret","created":true},"config":{"path":"/home/me/.config/annon/config.json","state":"kept"}}}.
source is default-file, flag-file, env-file or env; path is shown for files only. The
one-time creation notice goes to stderr, also with --json. The secret itself is never printed, in
results, errors or notices.
Back it up. The secret is not part of the encrypted backups in stateDir/backups; copy the file
itself, separately, to private encrypted storage. Never cat it or paste it into a terminal. This
copies without displaying it and refuses an existing destination:
node --input-type=module -e '
import { constants } from "node:fs";
import { copyFile } from "node:fs/promises";
await copyFile(process.argv[1], process.argv[2], constants.COPYFILE_EXCL);
' "$HOME/.config/annon/backup-secret" /mounted-private-encrypted-backup/annon-backup-secret
The copy keeps mode 0600 when the destination supports POSIX permissions; check it. A secret manager that imports files is also fine.
Restore. On a new machine, put the saved file in a private directory (directory mode 0700, file
mode 0600), copy the encrypted record backups separately, and select the file. Do not run init
first:
export ANNON_BACKUP_SECRET_FILE=/absolute/private/restored-annon-backup-secret
annon open /absolute/private/purchase-backup.json --url https://host.example/file --output restored-file
Opening one known backup proves the restore. To restore to the default location instead, create
~/.config/annon with mode 0700 and copy in the other direction, still refusing an existing file:
mkdir -p -m 700 "$HOME/.config/annon"
node --input-type=module -e '
import { constants } from "node:fs";
import { copyFile } from "node:fs/promises";
await copyFile(process.argv[1], process.argv[2], constants.COPYFILE_EXCL);
' /mounted-private-encrypted-backup/annon-backup-secret "$HOME/.config/annon/backup-secret"
Loss. If the secret disappears, commands fail with backup_secret_required and a pending
status stays pending; nothing recreates it. Restore the same bytes. Bare init creates a new
secret only when both checked state locations are empty: the effective state directory and the
default ~/.local/share/annon, each in records and backups. If every copy is lost and you want
to recover with a new secret, first move the whole old state, including ~/.local/share/annon, to
a separate private archive and keep it. Then use an empty state directory, run init, and run
recover with the same recovery wallet. That creates a fresh grant and new records; it cannot
decrypt the archived records or resume pending sell jobs. An operator can instead provision a
separate secret file and select it with ANNON_BACKUP_SECRET_FILE. Use one secret per state
directory.
Agents. init --agent does not create or reference a backup secret. Run bare init before it,
or give the agent an operator-managed file with an absolute ANNON_BACKUP_SECRET_FILE in the
launcher. A launcher that sets ANNON_BACKUP_SECRET_FILE must point it at a file that exists; a
missing file fails without falling back to the default. Once agent mode is active, init is
refused, so provision or restore the secret outside the running agent.
Commands
Identity syntax is evm:0xADDRESS, solana:BASE58_OR_HEX, or near:account.near.
Prices are decimal USDC with at most six decimals. Splits use integer basis points,
totaling 10000. The first split recipient gets the rounding remainder.
annon sell report.pdf --price 0.2 --split near:alice.near:10000 --wallet near --output report.pay2
annon sell report.pdf --resume 0xFILE_ID --wallet near --output resumed.pay2
annon sell report.pdf --price 0.2 --split evm:0x1111111111111111111111111111111111111111:10000 --wallet evm --base
annon buy https://host.example/report --route near --wallet near
annon buy https://host.example/report --route near --open report.pdf
annon buy 2 --shop demo --open report.pdf
annon status
annon open 0x1a2b3c4d --output report.pdf
annon buy offer.json --url https://host.example/report --route base --wallet evm --max-price 0.2
annon buy https://host.example/report --route 1click --wallet solana --from-chain solana
annon status 0xPURCHASE_ID --json
annon open 0xPURCHASE_ID --output report.pdf
annon open report.pay2 --purchase /private/purchase-backup.json --output report.pdf
annon recover --recovery near:alice.near --wallet near --json
annon open /private/recovery-backup.json --url https://host.example/report --output recovered.pdf
annon verify report.pay2 --json
annon verify https://host.example/report --json
annon stop 0xFILE_ID --wallet near
IDs in these commands are placeholders for full 0x plus 64 lowercase hex digits.
Fewer steps for a person (agent mode refuses all three and keeps requiring full URLs and IDs):
buy <row> --shop <id> [--search <q>]buys that row of the listingcatalogprints for the same--shopand--search. The CLI names the row's title and URL, then checks the file and its terms as for a typed URL. A catalog can change between listing and buying, so read the terms before you confirm. An offer file named like a number is written./2.buy --open <file>waits up to three minutes for acceptance and then writes the opened file. It refuses an existing<file>before paying. The result is the buy result withstate: "opened"andopened: { output, bytes }. If the purchase is not accepted in time it addssettlement: "pending"and exits 4; if a status check or the open fails after payment, the result still names the purchase and addsstatusErrororopenError, and the exit code is that error's. A purchase that is stillstate: "uncertain"wins over the follow-up error: the result carriesstatusError, and the exit code stays 4. Nothing is paid twice: finish withstatusandopen. A 1Click buy returns its deposit instructions without waiting. In a terminal,buywaits for acceptance even without--open.statusandopen --output <file>without an ID use the latest purchasebuysaved for the configured contract and network. An ID may be shortened to a prefix of 8 or more hex digits, with or without0x. A prefix only names purchases thatbuyorrecoversaved for the configured contract and network; one that matches none of them, or more than one, is refused withpurchase_required. A purchase saved by an older version, or for another contract or network, needs its full ID. Foropen, a name of 8 to 63 hex digits is always read as a prefix: write such a file as./name.sellcreates a PAY2 file; arrange hosting separately.buyaccepts the HTTPS resource URL or a named file containing decoded x402PAYMENT-REQUIREDJSON. An offer file requires--urlwith the independently selected resource URL; it must match the offer. It checks the public header and registered terms before the SDK authorizes payment. Every buy requires--max-price,ANNON_MAX_PRICEor configmaxPrice(decimal USDC); the offer never supplies the cap. A configured cap also bounds an explicit flag. The default route is direct NEAR for a NEAR wallet, 1Click when--from-chainis given, otherwise Base for an EVM wallet. Explicit Base fails if that route or a funded EOA is unavailable; it never silently chooses another payment route. A file whose final on-chain terms have no Base payee (files from NEAR and Solana sellers) has no Base route:--route basefails withroute_unavailable(exit 2) before any wallet step, and an EVM wallet without--routegetsorigin_required. Pay such a file with--route 1click --from-chain base(or a configured Base--origin) to spend USDC held on Base. After an uncertain reply, retain the saved backup and check status rather than buying again. Resume the existing purchase withstatusandopen. A saved live or accepted purchase blocks another buy withpurchase_open. Only an explicit--force(MCPforce: true) creates another purchase despite that saved purchase.
1Click accepts --from-chain solana or sol (ID sol), ethereum or eth (ID eth),
arbitrum/arb, polygon/pol, optimism/op, avalanche/avax, and berachain/bera.
Other chain IDs pass through unchanged. EVM refund defaults use eth, base, arb, pol, op,
avax, bsc, gnosis, bera, scroll, monad, xlayer, abs, and plasma.
The optional
--from-asset (the exact nep141: asset ID). Without an asset it selects the unique USDC
entry for that blockchain in 1Click's token list. Symbols such as sUSDC are not USDC matches. For BTC, other tokens, or ambiguous USDC
entries, specify --from-asset. --refund-to must name a refund address on the source
chain; it defaults to the selected wallet's address only when the chain family matches.
These also have ANNON_FROM_CHAIN, ANNON_FROM_ASSET, ANNON_REFUND_TO equivalents. Only
--from-chain or --origin selects 1Click automatically: with ANNON_FROM_CHAIN, name
--route 1click explicitly, or a NEAR wallet pays directly on NEAR.
Human configuration can define named origins, for example {"base-usdc":{"fromChain":"base","fromAsset":"nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near","usdcDecimals":6}}, or the same JSON in ANNON_ORIGINS. Select one with --origin base-usdc. Each may specify refundTo; otherwise the configured ANNON_REFUND_TO or matching wallet address is used.
For a human 1Click purchase, the SDK saves the live EXACT_OUTPUT quote and encrypted purchase record before confirmation. The terms show the source chain, asset, symbol and token contract when known, input amount in human and base units, and deposit cutoff. No funds are sent by quoting or confirming these instructions. Recovery proof follows review. Declining buys nothing and leaves an unpaid encrypted purchase record. The same live quote supplies the returned instructions. After review and recovery proof, at least ten minutes must remain before the deposit cutoff, otherwise the CLI returns quote_expired: "The 1Click quote expired. Run buy again." Do not fund that quote; the saved purchase still blocks a plain buy, so request a fresh quote with buy --force. Human terminal mode requires a prompt before requesting a quote. Explicit assets bypass token lookup; human units then use the quote's formatted amount when available.
Successful CLI JSON and agent results also include source with chain, asset, amount, amountFormatted when known, and depositBefore, plus available symbol, decimals and contract metadata. JSON and agent modes do not add an interactive prompt. A 1Click failure before deposit instructions return releases the agent budget reservation; returning instructions keeps it reserved.
The result includes instructions.address, amount in source token base units, asset,
chain, optional memo, and qrData. Fund these externally with the wallet you already use.
Never omit a required memo. instructions.depositBefore is the cutoff for a confirmed deposit;
purchaseExpiresAt is the later contract delivery deadline. The SDK reserves ten minutes between them,
refuses insufficient windows or a swap estimate longer than that buffer, and checks the entire echoed
quote request. Origin-chain confirmation time must fit before depositBefore; an estimate is not a
settlement guarantee. Do not deposit after that cutoff even if the service address stays active.
The three recorded quotes return an address-inactivity quote.deadline 72 hours after the echoed
request deadline. That extension must not extend the buyer's cutoff or contract purchase expiry.
The 1Click OpenAPI describes request deadline
as the start of refund handling, response deadline as address inactivity, and timeEstimate as
execution time after deposit confirmation. Late delivery can be refused by Annon; service SUCCESS
alone does not prove acceptance. status resumes a saved paid Base purchase by requesting unlock, then checks final NEAR acceptance. An unsafe payment returns settlement_pending immediately with exit code 4 (pending); 1Click SUCCESS alone
does not grant access.
The signing wallet is also the recovery identity. A supplied --recovery kind:id must match the
local wallet or configured signer.identity; a mismatch is refused with wrong_identity before
payment. Refunds from Annon go to that wallet's Intents identity; 1Click source-chain refunds use
--refund-to.
For moderated files, pass --moderator account.near on buy only after deciding to trust
that moderator, who can block release. A seller sets it with the same flag on sell.
open accepts a saved purchase ID, encrypted purchase/recovery backup, or a local PAY2 file
with --purchase. It uses saved resource metadata or --file/--url, then SDK grant proofs
and authenticated decryption. New-device recovery may require --url or a local PAY2 file.
Existing output files are never overwritten. verify checks a local file's header and body;
a URL checks only its public header. Verification does not prove future host availability.
Opening a Base purchase requests unlock before the grant-proved download. It also resends its saved signed payload with the download when present; it does not create a fresh payment authorization after a lost reply.
Key release transport timeout retries are bounded to three attempts with backoff, using the same
unlock/reopen/claim request. In-flight relayer replies (202 pending, or a legacy duplicate 409)
are polled every five seconds for at most three minutes. A known transaction hash is retained
across outcome timeouts, so it is looked up without reposting. If still pending, retain state and retry. Registration, transfers and payment authorization are never
blindly retried. Raw upstream errors are intentionally suppressed to avoid leaking secrets.
| Exit | Meaning |
|---|---|
| 0 | Command completed; buy may still require a deposit or settlement |
| 1 | Operation failed; inspect final status and retained encrypted state before retrying |
| 2 | Invalid arguments, configuration, wallet source or missing local input; purchase_open when a saved purchase of the file, including an uncertain NEAR send, still blocks a new one |
| 3 | First-use contract trust required or declined; browser approval cancelled (cancelled), expired (cancelled, or rejected or wallet_error after the last wallet failure the page reported) or declined by the wallet |
| 4 | Not settled, and not proof of failure: status reports pending; buy returned state: "uncertain" (its payment may be on chain; the JSON result is unchanged and names the saved purchase); or transaction_uncertain: a transaction may have been sent and is not confirmed |
In browser approval, once the CLI has acknowledged the page's send start, the request can only end
as a verified transaction or as transaction_uncertain: a wallet failure, a cancel, the expiry, or a
result the CLI cannot verify (an RPC rejection, malformed evidence) never counts as "not sent". The
purchase is saved with that uncertainty, with the transaction hash only when the wallet returned a
valid one. annon buy then exits 4 with state: "uncertain", and annon status <purchase id>
answers submission: "uncertain" until the purchase is accepted. Do not pay again.
A plain annon buy of the same file is refused with purchase_open while that uncertainty is
saved, also after the purchase expired: a late transfer still moves tokens, and the contract then
owes a refund that is paid out later rather than returned at once. Neither a pending status, an
expired purchase nor an empty wallet history proves that nothing was sent. --force overrides the
guard; use it only after you have reconciled the original attempt, for example by finding its
final transaction or its refund, because otherwise you may pay twice.
SDK seller resume and CKD configuration
sell saves an encrypted sell job and portable backup before registration. Retain the original
plaintext and its file ID; sdk.resumeSell({ fileId, data, seller, publish }) reconstructs the
same ciphertext, checks the registered commitment, and completes header publication/hosting.
It uses reopenSeller if registration landed without a usable CKD response, and retains the
CKD secret in the encrypted job only for publication retries. After publication, the saved job and its current
portable backup contain public terms/metadata and a published marker, with fileKey,
sellerSecret and ckdSecret cleared. Seller one-time keys are cleared from their records and
current backups after the CKD response is opened. Recovery of a published listing needs control of the registered seller
wallet and the existing PAY2 ciphertext; request a fresh CKD response with reopenSeller to open
that file. Before publication, resume requires the original plaintext and the pending sell job.
Plaintext alone can create a new listing, but cannot reproduce the old ciphertext after cleanup. A published job cannot recreate ciphertext using a retained file key. User-made
backup copies and external backup history cannot be erased by the SDK; remove obsolete pre-publication
copies if this retention policy matters to you. sdk.reopenSeller({ fileId, seller })
also works on a fresh device and backs up its new one-time key before the call. These are SDK
methods; the CLI exposes sell original.pdf --resume 0xFILE_ID, and MCP exposes
annon_sell with target and resume. A failure after saving the registration job reports fileId
in the safe error so it can be resumed without inspecting backups. Base split creation occurs before the
saved registration job, so a failed split deployment still needs separate reconciliation.
The SDK reads get_config.mpc and ckd_domain, then that account's public_key at finality.
An optional human mpcKey / ANNON_MPC_KEY pins the observed value and fails closed on a
mismatch. The low-level openAnswer requires this key explicitly; it has no mainnet default.
Recovery isolates failures per purchase in batch mode and returns safe errors in CLI/MCP.
An expired pending reopen without a final grant gets a new backed-up key, nonce and deadline;
the preceding revision remains in an encrypted revision backup.
Agent policy applies when the pinned config has agent: true, the launcher sets
ANNON_AGENT=true, or the MCP adapter forces it. Agent config must contain a decimal USDC
maxPrice, even when the launcher supplies an environment cap. Per-call --contract-id,
--near-rpc, --base-rpc, --relayer, --network, --trust-contract, --moderator,
--max-price, --state-dir and alternate config paths are refused. Init and login are refused
once agent policy is active. Buy targets must be secure URLs; local offer files are refused.
Offer header URLs must share the advertised resource origin in every mode.
In every agent mode, ANNON_STATE_DIR is ignored; the config owns stateDir and its budget
ledger. Config maxPrice is required. If ANNON_MAX_PRICE is present, the effective cap is the
smaller of environment and config. Absent allowedResources permits any HTTPS URL or HTTP localhost URL within mandatory
maxPrice and dailyBudget. An explicit empty list denies every URL. Entries may be exact
URLs or path prefixes ending in /*, on the same origin and port. Prefixes cannot cross
path boundaries or authorize another origin. ANNON_ALLOWED_RESOURCES, when present,
further restricts the effective list, including when config leaves it open.
These environment settings can only tighten policy, regardless of the agent-mode trigger.
Deployment and trust overrides (ANNON_CONTRACT_ID, ANNON_NETWORK, ANNON_NEAR_RPC,
ANNON_BASE_RPC, ANNON_RELAYER, ANNON_TRUST_CONTRACT, ANNON_MODERATORS,
ANNON_MPC_KEY and ANNON_ORIGINS) are ignored in agent mode unless the launcher explicitly
sets ANNON_AGENT=true. In that explicit mode, the launcher owns those values.
The resource allowlist applies to open --url and to saved download URLs too.
If the home config enables agent mode, an alternate ANNON_CONFIG is refused. Use
ANNON_AGENT=true or the MCP launcher to keep agent mode enabled independently of config contents.
For a 1Click USDC source, price and daily limits apply to the quoted source amount, including
its quoted fees. Every configured origin must set usdcDecimals to declare its source USDC
precision or maxSourceAmount to cap its source base units. Token catalog decimals do not set
spending policy.
For other assets, configure maxSourceAmount on that origin in source base units; the quoted
amount must fit it. The destination USDC amount still counts toward the daily USDC budget.
Quotes without enough source policy are refused before deposit instructions are released.
A saved live or accepted purchase blocks another buy of that file. Resume its status and open
it using its purchase ID. Use buy --force only when you explicitly want another purchase.
A supplied --recovery must match the configured signer.
Base purchases check the trusted relayer's eligibility decision and registered split before signing.
Completed-download cooldowns return download_limited and retryAfterSeconds immediately.
Other host overloads retry within a total automatic wait of 60 seconds. When the next wait would
exceed that budget, the full remaining hint is returned. CLI JSON includes the error and exit code 4;
human output states the wait. MCP stores download and settlement waits locally and refuses repeat
requests until they elapse, including after restart. Wait, then reuse the same purchase and output
path. Buying again to bypass a wait spends money unnecessarily.
Agent mode also requires a human-set workDir. Relative sell.target/output and
open.file/output paths start there. Local verify targets, non-ID open targets and
non-ID open --purchase backup paths also start there. Verify URLs and purchase IDs retain
their existing meanings. Canonical paths must stay inside it, including symlink
targets and parents of new outputs; parent traversal (..) is refused with path_not_allowed.
The sell default output is checked too. ANNON_WORK_DIR is accepted only when the launcher
explicitly sets ANNON_AGENT=true. That flag also pins the config to
~/.config/annon/config.json; a different ANNON_CONFIG is an error.
MCP is the policy boundary: tools cannot replace the operator config, environment or credentials.
A shell agent running as the same OS user is not contained by these checks; it can edit that
user's files or run another client. Configure process and OS permissions for that threat model.
Browser opener processes receive only executable lookup and desktop routing variables, including
BROWSER, desktop session identifiers and LANG, excluding signing and backup credentials.
Relayer HTTP 429 and 503 responses with short Retry-After delays are retried at most three
times. Delays above 60 seconds return relayer_rate_limited or relayer_unavailable immediately.
HTTP 425 always keeps settlement_pending guidance: agents, JSON and status return immediately;
human open retries at 10, 20, 30, 40 and 60 seconds, with Retry-After as a minimum. A hint above
60 seconds returns immediately for later resumption. Keep the saved purchase and never pay again.
Before a Base payment through a configured relayer, the client checks its advertised contract,
unlock support, disabled state and minimum sponsored price.
A final unlock CKD answer can supply the first open using exactly the same final-grant and MPC
pairing verification as claim_key. An optional configured MPC pin remains enforced, but is not
required for this optimization. Missing or invalid answers fall back to verified claim_key.
Streaming sell/open accepts regular files only, refusing FIFOs; long output basenames can exceed the filesystem name limit because temporary files append a random suffix. Local verify still buffers the file.
Interrupted processes may leave private .tmp plaintext files or .annon-spool-* encrypted directories beside the output; remove these leftovers before retrying.
Outputs are published with a hard link, so the output directory must be on a filesystem that supports hard links (not exFAT or FAT32, and not some network or FUSE mounts); otherwise the final step fails with no output written.
Purchase storage and sponsored splits
Self-funded NEAR sellers can use annon sell <file> --price <USDC> --split <split> --storage-budget 0.05. The budget is NEAR, separate from registration storage and from
the signed terms. Registration is followed by explicit wallet funding before publication.
A definite funding refusal clears the uncertainty state and can be retried on resume.
Saved sell jobs record funding intent before sending and never automatically replenish
a completed or uncertain allocation. After uncertainty, inspect the transaction and explicitly
fund with annon fund if needed; resume requires the configured target to be available
before accepting that uncertain allocation as resolved. The human config field storageBudget supplies the same decimal-NEAR
target. In agent/MCP mode it is the only source; per-call storage funding overrides are
refused. Sponsored registrations use the relayer allocation instead.
annon fund <file-id> <NEAR> allocates nonwithdrawable NEAR using a NEAR wallet.
annon budget <file-id> reads available yoctoNEAR and the admission requirement.
After an uncertain funding result, check the file's storage balance with annon budget <file-id> before funding again; a new run is a new allocation.
Funding is human-only: agent mode refuses fund with human_only, and MCP exposes
no funding tool. --storage-budget requires a self-registered NEAR sale; other routes
refuse the flag. Self-registered sales without an allocation return a warning.
The SDK exports fundFileStorage(wallet, contract, fileId, amountYocto, prepaid?)
and fileStorageBalance(rpc, contract, fileId); zero-attachment prepaid funding can spend
only the caller's own prepaid balance.
NEAR and 1Click buy preflight refuses before payment with file_storage_low if the
file cannot cover the 4,096-byte admission allowance. The contract checks again at receipt;
preflight cannot reserve capacity. Base unlock stays caller-funded and needs no file budget.
Existing claims and recovery continue after a file budget is depleted.
Sponsored sell obtains the relayer fee and treasuries from /v1/capabilities, adds the
required treasury share and proportionally scales the other shares. Base listings use
one EVM treasury share at the larger route requirement. Rounding goes to an original
non-treasury recipient; the treasury share rounds up by less than one basis point. Interactive CLI asks approval of the resulting split
before registering or creating a Base split. Config maxProtocolFee defaults to
{ "fixed": "30000", "bps": 100 } (0.03 USDC plus 100 bps); fixed is USDC base units.
JSON, agent and MCP sells refuse higher advertised fees with protocol_fee_above_max.
Interactive CLI shows the advertised fee and whether it exceeds the ceiling before
approval. Agent URL paths refuse %2f and %5c, case-insensitively.
JSON/agent modes return the resulting split in terms.
Self-funded listings have no compulsory protocol fee. An eight-recipient split needs a
free slot or an existing treasury recipient before sponsorship can add a treasury.
Shop discovery
Use discovery before configuring a wallet or contract:
annon shops
annon shop add https://shop.example/demo --id example
annon catalog --shop example --search notes --limit 20 --offset 0
shop add saves a local alias for the canonical /.well-known/annon-shop.json URL. It grants no deployment trust. Configure shopDirectoryUrl to read a directory; no directory is selected by default. Local shops and optional defaultShop belong to the human configuration and cannot be changed by remote documents.
{
"shopDirectoryUrl": "https://directory.example/shops.json",
"shops": [
{
"id": "example",
"manifest": "https://shop.example/.well-known/annon-shop.json"
}
],
"defaultShop": "example"
}
Both listing and catalog results contain items, total, and nextOffset (null at the end). shops searches shop names; catalog searches file name, title and description. Search ignores case. Catalogs sort by newest creation time, then file ID; limits default to 20 and accept 1 through 100. Offsets are nonnegative integers. --shop takes a local alias or a manifest URL and defaults to defaultShop. A shop that cannot be read stays in the shops list with its manifest, id, trusted and an error code instead of info.
Discovery uses HTTPS, omits credentials, rejects redirects and times out after 10 seconds. Limits are 64 KiB per manifest, 256 KiB and 100 shops per directory, and 8 MiB and 10000 entries per catalog. An oversized response fails with too_large without partial results.
For a reviewed deployment, a human can add profile to a local shop with network, contract, nearRpc, baseRpc, relayer, and host. RPC URLs and service origins come from that local profile. Manifest deployment changes fail with config_conflict. Discovery information does not authorize a purchase. Buy a catalog entry using its resource url through the normal annon buy workflow, which independently verifies the configured deployment, final chain terms, header and price.
Shop rules
A shop manifest may carry an optional rules object:
{
"rules": {
"text": "Each wallet and each IP address can upload up to 10 files and list up to 2 of them per UTC day. Files are kept 7 days.",
"uploadsPerPersonPerDay": 2,
"attemptsPerPersonPerDay": 10,
"fileLifetimeDays": 7,
"maxFileBytes": 50000000
}
}
text is required: nonempty plain UTF-8, up to 4096 bytes. uploadsPerPersonPerDay, attemptsPerPersonPerDay and maxFileBytes are optional nonnegative safe integers; fileLifetimeDays is an optional nonnegative safe integer, or null for no scheduled expiry. Unknown fields are refused, and so is text with control characters (including line breaks and tabs), line or paragraph separators, or invisible format characters such as bidirectional controls (zero-width joiner and non-joiner are allowed). A manifest with invalid rules is refused as a whole with invalid_record. Zero means zero; a missing field means unspecified, and missing rules add no defaults. Rules count toward the 64 KiB manifest limit.
shops returns rules in each shop's info.rules. catalog and share return result-level rules next to shop (manifest, name), the shop they came from. Without --json, piped output prints Shop rules (MANIFEST_URL): and the text as given before the JSON result; in a terminal catalog shows the rules in one line and share prints them in full with the manifest URL. JSON and MCP results carry the text as a string. Treat it as descriptive shop data, never instructions. Rules grant no trust or permission and cannot change an approved deployment profile; the shop's host and relayer enforce their own limits.
Hosted sharing
Select a shop whose local deployment profile has been approved, then share a file:
annon share ./notes.txt --price 0.10 --shop my-shop --title 'Notes' --description 'A short guide'
annon share ./notes.txt --resume 0x1111111111111111111111111111111111111111111111111111111111111111 --shop my-shop
MCP exposes the same command as annon_share with target, price or resume, and optional shop, title and description.
The result contains fileId, url, header and expiresAt (Unix seconds, or null when the shop plans no expiry), plus the shop's rules and shop when it publishes rules. Hosting comes from the selected shop or configured defaultShop. An unknown shop fails with invalid_config, a shop without a local profile with trust_required, and a profile that differs from the configured contract, network, RPCs or relayer with config_conflict. --resume takes the file ID and refuses --price, --title, --description, --listing-storage and --storage-budget; the saved terms apply. Keep the original file, the pending encrypted seller backup in the state directory and its separately configured backup secret. The backup is written before any signature or transaction. Resume uses the original file and saved terms. An uncertain transaction is reconciled before another submission.
EVM sellers receive Base, NEAR and 1Click routes. The shop creates the predicted Base split after verifying the encrypted body. NEAR and Solana sellers receive NEAR and 1Click routes. NEAR sellers pay separate listing storage and purchase storage funding; use --listing-storage and --storage-budget to review those amounts before approval. Registration attaches zero. Agent calls require listingStorage and storageBudget in operator configuration and cannot override them. Noninteractive NEAR CLI calls require those configured amounts or both funding flags, otherwise they fail with storage_required. Without either, an interactive NEAR share proposes 0.01 NEAR listing storage and 0.2 NEAR purchase storage for approval, and in a terminal says that both are proposals. Purchase storage covers about 1 + floor((bytes - 4096) / 854) sales, where bytes is the budget divided by 10^19 yoctoNEAR: 0.2 NEAR covers about 19, 0.05 NEAR about 2, and below 0.04096 NEAR none. File plaintext is limited to 50,000,000 bytes. Save your own copy before the returned hosting expiry. The hosting lifetime is the shop's policy; the CLI accepts any future expiry or null.
Shop limits answer with error codes: the host with rate_limited (daily upload count per wallet, per IP or overall, with retryAfterSeconds), host_capacity or too_large; the relayer with limited (a relayer admission limit, such as an hourly request limit or a daily sponsorship quota; wait retryAfterSeconds) or budget. None of these refusals spends the seller's funds. Resume the saved sale later with --resume rather than starting another one.