qiyu-cli 0.0.0-stage → 0.2.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 (230) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +467 -2
  3. package/dist/cli.js +248 -0
  4. package/dist/commands/api.js +770 -0
  5. package/dist/commands/auth.js +349 -0
  6. package/dist/commands/credentials-source.js +70 -0
  7. package/dist/commands/db.js +503 -0
  8. package/dist/commands/local-fallback-wiring.js +67 -0
  9. package/dist/commands/local-fallback.js +34 -0
  10. package/dist/commands/query.js +564 -0
  11. package/dist/commands/skill-specs.js +64 -0
  12. package/dist/commands/skill.js +908 -0
  13. package/dist/commands/spec-types.js +145 -0
  14. package/dist/commands/stats.js +299 -0
  15. package/dist/commands/store-flags.js +56 -0
  16. package/dist/commands/store.js +258 -0
  17. package/dist/commands/sync-run.js +479 -0
  18. package/dist/commands/sync.js +757 -0
  19. package/dist/commands/tree.js +27 -0
  20. package/dist/core/config.js +259 -0
  21. package/dist/core/credentials.js +71 -0
  22. package/dist/core/edition.js +28 -0
  23. package/dist/core/envelope.js +201 -0
  24. package/dist/core/errors.js +356 -0
  25. package/dist/core/http.js +348 -0
  26. package/dist/core/ratelimit.js +126 -0
  27. package/dist/core/registry/index.js +212 -0
  28. package/dist/core/registry/params/ai.knowledge.addKnowledge.json +88 -0
  29. package/dist/core/registry/params/ai.knowledge.deleteKnowledges.json +46 -0
  30. package/dist/core/registry/params/ai.knowledge.editChannelAnswer.json +60 -0
  31. package/dist/core/registry/params/ai.knowledge.editKnowledge.json +95 -0
  32. package/dist/core/registry/params/ai.knowledge.editKnowledgeNoSimilars.json +102 -0
  33. package/dist/core/registry/params/ai.knowledge.getCategoryTree.json +39 -0
  34. package/dist/core/registry/params/ai.knowledge.getDetail.json +46 -0
  35. package/dist/core/registry/params/ai.knowledge.search.json +67 -0
  36. package/dist/core/registry/params/ai.statistic.transferHuman.json +60 -0
  37. package/dist/core/registry/params/category.list.json +39 -0
  38. package/dist/core/registry/params/chat.queue.group.query.json +39 -0
  39. package/dist/core/registry/params/crm.modifyOrder.json +48 -0
  40. package/dist/core/registry/params/crm.modifyUser.json +48 -0
  41. package/dist/core/registry/params/crm.syncCrmInfo.json +46 -0
  42. package/dist/core/registry/params/crm.tagChange.json +74 -0
  43. package/dist/core/registry/params/data.overview.ipcc.json +32 -0
  44. package/dist/core/registry/params/data.overview.session.json +53 -0
  45. package/dist/core/registry/params/evaluation.setting.get.json +39 -0
  46. package/dist/core/registry/params/event.applyStaff.json +116 -0
  47. package/dist/core/registry/params/event.evaluate.json +74 -0
  48. package/dist/core/registry/params/event.inviteEvaluate.json +81 -0
  49. package/dist/core/registry/params/event.qcResult.json +166 -0
  50. package/dist/core/registry/params/event.queryQueueStatus.json +39 -0
  51. package/dist/core/registry/params/event.queueEnter.json +40 -0
  52. package/dist/core/registry/params/event.queueLeave.json +46 -0
  53. package/dist/core/registry/params/event.quitQueue.json +39 -0
  54. package/dist/core/registry/params/event.sessionChange.json +95 -0
  55. package/dist/core/registry/params/event.sessionData.json +452 -0
  56. package/dist/core/registry/params/event.sessionEnd.json +117 -0
  57. package/dist/core/registry/params/event.sessionStart.json +109 -0
  58. package/dist/core/registry/params/event.updateUInfo.json +46 -0
  59. package/dist/core/registry/params/export.session.check.json +7 -0
  60. package/dist/core/registry/params/export.session.json +7 -0
  61. package/dist/core/registry/params/export.session.one.json +7 -0
  62. package/dist/core/registry/params/export.session.one.message.json +7 -0
  63. package/dist/core/registry/params/get_call_order.json +50 -0
  64. package/dist/core/registry/params/get_call_user_info.json +36 -0
  65. package/dist/core/registry/params/get_order.json +50 -0
  66. package/dist/core/registry/params/get_token.json +22 -0
  67. package/dist/core/registry/params/get_user_info.json +36 -0
  68. package/dist/core/registry/params/icoutcall.callIntercept.list.json +32 -0
  69. package/dist/core/registry/params/icoutcall.dialogFlow.fuzzySearch.json +53 -0
  70. package/dist/core/registry/params/icoutcall.dialogFlow.getDialogFlowList.json +32 -0
  71. package/dist/core/registry/params/icoutcall.get.customer.json +39 -0
  72. package/dist/core/registry/params/icoutcall.get.jobdetail.json +39 -0
  73. package/dist/core/registry/params/icoutcall.get.jobproperties.json +39 -0
  74. package/dist/core/registry/params/icoutcall.history.seat.json +67 -0
  75. package/dist/core/registry/params/icoutcall.history.team.json +67 -0
  76. package/dist/core/registry/params/icoutcall.job.create.json +53 -0
  77. package/dist/core/registry/params/icoutcall.job.importcustomer.json +46 -0
  78. package/dist/core/registry/params/icoutcall.job.pause.json +39 -0
  79. package/dist/core/registry/params/icoutcall.job.readdcustomer.json +109 -0
  80. package/dist/core/registry/params/icoutcall.job.start.json +39 -0
  81. package/dist/core/registry/params/icoutcall.job.terminate.json +39 -0
  82. package/dist/core/registry/params/icoutcall.phone.getLineList.json +32 -0
  83. package/dist/core/registry/params/ipcc.calltask.add.auto.json +117 -0
  84. package/dist/core/registry/params/ipcc.calltask.add.byCustom.json +96 -0
  85. package/dist/core/registry/params/ipcc.calltask.add.byRelation.json +82 -0
  86. package/dist/core/registry/params/ipcc.calltask.add.toGroup.json +89 -0
  87. package/dist/core/registry/params/ipcc.calltask.add.toStaff.json +89 -0
  88. package/dist/core/registry/params/ipcc.calltask.get.json +47 -0
  89. package/dist/core/registry/params/ipcc.calltaskdetail.add.json +54 -0
  90. package/dist/core/registry/params/ipcc.calltaskdetail.delete.json +40 -0
  91. package/dist/core/registry/params/ipcc.calltaskdetail.get.json +54 -0
  92. package/dist/core/registry/params/ipcc.calltaskdetail.update.json +40 -0
  93. package/dist/core/registry/params/ipcc.customfield.template.get.json +47 -0
  94. package/dist/core/registry/params/ipcc.login.json +47 -0
  95. package/dist/core/registry/params/kefu.add.json +130 -0
  96. package/dist/core/registry/params/kefu.delete.json +39 -0
  97. package/dist/core/registry/params/kefu.update.json +137 -0
  98. package/dist/core/registry/params/kefu.v2.query.json +39 -0
  99. package/dist/core/registry/params/kefuGroup.add.json +39 -0
  100. package/dist/core/registry/params/kefuGroup.delete.json +39 -0
  101. package/dist/core/registry/params/kefuGroup.update.json +46 -0
  102. package/dist/core/registry/params/kefuGroup.updateKefus.json +46 -0
  103. package/dist/core/registry/params/merchant.account.login.json +53 -0
  104. package/dist/core/registry/params/merchant.changePassword.json +46 -0
  105. package/dist/core/registry/params/merchant.create.json +81 -0
  106. package/dist/core/registry/params/merchant.disable.json +39 -0
  107. package/dist/core/registry/params/merchant.enable.json +39 -0
  108. package/dist/core/registry/params/merchant.list.json +46 -0
  109. package/dist/core/registry/params/merchant.query.json +46 -0
  110. package/dist/core/registry/params/merchant.update.json +74 -0
  111. package/dist/core/registry/params/message.send.image.json +53 -0
  112. package/dist/core/registry/params/message.send.json +53 -0
  113. package/dist/core/registry/params/message.send.voice.json +53 -0
  114. package/dist/core/registry/params/message.sendFile.json +39 -0
  115. package/dist/core/registry/params/message.uploadFile.json +39 -0
  116. package/dist/core/registry/params/online.session.category.list.json +39 -0
  117. package/dist/core/registry/params/online.session.customfield.template.json +39 -0
  118. package/dist/core/registry/params/online.session.customfield.update.json +74 -0
  119. package/dist/core/registry/params/order.upload.json +40 -0
  120. package/dist/core/registry/params/push.msg.image.json +74 -0
  121. package/dist/core/registry/params/push.msg.richText.json +74 -0
  122. package/dist/core/registry/params/push.msg.text.json +74 -0
  123. package/dist/core/registry/params/receive.message.json +89 -0
  124. package/dist/core/registry/params/robot.data.getQuestionsByCategoryName.json +67 -0
  125. package/dist/core/registry/params/robot.data.knowledge.json +46 -0
  126. package/dist/core/registry/params/robot.data.kpoint.json +46 -0
  127. package/dist/core/registry/params/robot.data.queryStandardByEffectiveQuestion.json +46 -0
  128. package/dist/core/registry/params/robot.data.queryStandardQuestionList.json +46 -0
  129. package/dist/core/registry/params/robot.evaluation.comment.json +67 -0
  130. package/dist/core/registry/params/robot.evaluation.setting.json +46 -0
  131. package/dist/core/registry/params/robot.session.assist.json +74 -0
  132. package/dist/core/registry/params/robot.session.chat.json +74 -0
  133. package/dist/core/registry/params/robot.session.close.json +53 -0
  134. package/dist/core/registry/params/robot.session.commonQuestions.json +74 -0
  135. package/dist/core/registry/params/robot.session.create.json +81 -0
  136. package/dist/core/registry/params/robot.session.evaluation.json +67 -0
  137. package/dist/core/registry/params/robot.session.msgAssociate.json +46 -0
  138. package/dist/core/registry/params/robot.session.msgEvaluation.json +53 -0
  139. package/dist/core/registry/params/robot.session.msgPredict.json +74 -0
  140. package/dist/core/registry/params/robot.session.transfer.json +36 -0
  141. package/dist/core/registry/params/robot.session.uploadFile.json +32 -0
  142. package/dist/core/registry/params/robot.statistic.summary.json +53 -0
  143. package/dist/core/registry/params/robot.transfer.config.json +15 -0
  144. package/dist/core/registry/params/session.user.profile.json +39 -0
  145. package/dist/core/registry/params/settings.wxTemplates.json +46 -0
  146. package/dist/core/registry/params/smstask.create.json +53 -0
  147. package/dist/core/registry/params/smstask.status.json +39 -0
  148. package/dist/core/registry/params/staff.group.list.new.json +39 -0
  149. package/dist/core/registry/params/staff.group.members.new.json +46 -0
  150. package/dist/core/registry/params/staff.list.new.json +46 -0
  151. package/dist/core/registry/params/staff.login.json +47 -0
  152. package/dist/core/registry/params/statistic.overview.json +61 -0
  153. package/dist/core/registry/params/statistic.performance.json +82 -0
  154. package/dist/core/registry/params/statistic.salaryDetail.json +54 -0
  155. package/dist/core/registry/params/statistic.satisfaction.report.json +68 -0
  156. package/dist/core/registry/params/statistic.staffAttendance.json +75 -0
  157. package/dist/core/registry/params/statistic.staffquality.json +75 -0
  158. package/dist/core/registry/params/statistic.staffworklod.json +68 -0
  159. package/dist/core/registry/params/tag.all.json +32 -0
  160. package/dist/core/registry/params/tag.batchUpdate.json +32 -0
  161. package/dist/core/registry/params/tag.update.json +60 -0
  162. package/dist/core/registry/params/ticket.apply.json +46 -0
  163. package/dist/core/registry/params/ticket.batch.modify.json +53 -0
  164. package/dist/core/registry/params/ticket.create.json +151 -0
  165. package/dist/core/registry/params/ticket.filter.count.json +46 -0
  166. package/dist/core/registry/params/ticket.filter.list.json +46 -0
  167. package/dist/core/registry/params/ticket.finish.json +60 -0
  168. package/dist/core/registry/params/ticket.followers.update.json +60 -0
  169. package/dist/core/registry/params/ticket.list.json +74 -0
  170. package/dist/core/registry/params/ticket.log.json +39 -0
  171. package/dist/core/registry/params/ticket.modify.json +74 -0
  172. package/dist/core/registry/params/ticket.new.detail.json +39 -0
  173. package/dist/core/registry/params/ticket.reminder.json +60 -0
  174. package/dist/core/registry/params/ticket.reopen.json +67 -0
  175. package/dist/core/registry/params/ticket.reply.json +60 -0
  176. package/dist/core/registry/params/ticket.search.json +116 -0
  177. package/dist/core/registry/params/ticket.template.fields.json +39 -0
  178. package/dist/core/registry/params/ticket.template.list.json +39 -0
  179. package/dist/core/registry/params/ticket.transfer.json +74 -0
  180. package/dist/core/registry/params/track.event.set.json +32 -0
  181. package/dist/core/registry/params/wecom.robot.switch.json +43 -0
  182. package/dist/core/registry/params.js +84 -0
  183. package/dist/core/registry/specs.json +2172 -0
  184. package/dist/core/registry/validate.json +11 -0
  185. package/dist/core/registry/validation-overrides.js +98 -0
  186. package/dist/core/sanitize.js +24 -0
  187. package/dist/core/sign.js +21 -0
  188. package/dist/core/time.js +194 -0
  189. package/dist/core/validate.js +140 -0
  190. package/dist/output.js +263 -0
  191. package/dist/postinstall.js +178 -0
  192. package/dist/query/errors.js +395 -0
  193. package/dist/query/mask.js +368 -0
  194. package/dist/query/metric-catalog.js +85 -0
  195. package/dist/query/sandbox.js +544 -0
  196. package/dist/query/table-query.js +297 -0
  197. package/dist/query/time-shape.js +44 -0
  198. package/dist/schedule/install.js +377 -0
  199. package/dist/skill/check.js +429 -0
  200. package/dist/skill/detect.js +371 -0
  201. package/dist/skill/install.js +1202 -0
  202. package/dist/skill/paths.js +343 -0
  203. package/dist/skill/qiyu/SKILL.md +92 -0
  204. package/dist/skill/qiyu/errors.md +55 -0
  205. package/dist/skill/qiyu/forbidden.md +52 -0
  206. package/dist/skill/qiyu/metrics.md +65 -0
  207. package/dist/skill/qiyu/protocols.md +55 -0
  208. package/dist/skill/qiyu/setup.md +50 -0
  209. package/dist/skill/refs.js +379 -0
  210. package/dist/store/config.js +137 -0
  211. package/dist/store/duckdb.js +321 -0
  212. package/dist/store/index.js +18 -0
  213. package/dist/store/retry.js +36 -0
  214. package/dist/store/schema.js +419 -0
  215. package/dist/store/types.js +4 -0
  216. package/dist/sync/day.js +8 -0
  217. package/dist/sync/engine.js +818 -0
  218. package/dist/sync/rate-gate.js +95 -0
  219. package/dist/sync/registry.js +22 -0
  220. package/dist/sync/state.js +114 -0
  221. package/dist/sync/tasks/dim.js +186 -0
  222. package/dist/sync/tasks/knowledge.js +252 -0
  223. package/dist/sync/tasks/pace.js +66 -0
  224. package/dist/sync/tasks/pipeline.js +321 -0
  225. package/dist/sync/tasks/reports.js +448 -0
  226. package/dist/sync/tasks/sessions.js +188 -0
  227. package/dist/sync/tasks/tickets.js +219 -0
  228. package/dist/sync/types.js +1 -0
  229. package/dist/sync/windowing.js +56 -0
  230. package/package.json +52 -4
@@ -0,0 +1,349 @@
1
+ import { ok, fail, usageFail, failFromTagged, describeArgs, setPretty, EXIT } from '../output.js';
2
+ import { configPathFor, loadConfigFile, loadConfigChecked, writeConfigFile, checkPermissions, } from '../core/config.js';
3
+ import { GLOBAL_FLAGS, GLOBAL_FLAG_NAMES, prettyAfterSubcommand, REJECTED_FLAGS } from './spec-types.js';
4
+ /** `auth login` 的业务 flag:只有 `--profile`(凭证从**环境变量**读,见命令内注释)。 */
5
+ const LOGIN_FLAGS = [{ name: '--profile', kind: 'value' }];
6
+ /**
7
+ * 命令契约(F 组 D4):`skill check` 据此判断 skill 正文里的 `qiyu auth …` 是否真的存在。
8
+ * `flags` 是**完整接受集**(含全局 flag)。
9
+ */
10
+ export const AUTH_SPECS = [
11
+ {
12
+ path: ['auth', 'whoami'],
13
+ flags: [...GLOBAL_FLAGS],
14
+ positionals: [],
15
+ rejected: REJECTED_FLAGS,
16
+ },
17
+ {
18
+ path: ['auth', 'login'],
19
+ flags: [...GLOBAL_FLAGS, ...LOGIN_FLAGS],
20
+ positionals: [],
21
+ rejected: REJECTED_FLAGS,
22
+ },
23
+ ];
24
+ const AUTH_USAGE = `用法:qiyu auth <whoami|login> [参数]
25
+
26
+ qiyu auth whoami 检查凭证是否已配置(只检查存在性,不校验有效性)
27
+ qiyu auth login [--profile <name>]
28
+ 把环境变量里的凭证写入配置文件
29
+
30
+ 凭证来源与优先级:环境变量 > 配置文件(QIYU_APP_KEY / QIYU_APP_SECRET)。
31
+ ⚠️ whoami 成功不代表凭证可用 —— 一个拼错的 appKey 同样返回 configured: true。
32
+ 第一次真实调用才是唯一的验证。
33
+
34
+ auth login 从环境变量读取凭证(不接受 --app-key/--app-secret:命令行参数会
35
+ 留在 shell 历史与进程列表里)。写入 ~/.config/qiyu/config.json,目录 0700、文件 0600。
36
+
37
+ 出错时 stdout 是 {"ok":false,"error":{code,kind,retryable,message,hint?}}。
38
+ ⚠️ 请按 kind 分支,不要按 code —— code 只是个标签:它可能是服务端的
39
+ 数字码(如 14009),也可能是本 CLI 合成的词(usage / network / internal /
40
+ auth_missing / config_insecure / confirm_required / store_locked / store_not_initialized /
41
+ local_rate_limit / unknown)。合成词查不到官方错误码表。
42
+
43
+ 退出码:0 成功 · 1 业务错误 · 2 用法错误 · 3 网络错误 · 4 需要 --yes
44
+ `;
45
+ export async function authCommand(argv) {
46
+ setPretty(false); // G1:每条命令入口重置输出格式 —— 同一进程内多次 run(测试)不残留上一条命令的开关。
47
+ const [sub] = argv;
48
+ // ⚠️ `--help` 不吞额外参数(2026-10-08 修)—— 与叶子命令同一条次序
49
+ // (未知/位置参数 → help):实测 `qiyu auth --help --bod` / `qiyu auth --help extra`
50
+ // 此前返回 0,拼错的 flag / 多余的位置参数被静默吞掉(`qiyu auth --bod` 单独跑是 2)。
51
+ // `--help --help` 仍给帮助(与 `api list --help --help` 同答)。
52
+ // ⚠️ `--pretty` 同样豁免(2026-10-08;G1 起已实现为缩进开关):它是**合法 flag**,
53
+ // 不是"额外参数"。
54
+ if (sub === '--help' || sub === '-h') {
55
+ const extra = argv.slice(1).filter((a) => a !== '--help' && a !== '-h' && a !== '--pretty');
56
+ if (extra.length > 0) {
57
+ return usageFail(`未知参数:${describeArgs(extra)}。--help 不接受额外参数`);
58
+ }
59
+ process.stdout.write(AUTH_USAGE);
60
+ return EXIT.OK;
61
+ }
62
+ // ⚠️ 分派层的 `--pretty` 与叶子层同答(2026-10-08 统一):次序 **未知/位置 → help
63
+ // → `--pretty`**。此前它落到「未知子命令:--pretty」—— 把承诺过、未实现的合法 flag
64
+ // 说成"未知子命令",与 ㉖ 在叶子层修的是同一类事实错误。
65
+ // G1:--pretty 已实现,但必须写在具体子命令之后(`auth whoami --pretty`)。
66
+ if (sub === '--pretty') {
67
+ const unknown = argv.slice(1).filter((a) => a.startsWith('-') && a !== '--pretty' && a !== '--help' && a !== '-h');
68
+ const positional = argv.slice(1).filter((a) => !a.startsWith('-'));
69
+ const extra = [...unknown, ...positional];
70
+ if (extra.length > 0) {
71
+ return usageFail(`未知参数:${describeArgs(extra)}。--pretty 不接受额外参数`);
72
+ }
73
+ if (argv.includes('--help') || argv.includes('-h')) {
74
+ process.stdout.write(AUTH_USAGE);
75
+ return EXIT.OK;
76
+ }
77
+ return usageFail(prettyAfterSubcommand('auth'));
78
+ }
79
+ if (sub === 'login')
80
+ return login(argv.slice(1));
81
+ if (sub !== 'whoami') {
82
+ // ⚠️ **必须点名 token、并把"无参数"与"未知子命令"分开**(2026-10-05 修)。
83
+ // 此前这里对两者都只吐整段用法:Agent 拿到一屏文字不知道自己错在哪;
84
+ // 而 `qiyu auth`(无参数)会被报成"未知子命令"——它其实只是**没给子命令**。
85
+ // 顶层 `run()` 的 `if (!sub)` 已经把这两件事分开了,三处(顶层/api/auth)
86
+ // 必须一致,否则 Agent 学不到统一规则。
87
+ if (!sub) {
88
+ return usageFail('用法:qiyu auth <whoami|login> [参数](`qiyu auth --help` 查看全部)', '可用子命令:whoami、login');
89
+ }
90
+ // ⚠️ 用 describeArgs 渲染 sub(2026-10-08 修):`qiyu auth " "` 此前报
91
+ // 「未知子命令: 」—— 名字是纯空白、不可见(与空串参数同一个病)。
92
+ return usageFail(`未知子命令:${describeArgs([sub])}\n可用子命令:whoami、login`,
93
+ // ⚠️ 不能写「见「已知缺口」」—— 那是**计划文档**的章节标题,
94
+ // Agent 手里只有这个 CLI,没有那份文档,读到的是一个悬空引用
95
+ // (2026-10-06 修)。要指向 Agent 自己能观察到的现象:跑一下就知道了。
96
+ '`qiyu auth --help` 查看完整用法');
97
+ }
98
+ // ⚠️ `whoami --help` / `-h` 必须给帮助(2026-10-07 修)。
99
+ // 此前它落到下面的"多余参数"分支,报「未知参数:--help」—— 而 `--help` 是合法
100
+ // flag,那是一句**事实错误**的说明。更重的是不一致:顶层 `qiyu --help`、`api --help`、
101
+ // `auth --help`、`api list --help`、`api call --help` 全部给帮助,唯独
102
+ // `auth whoami --help` 报错。
103
+ //
104
+ // ⚠️ **次序必须与 `list()` 完全相同**:未知/位置参数 → help → `--pretty`。
105
+ const KNOWN = new Set(GLOBAL_FLAG_NAMES);
106
+ const unknown = argv.slice(1).filter((a) => a.startsWith('-') && !KNOWN.has(a));
107
+ if (unknown.length > 0) {
108
+ return usageFail(`未知参数:${describeArgs(unknown)}。auth whoami 不接受任何参数`);
109
+ }
110
+ // ⚠️ `whoami` **不接受任何位置参数**,多出来的必须报错,不能静默忽略。
111
+ // 实测此前 `qiyu auth whoami extra` / `--bod` / `--pretty` / `--yes`
112
+ // **全部返回退出码 0 与 `{"ok":true,"data":{"configured":true}}`** ——
113
+ // 与 `api list`/`api call` 是同族问题,只是这条命令的后果不同:
114
+ // 它不发出任何请求,所以不会造成静默失败;但 `--pretty` 被无声吞掉后
115
+ // Agent 会去解析一个它没拿到的格式(与 `api list --pretty` 完全一样的坑),
116
+ // 而 `--yes` 被吞掉会让人以为这个命令接受确认参数。
117
+ // 三个子命令的参数校验必须一致 —— 只在两个上做,第三个就是漏网。
118
+ const positional = argv.slice(1).filter((a) => !a.startsWith('-'));
119
+ if (positional.length > 0) {
120
+ return usageFail(`未知参数:${describeArgs(positional)}。auth whoami 不接受任何参数`);
121
+ }
122
+ // 命令行已证明合法 —— 现在 help 优先于 `--pretty`(与 `list()` 的 ② 同源)。
123
+ if (argv.includes('--help') || argv.includes('-h')) {
124
+ process.stdout.write(AUTH_USAGE);
125
+ return EXIT.OK;
126
+ }
127
+ // G1:--pretty 已实现 —— 原拒绝点开启缩进输出(次序不变:未知/位置 → help → 这里)。
128
+ if (argv.includes('--pretty'))
129
+ setPretty(true);
130
+ return whoami();
131
+ }
132
+ /** profile 名解析与格式校验(login 与 whoami 共用)。 */
133
+ function normalizeProfile(raw) {
134
+ if (raw === undefined)
135
+ return undefined;
136
+ if (raw.trim() === '')
137
+ throw new Error('--profile 不能为空');
138
+ return raw;
139
+ }
140
+ /**
141
+ * `auth login`:把**环境变量**里的凭证写进配置文件(G1)。
142
+ *
143
+ * ⚠️ **不接受 `--app-key` / `--app-secret`**(有意的不对称,不要"为了完整"补上):
144
+ * 命令行参数会留在 shell 历史、进程列表(`ps`)与 CI 日志里 —— 凭证的三种最常见
145
+ * 泄漏途径全都命中。环境变量是唯一入口(`QIYU_APP_KEY`/`QIYU_APP_SECRET`,
146
+ * 与 whoami/api 的既有约定同源)。
147
+ *
148
+ * ⚠️ **不回显凭证**,连末四位都不 —— 与 whoami 同一条约束(全局约束:
149
+ * 「凭证绝不出现在 stdout」)。输出只有 configured/profile/config_path。
150
+ *
151
+ * ⚠️ **不发网络请求**:login 只做"把已有凭证落盘",不校验它是否有效 ——
152
+ * `whoami` 的既有说明(「拼错的 appKey 同样返回 configured: true」)对 login
153
+ * 同样成立。第一次真实调用才是唯一的验证。
154
+ */
155
+ async function login(argv) {
156
+ const KNOWN = new Set([...GLOBAL_FLAG_NAMES, '--profile']);
157
+ const unknown = argv.filter((a) => a.startsWith('-') && !KNOWN.has(a));
158
+ if (unknown.length > 0) {
159
+ return usageFail(`未知参数:${describeArgs(unknown)}。auth login 只接受 --profile <name>`);
160
+ }
161
+ // ⚠️ help 先于值位解析(与 whoami 同序:未知/位置 → help → 其余)。
162
+ if (argv.includes('--help') || argv.includes('-h')) {
163
+ process.stdout.write(AUTH_USAGE);
164
+ return EXIT.OK;
165
+ }
166
+ // 逐 token 解析:`--profile` 会**吃掉**它的取值,被吃掉的取值不是位置参数。
167
+ // ⚠️ 此前这里用 `argv.filter(a => !a.startsWith('-'))` 找位置参数 —— 于是
168
+ // `login --profile staging` 把取值 `staging` 当成多余的位置参数报错(合法的
169
+ // 调用被判成非法),而 `--profile a --profile b` 报的是「未知参数:a、b」
170
+ // 而不是真正的原因(重复给)。两处都是同一个 bug:不认识值位。
171
+ let profileFlag;
172
+ let seenProfile = false;
173
+ const positional = [];
174
+ for (let i = 0; i < argv.length; i++) {
175
+ const a = argv[i];
176
+ if (a === '--pretty')
177
+ continue; // 唯一的非 help 全局 flag,不取值
178
+ if (a === '--profile') {
179
+ if (seenProfile)
180
+ return usageFail('用法:--profile 只能出现一次');
181
+ seenProfile = true;
182
+ const v = argv[i + 1];
183
+ if (v === undefined || v.startsWith('--'))
184
+ return usageFail('用法:--profile 后面缺少取值');
185
+ profileFlag = v;
186
+ i++; // 吃掉取值
187
+ continue;
188
+ }
189
+ if (!a.startsWith('-'))
190
+ positional.push(a);
191
+ }
192
+ if (positional.length > 0) {
193
+ return usageFail(`未知参数:${describeArgs(positional)}。auth login 不接受位置参数`);
194
+ }
195
+ // G1:--pretty 已实现 —— 原拒绝点。
196
+ if (argv.includes('--pretty'))
197
+ setPretty(true);
198
+ let profile;
199
+ try {
200
+ profile = normalizeProfile(profileFlag);
201
+ }
202
+ catch (e) {
203
+ return usageFail(e.message);
204
+ }
205
+ // ⚠️ 空串同样视为缺失(`export QIYU_APP_KEY=` 是 shell 里变量未设的典型形态,
206
+ // 与 credentials-source.ts 的口径一致 —— 两层对"空"的判定不能分叉)。
207
+ const envKey = process.env.QIYU_APP_KEY;
208
+ const envSecret = process.env.QIYU_APP_SECRET;
209
+ const appKey = envKey !== undefined && envKey !== '' ? envKey : undefined;
210
+ const appSecret = envSecret !== undefined && envSecret !== '' ? envSecret : undefined;
211
+ // ⚠️ 缺任一即 usage(退出码 2):这是"调用方式"问题(shell 里少 export 一个),
212
+ // 与"凭证无效"(业务错误)不同 —— 后者要发请求才知道,login 不发请求。
213
+ // ⚠️ 必须点名叫用户 export 什么,否则它只知道"少东西"。
214
+ const missing = [];
215
+ if (!appKey)
216
+ missing.push('QIYU_APP_KEY');
217
+ if (!appSecret)
218
+ missing.push('QIYU_APP_SECRET');
219
+ if (missing.length > 0 || appKey === undefined || appSecret === undefined) {
220
+ // `missing.length > 0` 与后两个判据等价,但**必须都写**:前者给人看的清单,
221
+ // 后者给类型收窄(TS 推不出 `missing.length === 0 ⇒ appKey 已定义`)。
222
+ return usageFail(`auth login 需要从环境变量读取凭证,缺少:${missing.join('、')}`, `先在 shell 里设置并导出:export ${missing.join('=… ')}` + '=…,然后重新运行 auth login');
223
+ }
224
+ const configPath = configPathFor();
225
+ let file;
226
+ try {
227
+ file = loadConfigFile(configPath).file;
228
+ }
229
+ catch (e) {
230
+ // 读不出来(畸形 JSON / 未知键 / 权限拒绝)——不能"无视坏文件直接覆盖":
231
+ // 那会静默丢掉用户手写的其它配置。如实报错,让人先修。
232
+ return usageFail(`无法读取现有配置文件:${e.message}`);
233
+ }
234
+ // ⚠️ 与全局优先级一致(spec §3.2:命令行 > 环境变量 > 配置文件 > 默认)——
235
+ // 此前写成 defaultProfile 优先于 QIYU_PROFILE,同一台机器上 export 过
236
+ // QIYU_PROFILE 的用户会发现自己写进了别的 profile。
237
+ const name = profile
238
+ ?? (process.env.QIYU_PROFILE !== undefined && process.env.QIYU_PROFILE !== '' ? process.env.QIYU_PROFILE : undefined)
239
+ ?? file.defaultProfile ?? 'default';
240
+ const existing = file.profiles[name] ?? {};
241
+ const next = {
242
+ ...(file.defaultProfile !== undefined ? { defaultProfile: file.defaultProfile } : {}),
243
+ profiles: {
244
+ ...file.profiles,
245
+ // 合并保留该 profile 下的其它键(store/robots)——覆盖式写入会把
246
+ // 用户手工配的 knowledgeRobotIds 一起抹掉。
247
+ [name]: { ...existing, credentials: { appKey, appSecret } },
248
+ },
249
+ };
250
+ try {
251
+ writeConfigFile(configPath, next);
252
+ }
253
+ catch (e) {
254
+ // 写盘失败是环境问题(权限/符号链接/磁盘)——归业务错误(退出码 1),
255
+ // 不是"改参数重来"。文案带上底层原因,否则用户只知道"失败了"。
256
+ const msg = e.message;
257
+ // 符号链接是我们的显式拒绝 —— 也归这里(用户的动作是"换成普通文件")。
258
+ return fail({
259
+ code: 'config_insecure', kind: 'config_insecure', retryable: false,
260
+ message: `无法写入配置文件 ${configPath}:${msg}`,
261
+ hint: '请检查路径权限(父目录可写、非符号链接),或换到 HOME 下可写的位置',
262
+ });
263
+ }
264
+ // 权限自检:写出的文件必须 0600,否则这次"成功"是假的(凭证已落盘且可被他人读)。
265
+ // writeConfigFile 用 0600 创建,这里只做一次如实复核 —— 失败则如实报告。
266
+ try {
267
+ const perm = checkPermissions(configPath, { hasCredentials: true, onWarn: () => { } });
268
+ if (!perm.ok) {
269
+ return fail({
270
+ code: 'config_insecure', kind: 'config_insecure', retryable: false,
271
+ message: `凭证已写入 ${configPath},但落盘权限不合格(${perm.reason === 'file' ? '文件' : '目录'}过宽)`,
272
+ hint: `请执行 chmod ${perm.reason === 'file' ? '600 ' + configPath : '700 ' + configPath.split('/').slice(0, -1).join('/')}`,
273
+ });
274
+ }
275
+ }
276
+ catch { /* 自检失败不影响"已写入"这一事实;下一次任何命令都会再查一次 */ }
277
+ // ⚠️ 绝不回显 appKey/appSecret —— 连末四位都不(与 whoami 同一条约束)。
278
+ return ok({ configured: true, profile: name, config_path: configPath, source: 'file' });
279
+ }
280
+ function whoami() {
281
+ const configPath = configPathFor();
282
+ let file;
283
+ let configError;
284
+ try {
285
+ // ⚠️ `loadConfigChecked`:含凭证且权限过宽 → 抛带 kind 的错误(不降级成 auth_missing)。
286
+ // 这类是**环境/安全问题**,与"凭证没配"是两件事,必须如实分流。
287
+ file = loadConfigChecked(configPath).file;
288
+ }
289
+ catch (e) {
290
+ const tagged = e;
291
+ if (tagged.kind)
292
+ return failFromTagged(e);
293
+ // 配置畸形(非法 JSON / 未知键)**不等于"凭证没配"** —— 但它是配置问题,
294
+ // 继续往下走(会让下方按"未检测到完整凭证"报),并把这句原因拼进 message。
295
+ configError = e.message;
296
+ }
297
+ const envKey = process.env.QIYU_APP_KEY;
298
+ const envSecret = process.env.QIYU_APP_SECRET;
299
+ const envProfile = process.env.QIYU_PROFILE;
300
+ const profileName = envProfile ?? file?.defaultProfile ?? 'default';
301
+ const profBlock = file?.profiles[profileName];
302
+ const fileKey = profBlock?.credentials?.appKey;
303
+ const fileSecret = profBlock?.credentials?.appSecret;
304
+ const fromEnvKey = envKey !== undefined && envKey !== '';
305
+ const fromEnvSecret = envSecret !== undefined && envSecret !== '';
306
+ const fromFileKey = fileKey !== undefined && fileKey !== '';
307
+ const fromFileSecret = fileSecret !== undefined && fileSecret !== '';
308
+ const configured = (fromEnvKey || fromFileKey) && (fromEnvSecret || fromFileSecret);
309
+ if (!configured) {
310
+ const detail = configError !== undefined
311
+ ? `(另外:配置文件读取失败 —— ${configError})`
312
+ : '';
313
+ return fail({
314
+ code: 'auth_missing', kind: 'auth_missing', retryable: false,
315
+ message: `未检测到完整凭证。appKey 来自 ${fromEnvKey ? '环境变量' : fromFileKey ? '配置文件' : '(缺失)'},` +
316
+ `appSecret 来自 ${fromEnvSecret ? '环境变量' : fromFileSecret ? '配置文件' : '(缺失)'}${detail}`,
317
+ hint: '运行 `qiyu auth login`(从环境变量 QIYU_APP_KEY/QIYU_APP_SECRET 写入配置),' +
318
+ '或直接设置这两个环境变量',
319
+ });
320
+ }
321
+ // ⚠️ `source` 必须**如实**是三态(G1 起有意义):env 给一个、文件给另一个是
322
+ // 合法组合(用户 export 了 appKey、appSecret 留在配置里)。只报单一来源是谎报,
323
+ // 而 Agent 会据此判断"我 export 的那个到底生效了没有"。
324
+ // ⚠️ 判据是**逐字段的实际取值来源**(env 优先),不是"文件是否完整" ——
325
+ // 后者在「文件两个字段齐全 + env 只给 appKey」时错报 'file',而 appKey 其实
326
+ // 用的是 env 那个(实测踩到:这正是 mixed 最典型的形态)。
327
+ const srcKey = fromEnvKey ? 'env' : 'file';
328
+ const srcSecret = fromEnvSecret ? 'env' : 'file';
329
+ const source = srcKey === srcSecret ? srcKey : 'mixed';
330
+ // ⚠️ robots 不是死字段:`sync run` 的 knowledge.categories 在
331
+ // store.options.knowledgeRobotIds 缺席时回退用它(见 sync-run.ts)。
332
+ // 这里如实输出映射,**不声明**它已被校验过 —— 配置里的 robotId 可能无效或
333
+ // 不属于本租户,CLI 不做这个校验(那需要发请求)。
334
+ const robots = Object.entries(profBlock?.robots ?? {})
335
+ .map(([id, name2]) => ({ id: Number(id), name: name2 }));
336
+ return ok({
337
+ configured: true,
338
+ source,
339
+ profile: profileName,
340
+ robots,
341
+ }, {
342
+ field_notes: {
343
+ source: 'env = 两个字段都来自环境变量;file = 都来自配置文件;mixed = 各来自一处(合法组合)',
344
+ robots: '来自配置文件的 profiles.<name>.robots 映射(robotId → 显示名),**未校验有效性**、' +
345
+ '未与本地库比对;sync run 在 store.options.knowledgeRobotIds 缺席时回退使用它',
346
+ configured: 'true 只表示"两个字段都有值",**不代表**它们有效 —— 拼错的 appKey 同样返回 true',
347
+ },
348
+ });
349
+ }
@@ -0,0 +1,70 @@
1
+ // src/commands/credentials-source.ts
2
+ //
3
+ // 凭证来源合流(G1 第三批):环境变量 > 配置文件(`auth login` 写入的那份)。
4
+ // api / sync / sync-run 三处调用点共用 —— 此前各自手写
5
+ // `resolveCredentials({}, { appKey: process.env.QIYU_APP_KEY, … })`,G1 起配置文件
6
+ // 成为第二来源,三处若各写一遍「缺哪项才读文件」,任何一处漏改就会出现
7
+ // 「api 认配置、sync 只认环境变量」的分叉,而 Agent 无法从报错里看出这种差异。
8
+ //
9
+ // ⚠️ **缺哪一项才读配置文件**(不是无条件读):两个都齐时读文件只会多一个
10
+ // 失败通道(权限拒绝/畸形 JSON 会挡下一次本来完全正常的调用),而它提供的
11
+ // 值一个也用不上。「env 完整时不读文件」是钉死在测试里的契约。
12
+ // ⚠️ 权限拒绝(`config_insecure`)**必须**原样透出 —— 那是一个安全问题,
13
+ // 不能因为 env 恰好齐备就替用户瞒下它。读文件的前提(env 缺项)意味着
14
+ // 这条只会在「真的要用的文件」上触发。
15
+ import { resolveCredentials } from '../core/credentials.js';
16
+ import { fileCredentials } from '../core/config.js';
17
+ /**
18
+ * 当前进程的凭证环境变量(架构审查 M-3 的同款收口:调用方应传
19
+ * `currentCredentialEnv()`,需要注入的测试自己传对象 —— 缺省 env 是静默忽略,
20
+ * 加第 3 个变量时漏改任何一处,那条命令就会静默丢一个凭证来源)。
21
+ */
22
+ export function currentCredentialEnv() {
23
+ return { appKey: process.env.QIYU_APP_KEY, appSecret: process.env.QIYU_APP_SECRET };
24
+ }
25
+ /** env 里该字段是否有**非空**值(空串视为未设置 —— shell 里变量未设的典型形态)。 */
26
+ const has = (v) => v !== undefined && v !== '';
27
+ export function resolveCredentialsUsingFile(env = currentCredentialEnv(), opts = {}) {
28
+ const envKey = has(env.appKey);
29
+ const envSecret = has(env.appSecret);
30
+ let fromFile;
31
+ let configWarn;
32
+ if (!envKey || !envSecret) {
33
+ const r = fileCredentials(opts.configPath);
34
+ if (r.fatal !== undefined) {
35
+ // 权限拒绝带 kind(config_insecure):如实透出 —— 退出码 1、hint 点名 chmod。
36
+ const t = r.fatal;
37
+ return {
38
+ ok: false,
39
+ error: {
40
+ code: t.code ?? 'config_insecure', kind: t.kind ?? 'config_insecure',
41
+ retryable: t.retryable ?? false, message: t.message, ...(t.hint !== undefined ? { hint: t.hint } : {}),
42
+ },
43
+ };
44
+ }
45
+ fromFile = r.creds;
46
+ configWarn = r.warn;
47
+ }
48
+ try {
49
+ // 空串视为未设置传给 resolveCredentials:`??` 链会把 '' 当有效值放行,
50
+ // 随后 `if (!appKey)` 又按缺失报错 —— 两层对"空"的判定不一致,先归一。
51
+ const creds = resolveCredentials({}, {
52
+ appKey: has(env.appKey) ? env.appKey : undefined,
53
+ appSecret: has(env.appSecret) ? env.appSecret : undefined,
54
+ }, fromFile);
55
+ return { ok: true, creds };
56
+ }
57
+ catch (e) {
58
+ // ⚠️ 缺凭证是**环境配置**问题(退出码 1),不是参数写错 —— 否则 Agent 会去改
59
+ // 命令行参数,而正确动作是配凭证。与 `auth whoami` 同一 kind,两处必须一致。
60
+ const detail = configWarn !== undefined ? `(另外:配置文件读取失败 —— ${configWarn})` : '';
61
+ return {
62
+ ok: false,
63
+ error: {
64
+ code: 'auth_missing', kind: 'auth_missing', retryable: false,
65
+ message: `${e instanceof Error ? e.message : String(e)}${detail}`,
66
+ hint: '运行 `qiyu auth login`(从环境变量 QIYU_APP_KEY/QIYU_APP_SECRET 写入配置文件),或直接设置这两个环境变量',
67
+ },
68
+ };
69
+ }
70
+ }