Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Helpers

Use @agentpost-tools/resourceshark-sdk/helpers for five optional tasks. Prepare dated supply, combine totals, compare a line with its availability, reverse up to what remains from a supply entry, or display a slot in another time zone.

Prepare recurring supply

supplyPeriods(rule) returns { period, entry } pairs without making a request. Choose 1 to 120 periods. Each Period has a zero-based index and UTC start and end timestamps. The range includes the start and excludes the end. Entries start at validFrom. Set expires: true to set each expiresAt to the period’s end. Set expires: false to leave expiry unset. Give each period its own sourceKey and evidence. You can supply attributes per period and drawOrder for the rule.

Choose a Cadence for the way you measure a period.

  • every: 'month' or every: 'day' takes a positive whole count and a timeZone. An anchor date or timestamp without an offset uses that zone. The schedule keeps the local clock time across changes in offset. A repeated local time uses the earlier instant. A skipped local time moves forward by the gap.
  • every: 'month' also takes dayOverflow. Use 'clamp' to move a missing day to the month’s last day, or 'roll' to carry it into the next month. Each boundary uses the original anchor day.
  • every: 'duration' takes an elapsed length, such as '7d' for seven 24-hour days. Use a positive duration of at most 1,000,000 days. A date alone starts at UTC midnight. A timestamp requires an offset or Z.

postSupplyPeriods posts the entries in order with the idempotencyKey callback you supply. It stops at the first failed write. Earlier successful writes stay in place. Reuse the same keys if you retry the same entries.

import type { ResourcesharkClient } from '@agentpost-tools/resourceshark-sdk';
import {
  postSupplyPeriods,
  supplyPeriods,
} from '@agentpost-tools/resourceshark-sdk/helpers';

export function postMonthlyCredits(
  client: ResourcesharkClient,
  resourceId: string,
  holderRef: string,
  planId: string,
  from: string,
) {
  const entries = supplyPeriods({
    resourceId,
    scope: { holderRef },
    quantity: 10,
    kind: 'added',
    cadence: {
      every: 'month',
      count: 1,
      timeZone: 'America/New_York',
      dayOverflow: 'clamp',
    },
    from,
    periods: 2,
    expires: true,
    evidence: () => ({ kind: 'plan', ref: planId }),
    sourceKey: ({ start }) => `plan:${planId}:${start}`,
  });
  return postSupplyPeriods(client, entries, {
    idempotencyKey: ({ sourceKey }) => `add:${sourceKey}`,
  });
}

Post recurring supply works through a monthly limit, a subscription, and an allowance that rolls over.

Sum totals

sumTotals(report, options) returns a TotalsSum for each combination of unit code and precision. Pass resourceIds to select which resources to include or {} to sum all rows. Each sum has the resource IDs, balance, and signed movements by reason. Pass reasons to receive chosen, the signed sum of those reasons. The movements field still includes every reason reported for the selected resources.

The bucketed list identifies resources with a null balance. Their movements still count. If all rows for a unit have a null balance, its sum has a null balance. On a report requested with groupBy, sumGroups(report, options) returns a Map from each attribute value to its sums by unit. The null key covers entries without the attribute. periodLength(report) returns elapsed ms and days, with 86,400,000 ms per day. It returns null if the report has no complete range.

import type { TotalsReport } from '@agentpost-tools/resourceshark-sdk';
import {
  periodLength,
  sumGroups,
  sumTotals,
} from '@agentpost-tools/resourceshark-sdk/helpers';

export function summarizeUsage(report: TotalsReport) {
  return {
    usageByUnit: sumTotals(report, { reasons: ['use', 'settle'] }),
    groups: sumGroups(report, {}),
    period: periodLength(report),
  };
}

Sum usage with totals reads the report and combines its rows.

Compare a line with availability

Pass a line with quantity and available in whole base units. hasEnough tells you whether the available quantity covers the request. shortBy gives the missing quantity, or 0 if the line fits. Use these with short lines from a refusal or lines from an expired commit.

import { hasEnough, shortBy } from '@agentpost-tools/resourceshark-sdk/helpers';

const line = { quantity: 5, available: 3 };
console.log(hasEnough(line), shortBy(line)); // false 2

Take back supply up to what is left

Use takeBackUpTo(client, supplyId, input) when your app chooses to take back a smaller quantity if the full reversal falls short. Pass quantity, evidence, sourceKey, and idempotencyKey. On insufficient_supply, the helper reads the first short line. If ResourceShark reports a smaller positive quantity, the helper asks for that quantity with the same sourceKey and an idempotency key suffixed with :1, :2, and so on. attempts counts all tries, including the first. It defaults to 3.

taken gives the requested quantity in asked and the reversed quantity in taken. A short line that reports zero available returns nothing_left. An API refusal the helper cannot retry returns failed with the API error. Fetch errors propagate to the caller. Sell prepaid credits takes back disputed credits with this helper.

Display a slot in another time zone

slotIn(slot, timeZone) returns the local date, time, endDate, and endTime, with offsetMinutes for the start. The start and end use their own offsets. Use formatSlot(slot, { timeZone, locale, ...options }) for a localized range. It uses Intl.DateTimeFormat and defaults to medium date and short time when you leave out the formatting options. Pass the time zone in either call. The slot’s original timestamps stay the same. Schedules explains a slot’s exact start and end and its local label.

import type { Slot } from '@agentpost-tools/resourceshark-sdk';
import { slotIn } from '@agentpost-tools/resourceshark-sdk/helpers';

const slot: Slot = {
  start: '2026-03-08T06:30:00.000Z',
  end: '2026-03-08T07:30:00.000Z',
  timeZone: 'UTC',
  local: { date: '2026-03-08', time: '06:30' },
  capacity: 1,
  taken: 0,
  held: 0,
  available: 1,
};
const local = slotIn(slot, 'America/New_York');
console.log(local.time, local.endTime); // 01:30 03:30

Errors

supplyPeriods throws for invalid periods or cadence, invalid anchors, or repeated source keys. hasEnough and shortBy throw for inputs outside the safe-integer range or with fractions. A shortfall or total that exceeds the safe-integer range throws too. postSupplyPeriods passes on the client error for a failed write. The SDK refusal readers read a refusal’s details from that error.