@cloudbase/cloudbase-mcp 2.34.5 → 2.34.7

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/dist/index.js CHANGED
@@ -16,6 +16,7 @@ import * as __WEBPACK_EXTERNAL_MODULE_lockfile__ from "lockfile";
16
16
  import * as __WEBPACK_EXTERNAL_MODULE_net__ from "net";
17
17
  import * as __WEBPACK_EXTERNAL_MODULE_node_crypto_803ecaf5__ from "node:crypto";
18
18
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs_75ed2103__ from "node:fs";
19
+ import * as __WEBPACK_EXTERNAL_MODULE_node_os_e12349cb__ from "node:os";
19
20
  import * as __WEBPACK_EXTERNAL_MODULE_node_path_02319fef__ from "node:path";
20
21
  import * as __WEBPACK_EXTERNAL_MODULE_os__ from "os";
21
22
  import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
@@ -51,6 +52,7 @@ exports.getLoginState = getLoginState;
51
52
  exports.logout = logout;
52
53
  const toolbox_1 = __webpack_require__(2090);
53
54
  const logger_js_1 = __webpack_require__(781);
55
+ const project_config_js_1 = __webpack_require__(9175);
54
56
  const site_map_js_1 = __webpack_require__(4533);
55
57
  const auth = toolbox_1.AuthSupervisor.getInstance({});
56
58
  const authProgressState = {
@@ -455,8 +457,7 @@ async function peekLoginState(options) {
455
457
  if ('_type' in envVarLoginState && envVarLoginState._type === 'api_key') {
456
458
  (0, logger_js_1.debug)("peekLoginState: detected CLOUDBASE_API_KEY env var");
457
459
  try {
458
- // 优先使用 IDE 注入的工作目录,其次 process.cwd()
459
- const projectCwd = process.env.WORKSPACE_FOLDER_PATHS || process.cwd();
460
+ const projectCwd = (0, project_config_js_1.requireProjectRoot)();
460
461
  // 换取网关按站点选型:显式 intl → ap-singapore;domestic/歧义 → toolbox 默认
461
462
  // ap-shanghai(国内站多地域环境均经其全局路由,详见 resolveApiKeyExchangeRegion)
462
463
  const exchangeRegion = (0, site_map_js_1.resolveApiKeyExchangeRegion)({
@@ -613,7 +614,7 @@ async function logout(options) {
613
614
  await toolbox_1.authStore.set("credential", slotted);
614
615
  }
615
616
  else if (site === LEGACY_SITE) {
616
- const cwd = process.env.WORKSPACE_FOLDER_PATHS || process.cwd();
617
+ const cwd = (0, project_config_js_1.requireProjectRoot)();
617
618
  await auth.logout({ cwd });
618
619
  }
619
620
  resetAuthProgressState();
@@ -1007,6 +1008,14 @@ class EnvironmentManager {
1007
1008
  this._setCachedEnvId(loginState.envId);
1008
1009
  return loginState.envId;
1009
1010
  }
1011
+ // 3.1 未登录必须交回 AUTH_REQUIRED,不能继续往下走「选环境」。
1012
+ // 未登录时拿不到任何环境候选,落到 throwEnvRequiredError 会输出
1013
+ // 「当前已登录,但还没有可用环境」——把「没登录」误诊成「登录了但缺环境」。
1014
+ // 调用方读到这句会去 set_env 选环境,而候选列表永远为空,只能原样重试。
1015
+ // 与 getCloudBaseManager 的登录态分流保持同构。
1016
+ if (!loginState) {
1017
+ throwAuthRequiredError();
1018
+ }
1010
1019
  // 4. 单环境自动绑定;多环境时返回结构化引导,不再触发交互弹窗
1011
1020
  const envCandidates = await listAvailableEnvCandidates({ loginState });
1012
1021
  if (envCandidates.length === 1) {
@@ -2269,6 +2278,7 @@ const msgPush_js_1 = __webpack_require__(6191);
2269
2278
  const setup_js_1 = __webpack_require__(8707);
2270
2279
  const envSetup_js_1 = __webpack_require__(7148);
2271
2280
  const interactive_js_1 = __webpack_require__(1838);
2281
+ const feedback_js_1 = __webpack_require__(9391);
2272
2282
  exports.en = {
2273
2283
  env: env_js_1.env.en,
2274
2284
  storage: storage_js_1.storage.en,
@@ -2298,6 +2308,7 @@ exports.en = {
2298
2308
  setup: setup_js_1.setup.en,
2299
2309
  envSetup: envSetup_js_1.envSetup.en,
2300
2310
  interactive: interactive_js_1.interactive.en,
2311
+ feedback: feedback_js_1.feedback.en,
2301
2312
  };
2302
2313
 
2303
2314
 
@@ -2651,7 +2662,7 @@ exports.capi = (0, types_js_1.defineModule)({
2651
2662
  docGuidanceCloudbase: "优先查阅 CloudBase API 概览 {controlPlaneUrl} 与云开发依赖资源接口指引 {dependencyUrl}。",
2652
2663
  docGuidanceMonitor: "请优先核对云监控(腾讯云可观测平台)官方 API 文档:API 概览 https://cloud.tencent.com/document/product/649/30343 ,单 Action 详细文档在 https://cloud.tencent.com/document/api/248/ 产品线下。",
2653
2664
  docGuidanceGeneric: "请优先核对对应官方云 API 文档;若你的场景其实是通过 HTTP 协议直接集成 auth/functions/cloudrun/storage/mysqldb 等 CloudBase 业务 API,请优先使用 OpenAPI / Swagger 或 searchKnowledgeBase(mode=\"openapi\"),不要继续猜测管控面 Action。",
2654
- camAuthGuidance: "这通常是 CAM 权限不足(常见于 API Key 登录仅授权数据面:DB/函数/存储)。请任选其一:1) 改用 device code 登录管控面:auth(action=\"start_auth\", authMode=\"device\");2) 或使用腾讯云 SecretId/SecretKey(确认子账号已授 CAM 策略,如 QcloudTCBFullAccess、QcloudVPCReadOnlyAccess);3) 确认目标资源属于当前登录账号。",
2665
+ camAuthGuidance: "这是 CAM 权限不足。先分清是谁缺权限,再决定怎么补:用 auth(action=\"status\") 看 credential_scope,用 callCloudApi(service=\"sts\", action=\"GetCallerIdentity\") 看实际调用者(Type=CAMRole 表示角色扮演身份,UserId 里带角色名)。若缺权限的是角色(如 TCB_QcsRole),补的是挂在**角色**上的策略 —— 给用户一条 cam/role/grant 一键授权链接,拼法与 principal 取值见 skill cloud-api-operations 的 §3.2;若是账号级身份本人,则由主账号给这个身份追加策略(用腾讯云 SecretId/SecretKey 登录时,调用者就是该身份)。环境级 API Key 只能访问绑定环境的数据面,跨产品调用需改用账号级凭据:auth(action=\"start_auth\", authMode=\"device\")。另请确认目标资源确实属于当前账号。",
2655
2666
  errorInvalidAction: "Action `{action}` 可能不存在或不对外开放。请不要继续猜测 Action 名称,先确认 service=`{service}` 下该 Action 在当前 API 版本是否真实存在。",
2656
2667
  errorSuggestedActions: "可能的 tcb Action:{candidates}。",
2657
2668
  errorRegionParam: "Region 不是 Action body 参数。请使用 callCloudApi 顶层参数 region(例如 region=\"ap-singapore\"),对应 X-TC-Region。",
@@ -2685,7 +2696,7 @@ exports.capi = (0, types_js_1.defineModule)({
2685
2696
  docGuidanceCloudbase: "Prefer the CloudBase API overview {controlPlaneUrl} and the dependent-resource API guide {dependencyUrl}.",
2686
2697
  docGuidanceMonitor: "Check the official Cloud Monitor (Tencent Cloud Observability Platform) API docs first: API overview https://cloud.tencent.com/document/product/649/30343 , per-Action docs live under https://cloud.tencent.com/document/api/248/ .",
2687
2698
  docGuidanceGeneric: "Check the corresponding official cloud API docs first; if your scenario is actually integrating CloudBase business APIs such as auth/functions/cloudrun/storage/mysqldb over HTTP, prefer OpenAPI / Swagger or searchKnowledgeBase(mode=\"openapi\") instead of guessing control-plane Actions.",
2688
- camAuthGuidance: "This is usually insufficient CAM permission (common with API Key logins that only grant the data plane: DB/functions/storage). Pick one: 1) switch to device code login for the control plane: auth(action=\"start_auth\", authMode=\"device\"); 2) or use Tencent Cloud SecretId/SecretKey (ensure the sub-account has CAM policies such as QcloudTCBFullAccess, QcloudVPCReadOnlyAccess); 3) confirm the target resource belongs to the logged-in account.",
2699
+ camAuthGuidance: "This is a CAM permission gap. Work out who is missing it before choosing a fix: auth(action=\"status\") shows credential_scope, and callCloudApi(service=\"sts\", action=\"GetCallerIdentity\") shows the actual caller (Type=CAMRole means an assumed role; the UserId carries the role name). When the role is the one missing permission (e.g. TCB_QcsRole), the fix is a policy attached to that role — give the user a cam/role/grant authorization link, built as described in the cloud-api-operations skill, section 3.2. When an account-level identity is the caller, the main account attaches the policy to it (signing in with a Tencent Cloud SecretId/SecretKey makes the caller that identity). An environment-level API Key can only reach the bound environment's data plane; for cross-product calls switch to account-level credentials: auth(action=\"start_auth\", authMode=\"device\"). Also confirm the target resource belongs to the current account.",
2689
2700
  errorInvalidAction: "Action `{action}` may not exist or is not publicly available. Do not keep guessing Action names; first confirm the Action actually exists under service=`{service}` in the current API version.",
2690
2701
  errorSuggestedActions: "Possible tcb Actions: {candidates}.",
2691
2702
  errorRegionParam: "Region is not an Action body parameter. Use the callCloudApi top-level region parameter (e.g. region=\"ap-singapore\"), which maps to X-TC-Region.",
@@ -2729,7 +2740,7 @@ exports.cloudrun = (0, types_js_1.defineModule)({
2729
2740
  "manage.description": "管理云托管服务,按开发顺序支持:开通云托管环境(initEnv)、初始化项目(可从模板开始,模板列表可通过 queryCloudRun 查询)、下载服务代码、本地运行(仅函数型服务)、部署代码、仅更新配置(updateConfig,无需重新上传代码)、删除服务。deploy 支持两种方式:1) 源码构建(传入 targetPath,本地代码打包上传,默认路径);2) 已有镜像部署(传入 imageUrl,如 ccr.ccs.tencentyun.com/ns/img:v1,走 DeployType=image 容器型部署,targetPath 可省略)。deploy 语义为「触发部署 + 轻量等待任务注册」(最多约 45s;不需要 buildId 时可传 waitRegistration=false 跳过等待)。源码构建返回 buildId,用 getDeployLog 轮询构建进度后再 getProcessLog;镜像部署(imageUrl)BuildId 常为 0,跳过 getDeployLog,返回 runId/next_step 引导 getProcessLog(或先 getDeployRecords 取 RunId)。若用户明确指定镜像或无需重新构建,必须传 imageUrl,不要仅因本地有源码目录就回退到源码构建。deploy 对已存在服务会先读取远程配置再合并(保留 VpcConf/EnvParams/OpenAccessTypes)。updateConfig 对齐控制台服务设置页。删除操作需要确认,建议设置force=true。新环境首次部署前若提示未开通云托管,先调用 initEnv 开通(异步、幂等)。",
2730
2741
  "error.managerInitFailed": "CloudBase Manager 初始化失败,请检查凭据与环境配置。",
2731
2742
  "error.unsupportedAction": "不支持的操作:{action}",
2732
- "error.pathOutsideCwd": "路径必须在当前工作目录内:{cwd}",
2743
+ "error.pathOutsideCwd": "路径必须在当前工作目录内:{cwd}。允许:`{cwd}` 下的路径,或传入项目目录的绝对路径(相对路径不能通过 `../` 逃逸 CWD)。收到的解析路径:{resolvedPath}。建议:将 targetPath 设为项目绝对路径(deploy/download/init)。",
2733
2744
  "error.commonServiceQueryEnv": "当前 CloudBase Manager 不支持 commonService,无法查询云托管环境开通状态。",
2734
2745
  "error.commonServiceInitEnv": "当前 CloudBase Manager 不支持 commonService,无法初始化云托管环境。",
2735
2746
  "error.commonServiceSubmitDiff": "当前 CloudBase Manager 不支持 commonService,无法调用 SubmitServerConfigChangeDiff。",
@@ -2919,7 +2930,7 @@ exports.cloudrun = (0, types_js_1.defineModule)({
2919
2930
  "manage.description": "Manage CloudRun services, in development order: provision the CloudRun env (initEnv), initialize a project (optionally from a template; list templates via queryCloudRun), download service code, run locally (function services only), deploy code, update config only (updateConfig, no code upload needed), and delete the service. deploy supports two modes: 1) source build (pass targetPath; local code is packaged and uploaded, the default); 2) existing image deploy (pass imageUrl, e.g. ccr.ccs.tencentyun.com/ns/img:v1; DeployType=image container deploy, targetPath optional). deploy means \"trigger deploy + lightweight wait for task registration\" (up to ~45s; pass waitRegistration=false to skip the wait when you don't need the buildId). Source builds return buildId — poll getDeployLog for build progress, then getProcessLog; image deploys (imageUrl) usually have BuildId=0 — getDeployLog is skipped, and runId/next_step guide you to getProcessLog (or getDeployRecords first for RunId). If the user explicitly specifies an image or no rebuild is needed, you must pass imageUrl instead of falling back to a source build just because a local source directory exists. For existing services, deploy reads the remote config first and merges (preserving VpcConf/EnvParams/OpenAccessTypes). updateConfig aligns with the console service settings page. Deletion requires confirmation; set force=true. If a new env reports CloudRun not provisioned before the first deploy, call initEnv first (async, idempotent).",
2920
2931
  "error.managerInitFailed": "Failed to initialize CloudBase manager. Please check your credentials and environment configuration.",
2921
2932
  "error.unsupportedAction": "Unsupported action: {action}",
2922
- "error.pathOutsideCwd": "Path must be within current working directory: {cwd}",
2933
+ "error.pathOutsideCwd": "Path must be within current working directory: {cwd}. Allowed: paths under `{cwd}`, or pass an absolute path to the project directory (relative paths cannot escape CWD via `../`). Received resolved path: {resolvedPath}. Suggestion: set targetPath to the absolute project path (deploy/download/init).",
2923
2934
  "error.commonServiceQueryEnv": "Current CloudBase Manager does not support commonService; cannot query CloudRun env status.",
2924
2935
  "error.commonServiceInitEnv": "Current CloudBase Manager does not support commonService; cannot initialize CloudRun env.",
2925
2936
  "error.commonServiceSubmitDiff": "Current CloudBase Manager does not support commonService; cannot call SubmitServerConfigChangeDiff.",
@@ -3858,11 +3869,28 @@ exports.databaseSQL = (0, types_js_1.defineModule)({
3858
3869
  "gate.pgOnlyMode": "当前环境({envId})已开通 PostgreSQL,MySQL 不可用。请改用 managePgDatabase / queryPgDatabase,而不是 manageMysqlDatabase / queryMysqlDatabase。",
3859
3870
  "gate.useManagePg": "请使用 managePgDatabase 执行 PostgreSQL 操作",
3860
3871
  "queryMysqlDatabase.title": "查询 CloudBase MySQL 数据库状态或执行只读 SQL",
3861
- "queryMysqlDatabase.description": "查询 CloudBase MySQL 数据库信息。支持执行只读 SQL、查询 MySQL 开通结果、查询 MySQL 任务状态,以及获取当前实例生命周期上下文。标准 getInstanceInfo/describeInstance 不返回连接凭据;仅 getConnectionInfo 透传原始连接/集群载荷(含可能的凭据),且仅用于显式 TCP 迁移。业务 CRUD 优先使用 SDK 或 runQuery/runStatement。",
3862
- "schema.query.action": "runQuery=执行只读 SQL;describeCreateResult=查询 CreateMySQL 结果;describeTaskStatus=查询 MySQL 任务状态;getInstanceInfo=获取不含连接凭据的生命周期上下文;describeInstance=getInstanceInfo 的别名;getConnectionInfo=透传可能包含凭据的原始连接/集群载荷(仅限 TCP 迁移例外场景)",
3872
+ "queryMysqlDatabase.description": "查询 CloudBase MySQL 数据库信息。支持执行只读 SQL、查询 MySQL 开通结果、查询 MySQL 任务状态、获取当前实例生命周期上下文,以及查询实例慢查询/错误日志(对齐 Manager SDK describeInstanceSlowQueries / describeInstanceErrorLogs)。标准 getInstanceInfo/describeInstance 不返回连接凭据;仅 getConnectionInfo 透传原始连接/集群载荷(含可能的凭据),且仅用于显式 TCP 迁移。业务 CRUD 优先使用 SDK 或 runQuery/runStatement。",
3873
+ "schema.query.action": "runQuery=执行只读 SQL;describeCreateResult=查询 CreateMySQL 结果;describeTaskStatus=查询 MySQL 任务状态;getInstanceInfo=获取不含连接凭据的生命周期上下文;describeInstance=getInstanceInfo 的别名;getConnectionInfo=透传可能包含凭据的原始连接/集群载荷(仅限 TCP 迁移例外场景);describeInstanceSlowQueries=查询实例慢查询日志;describeInstanceErrorLogs=查询实例错误日志",
3863
3874
  "schema.query.sql": "action=runQuery 使用的只读 SQL",
3864
- "schema.query.request": "describeCreateResult/describeTaskStatus 使用的官方请求载荷",
3865
- "schema.query.dbInstance": "runQuery 可选的 SQL 数据库实例上下文",
3875
+ "schema.query.request": "describeCreateResult/describeTaskStatus/describeInstanceSlowQueries/describeInstanceErrorLogs 使用的官方请求载荷(可含 InstanceId 等)",
3876
+ "schema.query.dbInstance": "runQuery / 慢查/错误日志可选的 SQL 数据库实例上下文",
3877
+ "schema.query.startTime": "慢查/错误日志查询开始时间(YYYY-MM-DD HH:mm:ss)",
3878
+ "schema.query.endTime": "慢查/错误日志查询结束时间(YYYY-MM-DD HH:mm:ss)",
3879
+ "schema.query.limit": "慢查/错误日志返回条数限制",
3880
+ "schema.query.offset": "慢查/错误日志分页偏移",
3881
+ "schema.query.username": "慢查过滤:用户名",
3882
+ "schema.query.host": "慢查过滤:客户端 host",
3883
+ "schema.query.database": "慢查过滤:数据库名",
3884
+ "schema.query.orderBy": "排序字段。慢查支持 QueryTime/LockTime/RowsExamined/RowsSent;错误日志支持 Timestamp",
3885
+ "schema.query.orderByType": "排序方向:asc/desc(大小写均可)",
3886
+ "schema.query.sqlText": "慢查过滤:SQL 文本片段",
3887
+ "schema.query.logLevels": "错误日志等级过滤,可选值:error / warning / note",
3888
+ "schema.query.keyWords": "错误日志关键字模糊搜索列表",
3889
+ "instanceLogs.notProvisioned": "MySQL 尚未开通,无法查询实例慢查/错误日志。",
3890
+ "instanceLogs.instanceIdRequired": "无法解析 CynosDB InstanceId。请先 getInstanceInfo,或通过 dbInstance.instanceId / request.InstanceId 传入。",
3891
+ "instanceLogs.resolveInstanceId": "先查询实例信息以获取可用的 InstanceId。",
3892
+ "instanceLogs.slowQueriesSuccess": "MySQL 实例慢查询日志检索成功。",
3893
+ "instanceLogs.errorLogsSuccess": "MySQL 实例错误日志检索成功。",
3866
3894
  "manageMysqlDatabase.title": "管理 CloudBase MySQL 数据库生命周期或执行写入 SQL",
3867
3895
  "manageMysqlDatabase.description": "管理 CloudBase MySQL 数据库资源。支持开通 MySQL、销毁 MySQL、执行写入 SQL/DDL,以及初始化数据库 Schema。注意:必须先开通 MySQL(action=provisionMySQL,confirm=true)才能执行 runStatement 或 initializeSchema。若 MySQL 尚未开通,工具会返回 MYSQL_NOT_CREATED 并给出开通的 nextAction 提示。",
3868
3896
  "schema.manage.action": "provisionMySQL=创建 MySQL 实例;destroyMySQL=销毁 MySQL 实例;runStatement=执行写入 SQL 或 DDL;initializeSchema=按顺序执行 Schema 初始化语句",
@@ -3933,11 +3961,28 @@ exports.databaseSQL = (0, types_js_1.defineModule)({
3933
3961
  "gate.pgOnlyMode": "This environment ({envId}) has PostgreSQL enabled but MySQL is NOT available. Use managePgDatabase / queryPgDatabase instead of manageMysqlDatabase / queryMysqlDatabase.",
3934
3962
  "gate.useManagePg": "Use managePgDatabase for PostgreSQL operations",
3935
3963
  "queryMysqlDatabase.title": "Query CloudBase MySQL database status or run read-only SQL",
3936
- "queryMysqlDatabase.description": "Query CloudBase MySQL database information. Supports running read-only SQL, checking the MySQL provisioning result, querying MySQL task status, and getting the current instance lifecycle context. Standard getInstanceInfo/describeInstance never returns connection credentials; only getConnectionInfo passes through the raw connection/cluster payload (possibly including credentials), and only for explicit TCP migration. Prefer the SDK or runQuery/runStatement for business CRUD.",
3937
- "schema.query.action": "runQuery=execute read-only SQL; describeCreateResult=query CreateMySQL result; describeTaskStatus=query MySQL task status; getInstanceInfo=get lifecycle context without connection credentials; describeInstance=alias of getInstanceInfo; getConnectionInfo=passthrough raw connection/cluster payload including possible credentials (TCP migration exception only)",
3964
+ "queryMysqlDatabase.description": "Query CloudBase MySQL database information. Supports running read-only SQL, checking the MySQL provisioning result, querying MySQL task status, getting the current instance lifecycle context, and querying instance slow queries / error logs (aligned with Manager SDK describeInstanceSlowQueries / describeInstanceErrorLogs). Standard getInstanceInfo/describeInstance never returns connection credentials; only getConnectionInfo passes through the raw connection/cluster payload (possibly including credentials), and only for explicit TCP migration. Prefer the SDK or runQuery/runStatement for business CRUD.",
3965
+ "schema.query.action": "runQuery=execute read-only SQL; describeCreateResult=query CreateMySQL result; describeTaskStatus=query MySQL task status; getInstanceInfo=get lifecycle context without connection credentials; describeInstance=alias of getInstanceInfo; getConnectionInfo=passthrough raw connection/cluster payload including possible credentials (TCP migration exception only); describeInstanceSlowQueries=query instance slow query logs; describeInstanceErrorLogs=query instance error logs",
3938
3966
  "schema.query.sql": "Read-only SQL used by action=runQuery",
3939
- "schema.query.request": "Official request payload used by describeCreateResult/describeTaskStatus",
3940
- "schema.query.dbInstance": "Optional SQL database instance context for runQuery",
3967
+ "schema.query.request": "Official request payload used by describeCreateResult/describeTaskStatus/describeInstanceSlowQueries/describeInstanceErrorLogs (may include InstanceId, etc.)",
3968
+ "schema.query.dbInstance": "Optional SQL database instance context for runQuery / slow-query / error-log actions",
3969
+ "schema.query.startTime": "Slow-query / error-log query start time (YYYY-MM-DD HH:mm:ss)",
3970
+ "schema.query.endTime": "Slow-query / error-log query end time (YYYY-MM-DD HH:mm:ss)",
3971
+ "schema.query.limit": "Max rows for slow-query / error-log results",
3972
+ "schema.query.offset": "Pagination offset for slow-query / error-log results",
3973
+ "schema.query.username": "Slow-query filter: username",
3974
+ "schema.query.host": "Slow-query filter: client host",
3975
+ "schema.query.database": "Slow-query filter: database name",
3976
+ "schema.query.orderBy": "Sort field. Slow queries: QueryTime/LockTime/RowsExamined/RowsSent; error logs: Timestamp",
3977
+ "schema.query.orderByType": "Sort direction: asc/desc (case-insensitive)",
3978
+ "schema.query.sqlText": "Slow-query filter: SQL text fragment",
3979
+ "schema.query.logLevels": "Error log level filter. Allowed values: error / warning / note",
3980
+ "schema.query.keyWords": "Error log keyword fuzzy-search list",
3981
+ "instanceLogs.notProvisioned": "MySQL is not provisioned yet, so instance slow/error logs cannot be queried.",
3982
+ "instanceLogs.instanceIdRequired": "Unable to resolve CynosDB InstanceId. Call getInstanceInfo first, or pass dbInstance.instanceId / request.InstanceId.",
3983
+ "instanceLogs.resolveInstanceId": "Query instance info first to obtain a usable InstanceId.",
3984
+ "instanceLogs.slowQueriesSuccess": "MySQL instance slow query logs retrieved successfully.",
3985
+ "instanceLogs.errorLogsSuccess": "MySQL instance error logs retrieved successfully.",
3941
3986
  "manageMysqlDatabase.title": "Manage CloudBase MySQL database lifecycle or run write SQL",
3942
3987
  "manageMysqlDatabase.description": "Manage CloudBase MySQL database resources. Supports provisioning MySQL, destroying MySQL, running write SQL/DDL, and initializing the database schema. Note: MySQL must be provisioned first (action=provisionMySQL, confirm=true) before runStatement or initializeSchema can run. If MySQL is not provisioned, the tool returns MYSQL_NOT_CREATED with a provisioning nextAction hint.",
3943
3988
  "schema.manage.action": "provisionMySQL=create MySQL instance; destroyMySQL=destroy MySQL instance; runStatement=execute write SQL or DDL; initializeSchema=run ordered schema initialization statements",
@@ -4747,6 +4792,49 @@ exports.envSetup = (0, types_js_1.defineModule)({
4747
4792
  });
4748
4793
 
4749
4794
 
4795
+ /***/ },
4796
+
4797
+ /***/ 9391
4798
+ (__unused_webpack_module, exports, __webpack_require__) {
4799
+
4800
+ var __webpack_unused_export__;
4801
+
4802
+ __webpack_unused_export__ = ({ value: true });
4803
+ exports.feedback = void 0;
4804
+ const types_js_1 = __webpack_require__(9921);
4805
+ exports.feedback = (0, types_js_1.defineModule)({
4806
+ title: "整理本次开发反馈",
4807
+ description: "把当前这次 CloudBase 开发整理成用户可以自己提交的反馈。" +
4808
+ "作品做出来了,用它生成案例,方便展示;开发不顺利,用它生成复盘,方便把卡点反馈给平台。" +
4809
+ "\n\n**什么时候用**:" +
4810
+ "\n- `channel=\"case\"`:部署或发布已经成功,用户愿意把作品放到案例墙时使用。返回案例草稿;用户确认后附上预填好的新建 issue 链接。" +
4811
+ "\n- `channel=\"retrospective\"`:用户表示这次开发不顺利、想反馈时使用。根据本会话里真实的工具调用失败生成复盘草稿;用户确认后同样附上预填链接。" +
4812
+ "\n\n**怎么用**:" +
4813
+ "\n- 第一次不要传 `confirmed`。先把返回的草稿全文给用户看。" +
4814
+ "\n- 用户明确同意后,再以 `confirmed=true` 调用。这时才会返回可打开的链接。" +
4815
+ "\n- 本工具不会替用户提交。链接里的正文就是本次返回的 draft,不要改写成另一份再让用户提交。" +
4816
+ "\n- 不采集对话轮次,不要编造轮次、作品名、简介或公网地址。" +
4817
+ "\n- 国际站是英文草稿和 GitHub 链接(body 参数)。国内站是中文草稿,链接指向 CNB 上公开的 CloudBase-AI-ToolKit 仓库,正文放在模板字段 session。若页面没自动填上,把 draft 粘贴到「本次会话记录」。",
4818
+ "schema.channel": "反馈用途:`case` 是把已完成的作品整理成案例;`retrospective` 是把这次不顺利的开发整理成复盘。",
4819
+ "schema.confirmed": "用户是否已经看过草稿全文并明确同意提交。省略或 false 时只返回草稿、不给链接。",
4820
+ }, {
4821
+ title: "Prepare feedback for this session",
4822
+ description: "Turn this CloudBase session into feedback the user can submit themselves. " +
4823
+ "Use it to showcase a finished work, or to report a session that was hard to finish." +
4824
+ "\n\n**When to use**:" +
4825
+ "\n- `channel=\"case\"`: the deploy or publish already succeeded and the user wants the work on the case wall. Returns a case draft, and a prefilled new-issue link after the user confirms." +
4826
+ "\n- `channel=\"retrospective\"`: the user says this session went badly and wants to report it. Builds the retrospective from tool failures that actually happened in this session, and adds a prefilled link after confirmation." +
4827
+ "\n\n**How to use**:" +
4828
+ "\n- Do not pass `confirmed` on the first call. Show the returned draft to the user in full." +
4829
+ "\n- Call again with `confirmed=true` only after the user explicitly agrees. That call returns the link." +
4830
+ "\n- This tool does not submit the issue. The link body is the draft in this response. Do not rewrite it and ask the user to submit the rewrite." +
4831
+ "\n- Conversation turns are not collected. Do not invent a turn count, title, summary, or public URL." +
4832
+ "\n- International site: English draft and a GitHub link (body parameter). China site: Chinese draft and a link to the public CloudBase-AI-ToolKit repo on CNB. The draft is placed in the template field id session. If the page does not fill it, paste the draft into that field.",
4833
+ "schema.channel": "What the feedback is for: `case` turns a finished work into a showcase entry; `retrospective` turns a difficult session into a write-up.",
4834
+ "schema.confirmed": "Whether the user has read the full draft and agreed to submit it. Omit or pass false to return the draft only, with no link.",
4835
+ });
4836
+
4837
+
4750
4838
  /***/ },
4751
4839
 
4752
4840
  /***/ 8015
@@ -4986,8 +5074,8 @@ const types_js_1 = __webpack_require__(9921);
4986
5074
  exports.functions = (0, types_js_1.defineModule)({
4987
5075
  // ---- 工具 meta ----
4988
5076
  queryTitle: "查询 CloudBase 云函数",
4989
- queryDescription: "CloudBase 云函数统一只读入口。通过更自解释的 action 查询 CloudBase 云函数列表、函数详情、执行日志、层、触发器和代码下载地址。" +
4990
- "\n\n**分页说明**:`listFunctions`、`listLayers` 支持 `limit` 和 `offset` 参数。" +
5077
+ queryDescription: "CloudBase 云函数统一只读入口。通过更自解释的 action 查询 CloudBase 云函数列表、函数详情、执行日志、层、触发器、代码下载地址、已发布版本与流量别名。" +
5078
+ "\n\n**分页说明**:`listFunctions`、`listLayers`、`listVersionByFunction` 支持 `limit` 和 `offset` 参数。" +
4991
5079
  "\n- `limit`: 分页数量,默认值由后端决定" +
4992
5080
  "\n- `offset`: 分页偏移,从 0 开始" +
4993
5081
  "\n- 示例:`queryFunctions(action=\"listFunctions\", offset=10, limit=10)`" +
@@ -4995,6 +5083,7 @@ exports.functions = (0, types_js_1.defineModule)({
4995
5083
  "\n- 示例:`queryFunctions(action=\"listFunctionLogs\", functionName=\"my-function\")`" +
4996
5084
  "\n- 如需查看日志详情:`queryFunctions(action=\"getFunctionLogDetail\", requestId=\"xxx\")`" +
4997
5085
  "\n\n**定时任务 / cron / 定时跑**:使用 `listFunctionTriggers` 查询函数的 timer 触发器配置。" +
5086
+ "\n\n**版本与流量路由**:`listVersionByFunction` 列出已发布版本(对齐 tcb fn list-function-versions);`getFunctionAlias` 查看别名/灰度配置(对齐 tcb fn get-route,aliasName 默认 `$DEFAULT`)。" +
4998
5087
  "\n\n**层(Layer)说明**:" +
4999
5088
  "\n- 层为 SCF 账号级共享命名空间:不同环境创建同名层会共享同一层的版本序列;删除某版本会影响所有绑定该版本的环境的函数" +
5000
5089
  "\n- 创建层必须用带环境标识的唯一层名,固定格式:`{layerName}_{当前envId}`(如 `common_cloud1-d9ghadgak3edf6b36`)。不要在不同环境使用相同裸层名,创建前先 `listLayers` 查重" +
@@ -5003,8 +5092,9 @@ exports.functions = (0, types_js_1.defineModule)({
5003
5092
  "\n- 本工具用于查询特定 CloudBase 云函数的执行日志" +
5004
5093
  "\n- `queryLogs` 工具用于搜索 CLS 日志服务(跨服务日志聚合)",
5005
5094
  manageTitle: "管理 CloudBase 云函数",
5006
- manageDescription: "CloudBase 云函数统一写入口。支持创建函数、更新代码、更新配置、调用函数、管理定时跑 / 定时任务 / scheduled job 的 timer 触发器和层绑定。" +
5095
+ manageDescription: "CloudBase 云函数统一写入口。支持创建函数、更新代码、更新配置、调用函数、发布版本、配置流量别名、管理定时跑 / 定时任务 / scheduled job 的 timer 触发器和层绑定。" +
5007
5096
  "如果要创建 cron 定时任务,先用 createFunction 创建函数,再用 createFunctionTrigger 创建 timer 触发器(支持7段cron表达式),deleteFunctionTrigger 删除触发器。" +
5097
+ "版本发布:`publishVersion` 对齐 tcb fn publish-version / SDK publishVersion;灰度/切流:`updateFunctionAliasConfig` 对齐 tcb fn config-route / SDK updateFunctionAliasConfig(aliasName 默认 `$DEFAULT`)。" +
5008
5098
  "HTTP 云函数镜像构建部署:createFunction / updateFunctionCode 通过 func.buildStrategy 区分。" +
5009
5099
  "func.buildStrategy=image(已有镜像,填 func.imageConfig.imageUri)直接创建/更新 HTTP 函数;" +
5010
5100
  "func.buildStrategy=local(本地 Docker 构建推送)、cloud(CloudApp 云端构建)走镜像构建部署编排(需要 func.imageConfig;build 非必填,缺省仓库坐标自动补齐:namespace 默认 envId、repository 默认函数名)," +
@@ -5054,7 +5144,7 @@ exports.functions = (0, types_js_1.defineModule)({
5054
5144
  "opErr.default": "请检查函数名、目录结构和环境中的函数状态后重试。",
5055
5145
  "opErr.prefix": "[{operation}] {message}\n建议:",
5056
5146
  confirmRequired: "{action} 是危险操作,请显式传入 confirm=true 后再执行",
5057
- "cloudMode.localOnly": "{action} 在 cloud mode 下不可用,因为该操作依赖本地函数代码目录。请改用本地模式执行,或使用镜像部署(runtime=CustomImage + imageConfig)。",
5147
+ "cloudMode.localOnly": "{action} 在 cloud mode 下不可用,因为该操作依赖本地函数代码目录。可用出路:1) 使用镜像部署(runtime=CustomImage + imageConfig);2) 使用 ZIP 两段式部署:先 queryFunctions action=getFunctionUploadUrl 获取预签名上传地址,PUT 代码 zip 后通过 manageFunctions 的 code 入参部署(阶段 B 同样不依赖本地目录)。",
5058
5148
  "cloudMode.contentPathUnsupported": "createLayerVersion 在 cloud mode 下不支持 contentPath,本地文件内容请改为 base64Content 或改用本地模式执行。",
5059
5149
  offsetLimitTooLarge: "offset+limit 不能大于 10000",
5060
5150
  startTimeInvalid: "startTime 格式错误: \"{value}\"。必须使用 YYYY-MM-DD HH:mm:ss 格式(如 2024-01-01 00:00:00)",
@@ -5067,6 +5157,8 @@ exports.functions = (0, types_js_1.defineModule)({
5067
5157
  "deployStatus.cloudMode": "{action} 在 cloud mode 下不可用:异步部署任务只由 buildStrategy=cloud/local 的真实部署创建,而这两种策略的真实执行在 cloud mode 下都不支持(需要读取本地构建上下文或本地 Docker),因此不会存在任何 taskId。buildStrategy=image 走同步部署,直接在 manageFunctions 的返回里拿结果,也不需要查询部署状态。如需异步镜像构建部署,请改用本地 MCP 模式。",
5068
5158
  deployTaskNotFound: "未找到部署任务 {taskId};部署任务不存在,可能已过期、不属于当前环境 {envId},或 MCP Server 已重启(任务仅保存在 MCP 进程内存中)。",
5069
5159
  unsupportedAction: "不支持的操作类型: {action}",
5160
+ storageMissing: "当前环境没有可用的对象存储桶(DescribeEnvs 未返回 Storages),无法使用 COS 两段式部署。请检查环境存储配置,或改用本地模式部署。共享存储桶(ExternalStorage)环境同样不支持该通道。",
5161
+ credentialMissing: "当前凭据缺少 SecretId/SecretKey(如 IDE 代理模式),无法本地铸造 COS 预签名上传地址。请改用本地模式或包含永久密钥/临时密钥的登录方式。",
5070
5162
  // ---- nextActions reasons ----
5071
5163
  "reason.continuePolling": "继续查询云函数部署状态",
5072
5164
  "reason.getDetail": "查看单个函数详情",
@@ -5105,8 +5197,15 @@ exports.functions = (0, types_js_1.defineModule)({
5105
5197
  "reason.imageFnReady": "确认镜像函数已就绪(Active)",
5106
5198
  "reason.imageUpdateReady": "确认镜像更新后函数已就绪(Active)",
5107
5199
  "reason.imageNextIteration": "后续迭代只需用新镜像 tag 调用 updateFunctionCode 更新镜像",
5200
+ "reason.cosCreate": "把 PUT 好的代码 zip 通过 code 入参部署为函数(两段式阶段 B)",
5108
5201
  "reason.imageGatewayRoute": "如需通过 URL 访问镜像 HTTP 函数,显式创建 Domain/Route 访问入口并传 type=\"HTTP\"(映射 WEB_SCF)",
5109
5202
  "reason.latestConfig": "确认最新函数配置",
5203
+ "reason.publishVersion": "发布函数新版本(对齐 tcb fn publish-version)",
5204
+ "reason.getFunctionAlias": "查看函数流量别名配置(对齐 tcb fn get-route)",
5205
+ "reason.updateFunctionAlias": "更新函数流量别名/灰度路由(对齐 tcb fn config-route)",
5206
+ "reason.listVersions": "查看函数已发布版本列表(对齐 tcb fn list-function-versions)",
5207
+ "reason.routeTraffic": "将流量切到新版本或配置灰度权重",
5208
+ "reason.confirmAlias": "确认别名与流量配置已生效",
5110
5209
  // ---- 成功 message ----
5111
5210
  listedFunctions: "已获取 {count} 个云函数",
5112
5211
  gotFunctionDetail: "已获取函数 {fnName} 的详情",
@@ -5118,8 +5217,15 @@ exports.functions = (0, types_js_1.defineModule)({
5118
5217
  gotLayerVersionDetail: "已获取层 {layerName} 版本 {layerVersion} 的详情",
5119
5218
  gotFunctionTriggers: "已获取函数 {fnName} 的触发器列表",
5120
5219
  gotDownloadUrl: "已获取函数 {fnName} 的代码下载链接",
5220
+ gotUploadUrl: "已生成函数代码包上传地址({seconds} 秒内有效)。下一步:PUT 代码 zip 到 uploadUrl(uploadHeaders 非空时须随请求携带),再调用 manageFunctions createFunction/updateFunctionCode 并传入 code 三元组(cosBucketName/cosObjectName/cosBucketRegion)完成部署",
5221
+ gotFunctionVersions: "已获取函数 {fnName} 的版本列表",
5222
+ gotFunctionAlias: "已获取函数 {fnName} 的别名 {aliasName}",
5223
+ publishedVersion: "已发布函数 {fnName} 的新版本 {version}",
5224
+ updatedFunctionAlias: "已更新函数 {fnName} 别名 {aliasName}(主版本 {version})",
5121
5225
  createdHttpFunctionMessage: "已创建 HTTP 函数 {fnName}。如果后续需要通过 URL 访问,请显式调用 manageGateway(action=\"createRoute\"),并把 upstreamResourceType=\"WEB_SCF\" 一起传入,再按实际路径和鉴权需求创建访问入口。评测或其他外部调用方可能会以匿名身份访问,而且失败后不一定会把 EXCEED_AUTHORITY 再反馈给 AI;交付前请主动确认访问路径和函数安全规则,若已出现 EXCEED_AUTHORITY,请先调用 queryPermissions(action=\"getResourcePermission\", resourceType=\"function\", resourceId=\"{fnName}\") 查看当前规则,再按需要使用 managePermissions(action=\"updateResourcePermission\") 调整权限。",
5122
5226
  createdFunction: "已创建函数 {fnName}",
5227
+ cosCreatedMessage: "已基于环境 COS 桶中的代码包(deployMode=cos)创建函数 {fnName}。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪。",
5228
+ cosUpdatedMessage: "已用环境 COS 桶中的新代码包(deployMode=cos)更新函数 {fnName} 的代码。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪(Active)。",
5123
5229
  imageCreatedMessage: "已基于镜像 {imageUri} 创建 HTTP 函数 {fnName}。请确认 TCR、SCF 与构建管道处于同一地域;如需通过 URL 访问,请显式调用 manageGateway(action=\"createRoute\", upstreamResourceType=\"WEB_SCF\") 并按需调整函数安全规则。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪。",
5124
5230
  imageUpdatedMessage: "已将函数 {fnName} 的镜像更新为 {imageUri}。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪(Active)。",
5125
5231
  updatedCode: "已更新函数 {fnName} 的代码",
@@ -5185,12 +5291,12 @@ exports.functions = (0, types_js_1.defineModule)({
5185
5291
  "schema.create.layers": "Layer 配置",
5186
5292
  "schema.manageLayer.name": "层名称",
5187
5293
  "schema.manageLayer.version": "层版本号",
5188
- "schema.query.action": "只读操作类型:\n- `listFunctions`: 列出所有 CloudBase 云函数\n- `getFunctionDetail`: 获取 CloudBase 云函数详情(需要 functionName)\n- `listFunctionLogs`: 查询 CloudBase 云函数执行日志(需要 functionName)\n- `getFunctionLogDetail`: 获取日志详情(需要 requestId)\n- `listFunctionLayers`: 列出函数绑定的层\n- `listLayers`: 列出所有层(账号级视图,含其他环境创建的层)\n- `listLayerVersions`: 列出层的版本(注意:是 Versions 不是 Version;账号级视图)\n- `getLayerVersionDetail`: 获取层版本详情(账号级视图)\n- `listFunctionTriggers`: 列出函数触发器(用于查看定时任务 / cron / timer 配置)\n- `getFunctionDownloadUrl`: 获取函数代码下载地址\n- `getFunctionDeployStatus`: 按 taskId 查询异步部署状态、阶段进度和最终结果。返回 data.build(构建子状态)、data.deploy(部署子状态)、data.progress(阶段事件);status=running 时 data.result 与 data.error 一律为 null,不得报告部署完成。调用方必须持续轮询直到 status=succeeded/failed;status=expired 表示任务超过最长保留时间(2 小时)被终结,云端可能仍在部署,需用 getFunctionDetail 确认。任务只保存在 MCP 进程内存中,过期或 MCP Server 重启后返回 errorCode=DEPLOY_TASK_NOT_FOUND;任务按环境隔离,只能查到当前环境自己发起的部署。cloud mode 下本 action 不可用:异步任务只由 buildStrategy=cloud/local 的真实部署创建,而这两种策略在 cloud mode 下都不支持真实执行,image 策略则走同步部署不产生 taskId。",
5189
- "schema.query.functionName": "CloudBase 云函数名称。`getFunctionDetail`、`listFunctionLogs`、`listFunctionLayers`、`listFunctionTriggers`、`getFunctionDownloadUrl` 时必填",
5294
+ "schema.query.action": "只读操作类型:\n- `listFunctions`: 列出所有 CloudBase 云函数\n- `getFunctionDetail`: 获取 CloudBase 云函数详情(需要 functionName)\n- `listFunctionLogs`: 查询 CloudBase 云函数执行日志(需要 functionName)\n- `getFunctionLogDetail`: 获取日志详情(需要 requestId)\n- `listFunctionLayers`: 列出函数绑定的层\n- `listLayers`: 列出所有层(账号级视图,含其他环境创建的层)\n- `listLayerVersions`: 列出层的版本(注意:是 Versions 不是 Version;账号级视图)\n- `getLayerVersionDetail`: 获取层版本详情(账号级视图)\n- `listFunctionTriggers`: 列出函数触发器(用于查看定时任务 / cron / timer 配置)\n- `getFunctionDownloadUrl`: 获取函数代码下载地址\n- `getFunctionDeployStatus`: 按 taskId 查询异步部署状态、阶段进度和最终结果。返回 data.build(构建子状态)、data.deploy(部署子状态)、data.progress(阶段事件);status=running 时 data.result 与 data.error 一律为 null,不得报告部署完成。调用方必须持续轮询直到 status=succeeded/failed;status=expired 表示任务超过最长保留时间(2 小时)被终结,云端可能仍在部署,需用 getFunctionDetail 确认。任务只保存在 MCP 进程内存中,过期或 MCP Server 重启后返回 errorCode=DEPLOY_TASK_NOT_FOUND;任务按环境隔离,只能查到当前环境自己发起的部署。cloud mode 下本 action 不可用:异步任务只由 buildStrategy=cloud/local 的真实部署创建,而这两种策略在 cloud mode 下都不支持真实执行,image 策略则走同步部署不产生 taskId。\n- `listVersionByFunction`: 列出函数已发布版本(对齐 tcb fn list-function-versions / SDK listVersionByFunction;需要 functionName)\n- `getFunctionAlias`: 查询函数别名与流量路由(对齐 tcb fn get-route / SDK getFunctionAlias;需要 functionName;aliasName 默认 $DEFAULT)\n- `getFunctionUploadUrl`: 获取函数代码包的 COS 预签名上传地址(ZIP 两段式部署阶段 A):PUT 代码 zip 到 uploadUrl(uploadHeaders 非空时须随请求携带对应请求头),再调用 manageFunctions 的 createFunction/updateFunctionCode 并传 code 三元组(阶段 B)。functionName 可选,仅用于生成上传对象 key。返回的 uploadUrl 含凭据签名,不得写入日志或持久化",
5295
+ "schema.query.functionName": "CloudBase 云函数名称。`getFunctionDetail`、`listFunctionLogs`、`listFunctionLayers`、`listFunctionTriggers`、`getFunctionDownloadUrl`、`listVersionByFunction`、`getFunctionAlias` 时必填;`getFunctionUploadUrl` 可选(仅用于生成上传对象 key)",
5190
5296
  "schema.query.limit": "分页数量(limit)。列表类 action 可选,默认值由后端决定",
5191
5297
  "schema.query.offset": "分页偏移(offset)。列表类 action 可选,默认 0",
5192
5298
  "schema.query.codeSecret": "代码保护密钥,用于解密函数代码",
5193
- "schema.query.revealEnvValues": "getFunctionDetail / listFunctionTriggers 时是否返回环境变量明文值。默认 false:Value 脱敏为 ***,仅保留 Key 与 ValueLength,足以确认配置了哪些变量及变更是否生效;true 时返回明文,敏感变量会进入模型上下文,谨慎使用。如需查看明文,建议优先使用控制台或 CLI",
5299
+ "schema.query.revealEnvValues": "getFunctionDetail / listFunctionTriggers / listFunctionLayers 时是否返回环境变量明文值。默认 false:Value 脱敏为 ***,仅保留 Key 与 ValueLength,足以确认配置了哪些变量及变更是否生效;true 时返回明文,敏感变量会进入模型上下文,谨慎使用。如需查看明文,建议优先使用控制台或 CLI",
5194
5300
  "schema.query.startTime": "日志查询开始时间,格式必须为 YYYY-MM-DD HH:mm:ss(如 2024-01-01 00:00:00)。与 endTime 间隔不能超过一天。不传时默认查询最近一天",
5195
5301
  "schema.query.endTime": "日志查询结束时间,格式必须为 YYYY-MM-DD HH:mm:ss(如 2024-01-01 23:59:59)。与 startTime 间隔不能超过一天。不传时默认为当前时间",
5196
5302
  "schema.query.requestId": "日志请求 ID。`getFunctionLogDetail` 操作必填,可从 `listFunctionLogs` 结果中获取",
@@ -5200,12 +5306,19 @@ exports.functions = (0, types_js_1.defineModule)({
5200
5306
  "schema.query.layerName": "层名称。`listLayerVersions`、`getLayerVersionDetail` 操作必填。层为账号级共享命名空间;推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36)",
5201
5307
  "schema.query.layerVersion": "层版本号。`getLayerVersionDetail` 操作必填",
5202
5308
  "schema.query.taskId": "`getFunctionDeployStatus` 操作时的异步部署任务 ID(由 manageFunctions 的 wait=false 返回)。任务仅保存在当前 MCP 进程内存中:终态任务保留约 30 分钟,运行中任务最长保留 2 小时。",
5203
- "schema.manage.action": "写操作类型,例如 createFunction、updateFunctionCode、incrementalDeployFunction、invokeFunction、deleteFunction、createFunctionTrigger(定时任务 / cron / timer)、deleteFunctionTrigger、createLayerVersion、deleteLayerVersion、attachLayer、detachLayer、updateFunctionLayers。层名推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36)",
5309
+ "schema.query.order": "`listVersionByFunction` 排序方向,如 ASC / DESC",
5310
+ "schema.query.orderBy": "`listVersionByFunction` 排序字段,如 AddTime / ModTime",
5311
+ "schema.query.aliasName": "`getFunctionAlias` 的别名名称。省略时默认 `$DEFAULT`(与 tcb fn get-route 一致)",
5312
+ "schema.manage.action": "写操作类型,例如 createFunction、updateFunctionCode、incrementalDeployFunction、invokeFunction、deleteFunction、createFunctionTrigger(定时任务 / cron / timer)、deleteFunctionTrigger、createLayerVersion、deleteLayerVersion、attachLayer、detachLayer、updateFunctionLayers、publishVersion(发布新版本,对齐 tcb fn publish-version)、updateFunctionAliasConfig(更新别名/流量路由,对齐 tcb fn config-route)。层名推荐固定格式 `{layerName}_{当前envId}`(如 common_cloud1-d9ghadgak3edf6b36)",
5204
5313
  "schema.manage.func": "createFunction / updateFunctionCode 的函数配置。镜像/构建部署通过 func.buildStrategy(zip/cloud/local/image)区分,镜像相关字段收敛在 func.imageConfig 命名空间下。",
5205
5314
  "schema.manage.functionRootPath": "创建或更新函数代码时默认推荐的本地目录方式。必须是直接包含函数文件夹的目录绝对路径(如 /abs/path/cloudfunctions 或 /abs/path/functions),不要传项目根目录(如 /abs/path),也不要传到函数名子目录(如 /abs/path/cloudfunctions/hello)。本地应按 cloudfunctions/<functionName>/index.js 或 functions/<functionName>/index.js 布局,此参数传 cloudfunctions 或 functions 目录的绝对路径。SDK 会自动拼接函数名子目录,无需预先压缩 zip 或 base64 编码。",
5206
5315
  "schema.manage.force": "createFunction 时是否覆盖",
5207
- "schema.manage.functionName": "目标函数名称(顶层)。updateFunctionCode / updateFunctionConfig / invokeFunction 等 action 使用此字段。不要只写在 func.name:createFunction 用 func.name,其它 action 用顶层 functionName。若误传 func.name,也会被识别为 functionName。",
5316
+ "schema.manage.functionName": "目标函数名称(顶层)。updateFunctionCode / updateFunctionConfig / invokeFunction / publishVersion / updateFunctionAliasConfig 等 action 使用此字段。不要只写在 func.name:createFunction 用 func.name,其它 action 用顶层 functionName。若误传 func.name,也会被识别为 functionName。",
5208
5317
  "schema.manage.zipFile": "仅兼容特殊场景:预先准备好的代码包 base64 编码。普通 createFunction/updateFunctionCode 默认不要先压缩 zip,优先使用 functionRootPath。",
5318
+ "schema.manage.code": "ZIP 两段式部署阶段 B:代码包已通过 queryFunctions action=getFunctionUploadUrl 上传到环境 COS 桶。三元组(cosBucketName/cosObjectName/cosBucketRegion)直接使用 getFunctionUploadUrl 返回值原样透传。传入 code 后 createFunction/updateFunctionCode 不再读取本地目录(functionRootPath/zipFile 均不需要),默认不触发云端依赖安装(可用 func.installDependency 覆盖)。",
5319
+ "schema.code.cosBucketName": "环境存储桶短名(不含 -appid 后缀),直接使用 getFunctionUploadUrl 返回的 cosBucketName,不要自填",
5320
+ "schema.code.cosObjectName": "上传对象 key,直接使用 getFunctionUploadUrl 返回的 cosObjectName",
5321
+ "schema.code.cosBucketRegion": "存储桶地域,省略时自动使用当前环境存储桶地域",
5209
5322
  "schema.manage.handler": "函数入口",
5210
5323
  "schema.manage.timeout": "配置更新时的超时时间",
5211
5324
  "schema.manage.envVariables": "配置更新时要合并的环境变量。若含 DATABASE_URL / MYSQL_* / POSTGRES_* / REDIS_* 等 TCP 连库变量,必须同时提供真实 vpc(或函数已绑定完整 VPC)。禁止猜测 vpcId/subnetId。",
@@ -5218,7 +5331,7 @@ exports.functions = (0, types_js_1.defineModule)({
5218
5331
  "schema.manage.contentPath": "层内容路径,可为目录或 ZIP 文件",
5219
5332
  "schema.manage.base64Content": "层内容的 base64 编码",
5220
5333
  "schema.manage.runtimes": "层适用的运行时列表",
5221
- "schema.manage.description": "层版本描述",
5334
+ "schema.manage.description": "描述信息。createLayerVersion 时为层版本描述;publishVersion / updateFunctionAliasConfig 时为版本或别名描述",
5222
5335
  "schema.manage.licenseInfo": "层许可证信息",
5223
5336
  "schema.manage.layers": "updateFunctionLayers 的目标层列表,顺序即最终顺序",
5224
5337
  "schema.manage.codeSecret": "层绑定时的代码保护密钥",
@@ -5227,11 +5340,22 @@ exports.functions = (0, types_js_1.defineModule)({
5227
5340
  "schema.manage.autoGrant": "镜像部署是否允许 manager-node 自动补齐固定白名单 CAM 策略。默认 false;仅在明确确认权限变更时设为 true。",
5228
5341
  "schema.manage.confirm": "危险操作确认开关。deleteFunction、deleteFunctionTrigger、deleteLayerVersion、detachLayer 等删除类操作以及镜像构建部署(func.buildStrategy=cloud/local)真实执行需要显式传入 confirm=true",
5229
5342
  "schema.manage.incrementalFile": "incrementalDeployFunction 增量部署时的变更文件路径",
5343
+ "schema.manage.aliasName": "`updateFunctionAliasConfig` 的别名名称。省略时默认 `$DEFAULT`(与 tcb fn config-route 一致)",
5344
+ "schema.manage.functionVersion": "`updateFunctionAliasConfig` 的主版本。可为具体版本号或 `$LATEST`",
5345
+ "schema.manage.routingConfig": "`updateFunctionAliasConfig` 的流量路由配置。AdditionalVersionWeights 用于灰度权重;AddtionVersionMatchs 为 SCF/SDK 历史字段名(含拼写)",
5346
+ "schema.routing.version": "附加流量版本号",
5347
+ "schema.routing.weight": "附加流量权重(0-1 或百分比,按 SCF 约定)",
5348
+ "schema.routing.matchVersion": "匹配规则指向的版本号",
5349
+ "schema.routing.matchKey": "匹配规则的 Header/Query Key",
5350
+ "schema.routing.matchMethod": "匹配方法,如 Exact / Regex",
5351
+ "schema.routing.matchExpression": "匹配表达式",
5352
+ "schema.routing.additionalWeights": "附加版本权重列表(灰度发布)",
5353
+ "schema.routing.additionalMatches": "附加版本匹配规则列表(字段名保持 SCF AddtionVersionMatchs)",
5230
5354
  }, {
5231
5355
  // ---- Tool meta ----
5232
5356
  queryTitle: "Query CloudBase Cloud Functions",
5233
- queryDescription: "Unified read-only entry for CloudBase cloud functions. Query function lists, function details, execution logs, layers, triggers, and code download URLs through self-explanatory actions." +
5234
- "\n\n**Pagination**: `listFunctions` and `listLayers` support `limit` and `offset` parameters." +
5357
+ queryDescription: "Unified read-only entry for CloudBase cloud functions. Query function lists, function details, execution logs, layers, triggers, code download URLs, published versions, and traffic aliases through self-explanatory actions." +
5358
+ "\n\n**Pagination**: `listFunctions`, `listLayers`, and `listVersionByFunction` support `limit` and `offset` parameters." +
5235
5359
  "\n- `limit`: page size, the default is decided by the backend" +
5236
5360
  "\n- `offset`: pagination offset, starting from 0" +
5237
5361
  "\n- Example: `queryFunctions(action=\"listFunctions\", offset=10, limit=10)`" +
@@ -5239,6 +5363,7 @@ exports.functions = (0, types_js_1.defineModule)({
5239
5363
  "\n- Example: `queryFunctions(action=\"listFunctionLogs\", functionName=\"my-function\")`" +
5240
5364
  "\n- To view log details: `queryFunctions(action=\"getFunctionLogDetail\", requestId=\"xxx\")`" +
5241
5365
  "\n\n**Scheduled tasks / cron / timers**: use `listFunctionTriggers` to query a function's timer trigger configuration." +
5366
+ "\n\n**Versions and traffic routing**: `listVersionByFunction` lists published versions (aligns with tcb fn list-function-versions); `getFunctionAlias` views alias / canary config (aligns with tcb fn get-route; aliasName defaults to `$DEFAULT`)." +
5242
5367
  "\n\n**Layers**:" +
5243
5368
  "\n- Layers are account-level shared namespaces in SCF: same-named layers created in different environments share one version sequence; deleting a version affects functions in every environment bound to it" +
5244
5369
  "\n- When creating a layer, use a unique name with the environment suffix, in the fixed format `{layerName}_{current envId}` (e.g. `common_cloud1-d9ghadgak3edf6b36`). Do not reuse the same bare layer name across environments; check with `listLayers` before creating" +
@@ -5247,8 +5372,9 @@ exports.functions = (0, types_js_1.defineModule)({
5247
5372
  "\n- This tool queries execution logs of a specific CloudBase cloud function" +
5248
5373
  "\n- The `queryLogs` tool searches the CLS log service (cross-service log aggregation)",
5249
5374
  manageTitle: "Manage CloudBase Cloud Functions",
5250
- manageDescription: "Unified write entry for CloudBase cloud functions. Supports creating functions, updating code, updating configuration, invoking functions, and managing timer triggers (scheduled jobs / cron) and layer bindings." +
5375
+ manageDescription: "Unified write entry for CloudBase cloud functions. Supports creating functions, updating code, updating configuration, invoking functions, publishing versions, configuring traffic aliases, and managing timer triggers (scheduled jobs / cron) and layer bindings." +
5251
5376
  " To create a cron scheduled task, first create the function with createFunction, then create the timer trigger with createFunctionTrigger (7-field cron expression supported), and delete triggers with deleteFunctionTrigger." +
5377
+ " Version publish: `publishVersion` aligns with tcb fn publish-version / SDK publishVersion; canary / traffic shift: `updateFunctionAliasConfig` aligns with tcb fn config-route / SDK updateFunctionAliasConfig (aliasName defaults to `$DEFAULT`)." +
5252
5378
  " HTTP function image build & deploy: createFunction / updateFunctionCode distinguish via func.buildStrategy." +
5253
5379
  " func.buildStrategy=image (existing image, set func.imageConfig.imageUri) creates/updates the HTTP function directly;" +
5254
5380
  " func.buildStrategy=local (local Docker build & push) and cloud (CloudApp cloud build) go through the image build/deploy orchestration (func.imageConfig required; build optional — missing registry coordinates are auto-filled: namespace defaults to envId, repository defaults to the function name)," +
@@ -5298,7 +5424,7 @@ exports.functions = (0, types_js_1.defineModule)({
5298
5424
  "opErr.default": "Please check the function name, directory structure, and the function status in the environment, then retry.",
5299
5425
  "opErr.prefix": "[{operation}] {message}\nSuggestions: ",
5300
5426
  confirmRequired: "{action} is a dangerous operation; pass confirm=true explicitly before executing",
5301
- "cloudMode.localOnly": "{action} is unavailable in cloud mode because the operation depends on a local function code directory. Run it in local mode, or use image deployment (runtime=CustomImage + imageConfig).",
5427
+ "cloudMode.localOnly": "{action} is unavailable in cloud mode because the operation depends on a local function code directory. Options: 1) use image deployment (runtime=CustomImage + imageConfig); 2) use two-phase ZIP deployment: first call queryFunctions action=getFunctionUploadUrl to get a presigned upload URL, PUT the code zip, then deploy via the manageFunctions code parameter (phase B also needs no local directory).",
5302
5428
  "cloudMode.contentPathUnsupported": "createLayerVersion does not support contentPath in cloud mode; switch local file content to base64Content or run in local mode.",
5303
5429
  offsetLimitTooLarge: "offset+limit must not be greater than 10000",
5304
5430
  startTimeInvalid: "Invalid startTime: \"{value}\". It must use the YYYY-MM-DD HH:mm:ss format (e.g. 2024-01-01 00:00:00)",
@@ -5311,6 +5437,8 @@ exports.functions = (0, types_js_1.defineModule)({
5311
5437
  "deployStatus.cloudMode": "{action} is unavailable in cloud mode: async deployment tasks are only created by real deployments with buildStrategy=cloud/local, and real execution of both strategies is unsupported in cloud mode (they need the local build context or local Docker), so no taskId can exist. buildStrategy=image uses synchronous deployment and returns the result directly from manageFunctions, so no deployment status query is needed. For async image build deployment, switch to local MCP mode.",
5312
5438
  deployTaskNotFound: "Deployment task {taskId} not found; the task does not exist — it may have expired, belong to a different environment than {envId}, or the MCP Server was restarted (tasks are only kept in MCP process memory).",
5313
5439
  unsupportedAction: "Unsupported action: {action}",
5440
+ storageMissing: "The current environment has no usable object storage bucket (DescribeEnvs returned no Storages), so COS two-phase deployment is unavailable. Check the environment storage configuration, or deploy in local mode. Environments with a shared bucket (ExternalStorage) are not supported either.",
5441
+ credentialMissing: "The current credential lacks SecretId/SecretKey (e.g. IDE proxy mode), so a COS presigned upload URL cannot be minted locally. Use local mode or a login method with permanent/temporary keys.",
5314
5442
  // ---- nextActions reasons ----
5315
5443
  "reason.continuePolling": "Keep polling the cloud function deployment status",
5316
5444
  "reason.getDetail": "View details of a single function",
@@ -5349,8 +5477,15 @@ exports.functions = (0, types_js_1.defineModule)({
5349
5477
  "reason.imageFnReady": "Confirm the image function is ready (Active)",
5350
5478
  "reason.imageUpdateReady": "Confirm the function is ready (Active) after the image update",
5351
5479
  "reason.imageNextIteration": "For later iterations, just call updateFunctionCode with the new image tag to update the image",
5480
+ "reason.cosCreate": "Deploy the uploaded code zip as a function via the code parameter (two-phase deployment phase B)",
5352
5481
  "reason.imageGatewayRoute": "To access the image HTTP function via URL, explicitly create a Domain/Route access entry and pass type=\"HTTP\" (mapped to WEB_SCF)",
5353
5482
  "reason.latestConfig": "Confirm the latest function configuration",
5483
+ "reason.publishVersion": "Publish a new function version (aligns with tcb fn publish-version)",
5484
+ "reason.getFunctionAlias": "View function traffic alias config (aligns with tcb fn get-route)",
5485
+ "reason.updateFunctionAlias": "Update function traffic alias / canary routing (aligns with tcb fn config-route)",
5486
+ "reason.listVersions": "List published function versions (aligns with tcb fn list-function-versions)",
5487
+ "reason.routeTraffic": "Shift traffic to the new version or configure canary weights",
5488
+ "reason.confirmAlias": "Confirm the alias and traffic config have taken effect",
5354
5489
  // ---- Success messages ----
5355
5490
  listedFunctions: "Retrieved {count} cloud functions",
5356
5491
  gotFunctionDetail: "Retrieved details of function {fnName}",
@@ -5362,8 +5497,15 @@ exports.functions = (0, types_js_1.defineModule)({
5362
5497
  gotLayerVersionDetail: "Retrieved details of layer {layerName} version {layerVersion}",
5363
5498
  gotFunctionTriggers: "Retrieved the trigger list of function {fnName}",
5364
5499
  gotDownloadUrl: "Retrieved the code download URL of function {fnName}",
5500
+ gotUploadUrl: "Generated the code package upload URL (valid for {seconds} seconds). Next: PUT the code zip to uploadUrl (include the uploadHeaders when non-empty), then call manageFunctions createFunction/updateFunctionCode with the code triplet (cosBucketName/cosObjectName/cosBucketRegion) to deploy",
5501
+ gotFunctionVersions: "Retrieved the version list of function {fnName}",
5502
+ gotFunctionAlias: "Retrieved alias {aliasName} of function {fnName}",
5503
+ publishedVersion: "Published new version {version} of function {fnName}",
5504
+ updatedFunctionAlias: "Updated alias {aliasName} of function {fnName} (primary version {version})",
5365
5505
  createdHttpFunctionMessage: "Created HTTP function {fnName} from the image. If URL access is needed later, explicitly call manageGateway(action=\"createRoute\") with upstreamResourceType=\"WEB_SCF\", then create the access entry according to the actual path and auth requirements. Evaluators or other external callers may access anonymously, and failures may not feed EXCEED_AUTHORITY back to the AI; before delivery, proactively confirm the access path and the function security rules. If EXCEED_AUTHORITY has already appeared, first call queryPermissions(action=\"getResourcePermission\", resourceType=\"function\", resourceId=\"{fnName}\") to view the current rules, then adjust permissions with managePermissions(action=\"updateResourcePermission\") as needed.",
5366
5506
  createdFunction: "Created function {fnName}",
5507
+ cosCreatedMessage: "Created function {fnName} from the code package in the environment COS bucket (deployMode=cos). Use queryFunctions(action=\"getFunctionDetail\") after deployment to confirm the function is ready.",
5508
+ cosUpdatedMessage: "Updated the code of function {fnName} with the new package in the environment COS bucket (deployMode=cos). Use queryFunctions(action=\"getFunctionDetail\") after deployment to confirm the function is ready (Active).",
5367
5509
  imageCreatedMessage: "Created HTTP function {fnName} from image {imageUri}. Please confirm TCR, SCF, and the build pipeline are in the same region; for URL access, explicitly call manageGateway(action=\"createRoute\", upstreamResourceType=\"WEB_SCF\") and adjust the function security rules as needed. After deployment, use queryFunctions(action=\"getFunctionDetail\") to confirm the function is ready.",
5368
5510
  imageUpdatedMessage: "Updated the image of function {fnName} to {imageUri}. After deployment, use queryFunctions(action=\"getFunctionDetail\") to confirm the function is ready (Active).",
5369
5511
  updatedCode: "Updated the code of function {fnName}",
@@ -5429,12 +5571,12 @@ exports.functions = (0, types_js_1.defineModule)({
5429
5571
  "schema.create.layers": "Layer configuration",
5430
5572
  "schema.manageLayer.name": "Layer name",
5431
5573
  "schema.manageLayer.version": "Layer version number",
5432
- "schema.query.action": "Read-only action type:\n- `listFunctions`: list all CloudBase cloud functions\n- `getFunctionDetail`: get function details (requires functionName)\n- `listFunctionLogs`: query function execution logs (requires functionName)\n- `getFunctionLogDetail`: get log details (requires requestId)\n- `listFunctionLayers`: list layers bound to a function\n- `listLayers`: list all layers (account-level view, including layers from other environments)\n- `listLayerVersions`: list layer versions (Versions, not Version; account-level view)\n- `getLayerVersionDetail`: get layer version details (account-level view)\n- `listFunctionTriggers`: list function triggers (scheduled task / cron / timer configuration)\n- `getFunctionDownloadUrl`: get the function code download URL\n- `getFunctionDeployStatus`: query async deployment status, stage progress, and final result by taskId. Returns data.build, data.deploy, and data.progress. While status=running, data.result and data.error are null and deployment must not be reported as complete. Keep polling until status=succeeded/failed. status=expired means the task exceeded the 2-hour retention limit; cloud deployment may still be running, so confirm with getFunctionDetail. Tasks exist only in MCP process memory; expired tasks or a restarted MCP Server return errorCode=DEPLOY_TASK_NOT_FOUND. Tasks are isolated by environment. This action is unavailable in cloud mode because real cloud/local builds cannot run there, while image deployment is synchronous and creates no taskId.",
5433
- "schema.query.functionName": "CloudBase cloud function name. Required for `getFunctionDetail`, `listFunctionLogs`, `listFunctionLayers`, `listFunctionTriggers`, and `getFunctionDownloadUrl`.",
5574
+ "schema.query.action": "Read-only action type:\n- `listFunctions`: list all CloudBase cloud functions\n- `getFunctionDetail`: get function details (requires functionName)\n- `listFunctionLogs`: query function execution logs (requires functionName)\n- `getFunctionLogDetail`: get log details (requires requestId)\n- `listFunctionLayers`: list layers bound to a function\n- `listLayers`: list all layers (account-level view, including layers from other environments)\n- `listLayerVersions`: list layer versions (Versions, not Version; account-level view)\n- `getLayerVersionDetail`: get layer version details (account-level view)\n- `listFunctionTriggers`: list function triggers (scheduled task / cron / timer configuration)\n- `getFunctionDownloadUrl`: get the function code download URL\n- `getFunctionDeployStatus`: query async deployment status, stage progress, and final result by taskId. Returns data.build, data.deploy, and data.progress. While status=running, data.result and data.error are null and deployment must not be reported as complete. Keep polling until status=succeeded/failed. status=expired means the task exceeded the 2-hour retention limit; cloud deployment may still be running, so confirm with getFunctionDetail. Tasks exist only in MCP process memory; expired tasks or a restarted MCP Server return errorCode=DEPLOY_TASK_NOT_FOUND. Tasks are isolated by environment. This action is unavailable in cloud mode because real cloud/local builds cannot run there, while image deployment is synchronous and creates no taskId.\n- `listVersionByFunction`: list published function versions (aligns with tcb fn list-function-versions / SDK listVersionByFunction; requires functionName)\n- `getFunctionAlias`: get function alias and traffic routing (aligns with tcb fn get-route / SDK getFunctionAlias; requires functionName; aliasName defaults to $DEFAULT)\n- `getFunctionUploadUrl`: get a COS presigned upload URL for a function code package (two-phase ZIP deployment phase A): PUT the code zip to uploadUrl (include the corresponding request headers when uploadHeaders is non-empty), then call manageFunctions createFunction/updateFunctionCode with the code triplet (phase B). functionName is optional and only shapes the upload object key. The uploadUrl carries credential-bound signatures; never log or persist it",
5575
+ "schema.query.functionName": "CloudBase cloud function name. Required for `getFunctionDetail`, `listFunctionLogs`, `listFunctionLayers`, `listFunctionTriggers`, `getFunctionDownloadUrl`, `listVersionByFunction`, and `getFunctionAlias`. Optional for `getFunctionUploadUrl` (only used to generate the upload object key).",
5434
5576
  "schema.query.limit": "Page size (limit). Optional for list actions; the backend determines the default.",
5435
5577
  "schema.query.offset": "Pagination offset. Optional for list actions; defaults to 0.",
5436
5578
  "schema.query.codeSecret": "Code protection secret used to decrypt function code.",
5437
- "schema.query.revealEnvValues": "Whether `getFunctionDetail` / `listFunctionTriggers` returns plaintext environment variable values. Defaults to false: Value is masked as ***, while Key and ValueLength remain, which is sufficient to verify configured variables and changes. true returns plaintext and may expose secrets to the model context; use cautiously. Prefer the console or CLI for plaintext values.",
5579
+ "schema.query.revealEnvValues": "Whether `getFunctionDetail` / `listFunctionTriggers` / `listFunctionLayers` returns plaintext environment variable values. Defaults to false: Value is masked as ***, while Key and ValueLength remain, which is sufficient to verify configured variables and changes. true returns plaintext and may expose secrets to the model context; use cautiously. Prefer the console or CLI for plaintext values.",
5438
5580
  "schema.query.startTime": "Log query start time in YYYY-MM-DD HH:mm:ss format (for example, 2024-01-01 00:00:00). The interval to endTime must not exceed one day. Defaults to the most recent day when omitted.",
5439
5581
  "schema.query.endTime": "Log query end time in YYYY-MM-DD HH:mm:ss format (for example, 2024-01-01 23:59:59). The interval from startTime must not exceed one day. Defaults to the current time when omitted.",
5440
5582
  "schema.query.requestId": "Log request ID. Required for `getFunctionLogDetail`; obtain it from `listFunctionLogs`.",
@@ -5444,12 +5586,19 @@ exports.functions = (0, types_js_1.defineModule)({
5444
5586
  "schema.query.layerName": "Layer name. Required for `listLayerVersions` and `getLayerVersionDetail`. Layers use an account-level shared namespace; use the fixed format `{layerName}_{current envId}` (for example, common_cloud1-d9ghadgak3edf6b36).",
5445
5587
  "schema.query.layerVersion": "Layer version number. Required for `getLayerVersionDetail`.",
5446
5588
  "schema.query.taskId": "Async deployment task ID for `getFunctionDeployStatus` (returned by manageFunctions with wait=false). Tasks exist only in current MCP process memory: terminal tasks are retained for about 30 minutes and running tasks for at most 2 hours.",
5447
- "schema.manage.action": "Write action type, such as createFunction, updateFunctionCode, incrementalDeployFunction, invokeFunction, deleteFunction, createFunctionTrigger (scheduled task / cron / timer), deleteFunctionTrigger, createLayerVersion, deleteLayerVersion, attachLayer, detachLayer, or updateFunctionLayers. Use the fixed layer naming format `{layerName}_{current envId}` (for example, common_cloud1-d9ghadgak3edf6b36).",
5589
+ "schema.query.order": "Sort direction for `listVersionByFunction`, such as ASC / DESC.",
5590
+ "schema.query.orderBy": "Sort field for `listVersionByFunction`, such as AddTime / ModTime.",
5591
+ "schema.query.aliasName": "Alias name for `getFunctionAlias`. Defaults to `$DEFAULT` when omitted (same as tcb fn get-route).",
5592
+ "schema.manage.action": "Write action type, such as createFunction, updateFunctionCode, incrementalDeployFunction, invokeFunction, deleteFunction, createFunctionTrigger (scheduled task / cron / timer), deleteFunctionTrigger, createLayerVersion, deleteLayerVersion, attachLayer, detachLayer, updateFunctionLayers, publishVersion (publish a new version; aligns with tcb fn publish-version), or updateFunctionAliasConfig (update alias / traffic routing; aligns with tcb fn config-route). Use the fixed layer naming format `{layerName}_{current envId}` (for example, common_cloud1-d9ghadgak3edf6b36).",
5448
5593
  "schema.manage.func": "Function configuration for createFunction / updateFunctionCode. Image/build deployment is selected by func.buildStrategy (zip/cloud/local/image), with image fields under func.imageConfig.",
5449
5594
  "schema.manage.functionRootPath": "Recommended local-directory input for creating or updating function code. It must be the absolute directory that directly contains function folders (for example, /abs/path/cloudfunctions or /abs/path/functions), not the project root or the function subdirectory. Local layout should be cloudfunctions/<functionName>/index.js or functions/<functionName>/index.js. Pass the absolute cloudfunctions/functions directory; the SDK appends the function subdirectory. Do not precompress ZIP or base64 content.",
5450
5595
  "schema.manage.force": "Whether createFunction overwrites an existing function.",
5451
- "schema.manage.functionName": "Target function name at the top level. Used by updateFunctionCode, updateFunctionConfig, invokeFunction, and similar actions. createFunction uses func.name; other actions use top-level functionName. A mistakenly supplied func.name is also recognized as functionName.",
5596
+ "schema.manage.functionName": "Target function name at the top level. Used by updateFunctionCode, updateFunctionConfig, invokeFunction, publishVersion, updateFunctionAliasConfig, and similar actions. createFunction uses func.name; other actions use top-level functionName. A mistakenly supplied func.name is also recognized as functionName.",
5452
5597
  "schema.manage.zipFile": "Compatibility only: base64-encoded prebuilt code package. For ordinary createFunction/updateFunctionCode, do not create a ZIP first; prefer functionRootPath.",
5598
+ "schema.manage.code": "Two-phase ZIP deployment phase B: the code package has been uploaded to the environment COS bucket via queryFunctions action=getFunctionUploadUrl. Pass the triplet (cosBucketName/cosObjectName/cosBucketRegion) through unchanged from the getFunctionUploadUrl response. With code provided, createFunction/updateFunctionCode no longer reads local directories (functionRootPath/zipFile are unnecessary), and cloud dependency installation is skipped by default (override with func.installDependency).",
5599
+ "schema.code.cosBucketName": "Environment bucket short name (without the -appid suffix); pass through the cosBucketName returned by getFunctionUploadUrl, do not invent one",
5600
+ "schema.code.cosObjectName": "Uploaded object key; pass through the cosObjectName returned by getFunctionUploadUrl",
5601
+ "schema.code.cosBucketRegion": "Bucket region; defaults to the current environment bucket region when omitted",
5453
5602
  "schema.manage.handler": "Function entry point",
5454
5603
  "schema.manage.timeout": "Timeout used for configuration updates.",
5455
5604
  "schema.manage.envVariables": "Environment variables to merge during a configuration update. If they contain TCP database variables such as DATABASE_URL, MYSQL_*, POSTGRES_*, or REDIS_*, also provide a real vpc (or ensure the function already has a complete VPC binding). Never guess vpcId/subnetId.",
@@ -5462,7 +5611,7 @@ exports.functions = (0, types_js_1.defineModule)({
5462
5611
  "schema.manage.contentPath": "Layer content path, either a directory or ZIP file.",
5463
5612
  "schema.manage.base64Content": "Base64-encoded layer content.",
5464
5613
  "schema.manage.runtimes": "Runtimes supported by the layer.",
5465
- "schema.manage.description": "Layer version description.",
5614
+ "schema.manage.description": "Description. Layer version description for createLayerVersion; version or alias description for publishVersion / updateFunctionAliasConfig.",
5466
5615
  "schema.manage.licenseInfo": "Layer license information.",
5467
5616
  "schema.manage.layers": "Target layer list for updateFunctionLayers; array order becomes final order.",
5468
5617
  "schema.manage.codeSecret": "Code protection secret used when binding a layer.",
@@ -5471,6 +5620,17 @@ exports.functions = (0, types_js_1.defineModule)({
5471
5620
  "schema.manage.autoGrant": "Whether manager-node may automatically add the fixed allowlist of CAM policies for image deployment. Defaults to false; set true only after explicitly confirming permission changes.",
5472
5621
  "schema.manage.confirm": "Dangerous-operation confirmation. deleteFunction, deleteFunctionTrigger, deleteLayerVersion, detachLayer, other delete actions, and real image build deployment (func.buildStrategy=cloud/local) require confirm=true.",
5473
5622
  "schema.manage.incrementalFile": "Changed-file path for incrementalDeployFunction incremental deployment.",
5623
+ "schema.manage.aliasName": "Alias name for `updateFunctionAliasConfig`. Defaults to `$DEFAULT` when omitted (same as tcb fn config-route).",
5624
+ "schema.manage.functionVersion": "Primary version for `updateFunctionAliasConfig`. May be a concrete version number or `$LATEST`.",
5625
+ "schema.manage.routingConfig": "Traffic routing config for `updateFunctionAliasConfig`. AdditionalVersionWeights is used for canary weights; AddtionVersionMatchs keeps the SCF/SDK historical field name (including the typo).",
5626
+ "schema.routing.version": "Additional traffic version number",
5627
+ "schema.routing.weight": "Additional traffic weight (0-1 or percentage per SCF convention)",
5628
+ "schema.routing.matchVersion": "Version targeted by a match rule",
5629
+ "schema.routing.matchKey": "Header/Query key for a match rule",
5630
+ "schema.routing.matchMethod": "Match method, such as Exact / Regex",
5631
+ "schema.routing.matchExpression": "Match expression",
5632
+ "schema.routing.additionalWeights": "Additional version weight list (canary release)",
5633
+ "schema.routing.additionalMatches": "Additional version match rules (field name keeps SCF AddtionVersionMatchs)",
5474
5634
  });
5475
5635
 
5476
5636
 
@@ -5804,10 +5964,11 @@ exports.hosting = (0, types_js_1.defineModule)({
5804
5964
  queryDescription: "查询 CloudBase 静态托管的只读信息。适合 AI 先做发现再决定下一步:action=websiteConfig 查询首页/错误页/路由规则与站点域名信息;action=status 查询托管服务状态;action=findFiles 按前缀查找文件;action=listFiles 列出全部托管文件;action=domainStatus 查询自定义域名的当前状态与配置。该工具不会产生任何副作用。",
5805
5965
  manageTitle: "管理 CloudBase 静态托管",
5806
5966
  manageDescription: "管理 CloudBase 静态托管的变更操作。action=upload 上传本地构建产物到共享域名(域名格式:<envId>-<appId>.tcloudbaseapp.com/<cloudPath>);action=delete 删除托管文件或目录(必须 confirm=true);action=setWebsiteDocument 设置首页/错误页/路由规则;action=enableService 开通静态托管;action=bindDomain / unbindDomain / updateDomain 管理自定义域名;action=downloadFile / downloadDirectory 下载托管内容到本地。⚠️ 底层每次托管操作都会请求 DescribeStaticStore 管控接口(20 次/秒 QPS 限制):批量删除多个文件请逐次调用并保持间隔(建议每秒不超过 10 次),同一目录下多个文件可优先用 isDir=true 一次删除整个目录;若报错含 \"frequency limit\" 说明触发了限流,请等待 1-2 秒后重试,不要连续快速重试。⚠️ 本工具没有关闭默认域名(*.tcloudbaseapp.com)的 action;要禁用该默认公网域名,请用 manageGateway(action=\"disableRoute\", domain=该 STATIC_STORE IsDefault 域名, path=\"/\")(底层 ModifyHTTPServiceRoute,不是 ModifyGatewayRoute)。⚠️ 新项目部署优先使用 manageApps(部署到独立子域名),本工具适合已有老项目继续使用或作为 manageApps 的 fallback。manageApps 与 manageHosting 域名不同,切换会导致老链接失效。若任务只是查看配置、文件或域名状态,请改用 queryHosting。",
5967
+ manageDescriptionCloud: "管理 CloudBase 静态托管的变更操作(cloud mode 版本)。⚠️ 依赖本地文件路径的 action 在 cloud mode 下不可用:action=upload / downloadFile / downloadDirectory 会直接报错,请勿调用。部署静态站点请改用 manageApps 云端链路:queryApps(action=\"getUploadUrl\", serviceName=\"<应用名>\") 获取预签名上传 URL → 将代码 zip PUT 上传到 uploadUrl(带 uploadHeaders 与 Content-Type: application/zip)→ manageApps(action=\"deployApp\", serviceName, cosTimestamp=<返回的 unixTimestamp>) 触发部署。可正常使用的远端管理操作:action=delete 删除托管文件或目录(必须 confirm=true);action=setWebsiteDocument 设置首页/错误页/路由规则;action=enableService 开通静态托管;action=bindDomain / unbindDomain / updateDomain 管理自定义域名。⚠️ 底层每次托管操作都会请求 DescribeStaticStore 管控接口(20 次/秒 QPS 限制):批量删除多个文件请逐次调用并保持间隔(建议每秒不超过 10 次);若报错含 \"frequency limit\" 说明触发了限流,请等待 1-2 秒后重试。若任务只是查看配置、文件或域名状态,请改用 queryHosting。",
5807
5968
  commonServiceUnsupported: "当前 CloudBase Manager 实例不支持 commonService.call,无法执行 {action}。",
5808
5969
  managerUnavailable: "CloudBase Manager 实例不可用。",
5809
5970
  hostingStoreMissing: "当前环境 {envId} 未发现静态托管资源配置,无法上传文件。请先确认 MCP 已绑定到已开通静态托管的 CloudBase 环境;如需切换环境,请调用 auth(action=\"set_env\", envId=\"目标环境ID\") 后重试。",
5810
- cloudModeLocalActionUnavailable: "manageHosting(action=\"{action}\") 在 cloud mode 下不可用,因为该操作依赖本地文件路径。请改用本地模式执行;若只需要远端管理静态托管,可继续使用 delete / setWebsiteDocument / enableService / bindDomain / unbindDomain / updateDomain。",
5971
+ cloudModeLocalActionUnavailable: "manageHosting(action=\"{action}\") 在 cloud mode 下不可用,因为该操作依赖本地文件路径。若需要部署静态站点,请改用 manageApps 云端链路:queryApps(action=\"getUploadUrl\", serviceName=\"<应用名>\") 获取预签名上传 URL → 将代码 zip PUT 上传到 uploadUrl(带 uploadHeaders 与 Content-Type: application/zip)→ manageApps(action=\"deployApp\", serviceName, cosTimestamp=<返回的 unixTimestamp>) 触发部署;若只是要上传/下载已有托管文件且无本地文件系统,该操作在云端没有替代路径,请改用本地模式执行。远端管理操作(delete / setWebsiteDocument / enableService / bindDomain / unbindDomain / updateDomain)不受影响,可继续使用。",
5811
5972
  uploadArgsRequired: "manageHosting(action=\"upload\") 需要提供 localPath + cloudPath,或提供 files 多文件上传列表。",
5812
5973
  uploadSuccess: "静态托管文件上传成功。若需要校验上传结果,请继续调用 queryHosting(action=\"findFiles\") 或 queryHosting(action=\"listFiles\")。",
5813
5974
  uploadRouteDisabledWithFallback: "静态托管文件上传成功。默认静态托管域名的网关路由已禁用(访问会返回 GATEWAY_ROUTE_DISABLED),已改用其他可达域名作为 accessUrl。可用 manageGateway(action=\"updateRoute\", route.enable=true) 重新启用默认域路由。",
@@ -5907,10 +6068,11 @@ exports.hosting = (0, types_js_1.defineModule)({
5907
6068
  queryDescription: "Read-only information about CloudBase static hosting. Lets the AI discover state first and then decide the next step: action=websiteConfig queries the index/error document, routing rules, and site domain info; action=status queries the hosting service status; action=findFiles finds files by prefix; action=listFiles lists all hosted files; action=domainStatus queries the current status and configuration of custom domains. This tool has no side effects.",
5908
6069
  manageTitle: "Manage CloudBase static hosting",
5909
6070
  manageDescription: "Mutation operations for CloudBase static hosting. action=upload uploads local build artifacts to the shared domain (domain format: <envId>-<appId>.tcloudbaseapp.com/<cloudPath>); action=delete deletes hosted files or directories (confirm=true required); action=setWebsiteDocument sets the index/error document and routing rules; action=enableService enables static hosting; action=bindDomain / unbindDomain / updateDomain manage custom domains; action=downloadFile / downloadDirectory download hosted content to local disk. ⚠️ Every hosting operation calls the DescribeStaticStore control-plane API underneath (20 req/s QPS limit): when deleting multiple files, call sequentially with intervals (no more than 10 calls per second recommended); for multiple files in the same directory, prefer isDir=true to delete the whole directory in one call. If the error contains \"frequency limit\", rate limiting was triggered — wait 1-2 seconds and retry; do not retry in rapid succession. ⚠️ This tool has no action to disable the default domain (*.tcloudbaseapp.com); to disable that default public domain, use manageGateway(action=\"disableRoute\", domain=the STATIC_STORE IsDefault domain, path=\"/\") (backed by ModifyHTTPServiceRoute, not ModifyGatewayRoute). ⚠️ For new projects prefer manageApps (deploys to a dedicated subdomain); this tool suits existing legacy projects or as a fallback for manageApps. manageApps and manageHosting use different domains, so switching invalidates old links. If the task is only inspecting config, files, or domain status, use queryHosting instead.",
6071
+ manageDescriptionCloud: "Mutation operations for CloudBase static hosting (cloud mode variant). ⚠️ Actions that depend on local file paths are unavailable in cloud mode: action=upload / downloadFile / downloadDirectory will fail immediately — do not call them. To deploy a static site, use the manageApps cloud path instead: queryApps(action=\"getUploadUrl\", serviceName=\"<app name>\") to get a presigned upload URL → PUT the code zip to uploadUrl (with uploadHeaders and Content-Type: application/zip) → manageApps(action=\"deployApp\", serviceName, cosTimestamp=<returned unixTimestamp>) to trigger deployment. Remote-only management actions remain available: action=delete deletes hosted files or directories (confirm=true required); action=setWebsiteDocument sets the index/error document and routing rules; action=enableService enables static hosting; action=bindDomain / unbindDomain / updateDomain manage custom domains. ⚠️ Every hosting operation calls the DescribeStaticStore control-plane API underneath (20 req/s QPS limit): when deleting multiple files, call sequentially with intervals (no more than 10 calls per second recommended); if the error contains \"frequency limit\", rate limiting was triggered — wait 1-2 seconds and retry. If the task is only inspecting config, files, or domain status, use queryHosting instead.",
5910
6072
  commonServiceUnsupported: "The current CloudBase Manager instance does not support commonService.call; cannot execute {action}.",
5911
6073
  managerUnavailable: "CloudBase manager is unavailable.",
5912
6074
  hostingStoreMissing: "No static hosting storage config found for environment {envId}; cannot upload files. Make sure MCP is bound to a CloudBase environment with static hosting enabled; to switch environments, call auth(action=\"set_env\", envId=\"<target env ID>\") and retry.",
5913
- cloudModeLocalActionUnavailable: "manageHosting(action=\"{action}\") is unavailable in cloud mode because the operation depends on local file paths. Run MCP in local mode instead; for remote-only static hosting management, you can still use delete / setWebsiteDocument / enableService / bindDomain / unbindDomain / updateDomain.",
6075
+ cloudModeLocalActionUnavailable: "manageHosting(action=\"{action}\") is unavailable in cloud mode because the operation depends on local file paths. To deploy a static site, use the manageApps cloud path instead: queryApps(action=\"getUploadUrl\", serviceName=\"<app name>\") to get a presigned upload URL → PUT the code zip to uploadUrl (with uploadHeaders and Content-Type: application/zip) → manageApps(action=\"deployApp\", serviceName, cosTimestamp=<returned unixTimestamp>) to trigger deployment. If you only need to upload/download existing hosted files and there is no local filesystem, there is no cloud alternative for this action — run MCP in local mode instead. Remote-only management actions (delete / setWebsiteDocument / enableService / bindDomain / unbindDomain / updateDomain) are unaffected and remain available.",
5914
6076
  uploadArgsRequired: "manageHosting(action=\"upload\") requires localPath + cloudPath, or a files list for multi-file upload.",
5915
6077
  uploadSuccess: "Static hosting files uploaded. To verify the upload result, call queryHosting(action=\"findFiles\") or queryHosting(action=\"listFiles\").",
5916
6078
  uploadRouteDisabledWithFallback: "Static hosting files uploaded. The gateway route for the default static hosting domain is disabled (access returns GATEWAY_ROUTE_DISABLED); another reachable domain is used as accessUrl. Use manageGateway(action=\"updateRoute\", route.enable=true) to re-enable the default domain route.",
@@ -6065,6 +6227,7 @@ exports.logs = (0, types_js_1.defineModule)({
6065
6227
  "\n\n**重要区分**:" +
6066
6228
  "\n- 查询云函数日志:使用 `queryFunctions(action=\"listFunctionLogs\", functionName=\"xxx\")`" +
6067
6229
  "\n- 查询 CLS 日志(跨服务日志聚合):使用本工具 `queryLogs(action=\"searchLogs\")`" +
6230
+ "\n- 开通 CLS 日志服务:使用 `manageLogs(action=\"createLogService\", confirm=true)`" +
6068
6231
  "\n\n**适用场景**:" +
6069
6232
  "\n- 检查 CLS 日志服务是否开通:`action=\"checkLogService\"`" +
6070
6233
  "\n- 跨服务日志搜索(如搜索所有 ERROR 日志):`action=\"searchLogs\"`" +
@@ -6110,12 +6273,28 @@ exports.logs = (0, types_js_1.defineModule)({
6110
6273
  "schema.limit": "返回日志条数限制,默认 20",
6111
6274
  "schema.context": "翻页上下文,用于继续上一次查询",
6112
6275
  "schema.sort": "按时间排序:`asc` 升序,`desc` 降序",
6276
+ "manage.title": "管理 CloudBase 日志服务",
6277
+ "manage.description": "CloudBase 日志域写入入口。用于开通 CLS 日志服务(对齐 Manager SDK `log.createLogService` / CreateEnvResource Resources=['log'])。" +
6278
+ "\n\n**适用场景**:" +
6279
+ "\n- 开通 CLS 日志服务:`action=\"createLogService\", confirm=true`" +
6280
+ "\n\n开通为异步操作:接口成功不代表立即可用,请随后用 `queryLogs(action=\"checkLogService\")` 轮询确认。",
6281
+ "manage.schema.action": "操作类型:" +
6282
+ "\n- `createLogService`: 开通 CLS 日志服务(需 `confirm=true`)",
6283
+ "manage.schema.confirm": "开通日志服务前的显式确认。必须传 `confirm=true`;未传时返回 CONFIRM_REQUIRED。",
6284
+ "manage.create.confirmRequired": "开通日志服务会创建 CLS 日志资源。请使用 `confirm: true` 重新执行以继续。",
6285
+ "manage.create.needsConfirmation": "开通日志服务前需要显式确认。",
6286
+ "manage.create.alreadyEnabled": "当前环境日志服务已开通,无需重复开通。",
6287
+ "manage.create.submitted": "日志服务开通请求已提交。请使用 queryLogs(action=\"checkLogService\") 轮询直至 enabled=true。",
6288
+ "manage.create.nextCheck": "轮询日志服务是否已就绪。",
6289
+ "manage.create.nextSearch": "日志服务已就绪,可开始搜索 CLS 日志。",
6290
+ "manage.unsupportedAction": "不支持的日志管理 action:{action}",
6113
6291
  }, {
6114
6292
  title: "Query CloudBase log service",
6115
6293
  description: "Unified read-only entry for the CloudBase logs domain. Supports checking log service status and searching CLS logs." +
6116
6294
  "\n\n**Important distinction**:" +
6117
6295
  "\n- Query cloud function logs: use `queryFunctions(action=\"listFunctionLogs\", functionName=\"xxx\")`" +
6118
6296
  "\n- Query CLS logs (cross-service log aggregation): use this tool `queryLogs(action=\"searchLogs\")`" +
6297
+ "\n- Enable the CLS log service: use `manageLogs(action=\"createLogService\", confirm=true)`" +
6119
6298
  "\n\n**Use cases**:" +
6120
6299
  "\n- Check whether the CLS log service is enabled: `action=\"checkLogService\"`" +
6121
6300
  "\n- Cross-service log search (e.g. find all ERROR logs): `action=\"searchLogs\"`" +
@@ -6161,6 +6340,21 @@ exports.logs = (0, types_js_1.defineModule)({
6161
6340
  "schema.limit": "Maximum number of log entries to return; defaults to 20.",
6162
6341
  "schema.context": "Pagination context used to continue the previous query.",
6163
6342
  "schema.sort": "Time sort order: `asc` for ascending or `desc` for descending.",
6343
+ "manage.title": "Manage CloudBase log service",
6344
+ "manage.description": "Write entry for the CloudBase logs domain. Enables the CLS log service (aligned with Manager SDK `log.createLogService` / CreateEnvResource Resources=['log'])." +
6345
+ "\n\n**Use cases**:" +
6346
+ "\n- Enable CLS log service: `action=\"createLogService\", confirm=true`" +
6347
+ "\n\nProvisioning is asynchronous: API success does not mean the service is immediately ready. Poll with `queryLogs(action=\"checkLogService\")` afterward.",
6348
+ "manage.schema.action": "Operation type:" +
6349
+ "\n- `createLogService`: Enable the CLS log service (requires `confirm=true`)",
6350
+ "manage.schema.confirm": "Explicit confirmation before enabling the log service. Must pass `confirm=true`; omitting it returns CONFIRM_REQUIRED.",
6351
+ "manage.create.confirmRequired": "Enabling the log service creates CLS log resources. Re-run with `confirm: true` to continue.",
6352
+ "manage.create.needsConfirmation": "Explicit confirmation is required before enabling the log service.",
6353
+ "manage.create.alreadyEnabled": "The log service is already enabled for this environment; no need to enable again.",
6354
+ "manage.create.submitted": "Log service enablement request submitted. Poll with queryLogs(action=\"checkLogService\") until enabled=true.",
6355
+ "manage.create.nextCheck": "Poll whether the log service is ready.",
6356
+ "manage.create.nextSearch": "Log service is ready; you can start searching CLS logs.",
6357
+ "manage.unsupportedAction": "Unsupported log manage action: {action}",
6164
6358
  });
6165
6359
 
6166
6360
 
@@ -6454,19 +6648,19 @@ exports.permissions = (0, types_js_1.defineModule)({
6454
6648
  "或 securityRule='{\"invoke\":true}'(放通所有云函数)。" +
6455
6649
  "底层错误:{message}",
6456
6650
  mustBeArray: "{label} 必须是数组",
6457
- roleLookupNote: "如果你需要 app-level admin override(例如 CMS 中 admin 可编辑所有文章,而 editor 只能编辑自己的文章),CUSTOM 规则通常是必要的。一个已验证可用的模式是:角色集合文档主键就是 auth.uid,并在文章权限里写 get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid。若现有 schema 已经有 users / profiles / user_roles 其一,请复用已存在且能通过 _id == auth.uid 直接 get() 到的那一份;不要把 where({ uid }) 查询得到的集合误写成 get('database.users.' + auth.uid)。",
6458
- recommendedClientWritePattern: "对于 CMS 文章这类使用 app-level admin override 的 CUSTOM 规则,前端可继续使用 db.collection('{resourceId}').doc(id).update(...) / remove(...)。关键是安全规则要采用已验证模式:get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid,并且文章文档中要真实写入 authorId。",
6651
+ roleLookupNote: "如果你需要 app-level admin override(例如 CMS 中 admin 可编辑所有文章,而 editor 只能编辑自己的文章),CUSTOM 规则通常是必要的。一个已验证可用的模式是:角色集合文档主键就是 auth.uid,并在文章权限里写 get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid。若现有 schema 已经有 users / profiles / user_roles 其一,请复用已存在且能通过 _id == auth.uid 直接 get() 到的那一份;不要把 where({ uid }) 查询得到的集合误写成 get(`database.users.${auth.uid}`)。",
6652
+ recommendedClientWritePattern: "对于 CMS 文章这类使用 app-level admin override 的 CUSTOM 规则,前端可继续使用 db.collection('{resourceId}').doc(id).update(...) / remove(...)。关键是安全规则要采用已验证模式:get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid,并且文章文档中要真实写入 authorId。",
6459
6653
  createRuleSummary: "create 规则不应引用 doc.*,因为 create 时文档尚未存在。",
6460
6654
  createRuleDetail: "CloudBase 的 create 规则验证的是写入数据(request.data),此时文档尚不存在,doc.* 不可用。" +
6461
6655
  "请将 create 规则改为仅使用 auth.* 检查(如 auth.uid != null && auth.loginType != 'ANONYMOUS')," +
6462
6656
  "或在写入时将 owner 字段(如 _openid / authorId)写入 request.data,然后在 create 规则中用 request.data._openid == auth.openid 做校验。" +
6463
6657
  "read / update / delete 规则可以使用 doc.* 引用已有文档字段,且客户端查询条件必须是规则约束的子集(如 _openid: '{openid}')。",
6464
6658
  docIdWriteSummary: "当前安全规则在 document-id 写入场景下可能被后端直接拒绝。",
6465
- docIdWriteDetail: "这类规则经常在 owner-only 集合里被写错,但对于 CMS 文章这种“admin 可编辑所有文章、editor 只能编辑自己的文章”的场景,已验证可用的做法是保留 doc.authorId,并通过独立角色集合做 admin override:get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid。不要默认改成 where(...),也不要把同集合 owner 判断重写成 get('database.collection.' + doc._id)。",
6659
+ docIdWriteDetail: "这类规则经常在 owner-only 集合里被写错,但对于 CMS 文章这种“admin 可编辑所有文章、editor 只能编辑自己的文章”的场景,已验证可用的做法是保留 doc.authorId,并通过独立角色集合做 admin override:get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid。不要默认改成 where(...),也不要把同集合 owner 判断重写成 ``get(`database.collection.${doc._id}`)``。",
6466
6660
  invalidGetPathSummary: "get() 的 path 只应包含 collection 和 documentId,不应把字段名拼进 path 字符串。",
6467
- invalidGetPathDetail: "请写成 get('database.collection.' + doc._id).fieldName,而不是 get('database.collection.' + doc._id + '.fieldName')。但在 CMS 文章权限里,不要把 get('database.collection.' + doc._id) 当成默认首选方案;更稳的已验证模式是读取单独的角色集合:get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid。",
6468
- templateLiteralSummary: "CloudBase security rule 表达式不支持把 ${...} 当作 JS 模板字符串插值。",
6469
- templateLiteralDetail: "在 securityRule 字符串里,请使用表达式拼接,例如 get('database.user_roles.' + auth.uid).role,而不是 get('database.user_roles.${auth.uid}').role。对于 CMS 文章这类需要 app-level admin override 的规则,请优先使用已验证的 user_roles + doc.authorId 模式。",
6661
+ invalidGetPathDetail: "请写成 ``get(`database.collection.${doc._id}`).fieldName``,而不是把字段名拼进 path。安全规则的表达式不支持用 + 拼接 get() 的 path 参数——形如 get('database.collection.' + doc._id) 的规则在保存时就会被判 rule invalid,请改用反引号模板字符串。但在 CMS 文章权限里,不要把同集合文档当成默认首选方案;更稳的模式是读取单独的角色集合:``get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid``。",
6662
+ templateLiteralSummary: "${...} 出现在引号字符串里也能被引擎识别,但官方形态是反引号模板字符串。",
6663
+ templateLiteralDetail: "推荐统一写成 ``get(`database.user_roles.${auth.uid}`).role == 'admin'``。真正会被拒绝的不是 ${...},而是另外两种写法:不含 ${...} 的裸引号字面量(如 get('database.admin_locks.article_lock'),请求时会返回 500),以及用 + 拼接的 get(`database.user_roles.${auth.uid}`)(保存规则时判 rule invalid)。对于 CMS 文章这类需要 app-level admin override 的规则,请优先使用 user_roles + doc.authorId 模式。",
6470
6664
  bucketMissing: "存储 Bucket {bucket} 不存在",
6471
6665
  bucketsMissing: "以下存储 Bucket 不存在: {buckets}",
6472
6666
  paramRequired: "action={action} 时必须提供 {param}",
@@ -6535,19 +6729,19 @@ exports.permissions = (0, types_js_1.defineModule)({
6535
6729
  "(package authz.user) or securityRule='{\"invoke\":true}' for public functions. " +
6536
6730
  "Underlying error: {message}",
6537
6731
  mustBeArray: "{label} must be an array",
6538
- roleLookupNote: "If you need app-level admin override (e.g. in a CMS, admins can edit all articles while editors can only edit their own), a CUSTOM rule is usually required. A verified pattern is: make the role collection's document primary key auth.uid itself, and in the article permission write get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid. If the existing schema already has users / profiles / user_roles, reuse the one that exists and can be fetched directly via _id == auth.uid with get(); do not mistakenly write the collection obtained by a where({ uid }) query as get('database.users.' + auth.uid).",
6539
- recommendedClientWritePattern: "For CMS articles using CUSTOM rules with app-level admin override, the frontend can keep using db.collection('{resourceId}').doc(id).update(...) / remove(...). The key is that the security rule uses the verified pattern: get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid, and the article document must actually contain the authorId field.",
6732
+ roleLookupNote: "If you need app-level admin override (e.g. in a CMS, admins can edit all articles while editors can only edit their own), a CUSTOM rule is usually required. A verified pattern is: make the role collection's document primary key auth.uid itself, and in the article permission write get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid. If the existing schema already has users / profiles / user_roles, reuse the one that exists and can be fetched directly via _id == auth.uid with get(); do not mistakenly write the collection obtained by a where({ uid }) query as get(`database.users.${auth.uid}`).",
6733
+ recommendedClientWritePattern: "For CMS articles using CUSTOM rules with app-level admin override, the frontend can keep using db.collection('{resourceId}').doc(id).update(...) / remove(...). The key is that the security rule uses the verified pattern: get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid, and the article document must actually contain the authorId field.",
6540
6734
  createRuleSummary: "The create rule should not reference doc.*, because the document does not exist yet at create time.",
6541
6735
  createRuleDetail: "CloudBase's create rule validates the written data (request.data); the document does not exist yet, so doc.* is unavailable. " +
6542
6736
  "Change the create rule to use only auth.* checks (e.g. auth.uid != null && auth.loginType != 'ANONYMOUS'), " +
6543
6737
  "or write the owner field (e.g. _openid / authorId) into request.data at write time, then validate with request.data._openid == auth.openid in the create rule. " +
6544
6738
  "read / update / delete rules may use doc.* to reference existing document fields, and the client's query conditions must be a subset of the rule constraints (e.g. _openid: '{openid}').",
6545
6739
  docIdWriteSummary: "The current security rule may be rejected by the backend in document-id write scenarios.",
6546
- docIdWriteDetail: "Such rules are often written incorrectly in owner-only collections, but for the CMS article scenario where \"admins can edit all articles and editors can only edit their own\", the verified approach is to keep doc.authorId and do admin override through a separate role collection: get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid. Do not default to where(...), and do not rewrite the same-collection owner check as get('database.collection.' + doc._id).",
6740
+ docIdWriteDetail: "Such rules are often written incorrectly in owner-only collections, but for the CMS article scenario where \"admins can edit all articles and editors can only edit their own\", the verified approach is to keep doc.authorId and do admin override through a separate role collection: get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid. Do not default to where(...), and do not rewrite the same-collection owner check as ``get(`database.collection.${doc._id}`)``.",
6547
6741
  invalidGetPathSummary: "The get() path should only contain the collection and documentId; do not concatenate field names into the path string.",
6548
- invalidGetPathDetail: "Write get('database.collection.' + doc._id).fieldName instead of get('database.collection.' + doc._id + '.fieldName'). However, for CMS article permissions, do not treat get('database.collection.' + doc._id) as the default first choice; the more robust verified pattern is reading a separate role collection: get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid.",
6549
- templateLiteralSummary: "CloudBase security rule expressions do not support ${...} as JS template string interpolation.",
6550
- templateLiteralDetail: "In the securityRule string, use expression concatenation, e.g. get('database.user_roles.' + auth.uid).role, instead of get('database.user_roles.${auth.uid}').role. For rules needing app-level admin override like CMS articles, prefer the verified user_roles + doc.authorId pattern.",
6742
+ invalidGetPathDetail: "Write ``get(`database.collection.${doc._id}`).fieldName`` instead of embedding the field name in the path. Security rule expressions do not support concatenating the get() path with +: a rule such as get('database.collection.' + doc._id) is rejected with rule invalid when the rule is saved, so use a backtick template literal. However, for CMS article permissions, do not treat a same-collection document as the default first choice; the more robust pattern is reading a separate role collection: ``get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid``.",
6743
+ templateLiteralSummary: "${...} inside a quoted string is understood by the engine, but the official form is a backtick template literal.",
6744
+ templateLiteralDetail: "Prefer ``get(`database.user_roles.${auth.uid}`).role == 'admin'``. What actually breaks is not ${...} but two other spellings: a bare quoted literal with no ${...} (e.g. get('database.admin_locks.article_lock'), which returns 500 at request time), and a concatenated path such as get(`database.user_roles.${auth.uid}`) (rejected with rule invalid when the rule is saved). For rules needing app-level admin override like CMS articles, prefer the user_roles + doc.authorId pattern.",
6551
6745
  bucketMissing: "Storage bucket {bucket} does not exist",
6552
6746
  bucketsMissing: "The following storage buckets do not exist: {buckets}",
6553
6747
  paramRequired: "{param} is required when action={action}",
@@ -6639,6 +6833,8 @@ exports.rag = (0, types_js_1.defineModule)({
6639
6833
  findByNameSuccess: "CloudBase 文档查找成功",
6640
6834
  readDocSuccess: "CloudBase 文档读取成功",
6641
6835
  readDocNotMarkdown: "文档 {docPath} 没有可用的 Markdown 版本(站点对该路径返回了 HTML 页面)。请用 action=searchDocs 或 action=findByName 确认正确地址后重试;也可以直接抓取网页版:{pageUrl}",
6836
+ readDocUrlNotAllowed: "readDoc 只读取 CloudBase 官方文档站({host})上的文档,不接受其他主机的地址:{docPath}。请改传站内相对路径(如 /quick-start),或该文档站上的地址。",
6837
+ readDocPathEmpty: "readDoc 需要一个具体文档路径,{docPath} 里没有路径部分。例如传 /quick-start,或传 action=findByName / action=searchDocs 返回的文档地址。",
6642
6838
  searchDocsSuccess: "CloudBase 文档搜索成功",
6643
6839
  skillNotFound: "未找到技能文档 \"{skillName}\"。可用技能文档:{available}。{remoteHint}",
6644
6840
  skillRemoteHint: " 你也可以直接从这个地址获取技能文档:{url}",
@@ -6659,7 +6855,7 @@ exports.rag = (0, types_js_1.defineModule)({
6659
6855
  "schema.action": "仅 mode=docs 时指定;mode=openapi 不要传 action。CloudBase 文档操作类型:listModules=列出所有文档模块,listModuleDocs=获取指定模块的目录结构,findByName=按名称/路径/URL 智能查找,readDoc=读取指定文档 Markdown,searchDocs=全文搜索官方文档。",
6660
6856
  "schema.moduleName": "mode=docs 且 action=listModuleDocs 时指定。模块名称。",
6661
6857
  "schema.input": "mode=docs 且 action=findByName 时指定。支持模块名、文档标题、层级路径或 URL。",
6662
- "schema.docPath": "mode=docs 且 action=readDoc 时指定。文档相对路径或完整 URL。",
6858
+ "schema.docPath": "mode=docs 且 action=readDoc 时指定。站内相对路径(如 /quick-start),或 action=findByName / action=searchDocs 返回的文档地址 —— 传地址时只取其中的路径,主机部分一律忽略。",
6663
6859
  "schema.query": "mode=docs 且 action=searchDocs 时指定。全文检索关键词。",
6664
6860
  }, {
6665
6861
  title: "CloudBase knowledge base search",
@@ -6695,6 +6891,8 @@ exports.rag = (0, types_js_1.defineModule)({
6695
6891
  findByNameSuccess: "CloudBase doc lookup succeeded",
6696
6892
  readDocSuccess: "CloudBase doc read successfully",
6697
6893
  readDocNotMarkdown: "No Markdown version is available for {docPath} (the site returned an HTML page for it). Use action=searchDocs or action=findByName to confirm the correct address and retry; you can also fetch the rendered page directly: {pageUrl}",
6894
+ readDocUrlNotAllowed: "readDoc only reads documents on the official CloudBase docs site ({host}); other hosts are not accepted: {docPath}. Pass a site-relative path such as /quick-start, or an address on that docs site.",
6895
+ readDocPathEmpty: "readDoc needs a concrete document path; {docPath} carries no path. For example pass /quick-start, or a document address returned by action=findByName / action=searchDocs.",
6698
6896
  searchDocsSuccess: "CloudBase doc search succeeded",
6699
6897
  skillNotFound: "Skill document \"{skillName}\" not found. Available skill docs: {available}.{remoteHint}",
6700
6898
  skillRemoteHint: " You can also try fetching the skill doc directly from: {url}",
@@ -6715,7 +6913,7 @@ exports.rag = (0, types_js_1.defineModule)({
6715
6913
  "schema.action": "Only for mode=docs; do not pass action with mode=openapi. CloudBase documentation action: listModules lists all documentation modules; listModuleDocs gets the catalog for a module; findByName searches intelligently by name, path, or URL; readDoc reads document Markdown; searchDocs performs a full-text search of the official documentation.",
6716
6914
  "schema.moduleName": "Required when mode=docs and action=listModuleDocs. The module name.",
6717
6915
  "schema.input": "Required when mode=docs and action=findByName. Accepts a module name, document title, hierarchical path, or URL.",
6718
- "schema.docPath": "Required when mode=docs and action=readDoc. A relative document path or full URL.",
6916
+ "schema.docPath": "Required when mode=docs and action=readDoc. A site-relative path such as /quick-start, or a document address returned by action=findByName / action=searchDocs — only the path is used; any host is ignored.",
6719
6917
  "schema.query": "Required when mode=docs and action=searchDocs. Full-text search keywords.",
6720
6918
  });
6721
6919
 
@@ -6794,6 +6992,7 @@ exports.setup = (0, types_js_1.defineModule)({
6794
6992
  "schema.template": "要下载的模板类型",
6795
6993
  "schema.ide": "指定要下载的IDE类型。",
6796
6994
  "schema.overwrite": "是否覆盖已存在的文件,默认为false(不覆盖)",
6995
+ "projectRoot.hostConfigDir": "拒绝把 {dir} 当作项目根目录。这是宿主配置目录,不是项目。请由宿主设置 WORKSPACE_FOLDER_PATHS 为项目目录后再试。",
6797
6996
  }, {
6798
6997
  "downloadTemplate.title": "Download project template",
6799
6998
  "downloadTemplate.description": "Automatically downloads and deploys CloudBase project templates.\n**Note**: Call this tool when the user requests to create a new project using a CloudBase template.\n\nSupported templates:\n- react: React + CloudBase full-stack app template\n- vue: Vue + CloudBase full-stack app template\n- miniprogram: WeChat Mini Program + CloudBase template\n- uniapp: UniApp + CloudBase cross-platform app template\n- rules: AI editor configuration files only (includes configurations for all mainstream editors such as Cursor, WindSurf, and CodeBuddy), suitable for adding AI editor configuration to an existing project\n\nSupported IDE types:\n- all: download configurations for all IDEs\n- cursor: Cursor AI editor\n- see the list below for other IDE types\n\nNote: if the ide parameter is not provided and the IDE cannot be detected from environment variables, an error will be returned asking for the ide parameter\n- windsurf: WindSurf AI editor\n- codebuddy: CodeBuddy AI editor\n- claude-code: Claude Code AI editor\n- cline: Cline AI editor\n- gemini-cli: Gemini CLI\n- opencode: OpenCode AI editor\n- qwen-code: Tongyi Lingma\n- baidu-comate: Baidu Comate\n- openai-codex-cli: OpenAI Codex CLI\n- augment-code: Augment Code\n- github-copilot: GitHub Copilot\n- roocode: RooCode AI editor\n- tongyi-lingma: Tongyi Lingma\n- trae: Trae AI editor\n- qoder: Qoder AI editor\n- antigravity: Google Antigravity AI editor\n- vscode: Visual Studio Code\n- kiro: Kiro AI editor\n- aider: Aider AI editor\n\nNotes:\n- the rules template automatically embeds the current MCP version for future maintenance and version tracking\n- when downloading the rules template, if a README.md file already exists in the project, the system protects it from being overwritten (unless overwrite=true is set)",
@@ -6858,6 +7057,7 @@ exports.setup = (0, types_js_1.defineModule)({
6858
7057
  "schema.template": "The type of template to download",
6859
7058
  "schema.ide": "The IDE type whose configuration should be downloaded.",
6860
7059
  "schema.overwrite": "Whether to overwrite existing files. Defaults to false (do not overwrite).",
7060
+ "projectRoot.hostConfigDir": "Refusing to use {dir} as the project root. That directory belongs to the host, not a project. Set WORKSPACE_FOLDER_PATHS to the project directory and retry.",
6861
7061
  });
6862
7062
 
6863
7063
 
@@ -7065,6 +7265,7 @@ const msgPush_js_1 = __webpack_require__(6191);
7065
7265
  const setup_js_1 = __webpack_require__(8707);
7066
7266
  const envSetup_js_1 = __webpack_require__(7148);
7067
7267
  const interactive_js_1 = __webpack_require__(1838);
7268
+ const feedback_js_1 = __webpack_require__(9391);
7068
7269
  exports.zh = {
7069
7270
  env: env_js_1.env.zh,
7070
7271
  storage: storage_js_1.storage.zh,
@@ -7094,6 +7295,7 @@ exports.zh = {
7094
7295
  setup: setup_js_1.setup.zh,
7095
7296
  envSetup: envSetup_js_1.envSetup.zh,
7096
7297
  interactive: interactive_js_1.interactive.zh,
7298
+ feedback: feedback_js_1.feedback.zh,
7097
7299
  };
7098
7300
 
7099
7301
 
@@ -7212,6 +7414,7 @@ const apps_js_1 = __webpack_require__(8267);
7212
7414
  const logs_js_1 = __webpack_require__(1628);
7213
7415
  const permissions_js_1 = __webpack_require__(2639);
7214
7416
  const msg_push_js_1 = __webpack_require__(7707);
7417
+ const feedback_js_1 = __webpack_require__(3951);
7215
7418
  const index_js_1 = __webpack_require__(4908);
7216
7419
  const schema_js_1 = __webpack_require__(6273);
7217
7420
  const cloud_mode_js_1 = __webpack_require__(8694);
@@ -7241,6 +7444,7 @@ const DEFAULT_PLUGINS = [
7241
7444
  "logs",
7242
7445
  "agents",
7243
7446
  "capi",
7447
+ "feedback",
7244
7448
  ];
7245
7449
  function registerDatabase(server) {
7246
7450
  // NoSQL 数据库按站点能力集合注册(国际站默认不支持 NoSQL)
@@ -7290,6 +7494,7 @@ const AVAILABLE_PLUGINS = {
7290
7494
  deploy: { name: "deploy", register: deploy_js_1.registerDeployTools },
7291
7495
  capi: { name: "capi", register: capi_js_1.registerCapiTools },
7292
7496
  "msg-push": { name: "msg-push", register: msg_push_js_1.registerMsgPushTools },
7497
+ feedback: { name: "feedback", register: feedback_js_1.registerFeedbackTools },
7293
7498
  };
7294
7499
  const PLUGIN_ALIASES = {
7295
7500
  "access-control": "permissions",
@@ -9117,6 +9322,8 @@ exports.MZ = {
9117
9322
  tag: ["2018-08-13"],
9118
9323
  billing: ["2018-07-09"],
9119
9324
  region: ["2022-06-27"],
9325
+ // 备案
9326
+ ba: ["2020-07-20"],
9120
9327
  // 计算 / 容器 / 存储
9121
9328
  cvm: ["2017-03-12"],
9122
9329
  lighthouse: ["2020-03-24"],
@@ -9772,6 +9979,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9772
9979
  Object.defineProperty(exports, "__esModule", ({ value: true }));
9773
9980
  exports.CLOUDRUN_ENV_TYPE = exports.CLOUDRUN_DEPLOY_REGISTRATION_INTERVAL_MS = exports.CLOUDRUN_DEPLOY_REGISTRATION_MAX_WAIT_MS = exports.MASKED_CLOUDRUN_ENV_VALUE = exports.CLOUDRUN_PACKAGE_TYPES = exports.CLOUDRUN_ACCESS_TYPES = exports.CLOUDRUN_SERVICE_TYPES = void 0;
9774
9981
  exports.maskCloudRunDetailEnvParams = maskCloudRunDetailEnvParams;
9982
+ exports.validateAndNormalizePath = validateAndNormalizePath;
9775
9983
  exports.resolveCloudRunProjectDir = resolveCloudRunProjectDir;
9776
9984
  exports.buildManageCloudRunErrorMessage = buildManageCloudRunErrorMessage;
9777
9985
  exports.isValidCloudRunBuildId = isValidCloudRunBuildId;
@@ -9798,6 +10006,7 @@ const zod_1 = __webpack_require__(2971);
9798
10006
  const cloudbase_manager_js_1 = __webpack_require__(3109);
9799
10007
  const index_js_1 = __webpack_require__(4908);
9800
10008
  const logger_js_1 = __webpack_require__(781);
10009
+ const project_config_js_1 = __webpack_require__(9175);
9801
10010
  const gateway_access_urls_js_1 = __webpack_require__(4173);
9802
10011
  const notification_js_1 = __webpack_require__(4718);
9803
10012
  const capi_js_1 = __webpack_require__(8900);
@@ -10002,31 +10211,20 @@ function checkIfAgentProject(projectPath) {
10002
10211
  }
10003
10212
  }
10004
10213
  /**
10005
- * Validate and normalize file path.
10006
- * Accepts absolute paths as-is; for relative paths, resolves against CWD and
10007
- * ensures the result does not escape the CWD (path-traversal protection).
10008
- * @param inputPath User provided path
10009
- * @returns Absolute path
10214
+ * Validate and normalize a file path.
10215
+ * Absolute paths are accepted as-is. Relative paths resolve against the project
10216
+ * root and must stay inside it.
10010
10217
  */
10011
10218
  function validateAndNormalizePath(inputPath) {
10012
- const normalizedPath = path_1.default.resolve(inputPath);
10013
- // On Windows, path.resolve may return a path on a different drive/UNC share.
10014
- // That is safe — the user explicitly provided an absolute path there.
10015
- // Only apply the traversal check when the resolved path shares the same root
10016
- // as CWD (i.e. the path was relative or on the same drive).
10017
- const cwd = process.cwd();
10018
- const cwdRoot = path_1.default.parse(cwd).root;
10019
- const pathRoot = path_1.default.parse(normalizedPath).root;
10020
- if (cwdRoot === pathRoot) {
10021
- // Same filesystem root — ensure the resolved path is still inside CWD
10022
- // (or is exactly CWD) to block "../" traversal.
10023
- const prefix = cwd.endsWith(path_1.default.sep) ? cwd : cwd + path_1.default.sep;
10024
- if (!normalizedPath.startsWith(prefix) && normalizedPath !== cwd) {
10025
- throw new Error((0, index_js_1.t)("cloudrun.error.pathOutsideCwd", { cwd }));
10026
- }
10027
- }
10028
- // Cross-root absolute paths (e.g. D:\ on Windows when CWD is C:\) are
10029
- // allowed — the user own the machine and the path is explicitly absolute.
10219
+ if (path_1.default.isAbsolute(inputPath)) {
10220
+ return path_1.default.resolve(inputPath);
10221
+ }
10222
+ const projectRoot = (0, project_config_js_1.requireProjectRoot)();
10223
+ const normalizedPath = path_1.default.resolve(projectRoot, inputPath);
10224
+ const prefix = projectRoot.endsWith(path_1.default.sep) ? projectRoot : projectRoot + path_1.default.sep;
10225
+ if (!normalizedPath.startsWith(prefix) && normalizedPath !== projectRoot) {
10226
+ throw new Error((0, index_js_1.t)("cloudrun.error.pathOutsideCwd", { cwd: projectRoot, resolvedPath: normalizedPath }));
10227
+ }
10030
10228
  return normalizedPath;
10031
10229
  }
10032
10230
  /**
@@ -14455,6 +14653,7 @@ const zod_1 = __webpack_require__(2971);
14455
14653
  const cloudbase_manager_js_1 = __webpack_require__(3109);
14456
14654
  const env_js_1 = __webpack_require__(6504);
14457
14655
  const index_js_1 = __webpack_require__(4908);
14656
+ const project_config_js_1 = __webpack_require__(9175);
14458
14657
  const tool_result_js_1 = __webpack_require__(9645);
14459
14658
  const sql_risk_js_1 = __webpack_require__(9885);
14460
14659
  const CATEGORY = "PostgreSQL database";
@@ -14739,19 +14938,7 @@ function validateMigrationName(name, actionLabel) {
14739
14938
  return null;
14740
14939
  }
14741
14940
  function getMigrationProjectRoot() {
14742
- const fromEnv = process.env.WORKSPACE_FOLDER_PATHS ||
14743
- process.env.PROJECT_ROOT ||
14744
- process.env.GITHUB_WORKSPACE ||
14745
- process.env.CI_PROJECT_DIR ||
14746
- process.env.BUILD_SOURCESDIRECTORY;
14747
- if (fromEnv && fromEnv.trim()) {
14748
- // IDEs may inject multiple folders separated by path.delimiter.
14749
- const first = fromEnv.split(path.delimiter).map((p) => p.trim()).find(Boolean);
14750
- if (first) {
14751
- return first;
14752
- }
14753
- }
14754
- return process.cwd();
14941
+ return (0, project_config_js_1.requireProjectRoot)();
14755
14942
  }
14756
14943
  function buildLocalMigrationFileName(version, name) {
14757
14944
  return `${version}_${name}.sql`;
@@ -17126,7 +17313,17 @@ const QUERY_ACTIONS = [
17126
17313
  "getInstanceInfo",
17127
17314
  "describeInstance",
17128
17315
  "getConnectionInfo",
17316
+ "describeInstanceSlowQueries",
17317
+ "describeInstanceErrorLogs",
17318
+ ];
17319
+ const SLOW_QUERY_ORDER_BY = [
17320
+ "QueryTime",
17321
+ "LockTime",
17322
+ "RowsExamined",
17323
+ "RowsSent",
17129
17324
  ];
17325
+ const ERROR_LOG_LEVELS = ["error", "warning", "note"];
17326
+ const ORDER_BY_TYPE = ["asc", "desc", "ASC", "DESC"];
17130
17327
  const MANAGE_ACTIONS = [
17131
17328
  "provisionMySQL",
17132
17329
  "destroyMySQL",
@@ -17633,6 +17830,138 @@ async function handleGetConnectionInfo(context) {
17633
17830
  ],
17634
17831
  });
17635
17832
  }
17833
+ function resolveMysqlInstanceId(instanceInfo, args) {
17834
+ const fromRequest = typeof args.request?.InstanceId === "string"
17835
+ ? args.request.InstanceId
17836
+ : undefined;
17837
+ const fromDbInstance = args.dbInstance?.instanceId;
17838
+ const candidate = fromRequest || fromDbInstance || instanceInfo.instanceId;
17839
+ if (!candidate || candidate === "default") {
17840
+ return null;
17841
+ }
17842
+ return candidate;
17843
+ }
17844
+ async function requireReadyMysqlInstance(args, context) {
17845
+ const instanceInfo = await getSqlInstanceInfo(context);
17846
+ if (!instanceInfo.exists) {
17847
+ return {
17848
+ ok: false,
17849
+ payload: buildSqlToolResult({
17850
+ success: false,
17851
+ errorCode: "MYSQL_NOT_CREATED",
17852
+ data: sanitizeInstanceInfo(instanceInfo),
17853
+ message: (0, index_js_1.t)("databaseSQL.instanceLogs.notProvisioned"),
17854
+ nextActions: [
17855
+ buildNextAction(MANAGE_MYSQL_DATABASE, "provisionMySQL", (0, index_js_1.t)("databaseSQL.next.provisionBeforeSql"), { action: "provisionMySQL", confirm: true }),
17856
+ ],
17857
+ }),
17858
+ };
17859
+ }
17860
+ const instanceId = resolveMysqlInstanceId(instanceInfo, args);
17861
+ if (!instanceId) {
17862
+ return {
17863
+ ok: false,
17864
+ payload: buildSqlToolResult({
17865
+ success: false,
17866
+ errorCode: "MYSQL_INSTANCE_ID_REQUIRED",
17867
+ data: sanitizeInstanceInfo(instanceInfo),
17868
+ message: (0, index_js_1.t)("databaseSQL.instanceLogs.instanceIdRequired"),
17869
+ nextActions: [
17870
+ buildNextAction(QUERY_MYSQL_DATABASE, "getInstanceInfo", (0, index_js_1.t)("databaseSQL.instanceLogs.resolveInstanceId"), { action: "getInstanceInfo" }),
17871
+ ],
17872
+ }),
17873
+ };
17874
+ }
17875
+ return { ok: true, instanceInfo, instanceId };
17876
+ }
17877
+ async function handleDescribeInstanceSlowQueries(args, context) {
17878
+ const ready = await requireReadyMysqlInstance(args, context);
17879
+ if (!ready.ok) {
17880
+ return ready.payload;
17881
+ }
17882
+ const request = args.request || {};
17883
+ const cloudbase = await context.getManager();
17884
+ const result = await cloudbase.mysql.describeInstanceSlowQueries({
17885
+ InstanceId: ready.instanceId,
17886
+ StartTime: (typeof request.StartTime === "string" ? request.StartTime : undefined) ??
17887
+ args.startTime,
17888
+ EndTime: (typeof request.EndTime === "string" ? request.EndTime : undefined) ??
17889
+ args.endTime,
17890
+ Limit: (typeof request.Limit === "number" ? request.Limit : undefined) ??
17891
+ args.limit,
17892
+ Offset: (typeof request.Offset === "number" ? request.Offset : undefined) ??
17893
+ args.offset,
17894
+ Username: (typeof request.Username === "string" ? request.Username : undefined) ??
17895
+ args.username,
17896
+ Host: (typeof request.Host === "string" ? request.Host : undefined) ??
17897
+ args.host,
17898
+ Database: (typeof request.Database === "string" ? request.Database : undefined) ??
17899
+ args.database,
17900
+ OrderBy: (typeof request.OrderBy === "string" ? request.OrderBy : undefined) ??
17901
+ args.orderBy,
17902
+ OrderByType: (typeof request.OrderByType === "string"
17903
+ ? request.OrderByType
17904
+ : undefined) ?? args.orderByType,
17905
+ SqlText: (typeof request.SqlText === "string" ? request.SqlText : undefined) ??
17906
+ args.sqlText,
17907
+ });
17908
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(context.server.logger, result);
17909
+ return buildSqlToolResult({
17910
+ success: true,
17911
+ data: {
17912
+ action: "describeInstanceSlowQueries",
17913
+ instanceId: ready.instanceId,
17914
+ totalCount: result.TotalCount ?? 0,
17915
+ slowQueries: result.SlowQueries ?? [],
17916
+ requestId: result.RequestId,
17917
+ raw: result,
17918
+ },
17919
+ message: (0, index_js_1.t)("databaseSQL.instanceLogs.slowQueriesSuccess"),
17920
+ });
17921
+ }
17922
+ async function handleDescribeInstanceErrorLogs(args, context) {
17923
+ const ready = await requireReadyMysqlInstance(args, context);
17924
+ if (!ready.ok) {
17925
+ return ready.payload;
17926
+ }
17927
+ const request = args.request || {};
17928
+ const cloudbase = await context.getManager();
17929
+ const result = await cloudbase.mysql.describeInstanceErrorLogs({
17930
+ InstanceId: ready.instanceId,
17931
+ Limit: (typeof request.Limit === "number" ? request.Limit : undefined) ??
17932
+ args.limit,
17933
+ Offset: (typeof request.Offset === "number" ? request.Offset : undefined) ??
17934
+ args.offset,
17935
+ StartTime: (typeof request.StartTime === "string" ? request.StartTime : undefined) ??
17936
+ args.startTime,
17937
+ EndTime: (typeof request.EndTime === "string" ? request.EndTime : undefined) ??
17938
+ args.endTime,
17939
+ OrderBy: (typeof request.OrderBy === "string" ? request.OrderBy : undefined) ??
17940
+ (args.orderBy === "Timestamp" ? args.orderBy : undefined),
17941
+ OrderByType: (typeof request.OrderByType === "string"
17942
+ ? request.OrderByType
17943
+ : undefined) ?? args.orderByType,
17944
+ LogLevels: (Array.isArray(request.LogLevels)
17945
+ ? request.LogLevels
17946
+ : undefined) ?? args.logLevels,
17947
+ KeyWords: (Array.isArray(request.KeyWords)
17948
+ ? request.KeyWords
17949
+ : undefined) ?? args.keyWords,
17950
+ });
17951
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(context.server.logger, result);
17952
+ return buildSqlToolResult({
17953
+ success: true,
17954
+ data: {
17955
+ action: "describeInstanceErrorLogs",
17956
+ instanceId: ready.instanceId,
17957
+ totalCount: result.TotalCount ?? 0,
17958
+ errorLogs: result.ErrorLogs ?? [],
17959
+ requestId: result.RequestId,
17960
+ raw: result,
17961
+ },
17962
+ message: (0, index_js_1.t)("databaseSQL.instanceLogs.errorLogsSuccess"),
17963
+ });
17964
+ }
17636
17965
  async function handleProvisionMySQL(args, context) {
17637
17966
  if (args.confirm !== true) {
17638
17967
  return buildSqlToolResult({
@@ -18003,6 +18332,54 @@ function registerSQLDatabaseTools(server) {
18003
18332
  })
18004
18333
  .optional()
18005
18334
  .describe("databaseSQL.schema.query.dbInstance"),
18335
+ startTime: zod_1.z
18336
+ .string()
18337
+ .optional()
18338
+ .describe("databaseSQL.schema.query.startTime"),
18339
+ endTime: zod_1.z
18340
+ .string()
18341
+ .optional()
18342
+ .describe("databaseSQL.schema.query.endTime"),
18343
+ limit: zod_1.z
18344
+ .number()
18345
+ .optional()
18346
+ .describe("databaseSQL.schema.query.limit"),
18347
+ offset: zod_1.z
18348
+ .number()
18349
+ .optional()
18350
+ .describe("databaseSQL.schema.query.offset"),
18351
+ username: zod_1.z
18352
+ .string()
18353
+ .optional()
18354
+ .describe("databaseSQL.schema.query.username"),
18355
+ host: zod_1.z
18356
+ .string()
18357
+ .optional()
18358
+ .describe("databaseSQL.schema.query.host"),
18359
+ database: zod_1.z
18360
+ .string()
18361
+ .optional()
18362
+ .describe("databaseSQL.schema.query.database"),
18363
+ orderBy: zod_1.z
18364
+ .enum([...SLOW_QUERY_ORDER_BY, "Timestamp"])
18365
+ .optional()
18366
+ .describe("databaseSQL.schema.query.orderBy"),
18367
+ orderByType: zod_1.z
18368
+ .enum(ORDER_BY_TYPE)
18369
+ .optional()
18370
+ .describe("databaseSQL.schema.query.orderByType"),
18371
+ sqlText: zod_1.z
18372
+ .string()
18373
+ .optional()
18374
+ .describe("databaseSQL.schema.query.sqlText"),
18375
+ logLevels: zod_1.z
18376
+ .array(zod_1.z.enum(ERROR_LOG_LEVELS))
18377
+ .optional()
18378
+ .describe("databaseSQL.schema.query.logLevels"),
18379
+ keyWords: zod_1.z
18380
+ .array(zod_1.z.string())
18381
+ .optional()
18382
+ .describe("databaseSQL.schema.query.keyWords"),
18006
18383
  },
18007
18384
  annotations: {
18008
18385
  readOnlyHint: true,
@@ -18026,6 +18403,10 @@ function registerSQLDatabaseTools(server) {
18026
18403
  return handleGetInstanceInfo(context);
18027
18404
  case "getConnectionInfo":
18028
18405
  return handleGetConnectionInfo(context);
18406
+ case "describeInstanceSlowQueries":
18407
+ return handleDescribeInstanceSlowQueries(args, context);
18408
+ case "describeInstanceErrorLogs":
18409
+ return handleDescribeInstanceErrorLogs(args, context);
18029
18410
  default:
18030
18411
  throw new Error((0, index_js_1.t)("databaseSQL.unsupportedQueryAction", { action: args.action }));
18031
18412
  }
@@ -18122,6 +18503,7 @@ const zod_1 = __webpack_require__(2971);
18122
18503
  const cloudbase_manager_js_1 = __webpack_require__(3109);
18123
18504
  const index_js_1 = __webpack_require__(4908);
18124
18505
  const json_content_js_1 = __webpack_require__(8027);
18506
+ const project_config_js_1 = __webpack_require__(9175);
18125
18507
  const sql_risk_js_1 = __webpack_require__(9885);
18126
18508
  const hosting_build_utils_js_1 = __webpack_require__(7572);
18127
18509
  // 声明式部署可编排的资源类型,与 DeployOrchestrator 的部署顺序一致:
@@ -18386,7 +18768,7 @@ function registerDeployTools(server) {
18386
18768
  },
18387
18769
  }, async ({ cwd, mode }) => {
18388
18770
  try {
18389
- const projectRoot = cwd ?? process.cwd();
18771
+ const projectRoot = (0, project_config_js_1.requireProjectRoot)(cwd);
18390
18772
  const config = await resolveDeployConfig({ cwd: projectRoot, mode });
18391
18773
  assertConfigValid(config);
18392
18774
  const hostingItems = Array.isArray(config.hosting)
@@ -18458,7 +18840,7 @@ function registerDeployTools(server) {
18458
18840
  },
18459
18841
  }, async ({ cwd, mode, envId: envIdInput, only, skip, yes, }) => {
18460
18842
  try {
18461
- const projectRoot = cwd ?? process.cwd();
18843
+ const projectRoot = (0, project_config_js_1.requireProjectRoot)(cwd);
18462
18844
  const config = await resolveDeployConfig({ cwd: projectRoot, mode });
18463
18845
  assertConfigValid(config);
18464
18846
  const envId = await resolveDeployEnvId({
@@ -18542,7 +18924,7 @@ function registerDeployTools(server) {
18542
18924
  if (confirm !== true) {
18543
18925
  throw new DeployError(exports.DEPLOY_ERROR_CODES.CONFIRM_REQUIRED, (0, index_js_1.t)("deploy.confirmRequired"));
18544
18926
  }
18545
- const projectRoot = cwd ?? process.cwd();
18927
+ const projectRoot = (0, project_config_js_1.requireProjectRoot)(cwd);
18546
18928
  const config = await resolveDeployConfig({ cwd: projectRoot, mode });
18547
18929
  assertConfigValid(config);
18548
18930
  const envId = await resolveDeployEnvId({
@@ -22478,6 +22860,507 @@ function registerEnvTools(server) {
22478
22860
  }
22479
22861
 
22480
22862
 
22863
+ /***/ },
22864
+
22865
+ /***/ 3951
22866
+ (__unused_webpack_module, exports, __webpack_require__) {
22867
+
22868
+ var __webpack_unused_export__;
22869
+
22870
+ __webpack_unused_export__ = ({ value: true });
22871
+ exports.bE = exports.NC = exports.RS = void 0;
22872
+ __webpack_unused_export__ = resolveMcpVersion;
22873
+ __webpack_unused_export__ = buildFeedbackIssueUrl;
22874
+ __webpack_unused_export__ = buildFeedbackIssueLink;
22875
+ __webpack_unused_export__ = buildFeedbackPayload;
22876
+ exports.registerFeedbackTools = registerFeedbackTools;
22877
+ const zod_1 = __webpack_require__(2971);
22878
+ const feedback_session_js_1 = __webpack_require__(3379);
22879
+ const json_content_js_1 = __webpack_require__(8027);
22880
+ const site_map_js_1 = __webpack_require__(4533);
22881
+ /**
22882
+ * Not a CloudBase resource, so this does not use the query* / manage* pair.
22883
+ * The feedback plugin is in the default set and always registers this tool.
22884
+ */
22885
+ exports.RS = "prepareFeedback";
22886
+ const CASE_TEMPLATE_FILE = "1-case-showcase.yml";
22887
+ const RETROSPECTIVE_TEMPLATE_FILE = "2-dev-retrospective.yml";
22888
+ /** Fixed new-issue pages. Intl uses GitHub. Domestic uses the CNB CloudBase-AI-ToolKit repo. */
22889
+ exports.NC = {
22890
+ intl: "https://github.com/TencentCloudBase/CloudBase-AI-ToolKit/issues/new",
22891
+ domestic: "https://cnb.cool/tencent/cloud/cloudbase/CloudBase-AI-ToolKit/-/issues/new",
22892
+ };
22893
+ const RESOURCE_BY_TOOL = {
22894
+ queryHosting: { zh: "静态托管", en: "Static hosting" },
22895
+ manageHosting: { zh: "静态托管", en: "Static hosting" },
22896
+ readNoSqlDatabaseStructure: { zh: "云数据库(文档型)", en: "Document database" },
22897
+ writeNoSqlDatabaseStructure: { zh: "云数据库(文档型)", en: "Document database" },
22898
+ readNoSqlDatabaseContent: { zh: "云数据库(文档型)", en: "Document database" },
22899
+ writeNoSqlDatabaseContent: { zh: "云数据库(文档型)", en: "Document database" },
22900
+ queryMysqlDatabase: { zh: "云数据库(MySQL)", en: "MySQL" },
22901
+ manageMysqlDatabase: { zh: "云数据库(MySQL)", en: "MySQL" },
22902
+ queryPgDatabase: { zh: "云数据库(PostgreSQL)", en: "PostgreSQL" },
22903
+ managePgDatabase: { zh: "云数据库(PostgreSQL)", en: "PostgreSQL" },
22904
+ queryFunctions: { zh: "云函数", en: "Cloud functions" },
22905
+ manageFunctions: { zh: "云函数", en: "Cloud functions" },
22906
+ queryStorage: { zh: "云存储", en: "Cloud storage" },
22907
+ manageStorage: { zh: "云存储", en: "Cloud storage" },
22908
+ queryPgStorage: { zh: "云存储", en: "Cloud storage" },
22909
+ queryAppAuth: { zh: "身份认证", en: "Auth" },
22910
+ manageAppAuth: { zh: "身份认证", en: "Auth" },
22911
+ queryCloudRun: { zh: "CloudRun", en: "CloudRun" },
22912
+ manageCloudRun: { zh: "CloudRun", en: "CloudRun" },
22913
+ };
22914
+ /** Stay under common browser and proxy URL limits. Longer drafts are pasted by the user. */
22915
+ exports.bE = 6000;
22916
+ function resolveMcpVersion(declared, packageVersion) {
22917
+ const fromBuild = typeof declared === "string" ? declared.trim() : "";
22918
+ if (fromBuild) {
22919
+ return fromBuild;
22920
+ }
22921
+ const fromPackage = typeof packageVersion === "string" ? packageVersion.trim() : "";
22922
+ return fromPackage;
22923
+ }
22924
+ function readDeclaredMcpVersion() {
22925
+ return true ? "2.34.7" : 0;
22926
+ }
22927
+ function blank(value, lang) {
22928
+ return value.trim().length > 0 ? value.trim() : (lang === "en" ? "blank" : "留空");
22929
+ }
22930
+ function feedbackSite(server) {
22931
+ return (0, site_map_js_1.resolveSiteAndRegion)({
22932
+ site: server.cloudBaseOptions?.site,
22933
+ region: server.cloudBaseOptions?.region,
22934
+ }).site;
22935
+ }
22936
+ function feedbackLang(site) {
22937
+ return site === "intl" ? "en" : "zh";
22938
+ }
22939
+ function uniqueJoin(parts) {
22940
+ const seen = new Set();
22941
+ const ordered = [];
22942
+ for (const part of parts) {
22943
+ const trimmed = part.trim();
22944
+ if (!trimmed || seen.has(trimmed)) {
22945
+ continue;
22946
+ }
22947
+ seen.add(trimmed);
22948
+ ordered.push(trimmed);
22949
+ }
22950
+ return ordered.join(" / ");
22951
+ }
22952
+ function readAgentLabel(server) {
22953
+ const ide = server.ide || process.env.INTEGRATION_IDE || "";
22954
+ const client = server.client || process.env.CLOUDBASE_MCP_CLIENT || "";
22955
+ return uniqueJoin([ide, client]);
22956
+ }
22957
+ function toLocalIso(iso) {
22958
+ const date = new Date(iso);
22959
+ if (Number.isNaN(date.getTime())) {
22960
+ return "";
22961
+ }
22962
+ const pad = (value) => String(value).padStart(2, "0");
22963
+ const offsetMinutes = -date.getTimezoneOffset();
22964
+ const sign = offsetMinutes >= 0 ? "+" : "-";
22965
+ const absolute = Math.abs(offsetMinutes);
22966
+ return (`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` +
22967
+ `T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` +
22968
+ `${sign}${pad(Math.floor(absolute / 60))}:${pad(absolute % 60)}`);
22969
+ }
22970
+ function resourceTypesFrom(outcomes, lang) {
22971
+ const seen = new Set();
22972
+ const types = [];
22973
+ for (const outcome of outcomes) {
22974
+ if (outcome.failed) {
22975
+ continue;
22976
+ }
22977
+ const resourceType = RESOURCE_BY_TOOL[outcome.toolName]?.[lang];
22978
+ if (!resourceType || seen.has(resourceType)) {
22979
+ continue;
22980
+ }
22981
+ seen.add(resourceType);
22982
+ types.push(resourceType);
22983
+ }
22984
+ return types;
22985
+ }
22986
+ function formatDeployDuration(outcomes, lang) {
22987
+ const build = outcomes.filter((item) => !item.failed && item.toolName === "deployBuild");
22988
+ const apply = outcomes.filter((item) => !item.failed && item.toolName === "deployApply");
22989
+ if (build.length === 0 && apply.length === 0) {
22990
+ return "";
22991
+ }
22992
+ const sum = (items) => items.reduce((total, item) => total + item.durationMs, 0);
22993
+ const parts = [];
22994
+ if (build.length > 0) {
22995
+ parts.push(`deployBuild ${sum(build)}ms`);
22996
+ }
22997
+ if (apply.length > 0) {
22998
+ parts.push(`deployApply ${sum(apply)}ms`);
22999
+ }
23000
+ const joined = parts.join(lang === "en" ? "; " : ";");
23001
+ return lang === "en"
23002
+ ? `${joined}. Cloud build time and end-to-end time cannot be separated from these tool names.`
23003
+ : `${joined}。无法区分云端构建与端到端,只记录上述工具耗时,未补另一项`;
23004
+ }
23005
+ function latestDeployTime(outcomes) {
23006
+ const deployOutcomes = outcomes.filter((item) => !item.failed && (item.toolName === "deployBuild" || item.toolName === "deployApply"));
23007
+ if (deployOutcomes.length === 0) {
23008
+ return "";
23009
+ }
23010
+ const latest = deployOutcomes.reduce((current, item) => (item.at > current.at ? item : current));
23011
+ return toLocalIso(latest.at);
23012
+ }
23013
+ function failureLines(server, outcomes, lang) {
23014
+ const counts = new Map();
23015
+ for (const outcome of outcomes) {
23016
+ if (!outcome.failed) {
23017
+ continue;
23018
+ }
23019
+ counts.set(outcome.toolName, (counts.get(outcome.toolName) ?? 0) + 1);
23020
+ }
23021
+ const lines = [];
23022
+ for (const [toolName, count] of counts) {
23023
+ lines.push(lang === "en"
23024
+ ? `- Verified: tool call failed ${toolName} ×${count}`
23025
+ : `- 可验证事实:工具调用失败 ${toolName} ×${count}`);
23026
+ }
23027
+ const repeatPeak = (0, feedback_session_js_1.readRepeatPeak)(server);
23028
+ if (repeatPeak > 0) {
23029
+ lines.push(lang === "en"
23030
+ ? `- Verified: peak consecutive identical structured errors ${repeatPeak}`
23031
+ : `- 可验证事实:连续相同结构化错误峰值 ${repeatPeak}`);
23032
+ }
23033
+ return lines;
23034
+ }
23035
+ function collectSecretValues(server) {
23036
+ const options = server.cloudBaseOptions;
23037
+ return [options?.envId, options?.secretId, options?.secretKey, options?.token].filter((value) => typeof value === "string" && value.trim().length >= 6);
23038
+ }
23039
+ function redact(text, secrets) {
23040
+ let redacted = text;
23041
+ for (const secret of secrets) {
23042
+ redacted = redacted.split(secret).join("");
23043
+ }
23044
+ return redacted;
23045
+ }
23046
+ function buildCaseDraft(server, outcomes, lang) {
23047
+ const resources = resourceTypesFrom(outcomes, lang);
23048
+ const empty = blank("", lang);
23049
+ const resourceText = resources.length > 0 ? resources.join(lang === "en" ? ", " : "、") : empty;
23050
+ const version = blank(resolveMcpVersion(readDeclaredMcpVersion(), process.env.npm_package_version), lang);
23051
+ if (lang === "en") {
23052
+ return [
23053
+ "This issue will be public. Do not add an environment ID, secrets, or user data.",
23054
+ `Work name: ${empty}`,
23055
+ `One-line summary: ${empty}`,
23056
+ `Public URL: ${empty}`,
23057
+ `Cover / screenshot: ${empty}`,
23058
+ `Agent / CLI: ${blank(readAgentLabel(server), lang)}`,
23059
+ `Model: ${empty}`,
23060
+ `MCP version: ${version}`,
23061
+ `Deploy duration: ${blank(formatDeployDuration(outcomes, lang), lang)}`,
23062
+ `Cloud resources: ${resourceText}`,
23063
+ `Deploy time: ${blank(latestDeployTime(outcomes), lang)}`,
23064
+ `Author: ${empty}`,
23065
+ `Pitfalls: ${empty}`,
23066
+ `Other notes: ${empty}`,
23067
+ ].join("\n");
23068
+ }
23069
+ return [
23070
+ "这条 Issue 会公开。不要补充环境 ID、密钥或用户数据。",
23071
+ `作品名称:${empty}`,
23072
+ `一句话简介:${empty}`,
23073
+ `公网访问地址:${empty}`,
23074
+ `封面 / 截图地址:${empty}`,
23075
+ `Agent / CLI:${blank(readAgentLabel(server), lang)}`,
23076
+ `所用模型:${empty}`,
23077
+ `MCP 版本:${version}`,
23078
+ `部署耗时:${blank(formatDeployDuration(outcomes, lang), lang)}`,
23079
+ `用到的云资源:${resourceText}`,
23080
+ `部署时间:${blank(latestDeployTime(outcomes), lang)}`,
23081
+ `作者署名 / 主页:${empty}`,
23082
+ `开发过程中踩到的坑:${empty}`,
23083
+ `其他补充:${empty}`,
23084
+ ].join("\n");
23085
+ }
23086
+ function buildRetrospectiveDraft(server, outcomes, lang) {
23087
+ const resources = resourceTypesFrom(outcomes, lang);
23088
+ const failures = failureLines(server, outcomes, lang);
23089
+ const empty = blank("", lang);
23090
+ if (lang === "en") {
23091
+ const failureBlock = failures.length > 0
23092
+ ? failures.join("\n")
23093
+ : "No tool failures recorded in this session.";
23094
+ const resourceBlock = resources.length > 0
23095
+ ? resources.join(", ")
23096
+ : empty;
23097
+ return [
23098
+ "This issue will be public. Do not add an environment ID, secrets, collection names, or function names.",
23099
+ "Conversation turns are not collected. Do not invent a turn count.",
23100
+ "",
23101
+ "Tool failures:",
23102
+ failureBlock,
23103
+ "",
23104
+ "Cloud resources:",
23105
+ resourceBlock,
23106
+ ].join("\n");
23107
+ }
23108
+ const failureBlock = failures.length > 0
23109
+ ? failures.join("\n")
23110
+ : "本次会话没有记录到工具失败。";
23111
+ const resourceBlock = resources.length > 0
23112
+ ? resources.join("、")
23113
+ : empty;
23114
+ return [
23115
+ "这条 Issue 会公开。不要补充环境 ID、密钥、集合名或函数名。",
23116
+ "不采集对话轮次。不要把失败次数写成轮次,也不要补一个数字。",
23117
+ "",
23118
+ "工具失败:",
23119
+ failureBlock,
23120
+ "",
23121
+ "云资源:",
23122
+ resourceBlock,
23123
+ ].join("\n");
23124
+ }
23125
+ function buildFeedbackIssueUrl(site, channel, draft) {
23126
+ return buildFeedbackIssueLink(site, channel, draft).url;
23127
+ }
23128
+ function buildFeedbackIssueLink(site, channel, draft) {
23129
+ const title = site === "intl"
23130
+ ? (channel === "case" ? "[case] " : "[retrospective] ")
23131
+ : (channel === "case" ? "[案例] " : "[复盘] ");
23132
+ const base = exports.NC[site];
23133
+ const draftQuery = site === "intl"
23134
+ ? `body=${encodeURIComponent(draft)}`
23135
+ : `session=${encodeURIComponent(draft)}`;
23136
+ const head = site === "intl"
23137
+ ? `${base}?title=${encodeURIComponent(title)}`
23138
+ : `${base}?template=${encodeURIComponent(channel === "case" ? CASE_TEMPLATE_FILE : RETROSPECTIVE_TEMPLATE_FILE)}&title=${encodeURIComponent(title)}`;
23139
+ const prefilled = `${head}&${draftQuery}`;
23140
+ if (prefilled.length <= exports.bE) {
23141
+ return { url: prefilled, prefilled: true };
23142
+ }
23143
+ return { url: head, prefilled: false };
23144
+ }
23145
+ function buildFeedbackPayload(input) {
23146
+ const site = feedbackSite(input.server);
23147
+ const lang = feedbackLang(site);
23148
+ const outcomes = (0, feedback_session_js_1.readToolOutcomes)(input.server);
23149
+ const secrets = collectSecretValues(input.server);
23150
+ const draft = redact(input.channel === "case"
23151
+ ? buildCaseDraft(input.server, outcomes, lang)
23152
+ : buildRetrospectiveDraft(input.server, outcomes, lang), secrets);
23153
+ if (!input.confirmed) {
23154
+ return {
23155
+ success: true,
23156
+ channel: input.channel,
23157
+ confirmed: false,
23158
+ submittable: false,
23159
+ draft,
23160
+ nextStep: lang === "en"
23161
+ ? "Show this draft to the user unchanged. Do not give a submission link before they explicitly confirm. Do not rewrite it into a different write-up."
23162
+ : "把这份 draft 原样给用户看。用户明确确认之前,不要给出提交链接,也不要改写成另一份说明。",
23163
+ };
23164
+ }
23165
+ const link = buildFeedbackIssueLink(site, input.channel, draft);
23166
+ const pasteHint = link.prefilled
23167
+ ? ""
23168
+ : (lang === "en"
23169
+ ? " The link does not include the draft because the URL would be too long. Paste the draft into the session field."
23170
+ : " 链接没有带上正文,因为地址过长。请把 draft 粘贴到「本次会话记录」。");
23171
+ return {
23172
+ success: true,
23173
+ channel: input.channel,
23174
+ confirmed: true,
23175
+ submittable: true,
23176
+ draft,
23177
+ url: link.url,
23178
+ nextStep: (lang === "en"
23179
+ ? "The user confirmed. The link body is this draft. Do not submit a rewritten version, and do not submit it for them."
23180
+ : "用户已确认。链接里的正文就是这份 draft。不要另写一版再提交,也不要代为提交。") + pasteHint,
23181
+ };
23182
+ }
23183
+ function registerFeedbackTools(server) {
23184
+ server.registerTool(exports.RS, {
23185
+ title: "feedback.title",
23186
+ description: "feedback.description",
23187
+ inputSchema: {
23188
+ channel: zod_1.z
23189
+ .enum(["case", "retrospective"])
23190
+ .describe("feedback.schema.channel"),
23191
+ confirmed: zod_1.z
23192
+ .boolean()
23193
+ .optional()
23194
+ .describe("feedback.schema.confirmed"),
23195
+ },
23196
+ annotations: {
23197
+ readOnlyHint: true,
23198
+ destructiveHint: false,
23199
+ openWorldHint: false,
23200
+ category: "feedback",
23201
+ },
23202
+ }, async ({ channel, confirmed }) => {
23203
+ return (0, json_content_js_1.jsonContent)(buildFeedbackPayload({
23204
+ server,
23205
+ channel,
23206
+ confirmed: confirmed === true,
23207
+ }));
23208
+ });
23209
+ }
23210
+
23211
+
23212
+ /***/ },
23213
+
23214
+ /***/ 5735
23215
+ (__unused_webpack_module, exports, __webpack_require__) {
23216
+
23217
+ var __webpack_unused_export__;
23218
+
23219
+ /**
23220
+ * 云函数 ZIP 两段式部署·阶段 A:生成 COS 预签名上传地址。
23221
+ *
23222
+ * 通道来源(R1 探针实测裁决,见 output/2026-09-23-functions-zip-two-phase-design.md §4):
23223
+ * - DescribeBuildServiceCosInfo / build-service 上传 / GetTempCosInfo 三条通道全部判死
23224
+ * (CosTimestamp 稳定 InternalError;SCF 拉代码强制给桶名拼 -appid 后缀,共享 build 桶
23225
+ * 永远拉不到;tempcos 桶全 region 404)。
23226
+ * - 活通道:用环境自有存储桶(DescribeEnvs → Storages[0].Bucket/Region)+ 用户凭据
23227
+ * 本地铸 COS q-sign 预签名 PUT URL。CloudBase 临时凭据可直接用于 COS(manager-node
23228
+ * storage 同款 SecretId+SecretKey+token 范式),但必须把 x-cos-security-token 纳入
23229
+ * 签名 Headers 且请求时携带同名头。
23230
+ *
23231
+ * 设计约束:
23232
+ * - 纯函数、零第三方依赖(node:crypto 即可):签名算法从 cos-nodejs-sdk-v5 getAuth
23233
+ * 逐行复刻,测试里与 SDK 真实现做黄金值对照,防止复刻漂移。
23234
+ * - 预签名是本地 HMAC 计算:CAM 零新增权限、不暴露 appId(URL 用全桶名,阶段 B 回传
23235
+ * TCB 的 CosBucketName 用短名)、国际站天然可用。
23236
+ */
23237
+ __webpack_unused_export__ = ({ value: true });
23238
+ exports.stripAppIdSuffix = stripAppIdSuffix;
23239
+ __webpack_unused_export__ = camSafeUrlEncode;
23240
+ __webpack_unused_export__ = buildCosPutAuthorization;
23241
+ exports.buildFunctionZipUpload = buildFunctionZipUpload;
23242
+ const crypto_1 = __webpack_require__(7823);
23243
+ /** 环境存储桶全名形如 `mybucket-1258016615`;TCB CosBucketName 只收短名(不带 -appid 后缀)。 */
23244
+ function stripAppIdSuffix(bucket) {
23245
+ return bucket.replace(/-\d+$/, "");
23246
+ }
23247
+ /** 复刻 cos-nodejs-sdk-v5 util.camSafeUrlEncode:encodeURIComponent 强制编码 !'()* 五个字符。 */
23248
+ function camSafeUrlEncode(str) {
23249
+ return encodeURIComponent(str)
23250
+ .replace(/!/g, "%21")
23251
+ .replace(/'/g, "%27")
23252
+ .replace(/\(/g, "%28")
23253
+ .replace(/\)/g, "%29")
23254
+ .replace(/\*/g, "%2A");
23255
+ }
23256
+ /** 复刻 SDK getObjectKeys:原始 key 按小写比较排序(排序在编码之前)。 */
23257
+ function sortedKeys(obj) {
23258
+ return Object.keys(obj).sort((a, b) => {
23259
+ a = a.toLowerCase();
23260
+ b = b.toLowerCase();
23261
+ return a === b ? 0 : a > b ? 1 : -1;
23262
+ });
23263
+ }
23264
+ /** 复刻 SDK obj2str(obj, true):key 编码后小写、value 编码,按 key 升序以 & 连接。 */
23265
+ function encodeKv(obj) {
23266
+ return sortedKeys(obj)
23267
+ .map((key) => {
23268
+ const k = camSafeUrlEncode(key).toLowerCase();
23269
+ const v = camSafeUrlEncode(obj[key] ?? "");
23270
+ return `${k}=${v}`;
23271
+ })
23272
+ .join("&");
23273
+ }
23274
+ /**
23275
+ * 生成 COS q-sign 预签名授权串(PUT 方法)。
23276
+ * 算法逐行复刻 cos-nodejs-sdk-v5 getAuth:
23277
+ * signKey = HMAC-SHA1(SecretKey, KeyTime)
23278
+ * formatString = method \n pathname \n query-str \n header-str \n
23279
+ * stringToSign = sha1 \n KeyTime \n sha1(formatString) \n
23280
+ * signature = HMAC-SHA1(signKey, stringToSign)
23281
+ * Host 头始终签入(对齐 SDK ForceSignHost 默认 true),query 为空故 q-url-param-list 为空。
23282
+ */
23283
+ function buildCosPutAuthorization(options) {
23284
+ const { secretId, secretKey, bucket, region, objectKey, securityToken, expiresInSeconds = 3600, } = options;
23285
+ if (!secretId)
23286
+ throw new Error("missing param SecretId");
23287
+ if (!secretKey)
23288
+ throw new Error("missing param SecretKey");
23289
+ if (!bucket)
23290
+ throw new Error("missing param Bucket");
23291
+ if (!region)
23292
+ throw new Error("missing param Region");
23293
+ if (!objectKey)
23294
+ throw new Error("missing param objectKey");
23295
+ const headers = {
23296
+ host: `${bucket}.cos.${region}.myqcloud.com`,
23297
+ };
23298
+ if (securityToken) {
23299
+ headers["x-cos-security-token"] = securityToken;
23300
+ }
23301
+ const keyTime = options.keyTime ??
23302
+ (() => {
23303
+ const now = options.now ?? Math.floor(Date.now() / 1000);
23304
+ return `${now - 1};${now + expiresInSeconds}`;
23305
+ })();
23306
+ // 与请求 URL 一致的编码路径(对象 key 仅允许安全字符时与原始 key 相同)。
23307
+ const pathname = `/${objectKey.split("/").map(encodeURIComponent).join("/")}`;
23308
+ const signKey = (0, crypto_1.createHmac)("sha1", secretKey).update(keyTime).digest("hex");
23309
+ const formatString = ["put", pathname, "", encodeKv(headers), ""].join("\n");
23310
+ const stringToSign = [
23311
+ "sha1",
23312
+ keyTime,
23313
+ (0, crypto_1.createHash)("sha1").update(Buffer.from(formatString, "utf8")).digest("hex"),
23314
+ "",
23315
+ ].join("\n");
23316
+ const signature = (0, crypto_1.createHmac)("sha1", signKey).update(stringToSign).digest("hex");
23317
+ const headerList = sortedKeys(headers)
23318
+ .map((key) => camSafeUrlEncode(key).toLowerCase())
23319
+ .join(";");
23320
+ return [
23321
+ "q-sign-algorithm=sha1",
23322
+ `q-ak=${secretId}`,
23323
+ `q-sign-time=${keyTime}`,
23324
+ `q-key-time=${keyTime}`,
23325
+ `q-header-list=${headerList}`,
23326
+ "q-url-param-list=",
23327
+ `q-signature=${signature}`,
23328
+ ].join("&");
23329
+ }
23330
+ /**
23331
+ * 生成两段式部署阶段 A 的完整返回体:预签名 PUT URL + 阶段 B 所需的 COS 三元组。
23332
+ * 对象 key 形如 `fnzip-upload/{ts}-{rand}/{functionName|code}.zip`,全部为 COS 签名
23333
+ * 安全字符(字母数字与 -_. /),保证签名 pathname 与请求 URL 一致。
23334
+ */
23335
+ function buildFunctionZipUpload(params) {
23336
+ const { storage, credential, functionName } = params;
23337
+ const expiresIn = params.expiresIn ?? 3600;
23338
+ const ts = params.now ?? Math.floor(Date.now() / 1000);
23339
+ const rand = params.randomSuffix ?? (0, crypto_1.randomBytes)(8).toString("hex");
23340
+ const objectKey = `fnzip-upload/${ts}-${rand}/${functionName || "code"}.zip`;
23341
+ const keyTime = params.keyTime ?? `${ts - 1};${ts + expiresIn}`;
23342
+ const authorization = buildCosPutAuthorization({
23343
+ secretId: credential.secretId,
23344
+ secretKey: credential.secretKey,
23345
+ bucket: storage.bucket,
23346
+ region: storage.region,
23347
+ objectKey,
23348
+ securityToken: credential.token || undefined,
23349
+ keyTime,
23350
+ });
23351
+ return {
23352
+ uploadUrl: `https://${storage.bucket}.cos.${storage.region}.myqcloud.com/${objectKey}?${authorization}`,
23353
+ uploadHeaders: credential.token
23354
+ ? [{ Key: "x-cos-security-token", Value: credential.token }]
23355
+ : [],
23356
+ cosBucketName: stripAppIdSuffix(storage.bucket),
23357
+ cosBucketRegion: storage.region,
23358
+ cosObjectName: objectKey,
23359
+ expiresInSeconds: expiresIn,
23360
+ };
23361
+ }
23362
+
23363
+
22481
23364
  /***/ },
22482
23365
 
22483
23366
  /***/ 4931
@@ -23844,7 +24727,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
23844
24727
  return (mod && mod.__esModule) ? mod : { "default": mod };
23845
24728
  };
23846
24729
  Object.defineProperty(exports, "__esModule", ({ value: true }));
23847
- exports.CUSTOM_IMAGE_RUNTIME = exports.MASKED_ENV_VALUE = exports.LAYER_SOFT_WARN = exports.MANAGE_FUNCTION_ACTIONS = exports.QUERY_FUNCTION_ACTIONS = exports.TRIGGER_CONFIG_EXAMPLES = exports.SUPPORTED_TRIGGER_TYPES = exports.DEFAULT_NODEJS_RUNTIME = exports.SUPPORTED_NODEJS_RUNTIMES = exports.RECOMMENDED_RUNTIMES = exports.DEFAULT_RUNTIME = exports.ALL_SUPPORTED_RUNTIMES = exports.SUPPORTED_RUNTIMES = void 0;
24730
+ exports.CUSTOM_IMAGE_RUNTIME = exports.MASKED_ENV_VALUE = exports.LAYER_SOFT_WARN = exports.DEFAULT_FUNCTION_ALIAS = exports.MANAGE_FUNCTION_ACTIONS = exports.QUERY_FUNCTION_ACTIONS = exports.TRIGGER_CONFIG_EXAMPLES = exports.SUPPORTED_TRIGGER_TYPES = exports.DEFAULT_NODEJS_RUNTIME = exports.SUPPORTED_NODEJS_RUNTIMES = exports.RECOMMENDED_RUNTIMES = exports.DEFAULT_RUNTIME = exports.ALL_SUPPORTED_RUNTIMES = exports.SUPPORTED_RUNTIMES = void 0;
23848
24731
  exports.formatRuntimeList = formatRuntimeList;
23849
24732
  exports.layerNameIncludesEnvId = layerNameIncludesEnvId;
23850
24733
  exports.buildCreateLayerNameWarning = buildCreateLayerNameWarning;
@@ -23864,6 +24747,7 @@ const logger_js_1 = __webpack_require__(781);
23864
24747
  const tool_result_js_1 = __webpack_require__(9645);
23865
24748
  const function_deploy_js_1 = __webpack_require__(9151);
23866
24749
  const function_deploy_schema_js_1 = __webpack_require__(6427);
24750
+ const function_cos_upload_js_1 = __webpack_require__(5735);
23867
24751
  const function_updating_js_1 = __webpack_require__(326);
23868
24752
  const index_js_1 = __webpack_require__(4908);
23869
24753
  const fs_1 = __webpack_require__(4421);
@@ -23943,6 +24827,9 @@ exports.QUERY_FUNCTION_ACTIONS = [
23943
24827
  "listFunctionTriggers",
23944
24828
  "getFunctionDownloadUrl",
23945
24829
  "getFunctionDeployStatus",
24830
+ "listVersionByFunction",
24831
+ "getFunctionAlias",
24832
+ "getFunctionUploadUrl",
23946
24833
  ];
23947
24834
  exports.MANAGE_FUNCTION_ACTIONS = [
23948
24835
  "createFunction",
@@ -23957,8 +24844,12 @@ exports.MANAGE_FUNCTION_ACTIONS = [
23957
24844
  "attachLayer",
23958
24845
  "detachLayer",
23959
24846
  "updateFunctionLayers",
24847
+ "publishVersion",
24848
+ "updateFunctionAliasConfig",
23960
24849
  "incrementalDeployFunction", // 增量部署,需通过 pluginOptions.functions 注入实现
23961
24850
  ];
24851
+ /** Default SCF traffic alias used by CloudBase CLI `fn get-route` / `fn config-route`. */
24852
+ exports.DEFAULT_FUNCTION_ALIAS = "$DEFAULT";
23962
24853
  /** Layer soft-warn copy — account-scoped SCF LayerName guidance (no hard fail). */
23963
24854
  exports.LAYER_SOFT_WARN = {
23964
24855
  createNameFormat: (envId) => (0, index_js_1.t)("functions.layerWarn.createNameFormat", { envId }),
@@ -24118,6 +25009,46 @@ const MANAGE_LAYER_SCHEMA = zod_1.z.object({
24118
25009
  layerName: zod_1.z.string().describe("functions.schema.manageLayer.name"),
24119
25010
  layerVersion: zod_1.z.number().describe("functions.schema.manageLayer.version"),
24120
25011
  });
25012
+ /**
25013
+ * ZIP 两段式部署阶段 B 的 code 入参(camelCase,映射为 SDK 的 PascalCase code 三元组)。
25014
+ * 三件套均来自 queryFunctions getFunctionUploadUrl 的返回体,原样透传即可。
25015
+ * strict:拼错字段名直接报错,而不是被静默丢弃后按本地目录语义执行。
25016
+ */
25017
+ const FUNCTION_CODE_SCHEMA = zod_1.z
25018
+ .object({
25019
+ cosBucketName: zod_1.z
25020
+ .string()
25021
+ .describe("functions.schema.code.cosBucketName"),
25022
+ cosObjectName: zod_1.z
25023
+ .string()
25024
+ .describe("functions.schema.code.cosObjectName"),
25025
+ cosBucketRegion: zod_1.z
25026
+ .string()
25027
+ .optional()
25028
+ .describe("functions.schema.code.cosBucketRegion"),
25029
+ })
25030
+ .strict();
25031
+ const FUNCTION_VERSION_WEIGHT_SCHEMA = zod_1.z.object({
25032
+ Version: zod_1.z.string().describe("functions.schema.routing.version"),
25033
+ Weight: zod_1.z.number().describe("functions.schema.routing.weight"),
25034
+ });
25035
+ const FUNCTION_VERSION_MATCH_SCHEMA = zod_1.z.object({
25036
+ Version: zod_1.z.string().describe("functions.schema.routing.matchVersion"),
25037
+ Key: zod_1.z.string().describe("functions.schema.routing.matchKey"),
25038
+ Method: zod_1.z.string().describe("functions.schema.routing.matchMethod"),
25039
+ Expression: zod_1.z.string().describe("functions.schema.routing.matchExpression"),
25040
+ });
25041
+ const FUNCTION_ROUTING_CONFIG_SCHEMA = zod_1.z.object({
25042
+ AdditionalVersionWeights: zod_1.z
25043
+ .array(FUNCTION_VERSION_WEIGHT_SCHEMA)
25044
+ .optional()
25045
+ .describe("functions.schema.routing.additionalWeights"),
25046
+ // Keep SCF/SDK historical field name (typo included) as the public contract.
25047
+ AddtionVersionMatchs: zod_1.z
25048
+ .array(FUNCTION_VERSION_MATCH_SCHEMA)
25049
+ .optional()
25050
+ .describe("functions.schema.routing.additionalMatches"),
25051
+ });
24121
25052
  /**
24122
25053
  * Prefer top-level functionName; fall back to func.name for the common
24123
25054
  * mistake of nesting the target name under func (createFunction shape).
@@ -24296,6 +25227,48 @@ function registerFunctionTools(server) {
24296
25227
  throw new Error((0, index_js_1.t)("functions.confirmRequired", { action }));
24297
25228
  }
24298
25229
  };
25230
+ /**
25231
+ * 解析当前环境的自有存储桶(DescribeEnvs → Storages[0])。
25232
+ * 两段式部署的上传桶必须用环境自己的桶:共享 build 桶会被 SCF 拉
25233
+ * 代码时的 -appid 拼接判死(R1 探针实测)。无存储的环境直接报错引导。
25234
+ *
25235
+ * DescribeEnvs 是账号级动作,环境级凭据(如 API Key 换取的 STS,
25236
+ * remote MCP 临时 API Key 即此类)调用会被网关拒绝(invalid token),
25237
+ * 此时回退到环境级的 DescribeEnvInfo —— 其 EnvBaseInfo.Storages 与
25238
+ * DescribeEnvs 的 Storages 同构(实测两者均含 Bucket/Region/Status)。
25239
+ */
25240
+ const resolveEnvFunctionCosStorage = async () => {
25241
+ const cloudbase = await getManager();
25242
+ const envId = cloudBaseOptions?.envId ?? (await (0, cloudbase_manager_js_1.getEnvId)(cloudBaseOptions));
25243
+ const tcbService = cloudbase.commonService("tcb", "2018-06-08");
25244
+ const fetchStorages = async () => {
25245
+ try {
25246
+ const envsResult = (await tcbService.call({
25247
+ Action: "DescribeEnvs",
25248
+ Param: { EnvId: envId },
25249
+ }));
25250
+ const storages = envsResult?.EnvList?.[0]?.Storages ?? envsResult?.EnvInfo?.Storages ?? [];
25251
+ if (storages.length > 0) {
25252
+ return storages;
25253
+ }
25254
+ }
25255
+ catch (e) {
25256
+ (0, logger_js_1.debug)("resolveEnvFunctionCosStorage: DescribeEnvs failed, falling back to DescribeEnvInfo", { envId, error: e instanceof Error ? e.message : String(e) });
25257
+ }
25258
+ const infoResult = (await tcbService.call({
25259
+ Action: "DescribeEnvInfo",
25260
+ Param: { EnvId: envId },
25261
+ }));
25262
+ return infoResult?.EnvInfo?.EnvBaseInfo?.Storages ?? [];
25263
+ };
25264
+ const storages = await fetchStorages();
25265
+ const bucket = storages[0]?.Bucket ?? "";
25266
+ const region = storages[0]?.Region ?? "";
25267
+ if (!bucket || !region) {
25268
+ throw new Error((0, index_js_1.t)("functions.storageMissing"));
25269
+ }
25270
+ return { bucket, region };
25271
+ };
24299
25272
  const ensureActionAllowedInCloudMode = (input) => {
24300
25273
  if (!(0, cloud_mode_js_1.isCloudMode)()) {
24301
25274
  return;
@@ -24310,6 +25283,11 @@ function registerFunctionTools(server) {
24310
25283
  if (hasImageDeploy) {
24311
25284
  return;
24312
25285
  }
25286
+ // 两段式部署阶段 B:代码包已上传到环境 COS 桶,全程不依赖本地目录,
25287
+ // 与镜像部署同属可在 cloud mode 下真实执行的路径。
25288
+ if (Boolean(input.code)) {
25289
+ return;
25290
+ }
24313
25291
  throw new Error((0, index_js_1.t)("functions.cloudMode.localOnly", { action: input.action }));
24314
25292
  }
24315
25293
  if (input.action === "createLayerVersion" && input.contentPath) {
@@ -24528,7 +25506,13 @@ function registerFunctionTools(server) {
24528
25506
  }
24529
25507
  const cloudbase = await getManager();
24530
25508
  const result = await cloudbase.functions.getFunctionDetail(input.functionName, input.codeSecret);
24531
- (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
25509
+ // 与 getFunctionDetail / listFunctionTriggers 一致:本 action 只想取 Layers,
25510
+ // 但 getFunctionDetail 的返回里带着环境变量明文,日志与 raw 都必须脱敏 ——
25511
+ // 否则一个只读的「看层」动作会把明文环境变量带进模型上下文与持久化日志。
25512
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, maskFunctionDetailEnvValues(result));
25513
+ const detail = input.revealEnvValues === true
25514
+ ? result
25515
+ : maskFunctionDetailEnvValues(result);
24532
25516
  const layers = normalizeFunctionLayers(result.Layers);
24533
25517
  return buildEnvelope({
24534
25518
  action: input.action,
@@ -24536,7 +25520,7 @@ function registerFunctionTools(server) {
24536
25520
  layers,
24537
25521
  count: layers.length,
24538
25522
  requestId: result.RequestId,
24539
- raw: result,
25523
+ raw: detail,
24540
25524
  }, (0, index_js_1.t)("functions.gotFunctionLayers", { fnName: input.functionName }), [
24541
25525
  {
24542
25526
  tool: "manageFunctions",
@@ -24684,6 +25668,116 @@ function registerFunctionTools(server) {
24684
25668
  raw: result,
24685
25669
  }, (0, index_js_1.t)("functions.gotDownloadUrl", { fnName: input.functionName }));
24686
25670
  }
25671
+ case "listVersionByFunction": {
25672
+ if (!input.functionName) {
25673
+ throw new Error((0, index_js_1.t)("functions.paramRequired", { action: input.action, param: "functionName" }));
25674
+ }
25675
+ const cloudbase = await getManager();
25676
+ const result = await cloudbase.functions.listVersionByFunction({
25677
+ functionName: input.functionName,
25678
+ offset: input.offset,
25679
+ limit: input.limit,
25680
+ order: input.order,
25681
+ orderBy: input.orderBy,
25682
+ });
25683
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
25684
+ return buildEnvelope({
25685
+ action: input.action,
25686
+ functionName: input.functionName,
25687
+ functionVersions: result.FunctionVersion || [],
25688
+ versions: result.Versions || [],
25689
+ totalCount: result.TotalCount,
25690
+ requestId: result.RequestId,
25691
+ raw: result,
25692
+ }, (0, index_js_1.t)("functions.gotFunctionVersions", { fnName: input.functionName }), [
25693
+ {
25694
+ tool: "manageFunctions",
25695
+ action: "publishVersion",
25696
+ reason: (0, index_js_1.t)("functions.reason.publishVersion"),
25697
+ },
25698
+ {
25699
+ tool: "queryFunctions",
25700
+ action: "getFunctionAlias",
25701
+ reason: (0, index_js_1.t)("functions.reason.getFunctionAlias"),
25702
+ },
25703
+ ]);
25704
+ }
25705
+ case "getFunctionAlias": {
25706
+ if (!input.functionName) {
25707
+ throw new Error((0, index_js_1.t)("functions.paramRequired", { action: input.action, param: "functionName" }));
25708
+ }
25709
+ const aliasName = input.aliasName || exports.DEFAULT_FUNCTION_ALIAS;
25710
+ const cloudbase = await getManager();
25711
+ const result = await cloudbase.functions.getFunctionAlias({
25712
+ functionName: input.functionName,
25713
+ name: aliasName,
25714
+ });
25715
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
25716
+ return buildEnvelope({
25717
+ action: input.action,
25718
+ functionName: input.functionName,
25719
+ aliasName,
25720
+ functionVersion: result.FunctionVersion,
25721
+ routingConfig: result.RoutingConfig,
25722
+ description: result.Description,
25723
+ addTime: result.AddTime,
25724
+ modTime: result.ModTime,
25725
+ requestId: result.RequestId,
25726
+ raw: result,
25727
+ }, (0, index_js_1.t)("functions.gotFunctionAlias", {
25728
+ fnName: input.functionName,
25729
+ aliasName,
25730
+ }), [
25731
+ {
25732
+ tool: "manageFunctions",
25733
+ action: "updateFunctionAliasConfig",
25734
+ reason: (0, index_js_1.t)("functions.reason.updateFunctionAlias"),
25735
+ },
25736
+ {
25737
+ tool: "queryFunctions",
25738
+ action: "listVersionByFunction",
25739
+ reason: (0, index_js_1.t)("functions.reason.listVersions"),
25740
+ },
25741
+ ]);
25742
+ }
25743
+ case "getFunctionUploadUrl": {
25744
+ // ZIP 两段式部署阶段 A:环境自有存储桶 + 用户凭据本地铸 COS 预签名 PUT URL。
25745
+ // functionName 可选,仅用于生成可读的对象 key。
25746
+ const cloudbase = await getManager();
25747
+ const authConfig = cloudbase.currentEnvironment().getAuthConfig();
25748
+ if (!authConfig?.secretId || !authConfig?.secretKey) {
25749
+ throw new Error((0, index_js_1.t)("functions.credentialMissing"));
25750
+ }
25751
+ const storage = await resolveEnvFunctionCosStorage();
25752
+ const upload = (0, function_cos_upload_js_1.buildFunctionZipUpload)({
25753
+ storage,
25754
+ credential: {
25755
+ secretId: authConfig.secretId,
25756
+ secretKey: authConfig.secretKey,
25757
+ // 永久密钥时 token 为空串,转 undefined 才不签入 token 头
25758
+ token: authConfig.token || undefined,
25759
+ },
25760
+ functionName: input.functionName,
25761
+ });
25762
+ // uploadUrl 内含凭据绑定的签名(临时凭据还绑定 token),禁止落日志
25763
+ (0, logger_js_1.debug)(`[getFunctionUploadUrl] envId=${authConfig.envId ?? "n/a"}, cosObjectName=${upload.cosObjectName}, expiresIn=${upload.expiresInSeconds}s`);
25764
+ return buildEnvelope({
25765
+ action: input.action,
25766
+ ...(input.functionName ? { functionName: input.functionName } : {}),
25767
+ uploadUrl: upload.uploadUrl,
25768
+ uploadHeaders: upload.uploadHeaders,
25769
+ cosBucketName: upload.cosBucketName,
25770
+ cosBucketRegion: upload.cosBucketRegion,
25771
+ cosObjectName: upload.cosObjectName,
25772
+ expiresInSeconds: upload.expiresInSeconds,
25773
+ }, (0, index_js_1.t)("functions.gotUploadUrl", { seconds: upload.expiresInSeconds }), [
25774
+ {
25775
+ tool: "manageFunctions",
25776
+ action: "createFunction",
25777
+ reason: (0, index_js_1.t)("functions.reason.cosCreate"),
25778
+ },
25779
+ ]);
25780
+ }
24687
25781
  default:
24688
25782
  throw new Error((0, index_js_1.t)("functions.unsupportedAction", { action: input.action }));
24689
25783
  }
@@ -24940,6 +26034,63 @@ function registerFunctionTools(server) {
24940
26034
  },
24941
26035
  ]);
24942
26036
  }
26037
+ // code 入参(ZIP 两段式部署阶段 B):代码包已由 getFunctionUploadUrl 上传到
26038
+ // 环境 COS 桶,直接 deployMode=cos 提交,跳过本地目录 / 依赖安装逻辑。
26039
+ if (input.code) {
26040
+ const storage = await resolveEnvFunctionCosStorage();
26041
+ const cosBucketName = (0, function_cos_upload_js_1.stripAppIdSuffix)(input.code.cosBucketName || storage.bucket);
26042
+ const cosBucketRegion = input.code.cosBucketRegion ?? storage.region;
26043
+ const codeFunc = { ...func };
26044
+ // 用户 zip 自带依赖语义(装没装由上传方决定),默认不触发云端依赖安装
26045
+ delete codeFunc.installDependency;
26046
+ if (input.func?.installDependency !== undefined) {
26047
+ codeFunc.installDependency = input.func.installDependency;
26048
+ }
26049
+ if (codeFunc.type !== "HTTP") {
26050
+ codeFunc.runtime = resolveEventFunctionRuntime(codeFunc.runtime);
26051
+ }
26052
+ let cosCreateResult;
26053
+ try {
26054
+ cosCreateResult = await cloudbase.functions.createFunction({
26055
+ func: codeFunc,
26056
+ code: {
26057
+ CosBucketName: cosBucketName,
26058
+ CosBucketRegion: cosBucketRegion,
26059
+ CosObjectName: input.code.cosObjectName,
26060
+ },
26061
+ deployMode: "cos",
26062
+ force: Boolean(input.force),
26063
+ });
26064
+ }
26065
+ catch (error) {
26066
+ throw wrapFunctionOperationError("createFunction", functionName, undefined, error);
26067
+ }
26068
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, cosCreateResult);
26069
+ return buildEnvelope({
26070
+ action: input.action,
26071
+ functionName,
26072
+ deployMode: "cos",
26073
+ cosBucketName,
26074
+ cosBucketRegion,
26075
+ cosObjectName: input.code.cosObjectName,
26076
+ raw: cosCreateResult,
26077
+ }, (0, index_js_1.t)("functions.cosCreatedMessage", { fnName: functionName }), [
26078
+ {
26079
+ tool: "queryFunctions",
26080
+ action: "getFunctionDetail",
26081
+ reason: (0, index_js_1.t)("functions.reason.confirmConfig"),
26082
+ },
26083
+ ...(codeFunc.type === "HTTP"
26084
+ ? [
26085
+ {
26086
+ tool: "manageGateway",
26087
+ action: "createRoute",
26088
+ reason: (0, index_js_1.t)("functions.reason.gatewayRouteForHttp"),
26089
+ },
26090
+ ]
26091
+ : []),
26092
+ ]);
26093
+ }
24943
26094
  if (func.type !== "HTTP") {
24944
26095
  const originalRuntime = typeof func.runtime === "string" ? func.runtime : undefined;
24945
26096
  func.runtime = resolveEventFunctionRuntime(func.runtime);
@@ -25148,6 +26299,58 @@ function registerFunctionTools(server) {
25148
26299
  },
25149
26300
  ]);
25150
26301
  }
26302
+ // code 入参(ZIP 两段式部署阶段 B):zip 已在环境 COS 桶,直接 deployMode=cos
26303
+ // 更新代码包,跳过 functionRootPath / zipFile 本地语义。
26304
+ if (input.code) {
26305
+ const storage = await resolveEnvFunctionCosStorage();
26306
+ const cosBucketName = (0, function_cos_upload_js_1.stripAppIdSuffix)(input.code.cosBucketName || storage.bucket);
26307
+ const cosBucketRegion = input.code.cosBucketRegion ?? storage.region;
26308
+ let cosUpdateResult;
26309
+ try {
26310
+ cosUpdateResult = await cloudbase.functions.updateFunctionCode({
26311
+ func: {
26312
+ name: input.functionName,
26313
+ // 与 create 的 code 分支一致:默认不触发云端依赖安装,显式传参才覆盖
26314
+ ...(input.func?.installDependency !== undefined
26315
+ ? { installDependency: input.func.installDependency }
26316
+ : {}),
26317
+ ...(input.handler ? { handler: input.handler } : {}),
26318
+ },
26319
+ code: {
26320
+ CosBucketName: cosBucketName,
26321
+ CosBucketRegion: cosBucketRegion,
26322
+ CosObjectName: input.code.cosObjectName,
26323
+ },
26324
+ deployMode: "cos",
26325
+ });
26326
+ }
26327
+ catch (error) {
26328
+ if ((0, function_updating_js_1.isFunctionUpdatingError)(error)) {
26329
+ return (0, function_updating_js_1.buildFunctionUpdatingPayload)({
26330
+ action: "updateFunctionCode",
26331
+ functionName: input.functionName,
26332
+ rawMessage: (0, function_updating_js_1.getErrorMessage)(error),
26333
+ });
26334
+ }
26335
+ throw wrapFunctionOperationError("updateFunctionCode", input.functionName, undefined, error);
26336
+ }
26337
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, cosUpdateResult);
26338
+ return buildEnvelope({
26339
+ action: input.action,
26340
+ functionName: input.functionName,
26341
+ deployMode: "cos",
26342
+ cosBucketName,
26343
+ cosBucketRegion,
26344
+ cosObjectName: input.code.cosObjectName,
26345
+ raw: cosUpdateResult,
26346
+ }, (0, index_js_1.t)("functions.cosUpdatedMessage", { fnName: input.functionName }), [
26347
+ {
26348
+ tool: "queryFunctions",
26349
+ action: "getFunctionDetail",
26350
+ reason: (0, index_js_1.t)("functions.reason.confirmConfig"),
26351
+ },
26352
+ ]);
26353
+ }
25151
26354
  const processedRootPath = processFunctionRootPath(input.functionRootPath, input.functionName);
25152
26355
  const updateParams = {
25153
26356
  func: {
@@ -25522,6 +26725,94 @@ function registerFunctionTools(server) {
25522
26725
  },
25523
26726
  ], bindWarnings);
25524
26727
  }
26728
+ case "publishVersion": {
26729
+ if (!input.functionName) {
26730
+ throw new Error((0, index_js_1.t)("functions.paramRequired", { action: input.action, param: "functionName" }));
26731
+ }
26732
+ const cloudbase = await getManager();
26733
+ const result = await cloudbase.functions.publishVersion({
26734
+ functionName: input.functionName,
26735
+ description: input.description,
26736
+ });
26737
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
26738
+ return buildEnvelope({
26739
+ action: input.action,
26740
+ functionName: input.functionName,
26741
+ functionVersion: result.FunctionVersion,
26742
+ description: result.Description,
26743
+ codeSize: result.CodeSize,
26744
+ memorySize: result.MemorySize,
26745
+ handler: result.Handler,
26746
+ timeout: result.Timeout,
26747
+ runtime: result.Runtime,
26748
+ namespace: result.Namespace,
26749
+ requestId: result.RequestId,
26750
+ raw: result,
26751
+ }, (0, index_js_1.t)("functions.publishedVersion", {
26752
+ fnName: input.functionName,
26753
+ version: result.FunctionVersion,
26754
+ }), [
26755
+ {
26756
+ tool: "queryFunctions",
26757
+ action: "listVersionByFunction",
26758
+ reason: (0, index_js_1.t)("functions.reason.listVersions"),
26759
+ },
26760
+ {
26761
+ tool: "manageFunctions",
26762
+ action: "updateFunctionAliasConfig",
26763
+ reason: (0, index_js_1.t)("functions.reason.routeTraffic"),
26764
+ suggested_args: {
26765
+ functionName: input.functionName,
26766
+ functionVersion: result.FunctionVersion,
26767
+ aliasName: exports.DEFAULT_FUNCTION_ALIAS,
26768
+ },
26769
+ },
26770
+ ]);
26771
+ }
26772
+ case "updateFunctionAliasConfig": {
26773
+ if (!input.functionName) {
26774
+ throw new Error((0, index_js_1.t)("functions.paramRequired", { action: input.action, param: "functionName" }));
26775
+ }
26776
+ if (!input.functionVersion) {
26777
+ throw new Error((0, index_js_1.t)("functions.paramRequired", {
26778
+ action: input.action,
26779
+ param: "functionVersion",
26780
+ }));
26781
+ }
26782
+ const aliasName = input.aliasName || exports.DEFAULT_FUNCTION_ALIAS;
26783
+ const cloudbase = await getManager();
26784
+ const result = await cloudbase.functions.updateFunctionAliasConfig({
26785
+ functionName: input.functionName,
26786
+ name: aliasName,
26787
+ functionVersion: input.functionVersion,
26788
+ description: input.description,
26789
+ routingConfig: input.routingConfig,
26790
+ });
26791
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
26792
+ return buildEnvelope({
26793
+ action: input.action,
26794
+ functionName: input.functionName,
26795
+ aliasName,
26796
+ functionVersion: input.functionVersion,
26797
+ routingConfig: input.routingConfig,
26798
+ requestId: result.RequestId,
26799
+ raw: result,
26800
+ }, (0, index_js_1.t)("functions.updatedFunctionAlias", {
26801
+ fnName: input.functionName,
26802
+ aliasName,
26803
+ version: input.functionVersion,
26804
+ }), [
26805
+ {
26806
+ tool: "queryFunctions",
26807
+ action: "getFunctionAlias",
26808
+ reason: (0, index_js_1.t)("functions.reason.confirmAlias"),
26809
+ suggested_args: {
26810
+ functionName: input.functionName,
26811
+ aliasName,
26812
+ },
26813
+ },
26814
+ ]);
26815
+ }
25525
26816
  default:
25526
26817
  // incrementalDeployFunction:无默认实现,必须通过 pluginOptions 注入
25527
26818
  if (input.action === 'incrementalDeployFunction') {
@@ -25581,6 +26872,12 @@ function registerFunctionTools(server) {
25581
26872
  .string()
25582
26873
  .optional()
25583
26874
  .describe("functions.schema.query.taskId"),
26875
+ order: zod_1.z.string().optional().describe("functions.schema.query.order"),
26876
+ orderBy: zod_1.z.string().optional().describe("functions.schema.query.orderBy"),
26877
+ aliasName: zod_1.z
26878
+ .string()
26879
+ .optional()
26880
+ .describe("functions.schema.query.aliasName"),
25584
26881
  },
25585
26882
  annotations: {
25586
26883
  readOnlyHint: true,
@@ -25604,6 +26901,7 @@ function registerFunctionTools(server) {
25604
26901
  .optional()
25605
26902
  .describe("functions.schema.manage.functionName"),
25606
26903
  zipFile: zod_1.z.string().optional().describe("functions.schema.manage.zipFile"),
26904
+ code: FUNCTION_CODE_SCHEMA.optional().describe("functions.schema.manage.code"),
25607
26905
  handler: zod_1.z.string().optional().describe("functions.schema.manage.handler"),
25608
26906
  timeout: zod_1.z.number().optional().describe("functions.schema.manage.timeout"),
25609
26907
  envVariables: zod_1.z
@@ -25649,6 +26947,15 @@ function registerFunctionTools(server) {
25649
26947
  .describe("functions.schema.manage.autoGrant"),
25650
26948
  confirm: zod_1.z.boolean().optional().describe("functions.schema.manage.confirm"),
25651
26949
  incrementalFile: zod_1.z.string().optional().describe("functions.schema.manage.incrementalFile"),
26950
+ aliasName: zod_1.z
26951
+ .string()
26952
+ .optional()
26953
+ .describe("functions.schema.manage.aliasName"),
26954
+ functionVersion: zod_1.z
26955
+ .string()
26956
+ .optional()
26957
+ .describe("functions.schema.manage.functionVersion"),
26958
+ routingConfig: FUNCTION_ROUTING_CONFIG_SCHEMA.optional().describe("functions.schema.manage.routingConfig"),
25652
26959
  },
25653
26960
  annotations: {
25654
26961
  readOnlyHint: false,
@@ -27787,7 +29094,12 @@ function registerHostingTools(server) {
27787
29094
  });
27788
29095
  server.registerTool('manageHosting', {
27789
29096
  title: 'hosting.manageTitle',
27790
- description: 'hosting.manageDescription',
29097
+ // cloud mode 下注册期即切换描述:upload/download 系 action 不可用、部署引导走
29098
+ // manageApps 云端链路(getUploadUrl → PUT zip → deployApp(cosTimestamp)),
29099
+ // 让 agent 在 tools/list 阶段就避开必败调用,而不是等报错后浪费一轮。
29100
+ description: (0, cloud_mode_js_1.isCloudMode)()
29101
+ ? 'hosting.manageDescriptionCloud'
29102
+ : 'hosting.manageDescription',
27791
29103
  inputSchema: manageHostingInputSchema,
27792
29104
  annotations: {
27793
29105
  readOnlyHint: false,
@@ -28225,18 +29537,23 @@ const cloudbase_manager_js_1 = __webpack_require__(3109);
28225
29537
  const json_content_js_1 = __webpack_require__(8027);
28226
29538
  const index_js_1 = __webpack_require__(4908);
28227
29539
  const QUERY_LOG_ACTIONS = ["checkLogService", "searchLogs"];
28228
- function buildEnvelope(data, message) {
29540
+ const MANAGE_LOG_ACTIONS = ["createLogService"];
29541
+ function buildEnvelope(data, message, extras) {
28229
29542
  return {
28230
29543
  success: true,
28231
29544
  data,
28232
29545
  message,
29546
+ ...extras,
28233
29547
  };
28234
29548
  }
28235
- function buildErrorEnvelope(error) {
29549
+ function buildErrorEnvelope(error, extras) {
28236
29550
  return {
28237
29551
  success: false,
28238
- data: {},
28239
- message: error instanceof Error ? error.message : String(error),
29552
+ data: extras?.data ?? {},
29553
+ message: extras?.message ??
29554
+ (error instanceof Error ? error.message : String(error)),
29555
+ errorCode: extras?.errorCode,
29556
+ nextActions: extras?.nextActions,
28240
29557
  };
28241
29558
  }
28242
29559
  function registerLogTools(server) {
@@ -28309,6 +29626,89 @@ function registerLogTools(server) {
28309
29626
  return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(error));
28310
29627
  }
28311
29628
  });
29629
+ server.registerTool?.("manageLogs", {
29630
+ title: "logs.manage.title",
29631
+ description: "logs.manage.description",
29632
+ inputSchema: {
29633
+ action: zod_1.z
29634
+ .enum(MANAGE_LOG_ACTIONS)
29635
+ .describe("logs.manage.schema.action"),
29636
+ confirm: zod_1.z
29637
+ .boolean()
29638
+ .optional()
29639
+ .describe("logs.manage.schema.confirm"),
29640
+ },
29641
+ annotations: {
29642
+ readOnlyHint: false,
29643
+ destructiveHint: false,
29644
+ idempotentHint: false,
29645
+ openWorldHint: false,
29646
+ category: "logs",
29647
+ },
29648
+ }, async ({ action, confirm, }) => {
29649
+ try {
29650
+ if (action !== "createLogService") {
29651
+ return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(new Error((0, index_js_1.t)("logs.manage.unsupportedAction", { action })), {
29652
+ errorCode: "UNSUPPORTED_ACTION",
29653
+ }));
29654
+ }
29655
+ if (confirm !== true) {
29656
+ return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(null, {
29657
+ errorCode: "CONFIRM_REQUIRED",
29658
+ message: (0, index_js_1.t)("logs.manage.create.confirmRequired"),
29659
+ data: { action },
29660
+ nextActions: [
29661
+ {
29662
+ tool: "manageLogs",
29663
+ action: "createLogService",
29664
+ suggested_args: { action: "createLogService", confirm: true },
29665
+ reason: (0, index_js_1.t)("logs.manage.create.needsConfirmation"),
29666
+ },
29667
+ ],
29668
+ }));
29669
+ }
29670
+ const cloudbase = await getManager();
29671
+ const enabled = await cloudbase.log.checkLogServiceEnabled();
29672
+ if (enabled) {
29673
+ return (0, json_content_js_1.jsonContent)(buildEnvelope({
29674
+ action,
29675
+ enabled: true,
29676
+ alreadyEnabled: true,
29677
+ }, (0, index_js_1.t)("logs.manage.create.alreadyEnabled"), {
29678
+ nextActions: [
29679
+ {
29680
+ tool: "queryLogs",
29681
+ action: "searchLogs",
29682
+ suggested_args: {
29683
+ action: "searchLogs",
29684
+ queryString: 'log:"ERROR"',
29685
+ },
29686
+ reason: (0, index_js_1.t)("logs.manage.create.nextSearch"),
29687
+ },
29688
+ ],
29689
+ }));
29690
+ }
29691
+ const result = await cloudbase.log.createLogService();
29692
+ (0, cloudbase_manager_js_1.logCloudBaseResult)(server.logger, result);
29693
+ return (0, json_content_js_1.jsonContent)(buildEnvelope({
29694
+ action,
29695
+ requestId: result.RequestId ?? null,
29696
+ raw: result,
29697
+ }, (0, index_js_1.t)("logs.manage.create.submitted"), {
29698
+ nextActions: [
29699
+ {
29700
+ tool: "queryLogs",
29701
+ action: "checkLogService",
29702
+ suggested_args: { action: "checkLogService" },
29703
+ reason: (0, index_js_1.t)("logs.manage.create.nextCheck"),
29704
+ },
29705
+ ],
29706
+ }));
29707
+ }
29708
+ catch (error) {
29709
+ return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(error));
29710
+ }
29711
+ });
28312
29712
  }
28313
29713
 
28314
29714
 
@@ -29655,7 +31055,7 @@ function extractRiskyDocFieldOperations(securityRule) {
29655
31055
  continue;
29656
31056
  }
29657
31057
  const referencesNonIdDocField = /doc\.(?!_id\b)[A-Za-z_][A-Za-z0-9_]*/.test(expression);
29658
- const usesGetByDocId = /get\('database\.[^']+'\s*\+\s*doc\._id\)/.test(expression);
31058
+ const usesGetByDocId = /get\(('database\.[^']+'\s*\+\s*doc\._id|`database\.[^`]*\$\{\s*doc\._id\s*\})\)/.test(expression);
29659
31059
  if (referencesNonIdDocField && !usesGetByDocId) {
29660
31060
  operations.push(operation);
29661
31061
  }
@@ -29665,8 +31065,8 @@ function extractRiskyDocFieldOperations(securityRule) {
29665
31065
  function buildRecommendedOwnerWriteRule(resourceId) {
29666
31066
  return JSON.stringify({
29667
31067
  create: "auth.uid != null",
29668
- update: "auth.uid != null && (get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid)",
29669
- delete: "auth.uid != null && (get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid)",
31068
+ update: "auth.uid != null && (get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid)",
31069
+ delete: "auth.uid != null && (get(`database.user_roles.${auth.uid}`).role == 'admin' || doc.authorId == auth.uid)",
29670
31070
  });
29671
31071
  }
29672
31072
  function buildRoleLookupNote() {
@@ -29728,7 +31128,9 @@ function buildInvalidGetPathHint(securityRule, resourceId) {
29728
31128
  if (!securityRule) {
29729
31129
  return undefined;
29730
31130
  }
29731
- const hasFieldEmbeddedInsideGetPath = /get\('database\.[^']+'\s*\+\s*[^)]*\+\s*'\.[A-Za-z_][A-Za-z0-9_]*'\)/.test(securityRule);
31131
+ // get() 的 path 里嵌了字段名:拼接形态,或反引号模板里在 ${} 之后又接字段
31132
+ const hasFieldEmbeddedInsideGetPath = /get\('database\.[^']+'\s*\+\s*[^)]*\+\s*'\.[A-Za-z_][A-Za-z0-9_]*'\)/.test(securityRule) ||
31133
+ /get\(`database\.[^`]*\.\$\{[^}]+\}\.[A-Za-z_][A-Za-z0-9_]*`\)/.test(securityRule);
29732
31134
  if (!hasFieldEmbeddedInsideGetPath) {
29733
31135
  return undefined;
29734
31136
  }
@@ -29748,7 +31150,9 @@ function buildTemplateLiteralRuleHint(securityRule, resourceId) {
29748
31150
  if (!securityRule) {
29749
31151
  return undefined;
29750
31152
  }
29751
- const usesTemplateLiteralPlaceholderInRule = /\$\{(?:auth\.uid|doc\._id|doc\.[A-Za-z_][A-Za-z0-9_]*)\}/.test(securityRule);
31153
+ // 反引号模板字符串是官方形态,必须先剥掉再判——否则会把正确的写法误报成错误
31154
+ const withoutTemplateLiterals = securityRule.replace(/`[^`]*`/g, '');
31155
+ const usesTemplateLiteralPlaceholderInRule = /['"][^'"]*\$\{(?:auth\.uid|doc\._id|doc\.[A-Za-z_][A-Za-z0-9_]*)\}/.test(withoutTemplateLiterals);
29752
31156
  if (!usesTemplateLiteralPlaceholderInRule) {
29753
31157
  return undefined;
29754
31158
  }
@@ -30308,9 +31712,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
30308
31712
  return (mod && mod.__esModule) ? mod : { "default": mod };
30309
31713
  };
30310
31714
  Object.defineProperty(exports, "__esModule", ({ value: true }));
30311
- exports.SKILL_REMOTE_BASE_URL = void 0;
31715
+ exports.DOCS_BASE_HOST = exports.SKILL_REMOTE_BASE_URL = void 0;
30312
31716
  exports.resolveSkillSearchRoots = resolveSkillSearchRoots;
30313
31717
  exports.resolveDocsMarkdownPath = resolveDocsMarkdownPath;
31718
+ exports.toSiteRelativeDocPath = toSiteRelativeDocPath;
31719
+ exports.assertNoHostInDocPath = assertNoHostInDocPath;
30314
31720
  exports.isDocsHtmlFallback = isDocsHtmlFallback;
30315
31721
  exports.registerRagTools = registerRagTools;
30316
31722
  exports.buildSkillRawUrl = buildSkillRawUrl;
@@ -30739,6 +32145,74 @@ function resolveDocsMarkdownPath(docPath) {
30739
32145
  : `${base.replace(/\/index$/i, "")}.md`;
30740
32146
  return `${normalized}${hash}`;
30741
32147
  }
32148
+ /**
32149
+ * 交给 `DocsService.readDoc()` 的地址**永远不含 host**。
32150
+ *
32151
+ * Manager SDK 的 `DocsService.readDoc()` 见到 `http` 前缀就把入参原样 fetch、并把整段响应体
32152
+ * 回显给调用方(`@cloudbase/manager-node/lib/docs/index.js:101`)。等于 docPath 是一条「由服务端
32153
+ * 发起任意 HTTP 请求、把响应交给调用方」的通路:只要入参能带主机,`http://127.0.0.1/...`、
32154
+ * `http://169.254.169.254/...`(云主机元数据)就能把工具变成 SSRF 原语。
32155
+ *
32156
+ * 而 docPath 收到完整 URL 是**主线用法**,不能靠「拒绝一切 URL」收口:`findByName` /
32157
+ * `listModuleDocs` 的数据源 `category.json` 里 1016 个文档值全部是
32158
+ * `https://docs.cloudbase.net/...` 形态,`searchDocs`(Algolia)返回的 `url` 也是完整地址,
32159
+ * AI 拿到之后自然是原样喂回 readDoc。
32160
+ *
32161
+ * 所以这里的做法是**剥掉主机**:官方文档站的地址只取 pathname(+ 锚点),其余主机直接拒绝。
32162
+ * 效果比白名单更强 —— 不是「允许的 host 恰好只有一个」,而是**没有任何 host 能走到 fetch**,
32163
+ * 请求目标恒为 SDK 里的 `DOCS_BASE_URL`;顺带也让 `resolveDocsMarkdownPath` 的 `.md` 后缀
32164
+ * 拼接不再可能作用在主机上(旧实现里裸主机名会被拼成 `docs.cloudbase.net.md`——`.md` 是
32165
+ * 可被第三方注册的国家顶级域)。
32166
+ */
32167
+ exports.DOCS_BASE_HOST = "docs.cloudbase.net";
32168
+ /** 带 scheme 的绝对地址(`//host/path` 这类 protocol-relative 也算「指定了主机」)。 */
32169
+ const ABSOLUTE_DOC_URL_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
32170
+ function parseAbsoluteDocUrl(value) {
32171
+ const candidate = value.startsWith("//") ? `https:${value}` : value;
32172
+ if (!ABSOLUTE_DOC_URL_PATTERN.test(candidate)) {
32173
+ return null;
32174
+ }
32175
+ try {
32176
+ return new URL(candidate);
32177
+ }
32178
+ catch {
32179
+ return null;
32180
+ }
32181
+ }
32182
+ /**
32183
+ * 把 docPath 折成站内相对路径:官方文档站地址**丢掉 host**只留路径,非首方主机直接拒绝。
32184
+ *
32185
+ * 查询串一并丢弃:站点用 `<路径>.md` 寻址,query 不属于寻址的一部分,留着只会拼出
32186
+ * `.../x.md?foo` 这种畸形地址。锚点保留(`resolveDocsMarkdownPath` 本就支持 `#`)。
32187
+ */
32188
+ function toSiteRelativeDocPath(docPath) {
32189
+ const raw = docPath.trim();
32190
+ const parsed = parseAbsoluteDocUrl(raw);
32191
+ if (!parsed) {
32192
+ return raw;
32193
+ }
32194
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
32195
+ const isAllowedProtocol = parsed.protocol === "http:" || parsed.protocol === "https:";
32196
+ if (!isAllowedProtocol || host !== exports.DOCS_BASE_HOST) {
32197
+ throw new Error((0, index_js_1.t)("rag.readDocUrlNotAllowed", { docPath: raw, host: exports.DOCS_BASE_HOST }));
32198
+ }
32199
+ const sitePath = `${parsed.pathname}${parsed.hash}`;
32200
+ if (!sitePath.replace(/^\/+|\/+$/g, "")) {
32201
+ throw new Error((0, index_js_1.t)("rag.readDocPathEmpty", { docPath: raw }));
32202
+ }
32203
+ return sitePath;
32204
+ }
32205
+ /**
32206
+ * invariant:走到 SDK 的地址不能含 host。
32207
+ *
32208
+ * 归一化之后再过一次,保证「fetch 目标恒为首方基址」这条性质不依赖
32209
+ * `resolveDocsMarkdownPath` 的实现细节 —— 它以后改动了也漏不掉。
32210
+ */
32211
+ function assertNoHostInDocPath(sitePath) {
32212
+ if (parseAbsoluteDocUrl(sitePath.trim())) {
32213
+ throw new Error((0, index_js_1.t)("rag.readDocUrlNotAllowed", { docPath: sitePath, host: exports.DOCS_BASE_HOST }));
32214
+ }
32215
+ }
30742
32216
  /**
30743
32217
  * 识别 SPA 兜底页:站点对不存在的 markdown 路径同样返回 200,正文是站点 HTML 外壳。
30744
32218
  * 用于把「静默返回一坨 HTML」换成明确的失败信息。
@@ -30859,14 +32333,22 @@ async function registerRagTools(server) {
30859
32333
  }
30860
32334
  if (resolvedAction === "readDoc") {
30861
32335
  const resolvedDocPath = requireStringParam(docPath, "docPath", resolvedAction);
30862
- const markdownPath = resolveDocsMarkdownPath(resolvedDocPath);
32336
+ // 先剥掉 host(非首方主机直接拒绝),再做 `.md` 归一化,最后复核一遍不含 host。
32337
+ // 三者顺序不能换:归一化会给路径补后缀,若让它作用在主机上就会把
32338
+ // `docs.cloudbase.net` 拼成 `docs.cloudbase.net.md`(`.md` 是第三方可注册的 TLD)。
32339
+ const siteDocPath = toSiteRelativeDocPath(resolvedDocPath);
32340
+ const markdownPath = resolveDocsMarkdownPath(siteDocPath);
32341
+ assertNoHostInDocPath(markdownPath);
30863
32342
  const markdown = await docsManager.readDoc(markdownPath);
30864
32343
  // 站点对没有 markdown 的路径也返回 200 + HTML 外壳,必须显式判失败,
30865
32344
  // 否则会把整页 HTML 当成文档正文交给模型(旧行为就是这样静默出错的)。
30866
32345
  if (isDocsHtmlFallback(markdown)) {
32346
+ // 「网页版」退路必须是绝对地址:走到这里 markdownPath 已不含 host,只给路径
32347
+ // 调用方没法直接抓。
32348
+ const pageUrl = `https://${exports.DOCS_BASE_HOST}${markdownPath.replace(/\.md(?=#|$)/i, "")}`;
30867
32349
  throw new Error((0, index_js_1.t)("rag.readDocNotMarkdown", {
30868
32350
  docPath: markdownPath,
30869
- pageUrl: markdownPath.replace(/\.md(?=#|$)/i, ""),
32351
+ pageUrl,
30870
32352
  }));
30871
32353
  }
30872
32354
  return (0, json_content_js_1.jsonContent)(buildDocsEnvelope(resolvedAction, { docPath: resolvedDocPath, markdownPath, content: markdown }, (0, index_js_1.t)("rag.readDocSuccess")));
@@ -31204,6 +32686,7 @@ const url_1 = __webpack_require__(6887);
31204
32686
  const zod_1 = __webpack_require__(2971);
31205
32687
  const index_js_1 = __webpack_require__(4908);
31206
32688
  const remote_url_safety_js_1 = __webpack_require__(3694);
32689
+ const project_config_js_1 = __webpack_require__(9175);
31207
32690
  // CloudBase 模板配置
31208
32691
  const TEMPLATES = {
31209
32692
  react: {
@@ -31689,6 +33172,23 @@ function registerSetupTools(server) {
31689
33172
  };
31690
33173
  }
31691
33174
  const resolvedIDE = ideResolution.resolvedIDE;
33175
+ let workspaceFolder;
33176
+ try {
33177
+ workspaceFolder = (0, project_config_js_1.resolveProjectRoot)();
33178
+ }
33179
+ catch (error) {
33180
+ if (error instanceof project_config_js_1.ProjectRootError) {
33181
+ return {
33182
+ content: [
33183
+ {
33184
+ type: "text",
33185
+ text: (0, index_js_1.t)("setup.projectRoot.hostConfigDir", { dir: error.dir }),
33186
+ },
33187
+ ],
33188
+ };
33189
+ }
33190
+ throw error;
33191
+ }
31692
33192
  // 验证IDE类型
31693
33193
  const ideValidation = validateIDE(resolvedIDE);
31694
33194
  if (!ideValidation.valid) {
@@ -31726,7 +33226,6 @@ function registerSetupTools(server) {
31726
33226
  // 创建过滤后的目录结构(当选择特定IDE时)
31727
33227
  const workingDir = await createFilteredDirectory(extractDir, filteredFiles, resolvedIDE);
31728
33228
  // 检查是否需要复制到项目目录
31729
- const workspaceFolder = process.env.WORKSPACE_FOLDER_PATHS || process.cwd();
31730
33229
  let finalFiles = [];
31731
33230
  let createdCount = 0;
31732
33231
  let overwrittenCount = 0;
@@ -32929,6 +34428,143 @@ function resolveRequestId(error) {
32929
34428
  }
32930
34429
 
32931
34430
 
34431
+ /***/ },
34432
+
34433
+ /***/ 3379
34434
+ (__unused_webpack_module, exports, __webpack_require__) {
34435
+
34436
+ var __webpack_unused_export__;
34437
+
34438
+ /**
34439
+ * In-process log of tool outcomes for an explicitly requested feedback draft.
34440
+ *
34441
+ * Hosted gateways may construct a new server object per request. The log is
34442
+ * therefore keyed by a hash of the credential when one is present, and only
34443
+ * falls back to the server object when no credential is available. The cache
34444
+ * is bounded. Arguments are never stored, and the raw credential is not stored.
34445
+ */
34446
+ __webpack_unused_export__ = ({ value: true });
34447
+ __webpack_unused_export__ = __webpack_unused_export__ = void 0;
34448
+ exports.recordToolOutcome = recordToolOutcome;
34449
+ exports.readToolOutcomes = readToolOutcomes;
34450
+ exports.noteRepeatCount = noteRepeatCount;
34451
+ exports.readRepeatPeak = readRepeatPeak;
34452
+ __webpack_unused_export__ = clearToolOutcomes;
34453
+ __webpack_unused_export__ = __resetFeedbackSessionsForTests;
34454
+ const node_crypto_1 = __webpack_require__(2561);
34455
+ const MAX_OUTCOMES = 200;
34456
+ const MAX_CREDENTIALS = 64;
34457
+ const MAX_TOOL_NAME_LENGTH = 80;
34458
+ const byCredential = new Map();
34459
+ const byServer = new WeakMap();
34460
+ function credentialKey(server) {
34461
+ const options = server.cloudBaseOptions;
34462
+ const secretId = typeof options?.secretId === "string" ? options.secretId.trim() : "";
34463
+ if (!secretId) {
34464
+ return undefined;
34465
+ }
34466
+ const token = typeof options?.token === "string" ? options.token.trim() : "";
34467
+ const site = typeof options?.site === "string" ? options.site.trim() : "";
34468
+ return (0, node_crypto_1.createHash)("sha256").update(`${site}\n${secretId}\n${token}`).digest("hex");
34469
+ }
34470
+ function emptyBucket() {
34471
+ return { outcomes: [], repeatPeak: 0, touchedAt: Date.now() };
34472
+ }
34473
+ function evictOldestCredential() {
34474
+ let oldestKey;
34475
+ let oldestTouched = Number.POSITIVE_INFINITY;
34476
+ for (const [key, bucket] of byCredential) {
34477
+ if (bucket.touchedAt < oldestTouched) {
34478
+ oldestTouched = bucket.touchedAt;
34479
+ oldestKey = key;
34480
+ }
34481
+ }
34482
+ if (oldestKey) {
34483
+ byCredential.delete(oldestKey);
34484
+ }
34485
+ }
34486
+ function bucketFor(server) {
34487
+ if (!server || typeof server !== "object") {
34488
+ return undefined;
34489
+ }
34490
+ const key = credentialKey(server);
34491
+ if (key) {
34492
+ let bucket = byCredential.get(key);
34493
+ if (!bucket) {
34494
+ if (byCredential.size >= MAX_CREDENTIALS) {
34495
+ evictOldestCredential();
34496
+ }
34497
+ bucket = emptyBucket();
34498
+ byCredential.set(key, bucket);
34499
+ }
34500
+ bucket.touchedAt = Date.now();
34501
+ return bucket;
34502
+ }
34503
+ let bucket = byServer.get(server);
34504
+ if (!bucket) {
34505
+ bucket = emptyBucket();
34506
+ byServer.set(server, bucket);
34507
+ }
34508
+ return bucket;
34509
+ }
34510
+ function recordToolOutcome(server, input) {
34511
+ const bucket = bucketFor(server);
34512
+ if (!bucket) {
34513
+ return;
34514
+ }
34515
+ const toolName = typeof input.toolName === "string" ? input.toolName.trim() : "";
34516
+ if (!toolName) {
34517
+ return;
34518
+ }
34519
+ const durationMs = Number.isFinite(input.durationMs) && input.durationMs >= 0
34520
+ ? Math.round(input.durationMs)
34521
+ : 0;
34522
+ const at = typeof input.at === "string" && input.at.length > 0
34523
+ ? input.at
34524
+ : new Date().toISOString();
34525
+ bucket.outcomes.push({
34526
+ toolName: toolName.slice(0, MAX_TOOL_NAME_LENGTH),
34527
+ durationMs,
34528
+ failed: input.failed === true,
34529
+ at,
34530
+ });
34531
+ if (bucket.outcomes.length > MAX_OUTCOMES) {
34532
+ bucket.outcomes.splice(0, bucket.outcomes.length - MAX_OUTCOMES);
34533
+ }
34534
+ }
34535
+ function readToolOutcomes(server) {
34536
+ return bucketFor(server)?.outcomes ?? [];
34537
+ }
34538
+ function noteRepeatCount(server, count) {
34539
+ const bucket = bucketFor(server);
34540
+ if (!bucket || !Number.isFinite(count) || count <= 0) {
34541
+ return;
34542
+ }
34543
+ const rounded = Math.round(count);
34544
+ if (rounded > bucket.repeatPeak) {
34545
+ bucket.repeatPeak = rounded;
34546
+ }
34547
+ }
34548
+ function readRepeatPeak(server) {
34549
+ return bucketFor(server)?.repeatPeak ?? 0;
34550
+ }
34551
+ function clearToolOutcomes(server) {
34552
+ const key = server && typeof server === "object" ? credentialKey(server) : undefined;
34553
+ if (key) {
34554
+ byCredential.delete(key);
34555
+ return;
34556
+ }
34557
+ if (server && typeof server === "object") {
34558
+ byServer.delete(server);
34559
+ }
34560
+ }
34561
+ function __resetFeedbackSessionsForTests() {
34562
+ byCredential.clear();
34563
+ }
34564
+ __webpack_unused_export__ = MAX_OUTCOMES;
34565
+ __webpack_unused_export__ = MAX_CREDENTIALS;
34566
+
34567
+
32932
34568
  /***/ },
32933
34569
 
32934
34570
  /***/ 4173
@@ -33393,14 +35029,101 @@ async function sendDeployNotification(server, notificationData) {
33393
35029
  var __webpack_unused_export__;
33394
35030
 
33395
35031
  __webpack_unused_export__ = ({ value: true });
35032
+ exports.ProjectRootError = void 0;
35033
+ exports.resolveProjectRoot = resolveProjectRoot;
35034
+ exports.requireProjectRoot = requireProjectRoot;
33396
35035
  exports.readCloudbaseRcBinding = readCloudbaseRcBinding;
33397
35036
  exports.readProjectConfig = readProjectConfig;
33398
35037
  exports.readProjectEnvId = readProjectEnvId;
33399
35038
  exports.writeProjectConfig = writeProjectConfig;
33400
35039
  const node_fs_1 = __webpack_require__(9627);
35040
+ const node_os_1 = __webpack_require__(6674);
33401
35041
  const node_path_1 = __webpack_require__(5663);
33402
35042
  const toolbox_1 = __webpack_require__(2090);
35043
+ const index_js_1 = __webpack_require__(4908);
33403
35044
  const CLOUDBASE_RC_FILENAME = "cloudbaserc.json";
35045
+ const PROJECT_ROOT_ENV_KEYS = [
35046
+ "WORKSPACE_FOLDER_PATHS",
35047
+ "PROJECT_ROOT",
35048
+ "GITHUB_WORKSPACE",
35049
+ "CI_PROJECT_DIR",
35050
+ "BUILD_SOURCESDIRECTORY",
35051
+ ];
35052
+ /** Thrown when the resolved directory is a host config root, not a project. */
35053
+ class ProjectRootError extends Error {
35054
+ dir;
35055
+ constructor(dir) {
35056
+ super("setup.projectRoot.hostConfigDir");
35057
+ this.name = "ProjectRootError";
35058
+ this.dir = dir;
35059
+ }
35060
+ }
35061
+ exports.ProjectRootError = ProjectRootError;
35062
+ function firstPathSegment(value) {
35063
+ return value
35064
+ .split(node_path_1.delimiter)
35065
+ .map((segment) => segment.trim())
35066
+ .find((segment) => segment.length > 0);
35067
+ }
35068
+ function isUnderHostConfig(candidate) {
35069
+ const hostRoot = (0, node_path_1.resolve)((0, node_os_1.homedir)(), ".dsh");
35070
+ const resolved = (0, node_path_1.resolve)(candidate);
35071
+ const rel = (0, node_path_1.relative)(hostRoot, resolved);
35072
+ return rel === "" || (!rel.startsWith("..") && !(0, node_path_1.isAbsolute)(rel));
35073
+ }
35074
+ /**
35075
+ * Project directory for reads and writes.
35076
+ *
35077
+ * Explicit path, then host-injected workspace env vars, then process.cwd().
35078
+ * A result under ~/.dsh is refused so tools do not treat the host profile as a project.
35079
+ */
35080
+ function resolveProjectRoot(explicit) {
35081
+ const trimmed = explicit?.trim();
35082
+ let chosen;
35083
+ if (trimmed) {
35084
+ chosen = (0, node_path_1.resolve)(trimmed);
35085
+ }
35086
+ else {
35087
+ let fromEnv;
35088
+ for (const key of PROJECT_ROOT_ENV_KEYS) {
35089
+ const raw = process.env[key];
35090
+ if (!raw?.trim())
35091
+ continue;
35092
+ const first = firstPathSegment(raw);
35093
+ if (first) {
35094
+ fromEnv = (0, node_path_1.resolve)(first);
35095
+ break;
35096
+ }
35097
+ }
35098
+ chosen = fromEnv ?? (0, node_path_1.resolve)(process.cwd());
35099
+ }
35100
+ if (isUnderHostConfig(chosen)) {
35101
+ throw new ProjectRootError(chosen);
35102
+ }
35103
+ return chosen;
35104
+ }
35105
+ /** Same as resolveProjectRoot, with the refusal already translated for tool output. */
35106
+ function requireProjectRoot(explicit) {
35107
+ try {
35108
+ return resolveProjectRoot(explicit);
35109
+ }
35110
+ catch (error) {
35111
+ if (error instanceof ProjectRootError) {
35112
+ throw new Error((0, index_js_1.t)("setup.projectRoot.hostConfigDir", { dir: error.dir }));
35113
+ }
35114
+ throw error;
35115
+ }
35116
+ }
35117
+ function projectRootForConfig(cwd) {
35118
+ try {
35119
+ return resolveProjectRoot(cwd);
35120
+ }
35121
+ catch (error) {
35122
+ if (error instanceof ProjectRootError)
35123
+ return undefined;
35124
+ throw error;
35125
+ }
35126
+ }
33404
35127
  /**
33405
35128
  * 解析 cloudbaserc.json 字段值用于绑定(fail-safe:解析不出一律返回 undefined 回落下一级):
33406
35129
  * - 字面量 → trim 后直接返回
@@ -33458,7 +35181,9 @@ function resolveBindingValue(raw, projectRoot) {
33458
35181
  */
33459
35182
  function readCloudbaseRcBinding(cwd) {
33460
35183
  try {
33461
- const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
35184
+ const projectRoot = projectRootForConfig(cwd);
35185
+ if (!projectRoot)
35186
+ return undefined;
33462
35187
  const configPath = (0, node_path_1.join)(projectRoot, CLOUDBASE_RC_FILENAME);
33463
35188
  if (!(0, node_fs_1.existsSync)(configPath)) {
33464
35189
  return undefined;
@@ -33492,7 +35217,9 @@ function readCloudbaseRcBinding(cwd) {
33492
35217
  */
33493
35218
  function readProjectConfig(cwd) {
33494
35219
  try {
33495
- const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
35220
+ const projectRoot = projectRootForConfig(cwd);
35221
+ if (!projectRoot)
35222
+ return undefined;
33496
35223
  const configPath = (0, node_path_1.join)(projectRoot, ".cloudbase", "project.json");
33497
35224
  if (!(0, node_fs_1.existsSync)(configPath)) {
33498
35225
  return undefined;
@@ -33540,7 +35267,9 @@ function readProjectEnvId(cwd) {
33540
35267
  */
33541
35268
  function writeProjectConfig(patch, cwd) {
33542
35269
  try {
33543
- const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
35270
+ const projectRoot = projectRootForConfig(cwd);
35271
+ if (!projectRoot)
35272
+ return false;
33544
35273
  const configPath = (0, node_path_1.join)(projectRoot, ".cloudbase", "project.json");
33545
35274
  let existing = {};
33546
35275
  if ((0, node_fs_1.existsSync)(configPath)) {
@@ -33765,6 +35494,7 @@ var __webpack_unused_export__;
33765
35494
 
33766
35495
  __webpack_unused_export__ = ({ value: true });
33767
35496
  exports.iA = void 0;
35497
+ exports.getRepeatGuardSnapshot = getRepeatGuardSnapshot;
33768
35498
  exports.applyRepeatGuardToPayload = applyRepeatGuardToPayload;
33769
35499
  exports.resetRepeatGuard = resetRepeatGuard;
33770
35500
  __webpack_unused_export__ = __resetRepeatGuardForTests;
@@ -33783,6 +35513,13 @@ exports.iA = 3;
33783
35513
  const REPEAT_GUARD_KEY_MAX_LENGTH = 200;
33784
35514
  let lastKey = null;
33785
35515
  let consecutiveCount = 0;
35516
+ /**
35517
+ * Live streak only. Does not expose the dedup key: that key contains the raw
35518
+ * error message, which may include secrets or identifiers.
35519
+ */
35520
+ function getRepeatGuardSnapshot() {
35521
+ return { consecutiveCount };
35522
+ }
33786
35523
  function buildRepeatGuardKey(payload) {
33787
35524
  const code = typeof payload.code === "string" ? payload.code : "";
33788
35525
  const message = typeof payload.message === "string" ? payload.message : "";
@@ -34254,7 +35991,7 @@ class TelemetryReporter {
34254
35991
  const arch = os_1.default.arch(); // 系统架构
34255
35992
  // Build-time injected version; guard for vitest / non-webpack runtimes.
34256
35993
  const mcpVersion = process.env.npm_package_version ||
34257
- ( true ? "2.34.5" : 0);
35994
+ ( true ? "2.34.7" : 0);
34258
35995
  return {
34259
35996
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
34260
35997
  deviceId: this.deviceId,
@@ -34760,7 +36497,7 @@ var __webpack_unused_export__;
34760
36497
  __webpack_unused_export__ = ({ value: true });
34761
36498
  exports.ToolPayloadError = void 0;
34762
36499
  exports.buildJsonToolResult = buildJsonToolResult;
34763
- __webpack_unused_export__ = isBusinessFailureToolResult;
36500
+ exports.isBusinessFailureToolResult = isBusinessFailureToolResult;
34764
36501
  exports.withBusinessFailureIsError = withBusinessFailureIsError;
34765
36502
  exports.buildTextErrorResult = buildTextErrorResult;
34766
36503
  exports.isToolPayloadError = isToolPayloadError;
@@ -34901,6 +36638,7 @@ const logger_js_1 = __webpack_require__(781);
34901
36638
  const telemetry_js_1 = __webpack_require__(5198);
34902
36639
  const tool_result_js_1 = __webpack_require__(9645);
34903
36640
  const repeat_error_guard_js_1 = __webpack_require__(13);
36641
+ const feedback_session_js_1 = __webpack_require__(3379);
34904
36642
  const error_guidance_js_1 = __webpack_require__(1194);
34905
36643
  /**
34906
36644
  * Mirror annotations.category into _meta.category.
@@ -34976,7 +36714,7 @@ ${envIdSection}
34976
36714
  ## 环境信息
34977
36715
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
34978
36716
  - Node.js版本: ${process.version}
34979
- - MCP 版本:${( true ? "2.34.5" : 0) || 0 || 0}
36717
+ - MCP 版本:${( true ? "2.34.7" : 0) || 0 || 0}
34980
36718
  - 系统架构: ${os_1.default.arch()}
34981
36719
  - 时间: ${new Date().toISOString()}
34982
36720
  - 请求ID: ${requestId}
@@ -35010,6 +36748,8 @@ function createWrappedHandler(name, handler, server) {
35010
36748
  return async (args) => {
35011
36749
  const startTime = Date.now();
35012
36750
  let success = false;
36751
+ let businessFailed = false;
36752
+ let repeatCountSeen = 0;
35013
36753
  let errorMessage;
35014
36754
  let requestId;
35015
36755
  try {
@@ -35021,7 +36761,11 @@ function createWrappedHandler(name, handler, server) {
35021
36761
  }
35022
36762
  // 执行原始处理函数
35023
36763
  const result = await handler(args);
36764
+ // Returned { success: false } is a business failure for the local
36765
+ // session log. The telemetry flag below stays on the existing path.
36766
+ businessFailed = (0, tool_result_js_1.isBusinessFailureToolResult)(result);
35024
36767
  success = true;
36768
+ repeatCountSeen = (0, repeat_error_guard_js_1.getRepeatGuardSnapshot)().consecutiveCount;
35025
36769
  // 任一工具成功说明重复错误循环已被打破,清零连续错误计数
35026
36770
  (0, repeat_error_guard_js_1.resetRepeatGuard)();
35027
36771
  requestId = extractRequestIdFromToolResult(result);
@@ -35054,8 +36798,11 @@ function createWrappedHandler(name, handler, server) {
35054
36798
  if ((0, tool_result_js_1.isToolPayloadError)(error)) {
35055
36799
  // 连续相同结构化错误达到阈值时注入 repeat_guard 升级提示,
35056
36800
  // 打断无头客户端的原样重试循环(不改写 message,保持遥测聚合稳定)
35057
- throw new tool_result_js_1.ToolPayloadError((0, repeat_error_guard_js_1.applyRepeatGuardToPayload)(error.payload));
36801
+ const payload = (0, repeat_error_guard_js_1.applyRepeatGuardToPayload)(error.payload);
36802
+ repeatCountSeen = (0, repeat_error_guard_js_1.getRepeatGuardSnapshot)().consecutiveCount;
36803
+ throw new tool_result_js_1.ToolPayloadError(payload);
35058
36804
  }
36805
+ repeatCountSeen = (0, repeat_error_guard_js_1.getRepeatGuardSnapshot)().consecutiveCount;
35059
36806
  // In tests, avoid any extra work that may block (envId lookup, issue link generation, etc.)
35060
36807
  if (isTestEnvironment) {
35061
36808
  throw error instanceof Error ? error : new Error(String(error));
@@ -35065,7 +36812,7 @@ function createWrappedHandler(name, handler, server) {
35065
36812
  requestId,
35066
36813
  ide: server.ide || process.env.INTEGRATION_IDE || ''
35067
36814
  });
35068
- const mcpVersion = true ? "2.34.5" : 0;
36815
+ const mcpVersion = true ? "2.34.7" : 0;
35069
36816
  const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
35070
36817
  const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
35071
36818
  // 创建新的错误对象,保持原有的错误类型但更新消息
@@ -35081,6 +36828,20 @@ function createWrappedHandler(name, handler, server) {
35081
36828
  throw enhancedError;
35082
36829
  }
35083
36830
  finally {
36831
+ try {
36832
+ (0, feedback_session_js_1.noteRepeatCount)(server, repeatCountSeen);
36833
+ (0, feedback_session_js_1.recordToolOutcome)(server, {
36834
+ toolName: name,
36835
+ durationMs: Date.now() - startTime,
36836
+ failed: Boolean(errorMessage) || businessFailed,
36837
+ });
36838
+ }
36839
+ catch (recordError) {
36840
+ (0, logger_js_1.debug)("feedback session record failed", {
36841
+ toolName: name,
36842
+ error: recordError instanceof Error ? recordError.message : String(recordError),
36843
+ });
36844
+ }
35084
36845
  // 上报工具调用数据(测试环境中跳过,避免阻塞)
35085
36846
  const isTestEnvironment = false || process.env.VITEST === "true";
35086
36847
  if (!isTestEnvironment) {
@@ -35348,7 +37109,7 @@ var x = (y) => {
35348
37109
  var x = {}; __webpack_require__.d(x, y); return x
35349
37110
  }
35350
37111
  var y = (x) => (() => (x))
35351
- module.exports = x({ ["randomUUID"]: () => (__WEBPACK_EXTERNAL_MODULE_node_crypto_803ecaf5__.randomUUID) });
37112
+ module.exports = x({ ["createHash"]: () => (__WEBPACK_EXTERNAL_MODULE_node_crypto_803ecaf5__.createHash), ["randomUUID"]: () => (__WEBPACK_EXTERNAL_MODULE_node_crypto_803ecaf5__.randomUUID) });
35352
37113
 
35353
37114
  /***/ },
35354
37115
 
@@ -35359,6 +37120,17 @@ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_75ed2103__;
35359
37120
 
35360
37121
  /***/ },
35361
37122
 
37123
+ /***/ 6674
37124
+ (module, __unused_webpack_exports, __webpack_require__) {
37125
+
37126
+ var x = (y) => {
37127
+ var x = {}; __webpack_require__.d(x, y); return x
37128
+ }
37129
+ var y = (x) => (() => (x))
37130
+ module.exports = x({ ["homedir"]: () => (__WEBPACK_EXTERNAL_MODULE_node_os_e12349cb__.homedir) });
37131
+
37132
+ /***/ },
37133
+
35362
37134
  /***/ 5663
35363
37135
  (module) {
35364
37136