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

> ## Agent Instructions
> If you're integrating Kardinal into an application with an SDK, start with Integration paths: https://developers.kardinal.ai/getting-started/integration-paths.md. It lists the sections to read, in order. If you follow Integration paths, you don't need llms-full.txt or openapi.yaml. Each step links the section you need.

# TypeScript SDK reference

> Every public class, method, and error of the Kardinal TypeScript SDK (@kardinal-ai/sdk): signatures, the API endpoint behind each call, and what each returns.

Reference for `@kardinal-ai/sdk` 1.3.0, for Node.js 22 or later. Every method below returns a `Promise`, except `plans.iterAll`, an async iterator. The fields of a solution are in [Solution fields](#solution-fields). The fields of a plan are in the [API Reference](https://developers.kardinal.ai/api-reference/plan/create-a-plan.md).

## Client

### `Kardinal`

```ts theme={null}
new Kardinal(options?: KardinalOptions)
```

| Option | Type | Default | Description |
| - | - | - | - |
| `apiKey` | `string` | `KARDINAL_API_KEY` | Your API key. Throws `MissingApiKeyError` if none is found, `EmptyApiKeyError` for `""`. |
| `baseUrl` | `string` | `KARDINAL_BASE_URL`, then `https://app.kardinal.ai/api/v2` | API host. Leave unset. |
| `timeoutMs` | `number` | `30000` | Milliseconds, one deadline for the whole request, reading the response included. |
| `maxRetries` | `number` | `3` | Retries of a read, `update`, `replace`, `delete`, `start`, or `stop` after a network error, a `429`, or a `5xx`. |
| `onWarning` | `(message: string, fields: UnknownField[]) => void` | `console.warn` | Receives the likely typos `update` can only warn about, and one line for each kind of warning the API returns to `submit`, `update`, and `replace`. |

The methods hang off `k.routing.plans` and `k.routing.solutions`. There's nothing to close. See [Client configuration](https://developers.kardinal.ai/sdks/configuration.md).

### `whoami`

```ts theme={null}
k.whoami(): Promise<Whoami>
```

[`GET /plans`](https://developers.kardinal.ai/api-reference/plan/retrieve-the-list-of-plans-in-a-light-representation), for one plan, archived plans excluded. Returns `Whoami`, an object `{ baseUrl: string; agencyId: string | null }`: the host the key was checked against, and the agency the key belongs to. `agencyId` is `null` when the API names none. The call is free, and it is retried like a read. See [Checking the key at startup](https://developers.kardinal.ai/sdks/configuration.md#checking-the-key-at-startup).

## Plans

### `plans.submit`

```ts theme={null}
k.routing.plans.submit(plan: PlanCreateInput, opts?: { allowUnknown?: string[] }): Promise<Plan>
```

[`POST /plans`](https://developers.kardinal.ai/api-reference/plan/create-a-plan). Validates the plan locally, then creates it and starts its optimization. Returns the stored `Plan`, with the `id` the server assigned and `warnings`. Throws a `ZodError` for an invalid plan, and `UnknownFieldError` for a key no schema declares unless named in `allowUnknown`, both before sending. Consumes credits with a production key. **Never retried.**

`submit`, `update`, and `replace` pass each kind of warning the API returns to `onWarning`, as one line with an empty `fields` array. By default, `onWarning` is `console.warn`. To stay quiet, pass `onWarning: () => {}`. To keep only the typo warnings of `update`, ignore the calls whose `fields` array is empty. If your handler fails, the SDK reports the failure with `console.error`, and the call still returns the plan. A program that needs the warnings reads `plan.warnings`. See [Warnings on successful calls](https://developers.kardinal.ai/sdks/errors-and-warnings.md#warnings-on-successful-calls).

### `plans.get`

```ts theme={null}
k.routing.plans.get(planId: string): Promise<Plan>
```

[`GET /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/retrieve-a-plan). Returns the plan as currently stored. Rejects with `KardinalNotFoundError` if it doesn't exist.

### `plans.update`

```ts theme={null}
k.routing.plans.update(plan: Plan, opts?: { force?: boolean; allowUnknown?: string[] }): Promise<Plan>
```

[`PUT /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/update-a-plan). Replaces the whole plan: anything left out is removed. The version increments, and the plan is re-optimized, only if the content changed; an identical update is a free no-op. Fields unknown to this SDK version that `get` read are sent back untouched; a key you added that no schema declares throws `UnknownFieldError`, unless named in `allowUnknown`. On a plan this client didn't read, a likely typo only goes to `onWarning`. `force: true` unarchives an archived plan first. Retried.

### `plans.replace`

```ts theme={null}
k.routing.plans.replace(planId: string, plan: PlanCreateInput, opts?: { force?: boolean; allowUnknown?: string[] }): Promise<Plan>
```

[`PUT /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/update-a-plan). Replaces the whole plan from a `PlanCreateInput`, the input `submit` takes. The input has no `id`, `agencyId`, or `version` to copy. Anything you leave out is removed, including a field the API gained after this SDK version. To keep such a field, use `get` and `update` instead. Validates the plan locally first, and throws a `ZodError` or an `UnknownFieldError` before any request. `allowUnknown` names keys to send anyway. An identical plan is a free no-op, and the version stays the same. A plan created from raw JSON gets one new version the first time. There is no version check, so the last write wins. `force: true` unarchives an archived plan first. Retried. See [Replacing a plan from your own data](https://developers.kardinal.ai/sdks/plan-lifecycle.md#replacing-a-plan-from-your-own-data).

### `plans.delete`

```ts theme={null}
k.routing.plans.delete(planId: string): Promise<void>
```

[`DELETE /plans/{planId}`](https://developers.kardinal.ai/api-reference/plan/delete-a-plan). Permanently deletes the plan and its solution, and stops any optimization in progress. Retried.

### `plans.list`

```ts theme={null}
k.routing.plans.list(opts?: { page?: number; itemsPerPage?: number; archived?: "excluded" | "included" | "only" }): Promise<Page<PlanLight>>
```

[`GET /plans`](https://developers.kardinal.ai/api-reference/plan/retrieve-the-list-of-plans-in-a-light-representation). Returns one page of plans, in their light form; defaults: page `1`, `20` items, archived plans excluded. A page past the last one returns the last page.

### `plans.iterAll`

```ts theme={null}
k.routing.plans.iterAll(opts?: { archived?: "excluded" | "included" | "only" }): AsyncGenerator<PlanLight>
```

`GET /plans`, every page. Iterates over every plan with `for await`, fetching pages as it goes.

### `plans.start`

```ts theme={null}
k.routing.plans.start(planId: string, opts?: { force?: boolean }): Promise<PlanReference>
```

[`PUT /plans/{planId}/running`](https://developers.kardinal.ai/api-reference/plan/stop-or-restart-the-optimization-of-a-plan). Restarts the optimization of the current version, without changing its content or version. Returns `agencyId`, `planId`, `planVersion`, and `warnings`. Retried.

### `plans.stop`

```ts theme={null}
k.routing.plans.stop(planId: string, opts?: { force?: boolean }): Promise<PlanReference>
```

[`PUT /plans/{planId}/running`](https://developers.kardinal.ai/api-reference/plan/stop-or-restart-the-optimization-of-a-plan). Stops the optimization in progress, without changing the plan's content or version. Retried.

### `plans.getStatus`

```ts theme={null}
k.routing.plans.getStatus(planId: string): Promise<PlanState | string>
```

[`GET /plans/{planId}/state`](https://developers.kardinal.ai/api-reference/plan/retrieve-the-latest-state-of-a-plan). Returns the plan's current state, a single value: `waiting`, `processing`, `optimizing`, `optimized`, `stopped`, `interrupted`, and so on. A state this SDK version doesn't know comes back as its raw string. Not the detailed `PlanStatus` object found in `Plan.status`.

## Solutions

### `solutions.wait`

```ts theme={null}
k.routing.solutions.wait(planId: string, timeoutMs?: number): Promise<WaitedSolution>
```

`GET /plans/{planId}/state`, then [`/solution`](https://developers.kardinal.ai/api-reference/solution/retrieve-a-plan-solution). Resolves once the optimization of the current version is over, with its solution. Reads the state every 10 seconds at first, up to every 60 seconds. `solution.finalState` tells how it ended: `optimized`, `interrupted`, or `stopped`. Rejects with `KardinalOptimizationError` (`NO_SOLUTION`, `PLAN_SUPERSEDED`, `OPTIMIZATION_STALLED`), `KardinalNotFoundError` if the plan is deleted meanwhile, and `KardinalTimeoutError` once `timeoutMs` milliseconds have elapsed. See [Waiting for the solution](https://developers.kardinal.ai/sdks/plan-lifecycle.md#waiting-for-the-solution).

### `solutions.get`

```ts theme={null}
k.routing.solutions.get(planId: string): Promise<Solution>
```

[`GET /plans/{planId}/solution`](https://developers.kardinal.ai/api-reference/solution/retrieve-a-plan-solution). Returns the current best solution right away, without waiting. Rejects with `KardinalNotFoundError` until the engine has a first solution.

### `solutions.getObjectives`

```ts theme={null}
k.routing.solutions.getObjectives(planId: string): Promise<SolutionObjectives>
```

[`GET /plans/{planId}/solution/objectives`](https://developers.kardinal.ai/api-reference/solution/retrieve-the-objectives-of-a-plan-solution). Returns the value of each objective, without the tours: a plain array of `SolutionObjective`, with a `warnings` property.

### Solution fields

`solution.tours` holds one `Tour` for each resource used. `tour.wayPoints` is a list of waypoints, and each waypoint has a `type`: `"begin"`, `"stop"`, `"break"`, or `"end"`. Read `wp.type` before you read any other field.

From 1.3.0, the package exports the four waypoint types by name: `WayPointBegin`, `WayPointStop`, `WayPointBreak`, and `WayPointEnd`. Narrow a waypoint on `wp.type` before you read its other fields. The `delay` field only exists after `wp.type === "stop"`.

```ts theme={null}
import type { WayPointStop } from "@kardinal-ai/sdk";

const stops = (tour.wayPoints ?? []).filter((wp): wp is WayPointStop => wp.type === "stop");
```

Every field in these tables except `type` is optional, so it is `undefined` when the API leaves it out. The SDK returns dates and durations as `string`, without converting them. A date is the local time of the plan's `tz`, with its offset and seconds, for example `2026-11-20T08:01:23+01:00`. Without `tz`, a date is in UTC, with a `Z`. `solution.timestamp` is always in `Z`. See [Dates and time zones](https://developers.kardinal.ai/reference/data-model.md#dates-and-time-zones).

`new Date(value)` keeps the instant, but not the offset. To show the local time of `tz`, format the `Date` with that time zone. A duration is an ISO 8601 string such as `PT5H11M55S`. JavaScript has no parser for it.

| Field of `Tour` | Type | Description |
| - | - | - |
| `resourceId` | `string` | The resource that drives this tour. |
| `isValid` | `boolean` | Whether the tour respects every hard constraint. A valid tour can still be late: read `totalDelay` and the `delay` of each stop. |
| `distanceInKm` | `number` | Total distance of the tour. |
| `travelDuration` | `string` (duration) | Total time spent driving. |
| `workingDuration` | `string` (duration) | Total working time. |
| `waitingDuration` | `string` (duration) | Total time spent waiting. |
| `totalDelay` | `string` (duration) | Total delay of the tour. |
| `wayPoints` | list of waypoints | The waypoints, in order. |

| Field of a waypoint | Type | `begin` | `stop` | `break` | `end` | Description |
| - | - | - | - | - | - | - |
| `type` | `"begin"`, `"stop"`, `"break"`, `"end"` | ✓ | ✓ | ✓ | ✓ | The kind of waypoint. |
| `stopId` | `string` | — | ✓ | — | — | The stop served here. |
| `status` | `"fixed"`, `"assigned"`, or `"optimized"` | ✓ | ✓ | ✓ | ✓ | The status of the waypoint. |
| `arrivalTime` | `string` (date) | — | ✓ | ✓ | ✓ | When the vehicle gets here. |
| `beginTime` | `string` (date) | — | ✓ | — | — | When the service starts. It is later than `arrivalTime` when the vehicle waits for the time window to open. |
| `departureTime` | `string` (date) | ✓ | ✓ | ✓ | — | When the vehicle leaves. |
| `delay` | `string` (duration) | — | ✓ | — | — | How late the service starts. It is `PT0S` for a stop served on time. |
| `fromPrevious` | `{ travelDistanceInKm: number; travelDuration: string }` | ✓ | ✓ | ✓ | ✓ | The leg driven from the previous waypoint. |

A break waypoint runs from `arrivalTime` to `departureTime`, and that span can be longer than the break, because it includes any wait before the break. For example, a 30-minute break can show 10:10 to 12:30. See [Breaks](https://developers.kardinal.ai/guides/breaks.md).

`solution.totalDelay` sums the delays of the tours, and `solution.unaffectedStopIds` lists the stops left out of every tour. Capacities, violations, and properties are in the [API Reference](https://developers.kardinal.ai/api-reference/solution/retrieve-a-plan-solution.md).

## Examples

### `examples.smallDeliveryPlan`

```ts theme={null}
import { examples } from "@kardinal-ai/sdk";

examples.smallDeliveryPlan(): PlanCreate
```

A ready-to-submit plan: two resources, eight single-stop orders around central Paris, and a 10-second optimization. The working window starts tomorrow at 8:00. Each call returns a new object.

### `examples.coldChainPlan`

```ts theme={null}
examples.coldChainPlan(): PlanCreateInput
```

The plan of the [cold-chain last-mile](https://developers.kardinal.ai/case-studies/cold-chain-last-mile.md) case study, as a typed object to adapt to your data. Each call returns a new object.

### `examples.parcelExpressPlan`

```ts theme={null}
examples.parcelExpressPlan(): PlanCreateInput
```

The plan of the [parcel express](https://developers.kardinal.ai/case-studies/parcel-express.md) case study, as a typed object to adapt to your data. Each call returns a new object.

## Local checks

### `unknownFields`

```ts theme={null}
import { unknownFields } from "@kardinal-ai/sdk";

unknownFields(plan: unknown): UnknownField[]
```

Runs the check `submit` makes, without sending anything: every key no schema declares, with its path and, when one is close, the real field name it was likely meant to be. Empty when the plan is clean.

`parsePlanCreate(data, allowUnknown?)` runs all of `submit`'s local checks, `zod` validation included, and returns the plan with its defaults applied; `parsePlan(data)` validates a stored plan, such as one read from a file before an `update`.

## Types

### `PlanCreate`

The plan you submit: no `id`, the server assigns it. `PlanCreateInput` is the same shape before defaults are applied: the type to use for a plan you build by hand.

### `Plan`

The plan as stored, returned by `submit`, `get`, `update`, and `replace`: the same content plus `id`, `version`, `status`, `state`, and `agencyId`, and `warnings` from the call that returned it.

### `Page`

Returned by `plans.list`: `items`, `page`, `totalPages`, `total`, `nextPage` (`null` on the last page), `previousPage` (`null` on the first page), and `itemsPerPage`.

### Model types

The package exports a type for the main schemas of the [API specification](https://developers.kardinal.ai/api-reference/plan/create-a-plan.md) (`Resource`, `SingleStop`, `AlternativesStop`, `Position`, `TimeWindow`, `Solution`, `Tour`, `Warning`, and so on), with the API's field names and descriptions. Import them with `import type`. From 1.3.0, the four waypoint types are among them: see [Solution fields](#solution-fields).

## Exceptions

All importable from `@kardinal-ai/sdk`, all subclasses of `KardinalError`. See [Errors, retries, and warnings](https://developers.kardinal.ai/sdks/errors-and-warnings.md).

| Error | Thrown on |
| - | - |
| `KardinalAuthError` | `401`. From 1.1.0, also a `403` for a revoked or regenerated key. |
| `KardinalLimitError` | A `403` recognized as a limit: plan size, quota, or credits. In 1.0.x, any `403`. |
| `KardinalForbiddenError` | From 1.1.0, any other `403`. |
| `KardinalValidationError` | `400`. From 1.1.0, also the `403` of an archived plan without `force`. |
| `KardinalNotFoundError` | `404` |
| `KardinalRateLimitError` | `429` |
| `KardinalServerError` | `5xx` |
| `KardinalConnectionError` | No HTTP response |
| `KardinalTimeoutError` | `solutions.wait` time limit elapsed |
| `KardinalOptimizationError` | `solutions.wait` has no solution to return |
| `UnknownFieldError` | Unknown key found before sending |
| `MissingApiKeyError`, `EmptyApiKeyError` | No usable key when creating the client |

A plan that fails local validation throws a `ZodError`, from `zod`, instead.

Every error carries `.code`, `.status`, `.errors`, `.details`, `.retryable`, `.warnings`, and `.requestId`.

## Known limitations

* Node.js only: browsers aren't supported.
* The inside of the rarer nested objects (`cost`, `breaks`, `objectives`, constraints) isn't validated locally, and a misspelled key there isn't reported.
* `update`'s exact check of unknown keys needs the plan to have been read by the same client, in the same process; it remembers the last 64 plans.
* `.requestId` is usually `null`: the API sends an `X-Request-Id` header only on some responses.
* The `kardinal` command needs `commander` installed alongside the package.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.