@workopilot/pluginapi-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.
Files changed (3) hide show
  1. package/README.md +251 -145
  2. package/dist/index.d.ts +26 -1
  3. package/package.json +33 -33
package/README.md CHANGED
@@ -1,145 +1,251 @@
1
- # @workopilot/pluginapi-sdk
2
-
3
- Workopilot Plugin API SDK defines the TypeScript contract between the host application and third-party plugins.
4
-
5
- It provides plugin manifest types, request/handler types, database capability types, logger types, and current user context types. The SDK does not start a server or connect to databases by itself. Runtime capabilities are injected by the host application or by `@workopilot/pluginapi-dev-host` during local development.
6
-
7
- ## Installation
8
-
9
- ```bash
10
- npm install @workopilot/pluginapi-sdk
11
- ```
12
-
13
- ## Usage
14
-
15
- Create plugin handlers with the `PluginHandler` type:
16
-
17
- ```ts
18
- import type { PluginHandler } from '@workopilot/pluginapi-sdk';
19
-
20
- export const getCurrentUser: PluginHandler = ({ ctx }) => ({
21
- currentUser: ctx.currentUser
22
- });
23
-
24
- export const listItems: PluginHandler = async ({ ctx }) => {
25
- const rows = await ctx.database.query('SELECT * FROM plugin_demo_items LIMIT ?', [10]);
26
- return { rows };
27
- };
28
- ```
29
-
30
- Register exported handlers in the plugin manifest:
31
-
32
- ```json
33
- {
34
- "name": "my-plugin",
35
- "version": "0.1.0",
36
- "entry": "dist/index.js",
37
- "routes": [
38
- {
39
- "method": "GET",
40
- "path": "/me",
41
- "handler": "getCurrentUser"
42
- }
43
- ]
44
- }
45
- ```
46
-
47
- ## Provided Types
48
-
49
- ### Platform Service URL
50
-
51
- Hosts configure `PLATFORM_SERVICE_URL` as an HTTP(S) origin without `/net-api`
52
- (for example `https://agent.workopilot.com`). HTTP and MCP handlers receive the
53
- normalized origin through `ctx.platformServiceUrl`. It contains no database
54
- credentials. `readPlatformServiceUrl(value)` validates and normalizes this setting.
55
-
56
- ### Plugin Handler
57
-
58
- ```ts
59
- PluginHandler
60
- PluginHandlerInput
61
- PluginRequest
62
- PluginContext
63
-
64
- ### MCP Tool
65
-
66
- Plugins can optionally export an MCP tool array from the module named by `plugin.json.mcp.toolsExport` (default: `mcpTools`):
67
-
68
- ```json
69
- {
70
- "appCode": "my-app",
71
- "mcp": {
72
- "toolsExport": "mcpTools"
73
- }
74
- }
75
- ```
76
-
77
- Each tool uses `McpToolDefinition`, provides a JSON Schema `inputSchema`, and receives the same `ctx.currentUser`, database capability, logger, and request headers as an HTTP handler. The host owns MCP transport, authentication, and appCode grouping.
78
- ```
79
-
80
- Handlers receive:
81
-
82
- ```ts
83
- {
84
- request,
85
- ctx
86
- }
87
- ```
88
-
89
- ### Database Capability
90
-
91
- The host injects database access through `ctx.database`:
92
-
93
- ```ts
94
- ctx.database.query(sql, params)
95
- ctx.database.insert(sql, params)
96
- ctx.database.update(sql, params)
97
- ctx.database.delete(sql, params)
98
- ```
99
-
100
- Write operations return:
101
-
102
- ```ts
103
- {
104
- affectedRows,
105
- insertId,
106
- warningStatus,
107
- changedRows,
108
- info
109
- }
110
- ```
111
-
112
- ### Current User
113
-
114
- The host injects the authenticated user through:
115
-
116
- ```ts
117
- ctx.currentUser
118
- ```
119
-
120
- Current user shape:
121
-
122
- ```ts
123
- {
124
- tenantId,
125
- userId,
126
- clientid,
127
- userName,
128
- deptId,
129
- deptName,
130
- deptCategory
131
- }
132
- ```
133
-
134
- ### Logger
135
-
136
- Plugins can write host-managed logs:
137
-
138
- ```ts
139
- ctx.logger.info(message, data)
140
- ctx.logger.error(message, data)
141
- ```
142
-
143
- ## Notes
144
-
145
- Plugin packages should normally use this SDK as a TypeScript type dependency. Database credentials, JWT verification, Redis token checks, and route mounting are handled by the host side.
1
+ # @workopilot/pluginapi-sdk
2
+
3
+ Workopilot Plugin API SDK defines the TypeScript contract between the host application and third-party plugins.
4
+
5
+ It provides plugin manifest types, request/handler types, database capability types, logger types, and current user context types. The SDK does not start a server or connect to databases by itself. Runtime capabilities are injected by the host application or by `@workopilot/pluginapi-dev-host` during local development.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @workopilot/pluginapi-sdk
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Create plugin handlers with the `PluginHandler` type:
16
+
17
+ ```ts
18
+ import type { PluginHandler } from '@workopilot/pluginapi-sdk';
19
+
20
+ export const getCurrentUser: PluginHandler = ({ ctx }) => ({
21
+ currentUser: ctx.currentUser
22
+ });
23
+
24
+ export const listItems: PluginHandler = async ({ ctx }) => {
25
+ const rows = await ctx.database.query('SELECT * FROM plugin_demo_items LIMIT ?', [10]);
26
+ return { rows };
27
+ };
28
+ ```
29
+
30
+ Register exported handlers in the plugin manifest:
31
+
32
+ ```json
33
+ {
34
+ "name": "my-plugin",
35
+ "version": "0.1.0",
36
+ "entry": "dist/index.js",
37
+ "routes": [
38
+ {
39
+ "method": "GET",
40
+ "path": "/me",
41
+ "handler": "getCurrentUser"
42
+ }
43
+ ]
44
+ }
45
+ ```
46
+
47
+ ## Provided Types
48
+
49
+ ### Platform Service URL
50
+
51
+ Hosts configure `PLATFORM_SERVICE_URL` as an HTTP(S) origin without `/net-api`
52
+ (for example `https://agent.workopilot.com`). HTTP and MCP handlers receive the
53
+ normalized origin through `ctx.platformServiceUrl`. It contains no database
54
+ credentials. `readPlatformServiceUrl(value)` validates and normalizes this setting.
55
+
56
+ ### Plugin Handler
57
+
58
+ ```ts
59
+ PluginHandler
60
+ PluginHandlerInput
61
+ PluginRequest
62
+ PluginContext
63
+ ```
64
+
65
+ ### MCP Tool
66
+
67
+ Plugins can optionally export an MCP tool array from the module named by `plugin.json.mcp.toolsExport` (default: `mcpTools`):
68
+
69
+ ```json
70
+ {
71
+ "appCode": "my-app",
72
+ "mcp": {
73
+ "toolsExport": "mcpTools"
74
+ }
75
+ }
76
+ ```
77
+
78
+ Each tool uses `McpToolDefinition`, provides a JSON Schema `inputSchema`, and receives the same `ctx.currentUser`, database capability, logger, and request headers as an HTTP handler. The host owns MCP transport, authentication, and appCode grouping.
79
+
80
+ Handlers receive:
81
+
82
+ ```ts
83
+ {
84
+ request,
85
+ ctx
86
+ }
87
+ ```
88
+
89
+ ### Database Capability
90
+
91
+ The host injects database access through `ctx.database`:
92
+
93
+ ```ts
94
+ ctx.database.query(sql, params)
95
+ ctx.database.insert(sql, params)
96
+ ctx.database.update(sql, params)
97
+ ctx.database.delete(sql, params)
98
+ ```
99
+
100
+ Write operations return:
101
+
102
+ ```ts
103
+ {
104
+ affectedRows,
105
+ insertId,
106
+ warningStatus,
107
+ changedRows,
108
+ info
109
+ }
110
+ ```
111
+
112
+ ### Current User
113
+
114
+ The host injects the authenticated user through:
115
+
116
+ ```ts
117
+ ctx.currentUser
118
+ ```
119
+
120
+ Current user shape:
121
+
122
+ ```ts
123
+ {
124
+ tenantId,
125
+ userId,
126
+ clientid,
127
+ userName,
128
+ deptId,
129
+ deptName,
130
+ deptCategory
131
+ }
132
+ ```
133
+
134
+ ### Logger
135
+
136
+ Plugins can write host-managed logs:
137
+
138
+ ```ts
139
+ ctx.logger.info(message, data)
140
+ ctx.logger.error(message, data)
141
+ ```
142
+
143
+ ## Notes
144
+
145
+ Plugin packages should normally use this SDK as a TypeScript type dependency. Database credentials, JWT verification, Redis token checks, and route mounting are handled by the host side.
146
+
147
+ ## 文件上传(SDK 0.1.5 / 开发宿主 0.1.7 / 生产宿主 1.0.1)
148
+
149
+ 生产宿主和开发宿主均支持 `multipart/form-data`。通过原有的
150
+ `plugin.json.routes` 注册 POST 路由,无需在插件内安装 Web 框架或解析器。
151
+ 请求先鉴权和匹配路由,再读取上传内容。
152
+
153
+ ```ts
154
+ import type { PluginHandler } from '@workopilot/pluginapi-sdk';
155
+
156
+ export const upload: PluginHandler = async ({ request }) => {
157
+ const file = request.files?.find((item) => item.fieldname === 'file');
158
+ if (!file) {
159
+ return { message: '请选择文件。' };
160
+ }
161
+ // file.buffer 是 Uint8Array(Node.js 宿主实际提供 Buffer)。
162
+ // 在这里调用应用已有的文件处理或存储逻辑;宿主不会自动保存文件。
163
+ return {
164
+ filename: file.filename,
165
+ mimetype: file.mimetype,
166
+ size: file.size
167
+ };
168
+ };
169
+ ```
170
+
171
+ `request.files` 是文件数组,每项提供 `fieldname`、`filename`、`mimetype`、
172
+ `encoding`、`size` 和 `buffer`。相同字段名的多个文件也按上传顺序保留。
173
+ 普通表单字段放在 `request.body` 中,重复字段为数组;使用前仍需校验和收窄类型。
174
+ 非 multipart 请求保持原来的 `body`,不设置 `files`。
175
+
176
+ ```bash
177
+ curl -H 'Authorization: Bearer <token>' \
178
+ -F 'file=@./report.pdf' -F 'title=月报' \
179
+ http://127.0.0.1:3100/plugins/my-plugin/upload
180
+ ```
181
+
182
+ 浏览器可使用 `FormData` 或前端 SDK 的 `uploadFile()`;不要手动设置
183
+ `Content-Type`,浏览器需要自动生成 boundary。文件名和媒体类型均由客户端提供,
184
+ 业务代码应按用途校验,不能把文件名直接用作存储路径。文件内容只在当前请求中驻留内存。
185
+
186
+ 生产宿主 `.env` 和开发宿主 `.env.local` 可配置以下正整数字节/数量限制:
187
+
188
+ | 环境变量 | 默认值 | 含义 |
189
+ | --- | ---: | --- |
190
+ | `UPLOAD_MAX_FILE_BYTES` | 20971520 | 单文件 20 MiB |
191
+ | `UPLOAD_MAX_FILES` | 5 | 每次请求最多 5 个文件 |
192
+ | `UPLOAD_MAX_TOTAL_BYTES` | 52428800 | 文件内容和解析后字段值合计 50 MiB |
193
+ | `UPLOAD_MAX_FIELDS` | 50 | 最多 50 个普通字段 |
194
+ | `UPLOAD_MAX_FIELD_BYTES` | 65536 | 单字段 64 KiB |
195
+
196
+ 超过限制返回 413,格式错误返回 400,不会把截断内容交给 Handler。
197
+ 网关自身的上传限制仍需覆盖实际业务需求。
198
+
199
+ ## 数据库事务(SDK 0.1.6 / 开发宿主 0.1.8 / 生产宿主 1.0.2)
200
+
201
+ 通过 `ctx.database.transaction(async (tx) => { ... })` 使用单数据库事务。
202
+ HTTP Handler 和 MCP 工具使用相同协议,旧的数据库读写方法保持兼容。
203
+
204
+ ```ts
205
+ const result = await ctx.database.transaction(async (tx) => {
206
+ const order = await tx.insert(
207
+ 'INSERT INTO orders (tenant_id, order_no) VALUES (?, ?)',
208
+ [ctx.currentUser.tenantId, orderNo]
209
+ );
210
+ const stock = await tx.update(
211
+ `UPDATE inventory
212
+ SET quantity = quantity - ?
213
+ WHERE tenant_id = ? AND id = ? AND quantity >= ?`,
214
+ [quantity, ctx.currentUser.tenantId, inventoryId, quantity]
215
+ );
216
+ if (stock.affectedRows !== 1) {
217
+ throw new Error('库存不足。');
218
+ }
219
+ return { orderId: order.insertId };
220
+ });
221
+ ```
222
+
223
+ 示例中的业务参数应先校验;表结构由应用自己的 SQL 交付流程管理。
224
+ `tx` 的类型为 `DatabaseTransaction`,提供与普通调用一致的
225
+ `query / insert / update / delete`;公共业务方法应接受 `DatabaseSession` 参数,
226
+ 从而可同时接收 `ctx.database` 或 `tx`,不要在事务辅助方法中重新使用外层数据库对象。
227
+
228
+ - 所有 `tx` 操作使用同一条连接。回调正常返回后自动提交,提交成功后才返回结果。
229
+ - 返回 `{ ok: false }` 仍属于正常返回;业务需要撤销时必须抛出异常。
230
+ - 任意事务 SQL 失败都会标记整个事务失败,即使被业务代码 catch,也会整体回滚。
231
+ - `ctx.database` 的普通方法不会自动加入当前事务;需要原子性的操作必须全部使用 `tx`。
232
+ - 所有数据库操作必须 await;回调结束仍有未完成操作时,等待其结束后回滚并报错。
233
+ - `tx` 在回调结束后失效,不得缓存、跨请求或用于后台任务。
234
+ - 不支持嵌套事务或保存点;通过传递现有 `tx` 组合业务方法。
235
+ - 隔离级别沿用数据库配置,不自动重试,不提供跨库或跨请求事务。
236
+ - 使用支持事务的表引擎(例如 InnoDB)。继续显式添加租户条件,事务不会自动补充租户隔离。
237
+ - 不在事务内执行 DDL、手工事务控制语句,避免隐式提交或改变宿主管理的事务边界。
238
+ - 尽量不在事务回调中执行上传、外部 API 或耗时工作;这些操作不能由数据库回滚。
239
+ - 提交时断连可能导致提交结果不确定,宿主会报错并丢弃连接;业务应依靠幂等约束处理重试。
240
+
241
+ 正常回滚后连接归还连接池;开启、提交、回滚失败或连接致命错误时销毁连接,
242
+ 异常继续向调用方传播。调用方可在 transaction 外统一处理业务错误。
243
+
244
+ | 错误码 | 含义 |
245
+ | --- | --- |
246
+ | `TRANSACTION_NESTED` | 当前异步上下文存在活动事务,禁止再次开启 |
247
+ | `TRANSACTION_CLOSED` | 事务回调已结束,不能再使用 tx |
248
+ | `TRANSACTION_FAILED` | 已有 SQL 失败,禁止继续执行新的 SQL |
249
+ | `TRANSACTION_PENDING` | 回调返回时仍有未等待完成的数据库操作 |
250
+
251
+ 原始 SQL 和驱动错误保留用于宿主日志排查,业务接口不要向客户端返回数据库内部信息。
package/dist/index.d.ts CHANGED
@@ -25,12 +25,20 @@ export interface DatabaseWriteResult {
25
25
  changedRows?: number;
26
26
  info?: string;
27
27
  }
28
- export interface DatabaseCapability {
28
+ /** 普通及事务内共用的数据库读写协议。 */
29
+ export interface DatabaseSession {
29
30
  query<T = Record<string, unknown>>(sql: string, params?: QueryParam[]): Promise<T[]>;
30
31
  insert(sql: string, params?: QueryParam[]): Promise<DatabaseWriteResult>;
31
32
  update(sql: string, params?: QueryParam[]): Promise<DatabaseWriteResult>;
32
33
  delete(sql: string, params?: QueryParam[]): Promise<DatabaseWriteResult>;
33
34
  }
35
+ /** 宿主管理的事务会话,不暴露连接、提交或回滚方法。 */
36
+ export interface DatabaseTransaction extends DatabaseSession {
37
+ }
38
+ /** 由宿主注入的数据库能力,事务回调成功后自动提交。 */
39
+ export interface DatabaseCapability extends DatabaseSession {
40
+ transaction<T>(callback: (tx: DatabaseTransaction) => Promise<T> | T): Promise<T>;
41
+ }
34
42
  export interface PluginLogger {
35
43
  info(message: string, data?: unknown): void;
36
44
  error(message: string, data?: unknown): void;
@@ -44,12 +52,29 @@ export interface CurrentUser {
44
52
  deptName: string;
45
53
  deptCategory: string;
46
54
  }
55
+ /** 宿主解析后的上传文件,仅在本次请求中驻留内存,不自动保存。 */
56
+ export interface PluginUploadedFile {
57
+ /** 表单文件字段名。 */
58
+ fieldname: string;
59
+ /** 客户端提供的文件名,不可直接作为存储路径。 */
60
+ filename: string;
61
+ /** 客户端声明的媒体类型。 */
62
+ mimetype: string;
63
+ /** 文件传输编码。 */
64
+ encoding: string;
65
+ /** 文件实际字节数。 */
66
+ size: number;
67
+ /** 文件内容,Node.js 宿主实际提供 Buffer。 */
68
+ buffer: Uint8Array;
69
+ }
47
70
  export interface PluginRequest {
48
71
  method: string;
49
72
  url: string;
50
73
  query: unknown;
51
74
  body: unknown;
52
75
  headers: Record<string, string | string[] | undefined>;
76
+ /** multipart 请求的文件列表;普通字段位于 body,重复字段为数组。 */
77
+ files?: PluginUploadedFile[];
53
78
  }
54
79
  export interface PluginContext {
55
80
  /** 智能体平台服务域名,由宿主配置并注入,不包含 /net-api。 */
package/package.json CHANGED
@@ -1,33 +1,33 @@
1
- {
2
- "name": "@workopilot/pluginapi-sdk",
3
- "version": "0.1.4",
4
- "description": "Workopilot plugin API SDK for database-capability plugins",
5
- "keywords": [
6
- "wiseai",
7
- "workopilot",
8
- "plugin",
9
- "sdk"
10
- ],
11
- "author": "workopilot",
12
- "license": "MIT",
13
- "type": "module",
14
- "main": "dist/index.js",
15
- "module": "dist/index.js",
16
- "types": "dist/index.d.ts",
17
- "exports": {
18
- ".": {
19
- "types": "./dist/index.d.ts",
20
- "import": "./dist/index.js"
21
- }
22
- },
23
- "files": [
24
- "dist",
25
- "README.md"
26
- ],
27
- "scripts": {
28
- "build": "tsc -p tsconfig.json"
29
- },
30
- "devDependencies": {
31
- "typescript": "^5.7.2"
32
- }
33
- }
1
+ {
2
+ "name": "@workopilot/pluginapi-sdk",
3
+ "version": "0.1.6",
4
+ "description": "Workopilot plugin API SDK for database-capability plugins",
5
+ "keywords": [
6
+ "wiseai",
7
+ "workopilot",
8
+ "plugin",
9
+ "sdk"
10
+ ],
11
+ "author": "workopilot",
12
+ "license": "MIT",
13
+ "type": "module",
14
+ "main": "dist/index.js",
15
+ "module": "dist/index.js",
16
+ "types": "dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md"
26
+ ],
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json"
29
+ },
30
+ "devDependencies": {
31
+ "typescript": "^5.7.2"
32
+ }
33
+ }