dknowc-dsh 1.4.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 (82) hide show
  1. package/README.md +18 -19
  2. package/package.json +3 -3
  3. package/skills/dknowc-official-doc-writer/README.md +18 -16
  4. package/skills/dknowc-official-doc-writer/SKILL.md +112 -143
  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 +38 -18
  12. package/skills/dknowc-official-doc-writer/reference/search_guide.md +100 -33
  13. package/skills/dknowc-official-doc-writer/reference/search_intro.md +6 -6
  14. package/skills/dknowc-official-doc-writer/reference/search_policy.md +77 -55
  15. package/skills/dknowc-official-doc-writer/reference/task_router.md +6 -6
  16. package/skills/dknowc-official-doc-writer/scripts/api_key.py +41 -14
  17. package/skills/dknowc-official-doc-writer/scripts/attribution.py +60 -0
  18. package/skills/dknowc-official-doc-writer/scripts/build_trace_json.py +288 -0
  19. package/skills/dknowc-official-doc-writer/scripts/check_materials.py +265 -0
  20. package/skills/dknowc-official-doc-writer/scripts/deep_convert.py +235 -0
  21. package/skills/dknowc-official-doc-writer/scripts/deep_query.py +333 -0
  22. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +13 -4
  23. package/skills/dknowc-official-doc-writer/scripts/extract_reference.py +245 -0
  24. package/skills/dknowc-official-doc-writer/scripts/format_document.py +106 -18
  25. package/skills/dknowc-official-doc-writer/scripts/initialize.py +13 -7
  26. package/skills/dknowc-official-doc-writer/scripts/mcp_convert.py +272 -0
  27. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +257 -143
  28. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +72 -8
  29. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +14 -4
  30. package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +6 -1
  31. package/skills/dknowc-official-doc-writer/scripts/register.mjs +122 -50
  32. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +238 -94
  33. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +11 -2
  34. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +13 -0
  35. package/skills/dknowc-ppt-assistant/README.md +14 -10
  36. package/skills/dknowc-ppt-assistant/SKILL.md +33 -15
  37. package/skills/dknowc-ppt-assistant/attribution.json +5 -0
  38. package/skills/dknowc-ppt-assistant/references/material_usage.md +9 -5
  39. package/skills/dknowc-ppt-assistant/references/onboarding_scripts.md +14 -2
  40. package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +123 -115
  41. package/skills/dknowc-ppt-assistant/references/search_intro.md +1 -1
  42. package/skills/dknowc-ppt-assistant/references/svg-authoring.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 +5 -3
  46. package/skills/dknowc-ppt-assistant/scripts/mcp_convert.py +188 -0
  47. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +184 -94
  48. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +141 -121
  49. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +33 -3
  50. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +15 -17
  51. package/skills/dknowc-trusted-search/README.md +27 -23
  52. package/skills/dknowc-trusted-search/SKILL.md +213 -141
  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 +129 -521
  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 +19 -27
  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 +151 -45
  64. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +340 -129
  65. package/skills/dknowc-trusted-search/scripts/trusted_search.py +28 -28
  66. package/src/index.js +2 -7
  67. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +0 -279
  68. package/skills/dknowc-trusted-consulting/README.md +0 -63
  69. package/skills/dknowc-trusted-consulting/SKILL.md +0 -241
  70. package/skills/dknowc-trusted-consulting/reference/consult_intro.md +0 -47
  71. package/skills/dknowc-trusted-consulting/reference/onboarding_scripts.md +0 -132
  72. package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +0 -31
  73. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +0 -867
  74. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +0 -283
  75. package/skills/dknowc-trusted-consulting/scripts/api_key.py +0 -41
  76. package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +0 -508
  77. package/skills/dknowc-trusted-consulting/scripts/initialize.py +0 -123
  78. package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +0 -166
  79. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +0 -281
  80. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +0 -2534
  81. package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +0 -261
  82. package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +0 -894
@@ -1,34 +1,77 @@
1
1
  #!/usr/bin/env node
2
- // 国内 MaaS headless 注册助手(供 skillhub skill 调用;纯 node,内置 fetch,无三方依赖)。
3
- // node register_key.mjs [--base URL] send --phone <p>
4
- // node register_key.mjs [--base URL] register --phone <p> --vcode <c> [--type 11] [--organ ..] [--name ..] [--channel ..] [--source ..] [--password ..] [--new-key] [--no-zshrc]
5
- // 无需 cookie / 加密 / 登录态。注册成功后自动把 API Key 写入 ~/.zshrc 标记块(--no-zshrc 跳过);
6
- // 业务脚本从 ~/.zshrc 直读,无需重启宿主。默认打生产,--base 可切测试环境。
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]
5
+ // node register_key.mjs save-key # MCP create_api_key 拿到的密钥落盘(stdin 优先,或 --api-key)
7
6
 
8
7
  import fs from "fs";
9
8
  import os from "os";
10
9
  import path from "path";
10
+ import { fileURLToPath } from "url";
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.dirname(__filename);
11
14
 
12
15
  const DEFAULT_BASE = "https://platform.dknowc.cn/auth/home/userAuto";
13
16
  const DEFAULT_OPEN_BASE = "https://open.dknowc.cn";
14
17
  const DEFAULT_CHANNEL = "46A3BA1D-3E1A-4E8C-BD50-A6DCBEE1DB05";
15
18
  const DEFAULT_TYPE = "11";
16
- const DEFAULT_SOURCE = "agent";
19
+ // 2026-09-29 调整:与统一来源声明(X-Dknowc-Attribution)的 source 对齐,
20
+ // 不再用旧值 "agent"(与"来源统计最终方案 V1.0"的字段语义冲突)。
21
+ const DEFAULT_SOURCE = "dknowc-ppt-assistant";
17
22
  const API_KEY_ENV = "DKNOWC_API_KEY";
18
23
  const MAAS_PLATFORM_URL = "https://platform.dknowc.cn/auth/#/login";
19
- const FALLBACK_REGISTER_URL = MAAS_PLATFORM_URL;
20
- const ZSHRC_START = "# >>> dknowc api key >>>";
21
- const ZSHRC_END = "# <<< dknowc api key <<<";
24
+ // Key 持久化目标:本机专用配置文件(XDG 规范路径),不再依赖 ~/.zshrc。
25
+ // 迁移:写入新文件成功后,清理 ~/.zshrc 中的历史 Key 块。
26
+ const KEY_FILE_NAME = "api_key";
27
+ const ZSHRC_START = "# >>> dknowc ppt assistant api key >>>";
28
+ const ZSHRC_END = "# <<< dknowc ppt assistant api key <<<";
29
+ // 历史 ~/.zshrc 标记块(含旧名),迁移期统一清理
30
+ const LEGACY_BLOCKS = [
31
+ [ZSHRC_START, ZSHRC_END],
32
+ ["# >>> dknowc api key >>>", "# <<< dknowc api key <<<"],
33
+ ];
22
34
 
23
- function maskPhone(phone) {
24
- const p = String(phone || "");
25
- return p.length >= 7 ? `${p.slice(0, 3)}****${p.slice(-4)}` : p;
35
+ function escapeRegExp(value) {
36
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26
37
  }
27
38
 
28
- function maskKey(apiKey) {
29
- if (!apiKey) return null;
30
- if (apiKey.length <= 12) return "***";
31
- return `${apiKey.slice(0, 7)}...${apiKey.slice(-4)}`;
39
+ function apiKeyFilePath() {
40
+ const home = os.homedir();
41
+ if (process.platform === "win32") {
42
+ const appdata = process.env.APPDATA || home;
43
+ return path.join(appdata, "dknowc", KEY_FILE_NAME);
44
+ }
45
+ const xdg = process.env.XDG_CONFIG_HOME || path.join(home, ".config");
46
+ return path.join(xdg, "dknowc", KEY_FILE_NAME);
47
+ }
48
+
49
+ function removeLegacyZshrcBlocks() {
50
+ // 迁移:从 ~/.zshrc 移除历史 Key 标记块(避免污染 shell 配置)
51
+ const zshrcPath = path.join(os.homedir(), ".zshrc");
52
+ try {
53
+ let existing = fs.existsSync(zshrcPath) ? fs.readFileSync(zshrcPath, "utf8") : "";
54
+ if (!existing) return;
55
+ let changed = false;
56
+ for (const [start, end] of LEGACY_BLOCKS) {
57
+ const re = new RegExp(`${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}\\n?`, "m");
58
+ if (re.test(existing)) { existing = existing.replace(re, ""); changed = true; }
59
+ }
60
+ if (changed) fs.writeFileSync(zshrcPath, existing, { encoding: "utf8", mode: 0o600 });
61
+ } catch (e) { /* 清理失败不阻断写入流程 */ }
62
+ }
63
+
64
+ function writeApiKeyToConfigFile(apiKey) {
65
+ // 写本机专用配置文件(纯文本一行 Key,600 权限);成功后清理历史 ~/.zshrc 块
66
+ const filePath = apiKeyFilePath();
67
+ try {
68
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
69
+ fs.writeFileSync(filePath, `${String(apiKey).trim()}\n`, { encoding: "utf8", mode: 0o600 });
70
+ removeLegacyZshrcBlocks();
71
+ return { written: true, path: filePath, error: null };
72
+ } catch (e) {
73
+ return { written: false, path: filePath, error: e && e.message ? e.message : String(e) };
74
+ }
32
75
  }
33
76
 
34
77
  function parseArgs(argv) {
@@ -51,13 +94,35 @@ function parseArgs(argv) {
51
94
  return out;
52
95
  }
53
96
 
97
+ // —— 统一来源声明(X-Dknowc-Attribution)——
98
+ // 读包根 attribution.json(kind/source/channel)+ SKILL.md 的 version;仅统计用、
99
+ // 不参与鉴权;读取失败返回 null(不加头、不阻断请求)。
100
+ function buildAttributionHeader() {
101
+ try {
102
+ const root = path.resolve(__dirname, "..");
103
+ const meta = JSON.parse(fs.readFileSync(path.join(root, "attribution.json"), "utf-8"));
104
+ if (!meta.source) return null;
105
+ const parts = [`kind=${meta.kind || "skill"}`, `source=${meta.source}`];
106
+ try {
107
+ const m = fs.readFileSync(path.join(root, "SKILL.md"), "utf-8").match(/^version:\s*"?([^"\n]+)"?/m);
108
+ if (m) parts.push(`version=${m[1].trim()}`);
109
+ } catch {}
110
+ if (meta.channel) parts.push(`channel=${meta.channel}`);
111
+ return parts.join(";");
112
+ } catch { return null; }
113
+ }
114
+ function withAttribution(headers) {
115
+ const attr = buildAttributionHeader();
116
+ return attr ? { ...headers, "X-Dknowc-Attribution": attr } : headers;
117
+ }
118
+
54
119
  async function postJson(url, payload, headers = {}) {
55
120
  const controller = new AbortController();
56
121
  const timer = setTimeout(() => controller.abort(), 30000);
57
122
  try {
58
123
  const response = await fetch(url, {
59
124
  method: "POST",
60
- headers: { "Content-Type": "application/json", ...headers },
125
+ headers: withAttribution({ "Content-Type": "application/json", ...headers }),
61
126
  body: JSON.stringify(payload),
62
127
  signal: controller.signal,
63
128
  });
@@ -104,42 +169,19 @@ async function createNewApiKey(openBase, existingApiKey, name, remark) {
104
169
  return { result, apiKey };
105
170
  }
106
171
 
107
- function shellSingleQuote(value) {
108
- return `'${String(value).replace(/'/g, `'\\''`)}'`;
172
+ function maskPhone(phone) {
173
+ const p = String(phone || "");
174
+ return p.length === 11 ? `${p.slice(0, 3)}****${p.slice(-4)}` : p;
109
175
  }
110
176
 
111
- function escapeRegExp(value) {
112
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
177
+ function isValidCnPhone(phone) {
178
+ return /^1[3-9]\d{9}$/.test(String(phone || ""));
113
179
  }
114
180
 
115
- function writeApiKeyToZshrc(apiKey) {
116
- const zshrcPath = path.join(os.homedir(), ".zshrc");
117
- const block = [
118
- ZSHRC_START,
119
- `export ${API_KEY_ENV}=${shellSingleQuote(apiKey)}`,
120
- ZSHRC_END,
121
- "",
122
- ].join("\n");
123
- let existing = "";
124
- try {
125
- existing = fs.existsSync(zshrcPath) ? fs.readFileSync(zshrcPath, "utf8") : "";
126
- } catch (error) {
127
- const msg = error && error.message ? error.message : String(error);
128
- return { written: false, path: zshrcPath, error: msg };
129
- }
130
-
131
- const pattern = new RegExp(`${escapeRegExp(ZSHRC_START)}[\\s\\S]*?${escapeRegExp(ZSHRC_END)}\\n?`, "m");
132
- const next = pattern.test(existing)
133
- ? existing.replace(pattern, block)
134
- : `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${block}`;
135
-
136
- try {
137
- fs.writeFileSync(zshrcPath, next, { encoding: "utf8", mode: 0o600 });
138
- return { written: true, path: zshrcPath, error: null };
139
- } catch (error) {
140
- const msg = error && error.message ? error.message : String(error);
141
- return { written: false, path: zshrcPath, error: msg };
142
- }
181
+ function maskKey(apiKey) {
182
+ if (!apiKey) return null;
183
+ if (apiKey.length <= 12) return "***";
184
+ return `${apiKey.slice(0, 7)}...${apiKey.slice(-4)}`;
143
185
  }
144
186
 
145
187
  async function main() {
@@ -152,20 +194,31 @@ async function main() {
152
194
  console.error("缺少 --phone");
153
195
  process.exit(2);
154
196
  }
155
- // 渠道细分:sendMessage 与 register 请求体统一携带 SkillHub 渠道码。
156
- const result = await postJson(`${base}/sendMessage`, {
157
- phone: args.phone,
158
- type: "register",
159
- channel: args.channel && args.channel !== true ? args.channel : DEFAULT_CHANNEL,
160
- });
161
- // user_message:给用户的固定话术,Agent 必须原样转述,不得改写后发挥
197
+ const channel = args.channel && args.channel !== true ? args.channel : DEFAULT_CHANNEL;
198
+ if (!isValidCnPhone(args.phone)) {
199
+ console.log(JSON.stringify({
200
+ status: false,
201
+ msg: "手机号格式不正确",
202
+ user_message: "这个手机号格式好像不对,麻烦核对一下再发我。",
203
+ }));
204
+ process.exit(1);
205
+ }
206
+ let result;
207
+ try {
208
+ result = await postJson(`${base}/sendMessage`, {
209
+ phone: args.phone,
210
+ type: "register",
211
+ channel,
212
+ });
213
+ } catch (e) {
214
+ result = { status: false, msg: String((e && e.message) || e) };
215
+ }
216
+ // user_message:给用户的固定话术,Agent 必须原样转述,不得改写后发挥。
162
217
  let userMessage;
163
218
  if (result.status) {
164
219
  userMessage = `验证码已发送到 ${maskPhone(args.phone)},请把最新一条短信里的 6 位验证码发我。`;
165
- } else if (String(result.msg || "").includes("手机号")) {
166
- userMessage = "这个手机号格式好像不对,麻烦核对一下再发我。";
167
220
  } else {
168
- userMessage = `验证码发送没成功(可能是网络或短信通道问题),可以再试一次;如果连续失败,也可以用网页方式开通:${FALLBACK_REGISTER_URL}`;
221
+ userMessage = `验证码发送没成功(可能是网络或短信通道问题),可以再试一次;如果连续失败,也可以用网页方式开通:${MAAS_PLATFORM_URL}`;
169
222
  }
170
223
  console.log(JSON.stringify({ ...result, user_message: userMessage }));
171
224
  if (result.status) console.error("验证码已发送(话术见 user_message,请向用户转述后索取 6 位验证码)。");
@@ -192,11 +245,11 @@ async function main() {
192
245
 
193
246
  const result = await postJson(`${base}/register`, payload);
194
247
  const data = result.data || {};
195
- const ok = Boolean(result.status) && Boolean(data.apiKey);
196
- let apiKeyToSave = ok ? data.apiKey : "";
248
+ let apiKey = result.status && data.apiKey ? data.apiKey : "";
197
249
  let newKeyCreated = false;
198
250
  let newKeyError = null;
199
- if (ok && args["new-key"]) {
251
+
252
+ if (apiKey && args["new-key"]) {
200
253
  const keyName = args["new-key-name"] && args["new-key-name"] !== true
201
254
  ? args["new-key-name"]
202
255
  : payload.apiKeyName;
@@ -205,64 +258,101 @@ async function main() {
205
258
  : "由 SkillHub 深知可信搜索按用户要求重新生成";
206
259
  const created = await createNewApiKey(
207
260
  args["open-base"] && args["open-base"] !== true ? args["open-base"] : DEFAULT_OPEN_BASE,
208
- data.apiKey,
261
+ apiKey,
209
262
  keyName,
210
263
  keyRemark,
211
264
  );
212
265
  if (created.apiKey) {
213
- apiKeyToSave = created.apiKey;
266
+ apiKey = created.apiKey;
214
267
  newKeyCreated = true;
215
268
  } else {
216
- // 新建失败:沿用原密钥继续(不中断用户任务),newKeyCreated=false 明确区分新旧
269
+ // 新建失败:沿用原密钥继续并如实告知,不弃 key、不冒充新 Key
217
270
  newKeyError = created.result.errmsg || created.result.msg || "新 API Key 创建失败";
218
271
  }
219
272
  }
220
- const zshrcWrite = ok && apiKeyToSave && !args["no-zshrc"]
221
- ? writeApiKeyToZshrc(apiKeyToSave)
222
- : { written: false, path: path.join(os.homedir(), ".zshrc"), error: null };
273
+
274
+ // 注册成功即写入本机专用配置文件(--no-persist 可关闭):脚本直读文件,
275
+ // 避免宿主进程读不到环境变量造成"每任务重新注册"的误判。
276
+ const persistResult = registered && !args["no-persist"]
277
+ ? writeApiKeyToConfigFile(apiKey)
278
+ : { written: false, path: apiKeyFilePath(), error: null };
279
+
223
280
  // user_message:给用户的固定话术,Agent 必须原样转述,不得改写后发挥。
224
- // 权益告知(300 次额度 + 实名认证赠金)已前移到开通引导(initialize.guide_message / onboarding_scripts S1),
225
- // 此处只做轻确认,避免成功节点信息过重导致转述截断。
281
+ const registered = Boolean(apiKey);
226
282
  let userMessage;
227
- if (ok && apiKeyToSave) {
228
- userMessage = Boolean(data.existed)
229
- ? `这个手机号之前开通过,已直接找回原来的密钥和额度,不用重新注册。我马上开始检索。`
230
- : `开通成功,访问密钥已写入本机,300 次免费检索额度已生效。我马上开始检索。`;
231
- if (newKeyError) {
232
- userMessage += ` 另外你要求的新密钥生成失败(${newKeyError}),已先沿用现有密钥继续,不影响使用;需要的话稍后再重新生成。`;
233
- }
234
- } else if (String(result.msg || "").includes("验证码")) {
283
+ if (registered && data.existed) {
284
+ userMessage = "这个手机号之前开通过,已直接找回原来的密钥和额度,不用重新注册。我马上开始检索。";
285
+ } else if (registered) {
286
+ userMessage = "开通成功,访问密钥已写入本机,300 次免费检索额度已生效。我马上开始检索。";
287
+ } else if (/vcode|验证码/i.test(String(result.msg || ""))) {
235
288
  userMessage = `验证码校验没通过(可能是输入有误或已过期)。请核对 ${maskPhone(args.phone)} 最新一条短信的 6 位验证码重新发我;需要我重新发送一条,直接说一声。`;
236
289
  } else {
237
- userMessage = `开通服务暂时没连上(${result.msg || "网络波动"}),可以稍后再试,或用网页方式开通:${FALLBACK_REGISTER_URL}`;
290
+ userMessage = `开通服务暂时没连上(${result.msg || "网络波动"}),可以稍后再试,或用网页方式开通:${MAAS_PLATFORM_URL}`;
238
291
  }
292
+ if (registered && newKeyError) {
293
+ userMessage += ` 另外你要求的新密钥生成失败(${newKeyError}),已先沿用现有密钥继续,不影响使用;需要的话稍后再重新生成。`;
294
+ }
295
+
239
296
  console.log(JSON.stringify({
240
- status: ok && Boolean(apiKeyToSave),
297
+ status: registered,
241
298
  msg: result.msg,
242
299
  url: data.url || null,
243
300
  existed: Boolean(data.existed),
244
301
  keyCreatedByRegister: Boolean(data.keyCreated),
245
302
  newKeyRequested: Boolean(args["new-key"]),
246
303
  newKeyCreated,
247
- user_message: userMessage,
248
304
  envName: API_KEY_ENV,
249
- apiKey: apiKeyToSave,
250
- apiKeyMasked: maskKey(apiKeyToSave),
251
- envWriteRequired: false,
252
- envWriteTarget: zshrcWrite.path,
253
- envWriteSucceeded: Boolean(zshrcWrite.written),
254
- envWriteError: zshrcWrite.error,
255
- envWriteInstruction: zshrcWrite.written
256
- ? `已写入 ${zshrcWrite.path};脚本直读该文件,无需重启宿主。当前任务可继续使用返回的 apiKey。`
257
- : `未能写入 ${zshrcWrite.path},请由 Agent 或平台密钥配置将返回的 apiKey 写入环境变量 ${API_KEY_ENV}。`,
258
- currentSessionInstruction: `当前任务继续执行初始化时,请用本次返回的 apiKey 临时注入环境变量 ${API_KEY_ENV},不得向用户展示完整 Key。`,
305
+ apiKey,
306
+ apiKeyMasked: maskKey(apiKey),
307
+ keyFilePersisted: Boolean(persistResult.written),
308
+ keyFilePath: persistResult.path || null,
309
+ keyFileError: persistResult.error || null,
310
+ persistInstruction: persistResult.written
311
+ ? `访问密钥已写入本机专用配置文件(${persistResult.path},仅本机、600 权限),后续任务直接读取、无需重复注册。`
312
+ : `本次返回的 apiKey 仅供当前任务临时注入 ${API_KEY_ENV}。任务完成后可在平台环境变量或密钥配置中保存 ${API_KEY_ENV}。`,
313
+ fallbackRegisterUrl: MAAS_PLATFORM_URL,
259
314
  newKeyError,
260
- fallbackRegisterUrl: FALLBACK_REGISTER_URL,
315
+ user_message: userMessage,
316
+ }));
317
+ process.exit(apiKey && !newKeyError ? 0 : 1);
318
+ }
319
+
320
+ if (cmd === "save-key") {
321
+ // MCP create_api_key 拿到的密钥经 stdin 传入(避免出现在命令行参数与日志),--api-key 兜底
322
+ let key = "";
323
+ if (args["api-key"] && args["api-key"] !== true) {
324
+ key = String(args["api-key"]).trim();
325
+ } else {
326
+ key = await new Promise((resolve) => {
327
+ let buf = "";
328
+ process.stdin.setEncoding("utf8");
329
+ process.stdin.on("data", (chunk) => { buf += chunk; });
330
+ process.stdin.on("end", () => resolve(buf.trim()));
331
+ });
332
+ }
333
+ const looksValid = /^sk-/.test(key) && key.length >= 20;
334
+ if (!looksValid) {
335
+ console.log(JSON.stringify({
336
+ status: false,
337
+ user_message: "密钥格式不对(应以 sk- 开头),没有写入本机。请重新获取后再试。",
338
+ }));
339
+ process.exit(1);
340
+ }
341
+ const saved = writeApiKeyToConfigFile(key);
342
+ console.log(JSON.stringify({
343
+ status: Boolean(saved.written),
344
+ keyFilePath: saved.path || null,
345
+ keyFileError: saved.error || null,
346
+ envName: API_KEY_ENV,
347
+ apiKeyMasked: maskKey(key),
348
+ user_message: saved.written
349
+ ? "已通过你的深知可信工作台授权直接开通搜索功能,无需手机号验证,马上开始检索。"
350
+ : `密钥写入本机配置文件失败(${saved.error || "未知原因"}),本次可先用临时密钥继续,稍后再试。`,
261
351
  }));
262
- process.exit(ok && Boolean(apiKeyToSave) ? 0 : 1);
352
+ process.exit(saved.written ? 0 : 1);
263
353
  }
264
354
 
265
- console.error("用法: node register_key.mjs <send|register> ...");
355
+ console.error("用法: node register_key.mjs <send|register|save-key> ...");
266
356
  process.exit(2);
267
357
  }
268
358