@reachv2/sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @reachv2/sdk
2
2
 
3
- Reach(reach.codes)统一平台的官方 TypeScript SDK —— 由 aiservicer SDK(crm 域,18 资源)与 aiops-saas SDK(social 域,5 资源)合并而来(P2.4)。一个客户端覆盖客服 / 销售引导、社群维护与社媒运营全部资源。
3
+ Reach(reach.codes)统一平台的官方 TypeScript SDK —— 由 aiservicer SDK(crm 域,18 资源)与 aiops-saas SDK(social 域,5 资源)合并而来(P2.4),现统一为 **27 个资源类 / 203 个资源方法**。一个客户端覆盖客服 / 销售引导、社群维护与社媒运营全部资源(含效果追踪、SEO/GEO、内容规则与数据源)。
4
4
 
5
5
  - 运行时:Node.js >= 18(ESM)
6
6
  - 类型:完整 TypeScript 类型定义(自带 `dist/index.d.ts`)
@@ -8,7 +8,7 @@ Reach(reach.codes)统一平台的官方 TypeScript SDK —— 由 aiservicer
8
8
 
9
9
  ## 文档
10
10
 
11
- - **[API Reference](docs/API-REFERENCE.md)**(P2.6,v0.2.0 扩展统一租户):全部 27 个资源类 + `ReachClient` 共 **203 个资源方法**(另含 `ReachClient.setToken` / `request`)的签名 / 端点 / 参数 / 返回类型 / 错误 / 示例,与 `sdk/src` 源码一一对应。
11
+ - **[API Reference](docs/API-REFERENCE.md)**(P2.6,v0.3.0 补 P-REACH 四域):全部 27 个资源类 + `ReachClient` 共 **203 个资源方法**(另含 `ReachClient.setToken` / `request`)的签名 / 端点 / 参数 / 返回类型 / 错误 / 示例,与 `sdk/src` 源码一一对应。
12
12
 
13
13
  ## 安装
14
14
 
@@ -42,21 +42,25 @@ const { reply, transaction } = await client.agents.chat("bot-xxx", {
42
42
  const post = await client.content.generate("AI trends", "twitter", "professional");
43
43
  ```
44
44
 
45
- ### 方式二:JWT 登录(需数学验证码)
45
+ ### 方式二:JWT 登录(邮箱 + 密码,图形验证码可选)
46
46
 
47
47
  ```ts
48
48
  const client = new ReachClient({ baseUrl: "https://reach.codes", apiKey: "reach-xxx" });
49
49
 
50
- const { token, svg } = await client.auth.getCaptcha();
51
- const svgText = Buffer.from(svg.replace(/^data:image\/svg\+xml;base64,/, ""), "base64").toString("utf-8");
52
- const m = svgText.match(/(\d+)\s*([+-])\s*(\d+)/)!;
50
+ // 1) 取图形验证码(算式图):{ captchaId, image, expiresIn },image 为 data:image/svg+xml;base64
51
+ const { captchaId, image } = await client.auth.getCaptcha();
52
+ const svg = Buffer.from(image.replace(/^data:image\/svg\+xml;base64,/, ""), "base64").toString("utf-8");
53
+ const m = svg.match(/(\d+)\s*([+-])\s*(\d+)/)!;
53
54
  const answer = m[2] === "+" ? Number(m[1]) + Number(m[3]) : Number(m[1]) - Number(m[3]);
54
55
 
55
- const { token: jwt } = await client.auth.login("username", "password", { token, answer });
56
- client.setToken(jwt); // SDK 不会自动接线,需手动 setToken 切换为 JWT 模式
56
+ // 2) 登录:返回 { accessToken, refreshToken, account }
57
+ const { accessToken } = await client.auth.login("user@example.com", "password", { token: captchaId, answer });
58
+ client.setToken(accessToken); // SDK 不会自动接线,需手动 setToken 切换为 JWT 模式
57
59
  ```
58
60
 
59
- > **JWT 续期约定**:`login` 签发 7 天有效 JWT 且无 refresh 机制,请提前 1 天重新登录并 `setToken`。
61
+ > **JWT 续期**:`accessToken` 默认 2h(`JWT_ACCESS_TTL`),`refreshToken` 30d(`JWT_REFRESH_TTL_SEC`)。
62
+ > SDK 未封装 refresh;过期后用 `await client.request("POST", "/api/auth/refresh", { refreshToken })` 轮换并 `setToken`。
63
+ > 启用 MFA 的账户 `login` 返回 `{ mfaRequired: true, account }`(不带 token),需携带 `mfaCode`(TOTP/恢复码)重试。
60
64
 
61
65
  ## 认证方式
62
66
 
@@ -73,10 +77,12 @@ client.setToken(jwt); // SDK 不会自动接线,需手动 setToken 切换为 J
73
77
  Reach 将自身能力以 **MCP(Model Context Protocol)** 形式对外开放(Streamable HTTP,路径 `/mcp`),
74
78
  让支持 MCP 的客户端(Claude Desktop / Cursor / 自研 Agent)可直接调用 crm + social 域工具。
75
79
 
76
- - 端点:`https://reach.codes/mcp`(探活:`GET https://reach.codes/mcp/health`)
77
- - 鉴权:`X-API-Key: reach-xxx` 或 `Authorization: Bearer sk-xxx`(复用 REST API Key,租户隔离由此 Key 决定)
78
- - 权限:MCP 工具调用为写操作,API Key 需含 `write` / `all` scope
79
- - 工具域:按平台配置白名单裁剪(当前 `crm` / `social`),`tools/list` 返回实际可用集合
80
+ - 端点:`https://reach.codes/mcp`(探活:`GET https://reach.codes/mcp/health`,返回 `{ status, tools, publicMode, domains }`)
81
+ - 鉴权:`X-API-Key: reach-xxx` 或 `Authorization: Bearer <key>`(复用 REST API Key,租户隔离由此 Key 决定)
82
+ - 权限(读 / 写门禁):只读 Key(scope 不含 `write` / `all` / `*`)**只能调用读工具**(工具名按 `_` 分词命中
83
+ `list` / `get` / `status` / `query` / `summary` / `check` / `history` / `usage` … 即视为读,未命中一律按写拒绝);
84
+ 写工具需 `write` / `all` / `*` scope,否则 `tools/call` 返回 JSON-RPC `-32001 requires a write-scoped API key`
85
+ - 工具规模:**269**(crm 87 + social 182),按域白名单裁剪(当前 `crm` / `social`),`tools/list` 返回实际可用集合
80
86
 
81
87
  会话按 MCP Streamable HTTP 规范:先 `initialize` 取得 `mcp-session-id`,
82
88
  再发 `notifications/initialized`,之后 `tools/call`,结束时 `DELETE` 会话。
@@ -158,7 +164,7 @@ const client = new ReachClient({
158
164
  | `client.tts` | 文本转语音(synthesize/voices/history) | Server |
159
165
  | `client.accounts` | 社媒账号矩阵(list/connect) | Server |
160
166
 
161
- ### social 域 — P-REACH(效果 / SEO-GEO / 内容规则 / 数据源,v0.2.0 新增)
167
+ ### social 域 — P-REACH(效果 / SEO-GEO / 内容规则 / 数据源,v0.3.0 新增)
162
168
 
163
169
  | 资源 | 主要能力 | API 域 |
164
170
  |------|----------|--------|
@@ -185,18 +191,25 @@ const client = new ReachClient({
185
191
  ```bash
186
192
  cd sdk
187
193
  npm install
188
- npm run build # tsc → dist
189
- npm test # node --test test/(冒烟:导出 + 资源方法面)
194
+ npm run build # clean + tsc → dist
195
+ npm test # node --test,覆盖 test/*.test.mjs
190
196
  ```
191
197
 
198
+ | 测试文件 | 覆盖 |
199
+ |----------|------|
200
+ | `test/client.test.mjs` | ReachClient 核心行为:构造校验(`MISSING_AUTH`)、认证 Header、双 base 路由、body 序列化、错误语义 |
201
+ | `test/resources.test.mjs` | **全量** 27 资源类 203 方法的 method / path / body 断言(要求每个方法至少被一条用例覆盖) |
202
+ | `test/smoke.test.mjs` | 导出面 + 资源方法面快照 |
203
+
204
+ > 测试跑 **`dist/` 产物**,改完 `src/` 必须先 `npm run build`。
205
+
192
206
  ## 发布流程(维护者)
193
207
 
194
208
  ```bash
195
209
  cd sdk
196
210
  npm version <minor> --no-git-tag-version # 小版本递增,紧贴 API 变更
197
- npm run build # tsc → dist
198
- npm pack # 本地验证发布产物(含 dist + README)
199
- npm publish # token 在 ~/.npmrc(reachv2 组织)
211
+ npm publish # prepublishOnly 自动执行 build + test;产物仅含 dist(package.json files 字段)
212
+ # 可选:npm pack 本地检查 tarball 内容
200
213
  cd .. && git add sdk/package.json sdk/package-lock.json
201
214
  git commit -m "chore(sdk): 发布 @reachv2/sdk@<version>"
202
215
  ```
package/dist/index.d.ts CHANGED
@@ -27,5 +27,5 @@ export { DataSourcesResource } from "./resources/data-sources.js";
27
27
  export { HealthResource } from "./resources/health.js";
28
28
  export { TenantsResource } from "./resources/tenants.js";
29
29
  export { TeamResource } from "./resources/team.js";
30
- export type { ReachClientConfig, BotType, AgentType, BotStatus, ChannelType, ChannelStatus, KnowledgeStatus, Pagination, PaginatedResponse, Project, ProjectCreateParams, ProjectUpdateParams, TransactionBotConfig, Bot, BotStats, BotCreateParams, BotUpdateParams, KnowledgeDoc, KnowledgeRecommendation, Channel, ChannelConfigureParams, Conversation, Message, ChatParams, ChatResponse, ChatToolDefinition, ChatToolFunction, DashboardData, BotMetrics, TxIntent, TxStep, PreparedTransaction, ContractInfo, ContractMethod, SimulationResult, DecodedCalldata, ProtocolSummary, ProtocolRegistryEntry, ChainDeployment, ProtocolAction, ParamHint, WalletChallenge, WalletLoginParams, AuthResult, CaptchaResponse, CaptchaAnswer, AgentXAgent, AgentXAgentDetail, AgentXMarketplaceResult, AgentXSubscriptionPlans, AgentXSubscriptionCheck, AgentXAgentContext, AgentXPublishParams, AgentXPublishResult, AgentXSkill, AgentXSkillCreateParams, AgentXAgentStatus, AgentXAgentUsage, AgentXSubscriptionDetail, AgentXSubscriptionList, ServerChatParams, ServerChatResponse, ChatUsage, ChatUsageSummary, AgentSummary, AgentListResult, AgentListParams, AgentChainInfo, AgentActionType, AgentCapabilities, AgentChatParams, AgentChatResult, LightRAGKeyInfo, LightRAGDocumentParams, LightRAGQueryParams, LightRAGQueryResult, LightRAGBatchItem, LightRAGBatchError, LightRAGBatchResult, GlobalAnalytics, AdminDashboard, AdminMerchant, AdminMerchantDetail, AdminBillingRecord, AdminCreateBillingParams, LlmSettings, LlmUpdateParams, ConversationTask, ConversationTaskStatus, ConversationSession, ConversationCapabilities, ConversationMessage, OrchestrationTaskParams, OrchestrateParams, OrchestratedTaskResult, OrchestrateResult, ScheduledTask, ScheduledTaskStatus, ScheduledTaskTriggerType, MonitorConnectorKind, EnterpriseDoc, MonitorConnector, MonitorEvent, MerchantAbi, MerchantAbiCreateParams, SimpleResult, TenantType, TenantMemberRole, TenantMemberStatus, Tenant, TenantMemberInfo, TenantInvite, PublicInviteInfo, InviteAcceptResult, MemberRoleUpdateResult, TransferOwnerResult, TeamMemberItem, TeamInviteResult, HealthInfo, } from "./types.js";
30
+ export type { ReachClientConfig, BotType, AgentType, BotStatus, ChannelType, ChannelStatus, KnowledgeStatus, Pagination, PaginatedResponse, Project, ProjectCreateParams, ProjectUpdateParams, TransactionBotConfig, Bot, BotStats, BotCreateParams, BotUpdateParams, KnowledgeDoc, KnowledgeRecommendation, Channel, ChannelConfigureParams, Conversation, Message, ChatParams, ChatResponse, ChatToolDefinition, ChatToolFunction, DashboardData, BotMetrics, TxIntent, TxStep, PreparedTransaction, ContractInfo, ContractMethod, SimulationResult, DecodedCalldata, ProtocolSummary, ProtocolRegistryEntry, ChainDeployment, ProtocolAction, ParamHint, WalletNonce, WalletLoginParams, AuthAccount, AuthResult, MfaRequiredResult, CaptchaResponse, CaptchaAnswer, AgentXAgent, AgentXAgentDetail, AgentXMarketplaceResult, AgentXSubscriptionPlans, AgentXSubscriptionCheck, AgentXAgentContext, AgentXPublishParams, AgentXPublishResult, AgentXSkill, AgentXSkillCreateParams, AgentXAgentStatus, AgentXAgentUsage, AgentXSubscriptionDetail, AgentXSubscriptionList, ServerChatParams, ServerChatResponse, ChatUsage, ChatUsageSummary, AgentSummary, AgentListResult, AgentListParams, AgentChainInfo, AgentActionType, AgentCapabilities, AgentChatParams, AgentChatResult, LightRAGKeyInfo, LightRAGDocumentParams, LightRAGQueryParams, LightRAGQueryResult, LightRAGBatchItem, LightRAGBatchError, LightRAGBatchResult, GlobalAnalytics, AdminDashboard, AdminMerchant, AdminMerchantDetail, AdminBillingRecord, AdminCreateBillingParams, LlmSettings, LlmUpdateParams, ConversationTask, ConversationTaskStatus, ConversationSession, ConversationCapabilities, ConversationMessage, OrchestrationTaskParams, OrchestrateParams, OrchestratedTaskResult, OrchestrateResult, ScheduledTask, ScheduledTaskStatus, ScheduledTaskTriggerType, MonitorConnectorKind, EnterpriseDoc, MonitorConnector, MonitorEvent, MerchantAbi, MerchantAbiCreateParams, SimpleResult, TenantType, TenantMemberRole, TenantMemberStatus, Tenant, TenantMemberInfo, TenantInvite, PublicInviteInfo, InviteAcceptResult, MemberRoleUpdateResult, TransferOwnerResult, TeamMemberItem, TeamInviteResult, HealthInfo, } from "./types.js";
31
31
  export type { ApiKeyInfo, ApiKeyCreated } from "./resources/api-key.js";
@@ -1,11 +1,14 @@
1
- import { RequestMethod, WalletChallenge, WalletLoginParams, AuthResult, CaptchaResponse, CaptchaAnswer } from "../types.js";
1
+ import { RequestMethod, WalletNonce, WalletLoginParams, AuthResult, CaptchaResponse, CaptchaAnswer } from "../types.js";
2
2
  type RequestFn = <T>(method: RequestMethod, path: string, body?: unknown) => Promise<T>;
3
3
  export declare class AuthResource {
4
4
  private request;
5
5
  constructor(request: RequestFn);
6
- /** 获取钱包签名挑战 */
7
- getChallenge(walletAddress: string): Promise<WalletChallenge>;
8
- /** 钱包签名登录,返回 token + user */
6
+ /**
7
+ * 获取钱包签名挑战(nonce)。
8
+ * 服务端签发后存 Redis 10 分钟一次性;签名对象即返回的 nonce 字符串本体。
9
+ */
10
+ getChallenge(wallet: string): Promise<WalletNonce>;
11
+ /** 钱包签名登录(server 契约:{ wallet, nonce, signature }) */
9
12
  walletLogin(params: WalletLoginParams): Promise<AuthResult>;
10
13
  /**
11
14
  * 获取图形验证码(login/register 前置,可选)。
@@ -2,11 +2,14 @@ export class AuthResource {
2
2
  constructor(request) {
3
3
  this.request = request;
4
4
  }
5
- /** 获取钱包签名挑战 */
6
- getChallenge(walletAddress) {
7
- return this.request("POST", "/api/auth/wallet-challenge", { address: walletAddress });
5
+ /**
6
+ * 获取钱包签名挑战(nonce)。
7
+ * 服务端签发后存 Redis 10 分钟一次性;签名对象即返回的 nonce 字符串本体。
8
+ */
9
+ getChallenge(wallet) {
10
+ return this.request("POST", "/api/auth/wallet-nonce", { wallet });
8
11
  }
9
- /** 钱包签名登录,返回 token + user */
12
+ /** 钱包签名登录(server 契约:{ wallet, nonce, signature }) */
10
13
  walletLogin(params) {
11
14
  return this.request("POST", "/api/auth/wallet-login", params);
12
15
  }
package/dist/types.d.ts CHANGED
@@ -270,27 +270,34 @@ export interface ParamHint {
270
270
  source: "user_input" | "derived" | "user_address" | "computed";
271
271
  computeHint?: string;
272
272
  }
273
- export interface WalletChallenge {
274
- challenge: string;
275
- timestamp: number;
273
+ /** 钱包登录 nonce(10 分钟一次性;签名对象即该 nonce 字符串本体) */
274
+ export interface WalletNonce {
276
275
  nonce: string;
277
276
  }
277
+ /** 钱包签名登录入参(server 契约:签名对象为 nonce) */
278
278
  export interface WalletLoginParams {
279
- walletAddress: string;
280
- signature: string;
281
- timestamp: number;
279
+ wallet: string;
282
280
  nonce: string;
281
+ signature: string;
282
+ }
283
+ /** 账户公开信息(server `publicAccount` 投影) */
284
+ export interface AuthAccount {
285
+ id: string;
286
+ email: string | null;
287
+ wallet: string | null;
288
+ mfaEnabled: boolean;
289
+ status: string;
283
290
  }
291
+ /** 登录 / 注册 / 钱包登录成功:server 统一返回 { accessToken, refreshToken, account } */
284
292
  export interface AuthResult {
285
- token: string;
286
- user: {
287
- id: string;
288
- username: string;
289
- role: string;
290
- name: string;
291
- email: string;
292
- walletAddress?: string;
293
- };
293
+ accessToken: string;
294
+ refreshToken: string;
295
+ account: AuthAccount;
296
+ }
297
+ /** MFA 账户未携带 mfaCode 时的响应(不签发 token,校验后重调原端点) */
298
+ export interface MfaRequiredResult {
299
+ mfaRequired: true;
300
+ account: AuthAccount;
294
301
  }
295
302
  /** 图形验证码(login/register 前置,可选):image 为 data URI,算式恒为非负结果 */
296
303
  export interface CaptchaResponse {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reachv2/sdk",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Reach unified REST API client library for TypeScript — crm 域(AgentApi/Project/Bot/Knowledge/Channel/Conversation/Transaction/Auth/Chat/ApiKey/LightRAG/Orchestration/ScheduledTasks/Internal/Abis/Admin)+ social 域(Content/Tts/Accounts/Effect 效果追踪/SeoGeo SEO-GEO 矩阵/ContentRules 内容规则引擎/DataSources 数据源)+ 统一 DashboardApi(crm/social 看板)+ 统一租户成员模型(Tenants/Team/Health,G-1~G-3)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",