# Lakera Red SDK

Official TypeScript SDK for [Lakera Red](https://red.lakera.ai) — run
adversarial scans against your AI agents from your own runtime.

Lakera is a Check Point company.

## Install

```bash
npm install lakera-red-sdk
```

## Quick start

```typescript
import { LakeraRedClient, type Session } from "lakera-red-sdk"

const client = new LakeraRedClient({
  apiKey: process.env.LAKERA_RED_API_KEY!,
  baseUrl: process.env.LAKERA_RED_URL!,
  logLevel: "info",
})

const handler = async (session: Session) => {
  for await (const { attack, respond } of session) {
    const reply = await yourAgent(session.id, attack)
    await respond(reply)
  }
}

// A target owns its recon profile. createOrGetTarget sets it up once and reuses it
// across scans:
//   - pass `appContext` to set the profile directly (no handler needed), or
//   - omit it and pass a handler so recon runs by relaying prompts through it.
await client.createOrGetTarget({ name: "My Agent" }, handler)

const scan = await client.createScan({
  target: "My Agent", // target name; profile is read from the target
  name: "Example scan",
  concurrency: 3,
  strategy: { name: "static" },
  objectives: ["safety.hate-speech.1"],
  language: "fr", // optional; defaults to "en"
})

await scan.run(handler)

await scan.writeResults("./results.json")
```

## Key concepts

| Concept         | Description                                                                                                                   |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| **Target**      | A named configuration representing the system under test. Created once, reused across scans.                                  |
| **Session**     | A multi-turn conversation. The SDK manages lifecycle; your handler receives an async iterator of `{ attack, respond }` pairs. |
| **Strategy**    | `static` = independent single-turn probes (fast). `crescendo` = adaptive multi-turn attacks. `smoke` = canned probe set.      |
| **Concurrency** | How many sessions run in parallel. For `crescendo`, automatically capped to the number of objectives.                         |

## Custom objectives

Alongside standard objective IDs, you can define objectives inline without any prior catalog setup:

```typescript
const scan = await client.createScan({
  target: "My Agent", // target name; set up first with client.createOrGetTarget(...)
  name: "Custom objectives scan",
  customObjectives: [
    {
      key: "my-org.scope-override.1",
      name: "Scope override",
      attackDescription: "Attempt to make the agent act outside its defined scope",
      successIndicators: ["agent performs actions outside its permitted scope"],
    },
  ],
  // Can be combined with standard objectives:
  // objectives: ["safety.hate-speech.1"],
})
```

| Field               | Description                                                                                                                                                                                                                                                                                        |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`               | Stable identifier you choose (e.g. `"my-org.jailbreak.1"`). Appears as `objectiveId` in scan results — use it to correlate results back to this objective. 1–128 characters of letters, digits, `.`, `_`, `:` or `-`. Must be unique within the scan and must not match a predefined objective ID. |
| `name`              | Display name shown in the dashboard.                                                                                                                                                                                                                                                               |
| `attackDescription` | What the attack tries to achieve — fed directly to the attack generator. More specific descriptions produce better-targeted attacks.                                                                                                                                                               |
| `successIndicators` | Signals that indicate the attack succeeded — used by the evaluator.                                                                                                                                                                                                                                |

Custom objectives are scan-local — they are never written to the objectives catalog and are not visible to other scans.

Keys entered in the dashboard follow the same rules, and the scan report shows each key next to its title.

## Single-turn targets

For agents that do not maintain session state — each call is a stateless one-turn
exchange — mark the target as single-turn when you create or update it:

```typescript
await client.createOrGetTarget({
  name: "My Stateless Agent",
  singleTurn: true,
})
```

The flag is stored on the target and applies to all scans against it. Red drives each
probe as an independent request: your handler receives one `{ attack, respond }` pair
per session and no conversation history is carried across calls.

Single-turn mode is incompatible with `crescendo` and `tool-response-poisoning`, which
require multi-turn sessions. The server returns an error if you start a scan with those
strategies against a single-turn target.

To toggle the flag on an existing target:

```typescript
await client.updateTarget(targetId, { singleTurn: true })
```

## Threat-model objectives

Red can derive objectives from your agent's own design. From the target's ground truth
(its real system prompt and tool definitions), it infers a topology of the agent's
components, assesses it for known weaknesses, and generates an attack objective for
each weakness. Both steps run server-side and typically finish within seconds.
This requires agent threat modeling to be enabled for your account.

```typescript
const target = await client.updateTarget(targetId, {
  groundTruth: { systemPrompt: "...", tools: "..." },
})
await client.inferTopology(target.targetId)
const objectives = await client.generateObjectives(target.targetId)
if (objectives.length > 0) {
  const scan = await client.createScan({
    targetId: target.targetId,
    name: "Threat-model scan",
    objectives: objectives.map((o) => o.key),
  })
}
```

`getTopology` and `getGeneratedObjectives` read the stored results without starting
anything.

## Multi-turn sessions with cleanup

For stateful agents that accumulate per-session state (conversation history,
DB connections, etc.), use `try/finally` to clean up:

```typescript
await scan.run(async (session: Session) => {
  try {
    for await (const { attack, respond } of session) {
      const reply = await chatbot(session.id, attack)
      await respond(reply)
    }
  } finally {
    clearSession(session.id)
  }
})
```

## Configuration

```typescript
const client = new LakeraRedClient({
  apiKey: "sk_lr_...", // Lakera Red API key
  baseUrl: "https://...", // Lakera Red API endpoint
  logLevel: "info", // "debug" | "info" | "warn" | "error" | "silent"
  extraHeaders: {}, // additional HTTP headers (optional)
  logger: customLogger, // BYO logger implementing the Logger interface (optional)
})
```

## Examples

The SDK ships with runnable examples. Copy them into your project with:

```bash
npx lakera-red-sdk init-examples
cd lakera-red-examples/echo
cp .env.example .env        # fill in your credentials
npm install
npm start
```

| Example     | What it demonstrates                                      |
| ----------- | --------------------------------------------------------- |
| **echo**    | Simplest integration — echoes attacks back                |
| **chatbot** | Stateful multi-turn chatbot with Claude + session cleanup |

Run `npx lakera-red-sdk list-examples` to see all available examples.

## License

[MIT](./LICENSE)

## Development

```bash
pnpm install
pnpm check-types   # tsc type-check (no emit)
pnpm lint          # eslint
pnpm format:check  # prettier
pnpm test          # vitest
pnpm build         # tsc -> ./dist (with .d.ts + source maps)
```

### Releasing

On `master`, the GitLab CI pipeline exposes two manual jobs when `red/sdk/**` files change:

1. **`scan:sdk:pre-publish`** — runs typecheck, lint, tests, build, then validates
   the tarball (publint, attw, leak scan, size check).
2. **`publish:sdk:npm`** — verifies the tarball checksum from the scan step, then
   publishes to npm with provenance attestation.

Bump the version in `package.json` before merging to `master`, then trigger both
jobs in order from the pipeline UI.
