Skip to content
Agentpost robot in sunglasses on a red circleAgentpost

Clients

The SDK has two clients, createClient and createIdentity; the SDK overview says which to create where.

createClient

Import createClient from @agentpost-tools/identityhound-sdk:

import {
  createClient,
  IdentityhoundApiError,
} from '@agentpost-tools/identityhound-sdk';

const identity = createClient({ token: key });
  • Methods follow the API reference. Each operation’s SDK tab names its method, such as identity.access.check(request), with the same values as its curl example.
  • Another credential: identity.withToken(token) creates a client with the same options and another token, such as a user token.
  • Per call: Most methods take a final options object. Pass idempotencyKey on a write or token to replace the client’s token for that call. Retrying a write says what a retry with the same key answers. auth.requestCode, auth.verifyCode, and invitations.preview take no such argument.
  • Errors: an HTTP refusal throws IdentityhoundApiError, with code and status, plus details and a docs URL when the API supplies them. The errors page lists every code and what to do.
  • Options: baseUrl is IdentityHound’s API root and defaults to https://api.agentpost.tools/v1/identity. Against an Agentpost API running on your machine, it is that API’s address with the same path, such as http://localhost:3012/v1/identity. A baseUrl without that path, such as http://localhost:3012, throws when the client is created, since the SDK also reaches Agentpost’s /v1/user-tokens beside it. createIdentity, IdentityhoundProvider, and the server helpers take the same baseUrl and check it the same way. fetch replaces the global fetch. headers adds to the headers each call sends and replaces accept; the token’s authorization, the idempotency-key, and a body’s content-type still win.

createIdentity

Import createIdentity from @agentpost-tools/identityhound-sdk/workflows.

  • Who is signed in: identity.getSnapshot().session is loading, signed_out, signed_in with the principal, or error when the identity couldn’t load the session. identity.subscribe follows it. identity.load() asks the strategy who the session signs in, so a page can restore its signed-in state after a reload. It mints no user token. identity.load({ verify: false }) answers from what the strategy keeps, with no request when it can; Session strategies says what each strategy does.
  • User tokens: it mints a user token only when a call needs one, keeps it in memory, and mints it again on use when a minute or less is left. identity.asUser(call) runs call with { token } set to that user token, for a client method that takes call options, and mints once more if the token is refused with 401. identity.getUserToken() returns the token itself. When the strategy returns null, the identity becomes signed_out.
  • The session token: identity.getSessionToken() returns the session token itself, for your own API, with deviceSession({ bearer: 'session' }). It makes no request, and returns null when nobody is signed in. Any other strategy rejects with session_token_unavailable.
  • Signing out: identity.signOut() asks the strategy to end the session and sets the identity to signed_out when the strategy succeeds. identity.signOut({ revoke: false }) only forgets the session here, for one your own server already refused; Sign out gives the order and what happens when a step fails.
  • Errors: each workflow’s error is a union of the codes that workflow can fail with, such as EmailCodeError, so details has a type once you check code: code_invalid has details.guessesLeft, throttled has details.retryAfter, and resend_too_soon has details.resendIn. A code the workflow doesn’t know, such as one from your own server, comes as unknown, with the original in details.code. message is for logs and agents, not for the screen.
  • OAuth across its redirect: storage keeps an OAuth sign-in while the provider’s page is open. Pass sessionStorage on the web; it defaults to memory.
  • A new principal’s name from the provider: IdentityHound keeps the provider’s name and picture on the sign-in identity’s profile, not on the principal. To start a principal that signs up with a provider with them, pass profileFromProvider: { name, avatar }. name is the provider field that becomes displayName, 'displayName' or 'login', and avatar: true copies the picture to avatarUrl. Both are required, and nothing is copied unless you set it. When OAuth answers signedUp: true, including for a guest upgrade, the identity reads GET /me/identities and sends PATCH /me if there are fields to copy. It does so before it shows the principal signed in. If the copy fails, sign-in still succeeds with the profile in the sign-in’s answer. A returning principal’s profile is left as it is.

The sign-in, invitation, and workspace workflows, such as createEmailCodeSignIn, run on it, and so do the React hooks in @agentpost-tools/identityhound-react and the email sign-in component. In React, useSession()’s getUserToken, getSessionToken, signOut, and refresh call those identity methods. IdentityhoundProvider takes load, such as { verify: false }, for its first load, or false to leave it to you, and takes an identity you made with createIdentity in place of its options, so code outside React shares it.

Account merging

Use createAccountMerge(identity) from @agentpost-tools/identityhound-sdk/workflows to handle a merge offer from a failed link. It takes the shared, signed-in identity and no options. receiveOffer(error) accepts an SDK error or workflow error, holds a valid offer, and returns true; it returns false when there is no offer, the offer expired, or nobody is signed in. It sends no merge request.

This function adds the workflow to an existing identity. Call verifyAddedEmail with the email, code, and verificationId from the added-email flow:

import {
  createAccountMerge,
  type Identity,
} from '@agentpost-tools/identityhound-sdk/workflows';

export function accountMerging(identity: Identity) {
  const merge = createAccountMerge(identity);

  async function verifyAddedEmail(input: {
    email: string;
    code: string;
    verificationId: string;
  }) {
    try {
      return await identity.asUser((opts) =>
        identity.client.me.verifyEmailCode(input, opts),
      );
    } catch (error) {
      if (!merge.receiveOffer(error)) throw error;
      // Show the offer and ask whether to merge. This call moves nothing.
      return null;
    }
  }

  return {
    merge,
    verifyAddedEmail,
    // Connect these actions to the principal's answer in your app.
    agree: () => merge.confirm(),
    cancel: () => merge.dismiss(),
  };
}

Read merge.getSnapshot() and follow changes with merge.subscribe(listener). Its status is idle, offered, confirming, blocked, merged, or expired. The snapshot holds offer, blockers, result, and error. Keep the offer’s ticket in memory and out of logs. confirm() returns the API’s answer to the merge on success or null with the failure in error. A blocked merge exposes blockers and keeps the offer so you can retry after resolving them, before expiry.

After success, the workflow refreshes the identity and any loaded workspaces. Expired and dismissed offers cannot be confirmed. Repeated confirmations while one runs share its request; receiveOffer returns false and dismiss does nothing while it runs. In React or React Native, useAccountMerge() from @agentpost-tools/identityhound-react returns the same snapshot and the receiveOffer, confirm, and dismiss actions, inside your IdentityhoundProvider.