@sparkelf/dsh-dataops-managed 0.3.28 → 0.3.30

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/lib/index.js CHANGED
@@ -4,8 +4,8 @@ import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
4
  import * as McpClient from "@sparkelf/dsh-plugin-mcp-credentials";
5
5
  import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
6
6
  import z from "@deepseek-ai/schemastery";
7
- import { defineTool } from "@deepseek-ai/dsh-tools";
8
7
  import { basename, dirname, extname, join } from "node:path";
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
9
  import { randomUUID } from "node:crypto";
10
10
  //#region src/auth-state.ts
11
11
  let state = "unknown";
@@ -876,7 +876,32 @@ const AI_TOOL_ACCESS = {
876
876
  dataops_collect_plan: { permission: "data:resource:manage" },
877
877
  dataops_collect_execute: { permission: "data:resource:manage" },
878
878
  dataops_collect_resources: { permission: "data:resource:read" },
879
- dataops_open_resource_tab: {}
879
+ dataops_open_resource_tab: {},
880
+ dataops_resource_pending_list: {
881
+ capability: "resource.manage",
882
+ adminOnly: true,
883
+ defaultEnabled: true
884
+ },
885
+ dataops_resource_grant_list: {
886
+ capability: "resource.manage",
887
+ adminOnly: true,
888
+ defaultEnabled: true
889
+ },
890
+ dataops_resource_grant_batch: {
891
+ capability: "resource.manage",
892
+ adminOnly: true,
893
+ defaultEnabled: true
894
+ },
895
+ dataops_resource_approval_decide: {
896
+ capability: "resource.manage",
897
+ adminOnly: true,
898
+ defaultEnabled: true
899
+ },
900
+ dataops_resource_grant_revoke: {
901
+ capability: "resource.manage",
902
+ adminOnly: true,
903
+ defaultEnabled: true
904
+ }
880
905
  };
881
906
  /** Every managed tool name, in the order the manager considers them. */
882
907
  const AI_TOOL_NAMES = Object.keys(AI_TOOL_ACCESS);
@@ -938,9 +963,16 @@ const hasPermission = (scope, key) => {
938
963
  * Every check is disclosure metadata, not an execution gate: a visible tool still lets DataOps
939
964
  * answer with 403 when the underlying grant changed between a scope sync and the call.
940
965
  */
966
+ function isToolCapabilityEnabled(name, state) {
967
+ const policy = AI_TOOL_ACCESS[name];
968
+ if (policy.capability === void 0) return true;
969
+ if (!state.enabled) return false;
970
+ return state.capabilities[policy.capability] ?? policy.defaultEnabled ?? false;
971
+ }
941
972
  function isToolVisible(name, scope) {
942
973
  const policy = AI_TOOL_ACCESS[name];
943
974
  if (policy.superAdminOnly === true && !isSuperAdmin(scope)) return false;
975
+ if (policy.adminOnly === true && !isAdmin(scope)) return false;
944
976
  if (policy.reviewer === true && !canReview(scope)) return false;
945
977
  if (policy.permission !== void 0 && !hasPermission(scope, policy.permission)) return false;
946
978
  return true;
@@ -984,6 +1016,141 @@ function normalizeScope(body) {
984
1016
  };
985
1017
  }
986
1018
  //#endregion
1019
+ //#region src/connector-state.ts
1020
+ /**
1021
+ * The DataOps connector's workspace-visible state and skill-center catalogue.
1022
+ *
1023
+ * The skill center is skill-first, with connectors as its fourth tab. DataOps contributes one
1024
+ * connector whose capability rows are derived from the same scope that drives tool disclosure;
1025
+ * a capability the account cannot use is omitted rather than rendered as a disabled placeholder.
1026
+ *
1027
+ * This module owns only state and presentation. It never authorizes a tool call or a DataOps
1028
+ * request: the backend remains the final boundary.
1029
+ *
1030
+ * @module connector-state
1031
+ */
1032
+ /** Same-origin route the skill center's connector tab reads and writes. */
1033
+ const CONNECTORS_PATH = "/api/dsh-skill-center/connectors";
1034
+ /** Connector id shown in the skill center. */
1035
+ const DATAOPS_CONNECTOR_ID = "dataops-managed";
1036
+ /** Resolve the persisted state file without depending on a global DSH path. */
1037
+ const CONNECTOR_STATE_PATH = join(process.env.DSH_HOME?.trim() || "/workspace/.dataops/dsh", "dataops-managed", "connector-state.json");
1038
+ /**
1039
+ * Capability definitions before permission filtering.
1040
+ *
1041
+ * The set follows `dataops/docs/dataops-connector-development-spec.md` §2.3's credential list.
1042
+ * `approval.push` was renamed to `resource.manage` when the capability grew from approval push
1043
+ * into resource approval and authorization. Skill plaza and review queue are governed by
1044
+ * `skill:*` permissions and stay out of the connector's capability switches.
1045
+ */
1046
+ const CAPABILITIES = [
1047
+ {
1048
+ id: "data.query",
1049
+ name: "数据查询",
1050
+ description: "通过 DataOps 数据查询能力回答业务问题",
1051
+ defaultEnabled: true,
1052
+ visible: () => true,
1053
+ allowed: () => true
1054
+ },
1055
+ {
1056
+ id: "resource.manage",
1057
+ name: "资源管理",
1058
+ description: "在对话中批量审批资源申请,给用户或角色授予资源访问权限",
1059
+ defaultEnabled: true,
1060
+ visible: (scope) => isAdmin(scope),
1061
+ allowed: (scope) => isAdmin(scope)
1062
+ },
1063
+ {
1064
+ id: "admin.manage",
1065
+ name: "万相中台管理",
1066
+ description: "登录万相中台后台执行管理动作",
1067
+ defaultEnabled: true,
1068
+ visible: (scope) => isAdmin(scope),
1069
+ allowed: (scope) => isAdmin(scope)
1070
+ }
1071
+ ];
1072
+ /**
1073
+ * Persisted ids that moved to a new capability id.
1074
+ *
1075
+ * `approval.push` shipped before the capability grew from approval push into resource
1076
+ * approval and authorization. Its stored toggle carries over to `resource.manage`; when both
1077
+ * keys are present the current id wins.
1078
+ */
1079
+ const CAPABILITY_ALIASES = { "approval.push": "resource.manage" };
1080
+ /** The ids the catalogue accepts; any other persisted key is a legacy value. */
1081
+ const CAPABILITY_IDS = CAPABILITIES.map((capability) => capability.id);
1082
+ /**
1083
+ * Keep only boolean values for known capability ids.
1084
+ *
1085
+ * A state file written before the catalogue changed may still hold retired ids. Those keys are
1086
+ * ignored rather than treated as a corrupt file; a missing new key takes the capability's
1087
+ * `defaultEnabled`.
1088
+ * @param value - the `capabilities` member of a parsed state file.
1089
+ * @returns the readable toggles, keyed by current capability id.
1090
+ */
1091
+ function migrateCapabilities(value) {
1092
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
1093
+ const stored = value;
1094
+ const capabilities = {};
1095
+ for (const id of CAPABILITY_IDS) if (typeof stored[id] === "boolean") capabilities[id] = stored[id];
1096
+ for (const [legacyId, id] of Object.entries(CAPABILITY_ALIASES)) if (capabilities[id] === void 0 && typeof stored[legacyId] === "boolean") capabilities[id] = stored[legacyId];
1097
+ return capabilities;
1098
+ }
1099
+ /** Read state; a missing or corrupt file is a safe disabled state. */
1100
+ async function readConnectorState(path = CONNECTOR_STATE_PATH) {
1101
+ try {
1102
+ const payload = JSON.parse(await readFile(path, "utf8"));
1103
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return {
1104
+ enabled: false,
1105
+ capabilities: {}
1106
+ };
1107
+ const record = payload;
1108
+ return {
1109
+ enabled: record.enabled === true,
1110
+ capabilities: migrateCapabilities(record.capabilities)
1111
+ };
1112
+ } catch {
1113
+ return {
1114
+ enabled: false,
1115
+ capabilities: {}
1116
+ };
1117
+ }
1118
+ }
1119
+ /** Persist state atomically. */
1120
+ async function writeConnectorState(state, path = CONNECTOR_STATE_PATH) {
1121
+ await mkdir(dirname(path), { recursive: true });
1122
+ const temporary = path + ".tmp-" + process.pid.toString();
1123
+ const payload = {
1124
+ enabled: state.enabled,
1125
+ capabilities: migrateCapabilities(state.capabilities)
1126
+ };
1127
+ await writeFile(temporary, JSON.stringify(payload, null, 2), "utf8");
1128
+ await rename(temporary, path);
1129
+ }
1130
+ /** Build the connector row for one current scope. */
1131
+ function buildConnectorView(scope, state) {
1132
+ const capabilities = scope === void 0 ? [] : CAPABILITIES.filter((capability) => capability.visible(scope) && capability.allowed(scope)).map((capability) => ({
1133
+ id: capability.id,
1134
+ name: capability.name,
1135
+ description: capability.description,
1136
+ enabled: state.capabilities[capability.id] ?? capability.defaultEnabled,
1137
+ permitted: true
1138
+ }));
1139
+ return {
1140
+ id: DATAOPS_CONNECTOR_ID,
1141
+ name: "万相AI中台连接器",
1142
+ vendor: "DataOps",
1143
+ description: "把万相AI中台的技能、审核和数据能力接入当前工作区。",
1144
+ enabled: state.enabled,
1145
+ connected: scope !== void 0,
1146
+ capabilities
1147
+ };
1148
+ }
1149
+ /** Whether one capability id is in the fixed catalogue. */
1150
+ function hasCapability(id) {
1151
+ return CAPABILITIES.some((capability) => capability.id === id);
1152
+ }
1153
+ //#endregion
987
1154
  //#region src/collect-api.ts
988
1155
  /**
989
1156
  * DataOps spreadsheet-import transport for the collection skill.
@@ -1011,7 +1178,7 @@ const statusError = (result, operation) => {
1011
1178
  if (result.status === 403) return /* @__PURE__ */ new Error("Forbidden (403): " + (reason || "the current role may not import resources"));
1012
1179
  return /* @__PURE__ */ new Error(`${operation} failed: HTTP ${result.status}${reason ? ": " + reason : ""}`);
1013
1180
  };
1014
- const unwrap = (result, operation) => {
1181
+ const unwrap$1 = (result, operation) => {
1015
1182
  if (result.status < 200 || result.status >= 300) throw statusError(result, operation);
1016
1183
  return result.body;
1017
1184
  };
@@ -1045,11 +1212,11 @@ var CollectApi = class {
1045
1212
  method: "POST",
1046
1213
  body: form
1047
1214
  });
1048
- return unwrap(result, "spreadsheet preview");
1215
+ return unwrap$1(result, "spreadsheet preview");
1049
1216
  }
1050
1217
  async dataSources() {
1051
1218
  const result = await this.reviewApi.request("/api/resources/spreadsheet-import/data-sources", { method: "GET" });
1052
- const body = unwrap(result, "import data sources");
1219
+ const body = unwrap$1(result, "import data sources");
1053
1220
  return Array.isArray(body.dataSources) ? body.dataSources : [];
1054
1221
  }
1055
1222
  async plan(payload) {
@@ -1057,18 +1224,18 @@ var CollectApi = class {
1057
1224
  method: "POST",
1058
1225
  body: JSON.stringify(payload)
1059
1226
  });
1060
- return unwrap(result, "spreadsheet plan");
1227
+ return unwrap$1(result, "spreadsheet plan");
1061
1228
  }
1062
1229
  async execute(payload) {
1063
1230
  const result = await this.reviewApi.request("/api/resources/spreadsheet-import/execute", {
1064
1231
  method: "POST",
1065
1232
  body: JSON.stringify(payload)
1066
1233
  });
1067
- return unwrap(result, "spreadsheet execute");
1234
+ return unwrap$1(result, "spreadsheet execute");
1068
1235
  }
1069
1236
  async listResources(query = "", limit = 20) {
1070
1237
  const result = await this.reviewApi.request("/api/resources", { method: "GET" });
1071
- const body = unwrap(result, "resource list");
1238
+ const body = unwrap$1(result, "resource list");
1072
1239
  const rows = Array.isArray(body.resources) ? body.resources : [];
1073
1240
  const keyword = query.trim().toLowerCase();
1074
1241
  return rows.filter((row) => row.resourceType === void 0 || row.resourceType === "TABLE").filter((row) => {
@@ -1082,6 +1249,72 @@ var CollectApi = class {
1082
1249
  }
1083
1250
  };
1084
1251
  //#endregion
1252
+ //#region src/resource-management-api.ts
1253
+ const reasonOf = (body) => {
1254
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return "";
1255
+ const record = body;
1256
+ if (typeof record.error === "string") return record.error;
1257
+ if (typeof record.message === "string") return record.message;
1258
+ const details = record.details;
1259
+ return Array.isArray(details?.errors) ? details.errors.filter((v) => typeof v === "string").join("; ") : "";
1260
+ };
1261
+ const unwrap = (result, operation) => {
1262
+ if (result.status < 200 || result.status >= 300) {
1263
+ const reason = reasonOf(result.body);
1264
+ throw new Error(operation + " failed: HTTP " + result.status.toString() + (reason ? ": " + reason : ""));
1265
+ }
1266
+ return result.body;
1267
+ };
1268
+ /** Thin typed wrapper over the existing DataOps REST endpoints. */
1269
+ var ResourceManagementApi = class {
1270
+ reviewApi;
1271
+ constructor(reviewApi) {
1272
+ this.reviewApi = reviewApi;
1273
+ }
1274
+ async call(path, init = {}) {
1275
+ return unwrap(await this.reviewApi.request(path, init), path);
1276
+ }
1277
+ async listPendingTasks(query = "", limit = 20) {
1278
+ const params = new URLSearchParams({
1279
+ status: "pending",
1280
+ page: "1"
1281
+ });
1282
+ const keyword = query.trim();
1283
+ if (keyword) params.set("keyword", keyword);
1284
+ const rows = (await this.call("/api/tasks?" + params.toString(), { method: "GET" })).tasks;
1285
+ return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null).slice(0, Math.max(1, Math.min(100, limit))) : [];
1286
+ }
1287
+ async listGrants(resourceId) {
1288
+ const rows = (await this.call("/api/resources/" + resourceId.toString() + "/access-grants", { method: "GET" })).grants;
1289
+ return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null) : [];
1290
+ }
1291
+ async listApplications() {
1292
+ const rows = (await this.call("/api/tasks/asset-access-applications", { method: "GET" })).applications;
1293
+ return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null) : [];
1294
+ }
1295
+ async replaceGrants(resourceId, grants) {
1296
+ return this.call("/api/resources/" + resourceId.toString() + "/access-grants", {
1297
+ method: "PUT",
1298
+ body: JSON.stringify({ grants })
1299
+ });
1300
+ }
1301
+ async getTask(taskId) {
1302
+ const task = (await this.call("/api/tasks/" + taskId.toString(), { method: "GET" })).task;
1303
+ if (typeof task !== "object" || task === null) throw new Error("task detail is unavailable");
1304
+ return task;
1305
+ }
1306
+ async decideTask(decision) {
1307
+ const action = decision.decision === "approve" ? "complete" : "reject";
1308
+ return this.call("/api/tasks/" + decision.taskId.toString() + "/user-tasks/" + encodeURIComponent(decision.userTaskId) + "/" + action, {
1309
+ method: "POST",
1310
+ body: JSON.stringify({
1311
+ expectedVersion: decision.expectedVersion ?? 0,
1312
+ comment: decision.comment?.trim() || (decision.decision === "approve" ? "同意" : "驳回")
1313
+ })
1314
+ });
1315
+ }
1316
+ };
1317
+ //#endregion
1085
1318
  //#region src/api-docs.ts
1086
1319
  /** Raised when the upstream body is not an OpenAPI document this module can search. */
1087
1320
  var ApiDocsUnavailableError = class extends Error {};
@@ -1341,6 +1574,7 @@ const forbidden = (message) => /* @__PURE__ */ new Error("Forbidden (403): " + m
1341
1574
  */
1342
1575
  function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
1343
1576
  const collectApi = new CollectApi(reviewApi);
1577
+ const resourceManagementApi = new ResourceManagementApi(reviewApi);
1344
1578
  const approve = async (tool, exec, reason) => {
1345
1579
  if (exec.agent === void 0) throw new Error(tool + " requires an initiating agent");
1346
1580
  const outcome = await ctx.approval.request({
@@ -1463,6 +1697,41 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
1463
1697
  if (!Array.isArray(parsed)) throw new Error(tool + ": " + label + " must be a JSON array");
1464
1698
  return parsed;
1465
1699
  };
1700
+ /**
1701
+ * Keep only the fields the DataOps execute DTO accepts. The plan tool returns
1702
+ * `createSql`/`targetSchema`/`notes` beside `createTable`; if the model passes
1703
+ * the whole plan (or rebuilds it after a table-name edit), the backend's
1704
+ * `forbidNonWhitelisted` pipe rejects the call with a generic 400.
1705
+ */
1706
+ const normalizeCreatePlan = (tool, plan) => {
1707
+ if (plan === void 0) return void 0;
1708
+ const tableName = typeof plan.tableName === "string" ? plan.tableName.trim() : "";
1709
+ if (!tableName) throw new Error(tool + ": create_plan_json.tableName is required");
1710
+ const rawColumns = Array.isArray(plan.columns) ? plan.columns : [];
1711
+ if (!rawColumns.length) throw new Error(tool + ": create_plan_json.columns is required");
1712
+ const columns = rawColumns.map((raw, index) => {
1713
+ const column = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
1714
+ const sourceKey = typeof column.sourceKey === "string" ? column.sourceKey : "";
1715
+ const name = typeof column.name === "string" ? column.name : "";
1716
+ const chineseName = typeof column.chineseName === "string" ? column.chineseName : "";
1717
+ const dataType = typeof column.dataType === "string" ? column.dataType : "";
1718
+ if (!sourceKey || !name || !chineseName || !dataType) throw new Error(tool + ": create_plan_json.columns[" + index + "] needs sourceKey/name/chineseName/dataType");
1719
+ return {
1720
+ sourceKey,
1721
+ name,
1722
+ chineseName,
1723
+ dataType,
1724
+ ...typeof column.nullable === "boolean" ? { nullable: column.nullable } : {},
1725
+ ...typeof column.comment === "string" ? { comment: column.comment } : {}
1726
+ };
1727
+ });
1728
+ return {
1729
+ tableName,
1730
+ ...typeof plan.tableChineseName === "string" && plan.tableChineseName.trim() ? { tableChineseName: plan.tableChineseName.trim() } : {},
1731
+ ...typeof plan.tableComment === "string" && plan.tableComment.trim() ? { tableComment: plan.tableComment.trim() } : {},
1732
+ columns
1733
+ };
1734
+ };
1466
1735
  return [
1467
1736
  {
1468
1737
  name: "skill_list",
@@ -1949,7 +2218,7 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
1949
2218
  name: "dataops_collect_execute",
1950
2219
  definition: defineTool({
1951
2220
  name: "dataops_collect_execute",
1952
- description: "Execute one confirmed spreadsheet import: create a table (or write to an existing table), insert rows, and register the DataOps resource. This is the ONLY collection tool that mutates data. Call it only after the user explicitly clicked the plan's \"开始导入\" action; never call it while the plan is still being edited.",
2221
+ description: "Execute one confirmed spreadsheet import: create a table (or write to an existing table), insert rows, and register the DataOps resource. This is the ONLY collection tool that mutates data. Call it only after the user explicitly confirms the read-only plan in natural language (e.g. 确认/开始吧); never call it while the plan is still being edited.",
1953
2222
  parameters: {
1954
2223
  session_id: {
1955
2224
  type: "string",
@@ -1976,7 +2245,7 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
1976
2245
  },
1977
2246
  create_plan_json: {
1978
2247
  type: "string",
1979
- description: "JSON object returned as plan.createTable, edited by the user."
2248
+ description: "Only plan.createTable (tableName/tableChineseName/tableComment/columns). Do not send createSql/targetSchema/notes; if the user edits the table name, call dataops_collect_plan again and pass its createTable."
1980
2249
  },
1981
2250
  mappings_json: {
1982
2251
  type: "string",
@@ -2010,7 +2279,7 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
2010
2279
  },
2011
2280
  execute: async (args, exec) => {
2012
2281
  if (args.mode !== "CREATE_TABLE" && args.mode !== "EXISTING_TABLE") throw new Error("dataops_collect_execute: mode must be CREATE_TABLE or EXISTING_TABLE");
2013
- const createPlan = parseJsonObject("dataops_collect_execute", "create_plan_json", args.create_plan_json);
2282
+ const createPlan = normalizeCreatePlan("dataops_collect_execute", parseJsonObject("dataops_collect_execute", "create_plan_json", args.create_plan_json));
2014
2283
  const mappings = parseJsonArray("dataops_collect_execute", "mappings_json", args.mappings_json);
2015
2284
  if (args.mode === "CREATE_TABLE" && createPlan === void 0) throw new Error("dataops_collect_execute: create_plan_json is required for CREATE_TABLE");
2016
2285
  if (args.mode === "EXISTING_TABLE" && (!args.target_schema || !args.target_table)) throw new Error("dataops_collect_execute: target_schema and target_table are required for EXISTING_TABLE");
@@ -2114,6 +2383,342 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
2114
2383
  };
2115
2384
  }
2116
2385
  })
2386
+ },
2387
+ {
2388
+ name: "dataops_resource_pending_list",
2389
+ definition: defineTool({
2390
+ name: "dataops_resource_pending_list",
2391
+ description: "List pending DataOps approval tasks and their active user tasks. Administrator only; the resource.manage connector capability must be on. Read-only.",
2392
+ parameters: {
2393
+ query: {
2394
+ type: "string",
2395
+ description: "Optional keyword over task title/code/requester."
2396
+ },
2397
+ limit: {
2398
+ type: "number",
2399
+ description: "Maximum tasks (default 20, max 100)."
2400
+ }
2401
+ },
2402
+ output: {
2403
+ schema: OPEN_OBJECT_SCHEMA,
2404
+ render: renderJson
2405
+ },
2406
+ execute: async (args) => {
2407
+ const limit = Math.max(1, Math.min(100, Math.round(args.limit ?? 20)));
2408
+ const tasks = await resourceManagementApi.listPendingTasks(args.query ?? "", limit);
2409
+ return {
2410
+ tasks: tasks.map((task) => ({
2411
+ id: task.id,
2412
+ code: task.code,
2413
+ title: task.title,
2414
+ status: task.status,
2415
+ requester: task.requester,
2416
+ requesterUserId: task.requesterUserId,
2417
+ workflow: task.workflow,
2418
+ userTasks: task.userTasks,
2419
+ updatedAt: task.updatedAt
2420
+ })),
2421
+ count: tasks.length
2422
+ };
2423
+ }
2424
+ })
2425
+ },
2426
+ {
2427
+ name: "dataops_resource_grant_list",
2428
+ definition: defineTool({
2429
+ name: "dataops_resource_grant_list",
2430
+ description: "List the current access grants of one DataOps resource. Administrator only; resource.manage capability must be on. Read-only.",
2431
+ parameters: { resource_id: {
2432
+ type: "number",
2433
+ required: true,
2434
+ description: "DataOps resource id."
2435
+ } },
2436
+ output: {
2437
+ schema: OPEN_OBJECT_SCHEMA,
2438
+ render: renderJson
2439
+ },
2440
+ execute: async (args) => {
2441
+ if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2442
+ const grants = await resourceManagementApi.listGrants(args.resource_id);
2443
+ return {
2444
+ resourceId: args.resource_id,
2445
+ grants
2446
+ };
2447
+ }
2448
+ })
2449
+ },
2450
+ {
2451
+ name: "dataops_resource_grant_batch",
2452
+ definition: defineTool({
2453
+ name: "dataops_resource_grant_batch",
2454
+ description: "Batch grant READ/MANAGE access on one DataOps resource to users, roles or departments. Administrator only; resource.manage capability must be on. The existing grants are preserved; the operation is audited by DataOps.",
2455
+ parameters: {
2456
+ resource_id: {
2457
+ type: "number",
2458
+ required: true,
2459
+ description: "DataOps resource id."
2460
+ },
2461
+ application_id: {
2462
+ type: "number",
2463
+ description: "Application id used for the grants. Defaults to an existing grant application or the first selectable application."
2464
+ },
2465
+ grants: {
2466
+ type: "array",
2467
+ required: true,
2468
+ description: "Targets to grant.",
2469
+ items: {
2470
+ type: "object",
2471
+ properties: {
2472
+ targetType: {
2473
+ type: "string",
2474
+ description: "USER, ROLE, DEPARTMENT or APPLICATION."
2475
+ },
2476
+ targetId: {
2477
+ type: "string",
2478
+ description: "User id, role code, department code or application id."
2479
+ },
2480
+ permission: {
2481
+ type: "string",
2482
+ description: "READ or MANAGE. Defaults to READ."
2483
+ },
2484
+ grantType: {
2485
+ type: "string",
2486
+ description: "REGULAR or TEMPORARY. Defaults to REGULAR."
2487
+ },
2488
+ applicationId: {
2489
+ type: "number",
2490
+ description: "Optional per-grant application id override."
2491
+ }
2492
+ },
2493
+ additionalProperties: false
2494
+ }
2495
+ }
2496
+ },
2497
+ output: {
2498
+ schema: OPEN_OBJECT_SCHEMA,
2499
+ render: renderJson
2500
+ },
2501
+ execute: async (args, exec) => {
2502
+ if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2503
+ if (!Array.isArray(args.grants) || args.grants.length === 0) throw new Error("grants must be a non-empty array");
2504
+ const existing = await resourceManagementApi.listGrants(args.resource_id);
2505
+ let appId = args.application_id;
2506
+ if (appId === void 0) appId = existing.map((g) => Number(g.applicationId)).find((id) => Number.isSafeInteger(id) && id > 0);
2507
+ if (appId === void 0) appId = (await resourceManagementApi.listApplications()).map((app) => Number(app.id)).find((id) => Number.isSafeInteger(id) && id > 0);
2508
+ if (appId === void 0) throw new Error("no application is available for access grants");
2509
+ const merged = /* @__PURE__ */ new Map();
2510
+ for (const grant of existing) {
2511
+ const targetType = String(grant.targetType ?? "");
2512
+ const targetId = String(grant.targetId ?? "");
2513
+ if (!targetType || !targetId) continue;
2514
+ const applicationId = Number(grant.applicationId) || appId;
2515
+ merged.set(targetType + ":" + targetId + ":" + applicationId, {
2516
+ targetType,
2517
+ targetId,
2518
+ permission: String(grant.permission ?? "READ"),
2519
+ grantType: String(grant.grantType ?? "REGULAR"),
2520
+ applicationId
2521
+ });
2522
+ }
2523
+ for (const grant of args.grants) {
2524
+ const targetType = String(grant.targetType ?? "").trim().toUpperCase();
2525
+ const targetId = String(grant.targetId ?? "").trim();
2526
+ if (![
2527
+ "USER",
2528
+ "ROLE",
2529
+ "DEPARTMENT",
2530
+ "APPLICATION"
2531
+ ].includes(targetType) || !targetId) throw new Error("each grant needs targetType and targetId");
2532
+ const permission = String(grant.permission ?? "READ").trim().toUpperCase();
2533
+ if (![
2534
+ "READ",
2535
+ "WRITE",
2536
+ "MANAGE"
2537
+ ].includes(permission)) throw new Error("permission must be READ, WRITE or MANAGE");
2538
+ const applicationId = grant.applicationId ?? appId;
2539
+ merged.set(targetType + ":" + targetId + ":" + applicationId, {
2540
+ targetType,
2541
+ targetId,
2542
+ permission,
2543
+ grantType: String(grant.grantType ?? "REGULAR").trim().toUpperCase(),
2544
+ applicationId
2545
+ });
2546
+ }
2547
+ const grants = [...merged.values()];
2548
+ await resourceManagementApi.replaceGrants(args.resource_id, grants);
2549
+ audit("dataops_resource_grant_batch", exec, {
2550
+ resourceId: args.resource_id,
2551
+ count: grants.length,
2552
+ applicationId: appId
2553
+ });
2554
+ return {
2555
+ resourceId: args.resource_id,
2556
+ applicationId: appId,
2557
+ grants,
2558
+ count: grants.length
2559
+ };
2560
+ }
2561
+ })
2562
+ },
2563
+ {
2564
+ name: "dataops_resource_approval_decide",
2565
+ definition: defineTool({
2566
+ name: "dataops_resource_approval_decide",
2567
+ description: "Approve or reject pending DataOps user tasks in batch. Administrator only; resource.manage capability must be on. Each decision needs task_id and user_task_id; expected_version is read from the task when omitted.",
2568
+ parameters: { decisions: {
2569
+ type: "array",
2570
+ required: true,
2571
+ description: "Approval decisions.",
2572
+ items: {
2573
+ type: "object",
2574
+ properties: {
2575
+ task_id: {
2576
+ type: "number",
2577
+ description: "DataOps task id."
2578
+ },
2579
+ user_task_id: {
2580
+ type: "string",
2581
+ description: "BPMN user task UUID."
2582
+ },
2583
+ decision: {
2584
+ type: "string",
2585
+ description: "approve or reject."
2586
+ },
2587
+ comment: {
2588
+ type: "string",
2589
+ description: "Decision comment."
2590
+ },
2591
+ expected_version: {
2592
+ type: "number",
2593
+ description: "Current taskVersion; read from task detail when omitted."
2594
+ }
2595
+ },
2596
+ additionalProperties: false
2597
+ }
2598
+ } },
2599
+ output: {
2600
+ schema: OPEN_OBJECT_SCHEMA,
2601
+ render: renderJson
2602
+ },
2603
+ execute: async (args, exec) => {
2604
+ if (!Array.isArray(args.decisions) || args.decisions.length === 0) throw new Error("decisions must be a non-empty array");
2605
+ const results = [];
2606
+ for (const decision of args.decisions) {
2607
+ const taskId = Number(decision.task_id);
2608
+ const userTaskId = String(decision.user_task_id ?? "");
2609
+ const action = String(decision.decision ?? "").toLowerCase();
2610
+ if (!Number.isSafeInteger(taskId) || taskId <= 0 || !userTaskId || action !== "approve" && action !== "reject") {
2611
+ results.push({
2612
+ taskId,
2613
+ userTaskId,
2614
+ ok: false,
2615
+ error: "invalid decision"
2616
+ });
2617
+ continue;
2618
+ }
2619
+ try {
2620
+ let expectedVersion = decision.expected_version;
2621
+ if (expectedVersion === void 0) {
2622
+ const task = await resourceManagementApi.getTask(taskId);
2623
+ const target = (Array.isArray(task.userTasks) ? task.userTasks : []).find((item) => item.id === userTaskId);
2624
+ expectedVersion = typeof target?.taskVersion === "number" ? target.taskVersion : 0;
2625
+ }
2626
+ await resourceManagementApi.decideTask({
2627
+ taskId,
2628
+ userTaskId,
2629
+ decision: action,
2630
+ comment: decision.comment,
2631
+ expectedVersion
2632
+ });
2633
+ results.push({
2634
+ taskId,
2635
+ userTaskId,
2636
+ decision: action,
2637
+ ok: true
2638
+ });
2639
+ } catch (error) {
2640
+ results.push({
2641
+ taskId,
2642
+ userTaskId,
2643
+ decision: action,
2644
+ ok: false,
2645
+ error: error instanceof Error ? error.message : String(error)
2646
+ });
2647
+ }
2648
+ }
2649
+ audit("dataops_resource_approval_decide", exec, {
2650
+ count: results.length,
2651
+ ok: results.filter((item) => item.ok === true).length
2652
+ });
2653
+ return { results };
2654
+ }
2655
+ })
2656
+ },
2657
+ {
2658
+ name: "dataops_resource_grant_revoke",
2659
+ definition: defineTool({
2660
+ name: "dataops_resource_grant_revoke",
2661
+ description: "Batch revoke access grants from one DataOps resource by target type and target id. Administrator only; resource.manage capability must be on. DataOps audits the resulting grant replacement.",
2662
+ parameters: {
2663
+ resource_id: {
2664
+ type: "number",
2665
+ required: true,
2666
+ description: "DataOps resource id."
2667
+ },
2668
+ targets: {
2669
+ type: "array",
2670
+ required: true,
2671
+ description: "Targets to revoke.",
2672
+ items: {
2673
+ type: "object",
2674
+ properties: {
2675
+ targetType: {
2676
+ type: "string",
2677
+ description: "USER, ROLE, DEPARTMENT or APPLICATION."
2678
+ },
2679
+ targetId: {
2680
+ type: "string",
2681
+ description: "Target id/code."
2682
+ }
2683
+ },
2684
+ additionalProperties: false
2685
+ }
2686
+ }
2687
+ },
2688
+ output: {
2689
+ schema: OPEN_OBJECT_SCHEMA,
2690
+ render: renderJson
2691
+ },
2692
+ execute: async (args, exec) => {
2693
+ if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2694
+ if (!Array.isArray(args.targets) || args.targets.length === 0) throw new Error("targets must be a non-empty array");
2695
+ const existing = await resourceManagementApi.listGrants(args.resource_id);
2696
+ const keys = new Set(args.targets.map((target) => String(target.targetType).toUpperCase() + ":" + String(target.targetId)));
2697
+ let appId = existing.map((g) => Number(g.applicationId)).find((id) => Number.isSafeInteger(id) && id > 0);
2698
+ if (appId === void 0) appId = (await resourceManagementApi.listApplications()).map((app) => Number(app.id)).find((id) => Number.isSafeInteger(id) && id > 0);
2699
+ if (appId === void 0) throw new Error("no application is available for access grants");
2700
+ const remaining = existing.filter((grant) => !keys.has(String(grant.targetType).toUpperCase() + ":" + String(grant.targetId))).map((grant) => ({
2701
+ targetType: String(grant.targetType),
2702
+ targetId: String(grant.targetId),
2703
+ permission: String(grant.permission ?? "READ"),
2704
+ grantType: String(grant.grantType ?? "REGULAR"),
2705
+ applicationId: Number(grant.applicationId) || appId
2706
+ }));
2707
+ const removed = existing.length - remaining.length;
2708
+ if (removed === 0) throw new Error("no matching grant to revoke");
2709
+ await resourceManagementApi.replaceGrants(args.resource_id, remaining);
2710
+ audit("dataops_resource_grant_revoke", exec, {
2711
+ resourceId: args.resource_id,
2712
+ removed
2713
+ });
2714
+ return {
2715
+ resourceId: args.resource_id,
2716
+ removed,
2717
+ remaining,
2718
+ count: remaining.length
2719
+ };
2720
+ }
2721
+ })
2117
2722
  }
2118
2723
  ];
2119
2724
  }
@@ -2135,6 +2740,7 @@ var AiToolManager = class {
2135
2740
  unsubscribeExpiry;
2136
2741
  disposeViewer;
2137
2742
  scope;
2743
+ connectorState;
2138
2744
  revision = 0;
2139
2745
  inflight;
2140
2746
  disposed = false;
@@ -2219,6 +2825,37 @@ var AiToolManager = class {
2219
2825
  this.disposeViewer = void 0;
2220
2826
  this.scope = void 0;
2221
2827
  }
2828
+ /**
2829
+ * Read the connector state that gates capability-owned tools.
2830
+ *
2831
+ * A missing or unreadable state file is not a permission decision: it means the connector has
2832
+ * never been enabled in this workspace, so capability-gated tools stay unregistered.
2833
+ * @returns The persisted connector state, or a disabled placeholder when it cannot be read.
2834
+ */
2835
+ async readConnectorState() {
2836
+ try {
2837
+ return await readConnectorState();
2838
+ } catch (error) {
2839
+ this.ctx.logger.warn("dataops-managed: connector state could not be read for tool disclosure");
2840
+ this.ctx.logger.warn(error);
2841
+ return {
2842
+ enabled: false,
2843
+ capabilities: {}
2844
+ };
2845
+ }
2846
+ }
2847
+ /**
2848
+ * Re-reconcile after the connector's capability switches changed.
2849
+ *
2850
+ * The skill center writes the connector state; calling this keeps the registered tool set in
2851
+ * step with it without waiting for the next credential or role sync.
2852
+ */
2853
+ async refreshCapabilities() {
2854
+ if (this.disposed) return;
2855
+ const connectorState = await this.readConnectorState();
2856
+ if (this.disposed) return;
2857
+ this.applyScope(this.scope, connectorState);
2858
+ }
2222
2859
  async loadScope(revision) {
2223
2860
  let result;
2224
2861
  try {
@@ -2229,22 +2866,29 @@ var AiToolManager = class {
2229
2866
  return;
2230
2867
  }
2231
2868
  if (this.disposed || revision !== this.revision) return;
2869
+ const connectorState = await this.readConnectorState();
2870
+ if (this.disposed || revision !== this.revision) return;
2232
2871
  if (result.status === 200) {
2233
- this.applyScope(normalizeScope(result.body));
2872
+ this.applyScope(normalizeScope(result.body), connectorState);
2234
2873
  return;
2235
2874
  }
2236
2875
  if (result.status === 401 || result.status === 403 || result.status === 404 || result.status === 503) {
2237
- this.applyScope(void 0);
2876
+ this.applyScope(void 0, connectorState);
2238
2877
  return;
2239
2878
  }
2240
2879
  this.ctx.logger.warn("dataops-managed: tool disclosure scope read failed with HTTP " + result.status.toString());
2241
2880
  }
2242
2881
  /** Store the scope and make the registry match it. */
2243
- applyScope(scope) {
2882
+ applyScope(scope, connectorState) {
2244
2883
  this.scope = scope;
2884
+ if (connectorState !== void 0) this.connectorState = connectorState;
2245
2885
  if (this.disposed) return;
2246
2886
  this.applyViewer(scope);
2247
- const desired = new Set(scope === void 0 ? [] : AI_TOOL_NAMES.filter((name) => isToolVisible(name, scope)));
2887
+ const capabilities = this.connectorState ?? {
2888
+ enabled: false,
2889
+ capabilities: {}
2890
+ };
2891
+ const desired = new Set(scope === void 0 ? [] : AI_TOOL_NAMES.filter((name) => isToolVisible(name, scope) && isToolCapabilityEnabled(name, capabilities)));
2248
2892
  for (const [name, registration] of this.registrations) {
2249
2893
  if (desired.has(name)) continue;
2250
2894
  this.disposeRegistration(name, registration);
@@ -2411,141 +3055,6 @@ const resolveResourceTabConfig = (request, configuredWebBaseUrl) => {
2411
3055
  };
2412
3056
  };
2413
3057
  //#endregion
2414
- //#region src/connector-state.ts
2415
- /**
2416
- * The DataOps connector's workspace-visible state and skill-center catalogue.
2417
- *
2418
- * The skill center is skill-first, with connectors as its fourth tab. DataOps contributes one
2419
- * connector whose capability rows are derived from the same scope that drives tool disclosure;
2420
- * a capability the account cannot use is omitted rather than rendered as a disabled placeholder.
2421
- *
2422
- * This module owns only state and presentation. It never authorizes a tool call or a DataOps
2423
- * request: the backend remains the final boundary.
2424
- *
2425
- * @module connector-state
2426
- */
2427
- /** Same-origin route the skill center's connector tab reads and writes. */
2428
- const CONNECTORS_PATH = "/api/dsh-skill-center/connectors";
2429
- /** Connector id shown in the skill center. */
2430
- const DATAOPS_CONNECTOR_ID = "dataops-managed";
2431
- /** Resolve the persisted state file without depending on a global DSH path. */
2432
- const CONNECTOR_STATE_PATH = join(process.env.DSH_HOME?.trim() || "/workspace/.dataops/dsh", "dataops-managed", "connector-state.json");
2433
- /**
2434
- * Capability definitions before permission filtering.
2435
- *
2436
- * The set and its order follow `dataops/docs/dataops-connector-development-spec.md` §2.3,
2437
- * whose credential `requiredFor` list is `approval.push`, `data.query`, and `admin.manage`.
2438
- * Skill plaza and review queue are governed by `skill:*` permissions and stay out of the
2439
- * connector's capability switches.
2440
- */
2441
- const CAPABILITIES = [
2442
- {
2443
- id: "data.query",
2444
- name: "数据查询",
2445
- description: "通过 DataOps 数据查询能力回答业务问题",
2446
- defaultEnabled: true,
2447
- visible: () => true,
2448
- allowed: () => true
2449
- },
2450
- {
2451
- id: "resource.manage",
2452
- name: "资源管理",
2453
- description: "在对话中批量审批资源申请,给用户或角色授予资源访问权限",
2454
- defaultEnabled: true,
2455
- visible: (scope) => isAdmin(scope),
2456
- allowed: (scope) => isAdmin(scope)
2457
- },
2458
- {
2459
- id: "admin.manage",
2460
- name: "万相中台管理",
2461
- description: "登录万相中台后台执行管理动作",
2462
- defaultEnabled: true,
2463
- visible: (scope) => isAdmin(scope),
2464
- allowed: (scope) => isAdmin(scope)
2465
- }
2466
- ];
2467
- /**
2468
- * Persisted ids that moved to a new capability id.
2469
- *
2470
- * `approval.push` shipped before the capability grew from approval push into resource
2471
- * approval and authorization. Its stored toggle carries over to `resource.manage`; when both
2472
- * keys are present the current id wins.
2473
- */
2474
- const CAPABILITY_ALIASES = { "approval.push": "resource.manage" };
2475
- /** The ids the catalogue accepts; any other persisted key is a legacy value. */
2476
- const CAPABILITY_IDS = CAPABILITIES.map((capability) => capability.id);
2477
- /**
2478
- * Keep only boolean values for known capability ids.
2479
- *
2480
- * A state file written before the catalogue changed may still hold retired ids. Those keys are
2481
- * ignored rather than treated as a corrupt file; a missing new key takes the capability's
2482
- * `defaultEnabled`.
2483
- * @param value - the `capabilities` member of a parsed state file.
2484
- * @returns the readable toggles, keyed by current capability id.
2485
- */
2486
- function migrateCapabilities(value) {
2487
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
2488
- const stored = value;
2489
- const capabilities = {};
2490
- for (const id of CAPABILITY_IDS) if (typeof stored[id] === "boolean") capabilities[id] = stored[id];
2491
- for (const [legacyId, id] of Object.entries(CAPABILITY_ALIASES)) if (capabilities[id] === void 0 && typeof stored[legacyId] === "boolean") capabilities[id] = stored[legacyId];
2492
- return capabilities;
2493
- }
2494
- /** Read state; a missing or corrupt file is a safe disabled state. */
2495
- async function readConnectorState(path = CONNECTOR_STATE_PATH) {
2496
- try {
2497
- const payload = JSON.parse(await readFile(path, "utf8"));
2498
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return {
2499
- enabled: false,
2500
- capabilities: {}
2501
- };
2502
- const record = payload;
2503
- return {
2504
- enabled: record.enabled === true,
2505
- capabilities: migrateCapabilities(record.capabilities)
2506
- };
2507
- } catch {
2508
- return {
2509
- enabled: false,
2510
- capabilities: {}
2511
- };
2512
- }
2513
- }
2514
- /** Persist state atomically. */
2515
- async function writeConnectorState(state, path = CONNECTOR_STATE_PATH) {
2516
- await mkdir(dirname(path), { recursive: true });
2517
- const temporary = path + ".tmp-" + process.pid.toString();
2518
- const payload = {
2519
- enabled: state.enabled,
2520
- capabilities: migrateCapabilities(state.capabilities)
2521
- };
2522
- await writeFile(temporary, JSON.stringify(payload, null, 2), "utf8");
2523
- await rename(temporary, path);
2524
- }
2525
- /** Build the connector row for one current scope. */
2526
- function buildConnectorView(scope, state) {
2527
- const capabilities = scope === void 0 ? [] : CAPABILITIES.filter((capability) => capability.visible(scope) && capability.allowed(scope)).map((capability) => ({
2528
- id: capability.id,
2529
- name: capability.name,
2530
- description: capability.description,
2531
- enabled: state.capabilities[capability.id] ?? capability.defaultEnabled,
2532
- permitted: true
2533
- }));
2534
- return {
2535
- id: DATAOPS_CONNECTOR_ID,
2536
- name: "万相AI中台连接器",
2537
- vendor: "DataOps",
2538
- description: "把万相AI中台的技能、审核和数据能力接入当前工作区。",
2539
- enabled: state.enabled,
2540
- connected: scope !== void 0,
2541
- capabilities
2542
- };
2543
- }
2544
- /** Whether one capability id is in the fixed catalogue. */
2545
- function hasCapability(id) {
2546
- return CAPABILITIES.some((capability) => capability.id === id);
2547
- }
2548
- //#endregion
2549
3058
  //#region src/workspace-limits.ts
2550
3059
  /** Narrow a value to a plain object. */
2551
3060
  function asRecord(value) {
@@ -4137,6 +4646,7 @@ async function apply(ctx, config) {
4137
4646
  state.enabled = body.enabled;
4138
4647
  }
4139
4648
  await writeConnectorState(state);
4649
+ await aiTools.refreshCapabilities();
4140
4650
  writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state)] });
4141
4651
  return;
4142
4652
  }