Skip to content

Releases

v1.3.0

Choose a tag to compare

@github-actions github-actions released this 04 Dec 04:43
a4b1ec9

Added

  • The ./observability subpath: AiTokensObservabilityModule, AiTokensMetrics, AiTokensHealthIndicator and OtelOperationTracer.
  • PrismaAiTokensStore.countActiveHolds() and ping(signal), the optional ILedgerStore reads that the ./observability subpath consumes: the
    holds gauge counts the pending holds, and the health indicator pings the store. ping sends SELECT 1 and rejects at once for a signal that arrived
    already aborted.
  • AiTokensHealthIndicator keeps one ping in flight: a check that finds the earlier ping unanswered waits on it, bounded by its own 3 s, instead of
    sending another SELECT 1. The abort of a ping ends its wait and not the query, so without this a stalled database was given a new query by every probe. A ping unanswered for 12 s is given up on and the next check sends one replacement.
  • ai_tokens.budget.exceeded is now also emitted, with policy: 'throttle', when a throttled budget is over its limit. Before, a throttled
    budget only called onThrottle, or logged that none was configured, so a host without the callback had no event to react to. The payload is
    the one the block and allow policies already carry.
  • BudgetGuard now emits ai_tokens.budget.exceeded with policy: 'block' when it refuses a request because a hard budget has no headroom. Before, that
    refusal threw AI_TOKENS_BUDGET_EXCEEDED or AI_TOKENS_QUOTA_EXCEEDED with no event, so only the refusal at consume time was announced. The payload fields are the
    ones the consume-time refusal carries; the event's own scope is the payer's at the guard and the budget's at consume time. The module exports the dispatcher to the guard and the
    interceptor a host references by name; only a guard built with new and no dispatcher announces nothing.
  • ai_tokens.wallet.insufficient, emitted when a debit is refused for lack of credit, the refusal that throws AI_TOKENS_INSUFFICIENT_CREDITS. Its payload is
    { balanceNanoUsd, requestedNanoUsd } and nothing else; the balance is zero when the wallet does not exist. The tenant and the wallet owner are the event's own.
  • ai_tokens.hold.release_failed, emitted when the interceptor could not release a hold after its handler threw. Its payload is { errorCode? }: no id and no text of the error.
  • The bymax_ai_tokens_consumptions_total counter of ./observability has two new outcome values, each present from the first scrape: throttled, for a
    throttle budget that was exceeded (also counted ok when the call is served, and insufficient_funds or blocked when it is then refused), and insufficient_funds, for a debit
    refused for lack of credit (a refusal after the call was served is also counted error). A refusal by BudgetGuard is counted blocked.

None of these changes a result: an event that fails to deliver is logged by the dispatcher, the over-limit consume still resolves, the typed error of a refused debit and the handler's error still reach the caller.

Apply to a consumer: a dashboard or alert that sums bymax_ai_tokens_consumptions_total over every outcome now includes the two new values, and a throttled call is counted throttled plus ok, or plus the outcome of its refusal; select the outcomes you mean. Nothing else to change in code. A host that switches on the event type exhaustively needs a case for each new event type. A host that handles ai_tokens.budget.exceeded should read policy, which may now be throttle, and may now see a block refusal both when the guard checks and when the charge is consumed.

Changed

  • Every operational line the library writes is now one object through the Nest Logger, { event, message, ...fields }, not a string. A line that carried a dotted tag keeps it at the front of message, so a search on it still
    matches. A host that parses these lines as strings reads the object instead.
  • A promise that a host event sink or a host callback returns (events.sink.deliver, and the callback run through
    absorbHostCallAndWait) is now waited for through the same checked wait as every other host promise. One that carries a constructor or then of
    its own, or is a Proxy, is refused: it is logged as a failed delivery or callback. Before, a native
    await read those members. A sink or callback that returns an ordinary promise or a plain value behaves as before.
  • That wait refuses a Proxy before any member of it is read, and checks the realm both before and after the wait. A value a refused sink returned may already have been delivered when the refusal is logged.
  • A row, a list or an argument that is a Proxy, or whose prototype is one, is now refused with AI_TOKENS_INVALID_CONFIG before any trap of it runs, when a service
    hands it to its store or its store hands it to a service, nested at any depth the library copies. Before, a Proxy row that an asynchronous store method
    resolved with was copied and answered, and its getPrototypeOf trap ran when the guard decided whether it was a plain object. A store that
    returns a Proxy must return a plain object or an instance of a class instead.
  • A Proxy argument itself is still read through its traps, as the README states, and is refused only where a store takes it. Called directly, the PostgreSQL adapter reports a Proxy
    argument as AI_TOKENS_STORE_ERROR with the refusal on cause, not AI_TOKENS_INVALID_CONFIG; a service that reaches it through the store maps it as above.

Fixed

  • A host logger that throws no longer fails the library. logEvent and the ./observability warnEvent drop a line the logger cannot write, so record() no longer rejects for a usage row that is already posted when an event listener or sink fails and the logger throws too, the holds gauge no longer fails every scrape until restart after a failed count, and ContentCapture and the late-append conflict keep their own outcome.

Internal

  • The promise-chain scanner has no allowed chains left: the code it covered is written with await and try/catch instead of .then,
    .catch, .finally or Promise.resolve, and each behaves as before.
  • The server and observability bundle size budgets were raised for the typed events and the metrics mapping, and the server budget again for the
    internal token that exports the dispatcher to the guard and the interceptor.
  • The shared, prisma and redis bundle size budgets are the measured size plus 30 bytes.
  • Six expressions that were wrapped in a type assertion are restructured so that mutation testing
    reaches them; behaviour is unchanged. The server, prisma and redis size budgets are the new measured
    size plus 30 bytes.

v1.2.0

Choose a tag to compare

@github-actions github-actions released this 30 Nov 06:54
282234f

Changed

  • The optional peer @nestjs/event-emitter is now >=3.0.0 <13.0.0; it was >=2.0.0. Every 2.x release declares NestJS 8 to 10
    only, while this library requires NestJS 11, and 3.0.0 is the first release that declares NestJS 11. CI now runs the unit suite
    at 3.0.0.
    • Apply: no code change. An install with 2.x already needed npm's peer conflict override: npm install of
      @nestjs/common and @nestjs/core 11 beside @nestjs/event-emitter 2.0.0 or 2.1.1 fails with ERESOLVE. Move to 3.0.0
      or later.

Fixed

  • SECURITY.md no longer says that every GitHub Action is pinned by commit SHA: third-party actions are, and some of the organisation's
    own shared workflows are referenced by the moving v1 tag.
  • Unknown scope and owner types are rejected on the calls below, and existing rows remain releasable. record(), hold(),
    meter() and getStatus() throw AI_TOKENS_INVALID_CONFIG for a payer scope type other than tenant, team, user or key, and
    wallets.grant(), debit(), adjust() and reconcile() for an owner type other than tenant, team or user; before, only
    a key owner was refused. release(), capture(), reverse() and the sweeps still work on a row stored under another type, and
    wallets.getBalance(), getBalanceBreakdown(), getEntries(), refund() and settleAdjustment() still accept it. Known
    limit: a plain getBalance() on such a wallet can include an expired grant, since debit() and reconcile() are refused for it.
    • Apply: check what your scopeResolver returns and which types your stored rows and wallets carry. The guard meters
      through hold(). Without a hold, the interceptor now resolves the context and checks its tenant and scope before the
      handler, so a call it refuses, or whose scopeResolver throws, never runs the handler. A retry under the idempotency key
      of a row stored under another type is rejected, not replayed.

Documentation

  • SECURITY.md states when the intrinsics guard checks: at each assertCleanRealm() call, against what the built-ins held when
    the server layer loaded, not continuously. It lists what the guard leaves out: the global Promise and JSON bindings, the
    global timers, and the ./shared and ./prices subpaths imported without the server layer.

Internal

  • Removes mutation-testing disable comments and some type casts from shipped code: the export header and rows are read from the same
    column list, and the context guard and the settle failure announcement share the payer check. No behaviour change.
  • The secret scan in CI runs the TruffleHog image of the version its action is pinned to, instead of latest, and a CI check
    fails when the two differ.
  • The mutation-directive check reads every comment of the production source, block comments and trailing ones included, not only a
    line that holds nothing else.
  • The server bundle size budget is the measured size plus 30 bytes.
  • The unit coverage gate collects the index barrels and the Redis counter store (src/redis/index.ts), which a glob had left out.
  • The two osv-scanner.toml ignores are gone with the file: both advisories were withdrawn. A .npmrc setting that pnpm did not
    read is gone too.

v1.1.27

Choose a tag to compare

@github-actions github-actions released this 28 Nov 14:38
43eb6a4

Apply: no database migration and no option change. A host that watched stderr for [ioredis] Unhandled error event from the
counter store should watch for the log line below.

Changed

  • A RedisBudgetCounterStore built from a connection URL now handles the error events of the client it creates: each one is a
    warning ai_tokens.redis_counter.client_error with at most the error code, in place of the client's own line on stderr. A
    client the host passes in is not touched.

v1.1.26

Choose a tag to compare

@github-actions github-actions released this 28 Nov 11:30
47b8996

Apply: no database migration and no option change. A host that reverses a compensating record, or appends a record
that does, now gets AI_TOKENS_IDEMPOTENCY_CONFLICT. A host that calls RedisBudgetCounterStore itself and reads the
message or command of a rejection should read its code.

Changed

  • A command that fails now rejects RedisBudgetCounterStore with the store's own error: the message counter command failed
    and, when the failure has one, its code (OOM, READONLY). The error of the Redis client, with its
    message, command and arguments, is not passed on. A connection URL that cannot be parsed rejects with invalid connection URL.
  • Internal: most mutation-testing suppression comments were removed from the source. No change in behaviour is intended.

Fixed

  • reverse() refuses a compensating record, one with reversesRecordId, and LedgerService.append() refuses a record
    whose reversesRecordId names one. reverse() used to accept it: the ledger, and for an enforced non-system record the budget,
    counted the charge again while the wallet was not debited. Rows already written that way are not repaired; they are the
    compensating records whose reversesRecordId points at another compensating record.
  • Documentation: the specification said reverse() runs in one store transaction. It does not. The specification and the
    README now say what a failure part-way leaves, what a retry completes, and what needs the settlement sweep. No behaviour
    changed.

v1.1.25

Choose a tag to compare

@github-actions github-actions released this 26 Nov 11:28
1813fb0

Apply: no database migration and no option change. A host with its own IWalletStore (appendEntry now receives a fourth argument), a switch that must cover every AiTokensEventType, a consumer of ai_tokens.hold.released or a client that retries after a failed settle should read the Apply notes below.

Added

  • ai_tokens.settle.failed ({ holdId?, correlationId?, errorCode?, where }, with the tenant and scope on the envelope) and the
    SettleFailedEventData type. It says that a served call was not settled, so the host can reconcile the usage from its own
    provider log; the error's message is never carried. A call with no hold has no holdId, and
    correlationId is the one of the call's metering context, so set it if you need to match such a call; it is carried when it is text
    of at most 256 characters with no NUL. When the ledger could not be read back after the failure, the row may exist all the same, so
    check the ledger before billing from your provider's log.
    • Known limit. The event is a snapshot: the row may post after it, and LedgerFilter has no correlationId.
    • Known limit. The error reaches the caller after the delivery, so a sink that never settles holds the failed request.
    • Known limit. A small budget or wallet can refuse further calls until the reaper releases an unsettled hold; release() it by
      the event's holdId, tenant and scope to free it sooner.
    • Apply: AiTokensEventType gains a member, so a switch that must cover every type needs a case for it.

Fixed

  • MeteringInterceptor released the guard's hold as handler threw when the handler had succeeded and settling failed. A pending hold
    now stays pending and the hold reaper releases it after TTL, normally within one interval. Apply: until then its wallet and budget
    reservation stays in place, and a retry with the same idempotency key gets the same hold. A consumer of the
    ai_tokens.hold.released event no longer receives one at the time of the failure.
  • MeteringInterceptor without a guard's hold now emits ai_tokens.settle.failed when the handler returned and record() failed
    before writing its row. The thrown error is unchanged.
  • MeteringService.meter() now emits ai_tokens.settle.failed when the function had served and its usage could not be
    settled, after releasing the hold when there is one; the release and the thrown error are unchanged.
  • The hold reaper reclaimed at most 100 expired holds per sweep, so a backlog kept its reservations for many sweeps after the TTL. A
    sweep now reads further batches while one comes back full, up to 100 batches.
    • Known limit. A hold that keeps failing to be released can be tried again in each of a sweep's batches,
      with a warning each time.
  • A grant given no effectiveAt was left out of the stored balance, and out of the running balance of its entry, when the application clock was ahead of the database clock: it entered only at the next debit or reconcile(). The Prisma store now keeps the earlier of the two clocks for such a grant. A given effectiveAt, new Date() included, is stored unchanged. Entries already written are not changed.
    • Known limit. Such a grant whose expiresAt is already past on the application clock, but not yet on the database clock, shows in a plain getBalance() until the next debit or reconcile(); a debit cannot spend it.

For store implementors

  • IWalletStore.appendEntry receives a fourth argument, { effectiveAtDefaulted }. When it is true, store the earlier of entry.effectiveAt and the instant you stamp createdAt with, and judge the balance contribution on the stored value. A store that ignores it behaves as before.
    • Apply: WalletService now passes four arguments on every appendEntry call, the third undefined. A store with an optional fourth parameter of its own, such as a transaction handle, no longer type-checks against IWalletStore when that type is unrelated to AppendEntryOptions, and is handed { effectiveAtDefaulted } in that position at run time: move that parameter.

v1.1.24

Choose a tag to compare

@github-actions github-actions released this 25 Nov 21:51
66b2f4d

Apply: run 0004_wallet_entry_order.sql, then 0005_wallet_entry_order_indexes.sql, before you update the package. 0004 only adds columns and 0005 only adds indexes and a foreign key; neither rewrites a row, and each header documents its rollback. Entries written before 0004 keep seq and balanceAfterNanoUsd null and sort first in the order they always had. During a rolling deploy, an instance still on the previous release writes entries with a null seq, so those entries list before the ones the new code wrote; the balance, the running balance of later entries and the refund cap count them correctly.

Added

  • refund() accepts restore: 'source' and debitEntryId: the refund puts the amount back on the grants the debit burned, by negative allocation rows, and links itself to the debit. A part on an expired grant is taken out again by an expiry:refund:<refundId>:<grantId> entry. A hold: or record: debit is refused, and the restorable amount is capped by the debit less its linked refunds and the unlinked refunds and positive adjustments of the same usageRecordId. A replay of the key is checked in both directions: a plain refund and a restoring refund never share a key.
  • getBalance(ref, { asOf }) and getBalanceBreakdown(ref, { asOf }) answer what could be spent at an instant; an asOf more than 5 seconds in the past is refused. Both need a store with balanceAt and balanceBreakdown, which are optional on the port.
  • Each ledger entry of a wallet carries a per-wallet seq and the balanceAfterNanoUsd it left, and entries list in commit order.

Fixed

  • BudgetGuard could not be built by Nest in a host that names it in @UseGuards(BudgetGuard), including the README's own controller: its constructor parameters carried no @Inject, the published build is made without decorator metadata, and Nest reported "can't resolve dependencies of the BudgetGuard (?, +, +, Symbol(BYMAX_AI_TOKENS_OPTIONS))". It failed in every published version. Every parameter now names its token. A consumer-runtime gate now boots a Nest host over HTTP against the packed tarball with the README controller, and proves the guard passes a request under budget, answers 402 or 429 over it, and refuses a hold larger than the budget before the handler runs.
  • @RequireBudget with a { tokens } or { amountNanoUsd } estimate on a rate-table mode is refused with AI_TOKENS_INVALID_CONFIG (HTTP 500) before the handler runs when pricing.strict is true and the price list has no price for the row its hold will record. Such an estimate settles on the model context.baseModel names (the placeholder unspecified when none, which no rate table lists), so with none or an unlisted one its settle after the provider call was refused with AI_TOKENS_PRICE_NOT_FOUND and the served usage was released unbilled; a baseModel listed for the preset's provider is placed and billed as before (with no preset the provider is unspecified, no baseModel is listed for it, and the guard refuses). A provider-reported preset, a rated { provider, model, ... } estimate and pricing.strict: false are unchanged; with strict: false an unpriced hold on a rate-table mode is recorded at 0 USD, so name provider and model to bill it. A direct metering.hold() followed by capture() is unchanged.
  • The realm guard no longer refuses every billing call in a host that evaluates a second copy of reflect-metadata after the package loaded. It recorded every function of Reflect, so the functions that polyfill defines again were read as a replaced built-in. It now records only the functions the language defines on Reflect; a replaced one is still refused, and no decision of the library reads a polyfill function.

Documentation

  • README step 4 names the model in the @RequireBudget estimate and extracts the provider response in @Meter: the anthropic normalizer reads the whole response, so the default result.usage made the settle fail with AI_TOKENS_USAGE_MALFORMED.

Changed

  • appendEntry of the Prisma store locks the wallet row before it writes. Parallel writers to one wallet queue on that lock. The cost of the lock, measured on a local PostgreSQL with 8 parallel appends (a relative figure between the two versions, not a capacity): about 1.5 ms at p50 and 2.2 ms at p95 on one wallet (p50 5.1 to 6.6 ms, p95 7.6 to 9.8 ms), and about 0.9 ms at p95 on eight wallets (p95 4.9 to 5.8 ms).

v1.1.23

Choose a tag to compare

@github-actions github-actions released this 24 Nov 23:52
d3ec540

Apply: no migration and no option change is needed. This release closes one class of defect: a host that planted Promise[Symbol.species], a then or a constructor could decide what a store or a callback answered, because the library chained the promise it was given. It now waits for what a host returns with a native await, after refusing a native promise that carries a then or a constructor of its own, and refuses it again when the answer it resolved with has a then. A store, a markup policy, a tokenizer, an fx function and the async options factory may still return a Promise subclass, a thenable (a plain object or a class instance with a then, a query builder) or a native promise of another realm, as in 1.1.22. A Proxy is refused, since its traps are host code: a promise that is a Proxy is refused on every call, and for the function meter() runs an answer that is a Proxy is refused too, with AI_TOKENS_INVALID_CONFIG, so a provider SDK that wraps its response in a Proxy must be unwrapped by the host before the function returns it. The module also loads when the global Promise was replaced before the import (a subclass, bluebird, zone.js, a wrapper): it takes the engine's promise from an async function and never reads the global.

Fixed

  • A host can no longer answer for a store through Promise[Symbol.species] or a replaced Promise.resolve. Decision sites chained a promise a store returned (.then, .catch, Promise.all), and a chain builds its result with the species constructor read live, so a planted species made a store return a forged answer. Decision sites now wait natively, and check the promise they got first: one whose constructor or then a host planted for the one read is refused instead of answering. A source scan fails on any new chain or promise combinator in shipped code that is not named with the reason its result decides nothing.
  • The realm guard reads the value of a property descriptor as the descriptor's own, so a value planted on Object.prototype cannot make an accessor look like a built-in function, and it refuses while Promise.prototype.constructor is not Promise, while either it or then is an accessor, or while the getter of Promise[Symbol.species] is not the engine's, which a driver's own then reads.
  • The Redis counter takes the client from a box with no prototype, so a then planted on the class of the client cannot swap the client the store runs its script on.
  • The hold reaper waits for a sweep natively, so a species that never settles can no longer leave the running flag set and stop later sweeps.
  • A promise a host returns is waited for with a native await, after a synchronous check that a native promise has no then or constructor of its own and that the value is no Proxy; the answer is checked again after the wait. A Promise subclass, a thenable and a native promise of another realm are waited for as in 1.1.22, because the then they run is the one the host gave them. A value with a then anywhere on its chain is refused as an answer, since resolving it would run that then. Apply: none; a store that returns a native promise, a subclass or a thenable works as before.
  • After every store or host answer the Array.prototype members the library reads are compared with the engine's, and neither prototype may hold a then, and the budget and status lists are built with helpers that read none of them, so a one-shot map, filter, push or then a store plants is refused instead of emptying a budget list and letting an over-limit consume through.
  • The Redis client is quit on shutdown even when its connection promise was refused, and the bounded quit no longer races a promise.
  • These checks are best-effort hardening, not a security boundary against code that already runs in the host process; see "Threat model: same-process code" in SECURITY.md for what stays a known limit.

Documentation

  • The README states the limit of a ledger store without the optional effects-owed marker calls. A wallet leg that fails after a capture commits leaves the record posted at its actual cost while the wallet keeps the hold's reserved debit, and a second capture returns the posted record without running the leg again. A store that keeps the marker, as the Prisma store does, lets the reaper finish the leg.

v1.1.22

Choose a tag to compare

@github-actions github-actions released this 24 Nov 06:56
bc54d53

Apply: no migration and no option change is needed. This release closes one class of defect, found in every earlier release: a key put on Object.prototype (by another library, or by prototype pollution) was read as a value the host had supplied, in the options of the module, the metadata of @Meter and @RequireBudget, the usage a handler returns and a normalizer builds, the rows, filters and optional methods of a store, the inputs the PostgreSQL adapter binds and the descriptors the library defines. Read the Changed entries before you upgrade: the library now refuses to start or to move money in a process whose Object.prototype or built-ins are not the engine's, and the records the services hand back are copies with no prototype.

Fixed

  • A planted key can no longer change what is billed or blocked. A key on Object.prototype named like an option (strict, failClosed, settlement.enabled, wallets.overdraftNanoUsd, holds.ttlSeconds, ratingMode, markup), like a field of @Meter or @RequireBudget (isSystemCost, estimate, feature, preset, tags, extract, exposeHeaders), like a field of the handler's result (usage), like a field a normalizer builds (serverToolUse, the cache, audio, image and reasoning counts, serviceTier, a reported cost), like a model (constructor, toString) or like a field of the request the guard enriched (hold) was taken for something the host set: a planted isSystemCost made every metered call free, a planted strict=false turned off the missing-price refusal, a planted serverToolUse billed 10,006,250,000 nano-USD for a call of 6,250,000, a planted usage was billed instead of refused with AI_TOKENS_USAGE_MALFORMED, and a planted hold was captured when the guard had placed none. They are read as the host's own fields (an own field, or one the host's class defines; a getter of a class still counts) and never from the root of the prototype chain.
  • A planted key can no longer be persisted by the PostgreSQL adapter. The adapter binds the optional names of its inputs from plain objects, so a planted limitTokens of 0 became a hard token limit on a budget (every later call blocked), a planted cacheReadNanoUsdPerMillion, tier* or unitRates became the price of a model (also on the seed path of seedFromSnapshot), and a planted extraUnits, requestedModel, beneficiary or expiresAt went into a usage row or a wallet entry. Every argument a store takes is copied first, and the price snapshot builds its rows from their own keys, so a key planted before the first import no longer ends up in a seeded row.
  • A planted key can no longer change how a service reads a row a store returned or builds from one. A planted extraUnits on a stored hold billed a captured call at the table rate plus the planted units (10,006,250,000 nano-USD instead of 6,250,000), a planted reversesRecordId reconciled a budget count wrongly, a planted features exempted an exhausted budget, a stored budget row with no tenantId and a planted tenantId passed the tenant check, a planted isSystemCost or feature dropped records from a usage report (three recorded calls of 6,250,000 each came back as none with isSystemCost planted), a planted expiresAt made the PostgreSQL store read a grant with no expiry as not spendable (the balance read 0), a planted limit or offset paged getEntries, and a planted correlationId, requestedBy, reversesRecordId or extraUnits written into a hash chain made verifyChain fail for good. The services read the rows of every store, the library's and the host's, as copies that hold only what the row has, the report filter and the chain hash read their fields as the record's own, and the rows the adapter maps have no prototype.
  • A planted get, set, value or writable on Object.prototype no longer makes every metered call throw. The descriptors the library hands to Object.defineProperty, and the descriptor the store guard returns to the engine, have no prototype, and the parts of the internal shapes that read a call's arguments (nested, raw, limits) are the shape's own, so a planted extraUnits or nested no longer drops a host's tool units or a price's unit rates. A typed error has its own message, body, status and name, so a message planted on Object.prototype is not the text of an exception, and the refusal of the realm guard, built without running the constructor of HttpException, is not changed by any key planted under those names, whether it is read-only or not.
  • A function planted under the name of an optional method of a store (findStaleReferences, pruneApplication, pruneGivenBack, pruneGivenBackExcept, findDebitsBefore, findEffectsOwed, findEffectsOwedFor, clearEffectsOwed, seedPrice, summarize) or of a sink is no longer called as the host's, and a key planted under the name of an option of a sweep or of the Redis counter (pageSize, pages, keyPrefix) is not one.
  • A hold estimate above what a ledger row stores (2,147,483,647 tokens) is refused with AI_TOKENS_INVALID_CONFIG before anything is reserved, and a pending hold replayed with different tool units is refused with AI_TOKENS_IDEMPOTENCY_CONFLICT, as record() does.

Changed

  • The library refuses to start, and to move, read or report money, in a process whose Object.prototype or built-ins are not the engine's. The module does not start, and every call that moves, reads or reports money refuses with AI_TOKENS_INVALID_CONFIG, before anything is written, while the Object.prototype of the process holds a name the engine does not define, lacks one it defines or holds one changed, or while any function of the standard namespaces and constructors it relies on (Object, Reflect, Array, Math, Number, String, Set, Map, Date, BigInt, DataView, TextEncoder, typed arrays and the others, with their prototypes) is not the function it was when the library loaded, or while the name of one of them has been rebound to another object. Promise, its prototype and its binding are exempt: tracing and monitoring agents (dd-trace, New Relic, zone.js) wrap them after load on healthy hosts, and the code that settles a store result or serializes the writes of a call uses await, which does not look the global up. JSON is exempt too, because a host's own tests spy on it: the keys, the statement parameters and the hashes are made with the JSON.stringify the library met when it loaded. The refusal says how many names of Object.prototype differ and how many built-ins do, with a count, never a name or a value. A host that extends Object.prototype (a should-style assertion library, a polyfill) cannot run the library, and neither can a process that patches one of those built-ins in place (jest.spyOn(Date, 'now') in a host's own tests): restore the built-in before the call. The global Date is one of them, so a fake clock (jest.useFakeTimers()) must be restored before the library is called. A symbol on Object.prototype is counted whether it is enumerable or not, except the one hidden mark that Jest puts there. The check is made again at every call, and again before the amounts of an estimate or of a capture are computed, so load order does not help.
  • The records a service returns as a store returned them (UsageRecord, Budget, wallet entries and price versions), and the usage a built-in normalizer returns, are copies that have no prototype: they carry the fields of the row, but record.hasOwnProperty(...), record.toString(), String(record) and record instanceof Class are not available on them (use Object.hasOwn(record, name); JSON.stringify is unchanged). A getter of a class a store's row is an instance of is read once and counts as a field; a field defined as not enumerable is still a field. A host that mutated a returned record expecting the store to change must call the store.
  • A record or list nested deeper than 8 levels, in an argument a store takes or a row it returns, is refused with AI_TOKENS_INVALID_CONFIG instead of being handed on.
  • A frozen or sealed store object can be given to the services; its methods are wrapped, and a method it lacks stays absent.
  • A key that another library put on Object.prototype under the name of an optional field of a host option or input (limitTokens, features, expiresAt, a rate) no longer counts. A host that relied on an inherited default put on Object.prototype must set the option or the field itself.

v1.1.21

Choose a tag to compare

@github-actions github-actions released this 22 Nov 09:33
6221ca6

Apply: no migration and no option change is needed. This release fixes billing defects in the usage of a call, all of them present in earlier releases, and some of its changes refuse a usage or a call that an earlier release billed (see Changed). Check a host that passes its own normalized usage or normalizer, and a host that bills tool units.

Fixed

  • A hold that is captured now bills the tool units of the call. capture() rated the hold's stored units, which were always empty because a hold never stored context.extraUnits, and it overwrote the tool units the provider reported in the usage, so a host that meters through hold() and capture() undercharged every tool call (seven web searches rated at 10,000,000 nano-USD each billed 70,000,000 less through capture() than through record()). The hold now stores its units, capture rates the usage's units merged with the hold's (the host's count wins for a unit both name, as in record()), and the settled record names the units it billed. The units are written to the existing extraUnits JSONB column, so no migration is needed.
  • OpenAI chat and Responses bill the audio output tokens once. They were counted in the output total and again as audio output, so a call with 20 audio tokens was billed 200,000 nano-USD too much at a 10,000 nano-USD output rate.
  • A count that a response reports twice is billed once: the AI SDK reports reasoning tokens and cache reads at the root of the usage and in its details, and OpenAI-compatible gateways report the cache hit at the root and nested. Two equal values are one count; two values that differ are refused with AI_TOKENS_USAGE_MALFORMED, not added.
  • Anthropic cache_creation: {} beside cache_creation_input_tokens, and Bedrock cacheDetails: [] beside cacheWriteInputTokens, billed no cache write. The total is billed when the split reports nothing. A total that disagrees with a non-empty split, and a null entry of cacheDetails, are refused.
  • The tool units a host puts on a context (extraUnits) are validated: a count that is not a whole number from 0 to the largest safe integer is refused with AI_TOKENS_USAGE_MALFORMED on hold() and record() before anything is debited, and the merged units are checked again before a capture settles, where a negative one under-billed or credited the wallet and a fraction threw a raw RangeError. For a unit both the provider and the host name, the host's count replaces the provider's (so a host that passes 0 bills 0 for that unit); -0 is 0; this is the rule record() always had and capture() now shares.
  • A call whose tokens add up to more than 2,147,483,647 (the 32-bit columns of a ledger row) is refused with AI_TOKENS_USAGE_MALFORMED before anything is debited. It used to debit the wallet and then fail to store the row.

Changed

  • A tool unit with a count above 0 and no rate in the price's unitRates is a missing price, like an unpriced model. It was billed at 0 without a trace. With pricing.strict on (the default) the call is refused with AI_TOKENS_PRICE_NOT_FOUND before anything is debited; with it off the call is billed for what has a price, priceMissing is set on the record and ai_tokens.price.missing is raised, by capture() as by record(). A unit named like an inherited property (constructor) is looked up as an own entry of the price only. A host that bills tool units must list a rate for each unit it uses.
  • The seeded price snapshot lists a web_search_requests rate only for the models that carry one in src/prices/model-prices.seed.ts. For the others, with pricing.strict on a call with web searches on one of them is refused until the host lists a rate with upsertPrice; a host that supplies its own snapshot lists a rate for every unit it bills.
  • A negative token or tool unit count, a count past the largest safe integer and a negative provider-reported cost in a normalized usage (from a host normalizer or passed by the host) are refused with AI_TOKENS_USAGE_MALFORMED. They were clamped to 0, which hid the defect and billed the call as another. A host that relied on the clamp must fix the usage it passes.

v1.1.20

Choose a tag to compare

@github-actions github-actions released this 21 Nov 20:24
0393474

Apply: no migration and no option change is needed. Every argument a host passes to a public method is read once, at the call, and by the names of its type: a getter or a Proxy trap that answers once and throws afterwards, a date that does the same, and a list or object that cannot be read are refused as AI_TOKENS_INVALID_CONFIG naming the argument or the field, and the host's own error and text no longer reach the caller. A sink or a callback of the host that fails no longer fails a call that had done its work. Two behaviours tighten: a text with a NUL character and an amount beyond a BIGINT column are refused naming the argument where the store answered with its own error, and an object that lists no key, where the library lists keys itself, is refused where it was read as empty.

Fixed

  • Apply: no migration and no option change is needed. A date a caller supplies is read once at the call and used as a copy, so a Date subclass that answers its first call and throws on later ones can no longer fail after the call has begun (budgets.rotateWindow threw the host's own error after it had persisted the rotation). A text argument that contains a NUL character, and an amount outside what a BIGINT column holds, is refused with AI_TOKENS_INVALID_CONFIG naming the argument, where the store answered AI_TOKENS_STORE_ERROR without naming it. An argument object whose getter throws is refused naming the field (<field> could not be read) and no longer surfaces the host's own error. The messages that refuse an amount now state the range, and wallets.creditRateNanoUsd and wallets.overdraftNanoUsd are refused above it.
  • Apply: no migration and no option change is needed. A list or an object nested in an input is copied once with the input, element by element, so a Proxy list whose get or length throws, or a nested getter that answers once, can no longer fail a call after it has begun or put the host's own error in the caller's hands: it is refused as AI_TOKENS_INVALID_CONFIG, <field> could not be read. A list or nesting beyond the limits is refused the same way, and a key of the host's object that is not a short plain name is written in the refusal as <key>.
  • Apply: no migration and no option change is needed. A telemetry sink (recordUsage, recordDuration) or an onThrottle callback that throws, returns a promise that rejects, or returns a thenable whose then throws no longer fails the call that had already done its work (record, capture, a consumption that throttles): the failure is one log line, ai_tokens.telemetry.sink_failed or ai_tokens.budget.on_throttle_failed, with the error's name and code and never its message, and a rejection nobody handles is no longer left behind. A sink that does not return, or a callback that never settles, is not guarded: onThrottle is awaited.
  • Apply: no migration and no option change is needed. The reference of a wallet, the scope of a budget lookup and the input of a rate lookup are read once with the call, like the other inputs, and every input read once is read by the names of its type: a getter of a class and a field defined as not enumerable are read, a key planted on Object.prototype, of any realm, is not. A field the host's object does not have is absent, whatever else the object holds.
  • Apply: no migration and no option change is needed. The arguments of the metering calls are read once with the call and by the names of their type. An estimate is read by the names of the variant it is, so a getter named like a field of another variant is not run. A StreamUsageCollector passed to capture() is used as it is.
  • Apply: no migration and no option change is needed. A raw provider response is no longer copied before its normalizer reads it: a nested object that answers by a get trap and lists no key (a lazy wrapper of cache_creation, prompt_tokens_details, completion_tokens_details) is read by name as before, and the billed amounts are exact; the normalizer reads the response through a view that answers each field the same way every time. An object that lists no key where the library lists keys itself (serverToolUse of a usage, context.extraUnits, tags, unitRates) is refused instead of read as empty, which had billed a tool as free: AI_TOKENS_USAGE_MALFORMED for the usage, AI_TOKENS_INVALID_CONFIG, <field> could not be read for the others. A Buffer, a typed array and a full embeddings response in a usage are accepted without being walked. A hold estimate that is a Proxy answering by its get trap is the variant it answers for.
  • Apply: a usage whose counts are not counts is refused where it used to be billed for another amount. Every built-in normalizer reads a count that is there as a whole number from 0 to the largest safe integer; a string, NaN, Infinity, a negative, a fraction or a list is refused as AI_TOKENS_USAGE_MALFORMED, where it was read as 0 (a call billed for less than it used) or kept as a negative (billed for more, then clamped). A cached, audio or reasoning count that is more than the prompt or the completion it is part of is refused, where the clamp billed the call as another. A container of counts that is there (prompt_tokens_details, cache_creation, server_tool_use, cacheDetails) must be an object (cacheDetails, a list), where another type was read as absent and dropped what it held, and a server_tool_use entry that is not a count is refused instead of dropped, which had billed a tool as free. An absent count, or null, is still 0. A streamed final usage that cannot be normalized is AI_TOKENS_USAGE_MALFORMED and not the normalizer's plain error.