@tbox-dev-js/sdk 0.1.4 → 0.1.6

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,19 +1,25 @@
1
1
  # @tbox-dev-js/sdk
2
2
 
3
- 百宝箱(Tbox)平台 JavaScript SDK,提供知识库管理、插件工具执行、LLM 对话、会话管理、高德地图等一站式客户端能力。
3
+ 百宝箱(Tbox)平台 JavaScript SDK,提供知识库管理、插件工具执行、LLM 对话、首页开场白、会话管理、高德地图等一站式客户端能力。
4
4
 
5
5
  **核心特性:**
6
6
 
7
7
  - 🚀 **配置驱动** — 通过 `knowledge.json` 业务配置文件驱动多知识库操作,AI Coding 友好
8
- - 🔐 **认证统一** SDK 共享一套 Token 配置,支持静态字符串或动态函数
8
+ - 🔐 **双鉴权模式**支持 B端(API Key)和 C端(Session)两种鉴权,自动桥接
9
9
  - 📦 **双格式支持** — 同时提供 ESM(`import`)和 CommonJS(`require`)构建产物
10
10
  - 🛡️ **类型安全** — 完整的 TypeScript 类型定义
11
- - 🧩 **模块化** — 知识库、插件、LLM、会话、地图等模块独立可用
11
+ - 🧩 **模块化** — 知识库、插件、LLM、首页、会话、地图等模块独立可用
12
12
 
13
13
  调用域名:`https://o.tbox.cn`
14
14
 
15
15
  ---
16
16
 
17
+ ## 获取 API Key
18
+
19
+ API Key 需要从 **百宝箱平台开发网关后台** 申请获取,用于 B端接口鉴权。
20
+
21
+ ---
22
+
17
23
  ## 安装
18
24
 
19
25
  ```bash
@@ -26,14 +32,53 @@ pnpm add @tbox-dev-js/sdk
26
32
 
27
33
  ---
28
34
 
35
+ ## 鉴权模式
36
+
37
+ SDK 支持两种鉴权模式,适用于不同的接口场景:
38
+
39
+ | 模式 | 请求头 | 适用客户端 | 说明 |
40
+ |------|--------|-----------|------|
41
+ | **B端** | `Authorization: <apiKey>` | `TboxPluginClient`、`TboxAppClient`、`TboxConversationClient`、`LlmClient`、`AmapClient`、`KnowledgeClient` | 服务端直接调用,使用 API Key |
42
+ | **C端** | `TBOXSESSIONID` + `X-Tbox-Channel` + `X-Tbox-AppId` | `TboxHomepageClient` | 面向终端用户,需先通过 `generateSession` 获取 Session |
43
+
44
+ **C端鉴权流程:**
45
+
46
+ ```
47
+ B端 apiKey → TboxAppClient.generateSession() → sessionId + channel → C端请求头
48
+ ```
49
+
50
+ ---
51
+
29
52
  ## 快速开始
30
53
 
54
+ ### 首页开场白(C端鉴权)
55
+
56
+ ```ts
57
+ import { TboxHomepageClient } from '@tbox-dev-js/sdk';
58
+
59
+ // 一步到位:自动获取 session 并创建客户端
60
+ const client = await TboxHomepageClient.create({
61
+ apiKey: 'your-api-key', // B端 API Key,从百宝箱平台开发网关后台获取
62
+ appId: 'your-app-id',
63
+ userId: 'user-123',
64
+ });
65
+
66
+ const result = await client.get({
67
+ agentId: 'your-agent-id',
68
+ extInfo: '{}',
69
+ });
70
+
71
+ if (result.success) {
72
+ console.log('开场白:', result.data?.prologue);
73
+ console.log('推荐问题:', result.data?.suggestQuestions);
74
+ }
75
+ ```
76
+
31
77
  ### 知识库管理(新架构 · 推荐)
32
78
 
33
79
  ```ts
34
80
  import { KnowledgeClient } from '@tbox-dev-js/sdk';
35
81
 
36
- // 从配置文件加载(支持多知识库)
37
82
  const client = new KnowledgeClient({
38
83
  token: process.env.TBOX_API_KEY,
39
84
  config: './config/knowledge.json',
@@ -48,7 +93,7 @@ console.log(results.data);
48
93
  const faqResults = await client.retrieve('FAQ', '如何重置密码?');
49
94
  ```
50
95
 
51
- ### 插件工具执行
96
+ ### 插件工具执行(B端鉴权)
52
97
 
53
98
  ```ts
54
99
  import { TboxPluginClient } from '@tbox-dev-js/sdk';
@@ -64,7 +109,7 @@ if (result.success) {
64
109
  }
65
110
  ```
66
111
 
67
- ### LLM 对话
112
+ ### LLM 对话(B端鉴权)
68
113
 
69
114
  ```ts
70
115
  import { LlmClient } from '@tbox-dev-js/sdk';
@@ -82,6 +127,68 @@ console.log(answer);
82
127
 
83
128
  ## 模块详解
84
129
 
130
+ ### TboxHomepageClient — 首页开场白(C端鉴权)
131
+
132
+ 封装 `/agent/v1/homepage` 下的接口,走 C端 Session 鉴权。
133
+
134
+ #### 构造方式
135
+
136
+ ```ts
137
+ import { TboxHomepageClient } from '@tbox-dev-js/sdk';
138
+
139
+ // 方式一:自动获取 session(推荐)
140
+ // 内部自动调用 generateSession 获取 sessionId + channel
141
+ const client = await TboxHomepageClient.create({
142
+ apiKey: 'your-api-key', // B端 API Key
143
+ appId: 'your-app-id', // 百宝箱应用 ID
144
+ userId: 'user-123', // 用户 ID
145
+ });
146
+
147
+ // 方式二:手动传入已有的 session
148
+ const client = new TboxHomepageClient({
149
+ session: {
150
+ sessionId: '00a42411d8anzMXjKa3UcibPq',
151
+ channel: 'alipay_mini_app',
152
+ appId: 'your-app-id',
153
+ },
154
+ });
155
+ ```
156
+
157
+ #### API 方法
158
+
159
+ | 方法 | 说明 | 示例 |
160
+ |------|------|------|
161
+ | `create(options)` | 静态工厂:自动获取 session 并创建客户端 | `TboxHomepageClient.create({ apiKey, appId, userId })` |
162
+ | `get(request)` | 获取首页开场白 | `client.get({ agentId: 'xxx', extInfo: '{}' })` |
163
+
164
+ ---
165
+
166
+ ### TboxAppClient — 应用服务 & C端鉴权桥接(B端鉴权)
167
+
168
+ 封装 `/openapi/v1/app` 下的接口。核心功能是 `generateSession`,用于将 B端 API Key 转换为 C端 Session 鉴权信息。
169
+
170
+ ```ts
171
+ import { TboxAppClient } from '@tbox-dev-js/sdk';
172
+
173
+ const client = new TboxAppClient({ apiKey: 'your-api-key' });
174
+
175
+ // 生成 sessionId + channel(C端鉴权的基础)
176
+ const result = await client.generateSession({
177
+ appId: 'your-app-id',
178
+ userId: 'user-123',
179
+ userInfo: [{ infoType: 'name', infoValue: '张三' }],
180
+ deviceInfo: { platform: 'IOS', appVersion: '1.0.0' },
181
+ });
182
+
183
+ if (result.success) {
184
+ console.log('sessionId:', result.data?.sessionId);
185
+ console.log('channel:', result.data?.channel);
186
+ // 可用于构造 C端鉴权的 TboxHomepageClient 等
187
+ }
188
+ ```
189
+
190
+ ---
191
+
85
192
  ### KnowledgeClient — 知识库管理
86
193
 
87
194
  配置驱动的多知识库客户端,支持语义检索、文档创建与更新。
@@ -124,7 +231,7 @@ const client = new KnowledgeClient({
124
231
  | 方法 | KnowledgeClient 签名 | KnowledgeScopedClient 签名 | 说明 |
125
232
  |------|----------------------|---------------------------|------|
126
233
  | `use` | `use(name)` | — | 获取绑定到指定知识库的 Scoped Client |
127
- | `list` | `list(name?, pageNo?, pageSize?)` | — | 查询知识库列表(共享,不绑定具体知识库) |
234
+ | `list` | `list(name?, pageNo?, pageSize?)` | — | 查询知识库列表 |
128
235
  | `retrieve` | `retrieve(name, query, options?)` | `retrieve(query, options?)` | 语义检索 |
129
236
  | `create` | `create(name, file, options?)` | `create(file, options?)` | 上传文件创建知识库文档 |
130
237
  | `update` | `update(name, file, options?)` | `update(file, options?)` | 更新知识库文档 |
@@ -172,7 +279,7 @@ const client = new KnowledgeClient({
172
279
 
173
280
  ---
174
281
 
175
- ### TboxPluginClient — 插件工具执行
282
+ ### TboxPluginClient — 插件工具执行(B端鉴权)
176
283
 
177
284
  封装 `/openapi/v1/plugin` 下的全部接口。
178
285
 
@@ -180,7 +287,7 @@ const client = new KnowledgeClient({
180
287
  import { TboxPluginClient } from '@tbox-dev-js/sdk';
181
288
 
182
289
  const client = new TboxPluginClient({
183
- apiKey: 'your-api-key',
290
+ apiKey: 'your-api-key', // 从百宝箱平台开发网关后台获取
184
291
  baseUrl: 'https://o.tbox.cn', // 可选,默认值
185
292
  timeout: 10000, // 可选,毫秒
186
293
  });
@@ -196,7 +303,7 @@ const client = new TboxPluginClient({
196
303
 
197
304
  ---
198
305
 
199
- ### LlmClient — LLM 大模型对话
306
+ ### LlmClient — LLM 大模型对话(B端鉴权)
200
307
 
201
308
  提供 OpenAI 兼容的 Chat Completions 接口,支持流式和非流式输出。
202
309
 
@@ -251,7 +358,7 @@ console.log(response.choices?.[0]?.message?.content);
251
358
 
252
359
  ---
253
360
 
254
- ### TboxConversationClient — 会话管理
361
+ ### TboxConversationClient — 会话管理(B端鉴权)
255
362
 
256
363
  封装 `/openapi/v1/conversation` 下的全部接口。
257
364
 
@@ -270,31 +377,7 @@ const client = new TboxConversationClient({ apiKey: 'your-api-key' });
270
377
 
271
378
  ---
272
379
 
273
- ### TboxAppClient应用服务
274
-
275
- 封装 `/openapi/v1/app` 下的接口。
276
-
277
- ```ts
278
- import { TboxAppClient } from '@tbox-dev-js/sdk';
279
-
280
- const client = new TboxAppClient({ apiKey: 'your-api-key' });
281
-
282
- // 生成免登录 sessionId
283
- const result = await client.generateSession({
284
- appId: 'your-app-id',
285
- userId: 'user-123',
286
- userInfo: [{ infoType: 'name', infoValue: '张三' }],
287
- deviceInfo: { platform: 'IOS', appVersion: '1.0.0' },
288
- });
289
-
290
- if (result.success) {
291
- console.log('sessionId:', result.data?.sessionId);
292
- }
293
- ```
294
-
295
- ---
296
-
297
- ### AmapClient — 高德地图服务
380
+ ### AmapClient高德地图服务(B端鉴权)
298
381
 
299
382
  通过百宝箱插件服务调用高德地图 API,支持天气查询、地理编码、路线规划等。
300
383
 
@@ -351,17 +434,19 @@ console.log(schema?.operations);
351
434
 
352
435
  ## 统一响应格式
353
436
 
354
- 旧架构客户端(`TboxPluginClient`、`TboxConversationClient`、`TboxAppClient`、`AmapClient`)的所有方法均返回 `SdkResponse<T>`:
437
+ 旧架构客户端(`TboxPluginClient`、`TboxConversationClient`、`TboxAppClient`、`TboxHomepageClient`、`AmapClient`)的所有方法均返回 `SdkResponse<T>`:
355
438
 
356
439
  ```ts
357
440
  interface SdkResponse<T> {
358
441
  success: boolean;
359
442
  data?: T;
360
- errorCode?: string;
361
- errorMsg?: string;
443
+ errorCode?: string; // 业务错误码或 HTTP 状态码
444
+ errorMsg?: string; // 错误描述(含服务端返回的中文信息)
362
445
  }
363
446
  ```
364
447
 
448
+ > HTTP 非 200 响应也会尝试解析服务端返回的 JSON 错误体,提取真实的 `errorCode` 和 `errorMsg`,而非仅返回 `HTTP_403` 等笼统信息。
449
+
365
450
  新架构客户端(`TboxAPI`、`KnowledgeClient`)直接返回业务数据,错误通过异常抛出:
366
451
 
367
452
  ```ts
@@ -404,23 +489,27 @@ tbox-js/
404
489
  │ │ ├── types.ts # 类型定义
405
490
  │ │ └── schema.ts # JSON Schema 定义
406
491
  │ ├── schema.ts # ResourceSchema 类型体系 + SchemaRegistry
407
- │ ├── plugin.ts # 插件工具执行客户端
408
- │ ├── conversation.ts # 会话管理客户端
409
- │ ├── app.ts # 应用服务客户端
410
- │ ├── amap.ts # 高德地图客户端
411
- │ ├── llm.ts # LLM 大模型对话客户端
412
- │ ├── http.ts # 旧架构 HTTP 封装
492
+ │ ├── homepage.ts # 首页开场白客户端(C端鉴权)
493
+ │ ├── plugin.ts # 插件工具执行客户端(B端鉴权)
494
+ │ ├── conversation.ts # 会话管理客户端(B端鉴权)
495
+ │ ├── app.ts # 应用服务客户端(B端鉴权 + C端桥接)
496
+ │ ├── amap.ts # 高德地图客户端(B端鉴权)
497
+ │ ├── llm.ts # LLM 大模型对话客户端(B端鉴权)
498
+ │ ├── http.ts # 底层 HTTP 封装(支持 B端/C端双鉴权)
413
499
  │ ├── error.ts # 错误类层级
414
500
  │ ├── resource.ts # APIResource 基类
415
501
  │ ├── constant.ts # 常量定义
416
- │ ├── types.ts # 旧架构类型定义
502
+ │ ├── types.ts # 类型定义(含鉴权类型)
417
503
  │ └── index.ts # 统一导出入口
418
504
  ├── config/
419
505
  │ └── knowledge.json # 知识库业务配置文件
506
+ ├── test/
507
+ │ ├── homepage.test.mjs # 首页开场白测试(含 C端鉴权流程)
508
+ │ └── knowledge.test.mjs # 知识库模块测试
420
509
  ├── docs/
421
510
  │ └── knowledge-client.md # KnowledgeClient 设计文档
422
511
  ├── scripts/
423
- │ └── publish.sh # npm 发布脚本
512
+ │ └── publish.sh # npm 发布脚本(自动切换 registry)
424
513
  ├── dist/ # 构建产物
425
514
  │ ├── index.cjs # CJS 格式
426
515
  │ ├── index.esm.js # ESM 格式
@@ -448,6 +537,31 @@ npm run build
448
537
  npm run clean
449
538
  ```
450
539
 
540
+ ## 测试
541
+
542
+ ```bash
543
+ # 首页开场白测试(含 C端鉴权完整流程)
544
+ node test/homepage.test.mjs <apiKey> <appId>
545
+
546
+ # 知识库模块测试
547
+ node test/knowledge.test.mjs <apiKey> [datasetId]
548
+ ```
549
+
550
+ ## 发布
551
+
552
+ ```bash
553
+ # 预览发布内容(Dry-run)
554
+ ./scripts/publish.sh
555
+
556
+ # 正式发布(自动切换到官方 npm 源,发布后恢复)
557
+ ./scripts/publish.sh --release
558
+
559
+ # 自动 bump 版本号并发布
560
+ ./scripts/publish.sh --patch # 0.1.0 → 0.1.1
561
+ ./scripts/publish.sh --minor # 0.1.0 → 0.2.0
562
+ ./scripts/publish.sh --major # 0.1.0 → 1.0.0
563
+ ```
564
+
451
565
  ## 许可证
452
566
 
453
567
  MIT
@@ -0,0 +1,79 @@
1
+ /**
2
+ * 百宝箱首页开场白 SDK - HomepageClient 核心类
3
+ *
4
+ * 封装 /agent/v1/homepage 下的接口。
5
+ * 该接口走 C端鉴权(TBOXSESSIONID + X-Tbox-Channel + X-Tbox-AppId)。
6
+ */
7
+ import type { TboxSessionClientConfig, CreateSessionClientOptions, SdkResponse, HomepageGetRequest, HomepageGetResponse } from './types';
8
+ /**
9
+ * 百宝箱首页开场白客户端(C端鉴权)
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { TboxHomepageClient } from '@tbox-dev-js/sdk';
14
+ *
15
+ * // 方式一:自动获取 session(推荐)
16
+ * const client = await TboxHomepageClient.create({
17
+ * apiKey: 'your-api-key',
18
+ * appId: '202508APhciU03604644',
19
+ * userId: 'user-123',
20
+ * });
21
+ *
22
+ * // 方式二:手动传入 session
23
+ * const client = new TboxHomepageClient({
24
+ * session: { sessionId: 'xxx', channel: 'alipay_mini_app', appId: '202508APhciU03604644' },
25
+ * });
26
+ *
27
+ * const result = await client.get({ agentId: '202508APhciU03604644' });
28
+ * if (result.success) {
29
+ * console.log('开场白:', result.data?.prologue);
30
+ * }
31
+ * ```
32
+ */
33
+ export declare class TboxHomepageClient {
34
+ private readonly http;
35
+ /**
36
+ * 使用 C端 Session 鉴权构造
37
+ */
38
+ constructor(config: TboxSessionClientConfig);
39
+ /**
40
+ * 便捷工厂方法:通过 B端 apiKey 自动获取 session 并创建 C端客户端
41
+ *
42
+ * 内部流程:
43
+ * 1. 使用 apiKey 调用 TboxAppClient.generateSession() 获取 sessionId + channel
44
+ * 2. 用获取到的 session 信息创建 C端鉴权的 HomepageClient
45
+ *
46
+ * @param options - 创建参数(apiKey、appId、userId)
47
+ * @returns 已鉴权的 TboxHomepageClient 实例
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const client = await TboxHomepageClient.create({
52
+ * apiKey: 'your-api-key',
53
+ * appId: '202508APhciU03604644',
54
+ * userId: 'user-123',
55
+ * });
56
+ * ```
57
+ */
58
+ static create(options: CreateSessionClientOptions): Promise<TboxHomepageClient>;
59
+ /**
60
+ * 获取首页开场白
61
+ *
62
+ * POST /agent/v1/homepage/get
63
+ *
64
+ * @param request - 请求参数,agentId 为必填
65
+ * @returns 开场白信息,包含开场白文本、推荐问题等
66
+ *
67
+ * @example
68
+ * ```ts
69
+ * const res = await client.get({
70
+ * agentId: '202508APhciU03604644',
71
+ * extInfo: '{}',
72
+ * });
73
+ * if (res.success) {
74
+ * console.log(res.data?.prologue);
75
+ * }
76
+ * ```
77
+ */
78
+ get(request: HomepageGetRequest): Promise<SdkResponse<HomepageGetResponse>>;
79
+ }
package/dist/http.d.ts CHANGED
@@ -1,23 +1,55 @@
1
1
  /**
2
2
  * 百宝箱插件服务 SDK - 底层 HTTP 请求封装
3
+ *
4
+ * 支持两种鉴权模式:
5
+ * - B端:Authorization header(API Key)
6
+ * - C端:TBOXSESSIONID + X-Tbox-Channel + X-Tbox-AppId headers
3
7
  */
4
- import type { SdkResponse } from './types';
8
+ import type { SdkResponse, SessionAuth } from './types';
5
9
  /** 默认调用域名 */
6
10
  export declare const DEFAULT_BASE_URL = "https://o.tbox.cn";
11
+ /**
12
+ * 鉴权模式
13
+ */
14
+ export type AuthMode = {
15
+ type: 'apiKey';
16
+ apiKey: string;
17
+ } | {
18
+ type: 'session';
19
+ session: SessionAuth;
20
+ };
7
21
  /** 内部 HTTP 客户端配置 */
8
22
  export interface HttpClientConfig {
23
+ baseUrl: string;
24
+ auth: AuthMode;
25
+ timeout?: number;
26
+ }
27
+ /**
28
+ * 旧版配置(向后兼容)
29
+ */
30
+ export interface LegacyHttpClientConfig {
9
31
  baseUrl: string;
10
32
  apiKey: string;
11
33
  timeout?: number;
12
34
  }
13
35
  /**
14
36
  * 底层 HTTP 客户端
37
+ *
38
+ * 支持两种构造方式:
39
+ * - 新版:传入 HttpClientConfig(含 AuthMode)
40
+ * - 旧版:传入 LegacyHttpClientConfig(含 apiKey,向后兼容)
15
41
  */
16
42
  export declare class HttpClient {
17
- private readonly baseUrl;
18
- private readonly apiKey;
43
+ private readonly _baseUrl;
44
+ private readonly auth;
19
45
  private readonly timeout?;
20
- constructor(config: HttpClientConfig);
46
+ constructor(config: HttpClientConfig | LegacyHttpClientConfig);
47
+ /** 获取 base URL */
48
+ get baseUrl(): string;
49
+ /** 获取鉴权请求头(供外部流式请求等场景使用) */
50
+ getAuthHeaders(): Record<string, string>;
51
+ /** 构建鉴权相关的请求头 */
52
+ private buildAuthHeaders;
21
53
  /** 构建通用请求头 */
22
54
  private buildHeaders;
23
55
  /** 构建 FormData 请求头(不设置 Content-Type,让浏览器自动处理 boundary) */