dknowc-dsh 1.0.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 (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -0
  3. package/cordis.patch.yml +17 -0
  4. package/package.json +33 -0
  5. package/skills/dknowc-official-doc-writer/README.md +156 -0
  6. package/skills/dknowc-official-doc-writer/SKILL.md +462 -0
  7. package/skills/dknowc-official-doc-writer/config/format.json +101 -0
  8. package/skills/dknowc-official-doc-writer/config/user_profile.json.example +6 -0
  9. package/skills/dknowc-official-doc-writer/official-docs/input/mcp_intro_content.md +61 -0
  10. package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +113 -0
  11. package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +62 -0
  12. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +138 -0
  13. package/skills/dknowc-official-doc-writer/reference/output_guide.md +288 -0
  14. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +156 -0
  15. package/skills/dknowc-official-doc-writer/reference/search_guide.md +317 -0
  16. package/skills/dknowc-official-doc-writer/reference/search_intro.md +15 -0
  17. package/skills/dknowc-official-doc-writer/reference/search_policy.md +284 -0
  18. package/skills/dknowc-official-doc-writer/reference/standards/00_index.md +151 -0
  19. package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +51 -0
  20. package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +53 -0
  21. package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +48 -0
  22. package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +51 -0
  23. package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +55 -0
  24. package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +81 -0
  25. package/skills/dknowc-official-doc-writer/reference/standards/07_minutes.md +46 -0
  26. package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +53 -0
  27. package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +45 -0
  28. package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +44 -0
  29. package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +46 -0
  30. package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +46 -0
  31. package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +46 -0
  32. package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +41 -0
  33. package/skills/dknowc-official-doc-writer/reference/standards/15_business_docs.md +47 -0
  34. package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +47 -0
  35. package/skills/dknowc-official-doc-writer/reference/standards/17_resolution.md +45 -0
  36. package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +44 -0
  37. package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +45 -0
  38. package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +45 -0
  39. package/skills/dknowc-official-doc-writer/reference/standards/21_explanation.md +40 -0
  40. package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +47 -0
  41. package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +46 -0
  42. package/skills/dknowc-official-doc-writer/reference/standards/24_procurement.md +40 -0
  43. package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +42 -0
  44. package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +42 -0
  45. package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +43 -0
  46. package/skills/dknowc-official-doc-writer/reference/standards/28_rules.md +40 -0
  47. package/skills/dknowc-official-doc-writer/reference/standards/29_research.md +42 -0
  48. package/skills/dknowc-official-doc-writer/reference/standards/30_feasibility.md +42 -0
  49. package/skills/dknowc-official-doc-writer/reference/standards/31_review_material.md +40 -0
  50. package/skills/dknowc-official-doc-writer/reference/standards/32_ai_compute.md +41 -0
  51. package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +569 -0
  52. package/skills/dknowc-official-doc-writer/reference/task_router.md +119 -0
  53. package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +241 -0
  54. package/skills/dknowc-official-doc-writer/scripts/check_release.py +78 -0
  55. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +575 -0
  56. package/skills/dknowc-official-doc-writer/scripts/format_document.py +1756 -0
  57. package/skills/dknowc-official-doc-writer/scripts/initialize.py +178 -0
  58. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +158 -0
  59. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +223 -0
  60. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +202 -0
  61. package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +242 -0
  62. package/skills/dknowc-official-doc-writer/scripts/register.mjs +218 -0
  63. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +966 -0
  64. package/skills/dknowc-official-doc-writer/scripts/review_document.py +127 -0
  65. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +180 -0
  66. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +975 -0
  67. package/skills/dknowc-trusted-consulting/README.md +63 -0
  68. package/skills/dknowc-trusted-consulting/SKILL.md +172 -0
  69. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +241 -0
  70. package/skills/dknowc-trusted-consulting/scripts/check_release.py +66 -0
  71. package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +475 -0
  72. package/skills/dknowc-trusted-consulting/scripts/initialize.py +89 -0
  73. package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +158 -0
  74. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +181 -0
  75. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +990 -0
  76. package/skills/dknowc-trusted-search/README.md +63 -0
  77. package/skills/dknowc-trusted-search/SKILL.md +232 -0
  78. package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
  79. package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
  80. package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +241 -0
  81. package/skills/dknowc-trusted-search/scripts/check_release.py +79 -0
  82. package/skills/dknowc-trusted-search/scripts/deep_query.py +266 -0
  83. package/skills/dknowc-trusted-search/scripts/initialize.py +89 -0
  84. package/skills/dknowc-trusted-search/scripts/mcp_direct.py +158 -0
  85. package/skills/dknowc-trusted-search/scripts/register_key.mjs +181 -0
  86. package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +889 -0
  87. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1011 -0
  88. package/skills/dknowc-trusted-search/scripts/trusted_search.py +325 -0
  89. package/src/index.js +103 -0
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env python3
2
+ """深知 dsh —— MCP 临时直连客户端。
3
+
4
+ dsh 场景下,MCP Bearer 认证在会话启动时从环境变量冻结,注册后拿到的新
5
+ API Key 无法热注入到已运行的 mcp-client。本脚本作为"临时 Key 通道":
6
+ 用 `DKNOWC_API_KEY=<临时Key> python3 mcp_direct.py ...` 前缀赋值方式,
7
+ 把临时 Key 直接传给脚本(绕过 dsh 的环境清理),通过 HTTP 直调深知可信
8
+ 工作台 MCP server 的 tools/call,输出与 dsh mcp-client 一致的 MCP 返回
9
+ 结构,后续照常走 adapt_mcp_result.py → render_trace_html.py 链路。
10
+
11
+ 用法:
12
+ DKNOWC_API_KEY=<key> python3 mcp_direct.py <tool> '<json-args>' [--output <out.json>] [--timeout 120]
13
+
14
+ 示例:
15
+ DKNOWC_API_KEY=sk-xxx python3 mcp_direct.py credible_chat \
16
+ '{"query": "深圳公积金租房提取需要哪些材料?", "area": "深圳"}' \
17
+ --output official-docs/search-results/dknowc_mcp_raw.json
18
+
19
+ 注意:
20
+ - API Key 只通过环境变量 DKNOWC_API_KEY 传入(bash 前缀赋值),不得作为命令行参数
21
+ - 不打印完整 Key,不持久化 Key
22
+ - 输出为 MCP 协议结构 {"content":[{"type":"text","text":"<接口JSON>"}]}
23
+ """
24
+
25
+ import argparse
26
+ import json
27
+ import os
28
+ import sys
29
+ import urllib.error
30
+ import urllib.request
31
+ from typing import Any, Dict, Optional
32
+
33
+ DEFAULT_ENDPOINT = "https://mcp.dknowc.cn/s6/mcp/"
34
+ PROTOCOL_VERSION = "2025-03-26"
35
+ API_KEY_ENV = "DKNOWC_API_KEY"
36
+
37
+
38
+ def _post(endpoint: str, api_key: str, payload: Dict[str, Any], session_id: Optional[str], timeout: int) -> tuple[int, str, Optional[str]]:
39
+ """POST 一次 JSON-RPC,返回 (http_code, body, 新 session_id)。"""
40
+ headers = {
41
+ "Content-Type": "application/json",
42
+ "Accept": "application/json, text/event-stream",
43
+ "Authorization": f"Bearer {api_key}",
44
+ }
45
+ if session_id:
46
+ headers["Mcp-Session-Id"] = session_id
47
+ req = urllib.request.Request(endpoint, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers=headers, method="POST")
48
+ try:
49
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
50
+ body = resp.read().decode("utf-8", errors="replace")
51
+ new_session = resp.headers.get("Mcp-Session-Id")
52
+ return resp.status, body, new_session
53
+ except urllib.error.HTTPError as e:
54
+ body = e.read().decode("utf-8", errors="replace")
55
+ return e.code, body, e.headers.get("Mcp-Session-Id")
56
+ except urllib.error.URLError as e:
57
+ raise RuntimeError(f"MCP 连接失败: {e.reason}")
58
+
59
+
60
+ def _call_tool(api_key: str, tool: str, arguments: Dict[str, Any], endpoint: str, timeout: int) -> Dict[str, Any]:
61
+ """initialize → tools/call,返回 MCP 标准结果。"""
62
+ # 1. initialize 建立会话
63
+ status, body, session_id = _post(endpoint, api_key, {
64
+ "jsonrpc": "2.0",
65
+ "id": 1,
66
+ "method": "initialize",
67
+ "params": {
68
+ "protocolVersion": PROTOCOL_VERSION,
69
+ "capabilities": {},
70
+ "clientInfo": {"name": "dknowc-dsh-mcp-direct", "version": "1.0.0"},
71
+ },
72
+ }, None, timeout)
73
+ if status not in (200, 202):
74
+ raise RuntimeError(f"MCP initialize 失败 (HTTP {status}): {body[:300]}")
75
+ # session_id 若未在响应头返回,尝试从 JSON 里读;无则沿用
76
+ if not session_id:
77
+ try:
78
+ init = json.loads(body)
79
+ sid = init.get("result", {}).get("_meta", {}).get("sessionId")
80
+ if isinstance(sid, str) and sid:
81
+ session_id = sid
82
+ except json.JSONDecodeError:
83
+ pass
84
+
85
+ # 2. tools/call
86
+ status, body, _ = _post(endpoint, api_key, {
87
+ "jsonrpc": "2.0",
88
+ "id": 2,
89
+ "method": "tools/call",
90
+ "params": {"name": tool, "arguments": arguments},
91
+ }, session_id, timeout)
92
+ if status not in (200, 202):
93
+ raise RuntimeError(f"MCP tools/call 失败 (HTTP {status}): {body[:300]}")
94
+
95
+ # 解析返回;streamable-http 可能是 SSE 或 JSON
96
+ text = body.strip()
97
+ # 若为 SSE 多行,取 data: 行拼接
98
+ if text.startswith("event:") or "\ndata:" in text:
99
+ chunks = []
100
+ for line in text.splitlines():
101
+ line = line.strip()
102
+ if line.startswith("data:"):
103
+ chunks.append(line[5:].strip())
104
+ text = "\n".join(chunks)
105
+ try:
106
+ return json.loads(text)
107
+ except json.JSONDecodeError:
108
+ # 不是标准 JSON,包成 MCP content
109
+ return {"content": [{"type": "text", "text": text}], "isError": False}
110
+
111
+
112
+ def main() -> int:
113
+ parser = argparse.ArgumentParser(description="MCP 临时直连客户端(注册后临时 Key 通道)")
114
+ parser.add_argument("tool", help="MCP 工具名:credible_chat / trusted_search / deep_query")
115
+ parser.add_argument("args_json", help="工具参数 JSON 字符串")
116
+ parser.add_argument("--output", "-o", help="输出 JSON 文件路径(保存 MCP 原始返回)")
117
+ parser.add_argument("--endpoint", default=None, help="MCP 端点,默认 https://mcp.dknowc.cn/s6/mcp/")
118
+ parser.add_argument("--timeout", type=int, default=120, help="请求超时秒数,deep_query 建议更大")
119
+ args = parser.parse_args()
120
+
121
+ api_key = os.environ.get(API_KEY_ENV, "").strip()
122
+ if not api_key:
123
+ print(f"错误:缺少环境变量 {API_KEY_ENV}(请用 DKNOWC_API_KEY=<key> 前缀赋值方式传入)。", file=sys.stderr)
124
+ return 2
125
+
126
+ try:
127
+ arguments = json.loads(args.args_json)
128
+ if not isinstance(arguments, dict):
129
+ raise ValueError("参数必须是 JSON 对象")
130
+ except (json.JSONDecodeError, ValueError) as e:
131
+ print(f"错误:参数不是合法 JSON 对象:{e}", file=sys.stderr)
132
+ return 2
133
+
134
+ endpoint = args.endpoint or DEFAULT_ENDPOINT
135
+ try:
136
+ result = _call_tool(api_key, args.tool, arguments, endpoint, args.timeout)
137
+ except RuntimeError as e:
138
+ print(f"错误:{e}", file=sys.stderr)
139
+ return 1
140
+
141
+ raw_json = json.dumps(result, ensure_ascii=False, indent=2)
142
+ if args.output:
143
+ out_path = os.path.abspath(args.output)
144
+ os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
145
+ with open(out_path, "w", encoding="utf-8") as f:
146
+ f.write(raw_json)
147
+ print(f"已保存 MCP 返回:{out_path}")
148
+ else:
149
+ print(raw_json)
150
+
151
+ # 若工具返回 isError 或内嵌业务错误码,非零退出以提示
152
+ if result.get("isError"):
153
+ return 1
154
+ return 0
155
+
156
+
157
+ if __name__ == "__main__":
158
+ sys.exit(main())
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env node
2
+ // MaaS key bootstrap helper for dsh distribution.
3
+ // It only requests/returns a key for the current task and never writes local files.
4
+ // node register_key.mjs send --phone <phone>
5
+ // node register_key.mjs register --phone <phone> --vcode <code> [--new-key]
6
+
7
+ const DEFAULT_BASE = "https://platform.dknowc.cn/auth/home/userAuto";
8
+ const DEFAULT_OPEN_BASE = "https://open.dknowc.cn";
9
+ const DEFAULT_CHANNEL = "46A3BA1D-3E1A-4E8C-BD50-A6DCBEE1DB05";
10
+ const DEFAULT_TYPE = "11";
11
+ const DEFAULT_SOURCE = "agent";
12
+ const API_KEY_ENV = "DKNOWC_API_KEY";
13
+ const MAAS_PLATFORM_URL = "https://platform.dknowc.cn/";
14
+
15
+ function parseArgs(argv) {
16
+ const out = { _: [] };
17
+ for (let i = 0; i < argv.length; i++) {
18
+ const arg = argv[i];
19
+ if (arg.startsWith("--")) {
20
+ const key = arg.slice(2);
21
+ const next = argv[i + 1];
22
+ if (next === undefined || next.startsWith("--")) {
23
+ out[key] = true;
24
+ } else {
25
+ out[key] = next;
26
+ i++;
27
+ }
28
+ } else {
29
+ out._.push(arg);
30
+ }
31
+ }
32
+ return out;
33
+ }
34
+
35
+ async function postJson(url, payload, headers = {}) {
36
+ const controller = new AbortController();
37
+ const timer = setTimeout(() => controller.abort(), 30000);
38
+ try {
39
+ const response = await fetch(url, {
40
+ method: "POST",
41
+ headers: { "Content-Type": "application/json", ...headers },
42
+ body: JSON.stringify(payload),
43
+ signal: controller.signal,
44
+ });
45
+ const text = await response.text();
46
+ try {
47
+ return JSON.parse(text);
48
+ } catch {
49
+ return { status: false, msg: `非 JSON 响应:${text.slice(0, 200)}` };
50
+ }
51
+ } catch (error) {
52
+ const msg = error && error.message ? error.message : String(error);
53
+ return { status: false, msg: `请求异常:${msg}` };
54
+ } finally {
55
+ clearTimeout(timer);
56
+ }
57
+ }
58
+
59
+ function genPassword() {
60
+ const pools = [
61
+ "ABCDEFGHJKLMNPQRSTUVWXYZ",
62
+ "abcdefghijkmnpqrstuvwxyz",
63
+ "23456789",
64
+ "!@#$%^&*",
65
+ ];
66
+ const pick = (value) => value[Math.floor(Math.random() * value.length)];
67
+ const chars = pools.map(pick);
68
+ const all = pools.join("");
69
+ for (let i = 0; i < 8; i++) chars.push(pick(all));
70
+ for (let i = chars.length - 1; i > 0; i--) {
71
+ const j = Math.floor(Math.random() * (i + 1));
72
+ [chars[i], chars[j]] = [chars[j], chars[i]];
73
+ }
74
+ return chars.join("");
75
+ }
76
+
77
+ async function createNewApiKey(openBase, existingApiKey, name, remark) {
78
+ const url = `${openBase.replace(/\/$/, "")}/open-api/maas/api-key/create`;
79
+ const result = await postJson(
80
+ url,
81
+ { name, remark },
82
+ { Authorization: `Bearer ${existingApiKey}` },
83
+ );
84
+ const apiKey = result && result.data ? result.data.appKey : "";
85
+ return { result, apiKey };
86
+ }
87
+
88
+ function maskKey(apiKey) {
89
+ if (!apiKey) return null;
90
+ if (apiKey.length <= 12) return "***";
91
+ return `${apiKey.slice(0, 7)}...${apiKey.slice(-4)}`;
92
+ }
93
+
94
+ async function main() {
95
+ const args = parseArgs(process.argv.slice(2));
96
+ const cmd = args._[0];
97
+ const base = args.base || DEFAULT_BASE;
98
+
99
+ if (cmd === "send") {
100
+ if (!args.phone) {
101
+ console.error("缺少 --phone");
102
+ process.exit(2);
103
+ }
104
+ const result = await postJson(`${base}/sendMessage`, {
105
+ phone: args.phone,
106
+ type: "register",
107
+ });
108
+ console.log(JSON.stringify(result));
109
+ process.exit(result.status ? 0 : 1);
110
+ }
111
+
112
+ if (cmd === "register") {
113
+ if (!args.phone || !args.vcode) {
114
+ console.error("缺少 --phone 或 --vcode");
115
+ process.exit(2);
116
+ }
117
+
118
+ const payload = {
119
+ phone: args.phone,
120
+ vcode: args.vcode,
121
+ password: args.password && args.password !== true ? args.password : genPassword(),
122
+ type: args.type && args.type !== true ? args.type : DEFAULT_TYPE,
123
+ organ: args.organ && args.organ !== true ? args.organ : "个人",
124
+ name: args.name && args.name !== true ? args.name : "用户",
125
+ apiKeyName: args["apikey-name"] && args["apikey-name"] !== true ? args["apikey-name"] : "agent-key",
126
+ channel: args.channel && args.channel !== true ? args.channel : DEFAULT_CHANNEL,
127
+ source: args.source && args.source !== true ? args.source : DEFAULT_SOURCE,
128
+ };
129
+
130
+ const result = await postJson(`${base}/register`, payload);
131
+ const data = result.data || {};
132
+ let apiKey = result.status && data.apiKey ? data.apiKey : "";
133
+ let newKeyCreated = false;
134
+ let newKeyError = null;
135
+
136
+ if (apiKey && args["new-key"]) {
137
+ const keyName = args["new-key-name"] && args["new-key-name"] !== true
138
+ ? args["new-key-name"]
139
+ : payload.apiKeyName;
140
+ const keyRemark = args["new-key-remark"] && args["new-key-remark"] !== true
141
+ ? args["new-key-remark"]
142
+ : "由 SkillHub 深知可信咨询按用户要求重新生成";
143
+ const created = await createNewApiKey(
144
+ args["open-base"] && args["open-base"] !== true ? args["open-base"] : DEFAULT_OPEN_BASE,
145
+ apiKey,
146
+ keyName,
147
+ keyRemark,
148
+ );
149
+ if (created.apiKey) {
150
+ apiKey = created.apiKey;
151
+ newKeyCreated = true;
152
+ } else {
153
+ apiKey = "";
154
+ newKeyError = created.result.errmsg || created.result.msg || "新 API Key 创建失败";
155
+ }
156
+ }
157
+
158
+ console.log(JSON.stringify({
159
+ status: Boolean(apiKey) && !newKeyError,
160
+ msg: result.msg,
161
+ url: data.url || null,
162
+ existed: Boolean(data.existed),
163
+ keyCreatedByRegister: Boolean(data.keyCreated),
164
+ newKeyRequested: Boolean(args["new-key"]),
165
+ newKeyCreated,
166
+ envName: API_KEY_ENV,
167
+ apiKey,
168
+ apiKeyMasked: maskKey(apiKey),
169
+ currentTaskOnly: true,
170
+ persistInstruction: `本次返回的 apiKey 仅供当前任务临时注入 ${API_KEY_ENV}。任务完成后,建议用户在 SkillHub/WorkBuddy 平台环境变量或密钥配置中保存 ${API_KEY_ENV}。`,
171
+ fallbackRegisterUrl: MAAS_PLATFORM_URL,
172
+ newKeyError,
173
+ }));
174
+ process.exit(apiKey && !newKeyError ? 0 : 1);
175
+ }
176
+
177
+ console.error("用法: node register_key.mjs <send|register> ...");
178
+ process.exit(2);
179
+ }
180
+
181
+ main();