SDK
Every method and type @nibify/sdk exports: the client, ask(), notify(), the Request handle, the lists, webhooks.verify() and the component constructors.
@nibify/sdk is the TypeScript client of the agent API. This page lists what the package exports, method by method, with its signatures and types. The examples follow invoice-flow, the agent that reads Kiwi Studio's invoice and asks before filing it.
Install
The package is ESM only, with no runtime dependencies. It runs on Node 20.3 or later, Bun, Deno and Cloudflare Workers: anything with fetch and Web Crypto.
It does not belong in the browser. The client needs your API key, and a key in a page is a key anyone who opens the page can read. Call Nibify from your server, your worker or your agent.
The client
new Nibify()
apiKey: ask_test_…orsk_live_…key. Left out, the client readsNIBIFY_API_KEY.baseUrl: left out,NIBIFY_BASE_URL, thenhttps://api.nibify.app, exported asDEFAULT_BASE_URL. A trailing/is dropped.maxRetries: how many times a call that is retried at all is retried, after a network failure, a429or a5xx. Defaults to3. The long polls ofask()andwait()keep a budget of their own. Which calls are retried is under NibifyError.fetch: thefetchthe client sends with. Defaults to the global one.
With the variables set, the constructor takes nothing:
The constructor throws a NibifyError with status: null when there is no key (missing_api_key), or when the key starts with neither sk_test_ nor sk_live_ (invalid_api_key). It makes no call: a revoked key fails on the first request, with 401.
Properties
environment comes from the key's prefix. Every Request the client creates lives in that environment, and the phone shows it with that tag.
ask()
Creates a Request and waits for its outcome. It has two forms.
Without a surface, the person answers from the notification's buttons, on the lock screen. The answer comes back with sourceComponentId: 'notification' and an empty context.
With a surface, the surface comes first, and the person opens it to answer. Here the invoice is a form: the person corrects the amount and files it, and context carries the fields the File it button names.
With a surface, each quickAction must name an action the surface dispatches; the API refuses any other with 422 and surface_invalid. The types hold you to it too: name is the union of the action names in the surface, when the surface is written in the call or built with the component constructors. A surface typed as Surface, or read from JSON, gives string, and the API is the only check. Without a surface, any name goes.
Options
AskOptions is the body of POST /v1/requests without its surface, plus two options for the wait.
sender.name: who is asking, as the phone shows it:invoice-flow.notification: the push.quickActionsare its buttons on the lock screen.priority:normalwhen left out.lowarrives without a push;highmay pass quiet hours.threadKey: your name for a conversation, up to 200 characters. Requests with the same key are one thread,vendor:kiwi-studiofor everything about that vendor. Left out, the Request is a thread of its own.expiresAt: an ISO 8601 time. Left out, the Request never expires.callbackUrl: where Nibify posts the outcome, signed. See webhooks.verify().timeoutandsignal: how long this call waits. They are not sent.
Outcomes
ask() resolves with an outcome and never rejects on one. It rejects only when a call fails: see NibifyError.
answered:result.responseholds the answer:responseId,actionName,sourceComponentId,context,clientTimestampandansweredAt.expired,dismissed,cancelled: the Request ended without an answer, because itsexpiresAtpassed, the person dismissed it, or you cancelled it.responseisnull.timeout: this call stopped waiting. It is notexpired: the Request is still pending on the server, the person can still answer it, andresult.request.wait()waits again.
Every outcome but timeout also carries the fields of the Request: requestId, createdAt, expiresAt, environment, deliveredAt, readAt, contentDeletedAt. And every outcome carries request, the handle to act on the Request later.
An expiry is an outcome, not an error. When research-agent asks whether to include paywalled sources and nobody answers within the hour, it goes on without them:
timeout and signal
Left alone, ask() waits as long as the Request stays pending, days if need be. It holds long polls of up to 30 seconds, one after another, and returns the moment the Request ends.
timeout, in milliseconds, and signal stop the wait without touching the Request. Either one resolves with timeout, and result.request.wait() picks the wait up again.
A signal that aborts before the Request exists rejects ask() with the signal's reason: there is no Request yet to wait for.
Retries
ask() sends an Idempotency-Key it makes up, and retries the creation with the same key after a network failure, a 429 or a 5xx. However many times it is sent, there is one Request.
notify()
Tells the person something and asks nothing back: the body of POST /v1/notifications. Once Kiwi Studio's invoice is filed, invoice-flow says so:
NotifyOptions takes sender, notification with title and body, priority, threadKey and surface. The surface goes inside the options, and it may not dispatch an action: one that does is a request, and the API answers surface_invalid. quickActions, expiresAt and callbackUrl are refused by name. A threadKey puts the notification in that thread, after the request it follows.
It resolves with what was created:
notify() is never retried: the endpoint takes no Idempotency-Key, and a retry after a lost answer would notify twice.
The Request handle
Every outcome of ask(), every result of getRequest() and every row of requests.list() carries one, as request. id is the requestId.
wait()
Waits for the outcome, as ask() does after it creates the Request, with the same timeout and signal. On a Request that has already ended, it resolves at once.
cancel()
Withdraws a pending Request: its status becomes cancelled, the card leaves the phone, and an ask() waiting on it resolves with cancelled. It resolves with the Request as it now stands, and request.
A Request that ended first rejects with a NibifyError with status 409, whose code names the state that won: request_already_answered, request_already_expired, request_already_dismissed or request_already_cancelled. With request_already_answered the person answered before the cancel arrived, and the answer is there to read.
cancel() is never retried: a retry after a lost answer would find the Request already cancelled, and reject with 409.
nudge()
Sends the push of a pending Request again. Nothing else changes: same Request, same status, same expiry, and the push keeps its priority and quiet hours. It resolves with the Request as it stands. On a Request that has ended, it rejects with 409, like cancel(). It is never retried: a retry could push twice.
getRequest()
The Request as it stands now, without waiting. status may be pending. Use it when the outcome reached you some other way, a callback or a list, or to read an answer after a restart: the answer is stored on the server the moment it is given.
deliveredAt and readAt are the receipts: when a phone received the push, and when the person opened the Request.
requests.list()
Every Request of the key's project and environment, newest first. The iterator fetches the pages as you walk it, until the last one.
status: one of the five.threadKey: only the Requests of that thread.createdAfter,createdBefore: ISO 8601 times.pageSize: how many rows each call fetches, from 1 to 100. It does not limit the walk.
The invoice was paid by bank transfer, so nothing in Kiwi Studio's thread needs an answer any more:
threads.list()
Every thread, the one that last spoke first. pageSize works as in requests.list().
A Request sent without a threadKey is a thread of its own, with threadKey: null.
threads.get()
A thread by its threadKey, with its messages oldest first in messages, an async iterable that fetches the pages as you walk it.
after: thesequenceof the last message you already hold. Only later ones come back.pageSize: as inrequests.list().
A message holds messageId, sequence, interactionType, status, sender, notification, minCatalogVersion, createdAt, expiresAt, deliveredAt, readAt and contentDeletedAt. status is null for a notification, which asks nothing. The answer is not in the thread: for a message that asks, getRequest(message.messageId) reads it.
A thread without a key has no address here: read its Request with getRequest().
webhooks.verify()
Checks the Nibify-Signature of a callback and resolves with the event. It uses Web Crypto only, so it is asynchronous and runs wherever the client does. It is exported on its own, so a server that only receives needs no API key, and it is also nibify.webhooks.verify().
body: the request body exactly as it arrived, as text. A body parsed and serialised again is not the bytes that were signed, and never verifies.signature: theNibify-Signatureheader.secret: the project'swhsec_…signing secret.tolerance: how many seconds the signature's time may differ from now, either way. Defaults to300, exported asDEFAULT_TOLERANCE_SECONDS.
invoice-flow asked with a callbackUrl and stopped waiting. The answer arrives at its handler:
When the signature does not hold, verify() rejects with a NibifyError with status: null and one of these codes:
webhook_signature_mismatch: the body is not the bytes that were sent, or the secret is not this project's.webhook_timestamp_out_of_tolerance: the signature is genuine, but older or newer thantolerance. A replay, or a clock that is off.webhook_signature_missing,webhook_signature_malformed: no header, or not=andv1=in it.webhook_secret_missing: no secret was passed.webhook_body_not_raw:bodyis not a string.webhook_payload_invalid: the signed body is not a Nibify event.
Delivery is at least once: the same event can arrive twice, with the same event.id. Skip an id you have handled.
The event types: WebhookEvent is any of them, and WebhookEventType their names. MessageAnswered is message.answered; MessageUnanswered is message.expired, message.dismissed and message.cancelled; MessageReceipt is message.delivered and message.read, which go only to a webhook endpoint of the project, never to a callbackUrl.
NibifyError
Every failure the SDK reports is a NibifyError: what the API refused, and a call that never reached it.
status: the HTTP status, ornullwhen no HTTP answer came back. A network failure isnetwork_error, with the cause incause.code: the API's own code whenever it sent one,http_<status>when it did not.details: where the body went wrong, one entry per problem,pointera dotted path into what you sent, such assurface.file.variantornotification.quickActions[1].name. A surface that fails the catalog also names thecomponentby itsid, and theproperty. The codes are in Errors and rate limits.retryAfterSeconds: theRetry-Afterof a429.
Which calls are retried
A retried call is sent again after a network failure, a 429 or a 5xx, after the Retry-After when the API gives one and an exponential backoff when it does not. Any other status rejects at once.
- Retried up to
maxRetriestimes: the creation inask(), with itsIdempotency-Key;getRequest();requests.list(),threads.list()andthreads.get(). - Retried up to 10 times in a row, whatever
maxRetriessays: the long polls ofask()andwait(). A dropped connection says nothing about the Request, so the wait carries on through a restart of the API, for about a minute of backoff. A long poll that answerspendingstarts the count again. The wait stays inside itstimeoutandsignal: one that ends while retrying resolves withtimeout. Past the tenth retry, it rejects with theNibifyErrorof the last attempt. - Never retried:
notify(),cancel()andnudge(). A retry after a lost answer would notify twice, answer409, or push twice.
Component constructors
One constructor per component of the catalog, with the same name: Text, Image, Icon, Divider, Row, Column, List, Card, Button, TextField, CheckBox, ChoicePicker, Slider and DateTimeInput. The first argument is the component's id, the second its props, typed from the catalog. Every one but Divider requires its props. Each returns the JSON you would have written by hand, so constructors and plain objects mix in one surface, and ask() takes either.
Button keeps the name of the action it dispatches as a literal type. That is what lets ask() hold the quickActions to the surface's actions.
There is no Form. A form is a Column or a Card of inputs, and a Button whose action.event.context names their paths, as the invoice above does.
What each component looks like, its props and the JSON it answers with are in the catalog. The constructors are generated from it: a component added to the catalog is a constructor in the next release.
Exported types
Surface: whatask()andnotify()take as a surface,root,dataModelandcomponents.Component,ComponentType: any component, and the name of one. Each component also has its…Propsand…Componenttypes:TextProps,TextComponent, and so on.ActionNameOf<S>: the action names surfaceSdispatches.AskOptions<S>,WaitOptions,NotifyOptions,NotificationCreated,NibifyOptions,Environment.AskResult,Answered,Unanswered,TimedOut,RequestState,Withdrawn.RequestListOptions,Thread,ThreadMessage,ThreadHistory,ThreadListOptions,ThreadGetOptions.VerifyOptions,WebhookEvent,WebhookEventType,WebhookEvents,WebhookResponse,MessageAnswered,MessageUnanswered,MessageReceipt.ApiErrorDetail.paths,operations,components: the agent API asopenapi-typescriptdescribes it, for whatever the client does not wrap.