@lark-apaas/client-capability 0.0.1-alpha.1 → 0.0.1-alpha.3
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 +13 -1
- package/dist/index.cjs +6 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -40,12 +40,13 @@ console.log(result);
|
|
|
40
40
|
```typescript
|
|
41
41
|
import { capabilityClient } from '@lark-apaas/client-capability';
|
|
42
42
|
|
|
43
|
+
// 泛型参数 T 表示 delta 的类型(插件的 OutputSchema)
|
|
43
44
|
const stream = capabilityClient.load('ai_chat').callStream<{ content: string }>('chat', {
|
|
44
45
|
message: 'hello',
|
|
45
46
|
});
|
|
46
47
|
|
|
47
48
|
for await (const chunk of stream) {
|
|
48
|
-
console.log(chunk.content);
|
|
49
|
+
console.log(chunk.content); // chunk 即为 delta,类型为 { content: string }
|
|
49
50
|
}
|
|
50
51
|
```
|
|
51
52
|
|
|
@@ -55,6 +56,8 @@ for await (const chunk of stream) {
|
|
|
55
56
|
import { createClient } from '@lark-apaas/client-capability';
|
|
56
57
|
|
|
57
58
|
const client = createClient({
|
|
59
|
+
// 全局路径前缀(线上环境)
|
|
60
|
+
baseURL: '/spark/a', // 请求路径: /spark/a/api/capability/xxx
|
|
58
61
|
fetchOptions: {
|
|
59
62
|
credentials: 'include',
|
|
60
63
|
headers: {
|
|
@@ -66,6 +69,13 @@ const client = createClient({
|
|
|
66
69
|
const result = await client.load('xxx').call('run', params);
|
|
67
70
|
```
|
|
68
71
|
|
|
72
|
+
**baseURL 配置说明:**
|
|
73
|
+
|
|
74
|
+
| 环境 | baseURL | 实际请求路径 |
|
|
75
|
+
|-----|---------|-------------|
|
|
76
|
+
| 本地开发 | `''`(默认) | `/api/capability/xxx` |
|
|
77
|
+
| 线上环境 | `'/spark/a'` | `/spark/a/api/capability/xxx` |
|
|
78
|
+
|
|
69
79
|
### 错误处理
|
|
70
80
|
|
|
71
81
|
```typescript
|
|
@@ -154,6 +164,8 @@ interface CapabilityExecutor {
|
|
|
154
164
|
|
|
155
165
|
```typescript
|
|
156
166
|
interface CapabilityClientOptions {
|
|
167
|
+
/** 全局路径前缀,默认 ''。例如线上环境可设置为 '/spark/a' */
|
|
168
|
+
baseURL?: string;
|
|
157
169
|
/** 自定义 fetch 配置 */
|
|
158
170
|
fetchOptions?: RequestInit;
|
|
159
171
|
}
|
package/dist/index.cjs
CHANGED
|
@@ -96,7 +96,9 @@ var ExecutionError = _ExecutionError;
|
|
|
96
96
|
var _CapabilityClient = class _CapabilityClient {
|
|
97
97
|
constructor(options) {
|
|
98
98
|
__publicField(this, "options");
|
|
99
|
+
__publicField(this, "baseURL");
|
|
99
100
|
this.options = options ?? {};
|
|
101
|
+
this.baseURL = (options?.baseURL ?? "").replace(/\/+$/, "");
|
|
100
102
|
}
|
|
101
103
|
/**
|
|
102
104
|
* 加载能力,返回执行器
|
|
@@ -117,7 +119,7 @@ var _CapabilityClient = class _CapabilityClient {
|
|
|
117
119
|
};
|
|
118
120
|
}
|
|
119
121
|
async executeCall(capabilityId, action, params) {
|
|
120
|
-
const url =
|
|
122
|
+
const url = `${this.baseURL}/api/capability/${capabilityId}`;
|
|
121
123
|
try {
|
|
122
124
|
const response = await fetch(url, {
|
|
123
125
|
method: "POST",
|
|
@@ -155,7 +157,7 @@ var _CapabilityClient = class _CapabilityClient {
|
|
|
155
157
|
}
|
|
156
158
|
}
|
|
157
159
|
async *executeCallStream(capabilityId, action, params) {
|
|
158
|
-
const url =
|
|
160
|
+
const url = `${this.baseURL}/api/capability/${capabilityId}/stream`;
|
|
159
161
|
let response;
|
|
160
162
|
try {
|
|
161
163
|
response = await fetch(url, {
|
|
@@ -198,7 +200,7 @@ var _CapabilityClient = class _CapabilityClient {
|
|
|
198
200
|
const parsed = JSON.parse(data);
|
|
199
201
|
if (parsed.status_code === ErrorCodes.SUCCESS && parsed.data) {
|
|
200
202
|
if (parsed.data.type === "content") {
|
|
201
|
-
yield parsed.data.delta
|
|
203
|
+
yield parsed.data.delta;
|
|
202
204
|
if (parsed.data.finished) {
|
|
203
205
|
return;
|
|
204
206
|
}
|
|
@@ -230,5 +232,5 @@ function createClient(options) {
|
|
|
230
232
|
return new CapabilityClient(options);
|
|
231
233
|
}
|
|
232
234
|
__name(createClient, "createClient");
|
|
233
|
-
var capabilityClient = new CapabilityClient();
|
|
235
|
+
var capabilityClient = new CapabilityClient({});
|
|
234
236
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["// 默认客户端实例\nexport { capabilityClient, createClient, CapabilityClient } from './client';\n\n// 类型\nexport type { CapabilityClientOptions, CapabilityExecutor } from './types';\n\n// 错误类型\nexport {\n CapabilityError,\n CapabilityNotFoundError,\n ActionNotFoundError,\n NetworkError,\n ExecutionError,\n} from './errors';\n","/**\n * 客户端配置选项\n */\nexport interface CapabilityClientOptions {\n /** 自定义 fetch 配置 */\n fetchOptions?: RequestInit;\n}\n\n/**\n * 能力执行器接口\n */\nexport interface CapabilityExecutor {\n /**\n * 调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns Action 执行结果\n */\n call<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): Promise<T>;\n\n /**\n * 流式调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns AsyncIterable,逐个 yield chunk\n */\n callStream<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T>;\n}\n\n// ========== API 响应类型 ==========\n\n/**\n * 成功响应\n */\nexport interface SuccessResponse<T> {\n status_code: '0';\n data: T;\n}\n\n/**\n * 错误响应\n */\nexport interface ErrorResponse {\n status_code: string;\n error_msg: string;\n}\n\n/**\n * API 响应类型\n */\nexport type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;\n\n// ========== 具体响应 data 结构 ==========\n\n/**\n * 执行接口响应 data 结构\n */\nexport interface ExecuteResponseData {\n output: unknown;\n}\n\n// ========== 流式响应结构 ==========\n\n/**\n * 流式内容响应\n */\nexport interface StreamContentResponse {\n status_code: '0';\n data: {\n type: 'content';\n delta: {\n content: unknown;\n };\n finished?: boolean;\n };\n}\n\n/**\n * 流式错误响应\n */\nexport interface StreamErrorResponse {\n status_code: '0';\n data: {\n type: 'error';\n error: {\n code: number;\n message: string;\n };\n };\n}\n\n/**\n * 流式响应类型\n */\nexport type StreamResponse = StreamContentResponse | StreamErrorResponse;\n\n// ========== 错误码 ==========\n\n/**\n * 后端错误码\n */\nexport const ErrorCodes = {\n SUCCESS: '0',\n CAPABILITY_NOT_FOUND: 'k_ec_cap_001',\n PLUGIN_NOT_FOUND: 'k_ec_cap_002',\n ACTION_NOT_FOUND: 'k_ec_cap_003',\n PARAMS_VALIDATION_ERROR: 'k_ec_cap_004',\n EXECUTION_ERROR: 'k_ec_cap_005',\n} as const;\n","/**\n * 能力调用错误基类\n */\nexport class CapabilityError extends Error {\n /** 错误码 */\n code: string;\n /** HTTP 状态码 */\n statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'CapabilityError';\n this.code = code;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * 能力不存在错误\n */\nexport class CapabilityNotFoundError extends CapabilityError {\n constructor(capabilityId: string, statusCode?: number) {\n super(`Capability not found: ${capabilityId}`, 'CAPABILITY_NOT_FOUND', statusCode);\n this.name = 'CapabilityNotFoundError';\n }\n}\n\n/**\n * Action 不存在错误\n */\nexport class ActionNotFoundError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'ACTION_NOT_FOUND', statusCode);\n this.name = 'ActionNotFoundError';\n }\n}\n\n/**\n * 网络错误\n */\nexport class NetworkError extends CapabilityError {\n constructor(message: string) {\n super(message, 'NETWORK_ERROR');\n this.name = 'NetworkError';\n }\n}\n\n/**\n * 执行错误\n */\nexport class ExecutionError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'EXECUTION_ERROR', statusCode);\n this.name = 'ExecutionError';\n }\n}\n","import type {\n CapabilityClientOptions,\n CapabilityExecutor,\n ApiResponse,\n ExecuteResponseData,\n StreamResponse,\n} from './types';\nimport { ErrorCodes } from './types';\nimport {\n CapabilityError,\n CapabilityNotFoundError,\n ActionNotFoundError,\n NetworkError,\n ExecutionError,\n} from './errors';\n\n/**\n * 能力客户端\n */\nexport class CapabilityClient {\n private options: CapabilityClientOptions;\n\n constructor(options?: CapabilityClientOptions) {\n this.options = options ?? {};\n }\n\n /**\n * 加载能力,返回执行器\n * @param capabilityId - 能力 ID\n * @returns 能力执行器\n */\n load(capabilityId: string): CapabilityExecutor {\n return this.createExecutor(capabilityId);\n }\n\n private createExecutor(capabilityId: string): CapabilityExecutor {\n return {\n call: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCall<T>(capabilityId, action, params);\n },\n callStream: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCallStream<T>(capabilityId, action, params);\n },\n };\n }\n\n private async executeCall<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): Promise<T> {\n const url = `/api/capability/${capabilityId}`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n\n const data = (await response.json()) as ApiResponse<ExecuteResponseData>;\n\n if (!response.ok || data.status_code !== ErrorCodes.SUCCESS) {\n const errorResponse = data as { status_code: string; error_msg: string };\n const errorCode = errorResponse.status_code;\n\n switch (errorCode) {\n case ErrorCodes.CAPABILITY_NOT_FOUND:\n throw new CapabilityNotFoundError(capabilityId, response.status);\n case ErrorCodes.ACTION_NOT_FOUND:\n throw new ActionNotFoundError(errorResponse.error_msg, response.status);\n case ErrorCodes.PLUGIN_NOT_FOUND:\n case ErrorCodes.EXECUTION_ERROR:\n default:\n throw new ExecutionError(errorResponse.error_msg, response.status);\n }\n }\n\n return (data as { data: ExecuteResponseData }).data.output as T;\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n }\n\n private async *executeCallStream<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T> {\n const url = `/api/capability/${capabilityId}/stream`;\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n } catch (error) {\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n\n if (!response.ok) {\n throw new NetworkError(`HTTP ${response.status} ${response.statusText}`);\n }\n\n if (!response.body) {\n throw new NetworkError('Response body is null');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n\n try {\n const parsed = JSON.parse(data) as StreamResponse;\n\n if (parsed.status_code === ErrorCodes.SUCCESS && parsed.data) {\n if (parsed.data.type === 'content') {\n yield parsed.data.delta.content as T;\n\n if (parsed.data.finished) {\n return;\n }\n } else if (parsed.data.type === 'error') {\n throw new ExecutionError(parsed.data.error.message);\n }\n }\n } catch (parseError) {\n if (parseError instanceof CapabilityError) {\n throw parseError;\n }\n // 忽略非 JSON 行\n }\n }\n }\n }\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n } finally {\n reader.releaseLock();\n }\n }\n}\n\n/**\n * 创建自定义客户端\n */\nexport function createClient(options?: CapabilityClientOptions): CapabilityClient {\n return new CapabilityClient(options);\n}\n\n/**\n * 默认客户端实例\n */\nexport const capabilityClient = new CapabilityClient();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;AC2GO,IAAMA,aAAa;EACxBC,SAAS;EACTC,sBAAsB;EACtBC,kBAAkB;EAClBC,kBAAkB;EAClBC,yBAAyB;EACzBC,iBAAiB;AACnB;;;AC/GO,IAAMC,mBAAN,MAAMA,yBAAwBC,MAAAA;EAMnC,YAAYC,SAAiBC,MAAcC,YAAqB;AAC9D,UAAMF,OAAAA;AALRC;;AAEAC;;AAIE,SAAKC,OAAO;AACZ,SAAKF,OAAOA;AACZ,SAAKC,aAAaA;EACpB;AACF;AAZqCH;AAA9B,IAAMD,kBAAN;AAiBA,IAAMM,2BAAN,MAAMA,iCAAgCN,gBAAAA;EAC3C,YAAYO,cAAsBH,YAAqB;AACrD,UAAM,yBAAyBG,YAAAA,IAAgB,wBAAwBH,UAAAA;AACvE,SAAKC,OAAO;EACd;AACF;AAL6CL;AAAtC,IAAMM,0BAAN;AAUA,IAAME,uBAAN,MAAMA,6BAA4BR,gBAAAA;EACvC,YAAYE,SAAiBE,YAAqB;AAChD,UAAMF,SAAS,oBAAoBE,UAAAA;AACnC,SAAKC,OAAO;EACd;AACF;AALyCL;AAAlC,IAAMQ,sBAAN;AAUA,IAAMC,gBAAN,MAAMA,sBAAqBT,gBAAAA;EAChC,YAAYE,SAAiB;AAC3B,UAAMA,SAAS,eAAA;AACf,SAAKG,OAAO;EACd;AACF;AALkCL;AAA3B,IAAMS,eAAN;AAUA,IAAMC,kBAAN,MAAMA,wBAAuBV,gBAAAA;EAClC,YAAYE,SAAiBE,YAAqB;AAChD,UAAMF,SAAS,mBAAmBE,UAAAA;AAClC,SAAKC,OAAO;EACd;AACF;AALoCL;AAA7B,IA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KAAK4C,MAAM1C,IAAAA;AAE1B,kBAAIyC,OAAOtC,gBAAgBC,WAAWC,WAAWoC,OAAOzC,MAAM;AAC5D,oBAAIyC,OAAOzC,KAAK2C,SAAS,WAAW;AAClC,wBAAMF,OAAOzC,KAAK4C,MAAMC;AAExB,sBAAIJ,OAAOzC,KAAK8C,UAAU;AACxB;kBACF;gBACF,WAAWL,OAAOzC,KAAK2C,SAAS,SAAS;AACvC,wBAAM,IAAI3B,eAAeyB,OAAOzC,KAAKkB,MAAMI,OAAO;gBACpD;cACF;YACF,SAASyB,YAAY;AACnB,kBAAIA,sBAAsB5B,iBAAiB;AACzC,sBAAM4B;cACR;YAEF;UACF;QACF;MACF;IACF,SAAS7B,OAAO;AACd,UAAIA,iBAAiBC,iBAAiB;AACpC,cAAMD;MACR;AACA,YAAM,IAAIE,aAAaF,iBAAiBG,QAAQH,MAAMI,UAAUC,OAAOL,KAAAA,CAAAA;IACzE,UAAA;AACEO,aAAOuB,YAAW;IACpB;EACF;AACF;AA7JapE;AAAN,IAAMA,mBAAN;AAkKA,SAASqE,aAAapE,SAAiC;AAC5D,SAAO,IAAID,iBAAiBC,OAAAA;AAC9B;AAFgBoE;AAOT,IAAMC,mBAAmB,IAAItE,iBAAAA;","names":["ErrorCodes","SUCCESS","CAPABILITY_NOT_FOUND","PLUGIN_NOT_FOUND","ACTION_NOT_FOUND","PARAMS_VALIDATION_ERROR","EXECUTION_ERROR","CapabilityError","Error","message","code","statusCode","name","CapabilityNotFoundError","capabilityId","ActionNotFoundError","NetworkError","ExecutionError","CapabilityClient","options","load","capabilityId","createExecutor","call","action","params","executeCall","callStream","executeCallStream","url","response","fetch","method","fetchOptions","headers","body","JSON","stringify","data","json","ok","status_code","ErrorCodes","SUCCESS","errorResponse","errorCode","CAPABILITY_NOT_FOUND","CapabilityNotFoundError","status","ACTION_NOT_FOUND","ActionNotFoundError","error_msg","PLUGIN_NOT_FOUND","EXECUTION_ERROR","ExecutionError","output","error","CapabilityError","NetworkError","Error","message","String","statusText","reader","getReader","decoder","TextDecoder","buffer","done","value","read","decode","stream","lines","split","pop","line","startsWith","slice","parsed","parse","type","delta","content","finished","parseError","releaseLock","createClient","capabilityClient"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["// 默认客户端实例\nexport { capabilityClient, createClient, CapabilityClient } from './client';\n\n// 类型\nexport type { CapabilityClientOptions, CapabilityExecutor } from './types';\n\n// 错误类型\nexport {\n CapabilityError,\n CapabilityNotFoundError,\n ActionNotFoundError,\n NetworkError,\n ExecutionError,\n} from './errors';\n","/**\n * 客户端配置选项\n */\nexport interface CapabilityClientOptions {\n /** 全局路径前缀,默认 ''。例如线上环境可设置为 '/spark/a' */\n baseURL?: string;\n /** 自定义 fetch 配置 */\n fetchOptions?: RequestInit;\n}\n\n/**\n * 能力执行器接口\n */\nexport interface CapabilityExecutor {\n /**\n * 调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns Action 执行结果\n */\n call<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): Promise<T>;\n\n /**\n * 流式调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns AsyncIterable,逐个 yield chunk\n */\n callStream<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T>;\n}\n\n// ========== API 响应类型 ==========\n\n/**\n * 成功响应\n */\nexport interface SuccessResponse<T> {\n status_code: '0';\n data: T;\n}\n\n/**\n * 错误响应\n */\nexport interface ErrorResponse {\n status_code: string;\n error_msg: string;\n}\n\n/**\n * API 响应类型\n */\nexport type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;\n\n// ========== 具体响应 data 结构 ==========\n\n/**\n * 执行接口响应 data 结构\n */\nexport interface ExecuteResponseData {\n output: unknown;\n}\n\n// ========== 流式响应结构 ==========\n\n/**\n * 流式内容响应\n */\nexport interface StreamContentResponse {\n status_code: '0';\n data: {\n type: 'content';\n delta: unknown;\n finished?: boolean;\n };\n}\n\n/**\n * 流式错误响应\n */\nexport interface StreamErrorResponse {\n status_code: '0';\n data: {\n type: 'error';\n error: {\n code: number;\n message: string;\n };\n };\n}\n\n/**\n * 流式响应类型\n */\nexport type StreamResponse = StreamContentResponse | StreamErrorResponse;\n\n// ========== 错误码 ==========\n\n/**\n * 后端错误码\n */\nexport const ErrorCodes = {\n SUCCESS: '0',\n CAPABILITY_NOT_FOUND: 'k_ec_cap_001',\n PLUGIN_NOT_FOUND: 'k_ec_cap_002',\n ACTION_NOT_FOUND: 'k_ec_cap_003',\n PARAMS_VALIDATION_ERROR: 'k_ec_cap_004',\n EXECUTION_ERROR: 'k_ec_cap_005',\n} as const;\n","/**\n * 能力调用错误基类\n */\nexport class CapabilityError extends Error {\n /** 错误码 */\n code: string;\n /** HTTP 状态码 */\n statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'CapabilityError';\n this.code = code;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * 能力不存在错误\n */\nexport class CapabilityNotFoundError extends CapabilityError {\n constructor(capabilityId: string, statusCode?: number) {\n super(`Capability not found: ${capabilityId}`, 'CAPABILITY_NOT_FOUND', statusCode);\n this.name = 'CapabilityNotFoundError';\n }\n}\n\n/**\n * Action 不存在错误\n */\nexport class ActionNotFoundError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'ACTION_NOT_FOUND', statusCode);\n this.name = 'ActionNotFoundError';\n }\n}\n\n/**\n * 网络错误\n */\nexport class NetworkError extends CapabilityError {\n constructor(message: string) {\n super(message, 'NETWORK_ERROR');\n this.name = 'NetworkError';\n }\n}\n\n/**\n * 执行错误\n */\nexport class ExecutionError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'EXECUTION_ERROR', statusCode);\n this.name = 'ExecutionError';\n }\n}\n","import type {\n CapabilityClientOptions,\n CapabilityExecutor,\n ApiResponse,\n ExecuteResponseData,\n StreamResponse,\n} from './types';\nimport { ErrorCodes } from './types';\nimport {\n CapabilityError,\n CapabilityNotFoundError,\n ActionNotFoundError,\n NetworkError,\n ExecutionError,\n} from './errors';\n\n/**\n * 能力客户端\n */\nexport class CapabilityClient {\n private options: CapabilityClientOptions;\n private baseURL: string;\n\n constructor(options?: CapabilityClientOptions) {\n this.options = options ?? {};\n // 移除末尾的斜杠,确保拼接时格式正确\n this.baseURL = (options?.baseURL ?? '').replace(/\\/+$/, '');\n }\n\n /**\n * 加载能力,返回执行器\n * @param capabilityId - 能力 ID\n * @returns 能力执行器\n */\n load(capabilityId: string): CapabilityExecutor {\n return this.createExecutor(capabilityId);\n }\n\n private createExecutor(capabilityId: string): CapabilityExecutor {\n return {\n call: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCall<T>(capabilityId, action, params);\n },\n callStream: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCallStream<T>(capabilityId, action, params);\n },\n };\n }\n\n private async executeCall<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): Promise<T> {\n const url = `${this.baseURL}/api/capability/${capabilityId}`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n\n const data = (await response.json()) as ApiResponse<ExecuteResponseData>;\n\n if (!response.ok || data.status_code !== ErrorCodes.SUCCESS) {\n const errorResponse = data as { status_code: string; error_msg: string };\n const errorCode = errorResponse.status_code;\n\n switch (errorCode) {\n case ErrorCodes.CAPABILITY_NOT_FOUND:\n throw new CapabilityNotFoundError(capabilityId, response.status);\n case ErrorCodes.ACTION_NOT_FOUND:\n throw new ActionNotFoundError(errorResponse.error_msg, response.status);\n case ErrorCodes.PLUGIN_NOT_FOUND:\n case ErrorCodes.EXECUTION_ERROR:\n default:\n throw new ExecutionError(errorResponse.error_msg, response.status);\n }\n }\n\n return (data as { data: ExecuteResponseData }).data.output as T;\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n }\n\n private async *executeCallStream<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T> {\n const url = `${this.baseURL}/api/capability/${capabilityId}/stream`;\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n } catch (error) {\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n\n if (!response.ok) {\n throw new NetworkError(`HTTP ${response.status} ${response.statusText}`);\n }\n\n if (!response.body) {\n throw new NetworkError('Response body is null');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n\n try {\n const parsed = JSON.parse(data) as StreamResponse;\n\n if (parsed.status_code === ErrorCodes.SUCCESS && parsed.data) {\n if (parsed.data.type === 'content') {\n yield parsed.data.delta as T;\n\n if (parsed.data.finished) {\n return;\n }\n } else if (parsed.data.type === 'error') {\n throw new ExecutionError(parsed.data.error.message);\n }\n }\n } catch (parseError) {\n if (parseError instanceof CapabilityError) {\n throw parseError;\n }\n // 忽略非 JSON 行\n }\n }\n }\n }\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n } finally {\n reader.releaseLock();\n }\n }\n}\n\n/**\n * 创建自定义客户端\n */\nexport function createClient(options?: CapabilityClientOptions): CapabilityClient {\n return new CapabilityClient(options);\n}\n\n/**\n * 默认客户端实例\n */\nexport const capabilityClient = new CapabilityClient({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BAAgBC,WAAWC,WAAWoC,OAAOzC,MAAM;AAC5D,oBAAIyC,OAAOzC,KAAK2C,SAAS,WAAW;AAClC,wBAAMF,OAAOzC,KAAK4C;AAElB,sBAAIH,OAAOzC,KAAK6C,UAAU;AACxB;kBACF;gBACF,WAAWJ,OAAOzC,KAAK2C,SAAS,SAAS;AACvC,wBAAM,IAAI3B,eAAeyB,OAAOzC,KAAKkB,MAAMI,OAAO;gBACpD;cACF;YACF,SAASwB,YAAY;AACnB,kBAAIA,sBAAsB3B,iBAAiB;AACzC,sBAAM2B;cACR;YAEF;UACF;QACF;MACF;IACF,SAAS5B,OAAO;AACd,UAAIA,iBAAiBC,iBAAiB;AACpC,cAAMD;MACR;AACA,YAAM,IAAIE,aAAaF,iBAAiBG,QAAQH,MAAMI,UAAUC,OAAOL,KAAAA,CAAAA;IACzE,UAAA;AACEO,aAAOsB,YAAW;IACpB;EACF;AACF;AAhKarE;AAAN,IAAMA,mBAAN;AAqKA,SAASsE,aAAarE,SAAiC;AAC5D,SAAO,IAAID,iBAAiBC,OAAAA;AAC9B;AAFgBqE;AAOT,IAAMC,mBAAmB,IAAIvE,iBAAiB,CAErD,CAAA;","names":["ErrorCodes","SUCCESS","CAPABILITY_NOT_FOUND","PLUGIN_NOT_FOUND","ACTION_NOT_FOUND","PARAMS_VALIDATION_ERROR","EXECUTION_ERROR","CapabilityError","Error","message","code","statusCode","name","CapabilityNotFoundError","capabilityId","ActionNotFoundError","NetworkError","ExecutionError","CapabilityClient","options","baseURL","replace","load","capabilityId","createExecutor","call","action","params","executeCall","callStream","executeCallStream","url","response","fetch","method","fetchOptions","headers","body","JSON","stringify","data","json","ok","status_code","ErrorCodes","SUCCESS","errorResponse","errorCode","CAPABILITY_NOT_FOUND","CapabilityNotFoundError","status","ACTION_NOT_FOUND","ActionNotFoundError","error_msg","PLUGIN_NOT_FOUND","EXECUTION_ERROR","ExecutionError","output","error","CapabilityError","NetworkError","Error","message","String","statusText","reader","getReader","decoder","TextDecoder","buffer","done","value","read","decode","stream","lines","split","pop","line","startsWith","slice","parsed","parse","type","delta","finished","parseError","releaseLock","createClient","capabilityClient"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* 客户端配置选项
|
|
3
3
|
*/
|
|
4
4
|
interface CapabilityClientOptions {
|
|
5
|
+
/** 全局路径前缀,默认 ''。例如线上环境可设置为 '/spark/a' */
|
|
6
|
+
baseURL?: string;
|
|
5
7
|
/** 自定义 fetch 配置 */
|
|
6
8
|
fetchOptions?: RequestInit;
|
|
7
9
|
}
|
|
@@ -30,6 +32,7 @@ interface CapabilityExecutor {
|
|
|
30
32
|
*/
|
|
31
33
|
declare class CapabilityClient {
|
|
32
34
|
private options;
|
|
35
|
+
private baseURL;
|
|
33
36
|
constructor(options?: CapabilityClientOptions);
|
|
34
37
|
/**
|
|
35
38
|
* 加载能力,返回执行器
|
package/dist/index.d.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* 客户端配置选项
|
|
3
3
|
*/
|
|
4
4
|
interface CapabilityClientOptions {
|
|
5
|
+
/** 全局路径前缀,默认 ''。例如线上环境可设置为 '/spark/a' */
|
|
6
|
+
baseURL?: string;
|
|
5
7
|
/** 自定义 fetch 配置 */
|
|
6
8
|
fetchOptions?: RequestInit;
|
|
7
9
|
}
|
|
@@ -30,6 +32,7 @@ interface CapabilityExecutor {
|
|
|
30
32
|
*/
|
|
31
33
|
declare class CapabilityClient {
|
|
32
34
|
private options;
|
|
35
|
+
private baseURL;
|
|
33
36
|
constructor(options?: CapabilityClientOptions);
|
|
34
37
|
/**
|
|
35
38
|
* 加载能力,返回执行器
|
package/dist/index.js
CHANGED
|
@@ -65,7 +65,9 @@ var ExecutionError = _ExecutionError;
|
|
|
65
65
|
var _CapabilityClient = class _CapabilityClient {
|
|
66
66
|
constructor(options) {
|
|
67
67
|
__publicField(this, "options");
|
|
68
|
+
__publicField(this, "baseURL");
|
|
68
69
|
this.options = options ?? {};
|
|
70
|
+
this.baseURL = (options?.baseURL ?? "").replace(/\/+$/, "");
|
|
69
71
|
}
|
|
70
72
|
/**
|
|
71
73
|
* 加载能力,返回执行器
|
|
@@ -86,7 +88,7 @@ var _CapabilityClient = class _CapabilityClient {
|
|
|
86
88
|
};
|
|
87
89
|
}
|
|
88
90
|
async executeCall(capabilityId, action, params) {
|
|
89
|
-
const url =
|
|
91
|
+
const url = `${this.baseURL}/api/capability/${capabilityId}`;
|
|
90
92
|
try {
|
|
91
93
|
const response = await fetch(url, {
|
|
92
94
|
method: "POST",
|
|
@@ -124,7 +126,7 @@ var _CapabilityClient = class _CapabilityClient {
|
|
|
124
126
|
}
|
|
125
127
|
}
|
|
126
128
|
async *executeCallStream(capabilityId, action, params) {
|
|
127
|
-
const url =
|
|
129
|
+
const url = `${this.baseURL}/api/capability/${capabilityId}/stream`;
|
|
128
130
|
let response;
|
|
129
131
|
try {
|
|
130
132
|
response = await fetch(url, {
|
|
@@ -167,7 +169,7 @@ var _CapabilityClient = class _CapabilityClient {
|
|
|
167
169
|
const parsed = JSON.parse(data);
|
|
168
170
|
if (parsed.status_code === ErrorCodes.SUCCESS && parsed.data) {
|
|
169
171
|
if (parsed.data.type === "content") {
|
|
170
|
-
yield parsed.data.delta
|
|
172
|
+
yield parsed.data.delta;
|
|
171
173
|
if (parsed.data.finished) {
|
|
172
174
|
return;
|
|
173
175
|
}
|
|
@@ -199,7 +201,7 @@ function createClient(options) {
|
|
|
199
201
|
return new CapabilityClient(options);
|
|
200
202
|
}
|
|
201
203
|
__name(createClient, "createClient");
|
|
202
|
-
var capabilityClient = new CapabilityClient();
|
|
204
|
+
var capabilityClient = new CapabilityClient({});
|
|
203
205
|
export {
|
|
204
206
|
ActionNotFoundError,
|
|
205
207
|
CapabilityClient,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["/**\n * 客户端配置选项\n */\nexport interface CapabilityClientOptions {\n /** 自定义 fetch 配置 */\n fetchOptions?: RequestInit;\n}\n\n/**\n * 能力执行器接口\n */\nexport interface CapabilityExecutor {\n /**\n * 调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns Action 执行结果\n */\n call<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): Promise<T>;\n\n /**\n * 流式调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns AsyncIterable,逐个 yield chunk\n */\n callStream<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T>;\n}\n\n// ========== API 响应类型 ==========\n\n/**\n * 成功响应\n */\nexport interface SuccessResponse<T> {\n status_code: '0';\n data: T;\n}\n\n/**\n * 错误响应\n */\nexport interface ErrorResponse {\n status_code: string;\n error_msg: string;\n}\n\n/**\n * API 响应类型\n */\nexport type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;\n\n// ========== 具体响应 data 结构 ==========\n\n/**\n * 执行接口响应 data 结构\n */\nexport interface ExecuteResponseData {\n output: unknown;\n}\n\n// ========== 流式响应结构 ==========\n\n/**\n * 流式内容响应\n */\nexport interface StreamContentResponse {\n status_code: '0';\n data: {\n type: 'content';\n delta: {\n content: unknown;\n };\n finished?: boolean;\n };\n}\n\n/**\n * 流式错误响应\n */\nexport interface StreamErrorResponse {\n status_code: '0';\n data: {\n type: 'error';\n error: {\n code: number;\n message: string;\n };\n };\n}\n\n/**\n * 流式响应类型\n */\nexport type StreamResponse = StreamContentResponse | StreamErrorResponse;\n\n// ========== 错误码 ==========\n\n/**\n * 后端错误码\n */\nexport const ErrorCodes = {\n SUCCESS: '0',\n CAPABILITY_NOT_FOUND: 'k_ec_cap_001',\n PLUGIN_NOT_FOUND: 'k_ec_cap_002',\n ACTION_NOT_FOUND: 'k_ec_cap_003',\n PARAMS_VALIDATION_ERROR: 'k_ec_cap_004',\n EXECUTION_ERROR: 'k_ec_cap_005',\n} as const;\n","/**\n * 能力调用错误基类\n */\nexport class CapabilityError extends Error {\n /** 错误码 */\n code: string;\n /** HTTP 状态码 */\n statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'CapabilityError';\n this.code = code;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * 能力不存在错误\n */\nexport class CapabilityNotFoundError extends CapabilityError {\n constructor(capabilityId: string, statusCode?: number) {\n super(`Capability not found: ${capabilityId}`, 'CAPABILITY_NOT_FOUND', statusCode);\n this.name = 'CapabilityNotFoundError';\n }\n}\n\n/**\n * Action 不存在错误\n */\nexport class ActionNotFoundError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'ACTION_NOT_FOUND', statusCode);\n this.name = 'ActionNotFoundError';\n }\n}\n\n/**\n * 网络错误\n */\nexport class NetworkError extends CapabilityError {\n constructor(message: string) {\n super(message, 'NETWORK_ERROR');\n this.name = 'NetworkError';\n }\n}\n\n/**\n * 执行错误\n */\nexport class ExecutionError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'EXECUTION_ERROR', statusCode);\n this.name = 'ExecutionError';\n }\n}\n","import type {\n CapabilityClientOptions,\n CapabilityExecutor,\n ApiResponse,\n ExecuteResponseData,\n StreamResponse,\n} from './types';\nimport { ErrorCodes } from './types';\nimport {\n CapabilityError,\n CapabilityNotFoundError,\n ActionNotFoundError,\n NetworkError,\n ExecutionError,\n} from './errors';\n\n/**\n * 能力客户端\n */\nexport class CapabilityClient {\n private options: CapabilityClientOptions;\n\n constructor(options?: CapabilityClientOptions) {\n this.options = options ?? {};\n }\n\n /**\n * 加载能力,返回执行器\n * @param capabilityId - 能力 ID\n * @returns 能力执行器\n */\n load(capabilityId: string): CapabilityExecutor {\n return this.createExecutor(capabilityId);\n }\n\n private createExecutor(capabilityId: string): CapabilityExecutor {\n return {\n call: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCall<T>(capabilityId, action, params);\n },\n callStream: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCallStream<T>(capabilityId, action, params);\n },\n };\n }\n\n private async executeCall<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): Promise<T> {\n const url = `/api/capability/${capabilityId}`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n\n const data = (await response.json()) as ApiResponse<ExecuteResponseData>;\n\n if (!response.ok || data.status_code !== ErrorCodes.SUCCESS) {\n const errorResponse = data as { status_code: string; error_msg: string };\n const errorCode = errorResponse.status_code;\n\n switch (errorCode) {\n case ErrorCodes.CAPABILITY_NOT_FOUND:\n throw new CapabilityNotFoundError(capabilityId, response.status);\n case ErrorCodes.ACTION_NOT_FOUND:\n throw new ActionNotFoundError(errorResponse.error_msg, response.status);\n case ErrorCodes.PLUGIN_NOT_FOUND:\n case ErrorCodes.EXECUTION_ERROR:\n default:\n throw new ExecutionError(errorResponse.error_msg, response.status);\n }\n }\n\n return (data as { data: ExecuteResponseData }).data.output as T;\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n }\n\n private async *executeCallStream<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T> {\n const url = `/api/capability/${capabilityId}/stream`;\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n } catch (error) {\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n\n if (!response.ok) {\n throw new NetworkError(`HTTP ${response.status} ${response.statusText}`);\n }\n\n if (!response.body) {\n throw new NetworkError('Response body is null');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n\n try {\n const parsed = JSON.parse(data) as StreamResponse;\n\n if (parsed.status_code === ErrorCodes.SUCCESS && parsed.data) {\n if (parsed.data.type === 'content') {\n yield parsed.data.delta.content as T;\n\n if (parsed.data.finished) {\n return;\n }\n } else if (parsed.data.type === 'error') {\n throw new ExecutionError(parsed.data.error.message);\n }\n }\n } catch (parseError) {\n if (parseError instanceof CapabilityError) {\n throw parseError;\n }\n // 忽略非 JSON 行\n }\n }\n }\n }\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n } finally {\n reader.releaseLock();\n }\n }\n}\n\n/**\n * 创建自定义客户端\n */\nexport function createClient(options?: CapabilityClientOptions): CapabilityClient {\n return new CapabilityClient(options);\n}\n\n/**\n * 默认客户端实例\n */\nexport const capabilityClient = new CapabilityClient();\n"],"mappings":";;;;;;AA2GO,IAAMA,aAAa;EACxBC,SAAS;EACTC,sBAAsB;EACtBC,kBAAkB;EAClBC,kBAAkB;EAClBC,yBAAyB;EACzBC,iBAAiB;AACnB;;;AC/GO,IAAMC,mBAAN,MAAMA,yBAAwBC,MAAAA;EAMnC,YAAYC,SAAiBC,MAAcC,YAAqB;AAC9D,UAAMF,OAAAA;AALRC;;AAEAC;;AAIE,SAAKC,OAAO;AACZ,SAAKF,OAAOA;AACZ,SAAKC,aAAaA;EACpB;AACF;AAZqCH;AAA9B,IAAMD,kBAAN;AAiBA,IAAMM,2BAAN,MAAMA,iCAAgCN,gBAAAA;EAC3C,YAAYO,cAAsBH,YAAqB;AACrD,UAAM,yBAAyBG,YAAAA,IAAgB,wBAAwBH,UAAAA;AACvE,SAAKC,OAAO;EACd;AACF;AAL6CL;AAAtC,IAAMM,0BAAN;AAUA,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BAAAA;","names":["ErrorCodes","SUCCESS","CAPABILITY_NOT_FOUND","PLUGIN_NOT_FOUND","ACTION_NOT_FOUND","PARAMS_VALIDATION_ERROR","EXECUTION_ERROR","CapabilityError","Error","message","code","statusCode","name","CapabilityNotFoundError","capabilityId","ActionNotFoundError","NetworkError","ExecutionError","CapabilityClient","options","load","capabilityId","createExecutor","call","action","params","executeCall","callStream","executeCallStream","url","response","fetch","method","fetchOptions","headers","body","JSON","stringify","data","json","ok","status_code","ErrorCodes","SUCCESS","errorResponse","errorCode","CAPABILITY_NOT_FOUND","CapabilityNotFoundError","status","ACTION_NOT_FOUND","ActionNotFoundError","error_msg","PLUGIN_NOT_FOUND","EXECUTION_ERROR","ExecutionError","output","error","CapabilityError","NetworkError","Error","message","String","statusText","reader","getReader","decoder","TextDecoder","buffer","done","value","read","decode","stream","lines","split","pop","line","startsWith","slice","parsed","parse","type","delta","content","finished","parseError","releaseLock","createClient","capabilityClient"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/errors.ts","../src/client.ts"],"sourcesContent":["/**\n * 客户端配置选项\n */\nexport interface CapabilityClientOptions {\n /** 全局路径前缀,默认 ''。例如线上环境可设置为 '/spark/a' */\n baseURL?: string;\n /** 自定义 fetch 配置 */\n fetchOptions?: RequestInit;\n}\n\n/**\n * 能力执行器接口\n */\nexport interface CapabilityExecutor {\n /**\n * 调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns Action 执行结果\n */\n call<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): Promise<T>;\n\n /**\n * 流式调用能力\n * @param action - Action 名称\n * @param params - 输入参数\n * @returns AsyncIterable,逐个 yield chunk\n */\n callStream<T = unknown>(\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T>;\n}\n\n// ========== API 响应类型 ==========\n\n/**\n * 成功响应\n */\nexport interface SuccessResponse<T> {\n status_code: '0';\n data: T;\n}\n\n/**\n * 错误响应\n */\nexport interface ErrorResponse {\n status_code: string;\n error_msg: string;\n}\n\n/**\n * API 响应类型\n */\nexport type ApiResponse<T> = SuccessResponse<T> | ErrorResponse;\n\n// ========== 具体响应 data 结构 ==========\n\n/**\n * 执行接口响应 data 结构\n */\nexport interface ExecuteResponseData {\n output: unknown;\n}\n\n// ========== 流式响应结构 ==========\n\n/**\n * 流式内容响应\n */\nexport interface StreamContentResponse {\n status_code: '0';\n data: {\n type: 'content';\n delta: unknown;\n finished?: boolean;\n };\n}\n\n/**\n * 流式错误响应\n */\nexport interface StreamErrorResponse {\n status_code: '0';\n data: {\n type: 'error';\n error: {\n code: number;\n message: string;\n };\n };\n}\n\n/**\n * 流式响应类型\n */\nexport type StreamResponse = StreamContentResponse | StreamErrorResponse;\n\n// ========== 错误码 ==========\n\n/**\n * 后端错误码\n */\nexport const ErrorCodes = {\n SUCCESS: '0',\n CAPABILITY_NOT_FOUND: 'k_ec_cap_001',\n PLUGIN_NOT_FOUND: 'k_ec_cap_002',\n ACTION_NOT_FOUND: 'k_ec_cap_003',\n PARAMS_VALIDATION_ERROR: 'k_ec_cap_004',\n EXECUTION_ERROR: 'k_ec_cap_005',\n} as const;\n","/**\n * 能力调用错误基类\n */\nexport class CapabilityError extends Error {\n /** 错误码 */\n code: string;\n /** HTTP 状态码 */\n statusCode?: number;\n\n constructor(message: string, code: string, statusCode?: number) {\n super(message);\n this.name = 'CapabilityError';\n this.code = code;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * 能力不存在错误\n */\nexport class CapabilityNotFoundError extends CapabilityError {\n constructor(capabilityId: string, statusCode?: number) {\n super(`Capability not found: ${capabilityId}`, 'CAPABILITY_NOT_FOUND', statusCode);\n this.name = 'CapabilityNotFoundError';\n }\n}\n\n/**\n * Action 不存在错误\n */\nexport class ActionNotFoundError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'ACTION_NOT_FOUND', statusCode);\n this.name = 'ActionNotFoundError';\n }\n}\n\n/**\n * 网络错误\n */\nexport class NetworkError extends CapabilityError {\n constructor(message: string) {\n super(message, 'NETWORK_ERROR');\n this.name = 'NetworkError';\n }\n}\n\n/**\n * 执行错误\n */\nexport class ExecutionError extends CapabilityError {\n constructor(message: string, statusCode?: number) {\n super(message, 'EXECUTION_ERROR', statusCode);\n this.name = 'ExecutionError';\n }\n}\n","import type {\n CapabilityClientOptions,\n CapabilityExecutor,\n ApiResponse,\n ExecuteResponseData,\n StreamResponse,\n} from './types';\nimport { ErrorCodes } from './types';\nimport {\n CapabilityError,\n CapabilityNotFoundError,\n ActionNotFoundError,\n NetworkError,\n ExecutionError,\n} from './errors';\n\n/**\n * 能力客户端\n */\nexport class CapabilityClient {\n private options: CapabilityClientOptions;\n private baseURL: string;\n\n constructor(options?: CapabilityClientOptions) {\n this.options = options ?? {};\n // 移除末尾的斜杠,确保拼接时格式正确\n this.baseURL = (options?.baseURL ?? '').replace(/\\/+$/, '');\n }\n\n /**\n * 加载能力,返回执行器\n * @param capabilityId - 能力 ID\n * @returns 能力执行器\n */\n load(capabilityId: string): CapabilityExecutor {\n return this.createExecutor(capabilityId);\n }\n\n private createExecutor(capabilityId: string): CapabilityExecutor {\n return {\n call: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCall<T>(capabilityId, action, params);\n },\n callStream: <T = unknown>(action: string, params?: Record<string, unknown>) => {\n return this.executeCallStream<T>(capabilityId, action, params);\n },\n };\n }\n\n private async executeCall<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): Promise<T> {\n const url = `${this.baseURL}/api/capability/${capabilityId}`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n\n const data = (await response.json()) as ApiResponse<ExecuteResponseData>;\n\n if (!response.ok || data.status_code !== ErrorCodes.SUCCESS) {\n const errorResponse = data as { status_code: string; error_msg: string };\n const errorCode = errorResponse.status_code;\n\n switch (errorCode) {\n case ErrorCodes.CAPABILITY_NOT_FOUND:\n throw new CapabilityNotFoundError(capabilityId, response.status);\n case ErrorCodes.ACTION_NOT_FOUND:\n throw new ActionNotFoundError(errorResponse.error_msg, response.status);\n case ErrorCodes.PLUGIN_NOT_FOUND:\n case ErrorCodes.EXECUTION_ERROR:\n default:\n throw new ExecutionError(errorResponse.error_msg, response.status);\n }\n }\n\n return (data as { data: ExecuteResponseData }).data.output as T;\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n }\n\n private async *executeCallStream<T>(\n capabilityId: string,\n action: string,\n params?: Record<string, unknown>\n ): AsyncIterable<T> {\n const url = `${this.baseURL}/api/capability/${capabilityId}/stream`;\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n ...this.options.fetchOptions,\n headers: {\n 'Content-Type': 'application/json',\n ...this.options.fetchOptions?.headers,\n },\n body: JSON.stringify({\n action,\n params: params ?? {},\n }),\n });\n } catch (error) {\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n }\n\n if (!response.ok) {\n throw new NetworkError(`HTTP ${response.status} ${response.statusText}`);\n }\n\n if (!response.body) {\n throw new NetworkError('Response body is null');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n const data = line.slice(6);\n\n try {\n const parsed = JSON.parse(data) as StreamResponse;\n\n if (parsed.status_code === ErrorCodes.SUCCESS && parsed.data) {\n if (parsed.data.type === 'content') {\n yield parsed.data.delta as T;\n\n if (parsed.data.finished) {\n return;\n }\n } else if (parsed.data.type === 'error') {\n throw new ExecutionError(parsed.data.error.message);\n }\n }\n } catch (parseError) {\n if (parseError instanceof CapabilityError) {\n throw parseError;\n }\n // 忽略非 JSON 行\n }\n }\n }\n }\n } catch (error) {\n if (error instanceof CapabilityError) {\n throw error;\n }\n throw new NetworkError(error instanceof Error ? error.message : String(error));\n } finally {\n reader.releaseLock();\n }\n }\n}\n\n/**\n * 创建自定义客户端\n */\nexport function createClient(options?: CapabilityClientOptions): CapabilityClient {\n return new CapabilityClient(options);\n}\n\n/**\n * 默认客户端实例\n */\nexport const capabilityClient = new CapabilityClient({\n\n});\n"],"mappings":";;;;;;AA2GO,IAAMA,aAAa;EACxBC,SAAS;EACTC,sBAAsB;EACtBC,kBAAkB;EAClBC,kBAAkB;EAClBC,yBAAyB;EACzBC,iBAAiB;AACnB;;;AC/GO,IAAMC,mBAAN,MAAMA,yBAAwBC,MAAAA;EAMnC,YAAYC,SAAiBC,MAAcC,YAAqB;AAC9D,UAAMF,OAAAA;AALRC;;AAEAC;;AAIE,SAAKC,OAAO;AACZ,SAAKF,OAAOA;AACZ,SAAKC,aAAaA;EACpB;AACF;AAZqCH;AAA9B,IAAMD,kBAAN;AAiBA,IAAMM,2BAAN,MAAMA,iCAAgCN,gBAAAA;EAC3C,YAAYO,cAAsBH,YAAqB;AACrD,UAAM,yBAAyBG,YAAAA,IAAgB,wBAAwBH,UAAAA;AACvE,SAAKC,OAAO;EACd;AACF;AAL6CL;AAAtC,IAAMM,0BAAN;AAUA,IAAME,uBAAN,MAAMA,6BAA4BR,gBAAAA;EACvC,YAAYE,SAAiBE,YAAqB;AAChD,UAAMF,SAAS,oBAAoBE,UAAAA;AACnC,SAAKC,OAAO;EACd;AACF;AALyCL;AAAlC,IAAMQ,sBAAN;AAUA,IAAMC,gBAAN,MAAMA,sBAAqBT,gBAAAA;EAChC,YAAYE,SAAiB;AAC3B,UAAMA,SAAS,eAAA;AACf,SAAKG,OAAO;EACd;AACF;AALkCL;AAA3B,IAAMS,eAAN;AAUA,IAAMC,kBAAN,MAAMA,wBAAuBV,gBAAAA;EAClC,YAAYE,SAAiBE,YAAqB;AAChD,UAAMF,SA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AAC3BP,iBAASM,MAAME,IAAG,KAAM;AAExB,mBAAWC,QAAQH,OAAO;AACxB,cAAIG,KAAKC,WAAW,QAAA,GAAW;AAC7B,kBAAMvC,OAAOsC,KAAKE,MAAM,CAAA;AAExB,gBAAI;AACF,oBAAMC,SAAS3C,KAAK4C,MAAM1C,IAAAA;AAE1B,kBAAIyC,OAAOtC,gBAAgBC,WAAWC,WAAWoC,OAAOzC,MAAM;AAC5D,oBAAIyC,OAAOzC,KAAK2C,SAAS,WAAW;AAClC,wBAAMF,OAAOzC,KAAK4C;AAElB,sBAAIH,OAAOzC,KAAK6C,UAAU;AACxB;kBACF;gBACF,WAAWJ,OAAOzC,KAAK2C,SAAS,SAAS;AACvC,wBAAM,IAAI3B,eAAeyB,OAAOzC,KAAKkB,MAAMI,OAAO;gBACpD;cACF;YACF,SAASwB,YAAY;AACnB,kBAAIA,sBAAsB3B,iBAAiB;AACzC,sBAAM2B;cACR;YAEF;UACF;QACF;MACF;IACF,SAAS5B,OAAO;AACd,UAAIA,iBAAiBC,iBAAiB;AACpC,cAAMD;MACR;AACA,YAAM,IAAIE,aAAaF,iBAAiBG,QAAQH,MAAMI,UAAUC,OAAOL,KAAAA,CAAAA;IACzE,UAAA;AACEO,aAAOsB,YAAW;IACpB;EACF;AACF;AAhKarE;AAAN,IAAMA,mBAAN;AAqKA,SAASsE,aAAarE,SAAiC;AAC5D,SAAO,IAAID,iBAAiBC,OAAAA;AAC9B;AAFgBqE;AAOT,IAAMC,mBAAmB,IAAIvE,iBAAiB,CAErD,CAAA;","names":["ErrorCodes","SUCCESS","CAPABILITY_NOT_FOUND","PLUGIN_NOT_FOUND","ACTION_NOT_FOUND","PARAMS_VALIDATION_ERROR","EXECUTION_ERROR","CapabilityError","Error","message","code","statusCode","name","CapabilityNotFoundError","capabilityId","ActionNotFoundError","NetworkError","ExecutionError","CapabilityClient","options","baseURL","replace","load","capabilityId","createExecutor","call","action","params","executeCall","callStream","executeCallStream","url","response","fetch","method","fetchOptions","headers","body","JSON","stringify","data","json","ok","status_code","ErrorCodes","SUCCESS","errorResponse","errorCode","CAPABILITY_NOT_FOUND","CapabilityNotFoundError","status","ACTION_NOT_FOUND","ActionNotFoundError","error_msg","PLUGIN_NOT_FOUND","EXECUTION_ERROR","ExecutionError","output","error","CapabilityError","NetworkError","Error","message","String","statusText","reader","getReader","decoder","TextDecoder","buffer","done","value","read","decode","stream","lines","split","pop","line","startsWith","slice","parsed","parse","type","delta","finished","parseError","releaseLock","createClient","capabilityClient"]}
|