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
idempotencyKeyon a write ortokento replace the client’s token for that call. Retrying a write says what a retry with the same key answers.auth.requestCode,auth.verifyCode, andinvitations.previewtake no such argument. - Errors: an HTTP refusal throws
IdentityhoundApiError, withcodeandstatus, plusdetailsand adocsURL when the API supplies them. The errors page lists every code and what to do. - Options:
baseUrlis IdentityHound’s API root and defaults tohttps://api.agentpost.tools/v1/identity. Against an Agentpost API running on your machine, it is that API’s address with the same path, such ashttp://localhost:3012/v1/identity. AbaseUrlwithout that path, such ashttp://localhost:3012, throws when the client is created, since the SDK also reaches Agentpost’s/v1/user-tokensbeside it.createIdentity,IdentityhoundProvider, and the server helpers take the samebaseUrland check it the same way.fetchreplaces the globalfetch.headersadds to the headers each call sends and replacesaccept; the token’sauthorization, theidempotency-key, and a body’scontent-typestill win.
createIdentity
Import createIdentity from @agentpost-tools/identityhound-sdk/workflows.
- Who is signed in:
identity.getSnapshot().sessionisloading,signed_out,signed_inwith theprincipal, orerrorwhen the identity couldn’t load the session.identity.subscribefollows 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)runscallwith{ 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 returnsnull, the identity becomessigned_out. - The session token:
identity.getSessionToken()returns the session token itself, for your own API, withdeviceSession({ bearer: 'session' }). It makes no request, and returnsnullwhen nobody is signed in. Any other strategy rejects withsession_token_unavailable. - Signing out:
identity.signOut()asks the strategy to end the session and sets the identity tosigned_outwhen 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
erroris a union of the codes that workflow can fail with, such asEmailCodeError, sodetailshas a type once you checkcode:code_invalidhasdetails.guessesLeft,throttledhasdetails.retryAfter, andresend_too_soonhasdetails.resendIn. A code the workflow doesn’t know, such as one from your own server, comes asunknown, with the original indetails.code.messageis for logs and agents, not for the screen. - OAuth across its redirect:
storagekeeps an OAuth sign-in while the provider’s page is open. PasssessionStorageon 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, passprofileFromProvider: { name, avatar }.nameis the provider field that becomesdisplayName,'displayName'or'login', andavatar: truecopies the picture toavatarUrl. Both are required, and nothing is copied unless you set it. When OAuth answerssignedUp: true, including for a guest upgrade, the identity readsGET /me/identitiesand sendsPATCH /meif 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.