Tech Docs

Learn about the architecture, metering rules, API, settlement, receipt verification and security rules.

Sandbox v0.1 · 2026-11-29

On this page
  1. System architecture
  2. Units and precision
  3. Report usage
  4. Deduplication
  5. Revisions
  6. Reporter signatures
  7. Normalize tokens
  8. Estimate electricity
  9. Compare with provider totals
  10. Data connections and legacy records
  11. Quotes and budgets
  12. Sponsorships
  13. Idempotency and retries
  14. Automatic matching plans
  15. What gets matched
  16. Run results
  17. Strict mode
  18. Edit or stop a plan
  19. Settlement and recovery
  20. Match statuses
  21. Batch statuses
  22. External registries
  23. Fees and net amounts
  24. Receipts and verification
  25. Reports and monthly certificates
  26. Webhooks
  27. x402 top-ups
  28. Embedded components
  29. Authentication and permissions
  30. API reference
  31. Usage and estimates
  32. Evidence, checks and data connections
  33. Quotes, budgets and matches
  34. Automatic matching plans
  35. Receipts and verification
  36. Reports, monthly certificates and sharing
  37. Accounts, members and projects
  38. Webhook
  39. Support tickets
  40. Platform operations
  41. Console queries
  42. Sessions and service status
  43. Error codes
  44. TypeScript SDK
  45. Python example
  46. MCP tools
  47. Photosynth collection
  48. Configuration and testing
  49. Real-chain adapter
  50. Not yet implemented
  51. Real pilot
  52. Later stages
  53. Production operations

This document covers the sandbox’s current architecture, API and rules for v0.1. For features that have not been built, see the last section. For Arkreen’s existing certificate protocol, see AREC Protocol.

System architecture

TypeScript SDKPhotosynth pluginMCP serverWeb consoleREST APIAuth and rate limitsThree ledgers · PostgreSQLUsage ledgerDedupe, revise, estimateEntitlement ledgerSupply and allocationsFunds ledgerBalances, holds, logSettlementBatch and checkReceiptsSign and versionChain adapterSimulated chainPublic checksWeb, API, offline
This is a modular monolith. Application data and ledgers are in PostgreSQL. The chain is accessed through a separate adapter and is currently simulated.

There are six main steps:

  1. Receive usage, remove duplicates and estimate electricity.
  2. Create a quote for the electricity waiting to be matched.
  3. Check the budget and reserve funds and supply in one database transaction.
  4. Group allocations into batches by tenant, payer, beneficiary scope and source pool. Save each transaction before broadcasting it.
  5. Once there are enough confirmations, record the actual net amount on-chain.
  6. Issue a new version of each affected match’s receipt.
LedgerWhat it recordsConstraints
Usage ledgerEvents, metering units and estimatesEvents and estimates can only be added. The same underlying usage is recorded only once
Entitlement ledgerSupply, allocations and settlement batchesA batch’s active allocations cannot exceed its net retirement
Funds ledgerBalances and held fundsThe balance cannot be lower than the held amount

Every change to funds or supply is written to an append-only log, so current balances can be recalculated from it. Electricity and money are recorded separately and cannot stand in for each other.

CodeContents
src/modules/usage.ts, normalize.ts, estimate.tsUsage, normalization and estimates
src/modules/matching.tsQuotes, grants, idempotency and reservations
src/modules/plans.ts, sponsorships.ts, payments.tsAutomatic plans, sponsorships and x402 top-ups
src/modules/settlement.tsBatching, reconciliation, recovery and batch problems
src/modules/evidence.ts, wallets.tsReporter signatures, total checks, data connections, legacy records and wallet links
src/modules/reports.ts, statements.tsReports, monthly certificates and sharing
src/modules/accounts.ts, operations.ts, support.tsMembers and keys, platform operations and support tickets
src/modules/webhooks.tsNotifications, signatures, retries and URL checks
src/api-reference.ts, src/openapi.tsEndpoint list, OpenAPI and llms.txt
src/modules/receipts.ts, src/verify-package.tsReceipt issuance and verification
src/chain/types.tsChain adapter interface
src/chain/evm.tsReal-chain adapter, not connected to the running service
migrations/Database tables, constraints and append-only rules

Units and precision

All quantities are stored and calculated as integers. Floating-point numbers are not used.

1 μWhLedger unit1 mWhSmallest ART unit100 mWh1/10,000 kWh1 Wh1 kWh1,000 kWh1 ART
Energy scale: each major step is ten times the last
UnitUsed forConversion
μWh (uWh in the API)Usage, allocations and matches1 kWh = 1,000,000,000 μWh
mWh (milliwatt-hour)On-chain settlement1 mWh = 1,000 μWh, which is also the smallest unit of ART
ARTOn-chain token1 ART = 1,000 kWh
pUSDInternal amounts of money1 USD_TEST = 1,000,000,000,000 pUSD

The API always returns electricity in uWh, with the value as a string. Direct electricity data can be reported in uWh, mWh, Wh or kWh. Values more precise than 1 μWh are rejected, not rounded.

Prices are whole numbers of pUSD/μWh. The smallest possible price is 1 USD_TEST/MWh (megawatt-hour). The sandbox price is 5 pUSD/μWh, or 5 USD_TEST/MWh, and is fictional.

Report usage

This is a usage report with a request ID:

{
  "project_id": "prj_demo",
  "beneficiary_scope_id": "scope_demo",
  "source_id": "my-app",
  "external_event_id": "request-001",
  "provider_request_id": "request-001",
  "revision": 1,
  "event_type": "usage_snapshot",
  "accounting_role": "metering",
  "occurred_at": "2026-11-29T08:30:00Z",
  "evidence_level": "runtime_reported",
  "model": { "provider": "example", "id": "model-demo" },
  "usage_semantics": "openai_responses_v1",
  "usage": { "input_tokens": 1000, "output_tokens": 600 }
}

Provide at least one of usage and energy. If you provide usage, you must also provide usage_semantics. If you provide provider_request_id, you must also provide model.

The server stores only normalized token counts, not the provider’s raw usage data. Fields used as identifiers cannot contain control characters. Use tags to add up to 10 tags, such as a team or app, for grouping reports. Tag names can contain only lowercase letters, numbers and underscores. Values can have up to 100 characters. Do not put prompts, answers or personal information in IDs, tags or similar fields.

Deduplication

SDKRuntime reportGatewayProvider reportSDK retryIdentical contents1 metering unitrequest-001Metering source: gatewayHigher evidence level; differences markedIf equal: direct electricity, then the earliest
Reports are combined only if their tenant, provider and provider_request_id all match and each one is a cumulative snapshot. They cannot be combined without a shared ID.

When there is a provider_request_id, the system deduplicates by tenant, provider and request ID, and event_type must be usage_snapshot. Without one, it identifies events by project, source and event ID. usage_delta represents a separate increment of usage.

If several sources report the same request, the metering source is chosen in this order:

  1. A source whose reporter signature has been verified.
  2. The higher evidence level. From highest to lowest: metered, provider_reported, runtime_reported, self_reported.
  3. At the same level, a source with direct electricity data.
  4. If they are still equal, the source that reported first.

If the electricity estimates differ, the metering unit is marked to show this. Reporters declare their own evidence level, and the system does not verify it. A signature can only prove who provided the data and that it has not changed, not that the values are accurate.

A request can belong to only one project and beneficiary scope. Otherwise, scope_conflict is returned. The system does not deduplicate across tenants.

Revisions

  • Same revision, same contents: returns duplicate without recording it again.
  • Same revision, different contents: returns event_conflict.
  • Higher revision: replaces that source’s earlier data. An older revision cannot overwrite it, even if it arrives later.
  • A revision cannot change the request ID, provider or metering method. Otherwise, identity_changed is returned.

If electricity increases after a match, only the difference can be quoted again. If it decreases, existing allocations stay in place. Use accounting_role: "rollup" for a parent task’s total. Rollups are only recorded and are not included in metering, so usage is not counted twice.

Reporter signatures

Meters, gateways and providers can sign usage with Ed25519. First register the public key and link it to a source_id, then use attestUsage from the SDK. The server accepts only public keys. The private key must stay with the reporter.

The signed content is the prefix arec-usage/v1\n followed by the original request without attestation. The request is encoded as deterministic JSON with sorted keys, and its numbers must be integers. An invalid signature, the wrong source or a disabled public key returns invalid_attestation. The data is not accepted as unverified instead. Disabling a public key does not affect data already received.

Normalize tokens

usage_semanticsHow it is handled
normalized_disjoint_v1Uses token categories that do not overlap, with no changes
openai_responses_v1Cached tokens are part of the input, and reasoning tokens are part of the output, so they are separated first. Only the Responses API is supported
anthropic_messages_v1input_tokens does not include cache reads or writes. Thinking tokens are already included in output_tokens

When an Anthropic response includes usage.iterations, it may cover several runs, such as compaction or a change of model. The top-level usage alone is not enough:

  • The server adds up all the runs and does not add the top-level numbers again. If there is only one run and it matches the top level, the top-level numbers are used to keep the thinking details.
  • If more than one model was used, the SDK splits usage by model. Any part with no model listed, and no way to infer it, is recorded as unknown.
  • The server rejects data that has not been split and returns mixed_models.

Estimate electricity

Estimates follow these steps:

  1. If energy is provided, it is used directly. No token estimate is added, and it is not multiplied by PUE again.
  2. Otherwise, the system looks for an estimation method that has taken effect. A method for the specific model version comes first, followed by the version that took effect most recently.
  3. If there is no method for this usage, a fallback method is used only if the project allows it. Its basis is marked fallback.
  4. If no method applies, electricity is null and the basis is unsupported. It is never counted as zero.

There are two types of estimation method:

TypeHow it is calculated
token_coefficientsMultiplies each non-overlapping token category by its coefficient, then adds a fixed overhead
per_taskUses the total for the whole task directly, without adding tokens

Each version must explain its data source, energy boundary, applicable workloads, input definitions and uncertainty. Published versions cannot be changed, and a new version applies only to later estimates. POST /v1/projects/:id/reestimate handles only usage that could not be estimated before. It does not change existing estimates or receipts.

The sandbox has test coefficients only for example/model-demo:

Token categoryFictional coefficient (μWh / token)
Uncached input100
Cached input10
Cache write125
Visible output1,000
Reasoning output1,000

For example, 1,000 uncached input tokens and 600 output tokens come to 100,000 + 600,000 = 700,000 μWh.

Coverage is confirmed electricity divided by recorded electricity. Each metering unit counts for no more than 100%. match_ratio_bps is in basis points and is always rounded down:

statusMeaningmatch_ratio_bps
knownAll recorded usage can be estimated0 to 10,000
unknownAt least one usage item cannot be estimatednull
no_usageThere is no electricity to countnull

Coverage applies only to recorded usage. Purchase buffers do not count towards it. Where external registration is required, electricity counts only after registration is confirmed.

Compare with provider totals

A tenant can submit a provider’s token totals for a period and compare each category with recorded usage. The comparison is redone each time it is viewed, so data that arrives late is included.

source_completenessMeaning
not_verifiedThere is no total for exactly the same period, or at least one provider’s total is missing
provider_totals_matchTotals were provided for every recorded provider in this period, and all of them match
provider_totals_mismatchAt least one total does not match

The system does not verify bills. Matching totals do not prove that collection is complete, because providers and tools that are not connected are not compared. Queries by beneficiary scope always return not_verified.

Data connections and legacy records

Once you set a data connection’s normal reporting interval, its status becomes stale if no data arrives for too long. ok means only that data arrived recently, not that collection is complete.

Legacy Photosynth records can be imported as legacy_sample, but are not included in metering, matching or coverage. If a record has a wallet address, the wallet must first be linked with a signature. The text to sign is valid for 10 minutes. It can be used only once and cannot be used for another account. Linking a wallet does not send a transaction. Only standard wallets (EOAs) are currently supported.

The legacy endpoint /legacy/photosynth/offset returns only upgrade_required. It does not read or save any data. It never returns accepted, because the old plugin would take that to mean the offset had been accepted.

Quotes and budgets

A quote locks the metering units, estimate versions, electricity, source pool and price. It is valid for 10 minutes and can be used only once. It can include up to 500 usage events. A quote does not reserve supply. If usage or allocations have changed by the time it is accepted, quote_stale is returned.

Quote optionDefaultMeaning
target_ratio_bps10000Target coverage. 10000 means 100%. The rest can be matched later
buffer_bps0Extra amount to buy above the target. The grant must allow it
settlement_modebatchindependent creates a separate batch

A purchase buffer is shown separately on the receipt. It does not count towards the electricity target or coverage, and cannot make up for missed usage. Settlement fills the electricity target before the buffer. A grant’s max_buffer_bps is 0 by default, so buffers are not allowed unless this is changed.

charge is the total price. charge_breakdown lists energy attribute purchases, execution costs and software service fees separately. The last two are charged per match and are both 0 by default in the sandbox. These fees are held when a match is accepted and charged only after some electricity is confirmed. They are released if everything fails, and the charge is reversed after a chain reorganization. Fees also count towards budget limits.

Source pools have two modes:

modeRule
supportRenewable energy support, with no matching rule
attributeMatches energy attributes to electricity use under the same_year rule. The year of use must be the same as the generation year of every source in the pool (UTC)

The source cannot be chosen at retirement, so every source in the pool must meet the rule. This is checked again when supply is reserved, and settlement also checks the sources actually used. The sample data has only a support source pool. These rules are also fictional and do not show compliance with any market rules.

A match must use every ID in the quote’s usage_event_ids and include max_charge. The server checks that:

  • The grant belongs to the current key and has not been revoked or expired
  • The project, beneficiary scope and source pool match the quote
  • The limits per match, per day and per month are not exceeded
  • The purchase buffer is within the percentage allowed by the grant
  • The payer has enough funds and the source pool has enough supply. If a sponsorship is used, its limit must not be exceeded either
  • The quote is still valid and does not cost more than max_charge

Daily and monthly limits use UTC. Reserved, submitted and confirmed amounts all count towards the limits, but released amounts do not. The checks and reservation happen in one database transaction. Row locks prevent concurrent requests from overspending or overselling.

Sponsorships

When a sponsor creates a sponsorship, they receive a claim code that is shown only once. The recipient links it to a beneficiary scope when claiming it. The sponsor pays only if the recipient then chooses this sponsorship for a new grant or plan.

  • The sponsorship amount is a spending limit. Funds are not held in advance. Every match checks the remaining amount and the sponsor’s balance.
  • If the sponsor’s balance is too low, the match fails. It will not use the recipient’s money instead.
  • If different accounts pay for the same beneficiary scope, their matches go into different batches. Charges, and any reversals after a chain reorganization, are recorded in the account that actually paid.
  • Sponsors see only totals, not the recipient’s account, usage or receipts. Recipients can see the sponsor’s name and the remaining amount.
  • Revoking a sponsorship prevents new spending, but matches that have already been accepted will still be settled.

Idempotency and retries

App or agentAREC APILedgerPOST /v1/matches, key AReserve funds and supply (once)Response lostRetry same request, key AFind the earlier resultSame match, no second hold
By default, the SDK uses quote: plus the quote ID as the idempotency key. This stays the same if the process restarts before a retry.

Every match must include an Idempotency-Key with 8 to 200 characters.

  • Same key, request and idempotency key: returns the result from when the match was first accepted. This is a snapshot from that time, so check the latest status separately.
  • Same idempotency key, but a different request or API key: returns idempotency_conflict.
  • The request was not accepted: the idempotency key is not used up. After fixing the problem, you can retry with the same key.
  • The response is lost, followed by a 401, 403 or 429: this does not mean the earlier request failed. Fix the problem first, then retry with exactly the same arguments and idempotency key.

Automatic matching plans

A plan automatically matches new usage within its budget, without asking you to confirm each match. Each beneficiary scope can have only one plan that has not been cancelled.

Time rangeTime used and first receivedStable estimateAt least 5 minutesPrice and budgetPrice, limits, balance, supplyReserveCreate a matchWait for the next runidleNot eligible yetStop and give a reasonblockedOver a limit
Checking the budget, choosing usage, making the reservation and updating the plan all happen in one database transaction. If any part fails, everything is rolled back.

Each plan has its own budget grant and uses the same limit checks and row locks as manual matches. No key can use this grant, and it cannot be revoked separately. It can be disabled only by cancelling the plan.

{
  "project_id": "prj_demo",
  "beneficiary_scope_id": "scope_demo",
  "source_pool_id": "pool_sandbox",
  "include_existing": false,
  "interval_minutes": 60,
  "per_match_limit": { "currency": "USD_TEST", "value": "0.01" },
  "daily_limit": { "currency": "USD_TEST", "value": "0.1" },
  "monthly_limit": { "currency": "USD_TEST", "value": "0.5" },
  "max_price_per_kwh": { "currency": "USD_TEST", "value": "0.005" },
  "expires_at": "2026-12-29T00:00:00Z"
}

You can also set target_ratio_bps, buffer_bps, settlement_mode, on_limit and sponsorship_id. The first three work the same way as the quote options. When you edit a plan, any options you leave out stay the same. sponsorship_id cannot be changed after the plan is created.

The interval can be 1 to 1,440 minutes, and a plan can last up to 366 days. The maximum unit price is converted to a whole number of pUSD/μWh and rounded down.

What gets matched

  • Time range: By default, only usage after the plan was created is matched. Both the time of use and the time the server first received it must be no earlier than the plan’s creation. Reporters provide the time of use. If only that time were checked, a fast clock could cause earlier usage to be charged. When include_existing is true, earlier unmatched usage is also included.
  • Stable estimates: The current estimate must stay the same for at least 5 minutes before it is matched. Changing the metering source restarts this wait. This reduces, but cannot fully prevent, buying too much if usage is revised down.
  • Usage that can be estimated: Usage with no applicable estimation method is skipped.
  • Source rules: If the year of use does not meet the source pool’s rule, the usage is skipped and a reason is given.

Older usage is handled first, with up to 500 items at a time. A large item that does not fit is skipped for now, so it does not block smaller items after it. A single item is never split. If it costs more than the limit per match, raise the limit or match it manually.

Run results

last_outcomeMeaning
matchedAll eligible usage was accepted. This does not mean settlement is complete
partialOnly some usage was accepted. See last_reason
idleThere was no eligible usage. This includes usage whose estimate is not stable yet
blockedA restriction prevented any matches. See last_reason
errorAn error occurred. Everything was rolled back, and the plan will try again after 1 minute

last_reason can be per_match_limit, daily_limit, monthly_limit, insufficient_funds, insufficient_inventory, price_too_high, sponsorship_limit, sponsorship_unavailable, source_not_applicable, grant_expired, more_pending or internal_error. more_pending means the item limit for one run was reached. The background worker will continue as soon as possible. If the budget, balance or supply is the limit, the plan waits until its next interval.

If more than one limit applies, only the one with the least remaining at that time is returned. After you resolve it, another limit may still apply.

Strict mode

By default, plans do not affect AI tasks (on_limit is continue). For stricter control, set it to block and check GET /v1/coverage-decision before each new task. It returns decision: "block" and a reason if the plan is paused, has expired, is more than 5 minutes late to run or cannot match normally.

The service only gives a recommendation. It does not block tasks. The integration decides what to do if the check fails. continue also means only that the plan has been running normally, not that the new task has been matched.

Edit or stop a plan

  • Edit: This updates the existing grant, so the amounts already used today and this month are not reset. The plan runs as soon as possible after it is saved. A paused plan stays paused.
  • Pause or cancel: If the plan is running, that run finishes first. Once the request succeeds, there will be no new matches. Matches that have already been accepted continue.
  • Resume: The plan runs as soon as possible and also matches usage from while it was paused.
  • Cancel: This cannot be undone. You can create a new plan, but its limits start again and do not include the old plan’s spending.
  • Run soon: run only asks the background worker to run the plan. It does not wait for matching to finish.

Plans and manual matches can be used together. The same unmatched electricity will not be reserved twice. Their limits are separate, so total spending can be as high as all the grants combined.

Settlement and recovery

Match statuses

reservedReservedsubmittedAwaiting confirmationconfirmedCompleteAdd to batchRemainder, gap or revertEnough confirmationsreconciliation_requiredNeeds reconciliationUnclear or source mismatchContinue once checked (not mismatches)ReorganizationfailedNot completed; releasedReverted 3 times in a rowIf partly confirmed: partially_confirmed
This shows the main paths. A match can have several allocations. Its status combines all of them and their batches.

The status combines all allocations and their batches. If any batch needs reconciliation, the match is reconciliation_required. Otherwise, if any allocation is still being settled, it is submitted.

Batch statuses

preparedTransaction savedsubmittedBroadcastconfirmed≥ 2 confirmationsfinalized≥ 12 confirmationsReorganization: checked again via reconciliation_requiredreconciliation_requiredUnclear or reorganizedUnclear resultRebroadcastfailedNothing is retiredRevertedsource_mismatchNeeds reconciliation; automation stopsSource mismatch
Each transaction is saved before it is broadcast. If the result is unclear, only the same transaction is rebroadcast. A new one is created only after the batch has definitely failed.

Allocations are grouped into batches by tenant, payer, beneficiary scope and source pool. Matches set to independent get their own batch. By default, settlement happens as soon as possible. A project can also have a maximum wait and an optional amount; settlement starts when either is reached. This setting does not affect separate settlement or period close. Every stage is saved to the database first, and a database lock allows only one settlement job to run at a time.

  • Create a batch: Only full units of 1 mWh are settled. Any remainder waits for the next batch. The batch must also reach the minimum net retirement amount on-chain.
  • Save, then broadcast: The nonce, raw transaction and hash are saved before broadcasting. If the result is unclear, the system only looks up or rebroadcasts the same transaction.
  • Enough confirmations: Amounts are posted after 2 confirmations. After 12, they are considered final and are no longer checked for reorganizations.
  • Reorganization: Before 12 confirmations, if the transaction disappears or its block changes, the posting is reversed and the funds are put back on hold. The system then keeps checking the original transaction.
  • Reverted transaction: A retry happens only after 12 confirmations. If the same allocation is reverted 3 times in a row, its funds and supply are released. Retrying too soon could retire it twice after a reorganization.
  • Source mismatch: The actual amount is deducted from supply. Completion claims and automatic processing stop, and a platform operator handles the batch. Until then, the related funds and reservations are kept.

To handle a source mismatch, an operator can release the reservation. They can also queue it again, which retires another batch. The original batch becomes closed. The amount already retired stays on record as retired but unallocated, and cannot be sold again. Batches that are still being checked automatically cannot be handled manually, because they could be retired twice.

123456789101112ConfirmedFinal
These are sandbox settings. They must be decided again before connecting to a real chain.

External registries

Some source pools also require registration in an external registry. The registration status is kept separately from the on-chain status: not_applicable, pending, confirmed or failed. An operator can enter the registration result only after the batch is final. A failed registration can later be changed to confirmed. Once confirmed, it cannot be changed.

If a match is confirmed on-chain but its registration is not, its status may be confirmed while its claim_status is still pending. To check whether it is complete, make sure claim_status is sandbox_complete.

Fees and net amounts

Gross 101 mWhNet retirement 100 mWhFee 1 mWh
Drawn to scale. The example fee is 1%, rounded down. Receipts use only the actual net amount on-chain.
fee = floor(gross × fee rate)
net = gross - fee

When creating a batch, the gross amount is calculated as follows:

gross = floor(target net × 10,000 ÷ (10,000 - fee rate))

The fee rate in this formula is in basis points. When the existing ART contract uses only one source, it calculates the fee again after taking the net amount. The actual charge can therefore be higher than the gross amount submitted. For example, with a 1% fee rate and a net amount of 198, submitting 199 results in a charge of 200. With this formula, the charge equals the submitted gross amount whether one or several sources are used. If the fee rate changes after submission, the actual on-chain charge is still recorded.

Only the actual net amount on-chain is posted:

  • If the net amount is too low, the difference goes back to being reserved and waits for the next batch.
  • At period close, a remainder of less than 1 mWh can be rounded up. The added amount is reserved first. After confirmation, it is recorded separately as an unallocated remainder.

Receipts and verification

Each receipt has append-only versions. A new version is issued when its contents change. Receipts use Ed25519 to sign the fixed prefix arec-receipt/v1\n together with the original receipt. This prevents the signature from being used for another type of content.

Public receipts do not include the tenant, project, beneficiary scope, amounts of money or exact times. The payer and beneficiary scope are shown as salted SHA-256 hashes. Only the tenant that owns the receipt can get the salt and check them. Private receipts also list the payer, beneficiary, user, executor and sponsor.

A receipt shows whether a sponsor paid, how many usage items have a verified reporter signature and the external registration status. If the target is less than the estimated electricity, it says that not all of this usage was matched.

The public verification endpoint POST /v1/verify accepts a receipt ID or a receipt package:

{ "receipt_id": "rct_..." }
CheckWhat it checksOffline
signatureThe contents match the signature and key IDYes
batch_manifestThe manifest hash, allocations, duplicates and totals are correctYes
latest_versionWhether this is the latest versionNo
retirement_on_chainThe retirement ID, net amount and sources match the on-chain recordNo
allocation_uniqueThe allocation and batch totals match the platform ledgerNo
matching_rulesame_year source pools check the years of use and generation; support returns not_applicableNo

If the signature is invalid, the rest of the receipt is neither checked nor trusted. If there is no confirmed settlement, some checks return not_applicable. No failed checks does not mean the match is complete. You must also make sure claim_status is sandbox_complete.

The public key used for offline verification must come from a trusted source outside the receipt package. Verification cannot prove that the electricity estimate is accurate. Whether an allocation is unique still depends on the platform ledger.

Reports and monthly certificates

GET /v1/reports uses UTC months. Data can be grouped by model, task, beneficiary scope, source or tag. Three types of data use different times:

DataTime used
Usage and coverageTime of use
SpendingWhen it was posted to the ledger, including reversals after a chain reorganization
Matches and purchase buffersWhen the match was created

Spending is split between your own payments and those made by sponsors, with the three types of cost shown separately. Held funds do not count as spending. Viewing amounts of money also requires billing:read. Reports can be exported as CSV, with protection against spreadsheet apps running content as formulas.

Monthly certificates can be issued only after the month ends. They can cover the whole project or one beneficiary scope. If late data arrives, issuing a certificate again creates a new version and leaves earlier versions unchanged. If nothing has changed, it is not issued again. Certificates are signed with a different fixed prefix, arec-statement/v1\n, so their signatures cannot be used for receipts or the other way around.

Monthly certificates are private by default. Users can choose to share a monthly certificate or their total support, set an expiry date and revoke the share at any time. Public content does not include accounts, projects, beneficiary scopes, amounts of money or receipt lists. The receipt list appears only as a hash. Revoking a share cannot take back anything others have already saved.

Webhooks

Notifications are saved in the same database transaction as the changes that cause them, then sent by a background worker. Each one is sent at least once. It may be sent more than once or arrive out of order, so use the notification ID to remove duplicates.

TypeWhen it is sent
receipt.updatedA receipt has a new version, including when a match is first accepted
plan.attentionA plan has a problem, its reason changes or it expires
plan.recoveredA plan is working normally again
statement.issuedA new version of a monthly certificate is issued
webhook.testA test notification is sent manually. You do not need to subscribe to it

Requests include these headers:

arec-webhook-id: evt_...
arec-webhook-timestamp: 1795939200
arec-webhook-signature: v1=<hex signature>

The signature uses HMAC-SHA256 over <notification ID>.<timestamp>.<raw body>. Use the full text of the secret, including whsec_ at the start. For 24 hours after the secret is rotated, the signature header has two signatures separated by a space. Both TypeScript and Python have functions to check them. Always check the raw body. Do not parse and serialize it again first.

  • A delivery succeeds only if it gets a 2xx response within 10 seconds. Redirects are not followed, and the response body is not saved.
  • After each failure, the wait is 10 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and then 12 hours. If every attempt fails, delivery stops. You can replay it manually with the same notification ID.
  • URLs must use HTTPS on the public internet. Each delivery checks every address the domain resolves to and connects only to a checked address. This prevents access to private networks.
  • For local debugging, set WEBHOOK_ALLOW_LOCAL=true. This allows only local addresses. Do not use it in production.

x402 top-ups

The sandbox uses the exact scheme from x402 v2 (EIP-3009) to top up test currency. The key needs the payment:write permission:

  1. Create an order with POST /v1/payment-orders. It is valid for 15 minutes.
  2. Call POST /v1/payment-orders/:id/pay and get the payment requirements from PAYMENT-REQUIRED in the 402 response.
  3. Sign with a test wallet, put the payment proof in PAYMENT-SIGNATURE and send the request again.
  4. A 200 response means the top-up has been posted. The result is in PAYMENT-RESPONSE.

The chain ID and token address are fictional. The signature is tied to them and cannot be used with real tokens. Even so, do not use a real wallet’s private key.

The service saves the payment proof before requesting settlement. A 202 response means the result is still unclear, so retry only with the same payment proof. The background worker also keeps processing it. Once the charge is confirmed, the top-up is posted even if the order has expired. Each authorization can be used for only one order. An operator can refund an unused top-up. A real payment would also need to be refunded separately through the payment provider.

Embedded components

<script src="http://127.0.0.1:4310/embed/v1.js" defer></script>
<arec-badge receipt="rct_..."></arec-badge>
<arec-receipt receipt="rct_..."></arec-receipt>
<arec-monthly-card share="shr_..." lang="en"></arec-monthly-card>
ComponentWhat it shows
arec-badgeA receipt status badge that opens the receipt details when clicked
arec-receiptA receipt card
arec-monthly-cardA monthly certificate or total support. You must create a share first

Components read only public data and do not send cookies. Do not put an API key on the page. A receipt is shown as complete only if no checks have failed and its claim_status is sandbox_complete. Receipts that are not complete refresh regularly. Content is not parsed as HTML, so components also work on pages that restrict inline styles. The page’s CSP must allow scripts to be loaded, and data to be read, from the service’s address.

Authentication and permissions

Server-side programs use Bearer keys. The database stores only a SHA-256 hash of each key:

Authorization: Bearer <api-key>

The console exchanges a key for an 8-hour session. Its cookie uses HttpOnly and SameSite=Strict, and the database stores only the token’s hash. Signing in, signing out and writing data through a session also check the Origin, Host and X-Arec-Console request headers.

  • A session has the same permissions as the key used to sign in. Revoking the key ends the session immediately.
  • If a request includes Authorization, its cookie is not used, even if the key is invalid.
  • When using HTTPS, you must set SECURE_COOKIE=true. This adds Secure and the __Host- prefix to the cookie.
  • Projects, matches and private receipts that belong to another tenant are treated as “not found”.

Organization accounts can add members. Personal accounts have only one owner. A member key’s permissions come from its role. Permissions for app and agent keys are chosen separately, and these keys can also have an expiry date.

RolePermissions
ownerFull access to the account, including managing members and keys
adminEverything except managing members and keys
financeView reports and manage budgets, billing and top-ups
developerView reports and manage usage, projects and webhooks
viewerView reports and receipts only
  • You cannot grant permissions you do not have, or rotate the key of a member with more permissions than you.
  • Changing a role, disabling a member or revoking a key takes effect immediately. The system always keeps at least one key that can manage members and does not expire.
  • The key itself is returned only once, when it is created. Changes to accounts, budgets, plans and settings are written to an append-only audit log, which never includes the keys themselves.
  • ops:read and ops:write work only for platform accounts. Keys from other accounts cannot use operations endpoints, even if they list these permissions.

Public and sign-in endpoints are rate-limited by IP address: 60 requests per minute for public receipts and verification, 10 for signing in and 20 for claiming sponsorships. Real IP addresses behind a reverse proxy are not supported yet. A proxy must also pass Host through unchanged.

API reference

The local address is http://127.0.0.1:4310. Requests and responses usually use JSON. Web pages, CSV files, the embed script and llms.txt are exceptions. The machine-readable API reference is at /openapi.json, and instructions for agents are at /llms.txt. A request body can be up to 2 MiB. Endpoints with “–” in the permission column do not require a specific permission, but GET /v1/session still requires authentication.

Usage and estimates

EndpointPermissionPurpose
POST/v1/usage-eventsusage:writeReport one usage event
POST/v1/usage-events/batchusage:writeReport up to 100 events; returns a result for each one
POST/v1/estimatesestimate:readEstimate electricity without recording usage
GET/v1/methodologiesreadList available estimation methods
GET/v1/pending-usagequote:readList unmatched usage
GET/v1/coveragereport:readView coverage of recorded usage

Evidence, checks and data connections

EndpointPermissionPurpose
GET/v1/reporter-keysproject:adminList reporter public keys
POST/v1/reporter-keysproject:adminRegister a reporter’s Ed25519 public key
POST/v1/reporter-keys/:id/revokeproject:adminDisable a public key; data already received is not affected
GET/v1/usage-totalsreport:readView provider totals and compare them with current usage
POST/v1/usage-totalsproject:adminSubmit provider totals to check against usage
GET/v1/connectionsreport:readCheck whether data connections are receiving data on time
POST/v1/connectionsproject:adminAdd a data connection
POST/v1/connections/:id/removeproject:adminRemove a connection; existing data is not affected
GET/v1/legacy-recordsreport:readList legacy Photosynth records
POST/legacy/photosynth/register–Legacy Photosynth registration; no longer in use
POST/legacy/photosynth/offset–Legacy reporting; saves no data and only asks for an upgrade
GET/legacy/photosynth/status–Legacy status; always returns no records
POST/v1/legacy-recordsproject:adminImport legacy records; not included in metering or matching

Quotes, budgets and matches

EndpointPermissionPurpose
GET/v1/source-poolsreadView source pools, prices and available supply
POST/v1/quotesquote:readGet a quote without reserving supply
POST/v1/matchesmatch:writeUse a grant to accept a quote; requires Idempotency-Key
GET/v1/matches/:idreadView a match
GET/v1/budget-grantsreadList active grants for the current key
POST/v1/budget-grantsbudget:adminCreate a grant
POST/v1/budget-grants/:id/revokebudget:adminRevoke a grant; safe to call more than once
GET/v1/balancesbilling:readView the status of funds and electricity
GET/v1/payment-ordersbilling:readView payment orders
POST/v1/payment-orderspayment:writeCreate a top-up order; pay within 15 minutes
GET/v1/payment-orders/:idpayment:writeView payment orders
POST/v1/payment-orders/:id/paypayment:writePay with x402 v2 (sandbox)
GET/v1/sponsorshipsbilling:readView sponsorships you offered or claimed
POST/v1/sponsorshipsbudget:adminCreate a sponsorship; the claim code is returned only once
POST/v1/sponsorships/redeembudget:adminClaim a sponsorship and link it to a beneficiary scope
POST/v1/sponsorships/:id/revokebudget:adminRevoke a sponsorship you offered

Automatic matching plans

EndpointPermissionPurpose
GET/v1/coverage-plansreport:readView plans, budgets and run results
POST/v1/coverage-plansbudget:adminCreate a plan; it will then spend automatically
PATCH/v1/coverage-plans/:idbudget:adminEdit settings; amounts already used are not reset
POST/v1/coverage-plans/:id/actionsbudget:adminPause, resume, run soon or cancel
GET/v1/coverage-decisionreadCheck whether a new AI task is recommended to continue

Receipts and verification

EndpointPermissionPurpose
GET/v1/receipts/:idreceipt:readView a receipt owned by your tenant
GET/v1/public/receipts/:id/package–Download a public receipt package
GET/v1/public/receipts/:id/summary–View a public receipt summary for embedded components
GET/v1/keys–View public signing keys
POST/v1/verify–Verify a receipt ID or package
GET/r/:id–Open a public receipt page

Reports, monthly certificates and sharing

EndpointPermissionPurpose
GET/v1/reportsreport:readView or export a monthly report; amounts of money also require billing:read
GET/v1/statementsreport:readList monthly certificates
POST/v1/statementsreport:readIssue or update a certificate for a month that has ended
GET/v1/statements/:idreport:readView a monthly certificate and its receipt list
GET/v1/sharesshare:adminList shares
POST/v1/sharesshare:adminCreate a public share
POST/v1/shares/:id/revokeshare:adminRevoke a share; takes effect immediately
GET/v1/public/shares/:id–View a public share
GET/s/:id–Open a public share page

Accounts, members and projects

EndpointPermissionPurpose
GET/v1/membersmembers:adminView members and the permissions for each role
POST/v1/membersmembers:adminAdd a member; the key is returned only once
PATCH/v1/members/:idmembers:adminChange a role; takes effect immediately
POST/v1/members/:id/disablemembers:adminDisable a member and revoke their key
POST/v1/members/:id/rotate-keymembers:adminRotate a key; the old key stops working immediately
POST/v1/api-keysmembers:adminCreate a key for an app or agent; returned only once
POST/v1/api-keys/:id/revokemembers:adminRevoke a key
POST/v1/projectsproject:adminCreate a project
GET/v1/projects/:id/settingsreport:readView project settings
POST/v1/projects/:id/settlement-policybudget:adminSet the settlement amount and maximum wait
POST/v1/projects/:id/fallbackproject:adminSet whether fallback estimates are allowed
POST/v1/projects/:id/reestimateproject:adminRe-estimate usage that could not be estimated before
GET/v1/beneficiary-scopesreport:readList beneficiary scopes
POST/v1/projects/:id/beneficiary-scopesproject:adminCreate a beneficiary scope; use external_ref to avoid duplicates
GET/v1/wallet-linksproject:adminList linked wallets
POST/v1/wallet-links/challengesproject:adminGet the text to sign when linking a wallet
POST/v1/wallet-linksproject:adminProve control with a signature and link a wallet; no transaction is sent
POST/v1/wallet-links/:id/removeproject:adminUnlink a wallet
GET/v1/audit-logmembers:adminView the audit log

Webhook

EndpointPermissionPurpose
GET/v1/webhook-endpointswebhook:adminList webhook URLs
POST/v1/webhook-endpointswebhook:adminAdd a URL; the signing secret is returned only once
POST/v1/webhook-endpoints/:id/rotate-secretwebhook:adminRotate the signing secret; the old one is still used to sign for 24 hours
POST/v1/webhook-endpoints/:id/testwebhook:adminSend a test notification
POST/v1/webhook-endpoints/:id/disablewebhook:adminDisable a URL
GET/v1/webhook-deliverieswebhook:adminView deliveries
POST/v1/webhook-deliveries/:id/replaywebhook:adminReplay a notification with the same ID

Support tickets

EndpointPermissionPurpose
GET/v1/support-ticketsreadList tickets
POST/v1/support-ticketsreadOpen a ticket
GET/v1/support-tickets/:idreadView a ticket and its replies
POST/v1/support-tickets/:id/messagesreadReply to or close a ticket

Platform operations

EndpointPermissionPurpose
GET/v1/ops/overviewops:readSource pools, supply and open issues
GET/v1/ops/reconciliationops:readCheck the ledgers and on-chain records without changing data
GET/v1/ops/batchesops:readView batches for all accounts
POST/v1/ops/batches/:id/resolveops:writeHandle a batch with source problems
POST/v1/ops/batches/:id/external-statusops:writeEnter an external registration result
GET/v1/ops/methodologiesops:readView all estimation methods
POST/v1/ops/methodologiesops:writePublish a new version of an estimation method
POST/v1/ops/source-pools/:id/priceops:writeChange a source pool’s price; affects only new quotes
GET/v1/ops/tenantsops:readView accounts and balances
POST/v1/ops/tenantsops:writeCreate a personal or organization account
POST/v1/ops/tenants/:id/feesops:writeSet the fees charged per match
POST/v1/ops/tenants/:id/top-upsops:writeTop up test currency; each ID is posted only once
POST/v1/ops/payment-orders/:id/refundops:writeRefund an unused top-up
GET/v1/ops/audit-logops:readView the operations activity log
GET/v1/ops/support-ticketsops:readView all tickets
GET/v1/ops/support-tickets/:idops:readView one ticket
POST/v1/ops/support-tickets/:id/messagesops:writeReply to or close a ticket

Console queries

EndpointPermissionPurpose
GET/v1/overviewreport:readOverview
GET/v1/usage-unitsreport:readDeduplicated usage details
GET/v1/usage-sourcesreport:readData sources
GET/v1/matchesreport:readList of matches
GET/v1/retirement-batchesreport:readSettlement batches
GET/v1/fund-entriesbilling:readFunds activity
GET/v1/admin/budget-grantsbudget:adminAll grants for the tenant
GET/v1/admin/api-keysbudget:adminList of keys, without the keys themselves

Sessions and service status

EndpointPermissionPurpose
POST/v1/session–Sign in to the console with an access key
GET/v1/session–View the current key or session; requires authentication
DELETE/v1/session–Sign out
POST/v1/sandbox/settlesandbox:adminRun settlement manually; sandbox only
GET/healthz–Check the service and its environment
GET/openapi.json–Download the OpenAPI document
GET/llms.txt–View instructions for agents
GET/embed/v1.js–Load the embedded components

Lists use cursor pagination. limit is 25 by default and can be up to 100. Use next_cursor from the response as the cursor for the next request. null means there is no more data. GET /v1/pending-usage does not use a cursor. Its limit is 100 by default and can be up to 500, and truncated means there is more usage that is not listed.

Error codes

Error responses look like this. The message in this example is in Chinese and means “The quote has expired”. Use code to handle errors. Do not rely on the text of message:

{
  "error": {
    "code": "quote_expired",
    "message": "报价已过期"
  }
}
HTTPCodeCause or what to do
400invalid_requestThe request format is invalid. Use issues to fix it
400invalid_paymentThe payment proof format is invalid
400invalid_cursorThe pagination value is invalid. Start again from the first page
401unauthorizedThe key is missing or invalid
401session_expiredYour console session has expired. Sign in again
402payment_requiredPay as described in the PAYMENT-REQUIRED response header. See details.reason for the cause
403wallet_not_linkedLink the wallet in the legacy record first
403forbiddenThe key does not have the required permission
403bad_originA console write request has an invalid origin or header
403grant_not_yoursThe grant does not belong to the current key
403grant_revokedThe grant has been revoked. Contact the account owner
403grant_expiredThe grant has expired. Contact the account owner
403grant_scope_mismatchThe grant does not cover this project, beneficiary scope or source pool
403budget_exceededThe limit per match, per day or per month has been exceeded. Contact the account owner
403buffer_not_allowedThe purchase buffer is higher than the grant allows
403sponsorship_unavailableThe sponsorship has been revoked, has expired or does not apply to this beneficiary scope
403scope_escalationYou cannot grant permissions you do not have
404not_foundIt does not exist or does not belong to the current tenant
404sponsorship_code_invalidThe claim code is invalid, has expired or has already been used
409event_conflictThe contents differ for the same revision. Increase revision when you make a change
409identity_changedA revision cannot change the request identifiers, provider or metering method
409scope_conflictThe usage already belongs to another project or beneficiary scope
409nothing_to_matchThere is no electricity left to match
409quote_usedThe quote has already been used. Get a new one
409quote_expiredThe quote has expired. Get a new one
409quote_mismatchThe usage events do not match the quote
409quote_staleUsage has changed since the quote. Get a new one
409max_charge_exceededThe quote is higher than max_charge
409insufficient_fundsThe account balance is too low
409insufficient_inventoryThe source pool does not have enough supply
409idempotency_conflictThe request differs for the same idempotency key
409plan_existsThe beneficiary scope already has an automatic plan. Edit or cancel that plan
409plan_not_activeThe plan is paused or has expired and cannot run
409plan_cancelledThe plan has been cancelled and cannot be edited. Create a new one
409scope_existsThe ID is already used for another type of beneficiary scope
409member_disabledThe member has been disabled
409last_managerKeep at least one key that can manage members and does not expire
409personal_accountMembers cannot be added to a personal account
409webhook_disabledThe webhook URL has been disabled. Create a new one
409too_many_endpointsYou have reached the webhook URL limit. Disable one you no longer use
409period_openThis month has not ended
409connection_existsThis source has already been added
409legacy_conflictA legacy record with the same ID has different contents
409methodology_existsThis version has already been published. Use a new version number
409batch_not_resolvableThe batch does not need manual handling or is still being checked automatically
409external_status_lockedAn external registration result cannot be entered for this batch yet, or registration is already confirmed
409order_expiredThe payment order has expired. Create a new one
409order_closedThe payment order has been refunded. Create a new one
409order_not_refundableOnly orders that have been posted can be refunded
409payment_in_progressThe previous payment has no result yet. Retry only that payment
409payment_reusedThe payment authorization has already been used for another order
409payment_failedThe payment did not succeed. Get the payment requirements again
409wallet_linkedThe wallet is linked to another account. Unlink it there first
409top_up_conflictThis ID has already been used for another top-up
413report_too_largeThere is too much data. Export each beneficiary scope separately
422invalid_limitsLimits must be greater than 0, with per match ≤ daily ≤ monthly
422invalid_expiryThe expiry must be in the future. Grants, plans, keys and sponsorships can last up to 366 days
422invalid_usageusage does not match usage_semantics
422mixed_modelsMore than one model was used. Split the usage by model, then report it
422not_meteredRollup events cannot be matched
422evidence_insufficientThere is no applicable estimation method
422invalid_energyThe electricity value has an invalid format, precision or range
422invalid_moneyThe amount of money has an invalid format or range
422source_not_applicableThe year of use does not match the source’s generation year
422invalid_attestationThe reporter signature is invalid, or the public key does not apply to this source
422invalid_wallet_signatureGet new text to sign. Each text can be used only once
422invalid_public_keyProvide an Ed25519 public key in PEM format. Never submit a private key
422invalid_webhook_urlOnly HTTPS URLs on the public internet are supported
422invalid_effective_fromA method cannot take effect in the past
410legacy_closedLegacy Photosynth registration is no longer available. Use the new plugin
500internal_errorAn internal error occurred. Requests that support idempotency can be retried without changes

Going over a rate limit returns HTTP 429. Errors handled by the framework, such as rate limits and oversized request bodies, all use the code request_error. Check the HTTP status code to tell them apart.

Batch reports return a result for each item. If an item returns internal_error, retry that item without changing it. Other errors must be fixed first.

TypeScript SDK

The SDK has no runtime dependencies and requires Node.js 22.12 or later. It can currently be used only inside the repository. Keep keys on the server and never use them in a browser.

FeatureMethods
Account and environmentgetSession, getEnvironment
Usage and estimatesreportUsage, reportUsageBatch, estimate, listMethodologies, listPendingUsage
Strict modegetCoverageDecision
Quotes and matcheslistSourcePools, listGrants, getBalances, createQuote, match, getMatch, waitForMatch
ReceiptsgetReceipt, verifyReceipt
Convert usagefromAnthropicMessage, fromOpenAIResponse
SignaturesattestUsage, verifyWebhook
Local queueenqueue and flush on UsageOutbox
  • All requests except createQuote are retried up to 2 times by default after a network error, timeout, 408, 429 or 5xx. If the server returns Retry-After, the SDK waits for that long. If the wait is more than 30 seconds, it returns the error right away.
  • By default, match uses the quote ID to create its idempotency key. After a restart, retrying with the same arguments will not charge you twice.
  • When an error’s outcomeUnknown is true, the request may have been processed. Even if the last response was a 401, do not get a new quote or change the idempotency key. Fix the problem first, then retry with the same arguments.
  • waitForMatch returning does not mean the match succeeded. Check claim_status to see whether it is complete.
  • Except on your local computer, only HTTPS is allowed. The SDK does not follow redirects, so keys are not sent to another address.
  • Report every event returned by the conversion functions. Missing even one means usage is undercounted. For a streamed response, pass in the final result.

UsageOutbox saves each event as a file. enqueue returns only after the event is written to the local disk, and flush then sends it. Several processes can share a folder on the same computer, and the server removes any duplicates. Events that are clearly rejected are moved to rejected/, which you should check regularly. See Quick Start for a full example.

Python example

examples/python/arec_ai.py is a single-file client that uses only the standard library. It supports Python 3.10 or later and has been tested with 3.11, 3.12 and 3.13. It supports usage, quotes, matches, receipts and webhook signature checks. It does not have a persistent local queue, so save events yourself before reporting them. See examples/python/README.md for instructions.

MCP tools

The MCP server runs locally over stdio. It supports the 2026-07-28 protocol and is also compatible with the 2025 protocol versions.

ToolWhat it doesSpends money
arec_get_statusView balances, grants, unmatched usage and plan statusNo
arec_estimateEstimate electricity without recording usageNo
arec_quoteGet a quote without reserving supplyNo
arec_matchUse an existing grant to accept a quoteYes
arec_get_receiptLook up and verify a receiptNo
arec_verify_receiptVerify a receiptNo

Once the arguments pass validation, every tool returns the same structure:

FieldMeaning
okWhether the tool call succeeded, not whether settlement is complete
environmentCurrently always sandbox
settlement_completetrue only if the completion claim is valid and no checks have failed. It stays false if the match is confirmed on-chain but external registration is not complete. null means settlement does not apply
next_actionnone, request_quote, match_quote, check_receipt, retry_same_arguments, fix_arguments or ask_owner
data / errorThe data if the call succeeds, or the error code if it fails

When error.outcome_unknown is true, the request may have been processed. Retry only with exactly the same arguments. Do not get a new quote.

MCP has no tools to create grants, raise budgets, top up, transfer money or call arbitrary contracts. ask_owner and the destructive label on arec_match are only hints. The server enforces the actual budget limits.

Photosynth collection

The Photosynth sandbox plugin reads local session records from Claude Code and Codex CLI, then reports usage through UsageOutbox. The hook only starts a background sync and does not wait for the network.

ClientMetering sourceDeduplicated by
Claude Codemessage.usage in assistant records, including iterationsmessage.id
Codex CLItoken_usage_record, including usage from compactionresponse_id
  • Usage is not lost if collection is interrupted: The reading position is saved only after events are added to the queue. Scanning again creates the same events.
  • Usage can be updated: The revision is the total number of tokens plus 1, so an increase in usage replaces the earlier data.
  • Codex totals are not counted as usage: token_count may repeat and does not include compaction. If an older version of Codex has no record for each request, the plugin warns that usage was missed.
  • Collection by project: Usage is collected only if it is allowed both by the rules when the response was created and by the current rules. If the folder cannot be identified, the usage is not collected. Paths are not reported.
  • Sandbox only: The plugin will not send data to other environments. It also rejects keys with spending or admin permissions.

Session records use the clients’ internal formats, which may change. If a record type is renamed, the plugin may miss usage. It may warn you if it has not collected any usage for more than a day, but this is not guaranteed.

The plugin does not support Kimi. Records from kimi-cli have no stable response ID, and providers count tokens differently. They cannot be reliably deduplicated or converted into separate token categories.

Configuration and testing

Environment variableDefaultPurpose
DATABASE_URLpostgres://arec@127.0.0.1:54329/arec_sandboxApplication database
TEST_DATABASE_URLpostgres://arec@127.0.0.1:54329/postgresUsed to create and delete test databases
HOST127.0.0.1Address to listen on
PORT4310Server port
WORKER_INTERVAL_MS2000Wait between background settlement runs
WEBHOOK_ALLOW_LOCALfalseAllows webhooks to be sent to local addresses. Use only for local debugging
SECURE_COOKIEfalseMust be true when using HTTPS

The server does not read .env files automatically, so set environment variables before you start it. New database migrations are applied automatically at startup. Do not edit a migration that has already been applied. Add a new file for any changes.

pnpm typecheck
pnpm test

Each database test creates its own arec_test_* database and deletes it at the end. Tests also recalculate balances from the logs to check that the ledgers agree.

Real-chain adapter

src/chain/evm.ts is based on a fixed version of the ArkreenCore source code. It is not connected to the service. It does not read private keys or environment variables, and has no default contract addresses. Its tests use simulated RPC calls. They show only that it handles data as the source code does, not that a live deployment behaves the same way.

It calls offsetAndMintCertificate and writes the batch ID to the certificate. Before signing, it checks the chain, nonce, fees and contract arguments. After broadcasting, it reads the actual net amount and sources from on-chain logs and state. If anything does not agree, it stops and does not treat the transaction as successful.

Before it is enabled, at least these issues must be resolved:

  • Beneficiary: The current interface has no beneficiary field, so each adapter can serve only one beneficiary. The certificate owner can still edit its details for 3 days after minting, so it must be monitored.
  • Sources: ART uses sources from a shared queue, and some paths switch to bridged sources. Simulating a transaction first cannot lock in its sources, so a dedicated pool or a contract that can limit sources is required.
  • Nonce: A dedicated account is required. If a signed nonce is used by another transaction, the adapter cannot currently replace the transaction or raise its fee automatically.
  • Nodes: Outdated node data could temporarily move a confirmed batch back to an earlier state. Check that nodes are consistent and keep historical data, and confirm the chain’s finality rules.
  • Locks: Preparing a transaction accesses a node while holding a database lock. Before connecting the adapter, change this to make the query first, then hold the lock only briefly.
  • Different deployed version: In the public code used by the adapter, every NFT whose idAsset is not 0 goes into the bridge queue. When checked, the ART contract on Polygon added only one specified type. Under the current rules, the source IDs of these NFTs in the normal queue would get a prefix. This could be treated as a source mismatch and stop processing, but it would not be wrongly reported as complete. Before enabling the adapter, update it for the deployed version and test it again.
  • Deployment: Fees, the minimum retirement amount and the source limit were checked on-chain once, but they may change. Check them again before enabling the adapter. Admin permissions and whether contracts are paused have not been verified, and the adapter has never been connected to a live deployment.

Not yet implemented

Real pilot

  • Using a real chain, real assets and real payments, with custody for signing keys and on-chain accounts
  • Evidence-based model energy coefficients, and checks on the reported values themselves
  • Asset rights and source records, real matching rules, and automatic connections to external registries
  • Data from the legacy Photosynth private backend, with checks on the imported results

Later stages

The design document lists these as optional or for later:

  • Hourly matching, and dedicated estimators for images, video, training and edge meters. This usage can currently be reported as direct electricity data
  • An on-chain AllocationRegistry or BatchRetirement, after contract testing and an audit
  • Remote MCP, and publishing the SDK on npm and PyPI

Any remainder that has been retired but not allocated is only recorded separately. It will not be allocated again, so the batch manifests used by issued receipts do not change. The Photosynth plugin only collects usage. Matches are made by a plan on the server or an agent with a grant.

Production operations

  • Custody and rotation for receipt signing keys, and a way for customers to hide or revoke receipts themselves
  • Enterprise single sign-on, reverse proxy support, complete rate limiting, backups, monitoring and alerts
  • An independent security audit

The number of confirmations, number of retries, fees and minimum retirement amount are sandbox settings. They must be checked again before connecting to a real chain.

Read nextThesis →