# Errors and retries (TypeScript)

Every error class and code of the TypeScript SDK, the per-call request options, the exact retry rules, and idempotency keys that survive a crash.

A failed request throws a `SailforkError`, and the client retries what is safe to retry. This page covers the error classes, `RequestOptions`, the retry rules and resuming a write after a crash.

## Errors

Every error the client raises about a request is a `SailforkError`. Catch by class, narrow with `instanceof`, and read the fields.

```ts
import Sailfork, { AgentPolicyError, ConflictError, NotFoundError, RateLimitError, SailforkError } from 'sailfork';

const sf = new Sailfork();

try {
	await sf.repo('acme/api').pull(99999).merge();
} catch (error) {
	if (error instanceof NotFoundError) {
		console.log('no such pull request');
	} else if (error instanceof AgentPolicyError) {
		console.log(error.code, error.hint); // agent_policy, agent_change_cap, held_declined or bypass_needs_person
	} else if (error instanceof ConflictError && error.code === 'file_changed') {
		console.log('read the file again');
	} else if (error instanceof RateLimitError) {
		console.log(`try again in ${error.retryAfter ?? 'a few'} seconds`);
	} else if (error instanceof SailforkError) {
		console.error(String(error));
	} else {
		throw error;
	}
}
```

### Fields

| Field | Type | Holds |
| --- | --- | --- |
| `name` | `string` | The class name, such as `NotFoundError` |
| `message` | `string` | The server's `error` text, else its `message`, else the plain body, else `the server answered 502` |
| `status` | `number` | The HTTP status; `0` when no answer arrived |
| `code` | `ErrorCode` or `string` | The server's `code`, else `http_<status>` |
| `hint` | `string \| undefined` | What to do about it, when the server says |
| `param` | `string \| undefined` | The field or scope the error is about |
| `requestId` | `string \| undefined` | The body's `requestId`, else the `Sailfork-Request-Id` header. Quote it in a report |
| `docUrl` | `string \| undefined` | A link to the error's documentation |
| `retryAfter` | `number \| undefined` | Seconds from `Retry-After`, when sent |
| `body` | `unknown` | The parsed answer body, for fields the class does not lift, such as `sha` and `version` on `file_changed` |

`String(error)` prints one line: `NotFoundError: not_found: not found | request: req_05e1... | docs: https://sailfork.com/docs/api#error-codes`. The hint, request id and doc address are included when present. A bad token prints `AuthenticationError: unauthenticated: authentication required | hint: sign in again or create an access token under Settings, then send it as a Bearer token | request: ... | docs: ...`.

### Classes

The class comes from the code when it is one of the listed codes, and from the status otherwise. A code the client does not know, such as `caisson_held_by`, gets the class its status maps to. [Error codes](https://sailfork.com/docs/api#error-codes) explains each code.

| Class | Status | Codes |
| --- | --- | --- |
| `InvalidRequestError` | 422, 413, 415, and any other 4xx | `invalid_request`, `payload_too_large`, `unsupported_media_type` |
| `AuthenticationError` | 401 | `unauthenticated`, `invalid_token` |
| `PermissionError` | 403 | `insufficient_scope`, `forbidden`, `suspended`, `blocked`, `private_fork_stays_private`, `private_forks_off`, `private_fork_outside_org`, `sso_deactivated`, `sso_invite`, `sso_name_taken`, `sso_account_linked`, `sso_expired` |
| `AgentPolicyError` | 403, 402 | `agent_policy`, `agent_change_cap`, `held_declined`, `bypass_needs_person` |
| `NotFoundError` | 404 | `not_found` |
| `ConflictError` | 409, 412 | `conflict`, `file_changed`, `idempotency_in_progress`, `precondition_failed` |
| `RateLimitError` | 429 | `rate_limited` |
| `ServerError` | 5xx | `internal`, `unavailable`, `busy` |
| `UnavailableForLegalReasonsError` | 451 | `disabled`, `region_blocked` |
| `ConnectionError` | 0 | `connection_failed`: DNS, connection, TLS, or a body that ended early. The original error is on `cause` |
| `TimeoutError` | 0 | `timeout`: the call outlasted its `timeout` |

`ERROR_CODES` is the array of the 32 codes above, and `ErrorCode` is its type, for exhaustive checks. `code` is typed `ErrorCode` or a plain string, because a newer server can send a code this version does not list.

Not everything is a `SailforkError`. A missing path parameter is a `TypeError`, `sf.repo('nope')` is an `Error`, `run` with an unknown tool name is an `Error`, and an aborted `signal` rejects with its own reason.

## Request options

Every method takes `RequestOptions` as its last argument.

| Field | Type | Meaning |
| --- | --- | --- |
| `signal` | `AbortSignal` | Aborts the call. The call rejects with the signal's `reason`, not a `SailforkError`, and is not retried |
| `timeout` | `number` | Milliseconds one attempt may take before it fails with `TimeoutError`. Default 60000, or 300000 for [long operations](https://sailfork.com/docs/sdk-typescript-calls#streams-and-long-operations) |
| `maxRetries` | `number` | Replaces the client's retry count for this call |
| `idempotencyKey` | `string` | The key to send on a write, instead of a fresh one |
| `headers` | `Record<string, string>` | Extra headers for this call, which win over the client's |

```ts
import Sailfork from 'sailfork';

const sf = new Sailfork();
const stop = new AbortController();

const page = await sf.repo('acme/api').pulls.list({ limit: 5 }, { signal: stop.signal, timeout: 10_000, maxRetries: 0 });
```

### Resume after a crash

A write sends an `Idempotency-Key`. By default it is a random UUID chosen per call and reused across that call's retries, so a retry inside one process runs the write once. After a crash that UUID is lost. To make a write safe across a restart, derive the key from the work and store it before the first attempt.

```ts
import Sailfork from 'sailfork';

const sf = new Sailfork();
const repo = sf.repo('acme/api');

const key = 'nightly-triage:2026-11-18:flaky-test-report'; // 1 to 200 characters, kept for a day
const issue = await repo.issues.create({ title: 'Flaky test report for 2026-11-18', body: 'See the attached run.' }, { idempotencyKey: key });
console.log(issue.number); // the same number on every rerun with this key
```

The server remembers only successful answers, so a rerun after a failure or a held 202 runs again. A rerun that sends the same key with a different request fails with a 409, a `ConflictError`. See [Caching, retries and timing](https://sailfork.com/docs/api#caching-retries-and-timing).

## Retries and idempotency

The rules, from the client's code:

- **Which calls.** Reads and the writes the catalog marks idempotent retry. Eleven operations never retry: `caissons.bash`, `caissons.reviewResolve`, `caissons.reviewSubmit`, `caissons.stop`, `issues.next`, `keys.add`, `labels.create`, `milestones.create`, `notes.create`, `repos.create` and `tokens.create`.
- **Which failures.** A connection error or a timeout (status 0), 408, 429, any 5xx, and 409 with code `idempotency_in_progress`. No other 4xx retries, so a 404, 409 `conflict`, 412 and 422 throw at once.
- **How many.** `maxRetries` retries after the first attempt, so 2 means 3 attempts. The `idempotency_in_progress` wait has a separate budget of 10 tries that `maxRetries` does not change, since it means the first request with that key is still running.
- **How long between.** With a `Retry-After` header, that many seconds plus up to 250 ms. A `Retry-After` over 60 seconds is not waited for: the error is thrown. Without the header, an exponential backoff of 500 ms, 1 s, 2 s, up to 8 s, each scaled by a random 0.5 to 1.
- **Timeouts.** `timeout` is per attempt, so a call can take longer than it in all.
- **Idempotency keys.** Every call that is not a read sends `Idempotency-Key`, one value reused across the call's retries, including the ones that never retry. Reads send none.

## Read the body of an error

`body` holds the whole answer, for fields the class does not lift. A `file_changed` conflict carries the file's current `sha` and `version`.

```ts
import Sailfork, { ConflictError } from 'sailfork';

const sf = new Sailfork();
const caisson = sf.repo('acme/api').caisson('c-z4nwicj7');

try {
	await caisson.batch({ changes: [{ path: 'src/charge.ts', content: 'export {};\n' }] });
} catch (error) {
	if (error instanceof ConflictError && error.code === 'file_changed') {
		const { sha, version } = error.body as { sha?: string; version?: string };
		console.log('the file moved on', sha, version);
	} else {
		throw error;
	}
}
```

The same topic for Python: [Python errors and retries](https://sailfork.com/docs/sdk-python-errors).

---

Every docs page: https://sailfork.com/llms.txt
