openapi: 3.1.0 info: title: AlphaLabel API version: 0.1.0 description: | REST API for the AlphaLabel data-labeling agent. AlphaLabel runs Claude to label text items using pluggable YAML kits, then runs a judge panel to verify each label. This API exposes the full read surface plus single-item labeling and cost estimation. ## Authentication All endpoints except `GET /v1/health` require an `X-API-Key` header. Set the key on the server via the `LABELER_API_KEY` environment variable. ``` X-API-Key: your-api-key ``` ## Pagination List endpoints return a `nextCursor` field. Pass it as `?after=` to fetch the next page. A `null` cursor means you are on the last page. Cursors are opaque — do not parse or construct them. ## Errors All errors share the same shape: ```json { "error": { "code": "ERROR_CODE", "message": "human-readable description" } } ``` Common codes: `UNAUTHORIZED`, `NOT_FOUND`, `BAD_REQUEST`, `CONFLICT`, `TIMEOUT`, `IDEMPOTENCY_CONFLICT`, `RATE_LIMITED`, `INTERNAL_ERROR`. ## Rate limiting Each `X-API-Key` is allocated a token bucket: defaults are 50 tokens/sec sustained, 100 token burst (override via `LABELER_RATE_LIMIT_PER_SEC` / `LABELER_RATE_LIMIT_BURST`). Every authenticated request consumes one token. When the bucket is empty the server returns: ``` HTTP/1.1 429 Too Many Requests Retry-After: 2 ``` Clients should honor `Retry-After` and back off — repeatedly hammering a rate-limited endpoint keeps the bucket empty. `/v1/health` is intentionally not rate-limited (load balancers probe it). ## CORS By default the API does not emit any CORS headers and browser clients from foreign origins are blocked. To allow browser-based clients (review UIs, dashboards) set: ``` LABELER_CORS_ORIGINS=https://review.example.com LABELER_CORS_ORIGINS=https://a.com,https://b.com # multiple origins LABELER_CORS_ORIGINS=* # allow any (dev only) ``` Allowed request headers: `Content-Type`, `X-API-Key`, `Idempotency-Key`. Allowed methods: `GET`, `POST`, `DELETE`, `OPTIONS`. Exposed response headers (visible to browser JS): `X-Request-Id`, `Retry-After`, `Idempotent-Replayed`. Preflight responses are cached for 10 minutes. ## Idempotency All mutating POST endpoints (`/v1/labels`, `/v1/batches`, `/v1/qa-batches`, `/v1/review`, `/v1/review/*/commit`, `/v1/review/*/correct`, `/v1/review/*/relabel`) honor the `Idempotency-Key` request header. ``` Idempotency-Key: 8b94c9a2-7e6c-4f0a-bea1-83b1a5c40c2f ``` - First request runs normally; the 2xx response is cached for 24 hours. - A retry with the **same key and same body** replays the cached response; the reply carries `Idempotent-Replayed: true`. - A retry with the **same key but a different body** returns `409 IDEMPOTENCY_CONFLICT`. Keys are scoped per `X-API-Key`, must be 1-200 characters, and are pruned 24 hours after first use. Use a UUID or any unique value per distinct operation — typically the same key your client uses to track that this is "the same request, just retried." servers: - url: http://localhost:3000 description: Local development security: - ApiKeyAuth: [] paths: /v1/health: get: operationId: getHealth summary: Health check description: | Returns server health and DB connectivity status. No authentication required. Load balancers should use this endpoint — it returns `503` when the DB is unreachable, so traffic will not be routed to a broken instance. security: [] tags: [System] responses: "200": description: Server is healthy content: application/json: schema: $ref: "#/components/schemas/HealthResponse" example: status: ok version: "0.1.0" db: status: ok schemaVersion: 9 "503": description: Server is unhealthy (DB unreachable) content: application/json: schema: $ref: "#/components/schemas/HealthResponse" example: status: error version: "0.1.0" db: status: error schemaVersion: null error: "unable to open database file" /v1/kits: get: operationId: listKits summary: List kits description: | Returns all kits loaded from the server's kit directory. A kit defines the taxonomy (allowed classes or span labels), the tools the labeling agent can call, and the judge-panel lenses used in QA. tags: [Kits] responses: "200": description: List of kits content: application/json: schema: allOf: - $ref: "#/components/schemas/ListEnvelope" - type: object properties: items: type: array items: $ref: "#/components/schemas/KitSummary" example: items: - name: sentiment version: "1.0.0" taxonomyVersion: demo-v0 tools: [apply_class, add_note, defer, abstain, finalize] lenses: [literal, contextual, policy] constraints: apply_class: allowedClasses: [positive, negative, neutral] maxCalls: 1 nextCursor: null "401": $ref: "#/components/responses/Unauthorized" /v1/kits/{name}: get: operationId: getKit summary: Get kit description: Returns a single kit by name. tags: [Kits] parameters: - name: name in: path required: true schema: type: string example: sentiment responses: "200": description: Kit details content: application/json: schema: $ref: "#/components/schemas/KitSummary" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/kits/{name}/lint: get: operationId: lintKit summary: Lint a registered kit description: | Runs static lints against a kit already registered on the server (loaded from `LABELER_KITS_DIR`). Returns a list of findings — callers can fail their CI if any severity is `error`. Uploading arbitrary YAML for linting is intentionally not supported. tags: [Kits] parameters: - name: name in: path required: true schema: type: string responses: "200": description: Lint results content: application/json: schema: type: object required: [kit, lints] properties: kit: type: string lints: type: array items: type: object required: [severity, code, message] properties: severity: type: string enum: [error, warn, info] code: type: string message: type: string "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/qa-summary: get: operationId: getQaSummary summary: QA summary across runs description: | Returns aggregate QA pass/fail rates with a Wilson-score CI plus per-stratum rollup across all matching runs. Used by dashboards and CI quality gates. tags: [QA] parameters: - name: kit in: query required: false schema: type: string - name: status in: query required: false schema: type: string enum: [running, completed, aborted] - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 20 responses: "200": description: QA summary content: application/json: schema: type: object "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/annotations: get: operationId: listAnnotations summary: List annotations description: | Returns committed annotations for a given kit, ordered by creation time. Pass `status=all` to include deferred and abstained annotations. Pagination is cursor-based — use the `nextCursor` from each response as the `after` parameter of the next request. tags: [Annotations] parameters: - name: kit in: query required: true description: Kit name to filter by (e.g. `sentiment`) schema: type: string - name: status in: query required: false description: Filter by annotation status. Defaults to `committed`. schema: type: string enum: [committed, all] default: committed - name: itemId in: query required: false description: | Restrict results to annotations of a single source item. Useful for finding every annotation in a relabel chain. schema: type: string - name: sessionId in: query required: false description: Restrict results to annotations produced by a single session. schema: type: string - name: limit in: query required: false description: Maximum number of results to return (1–200). schema: type: integer minimum: 1 maximum: 200 default: 50 - name: after in: query required: false description: Opaque cursor from a previous response's `nextCursor` field. schema: type: string responses: "200": description: Paginated list of annotations content: application/json: schema: allOf: - $ref: "#/components/schemas/ListEnvelope" - type: object properties: items: type: array items: $ref: "#/components/schemas/Annotation" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/annotations/export: get: operationId: exportAnnotations summary: Stream-export annotations description: | Streams all matching annotations as JSONL (newline-delimited JSON) or CSV. The response body is streamed in chunks to keep memory bounded — large exports do not load the full table into memory on the server. tags: [Annotations] parameters: - name: kit in: query required: true schema: type: string - name: format in: query required: false schema: type: string enum: [jsonl, csv] default: jsonl - name: status in: query required: false schema: type: string enum: [committed, all] default: committed responses: "200": description: Stream of annotations content: application/x-ndjson: schema: type: string description: One JSON-encoded annotation per line. text/csv: schema: type: string "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/annotations/by-item/{kit}/{itemId}/latest: get: operationId: getLatestAnnotationForItem summary: Get latest committed annotation for an item description: | Resolves the canonical "current" annotation for an item — the leaf of the relabel chain (no annotation has it as a parent) with the latest `emittedAt`. Only `status='committed'` rows are considered. Use this when a downstream consumer needs "what should we display for this item right now" without traversing the chain manually. tags: [Annotations] parameters: - name: kit in: path required: true schema: type: string - name: itemId in: path required: true schema: type: string responses: "200": description: Latest committed annotation content: application/json: schema: $ref: "#/components/schemas/Annotation" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/annotations/{id}: get: operationId: getAnnotation summary: Get annotation description: | Returns a single annotation by its ID. The `callHistory` field (raw LLM tool-call sequence) is omitted for brevity — use the export CLI command if you need it. tags: [Annotations] parameters: - name: id in: path required: true description: Annotation ID (format `ann_`) schema: type: string example: ann_4a3f9c1b responses: "200": description: Annotation content: application/json: schema: $ref: "#/components/schemas/Annotation" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/labels: post: operationId: createLabel summary: Label an item description: | Runs the labeling agent on a single text item and returns the committed annotation. This is a **synchronous** call — it waits for the LLM to complete, which typically takes 5–30 seconds. The request times out after 120 seconds. If `runPanel` is `true` (the default), the judge panel also runs immediately and verdicts are included in the response. The caller must supply `itemId`. AlphaLabel uses it to link the annotation back to your dataset. Use your own stable identifier (e.g. a database row ID or content hash). tags: [Labeling] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CreateLabelRequest" example: kit: sentiment itemId: product-review-00042 text: "This product completely exceeded my expectations." runPanel: true responses: "201": description: Annotation created content: application/json: schema: $ref: "#/components/schemas/LabelResponse" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": description: Kit not found content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" "422": description: LLM call timed out (120s exceeded) content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/qa-runs: get: operationId: listQaRuns summary: List QA runs description: | Returns QA batch runs, oldest first. Filter by kit or status. Each run represents one execution of `qa-batch` against a JSONL file. tags: [QA] parameters: - name: kit in: query required: false description: Filter by kit name schema: type: string - name: status in: query required: false description: Filter by run status schema: type: string enum: [running, completed, aborted] - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 20 - name: after in: query required: false schema: type: string responses: "200": description: Paginated list of QA runs content: application/json: schema: allOf: - $ref: "#/components/schemas/ListEnvelope" - type: object properties: items: type: array items: $ref: "#/components/schemas/QaRun" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/qa-runs/{id}: get: operationId: getQaRun summary: Get QA run description: | Returns a single QA run's summary fields. Per-sample outcomes are not embedded inline (they can number in the thousands); use the `outcomesUrl` field (or `GET /v1/qa-runs/{id}/outcomes` directly) to paginate through them. tags: [QA] parameters: - name: id in: path required: true description: QA run ID (format `qa_`) schema: type: string example: qa_7f2a1c responses: "200": description: QA run summary content: application/json: schema: allOf: - $ref: "#/components/schemas/QaRun" - type: object required: [outcomesCount, outcomesUrl] properties: outcomesCount: type: integer description: Number of qa_outcome rows for this run. example: 42 outcomesUrl: type: string description: Relative URL of the paginated outcomes endpoint. example: /v1/qa-runs/qa_7f2a1c/outcomes "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/qa-runs/{id}/outcomes: get: operationId: listQaOutcomes summary: List QA outcomes description: | Returns the individual sampled outcomes for a QA run, paginated. Each outcome is one item that was sent through the judge panel. tags: [QA] parameters: - name: id in: path required: true schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 200 default: 50 - name: after in: query required: false schema: type: string responses: "200": description: Paginated list of outcomes content: application/json: schema: allOf: - $ref: "#/components/schemas/ListEnvelope" - type: object properties: items: type: array items: $ref: "#/components/schemas/QaOutcome" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/cost-estimate: post: operationId: estimateCost summary: Estimate batch cost description: | Estimates the USD cost of a labeling + QA batch before you run it. Pass the lengths (in characters) of your item texts and an optional QA sampling rate. The estimate is based on ~4 chars/token and current Anthropic pricing — treat it as an order-of-magnitude figure, not an invoice. No LLM calls are made; this is a pure computation. tags: [Utilities] requestBody: required: true content: application/json: schema: $ref: "#/components/schemas/CostEstimateRequest" example: kit: sentiment itemTextLengths: [120, 340, 85, 210] qaRate: 0.2 responses: "200": description: Cost estimate content: application/json: schema: $ref: "#/components/schemas/CostEstimate" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": description: Kit not found content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/config: get: operationId: getConfig summary: Server configuration + limits + capabilities description: | Returns server-side limits, defaults, registered kits, CORS state, rate-limit state, and idempotency policy. Clients can read this at startup to adapt their batch sizes, retry budgets, and concurrency choices without trial-and-error 4xx responses. Values are pulled directly from the modules that enforce them — the endpoint cannot drift out of sync with the actual runtime limits. tags: [Utilities] responses: "200": description: Server config snapshot content: application/json: schema: type: object required: [apiVersion, kits, limits, cors, idempotency] properties: apiVersion: { type: string } kits: type: array items: { type: string } limits: type: object properties: batches: type: object properties: maxItems: { type: integer } maxConcurrency: { type: integer } defaultConcurrency: { type: integer } bulkReviewCommit: type: object properties: maxAnnotationIds: { type: integer } relabel: type: object properties: timeoutMs: { type: integer } rateLimit: type: object properties: disabled: { type: boolean } ratePerSec: { type: number } burst: { type: integer } cors: type: object properties: enabled: { type: boolean } allowAnyOrigin: { type: boolean } allowedOrigins: type: array items: { type: string } idempotency: type: object properties: header: { type: string } maxKeyLength: { type: integer } ttlSeconds: { type: integer } "401": $ref: "#/components/responses/Unauthorized" /v1/stats: get: operationId: getStats summary: System-level rollup for operator dashboards description: | Returns counts and rollups across the whole system in a single round-trip — annotations, sessions, batches by status, qa runs by status, review backlog, corrections, top kits by recent volume, and cumulative cost. \"last24h\" windows use a server-side cutoff of `serverTime - 86_400_000`. For other windows, query the underlying list endpoints with `since` / `until` filters. All counts are computed via indexed aggregate queries; the endpoint is safe to poll from dashboards once every few seconds. tags: [Utilities] responses: "200": description: System stats snapshot content: application/json: schema: type: object required: - serverTime - annotations - sessions - batches - qaRuns - reviewBacklog - corrections - topKitsLast24h - cost properties: serverTime: type: integer description: Epoch ms — server-side reference for last24h windows. annotations: type: object properties: total: { type: integer } committedTotal: { type: integer } last24h: { type: integer } sessions: type: object properties: total: { type: integer } last24h: { type: integer } batches: type: object properties: running: { type: integer } completed: { type: integer } failed: { type: integer } cancelled: { type: integer } last24h: { type: integer } qaRuns: type: object properties: running: { type: integer } completed: { type: integer } aborted: { type: integer } reviewBacklog: type: integer description: Pending tier.routed_to_human events with no commit/relabel yet. corrections: type: object properties: total: { type: integer } last24h: { type: integer } topKitsLast24h: type: array items: type: object properties: toolKitVersion: { type: string } count: { type: integer } cost: type: object properties: totalUsd: { type: number } last24hUsd: { type: number } "401": $ref: "#/components/responses/Unauthorized" /v1/corrections: get: operationId: listCorrections summary: List annotation corrections description: | Every time a reviewer corrects an annotation (via `POST /v1/review/:id/correct` or the LLM-assisted relabel path) a diff row is written to `annotation_correction`. This endpoint exposes those diffs so reviewer UIs can show "what changed" and active-learning pipelines can mine them as supervision signal. tags: [Review] parameters: - name: reviewer in: query required: false schema: type: string - name: parentAnnotationId in: query required: false schema: type: string - name: since in: query required: false description: Epoch ms. Returns rows with `time_corrected >= since`. schema: type: integer minimum: 0 - name: until in: query required: false description: Epoch ms. Returns rows with `time_corrected < until`. schema: type: integer minimum: 0 - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 200 default: 50 - name: after in: query required: false schema: type: string responses: "200": description: Paginated list of correction records content: application/json: schema: $ref: "#/components/schemas/ListEnvelope" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/corrections/{id}: get: operationId: getCorrection summary: Get a single correction by corrected-annotation id tags: [Review] parameters: - name: id in: path required: true description: ID of the corrected annotation (NOT the parent). schema: type: string responses: "200": description: Correction record with structured diff "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/sessions: get: operationId: listSessions summary: List labeling sessions description: | Each `labelItem()` call creates a session — sessions are the unit of agent execution and roll up cost + tokens consumed by that labeling pass. Annotations and audit events both reference the session via `sessionId` / `aggregateId`. tags: [Sessions] parameters: - name: projectId in: query required: false schema: type: string - name: agent in: query required: false schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 200 default: 50 - name: after in: query required: false schema: type: string responses: "200": description: Paginated list of sessions content: application/json: schema: $ref: "#/components/schemas/ListEnvelope" "401": $ref: "#/components/responses/Unauthorized" /v1/sessions/{id}: get: operationId: getSession summary: Get session details description: | Returns a session with rollup counts of annotations + events plus drill-in URLs to fetch them paginated. tags: [Sessions] parameters: - name: id in: path required: true schema: type: string responses: "200": description: Session details content: application/json: schema: type: object "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/events: get: operationId: listEvents summary: Read the audit event log description: | Generic read of the append-only event log. Every meaningful action in the labeler (`tier.routed_to_human`, `review.committed`, `review.relabeled`, `qa.started`, `qa.completed`, `qa.aborted`, `qa.early_stopped`, `qa.max_samples_reached`, `qa.auto_rate_chosen`, `qa.stratum_gates_evaluated`, ...) writes an event row that this endpoint exposes for audit dashboards, debugging, and external consumers. Filters compose with AND: - `kind=` or `kindPrefix=` (mutually exclusive) - `aggregateId=` - `since=` / `until=` — half-open interval `[since, until)` Results are ordered by id ASC (insertion order) with cursor pagination. The log is append-only, so a paginated walk that records the last `time` value is a safe long-poll pattern for incremental consumers. tags: [Events] parameters: - name: kind in: query required: false description: Exact match against the `kind` column. schema: type: string - name: kindPrefix in: query required: false description: | Match `kind` by prefix (e.g. `qa.` matches every QA-lifecycle event). Cannot be combined with `kind`. schema: type: string - name: aggregateId in: query required: false schema: type: string - name: since in: query required: false description: Epoch milliseconds. Returns events with `time >= since`. schema: type: integer minimum: 0 - name: until in: query required: false description: Epoch milliseconds. Returns events with `time < until`. schema: type: integer minimum: 0 - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 500 default: 50 - name: after in: query required: false schema: type: string responses: "200": description: Paginated list of events content: application/json: schema: allOf: - $ref: "#/components/schemas/ListEnvelope" - type: object properties: items: type: array items: type: object required: [id, aggregateId, seq, kind, data, time] properties: id: type: integer aggregateId: type: string seq: type: integer kind: type: string data: type: object description: Parsed JSON payload of the event. time: type: integer description: Epoch milliseconds. "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/batches: get: operationId: listBatches summary: List batch jobs description: | Returns batch jobs created via `POST /v1/batches`, with optional kit and status filters. Cursor-paginated. tags: [Batches] parameters: - name: kit in: query required: false schema: type: string - name: status in: query required: false schema: type: string enum: [running, completed, failed, cancelled] - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 100 default: 20 - name: after in: query required: false schema: type: string responses: "200": description: Paginated list of batch jobs content: application/json: schema: allOf: - $ref: "#/components/schemas/ListEnvelope" - type: object properties: items: type: array items: $ref: "#/components/schemas/BatchJobSummary" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" post: operationId: createBatch summary: Submit a labeling batch description: | Submits a batch of items for labeling. The job runs in the background — the response returns immediately with `202 Accepted` and a `jobId`. Poll `GET /v1/batches/{id}` for status. Max 200 items per submission; max 50 concurrent labelers. tags: [Batches] requestBody: required: true content: application/json: schema: type: object required: [kit, items] properties: kit: type: string items: type: array maxItems: 200 items: type: object required: [id, text] properties: id: type: string text: type: string runPanel: type: boolean default: true concurrency: type: integer minimum: 1 maximum: 50 default: 3 responses: "202": description: Batch accepted content: application/json: schema: type: object required: [jobId, status, totalItems] properties: jobId: type: string status: type: string enum: [running] totalItems: type: integer "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/batches/{id}: get: operationId: getBatch summary: Get batch job description: Returns a batch job with per-item status. tags: [Batches] parameters: - name: id in: path required: true schema: type: string responses: "200": description: Batch job content: application/json: schema: $ref: "#/components/schemas/BatchJob" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" delete: operationId: cancelBatch summary: Cancel a running batch description: | Marks a running batch job as `cancelled`. In-flight LLM calls complete normally (no AbortController plumbed through `labelItem`), but no new items start. Items still `pending` when cancel is observed transition to status `cancelled`. Returns `409 Conflict` if the job has already terminated. tags: [Batches] parameters: - name: id in: path required: true schema: type: string responses: "200": description: Batch cancelled content: application/json: schema: type: object required: [jobId, status] properties: jobId: type: string status: type: string enum: [cancelled] "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" "409": description: Job already terminated (completed / failed / cancelled) content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" /v1/qa-batches: post: operationId: createQaBatch summary: Submit a QA batch description: | Runs a QA batch (label + sample + judge) end-to-end. Returns a `qaRunId` to poll via `GET /v1/qa-runs/{id}`. tags: [QA] requestBody: required: true content: application/json: schema: type: object required: [kit, items, targetAccuracy, minSamples] properties: kit: type: string items: type: array maxItems: 200 items: type: object required: [id, text] properties: id: type: string text: type: string targetAccuracy: type: number minSamples: type: integer qaRate: type: number passCriterion: type: string ciLevel: type: number maxSamples: type: integer responses: "202": description: QA batch accepted content: application/json: schema: type: object required: [qaRunId] properties: qaRunId: type: string "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/review: get: operationId: listReview summary: List items pending human review description: | Returns the review queue — annotations the panel routed to humans (low-confidence / disagreement / forced abstain). Cursor-paginated; supports optional `kit` and `minConfidence` / `maxConfidence` filters. tags: [Review] parameters: - name: kit in: query required: false schema: type: string - name: minConfidence in: query required: false schema: type: number minimum: 0 maximum: 1 - name: maxConfidence in: query required: false schema: type: number minimum: 0 maximum: 1 - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 200 default: 50 - name: after in: query required: false schema: type: string responses: "200": description: Paginated review queue content: application/json: schema: $ref: "#/components/schemas/ListEnvelope" "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" post: operationId: enqueueReview summary: Manually enqueue an annotation for review description: | Emits a `tier.routed_to_human` event for an existing annotation — useful when a downstream consumer flags something the panel didn't. tags: [Review] requestBody: required: true content: application/json: schema: type: object required: [annotationId] properties: annotationId: type: string reason: type: string responses: "201": description: Annotation enqueued "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/review/bulk-commit: post: operationId: bulkCommitReview summary: Approve multiple annotations in one transaction description: | Records a `review.committed` event for each annotation in one bun:sqlite transaction. Per-item status is reported back so the caller can tell which ids weren't found. Annotations that don't exist do NOT abort the others — they just appear in the response with `status: not_found`. Events emitted here carry `source: "bulk-api"` so analytics can distinguish bulk approvals from individual ones. Limits: `annotationIds` must be 1-200 entries. tags: [Review] requestBody: required: true content: application/json: schema: type: object required: [reviewer, annotationIds] properties: reviewer: type: string annotationIds: type: array minItems: 1 maxItems: 200 items: type: string responses: "200": description: Bulk commit result content: application/json: schema: type: object required: [committed, notFound, results] properties: committed: type: integer notFound: type: integer results: type: array items: type: object required: [annotationId, status] properties: annotationId: type: string status: type: string enum: [committed, not_found] "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" /v1/review/history: get: operationId: reviewHistory summary: Audit log of review actions description: | Stream of `review.committed` + `review.relabeled` events, with optional `reviewer` filter. Cursor-paginated. tags: [Review] parameters: - name: reviewer in: query required: false schema: type: string - name: limit in: query required: false schema: type: integer minimum: 1 maximum: 200 default: 50 - name: after in: query required: false schema: type: string responses: "200": description: Paginated review events content: application/json: schema: $ref: "#/components/schemas/ListEnvelope" "401": $ref: "#/components/responses/Unauthorized" /v1/review/{id}: get: operationId: getReview summary: Get a review queue item description: Returns the annotation + source item text for a single review entry. tags: [Review] parameters: - name: id in: path required: true schema: type: string responses: "200": description: Review item "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/review/{id}/commit: post: operationId: commitReview summary: Approve an annotation (record human acceptance) description: Records a `review.committed` event; no annotation change. tags: [Review] parameters: - name: id in: path required: true schema: type: string requestBody: required: true content: application/json: schema: type: object required: [reviewer] properties: reviewer: type: string responses: "204": description: Commit recorded "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/review/{id}/correct: post: operationId: correctReview summary: Submit a human correction (no LLM call) description: | Replaces the annotation's classes / spans with a human-supplied version. Writes a new annotation row with `origin='human-correction'` plus an `annotation_correction` diff row, in a single transaction. Faster and cheaper than `relabel` when the reviewer already knows the answer. tags: [Review] parameters: - name: id in: path required: true schema: type: string requestBody: required: true content: application/json: schema: type: object required: [reviewer] properties: reviewer: type: string classes: type: array items: $ref: "#/components/schemas/ClassEntry" spans: type: array items: type: object rationale: type: string responses: "201": description: Correction created "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" /v1/review/{id}/relabel: post: operationId: relabelReview summary: Re-run an LLM relabel under reviewer guidance description: | Calls the kit's panel again with a reviewer-supplied hint and writes the new annotation. Subject to the same 120s timeout as `POST /v1/labels`. Returns 422 if the source session has no retained item text (pre-A4 annotations). tags: [Review] parameters: - name: id in: path required: true schema: type: string requestBody: required: true content: application/json: schema: type: object required: [class, reviewer] properties: class: type: string reviewer: type: string rationale: type: string responses: "201": description: Relabel created "400": $ref: "#/components/responses/BadRequest" "401": $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" "422": description: Source session has no retained item text content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" components: securitySchemes: ApiKeyAuth: type: apiKey in: header name: X-API-Key description: Server-side key set via `LABELER_API_KEY` env var. responses: Unauthorized: description: Missing or invalid API key content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: code: UNAUTHORIZED message: invalid or missing API key NotFound: description: Resource not found content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: code: NOT_FOUND message: annotation 'ann_xyz' not found BadRequest: description: Invalid request parameters content: application/json: schema: $ref: "#/components/schemas/ErrorResponse" example: error: code: BAD_REQUEST message: "'kit' is required" schemas: ErrorResponse: type: object required: [error] properties: error: type: object required: [code, message] properties: code: type: string description: Machine-readable error code example: NOT_FOUND message: type: string description: Human-readable error description example: annotation 'ann_xyz' not found ListEnvelope: type: object required: [items, nextCursor] properties: items: type: array items: {} nextCursor: type: [string, "null"] description: | Pass as `?after=` to fetch the next page. `null` means this is the last page. example: dW5kZWZpbmVk HealthResponse: type: object required: [status, version, db] properties: status: type: string enum: [ok, error] version: type: string example: "0.1.0" db: type: object required: [status] properties: status: type: string enum: [ok, error] schemaVersion: type: [integer, "null"] example: 9 error: type: string description: Present only when db.status is "error" KitConstraint: type: object description: Constraints applied to a specific tool within a kit properties: allowedClasses: type: array items: type: string description: Valid class names for `apply_class` allowedLabels: type: array items: type: string description: Valid span labels for `select_span` allowedRelationTypes: type: array items: type: string description: Valid relation types for `add_relation` allowedKeys: type: array items: type: string description: Valid attribute keys for `add_attribute` maxCalls: type: integer description: Maximum times this tool may be called per item KitSummary: type: object required: [name, version, taxonomyVersion, tools, lenses] properties: name: type: string example: sentiment version: type: string example: "1.0.0" taxonomyVersion: type: string example: demo-v0 tools: type: array items: type: string example: [apply_class, add_note, defer, abstain, finalize] lenses: type: array items: type: string description: Judge-panel lens names example: [literal, contextual, policy] constraints: type: object additionalProperties: $ref: "#/components/schemas/KitConstraint" description: Per-tool constraints. Keys are tool names. ClassEntry: type: object required: [class] properties: class: type: string description: The assigned class label example: positive evidence: type: string description: Brief quote or phrase from the text that supports the label example: "completely exceeded my expectations" SpanEntry: type: object required: [id, start, end, label] properties: id: type: string example: span_1 start: type: integer description: Start character offset (inclusive) end: type: integer description: End character offset (exclusive) label: type: string example: product note: type: string RelationEntry: type: object required: [id, from_id, to_id, type] properties: id: type: string example: rel_1 from_id: type: string to_id: type: string type: type: string example: mentions AttributeEntry: type: object required: [target_id, key, value] properties: target_id: type: string key: type: string value: {} NoteEntry: type: object required: [text] properties: text: type: string target_id: type: string Annotation: type: object required: [annotationId, itemId, sessionId, taxonomyVersion, toolKitVersion, status, classes, spans, regions, relations, attributes, notes, emittedAt] description: | A committed annotation produced by the labeling agent. The `callHistory` field (raw LLM tool-call sequence) is excluded from API responses for brevity. properties: annotationId: type: string description: Unique annotation ID (format `ann_`) example: ann_4a3f9c1b itemId: type: string description: Caller-supplied item identifier example: product-review-00042 sessionId: type: string description: Internal labeling session ID taxonomyVersion: type: string example: demo-v0 toolKitVersion: type: string description: Kit name and version that produced this annotation example: sentiment@1.0.0 status: type: string enum: [committed, deferred, abstained, in-progress] classes: type: array items: $ref: "#/components/schemas/ClassEntry" spans: type: array items: $ref: "#/components/schemas/SpanEntry" regions: type: array items: type: object relations: type: array items: $ref: "#/components/schemas/RelationEntry" attributes: type: array items: $ref: "#/components/schemas/AttributeEntry" notes: type: array items: $ref: "#/components/schemas/NoteEntry" deferral: type: object properties: reason: type: string queue: type: string abstention: type: object properties: reason: type: string emittedAt: type: integer description: Unix timestamp in milliseconds example: 1700000000000 Verdict: type: object required: [lens, refuted, confidence, reasoning] properties: lens: type: string description: Name of the judge-panel lens that produced this verdict example: literal refuted: type: boolean description: Whether this lens disagreed with the annotation confidence: type: number format: float minimum: 0 maximum: 1 example: 0.91 reasoning: type: string description: The lens's explanation proposedAlternative: type: string description: Present when `refuted=true`; what the lens would have assigned instead CreateLabelRequest: type: object required: [kit, itemId, text] properties: kit: type: string description: Kit name (must be loaded on the server) example: sentiment itemId: type: string description: | Your stable identifier for this item. Used to link the annotation back to your dataset. Must be unique within a kit + taxonomy version. example: product-review-00042 text: type: string description: Item text to label (max ~250KB before the 1MB body limit) example: "This product completely exceeded my expectations." runPanel: type: boolean description: Whether to run the judge panel after labeling. Adds 3 LLM calls but provides per-lens verdicts. default: true LabelResponse: type: object required: [annotationId, itemId, status, classes, spans, relations, attributes, notes, toolKitVersion, usage] properties: annotationId: type: string example: ann_4a3f9c1b itemId: type: string example: product-review-00042 status: type: string enum: [committed, deferred, abstained] classes: type: array items: $ref: "#/components/schemas/ClassEntry" spans: type: array items: $ref: "#/components/schemas/SpanEntry" relations: type: array items: $ref: "#/components/schemas/RelationEntry" attributes: type: array items: $ref: "#/components/schemas/AttributeEntry" notes: type: array items: $ref: "#/components/schemas/NoteEntry" toolKitVersion: type: string example: sentiment@1.0.0 deferral: type: object properties: reason: { type: string } queue: { type: string } abstention: type: object properties: reason: { type: string } verdicts: type: array items: $ref: "#/components/schemas/Verdict" description: Present when `runPanel=true` and status is `committed` panelAgreement: type: number format: float description: Fraction of lens pairs that agreed (0–1). Present when `runPanel=true`. example: 1.0 usage: type: object required: [inputTokens, outputTokens] properties: inputTokens: type: integer description: Total input tokens consumed (labeling + panel if run) outputTokens: type: integer description: Total output tokens consumed QaRun: type: object required: [id, batchId, kitName, qaRate, targetAccuracy, minSamples, passCriterion, ciLevel, status, totalLabeled, totalSampled, passes, fails, timeStarted] properties: id: type: string description: QA run ID (format `qa_`) example: qa_7f2a1c batchId: type: string kitName: type: string example: sentiment qaRate: type: number description: Fraction of items sampled for QA (0–1) example: 0.2 targetAccuracy: type: number description: Required accuracy for the run to pass example: 0.85 minSamples: type: integer example: 30 passCriterion: type: string enum: [strict, majority] ciLevel: type: number example: 0.95 status: type: string enum: [running, completed, aborted] totalLabeled: type: integer totalSampled: type: integer passes: type: integer fails: type: integer ciLower: type: [number, "null"] description: Lower bound of Wilson confidence interval ciUpper: type: [number, "null"] abortReason: type: [string, "null"] earlyStopReason: type: [string, "null"] totalPanelInputTokens: type: integer totalPanelOutputTokens: type: integer timeStarted: type: integer description: Unix timestamp in milliseconds timeFinished: type: [integer, "null"] description: Unix timestamp in milliseconds QaOutcome: type: object required: [id, qaRunId, annotationId, sessionId, outcome, stratum, verdicts, timeEvaluated] properties: id: type: integer qaRunId: type: string annotationId: type: string sessionId: type: string outcome: type: string enum: [pass, fail] stratum: type: string description: The class or label stratum this item was sampled from example: positive verdicts: type: array items: $ref: "#/components/schemas/Verdict" timeEvaluated: type: integer CostEstimateRequest: type: object required: [kit, itemTextLengths] properties: kit: type: string example: sentiment itemTextLengths: type: array items: type: integer minimum: 0 maxItems: 10000 description: | Length in characters of each item's text. Pass `items.map(i => i.text.length)` from your dataset. example: [120, 340, 85, 210] qaRate: type: number minimum: 0 maximum: 1 default: 0 description: Fraction of items that will go through QA. 0 means labeling only. example: 0.2 CostEstimate: type: object required: [itemCount, avgItemChars, maxItemChars, assumedQaRate, assumedQaSamples, labeling, qa, totalUsd] properties: itemCount: type: integer example: 4 avgItemChars: type: number example: 188.75 maxItemChars: type: integer example: 340 assumedQaRate: type: number example: 0.2 assumedQaSamples: type: integer description: Ceiling of (itemCount * qaRate) example: 1 labeling: type: object required: [inputTokens, outputTokens, usd] properties: inputTokens: { type: integer } outputTokens: { type: integer } usd: { type: number, example: 0.0012 } qa: type: object required: [inputTokens, outputTokens, usd] properties: inputTokens: { type: integer } outputTokens: { type: integer } usd: { type: number, example: 0.0003 } totalUsd: type: number example: 0.0015 BatchJobSummary: type: object required: [jobId, kitName, status, totalItems, completedItems, failedItems, timeStarted] properties: jobId: type: string example: apibatch_4a3f9c1b kitName: type: string example: sentiment runPanel: type: boolean status: type: string enum: [running, completed, failed, cancelled] totalItems: type: integer completedItems: type: integer failedItems: type: integer error: type: [string, "null"] timeStarted: type: integer description: Epoch milliseconds. timeFinished: type: [integer, "null"] BatchJob: allOf: - $ref: "#/components/schemas/BatchJobSummary" - type: object required: [items] properties: items: type: array items: type: object required: [itemId, status] properties: itemId: type: string status: type: string enum: [pending, completed, failed, cancelled] annotationId: type: string error: type: string timeFinished: type: integer