@arcticdata/dsh-datarc-skills 0.0.0-stage → 26.39.0

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 (135) hide show
  1. package/README.md +20 -2
  2. package/cordis.patch.yml +4 -0
  3. package/icon.svg +4 -0
  4. package/index.js +35 -0
  5. package/locale/en.json +6 -0
  6. package/locale/zh.json +6 -0
  7. package/package.json +37 -4
  8. package/skills/datarc-access-permissions/SKILL.md +30 -0
  9. package/skills/datarc-access-permissions/references/api.md +31 -0
  10. package/skills/datarc-access-permissions/references/write-order.md +16 -0
  11. package/skills/datarc-analysis-report/SKILL.md +125 -0
  12. package/skills/datarc-analysis-report/agents/openai.yaml +6 -0
  13. package/skills/datarc-analysis-report/references/analyst-frameworks.md +215 -0
  14. package/skills/datarc-analysis-report/references/api-contracts.md +478 -0
  15. package/skills/datarc-analysis-report/references/direct-card-fallback-design.md +66 -0
  16. package/skills/datarc-analysis-report/references/human-in-the-loop.md +142 -0
  17. package/skills/datarc-analysis-report/references/loop-personalization-policy.md +138 -0
  18. package/skills/datarc-analysis-report/references/manifest-example.json +779 -0
  19. package/skills/datarc-analysis-report/references/narrative-schema.md +160 -0
  20. package/skills/datarc-analysis-report/references/question-syntax.md +151 -0
  21. package/skills/datarc-analysis-report/scripts/run_analysis_report.py +2225 -0
  22. package/skills/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -0
  23. package/skills/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -0
  24. package/skills/datarc-data-search/SKILL.md +243 -0
  25. package/skills/datarc-data-search/scripts/calculate.py +116 -0
  26. package/skills/datarc-data-search/scripts/data-search.mjs +628 -0
  27. package/skills/datarc-data-search/scripts/datarc-client.mjs +464 -0
  28. package/skills/datarc-data-search/scripts/search-result.mjs +211 -0
  29. package/skills/datarc-dataseek-batch-evaluation/SKILL.md +59 -0
  30. package/skills/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -0
  31. package/skills/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -0
  32. package/skills/datarc-dataseek-batch-evaluation/scripts/datarc-client.mjs +464 -0
  33. package/skills/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -0
  34. package/skills/datarc-dataseek-search/SKILL.md +96 -0
  35. package/skills/datarc-dataseek-search/scripts/datarc-client.mjs +464 -0
  36. package/skills/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -0
  37. package/skills/datarc-dataseek-semantic-debugging/SKILL.md +44 -0
  38. package/skills/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -0
  39. package/skills/datarc-dataseek-semantic-debugging/evals/evals.json +165 -0
  40. package/skills/datarc-dataseek-semantic-debugging/references/dataset.md +77 -0
  41. package/skills/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -0
  42. package/skills/datarc-dataseek-semantic-debugging/references/interventions.md +64 -0
  43. package/skills/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -0
  44. package/skills/datarc-dataseek-semantic-debugging/references/rollback.md +11 -0
  45. package/skills/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -0
  46. package/skills/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -0
  47. package/skills/datarc-dataseek-testset-generation/SKILL.md +47 -0
  48. package/skills/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -0
  49. package/skills/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -0
  50. package/skills/datarc-datasource/SKILL.md +97 -0
  51. package/skills/datarc-oauth/SKILL.md +47 -0
  52. package/skills/datarc-oauth/scripts/auth.mjs +130 -0
  53. package/skills/datarc-oauth/scripts/credentials.mjs +237 -0
  54. package/skills/datarc-report-add-card/SKILL.md +90 -0
  55. package/skills/datarc-report-add-card/agents/openai.yaml +4 -0
  56. package/skills/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
  57. package/skills/datarc-report-add-card/scripts/report-card.mjs +439 -0
  58. package/skills/datarc-semantic-alias/SKILL.md +20 -0
  59. package/skills/datarc-semantic-alias/scripts/alias-plan.mjs +422 -0
  60. package/skills/datarc-semantic-alias/scripts/alias.mjs +11 -0
  61. package/skills/datarc-semantic-calibration/SKILL.md +20 -0
  62. package/skills/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -0
  63. package/skills/datarc-semantic-calibration/scripts/calibration.mjs +11 -0
  64. package/skills/datarc-semantic-core/SKILL.md +12 -0
  65. package/skills/datarc-semantic-core/scripts/artifact-journal.mjs +830 -0
  66. package/skills/datarc-semantic-core/scripts/canonical.mjs +48 -0
  67. package/skills/datarc-semantic-core/scripts/case-model.mjs +608 -0
  68. package/skills/datarc-semantic-core/scripts/cli.mjs +180 -0
  69. package/skills/datarc-semantic-core/scripts/datarc-client.mjs +180 -0
  70. package/skills/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -0
  71. package/skills/datarc-semantic-core/scripts/interventions.mjs +693 -0
  72. package/skills/datarc-semantic-core/scripts/live-resolution.mjs +305 -0
  73. package/skills/datarc-semantic-core/scripts/model-scope.mjs +49 -0
  74. package/skills/datarc-semantic-core/scripts/reproduction.mjs +330 -0
  75. package/skills/datarc-semantic-core/scripts/semantic-cli.mjs +740 -0
  76. package/skills/datarc-semantic-core/scripts/shared.mjs +312 -0
  77. package/skills/datarc-semantic-core/scripts/verification.mjs +1014 -0
  78. package/skills/datarc-semantic-dataset/SKILL.md +20 -0
  79. package/skills/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -0
  80. package/skills/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -0
  81. package/skills/datarc-semantic-dataset/scripts/dataset.mjs +11 -0
  82. package/skills/datarc-semantic-knowledge/SKILL.md +38 -0
  83. package/skills/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -0
  84. package/skills/datarc-semantic-knowledge/references/knowledge-generation.json +16 -0
  85. package/skills/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -0
  86. package/skills/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -0
  87. package/skills/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -0
  88. package/skills/datarc-semantic-prompt/SKILL.md +20 -0
  89. package/skills/datarc-semantic-prompt/scripts/prompt-plan.mjs +447 -0
  90. package/skills/datarc-semantic-prompt/scripts/prompt.mjs +15 -0
  91. package/skills/datarc-semantic-synonym/SKILL.md +20 -0
  92. package/skills/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -0
  93. package/skills/datarc-semantic-synonym/scripts/synonym.mjs +11 -0
  94. package/skills/datarc-viz-analysis-report/SKILL.md +108 -0
  95. package/skills/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -0
  96. package/skills/datarc-viz-analysis-report/assets/echarts.min.js +45 -0
  97. package/skills/datarc-viz-analysis-report/references/api-contracts.md +163 -0
  98. package/skills/datarc-viz-analysis-report/references/derivation-log.md +157 -0
  99. package/skills/datarc-viz-analysis-report/references/evidence-framework.md +76 -0
  100. package/skills/datarc-viz-analysis-report/references/html-template.md +92 -0
  101. package/skills/datarc-viz-analysis-report/references/provenance-format.md +56 -0
  102. package/skills/datarc-viz-analysis-report/references/question-syntax.md +151 -0
  103. package/skills/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -0
  104. package/skills/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -0
  105. package/skills/datarc-workspace-configuration/SKILL.md +59 -0
  106. package/skills/datarc-workspace-configuration/references/artifacts.md +75 -0
  107. package/skills/datarc-workspace-configuration/references/verification.md +20 -0
  108. package/skills/datarc-workspace-configuration/scripts/configuration.mjs +662 -0
  109. package/skills/datarc-workspace-context/SKILL.md +43 -0
  110. package/skills/datarc-workspace-context/agents/openai.yaml +4 -0
  111. package/skills/datarc-workspace-context/scripts/datarc-client.mjs +31 -0
  112. package/skills/datarc-workspace-context/scripts/query-display.mjs +114 -0
  113. package/skills/datarc-workspace-context/scripts/workspace-context.mjs +58 -0
  114. package/skills/datarc-workspace-custom-tables/SKILL.md +89 -0
  115. package/skills/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -0
  116. package/skills/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -0
  117. package/skills/datarc-workspace-keywords/SKILL.md +197 -0
  118. package/skills/datarc-workspace-keywords/agents/openai.yaml +4 -0
  119. package/skills/datarc-workspace-keywords/references/api-fields.md +79 -0
  120. package/skills/datarc-workspace-keywords/references/derived-measures.md +177 -0
  121. package/skills/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -0
  122. package/skills/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -0
  123. package/skills/datarc-workspace-membership/SKILL.md +29 -0
  124. package/skills/datarc-workspace-membership/references/api.md +19 -0
  125. package/skills/datarc-workspace-modeling/SKILL.md +209 -0
  126. package/skills/datarc-workspace-modeling/agents/openai.yaml +4 -0
  127. package/skills/datarc-workspace-modeling/references/join-preview.md +38 -0
  128. package/skills/datarc-workspace-modeling/references/model-plan.md +300 -0
  129. package/skills/datarc-workspace-modeling/references/model-tags.md +95 -0
  130. package/skills/datarc-workspace-modeling/references/modeling-contract.json +29 -0
  131. package/skills/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -0
  132. package/skills/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -0
  133. package/skills/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -0
  134. package/skills/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -0
  135. package/skills-index.json +194 -0
@@ -0,0 +1,464 @@
1
+ import { resolveCredentials } from "../../datarc-oauth/scripts/credentials.mjs";
2
+ import { createWriteStream } from "node:fs";
3
+ import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
4
+ import { basename, dirname, isAbsolute, relative, resolve } from "node:path";
5
+ import { Readable } from "node:stream";
6
+ import { pipeline } from "node:stream/promises";
7
+
8
+ export class DatarcError extends Error {
9
+ constructor(message, code = "DATARC_ERROR", details) {
10
+ super(message);
11
+ this.name = "DatarcError";
12
+ this.code = code;
13
+ this.details = details;
14
+ }
15
+ }
16
+
17
+ export function parseArgs(argv) {
18
+ const result = { _: [] };
19
+ for (let i = 0; i < argv.length; i += 1) {
20
+ if (!argv[i].startsWith("--")) {
21
+ result._.push(argv[i]);
22
+ continue;
23
+ }
24
+ const key = argv[i].slice(2);
25
+ const next = argv[i + 1];
26
+ if (next === undefined || next.startsWith("--")) result[key] = true;
27
+ else {
28
+ result[key] =
29
+ result[key] === undefined ? next : [].concat(result[key], next);
30
+ i += 1;
31
+ }
32
+ }
33
+ return result;
34
+ }
35
+
36
+ export function required(args, key) {
37
+ if (args[key] === undefined || args[key] === true || args[key] === "")
38
+ throw new DatarcError(`缺少参数 --${key}`, "INVALID_ARGUMENT");
39
+ return args[key];
40
+ }
41
+
42
+ export async function readJson(path) {
43
+ const text = path === "-" ? await stdin() : await readFile(path, "utf8");
44
+ try {
45
+ return JSON.parse(text);
46
+ } catch {
47
+ throw new DatarcError("输入不是有效 JSON", "INVALID_JSON");
48
+ }
49
+ }
50
+
51
+ export function createClient(options = {}) {
52
+ const { endpoint, token } = resolveCredentials(options);
53
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
54
+ const sleep =
55
+ options.sleep ??
56
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
57
+ if (!endpoint)
58
+ throw new DatarcError("未配置 DATARC_ENDPOINT", "MISSING_ENDPOINT");
59
+ if (!token) throw new DatarcError("未配置 DATARC_TOKEN", "MISSING_TOKEN");
60
+
61
+ async function request(method, path, { query, body } = {}) {
62
+ const url = new URL(`${endpoint}${path}`);
63
+ for (const [key, value] of Object.entries(query ?? {}))
64
+ for (const item of [].concat(value ?? []))
65
+ if (item !== "") url.searchParams.append(key, item);
66
+ let response;
67
+ try {
68
+ response = await fetchImpl(url, {
69
+ method,
70
+ headers: {
71
+ Authorization: token,
72
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
73
+ },
74
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
75
+ });
76
+ } catch (error) {
77
+ throw new DatarcError(`网络请求失败:${error.message}`, "NETWORK_ERROR");
78
+ }
79
+ const text = await response.text();
80
+ let payload;
81
+ try {
82
+ payload = text ? JSON.parse(text) : {};
83
+ } catch {
84
+ throw new DatarcError(
85
+ `服务返回非 JSON(HTTP ${response.status})`,
86
+ "INVALID_RESPONSE",
87
+ );
88
+ }
89
+ if (!response.ok || (payload.status && payload.status !== "SUCCESS"))
90
+ throw new DatarcError(
91
+ payload.message || `请求失败(HTTP ${response.status})`,
92
+ apiErrorCode(response.status, payload),
93
+ {
94
+ httpStatus: response.status,
95
+ status: payload.status,
96
+ errorCode: payload.code ?? payload.errcode,
97
+ },
98
+ );
99
+ return payload.data;
100
+ }
101
+
102
+ async function poll(workspaceId, uid, taskType, options = {}) {
103
+ const started = Date.now();
104
+ const maxWaitMs = Number(options.maxWaitMs ?? 600000);
105
+ const intervalMs = Number(options.intervalMs ?? 2000);
106
+ const pending = taskType === 4 ? [0, 1, 4, 5] : [0, 1];
107
+ while (Date.now() - started <= maxWaitMs) {
108
+ const task = await request(
109
+ "GET",
110
+ `/api/v2/account-projects/${workspaceId}/async-tasks/${uid}/`,
111
+ );
112
+ if (Number(task.status) === 2) {
113
+ const result = task.result;
114
+ if (
115
+ [8, 11].includes(Number(taskType)) &&
116
+ (!result ||
117
+ typeof result !== "object" ||
118
+ result.status !== "SUCCESS" ||
119
+ !Object.hasOwn(result, "data"))
120
+ )
121
+ throw new DatarcError(
122
+ "异步任务成功状态缺少有效结果",
123
+ "INVALID_TASK_RESULT",
124
+ { status: task.status, result: safeTaskResult(result) },
125
+ );
126
+ return result;
127
+ }
128
+ if (!pending.includes(Number(task.status)))
129
+ throw new DatarcError("异步任务失败、取消或过期", "TASK_FAILED", {
130
+ status: task.status,
131
+ result: safeTaskResult(task.result),
132
+ });
133
+ await sleep(intervalMs);
134
+ }
135
+ throw new DatarcError("异步任务轮询超时", "TASK_TIMEOUT");
136
+ }
137
+
138
+ async function download(url, destination) {
139
+ const targetUrl = new URL(url);
140
+ const headers =
141
+ targetUrl.origin === new URL(endpoint).origin
142
+ ? { Authorization: token }
143
+ : {};
144
+ let response;
145
+ try {
146
+ response = await fetchImpl(targetUrl, { headers, redirect: "follow" });
147
+ } catch (error) {
148
+ throw new DatarcError(`下载失败:${error.message}`, "NETWORK_ERROR");
149
+ }
150
+ if (!response.ok || !response.body)
151
+ throw new DatarcError(
152
+ `下载失败(HTTP ${response.status})`,
153
+ apiErrorCode(response.status, {}),
154
+ );
155
+ await mkdir(dirname(destination), { recursive: true });
156
+ const temporary = `${destination}.part`;
157
+ let overwritten = false;
158
+ try {
159
+ await stat(destination);
160
+ overwritten = true;
161
+ } catch (error) {
162
+ if (error.code !== "ENOENT") throw error;
163
+ }
164
+ try {
165
+ await pipeline(
166
+ Readable.fromWeb(response.body),
167
+ createWriteStream(temporary),
168
+ );
169
+ await rm(destination, { force: true });
170
+ await rename(temporary, destination);
171
+ return { size: (await stat(destination)).size, overwritten };
172
+ } catch (error) {
173
+ await rm(temporary, { force: true });
174
+ throw new DatarcError(
175
+ `保存下载文件失败:${error.message}`,
176
+ "DOWNLOAD_FAILED",
177
+ );
178
+ }
179
+ }
180
+ return { request, poll, sleep, download };
181
+ }
182
+
183
+ export function primaryCards(cards = []) {
184
+ if (!Array.isArray(cards)) return [];
185
+ const direct = cards.find(
186
+ (card) => Number(card?.resultType ?? card?.result_type ?? 0) === 0,
187
+ );
188
+ return direct ? [direct] : [];
189
+ }
190
+
191
+ export function seriesOf(cards = []) {
192
+ return cards.flatMap((card, cardIndex) =>
193
+ (card.data ?? []).map((series, seriesIndex) => ({
194
+ cardIndex,
195
+ seriesIndex,
196
+ title: card.title ?? `卡片 ${cardIndex + 1}`,
197
+ cardType: card.card_type,
198
+ columns: series.columns ?? [],
199
+ query: series.data,
200
+ })),
201
+ );
202
+ }
203
+
204
+ export function collectCards(value) {
205
+ const cards = [];
206
+ const seen = new Set();
207
+ function visit(current) {
208
+ if (!current || typeof current !== "object" || seen.has(current)) return;
209
+ seen.add(current);
210
+ if (Array.isArray(current.cards))
211
+ cards.push(...primaryCards(current.cards));
212
+ for (const [key, child] of Object.entries(current)) {
213
+ if (key !== "cards") visit(child);
214
+ }
215
+ }
216
+ visit(value);
217
+ if (!cards.length && Array.isArray(value)) return value;
218
+ return cards;
219
+ }
220
+
221
+ export async function preview(client, workspaceId, cards, options = {}) {
222
+ const output = [];
223
+ const seriesList = seriesOf(cards);
224
+ for (const series of seriesList) {
225
+ try {
226
+ if (!series.query?.qKey)
227
+ throw new DatarcError("卡片缺少 qKey", "MISSING_QKEY");
228
+ const queryWorkspaceId = series.query.project ?? workspaceId;
229
+ const task = await client.request(
230
+ "POST",
231
+ `/api/v2/account-projects/${queryWorkspaceId}/async-tasks/`,
232
+ {
233
+ body: {
234
+ taskType: 8,
235
+ params: {
236
+ qKey: series.query.qKey,
237
+ params: queryPageParams(series.query.params, options),
238
+ },
239
+ },
240
+ },
241
+ );
242
+ output.push({
243
+ ...series,
244
+ data: unwrapTaskResult(
245
+ await client.poll(queryWorkspaceId, task.uid, 8, options),
246
+ ),
247
+ });
248
+ } catch (error) {
249
+ rethrowGlobalError(error);
250
+ output.push({ ...series, error: errorJson(error) });
251
+ }
252
+ }
253
+ return output;
254
+ }
255
+
256
+ export function unwrapTaskResult(value) {
257
+ if (
258
+ value &&
259
+ typeof value === "object" &&
260
+ value.status === "SUCCESS" &&
261
+ Object.hasOwn(value, "data")
262
+ )
263
+ return value.data;
264
+ return value;
265
+ }
266
+
267
+ export async function exportAll(client, workspaceId, cards, options = {}) {
268
+ const extension = String(options.extension ?? ".csv").replace(/^(?!\.)/, ".");
269
+ if (![".csv", ".xlsx"].includes(extension))
270
+ throw new DatarcError("导出格式仅支持 csv 或 xlsx", "INVALID_ARGUMENT");
271
+ const output = [];
272
+ const seriesList = seriesOf(cards);
273
+ for (const series of seriesList) {
274
+ if ([1, 12].includes(Number(series.cardType))) {
275
+ output.push({
276
+ ...series,
277
+ extension,
278
+ status: "skipped",
279
+ reasonCode: "NUMBER_CARD_NOT_EXPORTABLE",
280
+ message: "数字卡不支持导出 CSV 或 Excel",
281
+ });
282
+ continue;
283
+ }
284
+ try {
285
+ if (!series.query?.qKey)
286
+ throw new DatarcError("卡片缺少 qKey", "MISSING_QKEY");
287
+ const title = fileTitle(
288
+ options.title ?? series.title,
289
+ seriesList.length > 1 ? series.seriesIndex + 1 : undefined,
290
+ );
291
+ const task = await client.request(
292
+ "POST",
293
+ `/api/v2/account-projects/${workspaceId}/async-tasks/`,
294
+ {
295
+ body: {
296
+ taskType: 4,
297
+ params: {
298
+ title,
299
+ extension,
300
+ data: [{ data: series.query, columns: series.columns }],
301
+ },
302
+ },
303
+ },
304
+ );
305
+ const exported = {
306
+ ...series,
307
+ exportTitle: title,
308
+ extension,
309
+ data: await client.poll(workspaceId, task.uid, 4, options),
310
+ };
311
+ if (options.download) {
312
+ const url = exported.data?.url;
313
+ if (!url)
314
+ throw new DatarcError("导出结果缺少下载地址", "MISSING_DOWNLOAD_URL");
315
+ const directory = outputDirectory(options.outputDir, options.taskId);
316
+ const filePath = resolve(
317
+ directory.absolutePath,
318
+ `${title}${extension}`,
319
+ );
320
+ const saved = await client.download(url, filePath);
321
+ exported.file = {
322
+ relativePath: relative(process.cwd(), filePath),
323
+ absolutePath: filePath,
324
+ size: saved.size,
325
+ overwritten: Boolean(saved.overwritten),
326
+ };
327
+ exported.directory = directory;
328
+ }
329
+ output.push(exported);
330
+ } catch (error) {
331
+ rethrowGlobalError(error);
332
+ output.push({ ...series, extension, error: errorJson(error) });
333
+ }
334
+ }
335
+ return output;
336
+ }
337
+
338
+ export function outputDirectory(value = ".datarc-downloads", taskId) {
339
+ if (typeof value !== "string" || !value)
340
+ throw new DatarcError(
341
+ "--output-dir 必须是非空相对路径",
342
+ "INVALID_ARGUMENT",
343
+ );
344
+ if (isAbsolute(value))
345
+ throw new DatarcError(
346
+ "--output-dir 必须是当前工作目录下的相对路径",
347
+ "INVALID_ARGUMENT",
348
+ );
349
+ if (
350
+ typeof taskId !== "string" ||
351
+ !/^[A-Za-z0-9._-]{1,80}$/.test(taskId) ||
352
+ [".", ".."].includes(taskId)
353
+ )
354
+ throw new DatarcError(
355
+ "下载时必须提供仅含字母、数字、点、下划线或连字符的 --task-id",
356
+ "INVALID_ARGUMENT",
357
+ );
358
+ const cwd = resolve(process.cwd());
359
+ const absolutePath = resolve(cwd, value, taskId);
360
+ const fromCwd = relative(cwd, absolutePath);
361
+ if (fromCwd.startsWith("..") || isAbsolute(fromCwd))
362
+ throw new DatarcError(
363
+ "--output-dir 不得超出当前工作目录",
364
+ "INVALID_ARGUMENT",
365
+ );
366
+ return { taskId, relativePath: fromCwd || ".", absolutePath };
367
+ }
368
+
369
+ export function assertAccess(data) {
370
+ if (data?.canAccessData === false)
371
+ throw new DatarcError("当前用户没有数据访问权限", "DATA_ACCESS_DENIED");
372
+ if (data?.noPermissionTokens?.length)
373
+ throw new DatarcError("查询包含无权访问的字段", "FIELD_ACCESS_DENIED", {
374
+ tokens: data.noPermissionTokens.map(({ word, prop }) => ({ word, prop })),
375
+ });
376
+ return data;
377
+ }
378
+
379
+ export function isGlobalError(error) {
380
+ return [
381
+ "MISSING_ENDPOINT",
382
+ "MISSING_TOKEN",
383
+ "NETWORK_ERROR",
384
+ "INVALID_RESPONSE",
385
+ "AUTHENTICATION_FAILED",
386
+ "PERMISSION_DENIED",
387
+ "RATE_LIMITED",
388
+ "DATA_ACCESS_DENIED",
389
+ "FIELD_ACCESS_DENIED",
390
+ ].includes(error?.code);
391
+ }
392
+
393
+ export function rethrowGlobalError(error) {
394
+ if (isGlobalError(error)) throw error;
395
+ }
396
+
397
+ export function errorJson(error) {
398
+ return {
399
+ code: error?.code ?? "UNEXPECTED_ERROR",
400
+ message: error?.message ?? String(error),
401
+ ...(error?.details === undefined ? {} : { details: error.details }),
402
+ };
403
+ }
404
+ export async function runCli(main) {
405
+ try {
406
+ process.stdout.write(
407
+ `${JSON.stringify({ ok: true, data: await main() }, null, 2)}\n`,
408
+ );
409
+ } catch (error) {
410
+ process.stdout.write(
411
+ `${JSON.stringify({ ok: false, error: errorJson(error) }, null, 2)}\n`,
412
+ );
413
+ process.exitCode = 1;
414
+ }
415
+ }
416
+
417
+ function apiErrorCode(httpStatus, payload) {
418
+ const businessCodes = [payload.status, payload.code, payload.errcode]
419
+ .filter((value) => value !== undefined && value !== null)
420
+ .map(String);
421
+ if (httpStatus === 401) return "AUTHENTICATION_FAILED";
422
+ if (httpStatus === 403) return "PERMISSION_DENIED";
423
+ if (httpStatus === 429 || businessCodes.includes("0110001"))
424
+ return "RATE_LIMITED";
425
+ return "API_ERROR";
426
+ }
427
+
428
+ function queryPageParams(value, options) {
429
+ const params =
430
+ value && typeof value === "object" && !Array.isArray(value)
431
+ ? { ...value }
432
+ : {};
433
+ if (options.offset !== undefined) params.offset = Number(options.offset);
434
+ else if (params.offset === undefined) params.offset = 0;
435
+ if (options.limit !== undefined) params.limit = Number(options.limit);
436
+ else if (params.limit === undefined) params.limit = 100;
437
+ return params;
438
+ }
439
+
440
+ function safeTaskResult(value) {
441
+ if (value === null || value === undefined) return value;
442
+ if (typeof value === "string") return { message: "异步任务执行失败" };
443
+ if (typeof value !== "object" || Array.isArray(value)) return undefined;
444
+ return {
445
+ ...(value.status === undefined ? {} : { status: value.status }),
446
+ ...(value.message === undefined ? {} : { message: "异步任务执行失败" }),
447
+ };
448
+ }
449
+
450
+ function fileTitle(value, seriesNumber) {
451
+ const safeTitle = basename(String(value ?? "data"))
452
+ .replace(/[\\/:*?"<>|]/g, "_")
453
+ .trim()
454
+ .replace(/[. ]+$/g, "")
455
+ .slice(0, 100);
456
+ const base = safeTitle || "data";
457
+ return seriesNumber === undefined ? base : `${base}-${seriesNumber}`;
458
+ }
459
+
460
+ async function stdin() {
461
+ const chunks = [];
462
+ for await (const chunk of process.stdin) chunks.push(chunk);
463
+ return Buffer.concat(chunks).toString("utf8");
464
+ }
@@ -0,0 +1,211 @@
1
+ import { mkdtemp, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { credentialBinding, resolveCredentials } from "../../datarc-oauth/scripts/credentials.mjs";
5
+ import { DatarcError, readJson } from "./datarc-client.mjs";
6
+
7
+ function credentialScope(options) {
8
+ const { endpoint, token } = resolveCredentials(options);
9
+ return credentialBinding(endpoint, token);
10
+ }
11
+
12
+ export async function readSearchResult(
13
+ file,
14
+ workspaceId,
15
+ options,
16
+ kind = "result",
17
+ ) {
18
+ if (options?.resultStorage === "artifact")
19
+ throw new DatarcError("远程问数请通过 input_artifact 传入原搜索任务的结果工件。", "INVALID_ARGUMENT");
20
+ let saved;
21
+ try {
22
+ saved = await readJson(file);
23
+ } catch (error) {
24
+ if (error.code !== "ENOENT") throw error;
25
+ throw new DatarcError(
26
+ "上轮结果文件已不可用,请使用对话中已有的预览,或重新查询缺少的数据",
27
+ "RESULT_UNAVAILABLE",
28
+ );
29
+ }
30
+ return validateSearchResult(saved, workspaceId, options, kind);
31
+ }
32
+
33
+ function validateSearchResult(saved, workspaceId, options, kind = "result") {
34
+ if (
35
+ saved?.kind !== kind ||
36
+ !saved.scope ||
37
+ saved.scope !== credentialScope(options) ||
38
+ (workspaceId !== undefined && String(workspaceId) !== saved.workspaceId)
39
+ ) {
40
+ throw new DatarcError(
41
+ "结果与当前服务、登录身份或工作区不匹配,请使用当前会话的查询结果",
42
+ "RESULT_SCOPE_MISMATCH",
43
+ );
44
+ }
45
+ // Older snapshots stored a requested offset as if it had been confirmed.
46
+ if (kind === "result" && saved.summary?.previews?.some((series) => "offset" in series)) {
47
+ saved.summary.previews = saved.summary.previews.map(({ offset, ...series }) => ({
48
+ ...series,
49
+ ...columnMetadata(saved.answer?.cards?.[series.cardIndex]?.data?.[series.seriesIndex]?.columns),
50
+ ...(offset === undefined ? {} : unknownPage),
51
+ }));
52
+ }
53
+ return saved;
54
+ }
55
+
56
+ export async function saveInspection(workspaceId, question, tokens, options) {
57
+ const dir = await mkdtemp(join(tmpdir(), "datarc-inspect-"));
58
+ const file = join(dir, "inspection.json");
59
+ await writeFile(
60
+ file,
61
+ JSON.stringify({
62
+ kind: "inspection",
63
+ workspaceId: String(workspaceId),
64
+ scope: credentialScope(options),
65
+ question,
66
+ tokens,
67
+ }),
68
+ { mode: 0o600, flag: "wx" },
69
+ );
70
+ return file;
71
+ }
72
+
73
+ // Resolve a saved CLI envelope, a single result file, or a legacy inline card.
74
+ export async function resolveResultInput(input, workspaceId, options) {
75
+ const payload = input?.ok === true ? input.data : input;
76
+ if (options?.resultStorage === "artifact" && Array.isArray(payload?.results) &&
77
+ payload.results.some((item) => !item?.answer && Array.isArray(item?.previews))) {
78
+ throw new DatarcError("业务摘要不含卡片,请用 input_artifact 传入原搜索任务的结果工件。", "INVALID_ARGUMENT");
79
+ }
80
+ if (payload?.kind === "result")
81
+ return validateSearchResult(payload, workspaceId, options);
82
+ if (
83
+ payload?.results?.length &&
84
+ payload.results.every((result) => result.resultFile || result.status === "calculation_required")
85
+ ) {
86
+ const results = await Promise.all(payload.results.map((result) =>
87
+ result.resultFile ? readSearchResult(result.resultFile, workspaceId, options) : result
88
+ ));
89
+ return { results };
90
+ }
91
+ return input;
92
+ }
93
+
94
+ // Attribution may include executable units. Keep business data rows intact.
95
+ export function businessMetadata(value) {
96
+ if (Array.isArray(value)) return value.map(businessMetadata);
97
+ if (!value || typeof value !== "object") return value;
98
+ return Object.fromEntries(
99
+ Object.entries(value)
100
+ .filter(([key]) => !["prop", "qKey", "units", "sql"].includes(key))
101
+ .map(([key, item]) => [key, businessMetadata(item)]),
102
+ );
103
+ }
104
+
105
+ function columnMetadata(columns = []) {
106
+ const details = columns.map((column) => ({
107
+ ...(column?._f ? { format: column._f } : {}),
108
+ ...(column?._cc ? { currencyCode: column._cc } : {}),
109
+ }));
110
+ return details.some((detail) => Object.keys(detail).length)
111
+ ? { columnMetadata: details }
112
+ : {};
113
+ }
114
+
115
+ const unknownPage = {
116
+ coverage: "unknown",
117
+ message: "服务端未确认实际分页范围,请按明确的对象或时间范围重新查询后再合并。",
118
+ };
119
+
120
+ export function businessSeries(entries, options = {}) {
121
+ return entries.map(({ columns, query, data, ...entry }) => {
122
+ const names = (columns ?? []).map((column) =>
123
+ typeof column === "string"
124
+ ? column
125
+ : column?._n && column._n !== column._nes
126
+ ? column._n
127
+ : null,
128
+ );
129
+ const series = { ...entry, columns: names, ...columnMetadata(columns), data };
130
+ if (entry.extension || entry.error) return series;
131
+ if (options.page || options.offset !== undefined || options.limit !== undefined ||
132
+ query?.params?.offset !== undefined || query?.params?.limit !== undefined)
133
+ return { ...series, ...unknownPage };
134
+ // A first preview describes the original question, including any ranking in it.
135
+ const truncated = data !== null && typeof data === "object" &&
136
+ (!Array.isArray(data) || data.length >= 100);
137
+ return { ...series, coverage: truncated ? "preview" : "complete" };
138
+ });
139
+ }
140
+
141
+ export async function presentSearch(raw, workspaceId, modelUids, options) {
142
+ const results = [];
143
+ const scope = options.resultStorage === "artifact" ? undefined : credentialScope(options);
144
+ let dir;
145
+ for (const [
146
+ index,
147
+ { answer, previews, exports, ...result },
148
+ ] of raw.results.entries()) {
149
+ if (result.status === "calculation_required") {
150
+ results.push(result);
151
+ continue;
152
+ }
153
+ const measureAliases = answer.cards.flatMap((card) =>
154
+ (card.explanations ?? []).flatMap((scope) =>
155
+ (scope.measures ?? [])
156
+ .flat()
157
+ .filter(
158
+ (token) =>
159
+ Array.isArray(token.names) &&
160
+ token.word !== token.prop &&
161
+ token.names.some(
162
+ (name) => name !== token.word && name !== token.prop,
163
+ ),
164
+ )
165
+ .map((token) => ({
166
+ model: scope.model,
167
+ measure: token.word,
168
+ names: token.names.filter(
169
+ (name) => name !== token.word && name !== token.prop,
170
+ ),
171
+ })),
172
+ ),
173
+ );
174
+ const summary = {
175
+ ...result,
176
+ ...(measureAliases.length ? { measureAliases } : {}),
177
+ insights: businessMetadata(result.insights),
178
+ previews: businessSeries(previews, options),
179
+ ...(exports ? { exports: businessSeries(exports) } : {}),
180
+ };
181
+ const cardSource = { tokens: answer.tokens, cards: answer.cards };
182
+ if (options.resultStorage === "artifact") {
183
+ results.push({ ...summary, answer: cardSource });
184
+ continue;
185
+ }
186
+ dir ??= await mkdtemp(join(tmpdir(), "datarc-search-"));
187
+ const resultFile = join(dir, `result-${index + 1}.json`);
188
+ const actualModels = answer.cards.flatMap((card) =>
189
+ card.activeTuids?.length
190
+ ? card.activeTuids
191
+ : (card.explanations ?? [])
192
+ .map((item) => item.modelUid)
193
+ .filter(Boolean),
194
+ );
195
+ const saved = {
196
+ kind: "result",
197
+ workspaceId: String(workspaceId),
198
+ scope,
199
+ modelUids: modelUids.length ? modelUids : [...new Set(actualModels)],
200
+ question: result.question,
201
+ answer: cardSource,
202
+ summary,
203
+ };
204
+ await writeFile(resultFile, JSON.stringify(saved), {
205
+ mode: 0o600,
206
+ flag: "wx",
207
+ });
208
+ results.push({ ...summary, resultFile });
209
+ }
210
+ return { ...raw, results };
211
+ }