@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,192 +1,192 @@
1
- import { basename } from "node:path";
2
- import { createInterface } from "node:readline/promises";
3
- import { setTimeout as delay } from "node:timers/promises";
4
- import { pathToFileURL } from "node:url";
5
- import { credentialsPath, normalizeEndpoint, resolveCredentials, saveCredentials } from "./credentials.mjs";
6
-
7
- export async function execute(argv, options = {}) {
8
- const [command, ...extra] = argv;
9
- if (
10
- !["status", "login"].includes(command) ||
11
- (extra.length && !(command === "login" && extra.length === 2 && extra[0] === "--endpoint" && extra[1]))
12
- )
13
- throw new Error("命令无效;请使用 status,或 login --endpoint <服务网址> 发起网页授权");
14
- let saved;
15
- if (command === "login") {
16
- let data;
17
- try {
18
- data = extra.length ? { endpoint: extra[1] } : JSON.parse(options.input ?? (await readInput(options)));
19
- } catch {
20
- throw new Error("认证输入无效;请提供服务网址,或通过安全标准输入提交包含 endpoint 和 token 的 JSON");
21
- }
22
- if (!data || typeof data !== "object" || Array.isArray(data))
23
- throw new Error("认证信息无效;请提供服务网址后重新发起授权");
24
- const endpoint = normalizeEndpoint(data.endpoint || resolveCredentials(options).endpoint);
25
- if (!endpoint) throw new Error("尚未配置服务网址;请使用 login --endpoint <服务网址> 发起授权");
26
- // Keep secure stdin token imports compatible; new logins need only an endpoint.
27
- let token = data.token;
28
- if (Object.hasOwn(data, "token")) {
29
- if (typeof token !== "string" || !token.trim() || /[\r\n]/.test(token))
30
- throw new Error("认证信息不完整;请提供服务网址和有效登录令牌,或只提供网址使用网页授权");
31
- } else {
32
- token = await browserLogin(endpoint, options);
33
- }
34
- const current = resolveCredentials({ ...options, endpoint, token });
35
- await validateCredentials(current, options);
36
- try {
37
- saveCredentials(current, options);
38
- saved = current;
39
- } catch (error) {
40
- return {
41
- authenticated: true,
42
- saved: false,
43
- endpoint: current.endpoint,
44
- message: "登录校验成功,但凭据未保存,后续调用仍需认证。" + error.message,
45
- };
46
- }
47
- }
48
- const current = resolveCredentials(options);
49
- return {
50
- ...(saved
51
- ? {
52
- authenticated: true,
53
- saved: true,
54
- active: saved.endpoint === current.endpoint && saved.token === current.token,
55
- ...(saved.endpoint !== current.endpoint || saved.token !== current.token
56
- ? { message: "凭据已保存,但当前环境变量覆盖了新配置;请更新或删除旧变量并重启宿主后使用新登录" }
57
- : {}),
58
- }
59
- : {}),
60
- configPath: options.configPath ?? credentialsPath(options.env),
61
- endpoint: current.endpoint,
62
- hasToken: Boolean(current.token),
63
- defaultWorkspace: current.defaultWorkspace ? { id: current.defaultWorkspace.id, name: current.defaultWorkspace.name } : null,
64
- };
65
- }
66
-
67
- async function browserLogin(endpoint, options) {
68
- const now = options.now ?? Date.now;
69
- const started = now();
70
- const workspace = options.env?.DATARC_WORKSPACE_DIR || process.env.DATARC_WORKSPACE_DIR || process.cwd();
71
- const flow = await authorizationRequest(endpoint, "device-authorizations/", {
72
- client_name: "北极九章",
73
- project_name: basename(workspace).slice(0, 200) || "当前项目",
74
- }, options, 30000);
75
- if (
76
- typeof flow?.user_code !== "string" || !/^[A-Za-z0-9_-]{8}$/.test(flow.user_code) ||
77
- typeof flow.device_code !== "string" || !/^[A-Za-z0-9_.-]{32,128}$/.test(flow.device_code) ||
78
- !Number.isInteger(flow.expires_in) || flow.expires_in < 1 || flow.expires_in > 600 ||
79
- !Number.isInteger(flow.interval) || flow.interval < 1 || flow.interval > 60
80
- )
81
- throw new Error("授权服务响应无效;请检查服务版本和网址后重新登录");
82
- // Do not open or display a server-controlled cross-origin URL or a credential-bearing URL.
83
- const expected = "/#/auth/authorize?user_code=" + encodeURIComponent(flow.user_code);
84
- if (flow.verification_uri_complete !== expected)
85
- throw new Error("授权网址与当前服务不匹配;请检查服务版本和网址后重新登录");
86
- const event = {
87
- url: new URL(expected, endpoint).href,
88
- userCode: flow.user_code,
89
- expiresIn: flow.expires_in,
90
- interval: flow.interval,
91
- };
92
- if (options.onAuthorization) await options.onAuthorization(event);
93
- else process.stdout.write(JSON.stringify({ ok: true, event: "authorization_required", data: event }) + "\n");
94
- const deadline = started + flow.expires_in * 1000;
95
- let interval = flow.interval;
96
- while (now() < deadline) {
97
- const remaining = deadline - now();
98
- if (remaining <= interval * 1000) break;
99
- try {
100
- await (options.sleepImpl ?? ((ms) => delay(ms, undefined, { signal: options.signal })))(interval * 1000);
101
- } catch {
102
- throw new Error("授权等待已取消;需要登录时请重新发起授权");
103
- }
104
- if (now() >= deadline) break;
105
- const result = await authorizationRequest(endpoint, "device-authorization/token/", { device_code: flow.device_code }, options, Math.min(30000, deadline - now()));
106
- if (result?.status === "authorized") {
107
- if (result.user_agent !== 5 || typeof result.token !== "string" || !result.token.trim() || result.token.length > 8192 || /[\r\n]/.test(result.token))
108
- throw new Error("领取的个人令牌无效;请从客户端重新发起授权");
109
- return result.token;
110
- }
111
- if (result?.status === "denied") throw new Error("用户已取消授权;需要登录时请重新发起授权");
112
- if (!["pending", "slow_down"].includes(result?.status))
113
- throw new Error("授权状态无效;请从客户端重新发起授权");
114
- if (result.interval !== undefined && (!Number.isInteger(result.interval) || result.interval < 1 || result.interval > 60))
115
- throw new Error("授权轮询间隔无效;请检查服务版本后重新登录");
116
- interval = Math.min(60, Math.max(interval, result.interval ?? interval) + (result.status === "slow_down" ? 5 : 0));
117
- }
118
- throw new Error("授权等待已超时;请重新发起授权并在十分钟内完成网页确认");
119
- }
120
-
121
- async function authorizationRequest(endpoint, path, body, options, timeout) {
122
- const response = await fetchResponse(`${endpoint}/api/v3/auth/${path}`, {
123
- method: "POST",
124
- headers: { "Content-Type": "application/json" },
125
- body: JSON.stringify(body),
126
- }, options, timeout);
127
- if (response.status === 429 && path === "device-authorization/token/") return { status: "slow_down", interval: 5 };
128
- let payload;
129
- try {
130
- payload = await response.json();
131
- } catch {
132
- throw new Error("授权服务响应无效;请检查服务网址后重新登录");
133
- }
134
- if (!response.ok || payload?.status !== "SUCCESS")
135
- throw new Error(`授权请求未完成(HTTP ${response.status});请检查服务网址或从客户端重新发起授权`);
136
- return payload.data;
137
- }
138
-
139
- async function validateCredentials(current, options) {
140
- const response = await fetchResponse(`${current.endpoint}/api/v2/account-projects/?limit=1`, {
141
- headers: { Authorization: current.token },
142
- }, options, 30000);
143
- let payload;
144
- try {
145
- payload = await response.json();
146
- } catch {
147
- throw new Error("服务响应无效;请检查服务网址后重试");
148
- }
149
- if (!response.ok || payload?.status !== "SUCCESS")
150
- throw new Error(`登录校验失败(HTTP ${response.status});请核对业务用户令牌及服务网址后重试`);
151
- }
152
-
153
- async function fetchResponse(url, init, options, timeout) {
154
- try {
155
- const signal = AbortSignal.timeout(Math.max(1, Math.floor(timeout)));
156
- return await (options.fetchImpl ?? fetch)(url, {
157
- ...init,
158
- redirect: "error",
159
- signal: options.signal ? AbortSignal.any([signal, options.signal]) : signal,
160
- });
161
- } catch {
162
- throw new Error("无法连接 datarc 或请求已取消;请检查服务网址和网络后重新登录");
163
- }
164
- }
165
-
166
- async function readInput(options) {
167
- if (process.stdin.isTTY) {
168
- const endpoint = resolveCredentials(options).endpoint;
169
- if (endpoint) return JSON.stringify({ endpoint });
170
- const terminal = createInterface({ input: process.stdin, output: process.stdout, terminal: true, historySize: 0 });
171
- try {
172
- return JSON.stringify({ endpoint: await terminal.question("datarc 服务网址:") });
173
- } finally {
174
- terminal.close();
175
- }
176
- }
177
- let input = "";
178
- for await (const chunk of process.stdin) {
179
- input += chunk;
180
- if (input.length > 65536) throw new Error();
181
- }
182
- return input;
183
- }
184
-
185
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
186
- try {
187
- console.log(JSON.stringify({ ok: true, data: await execute(process.argv.slice(2)) }));
188
- } catch (error) {
189
- console.log(JSON.stringify({ ok: false, error: { message: error.message } }));
190
- process.exitCode = 1;
191
- }
192
- }
1
+ import { basename } from "node:path";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { pathToFileURL } from "node:url";
5
+ import { credentialsPath, normalizeEndpoint, resolveCredentials, saveCredentials } from "./credentials.mjs";
6
+
7
+ export async function execute(argv, options = {}) {
8
+ const [command, ...extra] = argv;
9
+ if (
10
+ !["status", "login"].includes(command) ||
11
+ (extra.length && !(command === "login" && extra.length === 2 && extra[0] === "--endpoint" && extra[1]))
12
+ )
13
+ throw new Error("命令无效;请使用 status,或 login --endpoint <服务网址> 发起网页授权");
14
+ let saved;
15
+ if (command === "login") {
16
+ let data;
17
+ try {
18
+ data = extra.length ? { endpoint: extra[1] } : JSON.parse(options.input ?? (await readInput(options)));
19
+ } catch {
20
+ throw new Error("认证输入无效;请提供服务网址,或通过安全标准输入提交包含 endpoint 和 token 的 JSON");
21
+ }
22
+ if (!data || typeof data !== "object" || Array.isArray(data))
23
+ throw new Error("认证信息无效;请提供服务网址后重新发起授权");
24
+ const endpoint = normalizeEndpoint(data.endpoint || resolveCredentials(options).endpoint);
25
+ if (!endpoint) throw new Error("尚未配置服务网址;请使用 login --endpoint <服务网址> 发起授权");
26
+ // Keep secure stdin token imports compatible; new logins need only an endpoint.
27
+ let token = data.token;
28
+ if (Object.hasOwn(data, "token")) {
29
+ if (typeof token !== "string" || !token.trim() || /[\r\n]/.test(token))
30
+ throw new Error("认证信息不完整;请提供服务网址和有效登录令牌,或只提供网址使用网页授权");
31
+ } else {
32
+ token = await browserLogin(endpoint, options);
33
+ }
34
+ const current = resolveCredentials({ ...options, endpoint, token });
35
+ await validateCredentials(current, options);
36
+ try {
37
+ saveCredentials(current, options);
38
+ saved = current;
39
+ } catch (error) {
40
+ return {
41
+ authenticated: true,
42
+ saved: false,
43
+ endpoint: current.endpoint,
44
+ message: "登录校验成功,但凭据未保存,后续调用仍需认证。" + error.message,
45
+ };
46
+ }
47
+ }
48
+ const current = resolveCredentials(options);
49
+ return {
50
+ ...(saved
51
+ ? {
52
+ authenticated: true,
53
+ saved: true,
54
+ active: saved.endpoint === current.endpoint && saved.token === current.token,
55
+ ...(saved.endpoint !== current.endpoint || saved.token !== current.token
56
+ ? { message: "凭据已保存,但当前环境变量覆盖了新配置;请更新或删除旧变量并重启宿主后使用新登录" }
57
+ : {}),
58
+ }
59
+ : {}),
60
+ configPath: options.configPath ?? credentialsPath(options.env),
61
+ endpoint: current.endpoint,
62
+ hasToken: Boolean(current.token),
63
+ defaultWorkspace: current.defaultWorkspace ? { id: current.defaultWorkspace.id, name: current.defaultWorkspace.name } : null,
64
+ };
65
+ }
66
+
67
+ async function browserLogin(endpoint, options) {
68
+ const now = options.now ?? Date.now;
69
+ const started = now();
70
+ const workspace = options.env?.DATARC_WORKSPACE_DIR || process.env.DATARC_WORKSPACE_DIR || process.cwd();
71
+ const flow = await authorizationRequest(endpoint, "device-authorizations/", {
72
+ client_name: "北极九章",
73
+ project_name: basename(workspace).slice(0, 200) || "当前项目",
74
+ }, options, 30000);
75
+ if (
76
+ typeof flow?.user_code !== "string" || !/^[A-Za-z0-9_-]{8}$/.test(flow.user_code) ||
77
+ typeof flow.device_code !== "string" || !/^[A-Za-z0-9_.-]{32,128}$/.test(flow.device_code) ||
78
+ !Number.isInteger(flow.expires_in) || flow.expires_in < 1 || flow.expires_in > 600 ||
79
+ !Number.isInteger(flow.interval) || flow.interval < 1 || flow.interval > 60
80
+ )
81
+ throw new Error("授权服务响应无效;请检查服务版本和网址后重新登录");
82
+ // Do not open or display a server-controlled cross-origin URL or a credential-bearing URL.
83
+ const expected = "/#/auth/authorize?user_code=" + encodeURIComponent(flow.user_code);
84
+ if (flow.verification_uri_complete !== expected)
85
+ throw new Error("授权网址与当前服务不匹配;请检查服务版本和网址后重新登录");
86
+ const event = {
87
+ url: new URL(expected, endpoint).href,
88
+ userCode: flow.user_code,
89
+ expiresIn: flow.expires_in,
90
+ interval: flow.interval,
91
+ };
92
+ if (options.onAuthorization) await options.onAuthorization(event);
93
+ else process.stdout.write(JSON.stringify({ ok: true, event: "authorization_required", data: event }) + "\n");
94
+ const deadline = started + flow.expires_in * 1000;
95
+ let interval = flow.interval;
96
+ while (now() < deadline) {
97
+ const remaining = deadline - now();
98
+ if (remaining <= interval * 1000) break;
99
+ try {
100
+ await (options.sleepImpl ?? ((ms) => delay(ms, undefined, { signal: options.signal })))(interval * 1000);
101
+ } catch {
102
+ throw new Error("授权等待已取消;需要登录时请重新发起授权");
103
+ }
104
+ if (now() >= deadline) break;
105
+ const result = await authorizationRequest(endpoint, "device-authorization/token/", { device_code: flow.device_code }, options, Math.min(30000, deadline - now()));
106
+ if (result?.status === "authorized") {
107
+ if (result.user_agent !== 5 || typeof result.token !== "string" || !result.token.trim() || result.token.length > 8192 || /[\r\n]/.test(result.token))
108
+ throw new Error("领取的个人令牌无效;请从客户端重新发起授权");
109
+ return result.token;
110
+ }
111
+ if (result?.status === "denied") throw new Error("用户已取消授权;需要登录时请重新发起授权");
112
+ if (!["pending", "slow_down"].includes(result?.status))
113
+ throw new Error("授权状态无效;请从客户端重新发起授权");
114
+ if (result.interval !== undefined && (!Number.isInteger(result.interval) || result.interval < 1 || result.interval > 60))
115
+ throw new Error("授权轮询间隔无效;请检查服务版本后重新登录");
116
+ interval = Math.min(60, Math.max(interval, result.interval ?? interval) + (result.status === "slow_down" ? 5 : 0));
117
+ }
118
+ throw new Error("授权等待已超时;请重新发起授权并在十分钟内完成网页确认");
119
+ }
120
+
121
+ async function authorizationRequest(endpoint, path, body, options, timeout) {
122
+ const response = await fetchResponse(`${endpoint}/api/v3/auth/${path}`, {
123
+ method: "POST",
124
+ headers: { "Content-Type": "application/json" },
125
+ body: JSON.stringify(body),
126
+ }, options, timeout);
127
+ if (response.status === 429 && path === "device-authorization/token/") return { status: "slow_down", interval: 5 };
128
+ let payload;
129
+ try {
130
+ payload = await response.json();
131
+ } catch {
132
+ throw new Error("授权服务响应无效;请检查服务网址后重新登录");
133
+ }
134
+ if (!response.ok || payload?.status !== "SUCCESS")
135
+ throw new Error(`授权请求未完成(HTTP ${response.status});请检查服务网址或从客户端重新发起授权`);
136
+ return payload.data;
137
+ }
138
+
139
+ async function validateCredentials(current, options) {
140
+ const response = await fetchResponse(`${current.endpoint}/api/v2/account-projects/?limit=1`, {
141
+ headers: { Authorization: current.token },
142
+ }, options, 30000);
143
+ let payload;
144
+ try {
145
+ payload = await response.json();
146
+ } catch {
147
+ throw new Error("服务响应无效;请检查服务网址后重试");
148
+ }
149
+ if (!response.ok || payload?.status !== "SUCCESS")
150
+ throw new Error(`登录校验失败(HTTP ${response.status});请核对业务用户令牌及服务网址后重试`);
151
+ }
152
+
153
+ async function fetchResponse(url, init, options, timeout) {
154
+ try {
155
+ const signal = AbortSignal.timeout(Math.max(1, Math.floor(timeout)));
156
+ return await (options.fetchImpl ?? fetch)(url, {
157
+ ...init,
158
+ redirect: "error",
159
+ signal: options.signal ? AbortSignal.any([signal, options.signal]) : signal,
160
+ });
161
+ } catch {
162
+ throw new Error("无法连接 datarc 或请求已取消;请检查服务网址和网络后重新登录");
163
+ }
164
+ }
165
+
166
+ async function readInput(options) {
167
+ if (process.stdin.isTTY) {
168
+ const endpoint = resolveCredentials(options).endpoint;
169
+ if (endpoint) return JSON.stringify({ endpoint });
170
+ const terminal = createInterface({ input: process.stdin, output: process.stdout, terminal: true, historySize: 0 });
171
+ try {
172
+ return JSON.stringify({ endpoint: await terminal.question("datarc 服务网址:") });
173
+ } finally {
174
+ terminal.close();
175
+ }
176
+ }
177
+ let input = "";
178
+ for await (const chunk of process.stdin) {
179
+ input += chunk;
180
+ if (input.length > 65536) throw new Error();
181
+ }
182
+ return input;
183
+ }
184
+
185
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
186
+ try {
187
+ console.log(JSON.stringify({ ok: true, data: await execute(process.argv.slice(2)) }));
188
+ } catch (error) {
189
+ console.log(JSON.stringify({ ok: false, error: { message: error.message } }));
190
+ process.exitCode = 1;
191
+ }
192
+ }