dknowc-dsh 1.0.0 → 1.0.2
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.
- package/README.md +14 -9
- package/package.json +2 -2
- package/skills/dknowc-official-doc-writer/README.md +1 -1
- package/skills/dknowc-official-doc-writer/SKILL.md +75 -19
- package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +3 -3
- package/skills/dknowc-official-doc-writer/reference/task_router.md +14 -13
- package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +149 -111
- package/skills/dknowc-official-doc-writer/scripts/check_release.py +7 -2
- package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +8 -2
- package/skills/dknowc-official-doc-writer/scripts/format_document.py +14 -8
- package/skills/dknowc-official-doc-writer/scripts/initialize.py +36 -4
- package/skills/dknowc-official-doc-writer/scripts/local_memory.py +351 -0
- package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +9 -3
- package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +8 -2
- package/skills/dknowc-official-doc-writer/scripts/review_document.py +7 -1
- package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +7 -1
- package/skills/dknowc-official-doc-writer/scripts/template_generator.py +9 -3
- package/skills/dknowc-trusted-consulting/README.md +3 -3
- package/skills/dknowc-trusted-consulting/SKILL.md +25 -20
- package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +149 -111
- package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +17 -4
- package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +45 -7
- package/skills/dknowc-trusted-search/SKILL.md +33 -27
- package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +149 -111
- package/skills/dknowc-trusted-search/scripts/deep_query.py +8 -2
- package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +7 -1
- package/skills/dknowc-trusted-search/scripts/render_trace_html.py +7 -1
- package/skills/dknowc-trusted-search/scripts/trusted_search.py +8 -2
|
@@ -1,19 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""深知 dsh —— MCP 工具返回 → 渲染脚本输入 适配器。
|
|
3
3
|
|
|
4
|
-
dsh 场景下,skill
|
|
5
|
-
|
|
6
|
-
MCP
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
4
|
+
dsh 场景下,skill 通过深知可信工作台 MCP 工具(credible_chat /
|
|
5
|
+
trusted_search / deep_query,或注册后经 mcp_direct.py 直调)拿数据。
|
|
6
|
+
MCP 返回是协议结构 {content:[{type:"text",text:"<业务JSON>"}]},其内层
|
|
7
|
+
业务 JSON 的字段形态与原直连接口不同,而 render_trace_html.py 等渲染
|
|
8
|
+
脚本按原接口结构消费字段。
|
|
9
|
+
|
|
10
|
+
本脚本按【MCP 实测返回】做字段映射(2026-08-19 实测三个工具确认):
|
|
11
|
+
|
|
12
|
+
credible_chat 内层(chat 模式,渲染脚本基本兼容,直通+防御):
|
|
13
|
+
answer 答案正文(渲染脚本 extract_answer 支持顶层 answer)
|
|
14
|
+
referenceMaterials[] 参考材料(title/url/sourceUrl/unit/content[].text 等,
|
|
15
|
+
与 source_from_article 字段兼容,直接透传)
|
|
16
|
+
policyFiles[] / recommendationItems[] / trace_report_url 附加信息,透传保留
|
|
17
|
+
|
|
18
|
+
trusted_search 内层(search 模式,需要映射):
|
|
19
|
+
materials[{title,source,date,paragraph,url}] → data.检索文章[]
|
|
20
|
+
(渲染脚本 extract_articles_from_search 只认中文键 data.检索文章)
|
|
21
|
+
knowledge_base_url → knowledgeBase / knowledgeBaseUrl(渲染脚本只认驼峰)
|
|
22
|
+
|
|
23
|
+
deep_query 内层(deep 模式,需要映射):
|
|
24
|
+
materials[] / search_groups[].materials[] → data.list[]
|
|
25
|
+
(渲染脚本 extract_articles_from_deep 认 data.list)
|
|
26
|
+
progress[](字符串过程记录)原样保留,供 Agent 综合答案时参考
|
|
27
|
+
答案不由接口给出,由 Agent 基于材料形成后经 --answer-file 传入
|
|
11
28
|
|
|
12
29
|
用法:
|
|
13
30
|
python3 scripts/adapt_mcp_result.py <mcp返回.json> --output <规范化.json> [--mode chat|search|deep]
|
|
14
31
|
|
|
15
|
-
-
|
|
16
|
-
-
|
|
32
|
+
- 输入:MCP 工具返回 JSON(mcp_direct.py --output 的产物,或模型保存的
|
|
33
|
+
dsh mcp-client 工具返回;支持 content[].text / structuredContent / 已解包形态)
|
|
34
|
+
- 输出:render_trace_html.py 可直接消费的接口 JSON
|
|
17
35
|
- --mode:chat=可信咨询 / search=可信搜索 / deep=深度搜索;缺省自动识别
|
|
18
36
|
"""
|
|
19
37
|
|
|
@@ -25,12 +43,12 @@ from typing import Any, Dict, List, Optional
|
|
|
25
43
|
|
|
26
44
|
|
|
27
45
|
def _deep_find(o: Any, keys, depth=0, max_depth=8):
|
|
28
|
-
"""在任意嵌套结构里查找第一个命中任一 key
|
|
46
|
+
"""在任意嵌套结构里查找第一个命中任一 key 的非空值。"""
|
|
29
47
|
if depth > max_depth:
|
|
30
48
|
return None
|
|
31
49
|
if isinstance(o, dict):
|
|
32
50
|
for k, v in o.items():
|
|
33
|
-
if k in keys:
|
|
51
|
+
if k in keys and v not in (None, "", [], {}):
|
|
34
52
|
return v
|
|
35
53
|
r = _deep_find(v, keys, depth + 1, max_depth)
|
|
36
54
|
if r is not None:
|
|
@@ -47,13 +65,11 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
|
|
|
47
65
|
"""从 MCP 协议返回中提取文本内容。
|
|
48
66
|
|
|
49
67
|
支持形态:
|
|
50
|
-
- {content: [{type:"text", text:"..."}]}(MCP 标准,text
|
|
68
|
+
- {content: [{type:"text", text:"..."}]}(MCP 标准,text 为业务 JSON 字符串)
|
|
51
69
|
- {structuredContent: {...}}
|
|
52
|
-
-
|
|
53
|
-
返回:解析出的 dict payload;无法解析时返回 None。
|
|
70
|
+
- 已是解包后的业务 JSON dict
|
|
54
71
|
"""
|
|
55
72
|
if isinstance(o, dict):
|
|
56
|
-
# structuredContent 优先
|
|
57
73
|
sc = o.get("structuredContent")
|
|
58
74
|
if isinstance(sc, dict):
|
|
59
75
|
return json.dumps(sc, ensure_ascii=False)
|
|
@@ -67,8 +83,12 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
|
|
|
67
83
|
parts.append(block)
|
|
68
84
|
if parts:
|
|
69
85
|
return "\n".join(parts)
|
|
70
|
-
#
|
|
71
|
-
|
|
86
|
+
# result.content 嵌套形态(完整 MCP JSON-RPC 响应)
|
|
87
|
+
result = o.get("result")
|
|
88
|
+
if isinstance(result, dict):
|
|
89
|
+
return _extract_mcp_text(result)
|
|
90
|
+
# 已是业务 JSON(answer/materials/referenceMaterials 等特征键)
|
|
91
|
+
if any(k in o for k in ("answer", "referenceMaterials", "materials", "检索文章", "progress", "search_meta")):
|
|
72
92
|
return json.dumps(o, ensure_ascii=False)
|
|
73
93
|
return None
|
|
74
94
|
|
|
@@ -83,118 +103,139 @@ def _try_json(text: str) -> Any:
|
|
|
83
103
|
return None
|
|
84
104
|
|
|
85
105
|
|
|
86
|
-
def
|
|
87
|
-
"""
|
|
106
|
+
def _material_to_search_article(m: Dict[str, Any]) -> Dict[str, Any]:
|
|
107
|
+
"""trusted_search 的 materials 条目 → 渲染脚本认的检索文章结构。
|
|
88
108
|
|
|
89
|
-
|
|
90
|
-
|
|
109
|
+
渲染脚本 source_from_article 认的字段名(多 key 兜底):
|
|
110
|
+
标题:文章标题/title/标题;来源:unit/sourceElement/数据源/发布机关/来源;
|
|
111
|
+
日期:发布日期/date/发布时间;网址:sourceUrl/source_url/源网址/url/原文;
|
|
112
|
+
摘录:摘要/相关段落/全文/content/text。
|
|
113
|
+
这里把 MCP 的英文字段同时写入中文键与英文键,保证两条提取路径都能命中。
|
|
91
114
|
"""
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return merged
|
|
110
|
-
break
|
|
111
|
-
return cur if isinstance(cur, dict) else {"raw": cur}
|
|
115
|
+
title = str(m.get("title") or m.get("标题") or "")
|
|
116
|
+
source = str(m.get("source") or m.get("来源") or m.get("unit") or "")
|
|
117
|
+
date = str(m.get("date") or m.get("发布日期") or "")
|
|
118
|
+
url = str(m.get("url") or m.get("sourceUrl") or m.get("源网址") or "")
|
|
119
|
+
paragraph = str(m.get("paragraph") or m.get("content") or m.get("摘要") or "")
|
|
120
|
+
return {
|
|
121
|
+
"标题": title,
|
|
122
|
+
"title": title,
|
|
123
|
+
"来源": source,
|
|
124
|
+
"发布日期": date,
|
|
125
|
+
"date": date,
|
|
126
|
+
"源网址": url,
|
|
127
|
+
"sourceUrl": url,
|
|
128
|
+
"url": url,
|
|
129
|
+
"摘要": paragraph,
|
|
130
|
+
"全文": paragraph,
|
|
131
|
+
}
|
|
112
132
|
|
|
113
133
|
|
|
114
134
|
def _normalize_chat(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
115
|
-
"""规范化可信咨询(credible_chat)返回。
|
|
135
|
+
"""规范化可信咨询(credible_chat)返回。
|
|
136
|
+
|
|
137
|
+
MCP 内层已是顶层 answer + referenceMaterials 形态,渲染脚本
|
|
138
|
+
extract_answer / extract_sources / source_from_article 直接兼容,
|
|
139
|
+
此处直通透传,仅做两处防御:
|
|
140
|
+
- answer 缺失时从任意位置兜底找正文,包成渲染脚本认的 resp.content
|
|
141
|
+
- 保留 trace_report_url / policyFiles / recommendationItems 等附加字段
|
|
142
|
+
"""
|
|
116
143
|
out = dict(payload)
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
answer = _deep_find(payload, ("content", "answer", "text", "resp"), depth=0)
|
|
126
|
-
if isinstance(answer, str):
|
|
127
|
-
out["resp"] = {"content": answer}
|
|
128
|
-
# 确保 referenceMaterials
|
|
129
|
-
if "referenceMaterials" not in out:
|
|
130
|
-
rm = data.get("referenceMaterials") if isinstance(data, dict) else None
|
|
131
|
-
if isinstance(rm, list):
|
|
132
|
-
out["referenceMaterials"] = rm
|
|
133
|
-
# knowledgeBase / question
|
|
134
|
-
for key in ("knowledgeBase", "question"):
|
|
135
|
-
if key not in out and isinstance(data, dict) and key in data:
|
|
136
|
-
out[key] = data[key]
|
|
144
|
+
if not (isinstance(out.get("answer"), str) and out.get("answer").strip()):
|
|
145
|
+
answer = _deep_find(payload, ("answer", "contentText"))
|
|
146
|
+
if isinstance(answer, str) and answer.strip():
|
|
147
|
+
out["answer"] = answer
|
|
148
|
+
# 渲染脚本 extract_answer 优先找 resp.content;补一份兼容形态
|
|
149
|
+
answer = out.get("answer")
|
|
150
|
+
if isinstance(answer, str) and answer.strip() and not isinstance(out.get("resp"), dict):
|
|
151
|
+
out["resp"] = {"content": answer}
|
|
137
152
|
return out
|
|
138
153
|
|
|
139
154
|
|
|
140
155
|
def _normalize_search(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
141
|
-
"""规范化可信搜索(trusted_search
|
|
156
|
+
"""规范化可信搜索(trusted_search)返回:materials → data.检索文章,
|
|
157
|
+
knowledge_base_url → knowledgeBase(驼峰)。
|
|
158
|
+
"""
|
|
142
159
|
out = dict(payload)
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
data
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
if
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
out["knowledgeBase"] = kb
|
|
160
|
+
materials = payload.get("materials")
|
|
161
|
+
if isinstance(materials, list):
|
|
162
|
+
articles = [_material_to_search_article(m) for m in materials if isinstance(m, dict)]
|
|
163
|
+
data = out.get("data") if isinstance(out.get("data"), dict) else {}
|
|
164
|
+
data["检索文章"] = articles
|
|
165
|
+
out["data"] = data
|
|
166
|
+
out["total_articles"] = out.get("total_articles") or len(articles)
|
|
167
|
+
# 兼容旧直连形态(content.data.检索文章)的防御提取
|
|
168
|
+
if not (isinstance(out.get("data"), dict) and isinstance(out["data"].get("检索文章"), list)):
|
|
169
|
+
legacy = _deep_find(payload, ("检索文章",))
|
|
170
|
+
if isinstance(legacy, list) and legacy:
|
|
171
|
+
data = out.get("data") if isinstance(out.get("data"), dict) else {}
|
|
172
|
+
data["检索文章"] = [x for x in legacy if isinstance(x, dict)]
|
|
173
|
+
out["data"] = data
|
|
174
|
+
# 知识专库链接:MCP 用下划线 knowledge_base_url,渲染脚本只认驼峰
|
|
175
|
+
kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
|
|
176
|
+
if isinstance(kb, str) and kb.strip():
|
|
177
|
+
out["knowledgeBase"] = kb
|
|
178
|
+
out["knowledgeBaseUrl"] = kb
|
|
163
179
|
return out
|
|
164
180
|
|
|
165
181
|
|
|
166
182
|
def _normalize_deep(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
167
|
-
"""规范化深度搜索(deep_query
|
|
183
|
+
"""规范化深度搜索(deep_query)返回:materials / search_groups → data.list,
|
|
184
|
+
progress(字符串过程)保留,knowledge_base_url 映射驼峰。
|
|
185
|
+
深度搜索答案由 Agent 基于材料与 progress 综合形成,经 --answer-file 传入渲染。
|
|
186
|
+
"""
|
|
168
187
|
out = dict(payload)
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
188
|
+
items: List[Dict[str, Any]] = []
|
|
189
|
+
mats = payload.get("materials")
|
|
190
|
+
if isinstance(mats, list):
|
|
191
|
+
items.extend([m for m in mats if isinstance(m, dict)])
|
|
192
|
+
groups = payload.get("search_groups")
|
|
193
|
+
if isinstance(groups, list):
|
|
194
|
+
for g in groups:
|
|
195
|
+
if isinstance(g, dict) and isinstance(g.get("materials"), list):
|
|
196
|
+
items.extend([m for m in g["materials"] if isinstance(m, dict)])
|
|
197
|
+
elif isinstance(g, dict):
|
|
198
|
+
# search_groups 条目本身可能就是材料(含 title/url 等特征键)
|
|
199
|
+
if any(k in g for k in ("title", "url", "sourceUrl")):
|
|
200
|
+
items.append(g)
|
|
201
|
+
if items:
|
|
202
|
+
# 渲染脚本 extract_articles_from_deep 消费顶层 data.list
|
|
203
|
+
out["data"] = {"list": items}
|
|
204
|
+
# 兼容旧直连 events 形态的防御提取
|
|
205
|
+
if "data" not in out:
|
|
206
|
+
events = payload.get("events")
|
|
207
|
+
if isinstance(events, list):
|
|
208
|
+
out["events"] = events
|
|
209
|
+
kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
|
|
210
|
+
if isinstance(kb, str) and kb.strip():
|
|
211
|
+
out["knowledgeBase"] = kb
|
|
212
|
+
out["knowledgeBaseUrl"] = kb
|
|
182
213
|
return out
|
|
183
214
|
|
|
184
215
|
|
|
185
216
|
def detect_mode(payload: Dict[str, Any]) -> str:
|
|
186
|
-
"""
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
217
|
+
"""按 MCP 实测特征自动识别接口类型。
|
|
218
|
+
|
|
219
|
+
deep 的特征键(query_id/progress/search_groups/deep_query_meta)最特异,
|
|
220
|
+
必须先于 search 判断:deep 返回同样携带 materials 键,若先判 search
|
|
221
|
+
会被误判(materials 为空列表也是 list)。
|
|
222
|
+
"""
|
|
223
|
+
if (
|
|
224
|
+
"query_id" in payload
|
|
225
|
+
or isinstance(payload.get("progress"), list)
|
|
226
|
+
or isinstance(payload.get("search_groups"), list)
|
|
227
|
+
or isinstance(payload.get("deep_query_meta"), dict)
|
|
228
|
+
):
|
|
190
229
|
return "deep"
|
|
191
|
-
if
|
|
192
|
-
|
|
230
|
+
if isinstance(payload.get("search_meta"), dict) or (
|
|
231
|
+
isinstance(payload.get("materials"), list) and "answer" not in payload
|
|
232
|
+
):
|
|
233
|
+
return "search"
|
|
193
234
|
return "chat"
|
|
194
235
|
|
|
195
236
|
|
|
196
237
|
def main() -> int:
|
|
197
|
-
parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入
|
|
238
|
+
parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入 适配器(按 2026-08-19 实测 MCP 结构映射)")
|
|
198
239
|
parser.add_argument("input_json", help="MCP 工具返回 JSON 文件路径")
|
|
199
240
|
parser.add_argument("--output", "-o", required=True, help="规范化 JSON 输出路径")
|
|
200
241
|
parser.add_argument("--mode", choices=["chat", "search", "deep"], default=None, help="接口类型;缺省自动识别")
|
|
@@ -211,17 +252,14 @@ def main() -> int:
|
|
|
211
252
|
print(f"错误:输入不是合法 JSON:{e}", file=sys.stderr)
|
|
212
253
|
return 2
|
|
213
254
|
|
|
214
|
-
# 1) 提取 MCP
|
|
255
|
+
# 1) 提取 MCP 协议层 → 业务 JSON
|
|
215
256
|
text = _extract_mcp_text(raw)
|
|
216
257
|
payload = _try_json(text) if text else None
|
|
217
258
|
if not isinstance(payload, dict):
|
|
218
|
-
#
|
|
219
|
-
payload = {"
|
|
220
|
-
|
|
221
|
-
# 2) 展开包装层
|
|
222
|
-
payload = _unwrap_payload(payload)
|
|
259
|
+
# 纯文本回答(无业务 JSON)→ 包成 answer
|
|
260
|
+
payload = {"answer": text or json.dumps(raw, ensure_ascii=False)}
|
|
223
261
|
|
|
224
|
-
#
|
|
262
|
+
# 2) 按模式做字段映射
|
|
225
263
|
mode = args.mode or detect_mode(payload)
|
|
226
264
|
if mode == "search":
|
|
227
265
|
out = _normalize_search(payload)
|
|
@@ -9,7 +9,8 @@ SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
|
9
9
|
LOCAL_BLOCKLIST_PATH = SKILL_ROOT / "config" / "release_blocklist.txt"
|
|
10
10
|
SKIP_PARTS = {".git"}
|
|
11
11
|
SKIP_FILES = {"CHANGE_log.md", "release_blocklist.txt"}
|
|
12
|
-
BANNED_FILES = {"_meta.json", "config.ini", "config.ini.example", "environment_state.json", "user_profile.json"}
|
|
12
|
+
BANNED_FILES = {"_meta.json", "config.ini", "config.ini.example", "environment_state.json", "user_profile.json", "writing_preferences.json"}
|
|
13
|
+
BANNED_DIRS = {"knowledge-base"}
|
|
13
14
|
BANNED_ARTIFACT_NAMES = {".gitignore", ".gitkeep", ".DS_Store"}
|
|
14
15
|
BANNED_ARTIFACT_SUFFIXES = {".pyc", ".pyo"}
|
|
15
16
|
ALLOWED_API_KEY_VALUES = {"", "your_api_key_here", "你的深知搜索 API Key"}
|
|
@@ -48,8 +49,12 @@ def main():
|
|
|
48
49
|
if any(part == "__pycache__" for part in path.parts):
|
|
49
50
|
findings.append(f"{path.relative_to(SKILL_ROOT)}: 公开包不得包含 __pycache__")
|
|
50
51
|
continue
|
|
52
|
+
# 个人素材库与写作偏好是本机私有状态,绝不进入公开包。
|
|
53
|
+
if any(part in BANNED_DIRS for part in path.relative_to(SKILL_ROOT).parts):
|
|
54
|
+
findings.append(f"{path.relative_to(SKILL_ROOT)}: 公开包不得包含个人素材库等本机私有数据")
|
|
55
|
+
continue
|
|
51
56
|
if path.is_file() and path.name in BANNED_FILES:
|
|
52
|
-
findings.append(f"{path.relative_to(SKILL_ROOT)}:
|
|
57
|
+
findings.append(f"{path.relative_to(SKILL_ROOT)}: 公开包不得包含真实配置文件或本机私有状态")
|
|
53
58
|
continue
|
|
54
59
|
if not path.is_file() or path.name in SKIP_FILES or any(part in SKIP_PARTS for part in path.parts):
|
|
55
60
|
continue
|
|
@@ -33,7 +33,13 @@ QUERY_TOO_SHORT_ERROR = f"错误:查询关键词过短,最少需要 {MIN_QUE
|
|
|
33
33
|
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
34
34
|
# 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 skill 目录(SkillHub 兼容)
|
|
35
35
|
import os as _os
|
|
36
|
-
|
|
36
|
+
_ws = _os.environ.get("DKNWOC_WS_ROOT")
|
|
37
|
+
if not _ws:
|
|
38
|
+
# dsh 会话隔离:每会话独立产物目录 <工作区>/dknowc-output/<会话ID前8位>/,
|
|
39
|
+
# 多会话共用同一工作区时互不混杂;非 dsh 环境回退为工作区本身。
|
|
40
|
+
_sid = _os.environ.get("DSH_SESSION_ID", "")
|
|
41
|
+
_ws = str(Path(_os.getcwd()) / "dknowc-output" / (_sid[:8] if _sid else "_default"))
|
|
42
|
+
WS_ROOT = Path(_ws).resolve()
|
|
37
43
|
|
|
38
44
|
API_KEY_ENV = "DKNOWC_API_KEY"
|
|
39
45
|
DEFAULT_BASE_URL = "https://open.dknowc.cn/dependable/search/"
|
|
@@ -79,7 +85,7 @@ def resolve_output_json(output_path: str) -> Path:
|
|
|
79
85
|
elif raw_path.parent == Path("."):
|
|
80
86
|
resolved = (SEARCH_RESULTS_DIR / raw_path.name).resolve()
|
|
81
87
|
else:
|
|
82
|
-
resolved =
|
|
88
|
+
resolved = raw_path.resolve()
|
|
83
89
|
|
|
84
90
|
if resolved.suffix.lower() != ".json":
|
|
85
91
|
resolved = resolved.with_suffix(".json")
|
|
@@ -132,7 +132,13 @@ DEFAULT_OUTPUT_DIR = "official-docs/output"
|
|
|
132
132
|
CONFIG_PATH = os.path.join(os.path.dirname(__file__), '..', 'config', 'format.json')
|
|
133
133
|
SKILL_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
|
|
134
134
|
# 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 skill 目录
|
|
135
|
-
|
|
135
|
+
_ws = os.environ.get("DKNWOC_WS_ROOT")
|
|
136
|
+
if not _ws:
|
|
137
|
+
# dsh 会话隔离:每会话独立产物目录 <工作区>/dknowc-output/<会话ID前8位>/,
|
|
138
|
+
# 多会话共用同一工作区时互不混杂;非 dsh 环境回退为工作区本身。
|
|
139
|
+
_sid = os.environ.get("DSH_SESSION_ID", "")
|
|
140
|
+
_ws = os.path.join(os.getcwd(), "dknowc-output", (_sid[:8] if _sid else "_default"))
|
|
141
|
+
WS_ROOT = os.path.abspath(_ws)
|
|
136
142
|
|
|
137
143
|
OFFICIAL_DOCS_DIR = os.path.join(WS_ROOT, "official-docs")
|
|
138
144
|
INPUT_DIR = os.path.join(OFFICIAL_DOCS_DIR, "input")
|
|
@@ -163,7 +169,7 @@ def get_skill_root():
|
|
|
163
169
|
|
|
164
170
|
|
|
165
171
|
def get_configured_output_dir():
|
|
166
|
-
"""获取 Word
|
|
172
|
+
"""获取 Word 输出目录:相对路径基于会话工作区(WS_ROOT)解析,不依赖 skill 安装目录。"""
|
|
167
173
|
configured_dir = None
|
|
168
174
|
if FORMAT_CONFIG:
|
|
169
175
|
output_config = FORMAT_CONFIG.get('output', {})
|
|
@@ -172,10 +178,10 @@ def get_configured_output_dir():
|
|
|
172
178
|
|
|
173
179
|
output_dir = os.path.expanduser(configured_dir or DEFAULT_OUTPUT_DIR)
|
|
174
180
|
if not os.path.isabs(output_dir):
|
|
175
|
-
output_dir = os.path.join(
|
|
181
|
+
output_dir = os.path.join(WS_ROOT, output_dir)
|
|
176
182
|
output_dir = os.path.abspath(output_dir)
|
|
177
|
-
if not is_path_within(output_dir, os.path.abspath(os.path.join(
|
|
178
|
-
raise ValueError(f"输出目录必须位于 {os.path.join(
|
|
183
|
+
if not is_path_within(output_dir, os.path.abspath(os.path.join(WS_ROOT, DEFAULT_OUTPUT_DIR))):
|
|
184
|
+
raise ValueError(f"输出目录必须位于 {os.path.join(WS_ROOT, DEFAULT_OUTPUT_DIR)} 内")
|
|
179
185
|
return output_dir
|
|
180
186
|
|
|
181
187
|
|
|
@@ -195,7 +201,7 @@ def resolve_input_text_path(input_path):
|
|
|
195
201
|
elif raw_path == os.path.basename(raw_path):
|
|
196
202
|
resolved = os.path.abspath(os.path.join(INPUT_DIR, raw_path))
|
|
197
203
|
else:
|
|
198
|
-
resolved = os.path.abspath(
|
|
204
|
+
resolved = os.path.abspath(raw_path)
|
|
199
205
|
|
|
200
206
|
allowed_dirs = [
|
|
201
207
|
os.path.abspath(INPUT_DIR),
|
|
@@ -220,7 +226,7 @@ def resolve_output_path(output_path):
|
|
|
220
226
|
elif output_path == os.path.basename(output_path):
|
|
221
227
|
resolved = os.path.abspath(os.path.join(output_dir, output_path))
|
|
222
228
|
else:
|
|
223
|
-
resolved = os.path.abspath(os.path.join(
|
|
229
|
+
resolved = os.path.abspath(os.path.join(WS_ROOT, output_path))
|
|
224
230
|
if not is_path_within(resolved, output_dir):
|
|
225
231
|
raise ValueError(f"输出文件必须位于 Word 输出目录内: {output_dir}")
|
|
226
232
|
return resolved
|
|
@@ -230,7 +236,7 @@ def display_path(path):
|
|
|
230
236
|
"""将 Skill 内文件路径转换为面向用户的相对路径。"""
|
|
231
237
|
resolved = os.path.abspath(os.path.expanduser(str(path)))
|
|
232
238
|
try:
|
|
233
|
-
return os.path.relpath(resolved,
|
|
239
|
+
return os.path.relpath(resolved, WS_ROOT)
|
|
234
240
|
except ValueError:
|
|
235
241
|
return resolved
|
|
236
242
|
|
|
@@ -15,6 +15,9 @@ API_KEY_ENV = "DKNOWC_API_KEY"
|
|
|
15
15
|
PROFILE_PATH = SKILL_ROOT / "config" / "user_profile.json"
|
|
16
16
|
ENV_STATE_PATH = SKILL_ROOT / "config" / "environment_state.json"
|
|
17
17
|
SCRIPTS_DIR = SKILL_ROOT / "scripts"
|
|
18
|
+
# 个人素材库与写作偏好的持久数据根(与 local_memory.py 一致)
|
|
19
|
+
import os as _os
|
|
20
|
+
DATA_ROOT = Path(_os.environ.get("DKNWOC_HOME_DIR") or str(Path.home() / ".dknowc-writer")).resolve()
|
|
18
21
|
sys.path.insert(0, str(SCRIPTS_DIR))
|
|
19
22
|
|
|
20
23
|
|
|
@@ -41,6 +44,8 @@ def check_environment():
|
|
|
41
44
|
python_docx_available = _module_available("docx")
|
|
42
45
|
requests_available = _module_available("requests")
|
|
43
46
|
config_status = check_api_key_config()
|
|
47
|
+
kb_count = _count_kb_materials()
|
|
48
|
+
pref_count = _count_writing_preferences()
|
|
44
49
|
blocking_issues = []
|
|
45
50
|
if not python3_available:
|
|
46
51
|
blocking_issues.append("python3_missing")
|
|
@@ -74,6 +79,13 @@ def check_environment():
|
|
|
74
79
|
"blocking_issues": blocking_issues,
|
|
75
80
|
"ready": not blocking_issues,
|
|
76
81
|
"search_ready_note": None if config_status["api_key_configured"] else "仅需要搜索的任务需先完成 MaaS 注册获取 API Key 并写入环境变量;无需搜索的任务可先直接写作。",
|
|
82
|
+
"local_memory": {
|
|
83
|
+
"knowledge_base_materials": kb_count,
|
|
84
|
+
"knowledge_base_dir": "knowledge-base/",
|
|
85
|
+
"writing_preferences_count": pref_count,
|
|
86
|
+
"preferences_path": "config/writing_preferences.json",
|
|
87
|
+
"note": "个人素材库与写作偏好仅保存在本机,不随公开包分发;大于 0 时写作任务应先检索素材库并应用偏好。",
|
|
88
|
+
},
|
|
77
89
|
"dependency_install_prompt_needed": bool(dependency_issues) and not state.get("dependency_install_declined"),
|
|
78
90
|
"install_hint": "经用户同意后,可执行 python3 -m pip install python-docx requests" if dependency_issues else None,
|
|
79
91
|
"maas_platform_url": "https://platform.dknowc.cn/",
|
|
@@ -83,6 +95,28 @@ def check_environment():
|
|
|
83
95
|
}
|
|
84
96
|
|
|
85
97
|
|
|
98
|
+
def _count_kb_materials():
|
|
99
|
+
index_path = DATA_ROOT / "knowledge-base" / "_index.json"
|
|
100
|
+
try:
|
|
101
|
+
data = json.loads(index_path.read_text(encoding="utf-8"))
|
|
102
|
+
except (OSError, json.JSONDecodeError):
|
|
103
|
+
return 0
|
|
104
|
+
if isinstance(data, dict) and isinstance(data.get("items"), list):
|
|
105
|
+
return len(data["items"])
|
|
106
|
+
return 0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _count_writing_preferences():
|
|
110
|
+
pref_path = DATA_ROOT / "config" / "writing_preferences.json"
|
|
111
|
+
try:
|
|
112
|
+
data = json.loads(pref_path.read_text(encoding="utf-8"))
|
|
113
|
+
except (OSError, json.JSONDecodeError):
|
|
114
|
+
return 0
|
|
115
|
+
if not isinstance(data, dict):
|
|
116
|
+
return 0
|
|
117
|
+
return sum(len(v) for v in data.values() if isinstance(v, list))
|
|
118
|
+
|
|
119
|
+
|
|
86
120
|
def _module_available(module_name):
|
|
87
121
|
try:
|
|
88
122
|
__import__(module_name)
|
|
@@ -96,16 +130,14 @@ def _in_dsh() -> bool:
|
|
|
96
130
|
|
|
97
131
|
dsh 场景下,脚本子进程无法隐式继承 DKNOWC_API_KEY(dsh 安全机制会清理
|
|
98
132
|
名字含 KEY 的环境变量),但 dsh 插件会通过 shell-env 显式通道把该 Key
|
|
99
|
-
注入为 DSH_DKNOWC_API_KEY
|
|
100
|
-
|
|
101
|
-
无 Key 时仅暂停搜索,不阻断纯写作。
|
|
133
|
+
注入为 DSH_DKNOWC_API_KEY。搜索子能力走 MCP 转接,无 Key 时仅暂停
|
|
134
|
+
搜索,不阻断纯写作。
|
|
102
135
|
"""
|
|
103
136
|
return os.environ.get("DSH_SHELL") == "1"
|
|
104
137
|
|
|
105
138
|
|
|
106
139
|
def check_api_key_config():
|
|
107
140
|
if _in_dsh():
|
|
108
|
-
# dsh 场景:读取插件注入的 DSH_DKNOWC_API_KEY(来源为 dsh 主进程的 DKNOWC_API_KEY)
|
|
109
141
|
api_key = os.environ.get("DSH_DKNOWC_API_KEY", "").strip()
|
|
110
142
|
if _valid_api_key(api_key):
|
|
111
143
|
return {
|