Skip to content

Async runs and webhooks ​

Long runs (big documents, multi-step workflows) should not hold an HTTP connection open. Queue them with async: true and get the result by webhook or by polling.

Async runs ​

bash
curl "$HEVKAR_BASE_URL/v1/agents/report-builder/runs" \
  -H "Authorization: Bearer $HEVKAR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: report-2026-10" \
  -d '{"input": {"month": "2026-10"}, "async": true, "metadata": {"jobId": "j_981"}}'
# 202 {"runId": "…", "status": "queued"}
ts
const { runId } = await hevkar.agents.runAsync('report-builder', {
  input: { month: '2026-10' },
  metadata: { jobId: 'j_981' },
});

// either poll…
const run = await hevkar.runs.waitForCompletion(runId, { pollMs: 2000, timeoutMs: 15 * 60_000 });
// …or return now and handle the run.completed webhook
ts
const res = await fetch(`${baseUrl}/v1/agents/report-builder/runs`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ input: { month: '2026-10' }, async: true }),
});
const { runId } = await res.json(); // res.status === 202

All checks (input schema, files, guardrails, spend cap) run before the 202, so a queued run was accepted. async cannot be combined with stream (400 ASYNC_STREAM_CONFLICT).

Poll with GET /v1/runs/{id} (scope runs:read) until status is succeeded, failed or cancelled. A queued run can be cancelled with POST /v1/runs/{id}/cancel.

Webhook endpoints ​

Admins add endpoints in the console (Project → Webhooks): an HTTPS URL and the events to receive. The signing secret (whsec_…) is shown once when the endpoint is created. The console also shows every delivery with its attempts, status code and payload, can resend a delivery and send a test ping.

Endpoint URLs must be publicly reachable (private and loopback addresses are refused with WEBHOOK_URL_NOT_ALLOWED).

Events ​

EventWhen
run.completeda run started through the API (/v1) succeeded
run.faileda run started through the API failed or was cancelled (error.code RUN_CANCELLED)
run.waitinga workflow run paused for an approval or an event (any run source, including the console)
datasource.synceda data source sync finished
datasource.faileda sync failed, or every document of it failed
pingtest delivery from the console

Playground runs and child runs do not send run.completed / run.failed. Payload shapes: Webhook events.

Request format ​

http
POST /webhooks/hevkar HTTP/1.1
Content-Type: application/json
User-Agent: hevkar-webhooks/1.0
x-hevkar-event: run.completed
x-hevkar-delivery: 6c1d1a52-…
x-hevkar-signature: t=1763720100,v1=5b1f0c…

{
  "id": "e2b4…",
  "event": "run.completed",
  "createdAt": "2026-11-21T10:15:00.000Z",
  "projectId": "…",
  "data": {
    "runId": "…",
    "agentId": "…",
    "status": "succeeded",
    "output": { "total": 249.9 },
    "usage": { "inputTokens": 1830, "outputTokens": 120, "priceMicros": 1210 },
    "latencyMs": 8420
  }
}
  • id identifies the event and stays the same when a delivery is retried or resent: use it to de-duplicate.
  • x-hevkar-delivery identifies the delivery.

Verify the signature ​

x-hevkar-signature is t=<unix seconds>,v1=<hex HMAC-SHA256> where the HMAC is computed with your endpoint secret over the string "<t>.<raw body>". Always verify against the raw request body, before parsing JSON, and reject old timestamps to prevent replays.

ts
import express from 'express';
import { webhooks, WebhookVerificationError } from '@hevkar/sdk';

const app = express();

app.post('/webhooks/hevkar', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = webhooks.verify(
      req.body,
      req.header('x-hevkar-signature'),
      process.env.HEVKAR_WEBHOOK_SECRET!,
    );
  } catch (err) {
    if (err instanceof WebhookVerificationError) return res.status(400).end();
    throw err;
  }

  if (alreadyProcessed(event.id)) return res.status(204).end();
  switch (event.event) {
    case 'run.completed':
    case 'run.failed':
      saveResult(event.data.runId, event.data.status, event.data.output, event.data.error);
      break;
    case 'run.waiting':
      notifyReviewer(event.data);
      break;
    case 'datasource.synced':
      console.log(event.data.stats);
      break;
  }
  res.status(204).end();
});
ts
import { createHmac, timingSafeEqual } from 'node:crypto';

/** Throws unless `header` is a valid signature of `rawBody` (a Buffer or string). */
export function verifyQaSignature(
  rawBody: Buffer | string,
  header: string | undefined,
  secret: string,
) {
  if (!header) throw new Error('missing signature');
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=', 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || !parts.v1) throw new Error('malformed signature');
  if (Math.abs(Date.now() / 1000 - t) > 300) throw new Error('timestamp outside tolerance');

  const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
  const received = Buffer.from(parts.v1, 'hex');
  if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
    throw new Error('invalid signature');
  }
  return JSON.parse(rawBody.toString());
}
ts
import { webhooks } from '@hevkar/sdk';

export default {
  async fetch(request: Request, env: { HEVKAR_WEBHOOK_SECRET: string }) {
    const raw = await request.text();
    const event = await webhooks.verifyAsync(
      raw,
      request.headers.get('x-hevkar-signature'),
      env.HEVKAR_WEBHOOK_SECRET,
    );
    // …
    return new Response(null, { status: 204 });
  },
};

webhooks.verify(rawBody, header, secret, { toleranceSec = 300 }) throws WebhookVerificationError (code INVALID_SIGNATURE) for a missing or malformed header, a wrong signature or a timestamp more than toleranceSec from now. The comparison is constant-time. For tests, webhooks.sign(rawBody, secret) produces a valid header.

Delivery and retries ​

  • Any 2xx response within 10 seconds counts as delivered. Respond quickly and do heavy work asynchronously.
  • Otherwise the delivery is retried, 8 attempts in total, with exponential backoff (10 s, 20 s, 40 s, … by default). Redirects are not followed.
  • Deliveries can arrive out of order and more than once: de-duplicate on id, and use GET /v1/runs/{id} if you need the latest state.
  • A delivery that failed every attempt is marked failed; resend it from the console.

Hevkar public API v1