# TypeScript

> The Curva TypeScript SDK: a zero-dependency client using global fetch, for Node 18+, Deno, Bun and browsers.

Source: https://docs.tarkova.com/curva/guides/typescript/

The TypeScript SDK is a client for a running Curva server (`curva serve`, or a shared server). It
has zero dependencies and uses the global `fetch`, so it runs on Node 18+, Deno, Bun and in
browsers.

```bash
npm install curva-ai
```

The package is [`curva-ai` on npm](https://www.npmjs.com/package/curva-ai).

## First decision

```ts

const curva = new Curva();   // CURVA_BASE_URL (default http://localhost:7777), CURVA_API_KEY
const d = await curva.decide(
  { ticket: "I was charged twice for order A-104. Please refund the duplicate!" },
  {
    team: choice("Which team should handle this?", { billing: "payments, refunds", technical: "bugs", sales: "pricing" }),
    frustration: score("How frustrated is the customer?", ["calm", "annoyed", "angry"]),
    refund: noul("The customer explicitly asks for a refund"),
  },
);

d.answers.team.choice;        // "billing" | "technical" | "sales" | "none_of_these"
d.answers.team.confidence;
d.answers.frustration.score;
d.answers.refund.noul;        // P(yes)
```

Answers are typed from the questions you pass: `d.answers.team.choice` is a union of that
question's option keys (plus `"none_of_these"`), so a typo is a compile error.

## Questions

```ts

const questions = {
  team: choice("Which team should handle this?", ["billing", "technical"], { escape: true, minConfidence: 0.8 }),
  urgency: score("How urgent is it?", ["low", "medium", "high"], { minConfidence: 0.7, think: true }),
  refund: noul("Does the customer ask for a refund?", { examples: [{ state: "Refund me now", label: true }] }),
  topics: multi("Which topics come up?", ["price", "delivery", "quality"], { threshold: 0.5 }),
  callback: dependsOn(noul("Should someone call the customer back?"), "team", "urgency"),
};
```

`dependsOn(question, ...keys)` answers the question after `keys`, seeing their answers, and
those answers get `stage`.

`options` is a list of keys or a `{ key: description }` object. `think: true` lets that one
question reason in a call of its own; `dependsOn` runs a [workflow in one call](/curva/guides/dependencies/).

## Options

```ts

const curva = new Curva({
  baseUrl: "http://localhost:7777", apiKey: process.env.CURVA_API_KEY, model: "@gemini/gemini-3.1-flash-lite",
  timeout: 30_000, maxRetries: 3, headers: { "x-team": "support" }, fetch,
});
const state = { ticket: "Charged twice, refund please" };
const questions = { refund: noul("Does the customer ask for a refund?") };

await curva.decide(state, questions, {
  model: ["model-a", "model-b"],       // tried in order until one answers
  mode: "auto", debias: true, project: "support", explain: true,
  config: "curva-1.0.0", privacy: "strict",
});
await curva.decide(state, questions, { council: ["model-a", "model-b"] });                // blended; answers get `agreement`
await curva.decide(state, questions, { cascade: ["cheap", "strong"], escalateBelow: 0.8 }); // answers get `answeredBy`
await curva.decide(state, questions, { race: ["model-a", "model-b"] });                   // first valid answer wins
```

`model-a`, `cheap` and the rest stand for your own model ids. `council`, `cascade` and `race`
each replace `model`, so send at most one of them.

Decisions use camelCase: `latencyMs`, `costUsd`, `cached`, `requestId` (the `x-request-id`
header, for matching server logs).

## Actions, ask files and agent tools

```ts

const curva = new Curva();
const d = await curva.decide({ ticket: "I was charged twice, refund me now" }, { refund: noul("Asks for a refund?") }, {
  triggers: { refund: { if: { "@refund": true }, slack: "https://hooks.slack.com/services/T000/B000/XXXX" } },
});
d.actions;   // the triggers that fired: [{ name, id, because }]

await curva.decide({ ticket: "I was charged twice" }, {}, { ask: "support-rules.md" });

const fromCurva = await verifyWebhook(rawBody, request.headers.get("x-curva-signature"), secret, request.headers.get("x-curva-idempotency-key"));

const agentTools = tools({ questions: { team: ["billing", "technical"] }, name: "ticket", policy: "Refunds above $200 need a manager." });
const refund = guarded(async ({ amount }: { amount: number }) => `refunded ${amount}`, { name: "refund", policy: "Refunds above $200 need a manager." });
```

- `triggers` post to `webhook`, `slack`, `teams`, `discord` or `telegram`; `d.actions` lists the
  fired ones. See [Actions](/curva/guides/actions/).
- `ask` takes the path of an [ask file](/curva/guides/ask-files/); on Node, Deno and Bun the SDK reads it and
  sends its text.
- `verifyWebhook(body, signature, secret, idempotencyKey, toleranceSeconds = 300)` resolves to true
  when the `x-curva-signature` header is Curva's signature of its time, the
  `x-curva-idempotency-key` and the raw body, made at most `toleranceSeconds` ago.
- `tools()` gives `{ name, description, parameters, execute }` objects with a strict JSON Schema,
  and `guarded(fn, options)` checks every call against the policy before it runs. See
  [Agent frameworks](/curva/guides/agent-frameworks/).

## Feedback and reports

```ts
await curva.feedback(d.id, "team", "billing");
await curva.calibration("team", "support");
await curva.audit({ project: "support", limit: 100 });
await curva.drift("team", { project: "support", weeks: 8 });
await curva.models();
await curva.health();
```

## Route a prompt to a model

```ts
const r = await curva.route(prompt, { small: "short questions, lookups", large: "hard reasoning, long code" },
                            { default: "large", minConfidence: 0.7 });
r.model; r.confidence; r.defaulted;
```

See [Route a prompt to the right model](/curva/guides/routing/).

## When no model can answer

```ts
const d = await curva.decide(ticket, questions, { fallback: { team: "billing", refund: false } });
if (d.fallback) queueForAPerson(ticket);   // d.error says why
```

One safe answer per question, returned instead of throwing when every model failed, the rate
limit held or the server is unreachable. See [Many models](/curva/guides/multi-model/#when-no-model-can-answer).

## Errors

429, 5xx and dropped connections are retried, honouring `Retry-After`. Anything else throws a
`CurvaError` (with `status`, `type` and `message`), or one of its subclasses: `AuthError`,
`InvalidRequestError`, `NotFoundError`, `RateLimitError` and `ModelError`.
