> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gavai.io/llms.txt
> Use this file to discover all available pages before exploring further.

# @gavai/sdk

> High-level typed TypeScript client for the gavAI public REST API.

export const ExpectedOutput = ({caption = "Expected output", children}) => <div className="gv-output">
    <div className="gv-output__label">
      <svg className="gv-output__icon" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <polyline points="15 10 20 15 15 20" />
        <path d="M4 4v7a4 4 0 0 0 4 4h12" />
      </svg>
      <span>{caption}</span>
    </div>
    <div className="gv-output__body">{children}</div>
  </div>;

export const APIBadge = ({method = "GET", path, scope}) => {
  const m = method.toUpperCase();
  return <span className="gv-api-badge">
      <span className={`gv-api-badge__method gv-api-badge__method--${m.toLowerCase()}`}>
        {m}
      </span>
      <code className="gv-api-badge__path">{path}</code>
      {scope && <span className="gv-api-badge__scope">
          <span className="gv-api-badge__scope-label">scope</span>
          <code>{scope}</code>
        </span>}
    </span>;
};

export const Def = ({term, type, defaultValue, required, children}) => <>
    <dt className="gv-def-list__term">
      <span className="gv-def-list__name">{term}</span>
      {type && <span className="gv-def-list__type">{type}</span>}
      {required && <span className="gv-def-list__required">required</span>}
      {defaultValue !== undefined && <span className="gv-def-list__default">
          default <code>{defaultValue}</code>
        </span>}
    </dt>
    <dd className="gv-def-list__description">{children}</dd>
  </>;

export const DefList = ({children}) => <dl className="gv-def-list">{children}</dl>;

export const BrandCard = ({eyebrow, title, href, icon, badge, cta, featured = false, horizontal = false, children}) => {
  const classes = ["gv-card", featured && "gv-card--featured", horizontal && "gv-card--horizontal"].filter(Boolean).join(" ");
  const inner = <>
      {icon && <span className="gv-card__icon" aria-hidden="true">
          <Icon icon={icon} />
        </span>}
      <div className="gv-card__main">
        {(eyebrow || badge) && <div className="gv-card__meta">
            {eyebrow && <Eyebrow label={eyebrow} tone="muted" />}
            {badge && <span className="gv-card__badge">{badge}</span>}
          </div>}
        <h3 className="gv-card__title">{title}</h3>
        {children && <div className="gv-card__body">{children}</div>}
        {cta && <span className="gv-card__cta">
            {cta}
            <svg className="gv-card__cta-arrow" viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <line x1="7" y1="17" x2="17" y2="7" />
              <polyline points="7 7 17 7 17 17" />
            </svg>
          </span>}
      </div>
    </>;
  return href ? <a className={classes} href={href}>
      {inner}
    </a> : <div className={classes}>{inner}</div>;
};

export const ArrowItem = ({children}) => <li className="gv-arrow-item">
    <span className="gv-arrow-item__arrow" aria-hidden="true">{"↳︎"}</span>
    <span className="gv-arrow-item__content">{children}</span>
  </li>;

export const ArrowList = ({children}) => <ul className="gv-arrow-list">{children}</ul>;

export const Eyebrow = ({label, tone = "default"}) => <div className={`gv-eyebrow gv-eyebrow--${tone}`}>
    <span className="gv-eyebrow__bar" aria-hidden="true" />
    <span className="gv-eyebrow__label">{label}</span>
  </div>;

<Eyebrow label="SDK" />

`@gavai/sdk` is the official high-level client for the gavAI public REST API. It wraps every resource in typed methods, ships request and response shapes in the same package (no separate `@types` install), and authenticates with a bearer token. By the end of this page you will have it installed, authenticated, and calling the 14 resource namespaces it exposes.

## Install

<CodeGroup>
  ```sh bun theme={null}
  bun add @gavai/sdk
  ```

  ```sh npm theme={null}
  npm install @gavai/sdk
  ```

  ```sh pnpm theme={null}
  pnpm add @gavai/sdk
  ```

  ```sh yarn theme={null}
  yarn add @gavai/sdk
  ```
</CodeGroup>

## Minimal example

One file, one read call. If this prints your `user_id`, the SDK is wired correctly.

The call below maps to <APIBadge method="GET" path="/v1/me" scope="me:read" />.

```ts client.ts theme={null}
import { Gavai } from "@gavai/sdk";

const gv = new Gavai({
  apiKey: process.env.GAVAI_API_KEY, // gak_live_* or gak_test_*
});

const me = await gv.me.get();
console.log(me.user_id);
```

Run it: `bun run client.ts`.

<ExpectedOutput>
  ```text theme={null}
  usr_01HXR8K2M4...
  ```
</ExpectedOutput>

## Authentication

The constructor accepts exactly one token. Pass `apiKey` or `sessionToken` — never both.

<ArrowList>
  <ArrowItem>**`apiKey`** — a workspace API key in `gak_live_*` (production) or `gak_test_*` (sandbox) format. Use for backend services, CI pipelines, and any non-interactive caller.</ArrowItem>
  <ArrowItem>**`sessionToken`** — an OAuth session token in `gst_*` format. Use for CLI tools and IDE integrations that authenticate as a logged-in user.</ArrowItem>
</ArrowList>

See [Authentication](/api-reference/authentication) for the full token lifecycle — scopes, rotation, and revocation.

## The 14 resource namespaces

Every resource hangs off the `Gavai` instance as a typed namespace. Each namespace exposes the methods listed in the [API reference](/api-reference/introduction) for that resource.

<ArrowList>
  <ArrowItem>`gv.me` — current principal: user ID, token ID, active scopes</ArrowItem>
  <ArrowItem>`gv.workspaces` — list, fetch, and switch between workspaces</ArrowItem>
  <ArrowItem>`gv.tokens` — create, inspect, rotate, and revoke workspace API keys</ArrowItem>
  <ArrowItem>`gv.pages` — read, patch (RFC 6902), publish, and roll back page documents</ArrowItem>
  <ArrowItem>`gv.theme` — read and update the workspace theme</ArrowItem>
  <ArrowItem>`gv.forms` — list forms and retrieve submission records</ArrowItem>
  <ArrowItem>`gv.agents` — create, manage, and query run history for agents</ArrowItem>
  <ArrowItem>`gv.secrets` — read, write, rotate, and delete per-workspace secrets</ArrowItem>
  <ArrowItem>`gv.domains` — attach custom domains and manage DNS verification</ArrowItem>
  <ArrowItem>`gv.logs` — list, search, and tail workspace logs</ArrowItem>
  <ArrowItem>`gv.deployments` — inspect status, cancel in-flight runs, or promote a build</ArrowItem>
  <ArrowItem>`gv.billing` — read the current plan, usage, and invoices</ArrowItem>
  <ArrowItem>`gv.monetization` — manage Stripe Connect onboarding for end users</ArrowItem>
  <ArrowItem>`gv.approvals` — inspect and action the agent-action approval queue</ArrowItem>
</ArrowList>

## Constructor options

Everything is passed to `new Gavai({ ... })`.

<DefList>
  <Def term="apiKey" type="string">
    Workspace API key — `gak_live_*` or `gak_test_*`. Mutually exclusive with `sessionToken`. Required if `sessionToken` is not provided.
  </Def>

  <Def term="sessionToken" type="string">
    OAuth session token — `gst_*`. Mutually exclusive with `apiKey`. Required if `apiKey` is not provided.
  </Def>

  <Def term="baseUrl" type="string" defaultValue="https://api.gavai.app/v1">
    Override the API base URL. Use for pointing at a staging environment.
  </Def>

  <Def term="fetch" type="typeof fetch">
    Inject a custom fetch implementation. Use in test environments or runtimes without a native `fetch`.
  </Def>

  <Def term="hooks" type="object">
    Lifecycle hooks for cross-cutting concerns: `beforeRequest` (called before every request), `afterResponse` (after every successful response), `onError` (when any error is thrown).
  </Def>

  <Def term="timeoutMs" type="number">
    Request timeout in milliseconds. Requests that exceed this limit throw a `GavaiNetworkError`.
  </Def>
</DefList>

## A composite example

This block shows the patterns you will use most: construct, inject hooks, call multiple namespaces, narrow errors by class.

```ts composite.ts theme={null}
import { Gavai, GavaiError, GavaiNetworkError } from "@gavai/sdk";

const gv = new Gavai({
  apiKey: process.env.GAVAI_API_KEY,
  baseUrl: process.env.GAVAI_BASE_URL, // optional override
  timeoutMs: 10_000,
  hooks: {
    beforeRequest: (req) => console.log("[req]", req.method, req.url),
    onError: (err) => console.error("[err]", err.message),
  },
});

try {
  const me = await gv.me.get();
  const { workspaces } = await gv.workspaces.list();

  await gv.pages.patch({
    workspace: workspaces[0].slug,
    id: "page_01H...",
    operations: [
      { op: "replace", path: "/blocks/0/props/title", value: "Hello" },
    ],
  });

  await gv.pages.publish({ workspace: workspaces[0].slug });
  console.log("Published as", me.user_id);
} catch (e) {
  if (e instanceof GavaiNetworkError) {
    // Transient — retry with backoff
  } else if (e instanceof GavaiError && e.code === "rate_limited") {
    // Read Retry-After from e.headers and back off
  } else {
    throw e;
  }
}
```

## Errors at a glance

The SDK throws `GavaiError` for API-level failures and `GavaiNetworkError` for transport failures (DNS, connection refused, timeout). `GavaiError` carries `status`, `code`, `message`, `details`, and `headers` — `headers["x-request-id"]` is what you attach to a support ticket.

Common `code` values: `token_expired`, `insufficient_scope`, `rate_limited`, `workspace_forbidden`, `not_found`.

Full catch patterns and retry guidance live in [Error handling](/sdks/error-handling).

## Versioning

The public API is versioned by URL prefix (`/v1`, `/v2`, …). Each major SDK version tracks the matching API version — they ship together. Mixing major SDK and API versions is not supported.

## Next steps

<Columns cols={2}>
  <BrandCard title="Error handling" href="/sdks/error-handling">
    Typed error classes, retry-safe patterns, and what to log when something fails.
  </BrandCard>

  <BrandCard title="Examples" href="/sdks/examples">
    Copy-paste recipes — patching pages, paginating logs, idempotent writes, rate-limit handling.
  </BrandCard>
</Columns>
