@sparkelf/dsh-dataops-managed 0.3.54 → 0.4.1

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
@@ -5,8 +5,8 @@ import { credentialRef } from "@deepseek-ai/dsh-credentials";
5
5
  import * as McpClient from "@sparkelf/dsh-plugin-mcp-credentials";
6
6
  import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
7
7
  import z from "@deepseek-ai/schemastery";
8
+ import { randomBytes, randomUUID } from "node:crypto";
8
9
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
- import { randomUUID } from "node:crypto";
10
10
  //#region src/auth-state.ts
11
11
  let state = "unknown";
12
12
  const listeners = /* @__PURE__ */ new Set();
@@ -877,6 +877,11 @@ const AI_TOOL_ACCESS = {
877
877
  review_notifications_list: {},
878
878
  review_notifications_read: {},
879
879
  dataops_api_docs: { superAdminOnly: true },
880
+ synonym_group_list: { superAdminOnly: true },
881
+ synonym_group_get: { superAdminOnly: true },
882
+ synonym_group_create: { superAdminOnly: true },
883
+ synonym_group_update: { superAdminOnly: true },
884
+ synonym_group_delete: { superAdminOnly: true },
880
885
  workflow_query: { superAdminOnly: true },
881
886
  workflow_definition: { superAdminOnly: true },
882
887
  workflow_deployment: { superAdminOnly: true },
@@ -886,6 +891,17 @@ const AI_TOOL_ACCESS = {
886
891
  dataops_collect_execute: { permission: "data:resource:manage" },
887
892
  dataops_collect_resources: { permission: "data:resource:read" },
888
893
  dataops_open_resource_tab: {},
894
+ dataops_user_lookup: { permission: "system:user:read" },
895
+ dataops_user_create: {
896
+ capability: "admin.manage",
897
+ adminOnly: true,
898
+ defaultEnabled: true
899
+ },
900
+ dataops_role_assign: {
901
+ capability: "admin.manage",
902
+ adminOnly: true,
903
+ defaultEnabled: true
904
+ },
889
905
  dataops_resource_pending_list: {
890
906
  capability: "resource.manage",
891
907
  adminOnly: true,
@@ -1751,6 +1767,25 @@ const renderJson = (_args, value) => [{
1751
1767
  }];
1752
1768
  //#endregion
1753
1769
  //#region src/tools.ts
1770
+ /**
1771
+ * Model tools for the skill centre, the shared review queues, and the DataOps API reference.
1772
+ *
1773
+ * Registration is disclosure, not authorization. `AiToolManager` computes the workspace's
1774
+ * current DataOps scope once per credential/role sync and registers only the tools that scope
1775
+ * can use; these definitions assume they were registered for a principal that may call them.
1776
+ * Every `execute` therefore validates parameters, asks for user approval where a mutation needs
1777
+ * it, writes its audit line, and lets DataOps answer — no per-call role read, no local permission
1778
+ * tree, and no replacement for the backend's AuthGuard/PermissionGuard.
1779
+ *
1780
+ * The skill plaza is the catalogue. `scope=mine` exposes the caller's pending/rejected rows,
1781
+ * the public list exposes what the caller may install, and the admin list (administrators only)
1782
+ * exposes disabled entries. Installation, sharing and deletion are deliberately three different
1783
+ * actions: uninstall removes only the caller's installation, unshare unpublishes the shared entry
1784
+ * (with an unpublished notification), and delete permanently removes the entry after a second
1785
+ * confirmation, with its own deleted notification and audit trail.
1786
+ *
1787
+ * @module tools
1788
+ */
1754
1789
  /** Parse one plaza response body into rows without trusting its shape. */
1755
1790
  function rowsOf(body) {
1756
1791
  if (Array.isArray(body)) return body.filter((row) => typeof row === "object" && row !== null);
@@ -1783,6 +1818,87 @@ const provisioningDepartmentCode = (tool, value) => {
1783
1818
  return code;
1784
1819
  };
1785
1820
  /**
1821
+ * Roles a tool-created account receives.
1822
+ *
1823
+ * This is the same minimal set the IM private-chat auto-provision path writes: an ordinary
1824
+ * member, the basic data-security tier, and the admission role that lets the account open its
1825
+ * AI workspace. None of them carries a business capability or a resource grant.
1826
+ */
1827
+ const PROVISIONED_USER_ROLES = [
1828
+ "应用人员",
1829
+ "初级权限",
1830
+ "AI 工作区成员"
1831
+ ];
1832
+ /** The one role this tool set never assigns or removes; super-admin changes stay in the console. */
1833
+ const SUPER_ADMIN_ROLE = "超级管理员";
1834
+ /** The department a provisioned account lands in until an administrator assigns one. */
1835
+ const PROVISIONED_DEPARTMENT = "unassigned";
1836
+ /** Trim one optional string argument; a non-string becomes the empty string. */
1837
+ const textArg = (value) => typeof value === "string" ? value.trim() : "";
1838
+ /** Digits only, used to compare phone numbers written with separators or a country code. */
1839
+ const phoneDigits = (value) => value.replace(/\D+/gu, "");
1840
+ /** Case-insensitive exact match helper for usernames and emails. */
1841
+ const sameText = (left, right) => left.toLowerCase() === right.toLowerCase();
1842
+ /** The comparable form the backend's password policy uses for account tokens. */
1843
+ const comparable = (value) => value.toLowerCase().replace(/[^a-z0-9]/gu, "");
1844
+ /**
1845
+ * Generate an initial password the backend's strong-password policy accepts.
1846
+ *
1847
+ * The value never leaves this function's caller: it is sent to DataOps once, stored as a hash,
1848
+ * and deliberately not returned, logged or audited. A tool-created account therefore cannot be
1849
+ * signed into until an administrator sets a password in the user console, which is the intended
1850
+ * credential hand-off for an AI-driven provisioning action.
1851
+ * @param context - account fields the policy rejects when the password embeds them.
1852
+ */
1853
+ const generatedInitialPassword = (context) => {
1854
+ const localPart = context.email.includes("@") ? context.email.split("@")[0] ?? "" : context.email;
1855
+ const tokens = [
1856
+ context.username,
1857
+ context.displayName,
1858
+ localPart
1859
+ ].map((token) => comparable(token)).filter((token) => token.length >= 3);
1860
+ for (let attempt = 0; attempt < 20; attempt += 1) {
1861
+ const candidate = "Aa1!" + randomBytes(32).toString("base64url");
1862
+ const comparableCandidate = comparable(candidate);
1863
+ if (tokens.every((token) => !comparableCandidate.includes(token))) return candidate;
1864
+ }
1865
+ return "Aa1!" + randomBytes(48).toString("hex") + "Zz9!";
1866
+ };
1867
+ /** One user row projected to the fields the lookup contract promises, never password material. */
1868
+ const projectUserRow = (row) => {
1869
+ const department = typeof row.department === "object" && row.department !== null ? row.department : {};
1870
+ const departmentCode = textArg(department.code);
1871
+ const roles = Array.isArray(row.roles) ? row.roles.flatMap((role) => {
1872
+ if (typeof role !== "object" || role === null) return [];
1873
+ const entry = role;
1874
+ const code = textArg(entry.code);
1875
+ if (code === "") return [];
1876
+ return [{
1877
+ code,
1878
+ name: textArg(entry.name) || code
1879
+ }];
1880
+ }) : [];
1881
+ return {
1882
+ id: textArg(row.id),
1883
+ username: textArg(row.username),
1884
+ displayName: textArg(row.displayName),
1885
+ email: textArg(row.email),
1886
+ mobile: textArg(row.phone) || null,
1887
+ enabled: row.enabled === true,
1888
+ departments: departmentCode === "" ? [] : [{
1889
+ code: departmentCode,
1890
+ name: textArg(department.name) || departmentCode
1891
+ }],
1892
+ roles
1893
+ };
1894
+ };
1895
+ /** Read one user row from a DataOps response body without trusting its shape. */
1896
+ const userRowOf = (body) => {
1897
+ if (typeof body !== "object" || body === null) return void 0;
1898
+ const user = body.user;
1899
+ return typeof user === "object" && user !== null && !Array.isArray(user) ? user : void 0;
1900
+ };
1901
+ /**
1786
1902
  * Build every managed tool definition.
1787
1903
  *
1788
1904
  * The definitions are built once; `readScope` is a live getter so a tool that survives a role
@@ -2838,6 +2954,368 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
2838
2954
  }
2839
2955
  })
2840
2956
  },
2957
+ {
2958
+ name: "dataops_user_lookup",
2959
+ definition: defineTool({
2960
+ name: "dataops_user_lookup",
2961
+ description: "Look up DataOps users by username, display name, email, mobile or WeCom userid. Administrator and department-administrator visibility apply; DataOps returns only the users inside the caller's existing data scope. Read-only and never returns password or credential material.",
2962
+ parameters: {
2963
+ username: {
2964
+ type: "string",
2965
+ description: "Exact login name (case-insensitive)."
2966
+ },
2967
+ display_name: {
2968
+ type: "string",
2969
+ description: "Display-name keyword (case-insensitive contains)."
2970
+ },
2971
+ email: {
2972
+ type: "string",
2973
+ description: "Exact email address (case-insensitive)."
2974
+ },
2975
+ mobile: {
2976
+ type: "string",
2977
+ description: "Exact mobile number; separators and a country prefix are tolerated."
2978
+ },
2979
+ wecom_user_id: {
2980
+ type: "string",
2981
+ description: "Exact WeCom address-book userid."
2982
+ },
2983
+ department_code: {
2984
+ type: "string",
2985
+ description: "Restrict to one department code."
2986
+ },
2987
+ enabled_only: {
2988
+ type: "boolean",
2989
+ description: "Return enabled accounts only. Defaults to false."
2990
+ },
2991
+ limit: {
2992
+ type: "number",
2993
+ description: "Maximum rows (default 20, max 50)."
2994
+ }
2995
+ },
2996
+ output: {
2997
+ schema: OPEN_OBJECT_SCHEMA,
2998
+ render: renderJson
2999
+ },
3000
+ execute: async (args) => {
3001
+ const username = textArg(args.username);
3002
+ const displayName = textArg(args.display_name);
3003
+ const email = textArg(args.email);
3004
+ const mobile = textArg(args.mobile);
3005
+ const wecomUserId = textArg(args.wecom_user_id);
3006
+ const departmentCode = textArg(args.department_code);
3007
+ const enabledOnly = args.enabled_only === true;
3008
+ if (username === "" && displayName === "" && email === "" && mobile === "" && wecomUserId === "") throw new Error("dataops_user_lookup: provide at least one of username, display_name, email, mobile or wecom_user_id");
3009
+ const limit = Math.max(1, Math.min(50, Math.round(args.limit ?? 20)));
3010
+ const params = new URLSearchParams();
3011
+ const search = username || displayName || email || mobile;
3012
+ if (search !== "") params.set("search", search);
3013
+ if (wecomUserId !== "") params.set("wecomUserId", wecomUserId);
3014
+ if (departmentCode !== "") params.set("departmentCode", departmentCode);
3015
+ params.set("page", "1");
3016
+ params.set("pageSize", "100");
3017
+ const body = await call("/api/system/users?" + params.toString());
3018
+ const rows = typeof body === "object" && body !== null && Array.isArray(body.items) ? body.items.filter((row) => typeof row === "object" && row !== null) : [];
3019
+ const queryDigits = phoneDigits(mobile);
3020
+ const users = rows.filter((row) => {
3021
+ if (username !== "" && !sameText(textArg(row.username), username)) return false;
3022
+ if (email !== "" && !sameText(textArg(row.email), email)) return false;
3023
+ if (displayName !== "" && !textArg(row.displayName).toLowerCase().includes(displayName.toLowerCase())) return false;
3024
+ if (mobile !== "") {
3025
+ const storedDigits = phoneDigits(textArg(row.phone));
3026
+ if (queryDigits === "" || storedDigits === "") return false;
3027
+ if (storedDigits !== queryDigits && !(queryDigits.length >= 7 && storedDigits.endsWith(queryDigits))) return false;
3028
+ }
3029
+ if (enabledOnly && row.enabled !== true) return false;
3030
+ return true;
3031
+ });
3032
+ return {
3033
+ users: users.slice(0, limit).map(projectUserRow),
3034
+ count: Math.min(users.length, limit),
3035
+ scanned: rows.length,
3036
+ filters: {
3037
+ username: username || null,
3038
+ displayName: displayName || null,
3039
+ email: email || null,
3040
+ mobile: mobile || null,
3041
+ wecomUserId: wecomUserId || null,
3042
+ departmentCode: departmentCode || null,
3043
+ enabledOnly: enabledOnly === true
3044
+ }
3045
+ };
3046
+ }
3047
+ })
3048
+ },
3049
+ {
3050
+ name: "dataops_user_create",
3051
+ definition: defineTool({
3052
+ name: "dataops_user_create",
3053
+ description: "Create an enabled ordinary DataOps account with the same minimal roles as IM auto-provisioning (应用人员/初级权限/AI 工作区成员), in 待分配部门 unless a department is named, and with ZERO data-resource grants. Requires confirm=true and a user approval for the real write; dry_run=true previews without writing. The initial password is random, never returned and never logged — an administrator must set the password in the user console before hand-off. Use dataops_user_lookup first.",
3054
+ parameters: {
3055
+ username: {
3056
+ type: "string",
3057
+ required: true,
3058
+ description: "Login name."
3059
+ },
3060
+ display_name: {
3061
+ type: "string",
3062
+ required: true,
3063
+ description: "Display name."
3064
+ },
3065
+ email: {
3066
+ type: "string",
3067
+ required: true,
3068
+ description: "Email address."
3069
+ },
3070
+ mobile: {
3071
+ type: "string",
3072
+ description: "Optional mobile number."
3073
+ },
3074
+ department_code: {
3075
+ type: "string",
3076
+ description: "Department code. Defaults to unassigned (待分配部门)."
3077
+ },
3078
+ dry_run: {
3079
+ type: "boolean",
3080
+ description: "Preview the account that would be created without writing. Defaults to false."
3081
+ },
3082
+ confirm: {
3083
+ type: "boolean",
3084
+ description: "Must be true for a real create; the tool also asks the user for approval."
3085
+ }
3086
+ },
3087
+ output: {
3088
+ schema: OPEN_OBJECT_SCHEMA,
3089
+ render: renderJson
3090
+ },
3091
+ execute: async (args, exec) => {
3092
+ const username = textArg(args.username);
3093
+ const displayName = textArg(args.display_name);
3094
+ const email = textArg(args.email);
3095
+ if (username === "" || displayName === "" || email === "") throw new Error("dataops_user_create: username, display_name and email are required");
3096
+ const mobile = textArg(args.mobile);
3097
+ const departmentCode = textArg(args.department_code) || PROVISIONED_DEPARTMENT;
3098
+ const roles = [...PROVISIONED_USER_ROLES];
3099
+ const credential = {
3100
+ mode: "admin_reset_required",
3101
+ message: "初始密码由工具随机生成且不回显;请在用户管理页为该账号设置密码后再交付。"
3102
+ };
3103
+ const preview = {
3104
+ username,
3105
+ displayName,
3106
+ email,
3107
+ mobile: mobile || null,
3108
+ departmentCode,
3109
+ enabled: true,
3110
+ roles,
3111
+ directResourceGrants: 0,
3112
+ credential
3113
+ };
3114
+ if (args.dry_run === true) return {
3115
+ dryRun: true,
3116
+ wouldCreate: preview
3117
+ };
3118
+ if (args.confirm !== true) throw new Error("dataops_user_create: confirm must be true for a real create (use dry_run=true to preview)");
3119
+ await approve("dataops_user_create", exec, "Create DataOps user " + username + " with roles " + roles.join(" / ") + " and no resource grants.");
3120
+ const body = await call("/api/system/users", {
3121
+ method: "POST",
3122
+ body: JSON.stringify({
3123
+ username,
3124
+ displayName,
3125
+ email,
3126
+ ...mobile === "" ? {} : { phone: mobile },
3127
+ departmentCode,
3128
+ roleCodes: roles,
3129
+ password: generatedInitialPassword({
3130
+ username,
3131
+ displayName,
3132
+ email
3133
+ })
3134
+ })
3135
+ });
3136
+ const row = userRowOf(body);
3137
+ if (row === void 0) throw new Error("dataops_user_create: DataOps created the account but returned no user record");
3138
+ const user = projectUserRow(row);
3139
+ const actorUserId = readScope()?.userId ?? null;
3140
+ audit("dataops_user_create", exec, {
3141
+ actorUserId,
3142
+ userId: user.id,
3143
+ username,
3144
+ roles,
3145
+ departmentCode,
3146
+ directResourceGrants: 0
3147
+ });
3148
+ return {
3149
+ created: true,
3150
+ user,
3151
+ defaultRoles: roles,
3152
+ directResourceGrants: 0,
3153
+ credential
3154
+ };
3155
+ }
3156
+ })
3157
+ },
3158
+ {
3159
+ name: "dataops_role_assign",
3160
+ definition: defineTool({
3161
+ name: "dataops_role_assign",
3162
+ description: "Add or remove roles on one or more DataOps users (role_codes replaces nothing: action=add merges, action=remove subtracts, and the backend keeps all other roles). Administrator only; DataOps enforces role hierarchy and data scope on every write. The 超级管理员 role can never be assigned or removed here. Requires confirm=true and a user approval for real writes; dry_run=true previews. Adds no resource grants.",
3163
+ parameters: {
3164
+ user_ids: {
3165
+ type: "array",
3166
+ required: true,
3167
+ description: "DataOps user ids (UUID strings).",
3168
+ items: { type: "string" }
3169
+ },
3170
+ role_codes: {
3171
+ type: "array",
3172
+ required: true,
3173
+ description: "Role codes to add or remove, for example 应用人员 / 初级权限.",
3174
+ items: { type: "string" }
3175
+ },
3176
+ action: {
3177
+ type: "string",
3178
+ description: "add (default) or remove."
3179
+ },
3180
+ dry_run: {
3181
+ type: "boolean",
3182
+ description: "Preview each user's before/after roles without writing. Defaults to false."
3183
+ },
3184
+ confirm: {
3185
+ type: "boolean",
3186
+ description: "Must be true for a real change; the tool also asks the user for approval."
3187
+ }
3188
+ },
3189
+ output: {
3190
+ schema: OPEN_OBJECT_SCHEMA,
3191
+ render: renderJson
3192
+ },
3193
+ execute: async (args, exec) => {
3194
+ if (!Array.isArray(args.user_ids) || args.user_ids.length === 0) throw new Error("dataops_role_assign: user_ids must be a non-empty array");
3195
+ const userIds = Array.from(new Set(args.user_ids.map(textArg).filter((id) => id !== "")));
3196
+ if (userIds.length === 0) throw new Error("dataops_role_assign: user_ids must contain non-empty DataOps user ids");
3197
+ if (userIds.length > 50) throw new Error("dataops_role_assign: at most 50 users per call");
3198
+ const requestedRoles = Array.from(new Set((args.role_codes ?? []).map(textArg).filter((code) => code !== "")));
3199
+ if (requestedRoles.length === 0) throw new Error("dataops_role_assign: role_codes must be a non-empty array");
3200
+ if (requestedRoles.includes(SUPER_ADMIN_ROLE)) throw new Error("dataops_role_assign: 超级管理员 role cannot be assigned or removed through this tool; use the administrator console");
3201
+ const action = args.action === void 0 ? "add" : textArg(args.action).toLowerCase();
3202
+ if (action !== "add" && action !== "remove") throw new Error("dataops_role_assign: action must be add or remove");
3203
+ const plans = [];
3204
+ for (const userId of userIds) try {
3205
+ const body = await call("/api/system/users/" + encodeURIComponent(userId));
3206
+ const row = userRowOf(body);
3207
+ if (row === void 0) throw new Error("user record missing from the response");
3208
+ const beforeRoles = Array.isArray(row.roles) ? row.roles.flatMap((role) => {
3209
+ if (typeof role !== "object" || role === null) return [];
3210
+ const code = textArg(role.code);
3211
+ return code === "" ? [] : [code];
3212
+ }) : [];
3213
+ if (beforeRoles.includes(SUPER_ADMIN_ROLE)) {
3214
+ plans.push({
3215
+ userId,
3216
+ username: textArg(row.username),
3217
+ ok: false,
3218
+ changed: false,
3219
+ beforeRoles,
3220
+ afterRoles: beforeRoles,
3221
+ error: "target is a 超级管理员; super-admin changes stay in the administrator console"
3222
+ });
3223
+ continue;
3224
+ }
3225
+ const afterRoles = action === "add" ? Array.from(/* @__PURE__ */ new Set([...beforeRoles, ...requestedRoles])) : beforeRoles.filter((code) => !requestedRoles.includes(code));
3226
+ if (afterRoles.length === 0) {
3227
+ plans.push({
3228
+ userId,
3229
+ username: textArg(row.username),
3230
+ ok: false,
3231
+ changed: false,
3232
+ beforeRoles,
3233
+ afterRoles,
3234
+ error: "the change would leave the user without any role"
3235
+ });
3236
+ continue;
3237
+ }
3238
+ const changed = afterRoles.length !== beforeRoles.length || afterRoles.some((code) => !beforeRoles.includes(code));
3239
+ plans.push({
3240
+ userId,
3241
+ username: textArg(row.username),
3242
+ ok: true,
3243
+ changed,
3244
+ beforeRoles,
3245
+ afterRoles,
3246
+ updatedAt: textArg(row.updatedAt)
3247
+ });
3248
+ } catch (error) {
3249
+ plans.push({
3250
+ userId,
3251
+ username: "",
3252
+ ok: false,
3253
+ changed: false,
3254
+ beforeRoles: [],
3255
+ afterRoles: [],
3256
+ error: error instanceof Error ? error.message : String(error)
3257
+ });
3258
+ }
3259
+ const changedPlans = plans.filter((plan) => plan.ok && plan.changed);
3260
+ const rejectedPlans = plans.filter((plan) => !plan.ok).length;
3261
+ if (args.dry_run === true) return {
3262
+ dryRun: true,
3263
+ action,
3264
+ roleCodes: requestedRoles,
3265
+ results: plans,
3266
+ changed: changedPlans.length,
3267
+ failed: rejectedPlans
3268
+ };
3269
+ if (changedPlans.length === 0) return {
3270
+ action,
3271
+ roleCodes: requestedRoles,
3272
+ results: plans,
3273
+ changed: 0,
3274
+ failed: rejectedPlans
3275
+ };
3276
+ if (args.confirm !== true) throw new Error("dataops_role_assign: confirm must be true for a real change (use dry_run=true to preview)");
3277
+ await approve("dataops_role_assign", exec, (action === "add" ? "Add" : "Remove") + " role(s) " + requestedRoles.join(" / ") + " for " + String(changedPlans.length) + " DataOps user(s).");
3278
+ let failed = rejectedPlans;
3279
+ for (const plan of changedPlans) {
3280
+ if (plan.updatedAt === void 0 || plan.updatedAt === "") {
3281
+ plan.ok = false;
3282
+ plan.error = "user record has no updatedAt optimistic token; re-run the lookup";
3283
+ failed += 1;
3284
+ continue;
3285
+ }
3286
+ try {
3287
+ await call("/api/system/users/" + encodeURIComponent(plan.userId), {
3288
+ method: "PATCH",
3289
+ body: JSON.stringify({
3290
+ updatedAt: plan.updatedAt,
3291
+ roleCodes: plan.afterRoles
3292
+ })
3293
+ });
3294
+ } catch (error) {
3295
+ plan.ok = false;
3296
+ plan.error = error instanceof Error ? error.message : String(error);
3297
+ failed += 1;
3298
+ }
3299
+ }
3300
+ const actorUserId = readScope()?.userId ?? null;
3301
+ audit("dataops_role_assign", exec, {
3302
+ actorUserId,
3303
+ action,
3304
+ roleCodes: requestedRoles,
3305
+ userIds: changedPlans.map((plan) => plan.userId),
3306
+ changed: changedPlans.filter((plan) => plan.ok).length,
3307
+ failed
3308
+ });
3309
+ return {
3310
+ action,
3311
+ roleCodes: requestedRoles,
3312
+ results: plans,
3313
+ changed: changedPlans.filter((plan) => plan.ok).length,
3314
+ failed
3315
+ };
3316
+ }
3317
+ })
3318
+ },
2841
3319
  {
2842
3320
  name: "dataops_resource_pending_list",
2843
3321
  definition: defineTool({
@@ -3178,6 +3656,196 @@ function buildAiManagementTools(ctx, reviewApi, readScope, collectHub) {
3178
3656
  };
3179
3657
  }
3180
3658
  })
3659
+ },
3660
+ {
3661
+ name: "synonym_group_list",
3662
+ definition: defineTool({
3663
+ name: "synonym_group_list",
3664
+ description: "List DataOps synonym groups: the canonical wording, its aliases and the catalog node it belongs to. Read-only. Super administrators only.",
3665
+ parameters: {
3666
+ catalog_node_id: {
3667
+ type: "number",
3668
+ description: "Only groups attached to this catalog node id."
3669
+ },
3670
+ keyword: {
3671
+ type: "string",
3672
+ description: "Substring of the canonical term, or an exact alias."
3673
+ }
3674
+ },
3675
+ output: {
3676
+ schema: OPEN_OBJECT_SCHEMA,
3677
+ render: renderJson
3678
+ },
3679
+ execute: async (args) => {
3680
+ const query = new URLSearchParams();
3681
+ if (args.catalog_node_id !== void 0) query.set("catalogNodeId", String(args.catalog_node_id));
3682
+ if (args.keyword !== void 0 && args.keyword.trim() !== "") query.set("keyword", args.keyword.trim());
3683
+ return await call("/api/ai/synonym-groups?" + query.toString());
3684
+ }
3685
+ })
3686
+ },
3687
+ {
3688
+ name: "synonym_group_get",
3689
+ definition: defineTool({
3690
+ name: "synonym_group_get",
3691
+ description: "Read one DataOps synonym group by id. Read-only. Super administrators only.",
3692
+ parameters: { group_id: {
3693
+ type: "number",
3694
+ required: true,
3695
+ description: "Synonym group id."
3696
+ } },
3697
+ output: {
3698
+ schema: OPEN_OBJECT_SCHEMA,
3699
+ render: renderJson
3700
+ },
3701
+ execute: async (args) => {
3702
+ if (!Number.isSafeInteger(args.group_id) || args.group_id <= 0) throw new Error("group_id must be a positive integer");
3703
+ return await call("/api/ai/synonym-groups/" + args.group_id.toString());
3704
+ }
3705
+ })
3706
+ },
3707
+ {
3708
+ name: "synonym_group_create",
3709
+ definition: defineTool({
3710
+ name: "synonym_group_create",
3711
+ description: "Create one synonym group: a canonical wording plus up to 12 aliases. Aliases are unique across groups. Requires explicit user approval; DataOps rebuilds the search index after the write. Super administrators only.",
3712
+ parameters: {
3713
+ canonical: {
3714
+ type: "string",
3715
+ required: true,
3716
+ description: "The standard wording, e.g. 酒店."
3717
+ },
3718
+ aliases: {
3719
+ type: "array",
3720
+ items: { type: "string" },
3721
+ description: "Alternative wordings, e.g. 旅馆, 宾馆, hotel."
3722
+ },
3723
+ catalog_node_id: {
3724
+ type: "number",
3725
+ description: "Optional catalog node id the group belongs to."
3726
+ },
3727
+ description: {
3728
+ type: "string",
3729
+ description: "Optional description."
3730
+ },
3731
+ is_enabled: {
3732
+ type: "boolean",
3733
+ description: "Whether the group takes effect immediately (default true)."
3734
+ }
3735
+ },
3736
+ output: {
3737
+ schema: OPEN_OBJECT_SCHEMA,
3738
+ render: renderJson
3739
+ },
3740
+ execute: async (args, exec) => {
3741
+ if (typeof args.canonical !== "string" || args.canonical.trim() === "") throw new Error("canonical is required");
3742
+ await approve("synonym_group_create", exec, "Create synonym group " + args.canonical.trim());
3743
+ const body = {
3744
+ canonical: args.canonical.trim(),
3745
+ aliases: args.aliases ?? [],
3746
+ catalogNodeId: args.catalog_node_id ?? null,
3747
+ description: args.description ?? null,
3748
+ isEnabled: args.is_enabled ?? true
3749
+ };
3750
+ const value = await call("/api/ai/synonym-groups", {
3751
+ method: "POST",
3752
+ body: JSON.stringify(body)
3753
+ });
3754
+ audit("synonym_group_create", exec, {
3755
+ canonical: body.canonical,
3756
+ aliasCount: body.aliases.length
3757
+ });
3758
+ return value;
3759
+ }
3760
+ })
3761
+ },
3762
+ {
3763
+ name: "synonym_group_update",
3764
+ definition: defineTool({
3765
+ name: "synonym_group_update",
3766
+ description: "Update one synonym group: canonical wording, aliases, catalog node, description or enabled flag. Requires explicit user approval; DataOps rebuilds the documents that expanded the group. Super administrators only.",
3767
+ parameters: {
3768
+ group_id: {
3769
+ type: "number",
3770
+ required: true,
3771
+ description: "Synonym group id."
3772
+ },
3773
+ canonical: {
3774
+ type: "string",
3775
+ description: "New standard wording."
3776
+ },
3777
+ aliases: {
3778
+ type: "array",
3779
+ items: { type: "string" },
3780
+ description: "Full replacement alias list (max 12)."
3781
+ },
3782
+ catalog_node_id: {
3783
+ type: "number",
3784
+ description: "New catalog node id."
3785
+ },
3786
+ description: {
3787
+ type: "string",
3788
+ description: "New description."
3789
+ },
3790
+ is_enabled: {
3791
+ type: "boolean",
3792
+ description: "Enable or disable the group."
3793
+ }
3794
+ },
3795
+ output: {
3796
+ schema: OPEN_OBJECT_SCHEMA,
3797
+ render: renderJson
3798
+ },
3799
+ execute: async (args, exec) => {
3800
+ if (!Number.isSafeInteger(args.group_id) || args.group_id <= 0) throw new Error("group_id must be a positive integer");
3801
+ await approve("synonym_group_update", exec, "Update synonym group " + args.group_id.toString());
3802
+ const body = {};
3803
+ if (args.canonical !== void 0) body.canonical = args.canonical;
3804
+ if (args.aliases !== void 0) body.aliases = args.aliases;
3805
+ if (args.catalog_node_id !== void 0) body.catalogNodeId = args.catalog_node_id;
3806
+ if (args.description !== void 0) body.description = args.description;
3807
+ if (args.is_enabled !== void 0) body.isEnabled = args.is_enabled;
3808
+ const value = await call("/api/ai/synonym-groups/" + args.group_id.toString(), {
3809
+ method: "PATCH",
3810
+ body: JSON.stringify(body)
3811
+ });
3812
+ audit("synonym_group_update", exec, { groupId: args.group_id });
3813
+ return value;
3814
+ }
3815
+ })
3816
+ },
3817
+ {
3818
+ name: "synonym_group_delete",
3819
+ definition: defineTool({
3820
+ name: "synonym_group_delete",
3821
+ description: "Disable a synonym group (default) or permanently delete it with purge=true. Requires explicit user approval. Super administrators only.",
3822
+ parameters: {
3823
+ group_id: {
3824
+ type: "number",
3825
+ required: true,
3826
+ description: "Synonym group id."
3827
+ },
3828
+ purge: {
3829
+ type: "boolean",
3830
+ description: "Delete permanently instead of disabling."
3831
+ }
3832
+ },
3833
+ output: {
3834
+ schema: OPEN_OBJECT_SCHEMA,
3835
+ render: renderJson
3836
+ },
3837
+ execute: async (args, exec) => {
3838
+ if (!Number.isSafeInteger(args.group_id) || args.group_id <= 0) throw new Error("group_id must be a positive integer");
3839
+ const purge = args.purge === true;
3840
+ await approve("synonym_group_delete", exec, (purge ? "Delete" : "Disable") + " synonym group " + args.group_id.toString());
3841
+ const value = await call("/api/ai/synonym-groups/" + args.group_id.toString() + (purge ? "?purge=true" : ""), { method: "DELETE" });
3842
+ audit("synonym_group_delete", exec, {
3843
+ groupId: args.group_id,
3844
+ purge
3845
+ });
3846
+ return value;
3847
+ }
3848
+ })
3181
3849
  }
3182
3850
  ];
3183
3851
  }
@@ -5169,7 +5837,7 @@ const COLLECT_SKILL = {
5169
5837
  source: "bundled",
5170
5838
  resourceBase: {
5171
5839
  kind: "directory",
5172
- path: fileURLToPath(new URL("../", import.meta.url))
5840
+ path: fileURLToPath(new URL("../skills/dataops-collect/", import.meta.url))
5173
5841
  },
5174
5842
  rank: BUNDLED_SKILL_RANK,
5175
5843
  locator: COLLECT_SKILL_FILE
@@ -5204,6 +5872,93 @@ const CONNECTOR_SKILL = {
5204
5872
  * 没有权限时返回空列表,`get` 也拒绝,避免只靠 SKILL.md 里的 frontmatter 声明。
5205
5873
  */
5206
5874
  let connectorSkillAllowed = () => false;
5875
+ /** Admin data-governance skill: imports resources, writes metadata, and reads full platform metadata. */
5876
+ const GOVERNANCE_SKILL_NAME = "dataops-governance";
5877
+ const GOVERNANCE_SKILL_FILE = new URL("../skills/dataops-governance/SKILL.md", import.meta.url);
5878
+ const GOVERNANCE_SKILL = {
5879
+ name: GOVERNANCE_SKILL_NAME,
5880
+ description: "管理员/超管导入资源、维护资源/列/指标/血缘与可见性、查询全量平台元数据时使用。",
5881
+ invocation: {
5882
+ modelInvocable: true,
5883
+ userInvocable: true
5884
+ },
5885
+ provider: GOVERNANCE_SKILL_NAME,
5886
+ source: "bundled",
5887
+ resourceBase: {
5888
+ kind: "directory",
5889
+ path: fileURLToPath(new URL("../skills/dataops-governance/", import.meta.url))
5890
+ },
5891
+ rank: BUNDLED_SKILL_RANK,
5892
+ locator: GOVERNANCE_SKILL_FILE
5893
+ };
5894
+ const governanceSkillProvider = {
5895
+ name: GOVERNANCE_SKILL_NAME,
5896
+ list: () => Promise.resolve([GOVERNANCE_SKILL]),
5897
+ async get() {
5898
+ return {
5899
+ ...GOVERNANCE_SKILL,
5900
+ content: await readFile(GOVERNANCE_SKILL_FILE, "utf8")
5901
+ };
5902
+ }
5903
+ };
5904
+ /** Synonym-governance skill: discovers and maintains synonym groups for resource search. */
5905
+ const SYNONYM_SKILL_NAME = "dataops-synonym-governance";
5906
+ const SYNONYM_SKILL_FILE = new URL("../skills/dataops-synonym-governance/SKILL.md", import.meta.url);
5907
+ const SYNONYM_SKILL = {
5908
+ name: SYNONYM_SKILL_NAME,
5909
+ description: "超管维护资源检索的同义词组:从数据目录自底向上抽词、判定等价、确认后写入。",
5910
+ invocation: {
5911
+ modelInvocable: true,
5912
+ userInvocable: true
5913
+ },
5914
+ provider: SYNONYM_SKILL_NAME,
5915
+ source: "bundled",
5916
+ resourceBase: {
5917
+ kind: "directory",
5918
+ path: fileURLToPath(new URL("../skills/dataops-synonym-governance/", import.meta.url))
5919
+ },
5920
+ rank: BUNDLED_SKILL_RANK,
5921
+ locator: SYNONYM_SKILL_FILE
5922
+ };
5923
+ const synonymSkillProvider = {
5924
+ name: SYNONYM_SKILL_NAME,
5925
+ list: () => Promise.resolve([SYNONYM_SKILL]),
5926
+ async get() {
5927
+ return {
5928
+ ...SYNONYM_SKILL,
5929
+ content: await readFile(SYNONYM_SKILL_FILE, "utf8")
5930
+ };
5931
+ }
5932
+ };
5933
+ /** Metadata optimizer skill: inventories metadata and proposes governance improvements. */
5934
+ const METADATA_OPTIMIZER_SKILL_NAME = "dataops-metadata-optimizer";
5935
+ const METADATA_OPTIMIZER_SKILL_FILE = new URL("../skills/dataops-metadata-optimizer/SKILL.md", import.meta.url);
5936
+ const METADATA_OPTIMIZER_SKILL = {
5937
+ name: METADATA_OPTIMIZER_SKILL_NAME,
5938
+ description: "盘点资源/列/指标/血缘,识别命名、口径、冗余与缺失问题,生成治理提案并预览影响。",
5939
+ invocation: {
5940
+ modelInvocable: true,
5941
+ userInvocable: true
5942
+ },
5943
+ provider: METADATA_OPTIMIZER_SKILL_NAME,
5944
+ source: "bundled",
5945
+ resourceBase: {
5946
+ kind: "directory",
5947
+ path: fileURLToPath(new URL("../skills/dataops-metadata-optimizer/", import.meta.url))
5948
+ },
5949
+ rank: BUNDLED_SKILL_RANK,
5950
+ locator: METADATA_OPTIMIZER_SKILL_FILE
5951
+ };
5952
+ const metadataOptimizerSkillProvider = {
5953
+ name: METADATA_OPTIMIZER_SKILL_NAME,
5954
+ list: () => Promise.resolve([METADATA_OPTIMIZER_SKILL]),
5955
+ async get() {
5956
+ return {
5957
+ ...METADATA_OPTIMIZER_SKILL,
5958
+ content: await readFile(METADATA_OPTIMIZER_SKILL_FILE, "utf8")
5959
+ };
5960
+ }
5961
+ };
5207
5962
  const connectorSkillProvider = {
5208
5963
  name: CONNECTOR_SKILL_NAME,
5209
5964
  list: () => Promise.resolve(connectorSkillAllowed() ? [CONNECTOR_SKILL] : []),
@@ -5247,12 +6002,18 @@ const prefectScriptSkillProvider = {
5247
6002
  };
5248
6003
  }
5249
6004
  };
5250
- /** The skill that teaches the model how to use the local browser companion. */
5251
- const BROWSER_SKILL_NAME = "browser-bridge-companion";
5252
- const BROWSER_SKILL_FILE = new URL("../skills/browser-bridge-companion/SKILL.md", import.meta.url);
6005
+ /**
6006
+ * The browser entry skill: one catalog entry that routes headless scraping, the
6007
+ * local companion, and legacy Chrome-install troubleshooting through its
6008
+ * `references/` documents. The old `browser-headless` and
6009
+ * `browser-bridge-companion` entries were merged into it so the skill center
6010
+ * exposes one browser skill instead of three overlapping ones.
6011
+ */
6012
+ const BROWSER_SKILL_NAME = "browser";
6013
+ const BROWSER_SKILL_FILE = new URL("../skills/browser/SKILL.md", import.meta.url);
5253
6014
  const BROWSER_SKILL = {
5254
6015
  name: BROWSER_SKILL_NAME,
5255
- description: "用户要在自己的本地 Chrome/Edge 里打开内网系统、登录、点页面、填表、截图或做网页自动化时使用。先完成 8 位配对码配对、确认 Companion 在线且连接器显示已连接,再调用 browser_* 工具;登录/验证码必须让用户接管,不要索取密码,不要导出 Cookie。",
6016
+ description: "浏览器自动化总入口。抓取网页/大屏/表格、登录后取数、或用用户本地 Chrome/Edge 操作内网系统时使用。默认工作区 Playwright headless;只有用户明确要求本地浏览器、已登录 Chrome 或 Companion 才走 Browser Bridge。包含 headless、Companion 桥接与旧 Chrome 安装排查三套按需参考。",
5256
6017
  invocation: {
5257
6018
  modelInvocable: true,
5258
6019
  userInvocable: true
@@ -5261,7 +6022,7 @@ const BROWSER_SKILL = {
5261
6022
  source: "bundled",
5262
6023
  resourceBase: {
5263
6024
  kind: "directory",
5264
- path: fileURLToPath(new URL("../", import.meta.url))
6025
+ path: fileURLToPath(new URL("../skills/browser/", import.meta.url))
5265
6026
  },
5266
6027
  rank: BUNDLED_SKILL_RANK,
5267
6028
  locator: BROWSER_SKILL_FILE
@@ -5276,64 +6037,6 @@ const browserSkillProvider = {
5276
6037
  };
5277
6038
  }
5278
6039
  };
5279
- /** The browser entry skill: chooses headless scraping or the local companion. */
5280
- const BROWSER_GUIDE_SKILL_NAME = "browser";
5281
- const BROWSER_GUIDE_SKILL_FILE = new URL("../skills/browser/SKILL.md", import.meta.url);
5282
- const BROWSER_GUIDE_SKILL = {
5283
- name: BROWSER_GUIDE_SKILL_NAME,
5284
- description: "浏览器自动化总入口。默认用工作区 Playwright headless 抓取网页/大屏;只有用户明确要求“本地浏览器/已登录 Chrome/companion”才使用 Browser Bridge。账号密码登录走凭据插件,不强制 Companion。",
5285
- invocation: {
5286
- modelInvocable: true,
5287
- userInvocable: true
5288
- },
5289
- provider: BROWSER_GUIDE_SKILL_NAME,
5290
- source: "bundled",
5291
- resourceBase: {
5292
- kind: "directory",
5293
- path: fileURLToPath(new URL("../", import.meta.url))
5294
- },
5295
- rank: BUNDLED_SKILL_RANK,
5296
- locator: BROWSER_GUIDE_SKILL_FILE
5297
- };
5298
- const browserGuideSkillProvider = {
5299
- name: BROWSER_GUIDE_SKILL_NAME,
5300
- list: () => Promise.resolve([BROWSER_GUIDE_SKILL]),
5301
- async get() {
5302
- return {
5303
- ...BROWSER_GUIDE_SKILL,
5304
- content: await readFile(BROWSER_GUIDE_SKILL_FILE, "utf8")
5305
- };
5306
- }
5307
- };
5308
- /** The headless scraping skill the browser entry points at as the default mode. */
5309
- const BROWSER_HEADLESS_SKILL_NAME = "browser-headless";
5310
- const BROWSER_HEADLESS_SKILL_FILE = new URL("../skills/browser-headless/SKILL.md", import.meta.url);
5311
- const BROWSER_HEADLESS_SKILL = {
5312
- name: BROWSER_HEADLESS_SKILL_NAME,
5313
- description: "用工作区 Playwright + Chromium 无头抓取网页/大屏数据。默认模式;支持账号密码登录(凭据插件注入)、表格/文本/截图/JSON 输出。需要用户已登录的本地浏览器时改用 browser-bridge-companion。",
5314
- invocation: {
5315
- modelInvocable: true,
5316
- userInvocable: true
5317
- },
5318
- provider: BROWSER_HEADLESS_SKILL_NAME,
5319
- source: "bundled",
5320
- resourceBase: {
5321
- kind: "directory",
5322
- path: fileURLToPath(new URL("../", import.meta.url))
5323
- },
5324
- rank: BUNDLED_SKILL_RANK,
5325
- locator: BROWSER_HEADLESS_SKILL_FILE
5326
- };
5327
- const browserHeadlessSkillProvider = {
5328
- name: BROWSER_HEADLESS_SKILL_NAME,
5329
- list: () => Promise.resolve([BROWSER_HEADLESS_SKILL]),
5330
- async get() {
5331
- return {
5332
- ...BROWSER_HEADLESS_SKILL,
5333
- content: await readFile(BROWSER_HEADLESS_SKILL_FILE, "utf8")
5334
- };
5335
- }
5336
- };
5337
6040
  const PROVISIONING_SKILL_NAME = "skill-provisioning";
5338
6041
  const PROVISIONING_SKILL_FILE = new URL("../skills/skill-provisioning/SKILL.md", import.meta.url);
5339
6042
  /** 该技能只对持有 `skill:manage` 的身份展示:它驱动的分配工具使用同一能力。 */
@@ -5398,12 +6101,13 @@ async function apply(ctx, config) {
5398
6101
  let mcpFiber;
5399
6102
  ctx.skills.registerProvider(() => querySkillProvider);
5400
6103
  ctx.skills.registerProvider(() => collectSkillProvider);
6104
+ ctx.skills.registerProvider(() => governanceSkillProvider);
6105
+ ctx.skills.registerProvider(() => synonymSkillProvider);
6106
+ ctx.skills.registerProvider(() => metadataOptimizerSkillProvider);
5401
6107
  ctx.skills.registerProvider(() => connectorSkillProvider);
5402
6108
  ctx.skills.registerProvider(() => prefectScriptSkillProvider);
5403
6109
  ctx.skills.registerProvider(() => provisioningSkillProvider);
5404
6110
  ctx.skills.registerProvider(() => browserSkillProvider);
5405
- ctx.skills.registerProvider(() => browserGuideSkillProvider);
5406
- ctx.skills.registerProvider(() => browserHeadlessSkillProvider);
5407
6111
  const ensureMcp = async () => {
5408
6112
  if (mcpFiber !== void 0 && mcpFiber.uid !== null) return;
5409
6113
  const fiber = ctx.plugin(McpClient, {