@sparkelf/dsh-dataops-managed 0.3.29 → 0.3.31

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,78 @@ var CollectApi = class {
1082
1249
  }
1083
1250
  };
1084
1251
  //#endregion
1252
+ //#region src/resource-management-api.ts
1253
+ /**
1254
+ * DataOps resource-management transport: pending approval tasks, existing access grants,
1255
+ * batch grant/revoke, and approval decisions. Disclosure is handled by tool-scope; this file
1256
+ * only speaks to the existing DataOps APIs.
1257
+ */
1258
+ const reasonOf = (body) => {
1259
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return "";
1260
+ const record = body;
1261
+ if (typeof record.error === "string") return record.error;
1262
+ if (typeof record.message === "string") return record.message;
1263
+ const details = record.details;
1264
+ return Array.isArray(details?.errors) ? details.errors.filter((v) => typeof v === "string").join("; ") : "";
1265
+ };
1266
+ const unwrap = (result, operation) => {
1267
+ if (result.status < 200 || result.status >= 300) {
1268
+ const reason = reasonOf(result.body);
1269
+ throw new Error(operation + " failed: HTTP " + result.status.toString() + (reason ? ": " + reason : ""));
1270
+ }
1271
+ return result.body;
1272
+ };
1273
+ /** Thin typed wrapper over the existing DataOps REST endpoints. */
1274
+ var ResourceManagementApi = class {
1275
+ reviewApi;
1276
+ constructor(reviewApi) {
1277
+ this.reviewApi = reviewApi;
1278
+ }
1279
+ async call(path, init = {}) {
1280
+ return unwrap(await this.reviewApi.request(path, init), path);
1281
+ }
1282
+ async listPendingTasks(query = "", limit = 20) {
1283
+ const params = new URLSearchParams({
1284
+ status: "pending",
1285
+ page: "1"
1286
+ });
1287
+ const keyword = query.trim();
1288
+ if (keyword) params.set("keyword", keyword);
1289
+ const rows = (await this.call("/api/tasks?" + params.toString(), { method: "GET" })).tasks;
1290
+ return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null).slice(0, Math.max(1, Math.min(100, limit))) : [];
1291
+ }
1292
+ async listGrants(resourceId) {
1293
+ const rows = (await this.call("/api/resources/" + resourceId.toString() + "/access-grants", { method: "GET" })).grants;
1294
+ return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null) : [];
1295
+ }
1296
+ async listApplications() {
1297
+ const rows = (await this.call("/api/tasks/asset-access-applications", { method: "GET" })).applications;
1298
+ return Array.isArray(rows) ? rows.filter((row) => typeof row === "object" && row !== null) : [];
1299
+ }
1300
+ async replaceGrants(resourceId, grants) {
1301
+ return this.call("/api/resources/" + resourceId.toString() + "/access-grants", {
1302
+ method: "PUT",
1303
+ body: JSON.stringify({ grants })
1304
+ });
1305
+ }
1306
+ async getTask(taskId) {
1307
+ const task = (await this.call("/api/tasks/" + taskId.toString(), { method: "GET" })).task;
1308
+ if (typeof task !== "object" || task === null) throw new Error("task detail is unavailable");
1309
+ return task;
1310
+ }
1311
+ async decideTask(decision) {
1312
+ const action = decision.decision === "approve" ? "complete" : "reject";
1313
+ return this.call("/api/tasks/" + decision.taskId.toString() + "/user-tasks/" + encodeURIComponent(decision.userTaskId) + "/" + action, {
1314
+ method: "POST",
1315
+ headers: { "idempotency-key": decision.idempotencyKey?.trim() || "dataops-managed-" + randomUUID() },
1316
+ body: JSON.stringify({
1317
+ expectedVersion: decision.expectedVersion ?? 0,
1318
+ comment: decision.comment?.trim() || (decision.decision === "approve" ? "同意" : "驳回")
1319
+ })
1320
+ });
1321
+ }
1322
+ };
1323
+ //#endregion
1085
1324
  //#region src/api-docs.ts
1086
1325
  /** Raised when the upstream body is not an OpenAPI document this module can search. */
1087
1326
  var ApiDocsUnavailableError = class extends Error {};
@@ -1341,6 +1580,7 @@ const forbidden = (message) => /* @__PURE__ */ new Error("Forbidden (403): " + m
1341
1580
  */
1342
1581
  function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
1343
1582
  const collectApi = new CollectApi(reviewApi);
1583
+ const resourceManagementApi = new ResourceManagementApi(reviewApi);
1344
1584
  const approve = async (tool, exec, reason) => {
1345
1585
  if (exec.agent === void 0) throw new Error(tool + " requires an initiating agent");
1346
1586
  const outcome = await ctx.approval.request({
@@ -2149,6 +2389,347 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
2149
2389
  };
2150
2390
  }
2151
2391
  })
2392
+ },
2393
+ {
2394
+ name: "dataops_resource_pending_list",
2395
+ definition: defineTool({
2396
+ name: "dataops_resource_pending_list",
2397
+ description: "List pending DataOps approval tasks and their active user tasks. Administrator only; the resource.manage connector capability must be on. Read-only.",
2398
+ parameters: {
2399
+ query: {
2400
+ type: "string",
2401
+ description: "Optional keyword over task title/code/requester."
2402
+ },
2403
+ limit: {
2404
+ type: "number",
2405
+ description: "Maximum tasks (default 20, max 100)."
2406
+ }
2407
+ },
2408
+ output: {
2409
+ schema: OPEN_OBJECT_SCHEMA,
2410
+ render: renderJson
2411
+ },
2412
+ execute: async (args) => {
2413
+ const limit = Math.max(1, Math.min(100, Math.round(args.limit ?? 20)));
2414
+ const tasks = await resourceManagementApi.listPendingTasks(args.query ?? "", limit);
2415
+ return {
2416
+ tasks: tasks.map((task) => ({
2417
+ id: task.id,
2418
+ code: task.code,
2419
+ title: task.title,
2420
+ status: task.status,
2421
+ requester: task.requester,
2422
+ requesterUserId: task.requesterUserId,
2423
+ workflow: task.workflow,
2424
+ userTasks: task.userTasks,
2425
+ updatedAt: task.updatedAt
2426
+ })),
2427
+ count: tasks.length
2428
+ };
2429
+ }
2430
+ })
2431
+ },
2432
+ {
2433
+ name: "dataops_resource_grant_list",
2434
+ definition: defineTool({
2435
+ name: "dataops_resource_grant_list",
2436
+ description: "List the current access grants of one DataOps resource. Administrator only; resource.manage capability must be on. Read-only.",
2437
+ parameters: { resource_id: {
2438
+ type: "number",
2439
+ required: true,
2440
+ description: "DataOps resource id."
2441
+ } },
2442
+ output: {
2443
+ schema: OPEN_OBJECT_SCHEMA,
2444
+ render: renderJson
2445
+ },
2446
+ execute: async (args) => {
2447
+ if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2448
+ const grants = await resourceManagementApi.listGrants(args.resource_id);
2449
+ return {
2450
+ resourceId: args.resource_id,
2451
+ grants
2452
+ };
2453
+ }
2454
+ })
2455
+ },
2456
+ {
2457
+ name: "dataops_resource_grant_batch",
2458
+ definition: defineTool({
2459
+ name: "dataops_resource_grant_batch",
2460
+ 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.",
2461
+ parameters: {
2462
+ resource_id: {
2463
+ type: "number",
2464
+ required: true,
2465
+ description: "DataOps resource id."
2466
+ },
2467
+ application_id: {
2468
+ type: "number",
2469
+ description: "Application id used for the grants. Defaults to an existing grant application or the first selectable application."
2470
+ },
2471
+ grants: {
2472
+ type: "array",
2473
+ required: true,
2474
+ description: "Targets to grant.",
2475
+ items: {
2476
+ type: "object",
2477
+ properties: {
2478
+ targetType: {
2479
+ type: "string",
2480
+ description: "USER, ROLE, DEPARTMENT or APPLICATION."
2481
+ },
2482
+ targetId: {
2483
+ type: "string",
2484
+ description: "User id, role code, department code or application id."
2485
+ },
2486
+ permission: {
2487
+ type: "string",
2488
+ description: "READ or MANAGE. Defaults to READ."
2489
+ },
2490
+ grantType: {
2491
+ type: "string",
2492
+ description: "REGULAR or TEMPORARY. Defaults to REGULAR."
2493
+ },
2494
+ applicationId: {
2495
+ type: "number",
2496
+ description: "Optional per-grant application id override."
2497
+ }
2498
+ },
2499
+ additionalProperties: false
2500
+ }
2501
+ }
2502
+ },
2503
+ output: {
2504
+ schema: OPEN_OBJECT_SCHEMA,
2505
+ render: renderJson
2506
+ },
2507
+ execute: async (args, exec) => {
2508
+ if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2509
+ if (!Array.isArray(args.grants) || args.grants.length === 0) throw new Error("grants must be a non-empty array");
2510
+ const existing = await resourceManagementApi.listGrants(args.resource_id);
2511
+ let appId = args.application_id;
2512
+ if (appId === void 0) appId = existing.map((g) => Number(g.applicationId)).find((id) => Number.isSafeInteger(id) && id > 0);
2513
+ if (appId === void 0) appId = (await resourceManagementApi.listApplications()).map((app) => Number(app.id)).find((id) => Number.isSafeInteger(id) && id > 0);
2514
+ if (appId === void 0) throw new Error("no application is available for access grants");
2515
+ const merged = /* @__PURE__ */ new Map();
2516
+ for (const grant of existing) {
2517
+ const targetType = String(grant.targetType ?? "");
2518
+ const targetId = String(grant.targetId ?? "");
2519
+ if (!targetType || !targetId) continue;
2520
+ const applicationId = Number(grant.applicationId) || appId;
2521
+ merged.set(targetType + ":" + targetId + ":" + applicationId, {
2522
+ targetType,
2523
+ targetId,
2524
+ permission: String(grant.permission ?? "READ"),
2525
+ grantType: String(grant.grantType ?? "REGULAR"),
2526
+ applicationId
2527
+ });
2528
+ }
2529
+ for (const grant of args.grants) {
2530
+ const targetType = String(grant.targetType ?? "").trim().toUpperCase();
2531
+ const targetId = String(grant.targetId ?? "").trim();
2532
+ if (![
2533
+ "USER",
2534
+ "ROLE",
2535
+ "DEPARTMENT",
2536
+ "APPLICATION"
2537
+ ].includes(targetType) || !targetId) throw new Error("each grant needs targetType and targetId");
2538
+ const permission = String(grant.permission ?? "READ").trim().toUpperCase();
2539
+ if (![
2540
+ "READ",
2541
+ "WRITE",
2542
+ "MANAGE"
2543
+ ].includes(permission)) throw new Error("permission must be READ, WRITE or MANAGE");
2544
+ const applicationId = grant.applicationId ?? appId;
2545
+ merged.set(targetType + ":" + targetId + ":" + applicationId, {
2546
+ targetType,
2547
+ targetId,
2548
+ permission,
2549
+ grantType: String(grant.grantType ?? "REGULAR").trim().toUpperCase(),
2550
+ applicationId
2551
+ });
2552
+ }
2553
+ const grants = [...merged.values()];
2554
+ await resourceManagementApi.replaceGrants(args.resource_id, grants);
2555
+ audit("dataops_resource_grant_batch", exec, {
2556
+ resourceId: args.resource_id,
2557
+ count: grants.length,
2558
+ applicationId: appId
2559
+ });
2560
+ return {
2561
+ resourceId: args.resource_id,
2562
+ applicationId: appId,
2563
+ grants,
2564
+ count: grants.length
2565
+ };
2566
+ }
2567
+ })
2568
+ },
2569
+ {
2570
+ name: "dataops_resource_approval_decide",
2571
+ definition: defineTool({
2572
+ name: "dataops_resource_approval_decide",
2573
+ 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.",
2574
+ parameters: { decisions: {
2575
+ type: "array",
2576
+ required: true,
2577
+ description: "Approval decisions.",
2578
+ items: {
2579
+ type: "object",
2580
+ properties: {
2581
+ task_id: {
2582
+ type: "number",
2583
+ description: "DataOps task id."
2584
+ },
2585
+ user_task_id: {
2586
+ type: "string",
2587
+ description: "BPMN user task UUID."
2588
+ },
2589
+ decision: {
2590
+ type: "string",
2591
+ description: "approve or reject."
2592
+ },
2593
+ comment: {
2594
+ type: "string",
2595
+ description: "Decision comment."
2596
+ },
2597
+ expected_version: {
2598
+ type: "number",
2599
+ description: "Current taskVersion; read from task detail when omitted."
2600
+ },
2601
+ idempotency_key: {
2602
+ type: "string",
2603
+ description: "Optional replay key; reuse the original key to retry a timed-out command."
2604
+ }
2605
+ },
2606
+ additionalProperties: false
2607
+ }
2608
+ } },
2609
+ output: {
2610
+ schema: OPEN_OBJECT_SCHEMA,
2611
+ render: renderJson
2612
+ },
2613
+ execute: async (args, exec) => {
2614
+ if (!Array.isArray(args.decisions) || args.decisions.length === 0) throw new Error("decisions must be a non-empty array");
2615
+ const results = [];
2616
+ for (const decision of args.decisions) {
2617
+ const taskId = Number(decision.task_id);
2618
+ const userTaskId = String(decision.user_task_id ?? "");
2619
+ const action = String(decision.decision ?? "").toLowerCase();
2620
+ if (!Number.isSafeInteger(taskId) || taskId <= 0 || !userTaskId || action !== "approve" && action !== "reject") {
2621
+ results.push({
2622
+ taskId,
2623
+ userTaskId,
2624
+ ok: false,
2625
+ error: "invalid decision"
2626
+ });
2627
+ continue;
2628
+ }
2629
+ try {
2630
+ let expectedVersion = decision.expected_version;
2631
+ if (expectedVersion === void 0) {
2632
+ const task = await resourceManagementApi.getTask(taskId);
2633
+ const target = (Array.isArray(task.userTasks) ? task.userTasks : []).find((item) => item.id === userTaskId);
2634
+ expectedVersion = typeof target?.taskVersion === "number" ? target.taskVersion : 0;
2635
+ }
2636
+ await resourceManagementApi.decideTask({
2637
+ taskId,
2638
+ userTaskId,
2639
+ decision: action,
2640
+ comment: decision.comment,
2641
+ expectedVersion,
2642
+ idempotencyKey: decision.idempotency_key
2643
+ });
2644
+ results.push({
2645
+ taskId,
2646
+ userTaskId,
2647
+ decision: action,
2648
+ ok: true
2649
+ });
2650
+ } catch (error) {
2651
+ results.push({
2652
+ taskId,
2653
+ userTaskId,
2654
+ decision: action,
2655
+ ok: false,
2656
+ error: error instanceof Error ? error.message : String(error)
2657
+ });
2658
+ }
2659
+ }
2660
+ audit("dataops_resource_approval_decide", exec, {
2661
+ count: results.length,
2662
+ ok: results.filter((item) => item.ok === true).length
2663
+ });
2664
+ return { results };
2665
+ }
2666
+ })
2667
+ },
2668
+ {
2669
+ name: "dataops_resource_grant_revoke",
2670
+ definition: defineTool({
2671
+ name: "dataops_resource_grant_revoke",
2672
+ 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.",
2673
+ parameters: {
2674
+ resource_id: {
2675
+ type: "number",
2676
+ required: true,
2677
+ description: "DataOps resource id."
2678
+ },
2679
+ targets: {
2680
+ type: "array",
2681
+ required: true,
2682
+ description: "Targets to revoke.",
2683
+ items: {
2684
+ type: "object",
2685
+ properties: {
2686
+ targetType: {
2687
+ type: "string",
2688
+ description: "USER, ROLE, DEPARTMENT or APPLICATION."
2689
+ },
2690
+ targetId: {
2691
+ type: "string",
2692
+ description: "Target id/code."
2693
+ }
2694
+ },
2695
+ additionalProperties: false
2696
+ }
2697
+ }
2698
+ },
2699
+ output: {
2700
+ schema: OPEN_OBJECT_SCHEMA,
2701
+ render: renderJson
2702
+ },
2703
+ execute: async (args, exec) => {
2704
+ if (!Number.isSafeInteger(args.resource_id) || args.resource_id <= 0) throw new Error("resource_id must be a positive integer");
2705
+ if (!Array.isArray(args.targets) || args.targets.length === 0) throw new Error("targets must be a non-empty array");
2706
+ const existing = await resourceManagementApi.listGrants(args.resource_id);
2707
+ const keys = new Set(args.targets.map((target) => String(target.targetType).toUpperCase() + ":" + String(target.targetId)));
2708
+ let appId = existing.map((g) => Number(g.applicationId)).find((id) => Number.isSafeInteger(id) && id > 0);
2709
+ if (appId === void 0) appId = (await resourceManagementApi.listApplications()).map((app) => Number(app.id)).find((id) => Number.isSafeInteger(id) && id > 0);
2710
+ if (appId === void 0) throw new Error("no application is available for access grants");
2711
+ const remaining = existing.filter((grant) => !keys.has(String(grant.targetType).toUpperCase() + ":" + String(grant.targetId))).map((grant) => ({
2712
+ targetType: String(grant.targetType),
2713
+ targetId: String(grant.targetId),
2714
+ permission: String(grant.permission ?? "READ"),
2715
+ grantType: String(grant.grantType ?? "REGULAR"),
2716
+ applicationId: Number(grant.applicationId) || appId
2717
+ }));
2718
+ const removed = existing.length - remaining.length;
2719
+ if (removed === 0) throw new Error("no matching grant to revoke");
2720
+ await resourceManagementApi.replaceGrants(args.resource_id, remaining);
2721
+ audit("dataops_resource_grant_revoke", exec, {
2722
+ resourceId: args.resource_id,
2723
+ removed
2724
+ });
2725
+ return {
2726
+ resourceId: args.resource_id,
2727
+ removed,
2728
+ remaining,
2729
+ count: remaining.length
2730
+ };
2731
+ }
2732
+ })
2152
2733
  }
2153
2734
  ];
2154
2735
  }
@@ -2170,6 +2751,7 @@ var AiToolManager = class {
2170
2751
  unsubscribeExpiry;
2171
2752
  disposeViewer;
2172
2753
  scope;
2754
+ connectorState;
2173
2755
  revision = 0;
2174
2756
  inflight;
2175
2757
  disposed = false;
@@ -2254,6 +2836,37 @@ var AiToolManager = class {
2254
2836
  this.disposeViewer = void 0;
2255
2837
  this.scope = void 0;
2256
2838
  }
2839
+ /**
2840
+ * Read the connector state that gates capability-owned tools.
2841
+ *
2842
+ * A missing or unreadable state file is not a permission decision: it means the connector has
2843
+ * never been enabled in this workspace, so capability-gated tools stay unregistered.
2844
+ * @returns The persisted connector state, or a disabled placeholder when it cannot be read.
2845
+ */
2846
+ async readConnectorState() {
2847
+ try {
2848
+ return await readConnectorState();
2849
+ } catch (error) {
2850
+ this.ctx.logger.warn("dataops-managed: connector state could not be read for tool disclosure");
2851
+ this.ctx.logger.warn(error);
2852
+ return {
2853
+ enabled: false,
2854
+ capabilities: {}
2855
+ };
2856
+ }
2857
+ }
2858
+ /**
2859
+ * Re-reconcile after the connector's capability switches changed.
2860
+ *
2861
+ * The skill center writes the connector state; calling this keeps the registered tool set in
2862
+ * step with it without waiting for the next credential or role sync.
2863
+ */
2864
+ async refreshCapabilities() {
2865
+ if (this.disposed) return;
2866
+ const connectorState = await this.readConnectorState();
2867
+ if (this.disposed) return;
2868
+ this.applyScope(this.scope, connectorState);
2869
+ }
2257
2870
  async loadScope(revision) {
2258
2871
  let result;
2259
2872
  try {
@@ -2264,22 +2877,29 @@ var AiToolManager = class {
2264
2877
  return;
2265
2878
  }
2266
2879
  if (this.disposed || revision !== this.revision) return;
2880
+ const connectorState = await this.readConnectorState();
2881
+ if (this.disposed || revision !== this.revision) return;
2267
2882
  if (result.status === 200) {
2268
- this.applyScope(normalizeScope(result.body));
2883
+ this.applyScope(normalizeScope(result.body), connectorState);
2269
2884
  return;
2270
2885
  }
2271
2886
  if (result.status === 401 || result.status === 403 || result.status === 404 || result.status === 503) {
2272
- this.applyScope(void 0);
2887
+ this.applyScope(void 0, connectorState);
2273
2888
  return;
2274
2889
  }
2275
2890
  this.ctx.logger.warn("dataops-managed: tool disclosure scope read failed with HTTP " + result.status.toString());
2276
2891
  }
2277
2892
  /** Store the scope and make the registry match it. */
2278
- applyScope(scope) {
2893
+ applyScope(scope, connectorState) {
2279
2894
  this.scope = scope;
2895
+ if (connectorState !== void 0) this.connectorState = connectorState;
2280
2896
  if (this.disposed) return;
2281
2897
  this.applyViewer(scope);
2282
- const desired = new Set(scope === void 0 ? [] : AI_TOOL_NAMES.filter((name) => isToolVisible(name, scope)));
2898
+ const capabilities = this.connectorState ?? {
2899
+ enabled: false,
2900
+ capabilities: {}
2901
+ };
2902
+ const desired = new Set(scope === void 0 ? [] : AI_TOOL_NAMES.filter((name) => isToolVisible(name, scope) && isToolCapabilityEnabled(name, capabilities)));
2283
2903
  for (const [name, registration] of this.registrations) {
2284
2904
  if (desired.has(name)) continue;
2285
2905
  this.disposeRegistration(name, registration);
@@ -2446,141 +3066,6 @@ const resolveResourceTabConfig = (request, configuredWebBaseUrl) => {
2446
3066
  };
2447
3067
  };
2448
3068
  //#endregion
2449
- //#region src/connector-state.ts
2450
- /**
2451
- * The DataOps connector's workspace-visible state and skill-center catalogue.
2452
- *
2453
- * The skill center is skill-first, with connectors as its fourth tab. DataOps contributes one
2454
- * connector whose capability rows are derived from the same scope that drives tool disclosure;
2455
- * a capability the account cannot use is omitted rather than rendered as a disabled placeholder.
2456
- *
2457
- * This module owns only state and presentation. It never authorizes a tool call or a DataOps
2458
- * request: the backend remains the final boundary.
2459
- *
2460
- * @module connector-state
2461
- */
2462
- /** Same-origin route the skill center's connector tab reads and writes. */
2463
- const CONNECTORS_PATH = "/api/dsh-skill-center/connectors";
2464
- /** Connector id shown in the skill center. */
2465
- const DATAOPS_CONNECTOR_ID = "dataops-managed";
2466
- /** Resolve the persisted state file without depending on a global DSH path. */
2467
- const CONNECTOR_STATE_PATH = join(process.env.DSH_HOME?.trim() || "/workspace/.dataops/dsh", "dataops-managed", "connector-state.json");
2468
- /**
2469
- * Capability definitions before permission filtering.
2470
- *
2471
- * The set follows `dataops/docs/dataops-connector-development-spec.md` §2.3's credential list.
2472
- * `approval.push` was renamed to `resource.manage` when the capability grew from approval push
2473
- * into resource approval and authorization. Skill plaza and review queue are governed by
2474
- * `skill:*` permissions and stay out of the connector's capability switches.
2475
- */
2476
- const CAPABILITIES = [
2477
- {
2478
- id: "data.query",
2479
- name: "数据查询",
2480
- description: "通过 DataOps 数据查询能力回答业务问题",
2481
- defaultEnabled: true,
2482
- visible: () => true,
2483
- allowed: () => true
2484
- },
2485
- {
2486
- id: "resource.manage",
2487
- name: "资源管理",
2488
- description: "在对话中批量审批资源申请,给用户或角色授予资源访问权限",
2489
- defaultEnabled: true,
2490
- visible: (scope) => isAdmin(scope),
2491
- allowed: (scope) => isAdmin(scope)
2492
- },
2493
- {
2494
- id: "admin.manage",
2495
- name: "万相中台管理",
2496
- description: "登录万相中台后台执行管理动作",
2497
- defaultEnabled: true,
2498
- visible: (scope) => isAdmin(scope),
2499
- allowed: (scope) => isAdmin(scope)
2500
- }
2501
- ];
2502
- /**
2503
- * Persisted ids that moved to a new capability id.
2504
- *
2505
- * `approval.push` shipped before the capability grew from approval push into resource
2506
- * approval and authorization. Its stored toggle carries over to `resource.manage`; when both
2507
- * keys are present the current id wins.
2508
- */
2509
- const CAPABILITY_ALIASES = { "approval.push": "resource.manage" };
2510
- /** The ids the catalogue accepts; any other persisted key is a legacy value. */
2511
- const CAPABILITY_IDS = CAPABILITIES.map((capability) => capability.id);
2512
- /**
2513
- * Keep only boolean values for known capability ids.
2514
- *
2515
- * A state file written before the catalogue changed may still hold retired ids. Those keys are
2516
- * ignored rather than treated as a corrupt file; a missing new key takes the capability's
2517
- * `defaultEnabled`.
2518
- * @param value - the `capabilities` member of a parsed state file.
2519
- * @returns the readable toggles, keyed by current capability id.
2520
- */
2521
- function migrateCapabilities(value) {
2522
- if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
2523
- const stored = value;
2524
- const capabilities = {};
2525
- for (const id of CAPABILITY_IDS) if (typeof stored[id] === "boolean") capabilities[id] = stored[id];
2526
- for (const [legacyId, id] of Object.entries(CAPABILITY_ALIASES)) if (capabilities[id] === void 0 && typeof stored[legacyId] === "boolean") capabilities[id] = stored[legacyId];
2527
- return capabilities;
2528
- }
2529
- /** Read state; a missing or corrupt file is a safe disabled state. */
2530
- async function readConnectorState(path = CONNECTOR_STATE_PATH) {
2531
- try {
2532
- const payload = JSON.parse(await readFile(path, "utf8"));
2533
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return {
2534
- enabled: false,
2535
- capabilities: {}
2536
- };
2537
- const record = payload;
2538
- return {
2539
- enabled: record.enabled === true,
2540
- capabilities: migrateCapabilities(record.capabilities)
2541
- };
2542
- } catch {
2543
- return {
2544
- enabled: false,
2545
- capabilities: {}
2546
- };
2547
- }
2548
- }
2549
- /** Persist state atomically. */
2550
- async function writeConnectorState(state, path = CONNECTOR_STATE_PATH) {
2551
- await mkdir(dirname(path), { recursive: true });
2552
- const temporary = path + ".tmp-" + process.pid.toString();
2553
- const payload = {
2554
- enabled: state.enabled,
2555
- capabilities: migrateCapabilities(state.capabilities)
2556
- };
2557
- await writeFile(temporary, JSON.stringify(payload, null, 2), "utf8");
2558
- await rename(temporary, path);
2559
- }
2560
- /** Build the connector row for one current scope. */
2561
- function buildConnectorView(scope, state) {
2562
- const capabilities = scope === void 0 ? [] : CAPABILITIES.filter((capability) => capability.visible(scope) && capability.allowed(scope)).map((capability) => ({
2563
- id: capability.id,
2564
- name: capability.name,
2565
- description: capability.description,
2566
- enabled: state.capabilities[capability.id] ?? capability.defaultEnabled,
2567
- permitted: true
2568
- }));
2569
- return {
2570
- id: DATAOPS_CONNECTOR_ID,
2571
- name: "万相AI中台连接器",
2572
- vendor: "DataOps",
2573
- description: "把万相AI中台的技能、审核和数据能力接入当前工作区。",
2574
- enabled: state.enabled,
2575
- connected: scope !== void 0,
2576
- capabilities
2577
- };
2578
- }
2579
- /** Whether one capability id is in the fixed catalogue. */
2580
- function hasCapability(id) {
2581
- return CAPABILITIES.some((capability) => capability.id === id);
2582
- }
2583
- //#endregion
2584
3069
  //#region src/workspace-limits.ts
2585
3070
  /** Narrow a value to a plain object. */
2586
3071
  function asRecord(value) {
@@ -4172,6 +4657,7 @@ async function apply(ctx, config) {
4172
4657
  state.enabled = body.enabled;
4173
4658
  }
4174
4659
  await writeConnectorState(state);
4660
+ await aiTools.refreshCapabilities();
4175
4661
  writeJson(response, 200, { connectors: [buildConnectorView(aiTools.currentScope(), state)] });
4176
4662
  return;
4177
4663
  }