Capri

Capri 1 · API reference

Your agent writes the code.
Capri calls the next move.

Capri is a steering model for coding agents. You don’t chat with it. You send what your agent is doing — its goal and what each step produced — and ask typed questions. Capri answers with probabilities, a surprise score and the smallest useful move: keep going, a factual note for your agent, a re-plan, or “not done yet”.

Get access

  1. Subscribe to Basic ($50 a month) in the console. It includes 4,000 Capri credits a month.
  2. Create a key. Test keys (nika_cp_test_…) cost nothing; live keys (nika_cp_live_…) use your credits. Pick its scopes, and if you like a monthly cap and an expiry: see Keys.
  3. Keep the key on your server. Send it as Authorization: Bearer … (or in an X-Api-Key header). Never put it in a browser.

Protecting a web app you built yourself? Capri Shield is included in Basic for up to 10 of your sites, and it’s opening gradually.

Quickstart

The example below is a classic slip: the tests pass and the agent says it’s done, but two callers still use the old signature. Capri flags it and writes the note.

curl
# bash or zsh. Keep the key in an environment variable: export CAPRI_API_KEY=nika_cp_test_...
curl -sS https://www.codename-nika.com/api/capri/v1/predict/ \
  -H "Authorization: Bearer $CAPRI_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @- <<'JSON'
{
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "events": [
    {
      "seq": 1,
      "at": 1764600000000,
      "kind": "intent",
      "text": "Add a clock-skew option to verifyToken in src/auth.ts."
    },
    {
      "seq": 2,
      "at": 1764600004000,
      "kind": "diff",
      "files": [
        {
          "path": "src/auth.ts",
          "add": 12,
          "del": 3,
          "symbols": ["verifyToken"]
        }
      ]
    },
    {
      "seq": 3,
      "at": 1764600005000,
      "kind": "refs",
      "symbol": "verifyToken",
      "files": ["src/middleware.ts", "src/api/session.ts"]
    },
    {
      "seq": 4,
      "at": 1764600009000,
      "kind": "test",
      "runner": "jest",
      "passed": 16,
      "failed": 0,
      "source": "agent"
    },
    {
      "seq": 5,
      "at": 1764600012000,
      "kind": "intent",
      "text": "Auth tests pass. The change is done."
    }
  ],
  "asks": {
    "next": { "type": "next", "top": 3 },
    "health": { "type": "flags" },
    "done": { "type": "done" }
  },
  "settings": { "decisions": "auto" },
  "wait": "rules"
}
JSON
TypeScript
// Server-side only (Node 18+). Keep the trailing slash, and never send the key to a browser.
const CAPRI = "https://www.codename-nika.com/api/capri/v1/"
const OPTIONS = {
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "settings": { "decisions": "auto" },
  "wait": "rules"
}

type Answer = { by: 'rules' | 'model'; as_of_seq: number; fresh: boolean; calibrated: boolean; [field: string]: unknown }
/** One step back from Capri: typed answers, never prose to parse. */
export type CapriStep = {
  object: 'capri.step'
  model: string
  livemode: boolean
  folded_through: number | null
  resolved: unknown[]
  surprise: { score: number; trend: number; hard: string | null; drivers: string[] }
  steer: { rung: 'R0' | 'R1' | 'R2' | 'R3' | 'R4' | 'R5' | 'R6'; action: string; trigger: string; by: 'rules' | 'model'; note?: { text: string } }
  veto: string[]
  checks: { kind: string; priority: 'gate' | 'spec' }[]
  green: { ok: boolean; missing: string[] }
  answers: Record<string, Answer>
  narration?: { text: string } // notable steps only, with settings.narrate: for people, never for your agent
  usage: { credits: number; allowance_remaining: number | null; metered_as: 'allowance' | 'test' }
  warnings: { code: string; [detail: string]: unknown }[]
  degraded: string[]
  state: string
}

let state: string | undefined // the agent's mind so far: send it back with every call

export async function predict(events: object[], asks: Record<string, { type: string; [param: string]: unknown }>): Promise<CapriStep> {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(CAPRI + 'predict/', {
      method: 'POST',
      headers: { Authorization: `Bearer ${process.env.CAPRI_API_KEY}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...OPTIONS, events, asks, state }),
    })
    // 429 and 503 ran nothing: a Retry-After of 10 s or less is waited out, 3 tries in all. Capri can ask for an hour
    // or more, so a longer one is thrown at once (with retryAfter): a request to your server never hangs on it.
    const retryAfter = Number(res.headers.get('Retry-After')) || null
    if ((res.status === 429 || res.status === 503) && (retryAfter ?? 2) <= 10 && attempt < 3) {
      await new Promise((r) => setTimeout(r, 1000 * (retryAfter ?? 2)))
      continue
    }
    const text = await res.text() // as text: a proxy's or a gateway's page isn't JSON
    let json: any
    try {
      json = JSON.parse(text)
    } catch {
      throw new Error(`Capri answered ${res.status} without JSON: ${text.slice(0, 200)}`)
    }
    if (!res.ok) throw Object.assign(new Error(json.error?.message ?? `Capri answered ${res.status}`), json.error, { status: res.status, retryAfter })
    state = json.state
    return json
  }
}

const EVENTS = [
  {
    "seq": 1,
    "at": 1764600000000,
    "kind": "intent",
    "text": "Add a clock-skew option to verifyToken in src/auth.ts."
  },
  {
    "seq": 2,
    "at": 1764600004000,
    "kind": "diff",
    "files": [
      {
        "path": "src/auth.ts",
        "add": 12,
        "del": 3,
        "symbols": ["verifyToken"]
      }
    ]
  },
  {
    "seq": 3,
    "at": 1764600005000,
    "kind": "refs",
    "symbol": "verifyToken",
    "files": ["src/middleware.ts", "src/api/session.ts"]
  },
  {
    "seq": 4,
    "at": 1764600009000,
    "kind": "test",
    "runner": "jest",
    "passed": 16,
    "failed": 0,
    "source": "agent"
  },
  {
    "seq": 5,
    "at": 1764600012000,
    "kind": "intent",
    "text": "Auth tests pass. The change is done."
  }
]
const ASKS = {
  "next": { "type": "next", "top": 3 },
  "health": { "type": "flags" },
  "done": { "type": "done" }
}

// After each agent message, send what it did since the last call:
predict(EVENTS, ASKS).then((step) => {
  if (step.steer.note) console.log(step.steer.note.text) // hand the note to your agent as-is
  if (!step.green.ok) console.log('Not green yet:', step.green.missing.join(', '))
  for (const [name, answer] of Object.entries(step.answers)) console.log(name, answer)
})
Python
# Python 3.9+ with httpx (pip install httpx). Server-side only; keep the trailing slash.
import json, os, time, httpx

CAPRI = "https://www.codename-nika.com/api/capri/v1/"
AUTH = {"Authorization": f"Bearer {os.environ['CAPRI_API_KEY']}"}
OPTIONS = {
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "settings": { "decisions": "auto" },
  "wait": "rules"
}
state = None  # the agent's mind so far: send it back with every call


def predict(events, asks):
    """One step: events and asks in, typed answers out."""
    global state
    body = {**OPTIONS, "events": events, "asks": asks}
    if state:
        body["state"] = state
    for attempt in range(1, 4):
        r = httpx.post(CAPRI + "predict/", headers=AUTH, json=body, timeout=30)
        # 429 and 503 ran nothing: a Retry-After of 10 s or less is waited out, 3 tries in all. Capri can ask for an
        # hour or more, so a longer one is raised at once (with retry_after): a request to your server never hangs on it.
        header = r.headers.get("Retry-After", "")
        retry_after = int(header) if header.isdigit() else None
        if r.status_code in (429, 503) and (retry_after or 2) <= 10 and attempt < 3:
            time.sleep(retry_after or 2)
            continue
        try:
            data = json.loads(r.text)  # as text: a proxy's or a gateway's page isn't JSON
        except ValueError:
            raise RuntimeError(f"Capri answered {r.status_code} without JSON: {r.text[:200]}") from None
        if r.is_error:
            error = RuntimeError(data["error"]["message"])
            error.status, error.retry_after = r.status_code, retry_after
            raise error
        state = data["state"]
        return data


EVENTS = [
  {
    "seq": 1,
    "at": 1764600000000,
    "kind": "intent",
    "text": "Add a clock-skew option to verifyToken in src/auth.ts."
  },
  {
    "seq": 2,
    "at": 1764600004000,
    "kind": "diff",
    "files": [
      {
        "path": "src/auth.ts",
        "add": 12,
        "del": 3,
        "symbols": ["verifyToken"]
      }
    ]
  },
  {
    "seq": 3,
    "at": 1764600005000,
    "kind": "refs",
    "symbol": "verifyToken",
    "files": ["src/middleware.ts", "src/api/session.ts"]
  },
  {
    "seq": 4,
    "at": 1764600009000,
    "kind": "test",
    "runner": "jest",
    "passed": 16,
    "failed": 0,
    "source": "agent"
  },
  {
    "seq": 5,
    "at": 1764600012000,
    "kind": "intent",
    "text": "Auth tests pass. The change is done."
  }
]
ASKS = {
  "next": { "type": "next", "top": 3 },
  "health": { "type": "flags" },
  "done": { "type": "done" }
}

# After each agent message, send what it did since the last call:
step = predict(EVENTS, ASKS)
note = step["steer"].get("note")
if note:
    print(note["text"])  # hand the note to your agent as-is
if not step["green"]["ok"]:
    print("Not green yet:", ", ".join(step["green"]["missing"]))
for name, answer in step["answers"].items():
    print(name, answer)

Every URL ends in a slash. A POST without it gets a redirect that many clients won’t follow.

Endpoints

Every path is relative to https://www.codename-nika.com/api/capri/v1/.

Method · pathWhat it does
GET models/Lists the model: capri-1, its dated snapshot, type: "steering" and the asks it answers. No key needed.
GET models/{model}/One model, by its dated id or capri-1: either answers the same build. No key needed.
GET openapi/This API as an OpenAPI 3.1 document. No key needed. See OpenAPI reference.
POST predict/One step: fold your agent’s new events into Capri’s memory, answer your asks, return the next move and a new state.
POST sessions/Opens a session for one run of your agent. Capri keeps its memory of the run, so you carry no state. See session mode.
GET sessions/{id}/The session’s summary: status, counts, green and the last surprise. Never its content.
POST sessions/{id}/events/One step in a session: fold up to 50 new events and answer your asks.
GET sessions/{id}/updates/Long-polls up to 25 s for slower results. Or keep one connection open with stream/.
GET sessions/{id}/stream/The same items as updates/, as Server-Sent Events, each as it lands. See Streaming.
POST sessions/{id}/feedback/What your harness did with a note or a decision, between events calls.
POST sessions/{id}/close/Closes the session. Its content is kept retention_days, then erased.
DELETE sessions/{id}/Erases the session and its content now.
GET sessions/{id}/plan/The session’s living plan: each step’s status, what’s next, and progress. See plans.
POST sessions/{id}/replans/Starts a re-plan (or an extend) of the session’s plan. It answers 202; the result arrives in updates/.
GET replans/{id}/One re-plan: its status, and once it ends, what changed.
GET usage/Calls and credits per UTC day, for your key and its account.

OpenAPI reference

GET openapi/ answers the whole capri.v1 API as an OpenAPI 3.1 JSON document: every endpoint on this page, with its parameters, answers, errors and examples. It needs no key, touches no database, and is cached 5 minutes, like models/.

Import it into an API client, or generate types from it. Capri’s own tests validate the examples on this page against its schemas, all but the ones marked excerpt or shortened. Where this page and the document differ, that’s a bug.

curl
curl -sS https://www.codename-nika.com/api/capri/v1/openapi/ -o capri-openapi.json

Keys

Make keys in the console. Each key has scopes, what it can call, and can have a monthly cap and an expiry. New keys get predict and steer unless you pick others.

ScopeWhat it can call
predictPOST predict/.
steerEverything under sessions/ and replans/, reads included, and GET usage/.
voiceAccepted and kept with the key; nothing uses it yet.

Monthly caps

A live key can have a monthly cap of 1-100,000 credits, per calendar month in UTC. Each call holds its ceiling against the cap as it does against your allowance, and settles to what it used. Past its cap the key answers 402 key_cap_reached until 00:00 UTC on the 1st, and resets_at says when. A cap only narrows your allowance: the account’s credits still apply. Test keys cost nothing, so a cap never touches them.

Plans, re-plans and extends hold their ceilings against the cap too: 62, 42 and 21 credits. A cap below a ceiling can never hold that work, and asking for it answers 402 key_cap_too_low.

Expiry

A key can expire 1-365 days after it’s made. Past its expiry it’s refused exactly like a revoked one: 401 invalid_api_key.

Rotation

Rotating a key in the console makes a new one with the same name (marked “(rotated)”), scopes, monthly cap and expiry, shown once. The old key keeps working for an overlap you choose, 0-72 hours (24 by default), then expires; never later than it already would have. Each key counts its own use against its cap, so the new one starts the month from zero. Revoking still stops a key on its next call. An open stream/ checks its key again before it sends an item and at least once a minute, so a revoked key’s streams end within a minute (see Streaming). An Idempotency-Key retry still replays across a rotation: keys belong to the account.

Keys in your Nika apps

Apps you build in Nika can call Capri from their server code. In the console, under Apps, Insert adds lib/ai/capri.ts to a web app (src/lib/ai/capri.ts when the app keeps its code in a src folder) and saves a key of the app’s own as NIKA_CAPRI_KEY in the app’s keys. That key has the predict and steer scopes and a monthly cap of 1,000 credits, and it reaches the app when you publish it. Previews don’t get it, so check capriConfigured() first. Mobile apps, imported static sites, apps written in JavaScript and apps without an app/layout.tsx or src/app/layout.tsx can’t take it.

Inserting again or rotating gives the app a new key. Old keys keep working for an overlap, 24 hours by default when the app is published and none when it isn’t, so publish the app again before it ends. No old key outlives the newest overlap, so rotating with 0 hours stops all of them at once. Remove stops the app’s keys at once and deletes the setting. Rotate an app’s key under Apps: rotating it in the key list answers 409 app_key, because the app would keep the old key. An app’s key shares the account’s limits with your other keys, such as its 20 open sessions.

The client waits out a 429 or 503 only when its Retry-After is 10 seconds or less. A longer one comes back at once as a CapriError with retryAfter set, so a request to your app never hangs. readCapriWebhook() checks a delivery’s Nika-Signature header, within 300 seconds either way.

Request

FieldMeaning
model"capri-1" (always the newest snapshot) or a dated id to pin one.
goalWhat the agent is trying to do, in plain words (up to 2,000 characters).
done_means · rulesOptional: checkable done criteria, and your house rules.
agent · repoOptional: the agent kind, and facts Capri can’t see (languages, check kinds, test runner, files that change together).
eventsWhat happened since your last call, up to 50, each with a rising seq, at (ms) and kind.
asksYour questions, keyed by names you choose, up to 12. With none, you get next, outcome, ripples, flags and done.
settings.decisions"auto": Capri makes the call and your harness carries it out or vetoes it. "recommend": Capri recommends and you decide. Until "auto" opens to every account, a call that asks for it where it isn’t open yet runs "recommend" (the same choice, as a recommendation), and its warnings include decisions_downgraded. See Decisions.
settings.policyOptional limits that can only narrow what Capri may decide (for example, no re-plans).
settings.narrate"none" (the default), "text" or "audio": a line for the person watching, on notable steps only. It’s free, and read on every call. See Narration.
wait"rules" (default, fast) or "hunch" (waits up to 12 s for a fresh model prediction; costs a little more).
stateThe state from Capri’s last answer for this run. Leave it out on the first call.

Event kinds

toolA tool call your agent made (name, target files).
diffFiles changed, with lines added and removed and the symbols touched.
shellA command your agent ran, with its exit code.
testA test run: runner, passed, failed, failing files.
diagTypecheck or lint diagnostics.
checkA check your harness ran (not the agent).
intentWhat the agent said it is doing or has done.
turnAn agent turn started or ended.
refsFiles that reference a symbol (for example, callers of a function).
status · usage · question · permission · gitAgent status, token use, a question it asked, a permission prompt, git state.
humanYour own edits. Never treated as a surprise.
agentThe agent hit a usage limit. Pauses, never alarms.
note_ack · decisionWhether your harness delivered a Capri note, and what it did with a Capri decision.

Unknown kinds come back as a warning, never an error. Secrets, emails and phone numbers are scrubbed before anything is read.

Asks

nextThe likely next moves, with probabilities (top N).
choicePick between your own candidates. Outward actions (push, deploy, publish, send, buy) are always excluded.
outcomeWill a check pass? p_pass and the files likely to fail.
ripplesOther files that must change because of an edit.
risksWhat may break, and the check that would show it.
missing_testsDone criteria that no test covers yet.
rulesConflicts with your house rules.
flagsLoop, drift and a premature "done". With a session plan, plan_step too: the step the agent is on, as { id, status }.
lookaheadThe next few steps. With a session plan: the next step and up to 3 after it, each { id, title, targets, expect, status, p }.
done · doomThe chance the work is really done, or that this milestone fails.

Ask types: next, choice, outcome, ripples, risks, missing_tests, rules, flags, lookahead, done, doom. There are no free-text questions.

Response

object · model"capri.step" and the dated model snapshot that answered.
folded_throughThe last event seq Capri has taken in.
surprisescore (0-1), trend, hard (a hard jolt, if any) and its drivers.
steerThe smallest useful move: rung R0-R6, action, trigger, an optional factual note for your agent, and in auto mode the decision itself. In session mode, also a re-plan Capri recommends (replan).
veto · checks · greenOutward or risky attempts to block, the check kinds worth running next, and whether the work is green.
answersOne typed answer per ask. Each says by (rules or model), as_of_seq, fresh and calibrated.
narrationOnly on notable steps, with settings.narrate "text" or "audio": { text, cue, serious }, one line of at most 400 characters for the person watching. Never for your agent (see Narration).
audioWith settings.narrate "audio", beside narration: { "status": "unavailable", "credits": 0 }. Audio isn’t available yet, and costs nothing.
usageCredits this call used and your allowance left.
warnings · degradedThings to know, and "rules-only" when the model part is unavailable. A step never fails because a model is down. One warning to know: { "code": "decisions_downgraded", "reason": "auto_not_available" } means the call asked for "auto" decisions, which aren’t open to the account yet, so it ran "recommend" (see Decisions).
stateCapri’s memory of this run, signed. Send it back with your next call.

State

Capri keeps nothing between calls. Its memory of the run travels in state: signed, at most 16 KB, and only readable by Capri. Send the latest one back with each call. A changed state is refused.

Decisions

In auto mode, steer.decision is Capri’s call (for example, block a “done” while checks are red). Your harness carries it out or vetoes it and reports back with a decision event. Capri never decides anything outward: pushes, deploys, publishing, sending and buying stay yours.

During the beta, auto decisions are open only to the design partners Nika turns them on for. Every other account runs in recommend mode: a call or a session that asks for "auto" runs "recommend", and its warnings include decisions_downgraded. A session’s settings.decisions shows the mode it runs in.

In recommend mode there is no steer.decision: steer.recommendation is the decision Capri would make in auto mode, and it is never carried out. Your harness can show it, log it, or act on it itself.

The example request
{
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "events": [
    {
      "seq": 1,
      "at": 1764600000000,
      "kind": "intent",
      "text": "Add a clock-skew option to verifyToken in src/auth.ts."
    },
    {
      "seq": 2,
      "at": 1764600004000,
      "kind": "diff",
      "files": [
        {
          "path": "src/auth.ts",
          "add": 12,
          "del": 3,
          "symbols": ["verifyToken"]
        }
      ]
    },
    {
      "seq": 3,
      "at": 1764600005000,
      "kind": "refs",
      "symbol": "verifyToken",
      "files": ["src/middleware.ts", "src/api/session.ts"]
    },
    {
      "seq": 4,
      "at": 1764600009000,
      "kind": "test",
      "runner": "jest",
      "passed": 16,
      "failed": 0,
      "source": "agent"
    },
    {
      "seq": 5,
      "at": 1764600012000,
      "kind": "intent",
      "text": "Auth tests pass. The change is done."
    }
  ],
  "asks": {
    "next": { "type": "next", "top": 3 },
    "health": { "type": "flags" },
    "done": { "type": "done" }
  },
  "settings": { "decisions": "auto" },
  "wait": "rules"
}

Narration

Narration is a line about the step for the person watching the run, like a caption. Ask for it with settings.narrate: "none" (the default), "text" or "audio". On predict/ it’s read on every call; on sessions/ it’s fixed when the session opens, and the summary shows it as settings.narrate when it’s "text" or "audio" (absent for "none").

It comes only on notable steps: rung R1 or higher, a confident prediction that came true, a big miss, the step that turns green, and the step that delivers a ready re-plan. Any other step has no narration key.

It’s for people. Show it as a caption. Never hand it to your agent: steer.note is your agent’s.

Done, it says. But two files go with this change and weren't touched, and the typecheck is behind the latest edit. Seventy-two percent that's early.

POST predict/ with settings.narrate "text" · the note for the agent, and the line for you (excerpt)
{
  "steer": {
    "rung": "R1",
    "action": "note",
    "trigger": "ripple_at_done_claim",
    "note": {
      "text": "[Capri note 1] `verifyToken` in `src/auth.ts` changed. These reference it and were not edited since: `src/middleware.ts`, `src/api/session.ts`. Typecheck has not run since the last edit to `src/auth.ts`."
    }
  },
  "narration": {
    "text": "Done, it says. But two files go with this change and weren't touched, and the typecheck is behind the latest edit. Seventy-two percent that's early.",
    "cue": "done_ripples",
    "serious": false
  }
}
FieldMeaning
textThe line, at most 400 characters, in plain sentences: no digits, paths or links.
cueWhich kind of notable step it is: done_ripples, done_gaps, regression, confirmed, new_errors, stuck, house_rule, compaction, replan, escalate, agent_stopped, outward_blocked, forbidden_blocked, outward_question, replan_delivered, green, hit, miss. New cues can appear.
serioustrue on destructive, security, money and approval steps, whose line is in plain words. Style it apart if you like.

With settings.notes "off" Capri writes no notes, so the lines that go with a note (rung R1, such as a done claim with gaps, or a compaction) and a landed re-plan’s line never come. The rest still do: R2 and above, a confident prediction that came true, a big miss, and the step that turns green. Keep notes "shadow" (the default) if you only want narration.

"audio" adds audio: { "status": "unavailable", "credits": 0 } beside the text. Audio isn’t available yet, and nothing is charged. There’s no way to send text to be spoken.

Session mode

With predict/, your code carries Capri’s memory of a run in state. In session mode Capri keeps it for you, encrypted on our side: your harness opens a session for each run, sends each agent message’s events to it, long-polls for slower results, and closes it when the run ends. It can also keep one connection open and get those results as they land: see Streaming. Each events call answers and costs exactly like predict/. You can also see, close and delete your sessions in the console. A session can also keep a living plan, your own or one Capri writes, and re-plan it when the run goes off course: see Plans and re-plans.

curl
# bash or zsh, with jq. Keep the key in an environment variable: export CAPRI_API_KEY=nika_cp_test_...
CAPRI=https://www.codename-nika.com/api/capri/v1/

# 1. Open a session for this run. A retry with the same Idempotency-Key gets the same session back.
SESSION=$(curl -sS ${CAPRI}sessions/ \
  -H "Authorization: Bearer $CAPRI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: run-4821-open" \
  --data-binary @- <<'JSON' | jq -r .id
{
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "settings": { "decisions": "auto" },
  "retention_days": 7,
  "metadata": { "run": "run-4821" }
}
JSON
)

# 2. After each agent message, send what it did as one batch; seq keeps rising across batches.
curl -sS ${CAPRI}sessions/$SESSION/events/ \
  -H "Authorization: Bearer $CAPRI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: run-4821-batch-1" \
  --data-binary @- <<'JSON'
{
  "events": [
    {
      "seq": 1,
      "at": 1764600000000,
      "kind": "intent",
      "text": "Add a clock-skew option to verifyToken in src/auth.ts."
    },
    {
      "seq": 2,
      "at": 1764600004000,
      "kind": "diff",
      "files": [
        {
          "path": "src/auth.ts",
          "add": 12,
          "del": 3,
          "symbols": ["verifyToken"]
        }
      ]
    },
    {
      "seq": 3,
      "at": 1764600005000,
      "kind": "refs",
      "symbol": "verifyToken",
      "files": ["src/middleware.ts", "src/api/session.ts"]
    },
    {
      "seq": 4,
      "at": 1764600009000,
      "kind": "test",
      "runner": "jest",
      "passed": 16,
      "failed": 0,
      "source": "agent"
    },
    {
      "seq": 5,
      "at": 1764600012000,
      "kind": "intent",
      "text": "Auth tests pass. The change is done."
    }
  ],
  "asks": {
    "next": { "type": "next", "top": 3 },
    "health": { "type": "flags" },
    "done": { "type": "done" }
  }
}
JSON

# 3. Long-poll for slower results: it waits up to 25 s, then answers with any new items and next_after.
curl -sS "${CAPRI}sessions/$SESSION/updates/?after=0&wait=25" \
  -H "Authorization: Bearer $CAPRI_API_KEY"

# 4. When the run ends, close it: its content is kept retention_days, then erased.
curl -sS -X POST ${CAPRI}sessions/$SESSION/close/ \
  -H "Authorization: Bearer $CAPRI_API_KEY"
TypeScript
// Server-side only (Node 18+). Keep the trailing slash, and never send the key to a browser.
const CAPRI = "https://www.codename-nika.com/api/capri/v1/"

/** One call to Capri. It retries a short 429 or 503, and an Idempotency-Key makes a retried POST safe. */
async function capri<T>(path: string, body?: unknown, idempotencyKey?: string): Promise<T> {
  const headers: Record<string, string> = { Authorization: `Bearer ${process.env.CAPRI_API_KEY}`, 'Content-Type': 'application/json' }
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(CAPRI + path, { method: body === undefined ? 'GET' : 'POST', headers, body: body === undefined ? undefined : JSON.stringify(body) })
    // 429 and 503 ran nothing: a Retry-After of 10 s or less is waited out, 3 tries in all. Capri can ask for an hour
    // or more, so a longer one is thrown at once (with retryAfter): a request to your server never hangs on it.
    const retryAfter = Number(res.headers.get('Retry-After')) || null
    if ((res.status === 429 || res.status === 503) && (retryAfter ?? 2) <= 10 && attempt < 3) {
      await new Promise((r) => setTimeout(r, 1000 * (retryAfter ?? 2)))
      continue
    }
    const text = await res.text() // as text: a proxy's or a gateway's page isn't JSON
    let json: any
    try {
      json = JSON.parse(text)
    } catch {
      throw new Error(`Capri answered ${res.status} without JSON: ${text.slice(0, 200)}`)
    }
    if (!res.ok) throw Object.assign(new Error(json.error?.message ?? `Capri answered ${res.status}`), json.error, { status: res.status, retryAfter })
    return json as T
  }
}

type Session = { id: string; status: 'open' | 'closed' | 'expired'; next_seq: number }
/** A capri.step, as predict/ answers it, with the session id in place of the state. */
type Step = { session: string; folded_through: number | null; steer: { rung: string; note?: { text: string } }; green: { ok: boolean; missing: string[] } }
type Updates = { items: { id: number; kind: string; created_at: string; body: unknown }[]; next_after: number }

const OPEN = {
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "settings": { "decisions": "auto" },
  "retention_days": 7,
  "metadata": { "run": "run-4821" }
}
const EVENTS = [
  {
    "seq": 1,
    "at": 1764600000000,
    "kind": "intent",
    "text": "Add a clock-skew option to verifyToken in src/auth.ts."
  },
  {
    "seq": 2,
    "at": 1764600004000,
    "kind": "diff",
    "files": [
      {
        "path": "src/auth.ts",
        "add": 12,
        "del": 3,
        "symbols": ["verifyToken"]
      }
    ]
  },
  {
    "seq": 3,
    "at": 1764600005000,
    "kind": "refs",
    "symbol": "verifyToken",
    "files": ["src/middleware.ts", "src/api/session.ts"]
  },
  {
    "seq": 4,
    "at": 1764600009000,
    "kind": "test",
    "runner": "jest",
    "passed": 16,
    "failed": 0,
    "source": "agent"
  },
  {
    "seq": 5,
    "at": 1764600012000,
    "kind": "intent",
    "text": "Auth tests pass. The change is done."
  }
]
const ASKS = {
  "next": { "type": "next", "top": 3 },
  "health": { "type": "flags" },
  "done": { "type": "done" }
}

export async function steer(runId: string): Promise<void> {
  // 1. Open a session for this run. Capri keeps its memory, so there is no state to carry.
  const session = await capri<Session>('sessions/', OPEN, `${runId}-open`)

  // 2. After each agent message, send what it did as one batch; seq keeps rising across batches.
  const step = await capri<Step>(`sessions/${session.id}/events/`, { events: EVENTS, asks: ASKS }, `${runId}-batch-1`)
  if (step.steer.note) console.log(step.steer.note.text) // hand the note to your agent as-is
  if (!step.green.ok) console.log('Not green yet:', step.green.missing.join(', '))

  // 3. Long-poll for slower results: it waits up to 25 s, then answers with any new items.
  //    Next time, pass after=next_after to get only what is new.
  const updates = await capri<Updates>(`sessions/${session.id}/updates/?after=0&wait=25`)
  for (const item of updates.items) console.log(item.kind, item.body)

  // 4. When the run ends, close it: its content is kept retention_days, then erased.
  await capri<Session>(`sessions/${session.id}/close/`, {})
}

steer("run-4821").catch(console.error)
Python
# Python 3.9+ with httpx (pip install httpx). Server-side only; keep the trailing slash.
import json, os, time, httpx

CAPRI = "https://www.codename-nika.com/api/capri/v1/"
AUTH = {"Authorization": f"Bearer {os.environ['CAPRI_API_KEY']}"}


def capri(method, path, body=None, idempotency_key=None):
    """One call to Capri. Retries a short 429 or 503; an Idempotency-Key makes a retried POST safe."""
    headers = {**AUTH, "Idempotency-Key": idempotency_key} if idempotency_key else AUTH
    for attempt in range(1, 4):
        r = httpx.request(method, CAPRI + path, headers=headers, json=body, timeout=35)
        # 429 and 503 ran nothing: a Retry-After of 10 s or less is waited out, 3 tries in all. Capri can ask for an
        # hour or more, so a longer one is raised at once (with retry_after): a request to your server never hangs on it.
        header = r.headers.get("Retry-After", "")
        retry_after = int(header) if header.isdigit() else None
        if r.status_code in (429, 503) and (retry_after or 2) <= 10 and attempt < 3:
            time.sleep(retry_after or 2)
            continue
        try:
            data = json.loads(r.text)  # as text: a proxy's or a gateway's page isn't JSON
        except ValueError:
            raise RuntimeError(f"Capri answered {r.status_code} without JSON: {r.text[:200]}") from None
        if r.is_error:
            error = RuntimeError(data["error"]["message"])
            error.status, error.retry_after = r.status_code, retry_after
            raise error
        return data


OPEN = {
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "settings": { "decisions": "auto" },
  "retention_days": 7,
  "metadata": { "run": "run-4821" }
}
EVENTS = [
  {
    "seq": 1,
    "at": 1764600000000,
    "kind": "intent",
    "text": "Add a clock-skew option to verifyToken in src/auth.ts."
  },
  {
    "seq": 2,
    "at": 1764600004000,
    "kind": "diff",
    "files": [
      {
        "path": "src/auth.ts",
        "add": 12,
        "del": 3,
        "symbols": ["verifyToken"]
      }
    ]
  },
  {
    "seq": 3,
    "at": 1764600005000,
    "kind": "refs",
    "symbol": "verifyToken",
    "files": ["src/middleware.ts", "src/api/session.ts"]
  },
  {
    "seq": 4,
    "at": 1764600009000,
    "kind": "test",
    "runner": "jest",
    "passed": 16,
    "failed": 0,
    "source": "agent"
  },
  {
    "seq": 5,
    "at": 1764600012000,
    "kind": "intent",
    "text": "Auth tests pass. The change is done."
  }
]
ASKS = {
  "next": { "type": "next", "top": 3 },
  "health": { "type": "flags" },
  "done": { "type": "done" }
}

# 1. Open a session for this run. Capri keeps its memory, so there is no state to carry.
session = capri("POST", "sessions/", OPEN, "run-4821-open")
sid = session["id"]

# 2. After each agent message, send what it did as one batch; seq keeps rising across batches.
step = capri("POST", f"sessions/{sid}/events/", {"events": EVENTS, "asks": ASKS}, "run-4821-batch-1")
note = step["steer"].get("note")
if note:
    print(note["text"])  # hand the note to your agent as-is

# 3. Long-poll for slower results: it waits up to 25 s, then answers with any new items.
#    Next time, pass after=next_after to get only what is new.
updates = capri("GET", f"sessions/{sid}/updates/?after=0&wait=25")
for item in updates["items"]:
    print(item["kind"], item["body"])

# 4. When the run ends, close it: its content is kept retention_days, then erased.
capri("POST", f"sessions/{sid}/close/", {})

Opening a session

POST sessions/ fixes what stays true for the whole run. Opening is free, but needs Basic, and with a live key enough credits left for one call (402 otherwise). It answers 201 with the session.

FieldMeaning
modelRequired. "capri-1" (always the newest snapshot) or a dated id.
goalRequired. What the agent is trying to do, in plain words (1-2,000 characters).
done_means · rulesOptional: up to 8 checkable done criteria, and up to 20 house rules.
agent · repoOptional: the agent’s kind, a short name (a string, or { kind }); a kind Capri doesn’t know reads as "other". The names the adapters send are in Other agents. Then facts Capri can’t see: languages, check_kinds, test_runner, co_change and tree. With no languages, the paths in your first events name them.
preferencesOptional: how you like the work done, in up to 2,000 characters.
planOptional: { "source": "capri" } for a plan Capri writes (billed), your own steps as { "source": "client", "steps": [...] } with 1-25 steps, or { "source": "none" }, the default. See Plans and re-plans.
settingsOptional: decisions ("recommend" by default, or "auto"), notes ("shadow" by default, "live" or "off"), intensity ("balanced" by default, "quiet" or "eager"), narrate ("none" by default, "text" or "audio") and policy, read as predict/ reads them. Session mode adds replans ("manual" by default, "auto" or "off"): who starts re-plans.
retention_daysOptional: how many days the content stays after you close the session, 0-30 (7 by default). With 0 it goes as soon as you close.
metadataOptional: your own tags, up to 2 KB, returned with the session and never read by a model. Keep secrets out of it.

Chat fields (messages, system, instructions, prompt) are refused with a 400: Capri reads agent events and typed asks, not chat.

POST sessions/ → 201, as an account without auto decisions gets it
{
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "settings": { "decisions": "auto" },
  "retention_days": 7,
  "metadata": { "run": "run-4821" }
}

{
  "object": "capri.session",
  "id": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
  "model": "capri-1-20261028",
  "livemode": false,
  "status": "open",
  "next_seq": 1,
  "plan": { "source": "none" },
  "settings": {
    "decisions": "recommend",
    "notes": "shadow",
    "intensity": "balanced",
    "replans": "manual",
    "policy": null
  },
  "retention_days": 7,
  "metadata": { "run": "run-4821" },
  "counts": {
    "calls": 0,
    "events": 0,
    "hunches": 0,
    "notes": 0,
    "decisions": 0,
    "credits": 0
  },
  "green": null,
  "last_surprise": null,
  "created_at": "2026-10-28T12:00:00.000Z",
  "updated_at": "2026-10-28T12:00:00.000Z",
  "closed_at": null,
  "expires_at": "2026-10-29T12:00:00.000Z",
  "limits": { "events_per_call": 50, "events_per_minute": 60 },
  "warnings": [{ "code": "decisions_downgraded", "reason": "auto_not_available" }]
}

Sending events

After each agent message, POST sessions/{id}/events/ with { events, asks?, wait? }: what happened since the last batch, the asks you want answered, and wait as for predict/. Everything else was fixed when the session opened, so a goal, settings or state here is a 400. The answer is predict/’s capri.step with session, the id, in place of state, metered the same, with the same Capri-Credits header.

POST sessions/{id}/events/ · late and missing events, as warnings
{
  "events": [
    {
      "seq": 1,
      "at": 1764600000000,
      "kind": "intent",
      "text": "Add a clock-skew option to verifyToken in src/auth.ts."
    },
    {
      "seq": 2,
      "at": 1764600004000,
      "kind": "diff",
      "files": [
        {
          "path": "src/auth.ts",
          "add": 12,
          "del": 3,
          "symbols": ["verifyToken"]
        }
      ]
    },
    {
      "seq": 3,
      "at": 1764600005000,
      "kind": "refs",
      "symbol": "verifyToken",
      "files": ["src/middleware.ts", "src/api/session.ts"]
    },
    {
      "seq": 4,
      "at": 1764600009000,
      "kind": "test",
      "runner": "jest",
      "passed": 16,
      "failed": 0,
      "source": "agent"
    },
    {
      "seq": 5,
      "at": 1764600012000,
      "kind": "intent",
      "text": "Auth tests pass. The change is done."
    }
  ],
  "asks": {
    "next": { "type": "next", "top": 3 },
    "health": { "type": "flags" },
    "done": { "type": "done" }
  }
}

{
  "warnings": [
    { "code": "late_event", "seq": 3 },
    { "code": "seq_gap", "from": 6, "to": 8 }
  ]
}

Long-polling updates

Slower work that finishes after an events call is queued on the session as items. Today those are Capri’s plans and re-plans: capri.plan.* and capri.replan.* items (see Plans and re-plans). GET sessions/{id}/updates/?after=0&wait=25 answers as soon as there is an item after after, or when wait runs out, with at most 50 items, oldest first, each { id, kind, created_at, body }. Pass next_after as after next time. Polling is free; set your client’s timeout above 25 s. Or keep one connection open with stream/, which sends the same items as they land: see Streaming.

afterThe id of the last item you saw. 0, the default, for all of them.
waitSeconds to hold the call open for a new item, 0-25. 0, the default, answers at once.
GET sessions/{id}/updates/?after=0&wait=25, nothing new
{
  "object": "capri.updates",
  "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
  "model": "capri-1-20261028",
  "livemode": false,
  "items": [],
  "next_after": 0
}

Items live only as long as the session’s content. An expired session answers 410.

Feedback

Tell Capri what your harness did with a note or a decision without waiting for the next batch: POST sessions/{id}/feedback/ with up to 50 items. Verdicts carry no seq, so your numbering never moves. Feedback is free, and like events/ it needs Basic and an open session.

note_ack{ kind, note_id, status }, with status delivered, applied, failed, expired or refused.
decision{ kind, decision_id, outcome, reason? }, with outcome applied, vetoed or failed.

The answer lists the ids it applied and the ones it doesn’t know (unknown). A veto counts in the next events call, which decides again without the vetoed option; a second veto at the same point leaves the call to the user (requires_human). The same verdicts can also ride in an events batch as note_ack and decision events.

POST sessions/{id}/feedback/
{
  "items": [
    { "kind": "note_ack", "note_id": "cpn_1", "status": "delivered" },
    {
      "kind": "decision",
      "decision_id": "cpd_1",
      "outcome": "vetoed",
      "reason": "Our CI typechecks later."
    }
  ]
}

{
  "object": "capri.feedback",
  "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
  "model": "capri-1-20261028",
  "livemode": false,
  "applied": ["cpn_1", "cpd_1"],
  "unknown": []
}

Closing

POST sessions/{id}/close/ when the run ends; it needs no body. The session takes no more events or feedback (410 session_closed), while its summary and updates/ still answer. Its content is kept retention_days after closing, then erased; with retention_days: 0 the content, its queued items, its finished plans and re-plans, and its stored replays go at once. The answer is the summary with status: "closed" and expires_at set to when the content goes. Closing twice is fine; an expired session answers 410 session_expired. Closing is free and needs only a key.

A plan or re-plan still running when the session closes can’t land. If Capri had already written it, it ends superseded and is charged at cost; if not, it fails and costs nothing.

Deleting

DELETE sessions/{id}/ erases the session now: its content, its queued items, its finished plans and re-plans, and its stored replays. It answers { "object": "capri.session", "id": "cps_…", "deleted": true }, and the id is a 404 from then on. Usage rows stay, as numbers only. Deleting is free and needs only a key, so a lapsed account can always remove its data.

The summary

GET sessions/{id}/ answers the same capri.session as opening one, with its numbers so far: status (open, closed or expired), next_seq, counts (calls, events, hunches, notes, decisions and credits), green and last_surprise. It never holds the goal, Capri’s memory of the run or any event text. An open session expires 24 hours after its last events or feedback call and its content goes with it; an expired or closed session’s summary still answers for 30 days after its content goes.

Its plan says how the plan started: { "source": "none" }, { "source": "client", "steps": 3 } with your step count, or { "source": "capri", "id": "cpl_…", "status": "ready" } with the Capri plan’s status while the session keeps its content, and only its id once that content is gone ({ "source": "capri", "status": "unavailable" } when no planner could run). The plan itself is at plan/.

Limits

Events per call50 (413 payload_too_large). feedback/ takes up to 50 items too.
Events per minute, per session60, counted per event, not per call (429 rate_limited; wait for Retry-After).
Open sessions per account20 (409 session_limit_reached). Close one to open another.
Fresh hunches per session2, 4 or 6 a minute with intensity quiet, balanced or eager. Past it the hunch is skipped (degraded: capacity), never the call.
updates/Waits up to 25 s, and answers at most 50 items at a time.
stream/ connectionsAbout 4 minutes each, then end reconnect: connect again with Last-Event-ID. A : ping comment after every 15 s of quiet.
Open streams per account25 (429 capacity, Retry-After 30 s).
Idle expiry24 hours without an events or feedback call.
retention_days · metadata0-30 days (7 by default) · 2 KB.

Every session call also counts against the per-key and per-account rate limits predict/ uses.

Streaming

GET sessions/{id}/stream/ sends a session’s updates as Server-Sent Events, over one open connection: the same items updates/ answers, each as it lands. It needs the steer scope and is free. Like updates/, it keeps working while Capri is paused and needs no active Basic. A suspended account can’t open one, and its open streams end at the next check.

curl
# bash or zsh. Keep the key in an environment variable: export CAPRI_API_KEY=nika_cp_test_...
CAPRI=https://www.codename-nika.com/api/capri/v1/
SESSION=cps_...  # the id POST sessions/ answered
LAST=0  # the id of the last update you saw (0 for all)

# Updates as Server-Sent Events, each as it lands (-N prints them as they arrive). The connection ends with an end
# event after about 4 minutes: connect again with Last-Event-ID set to the last update's id.
curl -sS -N ${CAPRI}sessions/$SESSION/stream/ \
  -H "Authorization: Bearer $CAPRI_API_KEY" \
  -H "Accept: text/event-stream" \
  -H "Last-Event-ID: $LAST"
TypeScript
// Server-side only (Node 18+). Keep the trailing slash, and never send the key to a browser.
// Not EventSource: it can't send the key's header. fetch reads the stream instead.
const CAPRI = "https://www.codename-nika.com/api/capri/v1/"
const SESSION = 'cps_...' // the id POST sessions/ answered

/** An updates/ item: capri.plan.* items carry { plan }, capri.replan.* items { replan }. */
type Item = { id: number; kind: string; created_at: string; body: unknown }
type CapriError = { type: string; code: string; message: string }
type SseEvent = { event: string; data: string; retry?: number }

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

/** A text/event-stream body as events: a blank line ends one, and ":" lines (the heartbeat) are skipped. */
async function* sse(body: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent> {
  const reader = body.getReader()
  const decoder = new TextDecoder()
  let buffer = ''
  let event: SseEvent = { event: 'message', data: '' }
  for (;;) {
    const { done, value: chunk } = await reader.read()
    if (done) return
    buffer += decoder.decode(chunk, { stream: true })
    for (let nl = buffer.indexOf('\n'); nl >= 0; nl = buffer.indexOf('\n')) {
      const line = buffer.slice(0, nl).replace(/\r$/, '')
      buffer = buffer.slice(nl + 1)
      if (line === '') {
        if (event.data) yield event
        event = { event: 'message', data: '' }
      } else if (!line.startsWith(':')) {
        const at = line.indexOf(':')
        const field = at < 0 ? line : line.slice(0, at)
        const text = at < 0 ? '' : line.slice(at + 1).replace(/^ /, '')
        if (field === 'event') event.event = text
        else if (field === 'data') event.data += (event.data ? '\n' : '') + text
        else if (field === 'retry') event.retry = Number(text)
      }
    }
  }
}

/**
 * Every item of a session's updates, once each and oldest first, as they land. It connects again with Last-Event-ID
 * until the session has nothing more to send, and stops for good on an error that trying again won't fix.
 */
export async function follow(session: string, onItem: (item: Item) => void, after = 0): Promise<void> {
  let last = after // the id of the last update seen: Last-Event-ID on every connect
  let backoff = 3000 // a dropped connection waits 3 s, then twice as long each time, up to 60 s
  let wait = 0
  for (;;) {
    if (wait > 0) await sleep(wait)
    wait = backoff
    backoff = Math.min(backoff * 2, 60000)
    let res: Response
    try {
      res = await fetch(CAPRI + `sessions/${session}/stream/`, {
        headers: { Authorization: `Bearer ${process.env.CAPRI_API_KEY}`, Accept: 'text/event-stream', 'Last-Event-ID': String(last) },
      })
    } catch {
      continue // the network failed: back off
    }
    if (res.status === 429 || res.status === 503) {
      wait = 1000 * Number(res.headers.get('Retry-After') || 60)
      continue
    }
    if (res.status !== 200 || !res.body) {
      const json = await res.json().catch(() => null)
      // 400, 401, 403, 404 and 410 won't change by trying again: stop for good. Anything else backs off.
      if ([400, 401, 403, 404, 410].includes(res.status)) throw Object.assign(new Error(json?.error?.message ?? `Capri answered ${res.status}`), json?.error)
      continue
    }
    let stop: CapriError | null = null
    try {
      for await (const e of sse(res.body)) {
        if (e.event === 'ready') backoff = 3000
        else if (e.event === 'update') {
          const item: Item = JSON.parse(e.data)
          if (item.id > last) onItem(item) // ids only rise: one at or below the last is a repeat
          last = Math.max(last, item.id)
        } else if (e.event === 'end') {
          const end: { reason: string; next_after: number } = JSON.parse(e.data)
          if (end.reason === 'session_closed') return // nothing more will come
          last = Math.max(last, end.next_after)
          wait = 0 // reason "reconnect": connect again at once
        } else if (e.event === 'error') {
          const error: CapriError = JSON.parse(e.data).error
          // 401, 403, 404 and 410 won't change by trying again. A 503 asks for its retry (60 s); a 500 backs off.
          if (error.type !== 'api_error') stop = error
          else if (e.retry) wait = e.retry
        }
      }
    } catch {
      // The connection dropped: back off, then pick up after the last update.
    }
    if (stop) throw Object.assign(new Error(stop.message), stop)
  }
}

// While your harness sends events/ as usual, hand each item to it as it lands:
follow(SESSION, (item) => console.log(item.kind, item.body)).catch(console.error)
Python
# Python 3.9+ with httpx (pip install httpx). Server-side only; keep the trailing slash.
# Not EventSource: httpx.stream reads the events, and the key stays in a header.
import json, os, time, httpx

CAPRI = "https://www.codename-nika.com/api/capri/v1/"
AUTH = {"Authorization": f"Bearer {os.environ['CAPRI_API_KEY']}"}
SESSION = "cps_..."  # the id POST sessions/ answered


def sse(response):
    """A text/event-stream body as (event, data, retry): a blank line ends one, and ":" lines (the heartbeat) are skipped."""
    event, data, retry = "message", [], None
    for line in response.iter_lines():
        if line == "":
            if data:
                yield event, "\n".join(data), retry
            event, data, retry = "message", [], None
        elif not line.startswith(":"):
            field, _, value = line.partition(":")
            value = value[1:] if value.startswith(" ") else value
            if field == "event":
                event = value
            elif field == "data":
                data.append(value)
            elif field == "retry" and value.isdigit():
                retry = int(value)


def follow(session, on_item, after=0):
    """Every item of a session's updates, once each and oldest first, as they land.

    It connects again with Last-Event-ID until the session has nothing more to send, and stops for good on an error
    that trying again won't fix."""
    last = after  # the id of the last update seen: Last-Event-ID on every connect
    backoff, wait = 3, 0  # a dropped connection waits 3 s, then twice as long each time, up to 60 s
    while True:
        if wait:
            time.sleep(wait)
        wait, backoff = backoff, min(backoff * 2, 60)
        headers = {**AUTH, "Accept": "text/event-stream", "Last-Event-ID": str(last)}
        try:
            with httpx.stream("GET", f"{CAPRI}sessions/{session}/stream/", headers=headers, timeout=30) as r:
                if r.status_code in (429, 503):
                    wait = float(r.headers.get("Retry-After", "60"))
                    continue
                if r.status_code != 200:
                    r.read()
                    if r.status_code in (400, 401, 403, 404, 410):
                        raise RuntimeError(r.json()["error"]["message"])  # trying again won't help: stop for good
                    continue  # anything else backs off
                for name, data, retry in sse(r):
                    if name == "ready":
                        backoff = 3
                    elif name == "update":
                        item = json.loads(data)
                        if item["id"] > last:  # ids only rise: one at or below the last is a repeat
                            on_item(item)
                        last = max(last, item["id"])
                    elif name == "end":
                        end = json.loads(data)
                        if end["reason"] == "session_closed":
                            return  # nothing more will come
                        last, wait = max(last, end["next_after"]), 0  # reason "reconnect": connect again at once
                    elif name == "error":
                        error = json.loads(data)["error"]
                        if error["type"] != "api_error":
                            raise RuntimeError(error["message"])  # 401, 403, 404 and 410 won't change by trying again
                        if retry:
                            wait = retry / 1000  # a 503 asks for its retry (60 s); a 500 backs off
        except httpx.TransportError:
            pass  # the connection dropped: back off, then pick up after the last update


if __name__ == "__main__":
    # While your harness sends events/ as usual, hand each item to it as it lands:
    follow(SESSION, lambda item: print(item["kind"], item["body"]))

Events

readyAlways first, with retry: 3000. Its data is { object: "capri.stream", session, model, livemode, after, ends_at }: where this connection starts, and when it ends at the latest.
updateOne per item. Its id is the item’s id, and its data is the same { id, kind, created_at, body } that updates/ answers.
endThe connection is over. Its data is { object: "capri.stream.end", session, model, livemode, reason, next_after }: reason "reconnect" means connect again from next_after; "session_closed" means nothing more will come.
errorThe usual error object, then the connection closes. A 503’s block also asks for retry: 60000.
: pingA comment, not an event, after every 15 s of quiet. Skip it.
GET sessions/{id}/stream/ with Last-Event-ID: 1 · the re-plan lands (two pings stand for the rest)
retry: 3000
event: ready
data: {"object":"capri.stream","session":"cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P","model":"capri-1-20261028","livemode":true,"after":1,"ends_at":"2026-10-29T12:10:31.000Z"}

: ping

id: 2
event: update
data: {"id":2,"kind":"capri.replan.ready","created_at":"2026-10-29T12:07:15.000Z","body":{"replan":{"object":"capri.replan","id":"cpr_6Tj1Pw9Ec4Ya8Mf3Ku7Ld2Qe","session":"cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P","model":"capri-1-20261028","livemode":true,"kind":"replan","status":"ready","reason":"jolt","based_on_seq":5,"based_on_v":1,"plan_v":2,"diagnosis":"verifyToken now needs opts, and tests/helpers/token.ts still calls it without them, so the billing tests get 401.","ops":[{"op":"add","step":{"title":"Pass opts in the test token helper","kind":"edit","targets":["tests/helpers/token.ts"],"deps":["p1"],"expect":"tests green","confidence":0.8,"id":"p2b"},"after":"p2"}],"rejected":[],"steer":{"text":"Plan update (re-plan 1 of 4): The billing tests get 401 because tests/helpers/token.ts still calls verifyToken without opts. Pass opts there, then run the billing tests again.","trust":"model"},"confidence":0.74,"junction":null,"restart":null,"failure":null,"credits":20.038,"fixture":false,"created_at":"2026-10-29T12:06:40.000Z","finished_at":"2026-10-29T12:07:15.000Z"}}}

: ping

event: end
data: {"object":"capri.stream.end","session":"cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P","model":"capri-1-20261028","livemode":true,"reason":"reconnect","next_after":2}

Resuming

Every update carries its item’s id. To pick up where a connection left off, send the id of the last update you saw as Last-Event-ID (it wins), or as ?after=, read as updates/ reads it. Dedupe on id. Item ids are an opaque, increasing cursor: they mean nothing across sessions, and they aren’t consecutive.

Connections

Closed, expired and deleted sessions

Clients

Browsers’ EventSource can’t send the key header, and keys stay on servers anyway. Use fetch with a body reader (Node 18+), curl -N, or httpx.stream, as the snippets above do. They stop for good on 400, 401, 403, 404 and 410, and on end session_closed. They wait Retry-After on 429 and 503 (60 s after an in-stream error 503), and back off from 3 s, doubling to 60 s, when a connection drops. A client that loops on a 410 only burns its own rate limit.

Webhooks send the same results. A harness that uses both dedupes by kind and object id.

Plans and re-plans

A session can keep a living plan for its run: steps, each with what it works on and the result that shows it is done, kept current by rules as your events arrive. Write the plan yourself, or let Capri write it. When the run goes off course, Capri re-plans: it changes the plan’s steps and writes your agent one short note. Plans live only in session mode; predict/ has none.

curl
# bash or zsh, with jq. Keep the key in an environment variable: export CAPRI_API_KEY=nika_cp_test_...
CAPRI=https://www.codename-nika.com/api/capri/v1/

# 1. Open with a plan Capri writes. It comes after the 201: at most 62 credits, and nothing if it fails.
SESSION=$(curl -sS ${CAPRI}sessions/ \
  -H "Authorization: Bearer $CAPRI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: run-4822-open" \
  --data-binary @- <<'JSON' | jq -r .id
{
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "plan": { "source": "capri" },
  "settings": { "decisions": "auto", "notes": "live", "replans": "manual" },
  "retention_days": 7,
  "metadata": { "run": "run-4822" }
}
JSON
)

# 2. The plan arrives in updates/ as capri.plan.ready. After capri.plan.failed the run goes on without one.
curl -sS "${CAPRI}sessions/$SESSION/updates/?after=0&wait=25" \
  -H "Authorization: Bearer $CAPRI_API_KEY"

# 3. The living plan, with each step's status, any time:
curl -sS ${CAPRI}sessions/$SESSION/plan/ \
  -H "Authorization: Bearer $CAPRI_API_KEY"

# 4. When an events call answers steer.replan with "status": "recommended", start it with the same reason:
#    at most 42 credits. Key it by the step's folded_through (5 here), so a retry gets the same re-plan back.
REPLAN=$(curl -sS ${CAPRI}sessions/$SESSION/replans/ \
  -H "Authorization: Bearer $CAPRI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: run-4822-replan-5" \
  --data-binary @- <<'JSON' | jq -r .id
{ "reason": "jolt" }
JSON
)

# 5. It ends ready, failed or superseded, as a capri.replan.* item in updates/. Read it here any time.
#    Once it's ready, its steer reaches your agent as a later events call's steer.note.
curl -sS ${CAPRI}replans/$REPLAN/ \
  -H "Authorization: Bearer $CAPRI_API_KEY"
TypeScript
// Server-side only (Node 18+). Keep the trailing slash, and never send the key to a browser.
const CAPRI = "https://www.codename-nika.com/api/capri/v1/"

/** One call to Capri. It retries a short 429 or 503, and an Idempotency-Key makes a retried POST safe. */
async function capri<T>(path: string, body?: unknown, idempotencyKey?: string): Promise<T> {
  const headers: Record<string, string> = { Authorization: `Bearer ${process.env.CAPRI_API_KEY}`, 'Content-Type': 'application/json' }
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(CAPRI + path, { method: body === undefined ? 'GET' : 'POST', headers, body: body === undefined ? undefined : JSON.stringify(body) })
    // 429 and 503 ran nothing: a Retry-After of 10 s or less is waited out, 3 tries in all. Capri can ask for an hour
    // or more, so a longer one is thrown at once (with retryAfter): a request to your server never hangs on it.
    const retryAfter = Number(res.headers.get('Retry-After')) || null
    if ((res.status === 429 || res.status === 503) && (retryAfter ?? 2) <= 10 && attempt < 3) {
      await new Promise((r) => setTimeout(r, 1000 * (retryAfter ?? 2)))
      continue
    }
    const text = await res.text() // as text: a proxy's or a gateway's page isn't JSON
    let json: any
    try {
      json = JSON.parse(text)
    } catch {
      throw new Error(`Capri answered ${res.status} without JSON: ${text.slice(0, 200)}`)
    }
    if (!res.ok) throw Object.assign(new Error(json.error?.message ?? `Capri answered ${res.status}`), json.error, { status: res.status, retryAfter })
    return json as T
  }
}

type Session = { id: string; plan: { source: string; id?: string; status?: string } }
type Replan = { id: string; kind: 'replan' | 'extend'; status: 'queued' | 'running' | 'ready' | 'failed' | 'superseded'; failure: string | null }
/** An updates/ item: capri.plan.* items carry { plan }, capri.replan.* items { replan }. */
type Item = { id: number; kind: string; created_at: string; body: { plan?: { id: string; status: string }; replan?: Replan } | null }
/** What a step says about re-plans: one Capri recommends (in "auto", one it started), and the note a landed one becomes. */
type Step = {
  folded_through: number | null
  steer: {
    replan?: { status: 'recommended' | 'queued'; reason: string; id?: string; not_started?: string }
    note?: { text: string; trust: 'facts' | 'model'; replan?: string }
  }
}
type Plan = { v: number; next: string | null; steps: { id: string; title: string; status: string; pinned: boolean }[] }

/** Long-polls updates/ until the plan or re-plan with this id ends: ready, failed or superseded. */
async function waitFor(session: string, id: string, after = 0): Promise<Item> {
  for (;;) {
    const page = await capri<{ items: Item[]; next_after: number }>(`sessions/${session}/updates/?after=${after}&wait=25`)
    const item = page.items.find((i) => i.body?.plan?.id === id || i.body?.replan?.id === id)
    if (item) return item
    after = page.next_after
  }
}

const OPEN = {
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "plan": { "source": "capri" },
  "settings": { "decisions": "auto", "notes": "live", "replans": "manual" },
  "retention_days": 7,
  "metadata": { "run": "run-4822" }
}
const EVENTS = [
  {
    "seq": 1,
    "at": 1764600000000,
    "kind": "intent",
    "text": "Add a clock-skew option to verifyToken in src/auth.ts."
  },
  {
    "seq": 2,
    "at": 1764600004000,
    "kind": "diff",
    "files": [
      {
        "path": "src/auth.ts",
        "add": 12,
        "del": 3,
        "symbols": ["verifyToken"]
      }
    ]
  },
  {
    "seq": 3,
    "at": 1764600005000,
    "kind": "refs",
    "symbol": "verifyToken",
    "files": ["src/middleware.ts", "src/api/session.ts"]
  },
  {
    "seq": 4,
    "at": 1764600009000,
    "kind": "test",
    "runner": "jest",
    "passed": 16,
    "failed": 0,
    "source": "agent"
  },
  {
    "seq": 5,
    "at": 1764600012000,
    "kind": "intent",
    "text": "Auth tests pass. The change is done."
  }
]

export async function plannedRun(runId: string): Promise<void> {
  // 1. Open with a plan Capri writes. It comes after the 201: at most 62 credits, and nothing if it fails.
  //    With no plan id, Capri can't write plans right now (degraded: no-planner) and the run goes on without one.
  const session = await capri<Session>('sessions/', OPEN, `${runId}-open`)
  if (session.plan.id) console.log((await waitFor(session.id, session.plan.id)).kind) // capri.plan.ready, or .failed

  // 2. After each agent message, send its events. In "manual" (the default) Capri recommends a re-plan and your
  //    harness starts it: at most 42 credits, and nothing if it fails. In "auto" Capri starts it: want.id.
  const step = await capri<Step>(`sessions/${session.id}/events/`, { events: EVENTS }, `${runId}-batch-1`)
  const want = step.steer.replan
  if (want) {
    const key = `${runId}-replan-${step.folded_through}` // the step's own: a retry gets the same re-plan back
    const id = want.id || (await capri<Replan>(`sessions/${session.id}/replans/`, { reason: want.reason }, key)).id
    console.log((await waitFor(session.id, id)).kind) // capri.replan.ready, .failed or .superseded
  }

  // 3. A landed re-plan reaches your agent as a later step's steer.note (trust "model"): hand it over as-is.
  //    The living plan, with each step's status, is there any time.
  const plan = await capri<Plan>(`sessions/${session.id}/plan/`)
  for (const s of plan.steps) console.log(s.id, s.status, s.title)
}

plannedRun("run-4822").catch(console.error)
Python
# Python 3.9+ with httpx (pip install httpx). Server-side only; keep the trailing slash.
import json, os, time, httpx

CAPRI = "https://www.codename-nika.com/api/capri/v1/"
AUTH = {"Authorization": f"Bearer {os.environ['CAPRI_API_KEY']}"}


def capri(method, path, body=None, idempotency_key=None):
    """One call to Capri. Retries a short 429 or 503; an Idempotency-Key makes a retried POST safe."""
    headers = {**AUTH, "Idempotency-Key": idempotency_key} if idempotency_key else AUTH
    for attempt in range(1, 4):
        r = httpx.request(method, CAPRI + path, headers=headers, json=body, timeout=35)
        # 429 and 503 ran nothing: a Retry-After of 10 s or less is waited out, 3 tries in all. Capri can ask for an
        # hour or more, so a longer one is raised at once (with retry_after): a request to your server never hangs on it.
        header = r.headers.get("Retry-After", "")
        retry_after = int(header) if header.isdigit() else None
        if r.status_code in (429, 503) and (retry_after or 2) <= 10 and attempt < 3:
            time.sleep(retry_after or 2)
            continue
        try:
            data = json.loads(r.text)  # as text: a proxy's or a gateway's page isn't JSON
        except ValueError:
            raise RuntimeError(f"Capri answered {r.status_code} without JSON: {r.text[:200]}") from None
        if r.is_error:
            error = RuntimeError(data["error"]["message"])
            error.status, error.retry_after = r.status_code, retry_after
            raise error
        return data


def wait_for(sid, object_id, after=0):
    """Long-polls updates/ until the plan or re-plan with this id ends: ready, failed or superseded."""
    while True:
        page = capri("GET", f"sessions/{sid}/updates/?after={after}&wait=25")
        for item in page["items"]:
            body = item["body"] or {}
            if object_id in (body.get("plan", {}).get("id"), body.get("replan", {}).get("id")):
                return item
        after = page["next_after"]


OPEN = {
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "plan": { "source": "capri" },
  "settings": { "decisions": "auto", "notes": "live", "replans": "manual" },
  "retention_days": 7,
  "metadata": { "run": "run-4822" }
}
EVENTS = [
  {
    "seq": 1,
    "at": 1764600000000,
    "kind": "intent",
    "text": "Add a clock-skew option to verifyToken in src/auth.ts."
  },
  {
    "seq": 2,
    "at": 1764600004000,
    "kind": "diff",
    "files": [
      {
        "path": "src/auth.ts",
        "add": 12,
        "del": 3,
        "symbols": ["verifyToken"]
      }
    ]
  },
  {
    "seq": 3,
    "at": 1764600005000,
    "kind": "refs",
    "symbol": "verifyToken",
    "files": ["src/middleware.ts", "src/api/session.ts"]
  },
  {
    "seq": 4,
    "at": 1764600009000,
    "kind": "test",
    "runner": "jest",
    "passed": 16,
    "failed": 0,
    "source": "agent"
  },
  {
    "seq": 5,
    "at": 1764600012000,
    "kind": "intent",
    "text": "Auth tests pass. The change is done."
  }
]

# 1. Open with a plan Capri writes. It comes after the 201: at most 62 credits, and nothing if it fails.
#    With no plan id, Capri can't write plans right now (degraded: no-planner) and the run goes on without one.
session = capri("POST", "sessions/", OPEN, "run-4822-open")
sid = session["id"]
if session["plan"].get("id"):
    print(wait_for(sid, session["plan"]["id"])["kind"])  # capri.plan.ready, or .failed

# 2. After each agent message, send its events. In "manual" (the default) Capri recommends a re-plan and your
#    harness starts it: at most 42 credits, and nothing if it fails. In "auto" Capri starts it: want["id"].
step = capri("POST", f"sessions/{sid}/events/", {"events": EVENTS}, "run-4822-batch-1")
want = step["steer"].get("replan")
if want:
    key = f"run-4822-replan-{step['folded_through']}"  # the step's own: a retry gets the same re-plan back
    replan_id = want.get("id") or capri("POST", f"sessions/{sid}/replans/", {"reason": want["reason"]}, key)["id"]
    print(wait_for(sid, replan_id)["kind"])  # capri.replan.ready, .failed or .superseded

# 3. A landed re-plan reaches your agent as a later step's steer.note (trust "model"): hand it over as-is.
#    The living plan, with each step's status, is there any time.
for s in capri("GET", f"sessions/{sid}/plan/")["steps"]:
    print(s["id"], s["status"], s["title"])

A plan Capri writes

Open the session with plan: { "source": "capri" }. Capri writes the plan after the 201, from what the session opened with: the goal, done_means, rules, preferences and repo facts. The 201 says the plan is queued, and the plan arrives in updates/ as a capri.plan.ready item whose body is { plan }. Its steps move with the events you send after it lands.

POST sessions/ → 201 (excerpt)
{
  "model": "capri-1",
  "goal": "Add clock-skew tolerance to verifyToken",
  "done_means": ["auth tests green", "tsc 0 errors"],
  "repo": { "languages": ["typescript"], "check_kinds": ["typecheck", "test"] },
  "plan": { "source": "capri" },
  "settings": { "decisions": "auto", "notes": "live", "replans": "manual" },
  "retention_days": 7,
  "metadata": { "run": "run-4822" }
}

{
  "object": "capri.session",
  "id": "cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P",
  "model": "capri-1-20261028",
  "livemode": true,
  "status": "open",
  "plan": {
    "source": "capri",
    "id": "cpl_2Vd8Kq5mWz1Nc7Xt4Bg9Hr3S",
    "status": "queued"
  },
  "settings": {
    "decisions": "recommend",
    "notes": "live",
    "intensity": "balanced",
    "replans": "manual",
    "policy": null
  },
  "warnings": [{ "code": "decisions_downgraded", "reason": "auto_not_available" }]
}
GET sessions/{id}/updates/?after=0&wait=25 · the plan landed
{
  "object": "capri.updates",
  "session": "cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P",
  "model": "capri-1-20261028",
  "livemode": true,
  "items": [
    {
      "id": 1,
      "kind": "capri.plan.ready",
      "created_at": "2026-10-29T12:01:12.000Z",
      "body": {
        "plan": {
          "object": "capri.plan",
          "id": "cpl_2Vd8Kq5mWz1Nc7Xt4Bg9Hr3S",
          "session": "cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P",
          "model": "capri-1-20261028",
          "livemode": true,
          "source": "capri",
          "status": "ready",
          "failure": null,
          "v": 1,
          "criteria": ["auth tests green", "tsc 0 errors"],
          "steps": [
            {
              "id": "p1",
              "title": "Add opts.clockSkew to verifyToken",
              "kind": "edit",
              "targets": ["src/auth.ts"],
              "deps": [],
              "status": "todo",
              "confidence": 0.8,
              "pinned": false,
              "expect": "tsc 0 errors",
              "source": "plan"
            },
            {
              "id": "p2",
              "title": "Update the callers of verifyToken",
              "kind": "edit",
              "targets": [
                "src/middleware.ts",
                "src/api/session.ts"
              ],
              "deps": ["p1"],
              "status": "todo",
              "confidence": 0.7,
              "pinned": false,
              "expect": "tsc 0 errors",
              "source": "plan"
            },
            {
              "id": "p3",
              "title": "Run the auth tests",
              "kind": "test",
              "targets": ["npm test -- auth"],
              "deps": ["p2"],
              "status": "todo",
              "confidence": 0.75,
              "pinned": false,
              "expect": "auth tests green",
              "source": "plan"
            },
            {
              "id": "p4",
              "title": "Document the clockSkew option",
              "kind": "doc",
              "targets": ["docs/auth.md"],
              "deps": ["p1"],
              "status": "todo",
              "confidence": 0.6,
              "pinned": false,
              "expect": null,
              "source": "plan"
            }
          ],
          "next": "p1",
          "lookahead": ["p2", "p3", "p4"],
          "progress": {
            "done": [],
            "now": {
              "id": "p1",
              "title": "Add opts.clockSkew to verifyToken",
              "status": "todo"
            },
            "next": [
              {
                "id": "p2",
                "title": "Update the callers of verifyToken"
              },
              {
                "id": "p3",
                "title": "Run the auth tests"
              },
              {
                "id": "p4",
                "title": "Document the clockSkew option"
              }
            ]
          },
          "risks": [
            {
              "kind": "types",
              "text": "Callers still pass the old arguments",
              "p": 0.6,
              "impact": 2,
              "check": "typecheck"
            }
          ],
          "hypotheses": [],
          "junctions": [
            {
              "at": "p1",
              "options": [
                {
                  "key": "a",
                  "title": "An opts object",
                  "why": "Room for more options later",
                  "risk": "Every caller changes"
                },
                {
                  "key": "b",
                  "title": "A third argument",
                  "why": "A smaller change",
                  "risk": "Harder to extend later"
                }
              ],
              "irreversible": false
            }
          ],
          "credits": 37.37,
          "fixture": false
        }
      }
    }
  ],
  "next_after": 1
}

Your own plan

Or send your own steps: plan: { "source": "client", "steps": [...] } with 1-25 of them. It costs nothing and is in place when the 201 answers. Every step of your plan is pinned (source: "user"): a re-plan may add steps around it or park it, but never drops or rewrites it. A change that tries is listed in the re-plan’s rejected, with reason pinned. A step that would do something outward (push, deploy, publish, send, buy) starts blocked: only the user does those.

Step fieldMeaning
titleRequired: what the step does, 1-300 characters (shortened past 120). A step can be its title alone, as a string.
idOptional: 1-40 letters, digits, _ . or -, unique in the plan. By default p1, p2, … by position.
doneOptional: true when the step is already done.
kindOptional: one of read, search, edit, run, test, typecheck, build, migrate, config, doc, verify, ask (edit by default).
targetsOptional: up to 6 files or commands the step works on, 1-300 characters each (shortened past 160). With none, the paths in its title and the commands in backticks are its targets.
depsOptional: up to 6 ids of earlier steps it waits for.
expectOptional: the result that shows it is done, up to 160 characters, like "tsc 0 errors" or "auth tests green".

A plan that can’t be used is 400 bad_plan, with param naming the part (for example plan.steps.2.deps).

POST sessions/ · your own plan
{
  "plan": {
    "source": "client",
    "steps": [
      "Add opts.clockSkew to verifyToken in src/auth.ts",
      {
        "id": "callers",
        "title": "Pass opts from both callers",
        "targets": ["src/middleware.ts", "src/api/session.ts"],
        "deps": ["p1"],
        "expect": "tsc 0 errors"
      },
      {
        "title": "Run the auth tests",
        "kind": "test",
        "targets": ["npm test -- auth"],
        "deps": ["callers"],
        "expect": "auth tests green"
      }
    ]
  }
}

Reading the plan

GET sessions/{id}/plan/ answers capri.plan, the same object a capri.plan.ready item carries, as it is now. It’s free, and it answers while the session keeps its content, closed or not (410 once the content is gone).

FieldMeaning
id · sourceThe Capri plan’s cpl_ id (null when there is none), and how the plan started: capri, client or none.
status · failureA Capri plan’s status is its work’s: queued, running, ready, failed (failure says why) or superseded; unavailable when no planner could run. Your own plan is ready, and with no plan, none.
vThe plan’s version: 0 with no plan, and 1 more each time it’s seeded or a re-plan changes it.
stepsEvery step: { id, title, kind, targets, deps, status, confidence, pinned, expect, source }. source is plan (Capri wrote it), replan (a re-plan added it) or user (yours).
next · lookaheadThe first open step whose deps are all closed, and the ids of up to 3 open steps after it.
progressThe plan at a glance: done ({ id, title } each), now (the step in progress, else next, with its status) and next (up to 3 after it).
criteria · risks · hypothesesWhat done means to the plan; what may break, as { kind, text, p, impact, check? }, with the check that would show it; and for a fix, hypotheses { text, p, test, status }: what may be wrong, and the test that would show it.
junctionsHard-to-undo choices Capri saw while planning: { at, options, irreversible }, with options a and b. They’re yours to make.
credits · fixtureWhat writing the plan cost (each re-plan shows its own), and true for a test key’s plan, built by rules.

A step is open while it’s proposed, todo or doing, closed once it’s done, skipped or dropped, and parked while it’s blocked. Rules move steps as events arrive: an edit, diff or command whose file or command a step targets starts it (doing). It’s done when a check of the kind its expect names passes after it started: “tsc 0 errors” is a typecheck, “auth tests green” a test. A step whose expect no check shows is done when the agent’s todos or its own words say so, or when a later step starts. Reads and searches never start a step.

With a plan, the lookahead ask answers its next steps, and flags says which step the agent is on (plan_step).

GET sessions/{id}/plan/ · later in the run, after one re-plan (excerpt)
{
  "object": "capri.plan",
  "id": "cpl_2Vd8Kq5mWz1Nc7Xt4Bg9Hr3S",
  "status": "ready",
  "v": 2,
  "next": "p2",
  "lookahead": ["p2b", "p3", "p4"],
  "progress": {
    "done": [{ "id": "p1", "title": "Add opts.clockSkew to verifyToken" }],
    "now": {
      "id": "p2",
      "title": "Update the callers of verifyToken",
      "status": "doing"
    },
    "next": [
      { "id": "p2b", "title": "Pass opts in the test token helper" },
      { "id": "p3", "title": "Run the auth tests" },
      { "id": "p4", "title": "Document the clockSkew option" }
    ]
  }
}

Re-plans

A re-plan reads the run and the plan, then makes the fewest changes that fit what happened: it adds, drops, parks (block), modifies or reorders steps, and may write one short message for your agent. When the plan runs low on open steps, Capri asks for an extend instead (reason lookahead_low): a shorter re-plan that adds the next steps. Re-plans work with or without a plan; with none, the steps a re-plan adds start one.

When Capri thinks a re-plan is due, the events call’s steer.replan says so:

settings.replans, fixed when the session opens, says who starts them:

ReasonWhen
joltSomething surprising happened, like a check turning red after the work was green.
stuckThe agent is looping: the same error or the same move, again and again.
doomThis milestone looks likely to fail as it stands.
user_changeThe user changed what they want. Say what in note.
lookahead_lowThe plan is running out of open steps. This asks for an extend, which adds the next ones.
gapsThe plan misses something: a check, a test or a done criterion that no step covers.

Capri recommends jolt, stuck, doom and lookahead_low itself; user_change and gaps are yours to ask for.

Starting a re-plan

POST sessions/{id}/replans/ with { reason, note? }. If Capri recommended a re-plan for this reason, that one starts; otherwise the re-plan is your own. note says what changed, in up to 600 characters, and goes only with user_change; it’s scrubbed like event text. It answers 202 with a capri.replan, queued. With a live key, 42 credits are held (21 for an extend), and when it lands you pay what it used. Key the request by the step that asked for it, so a retry gets the same re-plan back.

POST sessions/{id}/replans/ → 202
{ "reason": "jolt" }

{
  "object": "capri.replan",
  "id": "cpr_6Tj1Pw9Ec4Ya8Mf3Ku7Ld2Qe",
  "session": "cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P",
  "model": "capri-1-20261028",
  "livemode": true,
  "kind": "replan",
  "status": "queued",
  "reason": "jolt",
  "based_on_seq": 5,
  "based_on_v": 1,
  "plan_v": null,
  "diagnosis": null,
  "ops": [],
  "rejected": [],
  "steer": null,
  "confidence": null,
  "junction": null,
  "restart": null,
  "failure": null,
  "credits": 0,
  "fixture": false,
  "created_at": "2026-10-29T12:06:40.000Z",
  "finished_at": null
}
POST sessions/{id}/replans/ · the user changed course
{
  "reason": "user_change",
  "note": "Keep verifyToken's signature. Add verifyTokenWithSkew beside it instead."
}

Reading a re-plan

A re-plan goes queued, running, then ready, failed or superseded. Its end arrives in updates/ as capri.replan.ready, capri.replan.failed or capri.replan.superseded, with { replan } as the body, and GET replans/{id}/ answers the same capri.replan any time while its session keeps its content: 404 once the session is deleted, 410 once its content is gone.

Superseded means it ran but couldn’t land: by then the plan had changed, what set it off had cleared (the failing check passed again), you vetoed the decision behind it, the session closed, or nothing it wrote fit the session’s memory. The plan stays as it was. It ran, so it’s charged at cost. When only part of it fits, the first changes land with its steer, and the rest are in rejected with reason no_room.

FieldMeaning
id · session · kindThe re-plan’s cpr_ id, its session, and replan or extend.
status · reason · failurequeued, running, ready, failed or superseded; why it ran; and why it failed, else null.
based_on_seq · based_on_vThe last event seq Capri had taken in when you asked (null before any), and the plan version it started from.
plan_vThe plan’s version once it landed, else null.
diagnosis · confidenceWhat Capri thinks happened, in up to 300 characters, and how sure it is (0-1).
opsThe changes that applied, in order: add (a step, after one), drop, block (park), modify or reorder.
rejectedThe changes that didn’t, as { op, reason }, with reason invalid, unknown_id, duplicate_id, pinned, closed, cycle, too_many_open, outward or no_room (the session’s memory had no room for it).
steer{ text, trust: "model" }: the message for your agent, filtered, as it will read it. Null when there is none, or when the session’s memory had no room for it.
junction · restartA hard-to-undo choice with two options ({ title, options, irreversible }), or advice to start this attempt over ({ why, keep }). Null when there is none. Both are yours to act on.
credits · fixtureWhat it cost, and true for a test key’s, built by rules.
created_at · finished_atWhen it was asked for, and when it ended.
GET replans/{id}/ · ready
{
  "object": "capri.replan",
  "id": "cpr_6Tj1Pw9Ec4Ya8Mf3Ku7Ld2Qe",
  "session": "cps_9Fk3wQ6nTb2Lx8Rd4Hs1Jv7P",
  "model": "capri-1-20261028",
  "livemode": true,
  "kind": "replan",
  "status": "ready",
  "reason": "jolt",
  "based_on_seq": 5,
  "based_on_v": 1,
  "plan_v": 2,
  "diagnosis": "verifyToken now needs opts, and tests/helpers/token.ts still calls it without them, so the billing tests get 401.",
  "ops": [
    {
      "op": "add",
      "step": {
        "title": "Pass opts in the test token helper",
        "kind": "edit",
        "targets": ["tests/helpers/token.ts"],
        "deps": ["p1"],
        "expect": "tests green",
        "confidence": 0.8,
        "id": "p2b"
      },
      "after": "p2"
    }
  ],
  "rejected": [],
  "steer": {
    "text": "Plan update (re-plan 1 of 4): The billing tests get 401 because tests/helpers/token.ts still calls verifyToken without opts. Pass opts there, then run the billing tests again.",
    "trust": "model"
  },
  "confidence": 0.74,
  "junction": null,
  "restart": null,
  "failure": null,
  "credits": 20.038,
  "fixture": false,
  "created_at": "2026-10-29T12:06:40.000Z",
  "finished_at": "2026-10-29T12:07:15.000Z"
}

The note your agent gets

A landed re-plan’s steer reaches your agent through a later events call, as steer.note with trust: "model" and replan, the re-plan’s id. Notes Capri makes by rules say trust: "facts". It reads “[Capri note 2] Plan update (re-plan 1 of 4): …”, or “Plan update: …” for an extend. Hand it over as-is, and report it with note_ack like any note.

POST sessions/{id}/events/, the next call · steer (excerpt)
{
  "steer": {
    "note": {
      "id": "cpn_2",
      "text": "[Capri note 2] Plan update (re-plan 1 of 4): The billing tests get 401 because tests/helpers/token.ts still calls verifyToken without opts. Pass opts there, then run the billing tests again.",
      "trust": "model",
      "delivery": "live",
      "deliver": "now",
      "premises": [
        {
          "kind": "check_failing",
          "check": "test",
          "since": 5
        }
      ],
      "expires": { "steps": 3, "seconds": 180 },
      "replan": "cpr_6Tj1Pw9Ec4Ya8Mf3Ku7Ld2Qe"
    }
  }
}

Limits

Re-plans per sessionsettings.policy’s max.replans_per_milestone: 4 by default, and a policy can only lower it (409 replan_limit_reached). Each re-plan counts once. Extends don’t count.
SpacingOne re-plan every 8 steps, and, counted apart, one extend every 8 steps (409 replan_too_soon). A step is one of the agent’s actions: a tool call, an edit or a command. The one Capri recommends skips this: Capri kept the spacing already. The 8 steps count from the last re-plan (or extend) Capri ran or recommended, so one you ask for yourself soon after a recommendation you passed on waits too.
One at a timeOne re-plan or extend runs per session (409 replan_in_progress, Retry-After 30 s), and none while Capri is still writing the session’s plan (409 plan_pending).
Per session, per hour10 re-plans and extends (429 rate_limited, Retry-After 600 s).
Per account, live keys2 plans or re-plans running at once (429 capacity, Retry-After 30 s), and 500 started in the last 24 hours (429 rate_limited, Retry-After 3600 s). A count of the day’s starts that deleting sessions doesn’t lower also refuses once it reaches 500, until 00:00 UTC, with Retry-After the seconds until then. Only a plan or re-plan that starts counts: a refused one never does.
CreditsRoom in your allowance for the ceiling: 62 for a plan, 42 for a re-plan, 21 for an extend (402 allowance_exhausted). On a key with a monthly cap, room under the cap too (402 key_cap_reached), and a cap no smaller than the ceiling (402 key_cap_too_low).

A refused request holds and charges nothing.

Failures

A plan or re-plan that fails gives its hold back and costs nothing. failure says why:

capacityCapri was too busy to take it. Try again later.
truncatedThe answer ran out of room before it was complete.
declinedCapri declined to answer.
no_answer · invalid_outputNo answer came back, or the answer couldn’t be read.
unavailable · errorCapri couldn’t write plans at that moment, or something else went wrong.
session_closedThe session closed, expired or was deleted before the work started.
pausedCapri was paused before the work started. Ask again once it’s back.
timed_outIt didn’t finish within 10 minutes.

Test keys

Test keys never call a model. Their plans, re-plans and extends are built by rules from the goal, done_means and repo facts, and go through the same flow: queued, then ready in updates/, marked fixture: true, for 0 credits. The session’s limits apply; the per-account ones don’t. Build and test your harness with them.

Webhooks

Capri can post events to your server as they happen, so your harness doesn’t have to long-poll for them: plans and re-plans as they finish, a session that expired, a change to your access, and credits running low. Add an endpoint in the console: an https URL, the events it takes (all of them unless you pick), and whether it gets your live keys’ events or your test keys’. Its signing secret, whsec_…, is shown once. The first try goes out at once, and a retry can come later than its time, so a harness that must not miss an event can also poll updates/ now and then. Session results also come by stream/ (see Streaming).

Event types

Every event is a JSON object, { id, type, created, livemode, data }: id is the event’s evt_… id, created is in unix seconds, and livemode says which kind of key it came from.

TypeWhendata
capri.plan.readyA plan Capri wrote has landed in the session.{ plan }: the capri.plan its updates/ item carries.
capri.plan.failedA plan Capri was writing failed, and charged nothing.{ plan }, with its failure.
capri.plan.supersededA plan ran but couldn’t land: the session closed, or had no room for it.{ plan }
capri.replan.readyA re-plan landed. Its steer reaches your agent as a later step’s note.{ replan }: the capri.replan its updates/ item carries.
capri.replan.failedA re-plan failed, and charged nothing.{ replan }, with its failure.
capri.replan.supersededA re-plan ran but no longer applied, or couldn’t land.{ replan }
capri.session.expiredAn open session went 24 hours without events, and its content was erased.{ session }: its summary, numbers only.
capri.access.changedYour Basic changed: paid, renewed, past due, canceled, paused or resumed, complimentary access started or was ended early, or Nika lifted a new subscription’s 72-hour limit early. A complimentary access reaching its end date, or the 72 hours running out, sends nothing: read GET usage/ when it matters.{ status, source, paid_through, suspended, ramp }: Basic as it now reads. source is "subscription" or "complimentary"; ramp is the 72-hour limit while it runs, { until, limit }, else null.
capri.allowance.lowYour credits reached 80%, and again 100%, of what the period includes: once each per period. A new subscription’s 72-hour limit gets its own two, at 80% and 100% of that limit, and the month’s still come once it ends. 100% means less than a rules-only call (0.04 credits) is left.{ period_id, used, included, percent, resets_at }: percent is the threshold, 80 or 100. For the 72-hour limit’s, included is that limit, resets_at is when the rest opens and reason is "ramp". Complimentary credits don’t reset: their resets_at is null.
capri.pingSend test, in the console. It goes only to the endpoint you test.{ endpoint }

With overage on for your account, capri.allowance.low also comes at 80% and 100% of your overage limit: reason is "overage", included is that limit, and period_id is the Basic period it belongs to. Each comes once a period, as the allowance’s do: a limit raised after one came brings Nika’s email again, never the event.

Live endpoints get your live keys’ events and your account’s (capri.access.changed and capri.allowance.low); test endpoints get your test keys’, fixtures included. A plan or re-plan event goes only while its session keeps its content: delete a session, or close it with retention 0, and what was still waiting to be sent for it is dropped.

capri.plan.ready (shortened)
{
  "id": "evt_3fK8pQ2mT7xLw1Zs8Dn4Vb6C",
  "type": "capri.plan.ready",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "plan": {
      "object": "capri.plan",
      "id": "cpl_Hs4kW9pZ2mQ7xT1nV6cB8rL3",
      "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
      "status": "ready",
      "v": 1,
      "next": "p1",
      "lookahead": ["p2", "p3", "p4"],
      "credits": 37.37
    }
  }
}
capri.plan.failed (shortened)
{
  "id": "evt_9gH2kL5nP8rS1tV4wY7zB0cD",
  "type": "capri.plan.failed",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "plan": {
      "object": "capri.plan",
      "id": "cpl_Hs4kW9pZ2mQ7xT1nV6cB8rL3",
      "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
      "status": "failed",
      "failure": "invalid_output",
      "credits": 0
    }
  }
}
capri.plan.superseded (shortened)
{
  "id": "evt_2bN6mQ9sU3wX5zA8cE1gI4kM",
  "type": "capri.plan.superseded",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "plan": {
      "object": "capri.plan",
      "id": "cpl_Hs4kW9pZ2mQ7xT1nV6cB8rL3",
      "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
      "status": "superseded",
      "failure": null,
      "credits": 37.37
    }
  }
}
capri.replan.ready (shortened)
{
  "id": "evt_6dF0hJ3lN6pR9tV2xZ5bD8fH",
  "type": "capri.replan.ready",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "replan": {
      "object": "capri.replan",
      "id": "cpr_Jd2fG8hK4mN7pQ1sT5vX9yB3",
      "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
      "kind": "replan",
      "status": "ready",
      "reason": "jolt",
      "plan_v": 2,
      "steer": {
        "text": "Plan update (re-plan 1 of 4): getSession() passes no opts. Pass opts in src/api/session.ts.",
        "trust": "model"
      },
      "credits": 20.038
    }
  }
}
capri.replan.failed (shortened)
{
  "id": "evt_4kM7oQ0sU3wY6aC9eG2iK5mO",
  "type": "capri.replan.failed",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "replan": {
      "object": "capri.replan",
      "id": "cpr_Jd2fG8hK4mN7pQ1sT5vX9yB3",
      "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
      "kind": "replan",
      "status": "failed",
      "reason": "jolt",
      "failure": "timed_out",
      "credits": 0
    }
  }
}
capri.replan.superseded (shortened)
{
  "id": "evt_8pR1tV4xZ7bD0fH3jL6nP9rT",
  "type": "capri.replan.superseded",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "replan": {
      "object": "capri.replan",
      "id": "cpr_Jd2fG8hK4mN7pQ1sT5vX9yB3",
      "session": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
      "kind": "replan",
      "status": "superseded",
      "reason": "jolt",
      "plan_v": null,
      "steer": null,
      "credits": 20.038
    }
  }
}
capri.session.expired (shortened)
{
  "id": "evt_1sU4wY7aC0eG3iK6mO9qS2uW",
  "type": "capri.session.expired",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "session": {
      "object": "capri.session",
      "id": "cps_7Qm2xR4tKp9Lw1Zs8Dn3Vb6C",
      "status": "expired",
      "next_seq": 24,
      "counts": { "calls": 5, "events": 23, "credits": 0.43 },
      "expires_at": "2026-10-29T11:58:02.000Z"
    }
  }
}
capri.access.changed (shortened)
{
  "id": "evt_5vX8zB1dF4hJ7lN0pR3tV6xZ",
  "type": "capri.access.changed",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "status": "past_due",
    "source": "subscription",
    "paid_through": "2026-11-28T12:00:00.000Z",
    "suspended": false,
    "ramp": null
  }
}
capri.allowance.low (shortened)
{
  "id": "evt_0cE3gI6kM9oQ2sU5wY8aC1eG",
  "type": "capri.allowance.low",
  "created": 1793275200,
  "livemode": true,
  "data": {
    "period_id": "bp_5f2a9c0d1e7b4a6c8d3e9f01",
    "used": 3204.5,
    "included": 4000,
    "percent": 80,
    "resets_at": "2026-11-28T12:00:00.000Z"
  }
}
capri.ping (shortened)
{
  "id": "evt_7hJ0lN3pR6tV9xZ2bD5fH8jL",
  "type": "capri.ping",
  "created": 1793275200,
  "livemode": false,
  "data": { "endpoint": "cpw_Ky3mP6rT9wZ2cF5hL8nQ1sV4" }
}

Verifying signatures

Each delivery is a POST with the event as its JSON body and these headers: Content-Type: application/json, User-Agent: Nika-Webhooks/1.0, Nika-Event-Id (the event’s id), Nika-Event-Type, and Nika-Signature: t=<unix seconds>,v1=<hex>. v1 is the HMAC-SHA256 of t, a dot and the raw body, byte for byte, keyed with your whole signing secret (whsec_ included).

  1. Read the raw body before any JSON parsing: a parsed and re-serialised body won’t match.
  2. Compute the HMAC over <t>.<raw body> and compare it with v1 in constant time.
  3. Refuse a t more than 300 s old. Refuse one more than 300 s ahead too.
  4. Keep each Nika-Event-Id you’ve handled, and skip one you’ve seen: the same event can arrive more than once.
Node
import crypto from 'node:crypto'

// rawBody: the request body exactly as it arrived (a string or a Buffer), before any JSON parsing.
// header: the Nika-Signature header. secret: your endpoint's whole signing secret, whsec_ included.
export function verifyCapriWebhook(rawBody, header, secret, toleranceS = 300) {
  const parts = Object.fromEntries(String(header || '').split(',').map((p) => p.split('=')))
  const t = Number(parts.t)
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > toleranceS) return false
  const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex')
  const given = Buffer.from(String(parts.v1 || ''))
  return given.length === expected.length && crypto.timingSafeEqual(given, Buffer.from(expected))
}
Python
import hashlib
import hmac
import time


def verify_capri_webhook(raw_body: bytes, header: str, secret: str, tolerance_s: int = 300) -> bool:
    # raw_body: the request body exactly as it arrived, before any JSON parsing.
    # header: the Nika-Signature header. secret: your endpoint's whole signing secret, whsec_ included.
    parts = dict(p.split("=", 1) for p in (header or "").split(",") if "=" in p)
    try:
        t = int(parts.get("t", ""))
    except ValueError:
        return False
    if abs(time.time() - t) > tolerance_s:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), parts.get("v1", "").encode())

Delivery and retries

Delivery is at least once, in no particular order: an event can come twice, and a later one can come first. Skip repeats by Nika-Event-Id, and order by created when it matters. Answer with any 2xx within 10 s. Anything else is a failure. A redirect is a failure too: deliveries never follow one. Only the status counts, and at most 64 KB of your answer is read.

The first try is at once. After a failure it’s tried again no sooner than 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours later: 6 tries in all, then it’s marked failed. Retries go out when Capri next handles a request, so when Capri is quiet one can come later than that. An endpoint whose deliveries fail 50 times in a row is disabled: nothing more is sent to it until you enable it again in the console. Any delivery that succeeds resets the count.

The console lists each endpoint’s last 20 deliveries, for 30 days: the event type, how many tries, and what went wrong (the status your server answered, timeout, dns, private_address, redirect, tls or network), never what was sent.

Endpoints

Usage

GET usage/?days=30 answers calls and credits per UTC day, for the key you call with and for its whole account, in that key’s mode: a live key sees live calls, a test key test calls. days is 1-90 (30 by default) and counts today. Every metered call is in it: predict/, session events/, plans, re-plans and extends, and the console’s playground. Opening, polling, streaming, feedback, closing and deleting are free, so they aren’t, and neither is a plan or re-plan that failed. Narration adds nothing to a step’s credits. models/ and openapi/ need no key, so they never show here. daily lists only the days with calls, newest first, and usage rows are kept 90 days.

GET usage/
{
  "object": "capri.usage",
  "model": "capri-1-20261028",
  "livemode": true,
  "metered_as": "allowance",
  "allowance": {
    "included": 4000,
    "used": 1200.5,
    "remaining": 2799.5,
    "resets_at": "2026-11-28T00:00:00.000Z",
    "ramp": null
  },
  "days": 30,
  "since": "2026-09-30T00:00:00.000Z",
  "key": {
    "id": "cpk_3f9c0a6d2b8e4f1a7c5d9e0b",
    "calls": 2,
    "credits": 0.43,
    "daily": [{ "date": "2026-10-29", "calls": 2, "credits": 0.43 }]
  },
  "account": {
    "calls": 4,
    "credits": 0.51,
    "daily": [
      { "date": "2026-10-29", "calls": 2, "credits": 0.43 },
      { "date": "2026-10-28", "calls": 2, "credits": 0.08 }
    ]
  }
}

Nika emails your account’s address when your credits reach 80%, and again at 100%, of what the period includes: once each per period, and once each for a new subscription’s 72-hour limit. Your live webhooks get capri.allowance.low at the same moments (see Webhooks).

allowance is Basic’s month: included, used and remaining credits, and when they reset (zeros without an active plan). Complimentary credits don’t reset: their resets_at is when the complimentary access ends. ramp is a new subscription’s 72-hour limit while it lasts, { until, limit }, else null: in its first 72 hours a first paid month can use up to 1,000 credits, and remaining counts that. metered_as is "allowance" for live keys and "test" for test keys.

With overage on, a step’s usage adds overage: the Nika credits it took after your included ones (absent otherwise). GET usage/ adds overage: { on, limit, used, remaining, resets_at } for this period.

Idempotency-Key

Every POST takes an Idempotency-Key header of 1-255 printable characters: predict/, sessions/, events/, feedback/, close/ and replans/. The first request with a key runs, and its answer is kept 24 hours. The same key with the same request gets that answer back, marked Idempotent-Replayed: true: it doesn’t run again, and a replay is never charged, nor does it queue a second plan or re-plan. Build keys from something stable, like your run id and batch number, so a retry after a timeout reuses them.

Errors

Errors use one shape: {"error": {"type", "code", "message", "param"?}}.

400invalid_request, invalid_state: the body or the state token is wrong.
401invalid_api_key: a key that is missing, unknown, revoked or past its expiry, all alike.
402subscription_inactive (no active Basic), allowance_exhausted (this month’s credits are used up; resets_at says when they come back. Complimentary credits don’t: resets_at is null and ends_at says when the complimentary access ends). In a new subscription’s first 72 hours, allowance_exhausted can also be its 1,000-credit limit: reason is "ramp", and resets_at says when the rest opens. key_cap_reached (this key reached its monthly cap; resets_at is 00:00 UTC on the 1st of next month). key_cap_too_low (this key’s monthly cap is below the ceiling of the plan, re-plan or extend it asked for, so it can never hold one; there’s no resets_at).
403access_suspended. key_scope: the key lacks the scope this endpoint needs (see Keys).
404not_found.
413payload_too_large: a body over 1 MB, more than 50 events or feedback items, a state over 16 KB, or metadata over 2 KB.
429rate_limited. Wait for Retry-After.
503capri_unavailable: Capri is not open yet, or is briefly down. capri_paused: Capri is paused for a while (Retry-After 300 s). It answers predict/, opening a session, events/, feedback/ and replans/; reads (models/, openapi/, a session’s summary, updates/, stream/, plan/ and replans/{id}/), close/, DELETE and usage/ keep working. Either way, wait for Retry-After.

With overage on, a 402 can also be overage_cap_reached (this period’s overage limit is used up as well; resets_at as for allowance_exhausted) or insufficient_credits (your Nika credits can’t cover the call right now).

Session mode adds

400seq_order: seq numbers must rise within one events/ call (predict/ checks this too). bad_plan: the plan you sent can’t be used; param says which part. invalid_request with param Last-Event-ID: a stream’s Last-Event-ID isn’t an item’s id.
403access_suspended: a suspended account can’t open a stream, and its open streams end at the next check.
404not_found: also a session on another account, a deleted one, or one opened with the other kind of key (live or test).
405method_not_allowed: the Allow header lists the methods the endpoint takes.
409session_busy: another call, or a plan or re-plan landing, changed the session at the same moment; send yours again. session_limit_reached: 20 sessions are open. idempotency_key_reused, idempotency_key_in_use: see Idempotency-Key.
410session_expired: 24 hours went by without events or feedback, and its content is gone. session_closed: the session takes no events after close/, and a stream on a closed session with nothing left to send answers it too. Open a new session for either.
429capacity: the account already has 25 streams open (Retry-After 30 s).

Plans and re-plans add

400invalid_request: replans/ takes { reason, note? }, with one of the six reasons, and note only with user_change.
402allowance_exhausted: there isn’t room to hold the plan’s or re-plan’s ceiling. key_cap_reached: the key’s monthly cap hasn’t that much left this month. key_cap_too_low: the key’s monthly cap is below the ceiling, so it never will.
404not_found: also a re-plan on another account, one made with the other kind of key, or a plan’s cpl_ id (read a plan through its session).
409replans_off: settings.replans is "off". plan_pending: Capri is still writing the plan. replan_in_progress: one is already running. replan_limit_reached, replan_too_soon: see Limits. superseded: the re-plan Capri recommended no longer applies, because the plan changed or what set it off cleared. It’s refused once, then forgotten: ask again once 8 steps have passed since it was recommended, and the re-plan is your own.
429rate_limited and capacity, with Retry-After: see Limits.
503capri_unavailable: Capri can’t write plans right now (Retry-After 300 s). A session asking for a Capri plan still opens, without one.

Claude Code hook pack

An opt-in Claude Code plugin that streams a coding session to Capri and hands Capri’s notes back to the agent as context. Each Claude Code session becomes one Capri session (see Session mode): it opens at your first prompt and closes when Claude Code exits. The pack does nothing until you set a key.

In Claude Code
/plugin marketplace add goodgains-dev/nika-plugins
/plugin install capri@nika

Put CAPRI_API_KEY in the shell environment Claude Code starts from (export CAPRI_API_KEY=nika_cp_test_…, or $env:CAPRI_API_KEY = "nika_cp_test_…" in PowerShell), then restart Claude Code. Start with a test key: it’s free, and answers with fixtures.

It needs Claude Code 2.1.163 or later, and Node.js 18 or newer on your PATH.

SettingDefaultWhat it does
CAPRI_API_KEYnoneRequired: a live or test key (nika_cp_live_… or nika_cp_test_…) with the steer scope (new keys have it). Without one, every hook does nothing.
CAPRI_HOOKSonoff turns every hook into a no-op.
CAPRI_DECISIONSrecommendauto lets Capri make decisions where they’re open to your account (see Decisions). The pack carries out the one it can: keeping the agent going when it says “done” while checks are red, once per stop.
CAPRI_REPLANSmanualauto, with CAPRI_DECISIONS=auto too, lets Capri start its own re-plans, which are billed. With manual the pack never starts one; off turns re-plans off.
CAPRI_PLANnonecapri asks Capri to write a plan for each session, which is billed (below).
CAPRI_RETENTION_DAYS70-30: how many days a session’s content stays after it closes (7 is Capri’s own default). 0 erases it at close.
CAPRI_BASE_URLhttps://www.codename-nika.com/api/capri/v1/The API base. It must be https.
CAPRI_TIMEOUT_MS4000Each call’s timeout in milliseconds, 250-7000.
CAPRI_STATE_DIRthe plugin’s data folderWhere the pack keeps each session’s state and its log.

What it sends

Your first prompt, as the session’s goal (code blocks removed, secrets scrubbed, at most 2,000 characters). Then events in batches: the files an edit touched with its lines added and removed, commands (scrubbed, at most 300 characters) and their exit codes, test counts and failing test names, the files and folders the agent read, the glob patterns it listed files with, and the web pages it fetched (without their query strings), its todos, and its last message at each stop. Paths inside your project are sent relative to it.

Never sent: file contents, diffs or patches, command output (apart from a test summary’s counts and failing names), tool results, code blocks, the text of your later prompts, web search queries, and the patterns of the Grep tool and of search-only commands.

What it costs

Each events/ call is metered like one step (about 0.04 credits for a rules-only one). Opening, closing and acknowledgements are free, and test keys cost nothing. A Capri plan (CAPRI_PLAN=capri) costs up to 62 credits per session, held when the session opens; re-plans Capri starts in auto mode cost up to 42 credits each.

Every hook fails quietly, and waits out a 429 or 503 for its Retry-After, so an account Capri hasn’t let in yet sees nothing. The rest, including how it stays out of your agent’s way: the hook pack’s README.

Using Codex or OpenCode? See Other agents.

Other agents: Codex and OpenCode

The hook pack plugs one agent into session mode. Codex and OpenCode have hooks and plugins of their own, and an adapter can connect them the same way. Capri never runs anything: an adapter on your machine or server maps the agent’s events to capri.v1 and hands Capri’s notes back. The key comes from the environment: never a browser, a repo or a committed config.

No adapter code ships yet. This section gives the mappings, the batching rule, a Codex hooks.json, and what may leave your machine.

These mappings follow each tool’s docs and source as of 2026-10-30. They haven’t been run against a real Codex or OpenCode yet. Start with a test key.

Batching

What may leave your machine

What an adapter may send. It’s stricter than the hook pack, which also sends the glob patterns it listed files with, the pages it fetched (without their query strings), and for a file outside your project, its path from your home folder or just its name.

Capri scrubs secrets again when events arrive, but only as a backstop.

Notes, never narration

Hand your agent only steer.note.text. Leave settings.narrate unset in an adapter: narration is for people, and it never goes into the agent’s context.

Codex

Codex hookcapri.v1
UserPromptSubmitThe first prompt opens the session as its goal, with agent "codex"; later prompts are a turn start, and their text stays on your machine.
PostToolUse Bashshell (Codex sends no exit code), plus test counts parsed from the output. A search-only command is a tool, class search.
PostToolUse apply_patchdiff: paths and +/− line counts, counted from the patch, never the patch.
PostToolUse update_plantodos.
PostToolUse mcp__*tool: the name only.
PermissionRequestpermission, decision "ask": the adapter never approves or denies.
PostCompactusage, compacted.
Stopturn end. In auto, a block_done decision becomes decision "block", which Codex turns into a new prompt; never when stop_hook_active is set.
SessionEndclose/.
~/.codex/hooks.json · capri-adapter.mjs is your adapter: it reads each event as JSON on stdin
{
  "hooks": {
    "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "node /path/to/capri-adapter.mjs", "timeout": 10 }] }],
    "PostToolUse": [
      {
        "matcher": "^(Bash|apply_patch|update_plan|mcp__.*)$",
        "hooks": [{ "type": "command", "command": "node /path/to/capri-adapter.mjs", "timeout": 10 }]
      }
    ],
    "PermissionRequest": [{ "hooks": [{ "type": "command", "command": "node /path/to/capri-adapter.mjs", "timeout": 10 }] }],
    "PostCompact": [{ "hooks": [{ "type": "command", "command": "node /path/to/capri-adapter.mjs", "timeout": 10 }] }],
    "Stop": [{ "hooks": [{ "type": "command", "command": "node /path/to/capri-adapter.mjs", "timeout": 10 }] }],
    "SessionEnd": [{ "hooks": [{ "type": "command", "command": "node /path/to/capri-adapter.mjs", "timeout": 3 }] }]
  }
}

Hooks change between Codex releases. That hook commands get your environment comes from Codex’s source, not its docs, and two things are untested: whether ~ expands in a hook’s command (the example uses a full path), and whether hooks for tool calls that run side by side overlap (keep the adapter’s queue behind a lock). Check your version’s hook docs.

OpenCode

OpenCodecapri.v1
prompt · chat.message2.x’s prompt hook, or 1.x’s chat.message: the first prompt opens the session as its goal, with agent "opencode"; later prompts are a turn start.
shell · bashAfter it runs (shell in 2.x, bash in 1.x): shell, with the exit code, plus test counts parsed from the output.
edit · patch · apply_patch · writediff: paths and +/− line counts, never the patch.
todowritetodos.
read · grep · globtool, with a path at most: never the patterns.
permission.askedpermission, decision "ask": the adapter never answers it.
session.execution.succeeded · session.execution.failed · session.idleturn end: the execution events in 2.x, session.idle in 1.x.
session.compaction.ended · session.compactedusage, compacted (2.x, then 1.x).
session.deletedclose/.
lsp.client.diagnostics1.x only: nothing. These events carry no error counts, which diag needs.

Appending a note to a tool result comes from 1.19.5’s source, not its docs, and 2.x’s instructions entry is experimental; whether a 2.x execution can span more than one prompt isn’t settled either. Check your version’s plugin docs.

Pricing and limits

Basic

$50 a month

Includes 4,000 Capri credits every paid month. Unused credits don’t roll over. Cancel anytime.

CallTypical credits
A rules-only step (wait: "rules")0.04
A step with a fresh hunch (wait: "hunch")about 0.16–0.27, never more than 0.46
A session’s events/ callThe same as a step above
A plan Capri writes (plan: { "source": "capri" })At cost, never more than 62
A re-planAt cost, never more than 42
An extend (reason lookahead_low)At cost, never more than 21
A plan or re-plan that fails0
Your own plan, and reading plans and re-plans0
Opening, polling, streaming, feedback, closing or deleting a session, usage/ and openapi/0
Text narration (settings.narrate: "text")0
Audio narration ("audio"): not available yet0
Any call with a test key0
Capri Shield on up to 10 of your own sites (opening gradually)0

When the month’s credits run out, calls answer 402 until the next month (complimentary credits, until the comp ends). Each response shows what it cost and what’s left. Requests are rate-limited per key and per account; on 429 or 503, wait for Retry-After.

A new subscription’s first paid month can use up to 1,000 credits in its first 72 hours; the rest of the month’s credits open after that. A key’s own monthly cap, when you set one, applies within your plan’s credits.

A plan or re-plan holds its ceiling when Capri accepts it, so it needs that much room in your allowance, and settles to what it used when it ends. One that fails gives the hold back. One that ran but couldn’t land (superseded) is charged at cost.

Overage

Overage is opening gradually. When it’s offered to your account, you can turn it on in the console’s Basic card: “Use my Nika credits after my included credits”. With it on, Capri keeps answering once the month’s included credits are used up, and takes what each call uses from your Nika credits at the same rate; every response shows its cost. A limit you set caps it each period: 1,000 Nika credits unless you choose another, from 100 to 10,000.

Capri takes Nika credits a few at a time and gives back what it didn’t use when the period ends or when you turn overage off (work still running gives its change back when it finishes), so a period’s overage costs its total rounded up to a whole credit. A hold that crosses the edge uses the included credits left first. A new subscription’s first 72 hours, key caps and test keys work as before: a key’s monthly cap counts overage too, and test keys never use it. When the limit is reached, calls answer 402 overage_cap_reached; when your Nika credits can’t cover a call, 402 insufficient_credits.

Your live webhooks get capri.allowance.low at 80% and 100% of your overage limit too, once a period at each, with reason "overage" and included set to the limit, and Nika emails you then. Raise the limit after that, and Nika emails you again as you pass 80% and 100% of the new one; the webhook doesn’t come again until the next period.

Talk to Capri

Talk to Capri is opening gradually. When it’s on for your account, you can talk with Capri in the console, in its own voice, and ask how it steers your agent. A call uses about 33.33 Capri credits a minute from your Basic credits, charged by the second; up to 333.34 credits are held while you talk, and a call ends after 10 minutes. One call at a time, and up to 10 calls a day. Overage doesn’t pay for calls, but with overage on, other Capri calls made while a call is open may use your Nika credits, because the call’s hold counts against your included credits. Nika keeps no recording or transcript of the call; the voice service keeps its record of it for at most a day. Capri is an AI from Nika, and on a call it can’t see your sessions, keys, code or account.

Versions

capri-1 always points at the newest snapshot (for example capri-1-20261028). Pin a dated id to keep behaviour fixed. Changes to /v1/ only add fields.

Capri API docs · the steering model for coding agents