@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,347 +1,347 @@
1
- import { readFile } from "node:fs/promises";
2
- import {
3
- createCli,
4
- journalCommand,
5
- } from "../../datarc-semantic-core/scripts/cli.mjs";
6
- import {
7
- fail,
8
- isRecord,
9
- listAllPages,
10
- normalizeText,
11
- } from "../../datarc-semantic-core/scripts/shared.mjs";
12
- import { hashArtifactValue } from "../../datarc-semantic-core/scripts/canonical.mjs";
13
- import {
14
- loadWorkspaceModels,
15
- normalizeModelScope,
16
- } from "../../datarc-semantic-core/scripts/model-scope.mjs";
17
- import {
18
- normalizeKnowledgeOperation,
19
- corpusCollection,
20
- } from "./knowledge-plan.mjs";
21
-
22
- export const generationContract = JSON.parse(
23
- await readFile(
24
- new URL("../references/knowledge-generation.json", import.meta.url),
25
- "utf8",
26
- ),
27
- );
28
-
29
- export function validateKnowledgeDrafts(generation, models) {
30
- exactFields(generation, ["drafts", "message"]);
31
- if (
32
- typeof generation.message !== "string" ||
33
- !Array.isArray(generation.drafts) ||
34
- generation.drafts.length === 0 ||
35
- generation.drafts.length > generationContract.limits.drafts
36
- )
37
- fail(
38
- "INVALID_KNOWLEDGE_DRAFT",
39
- "草稿数量应为 1 到 10 条,请修改需求并重新生成。",
40
- );
41
- const available = new Set(models.map((model) => model.uid));
42
- const seen = new Set();
43
- return generation.drafts.map((draft) => {
44
- exactFields(draft, [
45
- "knowledge_text",
46
- "purposes",
47
- "model_scope",
48
- "model_uids",
49
- "needs_confirmation",
50
- "questions",
51
- "warnings",
52
- ]);
53
- if (
54
- typeof draft.knowledge_text !== "string" ||
55
- !draft.knowledge_text.trim() ||
56
- [...draft.knowledge_text].length >
57
- generationContract.limits.knowledge_characters
58
- )
59
- fail(
60
- "INVALID_KNOWLEDGE_DRAFT",
61
- "每条知识须为非空文字且不超过 2000 字,请修改后重新校验。",
62
- );
63
- if (
64
- !Array.isArray(draft.purposes) ||
65
- draft.purposes.length === 0 ||
66
- new Set(draft.purposes).size !== draft.purposes.length ||
67
- draft.purposes.some(
68
- (purpose) => !Object.hasOwn(generationContract.purposes, purpose),
69
- )
70
- )
71
- fail(
72
- "INVALID_KNOWLEDGE_DRAFT",
73
- "请从五个独立用途选择至少一项,并去除重复用途。",
74
- );
75
- if (
76
- typeof draft.needs_confirmation !== "boolean" ||
77
- ![draft.questions, draft.warnings].every(
78
- (items) =>
79
- Array.isArray(items) &&
80
- items.every((item) => typeof item === "string" && item.trim()),
81
- )
82
- )
83
- fail(
84
- "INVALID_KNOWLEDGE_DRAFT",
85
- "草稿确认状态或提示格式无效,请按生成契约重新整理。",
86
- );
87
- if (
88
- draft.needs_confirmation ||
89
- draft.questions.length ||
90
- draft.model_scope === "unconfirmed"
91
- )
92
- fail(
93
- "DRAFT_CONFIRMATION_REQUIRED",
94
- "草稿仍有待确认内容,请先回答问题并修订草稿,再生成正式方案。",
95
- );
96
- let tuids;
97
- if (draft.model_scope === "all_available") {
98
- if (!Array.isArray(draft.model_uids) || draft.model_uids.length)
99
- fail(
100
- "INVALID_KNOWLEDGE_DRAFT",
101
- "全模型草稿的 model_uids 应为空数组,请修改后重新校验。",
102
- );
103
- tuids = null;
104
- } else if (draft.model_scope === "specified") {
105
- tuids = normalizeModelScope(draft.model_uids);
106
- if (tuids.some((uid) => !available.has(uid)))
107
- fail(
108
- "MODEL_SCOPE_UNAVAILABLE",
109
- "草稿包含不属于当前工作区的模型,请从实时模型列表重新选择。",
110
- );
111
- } else
112
- fail(
113
- "INVALID_KNOWLEDGE_DRAFT",
114
- "模型范围无效,请明确选择全模型或指定模型。",
115
- );
116
- const normalized = {
117
- ...structuredClone(draft),
118
- knowledge_text: draft.knowledge_text.trim(),
119
- purposes: [...draft.purposes].sort(),
120
- model_uids: tuids ?? [],
121
- };
122
- const identity = hashArtifactValue({
123
- knowledge_text: normalized.knowledge_text,
124
- model_scope: normalized.model_scope,
125
- model_uids: normalized.model_uids,
126
- });
127
- if (seen.has(identity))
128
- fail(
129
- "DUPLICATE_KNOWLEDGE_DRAFT",
130
- "草稿有重复知识,请合并相同正文与用途后重试。",
131
- );
132
- seen.add(identity);
133
- return normalized;
134
- });
135
- }
136
-
137
- export async function loadKnowledgeContext(client, workspaceId) {
138
- const rows = await listAllPages(client, corpusCollection(workspaceId));
139
- const knowledge = [];
140
- for (const row of rows) {
141
- const detail =
142
- typeof row.corpus === "string"
143
- ? row
144
- : await client.request(
145
- "GET",
146
- `${corpusCollection(workspaceId)}${row.id}/`,
147
- );
148
- if (
149
- String(detail?.id) !== String(row.id) ||
150
- typeof detail?.corpus !== "string"
151
- )
152
- fail(
153
- "INVALID_KNOWLEDGE_STATE",
154
- "无法读取完整共享知识,请刷新工作区后重试。",
155
- );
156
- knowledge.push({
157
- id: detail.id,
158
- name: detail.name,
159
- corpus: detail.corpus,
160
- scenes: detail.scenes,
161
- tuids: detail.tuids,
162
- active: detail.active,
163
- });
164
- }
165
- return {
166
- knowledge_scope: "workspace",
167
- workspace: { id: workspaceId },
168
- available_models: await loadWorkspaceModels(client, workspaceId),
169
- workspace_knowledge: knowledge,
170
- existing_personal_knowledge: [],
171
- limits: generationContract.limits,
172
- };
173
- }
174
-
175
- export function draftsToOperations(workspaceId, drafts, context, names, ids) {
176
- if (
177
- names !== undefined &&
178
- (!Array.isArray(names) || names.length !== drafts.length)
179
- )
180
- fail(
181
- "INVALID_KNOWLEDGE_DRAFT",
182
- "知识标题数量须与草稿一致,请修订 names 后重试。",
183
- );
184
- if (
185
- ids !== undefined &&
186
- (!Array.isArray(ids) || ids.length !== drafts.length)
187
- )
188
- fail(
189
- "INVALID_KNOWLEDGE_DRAFT",
190
- "编辑目标数量须与草稿一致,请修订 ids 后重试。",
191
- );
192
- const operations = drafts.map((draft, index) => {
193
- const name =
194
- names?.[index] ?? [...draft.knowledge_text].slice(0, 50).join("");
195
- const id = ids?.[index];
196
- if (
197
- id !== undefined &&
198
- id !== null &&
199
- !context.workspace_knowledge.some((row) => String(row.id) === String(id))
200
- )
201
- fail(
202
- "KNOWLEDGE_NOT_FOUND",
203
- "编辑目标不属于当前工作区,请刷新知识列表并重新选择。",
204
- );
205
- if (
206
- (id === undefined || id === null) &&
207
- context.workspace_knowledge.some(
208
- (row) => normalizeText(row.name) === normalizeText(name),
209
- )
210
- )
211
- fail(
212
- "KNOWLEDGE_IDENTITY_REVIEW_REQUIRED",
213
- "标题与已有知识相同,请明确 ids 编辑目标,或修改 names 后重试。",
214
- );
215
- return normalizeKnowledgeOperation({
216
- caseId: `knowledge-draft:${index}`,
217
- kind: "knowledge",
218
- name,
219
- corpus: draft.knowledge_text,
220
- scenes: draft.purposes.map(
221
- (purpose) => generationContract.purposes[purpose],
222
- ),
223
- tuids: draft.model_scope === "all_available" ? null : draft.model_uids,
224
- active: true,
225
- ...(id === undefined || id === null ? {} : { id }),
226
- });
227
- });
228
- if (
229
- new Set(operations.map((op) => op.id ?? normalizeText(op.name))).size !==
230
- operations.length
231
- )
232
- fail(
233
- "KNOWLEDGE_IDENTITY_AMBIGUOUS",
234
- "多条草稿指向同一知识,请合并草稿或调整标题与编辑目标。",
235
- );
236
- return { workspaceId, operations };
237
- }
238
-
239
- function exactFields(value, fields) {
240
- if (
241
- !isRecord(value) ||
242
- Object.keys(value).length !== fields.length ||
243
- fields.some((field) => !Object.hasOwn(value, field))
244
- )
245
- fail(
246
- "INVALID_KNOWLEDGE_DRAFT",
247
- "草稿字段不符合生成契约,请移除额外字段并补全必填字段。",
248
- );
249
- }
250
-
251
- function workspaceFromInput(input) {
252
- if (!Number.isSafeInteger(input?.workspaceId) || input.workspaceId <= 0)
253
- fail("INVALID_INPUT", "请选择当前工作区,再提供有效的 workspaceId。");
254
- return input.workspaceId;
255
- }
256
-
257
- async function draftCommand(client, input, args, options, command) {
258
- const allowed =
259
- command === "draft-context"
260
- ? ["workspaceId", "user_requirement"]
261
- : ["workspaceId", "generation", "names", "ids"];
262
- if (
263
- !isRecord(input) ||
264
- Object.keys(input).some((key) => !allowed.includes(key))
265
- )
266
- fail("INVALID_INPUT", "草稿命令参数无效,请按 --help 调整输入。");
267
- const workspaceId = workspaceFromInput(input);
268
- if (
269
- command === "draft-context" &&
270
- (typeof input.user_requirement !== "string" ||
271
- !input.user_requirement.trim() ||
272
- [...input.user_requirement].length >
273
- generationContract.limits.requirement_characters)
274
- )
275
- fail("INVALID_INPUT", "请输入不超过 8000 字的需求后重新生成。");
276
- return journalCommand({
277
- command,
278
- workspaceId,
279
- input,
280
- request: { workspaceId, inputHash: hashArtifactValue(input) },
281
- output: args.output,
282
- options,
283
- operation: async () => {
284
- const context = await loadKnowledgeContext(client, workspaceId);
285
- if (command === "draft-context")
286
- return {
287
- version: generationContract.version,
288
- system_prompt: generationContract.system_prompt,
289
- context: { ...context, user_requirement: input.user_requirement },
290
- };
291
- const drafts = validateKnowledgeDrafts(
292
- input.generation,
293
- context.available_models,
294
- );
295
- return {
296
- version: generationContract.version,
297
- draftHash: hashArtifactValue({ workspaceId, drafts }),
298
- drafts,
299
- planInput: draftsToOperations(
300
- workspaceId,
301
- drafts,
302
- context,
303
- input.names,
304
- input.ids,
305
- ),
306
- warnings: drafts.flatMap((draft) => draft.warnings),
307
- status: "validated_unsaved",
308
- previewSupported: false,
309
- };
310
- },
311
- response: (result, artifact) => ({
312
- artifact,
313
- summary: {
314
- workspaceId,
315
- status: command === "draft-context" ? "context_ready" : result.status,
316
- ...(result.draftHash
317
- ? { draftHash: result.draftHash, drafts: result.drafts.length }
318
- : {}),
319
- previewSupported: false,
320
- },
321
- }),
322
- });
323
- }
324
-
325
- export const draftCli = createCli({
326
- commandNames: ["draft-context", "draft-validate"],
327
- flags: {
328
- "draft-context": new Set(["input", "output"]),
329
- "draft-validate": new Set(["input", "output"]),
330
- },
331
- help: `Knowledge draft commands:
332
- draft-context --input PATH --output PATH
333
- Input: {workspaceId,user_requirement}; reads shared knowledge and models, writes the private generation Prompt and context.
334
- draft-validate --input PATH --output PATH
335
- Input: {workspaceId,generation:{drafts,message},names?,ids?}; validates five purposes and live models, writes private planInput.
336
- names and ids are optional parallel arrays; use null ids for new knowledge and explicit ids for updates.
337
- Generation is performed by the Agent using the shared Prompt; these commands do not save knowledge or preview DataSeek.
338
- Review planInput, then use the existing plan/apply/verify/rollback commands.
339
- `,
340
- requiresOutput: ["draft-context", "draft-validate"],
341
- handlers: {
342
- "draft-context": (client, input, args, options) =>
343
- draftCommand(client, input, args, options, "draft-context"),
344
- "draft-validate": (client, input, args, options) =>
345
- draftCommand(client, input, args, options, "draft-validate"),
346
- },
347
- });
1
+ import { readFile } from "node:fs/promises";
2
+ import {
3
+ createCli,
4
+ journalCommand,
5
+ } from "../../datarc-semantic-core/scripts/cli.mjs";
6
+ import {
7
+ fail,
8
+ isRecord,
9
+ listAllPages,
10
+ normalizeText,
11
+ } from "../../datarc-semantic-core/scripts/shared.mjs";
12
+ import { hashArtifactValue } from "../../datarc-semantic-core/scripts/canonical.mjs";
13
+ import {
14
+ loadWorkspaceModels,
15
+ normalizeModelScope,
16
+ } from "../../datarc-semantic-core/scripts/model-scope.mjs";
17
+ import {
18
+ normalizeKnowledgeOperation,
19
+ corpusCollection,
20
+ } from "./knowledge-plan.mjs";
21
+
22
+ export const generationContract = JSON.parse(
23
+ await readFile(
24
+ new URL("../references/knowledge-generation.json", import.meta.url),
25
+ "utf8",
26
+ ),
27
+ );
28
+
29
+ export function validateKnowledgeDrafts(generation, models) {
30
+ exactFields(generation, ["drafts", "message"]);
31
+ if (
32
+ typeof generation.message !== "string" ||
33
+ !Array.isArray(generation.drafts) ||
34
+ generation.drafts.length === 0 ||
35
+ generation.drafts.length > generationContract.limits.drafts
36
+ )
37
+ fail(
38
+ "INVALID_KNOWLEDGE_DRAFT",
39
+ "草稿数量应为 1 到 10 条,请修改需求并重新生成。",
40
+ );
41
+ const available = new Set(models.map((model) => model.uid));
42
+ const seen = new Set();
43
+ return generation.drafts.map((draft) => {
44
+ exactFields(draft, [
45
+ "knowledge_text",
46
+ "purposes",
47
+ "model_scope",
48
+ "model_uids",
49
+ "needs_confirmation",
50
+ "questions",
51
+ "warnings",
52
+ ]);
53
+ if (
54
+ typeof draft.knowledge_text !== "string" ||
55
+ !draft.knowledge_text.trim() ||
56
+ [...draft.knowledge_text].length >
57
+ generationContract.limits.knowledge_characters
58
+ )
59
+ fail(
60
+ "INVALID_KNOWLEDGE_DRAFT",
61
+ "每条知识须为非空文字且不超过 2000 字,请修改后重新校验。",
62
+ );
63
+ if (
64
+ !Array.isArray(draft.purposes) ||
65
+ draft.purposes.length === 0 ||
66
+ new Set(draft.purposes).size !== draft.purposes.length ||
67
+ draft.purposes.some(
68
+ (purpose) => !Object.hasOwn(generationContract.purposes, purpose),
69
+ )
70
+ )
71
+ fail(
72
+ "INVALID_KNOWLEDGE_DRAFT",
73
+ "请从五个独立用途选择至少一项,并去除重复用途。",
74
+ );
75
+ if (
76
+ typeof draft.needs_confirmation !== "boolean" ||
77
+ ![draft.questions, draft.warnings].every(
78
+ (items) =>
79
+ Array.isArray(items) &&
80
+ items.every((item) => typeof item === "string" && item.trim()),
81
+ )
82
+ )
83
+ fail(
84
+ "INVALID_KNOWLEDGE_DRAFT",
85
+ "草稿确认状态或提示格式无效,请按生成契约重新整理。",
86
+ );
87
+ if (
88
+ draft.needs_confirmation ||
89
+ draft.questions.length ||
90
+ draft.model_scope === "unconfirmed"
91
+ )
92
+ fail(
93
+ "DRAFT_CONFIRMATION_REQUIRED",
94
+ "草稿仍有待确认内容,请先回答问题并修订草稿,再生成正式方案。",
95
+ );
96
+ let tuids;
97
+ if (draft.model_scope === "all_available") {
98
+ if (!Array.isArray(draft.model_uids) || draft.model_uids.length)
99
+ fail(
100
+ "INVALID_KNOWLEDGE_DRAFT",
101
+ "全模型草稿的 model_uids 应为空数组,请修改后重新校验。",
102
+ );
103
+ tuids = null;
104
+ } else if (draft.model_scope === "specified") {
105
+ tuids = normalizeModelScope(draft.model_uids);
106
+ if (tuids.some((uid) => !available.has(uid)))
107
+ fail(
108
+ "MODEL_SCOPE_UNAVAILABLE",
109
+ "草稿包含不属于当前工作区的模型,请从实时模型列表重新选择。",
110
+ );
111
+ } else
112
+ fail(
113
+ "INVALID_KNOWLEDGE_DRAFT",
114
+ "模型范围无效,请明确选择全模型或指定模型。",
115
+ );
116
+ const normalized = {
117
+ ...structuredClone(draft),
118
+ knowledge_text: draft.knowledge_text.trim(),
119
+ purposes: [...draft.purposes].sort(),
120
+ model_uids: tuids ?? [],
121
+ };
122
+ const identity = hashArtifactValue({
123
+ knowledge_text: normalized.knowledge_text,
124
+ model_scope: normalized.model_scope,
125
+ model_uids: normalized.model_uids,
126
+ });
127
+ if (seen.has(identity))
128
+ fail(
129
+ "DUPLICATE_KNOWLEDGE_DRAFT",
130
+ "草稿有重复知识,请合并相同正文与用途后重试。",
131
+ );
132
+ seen.add(identity);
133
+ return normalized;
134
+ });
135
+ }
136
+
137
+ export async function loadKnowledgeContext(client, workspaceId) {
138
+ const rows = await listAllPages(client, corpusCollection(workspaceId));
139
+ const knowledge = [];
140
+ for (const row of rows) {
141
+ const detail =
142
+ typeof row.corpus === "string"
143
+ ? row
144
+ : await client.request(
145
+ "GET",
146
+ `${corpusCollection(workspaceId)}${row.id}/`,
147
+ );
148
+ if (
149
+ String(detail?.id) !== String(row.id) ||
150
+ typeof detail?.corpus !== "string"
151
+ )
152
+ fail(
153
+ "INVALID_KNOWLEDGE_STATE",
154
+ "无法读取完整共享知识,请刷新工作区后重试。",
155
+ );
156
+ knowledge.push({
157
+ id: detail.id,
158
+ name: detail.name,
159
+ corpus: detail.corpus,
160
+ scenes: detail.scenes,
161
+ tuids: detail.tuids,
162
+ active: detail.active,
163
+ });
164
+ }
165
+ return {
166
+ knowledge_scope: "workspace",
167
+ workspace: { id: workspaceId },
168
+ available_models: await loadWorkspaceModels(client, workspaceId),
169
+ workspace_knowledge: knowledge,
170
+ existing_personal_knowledge: [],
171
+ limits: generationContract.limits,
172
+ };
173
+ }
174
+
175
+ export function draftsToOperations(workspaceId, drafts, context, names, ids) {
176
+ if (
177
+ names !== undefined &&
178
+ (!Array.isArray(names) || names.length !== drafts.length)
179
+ )
180
+ fail(
181
+ "INVALID_KNOWLEDGE_DRAFT",
182
+ "知识标题数量须与草稿一致,请修订 names 后重试。",
183
+ );
184
+ if (
185
+ ids !== undefined &&
186
+ (!Array.isArray(ids) || ids.length !== drafts.length)
187
+ )
188
+ fail(
189
+ "INVALID_KNOWLEDGE_DRAFT",
190
+ "编辑目标数量须与草稿一致,请修订 ids 后重试。",
191
+ );
192
+ const operations = drafts.map((draft, index) => {
193
+ const name =
194
+ names?.[index] ?? [...draft.knowledge_text].slice(0, 50).join("");
195
+ const id = ids?.[index];
196
+ if (
197
+ id !== undefined &&
198
+ id !== null &&
199
+ !context.workspace_knowledge.some((row) => String(row.id) === String(id))
200
+ )
201
+ fail(
202
+ "KNOWLEDGE_NOT_FOUND",
203
+ "编辑目标不属于当前工作区,请刷新知识列表并重新选择。",
204
+ );
205
+ if (
206
+ (id === undefined || id === null) &&
207
+ context.workspace_knowledge.some(
208
+ (row) => normalizeText(row.name) === normalizeText(name),
209
+ )
210
+ )
211
+ fail(
212
+ "KNOWLEDGE_IDENTITY_REVIEW_REQUIRED",
213
+ "标题与已有知识相同,请明确 ids 编辑目标,或修改 names 后重试。",
214
+ );
215
+ return normalizeKnowledgeOperation({
216
+ caseId: `knowledge-draft:${index}`,
217
+ kind: "knowledge",
218
+ name,
219
+ corpus: draft.knowledge_text,
220
+ scenes: draft.purposes.map(
221
+ (purpose) => generationContract.purposes[purpose],
222
+ ),
223
+ tuids: draft.model_scope === "all_available" ? null : draft.model_uids,
224
+ active: true,
225
+ ...(id === undefined || id === null ? {} : { id }),
226
+ });
227
+ });
228
+ if (
229
+ new Set(operations.map((op) => op.id ?? normalizeText(op.name))).size !==
230
+ operations.length
231
+ )
232
+ fail(
233
+ "KNOWLEDGE_IDENTITY_AMBIGUOUS",
234
+ "多条草稿指向同一知识,请合并草稿或调整标题与编辑目标。",
235
+ );
236
+ return { workspaceId, operations };
237
+ }
238
+
239
+ function exactFields(value, fields) {
240
+ if (
241
+ !isRecord(value) ||
242
+ Object.keys(value).length !== fields.length ||
243
+ fields.some((field) => !Object.hasOwn(value, field))
244
+ )
245
+ fail(
246
+ "INVALID_KNOWLEDGE_DRAFT",
247
+ "草稿字段不符合生成契约,请移除额外字段并补全必填字段。",
248
+ );
249
+ }
250
+
251
+ function workspaceFromInput(input) {
252
+ if (!Number.isSafeInteger(input?.workspaceId) || input.workspaceId <= 0)
253
+ fail("INVALID_INPUT", "请选择当前工作区,再提供有效的 workspaceId。");
254
+ return input.workspaceId;
255
+ }
256
+
257
+ async function draftCommand(client, input, args, options, command) {
258
+ const allowed =
259
+ command === "draft-context"
260
+ ? ["workspaceId", "user_requirement"]
261
+ : ["workspaceId", "generation", "names", "ids"];
262
+ if (
263
+ !isRecord(input) ||
264
+ Object.keys(input).some((key) => !allowed.includes(key))
265
+ )
266
+ fail("INVALID_INPUT", "草稿命令参数无效,请按 --help 调整输入。");
267
+ const workspaceId = workspaceFromInput(input);
268
+ if (
269
+ command === "draft-context" &&
270
+ (typeof input.user_requirement !== "string" ||
271
+ !input.user_requirement.trim() ||
272
+ [...input.user_requirement].length >
273
+ generationContract.limits.requirement_characters)
274
+ )
275
+ fail("INVALID_INPUT", "请输入不超过 8000 字的需求后重新生成。");
276
+ return journalCommand({
277
+ command,
278
+ workspaceId,
279
+ input,
280
+ request: { workspaceId, inputHash: hashArtifactValue(input) },
281
+ output: args.output,
282
+ options,
283
+ operation: async () => {
284
+ const context = await loadKnowledgeContext(client, workspaceId);
285
+ if (command === "draft-context")
286
+ return {
287
+ version: generationContract.version,
288
+ system_prompt: generationContract.system_prompt,
289
+ context: { ...context, user_requirement: input.user_requirement },
290
+ };
291
+ const drafts = validateKnowledgeDrafts(
292
+ input.generation,
293
+ context.available_models,
294
+ );
295
+ return {
296
+ version: generationContract.version,
297
+ draftHash: hashArtifactValue({ workspaceId, drafts }),
298
+ drafts,
299
+ planInput: draftsToOperations(
300
+ workspaceId,
301
+ drafts,
302
+ context,
303
+ input.names,
304
+ input.ids,
305
+ ),
306
+ warnings: drafts.flatMap((draft) => draft.warnings),
307
+ status: "validated_unsaved",
308
+ previewSupported: false,
309
+ };
310
+ },
311
+ response: (result, artifact) => ({
312
+ artifact,
313
+ summary: {
314
+ workspaceId,
315
+ status: command === "draft-context" ? "context_ready" : result.status,
316
+ ...(result.draftHash
317
+ ? { draftHash: result.draftHash, drafts: result.drafts.length }
318
+ : {}),
319
+ previewSupported: false,
320
+ },
321
+ }),
322
+ });
323
+ }
324
+
325
+ export const draftCli = createCli({
326
+ commandNames: ["draft-context", "draft-validate"],
327
+ flags: {
328
+ "draft-context": new Set(["input", "output"]),
329
+ "draft-validate": new Set(["input", "output"]),
330
+ },
331
+ help: `Knowledge draft commands:
332
+ draft-context --input PATH --output PATH
333
+ Input: {workspaceId,user_requirement}; reads shared knowledge and models, writes the private generation Prompt and context.
334
+ draft-validate --input PATH --output PATH
335
+ Input: {workspaceId,generation:{drafts,message},names?,ids?}; validates five purposes and live models, writes private planInput.
336
+ names and ids are optional parallel arrays; use null ids for new knowledge and explicit ids for updates.
337
+ Generation is performed by the Agent using the shared Prompt; these commands do not save knowledge or preview DataSeek.
338
+ Review planInput, then use the existing plan/apply/verify/rollback commands.
339
+ `,
340
+ requiresOutput: ["draft-context", "draft-validate"],
341
+ handlers: {
342
+ "draft-context": (client, input, args, options) =>
343
+ draftCommand(client, input, args, options, "draft-context"),
344
+ "draft-validate": (client, input, args, options) =>
345
+ draftCommand(client, input, args, options, "draft-validate"),
346
+ },
347
+ });