Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Post recurring supply

Use this guide when your app grants units each billing period. Your app keeps the calendar and posts one dated supply entry per period. Set validFrom to the period’s start and expiresAt to its end when unused units should expire.

Run either code tab with the shared blocks. The SDK helpers are in @agentpost-tools/resourceshark-sdk/helpers.

Before you start

This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.

1. Create a separate resource for a monthly limit

Use key for the project that adopted ResourceShark. Start with the funded prepaidUsd resource, the prepaidAcme holder, and the resourceSharkRefusal helper from Sell prepaid credits. Create a resource that tracks the agent’s monthly limit separately. Your app spends one limit unit per unit it spends from the dollar balance.

const recurringWrite = (path: string, attempt: string, body: unknown) =>
  api('POST', `/v1/resources${path}`, key, body, {
    'Idempotency-Key': attempt,
  });
const recurringScopeBalance = (resourceId: string, holderRef?: string) => {
  const query =
    holderRef === undefined
      ? ''
      : `?holderRef=${encodeURIComponent(holderRef)}`;
  return api(
    'GET',
    `/v1/resources/resources/${resourceId}/balance${query}`,
    key,
  );
};
const recurringDollarBalance = await recurringScopeBalance(
  prepaidUsd.id,
  prepaidAcme,
);
const recurringNow = new Date(recurringDollarBalance.balance.asOf);
const recurringMonthAt = (offset: number, day: number) =>
  new Date(
    Date.UTC(
      recurringNow.getUTCFullYear(),
      recurringNow.getUTCMonth() + offset,
      day,
    ),
  );

const { resource: recurringCap } = await api(
  'POST',
  '/v1/resources/resources',
  key,
  {
    key: 'agent-limit',
    name: 'Agent limit',
    unit: {
      code: 'limit',
      singular: 'limit unit',
      plural: 'limit units',
      precision: 4,
    },
    settings: { time: 'none', identity: 'count', supplyExpiry: 'expiring' },
    scope: { places: false, holders: true },
    tracking: 'none',
    shortage: 'deny',
  },
);
const recurringBuilder = 'agent:acme-builder';

2. Post this month’s supply and next month’s supply

Give the builder 20,000 limit units each calendar month in UTC. Use a source key made from the plan and period start. Send a distinct Idempotency-Key for each write and reuse it when retrying that write. Use supplyPeriods to produce the entries and postSupplyPeriods to post them, or compute and post each entry in your app. Supply requests lists every field a supply entry takes.

type RecurringPlan = {
  resourceId: string;
  holderRef: string;
  planRef: string;
  quantity: number;
  from: string;
  periods: number;
  expires: boolean;
};
const recurringPeriodKey = (planRef: string, start: string) =>
  `period:${planRef}:${start}`;
const recurringPeriodAttempt = (entry: { sourceKey: string }) =>
  `post:${entry.sourceKey}`;
const recurringCapPlan = {
  resourceId: recurringCap.id,
  holderRef: recurringBuilder,
  planRef: 'acme-builder-limit',
  quantity: 20_000,
  from: recurringMonthAt(0, 1).toISOString(),
  periods: 2,
  expires: true,
};
async function postRecurringMonths(plan: RecurringPlan) {
  const anchor = new Date(plan.from);
  const year = anchor.getUTCFullYear();
  const month = anchor.getUTCMonth();
  const day = anchor.getUTCDate();
  const startOf = (offset: number) => {
    const lastDay = new Date(
      Date.UTC(year, month + offset + 1, 0),
    ).getUTCDate();
    return new Date(
      Date.UTC(year, month + offset, Math.min(day, lastDay)),
    ).toISOString();
  };

  const posted = [];
  for (let period = 0; period < plan.periods; period += 1) {
    const validFrom = startOf(period);
    const sourceKey = recurringPeriodKey(plan.planRef, validFrom);
    const entry = {
      resourceId: plan.resourceId,
      scope: { holderRef: plan.holderRef },
      kind: 'added',
      quantity: plan.quantity,
      validFrom,
      ...(plan.expires ? { expiresAt: startOf(period + 1) } : {}),
      evidence: { kind: 'plan', ref: plan.planRef },
      sourceKey,
    };
    posted.push(
      await recurringWrite('/supply', recurringPeriodAttempt(entry), entry),
    );
  }
  return posted;
}
import { createClient as createRecurringClient } from '@agentpost-tools/resourceshark-sdk';
import {
  postSupplyPeriods,
  supplyPeriods,
} from '@agentpost-tools/resourceshark-sdk/helpers';

const recurringClient = createRecurringClient({ token: key });
function postRecurringMonths(plan: RecurringPlan) {
  const entries = supplyPeriods({
    resourceId: plan.resourceId,
    scope: { holderRef: plan.holderRef },
    kind: 'added',
    quantity: plan.quantity,
    cadence: {
      every: 'month',
      count: 1,
      timeZone: 'UTC',
      dayOverflow: 'clamp',
    },
    from: plan.from,
    periods: plan.periods,
    expires: plan.expires,
    evidence: () => ({ kind: 'plan', ref: plan.planRef }),
    sourceKey: ({ start }) => recurringPeriodKey(plan.planRef, start),
  });
  return postSupplyPeriods(recurringClient, entries, {
    idempotencyKey: recurringPeriodAttempt,
  });
}
const recurringCapEntries = await postRecurringMonths(recurringCapPlan);
const recurringOpening = await recurringScopeBalance(
  recurringCap.id,
  recurringBuilder,
);
console.log(recurringCapEntries.length, recurringOpening.balance.onHand); // 2 20000

3. Spend from the dollar balance and the limit together

Put both lines in the same POST /consume so they succeed or fail together. Take 1,000 units as an estimate, then settle both claims at 600 in one request. Spend the 19,400 units left in the limit. The next request is refused in full with exhausted_until_supply and details.nextSupplyAt. Claim requests lists every field a consume and a settle take.

const recurringSpend = (quantity: number, ref: string, estimate: boolean) => ({
  lines: [
    { resourceId: prepaidUsd.id, scope: { holderRef: prepaidAcme }, quantity },
    {
      resourceId: recurringCap.id,
      scope: { holderRef: recurringBuilder },
      quantity,
    },
  ],
  evidence: { kind: 'request', ref },
  sourceKey: `builder:${ref}`,
  ...(estimate ? { estimate: true } : {}),
});
const recurringEstimate = await recurringWrite(
  '/consume',
  'builder-estimate',
  recurringSpend(1_000, 'builder-job', true),
);
const recurringSettlement = await recurringWrite('/settle', 'builder-settle', {
  lines: recurringEstimate.claims.map(({ id }: { id: string }) => ({
    claimId: id,
    quantity: 600,
  })),
  evidence: { kind: 'request', ref: 'builder-job' },
  sourceKey: 'settle:builder-job',
});
console.log(
  recurringSettlement.movements[0].quantity,
  recurringSettlement.movements[1].quantity,
); // 400 400

await recurringWrite(
  '/consume',
  'builder-spend-rest',
  recurringSpend(19_400, 'builder-spend-rest', false),
);
const recurringCapRefusal = await resourceSharkRefusal(
  'POST',
  '/consume',
  key,
  {
    body: recurringSpend(1, 'builder-over-limit', false),
    idempotencyKey: 'builder-over-limit',
  },
);
console.log(
  recurringCapRefusal.code,
  recurringCapRefusal.details.nextSupplyAt ===
    recurringCapEntries[1].supply.validFrom,
); // exhausted_until_supply true

When the next period starts, its 20,000 units become available to spend. The dollar balance still has to cover its line.

4. Post a subscription that starts on the 12th

Give Budi two bags per month from the 12th in UTC. Begin on the most recent 12th. Create one resource for the bag allowance and one for roasted coffee. Each order spends 1 bag from the allowance and 250 g from stock in the same request. A third order in the period has to wait for the next supply.

const { resource: recurringBags } = await api(
  'POST',
  '/v1/resources/resources',
  key,
  {
    key: 'subscription-bags',
    name: 'Subscription bags',
    unit: { code: 'bag', singular: 'bag', plural: 'bags', precision: 0 },
    settings: { time: 'none', identity: 'count', supplyExpiry: 'expiring' },
    scope: { places: false, holders: true },
    tracking: 'none',
    shortage: 'deny',
  },
);
const { resource: recurringCoffee } = await api(
  'POST',
  '/v1/resources/resources',
  key,
  {
    key: 'roasted-coffee',
    name: 'Roasted coffee',
    unit: { code: 'g', singular: 'gram', plural: 'grams', precision: 0 },
    settings: { time: 'none', identity: 'count', supplyExpiry: 'none' },
    scope: { places: false, holders: false },
    tracking: 'none',
    shortage: 'deny',
  },
);
await recurringWrite('/supply', 'roast-batch-14', {
  resourceId: recurringCoffee.id,
  kind: 'added',
  quantity: 10_000,
  evidence: { kind: 'roast', ref: 'batch-14' },
  sourceKey: 'roast:batch-14',
});

const recurringBudi = 'customer:budi';
const recurringBagAnchor = recurringMonthAt(
  recurringNow.getUTCDate() >= 12 ? 0 : -1,
  12,
);
const recurringBagPlan = {
  resourceId: recurringBags.id,
  holderRef: recurringBudi,
  planRef: 'budi-two-bags',
  quantity: 2,
  from: recurringBagAnchor.toISOString(),
  periods: 3,
  expires: true,
};
const recurringBagEntries = await postRecurringMonths(recurringBagPlan);

const recurringOrder = (ref: string) => ({
  lines: [
    {
      resourceId: recurringBags.id,
      scope: { holderRef: recurringBudi },
      quantity: 1,
    },
    { resourceId: recurringCoffee.id, quantity: 250 },
  ],
  evidence: { kind: 'order', ref },
  sourceKey: `order:${ref}`,
});
await recurringWrite(
  '/consume',
  'budi-order-1',
  recurringOrder('budi-order-1'),
);
await recurringWrite(
  '/consume',
  'budi-order-2',
  recurringOrder('budi-order-2'),
);
const recurringBagRefusal = await resourceSharkRefusal(
  'POST',
  '/consume',
  key,
  {
    body: recurringOrder('budi-order-3'),
    idempotencyKey: 'budi-order-3',
  },
);
console.log(
  recurringBagRefusal.code,
  recurringBagRefusal.details.nextSupplyAt ===
    recurringBagEntries[1].supply.validFrom,
); // exhausted_until_supply true

At the next period’s validFrom, an order can draw from the new allowance. The prior period’s unused bags stop counting at its expiresAt, which is the same instant.

5. Replace a future period when the subscriber upgrades

Before the third period starts, cancel its 2 bags with a supply reversal. Then post 4 for the same period with a new sourceKey. Cancel only periods that haven’t started when applying this change to an existing plan.

const recurringThird = recurringBagEntries[2].supply;
const recurringThirdStart = recurringThird.validFrom;
if (!recurringThirdStart) throw new Error('Expected a future period start');
const recurringUpgrade = await recurringWrite(
  `/supply/${recurringThird.id}/reverse`,
  'budi-upgrade-cancel',
  {
    quantity: 2,
    evidence: { kind: 'plan-change', ref: 'budi-four-bags' },
    sourceKey: `cancel:budi-two-bags:${recurringThirdStart}`,
  },
);
const [recurringReplacement] = await postRecurringMonths({
  ...recurringBagPlan,
  planRef: 'budi-four-bags',
  quantity: 4,
  from: recurringThirdStart,
  periods: 1,
});
console.log(
  recurringUpgrade.taken,
  recurringUpgrade.movement === undefined,
  recurringReplacement.supply.quantity,
); // 2 true 4

6. Post a monthly allowance that rolls over

Set expires: false so every posted month’s 8 court hours stay on hand until spent. Use shortage: 'negative' here because this app allows members to borrow against later months. Rina uses 5 hours and then uses 2 hours more than the balance holds. If Rina had stopped after the first use, the 3 hours left and the next three posted periods would add up to 27 hours by the fourth period.

const { resource: recurringCourtHours } = await api(
  'POST',
  '/v1/resources/resources',
  key,
  {
    key: 'court-hours',
    name: 'Court hours',
    unit: { code: 'h', singular: 'hour', plural: 'hours', precision: 0 },
    settings: { time: 'none', identity: 'count', supplyExpiry: 'none' },
    scope: { places: false, holders: true },
    tracking: 'none',
    shortage: 'negative',
  },
);
const recurringRina = 'member:rina';
await postRecurringMonths({
  resourceId: recurringCourtHours.id,
  holderRef: recurringRina,
  planRef: 'rina-court-hours',
  quantity: 8,
  from: recurringMonthAt(0, 1).toISOString(),
  periods: 4,
  expires: false,
});
const recurringBookHours = (quantity: number, ref: string) =>
  recurringWrite('/consume', ref, {
    lines: [
      {
        resourceId: recurringCourtHours.id,
        scope: { holderRef: recurringRina },
        quantity,
      },
    ],
    evidence: { kind: 'booking', ref },
    sourceKey: `booking:${ref}`,
  });
await recurringBookHours(5, 'rina-booking-1');
const recurringRinaBalance = await recurringScopeBalance(
  recurringCourtHours.id,
  recurringRina,
);
const recurringBorrowed = await recurringBookHours(
  recurringRinaBalance.balance.onHand + 2,
  'rina-booking-2',
);
console.log(
  recurringRinaBalance.balance.onHand,
  recurringBorrowed.movements[0].after,
); // 3 -2

Check it worked

Read the dollar and coffee balances. Acme has 76,675 dollar units left and the roaster has 9,500 g of coffee. The refused requests changed neither balance.

const recurringDollarsLeft = await recurringScopeBalance(
  prepaidUsd.id,
  prepaidAcme,
);
const recurringCoffeeLeft = await recurringScopeBalance(recurringCoffee.id);
console.log(
  recurringDollarsLeft.balance.onHand,
  recurringCoffeeLeft.balance.onHand,
); // 76675 9500

Use the resulting movements to sum usage with totals.