qiyu-cli 0.0.0-stage → 0.2.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 (230) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +464 -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 +863 -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 +18 -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 +336 -0
  201. package/dist/skill/install.js +1202 -0
  202. package/dist/skill/paths.js +343 -0
  203. package/dist/skill/qiyu/SKILL.md +86 -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,27 @@
1
+ // src/commands/tree.ts —— 全 CLI 的 `CommandSpec` 汇总(F 组 D4)。
2
+ //
3
+ // 为什么单独一个文件、而不是放在 `cli.ts`(计划原文的位置):`COMMAND_TREE` 的消费者是
4
+ // `src/skill/check.ts`,而 `skill/` 是与 `commands/` 平级的**叶子层**。让叶子层 import
5
+ // `cli.ts` 会把它反向拉进整个 CLI 入口(含 `run()`、USAGE 与 7 个命令模块的全部依赖),
6
+ // 层级倒置;本文件只 import 各命令模块并汇总,`cli.ts` 需要时从它取。
7
+ //
8
+ // 排序不是契约(`path` 自描述),消费者自行按需索引。但**不得**在这里合并/改写任何
9
+ // spec:它是各模块声明的并集,唯一性由 `tests/commands/command-tree.test.ts` 钉住
10
+ // (19 条叶命令 + tree 不变量)。
11
+ //
12
+ // skill 三条(`skill install/check/where`)的 spec 在 `skill-specs.ts` 这个**叶子模块**里,
13
+ // 而不是 `commands/skill.ts`:G3 审查 C1。本文件 import 各命令模块,若再 import
14
+ // `commands/skill.ts` 就是循环(skill.ts → tree.ts → skill.ts)。skill 的 flag 集与它的
15
+ // 解析器同源于 `skill-specs.ts`,`skill.ts` 与本文件各自从那里取一份。
16
+ import { AUTH_SPECS } from './auth.js';
17
+ import { API_SPECS } from './api.js';
18
+ import { STORE_SPECS } from './store.js';
19
+ import { SYNC_SPECS } from './sync.js';
20
+ import { DB_SPECS } from './db.js';
21
+ import { QUERY_SPECS } from './query.js';
22
+ import { STATS_SPECS } from './stats.js';
23
+ import { SKILL_SPECS } from './skill-specs.js';
24
+ export const COMMAND_TREE = [
25
+ ...AUTH_SPECS, ...API_SPECS, ...STORE_SPECS, ...SYNC_SPECS, ...DB_SPECS, ...QUERY_SPECS, ...STATS_SPECS,
26
+ ...SKILL_SPECS,
27
+ ];
@@ -0,0 +1,259 @@
1
+ // src/core/config.ts
2
+ //
3
+ // 配置文件的**通用层**(G1 第三批抽取):路径解析、读文件、JSON 解析、
4
+ // 键白名单校验、credentials/robots 块校验、权限检查、原子写。
5
+ // 只 import node:fs/os/path —— 这是「commands/auth.ts 与 commands/api.ts
6
+ // 不得加载 store/」这条分层红线(layering.test.ts 钉着)的解法:
7
+ // auth/api 只 import 本文件,`store/config.ts` 内部也走这里。
8
+ //
9
+ // ⚠️ 与 `store/config.ts` 的分工:本文件不知道任何 **store 专属**字段
10
+ // (backend/path/readOnlyRetryMs/batchSize/options 的语义校验仍在 store 侧),
11
+ // 只提供「配置文件作为载体」的全部通用能力。错误文案与 C1 逐字兼容 ——
12
+ // 现有 25 条 config.test.ts 一条不改地全绿是本次抽取的验收线。
13
+ import { readFileSync, writeFileSync, lstatSync, statSync, existsSync, mkdirSync, renameSync, chmodSync } from 'node:fs';
14
+ import { homedir } from 'node:os';
15
+ import { join, dirname } from 'node:path';
16
+ /** 顶层已知键 —— 未知键 fail-closed(spec §3.3)。 */
17
+ export const KNOWN_TOP = new Set(['defaultProfile', 'profiles']);
18
+ /** profile 内已知键:store(C1)+ credentials/robots(G1 起,`auth login` 写入)。 */
19
+ export const KNOWN_PROFILE = new Set(['store', 'credentials', 'robots']);
20
+ /** 配置文件的默认路径(`~/.config/qiyu/config.json`)。 */
21
+ export function configPathFor(home = homedir()) {
22
+ return join(home, '.config', 'qiyu', 'config.json');
23
+ }
24
+ /** 读出配置文件原文并解析为普通对象;文件不存在返回 `{}`。校验由 `parseConfig` 做。 */
25
+ export function readConfigRaw(configPath) {
26
+ if (!existsSync(configPath))
27
+ return {};
28
+ let raw;
29
+ try {
30
+ raw = readFileSync(configPath, 'utf8');
31
+ }
32
+ catch (e) {
33
+ throw new Error(`无法读取配置文件 ${configPath}:${e instanceof Error ? e.message : String(e)}`);
34
+ }
35
+ try {
36
+ return JSON.parse(raw);
37
+ }
38
+ catch (e) {
39
+ throw new Error(`配置文件 ${configPath} 不是合法 JSON:${e instanceof Error ? e.message : String(e)}`);
40
+ }
41
+ }
42
+ function assertObject(v, label) {
43
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) {
44
+ throw new Error(`配置文件 ${label} 必须是对象`);
45
+ }
46
+ return v;
47
+ }
48
+ /**
49
+ * 结构校验:顶层/profile/credentials/robots 的形态与类型。
50
+ * ⚠️ **不**校验 store 块的内容(backend 枚举、正整数上界等)—— 那是
51
+ * `store/config.ts` 的领域知识,本文件只保证「它是一个对象、键已知」。
52
+ */
53
+ export function parseConfig(raw) {
54
+ for (const k of Object.keys(raw)) {
55
+ if (!KNOWN_TOP.has(k))
56
+ throw new Error(`配置文件未知键:${k}`);
57
+ }
58
+ const profiles = {};
59
+ if (raw.profiles !== undefined) {
60
+ const profObj = assertObject(raw.profiles, 'profiles');
61
+ for (const [name, prof] of Object.entries(profObj)) {
62
+ const p = assertObject(prof, `profiles.${name}`);
63
+ for (const k of Object.keys(p)) {
64
+ if (!KNOWN_PROFILE.has(k))
65
+ throw new Error(`配置文件未知键:profiles.${name}.${k}`);
66
+ }
67
+ const block = {};
68
+ if (p.store !== undefined)
69
+ block.store = assertObject(p.store, `profiles.${name}.store`);
70
+ if (p.credentials !== undefined) {
71
+ const c = assertObject(p.credentials, `profiles.${name}.credentials`);
72
+ if (typeof c.appKey !== 'string' || !c.appKey) {
73
+ throw new Error(`配置文件 profiles.${name}.credentials.appKey 必须是非空字符串`);
74
+ }
75
+ if (typeof c.appSecret !== 'string' || !c.appSecret) {
76
+ throw new Error(`配置文件 profiles.${name}.credentials.appSecret 必须是非空字符串`);
77
+ }
78
+ block.credentials = { appKey: c.appKey, appSecret: c.appSecret };
79
+ }
80
+ if (p.robots !== undefined) {
81
+ const r = assertObject(p.robots, `profiles.${name}.robots`);
82
+ for (const [rid, rname] of Object.entries(r)) {
83
+ if (!/^\d+$/.test(rid)) {
84
+ throw new Error(`配置文件 profiles.${name}.robots 的键必须是数字 id,实际是 ${JSON.stringify(rid)}`);
85
+ }
86
+ if (typeof rname !== 'string' || rname.trim() === '') {
87
+ throw new Error(`配置文件 profiles.${name}.robots.${rid} 必须是非空字符串`);
88
+ }
89
+ }
90
+ block.robots = r;
91
+ }
92
+ profiles[name] = block;
93
+ }
94
+ }
95
+ let defaultProfile;
96
+ if (raw.defaultProfile !== undefined) {
97
+ if (typeof raw.defaultProfile !== 'string')
98
+ throw new Error('配置文件 defaultProfile 必须是字符串');
99
+ defaultProfile = raw.defaultProfile;
100
+ }
101
+ return { defaultProfile, profiles };
102
+ }
103
+ /** 读 + 解析一步完成(文件不存在返回空结构)。**不含权限裁决**(见 `loadConfigChecked`)。 */
104
+ export function loadConfigFile(configPath) {
105
+ const exists = existsSync(configPath);
106
+ const raw = readConfigRaw(configPath);
107
+ return { file: parseConfig(raw), exists };
108
+ }
109
+ /**
110
+ * 读 + 解析 + **权限裁决**(含凭证且过宽 → 抛带 kind 的错误)。
111
+ *
112
+ * ⚠️ 这是所有「按配置取凭证」的入口(auth/api/sync/store)应走的函数 ——
113
+ * 权限裁决必须与读取同源,否则会出现「某条命令查了、另一条没查」的不一致,
114
+ * 而那正是「同一个危险状态,两种行为」。无凭证的文件维持警告(C1 既有口径)。
115
+ *
116
+ * 抛出的错误带 `code/kind: 'config_insecure'`(退出码 1,重试无用)——
117
+ * 调用方用 `failFromTagged` 原样转成信封;**不要**用 usageFail 包它
118
+ * (那是"改参数重来"的语义,而这件事只能由人去 chmod)。
119
+ */
120
+ export function loadConfigChecked(configPath) {
121
+ const loaded = loadConfigFile(configPath);
122
+ if (!loaded.exists)
123
+ return loaded;
124
+ const perm = checkPermissions(configPath, {
125
+ hasCredentials: configHasCredentials(loaded.file),
126
+ onWarn: (m) => process.stderr.write(`${m}\n`),
127
+ });
128
+ if (!perm.ok) {
129
+ const dir = dirname(configPath);
130
+ const what = perm.reason === 'file' ? `配置文件 ${configPath}` : `配置目录 ${dir}`;
131
+ const fix = perm.reason === 'file' ? `chmod 600 ${configPath}` : `chmod 700 ${dir}`;
132
+ throw Object.assign(new Error(`${what} 含凭证但权限过宽(group/other 可访问,其他用户可读到 appSecret),已拒绝读取`), {
133
+ code: 'config_insecure', kind: 'config_insecure', retryable: false,
134
+ hint: `这是配置文件的权限问题,重试无用 —— 请执行:${fix}`,
135
+ });
136
+ }
137
+ return loaded;
138
+ }
139
+ /**
140
+ * 本进程内已发出过警告的路径 —— **警告去重**。
141
+ *
142
+ * ⚠️ 为什么需要(G1 实测):`sync run` 一次执行读**两遍**配置 —— 凭证合流
143
+ * (`credentials-source.ts`)与 `resolveStoreConfig` 各调一次权限检查。文件不含凭证
144
+ * 但权限过宽时,同一条「权限过宽(建议 chmod 600)」会在 stderr 出现**两次**,
145
+ * 用户会以为有两个不同的问题。拒绝路径不受影响(第一次就直接抛了)。
146
+ * 按「检查项 + 路径」记键,同进程只说一次;跨进程(下一次命令调用)仍会提醒 ——
147
+ * 警告的职责是"这次运行的环境有问题",不是"这台机器上只许提一次"。
148
+ */
149
+ const warnedPermissionPaths = new Set();
150
+ /** 测试用:清空警告去重表(同 `__resetBuckets` 的先例 —— 模块级状态必须可重置)。 */
151
+ export function __resetPermissionWarnings() { warnedPermissionPaths.clear(); }
152
+ /**
153
+ * 权限检查(spec §3.4)。G1 起**含凭证即拒绝**(不再只是警告):
154
+ * 文件 0644 落盘的 appSecret 对同机其他用户可读 —— 「警告不阻断」是
155
+ * C1 无凭证时代的口径,写入凭证后继续沿用等于每次调用都打印一句
156
+ * 没人执行的提示。
157
+ *
158
+ * ⚠️ 拒绝判据 = 文件 group/other 有**任何**位 && 至少一个 profile 含 credentials。
159
+ * 无 credentials 的文件维持警告(既有行为,C1 测试钉着)。
160
+ * ⚠️ `auth login` 的写入路径(`writeConfigFile`)总是产出 0600 文件 —— 所以
161
+ * 「含凭证且过宽」只会在用户手工 chmod 放宽时出现,此时拒绝并提示收紧。
162
+ */
163
+ export function checkPermissions(configPath, opts) {
164
+ if (process.platform === 'win32')
165
+ return { ok: true };
166
+ const mode = statSync(configPath).mode & 0o777;
167
+ const fileWide = (mode & 0o077) !== 0;
168
+ if (fileWide) {
169
+ if (opts.hasCredentials)
170
+ return { ok: false, reason: 'file' };
171
+ const key = `file:${configPath}`;
172
+ if (!warnedPermissionPaths.has(key)) {
173
+ warnedPermissionPaths.add(key);
174
+ opts.onWarn(`配置文件 ${configPath} 权限过宽(建议 chmod 600)`);
175
+ }
176
+ }
177
+ // 父目录:只查 group/other **写位**(0o755 是常规 umask 产物,不警告);
178
+ // 目录可整体替换文件 → 含凭证时同样拒绝。
179
+ const dirMode = statSync(dirname(configPath)).mode & 0o777;
180
+ if ((dirMode & 0o022) !== 0) {
181
+ if (opts.hasCredentials)
182
+ return { ok: false, reason: 'dir' };
183
+ const dirKey = `dir:${dirname(configPath)}`;
184
+ if (!warnedPermissionPaths.has(dirKey)) {
185
+ warnedPermissionPaths.add(dirKey);
186
+ opts.onWarn(`配置目录 ${dirname(configPath)} 权限过宽(建议 chmod 700)`);
187
+ }
188
+ }
189
+ return { ok: true };
190
+ }
191
+ /** 配置文件是否含任何 credentials 块(权限升级判据)。 */
192
+ export function configHasCredentials(file) {
193
+ return Object.values(file.profiles).some((p) => p.credentials !== undefined);
194
+ }
195
+ /**
196
+ * 读配置里某个 profile 的块(G1:凭证与 robots 都从这里取)。
197
+ *
198
+ * ⚠️ 走 `loadConfigChecked` —— **权限裁决与读取同源**,否则会出现
199
+ * 「auth 查了、api 没查」的不一致:同一个危险状态两种行为。
200
+ * ⚠️ 畸形配置**不抛**(只记 `warn`):环境变量齐备时 `api call` 仍应能工作 ——
201
+ * 把一个坏掉的配置文件升级成"所有命令都不可用"是过度反应。
202
+ * 但**缺凭证**的最终判定仍由 `resolveCredentials` 做,本函数不越权下结论。
203
+ */
204
+ export function fileProfile(configPath = configPathFor(), envProfile = process.env.QIYU_PROFILE) {
205
+ let file;
206
+ try {
207
+ file = loadConfigChecked(configPath).file;
208
+ }
209
+ catch (e) {
210
+ // ⚠️ 空串当未设置:`export QIYU_PROFILE=`(变量未设的典型形态)不该选中
211
+ // 一个名叫 '' 的 profile —— 与凭证侧「空串视为缺失」同一口径。
212
+ const name = envProfile !== undefined && envProfile !== '' ? envProfile : 'default';
213
+ // 权限拒绝带 kind(`config_insecure`)→ 致命;畸形配置无 kind → 非致命。
214
+ return e.kind !== undefined
215
+ ? { profileName: name, fatal: e }
216
+ : { profileName: name, warn: e.message };
217
+ }
218
+ const profileName = envProfile !== undefined && envProfile !== '' ? envProfile
219
+ : file.defaultProfile !== undefined && file.defaultProfile !== '' ? file.defaultProfile
220
+ : 'default';
221
+ const profile = file.profiles[profileName];
222
+ return profile === undefined ? { profileName } : { profileName, profile };
223
+ }
224
+ /** 配置里某个 profile 的凭证(`fileProfile` 的便捷视图,供 `resolveCredentials` 的第三参)。 */
225
+ export function fileCredentials(configPath, envProfile) {
226
+ const r = fileProfile(configPath, envProfile);
227
+ return r.profile?.credentials === undefined ? r : { ...r, creds: r.profile.credentials };
228
+ }
229
+ /**
230
+ * 原子写配置文件:0700 目录 + 0600 临时文件 + rename 换入。
231
+ *
232
+ * ⚠️ **绝不用 writeFileSync 直写**:写一半崩溃会留下一个被截断的 config.json,
233
+ * 下一次任何命令都起不来。临时文件与目标同目录(rename 跨文件系统才原子)。
234
+ * ⚠️ config 是符号链接时拒绝 —— 写入会穿透到链接目标(可能是任意路径)。
235
+ * ⚠️ 合并语义由调用方先算好完整内容;本函数只负责「安全落盘」。
236
+ */
237
+ export function writeConfigFile(configPath, content) {
238
+ const dir = dirname(configPath);
239
+ // ⚠️ lstat 不跟随链接:statSync 会穿透到目标,探测不到「config 本身是链接」。
240
+ // 文件不存在(首次 login)是正常路径 —— ENOENT 放行,其余 errno 照常抛。
241
+ try {
242
+ if (lstatSync(configPath).isSymbolicLink()) {
243
+ throw new Error(`配置文件 ${configPath} 是符号链接,拒绝写入(写入会穿透到链接目标)`);
244
+ }
245
+ }
246
+ catch (e) {
247
+ if (e.code !== 'ENOENT')
248
+ throw e;
249
+ }
250
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
251
+ const tmp = join(dir, `.config.json.tmp-${process.pid}-${Date.now()}`);
252
+ writeFileSync(tmp, serializeConfig(content), { mode: 0o600 });
253
+ chmodSync(tmp, 0o600); // mkdir 的 umask 不作用于文件,显式 chmod 兜住 0o600
254
+ renameSync(tmp, configPath);
255
+ }
256
+ /** 读出的整份配置序列化回 JSON(保存时的规范形态:缩进 2 + 尾换行)。 */
257
+ export function serializeConfig(content) {
258
+ return JSON.stringify(content, null, 2) + '\n';
259
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * 优先级:命令行参数 > 环境变量 > 配置文件。
3
+ * 两者缺一即报错 —— 只给 appKey 就发请求必然拿 14001,不如在本地就说清楚。
4
+ */
5
+ export function resolveCredentials(fromArgs, env = {}, fromFile) {
6
+ const appKey = fromArgs.appKey ?? env.appKey ?? fromFile?.appKey;
7
+ const appSecret = fromArgs.appSecret ?? env.appSecret ?? fromFile?.appSecret;
8
+ if (!appKey) {
9
+ throw new Error('缺少 appKey。请设置环境变量 QIYU_APP_KEY。');
10
+ }
11
+ if (!appSecret) {
12
+ throw new Error('缺少 appSecret。请设置环境变量 QIYU_APP_SECRET。');
13
+ }
14
+ return { appKey, appSecret };
15
+ }
16
+ /** 转义正则元字符 —— 凭证理论上可能含 `.` `*` 等,直接插进 RegExp 会改变语义。 */
17
+ function escapeRe(s) {
18
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
19
+ }
20
+ /** 把凭证从任意文本中抹掉。所有对外输出(含 stderr 与错误消息)都必须先过这一层。 */
21
+ export function redact(text, creds) {
22
+ let out = text;
23
+ // ⚠️ `split/join` 是无差别子串替换,对**极短**的凭证会把正常文本打烂 ——
24
+ // 实测旧实现 `redact('AppKey not exists', {appKey:'e', appSecret:'s'})` 得到
25
+ // `AppK<已隐藏>y not <已隐藏>xi<已隐藏>t<已隐藏>`,Agent 完全读不懂
26
+ // (2026-10-06 复跑确认:`s` 抹掉 4 个字母、`e` 再抹 1 个,原文只剩骨架)。
27
+ // ⚠️ **注意 `creds` 里有两个凭证才复现得出这行输出** —— 只传 `appKey:'e'`
28
+ // 会得到 `AppK<已隐藏>y not <已隐藏>xists`(少了两处)。注释里的示例必须
29
+ // 把它写成完整形态,否则照抄的人会以为"我跑得不对"。
30
+ //
31
+ // 但**绝不能**因为"太短"就跳过脱敏 —— 泄漏凭证比文本难读严重得多。
32
+ // 折中:短凭证仍然替换,但**只在它作为独立 token 出现时**(用词边界)。
33
+ // 七鱼真实凭证是 32 字符的十六进制串,走的是上面的无差别替换分支,
34
+ // 所以这条边界规则只影响测试夹具与将来可能的短凭证。
35
+ const MIN = 8;
36
+ const scrub = (s, secret) => secret.length >= MIN
37
+ ? s.split(secret).join('<已隐藏>')
38
+ : s.replace(new RegExp(`(?<![\\w])${escapeRe(secret)}(?![\\w])`, 'g'), '<已隐藏>');
39
+ if (creds.appSecret)
40
+ out = scrub(out, creds.appSecret);
41
+ if (creds.appKey)
42
+ out = scrub(out, creds.appKey);
43
+ // ⚠️ **appKey 还要抹掉它的 URL 编码形式。** 这条是必需的,不是冗余:
44
+ // `signedQuery` 对 appKey 做了 `encodeURIComponent`(见 sign.ts),所以 message 里
45
+ // 若出现 URL,串上是编码形式 `?appKey=a%2Bb&…` —— 而上面的 `scrub(out, creds.appKey)`
46
+ // 用**原始** appKey(`a+b`)做 `split/join`,在这串里**匹配不到任何东西**。
47
+ // 于是含 URL 保留字符(`+ / = &` 等)的 appKey 会原样留在错误 message 里。
48
+ // ⚠️ 计划自己的 sign.test.ts 就断言了「含保留字符的 appKey 是可能的」
49
+ // (`signedQuery('a+b/c=d&e', …)` 产出 `appKey=a%2Bb%2Fc%3Dd%26e`)——
50
+ // 所以这不是假想输入,只是两层(签名 vs 脱敏)对同一个值用了不同表示。
51
+ // 真实凭证是 32 位十六进制(不含保留字符),线上不触发;但形态一变就是无声泄漏。
52
+ if (creds.appKey) {
53
+ const encoded = encodeURIComponent(creds.appKey);
54
+ if (encoded !== creds.appKey)
55
+ out = scrub(out, encoded);
56
+ }
57
+ // ⚠️ `checksum` 也必须抹掉 —— 复核重点 8 自己点明了「URL 查询串就是
58
+ // appKey/checksum」,但只抹 appKey 是不够的。checksum = SHA1(appSecret + md5(body) + time),
59
+ // 它虽然不可逆,却是**一个 5 分钟内有效的可重放凭证**:拿到 `checksum` + 同一个 `time`
60
+ // + 同一个 body,任何人都能原样重发这个请求。异常 message 一旦带 URL,
61
+ // checksum 就在里面 —— 除非在这里拦掉。
62
+ // 匹配 40 位小写十六进制(SHA1 的十六进制表示)。
63
+ // ⚠️ 只匹配**小写**不是疏忽:本仓库的 `checksum` 与 `md5Hex` 都由
64
+ // `digest('hex')` 产生,恒为小写(设计稿 **§4.1 签名** 明写"小写十六进制" ——
65
+ // ⚠️ 此前这里误标为 §2;§2 是「范围」,不含此句)。把正则放宽到
66
+ // `[0-9a-fA-F]` 只会增加**误伤**风险 —— 任何 40 位的业务文本(如某接口返回的
67
+ // 哈希型字段)会被无差别抹掉。若将来真有大小写混用的凭证进入 message,
68
+ // 应在此显式处理,而不是靠一条更宽的正则顺带覆盖。
69
+ out = out.replace(/\b[0-9a-f]{40}\b/g, '<已隐藏>');
70
+ return out;
71
+ }
@@ -0,0 +1,18 @@
1
+ // src/core/edition.ts —— 版本常量唯一定义点。
2
+ //
3
+ // 为什么放 `core/` 而不是 `skill/`:`qiyu --version`(Task 12,cli.ts)与 skill 安装
4
+ // (Task 9/11/13)都要消费,而 `commands/` 不得反向 import `skill/`(分层红线),
5
+ // `cli.ts` 同理。skill 正文发生**结构性**改变(增删协议段落形态)时递增
6
+ // `SKILL_CONTRACT_VERSION`;命令/flag 变化但 skill 正文未受影响则不动(spec D6)。
7
+ //
8
+ // `PACKAGE_VERSION` 是构建期占位:发布包**顶层**有 package.json(npm 永远带上它),
9
+ // 但 `files: ["dist"]` 下 `dist/` 内部没有——运行时代码在 `dist/core/`,相对路径
10
+ // `../package.json` 解析不到包元数据;跨层猜路径(`../../package.json`)又依赖
11
+ // 构建层级,发布前后两种形态会分叉。所以版本在构建期注入:
12
+ // `scripts/copy-assets.mjs`(Task 13)在 tsc 之后把 dist/core/edition.js 里的
13
+ // '0.0.0-dev' 字面量正则替换为 package.json 的 version。源码里永远保持占位值,
14
+ // 靠测试钉住「构建产物非占位」这一契约。
15
+ /** skill 正文契约版本:结构性改变才递增(spec D6)。 */
16
+ export const SKILL_CONTRACT_VERSION = 1;
17
+ /** 包版本占位值;构建期被 copy-assets.mjs 替换为 package.json 的 version。 */
18
+ export const PACKAGE_VERSION = '0.2.0';
@@ -0,0 +1,201 @@
1
+ // src/core/envelope.ts
2
+ function tryParseJson(s) {
3
+ try {
4
+ return { parsed: true, value: JSON.parse(s) };
5
+ }
6
+ catch {
7
+ return { parsed: false, value: undefined };
8
+ }
9
+ }
10
+ /**
11
+ * 修复设计稿 §10.2 记录的畸形 JSON:**整数键没有引号**。
12
+ * 服务端返回的 `follower` / `customField` 形如 `{5000004:"张三",5000001:"李四"}`,
13
+ * `JSON.parse` 与 Python 的 `json.loads` **都会失败**。
14
+ *
15
+ * ⚠️ 这是**真实数据的缺陷,不是假想**:实测 `session.user.profile` 的 message
16
+ * 有 **28/59(47%)** 解析失败,且 28/28 都是这一个原因;`ticket.new.detail`
17
+ * 在较早的工单上有 **18%** 失败(近期的为 0%)。设计稿的结论是
18
+ * 「容错是回补路径特有的正确性要求」,而这个正则**修复了 100% 的失败样本**。
19
+ *
20
+ * ⚠️ 已知局限:正则不区分"结构位置的整数键"与"字符串值里的 `,123:`"。
21
+ * 但**它只在严格解析已经失败之后才运行** —— 合法的 JSON(哪怕字符串值里
22
+ * 恰好含 `,1:`)走的是严格路径,根本到不了这里。
23
+ */
24
+ function repairUnquotedIntKeys(s) {
25
+ return s.replace(/(\{|,)(\d+):/g, '$1"$2":');
26
+ }
27
+ /**
28
+ * 「成功但为空」。设计稿 §9.0 列出三种编码:`data` 键**缺失**、`data = {}`、`data = []`。
29
+ * 第一种(`data` 键缺失)由调用点的末尾分支处理,`{}` / `[]` 两种走这里。
30
+ */
31
+ function isEmptyPayload(v) {
32
+ if (v === null || v === undefined)
33
+ return true;
34
+ if (Array.isArray(v))
35
+ return v.length === 0;
36
+ if (typeof v === 'object')
37
+ return Object.keys(v).length === 0;
38
+ return false;
39
+ }
40
+ /**
41
+ * 把七鱼的各种响应形态归一到统一结构。
42
+ *
43
+ * ⚠️ 判据不是 key 集合,而是「该接口在注册表里登记的形状」+「message 能否解析为 JSON」。
44
+ * 仅 {code,message} 一种形状就分裂成五种(JSON 对象/数组/数字/纯文本/键不存在),
45
+ * 只按键集合分支的解析器会错四种。
46
+ *
47
+ * ⚠️ 最要命的一条:**形状 C 的端点,每一个错误也都返回 code:200**,配一段纯文本的
48
+ * message(`14501 ...`、`14004 Not found param`、`14009 api call too frequent`)。
49
+ * 因此形状 C 上"message 解析不出 JSON"必须判为**失败**,不能当"成功但无数据"——
50
+ * 否则 Agent 会把限流当成"这段时间没有数据",这是设计稿 §9.2 点名的头号静默失败。
51
+ */
52
+ export function normalize(raw, envelope) {
53
+ // 裸数组:ipcc.customfield.template.get 完全没有信封
54
+ if (Array.isArray(raw)) {
55
+ return { ok: true, code: '200', payload: raw, messageText: '', notFound: false };
56
+ }
57
+ if (typeof raw !== 'object' || raw === null) {
58
+ return { ok: false, code: 'unknown', payload: undefined,
59
+ messageText: String(raw), notFound: false };
60
+ }
61
+ const o = raw;
62
+ // Spring Boot 404:/openapi 下的路由不存在时返回这种形态
63
+ if ('status' in o && 'timestamp' in o && !('code' in o)) {
64
+ return {
65
+ ok: false,
66
+ code: String(o.status),
67
+ payload: undefined,
68
+ messageText: String(o.message ?? o.error ?? ''),
69
+ notFound: false,
70
+ };
71
+ }
72
+ const code = String(o.code ?? 'unknown');
73
+ const codeOk = code === '200';
74
+ const messageText = typeof o.message === 'string' ? o.message : '';
75
+ // 形状 C:数据藏在 message 里的 JSON 字符串。
76
+ // 解析成功 → 成功;解析失败 → **错误**(见上方说明),即便 code 是 200。
77
+ if (envelope === 'C') {
78
+ const nf = { notFound: false };
79
+ if (!codeOk)
80
+ return { ok: false, code, payload: undefined, messageText, ...nf };
81
+ if (!messageText)
82
+ return { ok: false, code, payload: undefined, messageText: '响应缺少 message', ...nf };
83
+ const { parsed, value } = tryParseJson(messageText);
84
+ // 形状 C 的载荷就是 message 解析出来的东西,所以 `{}` / `[]` 同样是"成功但为空"
85
+ if (parsed)
86
+ return { ok: true, code, payload: value, messageText,
87
+ notFound: isEmptyPayload(value) };
88
+ // ⚠️ 严格解析失败**不等于**服务端出错 —— `session.user.profile` 有 47% 的
89
+ // **正常**响应带整数键未加引号的畸形 JSON(设计稿 §10.2)。先试着修复再判错,
90
+ // 否则近一半的正常响应会被报成 `ok:false`(且 code 停在 '200',下游落 unknown)。
91
+ const repaired = tryParseJson(repairUnquotedIntKeys(messageText));
92
+ if (repaired.parsed)
93
+ return { ok: true, code, payload: repaired.value, messageText,
94
+ notFound: isEmptyPayload(repaired.value) };
95
+ // ⚠️ 关键:这一族的错误报文里,**顶层的 code 恒为 200,真实错误码写在 message 开头**
96
+ // (`14501 (endTime-startTime)/millsADay > 31 is invalid`、`14004 Not found param`、
97
+ // `14009 api call too frequent`)。若原样返回 200,下游 classify 会一律落到
98
+ // default → unknown,任务 3 建的 14501 双义分派与 14004 分发表就全部失效。
99
+ // 必须把开头的错误码提取出来当作 code。
100
+ const m = /^\s*(\d{4,6})\b/.exec(messageText);
101
+ return { ok: false, code: m ? m[1] : code, payload: undefined, messageText, ...nf };
102
+ }
103
+ // 形状 B:数据在 result
104
+ // ⚠️ 必须和形状 A 一样判空载荷。若这里硬编码 notFound:false,
105
+ // `tag.all` 返回 `{code:200, result:[], total:0}` 时会被当成"成功且有数据" ——
106
+ // 而设计稿 §9.0 明说该接口的 total 恒为 0、不可作数,只能看 result 本身。
107
+ // ⚠️ 与 data 分支同理:只在 envelope 已实测时才敢判 notFound ——
108
+ // 未实测的接口,"空 result 意味着什么"同样无从得知。
109
+ //
110
+ // 与 data 分支不同的是,**今天还没有实测到语义反转的 result 写接口**(形状 B 只有
111
+ // `tag.all` 一个读接口)。这条守卫因此是**防御性**的:它守的不是已发生的 bug,而是
112
+ // 「data 能反转、result 凭什么不能」这个不对称 —— 两个分支都是"载荷为空"的判据,
113
+ // 没有理由一个查注册表、另一个靠猜。写接口在注册表里会越来越多(§5.4.1 已列 5 个),
114
+ // 其中任何一个改用 `result` 承载失败列表,这里就会和 data 一样静默反转。
115
+ // → 宁可现在写死这条规则,也不留给下一个人去重新发现。
116
+ if ('result' in o) {
117
+ return { ok: codeOk, code, payload: o.result, messageText,
118
+ notFound: codeOk && envelope !== null && envelope !== undefined
119
+ && isEmptyPayload(o.result) };
120
+ }
121
+ // 形状 A / D:数据在 data
122
+ //
123
+ // ⚠️ **但"data 为空 ⇒ not_found"这条规则只在 envelope 已实测时成立。**
124
+ // envelope 为 null(未实测)的接口恰恰**全部是写接口**,而写接口的 `data` 语义
125
+ // 与读接口相反 —— 设计稿 §5.4.1 的**文档依据**(这 5 个接口实测中刻意未调用):
126
+ // · `addKnowledge` → `data` 是新 id(integer)
127
+ // · `editKnowledge` / `editKnowledgeNoSimilars` / `editChannelAnswer` → `data` 是 `true`
128
+ // · `deleteKnowledges` → `data` 是**失败**的 id 列表,**空数组 = 全部成功**
129
+ //
130
+ // 最后一个是**不可逆的批量删除**,而"空数组"在这里是**最成功**的结果。
131
+ // 旧实现无条件套用读接口的判据,实测把它报成
132
+ // `not_found: true` + "接口返回成功但无数据" —— Agent 会以为**什么都没删掉**,
133
+ // 而真相是**全部删掉了**。这是 §9.2 静默失败最危险的方向:它把一个已完成的
134
+ // 破坏性操作描述成一次空操作。
135
+ //
136
+ // → 未实测的接口**不判 not_found**:注册表既然不知道这个接口的 `data` 语义,
137
+ // 就不能假装知道。"空 data 是什么"这个问题,只有实测过才能回答。
138
+ if ('data' in o) {
139
+ return { ok: codeOk, code, payload: o.data, messageText,
140
+ notFound: codeOk && envelope !== null && envelope !== undefined
141
+ && isEmptyPayload(o.data) };
142
+ }
143
+ // chat.queue.group.query:数据在 staffInfo,且成功时 message 反而缺失。
144
+ // 空的 staffInfo([])是"无人在线"的合法状态,不是错误。
145
+ if ('staffInfo' in o) {
146
+ // ⚠️ 空的 staffInfo 是"无人在线"的**正常**状态(24 个组里 15 个如此),不是 not_found
147
+ return { ok: codeOk, code, payload: o.staffInfo, messageText, notFound: false };
148
+ }
149
+ // 宽松模式(envelope 为 undefined 或 null —— 该接口的信封未经实测):
150
+ // 按设计稿 §9.0,此时唯一能做的就是试探 message 能否解析。
151
+ // ⚠️ 这与形状 C 的严格语义不同:解析失败**不判错**,因为无从区分
152
+ // "形状 C 的错误报文"与"staff.list 那种 message='OK' 的正常响应"。
153
+ if (messageText) {
154
+ // 同样先严格、失败再修复(见上方 repairUnquotedIntKeys 的说明)
155
+ let { parsed, value } = tryParseJson(messageText);
156
+ if (!parsed)
157
+ ({ parsed, value } = tryParseJson(repairUnquotedIntKeys(messageText)));
158
+ // ⚠️ 这里同样要判空载荷。设计稿 §9.0 点名 `smstask.status` 未知任务 id 返回
159
+ // `{code:200, message:"[]"}` —— 那正是"成功但查无此物"。若因为该接口的
160
+ // envelope 还没实测(填 null)就硬编码 notFound:false,§9.2 的头号静默失败
161
+ // 会在宽松模式下原样复现。
162
+ //
163
+ // ⚠️ **为什么这里不判 envelope、而上面 data/result 两条要判** —— 这不是疏漏:
164
+ // · `message` 是 JSON 载荷的载体时,"载荷为空"就是**查无此物**,
165
+ // 设计稿 §9.0 对 `smstask.status` / `getDetail` 等接口**实测**过这一点。
166
+ // · `data` 为空则有**两种相反**的实测含义:读接口是"查无此物"(`group.members`
167
+ // 传错 groupId),写接口是"全部成功"(`deleteKnowledges` 的失败列表为空)。
168
+ // 在不知道是哪种时断言其一,就是在制造下面那条注释描述的静默失败。
169
+ // → 两者的区别不是"严格 vs 宽松",而是"这个形状有没有出现过语义反转的实测证据"。
170
+ if (parsed)
171
+ return { ok: codeOk, code, payload: value, messageText,
172
+ notFound: codeOk && isEmptyPayload(value) };
173
+ }
174
+ // 其余形状走到这里意味着"200 但无载荷"。
175
+ //
176
+ // ⚠️ **envelope 为 null(未实测)时与 data/result 两个分支取同一条规则:不判 not_found。**
177
+ // 设计稿 §9.0 的规则原文是"`code:200` 且无数据字段的,一律当作 not_found",但它同时
178
+ // 写明这条规则"必须是**注册表查询**而非启发式判断"—— 它假定每个接口都登记了 `envelope`。
179
+ // 在计划交付的 11 条骨架里那 5 个知识库写接口的 `envelope` 正是 `null`,生成脚本产出
180
+ // 154 条时 `null` 只会更多。若这里写 `envelope !== 'D'`,`null !== 'D'` 为真,于是
181
+ // **同一个未实测接口**会因为"载荷挂在 data 上还是完全缺席"得到相反的判定:
182
+ // `{code:200,data:[]}` 走 data 分支判 false,`{code:200}` 走这里判 true。
183
+ // 对未实测的写接口,`{code:200}` 无载荷恰恰可能就是"操作成功",判成 not_found 会把
184
+ // 一次成功的写描述成"什么都没发生"—— 与 data 分支注释里那条最危险的静默失败同构。
185
+ // → 与 data/result 对齐:不知道就不断言。'D' / 'D-nf' 这些**已登记**的取值照旧区分。
186
+ //
187
+ // ⚠️ 形状 D 这一族里**语义相反的两个接口共用同一个报文**,必须分开登记:
188
+ // `robot.transfer.config` → `{code}` 是**正常成功**(它就是返回一个空壳)
189
+ // `robot.session.msgAssociate` → `{code}` 是它的 **not-found 路径**
190
+ // (命中时返回 `{code,data}`,`data{content,questionList,robotId}`)
191
+ // 两者都返回 `{code:200}`、都没有 data,从报文里**根本无从分辨**。
192
+ //
193
+ // 区分它们的,就是这一行末尾那个 `envelope !== 'D'` 子句(前两个 `!= null` 子句管的是
194
+ // 未实测的情形,与 D 族无关):
195
+ // `'D'` 落在 `!== 'D'` 的假分支(不判 not_found),`'D-nf'` 落在真分支(判)。
196
+ // 因此这里**刻意不为 `'D-nf'` 单独开分支** —— 那会是一段不改变任何行为的死代码
197
+ // (变异测试确认:删掉它全量测试仍全绿)。`'D-nf'` 的全部意义就是
198
+ // "形状 D,但空报文表示查无此物",让它可以被登记,而不需要被特判。
199
+ return { ok: codeOk, code, payload: undefined, messageText,
200
+ notFound: codeOk && envelope !== null && envelope !== undefined && envelope !== 'D' };
201
+ }