# TypeScript SDK

`@zksecurity/zkao-sdk` is a typed client for the zkao API. Its types are generated from the [OpenAPI spec](https://docs.zkao.io/openapi/v1.yaml), so every request and response is checked at compile time. It runs on Node 18 or later and in any runtime with `fetch`.

```bash
npm install @zksecurity/zkao-sdk
```

## Create a client

```ts
import { ZkaoClient } from "@zksecurity/zkao-sdk";


const zkao = new ZkaoClient({
  token: process.env.ZKAO_API_TOKEN!,
  projectId: process.env.ZKAO_PROJECT_ID!,
});
```

A client is bound to one project. Every call is scoped to it.

| Option      | Type           | Meaning                                                    |
| ----------- | -------------- | ---------------------------------------------------------- |
| `token`     | `string`       | Project API token, `zkao_proj_<keyId>_<secret>`. Required. |
| `projectId` | `string`       | Id of the project the token belongs to. Required.          |
| `baseUrl`   | `string`       | API base URL, used exactly as given. Optional.             |
| `fetch`     | `typeof fetch` | Custom `fetch`, for tests or proxies. Optional.            |

### Base URL

The client picks its base URL in this order:

1. The `baseUrl` option, used verbatim.
2. The `ZKAO_URL` environment variable, normalized.
3. Production, `https://zkao.io/api/v1` (exported as `DEFAULT_BASE_URL`).

`ZKAO_URL` accepts a bare host, an origin, or a full API URL. A bare host gets `https://`, except localhost, which gets `http://`. `/api/v1` is appended unless the value already ends in `/api/v<n>`. So `staging.zkao.io` becomes `https://staging.zkao.io/api/v1`. A plain `http://` URL to a non-local host logs a warning, since the token would travel unencrypted.

Two helpers expose this logic:

| Function                                           | Meaning                                                                                     |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `normalizeBaseUrl(value: string): string`          | Turn a host, origin, or URL into a full API base URL. Throws on an empty or invalid value.  |
| `resolveBaseUrlFromEnv(env?): string \| undefined` | Read and normalize `ZKAO_URL`, from `env` or `process.env`. Returns `undefined` when unset. |

## Methods

Every method returns a promise. A non-2xx response rejects with [`ZkaoApiError`](https://docs.zkao.io/reference/sdk/#errors). The required token scope is noted where a method needs more than `read`. Each method links to its endpoint in the API reference.

### Token

| Method           | Returns     | Meaning                                                                                                                                                   |
| ---------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getTokenInfo()` | `TokenInfo` | The token’s scopes, repository allowlist, expiry, spend limit, and its project and organization. [API](https://docs.zkao.io/api/operations/gettokeninfo/) |

The standalone `getTokenInfo({ token, baseUrl?, fetch? })` does the same without a project id. Use it to find which project a token belongs to.

### Repositories

| Method                                        | Returns        | Meaning                                                                                                                          |
| --------------------------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `listRepositories()`                          | `Repository[]` | The project’s repositories, or the token’s allowlisted subset. [API](https://docs.zkao.io/api/operations/listrepositories/)      |
| `waitForRepositoryReady(repositoryId, opts?)` | `Repository`   | Block until the repository’s `readiness` is `ready`. See [Polling helpers](https://docs.zkao.io/reference/sdk/#polling-helpers). |

### Guidance

| Method                                                | Returns              | Meaning                                                                                                                          |
| ----------------------------------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `getRepositoryGuidance(repositoryId)`                 | `RepositoryGuidance` | Read a repository’s guidance. [API](https://docs.zkao.io/api/operations/getrepositoryguidance/)                                  |
| `setRepositoryGuidance(repositoryId, content, opts?)` | `SetGuidanceResult`  | Set guidance, or clear it with `null`. Needs `guidance:write`. [API](https://docs.zkao.io/api/operations/setrepositoryguidance/) |

`setRepositoryGuidance` takes `{ expectedContent?: string | null }`. Pass the content you last read, or `null` if it was cleared. The write then fails with `409 conflict` if someone changed it in between. Writing the content already stored is a no-op that returns `unchanged: true`.

```ts
const current = await zkao.getRepositoryGuidance(repoId);
await zkao.setRepositoryGuidance(repoId, `${current.content ?? ""}\nNew note.`, {
  expectedContent: current.content,
});
```

### Audit areas

| Method                                              | Returns                 | Meaning                                                                                                                                                     |
| --------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `listAuditAreas(repositoryId, opts?)`               | `AuditAreaList`         | A repository’s audit areas. `opts.branch` picks the branch whose map gives sizes. [API](https://docs.zkao.io/api/operations/listauditareas/)                |
| `createAuditArea(repositoryId, name, description?)` | `AuditArea`             | Add a custom area. The key is derived from the name. Needs `guidance:write`. [API](https://docs.zkao.io/api/operations/createauditarea/)                    |
| `deleteAuditArea(repositoryId, areaKey)`            | `DeleteAuditAreaResult` | Delete a custom area. An area a scan’s map named is refused with `409`. Needs `guidance:write`. [API](https://docs.zkao.io/api/operations/deleteauditarea/) |

### Continuous Security

A branch defaults to the repository’s default branch.

| Method                                           | Returns                          | Meaning                                                                                                                                                                                                              |
| ------------------------------------------------ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getContinuousTesting(repositoryId, opts?)`      | `ContinuousTesting`              | A branch’s available and enabled analyses, schedule, spend and monthly budget bounds. `opts.branch` picks the branch. [API](https://docs.zkao.io/api/operations/getcontinuoustesting/)                               |
| `setContinuousTesting(repositoryId, body)`       | `ContinuousTesting`              | Turn automatic analysis on or off, select analyses, or change the monthly budget or audit areas. Needs `automations:write`. [API](https://docs.zkao.io/api/operations/setcontinuoustesting/)                         |
| `removeContinuousTesting(repositoryId, opts?)`   | `RemoveContinuousTestingResult`  | Remove a branch’s schedule. Scans it already ran are kept. Needs `automations:write`. [API](https://docs.zkao.io/api/operations/removecontinuoustesting/)                                                            |
| `prepareContinuousTesting(repositoryId, branch)` | `{ preparing: true }`            | Plan the branch’s next analysis without running it, as **Prepare next analysis** does in the app. Spends no credits. Needs `automations:write`. [API](https://docs.zkao.io/api/operations/preparecontinuoustesting/) |
| `listAgentQuestions()`                           | `{ questions: AgentQuestion[] }` | The open questions Continuous Security analyses asked the project’s members, oldest first. [API](https://docs.zkao.io/api/operations/listagentquestions/)                                                            |
| `answerAgentQuestion(questionId, answer)`        | `{ questionId, status }`         | Answer with `selectedOption`, a `note`, or both. Needs `guidance:write`. [API](https://docs.zkao.io/api/operations/answeragentquestion/)                                                                             |

`availableFeatures` lists the branch’s analysis IDs. Use `enableFeatures` to add analyses or `enabledFeatures` to replace the selection. Omitting both keeps the current selection. This example enables formal verification (FV) alongside the branch’s other analyses.

```ts
const schedule = await zkao.setContinuousTesting(repositoryId, {
  branch: "main",
  enabled: true,
  monthlyBudgetCredits,
  enableFeatures: ["formal-verification"],
});
console.log(schedule.enabled, schedule.enabledFeatures);
```

For FV alone, pass `enabledFeatures: ["formal-verification"]`. An existing schedule accepts a feature change at its current budget. `areaKeys` selects the audit areas that analyses rotate through. An empty `areaKeys` scans the whole repository every run.

`selectedOption` is the label of one of the question’s `options`. The analysis reads the answer in its next session. The answer counts as that of the member who created the token, who needs a project role of their own. A question that was already answered or dismissed fails with `409`.

```ts
const { questions } = await zkao.listAgentQuestions();
for (const q of questions) console.log(q.id, q.text, q.options.map((o) => o.label));


await zkao.answerAgentQuestion(questionId, {
  selectedOption: "<one of the labels>",
  note: "Only the operator can call this.",
});
```

### Scans

| Method                                   | Returns                 | Meaning                                                                                                                                                            |
| ---------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `listScans(opts?)`                       | `Paginated<Scan>`       | Scans, most recent first. `opts` takes `page` and `limit` (max 100). [API](https://docs.zkao.io/api/operations/listscans/)                                         |
| `getScan(scanId)`                        | `ScanDetail`            | One scan’s status and detail. [API](https://docs.zkao.io/api/operations/getscan/)                                                                                  |
| `launchScan(body)`                       | `LaunchScanResult`      | Launch a scan. Needs `scans:launch`. [API](https://docs.zkao.io/api/operations/launchscan/)                                                                        |
| `waitForScan(scanId, opts?)`             | `ScanDetail`            | Block until the scan is `COMPLETED`, `FAILED`, or `CANCELLED`. See [Polling helpers](https://docs.zkao.io/reference/sdk/#polling-helpers).                         |
| `cancelScan(scanId)`                     | `CancelScanResult`      | Cancel a running or queued scan and release its unspent credits. Needs `scans:launch`. [API](https://docs.zkao.io/api/operations/cancelscan/)                      |
| `resumeTriage(scanId, body, opts)`       | `ResumeTriageResult`    | Resume budget-stopped triage. Needs `scans:launch`. [API](https://docs.zkao.io/api/operations/resumetriage/)                                                       |
| `getTriageRun(scanId, runId)`            | `TriageRun`             | Read a resumed triage run. [API](https://docs.zkao.io/api/operations/gettriagerun/)                                                                                |
| `waitForTriageRun(scanId, runId, opts?)` | `TriageRun`             | Wait for that run to reach a terminal status. Honors `Retry-After`.                                                                                                |
| `publishScan(scanId, opts?)`             | `PublishArtifactResult` | Publish a completed scan as a public page. `opts.withPassword` adds a generated password. Needs `publish`. [API](https://docs.zkao.io/api/operations/publishscan/) |

`launchScan` takes a `LaunchScanRequest`:

| Field           | Meaning                                                                                   |
| --------------- | ----------------------------------------------------------------------------------------- |
| `repositoryId`  | Repository to scan. Required.                                                             |
| `creditBudget`  | Maximum budget in credits. Omit it to use the budget zkao recommends.                     |
| `presetRef`     | Preset ref from `listScanPresets()`. Defaults to the first active preset.                 |
| `branch`        | Branch to scan. Ignored when `commitHash` is set.                                         |
| `commitHash`    | Commit to scan.                                                                           |
| `commitMessage` | Commit message to record.                                                                 |
| `baseCommit`    | Base commit, branch, or tag of a diff scan. Required by a diff preset, refused by others. |
| `auditAreaKeys` | Area keys to scope the scan to. Omit to scan the whole repository.                        |
| `guidance`      | Guidance for this scan only, replacing the repository’s.                                  |

It resolves to `{ scanId, queued, creditBudget, buildsOverview }`. `buildsOverview` is `true` when a diff scan also builds the repository’s overview, which raises its budget. See [Scans](https://docs.zkao.io/guides/scans/) and [Diff scans](https://docs.zkao.io/guides/diff-scans/).

`getScan` and `waitForScan` return a `triage` object. Check its `status`, `untriagedCount`, and `resume` before relying on results. Resumption takes `body: { creditBudget }` and `opts: { idempotencyKey }`. Reuse that key and budget when retrying the same request. The result is `{ run, replayed }`.

`waitForTriageRun` accepts the same polling options as `waitForScan`. Its `onPoll` receives the triage run. The run reports `budgetExhausted` separately from `status`. The parent scan stays `COMPLETED` while resumed triage runs. Read the scan’s `triage` again afterward to check remaining work.

### Findings

`findingId` accepts the full id or the `ZK-` label shown on the finding page.

| Method                                                  | Returns                                          | Meaning                                                                                                                                                                                                                                                  |
| ------------------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `listFindings(opts?)`                                   | `Paginated<Finding>`                             | Findings across the project. `opts` takes `scanId`, `page`, and `limit`. [API](https://docs.zkao.io/api/operations/listfindings/)                                                                                                                        |
| `getFinding(findingId)`                                 | `FindingDetail`                                  | Full finding text and notes. [API](https://docs.zkao.io/api/operations/getfinding/)                                                                                                                                                                      |
| `addFindingNote(findingId, content)`                    | `{ noteId, findingId }`                          | Add a comment. Needs `findings:write`. [API](https://docs.zkao.io/api/operations/addfindingnote/)                                                                                                                                                        |
| `pinFindingNote(findingId, noteId, kind?)`              | `{ findingId, noteId }`                          | Pin a note as the finding’s resolution note. `kind` is `"resolution"`. Needs `findings:write`. [API](https://docs.zkao.io/api/operations/pinfindingnote/)                                                                                                |
| `setFindingSeverity(findingId, severity)`               | `{ findingId, userSeverity, effectiveSeverity }` | Override severity, or clear the override with `null`. Needs `findings:write`. [API](https://docs.zkao.io/api/operations/updatefindingseverity/)                                                                                                          |
| `setFindingResolution(findingId, status, opts?)`        | `{ findingId, resolutionStatus }`                | Change the resolution status. Needs `findings:write`. [API](https://docs.zkao.io/api/operations/updatefindingresolution/)                                                                                                                                |
| `overrideFindingTriage(findingId, triageStatus, opts?)` | `FindingTriageResult`                            | Replace the AI triage verdict with `CONFIRMED` or `FALSE_POSITIVE`. Setting the AI’s own verdict again clears the override. `opts.note` is added as a comment. Needs `findings:write`. [API](https://docs.zkao.io/api/operations/overridefindingtriage/) |
| `listFindingDetails(opts?)`                             | `FindingDetailsPage`                             | Full text of many findings in one call. `opts` takes `scanId`, `ids`, `page`, and `limit`. [API](https://docs.zkao.io/api/operations/listfindingdetails/)                                                                                                |
| `publishFinding(findingId, opts?)`                      | `PublishArtifactResult`                          | Publish a finding as a public page. `opts` takes `noteId` and `withPassword`. Needs `publish`. [API](https://docs.zkao.io/api/operations/publishfinding/)                                                                                                |

`setFindingResolution` takes `{ note?: ChangeNote; reason?: ResolutionReason }`. `note` is `{ content }` for a new comment or `{ existingNoteId }` to reuse one. `reason` is a catalog code valid for the status. `note` wins when both are given. Both are ignored for `NOT_STARTED` and `IN_PROGRESS`. See [Triage findings](https://docs.zkao.io/guides/findings/) for the codes.

```ts
await zkao.setFindingResolution(findingId, "WONT_FIX", { reason: "risk_accepted" });
```

### Regression test pull requests

| Method                                             | Returns                      | Meaning                                                                                                                                                                                                               |
| -------------------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getRegressionTestReadiness(findingId)`            | `RegressionTestReadiness`    | Check GitHub installation, permissions, and requester access. [API](https://docs.zkao.io/api/operations/getregressiontestreadiness/)                                                                                  |
| `createRegressionTest(findingId, body, opts)`      | `CreateRegressionTestResult` | Request one paid attempt. `body` takes `creditBudget` and optional `targetBranch`. `opts` requires `idempotencyKey`. Needs `regression-tests:write`. [API](https://docs.zkao.io/api/operations/createregressiontest/) |
| `listRegressionTests(findingId)`                   | `RegressionTestRun[]`        | List the latest attempts. [API](https://docs.zkao.io/api/operations/listregressiontests/)                                                                                                                             |
| `getRegressionTest(findingId, runId)`              | `RegressionTestRun`          | Follow one attempt and read its draft PR URL. [API](https://docs.zkao.io/api/operations/getregressiontest/)                                                                                                           |
| `retryRegressionTestPublication(findingId, runId)` | `RegressionTestRun`          | Retry opening the saved test’s PR without another generation budget. Needs `regression-tests:write`. [API](https://docs.zkao.io/api/operations/retryregressiontestpublication/)                                       |

Reuse the same request key, budget, and target branch after an uncertain launch response. The result’s `replayed` flag identifies an existing attempt. See [Regression tests](https://docs.zkao.io/guides/findings/#regression-tests) for permissions and validation outcomes.

### Presets

| Method              | Returns        | Meaning                                                                                                                  |
| ------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `listScanPresets()` | `ScanPreset[]` | Presets the project can launch. Pass a `ref` as `presetRef`. [API](https://docs.zkao.io/api/operations/listscanpresets/) |

### Incoming reports

Vulnerability reports researchers filed through GitHub’s private vulnerability reporting. `intakeState` says whether a report has been read and split into claims yet; an investigation waits for `COMPLETE`.

| Method                        | Returns                   | Meaning                                                                                                                       |
| ----------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `listReports(opts?)`          | `Paginated<Report>`       | Reports, newest first. `opts` takes `status`, `page`, and `limit`. [API](https://docs.zkao.io/api/operations/listreports/)    |
| `investigateReport(publicId)` | `InvestigateReportResult` | Check a report’s claims against the code. Needs `scans:launch`. [API](https://docs.zkao.io/api/operations/investigatereport/) |

`investigateReport` checks each claim against the repository, deduplicates it against the findings already confirmed there, and writes a proof of concept where one can be written. It returns at once with the scan doing the work, so poll `getScan` and then read that scan’s findings.

It is idempotent: a report already under investigation comes back with the existing scan and `claimsQueued: null`, so a retry costs nothing.

```ts
const { scanId } = await zkao.investigateReport("REPORT-2026-0012");
await zkao.waitForScan(scanId);
```

### Advisories

A coordinated-disclosure advisory. `publicId` is the readable identifier, like `ADVISORY-ADV-2026-0045`.

An advisory makes two separate statements, and the difference matters. `software` is which repositories it is about, and it is what every notice is matched on: a contact is told only if they run something on that list. `affected` is the version ranges that carry the bug, and it is often empty because when a report arrives nobody yet knows which releases are involved.

| Method                                        | Returns               | Meaning                                                                                                                                    |
| --------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `listAdvisories(opts?)`                       | `Paginated<Advisory>` | Advisories, newest first. `opts` takes `status`, `page`, and `limit`. [API](https://docs.zkao.io/api/operations/listadvisories/)           |
| `getAdvisory(publicId)`                       | `AdvisoryDetail`      | The advisory, its `software`, its `affected` versions, and every planned `notice`. [API](https://docs.zkao.io/api/operations/getadvisory/) |
| `replaceAdvisoryAffected(publicId, affected)` | `AdvisoryDetail`      | Replace the affected version ranges. Needs `advisories:write`. [API](https://docs.zkao.io/api/operations/replaceadvisoryaffected/)         |

`replaceAdvisoryAffected` is the one write worth putting in a release pipeline. A patch notice is held back until some range names the version that fixed the bug, and nothing but whatever cut the release knows it:

```ts
await zkao.replaceAdvisoryAffected("ADVISORY-ADV-2026-0045", [
  { repository: { owner: "acme", name: "libfoo" }, introducedIn: "1.0.0", fixedIn: "2.0.3" },
]);
```

It replaces the whole set, so send what is affected now rather than a patch. It records versions and nothing else: a range may name only software already on the advisory’s `software`, and anything else is a `400`. Which software an advisory concerns decides who hears about it, so it is changed in the app, not from a token that records versions.

Reading an advisory also reports why a notice is held back. `notices[].status` is `BLOCKED` with a `blockedReason` when the plan is withholding one.

### Advisory contacts

The teams running your software. Each contact records which of your repositories they run, which is what notices are matched on, and a `tier` saying how early they hear: `EMBARGO` first and alone, `DOWNSTREAM` once a patch exists, `ANNOUNCE` at public disclosure.

| Method                        | Returns                      | Meaning                                                                                                                                                                     |
| ----------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `listAdvisoryContacts(opts?)` | `Paginated<AdvisoryContact>` | The contact list, oldest first. `opts` takes `tier`, `status`, `page`, and `limit`. Needs `contacts:read`. [API](https://docs.zkao.io/api/operations/listadvisorycontacts/) |
| `addAdvisoryContact(contact)` | `AdvisoryContact`            | Put one address on the list. Needs `contacts:write`. [API](https://docs.zkao.io/api/operations/addadvisorycontact/)                                                         |

`software` is required when adding one. A contact who runs nothing is told nothing, so an empty list is a `400` rather than a contact that sits silent.

```ts
await zkao.addAdvisoryContact({
  email: "security@downstream.example",
  organization: "Downstream Inc",
  tier: "DOWNSTREAM",
  software: [{ owner: "acme", name: "libfoo" }],
});
```

A new contact starts `PENDING_VERIFICATION`, and an unconfirmed address receives nothing embargoed. Nothing is emailed by this call: the confirmation mail is sent from the app.

The two contact scopes are separate from the rest on purpose. This list is who learns about a vulnerability before the public does, so `read` does not reach it and `advisories:write` cannot add to it.

### Billing

The balance belongs to the project’s organization and is shared by all its projects. Usage and the monthly summary count only movements attributed to this project. See [Credits](https://docs.zkao.io/guides/credits/).

| Method                     | Returns               | Meaning                                                                                                                                                                   |
| -------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getBillingBalance()`      | `BillingBalance`      | `balanceCredits`, `reservedCredits` held by active scans, and `availableCredits` for new scans. [API](https://docs.zkao.io/api/operations/getbillingbalance/)             |
| `getBillingUsage(opts?)`   | `BillingUsage`        | Ledger movements with signed `credits`. `opts` takes `from`, `to`, and `limit`. Defaults to the last 30 days. [API](https://docs.zkao.io/api/operations/getbillingusage/) |
| `getBillingSummary(opts?)` | `UsageMonthSummary[]` | Credits spent and purchased per UTC month, newest first. `opts.months` sets how many. [API](https://docs.zkao.io/api/operations/getbillingsummary/)                       |

## Polling helpers

Scans take minutes, and a tight polling loop is rejected with `429`. The helpers back off exponentially with jitter, honor the server’s `Retry-After`, and treat a `429` as a signal to slow down.

```ts
const { scanId } = await zkao.launchScan({ repositoryId, presetRef });
const scan = await zkao.waitForScan(scanId, {
  onPoll: (s) => console.log(s.status),
});
if (scan.status !== "COMPLETED") throw new Error(`Scan ended ${scan.status}`);
```

`waitForScan(scanId, opts)` resolves with the final detail whatever the final status is.

| Option          | Default | Meaning                                                             |
| --------------- | ------- | ------------------------------------------------------------------- |
| `intervalMs`    | `5000`  | First delay between polls. Grows by 1.5x each poll.                 |
| `maxIntervalMs` | `30000` | Cap on the delay.                                                   |
| `timeoutMs`     | 1 hour  | Give up and throw after this long.                                  |
| `signal`        | none    | `AbortSignal` that stops the wait. Rejects with the abort reason.   |
| `onPoll`        | none    | Called with the latest `ScanDetail` on each poll that is not final. |

`waitForRepositoryReady(repositoryId, opts)` takes the same options except `onPoll`, with a default timeout of 30 minutes. It throws if the repository is not in the project or the token’s allowlist. Call it between adding a repository and launching its first scan.

`isTerminalScanStatus(status)` and `TERMINAL_SCAN_STATUSES` tell whether a status is final, for your own loops.

## Errors

Every non-2xx response throws `ZkaoApiError`.

| Property         | Meaning                                                                              |
| ---------------- | ------------------------------------------------------------------------------------ |
| `status`         | HTTP status.                                                                         |
| `code`           | Machine-readable error code from the response, such as `insufficient_credits`.       |
| `message`        | Human-readable message.                                                              |
| `minimumCredits` | Set with `budget_below_minimum`: the smallest budget the launch accepts, in credits. |

Branch on `code`, not on the message.

```ts
import { ZkaoApiError } from "@zksecurity/zkao-sdk";


try {
  await zkao.launchScan({ repositoryId, presetRef });
} catch (err) {
  if (err instanceof ZkaoApiError && err.code === "repository_initializing") {
    await zkao.waitForRepositoryReady(repositoryId);
  } else if (err instanceof ZkaoApiError && err.code === "insufficient_credits") {
    console.error("Not enough credits for this budget.");
  } else {
    throw err;
  }
}
```

The full list of codes is in [API conventions](https://docs.zkao.io/reference/api-conventions/). Timeouts and aborts in the polling helpers throw a plain `Error`, not `ZkaoApiError`.

## Types

The package exports a named type for each API object.

| Type                                                                                                                        | Meaning                                                |
| --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| `Repository`, `RepositoryGuidance`, `SetGuidanceResult`                                                                     | Repositories and their guidance.                       |
| `Scan`, `ScanDetail`, `ScanStatus`, `ScanPreset`                                                                            | Scans, their status, and presets.                      |
| `LaunchScanRequest`, `LaunchScanResult`, `CancelScanResult`                                                                 | Launch and cancel bodies and results.                  |
| `Finding`, `FindingDetail`, `FindingNote`, `ChangeNote`, `FindingTriageResult`                                              | Findings, their notes, and a triage override’s result. |
| `ContinuousFeatureId`, `ContinuousTesting`, `SetContinuousTestingRequest`, `RemoveContinuousTestingResult`, `AgentQuestion` | Continuous Security analyses, schedules and questions. |
| `Severity`, `ResolutionStatus`, `ResolutionReason`, `TriageStatus`                                                          | Finding enums.                                         |
| `PublishArtifactResult`                                                                                                     | Result of publishing a scan or finding.                |
| `TokenInfo`                                                                                                                 | The calling token and its project.                     |
| `BillingBalance`, `BillingUsage`, `UsageEvent`, `UsageEventType`, `BillingSummary`, `UsageMonthSummary`                     | Credit balance and ledger.                             |
| `Paginated<T>`                                                                                                              | `{ items, page, limit, total }` for list endpoints.    |
| `ZkaoClientOptions`, `WaitForScanOptions`, `WaitForRepositoryReadyOptions`                                                  | Option objects.                                        |

The raw generated types are exported as `components` and `paths`. Any schema without a named export is available as `components["schemas"]["<Name>"]`, for example `components["schemas"]["AuditArea"]`.
