TypeScript SDK
适用于 Node.js、Bun、Deno 和 edge 运行时的 @dcision/sdk——从源码构建、decide、目的地与函数、错误、幂等重试、执行记录、me() 以及 webhook 验证。
@dcision/sdk 是官方的 JavaScript 和 TypeScript SDK。它没有任何依赖——只使用 fetch 和 Web Crypto——提供 ESM、CommonJS 和类型定义,可在 Node.js 20+、Bun、Deno 和 edge 运行时上运行。
安装
尚未发布到 npm
@dcision/sdk 尚未发布到 npm。请从 Dcision 仓库的检出副本构建它;在本页注明已发布之前,npm 上任何同名的包都不是来自 Dcision。
# 1. In a checkout of the Dcision repository (Node.js 22 and pnpm 10)
pnpm install
pnpm --filter @dcision/sdk build
# 2. In your project
npm install /path/to/dcision/packages/sdk对文件夹执行 npm install 会把它链接到你的项目中;pnpm、yarn 和 bun 也接受同样的路径。如果要复制这个包——放进 Docker 镜像、另一台机器——请打一个 tarball 并安装它:
cd /path/to/dcision/packages/sdk && npm pack # writes dcision-sdk-0.1.0.tgz
npm install ./dcision-sdk-0.1.0.tgz # in your project快速入门
在 API 密钥中创建一个 API 密钥,并在你服务器的环境中将其设置为 DCISION_API_KEY。
import { Dcision } from "@dcision/sdk";
const dcision = new Dcision(); // reads DCISION_API_KEY
const decision = await dcision.decide("lead-qualification", {
message: "We need pricing for 500 users and want to start next month.",
company_size: 500,
});
decision.result.route; // "sales"
decision.confidence.route; // 0.85
decision.action; // "continue" | "block" | "escalate" | "fallback"
decision.destinations; // what happens next: replies, queued deliveries, functions…CommonJS 的用法相同:const { Dcision } = require("@dcision/sdk")。
配置
const dcision = new Dcision({
apiKey: process.env.DCISION_API_KEY, // default: the DCISION_API_KEY environment variable
timeoutMs: 30_000,
maxRetries: 2,
userAgent: "acme-crm/2.1",
});| 选项 | 默认值 | 描述 |
|---|---|---|
apiKey | DCISION_API_KEY | dcs_live_… 或 dcs_test_…。缺少密钥或密钥不以 dcs_ 开头时,会立即抛出 DcisionError INVALID_API_KEY——不会发送任何内容。 |
baseUrl | https://api.dcision.io | 必须使用 https——仅当 API 位于回环地址时才允许普通 http。可以带路径前缀;凭据、查询字符串或片段会被拒绝。 |
timeoutMs | 30000 | 每次尝试的超时时间,以毫秒为单位。 |
maxRetries | 2 | 在网络错误、超时、429、502、503 或 504 之后的重试次数。 |
fetch | 全局 fetch | 自定义实现:(url, init) => Promise<Response>。 |
userAgent | — | 你的应用标识,会添加在 SDK 标识之前:acme-crm/2.1 dcision-sdk-js/0.1.0。 |
创建一个客户端并共享使用:它不保存任何每个请求的状态。
运行决策
const decision = await dcision.decide(slug, state, options);state 是决策要评估的内容——字符串、对象或数组,取决于决策的声明。在发送任何内容之前,slug 会在本地进行检查(小写字母、数字和单个连字符)。
| 选项 | 描述 |
|---|---|
idempotencyKey | Idempotency-Key:1 到 128 个字符,取自 A–Z a–z 0–9 . _ : -。默认:每次调用生成一个新的 UUID,并在其所有重试中复用。 |
includeProbabilities | 添加 probabilities,即每个问题的完整分布(?include=probabilities)。 |
functions | 函数目的地的处理函数。 |
onMissingFunction | "throw"(默认)或 "ignore"。 |
signal | 一个 AbortSignal:中止会停止请求及其重试,decide 会以 signal.reason 拒绝。 |
decide 解析为一个 Decision:包含 API 响应的每个字段——decision_id、execution_id、schema、version、result、confidence、scores、composites、action、action_reason、probabilities、metrics、destinations——外加 functionResults 和 dispatch()。destinations 始终是一个数组:当决策没有目的地或没有目的地触发时为 []。
设置了 onEngineError: "fallback" 的决策在引擎出错时会以其 fallback 行动作答:此时 action_reason.type 为 "engine_error",result 和 confidence 为空对象。
目的地
decision.destinations 保存响应中的目的地条目。Destination 是一个联合类型,可以根据 type 和 status 进行类型收窄:
for (const destination of decision.destinations) {
if (destination.type === "reply") chat.send(destination.text, destination.buttons);
else if (destination.type === "llm" && destination.status === "completed") chat.send(destination.text);
else if (destination.type === "agent" && destination.status === "completed") chat.send(destination.reply ?? "");
else if (destination.status === "failed") log.warn(`${destination.key}: ${destination.error}`);
else if (destination.status === "queued") log.info(`${destination.key} queued as ${destination.delivery_id}`);
else if (destination.status === "skipped") log.info(`${destination.key} skipped: ${destination.reason}`);
}函数目的地
函数目的地指定一个函数及其参数。在 functions 中传入处理函数,SDK 会在决策完成后调用它们:
const decision = await dcision.decide("lead-qualification", { message, email }, {
functions: {
assignToSales: async (params, decision) => crm.assign(String(params.email), decision.result.route),
notifySlack: (params) => slack.post(String(params.text)),
},
});
decision.functionResults;
// [{ key: "assign_owner", function: "assignToSales", result: <what the handler returned> }]- 处理函数以
functions[name](params, decision)的形式调用,按destinations的顺序逐个调用:异步处理函数会在下一个开始之前被 await。 - 只调用已触发的函数条目——不调用被跳过的条目,也不调用其他类型。
- 缺少处理函数: 在第一个处理函数运行之前会查找所有处理函数。如果缺少某一个,
decide会抛出DcisionErrorFUNCTION_NOT_REGISTERED,并且不会运行任何处理函数——除非你传入onMissingFunction: "ignore"。 - 处理函数抛出异常: 后续的处理函数不会被调用,
decide会抛出DcisionErrorFUNCTION_FAILED,附带cause(处理函数抛出的内容)、decision和functionResults(已完成的处理函数)。决策已经运行过了——并且已计费。 - 处理函数每次
decide调用只运行一次,在得到最终回答之后:调用内部的重试永远不会重复分派。使用相同的idempotencyKey再次调用decide会重放已存储的回答并再次分派其函数,因此请让处理函数具备幂等性——例如以decision.execution_id为键。
稍后或在其他地方,根据已存储的响应进行分派:
import { Decision } from "@dcision/sdk";
const decision = await dcision.decide("lead-qualification", state); // no functions: nothing is called
await queue.push(JSON.stringify(decision));
// in a worker
const results = await new Decision(JSON.parse(job.payload)).dispatch(handlers, { onMissingFunction: "ignore" });错误
SDK 因 API 回复、网络故障、处理函数或签名而抛出的所有错误都是 DcisionError:
import { DcisionError } from "@dcision/sdk";
try {
await dcision.decide("lead-qualification", state);
} catch (error) {
if (error instanceof DcisionError && error.code === "INVALID_STATE") return reportBadInput(error.message);
throw error;
}| 字段 | 描述 |
|---|---|
code | 稳定的代码:请根据它进行分支判断,而不是根据 message。 |
message | 人类可读的说明。 |
status | HTTP 状态码;没有响应(网络错误、超时)或检查在本地进行时为 undefined。 |
requestId | 请求的 request_id(X-Request-ID):联系支持时请提供它。 |
details | 某些代码附带的额外数据——参见错误。 |
retryAfter | 来自 Retry-After 请求头的秒数(如果有的话)。 |
idempotencyKey | decide 发送的 Idempotency-Key:之后复用它即可安全重试。 |
cause | 底层错误:网络故障、处理函数的异常。 |
decision、functionResults | 仅限 FUNCTION_NOT_REGISTERED 和 FUNCTION_FAILED。 |
API 的代码列在错误中。SDK 额外增加了:
| 代码 | 何时 |
|---|---|
NETWORK_ERROR | API 没有回复:DNS 失败、连接被拒绝或重置、TLS 错误。会重试。 |
TIMEOUT | 某次尝试耗时超过 timeoutMs。会重试。 |
FUNCTION_NOT_REGISTERED | 某个函数目的地在 functions 中没有处理函数。 |
FUNCTION_FAILED | 某个处理函数抛出了异常。 |
INVALID_SIGNATURE | 某个 webhook 未通过验证。 |
本地检查复用 API 的代码,status 为 undefined:缺少或格式错误的密钥为 INVALID_API_KEY,无效的 slug、idempotencyKey 或缺少状态为 INVALID_REQUEST。不是来自 API 的回复——来自代理的 HTML 页面、重定向——会保留其 HTTP 状态码,并使用一个兜底代码:INVALID_API_KEY(401)、FORBIDDEN(403)、NOT_FOUND(404)、CONFLICT(409)、PAYLOAD_TOO_LARGE(413)、RATE_LIMITED(429)、INVALID_REQUEST(其他 4xx)或 INTERNAL_ERROR。重定向永远不会被跟随。
重试与幂等性
decide 会发送一个 Idempotency-Key,每次调用生成一次,并在每次重试中复用。如果某次尝试运行了决策但回答丢失了,重试会得到已存储的回答:重试永远不会让一个决策运行或计费两次。
| 会重试 | 不会重试 |
|---|---|
| 网络错误和超时 | 500 INTERNAL_ERROR |
带有 Retry-After 的 409 IDEMPOTENCY_CONFLICT:使用该键的第一个请求仍在运行 | 不带 Retry-After 的 409——另一个不同的请求复用了该键——以及其他 4xx |
429 RATE_LIMITED | 502 ENGINE_AUTH_FAILED 和 ENGINE_INVALID_REQUEST:它们每次都会以同样的方式失败 |
其他 502 错误、503 和 504 | 函数错误和签名错误 |
- 最多重试
maxRetries次:默认 2 次,即共 3 次尝试。 - 当 API 发送
Retry-After时,SDK 会等待它,最长 30 秒。更长的Retry-After不会等待:错误会立即抛出,并设置retryAfter,以便你安排重试。 - 没有
Retry-After时,它会等待 0.5 秒、1 秒、2 秒……——每次翻倍,最多 8 秒——外加最多 25% 的随机抖动。 me()和executions也以同样的方式重试。
409 的情况正是让超时变得安全的原因:如果某次尝试在决策仍在运行时超时,重试会发现该键已被预留,等待一秒(Retry-After: 1)后再次尝试,直到得到已存储的回答——或者用完重试次数并抛出 IDEMPOTENCY_CONFLICT,键保存在 error.idempotencyKey 中,以便稍后再试。
传入你自己的键,可以让重试跨进程或跨重启都保持安全,例如使用你所决策对象的 ID:
await dcision.decide("support-routing", ticket, { idempotencyKey: `ticket-${ticket.id}` });timeoutMs 适用于每次尝试;若要为整个调用设置截止时间,请传入一个 signal:{ signal: AbortSignal.timeout(15_000) }。请让 timeoutMs 大于决策自身的 timeoutMs(默认 5 秒,最多 30 秒)加上其最慢的 LLM 或 sync 智能体目的地的超时时间,这样在重试之前,该次尝试在 Dcision 一侧确实已经结束。
账户与执行记录
const me = await dcision.me();
me.plan.rate_limit_per_minute;
me.usage.used / me.usage.included;
// one page, newest first
const page = await dcision.executions.list({ decision: "lead-qualification", status: "error", limit: 100 });
page.data; // the runs: answers, action, metrics — never the inputs
page.next_cursor; // pass it as `cursor` for the next page; null on the last one
// every page
for await (const run of dcision.executions.iterate({ decision: "lead-qualification", limit: 100 })) {
console.log(run.created_at, run.result?.route, run.action);
}iterate() 只有在你迭代到下一页时才会获取它,因此 break 会停止它。读取永远不计费,并有自己的速率限制窗口——参见获取账户与用量和列出执行记录。
合作伙伴模式
合作伙伴为每位客户保留一个子工作区。withWorkspace() 返回一个在其中某个子工作区中操作的客户端(请求头 Dcision-Workspace);workspaces 和 embed 用于管理它们——在服务器端,使用你的 API 密钥。
await dcision.workspaces.upsert({ external_id: "acme", name: "Acme Inc", seed: { decisions: ["lead-qualification"], deploy: true } });
await dcision.withWorkspace("ext:acme").decide("lead-qualification", { message: "Pricing?" });
const { url } = await dcision.embed.createSession({ workspace: "ext:acme", user: { id: user.id, name: user.name } });Webhook
import { DcisionError, verifyWebhook } from "@dcision/sdk";
const event = await verifyWebhook(rawBody, signatureHeader, process.env.DCISION_WEBHOOK_SECRET!);
event.type; // "decision.completed"
event.id; // "dlv_…": the same on every delivery attempt
event.data.result.route; // "sales"
event.data.params; // the params mapped in the destination (the state itself is never sent)verifyWebhook(body, header, secret, { toleranceSec = 300, now }):
body——原始请求体,可以是string、Uint8Array或Buffer,或ArrayBuffer;header——Dcision-Signature请求头;secret——签名密钥(whsec_…,位于设置 → 目的地),或在轮换期间传入一个密钥数组;toleranceSec——签名的时间戳与now允许相差多少;now——Unix 秒数或Date,用于测试。
当请求头缺失或格式错误、没有任何签名匹配(以恒定时间比较)、时间戳超出容差或请求体不是 JSON 事件时,它会抛出 DcisionError INVALID_SIGNATURE——此时请返回 400。误用——例如没有密钥或请求体已被解析——则会抛出 TypeError——此时请返回 500,这样 Dcision 会持续重试,直到修复被部署。
verifySignature(body, header, secret, options) 执行同样的检查,但不解析请求体:将其用于 API 请求和智能体,它们的请求体不是事件。
Express 和 Next.js 的完整接收端示例请参见 Webhook。
TypeScript
用泛型为决策的回答添加类型——interface 也同样适用:
interface LeadResult {
route: "sales" | "sdr" | "nurture" | "spam" | "other";
purchase_intent: number;
}
const decision = await dcision.decide<LeadResult>("lead-qualification", state, {
functions: {
// handlers can declare the params they expect
assignToSales: async (params: { email: string }, decision) => crm.assign(params.email, decision.result.route),
},
});
decision.result.route; // "sales" | "sdr" | "nurture" | "spam" | "other"
const event = await verifyWebhook<LeadResult>(body, header, secret);
event.data.result.route;该包导出 Dcision、Decision、DcisionError、verifyWebhook、verifySignature 和 VERSION,以及 DecisionResponse、Destination、QueuedDestination、SkippedDestination、FunctionDestination、WebhookEvent、Me、Execution、ExecutionPage 和 DcisionErrorCode 等类型。
运行时支持
| 运行时 | 说明 |
|---|---|
| Node.js 20+ | ESM(import)和 CommonJS(require)。 |
| Bun | 与 Node.js 相同。 |
| Deno | 导入构建产物:import { Dcision } from "/path/to/dcision/packages/sdk/dist/esm/index.js"。允许网络访问(--allow-net=api.dcision.io),并且为了读取 DCISION_API_KEY,需要 --allow-env=DCISION_API_KEY——或者传入 apiKey。 |
| Cloudflare Workers、Vercel Edge | 从你的 bindings 或环境中传入 apiKey。 |
| 浏览器 | 不支持:浏览器中的 API 密钥是公开的。请从你的服务器调用 Dcision。 |
安全说明
- API 密钥保持私密。 它保存在私有字段中——
console.log不会打印它,JSON.stringify中也不会出现——并且永远不会出现在错误消息中。不是 Dcision 密钥的值会在发出任何请求之前被拒绝。 - 传输。 仅限
https,并且永远不跟随重定向,因此密钥永远不会到达其他主机。 - 路径。 slug 会被校验和编码:URL 路径中不会出现任何其他内容。
- Webhook。 HMAC-SHA256 以恒定时间比较,超出容差的时间戳会被拒绝,验证只针对原始字节进行。