@arcticdata/dsh-datarc-assistant 26.39.0 → 26.39.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.
Files changed (149) hide show
  1. package/README.md +45 -10
  2. package/api-operations.js +404 -0
  3. package/client.js +452 -87
  4. package/cordis.patch.yml +4 -4
  5. package/entry/SKILL.md +34 -0
  6. package/icon.png +0 -0
  7. package/index.js +35 -47
  8. package/locale/en.json +6 -6
  9. package/locale/zh.json +6 -6
  10. package/native-api.mjs +326 -0
  11. package/native-contracts.js +195 -0
  12. package/native-execution.js +184 -0
  13. package/native-runner.mjs +107 -0
  14. package/native-state.js +67 -0
  15. package/native-tools.js +241 -0
  16. package/operations.js +1260 -0
  17. package/package.json +65 -51
  18. package/{skills → runtime}/datarc-access-permissions/SKILL.md +30 -30
  19. package/{skills → runtime}/datarc-access-permissions/references/api.md +31 -31
  20. package/{skills → runtime}/datarc-access-permissions/references/write-order.md +16 -16
  21. package/{skills → runtime}/datarc-analysis-report/SKILL.md +125 -125
  22. package/{skills → runtime}/datarc-analysis-report/agents/openai.yaml +6 -6
  23. package/{skills → runtime}/datarc-analysis-report/references/analyst-frameworks.md +215 -215
  24. package/{skills → runtime}/datarc-analysis-report/references/api-contracts.md +478 -478
  25. package/{skills → runtime}/datarc-analysis-report/references/direct-card-fallback-design.md +66 -66
  26. package/{skills → runtime}/datarc-analysis-report/references/human-in-the-loop.md +142 -142
  27. package/{skills → runtime}/datarc-analysis-report/references/loop-personalization-policy.md +138 -138
  28. package/{skills → runtime}/datarc-analysis-report/references/manifest-example.json +779 -779
  29. package/{skills → runtime}/datarc-analysis-report/references/narrative-schema.md +160 -160
  30. package/{skills → runtime}/datarc-analysis-report/references/question-syntax.md +151 -151
  31. package/{skills → runtime}/datarc-analysis-report/scripts/run_analysis_report.py +2225 -2225
  32. package/{skills → runtime}/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -1914
  33. package/{skills → runtime}/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -5295
  34. package/{skills → runtime}/datarc-data-search/SKILL.md +243 -243
  35. package/{skills → runtime}/datarc-data-search/scripts/calculate.py +116 -116
  36. package/{skills → runtime}/datarc-data-search/scripts/data-search.mjs +628 -628
  37. package/{skills/datarc-dataseek-search → runtime/datarc-data-search}/scripts/datarc-client.mjs +464 -464
  38. package/{skills → runtime}/datarc-data-search/scripts/search-result.mjs +211 -211
  39. package/{skills → runtime}/datarc-dataseek-batch-evaluation/SKILL.md +59 -59
  40. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -36
  41. package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -30
  42. package/{skills/datarc-data-search → runtime/datarc-dataseek-batch-evaluation}/scripts/datarc-client.mjs +464 -464
  43. package/{skills → runtime}/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -1020
  44. package/{skills → runtime}/datarc-dataseek-search/SKILL.md +96 -96
  45. package/{skills/datarc-dataseek-batch-evaluation → runtime/datarc-dataseek-search}/scripts/datarc-client.mjs +464 -464
  46. package/{skills → runtime}/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -257
  47. package/{skills → runtime}/datarc-dataseek-semantic-debugging/SKILL.md +44 -44
  48. package/{skills → runtime}/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -4
  49. package/{skills → runtime}/datarc-dataseek-semantic-debugging/evals/evals.json +165 -165
  50. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/dataset.md +77 -77
  51. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -93
  52. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/interventions.md +64 -64
  53. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -47
  54. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/rollback.md +11 -11
  55. package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -95
  56. package/{skills → runtime}/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -29
  57. package/{skills → runtime}/datarc-dataseek-testset-generation/SKILL.md +47 -47
  58. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -464
  59. package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -526
  60. package/{skills → runtime}/datarc-datasource/SKILL.md +97 -97
  61. package/{skills → runtime}/datarc-oauth/SKILL.md +50 -50
  62. package/{skills → runtime}/datarc-oauth/scripts/auth.mjs +192 -192
  63. package/{skills → runtime}/datarc-oauth/scripts/credentials.mjs +237 -237
  64. package/{skills → runtime}/datarc-report-add-card/SKILL.md +90 -90
  65. package/{skills → runtime}/datarc-report-add-card/agents/openai.yaml +4 -4
  66. package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  67. package/{skills → runtime}/datarc-report-add-card/scripts/report-card.mjs +439 -439
  68. package/{skills → runtime}/datarc-semantic-alias/SKILL.md +20 -20
  69. package/{skills → runtime}/datarc-semantic-alias/scripts/alias-plan.mjs +422 -422
  70. package/{skills → runtime}/datarc-semantic-alias/scripts/alias.mjs +11 -11
  71. package/{skills → runtime}/datarc-semantic-calibration/SKILL.md +20 -20
  72. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -683
  73. package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration.mjs +11 -11
  74. package/{skills → runtime}/datarc-semantic-core/SKILL.md +12 -12
  75. package/{skills → runtime}/datarc-semantic-core/scripts/artifact-journal.mjs +853 -830
  76. package/{skills → runtime}/datarc-semantic-core/scripts/canonical.mjs +48 -48
  77. package/{skills → runtime}/datarc-semantic-core/scripts/case-model.mjs +608 -608
  78. package/{skills → runtime}/datarc-semantic-core/scripts/cli.mjs +180 -180
  79. package/{skills → runtime}/datarc-semantic-core/scripts/datarc-client.mjs +180 -180
  80. package/{skills → runtime}/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -57
  81. package/{skills → runtime}/datarc-semantic-core/scripts/interventions.mjs +693 -693
  82. package/{skills → runtime}/datarc-semantic-core/scripts/live-resolution.mjs +305 -305
  83. package/{skills → runtime}/datarc-semantic-core/scripts/model-scope.mjs +49 -49
  84. package/{skills → runtime}/datarc-semantic-core/scripts/reproduction.mjs +330 -330
  85. package/{skills → runtime}/datarc-semantic-core/scripts/semantic-cli.mjs +799 -740
  86. package/{skills → runtime}/datarc-semantic-core/scripts/shared.mjs +312 -312
  87. package/{skills → runtime}/datarc-semantic-core/scripts/verification.mjs +1111 -1014
  88. package/{skills → runtime}/datarc-semantic-dataset/SKILL.md +20 -20
  89. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -749
  90. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -813
  91. package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset.mjs +11 -11
  92. package/{skills → runtime}/datarc-semantic-knowledge/SKILL.md +38 -38
  93. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -61
  94. package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-generation.json +16 -16
  95. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -347
  96. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -848
  97. package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -31
  98. package/{skills → runtime}/datarc-semantic-prompt/SKILL.md +20 -20
  99. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -447
  100. package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt.mjs +15 -15
  101. package/{skills → runtime}/datarc-semantic-synonym/SKILL.md +20 -20
  102. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -688
  103. package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym.mjs +11 -11
  104. package/{skills → runtime}/datarc-viz-analysis-report/SKILL.md +108 -108
  105. package/{skills → runtime}/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -8
  106. package/{skills → runtime}/datarc-viz-analysis-report/assets/echarts.min.js +45 -45
  107. package/{skills → runtime}/datarc-viz-analysis-report/references/api-contracts.md +163 -163
  108. package/{skills → runtime}/datarc-viz-analysis-report/references/derivation-log.md +157 -157
  109. package/{skills → runtime}/datarc-viz-analysis-report/references/evidence-framework.md +76 -76
  110. package/{skills → runtime}/datarc-viz-analysis-report/references/html-template.md +92 -92
  111. package/{skills → runtime}/datarc-viz-analysis-report/references/provenance-format.md +56 -56
  112. package/{skills → runtime}/datarc-viz-analysis-report/references/question-syntax.md +151 -151
  113. package/{skills → runtime}/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -1708
  114. package/{skills → runtime}/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -964
  115. package/{skills → runtime}/datarc-workspace-configuration/SKILL.md +59 -59
  116. package/{skills → runtime}/datarc-workspace-configuration/references/artifacts.md +75 -75
  117. package/{skills → runtime}/datarc-workspace-configuration/references/verification.md +20 -20
  118. package/{skills → runtime}/datarc-workspace-configuration/scripts/configuration.mjs +722 -662
  119. package/{skills → runtime}/datarc-workspace-context/SKILL.md +43 -43
  120. package/{skills → runtime}/datarc-workspace-context/agents/openai.yaml +4 -4
  121. package/{skills → runtime}/datarc-workspace-context/scripts/datarc-client.mjs +31 -31
  122. package/{skills → runtime}/datarc-workspace-context/scripts/query-display.mjs +114 -114
  123. package/{skills → runtime}/datarc-workspace-context/scripts/workspace-context.mjs +58 -58
  124. package/{skills → runtime}/datarc-workspace-custom-tables/SKILL.md +89 -89
  125. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -165
  126. package/{skills → runtime}/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -601
  127. package/{skills → runtime}/datarc-workspace-keywords/SKILL.md +197 -197
  128. package/{skills → runtime}/datarc-workspace-keywords/agents/openai.yaml +4 -4
  129. package/{skills → runtime}/datarc-workspace-keywords/references/api-fields.md +79 -79
  130. package/{skills → runtime}/datarc-workspace-keywords/references/derived-measures.md +177 -177
  131. package/{skills → runtime}/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -145
  132. package/{skills → runtime}/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -2421
  133. package/{skills → runtime}/datarc-workspace-membership/SKILL.md +29 -29
  134. package/{skills → runtime}/datarc-workspace-membership/references/api.md +19 -19
  135. package/{skills → runtime}/datarc-workspace-modeling/SKILL.md +209 -209
  136. package/{skills → runtime}/datarc-workspace-modeling/agents/openai.yaml +4 -4
  137. package/{skills → runtime}/datarc-workspace-modeling/references/join-preview.md +38 -38
  138. package/{skills → runtime}/datarc-workspace-modeling/references/model-plan.md +300 -300
  139. package/{skills → runtime}/datarc-workspace-modeling/references/model-tags.md +95 -95
  140. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-contract.json +29 -29
  141. package/{skills → runtime}/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -2423
  142. package/{skills → runtime}/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -137
  143. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -238
  144. package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -1261
  145. package/skills-provider.js +51 -0
  146. package/workflow-index.json +434 -0
  147. package/icon.svg +0 -4
  148. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +0 -464
  149. package/skills-index.json +0 -194
@@ -1,628 +1,628 @@
1
- #!/usr/bin/env node
2
- import { resolveCredentials } from "../../datarc-oauth/scripts/credentials.mjs";
3
- import { pathToFileURL } from "node:url";
4
- import {
5
- businessSeries,
6
- presentSearch,
7
- readSearchResult,
8
- saveInspection,
9
- resolveResultInput,
10
- businessMetadata,
11
- } from "./search-result.mjs";
12
- import { queryDisplay } from "../../datarc-workspace-context/scripts/query-display.mjs";
13
- import {
14
- assertAccess,
15
- collectCards,
16
- createClient,
17
- DatarcError,
18
- exportAll,
19
- parseArgs,
20
- preview,
21
- primaryCards,
22
- readJson,
23
- rethrowGlobalError,
24
- required,
25
- runCli,
26
- unwrapTaskResult,
27
- } from "./datarc-client.mjs";
28
-
29
- export async function execute(argv, options = {}) {
30
- const args = parseArgs(argv);
31
- const command = args._[0];
32
- if (!options.client) options = { ...options, ...resolveCredentials(options) };
33
- const client = options.client ?? createClient(options);
34
- let wid = args["workspace-id"];
35
- let source;
36
- if (args["from-result"] || command === "recall") {
37
- source = await readSearchResult(
38
- required(args, "from-result"),
39
- wid,
40
- options,
41
- );
42
- wid = source.workspaceId;
43
- if (command === "recall") return source.summary;
44
- }
45
-
46
- if (command === "workspaces")
47
- return client.request("GET", "/api/v2/account-projects/", {
48
- query: {
49
- q: args.query ?? "",
50
- offset: num(args.offset, 0),
51
- limit: num(args.limit, 20),
52
- },
53
- });
54
- if (command === "workspace")
55
- return client.request(
56
- "GET",
57
- `/api/v2/account-projects/${required(args, "workspace-id")}/`,
58
- );
59
- if (command === "catalog") {
60
- required(args, "workspace-id");
61
- const query = { offset: num(args.offset, 0), limit: num(args.limit, 100) };
62
- const [models, measures, dimensions, timeSeries] = await Promise.all(
63
- ["models", "measures", "dimensions", "dimensions/time-series"].map(
64
- (path) =>
65
- client.request("GET", `/api/v2/account-projects/${wid}/${path}/`, {
66
- query,
67
- }),
68
- ),
69
- );
70
- return businessMetadata({ models, measures, dimensions, timeSeries });
71
- }
72
- if (command === "dimension-values") {
73
- required(args, "workspace-id");
74
- let prop = args.prop === undefined ? undefined : required(args, "prop");
75
- if (args.dimension) {
76
- const name = required(args, "dimension");
77
- const cut = await cutQuestion(client, wid, name);
78
- const review = simplifyCut(name, cut);
79
- if (
80
- review.status !== "ready" ||
81
- cut.tokens.length !== 1 ||
82
- !/^d[0-9]+$/.test(cut.tokens[0].prop)
83
- ) {
84
- throw new DatarcError(
85
- "无法唯一定位这个维度,请使用已确认的维度名称重试",
86
- "QUESTION_NEEDS_REVIEW",
87
- review,
88
- );
89
- }
90
- prop = cut.tokens[0].prop;
91
- }
92
- const values = await client.request(
93
- "POST",
94
- `/api/v2/account-projects/${required(
95
- args,
96
- "workspace-id",
97
- )}/dimension-keywords/`,
98
- {
99
- body: {
100
- prop: prop ?? required(args, "dimension"),
101
- q: args.query ?? "",
102
- offset: num(args.offset, 0),
103
- limit: num(args.limit, 100),
104
- },
105
- },
106
- );
107
- return businessMetadata(values);
108
- }
109
- if (command === "inspect") {
110
- required(args, "workspace-id");
111
- const question = required(args, "question");
112
- const cut = await cutQuestion(client, wid, question);
113
- const review = simplifyCut(question, cut);
114
- if (review.status === "ready" && options.resultStorage === "artifact")
115
- return { ...review, inspection: { question, tokens: cut.tokens } };
116
- if (review.status === "ready")
117
- review.inspectionFile = await saveInspection(
118
- wid,
119
- question,
120
- cut.tokens,
121
- options,
122
- );
123
- return review;
124
- }
125
- if (["query", "search"].includes(command)) {
126
- if (!source) wid = required(args, "workspace-id");
127
- const plan = args.input
128
- ? await readJson(required(args, "input"))
129
- : {
130
- type: "single",
131
- questions: [{ question: required(args, "question") }],
132
- };
133
- const modelUids = args["model-uid"]
134
- ? modelUidsOf(required(args, "model-uid"))
135
- : (source?.modelUids ?? []);
136
- const inspection = args.inspection
137
- ? await readSearchResult(
138
- required(args, "inspection"),
139
- wid,
140
- options,
141
- "inspection",
142
- )
143
- : options.inspection;
144
- const raw = await executePlan(client, wid, plan, {
145
- inspection,
146
- ...polling(args),
147
- modelUids,
148
- download: Boolean(args.download),
149
- outputDir: args["output-dir"],
150
- taskId: args["task-id"],
151
- extension: args.extension,
152
- });
153
- return presentSearch(raw, wid, modelUids, { ...options, ...polling(args) });
154
- }
155
- if (["page", "export"].includes(command)) {
156
- required(args, "workspace-id");
157
- const file = required(args, "input");
158
- const input = await readJson(file);
159
- const cards = collectCards(await resolveResultInput(input, wid, options));
160
- const entries = await (command === "page"
161
- ? preview(client, wid, cards, polling(args))
162
- : exportAll(client, wid, cards, {
163
- ...polling(args),
164
- extension: args.extension,
165
- download: Boolean(args.download),
166
- outputDir: args["output-dir"],
167
- taskId: args["task-id"],
168
- }));
169
- return businessSeries(entries, { ...polling(args), page: command === "page" });
170
- }
171
- throw new DatarcError(
172
- "命令应为 workspaces、workspace、catalog、dimension-values、inspect、search、query、recall、page 或 export",
173
- "INVALID_ARGUMENT",
174
- );
175
- }
176
-
177
- export async function inspectQuestion(client, workspaceId, question) {
178
- const cut = await cutQuestion(client, workspaceId, question);
179
- return simplifyCut(question, cut);
180
- }
181
-
182
- export function simplifyCut(question, cut) {
183
- const recognizedSegments = [];
184
- const uncertainSegments = [];
185
- const unknownSegments = [];
186
- const unsupportedSegments = [];
187
- for (const [index, token] of (cut.tokens ?? []).entries()) {
188
- const common = { index, text: token.word, type: tokenType(token.prop) };
189
- if (token.invalidType) {
190
- unsupportedSegments.push({
191
- ...common,
192
- reasonCode: token.invalidType,
193
- reason: `分词接口标记为不可用于当前查询(invalidType=${token.invalidType})`,
194
- });
195
- continue;
196
- }
197
- const choiceTokens = token.choiceTokens ?? [];
198
- const guessTokens = token.guessTokens ?? [];
199
- if (choiceTokens.length || (isUnknown(token) && guessTokens.length)) {
200
- uncertainSegments.push({
201
- ...common,
202
- kind: choiceTokens.length ? "ambiguous" : "fuzzy",
203
- candidates: (choiceTokens.length ? choiceTokens : guessTokens).map(
204
- (candidate) => ({
205
- text: candidate.word,
206
- type: tokenType(candidate.prop),
207
- }),
208
- ),
209
- });
210
- } else if (isUnknown(token)) {
211
- unknownSegments.push(common);
212
- } else {
213
- recognizedSegments.push(common);
214
- }
215
- }
216
- if (!cut.tokens?.length)
217
- unknownSegments.push({ text: question, type: "unknown" });
218
- const needsReview = Boolean(
219
- uncertainSegments.length ||
220
- unknownSegments.length ||
221
- unsupportedSegments.length,
222
- );
223
- return {
224
- status: needsReview ? "needs_review" : "ready",
225
- originalQuestion: question,
226
- recognizedSegments,
227
- uncertainSegments,
228
- unknownSegments,
229
- unsupportedSegments,
230
- };
231
- }
232
-
233
- export async function executePlan(client, workspaceId, plan, options = {}) {
234
- const normalized = normalizePlan(plan);
235
- const prepare = (item) => prepareQuestion(client, workspaceId, item.question, options.inspection);
236
- const chainSteps = [];
237
- if (normalized.type === "chained") {
238
- for (const [index, item] of normalized.questions.entries()) {
239
- const step = await prepare(item);
240
- if (step.calculations.length) {
241
- const stepId = item.id ?? `q${index + 1}`;
242
- const guidance = chainCalculationGuidance(step.calculations);
243
- throw new DatarcError(
244
- `第 ${index + 1} 步「${item.question}」需要临时计算。请先确定成员集合,再对同一批成员${guidance},用 Python 计算。`,
245
- "CALCULATION_REQUIRED",
246
- { stepId, question: item.question },
247
- );
248
- }
249
- chainSteps.push(step);
250
- }
251
- }
252
- const results = [];
253
- let previous;
254
- for (const [index, item] of normalized.questions.entries()) {
255
- const { tokens, calculations } = chainSteps[index] ?? await prepare(item);
256
- if (calculations.length) {
257
- const message = `「${calculations[0].word}」需要临时计算,请沿用已有结果,只查询缺少的基础数据后用 Python 计算`;
258
- if (normalized.type !== "parallel")
259
- throw new DatarcError(message, "CALCULATION_REQUIRED");
260
- results.push({
261
- id: item.id ?? `q${index + 1}`, question: item.question, status: "calculation_required",
262
- code: "CALCULATION_REQUIRED", hasData: false, message,
263
- });
264
- continue;
265
- }
266
- const question = [...tokens];
267
- if (normalized.type === "chained" && previous) {
268
- question.unshift(
269
- {
270
- word: `上文的${previous.dimension.word}`,
271
- prop: `ds${previous.dataset.id}`,
272
- },
273
- {
274
- word: previous.dimension.word,
275
- prop: previous.dimension.prop,
276
- split: false,
277
- },
278
- ...(previous.dimension.split
279
- ? [{ word: "每个", prop: "keyword_every" }]
280
- : []),
281
- );
282
- }
283
- const answer = await ask(client, workspaceId, question, options.modelUids);
284
- const cards = primaryCards(answer.cards ?? []);
285
- const previews = await preview(client, workspaceId, cards, options);
286
- const resultState = classifyPreviews(cards, previews);
287
- const result = {
288
- id: item.id ?? `q${index + 1}`,
289
- observedAt: new Date().toISOString(),
290
- question: item.question,
291
- status: resultState.status,
292
- hasData: resultState.hasData,
293
- message: resultState.message,
294
- answer: { ...answer, tokens: answer.tokens ?? question, cards },
295
- queryDisplay: queryDisplay(cards),
296
- previews,
297
- insights: null,
298
- };
299
-
300
- if (
301
- normalized.type === "chained" &&
302
- index < normalized.questions.length - 1
303
- ) {
304
- if (!resultState.hasData || resultState.hasErrors)
305
- throw new DatarcError(
306
- resultState.hasData
307
- ? "链式查询的前一步取数不完整,不能安全创建临时数据集"
308
- : "链式查询的前一步没有有效数据,已停止后续查询",
309
- "CHAIN_SOURCE_UNAVAILABLE",
310
- {
311
- stepId: result.id,
312
- question: result.question,
313
- status: result.status,
314
- message: result.message,
315
- },
316
- );
317
- const dimension = resolveDimension(
318
- answer.tokens ?? question,
319
- item.outputDimension,
320
- );
321
- const dataset = await client.request(
322
- "POST",
323
- `/api/v3/account-projects/${workspaceId}/datasets/`,
324
- {
325
- body: {
326
- question: answer.tokens ?? question,
327
- content: (answer.tokens ?? question)
328
- .map((token) => token.word)
329
- .join(""),
330
- columns: [dimension.prop],
331
- },
332
- },
333
- );
334
- if (!dataset?.id)
335
- throw new DatarcError("临时数据集未返回 id", "DATASET_CREATION_FAILED");
336
- result.intermediate = { dimension: dimension.word, datasetCreated: true };
337
- previous = { dimension, dataset };
338
- }
339
- if (resultState.hasData)
340
- result.insights = await getAutoInsights(
341
- client,
342
- workspaceId,
343
- cards[0],
344
- options,
345
- );
346
- if (resultState.hasData && options.download) {
347
- result.exports = await exportAll(client, workspaceId, cards, {
348
- ...options,
349
- title: item.question,
350
- });
351
- result.downloadStatus = downloadStatus(result.exports);
352
- result.downloadDirectory = result.exports.find(
353
- (entry) => entry.directory,
354
- )?.directory;
355
- }
356
- results.push(result);
357
- }
358
- return {
359
- status: overallStatus(results),
360
- hasData: results.some((result) => result.hasData),
361
- type: normalized.type,
362
- results,
363
- downloadDirectories: uniqueDirectories(results),
364
- };
365
- }
366
-
367
- function chainCalculationGuidance(calculations) {
368
- const props = new Set(calculations.map(({ prop }) => prop));
369
- const hasShare = props.has("keyword_proportion");
370
- const periods = ["本期"];
371
- if (props.has("compare_yoy") || props.has("compare_yoyring")) periods.push("去年同期");
372
- if (props.has("compare_ring") || props.has("compare_en_ring") || props.has("compare_yoyring")) periods.push("上一周期");
373
- if (periods.length === 1 && props.has("keyword_growth")) periods.push("基期");
374
- if (periods.length === 1) return "按已确认的分母口径补查缺少的分子和分母";
375
- const inputs = hasShare ? "按同一分母口径补查各期缺少的分子和分母" : "补查各期缺少的指标值";
376
- return `分别核对${periods.join("、")},${inputs}`;
377
- }
378
-
379
- async function prepareQuestion(client, workspaceId, question, inspection) {
380
- const cut = inspection?.question === question
381
- ? inspection
382
- : await cutQuestion(client, workspaceId, question);
383
- const review = simplifyCut(question, cut);
384
- if (review.status !== "ready")
385
- throw new DatarcError(
386
- "规范化问题仍包含需要大模型确认的分词",
387
- "QUESTION_NEEDS_REVIEW",
388
- review,
389
- );
390
- // A modeled metric has a measure prop even when its name contains “同比” or “占比”.
391
- const calculations = cut.tokens.filter(({ prop }) =>
392
- ["keyword_proportion", "keyword_growth", "compare_yoy", "compare_ring", "compare_en_ring", "compare_yoyring"].includes(prop),
393
- );
394
- return { tokens: cut.tokens, calculations };
395
- }
396
-
397
- function overallStatus(results) {
398
- if (!results.some((result) => result.hasData)) {
399
- if (results.some((result) => result.status === "failed")) return "failed";
400
- if (results.some((result) => result.status === "calculation_required")) return "calculation_required";
401
- return "empty";
402
- }
403
- if (results.some((result) => result.status !== "success")) return "partial";
404
- return "success";
405
- }
406
-
407
- export function classifyPreviews(cards, previews) {
408
- if (!cards.length)
409
- return {
410
- status: "empty",
411
- hasData: false,
412
- hasErrors: false,
413
- message: "查询成功,但没有生成直接结果卡片",
414
- };
415
- const successful = previews.filter((entry) => !entry.error);
416
- const hasErrors = successful.length !== previews.length;
417
- const hasData = successful.some((entry) => !isEmptyQueryResult(entry.data));
418
- if (!hasData)
419
- return {
420
- status: hasErrors && !successful.length ? "failed" : "empty",
421
- hasData: false,
422
- hasErrors,
423
- message: hasErrors
424
- ? "未获得有效数据,部分或全部数据序列取数失败"
425
- : "查询成功,但数据结果为空",
426
- };
427
- return {
428
- status: hasErrors ? "partial" : "success",
429
- hasData: true,
430
- hasErrors,
431
- message: hasErrors
432
- ? "查询得到部分有效数据,另有数据序列取数失败"
433
- : "查询成功",
434
- };
435
- }
436
-
437
- function isEmptyQueryResult(value) {
438
- let current = value;
439
- if (
440
- current &&
441
- typeof current === "object" &&
442
- current.status === "SUCCESS" &&
443
- Object.hasOwn(current, "data")
444
- )
445
- current = current.data;
446
- if (current === null || current === undefined || current === "") return true;
447
- if (Array.isArray(current)) return current.length === 0;
448
- return false;
449
- }
450
-
451
- async function cutQuestion(client, workspaceId, question) {
452
- return client.request(
453
- "POST",
454
- `/api/v3/account-projects/${workspaceId}/cut/`,
455
- { body: { tokens: question } },
456
- );
457
- }
458
-
459
- async function ask(client, workspaceId, question, modelUids) {
460
- const body = { question, language: "zh-CN" };
461
- if (modelUids?.length) body.tuids = modelUids;
462
- const data = await client.request(
463
- "POST",
464
- `/api/v3/account-projects/${workspaceId}/ask/`,
465
- {
466
- body,
467
- },
468
- );
469
- try {
470
- return assertAccess(data);
471
- } catch (error) {
472
- if (error.code === "FIELD_ACCESS_DENIED")
473
- error.details.tokens = error.details.tokens.map(({ word }) => ({ word }));
474
- throw error;
475
- }
476
- }
477
-
478
- async function getAutoInsights(client, workspaceId, card, options) {
479
- const qKey = card?.data?.[0]?.data?.qKey;
480
- if (!card?.configs?.hasAutoInsights || !qKey) return null;
481
- try {
482
- const task = await client.request(
483
- "POST",
484
- `/api/v2/account-projects/${workspaceId}/async-tasks/`,
485
- {
486
- body: {
487
- taskType: 11,
488
- params: {
489
- units: card.units ?? [],
490
- tuids: card.tuids ?? null,
491
- qKey,
492
- },
493
- },
494
- },
495
- );
496
- return unwrapTaskResult(
497
- await client.poll(workspaceId, task.uid, 11, options),
498
- );
499
- } catch (error) {
500
- rethrowGlobalError(error);
501
- return {
502
- error: {
503
- code: error.code ?? "AUTO_INSIGHTS_FAILED",
504
- message: error.message,
505
- },
506
- };
507
- }
508
- }
509
-
510
- function normalizePlan(plan) {
511
- if (!plan || typeof plan !== "object")
512
- throw new DatarcError("搜索计划必须是 JSON 对象", "INVALID_PLAN");
513
- const type = plan.type ?? "single";
514
- if (!["single", "parallel", "chained"].includes(type))
515
- throw new DatarcError(
516
- "计划类型必须是 single、parallel 或 chained",
517
- "INVALID_PLAN",
518
- );
519
- const questions = Array.isArray(plan.questions) ? plan.questions : [];
520
- if (!questions.length || questions.length > 20)
521
- throw new DatarcError("搜索计划必须包含 1 至 20 个问题", "INVALID_PLAN");
522
- if (type === "single" && questions.length !== 1)
523
- throw new DatarcError("single 计划只能包含一个问题", "INVALID_PLAN");
524
- if (type === "chained" && questions.length > 5)
525
- throw new DatarcError("链式查询最多支持 5 层", "INVALID_PLAN");
526
- return {
527
- type,
528
- questions: questions.map((item, index) => {
529
- const normalized = typeof item === "string" ? { question: item } : item;
530
- if (!normalized?.question)
531
- throw new DatarcError(
532
- `第 ${index + 1} 个问题缺少 question`,
533
- "INVALID_PLAN",
534
- );
535
- if (
536
- type === "chained" &&
537
- index < questions.length - 1 &&
538
- !normalized.outputDimension
539
- )
540
- throw new DatarcError(
541
- `链式查询第 ${index + 1} 层缺少 outputDimension`,
542
- "INVALID_PLAN",
543
- );
544
- return normalized;
545
- }),
546
- };
547
- }
548
-
549
- function resolveDimension(tokens, requested) {
550
- const word = typeof requested === "string" ? requested : requested?.word;
551
- const matches = tokens.filter(
552
- (token) =>
553
- String(token.prop ?? "").startsWith("d") &&
554
- !String(token.prop ?? "").includes("=") &&
555
- (!word || token.word === word),
556
- );
557
- if (matches.length !== 1)
558
- throw new DatarcError(
559
- `无法唯一确定链式查询的输出维度${word ? `“${word}”` : ""}`,
560
- "INVALID_CHAIN_DIMENSION",
561
- );
562
- return {
563
- word: matches[0].word,
564
- prop: matches[0].prop.split("=")[0],
565
- split: Boolean(requested?.split),
566
- };
567
- }
568
-
569
- function tokenType(prop) {
570
- const value = String(prop ?? "unknown");
571
- if (value === "unknown") return "unknown";
572
- if (/^m/.test(value)) return "measure";
573
- if (/^d/.test(value))
574
- return value.includes("=") ? "dimension_value" : "dimension";
575
- if (/^(t|dateRange_)/.test(value)) return "time";
576
- if (/^(keyword_|op_|compare_|\$)/.test(value)) return "operator";
577
- return "recognized";
578
- }
579
-
580
- function isUnknown(token) {
581
- return !token.prop || token.prop === "unknown";
582
- }
583
-
584
- function modelUidsOf(value) {
585
- return value
586
- ? []
587
- .concat(value)
588
- .flatMap((item) => String(item).split(","))
589
- .filter(Boolean)
590
- : [];
591
- }
592
-
593
- function uniqueDirectories(results) {
594
- const values = results
595
- .map((result) => result.downloadDirectory)
596
- .filter(Boolean);
597
- return [
598
- ...new Map(values.map((value) => [value.absolutePath, value])).values(),
599
- ];
600
- }
601
-
602
- function downloadStatus(exports) {
603
- if (exports.length && exports.every((entry) => entry.status === "skipped"))
604
- return "not_applicable";
605
- const failures = exports.filter((entry) => entry.error).length;
606
- if (failures === exports.length) return "failed";
607
- if (failures) return "partial";
608
- return "success";
609
- }
610
-
611
- function num(value, fallback) {
612
- const result = Number(value ?? fallback);
613
- if (!Number.isFinite(result) || result < 0)
614
- throw new DatarcError("数值参数必须为非负数", "INVALID_ARGUMENT");
615
- return result;
616
- }
617
-
618
- function polling(args) {
619
- return {
620
- ...(args.offset === undefined ? {} : { offset: num(args.offset) }),
621
- ...(args.limit === undefined ? {} : { limit: num(args.limit) }),
622
- intervalMs: num(args["poll-interval-ms"], 2000),
623
- maxWaitMs: num(args["max-wait-ms"], 600000),
624
- };
625
- }
626
-
627
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
628
- await runCli(() => execute(process.argv.slice(2)));
1
+ #!/usr/bin/env node
2
+ import { resolveCredentials } from "../../datarc-oauth/scripts/credentials.mjs";
3
+ import { pathToFileURL } from "node:url";
4
+ import {
5
+ businessSeries,
6
+ presentSearch,
7
+ readSearchResult,
8
+ saveInspection,
9
+ resolveResultInput,
10
+ businessMetadata,
11
+ } from "./search-result.mjs";
12
+ import { queryDisplay } from "../../datarc-workspace-context/scripts/query-display.mjs";
13
+ import {
14
+ assertAccess,
15
+ collectCards,
16
+ createClient,
17
+ DatarcError,
18
+ exportAll,
19
+ parseArgs,
20
+ preview,
21
+ primaryCards,
22
+ readJson,
23
+ rethrowGlobalError,
24
+ required,
25
+ runCli,
26
+ unwrapTaskResult,
27
+ } from "./datarc-client.mjs";
28
+
29
+ export async function execute(argv, options = {}) {
30
+ const args = parseArgs(argv);
31
+ const command = args._[0];
32
+ if (!options.client) options = { ...options, ...resolveCredentials(options) };
33
+ const client = options.client ?? createClient(options);
34
+ let wid = args["workspace-id"];
35
+ let source;
36
+ if (args["from-result"] || command === "recall") {
37
+ source = await readSearchResult(
38
+ required(args, "from-result"),
39
+ wid,
40
+ options,
41
+ );
42
+ wid = source.workspaceId;
43
+ if (command === "recall") return source.summary;
44
+ }
45
+
46
+ if (command === "workspaces")
47
+ return client.request("GET", "/api/v2/account-projects/", {
48
+ query: {
49
+ q: args.query ?? "",
50
+ offset: num(args.offset, 0),
51
+ limit: num(args.limit, 20),
52
+ },
53
+ });
54
+ if (command === "workspace")
55
+ return client.request(
56
+ "GET",
57
+ `/api/v2/account-projects/${required(args, "workspace-id")}/`,
58
+ );
59
+ if (command === "catalog") {
60
+ required(args, "workspace-id");
61
+ const query = { offset: num(args.offset, 0), limit: num(args.limit, 100) };
62
+ const [models, measures, dimensions, timeSeries] = await Promise.all(
63
+ ["models", "measures", "dimensions", "dimensions/time-series"].map(
64
+ (path) =>
65
+ client.request("GET", `/api/v2/account-projects/${wid}/${path}/`, {
66
+ query,
67
+ }),
68
+ ),
69
+ );
70
+ return businessMetadata({ models, measures, dimensions, timeSeries });
71
+ }
72
+ if (command === "dimension-values") {
73
+ required(args, "workspace-id");
74
+ let prop = args.prop === undefined ? undefined : required(args, "prop");
75
+ if (args.dimension) {
76
+ const name = required(args, "dimension");
77
+ const cut = await cutQuestion(client, wid, name);
78
+ const review = simplifyCut(name, cut);
79
+ if (
80
+ review.status !== "ready" ||
81
+ cut.tokens.length !== 1 ||
82
+ !/^d[0-9]+$/.test(cut.tokens[0].prop)
83
+ ) {
84
+ throw new DatarcError(
85
+ "无法唯一定位这个维度,请使用已确认的维度名称重试",
86
+ "QUESTION_NEEDS_REVIEW",
87
+ review,
88
+ );
89
+ }
90
+ prop = cut.tokens[0].prop;
91
+ }
92
+ const values = await client.request(
93
+ "POST",
94
+ `/api/v2/account-projects/${required(
95
+ args,
96
+ "workspace-id",
97
+ )}/dimension-keywords/`,
98
+ {
99
+ body: {
100
+ prop: prop ?? required(args, "dimension"),
101
+ q: args.query ?? "",
102
+ offset: num(args.offset, 0),
103
+ limit: num(args.limit, 100),
104
+ },
105
+ },
106
+ );
107
+ return businessMetadata(values);
108
+ }
109
+ if (command === "inspect") {
110
+ required(args, "workspace-id");
111
+ const question = required(args, "question");
112
+ const cut = await cutQuestion(client, wid, question);
113
+ const review = simplifyCut(question, cut);
114
+ if (review.status === "ready" && options.resultStorage === "artifact")
115
+ return { ...review, inspection: { question, tokens: cut.tokens } };
116
+ if (review.status === "ready")
117
+ review.inspectionFile = await saveInspection(
118
+ wid,
119
+ question,
120
+ cut.tokens,
121
+ options,
122
+ );
123
+ return review;
124
+ }
125
+ if (["query", "search"].includes(command)) {
126
+ if (!source) wid = required(args, "workspace-id");
127
+ const plan = args.input
128
+ ? await readJson(required(args, "input"))
129
+ : {
130
+ type: "single",
131
+ questions: [{ question: required(args, "question") }],
132
+ };
133
+ const modelUids = args["model-uid"]
134
+ ? modelUidsOf(required(args, "model-uid"))
135
+ : (source?.modelUids ?? []);
136
+ const inspection = args.inspection
137
+ ? await readSearchResult(
138
+ required(args, "inspection"),
139
+ wid,
140
+ options,
141
+ "inspection",
142
+ )
143
+ : options.inspection;
144
+ const raw = await executePlan(client, wid, plan, {
145
+ inspection,
146
+ ...polling(args),
147
+ modelUids,
148
+ download: Boolean(args.download),
149
+ outputDir: args["output-dir"],
150
+ taskId: args["task-id"],
151
+ extension: args.extension,
152
+ });
153
+ return presentSearch(raw, wid, modelUids, { ...options, ...polling(args) });
154
+ }
155
+ if (["page", "export"].includes(command)) {
156
+ required(args, "workspace-id");
157
+ const file = required(args, "input");
158
+ const input = await readJson(file);
159
+ const cards = collectCards(await resolveResultInput(input, wid, options));
160
+ const entries = await (command === "page"
161
+ ? preview(client, wid, cards, polling(args))
162
+ : exportAll(client, wid, cards, {
163
+ ...polling(args),
164
+ extension: args.extension,
165
+ download: Boolean(args.download),
166
+ outputDir: args["output-dir"],
167
+ taskId: args["task-id"],
168
+ }));
169
+ return businessSeries(entries, { ...polling(args), page: command === "page" });
170
+ }
171
+ throw new DatarcError(
172
+ "命令应为 workspaces、workspace、catalog、dimension-values、inspect、search、query、recall、page 或 export",
173
+ "INVALID_ARGUMENT",
174
+ );
175
+ }
176
+
177
+ export async function inspectQuestion(client, workspaceId, question) {
178
+ const cut = await cutQuestion(client, workspaceId, question);
179
+ return simplifyCut(question, cut);
180
+ }
181
+
182
+ export function simplifyCut(question, cut) {
183
+ const recognizedSegments = [];
184
+ const uncertainSegments = [];
185
+ const unknownSegments = [];
186
+ const unsupportedSegments = [];
187
+ for (const [index, token] of (cut.tokens ?? []).entries()) {
188
+ const common = { index, text: token.word, type: tokenType(token.prop) };
189
+ if (token.invalidType) {
190
+ unsupportedSegments.push({
191
+ ...common,
192
+ reasonCode: token.invalidType,
193
+ reason: `分词接口标记为不可用于当前查询(invalidType=${token.invalidType})`,
194
+ });
195
+ continue;
196
+ }
197
+ const choiceTokens = token.choiceTokens ?? [];
198
+ const guessTokens = token.guessTokens ?? [];
199
+ if (choiceTokens.length || (isUnknown(token) && guessTokens.length)) {
200
+ uncertainSegments.push({
201
+ ...common,
202
+ kind: choiceTokens.length ? "ambiguous" : "fuzzy",
203
+ candidates: (choiceTokens.length ? choiceTokens : guessTokens).map(
204
+ (candidate) => ({
205
+ text: candidate.word,
206
+ type: tokenType(candidate.prop),
207
+ }),
208
+ ),
209
+ });
210
+ } else if (isUnknown(token)) {
211
+ unknownSegments.push(common);
212
+ } else {
213
+ recognizedSegments.push(common);
214
+ }
215
+ }
216
+ if (!cut.tokens?.length)
217
+ unknownSegments.push({ text: question, type: "unknown" });
218
+ const needsReview = Boolean(
219
+ uncertainSegments.length ||
220
+ unknownSegments.length ||
221
+ unsupportedSegments.length,
222
+ );
223
+ return {
224
+ status: needsReview ? "needs_review" : "ready",
225
+ originalQuestion: question,
226
+ recognizedSegments,
227
+ uncertainSegments,
228
+ unknownSegments,
229
+ unsupportedSegments,
230
+ };
231
+ }
232
+
233
+ export async function executePlan(client, workspaceId, plan, options = {}) {
234
+ const normalized = normalizePlan(plan);
235
+ const prepare = (item) => prepareQuestion(client, workspaceId, item.question, options.inspection);
236
+ const chainSteps = [];
237
+ if (normalized.type === "chained") {
238
+ for (const [index, item] of normalized.questions.entries()) {
239
+ const step = await prepare(item);
240
+ if (step.calculations.length) {
241
+ const stepId = item.id ?? `q${index + 1}`;
242
+ const guidance = chainCalculationGuidance(step.calculations);
243
+ throw new DatarcError(
244
+ `第 ${index + 1} 步「${item.question}」需要临时计算。请先确定成员集合,再对同一批成员${guidance},用 Python 计算。`,
245
+ "CALCULATION_REQUIRED",
246
+ { stepId, question: item.question },
247
+ );
248
+ }
249
+ chainSteps.push(step);
250
+ }
251
+ }
252
+ const results = [];
253
+ let previous;
254
+ for (const [index, item] of normalized.questions.entries()) {
255
+ const { tokens, calculations } = chainSteps[index] ?? await prepare(item);
256
+ if (calculations.length) {
257
+ const message = `「${calculations[0].word}」需要临时计算,请沿用已有结果,只查询缺少的基础数据后用 Python 计算`;
258
+ if (normalized.type !== "parallel")
259
+ throw new DatarcError(message, "CALCULATION_REQUIRED");
260
+ results.push({
261
+ id: item.id ?? `q${index + 1}`, question: item.question, status: "calculation_required",
262
+ code: "CALCULATION_REQUIRED", hasData: false, message,
263
+ });
264
+ continue;
265
+ }
266
+ const question = [...tokens];
267
+ if (normalized.type === "chained" && previous) {
268
+ question.unshift(
269
+ {
270
+ word: `上文的${previous.dimension.word}`,
271
+ prop: `ds${previous.dataset.id}`,
272
+ },
273
+ {
274
+ word: previous.dimension.word,
275
+ prop: previous.dimension.prop,
276
+ split: false,
277
+ },
278
+ ...(previous.dimension.split
279
+ ? [{ word: "每个", prop: "keyword_every" }]
280
+ : []),
281
+ );
282
+ }
283
+ const answer = await ask(client, workspaceId, question, options.modelUids);
284
+ const cards = primaryCards(answer.cards ?? []);
285
+ const previews = await preview(client, workspaceId, cards, options);
286
+ const resultState = classifyPreviews(cards, previews);
287
+ const result = {
288
+ id: item.id ?? `q${index + 1}`,
289
+ observedAt: new Date().toISOString(),
290
+ question: item.question,
291
+ status: resultState.status,
292
+ hasData: resultState.hasData,
293
+ message: resultState.message,
294
+ answer: { ...answer, tokens: answer.tokens ?? question, cards },
295
+ queryDisplay: queryDisplay(cards),
296
+ previews,
297
+ insights: null,
298
+ };
299
+
300
+ if (
301
+ normalized.type === "chained" &&
302
+ index < normalized.questions.length - 1
303
+ ) {
304
+ if (!resultState.hasData || resultState.hasErrors)
305
+ throw new DatarcError(
306
+ resultState.hasData
307
+ ? "链式查询的前一步取数不完整,不能安全创建临时数据集"
308
+ : "链式查询的前一步没有有效数据,已停止后续查询",
309
+ "CHAIN_SOURCE_UNAVAILABLE",
310
+ {
311
+ stepId: result.id,
312
+ question: result.question,
313
+ status: result.status,
314
+ message: result.message,
315
+ },
316
+ );
317
+ const dimension = resolveDimension(
318
+ answer.tokens ?? question,
319
+ item.outputDimension,
320
+ );
321
+ const dataset = await client.request(
322
+ "POST",
323
+ `/api/v3/account-projects/${workspaceId}/datasets/`,
324
+ {
325
+ body: {
326
+ question: answer.tokens ?? question,
327
+ content: (answer.tokens ?? question)
328
+ .map((token) => token.word)
329
+ .join(""),
330
+ columns: [dimension.prop],
331
+ },
332
+ },
333
+ );
334
+ if (!dataset?.id)
335
+ throw new DatarcError("临时数据集未返回 id", "DATASET_CREATION_FAILED");
336
+ result.intermediate = { dimension: dimension.word, datasetCreated: true };
337
+ previous = { dimension, dataset };
338
+ }
339
+ if (resultState.hasData)
340
+ result.insights = await getAutoInsights(
341
+ client,
342
+ workspaceId,
343
+ cards[0],
344
+ options,
345
+ );
346
+ if (resultState.hasData && options.download) {
347
+ result.exports = await exportAll(client, workspaceId, cards, {
348
+ ...options,
349
+ title: item.question,
350
+ });
351
+ result.downloadStatus = downloadStatus(result.exports);
352
+ result.downloadDirectory = result.exports.find(
353
+ (entry) => entry.directory,
354
+ )?.directory;
355
+ }
356
+ results.push(result);
357
+ }
358
+ return {
359
+ status: overallStatus(results),
360
+ hasData: results.some((result) => result.hasData),
361
+ type: normalized.type,
362
+ results,
363
+ downloadDirectories: uniqueDirectories(results),
364
+ };
365
+ }
366
+
367
+ function chainCalculationGuidance(calculations) {
368
+ const props = new Set(calculations.map(({ prop }) => prop));
369
+ const hasShare = props.has("keyword_proportion");
370
+ const periods = ["本期"];
371
+ if (props.has("compare_yoy") || props.has("compare_yoyring")) periods.push("去年同期");
372
+ if (props.has("compare_ring") || props.has("compare_en_ring") || props.has("compare_yoyring")) periods.push("上一周期");
373
+ if (periods.length === 1 && props.has("keyword_growth")) periods.push("基期");
374
+ if (periods.length === 1) return "按已确认的分母口径补查缺少的分子和分母";
375
+ const inputs = hasShare ? "按同一分母口径补查各期缺少的分子和分母" : "补查各期缺少的指标值";
376
+ return `分别核对${periods.join("、")},${inputs}`;
377
+ }
378
+
379
+ async function prepareQuestion(client, workspaceId, question, inspection) {
380
+ const cut = inspection?.question === question
381
+ ? inspection
382
+ : await cutQuestion(client, workspaceId, question);
383
+ const review = simplifyCut(question, cut);
384
+ if (review.status !== "ready")
385
+ throw new DatarcError(
386
+ "规范化问题仍包含需要大模型确认的分词",
387
+ "QUESTION_NEEDS_REVIEW",
388
+ review,
389
+ );
390
+ // A modeled metric has a measure prop even when its name contains “同比” or “占比”.
391
+ const calculations = cut.tokens.filter(({ prop }) =>
392
+ ["keyword_proportion", "keyword_growth", "compare_yoy", "compare_ring", "compare_en_ring", "compare_yoyring"].includes(prop),
393
+ );
394
+ return { tokens: cut.tokens, calculations };
395
+ }
396
+
397
+ function overallStatus(results) {
398
+ if (!results.some((result) => result.hasData)) {
399
+ if (results.some((result) => result.status === "failed")) return "failed";
400
+ if (results.some((result) => result.status === "calculation_required")) return "calculation_required";
401
+ return "empty";
402
+ }
403
+ if (results.some((result) => result.status !== "success")) return "partial";
404
+ return "success";
405
+ }
406
+
407
+ export function classifyPreviews(cards, previews) {
408
+ if (!cards.length)
409
+ return {
410
+ status: "empty",
411
+ hasData: false,
412
+ hasErrors: false,
413
+ message: "查询成功,但没有生成直接结果卡片",
414
+ };
415
+ const successful = previews.filter((entry) => !entry.error);
416
+ const hasErrors = successful.length !== previews.length;
417
+ const hasData = successful.some((entry) => !isEmptyQueryResult(entry.data));
418
+ if (!hasData)
419
+ return {
420
+ status: hasErrors && !successful.length ? "failed" : "empty",
421
+ hasData: false,
422
+ hasErrors,
423
+ message: hasErrors
424
+ ? "未获得有效数据,部分或全部数据序列取数失败"
425
+ : "查询成功,但数据结果为空",
426
+ };
427
+ return {
428
+ status: hasErrors ? "partial" : "success",
429
+ hasData: true,
430
+ hasErrors,
431
+ message: hasErrors
432
+ ? "查询得到部分有效数据,另有数据序列取数失败"
433
+ : "查询成功",
434
+ };
435
+ }
436
+
437
+ function isEmptyQueryResult(value) {
438
+ let current = value;
439
+ if (
440
+ current &&
441
+ typeof current === "object" &&
442
+ current.status === "SUCCESS" &&
443
+ Object.hasOwn(current, "data")
444
+ )
445
+ current = current.data;
446
+ if (current === null || current === undefined || current === "") return true;
447
+ if (Array.isArray(current)) return current.length === 0;
448
+ return false;
449
+ }
450
+
451
+ async function cutQuestion(client, workspaceId, question) {
452
+ return client.request(
453
+ "POST",
454
+ `/api/v3/account-projects/${workspaceId}/cut/`,
455
+ { body: { tokens: question } },
456
+ );
457
+ }
458
+
459
+ async function ask(client, workspaceId, question, modelUids) {
460
+ const body = { question, language: "zh-CN" };
461
+ if (modelUids?.length) body.tuids = modelUids;
462
+ const data = await client.request(
463
+ "POST",
464
+ `/api/v3/account-projects/${workspaceId}/ask/`,
465
+ {
466
+ body,
467
+ },
468
+ );
469
+ try {
470
+ return assertAccess(data);
471
+ } catch (error) {
472
+ if (error.code === "FIELD_ACCESS_DENIED")
473
+ error.details.tokens = error.details.tokens.map(({ word }) => ({ word }));
474
+ throw error;
475
+ }
476
+ }
477
+
478
+ async function getAutoInsights(client, workspaceId, card, options) {
479
+ const qKey = card?.data?.[0]?.data?.qKey;
480
+ if (!card?.configs?.hasAutoInsights || !qKey) return null;
481
+ try {
482
+ const task = await client.request(
483
+ "POST",
484
+ `/api/v2/account-projects/${workspaceId}/async-tasks/`,
485
+ {
486
+ body: {
487
+ taskType: 11,
488
+ params: {
489
+ units: card.units ?? [],
490
+ tuids: card.tuids ?? null,
491
+ qKey,
492
+ },
493
+ },
494
+ },
495
+ );
496
+ return unwrapTaskResult(
497
+ await client.poll(workspaceId, task.uid, 11, options),
498
+ );
499
+ } catch (error) {
500
+ rethrowGlobalError(error);
501
+ return {
502
+ error: {
503
+ code: error.code ?? "AUTO_INSIGHTS_FAILED",
504
+ message: error.message,
505
+ },
506
+ };
507
+ }
508
+ }
509
+
510
+ function normalizePlan(plan) {
511
+ if (!plan || typeof plan !== "object")
512
+ throw new DatarcError("搜索计划必须是 JSON 对象", "INVALID_PLAN");
513
+ const type = plan.type ?? "single";
514
+ if (!["single", "parallel", "chained"].includes(type))
515
+ throw new DatarcError(
516
+ "计划类型必须是 single、parallel 或 chained",
517
+ "INVALID_PLAN",
518
+ );
519
+ const questions = Array.isArray(plan.questions) ? plan.questions : [];
520
+ if (!questions.length || questions.length > 20)
521
+ throw new DatarcError("搜索计划必须包含 1 至 20 个问题", "INVALID_PLAN");
522
+ if (type === "single" && questions.length !== 1)
523
+ throw new DatarcError("single 计划只能包含一个问题", "INVALID_PLAN");
524
+ if (type === "chained" && questions.length > 5)
525
+ throw new DatarcError("链式查询最多支持 5 层", "INVALID_PLAN");
526
+ return {
527
+ type,
528
+ questions: questions.map((item, index) => {
529
+ const normalized = typeof item === "string" ? { question: item } : item;
530
+ if (!normalized?.question)
531
+ throw new DatarcError(
532
+ `第 ${index + 1} 个问题缺少 question`,
533
+ "INVALID_PLAN",
534
+ );
535
+ if (
536
+ type === "chained" &&
537
+ index < questions.length - 1 &&
538
+ !normalized.outputDimension
539
+ )
540
+ throw new DatarcError(
541
+ `链式查询第 ${index + 1} 层缺少 outputDimension`,
542
+ "INVALID_PLAN",
543
+ );
544
+ return normalized;
545
+ }),
546
+ };
547
+ }
548
+
549
+ function resolveDimension(tokens, requested) {
550
+ const word = typeof requested === "string" ? requested : requested?.word;
551
+ const matches = tokens.filter(
552
+ (token) =>
553
+ String(token.prop ?? "").startsWith("d") &&
554
+ !String(token.prop ?? "").includes("=") &&
555
+ (!word || token.word === word),
556
+ );
557
+ if (matches.length !== 1)
558
+ throw new DatarcError(
559
+ `无法唯一确定链式查询的输出维度${word ? `“${word}”` : ""}`,
560
+ "INVALID_CHAIN_DIMENSION",
561
+ );
562
+ return {
563
+ word: matches[0].word,
564
+ prop: matches[0].prop.split("=")[0],
565
+ split: Boolean(requested?.split),
566
+ };
567
+ }
568
+
569
+ function tokenType(prop) {
570
+ const value = String(prop ?? "unknown");
571
+ if (value === "unknown") return "unknown";
572
+ if (/^m/.test(value)) return "measure";
573
+ if (/^d/.test(value))
574
+ return value.includes("=") ? "dimension_value" : "dimension";
575
+ if (/^(t|dateRange_)/.test(value)) return "time";
576
+ if (/^(keyword_|op_|compare_|\$)/.test(value)) return "operator";
577
+ return "recognized";
578
+ }
579
+
580
+ function isUnknown(token) {
581
+ return !token.prop || token.prop === "unknown";
582
+ }
583
+
584
+ function modelUidsOf(value) {
585
+ return value
586
+ ? []
587
+ .concat(value)
588
+ .flatMap((item) => String(item).split(","))
589
+ .filter(Boolean)
590
+ : [];
591
+ }
592
+
593
+ function uniqueDirectories(results) {
594
+ const values = results
595
+ .map((result) => result.downloadDirectory)
596
+ .filter(Boolean);
597
+ return [
598
+ ...new Map(values.map((value) => [value.absolutePath, value])).values(),
599
+ ];
600
+ }
601
+
602
+ function downloadStatus(exports) {
603
+ if (exports.length && exports.every((entry) => entry.status === "skipped"))
604
+ return "not_applicable";
605
+ const failures = exports.filter((entry) => entry.error).length;
606
+ if (failures === exports.length) return "failed";
607
+ if (failures) return "partial";
608
+ return "success";
609
+ }
610
+
611
+ function num(value, fallback) {
612
+ const result = Number(value ?? fallback);
613
+ if (!Number.isFinite(result) || result < 0)
614
+ throw new DatarcError("数值参数必须为非负数", "INVALID_ARGUMENT");
615
+ return result;
616
+ }
617
+
618
+ function polling(args) {
619
+ return {
620
+ ...(args.offset === undefined ? {} : { offset: num(args.offset) }),
621
+ ...(args.limit === undefined ? {} : { limit: num(args.limit) }),
622
+ intervalMs: num(args["poll-interval-ms"], 2000),
623
+ maxWaitMs: num(args["max-wait-ms"], 600000),
624
+ };
625
+ }
626
+
627
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
628
+ await runCli(() => execute(process.argv.slice(2)));