Docs/TypeScript SDK (@nunc/sdk)
@nunc/sdk & EmbedNode.js · Bun · Deno · Edge · Browser Embed

TypeScript SDK & Web Embed

Build governed AI copilots, workflow automation, and isolated code sandboxes into your own software. Use @nunc/sdk on your server with a type="chat" Application key, or embed a published agent in any web app using short-lived nes_* session tokens.

Need deterministic backend-to-backend SaaS or SQL connector execution without an LLM in the loop? Use a type="service" Application on POST /service instead.

1. Install @nunc/sdk

bun add @nunc/sdk
# or
npm install @nunc/sdk

2. Register a Chat Application & scope end-users

  1. Open Console → Build → Applications, create an Application with Type set to chat, bind its default specialist agent, and mint a nunc_* key (keep this key on your server — never ship nunc_* keys to browsers).
  2. Call nunc.asExternalUser(id) for multi-user apps. The SDK sends X-Nunc-External-User, which isolates conversation threads, semantic memory, and per-user throttles under ext:app_<hex>:<sub>:
import { createNuncClient, NuncError } from "@nunc/sdk";

// Server-side only — register an Application with type="chat" in Console -> Build -> Applications
const nunc = createNuncClient({
  baseUrl: "https://api.nunc.cloud",
  auth: { bearer: process.env.NUNC_CHAT_APP_KEY! },
});

// Scope conversation history, memory, and rate limits to a customer end-user (ext:app_<hex>:usr_94810)
const userClient = nunc.asExternalUser("usr_94810");

3. Stream chat completions, tool calls & artifacts

userClient.chat.stream() yields typed ChatEvent frames including assistant tokens, reasoning traces, governed tool executions, structured canvas artifacts, and the resolved conversation ID:

for await (const event of userClient.chat.stream({
  messages: [
    {
      role: "user",
      content: "Summarize Q3 ARR churn by segment and flag renewals at risk.",
    },
  ],
  mode: "work",
})) {
  switch (event.type) {
    case "token":
      process.stdout.write(event.text);
      break;
    case "tool":
      console.log(`[tool:${event.status}] ${event.name}`, event.summary ?? "");
      break;
    case "artifact":
      console.log("Structured artifact:", event.artifactType, event.data);
      break;
    case "done":
      console.log("\nConversation ID:", event.conversationId);
      break;
  }
}

4. Run workflows, step approvals & isolated sandboxes

// 1. Start a durable workflow run and approve a human-gated write step
const run = await nunc.workflows.runs.start({
  scope: "Reconcile overdue Q3 invoices and draft reminders",
});

await nunc.workflows.runs.approveStep(
  run.id,
  "step_send_intacct_dunning",
  "Reviewed by Finance Controller",
);

// 2. Stage a CSV and execute Python inside an isolated container (24h auto-purge)
const { key } = await nunc.sandbox.stageUpload({
  name: "cohorts.csv",
  data: csvBytes,
});

const result = await nunc.sandbox.execute({
  language: "python",
  stdin: csvText,
  code: "import io, sys, pandas as pd\ndf = pd.read_csv(io.StringIO(sys.stdin.read()))\nprint(df.describe())",
});

5. SDK namespaces & formatting helpers

Namespace / ExportKey MethodsPurpose
nunc.chatstream, complete, resume, listConversations, getConversationGoverned chat turns, tool approval resumption, conversation history
nunc.workflows / runslist, run, schedule, runs.start, runs.approveStep, runs.rejectStepDurable workflow templates, scheduled jobs, and step-level human approval gates
nunc.sandboxexecute, eval, stageUpload, stageDownload, statusIsolated Python, TypeScript, and JavaScript execution with 24h auto-purged file staging
nunc.memory & nunc.knowledgememory.search, memory.ingest, knowledge.ingest, knowledge.sources, knowledge.listFilesPublic, Company, Workspace, and Agent semantic memory and document retrieval
nunc.subagentsspawnStream, spawn, fanOut, synthesize (plus createSubagentEngine)Parallel specialist delegation and map-reduce synthesis with shared parent guardrails
@nunc/sdk UI helperscreateChatVisualizer, formatHtmlDecisionCard, formatHtmlBarChart, formatChartToMarkdownRender charts, tables, and approval cards in Slack, HTML, or CLI surfaces
@nunc/formatsparseNuncFormatTags, exportTableToCsv, generatePptxBlob, generateXlsxBlob, exportDocumentToWord, printDocumentPdfParse structured Nunc canvas tags and export decks, sheets, documents, and PDFs

6. Publish a browser Web Embed (embed.js & /e/:slug)

  1. In Console → Build → Applications, publish your chat Application, set exact allowed_origins (enforced via HTTP Content-Security-Policy: frame-ancestors), and copy the HMAC embed signing secret.
  2. On your backend, sign a short-lived identity JWT for the logged-in customer user and exchange it at POST /e/:slug/session for a 24-hour nes_<hex> session token (valid only on POST /chat/completions):
// Backend route: exchange your signed user claim for a 24h nes_<hex> embed token
const sessionRes = await fetch("https://api.nunc.cloud/e/customer-concierge/session", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ identityToken: signedHostHmacJwt }),
});
const { sessionToken } = await sessionRes.json(); // "nes_..." (chat-only, 24h TTL)

Load embed.js on an allowed origin and pass the nes_* session token:

<script
  src="https://api.nunc.cloud/embed.js"
  data-slug="customer-concierge"
  defer
></script>
<script>
  window.addEventListener("load", () => {
    window.NuncEmbed?.identify({
      token: "<nes_session_token_from_your_backend>",
    });
  });
</script>