dknowc-dsh 1.3.0 → 2.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 (86) hide show
  1. package/README.md +20 -19
  2. package/package.json +4 -4
  3. package/skills/dknowc-official-doc-writer/README.md +18 -16
  4. package/skills/dknowc-official-doc-writer/SKILL.md +112 -123
  5. package/skills/dknowc-official-doc-writer/attribution.json +5 -0
  6. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +5 -0
  7. package/skills/dknowc-official-doc-writer/reference/onboarding_scripts.md +18 -8
  8. package/skills/dknowc-official-doc-writer/reference/output_guide.md +2 -2
  9. package/skills/dknowc-official-doc-writer/reference/research_notes.md +34 -0
  10. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +2 -9
  11. package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +922 -270
  12. package/skills/dknowc-official-doc-writer/reference/search_guide.md +123 -28
  13. package/skills/dknowc-official-doc-writer/reference/search_intro.md +6 -6
  14. package/skills/dknowc-official-doc-writer/reference/search_policy.md +88 -53
  15. package/skills/dknowc-official-doc-writer/reference/task_router.md +6 -6
  16. package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +52 -2
  17. package/skills/dknowc-official-doc-writer/scripts/api_key.py +41 -14
  18. package/skills/dknowc-official-doc-writer/scripts/attribution.py +60 -0
  19. package/skills/dknowc-official-doc-writer/scripts/build_trace_json.py +288 -0
  20. package/skills/dknowc-official-doc-writer/scripts/check_materials.py +265 -0
  21. package/skills/dknowc-official-doc-writer/scripts/deep_convert.py +235 -0
  22. package/skills/dknowc-official-doc-writer/scripts/deep_query.py +333 -0
  23. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +22 -5
  24. package/skills/dknowc-official-doc-writer/scripts/extract_reference.py +245 -0
  25. package/skills/dknowc-official-doc-writer/scripts/format_document.py +106 -18
  26. package/skills/dknowc-official-doc-writer/scripts/initialize.py +15 -17
  27. package/skills/dknowc-official-doc-writer/scripts/mcp_convert.py +272 -0
  28. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +257 -143
  29. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +72 -8
  30. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +14 -4
  31. package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +6 -1
  32. package/skills/dknowc-official-doc-writer/scripts/register.mjs +120 -48
  33. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +1514 -660
  34. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +151 -6
  35. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +13 -0
  36. package/skills/dknowc-ppt-assistant/README.md +14 -10
  37. package/skills/dknowc-ppt-assistant/SKILL.md +33 -15
  38. package/skills/dknowc-ppt-assistant/attribution.json +5 -0
  39. package/skills/dknowc-ppt-assistant/references/material_usage.md +9 -5
  40. package/skills/dknowc-ppt-assistant/references/onboarding_scripts.md +14 -2
  41. package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +1343 -292
  42. package/skills/dknowc-ppt-assistant/references/search_intro.md +1 -1
  43. package/skills/dknowc-ppt-assistant/scripts/api_key.py +41 -14
  44. package/skills/dknowc-ppt-assistant/scripts/attribution.py +60 -0
  45. package/skills/dknowc-ppt-assistant/scripts/initialize.py +9 -17
  46. package/skills/dknowc-ppt-assistant/scripts/mcp_convert.py +188 -0
  47. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +135 -6
  48. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1539 -714
  49. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +33 -3
  50. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +17 -19
  51. package/skills/dknowc-trusted-search/README.md +27 -22
  52. package/skills/dknowc-trusted-search/SKILL.md +213 -140
  53. package/skills/dknowc-trusted-search/attribution.json +5 -0
  54. package/skills/dknowc-trusted-search/reference/onboarding_scripts.md +17 -7
  55. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +720 -253
  56. package/skills/dknowc-trusted-search/scripts/api_key.py +41 -14
  57. package/skills/dknowc-trusted-search/scripts/attribution.py +61 -0
  58. package/skills/dknowc-trusted-search/scripts/chart_embed.py +350 -0
  59. package/skills/dknowc-trusted-search/scripts/deep_query.py +26 -5
  60. package/skills/dknowc-trusted-search/scripts/initialize.py +20 -29
  61. package/skills/dknowc-trusted-search/scripts/mcp_convert.py +189 -0
  62. package/skills/dknowc-trusted-search/scripts/merge_search_results.py +272 -0
  63. package/skills/dknowc-trusted-search/scripts/register_key.mjs +149 -43
  64. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1860 -751
  65. package/skills/dknowc-trusted-search/scripts/trusted_search.py +34 -31
  66. package/src/index.js +3 -8
  67. package/skills/dknowc-official-doc-writer/scripts/check_release.py +0 -93
  68. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +0 -279
  69. package/skills/dknowc-ppt-assistant/scripts/check_release.py +0 -106
  70. package/skills/dknowc-trusted-consulting/README.md +0 -63
  71. package/skills/dknowc-trusted-consulting/SKILL.md +0 -236
  72. package/skills/dknowc-trusted-consulting/reference/consult_intro.md +0 -47
  73. package/skills/dknowc-trusted-consulting/reference/onboarding_scripts.md +0 -132
  74. package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +0 -31
  75. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +0 -502
  76. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +0 -283
  77. package/skills/dknowc-trusted-consulting/scripts/api_key.py +0 -41
  78. package/skills/dknowc-trusted-consulting/scripts/check_release.py +0 -66
  79. package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +0 -508
  80. package/skills/dknowc-trusted-consulting/scripts/initialize.py +0 -133
  81. package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +0 -166
  82. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +0 -279
  83. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +0 -1616
  84. package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +0 -261
  85. package/skills/dknowc-trusted-search/scripts/check_release.py +0 -79
  86. package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +0 -894
@@ -1,166 +0,0 @@
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
- # dsh 兜底:注册成功后 Key 已自动写入 ~/.zshrc(register_key.mjs 持久化),
124
- # 本进程环境变量可能未注入——从 ~/.zshrc 解析(api_key.py 同源逻辑)。
125
- try:
126
- from api_key import resolve_api_key
127
- api_key, _src = resolve_api_key()
128
- except ImportError:
129
- pass
130
- if not api_key:
131
- print(f"错误:缺少环境变量 {API_KEY_ENV}(请用 DKNOWC_API_KEY=<key> 前缀赋值方式传入)。", file=sys.stderr)
132
- return 2
133
-
134
- try:
135
- arguments = json.loads(args.args_json)
136
- if not isinstance(arguments, dict):
137
- raise ValueError("参数必须是 JSON 对象")
138
- except (json.JSONDecodeError, ValueError) as e:
139
- print(f"错误:参数不是合法 JSON 对象:{e}", file=sys.stderr)
140
- return 2
141
-
142
- endpoint = args.endpoint or DEFAULT_ENDPOINT
143
- try:
144
- result = _call_tool(api_key, args.tool, arguments, endpoint, args.timeout)
145
- except RuntimeError as e:
146
- print(f"错误:{e}", file=sys.stderr)
147
- return 1
148
-
149
- raw_json = json.dumps(result, ensure_ascii=False, indent=2)
150
- if args.output:
151
- out_path = os.path.abspath(args.output)
152
- os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
153
- with open(out_path, "w", encoding="utf-8") as f:
154
- f.write(raw_json)
155
- print(f"已保存 MCP 返回:{out_path}")
156
- else:
157
- print(raw_json)
158
-
159
- # 若工具返回 isError 或内嵌业务错误码,非零退出以提示
160
- if result.get("isError"):
161
- return 1
162
- return 0
163
-
164
-
165
- if __name__ == "__main__":
166
- sys.exit(main())
@@ -1,279 +0,0 @@
1
- #!/usr/bin/env node
2
- // MaaS key bootstrap helper for SkillHub Public.
3
- // node register_key.mjs send --phone <phone>
4
- // node register_key.mjs register --phone <phone> --vcode <code> [--new-key] [--no-zshrc]
5
- //
6
- // 注册成功后自动把 Key 写入 ~/.zshrc 标记块(--no-zshrc 跳过);配合 api_key.py
7
- // 的 zshrc 兜底解析,写入后无需重启宿主即生效。
8
- // 各分支输出 user_message:给用户的固定话术,Agent 必须原样转述,不得改写后发挥
9
- // (话术库见 reference/onboarding_scripts.md;手机号一律脱敏显示)。
10
-
11
- import fs from "node:fs";
12
- import os from "node:os";
13
- import path from "node:path";
14
-
15
- const ZSHRC_START = "# >>> dknowc trusted consulting api key >>>";
16
- const ZSHRC_END = "# <<< dknowc trusted consulting api key <<<";
17
- // 早期版本遗留的标记块名(本 Skill 历史上无其他块名,保留机制以备后续变更)
18
- const LEGACY_BLOCKS = [
19
- ["# >>> dknowc api key >>>", "# <<< dknowc api key <<<"],
20
- ];
21
-
22
- const DEFAULT_BASE = "https://platform.dknowc.cn/auth/home/userAuto";
23
- const DEFAULT_OPEN_BASE = "https://open.dknowc.cn";
24
- const DEFAULT_CHANNEL = "46A3BA1D-3E1A-4E8C-BD50-A6DCBEE1DB05";
25
- const DEFAULT_SOURCE = "agent";
26
- const API_KEY_ENV = "DKNOWC_API_KEY";
27
- const LOGIN_URL = "https://platform.dknowc.cn/auth/#/login";
28
-
29
- function parseArgs(argv) {
30
- const out = { _: [] };
31
- for (let i = 0; i < argv.length; i++) {
32
- const arg = argv[i];
33
- if (arg.startsWith("--")) {
34
- const key = arg.slice(2);
35
- const next = argv[i + 1];
36
- if (next === undefined || next.startsWith("--")) {
37
- out[key] = true;
38
- } else {
39
- out[key] = next;
40
- i++;
41
- }
42
- } else {
43
- out._.push(arg);
44
- }
45
- }
46
- return out;
47
- }
48
-
49
- function maskPhone(phone) {
50
- const p = String(phone || "");
51
- if (p.length < 7) return "***";
52
- return `${p.slice(0, 3)}****${p.slice(-4)}`;
53
- }
54
-
55
- async function postJson(url, payload, headers = {}) {
56
- const controller = new AbortController();
57
- const timer = setTimeout(() => controller.abort(), 30000);
58
- try {
59
- const response = await fetch(url, {
60
- method: "POST",
61
- headers: { "Content-Type": "application/json", ...headers },
62
- body: JSON.stringify(payload),
63
- signal: controller.signal,
64
- });
65
- const text = await response.text();
66
- try {
67
- return JSON.parse(text);
68
- } catch {
69
- return { status: false, msg: `非 JSON 响应:${text.slice(0, 200)}` };
70
- }
71
- } catch (error) {
72
- const msg = error && error.message ? error.message : String(error);
73
- return { status: false, msg: `请求异常:${msg}` };
74
- } finally {
75
- clearTimeout(timer);
76
- }
77
- }
78
-
79
- function genPassword() {
80
- const pools = [
81
- "ABCDEFGHJKLMNPQRSTUVWXYZ",
82
- "abcdefghijkmnpqrstuvwxyz",
83
- "23456789",
84
- "!@#$%^&*",
85
- ];
86
- const pick = (value) => value[Math.floor(Math.random() * value.length)];
87
- const chars = pools.map(pick);
88
- const all = pools.join("");
89
- for (let i = 0; i < 8; i++) chars.push(pick(all));
90
- for (let i = chars.length - 1; i > 0; i--) {
91
- const j = Math.floor(Math.random() * (i + 1));
92
- [chars[i], chars[j]] = [chars[j], chars[i]];
93
- }
94
- return chars.join("");
95
- }
96
-
97
- async function createNewApiKey(openBase, existingApiKey, name, remark) {
98
- const url = `${openBase.replace(/\/$/, "")}/open-api/maas/api-key/create`;
99
- const result = await postJson(
100
- url,
101
- { name, remark },
102
- { Authorization: `Bearer ${existingApiKey}` },
103
- );
104
- const apiKey = result && result.data ? result.data.appKey : "";
105
- return { result, apiKey };
106
- }
107
-
108
- function escapeRegExp(value) {
109
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
110
- }
111
-
112
- function shellSingleQuote(value) {
113
- return `'${String(value).replace(/'/g, `'\\''`)}'`;
114
- }
115
-
116
- function writeApiKeyToZshrc(apiKey) {
117
- const zshrcPath = path.join(os.homedir(), ".zshrc");
118
- const block = [
119
- ZSHRC_START,
120
- `export ${API_KEY_ENV}=${shellSingleQuote(apiKey)}`,
121
- ZSHRC_END,
122
- "",
123
- ].join("\n");
124
- let existing = "";
125
- try {
126
- existing = fs.existsSync(zshrcPath) ? fs.readFileSync(zshrcPath, "utf8") : "";
127
- } catch (e) {
128
- return { written: false, path: zshrcPath, error: e && e.message ? e.message : String(e) };
129
- }
130
-
131
- // 清理早期版本遗留的标记块(含空块),再写入当前标准块
132
- for (const [start, end] of LEGACY_BLOCKS) {
133
- const legacy = new RegExp(`${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}\\n?`, "m");
134
- existing = existing.replace(legacy, "");
135
- }
136
-
137
- const pattern = new RegExp(`${escapeRegExp(ZSHRC_START)}[\\s\\S]*?${escapeRegExp(ZSHRC_END)}\\n?`, "m");
138
- const next = pattern.test(existing)
139
- ? existing.replace(pattern, block)
140
- : `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${block}`;
141
-
142
- try {
143
- fs.writeFileSync(zshrcPath, next, { encoding: "utf8", mode: 0o600 });
144
- return { written: true, path: zshrcPath, error: null };
145
- } catch (e) {
146
- return { written: false, path: zshrcPath, error: e && e.message ? e.message : String(e) };
147
- }
148
- }
149
-
150
- function maskKey(apiKey) {
151
- if (!apiKey) return null;
152
- if (apiKey.length <= 12) return "***";
153
- return `${apiKey.slice(0, 7)}...${apiKey.slice(-4)}`;
154
- }
155
-
156
- async function main() {
157
- const args = parseArgs(process.argv.slice(2));
158
- const cmd = args._[0];
159
- const base = args.base || DEFAULT_BASE;
160
-
161
- if (cmd === "send") {
162
- if (!args.phone) {
163
- console.error("缺少 --phone");
164
- process.exit(2);
165
- }
166
- const channel = args.channel && args.channel !== true ? args.channel : DEFAULT_CHANNEL;
167
- const r = await postJson(`${base}/sendMessage`, { phone: args.phone, type: "register", channel });
168
- // user_message:给用户的固定话术,Agent 必须原样转述,不得改写后发挥
169
- let userMessage;
170
- if (r.status) {
171
- userMessage = `验证码已发送到 ${maskPhone(args.phone)},请把最新一条短信里的 6 位验证码发我。`;
172
- } else if (String(r.msg || "").includes("手机号")) {
173
- userMessage = "这个手机号格式好像不对,麻烦核对一下再发我。";
174
- } else {
175
- userMessage = `验证码发送没成功(可能是网络或短信通道问题),可以再试一次;如果连续失败,也可以用网页方式开通:${LOGIN_URL}`;
176
- }
177
- console.log(JSON.stringify({ ...r, user_message: userMessage }));
178
- if (r.status) console.error("验证码已发送(话术见 user_message,请向用户转述后索取 6 位验证码)。");
179
- process.exit(r.status ? 0 : 1);
180
- }
181
-
182
- if (cmd === "register") {
183
- if (!args.phone || !args.vcode) {
184
- console.error("缺少 --phone 或 --vcode");
185
- process.exit(2);
186
- }
187
-
188
- const payload = {
189
- phone: args.phone,
190
- vcode: args.vcode,
191
- password: args.password && args.password !== true ? args.password : genPassword(),
192
- organ: args.organ && args.organ !== true ? args.organ : "个人",
193
- name: args.name && args.name !== true ? args.name : "用户",
194
- apiKeyName: args["apikey-name"] && args["apikey-name"] !== true ? args["apikey-name"] : "agent-key",
195
- channel: args.channel && args.channel !== true ? args.channel : DEFAULT_CHANNEL,
196
- source: args.source && args.source !== true ? args.source : DEFAULT_SOURCE,
197
- };
198
-
199
- const r = await postJson(`${base}/register`, payload);
200
- const data = r.data || {};
201
- let apiKey = r.status && data.apiKey ? data.apiKey : "";
202
- let newKeyCreated = false;
203
- let newKeyError = null;
204
-
205
- if (apiKey && args["new-key"]) {
206
- const keyName = args["new-key-name"] && args["new-key-name"] !== true
207
- ? args["new-key-name"]
208
- : payload.apiKeyName;
209
- const keyRemark = args["new-key-remark"] && args["new-key-remark"] !== true
210
- ? args["new-key-remark"]
211
- : "由 SkillHub 深知可信咨询按用户要求重新生成";
212
- const created = await createNewApiKey(
213
- args["open-base"] && args["open-base"] !== true ? args["open-base"] : DEFAULT_OPEN_BASE,
214
- apiKey,
215
- keyName,
216
- keyRemark,
217
- );
218
- if (created.apiKey) {
219
- apiKey = created.apiKey;
220
- newKeyCreated = true;
221
- } else {
222
- // 新建 Key 失败:沿用现有密钥继续,如实告知,不把旧 Key 冒充新 Key
223
- newKeyError = created.result.errmsg || created.result.msg || "新 API Key 创建失败";
224
- }
225
- }
226
-
227
- // 注册成功自动持久化到 ~/.zshrc 标记块(--no-zshrc 跳过);
228
- // 配合 api_key.py 兜底解析,写入后无需重启宿主即生效。
229
- const zshrcWrite = apiKey && !args["no-zshrc"]
230
- ? writeApiKeyToZshrc(apiKey)
231
- : { written: false, path: path.join(os.homedir(), ".zshrc"), error: null };
232
-
233
- // user_message:给用户的固定话术,Agent 必须原样转述,不得改写后发挥。
234
- // 权益(300 次额度 + 实名认证赠金)已在引导开通时告知,此处只做额度到账的轻确认。
235
- let userMessage;
236
- if (apiKey) {
237
- userMessage = Boolean(data.existed)
238
- ? `这个手机号之前开通过,已直接找回原来的密钥和额度,不用重新注册。我马上开始查询。`
239
- : `开通成功,访问密钥已写入本机,300 次免费咨询额度已生效。我马上开始查询。`;
240
- if (newKeyError) {
241
- userMessage += ` 另外你要求的新密钥生成失败(${newKeyError}),已先沿用现有密钥继续,不影响使用;需要的话稍后再重新生成。`;
242
- }
243
- } else if (String(r.msg || "").includes("验证码")) {
244
- userMessage = `验证码校验没通过(可能是输入有误或已过期)。请核对 ${maskPhone(args.phone)} 最新一条短信的 6 位验证码重新发我;需要我重新发送一条,直接说一声。`;
245
- } else {
246
- userMessage = `开通服务暂时没连上(${r.msg || "网络波动"}),可以稍后再试,或用网页方式开通:${LOGIN_URL}`;
247
- }
248
-
249
- console.log(JSON.stringify({
250
- status: Boolean(apiKey),
251
- msg: r.msg,
252
- url: data.url || null,
253
- existed: Boolean(data.existed),
254
- keyCreatedByRegister: Boolean(data.keyCreated),
255
- newKeyRequested: Boolean(args["new-key"]),
256
- newKeyCreated,
257
- user_message: userMessage,
258
- envName: API_KEY_ENV,
259
- apiKey,
260
- apiKeyMasked: maskKey(apiKey),
261
- currentTaskOnly: false,
262
- envWriteRequired: false,
263
- envWriteTarget: zshrcWrite.path,
264
- envWriteSucceeded: Boolean(zshrcWrite.written),
265
- envWriteError: zshrcWrite.error || null,
266
- persistInstruction: zshrcWrite.written
267
- ? `密钥已自动写入 ~/.zshrc 标记块(${API_KEY_ENV}),配合 api_key.py 兜底解析,无需重启即生效;不要重复写入。`
268
- : `本次未写入 ~/.zshrc${args["no-zshrc"] ? "(--no-zshrc)" : "(写入失败,见 envWriteError)"};如需持久化,把 ${API_KEY_ENV} 写入 ~/.zshrc 标记块后无需重启即生效。`,
269
- fallbackRegisterUrl: LOGIN_URL,
270
- newKeyError,
271
- }));
272
- process.exit(apiKey ? 0 : 1);
273
- }
274
-
275
- console.error("用法: node register_key.mjs <send|register> ...");
276
- process.exit(2);
277
- }
278
-
279
- main();