@cloudbase/cloudbase-mcp 2.34.6 → 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
@@ -5056,7 +5144,7 @@ exports.functions = (0, types_js_1.defineModule)({
5056
5144
  "opErr.default": "请检查函数名、目录结构和环境中的函数状态后重试。",
5057
5145
  "opErr.prefix": "[{operation}] {message}\n建议:",
5058
5146
  confirmRequired: "{action} 是危险操作,请显式传入 confirm=true 后再执行",
5059
- "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 同样不依赖本地目录)。",
5060
5148
  "cloudMode.contentPathUnsupported": "createLayerVersion 在 cloud mode 下不支持 contentPath,本地文件内容请改为 base64Content 或改用本地模式执行。",
5061
5149
  offsetLimitTooLarge: "offset+limit 不能大于 10000",
5062
5150
  startTimeInvalid: "startTime 格式错误: \"{value}\"。必须使用 YYYY-MM-DD HH:mm:ss 格式(如 2024-01-01 00:00:00)",
@@ -5069,6 +5157,8 @@ exports.functions = (0, types_js_1.defineModule)({
5069
5157
  "deployStatus.cloudMode": "{action} 在 cloud mode 下不可用:异步部署任务只由 buildStrategy=cloud/local 的真实部署创建,而这两种策略的真实执行在 cloud mode 下都不支持(需要读取本地构建上下文或本地 Docker),因此不会存在任何 taskId。buildStrategy=image 走同步部署,直接在 manageFunctions 的返回里拿结果,也不需要查询部署状态。如需异步镜像构建部署,请改用本地 MCP 模式。",
5070
5158
  deployTaskNotFound: "未找到部署任务 {taskId};部署任务不存在,可能已过期、不属于当前环境 {envId},或 MCP Server 已重启(任务仅保存在 MCP 进程内存中)。",
5071
5159
  unsupportedAction: "不支持的操作类型: {action}",
5160
+ storageMissing: "当前环境没有可用的对象存储桶(DescribeEnvs 未返回 Storages),无法使用 COS 两段式部署。请检查环境存储配置,或改用本地模式部署。共享存储桶(ExternalStorage)环境同样不支持该通道。",
5161
+ credentialMissing: "当前凭据缺少 SecretId/SecretKey(如 IDE 代理模式),无法本地铸造 COS 预签名上传地址。请改用本地模式或包含永久密钥/临时密钥的登录方式。",
5072
5162
  // ---- nextActions reasons ----
5073
5163
  "reason.continuePolling": "继续查询云函数部署状态",
5074
5164
  "reason.getDetail": "查看单个函数详情",
@@ -5107,6 +5197,7 @@ exports.functions = (0, types_js_1.defineModule)({
5107
5197
  "reason.imageFnReady": "确认镜像函数已就绪(Active)",
5108
5198
  "reason.imageUpdateReady": "确认镜像更新后函数已就绪(Active)",
5109
5199
  "reason.imageNextIteration": "后续迭代只需用新镜像 tag 调用 updateFunctionCode 更新镜像",
5200
+ "reason.cosCreate": "把 PUT 好的代码 zip 通过 code 入参部署为函数(两段式阶段 B)",
5110
5201
  "reason.imageGatewayRoute": "如需通过 URL 访问镜像 HTTP 函数,显式创建 Domain/Route 访问入口并传 type=\"HTTP\"(映射 WEB_SCF)",
5111
5202
  "reason.latestConfig": "确认最新函数配置",
5112
5203
  "reason.publishVersion": "发布函数新版本(对齐 tcb fn publish-version)",
@@ -5126,12 +5217,15 @@ exports.functions = (0, types_js_1.defineModule)({
5126
5217
  gotLayerVersionDetail: "已获取层 {layerName} 版本 {layerVersion} 的详情",
5127
5218
  gotFunctionTriggers: "已获取函数 {fnName} 的触发器列表",
5128
5219
  gotDownloadUrl: "已获取函数 {fnName} 的代码下载链接",
5220
+ gotUploadUrl: "已生成函数代码包上传地址({seconds} 秒内有效)。下一步:PUT 代码 zip 到 uploadUrl(uploadHeaders 非空时须随请求携带),再调用 manageFunctions createFunction/updateFunctionCode 并传入 code 三元组(cosBucketName/cosObjectName/cosBucketRegion)完成部署",
5129
5221
  gotFunctionVersions: "已获取函数 {fnName} 的版本列表",
5130
5222
  gotFunctionAlias: "已获取函数 {fnName} 的别名 {aliasName}",
5131
5223
  publishedVersion: "已发布函数 {fnName} 的新版本 {version}",
5132
5224
  updatedFunctionAlias: "已更新函数 {fnName} 别名 {aliasName}(主版本 {version})",
5133
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\") 调整权限。",
5134
5226
  createdFunction: "已创建函数 {fnName}",
5227
+ cosCreatedMessage: "已基于环境 COS 桶中的代码包(deployMode=cos)创建函数 {fnName}。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪。",
5228
+ cosUpdatedMessage: "已用环境 COS 桶中的新代码包(deployMode=cos)更新函数 {fnName} 的代码。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪(Active)。",
5135
5229
  imageCreatedMessage: "已基于镜像 {imageUri} 创建 HTTP 函数 {fnName}。请确认 TCR、SCF 与构建管道处于同一地域;如需通过 URL 访问,请显式调用 manageGateway(action=\"createRoute\", upstreamResourceType=\"WEB_SCF\") 并按需调整函数安全规则。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪。",
5136
5230
  imageUpdatedMessage: "已将函数 {fnName} 的镜像更新为 {imageUri}。部署后可用 queryFunctions(action=\"getFunctionDetail\") 确认函数已就绪(Active)。",
5137
5231
  updatedCode: "已更新函数 {fnName} 的代码",
@@ -5197,12 +5291,12 @@ exports.functions = (0, types_js_1.defineModule)({
5197
5291
  "schema.create.layers": "Layer 配置",
5198
5292
  "schema.manageLayer.name": "层名称",
5199
5293
  "schema.manageLayer.version": "层版本号",
5200
- "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)",
5201
- "schema.query.functionName": "CloudBase 云函数名称。`getFunctionDetail`、`listFunctionLogs`、`listFunctionLayers`、`listFunctionTriggers`、`getFunctionDownloadUrl`、`listVersionByFunction`、`getFunctionAlias` 时必填",
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)",
5202
5296
  "schema.query.limit": "分页数量(limit)。列表类 action 可选,默认值由后端决定",
5203
5297
  "schema.query.offset": "分页偏移(offset)。列表类 action 可选,默认 0",
5204
5298
  "schema.query.codeSecret": "代码保护密钥,用于解密函数代码",
5205
- "schema.query.revealEnvValues": "getFunctionDetail / listFunctionTriggers 时是否返回环境变量明文值。默认 false:Value 脱敏为 ***,仅保留 Key 与 ValueLength,足以确认配置了哪些变量及变更是否生效;true 时返回明文,敏感变量会进入模型上下文,谨慎使用。如需查看明文,建议优先使用控制台或 CLI",
5299
+ "schema.query.revealEnvValues": "getFunctionDetail / listFunctionTriggers / listFunctionLayers 时是否返回环境变量明文值。默认 false:Value 脱敏为 ***,仅保留 Key 与 ValueLength,足以确认配置了哪些变量及变更是否生效;true 时返回明文,敏感变量会进入模型上下文,谨慎使用。如需查看明文,建议优先使用控制台或 CLI",
5206
5300
  "schema.query.startTime": "日志查询开始时间,格式必须为 YYYY-MM-DD HH:mm:ss(如 2024-01-01 00:00:00)。与 endTime 间隔不能超过一天。不传时默认查询最近一天",
5207
5301
  "schema.query.endTime": "日志查询结束时间,格式必须为 YYYY-MM-DD HH:mm:ss(如 2024-01-01 23:59:59)。与 startTime 间隔不能超过一天。不传时默认为当前时间",
5208
5302
  "schema.query.requestId": "日志请求 ID。`getFunctionLogDetail` 操作必填,可从 `listFunctionLogs` 结果中获取",
@@ -5221,6 +5315,10 @@ exports.functions = (0, types_js_1.defineModule)({
5221
5315
  "schema.manage.force": "createFunction 时是否覆盖",
5222
5316
  "schema.manage.functionName": "目标函数名称(顶层)。updateFunctionCode / updateFunctionConfig / invokeFunction / publishVersion / updateFunctionAliasConfig 等 action 使用此字段。不要只写在 func.name:createFunction 用 func.name,其它 action 用顶层 functionName。若误传 func.name,也会被识别为 functionName。",
5223
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": "存储桶地域,省略时自动使用当前环境存储桶地域",
5224
5322
  "schema.manage.handler": "函数入口",
5225
5323
  "schema.manage.timeout": "配置更新时的超时时间",
5226
5324
  "schema.manage.envVariables": "配置更新时要合并的环境变量。若含 DATABASE_URL / MYSQL_* / POSTGRES_* / REDIS_* 等 TCP 连库变量,必须同时提供真实 vpc(或函数已绑定完整 VPC)。禁止猜测 vpcId/subnetId。",
@@ -5326,7 +5424,7 @@ exports.functions = (0, types_js_1.defineModule)({
5326
5424
  "opErr.default": "Please check the function name, directory structure, and the function status in the environment, then retry.",
5327
5425
  "opErr.prefix": "[{operation}] {message}\nSuggestions: ",
5328
5426
  confirmRequired: "{action} is a dangerous operation; pass confirm=true explicitly before executing",
5329
- "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).",
5330
5428
  "cloudMode.contentPathUnsupported": "createLayerVersion does not support contentPath in cloud mode; switch local file content to base64Content or run in local mode.",
5331
5429
  offsetLimitTooLarge: "offset+limit must not be greater than 10000",
5332
5430
  startTimeInvalid: "Invalid startTime: \"{value}\". It must use the YYYY-MM-DD HH:mm:ss format (e.g. 2024-01-01 00:00:00)",
@@ -5339,6 +5437,8 @@ exports.functions = (0, types_js_1.defineModule)({
5339
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.",
5340
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).",
5341
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.",
5342
5442
  // ---- nextActions reasons ----
5343
5443
  "reason.continuePolling": "Keep polling the cloud function deployment status",
5344
5444
  "reason.getDetail": "View details of a single function",
@@ -5377,6 +5477,7 @@ exports.functions = (0, types_js_1.defineModule)({
5377
5477
  "reason.imageFnReady": "Confirm the image function is ready (Active)",
5378
5478
  "reason.imageUpdateReady": "Confirm the function is ready (Active) after the image update",
5379
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)",
5380
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)",
5381
5482
  "reason.latestConfig": "Confirm the latest function configuration",
5382
5483
  "reason.publishVersion": "Publish a new function version (aligns with tcb fn publish-version)",
@@ -5396,12 +5497,15 @@ exports.functions = (0, types_js_1.defineModule)({
5396
5497
  gotLayerVersionDetail: "Retrieved details of layer {layerName} version {layerVersion}",
5397
5498
  gotFunctionTriggers: "Retrieved the trigger list of function {fnName}",
5398
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",
5399
5501
  gotFunctionVersions: "Retrieved the version list of function {fnName}",
5400
5502
  gotFunctionAlias: "Retrieved alias {aliasName} of function {fnName}",
5401
5503
  publishedVersion: "Published new version {version} of function {fnName}",
5402
5504
  updatedFunctionAlias: "Updated alias {aliasName} of function {fnName} (primary version {version})",
5403
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.",
5404
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).",
5405
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.",
5406
5510
  imageUpdatedMessage: "Updated the image of function {fnName} to {imageUri}. After deployment, use queryFunctions(action=\"getFunctionDetail\") to confirm the function is ready (Active).",
5407
5511
  updatedCode: "Updated the code of function {fnName}",
@@ -5467,12 +5571,12 @@ exports.functions = (0, types_js_1.defineModule)({
5467
5571
  "schema.create.layers": "Layer configuration",
5468
5572
  "schema.manageLayer.name": "Layer name",
5469
5573
  "schema.manageLayer.version": "Layer version number",
5470
- "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)",
5471
- "schema.query.functionName": "CloudBase cloud function name. Required for `getFunctionDetail`, `listFunctionLogs`, `listFunctionLayers`, `listFunctionTriggers`, `getFunctionDownloadUrl`, `listVersionByFunction`, and `getFunctionAlias`.",
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).",
5472
5576
  "schema.query.limit": "Page size (limit). Optional for list actions; the backend determines the default.",
5473
5577
  "schema.query.offset": "Pagination offset. Optional for list actions; defaults to 0.",
5474
5578
  "schema.query.codeSecret": "Code protection secret used to decrypt function code.",
5475
- "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.",
5476
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.",
5477
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.",
5478
5582
  "schema.query.requestId": "Log request ID. Required for `getFunctionLogDetail`; obtain it from `listFunctionLogs`.",
@@ -5491,6 +5595,10 @@ exports.functions = (0, types_js_1.defineModule)({
5491
5595
  "schema.manage.force": "Whether createFunction overwrites an existing function.",
5492
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.",
5493
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",
5494
5602
  "schema.manage.handler": "Function entry point",
5495
5603
  "schema.manage.timeout": "Timeout used for configuration updates.",
5496
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.",
@@ -6119,6 +6227,7 @@ exports.logs = (0, types_js_1.defineModule)({
6119
6227
  "\n\n**重要区分**:" +
6120
6228
  "\n- 查询云函数日志:使用 `queryFunctions(action=\"listFunctionLogs\", functionName=\"xxx\")`" +
6121
6229
  "\n- 查询 CLS 日志(跨服务日志聚合):使用本工具 `queryLogs(action=\"searchLogs\")`" +
6230
+ "\n- 开通 CLS 日志服务:使用 `manageLogs(action=\"createLogService\", confirm=true)`" +
6122
6231
  "\n\n**适用场景**:" +
6123
6232
  "\n- 检查 CLS 日志服务是否开通:`action=\"checkLogService\"`" +
6124
6233
  "\n- 跨服务日志搜索(如搜索所有 ERROR 日志):`action=\"searchLogs\"`" +
@@ -6164,12 +6273,28 @@ exports.logs = (0, types_js_1.defineModule)({
6164
6273
  "schema.limit": "返回日志条数限制,默认 20",
6165
6274
  "schema.context": "翻页上下文,用于继续上一次查询",
6166
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}",
6167
6291
  }, {
6168
6292
  title: "Query CloudBase log service",
6169
6293
  description: "Unified read-only entry for the CloudBase logs domain. Supports checking log service status and searching CLS logs." +
6170
6294
  "\n\n**Important distinction**:" +
6171
6295
  "\n- Query cloud function logs: use `queryFunctions(action=\"listFunctionLogs\", functionName=\"xxx\")`" +
6172
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)`" +
6173
6298
  "\n\n**Use cases**:" +
6174
6299
  "\n- Check whether the CLS log service is enabled: `action=\"checkLogService\"`" +
6175
6300
  "\n- Cross-service log search (e.g. find all ERROR logs): `action=\"searchLogs\"`" +
@@ -6215,6 +6340,21 @@ exports.logs = (0, types_js_1.defineModule)({
6215
6340
  "schema.limit": "Maximum number of log entries to return; defaults to 20.",
6216
6341
  "schema.context": "Pagination context used to continue the previous query.",
6217
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}",
6218
6358
  });
6219
6359
 
6220
6360
 
@@ -6508,19 +6648,19 @@ exports.permissions = (0, types_js_1.defineModule)({
6508
6648
  "或 securityRule='{\"invoke\":true}'(放通所有云函数)。" +
6509
6649
  "底层错误:{message}",
6510
6650
  mustBeArray: "{label} 必须是数组",
6511
- 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)。",
6512
- 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。",
6513
6653
  createRuleSummary: "create 规则不应引用 doc.*,因为 create 时文档尚未存在。",
6514
6654
  createRuleDetail: "CloudBase 的 create 规则验证的是写入数据(request.data),此时文档尚不存在,doc.* 不可用。" +
6515
6655
  "请将 create 规则改为仅使用 auth.* 检查(如 auth.uid != null && auth.loginType != 'ANONYMOUS')," +
6516
6656
  "或在写入时将 owner 字段(如 _openid / authorId)写入 request.data,然后在 create 规则中用 request.data._openid == auth.openid 做校验。" +
6517
6657
  "read / update / delete 规则可以使用 doc.* 引用已有文档字段,且客户端查询条件必须是规则约束的子集(如 _openid: '{openid}')。",
6518
6658
  docIdWriteSummary: "当前安全规则在 document-id 写入场景下可能被后端直接拒绝。",
6519
- 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}`)``。",
6520
6660
  invalidGetPathSummary: "get() 的 path 只应包含 collection 和 documentId,不应把字段名拼进 path 字符串。",
6521
- 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。",
6522
- templateLiteralSummary: "CloudBase security rule 表达式不支持把 ${...} 当作 JS 模板字符串插值。",
6523
- 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 模式。",
6524
6664
  bucketMissing: "存储 Bucket {bucket} 不存在",
6525
6665
  bucketsMissing: "以下存储 Bucket 不存在: {buckets}",
6526
6666
  paramRequired: "action={action} 时必须提供 {param}",
@@ -6589,19 +6729,19 @@ exports.permissions = (0, types_js_1.defineModule)({
6589
6729
  "(package authz.user) or securityRule='{\"invoke\":true}' for public functions. " +
6590
6730
  "Underlying error: {message}",
6591
6731
  mustBeArray: "{label} must be an array",
6592
- 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).",
6593
- 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.",
6594
6734
  createRuleSummary: "The create rule should not reference doc.*, because the document does not exist yet at create time.",
6595
6735
  createRuleDetail: "CloudBase's create rule validates the written data (request.data); the document does not exist yet, so doc.* is unavailable. " +
6596
6736
  "Change the create rule to use only auth.* checks (e.g. auth.uid != null && auth.loginType != 'ANONYMOUS'), " +
6597
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. " +
6598
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}').",
6599
6739
  docIdWriteSummary: "The current security rule may be rejected by the backend in document-id write scenarios.",
6600
- 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}`)``.",
6601
6741
  invalidGetPathSummary: "The get() path should only contain the collection and documentId; do not concatenate field names into the path string.",
6602
- 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.",
6603
- templateLiteralSummary: "CloudBase security rule expressions do not support ${...} as JS template string interpolation.",
6604
- 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.",
6605
6745
  bucketMissing: "Storage bucket {bucket} does not exist",
6606
6746
  bucketsMissing: "The following storage buckets do not exist: {buckets}",
6607
6747
  paramRequired: "{param} is required when action={action}",
@@ -6852,6 +6992,7 @@ exports.setup = (0, types_js_1.defineModule)({
6852
6992
  "schema.template": "要下载的模板类型",
6853
6993
  "schema.ide": "指定要下载的IDE类型。",
6854
6994
  "schema.overwrite": "是否覆盖已存在的文件,默认为false(不覆盖)",
6995
+ "projectRoot.hostConfigDir": "拒绝把 {dir} 当作项目根目录。这是宿主配置目录,不是项目。请由宿主设置 WORKSPACE_FOLDER_PATHS 为项目目录后再试。",
6855
6996
  }, {
6856
6997
  "downloadTemplate.title": "Download project template",
6857
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)",
@@ -6916,6 +7057,7 @@ exports.setup = (0, types_js_1.defineModule)({
6916
7057
  "schema.template": "The type of template to download",
6917
7058
  "schema.ide": "The IDE type whose configuration should be downloaded.",
6918
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.",
6919
7061
  });
6920
7062
 
6921
7063
 
@@ -7123,6 +7265,7 @@ const msgPush_js_1 = __webpack_require__(6191);
7123
7265
  const setup_js_1 = __webpack_require__(8707);
7124
7266
  const envSetup_js_1 = __webpack_require__(7148);
7125
7267
  const interactive_js_1 = __webpack_require__(1838);
7268
+ const feedback_js_1 = __webpack_require__(9391);
7126
7269
  exports.zh = {
7127
7270
  env: env_js_1.env.zh,
7128
7271
  storage: storage_js_1.storage.zh,
@@ -7152,6 +7295,7 @@ exports.zh = {
7152
7295
  setup: setup_js_1.setup.zh,
7153
7296
  envSetup: envSetup_js_1.envSetup.zh,
7154
7297
  interactive: interactive_js_1.interactive.zh,
7298
+ feedback: feedback_js_1.feedback.zh,
7155
7299
  };
7156
7300
 
7157
7301
 
@@ -7270,6 +7414,7 @@ const apps_js_1 = __webpack_require__(8267);
7270
7414
  const logs_js_1 = __webpack_require__(1628);
7271
7415
  const permissions_js_1 = __webpack_require__(2639);
7272
7416
  const msg_push_js_1 = __webpack_require__(7707);
7417
+ const feedback_js_1 = __webpack_require__(3951);
7273
7418
  const index_js_1 = __webpack_require__(4908);
7274
7419
  const schema_js_1 = __webpack_require__(6273);
7275
7420
  const cloud_mode_js_1 = __webpack_require__(8694);
@@ -7299,6 +7444,7 @@ const DEFAULT_PLUGINS = [
7299
7444
  "logs",
7300
7445
  "agents",
7301
7446
  "capi",
7447
+ "feedback",
7302
7448
  ];
7303
7449
  function registerDatabase(server) {
7304
7450
  // NoSQL 数据库按站点能力集合注册(国际站默认不支持 NoSQL)
@@ -7348,6 +7494,7 @@ const AVAILABLE_PLUGINS = {
7348
7494
  deploy: { name: "deploy", register: deploy_js_1.registerDeployTools },
7349
7495
  capi: { name: "capi", register: capi_js_1.registerCapiTools },
7350
7496
  "msg-push": { name: "msg-push", register: msg_push_js_1.registerMsgPushTools },
7497
+ feedback: { name: "feedback", register: feedback_js_1.registerFeedbackTools },
7351
7498
  };
7352
7499
  const PLUGIN_ALIASES = {
7353
7500
  "access-control": "permissions",
@@ -9832,6 +9979,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9832
9979
  Object.defineProperty(exports, "__esModule", ({ value: true }));
9833
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;
9834
9981
  exports.maskCloudRunDetailEnvParams = maskCloudRunDetailEnvParams;
9982
+ exports.validateAndNormalizePath = validateAndNormalizePath;
9835
9983
  exports.resolveCloudRunProjectDir = resolveCloudRunProjectDir;
9836
9984
  exports.buildManageCloudRunErrorMessage = buildManageCloudRunErrorMessage;
9837
9985
  exports.isValidCloudRunBuildId = isValidCloudRunBuildId;
@@ -9858,6 +10006,7 @@ const zod_1 = __webpack_require__(2971);
9858
10006
  const cloudbase_manager_js_1 = __webpack_require__(3109);
9859
10007
  const index_js_1 = __webpack_require__(4908);
9860
10008
  const logger_js_1 = __webpack_require__(781);
10009
+ const project_config_js_1 = __webpack_require__(9175);
9861
10010
  const gateway_access_urls_js_1 = __webpack_require__(4173);
9862
10011
  const notification_js_1 = __webpack_require__(4718);
9863
10012
  const capi_js_1 = __webpack_require__(8900);
@@ -10062,31 +10211,20 @@ function checkIfAgentProject(projectPath) {
10062
10211
  }
10063
10212
  }
10064
10213
  /**
10065
- * Validate and normalize file path.
10066
- * Accepts absolute paths as-is; for relative paths, resolves against CWD and
10067
- * ensures the result does not escape the CWD (path-traversal protection).
10068
- * @param inputPath User provided path
10069
- * @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.
10070
10217
  */
10071
10218
  function validateAndNormalizePath(inputPath) {
10072
- const normalizedPath = path_1.default.resolve(inputPath);
10073
- // On Windows, path.resolve may return a path on a different drive/UNC share.
10074
- // That is safe — the user explicitly provided an absolute path there.
10075
- // Only apply the traversal check when the resolved path shares the same root
10076
- // as CWD (i.e. the path was relative or on the same drive).
10077
- const cwd = process.cwd();
10078
- const cwdRoot = path_1.default.parse(cwd).root;
10079
- const pathRoot = path_1.default.parse(normalizedPath).root;
10080
- if (cwdRoot === pathRoot) {
10081
- // Same filesystem root — ensure the resolved path is still inside CWD
10082
- // (or is exactly CWD) to block "../" traversal.
10083
- const prefix = cwd.endsWith(path_1.default.sep) ? cwd : cwd + path_1.default.sep;
10084
- if (!normalizedPath.startsWith(prefix) && normalizedPath !== cwd) {
10085
- throw new Error((0, index_js_1.t)("cloudrun.error.pathOutsideCwd", { cwd }));
10086
- }
10087
- }
10088
- // Cross-root absolute paths (e.g. D:\ on Windows when CWD is C:\) are
10089
- // 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
+ }
10090
10228
  return normalizedPath;
10091
10229
  }
10092
10230
  /**
@@ -14515,6 +14653,7 @@ const zod_1 = __webpack_require__(2971);
14515
14653
  const cloudbase_manager_js_1 = __webpack_require__(3109);
14516
14654
  const env_js_1 = __webpack_require__(6504);
14517
14655
  const index_js_1 = __webpack_require__(4908);
14656
+ const project_config_js_1 = __webpack_require__(9175);
14518
14657
  const tool_result_js_1 = __webpack_require__(9645);
14519
14658
  const sql_risk_js_1 = __webpack_require__(9885);
14520
14659
  const CATEGORY = "PostgreSQL database";
@@ -14799,19 +14938,7 @@ function validateMigrationName(name, actionLabel) {
14799
14938
  return null;
14800
14939
  }
14801
14940
  function getMigrationProjectRoot() {
14802
- const fromEnv = process.env.WORKSPACE_FOLDER_PATHS ||
14803
- process.env.PROJECT_ROOT ||
14804
- process.env.GITHUB_WORKSPACE ||
14805
- process.env.CI_PROJECT_DIR ||
14806
- process.env.BUILD_SOURCESDIRECTORY;
14807
- if (fromEnv && fromEnv.trim()) {
14808
- // IDEs may inject multiple folders separated by path.delimiter.
14809
- const first = fromEnv.split(path.delimiter).map((p) => p.trim()).find(Boolean);
14810
- if (first) {
14811
- return first;
14812
- }
14813
- }
14814
- return process.cwd();
14941
+ return (0, project_config_js_1.requireProjectRoot)();
14815
14942
  }
14816
14943
  function buildLocalMigrationFileName(version, name) {
14817
14944
  return `${version}_${name}.sql`;
@@ -17186,7 +17313,17 @@ const QUERY_ACTIONS = [
17186
17313
  "getInstanceInfo",
17187
17314
  "describeInstance",
17188
17315
  "getConnectionInfo",
17316
+ "describeInstanceSlowQueries",
17317
+ "describeInstanceErrorLogs",
17318
+ ];
17319
+ const SLOW_QUERY_ORDER_BY = [
17320
+ "QueryTime",
17321
+ "LockTime",
17322
+ "RowsExamined",
17323
+ "RowsSent",
17189
17324
  ];
17325
+ const ERROR_LOG_LEVELS = ["error", "warning", "note"];
17326
+ const ORDER_BY_TYPE = ["asc", "desc", "ASC", "DESC"];
17190
17327
  const MANAGE_ACTIONS = [
17191
17328
  "provisionMySQL",
17192
17329
  "destroyMySQL",
@@ -17693,6 +17830,138 @@ async function handleGetConnectionInfo(context) {
17693
17830
  ],
17694
17831
  });
17695
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
+ }
17696
17965
  async function handleProvisionMySQL(args, context) {
17697
17966
  if (args.confirm !== true) {
17698
17967
  return buildSqlToolResult({
@@ -18063,6 +18332,54 @@ function registerSQLDatabaseTools(server) {
18063
18332
  })
18064
18333
  .optional()
18065
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"),
18066
18383
  },
18067
18384
  annotations: {
18068
18385
  readOnlyHint: true,
@@ -18086,6 +18403,10 @@ function registerSQLDatabaseTools(server) {
18086
18403
  return handleGetInstanceInfo(context);
18087
18404
  case "getConnectionInfo":
18088
18405
  return handleGetConnectionInfo(context);
18406
+ case "describeInstanceSlowQueries":
18407
+ return handleDescribeInstanceSlowQueries(args, context);
18408
+ case "describeInstanceErrorLogs":
18409
+ return handleDescribeInstanceErrorLogs(args, context);
18089
18410
  default:
18090
18411
  throw new Error((0, index_js_1.t)("databaseSQL.unsupportedQueryAction", { action: args.action }));
18091
18412
  }
@@ -18182,6 +18503,7 @@ const zod_1 = __webpack_require__(2971);
18182
18503
  const cloudbase_manager_js_1 = __webpack_require__(3109);
18183
18504
  const index_js_1 = __webpack_require__(4908);
18184
18505
  const json_content_js_1 = __webpack_require__(8027);
18506
+ const project_config_js_1 = __webpack_require__(9175);
18185
18507
  const sql_risk_js_1 = __webpack_require__(9885);
18186
18508
  const hosting_build_utils_js_1 = __webpack_require__(7572);
18187
18509
  // 声明式部署可编排的资源类型,与 DeployOrchestrator 的部署顺序一致:
@@ -18446,7 +18768,7 @@ function registerDeployTools(server) {
18446
18768
  },
18447
18769
  }, async ({ cwd, mode }) => {
18448
18770
  try {
18449
- const projectRoot = cwd ?? process.cwd();
18771
+ const projectRoot = (0, project_config_js_1.requireProjectRoot)(cwd);
18450
18772
  const config = await resolveDeployConfig({ cwd: projectRoot, mode });
18451
18773
  assertConfigValid(config);
18452
18774
  const hostingItems = Array.isArray(config.hosting)
@@ -18518,7 +18840,7 @@ function registerDeployTools(server) {
18518
18840
  },
18519
18841
  }, async ({ cwd, mode, envId: envIdInput, only, skip, yes, }) => {
18520
18842
  try {
18521
- const projectRoot = cwd ?? process.cwd();
18843
+ const projectRoot = (0, project_config_js_1.requireProjectRoot)(cwd);
18522
18844
  const config = await resolveDeployConfig({ cwd: projectRoot, mode });
18523
18845
  assertConfigValid(config);
18524
18846
  const envId = await resolveDeployEnvId({
@@ -18602,7 +18924,7 @@ function registerDeployTools(server) {
18602
18924
  if (confirm !== true) {
18603
18925
  throw new DeployError(exports.DEPLOY_ERROR_CODES.CONFIRM_REQUIRED, (0, index_js_1.t)("deploy.confirmRequired"));
18604
18926
  }
18605
- const projectRoot = cwd ?? process.cwd();
18927
+ const projectRoot = (0, project_config_js_1.requireProjectRoot)(cwd);
18606
18928
  const config = await resolveDeployConfig({ cwd: projectRoot, mode });
18607
18929
  assertConfigValid(config);
18608
18930
  const envId = await resolveDeployEnvId({
@@ -22538,6 +22860,507 @@ function registerEnvTools(server) {
22538
22860
  }
22539
22861
 
22540
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
+
22541
23364
  /***/ },
22542
23365
 
22543
23366
  /***/ 4931
@@ -23924,6 +24747,7 @@ const logger_js_1 = __webpack_require__(781);
23924
24747
  const tool_result_js_1 = __webpack_require__(9645);
23925
24748
  const function_deploy_js_1 = __webpack_require__(9151);
23926
24749
  const function_deploy_schema_js_1 = __webpack_require__(6427);
24750
+ const function_cos_upload_js_1 = __webpack_require__(5735);
23927
24751
  const function_updating_js_1 = __webpack_require__(326);
23928
24752
  const index_js_1 = __webpack_require__(4908);
23929
24753
  const fs_1 = __webpack_require__(4421);
@@ -24005,6 +24829,7 @@ exports.QUERY_FUNCTION_ACTIONS = [
24005
24829
  "getFunctionDeployStatus",
24006
24830
  "listVersionByFunction",
24007
24831
  "getFunctionAlias",
24832
+ "getFunctionUploadUrl",
24008
24833
  ];
24009
24834
  exports.MANAGE_FUNCTION_ACTIONS = [
24010
24835
  "createFunction",
@@ -24184,6 +25009,25 @@ const MANAGE_LAYER_SCHEMA = zod_1.z.object({
24184
25009
  layerName: zod_1.z.string().describe("functions.schema.manageLayer.name"),
24185
25010
  layerVersion: zod_1.z.number().describe("functions.schema.manageLayer.version"),
24186
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();
24187
25031
  const FUNCTION_VERSION_WEIGHT_SCHEMA = zod_1.z.object({
24188
25032
  Version: zod_1.z.string().describe("functions.schema.routing.version"),
24189
25033
  Weight: zod_1.z.number().describe("functions.schema.routing.weight"),
@@ -24383,6 +25227,48 @@ function registerFunctionTools(server) {
24383
25227
  throw new Error((0, index_js_1.t)("functions.confirmRequired", { action }));
24384
25228
  }
24385
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
+ };
24386
25272
  const ensureActionAllowedInCloudMode = (input) => {
24387
25273
  if (!(0, cloud_mode_js_1.isCloudMode)()) {
24388
25274
  return;
@@ -24397,6 +25283,11 @@ function registerFunctionTools(server) {
24397
25283
  if (hasImageDeploy) {
24398
25284
  return;
24399
25285
  }
25286
+ // 两段式部署阶段 B:代码包已上传到环境 COS 桶,全程不依赖本地目录,
25287
+ // 与镜像部署同属可在 cloud mode 下真实执行的路径。
25288
+ if (Boolean(input.code)) {
25289
+ return;
25290
+ }
24400
25291
  throw new Error((0, index_js_1.t)("functions.cloudMode.localOnly", { action: input.action }));
24401
25292
  }
24402
25293
  if (input.action === "createLayerVersion" && input.contentPath) {
@@ -24615,7 +25506,13 @@ function registerFunctionTools(server) {
24615
25506
  }
24616
25507
  const cloudbase = await getManager();
24617
25508
  const result = await cloudbase.functions.getFunctionDetail(input.functionName, input.codeSecret);
24618
- (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);
24619
25516
  const layers = normalizeFunctionLayers(result.Layers);
24620
25517
  return buildEnvelope({
24621
25518
  action: input.action,
@@ -24623,7 +25520,7 @@ function registerFunctionTools(server) {
24623
25520
  layers,
24624
25521
  count: layers.length,
24625
25522
  requestId: result.RequestId,
24626
- raw: result,
25523
+ raw: detail,
24627
25524
  }, (0, index_js_1.t)("functions.gotFunctionLayers", { fnName: input.functionName }), [
24628
25525
  {
24629
25526
  tool: "manageFunctions",
@@ -24843,6 +25740,44 @@ function registerFunctionTools(server) {
24843
25740
  },
24844
25741
  ]);
24845
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
+ }
24846
25781
  default:
24847
25782
  throw new Error((0, index_js_1.t)("functions.unsupportedAction", { action: input.action }));
24848
25783
  }
@@ -25099,6 +26034,63 @@ function registerFunctionTools(server) {
25099
26034
  },
25100
26035
  ]);
25101
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
+ }
25102
26094
  if (func.type !== "HTTP") {
25103
26095
  const originalRuntime = typeof func.runtime === "string" ? func.runtime : undefined;
25104
26096
  func.runtime = resolveEventFunctionRuntime(func.runtime);
@@ -25307,6 +26299,58 @@ function registerFunctionTools(server) {
25307
26299
  },
25308
26300
  ]);
25309
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
+ }
25310
26354
  const processedRootPath = processFunctionRootPath(input.functionRootPath, input.functionName);
25311
26355
  const updateParams = {
25312
26356
  func: {
@@ -25857,6 +26901,7 @@ function registerFunctionTools(server) {
25857
26901
  .optional()
25858
26902
  .describe("functions.schema.manage.functionName"),
25859
26903
  zipFile: zod_1.z.string().optional().describe("functions.schema.manage.zipFile"),
26904
+ code: FUNCTION_CODE_SCHEMA.optional().describe("functions.schema.manage.code"),
25860
26905
  handler: zod_1.z.string().optional().describe("functions.schema.manage.handler"),
25861
26906
  timeout: zod_1.z.number().optional().describe("functions.schema.manage.timeout"),
25862
26907
  envVariables: zod_1.z
@@ -28492,18 +29537,23 @@ const cloudbase_manager_js_1 = __webpack_require__(3109);
28492
29537
  const json_content_js_1 = __webpack_require__(8027);
28493
29538
  const index_js_1 = __webpack_require__(4908);
28494
29539
  const QUERY_LOG_ACTIONS = ["checkLogService", "searchLogs"];
28495
- function buildEnvelope(data, message) {
29540
+ const MANAGE_LOG_ACTIONS = ["createLogService"];
29541
+ function buildEnvelope(data, message, extras) {
28496
29542
  return {
28497
29543
  success: true,
28498
29544
  data,
28499
29545
  message,
29546
+ ...extras,
28500
29547
  };
28501
29548
  }
28502
- function buildErrorEnvelope(error) {
29549
+ function buildErrorEnvelope(error, extras) {
28503
29550
  return {
28504
29551
  success: false,
28505
- data: {},
28506
- 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,
28507
29557
  };
28508
29558
  }
28509
29559
  function registerLogTools(server) {
@@ -28576,6 +29626,89 @@ function registerLogTools(server) {
28576
29626
  return (0, json_content_js_1.jsonContent)(buildErrorEnvelope(error));
28577
29627
  }
28578
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
+ });
28579
29712
  }
28580
29713
 
28581
29714
 
@@ -29922,7 +31055,7 @@ function extractRiskyDocFieldOperations(securityRule) {
29922
31055
  continue;
29923
31056
  }
29924
31057
  const referencesNonIdDocField = /doc\.(?!_id\b)[A-Za-z_][A-Za-z0-9_]*/.test(expression);
29925
- 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);
29926
31059
  if (referencesNonIdDocField && !usesGetByDocId) {
29927
31060
  operations.push(operation);
29928
31061
  }
@@ -29932,8 +31065,8 @@ function extractRiskyDocFieldOperations(securityRule) {
29932
31065
  function buildRecommendedOwnerWriteRule(resourceId) {
29933
31066
  return JSON.stringify({
29934
31067
  create: "auth.uid != null",
29935
- update: "auth.uid != null && (get('database.user_roles.' + auth.uid).role == 'admin' || doc.authorId == auth.uid)",
29936
- 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)",
29937
31070
  });
29938
31071
  }
29939
31072
  function buildRoleLookupNote() {
@@ -29995,7 +31128,9 @@ function buildInvalidGetPathHint(securityRule, resourceId) {
29995
31128
  if (!securityRule) {
29996
31129
  return undefined;
29997
31130
  }
29998
- 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);
29999
31134
  if (!hasFieldEmbeddedInsideGetPath) {
30000
31135
  return undefined;
30001
31136
  }
@@ -30015,7 +31150,9 @@ function buildTemplateLiteralRuleHint(securityRule, resourceId) {
30015
31150
  if (!securityRule) {
30016
31151
  return undefined;
30017
31152
  }
30018
- 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);
30019
31156
  if (!usesTemplateLiteralPlaceholderInRule) {
30020
31157
  return undefined;
30021
31158
  }
@@ -31549,6 +32686,7 @@ const url_1 = __webpack_require__(6887);
31549
32686
  const zod_1 = __webpack_require__(2971);
31550
32687
  const index_js_1 = __webpack_require__(4908);
31551
32688
  const remote_url_safety_js_1 = __webpack_require__(3694);
32689
+ const project_config_js_1 = __webpack_require__(9175);
31552
32690
  // CloudBase 模板配置
31553
32691
  const TEMPLATES = {
31554
32692
  react: {
@@ -32034,6 +33172,23 @@ function registerSetupTools(server) {
32034
33172
  };
32035
33173
  }
32036
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
+ }
32037
33192
  // 验证IDE类型
32038
33193
  const ideValidation = validateIDE(resolvedIDE);
32039
33194
  if (!ideValidation.valid) {
@@ -32071,7 +33226,6 @@ function registerSetupTools(server) {
32071
33226
  // 创建过滤后的目录结构(当选择特定IDE时)
32072
33227
  const workingDir = await createFilteredDirectory(extractDir, filteredFiles, resolvedIDE);
32073
33228
  // 检查是否需要复制到项目目录
32074
- const workspaceFolder = process.env.WORKSPACE_FOLDER_PATHS || process.cwd();
32075
33229
  let finalFiles = [];
32076
33230
  let createdCount = 0;
32077
33231
  let overwrittenCount = 0;
@@ -33274,6 +34428,143 @@ function resolveRequestId(error) {
33274
34428
  }
33275
34429
 
33276
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
+
33277
34568
  /***/ },
33278
34569
 
33279
34570
  /***/ 4173
@@ -33738,14 +35029,101 @@ async function sendDeployNotification(server, notificationData) {
33738
35029
  var __webpack_unused_export__;
33739
35030
 
33740
35031
  __webpack_unused_export__ = ({ value: true });
35032
+ exports.ProjectRootError = void 0;
35033
+ exports.resolveProjectRoot = resolveProjectRoot;
35034
+ exports.requireProjectRoot = requireProjectRoot;
33741
35035
  exports.readCloudbaseRcBinding = readCloudbaseRcBinding;
33742
35036
  exports.readProjectConfig = readProjectConfig;
33743
35037
  exports.readProjectEnvId = readProjectEnvId;
33744
35038
  exports.writeProjectConfig = writeProjectConfig;
33745
35039
  const node_fs_1 = __webpack_require__(9627);
35040
+ const node_os_1 = __webpack_require__(6674);
33746
35041
  const node_path_1 = __webpack_require__(5663);
33747
35042
  const toolbox_1 = __webpack_require__(2090);
35043
+ const index_js_1 = __webpack_require__(4908);
33748
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
+ }
33749
35127
  /**
33750
35128
  * 解析 cloudbaserc.json 字段值用于绑定(fail-safe:解析不出一律返回 undefined 回落下一级):
33751
35129
  * - 字面量 → trim 后直接返回
@@ -33803,7 +35181,9 @@ function resolveBindingValue(raw, projectRoot) {
33803
35181
  */
33804
35182
  function readCloudbaseRcBinding(cwd) {
33805
35183
  try {
33806
- const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
35184
+ const projectRoot = projectRootForConfig(cwd);
35185
+ if (!projectRoot)
35186
+ return undefined;
33807
35187
  const configPath = (0, node_path_1.join)(projectRoot, CLOUDBASE_RC_FILENAME);
33808
35188
  if (!(0, node_fs_1.existsSync)(configPath)) {
33809
35189
  return undefined;
@@ -33837,7 +35217,9 @@ function readCloudbaseRcBinding(cwd) {
33837
35217
  */
33838
35218
  function readProjectConfig(cwd) {
33839
35219
  try {
33840
- const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
35220
+ const projectRoot = projectRootForConfig(cwd);
35221
+ if (!projectRoot)
35222
+ return undefined;
33841
35223
  const configPath = (0, node_path_1.join)(projectRoot, ".cloudbase", "project.json");
33842
35224
  if (!(0, node_fs_1.existsSync)(configPath)) {
33843
35225
  return undefined;
@@ -33885,7 +35267,9 @@ function readProjectEnvId(cwd) {
33885
35267
  */
33886
35268
  function writeProjectConfig(patch, cwd) {
33887
35269
  try {
33888
- const projectRoot = cwd ?? process.env.WORKSPACE_FOLDER_PATHS ?? process.cwd();
35270
+ const projectRoot = projectRootForConfig(cwd);
35271
+ if (!projectRoot)
35272
+ return false;
33889
35273
  const configPath = (0, node_path_1.join)(projectRoot, ".cloudbase", "project.json");
33890
35274
  let existing = {};
33891
35275
  if ((0, node_fs_1.existsSync)(configPath)) {
@@ -34110,6 +35494,7 @@ var __webpack_unused_export__;
34110
35494
 
34111
35495
  __webpack_unused_export__ = ({ value: true });
34112
35496
  exports.iA = void 0;
35497
+ exports.getRepeatGuardSnapshot = getRepeatGuardSnapshot;
34113
35498
  exports.applyRepeatGuardToPayload = applyRepeatGuardToPayload;
34114
35499
  exports.resetRepeatGuard = resetRepeatGuard;
34115
35500
  __webpack_unused_export__ = __resetRepeatGuardForTests;
@@ -34128,6 +35513,13 @@ exports.iA = 3;
34128
35513
  const REPEAT_GUARD_KEY_MAX_LENGTH = 200;
34129
35514
  let lastKey = null;
34130
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
+ }
34131
35523
  function buildRepeatGuardKey(payload) {
34132
35524
  const code = typeof payload.code === "string" ? payload.code : "";
34133
35525
  const message = typeof payload.message === "string" ? payload.message : "";
@@ -34599,7 +35991,7 @@ class TelemetryReporter {
34599
35991
  const arch = os_1.default.arch(); // 系统架构
34600
35992
  // Build-time injected version; guard for vitest / non-webpack runtimes.
34601
35993
  const mcpVersion = process.env.npm_package_version ||
34602
- ( true ? "2.34.6" : 0);
35994
+ ( true ? "2.34.7" : 0);
34603
35995
  return {
34604
35996
  userAgent: `${osType} ${osRelease} ${arch} ${nodeVersion} CloudBase-MCP/${mcpVersion}`,
34605
35997
  deviceId: this.deviceId,
@@ -35105,7 +36497,7 @@ var __webpack_unused_export__;
35105
36497
  __webpack_unused_export__ = ({ value: true });
35106
36498
  exports.ToolPayloadError = void 0;
35107
36499
  exports.buildJsonToolResult = buildJsonToolResult;
35108
- __webpack_unused_export__ = isBusinessFailureToolResult;
36500
+ exports.isBusinessFailureToolResult = isBusinessFailureToolResult;
35109
36501
  exports.withBusinessFailureIsError = withBusinessFailureIsError;
35110
36502
  exports.buildTextErrorResult = buildTextErrorResult;
35111
36503
  exports.isToolPayloadError = isToolPayloadError;
@@ -35246,6 +36638,7 @@ const logger_js_1 = __webpack_require__(781);
35246
36638
  const telemetry_js_1 = __webpack_require__(5198);
35247
36639
  const tool_result_js_1 = __webpack_require__(9645);
35248
36640
  const repeat_error_guard_js_1 = __webpack_require__(13);
36641
+ const feedback_session_js_1 = __webpack_require__(3379);
35249
36642
  const error_guidance_js_1 = __webpack_require__(1194);
35250
36643
  /**
35251
36644
  * Mirror annotations.category into _meta.category.
@@ -35321,7 +36714,7 @@ ${envIdSection}
35321
36714
  ## 环境信息
35322
36715
  - 操作系统: ${os_1.default.type()} ${os_1.default.release()}
35323
36716
  - Node.js版本: ${process.version}
35324
- - MCP 版本:${( true ? "2.34.6" : 0) || 0 || 0}
36717
+ - MCP 版本:${( true ? "2.34.7" : 0) || 0 || 0}
35325
36718
  - 系统架构: ${os_1.default.arch()}
35326
36719
  - 时间: ${new Date().toISOString()}
35327
36720
  - 请求ID: ${requestId}
@@ -35355,6 +36748,8 @@ function createWrappedHandler(name, handler, server) {
35355
36748
  return async (args) => {
35356
36749
  const startTime = Date.now();
35357
36750
  let success = false;
36751
+ let businessFailed = false;
36752
+ let repeatCountSeen = 0;
35358
36753
  let errorMessage;
35359
36754
  let requestId;
35360
36755
  try {
@@ -35366,7 +36761,11 @@ function createWrappedHandler(name, handler, server) {
35366
36761
  }
35367
36762
  // 执行原始处理函数
35368
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);
35369
36767
  success = true;
36768
+ repeatCountSeen = (0, repeat_error_guard_js_1.getRepeatGuardSnapshot)().consecutiveCount;
35370
36769
  // 任一工具成功说明重复错误循环已被打破,清零连续错误计数
35371
36770
  (0, repeat_error_guard_js_1.resetRepeatGuard)();
35372
36771
  requestId = extractRequestIdFromToolResult(result);
@@ -35399,8 +36798,11 @@ function createWrappedHandler(name, handler, server) {
35399
36798
  if ((0, tool_result_js_1.isToolPayloadError)(error)) {
35400
36799
  // 连续相同结构化错误达到阈值时注入 repeat_guard 升级提示,
35401
36800
  // 打断无头客户端的原样重试循环(不改写 message,保持遥测聚合稳定)
35402
- 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);
35403
36804
  }
36805
+ repeatCountSeen = (0, repeat_error_guard_js_1.getRepeatGuardSnapshot)().consecutiveCount;
35404
36806
  // In tests, avoid any extra work that may block (envId lookup, issue link generation, etc.)
35405
36807
  if (isTestEnvironment) {
35406
36808
  throw error instanceof Error ? error : new Error(String(error));
@@ -35410,7 +36812,7 @@ function createWrappedHandler(name, handler, server) {
35410
36812
  requestId,
35411
36813
  ide: server.ide || process.env.INTEGRATION_IDE || ''
35412
36814
  });
35413
- const mcpVersion = true ? "2.34.6" : 0;
36815
+ const mcpVersion = true ? "2.34.7" : 0;
35414
36816
  const requestIdSuffix = requestId ? `\n🆔 RequestId: ${requestId}` : '';
35415
36817
  const enhancedErrorMessage = `${errorMessage}${requestIdSuffix}\n\n📦 CloudBase MCP v${mcpVersion}\n🔗 遇到问题?请复制以下链接到浏览器打开\n即可自动携带错误详情快速创建 GitHub Issue:\n${issueLink}`;
35416
36818
  // 创建新的错误对象,保持原有的错误类型但更新消息
@@ -35426,6 +36828,20 @@ function createWrappedHandler(name, handler, server) {
35426
36828
  throw enhancedError;
35427
36829
  }
35428
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
+ }
35429
36845
  // 上报工具调用数据(测试环境中跳过,避免阻塞)
35430
36846
  const isTestEnvironment = false || process.env.VITEST === "true";
35431
36847
  if (!isTestEnvironment) {
@@ -35693,7 +37109,7 @@ var x = (y) => {
35693
37109
  var x = {}; __webpack_require__.d(x, y); return x
35694
37110
  }
35695
37111
  var y = (x) => (() => (x))
35696
- 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) });
35697
37113
 
35698
37114
  /***/ },
35699
37115
 
@@ -35704,6 +37120,17 @@ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_75ed2103__;
35704
37120
 
35705
37121
  /***/ },
35706
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
+
35707
37134
  /***/ 5663
35708
37135
  (module) {
35709
37136