@fastgpt-plugin/cli 0.1.0-alpha.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 ADDED
@@ -0,0 +1,35 @@
1
+ ## @fastgpt-plugin/cli
2
+
3
+ FastGPT 插件开发的命令行工具,用于创建、构建和测试 FastGPT 工具 / 工具集。
4
+
5
+ ### Features
6
+
7
+ - **统一构建流程**
8
+ - 基于 `tsdown`,一键将 TypeScript 源码构建为 Node 22 兼容的 `dist` 产物
9
+ - 自动生成 d.ts 类型声明,方便在其他包中引用
10
+ - **工具/工具集专用构建**
11
+ - 支持以工具目录为入口(包含 `config.ts`、`index.ts` 等)
12
+ - 在临时目录中对 `config.ts` 做 AST 转换,自动注入必要的 `toolId`、版本等元信息
13
+ - 递归复制源码目录,自动跳过 `node_modules`、`dist`、`.build-*` 等目录
14
+ - **安全的构建行为**
15
+ - 不在构建过程中调用 `process.exit`,错误以异常抛出,方便在上层脚本中统一处理
16
+ - 自动创建临时构建目录并在构建结束后进行清理
17
+ - **测试友好**
18
+ - 内置 Vitest 配置,支持对构建逻辑进行单元测试
19
+ - 在测试环境下跳过对部分依赖的打包,构建更快更稳定
20
+
21
+ ### 待实现 / TODO
22
+
23
+ - **发布相关能力(publish)**
24
+ - 提供 `cli publish` 命令,将构建好的工具包一键发布到 npm 或内部制品库
25
+ - 支持从 `config.ts` / `package.json` 读取版本号并进行版本校验(防止重复发布)
26
+ - 集成变更日志(changelog)生成和打 tag 流程
27
+ - 可选的 dry-run 模式(仅输出将要执行的操作,不真正发布)
28
+ - 支持自定义 npm registry / token 配置(环境变量或配置文件)
29
+ - **项目脚手架**
30
+ - 新建单工具模板(含 `config.ts`、`src/index.ts`、测试和示例)
31
+ - 新建工具集模板(含 children 目录、共享配置示例)
32
+ - **更多开发体验优化**
33
+ - `watch` 模式:监听源码变化自动重新构建
34
+ - 输出更友好的构建日志和错误提示
35
+
@@ -0,0 +1 @@
1
+ export { };
package/dist/index.js ADDED
@@ -0,0 +1,444 @@
1
+ import path, { join } from "node:path";
2
+ import { consola } from "consola";
3
+ import { Command } from "commander";
4
+ import fs from "node:fs/promises";
5
+ import { input, select } from "@inquirer/prompts";
6
+ import { build } from "tsdown";
7
+ import { parse } from "@babel/parser";
8
+ import * as $traverse from "@babel/traverse";
9
+ import * as $generate from "@babel/generator";
10
+ import { existsSync, readdirSync } from "node:fs";
11
+
12
+ //#region package.json
13
+ var name = "@fastgpt-plugin/cli";
14
+ var version = "0.1.0";
15
+
16
+ //#endregion
17
+ //#region src/constants.ts
18
+ const CLI_NAME = name;
19
+ const CLI_VERSION = version;
20
+ const DEFAULT_PLUGIN_NAME = "./packages/my-tool";
21
+ const DEFAULT_PLUGIN_DESCRIPTION = "This is a FastGPT plugin";
22
+ const TOOL_TEMPLATES_DIR = path.join(import.meta.dirname, "../templates");
23
+
24
+ //#endregion
25
+ //#region src/helpers.ts
26
+ const logger = consola.withTag(CLI_NAME);
27
+
28
+ //#endregion
29
+ //#region src/commands/base.ts
30
+ /**
31
+ * 所有子命令的基类:
32
+ * - 统一命令接口类型
33
+ * - 强制实现 register 方法,用于向 Commander 注册自身
34
+ */
35
+ var BaseCommand = class {};
36
+
37
+ //#endregion
38
+ //#region src/prompts/create/deps.ts
39
+ const defaultDeps = {
40
+ input,
41
+ select
42
+ };
43
+
44
+ //#endregion
45
+ //#region src/prompts/create/input-prompt.ts
46
+ async function inputPrompt(deps, options) {
47
+ return deps.input({
48
+ ...options,
49
+ validate: (value) => {
50
+ if (!value || value.trim().length === 0) return "请输入有效的内容";
51
+ return true;
52
+ }
53
+ });
54
+ }
55
+
56
+ //#endregion
57
+ //#region src/prompts/create/prompt.ts
58
+ var CreatePrompt = class {
59
+ deps;
60
+ constructor(deps = defaultDeps) {
61
+ this.deps = deps;
62
+ }
63
+ /**
64
+ * 根据 CLI 传入的原始参数,交互式补全缺失字段,生成完整的 CreatePluginCommandOptions。
65
+ * - 如果 name、type、description 都已提供,则不进入交互流程,直接返回
66
+ * - 否则使用交互式 prompt 补全缺失部分
67
+ */
68
+ async run(input) {
69
+ const getPluginType = () => {
70
+ if (!input.typeFlag) return void 0;
71
+ return input.typeFlag === "tool-suite" ? "tool-suite" : "tool";
72
+ };
73
+ const pluginType = getPluginType();
74
+ if (input.nameArg && pluginType && input.descriptionFlag !== void 0) return {
75
+ name: input.nameArg,
76
+ cwd: input.cwd,
77
+ type: pluginType,
78
+ description: input.descriptionFlag
79
+ };
80
+ const getPluginNameInputPrompt = async () => {
81
+ return await inputPrompt(this.deps, {
82
+ message: "插件名称",
83
+ default: DEFAULT_PLUGIN_NAME
84
+ });
85
+ };
86
+ const name = input.nameArg ?? await getPluginNameInputPrompt();
87
+ const getPluginTypeSelectPrompt = async () => {
88
+ return await this.deps.select({
89
+ message: "选择插件类型",
90
+ choices: [{
91
+ name: "单工具",
92
+ value: "tool",
93
+ description: "创建一个独立的工具"
94
+ }, {
95
+ name: "工具集",
96
+ value: "tool-suite",
97
+ description: "创建一个包含多个子工具的工具集"
98
+ }]
99
+ });
100
+ };
101
+ const type = pluginType ?? await getPluginTypeSelectPrompt();
102
+ const getPluginDescriptionInputPrompt = async () => {
103
+ return await inputPrompt(this.deps, {
104
+ message: "插件描述",
105
+ default: DEFAULT_PLUGIN_DESCRIPTION
106
+ });
107
+ };
108
+ const description = input.descriptionFlag ?? await getPluginDescriptionInputPrompt();
109
+ return {
110
+ name,
111
+ cwd: input.cwd,
112
+ type,
113
+ description
114
+ };
115
+ }
116
+ };
117
+
118
+ //#endregion
119
+ //#region src/commands/create.ts
120
+ var CreateCommand = class extends BaseCommand {
121
+ register(parent) {
122
+ parent.command("create").description("创建新的 FastGPT 插件项目").argument("[name]", "插件名称").option("-t, --type <type>", "插件类型: 单工具 | 工具集").option("-d, --description <desc>", "插件描述").option("--cwd <path>", "工作目录", process.cwd()).action(async (name, opts) => {
123
+ const options = await new CreatePrompt().run({
124
+ nameArg: name,
125
+ typeFlag: opts.type,
126
+ descriptionFlag: opts.description,
127
+ cwd: opts.cwd
128
+ });
129
+ await this.run(options);
130
+ });
131
+ }
132
+ async run(options) {
133
+ const targetDir = path.resolve(options.cwd, options.name);
134
+ const templateDir = path.join(TOOL_TEMPLATES_DIR, options.type === "tool-suite" ? "tool-suite" : "tool");
135
+ const files = await this.collectTemplateFiles(templateDir);
136
+ const description = options.description ?? DEFAULT_PLUGIN_DESCRIPTION;
137
+ await this.ensureDir(targetDir);
138
+ for (const rel of files) {
139
+ const templatePath = path.join(templateDir, rel);
140
+ const filePath = path.join(targetDir, rel);
141
+ await this.ensureDir(path.dirname(filePath));
142
+ const raw = await fs.readFile(templatePath, "utf-8");
143
+ const content = this.applyPlaceholders(raw, options.name, description);
144
+ await fs.writeFile(filePath, content, "utf-8");
145
+ }
146
+ logger.success(`创建插件项目: ${options.name} (${options.type})`, { cwd: options.cwd });
147
+ }
148
+ applyPlaceholders(text, name, description) {
149
+ name = path.basename(name);
150
+ return text.replace(/\{\{name\}\}/g, name).replace(/\{\{description\}\}/g, description);
151
+ }
152
+ async collectTemplateFiles(root) {
153
+ const result = [];
154
+ const walk = async (dir) => {
155
+ const entries = await fs.readdir(dir, { withFileTypes: true });
156
+ for (const entry of entries) {
157
+ const full = path.join(dir, entry.name);
158
+ if (entry.isDirectory()) await walk(full);
159
+ else {
160
+ const rel = path.relative(root, full).replace(/\\/g, "/");
161
+ result.push(rel);
162
+ }
163
+ }
164
+ };
165
+ await walk(root);
166
+ return result.sort();
167
+ }
168
+ async ensureDir(dir) {
169
+ await fs.mkdir(dir, { recursive: true });
170
+ }
171
+ };
172
+
173
+ //#endregion
174
+ //#region src/build/ast-transform.ts
175
+ const traverse = $traverse.default;
176
+ const generate = $generate.default;
177
+ function extractToolId(filePath) {
178
+ const stack = filePath.split("/");
179
+ if (stack.at(-3) === "children") return `${stack.at(-4)}/${stack.at(-2)}`;
180
+ return stack.at(-2) || "unknown";
181
+ }
182
+ function transformToolConfig({ sourceCode, filePath }) {
183
+ if (sourceCode.includes("toolId:")) return {
184
+ code: sourceCode,
185
+ hasToolId: true
186
+ };
187
+ const ast = parse(sourceCode, {
188
+ plugins: ["typescript"],
189
+ sourceType: "module"
190
+ });
191
+ const toolId = extractToolId(filePath);
192
+ let modified = false;
193
+ const childrenDir = join(filePath, "..", "children");
194
+ let childrenList = [];
195
+ if (existsSync(childrenDir)) try {
196
+ childrenList = readdirSync(childrenDir);
197
+ } catch {}
198
+ traverse(ast, { CallExpression(path) {
199
+ if (path.node.callee.type === "Identifier" && path.node.arguments[0] && path.node.arguments[0].type === "ObjectExpression") {
200
+ const objExpr = path.node.arguments[0];
201
+ let hasToolId = false;
202
+ traverse(path.node, { ObjectProperty(innerPath) {
203
+ if (innerPath.node.key.type === "Identifier" && innerPath.node.key.name === "toolId") hasToolId = true;
204
+ } }, path.scope, path.parentPath);
205
+ if (!hasToolId) {
206
+ const toolIdProp = {
207
+ type: "ObjectProperty",
208
+ key: {
209
+ type: "Identifier",
210
+ name: "toolId"
211
+ },
212
+ value: {
213
+ type: "StringLiteral",
214
+ value: toolId
215
+ },
216
+ computed: false,
217
+ shorthand: false
218
+ };
219
+ objExpr.properties.push(toolIdProp);
220
+ modified = true;
221
+ }
222
+ if (path.node.callee.type === "Identifier" && path.node.callee.name === "defineToolSet") {
223
+ let hasCustomChildren = false;
224
+ traverse(path.node, { ObjectProperty(innerPath) {
225
+ if (innerPath.node.key.type === "Identifier" && innerPath.node.key.name === "children") hasCustomChildren = true;
226
+ } }, path.scope, path.parentPath);
227
+ if (!hasCustomChildren && childrenList.length > 0) {
228
+ for (const child of childrenList) {
229
+ const importDecl = {
230
+ type: "ImportDeclaration",
231
+ source: {
232
+ type: "StringLiteral",
233
+ value: `./children/${child}`
234
+ },
235
+ importKind: "value",
236
+ specifiers: [{
237
+ type: "ImportDefaultSpecifier",
238
+ local: {
239
+ type: "Identifier",
240
+ name: child
241
+ }
242
+ }]
243
+ };
244
+ ast.program.body.unshift(importDecl);
245
+ }
246
+ const childrenProp = {
247
+ type: "ObjectProperty",
248
+ key: {
249
+ type: "Identifier",
250
+ name: "children"
251
+ },
252
+ value: {
253
+ type: "ArrayExpression",
254
+ elements: childrenList.map((child) => ({
255
+ type: "Identifier",
256
+ name: child
257
+ }))
258
+ },
259
+ computed: false,
260
+ shorthand: false
261
+ };
262
+ objExpr.properties.push(childrenProp);
263
+ modified = true;
264
+ }
265
+ }
266
+ }
267
+ } });
268
+ return {
269
+ code: generate(ast).code,
270
+ hasToolId: !modified && sourceCode.includes("toolId:")
271
+ };
272
+ }
273
+
274
+ //#endregion
275
+ //#region src/build/index.ts
276
+ /**
277
+ * 核心构建逻辑:给定入口目录和输出目录,完成一次工具构建。
278
+ * - 不做日志输出
279
+ * - 不调用 process.exit
280
+ * - 失败时抛出 Error
281
+ */
282
+ async function buildToolPackage(options) {
283
+ const entryDir = path.resolve(options.entry);
284
+ await assertPathExists(entryDir, `入口目录不存在: ${entryDir}`);
285
+ const configPath = path.join(entryDir, "config.ts");
286
+ await assertPathExists(configPath, `找不到 config.ts 文件: ${configPath}`);
287
+ const indexPath = path.join(entryDir, "index.ts");
288
+ await assertPathExists(indexPath, `找不到 index.ts 文件: ${indexPath}`);
289
+ const tempDir = path.join(entryDir, ".build-temp");
290
+ await ensureDir(tempDir);
291
+ try {
292
+ const transformed = transformToolConfig({
293
+ sourceCode: await fs.readFile(configPath, "utf-8"),
294
+ filePath: configPath
295
+ });
296
+ await fs.writeFile(path.join(tempDir, "config.ts"), transformed.code, "utf-8");
297
+ await copySourceFiles(entryDir, tempDir, entryDir);
298
+ const outputDir = path.resolve(options.output);
299
+ await ensureDir(outputDir);
300
+ await build({
301
+ entry: [path.join(tempDir, "index.ts")],
302
+ outDir: outputDir,
303
+ format: [options.format],
304
+ clean: true,
305
+ minify: options.minify,
306
+ platform: "node",
307
+ target: "node22",
308
+ dts: {
309
+ enabled: true,
310
+ sourcemap: false
311
+ },
312
+ treeshake: true,
313
+ skipNodeModulesBundle: process.env.NODE_ENV === "test",
314
+ external: process.env.NODE_ENV === "test" ? ["@fastgpt-plugin/helpers"] : []
315
+ });
316
+ return {
317
+ entryDir,
318
+ outputDir,
319
+ files: (await fs.readdir(outputDir)).map((f) => f)
320
+ };
321
+ } finally {
322
+ try {
323
+ await fs.rm(tempDir, {
324
+ recursive: true,
325
+ force: true
326
+ });
327
+ } catch {}
328
+ }
329
+ }
330
+ /**
331
+ * 从入口目录复制源码到临时目录:
332
+ * - 根目录的 config.ts 已被转换,不再复制
333
+ * - 子目录中的 config.ts 需要保留(子工具自身的配置)
334
+ */
335
+ async function copySourceFiles(sourceDir, targetDir, rootDir) {
336
+ const files = await fs.readdir(sourceDir, { withFileTypes: true });
337
+ for (const file of files) {
338
+ if (file.name === "node_modules" || file.name === "dist" || file.name.startsWith(".build-")) continue;
339
+ const sourcePath = path.join(sourceDir, file.name);
340
+ const targetPath = path.join(targetDir, file.name);
341
+ if (file.isDirectory()) {
342
+ await ensureDir(targetPath);
343
+ await copySourceFiles(sourcePath, targetPath, rootDir);
344
+ } else if (file.isFile()) {
345
+ if (!(file.name === "config.ts" && sourceDir === rootDir)) if (file.name === "config.ts") {
346
+ const transformed = transformToolConfig({
347
+ sourceCode: await fs.readFile(sourcePath, "utf-8"),
348
+ filePath: sourcePath
349
+ });
350
+ await fs.writeFile(targetPath, transformed.code, "utf-8");
351
+ } else await fs.copyFile(sourcePath, targetPath);
352
+ }
353
+ }
354
+ }
355
+ async function ensureDir(dir) {
356
+ await fs.mkdir(dir, { recursive: true });
357
+ }
358
+ async function assertPathExists(p, message) {
359
+ try {
360
+ await fs.access(p);
361
+ } catch {
362
+ throw new Error(message);
363
+ }
364
+ }
365
+
366
+ //#endregion
367
+ //#region src/commands/build.ts
368
+ var BuildCommand = class extends BaseCommand {
369
+ register(parent) {
370
+ parent.command("build").description("构建 FastGPT 插件为可分发的包").option("-e, --entry <path>", "工具入口目录", process.cwd()).option("-o, --output <path>", "输出目录", "./dist").option("-m, --minify", "压缩输出代码", false).option("-w, --watch", "监听模式", false).option("-f, --format <format>", "输出格式: esm | cjs", "esm").action(async (opts) => {
371
+ await this.run({
372
+ entry: opts.entry,
373
+ output: opts.output,
374
+ minify: opts.minify,
375
+ watch: opts.watch,
376
+ format: opts.format
377
+ });
378
+ });
379
+ }
380
+ async run(options) {
381
+ const start = Date.now();
382
+ logger.box([
383
+ "FastGPT 插件构建",
384
+ "",
385
+ `入口目录: ${options.entry}`,
386
+ `输出目录: ${options.output}`,
387
+ `代码压缩: ${options.minify ? "开启" : "关闭"}`,
388
+ `输出格式: ${options.format}`,
389
+ ""
390
+ ].join("\n"));
391
+ logger.start("准备构建插件...");
392
+ try {
393
+ const result = await buildToolPackage(options);
394
+ const duration = ((Date.now() - start) / 1e3).toFixed(2);
395
+ logger.success(`构建完成,用时 ${duration}s`);
396
+ logger.info(`输出目录: ${result.outputDir}`);
397
+ if (result.files.length > 0) {
398
+ logger.info("生成的文件列表:");
399
+ result.files.forEach((file) => {
400
+ logger.info(` • ${file}`);
401
+ });
402
+ } else logger.info("未检测到输出文件,请检查配置。");
403
+ logger.info("\n下一步: 可以将该目录作为 npm 包发布,或在 FastGPT 中作为插件安装使用。");
404
+ if (options.watch) logger.info("\n监听模式暂不支持,请使用 --no-watch 选项");
405
+ } catch (error) {
406
+ logger.error("构建失败,详情如下:");
407
+ logger.error(error instanceof Error ? error : new Error(String(error)));
408
+ logger.info("如果这是在 CI 中发生的,请查看上方构建日志以获取更多信息。");
409
+ process.exit(1);
410
+ }
411
+ }
412
+ };
413
+
414
+ //#endregion
415
+ //#region src/cmd.ts
416
+ function createProgram() {
417
+ const program = new Command();
418
+ program.name(CLI_NAME).version(CLI_VERSION).description("FastGPT 插件开发 CLI");
419
+ new CreateCommand().register(program);
420
+ new BuildCommand().register(program);
421
+ return program;
422
+ }
423
+ /**
424
+ * 运行 CLI,解析 process.argv。
425
+ * @param argv 可选,用于测试时注入参数(如 ['node', 'cli', '--version'])
426
+ */
427
+ async function run(argv) {
428
+ await createProgram().parseAsync(argv ?? process.argv);
429
+ }
430
+
431
+ //#endregion
432
+ //#region src/index.ts
433
+ const main = async () => {
434
+ try {
435
+ await run();
436
+ } catch (error) {
437
+ logger.error(error);
438
+ process.exitCode = 1;
439
+ }
440
+ };
441
+ if (import.meta.main) main();
442
+
443
+ //#endregion
444
+ export { };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@fastgpt-plugin/cli",
3
+ "version": "0.1.0-alpha.1",
4
+ "type": "module",
5
+ "private": false,
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "bin": {
10
+ "@fastgpt-plugin/cli": "dist/index.js"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "templates",
15
+ "README.md",
16
+ "LICENSE",
17
+ "package.json"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsdown",
21
+ "test": "vitest run",
22
+ "start": "bun run src/index.ts",
23
+ "dev": "bun run src/index.ts"
24
+ },
25
+ "dependencies": {
26
+ "@babel/generator": "^7.26.5",
27
+ "@babel/parser": "^7.26.5",
28
+ "@babel/traverse": "^7.26.5",
29
+ "@babel/types": "^7.26.5",
30
+ "@inquirer/prompts": "^8.2.0",
31
+ "commander": "^14.0.3",
32
+ "consola": "^3.4.2",
33
+ "tsdown": "^0.20.1"
34
+ },
35
+ "devDependencies": {
36
+ "@types/bun": "latest",
37
+ "typescript": "^5",
38
+ "vite-tsconfig-paths": "^6.0.5",
39
+ "vitest": "^4.0.18"
40
+ },
41
+ "engines": {
42
+ "node": ">=22.0.0"
43
+ }
44
+ }
@@ -0,0 +1,11 @@
1
+ # {{name}}
2
+
3
+ {{description}}
4
+
5
+ ## 开发
6
+
7
+ ```bash
8
+ bun install
9
+ bun run build
10
+ bun run test
11
+ ```
@@ -0,0 +1,29 @@
1
+ import { defineTool, WorkflowIOValueTypeEnum, ToolTagEnum } from '@fastgpt-plugin/helpers';
2
+
3
+ export default defineTool({
4
+ tags: [ToolTagEnum.enum.tools],
5
+ name: {
6
+ 'zh-CN': '{{name}}',
7
+ en: '{{name}}'
8
+ },
9
+ description: {
10
+ 'zh-CN': '{{description}}',
11
+ en: '{{description}}'
12
+ },
13
+ icon: 'core/workflow/template/{{name}}',
14
+ versionList: [
15
+ {
16
+ value: '0.0.1',
17
+ description: 'Initial version',
18
+ inputs: [],
19
+ outputs: [
20
+ {
21
+ key: 'message',
22
+ valueType: WorkflowIOValueTypeEnum.enum.string,
23
+ label: 'Message',
24
+ description: 'Tool output message'
25
+ }
26
+ ]
27
+ }
28
+ ]
29
+ });
@@ -0,0 +1,10 @@
1
+ import { exportTool } from '@fastgpt-plugin/helpers/tools/helper';
2
+ import config from './config.js';
3
+ import { InputType, OutputType, tool as toolCb } from './src/tool.js';
4
+
5
+ export default exportTool({
6
+ toolCb,
7
+ InputType,
8
+ OutputType,
9
+ config
10
+ });
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
2
+ <rect width="64" height="64" rx="8" fill="#e0e7ff" />
3
+ <text x="32" y="40" text-anchor="middle" font-size="24" fill="#4338ca">?</text>
4
+ </svg>
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.0.1",
4
+ "description": "{{description}}",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "test": "vitest run"
10
+ },
11
+ "dependencies": {
12
+ "@fastgpt-plugin/helpers": "catalog:",
13
+ "zod": "catalog:"
14
+ },
15
+ "devDependencies": {
16
+ "typescript": "catalog:",
17
+ "vitest": "catalog:"
18
+ }
19
+ }
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+
3
+ export const InputType = z.object({});
4
+
5
+ export const OutputType = z.object({
6
+ message: z.string()
7
+ });
8
+
@@ -0,0 +1,37 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { tool } from './tool';
3
+ import { InputType, OutputType } from './schemas';
4
+
5
+ describe('{{name}}', () => {
6
+ it('should run with valid IO schemas', async () => {
7
+ const input = InputType.parse({});
8
+ const result = await tool(input, {
9
+ systemVar: {
10
+ user: {
11
+ id: 'test',
12
+ username: 'test',
13
+ contact: 'test',
14
+ membername: 'test',
15
+ teamName: 'test',
16
+ teamId: 'test',
17
+ name: 'test'
18
+ },
19
+ app: {
20
+ id: 'test',
21
+ name: 'test'
22
+ },
23
+ tool: {
24
+ id: 'test',
25
+ version: '0.0.1'
26
+ },
27
+ time: new Date().toISOString()
28
+ },
29
+ streamResponse: () => {
30
+ // noop
31
+ }
32
+ });
33
+
34
+ const output = OutputType.parse(result);
35
+ expect(output).toBeDefined();
36
+ });
37
+ });
@@ -0,0 +1,10 @@
1
+ import type { RunToolSecondParamsType } from '@fastgpt-plugin/helpers/tools/schemas/req';
2
+ import type { z } from 'zod';
3
+ import { InputType, OutputType } from './schemas';
4
+
5
+ export async function tool(
6
+ _input: z.infer<typeof InputType>,
7
+ _ctx: RunToolSecondParamsType
8
+ ): Promise<z.infer<typeof OutputType>> {
9
+ return { message: 'Hello from {{name}}' };
10
+ }
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: 'node'
6
+ }
7
+ });
@@ -0,0 +1,11 @@
1
+ # {{name}}
2
+
3
+ {{description}}
4
+
5
+ ## 开发
6
+
7
+ ```bash
8
+ bun install
9
+ bun run build
10
+ bun run test
11
+ ```
@@ -0,0 +1,29 @@
1
+ import { defineTool, WorkflowIOValueTypeEnum, ToolTagEnum } from '@fastgpt-plugin/helpers';
2
+
3
+ export default defineTool({
4
+ tags: [ToolTagEnum.enum.tools],
5
+ name: {
6
+ 'zh-CN': '{{name}}',
7
+ en: '{{name}}'
8
+ },
9
+ description: {
10
+ 'zh-CN': '{{description}}',
11
+ en: '{{description}}'
12
+ },
13
+ icon: 'core/workflow/template/{{name}}',
14
+ versionList: [
15
+ {
16
+ value: '0.0.1',
17
+ description: 'Initial version',
18
+ inputs: [],
19
+ outputs: [
20
+ {
21
+ key: 'message',
22
+ valueType: WorkflowIOValueTypeEnum.enum.string,
23
+ label: 'Message',
24
+ description: 'Tool output message'
25
+ }
26
+ ]
27
+ }
28
+ ]
29
+ });
@@ -0,0 +1,10 @@
1
+ import { exportTool } from '@fastgpt-plugin/helpers/tools/helper';
2
+ import config from './config.js';
3
+ import { InputType, OutputType, tool as toolCb } from './src/tool.js';
4
+
5
+ export default exportTool({
6
+ toolCb,
7
+ InputType,
8
+ OutputType,
9
+ config
10
+ });
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
2
+ <rect width="64" height="64" rx="8" fill="#e0e7ff" />
3
+ <text x="32" y="40" text-anchor="middle" font-size="24" fill="#4338ca">?</text>
4
+ </svg>
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+
3
+ export const InputType = z.object({});
4
+
5
+ export const OutputType = z.object({
6
+ message: z.string()
7
+ });
8
+
@@ -0,0 +1,37 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { tool } from './tool';
3
+ import { InputType, OutputType } from './schemas';
4
+
5
+ describe('{{name}} child tool', () => {
6
+ it('should run with valid IO schemas', async () => {
7
+ const input = InputType.parse({});
8
+ const result = await tool(input, {
9
+ systemVar: {
10
+ user: {
11
+ id: 'test',
12
+ username: 'test',
13
+ contact: 'test',
14
+ membername: 'test',
15
+ teamName: 'test',
16
+ teamId: 'test',
17
+ name: 'test'
18
+ },
19
+ app: {
20
+ id: 'test',
21
+ name: 'test'
22
+ },
23
+ tool: {
24
+ id: 'test',
25
+ version: '0.0.1'
26
+ },
27
+ time: new Date().toISOString()
28
+ },
29
+ streamResponse: () => {
30
+ // noop
31
+ }
32
+ });
33
+
34
+ const output = OutputType.parse(result);
35
+ expect(output).toBeDefined();
36
+ });
37
+ });
@@ -0,0 +1,10 @@
1
+ import type { RunToolSecondParamsType } from '@fastgpt-plugin/helpers/tools/schemas/req';
2
+ import type { z } from 'zod';
3
+ import { InputType, OutputType } from './schemas';
4
+
5
+ export async function tool(
6
+ _input: z.infer<typeof InputType>,
7
+ _ctx: RunToolSecondParamsType
8
+ ): Promise<z.infer<typeof OutputType>> {
9
+ return { message: 'Hello from {{name}}' };
10
+ }
@@ -0,0 +1,13 @@
1
+ import { defineToolSet, ToolTagEnum } from '@fastgpt-plugin/helpers';
2
+
3
+ export default defineToolSet({
4
+ tags: [ToolTagEnum.enum.tools],
5
+ name: {
6
+ 'zh-CN': '{{name}}',
7
+ en: '{{name}}'
8
+ },
9
+ description: {
10
+ 'zh-CN': '{{description}}',
11
+ en: '{{description}}'
12
+ }
13
+ });
@@ -0,0 +1,2 @@
1
+ export { default as config } from './config.js';
2
+ export { tool as toolFromChild } from './children/tool/src/index.js';
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
2
+ <rect width="64" height="64" rx="8" fill="#e0e7ff" />
3
+ <text x="32" y="40" text-anchor="middle" font-size="24" fill="#4338ca">?</text>
4
+ </svg>
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.0.1",
4
+ "description": "{{description}}",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "test": "vitest run"
10
+ },
11
+ "dependencies": {
12
+ "@fastgpt-plugin/helpers": "catalog:",
13
+ "zod": "catalog:"
14
+ },
15
+ "devDependencies": {
16
+ "typescript": "catalog:",
17
+ "vitest": "catalog:"
18
+ }
19
+ }
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: 'node'
6
+ }
7
+ });
8
+