@happyrobot-ai/sdk

中文文档
0.2.9发布于 2026/11/17MITTypeScriptESM + CJS零依赖近 30 天下载 7752

TypeScript SDK for the HappyRobot Public API

原始使用文档
文档目录53 节
  1. Installation
  2. Quick Start
  3. Configuration
  4. Helpers
  5. triggerAndWait
  6. createVoiceAgent
  7. createFromTemplate
  8. Resources
  9. client.workflows
  10. client.versions
  11. client.nodes
  12. client.runs
  13. client.sessions
  14. client.messages
  15. client.artifacts
  16. client.variables
  17. client.phoneNumbers
  18. client.sipTrunks
  19. client.integrations
  20. client.contacts
  21. client.knowledgeBases
  22. client.workflowFolders
  23. client.mcp
  24. client.billing
  25. client.apiKey
  26. Native scenarios and retained history
  27. client.northstars
  28. client.customEvals
  29. client.nodeTests
  30. Tests on branches: client.branches.*
  31. client.issues
  32. client.auditRemarks
  33. Client access tokens ( client.tokens )
  34. Chat ( client.chat + HappyRobotChatClient )
  35. Server-side: Create a client token
  36. Browser-side: HappyRobotChatClient
  37. Browser-side: File uploads
  38. HappyRobotClient (server-side)
  39. HappyRobotChatClient (browser-side)
  40. ChatConnection
  41. WebSocket Events
  42. Token refresh
  43. Voice ( client.voice + HappyRobotVoiceClient )
  44. Server-side: Create a voice token
  45. Browser-side: HappyRobotVoiceClient
  46. HappyRobotClient (server-side)
  47. HappyRobotVoiceClient (browser-side)
  48. VoiceConnection
  49. VoiceListenerConnection
  50. Room Events
  51. Pagination
  52. Error Handling
  53. Shared test suites

@happyrobot-ai/sdk

TypeScript SDK for the HappyRobot Public API.

Installation

npm install @happyrobot-ai/sdk
# or
pnpm add @happyrobot-ai/sdk
# or
yarn add @happyrobot-ai/sdk

Optional: If you plan to use HappyRobotVoiceClient (imported from @happyrobot-ai/sdk/voice) for browser-side voice calls, also install livekit-client:

npm install livekit-client
# or
pnpm add livekit-client
# or
yarn add livekit-client

This is only needed for voice — all other SDK features work without it.

Quick Start

import { HappyRobotClient } from "@happyrobot-ai/sdk";

const client = new HappyRobotClient({ apiKey: "sk_live_..." });

// List workflows
const { data } = await client.workflows.list();

// Trigger a run
const { run_id } = await client.workflows.triggerRun("my-workflow", {
  payload: { phone: "+1234567890" },
});

Configuration

const client = new HappyRobotClient({
  apiKey: "sk_live_...", // Required. API key (sk_live_... or sk_test_...)
  cluster: "eu", // Optional. "us" (default) or "eu"
  timeout: 30_000, // Optional. Request timeout in ms. Defaults to 30000
  maxRetries: 2, // Optional. Retries on 429/5xx with exponential backoff. Defaults to 2
  fetch: customFetch, // Optional. Custom fetch implementation
});

Helpers

High-level convenience functions available via @happyrobot-ai/sdk/helpers.

triggerAndWait

Trigger a workflow run and poll until it reaches a terminal status.

import { triggerAndWait } from "@happyrobot-ai/sdk/helpers";

const { run, sessions } = await triggerAndWait(client, {
  workflowId: "my-workflow",
  payload: { phone: "+1234567890" },
  timeoutMs: 300_000, // Optional. Defaults to 5 minutes
  pollIntervalMs: 2_000, // Optional. Defaults to 2 seconds
  fetchSessions: true, // Optional. Fetch sessions on completion. Defaults to true
  environment: "production", // Optional. Defaults to "production"
});

console.log(run.status); // "completed" | "failed" | "canceled" | ...

createVoiceAgent

Create a voice agent workflow from a template with optional publishing.

import { createVoiceAgent } from "@happyrobot-ai/sdk/helpers";

const { workflow, publishResult } = await createVoiceAgent(client, {
  name: "Sales Agent",
  template: "voice-agent", // "voice-agent" (outbound) or "inbound-voice-agent"
  prompt: "You are a helpful sales assistant...",
  initialMessage: "Hi, how can I help you today?",
  publish: true,
  environment: "production",
  folderId: "folder-id", // Optional
});

createFromTemplate

Create any workflow from a template with custom inputs.

import { createFromTemplate } from "@happyrobot-ai/sdk/helpers";

const { workflow } = await createFromTemplate(client, {
  template: "voice-agent",
  name: "My Agent",
  inputs: { agent_name: "My Agent" },
  publish: false,
});

Resources

PropertyClassDescription
client.workflowsWorkflowsResourceWorkflow CRUD, publishing, runs, and templates
client.versionsVersionsResourceVersion management (fork, publish, lock, test)
client.nodesNodesResourceNode CRUD, config schema, and available variables
client.runsRunsResourceRun details, cancellation, and annotations
client.sessionsSessionsResourceSession details, messages, and SSE streaming
client.messagesMessagesResourceMessage quality flags
client.variablesVariablesResourceWorkflow-scoped variables
client.phoneNumbersPhoneNumbersResourcePhone number management
client.sipTrunksSipTrunksResourceSIP trunk management
client.integrationsIntegrationsResourceIntegration and event discovery
client.contactsContactsResourceContact lookup and history
client.knowledgeBasesKnowledgeBasesResourceKnowledge base document management
client.workflowFoldersWorkflowFoldersResourceWorkflow folder organization
client.mcpMCPResourceMCP server management
client.billingBillingResourceBilling usage details and totals
client.apiKeyApiKeyResourceAPI key introspection
client.artifactsArtifactsResourceResolve authorized artifact download URLs
client.adversarialSuitesAdversarialSuitesResourceRetained adversarial suite history
client.adversarialTestsAdversarialTestsResourceRetained adversarial test history
client.northstarsNorthstarsResourceNorthstar quality criteria management
client.customEvalsCustomEvalsResourceCustom eval management and execution
client.nodeTestsNodeTestsResourceSaved node tests and run history
client.issuesIssuesResourceQuality issue (flag) status management
client.auditRemarksAuditRemarksResourceAudit remark feedback management
client.chatChatResourceChat session management, messaging, and file uploads
client.voiceVoiceResourceVoice catalog lookup and call token creation

client.workflows

// List workflows (paginated)
const { data, pagination } = await client.workflows.list({ page: 1, limit: 20 });

// Iterate all workflows across pages
for await (const wf of client.workflows.listAll()) { ... }

// Create a workflow
const wf = await client.workflows.create({ name: "My Workflow" });

// Get by ID or slug
const wf = await client.workflows.get("my-workflow");

// Update
await client.workflows.update("my-workflow", { name: "New Name" });

// Delete
await client.workflows.delete("my-workflow");

// Duplicate
await client.workflows.duplicate("my-workflow", { name: "Copy" });

// Publish / unpublish
await client.workflows.publish("my-workflow");
await client.workflows.unpublish("my-workflow");

// Cancel current and queued runs. By default, this also unpublishes the workflow.
await client.workflows.cancelRuns("my-workflow");
await client.workflows.cancelRuns("my-workflow", { unpublish_workflow: false });

// List templates
const { data } = await client.workflows.listTemplates();

// List versions
const { data } = await client.workflows.listVersions("my-workflow");

// List runs
const { data } = await client.workflows.listRuns("my-workflow");

// List sessions across all runs
const { data: sessions } = await client.workflows.listSessions("my-workflow");

// Trigger a run
const { run_id } = await client.workflows.triggerRun("my-workflow", { payload: { phone: "+1..." } });
MethodHTTPPathDescription
list(query?)GET/workflowsList workflows, paginated
listAll(query?)GET/workflowsAsync generator over all pages
create(body)POST/workflowsCreate a new workflow
get(workflowId)GET/workflows/:idGet workflow by ID or slug
update(workflowId, body)PATCH/workflows/:idUpdate name, description, etc.
delete(workflowId)DELETE/workflows/:idDelete a workflow
duplicate(workflowId, body?)POST/workflows/:id/duplicateDuplicate a workflow
publish(workflowId, body?)POST/workflows/:id/publishPublish the latest version
unpublish(workflowId)POST/workflows/:id/unpublishUnpublish a workflow
cancelRuns(workflowId, body?)POST/workflows/:id/cancel-runsCancel current and queued runs
listTemplates(query?)GET/workflows/templatesList workflow templates
listVersions(workflowId, query?)GET/workflows/:id/versionsList versions for a workflow
listRuns(workflowId, query?)GET/workflows/:id/runsList runs for a workflow
listSessions(workflowId, query?)GET/workflows/:id/sessionsList sessions for a workflow
triggerRun(workflowId, body?)POST/workflows/:id/runsTrigger a new run

client.versions

const version = await client.versions.get("version-id");
await client.versions.update("version-id", { name: "v2" });
await client.versions.fork("version-id");
await client.versions.publish("version-id");
await client.versions.unpublish("version-id");
await client.versions.lock("version-id");
await client.versions.unlock("version-id");
await client.versions.testAll("version-id");
const issues = await client.versions.getPromptIssues("version-id");
MethodHTTPPathDescription
get(versionId)GET/versions/:idGet version with node summary and changelog
update(versionId, body)PATCH/versions/:idUpdate name or description
fork(versionId)POST/versions/:id/forkClone a version
publish(versionId, body?)POST/versions/:id/publishPublish a version
unpublish(versionId)POST/versions/:id/unpublishUnpublish a version
lock(versionId)POST/versions/:id/lockLock a version (prevent edits)
unlock(versionId)POST/versions/:id/unlockUnlock a version
testAll(versionId)POST/versions/:id/test-allRun test-all validation
getPromptIssues(versionId)GET/versions/:id/prompt-issuesGet prompt quality issues for all prompt nodes

client.nodes

Nodes are always scoped to a version.

const nodes = await client.nodes.list("version-id");
await client.nodes.addBatch("version-id", { nodes: [...] });
const node = await client.nodes.get("version-id", "node-id");
await client.nodes.update("version-id", "node-id", { config: { ... } });
await client.nodes.delete("version-id", "node-id");
const schema = await client.nodes.getConfigSchema("version-id", "node-id");
const vars = await client.nodes.getAvailableVars("version-id", "node-id");
const result = await client.nodes.test("version-id", "node-id");

Groups returned by getAvailableVars can include is_list: true. That means variables in the group resolve as arrays outside their loop. Sequential and parallel loops both return arrays; a single iteration returns a one-item array.

MethodHTTPPathDescription
list(versionId)GET/versions/:vId/nodesList all nodes in a version
addBatch(versionId, body)POST/versions/:vId/nodesAdd nodes in batch (1–50)
get(versionId, nodeId)GET/versions/:vId/nodes/:nIdGet a single node
update(versionId, nodeId, body)PUT/versions/:vId/nodes/:nIdUpdate a node
delete(versionId, nodeId)DELETE/versions/:vId/nodes/:nIdDelete a node
getConfigSchema(versionId, nodeId)GET/versions/:vId/nodes/:nId/config-schemaGet field types and requirements
getAvailableVars(versionId, nodeId)GET/versions/:vId/nodes/:nId/available-varsGet upstream variables available to this node
test(versionId, nodeId, body?)POST/versions/:vId/nodes/:nId/testTest a single node (version must not be published)

client.runs

const run = await client.runs.get("run-id");
const sessions = await client.runs.getSessions("run-id");
const recordings = await client.runs.getRecordings("run-id");
const flags = await client.runs.getFlags("run-id");
await client.runs.cancel("run-id");
await client.runs.mark("run-id", { annotation: "correct" });
MethodHTTPPathDescription
get(runId)GET/runs/:idGet run details
getSessions(runId, query?)GET/runs/:id/sessionsGet sessions for a run
getRecordings(runId)GET/runs/:id/recordingsGet recordings for a run
getFlags(runId, query?)GET/runs/:id/flagsGet quality flags for a run
cancel(runId)POST/runs/:id/cancelCancel a run
mark(runId, body)POST/runs/:id/markAnnotate a run (correct / incorrect / critical)

client.sessions

const session = await client.sessions.get("session-id");
const { data } = await client.sessions.getMessages("session-id");

// SSE streaming
for await (const event of await client.sessions.stream("session-id")) {
  if (event.event === "message")
    console.log(event.data.role, event.data.content);
  if (event.event === "session_ended") break;
}
MethodHTTPPathDescription
get(sessionId)GET/sessions/:idGet session details
getMessages(sessionId, query?)GET/sessions/:id/messagesGet paginated messages for a session
stream(sessionId, query?)GET/sessions/:id/streamOpen SSE stream of session messages

client.messages

const { data } = await client.messages.listFlags("message-id");
await client.messages.createFlag("message-id", {
  type: "incorrect",
  note: "...",
});
MethodHTTPPathDescription
listFlags(messageId, query?)GET/messages/:id/flagsList quality flags for a message
createFlag(messageId, body)POST/messages/:id/flagsCreate a quality flag on a message

client.artifacts

const resolved = await client.artifacts.createDownloadUrls({
  artifacts: [
    {
      message_id: "message-id-from-the-session-messages-response",
      s3_key: "artifacts/<media_id>/extracted_text.txt",
    },
  ],
});
MethodHTTPPathDescription
createDownloadUrls(body)POST/artifacts/download-urlsResolve authorized artifact URLs with provenance
resolve(body)POST/artifacts/resolveDeprecated; sunsets October 15, 2026 at 12:00 UTC

client.variables

Variables are scoped to a workflow.

const { data } = await client.variables.list("workflow-id");
await client.variables.create("workflow-id", {
  name: "MY_VAR",
  value: "hello",
});
await client.variables.update("workflow-id", "variable-id", { value: "world" });
await client.variables.delete("workflow-id", "variable-id");
MethodHTTPPathDescription
list(workflowId, query?)GET/workflows/:wId/variablesList variables for a workflow
create(workflowId, body)POST/workflows/:wId/variablesCreate a variable
update(workflowId, variableId, body)PATCH/workflows/:wId/variables/:vIdUpdate a variable
delete(workflowId, variableId)DELETE/workflows/:wId/variables/:vIdDelete a variable

client.phoneNumbers

const numbers = await client.phoneNumbers.list();
await client.phoneNumbers.buy({ area_code: "415" });
await client.phoneNumbers.update("id", { name: "Main Line" });
await client.phoneNumbers.getUsage("id");
await client.phoneNumbers.freeUp("id");
await client.phoneNumbers.delete("id");
await client.phoneNumbers.removeFromWorkflow("id", { use_case_id: "..." });
await client.phoneNumbers.getTollFreeVerification("id");
await client.phoneNumbers.createTollFreeVerification("id", { ... });
await client.phoneNumbers.deleteTollFreeVerification("verification-sid");
await client.phoneNumbers.createSipTrunk("id");
await client.phoneNumbers.validateTollFreeNumbers({ phone_numbers: [...] });
MethodHTTPPathDescription
list(query?)GET/phone-numbersList all phone numbers
buy(body)POST/phone-numbersPurchase a new phone number
update(id, body)PUT/phone-numbers/:idUpdate name or caller ID
getUsage(id)GET/phone-numbers/:id/usageGet usage info
getTollFreeVerification(id)GET/phone-numbers/:id/tollfree-verificationGet toll-free verification status
createTollFreeVerification(id, body)POST/phone-numbers/:id/tollfree-verificationStart toll-free verification
deleteTollFreeVerification(verificationSid)DELETE/phone-numbers/tollfree-verification/:sidDelete a toll-free verification
createSipTrunk(id)POST/phone-numbers/:id/sip-trunkCreate a SIP trunk for a number
freeUp(id)POST/phone-numbers/:id/free-up-numberRelease a number from workflows
delete(id)POST/phone-numbers/:id/delete-numberPermanently delete a number
removeFromWorkflow(id, body)POST/phone-numbers/:id/remove-from-workflowRemove from a specific workflow
validateTollFreeNumbers(body)POST/phone-numbers/validate-toll-free-numbersCheck for conflicts

client.sipTrunks

const trunks = await client.sipTrunks.list();
const options = await client.sipTrunks.listOptions();
await client.sipTrunks.create({ name: "Main Trunk", ... });
await client.sipTrunks.createBulk({ trunks: [...] });
const trunk = await client.sipTrunks.get("trunk-id");
await client.sipTrunks.update("trunk-id", { name: "Updated" });
await client.sipTrunks.delete("trunk-id");
MethodHTTPPathDescription
list()GET/sip-trunksList all SIP trunks
listOptions()GET/sip-trunks/optionsLightweight list of trunk options
create(body)POST/sip-trunksCreate a SIP trunk
createBulk(body)POST/sip-trunks/bulkCreate multiple SIP trunks
get(trunkId)GET/sip-trunks/:idGet a SIP trunk
update(trunkId, body)PUT/sip-trunks/:idUpdate a SIP trunk
delete(trunkId)DELETE/sip-trunks/:idDelete a SIP trunk

client.integrations

const integrations = await client.integrations.list();
const integration = await client.integrations.get("integration-id");
await client.integrations.createCredential("integration-id", { name: "My Creds", fields: { ... } });

// Integration-specific sub-resources
await client.integrations.googleSheets.spreadsheets();
await client.integrations.googleSheets.worksheets({ spreadsheet_id: "..." });
await client.integrations.googleSheets.columns({ spreadsheet_id: "...", worksheet_id: "..." });
await client.integrations.googleSheets.rows({ spreadsheet_id: "...", worksheet_id: "..." });

await client.integrations.slack.channels();
await client.integrations.slack.users();

await client.integrations.teams.teams();
await client.integrations.teams.channels();
await client.integrations.teams.users();

await client.integrations.twilioSms.phoneNumbers();

await client.integrations.whatsApp.businesses({ credential_id: "..." });
await client.integrations.whatsApp.businessAccounts({ credential_id: "...", business_id: "..." });
await client.integrations.whatsApp.phoneNumbers({ credential_id: "...", business_account_id: "..." });
await client.integrations.whatsApp.messageTemplates({ credential_id: "...", business_account_id: "..." });
MethodHTTPPathDescription
list(query?)GET/integrationsList all integrations
get(id)GET/integrations/:idGet integration and its events
createCredential(id, body)POST/integrations/:id/create-credentialCreate a credential for a form-based integration
googleSheets.spreadsheets(query?)GET/integrations/google-sheets/spreadsheetsList spreadsheets
googleSheets.worksheets(query)GET/integrations/google-sheets/worksheetsList worksheets in a spreadsheet
googleSheets.columns(query)GET/integrations/google-sheets/columnsList columns in a worksheet
googleSheets.rows(query)GET/integrations/google-sheets/rowsList rows in a worksheet
slack.channels(query?)GET/integrations/slack/channelsList Slack channels
slack.users(query?)GET/integrations/slack/usersList Slack users
teams.teams(query?)GET/integrations/teams/teamsList Microsoft Teams teams
teams.channels(query?)GET/integrations/teams/channelsList Microsoft Teams channels
teams.users(query?)GET/integrations/teams/usersList Microsoft Teams users
twilioSms.phoneNumbers(query?)GET/integrations/twilio-sms/phone-numbersList Twilio SMS numbers
whatsApp.businesses(query)GET/integrations/whatsapp/businessesList WhatsApp businesses
whatsApp.businessAccounts(query)GET/integrations/whatsapp/business-accountsList WhatsApp business accounts
whatsApp.phoneNumbers(query)GET/integrations/whatsapp/phone-numbersList WhatsApp phone numbers
whatsApp.messageTemplates(query)GET/integrations/whatsapp/message-templatesList WhatsApp message templates

client.contacts

const { data } = await client.contacts.list({ search: "John" });
const contact = await client.contacts.resolve({ phone_number: "+14155551234" });
const contact = await client.contacts.get("contact-id");
const interactions = await client.contacts.getInteractions("contact-id");
const memories = await client.contacts.getMemories("contact-id");
MethodHTTPPathDescription
list(query?)GET/contactsList contacts (cursor-paginated)
resolve(query)GET/contacts/resolveLook up a contact by phone number or email
get(contactId)GET/contacts/:idGet contact by ID
getInteractions(contactId)GET/contacts/:id/interactionsGet call/message history for a contact
getMemories(contactId)GET/contacts/:id/memoriesGet AI memories for a contact

client.knowledgeBases

const kbs = await client.knowledgeBases.list();
const files = await client.knowledgeBases.listFiles("kb-id");
const urls = await client.knowledgeBases.getUploadUrls("kb-id", {
  files: [{ name: "doc.pdf", content_type: "application/pdf" }],
});
await client.knowledgeBases.triggerChunking("kb-id");
await client.knowledgeBases.deleteFile("kb-id", "file-id");
await client.knowledgeBases.delete("kb-id");
MethodHTTPPathDescription
list()GET/knowledge-basesList all knowledge bases
listFiles(kbId)GET/knowledge-bases/:id/filesList documents in a knowledge base
getUploadUrls(kbId, body)POST/knowledge-bases/:id/upload-urlsGet pre-signed S3 upload URLs
triggerChunking(kbId)POST/knowledge-bases/:id/trigger-chunkingStart document processing/chunking
deleteFile(kbId, fileId)DELETE/knowledge-bases/:id/files/:fileIdDelete a file from a knowledge base
delete(kbId)DELETE/knowledge-bases/:idDelete a knowledge base

client.workflowFolders

const { data } = await client.workflowFolders.list();
await client.workflowFolders.create({ name: "Production" });
const folder = await client.workflowFolders.get("folder-id");
await client.workflowFolders.update("folder-id", { name: "Updated" });
await client.workflowFolders.delete("folder-id");
MethodHTTPPathDescription
list(query?)GET/workflow-foldersList folders (paginated)
create(body)POST/workflow-foldersCreate a folder
get(folderId)GET/workflow-folders/:idGet a folder
update(folderId, body)PUT/workflow-folders/:idUpdate a folder
delete(folderId)DELETE/workflow-folders/:idDelete a folder

client.mcp

const { data } = await client.mcp.list();
await client.mcp.create({ name: "My MCP", url: "https://..." });
await client.mcp.refresh("mcp-id");
MethodHTTPPathDescription
list(query?)GET/mcpList MCP servers (paginated)
create(body)POST/mcpRegister a new MCP server
refresh(mcpId)POST/mcp/:id/refreshRe-discover tools for an MCP server

OAuth2 (auth_type: "oauth2"): set oauth2_credential_id to the UUID of an OAuth 2.0 integration credential (same org) configured with your provider’s token URL. Do not send auth_token; the API fetches a short-lived access token when creating, listing refresh, or when workflows run.


client.billing

const details = await client.billing.getDetails({
  start: "2024-01-01",
  end: "2024-01-31",
});
const totals = await client.billing.getTotals({
  start: "2024-01-01",
  end: "2024-01-31",
});
MethodHTTPPathDescription
getDetails(query)GET/billing/usage/detailsDetailed billing line items
getTotals(query)GET/billing/usage/totalsAggregated billing totals

client.apiKey

const info = await client.apiKey.describe();
MethodHTTPPathDescription
describe()GET/api-key/describeIntrospect the current API key (ID, name, org, etc.)

Native scenarios and retained history

Create and execute scenarios through client.e2eScenarios. client.adversarialTests and client.adversarialSuites expose retained history reads only.

const { scenario } = await client.e2eScenarios.create({
  targetUseCaseId: "workflow-id",
  targetAgentNodePersistentId: "agent-persistent-id",
  targetEnvironment: "production",
  mode: "agent_isolated",
  seeds: [],
  name: "Booking probe",
  adversarialPrompt: "Ask to book load L-7.",
});
await client.e2eScenarios.run(scenario.id, "selected-version-id");
const { messages } =
  await client.adversarialTests.getRunMessages("legacy-run-id");

client.northstars

Northstars are quality criteria that define how the agent should behave. They are used to automatically grade conversations.

const { northstar } = await client.northstars.get("northstar-id");
await client.northstars.update("northstar-id", {
  enabled: true,
  priority: "high",
});
await client.northstars.delete("northstar-id");

// Get full regeneration history
const { history } = await client.northstars.getHistory("northstar-id");

// Rate a northstar (-2 = strongly wrong, +2 = strongly correct)
const { feedback } = await client.northstars.submitFeedback("northstar-id", {
  correctness: 2,
  feedback: "This criterion is perfect.",
  trigger_regeneration: false,
});

await client.northstars.deleteFeedback("northstar-id");
MethodHTTPPathDescription
get(northstarId)GET/northstars/:idGet a northstar
update(northstarId, body)PATCH/northstars/:idUpdate name, description, examples, category, priority, or enabled state
delete(northstarId)DELETE/northstars/:idDelete a northstar
getHistory(northstarId)GET/northstars/:id/historyGet the full regeneration chain, oldest first
submitFeedback(northstarId, body)POST/northstars/:id/feedbackRate a northstar's correctness (−2 to +2), optionally trigger regeneration
deleteFeedback(northstarId)DELETE/northstars/:id/feedbackRemove your feedback on a northstar

client.customEvals

Custom evals test a specific prompt node against expected outputs or northstar criteria.

const { test } = await client.customEvals.get("eval-id");
await client.customEvals.update("eval-id", {
  name: "Greeting check",
  expected_response: "Hello, how can I help you?",
});
await client.customEvals.delete("eval-id");

// Run an eval
const { run_id } = await client.customEvals.run("eval-id", {
  version_id: "v-id",
});

// Poll results
const { runs } = await client.customEvals.listRuns("eval-id");
MethodHTTPPathDescription
get(evalId)GET/custom-evals/:idGet a custom eval
update(evalId, body)PATCH/custom-evals/:idUpdate messages, expected outputs, variables, or northstar IDs
delete(evalId)DELETE/custom-evals/:idDelete a custom eval
run(evalId, body)POST/custom-evals/:id/runExecute the eval asynchronously, returns run_id
listRuns(evalId, query?)GET/custom-evals/:id/runsList runs with pass/fail and judge reasoning

client.nodeTests

Saved node tests run a node with fixed upstream values and compare its output to an expected output. They appear in the workflow's Tests tab and belong to the node of one version. Forking a version copies them.

const { test } = await client.nodeTests.create("node-id", {
  name: "Load 123 transcript",
  config: { overrides: { "upstream-persistent-id.transcript": "..." } },
  expected_output: { carrier: "ACME", rate: 1200 },
  ignored_fields: ["notes"],
});

const { run_id } = await client.nodeTests.run(test.id);
const { run } = await client.nodeTests.getRun(test.id, run_id); // poll until status !== "running"
MethodHTTPPathDescription
list(nodeId)GET/nodes/:id/node-testsList a node's saved tests
create(nodeId, body)POST/nodes/:id/node-testsCreate a saved test
get(id)GET/node-tests/:idGet a saved test
update(id, body)PATCH/node-tests/:idUpdate any of name, overrides, expected or ignored fields
delete(id)DELETE/node-tests/:idDelete a saved test
run(id)POST/node-tests/:id/runRun against the node's current configuration
listRuns(id, query?)GET/node-tests/:id/runsList runs, newest first (limit, cursor)
getRun(id, runId)GET/node-tests/:id/runs/:idGet a run's output, pass/fail and mismatched fields

Tests on branches: client.branches.*

On workspaces on branches, tests live on each branch: use the /branches/{branch_id}/... routes through client.branches.customEvals, .northstars, .nodeTests, .e2eScenarios and .testSuites. They take persistent IDs, which stay the same across edits and commits. Every object they return has id, its current revision, which changes after a commit, and persistent_id, which goes in paths; a node's is its persistent_id in client.branches.get(branchId). Edits land in the branch's working tree, and runs use its working commit. The flat routes above are for workspaces on versions, and refuse edits on branch workspaces with a pointer to the branch route.

const branchId = "branch-id";
const { data } = await client.branches.customEvals.listForNode(
  branchId,
  "prompt-persistent-id"
);
await client.branches.customEvals.update(branchId, data[0].persistent_id, {
  name: "Renamed",
});
const { run_id } = await client.branches.customEvals.run(
  branchId,
  data[0].persistent_id
);
const { runs } = await client.branches.customEvals.listRuns(
  branchId,
  data[0].persistent_id
);

const { data: northstars, suggestions } =
  await client.branches.northstars.listForNode(
    branchId,
    "prompt-persistent-id"
  );
// Refresh proposes changes as suggestions; accept or dismiss them by persistent ID.
await client.branches.northstars.acceptSuggestions(branchId, {
  suggestion_ids: suggestions.map((suggestion) => suggestion.persistent_id),
});
const { tests } = await client.branches.nodeTests.list(
  branchId,
  "node-persistent-id"
);
const { scenarios } = await client.branches.e2eScenarios.list(branchId);
await client.branches.e2eScenarios.run(branchId, scenarios[0].persistent_id);

client.issues

Issues (quality flags) are raised when a conversation fails a northstar or quality check.

await client.issues.update("issue-id", { status: "approved" });
MethodHTTPPathDescription
update(issueId, body)PATCH/issues/:idUpdate issue status (open / approved / rejected / closed)

client.auditRemarks

Audit remarks are individual northstar grades attached to a conversation. Feedback on audit remarks improves future grading.

const feedback = await client.auditRemarks.getFeedback("audit-remark-id");

// Thumbs up — automatically adds the remark as a northstar positive example
await client.auditRemarks.submitFeedback("audit-remark-id", {
  polarity: true,
});

// Thumbs down with attribution
await client.auditRemarks.submitFeedback("audit-remark-id", {
  polarity: false,
  issue_attribution: "northstar",
  comment: "The northstar criteria was wrong here.",
});

await client.auditRemarks.deleteFeedback("audit-remark-id");
MethodHTTPPathDescription
getFeedback(auditRemarkId)GET/audit-remarks/:id/feedbackGet your feedback for this remark, or null
submitFeedback(auditRemarkId, body)POST/audit-remarks/:id/feedbackSubmit thumbs up/down; a thumbs-up adds the remark as a northstar example
deleteFeedback(auditRemarkId)DELETE/audit-remarks/:id/feedbackDelete your feedback

Client access tokens (client.tokens)

Create a token on your backend using your API key, then pass it to a client app to read specific sessions or runs. Tokens use JWE encryption; treat them as opaque and use the returned expiry time.

// Your backend
const access = await client.tokens.create({
  grants: [
    { resource: "session", resource_id: sessionId, actions: ["read"] },
    { resource: "run", resource_id: runId, actions: ["read"] },
  ],
  ttl_seconds: 3600,
});

// Your client app
const reader = new HappyRobotClient({ apiKey: access.token });
const history = await reader.sessions.getMessages(sessionId);

POST /tokens accepts 1–10 grants. Every grant must be permitted by the API key. Supported resources are session and run; the only supported action is read. The lifetime defaults to 3600 seconds, with a minimum of 60 and a maximum of 86400. The response contains only token and expires_at.

A session grant permits its details, messages, and stream. A run grant permits those reads for sessions belonging to the run, plus GET /runs/{id}/sessions. Unsupported protected routes return 403; resources outside the grants return 404. Client tokens cannot mint tokens. Revoking or expiring the minting API key blocks subsequent client-token requests.

Client-token message reads hide system messages, internal events, reminders, tool results, and tool calls. They use the existing organization rate limit. Streams emit token_expiring 30 seconds before expiry, then token_expired and close at expiry. Request a fresh token from your backend and reconnect. Recover missed messages through paginated message reads and merge by message ID; the stream does not provide cursor replay.

Server configuration: client tokens use the existing ENCRYPTION_KEY (32 UTF-8 bytes), with HKDF-SHA256 deriving a separate key for happyrobot/client-access-token/v1. No additional secret or database migration is required. A missing key disables minting with 503; an invalid key fails startup. Rotating ENCRYPTION_KEY invalidates existing client tokens and also affects stored credential encryption.


Chat (client.chat + HappyRobotChatClient)

Build custom chat UIs powered by your workflows. Uses a two-tier auth model:

  1. Your server creates a scoped client token using the API key (keeps it secret)
  2. Your browser uses HappyRobotChatClient with that token for all chat operations

Server-side: Create a client token

// --- YOUR SERVER (e.g. Next.js API route, Express handler) ---
import { HappyRobotClient } from "@happyrobot-ai/sdk";

const client = new HappyRobotClient({ apiKey: process.env.HAPPYROBOT_API_KEY });

app.post("/api/chat-token", async (req, res) => {
  const { token, expires_at } = await client.chat.createToken({
    workflow_id: "your-workflow-id",
    // Optional. Token lifetime in seconds. Default 3600 (1 hour), min 60, max 86400.
    // ttl_seconds: 1800,
  });
  res.json({ token, expires_at });
});

Browser-side: HappyRobotChatClient

// --- YOUR BROWSER CODE (React, Vue, vanilla JS, etc.) ---
import { HappyRobotChatClient } from "@happyrobot-ai/sdk";

// 1. Get a client token from your server
const { token } = await fetch("/api/chat-token", { method: "POST" }).then((r) =>
  r.json()
);

// 2. Initialize the browser-side client
const chat = new HappyRobotChatClient({ token });

// 3. Create a session
const { session_id } = await chat.createSession();

// 4. Connect bidirectional WebSocket
const connection = chat.connect(session_id, {
  onResponseStart: () => {
    // Show typing indicator
  },
  onResponseChunk: (content) => {
    // Append streamed text to the UI
  },
  onResponseEnd: (content) => {
    // Full response complete — hide typing indicator
  },
  onSessionClosed: (event) => {
    // Session ended: event.status, event.reason, event.duration
  },
  // Auto-refresh: ~30s before the token expires the SDK calls this and
  // forwards the result over the WebSocket. The connection stays open.
  getToken: async () => {
    const { token } = await fetch("/api/chat-token", { method: "POST" }).then(
      (r) => r.json()
    );
    return token;
  },
  onTokenExpired: () => {
    // Backstop: only fires if no valid refresh arrived in time
    // (e.g. getToken not provided, network failure). Reconnect from scratch.
  },
});

// 5. Send messages through the WebSocket
const ack = await connection.sendMessage({ content: "Hello!" });
console.log(ack.message.id); // server-assigned message ID

// 6. Send messages with file attachments
const artifact = await chat.uploadFile(fileBlob, "photo.png", "image/png");
await connection.sendMessage({
  content: "Here's the photo",
  artifacts: [artifact],
});

// 7. Get history (page reload, reconnect)
const { messages } = await chat.getHistory(session_id);

// 8. Clean up
connection.close();

Browser-side: File uploads

// Option A: Use the convenience method (handles all 3 steps)
const artifact = await chat.uploadFile(fileBlob, "photo.png", "image/png");
await connection.sendMessage({
  content: "Here's the photo",
  artifacts: [artifact],
});

// Option B: Manual 3-step flow for more control
const upload = await chat.getPresignedUpload({
  filename: "photo.png",
  mime_type: "image/png",
});
await fetch(upload.upload_url, {
  method: "PUT",
  body: fileBlob,
  headers: { "Content-Type": "image/png" },
});
await chat.completeUpload({
  artifact_id: upload.artifact_id,
  s3_uri: upload.s3_uri,
  filename: "photo.png",
  mime_type: "image/png",
  size_bytes: fileBlob.size,
});
await connection.sendMessage({
  content: "Here's the photo",
  artifacts: [
    {
      media_id: upload.artifact_id,
      mime_type: "image/png",
      filename: "photo.png",
      size_bytes: fileBlob.size,
    },
  ],
});

HappyRobotClient (server-side)

MethodDescription
client.chat.createToken({ workflow_id, env?, ttl_seconds? })Create a scoped client token. ttl_seconds defaults to 3600 (1 hour).

HappyRobotChatClient (browser-side)

MethodDescription
chat.createSession()Create a new chat session
chat.connect(sessionId, handlers)Open bidirectional WebSocket — returns ChatConnection
chat.sendMessage(sessionId, { content, artifacts? })Send a user message via HTTP (fallback if WS unavailable)
chat.getHistory(sessionId)Get message history
chat.uploadFile(file, filename, mimeType)Upload a file (convenience method)
chat.getPresignedUpload({ filename, mime_type })Get presigned S3 upload URL
chat.completeUpload({ artifact_id, s3_uri, ... })Register uploaded artifact

ChatConnection

MethodDescription
connection.sendMessage({ content, artifacts? })Send a message via WebSocket. Returns a Promise that resolves with the server ack
connection.close()Close the WebSocket connection
connection.wsThe underlying WebSocket instance

WebSocket Events

Server → Client:

EventFieldsDescription
connectedsession_idConnection established
response-startcontentAI started generating a response
response-chunkcontentPartial response text
response-endcontentComplete response text
session-closedsession_id, status, reason, duration, timestampSession ended
token-refresh-required—Sent ~30s before exp. SDK handles automatically when getToken is provided
token-refresh-ackexpires_atServer accepted the refreshed token; connection lifetime extended
token-refresh-errorerrorRefresh token was invalid or scope-mismatched; previous token still in force
token-expired—Backstop: token expired without a valid refresh, connection is closing
message-ackid, messageServer confirmed the message was sent
message-errorid, errorServer failed to send the message
heartbeat—Keep-alive (every 15s)

Client → Server:

EventFieldsDescription
messagecontent, artifacts?, id?Send a user message. id is echoed back in ack/error
token-refreshtokenProvide a fresh token to extend the connection. Sent automatically by the SDK when getToken set

Token refresh

Tokens have a finite lifetime (default 1 hour, configurable via ttl_seconds on createToken). To keep long-lived connections alive without forcing the client to reconnect, the SDK supports in-band refresh:

  1. ~30s before the active token expires, the server sends token-refresh-required.
  2. The SDK calls your getToken handler to fetch a fresh token from your backend.
  3. The SDK sends { type: "token-refresh", token } over the WebSocket.
  4. The server verifies the new token (scope must match: same workflow_id, org, env) and replies with token-refresh-ack. onTokenRefreshed(expiresAt) fires on the client.
  5. If no valid refresh arrives by exp, the server sends token-expired and closes the connection — onTokenExpired fires as a backstop.

If you don't provide getToken, refreshes are skipped and the connection will close at exp (legacy behavior). When the same token is shared across multiple concurrent connections, each connection refreshes independently — they diverge to per-connection tokens after the first refresh.


Voice (client.voice + HappyRobotVoiceClient)

Build browser-side voice calls with AI agents powered by your workflows. Uses the same two-tier auth model as chat:

  1. Your server creates a scoped LiveKit token using the API key (keeps it secret)
  2. Your browser uses HappyRobotVoiceClient with that token to connect via WebRTC

Server-side: Create a voice token

// --- YOUR SERVER (e.g. Next.js API route, Express handler) ---
import { HappyRobotClient } from "@happyrobot-ai/sdk";

const client = new HappyRobotClient({ apiKey: process.env.HAPPYROBOT_API_KEY });

app.post("/api/voice-token", async (req, res) => {
  const result = await client.voice.createToken({
    workflow_id: "your-workflow-id",
    data: { customer_name: "John" }, // optional — passed to the agent
    // Optional. LiveKit token lifetime in seconds.
    // Default 21600 (6 hours), min 60, max 86400 (24 hours).
    // LiveKit does not refresh tokens on an active call.
    // ttl_seconds: 3600,
  });
  res.json(result); // { url, token, room_name, run_id }
});

app.post("/api/live-session/:sessionId/listen-token", async (req, res) => {
  const result = await client.voice.createToken({
    session_id: req.params.sessionId,
  });
  res.json(result); // Hidden, subscribe-only observer token
});

Browser-side: HappyRobotVoiceClient

// --- YOUR BROWSER CODE (React, Vue, vanilla JS, etc.) ---
import { HappyRobotVoiceClient } from "@happyrobot-ai/sdk/voice";

// 1. Get a voice token from your server
const { url, token } = await fetch("/api/voice-token", { method: "POST" }).then(
  (r) => r.json()
);

// 2. Create the voice client and connect
const voice = new HappyRobotVoiceClient({ url, token });
const connection = await voice.connect({
  onConnected: () => {
    // Call started — microphone is automatically enabled
  },
  onAgentConnected: (participant) => {
    // AI agent joined the room
    console.log("Agent:", participant.identity);
  },
  onDisconnected: (reason) => {
    // Call ended
  },
  onReconnecting: () => {
    // Connection temporarily lost
  },
  onReconnected: () => {
    // Successfully reconnected
  },
  onError: (error) => {
    console.error("Voice error:", error);
  },
});

// 3. Mute / unmute
await connection.mute();
console.log(connection.isMuted()); // true
await connection.unmute();

// 4. End the call
await connection.disconnect();

To listen to an existing call without publishing audio or affecting the AI agent, create a token with session_id and use listen() in the browser:

const { url, token } = await fetch(
  `/api/live-session/${sessionId}/listen-token`,
  { method: "POST" }
).then((r) => r.json());

const voice = new HappyRobotVoiceClient({ url, token });
const listener = await voice.listen();

// If the browser later blocks playback, call this from a click handler:
await listener.startAudio();

// Stop listening without affecting the call:
await listener.disconnect();

Set should_takeover: true when creating a session token to retain the existing takeover behavior, which removes the AI agent from the call.

HappyRobotClient (server-side)

List the voices available to the current workspace in its cluster. Use a language prefix for all accents, or a locale for a location-specific result:

const voices = await client.voice.list({ language: "en-GB" });

for (const voice of voices) {
  console.log(voice.id, voice.name, voice.locales);
}

voice.id is the value used in workflow agent.voices configuration.

MethodDescription
client.voice.list({ language? })List voices available to the current workspace. language accepts prefixes like en or locales like en-GB.
client.voice.createToken({ workflow_id, data?, env?, ttl_seconds? })Create a LiveKit token for a new voice call.
client.voice.createToken({ session_id, should_takeover?, ttl_seconds? })Observe a live session, or take it over when should_takeover is true.

HappyRobotVoiceClient (browser-side)

MethodDescription
new HappyRobotVoiceClient({ url, token })Create client with LiveKit credentials
voice.connect(handlers?)Connect and enable the microphone — returns VoiceConnection
voice.listen(handlers?)Connect without microphone access or publishing — returns VoiceListenerConnection

VoiceConnection

MethodDescription
connection.disconnect()End the call and disconnect from the room
connection.mute()Mute the local microphone
connection.unmute()Unmute the local microphone
connection.isMuted()Check mute state
connection.roomUnderlying LiveKit Room instance for advanced use cases

VoiceListenerConnection

MethodDescription
listener.disconnect()Stop listening without affecting the call
listener.startAudio()Resume audio playback from a browser user gesture
listener.roomUnderlying LiveKit Room instance for advanced use cases

Room Events

HandlerDescription
onConnectedConnected to the LiveKit room
onDisconnectedDisconnected from the room
onAgentConnectedAI agent participant joined the room
onTrackSubscribedRemote audio track subscribed (auto-plays)
onTrackUnsubscribedRemote audio track unsubscribed
onReconnectingConnection temporarily lost — attempting to reconnect
onReconnectedSuccessfully reconnected
onErrorAn error occurred

Pagination

List methods that are paginated return a PaginatedResponse<T>:

interface PaginatedResponse<T> {
  data: T[];
  pagination: {
    page: number;
    page_size: number;
    total_pages: number;
    total_records: number;
    has_next_page: boolean;
    has_previous_page: boolean;
  };
}

For resources that support listAll(), use the async generator to iterate all pages automatically:

for await (const workflow of client.workflows.listAll({ folder_id: "..." })) {
  console.log(workflow.name);
}

Error Handling

import {
  ApiError,
  AuthenticationError,
  NotFoundError,
} from "@happyrobot-ai/sdk";

try {
  const wf = await client.workflows.get("nonexistent");
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log("Workflow not found");
  } else if (err instanceof AuthenticationError) {
    console.log("Invalid API key");
  } else if (err instanceof ApiError) {
    console.log(err.status, err.message);
  }
}

Shared test suites

Use client.testSuites for workflow-scoped custom/scenario collections. create accepts the shared useCaseId, name, origin, generationConfig, coverageScope, folderId, and members fields. Membership changes preserve definitions and history.

const { suite } = await client.testSuites.create({
  useCaseId: "workflow-id",
  name: "Booking regression",
  members: [{ kind: "custom", id: "test-id" }],
});
await client.testSuites.membership(suite.id, {
  members: [{ kind: "e2e", id: "scenario-id" }],
});
const { suite_run_id } = await client.testSuites.run(suite.id, "version-id");
const { run, results } = await client.testSuites.results(suite_run_id);
await client.testSuites.delete(suite.id);

AI generation runs once from generationConfig with a concrete version via generate(suiteId, versionId). After it succeeds, edit definitions and membership manually. Suite coverage guides generation and does not override existing test grading.

版本与发布记录

@happyrobot-ai/sdk 共发布 69 个版本,首次发布于 2026/03/10;过去 12 个月发布了 69 个版本。

版本发布日期距今
0.2.9latest2026/11/17今天
0.2.82026/11/17今天
0.2.62026/11/161 天前
0.2.52026/11/143 天前
0.2.42026/11/143 天前
0.2.32026/11/098 天前

关于 @happyrobot-ai/sdk 的常见问题

@happyrobot-ai/sdk 是什么?

TypeScript SDK for the HappyRobot Public API

如何安装 @happyrobot-ai/sdk?

在项目目录运行 npm install @happyrobot-ai/sdk,或使用 pnpm add / yarn add / bun add。

@happyrobot-ai/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@happyrobot-ai/sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@happyrobot-ai/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@happyrobot-ai/sdk 可以商用吗?

@happyrobot-ai/sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyrobot-ai/sdk 的下载量有多少?

根据 npm 官方下载统计,@happyrobot-ai/sdk 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,752 次,日均约 258 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@happyrobot-ai/sdk 还在维护吗?

最新版本 0.2.9 发布于 2026/11/17(今天);至今共发布 69 个版本,其中过去 12 个月发布了 69 个;首次发布于 2026/03/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。