> ## Documentation Index
> Fetch the complete documentation index at: https://docs.beeos.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK

> 安装并使用 @beeos-ai/sdk —— BeeOS OpenAPI 的自动生成 TypeScript 客户端。

[`@beeos-ai/sdk`](https://www.npmjs.com/package/@beeos-ai/sdk)
package 是公开 BeeOS OpenAPI 契约的规范 TypeScript 客户端，契约由
[`openapi-gateway`](/zh/architecture/public-overview#3-each-surfaces-ownership)
在 `openapi.beeos.ai` 提供服务。它从同一份
[`backend/openapi/beeos-platform-v1.yaml`](https://github.com/beeos-ai/openagent/blob/main/backend/openapi/beeos-platform-v1.yaml)
生成 —— 本站 API Reference tab 看到啥，SDK 里就是啥。

<Info>
  SDK 只针对 **Platform API**。[A2A 协议](/zh/a2a/overview)
  （`a2a.beeos.ai`）和 [MCP 协议](/zh/mcp/overview)
  （`mcp.beeos.ai`）是独立主机、独立鉴权 —— **不**被本 package 包装。
  对那些主机用 HTTPS 直连即可。
</Info>

## 安装

```bash theme={null}
npm install @beeos-ai/sdk
```

当前发布版本：**0.6.1**（wire delta 见 [SDK 变更日志](/zh/sdks/changelog)）。

## 稳定任务 facade（推荐）

0.6.0 新增手工维护的 `BeeOSClient`，覆盖常用 Agent 任务生命周期；
OpenAPI 生成代码重新生成时，它的调用方式保持稳定。

```typescript theme={null}
import { BeeOSClient } from "@beeos-ai/sdk";

const client = new BeeOSClient({
  apiKey: process.env.BEEOS_API_KEY!,
  baseUrl: "https://openapi.beeos.ai",
});

const agents = await client.listAgents();
const created = await client.createTask(agents[0].id, {
  message: "汇总最新设备状态。",
});
const task = await client.getTask(agents[0].id, created.data.taskId);
await client.cancelTask(agents[0].id, created.data.taskId);
```

`client.taskEvents(agentId, taskId)` 是任务 SSE 流的 async generator。
完整生成 API 仍从 package root 导出，facade 也可从
`@beeos-ai/sdk/facade` 显式导入。

## 完整生成客户端

生成代码遵循 OpenAPI Generator `typescript-fetch` 模板：一个
`Configuration` 值 + 每个 OpenAPI tag 一个 class。

```typescript theme={null}
import {
  Configuration,
  DeployApi,
  InstancesApi,
  AgentsApi,
  TasksApi,
  ConversationsApi,
  FilesApi,
} from "@beeos-ai/sdk";

const config = new Configuration({
  basePath: "https://openapi.beeos.ai",
  headers: {
    Authorization: `Bearer ${process.env.BEEOS_API_KEY}`,
  },
});

const deploy = new DeployApi(config);
const instances = new InstancesApi(config);
const agents = new AgentsApi(config);
const tasks = new TasksApi(config);
const conversations = new ConversationsApi(config);
const files = new FilesApi(config);
```

<Note>
  本地开发把 `basePath` 设成 `http://localhost:8095`（
  [Procfile.staging](https://github.com/beeos-ai/openagent/blob/main/backend/Procfile.staging)
  里 `openapi-gw` 的默认端口）。
</Note>

## Catalog

```typescript theme={null}
const providers = await deploy.listProviders();
const regions = await deploy.listDeployRegions({ providerId: "default" });
const models = await deploy.listDeployModels({ agentFramework: "beeos-claw" });
```

## 实例生命周期

```typescript theme={null}
const created = await instances.deployInstance({
  deployInstanceRequest: {
    name: "my-agent",
    agentFramework: "beeos-claw",
    modelPrimary: "gpt-4o",
  },
});

const inst = await instances.getInstance({ id: created.data!.id });

await instances.startInstance({ id: inst.data!.id });
await instances.stopInstance({ id: inst.data!.id });
await instances.restartInstance({ id: inst.data!.id });
await instances.destroyInstance({ id: inst.data!.id });
```

`listInstances` 支持分页 + 状态过滤：

```typescript theme={null}
const list = await instances.listInstances({
  page: 0,
  pageSize: 20,
  status: "running",
});
```

## 智能体

```typescript theme={null}
const list = await agents.listAgents({
  instanceId: "inst_abc123",
  limit: 20,
});

const agent = await agents.getAgent({ agentId: "agent_abc123" });

await agents.patchAgent({
  agentId: agent.data!.id,
  patchAgentRequest: { visibility: "public" },
});
```

### Invoke（阻塞）

旗舰级 per-agent 操作。完整契约见 [调用智能体](/zh/guides/calling-agents)。

```typescript theme={null}
const reply = await agents.invokeAgent({
  agentId: "agent_abc123",
  invokeAgentRequest: {
    message: "Hello, what can you do?",
  },
});
console.log("Reply:", reply.data?.text);
console.log("Channel:", reply.data?.context_id);
```

### 带 idempotency + 附件的 Invoke（0.4.0）

```typescript theme={null}
const reply = await agents.invokeAgent({
  agentId: "agent_abc123",
  invokeAgentRequest: {
    message: "Summarize the attached PDF.",
    idempotency_key: "user_42:summarize_q3_report",
    attachments: [{ file_id: "file_abc123", filename: "q3-report.pdf" }],
    metadata: { campaign: "marketing-q3" },
  },
});
```

`idempotency_key` 让调用在 TTL 窗口内可安全重试（契约见
[ADR 0021](https://github.com/beeos-ai/openagent/blob/main/backend/docs/adr/0021-idempotency-key-ttl.md)）。
同 key 重复 → 相同响应、不会双重 invoke。

### 流式 Invoke（SSE）

SDK 不抽象 SSE —— 退回到 `fetch` + `Accept: text/event-stream`。
frame 形状见 [流式](/zh/guides/streaming)：

```typescript theme={null}
const res = await fetch(
  "https://openapi.beeos.ai/api/v1/agents/agent_abc123/invoke",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.BEEOS_API_KEY}`,
      "Content-Type": "application/json",
      Accept: "text/event-stream",
    },
    body: JSON.stringify({ message: "Tell me a long story." }),
  },
);

const reader = res.body!.getReader();
const decoder = new TextDecoder();
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  process.stdout.write(decoder.decode(value));
}
```

## 任务（异步 invocation）

```typescript theme={null}
const created = await tasks.createTask({
  agentId: "agent_abc123",
  createTaskRequest: {
    message: "Run the full Q3 audit.",
    idempotency_key: "audit_q3_2026",
  },
});
const taskId = created.data!.task_id;

// Poll
let task = await tasks.getTask({ agentId: "agent_abc123", taskId });
while (task.data?.status !== "completed" && task.data?.status !== "failed") {
  await new Promise(r => setTimeout(r, 2_000));
  task = await tasks.getTask({ agentId: "agent_abc123", taskId });
}

// 跨智能体列表（0.4.0 新增）
const all = await tasks.listUserTasks({ state: "running", limit: 50 });

// 取消
await tasks.cancelTask({ agentId: "agent_abc123", taskId });
```

需要服务端推送通知时，注册带 HMAC 签名的 webhook：

```typescript theme={null}
await tasks.registerTaskWebhook({
  agentId: "agent_abc123",
  taskId,
  registerTaskWebhookRequest: {
    url: "https://example.com/hooks/beeos",
    secret: "whsec_…",
    events: ["completed", "failed", "cancelled"],
  },
});
```

Webhook payload 用 HMAC-SHA256 签名；投递日志可通过
`listWebhookDeliveries` 查询、通过 `redeliverWebhook` 重放（0.4.0 新端点
—— 见 [Webhooks](/zh/guides/webhooks)）。

## 会话

```typescript theme={null}
const conv = await conversations.createConversation({
  agentId: "agent_abc123",
  createConversationRequest: { title: "Quarterly planning" },
});

await conversations.sendConversationMessage({
  agentId: "agent_abc123",
  conversationId: conv.data!.conversationId,
  sendConversationMessageRequest: { message: "Start the planning session." },
});

const msgs = await conversations.listConversationMessages({
  agentId: "agent_abc123",
  conversationId: conv.data!.conversationId,
  since: 0,
});
```

与任务对比：任务一次性、有终止态；会话开着直到你删它。
见 [会话](/zh/guides/conversations)。

## 文件

```typescript theme={null}
const presigned = await files.presignUpload({
  presignUploadRequest: {
    filename: "report.pdf",
    contentType: "application/pdf",
  },
});

await fetch(presigned.data!.url, {
  method: "PUT",
  headers: { "Content-Type": "application/pdf" },
  body: pdfBytes,
});

// 之后回读元数据 + 一个新的签名下载 URL
const meta = await files.presignDownload({ id: presigned.data!.file_id });
```

把得到的 `file_id` 放进 `invokeAgent` 或 `createTask` 的
`attachments[].file_id`。

## 错误处理

非 2xx 响应抛 `Response`（底层 `fetch` Response）。
检查 `.status` 和 `.json()` 拿 BeeOS error 信封
（`{ success: false, error: { code, message } }`）：

```typescript theme={null}
import { ResponseError } from "@beeos-ai/sdk";

try {
  await instances.getInstance({ id: "nonexistent" });
} catch (e) {
  if (e instanceof ResponseError) {
    const body = await e.response.json();
    console.error("API error:", body.error.code, body.error.message);
  } else {
    throw e;
  }
}
```

完整 code 列表见 [错误参考](/zh/reference/errors)。

## TypeScript 类型

每个请求和响应都全类型化：

```typescript theme={null}
import type {
  DeployInstanceRequest,
  InvokeAgentRequest,
  InvokeAgentResponse,
  TaskResponse,
  ListTasksResponse,
  ConversationResponse,
  PresignUploadRequest,
} from "@beeos-ai/sdk";
```

## 源码与生成

SDK 用 OpenAPI Generator
（[`sdks/openapi-sdk/generate.sh`](https://github.com/beeos-ai/openagent/blob/main/sdks/openapi-sdk/generate.sh)）
从
[`backend/openapi/beeos-platform-v1.yaml`](https://github.com/beeos-ai/openagent/blob/main/backend/openapi/beeos-platform-v1.yaml)
自动生成。wire 级变更归档在 [SDK 变更日志](/zh/sdks/changelog)、
迁移配方见 [SDK 迁移](/zh/sdks/migration)。

* npm：[`@beeos-ai/sdk`](https://www.npmjs.com/package/@beeos-ai/sdk)
* GitHub：[`beeos-ai/sdk`](https://github.com/beeos-ai/sdk)
