TypeScript SDK

Use @duun/sdk to start and follow runs, resolve asks, apply workflow versions and verify webhooks from Node.js, Bun, Deno or edge runtimes.

On this page

@duun/sdk is the official TypeScript client for the Duun API. It’s fully typed, pages through lists for you, retries safely, and verifies webhook signatures. It runs on Node.js 20+, Bun, Deno and edge runtimes that support fetch and Web Crypto.

Install

npm install @duun/sdk
pnpm add @duun/sdk

Create a client

Create an API key in Settings → API keys & secrets → Duun API keys with the scopes your code needs, and keep it in an environment variable.

duun.ts
import Duun from "@duun/sdk";

export const duun = new Duun({
  apiKey: process.env.DUUN_API_KEY, // duun_sk_…
});

apiKey defaults to process.env.DUUN_API_KEY, so new Duun() works when the variable is set. Never create a client in browser code: the key acts as your workspace.

OptionDefaultDescription
apiKeyprocess.env.DUUN_API_KEYAPI key (duun_sk_…).
baseURLhttps://api.duun.ai/v1API base URL.
apiVersionnoneSends Duun-Version, for example "2026-11-01", to pin a dated revision.
maxRetries2Retries for 429 and 5xx responses and network errors, with exponential backoff.
timeout60000Request timeout in milliseconds.
fetchglobal fetchCustom fetch implementation, for proxies or tests.

Start a run

runs.create starts a run in a factory and returns the run object. The factory’s default workflow is used unless you pass workflow_id.

const run = await duun.runs.create({
  factory_id: "fac_platform",
  prompt: "Add idempotency keys to refund webhooks",
  issue_url: "https://linear.app/acme/issue/PLT-482",
  inputs: { priority: "urgent" },
});

console.log(run.id, run.status); // run_7f3aK2pQ queued

Retrieve, pause, resume, restart and cancel by id:

const latest = await duun.runs.retrieve("run_7f3aK2pQ");

await duun.runs.pause("run_7f3aK2pQ");   // after the current step
await duun.runs.resume("run_7f3aK2pQ");
await duun.runs.cancel("run_7f3aK2pQ");  // worktree and thread are kept
await duun.runs.restart("run_7f3aK2pQ");

List and paginate

List methods return a page object that is also an async iterable. Iterating fetches further pages as you go, so you never handle cursors yourself.

for await (const run of duun.runs.list({ status: "waiting", factory_id: "fac_platform" })) {
  console.log(`${run.id} is waiting on: ${run.ask?.title}`);
}

To work page by page, use the page object directly:

let page = await duun.runs.list({ limit: 50 });
console.log(page.data.length, page.has_more);

while (page.has_more) {
  page = await page.nextPage();
  console.log(page.data.length);
}

limit is 1–100 and defaults to 20. See Pagination, errors and limits.

Stream logs

runs.logs with follow: true keeps the connection open and yields log lines until the run finishes. Without follow, it returns the log so far.

for await (const line of duun.runs.logs("run_7f3aK2pQ", { follow: true })) {
  console.log(`${line.at}  ${line.step.padEnd(10)} ${line.text}`);
}

Filter to one step with step: "implement", or start from a time with since. Break out of the loop to close the stream.

Resolve asks

When a run is waiting, its ask says what it needs. Resolve it with the action that matches the ask’s kind:

kindActions
approve_planapprove, request_changes
allow_commandallow_once, request_changes
answeranswer (with answers)
review_prmerge, request_changes
budgetapprove_once (with amount_usd), stop
const run = await duun.runs.retrieve("run_7f3aK2pQ");

if (run.ask?.kind === "approve_plan") {
  await duun.runs.asks.resolve(run.id, run.ask.id, {
    action: "request_changes",
    note: "Make the backfill a dry run first; finance reconciles on Mondays.",
  });
}

Resolving through the API counts as the key’s workspace, and the resolution shows in the run’s conversation and in the ask.resolved webhook. Approvals still follow your workspace’s Action approvals settings.

Apply a workflow version

Workflows are versioned. To change one, send the full config with the revision you based it on. If someone applied a newer version in the meantime, the API answers 409 and the SDK throws ConflictError.

import Duun from "@duun/sdk";

const workflow = await duun.workflows.retrieve("wf_base9c1d");
const config = structuredClone(workflow.config);
config.limits.budget_usd = 10;

// Check first: returns the changes and any problems, applies nothing.
const { changes, problems } = await duun.workflows.diff(workflow.id, { config });
if (problems.some((p) => p.severity === "error")) throw new Error(problems[0].message);

try {
  const version = await duun.workflows.versions.create(workflow.id, {
    config,
    expected_revision: workflow.live_revision,
    label: "Raise budget to $10",
  });
  console.log(`Applied v${version.revision}`);
} catch (err) {
  if (err instanceof Duun.ConflictError) {
    // Someone applied a newer version. Fetch it, re-apply your change, try again.
    console.warn(err.message);
  } else if (err instanceof Duun.ValidationError) {
    for (const p of err.problems) console.error(`${p.step_id ?? "workflow"}: ${p.message}`);
  } else {
    throw err;
  }
}

Roll back with duun.workflows.restore(id, { revision: 3, expected_revision }) and test with duun.workflows.test(id, { mode: "dry" }). See Versions and rollback and Test runs.

Verify webhooks

duun.webhooks.constructEvent checks the X-Duun-Signature header against the raw body and your endpoint’s signing secret, enforces the 300-second tolerance, and returns the typed event. It uses Web Crypto and works in edge runtimes. Here it is in a Next.js route handler:

app/api/duun/webhooks/route.ts
import Duun from "@duun/sdk";

const duun = new Duun();

export async function POST(request: Request) {
  const rawBody = await request.text(); // raw, not request.json()
  let event: Duun.WebhookEvent;
  try {
    event = await duun.webhooks.constructEvent(
      rawBody,
      request.headers.get("x-duun-signature"),
      process.env.DUUN_WEBHOOK_SECRET!,
    );
  } catch (err) {
    if (err instanceof Duun.WebhookSignatureError) {
      return new Response("Invalid signature", { status: 400 });
    }
    throw err;
  }

  switch (event.type) {
    case "run.waiting":
      // event.data.object is typed as Duun.Run here
      console.log(`${event.data.object.id} needs: ${event.data.object.ask?.title}`);
      break;
    case "pr.merged":
      console.log(`Merged #${event.data.object.number}`);
      break;
  }
  return new Response(null, { status: 200 });
}

constructEvent is async in edge runtimes and on Node.js alike. The verification page explains the scheme if you want to implement it yourself.

Errors

Every API error is thrown as a subclass of Duun.APIError, with the fields from the error object:

ClassStatusWhen
Duun.BadRequestError400invalid_request
Duun.AuthenticationError401Missing, invalid or revoked key
Duun.PermissionDeniedError403The key lacks a scope, or the action isn’t allowed
Duun.NotFoundError404The id doesn’t exist in this workspace
Duun.ConflictError409conflict or idempotency_error
Duun.ValidationError422Has .problems for workflow configs
Duun.RateLimitError429Has .retryAfter in seconds
Duun.InternalServerError5xxapi_error, service_unavailable
Duun.APIConnectionErrornoneNetwork failure or timeout
try {
  await duun.runs.retrieve("run_doesnotexist");
} catch (err) {
  if (err instanceof Duun.APIError) {
    console.error(err.status, err.type, err.code, err.message, err.requestId);
  }
}

Include err.requestId (req_…) when you contact support.

Retries and idempotency

The client retries 429, 5xx and connection errors up to maxRetries times with exponential backoff, and honours Retry-After. Every POST gets an Idempotency-Key automatically, and retries reuse it, so a retried runs.create never starts two runs.

To make a call idempotent across processes, for example when a job queue may deliver the same message twice, pass your own key:

await duun.runs.create(
  { factory_id: "fac_platform", issue_url: "https://linear.app/acme/issue/PLT-482" },
  { idempotencyKey: `linear-PLT-482-ready`, maxRetries: 5, timeout: 20_000 },
);

Keys are remembered for 24 hours. Reusing a key with a different body throws ConflictError with type idempotency_error.

Types

All request params, resources and events are exported as types under the Duun namespace:

import Duun from "@duun/sdk";

function summarize(run: Duun.Run): string {
  return `${run.title} · ${run.status} · $${run.cost.spent_usd.toFixed(2)}`;
}

const params: Duun.RunCreateParams = { factory_id: "fac_platform", prompt: "Fix the flaky settlement test" };
type Step = Duun.WorkflowStep; // discriminated union on `kind`

Duun.WebhookEvent is a discriminated union on type, so narrowing on event.type gives you the right data.object type.

Other resources

The client mirrors the API reference one to one:

  • duun.factories — list, create, retrieve, update, pause, resume, archive. Factories API
  • duun.workflows — list, create, retrieve, diff, versions.create, versions.list, versions.retrieve, restore, test, pause, resume. Workflows API
  • duun.agents, duun.skills (with publish), duun.commands. Agents, Skills, Commands
  • duun.webhookEndpoints (with rotateSecret, test, deliveries.list, deliveries.redeliver) and duun.triggerUrls. Webhook endpoints API
  • duun.usage.retrieve, duun.usage.credits(), duun.budgets.list(). Usage and budgets

    Type to search the docs, help center and blog.