# @diskd-ai/sdk 中文文档

规范地址：https://npmcn.com/package/%40diskd-ai/sdk/

版本：7\.10\.0
npm 元数据更新时间：2026-11-11T21:21:11.194Z
中文译文更新时间：2026-11-12T11:34:25.644Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40diskd-ai/sdk
原文对照：https://npmcn.com/package/%40diskd-ai/sdk/?lang=original
项目主页：https://github.com/diskd-ai/diskd-sdk#readme
源码仓库：https://github.com/diskd-ai/diskd-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.1 MB，343 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.0\.0
- 运行依赖：1 个
- peer 依赖：typeorm ^0\.3\.28
- 首次发布：2026-04-29T08:44:02.649Z
- 最新版本发布：2026-11-11T21:21:10.713Z
- 近 30 天下载量：8132（2026-10-13 至 2026-11-11，npm 官方下载统计）
- 已发布版本数：63（近 12 个月 63 个）

## 中文简介

DiskD 平台 API (Drive, LLM 路由器, Agent Hub, MCP Hub, Telegram Userbot, Web 导航) 的 SDK 版本

## 安装

```sh
npm install @diskd-ai/sdk
```

也可以使用：`pnpm add @diskd-ai/sdk`、`yarn add @diskd-ai/sdk`、`bun add @diskd-ai/sdk`

## README

# @ diskd-ai/ sdk (英语)

Upgraide平台API的统一TypeScript SDK.

所有服务均可通过下列途径获得: `diskd` 工厂,提供一致的 `diskd.auth.*` + 跨名称空间服务模式 `diskd.os.*`, (中文(简体) ), `diskd.platform.*`, (中文(简体) ), 财务报告和审定财务报表 `diskd.utils.*`数字 :

```ts
import { diskd } from '@diskd-ai/sdk';

const auth = diskd.auth.apiKey({ workspaceId: '...' });

const drive      = diskd.os.drive({ version: 'v1', auth });
const sessions   = diskd.platform.sessions({
  auth,
  scope: { scopeType: 'project', projectId: 'proj-1' },
});
const crontab    = diskd.platform.crontab({
  auth,
  scope: { scopeType: 'project', projectId: 'proj-1' },
});
const db         = diskd.os.database({ auth, dbName: '...', schema: { ... } });
const ds         = diskd.os.datasource({ auth, dbName: '...', entities: [...] });
const llm        = diskd.os.llm({ auth });
const agents     = diskd.os.agents({ auth, workspaceId: '...' }); // deprecated, unrouted
const mcp        = diskd.os.mcp({ auth, workspaceId: '...' });
const messages   = diskd.os.messagesStore({ auth });
const routines   = diskd.platform.routines({ auth });
const operatives = diskd.platform.operatives({ auth });
const calendar   = diskd.platform.calendar({ auth });
const tg         = diskd.utils.tgUserBot({ auth, workspaceId: '...' });
const webNav     = diskd.utils.webNavigator({ auth, workspaceId: '...' });
```

## 安装

1.  配置 `.npmrc` 在您的项目中( 或 `~/.npmrc`:
    
    ```ini
    @diskd:registry=https://gitlab.iosya.com/api/v4/projects/80/packages/npm/
    //gitlab.iosya.com/api/v4/projects/80/packages/npm/:_authToken=${NPM_TOKEN}
    ```
    
2.  设定 `NPM_TOKEN` gitLab 个人访问符 `read_api` 范围 :
    
    ```bash
    export NPM_TOKEN=glpat-xxxxxxxxxxxx
    ```
    
3.  安装 :
    
    ```bash
    bun add @diskd-ai/sdk
    ```
    

## 安装/ 构建( repo)

```bash
cd mono/platform-api
bun install
bun run build
```

## 认证

SDK 支持通过 `AuthModule` 接口.

### 外部客户端( OAuth2)

使用 `diskd.auth.credentials()` oAuth2 服务账户或 PKCE 浏览器流:

```ts
import { diskd } from '@diskd-ai/sdk';

const auth = await diskd.auth.credentials({
  scopes: [
    'openid',
    'drive:read',
    'drive:write',
    'sessions:read',
    'sessions:write',
    'crontab:read',
    'crontab:write',
  ],
  keyfilePath: 'credentials.json',
});

const drive = diskd.os.drive({ version: 'v1', auth });
const sessions = diskd.platform.sessions({
  auth,
  scope: { scopeType: 'project', projectId: 'proj-1' },
});
const crontab = diskd.platform.crontab({
  auth,
  scope: { scopeType: 'project', projectId: 'proj-1' },
});
```

#### OAuth2 范围

SDK前进 `scopes` 与象征性请求不变。 请求范围 所有客户端的 APIS 网关路线 (单位:千美元)`required_scopes` 服务中 `config/routes.yaml`) (中文(简体) ). 网关比较 表示对路由所申报的每个范围的标志,所以请按 每条路线 :

| SDK 客户端 | 网关路径 | 范围 |
| --- | --- | --- |
| `diskd.os.drive`, (中文(简体) ), `diskd.os.messagesStore` | `/v1/os/drive` | `drive:read drive:write` |
| `diskd.os.database` | `/v1/os/database` | `database:read database:write` |
| `diskd.os.email` | `/v1/os/email` | `email:read email:write` |
| `diskd.os.llm` | `/v1/os/llm` | `llm:invoke llm:models:read` |
| `diskd.os.mcp`, (中文(简体) ), `diskd.os.mcpTools` | `/v1/os/mcp` | `mcp:read mcp:execute` |
| `diskd.platform.sessions` | `/v1/platform/sessions` | `sessions:read sessions:write` |
| `diskd.platform.crontab` | `/v1/platform/crontab` | `crontab:read crontab:write` |
| `diskd.platform.operatives` | `/v1/platform/operatives` | `operatives:read operatives:write` |
| `diskd.platform.projects`, (中文(简体) ), `diskd.platform.notes` | `/v1/platform/projects` | `projects:read projects:write` |
| `diskd.platform.routines`, (中文(简体) ), `diskd.platform.routineRuns` | `/v1/platform/routines` | `routines:read routines:write` |
| `diskd.platform.events` | `/v1/platform/events` | `events:write` |
| `diskd.platform.calendar` | `/v1/platform/calendar` | `calendar:read calendar:write` |
| `diskd.platform.contacts` | `/v1/platform/contacts` | `contacts:read contacts:write` |
| `diskd.platform.inbox` | `/v1/os/drive`, (中文(简体) ), `/v1/os/email` | `drive:read drive:write email:read email:write` |
| `diskd.utils.tgUserBot` | `/v1/utils/tg-userbot` | `tg-userbot:read tg-userbot:write` |
| `diskd.utils.webNavigator` | `/v1/utils/web-navigator` | `web-navigator:read web-navigator:write` |

保留 `openid` 当您需要 OIDC 签名时( 浏览器 PKCE 流量); 无害 用于客户端证书密钥文件.

推出状态 (2026-10-05):网关尚未强制实施范围. 记录 每个 OAuth2 请求 `token_scopes` 以及他们是否满足路线 (单位:千美元)`scopes_satisfied`) (中文(简体) ). OAuth 服务范围之前注册的客户 仅允许推出 `openid`所以海德拉会回答 `invalid_scope` 当他们要求 路线范围。 SDK/CLI的证书下次会取出路线范围 证书通过应用程序的证书流获取( 工作空间保存) 同样的客户身份和秘密,所以存在 `credentials.json` 继续工作 ;自助 OAuth apps 启动时由 iam-service 调节.

### 内部服务(API密钥)

使用 `diskd.auth.apiKey()` 用于本组内服务间通信:

```ts
import { diskd } from '@diskd-ai/sdk';

const auth = diskd.auth.apiKey({ workspaceId: process.env.WORKSPACE_ID! });

const drive = diskd.os.drive({ version: 'v1', auth });
```

`diskd.auth.apiKey()` 读取 `APIS_API_KEY` 从环境,并在 无论是 `APIS_API_KEY` 或者说 `APIS_BASE_URL` 缺少.

两种认证模式生成相同的客户端实例 .

## 环境变量

所有资源 API 从中央网关基址解析 :

| 信封变量 | 默认 |
| --- | --- |
| `APIS_BASE_URL` | `https://apis.diskd.local:8080` |
| `APIS_API_KEY` | 无 |

网关为单一资源入口. 公共网关 URL 跟踪 版本公约 `https://apis.example/v1/{namespace}/{module}`. SDK 软件 aPI 路径来自公共 SDK 表面相同的命名空间结构 让网关处理API的管弦和认证策略.

衍生默认路径 :

-   `/v1/os/drive`
-   `/v1/os/database`
-   `/v1/os/llm`
-   `/v1/os/agents` (损坏的Hub代理客户端;APIS-Service没有这种路线)
-   `/v1/os/mcp`
-   `/v1/platform/sessions`
-   `/v1/platform/crontab`
-   `/v1/platform/operatives`
-   `/v1/platform/projects`
-   `/v1/platform/routines`
-   `/v1/platform/events`
-   `/v1/platform/calendar`
-   `/v1/utils/tg-userbot`
-   `/v1/utils/web-navigator`

您仍可使用明确权限覆盖客户端 `url`,但默认模式是 中央网关.

## 网关决定

此 SDK 不将资源 API 视为独立发现的主机 . 警犬模型是一个集中式的 `apis` 后门 `APIS_BASE_URL`。 。 。 .

这意味着:

-   无每服务默认 vars 如 `LLM_ROUTER_BASE_URL`, (中文(简体) ), `AGENT_HUB_BASE_URL`,或 `MCP_HUB_BASE_URL`
-   资源客户端从 `APIS_BASE_URL` 加上命名空间路径前缀
-   网关负责请求的路由、API的管弦和认证策略处理

每个客户 `url` 仍然只能作为明确的替代.

## 驱动 API

### 路径操作

```ts
await drive.init();
const entries = await drive.list({ path: '/' });
const dir = await drive.create({ dirName: 'my-folder' });
await drive.rename({ inode: dir.inode, newName: 'renamed-folder' });
await drive.delete({ inodes: [dir.inode], recursive: true });
const resolved = await drive.resolve({ inodes: ['inode1', 'inode2'] });
await drive.updateMetadata({ inode: 'abc', metadata: { key: 'value' } });
await drive.updateAttributes({ inode: 'abc', attributes: ['pinned'] });
```

### 上传( 缓冲+流)

```ts
// Buffer upload
const result = await drive.upload.file({
  name: 'hello.txt',
  data: new TextEncoder().encode('Hello, world!'),
  mimeType: 'text/plain',
  onProgress: (uploaded, total) => console.log(`${uploaded}/${total}`),
});

// Stream upload (large files)
const result = await drive.upload.file({
  name: 'large.bin',
  stream: readableStream,
  size: 1_000_000_000,
  sha256Root: 'precomputed-hex',
});
```

### 下载( 流出)

```ts
const file = await drive.download.file({
  inode: 'abc123',
  onProgress: (downloaded, total) => console.log(`${downloaded}/${total}`),
});
await file.stream.pipeTo(writableStream);
```

### 文件元数据、磁盘使用、工具

```ts
const meta = await drive.files.metadata({ inode: 'abc' });
const usage = await drive.diskUsage();
const ls = await drive.tools.ls({ path: '/', recursive: true });
const grep = await drive.tools.grep({ pattern: 'TODO' });
```

### 会议

SDK将这些会话方法曝光于 `diskd.platform.sessions({ auth, scope })`数字 :

-   `start`
-   `open`
-   `save`
-   `list`
-   `delete`
-   `message`

```ts
const session = await sessions.start({
  title: 'Deployment help',
});

await session.append([
  sessions.message({ role: 'user', content: 'How do I deploy to production?' }),
]);

const sessionList = await sessions.list();
```

### Crontab 调度器

SDK显示这些调度方法 `diskd.platform.crontab({ auth, scope, timezone? })`。 。 。 . 若为 `timezone` 省略, SDK 默认使用调用器运行时段 .

-   `save`
-   `get`
-   `getStatus`
-   `listJobs`
-   `runJob`
-   `createJob`

```ts
await crontab.createJob({
  job: {
    jobId: '01JABCD2FGH3JK4MNP5QRST6VW',
    enabled: true,
    schedule: {
      minute: '*/5',
      hour: '*',
      dayOfMonth: '*',
      month: '*',
      dayOfWeek: '*',
    },
    request: {
      method: 'POST',
      url: 'https://example.internal/hooks/sync',
      payload: {
        kind: 'json',
        value: { source: 'sdk-example' },
      },
    },
  },
});

const status = await crontab.getStatus();
```

见 `examples/node/drive-upload-download.ts`, (中文(简体) ), `examples/node/drive-session-external.ts`,以及 `examples/node/drive-crontab.ts`。 。 。 .

## 电子邮件提供者业务

`diskd.os.email({ auth })` 用途 `/v1/os/email` 以提交持久提供者命令 等待工作空间范围的结果。 它支持账户上市,5分钟 同步入学/状况、身体和附件水合物、旗帜、删除和 独立的SMTP/IMAP连接探测器. 邮件内容留在 Drive; 发送邮件 通过现有的Drive Exchange Outbox合同.

`diskd.platform.inbox({ auth })` 自动使用这些工人。 习惯 工人网关, 替换已删除的 `mcpUrl` 选项 `emailUrl`现有 收件箱方法和消息定位器不变. 内部消费者可以提供 `emailAuth` 当工人和Drive需要不同的服务证明时。 这个 然后,工人证书只发给电子邮件端点。 客户截止日期不 取消已经接受的命令 .

## 信件存储 API

频道-不可知消息存储于 Drive上方. 每个工作空间信箱是一 SQLite 文件在下面 `/Mailboxes/<mailboxId>.mailbox`; 附加字节存在 开车下去 `/Mailboxes/<mailboxId>/<per-message-folder>/`线是 `messages_store/*` JSON-RPC 命名空间通过驱动器服务.

用它来坚持电子邮件( IMAP / JMAP), Telegram, WhatsApp, 或任何其他 每个账户邮箱内的信息存储文件夹的频道。 消息 `payload` 是不透明的JSON; 商店从来不检查它.

将电子邮件改为/未读更改,使用 `diskd.platform.inbox({ auth }).markRead(...)`。 。 。 . 它解决了顽固的提供者身份, 排队共享的电子邮件工人命令, 并验证提供者的旗帜和一面新鲜的 Drive 镜像 返回前读取。 提供者 `flags` 优于遗产 `isRead` 财务报告和审定财务报表 `isFlagged` 布尔斯。 配置客户端 `contentMode: 'stored-only'` 拒绝 标记读取,因为它没有提供者突变边界。 公共方法和 参数形状不变;不需要存储数据迁移.

客户端暴露出四个边框 -- -- 邮箱、文件夹、信件、附件 - 通过a **功能范围界定模式**: 每个关卡返回客户端 在关闭时抓取其标识符, 因此调用者从不重复 `(mailboxId, folderId, externalId)` 每一个电话.

```ts
const messagesStore = diskd.os.messagesStore({ auth });
const mailbox = messagesStore.mailbox({ mailboxId: 'gmail-acme' });
const folder  = mailbox.folder({ folderId: 'INBOX' });
const message = folder.message({ externalId: 'imap-uid-1001' });
```

### 邮箱

```ts
// Allocate the mailbox SQLite file under /Mailboxes/.
// metadata is opaque JSON, stashed on the underlying drive_databases record.
const created = await messagesStore.createMailbox({
  mailboxId: 'gmail-acme',
  displayName: 'acme@gmail.com',
  metadata: { protocol: 'imap', host: 'imap.gmail.com' },
});
// → { mailboxId, dbInode, drivePath: '/Mailboxes/gmail-acme.mailbox' }

// Bind a mailbox-scoped client; subsequent calls don't repeat mailboxId.
const mailbox = messagesStore.mailbox({ mailboxId: 'gmail-acme' });

// Idempotent SQLite-schema bootstrap. Required before any folder/message ops.
await mailbox.init();

// Workspace-scoped enumeration.
const all = await messagesStore.listMailboxes();
//   → readonly { mailboxId, displayName, dbInode, recordCount,
//                sizeBytes, updatedAt }[]

// Cascade-delete (mailbox file + per-mailbox attachment subtree).
await mailbox.delete();
```

### 文件夹

`folderId` 是不透明( 调用选择) - IMAP 文件夹名称、 JMAP id、 Telegram 聊天等文件夹 `metadata` 是特定协议的自然位置 同步状态( e)`UIDVALIDITY`编号 :`UIDNEXT`编号 :`HIGHESTMODSEQ` 用于 IMAP, JMAP `state`, (中文(简体) ), Telegram pts等). 店从不读.

```ts
// Idempotent upsert. created=true on first call, false thereafter.
await mailbox.upsertFolder({
  folderId: 'INBOX',
  displayName: 'Inbox',
  metadata: { uidvalidity: 12345, uidnext: 1101 },
});

// List folders in this mailbox.
const folders = await mailbox.listFolders();

// Bind a folder-scoped client.
const folder = mailbox.folder({ folderId: 'INBOX' });

// Update display name / sync metadata via the scoped client (folderId implicit).
await folder.upsert({
  displayName: 'Inbox',
  metadata: { uidvalidity: 12345, uidnext: 1200 },
});

// Read one folder.
const summary = await folder.get();
//   → { folderId, displayName, metadata, messageCount, updatedAt }

// Cascade-delete folder + messages + per-message attachments.
const result = await folder.delete();
//   → { folderId, deleted, deletedMessageCount }
```

### 信件

`externalId` 是文件夹( IMAP UID) 内调用者的自定义键 已字符串, 电报 `message_id`, JMAP id, ...). (中文(简体) ). `payload` 是不透明的 JSON 商店从不检查.

一个成功的 `upsertBatch` 响应表示该批次在 S3 中具有耐用性 -- -- 该 SQLite头在呼叫返回前被承诺.

```ts
// Bulk insert-or-update by externalId.
const ub = await folder.upsertBatch({
  items: [
    {
      externalId: 'imap-uid-1001',
      payload: {
        subject: 'Welcome to upgraide',
        from: 'noreply@upgraide.dev',
        receivedAt: '2026-04-28T13:21:32Z',
        labels: ['inbox', 'unread'],
      },
    },
    { externalId: 'imap-uid-1002', payload: { subject: 'Your weekly digest' } },
  ],
});
//   → { inserted: 2, updated: 0 }

// Cursor-paginated read.
let cursor: string | null = null;
do {
  const page = await folder.listMessages({ limit: 100, cursor: cursor ?? undefined });
  for (const m of page.items) {
    // m.externalId, m.payload, m.createdAt, m.updatedAt
  }
  cursor = page.nextCursor;
} while (cursor);

// Single-message lookup.
const msg = await folder.getMessage({ externalId: 'imap-uid-1001' });

// Bulk delete; missing ids are silently skipped.
const del = await folder.deleteBatch({
  externalIds: ['imap-uid-1001', 'imap-uid-1002'],
});
//   → { deleted: 2 }
```

### 附录

附件遵循 Drive 的上传提示合同( 开始 ) ~ PUT 字节 ~ . . . . . 每个消息驱动文件夹是 以懒惰的方式创造第一个 `uploadStart` 电话.

```ts
const message = folder.message({ externalId: 'imap-uid-1001' });

// 1. Begin upload -- get an intent + presigned URL.
const intent = await message.attachments.uploadStart({
  attachmentId: 'att-1',
  filename: 'invoice.pdf',
  contentType: 'application/pdf',
  sizeBytes: 12345,
});

// 2. PUT the bytes to intent.uploadUrl with header X-Upload-Intent-Id.
//    (See Drive upload examples for streaming/buffer modes.)
const putRes = await fetch(intent.uploadUrl, {
  method: 'PUT',
  headers: { 'X-Upload-Intent-Id': intent.intentId, 'Content-Type': 'application/pdf' },
  body: pdfBytes,
});
const { etag } = (await putRes.json()) as { etag: string };

// 3. Commit -- registers the attachment row.
await message.attachments.uploadCommit({
  attachmentId: 'att-1',
  intentId: intent.intentId,
  etag,
});

// Enumerate this message's attachments.
const list = await message.attachments.list();

// Presigned download URL (with explicit expiresAt).
const dl = await message.attachments.downloadUrl({ attachmentId: 'att-1' });

// Delete the attachment row + its Drive file.
await message.attachments.delete({ attachmentId: 'att-1' });
```

### Auth 模式

和SDK的其余部分相同 - 两者都工作:

```ts
// API key (internal services / Tilt / port-forward).
const auth = diskd.auth.apiKey({ workspaceId: 'ws-...' });

// OAuth2 client-credentials (external clients); Messages Store calls /v1/os/drive.
const auth = await diskd.auth.credentials({
  scopes: ['openid', 'drive:read', 'drive:write'],
  keyfilePath: '.agents/credentials.json',
});

const messagesStore = diskd.os.messagesStore({ auth });
```

工作空间身份总是由认证产生(`X-Workspace-Id` aPI 标题 键, `ext.workspace_id` ——从未作为电线发送 参数。 见 `examples/node/messages-store-example.ts` 满额 端对端行走.

## 常规 API

用于管理常规(自动工作流程)的REST客户端,用于配置或项目:

```ts
const routines = diskd.platform.routines({ auth });

// List routines in a scope
const all = await routines.list({ scope: 'workspace' });
const projectRoutines = await routines.list({ scope: 'project', projectName: 'my-project' });

// Get by slug
const routine = await routines.get({ slug: 'daily-summary', scope: 'workspace' });

// Create
const created = await routines.create({
  name: 'Daily Summary',
  scope: 'workspace',
  operativeSlug: 'research-agent',
  triggerType: 'rhythm',
  trigger: { cron: '0 9 * * *' },
  steps: [{ id: 'step-1', name: 'Summarize', action: 'summarize', order: 0 }],
});

// Update
const updated = await routines.update(
  'daily-summary',
  { status: 'paused' },
  { scopeType: 'workspace' },
);

// Delete
await routines.delete({ slug: 'daily-summary', scope: 'workspace' });
```

## 运算 API

管理操作员(AI代理)的REST客户端,并附有文件、技能和MCP工具:

```ts
const ops = diskd.platform.operatives({ auth });

// List operatives in a project
const list = await ops.list({ projectId: 'proj-1' });

// Get by id or slug
const operative = await ops.get('op-01');
const bySlug = await ops.getBySlug({ projectId: 'proj-1', slug: 'research-agent' });

// Create
const created = await ops.create({
  projectId: 'proj-1',
  name: 'Research Agent',
  engine: 'deep',
  engineProvider: 'anthropic',
  engineModel: 'claude-4',
});

// Update
await ops.update('op-01', {
  orders: 'You are a research assistant focused on academic papers.',
  fileAccess: 'selected',
});

// Delete
await ops.delete('op-01');
```

### 操作文件(驱动知识来源)

附加 Drive 从操作员的项目chroot 中获取的文件作为知识源 :

```ts
// Attach files (paths relative to project chroot)
await ops.files.add('op-01', { paths: ['/docs/knowledge-base', '/docs/readme.md'] });

// List attached files
const files = await ops.files.list('op-01');

// Detach a file
await ops.files.remove('op-01', files[0].id);
```

### 操作技能

```ts
// Attach skills
await ops.skills.add('op-01', { refIds: ['web-search', 'code-review'] });

// List attached skills
const skills = await ops.skills.list('op-01');

// Detach a skill
await ops.skills.remove('op-01', skills[0].id);
```

### 业务多方案工具

```ts
// Attach MCP tools
await ops.tools.add('op-01', { selectors: ['github/search_repos', 'slack/send_message'] });

// List attached tools
const tools = await ops.tools.list('op-01');

// Detach a tool
await ops.tools.remove('op-01', tools[0].id);
```

## 日历 API

用于工作空间日历管理的 REST 客户端 -- -- 活动、参与者、注释链接、附件和设置:

```ts
const calendar = diskd.platform.calendar({ auth });

// Accounts and events
const accounts = await calendar.listAccounts();
const events = await calendar.listEvents({
  startAfter: '2026-03-01T00:00:00Z',
  startBefore: '2026-03-31T23:59:59Z',
});

// Event CRUD
const event = await calendar.createEvent({
  calendarId: accounts[0].calendars[0].id,
  title: 'Sprint Planning',
  startAt: '2026-03-25T10:00:00Z',
  endAt: '2026-03-25T11:00:00Z',
});

await calendar.updateEvent(event.id, {
  title: 'Sprint Planning (updated)',
  metadata: { timeBlockCategory: 'meeting' },
});

await calendar.deleteEvent(event.id);
```

### 参与者

```ts
const attendee = await calendar.attendees.add(event.id, {
  email: 'alice@example.com',
  role: 'required',
});

await calendar.attendees.updateRsvp(event.id, attendee.id, 'yes');
await calendar.attendees.remove(event.id, attendee.id);
```

### 注解链接

```ts
const link = await calendar.noteLinks.add(event.id, {
  noteDiskPath: '/Projects/sprint/notes/planning.md',
  title: 'Planning Notes',
  linkType: 'context',
});

await calendar.noteLinks.remove(event.id, link.id);
```

### 附录

```ts
const attachment = await calendar.attachments.add(event.id, {
  type: 'url',
  title: 'Meeting Recording',
  url: 'https://meet.example.com/recording/123',
});

await calendar.attachments.remove(event.id, attachment.id);
```

### 事件元数据

事件支持可扩展 `metadata` 跨域数据的 JSONB 字段 :

```ts
await calendar.updateEvent(event.id, {
  metadata: {
    timeBlockCategory: 'focus',
    linkedNotes: [
      { noteDiskPath: '/docs/spec.md', title: 'Spec', linkType: 'context' },
    ],
  },
});
```

### 设置

```ts
const settings = await calendar.getSettings();
await calendar.updateSettings({
  weekStartDay: 0,
  defaultView: 'month',
  timezone: 'America/New_York',
});
```

## 驱动数据库 API

Drive的SQLite后置数据库操作的JSON-RPC客户端 :

```ts
const drive = diskd.os.drive({ version: 'v1', auth });

// Create a database with schema
const db = await drive.db.create({
  name: 'myapp.workspace-123.main',
  schema: {
    users: {
      id:    { type: 'TEXT', primaryKey: true },
      name:  { type: 'TEXT', notNull: true },
      email: { type: 'TEXT', notNull: true },
    },
  },
});

// Insert rows
await drive.db.insert({
  name: 'myapp.workspace-123.main',
  table: 'users',
  rows: [{ id: '1', name: 'Alice', email: 'alice@example.com' }],
});

// Query with parameters
const result = await drive.db.query({
  name: 'myapp.workspace-123.main',
  sql: 'SELECT * FROM users WHERE id = ?',
  parameters: ['1'],
});

// Commit, metadata, drop, resolve
await drive.db.commit({ name: 'myapp.workspace-123.main' });
const meta = await drive.db.metadata({ name: 'myapp.workspace-123.main' });
const resolved = await drive.db.resolveByInode({ dbInode: db.dbInode });
```

## 驱动存储器( CRUD 模式)

高级数据库+表范围存储器模式 -- -- 服务的理想 用 DB 驱动作为其持久性层 :

```ts
// Create database with schema
const db = diskd.os.database({
  auth,
  dbName: 'shop.workspace-123.main',
  dbType: 'database',
  schema: {
    users:  { id: { type: 'TEXT', primaryKey: true }, name: { type: 'TEXT', notNull: true } },
    orders: { id: { type: 'TEXT', primaryKey: true }, user_id: { type: 'TEXT' }, total: { type: 'INTEGER' } },
  },
});

await db.ensureCreated();

// Get table-scoped repositories
const users = db.repository('users');
const orders = db.repository('orders');

// Insert
await users.insert([{ id: 'u1', name: 'Alice' }, { id: 'u2', name: 'Bob' }]);

// Find with where, orderBy, limit, offset
const results = await users.find({
  where: { name: 'Alice' },
  orderBy: { column: 'name', direction: 'ASC' },
  limit: 10,
});

// Find one (returns null if not found)
const alice = await users.findOne({ id: 'u1' });

// Count
const total = await orders.count();
const pending = await orders.count({ status: 'pending' });

// Update
await orders.update({ where: { id: 'o1' }, set: { status: 'shipped' } });

// Delete
await orders.deleteRows({ status: 'cancelled' });

// Raw SQL at database level for joins and complex queries
const summary = await db.query(`
  SELECT u.name, SUM(o.total) AS revenue
  FROM users u JOIN orders o ON o.user_id = u.id
  GROUP BY u.id ORDER BY revenue DESC
`);

// Commit and metadata (database-level operations)
await db.commit();
const meta = await db.metadata();
```

见 `examples/node/drive-db-repository-example.ts`。 。 。 .

## TypeORM 驱动程序 (`diskd.os.datasource()`(中文(简体) )

使用 TypeORM 实体、 关系和寄存器来对抗 DB 。 SQL 已路由 通过 DB JSON- RPC 驱动器和 TypeORM 的交易生命周期图来驱动 DB 执行/回滚语义. 要求数 `typeorm` 作为同伴的依赖.

### 安装

```bash
npm install @diskd-ai/sdk typeorm
```

### 使用量

```ts
import { diskd } from '@diskd-ai/sdk';
import { Entity, PrimaryColumn, Column } from 'typeorm';

// Define entities
@Entity({ name: 'users' })
class User {
  @PrimaryColumn({ type: 'varchar', length: 26 })
  id!: string;

  @Column({ type: 'varchar' })
  name!: string;

  @Column({ type: 'varchar' })
  email!: string;
}

// Create DataSource backed by Drive DB
process.env.APIS_BASE_URL ??= 'https://apis.diskd.local:8080';

const auth = diskd.auth.apiKey({ workspaceId: 'workspace-123' });

const ds = diskd.os.datasource({
  auth,
  url: `${process.env.APIS_BASE_URL}/v1/os/database/api/v1`,
  dbName: 'shop.workspace-123.main',
  entities: [User],
  synchronize: true,
});

await ds.initialize();

// Standard TypeORM repository operations
const userRepo = ds.getRepository(User);
await userRepo.save({ id: 'u1', name: 'Alice', email: 'alice@example.com' });

const alice = await userRepo.findOneBy({ id: 'u1' });
const users = await userRepo.find({ order: { name: 'ASC' } });

// Persist to S3 (flush WAL)
await ds.driver.commit();

// Rollback discards uncommitted changes (revert to last commit)
await ds.driver.driveRollback();
```

### 交易映射

| TypeORM 操作 | 驱动 DB 动作 |
| --- | --- |
| `BEGIN TRANSACTION` | 无操作( WAL 中自动累积写入) |
| `COMMIT` | `drive.db.commit()` -- 冲出 WAL 到 S3 |
| `ROLLBACK` | `drive.db.rollback()` - 丢弃 WAL |

### 限制(v1)

-   无嵌入式交易/ 保存点( 推迟到 v2)
-   受影响的行数返回 0 (每个 JSON- RPC 呼叫是单独的 SQLite) 连接; 基于 ULID 的实体工作罚款)
-   现场数据库的Schema回顾有限; `synchronize: true` 直接生成 DDL

见 `examples/node/typeorm-drive-example.ts` 财务报告和审定财务报表 `docs/typeorm-driver-design.md`。 。 。 .

## LLM 路由器 API

JSON-RPC 2.0 + NDJSON 为多供应商 LLM 完成而流出:

```ts
const llm = diskd.os.llm({ auth });

// Non-streaming completion
const result = await llm.completions.create({
  provider: 'openai', model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Hello' }],
  maxTokens: 64,
});

// Streaming
for await (const chunk of llm.completions.stream(params)) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}

// Models, embeddings, OCR, audio transcription
const models = await llm.models.listAll();
const embeddings = await llm.embeddings.create({ provider: 'openai', model: 'text-embedding-3-small', input: ['text'] });
```

见 `examples/node/llm-router-example.ts`。 。 。 .

## Hub API探员

**堕地而无道.** Hub探员堕地了,Apis服务宣告 没有 `/v1/os/agents` 路线,所以 `diskd.os.agents` (和 `createAgentHubClient`(中文(简体) ) 无法通过网关到达它。 客户端只为避免 打破更改。 特工通过Pi -agent -服务运行 应用服务会话 API(`/api/sessions`); 此 SDK 没有客户端 API 还没有. `diskd.platform.sessions` 是 Drive 会话存储, 不引用 探员.

SSE 流经中 `StreamProtocolHandler` + 键 `StreamProtocolFetcher` 代理人援引:

```ts
import { diskd, StreamProtocolHandler } from '@diskd-ai/sdk';

const agents = diskd.os.agents({ auth, workspaceId: '...' });

// List agents and models
const agentList = await agents.agents.list();
const models = await agents.agents.getSupportedModels('assistant');
const billing = await agents.billing.getAliases();

// Invoke with fluent stream handling
const handler = new StreamProtocolHandler()
  .on('response.output_text.delta', (e) => process.stdout.write(e.delta))
  .on('response.completed', (e) => console.log('done', e.response.usage))
  .on('response.failed', (e) => console.error(e.response.error.message))
  .on('error', (e) => console.error(e.message));

const stream = await agents.invoke({
  agentName: 'assistant',
  query: 'Hello',
  agentOptions: { maxTokens: 256 },
});

stream.map((event) => handler.handle(event))
  .stop(() => console.log('stream closed'))
  .catch((err) => console.error(err));
```

串流协议活动包括文本三角洲、函数调用/结果、内容部分 (图像、文件、音频)、网络/文件搜索生命周期、外部来源、计划更新、, 和错误/补全信号.

见 `examples/node/agent-hub-example.ts`。 。 。 .

## MCP 枢纽 API

用于 MCP 服务器目录、 注册和集成的 REST 客户端 :

```ts
const mcp = diskd.os.mcp({ auth, workspaceId: '...' });

// Catalog
const catalog = await mcp.catalog.list({ search: 'github' });
const details = await mcp.catalog.getServerDetails(serverId);

// Registry (installed servers)
const registry = await mcp.registry.list();
const added = await mcp.registry.addServer({ catalogServerId: '...' });
await mcp.registry.toggleTool(serverId, toolId, false);
const logs = await mcp.registry.getServerLogs(serverId, { limit: 10 });
await mcp.registry.deleteServer(serverId);

// Env vars, connection settings, remote servers
await mcp.registry.upsertEnvVar(serverId, { key: 'TOKEN', value: '...' });
await mcp.registry.addRemoteServer({ name: 'My MCP', url: '...', authType: 'pat' });
```

见 `examples/node/mcp-hub-example.ts`。 。 。 .

## 电报用户机器人 API

用于Telegram 信道分辨率、导入和信件检索的 REST 客户端 :

```ts
const tg = diskd.utils.tgUserBot({ auth, workspaceId: '...' });

// Resolve channel (public, no auth required)
const resolved = await tg.channels.resolve('durov');

// Channel operations
const channels = await tg.channels.list();
await tg.channels.add({ channelIdentifier: '@mychannel', limit: 1000 });
await tg.channels.sync({ telegramId: -1001234567890 });

// Messages and stats
const messages = await tg.channels.getMessages(channelId, { limit: 50, searchText: 'keyword' });
const stats = await tg.channels.getStats(channelId);
const status = await tg.channels.getStatus(channelId);

// Tasks
const tasks = await tg.tasks.list();
await tg.tasks.cancel(taskUuid);
```

见 `examples/node/tg-userbot-example.ts`。 。 。 .

## Web 导航 API

用于 URL 解析和网络删除任务的 REST 客户端 :

```ts
const webNav = diskd.utils.webNavigator({ auth, workspaceId: '...' });

// Resolve URL metadata
const meta = await webNav.resolve({ url: 'https://example.com' });

// Submit scrape job
const job = await webNav.scrape.submit({ url: 'https://example.com', depth: 1, maxPages: 10 });
const status = await webNav.scrape.getStatus(job.jobId);
const result = await webNav.scrape.getResult(job.jobId);
await webNav.scrape.cancel(job.jobId);
```

见 `examples/node/web-navigator-example.ts`。 。 。 .

## 网络快速启动( Vite + PKCE)

使用 `@diskd-ai/sdk/browser` 和标准的OAuth2授权代码+PKCE重定向.

可运行实例 : `examples/web/` (见 `examples/README.md`) (中文(简体) ).

## 出版新版本

1.  弹出版本 `package.json`数字 :
    
    ```bash
    npm version patch   # 0.3.0 -> 0.3.1
    npm version minor   # 0.3.0 -> 0.4.0
    npm version major   # 0.3.0 -> 1.0.0
    ```
    
2.  按下承诺并标记:
    
    ```bash
    git push gitlab main --tags
    ```
    
3.  GitLab CI管道启动 `v*.*.*` 标记和自动 :
    
    -   构建工程
    -   运行单元测试和打字检查
    -   向 GitLab 软件包登记册发布
4.  验证时间 : `https://gitlab.iosya.com/upgraide-v2/platform-api/-/packages`
    

## 文件和实例

-   快速启动 : `docs/sdk-quickstart.md`
-   实例: `examples/README.md`
-   设计 : `docs/drive-session-sdk-design.md`

## 常见问题

### @diskd-ai/sdk 是什么？

DiskD 平台 API \(Drive, LLM 路由器, Agent Hub, MCP Hub, Telegram Userbot, Web 导航\) 的 SDK 版本

### 如何安装 @diskd-ai/sdk？

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

### @diskd-ai/sdk 支持 TypeScript 吗？

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

### @diskd-ai/sdk 支持 ESM 还是 CommonJS？

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

### @diskd-ai/sdk 需要什么版本的 Node\.js？

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

### @diskd-ai/sdk 可以商用吗？

@diskd-ai/sdk 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @diskd-ai/sdk 的下载量有多少？

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

### @diskd-ai/sdk 还在维护吗？

最新版本 7\.10\.0 发布于 2026/11/12（今天）；至今共发布 63 个版本，其中过去 12 个月发布了 63 个；首次发布于 2026/04/29。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

