# 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

```bash
npm install @nibify/sdk
```

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()

```ts
new Nibify(options?: NibifyOptions)

interface NibifyOptions {
  apiKey?: string;
  baseUrl?: string;
  maxRetries?: number;
  fetch?: typeof fetch;
}
```

- `apiKey`: a `sk_test_…` or `sk_live_…` key. Left out, the client reads `NIBIFY_API_KEY`.
- `baseUrl`: left out, `NIBIFY_BASE_URL`, then `https://api.nibify.app`, exported as `DEFAULT_BASE_URL`. A trailing `/` is dropped.
- `maxRetries`: how many times a call that is retried at all is retried, after a network failure, a `429` or a `5xx`. Defaults to `3`. The long polls of `ask()` and `wait()` keep a budget of their own. Which calls are retried is under [NibifyError](#nibifyerror).
- `fetch`: the `fetch` the client sends with. Defaults to the global one.

With the variables set, the constructor takes nothing:

```bash
export NIBIFY_API_KEY=sk_test_…
```

```ts
import { Nibify } from '@nibify/sdk';

const nibify = new Nibify();
```

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

```ts
readonly environment: 'test' | 'live';
readonly baseUrl: string;
readonly requests: Requests;
readonly threads: Threads;
readonly webhooks: { verify(options: VerifyOptions): Promise<WebhookEvent> };
```

`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()

```ts
ask(options: AskOptions): Promise<AskResult>
ask<const S extends Surface>(surface: S, options: AskOptions<S>): Promise<AskResult>
```

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`.

TypeScript:

```ts
import { Nibify } from '@nibify/sdk';

const nibify = new Nibify({ apiKey: 'sk_test_…' });

const result = await nibify.ask({
  sender: { name: 'invoice-flow' },
  notification: {
    title: 'Kiwi Studio invoice: $1,240, due Oct 30',
    body: 'Read from the PDF. File it as consulting, or fix it first.',
    quickActions: [
      { name: 'file', label: 'File it' },
      { name: 'fix', label: 'Fix it' },
    ],
  },
});

if (result.status === 'answered') {
  result.response.actionName; // 'file'
}
```

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.

TypeScript:

```ts
import {
  Button,
  Card,
  CheckBox,
  ChoicePicker,
  Column,
  DateTimeInput,
  Nibify,
  Text,
  TextField,
} from '@nibify/sdk';

const nibify = new Nibify({ apiKey: 'sk_test_…' });

const surface = {
  root: 'root',
  dataModel: {
    amount: '1240',
    due: '2026-10-30',
    category: ['consulting'],
    recurring: false,
  },
  components: [
    Card('root', { child: 'body' }),
    Column('body', {
      children: ['title', 'ask', 'amount', 'due', 'category', 'recurring', 'file'],
    }),
    Text('title', { text: 'Kiwi Studio invoice', variant: 'h4' }),
    Text('ask', { text: 'Check it before I file it.' }),
    TextField('amount', {
      label: 'Amount',
      variant: 'number',
      value: { path: '/amount' },
    }),
    DateTimeInput('due', {
      label: 'Due',
      enableDate: true,
      value: { path: '/due' },
    }),
    ChoicePicker('category', {
      label: 'Category',
      options: [
        { label: 'Software', value: 'software' },
        { label: 'Consulting', value: 'consulting' },
      ],
      value: { path: '/category' },
    }),
    CheckBox('recurring', {
      label: 'Recurring',
      value: { path: '/recurring' },
    }),
    Button('file', {
      variant: 'primary',
      child: 'file-label',
      action: {
        event: {
          name: 'file',
          context: {
            amount: { path: '/amount' },
            due: { path: '/due' },
            category: { path: '/category' },
            recurring: { path: '/recurring' },
          },
        },
      },
    }),
    Text('file-label', { text: 'File it' }),
  ],
};

const result = await nibify.ask(surface, {
  sender: { name: 'invoice-flow' },
  notification: {
    title: 'Kiwi Studio invoice',
    body: 'Check it before I file it.',
  },
});

if (result.status === 'answered') {
  result.response.actionName; // 'file'
  result.response.context; // { amount: '1420', due: '2026-10-30', category: ['consulting'], recurring: false }
}
```

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](#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.

```ts
{
  sender: { name: string; icon?: string };
  notification: {
    title: string;
    body: string;
    quickActions?: { name: string; label: string }[];
  };
  priority?: 'low' | 'normal' | 'high';
  threadKey?: string;
  expiresAt?: string;
  callbackUrl?: string;
  timeout?: number;
  signal?: AbortSignal;
}
```

- `sender.name`: who is asking, as the phone shows it: `invoice-flow`.
- `notification`: the push. `quickActions` are its buttons on the lock screen.
- `priority`: `normal` when left out. `low` arrives without a push; `high` may pass quiet hours.
- `threadKey`: your name for a conversation, up to 200 characters. Requests with the same key are one thread, `vendor:kiwi-studio` for 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()](#webhooks-verify).
- `timeout` and `signal`: how long this call waits. They are not sent.

### Outcomes

```ts
type AskResult = Answered | Unanswered | TimedOut;
```

`ask()` resolves with an outcome and never rejects on one. It rejects only when a call fails: see [NibifyError](#nibifyerror).

- `answered`: `result.response` holds the answer: `responseId`, `actionName`, `sourceComponentId`, `context`, `clientTimestamp` and `answeredAt`.
- `expired`, `dismissed`, `cancelled`: the Request ended without an answer, because its `expiresAt` passed, the person dismissed it, or you cancelled it. `response` is `null`.
- `timeout`: this call stopped waiting. It is not `expired`: the Request is still pending on the server, the person can still answer it, and `result.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](#the-request-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:

TypeScript:

```ts
import { Button, Card, Column, Nibify, Row, Text } from '@nibify/sdk';

const nibify = new Nibify({ apiKey: 'sk_test_…' });

const surface = {
  root: 'root',
  dataModel: {},
  components: [
    Card('root', { child: 'body' }),
    Column('body', { children: ['title', 'text', 'actions'] }),
    Text('title', { text: 'Include paywalled sources?', variant: 'h4' }),
    Text('text', { text: 'Three of the twelve sources need a login.' }),
    Row('actions', { justify: 'end', children: ['button-0', 'button-1'] }),
    Button('button-0', {
      variant: 'primary',
      child: 'button-0-label',
      action: { event: { name: 'include', context: {} } },
    }),
    Text('button-0-label', { text: 'Include them' }),
    Button('button-1', {
      variant: 'default',
      child: 'button-1-label',
      action: { event: { name: 'skip', context: {} } },
    }),
    Text('button-1-label', { text: 'Skip them' }),
  ],
};

const result = await nibify.ask(surface, {
  sender: { name: 'research-agent' },
  notification: {
    title: 'Include paywalled sources?',
    body: 'Three of the twelve sources need a login.',
    quickActions: [
      { name: 'include', label: 'Include them' },
      { name: 'skip', label: 'Skip them' },
    ],
  },
  expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
});

if (result.status === 'expired') {
  // nobody answered in time: go on without it
}
```

### 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.

```ts
const result = await nibify.ask({
  sender: { name: 'invoice-flow' },
  notification: {
    title: 'Kiwi Studio invoice: $1,240, due Oct 30',
    body: 'Read from the PDF. File it as consulting, or fix it first.',
    quickActions: [
      { name: 'file', label: 'File it' },
      { name: 'fix', label: 'Fix it' },
    ],
  },
  timeout: 5 * 60 * 1000,
});

if (result.status === 'timeout') {
  const later = await result.request.wait();
}
```

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()

```ts
notify(options: NotifyOptions): Promise<NotificationCreated>
```

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:

TypeScript:

```ts
import { Card, Column, Nibify, Text } from '@nibify/sdk';

const nibify = new Nibify({ apiKey: 'sk_test_…' });

const surface = {
  root: 'root',
  dataModel: {},
  components: [
    Card('root', { child: 'body' }),
    Column('body', { children: ['title', 'text'] }),
    Text('title', { text: 'Kiwi Studio invoice filed', variant: 'h4' }),
    Text('text', { text: '$1,420, consulting, due Oct 30.' }),
  ],
};

await nibify.notify({
  sender: { name: 'invoice-flow' },
  notification: {
    title: 'Kiwi Studio invoice filed',
    body: '$1,420, consulting, due Oct 30.',
  },
  surface,
});
```

`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:

```ts
{
  messageId: string;
  threadId: string;
  sequence: number;
  interactionType: 'informational';
  createdAt: string;
  environment: 'test' | 'live';
  minCatalogVersion: number | null;
  warnings: { code: 'catalog_version_too_low'; message: string }[];
}
```

`notify()` is never retried: the endpoint takes no `Idempotency-Key`, and a retry after a lost answer would notify twice.

## The Request handle

```ts
class RequestHandle {
  readonly id: string;
  wait(options?: { timeout?: number; signal?: AbortSignal }): Promise<AskResult>;
  cancel(): Promise<Withdrawn>;
  nudge(): Promise<RequestState>;
}
```

Every outcome of `ask()`, every result of `getRequest()` and every row of `requests.list()` carries one, as `request`. `id` is the `requestId`.

### wait()

```ts
wait(options?: { timeout?: number; signal?: AbortSignal }): Promise<AskResult>
```

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()

```ts
cancel(): Promise<Withdrawn>
```

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.

```ts
import { NibifyError } from '@nibify/sdk';

try {
  await result.request.cancel();
} catch (error) {
  if (error instanceof NibifyError && error.code === 'request_already_answered') {
    const answered = await nibify.getRequest(result.request.id);
  }
}
```

`cancel()` is never retried: a retry after a lost answer would find the Request already cancelled, and reject with `409`.

### nudge()

```ts
nudge(): Promise<RequestState>
```

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()

```ts
getRequest(id: string): Promise<RequestState>
```

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.

```ts
type RequestState = {
  requestId: string;
  status: 'pending' | 'answered' | 'expired' | 'dismissed' | 'cancelled';
  createdAt: string;
  expiresAt: string | null;
  environment: 'test' | 'live';
  deliveredAt: string | null;
  readAt: string | null;
  contentDeletedAt: string | null;
  response: {
    responseId: string;
    actionName: string;
    sourceComponentId: string;
    context: Record<string, unknown> | null;
    clientTimestamp: string;
    answeredAt: string;
  } | null;
  request: RequestHandle;
};
```

`deliveredAt` and `readAt` are the receipts: when a phone received the push, and when the person opened the Request.

## requests.list()

```ts
requests.list(options?: RequestListOptions): AsyncGenerator<RequestState, void, undefined>
```

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:

```ts
for await (const pending of nibify.requests.list({
  status: 'pending',
  threadKey: 'vendor:kiwi-studio',
})) {
  await pending.request.cancel();
}
```

## threads.list()

```ts
threads.list(options?: ThreadListOptions): AsyncGenerator<Thread, void, undefined>
```

Every thread, the one that last spoke first. `pageSize` works as in `requests.list()`.

```ts
type Thread = {
  threadId: string;
  threadKey: string | null;
  environment: 'test' | 'live';
  messageCount: number;
  createdAt: string;
  lastMessage: ThreadMessage;
};
```

A Request sent without a `threadKey` is a thread of its own, with `threadKey: null`.

## threads.get()

```ts
threads.get(key: string, options?: ThreadGetOptions): Promise<ThreadHistory>
```

A thread by its `threadKey`, with its messages oldest first in `messages`, an async iterable that fetches the pages as you walk it.

- `after`: the `sequence` of the last message you already hold. Only later ones come back.
- `pageSize`: as in `requests.list()`.

```ts
const thread = await nibify.threads.get('vendor:kiwi-studio');

for await (const message of thread.messages) {
  message.sequence; // 1, 2, …
  message.notification.title; // 'Kiwi Studio invoice: $1,240, due Oct 30'
  message.status; // 'answered'
}
```

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()

```ts
webhooks.verify(options: VerifyOptions): Promise<WebhookEvent>

interface VerifyOptions {
  body: string;
  signature: string | null | undefined;
  secret: string;
  tolerance?: number;
}
```

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`: the `Nibify-Signature` header.
- `secret`: the project's `whsec_…` signing secret.
- `tolerance`: how many seconds the signature's time may differ from now, either way. Defaults to `300`, exported as `DEFAULT_TOLERANCE_SECONDS`.

`invoice-flow` asked with a `callbackUrl` and stopped waiting. The answer arrives at its handler:

```ts
import { webhooks } from '@nibify/sdk';

export async function POST(request: Request): Promise<Response> {
  const event = await webhooks.verify({
    body: await request.text(),
    signature: request.headers.get('nibify-signature'),
    secret: process.env.NIBIFY_WEBHOOK_SECRET!,
  });

  if (event.type === 'message.answered') {
    event.data.response.actionName; // 'file'
  }
  return new Response(null, { status: 204 });
}
```

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 than `tolerance`. A replay, or a clock that is off.
- `webhook_signature_missing`, `webhook_signature_malformed`: no header, or no `t=` and `v1=` in it.
- `webhook_secret_missing`: no secret was passed.
- `webhook_body_not_raw`: `body` is 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

```ts
class NibifyError extends Error {
  readonly name: 'NibifyError';
  readonly status: number | null;
  readonly code: string;
  readonly details: ApiErrorDetail[];
  readonly retryAfterSeconds: number | undefined;
}

type ApiErrorDetail = {
  pointer: string;
  message: string;
  component?: string;
  property?: string;
};
```

Every failure the SDK reports is a `NibifyError`: what the API refused, and a call that never reached it.

- `status`: the HTTP status, or `null` when no HTTP answer came back. A network failure is `network_error`, with the cause in `cause`.
- `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, `pointer` a dotted path into what you sent, such as `surface.file.variant` or `notification.quickActions[1].name`. A surface that fails the catalog also names the `component` by its `id`, and the `property`. The codes are in [Errors and rate limits](https://nibify.app/docs/errors-and-rate-limits).
- `retryAfterSeconds`: the `Retry-After` of a `429`.

```ts
import { NibifyError } from '@nibify/sdk';

try {
  await nibify.ask(surface, options);
} catch (error) {
  if (error instanceof NibifyError && error.code === 'surface_invalid') {
    for (const detail of error.details) console.error(detail.pointer, detail.message);
  }
  throw error;
}
```

### 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 `maxRetries` times: the creation in `ask()`, with its `Idempotency-Key`; `getRequest()`; `requests.list()`, `threads.list()` and `threads.get()`.
- Retried up to 10 times in a row, whatever `maxRetries` says: the long polls of `ask()` and `wait()`. 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 answers `pending` starts the count again. The wait stays inside its `timeout` and `signal`: one that ends while retrying resolves with `timeout`. Past the tenth retry, it rejects with the `NibifyError` of the last attempt.
- Never retried: `notify()`, `cancel()` and `nudge()`. A retry after a lost answer would notify twice, answer `409`, or push twice.

## Component constructors

```ts
Text(id: ComponentId, props: TextProps): TextComponent
Button<const Name extends string>(
  id: ComponentId,
  props: ButtonProps & Dispatches<Name>,
): ButtonComponent & Dispatches<Name>
Divider(id: ComponentId, props?: DividerProps): DividerComponent
```

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](https://nibify.app/catalog). The constructors are generated from it: a component added to the catalog is a constructor in the next release.

## Exported types

- `Surface`: what `ask()` and `notify()` take as a surface, `root`, `dataModel` and `components`.
- `Component`, `ComponentType`: any component, and the name of one. Each component also has its `…Props` and `…Component` types: `TextProps`, `TextComponent`, and so on.
- `ActionNameOf<S>`: the action names surface `S` dispatches.
- `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 as `openapi-typescript` describes it, for whatever the client does not wrap.

## Next

- [Wait for the answer](https://nibify.app/docs/wait-for-the-answer): Get the answer back by waiting for it with ask() or the long poll, or by a callback when your code cannot wait.
- [Webhooks and signatures](https://nibify.app/docs/webhooks-and-signatures): The events Nibify sends, how to verify their Nibify-Signature, and what happens when your server does not answer.
- [Errors and rate limits](https://nibify.app/docs/errors-and-rate-limits): The error body, what the SDK does with it, every code an agent can receive, and the limits behind a 429.
- [Requests API](https://nibify.app/docs/rest/requests): Every /v1/requests endpoint: list the Requests of this Project, create a Request, read a Request, withdraw a Request, re-notify a pending Request, await the outcome of a Request.
