Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Hold workflow

Use createHoldWorkflow from @agentpost-tools/resourceshark-sdk/workflows to list slots and manage a hold in plain TypeScript. Use apiTransport on a trusted server or in a script with a secret key. Use endpointTransport in a browser or app to reach your server. Add useHoldWorkflow from @agentpost-tools/resourceshark-react to follow the workflow in React.

apiTransport

Pass a client with your project’s secret key. Every placement and extension sends an explicit ttl. A placement names at least one line and your app’s sourceKey. For a resource kept by place, put scope.placeId on its line. For a resource with settings.identity: 'instance', name the unit in scope.instanceId. Scopes explains how a place, holder, or named unit picks the balance a line uses.

import { createClient } from '@agentpost-tools/resourceshark-sdk';
import {
  apiTransport,
  createHoldWorkflow,
} from '@agentpost-tools/resourceshark-sdk/workflows';

export async function placeStockHold(
  key: string,
  resourceId: string,
  placeId: string,
  sourceKey: string,
) {
  const client = createClient({ token: key });
  const workflow = createHoldWorkflow(apiTransport(client));
  const outcome = await workflow.place({
    lines: [{ resourceId, scope: { placeId }, quantity: 1 }],
    ttl: '15m',
    sourceKey,
  });
  return { workflow, outcome };
}

Before placing, the transport reads each distinct resource in the request. For a resource kept per holder, it copies the hold’s holderRef into a line whose scope.holderRef is absent. If both are absent, it reports holder_required. It reports place_required for a line missing a required scope.placeId. Both errors identify the line. Resource reads are fresh by default. Set resourceCacheMs to reuse a read for that many milliseconds.

endpointTransport

Set url to the prefix where your app mounts its hold endpoint. Use an absolute URL for a native app. Pass fetch to supply your own Fetch implementation. The optional headers callback supplies headers for each request and can return a promise. Use it when your app sends a session credential in a header. The three type parameters describe your app’s place, extend, and commit inputs. Extend and commit default to void when you omit those type parameters. The routes and JSON shape are in the hold endpoint wire format.

The page sends your app’s inputs. The server chooses the ResourceShark request, including the explicit ttl and any required scope.placeId. Keep your project’s secret key on the server. Apply your app’s rules there. Limit hold length and booking window checks a hold’s length and booking window on your server before it places a hold.

React

useHoldWorkflow returns the current state and the actions listSlots, place, extend, release, commit, and reset. It creates a workflow from the first render’s transport and optional HoldWorkflowOptions. Its countdown ticks while the component is mounted and stops on unmount. The hook renders nothing and works in React 19, React Native, and Expo. If your runtime lacks crypto.randomUUID, provide crypto.getRandomValues so the workflow can make attempt keys.

npm i @agentpost-tools/resourceshark-react @agentpost-tools/resourceshark-sdk react
import { useHoldWorkflow } from '@agentpost-tools/resourceshark-react';
import { endpointTransport } from '@agentpost-tools/resourceshark-sdk/workflows';

type BookingRequest = { requestId: string; start: string; end: string };
const transport = endpointTransport<BookingRequest>({ url: '/api/booking' });

export function useBooking() {
  return useHoldWorkflow(transport);
}

Use useStore(workflow) to follow the state of a workflow you created yourself. It subscribes with React’s useSyncExternalStore. Call the actions on the workflow and dispose it when you are done.

State and countdown

Read the current HoldWorkflowState with getSnapshot(). Use subscribe(listener) to follow changes. Call the function it returns to unsubscribe. pending is true while the workflow tracks a write or has a slot read in flight. pendingAction names the tracked write, is slots while only slot reads are pending, or is null when neither applies.

listSlots(query) reads one resource at a time and returns its slots. Identical queries share an in-flight read. Different reads can run alongside each other and alongside a write. The slots state keeps the last answer for each combination of resource, place, condition, and instance.

secondsLeft rounds remaining seconds up and uses the clock offset from serverNow. With apiTransport or createHoldEndpoint, serverNow comes from the process that sends the request to ResourceShark. The countdown ticks while subscribed and stops at zero or on dispose(). It can reach zero while step is still held. Use the action’s outcome to learn what ResourceShark accepted.

reset() returns the workflow to idle, clears its hold, and immediately stops tracking the current write. It keeps slot results, and in-flight slot reads still count toward pending. The write can still finish, and the workflow discards its state update.

If place() was in flight, its promise resolves to { status: 'superseded' } when the request finishes. An open hold stays reserved until it is resolved or reaches expiresAt, even if ResourceShark accepts it after reset. The reset workflow has no hold to release, so release() at that point returns failed with code no_hold. To release through the workflow, wait for place() to return held and call release() before resetting.

Use your own transport

Implement HoldTransport<Place, Extend, Commit> if your app uses a different endpoint. Return the slots or hold and an ISO serverNow on success. Accept the workflow’s attemptKey on writes and use it to identify retries. Support buy only if your transport can consume the given lines with the app’s own evidence and keys. For a refusal, throw an Error with a numeric status and string code. Include errorClass, docs, and details when available.

Outcomes and errors

Each action resolves to an outcome with a status field. An identical write shares an in-flight request. A different write during that request returns failed with code busy. A write retried with the same input after network_error reuses its attempt key. Any other answer, a success or a refusal, ends the attempt, and the next write gets a new key.

Action Outcome
listSlots(query) listed carries the slots.
place(input) held carries the hold. short carries the lines ResourceShark could not cover and, when present, nextSupplyAt. superseded signals a reset during the write.
extend(input) extended carries the updated hold. expired carries expiresAt. resolved carries the hold’s first resolution.
release() released carries the released hold. resolved carries the hold’s first resolution.
commit(input) committed carries the hold, movements, and duplicate: true on a replay ResourceShark reports. expired carries availability and a possible buy. resolved carries the hold’s first resolution.

All actions can return failed with a WorkflowError. Choose what to show by error.code. While a hold is still open, a new placement returns hold_open. An action that needs a hold returns no_hold when it has no eligible hold. With CommitInput, omit lines or pass [] to take every line in full. A nonempty list must name every line. A quantity of 0 gives a line back. The workflow rejects missing lines from a list of claim IDs before sending the commit.

ResourceShark refuses a short placement in full. The workflow returns short for insufficient_supply, exhausted_until_supply, and assignment_infeasible. ResourceShark answers assignment_infeasible for an instance that is unavailable. Read those short lines the same way as for insufficient_supply. Your app chooses the next request, such as a smaller quantity or another slot. The SDK refusal readers read the short lines and nextSupplyAt from a refusal.

You can still call commit after ResourceShark refuses an extension as expired. An expired commit carries line availability when ResourceShark reports it. With endpointTransport, buy is null. Use commitHold in your server’s payment handler when your app needs to decide whether to consume the lines after expiry.