@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/sdk2. Register a Chat Application & scope end-users
- Open Console → Build → Applications, create an Application with Type set to
chat, bind its default specialist agent, and mint anunc_*key (keep this key on your server — never shipnunc_*keys to browsers). - Call
nunc.asExternalUser(id)for multi-user apps. The SDK sendsX-Nunc-External-User, which isolates conversation threads, semantic memory, and per-user throttles underext: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 / Export | Key Methods | Purpose |
|---|---|---|
| nunc.chat | stream, complete, resume, listConversations, getConversation | Governed chat turns, tool approval resumption, conversation history |
| nunc.workflows / runs | list, run, schedule, runs.start, runs.approveStep, runs.rejectStep | Durable workflow templates, scheduled jobs, and step-level human approval gates |
| nunc.sandbox | execute, eval, stageUpload, stageDownload, status | Isolated Python, TypeScript, and JavaScript execution with 24h auto-purged file staging |
| nunc.memory & nunc.knowledge | memory.search, memory.ingest, knowledge.ingest, knowledge.sources, knowledge.listFiles | Public, Company, Workspace, and Agent semantic memory and document retrieval |
| nunc.subagents | spawnStream, spawn, fanOut, synthesize (plus createSubagentEngine) | Parallel specialist delegation and map-reduce synthesis with shared parent guardrails |
| @nunc/sdk UI helpers | createChatVisualizer, formatHtmlDecisionCard, formatHtmlBarChart, formatChartToMarkdown | Render charts, tables, and approval cards in Slack, HTML, or CLI surfaces |
| @nunc/formats | parseNuncFormatTags, exportTableToCsv, generatePptxBlob, generateXlsxBlob, exportDocumentToWord, printDocumentPdf | Parse structured Nunc canvas tags and export decks, sheets, documents, and PDFs |
6. Publish a browser Web Embed (embed.js & /e/:slug)
- In Console → Build → Applications, publish your
chatApplication, set exactallowed_origins(enforced via HTTPContent-Security-Policy: frame-ancestors), and copy the HMAC embed signing secret. - On your backend, sign a short-lived identity JWT for the logged-in customer user and exchange it at
POST /e/:slug/sessionfor a 24-hournes_<hex>session token (valid only onPOST /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>