@stalfh233/omc-cli 0.8.32 → 0.8.33

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.
Files changed (49) hide show
  1. package/dist/arg-vocabulary.js +223 -0
  2. package/dist/artifact-cmd.js +443 -0
  3. package/dist/batch-call.js +56 -3
  4. package/dist/call-command.js +70 -0
  5. package/dist/call-execute.js +228 -0
  6. package/dist/call-input.js +557 -0
  7. package/dist/call-output.js +240 -0
  8. package/dist/cli.js +13 -1359
  9. package/dist/command-transport.js +4 -1
  10. package/dist/form-support.js +14 -3
  11. package/dist/intent/plan-apply.js +14 -24
  12. package/dist/lanes/datarule.js +21 -0
  13. package/dist/lanes/field.js +31 -0
  14. package/dist/lanes/list-view-shapes.js +8 -1
  15. package/dist/lanes/list-view.js +64 -2
  16. package/dist/lanes/runtime-data/aggregate-support.js +209 -0
  17. package/dist/lanes/runtime-data/aggregate.js +679 -0
  18. package/dist/lanes/runtime-data/field-options.js +52 -0
  19. package/dist/lanes/runtime-data/lane.js +4 -0
  20. package/dist/lanes/runtime-data/record-delete.js +419 -0
  21. package/dist/lanes/runtime-data/record-read.js +984 -0
  22. package/dist/lanes/runtime-data/record-write.js +562 -0
  23. package/dist/lanes/runtime-data/registration.js +22 -0
  24. package/dist/lanes/runtime-data/shapes.js +594 -0
  25. package/dist/lanes/runtime-data/submission.js +1293 -0
  26. package/dist/lanes/runtime-data/write-support.js +875 -0
  27. package/dist/lanes/runtime-data.js +10 -5590
  28. package/dist/lanes/workflow/approval-ops.js +983 -0
  29. package/dist/lanes/workflow/instance-read.js +284 -0
  30. package/dist/lanes/workflow/lifecycle-write.js +1499 -0
  31. package/dist/lanes/workflow/permissions.js +571 -0
  32. package/dist/lanes/workflow/recovery.js +361 -0
  33. package/dist/lanes/workflow/registration.js +14 -0
  34. package/dist/lanes/workflow/shapes.js +811 -0
  35. package/dist/lanes/workflow/template-fetch.js +197 -0
  36. package/dist/lanes/workflow/template-merge.js +1351 -0
  37. package/dist/lanes/workflow/template-read.js +327 -0
  38. package/dist/lanes/workflow.js +11 -6312
  39. package/dist/read-projection.js +442 -0
  40. package/dist/read.js +40 -335
  41. package/dist/rollback.js +17 -23
  42. package/dist/runtime-support.js +1 -1
  43. package/dist/verification.js +39 -0
  44. package/dist/write-coordinator.js +152 -0
  45. package/dist/write-outcome.js +295 -0
  46. package/dist/write.js +34 -115
  47. package/package.json +3 -3
  48. package/skills/omc-refusals.md +1 -1
  49. package/skills/omc-start-here.md +2 -2
@@ -0,0 +1,571 @@
1
+ import { z } from "zod";
2
+ import { ENDPOINTS } from "../../endpoints.js";
3
+ import { collectOrgDepartments } from "../org-tree.js";
4
+ import { capabilityArg, environmentArg } from "../../args.js";
5
+ import { governedRead } from "../../read.js";
6
+ import { ToolRefusalError, ToolInputError, defineTool } from "../../tool-types.js";
7
+ import { writeTool } from "../../write.js";
8
+ import { wireCall, wireRows } from "../../wire.js";
9
+ import { PLATFORM_ADMIN_START_BYPASS, resolvePermissionActor } from "../../identity.js";
10
+ import { WORKFLOW_LANE, WORKFLOW_TOOLS, flattenRoleTree } from "./shapes.js";
11
+ import { resolveWorkflowArg } from "./template-fetch.js";
12
+ export function registerPermissionTools(tools) {
13
+ // ── 发起权限 (who may originate) ────────────────────────────────────────────
14
+ //
15
+ // 40009 流程发起权限不足 is the single most opaque refusal on this platform:
16
+ // `data.submit` (and `data.save` with workflowCode) answers it, the message
17
+ // names no permission, and there is no CLI face to inspect or grant one. r11
18
+ // (2026-10-24) burned 7 submit attempts and could not deliver the whole
19
+ // workflow section; the platform source shows the check is concrete:
20
+ // `WorkflowAspect.validateWorkflowPermission` → template header must exist and
21
+ // be published → `getWorkflowTemplateHeadersBySchemaCode(userId, schemaCode)`:
22
+ // • the user's root department must resolve (`getAllParentIds` non-empty),
23
+ // • `visibleType=ALL_VISIABLE` templates are open to everyone,
24
+ // • otherwise a `h_workflow_permission` row must match the user, their
25
+ // department (or any ancestor), or one of their roles,
26
+ // • platform admins (`h_perm_admin` ADMIN/SYS_MNG) bypass all of it.
27
+ // Publishing a flow creates NO permission row, so a freshly published flow is
28
+ // unusable by anyone who is not a platform admin.
29
+ const permissionRows = async (session, workflowCode) => wireRows((await wireCall(session, { path: ENDPOINTS.workflowListPermission, query: { workflowCode } })).data);
30
+ // `list_permission` echoes the PERMISSION row id plus the unit's display name
31
+ // and code — never the unitId (WorkflowTemplateController.getPermissionMap).
32
+ // So identity for readback/removal is resolved from the unit's own face.
33
+ const unitIdentity = async (session, unitType, unitId) => {
34
+ try {
35
+ if (unitType === 1) {
36
+ const row = (await wireCall(session, { path: ENDPOINTS.organizationDepartmentGet, query: { deptId: unitId } })).data;
37
+ return { name: row ? String(row.name ?? "") || null : null, code: row ? (String(row.code ?? "") || null) : null };
38
+ }
39
+ if (unitType === 2) {
40
+ const rows = wireRows((await wireCall(session, { path: ENDPOINTS.organizationRoleList, query: { expandAll: "true" } })).data);
41
+ const walk = (entries) => {
42
+ for (const entry of entries) {
43
+ if (String(entry.id ?? "") === unitId)
44
+ return entry;
45
+ const children = Array.isArray(entry.children) ? entry.children : [];
46
+ const hit = walk(children);
47
+ if (hit)
48
+ return hit;
49
+ }
50
+ return undefined;
51
+ };
52
+ const hit = walk(rows);
53
+ return { name: hit ? String(hit.name ?? "") || null : null, code: hit ? (String(hit.code ?? "") || null) : null };
54
+ }
55
+ const row = (await wireCall(session, { path: ENDPOINTS.organizationUserInfo, query: { id: unitId } })).data;
56
+ return { name: row ? String(row.name ?? "") || null : null, code: row ? (String(row.username ?? "") || null) : null };
57
+ }
58
+ catch {
59
+ return { name: null, code: null };
60
+ }
61
+ };
62
+ tools.push(defineTool({
63
+ name: "workflow.permissions",
64
+ search: { intents: ["谁能发起这个流程", "发起权限清单", "流程发起权限列表"] },
65
+ layer: "low",
66
+ kind: "read",
67
+ lane: WORKFLOW_LANE,
68
+ scope: WORKFLOW_TOOLS["workflow.permissions"].scope,
69
+ description: WORKFLOW_TOOLS["workflow.permissions"].description,
70
+ inputSchema: {
71
+ environment: environmentArg,
72
+ workflowCode: z.string().optional().describe("流程 code;省略则用 schemaCode 解析"),
73
+ schemaCode: z.string().optional().describe("模型 code:省略 workflowCode 时用它解析该模型的流程"),
74
+ capability: capabilityArg,
75
+ },
76
+ handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
77
+ const workflowCode = await resolveWorkflowArg(session, args);
78
+ if (!workflowCode)
79
+ return { schemaCode: args.schemaCode, exists: false, permissions: [], note: "该模型没有流程" };
80
+ const rows = await permissionRows(session, workflowCode);
81
+ const permissions = rows.map((row) => ({
82
+ id: row.id ?? null,
83
+ name: row.name ?? null,
84
+ unitType: row.unitType ?? null,
85
+ unitTypeName: row.unitType === 1 || row.unitType === "1" ? "部门" : row.unitType === 2 || row.unitType === "2" ? "角色" : row.unitType === 3 || row.unitType === "3" ? "用户" : null,
86
+ fullName: row.fullName ?? null,
87
+ corpId: row.corpId ?? null,
88
+ code: row.code ?? null,
89
+ ...(row.origin === "system-preset" || row.defaultPermission === true || row.preset === true ? { origin: "system-preset" } : row.origin === "user" ? { origin: "user" } : {}),
90
+ }));
91
+ const actor = await resolvePermissionActor(session);
92
+ const effectiveFor = {
93
+ userId: actor.userId,
94
+ name: actor.name,
95
+ allowed: actor.isAdmin || permissions.length > 0,
96
+ reason: actor.isAdmin
97
+ ? PLATFORM_ADMIN_START_BYPASS
98
+ : permissions.length === 0
99
+ ? "no-start-permission-row"
100
+ : "whitelist-configured-not-evaluated-for-membership",
101
+ note: actor.isAdmin
102
+ ? "当前登录人是平台管理员:发起成功不证明白名单生效。要用非管理员账号另建环境验证。"
103
+ : "本读面只回配置行;membership 命中需非管理员实发 data.submit 才能证伪。",
104
+ ...(actor.isAdmin ? { verifiable: false, verifyWith: `以普通账号凭据跑同查询:omc call workflow.permissions --env <env> --args '${JSON.stringify({ workflowCode })}'` } : {}),
105
+ };
106
+ return {
107
+ workflowCode,
108
+ count: permissions.length,
109
+ permissions,
110
+ actor,
111
+ effectiveFor,
112
+ ...(permissions.length === 0
113
+ ? {
114
+ blocker: "workflow-start-permission-empty",
115
+ note: "该流程没有任何发起权限行:除平台管理员(h_perm_admin 里 ADMIN/SYS_MNG)外**没有人能发起**,data.submit 会回 40009「流程发起权限不足」。发布流程不会自动建这一行,用 workflow.addPermission 授给部门/角色/用户(或把模板 visibleType 改成 ALL_VISIABLE)。管理员发起成功 ≠ 白名单生效。",
116
+ nextCommand: `omc call workflow.addPermission --env <env> --args '{"workflowCode":"${workflowCode}","unitId":"<部门|角色|用户 id>","unitType":1}'`,
117
+ }
118
+ : {
119
+ note: "permissions 是配置白名单。若 actor.isAdmin=true,data.submit 成功可能只是管理员绕过,不证明白名单对普通用户生效。",
120
+ }),
121
+ };
122
+ }),
123
+ }));
124
+ writeTool({
125
+ tools,
126
+ name: "workflow.addPermission",
127
+ search: { intents: ["加发起权限", "给流程加发起权限", "授予发起权限", "谁能发起流程"] },
128
+ lane: WORKFLOW_LANE,
129
+ scope: WORKFLOW_TOOLS["workflow.addPermission"].scope,
130
+ description: WORKFLOW_TOOLS["workflow.addPermission"].description,
131
+ inputSchema: {
132
+ workflowCode: z.string().optional().describe("流程 code;省略则用 schemaCode 解析"),
133
+ schemaCode: z.string().optional().describe("模型 code:省略 workflowCode 时用它解析该模型的流程"),
134
+ unitId: z.string().min(1).describe("部门 id / 角色 id / 用户 id(看 unitType)"),
135
+ unitType: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal("DEPARTMENT"), z.literal("ROLE"), z.literal("USER")]).describe("1=部门 2=角色 3=用户;也接受 DEPARTMENT/ROLE/USER"),
136
+ corpId: z.string().optional().describe("企业 id;省略则用当前会话企业"),
137
+ },
138
+ execute: async (session, args) => {
139
+ const workflowCode = await resolveWorkflowArg(session, args);
140
+ if (!workflowCode)
141
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-not-found", message: `模型 ${String(args.schemaCode ?? "")} 没有流程;先 workflow.create` });
142
+ const unitType = args.unitType === 1 || args.unitType === "DEPARTMENT" ? 1 : args.unitType === 2 || args.unitType === "ROLE" ? 2 : 3;
143
+ // Idempotent retry: the platform answers 402003 WORKFLOW_PERMISSION_EXIST
144
+ // for a duplicate unitId, which would read as a failure. `list_permission`
145
+ // does NOT echo unitId (only id/name/unitType/fullName/code), so identity
146
+ // is decided by the platform's own refusal rather than a guessed pre-read.
147
+ const before = await permissionRows(session, workflowCode);
148
+ try {
149
+ // Send the unit's own name/code too: `list_permission` reads them back
150
+ // (it echoes `name`/`code`), which is the only way `workflow.permissions`
151
+ // can describe a row by more than its opaque permission id.
152
+ const identity = await unitIdentity(session, unitType, args.unitId);
153
+ await wireCall(session, {
154
+ path: ENDPOINTS.workflowCreatePermission,
155
+ method: "POST",
156
+ body: {
157
+ workflowCode,
158
+ unitId: args.unitId,
159
+ unitType,
160
+ corpId: args.corpId ?? session.enterpriseId(),
161
+ ...(identity.name ? { name: identity.name } : {}),
162
+ ...(identity.code ? { code: identity.code } : {}),
163
+ },
164
+ });
165
+ }
166
+ catch (error) {
167
+ const errcode = error.details?.errcode ?? error.errcode;
168
+ if (String(errcode ?? "") !== "402003")
169
+ throw new ToolRefusalError({
170
+ status: "refused",
171
+ blocker: "workflow-permission-write-failed",
172
+ workflowCode,
173
+ unitId: args.unitId,
174
+ unitType,
175
+ message: `create_permission 被平台拒绝(err=${String(errcode ?? "n/a")})。核对 unitId 是否真实存在(部门用 org.department.list、角色用 org.role.list、用户用 org.user.search),以及发起权限是否被企业策略禁用。原始错误:${error instanceof Error ? error.message : String(error)}`,
176
+ });
177
+ const actor = await resolvePermissionActor(session);
178
+ return {
179
+ performed: { skipped: "already-present" },
180
+ readback: { workflowCode, alreadyPresent: true, unitId: args.unitId, unitType, count: before.length, note: "该主体已有发起权限(平台 402003),未重复写入", actor },
181
+ };
182
+ }
183
+ const after = await permissionRows(session, workflowCode);
184
+ const created = after.find((row) => !before.some((old) => String(old.id ?? "") === String(row.id ?? ""))) ?? after[after.length - 1];
185
+ const actor = await resolvePermissionActor(session);
186
+ return {
187
+ performed: { errcode: 0 },
188
+ readback: {
189
+ workflowCode,
190
+ count: after.length,
191
+ permissionId: created?.id ?? null,
192
+ unitType: created?.unitType ?? unitType,
193
+ name: created?.name ?? null,
194
+ actor,
195
+ note: "发起权限已授予。若之前 data.submit 回 40009,现在应可发起;仍失败先 workflow.permissions 确认行存在,并核对发起人所属部门/角色。管理员发起成功不证明白名单对普通人生效。",
196
+ },
197
+ };
198
+ },
199
+ rollback: {
200
+ target: (args) => `workflow-permission:${String(args.workflowCode ?? args.schemaCode ?? "")}`,
201
+ read: async (session, args) => {
202
+ const workflowCode = await resolveWorkflowArg(session, { workflowCode: args.workflowCode, schemaCode: args.schemaCode });
203
+ if (!workflowCode)
204
+ return null;
205
+ return permissionRows(session, workflowCode);
206
+ },
207
+ inverse: ({ before, args, readback }) => {
208
+ if (readback.alreadyPresent === true)
209
+ return { kind: "calls", calls: [], notes: ["权限行已存在(幂等),未写入,无需回滚"] };
210
+ const permissionId = readback.permissionId;
211
+ if (typeof permissionId === "string" && permissionId.length > 0)
212
+ return { kind: "calls", calls: [{ tool: "workflow.removePermission", args: { permissionId } }] };
213
+ return { kind: "irreversible", reason: "addPermission 回执缺少 permissionId,无法自动撤权;用 workflow.permissions 找 id 后手工 removePermission" };
214
+ },
215
+ },
216
+ });
217
+ writeTool({
218
+ tools,
219
+ name: "workflow.removePermission",
220
+ search: { intents: ["撤销发起权限", "撤销权限", "取消发起权限"] },
221
+ lane: WORKFLOW_LANE,
222
+ scope: WORKFLOW_TOOLS["workflow.removePermission"].scope,
223
+ description: WORKFLOW_TOOLS["workflow.removePermission"].description,
224
+ inputSchema: {
225
+ permissionId: z.string().min(1).optional().describe("首选:workflow.permissions 返回的 id(唯一确定)"),
226
+ workflowCode: z.string().optional().describe("配合 unitId+unitType 使用(平台的 list_permission 不回 unitId,需按显示名解析)"),
227
+ unitId: z.string().min(1).optional().describe("部门/角色/用户 id;按 unitType 解析显示名后匹配权限行"),
228
+ unitType: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal("DEPARTMENT"), z.literal("ROLE"), z.literal("USER")]).optional().describe("unitId 的类型:1=部门 2=角色 3=用户"),
229
+ schemaCode: z.string().optional(),
230
+ },
231
+ execute: async (session, args) => {
232
+ let permissionId = args.permissionId;
233
+ let workflowCodeForActor;
234
+ let beforeRow = null;
235
+ if (!permissionId) {
236
+ const workflowCode = await resolveWorkflowArg(session, { workflowCode: args.workflowCode, schemaCode: args.schemaCode });
237
+ workflowCodeForActor = workflowCode ?? undefined;
238
+ if (!workflowCode || !args.unitId || args.unitType === undefined)
239
+ throw new ToolInputError({ status: "error", blocker: "tool-input-invalid", tool: "workflow.removePermission", message: "需要 permissionId(推荐),或 workflowCode(/schemaCode)+ unitId + unitType" });
240
+ const unitType = args.unitType === 1 || args.unitType === "DEPARTMENT" ? 1 : args.unitType === 2 || args.unitType === "ROLE" ? 2 : 3;
241
+ const identity = await unitIdentity(session, unitType, args.unitId);
242
+ const rows = await permissionRows(session, workflowCode);
243
+ const wantedType = String(unitType);
244
+ const hit = rows.find((row) => String(row.unitType ?? "") === wantedType && (String(row.id ?? "") === args.unitId ||
245
+ // list_permission echoes `code` (unit business code or, on some faces, the
246
+ // unitId itself) but never unitId — accept both spellings so remove by
247
+ // unitId does not silently miss (r30d F11 / fake+live).
248
+ String(row.code ?? "") === args.unitId ||
249
+ (identity.name !== null && String(row.name ?? "") === identity.name) ||
250
+ (identity.code !== null && String(row.code ?? "") === identity.code) ||
251
+ (identity.name !== null && String(row.fullName ?? "") === identity.name)));
252
+ if (!hit) {
253
+ const actor = await resolvePermissionActor(session);
254
+ return {
255
+ performed: { skipped: "absent" },
256
+ readback: {
257
+ workflowCode,
258
+ removed: false,
259
+ note: `没有匹配该主体的权限行(幂等)。注意 list_permission 不回 unitId,匹配靠解析出的显示名「${identity.name ?? "?"}」/code;不确定时用 workflow.permissions 拿 id 再按 permissionId 删。`,
260
+ permissions: rows.map((row) => ({ id: row.id ?? null, name: row.name ?? null, unitType: row.unitType ?? null, code: row.code ?? null })),
261
+ actor,
262
+ },
263
+ };
264
+ }
265
+ beforeRow = {
266
+ id: hit.id ?? null,
267
+ name: hit.name ?? null,
268
+ unitType: hit.unitType ?? unitType,
269
+ fullName: hit.fullName ?? null,
270
+ code: hit.code ?? null,
271
+ corpId: hit.corpId ?? null,
272
+ unitId: args.unitId,
273
+ };
274
+ permissionId = String(hit.id ?? "");
275
+ }
276
+ else {
277
+ // Capture the row being removed so the receipt has a rebuildable before
278
+ // face even when the caller only passed permissionId (r30d F11).
279
+ const workflowCode = await resolveWorkflowArg(session, { workflowCode: args.workflowCode, schemaCode: args.schemaCode }).catch(() => null);
280
+ workflowCodeForActor = workflowCode ?? undefined;
281
+ if (workflowCode) {
282
+ const rows = await permissionRows(session, workflowCode);
283
+ const hit = rows.find((row) => String(row.id ?? "") === permissionId);
284
+ if (hit)
285
+ beforeRow = {
286
+ id: hit.id ?? null,
287
+ name: hit.name ?? null,
288
+ unitType: hit.unitType ?? null,
289
+ fullName: hit.fullName ?? null,
290
+ code: hit.code ?? null,
291
+ corpId: hit.corpId ?? null,
292
+ };
293
+ }
294
+ }
295
+ await wireCall(session, { path: ENDPOINTS.workflowDeletePermission, method: "POST", query: { permissionId } });
296
+ const actor = await resolvePermissionActor(session);
297
+ return {
298
+ performed: { errcode: 0 },
299
+ readback: {
300
+ permissionId,
301
+ removed: true,
302
+ ...(workflowCodeForActor ? { workflowCode: workflowCodeForActor } : {}),
303
+ before: beforeRow,
304
+ actor,
305
+ ...(beforeRow
306
+ ? {}
307
+ : { rollbackable: false, rollbackNote: "删除前未捕获到权限行详情(只给了 permissionId 且未能解析所属流程);撤错需手工按 id 复建。" }),
308
+ },
309
+ };
310
+ },
311
+ preflight: (args) => {
312
+ // R75-B(2026-11-18):目标形状是纯参数门——此前只在 execute 里,dry-run
313
+ // 绿灯、真写 tool-input-invalid。schemaCode→workflowCode 的解析仍留给
314
+ // execute(需要 session),这里只拒绝「怎么补都缺」的形状。
315
+ if (args.permissionId !== undefined && typeof args.permissionId === "string" && args.permissionId !== "")
316
+ return;
317
+ if (args.workflowCode === undefined && args.schemaCode === undefined)
318
+ throw new ToolInputError({ status: "error", blocker: "tool-input-invalid", tool: "workflow.removePermission", message: "需要 permissionId(推荐),或 workflowCode(/schemaCode)+ unitId + unitType(缺流程定位)" });
319
+ if (args.unitId === undefined || args.unitType === undefined)
320
+ throw new ToolInputError({ status: "error", blocker: "tool-input-invalid", tool: "workflow.removePermission", message: "需要 permissionId(推荐),或 workflowCode(/schemaCode)+ unitId + unitType(缺主体定位)" });
321
+ },
322
+ rollback: {
323
+ target: (args) => `workflow-permission:${String(args.workflowCode ?? args.schemaCode ?? args.permissionId ?? "")}`,
324
+ read: async (session, args) => {
325
+ // Prefer resolving the concrete row so inverse can re-add it.
326
+ const workflowCode = await resolveWorkflowArg(session, { workflowCode: args.workflowCode, schemaCode: args.schemaCode }).catch(() => null);
327
+ if (!workflowCode)
328
+ return null;
329
+ const rows = await permissionRows(session, workflowCode);
330
+ if (typeof args.permissionId === "string" && args.permissionId) {
331
+ return rows.find((row) => String(row.id ?? "") === args.permissionId) ?? null;
332
+ }
333
+ if (typeof args.unitId === "string" && args.unitType !== undefined) {
334
+ const unitType = args.unitType === 1 || args.unitType === "DEPARTMENT" ? 1 : args.unitType === 2 || args.unitType === "ROLE" ? 2 : 3;
335
+ const identity = await unitIdentity(session, unitType, args.unitId);
336
+ return rows.find((row) => String(row.unitType ?? "") === String(unitType) && (String(row.id ?? "") === args.unitId ||
337
+ String(row.code ?? "") === args.unitId ||
338
+ (identity.name !== null && String(row.name ?? "") === identity.name) ||
339
+ (identity.code !== null && String(row.code ?? "") === identity.code) ||
340
+ (identity.name !== null && String(row.fullName ?? "") === identity.name))) ?? null;
341
+ }
342
+ return null;
343
+ },
344
+ inverse: ({ before, args }) => {
345
+ if (before == null)
346
+ return { kind: "irreversible", reason: "removePermission 前未捕获到权限行(before 为空),无法自动复建;用 workflow.addPermission 手工补回" };
347
+ const row = before;
348
+ const workflowCode = String(args.workflowCode ?? "");
349
+ const unitId = typeof args.unitId === "string" && args.unitId ? args.unitId : null;
350
+ const unitType = args.unitType !== undefined
351
+ ? (args.unitType === 1 || args.unitType === "DEPARTMENT" ? 1 : args.unitType === 2 || args.unitType === "ROLE" ? 2 : 3)
352
+ : (row.unitType === 1 || row.unitType === "1" ? 1 : row.unitType === 2 || row.unitType === "2" ? 2 : row.unitType === 3 || row.unitType === "3" ? 3 : null);
353
+ if (!workflowCode || !unitId || unitType === null)
354
+ return {
355
+ kind: "irreversible",
356
+ reason: `before 有行(name=${String(row.name ?? "?")} unitType=${String(row.unitType ?? "?")}),但缺少可重放的 workflowCode+unitId+unitType;请手工:omc call workflow.addPermission --args '{"workflowCode":"<code>","unitId":"<id>","unitType":${unitType ?? 2}}'`,
357
+ partial: [],
358
+ };
359
+ return {
360
+ kind: "calls",
361
+ calls: [{ tool: "workflow.addPermission", args: { workflowCode, unitId, unitType } }],
362
+ notes: [`复建被删行:name=${String(row.name ?? "?")} unitType=${unitType}`],
363
+ };
364
+ },
365
+ },
366
+ });
367
+ tools.push(defineTool({
368
+ name: "org.role.list",
369
+ search: { intents: ["有哪些角色", "角色清单", "列出角色", "看角色组和角色"] },
370
+ layer: "low",
371
+ kind: "read",
372
+ lane: WORKFLOW_LANE,
373
+ scope: WORKFLOW_TOOLS["org.role.list"].scope,
374
+ description: WORKFLOW_TOOLS["org.role.list"].description,
375
+ inputSchema: { environment: environmentArg, search: z.string().min(1).optional().describe("关键字过滤(CLI 侧,按 code/name 不区分大小写子串);服务端无关键字面,过滤在本地做——避免为找一个 code 全量 dump"), expandAll: z.boolean().optional().describe("默认 true:展开所有角色组并带回角色。平台的 /role/list 只有 expandAll=true 才填 children(RoleController.list,1.1.25);传 false 只回角色组、roles 恒为空,别据此判断「角色未创建」"), capability: capabilityArg },
376
+ handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
377
+ // `/role/list` without `expandAll=true` only expands the FIRST group's
378
+ // children (RoleController.list, 1.1.25), so a role created under any
379
+ // other group is invisible — r9 read that as "role not created" and
380
+ // burned 8 org.role.list calls. Always expand; expose the flag only so
381
+ // a caller can ask for the container-only face deliberately.
382
+ const expandAll = args.expandAll ?? true;
383
+ const data = (await wireCall(session, {
384
+ path: ENDPOINTS.organizationRoleList,
385
+ query: expandAll ? { expandAll: "true" } : {},
386
+ })).data;
387
+ const flat = flattenRoleTree(wireRows(data));
388
+ // issue#9 C2:冷启动按关键字取角色,避免全量进上下文
389
+ const search = args.search;
390
+ if (typeof search === "string" && search.trim().length > 0) {
391
+ const needle = search.trim().toLowerCase();
392
+ const roles = flat.roles ?? [];
393
+ const groups = flat.groups ?? [];
394
+ const hit = (row) => String(row.code ?? "").toLowerCase().includes(needle) || String(row.name ?? "").toLowerCase().includes(needle);
395
+ return {
396
+ ...flat,
397
+ roles: roles.filter(hit),
398
+ groups: groups.filter(hit),
399
+ filteredBy: search,
400
+ totalBeforeFilter: roles.length,
401
+ };
402
+ }
403
+ return flat;
404
+ }, {
405
+ compact: (result) => ({
406
+ ...result,
407
+ roles: Array.isArray(result.roles) ? result.roles : [],
408
+ groups: Array.isArray(result.groups) ? result.groups : [],
409
+ }),
410
+ }),
411
+ }));
412
+ tools.push(defineTool({
413
+ name: "org.department.list",
414
+ search: { intents: ["查部门树", "部门列表", "查部门", "组织架构"] },
415
+ layer: "low",
416
+ kind: "read",
417
+ lane: WORKFLOW_LANE,
418
+ scope: WORKFLOW_TOOLS["org.department.list"].scope,
419
+ description: WORKFLOW_TOOLS["org.department.list"].description,
420
+ inputSchema: { environment: environmentArg, parentId: z.string().min(1).optional().describe("只列出该部门及其下属(BFS 展开;默认从根展开整棵部门树)"), capability: capabilityArg },
421
+ handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
422
+ // `/department/tree` semantics (re-verified r15, 1.1.25): no `deptIds`
423
+ // → ROOTS; `deptIds=<id>` → DIRECT CHILDREN. The old "whole subtree"
424
+ // reading hid third-level departments (电气组) from this list. The shared
425
+ // walker does a bounded BFS.
426
+ const requested = args.parentId;
427
+ const walked = await collectOrgDepartments(session, requested === undefined ? {} : { rootId: requested });
428
+ const levels = walked.rows;
429
+ const departments = levels.map((dept) => ({
430
+ id: dept.id ?? null,
431
+ name: dept.name ?? null,
432
+ code: dept.code ?? null,
433
+ corpId: dept.corpId ?? null,
434
+ parentId: dept.parentId ?? null,
435
+ }));
436
+ return { count: departments.length, departments };
437
+ }, {
438
+ // r28h F2: default CODE_NAME_LIST_KEYS collapses departments to
439
+ // `id|name` and drops parentId — the one field this tool exists for.
440
+ // Keep a dedicated slim shape that preserves hierarchy.
441
+ compact: (result) => {
442
+ const rows = Array.isArray(result.departments) ? result.departments : [];
443
+ return {
444
+ count: result.count ?? rows.length,
445
+ departments: rows.map((row) => ({
446
+ id: row.id ?? null,
447
+ name: row.name ?? null,
448
+ code: row.code ?? null,
449
+ parentId: row.parentId ?? null,
450
+ })),
451
+ departmentsCount: rows.length,
452
+ };
453
+ },
454
+ }),
455
+ }));
456
+ tools.push(defineTool({
457
+ name: "org.user.search",
458
+ search: { intents: ["搜员工", "找人", "按名字查用户", "搜索账号"] },
459
+ layer: "low",
460
+ kind: "read",
461
+ lane: WORKFLOW_LANE,
462
+ scope: WORKFLOW_TOOLS["org.user.search"].scope,
463
+ description: `${WORKFLOW_TOOLS["org.user.search"].description} 返回 count=本页 users 条数、total=总命中数;没有本页结果时两者均为 0。`,
464
+ inputSchema: {
465
+ environment: environmentArg,
466
+ // `wd` is the platform's own key; `keyword`/`q` are accepted aliases so a
467
+ // caller that reaches for the natural word is not bounced with
468
+ // "wd: Required" (round 10: an agent sent `keyword` and burned a retry).
469
+ wd: z.string().optional().describe("搜索关键字(用户姓名或账号用户名);**省略则列出全部员工**(工具按部门树聚合,见 description)。可用 keyword/q 作别名"),
470
+ keyword: z.string().optional().describe("`wd` 的别名"),
471
+ q: z.string().optional().describe("`wd` 的别名"),
472
+ page: z.number().int().min(0).optional().describe("页号,默认 0"),
473
+ size: z.number().int().min(1).optional().describe("每页条数,默认 100"),
474
+ filterType: z.string().optional().describe("admin=只搜当前应用管理员可见范围(可省)"),
475
+ capability: capabilityArg,
476
+ },
477
+ handler: async (ctx, args, self) => {
478
+ const keyword = args.wd ?? args.keyword ?? args.q;
479
+ // 0.4.81 (r11 2026-10-24): no keyword used to be a hard refusal, and the
480
+ // platform rejects an empty `wd` (10005), so the r11 probe enumerated
481
+ // `wd` = 0..9 to discover users — 11 calls, ~16 KB, to learn a roster the
482
+ // platform can already answer. Omitted keyword now aggregates
483
+ // `department/list_user` over the department tree (one tool call).
484
+ // r28h F4: ≤50 users inline as {id,name,username,departmentId}; larger
485
+ // rosters fall back to count + artifact. Default summarizeValue was folding
486
+ // a 12-person roster into `{count,sha256,omitted:true}`.
487
+ const userSearchCompact = (result) => {
488
+ const rows = Array.isArray(result.users) ? result.users : [];
489
+ const slim = rows.map((row) => ({
490
+ id: row.id ?? null,
491
+ name: row.name ?? null,
492
+ username: row.username ?? null,
493
+ departmentId: row.departmentId ?? null,
494
+ }));
495
+ return {
496
+ keyword: result.keyword ?? null,
497
+ count: result.count ?? rows.length,
498
+ total: result.total ?? rows.length,
499
+ ...(result.departmentsScanned !== undefined ? { departmentsScanned: result.departmentsScanned } : {}),
500
+ ...(result.truncated === true ? { truncated: true } : {}),
501
+ ...(typeof result.note === "string" ? { note: result.note } : {}),
502
+ ...(typeof result.hint === "string" ? { hint: result.hint } : {}),
503
+ users: slim.length <= 50 ? slim : { count: slim.length, omitted: true },
504
+ ...(slim.length > 50 ? { usersCount: slim.length } : {}),
505
+ };
506
+ };
507
+ if (!keyword) {
508
+ return governedRead(ctx, self, args, async (session) => {
509
+ const orgQuery = { corpId: session.enterpriseId() };
510
+ // r15: `deptIds` answers DIRECT CHILDREN only, so the earlier
511
+ // roots + one-level walk missed users in third-level departments.
512
+ const walked = await collectOrgDepartments(session, { limit: 200 });
513
+ const order = walked.rows.map((row) => row.id);
514
+ const seenUsers = new Map();
515
+ let departmentsScanned = 0;
516
+ for (const deptId of order.slice(0, 200)) {
517
+ departmentsScanned += 1;
518
+ for (const row of wireRows((await wireCall(session, { path: ENDPOINTS.organizationDepartmentUsers, query: { ...orgQuery, deptId } })).data)) {
519
+ const id = String(row.id ?? row.userId ?? "");
520
+ if (id === "" || seenUsers.has(id))
521
+ continue;
522
+ seenUsers.set(id, {
523
+ id: row.id ?? row.userId ?? null,
524
+ name: row.name ?? null,
525
+ username: row.username ?? null,
526
+ userId: row.userId ?? null,
527
+ departmentId: row.departmentId ?? deptId,
528
+ mobile: row.mobile ?? null,
529
+ });
530
+ }
531
+ }
532
+ const users = [...seenUsers.values()];
533
+ return {
534
+ keyword: null,
535
+ count: users.length,
536
+ total: users.length,
537
+ departmentsScanned,
538
+ ...(walked.truncated || order.length >= 200 ? { truncated: true, note: `部门树超过 200 个,只聚合了前 200 个;用 wd 关键字精确检索` } : {}),
539
+ users,
540
+ hint: "无关键字=列全员(按部门树聚合)。平台 user/search 的 wd 不支持空串(10005),所以这条路径走 department/list_user;只要某部门的人用 org.department.users。",
541
+ };
542
+ }, { compact: userSearchCompact });
543
+ }
544
+ return governedRead(ctx, self, { ...args, wd: keyword }, async (session) => {
545
+ const body = { wd: keyword, page: args.page ?? 0, size: args.size ?? 100 };
546
+ if (args.filterType !== undefined)
547
+ body.filterType = args.filterType;
548
+ const data = (await wireCall(session, { path: ENDPOINTS.organizationUserSearch, method: "POST", body })).data;
549
+ const rows = Array.isArray(data?.content) ? data.content : wireRows(data);
550
+ const users = rows.map((user) => ({
551
+ id: user.id ?? null,
552
+ name: user.name ?? null,
553
+ username: user.username ?? null,
554
+ userId: user.userId ?? null,
555
+ code: user.code ?? null,
556
+ departmentId: user.departmentId ?? null,
557
+ corpId: user.corpId ?? null,
558
+ status: user.status ?? null,
559
+ }));
560
+ const totalHits = users.length === 0 ? 0 : (typeof data?.totalElements === "number" ? data.totalElements : users.length);
561
+ return { keyword, count: users.length, total: totalHits, users };
562
+ }, { compact: userSearchCompact });
563
+ },
564
+ }));
565
+ // ──────────────────────────────────────────────────────────────────────────
566
+ // r64 流程运维三件套(用户需求 2026-11-14:「流程运维把当前审批人换成我自己 /
567
+ // 手动结束流程触发规则 / 运维到指定节点」)。**定位:测试提速工具**——快速
568
+ // 造/推测试数据用;真实流程与权限验证必须走 data.submit 正常链(换过审批人/
569
+ // 跳过节点的实例,权限语义已变)。端点形状全部真机实证(详见 r64 TASK-RESULT)。
570
+ }
571
+ //# sourceMappingURL=permissions.js.map