@cloudbase/cli 2.10.0-beta.0 → 2.11.0-beta.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.
Files changed (205) hide show
  1. package/lib/auth/login.js +51 -65
  2. package/lib/auth/logout.js +3 -14
  3. package/lib/commands/account/login.js +136 -149
  4. package/lib/commands/account/logout.js +3 -14
  5. package/lib/commands/ag/base.js +203 -0
  6. package/lib/commands/ag/create.js +301 -0
  7. package/lib/commands/ag/debug/index.html +699 -0
  8. package/lib/commands/ag/delete.js +200 -0
  9. package/lib/commands/ag/deploy.js +185 -0
  10. package/lib/commands/ag/detail.js +113 -0
  11. package/lib/commands/ag/index.js +22 -0
  12. package/lib/commands/ag/list.js +155 -0
  13. package/lib/commands/ag/run.js +644 -0
  14. package/lib/commands/ai/index.js +76 -95
  15. package/lib/commands/cloudfunction/base.js +182 -203
  16. package/lib/commands/cloudrun/base.js +578 -603
  17. package/lib/commands/common.js +48 -63
  18. package/lib/commands/config/delete.js +16 -27
  19. package/lib/commands/config/get.js +13 -24
  20. package/lib/commands/config/list.js +16 -27
  21. package/lib/commands/config/set.js +33 -44
  22. package/lib/commands/db/base.js +221 -240
  23. package/lib/commands/env/base.js +36 -49
  24. package/lib/commands/env/domain.js +79 -94
  25. package/lib/commands/env/login.js +120 -135
  26. package/lib/commands/framework/index.js +32 -49
  27. package/lib/commands/fun/base.js +223 -244
  28. package/lib/commands/functions/alias/getRoute.js +33 -44
  29. package/lib/commands/functions/alias/setRoute.js +36 -47
  30. package/lib/commands/functions/code-download.js +43 -54
  31. package/lib/commands/functions/code-update.js +23 -34
  32. package/lib/commands/functions/concurrency/delete.js +11 -22
  33. package/lib/commands/functions/concurrency/list.js +20 -31
  34. package/lib/commands/functions/concurrency/set.js +13 -24
  35. package/lib/commands/functions/config-update.js +30 -41
  36. package/lib/commands/functions/copy.js +12 -23
  37. package/lib/commands/functions/delete.js +30 -41
  38. package/lib/commands/functions/deploy.js +184 -202
  39. package/lib/commands/functions/detail.js +23 -34
  40. package/lib/commands/functions/invoke.js +69 -75
  41. package/lib/commands/functions/layer/bind.js +102 -105
  42. package/lib/commands/functions/layer/create.js +29 -35
  43. package/lib/commands/functions/layer/delete.js +42 -48
  44. package/lib/commands/functions/layer/download.js +52 -58
  45. package/lib/commands/functions/layer/list.js +44 -50
  46. package/lib/commands/functions/layer/sort.js +39 -45
  47. package/lib/commands/functions/list.js +25 -36
  48. package/lib/commands/functions/log.js +65 -73
  49. package/lib/commands/functions/run.js +118 -116
  50. package/lib/commands/functions/trigger-create.js +32 -43
  51. package/lib/commands/functions/trigger-delete.js +50 -61
  52. package/lib/commands/functions/version/list.js +29 -40
  53. package/lib/commands/functions/version/publish.js +11 -22
  54. package/lib/commands/gateway/create.js +50 -61
  55. package/lib/commands/gateway/delete.js +38 -49
  56. package/lib/commands/gateway/domain.js +65 -80
  57. package/lib/commands/gateway/list.js +31 -42
  58. package/lib/commands/gateway/switch.js +48 -61
  59. package/lib/commands/helpers/init.js +226 -249
  60. package/lib/commands/helpers/new.js +35 -46
  61. package/lib/commands/helpers/open.js +22 -33
  62. package/lib/commands/hosting/hosting.js +157 -178
  63. package/lib/commands/index.js +1 -0
  64. package/lib/commands/lowcode/app.js +114 -144
  65. package/lib/commands/lowcode/comps.js +136 -127
  66. package/lib/commands/lowcode/utils.js +11 -22
  67. package/lib/commands/pull/pull.js +33 -46
  68. package/lib/commands/run/delete.js +35 -46
  69. package/lib/commands/run/image/delete.js +32 -39
  70. package/lib/commands/run/image/download.js +26 -33
  71. package/lib/commands/run/image/list.js +41 -48
  72. package/lib/commands/run/image/upload.js +26 -33
  73. package/lib/commands/run/list.js +32 -43
  74. package/lib/commands/run/service/config.js +17 -28
  75. package/lib/commands/run/service/deploy.js +15 -26
  76. package/lib/commands/run/service/list.js +48 -59
  77. package/lib/commands/run/service/update.js +7 -18
  78. package/lib/commands/run/standalonegateway/create.js +35 -42
  79. package/lib/commands/run/standalonegateway/destroy.js +23 -30
  80. package/lib/commands/run/standalonegateway/list.js +19 -26
  81. package/lib/commands/run/standalonegateway/package.js +31 -38
  82. package/lib/commands/run/standalonegateway/turn.js +27 -34
  83. package/lib/commands/run/version/create.js +198 -205
  84. package/lib/commands/run/version/delete.js +31 -38
  85. package/lib/commands/run/version/list.js +42 -49
  86. package/lib/commands/run/version/modify.js +27 -34
  87. package/lib/commands/run/version/update.js +201 -208
  88. package/lib/commands/runf/base.js +216 -237
  89. package/lib/commands/self-update.js +59 -72
  90. package/lib/commands/smart.js +66 -79
  91. package/lib/commands/storage/storage.js +192 -219
  92. package/lib/commands/third/thirdAttach.js +16 -27
  93. package/lib/commands/utils.js +119 -149
  94. package/lib/db/index.js +48 -67
  95. package/lib/decorators/captureError.js +10 -21
  96. package/lib/decorators/guard.js +11 -22
  97. package/lib/decorators/injectParams.js +29 -40
  98. package/lib/decorators/params/common.js +5 -2
  99. package/lib/decorators/params/index.js +3 -12
  100. package/lib/env/domain.js +13 -28
  101. package/lib/env/index.js +25 -44
  102. package/lib/env/login.js +30 -45
  103. package/lib/function/alias.js +31 -44
  104. package/lib/function/base.js +187 -215
  105. package/lib/function/code.js +8 -19
  106. package/lib/function/concurrency.js +43 -58
  107. package/lib/function/create.js +43 -53
  108. package/lib/function/delete.js +22 -35
  109. package/lib/function/layer/attach.js +33 -46
  110. package/lib/function/layer/create.js +34 -45
  111. package/lib/function/layer/delete.js +5 -16
  112. package/lib/function/layer/download.js +11 -22
  113. package/lib/function/layer/list.js +12 -25
  114. package/lib/function/layer/sort.js +6 -17
  115. package/lib/function/trigger.js +65 -82
  116. package/lib/function/update.js +24 -32
  117. package/lib/function/version.js +29 -42
  118. package/lib/function/vpc.js +12 -25
  119. package/lib/gateway/index.js +77 -104
  120. package/lib/hosting.js +157 -188
  121. package/lib/run/delete.js +3 -12
  122. package/lib/run/image/build.js +6 -15
  123. package/lib/run/image/delete.js +3 -12
  124. package/lib/run/image/info.js +3 -12
  125. package/lib/run/image/list.js +6 -15
  126. package/lib/run/list.js +19 -30
  127. package/lib/run/repo.js +6 -15
  128. package/lib/run/service/common.js +160 -173
  129. package/lib/run/service/config.js +44 -57
  130. package/lib/run/service/deployPackage.js +33 -44
  131. package/lib/run/service/list.js +8 -14
  132. package/lib/run/service/showLogs.js +69 -90
  133. package/lib/run/service/update.js +50 -63
  134. package/lib/run/standalonegateway/create.js +3 -12
  135. package/lib/run/standalonegateway/destroy.js +3 -12
  136. package/lib/run/standalonegateway/list.js +3 -12
  137. package/lib/run/standalonegateway/package/list.js +3 -12
  138. package/lib/run/standalonegateway/turn/off.js +3 -12
  139. package/lib/run/standalonegateway/turn/on.js +3 -12
  140. package/lib/run/version/create.js +41 -31
  141. package/lib/run/version/delete.js +3 -12
  142. package/lib/run/version/list.js +3 -12
  143. package/lib/run/version/modify.js +3 -12
  144. package/lib/run/version/repo.js +6 -15
  145. package/lib/run/version/update.js +37 -26
  146. package/lib/storage.js +62 -93
  147. package/lib/third/index.js +6 -17
  148. package/lib/utils/ai/banner.js +49 -60
  149. package/lib/utils/ai/claudeWindows.js +2 -2
  150. package/lib/utils/ai/config.js +169 -206
  151. package/lib/utils/ai/ensureFiles.js +6 -17
  152. package/lib/utils/ai/env.js +16 -27
  153. package/lib/utils/ai/envLocalManager.js +35 -52
  154. package/lib/utils/ai/router.js +927 -1005
  155. package/lib/utils/ai/setup.js +527 -563
  156. package/lib/utils/auth.js +3 -14
  157. package/lib/utils/checkTcbrEnv.js +20 -31
  158. package/lib/utils/cli-table.js +6 -1
  159. package/lib/utils/config.js +4 -13
  160. package/lib/utils/dts.js +98 -113
  161. package/lib/utils/env.js +154 -175
  162. package/lib/utils/function-packer.js +29 -42
  163. package/lib/utils/log.js +10 -21
  164. package/lib/utils/mcp-config-modifier.js +105 -120
  165. package/lib/utils/net/cloud-api-request.js +15 -23
  166. package/lib/utils/net/credential.js +26 -39
  167. package/lib/utils/net/http-request.js +63 -80
  168. package/lib/utils/net/manager-service.js +22 -35
  169. package/lib/utils/notice.js +16 -27
  170. package/lib/utils/output/loading.js +3 -12
  171. package/lib/utils/parallel.js +32 -43
  172. package/lib/utils/platform/mac.js +4 -15
  173. package/lib/utils/platform/port.js +4 -15
  174. package/lib/utils/prompt/select.js +6 -15
  175. package/lib/utils/report.js +28 -33
  176. package/lib/utils/reporter/agree.js +11 -22
  177. package/lib/utils/reporter/download.js +17 -28
  178. package/lib/utils/reporter/usage.js +12 -23
  179. package/lib/utils/store/auth.js +17 -30
  180. package/lib/utils/store/config.js +11 -25
  181. package/lib/utils/store/db.js +17 -36
  182. package/lib/utils/tcbrApi/callTcbrApi.js +19 -28
  183. package/lib/utils/template-manager.js +215 -242
  184. package/lib/utils/template.js +81 -96
  185. package/lib/utils/tools/common.js +45 -56
  186. package/lib/utils/tools/time.js +5 -16
  187. package/lib/utils/url.js +10 -4
  188. package/package.json +2 -2
  189. package/specs/ag-command/design.md +421 -0
  190. package/specs/ag-command/doc.md +204 -0
  191. package/specs/ag-command/requirements.md +173 -0
  192. package/specs/ag-command/summary.md +174 -0
  193. package/specs/ag-command/tasks.md +197 -0
  194. package/specs/ag-command/usage-guide.md +420 -0
  195. package/tsconfig.json +1 -1
  196. package/types/commands/ag/base.d.ts +44 -0
  197. package/types/commands/ag/create.d.ts +25 -0
  198. package/types/commands/ag/delete.d.ts +32 -0
  199. package/types/commands/ag/deploy.d.ts +31 -0
  200. package/types/commands/ag/detail.d.ts +28 -0
  201. package/types/commands/ag/index.d.ts +6 -0
  202. package/types/commands/ag/list.d.ts +35 -0
  203. package/types/commands/ag/run.d.ts +52 -0
  204. package/types/commands/cloudrun/base.d.ts +10 -0
  205. package/types/commands/index.d.ts +1 -0
@@ -0,0 +1,644 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || function (mod) {
25
+ if (mod && mod.__esModule) return mod;
26
+ var result = {};
27
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
+ __setModuleDefault(result, mod);
29
+ return result;
30
+ };
31
+ var __metadata = (this && this.__metadata) || function (k, v) {
32
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33
+ };
34
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
35
+ return function (target, key) { decorator(target, key, paramIndex); }
36
+ };
37
+ var __importDefault = (this && this.__importDefault) || function (mod) {
38
+ return (mod && mod.__esModule) ? mod : { "default": mod };
39
+ };
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.AgentRunCommand = void 0;
42
+ const path_1 = __importDefault(require("path"));
43
+ const fs_extra_1 = __importDefault(require("fs-extra"));
44
+ const chalk_1 = __importDefault(require("chalk"));
45
+ const open_1 = __importDefault(require("open"));
46
+ const execa_1 = __importDefault(require("execa"));
47
+ const dotenv = __importStar(require("dotenv"));
48
+ const express_1 = __importDefault(require("express"));
49
+ const http_1 = require("http");
50
+ const common_1 = require("../common");
51
+ const decorators_1 = require("../../decorators");
52
+ const base_1 = require("./base");
53
+ const utils_1 = require("../utils");
54
+ const constants_1 = require("../constants");
55
+ const i18n_1 = require("../../i18n");
56
+ let AgentRunCommand = class AgentRunCommand extends common_1.Command {
57
+ get options() {
58
+ return {
59
+ cmd: 'ag',
60
+ childCmd: 'run <agentName>',
61
+ allowUnknownOption: true,
62
+ options: [
63
+ {
64
+ flags: '-e, --envId <envId>',
65
+ desc: (0, i18n_1.t)('环境 ID')
66
+ },
67
+ {
68
+ flags: '--extendedContext <extendedContext>',
69
+ desc: (0, i18n_1.t)('扩展上下文,示例:--extendedContext \'{"a":1,"b":2}\'')
70
+ },
71
+ {
72
+ flags: '--port <port>',
73
+ desc: (0, i18n_1.t)('监听的端口,默认为 3000'),
74
+ defaultValue: 3000
75
+ },
76
+ {
77
+ flags: '--dry-run',
78
+ desc: (0, i18n_1.t)('是否不启动服务,只验证代码可以正常加载,默认为 false')
79
+ },
80
+ {
81
+ flags: '--open-debug-panel',
82
+ desc: (0, i18n_1.t)('是否打开调试面板,默认为 true'),
83
+ defaultValue: 'false'
84
+ },
85
+ {
86
+ flags: '--entryPath <entryPath>',
87
+ desc: (0, i18n_1.t)('指定 Agent 服务启动的入口文件路径')
88
+ },
89
+ {
90
+ flags: '--web',
91
+ desc: (0, i18n_1.t)('同时启动前端项目(如果存在 client 目录)')
92
+ }
93
+ ],
94
+ requiredEnvId: false,
95
+ autoRunLogin: true,
96
+ desc: (0, i18n_1.t)('本地运行 Agent 进行调试')
97
+ };
98
+ }
99
+ async execute(ctx, envId, log, params, options) {
100
+ const agentName = params[0];
101
+ const { extendedContext, port = 9000, dryRun, openDebugPanel = 'false', entryPath, web: enableWeb = 'false' } = options;
102
+ const workDir = process.cwd();
103
+ const cloudbaseConfig = await (0, base_1.getCloudbaseConfig)(workDir);
104
+ if (!envId) {
105
+ if (cloudbaseConfig.envId) {
106
+ envId = cloudbaseConfig.envId;
107
+ }
108
+ else {
109
+ envId = await this.selectEnv();
110
+ }
111
+ }
112
+ log.info((0, i18n_1.t)(`当前环境:${envId}`));
113
+ let agentConfig;
114
+ try {
115
+ agentConfig = await (0, base_1.getAgentConfig)(agentName, workDir);
116
+ }
117
+ catch (error) {
118
+ throw new base_1.AgentError((0, i18n_1.t)(`未找到 Agent 配置,请先运行 tcb ag create ${agentName}`));
119
+ }
120
+ log.info((0, i18n_1.t)(`当前 Agent:${agentConfig.name}`));
121
+ const agentRoot = path_1.default.join(workDir, cloudbaseConfig.agentRoot);
122
+ const agentDir = path_1.default.join(agentRoot, agentName);
123
+ await this.setupEnvironment(envId, agentConfig, extendedContext, ctx, options);
124
+ console.log(chalk_1.default.green((0, i18n_1.t)('正在启动 Agent 本地调试服务...')));
125
+ await this.startNormal({
126
+ workDir: agentDir,
127
+ agentName,
128
+ port,
129
+ openDebugPanel: openDebugPanel !== 'false',
130
+ dryRun,
131
+ log,
132
+ entryPath,
133
+ enableWeb: enableWeb !== 'false'
134
+ });
135
+ }
136
+ async selectEnv() {
137
+ return (0, utils_1.selectEnv)({ source: [constants_1.EnvSource.MINIAPP, constants_1.EnvSource.QCLOUD] });
138
+ }
139
+ async setupEnvironment(envId, agentConfig, extendedContext, ctx, options) {
140
+ const credential = await (0, utils_1.getCredential)(ctx, options);
141
+ process.env.CLOUDBASE_ENV_ID = envId;
142
+ process.env.AGENT_NAME = agentConfig.name;
143
+ if (agentConfig.environment) {
144
+ Object.entries(agentConfig.environment).forEach(([key, value]) => {
145
+ process.env[key] = String(value);
146
+ });
147
+ }
148
+ const extendedContextObj = {
149
+ tmpSecret: {
150
+ secretId: credential.secretId,
151
+ secretKey: credential.secretKey,
152
+ token: credential.token
153
+ },
154
+ source: 'local_dev',
155
+ envId,
156
+ agentName: agentConfig.name,
157
+ accessToken: `Bearer ${await (0, utils_1.fetchAccessToken)({
158
+ envId,
159
+ secretId: credential.secretId,
160
+ secretKey: credential.secretKey,
161
+ token: credential.token
162
+ })}`
163
+ };
164
+ if (extendedContext) {
165
+ try {
166
+ const userContext = JSON.parse(extendedContext);
167
+ Object.assign(extendedContextObj, userContext);
168
+ }
169
+ catch (error) {
170
+ throw new base_1.AgentError((0, i18n_1.t)('扩展上下文格式错误,请提供有效的 JSON 字符串'));
171
+ }
172
+ }
173
+ process.env.EXTENDED_CONTEXT = JSON.stringify(extendedContextObj);
174
+ process.env.STATIC_SERVE_ROOT = __dirname;
175
+ process.env.ENABLE_CORS = 'true';
176
+ process.env.ALLOWED_ORIGINS = '*';
177
+ process.env.CLOUDBASE_RUNTIME = 'agent';
178
+ }
179
+ async startNormal(options) {
180
+ const { workDir, agentName, port, openDebugPanel, dryRun, log, entryPath, enableWeb } = options;
181
+ if (dryRun) {
182
+ log.info((0, i18n_1.t)('代码验证模式,不启动服务'));
183
+ return;
184
+ }
185
+ const agentServicePromise = this.startAgentService(workDir, agentName, port, log, entryPath);
186
+ if (openDebugPanel) {
187
+ this.startDebugPanelAfterAgentReady(agentName, port, log);
188
+ }
189
+ if (enableWeb) {
190
+ this.startWebProjectAfterAgentReady(workDir, port, log);
191
+ }
192
+ await agentServicePromise;
193
+ }
194
+ async startDebugPanelAfterAgentReady(agentName, agentPort, log) {
195
+ setTimeout(async () => {
196
+ try {
197
+ const agentUrl = `http://127.0.0.1:${agentPort}`;
198
+ await this.waitForService(agentUrl, 30000);
199
+ log.info((0, i18n_1.t)('Agent 服务已就绪,正在启动调试面板...'));
200
+ const debugPort = await this.startDebugPanelServer(agentName, agentPort, log);
201
+ await this.openDebugPanel(agentName, agentPort, debugPort, log);
202
+ }
203
+ catch (error) {
204
+ log.warn((0, i18n_1.t)('启动调试面板失败:{{error}}', { error: error.message }));
205
+ log.info((0, i18n_1.t)('Agent 服务仍在正常运行,可以手动访问:http://127.0.0.1:{{port}}', { port: agentPort }));
206
+ }
207
+ }, 1000);
208
+ }
209
+ async startWebProjectAfterAgentReady(workDir, agentPort, log) {
210
+ setTimeout(async () => {
211
+ try {
212
+ const clientDir = path_1.default.join(workDir, 'client');
213
+ if (!await fs_extra_1.default.pathExists(clientDir)) {
214
+ log.warn((0, i18n_1.t)('未找到前端项目目录 (client),跳过前端启动'));
215
+ return;
216
+ }
217
+ const agentUrl = `http://127.0.0.1:${agentPort}`;
218
+ await this.waitForService(agentUrl, 30000);
219
+ log.info((0, i18n_1.t)('Agent 服务已就绪,正在启动前端项目...'));
220
+ await this.startWebProject(clientDir, agentPort, log);
221
+ }
222
+ catch (error) {
223
+ log.warn((0, i18n_1.t)(`启动前端项目失败:${error.message}`));
224
+ log.info((0, i18n_1.t)(`Agent 服务仍在正常运行,可以手动访问:http://127.0.0.1:${agentPort}`));
225
+ }
226
+ }, 1000);
227
+ }
228
+ async startWebProject(clientDir, agentPort, log) {
229
+ const packageJsonPath = path_1.default.join(clientDir, 'package.json');
230
+ if (!await fs_extra_1.default.pathExists(packageJsonPath)) {
231
+ throw new Error((0, i18n_1.t)('前端项目缺少 package.json 文件'));
232
+ }
233
+ let packageJson;
234
+ try {
235
+ packageJson = await fs_extra_1.default.readJson(packageJsonPath);
236
+ }
237
+ catch (error) {
238
+ throw new Error((0, i18n_1.t)(`读取前端项目 package.json 失败:${error.message}`));
239
+ }
240
+ const scripts = packageJson.scripts || {};
241
+ let startScript = 'dev';
242
+ if (!scripts.dev && scripts.start) {
243
+ startScript = 'start';
244
+ }
245
+ else if (!scripts.dev && !scripts.start) {
246
+ throw new Error((0, i18n_1.t)('前端项目缺少 dev 或 start 脚本'));
247
+ }
248
+ log.info((0, i18n_1.t)('正在安装前端项目依赖...'));
249
+ const nodeModulesPath = path_1.default.join(clientDir, 'node_modules');
250
+ if (!await fs_extra_1.default.pathExists(nodeModulesPath)) {
251
+ try {
252
+ await (0, execa_1.default)('npm', ['install'], {
253
+ cwd: clientDir,
254
+ stdio: 'inherit'
255
+ });
256
+ log.info((0, i18n_1.t)('前端项目依赖安装完成'));
257
+ }
258
+ catch (error) {
259
+ throw new Error((0, i18n_1.t)(`安装前端项目依赖失败:${error.message}`));
260
+ }
261
+ }
262
+ log.info((0, i18n_1.t)('正在启动前端项目...'));
263
+ const env = {
264
+ ...process.env,
265
+ VITE_TS_AGENT_SERVER_URL: `http://127.0.0.1:${agentPort}`,
266
+ VITE_PYTHON_AGENT_SERVER_URL: `http://127.0.0.1:${agentPort}`,
267
+ };
268
+ const child = (0, execa_1.default)('npm', ['run', startScript], {
269
+ cwd: clientDir,
270
+ stdio: 'inherit',
271
+ env
272
+ });
273
+ child.on('exit', (code, signal) => {
274
+ if (code !== null) {
275
+ log.info((0, i18n_1.t)(`前端项目已退出,退出码:${code}`));
276
+ }
277
+ else if (signal) {
278
+ log.info((0, i18n_1.t)(`前端项目被信号终止:${signal}`));
279
+ }
280
+ });
281
+ child.on('error', (error) => {
282
+ log.error((0, i18n_1.t)(`前端项目启动失败:${error.message}`));
283
+ });
284
+ log.info((0, i18n_1.t)('前端项目已启动'));
285
+ log.info((0, i18n_1.t)('前端访问地址通常为:http://localhost:3000 或 http://localhost:5173'));
286
+ log.info((0, i18n_1.t)(`Agent API 地址:http://127.0.0.1:${agentPort}`));
287
+ }
288
+ async startDebugPanelServer(agentName, agentPort, log) {
289
+ const debugApp = (0, express_1.default)();
290
+ const debugPort = await this.findAvailablePort(agentPort + 1000);
291
+ debugApp.use((req, res, next) => {
292
+ res.header('Access-Control-Allow-Origin', '*');
293
+ res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
294
+ res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
295
+ if (req.method === 'OPTIONS') {
296
+ res.sendStatus(200);
297
+ }
298
+ else {
299
+ next();
300
+ }
301
+ });
302
+ const staticPath = path_1.default.join(__dirname, './debug');
303
+ debugApp.use(express_1.default.static(staticPath));
304
+ const server = (0, http_1.createServer)(debugApp);
305
+ return new Promise((resolve, reject) => {
306
+ server.listen(debugPort, '127.0.0.1', () => {
307
+ log.info((0, i18n_1.t)(`调试面板服务器已启动,端口:${debugPort}`));
308
+ resolve(debugPort);
309
+ });
310
+ server.on('error', (error) => {
311
+ reject(new base_1.AgentError((0, i18n_1.t)(`启动调试面板服务器失败:${error.message}`)));
312
+ });
313
+ });
314
+ }
315
+ async findAvailablePort(startPort) {
316
+ const net = await Promise.resolve().then(() => __importStar(require('net')));
317
+ return new Promise((resolve, reject) => {
318
+ const server = net.createServer();
319
+ server.listen(startPort, '127.0.0.1', () => {
320
+ var _a;
321
+ const port = (_a = server.address()) === null || _a === void 0 ? void 0 : _a.port;
322
+ server.close(() => resolve(port));
323
+ });
324
+ server.on('error', () => {
325
+ this.findAvailablePort(startPort + 1).then(resolve).catch(reject);
326
+ });
327
+ });
328
+ }
329
+ async openDebugPanel(agentName, agentPort, debugPort, log) {
330
+ const debugUrl = `http://127.0.0.1:${debugPort}/?agentName=${agentName}&agentPort=${agentPort}`;
331
+ log.info((0, i18n_1.t)(`调试面板地址:${debugUrl}`));
332
+ console.log(chalk_1.default.green((0, i18n_1.t)(`🚀 Agent 调试面板:${debugUrl}`)));
333
+ console.log(chalk_1.default.gray((0, i18n_1.t)(`Agent 服务地址:http://127.0.0.1:${agentPort}`)));
334
+ try {
335
+ await this.waitForService(debugUrl);
336
+ await (0, open_1.default)(debugUrl, { wait: false });
337
+ console.log(chalk_1.default.green((0, i18n_1.t)('已自动打开 Agent 调试面板')));
338
+ }
339
+ catch (error) {
340
+ log.warn((0, i18n_1.t)(`无法自动打开调试面板,请手动访问:${debugUrl}`));
341
+ }
342
+ }
343
+ async waitForService(url, timeout = 10000) {
344
+ const startTime = Date.now();
345
+ const { default: fetch } = await Promise.resolve().then(() => __importStar(require('node-fetch')));
346
+ while (Date.now() - startTime < timeout) {
347
+ try {
348
+ const response = await fetch(url, {
349
+ timeout: 2000,
350
+ method: 'GET'
351
+ });
352
+ if (response.status < 500) {
353
+ return;
354
+ }
355
+ }
356
+ catch (error) {
357
+ }
358
+ await new Promise(resolve => setTimeout(resolve, 1000));
359
+ }
360
+ throw new Error((0, i18n_1.t)('等待服务就绪超时'));
361
+ }
362
+ async startAgentService(workDir, agentName, port, log, customEntryPath) {
363
+ let entryPath;
364
+ if (customEntryPath) {
365
+ await this.validateCustomEntryPath(customEntryPath, workDir);
366
+ entryPath = customEntryPath;
367
+ log.info((0, i18n_1.t)(`使用自定义入口文件:${entryPath}`));
368
+ }
369
+ else {
370
+ entryPath = await this.getEntryPath(workDir);
371
+ log.info((0, i18n_1.t)(`使用默认入口文件:${entryPath}`));
372
+ }
373
+ process.env.PORT = String(port);
374
+ try {
375
+ const language = await this.detectLanguage(entryPath, workDir);
376
+ log.info((0, i18n_1.t)(`检测到项目语言:${language}`));
377
+ if (language === 'python') {
378
+ await this.startWithPython(entryPath, port, log, workDir);
379
+ }
380
+ else {
381
+ await this.startWithNode(entryPath, port, log, workDir);
382
+ }
383
+ }
384
+ catch (error) {
385
+ throw new base_1.AgentError((0, i18n_1.t)('启动 Agent 服务失败:{{error}}', { error: error.message }));
386
+ }
387
+ }
388
+ async detectLanguage(entryPath, workDir) {
389
+ const ext = path_1.default.extname(entryPath).toLowerCase();
390
+ if (['.py'].includes(ext)) {
391
+ return 'python';
392
+ }
393
+ if (['.js', '.ts', '.mjs', '.cjs'].includes(ext)) {
394
+ return 'node';
395
+ }
396
+ const packageJsonPath = path_1.default.join(workDir, 'package.json');
397
+ const requirementsPath = path_1.default.join(workDir, 'requirements.txt');
398
+ const setupPyPath = path_1.default.join(workDir, 'setup.py');
399
+ const pyprojectPath = path_1.default.join(workDir, 'pyproject.toml');
400
+ const hasPythonConfig = await Promise.all([
401
+ fs_extra_1.default.pathExists(requirementsPath),
402
+ fs_extra_1.default.pathExists(setupPyPath),
403
+ fs_extra_1.default.pathExists(pyprojectPath)
404
+ ]);
405
+ const hasNodeConfig = await fs_extra_1.default.pathExists(packageJsonPath);
406
+ if (hasPythonConfig.some(exists => exists)) {
407
+ return 'python';
408
+ }
409
+ if (hasNodeConfig) {
410
+ return 'node';
411
+ }
412
+ return 'node';
413
+ }
414
+ async validateCustomEntryPath(entryPath, workDir) {
415
+ try {
416
+ const fullPath = path_1.default.isAbsolute(entryPath) ? entryPath : path_1.default.resolve(workDir, entryPath);
417
+ if (!(await fs_extra_1.default.pathExists(fullPath))) {
418
+ throw new base_1.AgentError((0, i18n_1.t)(`指定的入口文件不存在:${entryPath}`));
419
+ }
420
+ const ext = path_1.default.extname(fullPath).toLowerCase();
421
+ if (!['.js', '.ts', '.mjs', '.cjs', '.py'].includes(ext)) {
422
+ throw new base_1.AgentError((0, i18n_1.t)(`入口文件必须是 JavaScript、TypeScript 或 Python 文件:${entryPath}`));
423
+ }
424
+ }
425
+ catch (error) {
426
+ if (error instanceof base_1.AgentError) {
427
+ throw error;
428
+ }
429
+ throw new base_1.AgentError((0, i18n_1.t)(`验证入口文件失败:${error.message}`));
430
+ }
431
+ }
432
+ async getPythonEntryPath(workDir) {
433
+ const commonEntryFiles = [
434
+ 'main.py',
435
+ 'app.py',
436
+ 'server.py',
437
+ 'run.py',
438
+ 'index.py',
439
+ 'src/main.py',
440
+ 'src/app.py'
441
+ ];
442
+ for (const entryFile of commonEntryFiles) {
443
+ const fullPath = path_1.default.join(workDir, entryFile);
444
+ if (await fs_extra_1.default.pathExists(fullPath)) {
445
+ return entryFile;
446
+ }
447
+ }
448
+ throw new base_1.AgentError((0, i18n_1.t)(`未找到 Python 入口文件,请确保存在以下文件之一:${commonEntryFiles.join(', ')}`));
449
+ }
450
+ async getEntryPath(workDir) {
451
+ const language = await this.detectLanguage('', workDir);
452
+ if (language === 'python') {
453
+ return await this.getPythonEntryPath(workDir);
454
+ }
455
+ try {
456
+ const packageJsonPath = path_1.default.join(workDir, 'package.json');
457
+ if (!(await fs_extra_1.default.pathExists(packageJsonPath))) {
458
+ throw new base_1.AgentError((0, i18n_1.t)('未找到 package.json 文件'));
459
+ }
460
+ const packageJson = await fs_extra_1.default.readJSON(packageJsonPath);
461
+ if (!packageJson.main) {
462
+ throw new base_1.AgentError((0, i18n_1.t)('package.json 中未配置 main 字段'));
463
+ }
464
+ const mainFile = path_1.default.resolve(workDir, packageJson.main);
465
+ if (!(await fs_extra_1.default.pathExists(mainFile))) {
466
+ throw new base_1.AgentError((0, i18n_1.t)(`main 字段指向的文件不存在:${packageJson.main}`));
467
+ }
468
+ return packageJson.main;
469
+ }
470
+ catch (error) {
471
+ if (error instanceof base_1.AgentError) {
472
+ throw error;
473
+ }
474
+ throw new base_1.AgentError((0, i18n_1.t)(`读取 package.json 失败:${error.message}`));
475
+ }
476
+ }
477
+ async startWithPython(entryPath, port, log, agentDir) {
478
+ log.info((0, i18n_1.t)('使用 Python 启动服务...'));
479
+ console.log('entryPath', entryPath);
480
+ console.log('agentDir', agentDir);
481
+ await this.checkPythonAvailable();
482
+ const envVars = await this.loadEnvFile(agentDir, log);
483
+ console.log('process.env', envVars);
484
+ log.info((0, i18n_1.t)('Agent 服务启动中...'));
485
+ let pythonCommand = 'python3';
486
+ try {
487
+ await (0, execa_1.default)('which', ['python3'], { stdio: 'pipe' });
488
+ }
489
+ catch {
490
+ try {
491
+ await (0, execa_1.default)('which', ['python'], { stdio: 'pipe' });
492
+ pythonCommand = 'python';
493
+ }
494
+ catch {
495
+ throw new base_1.AgentError((0, i18n_1.t)('未找到 Python 解释器,请确保已安装 Python'));
496
+ }
497
+ }
498
+ const child = (0, execa_1.default)(pythonCommand, [entryPath], {
499
+ cwd: agentDir,
500
+ stdio: 'inherit',
501
+ env: {
502
+ ...process.env,
503
+ ...envVars,
504
+ PORT: String(port),
505
+ PYTHONPATH: agentDir,
506
+ PYTHONUNBUFFERED: '1'
507
+ }
508
+ });
509
+ let isExiting = false;
510
+ const handleExit = () => {
511
+ if (isExiting)
512
+ return;
513
+ isExiting = true;
514
+ log.info((0, i18n_1.t)('正在关闭 Agent 服务...'));
515
+ child.kill('SIGTERM');
516
+ };
517
+ process.on('SIGINT', handleExit);
518
+ process.on('SIGTERM', handleExit);
519
+ child.on('exit', (code, signal) => {
520
+ if (code !== null) {
521
+ log.info((0, i18n_1.t)(`Agent 服务已退出,退出码:${code}`));
522
+ }
523
+ else if (signal) {
524
+ log.info((0, i18n_1.t)(`Agent 服务被信号终止:${signal}`));
525
+ }
526
+ process.removeListener('SIGINT', handleExit);
527
+ process.removeListener('SIGTERM', handleExit);
528
+ if (isExiting) {
529
+ process.exit(0);
530
+ }
531
+ });
532
+ try {
533
+ await child;
534
+ }
535
+ catch (error) {
536
+ log.error((0, i18n_1.t)(`Agent 服务启动失败:${error.message}`));
537
+ process.exit(1);
538
+ }
539
+ }
540
+ async checkPythonAvailable() {
541
+ try {
542
+ const result = await (0, execa_1.default)('python3', ['--version'], { stdio: 'pipe' });
543
+ console.log(`Python version: ${result.stdout}`);
544
+ return;
545
+ }
546
+ catch {
547
+ try {
548
+ const result = await (0, execa_1.default)('python', ['--version'], { stdio: 'pipe' });
549
+ console.log(`Python version: ${result.stdout}`);
550
+ return;
551
+ }
552
+ catch {
553
+ throw new base_1.AgentError((0, i18n_1.t)('未找到 Python 解释器,请确保已安装 Python 3.7+'));
554
+ }
555
+ }
556
+ }
557
+ async startWithNode(entryPath, port, log, agentDir) {
558
+ log.info((0, i18n_1.t)('使用 Node.js 启动服务...'));
559
+ console.log('entryPath', entryPath);
560
+ console.log('agentDir', agentDir);
561
+ const envVars = await this.loadEnvFile(agentDir, log);
562
+ console.log('process.env', envVars);
563
+ log.info((0, i18n_1.t)('Agent 服务启动中...'));
564
+ const child = (0, execa_1.default)('node', [entryPath], {
565
+ cwd: agentDir,
566
+ stdio: 'inherit',
567
+ env: {
568
+ ...process.env,
569
+ ...envVars,
570
+ PORT: String(port)
571
+ }
572
+ });
573
+ let isExiting = false;
574
+ const handleExit = () => {
575
+ if (isExiting)
576
+ return;
577
+ isExiting = true;
578
+ log.info((0, i18n_1.t)('正在关闭 Agent 服务...'));
579
+ child.kill('SIGTERM');
580
+ };
581
+ process.on('SIGINT', handleExit);
582
+ process.on('SIGTERM', handleExit);
583
+ child.on('exit', (code, signal) => {
584
+ if (code !== null) {
585
+ log.info((0, i18n_1.t)(`Agent 服务已退出,退出码:${code}`));
586
+ }
587
+ else if (signal) {
588
+ log.info((0, i18n_1.t)(`Agent 服务被信号终止:${signal}`));
589
+ }
590
+ process.removeListener('SIGINT', handleExit);
591
+ process.removeListener('SIGTERM', handleExit);
592
+ if (isExiting) {
593
+ process.exit(0);
594
+ }
595
+ });
596
+ try {
597
+ await child;
598
+ }
599
+ catch (error) {
600
+ log.error((0, i18n_1.t)(`Agent 服务启动失败:${error.message}`));
601
+ process.exit(1);
602
+ }
603
+ }
604
+ async loadEnvFile(agentDir, log) {
605
+ const envFiles = ['.env', '.env.local', '.env.development'];
606
+ const envVars = {};
607
+ for (const envFileName of envFiles) {
608
+ const envFilePath = path_1.default.join(agentDir, envFileName);
609
+ if (await fs_extra_1.default.pathExists(envFilePath)) {
610
+ try {
611
+ const result = dotenv.config({ path: envFilePath });
612
+ if (result.error) {
613
+ log.warn((0, i18n_1.t)(`解析环境变量文件失败:${envFileName} - ${result.error.message}`));
614
+ continue;
615
+ }
616
+ if (result.parsed) {
617
+ Object.assign(envVars, result.parsed);
618
+ log.info((0, i18n_1.t)(`加载环境变量文件:${envFileName}`));
619
+ console.log((0, i18n_1.t)(`加载了 ${Object.keys(result.parsed).length} 个环境变量从 ${envFileName}`));
620
+ }
621
+ }
622
+ catch (error) {
623
+ log.warn((0, i18n_1.t)(`读取环境变量文件失败:${envFileName} - ${error.message}`));
624
+ }
625
+ }
626
+ }
627
+ return envVars;
628
+ }
629
+ };
630
+ __decorate([
631
+ (0, decorators_1.InjectParams)(),
632
+ __param(0, (0, decorators_1.CmdContext)()),
633
+ __param(1, (0, decorators_1.EnvId)()),
634
+ __param(2, (0, decorators_1.Log)()),
635
+ __param(3, (0, decorators_1.ArgsParams)()),
636
+ __param(4, (0, decorators_1.ArgsOptions)()),
637
+ __metadata("design:type", Function),
638
+ __metadata("design:paramtypes", [Object, String, decorators_1.Logger, Array, Object]),
639
+ __metadata("design:returntype", Promise)
640
+ ], AgentRunCommand.prototype, "execute", null);
641
+ AgentRunCommand = __decorate([
642
+ (0, common_1.ICommand)()
643
+ ], AgentRunCommand);
644
+ exports.AgentRunCommand = AgentRunCommand;