weaver-work-cli 0.1.60 → 0.1.61

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 (121) hide show
  1. package/dist/chunks/{archive-4SQAVTIB.js → archive-S2VKZWQ3.js} +2 -2
  2. package/dist/chunks/{archive-oa-W2UEJ67L.js → archive-oa-HEDSIUUY.js} +2 -2
  3. package/dist/chunks/{asset-EGZEABBI.js → asset-HYH4W357.js} +2 -2
  4. package/dist/chunks/{asset-idle-EBUZBB6M.js → asset-idle-N7REBNGL.js} +2 -2
  5. package/dist/chunks/{attachment-content-I6WHKGR2.js → attachment-content-VYYA75FR.js} +3 -3
  6. package/dist/chunks/{blog-2YKMWOWI.js → blog-SLMZZICV.js} +2 -2
  7. package/dist/chunks/{caizhilian-5NM4X5HG.js → caizhilian-RV43KKBT.js} +4 -4
  8. package/dist/chunks/{calendar-H4QTJCUY.js → calendar-DMVZ4OLY.js} +2 -2
  9. package/dist/chunks/{chunk-VLL6JOB4.js → chunk-6XSSAUNW.js} +4 -4
  10. package/dist/chunks/{chunk-VQWPQTEY.js → chunk-BIA2NKUG.js} +4 -4
  11. package/dist/chunks/{chunk-VMCCRWFO.js → chunk-BQYX2UX5.js} +2 -2
  12. package/dist/chunks/{chunk-XF7S6FQW.js → chunk-DTCQFTHW.js} +1 -1
  13. package/dist/chunks/{chunk-CPG6NLN4.js → chunk-E5YD5JWR.js} +1 -1
  14. package/dist/chunks/{chunk-PH7N4UFT.js → chunk-EGANE35F.js} +1 -1
  15. package/dist/chunks/{chunk-Z4IPY5GV.js → chunk-H6YOMI3U.js} +2 -2
  16. package/dist/chunks/{chunk-HHH4K3YY.js → chunk-ILALC2N6.js} +1 -1
  17. package/dist/chunks/{chunk-WINR2Q6K.js → chunk-KXJA42EA.js} +86 -19
  18. package/dist/chunks/{chunk-CQ4OVCKG.js → chunk-KY3R42RS.js} +2 -2
  19. package/dist/chunks/{chunk-WVH5ESDA.js → chunk-NRYDJN4J.js} +1 -1
  20. package/dist/chunks/{chunk-TGM7BWEH.js → chunk-P6TXQK75.js} +2 -2
  21. package/dist/chunks/{chunk-6YWHRXEQ.js → chunk-QBDXJS2W.js} +119 -9
  22. package/dist/chunks/{chunk-2IGZUMNG.js → chunk-SHX7XBYR.js} +180 -18
  23. package/dist/chunks/{chunk-P7RXQDCA.js → chunk-T2KVJFWJ.js} +4 -4
  24. package/dist/chunks/{chunk-FMNCSYIG.js → chunk-TEZHIB6T.js} +2 -2
  25. package/dist/chunks/{chunk-HMIIVM2L.js → chunk-UBGWIXU3.js} +97 -45
  26. package/dist/chunks/{chunk-5N222HK6.js → chunk-UBRWONP4.js} +2 -2
  27. package/dist/chunks/{chunk-7U5YHCW7.js → chunk-UQFPF4EX.js} +2 -2
  28. package/dist/chunks/{chunk-4GG72JAT.js → chunk-V2LASYKO.js} +2 -2
  29. package/dist/chunks/{chunk-BDBTZVYA.js → chunk-VBFBMM7G.js} +55 -55
  30. package/dist/chunks/{chunk-YHSOCGKO.js → chunk-VNYOUAWV.js} +11 -11
  31. package/dist/chunks/{chunk-SFM3M2L3.js → chunk-WIWDVETN.js} +19 -3
  32. package/dist/chunks/{chunk-44KJ7WFA.js → chunk-XT77MP54.js} +2 -2
  33. package/dist/chunks/{chunk-JFKMPRZB.js → chunk-YI2YMW5N.js} +50 -3
  34. package/dist/chunks/{conflict-QMDLS2EW.js → conflict-GFJRS6I7.js} +2 -2
  35. package/dist/chunks/{contract-LLRKMLQQ.js → contract-U3ZGNRWB.js} +2 -2
  36. package/dist/chunks/{cowork-2RDFBZWB.js → cowork-EX7PKIDK.js} +2 -2
  37. package/dist/chunks/{create-flow-5ODJ7WJO.js → create-flow-EJZD434E.js} +6 -6
  38. package/dist/chunks/{data-LVDFIRNG.js → data-FOODGAMF.js} +278 -121
  39. package/dist/chunks/{ebuilder-form-7WA6X6ZI.js → ebuilder-form-I2EOKODG.js} +3 -3
  40. package/dist/chunks/{ehr-52GBKNJR.js → ehr-TE4RFNID.js} +2 -2
  41. package/dist/chunks/{entry-mode-73BJML22.js → entry-mode-ZOLSXEGX.js} +9 -5
  42. package/dist/chunks/{env-OHFS76HV.js → env-TID5NFR6.js} +2 -2
  43. package/dist/chunks/{esb-HJSXCEOM.js → esb-7L6MHYLB.js} +4 -4
  44. package/dist/chunks/{factory-FRTA2LP4.js → factory-OG7BPMH5.js} +1 -1
  45. package/dist/chunks/{fna-OBACRT3J.js → fna-6V2ENR3Y.js} +2 -2
  46. package/dist/chunks/{group-chat-KBFRPCR2.js → group-chat-5DKPWIHL.js} +3 -3
  47. package/dist/chunks/{host-TTSGY5NZ.js → host-3DLYA54R.js} +3 -3
  48. package/dist/chunks/{host-KJT3G5D2.js → host-GOJHHTPY.js} +3 -3
  49. package/dist/chunks/{host-KOWUMNAY.js → host-OGBHL75G.js} +3 -3
  50. package/dist/chunks/{host-MFXRA2MY.js → host-ONZC6AE7.js} +3 -3
  51. package/dist/chunks/{host-W4JCNRFS.js → host-TJ5VVHM7.js} +3 -3
  52. package/dist/chunks/{host-2BKMPWDH.js → host-VTPAWDZV.js} +3 -3
  53. package/dist/chunks/{hrm-AK3WGBMN.js → hrm-2N7NFQDZ.js} +3 -3
  54. package/dist/chunks/{im-JZSBPO4Z.js → im-XCH47ZBN.js} +3 -3
  55. package/dist/chunks/{invoice-6XDMPCWB.js → invoice-XQRKMGNY.js} +3 -3
  56. package/dist/chunks/{jiuchuanhui-K4EQU6GK.js → jiuchuanhui-PL6DRPBM.js} +2 -2
  57. package/dist/chunks/{lazy-dispatch-GCA6HDOB.js → lazy-dispatch-UATEN7H7.js} +5 -5
  58. package/dist/chunks/{mail-IKVCQCVZ.js → mail-Q7Z4CQ4D.js} +2 -2
  59. package/dist/chunks/{meeting-ARHVWK7G.js → meeting-5E3BNARL.js} +13 -13
  60. package/dist/chunks/{minute-doc-547KSYKR.js → minute-doc-NXRE5C77.js} +4 -4
  61. package/dist/chunks/{okr-KV43FPPX.js → okr-3O3XNYOK.js} +2 -2
  62. package/dist/chunks/{operations-6NXJ7RTE.js → operations-EZWG72FH.js} +4 -4
  63. package/dist/chunks/performance-Y7CPNSOR.js +1295 -0
  64. package/dist/chunks/{plan-WOYR4WEG.js → plan-BLGPZF5M.js} +2 -2
  65. package/dist/chunks/{project-CQJKBUIL.js → project-6MZMLJMP.js} +2 -2
  66. package/dist/chunks/{reception-MPBU3JXC.js → reception-F2VT2X52.js} +2 -2
  67. package/dist/chunks/{recruit-stage-USTTRHOX.js → recruit-stage-4ETIBMIW.js} +2 -2
  68. package/dist/chunks/{registry-GURQG4ZV.js → registry-3FYSWV3U.js} +3 -3
  69. package/dist/chunks/{registry-SS5J2FZQ.js → registry-7RS74TCK.js} +4 -4
  70. package/dist/chunks/{registry-H5HQ5QNH.js → registry-I4DVPDMU.js} +11 -11
  71. package/dist/chunks/{room-recommend-3UBROMZE.js → room-recommend-GWCVKCXW.js} +4 -4
  72. package/dist/chunks/{schedule-FTUQML6O.js → schedule-6AN63MJQ.js} +4 -4
  73. package/dist/chunks/{smart-extract-APX2PNIN.js → smart-extract-SR4SJJKN.js} +3 -3
  74. package/dist/chunks/{workflow-WMPW3WSB.js → workflow-KF7FA2UQ.js} +7 -7
  75. package/dist/cmd/refs/index.js +124 -4
  76. package/dist/core/output.js +199 -26
  77. package/dist/core/refs.js +36 -0
  78. package/dist/index.js +38 -33
  79. package/dist/internal/e10/auth/xiaoe.js +25 -3
  80. package/dist/shortcuts/caizhilian/operations/files.js +86 -15
  81. package/dist/shortcuts/data/index.js +12 -2
  82. package/dist/shortcuts/data/manifest.js +4 -2
  83. package/dist/shortcuts/data/operations/attribution.js +229 -0
  84. package/dist/shortcuts/data/operations/ds.js +87 -90
  85. package/dist/shortcuts/data/operations/index.js +3 -1
  86. package/dist/shortcuts/index.js +5 -0
  87. package/dist/shortcuts/meeting/operations/eb/create-flow.js +84 -16
  88. package/dist/shortcuts/meeting/operations/eb/entry-mode.js +61 -7
  89. package/dist/shortcuts/performance/continuation.js +74 -0
  90. package/dist/shortcuts/performance/errors.js +65 -0
  91. package/dist/shortcuts/performance/host.js +105 -0
  92. package/dist/shortcuts/performance/index.js +109 -0
  93. package/dist/shortcuts/performance/manifest.js +30 -0
  94. package/dist/shortcuts/performance/operations/hrm-resolve.js +114 -0
  95. package/dist/shortcuts/performance/operations/registry.js +44 -0
  96. package/dist/shortcuts/performance/operations/scheme-detail.js +70 -0
  97. package/dist/shortcuts/performance/operations/scheme-draft.js +116 -0
  98. package/dist/shortcuts/performance/operations/scheme-publish.js +158 -0
  99. package/dist/shortcuts/performance/operations/types.js +32 -0
  100. package/dist/shortcuts/performance/scheme-validate.js +307 -0
  101. package/dist/shortcuts/performance/shared.js +158 -0
  102. package/docs/agent-io-channel-design.md +67 -3
  103. package/docs/data.md +2 -1
  104. package/package.json +1 -1
  105. package/scripts/xiaoe_env.py +6 -1
  106. package/skill-template/business-info.json +19 -0
  107. package/skill-template/domains/performance.md +18 -0
  108. package/skills/weaver-e10-caizhilian/SKILL.md +1 -1
  109. package/skills/weaver-e10-data/references/datasource.md +2 -1
  110. package/skills/weaver-e10-meeting/SKILL.md +5 -3
  111. package/skills/weaver-e10-performance/SKILL.md +202 -0
  112. package/skills/weaver-e10-performance/agents/openai.yaml +74 -0
  113. package/skills/weaver-e10-performance/references/default-assembly.md +108 -0
  114. package/skills/weaver-e10-performance/references/entity-resolution.md +69 -0
  115. package/skills/weaver-e10-performance/references/enums-and-normalization.md +80 -0
  116. package/skills/weaver-e10-performance/references/examples.md +146 -0
  117. package/skills/weaver-e10-performance/references/extraction-guide.md +144 -0
  118. package/skills/weaver-e10-performance/references/scheme-edit-req-fields.md +185 -0
  119. package/skills/weaver-e10-performance/references/scheme-setting-page.md +62 -0
  120. package/skills/weaver-e10-performance/scripts/parse_appraisal_doc.py +483 -0
  121. package/skills/weaver-e10-shared/references/json-output-contract.md +5 -0
@@ -111,6 +111,7 @@ function multipartField(value) {
111
111
  /**
112
112
  * 组装 multipart/form-data。源 http_client 把 body 中的普通字段作为表单字段提交,
113
113
  * `_file_fields` 中声明的键作为文件字段提交。
114
+ * `start`/`size` 用于分片上传:只挂该切片的零拷贝视图,不复制整块内容。
114
115
  */
115
116
  export function buildMultipart(fields, file) {
116
117
  const form = new FormData();
@@ -123,7 +124,9 @@ export function buildMultipart(fields, file) {
123
124
  const mime = MIME_BY_EXT[extname(file.meta.name).toLowerCase()] || 'application/octet-stream';
124
125
  // Buffer 底层恒为普通 ArrayBuffer(fs.readFile 不给 SharedArrayBuffer),
125
126
  // 取零拷贝视图作为 Blob 分片,避免整块内容的多余拷贝。
126
- const bytes = new Uint8Array(file.meta.content.buffer, file.meta.content.byteOffset, file.meta.content.byteLength);
127
+ const start = file.start ?? 0;
128
+ const size = file.size ?? file.meta.content.byteLength - start;
129
+ const bytes = new Uint8Array(file.meta.content.buffer, file.meta.content.byteOffset + start, size);
127
130
  form.append(file.field, new Blob([bytes], { type: mime }), file.meta.name);
128
131
  }
129
132
  return form;
@@ -180,23 +183,91 @@ export async function uploadFileToServer(host, filePath, options = {}) {
180
183
  preUploadId: String(preUploadId),
181
184
  uploadType: String(uploadType),
182
185
  };
183
- const uploadResponse = await host.request({
186
+ const uploadPath = options.uploadPath ?? '/api/file/module/upload';
187
+ const operation = options.operation ?? 'caizhilian.file.upload';
188
+ const finalize = (data) => {
189
+ const result = {
190
+ file_id: String(data.fileid ?? ''),
191
+ name: data.name || meta.name,
192
+ size: data.size || meta.size,
193
+ ext_name: data.extName || '',
194
+ };
195
+ for (const field of options.extraResultFields ?? [])
196
+ result[field] = data[field] ?? 0;
197
+ return result;
198
+ };
199
+ if (uploadType === 'chunk') {
200
+ return await uploadChunked({
201
+ host,
202
+ meta,
203
+ uploadBody,
204
+ uploadPath,
205
+ operation,
206
+ preData,
207
+ finalize,
208
+ });
209
+ }
210
+ if (uploadType !== 'common' && uploadType !== 'second') {
211
+ throw caizhilianValidationError('upload_type_invalid', `文件服务返回未知上传策略: ${String(uploadType)}`);
212
+ }
213
+ // second / common:沿用整文件单发(second 的既有短路上面 uploadModuleDto 分支已处理)
214
+ const data = responseData(await host.request({
184
215
  method: 'POST',
185
- path: options.uploadPath ?? '/api/file/module/upload',
216
+ path: uploadPath,
186
217
  multipart: buildMultipart(uploadBody, { field: 'file', meta }),
187
218
  timeoutMs: TRANSFER_TIMEOUT_MS,
188
- operation: options.operation ?? 'caizhilian.file.upload',
189
- });
190
- const data = responseData(uploadResponse);
191
- const result = {
192
- file_id: String(data.fileid ?? ''),
193
- name: data.name || meta.name,
194
- size: data.size || meta.size,
195
- ext_name: data.extName || '',
196
- };
197
- for (const field of options.extraResultFields ?? [])
198
- result[field] = data[field] ?? 0;
199
- return result;
219
+ operation,
220
+ }));
221
+ return finalize(data);
222
+ }
223
+ /**
224
+ * 分片上传(对齐 weaver 端 upload_component 行为与 file-upload/protocol.ts 的判据):
225
+ * 预检返回 chunkDto.chunkSize(MiB)与 chunkCount,按 0 起编号逐片提交,
226
+ * 中间片必须显式 endChunk=false 且无文件 ID,末片必须给出非空文件 ID 且大小一致。
227
+ */
228
+ async function uploadChunked(deps) {
229
+ const { host, meta, uploadBody, uploadPath, operation, preData, finalize } = deps;
230
+ const chunkDto = asRecord(preData.chunkDto);
231
+ const chunkMiB = Number(chunkDto.chunkSize);
232
+ if (!Number.isSafeInteger(chunkMiB) || chunkMiB <= 0 || meta.size <= 0) {
233
+ throw caizhilianValidationError('chunk_size_invalid', '分片上传需要非空文件和正整数 MiB 分片大小');
234
+ }
235
+ const chunkSize = chunkMiB * 1024 * 1024;
236
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
237
+ throw caizhilianValidationError('chunk_size_invalid', '分片大小必须是有效的正 MiB 值');
238
+ }
239
+ const count = Math.max(1, Math.ceil(meta.size / chunkSize));
240
+ if (chunkDto.chunkCount !== undefined && Number(chunkDto.chunkCount) !== count) {
241
+ throw caizhilianValidationError('chunk_count_mismatch', '服务端分片数量与本地计算不一致');
242
+ }
243
+ for (let index = 0; index < count; index++) {
244
+ const start = index * chunkSize;
245
+ const size = Math.min(chunkSize, meta.size - start);
246
+ const response = await host.request({
247
+ method: 'POST',
248
+ path: uploadPath,
249
+ multipart: buildMultipart({ ...uploadBody, chunk: index, chunks: count, uploadShardSize: String(size) }, { field: 'file', meta, start, size }),
250
+ timeoutMs: TRANSFER_TIMEOUT_MS,
251
+ operation,
252
+ });
253
+ const data = responseData(response);
254
+ if (index === count - 1) {
255
+ const result = finalize(data);
256
+ if (!result.file_id) {
257
+ throw caizhilianValidationError('upload_not_terminal', '分片上传未返回非空文件 ID');
258
+ }
259
+ const reported = data.size;
260
+ if (reported !== undefined && reported !== null && reported !== '' && Number(reported) !== meta.size) {
261
+ throw caizhilianValidationError('upload_size_mismatch', '服务端文件大小与本地文件不一致');
262
+ }
263
+ return result;
264
+ }
265
+ const earlyFileId = data.fileid ?? data.fileId;
266
+ if (data.endChunk !== false || (earlyFileId !== undefined && earlyFileId !== null && String(earlyFileId) !== '')) {
267
+ throw caizhilianValidationError('chunk_terminal_early', '中间分片缺少明确未完成状态或提前返回文件 ID');
268
+ }
269
+ }
270
+ throw caizhilianValidationError('upload_not_terminal', '分片上传未确认完成');
200
271
  }
201
272
  function asRecord(value) {
202
273
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
@@ -116,7 +116,7 @@ export const dataShortcut = {
116
116
  // ---------------------------------------------------------------- ds
117
117
  const ds = data.command('ds').description('数据源:分组 / 找表 / 元数据 / 取数');
118
118
  ds.command('groups')
119
- .description('内置分组清单(仅用于 ds find 的默认扫描候选集)')
119
+ .description('数据源分组清单(实时 /api/dw/ds/group,sourceType=LOGIC)')
120
120
  .option('--pattern <sub>', '按 groupId / 中文名过滤')
121
121
  .action(action(async (ctx, options) => {
122
122
  await run(ctx, 'data.ds.groups', toInput(options), false);
@@ -130,7 +130,7 @@ export const dataShortcut = {
130
130
  .option('--pages <n>', '抓取页数(≤50),默认 1')
131
131
  .option('--concurrency <n>', '进程内并发数,默认 10')
132
132
  .option('--groups <a,b>', '显式指定扫描分组')
133
- .option('--all-groups', '扫描全部 58 个分组')
133
+ .option('--all-groups', '扫描全部实时分组')
134
134
  .option('--max-groups <n>', '默认扫描集上限,默认 6')
135
135
  .option('--app-id <id>', 'EB 分组按应用分域时显式传入')
136
136
  .option('--limit <n>', '候选上限')
@@ -245,6 +245,16 @@ export const dataShortcut = {
245
245
  .action(action(async (ctx, options) => {
246
246
  await run(ctx, 'data.noun.scope', toInput(options), false);
247
247
  }));
248
+ // ---------------------------------------------------------------- attribution
249
+ const attribution = data.command('attribution').description('归因分析设置(指标口径 / 维度 / 下钻路径)');
250
+ attribution.command('metric')
251
+ .description('按生效范围批量取归因分析设置(分组级 / 条目级绑定)')
252
+ .option('--ids <a,b|@f>', '生效范围 id 列表(分组 id + 条目 id 合并)')
253
+ .option('--group-ids <a,b|@f>', '仅分组 id(与 --ids 合并去重)')
254
+ .option('--item-ids <a,b|@f>', '仅条目 id(与 --ids 合并去重)')
255
+ .action(action(async (ctx, options) => {
256
+ await run(ctx, 'data.attribution.metric', toInput(options), false);
257
+ }));
248
258
  // ---------------------------------------------------------------- field
249
259
  const field = data.command('field').description('字段值翻译 / 选项字典');
250
260
  field.command('name2id')
@@ -31,6 +31,7 @@ const INPUT_SCHEMAS = {
31
31
  'data.ds.count': { required: ['group', 'table'], optional: ['where', 'source_type', 'app_id'] },
32
32
  'data.noun.list': { required: ['skill'], optional: ['source_type', 'source_group', 'source_table'] },
33
33
  'data.noun.scope': { required: ['ids'], optional: [] },
34
+ 'data.attribution.metric': { required: [], optional: ['ids', 'group_ids', 'item_ids'] },
34
35
  'data.field.name2id': { required: ['module', 'type', 'name'], optional: ['form_param', 'eb_browser_param', 'property_type'] },
35
36
  'data.field.options': { required: ['field_name', 'obj_id', 'group'], optional: ['source_type'] },
36
37
  'data.conf.get': { required: ['key'], optional: ['type', 'group'] },
@@ -64,7 +65,7 @@ function inputSchemaOf(name) {
64
65
  const spec = INPUT_SCHEMAS[name] || { required: [], optional: [] };
65
66
  const properties = {};
66
67
  for (const key of [...spec.required, ...spec.optional]) {
67
- properties[key] = { type: key === 'keys' || key === 'ids' ? 'array' : 'string' };
68
+ properties[key] = { type: key === 'keys' || key === 'ids' || key === 'group_ids' || key === 'item_ids' ? 'array' : 'string' };
68
69
  }
69
70
  return {
70
71
  type: 'object',
@@ -88,7 +89,7 @@ export const dataManifest = {
88
89
  host: 'e10-data',
89
90
  status: 'builtin',
90
91
  sourceSkill: 'weaver-e10-data',
91
- capabilities: ['dsl', 'discovery', 'metadata', 'fetch', 'lexicon', 'field', 'config', 'scene', 'module', 'attend'],
92
+ capabilities: ['dsl', 'discovery', 'metadata', 'fetch', 'lexicon', 'field', 'config', 'scene', 'module', 'attend', 'attribution'],
92
93
  auth: {
93
94
  required: 'e10-session',
94
95
  note: '所有操作都要求已登录 E10;登录统一走 `weaver-work-cli auth login --base-url <域名>`,data 模块不提供任何登录入口。',
@@ -102,6 +103,7 @@ export const dataManifest = {
102
103
  '人员 / 部门 / 岗位一律走 `weaver-work-cli hrm`;data 通道对 /api/hrm/ 路径有黑名单(退出码 6)。',
103
104
  '`hasSearchRight=false` 是权限受限(终端态):结果照常给出但退出码 4,不得交付为「无数据」。',
104
105
  '`field name2id`(名称→字段值 id)与 `ds fields`(字段元数据)是两件事;`id2name` 已停用并在本次迁移中删除。',
106
+ '`attribution metric` 取的是**归因分析设置**(指标口径 / 可关联维度 / 下钻路径),与 `noun scope` 的词库解释不同;归因分析优先用这里的设置,未配置时才回退通用流程。',
105
107
  ],
106
108
  operations: dataOperations,
107
109
  withheldOperations: [
@@ -0,0 +1,229 @@
1
+ import { dataApiError, dataValidationError } from '../errors.js';
2
+ import { readListArg } from './shared.js';
3
+ /**
4
+ * 归因分析设置(归因指标配置)。
5
+ *
6
+ * `getAttributionMetricByScopeId`:按**生效范围 id**批量取归因配置。范围既可绑在
7
+ * **场景分组**(分组级),也可绑在**组内条目**(条目级),因此入参与 `noun scope` 同构 ——
8
+ * 一次传「分组 id + 条目 id」的扁平列表,由后端按 `scopeEffectId` / `allScope` 归类。
9
+ *
10
+ * 与词库的分工:词库(`noun scope`)解释「指标叫什么、同义词、口径描述」;
11
+ * 本接口给的是**归因专用设置**(指标口径、可关联维度、下钻路径)。
12
+ * 归因分析应**优先**用这里的设置,取不到(未配置 / 空)才回退技能内的通用流程。
13
+ *
14
+ * 实测返回(2026-11-18):
15
+ * ```json
16
+ * { "data": [ { "id", "metricName", "caliber", "dimensions": "大;小",
17
+ * "drillPaths": "[\"大 > 小\"]", "allScope": 1, "scopeEffectId": "",
18
+ * "scopes": "", "scopeTableInfo": "[]", … } ],
19
+ * "actionMsg": { "code": 0, "message": "成功" } }
20
+ * ```
21
+ * ⚠️ 三个易错点(都已在本实现里处理):
22
+ * 1. **信封是 `{data, actionMsg}`**,业务码在 `actionMsg.code`,不在顶层 `code`;
23
+ * 2. **`allScope=1` 表示全局生效** —— 传任意 id(含不存在的 id)都会返回它,
24
+ * 因此「返回非空」不等于「本 scope 配过」,必须按 `scopeEffectId` / `allScope` 判归属;
25
+ * 3. **`dimensions` 是分号分隔字符串、`drillPaths` 是 JSON 数组字符串**(层级用 ` > ` 分隔),
26
+ * 不解析就只能当文本转述。
27
+ *
28
+ * ⚠️ id 一律按**字符串**下发:19 位雪花号超出 JS 安全整数(2^53),`Number()` 会丢精度
29
+ * → 下发即检不到配置,且不报错。
30
+ */
31
+ const ATTRIBUTION_PATH = '/api/dw/newetl/chatBi/attribution/getAttributionMetricByScopeId';
32
+ /** `--ids` / `--group-ids` / `--item-ids`:逗号/空白分隔,或 `@文件`(JSON 数组或逗号串)→ 字符串 id 数组。 */
33
+ function parseIds(value, flag) {
34
+ const raw = String(readListArg(value) ?? '').trim();
35
+ if (!raw)
36
+ return [];
37
+ const ids = raw
38
+ .replace(/^\[|\]$/g, '')
39
+ .split(/[,\s]+/)
40
+ .map((item) => item.trim().replace(/^["']|["']$/g, ''))
41
+ .filter(Boolean);
42
+ for (const id of ids) {
43
+ if (!/^\d+$/.test(id)) {
44
+ throw dataValidationError('ids_invalid', `${flag} 含非法项「${id}」(须为数字型 id:分组 id 取自 scene groups,条目 id 取自 scene items)`);
45
+ }
46
+ if (BigInt(id) > 9223372036854775807n) {
47
+ throw dataValidationError('ids_invalid', `${flag} 含超出 Long 上限的 id:${id}`);
48
+ }
49
+ }
50
+ return ids;
51
+ }
52
+ /** 合并 --ids 与 --group-ids/--item-ids,去重保序;三者全空即用法错误。 */
53
+ export function parseAttributionScopeIds(input) {
54
+ const ids = [
55
+ ...new Set([
56
+ ...parseIds(input.ids, '--ids'),
57
+ ...parseIds(input.group_ids, '--group-ids'),
58
+ ...parseIds(input.item_ids, '--item-ids'),
59
+ ]),
60
+ ];
61
+ if (!ids.length) {
62
+ throw dataValidationError('missing_argument', '缺少生效范围 id:请传 --ids(分组 id + 条目 id 合并),或分别传 --group-ids / --item-ids'
63
+ + '(如 --ids 1060565684758507537,2120434818314403840 或 --ids @ids.json)');
64
+ }
65
+ return ids;
66
+ }
67
+ function text(value) {
68
+ return value === null || value === undefined ? '' : String(value).trim();
69
+ }
70
+ /** 分号分隔的维度串 → 数组(去空、保序)。 */
71
+ export function splitDimensions(raw) {
72
+ const value = text(raw);
73
+ if (!value)
74
+ return [];
75
+ return value.split(/[;;]/).map((item) => item.trim()).filter(Boolean);
76
+ }
77
+ /**
78
+ * 下钻路径串 → 路径数组。
79
+ *
80
+ * 实测形态是 JSON 数组字符串 `["大 > 小"]`(层级用 ` > ` 分隔);也兼容直接传数组、
81
+ * 或未加 JSON 的裸写法 `大 > 小;中 > 小`(按 `;` 切成多条路径)。
82
+ */
83
+ export function parseDrillPaths(raw) {
84
+ if (Array.isArray(raw))
85
+ return raw.map((item) => splitPath(text(item))).filter((path) => path.length);
86
+ const value = text(raw);
87
+ if (!value)
88
+ return [];
89
+ try {
90
+ const parsed = JSON.parse(value);
91
+ if (Array.isArray(parsed))
92
+ return parsed.map((item) => splitPath(text(item))).filter((path) => path.length);
93
+ if (typeof parsed === 'string')
94
+ return [splitPath(parsed)].filter((path) => path.length);
95
+ }
96
+ catch {
97
+ // 非 JSON:按分号切成多条裸路径
98
+ }
99
+ return value.split(/[;;]/).map(splitPath).filter((path) => path.length);
100
+ }
101
+ function splitPath(value) {
102
+ return value.split(/\s*>\s*/).map((item) => item.trim()).filter(Boolean);
103
+ }
104
+ /**
105
+ * 归属判定:scopeEffectId 命中「条目 id」⇒ 条目级;命中分组 id ⇒ 分组级;
106
+ * 命中本次传入的其它 id ⇒ 范围级(`scoped`);`allScope=1` ⇒ 全局。
107
+ *
108
+ * `scoped` 这一档是为了「只传 `--ids` 合并列表」的常规用法:调用方把分组 id 与条目 id
109
+ * 混在一起传,脚本拿不到分类信息,但**能判断它命中了本次范围** —— 这已经足够表达
110
+ * 「这条设置是给本次对象的」,不能因为分不出层级就降级成 `other`(那会让调用方误判为无关设置)。
111
+ */
112
+ function scopeLevelOf(record, groupIds, itemIds, allIds) {
113
+ const effectId = text(record?.scopeEffectId);
114
+ const allScope = record?.allScope === null || record?.allScope === undefined ? null : Number(record.allScope);
115
+ if (effectId) {
116
+ if (itemIds.includes(effectId))
117
+ return { level: 'item', matchedId: effectId };
118
+ if (groupIds.includes(effectId))
119
+ return { level: 'group', matchedId: effectId };
120
+ // 只传 --ids 时分组 / 条目不分:命中本次入参即算「本范围命中」
121
+ if (allIds.includes(effectId))
122
+ return { level: 'scoped', matchedId: effectId };
123
+ return { level: 'other', matchedId: effectId };
124
+ }
125
+ if (allScope === 1)
126
+ return { level: 'global', matchedId: '' };
127
+ return { level: 'other', matchedId: '' };
128
+ }
129
+ const LEVEL_ORDER = { item: 0, group: 1, scoped: 2, other: 3, global: 4 };
130
+ const LEVEL_LABEL = {
131
+ item: '条目级',
132
+ group: '分组级',
133
+ scoped: '本次范围',
134
+ other: '其它范围',
135
+ global: '全局',
136
+ };
137
+ export function normalizeAttributionMetric(record, groupIds = [], itemIds = [], allIds = []) {
138
+ const { level, matchedId } = scopeLevelOf(record, groupIds, itemIds, allIds);
139
+ const normalized = {
140
+ id: text(record?.id),
141
+ metricName: text(record?.metricName),
142
+ caliber: text(record?.caliber),
143
+ dimensions: splitDimensions(record?.dimensions),
144
+ drillPaths: parseDrillPaths(record?.drillPaths),
145
+ allScope: record?.allScope === null || record?.allScope === undefined ? null : Number(record.allScope),
146
+ scopeEffectId: text(record?.scopeEffectId),
147
+ scopeLevel: level,
148
+ matchedId,
149
+ scopes: text(record?.scopes),
150
+ scopeTableInfo: parseJsonOrRaw(record?.scopeTableInfo),
151
+ };
152
+ if (record?.creator !== undefined)
153
+ normalized.creator = text(record.creator);
154
+ if (record?.createTime !== undefined)
155
+ normalized.createTime = text(record.createTime);
156
+ if (record?.updateTime !== undefined)
157
+ normalized.updateTime = text(record.updateTime);
158
+ return normalized;
159
+ }
160
+ function parseJsonOrRaw(value) {
161
+ const raw = text(value);
162
+ if (!raw)
163
+ return value ?? null;
164
+ try {
165
+ return JSON.parse(raw);
166
+ }
167
+ catch {
168
+ return raw;
169
+ }
170
+ }
171
+ function renderRecord(record) {
172
+ const lines = [];
173
+ const scope = record.scopeEffectId ? `${LEVEL_LABEL[record.scopeLevel]} ${record.scopeEffectId}` : LEVEL_LABEL[record.scopeLevel];
174
+ lines.push(`【${record.metricName || '(未命名指标)'}】 [${scope}]`);
175
+ if (record.caliber)
176
+ lines.push(` 计算口径:${record.caliber.replace(/\n/g, ' ')}`);
177
+ if (record.dimensions.length)
178
+ lines.push(` 可关联维度:${record.dimensions.join(' / ')}`);
179
+ if (record.drillPaths.length) {
180
+ lines.push(` 下钻路径:${record.drillPaths.map((path) => path.join(' > ')).join(';')}`);
181
+ }
182
+ if (!record.dimensions.length && !record.drillPaths.length)
183
+ lines.push(' (该条设置未配置维度 / 下钻路径)');
184
+ return lines;
185
+ }
186
+ export async function attributionMetric(input, host) {
187
+ const ids = parseAttributionScopeIds(input);
188
+ const groupIds = parseIds(input.group_ids, '--group-ids');
189
+ const itemIds = parseIds(input.item_ids, '--item-ids');
190
+ const response = await host.request({
191
+ method: 'POST',
192
+ path: ATTRIBUTION_PATH,
193
+ body: ids.map(String),
194
+ operation: 'attribution.metric',
195
+ });
196
+ // 业务码在 actionMsg.code(实测信封为 { data, actionMsg });同时兼容 { code, msg } 形态
197
+ const code = response?.actionMsg?.code ?? response?.code;
198
+ const message = response?.actionMsg?.message ?? response?.msg;
199
+ const bad = (code !== undefined && Number(code) !== 0) || response?.fail === true;
200
+ if (bad) {
201
+ throw dataApiError('attribution_metric_failed', `getAttributionMetricByScopeId 业务失败:code=${code} msg=${message || '(无 msg)'}`, { code });
202
+ }
203
+ const rawList = Array.isArray(response?.data) ? response.data : (response?.data ? [response.data] : []);
204
+ const metrics = rawList
205
+ .map((record) => normalizeAttributionMetric(record, groupIds, itemIds, ids))
206
+ .sort((a, b) => LEVEL_ORDER[a.scopeLevel] - LEVEL_ORDER[b.scopeLevel]);
207
+ const scoped = metrics.filter((record) => record.scopeLevel !== 'global');
208
+ const lines = [`== 归因设置 ${metrics.length} 条(生效范围 id ${ids.length} 个;非全局 ${scoped.length} + 全局 ${metrics.length - scoped.length})==`];
209
+ if (!metrics.length) {
210
+ lines.push('(空:该环境未返回任何归因设置 ⇒ 按技能通用规则归因)');
211
+ }
212
+ else {
213
+ for (const record of metrics)
214
+ lines.push(...renderRecord(record));
215
+ if (!scoped.length) {
216
+ lines.push('(提示:本次只命中全局设置,所选分组 / 条目本身未单独绑定归因口径)');
217
+ }
218
+ }
219
+ return {
220
+ data: {
221
+ scopeIds: ids,
222
+ count: metrics.length,
223
+ scopedCount: scoped.length,
224
+ globalCount: metrics.length - scoped.length,
225
+ metrics,
226
+ },
227
+ text: lines.join('\n'),
228
+ };
229
+ }