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/sdkpnpm add @duun/sdkCreate 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.
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.
| Option | Default | Description |
|---|---|---|
apiKey | process.env.DUUN_API_KEY | API key (duun_sk_…). |
baseURL | https://api.duun.ai/v1 | API base URL. |
apiVersion | none | Sends Duun-Version, for example "2026-11-01", to pin a dated revision. |
maxRetries | 2 | Retries for 429 and 5xx responses and network errors, with exponential backoff. |
timeout | 60000 | Request timeout in milliseconds. |
fetch | global fetch | Custom 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 queuedRetrieve, 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:
kind | Actions |
|---|---|
approve_plan | approve, request_changes |
allow_command | allow_once, request_changes |
answer | answer (with answers) |
review_pr | merge, request_changes |
budget | approve_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:
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:
| Class | Status | When |
|---|---|---|
Duun.BadRequestError | 400 | invalid_request |
Duun.AuthenticationError | 401 | Missing, invalid or revoked key |
Duun.PermissionDeniedError | 403 | The key lacks a scope, or the action isn’t allowed |
Duun.NotFoundError | 404 | The id doesn’t exist in this workspace |
Duun.ConflictError | 409 | conflict or idempotency_error |
Duun.ValidationError | 422 | Has .problems for workflow configs |
Duun.RateLimitError | 429 | Has .retryAfter in seconds |
Duun.InternalServerError | 5xx | api_error, service_unavailable |
Duun.APIConnectionError | none | Network 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 APIduun.workflows—list,create,retrieve,diff,versions.create,versions.list,versions.retrieve,restore,test,pause,resume. Workflows APIduun.agents,duun.skills(withpublish),duun.commands. Agents, Skills, Commandsduun.webhookEndpoints(withrotateSecret,test,deliveries.list,deliveries.redeliver) andduun.triggerUrls. Webhook endpoints APIduun.usage.retrieve,duun.usage.credits(),duun.budgets.list(). Usage and budgets