@cargo-ai/worker-sdk

中文文档
1.0.21发布于 2026/10/19UNLICENSEDES Module近 30 天下载 7.7万

Build Cargo Hosting workers (edge HTTP handlers) with automatic OpenAPI generation via Hono + Chanfana.

原始使用文档
文档目录8 节
  1. Install
  2. Write a worker
  3. Call the Cargo API
  4. Cron triggers
  5. Write a custom integration
  6. Scaffold a project
  7. Deploy
  8. Available templates

@cargo-ai/worker-sdk

Build Cargo Hosting workers — serverless edge HTTP handlers running on *.worker.getcargo.run — with automatic OpenAPI 3.1 generation. Hono + Chanfana + Zod are wrapped in two opinionated factories so you define routes once and get runtime validation, a Cargo-native manifest, and live OpenAPI docs for free.

Install

npm install @cargo-ai/worker-sdk

Write a worker

import { type Context, createWorker, OpenAPIRoute } from "@cargo-ai/worker-sdk";
import { z } from "zod";

const { app, openapi } = createWorker({ title: "my-worker" });

class GetHello extends OpenAPIRoute {
  override schema = {
    request: {
      query: z.object({ name: z.string().default("world") }),
    },
    responses: {
      "200": {
        description: "Greeting.",
        content: {
          "application/json": {
            schema: z.object({ message: z.string() }),
          },
        },
      },
    },
  };

  override async handle(c: Context): Promise<Response> {
    const { query } = await this.getValidatedData<typeof this.schema>();
    return c.json({ message: `Hello, ${query.name}!` });
  }
}

openapi.get("/hello", GetHello);

export default app;

createWorker gives you:

  • GET /openapi.json — OpenAPI 3.1 spec derived from every route's Zod schema.
  • GET /docs — Swagger UI.
  • Console drain — console.info("outbound_http", { status: 200 }) stores "outbound_http" as the message and the object as structured attributes, not a joined JSON string.

Call the Cargo API

Create a workspace API token in Cargo and add it to the worker as a CARGO_API_TOKEN secret environment variable. createCargoApi(env) then returns the fully-typed @cargo-ai/api client, connected to your workspace — the Cargo API host is allowed automatically, no outboundAllowlist entry needed:

import { createCargoApi } from "@cargo-ai/worker-sdk";

app.get("/workers", async (c) => {
  const api = createCargoApi(c.env);
  const { workers } = await api.hosting.worker.list();
  return c.json(workers);
});

Runs you start this way stay on the trace of the invocation that made the call: Cargo Hosting stamps the invocation's run and trace uuid on outbound Cargo API requests, so a play that calls this worker shows the run it created as a child span rather than an unrelated trace. Nothing to wire up — it applies to createCargoApi and to a plain fetch of the API alike.

Cron triggers

A worker can be called on a schedule. Each trigger — configured on the worker from the Cargo app, cargo-ai hosting worker create/update --triggers, or defineWorker in a project — describes the full request Cargo fires: cron, path, method, JSON body, and headers. Set an authorization header on the trigger and guard the route:

import { bearerAuth } from "hono/bearer-auth";

app.use("/cron/*", bearerAuth({ token: "<something-strong>" }));

app.post("/cron/sync", async (c) => {
  // ... scheduled work ...
  return c.json({ ok: true });
});

Ticks only fire once the worker has a promoted deployment.

Write a custom integration

createCustomIntegration({ info, connector, authenticate, actions, extractors, ... }) builds a worker that implements the Cargo Custom Integration HTTP contract from a single declarative spec. The same Zod schemas feed GET /manifest (Cargo-native wire format) and GET /openapi.json. See templates/custom-integration/.

Integration-domain types (IntegrationActionExecutePayload, IntegrationExtractorFetchResult, …) live in @cargo-ai/types under the ConnectionTypes namespace — you rarely need to import them directly because the SDK's CustomIntegrationAction / CustomIntegrationExtractor types wire them in for you.

Scaffold a project

You almost never want to wire this from scratch. Use the CLI:

# Blank edge handler
npx @cargo-ai/cli hosting worker init my-worker --template blank

# Worker that implements the Cargo Custom Integration HTTP contract
npx @cargo-ai/cli hosting worker init my-integration --template custom-integration

The CLI copies the matching template from @cargo-ai/worker-sdk/templates/<slug>/ into your target directory.

Deploy

You author in TypeScript and deploy the source directory as-is — no local build step. The uploaded source is the project root (with src/index.ts, manifest.json, package.json, package-lock.json):

npm install
cargo-ai hosting deployment create --worker-uuid <workerUuid> --source ./
cargo-ai hosting deployment promote --uuid <deploymentUuid>

The Cargo Hosting build pipeline runs npm ci then esbuild src/index.ts --bundle --format=esm --platform=neutral --target=es2022 (esbuild transpiles TypeScript natively) to produce the final edge bundle. So you can ship multi-file TypeScript projects — esbuild tree-shakes everything into a single ESM file at deploy time. (A pre-built index.js at the root is still accepted for backwards compatibility.)

Available templates

  • blank — a ready-to-extend Hono app built by createWorker(), with one sample route and /openapi.json + /docs out of the box. Use this when the worker just responds to inbound HTTP and doesn't need to integrate into the Cargo connector catalog.
  • custom-integration — a ready-to-extend spec passed to createCustomIntegration(). Handles /manifest, /openapi.json, /docs, /authenticate, /actions/<slug>/execute, /extractors/<slug>/{fetch,count}, /autocompletes/<slug>, /dynamicSchemas/<slug>, /completeOauth, /listUsers from a single declaration. Edge-native equivalent of getcargohq/dummy-integration. Register it in the connector catalog with defineCustomIntegration in the CDK, or cargo-ai connection custom-integration create --kind worker --worker-uuid <workerUuid>.

See each template's own README.md for the file layout and how to extend it.

版本与发布记录

@cargo-ai/worker-sdk 共发布 21 个版本,首次发布于 2026/05/13;过去 12 个月发布了 21 个版本。

版本发布日期距今
1.0.21latest2026/10/1921 天前
1.0.202026/09/191 个月前
1.0.192026/09/181 个月前
1.0.182026/09/181 个月前
1.0.172026/08/232 个月前
1.0.162026/08/212 个月前

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

@cargo-ai/worker-sdk 是什么?

Build Cargo Hosting workers (edge HTTP handlers) with automatic OpenAPI generation via Hono + Chanfana.

如何安装 @cargo-ai/worker-sdk?

在项目目录运行 npm install @cargo-ai/worker-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:zod(^4.3.6)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@cargo-ai/worker-sdk 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/cargo-ai__worker-sdk 是否存在。

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

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

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

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

@cargo-ai/worker-sdk 可以商用吗?

@cargo-ai/worker-sdk 使用 UNLICENSED 许可。作者声明为 UNLICENSED,即不授予公开使用许可(与公共领域的 Unlicense 不同)。使用前需获得作者授权。以上为概括,不构成法律意见,请以许可原文为准。

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

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

@cargo-ai/worker-sdk 还在维护吗?

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