@tbox-dev-js/sdk 0.1.0

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.
@@ -0,0 +1,112 @@
1
+ /**
2
+ * 百宝箱会话管理 SDK - ConversationClient 核心类
3
+ *
4
+ * 封装 /openapi/v1/conversation 下的全部接口
5
+ */
6
+ import type { TboxPluginClientConfig, MessageQueryRequest, MessageInfo, ConversationQueryRequest, ConversationInfo, ConversationCreateRequest, MessageSaveRequest, PaginationResult, SdkResponse } from './types';
7
+ /**
8
+ * 百宝箱会话管理客户端
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { TboxConversationClient } from '@tbox/plugin-sdk';
13
+ *
14
+ * const client = new TboxConversationClient({ apiKey: 'your-api-key' });
15
+ *
16
+ * // 创建新会话
17
+ * const res = await client.createConversation({ agentId: 'app-id', userId: 'user-id' });
18
+ * if (res.success) {
19
+ * console.log('会话 ID:', res.data);
20
+ * }
21
+ * ```
22
+ */
23
+ export declare class TboxConversationClient {
24
+ private readonly http;
25
+ constructor(config: TboxPluginClientConfig);
26
+ /**
27
+ * 创建新会话
28
+ *
29
+ * POST /openapi/v1/conversation/create
30
+ *
31
+ * @param request - 创建会话请求,包含 agentId 和 userId
32
+ * @returns 新会话 ID(字符串)
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const res = await client.createConversation({
37
+ * agentId: 'your-app-id',
38
+ * userId: 'user-123',
39
+ * });
40
+ * if (res.success) {
41
+ * const conversationId = res.data;
42
+ * }
43
+ * ```
44
+ */
45
+ createConversation(request: ConversationCreateRequest): Promise<SdkResponse<string>>;
46
+ /**
47
+ * 查询会话列表(分页)
48
+ *
49
+ * POST /openapi/v1/conversation/list
50
+ *
51
+ * @param request - 查询请求,支持按 agentId、userId 过滤,支持分页
52
+ * @returns 分页会话列表
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * const res = await client.listConversations({
57
+ * agentId: 'your-app-id',
58
+ * userId: 'user-123',
59
+ * pageNum: 1,
60
+ * pageSize: 20,
61
+ * });
62
+ * if (res.success) {
63
+ * console.log(res.data?.list);
64
+ * }
65
+ * ```
66
+ */
67
+ listConversations(request: ConversationQueryRequest): Promise<SdkResponse<PaginationResult<ConversationInfo>>>;
68
+ /**
69
+ * 查询消息列表(分页)
70
+ *
71
+ * POST /openapi/v1/conversation/message/list
72
+ *
73
+ * @param request - 查询请求,支持按 conversationId、agentId、userId 过滤,支持分页
74
+ * @returns 分页消息列表
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const res = await client.listMessages({
79
+ * conversationId: 'conv-id-xxx',
80
+ * pageNum: 1,
81
+ * pageSize: 20,
82
+ * });
83
+ * if (res.success) {
84
+ * console.log(res.data?.list);
85
+ * }
86
+ * ```
87
+ */
88
+ listMessages(request: MessageQueryRequest): Promise<SdkResponse<PaginationResult<MessageInfo>>>;
89
+ /**
90
+ * 新增会话消息
91
+ *
92
+ * POST /openapi/v1/conversation/message/save
93
+ *
94
+ * 将一条对话消息(问题 + 回答)保存到指定会话中。
95
+ *
96
+ * @param request - 保存消息请求
97
+ * @returns 消息 ID(字符串)
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * const res = await client.saveMessage({
102
+ * conversationId: 'conv-id-xxx',
103
+ * query: '今天天气怎么样?',
104
+ * answer: '今天杭州晴天,25°C。',
105
+ * });
106
+ * if (res.success) {
107
+ * const messageId = res.data;
108
+ * }
109
+ * ```
110
+ */
111
+ saveMessage(request: MessageSaveRequest): Promise<SdkResponse<string>>;
112
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @tbox/sdk — APIClient 核心基类
3
+ *
4
+ * 对齐 coze-js 的 core.ts 设计:
5
+ * - Token 管理(静态字符串 / 动态函数)
6
+ * - 请求构建(JSON / FormData / SSE)
7
+ * - 响应解包(兼容多种服务端格式)
8
+ * - 错误映射(HTTP 状态码 → 错误子类)
9
+ */
10
+ /** SDK 初始化配置 */
11
+ export interface ClientOptions {
12
+ /**
13
+ * API Key or dynamic token function.
14
+ * String is used directly as Bearer Token; function is called before each request.
15
+ */
16
+ token: string | (() => string | Promise<string>);
17
+ /** API base URL. @default "https://o.tbox.cn" */
18
+ baseURL?: string;
19
+ /** Request timeout in milliseconds. @default undefined (no timeout) */
20
+ timeout?: number;
21
+ /** Enable debug logging. @default false */
22
+ debug?: boolean;
23
+ /** Custom headers merged into every request. */
24
+ headers?: Record<string, string>;
25
+ }
26
+ /** Per-request option overrides */
27
+ export interface RequestOptions {
28
+ timeout?: number;
29
+ headers?: Record<string, string>;
30
+ debug?: boolean;
31
+ signal?: AbortSignal;
32
+ baseURL?: string;
33
+ }
34
+ /** SSE event object */
35
+ export interface SSEEvent {
36
+ data: string;
37
+ event?: string;
38
+ id?: string;
39
+ retry?: number;
40
+ }
41
+ /**
42
+ * Core request engine. All Resource classes call methods on this via `this._client`.
43
+ */
44
+ export declare class APIClient {
45
+ protected baseURL: string;
46
+ protected token: string | (() => string | Promise<string>);
47
+ protected timeout?: number;
48
+ protected debug: boolean;
49
+ protected defaultHeaders?: Record<string, string>;
50
+ constructor(options: ClientOptions);
51
+ /** Resolve the current token value (supports async token functions). */
52
+ protected getToken(): Promise<string>;
53
+ /** JSON POST request — returns unwrapped business data. */
54
+ post<Rsp>(path: string, body?: unknown, options?: RequestOptions): Promise<Rsp>;
55
+ /** GET request — query params auto-appended to URL. */
56
+ get<Rsp>(path: string, params?: Record<string, string | number | boolean | undefined>, options?: RequestOptions): Promise<Rsp>;
57
+ /** FormData POST request (file uploads). Content-Type is set automatically by fetch. */
58
+ postFormData<Rsp>(path: string, formData: FormData, options?: RequestOptions): Promise<Rsp>;
59
+ /** SSE streaming POST request — yields SSEEvent objects. */
60
+ postStream(path: string, body?: unknown, options?: RequestOptions): AsyncGenerator<SSEEvent>;
61
+ private buildUrl;
62
+ private buildHeaders;
63
+ private fetchWithTimeout;
64
+ private parseAndUnwrap;
65
+ /**
66
+ * Unwrap server response — extract business data from various envelope formats.
67
+ *
68
+ * Priority: data > resultObj > result.response (knowledge) > result > raw
69
+ */
70
+ private unwrapResponse;
71
+ /** Parse JSON response using ArrayBuffer + TextDecoder for correct UTF-8 handling. */
72
+ private parseJsonResponse;
73
+ /** Safely parse JSON without throwing (for error responses). */
74
+ private safeParseJson;
75
+ /** Parse SSE stream from ReadableStream. */
76
+ private parseSSEStream;
77
+ /** Output debug log when debug mode is enabled. */
78
+ protected debugLog(options: RequestOptions | undefined, ...messages: unknown[]): void;
79
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * @tbox/sdk — 分层错误体系
3
+ *
4
+ * 对齐 coze-js 的 error.ts 设计:
5
+ * TboxError → APIError → 按 HTTP 状态码的子类
6
+ */
7
+ /** 所有 SDK 错误的基类 */
8
+ export declare class TboxError extends Error {
9
+ constructor(message: string);
10
+ }
11
+ /** 服务端原始响应结构(用于错误工厂) */
12
+ interface RawErrorBody {
13
+ success?: boolean;
14
+ errorCode?: string;
15
+ code?: string | number;
16
+ resultCode?: string;
17
+ errorMsg?: string;
18
+ msg?: string;
19
+ resultDesc?: string;
20
+ traceId?: string;
21
+ }
22
+ /** API 调用错误,包含 HTTP 状态码和业务错误信息 */
23
+ export declare class APIError extends TboxError {
24
+ readonly status: number;
25
+ readonly errorCode?: string;
26
+ readonly errorMsg?: string;
27
+ readonly traceId?: string;
28
+ readonly rawResponse?: unknown;
29
+ constructor(status: number, errorCode: string | undefined, errorMsg: string | undefined, traceId: string | undefined, rawResponse?: unknown);
30
+ /**
31
+ * Factory: create the appropriate error subclass based on HTTP status code.
32
+ */
33
+ static generate(status: number, body?: RawErrorBody): APIError;
34
+ }
35
+ export declare class BadRequestError extends APIError {
36
+ constructor(errorCode?: string, errorMsg?: string, traceId?: string, rawResponse?: unknown);
37
+ }
38
+ export declare class AuthenticationError extends APIError {
39
+ constructor(errorCode?: string, errorMsg?: string, traceId?: string, rawResponse?: unknown);
40
+ }
41
+ export declare class ForbiddenError extends APIError {
42
+ constructor(errorCode?: string, errorMsg?: string, traceId?: string, rawResponse?: unknown);
43
+ }
44
+ export declare class NotFoundError extends APIError {
45
+ constructor(errorCode?: string, errorMsg?: string, traceId?: string, rawResponse?: unknown);
46
+ }
47
+ export declare class RateLimitError extends APIError {
48
+ constructor(errorCode?: string, errorMsg?: string, traceId?: string, rawResponse?: unknown);
49
+ }
50
+ export declare class InternalServerError extends APIError {
51
+ constructor(errorCode?: string, errorMsg?: string, traceId?: string, rawResponse?: unknown);
52
+ }
53
+ export declare class GatewayError extends APIError {
54
+ constructor(errorCode?: string, errorMsg?: string, traceId?: string, rawResponse?: unknown);
55
+ }
56
+ /** Network unreachable error */
57
+ export declare class NetworkError extends TboxError {
58
+ readonly cause?: Error;
59
+ constructor(message: string, cause?: Error);
60
+ }
61
+ /** Request timeout error */
62
+ export declare class TimeoutError extends TboxError {
63
+ readonly timeout: number;
64
+ constructor(timeout: number);
65
+ }
66
+ /** JSON parse error */
67
+ export declare class ParseError extends TboxError {
68
+ readonly responseText?: string;
69
+ constructor(message: string, responseText?: string);
70
+ }
71
+ export {};
package/dist/http.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * 百宝箱插件服务 SDK - 底层 HTTP 请求封装
3
+ */
4
+ import type { SdkResponse } from './types';
5
+ /** 默认调用域名 */
6
+ export declare const DEFAULT_BASE_URL = "https://o.tbox.cn";
7
+ /** 内部 HTTP 客户端配置 */
8
+ export interface HttpClientConfig {
9
+ baseUrl: string;
10
+ apiKey: string;
11
+ timeout?: number;
12
+ }
13
+ /**
14
+ * 底层 HTTP 客户端
15
+ */
16
+ export declare class HttpClient {
17
+ private readonly baseUrl;
18
+ private readonly apiKey;
19
+ private readonly timeout?;
20
+ constructor(config: HttpClientConfig);
21
+ /** 构建通用请求头 */
22
+ private buildHeaders;
23
+ /** 构建 FormData 请求头(不设置 Content-Type,让浏览器自动处理 boundary) */
24
+ private buildHeadersForFormData;
25
+ /** 发起 fetch,支持可选超时 */
26
+ private fetchWithTimeout;
27
+ /**
28
+ * POST 请求
29
+ */
30
+ post<T>(path: string, body: unknown, queryParams?: Record<string, string>): Promise<SdkResponse<T>>;
31
+ /**
32
+ * POST FormData 请求(用于文件上传)
33
+ */
34
+ postFormData<T>(path: string, formData: FormData, queryParams?: Record<string, string>): Promise<SdkResponse<T>>;
35
+ /**
36
+ * GET 请求
37
+ */
38
+ get<T>(path: string, queryParams?: Record<string, string>): Promise<SdkResponse<T>>;
39
+ /** 构建完整 URL(含 query string) */
40
+ private buildUrl;
41
+ /** 解析响应体 */
42
+ private parseResponse;
43
+ }